changeset 16603:189241a7c3a9

maint: periodic merge of stable to default
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Wed, 01 May 2013 15:29:57 -0400
parents e84b77df8940 (diff) f2f5dd09e97d (current diff)
children 2c11d7c6cc21
files doc/interpreter/contrib.txi doc/interpreter/sparse.txi
diffstat 2697 files changed, 124407 insertions(+), 43296 deletions(-) [+]
line wrap: on
line diff
new file mode 100644
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,8 @@
+*~
+*.user
+*.o
+*.a
+Makefile*
+*.pdb
+debug/
+release/
--- a/.hgignore
+++ b/.hgignore
@@ -3,14 +3,17 @@
 # to mean "at any directory" while the ^ idiom means "from the
 # project's top-level directory".
 
-# This one gets created by gnulib during the build, contains no Octave
-# files.
-^gnulib/
+# gnulib makes these silly backup files
+.~$
 
-# These directories mostly contain cruft during build time, but they
-# do contain some Octave code.
-^libgnu/
-^m4/
+# This directory gets created by gnulib during the build. 
+# It contains no Octave files.
+^libgnu/*
+
+# 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
+^m4/(?!ax_).+\.m4$
 
 # Emacs tools create these
 (^|/)TAGS$
@@ -19,7 +22,7 @@
 (/|^)Makefile\.in$
 ^INSTALL$
 
-^aclocal\.m4
+^aclocal\.m4$
 ^build-.*($|/)
 ^configure$
 ^autom4te\.cache($|/)
@@ -33,7 +36,7 @@
 ^doc/\w*/version\.texi$
 ^doc/interpreter/images\.mk$
 
-# e.g. liboctave/smx-op-inc.mk
-^liboctave/[\w-]*\.mk$
+# e.g. liboctave/operators/smx-op-inc.mk
+^liboctave/operators/\w+-op-\w+\.mk$
 
-^src/DLD-FUNCTIONS/module\.mk$
+^libinterp/dldfcn/module\.mk$
--- a/.hgsubstate
+++ b/.hgsubstate
@@ -1,1 +1,1 @@
-36ae40a11dd574ebee3d2dad3b87d10fc9d3c4db gnulib-hg
+5a51fb7777a9950502965a043a70bd6ca5e0498b gnulib-hg
--- a/.hgtags
+++ b/.hgtags
@@ -60,11 +60,19 @@
 64d9f33313cc8c691974bcd123357e24bccbabdc rc-3-6-0-1
 704f7895eef03008dd79848eb9da4bfb40787d73 release-3.6.0
 95c43fc8dbe1a07a46fefb3372df5b2309d874fd rc-3-6-1-0
+0000000000000000000000000000000000000000 release-3-2-4
+e320928eeb3aa2370b792e83dafc3e0ddecdc871 release-3-2-4
+ba4d6343524b406b0d15aee34579f80783581c54 release-3-6-1
+704f7895eef03008dd79848eb9da4bfb40787d73 release-3-6-0
 f947d2922febf12dcd1fb6e21b356756ecb54e55 rc-3-6-2-0
 4460c4fb20e6a5d3b1972fa737d4e00eb921545a rc-3-6-2-2
 551566201318bf615b27c60ccf9368f4844008bd release-3-6-2
 a95432e7309ca6fc776c02939264bb6d443f3525 release-3-6-3
 2e8eb9ac43a5f8cfaf0423814a312ed47cb80485 rc-3-6-4-0
+df1aceb8f0bc6b5b5062907931cc663467f57d93 ss-3-7-1
 858cbf6fc2ec1c232f5cf1d75dc344439b39a89c rc-3-6-4-1
+faefa1bea8ddae3cab170afdeab68d3d15c4e623 ss-3-7-2
+0000000000000000000000000000000000000000 ss-3-7-2
+23a7661e529ae9bfc91693618f8c314c31f695ca ss-3-7-2
 cc5a7d1233f3acea85648baeb754fc0e8f225225 rc-3-6-4-2
 b29b10fbb7448cdfe29322446e1a589e7fe1a40a release-3-6-4
new file mode 100644
--- /dev/null
+++ b/CITATION
@@ -0,0 +1,20 @@
+To cite GNU Octave in publications use:
+
+  John W. Eaton, David Bateman, and Søren Hauberg (2009).  GNU Octave version
+  3.0.1 manual: a high-level interactive language for numerical computations.
+  CreateSpace Independent Publishing Platform.  ISBN 1441413006,
+  URL http://www.gnu.org/software/octave/doc/interpreter/
+
+A BibTeX entry for LaTeX users is:
+
+  @book{,
+    author    = {John W. Eaton and David Bateman and S\oren Hauberg},
+    title     = {{GNU Octave} version 3.0.1 manual: a high-level interactive language for numerical computations},
+    publisher = {CreateSpace Independent Publishing Platform},
+    year      = {2009},
+    note      = {{ISBN} 1441413006},
+    url       = {http://www.gnu.org/software/octave/doc/interpreter},
+  }
+
+We have invested a lot of time and effort in creating GNU Octave, please cite it
+when using it.  See also `citation pkgname' for citing Octave packages.
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,4 +1,4 @@
-# Makefile for octave
+# Makefile for Octave
 #
 # Copyright (C) 1993-2012 John W. Eaton
 #
@@ -37,12 +37,14 @@
   INSTALL.OCTAVE \
   NEWS \
   README \
-  autogen.sh \
-  build-aux/bootstrap \
-  build-aux/bootstrap.conf \
+  CITATION \
+  bootstrap \
+  bootstrap.conf \
+  build-aux/find-files-with-tests.sh \
   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 \
@@ -67,11 +69,18 @@
 
 include m4/module.mk
 
-# Subdirectories in which to run `make all'.
-SUBDIRS = libgnu libcruft liboctave src scripts @DOCDIR@ examples test
+# Subdirectories in which to run `make all'.  Including "." here
+# is an attempt to force all preceding directories in the list to
+# be processed before the current directory so that the
+# scripts/DOCSTRINGS libinterp/DOCSTRINGS files are built before
+# attempting to build AUTHORS and BUGS.
+SUBDIRS = libgnu liboctave libinterp
+if AMCOND_BUILD_GUI
+SUBDIRS += libgui
+endif
+SUBDIRS += src scripts . @DOCDIR@ examples test
 
-if AMCOND_BUILD_DOCS
-else
+if ! AMCOND_BUILD_DOCS
 dist-hook:
 	echo "Documentation disabled.  Cannot package distribution!" ; exit 1;
 endif
@@ -87,13 +96,16 @@
 
 CLEANFILES = $(BUILT_SOURCES)
 
-DISTCLEANFILES = .gdbinit 
+DISTCLEANFILES = \
+  .gdbinit \
+  ChangeLog
 
 MAINTAINERCLEANFILES = $(BUILT_DISTFILES)
 
 CONFIG_FILES = @ac_config_headers@ @ac_config_files@
 
 nodist_octinclude_HEADERS = config.h
+octinclude_HEADERS = oct-conf-post.h
 
 all-local: $(noinst_SCRIPTS) $(INFO_FILES) .gdbinit
 	@echo ""
@@ -119,8 +131,10 @@
 	  cp $< $@; \
 	fi
 
+if AMCOND_BUILD_DOCS
 AUTHORS BUGS INSTALL.OCTAVE:
 	$(MAKE) -C doc/interpreter ../../$@
+endif
 .PHONY: AUTHORS BUGS INSTALL.OCTAVE
 
 ChangeLog:
@@ -128,7 +142,9 @@
 	mv $@.t $@
 .PHONY: ChangeLog
 
-octetc_DATA = NEWS
+octetc_DATA = \
+  NEWS \
+  CITATION
 
 DIRS_TO_MAKE = \
   $(localfcnfiledir) \
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,227 @@
+Summary of important user-visible changes for version 4.0:
+---------------------------------------------------------
+
+ ** A new GUI is now available with Octave.
+
+ ** Warning states may now be set temporarily, until the end of the
+    current function, using the syntax
+
+      warning STATE ID "local"
+
+    in which STATE may be "on", "off", or "error".  Changes to warning
+    states that are set locally affect the current function and all
+    functions called from the current scope.  The previous warning state
+    is restored on return from the current function.  The "local"
+    option is ignored if used in the top-level workspace.
+
+Summary of important user-visible changes for version 3.8:
+---------------------------------------------------------
+
+ ** strsplit has been modified to be compatible with Matlab.  There
+    are two instances where backward compatibility is broken.
+
+    (1) Delimiters are now string vectors, not scalars.
+
+    Octave's legacy behavior
+
+      strsplit ("1 2, 3", ", ")
+      ans = 
+      {
+       [1,1] = 1
+       [1,2] = 2
+       [1,3] = 
+       [1,4] = 3
+      }
+
+    Matlab compatible behavior
+
+      strsplit ("1 2, 3", ", ")
+      ans = 
+      {
+       [1,1] = 1 2
+       [1,2] = 3
+      }
+
+    (2) By default, Matlab treats consecutive delimiters are as a single
+    delimiter.  By default, Octave's legacy behavior was to return an
+    empty string for the part between the delmiters.
+
+    Where the legacy behavior is desired, the call to strsplit() should
+    specify that the delimitertype is "legacy".
+
+    strsplit (str, del, "collapsedelimiters", false,
+      "delimitertype", "legacy")
+
+ ** Octave now supports nested functions with scoping rules that are
+    compatible with Matlab.  A nested function is one declared and defined
+    within the body of another function.  The nested function is only
+    accessible from within the enclosing function which makes it one
+    method for making private functions whose names do not conflict with those
+    in the global namespace (See also subfunctions and private functions).
+    In addition, variables in the enclosing function are visible within the
+    nested function.  This makes it possible to have a pseudo-global variable
+    which can be seen by a group of functions, but which is not visible in
+    the global namespace.
+    
+    Example:
+    function outerfunc (...)
+      ...
+      function nested1 (...)
+        ...
+        function nested2 (...)
+           ...
+        endfunction
+      endfunction
+
+      function nested3 (...)
+        ...
+      endfunction
+    endfunction
+
+ ** 'emptymatch', 'noemptymatch' options added to regular expressions.
+
+    With this addition Octave now accepts the entire set of Matlab options
+    for regular expressions.  'noemptymatch' is the default, but 'emptymatch'
+    has certain uses where you need to match an assertion rather than actual
+    characters.  For example, 
+
+    regexprep ('World', '^', 'Hello ', 'emptymatch')
+      => Hello World
+
+    where the pattern is actually the assertion '^' or start-of-line.
+
+ ** For compatibility with Matlab, the regexp, regexpi, and regexprep
+    functions now process backslash escape sequences in single-quoted pattern
+    strings.  In addition, the regexprep function now processes backslash
+    escapes in single-quoted replacement strings.  For example,
+    
+    regexprep (str, '\t', '\n')
+
+    would search the variable str for a TAB character (escape sequence \t)
+    and replace it with a NEWLINE (escape sequence \n).  Previously the
+    expression would have searched for a literal '\' followed by 't' and
+    replaced the two characters with the sequence '\', 'n'.
+
+ ** Redundant terminal comma accepted by parser
+
+    A redundant terminal comma is now accepted in matrix
+    definitions which allows writing code such as 
+
+    [a,...
+     b,...
+     c,...
+    ] = deal (1,2,3)
+
+ ** Warning IDs renamed:
+
+    Octave:array-as-scalar => Octave:array-to-scalar
+    Octave:array-as-vector => Octave:array-to-vector
+
+ ** The colormap function now provides new options--"list", "register",
+    and "unregister"--to list all available colormap functions, and to
+    add or remove a function name from the list of known colormap
+    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.
+    In addition, the default for formats which do not specify a date is
+    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.
+
+ ** A citation command has been added to display information on how to
+    cite Octave and packages in publications.  The package system will
+    look for and install CITATION files from packages.
+
+ ** 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:
+
+      debug_java     java_matrix_autoconversion
+      isjava         java_unsigned_autoconversion
+      java2mat       javaaddpath
+      javaArray      javaclasspath
+      javaMethod     javamem
+      javaObject     javarmpath
+                     usejava
+
+    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   ellipj    findfigs     polyeig       tetramesh
+      cmpermute    ellipke   fminsearch   rgbplot       waterfall
+      cmunique     erfcinv   importdata   shrinkfaces
+      colorcube    erfi      iscolormap   splinefit
+      dawson       expint    lines        strjoin
+
+ ** Deprecated functions.
+
+    The following functions were deprecated in Octave 3.4 and have been
+    removed from Octave 3.8.
+                                           
+      autocor    dispatch              is_global    strerror
+      autocov    fstat                 krylovb      values  
+      betai      gammai                perror               
+      cellidx    glpkmex               replot               
+      cquad      is_duplicate_entry    saveimage            
+      
+    The following functions have been deprecated in Octave 3.8 and will
+    be removed from Octave 3.12 (or whatever version is the second major
+    release after 3.8):
+
+      java_convert_matrix
+      java_debug
+      java_get
+      java_invoke
+      java_new
+      java_set
+      java_unsigned_conversion
+      javafields
+      javamethods
+
+    The following keywords have been deprecated in Octave 3.8 and will
+    be removed from Octave 3.12 (or whatever version is the second major
+    release after 3.8):
+
+      static
+
+    The following configuration variables have been deprecated in Octave
+    3.8 and will be removed from Octave 3.12 (or whatever version is the
+    second major release after 3.8):
+
+      CC_VERSION  (now GCC_VERSION)
+      CXX_VERSION (now GXX_VERSION)
+
 Summary of important user-visible changes for version 3.6:
 ---------------------------------------------------------
 
@@ -709,9 +933,9 @@
     be removed from Octave 3.8 (or whatever version is the second major
     release after 3.4):
 
-      autocor  cellidx   gammai     krylovb  saveimage 
-      autocov  dispatch  glpkmex    perror   strerror  
-      betai    fstat     is_global  replot   values    
+      autocor  cellidx   gammai     is_global  replot     values
+      autocov  dispatch  glpkmex    krylovb    saveimage
+      betai    fstat     intwarning perror     strerror
 
 Summary of important user-visible changes for version 3.2:
 ---------------------------------------------------------
rename from autogen.sh
rename to bootstrap
--- a/autogen.sh
+++ b/bootstrap
@@ -1,53 +1,978 @@
 #! /bin/sh
-# autogen.sh
-# Run this to generate all the initial makefiles, etc.
+# Print a version string.
+scriptversion=2012-07-19.14; # UTC
+
+# Bootstrap this package from checked-out sources.
+
+# Copyright (C) 2003-2012 Free Software Foundation, Inc.
+
+# 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/>.
+
+# Originally written by Paul Eggert.  The canonical version of this
+# script is maintained as build-aux/bootstrap in gnulib, however, to
+# be useful to your project, you should place a copy of it under
+# version control in the top-level directory of your project.  The
+# intent is that all customization can be done with a bootstrap.conf
+# file also maintained in your version control; gnulib comes with a
+# template build-aux/bootstrap.conf to get you started.
+
+# Please report bugs or propose patches to bug-gnulib@gnu.org.
+
+nl='
+'
+
+# Ensure file names are sorted consistently across platforms.
+LC_ALL=C
+export LC_ALL
+
+# Ensure that CDPATH is not set.  Otherwise, the output from cd
+# would cause trouble in at least one use below.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+local_gl_dir=gl
+
+me=$0
+
+usage() {
+  cat <<EOF
+Usage: $me [OPTION]...
+Bootstrap this package from the checked-out sources.
+
+Options:
+ --gnulib-srcdir=DIRNAME  specify the local directory where gnulib
+                          sources reside.  Use this if you already
+                          have gnulib sources on your machine, and
+                          do not want to waste your bandwidth downloading
+                          them again.  Defaults to \$GNULIB_SRCDIR
+ --bootstrap-sync         if this bootstrap script is not identical to
+                          the version in the local gnulib sources,
+                          update this script, and then restart it with
+                          /bin/sh or the shell \$CONFIG_SHELL
+ --no-bootstrap-sync      do not check whether bootstrap is out of sync
+ --copy                   copy files instead of creating symbolic links
+ --force                  attempt to bootstrap even if the sources seem
+                          not to have been checked out
+ --no-git                 do not use git to update gnulib.  Requires that
+                          --gnulib-srcdir point to a correct gnulib snapshot
+ --skip-po                do not download po files
 
-set -e
+If the file $me.conf exists in the same directory as this script, its
+contents are read as shell variables to configure the bootstrap.
+
+For build prerequisites, environment variables like \$AUTOCONF and \$AMTAR
+are honored.
+
+Running without arguments will suffice in most cases.
+EOF
+}
+
+# warnf_ FORMAT-STRING ARG1...
+warnf_ ()
+{
+  warnf_format_=$1
+  shift
+  nl='
+'
+  case $* in
+    *$nl*) me_=$(printf "$me"|tr "$nl|" '??')
+       printf "$warnf_format_" "$@" | sed "s|^|$me_: |" ;;
+    *) printf "$me: $warnf_format_" "$@" ;;
+  esac >&2
+}
+
+# warn_ WORD1...
+warn_ ()
+{
+  # If IFS does not start with ' ', set it and emit the warning in a subshell.
+  case $IFS in
+    ' '*) warnf_ '%s\n' "$*";;
+    *)    (IFS=' '; warn_ "$@");;
+  esac
+}
 
-## Use --foreign since we auto-generate the AUTHORS file and the default
-## --gnu strictness level doesn't like it if the AUTHORS file is missing.
+# die WORD1...
+die() { warn_ "$@"; exit 1; }
+
+# Configuration.
+
+# Name of the Makefile.am
+gnulib_mk=gnulib.mk
+
+# List of gnulib modules needed.
+gnulib_modules=
+
+# Any gnulib files needed that are not in modules.
+gnulib_files=
+
+: ${AUTOPOINT=autopoint}
+: ${AUTORECONF=autoreconf}
+
+# A function to be called right after gnulib-tool is run.
+# Override it via your own definition in bootstrap.conf.
+bootstrap_post_import_hook() { :; }
+
+# A function to be called after everything else in this script.
+# Override it via your own definition in bootstrap.conf.
+bootstrap_epilogue() { :; }
+
+# The command to download all .po files for a specified domain into
+# a specified directory.  Fill in the first %s is the domain name, and
+# the second with the destination directory.  Use rsync's -L and -r
+# options because the latest/%s directory and the .po files within are
+# all symlinks.
+po_download_command_format=\
+"rsync --delete --exclude '*.s1' -Lrtvz \
+ 'translationproject.org::tp/latest/%s/' '%s'"
+
+# Fallback for downloading .po files (if rsync fails).
+po_download_command_format2=\
+"wget --mirror -nd -q -np -A.po -P '%s' \
+ http://translationproject.org/latest/%s/"
 
-AUTOMAKE="automake --foreign --warnings=no-portability"
-export AUTOMAKE
+extract_package_name='
+  /^AC_INIT(/{
+     /.*,.*,.*, */{
+       s///
+       s/[][]//g
+       s/)$//
+       p
+       q
+     }
+     s/AC_INIT(\[*//
+     s/]*,.*//
+     s/^GNU //
+     y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/
+     s/[^A-Za-z0-9_]/-/g
+     p
+  }
+'
+package=$(sed -n "$extract_package_name" configure.ac) \
+  || die 'cannot find package name in configure.ac'
+gnulib_name=lib$package
+
+build_aux=build-aux
+source_base=lib
+m4_base=m4
+doc_base=doc
+tests_base=tests
+gnulib_extra_files=''
+
+# Additional gnulib-tool options to use.  Use "\newline" to break lines.
+gnulib_tool_option_extras=
+
+# Other locale categories that need message catalogs.
+EXTRA_LOCALE_CATEGORIES=
+
+# Additional xgettext options to use.  Use "\\\newline" to break lines.
+XGETTEXT_OPTIONS='\\\
+ --flag=_:1:pass-c-format\\\
+ --flag=N_:1:pass-c-format\\\
+ --flag=error:3:c-format --flag=error_at_line:5:c-format\\\
+'
+
+# Package bug report address and copyright holder for gettext files
+COPYRIGHT_HOLDER='Free Software Foundation, Inc.'
+MSGID_BUGS_ADDRESS=bug-$package@gnu.org
+
+# Files we don't want to import.
+excluded_files=
+
+# File that should exist in the top directory of a checked out hierarchy,
+# but not in a distribution tarball.
+checkout_only_file=README-hacking
+
+# Whether to use copies instead of symlinks.
+copy=false
+
+# Set this to '.cvsignore .gitignore' in bootstrap.conf if you want
+# those files to be generated in directories like lib/, m4/, and po/.
+# Or set it to 'auto' to make this script select which to use based
+# on which version control system (if any) is used in the source directory.
+vc_ignore=auto
+
+# Set this to true in bootstrap.conf to enable --bootstrap-sync by
+# default.
+bootstrap_sync=false
+
+# Don't use git to update gnulib sources. We keep gnulib under a
+# Mercurial subrepository instead
+use_git=false
+GNULIB_SRCDIR=gnulib-hg
 
-## Check for files that automake --gnu would normally look for, except
-## AUTHORS, which we autogenerate from the documentation files along with
-## building the rest of Octave, and INSTALL, which is linked from
-## gnulib/doc/INSTALL by the bootstrap script.
+# find_tool ENVVAR NAMES...
+# -------------------------
+# Search for a required program.  Use the value of ENVVAR, if set,
+# otherwise find the first of the NAMES that can be run (i.e.,
+# supports --version).  If found, set ENVVAR to the program name,
+# die otherwise.
+#
+# FIXME: code duplication, see also gnu-web-doc-update.
+find_tool ()
+{
+  find_tool_envvar=$1
+  shift
+  find_tool_names=$@
+  eval "find_tool_res=\$$find_tool_envvar"
+  if test x"$find_tool_res" = x; then
+    for i
+    do
+      if ($i --version </dev/null) >/dev/null 2>&1; then
+       find_tool_res=$i
+       break
+      fi
+    done
+  else
+    find_tool_error_prefix="\$$find_tool_envvar: "
+  fi
+  test x"$find_tool_res" != x \
+    || die "one of these is required: $find_tool_names"
+  ($find_tool_res --version </dev/null) >/dev/null 2>&1 \
+    || die "${find_tool_error_prefix}cannot run $find_tool_res --version"
+  eval "$find_tool_envvar=\$find_tool_res"
+  eval "export $find_tool_envvar"
+}
+
+# Find sha1sum, named gsha1sum on MacPorts, and shasum on Mac OS X 10.6.
+find_tool SHA1SUM sha1sum gsha1sum shasum
+
+# Override the default configuration, if necessary.
+# Make sure that bootstrap.conf is sourced from the current directory
+# if we were invoked as "sh bootstrap".
+case "$0" in
+  */*) test -r "$0.conf" && . "$0.conf" ;;
+  *) test -r "$0.conf" && . ./"$0.conf" ;;
+esac
 
-for f in NEWS README COPYING; do
-  if ! test -f $f; then
-    echo "required file $f is missing" 2>&1
-    exit 1
-  fi
+# Extra files from gnulib, which override files from other sources.
+test -z "${gnulib_extra_files}" && \
+  gnulib_extra_files="
+        $build_aux/install-sh
+        $build_aux/mdate-sh
+        $build_aux/texinfo.tex
+        $build_aux/depcomp
+        $build_aux/config.guess
+        $build_aux/config.sub
+        doc/INSTALL
+"
+
+if test "$vc_ignore" = auto; then
+  vc_ignore=
+  test -d .git && vc_ignore=.gitignore
+  test -d CVS && vc_ignore="$vc_ignore .cvsignore"
+fi
+
+# Translate configuration into internal form.
+
+# Parse options.
+
+for option
+do
+  case $option in
+  --help)
+    usage
+    exit;;
+  --gnulib-srcdir=*)
+    GNULIB_SRCDIR=${option#--gnulib-srcdir=};;
+  --skip-po)
+    SKIP_PO=t;;
+  --force)
+    checkout_only_file=;;
+  --copy)
+    copy=true;;
+  --bootstrap-sync)
+    bootstrap_sync=true;;
+  --no-bootstrap-sync)
+    bootstrap_sync=false;;
+  --no-git)
+    use_git=false;;
+  *)
+    die "$option: unknown option";;
+  esac
 done
 
-echo "generating source lists for liboctave/Makefile..."
+$use_git || test -d "$GNULIB_SRCDIR" \
+  || die "Error: --no-git requires --gnulib-srcdir"
+
+if test -n "$checkout_only_file" && test ! -r "$checkout_only_file"; then
+  die "Bootstrapping from a non-checked-out distribution is risky."
+fi
+
+# Ensure that lines starting with ! sort last, per gitignore conventions
+# for whitelisting exceptions after a more generic blacklist pattern.
+sort_patterns() {
+  sort -u "$@" | sed '/^!/ {
+    H
+    d
+  }
+  $ {
+    P
+    x
+    s/^\n//
+  }' | sed '/^$/d'
+}
+
+# If $STR is not already on a line by itself in $FILE, insert it,
+# sorting the new contents of the file and replacing $FILE with the result.
+insert_sorted_if_absent() {
+  file=$1
+  str=$2
+  test -f $file || touch $file
+  echo "$str" | sort_patterns - $file | cmp -s - $file > /dev/null \
+    || { echo "$str" | sort_patterns - $file > $file.bak \
+      && mv $file.bak $file; } \
+    || die "insert_sorted_if_absent $file $str: failed"
+}
+
+# Adjust $PATTERN for $VC_IGNORE_FILE and insert it with
+# insert_sorted_if_absent.
+insert_vc_ignore() {
+  vc_ignore_file="$1"
+  pattern="$2"
+  case $vc_ignore_file in
+  *.gitignore)
+    # A .gitignore entry that does not start with '/' applies
+    # recursively to subdirectories, so prepend '/' to every
+    # .gitignore entry.
+    pattern=$(echo "$pattern" | sed s,^,/,);;
+  esac
+  insert_sorted_if_absent "$vc_ignore_file" "$pattern"
+}
+
+# Die if there is no AC_CONFIG_AUX_DIR($build_aux) line in configure.ac.
+found_aux_dir=no
+grep '^[	 ]*AC_CONFIG_AUX_DIR(\['"$build_aux"'\])' configure.ac \
+    >/dev/null && found_aux_dir=yes
+grep '^[	 ]*AC_CONFIG_AUX_DIR('"$build_aux"')' configure.ac \
+    >/dev/null && found_aux_dir=yes
+test $found_aux_dir = yes \
+  || die "configure.ac lacks 'AC_CONFIG_AUX_DIR([$build_aux])'; add it"
+
+# If $build_aux doesn't exist, create it now, otherwise some bits
+# below will malfunction.  If creating it, also mark it as ignored.
+if test ! -d $build_aux; then
+  mkdir $build_aux
+  for dot_ig in x $vc_ignore; do
+    test $dot_ig = x && continue
+    insert_vc_ignore $dot_ig $build_aux
+  done
+fi
 
-(cd liboctave; ./config-ops.sh)
+# Note this deviates from the version comparison in automake
+# in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a
+# but this should suffice as we won't be specifying old
+# version formats or redundant trailing .0 in bootstrap.conf.
+# If we did want full compatibility then we should probably
+# use m4_version_compare from autoconf.
+sort_ver() { # sort -V is not generally available
+  ver1="$1"
+  ver2="$2"
+
+  # split on '.' and compare each component
+  i=1
+  while : ; do
+    p1=$(echo "$ver1" | cut -d. -f$i)
+    p2=$(echo "$ver2" | cut -d. -f$i)
+    if [ ! "$p1" ]; then
+      echo "$1 $2"
+      break
+    elif [ ! "$p2" ]; then
+      echo "$2 $1"
+      break
+    elif [ ! "$p1" = "$p2" ]; then
+      if [ "$p1" -gt "$p2" ] 2>/dev/null; then # numeric comparison
+        echo "$2 $1"
+      elif [ "$p2" -gt "$p1" ] 2>/dev/null; then # numeric comparison
+        echo "$1 $2"
+      else # numeric, then lexicographic comparison
+        lp=$(printf "$p1\n$p2\n" | LANG=C sort -n | tail -n1)
+        if [ "$lp" = "$p2" ]; then
+          echo "$1 $2"
+        else
+          echo "$2 $1"
+        fi
+      fi
+      break
+    fi
+    i=$(($i+1))
+  done
+}
 
-echo "generating doc/interpreter/images.mk..."
+get_version() {
+  app=$1
+
+  $app --version >/dev/null 2>&1 || return 1
+
+  $app --version 2>&1 |
+  sed -n '# Move version to start of line.
+          s/.*[v ]\([0-9]\)/\1/
+
+          # Skip lines that do not start with version.
+          /^[0-9]/!d
+
+          # Remove characters after the version.
+          s/[^.a-z0-9-].*//
+
+          # The first component must be digits only.
+          s/^\([0-9]*\)[a-z-].*/\1/
+
+          #the following essentially does s/5.005/5.5/
+          s/\.0*\([1-9]\)/.\1/g
+          p
+          q'
+}
+
+check_versions() {
+  ret=0
+
+  while read app req_ver; do
+    # We only need libtoolize from the libtool package.
+    if test "$app" = libtool; then
+      app=libtoolize
+    fi
+    # Exempt git if --no-git is in effect.
+    if test "$app" = git; then
+      $use_git || continue
+    fi
+    # Honor $APP variables ($TAR, $AUTOCONF, etc.)
+    appvar=$(echo $app | LC_ALL=C tr '[a-z]-' '[A-Z]_')
+    test "$appvar" = TAR && appvar=AMTAR
+    case $appvar in
+        GZIP) ;; # Do not use $GZIP:  it contains gzip options.
+        *) eval "app=\${$appvar-$app}" ;;
+    esac
 
-(cd doc/interpreter; ./config-images.sh)
+    # Handle the still-experimental Automake-NG programs specially.
+    # They remain named as the mainstream Automake programs ("automake",
+    # and "aclocal") to avoid gratuitous incompatibilities with
+    # pre-existing usages (by, say, autoreconf, or custom autogen.sh
+    # scripts), but correctly identify themselves (as being part of
+    # "GNU automake-ng") when asked their version.
+    case $app in
+      automake-ng|aclocal-ng)
+        app=${app%-ng}
+        ($app --version | grep '(GNU automake-ng)') >/dev/null 2>&1 || {
+          warn_ "Error: '$app' not found or not from Automake-NG"
+          ret=1
+          continue
+        } ;;
+    esac
+    if [ "$req_ver" = "-" ]; then
+      # Merely require app to exist; not all prereq apps are well-behaved
+      # so we have to rely on $? rather than get_version.
+      $app --version >/dev/null 2>&1
+      if [ 126 -le $? ]; then
+        warn_ "Error: '$app' not found"
+        ret=1
+      fi
+    else
+      # Require app to produce a new enough version string.
+      inst_ver=$(get_version $app)
+      if [ ! "$inst_ver" ]; then
+        warn_ "Error: '$app' not found"
+        ret=1
+      else
+        latest_ver=$(sort_ver $req_ver $inst_ver | cut -d' ' -f2)
+        if [ ! "$latest_ver" = "$inst_ver" ]; then
+          warnf_ '%s\n'                                        \
+              "Error: '$app' version == $inst_ver is too old"  \
+              "       '$app' version >= $req_ver is required"
+          ret=1
+        fi
+      fi
+    fi
+  done
+
+  return $ret
+}
 
-echo "generating src/DLD-FUNCTIONS/module.mk..."
+print_versions() {
+  echo "Program    Min_version"
+  echo "----------------------"
+  printf %s "$buildreq"
+  echo "----------------------"
+  # can't depend on column -t
+}
+
+use_libtool=0
+# We'd like to use grep -E, to see if any of LT_INIT,
+# AC_PROG_LIBTOOL, AM_PROG_LIBTOOL is used in configure.ac,
+# but that's not portable enough (e.g., for Solaris).
+grep '^[	 ]*A[CM]_PROG_LIBTOOL' configure.ac >/dev/null \
+  && use_libtool=1
+grep '^[	 ]*LT_INIT' configure.ac >/dev/null \
+  && use_libtool=1
+if test $use_libtool = 1; then
+  find_tool LIBTOOLIZE glibtoolize libtoolize
+fi
+
+# gnulib-tool requires at least automake and autoconf.
+# If either is not listed, add it (with minimum version) as a prerequisite.
+case $buildreq in
+  *automake*) ;;
+  *) buildreq="automake 1.9
+$buildreq" ;;
+esac
+case $buildreq in
+  *autoconf*) ;;
+  *) buildreq="autoconf 2.59
+$buildreq" ;;
+esac
+
+# When we can deduce that gnulib-tool will require patch,
+# and when patch is not already listed as a prerequisite, add it, too.
+if test -d "$local_gl_dir" \
+    && ! find "$local_gl_dir" -name '*.diff' -exec false {} +; then
+  case $buildreq in
+    *patch*) ;;
+    *) buildreq="patch -
+$buildreq" ;;
+  esac
+fi
 
-(cd src/DLD-FUNCTIONS; ./config-module.sh)
+if ! printf "$buildreq" | check_versions; then
+  echo >&2
+  if test -f README-prereq; then
+    die "See README-prereq for how to get the prerequisite programs"
+  else
+    die "Please install the prerequisite programs"
+  fi
+fi
+
+echo "$0: Bootstrapping from checked-out $package sources..."
+
+# See if we can use gnulib's git-merge-changelog merge driver.
+if test -d .git && (git --version) >/dev/null 2>/dev/null ; then
+  if git config merge.merge-changelog.driver >/dev/null ; then
+    :
+  elif (git-merge-changelog --version) >/dev/null 2>/dev/null ; then
+    echo "$0: initializing git-merge-changelog driver"
+    git config merge.merge-changelog.name 'GNU-style ChangeLog merge driver'
+    git config merge.merge-changelog.driver 'git-merge-changelog %O %A %B'
+  else
+    echo "$0: consider installing git-merge-changelog from gnulib"
+  fi
+fi
+
+
+cleanup_gnulib() {
+  status=$?
+  rm -fr "$gnulib_path"
+  exit $status
+}
+
+git_modules_config () {
+  test -f .gitmodules && git config --file .gitmodules "$@"
+}
+
+gnulib_path=$(git_modules_config submodule.gnulib.path)
+test -z "$gnulib_path" && gnulib_path=gnulib
+
+# Get gnulib files.
+
+case ${GNULIB_SRCDIR--} in
+-)
+  if git_modules_config submodule.gnulib.url >/dev/null; then
+    echo "$0: getting gnulib files..."
+    git submodule init || exit $?
+    git submodule update || exit $?
 
-echo "bootstrapping..."
+  elif [ ! -d "$gnulib_path" ]; then
+    echo "$0: getting gnulib files..."
+
+    trap cleanup_gnulib 1 2 13 15
+
+    shallow=
+    git clone -h 2>&1 | grep -- --depth > /dev/null && shallow='--depth 2'
+    git clone $shallow git://git.sv.gnu.org/gnulib "$gnulib_path" ||
+      cleanup_gnulib
+
+    trap - 1 2 13 15
+  fi
+  GNULIB_SRCDIR=$gnulib_path
+  ;;
+*)
+  # Use GNULIB_SRCDIR as a reference.
+  if test -d "$GNULIB_SRCDIR"/.git && \
+        git_modules_config submodule.gnulib.url >/dev/null; then
+    echo "$0: getting gnulib files..."
+    if git submodule -h|grep -- --reference > /dev/null; then
+      # Prefer the one-liner available in git 1.6.4 or newer.
+      git submodule update --init --reference "$GNULIB_SRCDIR" \
+        "$gnulib_path" || exit $?
+    else
+      # This fallback allows at least git 1.5.5.
+      if test -f "$gnulib_path"/gnulib-tool; then
+        # Since file already exists, assume submodule init already complete.
+        git submodule update || exit $?
+      else
+        # Older git can't clone into an empty directory.
+        rmdir "$gnulib_path" 2>/dev/null
+        git clone --reference "$GNULIB_SRCDIR" \
+          "$(git_modules_config submodule.gnulib.url)" "$gnulib_path" \
+          && git submodule init && git submodule update \
+          || exit $?
+      fi
+    fi
+    GNULIB_SRCDIR=$gnulib_path
+  fi
+  ;;
+esac
+
+if $bootstrap_sync; then
+  cmp -s "$0" "$GNULIB_SRCDIR/build-aux/bootstrap" || {
+    echo "$0: updating bootstrap and restarting..."
+    exec sh -c \
+      'cp "$1" "$2" && shift && exec "${CONFIG_SHELL-/bin/sh}" "$@"' \
+      -- "$GNULIB_SRCDIR/build-aux/bootstrap" \
+      "$0" "$@" --no-bootstrap-sync
+  }
+fi
 
-build-aux/bootstrap "$@"
+gnulib_tool=$GNULIB_SRCDIR/gnulib-tool
+<$gnulib_tool || exit $?
+
+# Get translations.
+
+download_po_files() {
+  subdir=$1
+  domain=$2
+  echo "$me: getting translations into $subdir for $domain..."
+  cmd=$(printf "$po_download_command_format" "$domain" "$subdir")
+  eval "$cmd" && return
+  # Fallback to HTTP.
+  cmd=$(printf "$po_download_command_format2" "$subdir" "$domain")
+  eval "$cmd"
+}
+
+# Mirror .po files to $po_dir/.reference and copy only the new
+# or modified ones into $po_dir.  Also update $po_dir/LINGUAS.
+# Note po files that exist locally only are left in $po_dir but will
+# not be included in LINGUAS and hence will not be distributed.
+update_po_files() {
+  # Directory containing primary .po files.
+  # Overwrite them only when we're sure a .po file is new.
+  po_dir=$1
+  domain=$2
+
+  # Mirror *.po files into this dir.
+  # Usually contains *.s1 checksum files.
+  ref_po_dir="$po_dir/.reference"
+
+  test -d $ref_po_dir || mkdir $ref_po_dir || return
+  download_po_files $ref_po_dir $domain \
+    && ls "$ref_po_dir"/*.po 2>/dev/null |
+      sed 's|.*/||; s|\.po$||' > "$po_dir/LINGUAS" || return
+
+  langs=$(cd $ref_po_dir && echo *.po | sed 's/\.po//g')
+  test "$langs" = '*' && langs=x
+  for po in $langs; do
+    case $po in x) continue;; esac
+    new_po="$ref_po_dir/$po.po"
+    cksum_file="$ref_po_dir/$po.s1"
+    if ! test -f "$cksum_file" ||
+        ! test -f "$po_dir/$po.po" ||
+        ! $SHA1SUM -c --status "$cksum_file" \
+            < "$new_po" > /dev/null; then
+      echo "$me: updated $po_dir/$po.po..."
+      cp "$new_po" "$po_dir/$po.po" \
+          && $SHA1SUM < "$new_po" > "$cksum_file"
+    fi
+  done
+}
+
+case $SKIP_PO in
+'')
+  if test -d po; then
+    update_po_files po $package || exit
+  fi
+
+  if test -d runtime-po; then
+    update_po_files runtime-po $package-runtime || exit
+  fi;;
+esac
+
+symlink_to_dir()
+{
+  src=$1/$2
+  dst=${3-$2}
+
+  test -f "$src" && {
+
+    # If the destination directory doesn't exist, create it.
+    # This is required at least for "lib/uniwidth/cjk.h".
+    dst_dir=$(dirname "$dst")
+    if ! test -d "$dst_dir"; then
+      mkdir -p "$dst_dir"
+
+      # If we've just created a directory like lib/uniwidth,
+      # tell version control system(s) it's ignorable.
+      # FIXME: for now, this does only one level
+      parent=$(dirname "$dst_dir")
+      for dot_ig in x $vc_ignore; do
+        test $dot_ig = x && continue
+        ig=$parent/$dot_ig
+        insert_vc_ignore $ig "${dst_dir##*/}"
+      done
+    fi
+
+    if $copy; then
+      {
+        test ! -h "$dst" || {
+          echo "$me: rm -f $dst" &&
+          rm -f "$dst"
+        }
+      } &&
+      test -f "$dst" &&
+      cmp -s "$src" "$dst" || {
+        echo "$me: cp -fp $src $dst" &&
+        cp -fp "$src" "$dst"
+      }
+    else
+      # Leave any existing symlink alone, if it already points to the source,
+      # so that broken build tools that care about symlink times
+      # aren't confused into doing unnecessary builds.  Conversely, if the
+      # existing symlink's time stamp is older than the source, make it afresh,
+      # so that broken tools aren't confused into skipping needed builds.  See
+      # <http://lists.gnu.org/archive/html/bug-gnulib/2011-05/msg00326.html>.
+      test -h "$dst" &&
+      src_ls=$(ls -diL "$src" 2>/dev/null) && set $src_ls && src_i=$1 &&
+      dst_ls=$(ls -diL "$dst" 2>/dev/null) && set $dst_ls && dst_i=$1 &&
+      test "$src_i" = "$dst_i" &&
+      both_ls=$(ls -dt "$src" "$dst") &&
+      test "X$both_ls" = "X$dst$nl$src" || {
+        dot_dots=
+        case $src in
+        /*) ;;
+        *)
+          case /$dst/ in
+          *//* | */../* | */./* | /*/*/*/*/*/)
+             die "invalid symlink calculation: $src -> $dst";;
+          /*/*/*/*/)    dot_dots=../../../;;
+          /*/*/*/)      dot_dots=../../;;
+          /*/*/)        dot_dots=../;;
+          esac;;
+        esac
+
+        echo "$me: ln -fs $dot_dots$src $dst" &&
+        ln -fs "$dot_dots$src" "$dst"
+      }
+    fi
+  }
+}
+
+version_controlled_file() {
+  parent=$1
+  file=$2
+  if test -d .git; then
+    git rm -n "$file" > /dev/null 2>&1
+  elif test -d .svn; then
+    svn log -r HEAD "$file" > /dev/null 2>&1
+  elif test -d CVS; then
+    grep -F "/${file##*/}/" "$parent/CVS/Entries" 2>/dev/null |
+             grep '^/[^/]*/[0-9]' > /dev/null
+  else
+    warn_ "no version control for $file?"
+    false
+  fi
+}
+
+# NOTE: we have to be careful to run both autopoint and libtoolize
+# before gnulib-tool, since gnulib-tool is likely to provide newer
+# versions of files "installed" by these two programs.
+# Then, *after* gnulib-tool (see below), we have to be careful to
+# run autoreconf in such a way that it does not run either of these
+# two just-pre-run programs.
+
+# Import from gettext.
+with_gettext=yes
+grep '^[	 ]*AM_GNU_GETTEXT_VERSION(' configure.ac >/dev/null || \
+    with_gettext=no
+
+if test $with_gettext = yes || test $use_libtool = 1; then
+
+  tempbase=.bootstrap$$
+  trap "rm -f $tempbase.0 $tempbase.1" 1 2 13 15
+
+  > $tempbase.0 > $tempbase.1 &&
+  find . ! -type d -print | sort > $tempbase.0 || exit
 
-## G77 is obsolete, but it is still the first option in the autoconf Fortran
-## macros.  We should avoid it, because mixing old versions of g77 with modern
-## gcc and g++ causes trouble.  The following will make it harder (but not
-## impossible) for users to make this mistake.
-##
-## FIXME -- we should really work to fix autoconf so that it prefers gfortran
-## over g77 even when searching for a Fortran 77 compiler.
+  if test $with_gettext = yes; then
+    # Released autopoint has the tendency to install macros that have been
+    # obsoleted in current gnulib, so run this before gnulib-tool.
+    echo "$0: $AUTOPOINT --force"
+    $AUTOPOINT --force || exit
+  fi
+
+  # Autoreconf runs aclocal before libtoolize, which causes spurious
+  # warnings if the initial aclocal is confused by the libtoolized
+  # (or worse out-of-date) macro directory.
+  # libtoolize 1.9b added the --install option; but we support back
+  # to libtoolize 1.5.22, where the install action was default.
+  if test $use_libtool = 1; then
+    install=
+    case $($LIBTOOLIZE --help) in
+      *--install*) install=--install ;;
+    esac
+    echo "running: $LIBTOOLIZE $install --copy"
+    $LIBTOOLIZE $install --copy
+  fi
+
+  find . ! -type d -print | sort >$tempbase.1
+  old_IFS=$IFS
+  IFS=$nl
+  for file in $(comm -13 $tempbase.0 $tempbase.1); do
+    IFS=$old_IFS
+    parent=${file%/*}
+    version_controlled_file "$parent" "$file" || {
+      for dot_ig in x $vc_ignore; do
+        test $dot_ig = x && continue
+        ig=$parent/$dot_ig
+        insert_vc_ignore "$ig" "${file##*/}"
+      done
+    }
+  done
+  IFS=$old_IFS
+
+  rm -f $tempbase.0 $tempbase.1
+  trap - 1 2 13 15
+fi
+
+# Import from gnulib.
+
+gnulib_tool_options="\
+ --import\
+ --no-changelog\
+ --aux-dir $build_aux\
+ --doc-base $doc_base\
+ --lib $gnulib_name\
+ --m4-base $m4_base/\
+ --source-base $source_base/\
+ --tests-base $tests_base\
+ --local-dir $local_gl_dir\
+ $gnulib_tool_option_extras\
+"
+if test $use_libtool = 1; then
+  case "$gnulib_tool_options " in
+    *' --libtool '*) ;;
+    *) gnulib_tool_options="$gnulib_tool_options --libtool" ;;
+  esac
+fi
+echo "$0: $gnulib_tool $gnulib_tool_options --import ..."
+$gnulib_tool $gnulib_tool_options --import $gnulib_modules &&
+
+for file in $gnulib_files; do
+  symlink_to_dir "$GNULIB_SRCDIR" $file \
+    || die "failed to symlink $file"
+done
+
+bootstrap_post_import_hook \
+  || die "bootstrap_post_import_hook failed"
+
+# Remove any dangling symlink matching "*.m4" or "*.[ch]" in some
+# gnulib-populated directories.  Such .m4 files would cause aclocal to fail.
+# The following requires GNU find 4.2.3 or newer.  Considering the usual
+# portability constraints of this script, that may seem a very demanding
+# requirement, but it should be ok.  Ignore any failure, which is fine,
+# since this is only a convenience to help developers avoid the relatively
+# unusual case in which a symlinked-to .m4 file is git-removed from gnulib
+# between successive runs of this script.
+find "$m4_base" "$source_base" \
+  -depth \( -name '*.m4' -o -name '*.[ch]' \) \
+  -type l -xtype l -delete > /dev/null 2>&1
 
-echo "replacing all occurrences of g77 with gfortran in configure script..."
+# Some systems (RHEL 5) are using ancient autotools, for which the
+# --no-recursive option had not been invented.  Detect that lack and
+# omit the option when it's not supported.  FIXME in 2017: remove this
+# hack when RHEL 5 autotools are updated, or when they become irrelevant.
+no_recursive=
+case $($AUTORECONF --help) in
+  *--no-recursive*) no_recursive=--no-recursive;;
+esac
+
+# Tell autoreconf not to invoke autopoint or libtoolize; they were run above.
+echo "running: AUTOPOINT=true LIBTOOLIZE=true " \
+    "$AUTORECONF --verbose --install $no_recursive -I $m4_base $ACLOCAL_FLAGS"
+AUTOPOINT=true LIBTOOLIZE=true \
+    $AUTORECONF --verbose --install $no_recursive -I $m4_base $ACLOCAL_FLAGS \
+  || die "autoreconf failed"
+
+# Get some extra files from gnulib, overriding existing files.
+for file in $gnulib_extra_files; do
+  case $file in
+  */INSTALL) dst=INSTALL;;
+  build-aux/*) dst=$build_aux/${file#build-aux/};;
+  *) dst=$file;;
+  esac
+  symlink_to_dir "$GNULIB_SRCDIR" $file $dst \
+    || die "failed to symlink $file"
+done
+
+if test $with_gettext = yes; then
+  # Create gettext configuration.
+  echo "$0: Creating po/Makevars from po/Makevars.template ..."
+  rm -f po/Makevars
+  sed '
+    /^EXTRA_LOCALE_CATEGORIES *=/s/=.*/= '"$EXTRA_LOCALE_CATEGORIES"'/
+    /^COPYRIGHT_HOLDER *=/s/=.*/= '"$COPYRIGHT_HOLDER"'/
+    /^MSGID_BUGS_ADDRESS *=/s|=.*|= '"$MSGID_BUGS_ADDRESS"'|
+    /^XGETTEXT_OPTIONS *=/{
+      s/$/ \\/
+      a\
+          '"$XGETTEXT_OPTIONS"' $${end_of_xgettext_options+}
+    }
+  ' po/Makevars.template >po/Makevars \
+    || die 'cannot generate po/Makevars'
 
-sed 's/g77/gfortran/g' configure > configure.t
-mv configure.t configure
-chmod 755 configure
+  # If the 'gettext' module is in use, grab the latest Makefile.in.in.
+  # If only the 'gettext-h' module is in use, assume autopoint already
+  # put the correct version of this file into place.
+  case $gnulib_modules in
+  *gettext-h*) ;;
+  *gettext*)
+    cp $GNULIB_SRCDIR/build-aux/po/Makefile.in.in po/Makefile.in.in \
+      || die "cannot create po/Makefile.in.in"
+    ;;
+  esac
+
+  if test -d runtime-po; then
+    # Similarly for runtime-po/Makevars, but not quite the same.
+    rm -f runtime-po/Makevars
+    sed '
+      /^DOMAIN *=.*/s/=.*/= '"$package"'-runtime/
+      /^subdir *=.*/s/=.*/= runtime-po/
+      /^MSGID_BUGS_ADDRESS *=/s/=.*/= bug-'"$package"'@gnu.org/
+      /^XGETTEXT_OPTIONS *=/{
+        s/$/ \\/
+        a\
+            '"$XGETTEXT_OPTIONS_RUNTIME"' $${end_of_xgettext_options+}
+      }
+    ' po/Makevars.template >runtime-po/Makevars \
+    || die 'cannot generate runtime-po/Makevars'
+
+    # Copy identical files from po to runtime-po.
+    (cd po && cp -p Makefile.in.in *-quot *.header *.sed *.sin ../runtime-po)
+  fi
+fi
+
+bootstrap_epilogue
+
+echo "$0: done.  Now you can run './configure'."
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
+# End:
rename from build-aux/bootstrap.conf
rename to bootstrap.conf
--- a/build-aux/bootstrap.conf
+++ b/bootstrap.conf
@@ -18,17 +18,25 @@
 
 # gnulib modules used by this package.
 gnulib_modules="
-  c-strcase
+  base64
+  canonicalize
+  chdir
+  close
+  closedir
   copysign
   copysignf
-  closedir
   crypto/md5
+  dup2
   fclose
   fcntl
+  fflush
   filemode
+  float
+  floor
+  floorf
   fnmatch
   fopen
-  fflush
+  fpucw
   fseek
   ftell
   getcwd
@@ -37,33 +45,38 @@
   gettimeofday
   glob
   isatty
+  largefile
   link
   lstat
+  malloc-gnu
   mkdir
   mkfifo
   mkostemp
-  mkstemp
   mktime
   nanosleep
   nproc
+  open
   opendir
   pathmax
+  putenv
   progname
   readdir
   readlink
+  realloc-gnu
   rename
-  rewinddir
   rmdir
   round
   roundf
+  select
   sigaction
   signal
   sigprocmask
   sleep
-  sleep
   stat
+  stddef
   stdint
   stdio
+  strerror
   strftime
   strptime
   symlink
@@ -129,3 +142,53 @@
 gnulib_tool_option_extras="--libtool"
 gnulib_name="libgnu"
 source_base="libgnu"
+
+## Use --foreign since we auto-generate the AUTHORS file and the default
+## --gnu strictness level doesn't like it if the AUTHORS file is missing.
+
+AUTOMAKE="automake --foreign --warnings=no-portability"
+export AUTOMAKE
+
+bootstrap_post_import_hook ()
+{
+  ## Check for files that automake --gnu would normally look for, except
+  ## AUTHORS, which we autogenerate from the documentation files along
+  ## with building the rest of Octave, and INSTALL, which is linked from
+  ## gnulib/doc/INSTALL by the bootstrap script.
+
+  for f in NEWS README COPYING CITATION; do
+    if ! test -f $f; then
+      echo "required file $f is missing" 2>&1
+      exit 1
+    fi
+  done
+
+  echo "generating source lists for liboctave/operators/module.mk..."
+
+  (cd liboctave/operators; ./config-ops.sh)
+
+  echo "generating doc/interpreter/images.mk..."
+
+  (cd doc/interpreter; ./config-images.sh)
+
+  echo "generating libinterp/dldfcn/module.mk..."
+
+  (cd libinterp/dldfcn; ./config-module.sh)
+}
+
+bootstrap_epilogue ()
+{
+  ## G77 is obsolete, but it is still the first option in the autoconf
+  ## Fortran macros.  We should avoid it, because mixing old versions of
+  ## g77 with modern gcc and g++ causes trouble.  The following will
+  ## make it harder (but not impossible) for users to make this mistake.
+  ##
+  ## FIXME -- we should really work to fix autoconf so that it prefers
+  ## gfortran over g77 even when searching for a Fortran 77 compiler.
+
+  echo "replacing all occurrences of g77 with gfortran in configure script..."
+
+  sed 's/g77/gfortran/g' configure > configure.t
+  mv configure.t configure
+  chmod 755 configure
+}
new file mode 100644
index 0000000000000000000000000000000000000000..f165d7eafe3c6b3523e8a822fa1862aed5119b07
GIT binary patch
literal 774
zc${rg%Wl&^6g|^C>^N?drX;jL11(UT010HnA_ytvp{gWxP@*nifyQB!x;S=l#z_4L
zK7b8d)@4x;i+%tfg}CDsqK0}g*K^M~ch0>tzkdHb1<*jlz#=Z|ST(SQD;ZqHH67~)
z#j=6xxS?Z1$EJ>(I&NvWtznBH{n+(g`Gg^1RrVQ@PlI=YA=h?&u@{XT5%#&`Q6@R!
zuFp`i-n0+-M_%{1Kdkp;==#H^5-#>6AH47I@fqLf1yMK<FI=_B*#o&ts#oDrO{q;R
zA;*x}ZSA+-?%18@8t#~|P|;8|aToUpQ@q+iFcK#2qo$#5;sG8qWMfhLS+~{SVOWl7
zp6i61YLB@*AS*Fr+qU~tPH__XH75w<9M71!V#v?BvYkUQkmpj<Mrm5&L&Uua)wJ64
zf@bCQdCk#8iV+Pqh^Sa`%6Ef$mr6-0DEO#J?F@zNhQU~bl3Z+A7fkp66vN5|)flv~
z+Ijw*zkk<+4Vd&q)VBbpE`ioO?bazWimB>%uw(k6$<msRlL=%{z{(l*Q!EAcs;6J@
zvYKcV7EX}(jOA}g7E(WuK7sZX4F%{kAoCYkQ-BczOA5$Nf#cYcI&%{`tr}8vY93jX
c$#8{?J|c9RTy#*vC1n+f@@kQ+6k}=W4~M0zR{#J2
new file mode 100644
--- /dev/null
+++ b/build-aux/OctJavaQry.java
@@ -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"));
+      }
+    }
+  }
+}
deleted file mode 100755
--- a/build-aux/bootstrap
+++ /dev/null
@@ -1,973 +0,0 @@
-#! /bin/sh
-# Print a version string.
-scriptversion=2011-08-11.17; # UTC
-
-# Bootstrap this package from checked-out sources.
-
-# Copyright (C) 2003-2012 Free Software Foundation, Inc.
-
-# 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/>.
-
-# Originally written by Paul Eggert.  The canonical version of this
-# script is maintained as build-aux/bootstrap in gnulib, however, to
-# be useful to your project, you should place a copy of it under
-# version control in the top-level directory of your project.  The
-# intent is that all customization can be done with a bootstrap.conf
-# file also maintained in your version control; gnulib comes with a
-# template build-aux/bootstrap.conf to get you started.
-
-# Please report bugs or propose patches to bug-gnulib@gnu.org.
-
-nl='
-'
-
-# Ensure file names are sorted consistently across platforms.
-LC_ALL=C
-export LC_ALL
-
-local_gl_dir=gl
-
-# Temporary directory names.
-bt='._bootmp'
-bt_regex=`echo "$bt"| sed 's/\./[.]/g'`
-bt2=${bt}2
-me=$0
-
-usage() {
-  cat <<EOF
-Usage: $me [OPTION]...
-Bootstrap this package from the checked-out sources.
-
-Options:
- --gnulib-srcdir=DIRNAME  specify the local directory where gnulib
-                          sources reside.  Use this if you already
-                          have gnulib sources on your machine, and
-                          do not want to waste your bandwidth downloading
-                          them again.  Defaults to \$GNULIB_SRCDIR
- --bootstrap-sync         if this bootstrap script is not identical to
-                          the version in the local gnulib sources,
-                          update this script, and then restart it with
-                          /bin/sh or the shell \$CONFIG_SHELL
- --no-bootstrap-sync      do not check whether bootstrap is out of sync
- --copy                   copy files instead of creating symbolic links
- --force                  attempt to bootstrap even if the sources seem
-                          not to have been checked out
- --no-git                 do not use git to update gnulib.  Requires that
-                          --gnulib-srcdir point to a correct gnulib snapshot
- --skip-po                do not download po files
-
-If the file $me.conf exists in the same directory as this script, its
-contents are read as shell variables to configure the bootstrap.
-
-For build prerequisites, environment variables like \$AUTOCONF and \$AMTAR
-are honored.
-
-Running without arguments will suffice in most cases.
-EOF
-}
-
-# Configuration.
-
-# Name of the Makefile.am
-gnulib_mk=gnulib.mk
-
-# List of gnulib modules needed.
-gnulib_modules=
-
-# Any gnulib files needed that are not in modules.
-gnulib_files=
-
-# A function to be called to edit gnulib.mk right after it's created.
-# Override it via your own definition in bootstrap.conf.
-gnulib_mk_hook() { :; }
-
-# A function to be called after everything else in this script.
-# Override it via your own definition in bootstrap.conf.
-bootstrap_epilogue() { :; }
-
-# The command to download all .po files for a specified domain into
-# a specified directory.  Fill in the first %s is the domain name, and
-# the second with the destination directory.  Use rsync's -L and -r
-# options because the latest/%s directory and the .po files within are
-# all symlinks.
-po_download_command_format=\
-"rsync --delete --exclude '*.s1' -Lrtvz \
- 'translationproject.org::tp/latest/%s/' '%s'"
-
-extract_package_name='
-  /^AC_INIT(/{
-     /.*,.*,.*, */{
-       s///
-       s/[][]//g
-       s/)$//
-       p
-       q
-     }
-     s/AC_INIT(\[*//
-     s/]*,.*//
-     s/^GNU //
-     y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/
-     s/[^A-Za-z0-9_]/-/g
-     p
-  }
-'
-package=`sed -n "$extract_package_name" configure.ac` || exit
-gnulib_name=lib$package
-
-build_aux=build-aux
-source_base=lib
-m4_base=m4
-doc_base=doc
-tests_base=tests
-gnulib_extra_files=''
-
-# Additional gnulib-tool options to use.  Use "\newline" to break lines.
-gnulib_tool_option_extras=
-
-# Other locale categories that need message catalogs.
-EXTRA_LOCALE_CATEGORIES=
-
-# Additional xgettext options to use.  Use "\\\newline" to break lines.
-XGETTEXT_OPTIONS='\\\
- --flag=_:1:pass-c-format\\\
- --flag=N_:1:pass-c-format\\\
- --flag=error:3:c-format --flag=error_at_line:5:c-format\\\
-'
-
-# Package bug report address and copyright holder for gettext files
-COPYRIGHT_HOLDER='Free Software Foundation, Inc.'
-MSGID_BUGS_ADDRESS=bug-$package@gnu.org
-
-# Files we don't want to import.
-excluded_files=
-
-# File that should exist in the top directory of a checked out hierarchy,
-# but not in a distribution tarball.
-checkout_only_file=README-hacking
-
-# Whether to use copies instead of symlinks.
-copy=false
-
-# Set this to '.cvsignore .gitignore' in bootstrap.conf if you want
-# those files to be generated in directories like lib/, m4/, and po/.
-# Or set it to 'auto' to make this script select which to use based
-# on which version control system (if any) is used in the source directory.
-vc_ignore=auto
-
-# Set this to true in bootstrap.conf to enable --bootstrap-sync by
-# default.
-bootstrap_sync=false
-
-# Don't use git to update gnulib sources. We keep gnulib under a
-# Mercurial subrepository instead
-use_git=false
-GNULIB_SRCDIR=gnulib-hg
-
-# find_tool ENVVAR NAMES...
-# -------------------------
-# Search for a required program.  Use the value of ENVVAR, if set,
-# otherwise find the first of the NAMES that can be run (i.e.,
-# supports --version).  If found, set ENVVAR to the program name,
-# die otherwise.
-find_tool ()
-{
-  find_tool_envvar=$1
-  shift
-  find_tool_names=$@
-  eval "find_tool_res=\$$find_tool_envvar"
-  if test x"$find_tool_res" = x; then
-    for i
-    do
-      if ($i --version </dev/null) >/dev/null 2>&1; then
-       find_tool_res=$i
-       break
-      fi
-    done
-  else
-    find_tool_error_prefix="\$$find_tool_envvar: "
-  fi
-  if test x"$find_tool_res" = x; then
-    echo >&2 "$me: one of these is required: $find_tool_names"
-    exit 1
-  fi
-  ($find_tool_res --version </dev/null) >/dev/null 2>&1 || {
-    echo >&2 "$me: ${find_tool_error_prefix}cannot run $find_tool_res --version"
-    exit 1
-  }
-  eval "$find_tool_envvar=\$find_tool_res"
-  eval "export $find_tool_envvar"
-}
-
-# Find sha1sum, named gsha1sum on MacPorts, and shasum on MacOS 10.6.
-find_tool SHA1SUM sha1sum gsha1sum shasum
-
-# Override the default configuration, if necessary.
-# Make sure that bootstrap.conf is sourced from the current directory
-# if we were invoked as "sh bootstrap".
-case "$0" in
-  */*) test -r "$0.conf" && . "$0.conf" ;;
-  *) test -r "$0.conf" && . ./"$0.conf" ;;
-esac
-
-# Extra files from gnulib, which override files from other sources.
-test -z "${gnulib_extra_files}" && \
-  gnulib_extra_files="
-        $build_aux/install-sh
-        $build_aux/missing
-        $build_aux/mdate-sh
-        $build_aux/texinfo.tex
-        $build_aux/depcomp
-        $build_aux/config.guess
-        $build_aux/config.sub
-        doc/INSTALL
-"
-
-if test "$vc_ignore" = auto; then
-  vc_ignore=
-  test -d .git && vc_ignore=.gitignore
-  test -d CVS && vc_ignore="$vc_ignore .cvsignore"
-fi
-
-# Translate configuration into internal form.
-
-# Parse options.
-
-for option
-do
-  case $option in
-  --help)
-    usage
-    exit;;
-  --gnulib-srcdir=*)
-    GNULIB_SRCDIR=`expr "X$option" : 'X--gnulib-srcdir=\(.*\)'`;;
-  --skip-po)
-    SKIP_PO=t;;
-  --force)
-    checkout_only_file=;;
-  --copy)
-    copy=true;;
-  --bootstrap-sync)
-    bootstrap_sync=true;;
-  --no-bootstrap-sync)
-    bootstrap_sync=false;;
-  --no-git)
-    use_git=false;;
-  *)
-    echo >&2 "$0: $option: unknown option"
-    exit 1;;
-  esac
-done
-
-if $use_git || test -d "$GNULIB_SRCDIR"; then
-  :
-else
-  echo "$0: Error: --no-git requires --gnulib-srcdir" >&2
-  exit 1
-fi
-
-if test -n "$checkout_only_file" && test ! -r "$checkout_only_file"; then
-  echo "$0: Bootstrapping from a non-checked-out distribution is risky." >&2
-  exit 1
-fi
-
-# Ensure that lines starting with ! sort last, per gitignore conventions
-# for whitelisting exceptions after a more generic blacklist pattern.
-sort_patterns() {
-  sort -u "$@" | sed '/^!/ {
-    H
-    d
-  }
-  $ {
-    P
-    x
-    s/^\n//
-  }' | sed '/^$/d'
-}
-
-# If $STR is not already on a line by itself in $FILE, insert it,
-# sorting the new contents of the file and replacing $FILE with the result.
-insert_sorted_if_absent() {
-  file=$1
-  str=$2
-  test -f $file || touch $file
-  echo "$str" | sort_patterns - $file | cmp - $file > /dev/null \
-    || { echo "$str" | sort_patterns - $file > $file.bak \
-      && mv $file.bak $file; } \
-    || exit 1
-}
-
-# Adjust $PATTERN for $VC_IGNORE_FILE and insert it with
-# insert_sorted_if_absent.
-insert_vc_ignore() {
-  vc_ignore_file="$1"
-  pattern="$2"
-  case $vc_ignore_file in
-  *.gitignore)
-    # A .gitignore entry that does not start with `/' applies
-    # recursively to subdirectories, so prepend `/' to every
-    # .gitignore entry.
-    pattern=`echo "$pattern" | sed s,^,/,`;;
-  esac
-  insert_sorted_if_absent "$vc_ignore_file" "$pattern"
-}
-
-# Die if there is no AC_CONFIG_AUX_DIR($build_aux) line in configure.ac.
-found_aux_dir=no
-grep '^[	 ]*AC_CONFIG_AUX_DIR(\['"$build_aux"'\])' configure.ac \
-    >/dev/null && found_aux_dir=yes
-grep '^[	 ]*AC_CONFIG_AUX_DIR('"$build_aux"')' configure.ac \
-    >/dev/null && found_aux_dir=yes
-if test $found_aux_dir = no; then
-  echo "$0: expected line not found in configure.ac. Add the following:" >&2
-  echo "  AC_CONFIG_AUX_DIR([$build_aux])" >&2
-  exit 1
-fi
-
-# If $build_aux doesn't exist, create it now, otherwise some bits
-# below will malfunction.  If creating it, also mark it as ignored.
-if test ! -d $build_aux; then
-  mkdir $build_aux
-  for dot_ig in x $vc_ignore; do
-    test $dot_ig = x && continue
-    insert_vc_ignore $dot_ig $build_aux
-  done
-fi
-
-# Note this deviates from the version comparison in automake
-# in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a
-# but this should suffice as we won't be specifying old
-# version formats or redundant trailing .0 in bootstrap.conf.
-# If we did want full compatibility then we should probably
-# use m4_version_compare from autoconf.
-sort_ver() { # sort -V is not generally available
-  ver1="$1"
-  ver2="$2"
-
-  # split on '.' and compare each component
-  i=1
-  while : ; do
-    p1=$(echo "$ver1" | cut -d. -f$i)
-    p2=$(echo "$ver2" | cut -d. -f$i)
-    if [ ! "$p1" ]; then
-      echo "$1 $2"
-      break
-    elif [ ! "$p2" ]; then
-      echo "$2 $1"
-      break
-    elif [ ! "$p1" = "$p2" ]; then
-      if [ "$p1" -gt "$p2" ] 2>/dev/null; then # numeric comparison
-        echo "$2 $1"
-      elif [ "$p2" -gt "$p1" ] 2>/dev/null; then # numeric comparison
-        echo "$1 $2"
-      else # numeric, then lexicographic comparison
-        lp=$(printf "$p1\n$p2\n" | LANG=C sort -n | tail -n1)
-        if [ "$lp" = "$p2" ]; then
-          echo "$1 $2"
-        else
-          echo "$2 $1"
-        fi
-      fi
-      break
-    fi
-    i=$(($i+1))
-  done
-}
-
-get_version() {
-  app=$1
-
-  $app --version >/dev/null 2>&1 || return 1
-
-  $app --version 2>&1 |
-  sed -n '# Move version to start of line.
-          s/.*[v ]\([0-9]\)/\1/
-
-          # Skip lines that do not start with version.
-          /^[0-9]/!d
-
-          # Remove characters after the version.
-          s/[^.a-z0-9-].*//
-
-          # The first component must be digits only.
-          s/^\([0-9]*\)[a-z-].*/\1/
-
-          #the following essentially does s/5.005/5.5/
-          s/\.0*\([1-9]\)/.\1/g
-          p
-          q'
-}
-
-check_versions() {
-  ret=0
-
-  while read app req_ver; do
-    # We only need libtoolize from the libtool package.
-    if test "$app" = libtool; then
-      app=libtoolize
-    fi
-    # Exempt git if --no-git is in effect.
-    if test "$app" = git; then
-      $use_git || continue
-    fi
-    # Honor $APP variables ($TAR, $AUTOCONF, etc.)
-    appvar=`echo $app | tr '[a-z]-' '[A-Z]_'`
-    test "$appvar" = TAR && appvar=AMTAR
-    case $appvar in
-        GZIP) ;; # Do not use $GZIP:  it contains gzip options.
-        *) eval "app=\${$appvar-$app}" ;;
-    esac
-    if [ "$req_ver" = "-" ]; then
-      # Merely require app to exist; not all prereq apps are well-behaved
-      # so we have to rely on $? rather than get_version.
-      $app --version >/dev/null 2>&1
-      if [ 126 -le $? ]; then
-        echo "$me: Error: '$app' not found" >&2
-        ret=1
-      fi
-    else
-      # Require app to produce a new enough version string.
-      inst_ver=$(get_version $app)
-      if [ ! "$inst_ver" ]; then
-        echo "$me: Error: '$app' not found" >&2
-        ret=1
-      else
-        latest_ver=$(sort_ver $req_ver $inst_ver | cut -d' ' -f2)
-        if [ ! "$latest_ver" = "$inst_ver" ]; then
-          echo "$me: Error: '$app' version == $inst_ver is too old" >&2
-          echo "       '$app' version >= $req_ver is required" >&2
-          ret=1
-        fi
-      fi
-    fi
-  done
-
-  return $ret
-}
-
-print_versions() {
-  echo "Program    Min_version"
-  echo "----------------------"
-  printf %s "$buildreq"
-  echo "----------------------"
-  # can't depend on column -t
-}
-
-use_libtool=0
-# We'd like to use grep -E, to see if any of LT_INIT,
-# AC_PROG_LIBTOOL, AM_PROG_LIBTOOL is used in configure.ac,
-# but that's not portable enough (e.g., for Solaris).
-grep '^[	 ]*A[CM]_PROG_LIBTOOL' configure.ac >/dev/null \
-  && use_libtool=1
-grep '^[	 ]*LT_INIT' configure.ac >/dev/null \
-  && use_libtool=1
-if test $use_libtool = 1; then
-  find_tool LIBTOOLIZE glibtoolize libtoolize
-fi
-
-if ! printf "$buildreq" | check_versions; then
-  echo >&2
-  if test -f README-prereq; then
-    echo "$0: See README-prereq for how to get the prerequisite programs" >&2
-  else
-    echo "$0: Please install the prerequisite programs" >&2
-  fi
-  exit 1
-fi
-
-echo "$0: Bootstrapping from checked-out $package sources..."
-
-# See if we can use gnulib's git-merge-changelog merge driver.
-if test -d .git && (git --version) >/dev/null 2>/dev/null ; then
-  if git config merge.merge-changelog.driver >/dev/null ; then
-    :
-  elif (git-merge-changelog --version) >/dev/null 2>/dev/null ; then
-    echo "$0: initializing git-merge-changelog driver"
-    git config merge.merge-changelog.name 'GNU-style ChangeLog merge driver'
-    git config merge.merge-changelog.driver 'git-merge-changelog %O %A %B'
-  else
-    echo "$0: consider installing git-merge-changelog from gnulib"
-  fi
-fi
-
-
-cleanup_gnulib() {
-  status=$?
-  rm -fr "$gnulib_path"
-  exit $status
-}
-
-git_modules_config () {
-  test -f .gitmodules && git config --file .gitmodules "$@"
-}
-
-gnulib_path=`git_modules_config submodule.gnulib.path`
-test -z "$gnulib_path" && gnulib_path=gnulib
-
-# Get gnulib files.
-
-case ${GNULIB_SRCDIR--} in
--)
-  if git_modules_config submodule.gnulib.url >/dev/null; then
-    echo "$0: getting gnulib files..."
-    git submodule init || exit $?
-    git submodule update || exit $?
-
-  elif [ ! -d "$gnulib_path" ]; then
-    echo "$0: getting gnulib files..."
-
-    trap cleanup_gnulib 1 2 13 15
-
-    shallow=
-    git clone -h 2>&1 | grep -- --depth > /dev/null && shallow='--depth 2'
-    git clone $shallow git://git.sv.gnu.org/gnulib "$gnulib_path" ||
-      cleanup_gnulib
-
-    trap - 1 2 13 15
-  fi
-  GNULIB_SRCDIR=$gnulib_path
-  ;;
-*)
-  # Use GNULIB_SRCDIR as a reference.
-  if test -d "$GNULIB_SRCDIR"/.git && \
-        git_modules_config submodule.gnulib.url >/dev/null; then
-    echo "$0: getting gnulib files..."
-    if git submodule -h|grep -- --reference > /dev/null; then
-      # Prefer the one-liner available in git 1.6.4 or newer.
-      git submodule update --init --reference "$GNULIB_SRCDIR" \
-        "$gnulib_path" || exit $?
-    else
-      # This fallback allows at least git 1.5.5.
-      if test -f "$gnulib_path"/gnulib-tool; then
-        # Since file already exists, assume submodule init already complete.
-        git submodule update || exit $?
-      else
-        # Older git can't clone into an empty directory.
-        rmdir "$gnulib_path" 2>/dev/null
-        git clone --reference "$GNULIB_SRCDIR" \
-          "$(git_modules_config submodule.gnulib.url)" "$gnulib_path" \
-          && git submodule init && git submodule update \
-          || exit $?
-      fi
-    fi
-    GNULIB_SRCDIR=$gnulib_path
-  fi
-  ;;
-esac
-
-if $bootstrap_sync; then
-  cmp -s "$0" "$GNULIB_SRCDIR/build-aux/bootstrap" || {
-    echo "$0: updating bootstrap and restarting..."
-    exec sh -c \
-      'cp "$1" "$2" && shift && exec "${CONFIG_SHELL-/bin/sh}" "$@"' \
-      -- "$GNULIB_SRCDIR/build-aux/bootstrap" \
-      "$0" "$@" --no-bootstrap-sync
-  }
-fi
-
-gnulib_tool=$GNULIB_SRCDIR/gnulib-tool
-<$gnulib_tool || exit
-
-# Get translations.
-
-download_po_files() {
-  subdir=$1
-  domain=$2
-  echo "$me: getting translations into $subdir for $domain..."
-  cmd=`printf "$po_download_command_format" "$domain" "$subdir"`
-  eval "$cmd"
-}
-
-# Mirror .po files to $po_dir/.reference and copy only the new
-# or modified ones into $po_dir.  Also update $po_dir/LINGUAS.
-# Note po files that exist locally only are left in $po_dir but will
-# not be included in LINGUAS and hence will not be distributed.
-update_po_files() {
-  # Directory containing primary .po files.
-  # Overwrite them only when we're sure a .po file is new.
-  po_dir=$1
-  domain=$2
-
-  # Mirror *.po files into this dir.
-  # Usually contains *.s1 checksum files.
-  ref_po_dir="$po_dir/.reference"
-
-  test -d $ref_po_dir || mkdir $ref_po_dir || return
-  download_po_files $ref_po_dir $domain \
-    && ls "$ref_po_dir"/*.po 2>/dev/null |
-      sed 's|.*/||; s|\.po$||' > "$po_dir/LINGUAS" || return
-
-  langs=`cd $ref_po_dir && echo *.po|sed 's/\.po//g'`
-  test "$langs" = '*' && langs=x
-  for po in $langs; do
-    case $po in x) continue;; esac
-    new_po="$ref_po_dir/$po.po"
-    cksum_file="$ref_po_dir/$po.s1"
-    if ! test -f "$cksum_file" ||
-        ! test -f "$po_dir/$po.po" ||
-        ! $SHA1SUM -c --status "$cksum_file" \
-            < "$new_po" > /dev/null; then
-      echo "$me: updated $po_dir/$po.po..."
-      cp "$new_po" "$po_dir/$po.po" \
-          && $SHA1SUM < "$new_po" > "$cksum_file"
-    fi
-  done
-}
-
-case $SKIP_PO in
-'')
-  if test -d po; then
-    update_po_files po $package || exit
-  fi
-
-  if test -d runtime-po; then
-    update_po_files runtime-po $package-runtime || exit
-  fi;;
-esac
-
-symlink_to_dir()
-{
-  src=$1/$2
-  dst=${3-$2}
-
-  test -f "$src" && {
-
-    # If the destination directory doesn't exist, create it.
-    # This is required at least for "lib/uniwidth/cjk.h".
-    dst_dir=`dirname "$dst"`
-    if ! test -d "$dst_dir"; then
-      mkdir -p "$dst_dir"
-
-      # If we've just created a directory like lib/uniwidth,
-      # tell version control system(s) it's ignorable.
-      # FIXME: for now, this does only one level
-      parent=`dirname "$dst_dir"`
-      for dot_ig in x $vc_ignore; do
-        test $dot_ig = x && continue
-        ig=$parent/$dot_ig
-        insert_vc_ignore $ig `echo "$dst_dir"|sed 's,.*/,,'`
-      done
-    fi
-
-    if $copy; then
-      {
-        test ! -h "$dst" || {
-          echo "$me: rm -f $dst" &&
-          rm -f "$dst"
-        }
-      } &&
-      test -f "$dst" &&
-      cmp -s "$src" "$dst" || {
-        echo "$me: cp -fp $src $dst" &&
-        cp -fp "$src" "$dst"
-      }
-    else
-      # Leave any existing symlink alone, if it already points to the source,
-      # so that broken build tools that care about symlink times
-      # aren't confused into doing unnecessary builds.  Conversely, if the
-      # existing symlink's time stamp is older than the source, make it afresh,
-      # so that broken tools aren't confused into skipping needed builds.  See
-      # <http://lists.gnu.org/archive/html/bug-gnulib/2011-05/msg00326.html>.
-      test -h "$dst" &&
-      src_ls=`ls -diL "$src" 2>/dev/null` && set $src_ls && src_i=$1 &&
-      dst_ls=`ls -diL "$dst" 2>/dev/null` && set $dst_ls && dst_i=$1 &&
-      test "$src_i" = "$dst_i" &&
-      both_ls=`ls -dt "$src" "$dst"` &&
-      test "X$both_ls" = "X$dst$nl$src" || {
-        dot_dots=
-        case $src in
-        /*) ;;
-        *)
-          case /$dst/ in
-          *//* | */../* | */./* | /*/*/*/*/*/)
-             echo >&2 "$me: invalid symlink calculation: $src -> $dst"
-             exit 1;;
-          /*/*/*/*/)	dot_dots=../../../;;
-          /*/*/*/)	dot_dots=../../;;
-          /*/*/)	dot_dots=../;;
-          esac;;
-        esac
-
-        echo "$me: ln -fs $dot_dots$src $dst" &&
-        ln -fs "$dot_dots$src" "$dst"
-      }
-    fi
-  }
-}
-
-cp_mark_as_generated()
-{
-  cp_src=$1
-  cp_dst=$2
-
-  if cmp -s "$cp_src" "$GNULIB_SRCDIR/$cp_dst"; then
-    symlink_to_dir "$GNULIB_SRCDIR" "$cp_dst"
-  elif cmp -s "$cp_src" "$local_gl_dir/$cp_dst"; then
-    symlink_to_dir $local_gl_dir "$cp_dst"
-  else
-    case $cp_dst in
-      *.[ch])             c1='/* '; c2=' */';;
-      *.texi)             c1='@c '; c2=     ;;
-      *.m4|*/Make*|Make*) c1='# ' ; c2=     ;;
-      *)                  c1=     ; c2=     ;;
-    esac
-
-    # If the destination directory doesn't exist, create it.
-    # This is required at least for "lib/uniwidth/cjk.h".
-    dst_dir=`dirname "$cp_dst"`
-    test -d "$dst_dir" || mkdir -p "$dst_dir"
-
-    if test -z "$c1"; then
-      cmp -s "$cp_src" "$cp_dst" || {
-        # Copy the file first to get proper permissions if it
-        # doesn't already exist.  Then overwrite the copy.
-        echo "$me: cp -f $cp_src $cp_dst" &&
-        rm -f "$cp_dst" &&
-        cp "$cp_src" "$cp_dst-t" &&
-        sed "s!$bt_regex/!!g" "$cp_src" > "$cp_dst-t" &&
-        mv -f "$cp_dst-t" "$cp_dst"
-      }
-    else
-      # Copy the file first to get proper permissions if it
-      # doesn't already exist.  Then overwrite the copy.
-      cp "$cp_src" "$cp_dst-t" &&
-      (
-        echo "$c1-*- buffer-read-only: t -*- vi: set ro:$c2" &&
-        echo "${c1}DO NOT EDIT! GENERATED AUTOMATICALLY!$c2" &&
-        sed "s!$bt_regex/!!g" "$cp_src"
-      ) > $cp_dst-t &&
-      if cmp -s "$cp_dst-t" "$cp_dst"; then
-        rm -f "$cp_dst-t"
-      else
-        echo "$me: cp $cp_src $cp_dst # with edits" &&
-        mv -f "$cp_dst-t" "$cp_dst"
-      fi
-    fi
-  fi
-}
-
-version_controlled_file() {
-  dir=$1
-  file=$2
-  found=no
-  if test -d CVS; then
-    grep -F "/$file/" $dir/CVS/Entries 2>/dev/null |
-             grep '^/[^/]*/[0-9]' > /dev/null && found=yes
-  elif test -d .git; then
-    git rm -n "$dir/$file" > /dev/null 2>&1 && found=yes
-  elif test -d .svn; then
-    svn log -r HEAD "$dir/$file" > /dev/null 2>&1 && found=yes
-  else
-    echo "$me: no version control for $dir/$file?" >&2
-  fi
-  test $found = yes
-}
-
-slurp() {
-  for dir in . `(cd $1 && find * -type d -print)`; do
-    copied=
-    sep=
-    for file in `ls -a $1/$dir`; do
-      case $file in
-      .|..) continue;;
-      # FIXME: should all file names starting with "." be ignored?
-      .*) continue;;
-      esac
-      test -d $1/$dir/$file && continue
-      for excluded_file in $excluded_files; do
-        test "$dir/$file" = "$excluded_file" && continue 2
-      done
-      if test $file = Makefile.am && test "X$gnulib_mk" != XMakefile.am; then
-        copied=$copied${sep}$gnulib_mk; sep=$nl
-        remove_intl='/^[^#].*\/intl/s/^/#/;'"s!$bt_regex/!!g"
-        sed "$remove_intl" $1/$dir/$file |
-        cmp - $dir/$gnulib_mk > /dev/null || {
-          echo "$me: Copying $1/$dir/$file to $dir/$gnulib_mk ..." &&
-          rm -f $dir/$gnulib_mk &&
-          sed "$remove_intl" $1/$dir/$file >$dir/$gnulib_mk &&
-          gnulib_mk_hook $dir/$gnulib_mk
-        }
-      elif { test "${2+set}" = set && test -r $2/$dir/$file; } ||
-           version_controlled_file $dir $file; then
-        echo "$me: $dir/$file overrides $1/$dir/$file"
-      else
-        copied=$copied$sep$file; sep=$nl
-        cp_mark_as_generated $1/$dir/$file $dir/$file
-      fi || exit
-    done
-
-    for dot_ig in x $vc_ignore; do
-      test $dot_ig = x && continue
-      ig=$dir/$dot_ig
-      if test -n "$copied"; then
-        insert_vc_ignore $ig "$copied"
-        # If an ignored file name ends with .in.h, then also add
-        # the name with just ".h".  Many gnulib headers are generated,
-        # e.g., stdint.in.h -> stdint.h, dirent.in.h ->..., etc.
-        # Likewise for .gperf -> .h, .y -> .c, and .sin -> .sed
-        f=`echo "$copied" |
-          sed '
-            s/\.in\.h$/.h/
-            s/\.sin$/.sed/
-            s/\.y$/.c/
-            s/\.gperf$/.h/
-          '
-        `
-        insert_vc_ignore $ig "$f"
-
-        # For files like sys_stat.in.h and sys_time.in.h, record as
-        # ignorable the directory we might eventually create: sys/.
-        f=`echo "$copied"|sed 's/sys_.*\.in\.h$/sys/'`
-        insert_vc_ignore $ig "$f"
-      fi
-    done
-  done
-}
-
-
-# Create boot temporary directories to import from gnulib and gettext.
-rm -fr $bt $bt2 &&
-mkdir $bt $bt2 || exit
-
-# Import from gnulib.
-
-gnulib_tool_options="\
- --import\
- --no-changelog\
- --aux-dir $bt/$build_aux\
- --doc-base $bt/$doc_base\
- --lib $gnulib_name\
- --m4-base $bt/$m4_base/\
- --source-base $bt/$source_base/\
- --tests-base $bt/$tests_base\
- --local-dir $local_gl_dir\
- $gnulib_tool_option_extras\
-"
-if test $use_libtool = 1; then
-  case "$gnulib_tool_options " in
-    *' --libtool '*) ;;
-    *) gnulib_tool_options="$gnulib_tool_options --libtool" ;;
-  esac
-fi
-echo "$0: $gnulib_tool $gnulib_tool_options --import ..."
-$gnulib_tool $gnulib_tool_options --import $gnulib_modules &&
-slurp $bt || exit
-
-for file in $gnulib_files; do
-  symlink_to_dir "$GNULIB_SRCDIR" $file || exit
-done
-
-
-# Import from gettext.
-with_gettext=yes
-grep '^[	 ]*AM_GNU_GETTEXT_VERSION(' configure.ac >/dev/null || \
-    with_gettext=no
-
-if test $with_gettext = yes; then
-  echo "$0: (cd $bt2; ${AUTOPOINT-autopoint}) ..."
-  cp configure.ac $bt2 &&
-  (cd $bt2 && ${AUTOPOINT-autopoint} && rm configure.ac) &&
-  slurp $bt2 $bt || exit
-fi
-rm -fr $bt $bt2 || exit
-
-# Remove any dangling symlink matching "*.m4" or "*.[ch]" in some
-# gnulib-populated directories.  Such .m4 files would cause aclocal to fail.
-# The following requires GNU find 4.2.3 or newer.  Considering the usual
-# portability constraints of this script, that may seem a very demanding
-# requirement, but it should be ok.  Ignore any failure, which is fine,
-# since this is only a convenience to help developers avoid the relatively
-# unusual case in which a symlinked-to .m4 file is git-removed from gnulib
-# between successive runs of this script.
-find "$m4_base" "$source_base" \
-  -depth \( -name '*.m4' -o -name '*.[ch]' \) \
-  -type l -xtype l -delete > /dev/null 2>&1
-
-# Reconfigure, getting other files.
-
-# Skip autoheader if it's not needed.
-grep -E '^[	 ]*AC_CONFIG_HEADERS?\>' configure.ac >/dev/null ||
-  AUTOHEADER=true
-
-for command in \
-  libtool \
-  "${ACLOCAL-aclocal} --force -I '$m4_base' $ACLOCAL_FLAGS" \
-  "${AUTOCONF-autoconf} --force" \
-  "${AUTOHEADER-autoheader} --force" \
-  "${AUTOMAKE-automake} --add-missing --copy --force-missing"
-do
-  if test "$command" = libtool; then
-    test $use_libtool = 0 \
-      && continue
-    command="${LIBTOOLIZE-libtoolize} -c -f"
-  fi
-  echo "$0: $command ..."
-  eval "$command" || exit
-done
-
-
-# Get some extra files from gnulib, overriding existing files.
-for file in $gnulib_extra_files; do
-  case $file in
-  */INSTALL) dst=INSTALL;;
-  build-aux/*) dst=$build_aux/`expr "$file" : 'build-aux/\(.*\)'`;;
-  *) dst=$file;;
-  esac
-  symlink_to_dir "$GNULIB_SRCDIR" $file $dst || exit
-done
-
-if test $with_gettext = yes; then
-  # Create gettext configuration.
-  echo "$0: Creating po/Makevars from po/Makevars.template ..."
-  rm -f po/Makevars
-  sed '
-    /^EXTRA_LOCALE_CATEGORIES *=/s/=.*/= '"$EXTRA_LOCALE_CATEGORIES"'/
-    /^COPYRIGHT_HOLDER *=/s/=.*/= '"$COPYRIGHT_HOLDER"'/
-    /^MSGID_BUGS_ADDRESS *=/s|=.*|= '"$MSGID_BUGS_ADDRESS"'|
-    /^XGETTEXT_OPTIONS *=/{
-      s/$/ \\/
-      a\
-          '"$XGETTEXT_OPTIONS"' $${end_of_xgettext_options+}
-    }
-  ' po/Makevars.template >po/Makevars || exit 1
-
-  if test -d runtime-po; then
-    # Similarly for runtime-po/Makevars, but not quite the same.
-    rm -f runtime-po/Makevars
-    sed '
-      /^DOMAIN *=.*/s/=.*/= '"$package"'-runtime/
-      /^subdir *=.*/s/=.*/= runtime-po/
-      /^MSGID_BUGS_ADDRESS *=/s/=.*/= bug-'"$package"'@gnu.org/
-      /^XGETTEXT_OPTIONS *=/{
-        s/$/ \\/
-        a\
-            '"$XGETTEXT_OPTIONS_RUNTIME"' $${end_of_xgettext_options+}
-      }
-    ' po/Makevars.template >runtime-po/Makevars || exit 1
-
-    # Copy identical files from po to runtime-po.
-    (cd po && cp -p Makefile.in.in *-quot *.header *.sed *.sin ../runtime-po)
-  fi
-fi
-
-bootstrap_epilogue
-
-echo "$0: done.  Now you can run './configure'."
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "scriptversion="
-# time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
-# time-stamp-end: "; # UTC"
-# End:
--- a/build-aux/common.mk
+++ b/build-aux/common.mk
@@ -3,12 +3,15 @@
 AWK = @AWK@
 export AWK
 
-SED = @SED@
-export SED
+GREP = @GREP@
+export GREP
 
 FIND = @FIND@
 export FIND
 
+SED = @SED@
+export SED
+
 PERL = @PERL@
 export PERL
 
@@ -41,6 +44,7 @@
 
 YACC = @YACC@
 AM_YFLAGS = -dv
+BISON_PUSH_PULL_DECL_STYLE = @BISON_PUSH_PULL_DECL_STYLE@
 
 GPERF = @GPERF@
 
@@ -53,6 +57,7 @@
 RANLIB = @RANLIB@
 
 LN_S = @LN_S@
+MKDIR_P = @MKDIR_P@
 
 MAKEINFO = @MAKEINFO@
 TEXI2DVI = @TEXI2DVI@
@@ -62,6 +67,9 @@
 
 DEFAULT_PAGER = @DEFAULT_PAGER@
 
+DEFAULT_TERMINAL_FONT = @DEFAULT_TERMINAL_FONT@
+DEFAULT_TERMINAL_FONT_SIZE = @DEFAULT_TERMINAL_FONT_SIZE@
+
 ENABLE_DYNAMIC_LINKING = @ENABLE_DYNAMIC_LINKING@
 
 SHLEXT = @SHLEXT@
@@ -84,41 +92,27 @@
 F77 = @F77@
 AM_FFLAGS = @FFLAGS@
 FPICFLAG = @FPICFLAG@
-ALL_FFLAGS = $(FFLAGS)
 F77_FLOAT_STORE_FLAG = @F77_FLOAT_STORE_FLAG@
 F77_INTEGER_8_FLAG = @F77_INTEGER_8_FLAG@
+ALL_FFLAGS = $(FFLAGS)
 
 F77_TOLOWER=@F77_TOLOWER@
 F77_APPEND_UNDERSCORE=@F77_TOLOWER@
 F77_APPEND_EXTRA_UNDERSCORE=@F77_TOLOWER@
 
-X11_INCFLAGS = @X11_INCFLAGS@
-X11_LIBS = @X11_LIBS@
-
-CARBON_LIBS = @CARBON_LIBS@
-
-MAGICK_CPPFLAGS = @MAGICK_CPPFLAGS@
-MAGICK_LDFLAGS = @MAGICK_LDFLAGS@
-MAGICK_LIBS = @MAGICK_LIBS@
+F77_ISNAN_MACRO=@F77_ISNAN_MACRO@
 
-PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
-PTHREAD_LIBS = @PTHREAD_LIBS@
-
-LIBFLAGS = -L$(top_builddir)
-
-DEFS = @DEFS@
-
-UGLY_DEFS = @UGLY_DEFS@
+# C compiler flags.
 
 CC = @CC@
+## FIXME: CC_VERSION is deprecated and should be removed in version 3.12
 CC_VERSION = @CC_VERSION@
-CONFIGURE_CFLAGS = @CFLAGS@
+GCC_VERSION = @GCC_VERSION@
 CPICFLAG = @CPICFLAG@
 XTRA_CFLAGS = @XTRA_CFLAGS@
 WARN_CFLAGS = @WARN_CFLAGS@
-AM_CFLAGS = $(CONFIGURE_CFLAGS) \
-  $(INCFLAGS) $(DEFS) $(XTRA_CFLAGS) $(WARN_CFLAGS) $(CFLAGS) $(PTHREAD_CFLAGS)
-BUG_CFLAGS = $(DEFS) $(XTRA_CFLAGS) $(WARN_CFLAGS) $(CFLAGS)
+AM_CFLAGS = $(XTRA_CFLAGS)
+ALL_CPPFLAGS = $(CPPFLAGS) $(HDF5_CPPFLAGS) $(Z_CPPFLAGS) $(LLVM_CPPFLAGS)
 
 BUILD_CC = @BUILD_CC@
 BUILD_CFLAGS = @BUILD_CFLAGS@
@@ -126,30 +120,32 @@
 DEPEND_FLAGS = @DEPEND_FLAGS@
 DEPEND_EXTRA_SED_PATTERN = @DEPEND_EXTRA_SED_PATTERN@
 INCLUDE_DEPS = @INCLUDE_DEPS@
-# ifeq ($(INCLUDE_DEPS),false)
+# ifeq ($(INCLUDE_DEPS),no)
 #   omit_deps = true;
 # endif
 
-GRAPHICS_CFLAGS = @GRAPHICS_CFLAGS@
+DEFS = @DEFS@
+
+# C++ compiler flags.
 
 CXX = @CXX@
+## FIXME: CXX_VERSION is deprecated and should be removed in version 3.12
 CXX_VERSION = @CXX_VERSION@
+GXX_VERSION = @GXX_VERSION@
 CXXCPP = @CXXCPP@
-CONFIGURE_CXXFLAGS = @CXXFLAGS@
 CXXPICFLAG = @CXXPICFLAG@
 XTRA_CXXFLAGS = @XTRA_CXXFLAGS@
 WARN_CXXFLAGS = @WARN_CXXFLAGS@
-AM_CXXFLAGS = $(CONFIGURE_CXXFLAGS) \
-  $(INCFLAGS) $(DEFS) $(XTRA_CXXFLAGS) $(WARN_CXXFLAGS) $(CXXFLAGS) $(PTHREAD_CFLAGS)
-BUG_CXXFLAGS = $(DEFS) $(XTRA_CXXFLAGS) $(WARN_CXXFLAGS) $(CXXFLAGS)
+AM_CXXFLAGS = $(XTRA_CXXFLAGS)
 
 BUILD_CXX = @BUILD_CXX@
 BUILD_CXXFLAGS = @BUILD_CXXFLAGS@
 
-NO_UNDEFINED_LDFLAG = @NO_UNDEFINED_LDFLAG@
+# Linker and library flags
 
 LD_CXX = @LD_CXX@
 LD_STATIC_FLAG = @LD_STATIC_FLAG@
+LIBFLAGS = -L$(top_builddir)
 #ALL_LDFLAGS = $(LIBFLAGS) $(LD_STATIC_FLAG) $(CPICFLAG) $(LDFLAGS)
 
 BUILD_LDFLAGS = @BUILD_LDFLAGS@
@@ -164,7 +160,7 @@
 
 RDYNAMIC_FLAG = @RDYNAMIC_FLAG@
 
-FLIBS = @FLIBS@
+NO_UNDEFINED_LDFLAG = @NO_UNDEFINED_LDFLAG@
 
 MKOCTFILE_AR = @MKOCTFILE_AR@
 MKOCTFILE_CC = @MKOCTFILE_CC@
@@ -179,54 +175,27 @@
 
 LIBOCTINTERP = @LIBOCTINTERP@
 LIBOCTAVE = @LIBOCTAVE@
-LIBCRUFT = @LIBCRUFT@
 
-FT2_CFLAGS = @FT2_CFLAGS@
-FT2_LIBS = @FT2_LIBS@
-
-HDF5_CPPFLAGS = @HDF5_CPPFLAGS@
-HDF5_LDFLAGS = @HDF5_LDFLAGS@
-HDF5_LIBS = @HDF5_LIBS@
-
-Z_CPPFLAGS = @Z_CPPFLAGS@
-Z_LDFLAGS = @Z_LDFLAGS@
-Z_LIBS = @Z_LIBS@
-
-GRAPHICS_LIBS = @GRAPHICS_LIBS@
-
-QHULL_CPPFLAGS = @QHULL_CPPFLAGS@
-QHULL_LDFLAGS = @QHULL_LDFLAGS@
-QHULL_LIBS = @QHULL_LIBS@
-
-REGEX_LIBS = @REGEX_LIBS@
-
-LAPACK_LIBS = @LAPACK_LIBS@
-BLAS_LIBS = @BLAS_LIBS@
-
-FFTW3_CPPFLAGS = @FFTW3_CPPFLAGS@
-FFTW3_LDFLAGS = @FFTW3_LDFLAGS@
-FFTW3_LIBS = @FFTW3_LIBS@
-
-FFTW3F_CPPFLAGS = @FFTW3F_CPPFLAGS@
-FFTW3F_LDFLAGS = @FFTW3F_LDFLAGS@
-FFTW3F_LIBS = @FFTW3F_LIBS@
-
-GLPK_CPPFLAGS = @GLPK_CPPFLAGS@
-GLPK_LDFLAGS = @GLPK_LDFLAGS@
-GLPK_LIBS = @GLPK_LIBS@
-
-CURL_CPPFLAGS = @CURL_CPPFLAGS@
-CURL_LDFLAGS = @CURL_LDFLAGS@
-CURL_LIBS = @CURL_LIBS@
+DL_LIBS = @DL_LIBS@
+FLIBS = @FLIBS@
+LIBS = @LIBS@
 
 AMD_CPPFLAGS = @AMD_CPPFLAGS@
 AMD_LDFLAGS = @AMD_LDFLAGS@
 AMD_LIBS = @AMD_LIBS@
 
+ARPACK_CPPFLAGS = @ARPACK_CPPFLAGS@
+ARPACK_LDFLAGS = @ARPACK_LDFLAGS@
+ARPACK_LIBS = @ARPACK_LIBS@
+
+BLAS_LIBS = @BLAS_LIBS@
+
 CAMD_CPPFLAGS = @CAMD_CPPFLAGS@
 CAMD_LDFLAGS = @CAMD_LDFLAGS@
 CAMD_LIBS = @CAMD_LIBS@
 
+CARBON_LIBS = @CARBON_LIBS@
+
 COLAMD_CPPFLAGS = @COLAMD_CPPFLAGS@
 COLAMD_LDFLAGS = @COLAMD_LDFLAGS@
 COLAMD_LIBS = @COLAMD_LIBS@
@@ -239,31 +208,69 @@
 CHOLMOD_LDFLAGS = @CHOLMOD_LDFLAGS@
 CHOLMOD_LIBS = @CHOLMOD_LIBS@
 
+CURL_CPPFLAGS = @CURL_CPPFLAGS@
+CURL_LDFLAGS = @CURL_LDFLAGS@
+CURL_LIBS = @CURL_LIBS@
+
 CXSPARSE_CPPFLAGS = @CXSPARSE_CPPFLAGS@
 CXSPARSE_LDFLAGS = @CXSPARSE_LDFLAGS@
 CXSPARSE_LIBS = @CXSPARSE_LIBS@
 
-UMFPACK_CPPFLAGS = @UMFPACK_CPPFLAGS@
-UMFPACK_LDFLAGS = @UMFPACK_LDFLAGS@
-UMFPACK_LIBS = @UMFPACK_LIBS@
+FFTW3_CPPFLAGS = @FFTW3_CPPFLAGS@
+FFTW3_LDFLAGS = @FFTW3_LDFLAGS@
+FFTW3_LIBS = @FFTW3_LIBS@
+
+FFTW3F_CPPFLAGS = @FFTW3F_CPPFLAGS@
+FFTW3F_LDFLAGS = @FFTW3F_LDFLAGS@
+FFTW3F_LIBS = @FFTW3F_LIBS@
+
+FFTW_XCPPFLAGS = $(FFTW3_CPPFLAGS) $(FFTW3F_CPPFLAGS)
+FFTW_XLDFLAGS = $(FFTW3_LDFLAGS) $(FFTW3F_LDFLAGS)
+FFTW_XLIBS = $(FFTW3_LIBS) $(FFTW3F_LIBS)
+
+FT2_CFLAGS = @FT2_CFLAGS@
+FT2_LIBS = @FT2_LIBS@
+
+GLPK_CPPFLAGS = @GLPK_CPPFLAGS@
+GLPK_LDFLAGS = @GLPK_LDFLAGS@
+GLPK_LIBS = @GLPK_LIBS@
+
+GRAPHICS_CFLAGS = @GRAPHICS_CFLAGS@
+GRAPHICS_LIBS = @GRAPHICS_LIBS@
+
+HDF5_CPPFLAGS = @HDF5_CPPFLAGS@
+HDF5_LDFLAGS = @HDF5_LDFLAGS@
+HDF5_LIBS = @HDF5_LIBS@
+
+JAVA_CPPFLAGS = @JAVA_CPPFLAGS@
+JAVA_LIBS = @JAVA_LIBS@
+
+LAPACK_LIBS = @LAPACK_LIBS@
+
+LLVM_CPPFLAGS = @LLVM_CPPFLAGS@
+LLVM_LDFLAGS = @LLVM_LDFLAGS@
+LLVM_LIBS = @LLVM_LIBS@
+
+MAGICK_CPPFLAGS = @MAGICK_CPPFLAGS@
+MAGICK_LDFLAGS = @MAGICK_LDFLAGS@
+MAGICK_LIBS = @MAGICK_LIBS@
 
 OPENGL_LIBS = @OPENGL_LIBS@
 
+PTHREAD_CFLAGS = @PTHREAD_CFLAGS@
+PTHREAD_LIBS = @PTHREAD_LIBS@
+
+QHULL_CPPFLAGS = @QHULL_CPPFLAGS@
+QHULL_LDFLAGS = @QHULL_LDFLAGS@
+QHULL_LIBS = @QHULL_LIBS@
+
 QRUPDATE_CPPFLAGS = @QRUPDATE_CPPFLAGS@
 QRUPDATE_LDFLAGS = @QRUPDATE_LDFLAGS@
 QRUPDATE_LIBS = @QRUPDATE_LIBS@
 
-READLINE_LIBS = @READLINE_LIBS@
-TERM_LIBS = @TERM_LIBS@
+REGEX_LIBS = @REGEX_LIBS@
 
-ARPACK_CPPFLAGS = @ARPACK_CPPFLAGS@
-ARPACK_LDFLAGS = @ARPACK_LDFLAGS@
-ARPACK_LIBS = @ARPACK_LIBS@
-
-DL_LIBS = @DL_LIBS@
-LIBS = @LIBS@
-
-ALL_CPPFLAGS = $(CPPFLAGS) $(HDF5_CPPFLAGS) $(Z_CPPFLAGS)
+READLINE_LIBS = @READLINE_LIBS@
 
 SPARSE_XCPPFLAGS = \
   $(CHOLMOD_CPPFLAGS) $(UMFPACK_CPPFLAGS) \
@@ -277,15 +284,24 @@
 
 ## Order matters, at least on some systems (Cygwin, for example).
 SPARSE_XLIBS = \
-    $(CHOLMOD_LIBS) $(UMFPACK_LIBS) \
-    $(AMD_LIBS) $(CAMD_LIBS) $(COLAMD_LIBS) \
-    $(CCOLAMD_LIBS) $(CXSPARSE_LIBS)
+  $(CHOLMOD_LIBS) $(UMFPACK_LIBS) \
+  $(AMD_LIBS) $(CAMD_LIBS) $(COLAMD_LIBS) \
+  $(CCOLAMD_LIBS) $(CXSPARSE_LIBS)
+
+TERM_LIBS = @TERM_LIBS@
 
-FFTW_XCPPFLAGS = $(FFTW3_CPPFLAGS) $(FFTW3F_CPPFLAGS)
+UMFPACK_CPPFLAGS = @UMFPACK_CPPFLAGS@
+UMFPACK_LDFLAGS = @UMFPACK_LDFLAGS@
+UMFPACK_LIBS = @UMFPACK_LIBS@
 
-FFTW_XLDFLAGS = $(FFTW3_LDFLAGS) $(FFTW3F_LDFLAGS)
+X11_INCFLAGS = @X11_INCFLAGS@
+X11_LIBS = @X11_LIBS@
 
-FFTW_XLIBS = $(FFTW3_LIBS) $(FFTW3F_LIBS)
+Z_CPPFLAGS = @Z_CPPFLAGS@
+Z_LDFLAGS = @Z_LDFLAGS@
+Z_LIBS = @Z_LIBS@
+
+# Miscellaneous
 
 USE_64_BIT_IDX_T = @USE_64_BIT_IDX_T@
 OCTAVE_IDX_TYPE = @OCTAVE_IDX_TYPE@
@@ -332,7 +348,10 @@
 # Where to install and expect extra files like NEWS and doc-cache.
 octetcdir = @octetcdir@
 
-# Where to install and expect libraries like libcruft.a, liboctave.a,
+# Where to install and expect the language files for the gui.
+octlocaledir = @octlocaledir@
+
+# Where to install and expect libraries like liboctave.a, liboctinterp.a,
 # and other architecture-dependent data.
 octlibdir = @octlibdir@
 
@@ -350,9 +369,15 @@
 man1dir = @man1dir@
 man1ext = @man1ext@
 
+# Where to install test files.
+octtestsdir = @octtestsdir@
+
 # The full path to the default doc cache file.
 doc_cache_file = @doc_cache_file@
 
+# The full path to the default texi macros file.
+texi_macros_file_file = @texi_macros_file@
+
 # Where to install and expect the info files describing Octave..
 infodir = @infodir@
 
@@ -431,6 +456,8 @@
 
 NO_OCT_FILE_STRIP = @NO_OCT_FILE_STRIP@
 
+# ==================== Octave-specific Makefile rules ====================
+
 # The following pattern rules and the substitution functions require
 # GNU make.  If you don't have it, get it!
 
@@ -451,13 +478,13 @@
 fi
 endef
 
-# Yes, the second sed command near the end is needed, to avoid limits
-# in command lengths for some versions of sed.  UGLY_DEFS is often
-# quite large, so it makes sense to split this command there.
+## To avoid shell command line limits, break the replacement patterns
+## into two roughly equal sized parts.
 
 define do_subst_config_vals
 echo "making $@ from $<"
 $(SED) < $< \
+  -e "s|%NO_EDIT_WARNING%|DO NOT EDIT!  Generated automatically from $(<F) by Make.|" \
   -e "s|%NO_OCT_FILE_STRIP%|${NO_OCT_FILE_STRIP}|" \
   -e "s|%OCTAVE_BINDIR%|\"${bindir}\"|" \
   -e "s|%OCTAVE_CONF_ALL_CFLAGS%|\"${ALL_CFLAGS}\"|" \
@@ -504,12 +531,16 @@
   -e "s|%OCTAVE_CONF_CXXPICFLAG%|\"${CXXPICFLAG}\"|" \
   -e "s|%OCTAVE_CONF_CXX_VERSION%|\"${CXX_VERSION}\"|" \
   -e "s|%OCTAVE_CONF_DEFAULT_PAGER%|\"${DEFAULT_PAGER}\"|" \
+  -e "s|%OCTAVE_CONF_DEFS%|\"${DEFS}\"|" \
   -e "s|%OCTAVE_CONF_DEPEND_FLAGS%|\"${DEPEND_FLAGS}\"|" \
   -e "s|%OCTAVE_CONF_DEPEND_EXTRA_SED_PATTERN%|\"${DEPEND_EXTRA_SED_PATTERN}\"|" \
   -e "s|%OCTAVE_CONF_DL_LD%|\"${DL_LD}\"|" \
   -e "s|%OCTAVE_CONF_DL_LDFLAGS%|\"${DL_LDFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_DL_LIBS%|\"${DL_LIBS}\"|" \
+  -e "s|%OCTAVE_CONF_ENABLE_DYNAMIC_LINKING%|\"${ENABLE_DYNAMIC_LINKING}\"|" \
   -e "s|%OCTAVE_CONF_EXEEXT%|\"${EXEEXT}\"|" \
+  -e "s|%OCTAVE_CONF_GCC_VERSION%|\"${GCC_VERSION}\"|" \
+  -e "s|%OCTAVE_CONF_GXX_VERSION%|\"${GXX_VERSION}\"|" \
   -e "s|%OCTAVE_CONF_F77%|\"${F77}\"|" \
   -e "s|%OCTAVE_CONF_F77_FLOAT_STORE_FLAG%|\"${F77_FLOAT_STORE_FLAG}\"|" \
   -e "s|%OCTAVE_CONF_F77_INTEGER_8_FLAG%|\"${F77_INTEGER_8_FLAG}\"|" \
@@ -523,16 +554,17 @@
   -e "s|%OCTAVE_CONF_FFTW3F_LIBS%|\"${FFTW3F_LIBS}\"|" \
   -e "s|%OCTAVE_CONF_FLIBS%|\"${FLIBS}\"|" \
   -e "s|%OCTAVE_CONF_FPICFLAG%|\"${FPICFLAG}\"|" \
+  -e "s|%OCTAVE_CONF_FT2_CFLAGS%|\"${FT2_CFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_FT2_LIBS%|\"${FT2_LIBS}\"|" \
   -e "s|%OCTAVE_CONF_GLPK_CPPFLAGS%|\"${GLPK_CPPFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_GLPK_LDFLAGS%|\"${GLPK_LDFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_GLPK_LIBS%|\"${GLPK_LIBS}\"|" \
   -e "s|%OCTAVE_CONF_GNUPLOT%|\"${GNUPLOT}\"|" \
+  -e "s|%OCTAVE_CONF_GRAPHICS_CFLAGS%|\"${GRAPHICS_CFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_GRAPHICS_LIBS%|\"${GRAPHICS_LIBS}\"|" \
-  -e "s|%OCTAVE_CONF_HDF5_CPPFLAGS%|\"${HDF5_CPPFLAGS}\"|" \
-  -e "s|%OCTAVE_CONF_HDF5_LDFLAGS%|\"${HDF5_LDFLAGS}\"|" \
+  -e "s|%OCTAVE_CONF_HDF5_CPPFLAGS%|\"${HDF5_CPPFLAGS}\"|" | \
+  $(SED) -e "s|%OCTAVE_CONF_HDF5_LDFLAGS%|\"${HDF5_LDFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_HDF5_LIBS%|\"${HDF5_LIBS}\"|" \
-  -e "s|%OCTAVE_CONF_INCFLAGS%|\"${INCFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_INCLUDEDIR%|\"${includedir}\"|" \
   -e "s|%OCTAVE_CONF_LAPACK_LIBS%|\"${LAPACK_LIBS}\"|" \
   -e "s|%OCTAVE_CONF_LD_CXX%|\"${LD_CXX}\"|" \
@@ -541,13 +573,15 @@
   -e "s|%OCTAVE_CONF_LEX%|\"${LEX}\"|" \
   -e "s|%OCTAVE_CONF_LEXLIB%|\"${LEXLIB}\"|" \
   -e "s|%OCTAVE_CONF_LFLAGS%|\"${LFLAGS}\"|" \
-  -e "s|%OCTAVE_CONF_LIBCRUFT%|\"${LIBCRUFT}\"|" \
   -e "s|%OCTAVE_CONF_LIBDIR%|\"${libdir}\"|" \
   -e "s|%OCTAVE_CONF_LIBEXT%|\"${LIBEXT}\"|" \
   -e "s|%OCTAVE_CONF_LIBFLAGS%|\"${LIBFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_LIBOCTAVE%|\"${LIBOCTAVE}\"|" \
   -e "s|%OCTAVE_CONF_LIBOCTINTERP%|\"${LIBOCTINTERP}\"|" \
   -e "s|%OCTAVE_CONF_LIBS%|\"${LIBS}\"|" \
+  -e "s|%OCTAVE_CONF_LLVM_CPPFLAGS%|\"${LLVM_CPPFLAGS}\"|" \
+  -e "s|%OCTAVE_CONF_LLVM_LDFLAGS%|\"${LLVM_LDFLAGS}\"|" \
+  -e "s|%OCTAVE_CONF_LLVM_LIBS%|\"${LLVM_LIBS}\"|" \
   -e "s|%OCTAVE_CONF_LN_S%|\"${LN_S}\"|" \
   -e "s|%OCTAVE_CONF_MAGICK_CPPFLAGS%|\"${MAGICK_CPPFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_MAGICK_LDFLAGS%|\"${MAGICK_LDFLAGS}\"|" \
@@ -576,6 +610,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_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}\"|" \
@@ -590,13 +627,13 @@
   -e "s|%OCTAVE_CONF_SONAME_FLAGS%|\"${SONAME_FLAGS}\"|" \
   -e "s|%OCTAVE_CONF_STATIC_LIBS%|\"${STATIC_LIBS}\"|" \
   -e "s|%OCTAVE_CONF_TERM_LIBS%|\"${TERM_LIBS}\"|" \
-  -e "s|%OCTAVE_CONF_UGLY_DEFS%|\"${UGLY_DEFS}\"|" \
   -e "s|%OCTAVE_CONF_UMFPACK_CPPFLAGS%|\"${UMFPACK_CPPFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_UMFPACK_LDFLAGS%|\"${UMFPACK_LDFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_UMFPACK_LIBS%|\"${UMFPACK_LIBS}\"|" \
   -e "s|%OCTAVE_CONF_USE_64_BIT_IDX_T%|\"${USE_64_BIT_IDX_T}\"|" \
   -e "s|%OCTAVE_CONF_VERSION%|\"${version}\"|" \
-  -e "s|%OCTAVE_CONF_ENABLE_DYNAMIC_LINKING%|\"${ENABLE_DYNAMIC_LINKING}\"|" \
+  -e "s|%OCTAVE_CONF_WARN_CFLAGS%|\"${WARN_CFLAGS}\"|" \
+  -e "s|%OCTAVE_CONF_WARN_CXXFLAGS%|\"${WARN_CXXFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_X11_INCFLAGS%|\"${X11_INCFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_X11_LIBS%|\"${X11_LIBS}\"|" \
   -e "s|%OCTAVE_CONF_XTRA_CFLAGS%|\"${XTRA_CFLAGS}\"|" \
@@ -606,14 +643,14 @@
   -e "s|%OCTAVE_CONF_Z_CPPFLAGS%|\"${Z_CPPFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_Z_LDFLAGS%|\"${Z_LDFLAGS}\"|" \
   -e "s|%OCTAVE_CONF_Z_LIBS%|\"${Z_LIBS}\"|" \
-  -e "s|%OCTAVE_CONF_config_opts%|\"${config_opts}\"|" | \
-  $(SED)  -e "s|%OCTAVE_CONF_DEFS%|\"${UGLY_DEFS}\"|" > $@-t
+  -e "s|%OCTAVE_CONF_config_opts%|\"${config_opts}\"|" > $@-t
 $(simple_move_if_change_rule)
 endef
 
 define do_subst_default_vals
 echo "making $@ from $<"
 $(SED) < $< > $@-t \
+  -e "s|%NO_EDIT_WARNING%|DO NOT EDIT!  Generated automatically from $(<F) by Make.|" \
   -e "s|%OCTAVE_ARCHLIBDIR%|\"${archlibdir}\"|" \
   -e "s|%OCTAVE_BINDIR%|\"${bindir}\"|" \
   -e "s|%OCTAVE_CANONICAL_HOST_TYPE%|\"${canonical_host_type}\"|" \
@@ -646,10 +683,13 @@
   -e "s|%OCTAVE_OCTETCDIR%|\"${octetcdir}\"|" \
   -e "s|%OCTAVE_OCTINCLUDEDIR%|\"${octincludedir}\"|" \
   -e "s|%OCTAVE_OCTLIBDIR%|\"${octlibdir}\"|" \
+  -e "s|%OCTAVE_OCTLOCALEDIR%|\"${octlocaledir}\"|" \
+  -e "s|%OCTAVE_OCTTESTSDIR%|\"${octtestsdir}\"|" \
   -e "s|%OCTAVE_STARTUPFILEDIR%|\"${startupfiledir}\"|" \
   -e "s|%OCTAVE_PREFIX%|\"${prefix}\"|" \
   -e "s|%OCTAVE_API_VERSION%|\"${api_version}\"|" \
   -e "s|%OCTAVE_RELEASE%|\"${OCTAVE_RELEASE}\"|" \
+  -e "s|%OCTAVE_TEXI_MACROS_FILE%|\"${texi_macros_file}\"|" \
   -e "s|%OCTAVE_VERSION%|\"${version}\"|"
 $(simple_move_if_change_rule)
 endef
@@ -660,37 +700,29 @@
   -e "s|%AWK%|${AWK}|g" \
   -e "s|%FIND%|${FIND}|g" \
   -e "s|%SED%|${SED}|g" \
-  -e "s|%library_path_var%|${library_path_var}|g" \
-  -e "s|%liboctinterp%|${SHLPRE}octinterp.${SHLEXT}|g" \
-  -e "s|%liboctave%|${SHLPRE}octave.${SHLEXT}|g" \
-  -e "s|%libcruft%|${SHLPRE}cruft.${SHLEXT}|g" \
-  -e "s|%ldpreloadsep%|${ldpreloadsep}|g" \
-  -e "s|%srcdir%|${srcdir}|" \
-  -e "s|%top_srcdir%|${top_srcdir}|" \
   -e "s|%abs_top_srcdir%|${abs_top_srcdir}|" \
   -e "s|%builddir%|$(shell pwd)|" > $@-t
 $(simple_move_if_change_rule)
 endef
 
-define do_script_install
-$(top_srcdir)/build-aux/mkinstalldirs $(DESTDIR)$(fcnfiledir)/$(script_sub_dir)
-for f in $(FCN_FILES); do \
-  fbase=`basename $$f`; \
-  rm -f $(DESTDIR)$(fcnfiledir)/$(script_sub_dir)/$$fbase; \
-  $(INSTALL_DATA) $$f $(DESTDIR)$(fcnfiledir)/$(script_sub_dir)/$$fbase; \
-done
-$(top_srcdir)/mkpkgadd $(DESTDIR)$(fcnfiledir)/$(script_sub_dir) > $(DESTDIR)$(fcnfiledir)/$(script_sub_dir)/PKG_ADD.t
-if [ -n "`cat $(DESTDIR)$(fcnfiledir)/$(script_sub_dir)/PKG_ADD.t`" ]; then \
-  $(INSTALL_DATA) $(DESTDIR)$(fcnfiledir)/$(script_sub_dir)/PKG_ADD.t $(DESTDIR)$(fcnfiledir)/$(script_sub_dir)/PKG_ADD ; \
-else \
-  rm -f $(DESTDIR)$(fcnfiledir)/$(script_sub_dir)/PKG_ADD.t ; \
-fi
+define do_subst_qt_settings
+echo "making $@ from $<"
+$(SED) < $< \
+  -e "s|%DEFAULT_TERMINAL_FONT%|${DEFAULT_TERMINAL_FONT}|" \
+  -e "s|%DEFAULT_TERMINAL_FONT_SIZE%|${DEFAULT_TERMINAL_FONT_SIZE}|" > $@-t
+$(simple_move_if_change_rule)
 endef
 
-define do_script_uninstall
-for f in $(FCN_FILES_NO_DIR); \
-  do rm -f $(DESTDIR)$(fcnfiledir)/$(script_sub_dir)/$$f; \
-done
-rm -f $(DESTDIR)$(fcnfiledir)/$(script_sub_dir)/PKG_ADD
--rmdir $(DESTDIR)$(fcnfiledir)/$(script_sub_dir)
+define test-file-commands
+( echo "## DO NOT EDIT!  Generated automatically from $(<F) by Make."; $(GREP) '^%!' $< ) > $@-t
+mv $@-t $@
 endef
+
+%.cc-tst : %.cc
+	$(test-file-commands)
+
+%.yy-tst : %.yy
+	$(test-file-commands)
+
+%.ll-tst : %.ll
+	$(test-file-commands)
new file mode 100755
--- /dev/null
+++ b/build-aux/find-files-with-tests.sh
@@ -0,0 +1,20 @@
+#! /bin/sh
+
+set -e
+GREP=${GREP:-grep}
+SED=${SED:-sed}
+
+srcdir="$1"
+shift
+
+for arg
+do
+  if [ -f "$arg" ]; then
+    file="$arg"
+  else
+    file="$srcdir/$arg"
+  fi
+  if [ "`$GREP -l '^%!' $file`" ]; then
+    echo "$file" | $SED "s,\\$srcdir/,,";
+  fi
+done
--- a/build-aux/mk-opts.pl
+++ b/build-aux/mk-opts.pl
@@ -513,7 +513,7 @@
 
 #include "$header"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "pr-output.h"
 
 #include "oct-obj.h"
@@ -909,11 +909,11 @@
 sub emit_options_function
 {
   print <<"_END_EMIT_OPTIONS_FUNCTION_HDR_";
-DEFUN_DLD ($OPT_FCN_NAME, args, ,
+DEFUN ($OPT_FCN_NAME, args, ,
   "-*- texinfo -*-\\n\\
-\@deftypefn  {Loadable Function} {} $OPT_FCN_NAME ()\\n\\
-\@deftypefnx {Loadable Function} {val =} $OPT_FCN_NAME (\@var{opt})\\n\\
-\@deftypefnx {Loadable Function} {} $OPT_FCN_NAME (\@var{opt}, \@var{val})\\n\\
+\@deftypefn  {Built-in Function} {} $OPT_FCN_NAME ()\\n\\
+\@deftypefnx {Built-in Function} {val =} $OPT_FCN_NAME (\@var{opt})\\n\\
+\@deftypefnx {Built-in Function} {} $OPT_FCN_NAME (\@var{opt}, \@var{val})\\n\\
 $DOC_STRING\\n\\
 \\n\\
 Options include\\n\\
--- a/configure.ac
+++ b/configure.ac
@@ -1,5 +1,3 @@
-dnl configure.in
-dnl
 dnl Process this file with autoconf to produce a configure script.
 dnl
 dnl Copyright (C) 1993-2012 John W. Eaton
@@ -20,20 +18,14 @@
 ### along with Octave; see the file COPYING.  If not, see
 ### <http://www.gnu.org/licenses/>.
 
-### Preserve CFLAGS and CXXFLAGS from the environment before doing
-### anything else because we don't know which macros might call
-### AC_PROG_CC or AC_PROG_CXX.
-
-EXTERN_CFLAGS="$CFLAGS"
-EXTERN_CXXFLAGS="$CXXFLAGS"
-
-AC_INIT([GNU Octave], [3.6.4], [http://octave.org/bugs.html], [octave])
+AC_PREREQ([2.62])
+AC_INIT([GNU Octave], [3.7.3+], [http://octave.org/bugs.html], [octave])
 
 dnl PACKAGE_VERSION is set by the AC_INIT VERSION arg
 OCTAVE_VERSION="$PACKAGE_VERSION"
 OCTAVE_API_VERSION_NUMBER="48"
 OCTAVE_API_VERSION="api-v$OCTAVE_API_VERSION_NUMBER+"
-OCTAVE_RELEASE_DATE="2013-02-21"
+OCTAVE_RELEASE_DATE="2013-04-22"
 OCTAVE_COPYRIGHT="Copyright (C) 2013 John W. Eaton and others."
 AC_SUBST(OCTAVE_VERSION)
 AC_SUBST(OCTAVE_API_VERSION_NUMBER)
@@ -41,66 +33,128 @@
 AC_SUBST(OCTAVE_RELEASE_DATE)
 AC_SUBST(OCTAVE_COPYRIGHT)
 
-AC_REVISION($Revision: 1.603 $)
-AC_PREREQ([2.62])
-AC_CONFIG_SRCDIR([src/octave.cc])
-AC_CONFIG_HEADER([config.h])
+dnl FIXME: We should auto-insert the Mercurial changeset ID into the
+dnl        AC_REVISION field whenever configure.ac is modified.
+dnl AC_REVISION($Revision: 1.603 $)
+AC_CONFIG_SRCDIR([libinterp/octave.cc])
+AC_CONFIG_HEADERS([config.h:config.in.h])
 AC_CONFIG_AUX_DIR([build-aux])
 AC_CONFIG_MACRO_DIR([m4])
 
 AM_INIT_AUTOMAKE([1.11 tar-ustar])
 
-OCTAVE_HOST_TYPE
-
-AC_DEFINE(OCTAVE_SOURCE, 1, [Define if this is Octave.])
+OCTAVE_CANONICAL_HOST
+
+AC_DEFINE(OCTAVE_SOURCE, 1, [Define to 1 if this is Octave.])
   
-dnl FIXME -- we should probably only generate this file if it is missing.
-### Produce unistd.h for MSVC target, this simplifies changes in
-### Octave source tree and avoid problems with lex-generated code.
-case "$canonical_host_type" in
-  *-*-msdosmsvc)
-    AC_MSG_NOTICE([Generating replacement for <unistd.h> for MSVC])
-    cat << \EOF > unistd.h
-/* File generated by configure script. */
-#include <direct.h>
-#include <io.h>
-#include <process.h>
-EOF
-    CPPFLAGS="-I. $CPPFLAGS"
-    ;;
-esac
-
 AC_USE_SYSTEM_EXTENSIONS
 
-### Check for MSVC
-have_msvc=no
-case "$canonical_host_type" in
-  *-*-msdosmsvc)
-    have_msvc=yes
+### Make configure args available for other uses.
+
+config_opts=$ac_configure_args
+AC_SUBST(config_opts)
+
+### Set default file locations
+
+OCTAVE_SET_DEFAULT([octlibdir], '$(libdir)/octave/$(version)')
+OCTAVE_SET_DEFAULT([archlibdir],
+  '$(libexecdir)/octave/$(version)/exec/$(canonical_host_type)')
+OCTAVE_SET_DEFAULT([localarchlibdir],
+  '$(libexecdir)/octave/site/exec/$(canonical_host_type)')
+OCTAVE_SET_DEFAULT([localapiarchlibdir],
+  '$(libexecdir)/octave/$(api_version)/site/exec/$(canonical_host_type)')
+OCTAVE_SET_DEFAULT([localverarchlibdir],
+  '$(libexecdir)/octave/$(version)/site/exec/$(canonical_host_type)')
+OCTAVE_SET_DEFAULT([octfiledir],
+  '$(libdir)/octave/$(version)/oct/$(canonical_host_type)')
+OCTAVE_SET_DEFAULT([localoctfiledir],
+  '$(libdir)/octave/site/oct/$(canonical_host_type)')
+OCTAVE_SET_DEFAULT([localapioctfiledir],
+  '$(libdir)/octave/site/oct/$(api_version)/$(canonical_host_type)')
+OCTAVE_SET_DEFAULT([localveroctfiledir],
+  '$(libdir)/octave/$(version)/site/oct/$(canonical_host_type)')
+OCTAVE_SET_DEFAULT([octincludedir], '$(includedir)/octave-$(version)/octave')
+OCTAVE_SET_DEFAULT([fcnfiledir], '$(datadir)/octave/$(version)/m')
+OCTAVE_SET_DEFAULT([localfcnfiledir], '$(datadir)/octave/site/m')
+OCTAVE_SET_DEFAULT([localapifcnfiledir],
+  '$(datadir)/octave/site/$(api_version)/m')
+OCTAVE_SET_DEFAULT([localverfcnfiledir], '$(datadir)/octave/$(version)/site/m')
+OCTAVE_SET_DEFAULT([octetcdir], '$(datadir)/octave/$(version)/etc')
+OCTAVE_SET_DEFAULT([octlocaledir], '$(datadir)/octave/$(version)/locale')
+OCTAVE_SET_DEFAULT([doc_cache_file], '$(octetcdir)/doc-cache')
+OCTAVE_SET_DEFAULT([octtestsdir], '$(octetcdir)/tests')
+OCTAVE_SET_DEFAULT([texi_macros_file], '$(octetcdir)/macros.texi')
+OCTAVE_SET_DEFAULT([imagedir], '$(datadir)/octave/$(version)/imagelib')
+OCTAVE_SET_DEFAULT([man1dir], '$(mandir)/man1')
+OCTAVE_SET_DEFAULT([man1ext], '.1')
+OCTAVE_SET_DEFAULT([infofile], '$(infodir)/octave.info')
+
+### Check for programs used in building, installing, and running Octave.
+
+## Programs used in configuring Octave.
+## Find pkg-config executable (sets $PKG_CONFIG)
+PKG_PROG_PKG_CONFIG
+
+## Programs used in Makefiles.
+AC_PROG_AWK
+AC_PROG_GREP
+OCTAVE_PROG_FIND
+OCTAVE_PROG_SED
+OCTAVE_PROG_PERL
+
+## Programs used to build parts of Octave.
+OCTAVE_PROG_GPERF
+
+OCTAVE_PROG_FLEX
+AC_SUBST([LEX_OUTPUT_ROOT], [lex.octave_])
+
+OCTAVE_PROG_BISON
+
+OCTAVE_PROG_MAKEINFO
+OCTAVE_PROG_TEXI2DVI
+OCTAVE_PROG_TEXI2PDF
+
+## Programs used when installing Octave.
+AC_PROG_LN_S
+AC_PROG_MKDIR_P
+
+AC_PROG_INSTALL
+INSTALL_SCRIPT='${INSTALL}'
+AC_SUBST(INSTALL_SCRIPT)
+
+OCTAVE_PROG_DESKTOP_FILE_INSTALL
+
+## Programs used when running Octave
+OCTAVE_PROG_GHOSTSCRIPT
+OCTAVE_PROG_GNUPLOT
+OCTAVE_PROG_PAGER
+OCTAVE_PROG_PYTHON
+
+### Default terminal font for the GUI
+case $host_os in
+  mingw* | msdosmsvc)
+    DEFAULT_TERMINAL_FONT="Lucida Console"
   ;;
-  *-*-mingw*)
-    AC_MSG_CHECKING([for MSVC compiler])
-    AC_PREPROC_IFELSE([AC_LANG_SOURCE([
-#ifndef _MSC_VER
-#error "Not MSVC compiler"
-#endif
-])], have_msvc=yes, have_msvc=no)
-    AC_MSG_RESULT([$have_msvc])
+  *)
+    DEFAULT_TERMINAL_FONT="Courier"
   ;;
 esac
+DEFAULT_TERMINAL_FONT_SIZE=10
+AC_SUBST(DEFAULT_TERMINAL_FONT)
+AC_SUBST(DEFAULT_TERMINAL_FONT_SIZE)
 
 ### Path separator.
-sepchar=:
-AC_ARG_WITH(sepchar,
+
+sepchar=':'
+AC_ARG_WITH([sepchar],
   [AS_HELP_STRING([--with-sepchar=<char>],
-     [use <char> as the path separation character])])
+    [use <char> as the path separation character])])
 case $with_sepchar in
   yes | "")
-    case "$canonical_host_type" in
-      *-*-mingw* | *-*-msdosmsvc)
-        sepchar=';'
-        ;;
-      esac
+    case $host_os in
+      mingw* | msdosmsvc)
+        sepchar=';' ;;
+    esac
     ;;
   no)
     AC_MSG_ERROR([You are required to define a path separation character])
@@ -110,128 +164,113 @@
     ;;
 esac
 AC_SUBST(sepchar)
-AC_DEFINE_UNQUOTED(SEPCHAR, ['$sepchar'], [Define this to be the path separator for your system, as a character constant.])
-AC_DEFINE_UNQUOTED(SEPCHAR_STR, ["$sepchar"], [Define this to the path separator, as a string.])
-
-### some defaults
-
-OCTAVE_SET_DEFAULT(man1dir, '$(mandir)/man1')
-OCTAVE_SET_DEFAULT(man1ext, '.1')
-OCTAVE_SET_DEFAULT(doc_cache_file, '$(octetcdir)/doc-cache')
-OCTAVE_SET_DEFAULT(infofile, '$(infodir)/octave.info')
-OCTAVE_SET_DEFAULT(octincludedir, '$(includedir)/octave-$(version)/octave')
-OCTAVE_SET_DEFAULT(fcnfiledir, '$(datadir)/octave/$(version)/m')
-OCTAVE_SET_DEFAULT(localfcnfiledir, '$(datadir)/octave/site/m')
-OCTAVE_SET_DEFAULT(localapifcnfiledir,
-  '$(datadir)/octave/site/$(api_version)/m')
-OCTAVE_SET_DEFAULT(localverfcnfiledir, '$(datadir)/octave/$(version)/site/m')
-OCTAVE_SET_DEFAULT(octetcdir, '$(datadir)/octave/$(version)/etc')
-OCTAVE_SET_DEFAULT(octlibdir, '$(libdir)/octave/$(version)')
-OCTAVE_SET_DEFAULT(archlibdir,
-  '$(libexecdir)/octave/$(version)/exec/$(canonical_host_type)')
-OCTAVE_SET_DEFAULT(localarchlibdir,
-  '$(libexecdir)/octave/site/exec/$(canonical_host_type)')
-OCTAVE_SET_DEFAULT(localapiarchlibdir,
-  '$(libexecdir)/octave/$(api_version)/site/exec/$(canonical_host_type)')
-OCTAVE_SET_DEFAULT(localverarchlibdir,
-  '$(libexecdir)/octave/$(version)/site/exec/$(canonical_host_type)')
-OCTAVE_SET_DEFAULT(octfiledir,
-  '$(libdir)/octave/$(version)/oct/$(canonical_host_type)')
-OCTAVE_SET_DEFAULT(localoctfiledir,
-  '$(libdir)/octave/site/oct/$(canonical_host_type)')
-OCTAVE_SET_DEFAULT(localapioctfiledir,
-  '$(libdir)/octave/site/oct/$(api_version)/$(canonical_host_type)')
-OCTAVE_SET_DEFAULT(localveroctfiledir,
-  '$(libdir)/octave/$(version)/site/oct/$(canonical_host_type)')
-OCTAVE_SET_DEFAULT(imagedir, '$(datadir)/octave/$(version)/imagelib')
-
-### Find pkg-config executable (sets $PKG_CONFIG)
-
-PKG_PROG_PKG_CONFIG
-
-### Make configure args available for other uses.
-
-config_opts=$ac_configure_args
-AC_SUBST(config_opts)
-
-### Make it possible to have Octave's array and matrix classes do bounds
-### checking on element references.  This slows some operations down a
-### bit, so it is turned off by default.
-
-BOUNDS_CHECKING=false
-AC_ARG_ENABLE(bounds-check,
+AC_DEFINE_UNQUOTED(SEPCHAR, ['$sepchar'],
+  [Define this to be the path separator for your system, as a character constant.])
+AC_DEFINE_UNQUOTED(SEPCHAR_STR, ["$sepchar"],
+  [Define this to be the path separator for your system, as a string.])
+
+### 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.
+
+BOUNDS_CHECKING=no
+AC_ARG_ENABLE([bounds-check],
   [AS_HELP_STRING([--enable-bounds-check],
-     [bounds checking for indexing in internal array classes (default is no)])],
-  [if test "$enableval" = yes; then BOUNDS_CHECKING=true; fi], [])
-if $BOUNDS_CHECKING; then
-  AC_DEFINE(BOUNDS_CHECKING, 1, [Define to use internal bounds checking.])
+    [enable bounds checking for indexing in internal array classes])],
+  [if test "$enableval" = yes; then BOUNDS_CHECKING=yes; fi], [])
+if test $BOUNDS_CHECKING = yes; then
+  AC_DEFINE(BOUNDS_CHECKING, 1, [Define to 1 to use internal bounds checking.])
 fi
 
-USE_OCTAVE_ALLOCATOR=false
-AC_ARG_ENABLE(octave-allocator,
+### Use Octave's built-in memory allocator rather than straightforward malloc.
+### Disabled by default.
+
+USE_OCTAVE_ALLOCATOR=no
+AC_ARG_ENABLE([octave-allocator],
   [AS_HELP_STRING([--enable-octave-allocator],
-     [use the obsolete octave_allocator class for many of Octave's objects (mostly octave_value types).  You probably do NOT want to enable this feature.  (default is no)])],
-  [if test "$enableval" = yes; then USE_OCTAVE_ALLOCATOR=true; fi], [])
-if $USE_OCTAVE_ALLOCATOR; then
-  AC_DEFINE(USE_OCTAVE_ALLOCATOR, 1, [Define to use octave_allocator class.])
+    [use the obsolete octave_allocator class for many of Octave's objects (mostly octave_value types).  You probably do NOT want to enable this feature.])],
+  [if test "$enableval" = yes; then USE_OCTAVE_ALLOCATOR=yes; fi], [])
+if test $USE_OCTAVE_ALLOCATOR = yes; then
+  AC_DEFINE(USE_OCTAVE_ALLOCATOR, 1,
+    [Define to 1 to use octave_allocator class.])
 fi
 
-USE_ATOMIC_REFCOUNT=false
-AC_ARG_ENABLE(atomic-refcount,
+### Use atomic operations for internal reference counting.  This is required
+### for thread-safe behavior but incurs a significant slowdown, and is thus
+### disabled by default.
+
+USE_ATOMIC_REFCOUNT=no
+AC_ARG_ENABLE([atomic-refcount],
   [AS_HELP_STRING([--enable-atomic-refcount],
-     [use atomic operations for internal reference counting. This is required for thread-safe behavior.  (default is no)])],
-  [if test "$enableval" = yes; then USE_ATOMIC_REFCOUNT=true; fi], [])
-if $USE_ATOMIC_REFCOUNT; then
-  AC_DEFINE(USE_ATOMIC_REFCOUNT, 1, [Define to use atomic operations for reference counting.])
+    [use atomic operations for internal reference counting.  This is required for thread-safe behavior but does not by itself make Octave internals thread safe.])],
+  [if test "$enableval" = yes; then USE_ATOMIC_REFCOUNT=yes; fi], [])
+if test $USE_ATOMIC_REFCOUNT = yes; then
+  AC_DEFINE(USE_ATOMIC_REFCOUNT, 1,
+    [Define to 1 to use atomic operations for reference counting.])
 fi
 
-### Make it possible to disable running Make in the doc directory.
-### Useful for building on systems without TeX, for example.
+### Disable running Make in the doc directory.
+### This is useful, for example, when building Octave on systems without TeX.
+
 DOCDIR=doc
-AC_ARG_ENABLE(docs,
-  [AS_HELP_STRING([--enable-docs], [build documentation (default is yes)])],
+AC_ARG_ENABLE([docs],
+  [AS_HELP_STRING([--disable-docs], [don't build documentation files])],
   [if test "$enableval" = no; then
      DOCDIR=
      warn_docs="building documentation disabled; make dist will fail"
-     AC_MSG_WARN([$warn_docs])
-   fi], [])
+     OCTAVE_CONFIGURE_WARNING([warn_docs])
+   fi],
+  [])
 AC_SUBST(DOCDIR)
-AM_CONDITIONAL([AMCOND_BUILD_DOCS], [test -n "$DOCDIR"])
 
 ### If possible, use a 64-bit integer type for array dimensions and indexing.
 
-USE_64_BIT_IDX_T=false
+USE_64_BIT_IDX_T=no
 OCTAVE_IDX_TYPE=int
 AC_ARG_ENABLE(64,
   [AS_HELP_STRING([--enable-64],
-     [(EXPERIMENTAL) use 64-bit integers for array dimensions and indexing])],
-  [if test "$enableval" = yes; then USE_64_BIT_IDX_T=true; fi], [])
-if $USE_64_BIT_IDX_T; then
-  AC_CHECK_SIZEOF(void *)
-  AC_CHECK_SIZEOF(int)
-  AC_CHECK_SIZEOF(long)
+    [(EXPERIMENTAL) use 64-bit integers for array dimensions and indexing])],
+  [if test "$enableval" = yes; then USE_64_BIT_IDX_T=yes; fi], [])
+if test $USE_64_BIT_IDX_T = yes; then
+  AC_CHECK_SIZEOF([void *])
+  AC_CHECK_SIZEOF([int])
+  AC_CHECK_SIZEOF([long])
+  AC_CHECK_SIZEOF([int64_t])
   if test $ac_cv_sizeof_void_p -eq 8; then
-    if test $ac_cv_sizeof_int -eq 8; then
-      OCTAVE_IDX_TYPE=int
-    elif test $ac_cv_sizeof_long -eq 8; then
-      OCTAVE_IDX_TYPE=long
-      AC_DEFINE(IDX_TYPE_LONG, 1, [Define to 1 if octave index type is long])
-    else
-      warn_64_bit="no suitable type found for octave_idx_type so disabling 64-bit features"
-      AC_MSG_WARN([$warn_64_bit])
-      USE_64_BIT_IDX_T=false
-    fi
+    OCTAVE_IDX_TYPE=int64_t
   else
-    warn_64_bit="pointers are not 64-bits wide so disabling 64-bit features"
-    AC_MSG_WARN([$warn_64_bit])
-    USE_64_BIT_IDX_T=false
+    warn_64_bit="pointers are not 64-bits wide; disabling 64-bit features"
+    OCTAVE_CONFIGURE_WARNING([warn_64_bit])
+    USE_64_BIT_IDX_T=no
   fi
 fi
 AC_SUBST(OCTAVE_IDX_TYPE)
-AC_DEFINE_UNQUOTED(OCTAVE_IDX_TYPE, $OCTAVE_IDX_TYPE,
-  [Define to the type of octave_idx_type (64 or 32 bit signed integer)])
-if $USE_64_BIT_IDX_T; then
-  AC_DEFINE(USE_64_BIT_IDX_T, 1, [Define if using 64-bit integers for array dimensions and indexing])
+AC_DEFINE_UNQUOTED(OCTAVE_IDX_TYPE, [$OCTAVE_IDX_TYPE],
+  [Define to the type of octave_idx_type (64 or 32 bit signed integer).])
+if test $USE_64_BIT_IDX_T = yes; then
+  AC_DEFINE(USE_64_BIT_IDX_T, 1,
+    [Define to 1 if using 64-bit integers for array dimensions and indexing.])
 fi
 AC_SUBST(USE_64_BIT_IDX_T)
 
@@ -240,73 +279,88 @@
 ### GNU libc, just disable them for all platforms.
 
 AC_MSG_NOTICE([defining __NO_MATH_INLINES avoids buggy GNU libc exp function])
-AC_DEFINE(__NO_MATH_INLINES, 1, [Define if your version of GNU libc has buggy inline assembly code for math functions like exp.])
-
-### See which C++ compiler to use (we expect to find g++).
+AC_DEFINE(__NO_MATH_INLINES, 1,
+  [Define to 1 if your version of GNU libc has buggy inline assembly code for math functions like exp.])
+
+### Determine which C++ compiler to use (we expect to find g++).
 
 AC_PROG_CXX
 AC_PROG_CXXCPP
 
-### Do special things for g++.
-
-gxx_version=`$CXX -v 2>&1 | grep "^.*g.. version" | \
-  sed -e 's/^.*g.. version *//' -e 's/cygnus-//' -e 's/egcs-//' -e 's/ .*//'`
-
-case "$gxx_version" in
-  1.* | 2.[[0123456789]].* | 3.[[01234]].*)
-    AC_MSG_ERROR([g++ version $gxx_version will probably fail to compile Octave]
-)
-  ;;
-esac
-
-CXX_VERSION=
-if test -n "$gxx_version"; then
-  CXX_VERSION="$gxx_version"
+### Check version number when using g++.
+
+GXX_VERSION=
+if test "$GXX" = yes; then
+  gxx_version=`$CXX -v 2>&1 | grep "^.*g.. version" | \
+    sed -e 's/^.*g.. version *//' -e 's/cygnus-//' -e 's/egcs-//' -e 's/ .*//'`
+
+  AX_COMPARE_VERSION([$gxx_version], [lt], [3.5],
+    [AC_MSG_ERROR([g++ version $gxx_version will probably fail to compile Octave])])
+
+  GXX_VERSION=$gxx_version
 fi
+AC_SUBST(GXX_VERSION)
+
+## FIXME: CXX_VERSION is deprecated and should be removed in Octave version 3.12
+CXX_VERSION=$gxx_version
 AC_SUBST(CXX_VERSION)
 
-OCTAVE_CXX_NEW_FRIEND_TEMPLATE_DECL
-OCTAVE_CXX_ISO_COMPLIANT_LIBRARY
-OCTAVE_CXX_BROKEN_REINTERPRET_CAST
-
-### See which C compiler to use (we expect to find gcc).
+### Determine which C compiler to use (we expect to find gcc).
 
 AC_PROG_CC
 AC_PROG_CPP
 AC_PROG_GCC_TRADITIONAL
 
-### gnulib
-
-gl_EARLY
-gl_INIT
-
-### Do special things for gcc.
-
-gcc_version=`$CC -v 2>&1 | grep "^.*gcc version" | \
-  sed -e 's/^.*g.. version *//' -e 's/cygnus-//' -e 's/egcs-//'`
-case "$gcc_version" in
-  [12].*)
-    warn_gcc_version="gcc version $gcc_version is likely to cause problems"
-    AC_MSG_WARN([$warn_gcc_version])
+## Check for MSVC
+have_msvc=no
+case $host_os in
+  msdosmsvc)
+    have_msvc=yes
+  ;;
+  mingw*)
+    AC_MSG_CHECKING([for MSVC compiler])
+    AC_PREPROC_IFELSE([AC_LANG_SOURCE([[
+        #ifndef _MSC_VER
+        #error "Not MSVC compiler"
+        #endif
+        ]])],
+      have_msvc=yes, have_msvc=no)
+    AC_MSG_RESULT([$have_msvc])
   ;;
 esac
 
-CC_VERSION=
-if test -n "$gcc_version"; then
-  CC_VERSION="$gcc_version"
+### gnulib initialization: part 1
+### Must take place immediately after a compiler is determined
+
+gl_EARLY
+
+### Check version number when using gcc.
+
+GCC_VERSION=
+if test "$GCC" = yes; then
+  gcc_version=`$CC -v 2>&1 | grep "^.*gcc version" | \
+    sed -e 's/^.*g.. version *//' -e 's/cygnus-//' -e 's/egcs-//' -e 's/ .*//'`
+
+  AX_COMPARE_VERSION([$gcc_version], [lt], [3],
+    [warn_gcc_version="gcc version $gcc_version is likely to cause problems"
+     OCTAVE_CONFIGURE_WARNING([warn_gcc_version])])
+
+  GCC_VERSION=$gcc_version
 fi
 AC_SUBST(CC_VERSION)
 
-### The flag to create dependency varies depending on the compier.
-
-# Assume GCC.
-INCLUDE_DEPS=true
+## FIXME: CC_VERSION is deprecated and should be removed in Octave version 3.12
+CC_VERSION=$gcc_version
+AC_SUBST(GCC_VERSION)
+
+### Determine the compiler flag necessary to create dependencies
+
+## Assume GCC.
+INCLUDE_DEPS=yes
 DEPEND_FLAGS="-M"
 DEPEND_EXTRA_SED_PATTERN=""
-if test "$GCC" = yes; then
-  true
-else
-  case "$canonical_host_type" in
+if test "$GCC" != yes; then
+  case $canonical_host_type in
     sparc-sun-solaris2* | i386-pc-solaris2*)
       DEPEND_FLAGS="-xM1"
       DEPEND_EXTRA_SED_PATTERN="-e '/\/opt\/SUNWspro/d'"
@@ -314,12 +368,12 @@
     *-*-msdosmsvc)
     ;;
     *-*-mingw*)
-      if test "$have_msvc" = "no"; then
-        INCLUDE_DEPS=false
+      if test $have_msvc = no; then
+        INCLUDE_DEPS=no
       fi
     ;;
     *)
-      INCLUDE_DEPS=false
+      INCLUDE_DEPS=no
     ;;
   esac
 fi
@@ -327,39 +381,14 @@
 AC_SUBST(DEPEND_FLAGS)
 AC_SUBST(DEPEND_EXTRA_SED_PATTERN)
 
+### Check for pthread library
+
 AX_PTHREAD
-### Include pthread libs and flags here in case other tests need them.
-### They seem to be required for the OpenGL tests on Debian systems.
+## Include pthread libs and flags early in case other tests need them.
+## They seem to be required for the OpenGL tests on Debian systems.
 LIBS="$PTHREAD_LIBS $LIBS"
 CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-
-AC_PATH_X
-if test "$have_x" = "yes"; then
-  AC_DEFINE(HAVE_X_WINDOWS, 1, [Define if you have X11])
-
-  if test "$x_includes" != "NONE"; then
-    X11_INCFLAGS="$x_includes"
-  fi
-  AC_SUBST(X11_INCFLAGS)
-
-  if test -z $x_libraries; then
-    AC_CHECK_LIB(X11, XrmInitialize, [X11_LIBS=-lX11], [X11_LIBS=])
-  elif test $x_libraries != "NONE"; then
-    AC_CHECK_LIB(X11, XrmInitialize, 
-      [X11_LIBS="-L$x_libraries -lX11"], [X11_LIBS=], "-L$x_libraries")
-  fi
-  AC_SUBST(X11_LIBS)
-fi
-
-### On MacOSX system the Carbon framework is used to determine ScreenSize
-OCTAVE_HAVE_FRAMEWORK(Carbon, [#include <Carbon/Carbon.h>], [CGMainDisplayID ()],
-  [have_framework_carbon="yes"], [have_framework_carbon="no"])
-if test $have_framework_carbon = "yes"; then
-  AC_DEFINE(HAVE_FRAMEWORK_CARBON, 1, [Define if framework CARBON is available.])
-  CARBON_LIBS="-Wl,-framework -Wl,Carbon"
-  AC_MSG_NOTICE([adding -Wl,-framework -Wl,Carbon to CARBON_LIBS])
-  AC_SUBST(CARBON_LIBS)
-fi
+CXXFLAGS="$CXXFLAGS $PTHREAD_CFLAGS"
 
 ### When compiling math for x87, problems may arise in some code comparing
 ### floating-point intermediate results.
@@ -368,122 +397,99 @@
 ### Thus, we provide a FLOAT_TRUNCATE macro that may be defined to "volatile"
 ### when compiling for x87 target, or left empty for modern SSE math, that
 ### doesn't suffer from this problem at all.
-AC_ARG_ENABLE(float-truncate,
+AC_ARG_ENABLE([float-truncate],
   [AS_HELP_STRING([--enable-float-truncate],
-     [enables truncating intermediate FP results.])],
-  [if test "$enableval" = yes; then ac_float_truncate=volatile;
-   else ac_float_truncate=; fi],
-  ac_float_truncate=)
-
-AC_DEFINE_UNQUOTED(FLOAT_TRUNCATE, $ac_float_truncate, 
-          [Define to volatile if you need truncating intermediate FP results])
-
-### On Intel systems with gcc, we may need to compile with -mieee-fp
-### and -ffloat-store to get full support for IEEE floating point.
-###
-### On Alpha/OSF systems, we need -mieee.
+    [enables truncating intermediate FP results.])],
+  [if test "$enableval" = yes; then
+     ac_float_truncate=volatile
+   else
+     ac_float_truncate=
+   fi],
+  [ac_float_truncate=])
+
+AC_DEFINE_UNQUOTED(FLOAT_TRUNCATE, [$ac_float_truncate], 
+  [Define to volatile if you need to truncate intermediate FP results.])
+
+### Determine extra CFLAGS that may be necessary for Octave.
+
+## On Intel systems with gcc, we may need to compile with -mieee-fp
+## to get full support for IEEE floating point.
+##
+## On Alpha/OSF systems, we need -mieee.
 
 ieee_fp_flag=
-case "$canonical_host_type" in
-  ## Keep this pattern first, so that it is preferred over the
-  ## following pattern for x86.
+case $canonical_host_type in
   i[[3456789]]86-*-*)
     if test "$GCC" = yes; then
-      OCTAVE_CC_FLAG(-mieee-fp, [
+      OCTAVE_CC_FLAG([-mieee-fp], [
         ieee_fp_flag=-mieee-fp
         XTRA_CFLAGS="$XTRA_CFLAGS -mieee-fp"
         AC_MSG_NOTICE([adding -mieee-fp to XTRA_CFLAGS])])
-
-###      OCTAVE_CC_FLAG(-ffloat-store, [
-###        float_store_flag=-ffloat-store
-###        XTRA_CFLAGS="$XTRA_CFLAGS -ffloat-store"
-###        AC_MSG_RESULT([adding -ffloat-store to XTRA_CFLAGS])])
     fi
     if test "$GXX" = yes; then
-      OCTAVE_CXX_FLAG(-mieee-fp, [
+      OCTAVE_CXX_FLAG([-mieee-fp], [
         ieee_fp_flag=-mieee-fp
         XTRA_CXXFLAGS="$XTRA_CXXFLAGS -mieee-fp"
         AC_MSG_NOTICE([adding -mieee-fp to XTRA_CXXFLAGS])])
-
-###      OCTAVE_CXX_FLAG(-ffloat-store, [
-###        float_store_flag=-ffloat-store
-###        XTRA_CXXFLAGS="$XTRA_CXXFLAGS -ffloat-store"
-###        AC_MSG_RESULT([adding -ffloat-store to XTRA_CXXFLAGS])])
     fi
   ;;
   alpha*-*-*)
     if test "$GCC" = yes; then
-      OCTAVE_CC_FLAG(-mieee, [
+      OCTAVE_CC_FLAG([-mieee], [
         ieee_fp_flag=-mieee
         XTRA_CFLAGS="$XTRA_CFLAGS -mieee"
         AC_MSG_NOTICE([adding -mieee to XTRA_CFLAGS])])
     else
-      OCTAVE_CC_FLAG(-ieee, [
+      OCTAVE_CC_FLAG([-ieee], [
         ieee_fp_flag=-ieee
         XTRA_CFLAGS="$XTRA_CFLAGS -ieee"
         AC_MSG_NOTICE([adding -ieee to XTRA_CFLAGS])])
     fi
     if test "$GXX" = yes; then
-      OCTAVE_CXX_FLAG(-mieee, [
+      OCTAVE_CXX_FLAG([-mieee], [
         ieee_fp_flag=-mieee
         XTRA_CXXFLAGS="$XTRA_CXXFLAGS -mieee"
         AC_MSG_NOTICE([adding -mieee to XTRA_CXXFLAGS])])
     else
-      OCTAVE_CXX_FLAG(-ieee, [
+      OCTAVE_CXX_FLAG([-ieee], [
         ieee_fp_flag=-ieee
         XTRA_CXXFLAGS="$XTRA_CXXFLAGS -ieee"
         AC_MSG_NOTICE([adding -ieee to XTRA_CXXFLAGS])])
     fi
   ;;
   *ibm-aix4*)
-    OCTAVE_CC_FLAG(-mminimal-toc, [
+    OCTAVE_CC_FLAG([-mminimal-toc], [
       XTRA_CFLAGS="$XTRA_CFLAGS -mminimal-toc"])
 
-    OCTAVE_CXX_FLAG(-mminimal-toc, [
+    OCTAVE_CXX_FLAG([-mminimal-toc], [
       XTRA_CXXFLAGS="$XTRA_CXXFLAGS -mminimal-toc"])
   ;;
 esac
 
-## Test whether the compiler supports OpenMP. Experimental so disable by 
-## default. Enable it with the flag --enable-openmp
-USE_OPENMP=false
-AC_ARG_ENABLE(openmp,
+AC_SUBST(XTRA_CFLAGS)
+AC_SUBST(XTRA_CXXFLAGS)
+
+### Test whether the compiler supports OpenMP.  This is experimental so disable
+### it by default.  Enable it with the flag --enable-openmp.
+
+USE_OPENMP=no
+AC_ARG_ENABLE([openmp],
   [AS_HELP_STRING([--enable-openmp],
-     [(EXPERIMENTAL) use OpenMP SMP multi-threading])],
-  [if test "$enableval" = yes; then USE_OPENMP=true; fi], [])
-if $USE_OPENMP; then
-  case "$canonical_host_type" in
-    *-*-mingw* | *-*-cygwin* | *-*-gnu*)
-    OCTAVE_CHECK_OPENMP(-fopenmp)
+    [(EXPERIMENTAL) use OpenMP SMP multi-threading])],
+  [if test "$enableval" = yes; then USE_OPENMP=yes; fi], [])
+if test $USE_OPENMP = yes; then
+  case $host_os in
+    mingw* | cygwin* | *-gnu*)
+      OCTAVE_CHECK_OPENMP(-fopenmp)
     ;;
-    *-*-msdosmsvc)
-    ## FIXME is this the right flag for MSVC?
-    OCTAVE_CHECK_OPENMP(-openmp)
+    msdosmsvc)
+      ## FIXME: is this the right flag for MSVC?
+      OCTAVE_CHECK_OPENMP(-openmp)
     ;;
     ## Add other compilers supporting OpenMP here
   esac
 fi
 
-AC_SUBST(XTRA_CFLAGS)
-AC_SUBST(XTRA_CXXFLAGS)
-
-## Avoid #define of min/max from windows.h header
-if test "$have_msvc" = "yes"; then
-  AC_DEFINE(NOMINMAX, 1, [Define if you want to avoid min/max macro definition in Windows headers])
-fi
-
-### Use -static if compiling on Alpha OSF/1 1.3 systems.
-
-case "$canonical_host_type" in
-  alpha*-dec-osf1.3)
-    LD_STATIC_FLAG=-static
-  ;;
-esac
-if test -n "$LD_STATIC_FLAG"; then
-  AC_MSG_NOTICE([defining LD_STATIC_FLAG to be $LD_STATIC_FLAG])
-fi
-AC_SUBST(LD_STATIC_FLAG)
-
 ### Defaults for cross compiling.  BUILD_CC and BUILD_CXX are
 ### the compilers that we use for building tools on the build system.
 ### For now, we assume that the only cross compiling we can do is
@@ -502,42 +508,33 @@
   BUILD_CXX='$(CXX)'
   BUILD_CXXFLAGS='$(CXXFLAGS)'
   BUILD_LDFLAGS='$(LDFLAGS)'
-  case "$canonical_host_type" in
-    sparc-sun-solaris2*)
-      if test "$GCC" != yes; then
-        ## The Sun C++ compiler never seems to complete compiling
-        ## gendoc.cc unless we reduce the optimization level...
-        BUILD_CXXFLAGS="-g -O1"
-      fi
-    ;;
-  esac
   BUILD_EXEEXT='$(EXEEXT)'
 fi
 
-AC_ARG_VAR(BUILD_CC, [build system C compiler (used if cross compiling)])
-AC_ARG_VAR(BUILD_CFLAGS, [build system C compiler flags (used if cross compiling)])
-AC_ARG_VAR(BUILD_CXX, [build system C++ compiler (used if cross compiling)])
-AC_ARG_VAR(BUILD_CXXFLAGS, [build system C++ compiler flags (used if cross compiling)])
-AC_ARG_VAR(BUILD_LDFLAGS, [build system C++ compiler link flags (used if cross compiling)])
-AC_ARG_VAR(BUILD_EXEEXT, [build system executable extension (used if cross compiling)])
-
-dnl This is bogus.  We shouldn't have to explicitly add libc too!
-dnl Keep this check before the check for the Fortran compiler,
-dnl in case -lm is needed to compile Fortran programs.
+AC_ARG_VAR([BUILD_CC],
+  [build system C compiler (used if cross compiling)])
+AC_ARG_VAR([BUILD_CFLAGS],
+  [build system C compiler flags (used if cross compiling)])
+AC_ARG_VAR([BUILD_CXX],
+  [build system C++ compiler (used if cross compiling)])
+AC_ARG_VAR([BUILD_CXXFLAGS],
+  [build system C++ compiler flags (used if cross compiling)])
+AC_ARG_VAR([BUILD_LDFLAGS],
+  [build system C++ compiler link flags (used if cross compiling)])
+AC_ARG_VAR([BUILD_EXEEXT],
+  [build system executable extension (used if cross compiling)])
+
 
 ### Look for math library.  If found, this will add -lm to LIBS.
 
-case "$canonical_host_type" in
-  *-*-linux*)
-    AC_CHECK_LIB(m, sin, , , -lc)
-  ;;
-  *)
-    AC_CHECK_LIB(m, sin)
-  ;;
-esac
+dnl Keep this check before the check for the Fortran compiler,
+dnl in case -lm is needed to compile Fortran programs.
+AC_CHECK_LIB(m, sin)
+
+### Determine the Fortran compiler and how to invoke it
 
 ## Default FFLAGS is -O.
-if test "x$FFLAGS" = x; then
+if test x"$FFLAGS" = x""; then
   FFLAGS="-O"
 fi
 
@@ -547,33 +544,32 @@
 AC_F77_DUMMY_MAIN
 AC_F77_WRAPPERS
 
-F77_TOLOWER=true
-F77_APPEND_UNDERSCORE=true
-F77_APPEND_EXTRA_UNDERSCORE=true
-
-case "$ac_cv_f77_mangling" in
-  "upper case") F77_TOLOWER=false ;;
-esac
-case "$ac_cv_f77_mangling" in
-  "no underscore") F77_APPEND_UNDERSCORE=false ;;
+F77_TOLOWER=yes
+F77_APPEND_UNDERSCORE=yes
+F77_APPEND_EXTRA_UNDERSCORE=yes
+
+case $ac_cv_f77_mangling in
+  "upper case") F77_TOLOWER=no ;;
 esac
-case "$ac_cv_f77_mangling" in
-  "no extra underscore") F77_APPEND_EXTRA_UNDERSCORE=false ;;
+case $ac_cv_f77_mangling in
+  "no underscore") F77_APPEND_UNDERSCORE=no ;;
+esac
+case $ac_cv_f77_mangling in
+  "no extra underscore") F77_APPEND_EXTRA_UNDERSCORE=no ;;
 esac
 
-case "$canonical_host_type" in
+case $canonical_host_type in
   i[[3456789]]86-*-*)
-    if test "$ac_cv_f77_compiler_gnu" = yes; then
-      OCTAVE_F77_FLAG(-mieee-fp)
-###      OCTAVE_F77_FLAG(-ffloat-store)
+    if test $ac_cv_f77_compiler_gnu = yes; then
+      OCTAVE_F77_FLAG([-mieee-fp])
     fi
   ;;
   alpha*-*-*)
-    if test "$ac_cv_f77_compiler_gnu" = yes; then
-      OCTAVE_F77_FLAG(-mieee)
+    if test $ac_cv_f77_compiler_gnu = yes; then
+      OCTAVE_F77_FLAG([-mieee])
     else
-      OCTAVE_F77_FLAG(-ieee)
-      OCTAVE_F77_FLAG(-fpe1)
+      OCTAVE_F77_FLAG([-ieee])
+      OCTAVE_F77_FLAG([-fpe1])
     fi
   ;;
   powerpc-apple-machten*)
@@ -590,19 +586,27 @@
 AC_SUBST(F77_APPEND_EXTRA_UNDERSCORE)
 
 if test -z "$F77"; then
-  AC_MSG_ERROR([in order to build octave, you must have a compatible Fortran compiler or wrapper script for f2c that functions as a Fortran compiler installed and in your path.  See the file INSTALL for more information.])
+  AC_MSG_ERROR([in order to build Octave, you must have a compatible Fortran compiler or wrapper script for f2c that functions as a Fortran compiler installed and in your path.  See the file INSTALL for more information.])
+fi
+
+OCTAVE_CHECK_FUNC_FORTRAN_ISNAN
+F77_ISNAN_MACRO=
+if test $octave_cv_func_fortran_isnan = no; then
+  AC_MSG_NOTICE([substituting ISNAN(X) with X.NE.X in Fortran sources])
+  F77_ISNAN_MACRO="s|ISNAN(\(@<:@^)@:>@*\))|(\1.NE.\1)|"
 fi
-
-OCTAVE_CHECK_FORTRAN_INTEGER_SIZE
-if test "x$octave_cv_fortran_integer_size" = xno; then
-  if $USE_64_BIT_IDX_T; then
-    case "$F77" in
+AC_SUBST(F77_ISNAN_MACRO)
+
+OCTAVE_CHECK_SIZEOF_FORTRAN_INTEGER
+if test $octave_cv_sizeof_fortran_integer = no; then
+  if test $USE_64_BIT_IDX_T = yes; then
+    case $F77 in
       *gfortran*)
-        case "$F77_INTEGER_8_FLAG" in
+        case $F77_INTEGER_8_FLAG in
           *-fdefault-integer-8*)
           ;;
           *)
-            case "$FFLAGS" in
+            case $FFLAGS in
               *-fdefault-integer-8*)
                 AC_MSG_NOTICE([setting -fdefault-integer-8 in F77_INTEGER_8_FLAG instead of FFLAGS])
                 FFLAGS=`echo $FFLAGS | sed 's/-fdefault-integer-8//g'`
@@ -612,18 +616,18 @@
                 AC_MSG_NOTICE([adding -fdefault-integer-8 to F77_INTEGER_8_FLAG])
                 F77_INTEGER_8_FLAG="-fdefault-integer-8"
                 ## Invalidate the cache and try again.
-                $as_unset octave_cv_fortran_integer_size
+                $as_unset octave_cv_sizeof_fortran_integer
               ;;
             esac
           ;;
         esac
       ;;
     esac
-    if test -z "$octave_cv_fortran_integer_size"; then
-      OCTAVE_CHECK_FORTRAN_INTEGER_SIZE
+    if test -z "$octave_cv_sizeof_fortran_integer"; then
+      OCTAVE_CHECK_SIZEOF_FORTRAN_INTEGER
     fi
-    if test "x$octave_cv_fortran_integer_size" = xno; then
-      AC_MSG_ERROR([in order to build octave with 64-bit indexing support your Fortran compiler must have an option for setting the default integer size to 8 bytes.  See the file INSTALL for more information.])
+    if test $octave_cv_sizeof_fortran_integer = no; then
+      AC_MSG_ERROR([in order to build Octave with 64-bit indexing support your Fortran compiler must have an option for setting the default integer size to 8 bytes.  See the file INSTALL for more information.])
     fi
   else
     AC_MSG_ERROR([your Fortran compiler must have an option to make integers the same size as octave_idx_type ($OCTAVE_IDX_TYPE).  See the file INSTALL for more information.])
@@ -631,32 +635,30 @@
 fi
 AC_SUBST(F77_INTEGER_8_FLAG)
 
+## FIXME: Is this really used?  Makefile seems to use $F77 for compiler
 FC=$F77
 AC_SUBST(FC)
 
-OCTAVE_F77_FLAG(-ffloat-store, [
-AC_MSG_RESULT([setting F77_FLOAT_STORE_FLAG to -ffloat-store])
-F77_FLOAT_STORE_FLAG=-ffloat-store
-AC_SUBST(F77_FLOAT_STORE_FLAG)
+OCTAVE_F77_FLAG([-ffloat-store], [
+  AC_MSG_RESULT([setting F77_FLOAT_STORE_FLAG to -ffloat-store])
+  F77_FLOAT_STORE_FLAG=-ffloat-store
+  AC_SUBST(F77_FLOAT_STORE_FLAG)
 ])
 
-OCTAVE_IEEE754_DATA_FORMAT
-
-OCTAVE_CXX_COMPLEX_SETTERS
-OCTAVE_CXX_COMPLEX_REFERENCE_ACCESSORS
-
-### Check for the QHull library
-
-OCTAVE_CHECK_LIBRARY(qhull, QHull,
+### Check for the Qhull library
+
+OCTAVE_CHECK_LIB(qhull, QHull,
   [Qhull library not found -- this will result in loss of functionality of some geometry functions.],
-  [libqhull/libqhull.h qhull/libqhull.h libqhull.h qhull/qhull.h qhull.h], [qh_qhull], [], [],
+  [libqhull/libqhull.h qhull/libqhull.h libqhull.h qhull/qhull.h qhull.h],
+  [qh_qhull], [], [],
   [warn_qhull=
-   OCTAVE_CHECK_QHULL_VERSION
-   OCTAVE_CHECK_QHULL_OK([TEXINFO_QHULL="@set HAVE_QHULL"
-     AC_DEFINE(HAVE_QHULL, 1, [Define if QHull is available.])], [
-     warn_qhull="Qhull library found, but seems not to work properly -- this will result in loss of functionality of some geometry functions.  Please try recompiling the library with -fno-strict-aliasing."])])
-
-### Check for pcre regex library.
+  OCTAVE_CHECK_QHULL_VERSION
+  OCTAVE_CHECK_LIB_QHULL_OK(
+    [TEXINFO_QHULL="@set HAVE_QHULL"
+    AC_DEFINE(HAVE_QHULL, 1, [Define to 1 if Qhull is available.])],
+    [warn_qhull="Qhull library found, but does not seem to work properly -- this will result in loss of functionality of some geometry functions.  Please try recompiling the library with -fno-strict-aliasing."])])
+
+### Check for PCRE regex library.
 
 REGEX_LIBS=
 
@@ -667,30 +669,31 @@
 AC_CACHE_CHECK([whether pcre.h defines the macros we need],
   [ac_cv_pcre_h_macros_present],
   [AC_EGREP_CPP([PCRE_HAS_MACROS_WE_NEED], [
-#if defined (HAVE_PCRE_H)
-#include <pcre.h>
-#elif defined (HAVE_PCRE_PCRE_H)
-#include <pcre/pcre.h>
-#error "NO PCRE HEADER"
-#endif
-#if defined (PCRE_INFO_NAMECOUNT) \
-  && defined (PCRE_INFO_NAMEENTRYSIZE) \
-  && defined (PCRE_INFO_NAMETABLE)
-PCRE_HAS_MACROS_WE_NEED
-#endif], ac_cv_pcre_h_macros_present=yes, ac_cv_pcre_h_macros_present=no)])
+    #if defined (HAVE_PCRE_H)
+    # include <pcre.h>
+    #elif defined (HAVE_PCRE_PCRE_H)
+    # include <pcre/pcre.h>
+    #error "NO PCRE HEADER"
+    #endif
+    #if defined (PCRE_INFO_NAMECOUNT) \
+      && defined (PCRE_INFO_NAMEENTRYSIZE) \
+      && defined (PCRE_INFO_NAMETABLE)
+      PCRE_HAS_MACROS_WE_NEED
+    #endif],
+    ac_cv_pcre_h_macros_present=yes, ac_cv_pcre_h_macros_present=no)])
 
 if test $ac_cv_pcre_h_macros_present = yes; then
   ## check for pcre-config, and if so, set XTRA_CXXFLAGS appropriately
   AC_CHECK_PROG(HAVE_PCRE_CONFIG, pcre-config, [yes], [no])
   if test $HAVE_PCRE_CONFIG = yes; then
     XTRA_CXXFLAGS="$XTRA_CXXFLAGS `pcre-config --cflags`"
-    REGEX_LIBS="`pcre-config --libs`"
+    REGEX_LIBS=`pcre-config --libs`
   else
     REGEX_LIBS="-lpcre"
   fi
   save_LIBS="$LIBS"
   LIBS="$REGEX_LIBS $LIBS"
-  AC_CHECK_FUNCS(pcre_compile,
+  AC_CHECK_FUNCS([pcre_compile],
     [AC_SUBST(REGEX_LIBS)],
     [AC_MSG_ERROR([$pcre_fail_msg])])
   LIBS="$save_LIBS"
@@ -700,80 +703,206 @@
 
 ### Check for ZLIB library.
 
-OCTAVE_CHECK_LIBRARY(z, ZLIB,
+OCTAVE_CHECK_LIB(z, ZLIB,
   [ZLIB library not found.  Octave will not be able to save or load compressed data files or HDF5 files.],
   [zlib.h], [gzclearerr])
 
+### Also define HAVE_ZLIB if libz is found.
+if test $octave_cv_lib_z = yes; then
+  AC_DEFINE(HAVE_ZLIB, 1, [Define to 1 if ZLIB is available.])
+fi
+
+### Check for the LLVM library
+
+build_jit=no
+AC_ARG_ENABLE([jit],
+  [AS_HELP_STRING([--enable-jit],
+    [(EXPERIMENTAL) enable JIT compiler])],
+  [if test "$enableval" = yes; then
+     build_jit=yes
+   fi],
+  [])
+
+LLVM_CXXFLAGS=
+LLVM_CPPFLAGS=
+LLVM_LDFLAGS=
+LLVM_LIBS=
+
+if test $build_jit = yes; then
+
+  ## Find llvm-config program from environment variable or by searching
+  AC_ARG_VAR([LLVM_CONFIG], [path to llvm-config utility])
+  AC_CHECK_PROG([LLVM_CONFIG], llvm-config, llvm-config, [])
+
+  if test -z "$LLVM_CONFIG"; then
+    warn_llvm="llvm-config utility not found.  JIT compiler is disabled."
+  else
+    dnl Preset warning message in case compile fails
+    warn_llvm="LLVM was not found or is to old.  JIT compiler is disabled."
+
+    save_CPPFLAGS="$CPPFLAGS"
+    save_CXXFLAGS="$CXXFLAGS"
+
+    ## Use -isystem if available because we don't want to see warnings in LLVM
+    LLVM_INCLUDE_FLAG=-I
+    OCTAVE_CC_FLAG([-isystem .], [
+      LLVM_INCLUDE_FLAG=-isystem
+      AC_MSG_NOTICE([using -isystem for LLVM headers])])
+
+    dnl Use -isystem so we don't get warnings from llvm headers
+    LLVM_CPPFLAGS="$LLVM_INCLUDE_FLAG `$LLVM_CONFIG --includedir`"
+    LLVM_CXXFLAGS=
+    LLVM_LDFLAGS="-L`$LLVM_CONFIG --libdir`"
+    LLVM_LIBS=`$LLVM_CONFIG --libs`
+
+    dnl
+    dnl Define some extra flags that LLVM requires in order to include headers.
+    dnl Ideally we should get these from llvm-config, but llvm-config isn't
+    dnl very helpful.
+    dnl
+    CPPFLAGS="-D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS $LLVM_CPPFLAGS $CPPFLAGS"
+    CXXFLAGS="$LLVM_CXXFLAGS $CXXFLAGS"
+    AC_LANG_PUSH(C++)
+    AC_CHECK_HEADER([llvm/Support/TargetSelect.h], [
+      warn_llvm=
+      XTRA_CXXFLAGS="$XTRA_CXXFLAGS $LLVM_CXXFLAGS $LLVM_CPPFLAGS"])
+    AC_LANG_POP(C++)
+    CPPFLAGS="$save_CPPFLAGS"
+    CXXFLAGS="$save_CXXFLAGS"
+  fi
+
+  if test -z "$warn_llvm"; then
+    AC_DEFINE(HAVE_LLVM, 1, [Define to 1 if LLVM is available.])
+  else
+    build_jit=no
+    LLVM_CPPFLAGS=
+    LLVM_CXXFLAGS=
+    LLVM_LDFLAGS=
+    LLVM_LIBS=
+    OCTAVE_CONFIGURE_WARNING([warn_llvm])
+  fi
+dnl FIXME: Re-instate when JIT is enabled by default
+dnl else
+dnl   ## JIT build disabled
+dnl   warn_llvm="JIT compiler disabled, some performance loss for loops"
+dnl   OCTAVE_CONFIGURE_WARNING([warn_llvm])
+fi
+
+AC_SUBST(LLVM_CPPFLAGS)
+AC_SUBST(LLVM_CXXFLAGS)
+AC_SUBST(LLVM_LDFLAGS)
+AC_SUBST(LLVM_LIBS)
+
 ### Check for HDF5 library.
 
 save_CPPFLAGS="$CPPFLAGS"
+save_LIBS="$LIBS"
 CPPFLAGS="$Z_CPPFLAGS $CPPFLAGS"
-save_LIBS="$LIBS"
 LIBS="$Z_LDFLAGS $Z_LIBS $LIBS"
-OCTAVE_CHECK_LIBRARY(hdf5, HDF5,
+OCTAVE_CHECK_LIB(hdf5, HDF5,
   [HDF5 library not found.  Octave will not be able to save or load HDF5 data files.],
   [hdf5.h], [H5Gget_num_objs], [], [],
   [warn_hdf5=
-   OCTAVE_HDF5_HAS_ENFORCED_16_API
+   OCTAVE_CHECK_HDF5_HAS_VER_16_API
    TEXINFO_HDF5="@set HAVE_HDF5"
-   AC_DEFINE(HAVE_HDF5, 1, [Define if HDF5 is available and newer than version 1.6.])
-   if test "$have_msvc" = "yes"; then
-     OCTAVE_HDF5_DLL
+   AC_DEFINE(HAVE_HDF5, 1,
+     [Define to 1 if HDF5 is available and newer than version 1.6.])
+   if test $have_msvc = yes; then
+     OCTAVE_CHECK_LIB_HDF5_DLL
    fi
-   ])
+  ])
 CPPFLAGS="$save_CPPFLAGS"
 LIBS="$save_LIBS"
 
-
-# Subdirectory of libcruft to build if fftw is not found:
-
-FFT_DIR="fftpack"
-AC_SUBST(FFT_DIR)
-
-# Checks for FFTW header and library.
-
-OCTAVE_CHECK_LIBRARY(fftw3, FFTW3,
+### Check for FFTW library.  Default to Fortran FFTPACK if it is not available.
+
+## Check for FFTW header and library.
+OCTAVE_CHECK_LIB(fftw3, FFTW3,
   [FFTW3 library not found.  The slower FFTPACK library will be used instead.],
   [fftw3.h], [fftw_plan_dft_1d])
 
-OCTAVE_CHECK_LIBRARY(fftw3f, FFTW3F,
+OCTAVE_CHECK_LIB(fftw3f, FFTW3F,
   [FFTW3F library not found.  The slower FFTPACK library will be used instead.],
   [fftw3.h], [fftwf_plan_dft_1d])
 
+## Check for the multithreaded FFTW library.
+## Fallback to singlethreaded if not found or disabled
+build_fftw_threads=yes
+AC_ARG_ENABLE([fftw-threads],
+  [AS_HELP_STRING([--disable-fftw-threads],
+    [disable Multi-threaded FFTW])],
+  [if test "$enableval" = no; then
+     build_fftw_threads=no
+   fi],
+  [])
+
+if test $build_fftw_threads = yes; then
+  OCTAVE_CHECK_FFTW_THREADS(fftw3, fftw_plan_with_nthreads)
+  OCTAVE_CHECK_FFTW_THREADS(fftw3f, fftwf_plan_with_nthreads)
+fi
+
+## Octave is currently unable to use FFTW unless both float
+## and double versions are available.
+
 AM_CONDITIONAL([AMCOND_HAVE_FFTW],
   [test -n "$FFTW3_LIBS" && test -n "$FFTW3F_LIBS"])
 
-# Checks for GLPK header and library.
+if test -n "$FFTW3_LIBS" && test -n "$FFTW3F_LIBS"; then
+  AC_DEFINE(HAVE_FFTW, 1, [Define if you have both FFTW3 and FFTW3F libraries.])
+fi
+
+## Subdirectory of liboctave/cruft to build if FFTW is not found.
+FFT_DIR="fftpack"
+AC_SUBST(FFT_DIR)
+
+### Check for GLPK library and header.
 
 save_CPPFLAGS="$CPPFLAGS"
+save_LIBS="$LIBS"
 CPPFLAGS="$Z_CPPFLAGS $CPPFLAGS"
-save_LIBS="$LIBS"
 LIBS="$Z_LDFLAGS $Z_LIBS $LIBS"
-OCTAVE_CHECK_LIBRARY(glpk, GLPK,
+OCTAVE_CHECK_LIB(glpk, GLPK,
   [GLPK library not found.  The glpk function for solving linear programs will be disabled.],
   [glpk/glpk.h glpk.h], [_glp_lpx_simplex])
 LIBS="$save_LIBS"
 CPPFLAGS="$save_CPPFLAGS"
 
-# Checks for CURL header and library.
+### Checks for cURL header and library.
 
 save_CPPFLAGS="$CPPFLAGS"
+save_LIBS="$LIBS"
 CPPFLAGS="$Z_CPPFLAGS $CPPFLAGS"
-save_LIBS="$LIBS"
 LIBS="$Z_LDFLAGS $Z_LIBS $LIBS"
-OCTAVE_CHECK_LIBRARY(curl, cURL,
+OCTAVE_CHECK_LIB(curl, cURL,
   [cURL library not found.  The ftp objects, urlread and urlwrite functions will be disabled.],
   [curl/curl.h], [curl_easy_escape])
+if test -z "$warn_curl"; then
+  ## Additional check on cURL library that was found
+  AC_CACHE_CHECK([for CURLOPT_DIRLISTONLY in curl/curl.h],
+    [octave_cv_curl_has_curlopt_dirlistonly],
+    [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+      #include <curl/curl.h>
+      ]], [[
+      curl_easy_setopt ((CURL*)NULL, CURLOPT_DIRLISTONLY, 0);
+      ]])],
+      [octave_cv_curl_has_curlopt_dirlistonly=yes],
+      [octave_cv_curl_has_curlopt_dirlistonly=no])
+    ])
+  if test $octave_cv_curl_has_curlopt_dirlistonly = no; then
+    AC_DEFINE(CURLOPT_DIRLISTONLY, CURLOPT_FTPLISTONLY,
+      [Define to the legacy option name if using an older version of cURL.])
+  fi
+fi
 LIBS="$save_LIBS"
 CPPFLAGS="$save_CPPFLAGS"
 
-### Graphics/ImageMagick++
+### Check for either of Graphics/ImageMagick++ libraries
 
 AC_ARG_WITH([magick],
   [AS_HELP_STRING([--with-magick=LIB],
-    [select library to use for image I/O (options: GraphicsMagick(default) or ImageMagick)])], [
-  magick="$withval"], [
-  magick="GraphicsMagick"])
+    [select library to use for image I/O (options: GraphicsMagick(default) or ImageMagick)])],
+  [magick="$withval"],
+  [magick="GraphicsMagick"])
 
 warn_magick="$magick++ library not found.  The imread function for reading image files will not be fully functional."
 
@@ -782,8 +911,8 @@
 MAGICK_LIBS=
 
 PKG_CHECK_EXISTS([$magick++], [
-  ## Make sure we only get -I, -L and -l flags.  Some Graphics/ImageMagick++
-  ## packages adds extra flags that are useful when building
+  ## Make sure we only get -I, -L, and -l flags.  Some Graphics/ImageMagick++
+  ## packages add extra flags that are useful when building
   ## Graphics/ImageMagick++ extentions.  These extra flags break the
   ## Octave build. 
   MAGICK_LDFLAGS=`$PKG_CONFIG --libs-only-L $magick++`
@@ -797,22 +926,32 @@
   CPPFLAGS="$MAGICK_CPPFLAGS $CPPFLAGS"
   LIBS="$MAGICK_LDFLAGS $MAGICK_LIBS $LIBS"
   AC_LANG_PUSH(C++)
-    AC_CHECK_HEADER([Magick++.h], [
-      AC_MSG_CHECKING([for Magick::ColorRGB in Magick++.h])
-      AC_TRY_LINK([#include <Magick++.h>], [Magick::ColorRGB c;], [
-        AC_MSG_RESULT(yes)
-        warn_magick=
-      ], [
-        AC_MSG_RESULT(no)
+  AC_CHECK_HEADER([Magick++.h], [
+    AC_CACHE_CHECK([for Magick::ColorRGB in Magick++.h],
+      [octave_cv_func_magick_colorrgb],
+      [AC_PREPROC_IFELSE([AC_LANG_SOURCE([[
+        #include <Magick++.h>
+        ]], [[
+        Magick::ColorRGB c;
+        ]])],
+        octave_cv_func_magick_colorrgb=yes,
+        octave_cv_func_magick_colorrgb=no)
       ])
-    ])
+    if test $octave_cv_func_magick_colorrgb = yes; then
+      warn_magick=
+    fi
+  ])
   AC_LANG_POP(C++)
   CPPFLAGS="$save_CPPFLAGS"
   LIBS="$save_LIBS"
+
+  AC_CHECK_FUNCS([setlocale], [],
+                 [warn_magick="$magick++ requires setlocale function.  The imread function for reading image files will not be fully functional."])
 ])
 
 if test -z "$warn_magick"; then
-  AC_DEFINE(HAVE_MAGICK, 1, [Define if Graphics/ImageMagick++ is available.])
+  AC_DEFINE(HAVE_MAGICK, 1,
+    [Define to 1 if Graphics/ImageMagick++ is available.])
 else
   MAGICK_CPPFLAGS=
   MAGICK_LDFLAGS=
@@ -822,40 +961,76 @@
 AC_SUBST(MAGICK_LDFLAGS)
 AC_SUBST(MAGICK_LIBS)
 
-# ---------------------------------------------------------------------
-
-## libraries needed for native graphics renderer
-
+### Check for X11 libraries
+
+AC_PATH_X
+if test "$have_x" = yes; then
+  AC_DEFINE(HAVE_X_WINDOWS, 1, [Define to 1 if you have X11.])
+
+  if test "$x_includes" != "NONE"; then
+    X11_INCFLAGS="$x_includes"
+  fi
+  AC_SUBST(X11_INCFLAGS)
+
+  if test -z "$x_libraries"; then
+    AC_CHECK_LIB([X11], XrmInitialize, [X11_LIBS="-lX11"], [X11_LIBS=])
+  elif test $x_libraries != "NONE"; then
+    AC_CHECK_LIB([X11], XrmInitialize, 
+      [X11_LIBS="-L$x_libraries -lX11"], [X11_LIBS=], "-L$x_libraries")
+  fi
+  AC_SUBST(X11_LIBS)
+fi
+
+### Check for the Carbon framework on MacOSX systems
+OCTAVE_HAVE_FRAMEWORK([Carbon],
+  [[#include <Carbon/Carbon.h>]], [[CGMainDisplayID ()]],
+  [have_framework_carbon=yes], [have_framework_carbon=no])
+if test $have_framework_carbon = yes; then
+  AC_DEFINE(HAVE_FRAMEWORK_CARBON, 1,
+    [Define to 1 if framework CARBON is available.])
+  CARBON_LIBS="-Wl,-framework -Wl,Carbon"
+  AC_MSG_NOTICE([adding -Wl,-framework -Wl,Carbon to CARBON_LIBS])
+  AC_SUBST(CARBON_LIBS)
+fi
+
+### Check for list of libraries needed for native graphics renderer.
+
+native_graphics=yes
 warn_freetype=""
 
-check_opengl=false
+check_opengl=no
 AC_ARG_WITH([opengl],
-  [AS_HELP_STRING([--without-opengl], [don't use OpenGL libraries, disable native graphics])],
-  [if test "x$withval" = xno; then
+  [AS_HELP_STRING([--without-opengl],
+    [don't use OpenGL libraries, disable native graphics])],
+  [if test x"$withval" = x"no"; then
+     native_graphics=no
      warn_opengl="--without-opengl specified.  Native graphics will be disabled."
-     AC_MSG_WARN([$warn_opengl])
+     OCTAVE_CONFIGURE_WARNING([warn_opengl])
    else
-     check_opengl=true
+     check_opengl=yes
    fi],
-  [check_opengl=true])
-
-if $check_opengl; then
-  OCTAVE_OPENGL
+  [check_opengl=yes])
+
+## Check for OpenGL library
+if test $check_opengl = yes; then
+  OCTAVE_CHECK_LIB_OPENGL
 fi
 
 GRAPHICS_LIBS=
 GRAPHICS_CFLAGS=
 
 if test -z "$OPENGL_LIBS"; then
-  if $check_opengl; then
-    warn_fltk_opengl="OpenGL libs (GL and GLU) not found. Native graphics will be disabled."
+  if test $check_opengl = yes; then
+    native_graphics=no
+    warn_fltk_opengl="OpenGL libs (GL and GLU) not found.  Native graphics will be disabled."
+    OCTAVE_CONFIGURE_WARNING([warn_fltk_opengl])
   fi
 fi
 
 if test -n "$OPENGL_LIBS"; then
-  AC_DEFINE(HAVE_OPENGL, 1, [Define if OpenGL is available])
-
-  ## freetype 2
+  AC_DEFINE(HAVE_OPENGL, 1, [Define to 1 if OpenGL is available.])
+
+  ## Check for FreeType 2 library
 
   PKG_CHECK_MODULES([FT2], [freetype2], [
     min_ft2_version=9.03
@@ -871,41 +1046,51 @@
       warn_freetype="FreeType library not found.  Native graphics will be disabled."
     fi])
 
-  ## fontconfig library
+  if test -n "$warn_freetype"; then
+    OCTAVE_CONFIGURE_WARNING([warn_freetype])
+    native_graphics=no
+  fi
+
+  ## Check for fontconfig library
 
   warn_fontconfig=""
   if test -z "$warn_freetype"; then
-    PKG_CHECK_MODULES(FONTCONFIG, [fontconfig], [
-      have_fontconfig=yes
-      OPENGL_LIBS="$FONTCONFIG_LIBS $OPENGL_LIBS"
-      XTRA_CXXFLAGS="$XTRA_CXXFLAGS $FONTCONFIG_CFLAGS"
-      AC_DEFINE(HAVE_FONTCONFIG, 1, [Define to 1 if fontconfig is present])], [
-      have_fontconfig=no
-      warn_fontconfig="Fontconfig library not found.  Native graphics will be disabled."])
+    PKG_CHECK_MODULES(FONTCONFIG, [fontconfig],
+      [have_fontconfig=yes
+       OPENGL_LIBS="$FONTCONFIG_LIBS $OPENGL_LIBS"
+       XTRA_CXXFLAGS="$XTRA_CXXFLAGS $FONTCONFIG_CFLAGS"
+       AC_DEFINE(HAVE_FONTCONFIG, 1, [Define to 1 if fontconfig is present.])],
+      [have_fontconfig=no
+       warn_fontconfig="Fontconfig library not found.  Native graphics will be disabled."])
   fi
 
-  ## fltk (www.fltk.org)
+  if test -n "$warn_fontconfig"; then
+    native_graphics=no
+    OCTAVE_CONFIGURE_WARNING([warn_fontconfig])
+  fi
+
+  ## Check for FLTK (www.fltk.org) library
 
   AC_ARG_WITH([fltk-prefix], [
     AS_HELP_STRING([--with-fltk-prefix=PFX],
-      [Prefix where FLTK is installed (optional)])], [
-    fltk_prefix="$withval"], [
-    fltk_prefix=""])
+      [prefix where FLTK is installed (optional)])],
+    [fltk_prefix="$withval"],
+    [fltk_prefix=""])
 
   AC_ARG_WITH([fltk-exec-prefix], [
     AS_HELP_STRING([--with-fltk-exec-prefix=PFX],
-      [Exec prefix where FLTK is installed (optional)])], [
-    fltk_exec_prefix="$withval"], [
-    fltk_exec_prefix=""])
-
-  if test -n "$fltk_exec_prefix"; then
+      [exec prefix where FLTK is installed (optional)])],
+    [fltk_exec_prefix="$withval"],
+    [fltk_exec_prefix=""])
+
+  if test x"$fltk_exec_prefix" != x""; then
     fltk_args="$fltk_args --exec-prefix=$fltk_exec_prefix"
     if test "x${FLTK_CONFIG+set}" != xset ; then
       FLTK_CONFIG="$fltk_exec_prefix/bin/fltk-config"
     fi
   fi
 
-  if test -n "$fltk_prefix"; then
+  if test x"$fltk_prefix" != x""; then
     fltk_args="$fltk_args --prefix=$fltk_prefix"
     if test x${FLTK_CONFIG+set} != xset ; then
       FLTK_CONFIG="$fltk_prefix/bin/fltk-config"
@@ -917,43 +1102,64 @@
   warn_fltk_config=""
   warn_fltk_opengl=""
 
-  if test "$FLTK_CONFIG" = "no" ; then
+  if test "$FLTK_CONFIG" = no; then
+    native_graphics=no
     warn_fltk_config="FLTK config script not found.  Native graphics will be disabled."
+    OCTAVE_CONFIGURE_WARNING([warn_fltk_config])
   else
-    FLTK_CFLAGS="`$FLTK_CONFIG $fltkconf_args --use-gl --cflags`"
-    FLTK_LDFLAGS="`$FLTK_CONFIG $fltkconf_args --use-gl --ldflags`"
-
-    case "$canonical_host_type" in
-      *-*-mingw*)
-        FLTK_LDFLAGS="`echo $FLTK_LDFLAGS | sed -e 's/-mwindows//g'`"
+    FLTK_CFLAGS=`$FLTK_CONFIG $fltkconf_args --use-gl --cflags`
+    FLTK_LDFLAGS=`$FLTK_CONFIG $fltkconf_args --use-gl --ldflags`
+
+    case $host_os in
+      mingw*)
+        FLTK_LDFLAGS=`echo $FLTK_LDFLAGS | sed -e 's/-mwindows//g'`
       ;;
     esac
 
-    AC_MSG_CHECKING([for OpenGL support in FLTK])
-    save_CFLAGS="$CFLAGS"
-    CFLAGS="$CFLAGS $FLTK_CFLAGS"
-    AC_COMPILE_IFELSE(
-      [AC_LANG_PROGRAM([[#include <FL/gl.h>]], [[int nothing = 0;]])],
-        [
-         AC_MSG_RESULT([no])
-         warn_fltk_opengl="FLTK does not have OpenGL support.  Native graphics will be disabled."
-        ],[
-         AC_DEFINE(HAVE_FLTK, 1, [Define if FLTK is available])
-         AC_MSG_RESULT([yes])
-        ])
-         
+    AC_CACHE_CHECK([for OpenGL support in FLTK],
+      [octave_cv_fltk_opengl_support],
+      [save_CFLAGS="$CFLAGS"
+      CFLAGS="$CFLAGS $FLTK_CFLAGS"
+      AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+        #include <FL/gl.h>
+        ]], [[
+        int nothing = 0;
+        ]])],
+        octave_cv_fltk_opengl_support=no,
+        octave_cv_fltk_opengl_support=yes)
+      CFLAGS="$save_CFLAGS"
+      ])
+    if test $octave_cv_fltk_opengl_support = no; then
+      warn_fltk_opengl="FLTK does not have OpenGL support.  Native graphics will be disabled."
+    else
+      AC_DEFINE(HAVE_FLTK, 1, [Define to 1 if FLTK is available.])
+    fi 
+
     if test -z "$warn_fltk_opengl"; then
       GRAPHICS_CFLAGS="$FLTK_CFLAGS"
       GRAPHICS_LIBS="$FLTK_LDFLAGS"
+    else
+      native_graphics=no
+      OCTAVE_CONFIGURE_WARNING([warn_fltk_opengl])
     fi
-    CFLAGS="$save_CFLAGS"
   fi
 fi
 
 AC_SUBST(GRAPHICS_CFLAGS)
 AC_SUBST(GRAPHICS_LIBS)
 
-# ----------------------------------------------------------------------
+### Start determination of shared vs. static libraries
+
+## Use -static if compiling on Alpha OSF/1 1.3 systems.
+case $canonical_host_type in
+  alpha*-dec-osf1.3)
+    LD_STATIC_FLAG=-static
+  ;;
+esac
+if test -n "$LD_STATIC_FLAG"; then
+  AC_MSG_NOTICE([defining LD_STATIC_FLAG to be $LD_STATIC_FLAG])
+fi
+AC_SUBST(LD_STATIC_FLAG)
 
 OCTAVE_PROG_AR
 
@@ -965,26 +1171,26 @@
 LT_PREREQ([2.2.2])
 LT_INIT([disable-static dlopen win32-dll])
 
-if test x$enable_shared = xyes; then
-  SHARED_LIBS=true
+if test x"$enable_shared" = x"yes"; then
+  SHARED_LIBS=yes
 else
-  SHARED_LIBS=false
+  SHARED_LIBS=no
 fi
 
-if test x$enable_static = xyes; then
-  STATIC_LIBS=true
+if test x"$enable_static" = x"yes"; then
+  STATIC_LIBS=yes
 else
-  STATIC_LIBS=false
+  STATIC_LIBS=no
 fi
 
 XTRA_CRUFT_SH_LDFLAGS=
-if test "$have_msvc" = "yes"; then
+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)
 
-### Checks for BLAS and LAPACK libraries:
+### Check for BLAS and LAPACK libraries:
 
 ## Need to adjust FFLAGS to include correct integer size.
 save_FFLAGS="$FFLAGS"
@@ -996,8 +1202,8 @@
 ## Restore FFLAGS.
 FFLAGS="$save_FFLAGS"
 
-## Try again with -ff2c in FFLAGS
-if test "x$ax_blas_f77_func_ok" = "xno"; then
+## If necessary, try again with -ff2c in FFLAGS
+if test $ax_blas_f77_func_ok = no; then
   save_FFLAGS="$FFLAGS"
   FFLAGS="-ff2c $FFLAGS $F77_INTEGER_8_FLAG"
 
@@ -1006,7 +1212,7 @@
 
   ## Restore FFLAGS, with -ff2c if that was helpful
 
-  if test "x$ax_blas_f77_func_ok" = "xno"; then
+  if test $ax_blas_f77_func_ok = no; then
     FFLAGS="$save_FFLAGS"
   else
     FFLAGS="-ff2c $save_FFLAGS"
@@ -1014,161 +1220,174 @@
 fi
 
 ## On OSX, try again with a wrapper library (without -ff2c!)
-if test "x$ax_blas_f77_func_ok" = "xno"; then
-  case "$canonical_host_type" in
-    *-*-darwin*)
+if test $ax_blas_f77_func_ok = no; then
+  case $host_os in
+    darwin*)
       ## test if wrapper functions help
       octave_blaswrap_save_CFLAGS="$CFLAGS"
       CFLAGS="$CFLAGS -DUSE_BLASWRAP"
       AC_LANG_PUSH(C)
-      AC_COMPILE_IFELSE([AC_LANG_SOURCE([
-#include "libcruft/misc/blaswrap.c"
-])],
-       [mv conftest.$ac_objext blaswrap.$ac_objext
-        octave_blaswrap_save_BLAS_LIBS="$BLAS_LIBS"
-        BLAS_LIBS="blaswrap.$ac_objext -framework vecLib"
-
-        save_FFLAGS="$FFLAGS"
-        FFLAGS="$FFLAGS $F77_INTEGER_8_FLAG"
-
-        AX_BLAS_WITH_F77_FUNC([:], [:])
-        AX_LAPACK([:], [:])
-
-        ## Restore FFLAGS.
-        FFLAGS="$save_FFLAGS"
-
-        ## remove temp file
-        rm -f blaswrap.$ac_objext],
-       [AC_MSG_FAILURE([cannot compile libcruft/misc/blaswrap.c])])
+      AC_COMPILE_IFELSE([AC_LANG_SOURCE([[
+          #include "liboctave/cruft/misc/blaswrap.c"
+        ]])],
+        [mv conftest.$ac_objext blaswrap.$ac_objext
+         octave_blaswrap_save_BLAS_LIBS="$BLAS_LIBS"
+         BLAS_LIBS="blaswrap.$ac_objext -framework vecLib"
+
+         save_FFLAGS="$FFLAGS"
+         FFLAGS="$FFLAGS $F77_INTEGER_8_FLAG"
+
+         AX_BLAS_WITH_F77_FUNC([:], [:])
+         AX_LAPACK([:], [:])
+
+         ## Restore FFLAGS.
+         FFLAGS="$save_FFLAGS"
+
+         ## remove temp file
+         rm -f blaswrap.$ac_objext],
+        [AC_MSG_FAILURE([cannot compile liboctave/cruft/misc/blaswrap.c])])
       AC_LANG_POP(C)
       CFLAGS="$octave_blaswrap_save_CFLAGS"
 
-      if test "x$ax_blas_f77_func_ok" = "xno"; then
+      if test $ax_blas_f77_func_ok = no; then
         BLAS_LIBS="$octave_blaswrap_save_BLAS_LIBS"
       else
-        ## wrapper in libcruft, remove from BLAS_LIBS
-        BLAS_LIBS="`echo $BLAS_LIBS | sed -e 's/blaswrap.[[^ ]]* //g'`"
-        AC_DEFINE(USE_BLASWRAP, [1], [Define this if BLAS functions need to be wrapped (potentially needed for 64-bit OSX only).])
+        ## wrapper in cruft, remove from BLAS_LIBS
+        BLAS_LIBS=`echo $BLAS_LIBS | sed -e 's/blaswrap.[[^ ]]* //g'`
+        AC_DEFINE(USE_BLASWRAP, 1,
+          [Define to 1 if BLAS functions need to be wrapped (potentially needed for 64-bit OSX only).])
       fi
     ;;
   esac
 fi
 
-if test "x$ax_blas_f77_func_ok" = "xno"; then
-  if $USE_64_BIT_IDX_T && test "$ax_blas_integer_size_ok" = "no" ; then
+if test $ax_blas_f77_func_ok = no; then
+  if test $USE_64_BIT_IDX_T = yes && test $ax_blas_integer_size_ok = no; then
     ## Attempt to be more informative.
-    AC_MSG_ERROR([BLAS doesn't seem to support 64-bit integers. This is incompatible with --enable-64.])
+    AC_MSG_ERROR([BLAS doesn't seem to support 64-bit integers.  This is incompatible with --enable-64.])
   else
     AC_MSG_ERROR([A BLAS library was detected but found incompatible with your Fortran 77 compiler settings.])
   fi
 fi
 
-if test x$ax_blas_ok = xno || test x$ax_lapack_ok = xno; then
-  AC_MSG_ERROR([You are required to have BLAS and LAPACK libraries])
+if test $ax_blas_ok = no || test $ax_lapack_ok = no; then
+  AC_MSG_ERROR([BLAS and LAPACK libraries are required])
 fi
 
 ### Check for the qrupdate library
+
 ## No need to adjust FFLAGS because only link is attempted. 
 ## Must supply proper LIBS, however.
-
 save_LIBS="$LIBS"
 LIBS="$LAPACK_LIBS $BLAS_LIBS $FLIBS $LIBS"
-OCTAVE_CHECK_LIBRARY(qrupdate, qrupdate,
+OCTAVE_CHECK_LIB(qrupdate, qrupdate,
   [qrupdate not found.  The QR & Cholesky updating functions will be slow.],
   [],
   [sqr1up],
   [Fortran 77], [don't use qrupdate, disable QR & Cholesky updating functions])
 
-if test "$octave_qrupdate_ok" = yes; then
-  LIBS="$LIBS $QRUPDATE_LIBS"
-  AC_LANG_PUSH([Fortran 77])
-  AC_MSG_CHECKING([for slup1up in $QRUPDATE_LIBS])
-  octave_qrupdate_luu=no
-  AC_LINK_IFELSE([AC_LANG_CALL([], [slup1up])],
-  [octave_qrupdate_luu=yes])
-  AC_MSG_RESULT([$octave_qrupdate_luu])
-  if test "$octave_qrupdate_luu" = yes; then
-    AC_DEFINE(HAVE_QRUPDATE_LUU, [1], [Define if qrupdate supports LU updates])
+if test $octave_cv_lib_qrupdate = yes; then
+  AC_CACHE_CHECK([for slup1up in $QRUPDATE_LIBS],
+    [octave_cv_func_slup1up],
+    [LIBS="$LIBS $QRUPDATE_LIBS"
+    AC_LANG_PUSH([Fortran 77])
+    AC_LINK_IFELSE([AC_LANG_CALL([], [slup1up])],
+      octave_cv_func_slup1up=yes, octave_cv_func_slup1up=no)
+    AC_LANG_POP([Fortran 77])
+  ])
+  if test $octave_cv_func_slup1up = yes; then
+    AC_DEFINE(HAVE_QRUPDATE_LUU, 1, [Define to 1 if qrupdate supports LU updates.])
   fi
-  AC_LANG_POP([Fortran 77])
 fi
 LIBS="$save_LIBS"
 
-# Check for AMD library
-
-OCTAVE_CHECK_LIBRARY(amd, AMD,
+if test $USE_64_BIT_IDX_T = yes; then
+  CHOLMOD_TAG="_l_"
+  CXSPARSE_TAG="_dl_"
+  UMFPACK_TAG="_zl_"
+else
+  CHOLMOD_TAG="_"
+  CXSPARSE_TAG="_di_"
+  UMFPACK_TAG="_zi_"
+fi
+
+### Check for AMD library
+
+OCTAVE_CHECK_LIB(amd, AMD,
   [AMD library not found.  This will result in some lack of functionality for sparse matrices.],
   [suitesparse/amd.h ufsparse/amd.h amd/amd.h amd.h],
   [amd_postorder],
   [], [don't use AMD library, disable some sparse matrix functionality])
 
-# Check for CAMD library
-
-OCTAVE_CHECK_LIBRARY(camd, CAMD,
+### Check for CAMD library
+
+OCTAVE_CHECK_LIB(camd, CAMD,
   [CAMD library not found.  This will result in some lack of functionality for sparse matrices.],
   [suitesparse/camd.h ufsparse/camd.h camd/camd.h camd.h],
   [camd_postorder],
   [], [don't use CAMD library, disable some sparse matrix functionality])
 
-# Check for COLAMD library
-
-OCTAVE_CHECK_LIBRARY(colamd, COLAMD,
+### Check for COLAMD library
+
+OCTAVE_CHECK_LIB(colamd, COLAMD,
   [COLAMD library not found.  This will result in some lack of functionality for sparse matrices.],
   [suitesparse/colamd.h ufsparse/colamd.h colamd/colamd.h colamd.h],
   [colamd],
   [], [don't use COLAMD library, disable some sparse matrix functionality])
 
-# Check for CCOLAMD library
-
-OCTAVE_CHECK_LIBRARY(ccolamd, CCOLAMD,
+### Check for CCOLAMD library
+
+OCTAVE_CHECK_LIB(ccolamd, CCOLAMD,
   [CCOLAMD library not found.  This will result in some lack of functionality for sparse matrices.],
   [suitesparse/ccolamd.h ufsparse/ccolamd.h ccolamd/ccolamd.h ccolamd.h],
   [ccolamd],
   [], [don't use CCOLAMD library, disable some sparse matrix functionality])
 
-# Check for CHOLMOD library.  If your cholmod library requires cblas,
-# then you will need to configure with --with-cholmod="-lcholmod -lcblas".
+### Check for CHOLMOD library.
+### If your cholmod library requires cblas, then you will need to
+### configure with --with-cholmod="-lcholmod -lcblas".
 
 save_LIBS="$LIBS"
 LIBS="$COLAMD_LDFLAGS $COLAMD_LIBS $AMD_LDFLAGS $AMD_LIBS $LAPACK_LIBS $BLAS_LIBS $FLIBS $LIBS"
-OCTAVE_CHECK_LIBRARY(cholmod, CHOLMOD,
+OCTAVE_CHECK_LIB(cholmod, CHOLMOD,
   [CHOLMOD library not found.  This will result in some lack of functionality for sparse matrices.],
   [suitesparse/cholmod.h ufsparse/cholmod.h cholmod/cholmod.h cholmod.h],
-  [cholmod_start],
+  [cholmod${CHOLMOD_TAG}start],
   [], [don't use CHOLMOD library, disable some sparse matrix functionality])
 LIBS="$save_LIBS"
 
-# Check for CXSparse library
-
-OCTAVE_CHECK_LIBRARY(cxsparse, CXSparse,
+### Check for CXSparse library
+
+OCTAVE_CHECK_LIB(cxsparse, CXSparse,
   [CXSparse library not found.  This will result in some lack of functionality for sparse matrices.],
   [suitesparse/cs.h ufsparse/cs.h cxsparse/cs.h cs.h],
-  [cs_di_sqr],
+  [cs${CXSPARSE_TAG}sqr],
   [C++], [don't use CXSparse library, disable some sparse matrix functionality])
 
-# Check for UMFPACK library.
+### Check for UMFPACK library.
 
 save_LIBS="$LIBS"
 save_CPPFLAGS="$CPPFLAGS"
 LIBS="$AMD_LDFLAGS $AMD_LIBS $BLAS_LIBS $FLIBS $LIBS"
 CPPFLAGS="$AMD_CPPFLAGS $CPPFLAGS"
-OCTAVE_CHECK_LIBRARY(umfpack, UMFPACK,
+OCTAVE_CHECK_LIB([umfpack], UMFPACK,
   [UMFPACK not found.  This will result in some lack of functionality for sparse matrices.],
   [suitesparse/umfpack.h ufsparse/umfpack.h umfpack/umfpack.h umfpack.h],
-  [umfpack_zi_get_determinant],
+  [umfpack${UMFPACK_TAG}get_determinant],
   [], [don't use UMFPACK, disable some sparse matrix functionality])
 CPPFLAGS="$save_CPPFLAGS"
 LIBS="$save_LIBS"
 
 if test -z "$UMFPACK_LIBS"; then
   ## Invalidate the cache and try again with -lcblas.
-  $as_unset ac_cv_lib_umfpack_umfpack_zi_get_determinant
+  $as_unset ac_cv_lib_umfpack_umfpack${UMFPACK_TAG}get_determinant
+  $as_unset octave_cv_lib_umfpack
   save_LIBS="$LIBS"
   LIBS="-lcblas $AMD_LDFLAGS $AMD_LIBS $BLAS_LIBS $FLIBS $LIBS"
-  OCTAVE_CHECK_LIBRARY(umfpack, UMFPACK,
+  OCTAVE_CHECK_LIB([umfpack], UMFPACK,
     [UMFPACK not found.  This will result in some lack of functionality for sparse matrices.],
     [suitesparse/umfpack.h ufsparse/umfpack.h umfpack/umfpack.h umfpack.h],
-    [umfpack_zi_get_determinant],
+    [umfpack${UMFPACK_TAG}get_determinant],
     [], [don't use UMFPACK, disable some sparse matrix functionality])
   if test -n "$UMFPACK_LIBS"; then
     UMFPACK_LIBS="$UMFPACK_LIBS -lcblas"
@@ -1176,44 +1395,79 @@
   LIBS="$save_LIBS"
 fi
 
+## Test features of the installed UMFPACK library
+
 if test -n "$UMFPACK_LIBS"; then
+  ## SuiteSparse >= 4.0 needs additional link library for SuiteSparse_time()
   save_LIBS="$LIBS";
-  LIBS="$UMFPACK_LIBS $AMD_LIBS $BLAS_LIBS $FLIBS $LIBS"
-  OCTAVE_UMFPACK_SEPERATE_SPLIT
+  LIBS="$UMFPACK_LIBS $AMD_LDFLAGS $AMD_LIBS $BLAS_LIBS $FLIBS $LIBS"
+  xtra_libs=
+  OCTAVE_UMFPACK_NEED_SUITESPARSE_TIME
+  if test $octave_cv_umfpack_need_suitesparse_time = yes; then
+    AC_CHECK_LIB([rt], [clock_gettime], [xtra_libs="-lrt"], [xtra_libs=])
+    ## FIXME: This library list is only accurate for Linux, Mac OS X.
+    ##        Possibly need other library names for MinGW, Cygwin.
+    AC_SEARCH_LIBS([SuiteSparse_time],
+                   [suitesparseconfig SuiteSparse],
+                   [], [], [$xtra_libs])
+    case $ac_cv_search_SuiteSparse_time in
+      -l*)  
+        UMFPACK_LIBS="$UMFPACK_LIBS $ac_cv_search_SuiteSparse_time"
+      ;;
+      no)
+        UMFPACK_LIBS=
+        AC_MSG_WARN([UMFPACK library found but is missing SuiteSparse_time functionality.])
+        AC_MSG_WARN([UMFPACK library will be disabled.])
+      ;;
+    esac
+  fi
   LIBS="$save_LIBS"
+
+  ## Check for UMFPACK separately split complex matrix and RHS.
+  if test -n "$UMFPACK_LIBS"; then
+    save_LIBS="$LIBS";
+    LIBS="$UMFPACK_LIBS $CHOLMOD_LDFLAGS $CHOLMOD_LIBS $AMD_LDFLAGS $AMD_LIBS $COLAMD_LDFLAGS $COLAMD_LIBS $LAPACK_LIBS $BLAS_LIBS $FLIBS $LIBS $xtra_libs"
+    OCTAVE_UMFPACK_SEPARATE_SPLIT
+    LIBS="$save_LIBS"
+  fi
 fi
 
+### Check for ARPACK library.
+
 save_LIBS="$LIBS"
 LIBS="$LAPACK_LIBS $BLAS_LIBS $FLIBS $LIBS"
-OCTAVE_CHECK_LIBRARY(arpack, ARPACK,
+OCTAVE_CHECK_LIB([arpack], ARPACK,
   [ARPACK not found.  The eigs function will be disabled.],
   [],
   [dseupd],
   [Fortran 77], [don't use the ARPACK library, disable eigs function],
   [warn_arpack=
-   OCTAVE_CHECK_ARPACK_OK([
-     AC_DEFINE(HAVE_ARPACK, 1, [Define if ARPACK is available.])], [
-     warn_arpack="ARPACK library found, but seems not to work properly -- disabling eigs function"])])
+   OCTAVE_CHECK_LIB_ARPACK_OK(
+     [AC_DEFINE(HAVE_ARPACK, 1, [Define to 1 if ARPACK is available.])],
+     [warn_arpack="ARPACK library found, but does not seem to work properly -- disabling eigs function"])])
 LIBS="$save_LIBS"
 
+### Check for readline library.
+
+OCTAVE_ENABLE_READLINE
+
 ### Enable dynamic linking.  --enable-shared implies this, so
 ### --enable-dl is only need if you are only building static libraries
 ### and want to try dynamic linking too (works on some systems, for
 ### example, OS X and Windows).
 
 AC_ARG_ENABLE([dl],
-  [AS_HELP_STRING([--enable-dl],
-    [allow loading of dynamically linked modules (not all systems)])], [
-  case "${enableval}" in
-    yes) ENABLE_DYNAMIC_LINKING=true ;;
-    no) ENABLE_DYNAMIC_LINKING=false ;;
-    *) AC_MSG_ERROR([bad value ${enableval} for --enable-dl]) ;;
-  esac], [ENABLE_DYNAMIC_LINKING=true])
-
-if $STATIC_LIBS || $SHARED_LIBS; then
-  true
-else
-  AC_MSG_ERROR([You can't disable building static AND shared libraries!])
+  [AS_HELP_STRING([--disable-dl],
+    [disable loading of dynamically linked modules])],
+  [case $enableval in
+     yes) ENABLE_DYNAMIC_LINKING=yes ;;
+     no) ENABLE_DYNAMIC_LINKING=no ;;
+     *) AC_MSG_ERROR([bad value $enableval for --enable-dl]) ;;
+   esac],
+  [ENABLE_DYNAMIC_LINKING=no])
+
+if test $STATIC_LIBS = no && test $SHARED_LIBS = no; then
+  AC_MSG_ERROR([You can't disable building both static AND shared libraries!])
 fi
 
 CPICFLAG=-fPIC
@@ -1242,11 +1496,12 @@
 CRUFT_DLL_DEFS=
 OCTAVE_DLL_DEFS=
 OCTINTERP_DLL_DEFS=
+OCTGUI_DLL_DEFS=
 OCTGRAPHICS_DLL_DEFS=
 library_path_var=LD_LIBRARY_PATH
 ldpreloadsep=" "
-BUILD_COMPILED_AUX_PROGRAMS=false
-case "$canonical_host_type" in
+BUILD_COMPILED_AUX_PROGRAMS=no
+case $canonical_host_type in
   *-*-386bsd* | *-*-netbsd*)
     SH_LD=ld
     SH_LDFLAGS=-Bshareable
@@ -1264,10 +1519,10 @@
     SH_LDFLAGS="-shared -Wl,-expect_unresolved -Wl,'*'"
   ;;
   *-*-darwin*)
-    DL_LDFLAGS='-bundle -bundle_loader $(top_builddir)/src/octave $(LDFLAGS)'
+    DL_LDFLAGS='-bundle -bundle_loader $(top_builddir)/libinterp/octave $(LDFLAGS)'
     MKOCTFILE_DL_LDFLAGS='-bundle -bundle_loader $$BINDIR/octave-$$OCTAVE_VERSION$$EXEEXT'
     SH_LDFLAGS='-dynamiclib -single_module $(LDFLAGS)'
-    case "$canonical_host_type" in
+    case $canonical_host_type in
       powerpc-*)
         CXXPICFLAG=
         CPICFLAG=
@@ -1298,8 +1553,8 @@
     ldpreloadsep=":"
   ;;
   *-*-mingw*)
-    BUILD_COMPILED_AUX_PROGRAMS=true
-    if test "$have_msvc" = "yes"; then
+    BUILD_COMPILED_AUX_PROGRAMS=yes
+    if test $have_msvc = yes; then
       DL_LDFLAGS="-shared"
       CPICFLAG=
       CXXPICFLAG=
@@ -1312,17 +1567,17 @@
       SHLLIBPRE=
       SHLBINPRE=
       SH_LDFLAGS="-shared"
-      if test -n "`echo $CFLAGS | grep -e '-g'`" -o -n "`echo $CXXFLAGS | grep -e '-g'`"; then
+      if test -n "`echo $CFLAGS | grep -e '-g'`" || test -n "`echo $CXXFLAGS | grep -e '-g'`"; then
         DL_LDFLAGS="$DL_LDFLAGS -g"
         SH_LDFLAGS="$SH_LDFLAGS -g"
       fi
       NO_OCT_FILE_STRIP=true
       library_path_var=PATH
-      NO_OCT_FILE_STRIP=true
       ## Extra compilation flags.
       CRUFT_DLL_DEFS="-DCRUFT_DLL"
       OCTAVE_DLL_DEFS="-DOCTAVE_DLL"
       OCTINTERP_DLL_DEFS="-DOCTINTERP_DLL"
+      OCTGUI_DLL_DEFS="-DOCTGUI_DLL"
       OCTGRAPHICS_DLL_DEFS="-DOCTGRAPHICS_DLL"
     else
       CPICFLAG=
@@ -1339,7 +1594,7 @@
   ;;
 
   *-*-msdosmsvc)
-    BUILD_COMPILED_AUX_PROGRAMS=true
+    BUILD_COMPILED_AUX_PROGRAMS=yes
     DL_LDFLAGS="-shared"
     CPICFLAG=
     CXXPICFLAG=
@@ -1352,17 +1607,16 @@
     SHLLIBPRE=
     SHLBINPRE=
     SH_LDFLAGS="-shared"
-    if test -n "`echo $CFLAGS | grep -e '-g'`" -o -n "`echo $CXXFLAGS | grep -e '-g'`"; then
+    if test -n "`echo $CFLAGS | grep -e '-g'`" || test -n "`echo $CXXFLAGS | grep -e '-g'`"; then
       DL_LDFLAGS="$DL_LDFLAGS -g"
       SH_LDFLAGS="$SH_LDFLAGS -g"
     fi
     NO_OCT_FILE_STRIP=true
     library_path_var=PATH
-    NO_OCT_FILE_STRIP=true
     ## Extra compilation flags.
     CRUFT_DLL_DEFS="-DCRUFT_DLL"
     OCTAVE_DLL_DEFS="-DOCTAVE_DLL"
-    OCTINTERP_DLL_DEFS="-DOCTINTERP_DLL"
+    OCTGUI_DLL_DEFS="-DOCTGUI_DLL"
     OCTGRAPHICS_DLL_DEFS="-DOCTGRAPHICS_DLL"
   ;;
   *-*-linux* | *-*-gnu*)
@@ -1380,7 +1634,7 @@
     library_path_var=LIBPATH
   ;;
   hppa*-hp-hpux*)
-    if test "$ac_cv_f77_compiler_gnu" = yes; then
+    if test $ac_cv_f77_compiler_gnu = yes; then
       FPICFLAG=-fPIC
     else
       FPICFLAG=+Z
@@ -1390,7 +1644,7 @@
     library_path_var=SHLIB_PATH
   ;;
   ia64*-hp-hpux*)
-    if test "$ac_cv_f77_compiler_gnu" = yes; then
+    if test $ac_cv_f77_compiler_gnu = yes; then
       FPICFLAG=-fPIC
     else
       FPICFLAG=+Z
@@ -1403,7 +1657,7 @@
     FPICFLAG=
   ;;
   sparc-sun-sunos4*)
-    if test "$ac_cv_f77_compiler_gnu" = yes; then
+    if test $ac_cv_f77_compiler_gnu = yes; then
       FPICFLAG=-fPIC
     else
       FPICFLAG=-PIC
@@ -1412,7 +1666,7 @@
     SH_LDFLAGS="-assert nodefinitions"
   ;;
   sparc-sun-solaris2* | i386-pc-solaris2*)
-    if test "$ac_cv_f77_compiler_gnu" = yes; then
+    if test $ac_cv_f77_compiler_gnu = yes; then
       FPICFLAG=-fPIC
     else
       FPICFLAG=-KPIC
@@ -1430,9 +1684,7 @@
       SH_LDFLAGS=-G
     fi
     ## Template closures in archive libraries need a different mechanism.
-    if test "$GXX" = yes; then
-      true
-    else
+    if test "$GXX" != yes; then
       TEMPLATE_AR='$(CXX)'
       TEMPLATE_ARFLAGS="-xar -o"
     fi
@@ -1440,7 +1692,7 @@
 esac
 
 AM_CONDITIONAL([AMCOND_BUILD_COMPILED_AUX_PROGRAMS],
-  [test x$BUILD_COMPILED_AUX_PROGRAMS = xtrue])
+  [test $BUILD_COMPILED_AUX_PROGRAMS = yes])
 
 AC_MSG_NOTICE([defining FPICFLAG to be $FPICFLAG])
 AC_MSG_NOTICE([defining CPICFLAG to be $CPICFLAG])
@@ -1468,6 +1720,7 @@
 AC_MSG_NOTICE([defining CRUFT_DLL_DEFS to be $CRUFT_DLL_DEFS])
 AC_MSG_NOTICE([defining OCTAVE_DLL_DEFS to be $OCTAVE_DLL_DEFS])
 AC_MSG_NOTICE([defining OCTINTERP_DLL_DEFS to be $OCTINTERP_DLL_DEFS])
+AC_MSG_NOTICE([defining OCTGUI_DLL_DEFS to be $OCTGUI_DLL_DEFS])
 AC_MSG_NOTICE([defining OCTGRAPHICS_DLL_DEFS to be $OCTGRAPHICS_DLL_DEFS])
 AC_MSG_NOTICE([defining library_path_var to be $library_path_var])
 AC_SUBST(FPICFLAG)
@@ -1496,258 +1749,77 @@
 AC_SUBST(CRUFT_DLL_DEFS)
 AC_SUBST(OCTAVE_DLL_DEFS)
 AC_SUBST(OCTINTERP_DLL_DEFS)
+AC_SUBST(OCTGUI_DLL_DEFS)
 AC_SUBST(OCTGRAPHICS_DLL_DEFS)
 AC_SUBST(library_path_var)
 AC_SUBST(ldpreloadsep)
 
-### special checks for odd OS specific things.
-
-AC_CHECK_FUNCS(getpwnam, [], [AC_CHECK_LIB(sun, getpwnam)])
-
-case "$canonical_host_type" in
-  *-*-mingw*)
-    if test "$have_msvc" = "yes"; then
-      AC_CHECK_LIB(dirent, opendir)
-      LIBS="$LIBS -ladvapi32 -lgdi32 -lws2_32 -luser32 -lkernel32"
-    else
-      LIBS="$LIBS -lgdi32 -lws2_32 -luser32 -lkernel32"
-    fi
-    LIBS="$LIBS -lgdi32 -lws2_32 -luser32 -lkernel32"
-  ;;
-  *-*-msdosmsvc*)
-    AC_CHECK_LIB(dirent, opendir)
-    LIBS="$LIBS -ladvapi32 -lgdi32 -lws2_32 -luser32 -lkernel32"
-  ;;
-esac
+### More configure argument checking related to linking
 
 AC_ARG_ENABLE([no-undefined],
-  [AS_HELP_STRING([--enable-no-undefined],
-    [pass -no-undefined to libtool when linking Octave and its shared libraries (on by default)])],
-  [case "${enableval}" in
-    yes) NO_UNDEFINED_LDFLAG="-no-undefined" ;;
-    no)  NO_UNDEFINED_LDFLAG="" ;;
-    *) AC_MSG_ERROR([bad value ${enableval} for --enable-link-all-depenencies]) ;;
-   esac], [NO_UNDEFINED_LDFLAG="-no-undefined"])
+  [AS_HELP_STRING([--disable-no-undefined],
+    [don't pass -no-undefined to libtool when linking Octave and its shared libraries])],
+  [case $enableval in
+     yes) NO_UNDEFINED_LDFLAG="-no-undefined" ;;
+     no)  NO_UNDEFINED_LDFLAG="" ;;
+     *) AC_MSG_ERROR([bad value $enableval for --disable-no-undefined]) ;;
+   esac],
+  [NO_UNDEFINED_LDFLAG="-no-undefined"])
 AC_SUBST(NO_UNDEFINED_LDFLAG)
 
 AC_ARG_ENABLE([link-all-dependencies],
   [AS_HELP_STRING([--enable-link-all-dependencies],
     [link Octave and its shared libraries with all dependencies, not just those immediately referenced (should not be needed on most systems)])],
-  [case "${enableval}" in
-    yes) link_all_deps=true ;;
-    no)  link_all_deps=false ;;
-    *) AC_MSG_ERROR([bad value ${enableval} for --enable-link-all-depenencies]) ;;
-   esac], [link_all_deps=false])
-AM_CONDITIONAL([AMCOND_LINK_ALL_DEPS], [test x$link_all_deps = xtrue])
-
-### Type stuff.
-
-AC_TYPE_MODE_T
-AC_TYPE_OFF_T
-AC_TYPE_PID_T
-AC_TYPE_SIZE_T
-AC_TYPE_UID_T
-AC_CHECK_TYPES([dev_t, ino_t])
-AC_CHECK_TYPES([long long int, unsigned long long int])
-
-### How big are ints and how are they oriented?  These could probably
-### be eliminated in favor of run-time checks.
-
-AC_CHECK_SIZEOF(short)
-AC_CHECK_SIZEOF(int)
-AC_CHECK_SIZEOF(long)
-AC_CHECK_SIZEOF(long long)
-
-### Does the C compiler handle alloca() and const correctly?
-
-AC_FUNC_ALLOCA
-
-### See if we should use placement delete.
-
-OCTAVE_PLACEMENT_DELETE
-
-### See if we can auto allocate variable sized arrays.
-
-OCTAVE_DYNAMIC_AUTO_ARRAYS
-
-### See if we can use fast integer arithmetics
-
-OCTAVE_FAST_INT_OPS
-
-### Check for long double type (for 64-bit integers)
-
-AC_CHECK_SIZEOF(long double)
-
-### Checks for header files.
-
-AC_HEADER_DIRENT
-AC_HEADER_SYS_WAIT
-
-### C headers
-
-AC_CHECK_HEADERS(curses.h direct.h dlfcn.h floatingpoint.h grp.h \
-  ieeefp.h inttypes.h locale.h memory.h ncurses.h poll.h pthread.h \
-  pwd.h sunmath.h sys/ioctl.h sys/param.h sys/poll.h sys/resource.h \
-  sys/select.h sys/utsname.h termcap.h)
-
-### C++ headers
-
-AC_LANG_PUSH(C++)
-AC_CHECK_HEADERS(sstream)
-AC_CHECK_HEADERS([unordered_map], [], [
-  AC_CHECK_HEADERS([tr1/unordered_map])])
-AC_MSG_CHECKING([whether unordered_map requires tr1 namespace])
-unordered_map_requires_tr1_namespace=no
-if test "$ac_cv_header_unordered_map" = "yes"; then
-  ### Have <unordered_map>, but still have to check whether
-  ### tr1 namespace is required (like MSVC, for instance).
-  AC_COMPILE_IFELSE([
-    AC_LANG_PROGRAM([
-      #include <unordered_map>
-    ], [
-      std::unordered_map m;
-    ])], [], [unordered_map_requires_tr1_namespace=yes])
-elif test "$ac_cv_header_tr1_unordered_map" = "yes"; then
-  unordered_map_requires_tr1_namespace=yes
-fi
-if test "$unordered_map_requires_tr1_namespace" = "yes"; then
-  AC_DEFINE(USE_UNORDERED_MAP_WITH_TR1, 1, [Defines whether unordered_map requires the use of tr1 namespace.])
-fi
-AC_MSG_RESULT([$unordered_map_requires_tr1_namespace])
-AC_LANG_POP(C++)
-
-have_termios_h=no
-AC_CHECK_HEADERS(termios.h, have_termios_h=yes)
-AC_CHECK_HEADERS(termio.h, have_termio_h=yes, have_termio_h=no)
-AC_CHECK_HEADERS(sgtty.h, have_sgtty_h=yes, have_sgtty_h=no)
-AC_CHECK_HEADERS(fnmatch.h, have_fnmatch_h=yes, have_fnmatch_h=no)
-AC_CHECK_HEADERS(conio.h, have_conio_h=yes, have_conio_h=no)
-
-if test "$have_termios_h" = yes \
-    || test "$have_termio_h" = yes \
-    || test "$have_sgtty_h" = yes; then
-  true
-else
-  AC_MSG_WARN([I couldn't find termios.h, termio.h, or sgtty.h!])
-fi
-
-### Checks for functions and variables.
-
-AC_CHECK_FUNCS(basename canonicalize_file_name \
-  chmod dup2 endgrent endpwent execvp expm1 expm1f fork \
-  getegid geteuid getgid getgrent getgrgid getgrnam getpgrp getpid \
-  getppid getpwent getpwuid getuid getwd _kbhit kill \
-  lgamma lgammaf lgamma_r lgammaf_r localtime_r log1p log1pf \
-  mkstemp pipe putenv \
-  realpath resolvepath rindex roundl select setgrent setlocale \
-  setpwent setvbuf siglongjmp \
-  strsignal tempnam tgammaf umask \
-  uname utime waitpid \
-  _chmod x_utime _utime32)
-
-AC_LANG_PUSH(C++)
-AC_CHECK_DECLS([exp2, round, tgamma], [], [], [[#include <cmath>]])
-AC_CHECK_FUNCS([exp2 round tgamma])
-AH_VERBATIM([Z_FUNCS_AND_DECLS], [
-#if defined (__cplusplus)
-extern "C" {
-#endif
-#if HAVE_EXP2 && ! HAVE_DECL_EXP2
-double exp2 (double );
-#endif
-#if HAVE_ROUND && ! HAVE_DECL_ROUND
-double round (double);
-#endif
-#if HAVE_TGAMMA && ! HAVE_DECL_TGAMMA
-double tgamma (double);
-#endif
-#if defined (__cplusplus)
-}
-#endif
-])
-AC_LANG_POP(C++)
-
-case "$canonical_host_type" in
-  *-*-mingw*)
-    ## MinGW does not provide a mkstemp function.  However, it provides
-    ## the mkstemps function in libiberty.
-    AC_MSG_CHECKING([for mkstemps in libiberty])
-    save_LIBS="$LIBS"
-    LIBS="-liberty $LIBS"
-    AC_LINK_IFELSE([
-      AC_LANG_PROGRAM([[int mkstemps (char *pattern, int suffix_len);]], 
-       [[mkstemps ("XXXXXX", 0);]]
-    )],
-    [AC_MSG_RESULT(yes)
-     HAVE_MKSTEMPS=yes
-     AC_DEFINE(HAVE_MKSTEMPS, 1, [Define if mkstemps is available in libiberty.])
-    ],
-    [AC_MSG_RESULT(no)
-     HAVE_MKSTEMPS=no
-     LIBS="$save_LIBS"
-    ])
-   ;;
-esac
-
-OCTAVE_SMART_PUTENV
-
-case "$canonical_host_type" in
-  *-*-msdosmsvc | *-*-mingw*)
-    AC_MSG_CHECKING([for required _WIN32_WINNT])
-    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
-#include <windows.h>
-#if _WIN32_WINNT < 0x0403
-#error "Wrong version"
-#endif]], [])],
-      AC_MSG_RESULT([none]), [
-        AC_DEFINE(_WIN32_WINNT, 0x0403, [Define to 0x0403 to access InitializeCriticalSectionAndSpinCount])
-        AC_MSG_RESULT([0x0403])])
-    AC_MSG_CHECKING([whether _USE_MATH_DEFINES needs to be defined])
-    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <math.h>]],
-[[int x = M_LN2;]])],
-      AC_MSG_RESULT([no]), [
-        AC_DEFINE(_USE_MATH_DEFINES, 1, [Define if your system needs it to define math constants like M_LN2])
-        AC_MSG_RESULT([yes])])
-  ;;
-esac
-
-### Dynamic linking is now enabled only if we are building shared
-### libs and some API for dynamic linking is detected.
-
-## FIXME -- a lot of the following duplicates the functionality of
+  [case $enableval in
+     yes) link_all_deps=yes ;;
+     no)  link_all_deps=no ;;
+     *) AC_MSG_ERROR([bad value $enableval for --enable-link-all-depenencies])
+     ;;
+   esac],
+  [link_all_deps=no])
+AM_CONDITIONAL([AMCOND_LINK_ALL_DEPS], [test $link_all_deps = yes])
+
+## Dynamic linking is now enabled only if we are building shared
+## libs and some API for dynamic linking has been detected.
+
+## FIXME: A lot of the following duplicates the functionality of
 ## code generated by the dlopen option for LT_INIT.
 
 LD_CXX='$(CXX)'
 RDYNAMIC_FLAG=
 DL_API_MSG=""
-dlopen_api=false
-shl_load_api=false
-loadlibrary_api=false
-dyld_api=false
-
-if $SHARED_LIBS || $ENABLE_DYNAMIC_LINKING; then
-
-  case "$lt_cv_dlopen" in
+dlopen_api=no
+shl_load_api=no
+loadlibrary_api=no
+dyld_api=no
+
+if test $SHARED_LIBS = yes || test $ENABLE_DYNAMIC_LINKING = yes; then
+
+  case $lt_cv_dlopen in
     dlopen)
-      dlopen_api=true
+      dlopen_api=yes
       DL_API_MSG="(dlopen)"
-      AC_DEFINE(HAVE_DLOPEN_API, 1, [Define if your system has dlopen, dlsym, dlerror, and dlclose for dynamic linking])
-      OCTAVE_CXX_FLAG(-rdynamic, [RDYNAMIC_FLAG=-rdynamic])
+      AC_DEFINE(HAVE_DLOPEN_API, 1,
+        [Define to 1 if your system has dlopen, dlsym, dlerror, and dlclose for dynamic linking.])
+      OCTAVE_CXX_FLAG([-rdynamic], [RDYNAMIC_FLAG=-rdynamic])
     ;;
     shl_load)
-      shl_load_api=true
+      shl_load_api=yes
       DL_API_MSG="(shl_load)"
-      AC_DEFINE(HAVE_SHL_LOAD_API, 1, [Define if your system has shl_load and shl_findsym for dynamic linking])
+      AC_DEFINE(HAVE_SHL_LOAD_API, 1,
+        [Define to 1 if your system has shl_load and shl_findsym for dynamic linking.])
     ;;
     LoadLibrary)
-      loadlibrary_api=true
+      loadlibrary_api=yes
       DL_API_MSG="(LoadLibrary)"
-      AC_DEFINE(HAVE_LOADLIBRARY_API, 1, [Define if your system has LoadLibrary for dynamic linking])
+      AC_DEFINE(HAVE_LOADLIBRARY_API, 1,
+        [Define to 1 if your system has LoadLibrary for dynamic linking.])
     ;;
     dyld)
-      dyld_api=true
+      dyld_api=yes
       DL_API_MSG="(dyld)"
-      AC_DEFINE(HAVE_DYLD_API, 1, [Define if your system has dyld for dynamic linking])
+      AC_DEFINE(HAVE_DYLD_API, 1,
+        [Define to 1 if your system has dyld for dynamic linking.])
     ;;
   esac
 
@@ -1755,28 +1827,30 @@
   AC_SUBST(DL_LIBS)
 
   ## Disable dynamic linking if capability is not present.
-  if $dlopen_api || $shl_load_api || $loadlibrary_api || $dyld_api; then
-    true
+  if test $dlopen_api = yes \
+      || test $shl_load_api = yes \
+      || test $loadlibrary_api = yes \
+      || test $dyld_api = yes; then
+    # some form of dynamic linking present
+    ENABLE_DYNAMIC_LINKING=yes
   else
-    ENABLE_DYNAMIC_LINKING=false
+    ENABLE_DYNAMIC_LINKING=no
   fi
 fi
 
-if $ENABLE_DYNAMIC_LINKING; then
-  AC_DEFINE(ENABLE_DYNAMIC_LINKING, 1, [Define if using dynamic linking])
+if test $ENABLE_DYNAMIC_LINKING = yes; then
+  AC_DEFINE(ENABLE_DYNAMIC_LINKING, 1, [Define to 1 if using dynamic linking.])
 fi
 
 AM_CONDITIONAL([AMCOND_ENABLE_DYNAMIC_LINKING],
-  [test x$ENABLE_DYNAMIC_LINKING = xtrue])
-
-if $SHARED_LIBS; then
-   LIBOCTINTERP=-loctinterp$SHLLINKEXT
-   LIBOCTAVE=-loctave$SHLLINKEXT
-   LIBCRUFT=-lcruft$SHLLINKEXT
+  [test $ENABLE_DYNAMIC_LINKING = yes])
+
+if test $SHARED_LIBS = yes; then
+  LIBOCTINTERP="-loctinterp$SHLLINKEXT"
+  LIBOCTAVE="-loctave$SHLLINKEXT"
 else
-  LIBOCTINTERP='$(top_builddir)/src/liboctinterp.$(LIBEXT)'
+  LIBOCTINTERP='$(top_builddir)/libinterp/liboctinterp.$(LIBEXT)'
   LIBOCTAVE='$(top_builddir)/liboctave/liboctave.$(LIBEXT)'
-  LIBCRUFT='$(top_builddir)/libcruft/libcruft.$(LIBEXT)'
 fi
 
 AC_SUBST(LD_CXX)
@@ -1784,13 +1858,7 @@
 AC_SUBST(ENABLE_DYNAMIC_LINKING)
 AC_SUBST(LIBOCTINTERP)
 AC_SUBST(LIBOCTAVE)
-AC_SUBST(LIBCRUFT)
-
-dnl Maybe <cmath> defines the IEEE functions we need.
-
-OCTAVE_CMATH_FUNC(isnan)
-OCTAVE_CMATH_FUNC(isinf)
-OCTAVE_CMATH_FUNC(isfinite)
+
 
 if test "$cross_compiling" = yes && test -n "$ac_tool_prefix"; then
   CROSS_TOOL_PREFIX="$ac_tool_prefix"
@@ -1829,130 +1897,342 @@
 
 ### Check for existence of various libraries
 
-dnl Would like to get rid of this cruft, and just have
-dnl
-dnl   AC_CHECK_FUNCS(finite isnan isinf)
-dnl
-dnl instead, but that used to fail on some systems...
-dnl
-dnl Also just using AC_CHECK_FUNCS doesn't seem to work to find isinf
-dnl and isnan on Linux systems, so we use AC_CHECK_FUNC, and if that
-dnl fails, we try again by including math.h and invoking the function
-dnl with an argument. 
-
-### I am told that Inf and NaN don't work on m68k HP sytems.
-
-case "$canonical_host_type" in
-  m68k-hp-hpux*)
+## OS-specific test for dirent, opendir.
+case $host_os in
+  mingw*)
+    if test $have_msvc = yes; then
+      AC_CHECK_LIB([dirent], [opendir])
+      LIBS="$LIBS -ladvapi32 -lgdi32 -lws2_32 -luser32 -lkernel32"
+    else
+      LIBS="$LIBS -lgdi32 -lws2_32 -luser32 -lkernel32"
+    fi
+    LIBS="$LIBS -lgdi32 -lws2_32 -luser32 -lkernel32"
   ;;
-  *)
-    AC_CHECK_FUNCS(finite isnan isinf signbit)
-    AC_CHECK_FUNCS(_finite _isnan)
-    AC_CHECK_DECLS(signbit, , , [#include <math.h>])
+  msdosmsvc)
+    AC_CHECK_LIB([dirent], [opendir])
+    LIBS="$LIBS -ladvapi32 -lgdi32 -lws2_32 -luser32 -lkernel32"
   ;;
 esac
 
-### Check for nonstandard but common math functions that we need.
-
-AC_CHECK_FUNCS(acosh acoshf asinh asinhf atanh atanhf erf erff erfc erfcf exp2f log2 log2f)
-AC_CHECK_FUNCS(hypotf _hypotf cbrt cbrtf)
-
-### Checks for OS specific cruft.
-
-AC_CHECK_MEMBERS([struct stat.st_blksize, struct stat.st_blocks, struct stat.st_rdev])
+## Find a termlib to use.
+OCTAVE_CHECK_LIB_TERMLIB
+
+### Checks for header files.
+
+AC_HEADER_DIRENT
+AC_HEADER_SYS_WAIT
+
+## C headers
+
+dnl Use multiple AC_CHECKs to avoid line continuations '\' in list
+AC_CHECK_HEADERS([curses.h direct.h dlfcn.h floatingpoint.h fpu_control.h])
+AC_CHECK_HEADERS([grp.h ieeefp.h inttypes.h locale.h memory.h ncurses.h])
+AC_CHECK_HEADERS([poll.h pthread.h pwd.h sunmath.h sys/ioctl.h])
+AC_CHECK_HEADERS([sys/param.h sys/poll.h sys/resource.h ])
+AC_CHECK_HEADERS([sys/select.h sys/utsname.h termcap.h])
+
+## C++ headers
+
+AC_LANG_PUSH(C++)
+
+AC_CHECK_HEADERS([sstream])
+OCTAVE_UNORDERED_MAP_HEADERS
+
+AC_LANG_POP(C++)
+
+## Find a termio header to include.
+
+AC_CHECK_HEADERS([termios.h], have_termios_h=yes, have_termios_h=no)
+AC_CHECK_HEADERS([termio.h], have_termio_h=yes, have_termio_h=no)
+AC_CHECK_HEADERS([sgtty.h], have_sgtty_h=yes, have_sgtty_h=no)
+AC_CHECK_HEADERS([fnmatch.h], have_fnmatch_h=yes, have_fnmatch_h=no)
+AC_CHECK_HEADERS([conio.h], have_conio_h=yes, have_conio_h=no)
+
+if test $have_termios_h != yes \
+    && test $have_termio_h != yes \
+    && test $have_sgtty_h != yes; then
+  AC_MSG_WARN([I couldn't find termios.h, termio.h, or sgtty.h!])
+fi
+
+## For MSVC compilers, avoid #define of min/max from windows.h header
+if test $have_msvc = yes; then
+  AC_DEFINE(NOMINMAX, 1, [Define to 1 if you want to avoid min/max macro definition in Windows headers.])
+fi
+
+### Determine types and size of types.
+
+AC_TYPE_INT64_T
+AC_TYPE_MODE_T
+AC_TYPE_OFF_T
+AC_TYPE_PID_T
+AC_TYPE_SIZE_T
+AC_TYPE_SSIZE_T
+AC_TYPE_UID_T
+AC_TYPE_UINT64_T
+AC_CHECK_TYPES([dev_t, ino_t])
+AC_CHECK_TYPES([long long int, unsigned long long int])
+AC_CHECK_TYPES([ptrdiff_t])
+
+## How big are ints and how are they oriented?
+## These could probably be eliminated in favor of run-time checks.
+
+AC_CHECK_SIZEOF([short])
+AC_CHECK_SIZEOF([int])
+AC_CHECK_SIZEOF([long])
+AC_CHECK_SIZEOF([long long])
+## Check for long double type (for 64-bit integers)
+AC_CHECK_SIZEOF([long double])
+
+### Check structures and existence of necessary members
+
+AC_CHECK_MEMBERS([struct stat.st_blksize, struct stat.st_blocks,
+                  struct stat.st_rdev])
+AC_CHECK_MEMBERS([struct group.gr_passwd])
 
 AC_STRUCT_TIMEZONE
+
+### Check compiler characteristics.
+
+## Does compiler have support for new friend template declarations?
+OCTAVE_CXX_NEW_FRIEND_TEMPLATE_DECL
+
+## Does reinterpret_cast fail for function pointers?
+OCTAVE_CXX_BROKEN_REINTERPRET_CAST
+
+## Check if C++ compiler allows placement delete.
+OCTAVE_CXX_PLACEMENT_DELETE
+
+## Check if C++ compiler can auto allocate variable sized arrays.
+OCTAVE_CXX_DYNAMIC_AUTO_ARRAYS
+
+## Check that C compiler and libraries support IEEE754 data format.
+OCTAVE_IEEE754_DATA_FORMAT
+
+## Is C++ runtime library ISO compliant?
+OCTAVE_CXX_ISO_COMPLIANT_LIBRARY
+
+## Are bit_and, bit_or, and bit_xor defined as templated operators?
+OCTAVE_CXX_BITWISE_OP_TEMPLATES
+
+## Can complex class set components independently?
+OCTAVE_CXX_COMPLEX_SETTERS
+
+## Are there functions to access real/imag parts of numbers via references?
+OCTAVE_CXX_COMPLEX_REFERENCE_ACCESSORS
+
+## Check if fast integer arithmetics based on bit tricks is available.
+OCTAVE_FAST_INT_OPS
+
+## Does the C compiler handle alloca() and const correctly?
+AC_FUNC_ALLOCA
+
+## Does the C compiler support Automake subdir-objects option?
+AM_PROG_CC_C_O 
+
+### gnulib initialization: part 2
+### After all include and path modifications have taken place
+### and at the same priority level as function checks.
+
+gl_INIT
+
+### Checks for functions and variables.
+
+dnl These checks define/undefine HAVE_FUNCNAME in config.h.
+dnl Code tests HAVE_FUNCNAME and either uses function or provides workaround.
+dnl Use multiple AC_CHECKs to avoid line continuations '\' in list
+AC_CHECK_FUNCS([canonicalize_file_name dup2])
+AC_CHECK_FUNCS([endgrent endpwent execvp expm1 expm1f fork])
+AC_CHECK_FUNCS([getegid geteuid getgid getgrent getgrgid getgrnam])
+AC_CHECK_FUNCS([getpgrp getpid getppid getpwent getpwuid getuid])
+AC_CHECK_FUNCS([isascii kill])
+AC_CHECK_FUNCS([lgamma lgammaf lgamma_r lgammaf_r])
+AC_CHECK_FUNCS([log1p log1pf pipe])
+AC_CHECK_FUNCS([realpath resolvepath roundl])
+AC_CHECK_FUNCS([select setgrent setpwent siglongjmp strsignal])
+AC_CHECK_FUNCS([tempnam tgammaf toascii])
+AC_CHECK_FUNCS([umask uname waitpid])
+AC_CHECK_FUNCS([_kbhit])
+
+dnl There are no workarounds in the code for missing these functions.
+AC_CHECK_FUNCS([modf pow sqrt sqrtf], [],
+               [AC_MSG_ERROR([Missing function required to build Octave])])
+
+## exp2, round, tgamma function checks
+AC_LANG_PUSH(C++)
+AC_CHECK_DECLS([exp2, round, tgamma], [], [], [[#include <cmath>]])
+AC_CHECK_FUNCS([exp2 round tgamma])
+AH_VERBATIM([Z_FUNCS_AND_DECLS], [
+#if defined (__cplusplus)
+extern "C" {
+#endif
+#if HAVE_EXP2 && ! HAVE_DECL_EXP2
+double exp2 (double);
+#endif
+#if HAVE_ROUND && ! HAVE_DECL_ROUND
+double round (double);
+#endif
+#if HAVE_TGAMMA && ! HAVE_DECL_TGAMMA
+double tgamma (double);
+#endif
+#if defined (__cplusplus)
+}
+#endif
+])
+AC_LANG_POP(C++)
+
+## Look in <cmath> for the IEEE functions isnan, isinf, isfinite that we need.
+
+OCTAVE_CHECK_FUNC_CMATH(isnan)
+OCTAVE_CHECK_FUNC_CMATH(isinf)
+OCTAVE_CHECK_FUNC_CMATH(isfinite)
+
+## Check for Inf and NaN functions
+
+case $canonical_host_type in
+  m68k-hp-hpux*)
+    ## I am told that Inf and NaN don't work on m68k HP sytems.
+  ;;
+  *)
+    AC_CHECK_FUNCS([finite isnan isinf signbit])
+    AC_CHECK_FUNCS([_finite _isnan])
+    AC_CHECK_DECLS([signbit], , , [#include <math.h>])
+  ;;
+esac
+
+## Check for nonstandard, but common math functions, that we need.
+
+dnl Use multiple AC_CHECKs to avoid line continuations '\' in list
+AC_CHECK_FUNCS([acosh acoshf asinh asinhf atanh atanhf cbrt cbrtf])
+AC_CHECK_FUNCS([erf erff erfc erfcf exp2f hypotf _hypotf log2 log2f])
+
+## Check for math defines such as M_LN2 in math.h
+AC_CACHE_CHECK([for MATH DEFINES in math.h],
+  [octave_cv_header_math_defines],
+  [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+    #include <math.h>
+    ]], [[
+    double x = M_LN2;]])],
+    octave_cv_header_math_defines=yes,
+    octave_cv_header_math_defines=no)
+  ])
+
+if test $octave_cv_header_math_defines = no; then
+  ## Check again and try defining _USE_MATH_DEFINES
+  AC_CACHE_CHECK([whether _USE_MATH_DEFINES needs to be defined],
+    [octave_cv_header__use_math_defines],
+    [save_CPPFLAGS="$CPPFLAGS"
+    CPPFLAGS="$CPPFLAGS -D_USE_MATH_DEFINES"
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+      #include <math.h>
+      ]], [[
+      double x = M_LN2;]])],
+      octave_cv_header__use_math_defines=yes,
+      octave_cv_header__use_math_defines=no)
+    CPPFLAGS="$save_CPPFLAGS"
+    ])
+  if test $octave_cv_header__use_math_defines = yes; then
+    octave_cv_header_math_defines=yes
+    AC_DEFINE(_USE_MATH_DEFINES, 1,
+      [Define to 1 if _USE_MATH_DEFINES is required to get math constants like M_LN2.])
+    CPPFLAGS="$CPPFLAGS -D_USE_MATH_DEFINES"
+  fi
+fi 
+
+if test $octave_cv_header_math_defines = yes; then
+  AC_DEFINE(HAVE_MATH_DEFINES, 1,
+    [Define to 1 if defines such as M_PI are available in math.h])
+else
+  AC_MSG_ERROR([MATH DEFINES in math.h such as M_PI are required to build Octave])
+fi
+
+## Windows-specific tests for extra #defines
+case $host_os in
+  msdosmsvc | mingw*)
+    AC_MSG_CHECKING([for required _WIN32_WINNT])
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+        #include <windows.h>
+        #if _WIN32_WINNT < 0x0403
+        #error "Wrong version"
+        #endif
+        ]], [])],
+      [AC_MSG_RESULT([none])],
+      [AC_DEFINE(_WIN32_WINNT, 0x0403,
+        [Define to 0x0403 to access InitializeCriticalSectionAndSpinCount.])
+       AC_MSG_RESULT([0x0403])])
+  ;;
+esac
+
+## Windows-specific use of functions
+case $host_os in
+  msdosmsvc | mingw*)
+    AC_CHECK_FUNCS([setvbuf], [],
+                   [AC_MSG_ERROR([Missing function required to build Octave])])
+    ;;
+esac
+
+## Cygwin kluge for getrusage.
+AC_CHECK_FUNCS([getrusage])
+case $host_os in
+  cygwin*)
+    AC_DEFINE(RUSAGE_TIMES_ONLY, 1,
+      [Define to 1 if your struct rusage only has time information.])
+  ;;
+esac
+
+## Check for CGDisplayBitsPerPixel function on Mac OSX systems with Carbon
+if test $have_framework_carbon = yes; then
+  OCTAVE_CARBON_CGDISPLAYBITSPERPIXEL
+fi
+
+AC_CHECK_FUNCS([getpwnam], [], [AC_CHECK_LIB([sun], [getpwnam])])
+
 AC_FUNC_CLOSEDIR_VOID
 
-AC_CHECK_MEMBERS(struct group.gr_passwd)
-
-octave_found_termlib=no
-for termlib in ncurses curses termcap terminfo termlib; do
-  AC_CHECK_LIB(${termlib}, tputs, [
-    TERM_LIBS="-l${termlib}"
-    octave_found_termlib=yes
-    break])
-done
-
-if test "$octave_found_termlib" = no; then
-  warn_termlibs="I couldn't find -ltermcap, -lterminfo, -lncurses, -lcurses, o\
-r -ltermlib!"
-  AC_MSG_WARN([$warn_termlibs])
+## Check return type of matherr() 
+AC_CACHE_CHECK([for struct exception in math.h],
+  [octave_cv_func_matherr_type],
+  [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+      #include <math.h>
+      ]], [[
+      struct exception *x;
+      x->type;
+      x->name;
+      ]])],
+    octave_cv_func_matherr_type=yes,
+    octave_cv_func_matherr_type=no)
+  ])
+if test $octave_cv_func_matherr_type = yes; then
+  AC_DEFINE(EXCEPTION_IN_MATH, 1,
+    [Define to 1 if math.h declares struct exception for matherr().])
 fi
-AC_SUBST(TERM_LIBS)
-
-OCTAVE_ENABLE_READLINE
-
-AC_MSG_CHECKING([for struct exception in math.h])
-AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <math.h>]],
-  [[struct exception *x; x->type; x->name;]])],
-  [AC_MSG_RESULT(yes)
-   AC_DEFINE(EXCEPTION_IN_MATH, 1,
-     [Define if your math.h declares struct exception for matherr().])],
-  [AC_MSG_RESULT(no)])
-
-### Signal stuff.
+ 
+## Signal stuff.
 
 AC_CHECK_DECLS([sys_siglist], [], [],
-[#include <signal.h>
+[[#include <signal.h>
 /* NetBSD declares sys_siglist in unistd.h.  */
 #if HAVE_UNISTD_H
 # include <unistd.h>
 #endif
-])
-
-### A system dependent kluge or two.
-
-AC_CHECK_FUNCS(getrusage)
-case "$canonical_host_type" in
-  *-*-cygwin*)
-    AC_DEFINE(RUSAGE_TIMES_ONLY, 1, [Define if your struct rusage only has time information.])
-  ;;
-esac
-
-### Checks for other programs used for building, testing, installing,
-### and running Octave.
-
-AC_PROG_AWK
-OCTAVE_PROG_FIND
-OCTAVE_PROG_SED
-OCTAVE_PROG_PERL
-OCTAVE_PROG_PYTHON
-
-OCTAVE_PROG_FLEX
-AC_SUBST([LEX_OUTPUT_ROOT], [lex.octave_])
-
-OCTAVE_PROG_BISON
-
-AC_PROG_LN_S
-
-AC_PROG_INSTALL
-INSTALL_SCRIPT='${INSTALL}'
-AC_SUBST(INSTALL_SCRIPT)
-
-OCTAVE_PROG_DESKTOP_FILE_INSTALL
-
-OCTAVE_PROG_GNUPLOT
-OCTAVE_PROG_PAGER
-OCTAVE_PROG_GPERF
-
-OCTAVE_PROG_GHOSTSCRIPT
-OCTAVE_PROG_TEXI2DVI
-OCTAVE_PROG_TEXI2PDF
-
-### 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)
+]])
+
+### Need to disable building documentation if either gnuplot or
+### makeinfo are missing.  Skip this warning if building docs was
+### disabled with a configure option.
+
+if test -n "$DOCDIR"; then
+  if test -n "$warn_gnuplot"; then
+    DOCDIR=
+    warn_docs_gnuplot="building documentation disabled because gnuplot was not found; make dist will fail"
+    OCTAVE_CONFIGURE_WARNING([warn_docs_gnuplot])
+  fi
+  if test -n "$warn_makeinfo"; then
+    DOCDIR=
+    warn_docs_makeinfo="building documentation disabled because makeinfo was not found; make dist will fail"
+    OCTAVE_CONFIGURE_WARNING([warn_docs_makeinfo])
+  fi
+fi
+AM_CONDITIONAL([AMCOND_BUILD_DOCS], [test -n "$DOCDIR"])
 
 ### Maybe add -Wall, -W, and -Wshadow to compiler flags now that we're
 ### done feature testing. 
@@ -1961,23 +2241,24 @@
 
 GXX_EXTRA_FLAGS="-Wall -W -Wshadow -Wold-style-cast -Wformat -Wpointer-arith -Wwrite-strings -Wcast-align -Wcast-qual"
 
-try_extra_warning_flags=true
-
-AC_ARG_ENABLE(extra-warning-flags,
-  [AS_HELP_STRING([--enable-extra-warning-flags],
-     [add -Wall, -W, -Wshadow, and -Wold-style-cast options to CFLAGS and CXXFLAGS  (on by default, but only if the compiler appears to accept them)])],
+try_extra_warning_flags=yes
+
+AC_ARG_ENABLE([extra-warning-flags],
+  [AS_HELP_STRING([--disable-extra-warning-flags],
+    [don't add -Wall, -W, -Wshadow, and -Wold-style-cast options to CFLAGS and CXXFLAGS])],
   [if test "$enableval" = no; then
-     try_extra_warning_flags=false
-   fi], [])
-
-if $try_extra_warning_flags; then
+     try_extra_warning_flags=no
+   fi],
+  [])
+
+if test $try_extra_warning_flags = yes; then
   for flag in $GCC_EXTRA_FLAGS; do
-    OCTAVE_CC_FLAG($flag, [
+    OCTAVE_CC_FLAG([$flag], [
       WARN_CFLAGS="$WARN_CFLAGS $flag";
       AC_MSG_RESULT([adding $flag to WARN_CFLAGS])])
   done
   for flag in $GXX_EXTRA_FLAGS; do
-    OCTAVE_CXX_FLAG($flag, [
+    OCTAVE_CXX_FLAG([$flag], [
       WARN_CXXFLAGS="$WARN_CXXFLAGS $flag";
       AC_MSG_RESULT([adding $flag to WARN_CXXFLAGS])])
   done
@@ -1987,23 +2268,24 @@
 
 GXX_STRICT_FLAGS="-Wconversion -Weffc++"
 
-try_strict_warning_flags=false
-
-AC_ARG_ENABLE(strict-warning-flags,
+try_strict_warning_flags=no
+
+AC_ARG_ENABLE([strict-warning-flags],
   [AS_HELP_STRING([--enable-strict-warning-flags],
-     [add extra strict warning options to CFLAGS and CXXFLAGS (off by default)])],
+    [add extra strict warning options to CFLAGS and CXXFLAGS])],
   [if test "$enableval" = yes; then
-     try_strict_warning_flags=true
-   fi], [])
-
-if $try_strict_warning_flags; then
+     try_strict_warning_flags=yes
+   fi],
+  [])
+
+if test $try_strict_warning_flags = yes; then
   for flag in $GCC_STRICT_FLAGS; do
-    OCTAVE_CC_FLAG($flag, [
+    OCTAVE_CC_FLAG([$flag], [
       WARN_CFLAGS="$WARN_CFLAGS $flag";
       AC_MSG_RESULT([adding $flag to WARN_CFLAGS])])
   done
   for flag in $GXX_STRICT_FLAGS; do
-    OCTAVE_CXX_FLAG($flag, [
+    OCTAVE_CXX_FLAG([$flag], [
       WARN_CXXFLAGS="$WARN_CXXFLAGS $flag";
       AC_MSG_RESULT([adding $flag to WARN_CXXFLAGS])])
   done
@@ -2012,161 +2294,406 @@
 AC_SUBST(WARN_CFLAGS)
 AC_SUBST(WARN_CXXFLAGS)
 
+### Check for Java.
+
+build_java=yes
+AC_ARG_ENABLE([java],
+  [AS_HELP_STRING([--disable-java],
+    [disable Java interface])],
+  [if test "$enableval" = no; then
+     build_java=no
+   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 = yes
+do
+  ## Unset build_java.  Variable is set only if all configuration tests pass.
+  build_java=no
+
+  ## 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 $host_os 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
+        ## 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/^[^ ]* 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) already have
+  ## the required paths to compile and link against JDK.
+  case $host_os in
+    msdosmsvc)
+      build_java=yes
+      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=yes
+        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 $host_os 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 $host_os in
+    darwin*)
+      ## Sneak the -framework flag into mkoctfile via LDFLAGS
+      LDFLAGS="$LDFLAGS -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=no
+  for dir in $JNI_PATH; do 
+    if test -f "${dir}/jni.h"; then have_jni=yes; break; fi
+  done
+  if test $have_jni = yes; 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=yes
+  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 = yes])
+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.
+
+QT_CPPFLAGS=
+QT_LDFLAGS=
+QT_LIBS=
+win32_terminal=no
+build_gui=yes
+AC_ARG_ENABLE([gui],
+  [AS_HELP_STRING([--disable-gui], [don't build the GUI])],
+  [if test "$enableval" = no; then build_gui=no; fi], [])
+
+if test $build_gui = yes; then
+  ## Check for Qt libraries
+  PKG_CHECK_MODULES(QT, [QtCore, QtGui, QtNetwork],
+    [],
+    [AC_MSG_WARN([Qt libraries not found -- disabling GUI])
+     build_gui=no])
+
+  if test $build_gui = yes; then
+    ## 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_WARN([Qt >= 4.0.0 not found -- disabling GUI])
+      build_gui=no
+    fi
+  fi
+
+  if test $build_gui = yes; then
+    AC_CHECK_PROGS(MOC, [moc-qt5 moc-qt4 moc])
+    AC_CHECK_PROGS(UIC, [uic-qt5 uic-qt4 uic])
+    AC_CHECK_PROGS(RCC, [rcc])
+    AC_CHECK_PROGS(LRELEASE, [lrelease-qt5 lrelease-qt4 lrelease])
+    if test -n "$MOC" && test -n "$UIC" && test -n "$RCC" && test -n "$LRELEASE"; then
+      AC_DEFINE(HAVE_QT, 1, 
+        [Define to 1 if Qt is available (libraries, developer header files, utility programs (moc, uic, rcc, and lrelease))])
+    else
+      AC_MSG_WARN([Qt utility programs moc, uic, rcc, and lrelease not found -- disabling GUI])
+      build_gui=no
+    fi
+  fi
+
+  if test $build_gui = yes; then
+    OCTAVE_CHECK_FUNC_SETPLACEHOLDERTEXT
+  fi
+
+  if test $build_gui = yes; then
+    ## Check for Qscintilla library which is used in the GUI editor. 
+    AC_CACHE_CHECK([whether Qscintilla library is installed],
+      [octave_cv_lib_qscintilla],
+      [save_CPPFLAGS="$CPPFLAGS"
+      save_LDFLAGS="$LDFLAGS"
+      save_LIBS="$LIBS"
+      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>
+        ]], [[
+        QsciLexerSQL sqlLexer(0);
+        ]])],
+        octave_cv_lib_qscintilla=yes,
+        octave_cv_lib_qscintilla=no)
+      CPPFLAGS="$save_CPPFLAGS"
+      LDFLAGS="$save_LDFLAGS"
+      LIBS="$save_LIBS"
+      AC_LANG_POP([C++])
+    ])
+    if test $octave_cv_lib_qscintilla = no; then
+      AC_MSG_WARN([Qscintilla library not found -- disabling built-in GUI editor])
+    else
+      ## Let's assume Qscintilla library is at the same location as
+      ## other regular Qt libraries.
+      QT_LIBS="$QT_LIBS -lqscintilla2"
+      OCTAVE_CHECK_FUNC_FINDFIRST_MODERN
+      AC_DEFINE(HAVE_QSCINTILLA, 1, 
+        [Define to 1 if the QScintilla library and header files are available])
+    fi
+
+    AC_CHECK_FUNCS([setlocale], [],
+      [AC_MSG_WARN([setlocale not found -- disabling GUI])
+       build_gui=no])
+
+    if test $build_gui = yes; then
+      case $host_os in
+        mingw* | msdosmsvc*)
+          AC_CHECK_FUNCS([setvbuf], [win32_terminal=yes],
+            [AC_MSG_WARN([setvbuf not found -- disabling GUI])
+             build_gui=no])
+          ;;
+        *)
+          AC_CHECK_HEADERS([pty.h libutil.h util.h])
+          AC_SEARCH_LIBS([openpty], [util],
+            [AC_DEFINE(HAVE_OPENPTY, [], [Define whether openpty exists])])
+          AC_CHECK_FUNCS([chmod chown ftruncate mmap munmap], [],
+            [AC_MSG_ERROR([At least one of chmod, chown, ftruncate, mmap, and munmap not found -- disabling GUI])
+             build_gui=no])
+          ;;
+      esac
+    fi
+  fi
+fi
+
+AM_CONDITIONAL([AMCOND_BUILD_GUI], [test $build_gui = yes])
+AM_CONDITIONAL([AMCOND_HAVE_QSCINTILLA], [test "$octave_cv_lib_qscintilla" = yes])
+AM_CONDITIONAL([WIN32_TERMINAL], [test $win32_terminal = yes])
+AC_SUBST(QT_CPPFLAGS)
+AC_SUBST(QT_LDFLAGS)
+AC_SUBST(QT_LIBS)
+
 ### Run configure in subdirectories.
 
 export CC
 export CXX
 export F77
 
-### Some things to add to the bottom of config.h.
-
-AH_BOTTOM([
-#if !defined (GNULIB_NAMESPACE)
-#define GNULIB_NAMESPACE gnulib
-#endif
-
-#if defined (__GNUC__)
-#define GCC_ATTR_DEPRECATED __attribute__ ((__deprecated__))
-#define GCC_ATTR_NORETURN __attribute__ ((__noreturn__))
-#define GCC_ATTR_UNUSED __attribute__ ((__unused__))
-#else
-#define GCC_ATTR_DEPRECATED
-#define GCC_ATTR_NORETURN
-#define GCC_ATTR_UNUSED
-#endif
-
-#define X_CAST(T, E) (T) (E)
-
-#if defined (CXX_BROKEN_REINTERPRET_CAST)
-#define FCN_PTR_CAST(T, E) (T) (E)
-#else
-#define FCN_PTR_CAST(T, E) reinterpret_cast<T> (E)
-#endif
-
-#if !defined(HAVE_DEV_T)
-typedef short dev_t;
-#endif
-
-#if !defined(HAVE_INO_T)
-typedef unsigned long ino_t;
-#endif
-
-#if defined (_MSC_VER)
-#define __WIN32__
-#define WIN32
-/* missing parameters in macros */
-#pragma warning (disable: 4003)
-/* missing implementations in template instantiation */
-#pragma warning (disable: 4996)
-/* deprecated function names (FIXME?) */
-#pragma warning (disable: 4661)
-#endif
-
-#if defined (__WIN32__) && ! defined (__CYGWIN__)
-#define OCTAVE_HAVE_WINDOWS_FILESYSTEM 1
-#elif defined (__CYGWIN__)
-#define OCTAVE_HAVE_WINDOWS_FILESYSTEM 1
-#define OCTAVE_HAVE_POSIX_FILESYSTEM 1
-#else
-#define OCTAVE_HAVE_POSIX_FILESYSTEM 1
-#endif
-
-/* Define if we expect to have <windows.h>, Sleep, etc. */
-#if defined (__WIN32__) && ! defined (__CYGWIN__)
-#define OCTAVE_USE_WINDOWS_API 1
-#endif
-
-#if defined (__APPLE__) && defined (__MACH__)
-#define OCTAVE_USE_OS_X_API 1
-#endif
-
-/* sigsetjmp is a macro, not a function. */
-#if defined (sigsetjmp) && defined (HAVE_SIGLONGJMP)
-#define OCTAVE_HAVE_SIG_JUMP
-#endif
-
-#if defined (_UNICOS)
-#define F77_USES_CRAY_CALLING_CONVENTION
-#endif
-
-#if 0
-#define F77_USES_VISUAL_FORTRAN_CALLING_CONVENTION
-#endif
-
-#ifdef USE_64_BIT_IDX_T
-#define SIZEOF_OCTAVE_IDX_TYPE 8
-#else
-#define SIZEOF_OCTAVE_IDX_TYPE SIZEOF_INT
-#endif
-
-/* To be able to use long doubles for 64-bit mixed arithmetics, we need
-   them at least 80 bits wide and we need roundl declared in math.h.
-   FIXME -- maybe substitute this by a more precise check in the future.  */
-#if (SIZEOF_LONG_DOUBLE >= 10) && defined (HAVE_ROUNDL)
-#define OCTAVE_INT_USE_LONG_DOUBLE
-#endif
-
-#define OCTAVE_EMPTY_CPP_ARG
-
-/* Octave is currently unable to use FFTW unless both float
-   and double versions are both available.  */
-#if defined (HAVE_FFTW3) && defined (HAVE_FFTW3F)
-#define HAVE_FFTW
-#endif
-
-/* Backward compatibility.  */
-#if defined (HAVE_Z)
-#define HAVE_ZLIB
-#endif
-
-/* oct-dlldefs.h */
-
-#if defined (_MSC_VER)
-#define OCTAVE_EXPORT __declspec(dllexport)
-#define OCTAVE_IMPORT __declspec(dllimport)
-#else
-/* All other compilers, at least for now. */
-#define OCTAVE_EXPORT
-#define OCTAVE_IMPORT
-#endif
-
-/* API macro for libcruft */
-#ifdef CRUFT_DLL
-#define CRUFT_API OCTAVE_EXPORT
-#else
-#define CRUFT_API OCTAVE_IMPORT
-#endif
-
-/* API macro for liboctave */
-#ifdef OCTAVE_DLL
-#define OCTAVE_API OCTAVE_EXPORT
-#else
-#define OCTAVE_API OCTAVE_IMPORT
-#endif
-
-/* API macro for src */
-#ifdef OCTINTERP_DLL
-#define OCTINTERP_API OCTAVE_EXPORT
-#else
-#define OCTINTERP_API OCTAVE_IMPORT
-#endif
-
-/* API macro for src/graphics */
-#ifdef OCTGRAPHICS_DLL
-#define OCTGRAPHICS_API OCTAVE_EXPORT
-#else
-#define OCTGRAPHICS_API OCTAVE_IMPORT
-#endif
-
-/* oct-types.h */
-
-typedef OCTAVE_IDX_TYPE octave_idx_type;
-
-#include <stdint.h>
-
-/* Tag indicating octave config.h has been included */
-#define OCTAVE_CONFIG_INCLUDED 1
-])
+AH_BOTTOM([#include "oct-conf-post.h"])
+
+### 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.
+
+AC_OUTPUT_MAKE_DEFS
 
 ### Do the substitutions in all the Makefiles.
 
@@ -2174,18 +2701,21 @@
 AC_SUBST(ac_config_headers)
 
 AC_CONFIG_FILES([
+  oct-conf-post.h:oct-conf-post.in.h
   Makefile 
   doc/Makefile
-  doc/faq/Makefile
+  doc/doxyhtml/Makefile
   doc/icons/Makefile
   doc/interpreter/Makefile
   doc/liboctave/Makefile
   doc/refcard/Makefile
   examples/Makefile
-  libcruft/Makefile
-  libcruft/mkf77def
   libgnu/Makefile
+  libgui/Makefile
+  libinterp/Makefile
   liboctave/Makefile
+  liboctave/cruft/Makefile
+  liboctave/cruft/mkf77def
   scripts/Makefile
   src/Makefile
   test/Makefile])
@@ -2241,31 +2771,45 @@
   FFTW3F LDFLAGS:              $FFTW3F_LDFLAGS
   FFTW3F libraries:            $FFTW3F_LIBS
   fontconfig CFLAGS:           $FONTCONFIG_CFLAGS
-  fontconfig LIBS:             $FONTCONFIG_LIBS
-  FT2_CFLAGS:                  $FT2_CFLAGS
-  FT2_LIBS:                    $FT2_LIBS
+  fontconfig libraries:        $FONTCONFIG_LIBS
+  FreeType2 CFLAGS:            $FT2_CFLAGS
+  FreeType2 libraries:         $FT2_LIBS
   GLPK CPPFLAGS:               $GLPK_CPPFLAGS
   GLPK LDFLAGS:                $GLPK_LDFLAGS
   GLPK libraries:              $GLPK_LIBS
   graphics CFLAGS:             $GRAPHICS_CFLAGS
-  graphics LIBS:               $GRAPHICS_LIBS
+  graphics libraries:          $GRAPHICS_LIBS
+  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
+  LLVM libraries:              $LLVM_LIBS
   Magick++ CPPFLAGS:           $MAGICK_CPPFLAGS
   Magick++ LDFLAGS:            $MAGICK_LDFLAGS
   Magick++ libraries:          $MAGICK_LIBS
-  HDF5 CPPFLAGS:               $HDF5_CPPFLAGS
-  HDF5 LDFLAGS:                $HDF5_LDFLAGS
-  HDF5 libraries:              $HDF5_LIBS
-  LAPACK libraries:            $LAPACK_LIBS
   OPENGL libraries:            $OPENGL_LIBS
   PTHREAD flags:               $PTHREAD_CFLAGS
   PTHREAD libraries:           $PTHREAD_LIBS
   QHULL CPPFLAGS:              $QHULL_CPPFLAGS
   QHULL LDFLAGS:               $QHULL_LDFLAGS
   QHULL libraries:             $QHULL_LIBS
+  QRUPDATE CPPFLAGS:           $QRUPDATE_CPPFLAGS
+  QRUPDATE LDFLAGS:            $QRUPDATE_LDFLAGS
   QRUPDATE libraries:          $QRUPDATE_LIBS
+  Qt CPPFLAGS:                 $QT_CPPFLAGS
+  Qt LDFLAGS:                  $QT_LDFLAGS
+  Qt libraries:                $QT_LIBS
   READLINE libraries:          $READLINE_LIBS
   REGEX libraries:             $REGEX_LIBS
   TERM libraries:              $TERM_LIBS
+  UMFPACK CPPFLAGS:            $UMFPACK_CPPFLAGS
+  UMFPACK LDFLAGS:             $UMFPACK_LDFLAGS
   UMFPACK libraries:           $UMFPACK_LIBS
   X11 include flags:           $X11_INCFLAGS
   X11 libraries:               $X11_LIBS
@@ -2276,6 +2820,9 @@
   Default pager:               $DEFAULT_PAGER
   gnuplot:                     $GNUPLOT
 
+  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
@@ -2287,167 +2834,17 @@
 
 warn_msg_printed=false
 
-if $ENABLE_DYNAMIC_LINKING; then
-  if $SHARED_LIBS; then
-    true
-  else
+OCTAVE_CONFIGURE_WARNING_SUMMARY
+
+if test $ENABLE_DYNAMIC_LINKING = yes; then
+  if test $SHARED_LIBS = no; then
     AC_MSG_WARN([You used --enable-dl but not --enable-shared.])
     AC_MSG_WARN([Are you sure that is what you want to do?])
     warn_msg_printed=true
   fi
 fi
 
-if test -n "$gxx_only"; then
-  AC_MSG_WARN([$gxx_only])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_gcc_version"; then
-  AC_MSG_WARN([$warn_gcc_version])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_gcc_only"; then
-  AC_MSG_WARN([$warn_gcc_only])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_readline"; then
-  AC_MSG_WARN([$warn_readline])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_termlibs"; then
-  AC_MSG_WARN([$warn_termlibs])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_gperf"; then
-  AC_MSG_WARN([$warn_gperf])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_flex"; then
-  AC_MSG_WARN([$warn_flex])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_bison"; then
-  AC_MSG_WARN([$warn_bison])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_less"; then
-  AC_MSG_WARN([$warn_less])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_umfpack"; then
-  AC_MSG_WARN([$warn_umfpack])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_qrupdate"; then
-  AC_MSG_WARN([$warn_qrupdate])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_amd"; then
-  AC_MSG_WARN([$warn_amd])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_colamd"; then
-  AC_MSG_WARN([$warn_colamd])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_ccolamd"; then
-  AC_MSG_WARN([$warn_ccolamd])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_cholmod"; then
-  AC_MSG_WARN([$warn_cholmod])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_cxsparse"; then
-  AC_MSG_WARN([$warn_cxsparse])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_curl"; then
-  AC_MSG_WARN([$warn_curl])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_fftw"; then
-  AC_MSG_WARN([$warn_fftw])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_glpk"; then
-  AC_MSG_WARN([$warn_glpk])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_magick"; then
-  AC_MSG_WARN([$warn_magick])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_hdf5"; then
-  AC_MSG_WARN([$warn_hdf5])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_regex"; then
-  AC_MSG_WARN([$warn_regex])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_pcre"; then
-  AC_MSG_WARN([$warn_pcre])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_qhull"; then
-  AC_MSG_WARN([$warn_qhull])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_zlib"; then
-  AC_MSG_WARN([$warn_zlib])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_ghostscript"; then
-  AC_MSG_WARN([$warn_ghostscript])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_texi2dvi"; then
-  AC_MSG_WARN([$warn_texi2dvi])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_texi2pdf"; then
-  AC_MSG_WARN([$warn_texi2pdf])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_docs"; then
-  AC_MSG_WARN([$warn_docs])
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_64_bit"; then
-  AC_MSG_WARN([$warn_64_bit])
-  warn_msg_printed=true
-fi
-
-if $USE_64_BIT_IDX_T; then
+if test $USE_64_BIT_IDX_T = yes; then
   AC_MSG_WARN([])
   AC_MSG_WARN([You used the EXPERIMENTAL --enable-64 option.])
   AC_MSG_WARN([Are you sure that is what you want to do?])
@@ -2464,53 +2861,20 @@
   warn_msg_printed=true
 fi
 
-if $USE_OPENMP; then
+if test $USE_OPENMP = yes; then
   AC_MSG_WARN([])
   AC_MSG_WARN([You used the EXPERIMENTAL --enable-openmp option.])
   AC_MSG_WARN([Are you sure that is what you want to do?])
   AC_MSG_WARN([])
   AC_MSG_WARN([This option enables experimental SMP multithreding])
-  AC_MSG_WARN([code that has had very little testing. There is no])
+  AC_MSG_WARN([code that has had very little testing.  There is no])
   AC_MSG_WARN([certainity that the results returned by Octave with])
   AC_MSG_WARN([this option enabled will be correct.])
   AC_MSG_WARN([])
   warn_msg_printed=true
 fi
 
-native_graphics=true
-if test -n "$warn_opengl"; then
-  AC_MSG_WARN([$warn_opengl])
-  native_graphics=false
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_freetype"; then
-  AC_MSG_WARN([$warn_freetype])
-  native_graphics=false
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_fontconfig"; then
-  AC_MSG_WARN([$warn_fontconfig])
-  native_graphics=false
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_fltk_config"; then
-  AC_MSG_WARN([$warn_fltk_config])
-  native_graphics=false
-  warn_msg_printed=true
-fi
-
-if test -n "$warn_fltk_opengl"; then
-  AC_MSG_WARN([$warn_fltk_opengl])
-  native_graphics=false
-  warn_msg_printed=true
-fi
-
-if $native_graphics; then
-  true;
-else
+if test $native_graphics != yes; then
   AC_MSG_WARN([])
   AC_MSG_WARN([I didn't find the necessary libraries to compile native])
   AC_MSG_WARN([graphics.  It isn't necessary to have native graphics,])
@@ -2521,7 +2885,7 @@
 fi
 
 if test -n "$warn_gnuplot"; then
-  if $native_graphics; then
+  if test $native_graphics = yes; then
     AC_MSG_WARN([])
     AC_MSG_WARN([I didn't find gnuplot.  Plotting commands will use the])
     AC_MSG_WARN([native graphics toolkit.])
@@ -2545,15 +2909,15 @@
   warn_msg_printed=true
 fi
 
-if $USE_ATOMIC_REFCOUNT; then
+if test $USE_ATOMIC_REFCOUNT = yes; then
   AC_MSG_WARN([])
   AC_MSG_WARN([Using atomic reference counting.])
-  AC_MSG_WARN([This feature allows to access octave data safely from])
-  AC_MSG_WARN([another thread, for instance from a GUI. However this])
-  AC_MSG_WARN([results in a small performance penalty in the octave])
+  AC_MSG_WARN([This feature allows access to Octave data safely from])
+  AC_MSG_WARN([another thread, for instance from a GUI.  However this])
+  AC_MSG_WARN([results in a small performance penalty in the Octave])
   AC_MSG_WARN([interpreter.])
   AC_MSG_WARN([])
-  if $USE_OCTAVE_ALLOCATOR; then
+  if test $USE_OCTAVE_ALLOCATOR = yes; then
     AC_MSG_WARN([Thread-safe behavior is not guaranteed unless you also])
     AC_MSG_WARN([disable the use of the octave_allocator class.])
     AC_MSG_WARN([])
@@ -2563,8 +2927,9 @@
 
 if $warn_msg_printed; then
   AC_MSG_NOTICE([])
-  AC_MSG_NOTICE([NOTE: libraries may be skipped if a library is not found OR])
-  AC_MSG_NOTICE([NOTE: if the library on your system is missing required features.])
+  AC_MSG_NOTICE([NOTE: Libraries or auxiliary programs may be skipped if they are])
+  AC_MSG_NOTICE([NOTE: not found OR if they are missing required features on your])
+  AC_MSG_NOTICE([NOTE: system. ])
 fi
 
 ### End of configure.
--- a/doc/Makefile.am
+++ b/doc/Makefile.am
@@ -1,4 +1,4 @@
-# Makefile for octave's doc/interpreter directory
+# Makefile for Octave's doc directory
 #
 # Copyright (C) 1993-2012 John W. Eaton
 #
@@ -20,8 +20,8 @@
 
 include $(top_srcdir)/build-aux/common.mk
 
-## Avoid making multiple subdirs in parallel which can lead 
-## to a confusing error message stream
+## Avoid making multiple subdirs in parallel
+## which can lead to a confusing error message stream.
 .NOTPARALLEL:
 
 EXTRA_DIST = \
@@ -29,5 +29,5 @@
   texinfo.tex \
   texmf.cnf
 
-SUBDIRS = faq icons interpreter liboctave refcard
+SUBDIRS = doxyhtml icons interpreter liboctave refcard
 
rename from Doxyfile
rename to doc/doxyhtml/Doxygen.cfg
--- a/Doxyfile
+++ b/doc/doxyhtml/Doxygen.cfg
@@ -29,7 +29,7 @@
 # The public stable API version (unrelated to the internal API
 # version).
 
-PROJECT_NUMBER         = 3.6
+PROJECT_NUMBER         = 3.7
 
 # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
 # base path where the generated documentation will be put.
@@ -176,7 +176,7 @@
 
 # Which directories contain Octave source code
 
-INPUT                  = src/ liboctave/ libcruft/
+INPUT                  = src/ liboctave/ libinterp/
 
 # Search subdirectories for input.
 
new file mode 100644
--- /dev/null
+++ b/doc/doxyhtml/Makefile.am
@@ -0,0 +1,32 @@
+# Makefile for Octave's doc/doxyhtml directory
+#
+# Copyright (C) 1993-2012 John W. Eaton
+#
+# 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/>.
+
+include $(top_srcdir)/build-aux/common.mk
+
+doxyhtml:
+	cd ../..; doxygen doc/doxyhtml/Doxygen.cfg 
+
+EXTRA_DIST = \
+  Doxygen.cfg \
+  Makefile.am \
+  README
+
+maintainer-clean-local:
+	rm -rf `ls | $(GREP) -v Doxygen.cfg | $(GREP) -v Makefile.am | $(GREP) -v Makefile.in | $(GREP) -v README`
new file mode 100644
--- /dev/null
+++ b/doc/doxyhtml/README
@@ -0,0 +1,11 @@
+This directory contains documentation in Doxygen format for
+Octave's source code.  It is not created by default.
+
+To produce Doxygen documentation use
+
+make doxyhtml
+
+Doxygen documentation can be helpful for developers of Octave, but is not
+needed by users of Octave.  In addition, the documentation requires
+approximately 1.2GB of storage space.  For these reasons it is not maintained
+under version control nor distributed in tarballs.
deleted file mode 100644
--- a/doc/faq/Makefile.am
+++ /dev/null
@@ -1,34 +0,0 @@
-# Makefile for octave's doc/faq directory
-#
-# Copyright (C) 1996-2012 John W. Eaton
-#
-# 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/>.
-
-include $(top_srcdir)/build-aux/common.mk
-
-## Automake generated rules for documentation are not parallel-safe.
-## Restrict current directory to run serially
-.NOTPARALLEL:
-
-TEXINFO_TEX = ../texinfo.tex
-
-info_TEXINFOS = OctaveFAQ.texi
-
-all-local: dvi html pdf ps
-
-EXTRA_DIST = OctaveFAQ.dvi OctaveFAQ.html OctaveFAQ.pdf OctaveFAQ.ps
-
deleted file mode 100644
--- a/doc/faq/OctaveFAQ.texi
+++ /dev/null
@@ -1,1314 +0,0 @@
-% Copyright (C) 1997-2012 John W. Eaton
-%
-% 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/>.
-
-\input texinfo.tex      @c -*-texinfo-*-
-
-@setfilename OctaveFAQ.info
-@settitle Frequently asked questions about Octave (with answers)
-
-@setchapternewpage off
-@direntry
-* OctaveFAQ: (OctaveFAQ).  Frequently asked questions about Octave
-@end direntry
-@titlepage
-@title Octave FAQ
-@subtitle Frequently asked questions about Octave
-@subtitle @today{}
-@sp 1
-@author John W. Eaton and David Bateman
-@page
-@end titlepage
-
-@ifnottex
-@node Top
-@top
-@unnumbered Preface
-@cindex FAQ for Octave, latest version
-@end ifnottex
-
-This is a list of frequently asked questions (FAQ) for Octave users.
-
-We are always looking for new questions (@emph{with} answers), better
-answers, or both. Please send suggestions to
-@url{http://bugs.octave.org}. If you have general questions about
-Octave, or need help for something that is not covered by the Octave
-manual or the FAQ, please use the @email{help@@octave.org} mailing list.
-
-This FAQ is intended to supplement, not replace, the Octave manual.
-Before posting a question to the @email{help@@octave.org} mailing list,
-you should first check to see if the topic is covered in the manual.
-
-@menu
-* What is Octave?::
-* Licensing Issues::
-* How can I cite Octave?::
-* Series 3.4.N::
-* Octave Features::
-* Learning more about Octave::
-* Getting Octave::
-* Installation::
-* Common problems::
-* Using Octave::
-* @sc{Matlab} compatibility::
-* Index::
-@end menu
-
-@node What is Octave?
-@chapter What is Octave?
-
-Octave is a high-level interactive language, primarily intended for
-numerical computations that is mostly compatible with
-@sc{Matlab}.@footnote{@sc{Matlab} is a registered trademark of The
-MathWorks, Inc.}
-
-Octave can do arithmetic for real, complex or integer-valued scalars
-and matrices, solve sets of nonlinear algebraic equations, integrate
-functions over finite and infinite intervals, and integrate systems of
-ordinary differential and differential-algebraic equations.
-
-Octave uses the GNU readline library to handle reading and editing
-input.  By default, the line editing commands are similar to the
-cursor movement commands used by GNU Emacs, and a vi-style line
-editing interface is also available.  At the end of each session, the
-command history is saved, so that commands entered during previous
-sessions are not lost.
-
-The Octave distribution includes a 650+ page Texinfo manual. Access to
-the complete text of the manual is available via the @code{doc} command
-at the Octave prompt.
-
-@menu
-* Who develops Octave?::
-* Why GNU Octave?::
-* What version should I use?::
-* On what platforms does Octave run?::
-@end menu
-
-@node Who develops Octave?
-@section Who develops Octave?
-
-Discussions about writing the software that would eventually become
-Octave started in about 1988 with James B. Rawlings and John W. Eaton at
-the University of Texas. John W. Eaton was the original author of
-Octave, starting full-time development in February 1992. He is still the
-primary maintainer. The community of users/developers has in addition
-contributed some code and fuels the discussion on the mailing lists
-@email{help@@octave.org} (user forum), @email{maintainers@@octave.org}
-(development issues), and @email{octave-dev@@lists.sourceforge.net} (all
-things related to the Octave Forge repository of user-contributed
-functions).
-
-@node Why GNU Octave?
-@section Why GNU Octave?
-
-The GNU Project was launched in 1984 to develop a complete Unix-like
-operating system which is free software: the GNU system.
-
-GNU is a recursive acronym for ``GNU's Not Unix''; it is pronounced
-guh-noo, approximately like canoe.
-
-The Free Software Foundation (FSF) is the principal organizational
-sponsor of the GNU Project.
-
-Octave became GNU Octave in 1997 (beginning with version 2.0.6).  This
-meant agreeing to consider Octave a part of the GNU Project and support
-the efforts of the FSF.  However, Octave is not and has never been
-developed by the FSF.
-
-For more information about the GNU project, see @url{www.gnu.org}.
-
-@cindex FSF [Free Software Foundation]
-@cindex GNU [GNU's not unix]
-
-@node What version should I use?
-@section What version should I use?
-
-In general, you will find the latest version on
-@url{http://www.octave.org/download.html}. It is recommended to use the
-``stable'' version of octave for general use, and the ``development''
-version if you want the latest features.
-
-A list of user-visible changes since the last release is available in
-the file @file{NEWS}.  The file @file{ChangeLog} in the source
-distribution contains a more detailed record of changes made since the
-last release.
-
-@node On what platforms does Octave run?
-@section On what platforms does Octave run?
-
-Octave runs on various Unices---at least Linux and Solaris, Mac OS X,
-Windows and anything you can compile it on.  Binary distributions exist
-at least for Debian, Suse, Fedora and RedHat Linuxes (Intel and AMD
-@c Does Vista work? I get the feeling that even Windows users are trying
-@c to forget Vista like a bad nightmare. Tatsuro only confirmed XP and
-@c 7. I am tentatively assuming that Vista also works.
-CPUs, at least), for Mac OS X and Windows' 98, 2000, XP, Vista, and 7.
-
-Two and three dimensional plotting is fully supported using gnuplot and
-an experimental OpenGL backend.
-
-The underlying numerical solvers are currently standard Fortran ones
-like LAPACK, LINPACK, ODEPACK, the BLAS, etc., packaged in a library
-of C++ classes.  If possible, the Fortran subroutines are compiled
-with the system's Fortran compiler, and called directly from the C++
-functions.  If that's not possible, you can still compile Octave if
-you have the free Fortran to C translator f2c.
-
-Octave is also free software; you can redistribute it and/or modify it
-under the terms of the GNU General Public License, version 3, as
-published by the Free Software Foundation, or at your option any later
-version.
-
-@node Licensing Issues
-@chapter Licensing Issues
-
-@menu
-* If I write code using Octave do I have to release it under the GPL?: GPL
-* Since the MEX interface allows plugins to be distributed under terms that are incompatible with the GPL, does this mean that you are encouraging people to to write non-free software for Octave?: Licensing MEX Files
-* I wrote a program that links with Octave libraries and I don't want to release it under the terms of the GPL.  Will you change the license of the Octave libraries for me?: Requesting License Changes
-@end menu
-
-@node GPL
-@section If I write code using Octave do I have to release it under the GPL?
-
-The answer depends on precisely how the code is written and how it works.
-
-Code written entirely in the scripting language of Octave
-(interpreted code in .m files) may be released under the terms of
-whatever license you choose.
-
-Code written using Octave's native plug-in interface (also known
-as a .oct file) necessarily links with Octave internals and is
-considered a derivative work of Octave and therefore must be
-released under terms that are compatible with the GPL.
-
-Code written using Octave's implementation of the @sc{Matlab} MEX
-interface may be released under the terms of whatever license you
-choose, provided that the following conditions are met:
-
-@enumerate
-@item
-The plugin should not use any bindings that are specific to Octave.  In
-other words, the MEX file must use the MEX interface only, and not also
-call on other Octave internals.  It should be possible in principle to
-use the MEX file with other programs that implement the MEX interface
-(e.g., @sc{Matlab}).
-
-@item
-The MEX file should not be distributed together with Octave in such a
-way that they effectively create a single work.  For example, you should
-not distribute the MEX file and Octave together in a single package such
-that Octave automatically loads and runs the MEX file when it starts up.
-There are other possible ways that you might effectively create a single
-work; this is just one example.
-@end enumerate
-
-A program that embeds the Octave interpreter (e.g., by calling the
-"octave_main" function), or that calls functions from Octave's
-libraries (e.g., liboctinterp, liboctave, or libcruft) is
-considered a derivative work of Octave and therefore must be
-released under terms that are compatible with the GPL.
-
-@node Licensing MEX Files
-@section Since the MEX interface allows plugins to be distributed under terms that are incompatible with the GPL, does this mean that you are encouraging people to to write non-free software for Octave?
-
-No.  The original reason for implementing the MEX interface for Octave
-was to allow Octave to run free software that uses MEX files (the
-particular goal was to run SundialsTB in Octave).  The intent was to
-liberate that software from @sc{Matlab} and increase the amount of free
-software available to Octave users, not to enable people to write
-proprietary code for Octave.  For the good of the community, we strongly
-encourage users of Octave to release the code they write for Octave
-under terms that are compatible with the GPL.
-
-@node Requesting License Changes
-@section I wrote a program that links with Octave libraries and I don't want to release it under the terms of the GPL.  Will you change the license of the Octave libraries for me?
-
-No.  Instead of asking us to change the licensing terms for Octave, we
-recommend that you release your program under terms that are compatible
-with the GPL so that the free software community can benefit from your
-work the same as you have benefited from the work of all the people who
-have contributed to Octave.
-
-@node How can I cite Octave?
-@chapter How can I cite Octave?
-
-Pointing to @url{http://www.octave.org} is good, because that gives
-people a direct way to find out more.  If citation of a URL is not
-allowed by a publisher, or if you also want to point to a traditional
-reference, then you can cite the Octave manual:
-
-@example
-@group
-@@BOOK@{eaton:2008,
-  author =     "John W. Eaton and David Bateman and Søren Hauberg",
-  title =      "GNU Octave Manual Version 3",
-  publisher =  "Network Theory Limited",
-  year =       "2008",
-  isbn =       "0-9546120-6-X"
-@}
-@end group
-@end example
-
-@node Series 3.4.N
-@chapter What's new in version series 3.4.N and 3.5.N of Octave
-
-The 3.4.N series has enough new features to justify a minor version
-number change. The full details are in the @file{NEWS} file, but in
-brief 3.4.N series brings:
-
-@c This list is distilled from the NEWS file. Does it have enough
-@c things? Does it have too many?
-@itemize @bullet
-
-@item ARPACK now distributed with Octave
-
-@item Indexing optimisations
-
-@item FTP object using @file{libcurl}
-
-@item Better consistency with ismatrix, issquare, and issymetric
-
-@item Function handles aware of overloaded functions
-
-@item More efficient matrix division by making a single LAPACK call
-
-@item Other optimisations in matrix operations
-
-@item @code{bsxfun} optimised for basic arithmetic functions
-
-@item @sc{Matlab}-style ignoring of output arguments using @samp{~}
-
-@item Many optimisations of the @code{accumarray} function
-
-@item Sparse matrix indexing has been rewritten for speed
-
-@item Configuration pseudo-variables like @code{page_screen_output}
-accept a ``local'' option argument to limit their scope to function
-scope
-
-@item The @code{pkg} command now accepts a @code{-forge} option to pull
-packages directly from Octave-forge
-
-@item Several @code{dlmread} improvements
-
-@item Octave now uses gnulib for better cross-platform compatibility
-
-@end itemize
-
-Here are some features that have been around since 3.2.N
-
-@itemize @bullet
-
-@item integer types
-
-@item fixed point arithmetic
-
-@item sparse matrices
-
-@item Linear programming code based on GLPK
-
-@item 64-bit compilation support
-
-@item gzipped files and stream and consequently support of @sc{Matlab} v7 files
-
-@item better support for both msvc and mingw
-
-@item a fully compatible MEX interface
-
-@item many many other minor features and compatibility changes
-
-@item OpenGL graphics toolkit
-
-An experimental OpenGL graphics toolkit to replace gnuplot.
-
-@item Object Orient Programming
-
-@item Block comments
-
-@item imwrite and imread
-
-The functions are based on the GraphicsMagick library.
-
-@item Lazy transpose
-
-Special treatment in the parser of things like "a' * b", where the
-transpose is never explicitly formed but a flag is rather passed to the
-underlying LAPACK code.
-
-@item Single precision type
-
-@item Improved array indexing
-The underlying code used for indexing of arrays has been completely
-rewritten and so the indexing of arrays is now significantly faster.
-
-@end itemize
-
-Here are some older features that have been around since 2.1.N:
-
-@itemize @bullet
-
-@item NDarrays
-
-@item cells
-
-@end itemize
-
-The 3.5.N series is the current development release and will become a
-3.6.N release in the future. This series brings the following new
-features:
-
-@itemize
-@item Perl-compatible regular expressions are now part of Octave
-@end itemize
-
-
-@node Octave Features
-@chapter What features are unique to Octave?
-
-@menu
-* Functions defined on the command-line::
-* Comments with #::
-* Strings delimited by double quotes "::
-* Line continuation by backslash::
-* Informative block closing::
-* Coherent syntax::
-* Exclamation mark as not operator::
-* Increment and decrement operators::
-* Unwind-protect::
-* Built-in ODE and DAE solvers::
-@end menu
-
-This section refers to @sc{Matlab} R2010b and Octave 3.4.0.
-
-@node Functions defined on the command-line
-@section Functions defined on the command-line
-
-Functions can be defined by entering code on the command line, a feature
-not supported by @sc{Matlab}. For example, you may type:
-
-@example
-@group
-octave:1> function s = hello_string (to_who)
-> ## Say hello
-> if nargin<1, to_who = "World"; end
-> s = ["Hello ",\
->      to_who];
-> endfunction
-octave:2> hello_string ("Moon")
-ans = Hello Moon
-@end group
-@end example
-
-@node Comments with #
-@section Comments with #
-
-The pound character, @samp{#}, may be used to start comments, in
-addition to @samp{%}. See the previous example. The major advantage of
-this is that as @samp{#} is also a comment character for unix script
-files, any file that starts with a string like @samp{#! /usr/bin/octave
--q} will be treated as an octave script and be executed by octave.
-
-@node Strings delimited by double quotes "
-@section Strings delimited by double quotes "
-The double quote, @samp{"}, may be used to delimit strings, in addition
-to the single quote @samp{'}. See the previous example. Also,
-double-quoted strings include backslash interpretation (like C++, C, and
-Perl) while single quoted are uninterpreted (like @sc{Matlab} and Perl).
-
-@node Line continuation by backslash
-@section Line continuation by backslash
-
-Lines can be continued with a backslash, @samp{\}, in addition to three
-points @samp{@dots{}}.  See the previous example.
-
-@node Informative block closing
-@section Informative block closing
-
-You may close @code{function}, @code{for}, @code{while}, @code{if},
-@dots{} blocks with @code{endfunction}, @code{endfor}, @code{endwhile},
-@dots{} keywords in addition to using @code{end}.  As with @sc{Matlab}, the
-@code{end} (or @code{endfunction}) keyword that marks the end of a
-function defined in a @file{.m} file is optional.
-
-@node Coherent syntax
-@section Coherent syntax
-
-Indexing other things than variables is possible, as in:
-@example
-@group
-octave:1> [3 1 4 1 5 9](3)
-ans = 4
-octave:2> cos([0 pi pi/4 7])(3)
-ans = 0.70711
-@end group
-@end example
-
-@node Exclamation mark as not operator
-@section Exclamation mark as not operator
-
-The exclamation mark @samp{!} (aka ``Bang!'') is a negation operator, just
-like the tilde @samp{~}:
-
-@example
-@group
-octave:1> if ! strcmp (program_name, "octave"),
->   "It's an error"
-> else
->   "It works!"
-> end
-ans = It works!
-@end group
-@end example
-
-@noindent
-Note however that @sc{Matlab} uses the @samp{!} operator for shell
-escapes, for which Octave requires using the @code{system} command.
-
-@node Increment and decrement operators
-@section Increment and decrement operators
-
-@cindex Increment operators
-@cindex Decrement operators
-@cindex Operators, increment
-@cindex Operators, decrement
-
-If you like the @samp{++}, @samp{+=} etc operators, rejoice!
-Octave includes the C-like increment and decrement operators @samp{++}
-and @samp{--} in both their prefix and postfix forms, in addition to
-@samp{+=}, @samp{-=}, @samp{*=}, @samp{/=}, @samp{^=}, @samp{.*=},
-@samp{./=}, and @samp{.^=}.
-
-For example, to pre-increment the variable @var{x}, you would write
-@code{++@var{x}}.  This would add one to @var{x} and then return the new
-value of @var{x} as the result of the expression.  It is exactly the
-same as the expression @code{@var{x} = @var{x} + 1}.
-
-To post-increment a variable @var{x}, you would write @code{x++}.
-This adds one to the variable @var{x}, but returns the value that
-@var{x} had prior to incrementing it.  For example, if @var{x} is equal
-to 2, the result of the expression @code{x++} is 2, and the new
-value of @var{x} is 3.
-
-For matrix and vector arguments, the increment and decrement operators
-work on each element of the operand.
-
-@node Unwind-protect
-@section Unwind-protect
-
-@cindex Unwind-protect
-
-Octave supports a limited form of exception handling modeled after the
-unwind-protect form of Lisp.  The general form of an
-@code{unwind_protect} block looks like this:
-
-@example
-@group
-unwind_protect
-  @var{body}
-unwind_protect_cleanup
-  @var{cleanup}
-end_unwind_protect
-@end group
-@end example
-
-@noindent
-Where @var{body} and @var{cleanup} are both optional and may contain any
-Octave expressions or commands.  The statements in @var{cleanup} are
-guaranteed to be executed regardless of how control exits @var{body}.
-
-The @code{unwind_protect} statement is often used to reliably restore
-the values of global variables that need to be temporarily changed.
-
-@sc{Matlab} can be made to do something similar with their
-@code{OnCleanUp} function that was introduced in 2008a. Octave also has
-@code{onCleanup} since version 3.4.0.
-
-@node Built-in ODE and DAE solvers
-@section Built-in ODE and DAE solvers
-
-@cindex DASSL
-@cindex LSODE
-
-Octave includes LSODE and DASSL for solving systems of stiff ordinary
-differential and differential-algebraic equations.  These functions are
-built in to the interpreter.
-
-@node Learning more about Octave
-@chapter What documentation exists for Octave?
-
-@menu
-* Documentation::
-* Getting additional help::
-* User community::
-* Bug reports::
-@end menu
-
-@node Documentation
-@section What documentation exists for Octave?
-
-@cindex Octave, documentation
-
-The Octave distribution includes a 650+ page manual that is also
-distributed under the terms of the GNU GPL.
-It is available on the web at
-@url{http://www.octave.org/support.html} and you will also
-find there instructions on how to order a paper version.
-
-The complete text of the Octave manual is also available using the GNU
-Info system via the GNU Emacs, info, or xinfo programs, or by using
-the @samp{doc} command to start the GNU info browser directly from
-the Octave prompt.
-
-If you have problems using this documentation, or find that some topic
-is not adequately explained, indexed, or cross-referenced, please report
-it on @url{http://bugs.octave.org}.
-
-@node Getting additional help
-@section Getting additional help
-
-@cindex Additional help
-@cindex Mailing lists, help-octave
-
-If you can't find an answer to your question, the
-@email{help@@octave.org} mailing list is available for questions related
-to using, installing, and porting Octave that are not adequately
-answered by the Octave manual or by this document.
-
-@node User community
-@section User community
-
-To subscribe to the list, go to @url{http://www.octave.org/support.html}
-and follow the link to the subscription page for the list.
-
-@strong{Please do not} send requests to be added or removed from the
-mailing list, or other administrative trivia to the list itself.
-
-An archive of old postings to the help-octave mailing list is maintained
-on @url{http://www.octave.org/support.html}.
-
-You will also find some user advice and code spread over the web.  Good
-starting points are the Octave Wiki @url{http://wiki.octave.org} and
-Octave-Forge @url{http://octave.sourceforge.net}
-
-@node Bug reports
-@section I think I have found a bug in Octave.
-
-@cindex Bug in Octave, newly found
-
-``I think I have found a bug in Octave, but I'm not sure.  How do I know,
-and who should I tell?''
-
-@cindex Manual, for Octave
-
-First, see the section on bugs and bug reports in the Octave manual.
-When you report a bug, make sure to describe the type of computer you
-are using, the version of the operating system it is running, and the
-version of Octave that you are using. Also provide enough code and
-configuration details of your operating system so that the Octave
-maintainers can duplicate your bug.
-
-@node Getting Octave
-@chapter Getting Octave
-
-@menu
-* Source code::
-* Pre-compiled binary packages::
-* Octave for other platforms::
-@end menu
-
-@node Source code
-@section Source code
-@cindex Source code
-
-Source code is available on the Octave development site, where you are
-sure to get the latest version.
-
-@itemize @bullet
-@item @url{http://www.octave.org/download.html}
-@item @url{ftp://ftp.octave.org/pub/octave/}
-@end itemize
-
-Since Octave is distributed under the terms of the GPL, you can get
-Octave from a friend who has a copy, or from the Octave website.
-
-@node Pre-compiled binary packages
-@section Pre-compiled binary packages
-@cindex  Pre-compiled binary packages
-@cindex  Binaries
-
-The Octave project does not distribute binary packages, but other
-projects do.  For an up-to-date listing of packagers, see:
-
-@itemize @bullet
-@item @url{http://www.octave.org/download.html}
-@item @url{http://wiki.octave.org/Installation}
-@end itemize
-
-As of today, Octave binaries are available at least on Debian, Ubuntu,
-RedHat, Suse and Fedora GNU/Linuxen, Mac OS X, Windows' 98, 2000 and XP,
-Vista, and 7.
-
-@node Octave for other platforms
-@section How do I get a copy of Octave for (some other platform)?
-
-@cindex VMS support
-@cindex VAX
-@cindex MS-DOS support
-@cindex Windows support
-@cindex DJGPP
-@cindex EMX
-@cindex OS/2 support
-
-Octave currently runs on Unix-like systems, Mac OS X, and Windows.
-It should be possible to make Octave work on other systems as well.
-If you are interested in porting Octave to other systems, please contact
-@email{maintainers@@octave.org}.
-
-@c @menu
-@c * Octave for Unix::
-@c * Octave for other platforms::
-@c * latest versions::
-@c @end menu
-
-@c @cindex Octave, ordering
-@c @cindex Octave, getting a copy
-
-@node Installation
-@chapter Installation Issues and Problems
-
-@cindex Octave, building
-
-Octave 3.4 require approximately 1.3 GB of disk storage to unpack and
-compile from source (considerably less if you don't compile with
-debugging symbols). Once installed, Octave requires approximately 355 MB
-of disk space (again, considerably less if you don't compile with
-debugging symbols, approximately 50 MB).
-
-@menu
-* What else do I need?::
-* Other C++ compilers?::
-@end menu
-
-@node What else do I need?
-@section What else do I need?
-
-@cindex GNU gcc
-@cindex GNU g++
-@cindex libg++
-@cindex GNU Make
-@cindex Flex
-@cindex GNU Bison
-
-To compile Octave, you will need a recent version of GNU Make.  You
-will also need GCC 4.3  or later, although GCC 4.4 or later is
-recommended.
-
-@strong{You must have GNU Make to compile octave}.  Octave's Makefiles
-use features of GNU Make that are not present in other versions of make.
-GNU Make is very portable and easy to install.
-
-@node Other C++ compilers?
-@section Can I compile Octave with another C++ compiler?
-
-Yes, but development is done primarily with GCC, so you may hit some
-incompatibilities. Octave is intended to be portable to any standard
-conforming compiler. If you have difficulties that you think are bugs,
-please report them to the @url{http://bugs.octave.org} bug tracker, or
-ask for help on the @email{help@@octave.org} mailing list.
-
-@node Common problems
-@chapter Common problems
-
-This list is probably far too short.  Feel free to suggest additional
-questions (preferably with answers!)
-
-@itemize @bullet
-@item
-Octave takes a long time to find symbols.
-
-Octave uses the @code{genpath} function to recursively add directories
-to the list of directories searched for function files.  Check the list
-of directories with the @code{path} command. If the path list is very
-long check your use of the @code{genpath} function.
-
-@item
-When plotting Octave occasionally gives me errors like @samp{gnuplot> 9
-0.735604 line 26317: invalid command}.
-
-There is a known bug in gnuplot 4.2 that can cause an off by one error
-while piping data to gnuplot. It has been fixed in gnuplot 4.4.
-
-If you have obtained your copy of Octave from a distribution please file
-a bug report requesting that the fix reported in the above bug report be
-included.
-
-@item
-I cannot install a package. Octave complains about a missing
-@code{mkoctfile}.
-
-Most distributions split Octave into several packages. The script
-@code{mkoctfile} is then part of a separate package:
-@itemize @minus
-@item
-Debian/Ubuntu
-
-@c This will work once we upload the Octave packages without a version
-@c in their name to Debian.
-@code{aptitude install octave-headers}
-
-@item
-Fedora
-
-@code{yum install octave-devel}
-
-@end itemize
-@end itemize
-
-@node Using Octave
-@chapter  Using Octave
-
-@menu
-* How do I set the number of displayed decimals?::
-* How does Octave solve linear systems?::
-@end menu
-
-@cindex Tips and tricks
-@cindex Using Octave
-
-@node How do I set the number of displayed decimals?
-@section How do I set the number of displayed decimals?
-
-@example
-@group
-octave:1> format long
-octave:2> pi
-pi = 3.14159265358979
-octave:3> format short
-octave:4> pi
-pi = 3.1416
-@end group
-@end example
-
-@node How does Octave solve linear systems?
-@section How does Octave solve linear systems?
-
-@cindex backslash operator
-
-In addition to consulting Octave's source for the precise details, the
-Octave manual contains a complete high-level description of the
-algorithm that Octave uses to decide how to solve a particular linear
-system, e.g. how the backslash operator @code{A\x} will be interpreted.
-Sections ``Techniques Used for Linear Algebra'' and ``Linear Algebra on
-Sparse Matrices'' from the manual describe this procedure.
-
-@node @sc{Matlab} compatibility
-@chapter Porting programs from @sc{Matlab} to Octave
-
-@cindex @sc{Matlab} compatibility
-@cindex Compatibility with @sc{Matlab}
-
-People often ask
-
-@quotation
-I wrote some code for @sc{Matlab}, and I want to get it running under
-Octave.  Is there anything I should watch out for?
-@end quotation
-
-@noindent
-or alternatively
-
-@quotation
-I wrote some code in Octave, and want to share it with @sc{Matlab}
-users.  Is there anything I should watch out for?
-@end quotation
-
-@noindent
-which is not quite the same thing.  There are still a number of
-differences between Octave and @sc{Matlab}, however in general
-differences between the two are considered as bugs.  Octave might
-consider that the bug is in @sc{Matlab} and do nothing about it, but
-generally functionality is almost identical.  If you find a difference
-between Octave behavior and @sc{Matlab}, then you should send a
-description of this difference (with code illustrating the difference,
-if possible) to @url{http://bugs.octave.org}.
-
-Furthermore, Octave adds a few syntactical extensions to @sc{Matlab}
-that might cause some issues when exchanging files between @sc{Matlab}
-and Octave users. As both Octave and @sc{Matlab} are under constant
-development the information in this section is subject to change at
-anytime.
-
-You should also look at the page
-@url{http://octave.sourceforge.net/packages.html} and
-@url{http://octave.sourceforge.net/doc/} that has a function reference
-that is up to date. You can use this function reference to see the
-number of octave function that are available and their @sc{Matlab}
-compatibility.
-
-The major differences between Octave 3.4.N and  @sc{Matlab} R2010b are:
-
-@itemize @bullet
-@item Nested Functions
-
-Octave has limited support for nested functions. That is
-
-@example
-@group
-function y = foo (x)
-  y = bar(x)
-  function y = bar (x)
-    y = @dots{};
-  end
-end
-@end group
-@end example
-
-is equivalent to
-
-@example
-@group
-function y = foo (x)
-   y = bar(x)
-end
-function y = bar (x)
-   y = @dots{};
-end
-@end group
-@end example
-
-The main difference with @sc{Matlab} is a matter of scope. While nested
-functions have access to the parent function's scope in @sc{Matlab}, no
-such thing is available in Octave, due to how Octave essentially
-``un-nests'' nested functions.
-
-The authors of Octave consider the nested function scoping rules of
-@sc{Matlab} to be more problems than they are worth as they introduce
-difficult to find bugs as inadvertently modifying a variable in a
-nested function that is also used in the parent is particularly easy.
-
-@item Differences in core syntax
-There a few core @sc{Matlab} syntaxes that are not accepted by Octave,
-these being
-
-@itemize @bullet
-@item
-Some limitations on the use of function handles. The major difference is
-related to nested function scoping rules (as above) and their use with
-function handles.
-
-@item
-Some limitations of variable argument lists on the LHS of an expression,
-though the most common types are accepted.
-
-@item
-@sc{Matlab} classdef object oriented programming is not yet supported,
-though work is underway and when development more on to Octave 3.5 this
-will be included in the development tree.
-@end itemize
-
-@item Differences in core functions
-A large number of the @sc{Matlab} core functions (ie those that are in
-the core and not a toolbox) are implemented, and certainly all of the
-commonly used ones. There are a few functions that aren't implemented,
-usually to do with specific missing Octave functionality (GUI, DLL,
-Java, ActiveX, DDE, web, and serial functions). Some of the core
-functions have limitations that aren't in the @sc{Matlab} version. For
-example the @code{sprandn} function can not force a particular condition
-number for the matrix like @sc{Matlab} can.
-
-@item Just-In-Time compiler
-@sc{Matlab} includes a "Just-In-Time" compiler. This compiler allows the
-acceleration of for-loops in @sc{Matlab} to almost native performance
-with certain restrictions. The JIT must know the return type of all
-functions called in the loops and so you can't include user functions in
-the loop of JIT optimized loops. Octave doesn't have a JIT and so to
-some might seem slower than @sc{Matlab}. For this reason you must
-vectorize your code as much as possible. The MathWorks themselves have a
-good document discussing vectorization at
-@c It would be nice if we had our own guide for this instead of relying
-@c on Matlab documentation.
-@url{http://www.mathworks.com/support/tech-notes/1100/1109.html}.
-
-@item Compiler
-On a related point, there is no Octave compiler, and so you can't
-convert your Octave code into a binary for additional speed or
-distribution. There have been several aborted attempts at creating an
-Octave compiler. Should the JIT compiler above ever be implemented, an
-Octave compiler should be more feasible.
-@c Should we mention here any of the efforts to create a compiler? There
-@c used to be a dead link here to http://www.stud.tu-ilmenau.de/~rueckn/
-
-@item Graphic Handles
-Up to Octave 2.9.9 there was no support for graphic handles in Octave
-itself. In the 3.2.N versions of Octave and beyond the support for
-graphics handles is converging towards full compatibility. The
-@code{patch} function is currently limited to 2-D patches, due to an
-underlying limitation in gnuplot, but the experimental OpenGL backend is
-starting to see an implementation of 3-D patches.
-
-@item GUI
-There are no @sc{Matlab} compatible GUI functions. There are a number of
-bindings from Octave to Tcl/Tk, VTK and Zenity included in the Octave
-@c Is it too early to mention here the nascent fltk UI buttons?
-Forge project (@url{http://octave.sourceforge.net}) for example that can
-be used for a GUI, but these are not @sc{Matlab} compatible. Work on a
-@sc{Matlab} compatible GUI is in an alpha stage in the JHandles package
-@c Is Jhandles still usable? I thought Michael Goffioul had more or less
-@c already disowned it.
-(@url{http://octave.sourceforge.net/jhandles/index.html}). This might be
-an issue if you intend to exchange Octave code with @sc{Matlab} users.
-
-@item Simulink
-Octave itself includes no Simulink support. Typically the simulink
-models lag research and are less flexible, so shouldn't really be used
-in a research environment.  However, some @sc{Matlab} users that try to
-use Octave complain about this lack.  There is a similar package to
-simulink for the Octave and R projects available at
-@c is this project in any state of usability?
-@url{http://www.scicraft.org/}
-
-@item Mex-Files
-Octave includes an API to the @sc{Matlab} MEX interface. However, as MEX
-is an API to the internals of @sc{Matlab} and the internals of Octave
-differ from @sc{Matlab}, there is necessarily a manipulation of the data
-to convert from a MEX interface to the Octave equivalent. This is
-notable for all complex matrices, where @sc{Matlab} stores complex
-arrays as real and imaginary parts, whereas Octave respects the C99/C++
-standards of co-locating the real/imag parts in memory. Also due to the
-way @sc{Matlab} allows access to the arrays passed through a pointer,
-the MEX interface might require copies of arrays (even non complex
-ones).
-
-@item Block comments
-Block comments denoted by "%@{" and "%@}" markers are supported by
-Octave with some limitations. The major limitation is that block
-comments are not supported within [] or @{@}.
-
-@item Mat-File format
-There are some differences in the mat v5 file format accepted by Octave.
-@sc{Matlab} recently introduced the "-V7.3" save option which is an HDF5
-format which is particularly useful for 64-bit platforms where the
-standard @sc{Matlab} format can not correctly save variables. Octave
-accepts HDF5 files, but is not yet compatible with the "-v7.3" versions
-produced by @sc{Matlab}.
-
-Although Octave can load inline function handles saved by @sc{Matlab},
-it can not yet save them.
-
-Finally, Some multi-byte Unicode characters aren't yet treated in
-mat-files.
-
-@item Profiler
-Octave doesn't have a profiler. Though there is a patch for a flat
-profiler, that might become a real profiler sometime in the future. See
-the thread
-
-@c Did this idea go anywhere? Should it be mentioned?
-@url{http://octave.1599824.n4.nabble.com/Octave-profiler-td1641945.html#a1641947}
-
-for more details.
-
-@item Toolboxes
-Octave is a community project and so the toolboxes that exist are
-donated by those interested in them through the Octave Forge website
-(@url{http://octave.sourceforge.net}). These might be lacking in certain
-functionality relative to the @sc{Matlab} toolboxes, and might not
-exactly duplicate the @sc{Matlab} functionality or interface.
-
-@item Short-circuit & and | operators
-The @code{&} and @code{|} operators in @sc{Matlab} short-circuit when
-included in an if statement and not otherwise.  In Octave only the
-@code{&&} and @code{||} short circuit.  Note that this means that
-
-@example
-@group
-  if (a | b)
-    @dots{}
-  end
-@end group
-@end example
-
-and
-
-@example
-@group
-  t = a | b;
-  if t
-    @dots{}
-  end
-@end group
-@end example
-
-@noindent
-are different in @sc{Matlab}. This is really a @sc{Matlab} bug, but
-there is too much code out there that relies on this behaviour to change
-it. Prefer the || and && operators in if statements if possible. If you
-need to use code written for @sc{Matlab} that depends on this buggy
-behaviour, you can enable it since Octave 3.4.0 with the following
-command:
-
-@example
-@group
-  do_braindead_shortcircuit_evaluation(1)
-@end group
-@end example
-
-Note that the difference with @sc{Matlab} is also significant when
-either argument is a function with side effects or if the first argument
-is a scalar and the second argument is an empty matrix. For example,
-note the difference between
-
-@example
-@group
-  t = 1 | [];          ## results in [], so...
-  if (t) 1, end        ## in if ([]), this is false.
-@end group
-@end example
-
-and
-
-@example
-  if (1 | []) 1, end   ## short circuits so condition is true.
-@end example
-
-Another case that is documented in the @sc{Matlab} manuals is that
-
-@example
-@group
-  t = [1, 1] | [1, 2, 3];          ## error
-  if ([1, 1] | [1, 2, 3]) 1, end   ## OK
-@end group
-@end example
-
-Also @sc{Matlab} requires the operands of && and || to be scalar values
-but Octave does not (it just applies the rule that for an operand to be
-considered true, every element of the object must be nonzero or
-logically true).
-
-Finally, note the inconsistence of thinking of the condition of an if
-statement as being equivalent to @code{all(X(:))} when @var{X} is a
-matrix.  This is true for all cases EXCEPT empty matrices:
-
-@example
-@group
-  if ([0, 1]) == if (all ([0, 1]))   ==>  i.e., condition is false.
-  if ([1, 1]) == if (all ([1, 1]))   ==>  i.e., condition is true.
-@end group
-@end example
-
-However,
-
-@example
-  if ([]) != if (all ([]))
-@end example
-
-because @code{samp ([]) == 1} because, despite the name, it is really
-returning true if none of the elements of the matrix are zero, and since
-there are no elements, well, none of them are zero. This is an example
-of vacuous truth. But, somewhere along the line, someone decided that if
-@code{([])} should be false. Mathworks probably thought it just looks
-wrong to have @code{[]} be true in this context even if you can use
-logical gymnastics to convince yourself that "all" the elements of a
-matrix that doesn't actually have any elements are nonzero. Octave
-however duplicates this behavior for if statements containing empty
-matrices.
-
-@item Solvers for singular, under- and over-determined matrices
-
-@sc{Matlab}'s solvers as used by the operators mldivide (\) and mrdivide
-(/), use a different approach than Octave's in the case of singular,
-under-, or over-determined matrices. In the case of a singular matrix,
-@sc{Matlab} returns the result given by the LU decomposition, even
-though the underlying solver has flagged the result as erroneous. Octave
-has made the choice of falling back to a minimum norm solution of
-matrices that have been flagged as singular which arguably is a better
-result for these cases.
-
-In the case of under- or over-determined matrices, Octave continues to
-use a minimum norm solution, whereas @sc{Matlab} uses an approach that
-is equivalent to
-
-@example
-@group
-function x = mldivide (A, b)
-  [Q, R, E] = qr(A);
-  x = [A \ b, E(:, 1:m) * (R(:, 1:m) \ (Q' * b))]
-end
-@end group
-@end example
-
-@noindent
-While this approach is certainly faster and uses less memory than
-Octave's minimum norm approach, this approach seems to be inferior in
-other ways.
-
-A numerical question arises: how big can the null space component
-become, relative to the minimum-norm solution? Can it be nicely bounded,
-or can it be arbitrarily big? Consider this example:
-
-@example
-@group
-m = 10;
-n = 10000;
-A = ones(m, n) + 1e-6 * randn(m,n);
-b = ones(m, 1) + 1e-6 * randn(m,1);
-norm(A \ b)
-@end group
-@end example
-
-@noindent
-while Octave's minimum-norm values are around 3e-2, @sc{Matlab}'s
-results are 50-times larger. For another issue, try this code:
-
-@example
-@group
-m = 5;
-n = 100;
-j = floor(m * rand(1, n)) + 1;
-b = ones(m, 1);
-A = zeros(m, n);
-A(sub2ind(size(A),j,1:n)) = 1;
-x = A \ b;
-[dummy,p] = sort(rand(1,n));
-y = A(:,p)\b;
-norm(x(p)-y)
-@end group
-@end example
-
-@noindent
-It shows that unlike in Octave, mldivide in @sc{Matlab} is not invariant
-with respect to column permutations. If there are multiple columns of
-the same norm, permuting columns of the matrix gets you different
-result than permuting the solution vector. This will surprise many
-users.
-
-Since the mldivide (\) and mrdivide (/) operators are often part of a
-more complex expression, where there is no room to react to warnings or
-flags, it should prefer intelligence (robustness) to speed, and so the
-Octave developers are firmly of the opinion that Octave's approach for
-singular, under- and over-determined matrices is a better choice that
-@sc{Matlab}'s
-
-@item Octave extensions
-The extensions in Octave over @sc{Matlab} syntax are
-very useful, but might cause issues when sharing with @sc{Matlab} users.
-A list of the major extensions that should be avoided to be compatible
-with @sc{Matlab} are
-
-@itemize @bullet
-@item
-Comments in octave can be marked with @samp{#}. This allows POSIX
-systems to have the first line as @samp{#! octave -q} and mark the
-script itself executable. @sc{Matlab} doesn't have this feature due to
-the absence of comments starting with @samp{#}".
-
-@item
-Code blocks like @code{if}, @code{for}, @code{while}, etc can be
-terminated with block specific terminations like @code{endif}.
-@sc{Matlab} doesn't have this and all blocks must be terminated with
-@code{end}.
-
-@item
-Octave has a lisp like @code{unwind_protect} block that allows blocks of
-code that terminate in an error to ensure that the variables that are
-touched are restored. You can do something similar with
-@code{try}/@code{catch} combined with @samp{rethrow (lasterror ())} in
-@sc{Matlab}, however rethrow and lasterror are only available in Octave
-2.9.10 and later. @sc{Matlab} 2008a also introduced @code{OnCleanUp}
-that is similar to @code{unwind_protect}, except that the object created
-by this function has to be explicitly cleared in order for the cleanup
-code to run.
-
-Note that using @code{try}/@code{catch} combined with @samp{rethrow
-(lasterror ())} can not guarantee that global variables will be
-correctly reset, as it won't catch user interrupts with Ctrl-C. For
-example
-
-@example
-@group
-  global a
-  a = 1;
-  try
-    _a = a;
-    a = 2
-    while true
-    end
-  catch
-    fprintf ('caught interrupt\n');
-    a = _a;
-    rethrow (lasterror());
-  end
-@end group
-@end example
-
-@noindent
-compared to
-
-@example
-@group
-  global a
-  a = 1;
-  unwind_protect
-    _a = a;
-    a = 2
-    while true
-    end
-  unwind_protect_cleanup
-    fprintf ('caught interrupt\n');
-    a = _a;
-  end
-@end group
-@end example
-
-Typing Ctrl-C in the first case returns the user directly to the
-prompt, and the variable "a" is not reset to the saved value. In the
-second case the variable "a" is reset correctly.  Therefore @sc{Matlab}
-gives no safe way of temporarily changing global variables.
-
-@item
-Indexing can be applied to all objects in Octave and not just
-variable. Therefore @code{sin(x)(1:10);} for example is perfectly valid
-in Octave but not @sc{Matlab}. To do the same in @sc{Matlab} you must do
-@code{y = sin(x); y = y([1:10]);}
-
-@item
-Octave has the operators "++", "--", "-=", "+=", "*=", etc.  As
-@sc{Matlab} doesn't, if you are sharing code these should be avoided.
-
-@item
-Character strings in Octave can be denoted with double or single
-quotes. There is a subtle difference between the two in that escaped
-characters like @code{\n} (newline), @code{\t} (tab), etc are
-interpreted in double quoted strings but not single quoted strings. This
-difference is important on Windows platforms where the "\" character is
-used in path names, and so single quoted strings should be used in
-paths. @sc{Matlab} doesn't have double quoted strings and so they should
-be avoided if the code will be transferred to a @sc{Matlab} user.
-@end itemize
-
-@end itemize
-
-@node Index
-@appendix Concept Index
-
-@printindex cp
-
-@page
-@contents
-@bye
--- a/doc/icons/Makefile.am
+++ b/doc/icons/Makefile.am
@@ -1,4 +1,4 @@
-# Makefile for octave's doc/icons directory
+# Makefile for Octave's doc/icons directory
 #
 # Copyright (C) 2012 John W. Eaton
 #
--- a/doc/icons/octave.desktop.in
+++ b/doc/icons/octave.desktop.in
@@ -6,5 +6,5 @@
 Icon=%OCTAVE_IMAGEDIR%/octave-logo.svg
 Terminal=true
 Type=Application
-Categories=Development;Math;Science;
+Categories=Education;Science;Math;
 StartupNotify=false
--- a/doc/interpreter/Makefile.am
+++ b/doc/interpreter/Makefile.am
@@ -1,4 +1,4 @@
-# Makefile for octave's doc/interpreter directory
+# Makefile for Octave's doc/interpreter directory
 #
 # Copyright (C) 1993-2012 John W. Eaton
 #
@@ -20,10 +20,6 @@
 
 include $(top_srcdir)/build-aux/common.mk
 
-## Automake generated rules for documentation are not parallel-safe.
-## Restrict current directory to run serially
-.NOTPARALLEL:
-
 TEXINFO_TEX = ../texinfo.tex
 
 ## Leading PATH_SEPARATOR required due to weak parsing by dvips (12/04/09)
@@ -87,12 +83,31 @@
 $(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) \
-  $(HTMLDIR_IMAGES)
+  $(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 = \
   octave_logo.eps \
@@ -126,6 +141,7 @@
   interp.texi \
   intro.texi \
   io.texi \
+  java.texi \
   linalg.texi \
   matrix.texi \
   nonlin.texi \
@@ -153,23 +169,30 @@
 
 TXI_SRC = $(MUNGED_TEXI_SRC:.texi=.txi)
 
-info_TEXINFOS = octave.texi
-
-octave_TEXINFOS = \
+BUILT_TEXINFOS = \
   contributors.texi \
   $(MUNGED_TEXI_SRC)
 
-octave.info octave.dvi octave.html octave.pdf: $(srcdir)/version.texi $(octave_TEXINFOS) $(EXAMPLE_FILES) $(srcdir)/images.mk
+info_TEXINFOS = octave.texi
 
-octave.info: $(IMAGES_TXT)
-
-octave.dvi octave.ps: $(IMAGES_EPS) octave_logo.eps
+octave_TEXINFOS = \
+  $(BUILT_TEXINFOS) \
+  $(EXAMPLE_FILES) \
+  $(IMAGES) \
+  $(LOGOS) \
+  $(srcdir)/images.mk
 
-octave.html: $(IMAGES_PNG)
+all-local: dvi html pdf ps doc-cache
+
+html: $(HTMLDIR_IMAGES)
 
-octave.pdf: $(IMAGES_PDF) octave_logo.pdf
+$(HTMLDIR_IMAGES): $(IMAGES_PNG) | octave.html
+	cp $(@F) octave.html
 
-all-local: dvi html pdf ps doc-cache $(HTMLDIR_IMAGES)
+## The texi2dvi script (used to create both PDF and DVI output formats)
+## uses some fixed temporary file names.  In order to avoid a race condition
+## the DVI and PDF builds are forced to run serially through a Makefile rule.
+octave.pdf: octave.dvi
 
 # Prevent packaging of distribution unless all libraries 
 # necessary to create documentation are present
@@ -179,12 +202,12 @@
 	@$(GREP) '#define HAVE_UMFPACK 1' $(top_builddir)/config.h > /dev/null || { echo "Documentation creation requires missing UMFPACK library.  Cannot package distribution!" ; exit 1; }
 	@$(GREP) '#define HAVE_QHULL 1' $(top_builddir)/config.h > /dev/null || { echo "Documentation creation requires missing QHULL library.  Cannot package distribution!" ; exit 1; }
 
-octetc_DATA = doc-cache
+octetc_DATA = doc-cache macros.texi
 
 DOCSTRING_FILES = $(shell $(srcdir)/find-docstring-files.sh "$(top_srcdir)")
 
 doc-cache: $(DOCSTRING_FILES) mk_doc_cache.m
-	$(top_builddir)/run-octave -f -q -H $(srcdir)/mk_doc_cache.m doc-cache $(DOCSTRING_FILES) || { rm -f doc-cache; exit 1; }
+	$(top_builddir)/run-octave -f -q -H $(srcdir)/mk_doc_cache.m doc-cache $(srcdir)/macros.texi $(DOCSTRING_FILES) || { rm -f doc-cache; exit 1; }
 
 $(MUNGED_TEXI_SRC): $(DOCSTRING_FILES) $(munge_texi_SOURCES)
 
@@ -198,6 +221,10 @@
 
 ../../AUTHORS: preface.texi contributors.texi
 	rm -f AUTHORS
+	if [ "x$(srcdir)" != "x." ] && [ -f $(srcdir)/contributors.texi ] && [ ! -f contributors.texi ]; then \
+		cp $(srcdir)/contributors.texi contributors.texi; \
+		touch -r $(srcdir)/contributors.texi contributors.texi; \
+	fi
 	-$(MAKEINFO) -D AUTHORSONLY \
 	  --no-validate --no-headers --no-split --output AUTHORS $<
 	mv AUTHORS ../../AUTHORS
@@ -214,12 +241,12 @@
 	  --no-validate --no-headers --no-split --output INSTALL $<
 	mv INSTALL ../../INSTALL.OCTAVE
 
+
 undocumented_list:
 	rm -f $@
 	-$(PERL) $(srcdir)/doccheck/mk_undocumented_list > $@
 .PHONY: undocumented_list
 
-
 SPELLCHECK_FILES = $(MUNGED_TEXI_SRC:.texi=.scheck)
 
 %.scheck: %.texi
@@ -246,6 +273,7 @@
   images \
   images.awk \
   images.mk \
+  macros.texi \
   mk_doc_cache.m \
   mkcontrib.awk \
   munge-texi.pl \
@@ -258,7 +286,10 @@
   $(LOGOS) \
   $(TXI_SRC)
 
-DISTCLEANFILES = $(octave_TEXINFOS)
+clean-local:
+	rm -rf t2d_cache
 
-MAINTAINERCLEANFILES = $(IMAGES) doc-cache
+DISTCLEANFILES = $(BUILT_TEXINFOS)
 
+MAINTAINERCLEANFILES = $(BUILT_IMAGES) doc-cache
+
--- a/doc/interpreter/arith.txi
+++ b/doc/interpreter/arith.txi
@@ -118,6 +118,24 @@
 example, @code{sin} expects an angle in radians while @code{sind} expects an
 angle in degrees.
 
+Octave uses the C library trigonometric functions.  It is expected that these
+functions are defined by the ISO/IEC 9899 Standard.  This Standard is available
+at: @url{http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf}.
+Section F.9.1 deals with the trigonometric functions.  The behavior of most of
+the functions is relatively straightforward.  However, there are some
+exceptions to the standard behavior.  Many of the exceptions involve the
+behavior for -0.  The most complex case is atan2.  Octave exactly implements
+the behavior given in the Standard.  Including
+@tex
+$atan2(\pm0, -0)$ returns $\pm \pi$.
+@end tex
+@ifnottex
+@code{atan2(+- 0, 0)} returns @code{+- pi}.
+@end ifnottex
+
+It should be noted that @sc{matlab} uses different definitions which apparently
+do not distinguish -0.
+
 @DOCSTRING(sin)
 @DOCSTRING(cos)
 @DOCSTRING(tan)
@@ -244,6 +262,8 @@
 
 @DOCSTRING(sign)
 
+@DOCSTRING(signbit)
+
 @node Special Functions
 @section Special Functions
 
@@ -255,6 +275,8 @@
 
 @DOCSTRING(betainc)
 
+@DOCSTRING(betaincinv)
+
 @DOCSTRING(betaln)
 
 @DOCSTRING(bincoeff)
@@ -263,14 +285,26 @@
 
 @DOCSTRING(duplication_matrix)
 
+@DOCSTRING(dawson)
+
+@DOCSTRING(ellipj)
+
+@DOCSTRING(ellipke)
+
 @DOCSTRING(erf)
 
 @DOCSTRING(erfc)
 
 @DOCSTRING(erfcx)
 
+@DOCSTRING(erfi)
+
 @DOCSTRING(erfinv)
 
+@DOCSTRING(erfcinv)
+
+@DOCSTRING(expint)
+
 @DOCSTRING(gamma)
 
 @DOCSTRING(gammainc)
--- a/doc/interpreter/basics.txi
+++ b/doc/interpreter/basics.txi
@@ -101,6 +101,10 @@
 in the system or user startup files that set the built-in variable
 @w{@env{EXEC_PATH}}.
 
+@item --force-gui
+@cindex @code{--force-gui}
+Force the graphical user interface (GUI) to start.
+
 @item  --help
 @itemx -h
 @itemx -?
@@ -141,10 +145,19 @@
 remote shell command or inside an Emacs shell buffer.  For another way
 to run Octave within Emacs, see @ref{Emacs Octave Support}.
 
+@item --jit-debug
+@cindex @code{--jit-debug}
+Enable JIT compiler debugging and tracing.
+
 @item --line-editing
 @cindex @code{--line-editing}
 Force readline use for command-line editing.
 
+@item --no-gui
+@cindex @code{--no-gui}
+Disable the graphical user interface (GUI) and use the command line
+interface (CLI) instead.
+
 @item  --no-history
 @itemx -H
 @cindex @code{--no-history}
@@ -160,6 +173,10 @@
 Don't initialize the search path for function files to include default 
 locations.
 
+@item --no-jit-compiler
+@cindex @code{--no-jit-compiler}
+Disable the JIT compiler used for accelerating loops.
+
 @item --no-line-editing
 @cindex @code{--no-line-editing}
 Disable command-line editing.
@@ -168,6 +185,11 @@
 @cindex @code{--no-site-file}
 Don't read the site-wide @file{octaverc} initialization files.
 
+@item --no-window-system
+@cindex @code{--no-window-system}
+Disable use of a windowing system including graphics.  This forces a
+strictly terminal-only environment.
+
 @item  --norc
 @itemx -f
 @cindex @code{--norc}
@@ -199,6 +221,10 @@
 @cindex @code{-q}
 Don't print the usual greeting and version message at startup.
 
+@item --texi-macros-file @var{filename}
+@cindex @code{--texi-macros-file @var{filename}}
+Specify the name of the file containing Texinfo macros for use by makeinfo.
+
 @item  --traditional
 @itemx --braindead
 @cindex @code{--traditional}
@@ -235,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}
@@ -389,6 +421,8 @@
 
 @DOCSTRING(makeinfo_program)
 
+@DOCSTRING(texi_macros_file)
+
 @DOCSTRING(doc_cache_file)
 
 @DOCSTRING(suppress_verbose_help_message)
@@ -1021,10 +1055,10 @@
 @group
 function countdown
   # Count down for main rocket engines 
-  disp(3);
-  disp(2);
-  disp(1);
-  disp("Blast Off!");  # Rocket leaves pad
+  disp (3);
+  disp (2);
+  disp (1);
+  disp ("Blast Off!");  # Rocket leaves pad
 endfunction
 @end group
 @end example
@@ -1044,19 +1078,19 @@
 @group
 function quick_countdown
   # Count down for main rocket engines 
-  disp(3);
+  disp (3);
  #@{
-  disp(2);
-  disp(1);
+  disp (2);
+  disp (1);
  #@}
-  disp("Blast Off!");  # Rocket leaves pad
+  disp ("Blast Off!");  # Rocket leaves pad
 endfunction
 @end group
 @end example
 
 @noindent
 will produce a very quick countdown from '3' to 'Blast Off' as the
-lines "@code{disp(2);}" and "@code{disp(1);}" won't be executed.
+lines "@code{disp (2);}" and "@code{disp (1);}" won't be executed.
 
 The block comment markers must appear alone as the only characters on a line
 (excepting whitespace) in order to be parsed correctly.
--- a/doc/interpreter/container.txi
+++ b/doc/interpreter/container.txi
@@ -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::
@@ -308,7 +308,7 @@
 
 @example
 @group
-[x.a] = deal("new string1", "new string2");
+[x.a] = deal ("new string1", "new string2");
  x(1).a
      @result{} ans = new string1
  x(2).a
@@ -322,7 +322,7 @@
 @example
 @group
 x(3:4) = x(1:2);
-[x([1,3]).a] = deal("other string1", "other string2");
+[x([1,3]).a] = deal ("other string1", "other string2");
 x.a
      @result{}
         ans = other string1
@@ -337,7 +337,7 @@
 
 @example
 @group
-size(x)
+size (x)
      @result{} ans =
 
           1   4
@@ -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)
 
@@ -605,10 +627,10 @@
 
 @example
 @group
-iscell(c)
+iscell (c)
      @result{} ans = 1
 
-iscell(3)
+iscell (3)
      @result{} ans = 0
 
 @end group
@@ -631,7 +653,7 @@
 
 @example
 @group
-c = cell(2,2)
+c = cell (2,2)
      @result{} c =
          
          @{
@@ -652,9 +674,9 @@
 
 @example
 @group
-c1 = cell(3, 4, 5);
-c2 = cell( [3, 4, 5] );
-size(c1)
+c1 = cell (3, 4, 5);
+c2 = cell ( [3, 4, 5] );
+size (c1)
      @result{} ans =
          3   4   5
 @end group
@@ -690,14 +712,14 @@
 
 @example
 @group
-c = @{"1", "2", "3"; "a", "b", "c"; "4", "5", "6"@};
+c = @{"1", "2", "3"; "x", "y", "z"; "4", "5", "6"@};
 c@{2,3@}
-     @result{} ans = c
+     @result{} ans = z
 
 c(2,3)
      @result{} ans = 
         @{
-          [1,1] = c
+          [1,1] = z
         @}
 @end group
 @end example
@@ -766,7 +788,7 @@
 
 @example
 @group
-[c@{[1,2], :@}] = deal(c@{[2, 1], :@})
+[c@{[1,2], :@}] = deal (c@{[2, 1], :@})
      @result{} = 
         @{
           [1,1] =  1
--- a/doc/interpreter/contrib.txi
+++ b/doc/interpreter/contrib.txi
@@ -58,28 +58,35 @@
 @itemize @bullet
 @item
 Check out a copy of the Octave sources:
+
 @example
 hg clone http://www.octave.org/hg/octave
 @end example
 
 @item
 Change to the top-level directory of the newly checked out sources:
+
 @example
 cd octave
 @end example
 
 @item
 Generate the necessary configuration files:
+
 @example
-./autogen.sh
+./bootstrap
 @end example
 
 @item
 Create a build directory and change to it:
+
 @example
+@group
 mkdir build
 cd build
+@end group
 @end example
+
 By using a separate build directory, you will keep the source directory
 clean and it will be easy to completely remove all files generated by
 the build.  You can also have parallel build trees for different
@@ -90,15 +97,18 @@
 
 @item
 Run Octave's configure script from the build directory:
+
 @example
 ../configure
 @end example
 
 @item
 Run make in the build directory:
+
 @example
 make
 @end example
+
 @end itemize
 
 Once the build is finished, you will see a message like the following:
@@ -117,7 +127,11 @@
 @section Basics of Generating a Changeset
 
 The preferable form of contribution is creating a Mercurial changeset
-and sending it via e-mail to the octave-maintainers mailing list.
+and submit it to the @uref{http://savannah.gnu.org/bugs/?group=octave, bug} or
+@uref{http://savannah.gnu.org/patch/?func=additem&group=octave, patch}
+trackers@footnote{Please use the patch tracker only for patches which add new
+features.  If you have a patch to submit that fixes a bug, you should use the
+bug tracker instead.}.
 Mercurial is the source code management system currently used to develop
 Octave.  Other forms of contributions (e.g., simple diff patches) are
 also acceptable, but they slow down the review process.  If you want to
@@ -141,15 +155,14 @@
 hg export -o ../cool.diff tip
                              # export the changeset to a diff
                              # file
-# send ../cool.diff via email
+# attach ../cool.diff to your bug report
 @end group
 @end example
 
 You may want to get familiar with Mercurial queues to manage your
 changesets.  Here is a slightly more complex example using Mercurial
 queues, where work on two unrelated changesets is done in parallel and
-one of the changesets is updated after discussion on the maintainers
-mailing list:
+one of the changesets is updated after discussion on the bug tracker:
 
 @example
 hg qnew nasty_bug            # create a new patch
@@ -160,7 +173,7 @@
                              # save again with commit message
 hg export -o ../nasty.diff tip
                              # export the patch
-# send ../nasty.diff via email
+# attach ../nasty.diff to your bug report
 hg qpop                      # undo the application of the patch
                              # and remove the changes from the
                              # source tree
@@ -170,14 +183,14 @@
                              # save the changes into the patch
 hg export -o ../doc.diff tip
                              # export the second patch
-# send ../doc.diff tip via email
+# attach ../doc.diff to your bug report
 hg qpop
-# discussion in the maintainers mailing list @dots{}
+# discussion in the bug tracker @dots{}
 hg qpush nasty_bug           # apply the patch again
 # change sources yet again @dots{}
 hg qref
 hg export -o ../nasty2.diff tip
-# send ../nasty2.diff via email
+# attach ../nasty2.diff to your bug report
 @end example
 
 @node General Guidelines
@@ -313,7 +326,7 @@
 @example
 @group
 if (isvector (a))
-  s = sum(a);
+  s = sum (a);
 endif
 @end group
 @end example
--- a/doc/interpreter/contributors.in
+++ b/doc/interpreter/contributors.in
@@ -10,6 +10,7 @@
 Alexander Barth
 David Bateman
 Heinz Bauschke
+Julien Bect
 Roman Belov
 Karl Berry
 David Billinghurst
@@ -20,6 +21,7 @@
 Richard Bovey
 John Bradshaw
 Marcus Brinkmann
+Max Brister
 Remy Bruno
 Ansgar Burchard
 Marco Caliari
@@ -47,6 +49,9 @@
 Bill Denney
 Fabian Deutsch
 Christos Dimitrakakis
+Pantxo Diribarne
+Vivek Dogra
+John Donoghue
 David M. Doolin
 Carnë Draug
 Pascal A. Dupuis
@@ -78,6 +83,7 @@
 Steffen Groot
 Etienne Grossmann
 David Grundberg
+Kyle Guinn
 Peter Gustafson
 Kai Habel
 Patrick Häcker
@@ -90,6 +96,7 @@
 Daniel Heiserer
 Martin Helm
 Stefan Hepp
+Martin Hepperle
 Jordi Gutiérrez Hermoso
 Yozo Hida
 Ryan Hinton
@@ -101,6 +108,7 @@
 Kurt Hornik
 Christopher Hulbert
 Cyril Humbert
+John Hunt
 Teemu Ikonen
 Alan W. Irwin
 Geoff Jacobsen
@@ -152,9 +160,11 @@
 Hoxide Ma
 James Macnicol
 Jens-Uwe Mager
+Colin Macdonald
 Rob Mahurin
 Ricardo Marranita
 Orestes Mas
+Axel Mathéi
 Makoto Matsumoto
 Tatsuro Matsuoka
 Laurent Mazet
@@ -162,13 +172,16 @@
 Alexander Mamonov
 Christoph Mayer
 Júlio Hoffimann Mendes
+Ronald van der Meer
 Thorsten Meyer
 Petr Mikulik
+Mike Miller
 Stefan Monnier
 Antoine Moreau
 Kai P. Mueller
 Hannes Müller
 Victor Munoz
+Iain Murray
 Carmen Navarrete
 Todd Neal
 Philip Nienhuis
@@ -182,6 +195,7 @@
 Peter O'Gorman
 Thorsten Ohl
 Arno Onken
+Valentin Ortega-Clavero
 Luis F. Ortiz
 Scott Pakin
 Gabriele Pannocchia
@@ -213,6 +227,7 @@
 Petter Risholm
 Matthew W. Roberts
 Andrew Ross
+Fabio Rossi
 Mark van Rossum
 Joe Rothweiler
 Kevin Ruland
@@ -266,6 +281,7 @@
 Karsten Trulsen
 Frederick Umminger
 Utkarsh Upadhyay
+Daniel Wagenaar
 Stefan van der Walt
 Peter Van Wieren
 James R. Van Zandt
--- a/doc/interpreter/diagperm.txi
+++ b/doc/interpreter/diagperm.txi
@@ -23,7 +23,7 @@
 * Basic Usage::          Creation and Manipulation of Diagonal and Permutation Matrices
 * Matrix Algebra::       Linear Algebra with Diagonal and Permutation Matrices
 * Function Support::     Functions That Are Aware of These Matrices
-* Example Codes::        Some Examples of Usage
+* Example Code::         Some Examples of Usage
 * Zeros Treatment::      The Differences in Treatment of Zero Elements
 @end menu
 
@@ -93,7 +93,7 @@
    0   0   3   0
    0   0   0   4
 
-  diag(1:3,5,3)
+  diag (1:3,5,3)
 
 @result{}
 Diagonal Matrix
@@ -412,7 +412,7 @@
 The @dfn{find} function will also work efficiently with a permutation matrix,
 making it possible to conveniently obtain the permutation indices.
 
-@node Example Codes
+@node Example Code
 @section Some Examples of Usage
 
 The following can be used to solve a linear system @code{A*x = b}
@@ -426,12 +426,23 @@
 @end example
 
 @noindent
-This is how you normalize columns of a matrix @var{X} to unit norm:
+This is one way to normalize columns of a matrix @var{X} to unit norm:
 
 @example
 @group
   s = norm (X, "columns");
-  X = diag (s) \ X;
+  X /= diag (s);
+@end group
+@end example
+
+@noindent
+The same can also be accomplished with broadcasting
+(@pxref{Broadcasting}):
+
+@example
+@group
+  s = norm (X, "columns");
+  X ./= s;
 @end group
 @end example
 
@@ -445,7 +456,7 @@
 @end example
 
 @noindent
-Finally, here's how you solve a linear system @code{A*x = b} 
+Finally, here's how you solve a linear system @code{A*x = b}
 with Tikhonov regularization (ridge regression) using SVD (a skeleton only):
 
 @example
@@ -500,6 +511,7 @@
 This behavior not only facilitates the most straightforward and efficient
 implementation of algorithms, but also preserves certain useful invariants,
 like:
+
 @itemize
 @item scalar * diagonal matrix is a diagonal matrix
 
@@ -542,13 +554,13 @@
 
 @example
 @group
-diag(1:3) * [NaN; 1; 1]
+diag (1:3) * [NaN; 1; 1]
 @result{}
    NaN
      2
      3
 
-sparse(1:3,1:3,1:3) * [NaN; 1; 1]
+sparse (1:3,1:3,1:3) * [NaN; 1; 1]
 @result{}
    NaN
      2
--- a/doc/interpreter/diffeq.txi
+++ b/doc/interpreter/diffeq.txi
@@ -100,8 +100,8 @@
 
 @example
 @group
-t = [0, logspace (-1, log10(303), 150), \
-        logspace (log10(304), log10(500), 150)];
+t = [0, logspace(-1, log10(303), 150), \
+        logspace(log10(304), log10(500), 150)];
 @end group
 @end example
 
--- a/doc/interpreter/doccheck/aspell-octave.en.pws
+++ b/doc/interpreter/doccheck/aspell-octave.en.pws
@@ -66,6 +66,7 @@
 binopdf
 binornd
 Biomathematics
+bitmapped
 bitmax
 bitwise
 bivariate
@@ -120,10 +121,13 @@
 chol
 Cholesky
 cholmod
+chrominance
 cindex
 circ
 circshift
 circum
+classpath
+classpaths
 Clenshaw
 clim
 cloglog
@@ -138,6 +142,8 @@
 collectoutput
 colorbar
 colormap
+colormaps
+ColorOrder
 colperm
 Comint
 Commandline
@@ -259,6 +265,7 @@
 errorbar
 Errorbars
 errorbars
+errordlg
 ErrorHandler
 Esmond
 et
@@ -334,8 +341,9 @@
 geq
 gesdd
 gesvd
-gfortan
+gfortran
 Ghostscript
+Ghostscript's
 gif
 GIF
 glibc
@@ -356,6 +364,7 @@
 gplot
 grabdemo
 GradObj
+GraphicsAlphaBits
 GraphicsMagick
 Graymap
 grayscale
@@ -379,6 +388,7 @@
 hdf
 headerlines
 heartsuit
+helpdlg
 Helvetica
 Hermitian
 Hessenberg
@@ -426,6 +436,7 @@
 inline
 Inline
 inpolygon
+inputdlg
 internet
 interp
 interpderiv
@@ -444,15 +455,20 @@
 isreal
 issparse
 isvector
+iter
 ith
 iy
 Jacobian
 Jacobians
+javaaddpath
+javamem
 ji
+JIT
 jpeg
 JPEG
 jpg
 jvm
+JVM's
 keybindings
 keypress
 Kolmogorov
@@ -486,10 +502,10 @@
 LF
 lfloor
 li
-libcruft
 libcurl
 liblapack
 liboctave
+liboctinterp
 Libtool
 licensors
 lineanchors
@@ -498,8 +514,10 @@
 linespec
 linespoints
 linkprop
+listdlg
 literalspacing
 Liu
+LLVM
 LM
 lm
 loadpath
@@ -531,6 +549,7 @@
 Mahalanobis
 makefile
 makefiles
+makeinfo
 Mandriva
 MANOVA
 manova
@@ -555,6 +574,7 @@
 metafiles
 Metafont
 mex
+mget
 Michelsen
 Microsystems
 MinGW
@@ -565,6 +585,7 @@
 MIP
 miscompiled
 Misra
+mkdir
 mkoctfile
 mldivide
 mmd
@@ -578,7 +599,9 @@
 Montanet
 mpoles
 mpower
+mput
 mrdivide
+msgbox
 MSYS
 mtimes
 Multi
@@ -601,6 +624,7 @@
 nd
 ndgrid
 ne
+Nelder
 neq
 Neudecker
 Neumann
@@ -688,6 +712,7 @@
 poisspdf
 poissrnd
 polyderiv
+polyeig
 polyfit
 polyval
 POSIX
@@ -722,6 +747,7 @@
 QQ
 qrupdate
 QRUPDATE
+QScintilla
 quadcc
 quadgk
 quadl
@@ -730,6 +756,7 @@
 quantile
 Quantile
 quantiles
+questdlg
 Quickhull
 qz
 QZ
@@ -771,6 +798,7 @@
 Rightarrow
 rightarrow
 rline
+rmdir
 RMS
 rnd
 roffset
@@ -779,6 +807,7 @@
 rpath
 RPMs
 rr
+runtime
 sa
 Saad
 Sandia
@@ -824,6 +853,7 @@
 Spearman's
 speye
 spfun
+splinefit
 spmatrix
 spones
 spparms
@@ -854,6 +884,8 @@
 stringanchors
 strncmp
 strncmpi
+strread
+strread's
 struct
 structs
 subarrays
@@ -910,6 +942,8 @@
 tex
 texinfo
 Texinfo
+TextAlphaBits
+textfield
 textscan
 th
 ths
@@ -976,6 +1010,7 @@
 unnormalized
 unpadded
 unpivoted
+unregister
 unshare
 unsymmetric
 untabified
@@ -1007,10 +1042,12 @@
 waitbar
 waitbars
 wallis
+warndlg
 wblcdf
 wblinv
 wblpdf
 wblrnd
+WebKit
 Weibull
 Welch
 welch
@@ -1033,6 +1070,7 @@
 wp
 wspace
 xb
+xc
 xcorr
 xdigit
 xerrorbar
@@ -1054,6 +1092,7 @@
 xyerrorbar
 xyerrorbars
 xyz
+yc
 ydata
 yerrorbar
 yerrorbars
--- a/doc/interpreter/dynamic.txi
+++ b/doc/interpreter/dynamic.txi
@@ -551,7 +551,7 @@
 should use @code{numel} rather than @code{nelem}.  Note that for very
 large matrices, where the product of the two dimensions is larger than
 the representation of an unsigned int, then @code{numel} can overflow.
-An example is @code{speye(1e6)} which will create a matrix with a million
+An example is @code{speye (1e6)} which will create a matrix with a million
 rows and columns, but only a million non-zero elements.  Therefore the
 number of rows by the number of columns in this case is more than two
 hundred times the maximum value that can be represented by an unsigned int.
@@ -901,9 +901,9 @@
 @group
 funcdemo (@@sin,1)
 @result{} 0.84147
-funcdemo (@@(x) sin(x), 1)
+funcdemo (@@(x) sin (x), 1)
 @result{} 0.84147
-funcdemo (inline ("sin(x)"), 1)
+funcdemo (inline ("sin (x)"), 1)
 @result{} 0.84147
 funcdemo ("sin",1)
 @result{} 0.84147
@@ -1008,7 +1008,7 @@
 @result{}
   b = 1.00000   0.50000   0.33333
   s = There are   3 values in the input vector
-[b, s] = fortdemo(0:3)
+[b, s] = fortdemo (0:3)
 error: fortsub:divide by zero
 error: exception encountered in Fortran subroutine fortsub_
 error: fortdemo: error in Fortran
@@ -1086,7 +1086,7 @@
 for (octave_idx_type i = 0; i < a.nelem (); i++)
   @{
     OCTAVE_QUIT;
-    b.elem(i) = 2. * a.elem(i);
+    b.elem (i) = 2. * a.elem (i);
   @}
 @end group
 @end example
@@ -1195,9 +1195,9 @@
 @group
 /*
 
-%!error (sin())
-%!error (sin(1,1))
-%!assert (sin([1,2]),[sin(1),sin(2)])
+%!error (sin ())
+%!error (sin (1,1))
+%!assert (sin ([1,2]),[sin(1),sin(2)])
 
 */
 @end group
@@ -1279,7 +1279,7 @@
 
 @example
 @group
-firstmexdemo()
+firstmexdemo ()
 @result{} 1.2346
 @end group
 @end example
@@ -1324,10 +1324,10 @@
 
 @example
 @group
-myfunc()
+myfunc ()
 @result{} You called function: myfunc
     This is the principal function
-myfunc2()
+myfunc2 ()
 @result{} You called function: myfunc2
 @end group
 @end example
@@ -1371,7 +1371,7 @@
 mwSize *dims;
 UINT32_T *pr;
 
-dims = (mwSize *) mxMalloc (2 * sizeof(mwSize));
+dims = (mwSize *) mxMalloc (2 * sizeof (mwSize));
 dims[0] = 2;
 dims[1] = 2;
 m = mxCreateNumericArray (2, dims, mxUINT32_CLASS, mxREAL);
@@ -1403,8 +1403,8 @@
 
 @example
 @group
-b = randn(4,1) + 1i * randn(4,1);
-all(b.^2 == mypow2(b))
+b = randn (4,1) + 1i * randn (4,1);
+all (b.^2 == mypow2 (b))
 @result{} 1
 @end group
 @end example
@@ -1434,7 +1434,7 @@
 
 @example
 @group
-mystring(["First String"; "Second String"])
+mystring (["First String"; "Second String"])
 @result{} s1 = Second String
         First String
 @end group
@@ -1549,7 +1549,7 @@
 @example
 a(1).f1 = "f11"; a(1).f2 = "f12"; 
 a(2).f1 = "f21"; a(2).f2 = "f22";
-b = mystruct(a)
+b = mystruct (a)
 @result{} field f1(0) = f11
     field f1(1) = f21
     field f2(0) = f12
@@ -1651,8 +1651,8 @@
 
 @example
 @group
-myfeval("sin", 1)
-a = myfeval("sin", 1)
+myfeval ("sin", 1)
+a = myfeval ("sin", 1)
 @result{} Hello, World!
     I have 2 inputs and 1 outputs
     I'm going to call the interpreter function sin
@@ -1719,7 +1719,7 @@
 @group
 $ mkoctfile --link-stand-alone embedded.cc -o embedded
 $ ./embedded
-GCD of [5, 10] is 5
+GCD of [10, 15] is 5
 $
 @end group
 @end example
--- a/doc/interpreter/emacs.txi
+++ b/doc/interpreter/emacs.txi
@@ -329,6 +329,7 @@
 @end table
 
 If Font Lock mode is enabled, Octave mode will display
+
 @itemize @bullet
 @item
 strings in @code{font-lock-string-face}
@@ -436,6 +437,7 @@
 
 The effect of the commands which send code to the Octave process can be
 customized by the following variables.
+
 @table @code
 @item octave-send-echo-input
 Non-@code{nil} means echo input sent to the inferior Octave process.
--- a/doc/interpreter/errors.txi
+++ b/doc/interpreter/errors.txi
@@ -63,7 +63,7 @@
 @group
 function f (arg1)
   if (nargin == 0)
-    error("not enough input arguments");
+    error ("not enough input arguments");
   endif
 endfunction
 @end group
@@ -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)
-
-
--- a/doc/interpreter/eval.txi
+++ b/doc/interpreter/eval.txi
@@ -127,8 +127,8 @@
 @group
 function save (file, name1, name2)
   f = open_save_file (file);
-  save_var(f, name1, evalin ("caller", name1));
-  save_var(f, name2, evalin ("caller", name2));
+  save_var (f, name1, evalin ("caller", name1));
+  save_var (f, name2, evalin ("caller", name2));
 endfunction
 @end group
 @end example
--- a/doc/interpreter/expr.txi
+++ b/doc/interpreter/expr.txi
@@ -258,7 +258,7 @@
 $a_i = \sqrt{i}$.
 @end tex
 @ifnottex
-a(i) = sqrt(i).
+a(i) = sqrt (i).
 @end ifnottex
 
 @example
@@ -772,8 +772,8 @@
 
 @example
 @group
-  abs(@var{z1}) < abs(@var{z2}) 
-  || (abs(@var{z1}) == abs(@var{z2}) && arg(@var{z1}) < arg(@var{z2}))
+  abs (@var{z1}) < abs (@var{z2}) 
+  || (abs (@var{z1}) == abs (@var{z2}) && arg (@var{z1}) < arg (@var{z2}))
 @end group
 @end example
 
--- a/doc/interpreter/find-docstring-files.sh
+++ b/doc/interpreter/find-docstring-files.sh
@@ -5,7 +5,7 @@
   exit 1
 fi
 
-## if there is a file in teh build directory tree, assume it is
+## if there is a file in the build directory tree, assume it is
 ## the file we are looking for.  Otherwise, get the one from the
 ## source tree.
 
@@ -15,8 +15,8 @@
   echo "$1/scripts/DOCSTRINGS"
 fi
 
-if [ -f "../../src/DOCSTRINGS" ]; then
-  echo "../../src/DOCSTRINGS"
+if [ -f "../../libinterp/DOCSTRINGS" ]; then
+  echo "../../libinterp/DOCSTRINGS"
 else
-  echo "$1/src/DOCSTRINGS"
+  echo "$1/libinterp/DOCSTRINGS"
 fi
--- a/doc/interpreter/func.txi
+++ b/doc/interpreter/func.txi
@@ -29,6 +29,7 @@
 like built-in functions.
 
 @menu
+* Introduction to Function and Script Files::
 * Defining Functions::          
 * Multiple Return Values::      
 * Variable-length Argument Lists::  
@@ -43,6 +44,39 @@
 * Organization of Functions::   
 @end menu
 
+@node Introduction to Function and Script Files
+@section Introduction to Function and Script Files
+
+There are seven different things covered in this section.
+@enumerate
+@item
+Typing in a function at the command prompt.
+
+@item
+Storing a group of commands in a file --- called a script file.
+
+@item
+Storing a function in a file---called a function file.
+
+@item
+Subfunctions in function files.
+
+@item
+Multiple functions in one script file.
+
+@item
+Private functions.
+
+@item
+Nested functions.
+@end enumerate
+
+Both function files and script files end with an extension of .m, for
+@sc{matlab} compatibility.  If you want more than one independent
+functions in a file, it must be a script file (@pxref{Script Files}),
+and to use these functions you must execute the script file before you
+can use the functions that are in the script file.
+
 @node Defining Functions
 @section Defining Functions
 @cindex @code{function} statement
@@ -717,6 +751,7 @@
 * Manipulating the Load Path::
 * Subfunctions::
 * Private Functions::
+* Nested Functions::
 * Overloading and Autoloading::
 * Function Locking::
 * Function Precedence::
@@ -737,7 +772,7 @@
 code adds @samp{~/Octave} to the load path.
 
 @example
-addpath("~/Octave")
+addpath ("~/Octave")
 @end example
 
 @noindent
@@ -825,6 +860,157 @@
 then @code{func2} is only available for use of the functions, like 
 @code{func1}, that are found in @code{<directory>}.
 
+@node Nested Functions
+@subsection Nested Functions
+
+Nested functions are similar to subfunctions in that only the main function is
+visible outside the file.  However, they also allow for child functions to
+access the local variables in their parent function.  This shared access mimics
+using a global variable to share information --- but a global variable which is
+not visible to the rest of Octave.  As a programming strategy, sharing data
+this way can create code which is difficult to maintain.  It is recommended to
+use subfunctions in place of nested functions when possible.
+
+As a simple example, consider a parent function @code{foo}, that calls a nested
+child function @code{bar}, with a shared variable @var{x}.
+
+@example
+@group
+function y = foo ()
+  x = 10;
+  bar ();
+  y = x;
+
+  function bar ()
+    x = 20;
+  endfunction
+endfunction
+
+foo ()
+ @result{} 20
+@end group
+@end example
+
+@noindent
+Notice that there is no special syntax for sharing @var{x}.  This can lead to
+problems with accidental variable sharing between a parent function and its
+child.  While normally variables are inherited, child function parameters and
+return values are local to the child function.
+
+Now consider the function @code{foobar} that uses variables @var{x} and
+@var{y}.  @code{foobar} calls a nested function @code{foo} which takes
+@var{x} as a parameter and returns @var{y}.  @code{foo} then calls @code{bat}
+which does some computation.
+
+@example
+@group
+function z = foobar ()
+  x = 0;
+  y = 0;
+  z = foo (5);
+  z += x + y;
+
+  function y = foo (x)
+    y = x + bat ();
+
+    function z = bat ()
+      z = x;
+    endfunction
+  endfunction
+endfunction
+
+foobar ()
+    @result{} 10
+@end group
+@end example
+
+@noindent
+It is important to note that the @var{x} and @var{y} in @code{foobar} remain
+zero, as in @code{foo} they are a return value and parameter respectively.  The
+@var{x} in @code{bat} refers to the @var{x} in @code{foo}.
+
+Variable inheritance leads to a problem for @code{eval} and scripts.  If a
+new variable is created in a parent function, it is not clear what should happen
+in nested child functions.  For example, consider a parent function @code{foo}
+with a nested child function @code{bar}:
+
+@example
+@group
+function y = foo (to_eval)
+  bar ();
+  eval (to_eval);
+
+  function bar ()
+    eval ("x = 100;");
+    eval ("y = x;");
+  endfunction
+endfunction
+
+foo ("x = 5;")
+    @result{} error: can not add variable "x" to a static workspace
+
+foo ("y = 10;")
+    @result{} 10
+
+foo ("")
+    @result{} 100
+@end group
+@end example
+
+@noindent
+The parent function @code{foo} is unable to create a new variable
+@var{x}, but the child function @code{bar} was successful.  Furthermore, even
+in an @code{eval} statement @var{y} in @code{bar} is the same @var{y} as in its
+parent function @code{foo}.  The use of @code{eval} in conjunction with nested
+functions is best avoided.
+
+As with subfunctions, only the first nested function in a file may be called
+from the outside.  Inside a function the rules are more complicated.  In
+general a nested function may call:
+
+@enumerate 0
+@item
+Globally visible functions
+
+@item
+Any function that the nested function's parent can call
+
+@item
+Sibling functions (functions that have the same parents)
+
+@item
+Direct children
+
+@end enumerate
+
+As a complex example consider a parent function @code{ex_top} with two
+child functions, @code{ex_a} and @code{ex_b}.  In addition, @code{ex_a} has two
+more child functions, @code{ex_aa} and @code{ex_ab}.  For example:
+
+@example
+function ex_top ()
+  ## Can call: ex_top, ex_a, and ex_b
+  ## Can NOT call: ex_aa and ex_ab
+
+  function ex_a ()
+    ## Call call everything
+
+    function ex_aa ()
+      ## Can call everything
+    endfunction
+
+    function ex_ab ()
+      ## Can call everything
+    endfunction
+  endfunction
+
+  function ex_b ()
+    ## Can call: ex_top, ex_a, and ex_b
+    ## Can NOT call: ex_aa and ex_ab
+  endfunction
+endfunction
+@end example
+
 @node Overloading and Autoloading
 @subsection Overloading and Autoloading
 
@@ -891,7 +1077,7 @@
 
 @example
 @group
-function count_calls()
+function count_calls ()
   persistent calls = 0;
   printf ("'count_calls' has been called %d times\n",
           ++calls);
@@ -1214,7 +1400,7 @@
 function @math{f(x) = x^2 + 2}.
 
 @example
-f = inline("x^2 + 2");
+f = inline ("x^2 + 2");
 @end example
 
 @noindent
@@ -1244,7 +1430,7 @@
 is equivalent to 
 
 @example
-my_command("hello", "world")
+my_command ("hello", "world")
 @end example
 
 @noindent
--- a/doc/interpreter/geometry.txi
+++ b/doc/interpreter/geometry.txi
@@ -72,7 +72,7 @@
 X = [ x(T(:,1)); x(T(:,2)); x(T(:,3)); x(T(:,1)) ];
 Y = [ y(T(:,1)); y(T(:,2)); y(T(:,3)); y(T(:,1)) ];
 axis ([0, 1, 0, 1]);
-plot(X, Y, "b", x, y, "r*");
+plot (X, Y, "b", x, y, "r*");
 @end group
 @end example
 
@@ -96,6 +96,7 @@
 
 Octave has the functions @code{triplot}, @code{trimesh}, and @code{trisurf}
 to plot the Delaunay triangulation of a 2-dimensional set of points.
+@code{tetramesh} will plot the triangulation of a 3-dimensional set of points.
 
 @DOCSTRING(triplot)
 
@@ -103,6 +104,8 @@
 
 @DOCSTRING(trisurf)
 
+@DOCSTRING(tetramesh)
+
 The difference between @code{triplot}, and @code{trimesh} or @code{triplot},
 is that the former only plots the 2-dimensional triangulation itself, whereas
 the second two plot the value of a function @code{f (@var{x}, @var{y})}.  An
@@ -169,7 +172,7 @@
 @example
 @group
 @var{p} - @var{t}(end, :) = @var{beta}(1:end-1) * (@var{t}(1:end-1, :)
-      - ones(@var{N}, 1) * @var{t}(end, :)
+      - ones (@var{N}, 1) * @var{t}(end, :)
 @end group
 @end example
 
@@ -179,8 +182,8 @@
 @example
 @group
 @var{beta}(1:end-1) = (@var{p} - @var{t}(end, :)) / (@var{t}(1:end-1, :)
-      - ones(@var{N}, 1) * @var{t}(end, :))
-@var{beta}(end) = sum(@var{beta}(1:end-1))
+      - ones (@var{N}, 1) * @var{t}(end, :))
+@var{beta}(end) = sum (@var{beta}(1:end-1))
 @end group
 @end example
 
@@ -295,9 +298,9 @@
 
 @example
 @group
-rand("state",9);
-x = rand(10,1);
-y = rand(10,1);
+rand ("state",9);
+x = rand (10,1);
+y = rand (10,1);
 tri = delaunay (x, y);
 [vx, vy] = voronoi (x, y, tri);
 triplot (tri, x, y, "b");
@@ -333,7 +336,7 @@
 x = rand (10, 1);
 y = rand (10, 1);
 [c, f] = voronoin ([x, y]);
-af = zeros (size(f));
+af = zeros (size (f));
 for i = 1 : length (f)
   af(i) = polyarea (c (f @{i, :@}, 1), c (f @{i, :@}, 2));
 endfor
@@ -358,7 +361,7 @@
 vx = cos (pi * [-1 : 0.1: 1]);
 vy = sin (pi * [-1 : 0.1 : 1]);
 in = inpolygon (x, y, vx, vy);
-plot(vx, vy, x(in), y(in), "r+", x(!in), y(!in), "bo");
+plot (vx, vy, x(in), y(in), "r+", x(!in), y(!in), "bo");
 axis ([-2, 2, -2, 2]);
 @end group
 @end example
@@ -431,12 +434,12 @@
 
 @example
 @group
-rand("state",1);
-x=2*rand(1000,1)-1;
-y=2*rand(size(x))-1;
-z=sin(2*(x.^2+y.^2));
-[xx,yy]=meshgrid(linspace(-1,1,32));
-griddata(x,y,z,xx,yy);
+rand ("state", 1);
+x = 2*rand (1000,1) - 1;
+y = 2*rand (size (x)) - 1;
+z = sin (2*(x.^2+y.^2));
+[xx,yy] = meshgrid (linspace (-1,1,32));
+griddata (x,y,z,xx,yy);
 @end group
 @end example
 
--- a/doc/interpreter/geometryimages.m
+++ b/doc/interpreter/geometryimages.m
@@ -29,7 +29,7 @@
     d_typ = cstrcat ("-d", typ);
   endif
 
-  if (isempty (findstr (octave_config_info ("DEFS"), "HAVE_QHULL"))
+  if (! __have_feature__ ("QHULL")
       && (strcmp (nm, "voronoi") || strcmp (nm, "griddata")
           || strcmp (nm, "convhull") || strcmp (nm, "delaunay")
           || strcmp (nm, "triplot")))
--- a/doc/interpreter/grammar.txi
+++ b/doc/interpreter/grammar.txi
@@ -46,12 +46,12 @@
 @item @code{endif} @tab @code{endmethods} @tab @code{endparfor}
 @item @code{endproperties} @tab @code{endswitch} @tab @code{endwhile}
 @item @code{enumeration} @tab @code{events} @tab @code{for}
-@item @code{function} @tab @code{get} @tab @code{global}
-@item @code{if} @tab @code{methods} @tab @code{otherwise}
-@item @code{parfor} @tab @code{persistent} @tab @code{properties}
-@item @code{return} @tab @code{set} @tab @code{static}
-@item @code{switch} @tab @code{try} @tab @code{until}
-@item @code{unwind_protect} @tab @code{unwind_protect_cleanup} @tab @code{while}
+@item @code{function} @tab @code{global} @tab @code{if}
+@item @code{methods} @tab @code{otherwise} @tab @code{parfor}
+@item @code{persistent} @tab @code{properties} @tab @code{return}
+@item @code{static} @tab @code{switch} @tab @code{try}
+@item @code{until} @tab @code{unwind_protect} @tab @code{unwind_protect_cleanup}
+@item @code{while}
 @end multitable
 
 The function @code{iskeyword} can be used to quickly check whether an
--- a/doc/interpreter/image.txi
+++ b/doc/interpreter/image.txi
@@ -60,7 +60,7 @@
 @group
 I = imread ("my_input_image.img");
 J = process_my_image (I);
-imwrite ("my_output_image.img", J);
+imwrite (J, "my_output_image.img");
 @end group
 @end example
 
@@ -93,15 +93,15 @@
 @node Representing Images
 @section Representing Images
 
-In general Octave supports four different kinds of images, gray-scale
-images, RGB images, binary images, and indexed images.  A gray-scale
+In general Octave supports four different kinds of images, grayscale
+images, RGB images, binary images, and indexed images.  A grayscale
 image is represented with an M-by-N matrix in which each
 element corresponds to the intensity of a pixel.  An RGB image is
 represented with an M-by-N-by-3 array where each
 3-vector corresponds to the red, green, and blue intensities of each
 pixel.
 
-The actual meaning of the value of a pixel in a gray-scale or RGB
+The actual meaning of the value of a pixel in a grayscale or RGB
 image depends on the class of the matrix.  If the matrix is of class
 @code{double} pixel intensities are between 0 and 1, if it is of class
 @code{uint8} intensities are between 0 and 255, and if it is of class
@@ -117,6 +117,8 @@
 an RGB color.  The color map must be of class @code{double} with values
 between 0 and 1.
 
+@DOCSTRING(iscolormap)
+
 @DOCSTRING(gray2ind)
 
 @DOCSTRING(ind2gray)
@@ -127,10 +129,14 @@
 
 @DOCSTRING(colormap)
 
+@DOCSTRING(rgbplot)
+
 @DOCSTRING(autumn)
 
 @DOCSTRING(bone)
 
+@DOCSTRING(colorcube)
+
 @DOCSTRING(cool)
 
 @DOCSTRING(copper)
@@ -145,6 +151,8 @@
 
 @DOCSTRING(jet)
 
+@DOCSTRING(lines)
+
 @DOCSTRING(ocean)
 
 @DOCSTRING(pink)
@@ -166,9 +174,9 @@
 An additional colormap is @code{gmap40}.  This code map contains only
 colors with integer values of the red, green and blue components.  This
 is a workaround for a limitation of gnuplot 4.0, that does not allow the color
-of line or patch objects to be set, and so @code{gmap40} is useful for gnuplot
-4.0 users, and in particular in conjunction with the @var{bar},
-@var{barh} or @var{contour} functions.
+of line or patch objects to be set.  @code{gmap40} is chiefly useful to gnuplot
+4.0 users, and particularly in conjunction with the @var{bar}, @var{surf},
+and @var{contour} functions.
 
 @DOCSTRING(gmap40)
 
@@ -181,6 +189,12 @@
 
 @DOCSTRING(whitebg)
 
+The following functions can be used to manipulate colormaps.
+
+@DOCSTRING(cmunique)
+
+@DOCSTRING(cmpermute)
+
 @node Plotting on top of Images
 @section Plotting on top of Images
 
--- a/doc/interpreter/images
+++ b/doc/interpreter/images
@@ -2,3 +2,4 @@
 interpimages.m interpft interpn interpderiv1 interpderiv2
 plotimages.m plot hist errorbar polar mesh plot3 extended
 sparseimages.m gplot grid spmatrix spchol spcholperm
+splineimages.m splinefit1 splinefit2 splinefit3 splinefit4 splinefit6
--- a/doc/interpreter/images.awk
+++ b/doc/interpreter/images.awk
@@ -4,7 +4,6 @@
   exts[3] = "png";
   exts[4] = "txt";
   printf ("IMAGES_SRC =\n");
-  printf ("HTMLDIR_IMAGES =\n");
   for (i = 1; i <= 4; i++) {
     printf ("IMAGES_%s =\n", toupper (exts[i]));
   }
@@ -25,18 +24,7 @@
 
     printf ("IMAGES_%s += $(%s_%s)\n", uext, ubasename, uext);
 
-    if (ext == "png") {
-      printf ("HTMLDIR_IMAGES += ");
-      for (j = 2; j <= NF; j++)
-        printf (" octave.html/%s.png", $j);
-      printf ("\n");
-    }
-
     for (j = 2; j <= NF; j++) {
-      if (ext == "png") {
-	printf ("octave.html/%s.png: %s.png octave.html/index.html\n", $j, $j);
-	printf ("\tcp $< $@\n");
-      }
       printf ("%s.%s: %s\n", $j, ext, script);
       printf ("\t$(top_builddir)/run-octave -f -q -H -p $(srcdir) --eval \"%s ('%s', '%s');\"\n",
 	      basename, $j, ext);
--- a/doc/interpreter/install.txi
+++ b/doc/interpreter/install.txi
@@ -65,16 +65,16 @@
 yourself.
 
 @menu
-* Obtaining the Depencies Automatically::
+* Obtaining the Dependencies Automatically::
 * Build Tools::
 * External Packages::
 @end menu
 
-@node Obtaining the Depencies Automatically
-@subsection Obtaining the Depencies Automatically
+@node Obtaining the Dependencies Automatically
+@subsection Obtaining the Dependencies Automatically
 
 On some systems you can obtain many of Octave's build dependencies
-automatically. The commands for doing this vary by system. Similarly,
+automatically.  The commands for doing this vary by system.  Similarly,
 the names of pre-compiled packages vary by system and do not always
 match exactly the names listed in @ref{Build Tools} and @ref{External
 Packages}.
@@ -182,8 +182,10 @@
 (@url{http://www.netlib.org/blas}).  Accelerated BLAS libraries such as
 ATLAS (@url{http://math-atlas.sourceforge.net}) are recommeded for
 better performance.
+
 @item LAPACK
 Linear Algebra Package (@url{http://www.netlib.org/lapack}).
+
 @item PCRE
 The Perl Compatible Regular Expression library (http://www.pcre.org).
 @end table
@@ -196,7 +198,7 @@
 @end table
 
 If you wish to build Octave without GNU readline installed, you must use
-the @code{--disable-readline} option when running the configure script.
+the @option{--disable-readline} option when running the configure script.
 
 The following external software packages are optional but recommended:
 
@@ -248,8 +250,13 @@
 (@url{http://www.hdfgroup.org/HDF5}).  HDF5 is required for Octave's
 @code{load} and @code{save} commands to read and write HDF data files.
 
+@item LLVM
+Compiler framework, (@url{http://www.llvm.org}). LLVM is required for
+Octave's experimental just-in-time (JIT) compilation for speeding up the
+interpreter.
+
 @item OpenGL
-API for portable 2D and 3D graphics (@url{http://www.opengl.org}).  An
+API for portable 2-D and 3-D graphics (@url{http://www.opengl.org}).  An
 OpenGL implementation is required to provide Octave's OpenGL-based
 graphics functions.  Octave's OpenGL-based graphics functions usually
 outperform the gnuplot-based graphics functions because plot data can be
@@ -268,6 +275,17 @@
 provide improved performance for the functions @code{qrdelete},
 @code{qrinsert}, @code{qrshift}, and @code{qrupdate}.
 
+@item QScintilla
+Source code highlighter and manipulator; a Qt  port of Scintilla
+(@url{http://www.riverbankcomputing.co.uk/software/qscintilla}).
+QScintilla is used for syntax highlighting and code completion in the
+GUI.
+
+@item Qt
+GUI and utility libraries (@url{}). Qt is required for building the GUI.
+It is a large framework, but the only components required are the GUI,
+core, WebKit, and network modules.
+
 @item SuiteSparse
 Sparse matrix factorization library
 (@url{http://www.cise.ufl.edu/research/sparse/SuiteSparse}).
@@ -277,7 +295,7 @@
 @item zlib
 Data compression library (@url{http://zlib.net}).  The zlib library is
 required for Octave's @code{load} and @code{save} commands to handle
-compressed data, including @sc{Matlab} v5 MAT files.
+compressed data, including @sc{matlab} v5 MAT files.
 @end table
 
 @node Running Configure and Make
@@ -521,7 +539,7 @@
 Octave and other binaries that people will want to run directly.
 
 @item @var{prefix}/lib/octave-@var{version}
-Libraries like libcruft.a and liboctave.a.
+Libraries like liboctave.a and liboctinterp.a.
 
 @item @var{prefix}/octave-@var{version}/include/octave
 Include files distributed with Octave.
@@ -778,12 +796,12 @@
 @end example
 
 You must ensure that all Fortran sources except those in the
-@file{libcruft/ranlib} directory are compiled such that INTEGERS are
-8-bytes wide.  If you are using gfortan, the configure script should
+@file{liboctave/cruft/ranlib} directory are compiled such that INTEGERS are
+8-bytes wide.  If you are using gfortran, the configure script should
 automatically set the Makefile variable @w{@env{F77_INTEGER_8_FLAG}} to 
 @option{-fdefault-integer-8}.  If you are using another compiler, you
 must set this variable yourself.  You should NOT set this flag in
-@env{FFLAGS}, otherwise the files in @file{libcruft/ranlib} will be
+@env{FFLAGS}, otherwise the files in @file{liboctave/cruft/ranlib} will be
 miscompiled.
 
 @item Other dependencies
@@ -958,7 +976,7 @@
 @end example
 
 @noindent
-when compiling the Fortran subroutines in the @file{libcruft}
+when compiling the Fortran subroutines in the @file{liboctave/cruft}
 subdirectory, you should either upgrade your compiler or try compiling
 with optimization turned off.
 
--- a/doc/interpreter/interp.txi
+++ b/doc/interpreter/interp.txi
@@ -50,17 +50,17 @@
 dt = 1;
 ti =-2:0.025:2;
 dti = 0.025;
-y = sign(t);
-ys = interp1(t,y,ti,'spline');
-yp = interp1(t,y,ti,'pchip');
-ddys = diff(diff(ys)./dti)./dti;
-ddyp = diff(diff(yp)./dti)./dti;
-figure(1);
-plot (ti, ys,'r-', ti, yp,'g-');
-legend('spline','pchip',4);
-figure(2);
-plot (ti, ddys,'r+', ti, ddyp,'g*');
-legend('spline','pchip');
+y = sign (t);
+ys = interp1 (t,y,ti,'spline');
+yp = interp1 (t,y,ti,'pchip');
+ddys = diff (diff (ys)./dti) ./ dti;
+ddyp = diff (diff (yp)./dti) ./ dti;
+figure (1);
+plot (ti,ys,'r-', ti,yp,'g-');
+legend ('spline', 'pchip', 4);
+figure (2);
+plot (ti,ddys,'r+', ti,ddyp,'g*');
+legend ('spline', 'pchip');
 @end group
 @end example
 
@@ -107,9 +107,9 @@
 ti = t(1) + [0 : k-1]*dt*n/k;
 y = sin (4*t + 0.3) .* cos (3*t - 0.1);
 yp = sin (4*ti + 0.3) .* cos (3*ti - 0.1);
-plot (ti, yp, 'g', ti, interp1(t, y, ti, 'spline'), 'b', ...
+plot (ti, yp, 'g', ti, interp1 (t, y, ti, 'spline'), 'b', ...
       ti, interpft (y, k), 'c', t, y, 'r+');
-legend ('sin(4t+0.3)cos(3t-0.1','spline','interpft','data');
+legend ('sin(4t+0.3)cos(3t-0.1', 'spline', 'interpft', 'data');
 @end group
 @end example
 
@@ -164,9 +164,9 @@
 v = f (xx,yy,zz);
 xi = yi = zi = -1:0.1:1;
 [xxi, yyi, zzi] = meshgrid (xi, yi, zi);
-vi = interp3(x, y, z, v, xxi, yyi, zzi, 'spline');
+vi = interp3 (x, y, z, v, xxi, yyi, zzi, 'spline');
 [xxi, yyi, zzi] = ndgrid (xi, yi, zi);
-vi2 = interpn(x, y, z, v, xxi, yyi, zzi, 'spline');
+vi2 = interpn (x, y, z, v, xxi, yyi, zzi, 'spline');
 mesh (zi, yi, squeeze (vi2(1,:,:)));
 @end group
 @end example
--- a/doc/interpreter/intro.txi
+++ b/doc/interpreter/intro.txi
@@ -104,7 +104,7 @@
 tolerance of the calculation. 
 
 @example
-octave:1> exp(i*pi)
+octave:1> exp (i*pi)
 @end example
 
 @subsection Creating a Matrix
--- a/doc/interpreter/io.txi
+++ b/doc/interpreter/io.txi
@@ -230,6 +230,11 @@
 
 @DOCSTRING(textscan)
 
+The @code{importdata} function has the ability to work with a wide
+variety of data.
+
+@DOCSTRING(importdata)
+
 @menu
 * Saving Data on Unexpected Exits::
 @end menu
@@ -239,7 +244,7 @@
 
 If Octave for some reason exits unexpectedly it will by default save the
 variables available in the workspace to a file in the current directory.
-By default this file is named @samp{octave-core} and can be loaded
+By default this file is named @samp{octave-workspace} and can be loaded
 into memory with the @code{load} command.  While the default behavior
 most often is reasonable it can be changed through the following
 functions.
new file mode 100644
index 0000000000000000000000000000000000000000..d5ffef6d4345c4a12336e6ca5a03eeed7e6ca750
GIT binary patch
literal 14199
zc$~Gk^;cWn^9Gs_2zGEwTC|3=K!BEFg#a~*7ARIExD}_k1qrmYKwI2t@nVJI7Tn$4
z-QCIMec#XbuKN$%{E&09v)1gH*)z{P&;F#O@QRG&76}LhB9nRjTp0ucbKblM5<zah
zJs;@B-aPP4CFLbSpg$oV7jJ*u{AM+Ltt<}$x!nhWeEdM5Gu+K{6$JW-0D;y~AdpBD
z2*h9$l@&7x0zp7Za;h)-yPBUUej4iP`#?(k$}DPhup<ge$o<@XQ%48w<2l;0ND{q;
zyErOq8>8W|?Hi~V>T7KuY>%#7nwuIP>}@1*Tp!-N?(1y-7}-);nje@wjPdp9YOC)W
zs%!7>o9Jja!Ia}JcCeLyvy63?u5t9(v*EtZ@$RPSvHsYy3EcJB^4xev>0-y=)L>6r
zYh(3lW4WwWcxwIPJD1=6gC%C}g<lhTJ388=rIF&#M4CHBF{vH0rm3A)R(FK0<~pk9
ztFYRR#e;oyUO&6%+uF~|iwN<+33Xe|brq>ihdMq5mH5PWo_g<J<0O${=7CMYrGrHk
zEgd5jk?CV@QKiE@Exn!f{rx@j?VHlt>7@gCEBL^<l+y4*Z$~qBpr`rbGsex$nVLg)
zv9D`<xU03VQ`0=f2~*`B*Q4^`@5aik*^d&Vpd8=e$kMvCqemhQ0|V%9O(hE*hg&PA
zAx7to^}PewptQL=0&gPomYVyT-{xNNPhJlUjt_NrU0%&ZH%-m7Om?)?4AHPc-nI7h
zbrIin5>t(z80qaC8tfYB8t85Be=1Vb+1S#YIS_`K=xK{B-K}mu85p1UNvKJU_}Vo#
zF~4)w+BY`UP*c;?Y2b-%o-G#*I1@lBTZdu?vDm_#G+!HI`H*op@6XuI?yDo*abIii
zc(<e&lK8eZQpp%MH;Fsm$E_ZoxVZ0+tjHM_)J|aQM>_Hb&Y$Uq+@>O4y&M_q&l&5+
zZe4HIk6axw-rZkqs%b0j&P{HpDQ#q?$WnX_dY;lU`Kx!dp<!qZY~4KEnH5?%J>Asi
zl)j~8m)Ox=*wZ-D+=^{(>QIw^fzE9o9_g_Q$%l~gjLok&CRg|L47N-RZk${%%{LCr
zj5&n%e$DP~9d4p!<?A2nJ~`MK9&8Thd~}(ep5C?4-#$3dT94#rA8qf_@JbkKY3y%l
z>uGNs?JJ%gZ5-*VN-U2Y8m;|NFnGPy7npZ2+%tVO(~OIc?r!*Vj9WwLsmmvI_x868
z_O?`5bCrNV0>?7XB~@MG4HT9|C01T*r_CR4jI)&9*Nm9To!|2~KYJ~A{xR5c2NLy%
zYp;xH+~sI4B?1r6S=}qVmiwxD*UKuU&66sl_Rbv}=k2hiZ<JZpJRm5w`qLS)Hk7T?
zg8T~cZP$C#m~D3#tNNptthAJ7lSAH2{shS7No`Mck_Y7J_g!WW^Sp|Xlr@RCWU8S1
zFyp8M6K&i9uP;3ny3fY>=l(bIWNq)z4eE~^5?fx}FrN2#w0eaHBP<23M2waAIoBi2
zJESw$Ps$JO7$1!}WV~sYbxy;bvUR%7$MYdUd_1#Hj);s=nQs>^yWv^`$^(U&Cxq@>
zFFcnjLl>psgYf=E<`nGm_e5$al+}xy#5aBh?l#XLmBJB5){KNhp_CYOz@F`cSXbLt
zP(N6O@FyGW17Yg}D3k~zne6^YD#%UF4w_kM2MId^M9K+5pTl)KB>gS4U@%7V&0SR4
z4hbdl%Y1zmsk5_<K>?mjv@rjqQ9<Q5@3V;Ji|SCJLRjA9DVNBzgC{V*xwLl=Yj&UK
z1ZmiX)VaJNr}Q$({9ua8T+Lhs^|9`%l@&6zcE=|QGc}TF{t$j<L>7d3?RWZmJ_Z;N
zfct2G=H`2cY#*JN@yR`Q=khm*jwSPT@c<yf^GFyz`p~q@wv(C&Q#iLQ<+G6c&f9dF
zL<7b`YM+qO+7KgUPWOAeDF=^;^(9%labV?%m8lSkYMN^T+kBU#EL0I=!Tui8Fvrm3
zEZ`w2L%idEOn<WNsP0mrqD=AK<oSCGA27TSN)L;{8gX9I6S?|`^uW>KK6rWG!6xLs
z(AXC2E|DBRLK}~Y`w0MK6-mN~zIMakl_X6NQxg&Z_=;WEtrU&2tm2TOx=R=Wze!>I
z5v4*L!S}#F17CW0LMv0i#5K2Xg|Ql;%zpc#!i1}ou17M;i~Qa*2=<6O-w&C~4VF>f
z9cKy5*l*dwCt__jGX3@DNTWlTla47lm8viuZ=F3tluJ|<2HOU$k%tLA=GY9oV^#W)
z$d3&Ip~US^w?i8NfE6IHdPiwytKX6KPXD)7WaA*hY_hkk?uw3F@m|8R3F=)nnQzjm
zPuLm@O%DU>BK`w|gY)Je%j{j;7SFrj{M0Kwt<m4Wf~6^7|2mL$R0EjRzcA{RZ}NyB
z>lYoy%4kV|!^G_tP`7{UDGXMxj>*S2l|Ksv1Ydm!`LH+kJ>D~v&8UMSj)2Q~nLT?_
zA0<>|Ii~1@X}OjMf$<+@Jche%A6n=cgDk!pWEv8c)$PhIa<w9q3YbLk|BP-^Qu<bb
zf4;>dWt2nh29puNVWYRQQGEm?tgPe^0;+pHJR5j^F9m<r9mWnn;oixe7QN=j$;W*h
zJ}u!2-{#rkAs8>ZyGbfkCdA-o1tFw^_yvH)qFE&gNblK#Bq794Tv$Q0uYr7@!-oh`
zM%16DVR#)jG>A+X%=$N;AJ?}vyK%3ctzuGEH=2+_8}AtF^Nm#nACLj<wd-<Au4vv<
z{^PPuJN+;Nmu4(>NZrVqKu!g~{#CUL)R!ls#d~r~+lK%Sfp8p4dV!=ClMOBiNZu%g
zNrHRbDDjJ;8hv)Z!*E}(Q+}hD!kUPo7#ezZk_WVMC{(n&g~@rRV}ZzC6q1O08Zttd
zM~Jcf_)yv*_xc5D)jC(g&>k}<gT?p=So)2Ws6+FOM|WDWpv4u%&ZJgb_c!E|+Z(Yc
zBBR`qYT(|pByE%3Npg%+ASw%ZEfB*(Xb>h*2p<)AGIzeirN>LZ7jF~qB~HZZ6K&nj
zms34pw>H8I%`2;~-`(}a%exFb!}^TZ_12+C8!dfy$zivAW>a#p$re|QfkYh8*T^eh
z0$PNhHF&=S%PJI&1Q+|)Ni=(Z!dc*kwty`l6upa2s{pEZ#Ha|!!uw5s5~?nqTLRyZ
zWdV}4!?&aJH<Cb*&vpJO6lObGm}13;Xd@7<S9wB%Z5&(RoCuMVb}e~2Tu>mVwn%)}
zp4HF#!U=^Oa~-!L{0=SfDa3~k*8TwGkOzh6rOI!D(x$cfUkgj^)AnCj2EQ2TuGli1
z<^BRCVtp{I)KLr2-RU_wPYXEeiC^n#J?)yFzW(vqb1EU{(HJq-SI}Rd9MV7lMa39{
z?nz~nHF~)v(Hf3+u|^`E>5FjaMf-WAJ|cZ1GhI6h8-;m{!eAaS-x6&D2vp@ZC4_WS
z7T^PJM}06Fg;jh@`7TLMq^O~Rpw-ZzrA5#pI*n(I5VGn721-iRMlR(GX$)cb>6xx*
zEuaJL1?oEJn`tk2SNkocFZCO`E;T4+iX1lIpM0xy&`uf)#gG9G@7~!c>MI%d;@6Q-
zX0=k1Iv!SZpf^Uq5K`6r5BZZ`tv|s2aG1gf#Bcpn1>+6ibRm2Vs+cT_?lZ(=ub9!q
zU*809TR%hH;p>BP$7SAvJA^mzm~p|<%}vN<aN3PP2eZwLrP(eOF#$c!Wq&UXPE-Gw
z=}88){8Z$^`Z8&ht!zfyxc6%td);YZ@<M$co@}xeI60q+_yYu7$<{xIFJBbIu$UO0
z5&$p^cS2y@eYN*=h!;Bjm8mVD9;f6lgbLjBNHK8u-tvPU`Iqe;qGC=iJ}PvN55NM<
zhz&l(s@`C&#te~vZw^{J1FvWr1G3eG_#?*`J1IgoKA+SX51k`9@Qo#24;y9@LY+MC
z3dy@#L5yp?kwmF0d74<(t98RAWhfn_L!t-X=skTA(bM~^IG&Ex2PSb`Znvr0)@{RU
zwCglyFxp7TFs)~fy9~i=V8*Dcy#+GpHM1s#O>*N6oH>lv=EK9(12=PS!M)@s9#lB`
zI<zP|h-0S6-c48Pl%69lO$+kyOeAtGfxO{Y#w_mzlJQV3lA6iKFiI)cWFN2;;sOK3
zzm-r~NBObaOmmQ5=_*Q)bUfD3c4n={Az1NQff+<<U;ubu{cxg`8Eo<vCBqE*ptG*s
zSB^)L&BBNzdQ72_19|wQW1)1=8vMT5cpS@`4~>$;-Xr=#3JoAs?xAJo2&#da5GW01
zPD7!;UJ1Kvv_=x&hF`*eir=2O_^4l#S9H#GgH;9^gA*i={CtdEz2gU;qRe-JRxzT#
zi+BA98xr(%gJEz$YTlP&?0#3K&<yi_#m>rCL!fVZ;*K6)0Yk0e%FaaBti)Hldh3ZF
zKxHY(WW4Q<Io}QAW>holMz(Aa5>L_$`N9W}<hd^%F@9a0KM}`WRD{vr&LB1tfA~+`
z48E$wqg#W5rat(pS4Jo#pGLG6$YC?>F47?sB>QIx++hg|hj;4;x7Z5r@+0!EPszwR
z;+g~_0j!Tf8J%9UQo7YGlonYdR{Plxv}QaUrbN<1>%|$w5AMKI;!1RP-*)N|ZOR3F
zO-&e1XAE2Sbx0q*_~_=I4f_ek3+fZ^kx!3Lk-!m3OO(z3(E1ypZ*u)C^xj(&C?@qj
zx$qJbmOgT%A=SVN^IMl9Ul-RH)|l*M`E_}*_0HBlGS0wip{Gb?M4*Zad<6abm4Od*
zn-M+#;m5qs)=c!r<oV0n4EVkf$f70+YJ>vKu`mMcfDp2n1yXh^e&}3@8E+2FNTDDX
zMoaKp1`Y2$JR~L!2Z%bnl2t!;uQKx9dpD(yF9o%Y#Y@lTPaZ&a%W8yyh9Pg>rDveC
zNMa2nvn;lATB%!_1KBlrw>f5KS1K)&miGD{P01(RRCP3SqktILB9^Fe4hT?IraW=o
ze7)j9*WZk_MSVM#f$~}@78^h@ezS}ThkMa`+)tnw_zR~cpcD`GMIxU;(|h0g?Y2xZ
zbukhpEgFTMo4BX+ju80$ZpH`P1VV2kS8HjA&~35cAVtu|CmMPNY%xp0A1rGRi0mKO
z-@>ndi87^(j{U29fyB#Zrd3Km0y5BPlWHg=n9q+)sR{~HdIE?5rD*WSm=k`XWH}_b
zsUUie9+5oUl24e<g<|E4#<RoA>;_4pvPE)1<QxxBQ|#oA&3PI!K2P4Oy^Y841oq(4
z_FUC)`Em%*P!AUX;ZxrI(JX_CrS`5tcq|pkFzLT>1p*#QEdB<k9Y4*@3KAy!V0F<&
zr{g9NB^k#SvJ~_+>g8lODci~btdM$VSD<lCAa&O{n_Fwf-Hr-^KySs?i1UBwm}Gxv
z<HlmC1B!T!U1smSi@kG2O^J46L{6{wwiF_XjL^4)E27YpvAzm1V79Ut><KY#!>lrl
z2)U)oiZ4iw<>s<|-;V!1J@Ji11hnv2)VF`o>YZ&0`LLgvY#r%GL}fL#a;Bfp+FF%N
zftqOQYg5Hfw4q{FYHNC|AEm5)cfLb3ndkA69}`d_<+uQrel~Ni_>_5wX;Y#Uf<nW3
zbt<c1=rf_9^$LH`i=I{ER;7nCmC4a_N~djMXPAkSvFW*;E0~IQXYc!K|ELt$D5RP|
zPPGaEEPuQGhLxai(Z7eO`DiJ-0Z~ZSWokqWx4s4$2?wU7kP1jkM&c0;I%AA5Do7Uy
zkt8@`Px(@%xdTx8MMEnGjCdgH@JTp!g0aVgG)fa~_@map@ukdJ@%Nb|4cf3b5MV1x
z!YDWUlHCu^kqKi3FA<Y)KsAst3j74={7Ro=DS*s!z(ED3{n$8y<Pr{y(HGNxxNfZu
zmIOtoE5ku}L3S;6#RDs<YWAK#NOo4*ou^52AQ#REmmWTp(1G1VOY5|Hl!=e1yFv1U
zitu(eDCa|rA%j=DubW`#ua$=aubJqdNVK(p<U~TFh>X1E-Jd*_gD-w=0c7h-<a&&J
zihEOX9VtOiX^~5`Wwv;w{oD%3XaL(um`^MzE&Mg?oY5COD{+_77e@J=&6I?(z6;ky
zg0c0|p`rB^qND}@9v`-7vhCMBZy*&1B`z^t!yW84m~GzLpT{bWZ<piCUVQUaxd}tY
zhwbiG{Vg6$yD5&eR^G^ra2W0Gqq7tq67nqLg@b}@Kxa_I_v}iCKuL?x@bCzYpzzOH
z5)D18Ei5cJmk-v46J8_P9_uZkp}*<>%EkzIgt@U7i<t~9d<un&U+J_oH5XJu$CU}`
zn}F-rwol69@uVn0{Wn7~DKU|pD+Bd}?Q!xteEZ3?At+J<CrL@KgmfY&^7SLa^Y&vC
zOV&uK!}pa(QPT<m8?2sR<Dh}aLuXb6NS!87#Cn&q6umVh?H;wUrCojaxjQv;i5?&p
zh3iHz;Nepm?zek;NdjYM*heS1AhU4g7d2OsD9k&s+6*w4i>;aA`z@MJ4z6r>QUjPG
zaH5+qpR0=8+!k04PTl=|sep&|gjYY^C>&Cfm2+Dgo)fB78VnW{rIrh<PPyqE83J&!
zAcxj(lEM2Xqju%t;P2nDTbw8wFfex>b`iqbtB&ulB-jeVk3af`yDOp1G$27lW>MgK
zJF2*gwUzao$VC9YnFk>Zl8o6D%x6lr09yGK<DPJ9Up?w!Odg0wb8egBhJKLFC)QNq
zQzARho=E_@X1I5_dL^EY_VxWk+4B0jPsX9J=?L?W1@CG^k9(K*7V?2_E%Ry*CA=Q(
zl)dn>#G`3o8*y!~)Ld~zh}F!yU4)N+oxu7OPDi*LHg7fls-n3)e4221_(ei7WRAKl
zW(!E=t;UC-JQrN<&%f~x3F)SxBf8AlKU;nV-4lKPyd-Fnvb=5=O2k%|N_v8Loa|xE
zhDV|idWT>T<D51Hw7fCB5<8}WDX|Enb|s{*=0sS<8eLxRlTz--L!_B84!|qbaaAYK
zT&SqC^^`Gw2?sj&O^+zx@kxzXYJ1YMY36kmpVE2F^vd+aQA+Kl#qEDOt)Wytjvn#I
z0Q3L`#Rzi(*zktlGT5NK2`ZX@ir+|{sDPkiA*8*(2~hFztRiIt@{xCmxn#$rmy7s(
zDrRa&JK?i;Ns{-dSXDO0sd-ogcU|bphR7Qk!ej~XK_g<l<AnI#x2M&f*#zOI%)eYo
zrfgr4GEd_}FcyoqV?p&wtQQ*eYIRblO6Re|^`~*`sMX3b=L0>HOd+#fNb2;7RNqI`
zh*ji(IAyqJd<)i#UC2{^<^2tl@o-1}S=A$lm<16$HX`gx$Lk_-Rvq@Ad|TdNTL)@H
zwaW0JKwnEierxQRw;_O#C@TYuAKQ)PMfGTG;Kk856yMkXZQzsU+WQ@WDUp5JD+Lvd
zce>@OK}P=?`6Z8$>Ny9PfPxD(K}Mwk0I$9|`uY;nA}vahuv=mPP!q=nV}70tvNP~0
zL3rf%;L*PaT5^yJvB)*L11>b#psR}2O@4(hm43f0Du`5WNxEW7$1UYN9{yOSQL}!$
z$hYhI@NGR?-t4`+yDPW@T0@PH!wa5IIQpK2d$bKqQ;$a&E{}U;%Jq73`g(GWzTN*=
zEYH26NhYf9tv~Z#2lA&{j(DcZvndrm4U?L6hakMtJkDBVS#`B*sfcQ4${kwH8WfBJ
zD3Zv_b{Gie^932$b~n^d1dtzU9)W>cE<Jo{V@Zx#G?JM$@{4;1)W{6Id(GREz@w%2
zw`7c^mW?^+qwouHd%Qh1LZYhWf@w*$<G4*3TS4!JunJ*!t>e#|<`%xUb0qNg{ALgK
z4OSY}nM8-{(%q#`v=930iQK)R=`tX2V`|B&JypwisO(k0^mQUndF5xe`Q;Iv-wbkB
zttg%a*X4xfL3W9rcA+dIbq|SMIILM%ZYl$wE^&4iQ=MHHf$ODe+e#ESwKk58jZQr5
zd2GH!YB^Q@@Lm(kXb+9COZ|NRo=TJaeIkFf)j@K?ffEmYy1F-O;z|iAKD@t(LLf7B
z1d+LFtSB!*-Ux7waRIE+3EXXAU97~3dZ_4|8l(yUe*5vk6sjTqrGSV?qO)AWdDTL<
zDvBwyKDoUBnz<oB$)B0YqdG?1C}|1vA-A20$&JmepdoT~aFOtvwL)b%5IzRjv8<r_
z`W08;QBAC0bE7i4H%9V{zQWbc>AuuWxmNN1YP9X#6?75G!=QII+mFfEEwOF;f(^g0
z_E1u#4myfR>5fOCcq2&#VeVLL@-C6;NPK2Z?q`;tYqej$UF|}Y{NnEcw?-wKVcX_e
z=uR@9`1+H!g}Qj!S{d><?HhWV6+NeNui>|f9Ln;2cY3J}3SnvnhWaoz{Gv%#<E8;$
z64BuuX<WMFhl8QCVShm)J7C=}#QidL$b8`+zI<{@FZ?Pkodh<;i5rond!BDhg@pHn
zq?rqbNGXwD5?)nMG<t`bjEb9f6GKlb;)7&mf5Bn80{(pQB1|9O7jx4p3s8kBHdqLd
z+d5Bwk#z7A(fva5_-P{#IV<=_G(Mc?=iX7@X<fpS64Bhuqveana)if^he!}#cXT*I
z4;DL>5%aX|&QgEqsrd?7zzp8Smj3Y79_bHqnr^ZH<j2=S8TJ%%jEt&o!>^v?FEp&O
z5paqJVN#)VDPcEbI5_1X*H)OeHo|csjwZiBX@!Im3G8<yO5m)IE?u3caJY~8(b3ij
zaNR>#-f!swI|J2IMiRZD>g*r+19zn)Nb>GdeJ5FO+*l9etGHC4Vy7aSUc>hnWl54J
zrXi-8J%kXkLLcO=%+z{&UsvZ{;BdVn={rxYeIOg6luz-x2>xvB8anRy9{D1AIa3;4
z2!^UelCM%x)NH+PIbb@>FtK%|OS_fs1Qv;HqbrU({atH>H)$0OVL=gXI`_IhQ#m@m
zi&8(LZdf5(&k*wJwC9BkC+bcp(7f*YW_Gy*0D9f<J&!qk#MDOB$Qcz&!Q{YQf*;Xw
ztU5B(tQAg=uOC98y9Ve|0QeNj%e|%T{pu``ydfzm@1_ayH(OQt8U_C1J?tbzrQIKa
zC^QM!cD^MP<acYT@{!d4%<#)E5U|;r=C3ji65H|^kCEK&KQq(!h@SIUQKkj5ZDi`)
z?nyabMT2PNZlqXrPx6Q+`G<r*0*{O-4M0S!FTs+P1RrXt1#4QUjPpu`y(SeWPnNXp
z@^$Vtz){4wu#|)p`o|<~1y0MR7-yHe9;<%r$rU>n0WJTy*NFY3w`4WM!iepC*3wIw
zm?#J)Ekrl7!Pnva<~#jpXaxXVz=Tu+U^kE&FemC2VUjEtv&*6X(68X<IYmgNI-c_@
zQT{=Hf<>dG3WSWDFHbiU(zZMrJnEi!6#{1UAxh_@T-Dt51~*tfJCb3fW<+nGjfo-B
z*m~oPPT2l~>f~}2LYU9Mpa(1DMoAH+W#v7?;i3>6T(Bxn?=ts2Kb9pgEOhMp?m(xO
zN%i;HN9=dv0|m=EL2@d|n%X{~JJIQz-Du8`398axKE<hAlu-h!I&Q^!u-19P!a!l4
zC>0R+c|p90(V^Nj-e@31&8>sp%jvRh_FD1FL5J|!fKx(LWXWDn5H{bl72+a%!}}Xk
zvjPD?LKUtJi}b8%!-~Js*`zBdwrk~yV*8{&8m0Vti53Z>dX&K|h~VeX5v=s|>bS~J
zZ+CNRAt0G>p!2%=e1&j6mIQy|bhO(B;r(mWe?wf!1;cNvK`Wjo){QOr{BSpLW-FST
z^l1KT`m1i&-B_P(Hj3H*S*}-%NpQpN>UADWiCR)bc$H))xs(5yjxu%Gt$$}2)p+Mz
z$QcB#ipL{j^))9MB*f>gtRAeJ|I-kmzppP29j2=lWqH%c_+iDU<|AqCcFO;2c%EU}
z2#1qsTbkX}7-*$y)(l<d<N2aZ-`2{^dA6@U_`tg2|7*F>_oR~<N&pqdkSgn*cxg}U
z8V*tLib6*YgQA}ttj&&s33lyCZjL!pML5aO``P0+bd$Ym;=COrU)k!tf2qE`C%rM%
zKuQhcDR&xZsfG~#=ZBn1lFfDYU-yo%#Dl#iin;YADuFH&H>)owmyKrIlfdT<_XW?(
zoM%D*^W#nTU+2<^q{!m4cGIO9dRHrtyY*q+vpXzp*n$!-zlP=D0ZW$2{lOUL(WE~~
z=qxMTffwVl<Mq0s?SLz-gF#GP7H_Sd#l241*wyTh*tv85?XV~GJ^6fQI)=8o-)fT`
zrb~J42^$0Q1Tx){Q2dp<A-FXRYA5&`-Hr+OMUx4l&Uax%BA7;I<gbYxKMP8!nw!@7
zxU}Do!Q^4``mcVH3nmyj$0s|nBk{dG5x?(MS(9(Z9_mdx5qpNau9~PmR2}WX3FF3z
zAC#~F?2X<<Tr<76Zd<*Bsr!V)8A~&8>!0Pf<I|D<%Z>pry#KvGEdhisUw<@Oyhz0J
zmY;<5qJ8q9$u~&lqceQ#thFkI)5hJTI{%dQ@_RfE<W-q2`3D9qrJmI9>Fh}&w$(1P
zDEqZ$!%AjH)P<ST*nxRPuc5@@%S4gjCxI*KW7c-Tn$tAaG3Hm4f;B5z?YpMs1xf@9
z`I##8j6jQ!f*sF*R=WKubwf_ET0KL?w09zFBS@uI`zW<{hBtek@oj0b0&REU`R*c(
zbPk;aWJSIE=}0u3i<XQbs7FM2XOLJRtMrXpyPeji+wcke4n>t}b))T8WdcD(<=nqv
z=3L~2<c~URssDEH6hS0kUX|vas$>;8aW`mT!b)vsf>sr9EDMK6O(yy_I?x{ifX(o;
z7US+U_uA1|Q_Hli{wFnMW%Ix1MFp)QNs36iM7scWmrjYc<>&`u`>qYWM}1{_fphAC
zUAar|nFbXYXI%<kzblg3=yg`n4^2X=aK-TGC_fQ8UXjI7K!eL-|Nb@nz~lDKJ1>n7
zI~Z5UB<tG3d9aA}l{GKwkK}yJmlOMOg(~>6F!Q}~@lVY?Il8CU-3JLrX`6$(Hfil6
zfCQYU_&NWs&?UV%wqPf>UEI;x@22VhY5wP56axeh&t;xXTt=ex38amTDr`xmeQiY$
zq_>D_J%1T}cxw98&!5+?$9PKM0gwj>4TN_tK70#=RPd?{Ck-WJr{q)Ci5E|8HI>w_
zleFLqw~RZhFni<v{yAtMUZA1IE#A2fXcODxa}k}>Yk99`D1iCfN`s@v{g}vgQ0}&h
z%Zd#9+wMUQ4G21tBB842u=ty*w`u5;rT*#jsK`lnnJxbNmyI<vKf*&0)`oGO<L9x4
zWeaVu+^pv8;r0Ez<58XCovau0QJHf16W*mXyyE$fZB<U2v4&i0f!o&qA{>58pPs;`
z`}w>teSu0<`clC3@1WbWPH3p#vxcl7Ybp%QQu|Kq6Xr!k(D;i)eJy?bbp=C$EK+Av
zJv;BSgO`)`Ek(^2bP@YMJ5_5o2ejy%A|>?Qytqqo{ChiRH1f`6d{+*!A6c8s&t8y~
zcSzYB>Wxmi-Yb<FI?bVY8n)-7!f&IjyF}wvT%|EUXdeo@=B%QPD%+JM&+~fmTrxm)
z+W!@fmbq$+X34@(XrrN`#%AqTW@yy!@$P+zWkGlSqLs+F#^HWXg$o#S)stylzna^N
zMv{pJD!DfgZAfn#R6K<IW;%Rvy~VHk38bPLTsRmPd)5mbjH~swR131@7s}4JSJkL<
zvwG0LhKl`+!j^A*R8Vy)d(@zK9HQcpoEFYV@!$h0+S7vAkHGIwTf1Jcv-)Q45u(~M
zex-RgItADH48!R?eIL;oF>HF;xBuFjAv3vevJTap%$oRAzs3J`cS{C)j*in8Nd*Nk
zEKp1D1Ig?<6RcnNvpg!>QUCP8coQNNZN4QVoYVmD=4o>mn3h>yD1VvjAE&V(V5nN*
zd&E)Jtgkf-W7A=6RI)u%u8T0|hy5`7KNPpJ!da0-a|Z;_=;kC|?uB`bTVN<|-C~KO
zxGWRBYIg0os+HDE6VJA2YnzC9g!6PCQPo~%r2OXD*nrBL)@iHnZMR)}g(vNVeozU4
zTnt>Xqzcy(^7d#xSlPYI3czpB$4CW#z{s*R<@0G&sg6b5Gipw5ybPJUsLChEC&}9?
zbm^-@Y^3qCOJgD+4fdbtc*|h@;?{{E6>s+J+0qMQjOms=AXb~MAoPxvhVkQvF&j+&
z28*JZ3FTB~OI>oE#f4RUKCukY@?eqCHX5<g-EoHk%KdehSiwzEtaplxH{*uO*v7uu
zaHKn{9UE~LkRFbB5lWFbO(qAmSr>vU5Un5(jHalt{Fp!AQ`QlPiDw?k6~oj~e6q|3
zOmAHdJ+3C4JTpcB3r2H-K=#X^O%%d&?J|6hFyoI~uCAU{o#<~G>~p@I;df9r<~<r9
z8{oF?7`l_K`lXhC^7`1+w*jB+t0pxa5IWSEh`2QLZb!s*{e)<2xRBNl{Z^Gjh{ZLc
zB2jg_u`Bop#9};q;&pp_?<BmtSDW>=J?H1Sq#t(V4Gh6r(D#_nng=isSFd(qgld5-
z?T0Cx6Z!wa>!S?o;ab#bX_eTX?^?>!uU9MEi38%T1&Sr1`cw6creMt9yqJ9n+^662
zCJ5s&!`XAHp5CAaMnRM$?Z@S*Nn)T9c1RAIU<~z=kHKPhXKU^jFzEhO*0PtZKZ)pi
z1w%gMV_~APcZhB6c`)?8wV+-qg-b(Yt`0wWUI&lv0!G4h(t|gwq%fk35aMPqMY*`j
z6a6KD=sauqO<@fH&f+`@^!>UlWg8EBZ<Q-1?LR=gHUodmw*|>_JyUYAm5Lx+O{JsH
z??if#HV5GPCjUD*RO}n&;C3?|uvTIl>rW;JbyrK-#kGqb`1bbM8t}p0F(OSsFM>j|
zsemc-kP>11YL5R^)oabOrB^BO!Mp*YogehJzoV98b~7zTJhwA0?n_KwwPLf&`R-mC
z9{wWaJw<<|z9OWn5`0Uct-Dz$!uIX$`Id3NzfLG~t14qz$wTh`IfbFmgdGZEE(M#o
zU_xreJEZq@t6V<iUHeBDG`=9FUyH}?#&xwULKKNr`EneE?z)zz{anxTUq@S-#zar+
zswjKL>6LG!akW%iQpEFIC<x`DpU9)zIsav|pW!^WgW|5C=@MUQ=xs(HSz1Ku*%+W^
zH8Q-UeCDJz85*`*EEfmG)rk2W!Esg@3c>S;SBpD@WYswUv_y}j1IA-q#o*08NM(6`
zT7Yucs-vN^R_I`PGh+}G73^qq(Ymh?JSS?ph&GN=a3pm=Xq9Sc1o8CE9Ch#AO8W9K
zc<60zL|qz_LHrC{=%_d^L8Mu!AR_52no0gjHs*d^zl2b2Eq8IR%E#&Zdv_L32hZGH
zLo}<57piXz%vEbn)fWl!UYsaAv>zKNuJ}S<Dgq-%#7C9+aLe;CdT-vSL;sGf`?c_6
z7Li1#k>(_&CiGD>>@i%c%zj3I$jk#&Y^Kx0e`&+{!?di?mMAD{j{gD9Gx{v8e8lt;
z<-k!Sq<<ZP#=Y9#8YoorRj*g?>bE^V+HJ^1Ld%ye@*e9CFDEHJs^Kl`j~(VVwBxjY
zRrfykD1drg?P92k%n4DDbtSCtwgqWPqM`RL(H&5xEET#RZ(@zf6AzHM$VE3frx!25
z)x>{Kzw!+G@$63k&J7xPnExIq^7?G9TiIpzGfJ;O*uEUx!BwmYoOduha(`q`W*LhY
z@vqX@HVo3A>av}0&iVWI_S44-@rP4&*x7e0eHZof(1uTi%RErb6i`K2PkoH=abm7{
z*A#QHsm!a>YiLS@;ztQt@$GmYP%PL?(*p*ZdPR8{PcgpVp~9P`A^g%@4W7{8cuo=<
z#YyGfu}-`9`~Ktn-K72IEEkHfhnZe8uFW#<J`Xt7alb5v1e%(|-IJnQlG|M6%=h*@
zSJxG9<KFd;#~kwc)GY_wzslBWpZZLYK9}h3?Wx~8Q0CO|bJzcP;Bgv5i%D0di@}n3
zHw2jRp0-8td41ZpK0W=9oAUZ(LHpp}^QXt_5oZJ6e+IHY7WW~C{TbbA-;L3iknZPH
z`nKwF+w?WJ{%a-E(?!m`7r*D*vfgW%vn%X6+to~+>xrG38)dCNTPp=_bpb7r#xIyh
zW9hqDJ5$&kVi)>z+~wF|+`nK)&-J`SFLJ`w7k7ErOcjqGco;2ZQe~qwQX>vm&|@^g
z#_F|u$-i-~^RNykN$53Y50jcY{Uh!DxF>%4J5yUW)Gn}}v^?v3s`0aQA5S&dx|;{T
zh2L<py3%`?vWyFc6yDw!;r|>OLjIYdmuH<<OW+WIU2G_*>{ZR-oV)mb-}=JoX_P03
zB*E4g^uUiHP@qeJPkXvnub3=Kxb{R|f3~vG^dNOY`n(Bk4c$w98Uk3PLA$+!PZ=!v
zT1j#WvxX{_sj809yJ^o({L@Aiz4?RQ+g?VWo<zHT6WhGyjk~UP+Onwo1bLeyML3;k
zAk@z4kZU;2FNpDsr_ZjB3Q75mvzHPu4;kA(0n}>_azB5+s@^L-`;uuKyAvf~dpvVN
zL)WZ?&E8$Gd2uhUzWA@+jzYAjOr_o1K}j;hKM$&&{Ubd)I4x0u%X8aPI#}Al__NL<
znBgTIrcI|`zfz~eNm^k>$tX<d)<-U8*kwLE+ZNv77MgVMx9iW0TT-G9LkCR>Wp)|!
z*-B&KQpdWQS6>YbH|r@TJ>?b(>8>X^8Sr{A<+kg9lNE$6cg#yM*3oy=Joh^LD6O`U
z)-3)YnDg^|#sZxDa;LQ~yQ~RykQfkX#Vw7dt8n8XyoR`a`Nq4V;rTsS&-~|Fi5*)3
zj`IHXvp1{v2L@f?Zl)RHr>i}->-~N&=mi={i@6w;6Ftfu^@ygX{$(sMeA)$E(RC=p
zX()t<x1hAt`1ttP#J%lu<;Umt5tcx5I)>kyg?f$6%U#XQm-Z8~Yfo!6;;yeQ7;rf6
zOfen@43`UIBsD!tdh<WGLihuN+~`as%HeZL=R1q*6f<ZS&3MS0bGd;BD?0ebe`_h=
z9`HAjWlj(p^E(`i!bGXPY=r+Ot$k}{xtQFDJ{a<I2-PaCzB%^VObNepEm)T?E$Q?W
zQY6-}%pes7IY6J;dfkCE+&^S%_&>ofr}C&2=18aRN0NF*%zR(23Fq{_jQ_d6o8RI!
zp5J<oO>gL3^=WSus7DZo)C-bW{GUKySlxGuqi}?Inwyld<80keu3Lb-JRt9l_sMM=
z26yac<7L#`Sjfpaz{C$c;r=uO>r@+PI&;L|wR8M;*eq)4m3bNVf_M0+Xet*-=pBuf
z`X4$Q*%Cl$8@h1<A$*4t24>(0l?;sO{{dY5IcE&DN~i6Io@%DfeV!1Y62}jkfL6vV
zu}JKqruUo=OxAh`+CshjB7fb?w2-;?3SfLnKEp&^zBpJcocY?=1oYKm3X*WpjP1k%
z)^c!nIz+tg{ai8wik<(lQ0{#<H&bzk>3w0y2kKS<gg}R%-zqQ1f>q+KFL6~LL*ZLc
zbUK#M40s6oADwe+Roahn*7rD@y8`w*JCg_T@j8=pyJ_h4{Nm-t@a|AEAb^$Q{|;*M
zi&ROp1!A$&V^3#p4pWOLK<oP*EN?#%p~8maW4?SMrB=(;3iu=Gp84N}kpDn<&^L0w
zTYj7!+L)qJ2ef>zDeCP^SM$^b&vTZVVbLUgaU#Ew917|G+(8L96-W&Q>A$_Kr}KUc
z_w~+G(;y_tE@}qq={`Q>xumQhxn&?kM}DtfjSq3JlhCwo4*$PGn0`uAhi#xNMR>`6
zJ)Ia(EGcO%3JkDX)wcHjzP0`KY$($(>lrCV2g&v?ThLIDZ+mLOA1Q%w&5!o~A@fUN
zygh<C`1&P=H?C9sMW3GBiH$}y^ln3z>}-jvOuffp*4O{5Ii8F`uiw}7`a-73QF*|J
zboTt^fgjaJ-y{#nq(_3)lihavDSDe_J}Swkn1Y$&6-@t&ZFaKrHR0}=_|5JXyu+`d
z{|Selt}nL#{%`hJo(lBu+RFi2FeqsULX_P1_yq{tapUhTc@_MBuXO(ZS-K+@qG0S}
zX~kFWGu%RnZRrF5f8FWe!~^Nxlwz-0>>bd*DfpUxvoxJ}(@5tTStF{L$NvTMa>axQ
zbXo(y*@HWS2=s3SJho9>^PeE-h~9Sj<Pb*`FuP<pMngx)JbCp(gH!WABe5A-g%9&=
znDg|5v|5q3IUFnr8)$1Pi~rh7{M)UuQ7W+t_B3aD{yBSr`#pO7?wkrQK6qocD$r}+
zctiIpd_De4@mpkjcskoqCt~9w18Znr@cNZRXuPuRv&6Z>h7(`whglzZ0HTULtKG!>
zy-_+=A2VHrXXlGK@!PybTR?a|Wpy|j{n_P&^b>>UTmflS)_(`yCng_|zrLzgr1h$@
zzju!D*UFzQnCXcMsm}ndUpKztP5#Olf(=-IQSD^3p7SKKi39%d#w^l>3@t4a;=r|m
z_Osb)jXjHauNxFNs0jU9w|pOxk+by@{k0NV7N_?$Db~gCQ|4-%qKJg~l9!7+$v>W*
z@U8184~(9uWZKSX8fJKMIXjgn@c(eXcgC0?Zv0>u?09#P^i$OQ$lvJeXG)nC?wr@J
z$)nubRs>%yGV_gUFI9Ax-FcMyDjr;Aj*=*@e7bw|4+>ofo>O2h@|S4!(uHHPA9>sE
z<P;!-y4=8Ow;jj3mZRlgylcIN@ZQxsmx*_(D3(%Oik+<G(q2E=_I4aro89Ec&=~;6
zUch~&iAd#%v)zA?p^sC3=&;toBl+-jr?38QygDG~T;RF*>eqd10^N$Zice_vlsnz!
z!Dk(!u9gmZEv1(;c9|z*8-HHj(bpStbW7z_`X}bq@N^5k>)~QsMB>{@jxDw9wb+(W
z&t7v)&2P7hshNuw55=BWrh2DMStc!8F4gZ+MV)`u8z$AspJM4Oz#F9yQdoFQ!1YfZ
z951La0-t||!Wxfwc`Kae8WWvKojRDlDK1s|D0B!h4Mn?b_Qkv+!0CD$A>P~m+)tpp
zNQ~06%?h2@?ttrVtO6Drj+*?3NUPxVl7qR0e-c+}zuqQG)(1Jb9<7P4eYD;dg0);d
zJP#NVhhG1PKMh@|3y$~Awby0HwSNB6f^R`tVrwkBRwR_!u0QvmA{I%@x@Tv;2Umwr
zr?>5Y;M;L<3eiVq%m|4lX}7W#Mjmh~_23(_t5tiyai)Jg-JB+Vo$RkWLsd=yQ02oa
z1p9>K(akrF8DzaQh|X~3CoiRl_loiE-|9b^<!}_a{L@*D^^G{T@f0F4p+ls8+EIM7
zA+n4@%U0VvF-bRlz4CQ@_)l)Ex3VOfM_g#bwP5^CG6fRf_)u5=FY~<@IJ?hZV^_!1
zKYJ>sB^>K4$O!FfI0eRn$&YHIIN3YjOq2@v>Tcbj#n1P`#mAhrF<;8L{aT^7j}+_P
zAEyjh(lC~dY~pOU{SRwidBgJ(hLj7GxJ0>g{AI7|PusP+MFq3|=fRR{!C^~+!}yHm
zl*3hZ@I~Kk1;_D-%Hhecp=*A=homNg(A)`ooPs~yl-C6)>OB0(i}sz8*v;hk{~*eZ
zk?C!N(_hVrxN~sBNj?jVy1vgGb5zI<$7{Nupeycqvax2cm#5Qln94m^Gpo$2&S3q+
z)hw8Ns{LQ@-PaT1!W{c?kPiZb!#l%a6HllTmgx;DOHbNjNDp#Gt_@6GPx|MP;fAyu
zraao~I}fVH?3~XM2pugIZwB&Idsbo57sV((t}BwVv`wt-(gnNYxYWf_greHqh>2%g
z4b#~xM|$aF-_i~WJ^A`HFU>LChr^*G*1i80LPdm%;+K5*?V$X}k+zrf&DZELss!<?
zxgU|k-%MJ*FwERde=V?C6n33<#BMMwuDu?|BJ7PS%ZZRG{Rd=M)fCz`-OlD4RlMk)
z2{WUU@N5!#*ZQM8@Yd(G>~Ybf_w1R)s-51<FOWtus2ndS>+zId_wBsO5byhU`{wZK
z14V5;`mzq3D7$=emSto2?u#E|k|z=ZKD(Q$*#;@c=C?Cc2@<`DMaF4@o@H)c(*cB1
zGl{0cwa^>h*pTP3A7)9e-SlRw)yG!_Zv8bs!19j3bG-q4K>?#6@u1l6DidP7#9y*D
zuN?sIJGC06<F_IBl!lWr6Q6ICu>w)`FS5S|v+7Bv9mt}qw%c%J!xs%R?>Y@!&J<{Z
zvbMa?Ej#>Pwj8$A1VpUqG&6Kthd*GC1{=*GW9p>WRgX3#u4-v$mEl5THn`X=rL(YF
zrCb*OtgY+VTalsqvPWtN(9LdYArnO-p`PDOxWrJXWN>$-omTC9Ylb{Y$6Yuq^4E-`
ztgsO4o<YV%H)kB$sgCvC)Qs3ks&K<zuy`{F+*r0N`~KbShDzr67FlJYNf=D78>COH
zpJs%Yl3n7Qe3wSDQS?g@4JQE>XvOvpEFaU~q=wgoR*u7#Xw=qcTn#CSDEMM<*<<GY
zRgmD^5{jbYfaVZDU?dL^AUklx)C`5ASY|jKga`p5EGF%fvXPVq-F#$TC_K-TLizqb
Df?*ZT
new file mode 100644
index 0000000000000000000000000000000000000000..8f1ae84942c80bf7d389e8e3bbc505222ab13df1
GIT binary patch
literal 24794
zc%1CI_fu2f7d0FRgmw{BkRa7AJrwCxM0!z>BE6$1AiYBf1QaO>NGGT$pa>{UYJkvN
z=)LzITIeAU>gPN2%)CFm|G@J@=1y|&+;h&}Yp=ET$$71#rA$kGl^O&B(W<IEcnkuO
zaGie!DZ%Hzup(mo&o5;53YrQa(9dZ9lSgsq-#M*S9&3U?zPCW2U<3$sL_EJPgFqfI
z5NOo`1d>byftZ{VbCdf)ATUTrLr=-^ZKZpBOG$B2Z-4nv*Pw_-#2~g+-O&2-EsfT`
z_U_>&iksF6Wy?h3W>*_#c4BaGc9cjw+BqW*^fbdBx~e{VhY0a2ZS15>#=S-&h{S`<
zGa|X=Ku2G1K}BnL&hY49drxOQ{WUvYA))%}l7XI14zbtF%}0IM_WKIb;~gC-rQ>T$
zGlN|flcRlYjWyZji<7fm!^>ww*v8SWhFek|?fqkYJ&k0Hk6Jqhj)=rgZ0qPiS8re2
z*T$u$s;2g(GX<lV_Ms{WDT#ycuP0tPU`FfE)ULA=;_Uj#U{77;?}G5pZB6wRS&eu#
zyR4@kr3<5T{k?tupE}cP*US;WI$LX_i^fNGh>K^$_-_;AL*3V5+K`*C=Jtp^eVspY
zQVAy~RU@at{vLjB631qjf>TNoKjuu1bTM*!)HnWQxyf(j@acE`3X8DUc<;n$Z{yzH
zX?I`kU{^PhushP%xwXFZ+|74&|Ln12Nn>wsM{{jaepbm~P5<~b<gz#`%%;1&ap&ly
zw}0eYQMIZmYH#B>6*K-Nuj+XJq^+Us<m6-sTc=e({QT+5=H6a2CM!0tm3WNr9Gf`B
zZ*T0)H+PSqXOD+Qn?$D1<fWzS8nHDkhbP1n{Lbd&<T&wUtDu+AHGr`WuA3dM;D+OC
z>+5UVyUK@fYVU@+vE3cR{fR~0M@MH9L#^$dzsI`UMtXmZPc&4{HP&{v^f$JuS^pXy
z8R#163jDm*S6AEG+}7JxJ2-$oAg)vLIt&hW4|U`X4z$&ER38!X+Ab)!w93%JPVl|h
zvck&a<Ae2+!@kzunL%t}N%p}Zu5X}Wc(Bng2szkMzqoTS(%zfbH9OzaHqhQU*D!YF
z60O92jfLaA&Y`a1w)Q@3^PTG~13j%neeFczDUm?z!#4JGHWCS^1OlP2vw5hmMMh3y
z2-|*2Jikfk>1-bCX(tefPXp7tyD|Np4L$AcSZwoTPxnAy^LR^bL-Q}p2-fKJo(8Im
zNF?@mH!Dnxq=G=EMyd}K^t{uos@SEu#0xY90*@q9Yg#G9_U^oH6?PEbD`P#r>=jEW
z6+%o%20}inD=htpnY0>~z`q{|C0#Op-lrcX6W41SVZwiQC;+BU6C0le*RKs{;b1VA
zkWl~9P_`1Y9plbp7A7#}TcPvICjh|NQMe$bVm5lr5<#nnk6L3H;)YQnUp}GtR#C$d
zwYaLESQ43U=%2>8Yd`3gZz%+6V6_c{>y^L4U8!iGP>a(_K2hZt7sl9MyG&7q0)QJG
zqQm;FH|ZB<`B|Do!8}pF$EC!=<~T3H&q(c5ep|}Zqqo~cRzcm%!62(~{JMGPrOeM|
zd?#s}jV`8fb?EnSiP5xcF*Elt(#Wp`1<cS7Po&?kMUZ|=PL>s(Xb*DTv_WcTcKc+-
zNlBC?kj%T0O*T#cMk(}eNz?BHgw!g#0)RiN3(?pmm*~&mT5AEVIDTicyxPqTQOq3S
z+~tvf&UsjM4NR(+jd(FoPFhS8@^RJx8Vm1YB%>i^?hd|yVPc2Cnn*J3<aYL)+tW{T
z=i>W?kqnvUi;k+!QyaOA?f_>nbc#sHUG+<9<#Ctg7?*^6f;#j~16pYPaP{S_=Px~1
z*PP5_xhSyAFoIjZ=2Nzc<I0}$PqLh{nMKQ0mXD^6Y?Asib>^c~)@Q}8I~Ph(+%+4H
z;s4!EJG=XNkdwFUfRS~|&ZYFB?rD`P$=#nfiw*9>G+5JP$gVV#z9#>D|E?v;xJm4p
z9;8SWUmh-XSobM;?bgmFPk(OHYABeDe$F$UO$b%62TLnhwy?-q&Qba1X6az<AT*Y0
zXxLKA=_Tz024iSxA&}2*^6w9JBbRhy@-OhMQz$SP!xio^-K;pIO^dnIyaa^?*8y2k
zPTxbO=Qx0GW$;;6xwGAIZF`uN+y%AYADR`mE^|-@rO@_LP_c@Kdeg59igN%~OwIg|
z5y;1j`^_J`_#?x}$1W$|5&8qRV9G6Wex1Pk>3;l}`PCnN_Fsc$Q<<R|g=0^)=)mnM
zm(Eeqk@!uvf`CR~Cv#PSv?+L4haNIfQ<vG>^V_&(l2pvhmmRGG0qM-QwB&y9B;pOS
zkV9PPq1>dwgAj*D5MH+0!jB&<V`wN9ISn`CM?yn%?Xsi83W}{P;z^FCTZf2m$K_8^
zOEmPq&d%yN#l?~>OWHGZU>8g~V}-&=B6Js7i`0_iL}@NuzS5x;MlmYP1+%dLSq)79
z^6M2+Gr1y$`85{-X4&0eXVFHNgk{`(7u9Mgs8NT(uE$Jxf!jp8-#K2YM5{&jh?9F$
znrG74uqAbBd61wOdRq2Zt^V_bpyZ{Y7;_nO);Ncl53?0JYui!~ub1D~?gQLFc!CIV
z;|b|~{KRTyI!<cJOYdF4OR7*g_-$1e|0-t}#fxv5WufEp)LBTdXw22kRyGnVWR{F-
z?er@P9nyNSUgs>7xqU^~-s{&W6z1UKcgpX*_Q@^EVhK*%gu_lga05C>kn~zR6Z>Yl
zLi+`3DmB%+>UVd+9|zLn-C~2)Qq%XbHu_f)uSkUvf|!RS*2rp;F>e%!<?IX=@CoPJ
zEPr^WuWzTLUwQ(BYBS5?7^eN&mRdka3dsxo?Yu|+!pu-Ts-;U^+dh-qRl7TjC}!b;
zjs4WsG1gMXS&HgUG{8&j&9}~mBxLl~nV$!a24*2gLcBqSXRs|{f171nN&`b-{9T<9
z6ANl}wTx8h#F^>q2Zf0JHSiF{S1BAGv`CBlF)3dZoV%JnOW>1z!^D8w4HEec(r}Ph
zFmzSSx|_BBy5*98ZNCk9C=02mJZb4il6<XcFf=3yZ4^`_bog>-jNzBvJ(#Y7P>;D?
zgrrV&(_uKdNdx&0gyL@rdyU#yOQlfqB=i7FXxV)e?DS7CW!)@#SpJYHma!vt1+5D<
z>;=u4%r(873h&}!Nrk%en~_j*evRMFHq*0H&$F?#n09)>%gxQlCtzTa)K*L1Jl$0o
zXeo-ILtww*<y{Gtc)%9O47Mti?t(S?QNuJgg@c7yVVQ?;l13L2s4IO=y9F4bOcs1I
zCw><E-k+TFl8W&*$x${`RNfLyX+?JzsggNoAe=W@d_1(8@Dqp)mTc;1ad``Ww+#hT
zX4p{vx?n}g4Y9f_4Gz6!9~?_UW(4KEZJ1_p7xX-oi~&JHuP>~J%Yi^X2!e0M%EOYb
zdH+~p9<)g03S#|gTP$vKD52-pvh^AUYZd~L(f8?H&M1AN%iP8cRqI<#O-=QIp26~r
zc7yKC1$|HF!gVeAvL7&{5S{j)ZW}e1vEq(9u`WUF+qOfSej3|b`e<iR^u<P+O4+M-
zg+MPUzNiKUg1@$(CNc*<dkrUvFu55GJ4M&Kya;cnKx)(4)gB*XkiWE>^JGZ~P!Q4-
zFo`WBy?+^^;~gL$(#|Y;6ebi(x;?wq2t+d9hwpeXpCNuSBJM%+!3t|0^eHnm2neDT
z3z=X?vLh)ur7Z(OW<ncZQ*{8D@yirIJ`M1LbGfIj5FEh_9fl4E=f0s$dOi4*z2lIe
zFYGw<A?TZW*_w1^VWz#Zwf)YNG~}F<ta4OPN8}7TVZa1$=B1c$A{`i$61x#+D|>o)
zQl_5BY<O+bvT)+*4B>U%owqX@YUAXLd_x3wDarkCZ|x}$g`OSKpu1o!IoOU15;ze{
zZ!ly}baxw8Oj;+0)`)=ICf(pXC?Ytnhn*ymht@Az(BvW|B}nwiVYCrR0JX*=Q`_3&
z3UW#ojjO@WNEjYFGLy+~$wUAU`|1ICj;0Xdspk+KUwbm^hu+*|*<U;q%!6+hb~d!R
zAPEquySDJ)#z&Foe0HTHi1|$Dh3znzMxQbBJe>ahk^DOXP5igu6}8}x7$T-KJ$cA2
zL}_f;n3%k-!RK2Gn~A)Qx%npq<1Ht|zKX;l=$XiV0Qm<!UipUv2(m&-4)64)I=Z~s
zMdZTp-EnTKk=u-A5%7hY&pVTH0O~Ms)1(N0|F>EtI~cLxuCycpaM_avBCN8LEOB90
zkPCyfOn`T>y-*f*-rnB3F_yozkizg}1m=KEOPsfD>Mp#vTKCcn0K#9=VPyPGF9Yx=
zT^<$>K?;KhA@Wc(Ebv-kn+faMFN*vtCJzbWWcsV?{Uc75<MIP3r^Yk(>vBOwzYwdb
z?G=gejrZ4)*7|qgwqxdtk;e+(3zp4oEWGd1#oH2Si`S#6=}B2ytO|nhsM_$~nt|B;
zs}UzfcB>%7UQFG#M4BkyE`P=}871f9cj3*m<EGtU_>gO}+!+pNgjcd+1x!773{M%F
z?X?G}z7BO6y+F4m9E?6it;mlT5IH8puBMH*<8!85Po^jmcZLFfP9F1=2@E^pXJ1-z
zh|{oV{Op%>8DH@8`&K=8Jvww3RpjX^3~if`*lOupIT|^PGBHo$yQihfbYI4Ac%e}G
zp}b&~C1s6M5F4uw@br#6NlCbE`;ttgADnBI-OzN@=pp?X%9DS?gqyzN2c-V^4qzXY
zPQV|ui&=0A3Y*ZQc{hEf7k}fq9h0p)Vv<6fAQM$NZbzL7O^liEV-<Fz7Tc3Bt6ue}
zN?9VNmVbXO{E&_ivziSJ>=>LsSW-)sFyH9eW{f<OE_`IwEjVaFPRaT32d`#XPU7}L
z34qUh69XqY@+t17;A8`dx0vGtHnCO&0~~#&Z`esIN?kT+oNo0StAmYBM#prc&Qz7s
zR)8Dfm0OuzIL-`z!BaB|FL`}RTWHxq?yxN#;#8F?oF*b?)6uz=Fq1c-%4y$q3+|D5
zL2LEN`~`}_eXxQBytq}{;D{e~ZCMCbtdCfDFGm@y%P3yUxxt;6yPAW4<S3@&h^~1D
zU!vj3X|j>~Orxd?0P<WGkYY&oH%^PsfWv{J59eO+O-r4WOMc{`=-`2tw^6sK&xDzT
z=0#p)<QJB#JVwabtI=Ypg0#*nLJ~Vy8mW->@$w5cIXR-T1y>{e?B%kIcQX&S;?<DV
zCu>kU!H(W7mDCbTmcrGeO=-(}h0phL%_n{@Fo3hahTpn#1LK7nkOacr^^HUP3)~h+
zmKdXqBn@WE=Q{5#x_k)XW`jsYNrXe)AIpX~D%2zxWU`grv`{6l_kw5TbI=QozZ@VR
zOs~DbVOX;)1IvVxG4BUY&&t$3roN<;DMZbn@=RVbVdgF(wS*<-%zBzc)HQg4p)j75
zf&mQMB>}h9vl?m%2Djx#elN&_j1mg38frZOgSn6jyISI4=}f2{Y}tL3U@X8hHr*I|
z#F-WS@ttK*2SO6U^oJ36`N!Y0HBLY3GVQ0>Q_6iH2rjI(^5)nJiejKKZo1Dn_|hEE
zgO+kRnEFk7@H%~8cnaadr%v9%qth!eXM`+?C2fc&61Cnn#()wOpRBU54%}{L$}B@)
z>5_bwzjc`8Gny7}gz{njWEZZEca&4Hjd*F~mx;vba^;Lk#lb)3(S(-xmj-hd;@wOy
z>ruJ|kt<jTlf(;UMv?0fsen2@?j~Xm7qv-_;^^bXY8}};zDCe<&2*4rp?K+jKaZfH
z-<!VnVk5`4fkmD^x-K^<tLhW?s-xZ%$pQ*S5J`i`ySnQfP?}niCuDD<0~M~Q48>Z~
z#<X$7P$V+%2T~nXKKwFGf<cfn&Rl?8tHiBxPxgF@j3L_6FBQ8J1Jmk~6)p}plk8jR
zPuW*g9nLSDcy*#l9o^E4DVi4#JC09d;jiJAqL>ej0G+2+l11}fkk*qGiyZR2gJM}y
zFty$;oOE@~1L9;M|0Vc&%@ipbzQF>CJs#ks-0aA+3npW@aWgZRYxVA@MdLEC3WAhc
zZw($o)t~aqq7Wo1rBG)>lDAtL0;bNDX#_cGzb0{%Yc~gK^9z^|&DU&u#0;QW+JfsT
zf&B@VEQ+)+Hs?t?dimN4+`__yDYlKc#WVmOa{xGxH)e3Mq;`V9cbu;m1yPova`@dd
z=T-fsMxZpD?THh+>sj@QIwvM5Di!eBtR$VN46jR22>9Mcl&R>IGEunIK(ms438?gt
zt0|UwQO3XA%_6%oRvK<T!g~3qwYbee2uZ(&GnIur$c2Y(^fAR1zRX{&!-i(<pjCEG
zMIEYULISQY;f%4PS$>!rV2)LAe&sAEQi6})i-*C2VGJ5~lR*4b8EV>h#iv0?CV=%q
z?E*n8#Igu?X3k{z;i2<;Uze0?b=>Q}ZW~Wh{V811hsif#G^dtFhhHuZFOyLWTOxh@
zM({)CgIlYI-?K8>-c>wQUG1`sE~D5y)3f{?SFxd`)#!xB18aj**b&0xfFDj>n-jX5
z1tXX(TMA6d!rEE&;m+PpBom;_PBbYfU7X55RRM41l*|O#c)V|vZBFk-@$ngm!h%Vu
z$7Lx<TzDox{c6sjggQs&-~@K?b9qyel5Isej5Oj0H5^V>-`t__(%pexp^g86Jb?nD
zM+XMq&Abg`1<jCh+K9tuYF~0vg+b)k>5$#Qq`xi%+;d0$<~+`v0%KnT$JEijJmoxh
z1kbJ89DZW6FJIVX?zr@J)@6o?+Qp@m*n7InX53Tcp8nBZx4t{Pu=M6_pDx0jF3-hR
z(gm;J#W0hHiBb&fOr&Fvk^y6Oo)Agj1BG;diy<U2q_gh?5Y;{s5aA_@;u(hh4zA#$
zoiy&VM}p$|4}R2^RvH}pKp>di><$3S5~9Y7#0=R~Uoh_@{f54P7tgv!{`@W{Vz{x^
zZt1!>8J>E^wKm0>sc?D)T!NCHqoGlVD)ffZ!s{HFgkC&l0iL&qa2j&t$SnNCP(6S1
zh1e7+tr1kVk(MMUh=MD8jIj0`O&%^Ye+(jxSP|@tADN|-ED#LM<HF&}HYv#a^XMT+
zDFDFXV3b{MWma3S5<Lz^F5SAD=K2sb;(v^*b~{|!wD3m9S{8hojb5n@u5cmN2PiRH
zydqyGH?t5Y1u}1JGhG!OKOo)L=C6be^V-11y?-dYH$Q9?nEAnCDk|C{1kE_E-@3&X
z!CYMWj7_#9vr&pB>3Ti}{D$PJMh*!h1x?P>D|8~rc*Uu9P}~9PLJ>PoLUotULLN_2
zDSQ=hW}f`om~DjU0AV!cDQ^~#j0^?S_ha22Z|l4wtuv1e-T^->y@5G)9kfoYPYmUl
z1D5=siJr7IWic&X`IBPn%tqk}(Vt$xA}}(=>|g34)c;yIFP2==fdUa;O^5k_h=f9A
zZJl=~kM)QB9+^1e<8fb%nS<|zFWCAa^${m;YNOdPVb8mN*9U-+G#b7KGEQa|v$ls0
zZlNn2V4^aZU1y9^BxCxQvfu5?g@!#J$b_!${}vh8=*ci`-a7rZ-{#V~v{n22<Mx9^
zB!soTQ9<!3XVs9;c@Hj3oLB?uIx5F)INIfG<jL!uEo1Rw@r|{h1|~e7-?Sf{6QoH4
zyz9M5<`A$A{$`nE<p(8OV7C>n^54)k@b<iX-Z(o|2kpMM4v)X5xUUC+%C>RtQxCsh
zv6!6Itynf9_b&VdzE4u8k94f9wc0Y<8xF3s(emIawDyOSh>Tk8hRuX@+D_acrDi(x
zhzSlisqK8w-97PcFIklTvMgg7scqBJdmwYh9rnQWrh@|>0=^wgb_v+@fGF7M@VI85
znA?psOHFveQ`0hQLnxB!!QNZ)B+?F?(9R3SDili}PYpIP^3k$|b09!~Gl^yF8bR;a
z{l3Kcyz`d?AfAgq4#h%+)~$y5TP?~BZBnz=E5Jj{S_Dh)4S&^x9mhxMmE4I3(lP04
zcevfyhx;6J%jb#ZQwxSJktnmssS7dzV|Pd=j(zLH?qNLy#0IewXLwS?ESIL)0qqjA
z`&6;Uvi9=wc$xd``eQAm4)Sq&Dv+AYoB`7-ZI>pQ5xXuFcA2A98ZIfZKP>@P<_sj=
zq!WNJYS8miTqK@U6{ze;<iJ7{Kf7^8>9Av1E|$B65gx`&Mg&{VDEPt1UMp;`>U?(l
zuBc#rEDx~oS%dBk%Wu3R3Ja0dI8|7>oX7aVM3$dhc)0J+v?jrGa-H3klWg5>7(DI>
z10D+iC}ClkN?O-EuK%bjlPlLx%6zBd<L6CU%o@O-;P?E2(E|bsZKZN0`9l>}Y3F$N
z>g%O@TCXR0@n|nbanI@>J~i3qcJ|htJyuGMIAO7j(bi`zwL9Z6jkXH+(Ux^FhLD5N
z2efSb7Rp~Jm+||PcYbdC3<Dye{coN?`z_v8{+7?8j6lJlAv0F7^k7VCBM|c-gEz2Y
zi;O{KI@k(SCyu0Y?pjL|;O3U3vq9O56Cn;}@Q9C;=XR=Aq2xD+lm>pAVV@}j-1h7Z
zFX=1~J)<N*-{PY5;Bx4ZQ55+mx|haU#p2NY^s*uw2Ir5QZ6ubyB&FnpWCujPxeze8
zG2-nq*A&&E)FJ=WYfj;g9sP38y`z;ck<`gOpm#emoUWhwg>OHgSW|7t3PCtPC#n!E
z$?$8ShK>%c4kfMaN;-d2+aJEFmpOxjH<oB1cKo&DTO?4wwcCqB{uT~Y$1W~x2pNPF
z_(Xdx{a4H#PV3CO)b8&C#zWrrEY$hhr0)xYRx+<3ueekrfT53d7~trp<zs~#-S#a|
zL+s~iI)%01d=m=ywF<-$6A*n5wANDggC97zKb($@R>{srCgXj5pB+!X9A+Hp?qU}g
z7Y{~;i#I1ueRi`4HTm@XV;<y?_kSiIpvj6F*;1svL^2i-b&@qrbO4#2Eoy#{p!av{
z>XhJhGus}yJ4w8P%A-1W8L=sY9q)q@zBE4=Y8cM?eVCglL3v7nj330ViIu==S@<q9
zXnc|$3$k#TuDj~2f_QN?OW|$o{Wx@TP#ihcxrOJJt}OV-{q_7^9l5AphG7rfz|d($
z%9Zu(@2{Q(y<>FqDe}_t*GqC6FF2H+$|;21JXI3qUX>BbKj}FmXa3wOFm?$_3?zjj
z@I|>op2F9yE%_Nv>o!)L`7af^%NX!-dDmzzDBHZ{5AtOhTf33&s4%=R2<f6FS=pS)
zEjp<72I%EA#%`gFH9BF&KuT%sEO@^R1<Qj`;HxCyPZssGWVd{Qn`y;qmfS*+)o$gc
z<sDAp_q9ou?89$!jk7;l#4@-1?mE4xI$SUPhM}s&X-(DU?Z?~i6~?(3-yR4y2)rnN
zV$gtb3AGdkpR>tXn($nQr;KOr>}%lZub7b_>Qn1cuG-8p?mdfPHJ!3;9)!ndnoIf0
zJe;)r&@AkO`sC$XcMFLPwXt#+0hTou3`hH?`m%a~#&<uPqMCnYO_$a4U{vcIj>`wh
zKh{<YC!c-EPCZpe9of_A5UlM{+Wt(}i6U%ZO3o&Ptn=nX@e!-Nuk}(z3e^G-E~Nb?
z!^Wcf1nb~6r(92pEO>$bm3@7NX89V)^G`Rd-F+<DSuSbN?{897H<GIyp32@~$RWvi
zcavRFitB;3JE2H-iu%Ufz0KSrY*JR&<VsEF8k0_duckF2dSRoZ{v3UWF0LQ@tw-#A
z#jj+)_1=<PVwk(A5Kw7-e#@#MgLa-MDb~$@HBUZ{4l0Rb7Nr4`(f3I}L^)BN4w<GR
zhIRO|+U|=sTecud&f7O2-Qp(>DfQ$cVb`9$A>j;8>QajO%H=;@!6l+eLe}jdp#-XJ
z=L!a0<;$i7c}tMf%YR;AAOQ(vgGe2U)2@T27Z~J0Q6F^4Kvij^l$kxQZ$QC`x*!sf
zr&<?5Tdvfc!4KQHNI_;=|35E_*j(s$lp|3>Bd`z5!o!6_St#9``~Byan7nnYjf<KG
z3slYVBXuqp5gpC8G0e~RP~kk>GJ*J+fjNVilv0_)t;3%R8oC<4S8vo&%-HU^3jCQ5
z=R?c=&(txt9I)1&*2OK;>lDnG4}y-|{#S-$cbCzp*Cy0m&)%}!cb2I-_34`EyehV^
z86@$XIJ7r1vqfduzV1%v$D{GV`iuy(UsyA)Gd^o}@ZwIM^j|K0ueHfIbAtUH(>e1Q
zc8)^XVrk7GL2Z&pR9u5ox>p)H%ubI}^yk?x{J@D>2?ZXu%8YmPxV@wv(w-PIUwUEJ
z9dNhB>yg>X@oj~Ror-U-D<9Qwu9-iYx)n5Af+I)s;6kI-dRwato`iB*XMji^9Js30
zEga|a<b6AU9(TGeJ_r(JN(?$&?O06<k332<RhK=cXs^(A@34!P+YiNIWJyZz#87`R
zjeJpVm({US#aq_C??{btBHW<}-Tc|zUi~*Y%Vt_K-fahG^)zu~KL@40@-7}thz1N@
zA+H{xa2_4OjrC%>4nKWeQqZq!zz~hR?Sm3Cc)tvJ1uk8K^yuF!v91nZpi4fOaK#g*
zU0}lR%r?XRWWT|t_-)NIwY{x7UWvj7`#D`pjHA_V_F7+AP+BV(9<E<>{-5$ShkUBT
z7F<akXYUmqG`p)8tfo*+_<HYU-$pzvm=H*yko0^me7~mDFxmBi%;!YEd)kV9=V0rp
zPV-%F*j5aTxim#!A<jXezuDhp@XI#Tx*UJW5(Il+d$Cu|Sn%@eZDGUVJy?h4WZcNM
z?f^qEWF3zXP6i6-kT4B8M$6bkm=av;-+a%byDE@4yH?4s_FYDL_5&7muyGwx{}JWL
zqp|iD%NqE(ws1dJdC~FX_a$7H)J$EW!#;cB++~Ebw!Nje-{_FY%8G6eE3)$Ab=<lc
ztH<>hmp%R#1ZPE}?h90OxiR))sek3WYeIsrX9N-aU_TcM#e0aDaj*}h+@9FJ?rr<^
z?j1pC`)-XT`{AxaCB9u|%#k~CWj!^Ec@(N8V`-RJU+X_T^0|2?8Mq!J^aPJNA`g_y
zOz@jo_!pC7md>(Wug)$pK$rPS`cLsWjLV0a4ouO*eL&ZWV>6}wF8-j;(q~`BvmVd{
z*yVda4`{_-Lwt;Q>9)u$m+vzP1n~>^8wzjzd|tr2Vm@;R^Nm3yOku|NGs%x}ntvrq
zko~{~got@X$R^1~e(d0%2z@uhsi>8=QH}=Q2K-QMl~^AM=a;qW);4Y3aysrjIDwW{
z`RBCOwry>WIzh-qqi*^jr!)bB4yd<Blrf4R)HOO-yj#)Ksa!;--`7^X70B^-F)6E?
z86~3@W6ok@!U8pf;oZcKiE|I;%ZfVe5t@%nw3;JXAG=tL-nhC}?-DiR7<~<4I{qdc
zcp=D(T1UN!$nfK?<rGVwLDORz#eg!o1a0iGu^8c3<amik;<GD#f1wX${~%2uE)#Vv
z_ZSU}Nn?ccKH-l7Fd0;!74RuHsQ}&9v*9(l-l4wTGkSuVlDWd+BRt8OgKWZcnLy{j
z8lU51QeOd%V^LArxjBI+JtqQr*#)R;r*fE++<M_D2U+t#r5S)g_odhs_Z>#wm_4Nz
zcaMZLLcwrV7M8UsmzAKo%=y&Z``ZD}nSG5Y>9H?efO&vUPo#db!7)5$YUt}Da|CMY
zKqrZG>IOmi^o{7TwlD*nWbwQ69M6_Q3@V0bnTsoe$yNi6tJ&0+bi!vmTj<$?ff#+A
z-vuf>2h=>=cPE3s{dEHF0@)Q}#+?;U6Rl-RMm;N$Qy318@(Jzgj26-Do*&`+YiC7~
z1iA4EpBFUE$n{S*)Wuc;7KH^C`n;zr4o|b4E2u?J#Wsnp<#|8X`|8l)TFM+jr<<kU
z`KO3eysy(y4hv>~`P`jD-Mh=mb5)9_Eap^omv8gFRE%rMhe8SWw2FHJ;lyn;hY213
z31NtE)3nQmp<=g%15!T3O&2us-A<|PWH>ZiE^f4=#`OKnyB-$g($%(a_i;|&W#dw2
z+fJUHm>WGUXOjH@`nw=Xl40)2AGId-n4v=jxr(2XPnERMPlK@r*vW@eO{v-ikM2F?
z7+SS>UP<vseds6Jx$XyR&ecFD*H*Tv9vG}SQhKi?4m=QB-4<5b6_Y*9{Mal|n_WNT
z0M-qU&fQ@DyC8t>3&bEL<jVy{8QR;jsXhY-_(PV@xS%b@oS!p86p)0PjDXMbdzj}|
zL#evdX4?w?QPg#^;e<{2%<d<1N0i)ha$feY$!O=@m!6QYAmH(ORVt&BI0FX+C3#Hy
z?E;(GofqV)|1>f)6{kDeRmc{)QS;($M{@D|?WmrVwU;sZK`BYPCNI`+5WmCpGqlC#
zeoAYwNq#N$n<mJf3u^I#UU32LN8)i@(q4d^p0Z>7su=gw(o&y;Kk@OB;#~W~>W3A7
zb=jevi-eKQUUn(mSF-Dr^mt&PM<AW!8z~~^5fOo`DT*orP5jm9&}Y=7EciX=5pe@Y
z5vPM6i$hC8K|bo3MD!z^Vs1^wL%hFzfYm{x4)yf2e@YU@LfO#I>VNxvEAi3x2w3UN
zo}ZsTM$eSJl9fS+5%lZ(mzUb{YT-^e#`L7}w=<#cRxy)QmoHwP6i%+ZlFE8%Bmc}-
z<=)v<M8w8xir&)R{1>IYrP!BW?u8@-SNVG$F!g)>Q}v3WfC_UDaj#LfOOmU(ftrCS
zgxr=&V3cs}6JW3O*2(Gcr4QHU+nlOxqkM$#dbVbHP3N{f{lbY&yzbUY$+Gr-(ZS21
zutm8|vC;@JpZ<W^1+&s2vz;r-hF$Y%hpqgtgbE*M9yGq>u4FPh_=BC3fT#Z9l}dC(
zIh|v)@wNlwoB`xv9VXcrYDV-c5&j_^Hxvnn+a60IB{UMD>)A}gywsDOF3!HuQ)U)f
zqr%Ye2>Z>^?KKv~XI}{oQNZk@YsqhcRDs|N>#nxmk4kD<!jmIMH^UB2{_yOa?)|ZO
zs8hRnIpL&;J=-|q$&tHuffSJ3cW<3;bmO-K;mi|hyPiA)C|xgOzF_aEEjJ*Cm~pfl
zAZc8ogF?S@<jVwnxP~v2!uTRF_R+8^!LwbF;2Gl!h!zFpLO7N;0e$-V7_+vueV*x0
zei9yyPi2)28t(Xi>7^K?()DbyKU2qAir3W^<~nWnhbO-w2i*LjUxo5MP};TFB{da_
zoD8{BK}sU&gvOZl?Vht%Ih?+%t55}g0N2YdGyCU@so`wAtCMG<2zv-MNE1*eX0wpH
z@gGMBWb4HQ*c0Nsv4o^$@+HUFY`h7bAS^9+vb@S=H$knDA#v!or+HVpok((q#6-s-
zt$-BfSvTw8UPofaQde6f3<kv(4h?fX-^-JYTg&9axTEdA(sh~}njCvJg~IEWlSc_u
zr+WWGOQNpx*D+#lmCH{0X&5>?$i(8<A3u@YxcRa^e?nuVDz}J^+I3@+t4`0RxVwet
zWZj@n*b}g~W?sD6NtN!?<f)j+Hl!66E?t*h@DlGEFnsp*!Hm|nFdP;5H93t@=5+U&
zs^6z!?dRuc`O7q8y3|G-8LKQi)tAnQFSMI@W(=_PXD8g!dKVq^^t|_{9v*TLH=7)A
zM_+LGqnG|ia#g$~BW<3M8wB-Khk#UvgddXrQMk`X!F=4+s}sJ*FMOk}9)EceMS2|N
zoB3n%OU>!PpIVSPk0$TZZA2f##A0mcq<ElVL5Y}7`@`cjr=~9D_CY6?K-X|x&(x%<
ziM6Qbq^<0ZhfHnwjo5`)$>uHCbjwsV&m9Ljy-70xr^-}=V{yd*H%j6*V;duWjKxd1
z(}4dQvC_5ddW2o!M74d5kfLC$?1ikg)~u1+SE*{IRy<!Ed6GjQaV-l&Zd&lZe!+7r
zok(IGrL<rBi;vVd==AL@rf>OS(=QCfe21pk74YN?lomx8KZD(SfSb4E3`#98P0xC!
zGq!<g=40Mx-T!)72It)o@|N#X<AHR6a8iWugZd#K(!cdrxi?ZwX2xA}{IR~kF!Oq0
zc%$qVz+ilRMi?Ac{p76}NLU8OlqyGXUbh8se`*${*;6L-q;_u`)(7Zj=q};4N`LtO
zZqychoT{MG6*9B@x-mO!Ui5^oriLIAG1YECa%IXhJ%3LXf(#e9BByI@ad>%8`Si>0
zuUkPXDSvPj^O<;B?y+`IH1!0<rnCOke%v-s3ak=zhG#Hz@l+xX5s83Gf!{Z}#e$P@
zypb1M1f8Dpor(%U-V{yZy84_zlXes;MJ_DnGx#q^4!#`3Lynwe1$=MbpYQZ}^urP2
z%(?e2g7M;#(iF9#13kwz0av)wUUnogga$1qwFH*bjknZYRW<bcL%5R}zC`EbrB94u
z&&&L24G2DR+Y@|i&ot|C&Oaxg%F-IvPW5g^rQU{QO-;N3zu`bH44<@GCv1H))A#N9
z!rdeJp4GW#g`L6PVuV42WisQ>63enZlgEb}_pm$gWFZ63OrgkM$*vO!JzFD@Q9y%*
z^vElrtS>=}arwmHX+=r@FqvT*QA{+v?5{msy7giohB_ILD~tP>_Uh4iv;iQS4S0R?
z7qS^%DN<Tbkiz(2D!ri4ah%Xyl-PJ{?X<8#n$~6r$-}U*rOu_(iyA0YZS6092Xe9X
zDzZOlI_8S;@n~I=S6ANL^e$a47%pP*&$GhOVg(*cG)`Y@D%>3~wH35XsPu}*qGYhO
znWVC!*p!T61fOHq+7zub@s7}gGpeT_LFRIQn8$pnTqN+DXjyyNj+Px?TqQ88{KLo4
znbkHnqnw*pZvl62f=bu?`8d7Yv$Mx(OX~Z283L-i%k%uuob*G^T<4)pun+*W8x1P0
zpOP9c{c%<tsFX6N0m4hEWGim}1T-uHrRQ^Go9{Yq_R%QPE_cf`QaH6Ovr6eSt6qH}
z&Wjmp)`U)L232@OL=W$Nb91gSE@Hz_Tco`A-MGMk`j>+XtAU3>JABI3VeV;48RTW;
z%7Ak9Gnv@8^fM8ylji1h^KK3OxPq8x)1nJqbHmuqI!$eV9^-ND7FP^^97-mUNGvNs
z{!5AnDu1)c;Leb1qskDEQi`jxn({*zkYd=4kQ+kR-y?3^e=3Pol)T<6a@`f(7#Io7
z><B!rPg-Hqr>K8>kd(BSbV_t)qbvBUON5%W%KYzXdpTIAH?MPZmLgi5auQ1&bbdt?
z$1YA!$2#Q{IRA2Z^D|cevC!jRuo4~J$FtE3U+;9~CtmI~_mIHMXSdq!o@@{P&*%H{
zo`^5!%yB_B?m1qWvK2plrJTAOriA5Zt(XShS4-FnVaOo~G+o&7feG4V+Vm&TkZ4HH
z<;ZcY<lX_cAQL5Z{gNDanjZYWChqxMljh|vwntYkeT)4NJqNmd)5+rN+;qg-*PwSN
z@P@O9q+=D%*1FE>srnEWm5^)c4$<q;T^kD8jMc#bHN=B^^#8i4sj`)tQ{i^o@DF$<
zjU=8^Q42*S<!N7J>^=Azc*waxk4%X8ZQ>~w#6VLO1TXJD%al=xqr+T*NcK<!Qa6N(
zvaNle5R<}B;s=b&YL5f{Om3fn2Z5{1zmvFEVSbe6n<mtZ+e|NfQj4s>a3fJ&<6Z?#
zn^wZ}#NU1E6X}H>K~QJ|fa3;_tpQ$*=Dn|FuLzq<y*la-5pZT6RF&CcFr#zSKBu`|
zs}E#w?Nevr9GPr5P3Te0)9(!IS+3HX(_s;>uO{Z5y_&E+JUIP@<%^<8xg&C6jAd&N
zO|L6e$GL01%oaJ2_??)5CE8cE9S3U_H<>&^eEw)$;9YZClWjXBR_(6<X-b-+;eYi<
z)|O6c+M3Ng-ga*m9~W2^_6;Lu;)TG7fjifbd{#JSEx{_LRP-|XP#ALU=kHw{?(lTP
zM{oHu1|?NS9RJ8fknSmmTY8l0ZL1?khL{A$;n@GY)sJV9+3|!jN|Hf0z=~UH7P=T=
zMCDWE+qCuOXoLr{Xz&<Y`ud59;rvewLSmBvA%)?I*|m~o=XU>WKR!2OOKJPt^7`2w
z6<xRj`6LcZ$@#(U!(MvoPxIyJORqZo?$?FRTBm(M4~I@@a~ZL7NtE($dmnLqnaikG
zUn`TVE?)Y!nI7adn{W4q5cH${>*|@_lO!$o@p`33pIRZS=JiYu1-b{>Uf(Gd7VZA}
zv*l<vnIPd}UelSHzVzJ_Q6D7BRWaENd&7Lo!fOHH%^f&aVEZK?mhYQ}epDE>z>aD7
zo_XSyc1hZ^J94tVd*5CFu^<4ELuSTM7fck?HT9f#hMOB)-CXla`)ng#Hr$ju=ks)(
z_iwG)RaRS73l6zudlDS%#f_7l4B#BOvE&o8wbOeUZQ3p(cE&RnFegAHrcQ|wA<o+W
z3<xjH+=kz}7-`X|lBOtj13k>Y>by02Wozx25F7~{d`{%nf3b(l84i3zWJ+CXT03U3
z>uoiKZPgw$I7aGnNaI#AEW78YaDlXge}&=TWV6}PP&mN9a{uKjI)<20?BnjsAj{>~
zdo<5MDMh3?9U^R7dyO>*5i7{g2y4WpZ5&m=%($+`>+Qj-S6{ry6tO*_{hOSMm|Np=
zg=(J{HjKZQmJx_;)F^2Zh`~%;Nf<FhT<)3i+UfRGRS+Tjj35>Cd;_gJotfn(Pe}C(
zRaJYUI7fRoOXMtdtiJiuzf`1neGq(5Wj|~k*z3O%*o+1`g3Or^0teCd=@@!6%(m<L
zA|XZ0F1ur;TGsxNiL+pO8aag&zJsna!w#r;ylvM&eG!Q(eC7Vv36~rfb0MmzX%y+f
zh_SONz%9;bDJ@M@Mi+PN3}MMPl_&2CUu@9En*4SUSi^-?H|7?toXf*-Zr1`Pplv6D
z0i&r6Ig>H_-|m{A6ypy$uLr9wb3RMy?P;h)RS6bJ^%WHfb&14y6$vbl&pPk&>2LZ6
zlG^Vs@m};-w)eK-=)0&Rfk&SAs^#TJ_W$$DN%jnk={)b=yViKLOZ51>nI^S>^2Mfj
zIc5~a_a7PW$`6kmec0twuvf_4eH^kx&H+x>R`#E7k#Lb9r{=bhzt;B8>z6bJtd-ZI
zoAPPkxBBY6%Lw`uOik_goDJzZ9NB+X>I?c)ydhQ3Q}x+4^4b^fSb3SmSUDi&Frkn1
zy082~-jJ|3ZgX{(VydVJ#YiY2%J!UPwpIuPJ+S;sodJY?4m#ukT+aC3hlc`IDwe~}
z*?}&2_x#Z%z|${r(_;AEJwGPQW2A&S^Dij0qw}*a^o>vC)EyyKAJpLtkJqOy(}hYR
zv$NC3Tl$N8=e?1gfOWiF&zW_1Rd-?`{x8pO=L#$Zlx}L+n_Nwzs(6J(pFOS*SxNu^
zSD;j#d6dU*9(|j4_;&_;#`axje!(LaV%Sx1rHs^s7+LWX_*PfWrFwlGvJb?cae*uS
z%Yu$pXJG|vCI*r9P5(*eRCv0*=NAFlJsS!PG6>E>C@<h5TKY%_*fT1=ELdYX8WBsm
zy(F~hdV*d4IVU$qw0%Tx>YJDuyGs>#u4Xvq6QMv=El<&Qw1vyoTTzU<;RFS}e1}-g
z*jC^y(N4YqvDA+cAP$WA$65|hL@PfNWy!{MT~5x*bZ%qMf8^w(TWev{?$9N!YGfy*
zsMN-!x~XcO$Mlr^rho~n3nZj0e}?-jS6;Gn9^pXtJBSJK!1@BFm`{lbCG?fL%f$~k
zM~t@aX`?J3V|Ljv+powt(y#9nb)mn=nW5Y}R|FGDD?_@Z*g3egl5afe`B@XF{KgI^
z%w@q#bA1kr@_9y$f!?R?LPtEUjDpv3eweADlh*vlD=ejpsFhs@<FQgvEftlgIrk}5
znA5N9FkHGcdx;cIeeD{>wamLZ4=PAi)D$y|i*+u`6fzF2-=AZ#uYA+NWK=XER!;Gc
zqn1u=jEtWCU@O>gd}D^^OT4k;Hvi4pZ0LFom9lRDO`FX2hVguyia@gSyYH^rOTOe9
zTbH8UPa#NWHuS_N3eoufHIGXp-(CAt;IHfAt^u-B=ONxRm-E2njTYfpU@y%lg>X41
zNA0s#?9I_ld{%|}lSe{FdX?A@2q}JNqmqb^#i=AMni<9`J+%F|Wtl`8=dDdw6s->k
zeD(vpTJvTtjhU~OS`a0hvxWPAupLCuOSNz2rL|~n&{=gmS@0?16X^6D?~ydWdWZjZ
zo?lysoBBvl5g!Gn0Z#J7chz-ayse1n!K}u-sDIpGbmA~!)VP&sNu&AdjyewCAI1j&
zliVrP!0WAl<m2~Tu?1f6?1CEGYp+J1O<9<|IJezl*vuF4Lh=&1TQ8m%O2w8qIZyOt
zCdx}dAayMD2UC2mklVMTba5R%o1~YSzz(X68(Ys81GL{T-{~K(dNyR-9Q(^fAW!B$
z4(Xd1wA<K#8Q#nYFkps41!!?+t%DXVcHYzH<K$!6kREq_WIrdP;!Z`+AJGCy#6*-<
zl;hMVL9Y-AjOjK-X0Y0)TOW=q<r1!)c+w#3anz7U5YK-Ug~FZ8OLo4Ssf4#pd3Y!{
zI#1O+s@Ux#=IAP?4^go(=1G6M^`U{&=8OMo&h)8=zGazHT19~2_xaMpM_Aq2M`g~2
zKQ7ObTrnsP>)<Y8j%R+J@iNl4E4C7M$G?W|FPpv!lF=8_oFl#Lw(<yWUBKXhYpj-h
zk?+9Pu%&gH@F_U4nb*8Al_=2ANwv4JrDvco;uh$+CWy$dn?o%YBsss~i4Z0uX}|Q;
zYFjFo#q>()@Rp`zr_O;l>Hl^L&=;uD%PAFhy=AUV9P4q~BHNKuqaVhMel921k#k{V
z4geq2T`yOq$uX>s>{06HUgd?>cW!Yp1!?VFE?%iaqR1*@Bs1ritDRfwGYrIFD)uMF
zxTG5U<-GrS)KzxO^*h=l(az*=<!+BJn7nd6x?mfng^U(Q(p=+cDD#2wnz@yw&CIpZ
zLms*z<J^Wo?OXFPbhkT3WsKtCL8U{)O27>sCP};9o>@!<q;yJ^vRjIGPRkUL|F_YZ
zTeKc1b#_<irrh{;>`~H$Xjv7L)CM=OennNan$}r2m1~yu)33gODC||FQX(Ku%N-ve
z`)2YLYR!#51~)b?z0f5!*g6OlHv|oJT6uevTT5ZHnaZHIm4DZ_|5FkC;wu4R#KWC&
zk+9;&f{++Csg5%tUZF}%W_`DN#!QIt=l*myrVGsLwiez^E;H55LE`Aoy2G`}j}Gb|
zIgZ{(q8kA*Xw6;0(12NM9cuURf6)mLR);z@7Q*}iiQ46&mi4n23XQZw<DCNK!mPHf
zPXOTXC2{LlIQ)mQi@Zhfi?IDpW2x!WTDrs_oW-PUqUGkJr?b>ZGl)`CXadn-JHX1q
zWdt%M2L6lwQCG7SLD=1b@-JQVUaJC?N4JrWv6{Y-d2^uvE^o*X=R?FrqgSLz#m0T6
z>!uStr@&2e<u%3bedNLx&P~lJAH2gAQXYO?Cw2{30{(#VzIWZ<aGX?xnu?Lqx##_e
zd0hnhK^y%O_9JFy()r!9x`{&cWc??&;%h1Fb=}ra@YGZmm3gDuLmzzRz*_RjvugH<
zVl%Df+I^XtCb2iTXN3W0fO#V5Z(}KW;F;aGpjmq}??lw8M>zL)^qWmIBd|}w^xD*-
z`-%BwSHMuWdBfej_)D*bL-T_8wvtYbIHJ<K?8>ff=Eb1oXA!jg{Vz_QZ*8_dsea-w
z3S?j04fqGbYjH>8&rYQm7R>ae8t!LIsMcII3|u0@rLg=a{0C2UyNK(_NrOkj*G;t(
zjEFM)5fkujRAZMp!}7w#!voxu%~Pv`_88{F!8_GM)nxqHf&U`mmomz-Q>-Q8HXF^7
zHdWW{Q?M~J+{np1h5<ao<$<MYPeA_R`s{Fcjz1^Mrx4_{l;X(khmeVMZB&WDDC@S}
zZ?O6wAQ17oW+;?UXF%nk8YSt}Q~0zpr@uPG>A`lZ^3&NEO$~jf3w{B1);u)_i|oC!
zHs?bVYm%!`)m_y^A&4@096Aib7$3z1u2$4_DEYARdBfgKKvXo!DoRYddfKh!PY?n*
z+Vg*u?zHb1FrX=1MdSD4P5Mah>sWpxx5HoRHt(p_8F;8T?k^-FE2rc3Wvi2G#Q!nB
zKpE!0b}s&d%A6(A79ap2@>&+!(<O48EvJby0-@yb7`hUuXg32EGAkeD0?|h1ielxL
zZpn}Rh4`yI0W&FP?^!Vs$gfk9Qh5n9I$$3~{ywERpI~{^o~bTRymhrQ=G8M>|BmdD
zt7Fir&UD!y#x-oB(HG8PfjbZ^77`a)uNtg7RK{Jxe8Ht*v!KLaQmRm9B20w@K`Iyj
zRd77W?heK>iUkPj)E?aud{BS#FYnLsZz#W@@otY7K_f(F;@ZTuM`!^))-bX`en|#y
z8g<>rFWdk9qewifkw*FfZk!rTL=mjUO+*6=U{L!^Eq*4eQ`jOUB;oI3cC+({ZEmWv
zgmzB6#+w-~aM_OWB|OK+*WY915AOd|>SJR*G&p>j!uzF|?}F#qe-2S#lepgu7jbAL
zK@@M9`i`jcdV3-)5f{MAS)33#&c^Hu#(%eKa0fpLho0S+RMg>{AU|J&WV8KCG+D(^
zQhAYfNu*{i!ztCjj^doR#ec{4#_vq4>kb8PaB&{qAXn2B_5bI>g9HXGv~{lnBx>?0
z3(R*l1^q+*Y{7LqNQ6OLKKwhZ@R20#zmp6OAp8GLCS0vG`gd&M|2_8q9{c}3M%K<1
zmwFp3Uzn#8Ix_->Ag2fN?46A!<op`@{hXa=ny%`~#PQq~V}^=w6w1Mlp6?{YszU-&
z>Yw~k=^3}3PjE|`P<;55bg%U#OC6Isi;n@vm7cR!+4sQ^h%Uqv`5^Nu(l0|yMqo@>
zoZhuHQ(L$8+&+LmrG=p4&dqLUd#)y@_u|`4JIw(%S9{sv2HDfBokv+~_S<n^KlhE(
z5sBEsP!e~i9nY|}ibN{ZqUdrTL;jzdpiI=AW@xM}#1R#4c}Z!bF=}2Db|NjM&t)?@
z4s4Y)FN1F=b}XReJu(0wG05z;d&~T^w(jpgE#&p_49OOkqqVF16d55DVfG@4cew7D
zoE2_>6HEJk-m~*c)R5lyz$f=rm}?GuU_skMD0|9so9=8blRxph_(I#X6nz@UW(Z*u
zJ8m~R98*^;O5Cud{QhOe)yOol5xwbzUh-l41bIsZ>F<8|r&nl~P$#t)Fw^(VY?$UU
zp(iYR&n~ekL!BH7uP|WCKR&{GX5BJ&AG-vxI5xRlpYPXwHlhvb+@K~iso$T&DYRw-
z(?v`Q&))PGF+HP|Utm~%`{;v5U@C*cLi`*0`E{l9MSYU-z{br`BGeufSiCUVU)%t$
z$`7|^zOpVki%Pk{rwJG{>p`XA3vuAP7lNNt1z$7%lf*jL)sb7bkY9H-N!RZCB>6wd
z_LbF`U1-z$y%jq%v$E(H$mn?HP4oRXF~GiE95s`<2)-4<&;0AZK#WkbpSE`w)=&SQ
zjlM~TWIKgR*fX!<$X5>iaXmSvC$p*@DCN@I0*<U_cZ9@2y770fB?8AHVc-AQ`Oq<4
zY10m%(p|J%2&RG8sJvFq*SR`uJun{==;TRvFC*!x2wQyQz0`}}FEZC{p)92^a`*X}
z_nuK3`29mb)8ZuXGx3R|xU)Zv#nuRxGoDX8=327lDvkaUOPp7MjfHnwQ~8Xg2!<M|
zVv(vA_J6~7zkj6S>+6fxU)5Ch@(W2@dtWWXH1qE+{Gv)s2qdbt69S!u5ZP*Yls=MC
zj(I$xRLtk{UkLvLk)ak_uA|VIK?iII<N32j7&DoqpCJc0@}QYuAmLr5N06xFjUb}b
zq32-8aZs)6bDsZ}{>P_>Ea;sKO4i+Gh9EOB08<d**NGU{@EMU6^$YC`J#!N@v5d91
zu#okZpPeE>etx?f<Wz9Od;IAC8eMbGX%tf!uHX_^!!E}%*C|Iqr{=n`<eyonvqKJB
zrjuhJ+dpcMGmjvY&jo$5GwIvn`?EJ-A>pAvUO$KbTGT9HYIAsa9De8s$*0ps!z!H8
z4^2X5q^1t~&rBfjfS|8(Zwo9B1uBZXm;VQSc9hUJ+Z+qnBD!(wJ$$BF9jQ5G#-8I+
z{jqLqg<QpRfpifKv>%<)2{s5nsPPOE-uqv<mSsPNzs%bCk{RrKv~vriP{ah`Rd%Wp
znVtii5-w#dAO4^Atuw5tZD}LDL_t7JK#8cx0V$z_kN{#=ibfHX-U5o$gLDE!KoLZm
zv{2Q=AW}pO(n6KqML<eKAan>dgb;Em9?!YIzUR5$-;<wtX3g3&YxcWl&%C1&l^HU!
zdeK6}M5aW+@%N5WSV^Uz$4<N~D51o6qE(gjiO6JiNMDUF=oGMz$4i%Z70-cC$nlb>
z=pOR@$Ex9q@;m*OYVRUO*ucQPFv41omnARYk5CJCT6Z%>T^^$O(B8kAoId`B*7jaU
zQ+Gsi&pSmEKL~4ifP)OG1v3`Uc}yP-7CE3Oh0d()a(B?)7!XT+1c*k~n)8PJI?5~(
zjZ`p*NPStwCz2~D65ujyccqb^T_z(xBcq(-&e~(%N<U~b#!IbccIH{A_OIyMe($<<
z+2haQ87k+967Ox8Fz0<cn{Ww*0-!+c)(m`s7ha;~k?{y;DDm`9KtQsqcv!&irB@-k
z<87@1ZoG~G#6~99&j1+(`yzQrqMNISmy79e>+w_X-1-Avo^E!0sk`~?JodlCmJam_
zv-~z-EXe>Z%_H+Cd<gWUBx@d;3VZHnF#oEI^GALkT+I3lxbeDvM|wuoLG>Z7f1sZf
z)&%(6WFCt2|4w*5#EWs35-4|UqZRs3ueA<V5%aD{ZM}Y2-JLU8MJ7!q2_W>yc`hdB
z8^lnszkM90y<AsYRw1&yIqQVy5KhAk_2Z+Wf)MrH?~IwBy|)rrUoke))3CPKhoir(
z%+UI;)vJxeqeKUlp~S{7@4hm4T<~T?{Npa3xzyg;kSqair^m8~-xElb?<6X3D92&m
zTm|&;$r$Z)jLUAq=XEsI(se&7O-#pm{@fcX7&y=QN!~~SGAjd@{Gr*_Me?>B4Ozky
zqwZdMAem!u{L4SLenY)9k}rayOz@>e9e7!B2NObLl%^=xcsNytCABMaN%whJ*WI&x
z$*@w-(=_m^th88+_y^={pPa6r_Nf}HP~QijF5c`My)+>RvaqShqZe4{r>2y0|D5OG
zU8zCi#FCA2JG9+V)zh4Tzn`4ERT03>o@!;G4rlrL)yAlj+|Z5^_09f?eJIPOzwje=
zgC0EsKq(lI&KfC=^si}ah5@9oS_0QI+^!zHrB^k-lW4~Ddh1aI4+faig;-FB@<+4W
z#&~escs{dJiyrex3%jnSGE|&YUr8P>J6m(?AoQlGyv@#s5i>@j>zj9lj|X`;y&S+*
z_*(4Q_^`Zv%=C_HbG5q#U!%`v$!vmSFguD?C;Q7ih@jPT=ScDpmz?ir-l@0#2L4kC
zaConVofp;Ntj^;xTT>h&`c&!f2#Yq+vt2Nce>C>xB@~O-Ks!|v{6ukkxWALNoXWd&
z=Wa1s05xB@vQ*y#;6OkcwjV=uV5iI<(~MJ7@4H+6vIJ2=Al5!4991m3AO!rqmN+mU
z*TmPzSAKTZ4S-^KA*PqTdp<q8&S}Q=I0ucmLmUs~ixxc=byI58o&D|qwhEA@#eHs;
zF1a5D;s<|2c}%l}^2@vjzyq7+t4OYzHwq8>j4pfp{la}le{Zbi^XwP7rDwW@!!eCT
zbN&v9#__lf%}^vDp~i43*UAEs-*~DxSK!z`bmLScGm6j&)rP36lJU1$Cnz0Nzcs7E
zLJm~O1zyAjGMzQMAPM|1x|8RX@PhXLn5Aszev>d8#lXT{QnP=<Uzy>ASjIl|+#ZFw
zgQ@KozxgjYH}3sEr1qH6=U7ym{}uaJ>|e2e#r`L;C*y-QF3DZKI^qeFzOU1sq{TA-
z$<HENb0%~(h_D55*?$6X9p3At04d{Vc?l2CaFd)6RMkDUR}HBslLQQaNKCP69Uv<}
z5cA51#LMKCw9NaGHQM_lcG=J1yJ;_dq-YUN4%1Zd+LZ|X6gUZT+261@w_jjA@_~W2
zM4meBmCSv4NX{|~28T%Zy7d?s#W_8&vjw{)j>Z7f2@JAkDwBC=D+i`tUn6akMp;<Y
ztny^AgDz{-tt<q-&&pavT3ahCN2*kZbB9yXv%?*jcbT}Mk`?K<o3oC=(cN~Y&4VU`
z73;}{v&XC5kKFROCvSoje!N@Ceg&c32&w<Tn>aQpXfQ%gt|Qb1SB`&$Tln7Zh=<>l
zTCBg|sbEyNX<6Ko@#p!}1<g^Ia#+;Pkc?YfOohXAKXIjqnEmo%?|q0wBaG-BHnIp6
z>(_o9HR+>F@1@RFGs|ED=Ohk^?h?E#hAt7;;%1DMJsY1^tX!==g_1NzOzG%@N_a%)
za3`m$8KNG$ycJ@CRlee-KfKMNSqof(&ud&r^h&8Tu*G)7J*M1nMF88-RO)gGq->`n
z^=BSU<bvkSh=3-J9Q`LKS*1TvwclA#?T+(dO4AaRLp*!bnmGxAE+A^|fLwwH-RdN_
zyg{GVhR$m!q@mUxxnS&WJ9YJ~uX)Y)-J+Y~ZTi*45jw*3{6IZM8+5A2zoI>xZCzwq
zxO$zexKlWD)_;RUyb$Q?^DcO{sCk1d_SAv-80=)12ym=>!&%||3YTn4IeE9K1=WQD
zXpC%|;W#$2o3+~7xGRE|R&zmB5<ILiht^sB<hr({<TT=ZxB)n9^$Iu6o*t3U&$f@P
zT2eG{uHuXTRS0h0cSUL>C@bF*7{LhF*It}b>9NrbWXeJgC5Z8ze)E>^qLCPDM=AQI
z*WEUe!*i{?qcwXpY3M3a(p|i!LPy}q?Yxhvmg=0uGW<-xwRI@!4aID$^9kU#zeCGG
z$HO3@oC11Kc0b@bN>;xt+yv|=ep90Ot19tMH$INumfLlC|LvPYo-6H}jc4v*3M<!l
zjgtdOzj78n1{8DDT2D7xrD!<&1m`oDbuZp7+Dwa-odb#F!iyO*j*D?c&uEyYQoUjs
zLW=g#2%}bZj*#V(u4_9`_Mn$x3in1V(eJiV(r!`cKW!#CN_a&?lChb4b2+Xn?tqB^
zxy=vOr|#A~YM(n^CO2}abFLP>8Xi&QELh>Rb>q({?T-}u@Ukx{GePgfC&D2g6$W3V
zOH4MqxZ{hX^z!eujmJIx?2|rs#RELx8G0_%{3w|mxJMJL?~DXS1UgLfbvlIaOU%+z
z)z|efZMWI#6>_69<_V7y)?YumxaB||;V9i|#~rXuT(awJgeSl2h263+C>*mgcs3Ys
zrSd)j+BvrmH;;Oa13yt@6TZZ;ixXPnOx=PkoetcFdb;167d6AA2j<bZ0*P4W0USjW
zbDgnrZocrjw#%$Bn=my>`O>>FBd~|2yc)$K+@FLRn<)(Fb2o%;2jC0Ey1>iu{5{eG
zg^O_{Kyr1Z6K>U0=rGvJWEntAV3zdp!)Ga(RZx2PeiU~8@Z2(xHkcNsizYMZuXx-1
zWQ8^3Hk3EcsuOy932)qHM(Dh<)LXC@(-pM5T1AGYKPxY<*G?B*2ZO$PZ&UZya;6oD
z)Nq2RgN)Ga$4@{^8Wdo?w5o{@R~n+6*t??;V~>utEkKvauOiOYbhaGrefq(NHn#2I
zUBnH&uI8a5dOT2ngb+QIc_iT!9_oKT?q<^u%3|yH5KY+AH1E09K+A`VR^<n%Pm{Pw
zjhAF?zbn`z<w?_DXK7{A_R4}bO%mlC9Com;{VfU$nbA{)*Bz$Z0Wd%~;6#-;a2<Fa
zw6-euWKp*)rc~{@HbN5B2DZ3}Gosr!&u<>TITW^w`J&xvJ{F7G&U1%`WRGgsg9Nbz
zwVFkt!~*#Vh97lBp=O5TY%U-f;Qc8m77jFHRmkVq=Z~qmQG89B!h@Ty=}+5H0@u@}
zz9QUPtyo~kbEJcmZD9~q$?VD>Un(os!d7(H)$5u|L4IFb*0T}vz-#EO#{B1&hfv>7
zhNhP&q(@J~(0lxiqeGLConmfHIK=gclJF2uGf3GX<L)-gY6}zofG_XPhHJw@M++vW
zUt=jipczafH6V9lXu4IDB&&xkZY9^vc|{50=4o}U9qHjW^|b3d_c7Zy#KEthAgUes
zxEbela?!1;<Q0;%`B9KZ%^xv5(ks9^*83sNvKwuUCw{1-t=^-m$9{use!O$Hqt#{5
zQGs{c#NBG_3kfW@(ly5QpFWSebhQg8Z)?Bw6)oj~S90j}-jfVF7`uP^83wlQ{kwpq
zYL%&~%^_EWCU`8?Dp6@ltk_DNYw!NuewqhF@Fwlr*6fUF3a>ma+;1}{*^c5i3btbt
z7z#@%tdqIOUI@yOx8(Urh>x{IGNNLlHgk)X-meMwU;Z6HzSF|_N2lA)zRfskF17eJ
z;2Vp%N~BDkTD+4p?2p&xBPB)DUgy$;qf2+9<fS}^k5<Z!wzfY<R0s)8+kEpk+QIUj
zSx!;^-jX=8Z)7*AA@7GT+FEM^0_tqbZZ5u%`dXgnuJ?;_HXhe=C=zkohj?h~EI$W!
z6+$rxep<xAegtW2QMwqB$x1T&s|(*eSX0n{B#}}+X#>Vtq#Qv}tInKFSJtMIsjyv|
z!PUNT*9oGh3N)&-`5eEtHKW{Ga{sCy1hz{k-_~%?$DHwGh}R!%H9=FAKrhgAe)@q?
zVb8lVaTN&`^C5e@y=I(s`?v?AoI<7dhO72{TmBrze?4dW%IbJDIvw(M0B-U3a9x3H
zw`Q|v>EH&3!%)3pLp}vh?o8)4pzO7iX~`NF*oSnu8A=$x2^-o4!0FFZPuOAn4!nR;
zKUh1XZ%cC&`ZnNTU$VyDxI((#S|yX_(`i}ef>|glc(3i<`-)d7gX><@UYBgY64Syj
zdZEt#%Dwj2A}*8t$LRkso%;V9bqy@#lIH?s?B2}aOW@$+QB|CYm_4n4({gAQ%r8Nf
zoit=eF(mNy|MA!H@9mV3yojld2NWv*(;1d0A#cQ6^BRsVef|)6k)#fVPd28xGQOPN
z_LsNXs{JLn@T=LXYe-{zmQoN<L?qj6E837mJVQ$HJA<qiX5SX0may)7c`X8I1mxau
z5S(BP;q9Q_lb>cJBU=~_>-w`VNJyuBJ8~O1o+B$;E-Vgkp(OL$@*Ytx=DI@fTk`sl
zFnIIDz)|2%z95x3H@p^sU>w5205d+A%fgA7vKTcnRMbU`CVb2~_SV{Xx-5>1PfO8!
zW=V^|9ae>ZGM=Co(7~GhJymckvG@Wu^&;tABjLW|wawL^+d4bTpoeG$(&AUiIQ8W_
z-?cKsDgZ<g$k8|PRAIj|w^l<1M{6d|<H-x4^1Qcvr&q}!P0RSPAVhdf;p?;uXS$j;
zyM|&4*K=;~j^UB$FpO`yI%tdjS?{uGao|l=6eml~3^{5<E<o-?_$IsUNYn#Ct||AD
zrGychBTgWhS4)E@qWsRMk#=Ajm5aOp1-{DLxEx5Bim${aa)8Yjkr56bBIWF@I4L(;
zR+?)+x7<hd5CcqINq)QTRW0ch?tmo`SSgBVHw5(b@ocZJ$&0c6hY7)jkBE<SDH2Hu
zoKx12wK>9<UJGQqfFKANte0^mFGf&sjJ`6GBtFV;cHV@o`%g7~-q5Z*UwvoTY4Jf7
z2LPb1e<ZJCqzqNRDTWX-E8*PE8(NzstSF7-^!v0G2A}?*j9BW{b$BGaU3V~Be<4Th
zd`EC$3Qv&_@PND{hpW-I%xe#D)0+&EtGeE;v3-;`gn+O#)6$Q<*Mn%b=FuVvv#%KV
zTOb7xYl58MPesNLJF(DGXMYgWt|PZM@+(VUCSAo9UszmHa5#fefDD?gTs}WBddM^Q
zFi>H|{ETHjg3Ri=WigBKmlbUwW1sZ=T!nrn^e3zi-qB23cA+9wWcqs?ImSJ@uw@lW
zboq2TP8m%apvgnZnAdhvWYV}`0gd`x;@Hh4e@nS>%Mbl}(Jc#2*rK`KcJg|k?zTmM
zABt}tpVY;f1vGqk*O4)Pf~ZGzmJ!#39*(q1Ff3lAgnPYSuRk(zPB2D+7uHul5jL>d
z3UIOl_yYg3WSK5k#I@fl(W++M;BnBiOiCo3pySSi1&^Jw-}e^HjKTS;b_pgJkgHmv
zjtE}(T9j7)DG}?~?vnf<Y4YLXcwVeYzxlm1Qz$BEBxb8d->Zdyzh>MQvhR2xyRKSY
zj*rcd6FVi0F|LMT>86F~RLnQhPXMx5rH>ov$t__ZdPi0wjk{jWNc;R0H^}@+7YRKA
zARK5UCd(vSp}ieS{GVSM(?*kOcFCOHzTuM!DuUoCoazkj7E2=n@8=AK3mP_ftwm&%
zDk|10rX!_8(iCkSpUW^NrwSQu`nUh|W6MtUsP=PqQ04I=l-+helf0nwYI*ZwWEgL%
zxy0mcLbYv0_QemRJHi=aJM)4~5~2FArLeZ};Q-;2gmrzA6{XKJ7|`w9fACYFmfHC1
zI=+C@^YmWb6T+ZRwsJNb@{WlrC*3cQ#(&N#08)gEV~jv1>*D39PX_$#cTg3DL1#yA
zJtB6$-&&hv%Kg)noh`Kc^w9|RyU1+LyIL9OpZT4|FG~lt8f}G_+iOW?p-J6v6Ix)9
zxX)yrWv>47pLtNwr<pM@F|^+A@-K~do7PG7H7P<$dB(h8{@d}I#W&aA;e2?nscZ9a
z#=+I~2RpCA;r`2oB*wFZ)jEW1vJ2aQ3*9h(U2TFy?_ExKh#%|N_&7oU=q>LuS@$Qe
zeXZhgOKwRyY!Zu5mt84w^L_Iz63=aZZ3`msF;L4_a`Z$0ex2wgM(_#1#TM6;T<_dJ
ziF5;$lKqmnzcLlceLqAU%ni%-ep328q-f_B>4<~l6+Fqd4bohyIVuSQZN}Hk^$fj+
zbZ!jE2OsA913QnMar)#lx-mI&Gcwg2bW16oUT&^oHQ7dZ|E^M1OmT^!2S*l0r40GH
zr0`1rQhC2w5vhM;<FKQzgFsD<Vi4=WIXo%F91OeC!OT1^xNI`D7Pf>RS8`lyA|Mox
z_`Ll}Pu9LBGhloJ-@|xTeKN)LS}8A=!Vj3(0mI!9R0%B5jZOVdVntE|uI>*8F8<B@
z(UfYtPd59G1aE9RGlihs<4?P{d}DHQRXW%ZKogPBRJ3q}LMO-=eFcAa>=zMRJJ;gm
ze16Y7t{s(pt@RoghM$<oL+J@g9sACNM^Jzw?qh?)4J~hzV(Zo!yx6yaLptn{@vJKj
z@?`?U^}YGjG=6)js>f{pQX|nQ2mDbM#(0;6fU`NR2`}+|De3N)PaZ;!9GY@41I{M>
zXO0`CsLT}=8Q-so@1s&(k;{6(<AK2St7%J6^$hH~fss+-;Xd-<<`-N{%(zuTZLNKf
zSge?m$0-ME<-W~p<9IeH&x8letbEpe(diRg1^1R8W;j|a>e(~w8mABG56{3vCD~&3
z%^r|z&?vAtsiC1GV$|M&)Hl=^w^!3*DzNFNJ}t@J-(T56@3oZOpI@Z2T6-*8SUC=@
zh~+{r5+1ioYh}e7k_bja^-B|lefu>7nXJA_l&DkJ-k4Y`3DrII_h^knzf7jU9c%(x
zNzdN*B;5Jb(cl#t8e@$`5(w1StlI|NKUEha78?Xai{qkVn}b3we@;C0zUg2_|9H%C
za7UBhl?)Y`r|~;>u+Vah3l$MTL8qnjF&KHi_AWo&lW$uNWX1J6AS#w-jJ1}XSy+Kg
YrmUnmE@YW2)AsMm1-<jR=PZK%0|Q?C{Qv*}
new file mode 100644
index 0000000000000000000000000000000000000000..4ea78c63c5b7a12557daa52c7ed06e0723ff4613
GIT binary patch
literal 5332
zc%0Q(`9D<q|35Rsj5vc(&e%p|=|dSKA+9AtDNDD|A~TGoQpqmM%$N*i5G}U4lzUYu
zOPeBQ3=JXN$gNwUq{YP`8O+T29No|TJih<I_xqh6=6&YOdB2wD>-BuSUhi|(+tUp%
zuOSZr0DgzN%N_tg=_1z|a%kk+CRf!GS!BYTb~^z;T~6|{&jsYSZm|2F-2iaf000;)
z09b^P^)mp(k^tZ<1pu}d0D$_*f?Guc0H7AQ!^LTD!j+(=s8JcdF(g~g!0O&8L+dj9
z85bWkFFH2T)HrFQSPe~0=6Xk<&e7V>>=!L>0VmCeWQTGD%<=ayt~_JtIe_dqZxgyM
zt7A)MUS1vwWNuDloGbHiY9FZ_3F3h6dXVe7Th34`V^ey&vG_UnylX7Bl2t2OU8T^k
zb?%Fs-WBG$^gbJnfz66XGoeJs+)3;eyt1Qd;qM!c|I8fg4FpT=$xV`O;U_bUsy;?R
z0b^@|!I@wzR52F%{2Dq~+G6nr?h%USVR}haN8B^S8NMbUqkI|s{>7Fb7mdx{4Vq1n
zlEu%sZ9UxU0-+!N;(aKUoEaEGNfrnfaC|o`J82aRZ%pXgPWQ`A^Kn#HKJv_~Dag%D
zaPJO2JPkmdF<?DO;p>tMMq62QqQjFgQWzB+4IZG;#0vRKf>z-`4l~J;-|`dOLKjJD
zq-*#!VQLL@1VWx-rWSngE*0l{iUG9d^QM|84fMH%+}>P5wbcBgv3V^y%9N(u)FGTR
z;^XeabTZ_yT^uG7r&A|1*-E{H!qT6|lJ&U!;El@c>&LZkPii2sdW^tcORM!Og;JAK
zySNKyuX$f!mdwE2!+#0<=~AjlI1iT^l|s#u(3>iu?jy7YVfN@#FE%|;_i^)^Vzd?0
z%R=cDH{Ne4@6q+8_O{09)z<MF{D)eT7RxDWpj@AMEs)=#U_shWLV`{0qzuz7NF)hO
zs7zB14Qr5QeNlT6f1Eu`gyH4+Y~}=xf6EV4Z-6+Dpf~M=6Hh`ZjACy2WlU#qvc@CO
z-DXrWxXN*l`$OfBT}Kd5u3;I3RfXjYx%~3X&HzV1+0ma2$wi(b7e=z6cmm;mA>3dg
zE?Jy_7ZyOLWNvj^f>c1KU|)<<mDf^4!gRY&&0B{tVIIX7F`Z#IY|pRhIIx%hN-1ZH
z$sYq~!h)g|Pj;V{#yZZyW#!#&yN7&r6Oa3?Ipi{=+Wv<RNxlOsw8MT<89@KgtFFM0
z-z0@!SA%rukMFf4Ymzjnmm4lvf{9lAu4%9$4IUCxGs7r*M@43O&x8^Sf?`Sv>SAMC
z_D-hd>#pd4-rksPvyifT$v*T%gOSmn#M1Cfch8KQyQ|LFBe1?2#2n)_;xwnUZu-SW
zG~Fj&Y#g{+G8(Nj6wit|()e&)?>U54j%$F<V6g4uCS5>I*Ob61xG=ix^}U7zGb0q^
z`b48AJ=qQ_yILR-Bux$z^*rUGb@s?q1jI?<YV<&i{pyi-*Iak;N|K!BOV}O?hsM5o
zdK*-H==ZeB$WF@xMh4ZJZf6o#Xz|+~yF(ya3+#@EoZgzmW9y<pPB+L20(Z4`b5!1N
z!U_xRY#@Jv^)IAa$ryz~si;?yLs9S*5yNF@ml4D3#roI#6N0_)nCeS%D8IP9zrRW>
zr$Cs5x9M;2d?f%a=Yb6lqmG2pMjG)!urG}Q_v$tlIwhbn9$hdzPcN(?-wkJK1pKu?
zfE>JsBs8?;4MU3R>isTVxAAXWw2=Hh3fvBHr|DqibpK*$!LWr;J6JT<Ds=v3l(h--
zB9-km4W*_mc6B`Ki0Bb{u$Uh;S$#h2jKCHPapJ0eG_eAX2`0~yo|MJ$maA0X1-Nns
zvc9TkX<P&vsb;;g&MqU`B(Y=v1I0h^&L{L*mnq6X#6L^Ucb+S19}vnqUudZJBl(HV
z<mBa6;RjXBax!~*2JB6P{F}*Qdr<~+ahb0Fp!A4o_b}nika<(n()9FD1_+lCIBpwp
ziLr+D%xzoKKYKV3pf=E>&$n!6k+0+005XHET&24w%Ga_ZczNf8*l-hXr`;~U&KH9t
zhI+HV_aZrpRsOq#jeQs{ZAq2FqHJmxogHloZt8A9H$Z46`3eX_P+W5GJHhNye=nV=
zLna*x5uGZSI-!Fgm<kMO80-B_UI)hQ=50Fc3KOtq*t{uBO23d!wKw6nw1B%tW;nx#
zTBJz9k>oHx;+;!Ooac}4tR~8qQ%D#$H#hm+NH#{K)GFl?zUq(wlbeCVPEX8rMOYmL
z6yC6&L?WAuVZLx#lMg=x7uAjLrLNRGkmM)0Adh6ipDuIz^d1JFm#yHx{~E<3cMVuq
z52#vsPeHQIT4FanHxwF>>HA!yg_NE?#O=OttR~_C8>w-w7Jne+e6tLI+FZ;-`c2t7
zK(4GG+#>Ia!Xv(Aht?uch06ix@Xf4jghS3qDJdsJsBzF5Xa=CsL-{`@k`ziZtT>r0
z7T{j5LF9O&kRa!n&~S>ibq>D19@L<vnU8mQlbTN=B3RGUktdW9K7~gPQaBv?`jBmO
zc&URcypXXlHVw}leBc0uyRDdLkEr8a;+=76Y^H}%LPA3+eW<9O?x|nw?j|o*_AeW_
z^1Njc<1)#R#hiNR)7>1H02OVApa@7hhnDro%Gq6-INABa3p2SD4MZ*4na7{Yugn82
zj?g-cbuoyqy3Z(LaWox92T-~?+B&$A`Ana&1uLva)zI4UhXuDETlU@22XqUxgAONV
zCWmdQ*wnH8wesd-9NPe~&FLbqkWg@!WKoNWhWK7swq{w^b)I_urL|i78%O&~9uDJP
zGuLC>e_{H0hwqo0EIvJE$M(HVt*;wDc<87r4_E=-G&p7(T2(5cj=ZN)K8y!ZL_99g
z?HLHYYKNMeqaqWjVTmU@>uqHpJ;qG#It|?82p9*<TVEAEBekEpMUaibAP5*ACAmIr
zG2K<gz&qO?rd(}bf(14DwoJt&0himwML&LPV=EbB_vF57THM;V$pGJ{cdC5QQ+Qfw
zV_^163QGpTqU<J5CShE<IFp;3!DMD7wa?P?d|<BCZb_0j)5+EM^R(dMJNw+&dnalR
z8<iAQSoP%?;B~FU#=R%QAIatZrgmVn{7qRTtlk3@Q*e&)cH@an-t%h+vegyV4G;)H
zn@#RMB0vpJtnV=49NE+K;QY521*Mot|9sS)8Krwne0@o@a&)Andfr=-{O6Sf897FB
znku5xnWqCm@tcu%LnpCVdwXo&Nf2&nqNBcYW-`s2Qa(;dxRj;agU2rBs}A5^clraN
zws^wG&SC!vtIbZ<1sy!s>d>6Hr&xK!OKuqHCEWxzCr6%QRGMMgX6QrJ#O71d5K%jq
zYihEn{YLd?8YNk_dVEjN^UGF8($hQUW+TCSRsE<}odt#9+1T?e_j$FgC)K=H5}#3$
zDZbK0hs94jySdK<JwjsPEotJTT62=zsVJeldEI{hR2oIp1$0N)U8lb@cS#>sS=-!_
zIKgMe&LQM#!yqXz0zUm7_Ag}cvsG8Xn3(WyoOH~)=}jU2Rr>3%SL*+jarJGIcgc*v
z7P|$t*3jFlTKA(!yxl8RD*mbV`ASW6N2rV`;)z}{2ZxBhuGlzFPxf#NlqwDp33T-r
zOPQlpzc#J49ikJS&_V95g)a)>UyHm7NA;aAPRH(;`LpEVTTREXl>yNX$!cadrMg8O
zbvrB=HBJg;n>jEZWsNGZniW}(tuOp~kDVq~?Mo04g*OF5O5mY4EikEe#(aH7>A|M2
zyoG5xw(sK#zgHpPaLEwy&zBAk?<_3Hk+ZcHVo8^9!Ycghge`_;&AK*K^Tk8yk&Qhn
z`?Ofr>ud`4zRvyz>(pjy$GOLCqUp|eDf)L*^rNN{Vp0>mQ3y`8;M2u0v~hf$IVn1d
zBo^T-o2AT&Di|~z=bFxYZvT!+ctGH!N~oe4mXCMg>YI%0YsO#Nt{5!9l4S?)906ve
z%J}B}%jiTjaGZ2L-$1;6|L)2~nr*1)k|M$)5`mK&J26cx-CqPXFb360r77^L%3D&#
zL{%^7i=BQ&(0SG=M#XZat>kyhxnRVVh&K`3P+E0wNZfda?ZO+PvOrZvC_B5Cpd|>F
zyR#wUC~8S*N~z_G3}Ss@BI!=xU8E&Z!a^wHqd}tYtWl+gO+hq944)IzoV7}<yjFrc
zuutiT9-8;C6m)1NXJ*08l0vsL>nz8_O_z3_cz&*%E4FDsy&QZP9?k18unM(IuVxpn
z&y2lJsFL#)C?B!hWJZbVzxUx3*yc+9ra~Zp!y%3Vh+{`yl-8K-FCsJ~CPEOwiSQTE
zKW#NfN~)cc1`N=3{!o(%A$8Qd7)Ba=U)sp3CRYIq!|{Q0!M(lyN1DQ5OuYK`r6iPt
zF7(m=t`={fdYh4M5GXjRJ>y$`tL=mS*r9U|DivOshi_3Cuod~;M5qSPNI5lc>99F6
z0GrQ7k&-3nZZ<<)!dcC>IJqR;Q6ia@p}g)V^Rl#>7Ra7XIe#%o99hD=bj@@${Lf??
zKO<Sg3f{i6)H_w&V*Afu){9@}eS+#$tqf8H1GXJ=kR#A<%bGDiu{8g|3TKP4wZidB
zTfpIF{Yo>+)O)J+{fr(vbYW-nEsvdt-_9|La833zMAMQdr`yZ8{I;HU;mpB?iFv7k
zl2t?_VXWLKEYMr=bCIE3Xarfy`DoRpZ4;4SerqFqLjfq4X(z>;X$9syzBZ+!gNMD-
zOnGAJzGYdU93a;nFin8YoUm7~ob;xRWZ>6tQxl83gx`O{w2ai0f`?kc(WwHz+ljNE
z796%Nr|os@PFvss?y+F{k>UgU2nT{MsTlcaBMmd)7)g=c)zV@gLZyyieW_f|{G9r|
zNnBR|_u1FybG;zg%HE@M(qXo)wmDdoM9h=umTMCo$eBAx(RGrPWfL>eK-+I?GjiU>
z*ZWo6a1&ze^w&l@RmSwpn2jQlDwcaKpCZ1~UYs*})mSg(%q^9wMVGJIWBOVvCl!uk
z!I6oQz$Xd$ikDYOrX+K5mPR;Mrkp~8%A(o1&9#E|g<&)Qpt(BueYJhp(DTLlt=zZ4
z`g|kG%e47=Da&HLx)pzDc-S5udmol*x{xH|#e84yw{_*Th<?v2#@i}tStEL4Zu6wD
zwbEa4lBIUx7k;4cI1DorWq)^(;Jz|YB{^CS(3T#0KiO%fE4MeW^!1`YQ992Vopy*E
zl=bBUzt5G<yeJ5yLsCh|$P%A&eJ1AZu8&Cz4#peg`(Bu>lpYL#&TJ-d2H!8|+R~-K
zpKO@mRD@00fK^q+D3~}WzE3fHx*XVIZkO6BR4Q!r-j{}*BoGSsLyje_Qj*pqV?oc%
z^z7h`mFWoFwqkM*g=ifmI&(rQN?4k7Gc=?$Q<r)fc6L0O$_j`;IQ#^49|N;~D?84o
z%gKUe&QXxHKhtvEi(dx~lRQmU&8BFcIY@Hj8Lu?_>kA}_5wG*c)Vr$|pFS^44?}fc
zf!FpO^H)Rdt0hS!^BEtd7Ebn4(@)v&xA@8r#7`h?LT#l@FwTZrsD{|sbei}bMjg`&
z?a(sU4?VVejbqd+I<)L?1{Yy3{Wu<KvE^bYm7sQG0Xcjzut*uEywuy7d1{CC1~7AQ
zWyn)q8S;1z|6ga#|4otD@uln6WTWK&g?+t>wR%@kpLw4rg#Mum@}a;|31;$)lZ=+O
zHtzK*XY7xy`fCq8Nr)=DN;2jm96<ItuUffJ{2zMOW3(|@t37hidsf~+9exzK?ci|o
zJqZgprnVPYrj$F$pty$bnHU`8inEbJxjUi|0eDw3R1~t<@y+t%-}*ZN|4%P^Hc{%?
zy0q2R5eG1*mrh%w{-fZr!LhRKTpHe~@bWg=mk%oJehto{AO3P^j-|Bh%k;ik=xVe&
zACbH12TX`~Vf_{9qb#bj=yc|P3}xl*znr@(@Mpyzpyh$sCR4#{gK|qKGEm9qzvAk(
z=r^*Yi4pg(`bvLeK<L{T;vBVFhFWoQ>!&(Ix82IaSt&cP-%Pve#;cs(=leK<D|$6J
zG!nUMHt)-^XFp;@%I9^McDYs5Y{319qdS&G-M9St=+ZSbVndAOPgK(5VjTkKPKA+*
zBU&Co0%wycTW*`^h9dkEmv3t4d>nOFq}%^DBMz`uW6Q5*`#5g-q4l3=pa&`0+1Z#$
t4w4#dBjk+eio<0v<5u1z^49_~5YRY;MQiInGXap#j_sZ<ceYW|{taM;83+IX
new file mode 100644
index 0000000000000000000000000000000000000000..06de4cf8fff9b8a8e74679802bf396baebdb110d
GIT binary patch
literal 13008
zc${UpbzGD07e720j2bwR7$sl;l7k^32t!mrBovgE(cRq}-~bgx=>{c~?hqJ*(cRrG
zNO%8GKi}v1y`E=(?B4Fzxz2T+bKWPecZjO893?p;IRF5lRFHrC5&$4zzxo|c3cUJ0
zDAS+6dJvh(D9Hc-g&)07UxZ)%XETz2sRRIc-UR?q0RX`9<<)Zq0C0f;0INs<;6XG1
zKyMfQBX$4)00LB>t3UDe@#z{^>+fn^KE3GgZW`=uq2{$GOW5x1uev<nUz!_tjcy@z
zUu^I14f-)yURp5N**o0d7E`r&adFx<(7{lDA}HrLH#ywdijOTHHx8`m?d^T^=+V?@
z|7cg^;Obd=<MQ|N=C=OvkD>1sG{TMD@<S53&Mp?lI@*%zHkvzzUwdRLnq@pSi%Tz`
z-?_M4Tb>P0YaZ%uYOJds=&h5`h#c%`@cY(N-7+%XflY1M({`%r8z_eg`{<$yL4*XI
zgE$e5pr80A&zN$!08b#w?Usn6Wk}ulP;Y4ANc-$XM`wF@+E8mlO<>~B@%;;rfJj_b
zX?s(hq++mBK&4lF_YIymcZF3JHZRH>=UYZA)vQZ+9{C#u=Tr<`=vt>g)=Tg2Y143v
zova=2>A*+Tk2Ux76!+Ck%&!dfc34D|3rcIpRcytk7r!!y@9Ayu4aG<0FS&ZZ8=mi3
zY+LVWt^HazIo8`GCo9#|I~tTWd;eMNi=4}?^%YWfCqkvlmcF)u@hMzK_d~T*L+?8H
z<b^|M{->O-o}Tuxq0ZU<w*JA<^R<hd;q!~5E$qS>Dbs7au)2|sK3RjHr>`veQTxq(
z%{_g!BVF}TMLkbH4dQX_6XRozxQgD+(e}N|?zYB@!=ui@0ci=*&4Y{g-u8N-YXp)J
zjm^2OGfSip0V!mJ=BpP<Muk5|HWnJDDrf6EhC4?4b6*+Rly>ZQ3{9#iKJ9I*?H(QS
z3UIs<q~}0PwYLoo;>JhtZ4G5GRrKIsYyVj5{Ps4HL95%hHRlv;XJ>hBYx78d7k;Fx
zvAJ35nf}0VL+wBZ?AfQ$zC~51w3gNm|Gaj71N_0x#$bQ5)5l)F&~KwXC5@wlVWrcz
z5zeE{`2KqAbDP-w?iFoxN>6{o9VVs0!JdJRy6SeEfvy(qbuyHH&|+udaBr26^pgWz
zkAs7KPt#Ca%j9VH_-O4)Z*yC3M{|E44rw1D!KdpGo)eU}o0|T;q^4adxof;TeW1H_
zpr_gSMBp<3AfTe~SVrAF!SJ`xNg~YQU8P0xP1&tEIY)5OuQRaXyna(D%zd>hX1-PR
zIMkr_Hl#~iN+4*K35c(@0)zXpg7TuAf-rlZdBc{tCX_z|*1={UBm;uQqY0kk8+sRN
z(Mmxvo3#mO1DEP~-^<XCr<EvI2R&7z8BaWp%|9@E457I|NeX8!m&7tC;~QT5YLVRr
zgKb{fd;5uVv;3x)=4{lEs=GC(yPS?0xRae^2By}jQOO_axlqw6;~u%m28cEKfQNzc
zI6$J9(|TU-bej?31zI+Fq0}yfxzr-zri^@;^`my3#LsL$evWzzGnw1KZN)y{MZlgL
z(P<XHsPnkkckx@g>G88##l+WUKa<sA_d^<#Dxxcpt9kj;Nv}Q3_O^!W$^HZ}WS;)`
z-0WsPuQ90^lFJymWiV0)i{9qK!!b!4t-j3T%N#9|;g9^=Z`&|37Dc1xrnkIzCO)09
zL5qokM;Vst?S+8k7!-4%hG9N5Lzo~|M+t2WS*NT+vUTDv!U;YwK!x)IELxWl%yl^2
zHZTyckpw3+C|JdSFk6wx7F@v>JZs?e2D*poT$FIo-vaU*BhKdLxM2(-9-uH@6hd@*
zBmzZlPjHAPy_l`*puFtPA?Gnfj`&H<*!qlF^w%x|2pYIfZJHbFsr@i_!7fTeatsH;
z%yerb$JSMu`{|X}FQG)@x=|=Xf)!_15Gc`W8v4!}3QdDH;FfCrHQ{$j$kD$mm)V6$
zJCrbw*v3Zy3Pjv?-gM^NV)8^%FiGNG(LuD#K24xf7b;-=9zKE<c@4$hQ4B^1+|)YO
zrir~qg|gBHS02)G!jG)cI5>yd>k~L?9~hwOZq#Z6f?#6lsf6)Qpj^pfteO!y&o#Gi
zJJl~qn`tDuS7#J#<~iaLL)n|2UD+{m_oBS#wpd1X&ewptGh=}4jEgF>5G<|B6uI&p
zU;qo0Xi7luN<f5AUx@D9Lm(Ukph6`BIClJPaZ=$5WWleR881-$Z3yXrUB@9AQMcGS
z@DY+Z;oQRI=}hFHV3|HHg5y|s=U8JSU#lN=#L@G+yLwvue!f)_+&_a2GO`B7K)T2%
zKpXiJY;Hx<v2m1iMdI~1NEx^Ft0oM<+|mNjU-*6&(m}#)AT|T|V9J6ah17C1e=#^&
z^#S)*(%}LN=du|Q0Kq8<?}XXOAkT34(k>MG1*&Xg)MJS3(P<28gE2vQX-`#zU}DTL
z>0etc%&_T2Rw0x>srf(&?*bbk@ikROIx)uPz!Wr)oRMt+L=1K;5FQe>ePHE11pQwA
zJ^%aW2eM%7H%C*g2pmtDzI83Cj;0poJF8)a33^oB!{$Fm{Ib?9TU6K`B?D9r{$x@Y
zX7GZU3t5l4^=K2-Lmm@>;7vo$9o20Ep@?kRRGGb_BZ44cKlJrxblF4eY*HG>v1VMs
ztvO4byi>XD`+pENwSTxd>~>i~t;GQKg>MOZ8?Nvqr@JvEyhF%1%K{Vp2}Mwa#|loE
z;}9e%&o#u5h~#GiS=B;eP7`HvAn;NS(}cZM5GNq1?_QLFwx=6-ujGO-_oizZTOg^A
z_ZB_nHwo6JBaWP2x_d@PT36^Tw@4L6beDdz{U^B1O{QmUDNS-e9?_yoTMNm-Tg7V_
z_!&s!zg;}4ltWy&Al=_gZ?xJEjKvweoVpW64I^`w?jZq#=LFD@m<|*fQ!p_DG>N5R
zu00JXLa}lU1d8R6$~*W3ogz0SB!cu8-ojiniTkpNzFx1Tp`og(omDGqd!H8t6&7`d
z0g74iP8h2to26lBo(y3y0X0Ge#lDwDK)MVFP24r^lEZug-^1NXFDwjB{hS&+O93(6
zHWmaJFa%o@)@5*{B#_}5FiMxvFy7IUh5j!pm(u4X#63bOpWDj_&UvaeV`O63qhyj~
z-rU91#j+y>ARrO|uw^YzD1aVc|AT^o&Qu`hK|KVx;ITf{n1bJ8)$FGMII!UNvEpDS
zD3xFdteW4evw+=B_GU}&2v9zZfG7aXpu}0<-1qWm_iV84FitUGGg2?)$VYWB1x3Jy
zg4QxBU})9%XyJQwF!?ArOkGHLeKPm@w2P#sy>i=WDR>PiLZoRU0eG%>=<5SP!bg`D
z@v8f1nHdzG1e0aKRL{uxnyli!q{V6H1HPB4za=<f#AqHd)z^SW_T+>a$$3S2MQsOd
zt{_!4(g@!RxIa7IRP`j}4f&T%2_t)gm~j=MGeck|I|#G<rAN2{2Y4paGeDRz=~}s-
zMOf;9I=;aH>KZ|)=nn_dWDH@JWguMN9Dp%jGE9_o-1{Vb*>8oVSkTd^cJDfh-6_*?
zu9h|z`)sr0K>LH@m4Qvw7h_`pVQ|Q7FYPaK%nfiJF?e!O!u7Yg;f&J|@;jH2HD6_&
zJtU?Rb$3z(jk;ki`r2p95-tw@aLSFb=!dclZM;g1x?7NK5RDfEVZ=AJ1T-Hea5S7H
z5<n4P93YE?_}U#5>IVrm0xSYnnnJVy$WoNR@hF0l0XK{3KCBQ%2m^2D2PjFmvVqCj
zK&mXev@!2e2#5kx27urXHf+9w{A@%&8z^EJ(O<U!FNrgP*Tjcq7((k#Ry-iaJpke!
zVI)8h09;<E55K|ib%x*$>D%@LX|tYD-*+zS*e2k$GSBjA6MHjN6L-hq$UiaFALl(S
zO-#+N_-0#wIPLWi<&m56<I(&BJXz|R&SQ~$gAvuw+M`kuE(gBNUe6-Id|!X9N1nZK
zWWgrf)bWLTgEG1{yYDuFZS!^(&#-qeyH$0c!tS$Mr8oe&sl{=;$SEX%mR);zL+I#D
zKjB?w5LA<%2m`)GgMx4`RkD!Q<ydg<;0ST6P#ER5uj$qU>#EK*9#Onc<LSE@8loJ>
znzUqFCs5fF{#AXV43KS^zP>){J<l)MNV!WP9bn-mD3pl+EGo=MHTon62`Gi3-g4mW
zhNg3Ho<Pk_QbHY1l8o(~S0}bVGwoM7K+>3)_?oxUluH}#1?IE}071X1Kmof8q59Ly
zB`46*f(l}Z5^0I$=i6C29ZTLF_!9X{l*3Kl&N^SW>R`jWJUe99*BX3s_HOn8&)QSL
z&I;%7<#^iZ*2L@NB}gP`0=@uqmFdhW07Dc}Sk#Ul8>qfh8;rdggBk!7DK1y<SBwxu
zVVunV=yxM;c#r_C?IjqLKrL)tLjYupQF{04UHr>zC@;z+X}2tMJZ)5f5V&%ks|sLM
zN8i?m1DTJcwjI>E`Y~LL5dh_71L_pMvDbejph0{E-&1*+<X+$jI6ny~W`ZKrplKN_
z54ILG=hJTg;5o;_-Gi#lDw<&$FTzq2{zU#zx9^bOXl2|XER{_Cv*1>)w3xy9#wA$P
zPjaO<W@I{B@2i&Mx2mAjg=bA4-p)DM!qm$N!`DN31RCi*VL6asKaae<wuVuhZmp=9
z3#N$~6Jn6<js=WE*#J4c4F1DHFa)&%L~^j>8Bla3Z^e4s00}Tu{bHAAgJ~ZY9m0=B
zP3T`=gmBTK`yoI}?ne=_DN)3D7cwL_VU(<^=kh0Q*3vQwq8tnmRW|@BoC}*|m$2t1
z9E~l)8|}JXNoBBOOsLedH6O)7qZawK?|HU(?M4T@GEjsj)hd8U*)p^ZFu4dkdXyr@
z_vq+I$^%A23SfG7S#FM{?={)#HK~~5>zcV<7xsduXWc;-ZNLXC5Hjv*9r|VJo-)K2
z#@CSYtt&-Ks9Z`LiAgc#y9Ps{_FHMWz;BouAPuB};4nZOaiCNRfUwNV1(nDQ!Wd(g
zqW`8f9=tyTh$A&#h7SM)g;DM<9_tL&4At02gro`YpokylA_aN7hDT(9Zd1~P!%D-E
z`hfl(7fhS%a%}E88-epxM1x)ftW5r-vs$kr+XNWQhUBIua;1hsPaN~Ase4Ovw@gX>
z_)0ZEx>N-5V&Fgh_S|Ur$1-^C1WkMcb<Cqz6ilGWMhol@YbFXMR%=IFtl&R?WO$(A
zEc|%t%`m`Kli5x)kK$qdR)X40rO~t2$naghs$|8eoBB027dl9SV{gt8S&L$X7^V6w
zz{59wi8IQ@LVpnCvdVy1Z-A$~A?8X46ka^>0U>3kh}(==iP*x91+E4y9a(NSoGb_@
zO!Vwy3OQ?>A?_aO%UX6zp~qIFyrw=hU>TcRkG)8Bqlxq1(hOc@$08(b$&Kvw)L3b`
zmCk{jX}*1C<S>PwBdd0*W(7GLDh7&pICP#Otd7H-OyZMDKcWqSvU@0zN9olDNHMA9
z0E7Yp1WP<4X%-6zAjLa013*f0$VWF~@hNcW!g%(Q2zH0@kilApXUTTJvS27w(<~hg
z<oaSjU$D4Pu5kMEfYQd!#!l6X6e`(d21QKfd1BIWJ7&Kc(`NubQ|t{GVfIid7)&;m
z37^QTY9dXk9v<?GP)(p<=qE*1C8AVwu$kL@i;eI*YW8};U1z-;!3-aTG~v}C;_G2a
z4JaA}&iPIk8}{|YQ|6c{tSm6N&LsDna<ulU2nJJ({>^jvHovAhEd4tvZ|GGETKqgT
zWaN$ea@-$Ci0pxRA5j`_n3`|K>7N`fT5}*JI*{*w&aLr)t;&zo^<DtzSlP*S8kTjB
zw<ZZ<CPz3Aqy>}Jx**+<FTZ9#XB9AxJR$;JFF2dMx5_^!?)rgbBz9@Ec{gk}^-v0A
zhuqi&m1V5OL)jf_TkYVaLJ`|&wgQN*h#+eWifvyUGNG&MRBb9)!3yk1z7MW8i$I4(
zquDP^y<bWCd3St)4o@n&;@fi`J;nG=bvsGz`bxFo!U!A6f8yp$q}zT%QSN<p{A>w(
zk3oHHWdzr&^xVdE2lH$xeLYr6=-nD=y;5n5?>NotPfiw$WG~DWJu$oTz;=EV(je#9
z1H;mlo}iQ?k#I~Nr)d_?zY1uw+!`CtSDSvXRJ>Cuy<9se2;vE_0F!`GHcyZ{Wmej4
z57u#omO2=vR~l5CW=Jv9#;qs=0X!`WNc9`b%jZA}%bo(pXJ){*H`K+gb_#oa&@BWx
zkPG=WiXfm#Q8WD_0H99!-HQwy7qkOT5n=?-q6xqWcV__pJ7^QJ2u$|#SRh#vzdarB
zt{MnaTBo`{m|LZnt&^>D-<A|h(mM!Vr?=DJ0E_9Ry1u^_BOw6ouo9B5$h)kEvY}8u
zr-%z}_UOU9Dm?)y63cbd$wH<WM^wtUwGXWlDbp;6KplrAT-mrRtdp&_O*hGawxC6#
zf$efDt#bY$2J_eh6VDv}+*l+~iu-Mezpp)@O2?PYXvXH2{QDLD?_36e@*teeEmg5c
zW3p_3A6v1PggUZS6DdEb#&03F#%BD<h;Kk4DS2ds^wY0va>-YB@Fr|NHlP9)1f6^E
z*NVelVO0rI(z+T%&kCSIziA75+Vc$Geqq7*WHHg_$zg<uGSctptg3TN@2cRqZ+f-M
z-RN`!pH$tqMLl;S?n})^%S2@To_S@u(PBSec^k;}0dal?Lw3KpNIl~Y0;Z=}?uMPo
zN?@20QXCQuL6|8+drM8Ag^+)IC_>+H;_aS@44M#)<P6Y$M2ecwB%&P{AtZ&0jRcU$
zXHS6)?gXpuusj9;iTD9bBER^FIf7oYSpzAuCyu|kK16JJ-Zd{F8W92fl=CB)zIbYc
z0uUao3k>_{dM&ZTpvpq(&M|N?A=rc(;jin22OPo&KnZO^R^A62926xcf~eKl&~0mQ
z@%-o;n}usf0Og5()aWOf-@}zEwsb*SwRmPi>sfzxb1-8Y=r!mDZW06w%nAUj`4Sap
znkjcnni9WN_3(+2QI#@=$bdEsVjK#J6xZpXLMcFG(1J)w8ITwviT7_ZLJ(*cs4j{E
zv-ilKgu^8!m9!bGD>tOgCzg&J>8~z=lO8(wFy@?vkzRtVRBmRL`wY+sXy60e1i;f}
z5W6z^KA55=kdT`gife2o0r_G!IWDZTp)ZN4wuJ28k!^|Wu~w;;t|egc{E6pV0K*<P
zBH~XMjbvAy$-fWxV41FBY1@BDnl-fm7@P^56;uTX;!;Ecq@V$WBt)rz2VI2aB<2GT
zA((A;0%wW_{~0;R3b=`lT2p(&WQMrxV`-gce5z8xy4PVZcStt4ww=|x{p9swX!Gmj
zx-&ha#mq<&hCey%ULO<_Ou^)@RJO0{DcpVhbV|0dlrL6EZEyj*)e*8%H8WV_m2_#^
zN=zo5@q6mnXt7AIHu@*(X=EZQl)<ZsQ=~ac$i$&y+EDeqZpo+Zc{7Hi3i|~|n6W!|
zD4~FNTwLcNnJ`4`z87~uKla&H3ZrbPx{23;IvePh5i-oPECJ1KMjjE`LGl`b@Bxoz
zr^@1H*d-Hr@{3Xr_<}yT$c-7R5X;6$ARxkhRP7T^;q3FPiQxPOUg+x}p{>0gnr`gO
z36wY6(_dyEM+^c5<O*G(zCxfsz=i?l<tDTM^(~3%Rz27fE^fV-$U+CsOd{iGqTTVE
zXlF~z!WtT>e&@n}yorn*GwI%PRw2Z@0WZ`{5l7ojs^*0m>vz+W?hKb4nWZAGdD#(r
zdCifrO;WKK0YL2y-YMo1z&l(Yt%<i8#)@T1C55D{B=0i`?~#6+C7>d621}XeFwt-+
z8fKUZgrK)ZoIDv+SCW7G;1a+Q$=XDTx~S0HHJWEq(L_T@k~OAfnP|$ibr#x;OpT$E
zYW~kY5~(vd$*c4*{GcsvVzQnQ=O&8I)x+e$&y~q2P%H$h{d-`%QFp}Kc$lNGFNBm)
z<u36zH2lt(nIpzH*ihQoaTW~x{`ng3#+OZ|5g}*w30=*sW9|{JHQpM>E479_$F=f1
z71NTcn>pDZ*gqQF#w%eeKeeHv?DVR9QdvT%Ko4RK_!XcdhBEj&B-bsVzn>B%#p^Z|
zBpIy5HiLD-Svm8~DsZsMxuugmmAp%F?7CFR-&<(J-tx9@0w){HsL4w4wm2mR9MW=m
zd71nf)0FhkYh$CAjq(D1B1bLq2zW_!A^17)9#M;L0#O5e0oPOH?KS*Rv0X#a<O-i?
z4fmwJ=1+vNIEW{os4N1XGhvMxy;2n_RLB0<60k1Vb{4I`C~^|?;RgJMLcKa^>O+X1
zGNDl=!_yQtZh`XOMI{LamFl3YLve2VeemI`O`6@RuLZ}IbHJP#0jF>r6$dbl?;zyU
zg0Tuapfe}T{~pndEhG&t%*W#@2-Jyhpa`MA1<s2TuoFNc&-j24#B=bI!sqXv>-!Hk
z0|&ngZVBrnXF!(o1l@{&(_jRz47Kg8>tEM40b?rU8{Z(Z{tEA9C`SBrJ8=E4_eq2u
z!<uH=3Q*|TOdjA>9l;jS8pc5UI1et!ZXnU6uBjlrE?-KL-7UM1)(_8ekb`jQ`30sQ
zpN|AgsBTbmyps5VYTY>!zkSF1+JN4wjnNV4H&3G=Odb8;z5*D$8cylR$@*^MM#0rY
zhM1RSl6Dg072l>)&j;`vdf<FXhDGy4UxBB($?Ke=(+K2Ji0{n!b?v?k6U574*6++d
z0YASpI}d)!1%)DX(0cH0v2F+mQy!)~Cb{1Vo{CPtU5@291CX*keH}Gj`*x~O=;Eub
zI;962O%6GC5OW@o2-1(JGA{5J0H-*Tk^%_Lg#+yYH$fO881T=CSOFTk8$gTehg@0y
z`OWbMFhE5XKp-5~ZVzy0BqUAgh13(wSdg-zp0=|y1ClUT3QCy&_sWTZ>Yq5{BQby^
zB>_>7xp*M(ud>i6+5f%b$NwiTOG<*uWJduQ`GWpwXY*g|@iPU1`u$@w;K>iix2;oC
zW-dfe|L~Q4dyiLBWk0EO#IW1l6|n0#V<m+`J3`Ik=7ch{J5=P&lZ=OlFTW&d>B;D;
z6=NOaJ0x7V?;qU-0^<`{@B7G6{yo`aSoGaX0&2Ns>%&ROUpr|P%_`8Vi@>?<Nx_;M
z?|A9d^w=tRli@Lz0YO{bp;%|~u|+)|iTQFlE<6er%RKPY@a^MU;y*#w?Uydi%3$h~
zZ>r%n28gzVi6Dr;_EcjKh{Fn`aw%Sw>D|XYKYp_k>9YALyt=&7RKaJpx{rdf7YkBv
zYBBF3Pg|N5%BZVc=VOWo1>D=rOMEFspQA}JC;BGQd39m=9@sDM$lE3TOY?WoUw4s4
z%ci8qH8aG}36^yIeyy1qjbklpF<0E>csQNYxmu=V#_$;W_<2Viw_iYWk^^e`)A2_^
zYz<M#SkK1ju}Z&mX|=VVdwAwesFoabXk({7-7e*CL?E*VJ;P~f;ma|+3^{6nues9r
zZ1TA6;#@b+tUj@T?P}8A)k;;Q_|10s-ne0OEZyYi3fFD6P~M1Uz0^^IVsk%F>s+)A
zoZ1hK-}{&$s+7y}dJLvsQ8_yxiuj9=;I}D#2#kk9Ek)n{-6^|}7+vFL<jzOGe0Tsj
zpg7yzBmnKc!<y=hsrqU5{4uo8wD3&gV|&a>R`-{T!D>%>UTLMoTTN`{r%|(&)aG}G
zSuyMI>5{38sP6B?e_a!7ajh`R&38<A^0egLWcV#m?C(g$foVaQb=atnuB%twi5^A8
zB0~kkbLdn-hf$&NgP`^>1!?U`6+emkEfF7+<X=2P{W{0|3PK4NbLpP!x<w00oz~nQ
zA1wbFU@tEGi9KpI<D~OmFW84|BfT@~{!M94saB67^lZhKHYv>5L~HA3u-TM4L3;`r
zxYmK;w(flsv{x}LzB~GrU1OuKpGieZGj7KFd|`bV+&#K{w)r(~_&d?R&_>BBYBCIP
z)>0cBCR!dE8{Q50khwU<8<Ju>%oF4Y&1-4qpWAxafeSl+nwk}w8j5}uPa7>RZRdAg
z>T;eV;G5XDi~1a|p{dN{IC1G%Y)x#ps^$utII&(0vyN8mgrqnqb%39JC{KvJ?M(5(
z-=w=0(|%D7Ygl-LgqVzU!ak?^d|m8+6V<7A9o#JNOHk6F#bCtO=cQNOg45^EGshd#
z-eUbd%Un#;obNqfmHxbx4jn#rwzJyY6l<<{%%@h!v^l*JBb<``>8RGwAN`fUs=#vJ
z8N*0k{fy(^eqzgQC+r$NLIIm3-BO^QK5Yz7YBqy&-jThpfCCcQV^BcjE$%cdjCrtr
z7Yufa;g#N2!Wk%MS>Bh;mJc|+ff-hzWM;k7F?D=8_?sJFL!G=+re`caa!jgMgY>J{
zPLlhvoDAJC$<0?zag!lVb|NNaqXXrAa)0If{dMi=*+HJl#bb=^mg(XeSc)FXPpW%Q
z9ES^YGI{pFp!aoWY;KCCa;#`7oIF}QtDHf*v-+EQvOP<+<&UGCcb&Wny@NtIm$x6k
z*0c7xZ5Wb@)lQzx4480w%06@yE$9BKFjhhFUxg`P&cfoiEOTMNfDSs4653YjiJ9IL
zIVZb-YhXb^LACp`;|%<+7iR9-P9X;DKy$4Vp#%__kn^62kaN!Um!@1vPIfNG-c4oM
zjyj)|S1KALo-A}4gS|ZTbI(f!{69ClH5aYVft~FraqWNnsym*oo@<?N(qaZ+@z^%r
z&jNBh1+#;7l8yir+w;>5c|va9Rjq8Dsui%CIgGdYaJY3^vSgbQSKl|qyQO~1*PrAq
zhvYk#d}1k&D!8}e;k8i1`|~8wq!uc<X1C>iJ;FYEqLocPL#`F{x5^R8a>)z5SzLC-
zgrpPd%t>#->@R$BUzA}cGnf5EWIrqugKP?ef1ktq`D)R95Fih*i*DXOA^NQkWih#i
zu)I#8K#XnDl8f%?zFxaNrI!Yb)XMrIFx7W@Jc1>3yjH$iG{&}QWtW^>QjzW-bS7@T
zdm)Miq<zdWmDjWRg$=9wj;~vti=xJ4rz~y|f_b>1u3f}Y@?cjmn7Ed~)1CpZ>0_Mr
z!K?YlrkS^L=F!_^<C+4*Ob9Od3FYX<tLx|1&{Yb0L9AWnuhwF78-t_s;J{@X_bA@K
zA#A|4weIL|NmH!(G2`a<ZcR-q?_BTL+1a_c9t1z*93EA!*bvyP?Q2)W`dzf~#Z}oQ
zxXwNMTs+WobSNOr8ZAzpnBy;Vkj{JWfSN+m|95Q%t=Uc((u7)fYw>;HZ)py%Yrept
z4uM39m>8_L=}E`l;)0o022T8W-@Qw%buD6It$=qvT3VXV)a+wbY}jJ@V(aVcSGlhy
z8zLvI`N3yW_c3{!LSQh6{$sP`w9t!SnJimHU_sx{teR6i9J3(~CJ=REVo35=GZN%?
z(o}(+sheu<d2!+swHu#+r=}PQQdg-7l9#Q<^i>^cOe!o}rHy8zZEj9^PU+kDm^MZp
zbGh8q`CYbAmQA~MDd73KpTqW@8BNkpl(t16<X=pnk3_(}<I|I7p@hVc09X85aquQI
zkLGAAfH0U~Ab+wIH!3wuP!hgDxPqe5U3y&dyN||ziyMyYslIp|J3EE1uy_C-W_>0U
zvvX(S`B_KL)_ETjHrJFw`ksr;N0X6*DEMo43LsEpw5C7W_f!hI5c!KUHA`b536Tz9
zBb`~i8Y-^y22EvJXVG{LHyQ!JY@i_!=GyO+^H&5E?WlAJ{?+k8dg8rlO4qf0L3KeW
zpxq_G!u(_8cn!9HT)Fd&1-08MKYl-_b(R83B`t{5#HSodH^$b*=hx4EJp5q;mVlP=
zZD_Z!9ba<Ea>|P1qq#*eMzfyfIuSk$2^qg{yQl$2|Mdr?*UGn~_$b4P_5gZcD|&MY
zb9z!?7|dDH*xnrW$pjf=xwpwZkNFY#_JRrOEn^W(V8%$Echbl<@7uu(pYRJc`1OqT
zMPsDEYYuHa<cg{Lv36i&-Aw;=wM~}Ow;DxS*zqhEo4X{=cun#ET715dcX_cSu?nwe
z-Co#(3r_IAF0xdlcsQ6ZzIR-rEvTC~^D|zC&4dv@{ce~ETG3Tg85h~l?LH^31P98l
zTmwzh`$3^O4jJr&qK`y|FXW%c@atk%>Te)-PVoisvr7gb#u{T}2zn2F<IpwLs>)w`
zPj@tGH_Kh_=-kK@M>9}gu+kzp<aep!A^12?-s_MDYNn@P^REUr9I1w;J%Y;ilKI-K
zPv(J7JJ;@C6O^wpbw3C*u>A3<Z}*#shzYmiNm)qsXQTmA>>ZqPU+KuZE?vIWk|&^J
zawvCp^;vQ?r<(<rk9KQgrthrR!ZXpXrjPxM&xUvwEwRzDW!C3;+dtl;XUn6SI76o`
zRD{cZv{hFuu-B!?=R(;2>#XHLL%uUuePV0X<cg>{?ipPs4kshek>n@*V6fIJ;vn+y
z`&o;JFiHKSql|Y1B`!N${6_ESiYw_oyjYaZ4p!S1P)y#Z<w^Q1x2i9>y1Uf84ZXc;
z@=xyAdrr(uSkAD-x3p?ye=Xfl`t_;53i@%X%EPE}-|NsnnFf~NTV*1#Uk{M}moXzZ
zxdqG=Ja&u^@+X+qJ$1?&8f{*zloqY7)2?a^?7oQbEI!rS_}FwN=T*+sdVb?5)4<Tb
zJ>jKH9gU2>R!De`%%$W-YX<36vvBY+(CayV0)y?oZ;lSX^rp8zZUd!mK2KG$3WA}^
zgZ@C0-;1fc0_WXa^LA7%*`&L|`dmV8?JGI(hHU9E2dFU{y=*sBTba``#M9cu_I3Z`
zEI&|rmo8VQ9Bz`|>bD-@cuDVXHMO5SRVS=9v)Oua|J>~7{2K~mg*Nk_#ge*@Yt#`8
z|0@OlCw$;;muO+;sUdf@ZJ%Zh851e&%%B&qsJH8{2cElfn-7LtB4rr6`MQ#7I2uyo
zcdkW?V{NaCi@IMnka0UFy<9+wF&_2^xs;}jKOY(h3u2#sQ<-pS(q;eq!yWqDj44UU
z3cxMLf3wnij|b3(gG-5HUi{G;@0f3rvZAch+8C0zMYWRicB>06Gy@s>M<%Wm&_lJU
z*qHewr&s$0Swl#%hp&!0A2!W{6NSE97-r_ZTeqYiPZOVZP@yvOYHMA?BzM3h%z^(Q
zr!2@jhfu0IuF2cuq;qez#{|9oTHhVZ#L#Ke8<V%2tv!DHd=1oU=a<Vs&Y;;{46|0M
zuPk3q>+E`jDS!KddXrY-4)id2W8&yC()Bf>%)EYlp7S9KR@AlYhblPtdPau8J%WE7
zb-A4b2D4|C7JIVE@P2t=eL4#pd$WA3g|n?7)g$~g)kS8*VIohT|Dj)dO46PV>^zMW
z*!8nX_py6F#gq;BOk(=t#e@30)4bhB)$DG5zZhu`P4ug^8FiFdfA|$0rZeoH$^REC
zO{yP3@H@F)ObjoN-G}a>f$tfu$@8j@ou^hpe+^2n`Cm?3=pSyqOfKIFy#y<u;b=ZH
z72PFg=1bw*Dw|7%iqAGO=^Ec$Mi^UeS(Tpt7Pm@bak^--G&-)D2UvCTY)>x{FXgnv
zc=~cs{=N8Jx4ot}qvmEWX55UU6SElI-CL;1lklCCViAc<{T4`|$xETtMRXui<}+g$
z(+ufGV(H8nPpVygdUn6rxw}JML6I3IlO^X3KU*A5Y_h{g-K0IbrPw_UPRdj=LfdcQ
zoNQa%QU5M7t*7lTi3jJWeARcfAIzS=Ma5t|{6YqrPsY2K%4XgLtI07)3RD;TJg&Bi
zUtRz9VY^&_ID3jt(q-TQzo?h;lYP`%(g&z+7r>RO>^;{FuiI9OHBOCQpv6|O2K3-Y
zwu<qk(Q&EX^~^x$JH=BMhFr#QqmfqR`H=|zXX3bRvf)Uz<L6U#CQP9E%Sl<Df5p&|
zlvq$&TIW22?TN*0ARbQvCTLhat*w!cGMoCLSYJdLt+@z=&doz_K{r};AN*W*PKYLx
zEfAZQ=x^p6>hl>Qp+`mk9ZR@B)DEMm4xAK7Je^#;bcCNNN>`Touoj*yk++=`Rd20F
ztVhgz;VTs|xnE%BQMbusUOSD2n`}@Rk!i_z$!yc;@0^ehkmTG;<ehm#f&hH3PC7{*
zDhC>VyaDwOpM*wPuCCvCojfoWtoC*`x$K^eSNP<X-QqnSUxBGyQ1TwtnZ~56*NdZY
zif6;0a&@r%7~$a_s()erUHKIle(tYJaVM=Now)i2`ds^Ke;8Z4Ze176XjfOIzY}re
zdZqCt#ntHhD?#U{zAOKG^lx1wB=wDm7#{gIAJka?D*CKTm3#8p)kLi~*+f)4iPg{a
zcb;+%Rv;<c<D=%%L|&It?1WK`5VzdS@@Ms@#aT}dOPm;#eJn^%T^h>g`aw7UU&q@|
z-DK&|6<J#<_YhhF6B>fSdEifJ!KK?R^vQ7ghBty|KX(s8cS`xXGavKrENY#U6|np7
zVjZ`vhXRS4d52CK!<Vj&5xDDtAc#BVL8e^>p6o@VU(jnG=mHujLi{o<mYUGSTL*tm
zozT9NcJ{+_z8$yU87LE&y2{#xJyRw5o8NbWApI^;TDR<=L=4yv<`eju@J4CAEc3tl
z-9taf<b*X!^c8rMVX3CjNFJ_|i5&<1qegC3KD;BYrmvG0I?ELOmNdXu8S<k!jgsM?
zfhQaH6p#XMh;*qE4T4Q@l}py&fq!|FFS6f*WNLQ71sq04u1^*9YDf;_irK0D7B+eQ
zpl6;?+qjqjD<L^d{9WgGV7ll(9_FDRDaqgNVeU-N`F~M4)y#jGAD_Jc7@QSfum7kY
z;pkbwUlYHv|NnWO|A+cn68fKb;Qv@8$Nw+&lhUh;`A-}J`EP4&s{gbL3j}?CsAJvr
zj@)9=_OEnmbi4028AgJ?*2aAjyvQu_*waQ*vKkTn-`Z`iU1|8!H85|)A9McGy6}j!
z#`as}!++;q{BN^{M{ABPYbvAd*=BPL(7<bn_dKh59y5_ps%O=}F1TZ8q|%gBYxI)I
z0z~jqA1#C(MY$;X0D@PIcEROCnm@6XrMUQ8tGD8(dE|#=PW%lD`inG6L|MPrfLWlv
ziUBf#YVK-PO?QLb0+`v8w~sk;Cn)usNg;?5yK8)Wq+azeXD?sJ++V(fFW2i3Gw)rl
zr)tg-?dS&!nux6%IeN2Gx%^twDy>8bH~U^%ah_<}+m)t5aN~bau;Xd@QpSRKIXb+k
zD3Q|#*ce)AeAm9WDfUvC9~KsQv>bn|;#!p>#=akt4D_qCmaurv<A(p^>Rw4og*zJ+
zt5r?g6y41%MX$Y+#cJojZYI7Kg?PHD{K$U3#<+Y~@uXsqDSI!%-naI9fdKC}y@;hh
zI5K}jwY@oK{CS_&>~mO5{PB~s1qIy__nBIO(&ux$`VBx6cq6dUAxj?#{#sS@(0h7a
zyBc-ycWjp`{PJkaL%%g*4Lo(~A=#DVwbQP$bb~6+L9whpEzQHw0o?36F}+atQE@W!
z9qz4)$Z_jd!$Lf_DX*^b2=T(dloYnRmJZ(=F~?Y+FR^z)O15{`G%8jk<nnB)D*G?{
z$1A#~r|ExJ1gM=q#T?-`^5L6L#NZ8nwTNOx@a*~(JidB($s33Q+sDJFvQ$JE5+&M^
zjvIAA5a`B35C}?nBl+jLc`CMPDRBJx&Y>mEBf432I~(V&l>~*R@K>38bWO`WzrBV3
zLGbXw6iuS|JofiXUT?{ux9pU}vW?}FBQ@jC2jkGQ$xEf>EX8ePKc-JI){{aC7&?bu
z)c=iuFQxWkgY@<bZ5@MVA*OE%$#46pOqKhEAD6KdYsXq_n^2RC-zHquZ)=j~{Vjoj
zyW!V_{+wLAfjnnx_@a6WKo2t$3-C8UHjXvx&76w8vURgBS%kbyZYxenvlAR7S(*8F
zM_HPet!02tj0#wY;E2nFVp5P?n#XhLA-dzw!XtIwPd8r1dHaW*sDR1r-WlF-XD}z4
z@$ve%Ra;Ni$x^5rP!~ZILlq`Sv!}g|bhkxXUVrlv9?E`%rDETApaoM*MWMgOiTt<Q
zV$Tm9;>{<NwG{d6DasdbX@RmD?N6KWw)6v=i@|rORWF}Czt}d!m_;^h406!^R}1|Z
zejr1w=<tyxfmMM64=1??9P3W>4~MeBiJ5-UZ8ykM2bwv|x`c8pGrzzE|8@P&{+?mk
zkmURNiBpAhrRIUA%P-dK5Mzs#*T^YvG(Ry?yL5d&)OaH(&o<rTU#!}xc>+~@$@UU=
z7pJ4eWnu|AW2w<4$hjNPKMUqxCTlVsId0EA=g_WXni2qBEy-l>mR`PmYAar2gq=)%
z{3&o#R9I?fy4pT<asm7S6EgqR;m769!pTr}d4t9MCepv<d3T$Av@t=$hq%H&#uOgH
zMA2bjD0m^%Tw$b4^52?kb6-?lM;l8~uQxE6e<8_#dJA8PG5E12v6#LYCBy}<R&(`P
ze)kC9;Luw!Q0wH9Yd@Q*#UGFy@FxXW&q;eVy*-%lm+*Jd0&rea<VdD@4n5G?;I?^;
z7(Zk53A|}cgZ{L~n*Lrj{~t@rp>C0lt~KjCYux>BzWPMYW+}yr1c(6t`AQ?XH{EBy
zqe1uDAJa2HR|}$LW1q(s6>$bgV!fkggpzK1^;N0g0?JFHdtnZ`!u<QxH#uV^>Fj+{
zBdccrq_^PHiUGTP;|jn7dN&$2f`Hie$%hOb{O3fZY#9C8h)8`b5e1gHQ6Bo3yVjc%
z2tj<P`T|Aqxv3x@FcN=94vjy<Xc-a!2tWXm8X~#;>0m0r)koop^5eWmNdNx>nDTw;
new file mode 100644
index 0000000000000000000000000000000000000000..a443b7e054d71c9120a56ac2ff36253053c381c1
GIT binary patch
literal 14327
zc${5%bzGBg^!CPJ)CiRriiCn7IY0@i0V=4Jf|MwuyF^NA)JO#b0cjPG5C$k68(m|R
zbdB!r*nZ&mec#XT^X`w;eLv^9?{ltmo$EeNgtn$C9nDo5002PuNbUYJ004OLy^acW
z{w`)|7IFSTZmp!D1OODh_dR*~>HIgBx!N-g0N^bz0Duez0FFrKpNjy1I}89=MgRc!
z;sF3w=lGn&egFUj&{o%d5clal-7U+Zz7BkQV?Vxa0N*sy)v&j@L?V)UI$Otw`{F8Q
z|Mqk)&J1_s+p~UT;JW{|bq!37^^0momNpF!5B3qyj%c%w!#`*D_B3f(#d;<*i^8qK
za{gwQw!U$-w+b(7X{aI*Pf5r7tBdmuy;CDS_4CK1t<|N^86`Fz(F4OX`tF(i%V!|#
zfxkV?KN=T5mP`zG)joXgd<hCm!mhLoA9we3^x+#b+IBWqXFBH2LNhyi`iJ}Q&G^oG
zwTH@vZ_&&!pX8rSq*GFEWlw(}zPjSKp@Giy>Y2^kj9a}V@6bd&3!jLj`lWe7b;qQN
zvVxj*dRa++Sv?Nd*Sda2niw4-9ufV&^$y?~Uj~-uW~NpRp58YM9m3a<P7jI4N1dIm
zK2b#;pD|`Zh1lA%k@=pE77Srx-04&EU>|;G@nme5w7WS!Hi#d_wPCuZDhHNGrzgeL
z&Fd?RM|)fS_>O_e`Ka)q{?VhqJ*`V)t-4O>WDn4K&ol;lTYi?*&JxD{wC|(qdU|^6
zZ7od_a{E==NY>GH1$mjSfq4V{t^I@JJKO7x-J5eO>pi%}!M^tX?)K<{k+&(GNM8?b
zMPJjG`f15=`y;~#yDP#)hbeiLYrDj<o+*4=9lpK!R||neI`}&>(9_whrJ;&#Z0hd9
zwGg&)Yu9f{YHn;#91uyTXQXEyzXrRpD}T{>CFpPHX5gJ4x*reuRnw#-gb$bSHCSw8
zd%eOFi}CK|g09oJlyvjlv#r^g<>hH?dw)<!EvBh``{>|s`>?O0Ud(@NX?Bq~Go$HP
za7sKGA8DJ|obPXI`rd?3uAP=Oj_>Je8tCch#kD+8R2;y!ba%D%;~EEg+qyei`ubX&
z-d7zT9-fho`uaMFXD6ozTSU@H&)*&$*J4eVU;TeOi$^EN=QjB*+Px!(+FNm_CkMdT
zF?WBI0m2O6Rz5s{>%!NQRyO*_G24gp0P&_pZ1Yra?^ajqX3t=McVmBd6NyCX?`|13
zd%X()-0^sHUrE<1*^GGF<yPot9N1T1wq&ny!>>NOIBv5{Tr1i2#MYPdq<u209WNsj
z<1#U?zPRXiviSPD`s?XcBUWDdj=a^DIZ^gU8v&w@=<T%%YB}lycsIk(%IzBqVYbQ1
z$xZr~*ImWGn3yv0FKby>2UyTSvqqnfUQfUoQ3uJ+ZzSN~DlYnWSBw_=n*OF|O0J@-
zFZ9iLQ!TE0TER&k+z&FP>DGji?-&@G`X=~r@dSxXD9nUwql{38H6S_D%ww&SzY|d}
z6J=F@pWTH6#OmChe@K1Z;DW33d1iz+Xgr7@RV{a=+q)88g$*^sQ{oaOXy$h3ABKCM
z6df*%u^zK8wl90DK6%w=|Fz(D+J@gmn^vyXsliaHY~d@SIOD{JH1{p~zG>+XVQ+67
zBr1rt6}K(2IgY<|b&AHh>GQdAt>e~kb7q%o^0uDO=k@9H4mf7Q51n5CqluYSIL?qV
zoL7#IZ}XG78SS@eBuT1Sf9iTsT)Or_4jVMpCW$7bYSdrps8Y-QPetlipqN@yAHO7{
z<8RS+!qd*afLqQQZ}Dn7e~EJO+o>%>haXP%u4{e;02>eOvBT*)kc}Enu?;JJtD(+x
zf1O{bwZXY12;|vv6o;V%jQzLbPp?TLqF)Ehb+TVr9`P3f`6ane8E3(H-LKH^`R1#=
zZ66A2^>WS*%?>hx>T9m6<k^;DLNRh)jo_a>L@p2$lh`ivo*4gxHInd6LE1RLM2wLZ
zyfQis3WY$N@57;36tbcXQLf<P$CWTwLJ>3>4u|PZ20Z+b+mYl)Dw!N^FzWfZzGpLe
zjH`WiR#=<@APX<bSxhkO4r!#Mfr!=#!sHN$DT{=&2UEeAu==Bj>DSo{4Gy{8?<p={
zM>KNnMFS%<p-^}NAzuu1S=!!r;IKfPYLdb=ZbLv0q3xBvIc2l^j7w^tvv1k}{Klo3
zoQ4ewhthv}AO@qVHDTdB<bXWg{k#j4TL~^sYei=C$k?ELUonG&AYxCTNQ0>cP%tf+
z6$*V;!N<OM@}hkz-KFA-X#)tP(@bi<?k1(sE=f+s)yx?`OJDcFoN=Ify>9Dqw=j5q
z`>fge`av*6N`%2}jKM5Ojmv`SB@WOC7ytc`v#~Zom|FLi_?a0kNJWDdDh@;XQa7HY
zwWixlFt`_mb);UWqoaewt;Ma4=m#<`I%Ie%2d-pne`&#P=G;jr8+Dh89b18*5Fb3a
zCe|y)`_S(KGjf0BYHZbh>#k~@gD}i-wyWlcFAAAl!XEiOAa5|%zN(hmf#w2I{dzCf
zD0-T9oV0fk^o0EkenmVxdyltsXRqC&SDWQsA{Ha@-Hi4;RfxxXbDNf`n!Kny2p`-1
z)Aida+m<i|+HD{R7AT>XC$?&GSN;l>QU(TXa-4IMpWP0bYW>sH#_;7f8uf`F3*v`h
zFg}7HP%)m3eJzlfx}61VPcb8lhSg~x`0tv_OOq4D+T??dN$+VINn8o?aY_p`t)#Vd
zMDX$?edM<i3}d)4M+G}Om~m5^BZO1@b0GkwX6<b)1G8)$6oYkYg(yD+qe#&twi(vu
z5~7vmQP<S&{YM&S^UD;TnhzzUUtQ_1u%KduN0&fP=}kmj5aE||YB@SwZjIL`W$d>S
ze@#rKCk!0-e*iMEr2p2QUh}%NxZv3bh3W<O0%2E)@?T;s5hg?ag05FV(jwJm>z*Mf
z3Z6Uc2eftacDQbxUI3Z4r~ZxCtPQu(tv}@27VMP=<UX~hK;~Col9|Fnj+th)sD>69
zG&LX)I7A@){SZ4alEajLu(lnO{_?Y289uwjH!5aCIQ{3qT^RX_`4K1t0trpm?RmBn
zvE;gDa<-yMRxDv%FtSjg;eH;Iz@Yl79tWCuwOCLC;U^~D9P-)>tMS$h@;<GrV3|Ij
zEU8$a^O8Zem=L{%&4Fw|odAUCYDRI4e%OGQ@mDn5-flWbF0_7mVEJm-24XLL6B$CK
z(#Ib7<b;jg6D<MbQvQBf{jnG^3`H)@6x$APfvV#}TBL=Tl=baR=xV^*giF`BtkjYy
z=&7|0kPV>ESK+)5Dn@>3a)HCZRDcFDc8;lTKq#fky!v-q5u*Y{wt<cfx^T6cd~rXz
zb4Ydg8h&=4klDw7Ob(&gQgT#^@zat&EOlK<J}8@@_8Jn%d^@r8SRo(+n_RV0Ii2U`
z%<f;-Sy=Y@^T%n&5t*eU`iP21K{grx2Yz)Pn#bQ(Ux?LGzZf@kAlr^+u4mgbN}#B7
z6ks}m-d$*=EqvdRmsmwiMGV!{8mjEg<J>m}YZT4J8!SqG$e`_dzkc=-cg0&zSR-07
zo7?;+Pxo6^r{f!yI4&U=5BV8F;3Qb}#G&W=*dbsMZz*Nt?CdMWVsD-nF3-mKOE5VO
zU|*<F_Pc%i?-jJ3UjjGVyX5Vh1HtSoLqi$v8gII?0wAQv!b%xw!`9!Od$+x}V|Jd%
z*O6)hwznJRN#_*p(C$?7uzEJHzvR<j>pN}(g;FMZK6AsYY}P0699g359RoYE&TADy
z>)~RoH8=-zEdtSV`Ak)*c{0x=$~LXq`@!MNTv~14TugWhwa=E;qutOgeY&E6fEdA~
zI-kvY48a3Ag&TYt)94I)qS#+1ZMpk!^<C3Rm9sF?Hi>(#CT%8q&ty<mo?;>95#}S!
zXLGN>&7WgW?d3hVEEvOn&;Ye74_nbs&A+2c85v6{B!<Mp#n?Xt&(pb70#Ns}uLjdK
z*duZm)kIh)+R)D&c|p=V`M*!!<7E{1LJ3k5QM~*Cu;eW~euNp_b=bH!dWBfx6u|4%
zxFB{81;Z!4;bueTWVxMpUIg-hf@vD83zWg&D)X<Opd+;Smrg`1T4v#RLO89S9GdUT
zmjA{gwc>hYzzJz@W+=OCUE0_(md5%`LZ+<D)>bxc`{@Iths(a%UboWn<O9%HVj=d5
zzh9iH<!vAzn}A#gzQRk?Yipe_RxvV?1eL@g0Hr`XoITFYMC&cxn@I_jwK10sZtm@F
z*VC-;>V4T^$f?rU>DXzLrn=JrZ>Q?Yt<z>nFx7A1Jk2#!VT>b32j>UtSnEad20X+R
z^YuH5J5h;_EQXi;3L*g%lt~+aw-F@&vJFWbJwA{#^2d}X5|mDDQ8f_fJ5X{US$G@v
z^h4>eyvqZp%jAuaBta;YO_0s$u|$Zdz-!YXcQHTl4U6j<w<cNh6c*#x#cDyii3vBR
z>ZhzGxyMNubTIdLZFHciiDJX0?=R&~zd}xeBUw1*>Nn*-yNZ-p@t_$OD8JZ7nD7cH
zz^H2Em|1T9<}*Zy@Gun88PlrMWkc_qM3Ie3Btrxyk+Ffa#$oD~2{btm0!7v=7bym~
z>yUpIA8NT=@6~HUbfQ0*9u3}vY*=sxKe^(pZHUz-vVAU?7tc3KpcVP#lp~BbLi`0;
zOj?xZaNrqD_CPi<tSa;KV--GHg;fr-$KId=Tl<r15W{oKCsdG}N9X87UrY*_Q}OEw
zs>>3tcaQ=dPnuSx*xNZ37rnq^{AN|&H5OR?h}nwNyxED<rKD5k>9X;%Bvs?Cm7!m+
zhJPDJC<PPl=5?i7KjW<1zy8X8Uud&@Ek@t}dVN*^G}X`NM^U`$%avh<R7ah5-8#AW
znzlWkVLNRYpo7%8gc*4gKiZYRD^{qK0qo?)>tgnDMuc6WZk$ZMF^D2FNGm=w1BEtw
zxbTyWGQnSG%c3<YP!vBLa9{Q4b5tAjctK*?yDa6aa#j>547z;y?3%$}SF(=CLRGUX
ztY9a>%B_Lf0NI$PZ9cbiIWxSgl$mh<(0|AIJ)d>qzy>~`{Iqw_TIk+UYE-SDhz&K1
zqVYAM;+t#qs_pyn454zIIWJ%L#}l25TpvVlwV%>T@a``T+0@Aw*lcOf{C(0i^$9Oi
zQ2V>~cI8pW!i)Ojvl~*A{sEo30ZRv0O83~uO8OK`2-e*JHvNqv&4}G<V&}1Fx<`{4
zDy7hqtRXN-X)dE(rLasn{YxljeU%wrd6SjnvIAuxVUu;Nayo!somHR|BKsW4&F#bV
zS%4gFNe$yskOh|D#%6gT3xQ2N!h{!gH)8&B1}kG9&X!N&*8lMNOTbPE<X=GE!`_dr
z4>Y7Rmwc)hK|6_)oQm?`b9pqmFh}n;G6H5|4=8ZsZ6(Yu==hy*I|_kq%rA}ILm>5H
zASa;{GGDy3%v(p=r{pzK3Eb$VHh`0h*ea2c#^KGHhvm=VjiGvN(6Yy>V&%yc5fywA
zxF&@9POLoH;k!2?F-Ftb36%T_{SheK{%PK+N^?LmxI+VMkbBs?xAt@IsmmB>)C0n8
zuMB+~<rAfpWA<H<Ck)<8{zC(}yv`o@H?w<$i3+=oK4uyy1(Zq!9)YN`(l+ij^G_8e
z2Nt=_=wEtNV_0`CP`eFCBIFNTnJ_UXAj{2mW%1ZO4e_xXZBE`ZFK)BdJU~e$s-x^J
zbR>7KITdO<!?-@b3#doUd~-fvkWM3vT_K)U@c%*6t*`m;{N%Z&UfWj@Z}$jU8KOHC
zz6t^hvBeJ<+;EO|20KaS%ZJ>SmJB1l(oSEZyUiD}&3s9|?x8$CJx!tK{dW0EkEQ++
znY@x#?HdUFA7WVjZ{gAFk#x0}S0k3R$c)GYYosWli_iZ|^>CLp2RuLJd81>zhf9dv
zSj8yaVM(#4W>3xNwtsU;M?!y5E;mBF(izxjP^8eFd)bBtbd`TY&K`nwX~h8O-Kh9i
z!&JavE^w*ii##Q$fJqN9R9k_+8Ou1L8VE$h(1Gh-gSIH_5ruT&ad1D$AO6>#InzPN
zCmYb|%Z^<88z0{4k=1v6!=R_)pdb*VR%IJt)lmZW1L!lvHAJ`C6;%1#88k?#{I<w5
zZqNr6RXt5{jvC%b>Y6!Tv%)V*4&g@N28t_OjE%~hG~L0`+&%(OakvAyDN}lvi^S>;
zsulAv2pQ#?B0%gTODwN}P*Au8j49m|<*w8^1Rm=|-(C(zfCJ|C4gwQ^{dm>pO$E|e
z8|ws2y~~5_{7wrcW#Z7BG3u@~D%7K$DajKj6oQ@0mg8KQr<-rZGe%!`z}Rvz84pl2
z7~OG09Fs}Hxwy>{^NS)e_puO&{u?eRS%LIbV=tVSx8<iR=jH8A%8bMYGb0nz7zjnS
zsEvq03R4Bo#i9kYAt3~TjA{5^1V2Ao84%I~G#+D749RI|3=-sm#>G6T!(0JU(KEwT
zvD)srT1bn<D~`nRbLup3tC*P$_4;K`8_4~+pyiNr=u&T8I0cE)T{BR7HEyWiflI;p
z$5b3y<I>xBtDsGuFN)q=$?vmjS=#lz(x?8=h4U4`Vd~?YWT&xXZH#I#HaN!aXAO+_
zl>~ucoH&E0{d8NYm_6mN>22wLdlRC3NPw9_53BP^ZTH^Z1C;*Q=%2(_bv+6{+^MKn
z0s=8?*<71>LxL^(@al%Zv}++{vQCud4=5kN^ptcM`b0B%_n1Sh{cR^1>R~&kzGt1H
zCU7sStPOw0(zN>5a@WH3ugYcy7oEKe?o*QPuw8%5RqOxqi35<4RjDaP`N(Z8k)DHW
zdP#dLSeBkz132B`9E#bzIdk&21bG;6Q{^U=mWAA&X_a2*eqH3bds>rPrOzZb7Un*=
zgcOT3xIO{%7z3jxqYPZAKn-+sT*M$Jz#D^Q>F5p&ntkZ1NdcV8!+ZOd5|;=CmA7^x
zok*F|6m7o(_@_KtS&0>^`ZVBys=0<*!J4e$g(IvA=YP3=Oq8D7OWl&6>GZV6BW-y2
zY45N`vsnaQwPf2jajVz|hi6OFT9Xr`w26OL^i6`%))TBSIj2*ljVn}90gPnk{G_jk
zma>e*Mie-Gdt3W#<4ajT8%Qi^UGSY0T*$l7GEa=kx*F8*D=a{1s?g*bd<ZJw>|JfI
zK-B@B_*n&P+(=(`h9A8!UCx-!c7A#0bM~Ztg!W?lP$%!DHXeHU_2k<!nDwVH6`Agq
zn60VY<(Si7Ua+#|HEs$M<7sn*G(XHd@B*M>oe1g4IFHBgfzZnkEXIq~oUtLy&4|rt
z%M_*kw>u+*b92e}NHNh=5(GM*uBUeA6}SwVF?A_WPHqfyLiwSC#5wJLI!De3S5G=3
zyXmcD2G*AAh4Y}v)2c~=7Z(*R`kGB8A0`vj=+UY-J@2o-%_4Y%!M+KA#mwN9N5CfX
z*(xcK@|wQe5htwY^8-6*z!TnK*y-1hL<ra9bVCEgm~5Ke3XI4FP;q@3mnCu(k?KMD
zp4o*aECK^bD)5y%WZUYxuW$T;E2^+`x0P=l{U8T}9sU1Za0^8S)<P7Tur9X1QAS{8
zZeYI#K$TuR`K~ansHW+Z_2KCysM)#i_<vxpo~F6d`DP^<0R~nkVs0r6J<~83R@v!%
z`6an789+ugTTE_bWa&tE<6X3kEhRGmoqv7<gf=<uTMn<odv$epg}lUcWR}MVhH^IO
zdDRaMG##Hm3W@s&LC84u8ZokIfv)|e)D6rDiUV>X;YGiZUj~pWL8b&{qY<Us<#d|N
z03i9-=bGsca*@L2fb91yR}J7V0qW;}H<Aem8ra&jJlA$3-T(zFd?qEKJe~rOYcxmz
znN_U2?VUds_ZmW@Agm(Y{q!_}0_9*J71!4|=B?{zueS=1n%MVlIrb$Ple9+^Yt}E9
zDbs*<c)($g>JvjW(m9cz&u?+R#3QuPM@z<>ZJav5o9=LU$k0msM}n9fQ|??HuBhNv
z0-@oq(a<9xAnW|5-wX{2qb*#{Z{DOC^=G$0<fhO56l_DJCbVRGjy~M9SxZcl^uL4t
zco`rhc<u@-%TSGsnt@<=*)^$&@q1~!jI+WoYTh(yXyqJ>LPDc+{II`;)6~dgi^;f<
zHiHG-Kdo#66iQycLiYJ$XOd{YDSOt^Z!CZQ{EoR>F0Cb8OjR}(@JtUt&WLM|ER(k$
z=M+L5V>UNWu<iR4aUJCE%t|!HhsF3MjJ0wr1Rv7M-UeWFfsF7wE5XLG3LeK2!L#Pz
zb$O>M>x6a*3quE5w-=R!t*?|=iAJlPzIsg>0POjH#?`*Z&<RGW|J|sQ-%;bWm<b7s
z8=I^=V$Ixw9p1VB>q+JVP`m@+_W35M`Zr&}HOz-GDi)Ox{Vzu=wvnPGpRI-pn$YS`
zI)Vea0YioXl=%<b2Vlw8Xg-_Eju@@AyO6JN$SSS${3!$&H4Yx+x(I|qcto7${;v1w
zjz9c}l<`}bZuJJmYED(9ID5F1_?-HYcYioH;|<7a@WmQOn1@|!I8}!H#h9?<a34nG
zrlNwz8^D&vNZIeeL$kTK<g$m!XR_S&|9L=AFiS#W(?lMRM)d$_M3tv_n*&2v6bch-
z=6Ajx;_@Ln(5^KwK2)jwBFx7_xAOC+x@+T4ylW&Ip0DLS`F>tKs{=q|I@h&fWrb9~
zwRj9y$w>b0Cpm%!1oNbe^%qZXDBo;rl$$Bpk579bj)XNx<fw6>3If<+LQ-=K9cgFH
zHFO2n3Wg{*t^`oJiu_9?Fn3;r{1v|8vuqZGWeq*KkdRbDJX#SP6iyXSMTG*;#|MUz
zI7m8V_w2XKNiXybzi3wf-8^s(p0(t7N`#;1fn_Xi$2L}}*ZYl0s5mrDL(VLiCdcwp
zVtRvGsHtd_-*=TR@QH1-&#OT3*4mseB!i1i<MJ8}G{IKRPauBYa7GKF+C7CK`%VXe
zbU`TDR!#Jit-7tt(J0_R!TA!u?kSZQh)ctgGeg^$f&eI4NcuRf57YpA^Bp4~U+Dtp
zYmv_E5X$Okytwc8z+t99y7bssJyV;$L)?cNs^aNu$pZgo(TJdwk_3?OIeHc5hC~N2
zcvIk>TGa*i_4IrtYUwqZ1%AVl$y}^KJVMBv`VjA~qflN5`d@aK=#8;izyOzTK%S%W
zhZp#;S!>9g^8sX>?V+>YRoyHIySh#d@@^}l<7V%aF1Cp)GfymnEkQ+^@Jj;;xSC-}
z0RolhCqx=w<PWw87pbhP)|$nscn66L<d%@_8|oaIcyi2pRZboq+wqQ;>c<cIbz`3R
z<5P|y#n_^A6J(OrYl;MWulRV@&o|AL={D*Dlz3>L$S^FJ&xJj1iXmmx2apEn_&o>!
zU}iwf8SfDfui^px+Jy0G;5k0f`Q>5~FAu~o-@3DK#86#;V*V}eq_APlQKbS&7Y?HG
z4bv|ECN@R(X;PPdzIy1>8y-Gi>go%O1X(r(eWr;2AXcQe-%R!-vJX;^NA9tR&tFB@
zfP$W-3lKl-UP`)+C{w-w?+pXJUAFxtZgaEXZ(d@-V!^i?UgSK7<i(0LpaMhFISBIF
zeeDT^CDX+({Az~hxk27Rqjv{xXPEKh%|mK7H<x5@xmf6s7G<T%s@U)R@?ic8Dnl4<
zF}%~V5o3O9SoChl;yxc>B;)XlX;S>oS33QHE(<klWc+`0N|B$R9y-hfG8MH(-MEd~
zGuxKq68Z6OAAYeXrI2j~=NvKi(zuPmr-HZ2t*(M=#eE&_ik&KaB20=ZsU$K(Ak%L@
z+Sd^uo1BJmzYp|Q&^dKX2Y~^kgw!_7I367yL68F3oISY-%4Z-uU%qNlZMnFwwZXM&
zN$-y8Iff{<UN35LpiuCs=n}Qz@9D+2sH$V<fI1;WUv9+lA8nhu8KOd|&q7^5jL8Fw
z*k{+^rA@?g1mGnN#moBRn7`CqNUHaa+gsxmJD9Q4=3q*O^)bTClN+T&o#n4jXiE4O
z>K~;k%<;L7`^WaYk$th%mmMAb=t(XgG0nl*vtfN3j`)(4udj4?kBO^U5_s;rTrceA
zCvIaW4)o8XD>$yQPbX}F+F_YA@5|hG-af9MpaPHYt}P0z^ah-2a_84?tzALYhVRCb
zJav9T`+fjQo8Q9nL$~$oTmD%yyp-06&U4Y<%t<d0ca%b47-^;TfB3dBkpzE>TjxD1
zU{ukcej0&VikjAY6fOaH(sv)LyX~iPNjoUyzWi$()dg*bPsz0wi=+6$>I9@jfBs$f
z+P(z6dOs-jBgSypb%#R1*tl7G&Us|!eR-cRDZ!0MUFg+!SJ)%hN7(eH4Vko_1d_n3
zODN2ToX6b7!3}>!$+947=lvH2>-_iqw|U;S?|7~EtgU!X94yGOpK3j9T(5I1=&#zn
zSE5_xkulv&Y$<HprEWsFFEY^c6o|aZ5&l<tuy-f4k_Ij8#H0fmqBm(3)pifZk{ztU
z%>LgEzk$gZX7l!QnPD6y61(nY-t3F*dk@#Ii1rA3*#&PT)wKvmzMvxrl~;cRmNsAG
zLc-c<Xc3BYMXS5o=KC+2fR0+z>*V0%_`y2<`t)6$)1&eE`38aJzS9S{#EfMsx~JXU
zkC=>`7D-LqdH4N4b9x4JA-rn0(=bcnK`Lo<liqwTEuErPjMal-DxANtR$YISA$g|N
zA&F%FaTKgYa*kuTH8Rxh`cWH((a)VAZx#P3`gp-`Qt(AiRE^q^Z9tV7_Bf3J`i6}~
zJQ;6WgLKn>`iLhufBRF1(;7?40fPc*Gv}^xujYP7=k62ZUYQ`8(a*MX&x7ECy0q9t
z>bzFu1)J3yNBt?WTS&5p3@#7X7JT_+KV6kUE_7s2B8<~>W;Oj(ZoB^5;9#iW&G@8Y
zAr!*)+GV3T`BZ;S3`84jTABSoPrDqD7Q7jm2w7<l9ea24`BhHC+V6pU5o8(gI&QC}
zPHiySnuZac;K$g_Va64%*y`d}77%RviK_1H!x`guNvROSIVm<ClXWw%UtO%w{m0P+
zas|P}glx*Q8n12t_r5i!!yuoup_VU-ot4MZGh^E+&K9EU@JZFX>409!bD0)hYz9;z
z=%TcXa<1Sz+bwL~)Z9+reL9`2d6enKYzcu(Q0HwFF)QrL<eFbo;H5OkhmF<SNisI>
zp84=JO~s#ij^`lLM}*fp{3VGbA+y6rCZhAr#3?DPIOsR!*=3gh=&)X#L45CW!`Gbn
z{z7r}$-}RvlnvQ`AqR~_Mc7+=p_BwPQYpf;<w`2a3<8mvdYK(q9u!3SaDAqOSyg7z
z$<aX*G4}gL?uX$FhqZin(WZ_a<y40ODB5pv2>1`O&0Y@(f<?B5g^gL#yq04XrL|^x
zp7ru)D-e20yN1yAq4!ZcPV+({XLs#a=%UgfEJYAH`<|8qQ#$8T(q&VfnaNcr<Lhr1
z>Y2P>g@M8#evY;3h`2o?clAkk{fWQ?UV2a<wt#%?!^5TbuEf`57oH=#d>JB>O^?^M
zH0Z|1!s6EMW#4KLU3vcc$^6TOamemm)(S-Qb3k!$M<l{H=Z46}llJ~*oT=x>Y0-SN
zwRWY@pVOCr8u6@4uP7c}nHI?uGxobI!3CxLCyB|gb|;05NeG9VnG1#sAlkanf9Pa(
zw=)->j2pjPG45C@{N?Wc%l)~#`2yarZeyxzJBSRZH=uXZSiVniuA{`6G%FNejco~w
zKGK5-37Hg`J&@s}<%~ZIy5_0yVwdY}762I1BOy%A*(N*p+W#3?g{I*lGm7tSZW-Hq
z-@~spgyfG5Dk<T;9zD*V6o=KV58EbM7&G-kZwCJ;`GGneo{MY7oXD7i#hc@z7b%3;
z4`fRvHeV6_+$T^IFC^+PEf=!%JHyAW*oo?UyRUb|o|k;xVBLFOs{Ecy^JmV9g$p6|
zsQu31#vpX)%<3%pqxoS}2AwsXxM<tz!;~gl9faYwBono{%yCo!GAgj=(c5+<a7^-p
zdSH!RSUfx=@Gcb`V9GX{Y}lbKTe8p7kz<`aIrDx%$ifDAE0P!%<t4Hyme6v{VtL!d
z>latO3!AatRKAk`R<);v^r*`|L+rcgiqzLR5FRit2nIuHUT5vHmZo$S{8uHT-IG{C
z38(2Lr~t7f@qBsKs>8K6dYL|uXhkTrQ$%3g)JS%r|J#tRj-x+G-;9L-afFnMt8M9O
zDvUZ-r$ulQ(ixDQ?;nY=I~@6WHua`?*KA%TKWC>=<^?v)FI?Ld=poxsrq_LOoF6or
z<IAMhfTWq)ixab@l)lh3kpTZzu7`_vqF`Wfs*+4RJ((x;TPX<<-W9wRnDdY11nCWo
zSxvp_x9oAfbVl~GP^&a+xrt%~Hu9Rc5X7?pItLTjaO<wlKe4>3@`do3*I%bwhXSH*
zX5jT}y@PrND0-_0`L6XEm&}2f&ZOy9VvP(M4ft}7ybzgJMUn<PABL=cHK|&Ohfv`)
zQU^-!Rw@J$+A~!(261dzV=tti)=4c(!)i;Qn!6Id^}`ZpFHf677FK6VdVlY-vLUV>
zaw)gSYOyu?mHx=%4fKlLx)4R>&9dWOJ9D%}>e+ADoGP!+tR`5<o)O;lHy*ZCNcT7B
zk3&s3PxGASlU0q}LFcMs(9G|S#94Zqi|V3L{;`<lBdh(TVonw?E)UCm*##Cp=%@_v
z68^%ynk<X>r=nUUd0C0XKkf~gIhH|}`ZNni^wRmdZ<k6onm^;<kmmxtD6@?@Cx>(~
zi_i(F%}QL(@Pc=G7sbWK@4MVOJH@X$Jb(V&QRAA%uZP%I*he1w`&anJ>vMpmV<|CV
z8(X6-F-@O|bRtwh_(0os-kjXra5}2&y4S7i=TSN4T1<bqcD(gNB`EAMkAR{BjrWbW
z$==_tGwNQUp<!{WZE|knh&sFG0QgP6l=kuCWoH>aEpHiyZ~r7zM`QsdZa{O?t~Aj~
zTwS*CHRj;+-R}hUhYyuyUZdlgJ)!%64jS;Rd(uB4+ihCzD(`Mrmxp-0`EC<um&D4R
zpP1~|h?*j>ql<&0XbQ4#9hPzf46N9F+q>ttWe1SlZglsd1{czsu*bYtImjlRMC?+)
zFgh$8EWX6@JWmSs+f;et5`?XC(xE8cu3M(|om2erZ*dFi?$=fZHbB>9D?gp|<WqrB
zbyE_)RDU@!wb8vJe>0i~@wXzY*>pGA8*=G<Ca*~(<Az~pDcX9Bt-t;W_Z!vCFIdM;
zn9RE^xNJF(icHcg<_jU98VKF>$ZMe#XkS@c^}<hCv@aoVDcnW6GcMvG%mQPEaj||3
z88E|oG7<OOwgAP;YSfDNkR1FqjyROM2I`N$$<#$L{x)1;FbrY9lxXWJet548n9SWd
z-uYt>f%vEEta1A>{*&YetotU;zlc;b+X0Q)P-=A&&P_7P7TloodhCe``s)%W8m_pB
zJZmOH#dK#}`=`r8IwE%<iLpoGFq@|DmnqoOzVGH|Jzrm&ED5G9fEciqKC`jxDQo^y
z(#8FLAM_7KUK>N|?kZ9BG@G4DTR?D-AjuSy91$4GJ@m}>Uc-hG1zSB^P~cFpnTGbU
zR-+fsf10a!dY(CjxN^H2gekO3W8f3#pVm*&lr3^dY=U3!Leh@C8DF9g8B2|zRsJHL
zKM52V;kKlJ11<>(PJp<n-e9Otr&tqCaa^680mGY$GhavAAhvGM-jZEWVww|k(#fas
zO&x5A<tiAx$Godhfn@7yr${S_G$^A!KbVhx;wYZ|76Zh`yIV!Sb|acp!UQuPx!lnA
zmP*RuP8%-d*KxdR@QC`q{>!kT)VH-`Hdf2bC_7)4Q**DHc89;5@|xf((pXZ7lj;}m
z<gbdYU6Zp`h>Mf!uPv55*R@YF+kd9%Ht6*CWnO6=$uMVkh^e~`dY;v5Cw^2dpVL$Y
zEd6UK>?huOH9r2etGh(5mw=@kT{Qe9XJQvDV8^;;<X%TI<k>fz64kv<SXWpB{-f%z
zYZ7}eQ*T2ZhdyK>FtC}2)=`BR&eZ80r3sm;cl35_Fe=DyAjKje;ote!vdQxM5?=x5
z)1)T!HkSLHtvfS=|HI81$z5}`lV{qPr;X_pqjnAVt&t5CnBxDA#r+bkj`D}13fhRk
z_TrSkb~%b03Zym+%u+n~RJU2hTAC`2^?U=j|7$lj-3z{rdyqD;E{Zt3dUvO&sv)B0
zQHKKO<AFhHk<|9`ptjFLe!RcQK0#?6pvrO>R*ruf>6>BI4SwgX_d5`X_oqpT$s{?S
zgRT1;b5)bRmd6Q29zNe5^+q&7VprO;in}pRW*CAn1q3VVIeS;R9OH2gg`U;Z$cL!6
zM4>CFvZuCv<XUY)GeZ@Iq?yUi$(`N?FNNkEb<u9nWV2L+QWW~BE`@XYZXpGPlJ9z|
z+qHIz|I=E#R9dk4>Cxqe+?=<1C9K)Tk=|{ws{&oHcxMiVhI(EGJ)BI+=g;Kz$1RJr
zY#CF#U$5P@XJc6hR51V76YDzll*YLDn0ja1Z9gc{`81#TM!wg&^)RUc)+Bz@xtF(w
ztwmUAFgzHRf|XlzBrInSbeS3qJqwm*rTyn@DAQ>*@n<qOv0ABpw_+6%rx!gOFprji
zB~K?FWV}D>KhepC9!J6xz#cQ8Fe$#k3}uzg`u%JB5KTtYe^ua)prGXVOj0vi%rBy=
z<~FTaQr4_AjpH!BrZmG;(X*>#b+z)W8sdR5tA9W7fFgK0ER+*oUSiC52yRdU+Z0j%
z>l;ob->#VIYwU<(6&)}TDoyY!N+=$hR)znp_S!egY~lKu56Ot*i0WYzK>_pZPDp=A
zd6(SIRn`5y;&0Q|$DKJ4MW_X|R&!6>&#ENK2&_YkwC+t4hs`FBFuQe)fQn9_T*#l3
zl%`>;MX`#VQ-B}y&;B~t0fvrgv}*zZm<zdZK75o&Kf$vNOE>|<KF-P=?gwlpX+ISw
zLtn76uCxBBMOd;cciny-2sG=Ffu)$rQKk_gx79xn#b5lE6)6#R<-X!?OKA-JP+8y@
zBy=#N+*JsmO7AHqBm397dDuZi^)Icj3JXFJ7nJhu3-f<RssBC1^)G#Fe&-{Qapxp=
z$4C!`Y5)I*kbsN6_qpjHpxy-*{w^pTvvJuA-6$(Qog8T0+{+Qe$Cm_CHLP1XdF|~9
zk@|lcHy;0M^)0Q#Tx2byD1#Rj#(}aaKuX59d={_4;lT_Kf3PQ?ZlkaGrrkb=xPybv
zjUj8w;1~jn>(vAeYQW22%6qDfTg}R&qa3$YGa9P@>omS7t3WuyL{&B`yC$0;keXns
z!q7_R2@lj^XjpKtQb!(_ebGg-?r_}=W6-o}wJbl28UgE24W;jnzJ7sfz(VX(rvB?F
zdNYDYN7FYE(vN9NZUeh%Z#&Eb`pD4_A9N;?ku$EXOT4pg{iA5Z$*z1pPKHIa0w57{
z4(H3bME<WFloXRCfcPjR0KuuZtaRud7$^(nU%5eZ{&Cl@LK~p-)u-1x_0Q%5*&}Q&
z;)dIJ#CZcSG(vtpKIs?jU%CMYu}2mCi<V8m!4@MRR^eRx_T=Xy0|RUQ-b4Qp&;RrP
zxzSN}Gh|XA@LvSM2LDn*R4{>BkWHJhzRN`^fm-)GJl!^iKysPR^b3D|x1?ZHKcW@*
z&ki6cSzY_W(#ZHHg%Hf=rT;qzl%M~<;(KlY3lJ3iul0CkB*i(jiPRAGya%h~gPQt-
zg{*K`DiYgZg8H_O=)PJx@Cm|rIe5p(*~AlB=>Bft52H>}<jqCDYeQ4{HNp*-Q0a1q
znv=r3@+lqPphhl^XDR-s9~D5PgJ|B1{zgd=j=yfcOY}_fHQwbELles8pDfdfUcBQr
z$}nGdwgQDX&cl2Q<lTs(^m}LZRo4PslGxvP+aH=zoa_z_+iZ_%zdiUi+zE-lQl<t!
z`m=PI9ipUq<dRsmpC7dRJ$9S~h5kq1Eo_|oc(t}8k`!2WHTo#2*o8o1%H9K4-u5(q
zV`Z?^`BTO*J?cqKoWc6wwbwC&0z}2}W5vv!JC(jPOsPpN`J>rSOD;Dn3fnPCY(@EV
zin!s$g=zz^7#rSykFwk%$Chg_Ucw(nl*D%U4(jCxB8^9fEng{Mg0g{IM*H!ib)=`h
zW;Kdu1AkK=^bVB05vgv;AO;Tfjp%XU6Eql7?F!!+W1~ej{(#65m5n@z`|-x)Gb`2O
zXDWoM?Pdw-&gVzZ%jYtB_K-7?=dP>rX4HS!*3XsAyj32DEX!p2A!ZY}Nm^myWTRD>
zl1p_nJ!v|FP_I>gTPnq3<i;bM*6I2EEZ2QFQNov5S(K0Fc1$7)?|N}X*q4M_HAg>r
z;huPdbPq_*2zw6m?78v$&PyBloz`h0{eWh&%i16NJ{*N&*<ib~)M#D1O%+Q+sVZdD
z^{2n@?fsF}DLngNaz#@6owchybJ<BMa3p3l-bl$^2Je{=WU5=w!T@$}QYkkk^swDc
ziutvOH+gVD5Pn%OSWa`B?Kpv2bPM7=2r&0hZ3t$)3`q%N`(5B@YJf&zS>lf$NrqBh
z7b$ylyzt}r*fD_j{feAQZAlK6dgn;-t@4qMl%Ind)!p1i_v=h6%6?Umg?Phw>GO@?
z=9MBl4{8`DI#-YjfM18#ArzcLWn;btefK^sr5X=^W3|sJz+}Ga+*?~qcT0g-vxv)C
z0j?)S-(sLuo_T!`OjkvVXYywRsDLXvDsbOgTsdZ&vNBC3?b?3fF#txm5M<50#2}jr
zOPS@GlKWW5Cb(DfSPD8><$bzZpSjuFhWCZk`Z_}1Ic}6HK6X5*EqbZ=%3riVr%73H
z67gC@c;n7ih2q-Y*I=z4+&j5Xjh9NApYj!Vs@$2i-Hn3|W7s$+DB4kqp3&}vpSewc
z`14y!XD$B_?0CUoB*4t<r-hotckHXF`(%^>odZ?~w0fm(fZk25setAZ+p(Rfg_p*4
zU7(mRt?7!8IY{>UbBR+^j5I0ex#vWT%#DI)q9o_2-Nd?y9{Ao0=h^dnsL9R=J3rYr
z7(;fB9wZO?N^z|7VxO_zj1MIbcj2O%@{Pa*(!z?wkntqzABIsJEtiY9e#%N3vS+{#
zk~(R{<8b$F+u`b!VEieroIbXv=G0Rxk3nT23dGBjrwiTg?U^OH@|vXHHT2K<y1Bmk
zJWF|d;U$Uc$8uN29eKSF(^uUnsRNgUs&wZ7D9o{X0t@)}kd3{^662%VRUn<jsa_Xa
zbA{QMO%g`F#^h{pbL9%>Y}6A!D99}jZ;8ldq`}ctb;77$`lIye`|y4Yzn-y<y)?gh
zx>*yu+9QNAtk?RO<VjWaiWb9s8Kdo097(X^gh2pgROZ#we4zlV_c%+G`(cpT-n6~q
zZ=MA;HXqwRZ7KPYBTI+Dfv%M1jGB88$Y0NPwtH+7zmBUalL-Qqrxqx0K4E&l<<D}r
zZ9DnexDI359=;+Z*H0tE;=<yEO<@g7vE~@<(hroS<-l`7nqfXag-`9WP@U3R8@o2n
zs$`*AM;+)Jrh?~^ry*e`1z0wp3<%^`{H?%e51?*~Je|csJsX9@qj}n^9F-E^zGYok
z{2aGcCtx?;c^$&;AX$o~bjgyue^C}N9uGWL&HNfu;EJxx-1KObC6dsi5)pBtb$?5S
z6M<kD4}t6CKE^kSUX{V&5>xIa&1}vZ8!xj#MPNj0>HZ@#4)opEgl`JX!Vg&?BAvuU
z^Ooe3Q^lM3Ur(Ik6t}wsZ&MAkC*4jsaj5M#XU}43S+C<3y?J_Xl$r~f0G(*E6j!fP
z`x+1dToYs!Ta=jE9WFAybrv;DVq;aD^3UNcOPUmNjXYF6laa1Mv9j%heEKoESeLE(
zrX^SCwnHsRSZZ$Zy7=nhaB;Jmap9(CO|Pea;oYJg%ZAUHzAj~1gbPJe1bd;&G07wS
z4)nIlvh>mgH0giJxMCGqayE-h@CqLF^)$4#j{ewhn?nz1&yr=-lNPG2x)pIp$J5C&
zZYeH5)4u2ytl%)4+|HN7x|Fk`mlBpmjD8v!7o)#Q;YVY)ur1X;4jA%3&fjL^7<F*H
z#vjvRj2g`iU=tBLT=!yNghvmLr3ukCe6eVVob|h>U!466S*U`GSokDeA>;Zg6N4Mg
zUG{>3ROa7UL_ZndMlxRl*XvvOJzmMOG-?!eXvkQXH0nQOL<c+{+9rGNN22h^2U2l8
zEYQb&y3De<T85A=@)BTdd6po6nD0D!bx>RLF(XBJW(qM63Z-0wY(v(Y(^;Bo$8{yj
zi))_grQh?dymIas7ihVho|jMuQ3`*DA>_7vGPPCLL8YRD#E76ZV%QByLnfK7%-)`w
z5^tTfwazEoaBLaXspTOy<?y8-9NrX?Z@oEn#`tHGU4{R=vhCW2Z@XBAxw)RrUJga9
zrF}LHm*ESTc$I)_OB6o7ugfG#i~zglT%nU<Wxk7tn0ydko^K8vm3srn__IiTS>2qw
z(tG3yB4_;mZG?IfR||Rj3w{|wjk*a0+_i4&jN!wHE~SjA{5ZyitQLZ=?+x!2#bp=;
z_o_#mt+vTWv6-<|ax9*UvYBY+pkENf^l>?^s@w<#Bc>Pv!c7Ef0mO9*Z2TC5!x()<
yTN!C`?I={NfrfdLIyhs*6+PHz!l&zSBoH891v&yco~Z-QUymMW-Y-x_1pN;Oz??k*
new file mode 100644
index 0000000000000000000000000000000000000000..3cf5e8fea3758c0b5a7f101a1f93e6cb3e813c52
GIT binary patch
literal 13754
zc$`IecQ~8x`*tE4N~|hPO3|UM9kfcVpj9nOQL9E!qo`SXg%EqRcI~!SYmeH5*emwl
zwfElShtKyt-u#g~IiCBupYyuz>%7M4ulV*A1=(#f002PoTIPik001PtxNac@U3@RD
zXqjC65F1O#O8@}*A+9Iy!Y}@_7|1Be0|3sf000UN02~o6eis1%J2(Kaj06ClM*{%2
zETc1H`v3qCKv7QRWqHd;PiMV-Ow&+b8^uGTZ(oB)I&rNXJ)5il&d-kil(i1v8@k$Y
zk!5ppGs8Uc0q=~%e`lr+cjHEfdb_(@cDI(=yZUUc%xQid4ED4e`Iasmo?|lm{i8E_
z@C{F;jk`OWH`Z1Nr-UY4<#0d#m9(U){qLW+#p&_UuD(Gn4VC`ov%$`qZ$;y{o&|QB
zVH5k{h#v)O%X1|S3-pZe(!Yg0{UcLjy|3O|c&D~I_(ZjLw@r)=^>sBc3p%I&N{Xvp
zIXm9%>}+hGJ?rXjXKp2Qw$vLrCTlq7ZEtPkhR@QPw+gVm{oT!-9W8_XE&c5m$nma8
z9j}a2GAm~LyIR$ZTm#~;vnyvEE!dy=*odD^GMeZCe9QP^Z~xHv$-+i(?r2?g$=LR}
zYf#BRM`vl@*+5_C^ze*zcpbjAp{=oIpr@s;r{cZEkM(mxP3P3`?855q-0aL`aY5G5
z_>{h9PJdTzAHL;qcU?+CB)93fZ|orPPwDCLF_B!&(!$hWM|WcOkPfO??Y*L(54!x{
zS!YLWQ)|~JBR$2e)1DS=eLXh2Y3gs!LT^{=zmb;LErhJB^!V5a!ui?R@hRc-MA~m<
zqOED8vHfJ{@c8(wwWVROxAowhFwoQVZ+^L_8>^)7dSI|uM@zk~YxJG<pN;+Vs`?J1
z=f9epYh9h~fA;Rh<+fR)es7FcPc3g89UgSGH)Rcuph8m4&Q2RzxBB{<d+@CyAEHM3
zhjR0?Dw<1(%(~;Nrg2TpElusG1JiGn)psT)^_;NXZJh#7c=oym^$kCt5(vpji9gzx
zr#gCO21oCy<J#JrmZw)=Ysj^9R`)b^bayv4)o1s&;13UW`g<FC*XG9h>U(;-WMt*)
z*9ZfhZGHH*{_e(suKNC-mH~WIUw8XZN1Itl&FSeuZxgn^qj|8ivA3;xxT|Tntv)Be
zxS|G&)cMdfywTTIvpC#G95^;O*l~7pKGKMv9Oz;bQe5mFJtv$H2xo+I!o{brt7*cm
zND=_x6MFqZLd7v&e{AREA&!A#P8EFq7;~%m)!<})IV(PoC&-o({bI@7Nl1It?d{1}
zZ~AQeX_e*p`VudGKf5iloZE!V%+B$5?M;lZtj$8Yd*z(XLdkp)Cq|T;`3MHhF)Pqf
z(?jKnZ5N({w>@-?k%nET9nJ}!63Rz8+vDXA4Ldm?kmqX9hz*^=v41vh(Q)(jr;}N<
zI|rq|@Rd2&>wlbPL0C4Wy@79})GZG^jfnc)X9<t%04bjKfN8t1BX)-ucPRZTX*@Hf
zRq<qeglAHnsZMP^Kkr1z$4{4~Tbvwh#K&*c>+n7R5mOt)H$RyeFo@)bP5iQ0!Sl_z
zj_-@K?ZYeXp<}hX(?30WnANPW-cDPp^ACfWx3k5#+=Hx&4}0)!y6GdQ43IImT_*Gw
z4DJNFW9kwHi*k73CRL#u$grTv`b{Rk-1p|&D_zb6Ev2y9uX=ZIwy(h~14xu7!)+E<
zj3-HurR(%j9S*yBt(iz7EZB1e21P(0P!fA>NI)t0;99*zUm+VQ^SHj043ba2J?=@A
zsQR-szK;%q6Y9*QUtW}ANkU`+!1_ZebJjK>hTNYDw%__9zJ{$8yV+mFI#IC|H$5-Q
z%sL2P)gM}@w<?WIiAsspi;gSK?$sN`bySSmuNf5EjoKZS^i~T`{&j*8?7z7X-(1O9
zL}nltGi21e@@3bh0U*VXt+W_QGce{SqNBJwbYDmwiG+&<dXYawv49jANYPFZ2!iv#
z4;TbXc7?)4gNgL&6vZUZcIEOk!A}4|Qp}@q<PBzNHLX?EKXSwGa-5g9aVekx`XZGb
z8cz;-JmkUPzk$A*;W#K%hZp{2;Lo@c$h6#$5HC^iXZ1+O_%(*L^BbPELZ8($g%aXW
z7XFRB<}DE}Ng~8^ng)ty8RaSUsTe~Y_gjc6Dvr+Cli%A#0A;M)K$2euffDZ-sPAp@
zch9C=XNsDw#Tt{}BpP-|(Ptn+Kp{!ZfTOt6#5W*o^IGo)WW1PdTYw)O<X$`27&gJ_
z|Jw98oIB;g0E8M5#2-phQEa`#*DhEdGi@7Xhbe=hYp<cnS?*JWXxiRE4}Y?QkUCU&
z$$-JsV07RyLcb(N%+K!K6dFsCxA+@QP23}6kr)ZaKwQ)?=;R%pg(`@3AdBK^WK0vK
z2^1)5^_primX#MtI=InakL}VLU0sV7qiy$fd<wY9g*-RVfD_X*<Uow&I-ekbVd6A5
za(emGlb(r)o3$+HfYbk}ww%OLojE=G<fhy0|FS{*4Y?(NnEC+=_v9Lf(qE*p$z+ru
z!Ty;bV^)ZpohW!uoY?EsL+&_}Zs-8vvBIzQ5tXOP`>TV@0O1V;fgqqWs(J{dOA*lH
z;weTFz+5moZQZ;cHr{c<Lg1M2J!B#Z5kVpq0s6@vaz-#-csxH52B2<abR3lqMB0TB
z0dJ78iiR4>IwOi2Es|??uE}>ISQIVv#Ym+jK~PFeWpdYAWxECYuCKLWU($O~@dMq;
zkyBNR8wda|(?|H!P!~PYAvIz8EemeW|F;oDHl0uFl#C1nM&9u90ix+}ycS^wyEOhO
z<&hFkg7pT>Fo8kNe!Hlfw-MWYK2N|_P=M#I@=`hkQfpRA%}EsS1o;isRI&HY3@$24
z3xRc-?~<IPm(j;FL5<#afYbd@6kRHM)<jw75io*<8cWqfV#xG7Ea{pQyrLrF#H=$S
zo{dG9lfy<ort9yD!Z<+#qRLZ3%Jvpa%F>87Z%VNAW4vKnV|zngwd{6{UYOVy?>|`J
zFS`}?^-o={z_$#op%F<cZhPQ`K!dSl>P#@EsGUCYzWu_U#HZPNA`h@f_k#5Lv$T1E
zdXVb;!hL|X=HVN~ZG<;^?7r1NX*%)86U!p8WdisHxaA>>hD^MdB;w(nnA=c<Asgo_
zIO2>7!}2iZ%QauHhzO!307!EK0ufR!XXcZeuBP2S=1F=sNH4GB?{TDS^!(NMQs^b@
z!th(CW7x3VHb7Ro3iQjMWpL-nAGgryx1{LV{XyXR3cZ!fX3jg_!~8h{#|i;_OQS;o
z4rO2*kHf-?cjx@m$3$)fEqhqPV@?lq-Ia&*KIfHGb&|{z%nALl5O)<|z~?=B_XENs
z;eU}Vm=IQ<bKgjZ^3)EZGzd7bxb_hz%8EqkJ0Oju=`7>~mWCsTv6_(i&IZSt%z@sh
z19;(#*t@_s7!~Snez(U@arlGf@5|q@LS!-A(Dg+zC1>+U>ZAkLr_Z91iEBBZQy2h5
ze*U$l40$h%HZ_<teh{g^1S6+2+qC!CZ>>Ka{ocNZ&+^YZKZ!kg8<uCC@ibao;nx%c
zm=66)&9T0$Ec6Xr#>^Sc=;kWuchp7zJ&V-I{@6UeR-ACup-uTUE;^>|$IV=D#Ytt=
zd33_RS6v@40qEN<RU7V+?jH_s#xT7F;5=(*UO*o+LZ_y&c}aS-aCvWD)D#Si6a=&w
zsSCncd_W*2K{)CnzX@jPspB>Qq%g#^A_;^9^AKYJwrE)gV{-jP4m{vRjQoG&i$<oK
zM%f&WMWAm)FKk=-?&$MW>gzf^(iDj-1+^bTTn1IzcZ^CDyJe~xtW@TrO;ux1>Kk8$
zl|z|&Cv1BT>s}@NB$ssWcYCKMdKfW%MEM%*52iwLFPAN^5e_YOz{T@5Q4rxh^nv#*
z|KkqLBf?3_4RqYM0ySM7Ud<hL#g@2QVKce~|Gad_Bk0?BLB0InwLhmPs$3ukC?-Ko
z+ufaRJS2&~*Z`^zO#{3KxYZ+x%<KBRT1hbvOo%1{znNgz)OuTf>Y`}FFvC3K!v+B4
zdUCS=kCs>^@HOzYYd*nb3_H&f4KIQKQ@)UtH0i|Dt9allhMpmh3_~c+_mBQ`dY8(f
zPmZI!s2Bx@1J)6D(Y3zQ+lCln_T&P1h+c8=9zOUMC2#v7$eb)Ib{gk&Bwh3v4aI??
zUC6a=R%@LczZBBg9$L{{`T)5L8E}OV_A^$GJG&0F13e|STdR7DEz@k@tRZ98E3<`J
zLTXL_MGrcZ_K)qt%!NwEYW_8^G43bmMLy}OrHAM}s)Hi-((a*e;5@)9^rAYV$r=0p
ztPt6>S@<m6G1igSk++Zc2?3ny=d{F9<4e>_L<~{}=1oj}6tvsm#Tj7G5Oc^UNDd+?
zzRUxo_f$|+Za1kJ{#EZjuBiNzUF^58sOvoF!h1NPwa$gYk9X+bnjU<lj&;{wRJzQJ
ztfmu4WQ_Gu`g%{QEG)p4otsZ&uhfjC-72OwBxM6x4fLI>DNWM9?Gj?+VOUxqttNk1
z<?XbKZrTVDCbuXwJhb|t<yMh5y|q_kYIo1H%0kOkY~!s>(aRBkW7w@{UkdOwRVf0e
z1m|9b1Is(2MG{&ZCJZGnJx16u>GTi?_K9A8t3DkFF2n|0QN)};US;#}9`b5kOCv@G
zH2Yr=9)x>{(HzjkOhT6U!?8@m)OojKm{iekWWX&8ldzAG2sTOj7$zg$RikE-R8l0|
z2k>X=K0-$fEspC<%Su~<e1jx|r;H<GqhVRH1tpP<g`IJ_1B+X$KjuG!FS`a#_ll{R
z;J?)-+88q1$ky3#%O5buG5aOaqAKgY_&F0c9B&lE{1Ppb`yo3QVH0#8O*Cmy96G<;
zv|g`WTA%FjE-8FEbzB+~DyFtf#>(urH+N{Qj=t+K_`_+%-A&|E;>0f;b;K;L7Hc)<
z+j2W;Qdo*9o#&bWtLi)-+z}xAM)B-={hKLGP|RDNrK8V8J$_MrFj__7-#OP+r4fk5
zWfVn94GgO8AvHpSwU0QHkV(jQnW0A>ms4eaW<r?-2cNHN$lLXzKKCq?N5fQZqf{qe
zE4;07{L=H#sIUgM4M|jRa`f;3UKW-e^f+pb6kPEksSx_Mx~wtz=^g_J^vlo*sA=mp
zLLIhG90tk~2nAkO+`FE|Q^RM)-+sfyusPA0rq7W`AV-tO>$+mf#y2qMwia|B6&F*u
zzG<9wt*4ff1PUGCV<~<xbr+cP6e_kOIYOQB^s$W$iz$U-9GSW%(T50XRED_c9BYxN
z=UCL#`A7#=vGsG_&o|{8Q;kgp4)&`?g5}@bB3(o-;`00r2wX3GH;n!3Gc40DdR(7@
zuEgh%RA3Hul9U&V3p<EN#l;pq8aWjODmu%Xr0H?D8ZIR3%YcA-e&l*~V3r4pG#tu}
zu94%9on4<let_y|Lr%LZ?tBCGVUP$)60pe!GE*v>$H{$(icVGuKnsogl0Zf<8C7yN
zDHwc^&}ck9iE?c^>%SdSYdb&r&RWccd1&%Tz+hwGo7`N*;8SlwwabP-^BuFT?!>#5
z*B3o&_%=5b#R#gkBDJ}f$J_{LG%Z1@b2+n7KN8}HuU^w{Sx^+D?K^yJ9Ogpo8>R!h
zIi|$1jGp>{XO)1mckWSOQmEM}*ZqOk4~z1zuLPzX)Ve0`Y8#TS`aF!IP_#~WQzZQe
za?yr3&m|z$)jysb)=Ki4T?FtGS}~WOH4cgPhA#hR6se`_g)@{(8b~^?#R3IL-ZN!_
z{6I)Gk~wsF7<CXWXE1o$>pC)M(c=}55Arb;cPKmMMz+-H_|ivbXI&@RV0=`k4P4a_
z>G!SF{nOKnqoCj5`DijeMr8hNQ%rGlVnneWyQvDj?ot<Tt4+)C5s5<n+|bVz^n`}`
zvNR(4@9+Nf#8)Ey?w+eciMo#zGf-)vw|s>xVJvBtKHHwFE)bfy7Z=6Hx)wy}alAwB
zKJEV$>z*VpE7nIGBdvbm$@~V5X~a^e0a|&yY*tdf7>E-85cXyc4z=ifrMN{}fBL%w
z1`XSMMN5hayj~+}8tiQ+hcxZnl!E_u);c~z=+TNVJh{NVeJ$e5<=7PW?e)ZmTB}EW
z+OJY}=c6Hz85!uEO;@K!#C6acN(#^z1XP*a9l+@tHr*7>aMqBIEKXWQ9#YGTf>aoL
zrW(C%`z%^Oh8~6N6C?)8m}|N=eDfjzQWk03mHDR-Y{;>4hOpels8#KCVlI}|?!9er
zONzzj6PZ`V28Wm4?JvaAG>yK?QqfJQJXGmVFCtj-aUxFI8W|?B3<Hr$9oa(r%Fptr
zL=@#oy)h-#Hh=EI(ex@J0eTW%o5J(P7XulzR4qxOe#1cdi<zC-Q;-yg`Rer%8^JWd
z9MQ=cy$KYIb!Cfj&NN0gV^IOuB_Mln7p}L9T0niKFLz9~O`Eb5@3wQ+m)^L67*aMp
zR2j+i2)R60fiJ|Z<C@KR=W_dftC?ltFr#e*CRk5BKvAi2jo<G{2GHNTdoJ{SiKZtU
z^j%Qmq{}B|-k_A>H`A~}au>N*zyX7Jl-;KDA%q15HRoph>^gqP7ZrChjk8IxNg&wV
zC!a8>$?tmBr9*eIp!1>D#NILF2}^66&pF}Nk@&aGV4r6er&L9{#23>LjM?U(bk*q_
z%QcIZ68=&hI8<Hcv6&+51xc=5tDe)r<vaM923+UPj};O;?Z^aKUU+hs!BH_2Q(DV|
zJ@NhP_=}k8o{wu^ie2b{eaX=x>1W7h+jSr(lSwaht7NmS-Wc9phh5msTN$m<ycr~6
zT-@0<2<b<NYy&FVY%rP^OoCgQOir9Hw$^c|q10ysNEsO7IuSE4bN-1Q+8QUWqx}vl
zm-m<JcuWs0Cn?EDNRbRCo0v5^(XF@=OC3>Bvs^N21Z193q&>)1_dH!7&(Jj!P&Y0@
zHGhIn687LW5T^Q<e$=i~;wK3w^tygf6eeOpVcqUofP-3W18Q*|X$KOAF@^ehFO}XX
z1<20|rKvYnc-!^B02R16DAW{4M9N653!BZfsIL4WLQ86S+=L}Wd<vn$r6l4Y?qvZN
zJCgy1=qxX~ae8WW-1Oak3UT68r)P8Pj_rARwCKr(Yw@oawjduVsMR+^^^~bWAOt`{
zx&G7l;hm=r<xOdDCY=h@ajvc{#TG>i1%#A1ofM1$c%_jl|9*5`{IRHStr`140bp$h
zZx?IynRhnrujozCxl{7ZcjVNFCmi>Y$>vRlPCEU6LWCgEIMsrp-gc%pfQ+CE#+YPF
zobeHXRXX`kXT{hZUH9oyg`JsU4@`_`%8<a)0p!J+?~yceA2|C!Gh(nLSviW2c_Fgg
ztvwx);#<D8q5gV_%sk56{ag=jA=*e$fFBydGqJeiUfF8qm5ij>@^iwvB|h5O!j*fd
zfPl4QKBB;eF^d33LjK#BZ$Cxo287}r*+!rHud-o2xXc1U^}9LEW5!L#@KbSyk-3+A
z{~^6tjF&X_m{cq8E0j+T%-%pBY#10P<tI|;k(N~({=6r(o+7VO5~h_0P?EkFiaT0K
zQv*&Q&vt&ht8Qf*Jw8_YAr?Me7k}@i9xF!v9L@d|+j@l;mj9!j!>RT3fa=8qsU3IY
zwh1}QqqY%6x7EaXPK*a6eC~`i4)F-Ub^juojSOGx7pZ~6ljLHwHf=4oEUI1w|9*Mv
z=LT7z&Fjy3TQ1GJG4>R<{y%2r1zp2qCdZAFB&S5<z=JA6dx;Q#zz!_wI7!}@2wM6~
zX<V$JmPiH$ykOk?EsbhI+`s$MT((Y73qVUIL@3p857PUczuaA>CINrvVZ96&`D0>^
z5ZM-HD?#J?cz|ZYlVFMaj%y;oD2EHWk&3`^{AwYlpgUt@p`OV<^n1g1zle)RH?#|R
zl70Q^IUf`hM1}^I1o{aU^L#WfDRv_zo|D{xEsT22KfQST`#pNbd(em%MCt)CTtf%A
zuoOX#5kgl|l7z9`z`Hggvf8D2F(<VCn)f7R0h$9mI{7y5sZ5LjbeoIZt28CSUAM*z
zdMQk#uNylS`Am`Bc<#vo!9%&>L+aw5*AYz@KD=N{k;$tuYYofYrMKy=pLuK2^Q-t(
zN0i6G+Xxn1MB5wiqeonzG;J=$@1$C7QzVdUS79aD=+yZLOh+ef0RAh8(FaSXNf52`
zR_c|e-+W54u4r;e+vJ}^e^q!mpZ0JF(LFmqKT})E?YWj(Q;66_qG~({^QRq0TDt^7
zQ)rndKt<h4I{$*aTIx1$&3|d$1#)nz<vR5_mRX*+XuRF7rOc({SIIO4`b-@?5(8rt
zEYx&(Mf3n`g7I~`mJ=z-m+rod2LfZYWh&P#=--d+;YHb6(bjRx0%0WQ&)oE<42By1
zG$Y&KhRhyEOeU8{e8I*W9FJBv+#hWltwovq!&1<pjl1Y8^&>+Mre9-3xzCuV4KLl9
zl}j_ht!JmQ7(&_v32FZ^%2pkOCWgzA=wsIL+w&0ac%L(5iP!OM0Psa&b)$wu?T6uw
zg7pY-Wa+1*4y*8G`Y`hL+K=^1XAl>%16SXJr<Z8|(PT=8+C5q(sM2U0;?H$0GrMaf
zh@eTl@GQNLf+ojV-RYA)g=7Lu|3MWAY0)vVb{rXDb^Nfnn)bGxwE=X^ofpvSv2+W}
zhT%%uzgc%ldar@oeLVMf7kK7uV+K1}4qnaip^sLm*i}kAMX-n8XckA;CkP@*ZbPA(
z6{vbtu{8gsg+bKuGpS{-e?{I^^+}1m`|4w!Hwc6leEbqVlyqK~H}}YdyzxI`TtG?t
z;$C(RF1Yvm``xJJ#&D`3C}N3OT^fFvcd}XA#0k7S3Syi=qC(%Z2r__{G#u6Dm-K=9
z%9mE_JLK@vNGP~`97PG$IVVu<t{H=0ftkgkMUl~7BQzI2{8xr|dBPV>1Yo<5So7oZ
zary623pa00@7s$O&z>I=zImn`if066I4n6VnV};uo_ey~N@}GG8VecP`9$?2_Yx`3
z{S1LF305rpjvq|Svz0Vj?A8li5DQ9L2L@a++Z3zB=PekB|F@PQw2OD{h-f78Izw35
z4;<F&L*z7B1$zt=+?9VevFDLkV1xkXuRyRJcAxT#$VGUYs7e<lgb?aWnAngOpmFOs
z;7v*h$RFmc0JH^vlS;XQY_4O_;gZIabSSoE_mcy8{45#1M<LaB9ZVi50PadmGuw2c
zxFFPUr8KjYew0B*-qy{>%=R|7`?>DXj2R1dBD22ifVBY6uOOPenq4cZPB1o(ntDLu
zDLY#lUk2HWPlUjW-Y1E~W-GGwbW+AJA(XYd?62N^)1||6BVJf!|AWe%e4vyC(rPrG
z;Ovn+$ilqLR`#<;xq~|R$(+OEMQy&ToH3)&!<8D8)rB5~v2@LD2l{nDFeyBxHI$FF
zY=x^F<fVx~AVDZJ%@eaL@$d4S3i)QzXNCg{e;JdpB91T+f~u9rJ~=ksmkDY4X@guB
zbFJbQ%Bi<tU*a+_>r7s$m~`j~KF}Syt<`3FK4KTu{t9DR^8p4`5(?p|v<;C6p7ySH
zw#7)-1{7zrL53l#;)Y$EeEKLqtBwA5i33N;uAio(12rEJ-&){rn#*|jhs*iKv-^2l
zJ~8xbsviGHwwAU(L#RB3rt~1xZOpP>e=k$q&pXzux6yPsTy$<yHhqPM2W4;J9|(j4
z%ExC!_&e)ip2I>XS~g<EE@k|ZL+Yu_o~6AOJ-fV%y;|0(Mn7u_%;Rk%U%inSa`D{$
zu91a1Mr%@Pz0s451dNeMCWP@8-MKiN7{hvAjDZ?IRSUniNTbzk!C_nWs{Yp-3XZZp
zlbtPQXJIp~u1exFv*mx7bpor69P6-}m88CILUfQOdo!MpNE%hmukI)J;$UroK1s@s
zs)Bd;@{JW;hJ}%$1qK<^s+VQdNEa7S%Wf-x!@Vv<O=CAvcU2mmAGYnUkyrcVjus?u
zyDYRExHDacl?3KW?t}Jc3UU{R>d+O-J50s8tG1<OE~D#9lMl9ABh8`vqlv>A<8Ec>
zzts((tga~{nM-ECTm6=d4ftV7RJ@0TUQHJxO?pu8^6lC%xx$U-kaz}syY{E!oWtpq
zHYc5hA{auJ%YCM3gD`xuq1G@j+UZg?cb8lWy9WYe?zjw+^6%zxaciYIY<45ElX)c-
zXu9}_uHGSMfOG}~^3t7_|JrdbnQetp&`b&m!K!anf9SfeA=ELrzV%@EmNzHlFugv{
zrX)a9r`HD~#)=8WwmYnP9r0owVm?pezCj{C%_}Pbi!RH15TE{Y+^z~3ESwy(bSgCY
zyCG{blUKXS@det}cY=FsWV7r>PEL3#f2_>``n`f7wixuUs!`-^N`<d*HRG7^oZZUe
zugD6U?S00~q`aj})qI8WNt^rMPpE|v8!B8#RK!KZdw&+u7l1DS8s4r%@X(A_=#Jj|
zvH#>Cj+w`vm;VW<aA=sY4q?|J<{EQ6Pm{(=&M(MMuAeRPwNBJBJCC>);9YZtj7tgE
zitrCIk}QzGUzf<+tEHbyEq}{mm95@(S2(0I_?*G4QefW01EzHXVd4sT__B(`x;E;q
z{NKfhMr&(GOS@9q_rjn<?nP$rjXEB8(sow;IhwyFmGrf9*-Se+WSvIwOO|eD&0)$Q
z&44HNogAdHQZ9GO_j>JRh4StmENu-FildcrP^jwv=_qPN_%6!7YfPwSNpYX&K<8*j
z(c)Ap+|zHbw<WD}Ox!ZesBebZPt~in<azl_Bfh<P|H7-N^#B`62#?pyU8$JQrj3<w
zVpJkN*B;y#u95m+&lgbx7#X}elseC8>}%gokPqZ#u=Npbyb;oBD<d+`{yXJ}xl&=a
zSyJyu7hSqZe@_ZNg`NTa_~E4xT-{lYu18X_1xFn1?ZPk1X^)&;OvUc_1@F2%?<%b2
zY?80}!)R=h;l14tW4X+-dcR1!K@dowF`+W8-|8@~ZPbCA6+*-;!c=*PJ*@kky*5+L
zLS9W+kg~5?1qJW>@vW{72OH6FzI0`mH!gLp{Y{9%k}Po0Gh92YKb}b4snO^873yK_
zRdN?=Gi7`#q^_4usV#Ml8UZ!*mUxbqii-Gg5Mc`$p9e!+h($O>pf|-FUB8MIXm2YH
z<kLQ55T|>&_Rb*eE6|?Z`HhuEsZ#xN7xPixrh-|zj+Sc0!8@m!jr22{>^8@R&27pD
z0%NYyeqRl|ES}%IYJ=<41G#4I*`%JPgmlFLZmrPikMtm7vJzaM%{~gZEhyX>kLzUK
zgM6UMsC3^8SnDScgtfYS+dkKF&~dOAL_T#_IO@<iIymmDdGq0!!0FkE!|$HS8U_Lc
zK6TpBa=pHAT?%N<C2--mcC!o*@hNx%!<X{zUN+f>W!Ke7Wkdj&;a*TA8Gd;9tN<F%
zZOs>d*vf)y{|=U;xn-5=S4F~ll=#L@L9r^VHaT%cS=e%-vVIf-;Rm~}hlkeA(CS(~
zE%+d@a~W&HAsKptn<ue-g*TCF<uboKr#%}2Z#BJD_kK{LXykaf0|iN`^p#|<bgJ{6
zo>4sCV_3+9zg?wo+=;0aA9ruEDiw3$l~Pi=QL(Im@zm8m@V^_e(Q8U8=mGq7nRcOW
z!F%mCHRQ!mXg$3K{}|_c%2_hwMaW2>Q^P7ZTJGC4gK>x(EbxuFMo23kfAd&w%s9pZ
zFNqPv*g>QrWsQ#(TD0^0tVaq`#cVgsld>UGQc)y~t_kFFg!YO)M&nZS4{`dd7VP3x
zlO8Y&kBUa*`R`+sjm|3PX++Al#wUuvXYZ>8oz3Q)kogsl`|c8D$bZwjk+-4Y(^eO;
z#!u+qW$r)@{odQ>l+vYKtCD$u1czhqDc!W;W-q#|>oK-T{Rd{HMV;|a#9V%?dAigL
z=9_Um<IBT8MViosQ5hq3&voooyW6?Q5ydY}Uh=LRq9@!FeBH@r*@1CJN$WaJ=e`)7
z`xK|w!dGBW9bAQQ^8fN|5(T8Hsa?JuAD{u>wOfEg`K-p8i-mHh@3nmXH`m%>8(wSH
zEr%O&1%o%ITbD~$U4E#E`MwLP_0{9Y^_B?O_L<D_d;`veRoEhJ{>xTD_VqKENdg{*
z7y5M0?iOpM-hFE)`9L;4RHrItd#=9wZ>43yONGB;8Uxvp*eSb{{r$Df`O?+6<50cu
z%9#x=pjN7C8QU{!Fm$|@Uy!`O3v@Mq2Jy|jmI6J7#St#-bLZg97c11;VYf@ntzi<f
z)?GfU_N)Ed@>AZd@jAHpGjh(kbX7KZJxHxE(?C$uZmsiYcJV~fCanhG)n$)*!P9m|
z3?`Wc(^u$}_4fC-zdg3k+RKORl`ROS;9JwxPmlRWl4|Upt1-?x>T*47L`|PKXzgE%
zfIixh`CyqTK1_Z8EZ&ksUi1|i_T6Ra?cAfez7@($X8a;P%zW>iy^*W=dR?j7TJUBg
z``UQg#@`NYr{x3w&0!mID@_x}aJ`k+;Hd1lNpmq=o)drZnUuhP`^-CflY^uT{-sC>
z*nSihh<c#LTvhU7@m<S5FRqRIu$*{-)&bL~aF^=-)s@egOAyGU5UtfnNwnu(FKY}5
zIyapMgwExW7kNqfzx|H=MB!i)&JVkH(Jj^(Wv=K4u772q9~h&F@AwE;c>I|e`1HYZ
z`&rH4R6*|F=c@iA?#cf%snPKTr<5r5UtUgwF1UbxS5e^Gq3C@#=~BhO4P5nbuBk?!
zd*OL?hm~%iUh6H);E%icrEibS-2WaX-ar${pS_?*M9};&PL@pGx=330N-^v_kAfv~
zjg=e!Ds0CEp7U?Q$Ba-LZ_1Cq0~bE|7QctQIY6i-LIhAhuL7xB`c%pZX^I5=P1qoO
zB;XGV&Bzv?7@Ze$RQH{ARnasssL-n1@38XGdx)b2=c{$EmKq6sFNCeLQS4gX6hNs+
zqkb}9m6>+Fdp8;nJ36t4ac%_ueGpYi8t=`WUH{MJxG+!s$3NR?!Hmd^%OSzLJ0!2C
z;7xZI61j*(a-D0px2_K1yB^Q2@&2^0jr<nKE}k0q{kxzb9$u81ny;1}?s+@#+7o`x
z>Lz$;8)?L4W33lKGueKZgT`b3eEr%?&BJ*m2;LSdb{*baX%O?|j19yg)gOK>S!ZEm
zqSAPZ9GT~pa@D={<3mvt6KNl;E0KAm+-H(p=uBcqD3sHFOG8WO+8i?~k@>RA|6m;J
zF1M+CkkeCJ!o(mV*?<!K2i3e%Q3ez<;qcA9ZM&Tm-+ELMXB~;=SqsvWli2jtf4ASC
zoj3BoDpXUZa1Q;GjPpETk+TbwA^z@cN^rV!a9{NpF{lW<T&W+&J^3$hU&D`}S0c+Q
zifD(gCFsyoGvCjOOq(L8g?}R0kXh8FrSzw)UFtH!PEli@g-E`sgjgpeH0}kG`z^p1
zQ{_N2p4=iDZ<ADmgzvae>Oc|rLgFi-Wy3Zorz6hgr1T>etV*pzdD9j=Q>Iel|73H+
zdZd0Qbm32}QSL1`;!5;6&XmfF<!<?@(9X(g$!u3n<O#=?S|Rmj2?P-l!W>j@J)wqL
zq&Jo9Y6Obs(Ae^x<||PO<wGYXPJKt;RkoQ;aFBm5r(xK@vNQYRS?6D&U|?ea>`H_%
z83-wjcmGj4du+jB_!?YQ^z`MK^7dg(4qhO3cK-hTqPjMxP0m=)zyAqJ_3gWjtsEFg
zF5|ofZQ#u8llRk9c0tv6!e671^e4UXw@!yF+S5q#r2e6~gNP%qh9FVxa$QTUo?X%0
zCA^iwD?YVP$0wmZe<V|Ph-ci&a`+hyp&3?KVsaKYiYx8p-r3-C8u$;MjiI{Zb><sR
zrwWhh5wl|3{Z|uQ@g2<lyY~Z@>2F+TLJjKO*Za>1Rq5F=J@p9Df4fO^l6E>&x4%P=
zXC_}YFrUs^n+r%i$1Q}bl!Tg~3@)qs#W4T)r1@WK!qncl^B%e^NB7z0+?)B2a8CS?
zUPE$5TxuQm-RmLJ?<hw`v;3=J-8;PC<^gjcmrJg&hwFoMYuTw3Anv!;+njHf;Anb{
z?S0Cz=hy$YctHa*Si}EJ{VaGzJn;NygQ_HA^ybD1(E6bStqFN+40jWg)uLRXq%i)*
zrTYgRht)0NJLP%-xyyx5Fh@o_gtM<CQaW{-pU85wdwSb?WrruoraRYt_ODbC7u;ar
z@mZhFZC>94AA=6*l#+>>RF<$oTV%?zb${&dRCi4XL=zEj$26<j6~p?U*rk|M^3Z?>
z*PToF@x`)=cN{j9QEE;?$`hb`^A5uGuw3%F)Inydm9J#e|BkuL>G;P4n7;$|H=t63
z_g`xSY1dpA8n{!)r`7YZbO-#G_J5SycMDK3_XG2-b3RL?ZpUJap2uj?E0Xpct^1>-
zm-p{}_6KJ-fG>i+_`as2<+c#?NoL=l3Dx&ha_cR`JuEVp^jm_wfrRn4F+grZG$F}c
zqsdp}dDflUzha#;^0AX~u!i4+N%hVu3JPCO@s2H8IHMSs)aEV3l^9Z3-T0~Z%Psm~
zk&Rw40v`Wm7?LPl9V~(tK>)ravVzbu1e>CrE78S`!fl^!)tw~jIT1&XGQYjF^0;dO
zFyz0RYko)KWu`nloqgj4?{f(te2b@!7X?Xa=l?h>>>=b%cFH!i*f!O%x$95S-|>iH
zO7Q9s?cM7G>OW~i?hO9wP!{lrGq!b44$b!lX)S0FU5dMYn@8Ikd%CPfgib}fUKgv+
zo171E)`_fFR_1fLo(E<L9YNZvh}w3~#ZPyWE;Tu;1mo*hVv_qrixLff!R4pYXiMJu
zc2%t{j_iMs4eL)kU%FaCFMQouprS_&6N#ppzJeq@p<yR@i9ES`hZDwfnWSzz8TbG1
zCce-+>VJw5<0ZtdMW-l8*kw;7tpoG?Cn9^9(i~r45?AeJcQ{GNOJPJK*Uh(%m`9wV
zu4D~;rKrhA7^=|;mf&Ux<)OdcEnK>xpA>oWm8i2S(niP6r;B>iHr&S-^M*yyzg9o?
zTLap~<UfDRKQ)5)@r()R!EoZg<K$q9MB^emOC1kN0bg`3W^5CO`L&h3NinVo1M9Hm
zhsxkA(ew|?d{%oX)lL+i=L-6Z!ZHOgW}$L5H?o>BrMmVeaP2U$M`zAdSR)4TWu5k7
z7Xc={=eD<{R4vzCy&gGq!)ECcWv#}!n74@6t_;+GS&v8?N*K%s+!<DR7R%RlVx^s#
zRZFDN{DZIl%Fewqd<q!3a_MS&x8M|_<f~k-r)#hXP`nfaOvVPGL>EKqWs_RO5DH}n
zJily&e;N{BPTa}ed|tpyb-&95mJj&f1@KasHz^82UHM;A`o9!^o9jOP|GT(yVQ|!c
zQh;<DDfmiM{ApPKKXs9z@T2}r(6cu#M(#<d=er3aiwm;2*=%}#IsT_-hg-z{^LIqI
z>$K?otjlnEU(XUqqCs94oL)A|*F#Jk;?Ie3r@3Opeb&ia9#h}MEf2qX<THah$wmF1
zP~FjTFk&mKG$<pz%o^=I&XLg@A2F_ANm)a`w=}OJ#FO$p{=E3@l+ab-V08yIt5fTo
zZGO^keCevHX?WO~RKp;Fq)^C~rI1YLRO%Ytzc8w^yP5hql}jWo^R)oVJ$7H8$j|1h
z?=OSbAS&Jma#jg}unAHP`T{qyGoZe%tvlIl!nBXPznU_wLg?a;m7*LRs-oS&7lzBy
zu)Cg%1O<I1%#k8|qRHr*q0z1;stutJvRi!Fo>JZUeKWd<)Rgr1MTqq;i0LJN)jP=)
z`s6X6N~8Fw5qlO1yk1jx*Tb{L#&GWUOMHdQ6Ds@l9RbGWe;_6~`ppSTimUp$%Ny@+
z(*AK|Q-NOG)q0v+n6HtQ`2?T$Z#~Kx;v_lWA_e5$^DSrU=gT71ptxcvCwGBdyF$#W
z@1F>~(?h$5Yh#jwE0EmaG6k)!8_17VxrOJ)u&OV<{X`Bh{lKvUaeQu*9#gM4J=o`W
z)2+Qn{G}}(nrz9g8&w4RxKQJ9cNtNew%8J2v@m;u1*zOQ=Q)H01<uONciIq6J>{RA
zOhEF9>CG&uJ^1zI^zV@x!*vnO9JmVaRAmQS94jZMKuy1XX2{|ao$P7SHbF1$;j@>K
zYfbCMBH?es9j%sZ^Zt0$Pjz4c)CkZ;`B|-eV=@DaWB3tlT~p0{en3e0%0$4+GS|!u
z=w;%%8WlZd_iI|nFd;`=PpKjj*2F5rTb!nTF`VRndW2)$8jnx$AGFHR<BPC}FaW5+
zFM^?>8tlncBX-gD_1x4MRFTcwF}uDdwwql$Pg)Ygo)~<mX)Ddoc&B~;RJ3M2sXLqQ
zh9sCzf;Q59g2MkT*BgU{`CZ;Y{@T=yQ)Td`Dg7l^b<xxO<T^`gKjM4h<HR&~I(OyV
z+5eozeZUEu7&m*k{vrJ`w)M+z9P&^N_9Wy))S%Pwb9myHp^c#8#+{lY@f^0-B+|aw
zHyTnm0FT*z1@K?65fw>eS@THFP)47cnw+oiIHBoA8`kDze{hHC@bB@IJWWW&<k^zh
zfEa%Bn{5vlhArz=qLuaj=fcSw;;dG>A`7<hO}e#Lw9Vt2X$a_rB*9jPiKFFnH4b?#
zgV#^wg&?|I2G%QBU1=?sod(;%^!~Rc@e7r`<8|<buT^7JV+tb*wAJ#%C5ocU+}v(?
zmy`!*1zCLzo0*rVbzES-N4vG8XFT!AAR&$)R?u^`l}Kr^{O0?I7v$Ce|8BVb?xaSC
z`*VVMb#dgJS!Xq_sU$_0j+o?XFT@(Dj`lg*rWrHb!tNoB)%PS~+!ShVl$(TK%V@Bo
z9*erhTxO%KOyXx7f4~O^YylsOgM6Kf3-3ZWPpXWxaVhHyOY`#Xaiy>aIe*5wiS;Ei
z$~It7;si5T&J>@6gCuUJ#VK41NJI*y{u6NA^KXL>v9aDzD&+kFVAi_+(Sh1_vMh2A
z!0nTk9%tsMet$Qh)073XWoG@j=AKyW-udsB8%kCg!qH7|w8TO{XIbTIWDM2Q!9J>+
zWZ~OZk#&=_D+(6o<!2YhK)o5pBnu^VcOF-&4iVQytosht?|dim=D2PCz~{ZWB;C!M
zA^Ht*H&3z9Tg()rtIhPCJq6F|QY~mzAoim-<SIRyLhc}Lr<eV)ApiYvIOZ}>{46sH
z`>?A2QjtIm+0Y%_9hL+Rcw=^-&>3Rfyf%XIGk*TpuTf_mfo+l;pGJg|b86@2tIE5L
z7K>>uqv#1n*902Qpilwe*87YyxZeuE@*NM}m3+F30syS19tz`fIB$7aA}<mbj~Mdz
z<!iQOB6=CAq4B72M8PPPK1Sr|<_gKcgZS-iYLQsG0#4GOe*d02>?IudgsWU+$giQ}
z4KJP364FAJmJ-$xs{z7Feni<2TO}yUu|JDl6+@OrQp!C!JOlE910OR-mno~W(lMRw
z#IXfSjniZPvV&RNvDiFLGQVyfk~%{;e9t^~=mFzJ&I*#AiT&>IQ_A!X){t{A@8g@E
z`{&U~!fIphrjIccxCFlO9zakE!1uUI_8pc!((eTuw;iOHAGR(-?#q;)F9@uUwX#hy
z`UgMIcCP)-MgAr6VrVkx38z0uc!WwAm0m_x$x@dV?tW`k!MsoBnN}S1yN_A6&X_#n
z&7ye_D0@eSs4S3DEyL-~uRl!baeH1XYP^me*GO6DS^X*Qb*J1*`J=0N-B=R&Ws!ey
zu`4(Quj2=Z`x@hDvuFwibE*^jIwvzc;z#k?+p+At2y2fG(w{e_F*owc-<xgEQuHxG
b0YCtH##<Ti0e~0a;`93D+ZQ>KNU#3`DhE%d
new file mode 100644
index 0000000000000000000000000000000000000000..c9658c727e30a0278afdab266b7fb833b02baba0
GIT binary patch
literal 14931
zc$`&vbzIZ$_x4~gYJ^f7jfymk?h+9NBm|^kG}7G-4kZn`LqY*Tx@&ZIcXvw1eyE@C
z^Ljn}!PuL7_c`}<pL3n-oPAVQl*PxTzy$yR_^)0*e**xZG2Q>&jSam2P5+3U?EVGA
zT<WzH0Pri)`&#Ae{d+p&mv3GJ0G<p0fPWAGaEZEq-2?z!U;w~28~_lG0|3bF;=U)0
z0sugOvVxjS^ye^q1~Zqqj_H2n(DvQo?#l1Ot);o~wWaCqzLA)!^{LUm(ZM#hSBUX}
zwyKV)AK$Z;&7+40TW6<79qnxhGtQ<4o6SE~A-+$BCFb`Ij-pW4gT2V@?d86%mZ71}
zyvi<q8I#qEySCv~)E%k=S%*U1s=NHiYTYz-3Y{7sd}W>$omqxqKNV9kGu+=g(chTV
zyd$G-TU+^SsIO~$sAqn9DmycU1PXg8BZ)#?^!0b@YN-v4O%04poE#l?5BIsgj~^WB
zL0zK`cDHE+Jg%-zJEu;AvIZ9S?xdfIPtGn^wQrO+_hq#oHT5rer4G!m42}%6)3n`c
zc@>QgbWIL+o4aPH8+(4Q9vbg!ofsW(iEfnCjvO1R2}o+09PPQ-+#j2qt0*a`8M|q&
zuN>-Yy*fS0uUlK6I^4fQ=>=BKO!R*%>_A<hEX@pkBFZCv&6jqa^|UvAcpor6(3P5B
zQ&HFaHKX(3aAS34;r8Zgdu_ofDBmcsxVUk6u&3?f4uvUOH8g)dInZ=_b3W4F`&RY!
z_;A<MVEe(@-AI3DeBN*?viaio<y2qS^C8seP}kknW#+Hui}Q=t{tE^BACtp<L%r<+
z#g}7!qrZOUCMQI<cK55;X0A+k9xgTw4fGi4Yfem#DJi@d8|yk5o1Pfy7V=+7Zdl^5
z?r$F4UFd1c>D%-5a=E#_86IxTY@2Kuo~=RF-`re%AGo}`z4$pXGu+)Z&|i~YJcDV_
zI?&yCc7EKpayPfK)!Ef{ad}(c+CA3YI<q%BH#Rss*|xK>wKy_0Jkl@7$2BtAwzzY|
zul89{O)D@e^XB$qyu0h>?s9Uh>9vl6lXnvX|7+CkwM|qLP$d2O=5B7h^H)>f^l00}
zWdBPA#qs{0(Se@fzK+qJmcfCJk&&MM0puO(dbGE#ue*P2xFhph?%nP6SYKCKT5?fo
zm6uO|ZsyHI-#}Qwa9>y5b9nNn%Jzxrww!_@L%1Hs=NUsI^YMWW6_qzA6l!#^V~#vi
z2LRw7e)U{R%{|#@RtOoj6dfrJ3_9{e7+miQoX!rOm``prpY7j-Nh^)-y*dE12<p`-
zn6=!owwud9Cu6xpInChMzeelydx=bZMujUwyMF!TVqVw(F)wo)CTYyg13~fZI-x(L
zyLt;!QUWPGK_)+3D=jrQIfTI`Z>Nz>O(!x26feD~uh2)EVa!S!xY!$tASn>6DjytJ
zjhTciRX5x9_4w1fPc$HqNsL?bQ?zCo9}q8et(LBzJUxZnqv4P#D>3LB?ebkM@tbu8
zv#MypqF>kYA3}PK5OEAHuf<#n0BEg{yo}Uw2O((QisE!ZSu{1Y*2pqR)p*jDiT%2R
zX}^UIjqjk09NF##?y0PCzvI+8&TKUu_%ey&0Pp4aCi#&2?-|1dO*-rc@8DqMFbbTm
zZ1h2^#ol84VLM9F)r0ZzD3t>Ubebe-jk`vBvas2xvVuUps6s{R1k&x$*Dk=p@9FLr
zFhvDOopC9EEEs{f2>+z*zH&P6&SODzZW3DK+Xxd7(Se6UCjrJ@#+4m+0j_G?YvW?`
zivf7sAlJ^3SoZpK<X9XU`UeMb;|rRcdT_r41S9T}+uFA+-SH%<?9@{UQ5%bgQktz6
z^EJGAw%&Mz2Ze}McJQd>6?4N-_5Drhm)F5IH>_NU_l@k%5VCI3IA?@cStc;h&>Do$
zFd`M^k~bo2=lp1x2RIJ9QrqA3UkfnwXj<|I0^@@v8($NJ_ks)&tJPpQ7)W<UN)4(K
z#4y<6+{MayM)VzMG$8X8%kuXO#*?3tt1kYpOl-Mlds}?rx-f<MliQtj%k|}-Jl2m+
z>^NTvZbLi?>HHz&ROc#evve8VO^0_8KU~p*g0>%m5MO8x3g-h40<=B^NFCNMUi&Bp
zf-7a_KNR54Z<O(y5)g62dS9uCFn6ZA%0~pC1=<BnrB{Ujm9-IYI&b<6zs~_^!OfD(
zm_(uV+O(ZbfEIhWcWgjL5jJ+*3-VL?k6t!FL#F2s$$jyHLw1`kzB~pZeP#26L7-yc
zsSZi(kHmD5TEjYE1lUWrMPuJ#ibsT$>_z$@=JHNrds1z;cif?`*`oQRmtxO##r7WN
z4h;~4XeF`G@OWM9!Hl}yhT>g()e`O32E^s74{uLArm@efb{z}>6yjX8FVQ`ehlt4}
zjR>PKKVTy4PY<88z|bI9SP))Y1*XBOjL%#^bSNaffL&ZCwNvyn+D^b_Mky6`fcIRF
zq`P{OmXFIOUt!WVoR4Ru8OBbLtU@qdyYKpbrkc%Ci{xZk6A^Vodub2~q*u0f*|e+@
zJuz5s9Pjs%BES@>pLTPya<SqAb`VC=o<^L)tx#nz8Q+QsE*yG`y<bu#?J)noqro!H
zu6vD1=O6F;iwl-~+3<Dir+H7<!3ic5;s{Yp<na#*)S!GWMK72PIa@t2jNe>dZm|zp
z!r)C-gdGALu!w>d(IC$LgPc?l+^4WQ|6o-_dju5B1E~OHOv%Z@MB5fSi%Z;0i!|-*
zidqSODSlL}?6;|zai-ne-bU~MGT!FJ3L`}j$PmJtG#rdHh#5Bqx3^K%z@q11IVLt#
z7a9+Zj|*6go8<guCtkx<cXM>yp@oP8t3uuewJ=B1lWeLHUB)eOo(zp=eZs~>sIm$s
zYeRiuH;Wdl78vhUg?i3Kzyzt_lO2zuo|B`e2XLk$-TWUdpYVw!!+RhYYYEa<p<i^M
zsV}(M4&Zs_RYw{#ri6mH{c5`o0pDm}dI~$FFSnADzZ4cWM3Z|(X)B0PH;H_F{sAp9
z6^=>p$pn!7Eze1yX$vPl7SgLIW#pPK@B#BtAEYD~onEy6TqwY>lY$82xUCsSnu-nU
zVNVLUrMfBFnTRdN1wXia@#>ZzjXwE22)LTlxn}<%`DuVlsIV?Wo^H{*?^@U~Mz9o#
zQ-Q3$_o?BJ!;Fz}>^!5@U?NEcNp%#&68c3aO%AeP6yGSEES2wNvxK4CZ!CD?fX<W_
z@a7@*u|n}xo|mxMKq_YwJTQ0xXDEttim^7iffnw7g&kl?-831{ybK8TrP^y*ge`%B
zo;OE?%YX%JXD7Rx7VA%=6Q)|)--Gc=A1v`cz&_UlA%@p{=tH36Fe=d7Ps{0_(7#wo
z5|JpLRfFl=!<OiRo+w8>35q2n;<=Do^uoRceyLGPuCfo5`W#>=1mul=6!8541bYkI
zlpdcz;5_r1$pj8S5KD(y%ir`~&~EX8!7Q?n9MR;vvfSavf^Q?FR&FO=fcybQtHnY-
z-uTGX?eW}nBVNbq^VI5h^n{SJr?)qPF@~WPL6LzH$e9^3ymP^11xL+thRLH7Je$bN
zB8<8?3h@}S)GEIoFTC%i;kc}~=TDNW<8K^rf+T>*XJ{gzE?SL)3#SjgE{zw9vNuuh
zLv0PJ{d(2QSL{7AC7QWzUXb)K!#zEpo));UywO~frh}D1ApQ_BF{xn^nAq$7_c@HP
z=ZZ>T@E{2$Cr`%O(+XZp^b_I@9%o5bOZ#d<wo6pk?%V6uAKrXByIm;Nm}(O7_+0{Y
zY`Pab$XpF#_N*T|djw)JAhQM~FC%wa<_7M1MsM@-R2hHgkWGOAbu)B@Qn}@_6Tf%*
z&V}){yZcBRV%OWs75%%VANsd-g>AjU`3+bN8V(5=$FT<;oDHdUm!IAA&VLAm%$>V)
zuw5N#G}$1??PUCL>#wiQ7s7Vf22$hMhd+Jxe2VGH{AeQpiLK@<eOavh&=;@IEu9K$
zz-7=rFyw(_18_s=TOy`Vbovs88Jd#;rt~8wEZ+@`HL<A<J}L=qZGMUBRNJ?#kDOzq
zygs+(TyHo&7HI@v5UK7*Toi&2_6UG8y~D0eFO0E}vDAGs2lGt3zVvQyyls!iXn)Q?
z^o8ZOQ^xrH28#D>%Ptdl4`_(ZEXBmx*wUMdzxc2QWla*gh&aR)GRpMp-`0dIEwt_&
zEhoB0-te%muGq1{>eODE`w>47-)TP2@5Md$i-%sCh&p{X6l}BKh7yq|v8Q&U1yX_6
zh<g}4xpd8{dcmztkFM~M@`Z6NEiGWlWRBzpGiWjC2Y)blLfaq45{iZqU~@P5`d8A;
z1yu6WN=O@F5G@D{cb{22b0iAa?We;J^cp$;v8%44VyJ9bC4_n^y?hfIii>!05_-VC
zVCPe0W^pNg@=@XPZkta>fLq~B!kDv`0K=C6A<BD>g>1*VhoFp$P2u*XIt1WCT#y^0
zzjMF<y3XakIX2F<I-6GV%$g;Lk20v`RTs5t+lU&}Xk*XasOs_3P*x#$zVwV6V`1PH
zuk6RASTS>Zc7Eq!=aK2TeB|N5K~BH&564Sp_VbjbN5~@JQKf(Of^m*cErhBPCi>av
z6WTLo#QeMw!U$nax4Q}`#}Ss&uTAes$1BKu4xw0Rc>~T<3-}iJ5}ptE5KwL|A3;{^
zjb4f4-%L>}==zJcSnu$G<^oziS9&)dh(oeY+ojy{2{yls+zuC;k>+Y0xu!XA31Mm9
zkVL4aWuS7Pd2pB_6(O}Ji!aR<l$-v1;khyCTo|R+fla-x<23_P?LM!C+hcyYnC@h>
zZtKWFu{LHnB%19nRq|vK55Rj3)K`~lPPtTSsieaVg74j;aEr$ldrvsOJa+p0W2v+(
zGdVkA8SL9VLxLW(nj)e|Qs=QKqH#2vqV+08MHoB)RlMQX$y+(GXlMy~zweqm(0Frn
z8|)O$c|wJTIAjzD=YI1y#O(EHYcf;iM5=+{p6F*z-2suV=2hu<a!PRlG(XL&Kpa*9
z42OPnCNGTvF@0xPaY0*&u~w2Ea8K<sa<vm4w#d2GCX@ql&;_AGy2mmY1oDD_--gT+
zVCLlJ%=ADLQ?<EUxu{I-_g@{TRDY$R>!j=agdIp7L7jX}2^AdsHfqaNmIvdqPCLnT
zmRkR)gXN3Tp=-A%Q<J<;qpy1f*!_pvIHaKR%uKHZornQg!P}o6scCnq^dD}U@oho;
z>qwC_-Fj<W>sLpL5fvg=>Rz|><Ff1oJtxLNc8#;1n|rbip;+dDQx{~R*aIhIzJ8D0
zlS~d+mtF^Myyd3y^{~ianDx|&6ivNt8F;NgAWuW)TO3Zmf>`N}8SrNidLk1rLc)aa
zydI>Tkdp5Dba18y90Atmq=csLDZHRFiEjh2m_OQ++S;On$&|zV-%vezeTg=c=zGH{
zr0;kG0G+(YYx+%sYw0j=mIpN465f)LjNLd(U~uE_oh52IOr_^=@HL`B`XUY(&(oso
zPr;Lwd4}3dNX*^K_P0GhxZ>wtx@UU<EjnEM0fA*%9Jn+FDafX@YZA??kPUBfoOek<
zuk6FRO+yhq(aFpdO|}x))!q%bmhaG^)K58@UZ~5q;ef&jK*Tg~o*n<L1YCH`Nb@3~
z1*-{r^4svIPa>p;)}N7R_=pSG!FyFH7n)+yHf2;cx$cg`jsKV@c#%w~PIST(Z$GO}
z@2fcRYzca0$5J+LF)tQknEQEQCC-;?Uwg@88VI^plkEqV$l;r(1!9<6TdhIUI4qSk
zw`T5pjz_0X^%JFFiDY9uAA&!s!!@LfC#{jRzxYe@oBhwTSu0BvV6cXiPh9?`mwy2I
zeqB>y3ZvpWQadsIDh>_dkA_hY5)h#TmnI&4Y7VI6gHq|w0v?z}>CeX7+dc>aAtUlk
zDRk<gkY2L3F@a}#DSbykhG?RtCwC<d6vh40M^MK?ES4<DVg`nS(xEURjU2eC4htu1
z?el9Fiwq2$+^VnXFm4GP97aS(liBEy(xY=IC(T0KQ%`2IE{%Q8>7COc0Q!fa8Szu;
zC&;=dAYK?J4v-t>4<m{GEeR_=FYura=94nUoiMbqVuTxb+Q6`-$MWZ%1t~kgC&1y&
zw`N4%?A`a$Tp6%0@>n`guxbGusNA4&(QQLVbxk&$O7!A{uz(hyfRJwg{qcEI4Rx4t
zv;DJX40~P?$*U}|2Je7Ry{XG1n)@cAevQ-aYUK9|46}5KS&PXk07;W)L9qYYkr;=h
z?#wQFTb{iG8%fp<u!aacbO8o$LcVA|NU>$2r6&ZkK9YoF5WFYcHDXW2YyWgaj!4^m
ze=B(d;!Pz6nn=?RCYuwo{4HTC^+I>xg>I36chdVC^3hc$fYXMI2xEICs)rNU51yAM
zkN{XX4kbZ@lC<2xmd35TTamaJK>@f567>GI;uOL0*f|->mtg5tVb*)1%lqPDFITee
zed$OBaco#!#W3#IO75luuOQnB=^^cLi3|*wEy-1MYW307%B0v?-(|_MN(}AE-hxL6
z`6dW(7q6(5xpIS|f!OjX7(dVq<7Z!`zoQG6PN4?ROv%0Sz?;RwrZfAjZ(8{wCyf82
zCCXh~&R3y8MMGnOpmlqsE~wi7V)tjiw6~<_6zZoR2a&Az$K?q0WsN!&0&@S!WeYkh
zIwDz{?OFAZaIGvhDoMx>aeFCab!H-zQSGuT=7-1W+j0^>mmt_EReB9+HXWEaWLsK;
zyuA2CnVN{vuL4Ut8w(c~S8}&8)7p;tp&5U}F;%c%y~J<y;5nKkUmncmxPv0VrN*Ln
zZAVU&)WzDhv~JFc-_Og0<Pu@%2ft&EX-+Z$X43onRnlQ68Y(aQC=ZNiE^=7dn$?U#
zm#^|skh<X2#?{9mm5u9QAfO?Y4um-gXE+N{q@leQqj%V|Je+*P_X)@Hg}?Bi)Q%*i
z9gD04tZB~*1m=BNWomx}YWY!+vew9xQvkS^UXhIx&sc=_<s5-~x)k-iHQr7hxtv6-
z!9^I-&ljlB$J39}q~1*yv_A=akHONEeNeS_bb^3;k6sB9tqc>YPLxcMleUmZUbb7D
z6-s>#`7V2|^zgo`Ovxo^0id;3rJr4WWFU9tqEc<hpVgbzvm6}P)_WiPIi#tXCQ#7=
zg9na9FDM$hBuRBOxF$V#QS}?y#Djk9A=qlTAA=ik^`LuVyCHks78Q<jk4SIiLHyma
z>N%}=Dj88Yo*slHDjbCsVO?do0rE+ua+1G~Fqr(TgHgxtJPA=FQ6qLrZT?_Hx6<?W
zW0WlaEK#K)a6s(uGG5|-KVH_$p6}|5!DQ_K>(RicN1u+Aft&le*b@Atj;I*>M4UfL
z<q7yyJCaUoq`#O5laSAU-xt?Gqxzf^@d)%skn<*0sovDRAuqN&59^!ipmz{YtY-i&
z>l{lF#`Ni!b0^4LUB7#JztAYpRIucAs-bzWXayx$M^Y7-1t8T_1Vsd*VGw1(Cc17P
zEi^wei%rAd7dM1s8+;56A=zZ!60(t#5nYKN^J(jmQMd<`PWN*6y8nQ(NpiESj`)OP
z-IrvxrC0RZA;osfU09m<X&S5&<NjLD{FXVaBl9QTh?p7T4@2dwOTyjunYm!INoj(d
zueNx~*)zEoNd-4NrIO<AkEv;4ipI8TT68^YTGL^#w3fCrrx+6JRaO#Zwpi6Ifw?dO
zzBm5d%B#+sV^pn=xG&Gq_ycbB&Qm$f4mx10TQn_z`TmdzpI=a(7-|hDyn86^Q5<l|
z3|bQacY~YN23E>IEnqj&Gg<C?N|6Ue^fuyUOVh4HXKTFznirqtiXxGYKng8ck;7Oi
zsOAf<`&E72Or}iK53Gy%I33&i@jeA);r;Okp#1{v?>|e+i6)V~WEU5^9X>q$+<rHm
z)@CnQuPs37rX-Spp@Q(5&)5k+8-$w=@Z=qfygtUB;eqrKIKeIi+yM5hdlvur)^zmd
zvX@_Ud_rJH?;zX|o8+ab*lqIAVU*q-E@E-9pOn?YgcTo99PYV@YyuET^7eQ(Tc44Z
z25U*U6|oLYpRO4A)^&OyI#Q*!MFLFKFOeZ-C9zlckm+GE{)vxFElE=@y=`MT`4zp~
z?vn1SY(ZeY909U@{0pV%vDJiYY}^XPD;n>AhZ+G>Bs4DVMdwOfr9S;Ba#wPbd%@L=
z>E=pvwoqIC$&j&F?^M`*Gg>{J`^Sd>G&+Baw=cLxd92F~Ki%CnG;U6|nPWasN~2|3
z_@Vowz3DI|Lp8cNt{5!{L$ZhIk2B*lzg5}p4o1yBt|(OckyG~={8Hy$PC26P0fF2G
zLw}Wb2fv0q`43_A?Ip+Duu4>LPmZm+Sf;I4Qbxp5&ERm!!!b_6fN~n?jlr$1|2Brk
zTztwvZY+K^dABw9HQt)>Z9eDcsBVw%oExba1*fZPA~;E~mw>YH`)=>Y`RN68p3DF3
zx3i?a#;fbzJs~!cl!BJF#(}&228NcL$+P33u}=g%KP?CR$gY*n(paIf$wu(WZ12j7
z@b3M`P|0gg0NV4@01-_|A%{Mr&iGk%pXae#n)m~yGA$A&K*-Y`FQx~B2c1oTdFgLt
zS2I0)kL#_|MMCN(%27Disb=?HB)Wt$dbR&XD|N}Q$evp7153=e9qoqpj`@1|Vxjq@
z*NcKH$82#9PKq^*CS_PR9uTq}ROxq`!tY5l@$_`vZ$bU>!5z$I*&Gpv1Fmax^qb{=
zy3wHd+F}jLC`}7{eXCI@nmJcCZePTMwpNBU*g*3qD5)8o#w*Q~hKyz;+yvA7gplTq
zmy&nTND*_nD(5PWWuz&kzrEaOG+w>|O0M61Q*QDp1<*nS_wQZ*%B~3-e{ZQY>r>to
z_ikmMofvwvhMo-dw?_H7A4-9U)A=t$j={Nh!tuc`lza46(KVr%_fd<N_hs+v7_=W}
zpdWZOm1LNBgDiM=Jg-A*X2X!)m?pg$JWEVx+~OM)w?5PG_j8AA3j2R(D^p8k`^M%d
zB!MdIO(_j`=Pio%>~K@*Aog7ok+J&++R!Ua5>p6EPL955oyI9Vk}V=xR@A@ZPj;CZ
zuQ!ANtFm$e-2(M|s^?$7S(J{DoaRNaJ)>u!sgGWYxYa<2fju`M=h`|COG4HG(~*Dg
z#gI)8nxmeeq?(YUe5fdY^)4SdEuy3bwa$Gos)?7a_e6iN+vW+Hg#qC`DC3cq^9%=0
zCLb3X%s_~O%DvtY+oA^JrxHFKh7sU&G2weX>Ghk#tSI|xnPeEPjQS5AR<b^wrNkbO
zPmKd8lP;qd1`3txOhl`1kOZKKxmJqBmh^!pBHqIk^Zx;Vx=u!GQKn(G2s`eS7c4Vz
z=rK6m_~Pb$#f!aJI|T0YY9eVXj(!pO81sLLro*0L#_6nPtTLp+w`8$KE-EVx5fsV|
z8vpqKP|V$pA|gh5YF9^M08%D^_lL%eo|yi0U0n^%ABVx}6umWw>Q9cpi6Y!zJ<2t>
z<APa_CUp}*PST3C@1p_w?+iF%zFkPz*LOWu2+cwL$AzNs$Gn+VGNMDE3t&&)sT8jx
zHO@awf5fTKHm|ZEe&=9?e{|wIS27iR6!&EMbm4b_PxBGqbuz^|BX_S-o!$6p+Jm}}
zIOM7JX&y)KfTlt$B2mu&$kJ>t@9T!oLZJ|Qxy7}snHedWzPdo;b$P+9?G5And)t^i
z#kw31jT0Ji(UrI>&LBLqk7bUuL;qcBVHI)0o9?ZKt+c7}s+3ns5xA=m8WcJCdFr`i
zvn8S&WY^c*jk6hNe&`N#9`)xW4m>^mYn17Fc=!N}3Z6)Wa_-00d=l0fI2a5z&cAVe
zA<AZ8$m&F>Y0Zw(kHj+XI#|_t@Yy$%|L0>g$r+V<f+!_1J)F0z00prl`_rnIeq6f_
z<k#`E6-mC0xLhOo+M5%iN<;ihSuVja{VOrh2%qs!f_lKMym#5%mItn;!a3J33%yMG
z1sOt)-aO+EdON#vqH62D_LgW6^=WDJ$-!cIN^l8N-+xhsm-o8ViSlW#<1Tzqm3j5$
z)HhVHl=Q;MPIMYL$xc^`dH1+F$lrH{(_5YcgAxXImz4VFCU@v9$_})$KwfaB*Vs%Y
zy5XOl(j2~3x?ma?yyhtoDt_7f!opQ%d}q}g0S$uNu>GacdlH&W<DNZ>@%0XuI%r)^
zKMQo-dOYTFSJD&IqB#Ldb6lE&CHVUe4rzdc=#t@k{{r*+`|VW4m!;9KKZ&8-JHw$O
zjix!TiIzFL46ZoOqqTaipxRUNF8|#*zT(->Y)(xryKh`~iVdxY&Z@;9TMNEJcO-LD
zF<~}yG+c`^ghPOuGr*rzoR}dQ>uA#Tjio<%VuvX`Wz+lx`EJTi54v0@&mHAn$P00_
zBK)(hsoHo~nsBcYKT~eGyuqw^(#m-=f>CO>dTm2kYd12LU*shC#rPZA{}mTLb}Nyf
z!&E+bs%`$C`VF=tdWh^c+k-t`C*M1x&R6lzu3j+!|10}!=?Xas!N*+I@dlJ}pLd>A
z+J2own3vongLyC(K16evAJVC9;nM(YWdEv&JRYq#gmdTCn!g-XhVfD{AEI}}3EK!(
zJI$Q}rUZn@DavsuVVeI6S2%ZQ+!Bv;{6MT~!pH)Pl|gMUOl%?dyyjE|WF|d+J%I0%
zb1~oJr~%el1gjy7lclhQ?}7ov3CrFqaD2qLKp)iT1p4%5ez0%wxBJX_N6C4A*vD!f
ze^7x1W<RtLPn&$TCVS&@=&NCV-3~J!;omxZR#3U7rjmu6tDQcFOy8W?fW3_5JtXD^
zZ*5(6*D~tm!Wv5zhX6m&@~vBc&|?2U(O&geJLJ5G(a^JRo~Eo-JOp~grCL`tH^JRL
z#7@2v-9jA9EyNXFQ|t8<<E{X>zM%a*9mw@<LU7rd6iP)>Ij=4}+?R+p4KlF&RfKSN
zwp7(c*6yHZGsMj)lAZMGQJJ^Lv|oCxgx}S|oh;DX+s~hlw@lFGS4>%bS($T8Sxi`r
zbGGx^`+Bd!Z}|lrLuBH9cQ<_}0>d-I?->=X-J=I1_Ql_zMfI}YqJ-9C@1>=n1in+e
z%#u|6>+_Fw<u~9^unb<D=<S{w`fi(BE%s#eyvS46g`wR=W}O`@FxU?oOo2D}2oQT}
z-Q9Y}WnnPJ@zV5z4#xAa<q9uu3sjx71DF^v3qNK>?mmVpI8}KxD0@<&6&>3$EZu&-
z7t+B(G^BN8{68SQbVg<FxdS*V46H*EI!XQW6>q%ydnp?ij+nl#s=kB60suUT&BgvT
zv_cw)fKxmee3`7RP>96OWv=}_iyLIQh1pq9s`!EP&w)0(Ydc3;Est#}N8$JF&F%Lo
zgq;=s#y$NI@Z61CK|p+QP@lxBaxj}GS^hnPmapfJu?TlWe%dqyYBKPkY^gAMmp5d1
z2digAl*98EjF;r1@001Fe%Xg-A;jpji&`T^U@ZaYc$$%N`mE&NDiHs^x+Mrc*xi-r
z_^KoLSO-i&!6929@m3p$)YfCaHJ$6)ic7k?0Lnby(H#2N;jMv~mK!qr+5Bl~2m3Tf
zMdxqb*{p#PPHwjC-OSmo3$&^}zoR62Ao3xiSUuV<G~`bq$959^@p1``^Aii9YnTG@
zshs(R`?m^Nq{*!pD3X<KDjUqN3c0EvPCoLnW<L#;UOXm0E3}K_WFg(gulHnG%9Pts
zw+q#aq;2ZX!!!^a^F3lI$h_zz*>t~8SHrTbXn{m#7}t%ld&+6_lG3muC@XcRPl1fk
zm3x%S8hbLc>P!+K{d>FqRr8j(j<^3us*T0QtdwbikJaCgu91+kAT8bL@y0JY?YE+9
zXxaNuu`}uM$X5Me3GA0Qbm2xP>3@i?WjIn;U9G37sk}1CraQ(2;d9*!?KKyLEp+&t
z;sJ}}XVI)bb9eqIR1>Uh>md0?7Izu&6D#tFm4D7q*lAksWuapm>HF^7(ln<bUocfo
zv9aw<7z3^v+aG}BC7I8;Zt^!h%hsSl7U!yn@UMhtJ*;(g4j%)WZ?J&K$3hwd*CFM2
z2Tp#N<$^Jo_6aD*@=}pXwL9JKt?cH{TPy5*&aU%))s)Ekl)8re=QF-~$BCGIoC0>A
z!=(R^V9V}K`GWeL#*Dh_=Zuo$@=g{)Q0#T6)2#XWcWsz%Otr^?x}I&+1nO*I$-oOD
z8Hc$fY9RN>`QVc1$j!5IUXcH3o`%>jgU$z?%IMSalE#2~tGsnQpvxPQvLdYeKw41=
zC~!+iY%Hq&+Iskv{<C3-7#7l}TCWyDb2IUU&*-8uE}%JKX^Hl6{`!c46r=32uCrm1
zf%77!o6njrD2iJL{#kvyO*!4wio)|c`s%)iC_jWLGs;N)b)O1%9IkxVK}zFT^esiN
zd?0YC4G8x&cK`iBN8TffG6-K<3`q@Yqe562NLALtT16JQ{iOPQyhvXoT%&FiD!|uc
zXA4I5zZ>~%fO`YEfiWuGYH})r<yiNb{6HCX$Gl*Ag(mL9Q*$i}3n#JNclB#6e!IHI
zkI-|XaN`qh)GBCcvZv7mUIUzH`ejJE!RCZDdKyFXOPdmXLl5GkN6mN?I;UlJ#?gSl
z-$VziwO}qn2#vBWjdL#*oj<H6ufMh%Oa%tZf!Dg@1ZvaZpFEv2H6xqH+@Tg&ghXAq
z+@b=egT|UT)Dlf-Um8eD6<HgN2NvBKtt5cbZwCrDDDfb(*o7UrRD*ecOG!QKT4X_A
zGrFV6{-A#$?~q;A(oKiQ`ar=s<zTX_INWf`3lR*b33wknD+*o$8!*--9R!Zq(;a#@
zDfg$hz&jT)6#V+YV1~YmJ8)lZleP9T<&c2Ce^RX}0rLCzJ*+roD&@g?*gZZ&%%F-M
zR>;$}*T>T*1CI@R&TUHPT)C>cs_P|4oh%Q`T;bgf_EzO`v5V0XtVoU2=&J^r`Zk;$
zl5>pODSr+MFNI(7U1$_wN}H+yn8nQ-A*GC0#ecU}c|q-Xr`vZZ%~+K9YG|nbo!?=J
zo^20gy}<7x{k;=8ESZfgwPuw2)YM-BCR1qaPDcHq&mIO~F`GoflAgJJ0ZP6Lqfb~$
zWD439>z?p`*7Gk{jo_OswcH;KJ{g9Le!mS<s-Gh*52JUaQR?NWJRlZ7(6{4cUeM_n
z?HR<jl%@XA{;pXGG^l-~mV8_WTy$yU>((w(-)Aut;!J)1SIJ;!QJ0@Y2*SSIaY0;I
zef%gM^c;Hj6b(EKz+$Y{n>wza%$SDzUgJ{l91Kr`tpu(5_EQVJLwnGbLlaYkiI{QY
zj~ckkX7!jou`Z9r9RCSEh}HrAlL-4cm?2E)o!}M)k{|}_HU@lEUEfx!<Tr7Nq!V)c
zIil88x)cYk^0#rHWo?#XW^s{xLjvhlSKL-pd0Q>7$$<7xiM%l2G?!_Oc1CP1M84R+
zG11a+<FZv5d?2wD^vjE2_BY>(ZZvE6jm&IYM6+<z^@0F3DChXLiVYB_!cn?a9|h*^
zJ&p;Gy7NW3nIq)Kday0&Fw%X*?$Kn*dixx<>c82^IxI158dg)Ji|yUlM0e#TgzV``
z9#Fs2ksv`?`dnTXa2$$X`&E&9fOVmm=!63z3@#Nm@9LF)y&B}cZ-ZddDi6+~IjgJQ
zuGiUFW=642!D1>b((LWws&cDE*&@bW$5tT>!@lc$1>vkaaJcbB*KfkOOEy{*kAJSv
z8oja(&Eyxqwa1(iNfpW_ft?taQ>CReT<h~*ZaY5++t4uo;$Rl4?2V<Mf@?M9S~91s
znO_{cG>G5O#+bXnD_(P9G_HQ?g{l&+s(Dt^T@zb8SJmT7zEP1{lGrfy^vLGOj*4z@
zbvDWE<HH&8WU*()5R6B_B=Y^+E7P+(zNxBNSziBGl|L!5=v|dc&k<y(emK3T2X0dS
zjf3vmnr1^PzI~GRkw;eR(Q{l)4ErFbSy>PQzOG6**!$kD!OY%@t4D-;0_16IyQR*5
zHU{<;p|128qCwY7_ZB!)z%Mp`wWZZj?6Q7ug3GKyyxQY|2?vPRk-(C*eDqNKwqw=&
zv~pc{)_QP`tYyJcr`eK}CU}Wz$r|tN?G}Gm;jvziBaGLxz~*i8?%mJ*K1v?#6#>cX
zMm8hCGp?UeF)j9iQ3*f{qILx?ClZ5E6rBe><0T4popp7c>sP}@MowONV&SlT?R7km
z8iOunv55@H$Vm4v5;xQ3Y0JUNtS7I)$!}N=kW3Bc^m1Hpl=DA&2YN4Qf@Pqo$+)nD
zR8dh&U>@iGGeGR+whW76E;d=N&j%|il^7l*NAc`dm8tcw&XDyPgPHUKuVf4yY)w<R
zMGjhT3k_O%XLX^H@!xA6Nj65%zxWtXp=`|f!P*%9PGSdXze_mQ{U@`*Obmrrl`Y^j
z=zc63C7|R7ccOMOn8p*FC<5(fcYCha{h;@OGoOj(^qknGvGFUy{;70ItJ(9_+pb@Y
zh7Gl#;1wfZQtaykU!SOeicf71p1<Y!t<G(7oYL2!#Y&9-FXA=5no7987aV|!Em%BT
z=wj-^GIXz&61%eJvbn70x#~t=8QJU5R*4UK99)foRkP*ZB8r|%%wxZePYX}_RoLln
zG?ts$aPv{JK*yjf_8qPIvlHZA)A=k9*M*6aiDBosMV9k9zx5uPBtXT76Kvr_y2<|u
zi}>v?#px%`M{4S7UR+k=BZz8C{n8po+~vkg&i-MW0zX-HyzgM=N#9?$=)<3w*I|gg
zzxC^R>Dq|p4AfWYw;qf4+-O1jQ}gASaA-aY;k*!}4^mpI{+QvMyKpxfa`SBF9Q>~_
zvl3*exwv9U7~sAcf_HxS<&ehT#+y?T=Hk(bvzN}DyCvZ2mmSj<4g6*!oDXr&_=8L4
z6on!p2y9M#8bQ8Z>|mg2-rIM0!Hd+|8kZ>myFrgPj%)F6s+C*O|BY5E`jdV7*b=<Q
z?e@qU4wMK=4i^}REuc=eR(H?yeRj-Hd(|c{A6qelAUy`@EB`v#?OZv_oY-}vwoC0-
z=Mcwz8@OQZ;|ssqk2?8BIi+IF=kFShBQ5_o!p*Cbo>^y0EKqT~3}KGCjB=4e(H>e&
z$|R}jp03A3;79hjYxq>t{<83gqoTn-ZvtcgS?N9rj8pO1ZyiKMih_HR8iir{pCx`<
z5C)mb@k!swi6rOB6NvxU!kW*{-9GUR_HkUp6RR|qrFFnky3VaR+s?V(XX&YMvo8{}
z>Fax%?rjBI-Vwnp;+(q#h(@>LVH6+z?LC83uX*g2-!z{W<gko)ptLxn^CO6M;&&JF
zbEMhBEHGl<agZjoT{N0<<h=tt^zYyKH=9Nv!PM6$bE%5j#m~OOJSU7!35k=kitbWc
zUi0962VSHJaU8?pc{=#S{{PM-)|T*7@ew*6)U~5E29L8QFU|Bphq4HgAyO)pe_RE>
zH4s!pyYA3}`5)4*YM-BfAG^iT@Oetg<FKw}@0fEv>%ORSX*EqrF(u0m2!FX}bF5(q
z^tEpMtAI20#zoveI#_BlZa%wgvl{44G3)orccut>gyc%pdPz-0koeFe4?W40b=&{v
z(mexApPmxX);SuZA<ycy>;h9c>r-!o0+tePFc55b+FCCe=mv`MdCkjky7z)&{`nLw
zw>IABNDH;xP}Diiu%bTy;`KCl!jlK4Fw+aGq6Y@W@gtG>#U!VA<A0_?yS4dD079DR
z*yE$4Ln`7LbC;Xk&N~6r-MyOi)3}={-9BjcL)qR^?gBPj1W*OKsm>@AA<a%m<R233
zyYj@<FzRomHMG|~a-3=DJHGi5sS}l2ZW^ESjP*JXZ#@x|{Kmb|Q3-SYzZn|`vd>^^
z0ODCm$z`w2cB@*uAb_JuWBaJUK^YJ?Lg`KOVP2&MNXvtDzdA+*wKq0(Y;9XVR=vOG
zBia&bI_$S@00xU7TJxGk5MnuKI+DzxX#e&u&kCHV&!2Fe?XeGQ-a9O_6U`kU4SYTT
z9qJVRfliMw`HA17!8NN=gGC$lXLe&M7SfkM_GKEZHIuWK7+dbrm^H+Ucn9W;0PQ5B
zQ#7&tja{_0?!o$v%jn{F`ibD_gEOAq)K6{jIvaK*5e`!?_rKZX7!wJtT6_a;+0#+|
z&ZA<v=JwlleXWps3lnN}w2Hrr_-V>}!<(-INQyJ?rWI=zVgs6K%M3ct$RY}|SOBpq
zxdQP4Z%BaNK7R)&JHK$wZA=f%A<xLS=z;&tkSRCTgw{d%39eK~sQ{&a=T9*z)}~--
zei=j7zs{PD7FGVgw-#mLEx52hYL0?Es~G+7CNFxJ*Z?|z+E%rLoh`J&cUU&kVMckc
zQc{Gk8Djc!`HBhk`s@{qSKfi7-`hs*ha`;r<1MXm%FTLMbig$jTmU9Kkf<Z%{A1De
zE8e}pJ>xC)kCi-1zq31x#Ji~bGi0~*8Ex8spFuK-R3-U0DvOY9KHKpa?DnQWyQt?Y
zCc$L?|9s5!fM&no!LtC;F=PEXTlx?;u1FKpUn8b!QP(q5#6JnDb1vmrLGOJLbA4~X
zs;kYfaR0GbiN3o2(X&AnN<!!=EjO6nx~=JO5iQ6Hbi*dTISu^#9ng1QtZ@$<-6+JM
zVI@4B^QpFvpOLsxq0m3?3ZsriE8Xdl=paPB0t!KbAu{i`;(GB&b@S@K`PcWtK}0}?
zqY`ICZ!Rg5_-)dufR!ze?teU5GXGk~_y}wFWcG%Z3Cx`Lpm+j`eU6O64*16{{@s=N
z-K?Ptd^^~MZ0Qd)N!-12Pv$pM?9u*>l3BCnF^hbTG>s>Sw3P|a?)I>LbINg&2IKvk
zzfH}lBQcx$aY27M0fFa#c6tvUZ#p*GX1vfn+&_y1bOC?6$g-UseDc3~cF<z{F~;A4
zTm*=O9`GOBkN$fUs}lToqLw~XAdCIi2n9aVv%jYqw1CR|_lP|U`=5hZT2VxQX_A*h
z`F|he4*mD&`8Bs?8&cJc(>XQshE02SvEHL7F}`|)d@@C|!QwaxXH!-qiXgb<b=kv-
z+=BbWo__sZIw0VZA5;WKyy6ozus~O`RI>KvS_!Cp>TJ{xey#tt={Ze}r?Y$aU14_}
z^Zwg=BPaePF<d%HogKv{gb}?PwKautQt|<{B;9F2PYptUqT#3K%VK>=^Ozx|<bwVA
z>axAp5ME+kwYviU%q+yqjgtK$h-9vP-Cx|(KDbBE+y1&!uZYisIL@~3FCE0Gum&Gs
z*&j-BGH0R1uhg7;tKA3;tpBcfZ3g735hG4tu7c6K^$Fb!i0>}D+TCBu<?6G{7w3$i
zj~9yFQ9nA+AWkTyJHl@kCUq$nZ%+Iy-Gb53KdhUMsw@qAB4nGlLf)C&9W2O}$0vH6
zHJg3=uD3%SspI_4m#)L<Z~VJh$+Sq&P90u<zW4Stt0+#+j1;*+ICSr9(aTP~&+JNk
z++Xt{_ZdOpQ-6Uue2z^^dBrz=BQKMz<*~0g$K$)J+E&sX;QJ&~a&VokV7r03ARVxl
zWgzc%8ND#ND;>_+fLk4=pg4KgcC)I%$O)I(qDrkOf6k(d7^KdaPM#okeN|L`55|?V
zAwQ4vLpAOrTg>w{+X{oI?3;px_U8Si$9YlB7A*6%AJi8L$MH*QuixAZ9TVif_TYr-
z-&GA(aB8}IzG+Q-gLO$B+;^VZXCJ&Ib|0UN>E2wAD1gZ-;_%Khj?UHTs07u9l7TB+
zeEODivecf`5GBvlk`XMBJ|bRo<l|R?_XB;Olju;pa~i<<sz7ErKeK_Ird)FLiojS6
zTyzW~pDRzUVAXbT{o(4KR7Hnh*yftSUFoLaFXrux2f%p})A_Q?jT(aY5iyONy$|D1
z<R$)V2`|hJw+SUs_S>%o%u|(ucg%TKx$FKEn!O2WG<odYa3O}URKb}J2i-$LEz9l^
zZ^R@CgI^??U8v`$8KeFlI5OSE@NTWfBUuBw5gSsV`=hjMJpINacW*&3&{m@3Q@4Gp
z6cL?2=r#1zej`66IjT?f4JYimlGep0sJuHb4)2PlO!hhJ!U*w3s$Tb@@N|y;oK+WT
z632@zRnND+o98OVT(ocgq+mL8mVRwVO`KpZZttb@WU9j#i^t{NOdv)OXst+I37y9x
zL}oDJwS3{jk#KX2Qt?FR?<=o1a_WPr37P*S`e3xm(+7=d>>tcj7xN}W-Mx%vEPuqP
z&<~v#2>6s<{%ZPiq~`F<)j+$25>Zx7oHIKZ-w*F8PQjiC`jhzRu7*!h=E;-@2TH6l
z$w`*;>y2_83e>TU()9#q^4HW*apjjn+hPZ6bx&YVzS*^uzh9uWP8^iaGwhmoTS>><
zD2b*+B$9#DIY+wquP72gfug~-FLa@v;XX&J)Nc17ta9=7+lBm5Ik+uY_xaOLs$+U4
zhmKqGHW;HG)Ov2*UFA)-h{ODPVt#d3HOV#x?9HTWPSpJB3IB2z#^^0496q_x+H~Q!
z{56S?Lrv-KOV%5A`BO<6dLKm5Pc@E;^*J0O$#64bH`~+s8drvX)&gb>!trr2p`Y2s
zIFsMOlm1xw{XJ__ZY3o!Q&lFr;pd=_c>IigQ2+-VG#`E^+&wVy+c1O2>HBpfJ$Sw>
zp2RehKHS4Pxo=jU6z|K=2Dm*Nz~1b+?sxm?5Mc?H1aOt0($r?XF39<QlD6UgESwYj
z_<Bd0HzWENd3-9wmGc%VT;6CBN1VlGt<FL3gZb<GjPRNMk9Q2|isvW$bcne$+7xdO
z9hZfDf!(N4t=NW{GFz4m5jtMT>Nz@a`|%$OVGIjz=P25n5CXbg9rYyw;jhi~%hvgU
zIa;C@G?lV(G{`tL#M-lihEB2NkFy&Xh>PF;hw|?~K{;I}ic(%l&LJg4Nk3m1M330<
zSj%aj9=|zNM-;hvw2t6x;R$xe+uJph-V>V<ky#8+4Bl(6VRj`-rYur?3d+asRBv!d
zfI6uM>(Q{@0O@D&{>-V;4I;z4WFa`1-%;_S&?gw91wZ7*r&9A`&gVXY#y!n&1#%J0
ze)=cR9tDFgWHQSy(d}9)_dVs)_{`$l7W<T2i@zAYr5NfXJ1B%^nC5_^aHbafipS!Y
z3eLyNa%D{Q`k_3KGjyDEo8W!k_|_cDjz<*+#B~0e5Vu2jo0DU~0sFj^05W&4re2q4
zX@2#^42$VBxw{Wfe{(h_{+yLF`h?ORacl*FaWK^ggEB`V7}&*vD^@vv?$$RSu7}=C
zfC2=_-<&{OXZ*^zcsK1-=+X~<lzu(I>8qx_r*6X~FSLM(b@Z~}BB_fIfBz=s)>2Hf
zBs^?b*}eA7!Z(m^phJ2QW#T`Heu6-swB~t0*96%7(kT{8X|({j|9K^&`26QHc;Np5
DDl5iw
new file mode 100644
index 0000000000000000000000000000000000000000..0132fb753e79d4dce0fb8fe8c14f1c8c506277c1
GIT binary patch
literal 13497
zc$`IebzD>b_y1sH)D<QmY$`A;qz9-p3^6FBB?K8=3K$?Y7&THr=>`Rq6hyiPqr1C1
zq`QCk_WODK_Q&qs-RpJEd7jsa=ed5$&!1kRx=IBCfiB6(K2imNNMINDJ`~`K?<K;X
z`NaidCjCqr1j-9?IaUe1_>DA@Rec5mIo$?<aGoI0;rYdN5d^YBfk4X`5J)r<1Y)v@
zOpopbfxsYTMfJyhU5(AXEpt=DTu*H&lXePzWw#D*4fM2J=Kavu-c4aKbAEPwezqGF
z=-1oP+}l~()l=5e(;ZbdXCKkn)>Px0(LXiT$6R}8f-miAYo0qh>s>m{DsDgu`9>Fx
zG<OesdbpjPtc(wJ3q81x|5iWL*Z%O)qwel5IjyjU_MVoOrbp&6jkOhhUDZ{k`Kh)0
zFPt*v&C^UBf9lv3g?{UAnm&oISs7_<>F;VCZYg0CwJU1u({s;*l7g1!C%-i;1mzC7
zL>2i(w|py`7S#xMOKI=!ExP-}ZLqyYNXw_by0m4WRQjPrKy2pD*}0upnT1zF39%`;
zX=H5k{G(S$#n5SM+4w+5{R`(fm$;6u?pB@GsV((YbR2q-X~hF=ZFV2tiOS(i8fT`u
zmRlPu+j@x>VMQkROc}lJ!(GJknZ2;;p*N2HwS9dZtu;MewfyoCQ8{xRoz0D1?T@6y
z)U1j;U7b`i&u3Tm2Bw$!G4-tj?N3bn^Xs=*h4g~6TIxH7WnWkdPM%TTc;}Zk&G|6I
zz?t9{M2yXAYUr*LS51a!)W;OBcemG-_WtSVsLvlN+4wW3X#7*wCZWHLU>!^#N9dd%
z?sxSKxZzx?S~~7{>`(VKzWtOVAJRWEIyN%UNhH<{cNWYxv?{+(?H(R~ZV)@&Sy(nx
zPpt3i>}VhA$?oaxki>)?t(@#_Z%B)y&$ka=8d)~ZFHRDtc$GczKlX-tMzgDXKvHpC
zt@Sl+)x@fz?5^{*{j-72@{Z;@`_x5ZTYA@UYwPG_TVG#KPfJ%@?O<QsyHA~D4E+7A
zb=UbMhemrpBvtfuSM}D^c>ZjaloIP{s!mM)%5j^GFg#a1)Y3FqZyhku+>+bdU#)K8
z5m>U{(^@$+Ob9L<Z)#||0;BBct?X%U>}+XNvi;fFQPbYu(A!EJYN(qU`lV$1#o5)X
zuczTzVmluumE<u|$8Tq1mRPrTKDf2rKG66=Mak7d3*s^QCFk7xOTr$ZbEG46VQ0Cw
zvq8U@eF_BP7nXY@t?m$Ks4Hm@v>g*surSd47|VOo)(rcWP9(J0KDaMq%kK&IM0hH)
z>=#UAY6_k>bXKEgW{x>T05pj0@;%Y0FJLtvIWU{nr3TtVAGEHM4490HG&M#^0QK6v
z+lTe8%d8uS;Z2SSW`o~sQF><JYY#FXi#(Fv>3i=1Ab0(hk4{bXq4>7S*bV`6J?G8i
zi4^?FGoT>AmA`oI%3kJ)s}mTBgY!Z5>U>FdD@|coo@QIkX!qpELv6|`xh+AwDm&g7
z?=b+JJIg!C*EW~pGVX}4aE6i^;lHr_aVJry4&zwGV<=cD1q41s3LvMfq3WTfuL2_M
zs*zx@FT}4Ln#pqod#Q{4=xXhgjmz*wYKljTPov0c0p*W!<*;CrMGlf*1m2^LT;oc!
zCBu$$5J~ObL%FlVFh)Im@ncM*tq<Fym0QHe5;XYHt@psCg%^V5TZ4IR3VQE-d=?F%
zKi}9!Dz#W<#zc^P8-YlwyIT~yJSC&3Sq#!Ngf$XCQ^YW=;l^M!s2-LJx%|Ly`!iVd
zt>i#a?IDulD;xY4l{Ww=mkV46s@(4vXz(X>0)RCDyobY8=dT+wIP&NWRle2v`T{%S
zcSv`MiQy#|LS6|3fzh+e945rwJ}X~wL`=gS2F}08+MhHLHm1Lvb3wH!{g{8Ayca3<
zFeQJ>IwSU?b)ayKTz`ZX`PynmVVZ0D7-Z~bZUm~PC4HmuhLFqQG5E4hnPg{$9j>>V
zPD>$z+X&UrunyM<4|iK*M;@#3>bK^xqDSkQhy(qMJ^l6J6cATG01a%hfjwDad}K!_
ztKV$^8^k<#QwYk0zlwTAbxRMfF6|%*bU>y1uI4;K?pTo+hG>hRPbhs6aP?(%RZ-RX
zl<WCem)A3V(9B06j*Nm;dS*r1%}ojE5Ewe}z3a!5XIpuh*4fr37zz`NuSgvMWAC3_
zpmUIIt8yPq<iYnPXS%<8vJj}d7e{Xrf(7tE`M__<?N=>>%N2dcA-#fP$OzRE@CUK;
zr%-&uFWbhANAr}Ox&4+tU>fq}m}Q!wymQF5Gy?SF@M>uNB`6em)<J;>(z2?QViO*a
z`D6@npuAGz;KIh3;uLZvVWb%R-cRCTmqK-jfouOgnDNF~meb2Cs^TPLFNRN_%wF=G
zxPydbU^!3kWks{usGitY#}>Q`hC4L3D1b<POO_^VGN1lj$vVY`S5#aH5NA5)EC`Vx
zST<}h!@)kQrt$L*?VBg{Lf_t-SY-{s$L7v%IY0MwPjsJRI_F#GQhC`IoXM)`a>wqm
z{G1R<{J;$#M_U4=^iu)`4stdn3{Xy!Nw4#zo{yg;GetfaxKco~lD#fjevFK<m!1o1
zjxV}8wy=;`mAv_6`_sG?#us(><m?9oxNMQ+JW=U(JRT^0^)d?(sZNX1CEcn;ux!h)
zbtWvftVMp?MNU?D9I|d#7-Z$sYujl}WJD!Y)@`&iE!Ll3tz4(u54YbId|6>f;@yyE
zb3-YWjQK@{NpWI1+jOgDmzdIoo^n1783po5TKZ$^@yb(Go}F-a_gLwusnrko;zVX_
zA5de1(2?mwbEK5s|6upyMy@Vt>gAhI{LvHWct^;=<Y_B)+V&lHHZajz6UF)>`o#3K
zjY=`GNASCuN1eL`MA57jGzB0PLXyc}{n&CLsYYQ$?8q6k97EyU&wC#nzabsC9yd{a
z^ev)~?5B4av}{zqtU6a0!mthi_j#BAUKA=Ty^0Fx_9DY*5W+4g+HkhqT>pW7^VzZH
zP#RZ#e$aKB|BiD!0=_5e*(k_2V@Fe^DglL|75U^Dw<_Lf7?_)3LNYU3+8Hai4Z0QA
zmS0TG07VZq!7F-?@h|XYz{j#coawsb>)9Fth$=XgP>LW`sqw51PiCcY6HGy+7?bi7
z-y^e(ejHQQ0tf(sK<YLra|mnN^4=AfpPZ^D5JQUE0@(bfp1-0a-ooqHIvnupLTXg;
zr2**EIXl1#(Z6bMq(#onDpkedwtd)UhWDp-wshjvrHF1r#ZLV$6en6hWgT#%uWLa-
zuoz(jWJ*j#Hy%cWCI=^5XU=^Y{4F5lc=ND3;2qPaS!@Simy?NE6X*h>Qe6#S!HbD=
zTHqAYw6zuV8sDrg5jv4<nq9=b9ZVr4Flt6|Uv<ssu2_R@&=kMt0t-yL7D-k+;P8`Q
z*9epvE(c7)NV>}q#t5qK3<3;iyvCSQ2_F*3cfk`A^WjTg*@XZhtN{h~UEtp#WxGjy
z0DXfgpsqz9Q4{xV^x<g&ueW0&BZVwjWLRVbVb-KFSo|G)S^=z;0Glms;qf(KA_A8$
zCt2_S-cTspZQzi=Y3a8|hXHZR$)a=x-rkTAmnl~fM}@4blhBVYq3~Kz`{?zW32D>t
zSJ5F(EB>}S@5Y!5v19SWHUm-ZF29nom(U>o1X?Fs?0p&Mo5XAQR}b*@;`sLTU>X#6
z)A@iZY6|eo8MOQsHA4>nT?=Pe=X<~DCMCnD6)3$$1$o%RChU#gR&Zm3{rWl|k@$x&
zO3EEO<eGQd92I#_sb#vhV0zyJvrD*FbHXGmcxrUi0L~h!C>$fX_Hh|<w*mK3H}?dp
zDA74e>Vamw`@Nj$x0C~$o8j3b<jZ4Dm;gLMKO`6Q<w<)sr8YS0T)pOncQ$F6=e8Jo
z$P3d+7neP_^J4cKpu#N`@g>fm&rd+y00WRvAnQ-%%2?ts=5FmI0EKnoKHyQc95XJ!
zO~!aTx`r^Xsj{2(TiXICqCu5E*fPd|-oarYEh=0K2_~PW`zmR^`|c&kLya*tQW>Pe
z%2n9I6{z_s2yz^^Cqh|CZU7TM`$SEV`~(%1cu#6bM~`~<lwA@Ng}dfzUADvPUi->F
z@d0)_^01QN6MTYh3@PYyj(LDuKqQbCyjdgrNfseQFr;i0f-Il69{bEa`(ub~vFX`;
zN4x@*uT}$G;)juIs<K=~tqf)LI}#8iE(-U?{8Ey?_B+6)#Ct-px55l`XHnb6-EJf6
zM*8?y<rQ-)qINzVlPFxG7`4Kq>R^mhc$~6<K~vE}VGukS1u4-3ENkUn<4MBE5{y8@
zSXivcq#d%6o|8hnc(aLwblgK3#_KEvv6dpExH+=i`@|xAa*i>R46WxG@2SEO;q?cd
zli#DU$Ak?S0|@`*p6A}Z1dHK4@jaFW3HaJy!3-=J;&=d0$hrgsue%LOPgUnODFqr-
zLsL6qGvH^|1{=|tI!tso7&m8L!oe3o=VWXd%_tc5jMS7Ha|H~1`mzo%cf9XSn~*$Y
z+v}}nqz6m6&6MuV#MW|KZ^uI-VtJi0Ayc;+tCRMq8D5iWZp6X~_krInhA#cnUYpuT
zU3yYYO;j@BEa_Alb*;Os$$dW{!DY%l_44_rvuo9F7%@3h2P92`&qAE2;v`?mmWN<K
z-(eW$_wMK4PGk;!075-Ec+fcMkWega{IQV+ey6fU+5!?*cX&I|bJbDgX@yuw_yS1j
z8u7P9eGd5ptJN!F4ZB#<3n&$CQ0`E74Gx%@AO$sb6<OaEz%n~l9RY#UGMn8k&aIDP
z%jmA{@R)Miy~D(0EBo7nO;{X`oFd^oSjHujWISyLC6mElf{4TeFMcqEM~zHCGKh-S
zL$3l%#{!4|H_)xLw+^c|aorSP)F+S(_$tfw0w8Ha3k+PsTs7!4vMrn4BZad7gpCj|
zo;>$f2?hkv;(ZABzFvB8$P!Zik>bBUG0J+@Kaxr1Zvt)?+70N%Zxe#0A2pK<4q)U3
zR9+itRc}xYn#O}KSV^2B6OQB2jYJ`5P860Q(^#PQ+3AT3ohLgneNXOj-h0LIyMkJk
znBr#JI5sjZBFeX&BqFRcs=pN4dVf;b0jsCR;OlOfQ}%NaXJ8=JNXusR5ciB~U@WH$
zK{N93VMz6RG2#mwC~}<YK^@cJ{?71x3up(Pn^#TAO@cI;VYY3FB<T$%E0X42j*W9K
zFv6rRUo)qM44$EiLC-y%b<wGu6a;w<<u+<k&d!KNrM<*ItKo6L33Igx!W78M+J>uY
z>HJ<1sOz}H>kFnpVh}a9(FTmfN6Ms!M;fzdng&U}DH}YP!0#0fSXQmnaSfNv!KtFX
zJ9v?Wz(>;AAy1SYL7Xx<Cf7-Q8rZ-p&s4ye`%6?nFusOM^b(*6&qDO0et3Zl$Wh|B
zzD+r02UMK#U~?|>b;jI{jbXs6^%Y@b(zx-AuJxh|ifOucp3~&Ag1rbE!X&SKdY1;;
z$Wo<XTI9edyHslcLFmMJKcz)oN-*t&`ZSQ<_4+Ln2v<*n_0mllFBseKS(3ll&OEb=
z;%N)l5N}Q@NrV14HgSz=qQZd;Pcl^<hs^x+&iJPOr2PzCzQ*Og6B~Ml6|;9>Q0y}e
zF*m^EiYL6=Jt+Gn5^?S8ng9w{b1ljWxvKF>x$BZYqr(UwIZMJL6Y(^S(8D0?3LX$N
zE@vP&HGG?^HM{k#A5Fm_WsHPr8R+)m4KZ@S+6)SZ0{=Gk?0<t)9@idk0_1g(0NDvE
z8%$lA)WAZ>80j%patlVf;$1|LwHf*lI3%TSRVqO|4?7f8kg6zkC^~rK)&RkQNYg^R
zr_M5G#*3;>bsFLuLddBiLxH}>X;UZUzp-nvsVOPu-$y4hHjd8}R)1(V^YRi3EhTcr
zO*RZC$H11}8>DLWcVrzv+JK01BZ{o|xrwYFBs9sM6PyxH1<*p3wR{DyUlHdN7FxJV
z)J3|GGL*Pe1PAK?gj~#|QKumUPY%AzedgJH>v!5ynv3-gCng8f*3BSkNn%zox)Fza
zjHa;U(kC%cmZ1C-KB#yfgAslwDMH(85FMS+xbOFA>aNU`HuM6?p8YoB4oaLOG5n6m
z<uEhnp{u*RryvVbsL|)H63eOE%@IXj?%uKHS9^dkQ;L3jUxwdp1W*Rn;5AfM4Dw>j
zT)KgGo?S9Rf`iPmo@C`!67XXP2D|_-%_orNbB$EPY8lMUbB7<0XvsY@HwWFx3q(xX
z!+*De!kLgy1#t>riYDJ>=8L<1-BDW#xv!L(Y)L5KmC?WKIb5axhYrwpa-Y)`%`J6$
z%VAlRnHF&SqG}19PIa0k!js<j56-hOX;#}s&Q<YMB-*rYU?W!PmVWZP2)+_5*Pk4>
z{H;F|Y9Y9<J-dMs1}l|~0;5T=LujkCA-eGx=<YCJFm|DZ0_%w1kJymgI`ah~CfQ=4
z`Xp0+#zlp5`;imm_AuO}=q>R((Vj9hkQquu?*_&;<`0CD77r$4w|qVr2YTR&X1f9P
zAaGX`>NXx6Vu)$84Nc!&UC$1+b(WV3J{?`#<#Kn}yp6))pC%rwcc^=7TWQ~%XGuKX
zTFcuHy2P(Rcdp(`Lh7rMz7rUBi}<9>E$N7UFm2F*su#~_Dr`-erP*tp&0A*U7<W4#
zeQ4dfS=Ma1e>SR7NzFoQfD7{bF`=%{KwcwDlDYwsW-Wpc8|Rcov?NHl)vm21&v6Q)
z?j^&TeLj`paCMZhLJ+i3()OcM5f|KJPI6P44a}J<0l4$wBz6^?(8Xi)x>fF=AJ*Mq
z#&IRSirgdY@I9=lXs#I|@5aMdfroS#?tkS_940N}K{9wRyE3(3=OP+vE~x5qi<F&i
z_Wdw->AV(M?aeb1?cG=c>26+D3kwWCObyUdsF%!Csm#$7SJ2Rq7q`H&IVezKWLMQ6
zdO^UR$Xq*a2cX{52Li|tAyfv<_BVHAh+vO5?x{Tr6t6CQIJUII+zcWKlujkQ<bvX5
z><RTo6M=y}`q8ZX+}fiU4su|0vQnfCi08VNKnj7)@a+4r7V+QmWsVuFnp|+Uf)1sH
zRMpW->d(^O3wk?sc!OIbAulWD*vbvp(Z|6$q66PLrXCS-<qkNymmjt=!k(x35)OAM
z1R0dAnV=w>XwUC-fe9n$;Jk$gd?;w4k7*ivTc`ucc0IZKEhyemPI{#LVl}@^w>UD<
zV1yd;l0Jj<u15&DQDT+_`YPb&TcKJ-S%Vgw$HLJ3^d4+UwDOuH&JIa$_3>XTzv=@(
zDKHXnzHTeLukK4C`g|l}M)}W*F8Kw!&jQHU=?>tgaIFucPUiV$b1rzz<g!;T14XLh
zVlN}7<ly_Jbub=&qe#TWnzJUC%khgQWy(LHQYIm?3zmQ8t>&GVx5EsWiKWp+SnHp$
z2RnPB%8TXG&UGkuzPszJu#V#g>xbn`^Bssnl&m0xzx5FGPDqAM<_o%8JfsXOd5Ggz
z<~4uSS<VFT6E=JeKy5c6?re9j;~bck+e)KYffZLYM!%tatC9x4Rq04b=>D9=BZm|W
z_yWhBI3imw*H)9<3-%<rR}KI_S%Ej`D{lY|X^rc^6rfYTx9%ovTP!OW#olg4VRX=M
z_xMJDV0}0V5(l^Wkt%qLkJh0T@jJ-f!2bKpj$E_?9IoXC{v=XR>3?qYa{QL^LV|m8
z#a13SjL-cA$hHxE<A;TG^>^7`YrM4-n{S$wsho-P_n9+V&eCHk3gH|ZsdCup^U}i7
zkn@>spOrHb2uv;SmwfzH;>^qiGm*6`KM@ON3uoK?$O+~mp0yVSLocc>Xht5hPVd!*
z<DoPL{FJ8oQP-7Gez=+qQ0e5`IiFL2)P`4(0<<KLKM*MZHVF|zVni|g1Rw+=^_3nE
z&Nnz_eEyy`_%veb`^?PY;kNsvn~HGaVP@TY08?yitPRPu<~$68Xn%@035FiXlAnfQ
z-V6JZ8zsd)caAdCaWXb_T1>dhbul13sn);o6W*V#WzwPC-r3ZV=l_Y#-JNap3)}RR
zo3eAL0Ts7#wOzHd^qJ4rb*Yd|e+nqnIFL6O&y@5Ses1%kQ|sR5!A+^hTJ+s{I7P+T
zKiYHTAGV*?9s4tFG1kWlK0p5(a#BvOvR{3C*SBmWM?*7xJ97tOYLlA~-db0u@=Yc7
zPO({Yst(2~ZSM=d{_&@ks}1*p-l&rA?R-Z0Fp!fAjH`ng8azu<ieKEEnINrN2=UT9
zKYK=5dCS2f7>|d7DP9fdb1Ht-dN{o#fImK=JNc~E&N%{tz&u5S*uRS}M69~Rou4-}
zynmPTML)Hj60(UgZ>J<d+l%Xq!{2|cc2HM@*Q)t)kjbu*ZTX)qoDYyiFsTU~4&Byh
zaryfmXW`Mr%!m(Pt;3xLzNY&QHxBA113&jlBo6tQPUv7|y%f5Jb!3#3g0)j@`t~#?
zDx2KOd1`k~t_irdhvkz|z8~MOr@rESPl}3d>NdL=?H3PkuZNOfJgQLNJY+-k<Kj%m
z${j;Z+Ok$krarMtaoEa@Pg-fWs+&8!puHG+9wO4_5Q-#)+>dehae!xa9Me}m_-~dS
zmp=v$n^{azP0~Gp9UvHk3o(G^>Syfs(vc}SWqb<!`B-n8;DcaXegClDF<_eUvq#r1
zeeGfre32SI+k#BvHP1r%B%hCH;wgiN5bgcj?Ybl|G~tQMx!d0PDX^F-#S3b^e>X%6
z>v?6vv)T<qvB59<E+YKz%gFRq9IN{Z_%na{5&3P<{lp;zH%`RsBFSWFVEEmH6_pKJ
zP*P5(5}qD;=c2~*pRlXsGs+;TSZF{I4{^-c3%X{Axux<RAVL|$uY<U~jRjB_a+kE{
zH-c#IItYVO1TN-1E!n=Zi!?vL5r{V)p(_uXTp!XkLMV{kEih#`a%Kt?(hR$hWISoX
zJ9)sL9HLxodje^Lph%A!KfMb^!?<-ikh1Rwx*5^+!;&b)yR*l)4%zlu(V)xmCc{xw
zLkPr~k~xGg(^wXQS0Z<Ka-r9p%8`Ow=Hk!~1X7YVN^YSTW)tiMnHEr^TEq=f+2@zz
z(PC!Zw8(Ha5Xqwt2-VhV<W8u2-n4-QLS{n#c4`Qrpaae2Z?UZGMDia7Uu&P-^FI=<
zCsN1KVm>!tu4dDUIEw3^bj&mb<$KxDkl=c0F7oi}2%FRqB1oGztS~0*K8J#feC?&C
zONRu@<1VSIqM@#!bY@Z*`VqOTe)5KTn&aW==htRK?No|-Tx+G?$;k!=Tn6znAmpye
zh3Sg|UUK(2+*V7LE%9{7(Uy%Hs+AjD#8c?7$d?3A`rr2g9wxFoEz{=6LWaA0pJUf&
zXH(kO0mw*Eq)TAAW2NqQ^ZC|6tvPVIHl<lH-2pqp;*`L`ql_&%8odG+6$KMlJ-s<C
znzFI!vd2tYE4;?Awgt>=Ba?})FkARrk43LB@;-Y$7fS?JGxtTEG|c)TP_@72{nc{Z
zGB6?{kNOc)M!I9b@Js)fYkP$O8bKzDMvM|~Re8d{f}}bBIv*3!v}D+5pe1R>Nd$LN
zeZ*JL&to08ZYji8i<p*`r;B^`wbwk87>$GOyD3t>tW&PCxy<{1n$hiOqW;#~SE1o6
zIun^f4TFfU<6%F-uAkaJ`efn1{cZ3H3AH?gNxyJ1Q!DJAL|MbyD)SxYJAM(JdWt@S
zmEsB}P7J2)ACwv&JGBAr>H54b=5$utVa*{o3ImNY+UMyxLhS5~!T-+nuFNYGN}SOw
z%I(wCO&JoI@zB(cN(<^d`CnUt_xOsV;pHavDWC@RAnPDjzyJWA(-kX5w^zMhd*Vvm
zZz>pg_{;488&jLxI&;h<eO}hI=gMOC^$k2BJp1lY`g;$BQX=Q#OqgT7K2O<}Q8W48
z?e(A0@o`f}^VU}WA+==!X}v*A9kbV+4S}45EVJStUqjnBxJwV3$Cen#C{z&_(c;w-
z!t@ng{&j;eKFb8q!(&Wyy~ds2&%1IK-S(s;7I@};?$cAFX5_aOv_)l+LWihz>&5-<
z>TnAgO%$-$1sBn2vQX`{VJJdjVNrDi+x(5~%lMLI14E?)%f4ZKxu>h0nm;uT?I!)&
z@1&Y><@0e<l^qunjuIcOmaS)*UDZ(QTaX+rYkV_s)sF{o0baH%Jnhq7&kOo`7yV!6
z-Wa9%9JQW@J-*%P^lO!jEQ@J1%<$1WL~mgWf4sKqeCyZ8$M&O=r&PZ~?vO`4d?Cn9
zFljCEE25=BQ0P#vO|Vt3*c$R_J{cPwX4?AHY%*{&SceCDe$QZU<Td{B`Z+(u>Q$9F
z96{HXyDI%#9sg)4J}o3`enOHj;)$H@j$A@=GeIk{%l@gvl2f1RkdH<{seCV@mo!3!
z0V!)jaZx8)1=Ng7)V`QbaDK>%A>>+lSUT8QN!^s`x@>R<Q&ZALAdI!xx_%M1S;}Np
z!*SdqD-sb57pqiUc6__NG>TP_QqcFUEZn&!lV3|r6;}XHYv2A_g*7NhkkY7l9X{Vx
z0w}(F0))b2a(4N34YXXp$<1g;5aXF@x?12l8y%k{iOBD7{im)G$3Mn?9fJ=~r+h=e
zUF73As9^s^AqBLtTNckeqKbG<sz$f6N-9LW^1$z0?}$bqPO@zhMD=+^4=B>NKe=oQ
zie#f_oV@32_AWGGXy;mD#L;6x*Lze)2<-c%<KU+@*x-bUfs<>Vef3px11x;d`l|MT
zRQZ=L5%Lj|yS#=DwYJX`SH@zk02c*##1nq6cqf&SI@^Zlw{>t+#$l|U2+!-^Iyj!-
zxyodj_hrcb`Hx%1AJM*UG;3tbWp1Js#!O5SSo#)Zviq`YZ{c0henYx|uzNqe#RpYR
z7RgriHaIv%e>2_L;O)?f=FTlVwfDyXgh1}oDp}JPMi`jXu609qpW1@OM{3a#!G7!G
z%h*qcw`G)e^rWG9D`4o^z;ljA{MV_p=~ruzwUt%T?gp2LOi&U0%S<(R3_MJ<DwgM^
z6LD3T*V&KspMBS9rySHBq)+R=4~}FMNsrQ>+oUVxaXRNXQR$dcWIY>NC=WDk3pr9X
za(2Q_9t8`px=fzWB@6&~bLgRwU<@K+9Fr-r%zraxsxJFv8vw>6V*qJ0P1e`LR`#cQ
zy?3zq)F(`T&?`_!DIs=dr|q<*tLC3~0)m$Tpe>zlS4BRnsw0*}?Pmw|Zfe&uM=GA{
z)t76Gi!*=Q3#vujuy_EpQ*@2^#@7EAg>TX1t~l1_nz@9i3^(!X(-#YlqI_<q7-1mh
zd-a?4(%9AvAs6Ga9I2RwjT=MkGha_CQEBrleP6j|5i7y{uHyF{Bey>Znl8JDP1nxp
zk1kW@WnfkGkLM)7+m~(%B_w?3OAruu(s$do=ze|pJ4bANVl4~nBr!9ep;q)|K?|$P
zRv0o0a>tXG|JOqVKSuIp%0r<qUO*HS6v)ABFn&QXPk47)cX;<}IWbrE>uU@SEbX*0
z4KphZCPD33zRwc-b<h8F`x%)0!c5e0-kH8_`W7=F_OpD3U8@crrL_&;a(bh*xQKG(
z$yM%C8T)o?Zx-iU$4lJ@&QcUDEG(qf8VFe8-&j&)FbIx5n59hgCJXgW$l#>6q6%dR
zH(gV2k^kF15L+`(k868?iX!Qib95%ihKExU!A97i_{}!I>qdJqUwMlItAHCW`LF9l
z@b)7o>e)rUgK;5rOx0Mc!F;mF3bB07o9r^?sa<|19(?CdDcg->v`(fMGZV$e!%^ks
z4@Tbfmq>7~S9+mZX=dW|w{D0y_MJMU-q^Fc{a)fgZ+?yc%ZmAMI9u*{*QcuEFTBHQ
zVd#*Szg2ILCYrsWlaQNwv)Yi2_zZI<qQY71lG*&w4GML`2OMDoS`g#K_XX4w&MIYa
z1`@>kN^$eowM<RNRd^zA@D}*9H>~wIpOJ}(yX~b|rs#?YINl(Rdp~3!`5^pZO())H
zzg>$s`Tb-;rT3GBy-IL@97dQuA@)o%y(3<_oWm}y^_Yu!A?1~<9D|SFm7U(kjmmhT
z0QZvi*o*#a>2txus=0}0s@QNKQzAC~_dVgrD5!#1EYu9kKL&WEC1VB7Vslbloll|?
zS<78(Nh3w%GYn5pso`M>;@U~Stp+^EL=73`l|Iy}N5emSP_H}VgN@W7>r+y`H#el*
zN^>Gi`$c8IQA7uR{?$B8_qL(aFLc8VQ+IFgZW3k<4d%<KdP=p134=U?yD5oH0a$k}
zKKjSnP}%+bZEf5y;BVflJ#*^QdDC2G6PkDqhV9??^k62Y(rkyOjjUA0WRxdP&gLmR
zNwr%x>3l#At2LovA~xh-Ki-1x6&L?$8vm*Bw(T3{^B9vKOB(z3gVw6{+>DhimIS`o
z7o)=T0-1|xV71|26zR9JV*-Crt4P_G=ymCgaUQI;^CvK!t9r8=N8EdB;v2s=p5Hpt
z7o2#Wa-b=PqELx=2s6sK$lP4OF|uB{I+u?<)zjTTDkRgUU?9T8>g|vYv}4sr9UjDC
zG48ra{873^Ypw_KWL$Hak5xO8!;`xTrv6zgRwOgbCk+nG53B4=wQ%XgMCEVnWwf(D
z6=dIv<cTSsY;K1qjEuVo)y;lgR(171RU9dr>5>oMw}H@Bz>e?RJqvRj|NceknLl=k
zjj!~CCWZT~XrBt)cO>xFHfF=R+=8RY)y5KMM9$a}Cpay{H?sK*(5#~uG&M(EcfDct
zn(4&ZUDWe-`nH}YSyIt|luWEPX_Y8OYnL6XrZ%4V+}J@PaY{^Prk?4u3E~RSuecXJ
z-6p^MXI)8auX}XvH$-;zZ>+<S^;`5*S$lDR3{kT*t_uwz2bkv|`i7UGlL(jn$hZB2
zKN$m#_R0&CciEWZo{8alBmbkPzU?wlTKvs~#DVM)$5s2|ve2qWRYK2~F6D?*zHXAT
zczN~UW`eZ9^7+ljqQbHE|5z>K!_|;8X4XSze@GaO{2%}FYq##U*%H)K^{Q3m5)H=o
zz65alD*_5U@GEY%44rjz_egVf?g&O+%q<kA(ab9AYfSO7n%L_x<>ks}Bf8EePjbGJ
z`+eCu9bO3D_V!kgQjAY(?qq*T`>_Z3Hvyo~lDsd4C;Zv+-tx^ffd!e`U5fR}0=m+c
zbn_RxahRvihJJkC!U9FqQPw@xL%+fQYm0-3HK|_F7kkGaz&*|pQXDi=Qp_&gH5(??
zb3*}oGy3p~nfT2tWN=={uT5Wf=>N94GVFWUi&O>Wb}MYI@SLUC2froqwOeJb@g0`W
z2mN9`fOz@QFHKoqCH+Salw=4x@H!v?S^jK3%V(`%e*}Kj4)=)xI(qY=4COxzt)n?O
z9J*E=&kPK}C0)zsbqd<=ne&$2BW7~3B5GLbFZWAAK>snyN3E+K{a^U6S2FIZtlX6H
zyk~SQkh-l4lp(&hKM~9-6^)$_N+n1C<M0SNgB7+(5=B;)7IAyr<j#c4Q}vJUc!qNh
z1Bu248`x6esQ!QFR-+9qXW5M*2P7A5%sMr;DofGZv(m@?_LoG3BlrGqja928sTu{!
z1SM|h5Jo^&D~CsJx(Ut1Jm~L9{yFRQo3ZL!#d{0dkotehw?4C$c92mC=vgzgrq5e1
z#S)Ov-T>!T+q?hfGKvVckvv}x9qD=_Yku9-(h(@+pF56p_NOTRqo-Fd!C>hB>fw^r
zn9t3Buy#%bh?kLVEg(pzc?8KnSx>+a$iE#tGU)%zP3jW(-=j7GBu*XwcR3FC&x_wo
zC@B8Zbx#NXzen0o$p6>*SCRQ|;Qypk1o;3DkZ6-_Lc<p6r8ftMo||&M%wRO=QU&)m
z$t6{az1!$#CT5tby$JV<NXF~pltskhEIgoCPQpg$Is0Ou-Tztk0Z)<(lt7J1FN_g`
zKyXu+sj^I_6HynVcV|e8030Mi`<V)nltPyBci5ESMIRg<vLlT+y~vG~S}5`RNU96*
zuP$7h%tEF{g)vLgLQ!}O|8-ivz3ka9A@+#2FxMl`=6Qc9`YFfDnRcI~{oRkbU}{dH
zkBMG*%4GEL%y3SteZ9utJzJl}YCWQ*hIkAO5zm#6g+C1yPOwri&s;tyEghz&&{VBf
z?BwCQogEWu=tjwZaSCmuDQ$xZ(yO08=!q^8u$+c`yrx}DhBoJ}_q_={45jbyFD^g8
z!>plQW6{lH1}h|_zMtL8yno#MC`)Ep1b+-!b+f&tHl!<}9eao5CXeScby5A@n_w@-
zpVnjF@~qFLF6z}0a6?s^lUTic{c2p%mRr-ehRFbdH$f;Ie>mZYOH?zglIj_V0vTfx
z?HN2P&-nDZu=FbU$<-eEnDywU=VqWc*56-yiowy=(;(7)bUgjKNy$afn38<iv`w?j
z8qG7b=Zs_%G_@I7YA5^*ly#0BZ&1S(<WQ1YK%qr;N?;@U$ZWC;`QdEz+|%Rdu$Puy
zPqjGYlFZc18;>f#l>IqM;&MRWhuCe@>1N(6Ii^)4r$Bz`P`k|ty5@2!e)^}Pc-FaY
z??fM^60E1OfYS;jEBoT>9rb0I7q17fZ!ylM`cCzJKT=Ol@$w0_anFugC4DJ2GE)ek
zOD7(56f*e^z0q)Yxt!$788Qp*d4+yQ5><!EglN)!bAF?S6DTbE*6hN2<#F52MUazN
zl~Px=8b=HrPB$FeRK2JWOFi;aT5K?aJ_r!4_~Ex+l<44TRwg%iM|nku%@JYLkzN{m
zRzTg`V);FN!cnExYUgw0rb@Q2_(abark;tavdVeWj;>`UG1q-P8~F&w<`UiAI|I~F
zPH^mLZ*?p!U_-@!SLQF|tK<}G5+wEXj203ld7H)^0MGYa>_Zk^v05HU0hf{paT^1x
zg3zs7qoz5edS1;Tq64uDF*|qoDT5Ep^i<+vb)`55!pCMa)!uB{iriC>7xrhDM;)IQ
z-Q{?nAoh6u-d?e+kkg6Y-VN$BmM1@hOdM`orJN;9t?}e8fk<iz1PPS(6Fc`txA@FL
zz`6D{E3*Uq=AE?d+C9SC0CrIh>aDZPy<aokW}E8L*<P{1>rJ&$WE{?a)_8=IGnzLN
zD<b{E**XIBmOf`^uYQYSS5$nZ$e1N>SjJr&Bz3vxa+iS)=Gr%>$)-n_FTl5*KUd^S
zjMoFAUh-Z^@A%L4*VGDv&0q^1QJYQg%ItTJnW}Pz#zu)7=nRgO6vg*xUDIjN#XA*b
zdUC*rd>;(q^ANRA*lMgvmD0kka~G36O+hzaVW!hw&US-@F{yqv(}^>kIvzvei$U7J
z=ennMQwir@?`gq<XUe-1NgqNF?2F7YJTe2;NG}PQVn7!LaLLf@@pBvL55Fo*%J!G`
zl{-)T{gB@Cp^D(jsL(+C0(K}Z=p}m!;JE9WVeRTcEO(CF7pd5qI@jiDfN}K;y<K8s
z$}YVQ9id*R+!1&9(N%rbQ67DxTjzb-uSM#KTQ_!zm}P^VM19Q#vM_NIT=>5_LjjrO
zmB}#S6_WT=={Vo7O22DjVU}T?QKj!BgF3{P?N$fVJ#+rLKHXbF<&rvG(nxtxC?01%
zFVJM1=UCp-vN(Jr@OB<$gt3h&yD4z%*HhG!(_GIFzZ7rM%Jg_jd~Q=9LL$F=w_kD3
z*mv)Ky8r6=^Fj78GOoY1zkY@-*tR*&%J87Kuy@vC=A2cb!v055dPhh=yJ=L}^Z2R4
z!2l5pLE9yI=vXNQ<YSQNL;^f-IWTErww!1GTM)b6(85RX2g9<Hidd+^z-tTWp6Z8X
zID<eWV|k{XQ={@_tgFRrpd*0VMIDvK&M%M&K4&&kz8HRmTL>T+8vGzlH1EBRl9*>E
zndfxO;(C9}1W$)U!$ze0{$e^W-sYNwWOhv|?F+n@cEH(gWzzJ5h|g4eBz7($)^LsI
z?1NZ*^3vFKmg>bhjRNT<U_c&z-TG-6<pa$zW8sbs!6U=Ip8X5mI-z#U`ITm-FM!U!
z9SE8Q7<_PGWxaB0Q`7Y{Afnxrg8vuTX%|NPboWd^<5RD0^~++rhs_}-PbWmiBqdXq
zYZ6M;P8j1Y=rZdJ55v~D=iYvtif+RcaT|}NrxKuxb8x5zp1drA+wRrX{10lQ$!{*S
z#z<SMt%Ucl#2Wl%JD0Q&Uypulo&NGn?EN^QwU@j1qu_onEpKu`+F|n1jUwjlUh2&c
zBS;h3u!7RGd36@1PpyGMMXmY*Kj%z*oz8{Cj*i13W8=QUQxLqvkEFITXM=lwEFXLy
zZzaG_e`oN-OqC+kE6BqV-j4V^^)dK)IqNUah;ZkWv0k8zje0D3%)O9Cgr~ZwoUG}u
zGY5;io?$~Iusxq|?X?sK#gm4!B}EL;;eR}1<zwX%+ume5cEMB18T|TKM)#_DGbe8V
zO9<8D{W#U~nXmcd4V$f)G36H({Zg?@{viQ=O{)n4KaQR$A2sxcEjX1Kwjxb@CBXlo
z?k?l2eEt}h{3b)TgFNl@L6Kc=<s<K%^qiF!7EVGok-y1!vAF_X$%ng{(HR1CEv_A-
zqJ6GsX+!$LbZ26M8{TzPO|Oqm+UFL&-8bzSGG04to)Z|Y9@X9Qe)`xnI@6X`Q6lg`
zoFT@Bd+!|j7xdp`&d8}1$ok=|c72ymX1(pxM`}o#esL}A{Y>BPm4=TNCYA>?{gfOs
zzigKMZ!f-*Sgzr0Ya`f&y7fs}d_Ix1`0mCbZXw4XtmFODJ1#gwY(|*FM!r6tCI1e8
zNs+ZhotgJVGXLJ)yQ13@Gr{8dAN#>zqdlqZ5BM2QrINSiLt1jkUT5Z9@uU9DZO|{8
z{P~b`^K&MvwICZ7p|Lx%%;Ay!O5XIjiSEMTZQc8cmd#e9WkcUSJc`kdmzjRP%_JCF
zf16H~PVPN(f0&%xWfuz`ql#mx3#gTBm)|BND;+%eAJlns%|!mU6Dw_%D_3RaMXjLO
zfnWCT+YB+=tUG>9IUg~+`q#m;d%ZmVSE}sb*g~n(+64w=+_=3wc6m3<u{_)L<G9-g
zvHqS?uKYdiz?Y4YKlI4G;x$t%F~x^J_rI32sh^76jdzoo8th*D)0g`<hu|8CHV#{r
zH?XGH!ab4}0x7{@*!CYvO>MW|mgEH;kj|B(2h!>F$7>n+_2H|%1k~cjywj)FZlQ~I
z6D72MFeH&lixNf${rnF1u*oNzwnP*)d|p5Zye-UaB(w3P{pqIc;63cTlKEoA99k5<
zLkfWzwL;~l_{0I`svjo53Y(%c(Ylo%9lQI6cY)qY+#OqN<55|&+j@BV*w)A+G8fM&
zM%2$yRjbU>I%S^t8UTh4WaO)xh)IOZw-(hbTuS$>-dL+!;9p;F;fPfgLGzZs75gaT
z_?Wv77+rwiuRWq+E~d*HVnO1x23c4-pIMj)N4wQbCs5wsK+IPm%SToNWd}^=u3Bf5
zTqh+ByQ#JC-XC>xUsB-;Tz#kL2c@qkd>Xs(Goq5_LUYyvwor@8=NVJlFCsg~VfiIV
z6i2B~^L(LL7MVR2S9Wlrrs@?@lvW|Q<@?``e4zKesJICJcAg}4(zosNt~=T#)xO8+
zc06G>=8cBBcZO)I+t0-;ay@NVB|lL(pe}>R5i}n^qK08WN7!>7+Zx|q(8WjY@$*MH
I4>2D94_ZKbZ2$lO
new file mode 100644
index 0000000000000000000000000000000000000000..25ab16174c52fcc8f45f80f29428687214570a3e
GIT binary patch
literal 11198
zc%0>UXH*kw*lj`}L5K#V3lgNGXb7mtp#)G76ct4U6iMh<j-aTtkWi#4NK*kD*s+45
zQUnqRJwWK8hX7JUNkU6Vn;Xwv_gnYp{eS02X0m2xz5CtIe#)LSw_}Gk%59MYfj}Ew
zoDZA?fxrrq>l9gt<aeID79u%G2Rj^f0D(T=#S2d4O8)EkJD)rX0!15uKyis6&^jPF
z&w)TU%s`-DI1uQcJP=4NH1BOe9|!~ixw)P?*w@uO)!hrMar-FE^p386TK7<U&p>A{
zup}Iz4^L9Y=^X=Nk(k;2r>|qA@jJb<X=t!}vZ=9cVPU<ehu+oIYjZfo^;{nI%1fA*
z&(^(3Mwq*1E)Q%@6`i?Kkyg;2_hwjaXQ=uP+yQK{YfuTy=mr|sw9Wd)t^+r{BP*aP
zyHBUB-g>+GZ(<2#&pjijI4h6Lpd=E+xe9eW`S8W3?&0rl-fzACZLYX!{blu3dF!0L
ze_rU_+StM_nX_GTMn?_t%YL`YQs2_uy?kxY61@oTGQW(p_fH(Tn6YR7$wJES+)vc{
zap8^lyOfSW=#AMU+4O>{k?vV>&a=|Cp5fC`4<jE|CcbJcu52x9?5`v@fzLiZS_*74
z$Fz6#$``CBf1!<W#77G|Nuz%TXW7-w9d*?1qSjFsA870y>|;!AuH$Fq-j^<H|HWck
zjETF4hS$Wvj9A>+-{0EZMeXaU8=^M%P|4JWs>vp5e@6$M*49sL?QQ!yT;4I%dG*@W
z4<A3Y4mLISG<FWO_6~Opj`wu*Q99@~#Q2zANj!QxXx-Ft#%N1d31gbl-P_#VS2ZwL
z*Edk#)AwB{X7=>fj*O5n7%N9dyZ(M^Pfr^FaQpi^F&Nv<&X$A(0sshxhWdMZyQ$Px
zE_aPS(9}h1?CqxX_cr%-H`Z0=j`V))?`;J{%N=dC{k_zoju-Uq>i+Kf!M>*c?#8`)
z%mD$*^@wwK2W6<AO7Cs$?{4m;H4f9h(YqUm2RiA!)c)?)URrZ^M`LGO{U$lckMh!{
z`X4isBU3%!d#SY(BfY~k(r6E5u)Ddxo7&ycOrtikf6x4ynb^D$s;&grQd5|ux3o3Z
z*4KQW8mEs9cAMyHw>Q@f^mNcW>W63zBRws2S`&Ze&$cZ}eboB?j>be{%usI!y_?!k
zYwhi5?xr^Oc1kc%d%8O1WWaP<>u`VfL5y`jjY_9B(rNA8)YksGYJk5!*g=&6gCSt>
zXnQ*V06RzO&Px&tbp7Npci{i;1LV$yN$Q3X+U0=5smRBE!ia^BgF)XJK%m$JQ%PG(
zs++%qpkN=QhH7eDG5?Bo4IFI4bsBfDGnu<6n$T>Z2i^|1XXk<MJ3;Jym7~;=2S^}4
zU;S?%LZS<wb2PFCfo`4-*h!xQc#hVmZqscegRgI}w3v;69(%pP4$jaZn1@;XHpK~v
z>GPRzd(dZLZOM<sC-E8aNlY}v8iJx+D4O-s@LUJLURrQ(_=3h>aG-|zCopFR)S%)s
zrf3CedN=M)IPTp@+Us4LGKgDKq8L|Gr=%W7wsV-gI`%B}*Y)Jqc@1|Bf`u%)+TYmu
zVRKlE|6Lh-5L)cn>a8xiLM36{HX6X|kmaB$i&Ul=1qR)aTn@*Q(bSFb*9`l;uv1(0
z_o}1)k~SRP?>~cyhJztowR=#=3aCa-*Ukd;BH0GC*ZW~Sa}T6J$EWmy>~gw>j>)Q}
zppewgs8HX9)(WWT$Z95w3+I_b>X37BAit>kEUxHD7tzT%CkPsSb`s(|C12D{(vXhR
zNJ;`1t2m2ceom#ZL7eLTp)UJ%*hX0eE>h_p;>9-52c%XIMnh*P^{2d}>XltxtE547
z*#ugJ{vsOWZY^7CA<Ti!DB|W)9UWzV6SB5mCTe)8S15M3E^)VYJ=0bLNu_3IKWd$o
zZf2oua7>i_82LjZTeJhV4`d&|f?V_rNlgU9AoZr|Q|MbcjyFfb;q<oW?Aqt8U(9f@
zhx;1PZL%St7q@2RrIi$=v%Z=lR=SBrCWV!?Xj!}UEl>q}Q&&dLpgJM!vqf>-%cQtx
z5l@+{Q0OAYZ8pJ?Zv;U(1=v%eZWY4#_5G@wb!jiVRQ7`oJCkkd6K7O5Tt`lTTjDt~
zM>ko?=xJ_m0GXOiME}&#aabvgU#OahxdH{Bkq}tDv+zsOljg_q8u=%rBkiG>fXJPE
z<$JN>Qc!Q3+Do&*{fD<HfQ}oP61!fkq0Cb>5B@Srej`00G;-q-$<Nf7r#-*hgAQcK
z+-N_fj?D*e#dl2y^PoGUf-PQ}<0CmImPb7F<RuGb2Mu;MP{Mpxkcma`eRs?Nfv#}F
ze$36dd!cdj(u(>OQV=VB_0rR6IGuRqE%t1cD`b>%VCsbZ`>M~=Rps@e-BJg+UmA@D
zkjPgKCOc&F#~G>4v4P6&krJlTdzCZIKjE^(+=CB1c#tjwIXEzWK8UBgBVsM(gBIn5
z8Y$l7)*m{e7F#5j^vA+dDd(A%@fn>;h=F~Uqx4Suto_mtoQh1Ot(?Q8Wv@v&Y}kBj
zzn!jhcdsn4e;Ijrvid_BktSBFS>Q94GC`EkU2hcPKna4(lsqOS1;JtvL27%yz=Qvc
zrXM(n!TaGvVAEYM36QbQCT^Ny4P5KX#4{~QsEZ-C5pdN#v`>XZzU26q6tLPQA#1fj
zY=*`w1n|fd-G=(GJ9=5ZA_OGcLyO^MMG*T%HgnT5m~@O&$Z1%HSENJo!?o`4`e3ci
z#)_LP<WGv@mEimC>*VQN4snr|#>wz5xtiS4FWnc5crNqIV7o%9&G5(C#R%aKHIEV=
z2~Xg->zQfsd}7Q%(h4?7LVw=U2KC)iQdo5{C$4@@gu0so*D@6kFA^}sDowO`q&41u
zvOeffmUO7bWTZwcumOL1VphyAJh;_xlSHF@I**X30mlROociShpnEW)nJnKt-`Un&
zye8Ulhe0p=JrJxRy?Vu*^X$7T`p!X(4+B#n=W!SA670X8m$APvy~Al|qTJJXmlbWr
zEm?7=rpVIuMF<tXKATQ{QZ}KelsEjoL`uiM)~tGVn4_c<m#@>2nwfw*Z8Px|+|zRP
zLA>vtMA{S=zGN!(I8<yF7GqXjn|9*U#`8Mtrv>+!&HJI9fISU}*||vxCaa^WvUbyL
zC00mT%A8j!j@S<RH{?l8BlGi~b8H|ZG}DSO`W3deeD{l(zq$;|c{X_auBMKobUR)?
z&+$?+Wp#sY11>NXUh0w<wr5|)#Jj*Oa_Dc#9)gZYkKV+?E*81i5nrMvT8yixY+&r?
zguc-0Uc8D<+(e+PlCc+&urdchd_5}2kN?vbfty+ykxxc`0RKjHnoA4)1Zm@{TdLyb
z1*`vVy^A%-A6!I>V`Va>B|`C9p4KhSYy{>@*l!Tz=jxsb_(^7z_@KMzQ{QC{7T#2}
z$o$Stu#7)J7T-}b_;O-oTWW&TFg)Hv6!Hr6e2<iAmNHW-vNuuYo|BhO;D(B*CC%-1
z$pgn7U%DL&L%_F!<e`LskwzRGX9Gmly&YTor9e5Ae4eb$Dlu9@T9F=G2Z%Lw;_RPR
zz)pr^75%IbloWye8_sXP3ed`DQwp>c4D%XlC>Kc$!~hy*=AiAMJxt$3hx|H@(%?hK
zi%;reSHK~aAYE5aw-gyq-)#w7wAtHaTa00m4bs}%$>fRT5!0qPaP5*gK9+`(**&G0
z53n<h5h3Xioj7$3B42yT*G(qKPutLKBj*+%QcK1#G-|^@N96Ao{>G^D2qK)AS|???
zNJ59jCJvaV1KE?XO4GV-twS3RDj!ThIq07(eP&<-HN7uuy;tKwrdznD-ShV;QoaYQ
zZ#f*eUZ|ZV2c7(;BeuMPJFlz{mPi}p6B{(K-X?u9CGJpTq&DEYUJt&hqQ@-+F!rCO
zc#@r|moNquo~#0Fjy1IJnXTtH_>`WEbhM`fwIwfKWO<#fY3tf00O8g#I{sacdYq50
zMWl9thQyvs8Y(#?%Vna^c=eIP%r1(BB*p>LK><wAgBO5~C@kz7knsn$+noSg^Q{g4
z5<4wuTuaMcRhm`P&Znp|zfZs_PQrIxJ+a#k(=Kx38@Rkin>qWX+Q0jL=^y(%DjGi(
z@3f6h=O$FcQD4APsY&yi3{35D?;^0Sf*7F<2K9f;(gCme?$aPhCH_=`?a*VO93nel
zM^qd`2I{0_%ayiKbdQI%`NK-@K`)sVLE+CUTT)+d+G^%_zIfSb$$+J&7<p1aBX_p&
zZ!<L{1IP8UA2rJXVPj{A8S@BAA+?RF4w#q5c8F>9>~&1>OCA-tzpTWy6qj7alEgXd
zP4G+A6#k|;bQ@^vZAav#*hY}aNLQI^wCaB8Y2xk@^P==a_3yrtTB=InKPYng`F2^+
zU2{!HJC~?M(kNW**(9+c!0wC5MF1j6YSm;5Cs+80##0LmGf}|FXsIm=1zBxNvqsIx
zPobvB^-8g5y`6vme!Spq92r?;8XXF?HHhOC4JOJc@0(~)Kqp^v+aeQp$H>Vzcf&Kp
z*~`xc{1lSrX6i>*5$_5$jy}FGutvg4zsJ3W1-`_ZqHahy{k$KLO6(!-3e%1S_kE}X
z6<h;(U7*BS9lwUm$o$tQS(%+zy7@M!O7Jz#KuY&V8|YF2olF)|!saOqKq@_26C@>j
zNjf6{B<WwTh}w{miwyNe(8#4^^3AEuP&e~UkYvr7efq^84weiMia2OZ#bQuRd(`oq
z@T<qu73JMx8==QIfckh`6p;Ta5+oI}JE;g92a?+BD7GjCTP*FzeU^HdFQxLZ$oByI
zvJ%7;k#LP4Tq=vXQbvw*D_F{mv-t>CI{db=y-V(LdRRi0bo%qqX|FeFQqo-^at;s>
zxFPb_SDD20u5Ggy$Q8N%SwVvcR|t3_hiOcKK-+I7>;*$MB$?H?%SIQ#wp;L?iGtnU
zYwn&jlycoxk9=&&QmqoebmE-cWw(H2b((Au%1<JGEQ(l;FQF?6MtvyF-#8h_%QItw
zy2ZCz3m)2Wpe;wYg@AP8!j68Ql4gW3Z#zi;&$e`}l8VY*Q#3)cMcv8?P|5T)t$gjV
z>L>LBp#NFoxqHi5oS-ww7eP4(bsF^h=ePX+lzo41Kn}z)f#z?*T`?Mf2$s}D#2K+f
zVXi(P@BzHWWOWK+w>w|OTrys3zJe$vDoa{pcec=XCqz#V7)CU~;imRvz5t`p)e{Jj
zKuVocu5WJPrPRe*E*#9-#IUOORbY1PzDAGx3-lj*Z?1W%5JRRQwj}uD{bB;jSXvvP
z$SqZu<3RQx#jQFqKp9*3Qw&fxH$;`6btGQdc^ptJ)E&0^7x(u8Y_T|3ye(4hACyr8
z`&h`#1^2?8=lK31)1~oJ62NBmL5ZptORH6?b*jdu;aNzCSD4$=XhYl653;izZZVZ9
zC83B61C4!>Z1^3RO7`vS46Wj-|I`-Go`@12eH>pf|9SQFCsyHVXIWaYRv?dGkoSmb
zO~u}2rE6WJsW)Q7<ZUNoI+s$o7!*bAQ}AWt3hM2s2fkBheU-I?V+7YCt}_mEYIvX4
z*O0kAK9wHWLE_bO?k4sUYFf@38l=~yf~%zymm6PLNBG2foPAh^wlJ$e%i$|KaL!=?
zS=qBciLWDUI%l+qJR+X3mdV+{vfi|KM9P#HkyggO&{B5fOLZR5w0=mq1x1fdvt;QP
zrf#?$>pvr=n&?yXt|mQk5G)*D6aYR;cDb7;nZ8PRL3Z9Ffjo;bwgiw$!%9#5D>9W(
z*=bH*Yl1a-wJ(NiY=S5?&+hcbYUKB6hd+{i{WMJw<L(m;Te$G-jd$Uz4eBq*k(nvj
zsp<1GCFw}9MJpaXjpr2tq-p=$CvtfPNh(OQ>PcpWX;2L}<0~2V6G0@!PVoVsc|q_1
zy&dI6FfRoHMQcgR89n|FA{^7bi41&@ig4Zac06a{5fScj1HksYI4ds^tn6!rmdEdI
z2|f%l9H@Fea-U5e-e%;eM6YV+`w*T)wPca9PtTwgRnMQ`HAO#Kr)Z7?Tax+LCOxzX
zJ*sDBCj4=31HE`^5sp1YLwGGig!OVXb!ioiK)bhx#gfpm3g12ML!8gRG@)*Ns|A#2
z%$W*m?pX@=H{*J~MnT$N;Z^0lk1O9$Njv}KxPnCPbs*mWo_d=OCt5WeZrm(X=83t5
z!^q@d8lg5w*xI5}61AMO#2R@`dqpC`z72*w3b$l$TS!D0HW>oyNhPF<B8mx+w>+G!
zb~qx^5{O;p4vfJ<F=9~*dzrf<89-@oo$@_1OL+U-c;~zALY@*$&+yI*WajARZ&qs@
zFe`RZla2ut+^PZR$v#crPI}Bwg1OMP<<LhESXQS#P*$Fz#a5QqG@@KQrojCJfj$kz
z#-&Z_8J~?*zxnw{%~YjJi+YoF`^k12fwqm?gz(~Xbv^O?>uHZD&7Y3|-YOD<JL4}V
z9*jFD&bB~I4WWXFLlqTP>UN{}PSI0lZc84<2L2}CV1A$2JT-rNaoOX^lS%?&X8ih|
zk^(cXyo}Fj+|!v8FKmo;{ss{0{O(;T`_A(Pl6ox~&lYsD9n#Nvf<2d(<F-E{u`~!Z
zy)hq!zeTwv$hw89{IG}3ytCrGQHvx2D)jI*#y-)sh`2gS^BJ`ktjAYvE`KQt>9s|G
zo9Ge9Pra(jm8+-IxeE*DumuIR*B(dLzkk(2yS%peihndHnSO{=s9+X@XMO$$LD7q+
z!D;FhS5hwr1mHG%ANh~21n?I%Pl9HoR2dZu4Y~=v$sw5!Bka(4kzU)H_Se^wYLuhN
z=aH%Tv6Ft$txa=c9)MlVgik)NN)W=+-+jOUoG<9dQJs8lUsMw7cx`G6Nw&sRw`gsC
z`RF3?VwLXXXko|r7(qDSX#q7@Rr{4$`{k18dt`kPl`OuW;c#w(Y7zu}`UWAa3>6V+
z`v+wj{#Hg$s;o<X=#b$m(<r1#ZTF6gt71Kfk%bb{x^zJh7hk|sdp`$cB6qVEEbu|R
zW`*QlEe_EY5&0?B%s+C4`R@C~TOuC*J6L=noJb#^|IijYU4x-06{K+2YabR??~FcQ
zDCl!}D!ASL80&Rx!&NyVE@0n<O>&}<hof+My2h0a%U9*Kz6DKGY`<AIaewGV$xKYr
z*jp8y|Ej9~uJZ@H>cWoP14fKEh@RB`q`d1^By(d0^I0a0Ni;=%y!npcFSvfd>DIhJ
zuQMXrL!E$B`5|y%m(0)84g)GrKkpk;0oJ@kNpUS@2rUl-pW4m5dUC{_Y|b5CqLF!t
zdbyLixwwj^rz_?s#!Y;~I=a$iG7oD<y^lDX&y9m<JZ=8l*uuWO-yu}};-_`;urr8y
zl5k8fM5iW(o9vLo+|jES)<|tw*|P9mMPXuKc49`UrbC>5Kc!%KepwAGUJ9!gQK(Ck
ze;y$a6+SlZc+oHOg+s}+#3ABnp5H{C5O^xcl|`zR+KKAcGdU#*8O6KKnNI<zrQeL&
zCy>`iG+Z7ur^B%TX5wCSW5b(8`=nA3L=w8^!!ijaSvL{J&SG<Uf}p65y`@TvqedZS
zmyw%BLLWoz>x_~~c!XWG%-&t%&)0rke0y6+>{t?Een?}ep$~u$hIN1^snrv}EakaO
za7&I@7UbW$1;oa10hUA}Nd%D?wYmoGJ-r%(EwD2`@|okD_5~Xqljq{b#+2wx5e=`N
z__jk?M#>!YSKmts@ke<K49?Tuy>&s2<@L=@Dsf6JB*QREj92$mvp{Rv@)4okd|>19
zxtVe}tzU*=hL4F6Z9>W$K~hFbEDwkNoE}>b9gET<>sOpR!>5%a+D}#k7>vkJIB%_F
zxr_osp;4<?#-fne*-<3^`EBJsGQGN9O+yBd4_~Uz6|w>9AtsS@{L7P~GjacwP{kme
zYyggzJlIm#M5fAk?OEQeuFaa(9%=)CBOx$EsVzV4Cki5P*Ej=JjK`oh5{Z#qANy&`
zl*vmojL@60r()^}T#OQOndoF<H~_GuD`k>U93WQw^Zs<iCn9q3vu)Qs9<aEFjxm77
zM;r&na`-LA^<+~r<Z|`$hU!Y8_Z)hLk1_{Kdfy_|CUCI*B|$WTn(OiUjx8DVD!F5y
z=j8(cUVPK?eR`M26c%@e5Pu>~0C9V?hxZz~WcxyBB^{6{7)RHv8}dYy;Gk{LyC~By
z$6qeWS&W|ofI<%A4U6Fgl!XgbeEBrv*t|4{3DzpZoZ)jAAN{JH9C?0*fs8+dFA<As
z+Bh6Wu-5|&P)EhRm69kszqXxtC7A{^YLJI+G3l3%y;dtd?Lr6SuL8cHy^jnwY_hT-
zF{>zTsJ82@ty3@5SWj*EoRnNaM|gLpD@jI1V{t35p^mn~jTfj{z0CwPWUOSART|g5
zDk2+6#<e1&`t@^jCgobBimo^17t6gg3<}W~EMnKG>nn-*RqdFeLym>c=POfSf8(XR
z^s90cBzMUm+p^lbXtjc*?s)}$jmY~1ovc=x_RSxm6zd6d9qx4TH>*5<JY|1x`&lVT
zD&#xnt2Y$Z;QC_30?bN4CKf)5C9;Ll6f*lv785uGST5p;Uinv1|04bVb_$OlIYwUM
z^Q5=U>~mSOf6n1rw;5Ajm>MiOP5&Wo^SOIG{d2c2yig2i?k(FbsYDg!g2xNC6wRlP
za&ksV2I`+a*RJcgb<%h<n1yiY-4dj@w3sMhyR^&9nyBsH^q=ygI)y2D=x@}yC&h!P
z3nnIpQ7$*1SvuwjU7Kzrzi8}^B$-uj6xY%-296BO|E)2&IN_9^pnl(>)7}$rjVb%b
zusL*3FQQqsfX}2i|A3=@6P9GJv00+#(md@eujKzGoy(K?Z>6cq``4*Le^aGpEDYnu
z6WcFyk88gUg>S<2ee}6wi{n%3r>oUw=Pmbd{Ey>$!*<Rg0V%BOEjf?-+Vl6dVE<k}
z;p$T+A}@rnZuFV~REW1*17pka7pD{<8~;L+yPDLKiAf>aHREVSJPs9gWt;&Vy@w3D
zji0WahuwQIjBC&VNtohqM#M*a$g15*4|^;OmO#{fM?GzSxiu`!AqCu*RW9ZT`a@e&
z?AJ8Y6K9hlk_U3!TlQ~K^}=c1s@sSkRDnEOf4dF#-<t954(Fx(T6EHzcm5$_NNtZ5
z_u}i;X8(Njb^k$@Oy${+9j~B;QO)hZsT`T=exECYfg1mbLG0iTH8n});B#YI*@=hP
z5NpcD*J{YH1+9mY=(l(|^Zo$DO`i}&``x{hvCrfb?4{jPZ8mYV&8$WrP|eIh(p_QR
z7Y{4`H8!BXu50%eoxdi?2_h|Fuq!0)ulw1uQDL{lC%ypxbv_}x?Ykt1GN6A=&;RpF
zEk{q5I8M1o`)#zOcob>qxF4jOAO3Io|84emPoI?KpPg4xeh3?ml6FxksY~I5|L>ds
z6zz7}mU1W=T^-Xv)}iw6ga425D%zIk*rnF%Z$-PW4|<2y`MFs>(#l+d@b!NHOo>U4
z5yG)X*VP@HZhjWc1g?|GbFP8mKn<^h>yml`^j$S^%biO5k+M+EXkSp|O>ZfkI8SxP
zN71s^9j0x+N16+Pw>(v{wEyBGLC(3kwL&65Q1tdbE(JO|cZqajJr?_bDXDm$&Ez@O
zjLJ9qj(;xTYa^bc0Asu9XT#zX#uK8(?Yy)+Ci=IW<9@jgYs4NVm&FK;eEHf!B2xL~
zA4M_1DT2GG%c<MC@E(hyQp6A78GV8QN!qgPdc*rB=h466yIy;#d+KY5-&;gpmPqLV
zx95j=tAg(Jf2`*x(232es>``ObHV?(%lVYfZOt6t848(le|Q5|{y@u*PZu1%4AZj*
zp|vaYxcw``#E6TtHwsc7Rj<?ndaJyf3FNtrET<v5(`<2|c1WexKDUfQVJ~i?N<ts`
z>`Ynbru&7L-aZMm3%_GS2ofa!3T#PXRd*j!R~|fA95C)bS0`}Y<CFQb_KM}-&mprn
zsz1QZBi7&6bWP2MCS_6JrU`SF$|vP`1|GMB;Xye30fS{b2b#7;Y&+!ozg9{T@_yGK
zzveM_S#++|AN&L)cqEaG&*uqSTiZL>1!;oMAl4tE5ZRBt7CRNy{4Vn~L8W4h`!K%1
zA(46iMIUldd&L&`X(wyLB$n{*FZ{vQyua;A=e@!RV`z1)D*&2yNaow>Nd_WX2)tZ5
z$TvY+F2KfT0R}ae-$K5e7-Uzx7r!!m{6NBTLY?9x%`Guc5c{+~TZIr$&cbJd$5F>Z
zlQQQ?_hX8}ZXI=8teJ@DEUyoC)i#dPaclY&FXd|cc;@H5ee(^GldG=r0QRBSR$5ZB
zjz(M&zh_z1-ZuMePUN?n3Nu$3BJ8<8NezW%ga-jLH8kgjCvOzUJRpO|Acn33gdm~8
z>e(5J{1`o=qB8R3__+I|g0TL&eRRQ51?#CiQcpxA25sXn(vLbc$3pHk1bfenc?iQ3
z{a-A~Fl&BCyo%3Xe>w6In?7oJpaf0A5y&fNevMs94%Vu6O^2s9>ubmEs|R215&Zxj
zsJ+&9BKq@J*Y}mH3%75Ol#{{h#MX9QcH+;U7*5Gqp)P}HAq+efaX+X6NSht$H}dwD
zJK*uY9gf{)!QLPbId9x95ROC)1)u!zyV|>ae94>7&s|7N^jm@LeNB|g1m?q>Yfp-3
z+*K5vsQL-B4>7Aei{~eu0JgJ2!71G1QG*4w+sC5}MF)k{SSQ7xXO^f?{7GdM(ek5$
z^$`z)px2?qX@W`E)s|`%|Ae<G-FPg)HeLL21sb$VGGf597<n&m=~wQ&QVaf`PvV5t
z`15HO*PbxnY|_kxQxF`r10_L0qBo{Io)UwUm*f5G!*g#}(vXkPm(QEaOR_>Ndz{F9
z1cz54$8A7o-ZS!p!pg+FhL4>qm-KR<N*`OkGAC3J8Lir{^u`|#{YbLOIky(K`o{?B
zqjWT|8*$O~B+)Lms$Oqta>J}z&>G1bPTZ(L*npoB@--yn0yy`+(@{S(p1S|7@ei`6
zL_7z3-nL#;_PL-4lCxa30JxjEkVFoAp~kQ?e)`i)cdvcz(x^Y5%C>i&yu+hMB$Vp|
z=o&Fac$PKn0=?PVY-))-TrF%e=v;b$T^qAt5iJAlgB3&>1kOhKc}IA;>n6grie>xc
zc#o|04)8pYt7k_F?jv3h$IUN?ekWoW!YKie%Y9W$mQQ=6%divv{Gs2%VLlmW{Lpn<
zHH#%-0N}={12VNrTO_kX-Zt93r^E@|S6=6ODwB(<E0H^HXNLDbF#+BCoP@c@PbNe_
zkCE4=04!9MLzA;#`^lPtW3h5O%v#WM7}(w?8vToAVWcdy-2^%8HtQoik?o%J-t`)`
z!Y7S6j^2gO!(N_+>~Dgln^xCL42?;R;*3a0<G<5?4_dH*zRyE0hF=T=6n`q&Q3W$3
z4aytfV(@`DnXhXu#nFbwB0!IJuJTYj`>FhYa-cDYME*Ox04C41W|D}zWXHZ+g)ihb
za=A!lh8&6cQ@5(1j+1o4d4gpvhK1fDeh%^Roe&D{Fil~JYl)VmeYKCHitCF?!aODn
z1yn(aK`rU*)>mx)d!9#`Jj*o<D$A&efG=^^?G|jLnn-<#Kmw32wi(|^=?EKgy~p}T
z5OYU<wD~1ZTWDcN5wPkQ<@j<d<xhlQbeu%Ka410B{^Z0hhNiTn4^y*3)8UR%mOypP
z^0Fqx=tX>K-M`R1r=iCj4kpir9;`J}JWs`|WC7uM>u-iFvx9%NS(4bXXL4)T0g@>t
z*aGI;R7gakjkSDv&pR7LwBJwu!S<b73?0QLG2U;V+|6o@{dRn@gy&fSw1#gFH#4`u
z1c{B7xEOBY4;!^l#D3*+(B6uM!pG6Az$#5`=ZU~F?z^1wuYkz!FIt9rp_x{sM81Ll
zO>E9$@y<4C@#`yV8HJCqQ@tba-)WHt#tO<jj+v!a2l(n%<_fhvbH{U-0^w@kZ07Br
z&|~xH-$B!$u_uH&_C^}rdb=ZeaX8p+7c|+uup-oa!mc&Nom1Sip*9m!iL@{yDnvC1
zJ?1B0P+b9%d3CUwn=fx=ZCH>8M|x_+1qm%G*HrJ7g}$rFQ}`k8j(Ab2-Lj)>hu{~v
zUFJVic5k*b6Lm4OfOUj3j&Bvsp)4sdr~y<p9;1pJFEzfZRAmj>RDrPxI3cDI?uZr+
zLG2a+<c$vT!&p&s0Q9%Hjc^;p^yv5^T5TezYB}9OU`RRSl#JcXI3}$8lv(D$U$dh!
zkPFg29I9=U_^!iUQO9{(D=!(bQAt!jP%};7aubVqJHaj%h8kB^OKuaf;{h0h@L%g{
z&&thK%^os=o)}l|G4F%|`M>d3Xw{UW2OtTx?c%}{qG7MDZ>c?SV#yXWGn+1a(G3o=
z+iM0k1(b(+HDDe}4FPw(#sch`)&vYa|Kyayts1-V?l^wir^o@``-VeTk}n-jDBsOk
zCiqSWnp0v<B^=CNw@c)P4xtM3fmp&~*h&5f@ihZe`>;9?7u~t;9PjX36r0N}M7G&f
zw(9Z^oaZd~XTUb2zE%R1K1xUv_e6S06hNUWNIHYM4$bSHPc0v{>dEPSRA@8V+=n!-
ziG9NtrM8a%z&>o*c7-v4xKVU}o>ds^=utVo)Iz8w#}s-^H;&H<9&hKO*tYioJ$&*4
zook_6*eLc9ahb1#MnN;jO(#(YSyR=Ia#tHJJ%JGkU%udHnEw249uuF7+u|{W`FnR9
zsdcwOg(cpPcUiY%D5X(N+f7mWivW)g{4Qkl(244dTkin)D;Z^iT`tfLW?chID=?po
z>0%myC3D%)pb5X2=C(B<5|%lqcWjg4rcYQKB0#Klx*QiqJmKdXbaFzp^ngR%b7Fvo
z;f=EopwVpG;2BXPkjwcfEX!mi6%cBp#Zz31@4?5%W8GE6?N=Wt1;<(Zg4zXq%i?z!
zQ5tpt_ZOCFh#x?Ov02MCf;jf{1ZKx_I5QZJOd7xNHjRBz7)jY#&(D1{_3;bYB0pMP
zG$B5;XjJ`>eG4p61LVNu&)G7+%Y}C4=0MQ8z)5j%A)33Sm)D{;jxA(}-0}P8poaT+
z9oM-vrVJxP^f3o*Rl`MwE&v?HOo<~X!%Wc;gG=D-lwa-MfEbO>6Mkx4n}=AlQXZiS
z)V%;^^_{7)KT1->W5R&g6&JQ%;$U8cR;COF8LQJGkZ4r#6T`7Oo&NHQ*_RD~phd9!
zj~;CYPRTjv#59G=_^aRS>?iT-^wW_8Fj<}YUWJqJbR^?2FeQGuay;wj9++C<KL~-P
zPXR+~ltC~n_8sp|g$M&Dx@A<wp$u_kbJOzi$M?DKdA8qSuELlBF>i&{b{j#gurn#M
z<E^vG`u04<5Pi&xFCDg3<%yKu2=<-Ayx(3R-0c>oJSlpwH@DJ1|Ew1=glL<TYI|M{
zMI;68wDTmX5KV-R`P7+2t-N}~2E(cH+rVzzFW=pddXFz-&z@y(+yD3DUou|BkGGUD
z`zdav;}TKb6S(MOQKi4mg`|)pcD3e(Y75U8?6ntLq*kloHsecp$+O>h^dFZk*L{|1
zdkJf4C&)}PBd=RcMw@ef8fXy|9=rumFt6UjQ5qEiC9Ssg)kBJM1aEP~41>W421ebZ
zO>X{d&L#!(d|H6h{|EphDz_vv3Ym%woSm|vEjx?smSf|0_|Xa8xM_ZPGHX$@IQopS
z=pt$gG9&Q7`47NB;D*5k!qUgDOD8yL4g7Rx9nNnOD6@^^-#1R(-n24{ge=Q@TViq$
z+RkmYzEye~ByMNYXz&0Dl`Y!;ahsKTBww_VG(KdZD|c!yS26-sWu8&9uzise#n$-e
z4l$D?Jk9(24(edOSiI_2G?1#LHD_Uivw2r^WOc-8+Gh?pXM4%A-^qp<5n&gQrG~5E
zASLEVGTQa;TS|@>ZS?u~W#a6ayvChkY)<sCz;H$ls$e%qU9EriC9zhC8EmuS2Gfbl
z-zX+^=iuMpd@`&WwruRJL~0kMTnvWn2RCySoU|84P{lVa2kxL0*ctIG${x*|CUGD?
z-`eKNnT!?_#r7R!6G-}z1Iph?icxw;{td@4@<ic@Oz^ih8&AfBH6{FN_9KM8q)A<c
zzW6QwHswoA_o*)+C;=@FmOj7N_0RB;Uq~edyPOvfDoY(tGq)|EDx2W|SPBk$XSuvd
UJ3qV?Bsp9T9y{>K5ts140Nz{d;Q#;t
new file mode 100644
--- /dev/null
+++ b/doc/interpreter/java.txi
@@ -0,0 +1,958 @@
+@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
+@strong{FIXME:} Need documentation on how fieldnames() is overloaded to return
+the methods of a Java object.
+
+@cindex field, returning value of Java object field
+@strong{FIXME:} Need documentation on how to use structure-like indexing
+to get fields from Java object.
+
+@cindex field, setting value of Java object field
+@strong{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
+@strong{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?::
+* 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 @sc{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 retval = isOctave
+  persistent cacheval;  % speeds up repeated calls
+
+  if isempty (cacheval)
+    cacheval = (exist ('OCTAVE_VERSION', 'builtin') > 0);
+  end
+
+  retval = cacheval;
+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{javaclasspath.txt}
+@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
+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 will be used frequently 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{javaclasspath.txt} (or @file{classpath.txt} historically) 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 @samp{#} or a
+@samp{%} character are ignored.
+
+The search rules for the file @file{javaclasspath.txt}
+(or @file{classpath.txt}) are:
+
+@itemize
+@item First, Octave tries to locate it in the current directory (where Octave
+was started from).  If such a file is found, it is read and defines the initial
+@var{static classpath}.  Thus, it is possible to define a static classpath on a
+'per Octave invocation' basis.
+
+@item Next, Octave searches in the user's home directory.  If a file
+@file{javaclasspath.txt} exists here, its contents are appended to the static
+classpath (if any).  Thus, it is possible to build an initial static classpath
+on a 'per user' basis.
+
+@item Finally, Octave looks for a next occurrence of file
+@file{javaclasspath.txt} in the m-files directory where Octave Java functions 
+live.  This is where @file{javaclasspath.m} resides, usually something like
+@file{@env{OCTAVE_HOME}/share/octave/@env{OCTAVE_VERSION}/m/java/}.  You can
+find this directory by executing the command
+
+@example
+which javaclasspath
+@end example
+
+If this file exists here, its contents are also appended to the static
+classpath.  Note that the archives and class directories defined in this last
+step 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
+% contents 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 -
+
+The function @code{javaObject} can be used to create Java objects..
+
+Example:
+
+@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.
+
+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.
+
+The directory where the Java options file is located is specified by the
+environment variable @w{@env{OCTAVE_JAVA_DIR}}.  If unset the directory where
+@file{javaclasspath.m} resides is used instead (typically
+@file{@env{OCTAVE_HOME}/share/octave/@env{OCTAVE_VERSION}/m/java/}).  You can
+find this directory by executing
+
+@example
+which javaclasspath
+@end example
+
+The @option{-X} options allow you to increase the maximum amount of memory
+available to the JVM@.  The following example allows up to 256 Megabytes to
+be used 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 ('getProperty', 'java.lang.System', 'MyProperty');
+ans = 12.34
+@end group
+@end example
+
+@seealso{javamem}
+
+@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 ---------------------------------
new file mode 100644
--- /dev/null
+++ b/doc/interpreter/macros.texi
@@ -0,0 +1,67 @@
+@c Copyright (C) 2012 John W. Eaton
+@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/>.
+
+@c FIXME -- someday, we might replace this with @backslashchar, which
+@c has been added to Texinfo.
+
+@macro xbackslashchar
+\\
+@end macro
+
+@c The following macro is used for the on-line help system, but we don't
+@c want lots of `See also: foo, bar, and baz' strings cluttering the
+@c printed manual (that information should be in the supporting text for
+@c each group of functions and variables).
+@c
+@c Implementation Note:
+@c For TeX, @vskip produces a nice separation.
+@c For Texinfo '@sp 1' should work, but in practice produces ugly results
+@c for HTML.  We use a simple blank line to produce the correct behavior. 
+
+@macro seealso {args}
+@iftex
+@vskip 2pt
+@end iftex
+@ifnottex
+
+@end ifnottex
+@noindent
+@strong{See also:} \args\.
+@end macro
+
+@c The following macro marks words that aspell should ignore during
+@c spellchecking.  Within Texinfo it has no effect as it merely replaces
+@c the macro call with the argument itself.
+
+@macro nospell {arg}
+\arg\
+@end macro
+
+@c The following macro works around a situation where the Info/plain text
+@c expansion of the @code{XXX} macro is `XXX'.  The use of the apostrophe
+@c can be confusing if the code segment itself ends with a transpose operator.
+@ifinfo
+@macro xcode{arg}
+\arg\
+@end macro
+@end ifinfo
+@ifnotinfo
+@macro xcode{arg}
+@code{\arg\}
+@end macro
+@end ifnotinfo
--- a/doc/interpreter/mk_doc_cache.m
+++ b/doc/interpreter/mk_doc_cache.m
@@ -38,17 +38,20 @@
     error ("unable to open %s for reading", file);
   else
     tmp = fread (fid, Inf, "*char")';
-    ## Strip off header lines
-    [~, text{i}] = strtok (tmp, doc_delim);
+    if (isempty (strfind (tmp, doc_delim)))
+      ## No delimiter, copy verbatim (this is the case for the file
+      ## containing macro definitions, for example).
+      text{i} = tmp;
+    else
+      ## Strip off header lines
+      [~, text{i}] = strtok (tmp, doc_delim);
+    endif
   endif
 endfor
 text = [text{:}, doc_delim];
 
-## Modify Octave-specific macros before passing to makeinfo
+## Strip Texinfo markers and docstring separators.
 text = regexprep (text, "-\\*- texinfo -\\*-[ \t]*[\r\n]*", "");
-text = regexprep (text, '@seealso *\{([^}]*)\}', "See also: $1.");
-text = regexprep (text, '@nospell *\{([^}]*)\}', "$1");
-text = regexprep (text, '@xcode *\{([^}]*)\}', "$1");
 text = strrep (text, '@', "@@");
 
 ## Write data to temporary file for input to makeinfo
--- a/doc/interpreter/nonlin.txi
+++ b/doc/interpreter/nonlin.txi
@@ -172,7 +172,11 @@
 the zeroes where it crosses the x-axis.  @code{fminbnd} is designed for the
 simpler, but very common, case of a univariate function where the interval
 to search is bounded.  For unbounded minimization of a function with
-potentially many variables use @code{fminunc}.  @xref{Optimization}, for
+potentially many variables use @code{fminunc} or @code{fminsearch}.  The two
+functions use different internal algorithms and some knowledge of the objective
+function is required.  For functions which can be differentiated, @code{fminunc}
+is appropriate.  For functions with discontinuities, or for which a gradient
+search would fail, use @code{fminsearch}.  @xref{Optimization}, for
 minimization with the presence of constraint functions.  Note that searches
 can be made for maxima by simply inverting the objective function
 @tex
@@ -186,3 +190,5 @@
 
 @DOCSTRING(fminunc)
 
+@DOCSTRING(fminsearch)
+
--- a/doc/interpreter/numbers.txi
+++ b/doc/interpreter/numbers.txi
@@ -570,7 +570,7 @@
 When doing integer division Octave will round the result to the nearest
 integer.  This is different from most programming languages, where the
 result is often floored to the nearest integer.  So, the result of
-@code{int32(5) ./ int32(8)} is @code{1}.
+@code{int32 (5) ./ int32 (8)} is @code{1}.
 
 @DOCSTRING(idivide)
 
@@ -773,9 +773,9 @@
 @example
 @group
 x = ones (2, 2);
-x (1, 1) = single (2)
-    @result{} x = 2   1
-           1   1
+x(1, 1) = single (2)
+   @result{} x = 2   1
+          1   1
 @end group
 @end example
 
--- a/doc/interpreter/octave.texi
+++ b/doc/interpreter/octave.texi
@@ -19,46 +19,7 @@
 \input texinfo
 @setfilename octave.info
 
-@c The following macro is used for the online help system, but we don't
-@c want lots of 'See also: foo, bar, and baz' strings cluttering the
-@c printed manual (that information should be in the supporting text for
-@c each group of functions and variables).
-
-@macro seealso {args}
-@iftex
-@vskip 2pt
-@end iftex
-@ifnottex
-@c Texinfo @sp should work but in practice produces ugly results for HTML.
-@c A simple blank line produces the correct behavior. 
-@c @sp 1
-
-@end ifnottex
-@noindent
-@strong{See also:} \args\.
-@end macro
-
-@c The following macro marks words that aspell should ignore during
-@c spellchecking.  Within Texinfo it has no effect as it merely replaces
-@c the macro call with the argument itself.
-
-@macro nospell {arg}
-\arg\
-@end macro
-
-@c The following macro works around a situation where the Info/plain text
-@c expansion of the @code{XXX} macro is 'XXX'.  The use of the apostrophe
-@c can be confusing if the code segment itself ends with a transpose operator.
-@ifinfo
-@macro xcode{arg}
-\arg\
-@end macro
-@end ifinfo
-@ifnotinfo
-@macro xcode{arg}
-@code{\arg\}
-@end macro
-@end ifnotinfo
+@include macros.texi
 
 @ifinfo
 @format
@@ -129,7 +90,8 @@
 @sp 2
 @multitable @columnfractions 0.4 0.025 0.65
 @item
-@flushright @image{octave_logo,2.1in} @end flushright
+@flushright @image{octave_logo,2.1in}
+@end flushright
 @tab
 @c this is a spacer column
 @tab
@@ -216,6 +178,7 @@
 * Object Oriented Programming::            
 * GUI Development::            
 * System Utilities::            
+* Java Interface:: 
 * Packages:: 
 * Dynamically Linked Functions::
 * Test and Demo Functions::
@@ -416,16 +379,17 @@
 * The try Statement::           
 * Continuation Lines::          
 
-The @code{switch} Statement
+The switch Statement
 
 * Notes for the C Programmer::  
 
-The @code{for} Statement
+The for Statement
 
 * Looping Over Structure Elements::  
 
 Functions and Scripts
 
+* Introduction to Function and Script Files::
 * Defining Functions::          
 * Multiple Return Values::      
 * Variable-length Argument Lists::  
@@ -444,6 +408,7 @@
 * Manipulating the Load Path::
 * Subfunctions::
 * Private Functions::
+* Nested Functions::
 * Overloading and Autoloading::
 * Function Locking::
 * Function Precedence::
@@ -535,6 +500,9 @@
 * Plot Annotations::            
 * Multiple Plots on One Page::  
 * Multiple Plot Windows::       
+* Use of axis@comma{} line@comma{} and patch Functions::
+* Manipulation of Plot Windows::
+* Use of the @code{interpreter} Property::
 * Printing and Saving Plots::              
 * Interacting with Plots::      
 * Test Plotting Functions::     
@@ -644,7 +612,7 @@
 * Basic Usage::          Creation and Manipulation of Diagonal and Permutation Matrices
 * Matrix Algebra::       Linear Algebra with Diagonal and Permutation Matrices
 * Function Support::     Functions That Are Aware of These Matrices
-* Example Codes::        Some Examples of Usage
+* Example Code::         Some Examples of Usage
 * Zeros Treatment::      The Differences in Treatment of Zero Elements
 
 Basic Usage
@@ -795,6 +763,20 @@
 * FTP Objects::
 * URL Manipulation::
 
+Java Interface
+
+* Java Interface Functions::
+* Dialog Box Functions::
+* FAQ - Frequently asked Questions::
+
+FAQ - Frequently asked Questions
+
+* 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?::
+* Which @TeX{} symbols are implemented in the dialog functions?::
+
 Packages
 
 * Installing and Removing Packages::  
@@ -890,7 +872,7 @@
 
 Build Dependencies
 
-* Obtaining the Depencies Automatically::
+* Obtaining the Dependencies Automatically::
 * Build Tools::
 * External Packages::
 
@@ -948,6 +930,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/oop.txi
+++ b/doc/interpreter/oop.txi
@@ -184,7 +184,7 @@
 
 @noindent
 Note that in the display method, it makes sense to start the method
-with the line @code{fprintf("%s =", inputname(1))} to be consistent
+with the line @code{fprintf ("%s =", inputname (1))} to be consistent
 with the rest of Octave and print the variable name to be displayed
 when displaying the class. 
 
@@ -317,7 +317,7 @@
 
 @example
 @group
-p = polynomial([1,2,3,4]);
+p = polynomial ([1,2,3,4]);
 p(end-1)
   @result{} 3
 @end group
@@ -354,7 +354,7 @@
 @group
   function x = subsasgn (x, ss, val)
     @dots{}
-    x.myfield(ss.subs@{1@}) = val;
+    x.myfield (ss.subs@{1@}) = val;
   endfunction
 @end group
 @end example
@@ -495,6 +495,13 @@
 @cindex transpose, complex-conjugate
 @cindex unary minus
 
+@c Need at least one plaintext sentence here between the @node and @float
+@c table below or the two will overlap due to a bug in Texinfo. 
+@c This is not our fault; this *is* a ridiculous kluge.
+The following table shows, for each built-in numerical operation, the
+corresponding function name to use when providing an overloaded method for a
+user class.
+
 @float Table,tab:overload_ops
 @opindex +
 @opindex -
@@ -649,6 +656,8 @@
 Octave types.  So in fact marking our polynomial class higher than the 
 "double" class is in fact not necessary.
 
+When faced with two objects that have the same precedence, Octave will use the
+method of the object that appears first on the list of arguments.
 
 @node Inheritance and Aggregation
 @section Inheritance and Aggregation
@@ -726,15 +735,15 @@
 
 @example
 @group
-octave:1> f=FIRfilter(polynomial([1 1 1]/3))
+octave:1> f = FIRfilter (polynomial ([1 1 1]/3))
 f.polynomial = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2
-octave:2> class(f)
+octave:2> class (f)
 ans = FIRfilter
-octave:3> isa(f,"FIRfilter")
+octave:3> isa (f,"FIRfilter")
 ans =  1
-octave:4> isa(f,"polynomial")
+octave:4> isa (f,"polynomial")
 ans =  1
-octave:5> struct(f)
+octave:5> struct (f)
 ans = 
 @{
 polynomial = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2
@@ -759,9 +768,9 @@
 
 @example
 @group
-octave:2> f=FIRfilter(polynomial([1 1 1]/3));
-octave:3> x=ones(5,1);
-octave:4> y=f(x)
+octave:2> f = FIRfilter (polynomial ([1 1 1]/3));
+octave:3> x = ones (5,1);
+octave:4> y = f(x)
 y =
 
    0.33333
@@ -776,7 +785,7 @@
 
 @example
 @group
-octave:1> f=FIRfilter(polynomial([1 1 1]/3));
+octave:1> f = FIRfilter (polynomial ([1 1 1]/3));
 octave:2> f.polynomial
 ans = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2
 @end group
@@ -796,13 +805,12 @@
 
 @example
 @group
-octave:6> f=FIRfilter();
-octave:7> f.polynomial = polynomial([1 2 3]);
+octave:6> f = FIRfilter ();
+octave:7> f.polynomial = polynomial ([1 2 3]);
 f.polynomial = 1 + 2 * X + 3 * X ^ 2
 @end group
 @end example
 
-
 Defining the FIRfilter class as a child of the polynomial class
 implies that and FIRfilter object may be used any place that a
 polynomial may be used.  This is not a normal use of a filter, so that
--- a/doc/interpreter/package.txi
+++ b/doc/interpreter/package.txi
@@ -1,4 +1,4 @@
-@c Copyright (C) 2007-2012 S�ren Hauberg
+@c Copyright (C) 2007-2012 Søren Hauberg
 @c
 @c This file is part of Octave.
 @c
@@ -181,8 +181,12 @@
 following be referred to as @code{package} and may contain the
 following files:
 
-@noindent
 @table @code
+@item package/CITATION
+This is am optional file describing instructions on how to cite
+the package for publication.  It will be displayed verbatim by the
+function @code{citation}.
+
 @item package/COPYING
 This is a required file containing the license of the package.  No
 restrictions is made on the license in general.  If however the
@@ -212,6 +216,7 @@
 @item package/ONEWS
 This is an optional file describing old entries from the @file{NEWS} file.
 
+@cindex PKG_ADD
 @anchor{doc-PKG_ADD}
 @item package/PKG_ADD
 An optional file that includes commands that are run when the package
@@ -236,6 +241,8 @@
 @xref{PKG_ADD and PKG_DEL Directives}, for details on @w{@code{PKG_ADD}}
 directives.
 
+@cindex PKG_DEL
+@anchor{doc-PKG_DEL}
 @item package/PKG_DEL
 An optional file that includes commands that are run when the package
 is removed from the users path.  Note that @w{@code{PKG_DEL}} directives in
@@ -260,7 +267,6 @@
 Besides the above mentioned files, a package can also contain on or
 more of the following directories:
 
-@noindent
 @table @code
 @item package/inst
 An optional directory containing any files that are directly installed
@@ -305,7 +311,6 @@
 package, such as its name, author, and version.  This file has a very
 simple format
 
-@noindent
 @itemize
 @item
 Lines starting with @samp{#} are comments.
@@ -340,7 +345,6 @@
 
 The package manager currently recognizes the following keywords
 
-@noindent
 @table @code
 @item Name
 Name of the package.
@@ -441,7 +445,6 @@
 The optional @file{INDEX} file provides a categorical view of the
 functions in the package.  This file has a very simple format
 
-@noindent
 @itemize
 @item Lines beginning with @samp{#} are comments.
 
--- a/doc/interpreter/plot.txi
+++ b/doc/interpreter/plot.txi
@@ -62,6 +62,9 @@
 * Plot Annotations::            
 * Multiple Plots on One Page::  
 * Multiple Plot Windows::       
+* Use of axis@comma{} line@comma{} and patch Functions::
+* Manipulation of Plot Windows::
+* Use of the @code{interpreter} Property::
 * Printing and Saving Plots::              
 * Interacting with Plots::      
 * Test Plotting Functions::     
@@ -136,6 +139,10 @@
 
 @DOCSTRING(hist)
 
+@DOCSTRING(stemleaf)
+
+@DOCSTRING(printd)
+
 @DOCSTRING(stairs)
 
 @DOCSTRING(stem)
@@ -363,6 +370,8 @@
 
 @DOCSTRING(isocolors)
 
+@DOCSTRING(shrinkfaces)
+
 @DOCSTRING(diffuse)
 
 @DOCSTRING(specular)
@@ -383,6 +392,8 @@
 
 @DOCSTRING(scatter3)
 
+@DOCSTRING(waterfall)
+
 @menu
 * Aspect Ratio::
 * Three-dimensional Function Plotting::  
@@ -511,8 +522,9 @@
 the second a cosine wave.  Figure numbers must be positive integers.
 
 @DOCSTRING(figure)
-@subsection Use of @code{axis},  @code{line}, and @code{patch} functions
-@cindex use of @code{axis},  @code{line}, and @code{patch} functions
+
+@node Use of axis@comma{} line@comma{} and patch Functions
+@subsection Use of axis@comma{} line@comma{} and patch Functions
 
 You can create axes, line, and patch objects directly using the
 @code{axes}, @code{line}, and @code{patch} functions.  These objects
@@ -526,8 +538,8 @@
 
 @DOCSTRING(surface)
 
-@subsection Manipulation of plot windows
-@cindex manipulation of plot windows
+@node Manipulation of Plot Windows
+@subsection Manipulation of Plot Windows
 
 By default, Octave refreshes the plot window when a prompt is printed,
 or when waiting for input.  The
@@ -585,8 +597,8 @@
 
 @DOCSTRING(closereq)
 
+@node Use of the @code{interpreter} Property
 @subsection Use of the @code{interpreter} Property
-@cindex use of the @code{interpreter} property
 
 All text objects, including titles, labels, legends, and text, include
 the property 'interpreter', this property determines the manner in which
@@ -809,11 +821,11 @@
 @example
 @group
 x = 0:0.01:3;
-plot(x,erf(x));
+plot (x, erf (x));
 hold on;
-plot(x,x,"r");
-axis([0, 3, 0, 1]);
-text(0.65, 0.6175, strcat('\leftarrow x = @{2/\surd\pi',
+plot (x,x,"r");
+axis ([0, 3, 0, 1]);
+text (0.65, 0.6175, strcat ('\leftarrow x = @{2/\surd\pi',
 ' @{\fontsize@{16@}\int_@{\fontsize@{8@}0@}^@{\fontsize@{8@}x@}@}',
 ' e^@{-t^2@} dt@} = 0.6175'))
 @end group
@@ -834,15 +846,22 @@
 @cindex printing plots
 @cindex saving plots
 
-The @code{print} command allows you to save plots in a variety of
-formats.  For example,
+The @code{print} command allows you to send plots to you printer and
+to save plots in a variety of formats.  For example,
+
+@example
+print -dpsc
+@end example
+
+@noindent
+prints the current figure to a color PostScript printer.  And,
 
 @example
 print -deps foo.eps
 @end example
 
 @noindent
-writes the current figure to an encapsulated PostScript file called
+saves the current figure to an encapsulated PostScript file called
 @file{foo.eps}.
 
 @DOCSTRING(print)
@@ -1145,6 +1164,8 @@
 
 @DOCSTRING(allchild)
 
+@DOCSTRING(findfigs)
+
 @node Graphics Object Properties
 @subsection Graphics Object Properties
 @cindex graphics object properties
@@ -1169,6 +1190,7 @@
 @cindex root figure properties
 
 The @code{root figure} properties are:
+
 @table @code
 @item __modified__  
 --- Values: "on," "off"
@@ -1241,6 +1263,7 @@
 @cindex figure properties
 
 The @code{figure} properties are:
+
 @table @code
 @item __graphics_toolkit__  
 --- The graphics toolkit currently in use.
@@ -1324,6 +1347,7 @@
 respectively.  The functions are called with two input arguments.  The
 first argument holds the handle of the calling figure.  The second
 argument holds the event structure which has the following members:
+
 @table @code
 @item Character
 The ASCII value of the key
@@ -1345,6 +1369,7 @@
 
 @item nextplot
 May be one of
+
 @table @code
 @item "new"
 
@@ -1440,6 +1465,7 @@
 @cindex axes properties
 
 The @code{axes} properties are:
+
 @table @code
 @item __modified__
 
@@ -1569,6 +1595,7 @@
 
 @item nextplot
 May be one of
+
 @table @code
 @item "new"
 
@@ -1785,6 +1812,7 @@
 @cindex line properties
 
 The @code{line} properties are:
+
 @table @code
 @item __modified__
 
@@ -1896,6 +1924,7 @@
 @cindex text properties
 
 The @code{text} properties are:
+
 @table @code
 @item __modified__
 
@@ -2013,6 +2042,7 @@
 @cindex image properties
 
 The @code{image} properties are:
+
 @table @code
 @item __modified__
 
@@ -2089,6 +2119,7 @@
 @cindex patch properties
 
 The @code{patch} properties are:
+
 @table @code
 @item __modified__
 
@@ -2237,6 +2268,7 @@
 @cindex surface properties
 
 The @code{surface} properties are:
+
 @table @code
 @item __modified__
 
@@ -2512,6 +2544,7 @@
 @table @code
 @item linestyle
 May be one of
+
 @table @code
 @item "-"
 Solid line.  [default]
@@ -2540,20 +2573,21 @@
 @cindex marker styles, graphics
 
 Marker styles are specified by the following properties:
+
 @table @code
 @item marker
 A character indicating a plot marker to be place at each data point, or
 @code{"none"}, meaning no markers should be displayed.
 
-@itemx markeredgecolor
+@item markeredgecolor
 The color of the edge around the marker, or @code{"auto"}, meaning that
 the edge color is the same as the face color.  @xref{Colors}.
 
-@itemx markerfacecolor
+@item markerfacecolor
 The color of the marker, or @code{"none"} to indicate that the marker
 should not be filled.  @xref{Colors}.
 
-@itemx markersize
+@item markersize
 A number specifying the size of the marker.  The default is 1.  A value
 of 2 is twice as large as the default, etc.
 @end table
@@ -2586,7 +2620,7 @@
 @code{set} function.  For example,
 
 @example
-plot (x, "DeleteFcn", @@(s, e) disp("Window Deleted"))
+plot (x, "DeleteFcn", @@(s, e) disp ("Window Deleted"))
 @end example
 
 @noindent
--- a/doc/interpreter/poly.txi
+++ b/doc/interpreter/poly.txi
@@ -54,8 +54,8 @@
 
 @example
 @group
-N = length(c)-1;
-val = dot( x.^(N:-1:0), c );
+N = length (c) - 1;
+val = dot (x.^(N:-1:0), c);
 @end group
 @end example
 
@@ -84,6 +84,8 @@
 
 @DOCSTRING(roots)
 
+@DOCSTRING(polyeig)
+
 @DOCSTRING(compan)
 
 @DOCSTRING(mpoles)
@@ -114,8 +116,8 @@
 @example
 @group
 c = [1, 0, 1];
-integral = polyint(c);
-area = polyval(integral, 3) - polyval(integral, 0)
+integral = polyint (c);
+area = polyval (integral, 3) - polyval (integral, 0)
 @result{} 12
 @end group
 @end example
@@ -132,18 +134,224 @@
 Octave comes with good support for various kinds of interpolation,
 most of which are described in @ref{Interpolation}.  One simple alternative
 to the functions described in the aforementioned chapter, is to fit
-a single polynomial to some given data points.  To avoid a highly
-fluctuating polynomial, one most often wants to fit a low-order polynomial
-to data.  This usually means that it is necessary to fit the polynomial
-in a least-squares sense, which just is what the @code{polyfit} function does.
+a single polynomial, or a piecewise polynomial (spline) to some given
+data points.  To avoid a highly fluctuating polynomial, one most often
+wants to fit a low-order polynomial to data.  This usually means that it
+is necessary to fit the polynomial in a least-squares sense, which just
+is what the @code{polyfit} function does.
 
 @DOCSTRING(polyfit)
 
 In situations where a single polynomial isn't good enough, a solution
-is to use several polynomials pieced together.  The function @code{mkpp}
-creates a piecewise polynomial, @code{ppval} evaluates the function 
-created by @code{mkpp}, and @code{unmkpp} returns detailed information
-about the function.
+is to use several polynomials pieced together.  The function
+@code{splinefit} fits a peicewise polynomial (spline) to a set of
+data.
+
+@DOCSTRING(splinefit)
+
+The number of @var{breaks} (or knots) used to construct the piecewise
+polynomial is a significant factor in suppressing the noise present in
+the input data, @var{x} and @var{y}.  This is demonstrated by the example
+below.
+
+@example
+@group
+x = 2 * pi * rand (1, 200);
+y = sin (x) + sin (2 * x) + 0.2 * randn (size (x));
+## Uniform breaks
+breaks = linspace (0, 2 * pi, 41); % 41 breaks, 40 pieces
+pp1 = splinefit (x, y, breaks);
+## Breaks interpolated from data
+pp2 = splinefit (x, y, 10);  % 11 breaks, 10 pieces
+## Plot
+xx = linspace (0, 2 * pi, 400);
+y1 = ppval (pp1, xx);
+y2 = ppval (pp2, xx);
+plot (x, y, ".", xx, [y1; y2])
+axis tight
+ylim auto
+legend (@{"data", "41 breaks, 40 pieces", "11 breaks, 10 pieces"@})
+@end group
+@end example
+
+@ifnotinfo
+@noindent
+The result of which can be seen in @ref{fig:splinefit1}.
+
+@float Figure,fig:splinefit1
+@center @image{splinefit1,4in}
+@caption{Comparison of a fitting a piecewise polynomial with 41 breaks to one
+with 11 breaks.  The fit with the large number of breaks exhibits a fast ripple
+that is not present in the underlying function.}
+@end float
+@end ifnotinfo
+
+The piecewise polynomial fit, provided by @code{splinefit}, has
+continuous derivatives up to the @var{order}-1.  For example, a cubic fit
+has continuous first and second derivatives.  This is demonstrated by
+the code
+
+@example
+## Data (200 points)
+x = 2 * pi * rand (1, 200);
+y = sin (x) + sin (2 * x) + 0.1 * randn (size (x));
+## Piecewise constant
+pp1 = splinefit (x, y, 8, "order", 0);
+## Piecewise linear
+pp2 = splinefit (x, y, 8, "order", 1);
+## Piecewise quadratic
+pp3 = splinefit (x, y, 8, "order", 2);
+## Piecewise cubic
+pp4 = splinefit (x, y, 8, "order", 3);
+## Piecewise quartic
+pp5 = splinefit (x, y, 8, "order", 4);
+## Plot
+xx = linspace (0, 2 * pi, 400);
+y1 = ppval (pp1, xx);
+y2 = ppval (pp2, xx);
+y3 = ppval (pp3, xx);
+y4 = ppval (pp4, xx);
+y5 = ppval (pp5, xx);
+plot (x, y, ".", xx, [y1; y2; y3; y4; y5])
+axis tight
+ylim auto
+legend (@{"data", "order 0", "order 1", "order 2", "order 3", "order 4"@})
+@end example
+
+@ifnotinfo
+@noindent
+The result of which can be seen in @ref{fig:splinefit2}.
+
+@float Figure,fig:splinefit2
+@center @image{splinefit2,4in}
+@caption{Comparison of a piecewise constant, linear, quadratic, cubic, and
+quartic polynomials with 8 breaks to noisy data.  The higher order solutions
+more accurately represent the underlying function, but come with the
+expense of computational complexity.}
+@end float
+@end ifnotinfo
+
+When the underlying function to provide a fit to is periodic, @code{splinefit}
+is able to apply the boundary conditions needed to manifest a periodic fit.
+This is demonstrated by the code below.
+
+@example
+@group
+## Data (100 points)
+x = 2 * pi * [0, (rand (1, 98)), 1];
+y = sin (x) - cos (2 * x) + 0.2 * randn (size (x));
+## No constraints
+pp1 = splinefit (x, y, 10, "order", 5);
+## Periodic boundaries
+pp2 = splinefit (x, y, 10, "order", 5, "periodic", true);
+## Plot
+xx = linspace (0, 2 * pi, 400);
+y1 = ppval (pp1, xx);
+y2 = ppval (pp2, xx);
+plot (x, y, ".", xx, [y1; y2])
+axis tight
+ylim auto
+legend (@{"data", "no constraints", "periodic"@})
+@end group
+@end example
+
+@ifnotinfo
+@noindent
+The result of which can be seen in @ref{fig:splinefit3}.
+
+@float Figure,fig:splinefit3
+@center @image{splinefit3,4in}
+@caption{Comparison of piecewise polynomial fits to a noisy periodic
+function with, and without, periodic boundary conditions.}
+@end float
+@end ifnotinfo
+
+More complex constraints may be added as well.  For example, the code below
+illustrates a periodic fit with values that have been clamped at the endpoints,
+and a second periodic fit which is hinged at the endpoints.
+
+@example
+## Data (200 points)
+x = 2 * pi * rand (1, 200);
+y = sin (2 * x) + 0.1 * randn (size (x));
+## Breaks
+breaks = linspace (0, 2 * pi, 10);
+## Clamped endpoints, y = y' = 0
+xc = [0, 0, 2*pi, 2*pi];
+cc = [(eye (2)), (eye (2))];
+con = struct ("xc", xc, "cc", cc);
+pp1 = splinefit (x, y, breaks, "constraints", con);
+## Hinged periodic endpoints, y = 0
+con = struct ("xc", 0);
+pp2 = splinefit (x, y, breaks, "constraints", con, "periodic", true);
+## Plot
+xx = linspace (0, 2 * pi, 400);
+y1 = ppval (pp1, xx);
+y2 = ppval (pp2, xx);
+plot (x, y, ".", xx, [y1; y2])
+axis tight
+ylim auto
+legend (@{"data", "clamped", "hinged periodic"@})
+@end example
+
+@ifnotinfo
+@noindent
+The result of which can be seen in @ref{fig:splinefit4}.
+
+@float Figure,fig:splinefit4
+@center @image{splinefit4,4in}
+@caption{Comparison of two periodic piecewise cubic fits to a noisy periodic
+signal.  One fit has its endpoints clamped and the second has its endpoints
+hinged.}
+@end float
+@end ifnotinfo
+
+The @code{splinefit} function also provides the convenience of a @var{robust}
+fitting, where the effect of outlying data is reduced.  In the example below,
+three different fits are provided.  Two with differing levels of outlier
+suppression and a third illustrating the non-robust solution.
+
+@example
+## Data
+x = linspace (0, 2*pi, 200);
+y = sin (x) + sin (2 * x) + 0.05 * randn (size (x));
+## Add outliers
+x = [x, linspace(0,2*pi,60)];
+y = [y, -ones(1,60)];
+## Fit splines with hinged conditions
+con = struct ("xc", [0, 2*pi]);
+## Robust fitting, beta = 0.25
+pp1 = splinefit (x, y, 8, "constraints", con, "beta", 0.25);
+## Robust fitting, beta = 0.75
+pp2 = splinefit (x, y, 8, "constraints", con, "beta", 0.75);
+## No robust fitting
+pp3 = splinefit (x, y, 8, "constraints", con);
+## Plot
+xx = linspace (0, 2*pi, 400);
+y1 = ppval (pp1, xx);
+y2 = ppval (pp2, xx);
+y3 = ppval (pp3, xx);
+plot (x, y, ".", xx, [y1; y2; y3])
+legend (@{"data with outliers","robust, beta = 0.25", ...
+         "robust, beta = 0.75", "no robust fitting"@})
+axis tight
+ylim auto
+@end example
+
+@ifnotinfo
+@noindent
+The result of which can be seen in @ref{fig:splinefit6}.
+
+@float Figure,fig:splinefit6
+@center @image{splinefit6,4in}
+@caption{Comparison of two different levels of robust fitting (@var{beta} = 0.25 and 0.75) to noisy data combined with outlying data.  A conventional fit, without
+robust fitting (@var{beta} = 0) is also included.}
+@end float
+@end ifnotinfo
+
+The function, @code{ppval}, evaluates the piecewise polynomials, created
+by @code{mkpp} or other means, and @code{unmkpp} returns detailed
+information about the piecewise polynomial.
 
 The following example shows how to combine two linear functions and a
 quadratic into one function.  Each of these functions is expressed
@@ -155,10 +363,10 @@
 p = [ 0,  1, 0;
       1, -2, 1;
       0, -1, 1 ];
-pp = mkpp(x, p);
-xi = linspace(-2, 2, 50);
-yi = ppval(pp, xi);
-plot(xi, yi);
+pp = mkpp (x, p);
+xi = linspace (-2, 2, 50);
+yi = ppval (pp, xi);
+plot (xi, yi);
 @end group
 @end example
 
--- a/doc/interpreter/quad.txi
+++ b/doc/interpreter/quad.txi
@@ -338,7 +338,7 @@
 @ifnottex
 the sum over @code{i=1:n} and @code{j=1:n} of @code{q(i)*q(j)*f(r(i),r(j))},
 @end ifnottex
-where @math{q} and @math{r} is as returned by @code{colloc(n)}.  The
+where @math{q} and @math{r} is as returned by @code{colloc (n)}.  The
 generalization to more than two variables is straight forward.  The
 following code computes the studied integral using @math{n=8} points.
 
--- a/doc/interpreter/set.txi
+++ b/doc/interpreter/set.txi
@@ -40,7 +40,7 @@
 @code{y} contains two sets, then
 
 @example
-union(x, y)
+union (x, y)
 @end example
 
 @noindent
--- a/doc/interpreter/sparse.txi
+++ b/doc/interpreter/sparse.txi
@@ -108,7 +108,7 @@
 @example
 @group
   for (j = 0; j < nc; j++)
-    for (i = cidx (j); i < cidx(j+1); i++)
+    for (i = cidx(j); i < cidx(j+1); i++)
        printf ("non-zero element (%i,%i) is %d\n", 
            ridx(i), j, data(i));
 @end group
@@ -214,7 +214,7 @@
 that corresponds to this.  For example,
 
 @example
-s = diag (sparse(randn(1,n)), -1);
+s = diag (sparse (randn (1,n)), -1);
 @end example
 
 @noindent
@@ -350,8 +350,8 @@
 
 @example
 @group
-a = tril (sprandn(1024, 1024, 0.02), -1) ...
-    + speye(1024); 
+a = tril (sprandn (1024, 1024, 0.02), -1) ...
+    + speye (1024); 
 matrix_type (a);
 ans = Lower
 @end group
@@ -365,7 +365,7 @@
 @example
 @group
 a = matrix_type (tril (sprandn (1024, ...
-   1024, 0.02), -1) + speye(1024), 'Lower');
+   1024, 0.02), -1) + speye (1024), "Lower");
 @end group
 @end example
 
@@ -400,10 +400,10 @@
 
 @example
 @group
-A = sparse([2,6,1,3,2,4,3,5,4,6,1,5],
+A = sparse ([2,6,1,3,2,4,3,5,4,6,1,5],
     [1,1,2,2,3,3,4,4,5,5,6,6],1,6,6);
 xy = [0,4,8,6,4,2;5,0,5,7,5,7]';
-gplot(A,xy)
+gplot (A,xy)
 @end group
 @end example
 
@@ -424,8 +424,8 @@
 calculated in linear time without explicitly needing to calculate the
 Cholesky@tie{}factorization by the @code{etree} command.  This command
 returns the elimination tree of the matrix and can be displayed
-graphically by the command @code{treeplot(etree(A))} if @code{A} is
-symmetric or @code{treeplot(etree(A+A'))} otherwise.
+graphically by the command @code{treeplot (etree (A))} if @code{A} is
+symmetric or @code{treeplot (etree (A+A'))} otherwise.
 
 @DOCSTRING(spy)
 
@@ -521,7 +521,7 @@
 
 @example
 @group
-speye(3) + 0
+speye (3) + 0
 @result{}   1  0  0
   0  1  0
   0  0  1
@@ -543,7 +543,7 @@
 one area where it does cause a problem is where a sparse matrix is
 promoted to a full matrix, where subsequent operations would resparsify
 the matrix.  Such cases are rare, but can be artificially created, for
-example @code{(fliplr(speye(3)) + speye(3)) - speye(3)} gives a full
+example @code{(fliplr (speye (3)) + speye (3)) - speye (3)} gives a full
 matrix when it should give a sparse one.  In general, where such cases 
 occur, they impose only a small memory penalty.
 
@@ -553,7 +553,7 @@
 depending on the type of its input arguments.  So 
 
 @example
- a = diag (sparse([1,2,3]), -1);
+ a = diag (sparse ([1,2,3]), -1);
 @end example
 
 @noindent
@@ -657,7 +657,7 @@
 The standard Cholesky@tie{}factorization of this matrix can be
 obtained by the same command that would be used for a full
 matrix.  This can be visualized with the command 
-@code{r = chol(A); spy(r);}.
+@code{r = chol (A); spy (r);}.
 @xref{fig:simplechol}.
 The original matrix had 
 @ifinfo
@@ -684,8 +684,8 @@
 
 The appropriate sparsity preserving permutation of the original
 matrix is given by @dfn{symamd} and the factorization using this
-reordering can be visualized using the command @code{q = symamd(A);
-r = chol(A(q,q)); spy(r)}.  This gives 
+reordering can be visualized using the command @code{q = symamd (A);
+r = chol (A(q,q)); spy (r)}.  This gives 
 @ifinfo
 @ifnothtml
 29
@@ -699,7 +699,7 @@
 The Cholesky@tie{}factorization itself can be used to determine the
 appropriate sparsity preserving reordering of the matrix during the
 factorization, In that case this might be obtained with three return
-arguments as r@code{[r, p, q] = chol(A); spy(r)}.
+arguments as @code{[r, p, q] = chol (A); spy (r)}.
 
 @float Figure,fig:simplechol
 @center @image{spchol,4in}
@@ -714,7 +714,7 @@
 In the case of an asymmetric matrix, the appropriate sparsity
 preserving permutation is @dfn{colamd} and the factorization using
 this reordering can be visualized using the command
-@code{q = colamd(A); [l, u, p] = lu(A(:,q)); spy(l+u)}.
+@code{q = colamd (A); [l, u, p] = lu (A(:,q)); spy (l+u)}.
 
 Finally, Octave implicitly reorders the matrix when using the div (/)
 and ldiv (\) operators, and so no the user does not need to explicitly
@@ -951,23 +951,23 @@
 
 @example
 @group
-   node_y= [1;1.2;1.5;1.8;2]*ones(1,11);
-   node_x= ones(5,1)*[1,1.05,1.1,1.2, ...
+   node_y = [1;1.2;1.5;1.8;2]*ones(1,11);
+   node_x = ones(5,1)*[1,1.05,1.1,1.2, ...
              1.3,1.5,1.7,1.8,1.9,1.95,2];
-   nodes= [node_x(:), node_y(:)];
+   nodes = [node_x(:), node_y(:)];
 
-   [h,w]= size(node_x);
-   elems= [];
-   for idx= 1:w-1
-     widx= (idx-1)*h;
-     elems= [elems; ...
+   [h,w] = size (node_x);
+   elems = [];
+   for idx = 1:w-1
+     widx = (idx-1)*h;
+     elems = [elems; ...
        widx+[(1:h-1);(2:h);h+(1:h-1)]'; ...
        widx+[(2:h);h+(2:h);h+(1:h-1)]' ]; 
    endfor
 
-   E= size(elems,1); # No. of simplices
-   N= size(nodes,1); # No. of vertices
-   D= size(elems,2); # dimensions+1
+   E = size (elems,1); # No. of simplices
+   N = size (nodes,1); # No. of vertices
+   D = size (elems,2); # dimensions+1
 @end group
 @end example
 
@@ -1004,32 +1004,32 @@
 calculated.
 
 @example
-  # Element conductivity
-  conductivity= [1*ones(1,16), ...
+  ## Element conductivity
+  conductivity = [1*ones(1,16), ...
          2*ones(1,48), 1*ones(1,16)];
 
-  # Connectivity matrix
+  ## Connectivity matrix
   C = sparse ((1:D*E), reshape (elems', ...
          D*E, 1), 1, D*E, N);
 
-  # Calculate system matrix
+  ## Calculate system matrix
   Siidx = floor ([0:D*E-1]'/D) * D * ...
          ones(1,D) + ones(D*E,1)*(1:D) ;
-  Sjidx = [1:D*E]'*ones(1,D);
-  Sdata = zeros(D*E,D);
-  dfact = factorial(D-1);
-  for j=1:E
-     a = inv([ones(D,1), ... 
+  Sjidx = [1:D*E]'*ones (1,D);
+  Sdata = zeros (D*E,D);
+  dfact = factorial (D-1);
+  for j = 1:E
+     a = inv ([ones(D,1), ... 
          nodes(elems(j,:), :)]);
      const = conductivity(j) * 2 / ...
-         dfact / abs(det(a));
+         dfact / abs (det (a));
      Sdata(D*(j-1)+(1:D),:) = const * ...
          a(2:D,:)' * a(2:D,:);
   endfor
-  # Element-wise system matrix
-  SE= sparse(Siidx,Sjidx,Sdata);
-  # Global system matrix
-  S= C'* SE *C;
+  ## Element-wise system matrix
+  SE = sparse(Siidx,Sjidx,Sdata);
+  ## Global system matrix
+  S = C'* SE *C;
 @end example
 
 The system matrix acts like the conductivity 
@@ -1050,23 +1050,23 @@
 solve for the voltages at each vertex @code{V}. 
 
 @example
-  # Dirichlet boundary conditions
-  D_nodes=[1:5, 51:55]; 
-  D_value=[10*ones(1,5), 20*ones(1,5)]; 
+  ## Dirichlet boundary conditions
+  D_nodes = [1:5, 51:55]; 
+  D_value = [10*ones(1,5), 20*ones(1,5)]; 
 
-  V= zeros(N,1);
+  V = zeros (N,1);
   V(D_nodes) = D_value;
   idx = 1:N; # vertices without Dirichlet 
              # boundary condns
   idx(D_nodes) = [];
 
-  # Neumann boundary conditions.  Note that
-  # N_value must be normalized by the
-  # boundary length and element conductivity
-  N_nodes=[];
-  N_value=[];
+  ## Neumann boundary conditions.  Note that
+  ## N_value must be normalized by the
+  ## boundary length and element conductivity
+  N_nodes = [];
+  N_value = [];
 
-  Q = zeros(N,1);
+  Q = zeros (N,1);
   Q(N_nodes) = N_value;
 
   V(idx) = S(idx,idx) \ ( Q(idx) - ...
@@ -1085,8 +1085,8 @@
   xelems = reshape (nodes(elemx, 1), 4, E);
   yelems = reshape (nodes(elemx, 2), 4, E);
   velems = reshape (V(elemx), 4, E);
-  plot3 (xelems,yelems,velems,'k'); 
-  print ('grid.eps');
+  plot3 (xelems,yelems,velems,"k"); 
+  print "grid.eps";
 @end group
 @end example
 
--- a/doc/interpreter/sparseimages.m
+++ b/doc/interpreter/sparseimages.m
@@ -23,9 +23,9 @@
     set (0, "defaulttextfontname", "*");
   endif
 
-  if (! isempty (findstr (octave_config_info ("DEFS"), "HAVE_COLAMD"))
-      && ! isempty (findstr (octave_config_info ("DEFS"), "HAVE_CHOLMOD"))
-      && ! isempty (findstr (octave_config_info ("DEFS"), "HAVE_UMFPACK")))
+  if (__have_feature__ ("COLAMD")
+      && __have_feature__ ("CHOLMOD")
+      && __have_feature__ ("UMFPACK"))
     if (strcmp(typ,"txt"))
       txtimages (nm, 15, typ);
     else
@@ -86,8 +86,8 @@
   elseif (strcmp (nm, "spmatrix"))
     printsparse(a,cstrcat("spmatrix.",typ));
   else
-    if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_COLAMD")) &&
-        !isempty(findstr(octave_config_info ("DEFS"),"HAVE_CHOLMOD")))
+    if (__have_feature__ ("COLAMD")
+        && __have_feature__ ("CHOLMOD"))
       if (strcmp (nm, "spchol"))
         r1 = chol(a);
         printsparse(r1,cstrcat("spchol.",typ));
@@ -116,8 +116,8 @@
     print(cstrcat("spmatrix.",typ), d_typ)
     hide_output ();
   else
-    if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_COLAMD")) &&
-        !isempty(findstr(octave_config_info ("DEFS"),"HAVE_CHOLMOD")))
+    if (__have_feature__ ("COLAMD")
+        && __have_feature__ ("CHOLMOD"))
       if (strcmp (nm, "spchol"))
         r1 = chol(a);
         spy(r1);
@@ -182,9 +182,9 @@
     d_typ = cstrcat ("-d", typ);
   endif
 
-  if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_COLAMD")) &&
-      !isempty(findstr(octave_config_info ("DEFS"),"HAVE_CHOLMOD")) &&
-      !isempty(findstr(octave_config_info ("DEFS"),"HAVE_UMFPACK")))
+  if (__have_feature__ ("COLAMD")
+      && __have_feature__ ("CHOLMOD")
+      && __have_feature__ ("UMFPACK"))
     ## build a rectangle
     node_y = [1;1.2;1.5;1.8;2]*ones(1,11);
     node_x = ones(5,1)*[1,1.05,1.1,1.2,1.3,1.5,1.7,1.8,1.9,1.95,2];
new file mode 100644
--- /dev/null
+++ b/doc/interpreter/splineimages.m
@@ -0,0 +1,192 @@
+## Copyright (C) 2012 Ben Abbott, Jonas Lundgren
+##
+## 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/>.
+
+function splineimages (nm, typ)
+  graphics_toolkit ("gnuplot");
+  set_print_size ();
+  hide_output ();
+  if (strcmp (typ, "png"))
+    set (0, "defaulttextfontname", "*");
+  endif
+  if (strcmp (typ, "eps"))
+    d_typ = "-depsc2";
+  else
+    d_typ = cstrcat ("-d", typ);
+  endif
+
+  if (strcmp (typ, "txt"))
+    image_as_txt (nm);
+  elseif (strcmp (nm, "splinefit1")) ## Breaks and Pieces
+    x = 2 * pi * rand (1, 200);
+    y = sin (x) + sin (2 * x) + 0.2 * randn (size (x));
+    ## Uniform breaks
+    breaks = linspace (0, 2 * pi, 41); ## 41 breaks, 40 pieces
+    pp1 = splinefit (x, y, breaks);
+    ## Breaks interpolated from data
+    pp2 = splinefit (x, y, 10);  ## 11 breaks, 10 pieces
+    ## Plot
+    xx = linspace (0, 2 * pi, 400);
+    y1 = ppval (pp1, xx);
+    y2 = ppval (pp2, xx);
+    plot (x, y, ".", xx, [y1; y2])
+    axis tight
+    ylim ([-2.5 2.5])
+    legend ("data", "41 breaks, 40 pieces", "11 breaks, 10 pieces")
+    print (cstrcat (nm, ".", typ), d_typ)
+  elseif (strcmp (nm, "splinefit2")) ## Spline orders
+    ## Data (200 points)
+    x = 2 * pi * rand (1, 200);
+    y = sin (x) + sin (2 * x) + 0.1 * randn (size (x));
+    ## Splines
+    pp1 = splinefit (x, y, 8, "order", 0);  ## Piecewise constant
+    pp2 = splinefit (x, y, 8, "order", 1);  ## Piecewise linear
+    pp3 = splinefit (x, y, 8, "order", 2);  ## Piecewise quadratic
+    pp4 = splinefit (x, y, 8, "order", 3);  ## Piecewise cubic
+    pp5 = splinefit (x, y, 8, "order", 4);  ## Etc.
+    ## Plot
+    xx = linspace (0, 2 * pi, 400);
+    y1 = ppval (pp1, xx);
+    y2 = ppval (pp2, xx);
+    y3 = ppval (pp3, xx);
+    y4 = ppval (pp4, xx);
+    y5 = ppval (pp5, xx);
+    plot (x, y, ".", xx, [y1; y2; y3; y4; y5])
+    axis tight
+    ylim ([-2.5 2.5])
+    legend ({"data", "order 0", "order 1", "order 2", "order 3", "order 4"})
+    print (cstrcat (nm, ".", typ), d_typ)
+  elseif (strcmp (nm, "splinefit3"))
+    ## Data (100 points)
+    x = 2 * pi * [0, (rand (1, 98)), 1];
+    y = sin (x) - cos (2 * x) + 0.2 * randn (size (x));
+    ## No constraints
+    pp1 = splinefit (x, y, 10, "order", 5);
+    ## Periodic boundaries
+    pp2 = splinefit (x, y, 10, "order", 5, "periodic", true);
+    ## Plot
+    xx = linspace (0, 2 * pi, 400);
+    y1 = ppval (pp1, xx);
+    y2 = ppval (pp2, xx);
+    plot (x, y, ".", xx, [y1; y2])
+    axis tight
+    ylim ([-2 3])
+    legend ({"data", "no constraints", "periodic"})
+    print (cstrcat (nm, ".", typ), d_typ)
+  elseif (strcmp (nm, "splinefit4"))
+    ## Data (200 points)
+    x = 2 * pi * rand (1, 200);
+    y = sin (2 * x) + 0.1 * randn (size (x));
+    ## Breaks
+    breaks = linspace (0, 2 * pi, 10);
+    ## Clamped endpoints, y = y" = 0
+    xc = [0, 0, 2*pi, 2*pi];
+    cc = [(eye (2)), (eye (2))];
+    con = struct ("xc", xc, "cc", cc);
+    pp1 = splinefit (x, y, breaks, "constraints", con);
+    ## Hinged periodic endpoints, y = 0
+    con = struct ("xc", 0);
+    pp2 = splinefit (x, y, breaks, "constraints", con, "periodic", true);
+    ## Plot
+    xx = linspace (0, 2 * pi, 400);
+    y1 = ppval (pp1, xx);
+    y2 = ppval (pp2, xx);
+    plot (x, y, ".", xx, [y1; y2])
+    axis tight
+    ylim ([-1.5 1.5])
+    legend({"data", "clamped", "hinged periodic"})
+    print (cstrcat (nm, ".", typ), d_typ)
+  elseif (strcmp (nm, "splinefit5"))
+    ## Truncated data
+    x = [0,  1,  2,  4,  8, 16, 24, 40, 56, 72, 80] / 80;
+    y = [0, 28, 39, 53, 70, 86, 90, 79, 55, 22,  2] / 1000;
+    xy = [x; y];
+    ## Curve length parameter
+    ds = sqrt (diff (x).^2 + diff (y).^2);
+    s = [0, cumsum(ds)];
+    ## Constraints at s = 0: (x,y) = (0,0), (dx/ds,dy/ds) = (0,1)
+    con = struct ("xc", [0 0], "yc", [0 0; 0 1], "cc", eye (2));
+    ## Fit a spline with 4 pieces
+    pp = splinefit (s, xy, 4, "constraints", con);
+    ## Plot
+    ss = linspace (0, s(end), 400);
+    xyfit = ppval (pp, ss);
+    xyb = ppval(pp, pp.breaks);
+    plot (x, y, ".", xyfit(1,:), xyfit(2,:), "r", xyb(1,:), xyb(2,:), "ro")
+    legend ({"data", "spline", "breaks"})
+    axis tight
+    ylim ([0 0.1])
+    print (cstrcat (nm, ".", typ), d_typ)
+  elseif (strcmp (nm, "splinefit6"))
+    ## Data
+    x = linspace (0, 2*pi, 200);
+    y = sin (x) + sin (2 * x) + 0.05 * randn (size (x));
+    ## Add outliers
+    x = [x, linspace(0,2*pi,60)];
+    y = [y, -ones(1,60)];
+    ## Fit splines with hinged conditions
+    con = struct ("xc", [0, 2*pi]);
+    pp1 = splinefit (x, y, 8, "constraints", con, "beta", 0.25); ## Robust fitting
+    pp2 = splinefit (x, y, 8, "constraints", con, "beta", 0.75); ## Robust fitting
+    pp3 = splinefit (x, y, 8, "constraints", con); ## No robust fitting
+    ## Plot
+    xx = linspace (0, 2*pi, 400);
+    y1 = ppval (pp1, xx);
+    y2 = ppval (pp2, xx);
+    y3 = ppval (pp3, xx);
+    plot (x, y, ".", xx, [y1; y2; y3])
+    legend({"data with outliers","robust, beta = 0.25", ...
+            "robust, beta = 0.75", "no robust fitting"})
+    axis tight
+    ylim ([-2 2])
+    print (cstrcat (nm, ".", typ), d_typ)
+  endif
+  hide_output ();  
+endfunction
+
+function set_print_size ()
+  image_size = [5.0, 3.5]; # in inches, 16:9 format
+  border = 0;              # For postscript use 50/72
+  set (0, "defaultfigurepapertype", "<custom>");
+  set (0, "defaultfigurepaperorientation", "landscape");
+  set (0, "defaultfigurepapersize", image_size + 2*border);
+  set (0, "defaultfigurepaperposition", [border, border, image_size]);
+endfunction
+
+## Use this function before plotting commands and after every call to
+## print since print() resets output to stdout (unfortunately, gnpulot
+## can't pop output as it can the terminal type).
+function hide_output ()
+  f = figure (1);
+  set (f, "visible", "off");
+endfunction
+
+## generate something for the texinfo @image command to process
+function image_as_txt(nm)
+  fid = fopen (sprintf ("%s.txt", nm), "wt");
+  fputs (fid, "\n");
+  fputs (fid, "+---------------------------------+\n");
+  fputs (fid, "| Image unavailable in text mode. |\n");
+  fputs (fid, "+---------------------------------+\n");
+  fclose (fid);
+endfunction
+
+%!demo
+%! for s = 1:6
+%!   splineimages (sprintf ("splinefit##d", s), "pdf")
+%! endfor
+
--- a/doc/interpreter/stmt.txi
+++ b/doc/interpreter/stmt.txi
@@ -560,11 +560,11 @@
 
 @example
 @group
-disp("Loop over a matrix")
+disp ("Loop over a matrix")
 for i = [1,3;2,4]
   i
 endfor
-disp("Loop over a cell array")
+disp ("Loop over a cell array")
 for i = @{1,"two";"three",4@}
   i
 endfor
@@ -580,7 +580,7 @@
 
 @example
 @group
-a = [1,3;2,4]; c = cat(3, a, 2*a);
+a = [1,3;2,4]; c = cat (3, a, 2*a);
 for i = c
   i
 endfor
@@ -589,8 +589,8 @@
 
 @noindent
 In the above case, the multi-dimensional matrix @var{c} is reshaped to a
-two-dimensional matrix as @code{reshape (c, rows(c),
-prod(size(c)(2:end)))} and then the same behavior as a loop over a two
+two-dimensional matrix as @code{reshape (c, rows (c),
+prod (size (c)(2:end)))} and then the same behavior as a loop over a two
 dimensional matrix is produced.
 
 Although it is possible to rewrite all @code{for} loops as @code{while}
@@ -662,10 +662,11 @@
 @section The break Statement
 @cindex @code{break} statement
 
-The @code{break} statement jumps out of the innermost @code{for} or
-@code{while} loop that encloses it.  The @code{break} statement may only
-be used within the body of a loop.  The following example finds the
-smallest divisor of a given integer, and also identifies prime numbers:
+The @code{break} statement jumps out of the innermost @code{while},
+@code{do-until}, or @code{for} loop that encloses it.  The @code{break}
+statement may only be used within the body of a loop.  The following
+example finds the smallest divisor of a given integer, and also
+identifies prime numbers:
 
 @example
 @group
@@ -718,9 +719,10 @@
 @cindex @code{continue} statement
 
 The @code{continue} statement, like @code{break}, is used only inside
-@code{for} or @code{while} loops.  It skips over the rest of the loop
-body, causing the next cycle around the loop to begin immediately.
-Contrast this with @code{break}, which jumps out of the loop altogether.
+@code{while}, @code{do-until}, or @code{for} loops.  It skips over the
+rest of the loop body, causing the next cycle around the loop to begin
+immediately.  Contrast this with @code{break}, which jumps out of the
+loop altogether.
 Here is an example:
 
 @example
--- a/doc/interpreter/strings.txi
+++ b/doc/interpreter/strings.txi
@@ -187,14 +187,14 @@
 
 @example
 @group
-ischar(collection)
-     @result{} ans = 1
+ischar (collection)
+     @result{} 1
 
-ischar(collection) && isvector(collection)
-     @result{} ans = 0
+ischar (collection) && isvector (collection)
+     @result{} 0
 
-ischar("my string") && isvector("my string")
-     @result{} ans = 1
+ischar ("my string") && isvector ("my string")
+     @result{} 1
 @end group
 @end example
 
@@ -243,9 +243,8 @@
 
 @example
 @group
-char([98, 97, 110, 97, 110, 97])
-     @result{} ans =
-       banana
+char ([98, 97, 110, 97, 110, 97])
+   @result{} banana
 @end group
 @end example
 
@@ -256,16 +255,14 @@
 
 @example
 @group
-char("an apple", "two pears")
-     @result{} ans =
-       an apple
+char ("an apple", "two pears")
+    @result{} an apple
        two pears
 @end group
 
 @group
-strcat("oc", "tave", " is", " good", " for you")
-     @result{} ans =
-       octave is good for you
+strcat ("oc", "tave", " is", " good", " for you")
+     @result{} octave is good for you
 @end group
 @end example
 
@@ -275,18 +272,16 @@
 
 @example
 @group
-char("orange", "green", "", "red")
-     @result{} ans =
-       orange
+char ("orange", "green", "", "red")
+    @result{} orange
        green 
              
        red   
 @end group
 
 @group
-strvcat("orange", "green", "", "red")
-     @result{} ans =
-       orange
+strvcat ("orange", "green", "", "red")
+    @result{} orange
        green 
        red  
 @end group
@@ -299,21 +294,20 @@
 
 @example
 @group
-char(@{"red", "green", "", "blue"@})
-     @result{} ans =
-       red  
-       green
+char (@{"red", "green", "", "blue"@})
+     @result{} red  
+        green
 
-       blue 
+        blue 
 @end group
 
 @group
-strcat(@{"abc"; "ghi"@}, @{"def"; "jkl"@})
-     @result{} ans =
-       @{
-         [1,1] = abcdef
-         [2,1] = ghijkl
-       @}
+strcat (@{"abc"; "ghi"@}, @{"def"; "jkl"@})
+     @result{}
+        @{
+          [1,1] = abcdef
+          [2,1] = ghijkl
+        @}
 @end group
 @end example
 
@@ -323,17 +317,15 @@
 
 @example
 @group
-strcat(["dir1";"directory2"], ["/";"/"], ["file1";"file2"])
-     @result{} ans =
-       dir1/file1      
-       directory2/file2
+strcat (["dir1";"directory2"], ["/";"/"], ["file1";"file2"])
+     @result{} dir1/file1      
+        directory2/file2
 @end group
 @group
 
-cstrcat(["thirteen apples"; "a banana"], [" 5$";" 1$"])
-     @result{} ans =
-       thirteen apples 5$
-       a banana        1$
+cstrcat (["thirteen apples"; "a banana"], [" 5$";" 1$"])
+      @result{} thirteen apples 5$
+         a banana        1$
 @end group
 @end example
 
@@ -435,6 +427,8 @@
 
 @DOCSTRING(strfind)
 
+@DOCSTRING(strjoin)
+
 @DOCSTRING(strmatch)
 
 @DOCSTRING(strtok)
@@ -467,7 +461,7 @@
 @example
 @group
 hex2dec ("FF")
-     @result{} ans = 255
+      @result{} 255
 @end group
 @end example
 
--- a/doc/interpreter/system.txi
+++ b/doc/interpreter/system.txi
@@ -266,16 +266,34 @@
 @node FTP Objects
 @subsection FTP Objects
 
+Octave supports the FTP protocol through an object-oriented interface.
+Use the function @code{ftp} to create an FTP object which represents the
+connection.  All FTP functions take an FTP object as the first argument.
+
 @DOCSTRING(@ftp/ftp)
 
+@DOCSTRING(@ftp/close)
+
 @DOCSTRING(@ftp/mget)
 
 @DOCSTRING(@ftp/mput)
 
+@DOCSTRING(@ftp/cd)
+
+@DOCSTRING(@ftp/dir)
+
 @DOCSTRING(@ftp/ascii)
 
 @DOCSTRING(@ftp/binary)
 
+@DOCSTRING(@ftp/delete)
+
+@DOCSTRING(@ftp/rename)
+
+@DOCSTRING(@ftp/mkdir)
+
+@DOCSTRING(@ftp/rmdir)
+
 @node URL Manipulation
 @subsection URL Manipulation
 
@@ -503,8 +521,6 @@
 
 @DOCSTRING(octave_config_info)
 
-@DOCSTRING(usejava)
-
 @DOCSTRING(getrusage)
 
 @node Hashing Functions
--- a/doc/interpreter/testfun.txi
+++ b/doc/interpreter/testfun.txi
@@ -41,8 +41,12 @@
 
 Since @code{eval()} will stop at the first error it encounters, you must
 divide your tests up into blocks, with anything in a separate
-block evaluated separately.  Blocks are introduced by the keyword
-@code{test} immediately following @samp{%!}.  For example:
+block evaluated separately.  Blocks are introduced by valid keywords like
+@code{test}, @code{function}, or @code{assert} immediately following @samp{%!}.
+A block is defined by indentation as in Python.  Lines beginning with
+@samp{%!<whitespace>} are part of the preceeding block.
+ 
+For example:
 
 @example
 @group
@@ -72,7 +76,7 @@
 %! get = kron (@var{b}, @var{a});
 %! if (any (size (expect) != size (get)))
 %!   error ("wrong size: expected %d,%d but got %d,%d",
-%!          size(expect), size(get));
+%!          size (expect), size (get));
 %! elseif (any (any (expect != get)))
 %!   error ("didn't get what was expected.");
 %! endif
@@ -137,7 +141,7 @@
 @end example
 
 @noindent
-Review @file{config.h} or @code{octave_config_info ("DEFS")} to see some
+Review @file{config.h} or @code{octave_config_info ("features")} to see some
 of the possible values to check.
 
 Sometimes during development there is a test that should work but is
@@ -197,6 +201,24 @@
 Note that all previous variables and values are lost when a new 
 shared block is declared.
 
+Remember that @code{%!function} begins a new block and that 
+@code{%!endfunction} ends this block.  Be aware that until a new block
+is started, lines starting with @samp{%!<space>} will be discarded as comments.
+The following is nearly identical to the example above, but does nothing.
+
+@example
+@group
+%!function @var{a} = fn (@var{b})
+%!  @var{a} = 2*@var{b};
+%!endfunction
+%! assert (fn(2), 4);
+@end group
+@end example
+
+@noindent
+Because there is a space after @samp{%!} the @code{assert} statement does
+not begin a new block and this line is treated as a comment.
+
 Error and warning blocks are like test blocks, but they only succeed 
 if the code generates an error.  You can check the text of the error
 is correct using an optional regular expression @code{<pattern>}.  
--- a/doc/interpreter/tips.txi
+++ b/doc/interpreter/tips.txi
@@ -296,20 +296,20 @@
 When choosing variable names try to adhere to the following guidelines.
 
 @table @asis
-@item 
-vectors : x,y,z,t,w
+@item vectors :
+x,y,z,t,w
 
-@item
-matrices : A,B,M
+@item matrices :
+A,B,M
 
-@item
-strings : @nospell{str},s
+@item strings :
+@nospell{str},s
 
-@item
-filenames : @nospell{fname}
+@item filenames :
+@nospell{fname}
 
-@item
-cells,@nospell{cellstrs} : c,@nospell{cstr}
+@item cells,@nospell{cellstrs} :
+c,@nospell{cstr}
 @end table
 
 @item
--- a/doc/interpreter/var.txi
+++ b/doc/interpreter/var.txi
@@ -272,21 +272,21 @@
 
 clear
 for i = 1:2
-  count_calls();
+  count_calls ();
 endfor
 @print{} 'count_calls' has been called 3 times
 @print{} 'count_calls' has been called 4 times
 
 clear all
 for i = 1:2
-  count_calls();
+  count_calls ();
 endfor
 @print{} 'count_calls' has been called 1 times
 @print{} 'count_calls' has been called 2 times
 
 clear count_calls
 for i = 1:2
-  count_calls();
+  count_calls ();
 endfor
 @print{} 'count_calls' has been called 1 times
 @print{} 'count_calls' has been called 2 times
--- a/doc/interpreter/vectorize.txi
+++ b/doc/interpreter/vectorize.txi
@@ -191,6 +191,7 @@
 
 @item
 Repetition
+
 @itemize
 @item
 repmat
@@ -201,6 +202,7 @@
 
 @item
 Vectorized arithmetic
+
 @itemize
 @item
 sum
@@ -232,6 +234,7 @@
 
 @item
 Shape of higher dimensional arrays
+
 @itemize
 @item
 reshape
@@ -342,8 +345,8 @@
 subtraction takes place.
 
 A special case of broadcasting that may be familiar is when all
-dimensions of the array being broadcast are 1, i.e. the array is a
-scalar. Thus for example, operations like @code{x - 42} and @code{max
+dimensions of the array being broadcast are 1, i.e., the array is a
+scalar.  Thus for example, operations like @code{x - 42} and @code{max
 (x, 2)} are basic examples of broadcasting.
 
 For a higher-dimensional example, suppose @code{img} is an RGB image of
@@ -657,7 +660,7 @@
 @group
 n = length (A);
 B = zeros (n, 2);
-for i = 1:length(A)
+for i = 1:length (A)
   ## this will be two columns, the first is the difference and
   ## the second the mean of the two elements used for the diff.
   B(i,:) = [A(i+1)-A(i), (A(i+1) + A(i))/2)];
--- a/doc/liboctave/Makefile.am
+++ b/doc/liboctave/Makefile.am
@@ -1,4 +1,4 @@
-# Makefile for octave's doc/liboctave directory
+# Makefile for Octave's doc/liboctave directory
 #
 # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
 #               2005, 2006, 2007 John W. Eaton
@@ -21,10 +21,6 @@
 
 include $(top_srcdir)/build-aux/common.mk
 
-## Automake generated rules for documentation are not parallel-safe.
-## Restrict current directory to run serially
-.NOTPARALLEL:
-
 TEXINFO_TEX = ../texinfo.tex
 
 info_TEXINFOS = liboctave.texi
@@ -52,7 +48,13 @@
 
 all-local: dvi html pdf ps
 
-liboctave.info liboctave.dvi liboctave.html liboctave.pdf: $(srcdir)/version.texi
+## The texi2dvi script (used to create both PDF and DVI output formats)
+## uses some fixed temporary file names.  In order to avoid a race condition
+## the DVI and PDF builds are forced to run serially through a Makefile rule.
+liboctave.pdf: liboctave.dvi
 
 EXTRA_DIST = liboctave.dvi liboctave.html liboctave.pdf liboctave.ps
 
+clean-local:
+	rm -rf t2d_cache
+
--- a/doc/liboctave/liboctave.texi
+++ b/doc/liboctave/liboctave.texi
@@ -80,10 +80,10 @@
 @end ifnottex
 
 @titlepage
-@title{Octave C++ Classes}
-@subtitle{Edition 1.0 for Octave version @value{VERSION}}
-@subtitle{September 1993}
-@author{John W. Eaton}
+@title Octave C++ Classes
+@subtitle Edition 1.0 for Octave version @value{VERSION}
+@subtitle September 1993
+@author John W. Eaton
 @page
 @vskip 0pt plus 1filll
 Copyright @copyright{} 1996, 1997 John W. Eaton.
--- a/doc/refcard/Makefile.am
+++ b/doc/refcard/Makefile.am
@@ -1,4 +1,4 @@
-# Makefile for octave's doc/refcard directory
+# Makefile for Octave's doc/refcard directory
 #
 # Copyright (C) 1996-2012 John W. Eaton
 #
--- a/doc/refcard/refcard.tex
+++ b/doc/refcard/refcard.tex
@@ -679,7 +679,7 @@
 \sec Paths and Packages;
 path&display the current Octave function path.\cr
 pathdef&display the default path.\cr
-addpath({\it dir})&add a directory to the path.\cr
+addpath ({\it dir})&add a directory to the path.\cr
 EXEC\_PATH&manipulate the Octave executable path.\cr
 pkg list&display installed packages.\cr
 pkg load {\it pack}&Load an installed package.\cr
@@ -688,8 +688,8 @@
 \sec Cells and Structures;
 {\it{var}}.{\it{field}} = ...&set a field of a structure.\cr
 {\it{var}}$\{${\it{idx}}$\}$ = ...&set an element of a cell array.\cr
-cellfun({\it f}, {\it c})&apply a function to elements of cell array.\cr
-fieldnames({\it s})&returns the fields of a structure.\cr
+cellfun ({\it f}, {\it c})&apply a function to elements of cell array.\cr
+fieldnames ({\it s})&returns the fields of a structure.\cr
 \endsec
 
 \widesec Statements;
@@ -803,10 +803,10 @@
   values\cr 
 \endsec
 
-% sin({\it a}) cos({\it a}) tan({\it a})&trigonometric functions\cr
-% asin({\it a}) acos({\it a}) atan({\it a})&inverse trigonometric functions\cr
-% sinh({\it a}) cosh({\it a}) tanh({\it a})&hyperbolic trig functions\cr
-% asinh({\it a}) acosh({\it a}) atanh({\it a})&inverse hyperbolic trig
+% sin ({\it a}) cos({\it a}) tan({\it a})&trigonometric functions\cr
+% asin ({\it a}) acos({\it a}) atan({\it a})&inverse trigonometric functions\cr
+% sinh ({\it a}) cosh({\it a}) tanh({\it a})&hyperbolic trig functions\cr
+% asinh ({\it a}) acosh({\it a}) atanh({\it a})&inverse hyperbolic trig
 % functions\cr\cr 
 
 \sec Linear Algebra;
--- a/etc/HACKING
+++ b/etc/HACKING
@@ -5,7 +5,7 @@
 
 * Working from the repository
 
-These notes are intended to help people working on sources checked-out from
+These notes are intended to help people working on sources cloned from
 the savannah source code repository.
 These requirements do not apply when building from a distribution tarball.
 
@@ -13,7 +13,7 @@
 
 We've opted to keep only the highest-level sources in the repository.
 This eases our maintenance burden, (fewer merges, etc.), but imposes
-more requirements on anyone wishing to build from the just-checked-out
+more requirements on anyone wishing to build from the just-cloned
 sources.  For example, you have to use the latest stable versions of
 the maintainer tools we depend upon, including:
 
@@ -21,7 +21,6 @@
   - Automake <http://www.gnu.org/software/automake/>
   - Bison <http://www.gnu.org/software/bison/>
   - Flex <http://www.gnu.org/software/flex/>
-  - Git <http://git-scm.com/>
   - Gnulib <http://www.gnu.org/software/gnulib/>
   - GNU Make <http://www.gnu.org/software/make/>
   - Gzip <http://www.gnu.org/software/gzip/>
@@ -35,24 +34,23 @@
 Later, after synchronizing from the repository, a plain `make' should
 be sufficient.
 
-** First checkout
+** First clone
 
-Obviously, if you are reading these notes, you did manage to check out
+If you are reading these notes, you may have already managed to clone
 this package from the repository.  For the record, you will find all the
 relevant information on downloading sources at:
 
   http://www.octave.org/download.html
 
-After checking out Octave, you will need to run the autogen.sh script:
+After cloning Octave, you will need to run the bootstrap script:
 
-  $ ./autogen.sh
+  $ ./bootstrap
 
 This script will examine the source tree and generate some Makefile
-fragments and then runs the bootstrap script.  The bootstrap script comes
-from gnulib, but is kept in the Octave source archive.  It should be
-updated from the gnulib sources as necssary.  The bootstrap script takes
-care of checking out a copy of gnulib, running the autotools, and
-generating the configure script.
+fragments, then run autotools scripts to generate Makefile.in files from
+Makefile.am files and create the configure script.  The bootstrap script
+comes from gnulib, but is kept in the Octave source archive.  It should
+be updated from the gnulib sources as necessary.
 
 If you have a copy of gnulib in some directory apart from the Octave
 source tree, then pass the name of the directory containing gnulib-tool
@@ -66,25 +64,28 @@
 gnulib-tool script resides).
 
 By using an external gnulib directory, you can share a single gnulib source
-tree among several projects.  Regardless of the location of the gnulib
-sources, the bootstrap script will try to update them if it appears
-that they are checked out using git.  Otherwise, it is your
-responsibility to keep the gnulib sources up to date.  They change
-frequently, so the best way to stay current is probably to use git to
-do the job.
+tree among several projects.  Since 2011, the gnulib sources are a Mercurial
+subrepository, so they will be automatically updated to the
+corresponding Mercurial revision if you update the working directory to
+a past revision not too far in the past.
+
+Additional options besides --gnulib-srcdir can be passed to bootstrap and
+they will be forwarded without modification to the gnulib bootstrap script.
 
-Additional options besides --gnulib-srcdir can be passed to autogen.sh and
-they will be forwarded without modification to the bootstrap script.
+Once the bootstrap script completes successfully, you may configure and
+build Octave.  We recommend that you build Octave in a separate
+directory tree from the sources.  For example, if you have just finished
+running the bootstrap script in the top-level source directory, run the
+following commands to create a build tree, configure, and build Octave:
 
-Once the autogen.sh and bootstrap scripts complete successfully, you may
-run
-
-  $ ./configure
+  $ mkdir .build
+  $ cd .build
+  $ ../configure
   $ make
   $ make check
 
-At this point, there should be no difference between your local copy,
-and the master copy:
+At this point, there should be no difference between your working tree
+and the currently visited hg revision:
 
   $ hg diff
 
@@ -108,88 +109,207 @@
 
   doc           -- Texinfo documentation for Octave
 
+
   examples      -- some example files
 
-  libcruft      -- various numerical libraries (mostly Fortran)
-    amos           * bessel functions
-    blas-xtra      * wrappers for blas functions used in Octave
-    daspk          * large scale differential algebraic equation solver
-    dasrt          * differential algebraic equation solver with root finding
-    dassl          * differential-algebraic system solver
-    fftpack        * subroutines for fast fourier transforms
-    lapack-xtra    * wrappers for lapack functions used in Octave
-    misc           * miscellaneous utilities
-    odepack        * ordinary differential equation solver
-    ordered-qz     * code for ordering eigenvalues for QZ factorization
-    quadpack       * subroutines for numerical integration
-    ranlib         * random number generators
-    slatec-err     * slatec error handling library
-    slatec-fn      * various special function subroutines
+
+  gnulib-hg     -- gnulib subrepo.  This is a clone of the gnulib source
+                   tree maintained by the Octave project.  The default
+                   branch is identical to the upstream gnulib sources.
+                   There is also an "octave-stable" branch that may
+                   contain changes as needed for the "stable" branch in
+                   the Octave archive.  We usually don't want to update
+                   gnulib sources when going from one stable point
+                   release to the next, but we occasionally need to
+                   include small updates.
+
 
-  liboctave     -- the C++ interfaces to the numerical libraries and
-                   various OS facilities
+  libgnu        -- gnulib sources that we use.  The files here are
+                   copied here from the gnulib directory by the
+                   bootstrap script.
+
+
+  liboctave     -- C++ interfaces to the numerical libraries, Fortran
+                   numerical libraries, various OS facilities, and utility
+                   functions
+
+    array       the base Array, NDArray, Matrix, and Sparse classes
+
+    cruft       various numerical libraries (mostly Fortran)
+
+      amos             bessel functions
+
+      blas-xtra        wrappers for blas functions used in Octave
+
+      daspk            large scale differential algebraic equation solver
 
-  scripts       -- functions written in the Octave language
-    audio          * play and record sound files (system dependent)
-    deprecated     * older deprecated functions
-    elfun          * elementary mathematical functions
-    @ftp           * ftp object class
-    general        * utility functions
-    geometry       * geometry algorithms
-    help           * help subsystem functions
-    image          * image processing
-    io             * input/output functions
-    linear-algebra * linear algebra stuff
-    miscellaneous  * stuff that doesn't fit anywhere else
-    optimization   * zero finders and minimizers
-    path           * functions for path manipulation
-    pkg            * the package manager
-    plot           * plotting functions
-    polynomial     * polynomial manipulation
-    prefs          * user-defined preferences
-    set            * set manipulation
-    signal         * signal processing
-    sparse         * sparse matrix support
-    specfun        * special mathematical functions
-    special-matrix * functions for generating special types of matrices
-    startup        * initialization functions
-    statistics     * statistical functions, distributions, and tests
-    strings        * character string manipulation
-    testfun        * unit testing
-    time           * time and date functions
+      dasrt            differential algebraic equation solver with root finding
+
+      dassl            differential-algebraic system solver
+
+      fftpack          subroutines for fast fourier transforms
+
+      lapack-xtra      wrappers for lapack functions used in Octave
+
+      misc             miscellaneous utilities
+
+      odepack          ordinary differential equation solver
+
+      ordered-qz       code for ordering eigenvalues for QZ factorization
+
+      quadpack         subroutines for numerical integration
 
-  src           -- the interpreter itself plus lots of infrastructure
+      ranlib           random number generators
+
+      slatec-err       slatec error handling library
+
+      slatec-fn        various special function subroutines
+
+    numeric     C++ numerical algorithms and interfaces to the Fortran
+                algorithms
+
+    operators   code for operators that act on base classes such as Array
+
+    system      OS-related functions
+ 
+    util        utility and miscellaneous functions
+
+  libinterp     -- The interpreter itself plus lots of infrastructure
                    around it.  Octave's extensive octave_value class
                    hierarchy for polymorphically handling all Octave
                    types is defined here.  The built-in functions are
-                   also defined here, so if "help foo" tells you foo is
-                   built-in, its source will be somewhere in this
-                   directory.
-    DLD-FUNCTIONS  * Dynamically linked oct files.  If you see "help foo"
-                     telling you that foo is defined in foo.oct, then
-                     foo.cc will be found here and contain the source
-                     code.
-    OPERATORS      * Definitions and template instantiations for
+                   also defined here.
+
+    octave-value     The octave_value class hierarchy.  These are the
+                     container classes that hold various Octave data
+                     types like struct numerical arrays, structure
+                     arrays, and cell arrays.
+
+    parse-tree       Classes that define the parse tree for the
+                     interpreter.
+
+    interp-core      Core utilities for the interpreter.  There are no
+                     DEFUN functions (callable from the scripting
+                     language) defined here.
+
+    interpfcn        Functions closely related to the interpreter.
+                     Includes DEFUN functions (callable from the
+                     scripting language).  Also may export C++ functions
+                     that are used in other parts of the interpreter.
+
+    corefcn          Statically linked DEFUN functions (callable from
+                     the scripting langauge).  No C++ functions exported
+                     for use in other parts of the interpreter.
+
+    dldfcn           Dynamically linked DEFUN functions (callable
+                     from the scripting language).  If you see "help
+                     foo" telling you that foo is defined in foo.oct,
+                     then foo.cc will be found here and contain the
+                     source code.
+
+    operators        Definitions and template instantiations for
                      operators for all possible Octave type
                      combinations.
-    TEMPLATE-INST  * Some C++ template instantiations.
+
+    template-inst    Some C++ template instantiations.
+
+
+  libgui        -- the graphical user interface of GNU Octave
+
+    src              source files.
+
+      m-editor       source files for the m-file editor.
+
+      octave-adapter souce files for the octave layer for threadsafe
+                     communication with the octave interpreter.
+      qtinfo         source files for the Qt texinfo browser.
+
+      icons          icon files that will be compiled into the
+                     executable via a resource file.
+
+    qterminal        Qt terminal widget
+
+    languages        translation files and list of translators.
+
+    kb-layouts       various files need by the qterminal widget that has
+                     been derived from Konsole.
+      
+
+  scripts       -- functions written in the Octave language
+
+    audio            play and record sound files (system dependent)
+
+    deprecated       older deprecated functions
+
+    elfun            elementary mathematical functions
+
+    @ftp             ftp object class
+
+    general          utility functions
+
+    geometry         geometry algorithms
+
+    help             help subsystem functions
+
+    image            image processing
+
+    io               input/output functions
+
+    linear-algebra   linear algebra stuff
+
+    miscellaneous    stuff that doesn't fit anywhere else
+
+    optimization     zero finders and minimizers
+
+    path             functions for path manipulation
+
+    pkg              the package manager
+
+    plot             plotting functions
+
+    polynomial       polynomial manipulation
+
+    prefs            user-defined preferences
+
+    set              set manipulation
+
+    signal           signal processing
+
+    sparse           sparse matrix support
+
+    specfun          special mathematical functions
+
+    special-matrix   functions for generating special types of matrices
+
+    startup          initialization functions
+
+    statistics       statistical functions, distributions, and tests
+
+    strings          character string manipulation
+
+    testfun          unit testing
+
+    time             time and date functions
+
 
   test          -- tests for the interpreter
-    test_*.m       * fixed tests for the interpreter
-    fntests.m      * script to run function tests embedded in C++ and .m files
+
+    test_ .m         fixed tests for the interpreter
 
+    fntests.m        script to run function tests embedded in C++ and .m
+                     files
 
 ----
 John W. Eaton
 jwe@octave.org
 
 
-Last updated: Tue Nov 22 20:51:34 PST 2011
+Last updated: Thu, 10 Jan 2013 10:46:41 EST
 
 
 ################################################################################
 
-Copyright (C) 2009,2012 John W. Eaton
+Copyright (C) 2009-2012 John W. Eaton
 
 This file is part of Octave.
 
--- a/etc/OLD-ChangeLogs/ChangeLog
+++ b/etc/OLD-ChangeLogs/ChangeLog
@@ -1882,7 +1882,7 @@
 	(--enable-strict-warning-flags): Rename from --enable-picky-flags.
 	(GXX_STRICT_FLAGS): Remove -Wenum-clash from the list.
 
-2009-03-08  S�ren Hauberg  <hauberg@gmail.com>
+2009-03-08  Søren Hauberg  <hauberg@gmail.com>
 
 	* NEWS: Mention 'histc'.
 
@@ -2652,7 +2652,7 @@
 	* aclocal.m4 (OCTAVE_PROG_GNUPLOT): Drop check for multiple plot
 	windows.
 
-2007-08-10  S�ren Hauberg  <hauberg@gmail.com>
+2007-08-10  Søren Hauberg  <hauberg@gmail.com>
 
 	* ROADMAP: Update for current sources.
 
@@ -2973,7 +2973,7 @@
 	* Makeconf.in (simple-move-if-change-rule,
 	(builddir-move-if-change-rule): New macros.
 
-2006-11-11  S�ren Hauberg  <hauberg@gmail.com>
+2006-11-11  Søren Hauberg  <hauberg@gmail.com>
 
 	* examples/Makefile.in (uninstall): Add missing semicolon.
 
@@ -3183,7 +3183,7 @@
 2006-09-27  John W. Eaton  <jwe@octave.org>
 
 	* mkoctfile.in [--mex]: Include -I. in incflags.
-	From S�ren Hauberg <hauberg@gmail.com>.
+	From Søren Hauberg <hauberg@gmail.com>.
 
 2006-09-26  John W. Eaton  <jwe@octave.org>
 
@@ -3565,7 +3565,7 @@
 	* configure.in: Use it.
 	* Makeconf.in: Substitute DESKTOP_FILE_INSTALL.
 
-	* octave.desktop.in: New file.  From S�ren Hauberg <hauberg@gmail.com>.
+	* octave.desktop.in: New file.  From Søren Hauberg <hauberg@gmail.com>.
 	* examples/Makefile.in (SOURCES): Add it to the list.
 	(octave.desktop): New target.
 	(all): Depend on octave.desktop.
--- a/etc/OLD-ChangeLogs/doc-ChangeLog
+++ b/etc/OLD-ChangeLogs/doc-ChangeLog
@@ -1311,11 +1311,11 @@
 	* interpreter/oop.txi: Update docs of polynomial class, mention
 	chained indexing.
 
-2009-05-27  S�ren Hauberg  <hauberg@gmail.com>
+2009-05-27  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/errors.txi: fix 'print_usage' output.
 
-2009-05-27  S�ren Hauberg  <hauberg@gmail.com>
+2009-05-27  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/bugs.txi: fix call to 'page_screen_output'.
 
@@ -1456,7 +1456,7 @@
 	* interpreter/Makefile.in (DISTFILES): Use doc-cache instead of
 	DOC for doc cache file.
 
-2009-03-08  S�ren Hauberg  <hauberg@gmail.com>
+2009-03-08  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/stats.txi (Basic Statistical Functions):
 	Add the 'histc' function.
@@ -1542,11 +1542,11 @@
 	(DISTFILES): Add DOC nad mk_doc_cache.m to the list.
 	* mk_doc_cache.m: New file.
 
-2009-02-01  S�ren Hauberg  <hauberg@gmail.com>
+2009-02-01  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/nonlin.txi: Remove reference to 'fsolve_options'.
 
-2009-02-01  S�ren Hauberg  <hauberg@gmail.com>
+2009-02-01  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/system.txi: Remove reference to 'eomdate'.
 
@@ -1562,7 +1562,7 @@
 	* vr-idx.txi: Delete.
 	* interpreter/Makefile.in (SUB_SOURCE): Remove it from the list.
 
-2009-01-22  S�ren Hauberg  <hauberg@gmail.com>
+2009-01-22  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/func.txi: Put varargin and varargout in concept index.
 	* interpreter/var.txi: Put ans in concept index.
@@ -1684,12 +1684,12 @@
 	* interpreter/contrib.txi: correction of the mercurial example
 	* interpreter/container.txi: minor correction of the text
 
-2008-09-25  S�ren Hauberg  <hauberg@gmail.com>
+2008-09-25  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/image.txi: Update for imread and imwrite instead of
 	loadimge and saveimage.
 
-2008-09-24  S�ren Hauberg  <hauberg@gmail.com>
+2008-09-24  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/image.txi: Document imfinfo.
 
@@ -1738,7 +1738,7 @@
 
 	* interpreter/numbers.txi: Document intwarning.
 
-2008-08-06  S�ren Hauberg  <hauberg@gmail.com>
+2008-08-06  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/basics.txi, interpreter/errors.txi,
 	interpreter/expr.txi, interpreter/func.txi,
@@ -1955,7 +1955,7 @@
 
 	* refcard/refcard.tex: Update for 3.0.
 
-2007-10-15  S�ren Hauberg  <hauberg@gmail.com>
+2007-10-15  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/preface.txi, interpreter/basics.txi,
 	interpreter/strings.txi, interpreter/container.txi,
@@ -1987,7 +1987,7 @@
 
 2007-10-06  John W. Eaton  <jwe@octave.org>
 
-	* interpreter/octave.texi: Add David Bateman and S�ren Hauberg as
+	* interpreter/octave.texi: Add David Bateman and Søren Hauberg as
 	authors.
 
 2006-09-28  Henry Mollet  mollet@pacbell.net
@@ -2019,7 +2019,7 @@
 	* interpreter/geometry.txi: Check whether TEXINFO_QHULL is set
 	before including certain figures.
 
-2007-08-31  S�ren Hauberg  <hauberg@gmail.com>
+2007-08-31  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/nonlin.txi: Extended the example.
 
@@ -2102,7 +2102,7 @@
 	* interpreter/interp.txi: Also change figures here.
 	* interpreter/Makefile.in: and here.
 
-2007-06-18  S�ren Hauberg  <hauberg@gmail.com>
+2007-06-18  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/optim.txi: Added some introductory text to each
 	section.
@@ -2148,7 +2148,7 @@
 	chapter. Remove references to Hashing chapter and hashing.texi,
 	and subsections for hashing to system utilities chapter.
 
-2007-06-12  2007-06-10  S�ren Hauberg  <hauberg@gmail.com>
+2007-06-12  2007-06-10  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/diffeq.txi: Note that x-dot is the derivative of x.
 
@@ -2176,7 +2176,7 @@
 	* interpreter/Makefile.in ($(HTML_IMAGES_PNG)): Use cp instead of
 	INSTALL_DATA to copy files to the HTML directory.
 
-2007-05-28  S�ren Hauberg  <hauberg@gmail.com>
+2007-05-28  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/errors.txi: Add new sections and some more detailed
 	descriptions on errors and warnings.
@@ -2184,7 +2184,7 @@
 	interpreter/var.txi: Add references to the new sections in
 	errors.txi.
 
-2007-05-28  S�ren Hauberg  <hauberg@gmail.com>
+2007-05-28  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/io.txi: Rearrange some sections, and add
 	a few examples.
@@ -2218,7 +2218,7 @@
 
 	* interpreter/debug.txi, io.txi, octave.txi: Doc fixes.
 
-2007-05-21  S�ren Hauberg  <hauberg@gmail.com>
+2007-05-21  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/expr.txi: Describe +=, -=, *=, and /= operators.
 	Add new example.
@@ -2240,7 +2240,7 @@
 	* interpreter/func.txi: Additional documentation for function
 	locking, dispatch and autoloading.
 
-2007-05-16  S�ren Hauberg  <hauberg@gmail.com>
+2007-05-16  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/expr.txi: Improve docs.
 
@@ -2250,7 +2250,7 @@
 	interpreter/intro.txi, interpreter/numbers.txi,
 	interpreter/octave.texi, interpreter/preface.txi: Doc fixes.
 
-2007-04-18  S�ren Hauberg  <hauberg@gmail.com>
+2007-04-18  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/package.texi: Document "*" flag for loaded packages.
 
@@ -2333,7 +2333,7 @@
 
 	* Makefile.in (SUB_SOURCE): Include dynamic.txi in the list.
 
-2007-04-18  S�ren Hauberg  <hauberg@gmail.com>
+2007-04-18  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/package.texi: New file.
 	* octave/texi: @include it, add it to the menus.
@@ -2358,7 +2358,7 @@
 	* interpreter/stream.txi: Delete.
 	* interpreter/Makefile.in (SUB_SOURCE): Remove it from the list.
 
-2007-04-16  S�ren Hauberg  <hauberg@gmail.com>
+2007-04-16  Søren Hauberg  <hauberg@gmail.com>
 
 	* intrepreter/stmt.txi: Improve documentation of switch statement.
 
@@ -2370,15 +2370,15 @@
 
 	* interpreter/image.txi: Update docs.
 
-2007-04-11  S�ren Hauberg  <hauberg@gmail.com>
+2007-04-11  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/container.txi: Document indexing with ().
 
-2007-04-11  S�ren Hauberg  <hauberg@gmail.com>
+2007-04-11  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/container.txi: Improve cell array documentation.
 
-2007-04-09  S�ren Hauberg  <hauberg@gmail.com>
+2007-04-09  Søren Hauberg  <hauberg@gmail.com>
 
 	* interpreter/func.txi: Document varargin, varargout, and default
 	argument values.
--- a/etc/OLD-ChangeLogs/liboctave-ChangeLog
+++ b/etc/OLD-ChangeLogs/liboctave-ChangeLog
@@ -1480,7 +1480,7 @@
 	Remove occurences of ftrunc, fnon_int and fnan eveywhere.
 	* oct-inttypes.cc: Ditto last sentence. Remove warning tests.
 
-2010-03-07  Soren Hauberg  <hauberg@gmail.com>
+2010-03-07  Søren Hauberg  <hauberg@gmail.com>
 
 	* dim-vector.h: New constructor accepting a C array of dimensions.
 
--- a/etc/OLD-ChangeLogs/scripts-ChangeLog
+++ b/etc/OLD-ChangeLogs/scripts-ChangeLog
@@ -1585,7 +1585,7 @@
 
 	* audio/setaudio.m: Re-write docstring.
 
-2010-12-23  Soren Hauberg  <hauberg@gmail.com>
+2010-12-23  Søren Hauberg  <hauberg@gmail.com>
 
 	* signal/detrend.m: Also accept polynomial order as a string
 	("constant" or "linear") for compatibility with Matlab.
@@ -2863,7 +2863,7 @@
 	* general/interpn.m: Convert interpolation vectors of non-equal
 	length to nd-arrays.
 
-2010-07-26  Soren Hauberg  <hauberg@gmail.com>
+2010-07-26  Søren Hauberg  <hauberg@gmail.com>
 
 	* image/image.m: Replace parenthesis with curly bracket in Texinfo.
 
@@ -3065,7 +3065,7 @@
 	* newplot.m: Conditionally initialisation the line style and color
 	based on the __hold_all__ axes property.
 
-2010-07-04  Soren Hauberg  <hauberg@gmail.com>
+2010-07-04  Søren Hauberg  <hauberg@gmail.com>
 
 	* polynomial/deconv.m: ensure that the orientation of the third
 	input to 'filter' matches the orientation of 'y'.
@@ -3733,17 +3733,17 @@
 
 	* plot/refreshdata.m: Don't use cell2mat on cell array of cell arrays.
 
-2010-03-22  Soren Hauberg  <hauberg@gmail.com>
+2010-03-22  Søren Hauberg  <hauberg@gmail.com>
 
 	* image/gmap40.m, image/hot.m, image/hsv2rgb.m, image/image.m,
 	image/image_viewer.m, image/imfinfo.m, image/imread.m, image/imshow.m,
 	image/saveimage: Detabify.
 
-2010-03-21  Soren Hauberg  <hauberg@gmail.com>
+2010-03-21  Søren Hauberg  <hauberg@gmail.com>
 
 	* general/quadv.m: Replace 'quadl' with 'quadv' in help text.
 
-2010-03-20  Soren Hauberg  <hauberg@gmail.com>
+2010-03-20  Søren Hauberg  <hauberg@gmail.com>
 
 	* general/interp2.m: For nearest neighbour interpolation ceil
 	(instead of floor) at the center of the data intervals to be
@@ -3782,12 +3782,12 @@
 
 	* strings/strchr.m: Optimize.
 
-2010-03-05  Soren Hauberg  <hauberg@gmail.com>
+2010-03-05  Søren Hauberg  <hauberg@gmail.com>
 
 	* pkg/pkg.m (write_index): include classes in autogenerated
 	INDEX files.
 
-2010-03-05  Soren Hauberg  <hauberg@gmail.com>
+2010-03-05  Søren Hauberg  <hauberg@gmail.com>
 
 	* plot/fplot.m: Ensure that 'limits' is a 2 or 4 vector, and
 	that 'fn' is a function.
@@ -4738,7 +4738,7 @@
 	* general/tril.m, general/triu.m: Remove sources.
 	* general/Makefile.in: Update.
 
-2009-10-20  Soren Hauberg  <hauberg@gmail.com>
+2009-10-20  Søren Hauberg  <hauberg@gmail.com>
 
 	* general/interp2.m: improved error checking and support for bicubic
 	interpolation when X and Y are meshgrid format.
@@ -4749,7 +4749,7 @@
 	instead of multiple ifs).
 	* polynomial/pchip.m: Employ more optimized formulas (from SLATEC).
 
-2009-10-22  Soren Hauberg  <hauberg@gmail.com>
+2009-10-22  Søren Hauberg  <hauberg@gmail.com>
 
 	* image/autumn.m, image/bone.m, image/cool.m, image/copper.m,
 	image/flag.m, image/gmap40.m, image/gray.m, image/hot.m,
@@ -4757,11 +4757,11 @@
 	image/prism.m, image/rainbow.m, image/spring.m, image/summer.m,
 	image/white.m, image/winter.m: Add demos.
 
-2009-10-20  Soren Hauberg  <hauberg@gmail.com>
+2009-10-20  Søren Hauberg  <hauberg@gmail.com>
 
  	* general/interp2.m: improved error checking and support for bicubic
 
-2009-10-19  Soren Hauberg  <hauberg@gmail.com>
+2009-10-19  Søren Hauberg  <hauberg@gmail.com>
 
 	* io/strread.m, io/textread.m: New functions.
 
@@ -5242,7 +5242,7 @@
 	* plot/__go_draw_axes__.m: Fix rendering of overlaping images and
 	line objects.  Add demos as well.
 
-2009-05-27 S�ren Hauberg  <hauberg@gmail.com>
+2009-05-27 Søren Hauberg  <hauberg@gmail.com>
 
 	* geometry/delaunay.m: Support cellstr's as options.
 
@@ -5250,7 +5250,7 @@
 
 	* plot/imshow.m: Fix handling of indexed images.
 
-2009-05-26 S�ren Hauberg  <hauberg@gmail.com>
+2009-05-26 Søren Hauberg  <hauberg@gmail.com>
 
 	* help/__makeinfo__.m: Support several @seealso's in one text.
 
@@ -5621,7 +5621,7 @@
 	__accumarray_sum__ for the default summation case.
 	* statistics/base/histc.m: Reimplement using lookup & accumarray.
 
-2009-03-08  S�ren Hauberg  <hauberg@gmail.com>
+2009-03-08  Søren Hauberg  <hauberg@gmail.com>
 
 	* statistics/base/histc.m: New function.
 
@@ -5959,12 +5959,12 @@
 
 	* general/sortrows.m: Call __sort_rows_idx__, not __sortrows_idx__.
 
-2009-02-12  Soren Hauberg  <hauberg@gmail.com>
+2009-02-12  Søren Hauberg  <hauberg@gmail.com>
 
 	* help/gen_doc_cache.m: Change API so we only handle one directory per
 	call to this function.
 
-2009-02-12  Soren Hauberg  <hauberg@gmail.com>
+2009-02-12  Søren Hauberg  <hauberg@gmail.com>
 
 	* help/lookfor.m: Adapt to new cache scheme.
 
@@ -6012,7 +6012,7 @@
 
 	* help/which.m: Still print something sensible if type is empty.
 
-2009-02-04  Soren Hauberg  <hauberg@gmail.com>
+2009-02-04  Søren Hauberg  <hauberg@gmail.com>
 	    Thomas Treichl  <Thomas.Treichl@gmx.net>
 
 	* miscellaneous/Makefile.in (SOURCES): Add bzip2.m to the list.
@@ -6107,7 +6107,7 @@
 
 	* plot/__go_draw_axes__.m: Add support for transparent patches.
 
-2009-01-29  S�ren Hauberg  <hauberg@gmail.com>
+2009-01-29  Søren Hauberg  <hauberg@gmail.com>
 
 	* help/help.m, help/print_usage.m, help/get_first_help_sentence.m:
 	print sensible error message when function is found but not documented.
@@ -6160,7 +6160,7 @@
 
 	* polynomial/spline.m: Doc fix.
 
-2009-01-27  S�ren Hauberg  <hauberg@gmail.com>
+2009-01-27  Søren Hauberg  <hauberg@gmail.com>
 
 	* general/gradient.m: Handle computing the gradient of a function
 	handle.
@@ -6206,7 +6206,7 @@
 
 	* sparse/svds.m: svds.m: skip tests if ARPACK is missing.
 
-2009-01-23  S�ren Hauberg  <hauberg@gmail.com>
+2009-01-23  Søren Hauberg  <hauberg@gmail.com>
 
 	* help/type.m: Make 'type X' work, when X is the name of a variable.
 
@@ -6220,7 +6220,7 @@
 	* help/__additional_help_message__.m: Return message instead of
 	displaying it.
 
-2009-01-22  S�ren Hauberg  <hauberg@gmail.com>
+2009-01-22  Søren Hauberg  <hauberg@gmail.com>
 
 	* help: New directory.
 	* configure.in (AC_CONFIG_FILES): Add help/Makefile to the list.
@@ -6311,7 +6311,7 @@
 	* plot/__go_draw_axes__.m (ticklabel_to_cell): New function.
 	Use it to handle non-cell ticklabels.
 
-2009-01-14  S�ren Hauberg  <hauberg@gmail.com>
+2009-01-14  Søren Hauberg  <hauberg@gmail.com>
 
 	* general/diff.m, general/logspace.m, general/nextpow2.m,
 	linear-algebra/commutation_matrix.m,
@@ -6695,7 +6695,7 @@
 	* optimization/qp.m: Convert bounds of the form b <= x <= b and
 	constraints of the form b <= A*x <= b to equality constraints.
 
-2008-10-27  S�ren Hauberg  <hauberg@gmail.com>
+2008-10-27  Søren Hauberg  <hauberg@gmail.com>
 
 	* plot/ellipsoid.m: Check nargin == 6, not nargin == 5.
 
@@ -6972,7 +6972,7 @@
 
 	* image/imfinfo.m: Delete temporary file.
 
-2008-09-25  S�ren Hauberg  <hauberg@gmail.com>
+2008-09-25  Søren Hauberg  <hauberg@gmail.com>
 
 	* image/imread.m, image/imwrite.m: Doc fix.
 
@@ -6980,7 +6980,7 @@
 
 	* plot/fplot.m: Call axis after calling plot.
 
-2008-09-24  S�ren Hauberg  <hauberg@gmail.com>
+2008-09-24  Søren Hauberg  <hauberg@gmail.com>
 
 	* image/imfinfo.m: New function.
 	* image/Makefile.in (SOURCES): Add it to the list.
@@ -7450,7 +7450,7 @@
 	Change caller.  Improve sizing and position of colorbox for subplots.
 	* plot/colorbar.m: New demos.
 
-2008-04-16  S�ren Hauberg  <hauberg@gmail.com>
+2008-04-16  Søren Hauberg  <hauberg@gmail.com>
 
 	* plot/__gnuplot_version__.m: Display error if gnuplot is not found.
 
@@ -7740,7 +7740,7 @@
 	* miscellaneous/info.m: New function.
 	* miscellaneous/Makefile.in (SOURCES): Add it to the list.
 
-2008-03-27  S�ren Hauberg  <hauberg@gmail.com>
+2008-03-27  Søren Hauberg  <hauberg@gmail.com>
 
 	* plot/xlim.m, plot/ylim.m, plot/zlim.m, strings/strtrim.m:
 	Doc fixes.
@@ -7798,7 +7798,7 @@
 
 	* linear-algebra/dmult.m: Handle scaling along arbitrary dimension.
 
-2008-03-26  S�ren Hauberg  <hauberg@gmail.com>
+2008-03-26  Søren Hauberg  <hauberg@gmail.com>
 
 	* polynomial/convn.m: New tests.
 
@@ -7810,7 +7810,7 @@
 	statistics/base/prctile.m: New functions.
 	* statistics/base/Makefile.in (SOURCES): Add them to the list.
 
-2008-03-25  S�ren Hauberg  <hauberg@gmail.com>
+2008-03-25  Søren Hauberg  <hauberg@gmail.com>
 
 	* polynomial/convn.m: New function.
 	* polynomial/Makefile.in (SOURCES): Add it to the list.
@@ -8327,7 +8327,7 @@
 
 	* plot/axis.m: Correctly handle "tight" and "image" options.
 
-2008-01-14  S�ren Hauberg  <hauberg@gmail.com>
+2008-01-14  Søren Hauberg  <hauberg@gmail.com>
 
 	* image/hsv2rgb.m, image/ntsc2rgb.m, image/rgb2hsv.m,
 	image/rgb2ntsc.m: Also accept images as input.
@@ -8388,7 +8388,7 @@
 
 	* general/sub2ind.m, general/ind2sub.m: Doc fix.
 
-2008-01-04  S�ren Hauberg   <hauberg@gmail.com>
+2008-01-04  Søren Hauberg   <hauberg@gmail.com>
 
 	* set/create_set.m, set/union.m: Accept "rows" argument.
 
@@ -8416,7 +8416,7 @@
 
 	Version 3.0.0 released.
 
-2007-12-21  S�ren Hauberg  <hauberg@gmail.com>
+2007-12-21  Søren Hauberg  <hauberg@gmail.com>
 
 	* image/imshow.m: Accept empty value for display_range.
 
@@ -8424,7 +8424,7 @@
 
 	* pkg/pkg.m: Add .lib as architecture-dependent suffix.
 
-2007-12-19  S�ren Hauberg  <hauberg@gmail.com>
+2007-12-19  Søren Hauberg  <hauberg@gmail.com>
 
 	* image/imshow.m: Store uint8 images as doubles.  Handle default
 	display ranges correctly.
@@ -9227,7 +9227,7 @@
 	* plot/print.m: Handle -textspecial and -textnormal flags for fig
 	output.
 
-2007-10-15  S�ren Hauberg  <hauberg@gmail.com>
+2007-10-15  Søren Hauberg  <hauberg@gmail.com>
 
 	* general/rat.m, sparse/pcg.m, sparse/pcr.m, optimization/sqp.m,
 	statistics/models/logistic_regression.m, polynomial/polygcd.m,
@@ -9412,7 +9412,7 @@
 
 	* polynomial/residue.m: New test from test/test_poly.m.
 
-2007-10-06  S�ren Hauberg  <hauberg@gmail.com>
+2007-10-06  Søren Hauberg  <hauberg@gmail.com>
 
 	* image/saveimage.m: Handle saving color images without a colormap.
 	* image/__img_via_file__.m: Add missing semicolon.
@@ -9655,7 +9655,7 @@
 
 	* plot/ancestor.m: New function, adapted from Octave Forge.
 
-2007-08-31  S�ren Hauberg  <hauberg@gmail.com>
+2007-08-31  Søren Hauberg  <hauberg@gmail.com>
 
 	* polynomial/polygcd.m: Better layout of example.
 	* polynomial/compan.m: Remove unnecessary check.
@@ -9889,7 +9889,7 @@
 	* plot/drawnow.m, plot/__go_draw_axes__.m: Use strcmpi instead of
 	strcmp for selected property comparisons.
 
-2007-06-25  S�ren Hauberg  <hauberg@gmail.com>
+2007-06-25  Søren Hauberg  <hauberg@gmail.com>
 
 	* image/imshow.m: Fix check for colormap arguments.
 
@@ -9897,7 +9897,7 @@
 
 	* plot/drawnow.m: Handle GNUTERM=aqua if DISPLAY is not set.
 
-2007-06-25  S�ren Hauberg  <hauberg@gmail.com>
+2007-06-25  Søren Hauberg  <hauberg@gmail.com>
 
 	* statistics/base/median.m: Update help text to mention 'dim'
 	argument, and note that the data should be sorted for the
@@ -9990,19 +9990,19 @@
 	* plot/__go_draw_axes__.m (do_tics, do_tics_1): New functions.
 	(__go_draw_axes__): Call do_tics to handle tic marks.
 
-2007-06-18  S�ren Hauberg  <hauberg@gmail.com>
+2007-06-18  Søren Hauberg  <hauberg@gmail.com>
 
 	* general/interp1.m, general/interp2.m, general/interp3.m,
 	general/interpn.m: Replace, NaN with NA.  Use isna instead of ==
 	to check for NA.
 
-2007-06-18  S�ren Hauberg  <hauberg@gmail.com>
+2007-06-18  Søren Hauberg  <hauberg@gmail.com>
 
 	* optimization/glpk.m: TeXified the help text.
 	* optimization/qp.m: TeXified the help text.
 	* optimization/sqp.m: TeXified the help text.
 
-2007-06-16  S�ren Hauberg  <hauberg@gmail.com>
+2007-06-16  Søren Hauberg  <hauberg@gmail.com>
 
 	* plot/legend.m: Replace 'vargin' with 'varargin'.
 
@@ -10094,7 +10094,7 @@
 
 	* statistics/tests/wilcoxon_test.m: Error if N <= 25.
 
-2007-06-12  S�ren Hauberg  <soren@hauberg.org>
+2007-06-12  Søren Hauberg  <soren@hauberg.org>
 
 	* plot/fplot.m: If function is inline, vectorize it.
 
@@ -10121,7 +10121,7 @@
 	indexes into the installed package list indicating the packages to
 	load and the order to load them in to respect the dependencies.
 
-2007-06-03  S�ren Hauberg  <soren@hauberg.org>
+2007-06-03  Søren Hauberg  <soren@hauberg.org>
 
 	* plot/axes.m: Eliminate redundant else clause.
 
@@ -10233,7 +10233,7 @@
 	* plot/hbar.m: Remove.
 	* plot/barh.m: and move it here.
 
-2007-05-16  S�ren Hauberg  <soren@hauberg.org>
+2007-05-16  Søren Hauberg  <soren@hauberg.org>
 
 	* general/sub2ind.m, general/ind2sub.m: Doc fix.
 
@@ -10264,7 +10264,7 @@
 
 	* pkg/pkg.m: Mark loaded packages with "*".
 
-2007-05-13  S�ren Hauberg  <soren@hauberg.org>
+2007-05-13  Søren Hauberg  <soren@hauberg.org>
 
 	* miscellaneous/single.m: Doc fix.
 	Convert to double instead of returning argument unchanged.
@@ -10349,7 +10349,7 @@
 2007-04-24  John W. Eaton  <jwe@octave.org>
 
 	* io/beep.m: Fix cut and paste error.
-	From S�ren Hauberg  <soren@hauberg.org>.
+	From Søren Hauberg  <soren@hauberg.org>.
 
 2007-04-23  John W. Eaton  <jwe@octave.org>
 
@@ -10400,7 +10400,7 @@
 
 	* gethelp.cc (looks_like_octave_copyright): Use same logic as in
 	looks_like_copyright in src/help.cc.
-	From S�ren Hauberg <soren@hauberg.org>.
+	From Søren Hauberg <soren@hauberg.org>.
 
 	* plot/__go_draw_axes__.m: For log plots, omit zero values too.
 
@@ -10765,7 +10765,7 @@
 
 	* miscellaneous/cast.m: Use feval and strcmp with cell to check
 	arg instead of switch statement.
-	From S�ren Hauberg <soren@hauberg.org>.
+	From Søren Hauberg <soren@hauberg.org>.
 
 2007-03-12  John W. Eaton  <jwe@octave.org>
 
@@ -11438,7 +11438,7 @@
 
 	* polynomial/spline.m: Make DG a column instead of a row vector.
 
-2007-01-18  S�ren Hauberg  <hauberg@gmail.com>
+2007-01-18  Søren Hauberg  <hauberg@gmail.com>
 
 	* pkg/pkg.m (copy_files): Call write_INDEX with correct target
 	file name.
@@ -11460,11 +11460,11 @@
 	elfun/cscd.m, elfun/secd.m, elfun/sind.m, elfun/tand.m:
 	New files.
 
-2007-01-09  S�ren Hauberg  <hauberg@gmail.com>
+2007-01-09  Søren Hauberg  <hauberg@gmail.com>
 
 	* pkg/pkg.m: Allow filenames to contain glob patterns.
 
-2007-01-08  S�ren Hauberg  <hauberg@gmail.com>
+2007-01-08  Søren Hauberg  <hauberg@gmail.com>
 
 	* pkg/pkg.m: Use copyfile instead of calling system.  Use fullfile
 	instead of concatenating with "/".  Use mlock to ensure that
@@ -11474,7 +11474,7 @@
 
 	* miscellaneous/copyfile.m, miscellaneous/movefile.m:
 	Improve handling of file names containing globbing characters.
-	From S�ren Hauberg <hauberg@gmail.com>.
+	From Søren Hauberg <hauberg@gmail.com>.
 
 2007-01-05  John W. Eaton  <jwe@octave.org>
 
@@ -11486,7 +11486,7 @@
 	* sparse/spfun.m: Check for "function_handle" not "function handle".
 	* plot/fplot.m: Likewise.  Use isa instead of strcmp + class.
 
-2006-12-27  S�ren Hauberg  <hauberg@gmail.com>
+2006-12-27  Søren Hauberg  <hauberg@gmail.com>
 
 	* image/imshow.m: Strip NaNs from image.
 
@@ -11501,7 +11501,7 @@
 
 	* startup/inputrc: Include sequences for Windows.
 
-2006-12-06  S�ren Hauberg  <hauberg@gmail.com>
+2006-12-06  Søren Hauberg  <hauberg@gmail.com>
 
 	* pkg/pkg.m (unload_packages): New function.
 	(pkg): Handle unload action.
@@ -11578,7 +11578,7 @@
 	* image/image_viewer.m: Always return old values.  Check arguments.
 	* image/__img_gnuplot__.m: Rename from __img__m.
 
-2006-11-14  S�ren Hauberg  <soren@hauberg.org>
+2006-11-14  Søren Hauberg  <soren@hauberg.org>
 
 	* image/image_viewer.m: New function.
 	* image/__img_via_file__.m: New function.
@@ -11608,7 +11608,7 @@
 	* general/__isequal__.m: Avoid assignment of comma-separated lists
 	when comparing structs.
 
-2006-11-13  S�ren Hauberg  <hauberg@gmail.com>
+2006-11-13  Søren Hauberg  <hauberg@gmail.com>
 
 	* general/bicubic.m, general/cart2pol.m, general/cart2sph.m,
 	plot/contour.m, linear-algebra/cross.m, general/cumtrapz.m,
@@ -11622,11 +11622,11 @@
 
 	* plot/mesh.m: Use size_equal to compare dimensions.
 
-2006-11-13  S�ren Hauberg  <soren@hauberg.org>
+2006-11-13  Søren Hauberg  <soren@hauberg.org>
 
 	* plot/mesh.m: Simplify.  Set hidden3d for the plot.
 
-2006-11-11  S�ren Hauberg  <soren@hauberg.org>
+2006-11-11  Søren Hauberg  <soren@hauberg.org>
 
 	* miscellaneous/copyfile.m: Fix docs to match function.
 
@@ -11674,7 +11674,7 @@
 
 	* startup/main-rcfile: Conditionally set PAGER_FLAGS.
 
-2006-11-06  S�ren Hauberg  <soren@hauberg.org>
+2006-11-06  Søren Hauberg  <soren@hauberg.org>
 
 	* pkg/pkg.m (extract_pkg): No need to pass "dotexceptnewline"
 	option to regexp.
@@ -11720,7 +11720,7 @@
 	Daniel J Sebald <daniel.sebald@ieee.org> by way of
 	Quentin Spencer <qspencer@ieee.org>.
 
-2006-10-25  S�ren Hauberg  <soren@hauberg.org>
+2006-10-25  Søren Hauberg  <soren@hauberg.org>
 
 	* plot/__pltopt__.m: Update symbol marker id numbers for gnuplot 4.
 
@@ -12034,7 +12034,7 @@
 
 	* pkg/pkg.m: Use fullfile to concatenate directory and file names.
 
-2006-10-04  S�ren Hauberg  <soren@hauberg.org>
+2006-10-04  Søren Hauberg  <soren@hauberg.org>
 
 	* pkg/pkg.m: Update docs.  Handle prefix option.
 	Handle dependencies for load option.
@@ -12047,7 +12047,7 @@
 	* plot/__init_plot_vars__.m: New function.
 	* plot/__setup_plot__.m: Use __init_plot_vars__.
 
-2006-10-03  S�ren Hauberg  <soren@hauberg.org>
+2006-10-03  Søren Hauberg  <soren@hauberg.org>
 
 	* pkg/pkg.m: Avoid calling addpath with no args.
 
@@ -12103,7 +12103,7 @@
 
 	* deprecated/chisquare_pdf.m: Typo in documentation.
 
-2006-09-22  S�ren Hauberg  <soren@hauberg.org>
+2006-09-22  Søren Hauberg  <soren@hauberg.org>
 
 	* signal/filter2.m: Correct texinfo doc.
 
@@ -12182,7 +12182,7 @@
 	* image/saveimage.m: Use logical indexing instead of
 	indices computed by calling find on the logical index.
 
-2006-08-24  S�ren Hauberg  <soren@hauberg.org>
+2006-08-24  Søren Hauberg  <soren@hauberg.org>
 
 	* miscellaneous/bincoeff.m, specfun/factorial.m:
 	Use logical indexing instead of indices computed by calling find
@@ -12210,7 +12210,7 @@
 	PKG_ADD directives and append user supplied PKG_ADD.
 	(pkg): Call create_pkgadd after copying files.
 
-2006-08-21  S�ren Hauberg  <soren@hauberg.org>
+2006-08-21  Søren Hauberg  <soren@hauberg.org>
 
 	* pkg/pkg.m: Handle multiple packages in a single file.
 	Insert directory separator between OCTAVE_HOME and rest of package
@@ -12229,7 +12229,7 @@
 
 	* audio/wavread.m: Fix calculation of sample count.
 
-2006-08-14  S�ren Hauberg  <soren@hauberg.org>
+2006-08-14  Søren Hauberg  <soren@hauberg.org>
 
 	* image/imshow.m: New Matlab-compatible version.
 
@@ -12246,7 +12246,7 @@
 	* sparse/spy.m, control/base/bode.m, control/base/__stepimp__.m,
 	signal/freqz_plot.m: Adapt to new automatic_replot definition.
 
-2006-08-14  S�ren Hauberg  <soren@hauberg.org>
+2006-08-14  Søren Hauberg  <soren@hauberg.org>
 
 	* pkg/pkg.m: Don't pass function name to print_usage.
 	Use addpath and rmpath instead of manipulating LOADPATH.
@@ -12377,7 +12377,7 @@
 	* tar.m, untar.m, unzip.m: Adapt to Octave coding style.
 	* tar.m, untar.m: Only tar; don't compress or uncompress.
 
-2006-05-10  S�ren Hauberg  <hauberg@gmail.com>
+2006-05-10  Søren Hauberg  <hauberg@gmail.com>
 
 	* tar.m, untar.m, unzip.m: New files.
 
@@ -12594,7 +12594,7 @@
 2006-03-15  John W. Eaton  <jwe@octave.org>
 
 	* miscellaneous/doc.m: New file.
-	From S�ren Hauberg <soren@hauberg.org>.
+	From Søren Hauberg <soren@hauberg.org>.
 
 2006-03-15  Keith Goodman  <kwgoodman@gmail.com>
 
@@ -13382,7 +13382,7 @@
 	* optimization/glpk.m, optimization/glpkparams.m,
 	optimization/glpktest1, optimization/glpktest2: New files.
 
-2005-03-16  S�ren Hauberg  <soren@hauberg.org>
+2005-03-16  Søren Hauberg  <soren@hauberg.org>
 
 	* strings/split.m: Quick return for empty second arg.
 	Improve warning for multi-line strings.
--- a/etc/OLD-ChangeLogs/src-ChangeLog
+++ b/etc/OLD-ChangeLogs/src-ChangeLog
@@ -3027,7 +3027,7 @@
 	the "eng" argument.
 	(Fformat): Document the new engineering format.
 
-2010-07-04  Soren Hauberg  <hauberg@gmail.com>
+2010-07-04  Søren Hauberg  <hauberg@gmail.com>
 
 	* DLD_FUNCTIONS/__magick_read__.cc: restore locale after
 	GraphicsMagick initialisation.
@@ -4226,7 +4226,7 @@
 	* load-path.cc (in_path_list): New helper function.
 	(add_to_fcn_map): Use it here.
 
-2010-02-18  S�ren Hauberg  <hauberg@gmail.com>
+2010-02-18  Søren Hauberg  <hauberg@gmail.com>
 
 	* DLD-FUNCTIONS/__magick_read__.cc (__magick_finfo__):
 	Handle multiple frames in a single image file.
@@ -7564,7 +7564,7 @@
 	zooming methods.
 	(help_text): Update to reflect new mouse/key bindings.
 
-2009-07-23  Soren Hauberg  <hauberg@gmail.com>
+2009-07-23  Søren Hauberg  <hauberg@gmail.com>
 
 	* graphics.cc (axes::properties::zoom_about_point,
 	axes::properties::translate_view): New functions.
@@ -10246,12 +10246,12 @@
 
 	* DLD-FUNCTIONS/eigs.cc: eigs.cc: skip tests if ARPACK is missing.
 
-2009-01-25  S�ren Hauberg  <hauberg@gmail.com>
+2009-01-25  Søren Hauberg  <hauberg@gmail.com>
 
 	* help.cc (do_get_help_text, raw_help_from_symbol_table): new output to
 	flag the a function is found but not documented.
 
-2009-01-25  S�ren Hauberg  <hauberg@gmail.com>
+2009-01-25  Søren Hauberg  <hauberg@gmail.com>
 
 	* help.cc (raw_help_from_file): No longer search for files called
 	'Contents.m', as this is moved to 'script/help.m'.
@@ -10302,7 +10302,7 @@
 	* do_which (const std::string&):
 	Call do_which (const std::string&, std::string&) to do the work.
 
-2009-01-22  S�ren Hauberg  <hauberg@gmail.com>
+2009-01-22  Søren Hauberg  <hauberg@gmail.com>
 
 	* defun-int.h (print_usage): No longer mark as deprecated.
 	* defun.cc (print_usage): Simply call feval to execute print_usage.m.
@@ -10452,12 +10452,12 @@
 	* ov-struct.cc: Ditto.
 	* pt-decl.h: Ditto.
 
-2009-01-15  S�ren Hauberg  <hauberg@gmail.com>
+2009-01-15  Søren Hauberg  <hauberg@gmail.com>
 
 	* DLD-FUNCTIONS/__magick_read__.cc (encode_uint_image):
 	Initialize bitdepth.
 
-2009-01-14  S�ren Hauberg  <hauberg@gmail.com>
+2009-01-14  Søren Hauberg  <hauberg@gmail.com>
 
 	* DLD-FUNCTIONS/betainc.cc, DLD-FUNCTIONS/chol.cc,
 	DLD-FUNCTIONS/daspk.cc, DLD-FUNCTIONS/dasrt.cc,
@@ -11429,7 +11429,7 @@
 	* symtab.cc (symbol_table::do_find): Don't set evaluated_args and
 	args_evaluated here, prior to call to symbol_table::fcn_info::find.
 
-2008-09-24  S�ren Hauberg  <hauberg@gmail.com>
+2008-09-24  Søren Hauberg  <hauberg@gmail.com>
 
 	* DLD-FUNCTIONS/__magick_read__.cc (magick_to_octave_value): New
 	template function with specializations for various
@@ -11873,7 +11873,7 @@
 	Fix typo in warning identifier.
 	(make_unimplemented_options): Use CamelCase names here.
 
-2008-08-06  S�ren Hauberg  <hauberg@gmail.com>
+2008-08-06  Søren Hauberg  <hauberg@gmail.com>
 
 	* error.cc (Ferror): Update format of error messages in exmple.
 	* parse.y: (Feval): Likewise.
@@ -14465,7 +14465,7 @@
 	* DLD-FUNCTIONS/__convn__.cc (convn): Use traits class and
 	typedefs to allow all types to be deduced from argument types.
 
-2008-03-27  S�ren Hauberg  <hauberg@gmail.com>
+2008-03-27  Søren Hauberg  <hauberg@gmail.com>
 
 	* DLD-FUNCTIONS/__convn__.cc (Fconvn): Allow convolving real data with
 	complex data.
@@ -14515,7 +14515,7 @@
 	DLD-FUNCTIONS/qr.cc, DLD-FUNCTIONS/symrcm.cc, file-io.cc):
 	Texinfo fixes.
 
-2008-03-26  S�ren Hauberg  <hauberg@gmail.com>
+2008-03-26  Søren Hauberg  <hauberg@gmail.com>
 
 	* DLD-FUNCTIONS/__convn__.cc (Fconvn):
 	Call complex_array_value to extract N-d array.
@@ -14525,7 +14525,7 @@
 	* ov-base-sparse.cc (octave_base_sparse<T>::print_raw):
 	Also display percentage of elements that are nonzero.
 
-2008-03-25  S�ren Hauberg  <hauberg@gmail.com>
+2008-03-25  Søren Hauberg  <hauberg@gmail.com>
 
 	* DLD-FUNCTIONS/__convn__.cc: New file.
 	* Makefile.in: Add __convn__.cc
@@ -16805,7 +16805,7 @@
 
 	* DLD-FUNCTIONS/__qp__.cc (qp): Fix check for Wact(j).
 
-2007-10-15  S�ren Hauberg  <hauberg@gmail.com>
+2007-10-15  Søren Hauberg  <hauberg@gmail.com>
 
 	* error.cc (Ferror): Make text fit on pages when using smallbook.
 	* load-save.cc (Fsave_header_format_string): Ditto.
@@ -17533,7 +17533,7 @@
 	(octave_stream_list::do_insert, octave_steam_list::insert):
 	Remove const qualifier of argument.
 
-2007-06-18  S�ren Hauberg  <hauberg@gmail.com>
+2007-06-18  Søren Hauberg  <hauberg@gmail.com>
 
 	* DLD-FUNCTIONS/__lin_interpn__.cc: Replace octave_NaN with octave_NA.
 
@@ -17748,7 +17748,7 @@
 	arguments.
 	(Fdbclar): ditto. Eliminate extraneous debugging messages.
 
-2007-05-21  S�ren Hauberg  <hauberg@gmail.com>
+2007-05-21  Søren Hauberg  <hauberg@gmail.com>
 
 	* load-path.cc (Fpath, Frehash): Replace "LOADPATH" with "load
 	path" in doc strings.
@@ -17769,7 +17769,7 @@
 	(Octave_map::empty): Delete.
 	Change all uses of empty to check nfields () == 0 instead.
 
-2007-05-21  S�ren Hauberg  <soren@hauberg.org>
+2007-05-21  Søren Hauberg  <soren@hauberg.org>
 
 	* help.cc (Fautoload): Doc fix.
 	* variables.cc (Fiscommand): Doc fix.
@@ -17778,7 +17778,7 @@
 
 	* ov-fcn-inline.cc (Fvectorize): Doc fix.
 
-2007-05-16  S�ren Hauberg  <soren@hauberg.org>
+2007-05-16  Søren Hauberg  <soren@hauberg.org>
 
 	* ov.cc (Fsubsref, Fsubsasgn): Doc fix.
 
@@ -17846,14 +17846,14 @@
 
 	* DLD-FUNCTIONS/fft.cc (do_fft): Handle empty matrices.  New tests.
 
-2007-05-14  S�ren Hauberg  <soren@hauberg.org>
+2007-05-14  Søren Hauberg  <soren@hauberg.org>
 
 	* toplev.cc (Fatexit): Simplify example in doc string.
 	* help.cc (Flookfor): Doc fix.
 	* DLD-FUNCTIONS/cellfun.cc (Fcellfun):
 	Reformat to avoid long lines in doc string example.
 
-2007-05-13  S�ren Hauberg  <soren@hauberg.org>
+2007-05-13  Søren Hauberg  <soren@hauberg.org>
 
 	* toplev.cc (Fquit): Doc fix.
 	* help.cc (Fhelp): Doc fix.
@@ -17934,7 +17934,7 @@
 	* ov-usr-fcn.cc (octave_user_function::do_multi_index_op):
 	Only deal with varargout if ret_list->takes_varargs () is true.
 
-2007-04-26  S�ren Hauberg  <soren@hauberg.org>
+2007-04-26  Søren Hauberg  <soren@hauberg.org>
 
 	* DLD-FUNCTIONS/urlwrite.cc: Doc fix.
 
@@ -17963,7 +17963,7 @@
 	(color_property::validate): Use rgba.
 	(color_property::c2rgba): New function.
 
-2007-04-23  S�ren Hauberg  <soren@hauberg.org>
+2007-04-23  Søren Hauberg  <soren@hauberg.org>
 
 	* data.cc (Fsize_equal): Allow more than two arguments.
 
@@ -19366,7 +19366,7 @@
 	New functions.
 	* ov-base-int.h: Provide decls.
 
-2006-09-15  S�ren Hauberg  <soren@hauberg.org>.
+2006-09-15  Søren Hauberg  <soren@hauberg.org>.
 
 	* data.cc (Fsize): If nargout > ndims, fill with 1.
 
@@ -21472,7 +21472,7 @@
 	* help.cc (help_from_info): Simplify.
 	(try_info): Use feval to call doc instead of executing info program.
 	(additional_help_message): Point users to doc instead of help -i.
-	From S�ren Hauberg <soren@hauberg.org>.
+	From Søren Hauberg <soren@hauberg.org>.
 
 	* toplev.cc (Fsystem): Return output if nargout > 1, not 0.
 
@@ -22319,7 +22319,7 @@
 
 2005-07-18  John W. Eaton  <jwe@octave.org>
 
-	* strfns.cc (Fstrcmp): New function from S�ren Hauberg
+	* strfns.cc (Fstrcmp): New function from Søren Hauberg
 	<soren@hauberg.org> and Tom Holroyd <tomh@kurage.nimh.nih.gov>.
 	Adapt to Octave conventions.
 
--- a/etc/OLD-ChangeLogs/test-ChangeLog
+++ b/etc/OLD-ChangeLogs/test-ChangeLog
@@ -285,7 +285,7 @@
 
 	* test_struct.m: Add struct array tests.
 
-2009-01-23  Søren Hauberg  <hauberg@gmail.com>
+2009-01-23  Søren Hauberg  <hauberg@gmail.com>
 
 	* test_prefer.m: Update to match new API of the 'type' function.
 
--- a/etc/README.MacOS
+++ b/etc/README.MacOS
@@ -270,8 +270,8 @@
 After installing each of the dependencies, the sources are compiled by
 setting the proper environment variables and then following the standard build
 sequence.  The following is an example set of variables for a 32-bit build
-using gcc-4.2.  When building from the sources obtained from the mercurial
-archive, ./autogen.sh must be run prior to ./configure.
+using gcc-4.2.  When building from the sources obtained from the Mercurial
+archive, ./bootstrap must be run prior to ./configure.
 
   export FINK_PREFIX="/sw"
   export PREFIX="/usr/local/bin"
@@ -385,7 +385,7 @@
 Octave may now be built from a local mercurial archive by typing the commands
 below (these assume gcc-4.4 is installed by macports).
 
-  ./autogen.sh
+  ./bootstrap
   export PREFIX=/opt/local
   export CC=/opt/local/bin/gcc-mp-4.4
   export CXX=/opt/local/bin/g++-mp-4.4
--- a/etc/README.MinGW
+++ b/etc/README.MinGW
@@ -94,7 +94,7 @@
   http://thread.gmane.org/gmane.comp.gnu.octave.bugs/12361/focus=12404
 
   To build development sources from the Mercurial repository you must run
-  'autogen.sh' (bootstrap) before running configure and make.  This requires
+  bootstrap before running configure and make.  This requires
   that automake and autoconf tools be installed.
 
 
deleted file mode 100644
--- a/etc/README.devel
+++ /dev/null
@@ -1,81 +0,0 @@
-This directory contains development releases of Octave.
-
-If you want a stable, well-tested version of Octave, you should be
-looking at ftp://ftp.gnu.org/gnu/octave.
-
-Development releases are provided for people who want to help test,
-debug, and improve Octave.  Very little testing is done before making
-the development releases and they may even be made when Octave is in
-an inconsistent state.  It is possible that you will encounter a
-very obvious bug, such as a failure to compile on *any* machine.  It is
-likely that such bugs will be fixed by the next development release,
-so it really isn't necessary to report them unless they persist over
-more than one release.
-
-Please DO report other bugs in the development releases as soon as you
-find them.  Bugs should be reported to the bug tracker at
-'http://bugs.octave.org'.  Please read read the bug reporting
-guidelines (http://www.octave.org/bugs.html) before submitting an item.
-
-If you have a fix for a bug, or an enhancement to submit, send your
-patch to maintainers@octave.org or submit it to the patch
-tracker at 'http://savannah.gnu.org/patch/?group=octave'. 
-
-By adhering to the following guidelines you can minimize the work that
-Octave maintainers need to do to apply your patch.  Maintaining Octave
-is a lot of work in the best of circumstances, and we can't keep up
-unless you do your best to help.
-
-   * Send an explanation with your changes of what problem they fix or
-     what improvement they bring about.  For a bug fix, just include a
-     copy of the bug report, and explain why the change fixes the bug.
-
-   * Always include a proper bug report for the problem you think you
-     have fixed.  We need to convince ourselves that the change is
-     right before installing it.  Even if it is right, we might have
-     trouble judging it if we don't have a way to reproduce the problem.
-
-   * Include all the comments that are appropriate to help people
-     reading the source in the future understand why this change was
-     needed.
-
-   * Don't mix together changes made for different reasons.  Send them
-     _individually_.
-
-     If you make two changes for separate reasons, then we might not
-     want to install them both.  We might want to install just one.
-
-   * Use `diff -c' to make your diffs.  Diffs without context are hard
-     for us to install reliably.  More than that, they make it hard for
-     us to study the diffs to decide whether we want to install them.
-     Unified diff format is better than contextless diffs, but not as
-     easy to read as `-c' format.
-
-     If you have GNU diff, use `diff -cp', which shows the name of the
-     function that each change occurs in.
-
-   * Write the change log entries for your changes.
-
-     Read the `ChangeLog' file to see what sorts of information to put
-     in, and to learn the style that we use.  The purpose of the
-     change log is to show people where to find what was changed.  So
-     you need to be specific about what functions you changed; in
-     large functions, it's often helpful to indicate where within the
-     function the change was made.
-
-     On the other hand, once you have shown people where to find the
-     change, you need not explain its purpose.  Thus, if you add a new
-     function, all you need to say about it is that it is new.  If you
-     feel that the purpose needs explaining, it probably does--but the
-     explanation will be much more useful if you put it in comments in
-     the code.
-
-     If you would like your name to appear in the header line for who
-     made the change, send us the header line.
-
-If you would like to be on the very sharpest part of the bleeding
-edge, you can now use Mercurial to access Octave's current development
-sources.  Instructions for checking out a copy are available on the
-web at http://www.octave.org/download.html.
-
-Last updated: Sat Jan 22 21:26:18 PST 2011
deleted file mode 100644
--- a/etc/README.ftp
+++ /dev/null
@@ -1,38 +0,0 @@
-This directory contains the source for Octave, a high-level interactive
-language for solving numerical problems.  See the file README for more general
-information, and the file NEWS for a list of recent changes.
-
-Binary distributions:
---------------------
-
-Octave binaries are not distributed from this site.
-
-Packaged versions of Octave for various GNU/Linux systems are available
-with the major GNU/Linux distributions (Debian, Ubuntu, Red Hat, SUSE, etc.).
-
-Binary distributions of Octave for Mac OS X are available from both Fink
-and MacPorts.
-
-  http://www.finkproject.com
-  http://www.macports.org/
-
-The file README.Windows provides instructions for installing Octave on
-Windows systems.
-
-A note about .gz files:
-----------------------
-
-Files with names ending in `.gz' have been compressed with `gzip'.
-
-Unlike the compress utility, gzip is free of any known software
-patents and tends to compress better anyway.  Gzip can uncompress
-`compress'-compressed files too, so you can install it as "uncompress"
-and use it to handle both types of files.
-
-The gzip program is available in the directory /pub/gnu in shar, tar,
-or gzipped tar format (for those who already have a prior version of
-gzip and want faster data transmission).  It works on virtually every
-unix system, MSDOS, OS/2, and VMS.
-
-
-Last updated: Thu Jan 20 10:14:49 PST 2011
deleted file mode 100644
--- a/etc/README.mirrors
+++ /dev/null
@@ -1,12 +0,0 @@
-If you have trouble transferring Octave from this site, you might try
-one of those listed below.  They mirror the /pub/octave directory on
-ftp.octave.org
-
-FTP:
-
-  site                          directory
-  ----                          ---------
-  ftp.u-aizu.ac.jp              /pub/SciEng/numanal/Octave
-  mirrors.fe.up.pt              /pub/octave
-
-Last updated: Mon Jan 10 21:26:17 PST 2011
deleted file mode 100644
--- a/etc/README.snapshots
+++ /dev/null
@@ -1,161 +0,0 @@
-Octave Snapshots -- general info
-
-Snapshots are an "image" of the main Octave development tree, captured
-at a particular random instant in time.  When you use the snapshots,
-you should be able to maintain a local copy of Octave that is
-reasonably close to the official source tree used by the Octave
-maintainers.
-
-The primary purpose of providing snapshots is to widen the group of
-motivated developers that would like to help test, debug, and enhance
-Octave, by providing you with access to the "latest and greatest"
-source.  This has several advantages, and several disadvantages.
-
-    First the advantages:
-
-    o	Once we have a large base of motivated testers using the
-	snapshots, this should provide good coverage across all
-	currently supported Octave hosts and targets.  If a new bug is
-	introduced in Octave due to fixing another bug or ongoing
-	development, it should become obvious much more quickly and
-	get fixed before the next general net release.  This should
-	help to reduce the chances of Octave being released to the
-	general public with a major bug that went unnoticed during the
-	release cycle testing because they are machine dependent.  We
-	hope to greatly improve Octave's stability and reliability by
-	involving more people and more execution environments in the
-	prerelease testing.
-
-    o	With access to the latest source, any diffs that you send to fix
-	bugs or add new features should be much easier for the Octave
-	maintainers to merge into the official source base (after
-	suitable review of course).  This encourages us to merge your
-	changes quicker, while they are still "fresh".
-
-    o	Once your diffs are merged, you can obtain a new copy of Octave
-	containing your changes almost immediately.  Thus you do not
-	have to maintain local copies of your changes for any longer
-	than it takes to get them merged into the official source
-	base.  This encourages you to send in changes quicker.
-
-    And the disadvantages:
-
-    o	The snapshot you get will be largely untested and of unknown
-	quality.  It may fail to configure or compile.  It may have
-	serious bugs.  You should always keep a copy of the last known
-	working version before updating to the current snapshot, or at
-	least be able to regenerate a working version if the latest
-	snapshot is unusable in your environment for some reason.
-
-	If a production version of Octave has a bug and a snapshot has
-	the fix, and you care about stability, you should put only the
-	fix for that particular problem into your production version.
-	Of course, if you are eager to test Octave, you can use the
-	snapshot versions in your daily work, but users who have not
-	been consulted about whether they feel like testing Octave should
-	generally have something which is at least as bug free as the
-	last released version.
-
-    o	Providing timely response to your questions, bug reports, and
-	submitted patches will require the Octave developers to
-	allocate time from an already thin time budget.  Please try to
-	help us make this time as productive as possible.  See the
-	section below about how to submit changes.
-
-
-How to get the snapshots
-------------------------
-
-The current plan is to provide a full snapshot every week or so.  For
-now, diffs from previous versions will not be available.  The files
-will be available via anonymous ftp from ftp.octave.org, in the
-directory /private/octave in the form of a tar files compressed with
-GNU gzip.  You can ftp gzip from ftp.octave.org in the directory
-/pub/gnu.
-
-Even though the snapshots are available in a public place, we ask that
-recipients not widely publicize the availability of the snapshots.
-The motivation for this request is not to hoard them, but to avoid the
-situation where the general Octave user base naively attempts to use
-the snapshots, has trouble with them, complains publicly, and the
-reputation of Octave declines because of a perception of instability
-or lack of quality control.
-
-
-Octave test suite
------------------
-
-A test suite is distributed as an integral part of the snapshots.
-However, to use it you will need to get a copy of the dejagnu testing
-framework.  Snapshots of dejagnu are available alongside the Octave
-snapshots, using the same naming conventions as the Octave snapshots.
-Once you have installed the dejagnu framework, a simple "make check"
-in the Octave directory should be sufficient to run the tests.
-
-Note that the test suite is still quite limited.  The test framework
-itself might not install on your system if you have an environment
-that is not similar to one that the Octave developers already use.
-The tests themselves only cover a small portion of Octave features,
-and what tests do exist for a feature are not exhaustive.  New tests
-are welcomed.
-
-
-Bug reports
------------
-
-Send bug reports to maintainers@octave.org.
-
-Note that since no testing is done on the snapshots, and snapshots may
-even be made when Octave is in an inconsistent state, it may not be
-unusual for an occasional snapshot to have a very obvious bug, such as
-failure to compile on *any* machine.  It is likely that such bugs will
-be fixed by the next snapshot, so it really isn't necessary to report
-them unless they persist over more than one snapshot.
-
-Missing files should always be reported, since they usually mean there
-is a problem with the snapshot-generating process and we won't know
-about them unless someone tells us.
-
-Bugs which are non-obvious, such as failure to compile on only a
-specific machine, a new machine dependent or obscure bug (particularly
-one not detected by the testsuite), etc. should be reported when you
-discover them, or have a suggested patch to fix them.
-
-
-FORMAT FOR PATCHES
-------------------
-
-If you have a fix for a bug, or an enhancement to submit, send your
-patch to maintainers@octave.org.  Here are some simple guidelines for
-submitting patches:
-
-    o	Use "context diffs" for patches.  A typical command for
-	generating context diffs is "diff -rc octave-old octave-new".
-
-    o	Use the "minimalist approach" for patches.  That is, each patch
-	should address only one particular bug, new feature, etc.  Do
-	not save up many unrelated changes and submit them all in one
-	big patch, since in general, the larger the patch the more
-	difficult it is for us to decide if the patch is either
-	correct or desirable.  And if we find something about the
-	patch that needs to be corrected before it can be installed,
-	we would have to reject the entire patch, which might contain
-	changes which otherwise would be accepted if submitted
-	separately.
-
-    o	Submit a sample ChangeLog entry with your patch.  See the
-	existing Octave ChangeLog for examples of what a ChangeLog
-	entry should look like.  The emacs command ^X4A will create a
-	ChangeLog entry header for you.
-
-
-Thanks,
-
-John W. Eaton
-jwe@octave.org
-
-Wed, 31 Oct 2007 16:31:54 EDT
-
-This file was adapted from a similar document written by Fred Fish and
-used by the GDB developers.
-
--- a/examples/@FIRfilter/display.m
+++ b/examples/@FIRfilter/display.m
@@ -1,6 +1,6 @@
 function display (f)
 
-  display(f.polynomial);
+  display (f.polynomial);
 
 endfunction
 
--- a/examples/@FIRfilter/subsref.m
+++ b/examples/@FIRfilter/subsref.m
@@ -2,7 +2,7 @@
   switch x.type
     case "()"
       n = f.polynomial;
-      out = filter(n.poly, 1, x.subs{1});
+      out = filter (n.poly, 1, x.subs{1});
     case "."
       fld = x.subs;
       if (strcmp (fld, "polynomial"))
--- a/examples/@polynomial/display.m
+++ b/examples/@polynomial/display.m
@@ -1,7 +1,7 @@
 function display (p)
   a = p.poly;
   first = true;
-  fprintf("%s =", inputname(1));
+  fprintf ("%s =", inputname (1));
   for i = 1 : length (a);
     if (a(i) != 0)
       if (first)
@@ -26,7 +26,7 @@
     endif
   endfor
   if (first)
-    fprintf(" 0");
+    fprintf (" 0");
   endif
-  fprintf("\n");
+  fprintf ("\n");
 endfunction
--- a/examples/@polynomial/mtimes.m
+++ b/examples/@polynomial/mtimes.m
@@ -1,3 +1,3 @@
 function y = mtimes (a, b)
-  y = polynomial (conv (double(a),double(b)));
-endfunction
\ No newline at end of file
+  y = polynomial (conv (double (a), double (b)));
+endfunction
--- a/examples/@polynomial/plot.m
+++ b/examples/@polynomial/plot.m
@@ -1,10 +1,10 @@
-function h = plot(p, varargin)
+function h = plot (p, varargin)
   n = 128;
   rmax = max (abs (roots (p.poly)));
   x = [0 : (n - 1)] / (n - 1) * 2.2 * rmax - 1.1 * rmax;
   if (nargout > 0)
-    h = plot(x, p(x), varargin{:});
+    h = plot (x, p(x), varargin{:});
   else
-    plot(x, p(x), varargin{:});
+    plot (x, p(x), varargin{:});
   endif
-endfunction
\ No newline at end of file
+endfunction
--- a/examples/@polynomial/polyval.m
+++ b/examples/@polynomial/polyval.m
@@ -1,7 +1,7 @@
 function [y, dy] = polyval (p, varargin)
   if (nargout == 2)
-    [y, dy] = polyval (fliplr(p.poly), varargin{:});
+    [y, dy] = polyval (fliplr (p.poly), varargin{:});
   else
-    y = polyval (fliplr(p.poly), varargin{:});
+    y = polyval (fliplr (p.poly), varargin{:});
   endif
 endfunction
--- a/examples/Makefile.am
+++ b/examples/Makefile.am
@@ -1,4 +1,4 @@
-# Makefile for octave's examples directory
+# Makefile for Octave's examples directory
 #
 # Copyright (C) 1996-2012 John W. Eaton
 #
--- a/examples/embedded.cc
+++ b/examples/embedded.cc
@@ -16,7 +16,7 @@
   octave_value_list in;
 
   for (octave_idx_type i = 0; i < n; i++)  
-    in(i) = octave_value (5 * (i + 1));
+    in(i) = octave_value (5 * (i + 2));
   
   octave_value_list out = feval ("gcd", in, 1);
 
--- a/examples/fortdemo.cc
+++ b/examples/fortdemo.cc
@@ -12,7 +12,7 @@
 DEFUN_DLD (fortdemo , args , , "Fortran Demo.")
 {
   octave_value_list retval;
-  int nargin = args.length();
+  int nargin = args.length ();
   if (nargin != 1)
     print_usage ();
   else
--- a/examples/funcdemo.cc
+++ b/examples/funcdemo.cc
@@ -3,7 +3,7 @@
 
 DEFUN_DLD (funcdemo, args, nargout, "Function Demo")
 {
-  int nargin = args.length();
+  int nargin = args.length ();
   octave_value_list retval;
 
   if (nargin < 2)
--- a/examples/hello.cc
+++ b/examples/hello.cc
@@ -89,9 +89,9 @@
 
   for (int i = 0; i < nargin; i++)
     {
-      octave_value tmp = args (i);
+      octave_value tmp = args(i);
       tmp.print (octave_stdout);
-      retval (nargin-i-1) = tmp;
+      retval(nargin-i-1) = tmp;
     }
 
   return retval;
--- a/examples/myprop.c
+++ b/examples/myprop.c
@@ -8,7 +8,7 @@
 
   if (nrhs < 2 || nrhs > 3)
     mexErrMsgTxt ("incorrect number of arguments");
-  if (!mxIsDouble(prhs[0]))
+  if (!mxIsDouble (prhs[0]))
     mexErrMsgTxt ("handle expected to be a double scalar");
   if (!mxIsChar (prhs[1]))
     mexErrMsgTxt ("expected property to be a string");
--- a/examples/mysparse.c
+++ b/examples/mysparse.c
@@ -56,7 +56,7 @@
     }
   else if (mxIsLogical (prhs[0]))
     {
-      bool *pbr, *pbr2;
+      mxLogical *pbr, *pbr2;
       mexPrintf ("Matrix is %d-by-%d logical",
                  " sparse matrix", m, n);
       mexPrintf (" with %d elements\n", nz);
--- a/examples/paramdemo.cc
+++ b/examples/paramdemo.cc
@@ -7,23 +7,23 @@
   octave_value retval;
 
   if (nargin != 1)
-    print_usage();
+    print_usage ();
   else if (nargout != 0)
     error ("paramdemo: function has no output arguments");
   else
     {
-      NDArray m = args(0).array_value();
+      NDArray m = args(0).array_value ();
       double min_val = -10.0;
       double max_val = 10.0;
       octave_stdout << "Properties of input array:\n";
       if (m.any_element_is_negative ())
         octave_stdout << "  includes negative values\n";
-      if (m.any_element_is_inf_or_nan())
+      if (m.any_element_is_inf_or_nan ())
         octave_stdout << "  includes Inf or NaN values\n";
-      if (m.any_element_not_one_or_zero())
+      if (m.any_element_not_one_or_zero ())
         octave_stdout <<
           "  includes other values than 1 and 0\n";
-      if (m.all_elements_are_int_or_inf_or_nan())
+      if (m.all_elements_are_int_or_inf_or_nan ())
         octave_stdout <<
           "  includes only int, Inf or NaN values\n";
       if (m.all_integers (min_val, max_val))
--- a/examples/stringdemo.cc
+++ b/examples/stringdemo.cc
@@ -2,7 +2,7 @@
 
 DEFUN_DLD (stringdemo, args, , "String Demo")
 {
-  int nargin = args.length();
+  int nargin = args.length ();
   octave_value_list retval;
 
   if (nargin != 1)
@@ -18,13 +18,13 @@
           else
             retval(1) = octave_value (ch, true, '\'');
 
-          octave_idx_type nr = ch.rows();
+          octave_idx_type nr = ch.rows ();
           for (octave_idx_type i = 0; i < nr / 2; i++)
             {
               std::string tmp = ch.row_as_string (i);
-              ch.insert (ch.row_as_string(nr-i-1).c_str(),
+              ch.insert (ch.row_as_string (nr-i-1).c_str (),
                          i, 0);
-              ch.insert (tmp.c_str(), nr-i-1, 0);
+              ch.insert (tmp.c_str (), nr-i-1, 0);
             }
           retval(0) = octave_value (ch, true);
         }
--- a/examples/unwinddemo.cc
+++ b/examples/unwinddemo.cc
@@ -9,7 +9,7 @@
 
 DEFUN_DLD (unwinddemo, args, nargout, "Unwind Demo")
 {
-  int nargin = args.length();
+  int nargin = args.length ();
   octave_value retval;
   if (nargin < 2)
     print_usage ();
@@ -22,7 +22,7 @@
         {
           unwind_protect::begin_frame ("Funwinddemo");
           unwind_protect_ptr (current_liboctave_warning_handler);
-          set_liboctave_warning_handler(err_hand);
+          set_liboctave_warning_handler (err_hand);
           retval = octave_value (quotient (a, b));
           unwind_protect::run_frame ("Funwinddemo");
         }
deleted file mode 100644
--- a/libcruft/link-deps.mk
+++ /dev/null
@@ -1,30 +0,0 @@
-## The following libraries may be needed to satisfy gnulib dependencies:
-##
-##   $(COPYSIGN_LIBM)
-##   $(FLOOR_LIBM)
-##   $(GETHOSTNAME_LIB)
-##   $(LIBSOCKET)
-##   $(LIB_NANOSLEEP)
-##   $(LTLIBINTL)
-##   $(ROUNDF_LIBM)
-##   $(ROUND_LIBM)
-##   $(TRUNCF_LIBM)
-##   $(TRUNC_LIBM)
-
-LIBCRUFT_LINK_DEPS = \
-  $(COPYSIGN_LIBM) \
-  $(FLOOR_LIBM) \
-  $(GETHOSTNAME_LIB) \
-  $(LIBSOCKET) \
-  $(LIB_NANOSLEEP) \
-  $(LTLIBINTL) \
-  $(ROUNDF_LIBM) \
-  $(ROUND_LIBM) \
-  $(TRUNCF_LIBM) \
-  $(TRUNC_LIBM) \
-  $(LAPACK_LIBS) \
-  $(BLAS_LIBS) \
-  $(FLIBS) \
-  $(LIBS)
-
-LIBCRUFT_LINK_OPTS =
deleted file mode 100644
--- a/libgnu/Makefile.am
+++ /dev/null
@@ -1,21 +0,0 @@
-# Copyright (C) 2009 John W. Eaton
-#
-# 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/>.
-
-# Simply include gnulib.mk, at least for now.
-
-include gnulib.mk
new file mode 100644
--- /dev/null
+++ b/libgui/Makefile.am
@@ -0,0 +1,112 @@
+# Makefile for Octave's libgui directory
+#
+# Copyright (C) 2012 John W. Eaton
+#
+# 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/>.
+
+include $(top_srcdir)/build-aux/common.mk
+
+AUTOMAKE_OPTIONS = subdir-objects
+
+MOC_CPPFLAGS =
+
+octlib_LTLIBRARIES = liboctgui.la
+
+TRANSLATIONS = \
+  languages/be_BY.ts \
+  languages/de_DE.ts \
+  languages/en_US.ts \
+  languages/es_ES.ts \
+  languages/nl_NL.ts \
+  languages/pt_BR.ts \
+  languages/ru_RU.ts \
+  languages/uk_UA.ts
+
+LOCALES = $(patsubst languages/%.ts, languages/%.qm, $(TRANSLATIONS))
+
+EXTRA_DIST = default-qt-settings.in $(TRANSLATIONS)
+CLEANFILES =
+
+BUILT_SOURCES =
+
+noinst_HEADERS =
+
+noinst_LTLIBRARIES =
+
+include src/module.mk
+include qterminal-module.mk
+
+## liboctgui merely collects a bunch of compiled convenience libraries.
+## It has no source code itself.
+liboctgui_la_SOURCES = 
+
+include link-deps.mk
+
+# Dummy C++ source to force C++ linking.
+nodist_EXTRA_liboctgui_la_SOURCES = dummy.cc
+
+liboctgui_la_LIBADD = \
+  qterminal/libqterminal.la \
+  src/libgui-src.la \
+  $(top_builddir)/libinterp/liboctinterp.la \
+  $(top_builddir)/liboctave/liboctave.la \
+  $(LIBOCTGUI_LINK_DEPS)
+
+# Increment these as needed and according to the rules in the libtool manual:
+liboctgui_current = 0
+liboctgui_revision = 0
+liboctgui_age = 0
+
+liboctgui_version_info = $(liboctgui_current):$(liboctgui_revision):$(liboctgui_age)
+
+liboctgui_la_LDFLAGS = \
+  -version-info $(liboctgui_version_info) \
+  $(NO_UNDEFINED_LDFLAG) \
+  -bindir $(bindir) \
+  $(LIBOCTGUI_LINK_OPTS)
+
+octetc_DATA = default-qt-settings
+
+octlocale_DATA = $(LOCALES)
+
+default-qt-settings: default-qt-settings.in
+	$(do_subst_qt_settings)
+
+define moc-command
+( echo '#ifdef HAVE_CONFIG_H'; \
+  echo '#include <config.h>'; \
+  echo '#endif'; \
+  $(MOC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(MOC_CPPFLAGS) $(liboctgui_la_CPPFLAGS) $< ) > $@-t
+mv $@-t $@
+endef
+
+moc-%.cc: %.h
+	$(moc-command)
+
+ui-%.h: %.ui
+	$(UIC) -o $@ $<
+
+qrc-%.cc: %.qrc
+	$(RCC) -o $@ $<
+
+%.qm: %.ts
+	$(MKDIR_P) languages
+	$(LRELEASE) -qm $@ $<
+
+DISTCLEANFILES = \
+  $(LOCALES)
+
new file mode 100644
--- /dev/null
+++ b/libgui/default-qt-settings.in
@@ -0,0 +1,71 @@
+[General]
+connectOnStartup=true
+showMessageOfTheDay=true
+showTopic=true
+autoIdentification=false
+useCustomFileEditor=false
+customFileEditor=emacs
+useProxyServer=false
+proxyType=
+proxyHostName=none
+proxyPort=8080
+proxyUserName=
+proxyPassword=
+
+[editor]
+showLineNumbers=true
+highlightCurrentLine=true
+codeCompletion=true
+longWindowTitle=false
+restoreSession=false
+savedSessionTabs=@Invalid()
+mru_file_list=@Invalid()
+
+[terminal]
+fontSize=%DEFAULT_TERMINAL_FONT_SIZE%
+fontName=%DEFAULT_TERMINAL_FONT%
+cursorBlinking=true
+cursorType=ibeam
+
+[MainWindow]
+geometry="@ByteArray(\x1\xd9\xd0\xcb\0\x1\0\0\0\0\0\x14\0\0\0'\0\0\x4;\0\0\x3\x4\0\0\0\x1e\0\0\0\x45\0\0\x4\x31\0\0\x2\xfa\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\x4\x14\0\0\x2]\xfc\x2\0\0\0\x1\xfc\0\0\0\x42\0\0\x2]\0\0\x1\xa7\0\xff\xff\xff\xfc\x1\0\0\0\x2\xfc\0\0\0\0\0\0\x1y\0\0\0X\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\x42\0\0\0\xc0\0\0\0\x97\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\x1\b\0\0\0\xce\0\0\0q\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\xdc\0\0\0\xc3\0\0\0\x93\0\xff\xff\xff\xfc\0\0\x1\x7f\0\0\x2\x95\0\0\x1,\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\0\xe1\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\0k\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\xba\0\xff\xff\xff\0\0\0\0\0\0\x2]\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\0\0\0\x16\0M\0\x61\0i\0n\0T\0o\0o\0l\0\x42\0\x61\0r\x1\0\0\0\0\xff\xff\xff\xff\0\0\0\0\0\0\0\0)"
+current_directory_list=/scratch/jwe/build/octave
+
+[DockWidgets]
+TerminalDockWidget=@ByteArray(\x1\xd9\xd0\xcb\0\x1\0\0\0\0\x1\x7f\0\0\0\x42\0\0\x4\x13\0\0\x2\x7f\0\0\x1\x7f\0\0\0\x42\0\0\x4\x13\0\0\x2\x7f\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\x1\b\0\0\x1x\0\0\x1\xd5\0\0\0\0\0\0\x1\b\0\0\x1x\0\0\x1\xd5\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\xdc\0\0\x1x\0\0\x2\x9e\0\0\0\0\0\0\x1\xdc\0\0\x1x\0\0\x2\x9e\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\x42\0\0\x1x\0\0\x1\x1\0\0\0\0\0\0\0\x42\0\0\x1x\0\0\x1\x1\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\xf4\0\0\0\x5\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\xf4\0\0\0\x5\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\x1\x63\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\x1\x63\0\0\0\x1\0\0\0\0\0\0\0\0\0\0\0\x3\0\0\0\0)
+showFilenames=true
+showFileSize=false
+showFileType=false
+showLastModified=false
+showHiddenFiles=false
+sync_octave_directory=true
+useAlternatingRowColors=true
new file mode 100644
--- /dev/null
+++ b/libgui/gui.pro
@@ -0,0 +1,2 @@
+TEMPLATE = subdirs
+SUBDIRS = qterminal src
new file mode 100644
--- /dev/null
+++ b/libgui/kb-layouts/default.keytab
@@ -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.
new file mode 100644
--- /dev/null
+++ b/libgui/kb-layouts/linux.keytab
@@ -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.
new file mode 100644
--- /dev/null
+++ b/libgui/kb-layouts/vt420pc.keytab
@@ -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.
new file mode 100644
--- /dev/null
+++ b/libgui/languages/be_BY.ts
@@ -0,0 +1,1066 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE TS>
+<TS version="2.0" language="be_BY">
+<context>
+    <name>documentation_dock_widget</name>
+    <message>
+        <location filename="../src/documentation-dockwidget.cc" line="+34"/>
+        <source>Documentation</source>
+        <translation type="unfinished">ДакументацыÑ</translation>
+    </message>
+</context>
+<context>
+    <name>file_editor</name>
+    <message>
+        <location filename="../src/m-editor/file-editor.cc" line="+146"/>
+        <location line="+38"/>
+        <location line="+43"/>
+        <location line="+26"/>
+        <source>Octave Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-106"/>
+        <source>File %1 is already open in the editor.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+38"/>
+        <source>Could not open file %1 for read:
+%2.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+43"/>
+        <source>File not saved! A file with the selected name
+%1
+is already open in the editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>The associated file editor tab has disappeared.  It was likely closed by some means.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+141"/>
+        <source>&amp;%1 %2</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+130"/>
+        <source>&amp;New File</source>
+        <translation type="unfinished">&amp;Ðовы файл</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Open File</source>
+        <translation type="unfinished">&amp;Ðдкрыць файл</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Save File</source>
+        <translation type="unfinished">&amp;Захаваць файл</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save File &amp;As</source>
+        <translation type="unfinished">Захаваць файл &amp;Ñк</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Undo</source>
+        <translation type="unfinished">&amp;Ðдрабіць</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Redo</source>
+        <translation type="unfinished">&amp;Паўтарыць</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Copy</source>
+        <translation type="unfinished">&amp;КапіÑваць</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Cu&amp;t</source>
+        <translation type="unfinished">Вы&amp;разаць</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Next Bookmark</source>
+        <translation type="unfinished">&amp;ÐаÑÑ‚ÑƒÐ¿Ð½Ð°Ñ Ð·Ð°ÐºÐ»Ð°Ð´ÐºÐ°</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Pre&amp;vious Bookmark</source>
+        <translation type="unfinished">Па&amp;пÑÑ€ÑднÑÑ Ð·Ð°ÐºÐ»Ð°Ð´ÐºÐ°</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Toggle &amp;Bookmark</source>
+        <translation type="unfinished">&amp;ПаÑтавіць/прыбраць закладку</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Remove All Bookmarks</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Next breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Pre&amp;vious breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Toggle &amp;breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Remove All breakpoints</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Comment Selected Text</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Uncomment Selected Text</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Find and Replace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Save File And Run</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+51"/>
+        <source>&amp;File</source>
+        <translation type="unfinished">&amp;Файл</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Open &amp;Recent</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>&amp;Edit</source>
+        <translation type="unfinished">&amp;ЗмÑніць</translation>
+    </message>
+    <message>
+        <location line="+19"/>
+        <source>&amp;Debug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+9"/>
+        <source>&amp;Run</source>
+        <translation type="unfinished">&amp;ЗапуÑціць</translation>
+    </message>
+</context>
+<context>
+    <name>file_editor_tab</name>
+    <message>
+        <location filename="../src/m-editor/file-editor-tab.cc" line="+687"/>
+        <location line="+102"/>
+        <location line="+98"/>
+        <location line="+63"/>
+        <location line="+14"/>
+        <source>Octave Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-276"/>
+        <source>The file &apos;%1&apos; has been modified. Do you want to save the changes?</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+102"/>
+        <source>Could not open file %1 for write:
+%2.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+98"/>
+        <source>File not saved!  You&apos;ve selected a file name
+
+     %1
+
+which is the same as the current file name.  Use Save to overwrite.  (Could allow overwriting, with message, if that is what folks want.)</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+63"/>
+        <source>It seems that &apos;%1&apos; has been modified by another application. Do you want to reload it?</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+14"/>
+        <source>It seems that &apos;%1&apos; has been deleted or renamed. Do you want to save it now?</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>files_dock_widget</name>
+    <message>
+        <location filename="../src/files-dockwidget.cc" line="+43"/>
+        <source>Current Directory</source>
+        <translation type="unfinished">БÑгучы каталог</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Move up one directory.</source>
+        <translation type="unfinished">ПаÑунуцца да ўзроўню вышÑй.</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Enter the path or filename.</source>
+        <translation type="unfinished">УвÑдзіце шлÑÑ… ці назву файла.</translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>Doubleclick a file to open it.</source>
+        <translation type="unfinished">Двойчы пÑтрык па файле адкрые Ñго.</translation>
+    </message>
+</context>
+<context>
+    <name>find_dialog</name>
+    <message>
+        <location filename="../src/m-editor/find-dialog.cc" line="+58"/>
+        <source>Find &amp;what:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Re&amp;place with:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Match &amp;case</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search from &amp;start</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Wrap while searching</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Find Next</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Replace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Replace &amp;All</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;More</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>&amp;Whole words</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Regular E&amp;xpressions</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search &amp;backward</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search se&amp;lection</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>history_dock_widget</name>
+    <message>
+        <location filename="../src/history-dockwidget.cc" line="+55"/>
+        <source>Doubleclick a command to transfer it to the terminal.</source>
+        <translation type="unfinished">Двойчы пÑтрык па загадзе перадаÑць Ñго Ñž Ñ‚Ñрмінал.</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Enter text to filter the command history.</source>
+        <translation type="unfinished">УвÑдзіце Ñ‚ÑкÑÑ‚ Ð´Ð»Ñ Ñ„Ñ–Ð»ÑŒÑ‚Ñ€Ð°Ð²Ð°Ð½Ð½Ñ Ð³Ñ–Ñторыі загадаў.</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation type="unfinished">ГіÑÑ‚Ð¾Ñ€Ñ‹Ñ Ð·Ð°Ð³Ð°Ð´Ð°Ñž</translation>
+    </message>
+    <message>
+        <location line="+42"/>
+        <source>Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Evaluate</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>lexer_octave_gui</name>
+    <message>
+        <location filename="../src/m-editor/lexer-octave-gui.cc" line="+145"/>
+        <source>Default</source>
+        <translation type="unfinished">Па змоўчванні</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Comment</source>
+        <translation type="unfinished">Каментар</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Command</source>
+        <translation type="unfinished">Загад</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Number</source>
+        <translation type="unfinished">Ðумар</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Keyword</source>
+        <translation type="unfinished">КлючаÑлова</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Single-quoted string</source>
+        <translation type="unfinished">Радок у аднакоÑÑÑ–</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Operator</source>
+        <translation type="unfinished">Ðператар</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Identifier</source>
+        <translation type="unfinished">ІдÑнтыфікатар</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Double-quoted string</source>
+        <translation type="unfinished">Радок у двукоÑÑÑ–</translation>
+    </message>
+</context>
+<context>
+    <name>main_window</name>
+    <message>
+        <location filename="../src/main-window.cc" line="+135"/>
+        <source>Save Workspace</source>
+        <translation type="unfinished">Захаваць праÑтору зменных</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Load Workspace</source>
+        <translation type="unfinished">Загрузіць праÑтору зменных</translation>
+    </message>
+    <message>
+        <location line="+155"/>
+        <source>Set working direcotry</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+186"/>
+        <location line="+381"/>
+        <source>About Octave</source>
+        <translation type="unfinished">Пра Octave</translation>
+    </message>
+    <message>
+        <location line="-290"/>
+        <source>View the variables in the active workspace.</source>
+        <translation type="unfinished">ПраглÑд зменных бÑгучай праÑторы.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse and search the command history.</source>
+        <translation type="unfinished">ÐглÑд Ñ– пошук па гіÑторыі загадаў.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse your files.</source>
+        <translation type="unfinished">ÐглÑд файлаў.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>See the documentation for help.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+39"/>
+        <source>&amp;File</source>
+        <translation type="unfinished">&amp;Файл</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>New</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Script</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Function</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Class</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Enumeration</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Figure</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Variable</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Model</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>GUI</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Open...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Close Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Import Data...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save Workspace...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Preferences...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Page Setup...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Print</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Print Selection...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Exit</source>
+        <translation type="unfinished">ВыйÑці</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Edit</source>
+        <translation type="unfinished">&amp;ЗмÑніць</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Undo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Redo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Cut</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste To Workspace...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Select All</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Delete</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Find...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Find Files...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Clear Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Clear Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Clear Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>De&amp;bug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Step</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step in</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step out</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Continue</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <source>Exit Debug Mode</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <source>&amp;Desktop</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Load workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Show Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Current Directory</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Documentation</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation type="unfinished">ГіÑÑ‚Ð¾Ñ€Ñ‹Ñ Ð·Ð°Ð³Ð°Ð´Ð°Ñž</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Current Directory</source>
+        <translation type="unfinished">БÑгучы каталог</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Workspace</source>
+        <translation type="unfinished">ПраÑтора зменных</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Editor</source>
+        <translation type="unfinished">РÑдактар</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Documentation</source>
+        <translation type="unfinished">ДакументацыÑ</translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Reset Windows</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Help</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Report Bug</source>
+        <translation type="unfinished">Паведаміць пра хібу</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Agora</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Octave Forge</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+20"/>
+        <source>Current Directory:</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>settings_dialog</name>
+    <message>
+        <location filename="../src/settings-dialog.ui" line="+29"/>
+        <location filename="../src/ui-settings-dialog.h" line="+461"/>
+        <source>Settings</source>
+        <translation type="unfinished">ÐаÑтаўленні</translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+5"/>
+        <source>General</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+18"/>
+        <location filename="../src/ui-settings-dialog.h" line="-4"/>
+        <source>Icon set for dock widget</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Octave logo only</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+16"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Letter icons</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Graphic  icons</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+11"/>
+        <source>Editor</source>
+        <translation type="unfinished">РÑдактар</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-130"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font Size</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-109"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <source>Show line numbers</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Highlight current line</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Code completion</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show complete path in window title</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Restore tabs from previous session on startup</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Use custom file editor:</source>
+        <translation type="unfinished">Вызначыць ўлаÑны Ñ€Ñдактар:</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>emacs</source>
+        <translation type="unfinished">emacs</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+6"/>
+        <source>Terminal</source>
+        <translation type="unfinished">ТÑрмінал</translation>
+    </message>
+    <message>
+        <location line="+62"/>
+        <location filename="../src/ui-settings-dialog.h" line="-2"/>
+        <source>Cursor type:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Cursor blinking</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+36"/>
+        <location filename="../src/ui-settings-dialog.h" line="+8"/>
+        <source>File Browser</source>
+        <translation type="unfinished">Файлавы аглÑдальнік</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-6"/>
+        <source>Show filenames</source>
+        <translation type="unfinished">Паказваць назвы файлаў</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file size</source>
+        <translation type="unfinished">Паказваць памеры файлаў</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file type</source>
+        <translation type="unfinished">Паказваць тыпы файлаў</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show date of last modification</source>
+        <translation type="unfinished">Паказваць дату апошнÑга змÑненнÑ</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show hidden files</source>
+        <translation type="unfinished">Паказваць ÑÑ…Ð°Ð²Ð°Ð½Ñ‹Ñ Ñ„Ð°Ð¹Ð»Ñ‹</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Alternating row colors</source>
+        <translation type="unfinished">Колеры радкоў чаргуюцца</translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+13"/>
+        <source>Network</source>
+        <translation type="unfinished">Сетка</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-11"/>
+        <source>Use proxy server</source>
+        <translation type="unfinished">ВыкарыÑтоўваць прокÑÑ–-Ñервер</translation>
+    </message>
+    <message>
+        <location line="+12"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Proxy Type:</source>
+        <translation type="unfinished">Тып прокÑÑ–:</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+3"/>
+        <source>HttpProxy</source>
+        <translation type="unfinished">HttpProxy</translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Socks5Proxy</source>
+        <translation type="unfinished">Socks5Proxy</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+2"/>
+        <source>Hostname:</source>
+        <translation type="unfinished">Ðазва хоÑта:</translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Port:</source>
+        <translation type="unfinished">Порт:</translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Username:</source>
+        <translation type="unfinished">Ð†Ð¼Ñ ÐºÐ°Ñ€Ñ‹Ñтальніка:</translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Password:</source>
+        <translation type="unfinished">Пароль:</translation>
+    </message>
+</context>
+<context>
+    <name>terminal_dock_widget</name>
+    <message>
+        <location filename="../src/terminal-dockwidget.cc" line="+34"/>
+        <source>Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>webinfo</name>
+    <message>
+        <location filename="../src/qtinfo/webinfo.cc" line="+74"/>
+        <source>Type here and press &apos;Return&apos; to search</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Global search</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>welcome_wizard</name>
+    <message>
+        <location filename="../src/welcome-wizard.ui" line="+26"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+286"/>
+        <source>Welcome to GNU Octave</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>It appears that you have launched Octave GUI for the first time on this computer, since no configuration file could be found at &apos;~/.octave-gui&apos;. This wizard will guide you through the essential settings you should make before you can start using Octave GUI. If you want to transfer your settings you have previously made just close this dialog and copy over the settings file to your home folder. The presence of that file will automatically be detected and will skip this wizard. IMPORTANT: This wizard is not fully functional yet. Just click your way to the end and it will create a standard settings file.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+41"/>
+        <location line="+50"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <source>Next</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-124"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location line="+87"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-5"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+5"/>
+        <source>Previous</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-45"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-3"/>
+        <source>Welcome to Octave!</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>This is the development version of Octave with the first official GUI.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>You seem to run Octave GUI for the first time on this computer. This assistant will help you to configure this software installation. Click &apos;Finish&apos; to write a configuration file and launch Octave GUI.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+48"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+2"/>
+        <source>Finish</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>workspace_model</name>
+    <message>
+        <location filename="../src/workspace-model.cc" line="+42"/>
+        <source>Name</source>
+        <translation type="unfinished">ІдÑнтыфікатар</translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Class</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Dimension</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Value</source>
+        <translation type="unfinished">ЗначÑнне</translation>
+    </message>
+</context>
+<context>
+    <name>workspace_view</name>
+    <message>
+        <location filename="../src/workspace-view.cc" line="+39"/>
+        <source>Workspace</source>
+        <translation type="unfinished">ПраÑтора зменных</translation>
+    </message>
+</context>
+</TS>
new file mode 100644
--- /dev/null
+++ b/libgui/languages/de_DE.ts
@@ -0,0 +1,1066 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE TS>
+<TS version="2.0" language="de_DE">
+<context>
+    <name>documentation_dock_widget</name>
+    <message>
+        <location filename="../src/documentation-dockwidget.cc" line="+34"/>
+        <source>Documentation</source>
+        <translation type="unfinished">Dokumentation</translation>
+    </message>
+</context>
+<context>
+    <name>file_editor</name>
+    <message>
+        <location filename="../src/m-editor/file-editor.cc" line="+146"/>
+        <location line="+38"/>
+        <location line="+43"/>
+        <location line="+26"/>
+        <source>Octave Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-106"/>
+        <source>File %1 is already open in the editor.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+38"/>
+        <source>Could not open file %1 for read:
+%2.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+43"/>
+        <source>File not saved! A file with the selected name
+%1
+is already open in the editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>The associated file editor tab has disappeared.  It was likely closed by some means.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+141"/>
+        <source>&amp;%1 %2</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+130"/>
+        <source>&amp;New File</source>
+        <translation type="unfinished">&amp;Neue Datei</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Open File</source>
+        <translation type="unfinished">&amp;Öffne Datei</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Save File</source>
+        <translation type="unfinished">&amp;Sichere Datei</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save File &amp;As</source>
+        <translation type="unfinished">Sichere Datei &amp;als</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Undo</source>
+        <translation type="unfinished">&amp;Rückgängig</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Redo</source>
+        <translation type="unfinished">&amp;Wiederholen</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Copy</source>
+        <translation type="unfinished">&amp;Kopieren</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Cu&amp;t</source>
+        <translation type="unfinished">&amp;Ausschneiden</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Next Bookmark</source>
+        <translation type="unfinished">&amp;Nächstes Bookmark</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Pre&amp;vious Bookmark</source>
+        <translation type="unfinished">&amp;Voriges Bookmark</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Toggle &amp;Bookmark</source>
+        <translation type="unfinished">&amp;Bookmark setzen</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Remove All Bookmarks</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Next breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Pre&amp;vious breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Toggle &amp;breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Remove All breakpoints</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Comment Selected Text</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Uncomment Selected Text</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Find and Replace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Save File And Run</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+51"/>
+        <source>&amp;File</source>
+        <translation type="unfinished">&amp;Datei</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Open &amp;Recent</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>&amp;Edit</source>
+        <translation type="unfinished">&amp;Editieren</translation>
+    </message>
+    <message>
+        <location line="+19"/>
+        <source>&amp;Debug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+9"/>
+        <source>&amp;Run</source>
+        <translation type="unfinished">&amp;Ausführen</translation>
+    </message>
+</context>
+<context>
+    <name>file_editor_tab</name>
+    <message>
+        <location filename="../src/m-editor/file-editor-tab.cc" line="+687"/>
+        <location line="+102"/>
+        <location line="+98"/>
+        <location line="+63"/>
+        <location line="+14"/>
+        <source>Octave Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-276"/>
+        <source>The file &apos;%1&apos; has been modified. Do you want to save the changes?</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+102"/>
+        <source>Could not open file %1 for write:
+%2.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+98"/>
+        <source>File not saved!  You&apos;ve selected a file name
+
+     %1
+
+which is the same as the current file name.  Use Save to overwrite.  (Could allow overwriting, with message, if that is what folks want.)</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+63"/>
+        <source>It seems that &apos;%1&apos; has been modified by another application. Do you want to reload it?</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+14"/>
+        <source>It seems that &apos;%1&apos; has been deleted or renamed. Do you want to save it now?</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>files_dock_widget</name>
+    <message>
+        <location filename="../src/files-dockwidget.cc" line="+43"/>
+        <source>Current Directory</source>
+        <translation type="unfinished">Aktuelles Verzeichnis</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Move up one directory.</source>
+        <translation type="unfinished">Ein Verzeichnis höher wechseln.</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Enter the path or filename.</source>
+        <translation type="unfinished">Geben Sie einen Pfad oder Dateinamen ein.</translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>Doubleclick a file to open it.</source>
+        <translation type="unfinished">Führen Sie einen Doppelklick aus, um eine Datei zu öffnen.</translation>
+    </message>
+</context>
+<context>
+    <name>find_dialog</name>
+    <message>
+        <location filename="../src/m-editor/find-dialog.cc" line="+58"/>
+        <source>Find &amp;what:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Re&amp;place with:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Match &amp;case</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search from &amp;start</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Wrap while searching</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Find Next</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Replace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Replace &amp;All</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;More</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>&amp;Whole words</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Regular E&amp;xpressions</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search &amp;backward</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search se&amp;lection</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>history_dock_widget</name>
+    <message>
+        <location filename="../src/history-dockwidget.cc" line="+55"/>
+        <source>Doubleclick a command to transfer it to the terminal.</source>
+        <translation type="unfinished">Führen Sie einen Doppelklick aus, um den Befehl in das Terminal zu übertragen.</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Enter text to filter the command history.</source>
+        <translation type="unfinished">Geben Sie Text ein, um die Befehlshistorie zu filtern.</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation type="unfinished">Befehlshistorie</translation>
+    </message>
+    <message>
+        <location line="+42"/>
+        <source>Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Evaluate</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>lexer_octave_gui</name>
+    <message>
+        <location filename="../src/m-editor/lexer-octave-gui.cc" line="+145"/>
+        <source>Default</source>
+        <translation type="unfinished">Standard</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Comment</source>
+        <translation type="unfinished">Kommentar</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Command</source>
+        <translation type="unfinished">Befehl</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Number</source>
+        <translation type="unfinished">Zahl</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Keyword</source>
+        <translation type="unfinished">Schlüsselwort</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Single-quoted string</source>
+        <translation type="unfinished">Zeichenkette in einfachen Hochkommata</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Operator</source>
+        <translation type="unfinished">Operator</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Identifier</source>
+        <translation type="unfinished">Bezeichner</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Double-quoted string</source>
+        <translation type="unfinished">Zeichenkette in doppelten Hochkommata</translation>
+    </message>
+</context>
+<context>
+    <name>main_window</name>
+    <message>
+        <location filename="../src/main-window.cc" line="+135"/>
+        <source>Save Workspace</source>
+        <translation type="unfinished">Speichere Arbeitsumgebung</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Load Workspace</source>
+        <translation type="unfinished">Lade Arbeitsumgebung</translation>
+    </message>
+    <message>
+        <location line="+155"/>
+        <source>Set working direcotry</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+186"/>
+        <location line="+381"/>
+        <source>About Octave</source>
+        <translation type="unfinished">Über Octave</translation>
+    </message>
+    <message>
+        <location line="-290"/>
+        <source>View the variables in the active workspace.</source>
+        <translation type="unfinished">Sehen Sie die Variablen ein, die sich in der aktiven Arbeitsumgebung befinden.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse and search the command history.</source>
+        <translation type="unfinished">Durchsuchen Sie die Befehlshistorie.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse your files.</source>
+        <translation type="unfinished">Durchsuchen Sie Ihre Dateien.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>See the documentation for help.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+39"/>
+        <source>&amp;File</source>
+        <translation type="unfinished">&amp;Datei</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>New</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Script</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Function</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Class</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Enumeration</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Figure</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Variable</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Model</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>GUI</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Open...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Close Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Import Data...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save Workspace...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Preferences...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Page Setup...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Print</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Print Selection...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Exit</source>
+        <translation type="unfinished">Beenden</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Edit</source>
+        <translation type="unfinished">&amp;Editieren</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Undo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Redo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Cut</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste To Workspace...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Select All</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Delete</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Find...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Find Files...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Clear Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Clear Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Clear Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>De&amp;bug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Step</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step in</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step out</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Continue</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <source>Exit Debug Mode</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <source>&amp;Desktop</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Load workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Show Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Current Directory</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Documentation</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Command Window</source>
+        <translation type="unfinished">Konsolenfenster</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation type="unfinished">Befehlshistorie</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Current Directory</source>
+        <translation type="unfinished">Aktuelles Verzeichnis</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Workspace</source>
+        <translation type="unfinished">Arbeitsumgebung</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Editor</source>
+        <translation type="unfinished">Editor</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Documentation</source>
+        <translation type="unfinished">Dokumentation</translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Reset Windows</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Help</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Report Bug</source>
+        <translation type="unfinished">Fehler melden</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Agora</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Octave Forge</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+20"/>
+        <source>Current Directory:</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>settings_dialog</name>
+    <message>
+        <location filename="../src/settings-dialog.ui" line="+29"/>
+        <location filename="../src/ui-settings-dialog.h" line="+461"/>
+        <source>Settings</source>
+        <translation type="unfinished">Einstellungen</translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+5"/>
+        <source>General</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+18"/>
+        <location filename="../src/ui-settings-dialog.h" line="-4"/>
+        <source>Icon set for dock widget</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Octave logo only</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+16"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Letter icons</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Graphic  icons</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+11"/>
+        <source>Editor</source>
+        <translation type="unfinished">Editor</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-130"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font Size</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-109"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <source>Show line numbers</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Highlight current line</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Code completion</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show complete path in window title</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Restore tabs from previous session on startup</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Use custom file editor:</source>
+        <translation type="unfinished">Benutzerdefinierten Editor verwenden:</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>emacs</source>
+        <translation type="unfinished">emacs</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+6"/>
+        <source>Terminal</source>
+        <translation type="unfinished">Terminal</translation>
+    </message>
+    <message>
+        <location line="+62"/>
+        <location filename="../src/ui-settings-dialog.h" line="-2"/>
+        <source>Cursor type:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Cursor blinking</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+36"/>
+        <location filename="../src/ui-settings-dialog.h" line="+8"/>
+        <source>File Browser</source>
+        <translation type="unfinished">Dateibrowser</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-6"/>
+        <source>Show filenames</source>
+        <translation type="unfinished">Dateinamen anzeigen</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file size</source>
+        <translation type="unfinished">Dateigröße anzeigen</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file type</source>
+        <translation type="unfinished">Dateityp anzeigen</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show date of last modification</source>
+        <translation type="unfinished">Datum der letzten Änderung anzeigen</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show hidden files</source>
+        <translation type="unfinished">Versteckte Dateien anzeigen</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Alternating row colors</source>
+        <translation type="unfinished">Alternierende Farben verwenden</translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+13"/>
+        <source>Network</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-11"/>
+        <source>Use proxy server</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+12"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Proxy Type:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+3"/>
+        <source>HttpProxy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Socks5Proxy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+2"/>
+        <source>Hostname:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Port:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Username:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Password:</source>
+        <translation type="unfinished">Passwort:</translation>
+    </message>
+</context>
+<context>
+    <name>terminal_dock_widget</name>
+    <message>
+        <location filename="../src/terminal-dockwidget.cc" line="+34"/>
+        <source>Command Window</source>
+        <translation type="unfinished">Konsolenfenster</translation>
+    </message>
+</context>
+<context>
+    <name>webinfo</name>
+    <message>
+        <location filename="../src/qtinfo/webinfo.cc" line="+74"/>
+        <source>Type here and press &apos;Return&apos; to search</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Global search</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>welcome_wizard</name>
+    <message>
+        <location filename="../src/welcome-wizard.ui" line="+26"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+286"/>
+        <source>Welcome to GNU Octave</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>It appears that you have launched Octave GUI for the first time on this computer, since no configuration file could be found at &apos;~/.octave-gui&apos;. This wizard will guide you through the essential settings you should make before you can start using Octave GUI. If you want to transfer your settings you have previously made just close this dialog and copy over the settings file to your home folder. The presence of that file will automatically be detected and will skip this wizard. IMPORTANT: This wizard is not fully functional yet. Just click your way to the end and it will create a standard settings file.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+41"/>
+        <location line="+50"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <source>Next</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-124"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location line="+87"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-5"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+5"/>
+        <source>Previous</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-45"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-3"/>
+        <source>Welcome to Octave!</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>This is the development version of Octave with the first official GUI.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>You seem to run Octave GUI for the first time on this computer. This assistant will help you to configure this software installation. Click &apos;Finish&apos; to write a configuration file and launch Octave GUI.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+48"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+2"/>
+        <source>Finish</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>workspace_model</name>
+    <message>
+        <location filename="../src/workspace-model.cc" line="+42"/>
+        <source>Name</source>
+        <translation type="unfinished">Bezeichner</translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Class</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Dimension</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Value</source>
+        <translation type="unfinished">Wert</translation>
+    </message>
+</context>
+<context>
+    <name>workspace_view</name>
+    <message>
+        <location filename="../src/workspace-view.cc" line="+39"/>
+        <source>Workspace</source>
+        <translation type="unfinished">Arbeitsumgebung</translation>
+    </message>
+</context>
+</TS>
new file mode 100644
--- /dev/null
+++ b/libgui/languages/en_US.ts
@@ -0,0 +1,1066 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE TS>
+<TS version="2.0">
+<context>
+    <name>documentation_dock_widget</name>
+    <message>
+        <location filename="../src/documentation-dockwidget.cc" line="+34"/>
+        <source>Documentation</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>file_editor</name>
+    <message>
+        <location filename="../src/m-editor/file-editor.cc" line="+146"/>
+        <location line="+38"/>
+        <location line="+43"/>
+        <location line="+26"/>
+        <source>Octave Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-106"/>
+        <source>File %1 is already open in the editor.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+38"/>
+        <source>Could not open file %1 for read:
+%2.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+43"/>
+        <source>File not saved! A file with the selected name
+%1
+is already open in the editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>The associated file editor tab has disappeared.  It was likely closed by some means.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+141"/>
+        <source>&amp;%1 %2</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+130"/>
+        <source>&amp;New File</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Open File</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Save File</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save File &amp;As</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Undo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Redo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Cu&amp;t</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Next Bookmark</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Pre&amp;vious Bookmark</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Toggle &amp;Bookmark</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Remove All Bookmarks</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Next breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Pre&amp;vious breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Toggle &amp;breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Remove All breakpoints</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Comment Selected Text</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Uncomment Selected Text</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Find and Replace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Save File And Run</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+51"/>
+        <source>&amp;File</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Open &amp;Recent</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>&amp;Edit</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+19"/>
+        <source>&amp;Debug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+9"/>
+        <source>&amp;Run</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>file_editor_tab</name>
+    <message>
+        <location filename="../src/m-editor/file-editor-tab.cc" line="+687"/>
+        <location line="+102"/>
+        <location line="+98"/>
+        <location line="+63"/>
+        <location line="+14"/>
+        <source>Octave Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-276"/>
+        <source>The file &apos;%1&apos; has been modified. Do you want to save the changes?</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+102"/>
+        <source>Could not open file %1 for write:
+%2.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+98"/>
+        <source>File not saved!  You&apos;ve selected a file name
+
+     %1
+
+which is the same as the current file name.  Use Save to overwrite.  (Could allow overwriting, with message, if that is what folks want.)</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+63"/>
+        <source>It seems that &apos;%1&apos; has been modified by another application. Do you want to reload it?</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+14"/>
+        <source>It seems that &apos;%1&apos; has been deleted or renamed. Do you want to save it now?</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>files_dock_widget</name>
+    <message>
+        <location filename="../src/files-dockwidget.cc" line="+43"/>
+        <source>Current Directory</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Move up one directory.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Enter the path or filename.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>Doubleclick a file to open it.</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>find_dialog</name>
+    <message>
+        <location filename="../src/m-editor/find-dialog.cc" line="+58"/>
+        <source>Find &amp;what:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Re&amp;place with:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Match &amp;case</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search from &amp;start</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Wrap while searching</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Find Next</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Replace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Replace &amp;All</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;More</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>&amp;Whole words</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Regular E&amp;xpressions</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search &amp;backward</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search se&amp;lection</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>history_dock_widget</name>
+    <message>
+        <location filename="../src/history-dockwidget.cc" line="+55"/>
+        <source>Doubleclick a command to transfer it to the terminal.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Enter text to filter the command history.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+42"/>
+        <source>Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Evaluate</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>lexer_octave_gui</name>
+    <message>
+        <location filename="../src/m-editor/lexer-octave-gui.cc" line="+145"/>
+        <source>Default</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Comment</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Command</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Number</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Keyword</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Single-quoted string</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Operator</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Identifier</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Double-quoted string</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>main_window</name>
+    <message>
+        <location filename="../src/main-window.cc" line="+135"/>
+        <source>Save Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Load Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+155"/>
+        <source>Set working direcotry</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+186"/>
+        <location line="+381"/>
+        <source>About Octave</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-290"/>
+        <source>View the variables in the active workspace.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse and search the command history.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse your files.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>See the documentation for help.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+39"/>
+        <source>&amp;File</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>New</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Script</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Function</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Class</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Enumeration</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Figure</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Variable</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Model</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>GUI</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Open...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Close Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Import Data...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save Workspace...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Preferences...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Page Setup...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Print</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Print Selection...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Exit</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Edit</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Undo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Redo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Cut</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste To Workspace...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Select All</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Delete</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Find...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Find Files...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Clear Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Clear Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Clear Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>De&amp;bug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Step</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step in</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step out</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Continue</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <source>Exit Debug Mode</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <source>&amp;Desktop</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Load workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Show Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Current Directory</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Documentation</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Current Directory</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Documentation</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Reset Windows</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Help</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Report Bug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Agora</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Octave Forge</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+20"/>
+        <source>Current Directory:</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>settings_dialog</name>
+    <message>
+        <location filename="../src/settings-dialog.ui" line="+29"/>
+        <location filename="../src/ui-settings-dialog.h" line="+461"/>
+        <source>Settings</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+5"/>
+        <source>General</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+18"/>
+        <location filename="../src/ui-settings-dialog.h" line="-4"/>
+        <source>Icon set for dock widget</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Octave logo only</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+16"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Letter icons</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Graphic  icons</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+11"/>
+        <source>Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-130"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font Size</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-109"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <source>Show line numbers</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Highlight current line</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Code completion</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show complete path in window title</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Restore tabs from previous session on startup</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Use custom file editor:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>emacs</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+6"/>
+        <source>Terminal</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+62"/>
+        <location filename="../src/ui-settings-dialog.h" line="-2"/>
+        <source>Cursor type:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Cursor blinking</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+36"/>
+        <location filename="../src/ui-settings-dialog.h" line="+8"/>
+        <source>File Browser</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-6"/>
+        <source>Show filenames</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file size</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file type</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show date of last modification</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show hidden files</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Alternating row colors</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+13"/>
+        <source>Network</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-11"/>
+        <source>Use proxy server</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+12"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Proxy Type:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+3"/>
+        <source>HttpProxy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Socks5Proxy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+2"/>
+        <source>Hostname:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Port:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Username:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Password:</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>terminal_dock_widget</name>
+    <message>
+        <location filename="../src/terminal-dockwidget.cc" line="+34"/>
+        <source>Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>webinfo</name>
+    <message>
+        <location filename="../src/qtinfo/webinfo.cc" line="+74"/>
+        <source>Type here and press &apos;Return&apos; to search</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Global search</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>welcome_wizard</name>
+    <message>
+        <location filename="../src/welcome-wizard.ui" line="+26"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+286"/>
+        <source>Welcome to GNU Octave</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>It appears that you have launched Octave GUI for the first time on this computer, since no configuration file could be found at &apos;~/.octave-gui&apos;. This wizard will guide you through the essential settings you should make before you can start using Octave GUI. If you want to transfer your settings you have previously made just close this dialog and copy over the settings file to your home folder. The presence of that file will automatically be detected and will skip this wizard. IMPORTANT: This wizard is not fully functional yet. Just click your way to the end and it will create a standard settings file.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+41"/>
+        <location line="+50"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <source>Next</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-124"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location line="+87"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-5"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+5"/>
+        <source>Previous</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-45"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-3"/>
+        <source>Welcome to Octave!</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>This is the development version of Octave with the first official GUI.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>You seem to run Octave GUI for the first time on this computer. This assistant will help you to configure this software installation. Click &apos;Finish&apos; to write a configuration file and launch Octave GUI.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+48"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+2"/>
+        <source>Finish</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>workspace_model</name>
+    <message>
+        <location filename="../src/workspace-model.cc" line="+42"/>
+        <source>Name</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Class</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Dimension</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Value</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>workspace_view</name>
+    <message>
+        <location filename="../src/workspace-view.cc" line="+39"/>
+        <source>Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+</TS>
new file mode 100644
--- /dev/null
+++ b/libgui/languages/es_ES.ts
@@ -0,0 +1,1066 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE TS>
+<TS version="2.0" language="es_MX">
+<context>
+    <name>documentation_dock_widget</name>
+    <message>
+        <location filename="../src/documentation-dockwidget.cc" line="+34"/>
+        <source>Documentation</source>
+        <translation type="unfinished">Documentación</translation>
+    </message>
+</context>
+<context>
+    <name>file_editor</name>
+    <message>
+        <location filename="../src/m-editor/file-editor.cc" line="+146"/>
+        <location line="+38"/>
+        <location line="+43"/>
+        <location line="+26"/>
+        <source>Octave Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-106"/>
+        <source>File %1 is already open in the editor.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+38"/>
+        <source>Could not open file %1 for read:
+%2.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+43"/>
+        <source>File not saved! A file with the selected name
+%1
+is already open in the editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>The associated file editor tab has disappeared.  It was likely closed by some means.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+141"/>
+        <source>&amp;%1 %2</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+130"/>
+        <source>&amp;New File</source>
+        <translation type="unfinished">Archivo &amp;nuevo</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Open File</source>
+        <translation type="unfinished">&amp;Abrir archivo</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Save File</source>
+        <translation type="unfinished">&amp;Guardar archivo</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save File &amp;As</source>
+        <translation type="unfinished">Guardar archivo &amp;como</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Undo</source>
+        <translation type="unfinished">&amp;Deshacer</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Redo</source>
+        <translation type="unfinished">&amp;Rehacer</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Copy</source>
+        <translation type="unfinished">&amp;Copiar</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Cu&amp;t</source>
+        <translation type="unfinished">Cor&amp;tar</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Next Bookmark</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Pre&amp;vious Bookmark</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Toggle &amp;Bookmark</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Remove All Bookmarks</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Next breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Pre&amp;vious breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Toggle &amp;breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Remove All breakpoints</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Comment Selected Text</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Uncomment Selected Text</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Find and Replace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Save File And Run</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+51"/>
+        <source>&amp;File</source>
+        <translation type="unfinished">&amp;Archivo</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Open &amp;Recent</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>&amp;Edit</source>
+        <translation type="unfinished">&amp;Editar</translation>
+    </message>
+    <message>
+        <location line="+19"/>
+        <source>&amp;Debug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+9"/>
+        <source>&amp;Run</source>
+        <translation type="unfinished">&amp;Ejecutar</translation>
+    </message>
+</context>
+<context>
+    <name>file_editor_tab</name>
+    <message>
+        <location filename="../src/m-editor/file-editor-tab.cc" line="+687"/>
+        <location line="+102"/>
+        <location line="+98"/>
+        <location line="+63"/>
+        <location line="+14"/>
+        <source>Octave Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-276"/>
+        <source>The file &apos;%1&apos; has been modified. Do you want to save the changes?</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+102"/>
+        <source>Could not open file %1 for write:
+%2.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+98"/>
+        <source>File not saved!  You&apos;ve selected a file name
+
+     %1
+
+which is the same as the current file name.  Use Save to overwrite.  (Could allow overwriting, with message, if that is what folks want.)</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+63"/>
+        <source>It seems that &apos;%1&apos; has been modified by another application. Do you want to reload it?</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+14"/>
+        <source>It seems that &apos;%1&apos; has been deleted or renamed. Do you want to save it now?</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>files_dock_widget</name>
+    <message>
+        <location filename="../src/files-dockwidget.cc" line="+43"/>
+        <source>Current Directory</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Move up one directory.</source>
+        <translation type="unfinished">Subir un directorio.</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Enter the path or filename.</source>
+        <translation type="unfinished">Introduzca dirección o nombre de archivo.</translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>Doubleclick a file to open it.</source>
+        <translation type="unfinished">Haga doble clic para abir archivo.</translation>
+    </message>
+</context>
+<context>
+    <name>find_dialog</name>
+    <message>
+        <location filename="../src/m-editor/find-dialog.cc" line="+58"/>
+        <source>Find &amp;what:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Re&amp;place with:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Match &amp;case</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search from &amp;start</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Wrap while searching</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Find Next</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Replace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Replace &amp;All</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;More</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>&amp;Whole words</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Regular E&amp;xpressions</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search &amp;backward</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search se&amp;lection</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>history_dock_widget</name>
+    <message>
+        <location filename="../src/history-dockwidget.cc" line="+55"/>
+        <source>Doubleclick a command to transfer it to the terminal.</source>
+        <translation type="unfinished">Haga doble clic para transferir el comando a la terminal.</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Enter text to filter the command history.</source>
+        <translation type="unfinished">Introduzca texto para filtrar el historial de comandos.</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation type="unfinished">Historial de comandos</translation>
+    </message>
+    <message>
+        <location line="+42"/>
+        <source>Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Evaluate</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>lexer_octave_gui</name>
+    <message>
+        <location filename="../src/m-editor/lexer-octave-gui.cc" line="+145"/>
+        <source>Default</source>
+        <translation type="unfinished">Valores predeterminados</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Comment</source>
+        <translation type="unfinished">Comentario</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Command</source>
+        <translation type="unfinished">Comando</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Number</source>
+        <translation type="unfinished">Número</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Keyword</source>
+        <translation type="unfinished">Contraseña</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Single-quoted string</source>
+        <translation type="unfinished">Cadena entre comillas simples</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Operator</source>
+        <translation type="unfinished">Operador</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Identifier</source>
+        <translation type="unfinished">Identificador</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Double-quoted string</source>
+        <translation type="unfinished">Cadena entre comillas dobles</translation>
+    </message>
+</context>
+<context>
+    <name>main_window</name>
+    <message>
+        <location filename="../src/main-window.cc" line="+135"/>
+        <source>Save Workspace</source>
+        <translation type="unfinished">Guardar espacio de trabajo</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Load Workspace</source>
+        <translation type="unfinished">Cargar espacio de trabajo</translation>
+    </message>
+    <message>
+        <location line="+155"/>
+        <source>Set working direcotry</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+186"/>
+        <location line="+381"/>
+        <source>About Octave</source>
+        <translation type="unfinished">Acerca de Octave</translation>
+    </message>
+    <message>
+        <location line="-290"/>
+        <source>View the variables in the active workspace.</source>
+        <translation type="unfinished">Ver variables en el espacio de trabajo activo.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse and search the command history.</source>
+        <translation type="unfinished">Navegar y buscar en el historial de comandos.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse your files.</source>
+        <translation type="unfinished">Explorar sus archivos.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>See the documentation for help.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+39"/>
+        <source>&amp;File</source>
+        <translation type="unfinished">&amp;Archivo</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>New</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Script</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Function</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Class</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Enumeration</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Figure</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Variable</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Model</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>GUI</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Open...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Close Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Import Data...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save Workspace...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Preferences...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Page Setup...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Print</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Print Selection...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Exit</source>
+        <translation type="unfinished">Salir</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Edit</source>
+        <translation type="unfinished">&amp;Editar</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Undo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Redo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Cut</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste To Workspace...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Select All</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Delete</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Find...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Find Files...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Clear Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Clear Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Clear Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>De&amp;bug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Step</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step in</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step out</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Continue</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <source>Exit Debug Mode</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <source>&amp;Desktop</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Load workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Show Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Current Directory</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Documentation</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation type="unfinished">Historial de comandos</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Current Directory</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Workspace</source>
+        <translation type="unfinished">Espacio de trabajo</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Editor</source>
+        <translation type="unfinished">Editor</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Documentation</source>
+        <translation type="unfinished">Documentación</translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Reset Windows</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Help</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Report Bug</source>
+        <translation type="unfinished">Reportar error de software/Bug</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Agora</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Octave Forge</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+20"/>
+        <source>Current Directory:</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>settings_dialog</name>
+    <message>
+        <location filename="../src/settings-dialog.ui" line="+29"/>
+        <location filename="../src/ui-settings-dialog.h" line="+461"/>
+        <source>Settings</source>
+        <translation type="unfinished">Configuración</translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+5"/>
+        <source>General</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+18"/>
+        <location filename="../src/ui-settings-dialog.h" line="-4"/>
+        <source>Icon set for dock widget</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Octave logo only</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+16"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Letter icons</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Graphic  icons</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+11"/>
+        <source>Editor</source>
+        <translation type="unfinished">Editor</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-130"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font Size</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-109"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <source>Show line numbers</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Highlight current line</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Code completion</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show complete path in window title</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Restore tabs from previous session on startup</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Use custom file editor:</source>
+        <translation type="unfinished">Usar editor de archivos personalizados:</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>emacs</source>
+        <translation type="unfinished">emacs</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+6"/>
+        <source>Terminal</source>
+        <translation type="unfinished">Terminal</translation>
+    </message>
+    <message>
+        <location line="+62"/>
+        <location filename="../src/ui-settings-dialog.h" line="-2"/>
+        <source>Cursor type:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Cursor blinking</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+36"/>
+        <location filename="../src/ui-settings-dialog.h" line="+8"/>
+        <source>File Browser</source>
+        <translation type="unfinished">Explorador de archivos</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-6"/>
+        <source>Show filenames</source>
+        <translation type="unfinished">Mostrar nombres de archivos</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file size</source>
+        <translation type="unfinished">Mostrar tamaño de archivo</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file type</source>
+        <translation type="unfinished">Mostrar tipo de archivo</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show date of last modification</source>
+        <translation type="unfinished">Mostrar fecha de la última modificación</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show hidden files</source>
+        <translation type="unfinished">Mostrar archivos ocultos</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Alternating row colors</source>
+        <translation type="unfinished">Colores alternos de filas</translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+13"/>
+        <source>Network</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-11"/>
+        <source>Use proxy server</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+12"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Proxy Type:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+3"/>
+        <source>HttpProxy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Socks5Proxy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+2"/>
+        <source>Hostname:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Port:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Username:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Password:</source>
+        <translation type="unfinished">Contraseña:</translation>
+    </message>
+</context>
+<context>
+    <name>terminal_dock_widget</name>
+    <message>
+        <location filename="../src/terminal-dockwidget.cc" line="+34"/>
+        <source>Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>webinfo</name>
+    <message>
+        <location filename="../src/qtinfo/webinfo.cc" line="+74"/>
+        <source>Type here and press &apos;Return&apos; to search</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Global search</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>welcome_wizard</name>
+    <message>
+        <location filename="../src/welcome-wizard.ui" line="+26"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+286"/>
+        <source>Welcome to GNU Octave</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>It appears that you have launched Octave GUI for the first time on this computer, since no configuration file could be found at &apos;~/.octave-gui&apos;. This wizard will guide you through the essential settings you should make before you can start using Octave GUI. If you want to transfer your settings you have previously made just close this dialog and copy over the settings file to your home folder. The presence of that file will automatically be detected and will skip this wizard. IMPORTANT: This wizard is not fully functional yet. Just click your way to the end and it will create a standard settings file.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+41"/>
+        <location line="+50"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <source>Next</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-124"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location line="+87"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-5"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+5"/>
+        <source>Previous</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-45"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-3"/>
+        <source>Welcome to Octave!</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>This is the development version of Octave with the first official GUI.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>You seem to run Octave GUI for the first time on this computer. This assistant will help you to configure this software installation. Click &apos;Finish&apos; to write a configuration file and launch Octave GUI.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+48"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+2"/>
+        <source>Finish</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>workspace_model</name>
+    <message>
+        <location filename="../src/workspace-model.cc" line="+42"/>
+        <source>Name</source>
+        <translation type="unfinished">Nombre</translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Class</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Dimension</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Value</source>
+        <translation type="unfinished">Valor</translation>
+    </message>
+</context>
+<context>
+    <name>workspace_view</name>
+    <message>
+        <location filename="../src/workspace-view.cc" line="+39"/>
+        <source>Workspace</source>
+        <translation type="unfinished">Espacio de trabajo</translation>
+    </message>
+</context>
+</TS>
new file mode 100644
--- /dev/null
+++ b/libgui/languages/nl_NL.ts
@@ -0,0 +1,1074 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE TS>
+<TS version="2.0" language="nl_NL">
+<context>
+    <name>documentation_dock_widget</name>
+    <message>
+        <location filename="../src/documentation-dockwidget.cc" line="+34"/>
+        <source>Documentation</source>
+        <translation>Documentatie</translation>
+    </message>
+</context>
+<context>
+    <name>file_editor</name>
+    <message>
+        <location filename="../src/m-editor/file-editor.cc" line="+146"/>
+        <location line="+38"/>
+        <location line="+43"/>
+        <location line="+26"/>
+        <source>Octave Editor</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="-106"/>
+        <source>File %1 is already open in the editor.</source>
+        <translation>Bestand %1 is al geopend in de editor.</translation>
+    </message>
+    <message>
+        <location line="+38"/>
+        <source>Could not open file %1 for read:
+%2.</source>
+        <translation>Bestand %1 kon niet geopend worden om te lezen:
+%2.</translation>
+    </message>
+    <message>
+        <location line="+43"/>
+        <source>File not saved! A file with the selected name
+%1
+is already open in the editor</source>
+        <translation>Bestand niet opgeslagen! Een bestand met de naam
+%1
+is al geopend in de editor</translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>The associated file editor tab has disappeared.  It was likely closed by some means.</source>
+        <translation>Het bijbehorende tabblad in de editor is verdwenen. Het is waarschijnlijk op een of andere manier gesloten.</translation>
+    </message>
+    <message>
+        <location line="+141"/>
+        <source>&amp;%1 %2</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+130"/>
+        <source>&amp;New File</source>
+        <translation>&amp;Nieuw Bestand</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Open File</source>
+        <translation>&amp;Openen</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Save File</source>
+        <translation>Op&amp;slaan</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save File &amp;As</source>
+        <translation>Opslaan &amp;als</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Undo</source>
+        <translation>Ongedaan maken</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Redo</source>
+        <translation>He&amp;rhalen</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Copy</source>
+        <translation>Kopiëren</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Cu&amp;t</source>
+        <translation>Knippen</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation>Plakken</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Next Bookmark</source>
+        <translation>Volge&amp;nde bladwijzer</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Pre&amp;vious Bookmark</source>
+        <translation>&amp;Vorige bladwijzer</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Toggle &amp;Bookmark</source>
+        <translation>&amp;Bladwijzer invoegen</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Remove All Bookmarks</source>
+        <translation>Alle bladwijzers ve&amp;rwijderen</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Next breakpoint</source>
+        <translation>Volge&amp;nd breekpunt</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Pre&amp;vious breakpoint</source>
+        <translation>&amp;Vorig breekpunt</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Toggle &amp;breakpoint</source>
+        <translation>&amp;Breekpunt invoegen</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Remove All breakpoints</source>
+        <translation>Alle breekpunten ve&amp;rwijderen</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Comment Selected Text</source>
+        <translation>Geselecteerde tekst markeren als &amp;commentaar</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Uncomment Selected Text</source>
+        <translation>Gelesecteerde tekst niet markeren als commentaar</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Find and Replace</source>
+        <translation>Vervangen</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Save File And Run</source>
+        <translation>Bestand opslaan en uitvoeren</translation>
+    </message>
+    <message>
+        <location line="+51"/>
+        <source>&amp;File</source>
+        <translation>Bestand</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Open &amp;Recent</source>
+        <translation>&amp;Recent bestand openen</translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>&amp;Edit</source>
+        <translation>B&amp;ewerken</translation>
+    </message>
+    <message>
+        <location line="+19"/>
+        <source>&amp;Debug</source>
+        <translation>&amp;Debuggen</translation>
+    </message>
+    <message>
+        <location line="+9"/>
+        <source>&amp;Run</source>
+        <translation>Uitvoe&amp;ren</translation>
+    </message>
+</context>
+<context>
+    <name>file_editor_tab</name>
+    <message>
+        <location filename="../src/m-editor/file-editor-tab.cc" line="+687"/>
+        <location line="+102"/>
+        <location line="+98"/>
+        <location line="+63"/>
+        <location line="+14"/>
+        <source>Octave Editor</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="-276"/>
+        <source>The file &apos;%1&apos; has been modified. Do you want to save the changes?</source>
+        <translation>Het bestand &apos;%1&apos; is aangepast. Wil je de wijzigingen opslaan?</translation>
+    </message>
+    <message>
+        <location line="+102"/>
+        <source>Could not open file %1 for write:
+%2.</source>
+        <translation>Kon bestand %1 niet openen om te schrijven:
+%2.</translation>
+    </message>
+    <message>
+        <location line="+98"/>
+        <source>File not saved!  You&apos;ve selected a file name
+
+     %1
+
+which is the same as the current file name.  Use Save to overwrite.  (Could allow overwriting, with message, if that is what folks want.)</source>
+        <translation>Bestand niet opgeslagen! Je hebt een bestandsnaam
+
+     %1
+
+gekozen die hetzelfde is als de huidige bestandsnaam. Gebruik Opslaan om te overschrijven.</translation>
+    </message>
+    <message>
+        <location line="+63"/>
+        <source>It seems that &apos;%1&apos; has been modified by another application. Do you want to reload it?</source>
+        <translation>Het lijkt erop dat &apos;%1&apos; is aangepast door een ander programma. Wil je het opnieuw laden?</translation>
+    </message>
+    <message>
+        <location line="+14"/>
+        <source>It seems that &apos;%1&apos; has been deleted or renamed. Do you want to save it now?</source>
+        <translation>Het lijkt erop dat &apos;%1&apos; verwijderd of hernoemd is. Wil je het nu opslaan?</translation>
+    </message>
+</context>
+<context>
+    <name>files_dock_widget</name>
+    <message>
+        <location filename="../src/files-dockwidget.cc" line="+43"/>
+        <source>Current Directory</source>
+        <translation>Huidige map</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Move up one directory.</source>
+        <translation>Een map naar boven gaan.</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Enter the path or filename.</source>
+        <translation>Voer het pad of de bestandsnaam in.</translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>Doubleclick a file to open it.</source>
+        <translation>Dubbelklik op een bestand om te openen.</translation>
+    </message>
+</context>
+<context>
+    <name>find_dialog</name>
+    <message>
+        <location filename="../src/m-editor/find-dialog.cc" line="+58"/>
+        <source>Find &amp;what:</source>
+        <translation>Zoek naar:</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Re&amp;place with:</source>
+        <translation>Vervang door:</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Match &amp;case</source>
+        <translation>Hoofdlettergevoelig</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search from &amp;start</source>
+        <translation>Zoek vanaf het begin</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Wrap while searching</source>
+        <translation>Bestandseinde negeren</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Find Next</source>
+        <translation>Volgende zoeken</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Replace</source>
+        <translation>Ve&amp;rvang</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Replace &amp;All</source>
+        <translation>&amp;Alles vervangen</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;More</source>
+        <translation>&amp;Meer</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>&amp;Whole words</source>
+        <translation>Hele &amp;woorden</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Regular E&amp;xpressions</source>
+        <translation>Reguliere e&amp;xpressies</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search &amp;backward</source>
+        <translation>Terug zoeken</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search se&amp;lection</source>
+        <translation>In se&amp;lectie</translation>
+    </message>
+</context>
+<context>
+    <name>history_dock_widget</name>
+    <message>
+        <location filename="../src/history-dockwidget.cc" line="+55"/>
+        <source>Doubleclick a command to transfer it to the terminal.</source>
+        <translation>Dubbelklik een commando om het naar de terminal te sturen.</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Enter text to filter the command history.</source>
+        <translation>Voer text in om de commandogeschiedenis te filteren.</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation>Commandogeschiedenis</translation>
+    </message>
+    <message>
+        <location line="+42"/>
+        <source>Copy</source>
+        <translation>Kopiëren</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Evaluate</source>
+        <translation>Evalueer</translation>
+    </message>
+</context>
+<context>
+    <name>lexer_octave_gui</name>
+    <message>
+        <location filename="../src/m-editor/lexer-octave-gui.cc" line="+145"/>
+        <source>Default</source>
+        <translation>Standaard</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Comment</source>
+        <translation>Commentaar</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Command</source>
+        <translation>Commando</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Number</source>
+        <translation>Nummer</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Keyword</source>
+        <translation>Trefwoord</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Single-quoted string</source>
+        <translation>String met enkele quotes</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Operator</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Identifier</source>
+        <translation>Identificator</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Double-quoted string</source>
+        <translation>String met dubbele quotes</translation>
+    </message>
+</context>
+<context>
+    <name>main_window</name>
+    <message>
+        <location filename="../src/main-window.cc" line="+135"/>
+        <source>Save Workspace</source>
+        <translation>Werkruimte opslaan</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Load Workspace</source>
+        <translation>Werkruimte laden</translation>
+    </message>
+    <message>
+        <location line="+155"/>
+        <source>Set working direcotry</source>
+        <translation>Werkmap instellen</translation>
+    </message>
+    <message>
+        <location line="+186"/>
+        <location line="+381"/>
+        <source>About Octave</source>
+        <translation>Over Octave</translation>
+    </message>
+    <message>
+        <location line="-290"/>
+        <source>View the variables in the active workspace.</source>
+        <translation>Bekijk de variabelen in de huidige werkruimte.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse and search the command history.</source>
+        <translation>Bladeren en zoeken door de commandogeschiedenis.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse your files.</source>
+        <translation>Blader door uw bestanden.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>See the documentation for help.</source>
+        <translation>Zie de documentatie voor hulp.</translation>
+    </message>
+    <message>
+        <location line="+39"/>
+        <source>&amp;File</source>
+        <translation>Bestand</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>New</source>
+        <translation>Nieuw</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Script</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Function</source>
+        <translation>Functie</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Class</source>
+        <translation>Klasse</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Enumeration</source>
+        <translation>Enumeratie</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Figure</source>
+        <translation>Figuur</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Variable</source>
+        <translation>Variabele</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Model</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>GUI</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Open...</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Close Command Window</source>
+        <translation>Commandoscherm sluiten</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Import Data...</source>
+        <translation>Importeer data...</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save Workspace...</source>
+        <translation>Werkruimte opslaan...</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Preferences...</source>
+        <translation>Voorkeuren...</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Page Setup...</source>
+        <translation>Pagina instellingen...</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Print</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Print Selection...</source>
+        <translation>Print selectie...</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Exit</source>
+        <translation>Sluiten</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Edit</source>
+        <translation>B&amp;ewerken</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Undo</source>
+        <translation>Ongedaan maken</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Redo</source>
+        <translation>Herhalen</translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Cut</source>
+        <translation>Knippen</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Copy</source>
+        <translation>Kopiëren</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation>Plakken</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste To Workspace...</source>
+        <translation>Plak naar werkruimte...</translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Select All</source>
+        <translation>Alles selecteren</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Delete</source>
+        <translation>Verwijderen</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Find...</source>
+        <translation>Vind...</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Find Files...</source>
+        <translation>Vind bestanden...</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Clear Command Window</source>
+        <translation>Wis commandoscherm</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Clear Command History</source>
+        <translation>Wis commandogeschiedenis</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Clear Workspace</source>
+        <translation>Wis werkruimte</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>De&amp;bug</source>
+        <translation>De&amp;buggen</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Step</source>
+        <translation>Stap</translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step in</source>
+        <translation>Stap in</translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step out</source>
+        <translation>Stap uit</translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Continue</source>
+        <translation>Doorgaan</translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <source>Exit Debug Mode</source>
+        <translation>Debuggen sluiten</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <source>&amp;Desktop</source>
+        <translation>Bureaubla&amp;d</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Load workspace</source>
+        <translation>Werkruimte laden</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Window</source>
+        <translation>Scherm</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Show Command Window</source>
+        <translation>Commandoscherm weergeven</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Command History</source>
+        <translation>Commandogeschiedenis weergeven</translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Current Directory</source>
+        <translation>Huidige map weergeven</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Workspace</source>
+        <translation>Werkruimte weergeven</translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Editor</source>
+        <translation>Editor weergeven</translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Documentation</source>
+        <translation>Documentatie weergeven</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Command Window</source>
+        <translation>Commandoscherm</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation>Commandogeschiedenis</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Current Directory</source>
+        <translation>Huidige map</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Workspace</source>
+        <translation>Werkruimte</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Editor</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Documentation</source>
+        <translation>Documentatie</translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Reset Windows</source>
+        <translation>Reset schermen</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Help</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Report Bug</source>
+        <translation>Probleem rapporteren</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Agora</source>
+        <translation>Bezoek Agora</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Octave Forge</source>
+        <translation>Bezoek Octave Forge</translation>
+    </message>
+    <message>
+        <location line="+20"/>
+        <source>Current Directory:</source>
+        <translation>Huidige map:</translation>
+    </message>
+</context>
+<context>
+    <name>settings_dialog</name>
+    <message>
+        <location filename="../src/settings-dialog.ui" line="+29"/>
+        <location filename="../src/ui-settings-dialog.h" line="+461"/>
+        <source>Settings</source>
+        <translation>Instellingen</translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+5"/>
+        <source>General</source>
+        <translation>Algemeen</translation>
+    </message>
+    <message>
+        <location line="+18"/>
+        <location filename="../src/ui-settings-dialog.h" line="-4"/>
+        <source>Icon set for dock widget</source>
+        <translation>Icoon ingesteld voor dock widget</translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Octave logo only</source>
+        <translation>Alleen Octave logo</translation>
+    </message>
+    <message>
+        <location line="+16"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Letter icons</source>
+        <translation>Letter iconen</translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Graphic  icons</source>
+        <translation>Grafische iconen</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+11"/>
+        <source>Editor</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font</source>
+        <translation>Lettertype</translation>
+    </message>
+    <message>
+        <location line="-130"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font Size</source>
+        <translation>Lettergrootte</translation>
+    </message>
+    <message>
+        <location line="-109"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <source>Show line numbers</source>
+        <translation>Regelnummers weergeven</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Highlight current line</source>
+        <translation>Markeer huidige regel</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Code completion</source>
+        <translation>Automatisch aanvullen</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show complete path in window title</source>
+        <translation>Hele pad in schermtitel weergeven</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Restore tabs from previous session on startup</source>
+        <translation>Tabbladen van vorige sessie herladen bij opstarten</translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Use custom file editor:</source>
+        <translation>Gebruik andere bestandeditor:</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>emacs</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+6"/>
+        <source>Terminal</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+62"/>
+        <location filename="../src/ui-settings-dialog.h" line="-2"/>
+        <source>Cursor type:</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Cursor blinking</source>
+        <translation>Cursor knipperen</translation>
+    </message>
+    <message>
+        <location line="+36"/>
+        <location filename="../src/ui-settings-dialog.h" line="+8"/>
+        <source>File Browser</source>
+        <translation>Bestandsbrowser</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-6"/>
+        <source>Show filenames</source>
+        <translation>Bestandsnamen weergeven</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file size</source>
+        <translation>Bestandsgrootte weergeven</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file type</source>
+        <translation>Bestandstype weergeven</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show date of last modification</source>
+        <translation>Datum van laatste aanpassing weergeven</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show hidden files</source>
+        <translation>Verborgen bestanden weergeven</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Alternating row colors</source>
+        <translation>Afwisselende regelkleuren</translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+13"/>
+        <source>Network</source>
+        <translation>Netwerk</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-11"/>
+        <source>Use proxy server</source>
+        <translation>Gebruik proxyserver</translation>
+    </message>
+    <message>
+        <location line="+12"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Proxy Type:</source>
+        <translation>Proxy type:</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+3"/>
+        <source>HttpProxy</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Socks5Proxy</source>
+        <translation></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+2"/>
+        <source>Hostname:</source>
+        <translation>Hostnaam:</translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Port:</source>
+        <translation>Poort:</translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Username:</source>
+        <translation>Gebruikersnaam:</translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Password:</source>
+        <translation>Wachtwoord:</translation>
+    </message>
+</context>
+<context>
+    <name>terminal_dock_widget</name>
+    <message>
+        <location filename="../src/terminal-dockwidget.cc" line="+34"/>
+        <source>Command Window</source>
+        <translation>Commandoscherm</translation>
+    </message>
+</context>
+<context>
+    <name>webinfo</name>
+    <message>
+        <location filename="../src/qtinfo/webinfo.cc" line="+74"/>
+        <source>Type here and press &apos;Return&apos; to search</source>
+        <translation>Typ hier en druk op &apos;Enter&apos; om te zoeken</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Global search</source>
+        <translation>Globaal zoeken</translation>
+    </message>
+</context>
+<context>
+    <name>welcome_wizard</name>
+    <message>
+        <location filename="../src/welcome-wizard.ui" line="+26"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+286"/>
+        <source>Welcome to GNU Octave</source>
+        <translation>Welkom bij GNU Octave</translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>It appears that you have launched Octave GUI for the first time on this computer, since no configuration file could be found at &apos;~/.octave-gui&apos;. This wizard will guide you through the essential settings you should make before you can start using Octave GUI. If you want to transfer your settings you have previously made just close this dialog and copy over the settings file to your home folder. The presence of that file will automatically be detected and will skip this wizard. IMPORTANT: This wizard is not fully functional yet. Just click your way to the end and it will create a standard settings file.</source>
+        <translation>Het lijkt erop dat je de Octave GUI voor de eerste keer opstart op deze computer, omdat er geen configuratiebestand in &apos;~/.octave-gui&apos; gevonden is. Deze wizard zal je begeleiden tijdens het invullen van de belangrijkste instellingen die je zou moeten doen voordat je Octave GUI kan gebruiken. Als je eerder gemaakte instellingen wilt overzetten, sluit dan dit scherm en kopieer het configuratiebestand naar je home map. De aanwezigheid van het bestand zal automatisch gedetecteerd worden en deze wizard overslaan. BELANGRIJK: Deze wizard is nog niet volledig functioneel. Klik door tot het einde voor standaardinstellingen.</translation>
+    </message>
+    <message>
+        <location line="+41"/>
+        <location line="+50"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <source>Next</source>
+        <translation>Volgende</translation>
+    </message>
+    <message>
+        <location line="-124"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location line="+87"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-5"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+5"/>
+        <source>Previous</source>
+        <translation>Vorige</translation>
+    </message>
+    <message>
+        <location line="-45"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-3"/>
+        <source>Welcome to Octave!</source>
+        <translation>Welkom bij Octave!</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>This is the development version of Octave with the first official GUI.</source>
+        <translation>Dit is de ontwikkelvariant van Octave met de eerste officiële GUI.</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>You seem to run Octave GUI for the first time on this computer. This assistant will help you to configure this software installation. Click &apos;Finish&apos; to write a configuration file and launch Octave GUI.</source>
+        <translation>Het lijkt erop dat je de Octave GUI voor de eerste keer uitvoert op deze computer. Deze assistent zal je helpen het programma te configureren. Klik &apos;Voltooien&apos; om een configuratiebestand te maken en de Octave GUI te starten.</translation>
+    </message>
+    <message>
+        <location line="+48"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+2"/>
+        <source>Finish</source>
+        <translation>Voltooien</translation>
+    </message>
+</context>
+<context>
+    <name>workspace_model</name>
+    <message>
+        <location filename="../src/workspace-model.cc" line="+42"/>
+        <source>Name</source>
+        <translation>Naam</translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Class</source>
+        <translation>Klasse</translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Dimension</source>
+        <translation>Dimensie</translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Value</source>
+        <translation>Waarde</translation>
+    </message>
+</context>
+<context>
+    <name>workspace_view</name>
+    <message>
+        <location filename="../src/workspace-view.cc" line="+39"/>
+        <source>Workspace</source>
+        <translation>Werkruimte</translation>
+    </message>
+</context>
+</TS>
new file mode 100644
--- /dev/null
+++ b/libgui/languages/pt_BR.ts
@@ -0,0 +1,1066 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE TS>
+<TS version="2.0" language="pt_BR" sourcelanguage="en">
+<context>
+    <name>documentation_dock_widget</name>
+    <message>
+        <location filename="../src/documentation-dockwidget.cc" line="+34"/>
+        <source>Documentation</source>
+        <translation type="unfinished">Documentação</translation>
+    </message>
+</context>
+<context>
+    <name>file_editor</name>
+    <message>
+        <location filename="../src/m-editor/file-editor.cc" line="+146"/>
+        <location line="+38"/>
+        <location line="+43"/>
+        <location line="+26"/>
+        <source>Octave Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-106"/>
+        <source>File %1 is already open in the editor.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+38"/>
+        <source>Could not open file %1 for read:
+%2.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+43"/>
+        <source>File not saved! A file with the selected name
+%1
+is already open in the editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>The associated file editor tab has disappeared.  It was likely closed by some means.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+141"/>
+        <source>&amp;%1 %2</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+130"/>
+        <source>&amp;New File</source>
+        <translation type="unfinished">&amp;Novo Arquivo</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Open File</source>
+        <translation type="unfinished">&amp;Abrir Arquivo</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Save File</source>
+        <translation type="unfinished">&amp;Salvar Arquivo</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save File &amp;As</source>
+        <translation type="unfinished">Salvar Arquivo &amp;Como</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Undo</source>
+        <translation type="unfinished">&amp;Desfazer</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Redo</source>
+        <translation type="unfinished">&amp;Refazer</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Cu&amp;t</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Next Bookmark</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Pre&amp;vious Bookmark</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Toggle &amp;Bookmark</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Remove All Bookmarks</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Next breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Pre&amp;vious breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Toggle &amp;breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Remove All breakpoints</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Comment Selected Text</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Uncomment Selected Text</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Find and Replace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Save File And Run</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+51"/>
+        <source>&amp;File</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Open &amp;Recent</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>&amp;Edit</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+19"/>
+        <source>&amp;Debug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+9"/>
+        <source>&amp;Run</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>file_editor_tab</name>
+    <message>
+        <location filename="../src/m-editor/file-editor-tab.cc" line="+687"/>
+        <location line="+102"/>
+        <location line="+98"/>
+        <location line="+63"/>
+        <location line="+14"/>
+        <source>Octave Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-276"/>
+        <source>The file &apos;%1&apos; has been modified. Do you want to save the changes?</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+102"/>
+        <source>Could not open file %1 for write:
+%2.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+98"/>
+        <source>File not saved!  You&apos;ve selected a file name
+
+     %1
+
+which is the same as the current file name.  Use Save to overwrite.  (Could allow overwriting, with message, if that is what folks want.)</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+63"/>
+        <source>It seems that &apos;%1&apos; has been modified by another application. Do you want to reload it?</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+14"/>
+        <source>It seems that &apos;%1&apos; has been deleted or renamed. Do you want to save it now?</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>files_dock_widget</name>
+    <message>
+        <location filename="../src/files-dockwidget.cc" line="+43"/>
+        <source>Current Directory</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Move up one directory.</source>
+        <translation type="unfinished">Subir um diretório.</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Enter the path or filename.</source>
+        <translation type="unfinished">Digite o caminho ou o nome do arquivo.</translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>Doubleclick a file to open it.</source>
+        <translation type="unfinished">Clique duas vezes num arquivo para abrí-lo.</translation>
+    </message>
+</context>
+<context>
+    <name>find_dialog</name>
+    <message>
+        <location filename="../src/m-editor/find-dialog.cc" line="+58"/>
+        <source>Find &amp;what:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Re&amp;place with:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Match &amp;case</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search from &amp;start</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Wrap while searching</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Find Next</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Replace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Replace &amp;All</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;More</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>&amp;Whole words</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Regular E&amp;xpressions</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search &amp;backward</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search se&amp;lection</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>history_dock_widget</name>
+    <message>
+        <location filename="../src/history-dockwidget.cc" line="+55"/>
+        <source>Doubleclick a command to transfer it to the terminal.</source>
+        <translation type="unfinished">Clique duas vezes num comando para transferí-lo ao terminal.</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Enter text to filter the command history.</source>
+        <translation type="unfinished">Digite um texto para filtrar o hitórico de comandos.</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation type="unfinished">Histórico de Comandos</translation>
+    </message>
+    <message>
+        <location line="+42"/>
+        <source>Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Evaluate</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>lexer_octave_gui</name>
+    <message>
+        <location filename="../src/m-editor/lexer-octave-gui.cc" line="+145"/>
+        <source>Default</source>
+        <translation type="unfinished">Padrão</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Comment</source>
+        <translation type="unfinished">Comentário</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Command</source>
+        <translation type="unfinished">Comando</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Number</source>
+        <translation type="unfinished">Número</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Keyword</source>
+        <translation type="unfinished">Palavra-Chave</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Single-quoted string</source>
+        <translation type="unfinished">String com aspas simples</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Operator</source>
+        <translation type="unfinished">Operador</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Identifier</source>
+        <translation type="unfinished">Identificador</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Double-quoted string</source>
+        <translation type="unfinished">String com aspas duplas</translation>
+    </message>
+</context>
+<context>
+    <name>main_window</name>
+    <message>
+        <location filename="../src/main-window.cc" line="+135"/>
+        <source>Save Workspace</source>
+        <translation type="unfinished">Salvar ambiente de trabalho</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Load Workspace</source>
+        <translation type="unfinished">Carregar ambiente de trabalho</translation>
+    </message>
+    <message>
+        <location line="+155"/>
+        <source>Set working direcotry</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+186"/>
+        <location line="+381"/>
+        <source>About Octave</source>
+        <translation type="unfinished">Sobre o Octave</translation>
+    </message>
+    <message>
+        <location line="-290"/>
+        <source>View the variables in the active workspace.</source>
+        <translation type="unfinished">Visualizar variáveis no ambiente de trabalho.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse and search the command history.</source>
+        <translation type="unfinished">Pesquise no histórico de comandos.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse your files.</source>
+        <translation type="unfinished">Procure seus arquivos.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>See the documentation for help.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+39"/>
+        <source>&amp;File</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>New</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Script</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Function</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Class</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Enumeration</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Figure</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Variable</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Model</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>GUI</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Open...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Close Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Import Data...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save Workspace...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Preferences...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Page Setup...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Print</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Print Selection...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Exit</source>
+        <translation type="unfinished">Sair</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Edit</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Undo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Redo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Cut</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste To Workspace...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Select All</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Delete</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Find...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Find Files...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Clear Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Clear Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Clear Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>De&amp;bug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Step</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step in</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step out</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Continue</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <source>Exit Debug Mode</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <source>&amp;Desktop</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Load workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Show Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Current Directory</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Documentation</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation type="unfinished">Histórico de Comandos</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Current Directory</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Workspace</source>
+        <translation type="unfinished">Ambiente de trabalho</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Editor</source>
+        <translation type="unfinished">Editor</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Documentation</source>
+        <translation type="unfinished">Documentação</translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Reset Windows</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Help</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Report Bug</source>
+        <translation type="unfinished">Reportar Bug</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Agora</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Octave Forge</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+20"/>
+        <source>Current Directory:</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>settings_dialog</name>
+    <message>
+        <location filename="../src/settings-dialog.ui" line="+29"/>
+        <location filename="../src/ui-settings-dialog.h" line="+461"/>
+        <source>Settings</source>
+        <translation type="unfinished">Configurações</translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+5"/>
+        <source>General</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+18"/>
+        <location filename="../src/ui-settings-dialog.h" line="-4"/>
+        <source>Icon set for dock widget</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Octave logo only</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+16"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Letter icons</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Graphic  icons</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+11"/>
+        <source>Editor</source>
+        <translation type="unfinished">Editor</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-130"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font Size</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-109"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <source>Show line numbers</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Highlight current line</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Code completion</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show complete path in window title</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Restore tabs from previous session on startup</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Use custom file editor:</source>
+        <translation type="unfinished">Usar editor de arquivos personalizado:</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>emacs</source>
+        <translation type="unfinished">emacs</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+6"/>
+        <source>Terminal</source>
+        <translation type="unfinished">Terminal</translation>
+    </message>
+    <message>
+        <location line="+62"/>
+        <location filename="../src/ui-settings-dialog.h" line="-2"/>
+        <source>Cursor type:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Cursor blinking</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+36"/>
+        <location filename="../src/ui-settings-dialog.h" line="+8"/>
+        <source>File Browser</source>
+        <translation type="unfinished">Navegador de Arquivos</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-6"/>
+        <source>Show filenames</source>
+        <translation type="unfinished">Mostrar nomes de arquivo</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file size</source>
+        <translation type="unfinished">Mostrar tamanho do arquivo</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file type</source>
+        <translation type="unfinished">Mostrar tipo do arquivo</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show date of last modification</source>
+        <translation type="unfinished">Mostrar data de última modificação</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show hidden files</source>
+        <translation type="unfinished">Mostrar arquivos ocultos</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Alternating row colors</source>
+        <translation type="unfinished">Alternar cores das linhas</translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+13"/>
+        <source>Network</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-11"/>
+        <source>Use proxy server</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+12"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Proxy Type:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+3"/>
+        <source>HttpProxy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Socks5Proxy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+2"/>
+        <source>Hostname:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Port:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Username:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Password:</source>
+        <translation type="unfinished">Senha:</translation>
+    </message>
+</context>
+<context>
+    <name>terminal_dock_widget</name>
+    <message>
+        <location filename="../src/terminal-dockwidget.cc" line="+34"/>
+        <source>Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>webinfo</name>
+    <message>
+        <location filename="../src/qtinfo/webinfo.cc" line="+74"/>
+        <source>Type here and press &apos;Return&apos; to search</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Global search</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>welcome_wizard</name>
+    <message>
+        <location filename="../src/welcome-wizard.ui" line="+26"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+286"/>
+        <source>Welcome to GNU Octave</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>It appears that you have launched Octave GUI for the first time on this computer, since no configuration file could be found at &apos;~/.octave-gui&apos;. This wizard will guide you through the essential settings you should make before you can start using Octave GUI. If you want to transfer your settings you have previously made just close this dialog and copy over the settings file to your home folder. The presence of that file will automatically be detected and will skip this wizard. IMPORTANT: This wizard is not fully functional yet. Just click your way to the end and it will create a standard settings file.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+41"/>
+        <location line="+50"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <source>Next</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-124"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location line="+87"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-5"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+5"/>
+        <source>Previous</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-45"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-3"/>
+        <source>Welcome to Octave!</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>This is the development version of Octave with the first official GUI.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>You seem to run Octave GUI for the first time on this computer. This assistant will help you to configure this software installation. Click &apos;Finish&apos; to write a configuration file and launch Octave GUI.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+48"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+2"/>
+        <source>Finish</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>workspace_model</name>
+    <message>
+        <location filename="../src/workspace-model.cc" line="+42"/>
+        <source>Name</source>
+        <translation type="unfinished">Nome</translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Class</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Dimension</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Value</source>
+        <translation type="unfinished">Valor</translation>
+    </message>
+</context>
+<context>
+    <name>workspace_view</name>
+    <message>
+        <location filename="../src/workspace-view.cc" line="+39"/>
+        <source>Workspace</source>
+        <translation type="unfinished">Ambiente de trabalho</translation>
+    </message>
+</context>
+</TS>
new file mode 100644
--- /dev/null
+++ b/libgui/languages/ru_RU.ts
@@ -0,0 +1,1066 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE TS>
+<TS version="2.0" language="ru_RU">
+<context>
+    <name>documentation_dock_widget</name>
+    <message>
+        <location filename="../src/documentation-dockwidget.cc" line="+34"/>
+        <source>Documentation</source>
+        <translation type="unfinished">ДокументациÑ</translation>
+    </message>
+</context>
+<context>
+    <name>file_editor</name>
+    <message>
+        <location filename="../src/m-editor/file-editor.cc" line="+146"/>
+        <location line="+38"/>
+        <location line="+43"/>
+        <location line="+26"/>
+        <source>Octave Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-106"/>
+        <source>File %1 is already open in the editor.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+38"/>
+        <source>Could not open file %1 for read:
+%2.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+43"/>
+        <source>File not saved! A file with the selected name
+%1
+is already open in the editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>The associated file editor tab has disappeared.  It was likely closed by some means.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+141"/>
+        <source>&amp;%1 %2</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+130"/>
+        <source>&amp;New File</source>
+        <translation type="unfinished">Созд&amp;ать</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Open File</source>
+        <translation type="unfinished">&amp;Открыть</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Save File</source>
+        <translation type="unfinished">&amp;Сохранить</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save File &amp;As</source>
+        <translation type="unfinished">Сохранить &amp;как</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Undo</source>
+        <translation type="unfinished">О&amp;тменить</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Redo</source>
+        <translation type="unfinished">&amp;Повторить</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Copy</source>
+        <translation type="unfinished">&amp;Копировать</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Cu&amp;t</source>
+        <translation type="unfinished">Вы&amp;резать</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Next Bookmark</source>
+        <translation type="unfinished">С&amp;Ð»ÐµÐ´ÑƒÑŽÑ‰Ð°Ñ Ð·Ð°ÐºÐ»Ð°Ð´ÐºÐ°</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Pre&amp;vious Bookmark</source>
+        <translation type="unfinished">Пр&amp;ÐµÐ´Ñ‹Ð´ÑƒÑ‰Ð°Ñ Ð·Ð°ÐºÐ»Ð°Ð´ÐºÐ°</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Toggle &amp;Bookmark</source>
+        <translation type="unfinished">&amp;УÑтановить/ÑнÑть закладку</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Remove All Bookmarks</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Next breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Pre&amp;vious breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Toggle &amp;breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Remove All breakpoints</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Comment Selected Text</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Uncomment Selected Text</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Find and Replace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Save File And Run</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+51"/>
+        <source>&amp;File</source>
+        <translation type="unfinished">&amp;Файл</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Open &amp;Recent</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>&amp;Edit</source>
+        <translation type="unfinished">&amp;Правка</translation>
+    </message>
+    <message>
+        <location line="+19"/>
+        <source>&amp;Debug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+9"/>
+        <source>&amp;Run</source>
+        <translation type="unfinished">&amp;ЗапуÑк</translation>
+    </message>
+</context>
+<context>
+    <name>file_editor_tab</name>
+    <message>
+        <location filename="../src/m-editor/file-editor-tab.cc" line="+687"/>
+        <location line="+102"/>
+        <location line="+98"/>
+        <location line="+63"/>
+        <location line="+14"/>
+        <source>Octave Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-276"/>
+        <source>The file &apos;%1&apos; has been modified. Do you want to save the changes?</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+102"/>
+        <source>Could not open file %1 for write:
+%2.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+98"/>
+        <source>File not saved!  You&apos;ve selected a file name
+
+     %1
+
+which is the same as the current file name.  Use Save to overwrite.  (Could allow overwriting, with message, if that is what folks want.)</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+63"/>
+        <source>It seems that &apos;%1&apos; has been modified by another application. Do you want to reload it?</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+14"/>
+        <source>It seems that &apos;%1&apos; has been deleted or renamed. Do you want to save it now?</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>files_dock_widget</name>
+    <message>
+        <location filename="../src/files-dockwidget.cc" line="+43"/>
+        <source>Current Directory</source>
+        <translation type="unfinished">Текущий каталог</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Move up one directory.</source>
+        <translation type="unfinished">Перейти на уровень выше.</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Enter the path or filename.</source>
+        <translation type="unfinished">Введите путь или Ð¸Ð¼Ñ Ñ„Ð°Ð¹Ð»Ð°.</translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>Doubleclick a file to open it.</source>
+        <translation type="unfinished">Двойной щелчок по файлу откроет его.</translation>
+    </message>
+</context>
+<context>
+    <name>find_dialog</name>
+    <message>
+        <location filename="../src/m-editor/find-dialog.cc" line="+58"/>
+        <source>Find &amp;what:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Re&amp;place with:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Match &amp;case</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search from &amp;start</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Wrap while searching</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Find Next</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Replace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Replace &amp;All</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;More</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>&amp;Whole words</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Regular E&amp;xpressions</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search &amp;backward</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search se&amp;lection</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>history_dock_widget</name>
+    <message>
+        <location filename="../src/history-dockwidget.cc" line="+55"/>
+        <source>Doubleclick a command to transfer it to the terminal.</source>
+        <translation type="unfinished">Двойной щелчок по команде перенеÑёт её в командную Ñтроку.</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Enter text to filter the command history.</source>
+        <translation type="unfinished">Введите текÑÑ‚ Ð´Ð»Ñ Ñ„Ð¸Ð»ÑŒÑ‚Ñ€Ð°Ñ†Ð¸Ð¸ выполненных команд.</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation type="unfinished">Журнал выполненных команд</translation>
+    </message>
+    <message>
+        <location line="+42"/>
+        <source>Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Evaluate</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>lexer_octave_gui</name>
+    <message>
+        <location filename="../src/m-editor/lexer-octave-gui.cc" line="+145"/>
+        <source>Default</source>
+        <translation type="unfinished">По умолчанию</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Comment</source>
+        <translation type="unfinished">Комментарий</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Command</source>
+        <translation type="unfinished">Команда</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Number</source>
+        <translation type="unfinished">ЧиÑло</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Keyword</source>
+        <translation type="unfinished">Зарезервированное Ñлово</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Single-quoted string</source>
+        <translation type="unfinished">Строка в одинарных кавычках</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Operator</source>
+        <translation type="unfinished">Оператор</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Identifier</source>
+        <translation type="unfinished">Идентификатор</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Double-quoted string</source>
+        <translation type="unfinished">Строка в двойных кавычках</translation>
+    </message>
+</context>
+<context>
+    <name>main_window</name>
+    <message>
+        <location filename="../src/main-window.cc" line="+135"/>
+        <source>Save Workspace</source>
+        <translation type="unfinished">Сохранить облаÑть переменных</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Load Workspace</source>
+        <translation type="unfinished">Загрузить облаÑть переменных</translation>
+    </message>
+    <message>
+        <location line="+155"/>
+        <source>Set working direcotry</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+186"/>
+        <location line="+381"/>
+        <source>About Octave</source>
+        <translation type="unfinished">Об Octave</translation>
+    </message>
+    <message>
+        <location line="-290"/>
+        <source>View the variables in the active workspace.</source>
+        <translation type="unfinished">ПроÑмотр Ñодержимого текущей облаÑти переменных.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse and search the command history.</source>
+        <translation type="unfinished">ПроÑмотр и поиÑк в журнале выполненных команд.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse your files.</source>
+        <translation type="unfinished">ПроÑмотр файлов.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>See the documentation for help.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+39"/>
+        <source>&amp;File</source>
+        <translation type="unfinished">&amp;Файл</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>New</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Script</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Function</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Class</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Enumeration</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Figure</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Variable</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Model</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>GUI</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Open...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Close Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Import Data...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save Workspace...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Preferences...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Page Setup...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Print</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Print Selection...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Exit</source>
+        <translation type="unfinished">Выход</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Edit</source>
+        <translation type="unfinished">&amp;Правка</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Undo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Redo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Cut</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste To Workspace...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Select All</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Delete</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Find...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Find Files...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Clear Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Clear Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Clear Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>De&amp;bug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Step</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step in</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step out</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Continue</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <source>Exit Debug Mode</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <source>&amp;Desktop</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Load workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Show Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Current Directory</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Documentation</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation type="unfinished">Журнал выполненных команд</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Current Directory</source>
+        <translation type="unfinished">Текущий каталог</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Workspace</source>
+        <translation type="unfinished">ОблаÑть переменных</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Editor</source>
+        <translation type="unfinished">Редактор</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Documentation</source>
+        <translation type="unfinished">ДокументациÑ</translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Reset Windows</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Help</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Report Bug</source>
+        <translation type="unfinished">Сообщить об ошибке</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Agora</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Octave Forge</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+20"/>
+        <source>Current Directory:</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>settings_dialog</name>
+    <message>
+        <location filename="../src/settings-dialog.ui" line="+29"/>
+        <location filename="../src/ui-settings-dialog.h" line="+461"/>
+        <source>Settings</source>
+        <translation type="unfinished">Параметры</translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+5"/>
+        <source>General</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+18"/>
+        <location filename="../src/ui-settings-dialog.h" line="-4"/>
+        <source>Icon set for dock widget</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Octave logo only</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+16"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Letter icons</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Graphic  icons</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+11"/>
+        <source>Editor</source>
+        <translation type="unfinished">Редактор</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-130"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font Size</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-109"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <source>Show line numbers</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Highlight current line</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Code completion</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show complete path in window title</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Restore tabs from previous session on startup</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Use custom file editor:</source>
+        <translation type="unfinished">Выбрать редактор:</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>emacs</source>
+        <translation type="unfinished">emacs</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+6"/>
+        <source>Terminal</source>
+        <translation type="unfinished">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð½Ð°Ñ Ñтрока</translation>
+    </message>
+    <message>
+        <location line="+62"/>
+        <location filename="../src/ui-settings-dialog.h" line="-2"/>
+        <source>Cursor type:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Cursor blinking</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+36"/>
+        <location filename="../src/ui-settings-dialog.h" line="+8"/>
+        <source>File Browser</source>
+        <translation type="unfinished">Файловый менеджер</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-6"/>
+        <source>Show filenames</source>
+        <translation type="unfinished">Показывать имена файлов</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file size</source>
+        <translation type="unfinished">Показывать размер файлов</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file type</source>
+        <translation type="unfinished">Показывать типы файлов</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show date of last modification</source>
+        <translation type="unfinished">Показывать дату поÑледнего изменениÑ</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show hidden files</source>
+        <translation type="unfinished">Показывать Ñкрытые файлы</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Alternating row colors</source>
+        <translation type="unfinished">ЧередующиеÑÑ Ñ†Ð²ÐµÑ‚Ð° Ñтрок</translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+13"/>
+        <source>Network</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-11"/>
+        <source>Use proxy server</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+12"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Proxy Type:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+3"/>
+        <source>HttpProxy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Socks5Proxy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+2"/>
+        <source>Hostname:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Port:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Username:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Password:</source>
+        <translation type="unfinished">Пароль:</translation>
+    </message>
+</context>
+<context>
+    <name>terminal_dock_widget</name>
+    <message>
+        <location filename="../src/terminal-dockwidget.cc" line="+34"/>
+        <source>Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>webinfo</name>
+    <message>
+        <location filename="../src/qtinfo/webinfo.cc" line="+74"/>
+        <source>Type here and press &apos;Return&apos; to search</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Global search</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>welcome_wizard</name>
+    <message>
+        <location filename="../src/welcome-wizard.ui" line="+26"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+286"/>
+        <source>Welcome to GNU Octave</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>It appears that you have launched Octave GUI for the first time on this computer, since no configuration file could be found at &apos;~/.octave-gui&apos;. This wizard will guide you through the essential settings you should make before you can start using Octave GUI. If you want to transfer your settings you have previously made just close this dialog and copy over the settings file to your home folder. The presence of that file will automatically be detected and will skip this wizard. IMPORTANT: This wizard is not fully functional yet. Just click your way to the end and it will create a standard settings file.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+41"/>
+        <location line="+50"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <source>Next</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-124"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location line="+87"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-5"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+5"/>
+        <source>Previous</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-45"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-3"/>
+        <source>Welcome to Octave!</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>This is the development version of Octave with the first official GUI.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>You seem to run Octave GUI for the first time on this computer. This assistant will help you to configure this software installation. Click &apos;Finish&apos; to write a configuration file and launch Octave GUI.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+48"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+2"/>
+        <source>Finish</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>workspace_model</name>
+    <message>
+        <location filename="../src/workspace-model.cc" line="+42"/>
+        <source>Name</source>
+        <translation type="unfinished">Идентификатор</translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Class</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Dimension</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Value</source>
+        <translation type="unfinished">Значение</translation>
+    </message>
+</context>
+<context>
+    <name>workspace_view</name>
+    <message>
+        <location filename="../src/workspace-view.cc" line="+39"/>
+        <source>Workspace</source>
+        <translation type="unfinished">ОблаÑть переменных</translation>
+    </message>
+</context>
+</TS>
new file mode 100644
--- /dev/null
+++ b/libgui/languages/translators
@@ -0,0 +1,12 @@
+# Below Octave GUI translators are listed with their e-mails
+# to be able to inform them about generic translation file changes.
+# The gerenic file that can be used as a template for new
+# translation files is en_US.ts
+be_BY Mihas Varantsou <meequz@gmail.com>
+de_DE Jacob Dawid <jacob.dawid@googlemail.com>
+en_US Jacob Dawid <jacob.dawid@googlemail.com>
+es_ES Valentin Ortega-Clavero <arcanos3030@gmail.com>
+pt_BE Júlio Hoffimann Mendes <julio.hoffimann@gmail.com>
+ru_RU Andriy Shinkarchuck <adriano32.gnu@gmail.com>
+uk_UA Andriy Shinkarchuck <adriano32.gnu@gmail.com>
+nl_NL Sander van Rijn <svr003@gmail.com>
new file mode 100644
--- /dev/null
+++ b/libgui/languages/uk_UA.ts
@@ -0,0 +1,1066 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE TS>
+<TS version="2.0" language="uk_UA">
+<context>
+    <name>documentation_dock_widget</name>
+    <message>
+        <location filename="../src/documentation-dockwidget.cc" line="+34"/>
+        <source>Documentation</source>
+        <translation type="unfinished">ДокументаціÑ</translation>
+    </message>
+</context>
+<context>
+    <name>file_editor</name>
+    <message>
+        <location filename="../src/m-editor/file-editor.cc" line="+146"/>
+        <location line="+38"/>
+        <location line="+43"/>
+        <location line="+26"/>
+        <source>Octave Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-106"/>
+        <source>File %1 is already open in the editor.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+38"/>
+        <source>Could not open file %1 for read:
+%2.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+43"/>
+        <source>File not saved! A file with the selected name
+%1
+is already open in the editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>The associated file editor tab has disappeared.  It was likely closed by some means.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+141"/>
+        <source>&amp;%1 %2</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+130"/>
+        <source>&amp;New File</source>
+        <translation type="unfinished">&amp;Створити</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Open File</source>
+        <translation type="unfinished">&amp;Відкрити</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Save File</source>
+        <translation type="unfinished">&amp;Зберегти</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save File &amp;As</source>
+        <translation type="unfinished">Зберегти &amp;Ñк</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Undo</source>
+        <translation type="unfinished">В&amp;ернути</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Redo</source>
+        <translation type="unfinished">П&amp;овторити</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Copy</source>
+        <translation type="unfinished">&amp;Копіювати</translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Cu&amp;t</source>
+        <translation type="unfinished">Виріза&amp;ти</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Next Bookmark</source>
+        <translation type="unfinished">До &amp;наÑтупної закладки</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Pre&amp;vious Bookmark</source>
+        <translation type="unfinished">До &amp;попередньої закладки</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Toggle &amp;Bookmark</source>
+        <translation type="unfinished">Ð’&amp;Ñтановити/видалити закладку</translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Remove All Bookmarks</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Next breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Pre&amp;vious breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Toggle &amp;breakpoint</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Remove All breakpoints</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Comment Selected Text</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Uncomment Selected Text</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>&amp;Find and Replace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Save File And Run</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+51"/>
+        <source>&amp;File</source>
+        <translation type="unfinished">&amp;Файл</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Open &amp;Recent</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>&amp;Edit</source>
+        <translation type="unfinished">&amp;Правка</translation>
+    </message>
+    <message>
+        <location line="+19"/>
+        <source>&amp;Debug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+9"/>
+        <source>&amp;Run</source>
+        <translation type="unfinished">&amp;ВиконаннÑ</translation>
+    </message>
+</context>
+<context>
+    <name>file_editor_tab</name>
+    <message>
+        <location filename="../src/m-editor/file-editor-tab.cc" line="+687"/>
+        <location line="+102"/>
+        <location line="+98"/>
+        <location line="+63"/>
+        <location line="+14"/>
+        <source>Octave Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-276"/>
+        <source>The file &apos;%1&apos; has been modified. Do you want to save the changes?</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+102"/>
+        <source>Could not open file %1 for write:
+%2.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+98"/>
+        <source>File not saved!  You&apos;ve selected a file name
+
+     %1
+
+which is the same as the current file name.  Use Save to overwrite.  (Could allow overwriting, with message, if that is what folks want.)</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+63"/>
+        <source>It seems that &apos;%1&apos; has been modified by another application. Do you want to reload it?</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+14"/>
+        <source>It seems that &apos;%1&apos; has been deleted or renamed. Do you want to save it now?</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>files_dock_widget</name>
+    <message>
+        <location filename="../src/files-dockwidget.cc" line="+43"/>
+        <source>Current Directory</source>
+        <translation type="unfinished">Поточний каталог</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Move up one directory.</source>
+        <translation type="unfinished">Перейти вгору деревом каталогів.</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Enter the path or filename.</source>
+        <translation type="unfinished">Введіть повний шлÑÑ… до файлу або назву файлу.</translation>
+    </message>
+    <message>
+        <location line="+26"/>
+        <source>Doubleclick a file to open it.</source>
+        <translation type="unfinished">Подвійне ÐºÐ»Ð°Ñ†Ð°Ð½Ð½Ñ Ð²Ñ–Ð´ÐºÑ€Ð¸Ñ” файл.</translation>
+    </message>
+</context>
+<context>
+    <name>find_dialog</name>
+    <message>
+        <location filename="../src/m-editor/find-dialog.cc" line="+58"/>
+        <source>Find &amp;what:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Re&amp;place with:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Match &amp;case</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search from &amp;start</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>&amp;Wrap while searching</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Find Next</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;Replace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Replace &amp;All</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>&amp;More</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>&amp;Whole words</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Regular E&amp;xpressions</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search &amp;backward</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Search se&amp;lection</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>history_dock_widget</name>
+    <message>
+        <location filename="../src/history-dockwidget.cc" line="+55"/>
+        <source>Doubleclick a command to transfer it to the terminal.</source>
+        <translation type="unfinished">Подвійне ÐºÐ»Ð°Ñ†Ð°Ð½Ð½Ñ Ð¿ÐµÑ€ÐµÐ½ÐµÑе команду до командного Ñ€Ñдку.</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Enter text to filter the command history.</source>
+        <translation type="unfinished">Введіть текÑÑ‚ Ð´Ð»Ñ Ñ„Ñ–Ð»ÑŒÑ‚Ñ€ÑƒÐ²Ð°Ð½Ð½Ñ Ñ–Ñторії виконаних команд.</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation type="unfinished">ІÑÑ‚Ð¾Ñ€Ñ–Ñ Ð²Ð¸ÐºÐ¾Ð½Ð°Ð½Ð¸Ñ… команд</translation>
+    </message>
+    <message>
+        <location line="+42"/>
+        <source>Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Evaluate</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>lexer_octave_gui</name>
+    <message>
+        <location filename="../src/m-editor/lexer-octave-gui.cc" line="+145"/>
+        <source>Default</source>
+        <translation type="unfinished">Стандартні налаштуваннÑ</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Comment</source>
+        <translation type="unfinished">Коментар</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Command</source>
+        <translation type="unfinished">Команда</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Number</source>
+        <translation type="unfinished">ЧиÑло</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Keyword</source>
+        <translation type="unfinished">Зарезервоване Ñлово</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Single-quoted string</source>
+        <translation type="unfinished">РÑдок в одинарних лапках</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Operator</source>
+        <translation type="unfinished">Оператор</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Identifier</source>
+        <translation type="unfinished">Ідентифікатор</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Double-quoted string</source>
+        <translation type="unfinished">РÑдок у подвійних лапках</translation>
+    </message>
+</context>
+<context>
+    <name>main_window</name>
+    <message>
+        <location filename="../src/main-window.cc" line="+135"/>
+        <source>Save Workspace</source>
+        <translation type="unfinished">Зберегти облаÑть змінних</translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <source>Load Workspace</source>
+        <translation type="unfinished">Завантажити облаÑть змінних</translation>
+    </message>
+    <message>
+        <location line="+155"/>
+        <source>Set working direcotry</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+186"/>
+        <location line="+381"/>
+        <source>About Octave</source>
+        <translation type="unfinished">Про Octave</translation>
+    </message>
+    <message>
+        <location line="-290"/>
+        <source>View the variables in the active workspace.</source>
+        <translation type="unfinished">ПереглÑд зміÑту поточної облаÑті змінних.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse and search the command history.</source>
+        <translation type="unfinished">ПереглÑд Ñ– пошук Ñеред Ñ–Ñторії виконаних команд.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Browse your files.</source>
+        <translation type="unfinished">ПереглÑнути файли.</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>See the documentation for help.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+39"/>
+        <source>&amp;File</source>
+        <translation type="unfinished">&amp;Файл</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>New</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Script</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Function</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Class</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Enumeration</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Figure</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Variable</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Model</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>GUI</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Open...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Close Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Import Data...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Save Workspace...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Preferences...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Page Setup...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Print</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Print Selection...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Exit</source>
+        <translation type="unfinished">Вийти</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Edit</source>
+        <translation type="unfinished">&amp;Правка</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Undo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Redo</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Cut</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Copy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Paste To Workspace...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Select All</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Delete</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Find...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Find Files...</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Clear Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+3"/>
+        <source>Clear Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Clear Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>De&amp;bug</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Step</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step in</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Step out</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+8"/>
+        <source>Continue</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <source>Exit Debug Mode</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <source>&amp;Desktop</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+1"/>
+        <source>Load workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Show Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Command History</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Current Directory</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <source>Show Workspace</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Editor</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Show Documentation</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <source>Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Command History</source>
+        <translation type="unfinished">ІÑÑ‚Ð¾Ñ€Ñ–Ñ Ð²Ð¸ÐºÐ¾Ð½Ð°Ð½Ð¸Ñ… команд</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Current Directory</source>
+        <translation type="unfinished">Поточний каталог</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Workspace</source>
+        <translation type="unfinished">ОблаÑть змінних</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Editor</source>
+        <translation type="unfinished">Редактор</translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Documentation</source>
+        <translation type="unfinished">ДокументаціÑ</translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <source>Reset Windows</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>&amp;Help</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Report Bug</source>
+        <translation type="unfinished">Повідомити про помилку</translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Agora</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+2"/>
+        <source>Visit Octave Forge</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+20"/>
+        <source>Current Directory:</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>settings_dialog</name>
+    <message>
+        <location filename="../src/settings-dialog.ui" line="+29"/>
+        <location filename="../src/ui-settings-dialog.h" line="+461"/>
+        <source>Settings</source>
+        <translation type="unfinished">ÐалаштуваннÑ</translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+5"/>
+        <source>General</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+18"/>
+        <location filename="../src/ui-settings-dialog.h" line="-4"/>
+        <source>Icon set for dock widget</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Octave logo only</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+16"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Letter icons</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Graphic  icons</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+11"/>
+        <source>Editor</source>
+        <translation type="unfinished">Редактор</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-130"/>
+        <location line="+147"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <location line="+10"/>
+        <source>Font Size</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-109"/>
+        <location filename="../src/ui-settings-dialog.h" line="-9"/>
+        <source>Show line numbers</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Highlight current line</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Code completion</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show complete path in window title</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Restore tabs from previous session on startup</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Use custom file editor:</source>
+        <translation type="unfinished">ВикориÑтовувати інший редактор:</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>emacs</source>
+        <translation type="unfinished">emacs</translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-settings-dialog.h" line="+6"/>
+        <source>Terminal</source>
+        <translation type="unfinished">Командний Ñ€Ñдок</translation>
+    </message>
+    <message>
+        <location line="+62"/>
+        <location filename="../src/ui-settings-dialog.h" line="-2"/>
+        <source>Cursor type:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+27"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Cursor blinking</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+36"/>
+        <location filename="../src/ui-settings-dialog.h" line="+8"/>
+        <source>File Browser</source>
+        <translation type="unfinished">Файловий менеджер</translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-6"/>
+        <source>Show filenames</source>
+        <translation type="unfinished">Показувати назви файлів</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file size</source>
+        <translation type="unfinished">Показувати розмір файлів</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show file type</source>
+        <translation type="unfinished">Показувати типи файлів</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show date of last modification</source>
+        <translation type="unfinished">Показувати дату оÑтанньої зміни</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Show hidden files</source>
+        <translation type="unfinished">Показувати приховані файли</translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Alternating row colors</source>
+        <translation type="unfinished">Чергувати колір Ñ€Ñдків</translation>
+    </message>
+    <message>
+        <location line="+21"/>
+        <location filename="../src/ui-settings-dialog.h" line="+13"/>
+        <source>Network</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+6"/>
+        <location filename="../src/ui-settings-dialog.h" line="-11"/>
+        <source>Use proxy server</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+12"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Proxy Type:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+3"/>
+        <source>HttpProxy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+5"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Socks5Proxy</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+11"/>
+        <location filename="../src/ui-settings-dialog.h" line="+2"/>
+        <source>Hostname:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Port:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Username:</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+17"/>
+        <location filename="../src/ui-settings-dialog.h" line="+1"/>
+        <source>Password:</source>
+        <translation type="unfinished">Пароль:</translation>
+    </message>
+</context>
+<context>
+    <name>terminal_dock_widget</name>
+    <message>
+        <location filename="../src/terminal-dockwidget.cc" line="+34"/>
+        <source>Command Window</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>webinfo</name>
+    <message>
+        <location filename="../src/qtinfo/webinfo.cc" line="+74"/>
+        <source>Type here and press &apos;Return&apos; to search</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+4"/>
+        <source>Global search</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>welcome_wizard</name>
+    <message>
+        <location filename="../src/welcome-wizard.ui" line="+26"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+286"/>
+        <source>Welcome to GNU Octave</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+13"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>It appears that you have launched Octave GUI for the first time on this computer, since no configuration file could be found at &apos;~/.octave-gui&apos;. This wizard will guide you through the essential settings you should make before you can start using Octave GUI. If you want to transfer your settings you have previously made just close this dialog and copy over the settings file to your home folder. The presence of that file will automatically be detected and will skip this wizard. IMPORTANT: This wizard is not fully functional yet. Just click your way to the end and it will create a standard settings file.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+41"/>
+        <location line="+50"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <source>Next</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-124"/>
+        <location line="+52"/>
+        <location line="+52"/>
+        <location line="+87"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-5"/>
+        <location line="+2"/>
+        <location line="+2"/>
+        <location line="+5"/>
+        <source>Previous</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="-45"/>
+        <location filename="../src/ui-welcome-wizard.h" line="-3"/>
+        <source>Welcome to Octave!</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+7"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>This is the development version of Octave with the first official GUI.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+10"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+1"/>
+        <source>You seem to run Octave GUI for the first time on this computer. This assistant will help you to configure this software installation. Click &apos;Finish&apos; to write a configuration file and launch Octave GUI.</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+48"/>
+        <location filename="../src/ui-welcome-wizard.h" line="+2"/>
+        <source>Finish</source>
+        <translation type="unfinished"></translation>
+    </message>
+</context>
+<context>
+    <name>workspace_model</name>
+    <message>
+        <location filename="../src/workspace-model.cc" line="+42"/>
+        <source>Name</source>
+        <translation type="unfinished">Ідентифікатор</translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Class</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Dimension</source>
+        <translation type="unfinished"></translation>
+    </message>
+    <message>
+        <location line="+0"/>
+        <source>Value</source>
+        <translation type="unfinished">ЗначеннÑ</translation>
+    </message>
+</context>
+<context>
+    <name>workspace_view</name>
+    <message>
+        <location filename="../src/workspace-view.cc" line="+39"/>
+        <source>Workspace</source>
+        <translation type="unfinished">ОблаÑть змінних</translation>
+    </message>
+</context>
+</TS>
new file mode 100644
--- /dev/null
+++ b/libgui/link-deps.mk
@@ -0,0 +1,21 @@
+include $(top_srcdir)/libinterp/link-deps.mk
+
+if AMCOND_ENABLE_DYNAMIC_LINKING
+  LIBOCTGUI_LINK_DEPS =
+else
+  LIBOCTGUI_LINK_DEPS = $(DLDFCN_LIBS)
+endif
+
+LIBOCTGUI_LINK_DEPS += \
+  @QT_LIBS@
+
+LIBOCTGUI_LINK_OPTS = \
+  @QT_LDFLAGS@
+
+if AMCOND_LINK_ALL_DEPS
+  LIBOCTGUI_LINK_DEPS += $(LIBOCTINTERP_LINK_DEPS)
+  LIBOCTGUI_LINK_OPTS += $(LIBOCTINTERP_LINK_OPTS)
+
+  OCTAVE_GUI_LINK_DEPS = $(LIBOCTGUI_LINK_DEPS)
+  OCTAVE_GUI_LINK_OPTS = $(LIBOCTGUI_LINK_OPTS)
+endif
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal-module.mk
@@ -0,0 +1,94 @@
+EXTRA_DIST += \
+  qterminal-module.mk
+
+noinst_HEADERS += \
+  qterminal/libqterminal/QTerminal.h \
+  qterminal/libqterminal/QTerminalInterface.h \
+  qterminal/libqterminal/win32/QTerminalColors.h \
+  qterminal/libqterminal/win32/QWinTerminalImpl.h \
+  qterminal/libqterminal/unix/BlockArray.h \
+  qterminal/libqterminal/unix/Character.h \
+  qterminal/libqterminal/unix/CharacterColor.h \
+  qterminal/libqterminal/unix/Emulation.h \
+  qterminal/libqterminal/unix/ExtendedDefaultTranslator.h \
+  qterminal/libqterminal/unix/Filter.h \
+  qterminal/libqterminal/unix/History.h \
+  qterminal/libqterminal/unix/KeyboardTranslator.h \
+  qterminal/libqterminal/unix/konsole_wcwidth.h \
+  qterminal/libqterminal/unix/kpty.h \
+  qterminal/libqterminal/unix/kpty_p.h \
+  qterminal/libqterminal/unix/LineFont.h \
+  qterminal/libqterminal/unix/QUnixTerminalImpl.h \
+  qterminal/libqterminal/unix/Screen.h \
+  qterminal/libqterminal/unix/ScreenWindow.h \
+  qterminal/libqterminal/unix/TerminalCharacterDecoder.h \
+  qterminal/libqterminal/unix/Vt102Emulation.h \
+  qterminal/libqterminal/unix/SelfListener.h \
+  qterminal/libqterminal/unix/TerminalModel.h \
+  qterminal/libqterminal/unix/TerminalView.h
+
+qterminal_libqterminal_la_MOC = \
+  qterminal/libqterminal/moc-QTerminal.cc \
+  qterminal/libqterminal/moc-QTerminalInterface.cc
+
+nodist_qterminal_libqterminal_la_SOURCES = $(qterminal_libqterminal_la_MOC)
+
+qterminal_libqterminal_la_CPPFLAGS = \
+  $(AM_CPPFLAGS) \
+  @QT_CPPFLAGS@ \
+  -I$(srcdir)/qterminal/libqterminal
+
+qterminal_libqterminal_la_CFLAGS = $(AM_CFLAGS)
+
+qterminal_libqterminal_la_CXXFLAGS = $(AM_CXXFLAGS)
+
+if WIN32_TERMINAL
+
+qterminal_libqterminal_la_SOURCES = \
+  qterminal/libqterminal/win32/QTerminalColors.cpp \
+  qterminal/libqterminal/win32/QWinTerminalImpl.cpp \
+  qterminal/libqterminal/QTerminal.cc
+
+qterminal_libqterminal_la_MOC += \
+  qterminal/libqterminal/win32/moc-QWinTerminalImpl.cc
+
+qterminal_libqterminal_la_CPPFLAGS += -DUNICODE
+
+# This flag is required to let MOC know about Q_OS_WIN32.
+MOC_CPPFLAGS += -DQ_OS_WIN32
+
+else
+
+qterminal_libqterminal_la_SOURCES = \
+  qterminal/libqterminal/unix/BlockArray.cpp \
+  qterminal/libqterminal/unix/Emulation.cpp \
+  qterminal/libqterminal/unix/Filter.cpp \
+  qterminal/libqterminal/unix/History.cpp \
+  qterminal/libqterminal/unix/KeyboardTranslator.cpp \
+  qterminal/libqterminal/unix/konsole_wcwidth.cpp \
+  qterminal/libqterminal/unix/kpty.cpp \
+  qterminal/libqterminal/unix/QUnixTerminalImpl.cpp \
+  qterminal/libqterminal/unix/Screen.cpp \
+  qterminal/libqterminal/unix/ScreenWindow.cpp \
+  qterminal/libqterminal/unix/TerminalCharacterDecoder.cpp \
+  qterminal/libqterminal/unix/Vt102Emulation.cpp \
+  qterminal/libqterminal/unix/SelfListener.cpp \
+  qterminal/libqterminal/unix/TerminalModel.cpp \
+  qterminal/libqterminal/unix/TerminalView.cpp \
+  qterminal/libqterminal/QTerminal.cc
+
+qterminal_libqterminal_la_MOC += \
+  qterminal/libqterminal/unix/moc-Emulation.cc \
+  qterminal/libqterminal/unix/moc-Filter.cc \
+  qterminal/libqterminal/unix/moc-QUnixTerminalImpl.cc \
+  qterminal/libqterminal/unix/moc-ScreenWindow.cc \
+  qterminal/libqterminal/unix/moc-SelfListener.cc \
+  qterminal/libqterminal/unix/moc-TerminalModel.cc \
+  qterminal/libqterminal/unix/moc-TerminalView.cc \
+  qterminal/libqterminal/unix/moc-Vt102Emulation.cc
+
+endif
+
+noinst_LTLIBRARIES += qterminal/libqterminal.la
+
+CLEANFILES += $(qterminal_libqterminal_la_MOC)
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/LineFont.src
@@ -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
+ ||| 
+ ||| 
+ ||| 
+  |  
+  |  
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/QTerminal.cc
@@ -0,0 +1,44 @@
+/*
+
+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"
+
+void
+QTerminal::notice_settings (const QSettings *settings)
+{
+  // QSettings pointer is checked before emitting.
+
+  // Set terminal font:
+  QFont term_font = QFont();
+  term_font.setFamily(settings->value("terminal/fontName","Courier New").toString());
+  term_font.setPointSize(settings->value("terminal/fontSize",10).toInt ());
+  setTerminalFont (term_font);
+
+  QString cursorType = settings->value ("terminal/cursorType","ibeam").toString ();
+  bool cursorBlinking = settings->value ("terminal/cursorBlinking",true).toBool ();
+  if (cursorType == "ibeam")
+    setCursorType(QTerminalInterface::IBeamCursor, cursorBlinking);
+  else if (cursorType == "block")
+    setCursorType(QTerminalInterface::BlockCursor, cursorBlinking);
+  else if (cursorType == "underline")
+    setCursorType(QTerminalInterface::UnderlineCursor, cursorBlinking);
+}
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/QTerminal.h
@@ -0,0 +1,57 @@
+/*
+
+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 <QSettings>
+#include <QtGlobal>
+
+#ifdef Q_OS_WIN32
+    #include "win32/QWinTerminalImpl.h"
+    class QTerminal : public QWinTerminalImpl
+    {
+        Q_OBJECT
+    public:
+        QTerminal(QWidget *xparent = 0)
+            : QWinTerminalImpl(xparent) { }
+        ~QTerminal() { }
+
+    public slots:
+        void notice_settings (const QSettings *settings);
+    };
+#else
+    #include "unix/QUnixTerminalImpl.h"
+    class QTerminal : public QUnixTerminalImpl
+    {
+        Q_OBJECT
+    public:
+        QTerminal(QWidget *xparent = 0)
+            : QUnixTerminalImpl(xparent) { }
+        ~QTerminal() { }
+
+    public slots:
+        void notice_settings (const QSettings *settings);
+    };
+#endif
+
+#endif // QTERMINAL_H
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/QTerminalInterface.h
@@ -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 *xparent = 0) : QWidget(xparent) {
+      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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/README
@@ -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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/default.keytab
@@ -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.
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/kb-layouts/default.keytab
@@ -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.
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/kb-layouts/linux.keytab
@@ -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.
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/kb-layouts/vt420pc.keytab
@@ -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.
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/libqterminal.pro
@@ -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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/BlockArray.cpp
@@ -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);
+
+}
+
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/BlockArray.h
@@ -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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/Character.h
@@ -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
+
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/CharacterColor.h
@@ -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
+
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/Emulation.cpp
@@ -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;
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/Emulation.h
@@ -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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/ExtendedDefaultTranslator.h
@@ -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"
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/Filter.cpp
@@ -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"
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/Filter.h
@@ -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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/History.cpp
@@ -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;
+}
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/History.h
@@ -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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/KeyboardTranslator.cpp
@@ -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;
+}
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/KeyboardTranslator.h
@@ -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
+
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/LineFont.h
@@ -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
+};
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/QUnixTerminalImpl.cpp
@@ -0,0 +1,170 @@
+/*  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(300, 200);
+    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()
+{
+    // Store the file descriptor associated with the STDERR stream onto
+    // another temporary file descriptor for reconnect in the destructor.
+    fdstderr = dup (STDERR_FILENO);
+
+    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()
+{
+    // Restore stderr so that any errors at exit might appear somewhere.
+    dup2 (fdstderr, STDERR_FILENO);
+
+    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();
+}
+
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/QUnixTerminalImpl.h
@@ -0,0 +1,64 @@
+/*  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
+
+    int fdstderr;
+
+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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/Screen.cpp
@@ -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;
+}
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/Screen.h
@@ -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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/ScreenWindow.cpp
@@ -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(); 
+}
+
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/ScreenWindow.h
@@ -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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/SelfListener.cpp
@@ -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 + 1];
+    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;
+    }
+}
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/SelfListener.h
@@ -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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/TerminalCharacterDecoder.cpp
@@ -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;
+}
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/TerminalCharacterDecoder.h
@@ -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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/TerminalModel.cpp
@@ -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);
+}
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/TerminalModel.h
@@ -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
new file mode 100755
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/TerminalView.cpp
@@ -0,0 +1,2666 @@
+/*
+    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"
+
+#include <signal.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();
+#if defined (SIGWINCH)
+      ::raise (SIGWINCH);
+#endif
+      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.
+}
new file mode 100755
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/TerminalView.h
@@ -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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/Vt102Emulation.cpp
@@ -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
+}
+
+
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/Vt102Emulation.h
@@ -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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/konsole_wcwidth.cpp
@@ -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;
+}
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/konsole_wcwidth.h
@@ -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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/kpty.cpp
@@ -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;
+}
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/kpty.h
@@ -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
+
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/unix/kpty_p.h
@@ -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
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/win32/QTerminalColors.cpp
@@ -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;
+}
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/win32/QTerminalColors.h
@@ -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__
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/win32/QWinTerminalImpl.cpp
@@ -0,0 +1,918 @@
+/*
+
+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;
+  QColor m_foregroundColor;
+  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_backgroundColor = Qt::white;
+  m_foregroundColor = Qt::black;
+  SetConsoleTextAttribute (m_stdOut, 0xF0);
+
+  m_font.setFamily ("Lucida Console");
+  m_font.setPointSize (9);
+  m_font.setStyleHint (QFont::TypeWriter);
+
+  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 (d->m_foregroundColor);
+
+  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)
+{
+}
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/libqterminal/win32/QWinTerminalImpl.h
@@ -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__
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/msvc.pri
@@ -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
+}
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/qterminal.pro
@@ -0,0 +1,2 @@
+TEMPLATE 	= subdirs
+SUBDIRS 	= libqterminal qterminal
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/qterminal/README
@@ -0,0 +1,1 @@
+here is sample program which uses QTermWidet for displaying a terminal
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/qterminal/main.cpp
@@ -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();
+} 
+
+  
new file mode 100644
--- /dev/null
+++ b/libgui/qterminal/qterminal/qterminal.pro
@@ -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
+}
new file mode 100644
--- /dev/null
+++ b/libgui/src/color-picker.cc
@@ -0,0 +1,55 @@
+//
+// This class provides a simple color picker based on tQColorButton
+// by Harald Jedele, 23.03.01, GPL version 2 or any later version.
+//
+// Copyright (C) FZI Forschungszentrum Informatik Karlsruhe
+// Copyright (C) 2013 Torsten <ttl@justmail.de>
+//
+// 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/>.
+//
+
+#include "color-picker.h"
+
+// constuctor with initial color as parameter
+color_picker::color_picker (QColor old_color, QWidget* p) : QPushButton (p)
+{
+  _color = old_color;
+  setFlat (true);
+  update_button ();
+  connect(this, SIGNAL (clicked ()), SLOT (select_color ()));
+}
+
+// slot for bitton clicked: selct a new color using QColorDialog
+void
+color_picker::select_color ()
+{
+  QColor new_color = QColorDialog::getColor (_color);
+  if (new_color.isValid () && new_color != _color)
+    {
+      _color = new_color;
+      update_button ();
+    }
+}
+
+// draw the button with the actual color (using a stylesheet)
+void color_picker::update_button ()
+{
+  QString css = QString("background-color: %1; border: none;" )
+                        .arg(_color.name());
+  setStyleSheet(css);
+  repaint ();
+}
new file mode 100644
--- /dev/null
+++ b/libgui/src/color-picker.h
@@ -0,0 +1,47 @@
+//
+// This class provides a simple color picker based on tQColorButton
+// by Harald Jedele, 23.03.01, GPL version 2 or any later version.
+//
+// Copyright (C) FZI Forschungszentrum Informatik Karlsruhe
+// Copyright (C) 2013 Torsten <ttl@justmail.de>
+//
+// 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/>.
+//
+
+#ifndef COLORPICKER_H
+#define COLORPICKER_H
+
+#include <QPushButton>
+#include <QColorDialog>
+
+class color_picker: public QPushButton
+{
+  Q_OBJECT
+
+public:
+  color_picker (QColor color = QColor(0,0,0), QWidget *parent = 0);
+  QColor color () const { return _color; }
+
+private slots:
+  void select_color ();
+
+private:
+  virtual void update_button ();
+  QColor _color;
+};
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libgui/src/dialog.cc
@@ -0,0 +1,496 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2013 Daniel J. Sebald
+
+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 "dialog.h"
+
+#include <QString>
+#include <QStringList>
+#include <QStringListModel>
+#include <QListView>
+#include <QFileInfo>
+// Could replace most of these with #include <QtGui>
+#include <QMessageBox>
+#include <QHBoxLayout>
+#include <QVBoxLayout>
+#include <QPushButton>
+#include <QGroupBox>
+#include <QGridLayout>
+#include <QLabel>
+
+QUIWidgetCreator uiwidget_creator;
+
+
+QUIWidgetCreator::QUIWidgetCreator (void)
+  : QObject (), dialog_result (-1), dialog_button (),
+    string_list (new QStringList ()), list_index (new QIntList ()), path_name (new QString ())
+{ }
+
+
+QUIWidgetCreator::~QUIWidgetCreator (void)
+{
+  delete string_list;
+  delete list_index;
+  delete path_name;
+}
+
+
+void
+QUIWidgetCreator::dialog_button_clicked (QAbstractButton *button)
+{
+  // Store the value so that builtin functions can retrieve.
+  if (button)
+    dialog_button = button->text ();
+
+  // The value should always be 1 for the Octave functions.
+  dialog_result = 1;
+
+  // Wake up Octave process so that it continues.
+  waitcondition.wakeAll ();
+}
+
+
+void
+QUIWidgetCreator::list_select_finished (const QIntList& selected,
+                                        int button_pressed)
+{
+  // Store the value so that builtin functions can retrieve.
+  *list_index = selected;
+  dialog_result = button_pressed;
+
+  // Wake up Octave process so that it continues.
+  waitcondition.wakeAll ();
+}
+
+
+void
+QUIWidgetCreator::input_finished (const QStringList& input, int button_pressed)
+{
+  // Store the value so that builtin functions can retrieve.
+  *string_list = input;
+  dialog_result = button_pressed;
+
+  // Wake up Octave process so that it continues.
+  waitcondition.wakeAll ();
+}
+
+void
+QUIWidgetCreator::filedialog_finished (const QStringList& files,
+                                       const QString& path, int filterindex)
+{
+  // Store the value so that builtin functions can retrieve.
+  *string_list = files;
+  dialog_result = filterindex;
+  *path_name = path;
+
+  // Wake up Octave process so that it continues.
+  waitcondition.wakeAll ();
+}
+
+
+
+MessageDialog::MessageDialog (const QString& message,
+                              const QString& title,
+                              const QString& qsicon,
+                              const QStringList& qsbutton,
+                              const QString& defbutton,
+                              const QStringList& role)
+  : QMessageBox (QMessageBox::NoIcon, title.isEmpty () ? " " : title,
+                 message, 0, 0)
+{
+  // Create a NonModal message.
+  setWindowModality (Qt::NonModal);
+
+  // Interpret the icon string, because enumeration QMessageBox::Icon can't
+  // easily be made to pass through a signal.
+  QMessageBox::Icon eicon = QMessageBox::NoIcon;
+  if (qsicon == "error")
+    eicon = QMessageBox::Critical;
+  else if (qsicon == "warn")
+    eicon = QMessageBox::Warning;
+  else if (qsicon == "help")
+    eicon = QMessageBox::Information;
+  else if (qsicon == "quest")
+    eicon = QMessageBox::Question;
+  setIcon (eicon);
+
+  int N = qsbutton.size () < role.size () ? qsbutton.size () : role.size ();
+  if (N == 0)
+    addButton (QMessageBox::Ok);
+  else
+    {
+      for (int i = N-1; i >= 0; i--)
+        {
+          // Interpret the button role string, because enumeration
+          // QMessageBox::ButtonRole can't be made to pass through a signal.
+          QString srole = role.at (i);
+          QMessageBox::ButtonRole erole = QMessageBox::InvalidRole;
+          if (srole == "YesRole")
+            erole = QMessageBox::YesRole;
+          else if (srole == "NoRole")
+            erole = QMessageBox::NoRole;
+          else if (srole == "RejectRole")
+            erole = QMessageBox::RejectRole;
+          else if (srole == "AcceptRole")
+            erole = QMessageBox::AcceptRole;
+
+          QPushButton *pbutton = addButton (qsbutton.at (i), erole);
+          if (qsbutton.at (i) == defbutton)
+            setDefaultButton (pbutton);
+          // Make the last button the button pressed when <esc> key activated.
+          if (i == N-1)
+            {
+#define ACTIVE_ESCAPE true
+#if ACTIVE_ESCAPE
+              setEscapeButton (pbutton);
+#else
+              setEscapeButton (0);
+#endif
+#undef ACTIVE_ESCAPE
+            }
+        }
+    }
+
+  connect (this, SIGNAL (buttonClicked (QAbstractButton *)),
+           &uiwidget_creator, SLOT (dialog_button_clicked (QAbstractButton *)));
+}
+
+
+ListDialog::ListDialog (const QStringList& list, const QString& mode,
+                        int wd, int ht, const QList<int>& initial,
+                        const QString& title, const QStringList& prompt,
+                        const QString& ok_string, const QString& cancel_string)
+  : QDialog ()
+{
+  // Put the list of items into a model.  Keep this off of the stack
+  // because this conceivably could be a very large list.
+  QAbstractItemModel *model = new QStringListModel (list);
+
+  QListView *view = new QListView;
+  view->setModel (model);
+
+  if (mode == "Single")
+    view->setSelectionMode (QAbstractItemView::SingleSelection);
+  else if (mode == "Multiple")
+    view->setSelectionMode (QAbstractItemView::ExtendedSelection);
+//  else if ()
+//    view->setSelectionMode (QAbstractItemView::ContiguousSelection);
+//  else if ()
+//    view->setSelectionMode (QAbstractItemView::MultiSelection);
+  else
+    view->setSelectionMode (QAbstractItemView::NoSelection);
+
+  selector = view->selectionModel ();
+  int i = 0;
+  for (QList<int>::const_iterator it = initial.begin ();
+       it != initial.end (); it++)
+    {
+      QModelIndex idx = model->index (initial.value (i++) - 1, 0,
+                                      QModelIndex ());
+      selector->select (idx, QItemSelectionModel::Select);
+    }
+
+  bool fixed_layout = false;
+  if (wd > 0 && ht > 0)
+    {
+      view->setFixedSize (wd, ht);
+      fixed_layout = true;
+    }
+
+  view->setEditTriggers (QAbstractItemView::NoEditTriggers);
+
+  QVBoxLayout *listLayout = new QVBoxLayout;
+  if (! prompt.isEmpty ())
+    {
+      // For now, assume html-like Rich Text.  May be incompatible
+      // with something down the road, but just testing capability.
+      QString prompt_string;
+      for (int j = 0; j < prompt.length (); j++)
+        {
+          if (j > 0)
+#define RICH_TEXT true
+#if RICH_TEXT
+            prompt_string.append ("<br>");
+#else
+            prompt_string.append ("\n");
+#endif
+          prompt_string.append (prompt.at (j));
+        }
+      QLabel *plabel = new QLabel (prompt_string);
+#if RICH_TEXT
+      plabel->setTextFormat (Qt::RichText);
+#endif
+#undef RICH_TEXT
+      listLayout->addWidget (plabel);
+    }
+  listLayout->addWidget (view);
+  QPushButton *select_all = new QPushButton (tr ("Select All"));
+  select_all->setEnabled (mode == "Multiple");
+  listLayout->addWidget (select_all);
+
+  QPushButton *buttonOk = new QPushButton (ok_string);
+  QPushButton *buttonCancel = new QPushButton (cancel_string);
+  QHBoxLayout *buttonsLayout = new QHBoxLayout;
+  buttonsLayout->addStretch (1);
+  buttonsLayout->addWidget (buttonOk);
+  buttonsLayout->addWidget (buttonCancel);
+
+  QVBoxLayout *mainLayout = new QVBoxLayout;
+  mainLayout->addLayout (listLayout);
+  mainLayout->addSpacing (12);
+  mainLayout->addLayout (buttonsLayout);
+  setLayout (mainLayout);
+  if (fixed_layout)
+    layout()->setSizeConstraint (QLayout::SetFixedSize);
+
+  // If empty, make blank rather than use default OS behavior.
+  setWindowTitle (title.isEmpty () ? " " : title);
+
+  connect (select_all, SIGNAL (clicked ()),
+           view, SLOT (selectAll ()));
+
+  connect (buttonOk, SIGNAL (clicked ()),
+           this, SLOT (buttonOk_clicked ()));
+
+  connect (buttonCancel, SIGNAL (clicked ()),
+           this, SLOT (buttonCancel_clicked ()));
+
+  connect (this, SIGNAL (finish_selection (const QIntList&, int)),
+           &uiwidget_creator,
+           SLOT (list_select_finished (const QIntList&, int)));
+}
+
+
+void
+ListDialog::buttonOk_clicked (void)
+{
+  // Store information about what button was pressed so that builtin
+  // functions can retrieve.
+  QModelIndexList selected_index = selector->selectedIndexes ();
+  QIntList selected_int;
+
+  for (int i = 0; i < selected_index.size (); i++)
+    selected_int << selected_index.at (i).row () + 1;
+
+  emit finish_selection (selected_int, 1);
+
+  done (QDialog::Accepted);
+}
+
+
+void
+ListDialog::buttonCancel_clicked (void)
+{
+  // Store information about what button was pressed so that builtin
+  // functions can retrieve.
+  QIntList empty;
+
+  emit finish_selection (empty, 0);
+
+  done (QDialog::Rejected);
+}
+
+
+void
+ListDialog::reject (void)
+{
+  buttonCancel_clicked ();
+}
+
+
+InputDialog::InputDialog (const QStringList& prompt, const QString& title,
+                          const QFloatList& nr, const QFloatList& nc,
+                          const QStringList& defaults)
+  : QDialog ()
+{
+
+#define LINE_EDIT_FOLLOWS_PROMPT false
+
+#if LINE_EDIT_FOLLOWS_PROMPT
+    // Prompt on left followed by input on right.
+    QGridLayout *promptInputLayout = new QGridLayout;
+#else
+    // Prompt aligned above input.
+    QVBoxLayout *promptInputLayout = new QVBoxLayout;
+#endif
+    int N_gridrows = prompt.size ();
+    for (int i = 0; i < N_gridrows; i++)
+      {
+        QLabel *label = new QLabel (prompt.at (i));
+        QLineEdit *line_edit = new QLineEdit (defaults.at (i));
+        if (nr.at (i) > 0)
+          {
+            QSize qsize = line_edit->sizeHint ();
+            int intval = qsize.height () * nr.at (i);
+            line_edit->setFixedHeight (intval);
+            if (nc.at (i) > 0)
+              {
+                intval = qsize.height () * nc.at (i) / 2;
+                line_edit->setFixedWidth (intval);
+              }
+          }
+        input_line << line_edit;
+#if LINE_EDIT_FOLLOWS_PROMPT
+        promptInputLayout->addWidget (label, i + 1, 0);
+        promptInputLayout->addWidget (line_edit, i + 1, 1);
+#else
+        promptInputLayout->addWidget (label);
+        promptInputLayout->addWidget (line_edit);
+#endif
+      }
+#undef LINE_EDIT_FOLLOWS_PROMPT
+
+    QPushButton *buttonOk = new QPushButton("OK");
+    QPushButton *buttonCancel = new QPushButton("Cancel");
+    QHBoxLayout *buttonsLayout = new QHBoxLayout;
+    buttonsLayout->addStretch (1);
+    buttonsLayout->addWidget (buttonOk);
+    buttonsLayout->addWidget (buttonCancel);
+
+    QVBoxLayout *mainLayout = new QVBoxLayout;
+    mainLayout->addLayout (promptInputLayout);
+    mainLayout->addSpacing (12);
+    mainLayout->addLayout (buttonsLayout);
+    setLayout (mainLayout);
+
+    // If empty, make blank rather than use default OS behavior.
+    setWindowTitle (title.isEmpty () ? " " : title);
+
+    connect (buttonOk, SIGNAL (clicked ()),
+             this, SLOT (buttonOk_clicked ()));
+
+    connect (buttonCancel, SIGNAL (clicked ()),
+             this, SLOT (buttonCancel_clicked ()));
+
+    connect (this, SIGNAL (finish_input (const QStringList&, int)),
+             &uiwidget_creator,
+             SLOT (input_finished (const QStringList&, int)));
+}
+
+
+void
+InputDialog::buttonOk_clicked (void)
+{
+  // Store information about what button was pressed so that builtin
+  // functions can retrieve.
+  QStringList string_result;
+  for (int i = 0; i < input_line.size (); i++)
+    string_result << input_line.at (i)->text ();
+  emit finish_input (string_result, 1);
+  done (QDialog::Accepted);
+}
+
+void
+InputDialog::buttonCancel_clicked (void)
+{
+  // Store information about what button was pressed so that builtin
+  // functions can retrieve.
+  QStringList empty;
+  emit finish_input (empty, 0);
+  done (QDialog::Rejected);
+}
+
+  
+void
+InputDialog::reject (void)
+{
+  buttonCancel_clicked ();
+}
+
+FileDialog::FileDialog (const QStringList& filters, const QString& title,
+                        const QString& filename, const QString& dirname,
+                        const QString& multimode)
+  : QFileDialog()
+{
+  // Create a NonModal message.
+  setWindowModality (Qt::NonModal);
+
+  setWindowTitle (title.isEmpty () ? " " : title);
+  setDirectory (dirname);
+
+  if (multimode == "on")         // uigetfile multiselect=on
+    {
+      setFileMode (QFileDialog::ExistingFiles);
+      setAcceptMode (QFileDialog::AcceptOpen);
+    }
+  else if (multimode == "create") // uiputfile
+    {
+      setFileMode (QFileDialog::AnyFile); 
+      setAcceptMode (QFileDialog::AcceptSave);
+      setOption (QFileDialog::DontConfirmOverwrite, false);
+      setConfirmOverwrite(true);
+    }
+  else                           // uigetfile multiselect=off
+    {
+      setFileMode (QFileDialog::ExistingFile);
+      setAcceptMode (QFileDialog::AcceptOpen);
+    }
+
+  setNameFilters (filters);
+
+  selectFile (filename);
+  
+  connect (this,
+           SIGNAL (finish_input (const QStringList&, const QString&, int)),
+           &uiwidget_creator,
+           SLOT (filedialog_finished (const QStringList&, const QString&,
+                                      int)));
+}
+
+void
+FileDialog::reject (void)
+{
+  QStringList empty;
+  emit finish_input (empty, "", 0);
+  done (QDialog::Rejected);
+
+}
+
+void FileDialog::accept(void)
+{
+  QStringList string_result;
+  QString path;
+  int idx = 1;
+
+  string_result = selectedFiles ();
+
+  // Matlab expects just the file name, whereas the file dialog gave us
+  // pull path names, so fix it.
+
+  for (int i = 0; i < string_result.size (); i++)
+    string_result[i] = QFileInfo (string_result[i]).fileName ();
+
+
+  path = directory ().absolutePath ();
+
+  QStringList filters = nameFilters ();
+  idx = filters.indexOf (selectedNameFilter ()) + 1;
+  
+  // send the selected info
+  emit finish_input (string_result, path, idx);
+  done (QDialog::Accepted);
+}
+
new file mode 100644
--- /dev/null
+++ b/libgui/src/dialog.h
@@ -0,0 +1,269 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2013 Daniel J. Sebald
+
+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_guifcn_dialog_h)
+#define octave_guifcn_dialog_h 1
+
+#include <QMutex>
+#include <QWaitCondition>
+#include <QAbstractButton>
+#include <QList>
+#include <QItemSelectionModel>
+#include <QDialog>
+#include <QMessageBox>
+#include <QLineEdit>
+#include <QFileDialog>
+
+// Defined for purposes of sending QList<int> as part of signal.
+typedef QList<int> QIntList;
+
+// Defined for purposes of sending QList<float> as part of signal.
+typedef QList<float> QFloatList;
+
+
+class QUIWidgetCreator : public QObject
+{
+  Q_OBJECT
+
+public:
+
+  QUIWidgetCreator (void);
+
+  ~QUIWidgetCreator (void);
+
+public:
+
+  void signal_dialog (const QString& message, const QString& title,
+                      const QString& icon, const QStringList& button,
+                      const QString& defbutton, const QStringList& role)
+  {
+
+    // Use the last button in the list as the reject result, i.e., when no
+    // button is pressed such as in the case of the upper right close tab.
+    if (!button.isEmpty ())
+      dialog_button = button.last ();
+
+    QString xicon = icon;
+    if (xicon.isEmpty ())
+      xicon = "none";
+
+    emit create_dialog (message, title, xicon, button, defbutton, role);
+  };
+
+  int get_dialog_result (void) { return dialog_result; }
+
+  QString get_dialog_button (void) { return dialog_button; }
+
+  bool signal_listview (const QStringList& list, const QString& mode,
+                        int wd, int ht, const QList<int>& initial,
+                        const QString& name, const QStringList& prompt,
+                        const QString& ok_string, const QString& cancel_string)
+  {
+    if (list.isEmpty ())
+      return false;
+
+    emit create_listview (list, mode, wd, ht, initial, name,
+                          prompt, ok_string, cancel_string);
+
+    return true;
+  };
+
+  const QIntList *get_list_index (void) { return list_index; }
+
+  bool signal_inputlayout (const QStringList& prompt, const QString& title,
+                           const QFloatList& nr, const QFloatList& nc,
+                           const QStringList& defaults)
+  {
+    if (prompt.isEmpty ())
+      return false;
+
+    emit create_inputlayout (prompt, title, nr, nc, defaults);
+
+    return true;
+  };
+
+  const QStringList *get_string_list (void) { return string_list; }
+
+  bool signal_filedialog (const QStringList& filters, const QString& title, 
+                          const QString& filename, const QString& dirname, 
+                          const QString &multimode)
+  {
+    emit create_filedialog (filters, title, filename, dirname, multimode);
+    return true;
+  }
+
+  const QString *get_dialog_path (void) { return path_name; }
+
+  void wait (void)
+  {
+    // Wait while the user is responding to message box.
+    waitcondition.wait (&mutex);
+  }
+
+signals:
+
+  void create_dialog (const QString&, const QString&, const QString&,
+                      const QStringList&, const QString&, const QStringList&);
+
+  void create_listview (const QStringList&, const QString&, int, int,
+                        const QIntList&, const QString&, const QStringList&,
+                        const QString&, const QString&);
+
+  void create_inputlayout (const QStringList&, const QString&,
+                           const QFloatList&, const QFloatList&,
+                           const QStringList&);
+
+  void create_filedialog (const QStringList& filters, const QString& title,
+                          const QString& filename, const QString& dirname,
+                          const QString& multimode);
+public slots:
+
+  void dialog_button_clicked (QAbstractButton *button);
+
+  void list_select_finished (const QIntList& selected, int button_pressed);
+
+  void input_finished (const QStringList& input, int button_pressed);
+
+  void filedialog_finished (const QStringList& files, const QString& path,
+                            int filterindex);
+
+private:
+
+  int dialog_result;
+  QString dialog_button;
+
+  // The list could conceivably be big.  Not sure how things are
+  // stored internally, so keep off of the stack.
+  QStringList *string_list;
+  QIntList *list_index;
+
+  QString *path_name;
+
+  // GUI objects cannot be accessed in the non-GUI thread.  However,
+  // signals can be sent to slots across threads with proper
+  // synchronization.  Hence, the use of QWaitCondition.
+
+  QMutex mutex;
+
+  QWaitCondition waitcondition;
+};
+
+extern QUIWidgetCreator uiwidget_creator;
+
+
+class MessageDialog : public QMessageBox
+{
+  Q_OBJECT
+
+public:
+
+  explicit MessageDialog (const QString& message, const QString& title,
+                          const QString& icon, const QStringList& button,
+                          const QString& defbutton,
+                          const QStringList& role);
+
+private:
+
+  void closeEvent (QCloseEvent *)
+  {
+    // Reroute the close tab to a button click so there is only a single
+    // route to waking the wait condition.
+    emit buttonClicked (0);
+  }
+};
+
+
+class ListDialog : public QDialog
+{
+  Q_OBJECT
+
+  QItemSelectionModel *selector;
+
+public:
+
+  explicit ListDialog (const QStringList& list, const QString& mode,
+                       int width, int height, const QList<int>& initial,
+                       const QString& name, const QStringList& prompt,
+                       const QString& ok_string, const QString& cancel_string);
+
+signals:
+
+  void finish_selection (const QIntList&, int);
+
+public slots:
+
+  void buttonOk_clicked (void);
+
+  void buttonCancel_clicked (void);
+
+  void reject (void);
+};
+
+
+class InputDialog : public QDialog
+{
+  Q_OBJECT
+
+  QList<QLineEdit *> input_line;
+
+public:
+
+  explicit InputDialog (const QStringList& prompt, const QString& title,
+                        const QFloatList& nr, const QFloatList& nc,
+                        const QStringList& defaults);
+
+signals:
+
+  void finish_input (const QStringList&, int);
+
+public slots:
+
+  void buttonOk_clicked (void);
+
+  void buttonCancel_clicked (void);
+
+  void reject (void);
+};
+
+class FileDialog : public QFileDialog
+{
+  Q_OBJECT
+
+public:
+
+  explicit FileDialog (const QStringList& filters,
+                       const QString& title, const QString& filename, 
+                       const QString& dirname, const QString& multimode);
+
+signals:
+
+  void finish_input (const QStringList&, const QString&, int);
+
+private slots:
+
+  void reject (void);
+
+  void accept (void);
+};
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libgui/src/documentation-dock-widget.cc
@@ -0,0 +1,39 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 "documentation-dock-widget.h"
+
+documentation_dock_widget::documentation_dock_widget (QWidget *p)
+  : octave_dock_widget (p)
+{
+  setObjectName ("DocumentationDockWidget");
+  setWindowIcon (QIcon (":/actions/icons/logo.png"));
+  setWindowTitle (tr ("Documentation"));
+  setStatusTip (tr ("See the documentation for help."));
+
+  _webinfo = new webinfo (this);
+  setWidget (_webinfo);
+}
new file mode 100644
--- /dev/null
+++ b/libgui/src/documentation-dock-widget.h
@@ -0,0 +1,43 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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/>.
+
+*/
+
+#ifndef DOCUMENTATIONDOCKWIDGET_H
+#define DOCUMENTATIONDOCKWIDGET_H
+
+#include "octave-dock-widget.h"
+
+#include "webinfo.h"
+
+class documentation_dock_widget : public octave_dock_widget
+{
+  Q_OBJECT
+
+public:
+
+  documentation_dock_widget (QWidget *parent = 0);
+
+private:
+
+  webinfo *_webinfo;
+};
+
+#endif // DOCUMENTATIONDOCKWIDGET_H
new file mode 100644
--- /dev/null
+++ b/libgui/src/files-dock-widget.cc
@@ -0,0 +1,623 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 "resource-manager.h"
+#include "files-dock-widget.h"
+
+#include <QApplication>
+#include <QFileInfo>
+#include <QCompleter>
+#include <QSettings>
+#include <QProcess>
+#include <QDebug>
+#include <QHeaderView>
+#include <QLineEdit>
+#include <QSizePolicy>
+#include <QMenu>
+#include <QInputDialog>
+#include <QMessageBox>
+#include <QToolButton>
+#include <QUrl>
+#include <QDesktopServices>
+
+#include "load-save.h"
+
+files_dock_widget::files_dock_widget (QWidget *p)
+  : octave_dock_widget (p)
+{
+  setObjectName ("FilesDockWidget");
+  setWindowIcon (QIcon(":/actions/icons/logo.png"));
+  setWindowTitle (tr ("File Browser"));
+  setToolTip (tr ("Browse your files."));
+
+  QWidget *container = new QWidget (this);
+
+  setWidget (container);
+
+  connect (this, SIGNAL (open_file (const QString&)),
+           parent (), SLOT (open_file (const QString&)));
+
+  connect (this, SIGNAL (displayed_directory_changed (const QString&)),
+           parent (), SLOT (set_current_working_directory (const QString&)));
+
+  connect (parent (), SIGNAL (settings_changed (const QSettings *)),
+           this, SLOT (notice_settings (const QSettings *)));
+
+  // Create a toolbar
+  _navigation_tool_bar = new QToolBar ("", container);
+  _navigation_tool_bar->setAllowedAreas (Qt::TopToolBarArea);
+  _navigation_tool_bar->setMovable (false);
+
+  _current_directory = new QComboBox (_navigation_tool_bar);
+  _current_directory->setToolTip (tr ("Enter the path or filename"));
+  _current_directory->setEditable(true);
+  _current_directory->setMaxCount(MaxMRUDirs);
+  _current_directory->setInsertPolicy(QComboBox::NoInsert);
+  _current_directory->setSizeAdjustPolicy (QComboBox::AdjustToMinimumContentsLengthWithIcon);
+  QSizePolicy sizePol(QSizePolicy::Expanding, QSizePolicy::Preferred);
+  _current_directory->setSizePolicy(sizePol);
+
+  QAction *directory_up_action = new QAction (QIcon(":/actions/icons/up.png"),
+                                              "", _navigation_tool_bar);
+  directory_up_action->setToolTip (tr ("Move up one directory"));
+
+  _sync_browser_directory_action = new QAction (QIcon(":/actions/icons/reload.png"),
+                                                tr("Show octave directory"), _navigation_tool_bar);
+  _sync_browser_directory_action->setToolTip (tr ("Goto current octave directory"));
+  _sync_browser_directory_action->setEnabled ("false");
+
+  _sync_octave_directory_action = new QAction (QIcon(":/actions/icons/ok.png"),
+                                               tr("Set octave directory"), _navigation_tool_bar);
+  _sync_octave_directory_action->setToolTip (tr ("Set octave directroy to current browser directory"));
+  _sync_octave_directory_action->setEnabled ("false");
+
+  QToolButton * popdown_button = new QToolButton();
+  popdown_button->setToolTip(tr ("Actions on current directory"));
+  QMenu * popdown_menu = new QMenu();
+  popdown_menu->addAction(_sync_browser_directory_action);
+  popdown_menu->addAction(_sync_octave_directory_action);
+  popdown_button->setMenu(popdown_menu);
+  popdown_button->setPopupMode(QToolButton::InstantPopup);
+  popdown_button->setDefaultAction(new QAction(QIcon(":/actions/icons/gear.png"),"", _navigation_tool_bar));
+
+  popdown_menu->addSeparator();
+  popdown_menu->addAction(QIcon(":/actions/icons/filenew.png"),
+                          tr ("New File"),
+                          this, SLOT(popdownmenu_newfile(bool)));
+  popdown_menu->addAction(QIcon(":/actions/icons/folder_new.png"),
+                          tr ("New Directory"),
+                          this, SLOT(popdownmenu_newdir(bool)));
+
+  _navigation_tool_bar->addWidget (_current_directory);
+  _navigation_tool_bar->addAction (directory_up_action);
+  _navigation_tool_bar->addWidget (popdown_button);
+
+  connect (directory_up_action, SIGNAL (triggered ()), this,
+           SLOT (change_directory_up ()));
+  connect (_sync_octave_directory_action, SIGNAL (triggered ()), this,
+           SLOT (do_sync_octave_directory ()));
+  connect (_sync_browser_directory_action, SIGNAL (triggered ()), this,
+           SLOT (do_sync_browser_directory ()));
+
+  // Create the QFileSystemModel starting in the actual directory
+  QDir curr_dir;
+  _file_system_model = new QFileSystemModel (this);
+  _file_system_model->setFilter (QDir::NoDotAndDotDot | QDir::AllEntries);
+  QModelIndex rootPathIndex = _file_system_model->setRootPath (
+                                                  curr_dir.absolutePath ());
+
+  // Attach the model to the QTreeView and set the root index
+  _file_tree_view = new QTreeView (container);
+  _file_tree_view->setModel (_file_system_model);
+  _file_tree_view->setRootIndex (rootPathIndex);
+  _file_tree_view->setSortingEnabled (true);
+  _file_tree_view->setAlternatingRowColors (true);
+  _file_tree_view->setAnimated (true);
+  _file_tree_view->setToolTip (tr ("Doubleclick a file to open it"));
+
+  // get sort column and order as well as cloumn state (order and width)
+  QSettings *settings = resource_manager::get_settings ();
+  // FIXME -- what should happen if settings is 0?
+  _file_tree_view->sortByColumn (
+              settings->value ("filesdockwidget/sort_files_by_column",0).toInt (),
+              static_cast<Qt::SortOrder>(settings->value ("filesdockwidget/sort_files_by_order",Qt::AscendingOrder).toUInt ())
+  );
+  _file_tree_view->header ()->restoreState (settings->value ("filesdockwidget/column_state").toByteArray ());
+  
+  QStringList mru_dirs = settings->value ("filesdockwidget/mru_dir_list").toStringList ();
+  _current_directory->addItems(mru_dirs);
+
+  _current_directory->setEditText(_file_system_model->fileInfo (rootPathIndex).
+                              absoluteFilePath ());
+
+  connect (_file_tree_view, SIGNAL (doubleClicked (const QModelIndex &)),
+           this, SLOT (item_double_clicked (const QModelIndex &)));
+
+  // add context menu to tree_view
+  _file_tree_view->setContextMenuPolicy(Qt::CustomContextMenu);
+  connect(_file_tree_view, SIGNAL(customContextMenuRequested(const QPoint &)), 
+           this, SLOT(contextmenu_requested(const QPoint &)));
+
+  // Layout the widgets vertically with the toolbar on top
+  QVBoxLayout *vbox_layout = new QVBoxLayout ();
+  vbox_layout->setSpacing (0);
+  vbox_layout->addWidget (_navigation_tool_bar);
+  vbox_layout->addWidget (_file_tree_view);
+  vbox_layout->setMargin (1);
+
+  container->setLayout (vbox_layout);
+
+  // TODO: Add right-click contextual menus for copying, pasting, deleting files (and others)
+
+  connect (_current_directory->lineEdit(), SIGNAL (returnPressed ()),
+            this, SLOT (accept_directory_line_edit ()));
+
+  connect (_current_directory, SIGNAL (activated (const QString &)),
+           this, SLOT (set_current_directory (const QString &)));
+
+  connect (this, SIGNAL (run_file_signal (const QString&)),
+           parent (), SLOT (execute_command_in_terminal (const QString&)));
+
+  QCompleter *completer = new QCompleter (_file_system_model, this);
+  _current_directory->setCompleter (completer);
+
+  setFocusProxy (_current_directory);
+  
+  _sync_octave_dir = true;   // default, overwirtten with notice_settings ()
+  _octave_dir = "";
+}
+
+files_dock_widget::~files_dock_widget ()
+{
+  QSettings *settings = resource_manager::get_settings ();
+  int sort_column = _file_tree_view->header ()->sortIndicatorSection ();
+  Qt::SortOrder sort_order = _file_tree_view->header ()->sortIndicatorOrder ();
+  settings->setValue ("filesdockwidget/sort_files_by_column", sort_column);
+  settings->setValue ("filesdockwidget/sort_files_by_order", sort_order);
+  settings->setValue ("filesdockwidget/column_state", _file_tree_view->header ()->saveState ());
+
+  QStringList dirs;
+  for(int i=0; i< _current_directory->count(); i++)
+  {
+    dirs.append(_current_directory->itemText(i));
+  }
+  settings->setValue ("filesdockwidget/mru_dir_list", dirs);
+
+  settings->sync ();
+}
+
+void
+files_dock_widget::item_double_clicked (const QModelIndex& index)
+{
+  // Retrieve the file info associated with the model index.
+  QFileInfo fileInfo = _file_system_model->fileInfo (index);
+  set_current_directory (fileInfo.absoluteFilePath ());
+}
+
+void
+files_dock_widget::set_current_directory (const QString& dir)
+{
+  display_directory (dir);
+}
+
+void
+files_dock_widget::accept_directory_line_edit (void)
+{
+  display_directory (_current_directory->currentText ());
+}
+
+void
+files_dock_widget::change_directory_up (void)
+{
+  QDir dir = QDir (_file_system_model->filePath (_file_tree_view->rootIndex ()));
+  dir.cdUp ();
+  display_directory (dir.absolutePath ());
+}
+
+void
+files_dock_widget::do_sync_octave_directory (void)
+{
+  QDir dir = QDir (_file_system_model->filePath (_file_tree_view->rootIndex ()));
+  emit displayed_directory_changed (dir.absolutePath ());
+}
+
+void
+files_dock_widget::do_sync_browser_directory (void)
+{
+  display_directory (_octave_dir,false);  // false: no sync of octave dir
+}
+
+void
+files_dock_widget::update_octave_directory (const QString& dir)
+{
+  _octave_dir = dir;
+  if (_sync_octave_dir)
+    display_directory (_octave_dir,false);  // false: no sync of octave dir
+}
+
+void
+files_dock_widget::display_directory (const QString& dir, bool set_octave_dir)
+{
+  QFileInfo fileInfo (dir);
+  if (fileInfo.exists ())
+    {
+      if (fileInfo.isDir ())
+        {
+          _file_tree_view->setRootIndex (_file_system_model->
+                                         index (fileInfo.absoluteFilePath ()));
+          _file_system_model->setRootPath (fileInfo.absoluteFilePath ());
+          _file_system_model->sort (0, Qt::AscendingOrder);
+          if (_sync_octave_dir && set_octave_dir)
+            process_set_current_dir(fileInfo.absoluteFilePath ());
+
+          // see if its in the list, and if it is, remove it and then, put at top of the list
+          int index = _current_directory->findText(fileInfo.absoluteFilePath ());
+          if(index != -1)
+          {
+             _current_directory->removeItem(index);
+          }
+          _current_directory->insertItem(0, fileInfo.absoluteFilePath ());
+          _current_directory->setCurrentIndex(0);
+        }
+      else
+        {
+          QString abs_fname = fileInfo.absoluteFilePath ();
+
+          if (QFile::exists (abs_fname))
+            {
+              if (is_octave_data_file (abs_fname.toStdString ()))
+                emit load_file_signal (abs_fname);
+              else
+                emit open_file (fileInfo.absoluteFilePath ());
+            }
+        }
+    }
+}
+
+void
+files_dock_widget::open_item_in_app (const QModelIndex& index)
+{
+  // Retrieve the file info associated with the model index.
+  QFileInfo fileInfo = _file_system_model->fileInfo (index);
+
+  QString file = fileInfo.absoluteFilePath ();
+
+  QDesktopServices::openUrl (QUrl::fromLocalFile (file));
+}
+
+void 
+files_dock_widget::contextmenu_requested (const QPoint& mpos)
+{
+
+  QMenu menu(this);
+
+  QModelIndex index = _file_tree_view->indexAt (mpos);
+  //QAbstractItemModel *m = _file_tree_view->model ();
+
+  if (index.isValid())
+    { 
+      QFileInfo info = _file_system_model->fileInfo(index);
+
+      menu.addAction (QIcon (":/actions/icons/fileopen.png"), tr("Open"),
+                     this, SLOT(contextmenu_open(bool)));
+
+      menu.addAction (tr("Open in Default Application"),
+                      this, SLOT (contextmenu_open_in_app (bool)));
+
+      if (info.isFile () && info.suffix () == "m")
+        menu.addAction (QIcon (":/actions/icons/artsbuilderexecute.png"),
+                        tr("Run"), this, SLOT(contextmenu_run(bool)));
+
+      if (info.isFile ())
+        menu.addAction (tr("Load Data"), this, SLOT(contextmenu_load(bool)));
+
+      if (info.isDir ())
+        {
+          menu.addSeparator ();
+          menu.addAction (QIcon (":/actions/icons/ok.png"),
+                          tr ("Set Current Directory"),
+                          this, SLOT (contextmenu_setcurrentdir (bool)));
+        }
+
+      menu.addSeparator();
+      menu.addAction (tr ("Rename"), this, SLOT(contextmenu_rename(bool)));
+      menu.addAction (QIcon(":/actions/icons/editdelete.png"), tr("Delete"),
+                      this, SLOT(contextmenu_delete(bool)));
+
+      if (info.isDir())
+        {
+          menu.addSeparator();
+          menu.addAction (QIcon (":/actions/icons/filenew.png"),
+                          tr ("New File"),
+                          this, SLOT(contextmenu_newfile(bool)));
+          menu.addAction (QIcon (":/actions/icons/folder_new.png"),
+                          tr("New Directory"),
+                          this, SLOT(contextmenu_newdir(bool)));
+        }
+
+      menu.exec(_file_tree_view->mapToGlobal(mpos));
+
+    }
+}
+
+void
+files_dock_widget::contextmenu_open (bool)
+{
+
+  QItemSelectionModel *m = _file_tree_view->selectionModel ();
+  QModelIndexList rows = m->selectedRows ();
+
+  for( QModelIndexList::iterator it = rows.begin (); it != rows.end (); it++)
+    {
+      item_double_clicked(*it);
+    }
+}
+
+void
+files_dock_widget::contextmenu_open_in_app (bool)
+{
+  QItemSelectionModel *m = _file_tree_view->selectionModel ();
+  QModelIndexList rows = m->selectedRows ();
+
+  for (QModelIndexList::iterator it = rows.begin (); it != rows.end (); it++)
+    open_item_in_app (*it);
+}
+
+void
+files_dock_widget::contextmenu_load (bool)
+{
+  QItemSelectionModel *m = _file_tree_view->selectionModel ();
+  QModelIndexList rows = m->selectedRows ();
+
+  if (rows.size () > 0)
+    {
+      QModelIndex index = rows[0];
+
+      QFileInfo info = _file_system_model->fileInfo(index);
+
+      emit load_file_signal (info.fileName ());
+    }
+}
+
+void
+files_dock_widget::contextmenu_run (bool)
+{
+  QItemSelectionModel *m = _file_tree_view->selectionModel ();
+  QModelIndexList rows = m->selectedRows ();
+
+  if (rows.size () > 0)
+    {
+      QModelIndex index = rows[0];
+
+      QFileInfo info = _file_system_model->fileInfo(index);
+
+      QString function_name = info.fileName ();
+      // We have to cut off the suffix, because octave appends it.
+      function_name.chop (info.suffix ().length () + 1);
+      emit run_file_signal (QString ("cd \'%1\'\n%2\n")
+                            .arg(info.absolutePath ()).arg (function_name));
+    }
+}
+
+void 
+files_dock_widget::contextmenu_rename (bool)
+{
+  QItemSelectionModel *m = _file_tree_view->selectionModel ();
+  QModelIndexList rows = m->selectedRows ();
+  if(rows.size() > 0)
+    {
+      QModelIndex index = rows[0];
+
+      QFileInfo info = _file_system_model->fileInfo(index);
+      QDir path = info.absoluteDir();
+      QString old_name = info.fileName();
+      bool ok;
+
+      QString new_name = QInputDialog::getText (this, tr("Rename file/directory"), 
+                                                tr("Rename file/directory:\n") + old_name + tr("\n to: "),
+                                                QLineEdit::Normal, old_name, &ok);
+      if(ok && new_name.length()>0)
+        {
+          new_name = path.absolutePath() + "/" + new_name;
+          old_name = path.absolutePath() + "/" + old_name;
+          path.rename(old_name, new_name);
+          _file_system_model->revert();
+        }
+    }
+
+}
+
+void 
+files_dock_widget::contextmenu_delete (bool)
+{
+  QItemSelectionModel *m = _file_tree_view->selectionModel ();
+  QModelIndexList rows = m->selectedRows ();
+
+  for( QModelIndexList::iterator it = rows.begin (); it != rows.end (); it++)
+    {
+      QModelIndex index = *it;
+
+      QFileInfo info = _file_system_model->fileInfo(index);
+
+      if(QMessageBox::question(this, tr("Delete file/directory"), 
+                               tr("Are you sre you want to delete\n") + info.filePath(),
+                               QMessageBox::Yes|QMessageBox::No) == QMessageBox::Yes) 
+        {
+           if(info.isDir())
+             {
+               // see if direcory is empty
+               QDir path(info.absoluteFilePath());
+               QList<QFileInfo> fileLst = path.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
+
+               if(fileLst.count() != 0)
+                 QMessageBox::warning(this, tr("Delete file/directory"),
+                                      tr("Can not delete a directory that is not empty"));
+               else
+                 _file_system_model->rmdir(index);
+             }
+           else
+             {
+               _file_system_model->remove(index);
+             }
+
+           _file_system_model->revert();
+
+        }
+    }
+}
+
+void 
+files_dock_widget::contextmenu_newfile (bool)
+{
+  QItemSelectionModel *m = _file_tree_view->selectionModel ();
+  QModelIndexList rows = m->selectedRows ();
+
+  if(rows.size() > 0)
+    {
+      QModelIndex index = rows[0];
+
+      QFileInfo info = _file_system_model->fileInfo(index);
+      QString parent_dir = info.filePath();
+
+      process_new_file(parent_dir);
+    }
+}
+
+void 
+files_dock_widget::contextmenu_newdir (bool)
+{
+  QItemSelectionModel *m = _file_tree_view->selectionModel ();
+  QModelIndexList rows = m->selectedRows ();
+
+  if(rows.size() > 0)
+    {
+      QModelIndex index = rows[0];
+
+      QFileInfo info = _file_system_model->fileInfo(index);
+      QString parent_dir = info.filePath();
+
+      process_new_dir(parent_dir);
+    }
+}
+
+void 
+files_dock_widget::contextmenu_setcurrentdir (bool)
+{
+  QItemSelectionModel *m = _file_tree_view->selectionModel ();
+  QModelIndexList rows = m->selectedRows ();
+
+  if(rows.size() > 0)
+    {
+      QModelIndex index = rows[0];
+
+      QFileInfo info = _file_system_model->fileInfo(index);
+
+      if(info.isDir())
+        {
+          process_set_current_dir(info.absoluteFilePath ());
+        }
+    }
+}
+
+void
+files_dock_widget::notice_settings (const QSettings *settings)
+{
+  // Qsettings pointer is checked before emitting.
+
+  int icon_size = settings->value ("toolbar_icon_size",24).toInt ();
+  if (icon_size > 16)
+    icon_size = icon_size - 4;
+  _navigation_tool_bar->setIconSize (QSize (icon_size,icon_size));
+
+  // file names are always shown, other columns can be hidden by settings
+  _file_tree_view->setColumnHidden (0, false);
+  _file_tree_view->setColumnHidden (1, !settings->value ("filesdockwidget/showFileSize",false).toBool ());
+  _file_tree_view->setColumnHidden (2, !settings->value ("filesdockwidget/showFileType",false).toBool ());
+  _file_tree_view->setColumnHidden (3, !settings->value ("filesdockwidget/showLastModified",false).toBool ());
+  _file_tree_view->setAlternatingRowColors (settings->value ("filesdockwidget/useAlternatingRowColors",true).toBool ());
+  if (settings->value ("filesdockwidget/showHiddenFiles",false).toBool ())
+    {
+      // TODO: React on option for hidden files.
+    }
+  // enalbe the buttons to sync octave/browser dir only if this is not done by default
+  _sync_octave_dir = settings->value ("filesdockwidget/sync_octave_directory",false).toBool ();
+  _sync_octave_directory_action->setEnabled (!_sync_octave_dir);
+  _sync_browser_directory_action->setEnabled (!_sync_octave_dir);
+
+  if (_sync_octave_dir)
+    display_directory (_octave_dir);  // sync browser to octave dir
+
+}
+
+void
+files_dock_widget::popdownmenu_newdir (bool)
+{
+      process_new_dir(_file_system_model->rootPath());
+}
+
+void
+files_dock_widget::popdownmenu_newfile (bool)
+{
+      process_new_file(_file_system_model->rootPath());
+}
+
+void
+files_dock_widget::process_new_file (const QString &parent_dir)
+{
+  bool ok;
+
+  QString name = QInputDialog::getText (this, tr("Create File"), tr("Create file in\n") + parent_dir,
+                                       QLineEdit::Normal, "New File.txt", &ok);
+  if(ok && name.length()>0)
+    {
+      name = parent_dir + "/" + name;
+
+      QFile file(name);
+      file.open(QIODevice::WriteOnly);
+      _file_system_model->revert();
+    }
+}
+
+void
+files_dock_widget::process_new_dir (const QString &parent_dir)
+{
+  bool ok;
+
+  QString name = QInputDialog::getText (this, tr("Create Directory"), tr("Create folder in\n") + parent_dir,
+                                       QLineEdit::Normal, "New Directory", &ok);
+  if(ok && name.length()>0)
+    {
+     QDir dir(parent_dir);
+      dir.mkdir(name);
+      _file_system_model->revert();
+    }
+}
+
+void files_dock_widget::process_set_current_dir(const QString & dir)
+{
+  emit displayed_directory_changed (dir);
+}
+
new file mode 100644
--- /dev/null
+++ b/libgui/src/files-dock-widget.h
@@ -0,0 +1,144 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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/>.
+
+*/
+
+#ifndef FILESDOCKWIDGET_H
+#define FILESDOCKWIDGET_H
+
+#include <QListView>
+#include <QDate>
+#include <QObject>
+#include <QWidget>
+#include <QListWidget>
+#include <QFileSystemModel>
+#include <QToolBar>
+#include <QToolButton>
+#include <QVBoxLayout>
+#include <QAction>
+#include <QTreeView>
+#include <QSettings>
+
+#include <QComboBox>
+#include "octave-dock-widget.h"
+
+/**
+   \class files_dock_widget
+   \brief Dock widget to display files in the current directory.
+*/
+class files_dock_widget : public octave_dock_widget
+{
+  Q_OBJECT
+
+public:
+
+  files_dock_widget (QWidget *parent = 0);
+
+  ~files_dock_widget ();
+
+public slots:
+
+  /** Slot for handling a change in directory via double click. */
+  void item_double_clicked (const QModelIndex & index);
+
+  /** Slot for handling the up-directory button in the toolbar. */
+  void change_directory_up ();
+
+  /** Slot for handling the sync octave directory button in the toolbar. */
+  void do_sync_octave_directory ();
+
+  /** Slot for handling the sync browser directory button in the toolbar. */
+  void do_sync_browser_directory ();
+
+  /** Sets the current directory being displayed. */
+  void set_current_directory (const QString& dir);
+
+  /** Accepts user input a the line edit for the current directory. */
+  void accept_directory_line_edit ();
+
+  /** set the internal variable that holds the actual octave variable **/
+  void update_octave_directory (const QString& dir);
+
+  /** Tells the widget to react on changed settings. */
+  void notice_settings (const QSettings *settings);
+
+private slots:
+  /** context menu wanted */
+  void contextmenu_requested (const QPoint& pos);
+
+  /* context menu actions */
+  void contextmenu_open (bool);
+  void contextmenu_open_in_app (bool);
+  void contextmenu_run (bool);
+  void contextmenu_load (bool);
+  void contextmenu_rename (bool);
+  void contextmenu_delete (bool);
+  void contextmenu_newfile (bool);
+  void contextmenu_newdir (bool);
+  void contextmenu_setcurrentdir (bool);
+
+  /* popdown menu options */
+  void popdownmenu_newfile(bool);
+  void popdownmenu_newdir(bool);
+
+signals:
+
+  /** Emitted, whenever the user requested to open a file. */
+  void open_file (const QString& fileName);
+
+  /** Emitted, whenever the currently displayed directory changed. */
+  void displayed_directory_changed (const QString& dir);
+
+  /** Emitted, whenever the user requested to load a file. */
+  void load_file_signal (const QString& fileName);
+
+  /** Emitted, whenever the user requested to run a file. */
+  void run_file_signal (const QString& fileName);
+
+private:
+  void process_new_file(const QString &parent_name);
+  void process_new_dir(const QString &parent_name);
+  void process_set_current_dir(const QString &parent_name);
+
+  /** set a new directory or open a file **/
+  void display_directory (const QString& dir, bool set_octave_dir = true);
+
+  void open_item_in_app (const QModelIndex& index);
+
+  /** Variables for the actions **/
+  QToolBar *        _navigation_tool_bar;
+  QAction *         _sync_octave_directory_action;
+  QAction *         _sync_browser_directory_action;
+
+  /** The file system model. */
+  QFileSystemModel *_file_system_model;
+
+  /** The file system view. */
+  QTreeView *       _file_tree_view;
+  QComboBox *       _current_directory;
+
+  /** Internal variables **/
+  bool              _sync_octave_dir;    // flag if syncing with octave
+  QString           _octave_dir;         // the actual octave dir
+
+  enum { MaxMRUDirs = 10 };
+};
+
+#endif // FILESDOCKWIDGET_H
new file mode 100644
--- /dev/null
+++ b/libgui/src/find-files-dialog.cc
@@ -0,0 +1,376 @@
+/*
+
+Copyright (C) 2013 John Donoghue
+
+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/>.
+
+*/
+
+#include "find-files-dialog.h"
+#include "find-files-model.h"
+#include "resource-manager.h"
+#include <QPushButton>
+#include <QDialogButtonBox>
+#include <QGridLayout>
+#include <QLabel>
+#include <QLineEdit>
+#include <QComboBox>
+#include <QCheckBox>
+#include <QHeaderView>
+#include <QTableView>
+#include <QFileDialog>
+#include <QStatusBar>
+#include <QIcon>
+#include <QFileInfo>
+#include <QTimer>
+#include <QDirIterator>
+#include <QTextStream>
+#include <QGroupBox>
+
+find_files_dialog::find_files_dialog (QWidget * p)
+ : QDialog (p)
+{
+  setWindowTitle (tr("Find Files"));
+  setWindowIcon (QIcon (":/actions/icons/search.png"));
+
+  _dir_iterator = 0;
+
+  _timer = new QTimer (this);
+  connect(_timer, SIGNAL(timeout()), this, SLOT(look_for_files()));
+
+  QSettings *settings = resource_manager::get_settings ();
+
+  QLabel * file_name_label = new QLabel (tr ("Named:"));
+  _file_name_edit = new QLineEdit;
+  _file_name_edit->setToolTip (tr ("Enter the filename expression"));
+
+  _file_name_edit->setText (settings->value ("findfiles/file_name","*").toString ());
+  file_name_label->setBuddy (_file_name_edit);
+
+  QLabel * start_dir_label = new QLabel (tr ("Start in:"));
+
+  _start_dir_edit = new QLineEdit;
+  _start_dir_edit->setText (settings->value ("findfiles/start_dir",QDir::currentPath()).toString());
+  _start_dir_edit->setToolTip (tr ("Enter the start directory"));
+  start_dir_label->setBuddy (_start_dir_edit);
+
+  _browse_button = new QPushButton (tr ("Browse..."));
+  _browse_button->setToolTip (tr ("Browse for start directory"));
+  connect(_browse_button, SIGNAL(clicked()), this, SLOT(browse_folders()));
+
+  _recurse_dirs_check = new QCheckBox (tr ("Recurse directories"));
+  _recurse_dirs_check->setChecked (settings->value ("findfiles/recurse_dirs", false).toBool());
+  _recurse_dirs_check->setToolTip (tr ("Search recursively through directories for matching files"));
+
+  _include_dirs_check = new QCheckBox (tr ("Include directories"));
+  _include_dirs_check->setChecked (settings->value ("findfiles/include_dirs", false).toBool());
+  _include_dirs_check->setToolTip (tr ("Include matching directories in search results"));
+
+  _name_case_check = new QCheckBox (tr ("Name case insensitive"));
+  _name_case_check->setChecked (settings->value ("findfiles/name_case", false).toBool());
+  _name_case_check->setToolTip (tr ("Set matching name is case insensitive"));
+
+  _contains_text_check = new QCheckBox (tr("Contains text:"));
+  _contains_text_check->setToolTip (tr ("Search must match text"));
+  _contains_text_check->setChecked (settings->value ("findfiles/check_text", false).toBool());
+
+  _contains_text_edit = new QLineEdit ();
+  _contains_text_edit->setToolTip (tr ("Text to match"));
+  _contains_text_edit->setText (settings->value ("findfiles/contains_text", "").toString());
+
+  _content_case_check = new QCheckBox (tr("Text case insensitive"));
+  _content_case_check->setChecked (settings->value ("findfiles/content_case", false).toBool());
+  _content_case_check->setToolTip (tr ("Set text content is case insensitive"));
+  
+  find_files_model * model = new find_files_model ();
+  _file_list = new QTableView;
+  _file_list->setWordWrap (false);
+  _file_list->setModel (model);
+  _file_list->setShowGrid (false);
+  _file_list->setSelectionBehavior(QAbstractItemView::SelectRows);
+  _file_list->setSelectionMode(QAbstractItemView::SingleSelection);
+  _file_list->setAlternatingRowColors(true);
+  _file_list->setToolTip (tr ("Search results"));
+  _file_list->horizontalHeader ()->restoreState (settings->value ("findfiles/column_state").toByteArray ());
+  _file_list->sortByColumn (
+              settings->value ("findfiles/sort_files_by_column",0).toInt (),
+              static_cast<Qt::SortOrder>(settings->value ("findfiles/sort_files_by_order",Qt::AscendingOrder).toUInt ()));
+
+  connect (_file_list, SIGNAL(doubleClicked(const QModelIndex&)),
+           this,       SLOT(item_double_clicked(const QModelIndex &)));
+
+  _status_bar = new QStatusBar;
+  _status_bar->showMessage (tr("Idle."));
+
+  _find_button =  new QPushButton (tr("Find"));
+  _find_button->setToolTip (tr ("Start search for matching files"));
+  connect (_find_button, SIGNAL(clicked()), this, SLOT(start_find()));
+
+  _stop_button =  new QPushButton (tr("Stop"));
+  _stop_button->setToolTip (tr ("Stop searching"));
+  _stop_button->setEnabled (false);
+  connect (_stop_button, SIGNAL(clicked()), this, SLOT(stop_find()));
+
+  // layout everything
+  QDialogButtonBox * button_box = new QDialogButtonBox (Qt::Vertical);
+  button_box->addButton (_find_button, QDialogButtonBox::ActionRole);
+  button_box->addButton (_stop_button, QDialogButtonBox::ActionRole);
+
+  // add dialog close button
+  _close_button = button_box->addButton (QDialogButtonBox::Close);
+  connect (button_box,    SIGNAL (rejected ()),
+           this,          SLOT (close ()));
+
+  // name options
+  QGroupBox * name_group = new QGroupBox(tr("File name/location"));
+  QGridLayout * name_layout = new QGridLayout;
+  name_group->setLayout(name_layout);
+
+  name_layout->addWidget (file_name_label,1,1, 1,1);
+  name_layout->addWidget (_file_name_edit,1,2, 1,-1);
+
+  name_layout->addWidget (start_dir_label,2,1);
+  name_layout->addWidget (_start_dir_edit,2,2,1,3);
+  name_layout->addWidget (_browse_button,2,5);
+  name_layout->setColumnStretch (2,1);
+
+  name_layout->addWidget (_recurse_dirs_check,3,1);
+  name_layout->addWidget (_include_dirs_check,3,2);
+  name_layout->addWidget (_name_case_check,3,3);
+
+  // content options
+  QGroupBox * content_group = new QGroupBox(tr("File contents"));
+  QGridLayout * content_layout = new QGridLayout;
+  content_group->setLayout(content_layout);
+  content_layout->addWidget (_contains_text_check,4,1);
+  content_layout->addWidget (_contains_text_edit,4,2,1,3);
+  content_layout->setColumnStretch (2,1);
+  content_layout->addWidget (_content_case_check,5,1);
+
+
+  QGridLayout *main_layout = new QGridLayout;
+  main_layout->setSizeConstraint (QLayout::SetFixedSize);
+  main_layout->addWidget (name_group, 0, 0);
+  main_layout->addWidget (content_group, 1, 0);
+  main_layout->addWidget (button_box, 0, 1,3,1);
+  main_layout->addWidget (_file_list,2,0);
+  main_layout->setRowStretch (2,1);
+  main_layout->addWidget (_status_bar,3,0,1,-1);
+
+
+  setLayout (main_layout);
+
+  connect (this, SIGNAL(finished(int)), this, SLOT(handle_done(int)));
+}
+
+find_files_dialog::~find_files_dialog ()
+{
+  QSettings *settings = resource_manager::get_settings ();
+
+  int sort_column = _file_list->horizontalHeader ()->sortIndicatorSection ();
+  Qt::SortOrder sort_order = _file_list->horizontalHeader ()->sortIndicatorOrder ();
+  settings->setValue ("findfiles/sort_files_by_column", sort_column);
+  settings->setValue ("findfiles/sort_files_by_order", sort_order);
+  settings->setValue ("findfiles/column_state", _file_list->horizontalHeader ()->saveState ());
+
+  settings->setValue ("findfiles/file_name", _file_name_edit->text());
+
+  settings->setValue ("findfiles/start_dir", _start_dir_edit->text());
+
+  settings->setValue ("findfiles/recurse_dirs", _recurse_dirs_check->text());
+  settings->setValue ("findfiles/include_dirs", _include_dirs_check->text());
+  settings->setValue ("findfiles/name_case", _name_case_check->text());
+
+  settings->setValue ("findfiles/contains_text", _contains_text_edit->text());
+  settings->setValue ("findfiles/check_text", _contains_text_check->isChecked ());
+  settings->setValue ("findfiles/content_case", _content_case_check->isChecked ());
+
+  settings->sync ();
+
+  if(_dir_iterator)
+    delete _dir_iterator;
+}
+
+void find_files_dialog::handle_done (int button)
+{
+  // make sure we stopped processing 
+  stop_find ();
+}
+
+void find_files_dialog::set_search_dir(const QString &dir)
+{
+  stop_find();
+  _start_dir_edit->setText(dir);
+}
+
+void 
+find_files_dialog::start_find ()
+{
+  stop_find();
+
+  find_files_model *m = static_cast<find_files_model *> (_file_list->model());
+  m->clear();
+
+  QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags;
+  if (_recurse_dirs_check->isChecked ())  flags |= QDirIterator::Subdirectories;
+
+  QDir::Filters filters = QDir::Dirs|QDir::NoDotAndDotDot|QDir::Files;
+  if (!_name_case_check->isChecked ())
+    filters |=  QDir::CaseSensitive;
+
+  QStringList nameFilters;
+  nameFilters.append (_file_name_edit->text());
+
+  if (_dir_iterator) delete _dir_iterator;
+
+  _dir_iterator = new QDirIterator (_start_dir_edit->text(), nameFilters, filters, flags);
+  
+  // enable/disable widgets 
+  _find_button->setEnabled (false);
+  _stop_button->setEnabled (true);
+  _close_button->setEnabled (false);
+  _browse_button->setEnabled (false);
+  _start_dir_edit->setEnabled (false);
+  _file_name_edit->setEnabled (false);
+  _recurse_dirs_check->setEnabled (false);
+  _include_dirs_check->setEnabled (false);
+  _name_case_check->setEnabled (false);
+  _contains_text_check->setEnabled (false);
+  _content_case_check->setEnabled (false);
+  _contains_text_edit->setEnabled (false);
+
+  _status_bar->showMessage (tr("Searching..."));
+  _timer->start (0);
+}
+
+void 
+find_files_dialog::stop_find ()
+{
+  _timer->stop ();
+
+  _find_button->setEnabled (true);
+  _stop_button->setEnabled (false);
+  _close_button->setEnabled (true);
+  _browse_button->setEnabled (true);
+  _start_dir_edit->setEnabled (true);
+  _file_name_edit->setEnabled (true);
+  _recurse_dirs_check->setEnabled (true);
+  _include_dirs_check->setEnabled (true);
+  _name_case_check->setEnabled (true);
+  _contains_text_check->setEnabled (true);
+  _content_case_check->setEnabled (true);
+  _contains_text_edit->setEnabled (true);
+
+  find_files_model *m = static_cast<find_files_model *> (_file_list->model());
+  QString res_str = QString ("%1 matches").arg(m->rowCount());
+
+  _status_bar->showMessage (res_str);
+}
+
+void 
+find_files_dialog::browse_folders ()
+{
+  QString dir =
+    QFileDialog::getExistingDirectory (this, tr ("Set search directory"), 
+      _start_dir_edit->text());
+
+  if (! dir.isEmpty ())
+    {
+      _start_dir_edit->setText (dir);
+    }
+}
+
+void 
+find_files_dialog::item_double_clicked (const QModelIndex &idx)
+{
+  find_files_model *m = static_cast<find_files_model *> (_file_list->model ());
+
+  QFileInfo info = m->fileInfo (idx);
+
+  if(idx.column () == 1)
+    {
+      // clicked in directory part
+      emit dir_selected (info.absolutePath());
+    }
+  else
+    {
+      // clicked in filename part
+      if(info.isDir ())
+        emit dir_selected (info.absoluteFilePath());
+      else
+        emit file_selected (info.absoluteFilePath());
+    }
+}
+
+void
+find_files_dialog::look_for_files ()
+{
+  if(_dir_iterator && _dir_iterator->hasNext ())
+    {
+      QFileInfo info (_dir_iterator->next ());
+    
+      find_files_model *m = static_cast<find_files_model *> (_file_list->model ());
+
+      if(is_match (info))
+        m->addFile (info);
+    } 
+  else
+    {
+      stop_find (); 
+    }
+}
+
+bool find_files_dialog::is_match (const QFileInfo &info)
+{
+  bool match = true;
+  if (info.isDir ())
+    {
+      if(!_include_dirs_check->isChecked ()) match = false;
+      if(_contains_text_check->isChecked ()) match = false;
+    }
+  else
+    {
+      // a file
+      if (_contains_text_check->isChecked ())
+        {
+          match = false;
+
+          QFile file(info.absoluteFilePath ());
+          if (file.open (QIODevice::ReadOnly))
+            {
+              QTextStream stream (&file);
+
+              QString line;
+              QString match_str = _contains_text_edit->text ();
+
+              Qt::CaseSensitivity cs = _content_case_check->isChecked () ?
+                   Qt::CaseInsensitive : Qt::CaseSensitive;
+
+              do
+                {
+                  line = stream.readLine ();
+                  match = line.contains (match_str, cs);
+                }
+              while(!line.isNull () && match == false);
+            }
+
+        }
+    }
+
+  return match; 
+}
+
new file mode 100644
--- /dev/null
+++ b/libgui/src/find-files-dialog.h
@@ -0,0 +1,79 @@
+/*
+
+Copyright (C) 2013 John Donoghue
+
+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 (find_files_dialog_h)
+#define find_files_dialog_h
+
+#include <QDialog>
+#include <QModelIndex>
+#include <QFileInfo>
+
+class QLineEdit;
+class QPushButton;
+class QTableView;
+class QTimer;
+class QDirIterator;
+class QCheckBox;
+class QStatusBar;
+
+class find_files_dialog : public QDialog
+{
+  Q_OBJECT
+public:
+  find_files_dialog (QWidget * parent=0);
+  virtual ~find_files_dialog ();
+
+signals:
+  void file_selected (const QString &fileName);
+  void dir_selected (const QString &fileName);
+
+public slots:
+  void set_search_dir(const QString &dir);
+
+private slots:
+  void start_find ();
+  void stop_find ();
+  void browse_folders ();
+  void look_for_files ();
+  void item_double_clicked (const QModelIndex&);
+  void handle_done(int);
+private:
+  bool is_match(const QFileInfo &info);
+  QLineEdit * _start_dir_edit;
+  QLineEdit * _file_name_edit;
+  QPushButton * _stop_button;
+  QPushButton * _find_button;
+  QPushButton * _close_button;
+  QPushButton * _browse_button;
+  QTableView   * _file_list;
+  QTimer      * _timer;
+  QCheckBox   * _recurse_dirs_check;
+  QCheckBox   * _include_dirs_check;
+  QCheckBox   * _name_case_check;
+  QCheckBox   * _contains_text_check;
+  QCheckBox   * _content_case_check;
+  QLineEdit * _contains_text_edit;
+  QDirIterator * _dir_iterator;
+  QStatusBar * _status_bar;
+};
+
+#endif // find_files_dialog_h
+
new file mode 100644
--- /dev/null
+++ b/libgui/src/find-files-model.cc
@@ -0,0 +1,135 @@
+/*
+
+Copyright (C) 2013 John Donoghue
+
+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/>.
+
+*/
+
+#include "find-files-model.h"
+#include <QFileIconProvider>
+
+find_files_model::find_files_model (QObject *p)
+  : QAbstractListModel(p)
+{
+  _columnNames.append (tr ("Filename"));
+  _columnNames.append (tr ("Directory"));
+}
+
+find_files_model::~find_files_model ()
+{
+}
+
+void 
+find_files_model::clear ()
+{
+  beginResetModel();
+
+  _files.clear();
+
+  endResetModel ();
+}
+
+void 
+find_files_model::addFile (const QFileInfo &info)
+{
+  beginInsertRows(QModelIndex(), _files.size(), _files.size() );
+
+  _files.append(info);
+
+  endInsertRows(); 
+}
+
+int 
+find_files_model::rowCount (const QModelIndex & p) const
+{
+  return _files.size();
+}
+
+int 
+find_files_model::columnCount (const QModelIndex & p) const
+{
+  return _columnNames.size ();
+}
+
+QVariant 
+find_files_model::data (const QModelIndex& idx, int role) const
+{
+  QVariant retval;
+
+  if (idx.isValid ())
+    {
+      if(role == Qt::DisplayRole)
+      {
+        switch (idx.column ())
+          {
+          case 0:
+            retval = QVariant (_files[idx.row()].fileName());
+            break;
+
+          case 1:
+            retval = QVariant (_files[idx.row()].absolutePath());
+            break;
+
+          default:
+            break;
+          }
+      }
+      else if(role == Qt:: DecorationRole)
+      {
+        switch (idx.column())
+          {
+          case 0:
+            retval = fileIcon(idx);
+          default:
+            break;
+          }
+      }
+    }
+
+  return retval;
+}
+
+QVariant 
+find_files_model::headerData (int section, Qt::Orientation orientation, int role) const
+{
+  if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
+    return _columnNames[section];
+  else
+    return QVariant ();
+}
+
+QFileInfo 
+find_files_model::fileInfo (const QModelIndex & p) const
+{
+  if(p.isValid ())
+  {
+    return _files[p.row()];
+  }
+  return QFileInfo ();
+}
+
+QIcon
+find_files_model::fileIcon (const QModelIndex &p) const
+{
+  QFileIconProvider icon_provider;
+  if(p.isValid ())
+  {
+    return icon_provider.icon (_files[p.row()]);
+  }
+  return QIcon ();
+}
new file mode 100644
--- /dev/null
+++ b/libgui/src/find-files-model.h
@@ -0,0 +1,59 @@
+/*
+
+Copyright (C) 2013 John Donoghue
+
+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 (find_files_model_h)
+#define find_files_model_h
+
+#include <QAbstractListModel>
+#include <QStringList>
+#include <QList>
+#include <QFileInfo>
+#include <QIcon>
+
+
+class find_files_model : public QAbstractListModel
+{
+public:
+  find_files_model(QObject *p=0);
+  ~find_files_model ();
+
+  void clear();
+
+  void addFile(const QFileInfo &info);
+
+  int rowCount(const QModelIndex & p=QModelIndex()) const;
+
+  int columnCount(const QModelIndex & p=QModelIndex()) const;
+
+  QVariant data (const QModelIndex& idx, int role) const;
+
+  QVariant headerData (int section, Qt::Orientation orientation,
+                       int role = Qt::DisplayRole) const;
+
+  QFileInfo fileInfo (const QModelIndex & p) const;
+  QIcon     fileIcon (const QModelIndex &p) const;
+private:
+  QList<QFileInfo> _files;
+  QStringList _columnNames;
+};
+
+#endif // find_files_model_h
+
new file mode 100644
--- /dev/null
+++ b/libgui/src/history-dock-widget.cc
@@ -0,0 +1,171 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 <QApplication>
+#include <QClipboard>
+#include <QVBoxLayout>
+#include <QMenu>
+
+#include "error.h"
+
+#include "cmd-hist.h"
+
+#include "history-dock-widget.h"
+
+history_dock_widget::history_dock_widget (QWidget *p)
+  : octave_dock_widget (p)
+{
+  setObjectName ("HistoryDockWidget");
+  setStatusTip (tr ("Browse and search the command history."));
+
+  connect (this, SIGNAL (command_create_script (const QString&)),
+           p, SLOT (new_file (const QString&)));
+
+  connect (this, SIGNAL (information (const QString&)),
+           p, SLOT (report_status_message (const QString&)));
+
+  connect (this, SIGNAL (command_double_clicked (const QString&)),
+           p, SLOT (execute_command_in_terminal (const QString&)));
+
+  construct ();
+}
+
+void
+history_dock_widget::construct ()
+{
+  _history_model = new QStringListModel ();
+  _sort_filter_proxy_model.setSourceModel (_history_model);
+  _history_list_view = new QListView (this);
+  _history_list_view->setModel (&_sort_filter_proxy_model);
+  _history_list_view->setAlternatingRowColors (true);
+  _history_list_view->setEditTriggers (QAbstractItemView::NoEditTriggers);
+  _history_list_view->setStatusTip (tr ("Doubleclick a command to transfer it to the terminal."));
+  _history_list_view->setSelectionMode (QAbstractItemView::ExtendedSelection);
+  _history_list_view->setContextMenuPolicy(Qt::CustomContextMenu);
+  connect(_history_list_view, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(ctxMenu(const QPoint &)));
+
+  _filter_line_edit = new QLineEdit (this);
+  _filter_line_edit->setStatusTip (tr ("Enter text to filter the command history."));
+  QVBoxLayout *vbox_layout = new QVBoxLayout ();
+
+  setWindowIcon (QIcon(":/actions/icons/logo.png"));
+  setWindowTitle (tr ("Command History"));
+  setWidget (new QWidget ());
+
+  vbox_layout->addWidget (_history_list_view);
+  vbox_layout->addWidget (_filter_line_edit);
+  vbox_layout->setMargin (2);
+
+  widget ()->setLayout (vbox_layout);
+
+  connect (_filter_line_edit, SIGNAL (textEdited (QString)),
+           &_sort_filter_proxy_model, SLOT (setFilterWildcard (QString)));
+
+  connect (_history_list_view, SIGNAL (doubleClicked (QModelIndex)),
+           this, SLOT (handle_double_click (QModelIndex)));
+
+  setFocusProxy (_filter_line_edit);
+}
+
+void history_dock_widget::ctxMenu(const QPoint &xpos) {
+    QMenu menu(this);
+    menu.addAction(tr("Copy"), this, SLOT(handle_contextmenu_copy(bool)));
+    menu.addAction(tr("Evaluate"), this, SLOT(handle_contextmenu_evaluate(bool)));
+    menu.addAction(tr("Create script"), this, SLOT(handle_contextmenu_create_script(bool)));
+    menu.exec(_history_list_view->mapToGlobal(xpos));
+}
+
+void history_dock_widget::handle_contextmenu_copy(bool)
+{
+  QString text;
+  QItemSelectionModel *selectionModel = _history_list_view->selectionModel();
+  QModelIndexList rows = selectionModel->selectedRows();
+  QModelIndexList::iterator it;
+  for (it=rows.begin() ; it != rows.end(); it++) {
+    if ((*it).isValid()) {
+      text += (*it).data().toString()+"\n";
+    }
+  }
+  QApplication::clipboard()->setText(text);
+}
+
+void history_dock_widget::handle_contextmenu_evaluate(bool)
+{
+  QItemSelectionModel *selectionModel = _history_list_view->selectionModel();
+  QModelIndexList rows = selectionModel->selectedRows();
+  QModelIndexList::iterator it;
+  for (it=rows.begin() ; it != rows.end(); it++) {
+    if ((*it).isValid()) {
+      emit command_double_clicked ((*it).data().toString()+"\n");
+    }
+  }
+}
+
+void
+history_dock_widget::handle_contextmenu_create_script (bool)
+{
+  QString text;
+  QItemSelectionModel *selectionModel = _history_list_view->selectionModel ();
+  QModelIndexList rows = selectionModel->selectedRows ();
+
+  for (QModelIndexList::iterator it = rows.begin (); it != rows.end (); it++)
+    {
+      if ((*it).isValid ())
+        text += (*it).data().toString() + "\n";
+    }
+
+  if (text.length () > 0)
+    emit command_create_script (text);
+}
+
+
+void
+history_dock_widget::handle_double_click (QModelIndex modelIndex)
+{
+  emit command_double_clicked (modelIndex.data().toString()+"\n");
+}
+
+void
+history_dock_widget::set_history (const QStringList& hist)
+{
+  _history_model->setStringList (hist);
+  _history_list_view->scrollToBottom ();
+}
+
+void
+history_dock_widget::append_history (const QString& hist_entry)
+{
+  QStringList lst = _history_model->stringList ();
+  lst.append (hist_entry);
+  _history_model->setStringList (lst);
+  _history_list_view->scrollToBottom ();
+}
+
+void
+history_dock_widget::clear_history (void)
+{
+  _history_model->setStringList (QStringList ());
+}
new file mode 100644
--- /dev/null
+++ b/libgui/src/history-dock-widget.h
@@ -0,0 +1,76 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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/>.
+
+*/
+
+#ifndef HISTORYDOCKWIDGET_H
+#define HISTORYDOCKWIDGET_H
+
+#include <QLineEdit>
+#include <QListView>
+#include <QSortFilterProxyModel>
+#include <QStringListModel>
+#include "octave-dock-widget.h"
+
+class history_dock_widget : public octave_dock_widget
+{
+  Q_OBJECT
+
+public:
+
+  history_dock_widget (QWidget *parent = 0);
+
+public slots:
+
+  void set_history (const QStringList& hist);
+  void append_history (const QString& hist_entry);
+  void clear_history (void);
+
+signals:
+
+  void information (const QString& message);
+
+  /** Emitted, whenever the user double-clicked a command in the history. */
+  void command_double_clicked (const QString& command);
+
+  /** Emitted whenever the user selects command and chooses Create
+      script from popupmenu. */
+  void command_create_script (const QString& commands);
+
+private slots:
+
+  void handle_double_click (QModelIndex modelIndex);
+  void handle_contextmenu_copy(bool flag);
+  void handle_contextmenu_evaluate(bool flag);
+  void handle_contextmenu_create_script(bool flag);
+  void ctxMenu(const QPoint &pos);
+
+private:
+
+  void construct ();
+  QListView *_history_list_view;
+  QLineEdit *_filter_line_edit;
+  QSortFilterProxyModel _sort_filter_proxy_model;
+
+  /** Stores the current history_model. */
+  QStringListModel *_history_model;
+};
+
+#endif // HISTORYDOCKWIDGET_H
new file mode 100644
index 0000000000000000000000000000000000000000..5587ddee1c2a3b144104b36b6165d7f571ae4136
GIT binary patch
literal 3324
zc$@+J3<L9tP)<h;3K|Lk000e1NJLTq000mG000mO1^@s6AM^iV000V4X+uL$P-t&-
zZ*ypGa3D!TLm+T+Z)Rz1WdHzp+MQEpR8#2|J@?-9LQ9B%luK_?6$l_wLW_VDktQl3
z2@pz%A)(n7QNa;KMFbnjpojyGj)066Q7jCK3fKqaA)=0hqlk*i`{8?|Yu3E?=FR@K
z*FNX0^PRKL2fzpnmPj*EHGmAMLLL#|gU7_i;p8qrfeIvW01ybXWFd3?BLM*Temp!Y
zBESc}00DT@3kU$fO`E_l9Ebl8>Oz@Z0f2-7z;ux~O9+4z06=<<LZ$#fMgf4Gm?l#I
zpacM5%VT2W08lLeU?+d((*S^-_?deF09%wH6#<};03Z`(h(rKrI{>WDR*FRcSTFz-
zW=q650N5=6FiBTtNC2?60Km==3$g$R3;-}uh=nNt1bYBr$Ri_o0EC$U6h`t_Jn<{8
z5a%iY0C<_QJh>z}MS)ugEpZ1|S1ukX&Pf+56gFW3VVXcL!g-k)GJ!M?;PcD?0HBc-
z5#WRK{dmp}uFlRjj<yb8E$Y7p{~}^y<NoE(t8hR70O53g(f%wivl@Uq27qn;q9yJG
zXkH7Tb@z*AvJXJD0HEpGSMzZAemp!yp^&-R+2!Qq*h<7gTVcvqeg0>{U%*%WZ25jX
z{P*?XzTzZ-GF^d31o+^>%=Ap99M6&ogks$0k4OBs3;+Bb(;~!4V!2o<6ys46agIcq
zjPo+3B8fthDa9qy|77CdEc*jK-!%ZRYCZvbku9iQV*~a}ClFY4z~c7+0P?$U!PF=S
z1Au6Q;m>#f??3%Vpd|o+W=WE9003S@Bra6Svp>fO002awfhw>;8}z{#EWidF!3EsG
z3;bX<ghC|5!a@*23S@vBa$qT}f<h>U&9EIRU@z1_9W=mEXoiz;4lcq~xDGvV5BgyU
zp1~-*fe8db$Osc*A=-!mVv1NJjtCc-h4>-CNCXm#Bp}I%6j35eku^v$Qi@a{RY)E3
zJ#qp$hg?Rwkvqr$GJ^buyhkyVfwECO)C{#lxu`c9ghrwZ&}4KmnvWKso6vH!8a<3Q
zq36)6Xb;+tK10Vaz~~qUGsJ8#F2=(`u{bOVlVi)VBCHIn#u~6ztOL7=^<&SmcLWlF
zMZgI*1b0FpVIDz9SWH+>*hr`#93(Um+6gxa1B6k+CnA%mOSC4s5&6UzVlpv@SV$}*
z))J2sFA#f(L&P^E5{W}HC%KRUNwK6<(h|}}(r!{C=`5+6G)NjFlgZj-YqAG9lq?`C
z$c5yc<iq4M<QwE6@>>d>VnA`E_*3F2Qp##d8RZb=H01_mm@+|Cqnc9PsG(F5HIG_C
zt)aG3uTh7n6Et<2In9F>NlT@zqLtGcXcuVrX|L#Xx)I%#9!{6gSJKPrN9dR61N3(c
z4Tcqi$B1Vr8Jidf7-t!G7_XR2rWw<V8OKyGH!<s&=a~<gZ&g?-wkmuTk;)2{N|h#+
z8!9hUsj8-`-l_{#^Hs}KkEvc$eXd4TGgITK3DlOWRjQp(>r)$3XQ?}=hpK0&Z&W{|
zep&sA23f;Q!%st`QJ}G3<GjWo3u76xcq}1n4XcKAfi=V?vCY|hb}GA={T;iDJ*ugp
zIYTo_Ggq@x^OR;k2jiG=_?&c33Fj!Mm-Bv#-W2aC;wc-ZG)%cMWn62jmY0@Tt4OO+
zt4Hg-Hm>cbou<7-yIK2z4nfCCCtN2-XOGSWo##{8Q{ATurxr~;I`ytDs%xbip}RzP
zziy}Qn4Z2~fSycmr`~zJ=lUFdFa1>gZThG6M+{g7vkW8#+YHVaJjFF}Z#*3@$J_By
zLtVo_L#1JrVVB{Ak-5=4qt!-@Mh}c>#$4kh<88)m#-k<%CLtzEP3leVno>=<rYWX7
zOgl`+&CJcB&DNPUn>{htGUuD;o7bD)w_sX$S}eAxwzy?UvgBH(S?;#HZiQMoS*2K2
zT3xe7t(~nU*1N5{rxB;QPLocnp4Ml>u<^FZwyC!nu;thW+pe~4wtZn|Vi#w(#jeBd
zlf9FDx_yoPJqHbk*$%56S{;6Kv~m<WRyy9A&YbQ)eZ};a=`Uwk&k)bpGvl@s%PGWZ
zol~3BM`ssjxpRZ_h>M9!g3B(KJ}#RZ#@)!h<Vtk)ab4kh()FF2vzx;0sN1jZHtuQe
zhuojcG@mJ+Su=Cc!^lJ6QRUG;3!jxRYu~JXPeV_EXSL@eFJmu}SFP8ux21Qg_hIiB
zKK4FxpW{B`JU8Al-dSJFH^8^Zx64n%Z=PR;-$Q>R|78Dq|Iq-afF%KE1Brn_fm;Im
z_<DRHzm7jT+hz8$+3i7$pt(U6L63s1g5|-jA!x|#kgXy2=a|ls&S?&XP=4sv&<A1W
zVT;3l3@3$$g;$0@j&O)r8qqPAHFwe6Lv!Cm`b3sQ-kWDJPdTqGN;N7zsxE3g+Bdp1
zx<AG)W?9VDSe;l&Y)c$DE-J1zZfw5a{O$9H;+^6P<9ipFFUVbRd7;k2^o6GusV)*M
zI+j38h)y_^@IeqNs1}SR@)LI@jtY6g9l~cKFVQy9h}c71DjrVqNGeTwlI)SZHF+e(
zGo>u$xr8UFki1L{Ox>G0o)(&RAZ;=|I=wN2l97;cLaHH6leTB-XXa*h%dBOEvi`+x
zi?=Txl?TadvyiL>SuF~-LZ;|cS}4~l2eM~nS7yJ>iOM;atDY;(?aZ^v+mJV$@1Ote
z62cPUlD4IWOIIx&SmwQ~YB{nzae3Pc;}r!fhE@iwJh+OsDs9zItL;~pu715HdQEGA
zUct(O!L<Qv>kCy1<%NCg+}G`0PgpNm-?d@-hMgNe6^V+j6x$b<6@S<$+<4_1hi}Ti
zncS4LsjI}fWY1>OX6feMEuLErma3QLmkw?X+1j)X-&VBk_4Y;EFPF_I+q;9dL%E~B
zJh;4Nr^(LEJ3myURP<E(R5tF?-L+xY_-@he8+*L=H0;&eTfF!EKFPk@RRL8^)n?UY
z`$_w=_dl+Qs_FQa`)ysVPHl1R#{<#>{Rblsw%57T)g973R8o)DE9*xN#~;4_o$q%o
z4K@u`jhx2fBXC4{<mvYb-}fF3I@)%Od#vFH(;s#nXB{tULYnfLMw?Tb`&(jLx=+kL
z(bnqTdi+P*9}k=~JXv{4^Hj-c+UbJRlV|eJjGdL8eSR+a++f?HwtMGe&fjVeZ|}Mg
zbm7uP|BL54ygSZZ^0;*JvfJeoSGZT2uR33C>U8Qn{*%*B$Ge=nny$HAYq{=vy|sI0
z_vss+H_qMky?OB#|JK!>IX&II^LlUh#rO5!7TtbwC;iULyV-Xq?ybB}ykGP{?LpZ?
z-G|jbTmIbG@7#ZCz;~eY(cDM(28Dyq{*m>M4?_iynUBkc4TkHUI6gT!;y-fz>HMcd
z&t%Ugo)`Y2{>!cx7B7DI)$7;J(U{Spm-3gBzioV_{p!H$8L!*M!p0uH$#^p{Ui4P`
z?ZJ24cOCDe-w#jZd?0@)|7iKK^;6KN`;!@ylm7$*nDhK&GcDTy000JJOGiWi{{a60
z|De66lK=n!32;bRa{vGf5&!@T5&_cPe*6Fc00(qQO+^RX2LcBWD9bs{K>z>(E=fc|
zR5;6(lFv(&Q51%sbANo!sFUWxNE<;ih0KWh584Fn!i|+tkPDYV%arUNa3xU?CA4iR
zu37{w3e#35(U>`;PFZR?Dt_NL_q#1-go+XDz_YvWd+s^smDhJKQms5339Ok&HyyiB
zTv{GYEW=Xeo#KG<30-wZYfhgX9IkCU(>>%vMiT!Y20+o_Vsu2dub=jwp8G`H|JTDf
zN3-|T0VyDbCj*F2=yWA&d=w(8K=x`s@O&iyVb*%f(Ed24wXOA%QSqrjM{QnIJBo9F
z1+Pq|6rdEuF$4v&ef@;bp4?mdG#{HZ4*<mfoEZSRP-G!FiFfBwRw01+@;akM&;mg%
zK5Axu{1JtPg+WR2*zkQOL6pN9N4)EZwo24B2Bb4!13<u7@D9Q)Bo)(fYXHWdj(+<x
z9~$;H%AG>Mg|NE;+bfW+hg1rJ0DKHd1UdneAekmQdN0>*kH2_m$iFP#!U20gsq$^>
z!2-HM8VJg`0<6rvA>NI0hR6vT!64KiBnbPraupgX)Rre%oPw{jzg}s>ZIhcvv_%<<
z22A3y`}!aaEhj+!6i>tQ9244bO@yK;tnn7e0gV-oBZyCE%`|eerHgtjl!~zU9txkC
z6ydrEMF67|v(;jl2%TEfD*^ST9mvhVYMx1LxPh>Bm?$?Om~b0%?_f30m^NHNSpO@^
z2dS0fN4P`uaT+$)8Pk?Km6dWR17IzVnTj{*1}3YC0e%BG8`TKv>_FH60000<MNUMn
GLSTZIU@G4L
new file mode 100644
index 0000000000000000000000000000000000000000..814f916b5aab5d9474f3e857e982b123ac673b0c
GIT binary patch
literal 1382
zc$@)d1)2JZP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000FoNkl<ZScSco
zS!^BE8OML$cV@1ASC4IC;s(dbO&sjR1OlNIFO>=;0)!9`NC-jFsu)2qWl;-MVw0%U
zKJ}%PLd6q2@xmgW*g+@(9F{E2B_u?|S$v)AB{X*I+?hKwhlgv6I`}%SaX8W^of(bh
z|2x04%!sv?v)g6&y!LEsa=gcv?C}qdWN)&sTwD0jLyOdOwwnk0iyONxy(;myd#=gX
zC(QQx+dkOxvjUVu%d>9{aJV$dy_=SKbw*xF-SOe`nXMlse-;2^gh-&T7;xJyYq)W9
z9<kgVS$1ZBw|(7t2M`flRrYI=-U57;U(SZ>*3y)5y2B{`IQ#n@J?9kw0a2kG!HF`A
zOv2#u7V<Z3puH`Z3&ZGzOwY$JWbgVUdtLxU6jV_W904N`25_V<Np906tiR$SjI}+n
zwSBp}KkZ(00EB9)$c$SW!C+*VxIEAL-*n)m+^#UPeYtIY+ZGu>P@~n<vzoCmR))d0
z7V_7xqpdZQiX!{3T<^{o8}9qeTO<HL1+2ve7F&sClvE;uiHLra!uxe6UEM86%+}cQ
zNyGi0U$zJUf~aC+OB_^YEgMu|qRg=g%Vb9z-M?xhn{qm%m_F~pFYo)w05}R!jP=9X
z6@;iC@ZT|?VuMHf#&(uokW56eea3re*UOE6+}*Sw0GTpCY_a7E)}On?ui%fD>8}`a
zYnPE<;el{#3_BVh-t)@^7yyi5qnOyQ5c}ad%laXl2{?YLLV1ZtM@KXD3DX(I?C>7h
z`-fTp&g=k!sDap4UmnME4dO>5I$4IvL>;R-niw1ycZSC*|7d#bKUa&&ouhy0J~<Bq
z0*+wg`5XA(a-xt#6c8xfyLl;(UU?yvg5F%-FT1=43csC)0Z?Oz#?KHOJ57urB2(vr
zRJZ6<U#9y~ea3Z!Y}(M6P+A;A;JX|<9pYvTf!dNdcJ$l;Dp(`cMHoa_z^YacMwuCC
zr>;eXx`fi0G<YdXd!qrA=Rf+6p;C#=nwEdoTmCfi)LQ?X0D>T*7)MdpU=c*8MlU}Y
zn6{#-Wa<?!V`$DA+M8TTW0svqeI}0{n9R0ayk+Fci(j2BtL7A71TlgbQ?-4T>S+_M
zBjl0>FJox+3@sU#J;jiHyY^wC;6QR^_jMyrtm&UMr=|g&ItR467-6RV>3Oen4UHMa
zODQXwUBK|}p@5-p_S^KzuD=u8$44Gt?a!7mw}I&qtNvg>v^ot^osLYs!AmI@WDUz3
zU5aCtF9v)j`}dztuk6|~{OA1Za|O>0pj!PFs349`t%+*5V}xwd;H8z;hN|-2gArft
z-iL<%*QwR(Hw{0s^7wqhYXeOG56mzi)VV@KTJchbe6vGr4exwgVdP-JW>$6mmDoN#
z^ze#czTve20JOTt#R!6su2&jT%95<1z0u|9Da-B?70Tc4JC$C&ZtKuP%is8ag69TM
zL5zY?jBCi&D_&apMb6Naa@kdiICQv(9Uc5SwdT^ROAodUE+o7rfJjxpI!ZR<;H8yS
zO%9PYyni%g^gsc}G5@aX+|XOPe_6E9@R|S?Ax7wINpN#ll4GYrJ}bo(Mnn8>_MXgi
ztiSz4Z|j>sC3sE%QBX%2A5b=4n4~avhA$2tMuv-p)Y{88o!GW?!OG_eAZQ@G{a#4_
zp$Ybu_gKe~=e~R9hTg>ro)f^v!kHt=Dq|ROjt{z>>+TroS@Qm3ht~vfa;@7d1I5+D
ob;W-7qAPD4>1kdx<!86=0e?S5N-cB<^Z)<=07*qoM6N<$f{US}pa1{>
new file mode 100644
index 0000000000000000000000000000000000000000..5e761587198608815a4625f26923e4c2c59d5ed1
GIT binary patch
literal 690
zc$@*U0!{siP)<h;3K|Lk000e1NJLTq000mG000jN1^@s6?Q>5r00004XF*Lt006JZ
zHwB960000PbVXQnQ*UN;cVTj606}DLVr3vnZDD6+Qe|Oed2z{QJOBU!L`g(JRCwBA
zV88=DRWZzeU(PTepBjJwV#Fo!p^`y>iJ$%c@81jzzux>*l$^-$0h>C20Aj*r!2kaY
z1+2RA0&IF(0)PK76yQ<^5I{H$U|?g4XLHbF;Br!C_{Yi=k4qUq0AV%YZ5cxXv#PWL
zBj;lVM()Q99O?=RPntv<{{7o6fUXuGfEfREG0gw_k3r!t(64_v*&P0H^D}_h+!2-x
z%pxzrivGNmV|YH}0K?zE3=H32d}Lr?=lJmP{-+B-uRQ<=AjZF)4D<h~swXfzSpX&8
zLCt-N!@(jz%+B!l=^uuBvraO+Jojz^KmdVb;d=u^!9PCcevS}*21e#@xZ~^(BTzE~
z!<A{b7(T!JTWGhNVFEw^!K3kg1w#UZ0LOf8D?SDm5e`hvKbaW5-U8aZ`5D8f*Z&f2
zcQPyh2?GQWN;-HyS+d~wo0t6}?!s6NxW4EO!-wa81Fd&3Y=8*^1P}{Kh)Sypuzr2T
z!0_=WMBpD%JOKlcos*H_-#^p@1rR_e2K;*Z$exoGlnj3XF(bpTkN<(u@t=WB80b(S
z;${a1!yg6*po#-9JpciOV!+=|Ume&v|1<o({hQ(WlYb0v-~PYw2N<OSLW~9qI!p`#
zyg)U780?Yt00a;`A%POfucvPrKHUDtaQnvJ4<FwDPc&T1U}(CD!SL0K|B0t|{r&Lt
z_Fs^X43G@~2q1VM-cDpt0Q&DfFcCEZ=?OY3Q2n~kfdQN+fL^EvCOk!-Qw$G4;s5~#
Y0GrXxbc~n>*8l(j07*qoM6N<$f~cq`1poj5
new file mode 100644
index 0000000000000000000000000000000000000000..122ea66f099371b3272cae63812cdac415557c46
GIT binary patch
literal 1173
zc$@*11Zw+<P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FZT01FZU(%pXi00007bV*G`2iyn*
z5gr0Dkv-M`00b3DL_t(o!_AgmXj^3%$A53m$#=4zHC<P$)v9eA&g!<_y1Mnk3!zdS
zf@p`RV0SS@@4Qgb;gv#nRm2XVV|XJd2$o(+Tt#r!b?aab+r+KKt?7q}ZL{R$oRgE|
zMLybY?Upnd_`pLBBzgb8_j%6qe_vr)7CQ+c1hoix<6^`2`Eh^YbEnW-Zp5-Igb*e1
z&i+1v9S!)6MNn0e%PD3q&og=cj}k=jKQ#k5Q&{ZSxj_PpVMwlms^v4IfvOW<llkt4
z2mtTZ5WvQUod*`fuy&`o25N?YnV_@HORb{>5bS8!EUs#h-uRp$=+|lvAQvC<J<mW!
z-=YHf^o#6+10bC)h;9R5)Lwj33zEy}QorwNK|x$MA0WWY)cmHGu2g{yJD-l%9$@nr
z_Ouf){#kFu2JyHGqcfnHv;rZZ7f=dcuK?czr}|;GIwNZH67*&8+ssngr{i!b2AatM
z;HS?1K4lxTS^<vs!&JopWms`5aQWD|LFGPXwE`S0w-R!>-hM`iP-lOiQZlQ|-IEe9
zbvoO;%49SZ0^Tm`B@{wXP6E9Zm{o7ZQ&2`I>t?0h)2wU`NxAURi$7oa{CMh@_q#u>
z6~MY#ZI^|qaqRZs-R*q(*%P059(`v2$Kxlv2WkPZQm$F$3^QqB8b~@VulMnIM@MM<
zWOrz*MWu4pdtjf_<v!5tR!ic#kwZ5vbYVktI#JyorZpF-#)e6yeNR)<p)R)&x2WrQ
z9^2BwkyoGa+DCr75#BV0<pK;B$FQeeDVo*V-eyd%3;a&9yL{*k3Z}4GHdz?<U8cS9
z<pCj#C^(#8H4z>8ikmahfumo9PgM+1fXEwBn^y_?GWcKWftJTG_cWpHZN|N?9U(jO
zs|pLSK%WIkfWw2OHxfPjC9&(*PrNV`9<Hbb0Hd(b1K-3FhH`bmYQ5bMaINHWs5Vn~
z`HY0qy6F(vgoKp@D+$?EknDL7Q$@H`>N~nH=H|Lz3)an#Ox&2N>Rx3{e)bN+3L<F1
z)Se{$??G%i2W}s@T;OnkWk5~`DF<>6{PkF=cBamLs~!q{?UAcG%I1E|&yfjafNY`c
zb_?u<`bvNsaOBgB!ThyfG17Wu^Mzz5p_>8;fsDY3Acvsn>SiJ93h4pMgxLxB`|8Sh
zN#@<E0U}X^WXC4kkpMYoVK3@C+|c|8h>hYG;np=qC7Cz6PKT3K1H|H703wBZfdV{)
zKv+2*_A9*A{1iUykWIquC5ZjSm=L^K6t8#;%Z>35yMuN0j6ZjTrmP8(Nm!a=Op-Z%
z_;fh2^RuA*s6!xYw;}R7EX^?_$-Hu>c=a#gb_a}&Wi5sN=S5geFeKUe;P7DBy!W-d
nwh=cBCX7|~17q8X|1aV{8S+Raw4Al<00000NkvXXu0mjf5!)@f
new file mode 100644
index 0000000000000000000000000000000000000000..a183a08ec073d4390d4f4d4a3416c184daf1326f
GIT binary patch
literal 1159
zc$@);1bF+2P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FZT01FZU(%pXi00007bV*G`2iyn*
z5gs-WCCOs|00aj~L_t(o!_Ai4PaJg=$3MRr_69DyxD@OflqOta8){*F&?p6oCWf>P
zwJ%hO0b@#^jMit<^bcq?u`k=0cxj_gCVle7WFhTC6LpcQH3Ds2l#77i(q(Tm^PBNu
z2G|gxEG)*8octz}ncw-&IcGlSCn%9wmbIhz$|#`;ApnRz<hj8D(V~<Y5JId4k8~cQ
zsWps$Uj_Jlq+GR(|MVB}=(RNwB^PkT$-t@Ojf5%<@VUY30iWak0E@L<eD%hA0GzQb
z6iRH7h6+M*39>oJ<{_82*K8ghEEAfG5gF{;n;rmY^5-D~tTv_P`06#wG_^Dm-zx!r
zVL*1vV&T{4_AUbe=*GsFh0Ow)%-#vmB)HWA5rrkd0?Q(`u!jQ17NMo)-!ieTWc>cj
z&ILrF9yky5072(=@`@1GfeRzEB*K0O`8JBMgD)C>;=^~=;Z<btBfwCk^H6XT$RvRm
zJu0JZ`=L4HlmkeaD&s3&;&;<K1CjIPKb$(=7<>q1l0YkvC@G4g@JXbhqCe8)1+RNO
zu(x2X3=qFtMLc@#(=(Peu$_I2Az_aVncO<rG6j@#NY~U-4bUTmU^`w+69%^nnVM%0
z1aH6kLOQ!N7uR&-*wKrz2c^isdRJ%jn|fmIZz69V<M7${%PXop2Q8E4Qk@5qnk2Xt
zWG2-|P!BXy*ZUf%8WO1ksZt5JKDJ2zW{^n)s!=1)Q+K)#tZ6K*4r$<#I_*Pmchv$G
zf)tPgazc>q{4h3OjDQOxv-E`h1UEt^u`i5q<T>hl`+!-{b#N&>{)8)7Tjl!*gbC=F
zj0(&AO_T254bwFNTrC<z9+jcC{RCGbGgBKT{c<-A{bv#GdC)Q-EpXS{oU?>oCQ~;N
z>If+JF!=)*6V;KAi$d`rj7BA`x28CMYl@!0Q;!9o?s$df{<jdGX~<;(7bs<ro3tB5
z*C3mMbke|GDRGrcbVFj9=8k5;piQ^|U|^*8rA+hb6Fy<yg!v^f6p#uiZV)ceG|1&3
zy8@;H<#|v&PV<W0PeVPEoS6FN^TXkTNmKyM@hl)6*8yGF<tP*21ysP?DF+HHuV+r)
z`!PA3_!+EnAOr*ew<AQZjyww#Q{a&TMGAB&(4^RP2992e-M?|J>%{age4!{DtA7SW
zxgFTjVP*=n?Aq9MDK>dkLr0N1yBFYyNZok1>-DKSd?|Bu*SA5L3#fp(c~(+MJ`)Pl
zSXlNyO49MgqR#_c+0AoZk4l59HBZvr7=bbsZV&V4@)8{#AH>E>Hw!kg_DiuPwTzSV
zlU$zo4)QC2o$^4b#_@JUXsU~M7G}8o>-UgPqbUjt|Cs=Q_KPtIe7&;Fgs$`LYOVjb
Z_78p7$%OXBiSPgb002ovPDHLkV1kq945a`7
new file mode 100644
index 0000000000000000000000000000000000000000..7f1731df9a0b78e661e21c0597ff862071222b9b
GIT binary patch
literal 803
zc$@(v1Kj+HP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;wH)0002_L%V+f000SaNLh0L01FZT01FZU(%pXi00007bV*G`2iyn*
z5h4tw+G#ET00N^)L_t(o!|j$&NRwe4$3Ks3t(cS1B!oIx*f2s6cI>YmDu_Vx60vjB
zbC+)7v4h>Un}h@z1d{?G>*^ux(m?|?NQc>MZTkM%eD`$N<Lll{=ljZwLHLCqdwJgN
z`TYJo@AsXMQgRpxA@D<i>di(D_;N~p9yaMc3z1SHgs|a>RFZgCE0NL~=sJb<Ef(fh
z`TXgtoy5*>d`n<dZPqt7Ol)l$3V%R1D`A+R7s=)Wyh(op;IWShG*MM~Y;79ywQv)3
zgP65Jq9csovJ;4RwL0Ot30n2FK|Er5+FZgZ34>CdwS5mEpk{7>QQV^gm57LKFYspI
zJ#ZE1l<-J^+_wX0nzQ=aD0zaP1SS+5;306U;Rp)rnmzBj5h!@ka$WfpaHnediGU9c
z6Il4N>Ns@v2&yWd&mIU51Mh%qyGslRc<$~oynm5c>6d~R9q_CUlM7&4v;%`cFA!C?
zb3sTa;X)9u)WAo)8Bs@=c(XyI$+Fu%pM}{Bm=@i@$3!X_b(mEqk9;{p%kQn7eak?<
zfETWv(1jJZ19N?2!%>G>6?8~1!ir{>or9;R;hF1qfg5ih6=E=vN=9w7GV0*~-_M+2
z>SwXjwGjy+a1%hU!>smzb16jZY#DVvyg8u@MQyX%)FHjJ3l|kQE!K`%MLoTaT}#sx
zd>K}@obZU{$*d03fm|W836o0=;mWLXz9$fXba{LRerOFVS7!Cr*AYkvmEc@(V{;dN
zIRs&=&a7rL<bWaH5|9uC#)HrUU;&G5A=(1lL`rpLl`}1RQn2j$ACU|AE8u}zGBPlb
zh8wk3tlB>01%6=V5+)=_6}p7G9EBtVB)qPIYZ7jARFZI0LRrBL3HLZ^N$8i5mvEhb
hB?;#_*0KI~{RQ@;iH5@x4O0LB002ovPDHLkV1f(iTiyTw
new file mode 100644
index 0000000000000000000000000000000000000000..7d7e2e3ad2b797f3077b65989dcd8ccfb4dcbed8
GIT binary patch
literal 2608
zc$@(+3eWY4P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;wH)0002_L%V+f000SaNLh0L01FZT01FZU(%pXi00007bV*G`2iyn*
z5hMl^RVTIp012>3L_t(o!=0C1Y+ToI$A5Fbc9+XtE_X$mq$GYXrP!oonU<VZt_!;f
zP&jqs!cNe-GU~ikZQ6$dZJ$Lx^(jDs<V8jk+iB_)XzdoUS~!3ssdXzSwMkKyWRVm_
zQX;whT<&t0`+e`7KJcStWZ6j$aB$DPm~-ZTXU@!jMpTtwXAEuNki!xmv<`Q;S*pLz
zIijkF2mt3lLvS&rLA^pkCWywX1S4Pt1XF;T;%|bx1{JT1f}CW1=n={NN&t4051u_k
z-@pMPwPh%k7=H0zBm6rp?O7UHAQ%EO1WphFj$ny`EBGa-6qHI;@Y70VQpocqR)(IG
zwa*3c>b3=5_`$bHEMJ8D29zoc5BzUu`yHCvA=Cij7NN0Oi8<t>NUjboIiLc88bnG;
zV}2DjmW1^*<W`mHtte@Ig_+@m)IJly;Mp?__GTcr!SG+dZ|QeQ4pxab33c5{OEa4X
zk=qC1dY9LI&-OdaH9sarL{thIFy_64bt7DloScNd`J6T_P7A3O$lrjC-0w3peEfd5
z>;m}1@BSr`<&PNptM?uI@8~-P@q<d^!_Wz%y?*q<W7X#ZSC?DtnK|EB%lXD;MWw2M
zBWl)*hFc6j(NU@$b}m-?&B@b?aB5<f@azmMk1M(5=a?RTT(WxsSUZa?pO@h~^qhit
zCp0C=Cz1CatA2GNf2X(pM-w&sUalhff=UgouZcPy2v9YADO$6JyKvpIr#hZ>#*aPu
zVSn&@*PiX<>;D;$gElbdzC+j0jE)a=N$EZS6pIWW{jlrgJc&aPPiiiSy!BM+PgieV
zaYCc>6>F*Jg-fQ_x*71|CBu)F4L{(b_-fQF-`EV+tV}3vE`<wzrnnR~)2IKYnvQ?}
zdtYu{f5r5q-S-vVe}gXIllxqdx~2_1Z*$}b#7^Nq3~xVK{MO9$WjpZmMb}*Q+`}7o
ztz*MksbBr0$9oDpp}Tjy`O|Tu(nD*_zSmf@ry80}FZPsEIrh+ZHor#oFD~5D#Esj+
z>eYVk4!tPz0LJd_|Dg3CgnEQF_^7Y^;?(;8IL=7QHCOyvZzfO~SbF^QqqBvRy@dyb
z)Jwl})c<DZ(S=aDXFgEvPp`So`jv`vqxffa7t#MZmJ|-fz=_|W>0DW57eH!UBgqQU
zIMgS|9Q51XJv!MQyt?3;%f8!@3sjCQ|K79R%cF|`biOL`+Ih&F2i=~T^YGev=mdEA
zSWh;v+`3@blG#<?%>EqbM(vsLn#E-MVWp`X!tyR{|9=NQAkhrLR!E??4p+Vs9J}qB
zb7e1D4AeTaC!XqBxv&Tok4J$^gJ;jg_9m<RY9TgxHTBBK<(to+ho{fN*vo^-{2S9V
z>9Uy(F37^l`eV+Ghc1mgage^*yUL1OB?c@Q0M0D+HpoNJh<xzK-H1Jt_l-@{Ybyli
z0!tsvL&c*Lxb(sgz8xFv%@A4n2vSp!nkJIJ$Kb&tFFcow0he|x@yFd=E0)`q-&CVK
z?pky1z_j7WTA~5M?NE0vt(GxV!gxpsMj;HV4enrhb-^>%O1@RK+yjM|PA4mWvPD?u
z2G5>}C6+HjZYxt#sz7=BSt^t8)*0*#$AEJ?_ri1!Y>MAlPWwjI9kA}9OYsIF920CN
z2^-8&SFc!M2tcOZ>#){xY7`7VS~dM>Nkn$Y>iNEb1N)ViDp1_JF4GsO06f1N=WCi5
zKUyuRl)YAS9a(D#Z*vNZ)ETmY?Fgo=*iZ`iF)37)su1vv0(&VowwtWVl~1w2){KY?
z5Zl>w=47%U8t_~dFNYM-T*y%@Q!yluW8h<mqJ|*g8<_YApyI2~{$in6-2eB#IBV_$
z0@P4Y^$;IC(*Q#R)CWU@)I3lZJg{q0R>uTG#Wgf2)}B+c`PJgCzwdLww(_dCCA*uP
zE>BocGX#tf>OipSg6D%u0N0?IN(ub3QbnRgbJ>ptMT06u+jlC#Jple~axAs)((Srn
z&!11Ew`6zT-DWH58wJ}Iwd;yr1c~QMLZu2m3ChNBn^ZDT%|jUydGn^*)@1lG!zehu
znW@_YV0h&6&1^dF?Dzj3<>?ZPE|LX?cfNUb#fWcY0}Z0}=Ct2}HfQos+*DlcpkM&3
zhbfkYN<qUJV__iOYr1W9;s;!FIsC@t^Z|ggFbh2W);qVeBU4rK8~e?EeFZK|lC5|=
zy)DZRuS^DO_EI=xl!AvWui5_ZY7*MkGs@-)l!uQ>d5a5<lg%sc5@eu%COTF-+G2SJ
zJTn!phEj<)-y1i!L5u+>My3j{|7gt1zB&r8j>7BL$bK-->lKd^+cI0g4i#EGYd#V+
z{QBf(tw%PWxw$5RwG!0Uo5=5`V*N5JvsY+sgtcyZ=k518kDNTQaAe&#Hqv^hTIvgS
z0eALT;+xy^f#bE=PYzY=Pa5mY&G5sv+ZFi7@=2usC-chM3Y7URQoCd{Y>2LZf%FE{
zrj!&s^>O5%%cqaoZZcx!qE+Ws;_v5vmi&jSQ_;_>a^Ji(VSWGZSVzUV)fBLnqP?bj
zxaV5w2_yad*fO!Xb;wQDu`zUft0>t=>VG?=17C!AztVMp8^_&KKW-m?GIa6dnss}_
z3*;@gW7Be5b9TNy_i}$vX7An~j!s2t@oIx>Ek#^wE>dUa!rhkFesaEaI`GyLR+Xne
z`cRpi5VCWB!1bY{Qn?Sn(1=Fc-{DBF5_uGQB8&~V{TI5He>e30Xw|-*_Ki%*uPd8g
zyliNsiaMUCp(<6&Hww0IWCD(n3q=h-`~}<XOny@SqVtne9y~KPs&ac4vezGBYUmrX
zvRe`Tq6yFaSX+*a(9sU{j|d$x?j+HF`R(${jNEB*CT3l8F{ehps!~(%6+}?61*2ZH
z{-EhKJ?z$cgKw7~H&S1@<?`6X$I8rtkR54eVfb4zyRRz#G(VnuTU&dtarn@7N#0KJ
zFmk<{z`G|Z&o~oa(pp%z&CI4!R)vs(-6Vd4b=PgNuGD(Xh2NM%ADv#41NUyj{1OyD
zZXz}G=lhjE5CFir%i5T@Ovh1(Hg55EQ?pi@V7>`SCD7$KWa_~)prHWGS)?_M9$MWX
zx;7`QtSB3ELUE>#d&4iu@~1W?pV@$}sKr0g*}YD@MG1ukJFY}y5Dr7o5o`fm#VZKq
z4Jc$FpI6H3LiMJ>247=(=(v<0*qZ%Po$$B@^%AX#B^p|VP`zR~+l+=HDyR!uP`p*4
zoC=fYH%Sejmd(#?PJh*Q`rI`Qaff<VsiQ~$MF~)oI3+qM=rIbzVfm$d{{I8QIq;zW
SU00g`0000<MNUMnLSTY7U=K3@
new file mode 100644
index 0000000000000000000000000000000000000000..40b19cb63b244d6e71de31875904fb934d0498a2
GIT binary patch
literal 15258
zc$}4cRZ!gD5ASzbWbs9cI}~>>x=3*=P@paD#fv+OyE_ys#ogWAt+*B`6ff@F-~Ybf
zhnty`%;Y7R<eZ#*W|D9<6<JI)5;On+Fy-Z>)&G<5{~ZYOf4oo3Xbb?T0C{N%P5197
z9bfCshFmCaPD-67$u~r9k6LEdEuFzsa&g;0SfJ$RpFeeKX@cqb(&bI(Qu0~HVzS<_
z$)?!I{u@m=W*l)$>yKxZ?NdnEU5X&rz<(P6FySIfz!9eb&+LsOfv(4mtVzv=%ly*G
z5~oMLR#HoV&F!q=wCy&lM&-ob&ug*rH<V{5d#!_J;}l^nu}S+Bw8ft41vHQCQ2?io
zEhz9d-T#+r%T+JzVC>HjCwvo$6B!1I1Nbx2UXQ!FO}Z{6o?c$xMRoa{qrGs71>UE7
zoX;ZJWZ$V)KRKgNwodmh#`vQ5biO;-@(p^ON<47I-rCNu+Jd0#>WM_0hFier(7UfN
z)U*W!ADgPZJ&~Tzo<tmWi@rfowf<~iUUxeQKCMRTc<+CkHYG(-QHi**ESj0H;uGcl
zg|9F!V_aN_$2aDoBpKuHLW%LdcH=m3`&!2#cJ}2n<4*m;-<t;LzfoG3sHaRw^fP+%
zxfIH`&8i@syPmQzzZ3bbqCeHIYq9ylD-s<lxgQOEqNc0#5bj93N5O)3`!PoMd*aev
z&&*g9_fysF9;nZAxbEj=-G5_&IZ?v{qPS<!d6%!id0T$Bg*eFOnGXJn+ieEqAWWD1
zdOcG9yU7o<H}nE5aBiw3SRt3#D`dByRnFGX&9!vd!_H21zrO}0WP6v$K*+(+!*f?n
z+Soo{o(Gp#oszT^C&};!APo?WS5wNYEq>CdQU8#^Ts$!urW4dVP(vudG2-StRl4h+
z>h?U+JGR|y`F<?%erYDOCW68=PNJ@w(6jC6@8E?68ZeHbhPDkD@rM7cFbXnBttlhG
zC@G=zfH|Fj6(~GaiI8GXGfT;{iK+xFWWZ6ekSI*N!4QNfek2kcsxTNLqd9!yOo_`8
z)6$$S9cw44uY!H?3pwA);V#POlP7TI$%p#JH=f^F;!pK9(XP?^vhLCk{70%(?b-c!
zmaemc%`G^JmxCY(=*S4Uo2Q4XA5OgiPSAJ%U|7dYx8*+7;D1S$pED8q?jzEM>tpQh
zxlP+vBpY**gPy-W2fCS(A)>^!ln#=igF=wOYAfE|gDZTQuMK=!b<ueZ9Tnz`$h<@u
z{<@%5pXig$UYRc=Wk>hNqn<Z2$<a^wUsg#Zgt{8nt;OeaE2hePk75rsF1$4w@~lxc
zg%B$sxx$eIr@8>N`yKe#fb=spqE7e5y=zhvrB@CG`Sb45-7kii)2|dQeg@>X6DVm!
z1Vkn1h=`Wf11rqD+J6!vh|5I_>gwFfyps&!=0r`fX+Q_uA2rk3ZK-E?CLM-y3o0?T
zaebrp<sCbl*&O=VHKqPW+THK^L>t?qQ^HLDmyUk~KGZqx&L(CL9%?VpG{>FZQ=o+w
z)E&?hE?sYdC`C(5AF$)pvAbkY9Ig7&-$s$`eoP*kxqa>pA2IUJKva00m>y+R<H;pb
z%ZO)|N#IgPqH6(3m-6C+OAs_Crwtjc?@gVtsiVr`5Fm(9B!oOeIglI;lq(4Fk1TjR
z7E!RXD&(YdaDIYppCF+|F>-?P)0fPr_)Zm-$kW3!C23hd7LgVo`kx(Pq?ub=C-y<>
zp8z#PE!eO4xJ)$TslHn?$8Clir77<}Z8553o_A_t=^y+(sbKGe1_mYlCG$Fz@^e7n
z3gdU9SS?I3c1LH0Gm#^Vr7p{tUhEkSm|$fWezvqW5-=)AblfxsQU;DuF+EfPjAm(A
z%EUDT6%-*fdiD)QA7h%-MT=!;UwGATYJ0R;ZNKqTE&;#RXUDedSO*&}04VNl#zDde
zfD+;aZjTRn)V`CNwd{V$#$Ed3?dda1thfmOWA_Ho=OQU5gDUekq>Kmi%1MU9$XPv_
zj)x%o?`&0@J*NbeRv?v=$~c7H4Zc1J;QZ$mXV|cQU_6sd0uR3znsksFFd=7HPtCai
zEk+4p3j%Ip6vtzD9bU6Z*elEgeYmpQ-M^kz*}BmCwhv~$Dshy*sM2;Ly<3qr;2r1b
z7`SLefagibL9aE)pyayWiL4TY&QmE@nqKX_cjIRQL-(bANm0?jBGls}`~^{j!etoD
z`rk=0u_sl4;yPr1FIM<7wN2<o=Gwvz8vFDDqk1u+tZ|6Mi-uFdW?>bbGG#^7NSwNO
zMD}P(yhv8mc{1H=Vg05WhMUfC^hd|<ZDg_8T}00lCzE%vG9pj0p>yc3nJQwx42B<v
z-zso+B3<x<;JGeQ=C&AFcQ{d%`n|3`hdZ<;vcCVseb25QW6xrt@>B^?YHE2)y5Ov&
znHb_{CE7U~6Fv>2Nz7)LN?qO!jTm5KX!*KGKsCVS+SQRpRlCRsJD)ecvcFN}9)f{a
zYX-FpcB~>fx#+k=X*kJ1@rbU`a#4$K|1cmNXH7XAdRM<*>^;9qjVFpr9;N#FZYrH8
zU)#LNnt?p9Mc{0D0-RJ#5>DG$mX*pTOjhHV`#gTPJCtH~Jh54pVV?aE)Z$RnVr?$&
zi37TB*B?0hfOQV5GM=inbwg{ja*2)}w}jDNB~w^!`aTQ>lc2_cFHHkAwzI2&3g(<c
z)tup~<}#B}1t(<I<c94`T;j}JnzX!9TirqZ?ox)v(#E&C5!xza*p-!H=l7Z%PfaFq
zT|z<|%2kzvYD(^Pdu&Jm9_$*TZJ;;wtMAbvPvBn%Lk#)TkofsVI*OYzk%DaqB2(1V
zL~_kdg%0fpew=;`_6*MjtBQ-{Jy%Ssrp@C|9v}$Okr@g_QkOi!Pep4BWJ5eJnH>P}
zjUm;xan3awpkzF9^2M5^-jgIz3b$=Y>0EGzjyE63ck!>80W79&LsfECZ^t~iU)C??
z>%@iEggh&K-0?~DjW!TH#(>-g$)yiV9Yw)B``Dp>|D1N!*}rZW+-<eV<m>GO!HJ@W
zc_Vpwgt+qOE$AXdbM*Mn(Dqhei5Zis)YQ4H(TPwX&8Dh<adj!Of<$4T^{m^Jg~yr{
zkQF$g%Q?C>%y5_~SOJ;Gq#!GQo_0J|emq*?msD?$e7L!EacEHZKY*iCX>-#`)WOEm
zd$$Th-19}X@e9sMq1Fa|M>`)dO>&)1jJSDfxVUi4zH+-&CF<yWlem+Qu)nB&Oi8#T
zN*~XXn`3QrL)20K(~L0g%_!T!irHaQEk=P8Uky0(4#aw$%DR<w#+YOH#y0lt*EdXx
ztqiVgXj0EeJl!;bhWGs&L#MO>U;Qly2d>F7MWewQxc@~?j}{@C3Py)2r5v8BpAt%#
ziuI&8gD);{6CJ!MNBP2-P^HjLta(lVz&Uve9X4;pqw2~U@DiP{p9lY$;GI>xkE#(e
zdJXFL)RsV_!Vik>lrdLYLUaLihy&Q)jG1+#sOE7xW2KT-r+oS8xgLr-`k^!W7(Fng
zBljbFiw;~dgt2>zE090d>UKG;rxnmfhEu(zLd++(ZukCZawZMG{|D?S`#*v~O#TP)
zM!Y1vt~b5@uX@Fn#t#P;FC$h^rw3E-Rj%_t2ry3i3o=TvMG1S$i?*(#b?oQM`}OF)
zQ~@3(Y(+An)HvJ&i>RvaivQIKK~5YPFzh|%hSSde=5!5Ei{8+4K>5=<Ix>L4-*i^K
z!L-PuZ@s+B|7Ec^_#&&9S`9e_12Tkm(~kx%_nIC+LiOi`cUEWTXL4dqA`(@ChRng=
zC1dcgG4iwsFLqhl{62EWs*)Sr6?|W{IvRogwRJ|ZrvN0w<Hyimd$!*WPoBn#ykyJz
z-u7X~o+@w$kI+-c!JtrnFOt+R@3y06RCpg+20Q;jui*-mv9tTa1rOwc?^oA9Z~zOY
zvu!qd@IOC1l%@6QXTl<>BjDKl!{F{lOv~B+5b_8D|BqJjinAMMXi%b<eq~lkXv$ly
z6}0E5Z>Id+a(Y`!x^V4ON3wUn0N}f~*_0oivzgz4fAXseoh@q@BM=32AZ}e@mW10a
zu62*X<6cRLRGR*Qt9U<XY<p37Ud3;EJlzdf3ThBl;)GZS1+ztKYjd;O?HN{AV3?HT
z;ir+tr&*#^f28pu7a2tfWUnxATBaL!q_Rk5fTa_!NGu^icAsTX(byX`o9^#JjWgGe
zjd7d00G840VFc$!jZy+=%y>u|8SX(*R4O5lO%aL3<n6y%mJX5b(W%2zr<^ZdD2yKa
zk3=~Sl>Vn@OJ1E~q8o!75HBVqr9UK;VjY-yd!Z`rm+_nT-T&hCI(TJi5kqK9mZPVU
zTxIS9Acz4;hyzh&tMAzDOf4C7wa7|ebgegkjCb;)Y)8d^;)J%SWF3aK$Hu|q5UGc~
z6+tvcLl|lv6r)Z^%Xd8#QV8!Cs@n^nqaB6)sgC&yItap`a*_!=`g)_)GxL@*L62_1
zmdHW*p&5dX)fBrTk1P=E=dHD5VhTN^uu!|yg^gx4d=t~4YBzh>rrUeNpTf7(zaLef
z9!wZyT(9TIqT!sM38yj2UHKNgNKhESYXZcQXw2RX0Cee>y|@XhEsJ9O$Fh=EuuOvW
z6;EOr2Yy#z?Z~Wa9=>}-V38pT8ahM*5myrq>jon#3}7Mn2i-S2twpcF@w>eJkzPv*
z@H6#-Ymk2**uddL*kYVPqL&TS<YW&;9t`e7cl(4?t`!K^)a~>g>vHx@V@Od?{TBbG
z#2@GG1{L+bcj2C`I6d|FT}#DIbZ|_)k(5ufLgS3OXfol@lkL_j|5lJpJ3=IxHcDq<
zbi*kDqow-=hOG>XF2c&oXFG;+738`CF^*Y^msZsfy^7U^fy6K82Wt(F&)n6k`|MjS
zNJBb<w(e3h$D&E*(zt?L27T^QTTh-Lm)7rQll~>!*VlB+drIzeyvQE<)+~D(5iOtj
zk&HiQYW#w)@gs-1U~eAVZXbG<iPgMrRr#KInQx}DAVE1dpa6)pL;apTVG5rUAC)Wv
zjgya+S`LorZ~B#b_OqtAiOoQiYwy8cl%4s*188bH*utZEQZ`9zpE<7=`s3lX;n*-;
z0<y!e)*)ahfx%qGrlfBahZz-_*Q<<^&c4r!qOT`EqsWJ)6p}`fQv4nvR%A&U8sjY;
zg7SJ)b1CIW6O9`E=V)Qo7TnEXLHT1qTf=msL;Ui$8|7V%rzJw>zYuAvs0)F|)@sDm
zUo(cg5!7;quF}T7O1U`d?;J-zwsP9}LxvmvCYb%PPTD_Mst!X+c%^2(?Q`WwRNX5G
z7;d|bF@%N`1aYz(Lm{Rd+mrt5f0EdqPZ~u|MTnuEs5@6y$jCdxN?~f;=0%cZ?=(ZV
zmvf@upU(`wu*Y`1Ht9EQ*pUK%R78fqHT_#Z^F8l0SQ7pEV`(M>Mhkqd8I(~aywb)P
zG+g>F5@#K)%X0`aGGB5ok(n*SKWn=>8RQUVVSb~BY?M$+`TN9a2)%3_mkJOu122NW
z9<Vqt%z;u{r4@^`8|;sXweAC!UplbT)tTbbWgz>Gm50Cc@_3k*5p_83<r`11=X}}m
zUS=m{uMyZv6~7&Fc2QQHI2C(}-S}qd&Z@#|1u|+@IVg;3sAPZozHKF>%|k1jo~q67
zX)hi0uMm~2K(Q4t+hvRTQE;9VO^z>iPQ1o}8i&g-rHvrv4rc@`a+-d6U?&y-_cGkF
z=NXsreE8vvRVSZOeI1D8dV9@d<{Nt{GPy9M{C8wYsYqU6Vy(9ve1rmDuVi0)ju3iC
zk-M><=U-D*>?*+%qJH;a>`5_|>1m9pc~AvW8F{eoeHJg{5BE8Pv)Cbl65YhRf3+@}
zvn?74#HrfqUyZ`4AV&fR$dn(N(KK+x;6d1ss+Rqvk46C!gwz1Ff}4g5)7vq8<zFBu
ze6;WfRbskGS9W0fH$!IlLezaa<kATTf9iRk=@x5Bx&77U?-?d|%fRn+%4snFOvKgU
zb!tLc?usYc9J4qW!CEic*Dl7XWR?4ETjB*9c*)t011ywI97XLT<d*#3zs!Ds%ZRTa
z@F1u#)X?qFonYESugDq4xD(p@AbP8b_>;Y9i)n6v%rw)#l5;nC6)CK;geZ;};`Ehg
z=qjv#H!j>EmaJ3)`8qJ}(NFhnmf=g{>p{w=EzE)d@e8LeSy^*ZBi{PkDpBvvVVm#i
zDp@rl{jN4NH#8r1K6Py5{oO$}?|#`FgKK8?q#!Av4s2lnX15ixBY+*|0{?6G#;YA%
z)<c3{f@#@X45%m}66xJ|F@}X35ETA6VHh@N7_lKV6t3)cW&Ao<m3s_EO-pK|GyJA#
zvPe|z$K3yC50OU$=g+>R?x(b8d3Ba9KHiJ-cbcU20!ae>01w(y!u3!r*~%rJ6ebUi
z+fQ~7V6FG@YEC=Jey+~fQ!~#LT;OkqY`P*+UsE|d`a8po0`mQ>6vlK-U3r$6@JSIj
zCkrm`IZ<!E6QNfeYsGzr`GIwf|3`=4SjTnU$f2_zYt0at#>Wd-8fk6osbK)tX@$h_
zppQ_-lkdE3__D0;UW(3^3wW!>@9s>RSN@ta<9@v6xi6Y`4ubd}I3U#v_C4J@6diSY
z)?ueSMSv{<HK~~<1rGQ+T57))2O5&2BXX_-#Ezd@=*gp)AzR>pc37nYVRq#C4x*->
z(w^U{jdP83i7E4#0hu-u2!|TV`DrF;;ttg|BiJM##H;$u8QLK)<hxw~>h4jIk^kjx
zy1AhzF1W&oC)9$#|2Vk&44aDXWGn9s17W-}V_tDPMI8|`GRK#WQeWWjvV3y?7BE2?
zcI3VGLUTY`?M(?i)koS=izY>rImg%i+KQ$Lqi#1b1ywtex&r=fU9;W2S~2PIzz0AY
z$H<pI=uiA@9hu+$xvr<8kdGd4cYxxT*!xdp`u7z!Wi}<rRMI!^zIfv4c;@`2-a{Yl
z+^h>*0j8+ETPK5i;pyfoh-_cy1sXF$Re=388kJXht~Km8zy(2GTq#C|Yo%k+@hent
z!ciy|<97q(Z~uYCi^x$BP=uJ^^NqyZA~Q+T7~@mHkiP0lu76w&^H}s^H!Ydw{)<TP
zl~C&+RRN+qJ9U1(j+#^>6NV}i=20Sj4=(J1qKmefeT<Z@YK4D?TVgJ<wnY^=RxTPH
znMaX5I<NnTy}kBatg&^c#Hif+Adh#}4Z%uVGy%JJ1)pyt6k(tT^q#oiIy|Zu%p6)P
zVWX&JaPiY{iAWnpbr`US;+>Loe(mV2)PhN2hbM(>w0W6d`BPE#Gv(tzKf7MBe;}S{
zvnSk3C8sM4j@u0Z1(62tR3CjzIa|%5bd}swZJsdRdOeDW+}1;K^2i`(viuC;uV)}_
z;>=5vI`E{3EKbq=du*tQu!M!=$P)vc>8_^c9`9;sQ^2W~^re8_Mw+$G29=m+JnG(V
z&Cy+H_=5S4QQlX3{P$zknBk-&Y&_ku&wW+s>$^g`OF5aD<sT}?bFF9$S+op=u~fcn
zxTTBpLBX8I{Ys4|9=g__*oT=9)(4O`zMcD~imi=dLjC11yenOh-uU@oJ|>N;^<#pE
zw7+07F6ClqjRhrAssbs0PLLvC(_s4o5#T4C%|PLPJp~CtIvF~E6Gi*o-J(03%xlYj
zBZ;)x47qvfC}MrWJDUWLGL4Adw1pTvKSC6)eEn6JV$}4txtcYEJRfB)*;=*YbCYU(
zAc44C!F#OSwcoGkNt?R&n=6bStF}3aXx0{)*o<u<6ZXtHJ<%w?C}^AeQQon*x<UE>
z{0k{WWp<()T*Rw4hqwkRl`zH{p~H0ACX>^He?i7!3Gq1p)pB_IjbZj6wb+yUw&;z^
zUJ8g)poJ-6W4dPDWP+BP6OSw0e<C}i@#J0V(>JMl-NVK3BV>Bbilq`6&y@YcygPc;
z@ZNyHcGrdug8{zw5PUm@rOjRX0Nk}^iCRq?pFnapB_y>ikU!AO6<EkPd2vFg2`wgC
zc4UJ<km&+GkQvP6yP%+TyV`_|fuiE6!(j*>8_luOCeGWEMWLB#N)C#E;6vuCLVKV~
z+}v=!N#6&?Vw)-J)FG3_WgaL>?$hLn8vE~=@-mFyOfMvn9K5=-B_;tqI`H;Q;fTxI
z&g&JEbaE<IqA(0dd70BoHqo@^=XdW4aA2+>rPW(dt#}*simZhXNdDFN`A^3t@)FhQ
z@0ZwJkt!zc8^WOPgIK?w2C5~FMCtq5+LE-q1&;NLKOnC|YhC^7a9~W4-892IUCWO*
zZ?Kaz8ol=(PtGFdz1Ts4FPqrKHU;?E#ta3ItIZF75|?&4s?S)v(u2y?^X>EDhNPUh
zRIH?y))VhPFKxsg4+KTGFGYEAAjpez@-i6-clk#}UPw^Yqmr>*{Rbuqa8}|H5sb^J
zGjL(9v{@UUp=klqrA3S+@7BsQyH$=ZRxv${?Kkv$p!`(7Rxa<GweBakBjKosOQ4Ki
zzA?k()0l?WwyjZYj51}uGabJiM$o6LnZ#RV-_9Q7<UoHGI8EPv))&OGb4TQJ@M^8D
z7@n3;7Bb%+Of4IM2?Go`;&(#=cRTUAyrpE_6)`wB)FiKeFj4ode~=qa+TZs#_9j#N
z+(k(EW~S?$LUSeb+tsOevBxy`tC-G*mv701w3&_Eql(AFkV-!FY2TUiveqDD++q`c
zFMH)ip0E$6tXPJ_3Uw1n$qh`kjqFGWYQ9QaEmVnMDpH-+KY5~4ZG}#J^ybu1X=x?Q
z2;=3<=izJ3Ps7SQ-D^YQ@=6jg^;iWQrI6Xo3?x7E7;%-ZdQSn{)fs~sKC5K$rAdaV
zLl!W-_mS(u`^g7gV>7C<roJIn!Ztp?pW>~Sp^t)40<BX4f#-`nCHi#?JQ&8$nCDIK
zqpo6+VVVCWD@<yAF3IO?7W3M34g>1*#6e?lIA&PS52ikv3|PwSIG);GXS!<}-1i!F
zTWzt-@xn$a+AZZXNHpu)dRg?Pm;9tcxYm+F7-oZ(`MjXRWCP1Zowix-Zu~~h6c?Qk
z%-$AHjt3CHZhAA6%K9wcR)fOK6Y&w&oZnTE@lzOjiDnWfXS~Tv>2gKdA^<pf5z*vO
zl^alLsF`0nSndA-onOua-&sgZs;|k^es)-35Dk6+I9C-0+I0Pe7f|E1!;U~bNY<6P
z6nm+L)oh^5Wzr~{tYB+seSxXOAR8K~h$In|@s<^VvG7^r?@mMGvUo0;6&9Fo$F6b*
zZCF>82a1e%LLku^&J-ko38$T!?`d1XEtjH+Grp`IAaV=Uj}u7TUx~@e`r+fGw5)t+
z93)`{9(@V0##hz+I(ol<T<jNOoA8PL9GhL%6MsC{h}gefr$=~=6;F!(eK9ERQ{uFL
zcMg*c1tR+@xO+T?o5_5tzk@q1#s4b_8oD4S;nc|ZuwyhMeiEHP{s&qCOyD#~O(C2r
zVlZ4uH3x28*NT>hfT8k~RGL$IeH+hrHrgzhw7;CsB2_y2Y&Hcyaz$#lw`d65&M=<*
z_@Us}K#L8Vx}a+{x-5Y*H@^bA^O<*60f2%)fM~SH%lts0yIejS%*ln<!hAKV-;ChE
z6<KQOh`u_L!qW>YB97-)s+$Yc-YW#f&0Eps!=U@bpkZzq=-t9;@m$gxrNi$eRq!a!
ztCo*%UO>cNqCjk=X1gNd8!dJHPQ>`fowF;;HG`0%gEA`j&NMV0jw>XSdAny=qt+RX
z6+0_F5+q8z$k;ctur>+{(NrS0BH!(_cL0NKJVX9{{K-2y$a-h3XlbczLLDQ(*iz$Z
z-})vu07H@+$62KpW7#;9oF&6O2FrD8jfUig=A}2lXXW-5G~iIIFceFP3La?gp&501
z2NEz<^t6#;9NP236VxMSUZ2?Di+l%ZWPQ)l?Z@v%E?8JfUloNrw$+HBkaT;gN7ug3
zyZZhcwp$PsR+K5FfN)e!4!a(3@4rC56!>+d45o^D%Y%dW7tv5fUFv?6bPM$5oaVi?
z;wL&gk%1Ojc4nd%sg+CVWO?0JA>^d@jLBH4e|^V(H;9R;J$(>=FFC~GR4{KmCdY_<
z<wWon(*D>3ZpW5O>b^<*BnE69)~Kug`L6YaHVHTAg&B3j4!3M@h0wluG1C=f(uYPq
zi}A+3ZownrTXFp-n{d6io<oVZdN+s3!cYE$!55J$GG=PhI1KK|zgY^mNuIa`4V30<
zLF^YzU8wIhPo8+b$#>YD$S9|@@`3n?oWI&~N)WEQe?*^`gf}0vaLM$}W6?<tyom#J
zmJ9RN4d{x7?~t^cT8!(3(TpH;9UI(oZWneM9PM}L0vHH(86eMC@LF;PoPzr7=YXaS
zGcunh>spg<sCRCFuIlESw_3G+D)*D0KhV3O9erEC#;-t?-#hqzgo(kHAOY8V@-VdN
z&W(hPnA^3w5BS_U+mG#xqAmRcWj7F30`S=BUd#6V3yI@8I8`nskEc(t8h3pJ2Rhq>
zJX_m0T%ZYn^L*J6VYPZ!XQgObLB}^%_aK$>6iTdVb8Yvr>i~=2V1A)H_af3~GS(}?
zO{#2dy2kh^n-bl<bF)V4x60P(Z*K2KUAq+M$IB<U3y1;|K^9!ZnYvmfQ@F=-UpabG
zJc#pFF-gXhSwo@s;xn>5V#S>F!Q`h8k=wa0PUxuXyud-ELE!gDUWq0hmsDQ7gkPD>
zT*EbBg>nRA_=9NKzc>3<HO4+c#>XNpqa>Q`-~#f<SQ>blFKl;$L<T4K9>z%21J>R9
zq!y5y(3e{q75p9>9vBwUQ<N;^)HU*WbBdx(!Cm>)gRRejRyw7gFi0(uCi>B;*3}E-
zaB=IGQrD;stbD&EfJFKBCT|tHpEFORoJuch8s~X)bO$tT7HvqhRz+PBGQMF|M6ZNT
zJZcK1v+6`F4^Tj#P)e1~Zn7JC5q}_7Qq~D-t2N7M^JN>mPaOdO>Bs-g0{j@$9R$$t
zx@$MpA@yx&Coz&8GQ+bKJPGdd(%0^LM+Pnb%fb?Anst0A{*{i)B<gNhBG7^$$&t@r
zEaE3~oO^~+Dz5OVqyF_R+U*)<`9)*|&W--dGZOQ=fUKZp-6px|YUPHNa+R7VQV&$B
z)Bz{)5k-&8v2^@eQh_ZM+C-@FguWgQ5VGqiq*F7`;`WW$Nf3~FO|2@llt%cJZB<;6
z+T9*MZ~gaA-Ro{4;4p^)09JWby>Xu95BoX;ndSca25&^YJ3a34KdCP^bavIhsDDMu
zTyjD`VxKI-%BK6vxNgIOAd>VhpqB(iEV)r!;fQ}hZm~HyU{J3T1op3V(|h$mU-0*k
z+tk@gtttjPi4qF-R^g=`4V4UTJ4TGeL$W6S%)=izG@y3#D*}W7LK6gjEkE#C#%K0k
z61QpceO|Y#takR#i`*BP$9%~?@WL6T0V-?Ob)Qa4nX}F)2kR7*CWdA);mDaF2ee=o
z&24*>TEXE2g1`kJth}Q*2a68{1=<KeB7O*28VVC1b=9ZgS5=N|&l6Hzy^o(?8QUIJ
z=HT~J1n%a#Ugg(`KGx9bk0eec=1t3~%W%vf`8)<Ylia-d`=v`buh_xjd9v2~{c=X}
zAXrl*sP0Jty%&2;cbB7`0PYqw#r<Am?#<k~qAq$sMAa>z*H2N2B?5a;HqY5Xr@4Nk
z4~h^q0KWbB_Tm`OG6Kn5J?Y$CsFOC9=k2|_*ne42p6M!U`;t&j`V-QptkT$(ShQZ@
z$ynWzb$0yv`(s4x#YMW?6U8_-zJJQ9`OJqJ-L^VSBAfB8&!~tJ2(!N9{~;!g<=S&1
zV_E2(5|AX-hCKR(aSSZ~Zw(3kZb}&`6MqQfSKum<TyJ_L7Yzu}AJ)|7tRC_7c47Im
zfq=ar)^zF@WLU-WN69&YxU9dfS_TxAidV*SG{vS*-v1i4DIjm3lkq=j!KZM8H=F1+
z`>{F`$_s=C6qm4*!>Qfm7ss6*>1;BVEilK>K58)$mkuuq|H-}J`Yx$wvz1-)pwny8
zSzF3Hr6<<;p_8h<(Mk8SQnh_$NJF$MLFs%I*G@nhkyVwlxQpT$NsAfqM49u9vyOjV
ziLq-utM^PVI6|7&{h+1q1OKthC?j@<@#$Z<uy@-|WsPr@B+L4c=I0;P3RM^<j*lqf
z!3m1p_ylL4zWtsG_M<#&X}9%d32k>mS<kL=cXL3ZL&_Z$Lzsv<`+jQT+25XAKd0|5
zuYN%$p&vb`(thstx}iMRRkrwrU>$9iGma(cHs{Qy;yWoR+H@peqnBqlTIn!->&<6g
zhiMho5C2kqr}xP<)SEu|ey#aKMmUaorcudl{>IFoDu{8Zdx|>gO6e`+Y5xi)<-2P)
z_K}*`O|+|gqshSI^i>UaQeS@h$nrS7#N?Y<K4ocg5&p;=<YJ;>Kh<97!R?|IINz@P
z93xl%GuNqOVLJy+WnNCo*oQ?nMY!N@1pOi{*PF3a#MZ@N;IpnoM_<)nX>PY5QXC~M
z;eiM;eW&S`=pU;~kyq=_x|?tw3v938!nIQcm=3{zT^SRaK9a;I`9%-kHqoS@h6%DF
zj{aspd(5L%;)K%zi-O_KaMtGUG^ctmuP>8qpSrvjzNA#WUJt!nd=~pqpL@B%vzi%M
z#1JaQ2_{|5W?7OzPR}hbx6YIldwv&DrCF;jFH_U`-;E^P!e>+vVt8$`cz*wx2n(?o
zF(jEvd5a_%`*X!(QK|D82{^Y0YxO7a5I*R{;Z|e89fX0vTEWV`SaTnwelc&zYG7bZ
z)@gQxqR#*TTTeYLN(=L)_*V)RPQT@|T;~4%hGu2Ul;xLAi0YQzp>3lqfzB&hYa1Nd
zHXnkOD+TwkWwr|%^5ynZA~>q{(((lt*XQ!RxzxfGSUC-^eJvKY1c$AVlE(i=;+rE+
z*D-h%EB1E&C1Gc8tflI@GF!OQq8J_Ps4#zB<M7!{si1TR1Mb^+l)s|04`^~Df6f*O
zq)ho)|FqLDXkDJ1iFA2;w;Yax%o5<b^e1FPPbywmZ^$I5_YmFnym-^67%^11lluze
zEzifLL5?AK!|Co=qy|f2CpZ!F7id|0Q*2&pO<S<DD@M_pX?wC||Lt2<t^<6}lZoI@
z*RAFMGY-JfpZ}FpT$Yw2aoh@78(1}^q*x5mAO=)-nr$FBVwP4F$=yy-#rU-L1Brr1
zp_^t3i?j780a=|{*TUTdsNZ`J-+vSBVoi3uUm@6V!XWV{)s%a&E2TIZrGjj}o9}z@
z3~?i~GR&XQ(Q9#UiHYW5M%+Ao`*&N;N!T{W{n<X<TMD>K6@L{(ncESKpL;L=G!eab
zX|P?NI2rSP8pEdE@h5Sr(pFIQrJP=uX6O66{rhbp&vsbpb|?z|pH{cAy%l8Sf-rLY
z!_=OpQxIaDUtf<zY2e;vSuaY6m$wnZ9HHuMb@TV%<e`Uhj=ci|WnWx6pJWy01T;hH
zt^?avIXW(eN-s6UuSt^cS1v*T07x}>{(<(xT?6?Ft?aI(EY-lLPz6n+kJ=H_#_sFS
zcLtYR0xU@W7=sYl{A~M4XTtY@NJ3tWT~I_*K=Y-~w7Y)^HaC#`4wC$c@LqS@RZ|za
z7_HhkEp?ea_^<raO$h}-DtG%)r%)Ke_txfY>E#xNwEGgJ-#=9XqfMle?3Is$H+-Kt
z;#=7`qVCqKMA<q$tbBOK@1(PjVq>Gu9<DYXV<^`ZcpFV**bwPu!M|v~Af<dRAS@wF
zlmy!7%0vh4I0#IG1n87nO{C*X*`9=w>+LeUW$<Edh#9q68qR2$7q}fcTn+1fMQ5Ir
z=T2w}noV*T7>*e3=^K7!fHz;qpIj5W(l;~?5#BZ&F<FK{qXa?OUM-OeDZNrCR#3_9
zU?<X+72kXLg$}>0pAREqs^355kep<_7Brp?BC6nVzIGqYu9KPrz}*$fMo}H(DYUH4
zA78bpsnXZzdbFjCM+!7Z5~K^NaE%e1Uo5&L9jVw(g4YUfys)uGZ^dq|*4)1vW(^ec
zb`Y-K;W@cW(|lIuv{zd_wGw$Y#_q@-%$Gfc1OOa*YwE2|hs6FbgpOF*3kte|B00B{
zqA5o)5#3)gyO$;w$KY#?i-SHkTKfi86%B_CEs4}K!+%x=W;ikY4DDWfMqrHf8o{=Y
zlkmJ&#`1HS-o>Y8q!z5<@3Q{}*F3+ty(}jCBLWRh<(}))gQpI^&Jrs>xxpRG-VQ`s
zJP@Iwo{7v#bAa?)f2p@VkJf?Q#5T3Jt-pTH9$0ZN@@uG^pBrU=J%9L1*&GerJ#P{X
zE%+)>dL(JjMqk~-d;g4X{}oCT@7$mMJ;O+E!+_SY6p(AQk?<*ulKkkxjmz5$UKT;U
zFgYTu!g1H}{kPPDQD%z=hV3(__OI(fJ)`%mYWj*l>3*gUmJyoh>L}G%Fn9aZ;VcMu
zvk)$F+jL#n<USf4u-qq2)@je>&UpSFcj$cSKeD?%(HUQ*dEIWJjnZH58?t)#?aJYR
zEKDJS{Jz=#{YA-PAhwxdgPcZ;MTJN`Nu1Rwlf4;)*1R?;Og0W)U4Fb9YQ9Ag@;l=&
z{#zJyKV+b4hoYo=d%dC+Q)F;x{FSe-?~!(`i=}s#U?&+}(Pzfv-a25%FSXX2CiXHh
z%f@Hte#p7gcQ^XeQ|{WJKq$AQf`g5D2#4F{hPmI7aZ)0_|IhgW?c~XXvv&?xFC{WW
z#`&odUwPuBdGaWdZMMv(u^v7y&>yg1tTzDVAB9^P3yXx2fnx-U7ZR%X@ncR~{)Q-Q
zZ6n0OGp{bCJ0#THk-`mLQBK<Gx}W5^mXq9vW}yC1!G@%r!`ZzG#?EuTf%{ZEw$2Dv
z_m30jf1FU<_Ex<LCmtM{KG+?Vnec%nvd&+g<9%C&7xlWTzjbC8vHp;2;Aj7NxOXQN
zdMaMycI%E=p&ycM{IlhQG8@nv$BgF2@)o;aZ?PZgrQW*kXJ&yrW;N&K1=8^sx#r`a
z#$JvyH0NDh-K-SN%yx?wG#EBbL#=--zH?TVn>JUcAw+!hb_=?%0aj6e?+&o991#*6
zEzgTj;EN~kx(n?*DK&T1TvwPR-t$}6HE!6ZtiGHYPQZtW&aA6_Jq<eQT=RU4AQBYF
zG=J?lT&CLb{TyC@@5t^KGMI8q%+%T=PdI+@k$4w}0RIrTX-CVPtRd}WvpCE&1`w6H
zplcA=1ud1Afu~Aa9@Nph!2zzL*SyLvuGoyi^<+VGbR~oH4H&5@+*f$f_us;w@$!fl
zoASPW{l+$zRaZni|MK}qzqV6B&PhRYQa0tOcbmqTHsvJzlvH!vWmnn5qaK+mY49;4
z{-t$TxF&`Jt+a?HZe7IQUQh6PZRgwBd0*S@38~!z;);AsC%5l1tEV)Cc)*JMP0r~D
zk$2WfaC6MsF`qQP=hCXs##FW+-xz{>MT1-4OnPssfdGe!1~5`u5NDAq-r%Tt2n!3b
zr%!YVwLe~)6;TPg%|Lfc8P|d~;b$Yqz18yBBD}Xb3+4K`D|hoI%Z{(NFIz|r4?a17
z^wVInBe}=i21O+Z0`Wfg_jy=mTW)i%bTM<LiIqZJrMrmU3)W!iIJuU+r4VX$b2U!F
zEtpoR_poh$hR6h0%6~zpcZ_sMnqcO}=g?yX@J`wo7eOIvgG5-GFK)y{j$H3F35Cn-
zdi9p{G@x<&-CD9HE<8gQA@aeo0!XJh;hY<BVNP4epJU3#j!I7T+jYj8x{{fF=|5hT
zt2<|`CLWQZWQ-WNn<l?5bFio9{#H&BIJ^GGiAJ1))7f*hCVY9l8+i6`9$|HbSFuYk
z-?Da8ZXo*T__*$L`AE6c;C42==71?*Ijs?;n_2J?oMdZ8Yo~``AJ!s4TCbP$(UNEU
zdyg995H7*kAx10Gt*yVTZsor90*w1r5GL4-nnpyc4dXDfsdp;3WwLR5g9x7M!*%Mz
z?Q;p&<RWO~tt_{5s&X;=RLH`R_sc09cXPDflPfZx#n`j?d5P2P^?3~SA|K=5pHh_W
zObmcwT?PB+>eI$!$gH^MA7Rpl<>zm7vW>jeh*^4{^aY*1wlzFVS9YLajUQ)JU@wAA
z71D1JzA&itwu_b_A|%^W8^M+g$LcSQv=&Sg!P5Z>jX<e<u|%2cXw$3pf$;}RqbUtj
zExEq~B&&MCTC(}1Jerf1LESzY)btq$(P~ta@B!PwZBLZ-g>B^P)X5NL59;~td%-^R
zcePHRa4S@QlKHtjCq4Mf#(;~wBRrh;*g$aNue9-h@%t2*NJ!3H8=E+=`Su!f|0Ga-
zqmFKx(iif&_`UG3UDLAe<)*5lGGBBE;^kGJ7)~1>-7$TDB1lj%QFY7l$fVR<3IpQ-
zZw3sp1_nr8shABEzl1HrvbQA~DdC_BIGq`t*59n4nUk+{@1$5R8|T((5lmeC^M;+-
zT{L<JFoX9d_-`9iKL0Z4pu4;?Ej$R;9U*iauyDj-yJb3U)Y2dM6^|M-<&CG%g(q#F
zJw=(+gb1i8Ay=ciyne6j_@$h%XV}5T(Dn>pM35j1h8B6AECdp&*peHNQ;2el3W$sI
z@$m8L+QVVfrurOZ!{t4FoKc*==$yS)oJDy6qqOcPy3p_d9OfSC%r{f%Mh13f1YZ>1
z&`uG_WA!u9PVgleTbiXA{**~0#kG|Aqc;QsrPJ8-N6nw$lV(<keC4pG+GuChbY%W`
zrBFDa`1xPD&c!_ZXw{2eCc*xemY|2QI+?;h$)(+_(Efi@l7@k0B18QLcHg^bl2+!A
z=2ba<-me`mge9S83@|}ElAKquS#>Qb_4KUBveVKsa=vF1laf-RXEXqywZq+;<T^wL
zJ*u&!60ws2(Z`tHALuDck|Ult1A{+I9&1ZQ1X$8pY*|-Z0$S-XkPzZIIV_9OB@H<e
zEG30O{B7^}o7xU+DqLze9!LtZ6o1y%mHg0nw_Ec4KsTYp?2SNEW2;4irLTIlpBbb9
z8{#Y-v~}~=%wB%O5y1cPhCe)hu{%dhC`a_$*ZeG{s9So{nGm_zG05&1K(7AP+w|lx
zxi7O!8+#!%#4T1?NjX+E3OhC?W>|(%!t_@eQYLKrbMcWXCx==6x1i{aFk8YJWEyBM
zG~@w%c_KrE)JrKTGi~a~C9kq{Y+e6I+}NsjYTM-b)vYf0XWck+rxJ9ZC%CR9VV}Ez
zy&z9lxi**lr%+xr*Y&sq<ypym?&HIP*L(ZAb{_y<vIGR>JwOK=a~8ELqmC*{=1(3;
zqV?<DY&u9U2lCW9`iaj#4xFd;*n=l0&(@K~ZkpEP(aOq`$3pI#?sO&Y95rLf;Q<#N
zLD-;b31e8$2PT+u+d?enW5da!w$h&gf|d5hh8$++M6z}L9Iq^ujH}gkk&Tt@`mWLo
z?{Gc>$FRtVz(|iu4hsbii`<FulIk``E80xO{rUcBNQ#UyL$+aOv?y1V!G;zfI5Q4U
zvSbGNnE7X(i6!Y_#Z#iseA&R@muBl?%`?CO6~2x1=&5HoxyC9l`X@EfB1%~%kV)Oc
z{t4T@Qe2I7`=DtDwOh?}f$-p~WC9E0#IWO~yi>5C{JR*9to~<K<!w5}ZJmKE+hm3>
z<?|s6R`0EAlB{(<#zjWBGmXuonKtK<)Mf_D(<Fq8tkHCEI^i-b3_;6eT84MXY1|Nj
z@0=j+q=TUDH$6}O%37Q5{Kw)CTv@!_4eQ#DOy)vkAQ}0H^@#V8eBxMC<4$uJ;FjRj
zj-Rn1n~G5%j)opt9Xwq4Hb3iI*8JfetJU3Op8u3#xe&gvHrH~<d6|OHfM4Ac<x){o
zs#%?4UB0K#L=|{Kw7O39;VS`y2MhT;rRNk;&LLDqyf60_a-e{{m__S`4}6Da1`NF8
z6fONm^-JgvEEdgF@5jpz{4a8~F&F`~bb+l}h2e$uq-a_<Pj6V<mbO}np)ykb7zpT!
zWzW~>9DWR{2~OoD1>wdMWIT-Kh5D5(`SSIA#TE4{3mHw9toAIy`Xr;-7=3g^Rc85P
zEDr@$@pcp$+mSq=8!^lSS`0ZE!<|UskEe2gAT{&lML#{xuY{kARPG5a29y-*D8w=?
zvj+^V2Z%J7b8=TGk#IF^c(@!~e*2==*z51w-zw&0pSOfP^2$0WM>;I=W&s-XS!jjQ
ziV968DzYTBpDN-lzO891smD5NJWn7E_&s|KIhgIy@TbHEy7A?bqCw`#e{b5$oLT~K
ze-iY1aJUXJFNSsWeNeya57N4Pjo3hcLG40;nLjAH3$ge%+mJ8>!&-J~`R%9V;Dy;>
z9#!srzuvIU7?BRDx3{gIcheD3Fe{n_go&!A4x?=(C{yyE4!7l_$k&H*((JZWtwHot
zGIxQI)HJ(>h|mP($X%?)o2=cK9;O=k?Vy%kXl4Y)VRsk#*>4T&)jLgVbU&u(e{Us-
zaG64-@?-gBio}xk(4Lq4#B2VtsI8cS3#fuXMy>4B)DAbj!3_nMRle~$KH1dS$LcRu
z9hD0Kkw5C<Fs^qLukZTu8?O4tr5_HRldAOf7S6uMxc@D%@W^inZbjDNa^y74Ju`Lf
zV)FPx1UKAlAAw<Z3j#QZazTRyK3?aV9sWN35Y7Pcr+WkNf-fF$ei!SDym`IcC87A$
z+I`Un#SdAM_aR&|Wm%+S458O~Bm|^}4j*BJFGTU|t8mz`>-h!*xd$-13q|ZiHdG9p
zR@v)n-5T5x1(2BNq6Upaz@Rslh>|q(7{oGA$@U)VG`H+EEdXNcb%tyQ18B^nI8Ef3
zu7G;fY0$X~^2(=(Dsm4f!x>(f^`&9Oc@8)2-?w+C`LSDf*e`Uoh-qurjBI6TLq+D|
zdX(vR*mKg<Dz>Uw9pXIDpdd!7UvG_Q(54kNbOpT*ZR}0<P$jm<@Iy9_om|aqek_PK
zvt1>RMY>nB!zAB;Kj^LfJ8N4L12Dkf$St|5Pi)NrD8f`I^~?TeOj55K<C4s+0cs@Q
zP)YH(-l%{nP^Y8+u0uq{xc#gKd&}bG@Yc{4e7E43iGxH*mMMCN?O4Dxvc&qqUf4Z|
zw{KKZo(L6nf~s4gET4eA)02C3!!v+Rv;cJ~l$b!~kS04>{k9iU%Pn$$ny`uj-$e4|
zKzPZGwyI;$9yYg#^WMDuO$T188*<J~>}cC07H3qFdn8uT``qJ%j`_=io^riz-`@ab
zSLr+Br7I=^B9T9DXD2mkU%Yf7u|*|oy#OJHcWB*i300E8M^^puhs?3L{QQ5ssOIL*
zuj5|-1n8Tv0Tb9LtTi!_4kV3xv)5}TxyyH$&Bw`$RU8<VdSMjAqp>OAcW|)J2)P+b
z4^YQonsDSa0;EBCIC2n#6oICTh5<$Nk%bi}$>~Lj?R4HDmgkfCYlb43*&M95ES=_2
z=Xy;4SrH(q_GEE_jzrbZ^r4xA&YC;j{q7Rw7ri#%%8%bi`^*(Y6{Jpu25Eo=H1x_?
zD>f`tRSsm973E#*2jfq12b@XMbS!=8xna*TGkETs+Trp0r;+RXiYa>9#o@RLoTsmv
zsvuHD`x}aO*O~n2bUO=wHFLMQD7w&HMtu|XnGQ#RhgU!u*QT=JA#36A^Mb9OX;xMO
ze!Co<fl`k}pl^F^=g)^TA)&&D%p>SG^~tLahX1^N9k6Z1!ilTy?$Vnu6_zs(rS~w%
zpo{31M1#g}+qLB|$P1`=p15utm0KmVL+{%0w|T?2oU`YU-bC!paN46>e_jx06C4T7
zl5rjSDRv5Ju?3bo|4|FP?T0NO{_yz}cT?Qx`g>rr5LOB4l>q(f`Hok{4<-$$CPS+M
zBvSeM-&R~1hgtgQgxRfZIalBujD)~Mo!4QvrfR3dnhwSOGrpCJRIPBqs*f*b$en!v
z>b8#D3Oz2Vw2q1L5$;ly^??%Fp_I7?L9izWSGIc4*}U_PTk+<A;}8fAl2*^>=SsT$
z^3R-hnj;=J6#{91#s%=us~|e-;)MxIq!pUb<k<YWE*N;P|8$X<_EMv|1FMRSJ6(Q`
z-i-kRh9vkJ#Qy|T_;&(_7_-uPWzK5piJhqnrR><QJdAC0Zd(&-#J5UFsujPovP26i
z<6w=WwK6QG3iHs=05!;ZM!vr{Ar0srH`5{o4CZD+W$|ns(2|m$d8%EKYbTr}hRwv6
zw=_>*5?5<wrbX}TSlsBrYl%%t{~wE~|5x>j!XLqI^4KwS1pG(x?^UELB@F}q56vnw
A4FCWD
new file mode 100644
index 0000000000000000000000000000000000000000..1753139eae90fd43069b2bd7da99b852b3fd2e93
GIT binary patch
literal 2548
zc$@+B2@Cd#P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000TQNkl<ZScRpR
zdvKKH6^EbmeS6DwH(|3Il1)frfB+F22nDHW1r_naz10d-dr>O_irPBEOgn8+sZOP>
z7ONF4ZLPPqKvfKg2#ASTKoAncC6I&!ve^wG*-Mg5cE9iK9}q;qO4~E@oB8IvXU=)%
zci!)hS8o00x47ooYZtdPH)mW{T)gbbC!XMBM+ZtNPzpp400dK+EM9UyN-305n5KDF
z139bJO1!_Hf`Y=^^78YhrKP47TCA3nhN-q2M&d<*Qvf2ukb(j%A~Iy|ym?PsZB|}=
z`IYY|xLPT7VxS>PF%Sc}f#FIi)OmTO)D729om!cnmyg9}#o=(!9gXr~b@k18`S~@#
z#`?pD5fO5IKJ?O2qe78Lc=T7tk00U7^JR)?i>s@u9yzb+*@0iZa>C~an<nQ(#q{aZ
zH*1=Oa3q9?uyMmi)~xx*FKl-Eq^hmkj&yXKBHfveh)_^ih-E`%B^xR$=ah^b*;!sb
z*7e=*eb=h%`pTijmo4h=>%%k^BBxg{0J3xUu5;i_O!Kr$<>SV^UNT|?RUdqS!{Hzt
z4paH|+mFteG4tn!k)Sgio~Bu?H{|+q@0Bye+5q|;bLZv%?X|zXA)3YwQ>QL$I@Y}Q
zto`RWarWCZL78V)bh7>AZL{ah8JzBP;`8~?HJyE*>?1urwO65NY;64f>^ZaF%*)Ta
z<II%;z>?u|4KPH2nX_)1cGvHoedhU!tFD^0ef##cA~O551qu|H%A~iam-EBvbQUEg
zB_TlZ(4o}S?5A{eDbZ-;vHt%4$8MW9mrz%T{rmQ9jz%H?G#qXC%z<-a)dLF`-(><7
z6&169x6dyqDH)E_m43c*<n*p^BsuVUv&qaHgv;e38jTQ(#n|`BCwRQs^E}>c26Qn1
zfESkByYOxWOqw+5MqtzV1*yp?=W8&)vBoBTyW-b8`^+;q9CogpI1%&AnrdrnUk0M*
z_W2?JfK~VZ@Sb}@;SiH2Uws|$&bfz44KaST*Tc_h3OI5iNOn$6MO|$zRUd3;M|Cx!
zt}gcO{urMxmnl=OXZ4GJd>NR3{*eC!0Pu%JciuIvJrLxY$&;o48!lGV)~06mgvA|+
zc9Y}tF{Zqna5%!?oLo!=9<K*?mb);^lSNyb|8uf@2>`(QA1zum>zO~kxbEt!zcF>o
z)~#!RIRl4@W2&$!cjmf`jy{UoI_c^*@%enroIM9;dOGXhcrzlpZcdvq>&V5Lf0+XV
z@z00vyYKr(BEi?M`r2&ZC4gvSywu^$Y>0GP+2}83#e0erhsLQ>p`J&VJ@V*}9(-^*
zkPf(jJN_R4fYtXcxO=`PaNVS@&983^efwu4yJ`+upJKs@Mc8uk+1@sUhkmnd6_5h_
z6nN{)n*KKc059J<|G~-4?XcpPx4e4q_+%RPA7p-CnAP=nk!bJRlanuZUuv_P|Egoj
znEsQqiKln>L)q<!DC`a!HmikX1jIr&8ePgk*QT1r#IIIhdt(*d8#fa)O;UkTfo2Nh
zTgx3<HkEt8eF*?P?=D5k7Cd*s!MOm&8Gt@C>KpCjp6K7Tb9#P^V;kS5XvPdId3hLt
z0DJ%Z7ozdRb?&y-%^J`LBwKZQ;|6h{;PRXc=8TD7e(5V{ZBpaB!%B7@+4dK9z5W{Y
zp%AUxwvsw$4w9NmKZ-78yj$<}UVEuM_gHH#4d6tRDj#!Y+0G+dKITd9BWwvrNkb#6
z_%gOkoJeffE+#BkKw(A(Hj#G^dA(~d72-<)PBf{pH{Lv9*S7WhF#KU;R2d&FJ4)l%
zm$2!*t*Sc~V`EhnW>*(umoI0e&xe9pbsmp8>dqSfe*qkCQd7S*yJGj+HT#JiXhBNK
z7+&henQrAl=gih2fq-U;j7irt-hb&Oj9`%A%a>E?^`Zm8gz?c~kLU3J1aP8BO{lnL
z!iLw^eu{rb9Ws0@xg{Qk4N2u+JL*v_2gXgg=S_UU;NGZdF6~o__m?fhXm988l`9#O
zolTMmy-E$O%gR!1DXxpox@gkhq%wwGF?z=bRmV8C`6DR00%zVJ%133gzpjn$mWCyk
z0%;wnzbp`VJYt&o6A7x9E=6oMN>{94l*@%fgoIMmHk>rtYg!36c40>1SjB=>EEfX!
zo0R4qTGG<k665IRT~Iidlw1$v$9g$-JcPflt}>-So;q7^7<2#~hEe1Y;Y42_JLb(p
z_j(z#awT8!cu3YXdQ6kUUhjzu9Ed095>L)WPa8~{JBQ5t!iKoTm2z~`4)6@e;TufZ
zn8Cz)`#HRGzu#FPH(kuNksTe40)KZ~tsII(_-NKFtVKnXz4jVoy<U<vjZV|dIqGz+
z|H2g<Z&F(<F5i$(->QPNJnVTnjJRSjDGn=pKl~K4tF=@@K^(oExFdet5&!2PiUNUK
z4#r{(b2>Q?iSXg|*JFf2j9$H(v0g8B5rX~ko0?P77hVA1Z&EM#MwLy%)JQ8FhMt?t
z(9#@y*(vPWaghE%!(?ZHoEoU_dGi6f-+GAKo#`}-&@93p5t{q^wS%D$rGo}>C=y}I
zt+!$XgN%OudB$gFqls|*WOQYVBQ*y=N*{WQK$Ds=xOnJ4J5DAr4TF&*-9&m!GBO-|
zyz?lL#@eOMA&JK|O`~VsVnowW@|jEo6XEf2=(Lkgrwp^(&611^4s~{tW3y55)Klng
zH?@lwv(xWqSh|zq-X4+iAFs#Xq;|xU@+Smqk57C4og3G$_-(85q`=|&Af5GfuR8O4
z=Z0Uo6Wt0HtL+N`OdxI;{4N@y#pR;JZdXNVX|zP646@sqxO_QUS{g@}EyI<S#h~6^
z(ZU@;dOCs~MqeNKH(j}~txr8%Jlx5FLm}Ef-m)gOK<0*Cx$|Q8?h9j)-N6$*F>(R{
zsqX6flUvv6=<B2E;fGQ2IG0yfqnqZFD23R(B_z64iL-3U0r&VDC>)we{U^t1-ST3U
zr{lQ_G%JB%mo8w@tynEqn?*FuqD0e_XmZ8@(?kpt5^=*wsCYb%B9Y<AQV9i<JKBG6
zM`q>=DVj#v?YGlkS9fsa`pOXiGRO{n1}T!1HN|jVb-!uJbZgx;yKT`un>5{)o|0@!
zMbnZI-2sv$nx-R~j)<lZQ6ebBRETMUVS=HAUei>)rc$wlqNl&j?;jyDX3?O`2ljM#
z|7lfs_tS!Q%AxBgEdX|%ZaqoXiAUC%4uPQ18#XjCWBRF3Ojk;*i0C4k711<Aw9~I8
zk<T7)C<Uf@S_vf*M`0k6P>v*(6YE{)4FrCguj|+~9ZgREfd2*~QhUz%`(AAT0000<
KMNUMnLSTaRrTcFH
new file mode 100644
index 0000000000000000000000000000000000000000..532f4b4b8aa18a19aa29e550fe839c48e5d60689
GIT binary patch
literal 1730
zc$@*k20i(SP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyn*
z5(OA%gRyS_000?uMObu0Z*6U5Zgc=ca%Ew3Wn>_CX>@2HM@dakSAh-}000IZNkl<Z
zSi|j?U2Ggz8HS&8&dluW+H0?qU?*`m-niQY<)^-g_z88P!WD%C#YqFSA|wPUQ4nCD
z{9Lru#Jxiz4WL3PAfYHAglK^p5EiO7P!|!UYH1xi#)<8C?RaCyaUAd3-u2Gx%;92J
zNgTInii|2G&dq3a-kI;2@B8MQ_Xw>u@8poY!^61oCcO8lxBY^dU$iV8003JSzEBt-
zY>*ZZ0vQGs1A9Hpe(vd|&48gK!U6$k2||EWKmeo-G6X6Bh6O>uvCO3fuq+d4gD7=|
z5XCN$Hpn0-yO<4COa@ugSXzL9X&~)lP$5bnx(J|xAOgj!5?}+?k^@*KGI$*Tisg{O
z5=5w!4HE(-;H52rX`pOC6$1<4Cx3mQGq|i~%gku%=+_P<T4e}~P$>hY9ys;rb<I8Z
zsaERl2fGStwlHw~`=mxveCT_L+bMyG3UTez1yEKM*s$sIt)UCQe(Le>{<z7Dtf_6A
z8BOub4-z;P<#3ax^TZi1vZkkPW;De;-`;{DU2e73EdU4^8u#}<V(wCs-@Lbvf~O*~
zJUs5sUtU)G;HP}#?;cHd_vqNBjZYkGY2x_%zC&kA6O~chML9$t{tW0}9UkiL)@$$H
z_(W&hH;J#0++GQ$r>B|hJ;_wxDKaB{1U~X{Va(4(JYi}I^IF(*s&?ltgpyw$Iepr!
zsIG3?d+IU2`mRvK^+P!?o7T#l6w!zG0KaS-?&&etZr=R(KzDcXx4G3)JUu;4dwV<m
zC!S^U%s<FyrYNhfrZV<!QC%Ah3MCO*Bji=Jdi##hstp?t<z};wRV-f?Dqp=$t-Qku
zBZR>7(Rz&NLwi_RAOF^1SNGwyn>S%-c=3^@HwQ>2leD+D<6li(UzTgvP+1ohRUi1Y
zPzr(e5O`o@)Eyt)UQx5Qt|dR8`>YiT2UmRf3rb2Kw2$x$XgSH9dk<0@uWuXb?m4uw
zK8|*7k%6wRF1ot90IoHR9TeD=70ALk!kqwJ056a9(x~8+72Wng_+8Ox>-d?$hxGi2
zC7iM1gT9AwGKfHm`2GW|s*fKX8ywhQ8?UFcrHPlm(X_Y+hKGkqCX)*$RQ57t$H6qg
zP=E&%!0?e$pjBBQ+O)N*|Bs1QJ<)3s3KSu=3x*GdMue9U-@Pp~d+fQV<NFUB<Jiv`
z9~yXz&8RfIiSsB5kV}Ipi^`w?Q{zi06r?wC?lrHFbB7tYco&u^YHYyLpnSYBpNqXG
zakEap@LwXndmFRIo?Bdky1F`IvDo$XADF*#h1}$2{Cpmr&4I{)mBkO_DCk__;@Rxn
z$iJpuG>zFWi9*5A^DZbC%3O4~fN%Rc*#m>8r~j6Bv%9==9gMzk95*|?7@(n{frf^L
z1rwQco^(cYIRjn*O&RzWcn;p!Su*4O`Y(p157+_!+@&;*Zv$b_Huwef@ITS1UjC#E
zb~Nted<llUn_UbLi^XVeZYER{Lm&_W=5mmp!=Fl%^8;vKf;)>h+QsZxA19Q-BTkNq
ze1ZJr6j>caYXxowKlw85XfGW?u%~e!Gs#yV)eFjid!I}!28cu=G&eUBZQM!Yohw*X
z5hU+G-XSl*@g>5UqcHR;-i1Co(R|s-GJ(d;J0K-lt-zVZJO3)~=viJ6uy5-p$qfD-
zM$Z&Wdvovwo-h)Luwuhj=C>cF>SJG|L)@!<kE@PD4F$x|>!?dfekvuOaON2=ufqMx
zv#+6jw69Ul9RASj=!qmhQ;G-Qzk{j%laM-B3V!sBHzRSQD}EzSn20`~3WQjlp5lj6
z^40g;k9WQYCN30H>J=bZ#w|6CPbU6zPw1wef7wm55%{xZ;q|=&=_ybq?6|U<KP>+(
zuFIQh8jmDy-<BInVp?EXVA@~>Vdwh9uAO%$)=5c+>%wfhs6BWjfn}LA9!cPN>;l#)
zwNUd`!QYlA+;d+76#@|gRRiH0JmCkACjRdU|9hSg2{KST56D3AY;dzDTtZvE*b^eb
zFhK;tECVYHb_6QnnkQT`fQs@E>Qo0xDGVu)QlXSUDTyH^Qc0AQ7)qf8#8xl=-#;Dy
Y8{FuC0-DK(B>(^b07*qoM6N<$g1dnoYXATM
new file mode 100644
index 0000000000000000000000000000000000000000..671e3299121eb8de50d6e0564084e05904e48a87
GIT binary patch
literal 1251
zc$@*_1RVQ`P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyn*
z5&;=>=tTVh000?uMObu0Z*6U5Zgc=ca%Ew3Wn>_CX>@2HM@dakSAh-}000C&Nkl<Z
zSi{AaUx-yj9LGO1znMAbT=%SZwN_WHq;@qZ6k3=5psTU{fgXD4A%hfpUGZfFU+Q5c
zqJ-?<LTChu21X!Bgwex&$n7P;vNW-{u4}7VORfLbtM{(wP7mj-nz8HM_L>8S%Yi#H
z-}(M#KJz`wd(Z7`n%msW^)K<7zHw0<z{|kXfSYW93p>}Vx(NV;_VteguLDZ}rwphN
zv;%UWV~~XqE{4&U-mk9%M)Yds=vC0_H7EsIfB<v|ItLPfaS#C&XX`7#Ioqp4T2;0)
zlu8StL(maOn7SdU8I-K4uYkasRvo63Dg{adJ{2Gls383n1tH+-F2GrIbWH$&B3-=>
zL2{WJ7J^i8ol9U15(1J=tg<tqgS7TKNcVxsWe#L}U|&zygDtapq^%W?6VE+QK-dIx
z+I4ZqJLOZqp89I#+lAp8N??&3SC>96z*tZb*csqr2=g!#s5CZ=cbzSk#Rye29_6$8
zAx4i~@}6&Ma-gvxhkW}bB7)HhtpyQ<h{kA*7L90)5kV9zoHu*CYu;Gy#*mQUQGhj|
z5hs<)q=wbRf&U7XJkUzQ70P&$GK`ggs(7VKH48X!<k*xih7VutP(Vx7^AML9qv}1S
zGhhPni9s`pC$7~2XkY(NOKKsZLU{m>P0wu=X5`c30(LTIZzLhgrT?CcgbkFqW8^$O
zJkP$Ku0`H6|JrCCq6UcKY+A2<l|}n{y8ZxSrTKZqn}zcekq{k@Z{UeZxUTR9i_aY;
znm0<L;_D=#!DakFfG`B>KzU4j#m#I9H;bVxh`o5Gd<5v6h=kNa!UZFP%;7KY?|`6z
zxxNBi1WK6z=Q7tl&Cm9#=4!P`xd0N!k6T}DpEe11uUf~_;r+P7duZzb(@1(dodYU>
z9|L2cGMJ8IEhH@reX@-UCr`aKZ4#b%;9<@@wv6(|BF`N-OxvSi;%xQjfNBLu(o4fQ
zpoO7bA9MWBPn$aX3cV91qQF{$90UQl@Y)kPa1lf^AdaD_31(@b|IVivKEd9>@4zS7
z73lz}0%PEE;O8>5YbVDK9qPSt@@bRsuKCT#Fl$a9W2b~Xvv3(G2bd~^5x(5au^k`q
z`#|xv&c4E?S~8)U>a%=HVFY+#=rCUl?1uy(o`o;Zp}2i3Cx0pSE`PW1%0wJc*Qerm
zP2ZGBIGzdnH+03x6+XXjNq*IWC)ZNky|;9FpxD#dSJ*aL|9=aZA_+%6>b^?3{taFC
z1~&JZ&E?xh|NO0c#e0SAQ_X}mk#M3+xME9T09ZPmOjr{MZ)GMtt3&etXC~A)kgz+5
z=no>!1`)Ubf)Iiz<3TQccegMTekvi~BRsEQt%3z;+|4p!9ZO&n$#E3ejN%6c-Dp-C
zi@QlCtdD@}NO;+3wMT0?D55rs=+#E+rb#m4E&Dni1iFD)lhANl?Qe_?C5h@^vT^_b
N002ovPDHLkV1kd<G|2z}
new file mode 100644
index 0000000000000000000000000000000000000000..3fe18e6d45b2058d78520bfb6584ddfd78dee591
GIT binary patch
literal 1377
zc$@)Y1)lneP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyn*
z5(5IvyYG_#000?uMObu0Z*6U5Zgc=ca%Ew3Wn>_CX>@2HM@dakSAh-}000EMNkl<Z
zSi{AaYlu{37{`Cl`=0BpySi)Ot<80tMer82^{Lci0!c!OKD1pF3%ZFLVbD#@1qBIA
zOUwKqVQv(KhDfwQ48%$wB*bk|30*JQj@Ftvwzt_id(P>@Iqt6J&aOJ<0}sRbF!TQB
z|Gdv{{v%-+aw|)5i^~}LP`Y@_B~kYQD}e=oRp<jc8|$TL0su{I{X@WdU=Co30pftN
zfCQ*g&{g0}hpy+g7S{not2(i05J-j!L_lf42IYWCfVRP~zy<P_SzG~@Wi}{>q{KHv
zBpQfvK)Ilu$PFEtL62z^SAcCAN##U`ihw8}j09*G#ExFIfCE@X7hstvcTfO;5Pf^)
zfKJ42m|#bOi#!6;Ks$hr4wiT)lpW1p+0i{P60rmE9cW&WV$yi1NdlIJsSkrw4ijo=
z+xY>R(;4P(N{`F|+cdEgVB26hgY8&gx!{&SX(^PK!+4;gY)rH|K5KieDc$>9jOKkm
z`DI8L&kqdcQHXVyIZ!qxf!^PQ)*3?zN@=tfv{o2Op|nCPg`qWCplb4Xn(I>y)8@=v
zRasZhp-*0)(f3FHbcCNV4Nzd|{55glnxL{||66OO&7R#*S@$&PJU+e$bmI4c*8>EE
zQW&-}^tT`;;i#&qV$Zs%GiR-=d}=X-8N#5FgIiZ$xOg`ArYMdAAwnmR19BpC&)<~p
z7|8*st-oC1RY<sdZ)(lN>g3AGx@Up2;CWywrrcqUn^5j<0SN$)fEEdZlX>4d-5;38
zfX0zXh*;4ah9luu-=<!gl&o&JbIFUKJ0PEj5QKgvELtsuViN*^XCv|A2DpITyds4t
zn7bi8ED2H0zy<yf2|xcnwRB>2a$|Do^N5{+TrXgPG9dR`L@h55y`9jV?Z+zfF%v#s
zzfTwh6%$M7zR*{YgcKs-nA;|AO+K;Em0%xq{0;pId=<?{%*c&g4tl#FP>|@001^VB
zFzc1~Y2CK=`bp^ZWRJD~uyfAj8Cf(yKJH$?kJ|&h7-L4vYz+kP`+;^k+cU$1$TAIV
z2W%H?2ONh1FgZ5#c|DIGZ_WOA>JWqpA{vd26GJ{05bYMIK(Kv5`GV&Qd0$Sp9_IcJ
z(}hN0q7#EexP)TE1aV>YtLYPKH>Vb5j_`$2JX&=xNFq8o^x#Z8<a-C+ZYse5biar4
zJ!IaN^o^5n+st*HFCSX<O#5NJ^m8n%x+fAy3H;eXS7(;bM3EsRjCPc4+~;dXLBdhh
z_Pf^q^Fr&}i!(=Q^!iv>QyYa8t?3eB^SpN+IU1_DwC&hVrtJg|ew-d1iVqw)KI(}4
z4Ub_Eu!p@L5wN^^77$rJHtepUZTF{~JyH1Z>n7pQOsGv>J9h^1IhObJkXMRxEjxD6
z_177$HuD=M;gy;2femTDc}42Gu8S-H4g=@!ez)<uGhsmz4wnh%ZA>=-O~uHBS>-V9
z|ICEy3KA}}UG~{7S=$B6W&li<15P4(wr*l3{8~F4MDwJ;5`o)MSR-Y^BF1vl*9m?F
z-b46BU>S<}hKVIEm?dD9f-^26a6Zn2MH4WDggHaW9;I}P*7Ands?JcV{A!u-X8$`r
j1uO$97)<I{_6^m)Bl&HTP{LG=00000NkvXXu0mjfyxD7!
new file mode 100644
index 0000000000000000000000000000000000000000..b697dd8ec68ee5feaeef932c41f07eb13ea5661d
GIT binary patch
literal 1189
zc$@*H1X}xvP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyn*
z5&{$<bZdhE000?uMObu0Z*6U5Zgc=ca%Ew3Wn>_CX>@2HM@dakSAh-}000C4Nkl<Z
zSi|L)O>7la6vuz}+>e=g?dul_Dg{zwrACb!8(CS9Zb<6NxUgdJBeEcbBBqHOAl8*3
zhQ>fcB=Mt(E{t*Eg5XA<6c!4hXd)pbMFJu`MS(&~!<*N6*TuXBXtdhC2QECx&17bh
zIlucq_n!M7_`ipm`JlFErvOg?TY%Moo9zP=pKMZ<0GJucHSN8tfVY810H+M75X1o)
zkSypH2-{%dmE9F9a0`IZ(ybi*3R=B@QXm=#KthlV=m3m^2#B4nE`W2kUqV`yl<T7a
zDJPFWhp8Gm6@y7@stXWU(<)(_R4Gsb_!K}#pn~+O6@-ARI)JlCbOT^|l}c2G$duKv
z5Tw9WE`c@Z5YTC2MY#k)T6+o7bzm}O1**LU0&CHk8yj>Qz*tZb*cxzI2pgati0f)O
z(AQb#tl1ki-PJz+%ejFkcjmUu8=$T>gFf^nT5F6bL^N6}v=)pAq6IC2(HgCwWzhos
zue8-P1`j^Gep}}3r@OWeZzNecnCrh|oox8^&If+j-j(;)j(LCekpFqlYkqiR=bQ6V
zV7A!5xpSfS)R2}x#FGV7Qe;^&Md0HCO7bjuz6bcY|KKKU$Ijf=ssS`FZC-7pc)!!}
zQm^D*gvS62UQBk%Ap*rBxI9a`dnkPL{+4exP+YY;_tu=wg1-y@$H+RM4PgnC?!zaK
zBUaMw;?sr^pH7>E%i!aMoE&<O{HasxR}SX(RIC8Mjg(N5U`;}CG9kV?MNNYv%7S(2
zT#N;uK;bGXEYkY&IvDzJ;6N{h6}xgnl>uD8oX)fWBn6nf3=`)es)aBF=fD@C6oW2-
zDWS4Wv_9LFnHc(fH&7wKnXf>A1h@`Nm1VacY}&lgq^FciN0Nv0$G@dG8IM+8f;drV
z6b40rqJ+Yi-zDWyUmlsX5~mNt*<)k-wc*u@0Y*=vv_*_X1E%D$)A?Nlixz{rIr$Md
zcbvW2ux7<TZoFcE{6)S4MuCR%xCe#uC7QDhytJr|S}aVB!|9`t|A~D{@xpA$=d=xH
z>4eMbn;3rdDej(1U~~j7oME3ftnC=cU7D*U^K(b|VmS&^n1EBq;KEr3wV|(LAQ#WC
z6}R`^D$zf9LJ@v1Tq8bl1g>0SP+K;4?8qha^@J#w)@2T!@M5vZ;o=n@0`|=%`CoZL
zBrIF8f9VN3cI3u^XR751$0VfTPI^L_;R!bc5eI{au^<8$KoCL@feRtbr1$PNdcx0i
z$oFWTQ}CjK#R%?pdcs>2IR4I><i{>`A_&;-Li$|DunUPpmv+0T2C`XbY=i|sQ(bNK
z{|#@Br{Dd$MQinj*3xZ68fSV!5yb~<msi}({?qsqxP%@^S2l(O00000NkvXXu0mjf
D5r`Ld
new file mode 100644
index 0000000000000000000000000000000000000000..dab44a4ad261a5d3236bd449a461cfff80bc5569
GIT binary patch
literal 1010
zc$@+90}cF%P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyn*
z5)UcNvRU5%000?uMObu0Z*6U5Zgc=ca%Ew3Wn>_CX>@2HM@dakSAh-}0009`Nkl<Z
zSi|j?O>f&q5Qd-GrAW~+ZCRFLsESh{A4m>CfZTj<@A-YnZ|OaUo(nVw!-!=EjvY%%
zEQuEPV|t)m7-$g{(!qy%0Ah*dF8S>H&MZk$RqiqjcO3Ts_W*Yeko@T4A1_}5Fo}^|
z1gDAv98iVu_qcy6WVzM<>*3*Q0BNT~Z!#fy^9I{$VR}7cw~HT-@$cWm<t0oeq#<Cv
z#{$t9=1-q;aeU0odrtTFS684K4vCK*arohbMqnNz2`~q(AXY^YDGFIwDGDN>>RhDP
z1F#D*Rs*;Obbp`5WD<Wi#v}&^*u6dI_r-tvX2ZL8mg8gWWJ2OxJt@m%(&^aCvontR
zeSDIvo`kAO;vBQlXdIqB3ubQ*S}iC`5@Sf;z9oJAnq+4OvJ8v?@7Wj*+3j|*)~;6t
zE(G$^Q#`0?Hm!JHKLk(_q|-qT4&c=*XtyCrAVy48u{j)KVqC8ZR26e_f>UiZkB-3F
z+U1=cL<F@KX}96U3z*Fy1Q?C#wyKaA>p80eI8}5oAolx~k00wBdk@al5UOYhNS?#v
z$8|r{5HZ%U>nPw<`C69DW8``;pcx~m)(~Y0c@C;*o<pyP7*pGzN*s^TWhJl-;3gt4
zjS+Wt#-_EkwDUQ%+elGBnnF>a#vn1Gvl(+$)R^@Y0N7fzEnw^%S6{xcAwqIvg$QhK
zgE6%g-7e}JK~)=Nxik%z0%VKU0!^U2zQ$f$Agb6KOH`pKpwWP>EpQI~{+-6jiPc+M
z_R1F2`*O;Is=}&LP9^{}W5jxo#)$O$&~BqyhBTX)B#~4Eza$Zt0%%dxCwY#F(45Z!
zn9pXEA&^xSiT9{#op40~A&{gg7(=$igyjm{Y^9AxEp-Sqy+>kXT9){#VskzxiLq8<
zcb6CfW;SC~RXkXdi2ofRNf41b>B^F<s%QYy5V#tR*eOe7I)x`sh$6`OIosRYoR3Cp
z0xVYWd!D1Ju(45R{UW)-;%ESw_sFMDbvZgmo+Rs+p`<ClOs7JOP*o5ka&-kj3CtF6
z&7T12^$5GWxQ7q%g8{axu+N{b2k={?QTu;8y4`<_`%{EW1T!APcwB!Vh|v1{`Ns>q
g|1-J=_}>Hk1pvvDW}m?j=>Px#07*qoM6N<$f@s&a<^TWy
new file mode 100644
index 0000000000000000000000000000000000000000..8df8201ec9748822200f737fc52eb925382b0809
GIT binary patch
literal 1075
zc$@(<1kC%1P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000B}Nkl<ZScSEh
z%Wfk@6o&t<DrX#=2qRlTxk1>F4XY$#51Tv%gLs5t!G=w?gLnvd05%ymjJ$&pBL##A
z$}rOxw=c2NZJ9WZ9ox98>aei8V>_M8ke;%R<hHBN`Rbhibafd-gxki>&d$fFREnok
zb7_jbfuOa9QW{z-+~$*W&OOholu9K_+!`IgU@&;QP$>M6&1M&s(y?=hMi4}V+t!p$
z&*AaoZ@vTY#hm~EKuTpusSpIgjq?n{xRXDnR0;sD1=!u)Wov6|831{uR1N?et?uUK
z-KC`Cc{ByU7~|P&Hn+b1-ulMI`x_4*e*S4bpR4%3-`LvP{+2Q0Ev3|*oWITx0PyJ1
zmtP$m{Px+>($c&6d_FfnpJw5N^Yae&_xEqD>%9P0S64Q-x3@kD0tuxQdc8h?Q9b+p
z9;B3SCVB{Pc=*@f0B#gmSpU1$__Y9R+p?6>Fbw0`07(OcUIYMCtJPAw-5zE#nYlQj
zg`JgX2F89E0QkON_kF*~Iggz;GJ@90Sm-kX2!i0$b=_mm`BbX)#P`uhCt?~D6@iUY
zs~pF63<J}_^+eqXAf1q@84Uoy%a^aru+CA5CV-L@A(4)15CNE`X-TQ30T2dE8sO4L
z1W+!Qik(geLI^0WqZ~~FB?&MkLI5~9IXP}No2Q1sV$u%GX5qdzB|-q`cDv1LwOZ$b
zCmQH_o5=tX^@~Nv<%~_K|FQ++1^NFoFrxtgFip!c7@L|9wjdG~Az`Kq0Kl?LQ%X7d
za~wy98A!Sd#%`tnip8SS@ApR!9g5l@x+c=29=<n##uX6)K&@6Uw_2?WgBg)fCKY?R
zFC<{&m{S0!r~fqS^}5H|Y$qfuKnf{l0kqcba;a3A-IOjLMsK(a0Km3wn=$suY*5A+
zgb>g=Mgzw6mzoHI3#3x1=(mN1Ma(^TV8jAAj$;z0SG}^bibA0P#uyMa(8M5&_jx@!
zoB&|V0An1B3ybi5uhnX`{t!Yi07$3P^Ut6E`e!V_ix)>n{eC|R&KO57mjmYv;oA~L
zt2DqE0~Z{Eb1=q00D|EVoo*Lrt=7Q1xHx<I^r!ECeDdUL0DK}r5&(?ZzRqMaAN>5w
zvxDX3<(v#8h%}^9;Eay~2?5Rp0K)L!A=>RW{DyyCtJNB=>sD>sa*9sTtksU)X0v(R
z?RJle$S0!MH{L55==FMyhVR!lKitd>g8%?QN{Mc#Lw?O`SE`j0$9Bq=ZMo(v(=1oY
zcEk58gTcTD&?2H?T%ha56#yc-*xTFtT}rulczAeZS*GQ>rDC;ODSDn)?)7>efHn~&
ta#*-h0ss&~yrZ>dM07?($)Cq2#(#k4+4%v4qPzeA002ovPDHLkV1jDD`{Doq
new file mode 100644
index 0000000000000000000000000000000000000000..514bd97c273a2ab2f85222a0113d5aff45297b5b
GIT binary patch
literal 1379
zc$@)a1)TbcP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000FlNkl<ZScS!w
zZA?>F7{{M;+TIIo?=3_a_I3=hFkLA)3Wx)$#$*y*%rX;$FT<d7S;pSJEFsHg%$$Q5
z;|yk-Gcz%nMCXjC)dby#Ee@Rs6c8hCb!ia_rF2S*#a`OmXJ24xu+vWM_D{~2=bU@a
zFaPH`_c;U+AyR}8f^&m$6pa=uD=mFp5Cr}I1psEV`TgS!4c(<BCF|o(fQSzbL91PR
zv8gG1w(*Q7H8nLe+L~uIq6Y!kw|DF~)oJa(ulDc1ESJj@|5E@&gp`z&Rp-u}d0=gC
z$E}r>yW<8RXoXCp(O4421;y6N%A;+qt$3xmIapXw_*z^53@;g0c6M~!vsf&@m%LI^
z4gh3!lIQuQji*oF@3eMc<LSmbJkQU6<^TX7<2cS-Utj-QAP~TomX@1URaGDIJfDh)
zP+neM+j{*v-t6wiy1Ke^K!`jpH2?r<Wo4zG_xAQmh=@Z&L!O$Nnms(P$=~_e&Z`|(
zEB5vFVns#8$8jq{07y(uPF`1ATiZJ3av>t3-EP0z(9qD?+}tc#+uO0dt!>I+FqFjw
zAOd7TadC0o$sbQnIGs-P`~5gEF@X+;0|)y1(PFXK5)%`X;s!A52FtQ5Hf-2%;`}+w
zgWEP64i68bdwd*6Tw_?bckc;~<6?$TDV3S2DJiSeDz!c`PG&3dpF{{za~!u~)5eV-
zRc+t?s*+{l^5)G@xONRBSHCxUaNoYBE6rEBT<)=EpU?M)D2kJj->X!rj2HD;dzDJ1
z$?Nm>E0ro;AP{K1)!XxdBuT-?0?a@V0MKS-XTPznYFoA0-e*W#Rs^bb6%g=wVbAW}
z;IKPD3Wq)7v}hLtqCFT2x)_Gh5`fk2aZk(Wn5!ln4&MQQw3qYpPKx66)t<iIYI%(P
z0s&wI0KOrF{QC9xM}9Jwl;%jDahULWy$Y7S6$(r964-=AG8s(?homBvQVAT-LpU6U
zew*!pBuO`Bw!4>+{=x;FAiP5<{Uj!UIWRp2gW(7j#RCO}1@PUWL#KW?cI*oPV0oU;
z)d_-`Q*%ohmd)||{TjdD4}_3x0JsDIKq;k#`KHxApKlZqV@ttYQA&jsX7i;aO_FiU
z?LL0(ddr(LE&(A#4gg6E!(?fAO=$wlYzziN#`{zLgOpOIhU2y<6B3`d58Zi76vc~A
z1ONb_6Ljz98I9j66bk4Y7}!2w8#p?5%}nj&r3<?AYPC9D!6+OakLQ;Wm+LS9SP@Zr
zVgN$Oyn=kw1(i~{Ory~RI=Z^n4?BmOqCrqf6_gNJNRq+;5JE(0c0THhC>9~&pY}n=
zp-?CkcDY;$dB)sR$w|qJqpU+olBR>9&;vviBM%3F$NvW&C51wvUzo9=U7QwufZ$0_
zPv<*sbglIJ{mxkTcwz?t079YA6s2U!>zmv)I6Sn*cH7pSn`1mHm&=*|1ONagfsnf#
zuTDTj_t^M&wQF>AGB?L~LMD^RV%p(pn+dO0?=qK^4l)d*o=IoMqO9zm+#KWKr)owq
zcQXK8_CkGsaZypj-wlS4!X?Js!EAljr*Q{BL?8gmO-q(coAUF&oQ=sSU0!4=aO(tN
zOWXkffXZdE$|6(2{epZ`EyFSjL<B*rJzzBCT!V;r=0osLa}6U!2%!XEb+$gMUaOr?
z{8LjFxlFccXxQ22935GYh~c;t;an#GU@@ms*XtK#+R{>=`<YT&{K)h@D+lJdp#T64
l089hGBtGJhxB&bc{ROWmY2tDu<75B;002ovPDHLkV1jtxe=h(4
new file mode 100755
index 0000000000000000000000000000000000000000..1b2e691c8a564d007b29d5d7af5a04098b4f56a5
GIT binary patch
literal 2552
zc$@+F2?zFxP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000TUNkl<ZScR3B
zYiu0Xb;p1A-kI4qx#W@}DN2+`N~UVbisM90WY@Cn3Xz-`N!l1qQ}=^iz)hPJbrH8f
zTeMAp_DkCUMd3c+#BFM~FdFw2Cz4}FmKEEQqBLpUSQcba7Af(q-Q~WxkJ+7>d-{Q^
zn06A^J-}ej9bnG?Kj)tFzjM@|^H$S<>0TO$13~xR59A?jV26Q81vvo($|1}~Fg*yh
z0?=N6P6)KR>vlJmvjK0T|4x<wJ|*zL?reJhz}RM!8r@8yH%lbYS*uZBSz&c{p5^k|
zY2XRqNud6J1y=7O1E1TPiGN}0)>|{1k9-8@z-=(J6;KfRU_rD(b=pX+LiC+8EFU|{
z`BUF%U8=Xf5Wt`L?~s9aB5=c?=HG5Pc>A7-U-}e!awpPg5S1&?2|x*00c){hP_9A6
zJxnHpGA_~b91BnW6DMCdeQ8<vxi*~t{}8xiJd-?m*Ms+~)NKcld;!1FKr4--HDV0f
zIAB1D0#OJNQE0JI2m(5h#2xO#fB7`u{L<g^gL?CxHXM651a6<))brAj-}p`3z9Aa<
zC9DXJQkYnbH4zqyMOF%V%Jmu+AstUL+?Qp0Uyi;+lE_-D6_h|?c!;R9$k9i>#CHpo
zj|A|{I}sQg>PgQ0{HK4##Jx1dY8g;Cu7e+obK%k@UVr7kxwf=Sy&YCMLM;M8lhvN?
z9hjWpmOVFd>(DSB5CPUgHk&1ERQcz}zQSv3ttkhluLHiN3yh=w^}vTeWM~U>3s(>W
zZY<8Vj^dT0$C$Y^>(9ei=i%#lxDdb^0G3qFx08FPuiQJh`<4fyz8sCqmk_NHV5wYT
zXt0kDA3ns@uO0i3R%mzskU+cZSh(+}ci*sYQ*V~pnHhWqp6AhuB7X4fbDS^NUi`k|
z56%gv_PuS}P5_U=#lw#KJ2xhi<fktXHX4Z1hzOz-Gqo}kLz_9cYy8H?U%UL782k-@
z`jc)DFX7Gq@{vPZYNaYmA~+&=n>I21;)|RqR-QTzzdoWUofFsx6o794NuUF<SS<eS
z;P9aj773728H>RxLA0S`Eghgw8-{ulJaYVGCEp510AKrn4|i@I9o!<TH7*xRl*?s0
zTC;lbBCi%J-+vB%4Jcjz;@{Qqc-I#N*65S9J8u2pQn^TL_6mNZL8p{QZ{NoJ-o31q
zOEhaWW=pF?)h0I$4`eHFqyjh!2o#?fNv2s?UZ&7#<0!~vGR$4R%y;4Uf%0|mM-A&5
z3kZs)QAh19H}B6E^4LlVQ5q8kn28;HYhi(_3rkG-Eyg3u8Zgre8BeE3C_ec=!q*%C
z6LUV)+i7z-U!)>JCY_?Qy2|-haP(C;ejWUC&U&$2x3)3Q$kdLzudOUXy^7#KXz_OL
z<f+9goVmRCSADVAa5drFo3n~0a5*gUo?MPWPamRfjpIXK+H)p*8$L_5Iu!-UM2xj^
znQ8c!>tMef@Ag$U0Zn6`ZEqVoTwlD3_$@$TLLX;h3tufQ^U^~8v8%#Ew>8^8TTtP>
z*F>YkkV+_YoEm+O8F1Tnn{LCfbsU|FIy8Zf0#H<apLzJtQDF3KRqs3IxIdCRTq@>?
z8ZE3+Xe+2~qdeX6d3i4Xcdtf#7O-33LWH91IRqlKH26_O+!$OK)jssB7{h81a-myk
z?I@xVMt&ShG2n0lR2RIV_47KLKGdm}QJnzmD3k~?GR)H*pHnNvM_&^@3v}+Y;J_-d
z+IBr6fl$C&i&YRo!m$t;5nRV5&-&S&=(O34nAn@R0IH$&3;n6sLDi@eg%L_C908T<
z=Y-$ld#lyIea-TaT0e6LufM6aX}jz3R|WD~u^@s4t0SoSQ9y6pWn3Vopcw=h#0?>r
zTh~fmQ|g50>Vxf8o7FI)rl2W;pYGvYv%`NCs(=0J2Ji>$x)Z=A<vQ7>(#%Ke(&;*y
zmbKl4!b-yrn+3;ZyM}%RItl?{$mo3lO~uJxxHB1s1Y!xhC{aAlYRBj7TKzB2!b5by
z0UB>!`!ks|=`bXwU`!xo99p5J2G_KLTG$EBy&hR^a5eov+=BHy_U)Mbtxf$sC$@<?
zutkJ8kYZi^dR>=PJLGJ={TI(hJp5*lz(?(yKQt}PXU4Mqr0Z++7}#YLYp$XkgtHZx
z*8n!+*mS4KP3a6<ETlBpR*PMGZoGM4B5~JPD5QXlKuT+}#$l)(ak3qL@hRb92O<R=
zvG9ovIsx3>GctJlco^Zd0tSFxi5PEmENc<Z0f8>AGd=oxsgBp*%MCz}f;d9sxnuOK
zTqC6+rZw7iNNU4`A96adk3S*&p6=@6{ci;ZNaN}!_KuH}oSP?MU>q3CB)QaVQHG~S
z0H=E%zf$yrQ!hoq&)k(sP;0bk8HfiVNd=BJpoAXar`qsz#FKxjc+i9J4uRN@U^Cz;
zp5ODnn+LWo&a>L`$!YjN%;9^Hu+j=%UxAnCZW92Z@Q2SX6=`o7;(c0?0}@){8H3h}
z%<wSVZraCJqVS6^!+rM%!CmsB$iOd7CgN`#xa|Y)nW|M`VVPbBb}NO+_4DoO8jHdo
z15E(4qgy==T&ah4cv+(N-?M3u_-c(c*MKoNO5tYvSQ**OY^}bv+^A;^coyOUgAUvr
zhx>PV?w8*`G4bH;J-gyPOAE9Y=5ZXumX2lTNRBU88k}!*{{0+$J_HE?_0bK~i>RI<
z<mH3I1ABip8)NzEGIO3s;5sM~9M{EUdQldFFhqqGPidS)0=KsZ)sv!KuhE*jN~h!F
zq8SQ8w)SOt!f$gtU!8vi4piU@tgGDH2b0>OQum&^R(w8UVC>UVJJ__i#HC26dme5g
zM#?qBlL@?d0>|^vS`z`CRtvwdLc3naC`HydjA>1Bcz}N>RC%FTEnI+KP;h0Vyqc*E
zizW(DlnSV48ja@ui_PZdonu>>OeD#w5I3GAo=TBOBuT_$#2g3D7~Ckr2)IU*R+=%#
zVQVH$DW2ldxfRY<8`I}dpVV+R0{jh_Z{GqU1s$LP{S)v<qgp+5`(QsG-@TJeDhsZl
zL?f=#oedO-AYlYyMA)daTqyD4+#;t|%e-ObAE$-SCls?<gf>w5aRd}lcq;)KB8(_?
z=P2^<uu^wV#S;3x+cvX(beLR!KW-`m%HlT~R0^xSv9!X)<vbVab>^*{yrR@2Ga_Hl
zqN0R?A4}k48x}u-05c+LSgHL3$dR0IM;}b3p)aPC2M~w^H7HkMx(KINl={}P$l2{m
zHD^S~qWDP!-qm!xK74V;z?l=^^ubU}shs>!@>S46sx>IQx7*+E*8Uf{j)$PBSZZnj
O0000<MNUMnLSTY)1k%C)
new file mode 100644
index 0000000000000000000000000000000000000000..8906e80f7e2c57bfca05f524105a861fb278f127
GIT binary patch
literal 1550
zc$@(a2J!icP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000HmNkl<ZScR>Z
zON?Ac6^6gMkDi&HmuH3{cCa1C5i$-ASb!Hiy~2vbB5?!~!crozEFo-1EV2P10Y)s5
zOyaFq2nn%r5=Fcw1PhE5p(KdN3ZB@;cKlF0_B`F)_jc7ehsC|!Gd-T^9wUxa-Kthq
zoxlEb&VQ<%nbFJ6zW(ay%)I;qlTpLO;hdNyX_7qo%)zJM>UlsnGqaxKxkFEV>)Q1j
zccw4>$1c2o(WWn6vWr)5+xNeF@CO^&-)$r<Am9GNN1kz}d*YZ%2S7FHOI-iN`1r(X
z@Zr+ACyso1;-rg+J1>Q)@`uxZyZc%%0@?tElJJ@1Kl=HRkk|WtR#OQ%8a%3k`lg*b
zef;JZ55M$qb)cVmBeTDpe&P00U;WAfb7`z1s2MJbQB{(Gv4KDS>C9GO;{ZlC4L&w7
zF!|BB+4GnRSL)+@>A=&NX>lcNEN|SyH*-|g?fu%Zhnxzn40_}DFEdg5H<+M}jJ~vQ
z=ZnW&^!zE)o&a7v>LSyJDp`FFHO0h}#ltk*AXlzkEmk_vE4K?kKwRku91hs=$aeC+
zNy6fJ(14lYAO-q>MsEfjP7Oj3R0K06%W?**1I*4X;N0qM4r<Nz?D5?L)angP6+}>6
zYt?-_*971IHA8|FF&8Dt?~>K;v2X9=0Bx%2sM=!ExVK1JzlBLCK$xsv*n<JU3{+YS
zz-Dgo_OE}4sg}PPs#?rdP*v0v6~$B-0(7Wa0x-<XqKK~X?*M=qBB3}~g-V*@oGTqD
zm?Em=Sp!VLIk57}xgu=!8m5X_g!jUoS;EEuxPng8RtSXH8NnsYr<<_g8P_{V5aQ|>
z&B@QAD$CRX&Ola#W!KIF+ve`o-v04VPAEX+AWhRW&-1e<PW<$!l@gq+M5C&h2quCz
zxFKU);1OPLeu_a^;E4Yf(f0j(<Io{g3fyr7VGW|4V<e7vVs#cyO-=dIuLp>hLqNfR
z2%^SK9p`+sgLm?ep_MAvD?9k5dyYJK%zLESKz)O=7iv8Ji&qHE20mXN&8$JA-k`o>
z0AyL-0VrBIX~o|}n9&j5OCRHEbqAN01_)6<GyU87+0A`qUPvQ2bJ=tFoN_lWDDGKv
zYgk7JOcWKv%(F9G<_))x4~Msr*b;N|HO7W2Ji29w-6yZHXLCRA<|$#gil7^<y6ynf
z3^73khHa6r*UxYx*}|2Pt@JsVpQ~}%DgANGzh<D`FI1&)ZWv|{j^q9iNKpxyMr^U`
z9GyMIw%QH+$SCPpmANHh$t$@9k{~!$V59A~X#eX1XqTb3KqNe@*ZAJdNj|>#J`4?#
zY^vf#!3*jIR51lrL#_8Px&Tnql7&*!MaVT~bMrF$?@lpVt>A{MB%_0%hBX5g6hkp9
z1gqOn5llM)EKBi<5EOD-NUV9!pZ(`~W!JOVNR`AHttPAsbu0)d%M^Esx2?fIM-oyB
zk(K~rZE`Mrj^FHkf%ws3;wJbofCSJgcyXn3EqaBmKEBhmT(>R&Z8w@imc1w+EID@n
z^S7k$c)UTzCXzG-RYU+&CMFY96zx$0rnWYKLO_acC#}vWikjo#&|h&rM^#wLglzXW
z`Oe`Zgy4&Y?;K4rLND)>6|ibqrx3N<ZP|KF@fM*`1rU6s1fU^?Nb4k9@!8#4m9Q>=
zf`Kxl%l6yK3EGKSmfQwzyxL5AFi_lDmKi7?9?Q%~sd)Ftazg;t*w+G3q_5FV!gd+1
zEJ;-iEA*oKV|Ptc({;+w;Y20NvkcV;6UEeF8lffSh(pD-<@Eo{fDz-e*WUd5tJ{(&
z8MC%tm7fOAj6Aq>%O`agX3_r&fOSG3J3o>A4zf25Mpz-ytsWmogzK}(<mlM=%Q#nk
zVDIZ#0&wgllT*jtB2ag<|L1kQFCs^{Im7%`L1Gu7E?Rw7Pm5fHi#qqY2cdHRr=z}G
z`JN|7hx>-ix@X~9r$$i}FD@*6I6XZ*)q0fv7xf+NY*jU-p8x;=07*qoM6N<$g1$ZV
AnE(I)
new file mode 100644
index 0000000000000000000000000000000000000000..4828b63375b5067b8901ecf061bb65375cafe593
GIT binary patch
literal 410
zc$@*60cHM)P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F80004DNkl<ZScS!x
zL5{;P2t_gJE_cgKvx$_&TrCUeV#XDvK)_0-NELBx!z=!_+s4fBO~bEd2Y`q5a@)4s
z%Cam=I|cX~cv(^+0%nGN-#_|Xfa5rzwFb-#t^GnvZ@mKmVCJ_E5xoE`a{>AUJ+VW{
zXXzyn5dk8aak{x8loKS3_bhz}LByAzrl|(tC5eFaI1Nz(s3eRaBuELs3vMOKEQe=9
z6{uEX2;eN}=yIe1^tY`ftU#phf{}!mRzL^365^5yWFX1_BWm~b5<#Ty0)5{1_tEy!
zMnpA$OmgeQ^ZGnX9Yh*P_MeF}igyZNt*MtNBTmc0C6EcTCD-G6yIcWHuLDFoB&wFS
za2G_PyIq7marQ`+V>|&{He3M!f4%>$0+uc;@68VZJRwC#wC9H|qfDYJAY2X1^ZeG<
zzxks-D^}Yx7hql2A7*ZuOGo!x;}H>v=%WlRtJb^h3BCK`LD4@z3jhEB07*qoM6N<$
Ef=E%W8UO$Q
new file mode 100644
index 0000000000000000000000000000000000000000..e3528f02c939db2a07723980076767c367605454
GIT binary patch
literal 1365
zc$@)M1*-aqP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000FXNkl<ZScSEh
zONbm*6o$WBRb5@vJ<}7CIJ8L2gV-TTA}B$Lx(cXSxDnjA(3LwAapBH|E5)4)m##!a
zNCaIdijOf12`CCa6FZrSMjaC;qfU2EPd)BE$3<0l+D^|nJ(>em6veIk|M#5#Kew(?
zRjyae&d&N%Q&Y7#j%T(^PuE4<&WY;euH}_%_YFIDeXw)O#Ovn25SX2v^=q|SEso=v
zTCG;M*6yg)YP*avH&?6Gok0-X7)9lJISi)-FYKgBY?X4!@Y#3gP98mU>m$K9fTvEK
zx~X2TKNg1Jo=T;1^TC4$Z;Ya-9t6R35Coy```3J<z@IA_-P93;KGjMI6$hvQj74DE
zwrx-C+qdtTjgDXHq;yiDR0^n6%V59?s8gJv0NywReBUnv43=%J60Rhc-`W|KYD5qQ
zWCGTK)2r9m1VlszfqUS+=icS4rPc0m<@XMmUJL9LTrtyFB^bb8Gm<1BiDS|vK@>cN
zRKS=%byO6q*MWeD5XUhh4r2^T4rB!kfB{uNu0sZlG5r$ci&dmZb*4E1Pm4JOoco^%
zj2y3;*V`$^fB@DCz7bsR!tn^Wf_6`Q=4xTD2}7Q45pa?dP!*gL@IXYzCor6WK_Y{$
z7#wd!u&Q_p&bqurx=8}P3=D^=_Oqd?p!w=m6z2rzz=|LueKDqX6D8QV29%x%MIp0-
zIEx{-qg7=kb(<$Joa(_6^j%;I5elT41r>||&p<a-R<r*>1O4?5l%P*ga{_6Wky)F!
zTm!y=rLG`ub1slRKoRRX!C6OU9k#HcZ=jng%c~i>NgGZLzZ>3|^3^L@mge9#7h<mu
zTy9&emGN9~?8zr9_doE!6Ne5RdU%u-2eTj|WN8B8@Qt$6wfG30F)Vd0okZ{qXfe-*
zcEbzv^9PO`Ir37yUf<@N`-k9qBt(QP%Sh7{>x6RPbI0zG)}<vp;BqVFuN4a-IO}lh
zX<&b&VaS_VkS2+}rO~K}2tDxO6+7pU!sk&G6&sRJ!VxDim)e&0YHq{apxPI7Fa%rz
z{NjBH2rwp7s1C1IMEcLYFvbvuA!(ZCWP!{nVjU{N)t`yHMUTor6__YU^sWrmiGF&m
zU9(i9+OdivPWma=;@0b`!vt0f5>w>*@BphYF>3N2=-Pzx4M;?AgW}Emw1FWJo@q7{
zU=c`w3NT5Y{)s{14U2HSOei2uQ70G`d=wAJ>>4&a(`=^u8;ykmd>TkqwY-t@!yvFR
zh9C&=y<Bveb+#4D(qcPXxYWw7{L$U=#z+E1lnU@F;HzqR6#O;yR>k*yCMPFpwU*O`
zg@yCYpS!LV1&iPO(w=X}(n`b_Bl2+&n0MAAuma2jk;zGvC!&Z_skEjD(=>H)9G{z;
zn>+o{haaB)_Uo^{KL69t^W1*?>H2{!TNjtpwh2mQKUseF!pleB>wPzpz?o)KfM54F
z8Y_Mf+;(Mg@z;|lPP~8k@ZsBc@7YsdU0r2)d6`zLb*|g(e%@}kKe5)Ho|&0x&dkiD
z$BrN8t~>82n=q<Qd4$eM<V={9=iYzw!duUs8pQh7v*G?mBNCAtI-Sm6d-v`=@cfG}
zKCyM{)-Ntzy!a{b{f-?wlHqSW&*Pz^5BesIs+D`6eg5*~Uc&QlzxvZVFMKvUc2kGb
zvuDr#>(9yd?c2HU-g~^MyB~k_&tHE0e(vK}z8p1ftle;<VT_^M?Q-^qrWj*hTW{>&
X7MP!rkhXXe00000NkvXXu0mjfYNeO3
new file mode 100644
index 0000000000000000000000000000000000000000..bbbac94c15b45ab65c0148ddd5169d196eada9bf
GIT binary patch
literal 1482
zc$@*s1vUDKP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000G%Nkl<ZScUCZ
z%WqUw82_Df?#$dfcV3-=zMv1FFGD0@L+!XRK{2h7r0GHuDmz1ruISo70ax;JTQ^iT
zKtN2a8?XzYX(GW;5ef>ewjJ6sGxv2~E~f9!RB4TF{3YL=`<?IH`~ALe&i9>jiPjpG
z(A(SFS5;M&7D9^kHbN>swhYD?b6qc(p8jKSczC$HBdv8=>Fetwmo8nJ(OPSz^p?@x
z-F^J><twz3AEOd`&N+PF^RxyW$61VeW7y@!mJkky(ca$PaP;W=s?r=<$v_B!)}>Sv
zLMl3{6xotwvu}P@k>O?p{w@4ZpdtazIbyMx+^&OIET#ts2P^uiXsEBRXSQu`sQ*`m
zX_`29?tDdiMFJljJC+HBLiL<)or9DThG9fbocNHvGJ#OYumdhEr7D*2U!qis$~biB
z(4O0OZkMg&HI3-}`3vUc<RmkrrfzI#Ac=SqQc7^nL4Y;=SFgIR8(ew0VIc4Wj6WYI
zH*emGUcdGY>gwv{$&(*>OLNH5Uhu`4b8T&HE!V43RlEJb_ob8uB_!I~+6JXm>D^ib
zq~xfitF=BiC<H&=y9d)W11UJt>5R(da!()r@~HdMPd=VlL!hUpr)O~Rt81~CjhBT2
zz8<;=-}k{NgVH6Bgb+~1KxruxOTS7gXlN*<A*Fy`oUc(@2c~JFzrP=LG>UvakN*DS
zhi}~Y_WLz|K{A<4QcB>u9t!z9cJFRLYfBp<kuV6QfYzXlVRmK~gaGMu)pC0lLL!%&
zg^&uhwY88!f-I9{c>e4+<nwt@LO>}+B9TmPSOazSyQ&GLP)dP-KyZ#nj~*hO&cL!P
z5K0gUM_}7ggu`J(!V!4B2O%VE+eS@o9fS~2QleNaqEN`gaa<JhdCbgCqp`6ON^4L`
zQNL?f^#%g*c&wID3MCal03ifi$HC0>G=va~sV%JoLMaFcT+am$I84)o9|Z7R2cGM}
z_kB37gTN2qxh|}zjl*xh1E7?FSS(h%hQO(T0ovT$+)OA12tYvaa()4v2arlZ2m!$b
zgy7(ugL47FIh0Zmk|Xc~2q7V*gcJf&Do9n*xd`CR2XGt*=}ZQcQe-ljJ*Nf+=;x<T
ztN(m2FaRKC$7nK<Y-E&zF$Sd-ip9cmL|n*H7DOova+S^nU(C*;NDd(sq~H)jAm9Ol
zAb{f(VHgaQF(ebo#yNYA0#F73jEs!X*AE=XFveg2a2*#Tw|;=u8cHcBtstd>k`hv>
z(wJ0GYL&hyQb}m3AeDkv3PMVFu7ibz1sI_a7$Gn%YsbjQ2wl#A;}qH4+>3<gd6=2a
z;n}n2@P&Y3gaAgt05Ah<I^p`xxN=LDj941-eGdyS^O&6c9Xm5sn45c%betkvCcrtz
z<Hr+rzEH%Ir@!LCg9n(OUw~y=*wA0M0MGaF<jGTHcI<>131ed7iOo4*Sp!Ndy(5#h
z48uTsYYX<j){bn~8&F!|Z=Ak2g$6(=1tAnQwKXsdhICcRR9fj}0+wZo(b3V1<3Eq@
zHzOt~7K@QcB+`;jr$bV1?@U4|#pKkah}rhI2DtD0x=<*LS(YV$ReQm~g9nM@I?+%l
zL|n(UdwY8?_xJaA77B$;kKUU`uQlTFI4*p7;r7)lSKmveQeMCV9krv**yz|w1^{4e
zY)k_vE~<s0p&_THrUtfcZ;L=8kwCU9JA3xb+1YY)%6^zoN)vbQ-fgI^u0}i_-;(ns
zSeAu-`}Q>vLZVu0r!33$($v({k;~-@TmK+ii>axpxtiLVz2$tBZN=Gawl$SX+1m<z
z71HT+s;jGOZ#i380-c?m9hCla+eA1VMz$;4QO>qp1*>u7-6LHc?HzAPDZMh!yfPSL
kk^4X0A0Ga0_|AIUpYQdhxg}6*(*OVf07*qoM6N<$f{dBDfdBvi
new file mode 100644
index 0000000000000000000000000000000000000000..82db5055699c6c9e300a5bc6cc3e7dd936859a00
GIT binary patch
literal 1440
zc$@*C1z-A!P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000GNNkl<ZScR>Z
z&5vA16~%wI>b-7vkBtd2AWvc^4#*IYk?{&5F+q{SB7AHRk~c{FB`jcpvS0%v5yY1N
zz!3@(5!ixkVSz{pIM|K?NZ^bCd-}asb?;?S^?JI;v{<xDx_aML=bm%wRy}cdo;-K{
z!pW1TUv~(Tw)L-m?aTjcn}|DGHxXeN64ze+*_o6Qf;3;)+uQ%ikM~~&5O*iW_}eeN
z^!3YU9)FCt-+qf<{ql8Y(`Nh8Ydh=)UU=a}o;?3?nzrGM8^5@H=l0E~0U7{zXEvK*
z9&mTMzGpUV@JB#_h>%jk-N-p10;;-vUegp*jm2Vth>+Fj`ouf$+}awzGatJ^R>!>z
z9AjL2UI92MCHk%hcT61-xbVzVTLTaQGsE36GgJ-dh}oskW`>&L?hH9|*ri7zK@cHj
z#VG)+j`0wH5uv+dYM2?fZ{67%z*A43C#&M-M-r^$wFIE5Wng!bDk){o?w;KmKuVdM
zOJb^u>Lv!vmJFyGS?$rxf)EM=|IY)ey3{9UC9Cr8op-keaPIs$a#qZ(N}y{6Zry}c
ztE@&+<D<K~TLVa1vo^<6F;)0q64;6aS(Tjh(G{Y6B!L~1b{&8gs)m#aBK+;WzitiS
z>=V1>oR<Ky>ShmUWkFRDX*v7E_On0))O^`*2w_cvFrJJI<ed5ATW=DZme{m}*sO(w
zxG|2u8)Hk;PI&VVzbEHh7|0u@p=t&ZPM!J?-~ZlsXxp}CAczPE1PMqe*FrfurHCCx
zF`T;>svS~Foc`d4s|*`vftn%&vSuVqQ4?YeAOQ)1uo5Cts9a%h6~xhuGR%$GG^l3W
zL4s^v3&0Q&+O`1^1nBz#cL+i1y~0LG&eyJ4VI#)KbUG>EaI9u8E*m7sMFJ7QqyTAR
z!&hE<k*im~!F)bL;ApTB%tOstbUi=#;g7g+<2OhUG-uq6`N>lw%1sPZ%|pP<IB{ai
z^LwAiwC9yqe#*61uMtDw6VHB{Z+-JBXU;rM&KVG-q7#7=(<zrOJ<Ii9zd_r!w37+{
zx_3Z341^drnNW`axZ~Ba_wPSoXJ^i9KYtDNmKa<9^ygc=|NcFu(<v#XrBU4-5uu;<
z93C!;9A>x(AxIrVRu{u{2Hd?EZdtW5DJ62sfFlwJwX>8HDJ9H`T%~qY5I`CROcgEE
zEN1|eg>M4`4rX|jz|0tip04jIAV;;hKj+La4CI{GvM*AW9hRwLAyg(DGcWmXssrv$
zsDp!(bEfNi`o71_&<eoa$tj_=aE;C%C5$nUaw=20GGL~NK+`rGrlD%N?G7~~t*ci`
z3DpX~3RC?s(D(h4fw74QIcp(P4VCi#nDl7cjUMn7LlqB{P*sMZY_DSsq?8zjVQJn~
z21ZY)W<nin+~}D3!wk5)Ei2Uu09B*!d-|^9@@KDb^X6Y@nwBe9E`vM6Fs$t*$8SRj
z3`4(WLNjCNJ7Uw6J;5;sK6h~U@4q|!*hfAEg4NY)armEqXU#kJA3TW9?>)yC_nyPN
zR6lp4>$+t}qkqO@N|_-gYSkjfNJ;~_{G`Zn05RwE-MjyI@7q$^5JHgM-QAlvu3!Ja
zd_I?&St#p)NC?XxjIpz|-OItjLDL`J`($7BFA|l+c6Ls_y!?37ZZ@0A{{DV@@#4j4
z(=@ZmWHN1<X4W)KoKB~crfFs&gcC8wX$WB=A}!F0$ha!GyPLabGaFJGvO9yScB;A0
zDKAn^UDtK@=kxj9OP4-lBH~LEE*1+11|Zi+HD)!-28cDnO6KFa1G@5U4|K<3Q6m7h
u#=x;Qb}B39tM^vpc=KanHCC_3bN&m;%U}LayjrFJ0000<MNUMnLSTaS$g7(G
new file mode 100644
index 0000000000000000000000000000000000000000..59ecc9ff3cbef7d3b2484b2389234c1f39edc8ab
GIT binary patch
literal 1942
zc$@*22Wj|;P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000MFNkl<ZScR>Z
z?Q>Pt6~=#ipL6cb%Z(ujRuTz9&>)l=pjsu6XjB9<&`w+bgpSkc=YHxq{RjG~?Tj;h
z8>cgMMrS%Iq5{4|5uGAZC}4O|X#&cNL4uH%d(Pf#uYNcumm~)5h<j$uIrrRs&U)7K
zthM&uMpc;_w=Hg8TB$U@p<qi%qFcB1UrgeNX;Z%SFvgH&j+b`4vcNfq!NePTdj4pp
z1BjyN;HJlZ*0tc~7EYc#&RYX-P+yL3+<P%5su_KKk8oT2a^fWBy*;lF&-l8kQeR(B
zP>ZTkO;hU2G5Q@)V2r^zhibrkhcO@`%nHvS5}2Hv#2AB@Ks9xoIyH2|0G4$u#fzev
zJC33VU^W27IY(MeL6sniF|c&mk{bqK41^F+RYC}e1QeYOAfF^bP*pPTnW(z&L;`CJ
z&I?KoAQV2n0$>WEsuCm+LST64^bG@8a(g>o1Pyvk0{w~vxjsPxK@}&0bDl-5i@udp
zks``C#yOAod0--P?Z4SCX$Un2L;_yIx02vLhYm7$<PdA`xsT2jcVVo}8Th6g5RsZb
z-V0uYGpEn|Urtp6r-z1UYAEsJpKRm!hlh~>Lqo$XZeNV|LeNl1An05Y<mhs(yab#C
zzSr9Njm|}cL;Ls9ddoce9)6g8|Jp~>{Ds`!(UJE6DWVQa5Fv<wDt0aaQxbR)y!&QL
zt0|uj57F9sE7*t+-rvtZo_Ut8HTNJs)aE&VO@dHJJ0}A{a;h@tvBq%jv$J1AyE1lV
zl%`4<b#VI3XPh{GoVNB3KEE)+7Z)!9u&AvS?|lt`7rA~8NWp@LU`)cIwz;by1YzXD
zIc}cc#N^~SpPo5SP-Rj3Qtr9;ei|zkj4?poh$Lw3yVlyTkw66RJtvMIBZ?EEIKf8o
z3{zm_!Z~82OpJ|j?(BI2FgBTS?|mD%X<ke1y(mhElM=@UkK(=087SnKu^L)y4|c8F
z(4`7d6frS=nIuVy2uvQ0fh11o?7V~Co{cP6FrO30Pjd33kJ$U}do(muuu+6+o^Yy)
zqM+cMqp{LbE9+Aq4-S7-f*=?yUOdK@kzj}-3&vusrCcu4dFL`Vbl*qwO-&3Ao?v)*
zn0@abq<P*gSR3U|Ri{-{AZQ?pV?;cvV63_RS^xoK3`r7$F&H3CGmNpU=v>YZ*R7$Y
zrJ2EFCpdrZ0=r)ypsucoiODMHwd7P)q9~$VF6EVl5>yF6Fly$m0`Wd~Y7D{TK;kH7
zYyT#Cd%J0DtZ@1AC}+=}W8uv$G&R=q>@$C-xw*NPa0LV=t0}+#!&B_p^Df33#Cuc&
z4V9)Tl-FaR(A-)=2vjN!blts*hWdKi+S)jD=nzMb9^vqjL4NhiUobIom8(}T1BM(!
zeyuB)S-tu$-roBjNs^G1N_=^FlqAcFJh@I8)&QsyN0vM9SkAnb`Lwq$VaLm_aP;Vh
z?0Rj0y1EM0YR1^uIL^6RqN*y!7}9de#KdGSM+m4fSZfL&2IV@fSXD9BQi>veuzDq%
z9(jlrD^{@gop(6!!G2zQa}SkD6LAvb#p9eKgj}w?cN8E1mt_PIq>x989Dsb`yAA_N
zWZ?U&I(ewCkBuAF^X3}^T)cRJHwOlYqB>Nm^@}Xa@ZQgeK9@4zVFeL_wFMJO2%5(~
zw*;OjidfUNng<_zfWE#5dFAC-xpe6ZE?pX-R7yyl*4A_H98v(8%KRw_qsZdC%S*ao
zAOyh}h?5v)j!tNeVcpuh>F?jdmd%^ly?Yl24*Z)_r#@!o%9W_*8&?VWvYlobX`0qp
znA&XQpac|xgyNa6oiV)kfSC!PTrS&nYrELCwV&ReUS8Y1i+%gv=hdA%>F8Ka94Ckf
zS(cJkQ_?iWIY*XdwQHKDHFE_!BAy_gP_QNva>k}NqNkqvQ)TP6Z3{PV>8HE9o0qn4
z=kSrEY~Q|vN>g6rS(?(dW-Xt5@?YXOVeQ&3P$kQ<8GFg8YOvOlW$BD03?Y!ERiZd1
zOq~n<{FlE*pI<otyY)Z1zp`;-H#>LkVsLPf=U;dMRYO`Gzv9I=j*X8;y*=xBpl3Zn
z6@x)FP_0&LEUGHDNH}XP&UrHD$Xlc#iXxoL@cALdnBMM<jSoHg=x@ibUitOn#kVm&
zJ}IY$hO(!h{@bW?Zq!;ET3cH`>Fn&hsiC346p>kLE!G-iZ8YV3stwNAK#q=%#sdRy
zt$_Sck|$}-R%2u3Nz>83<fpf`w*Irf|1mCq`6XAbj-7e_#TTCJ?df^_i6@@$&CSiF
zIF9S%IF8EYaw(4EdTVW66h&ogZOIsu0EsciUL!$+s`?N@=3M4g$wZ_o;#2SZr1P#?
ztyaex8XCSZK-;2)3wJH=xMNl4s+B`8Zh!GNBO@a_o_p@O@y8#3yadz%WuShV)fH9(
z67q&-3l<a*zyleO0@YbI2}}T0QzXsea;fxlFLGE!_5)Wn=W6PsX4?JqXVY!=&{-A=
coBmt>2h=|W3Z}n&SO5S307*qoM6N<$f_1>8jQ{`u
new file mode 100644
index 0000000000000000000000000000000000000000..a3e5175b9098d3ccb097e5c633beb1f10fe22ca9
GIT binary patch
literal 1777
zc$@+81`hd&P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000KKNkl<ZScUDE
zeQZ_b9mhZC-1pO--uB+xmy}zev=rzHEk&l%76hdY8D$a8e1T#z7qg*5mPmr5+n6hp
zh$O&-CCemnMW$xLA}(D)J4HHVQlu{t>~85REq%Lf@44KU(|gXdKjsY1iT+2H@cZ-0
z^ZR~3`R14Bmq!vpa4So`rS7)@ZUg+^0KBmGK;_-b%14$gUeY_upR@U^?#=S&Y+kZ>
zN$=gu%12(<d!X{0XiH!B4t)OyKYFsG?c%<&@-k~Q66O544<lM=s`%5cK%l0k#sW}Z
zUvJFI%g<L++^u)qd6(i+Tr{6)P82OF*?Rc*zdd*}ee3@^JaY7P*T~55y@w9|=BKHt
zY2Oy6X?ee?3IEJlq^6}Qx*qoefvKsfqo1`r<ZwE@scC7-;NTzweZ5E)+1l3HvOj<B
z+zp$b{PC|dGBV%Y_~=8?uT9{{(br~2B9S*<JyO4P_Uv3-PAB>K`Gi7K==wCxADqGN
zw7>6kx!zS(bq9c^X}e<4=)HPOUr|<3j@@n}CB;o35Fi?h(bLn-hK)5JDT?yFjgLOu
zbJGM|igNhR$B!+os8~+R`4$Y*BsdYm<+PKXoyGKY94$1tA~%2T3ZE|>fOsta+|}M*
zoGurV1iiieL}Oh{P6n~aG8GleIobHvrH^dbco<l9qu&>X@TG%?R%5bKNm9|{IvJUn
z%*o9qJ1Ya9*8>8Ql9CB)8m$-3qlH3fp%8)2%Y-$Jq@-jJ;PZOO&dOj;ZY~*_ndosH
zB}oO7l`kDUwE8O(2nK^soo)U*hH22=-im)lHY3-r(%&~gvYJe?s^Uw}z~k{SG(5zD
z!fyf4*Vl{B<3+Yu>F8)DtZ9U`FgY{*czr(F+gowF-5mSV8_ZiU|0&?qmjJ4(tGB6Y
z$~x_On00Hvi@*dS=<n+zD=UlUGtCGAHmeO^Mh3&9BN&De1+dv{t~9Tgv5^t9kj6xC
zoU-yVyuNg-HXHt#vyhPasO2AAzI16_b#?W&6DLmW`Fsegs;bhbrnC=#xpU{7SUidZ
z*z9%;(_moWDtmVCrn0Jv){Cw9($h)vc(L0Zbab>{2Pi5kPSW)_6TxxDMn@?wDduEj
zBipub$M2tkMYb@l>j=Q<aPf<sJFmFi>RpYEjiXX!Wu<#?aPTkBZhyAy)bV$C?ae>p
z#Dx<VzEmIO_f$|^S;($m?ILe(0eJ-lSY!(}n~nDNi=P54Tv#%1dU_heH0bK=r0buZ
z?D*LZT2Fq$nfE?mY;uekQDQ`S_<=`QegAztzx(;-?Ck9CNLg7~dmmW8{_*R>QTKZd
zr&(LN9+yQyG9{*UosJ7_<gL!ZQ<6qU$0y9m&&M<joGyjGHNEo(fR(H6+Z2mNkS!Lj
z1OgNl6%xESLD#8%ib@w@v)d7}AZkQ-`@%8qS+ks^OxM(#$Bw-$D~eKDSXk(8Y515;
z<xi01&c>abO2Oi}Z28>}N%v&ZJ=w!-|13s_uMr#{$7Z$B({m+;Fsl$|RZq{An9XV<
zI6ltk@HJ-pXVE>`L%JsuRdu7PDa<b^VB4WBY$|_(mWGchEG%>@ic)Gd48tiBCJX(=
z$dW{|I~mzxK}}UT{pvaV`F`{y4Ov*k(CBa|8jmMT(~R`@_nk8g;~9WJAn;;N&dfVy
zSym=PlU7++Qq*Ks^5^?WPE~O!E|OA`X@31YvLvz4UyMkY7>41r3L%7$;JO?}2ooU$
z0+W&6F^q&ksxJ)@H9;oc)7{-JA?*RecDubZ7K;r4IGxU)w70hv0LcQe4VgOxrZd%-
zhTUNUNif_qikUDG!u+?F1VRWQ>$=`MbZy9V*d2ruVZz}s%N|@xLN|zL5ypl_aSSVT
z4|GQnoHb4JEz>lc{$mahi^T>^(`+(L^DP8ty9c_Xj$wtdp;01QgoJLe?7^jk!(qaS
zFb=zep=(2?uIs%L;P-euuN>I7e^tZ&Q>5j2$yBqs+BraXR~O!lG}b<|#;AF$=4Hb$
zwhAG>v`}s=Ns?R^i)CN^EA@}R{bGY<d}M;$ygX(U_!-s)ndlm4&C{#dvi0evU@-WY
zB!obcq#{*Sx7OCy-d|c$>UOylOZ0k#gqfIb>u4LRt=-WuJ)PJpgwSqgeglMRvsw4m
z)$LldsA!STDqC%?B!y@+VqCa*VXCgK?zpCD`-Bi3U)YB8=g<FnJRV;z%d!)|G|h<9
z={$Yu(xtj@V*KB=V8MdgSS+?&mSyELy_mz{IDPr@<>x+!z5Ow{4R9OaRs;MCoH_~0
Tjwl_{00000NkvXXu0mjf+=+ts
new file mode 100755
index 0000000000000000000000000000000000000000..cf189f4696a1d30580c10e6850ce6e5d95a71ed0
GIT binary patch
literal 1713
zc$@*T22S~jP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000JfNkl<ZScSEg
zPi$OQ6~=$}y*ux{dGp6k98aAzvEwWnxh)AoO;I2fMu4IUb;%Z~NR`?JMJ(8KMa2RM
zkl1vA0I8q?LWm+jYE_`rO+`ovQYG3Zp|PE`Y2u`@-DGC$nfK@3b6GskcpS%-iP|f@
z(HrU9d%knN?>p}*=NzBJnwgpLYqeTENs`9!(9oEOohVnT`<tuz<mklyzfBC6e*>WI
z6u`{Pj9;(U>q(L{>h=1VF=k)AUf-{j8n09;6I$!tQ524aK`<nE!Aj;xj3X>5PM?|m
z{liD@{ThJYZo(5MPTV~<Hum)(2oA(?JbviVq1{mwjcKiiwAO*|`<wPS;KpiBC$s3l
zrxKTNVgV<;m~8_X85#N3!Gj0Cv)%aRm5h~4D3vsEB?JXVz*&bC`fc~Nd!X<8A;2JI
zThX_g8m_i;;!1=LG`WDWVBPxje*+Mae%qXL{p7v(-eZlS)m~xg`U<(*oY*?BvVQKi
zDHzDV<x10(G)c(P6mj4=$OM$?L&u5340PaQ10W(KNrH$)DTSj*WCRp|0_Onv1UjIU
z>Qhh@>yWip=dJ+YxwSI{to@h)+&131f^X|k3Is4l@ReZKUATP!b`5q<d}^K8O-oU<
zTLi2W0Gt!774Sf0T?BXBfk7aHt{99rA{giJ99UxuirgInu!F?i0;Jas=N!1AdM6HR
z1#7{GAR>J+X66nk*uDlFJrRn7+z4U~io%Y@IaagvVzvYjKN9~q_QD5S?KUol`}f^9
z`PFwG;ps=8-VirPLEi;xO@snjZommjfv2F8IlB2aDDZs7pZ(FZpA&0P&Lb#=Jon3A
zZLW8Kg5G~z0U*nBa$|~dtH4*V+!4fXgMvhL%|EaFgNk1!NJ8?=aqph{H;C<{oM4S5
zHx{#ILtjBBcQm^>ZaX%tP&urtK3R~^?RN3<fVZ!l-BkVHdr`e3&$A-ADTLUY10S>v
z#>n<uF#XW<cvuf{zM)%bp}K(DXti70FCyew3S#k<W4UAS5j>?>?if~5!BgM{1ij_g
zFbIQ^j(xm9k?D+7CFqjgAh;d~5h2fWvMj?`A=EyfnG9%MTgC%EXl2}7H6VgDwirmg
z4t)9XuefG*gT!?qa8LqOQkZJaQGJA)S&NQYVOQmD<}S~2<go`B85*G$RFNDiQOx4a
zW&ZGk=ZT_d?Smwguq0{1wYH(%Eo@jA)NQb|zHXQJ(i5L$qIQ5ry}?j*h<TaCQ_wXj
zOUp|%S6al`FpoX?4Xm*!<>5Jn?`dpe`N>azfl`Vf2*|PwYb_4QtwW5(iLic|C`NQ2
zK$>J^i#gw$dy2{NN%r40Nu$=FWJ6Y)tK9hT2Hoo!7jDjSdFfrEYDAy|0z%4O%-Ha5
z(j>d>ICkO?EB%(cwV%PMs+|>F2FW?g#pEK3%ZrrD5uWw&JDOT^n5Y{QjA??M9y<0Y
z`97X=7?&bgoZUPn3quqm*bbIl%;~;zb>M~6hN_fzl~I|a+fGT-jB>e*pU1p+?hGUM
z4fEi>qcnm&;6X`gunI8{g=GRS95{bKpcI!-X9dp#PpN{Mfh&>TyL*DaKKD9z$w8D4
zcwiAmM|Kb&i@DmkjM<UW@tVB&yEDYpS-if;7Y-lA8MrP>?A<-FA+b^ltu?+^h%PtQ
zv=UifZ08HtTKUq4o#Eg10lf6XKW!LiQ}^6c13ta<MfF-eO^8N)cI_CY6qYEtGAEyU
ztzYTJmOFgkr&_JjYBjTkg@w8E?{{n~(u;3hZeM68(n>`sCGv{a>V-alP2|BUa6#pu
zJcTZ6%H=XqP+q%eY`%(TS!R<YnVp}XKlS&QUq1EroBw%p?!EUfaQMk@k9}%*=VCK!
zD_sixwE5!2XC8iOaPKAn=gyxO;L4##9{>xUr|>)vg+hBpc(d80)oRUlI-P&F+wE74
zF{c`h#`)>#>1=v>n#p~8Lls1onnz%*L{<f9IRBUDFaGhnCvMHR<tR?ODY2Bu$w?(4
zHyP<_#=^qFH!oefbP_mw{P^+oc6+tfMrm!7A4KP_W-GzmpMQPvh3}ufZR}P6s!`1N
z_)bRcF?{Fa8_iHS#MIQ(GgDJjTWtg2<iAeahmL)IMd$Cn9>4YK+4)y~{>E0ZTLRd#
zXCHGvyF@!}qe7_FDvXaF_{hY))#-Hj?>py3DYf|mam)H24%*=sTwet500000NkvXX
Hu0mjfM9NfX
new file mode 100755
index 0000000000000000000000000000000000000000..430a62341c613b35c9dddc9bfa359615b2e60b39
GIT binary patch
literal 2373
zc$@)63A*-)P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800006VoOIv0RI60
z0RN!9r;`8x010qNS#tmY3labT3lag+-G2N4000McNliru(+U>~B^h21PFDZ`2+~PJ
zK~#9!)mLe3T-6o+?!9lFeesO#7~Am{3~mCXNk~G{B0^dyEvPJ|i>NA9T~rl;P^GF;
zDXj`ENTm`jC8(v)0zxzp$_|0BxdfclByr+8n={^*u|1n-dGoe=`(wtzAt4E<e|rAR
z%$s}P`OZ1t`OduzXRxlX{e*DaQv7vGy`E@;X693ta2@=wjGbx0>hJ&dvI}qg=}nCr
zZn&xG(yxEn%B6bKgCFFUU2~gf_05lLrcCiWW^vBUCHbcTKtB2)*whI^Da#HIxbd#_
zWc4q$y*#)ye#LZzAXWt0cOTwv92>Y#i??~pt*!T#H5O*a61$zz;d>8nz2mLi@SgG~
z0U&+!!4>zsyhK*LS08+S%iF{6y)f$7q4;D!LH-K_1qEO$+BO9nmn=s~Sfh37lF2$*
ziq(B)Q;SJ+vK}}9U;=>nR3*6Z+qZ{m)^C1zxHf#N|NM(@Xk32TTEic_a5OCIZj?X}
zARVA|DyI6!Yt&HA&#1!)N-9t@<HUo37FpK9`vXlY_4aG-s)M8y3S)cuS(PBXw2OW5
zuIIj!Sk}5_Ux>&u2cl&mibNpor36AiowMLel%QozNUnhJO0eP@N;L|EBB5@~Flzcn
zcDS-aT+J6O^>^QY@R4tA6Wn#rTmnKgs`=I>dLUaJfYl5X6+%D=XwgNidlsSL9Awu5
zNF^vjDWt;;vaZ5x3}B|kug_iD@fBMk5FBXqTz*k|>Cc|TGq?Q1H4Db60MO%KD3MDh
z>a7U?Zv#jJZ~<E82=`_Y8_PoXI*@}DazKI{kidKtLKm=6hB}o&TYn1if&)uqDEcML
zM|B^Qd>bJ|@GLSwg>W6irwJ5F1RMYyK%FcjJ~9t~qw2b5DeIO?a}eC6s>e?it%l07
z4%dYc0uBr`i~}`>AA8R6LQ9*-kMB9ex$T~ogdJD?Kwo?FpKfH1)fSIv=VdfTip>-d
zKwz|lxNTUa@tx17_P+AB*<ITn%lzk!=dA3+JFb!LR|39}T2oWQG>K7_g3Ex90~%E@
z8B!26VqqDcU4_y2$3K>YUDw~XzTt=WzIlkcDi;D7iJ~Y`fC2S=DOY*@@kd9VzV&VZ
zvjB<!cy%w+Ynvj?*WI$Y{<7=tkUYL-!Cfi<_@UyE*NbG*6v6#N33qa6hseynI{w^u
zU#Jv!Q3=#Qw0<TJbu7pr7K&n5mN}|KWUA$>&U01g3uYV1(dofQ?s!rO`{(O6UU{by
z2%gWm3&9E692bdNos`yhw&~f9R{y@ije5hHK4W6{$ijPAxP2vA^}XM3IyS3anbm0}
zE?&jx0*p!|l6OUJ&(^27W0g)JGJ-pnJG1kpqjJEzE52_1RkC0A6Awj*P)wE?a*V+Y
zFv46d=FQ3lW1^>5I3*JRC;=ft2*&dO1^^rZFbu$`kgzN>pn2Jfy4BxYdAivlICm3|
z{c(>mJ@}9uV1^t}fFMIiR00u60<*{<1zT4UNe?fSpBd>X5oqe_aN{e#nx3vEd9IoT
zKfpm?Yl_?wYHd<g@1D%yd&!Rj;hJR;=;$1Ybe+47Y2GHqrI=0=%vgXnQAY5<(W&hF
zciwF#KR8n5Qbh-{BLkUe1c=4}PY7TE0hFpsTp-URq|a$tQ-8@fejaLF6+NA_PQCf+
zlr>*^mry`<fkKr_o=nQLhqgao8rt3iAb&y|Ql=FmHF2|6OpP|Gx%rS^i6p762vVh~
z3(U*1B!}YXb#!f9QGedriA-Yem|e`CG;|6h#~e>XQ*G15Yp*R%0==_<;{Xs;Qbe>-
z^DQ5S>^bVB2g=6*6laDCGy8Y!p6PpSr;$u_$6GGy$Oj|shFTR$4scG869mK;X{oJm
z-q3QvB~X2VRCZ(_%N^@Dka*{3Y3G$Ut_eijuiiZhOqVMAU5^Yq680$~wu+iGWe&g4
z2Y@d$oiMY>yqQhrn>YPfa+oTEiV6>`MKuONf=FzFL^{rG`P_Z=ZEJqneEn^2IqBg+
zNhUc$94*j#(P~2uZFq4XFuh3q1tqX`73EkkE^)IBfCoVSr1L<aeckeGw032N$`$8}
zk1V3{+XT>W0Xo&fL9O{(e|<A&6fU8l^J%bj2`D;?_GndiHb4r7!}C+=g?2s(fF<yy
zRLmO`GJxqS5p@8u>VmmSi*f-J2~aE_A8PcZAuj;<0Mu1Hv8)A_Oioz2(V<F{f2eyO
zrrEJtp%98700lr6K%@$S0|-<n<<zMp>BLL{0C8Oq&Oyoo`oBgEXW!OG?TOd=s#<%p
zu+(&HN`?_xIp5%k+ffR?uuwmkHe^>YJHiMLQXpK-j<YCQAAn%>QwC73{3oXj__~K7
z_l-|GyPkN^*niK%!YPg~u<IlMPI-P@W5H~|+k80_RE_lvP4Ty%eNvw(XT5f4i5XX9
z$H#!tMF2Q}P5{dQ)B=bDn5o1lBnCQfLG-`=bot-|j|w|KQiXTwW4SSxaA*7ec_12G
zQ3{S0?Xf3*^sD5qzi!LzfA%Ro!}mt4mJLRO&+nw9;~hc>ht%MJ3Kzmh0i9GxmjZ|;
zz~+jMIM(yBGx^#Z5KiW-?gdtE@?iSlOWlRB-a!Cq;ad4}>d+DIit9dK?uak5gHnYf
z4A8Shgx(!YtGzQt9`bpdxLV;%1W<?4obBBCp1JQg4+t|gabjbiq6-!*KhiV5NHPTg
zIK?@;JU=!eqzi!7ib6_rHatgWi^W%deY;akCUkoL7AM-Vl<N%A2RY83>Fzf7-g7rE
zjvZRi|FZ({5neA!4d==nhZ*H?eH7lFw1t1a^J*#a?3;qyW7^=6hqM<%KjZm%N9=w7
z9qaHDe{nOt2dcsFPYU29<6}eH^~ZOFv{0<m^?AeM=)k_*?%(}EaC;m;$r$+igHn1b
zV-0N`cTzq5;P%{yW9=-iW@o<4QI%39q&IGEWO`kVnK_U#r+X3=%7KGW0uT+tl~55)
r`*b&@PY&S3BRxAlCQgyw{|oysGyMwz%l5^H00000NkvXXu0mjfR3chC
new file mode 100644
index 0000000000000000000000000000000000000000..ed9193dba51719dc53f2a6aa4bfaefac18feffa7
GIT binary patch
literal 1863
zc$@)82e|l&P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;#5Zi2#W|HF6gK000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyx7
z2oN{7Io@*s00zfNL_t(o!>w0qY*g0~{=PYP{n%X_%)?J)(gg8F1Q9S;G=%~UA&{m{
za7&|<(k2QB)P$r0RVokXN2H~OCMhaON)ldzLW80tLJ=*6rr^|IVZdt&Daa6l2^JyP
z#%6cDd(ZU8dKXOm0K$=0duGnunQ!LKojF7FuqN+5;c<)<7~wNQ6dB<dA$>;JDrBPw
z|0CpHBmB1rE^VFgJ&QY7?Cx;V$F(C2xy%TkF+zwCLO_HtB#aQ!{@=deMsl4I1UD7k
z*K*eY#(WSosnpp<xJk%NAt3@aB8(dcM0mxJSBx-bM2rahhAe0YxkJb`n~LtMx+?%<
zcO73~h}T4zDnd1J0E~Mp$Bkf*A&-jie?}N~3{yzS5n`kv$BOV#AtOc*s2(@)%^EUv
z+W<!IsGcH5whECS_nc}-iZE&f>y60zeUA=5)s@1Z9Xy*NqT_`uf#X?NaN+P@=e$$$
z763rd<RQ+C{t(el0Sw<>onr(WgqS51h(Lv8+#9Ym9=vv7=BUVRWtXZ6Z1}^1hfi)>
zcYnCPj!+GU+t}LLx^mbKcWb8rhHg9Z69QXB=rsaOfH35)s*=&Afj~fU57zLV%beLq
z-~xb?U=G@JINh~&vXEX_01B!o0A6#9&QHiKUApu;8DG76H9Y2q<C56KfB~-6Nv<kv
z{HNAhxT;$Ymps^td$>+N{Fq7XlM(Pm8vBGj{z6(pNvMD-L~7ghzx1Rq6bhm4Y#r+B
z>k*Ack(ZZ;kt0STB_*X(`Tf88U@*#4f&kzIpF;0c;s?RtiXVQOJ-Htl4+}|v#KQls
znHYHr8CFsG$*qe1wI3^AS&7O+m59co9nN}X_QIlti?C|>Di{(ZK@)d8qxs^TUmp76
z^NmFV+Z+)t&+OaxrRj1Gvm4&jo03xjprucr_18n8YnLxK&b!r<iq9%=pyEKMUN$v1
z;nl#axOnj*-rMkAk{?O)!2(mM`XPWLj>qF!l#`nasOl|W1py!nfG-lsxO%nm>8@Tu
zUTz+yPo0kZ{Cpfeb`*R5u_t-9amz-OttdlbVIcq@HQWlTdQ`}#e^GhvnBzE3Dgae$
zNp{^D9LJ>J$}1=+z~*;1WA0Dq!f}%6gqe@e#3y@hys%(xFbMzvtm@kUJ|ej)@l?0Q
z6Q$)=#{7BnI~C0CpWT7>dc7U!?Zx-k%&n;VhR`Pj_juI=Yq0bEok=<~BNIjAi@qi2
zT0N*h={*HdeY6_WW=umUe53c22g<({fq13XO4sUm=ce%TyBI%q{1~P_G8K(YjY(eF
z@-jU4>*qR^w~8+b?d8OizlWYpqB}X)by52B(hkPgu3n2JFD&W$8P%8oDzRAXLaeQg
zXfHe<04hLLPytxja7)az*|XhwfBMYnBwakAxLe}@5OX!nTF{9`qf5TJbZM2xaq<9Y
zSUhQAruo2lF^WN0YaR&yeQ0Uz&@PnueSR!ju;>PWiN!re)v6A56?8`a4euX$yg3LU
z!?Dn?fxP%&`TCIKA4@7hgXXlpz6M{x6TfY$=v3K|Aw#h4^>ufYGgfsXEsO&IV?V;@
z9ZshduQ7<dEu>!vH3E9v=p&z{4(L=_<)KPE`~0&>`pJ?fQMRJ2yUU6<wD0_+RK&#T
zRN%$p?fB!qxlow}0t&(<S>@#7t>8sGKPtb2cuPwQPMkcEq$ku*=x8q%MN7?IwAAdy
zurH3_<Aqzco$o)o;B?{l;dBYoa*hjItK=X68oxP^%MR870Ok$LMVfPaWh7F65?9xi
zqJMTaruhLve=Ly-G#uEaU23o|Pl>2<mTUE@tDv<C*IKw%vFu<S$_|~wSFJr?4^<WJ
z*XQB&dXet+B0W6~Y3b=m@%rHJoz-&#z?y%~5Xd_s$TuX65f}jsiNRUv_}#dH7}MX6
z!i-dO)lZtMccbmy`RLa_8%Wd>65m|8a(mTJ%J)sC@Xv-ECUVmx)IK3Sl#_uU6=q>@
zRyuNhDeyW5jsVSVE*h@4p}BfD9^3l@GII*<4gdg{wfn~n(x$`bOmEx_B0jXl_vwyc
zfIk)f6a$YDv_vf~hubjfauqh$EQT|11Ym6vz}F28cUJ#@A6Tp2$t74_^(ES@!Wh6%
zkQmo)L`FIQ%!ypWD^)LJX!HVN;)xqo#r06=)Exl`1On;;XrK>=oLmG`vf(f>w6=pV
z?Zy*BtOy(`vZ9T6=;|p9ZmGwN+Q0)*3Zqfm>fB+|69f2PU%L2O+8du5qsUQWu_|UM
zG13A|wvc!M0aZgTx%o<Jzw$r5^qVs`eP;lG{{ynHhiN#VU<v>L002ovPDHLkV1lO6
BX#fBK
new file mode 100644
index 0000000000000000000000000000000000000000..9d59099eb77f5478afa24210106eac548157d81c
GIT binary patch
literal 1566
zc$@(q2I2XMP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyx7
z3l|^Hi(VH100o{&L_t(o!>w0aY*bYgU2E?%oze$d9&Mon5D0=mkRa3tYB9b=qm2^O
zAR0f^NPLnZCZebxW-3)wB8V8R5|F4dVu;ZoM0rZ3NLv&iQ4|QRSSY3Kyzlm7W}wBk
zw59uJPVTw6Ywa~_?{hYBmMGb<&*xN%R5(|NViisiGFyc$LN<zUhmadp_?-yqR$qF7
zhaLpG+MMx4?F1zks&K9fAwmcN5kg6*5R&>$t=EuTrh=M^;*rh0CNSl*8uim|RbhpY
z{e^@GOhuRk2SnJQWP=LhDxxCDQL-pSa-ERn6~!YfdqrUCr+Xh(VyOuIA~a1BU@}|T
ztAekT+#|wYRTy^43{nb&n5g7b5#A(ZL<PaBX(Lutlc8=Cn7poPrl_nIVrVjRnvxV@
zOa;qTWcj9>F52JO2j^`4Geg9t3t0;1d!*>lu8;0|xAbiQfZ&9W_<i!{h;>NdqP0~8
zDp)1NETKRICM1*D@OkxN>6V)(MY`oKGYzhK<>9M-UbAde`0yWuSvVYJOH0f1<JTot
zcSvB|n%#F0SS`XV6<C^tlAl(VPM#eM1`T}>3l}X+E~21IKO9rBt6#$NN`%aU2f#oR
z1Hh9`?Sb@rfk5D#!0B(3a|Y}bfjBTsJey&1T10prLHTf3>6Dhf$h;kRDozo|jx-Jk
z`*McUBaDOzXhQg-t?zX7v9hwVPJud7sUvViL05Ap&i4~n*VH_B&A0g_gGfLCkOW9P
z@>BU`kvoy=8Fqeo7LcA~e*c!g{O=c!fD_@O{sRX-b)6i*t@SIcjX4bfng<M6-Wm#>
zJbJWoUT+lW2z>5$2ex}=lK|{?KA-Q=g2F<;%+9C^0ze*s>_{Z{`0>Vj(Mtu|M)0K|
zs?GKYdGCEY5B%tybAAA3o=39tqro}t*IfnvS8i!nM+{|UW$?^a0$5LSaoU7kf}g62
z9x4!MtpH#C2^MMJKGt47s`~D2e;gz1cGugI>W%_|#rt53JKjrpwpE3*drjb68<Lsr
zOn8{%+Q`duQJ|-UJi|f4&T~ogpQVmTocZ3lDv&UX3t%oDj~|Lhqr;rf*G3FGt%@1E
zaC2Ov-k&}7Kv!hr3Cnasx>zjs<dM3%#XjeT0I;z5GQ-Tw29wPw4q>g14u3svcI~)6
zRKPPEn=sH#{1~6?zOAVSK(6y(VTC+#@si~smot?#f{Lchf!X!hMYk_Fu?>9{p4nye
zpbh}0uE#I!c4uB*u86M`GDiqg0ey+s4cq<0`Uc%BE41nF8Ggj2Q|Iezo7M|tR_Yc^
zCE=st<*UZvp-Dr#?SVib0E@@aT)h#^)f@3c<!;bx`26p|lW+KK_?4NR5|HxEe!yyl
z9HT-@UB#(N1ZRxGyzzy|bkZ#n;lHZ!&kI*zaDF~u0AUaq>g(#P%i8CX%@+c;LsjyW
zFd?WaP$8yAkDxeu7`YZbo7{Nx+6f4~_aFx4=L4RXu5BDYb_`v1LR&EN7nFZ<kLTID
z5DWzf8bC8tW(>iJf>C&8+6YV;oP*)Hesp%8G*xX#R`nUZ#LT+a{bb3e5(?i^a=b{J
zNhmcTT~d&X>xbuIY+gSUW@jMFDVzXJ(FE#SqiCwyfLk^`j{XHjr%8}F*3i)X_N%XM
zo;Jo#>^h+5qb-T#(2`vDbAn+xe&l2*d@5*;c{m!5V$#t{d{8|fZp4Ikf5E@?^*!tV
z&jw$$tddfcRUSmtGpGVeL3&&}t&FrISP-ehi<M7fT<j3y;!A>>p*0lR-y;ISV9*i(
z>Y0u2T_I{R^5K{sT2mxaCe`#1D*{JDUaS$99N&+z&4+PgZE$pq!dT2}>FIGS3go;V
zn13?!jc-*A1xCy_!z?2vdH`t#TIxoZG;AnAe$e0_wB*gF9{asbF9ZPm2P@qghZxN}
QLjV8(07*qoM6N<$f{uIAi~s-t
new file mode 100644
index 0000000000000000000000000000000000000000..72617b8089ce019b0a220f0dba8120ffade169b4
GIT binary patch
literal 1595
zc$@({2E_S^P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;wH)0002_L%V+f000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyx7
z3lIyM5FD)l00p~AL_t(o!>yNXjFeXu$AABGpV^t6-9=a^U}<O@2x%yS1a+lB<t4Qt
zDcW?K#<W4~HyazHNOt>0;p=RmsV@nQ#zZQqX>@Jc#zdONinT3Zp{)ysDoFv6F5zVt
zW|o=VnYqUgyF+)U>>F^B$;>nNJoo(1+yC4vCXuy&I+jX;EeNK~Cfb5&rAbY}G+<J{
zncgw!^<es&8NGYIe0O9TqKOvQyn6KBAaw@Q=3v51n7~W~iD1G;zDIt)An6yu=-JbD
zSK)>MtbC~_q~)7}X^%-WOu`HgW*RmQX1W-pi@{V0X2Fc+AT1aH`Jzd?_O#vgj~fE8
zs{4cQ2Jx(!(q{573_!!)+6Ted7o_*h^zUFQB|#06%`>qqNUO}W(WJp(<c@st&gcFq
z6{ief#fwMQS+Kn(ZXfns9weEm9E{z;Z1-O_E<K*h<$OB1-tcDUYK+S%abm^GlxzPd
zqm`Ea?#R3dTZ!>@WMJ+@gct<2EAZ_8jY|h>`W+n|Q!?Jw)y2YvbM}@>LmC(u*bddb
z*98#W@AE3_%|x*19t}5-z$*v8xjc8h&AYq1uWPiuy?xB{?Adb`6$%B)<)M3DT~!U6
z4pSWiVDX+qjnx>}nv^91j@%qjJ_-KBc;3|;8c%jMKLO3ae4b_*Pjk3aV*pg(4vW6V
z?b<s|j6(L?Ll3VU7;oe8B2W)-bh^5_y7*KIng;t@OR46Ciozw_kef&kUH#Qm3`{09
zp!NDm&m+uCi?8+c{AB(9xohW0V1Oi$c=BJnRu4WxOLPt_@1`<Q1SSGgzxJJjry73K
zcIQxHrXSCkJ$vi@c9Ko!p7T-d=>Ub+*4<Z&#r*m6{ab*SZYBbwb));|fWt{DmHOVi
z`SZcu>v%x`vw)_-!Ir+h{>O8<+#fqTJ9Q&nQ2*@k__q(7d_PH&Bn`O7C~5rBkR+k8
z-uTVbKy-gt(vDgYPH6lS&@h?-M_2P?#8eM7M!zKdp=3IAn#<*UA|qX0T~lVqYV^Mc
z)1%V@Fj3yy+uP~r==fAr#*3D_AE-vYm5d6nxCyCM`D78O0g29kg?}a)F8)bow!~EQ
zCS%1hDR8eCxK%2ZGnJtsF+w~Dkb~Tj1CdxNRKigFh+8O?s%K(ENx5A9;m5tbJ5ovV
zS-?w{%9NC8Lc?TK!E`h%D!q2kqet(#g#e=alB%O*+3)$o;cr~&0a}uXmjd>K&+pt_
zOqy3oE)=+uncZ}*X~9F=F28jv0jyReBmk>k;lnYj>+ahXsQl8TW)mI^rK;rz-cH|f
zON<XC2}NsMlcr+fx*C7}^-+6Z^J+Ougj1`G-q6g<#uV9$XQt_Hh3v=gGxI<DXgPO`
zrs8Q9oqZ=8VkH^3^=#K0Y4D>aEe<9hIf^R;@mNcquV${2nquRo`%kg_t?k@4cP=;x
z$8gT|_KrG!)Pw%fx<Pk6SdHFSbrhphjge|}UdXr5J<vj5)h4&@PWtKvve_(|Y?j8x
z44KA88nR6^&zz+RckpfNK6LqGG5Xo6yQ0JJC-VB$EYDnS<=w#y7pj4AX+k2(M$UL%
z&xV9aJ$UW;6Z-m=BS>vRx7Fsf1Oo)#8*1cawSl|`3Is|RMK=ZrT<{d9W17DFCECuv
zNxFH)7+}R>ktxlBxNZGk!!vJexjXhBI;ojN*9cEV9OI)(iqo-yv_Y#yGQmkn3|gR|
zzzWTxv7CnxAjVH36XO&jPz%?-J!hZX@TDF1e`PgqpXn!J*NC&$CXOg#6iCREP$B?E
zG-Gk^yJRk%qCY=C{>l~dmoJkq6pl}80OfKyuL9@P#KB}fJq>e7RJ*he-x))&;md06
z5^F{xXI8nNFZ3N}N#TEhv*Fmz#pQAwnC>{X0L?$`cq*Uy+5Qlmc`lxE=Rp_CBIw!(
tLBlQQUaU&bUrf*0`SY#cKT*Ho{{boYU)m-%r9S`w002ovPDHLkV1mNI3vd7c
new file mode 100644
index 0000000000000000000000000000000000000000..f832ffa441fb221f92acd3e42aaeea41024a5764
GIT binary patch
literal 1540
zc$@(Q2K)JmP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyx7
z2ml;WM>S#q00o3eL_t(o!@ZYpXq{&n#(&rSyk{qElG=YJ-4cY+(bZaK%Ldv}Fb%j=
z+_bb~Xr&t>0jpzZE%l3=>%b2uv~wz~)hIF*MKmaz!=5oxJJf9*>!wLZ=N~q=+9h;J
zvnEYWa?W{fKb#~zNl#9aQoX;tFTBt5-q(9w_kBI@E#`@qr%$JnU`@fa$HYg2X|qYS
z!F0)_Au~O1(zC(zoEd#T|JaR@MTDw7-1=1Shl2EtVA>N*m<bb@i69Y7*yMHc{ul2a
z{L=2Z-j~g0ugI5FTDbYQJs~Z>%iW)du#5<fd%)x-hz`a8kpYZ?T;aV(_TCKaZf|d|
z_Dwz;NJRh^V|x^j0cp3=CL9qXV1Jd7Rpgau{9R6N^xI!PJ(YOZu3acCeB7%7nF4VI
zfRFs@)VApUAdvPr30cTd9`hq|Kl1Dy8_tyPX=`hnPCl(|1rSruJ3BioOR(XWry3*d
zBgPw$fw>bAVjTFE0*{^e<c9HC$-TY3eMWL0ca)yHye8T5Y&NSI0HXWtUZmAb1dHy`
zaPtT}`Qm48$z(DazcZ7W@v`pj?zt;`ekm?9aMKefmlR`cF=;8Wq`8{|8cu?LVQSrh
z0|yoaU_KVE08oHti@w#ZtYTvnvY(yYx%m=T8RZ}<u`vyxc6?}ME>-sdMd1=|$W5dt
zMmuM3>gecLQ1bcc2S|GEW_enCyr<`())Ngat0gc%5=iWQ?eLcIyQz=P3xB8}L$w-M
zNF-)@aM`L=`#xcBa##ORFLOu-7+JaU$mrPE@cHvY_whf7B$Y~irE$#~aQ9i(EPxe2
z?f7{8g$qNUuOvZhYwL7hm$%|v(bd&OXJ;o32Y>LLdk+$lBuUbMdyJCiuG%CCOXll@
zuCA`CAiBD`%3FS?q=%=9uxj#hAFmY0jvZtB_U-e2{S;H#Y*wFp$WIC1kz9>#mAas{
zwe<>{tpv2Aql0WVOELPNg6W>C0x(;Gg+7}>r~3=V$Y+x>dd2@SqVu-!_a&v`pU2H4
z%GWK_h^nzubT1fqQYaM87A7W|lT@mV48P2ZJ25v>2ov#*#nN0Y3PrC;OiJ?k{MX*;
z>w7qrB-aC;vs6t^HMOW@Mg>g0VQuc2_4o9yzoruSx}u|G<FEP6%b&j31JoxG&jswO
zn+_crOX_ZwTqtm{W>sx}ZPSkZ@BR6jNf6z)C=wEYTc70h87sHlemGG0p-FWnJQzw9
z^KE}gH(whG+?S4ZzqK_@!9wMR{c*3g?b#w{op4m@5cP#RmM=+hTVws=@)h!oy!s4-
z*`wrNdyd_|KfJN|{OQdh7Lqwz&ki3?gZG+rQ!x4Dued@GcjVq+Q@)P`Ul4%$(RcXN
zTR-Cc4GrKR9K-4F>+`C;uS3Ug27f*TTM>ktPzXjavG<l6cwkc#*Vm@!GaN=wJ<Zrp
zzR2o^21<X{fW(EtL9FWL{o7u5`R*9~T+v<8OCv#a=jh+gvE!*;e)q3;`S-;fbNPuR
zikdv#XRUGfg}I*{>TZ$g@gRM$Bn72OC>TMaDUPr<Kgg;$N}W%T@*)OISi)#Xvu5}o
z>^u87%Nm<5gOC^;7+^tXLEPW^$MER!`)-UwC*Ra^qDm$qcN{nu>gZ3^vm`N^>(bO+
z7f1zTBp*4So8ZIbSehS(5N1daV_cm7e>3x_FKyXL$4hTB5uFeq$S7x}G(+0-eUNAz
z@8gk|zRvpmSqhdaC3R<XZ0yXU0Aw;5F9Q9l<;7$TJ=ZmmXliJk1Tk5pVQPpqBayQr
zKg4Yp&aiIeKWy*Ktj)`m&&NxPJ&r9v-FFY%KV0*@6CpT_F79{dP8S;^NbYEIp2I=z
qV@2tw1L@U=zQ6B*f0hXgz<&WY?PDaf4M~3h0000<MNUMnLSTY_3hCDX
new file mode 100644
index 0000000000000000000000000000000000000000..707c0e1628a341001782eb34f90cec7c894f01f7
GIT binary patch
literal 1597
zc$@(}2EzG?P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyx7
z3ls<U%9Vlu00q5CL_t(o!>yNpa8%V5$G_im?#pI(6C@#$w8@A?CIg6r3@F7iHnh`P
zD>yWxOh<>>_Ai|>{h<!~PpP&2Yg6Lb)+yBLOtB0WTgR$(S{(;Q#TLkbHHj8ltDuNU
zLokGd-R!=1Pyg6mNNfU|A7|#y-hJ=xJD+pjx!=8qxP-O5@K)ed8dbPah?Oc_CS+2D
z!$J;-@b5yttio4C(6jTipYfQ4@nSbuKi_?|k|`B#R3StNAs|912^B($pT+qul8>mM
zYsbnfho%g$?3pf&(blPOhmf;`ga}MUSa1%AuwTi36^1IJBB)Zbu?V?a$o3s8uk4r-
z!1AZxyjzKfMHmyIX#s$RXyr{6yr|?GBK(&Mvrbt-O1%(Elw2;tn}r-vLHh7@^R{=A
znX&<v?moOmRCWsS=|bc*B`LzZ3bv`pwmmm5J~Gh*zrOFi3K6?r$X2-Ep2iage}DVq
zt-l5U2+jn=J4>HMeq4aXPadvU!DB+K6$(UPLb4DIAJ6~~zxLH@M#`!#GfhACv%7En
z=dMTQXFq(GFw16h93CEiVA1Yq=ePh1cOCi~ft?~usK81PN<Q7ux^zQ2oi@yXEq*HH
z)*V6w0Iqa#!H$FR$om!{6Yu~GG%)}?>(stgTDN)g=4m-^YimQG7Xp{kBm|lwZ>u9S
z_`)#nJtDK;9c;aJ7&B=9zVR0QKY--OKrN&23Wgyp3}I17^C4oHf!|<;ZSS|AX)euO
z*KL>`BR=2N^`kGmGPk9UEKrdINZj*w`>K)KQ0)!-|1v`W)q^K*|K@??M}NC=Ue1Yd
z%d9zb?){P+!@Az>HmW!c0ETL7x1Gym&i3^U+%;1f@W2;o_AG!y5(L3_>KhtRT{Fjm
zx<(cUO7oi9T3lXNSM40`Jim2f1Y<;7TietC%-%5I&Ts5LrsAB70WkBPFvGY5fO8r@
zzr{xi*HT+jQ-bhjk9xCK4<t)PNRpS7mN8$Z0rBJw^E<t_(?0U+WjgP2IuMb!eFkih
z=@!&fA<S%l<n4MlD!rTv0Aq!prGJ{9luCNT2ZUYb%q}hOBr)E)sX7OM$Sf4VTo{HY
z!d$M&1;MCf*oCZ^!Doj;&H4AraX!&&_#|K$S)~)w<@5O;eALtP<G{I30kEtDm04CM
z!Gait5O(WT*_Re>=w4Vx<f$#GaRE|WQs?WXxD}ft1KpB8;E#uH9qa;7?K~{2kndl+
zbz8<&EhmkjVz6>fvNzed{{Azsk14#16=fM(u!<h)0ATrZI6CI;nj6{`;iE!U31KQ=
z5an<BTdZkjwAd_>+4KJD7(&r;7yR|{Zn<gWDjJ#z0}DHZJz9m?@c=98t0(6#%wy;u
zFX8ly+mV0!RowCC_9abyZ!J?Fx(T<QwC{}p)-B`$6<YBqPE{hkdOq%2)PPD?o{VIV
zcjCVfeh!z<oeLO17zBpio*tX<3I4t{BW7G1dHXmr(0fDVJtA*N?Rysw9yo@NhDXW~
z97LzyM<S6xJdr>=UWv+h92JQqs%F>lq9NG*YmOT24)5(`WJYg5VHmb|p2Yg+yYZ+0
zoWk+JEGE(ul89LRcmKp1Gb>O1Wb2+53V)^KB9T#@P_aW=QD2QOUr~eRnm8Jg6-YRR
z6JRhGq4!)4gNI+hEiZo$v+5f!K#(}y-(SA`>O*_4TVQ7n9@E(v4N+)X3iG%VG*!h=
zRiOw}FqHS`%jR%RUk9G(+ypo8YQX#R0H=C;C#U~EOh06amR7WNe1M!cr~*nssa?B}
z85sjuKhlGrbliu9`4b2wC^$94xlHEBqyW<Cv_$}VnZyCtfUb(Ua4a>gMF=fAFEz0u
za5U892e9JfBWND_5MSv|UzMjYpZCLVk`f{cRQ-JOrn8m5ctzDvZ^R}utTkeZ2S_u}
vipNR=XqJh{C;DS`TYq`)ci$OvG6e8Hq3vrR-9Cqz00000NkvXXu0mjft2O7d
new file mode 100644
index 0000000000000000000000000000000000000000..1f727bf0f74bc0c8e5d1d1d23f49f5ffeffd4fa1
GIT binary patch
literal 2024
zc$@*~2N(E>P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyx7
z3mqJ+ZRaNd00(GEL_t(o!>yNna8=b2z<;~vzI?nSmV}tZ20y9<BI2M0L?B|Q(^`r`
zV3eUamRbi#M~12h(YBVVGfW>EYK!tAFawm)TBH_5iywo7pGYJs2^N$p_(cLjLLlTN
z@7}xp<K-owqz1~FIrH|NyZ7#I_wLzqSNM)m{`~fc=d{?V+^E7Zr*f%^WI2@<6=_nH
zw^ig7r}COA^{X%cLC8rAIniP)7PHFAN-2A;?jk2r=~QlXDyRx7pei^KoC@0U+aW(8
zB9A(ycIB}1j+`>UrO(v5bg^rl%1RYELq$-<oT?;^gQ^^GA_ts`?^K;C*-oUm1M(>q
zsaiSgyy{Z|7`*m_Tb=NTs-&xmxg>xjz10t#@}d)YPgOp0Dsj(Anur#vFwlt%R+TX-
z(&m&{&CqifZxd<lF~FdwYDTNm)hc{H>A9E_5miYzWsy@|v~kRU9o;=}@*AI~soG^K
zG7&FwTk#iL{&xNHiAw-b4n>4rgVvEaA;5qqYYLsROoeMy6je+`B<YRJaS<MQ{bv`q
z^(ec{Tx{7xw~qSv6OW!B|MC;TEFN!{mX?+|7d{oNJ|RHq6I&+;tX7q%Q!EAHMAlYM
z95g8wiy5b34ETGcckNaJ057%JcjcDMAPmb@BuWSvVrqaK_MF|6(wjYd_Wxyk-n@B4
zT$kgT5`5?rgjN=q5hkaFVMt*1*DVt-Y2h@Ek4KGl-vY>LYs!<rKSz8Y^L;Gv#X_I-
z)~2PL=JD#Up6Qp8z1r*Ol`dRaTl@PTZ7L|w7fDiy2#9dohgHMdt|KQjHvj810pv7)
zb^R~j*|T%SuyflzRk`ns-o5YovF_&DhQ)SFavH#qyu3w6TU!tB-`_M9APhsoFvK~R
zgiO6c-%onvb*2^j_U)sosfqmjeDd=0I@d$EO3c;)TQw4i++J8zL{4sRi{uwe$0Q}^
z=H+o_etwSUaRb29|9F~6R)nF$hmuGnxAUsitB7Pp7<uJLf*=5(|G@qfo?S@)i~H02
ztlpHBm(kGBkOVM$&)|k%Y~JnMoj*)}FgG{XEDS}u30V*X9BMwad*@kKmE1Dz7Iy5|
z!OI(8MnovNpoDP~#{sZm{RRpO3II5G;2<+@pTU&LQ`o+JJMY%KOEelK%}ZnNIRmBv
z4<NEU6)%x)&3BcSl(2BYLN>j=iMfBA%lhZn({!kb`Sa#eT3XtvJm<bSo$?DCUZ8e+
zE!kPwSYSLk;{0ttfAf=rf>r3LBvD>o9!nQ3#SeUH-ml?`kymiXj61%iH+KA3N(Pj$
zWZ4ob##Jz5`i!oqhW3WRB=1x+dH0^(opQsz2IBEJnVFf#>6DEq<Lo|X)7aR^x@Xt1
zX6>3|Dz$A6LMH1s!`qXwYu7F+e^W_Lb`BNeD){K*kGSWz_k2t5-pYGf{McgVKQtf1
zSg~qF*G@1#56!;knSHly5h0})h9OgLp32eIqddOwaVAfi%%CBISn${aCXAmz`IY5V
zzgx|kwQCr0`3O{%rOT7GtfX&A*DEmd6-<5K|H5x?7di?L0*HZ_AqIqm@gu%#4?hK{
z`coBeZGMX}SC3)Z&C|%q$zjE^6^IBoO}mN1hYw?BELpmQ36mx;{<`tJz4>h_##J!)
z!MR;^Be0AxM7%^Iap&Ip`aeWG?<~OL8p()DMi!DRMm{Qa?t=JBrIYGPfmt(WF>B_m
z<03Tbictjdp!5G_LocIoUn6_>?#1_gii(OzPftJYp3tmcV2C$x4Nq?!*IWzacp(;d
z=pC0lyr|X79xP&lIGQthXEkIMSKNK*%^v58s#08B-0k(yY`BCt4`A@K>^$!3=n+*8
z|8W(`R>7PiksxvPTj_mH&tYH|ZQb};SvtPD6Dn+2UZ+>zI9!Z=f|1IMdY4VF%m_mY
zb572lpWw**FLCh2#Uws_jVbG^2KL#%{ZbeDUbp2>t6oh9t5cD_PQ^Mt#l<-xR(3v9
zFDxR%>scL(@7cz_`$uwSK>-*DhGI0-*ITzw2xpFNGm~qA&>90n!q5o9kRUWF-}r?4
z-`UOHmbM;5+X%k?jA%4UW;9A>W(FCVnWROt$nKRZ|I-D#d-P5dn-YfhRbVEeL2??4
zw|zy$b9MalKVP$_IZk)=L_`Rr<8=Rqj+r4n%IJqTmW#?lCvu_cF`ZCHhcu)xho792
zOTXMqin7v(dJa#axjmraXgkd{&olOwUvoxbaTkOL2M-+R832Hr|LV}bc4*6P*NbBz
zl1)oe&h(T%+394bIU-Iuk_g!!Z|CCu)vVe!9q-(WAPhSJzHVsfIRL=#V)HFpK9PCV
zpVJ;1&Vdsp)vk3#Mvnt5Y^&#i>Y0=#zQET=(x@3nTU&RW6hJH%vjAw2EZ*^os7))t
zlT_2%0pU7~r<zz*JTY<;O$=$=LBAtk^3%H51qo3}B*K=HJ&x5u_Mc}@Kb-NGP0ksG
zCQLWu8WRSFAe~1DlH77;t%1m@1L^q>FSu*QE{^>&1pW)sTIqC;0Uq=K0000<MNUMn
GLSTYVhtDnm
new file mode 100644
index 0000000000000000000000000000000000000000..cf0fd38174d6901460943a4c7e66039eb95afaae
GIT binary patch
literal 22733
zc$@$_K*hg_P)<h;3K|Lk000e1NJLTq004jh004jp1^@s6!#-il001BWNkl<Zc%0<D
zd6=bVSttCvpXYg(v!B}c>Z<B}-_z+Nodr6CYy<@%=<tCeDxZ8t$C+zJ2OS+9@NyhM
zXLLRdDhQ%7V88?tAc1uDwbPw+(tB6e(%n^c&Z)DXcYBuakM~q{$G|6GAdPeP^<HPG
zrQh@1zvp+a&s}7U!RsM^OoTFk2*8y9{t|#_KmQ_tcK~<=z+V9P0Duhuz6@X(z#0In
z0jzI-|IY#V3V_M>?<Sf+U++g~(~d(-rEMdsOnYeq!+HSb!44(5oD45xp4Q~K9vSL3
zMbpHm4Z(|i;w8YnXS-?Hzm8_}CxFGr4De%@+|f9II{<v*by<ryLcU);ir4u*UUzX5
zBUmxIi;av-aWbwlf#p(KOmuek^l7*-Mj06t&w;$@0Vky#CnY?S(OwW@mtneAtQ&cr
zp>y+TS{%Fy3+F~Kw=kjQWYVa{8~y3tc)9EVAOLUyTm?{WLq9gI-OW9jvOI52@y@|(
zb6u-{Tx(w;@{5K-AH>qh^w>CzsyeLnw@xBB+4L(B3yc{ISt_MEyIVOJ8OUn3+P9ES
zOhrTMCwOyQVP<w*mro37(;xt^4-@{V$r}y;4nQ%WQvjtg&~HmHZ!KtZ<gk^QG?ir0
zBBMBUZn(kpZoUhPhd-tL#itk{BH?lpLU1Y4TeoieFB9YI9>`erZ#3(*nb|_%A3JaF
zO*;M@k95O8FsZ^;;8mYOx%@Dv)8{vgB}H|`2ib*ZimG%DuahzS(ULa|05*WN<Dlyt
zP}wDRt^>^PbSM>q*&<<DuI1*m>0rE>Pg<Gra__|Nt*w9Npev_VQ1|HW*2q4inG;H5
zJQ&z(hpm-8SwE-Yyfc^SN8bQp>jopg`N+Y$j-8%=&X>$FJU8kl^E;9wJvV!;@{`TV
zxqC9+;#_un-m0ytsUxS~qs{DB3{ZQcmgR>oKU4rH0LcWfW+f<R6T5P?#RFJ8(Q*+m
z?IdCKrW0yq(#DRoh&E<LX?238haPq}cD2+Y`%degm70N7SFXas?tMVyK`RBNG^CVR
zT&zPI4Xq7gN;kq4a#L59&DWZ0rsWq7MU~>S+E`t7cHk|^;VpmMsLX%aTRiuL{6N-h
zNOrQ9!;Hkj=M3<FhJ)}!0e}IJvq0BQfX3G_Hkxxqz2!1Q!b%Vy%4X%&dB^PQ5dPi-
zQ)9Me3C=BWHwj9PW3svpS9eSy-~Bcg!U0?VcDO4>K#>n)bPNEc5JeHfAVlB?2!jAY
z6k*f4l|MHz>b<3~SbM%utUfVcEWcQ*HcDRk=--9)%+r~!)$dCr^1JJW)4$hmhb6VS
zR~&zFi!_BN{*SN-^n(rq_ho^(F|e(J#QhFeL@LEJ>~zjnJNjIGd$%obPTOY8wiDpV
zE{OafSauM+a|j~cg@9%7@n^Dl?=FUw11U(&p!zq$q<aCQ0071SS{oRxAf<wo5<wWC
z)%4J8dhl8;_`VO%^K`A=JiRb=@>_GqU-;I!x^=oK-H7*XeLoVtqm{XrewoXturOVS
z4nO}nsZ0<r5`Z*fPPklAaao0d27n7-U=Y-?m$78RwHCdE5XR1QCUEs|GJ1cvtKaOp
zj%%d{VfC(o)w>p=V+APP31%k&Ccrp{3K{zQB?h_`z~lGerlC0lz2-9u*d|_#v`M3*
zLnDeJ1VMmiqlsFr!LnYsdWbEo&YXGR&Z$)AV+UI!_nx^>`rBye%^%8S`ajqzy!87k
z`UEm7C-h^dj%o#<6Trg&t_M*1K`huCD6cyJB!GksTyX_4t2-@xmavr)PG`dG8PA$u
z>`Cbx6Umfib&SIr*aWM04R~%CERh9-6>n!50y+Ye2QCHH4RykbrU3<zaKJ1F#Mo=L
zqcH%HX}j|bj1f3za2y-ybQ+yqooGb{p?@5_voo8koWEtlntStczx%<b%KFKv-gjNq
z!CS**g7afr`sHHlv~kae<`{qsVkY?4Ca)U+41gSf>L{pmg~L0nv>oWAWeYtvp4A^3
zN}2bjQf|`jUIk}xD@4y~P_h$@+W=!gSOo$NC<!tKWOV$fZ3JN&%=ba0fTRP%M63-%
z?Z+4iL_quowO_OLmkbyKIOnhv95l8DdjDPU&OQfm`YC5edHU8-dEnZ6%?7`Y!YZ!I
zm82i)fpuBGQx)YO&BN%|YoRVPdEEfubKuQ)F!q?079LMK(uhQV#@w<hk6-IdIcu!!
z0PMl-uzS~lCp%+hwMsx3TUO!@h}p3gwE;x|5c!aiK&i-~t0w@8VEWfXY6Cz4+5nee
zU<m+3)PBwYGJv5rGZ4rqFdYH|>ma(v;g0V{>-Zz!r=Q5&S^Gq0A(Q&(v3llXjZi*l
z^T2d(1@2sck|&@|>-Ac#%ST=}0Ce66e!9EcO1F}Z=IC3O!(C$?_&GP(A*|jFu=_TF
zr@Fw1ftm||zX*gakRcER2yIGN3Wy@W^MO_qCS*8SNg#Ajz}9uB#2_LAP#9s!1`xG(
zJpt5a0LEev5V4Ej!x*U50K0GmhCASiELhJ<h-@F6p$)KJ`Wl>buWZWm*4<~D?kDER
zzPn~piz6eg;6j&)Ry_h;ie9f3yFBD|0l@G7B#D9kF1yxBI~f-n*7e|b2eaaOk?x1x
zzYSJ?6r9^2zYH{sfb_u>fusZ?2}lJ<3CIWt+n4VHz7GmHimf$h*(Ic90ctZr5(h~i
zpjh4Q?GCnN0*IhBmI1KD2xJMc%6YKTd1%G}+Xf{&;%j6ZL~a1q@dIGT9!{=dwO>zi
zd;Mg?`E3gM^fBRi@7)qb)x%K7<m<6&mxug|0r0V(A<-@JZlF?5XF^}SWq|+pj<mZ<
z<R@VFZH7p6f-4Es&jWr9Oc{_=Kq!GQj31*22qGYgV4@fdCQ@KBf{+YJCb1Yf==DNK
zD-ESJNU3GT0|Z8ZZoeih?S25zF#s3?aRYn$CD6hQSUL~m*f3rVRGR}&_kdEJ$ZWY4
zB0m6r_^TK#&i+`Eo1v36@$Va<dqi{@|Nq`3gFij;uLlJGA^?2!XGnCiyhA$ecBkm(
zEq(Nd>7?6jb*+cfy9wM*fPxCBQ2<m3iZsX%;@us}w(=!R7+;VIPzFXDKpQAcAY}mU
zqW}l%ARtqnP%;8(jf?6B6kTEhsO<-!P5ne5gP8u0J`EJ-L4gNKq+nbZTC_l|GANM;
z&krH7Vh4C42lm3fz`3JWFlIh^yexjD9=T6aua95cEQ3FJ>0bv3zHb2h(YuLv*?E`g
zwA+)STQ>L6A7)&)%kEqYr)LAW<$^UAK+O_J8&D{LrU$e<zz={(!${TM@ft=N7#+v(
zMz^iI29(rDBrO#E6qMvpi3~_9z?kJI(BNVsgxbCUBLKvfO#}%BzIYxqc?3{l%sx&X
zlyJck2^hx$`3<010P7rs(>aR#j<<uj1xz1Vy)GyJ<XDw|xExqdu`Y?bHX-=p5vT`$
z#6j?V0pRX^jQ5OnI$o4=^J%<gb07c1wBvT!-Rt1=t^?;BtTqegRe_~l-)sR*9|!^<
zRM5%*Do*AZ4H#{p4WKn(lz}p_{pOq_%@k^O4q>Vnk&}W6{McUrVrpkBb}orQ10bWJ
z3;?KQCV-uQIP(%vD#F+nC=39>ftCO{4v=ubTo=X`FkTJF4#LXxA-8cqj5aVcM^>!O
znLmDc(fVLBFo*n{kN;}~ft-YT_;pgo8zJ8_0G`=LEEwvtp^}NbLsx9>WgpA9$u7Hl
z6`Y<mU<9zr49Kqop#nAiSoy602qlcvFcL7DU`(uhtpTMCv;quqz;dCS1VU~>D}`#r
zAwz)$1JoJ~==t+7GK?b!7$8<V1QT$RNhDHfShfpBEG`ZKfRbRRUxM}`5EFn_phyCt
z4|pw5OMqM(I^lx37IdQsxOuRS709gK3ljy<7fz0^&f&iwD?7gsGCH9qJhiC_^XLM!
zdYu*X!;<d_03YfncFh&GmC$y=7JAj%F8Z%IH!*5=O~CG32hJF%ItywwKz;;jv=tvj
zK&0Z`t_WJi%GU-^(m*M|FbgJ`hHtrOL<(ND1=%Qp8cocJZgd89RDv@wA_YxWI|tMT
z0L2-=P-`?7OQ6Lf5{`>RDuHAw4=a&^@#?_I7oo@kQ!Gw0wQ~q$G@t@NMqr^2@;Sf^
zbYT`Korf4)kIcj_sK|pU%xoRc&~F{DieD*N*4*kHQRC;IgZaxMjQ@kt(GOI<CjeY~
zCGnb-N(w{W6KVAyds6N;yJHY`&uVZmu*xi`UIBR_sNn%#O!vz>UIE4slm@giP!iBg
zz@##0+6k0v4b)DbMNq83uQj1UiAY8`*)fPg*}|!y1pC}Mh`bMr#j!q!z=?qi4$cLL
zTyREcN(H}KN2OeWo6V!6u?TAUP|S%V3?8S70RtEVf(F8vjz~t}OaofMw5A|K4}5qN
zGGjZS{3iN!`KG26ADXS(e-LP`28UH^QyKEPA3+-Ut^x3;R}pu*9hX9$9LPmKHJs*e
zw~`&OJ14-2$FyH9g0&)`<pW;ScJ3%vz9wiD)4h}iN)h0s&~no#H9eG%okZpAJj(SZ
zEMhQ>pkUwu5cw{2&d;I3ZFCU>q6kuJ5Sez2PvDG!aSp~AII-CAV*-wCBMKrk?)~4W
z%$3nU*o#EegbC^}09czx00v?jkZnMa1|vX_4O5v17>6~u9_ba^5S@4eBRc%KTF725
z_|BKC6`uOVy3u!?hW=4&CHbxZa91C(EB9JfT_)UYLhYGIvkyBW2|F_YP8O(g4pc3G
zS|QL30AI!qUR&`o?E^{~NM)ckN91NvjDUsXXHlKJfWl%OO=ZA21LI3Rfy9iJLqX@U
zvwi{RnKXR<f)x2KW!e<Zg%E;s!MT7C0-Uq9^T@!Mgw__w_d#EO2vKnk)x`$-#s<-s
z>;n8s9C{)S6B!t2$){ih#yCKL;RdFB9>#LvbdMoDum)=Sh%=TkzuJh{E6U?Xn?q9W
zoksYz=(4RCe_Q!y0r1WtL2te?&&xhba*O&#)B3|H!8(PL1?MiPRsd@(g85MlfM7}a
zY<c%96;r+pH555$3K!=}HPoi(QNK{aq8Gvgfh>*y2B9|awSg~Xbb4YN&)Y%$d@_5~
z?dvU69(}By=<g4CI%Aj+j2PKMSZT*`I^9H~JDp1PB$BDT<2a0S4$V0*c>=-g3>>MD
zoms$KqlNlNAI1hc;RIDc24I3MYmSJ;ekBOR0S*I02D)$-%t<2AJC2~bfDSdkdN|2`
zcCu;zwsLiJ!)mRLy#hJ)16A4UE8h_SJv~>^>Xqx+>K)heX;yJN`C@7!*}T2q!3~@&
zSat@?Yl4MMP^dwHjFm3|EGr)|?JGbA3Q`JGY#ZkaRmj-|)Cv_WMhemrFdFb-(9%G|
zpk5<BTkKjLOm^(p)LlAspkk+<$&pod{h+~vFti=1l>rAqghAxCTCF6?<(%N6+jgv>
zOeV9sqoZ>?V_E6o;fEj_EyzRyQPV@Gl<)$H<1HT(WBtfz4jr{X7F(|Q5+}egkOmkt
z;A9}Qf|)-JF}w+>fi(!5W%Q?_cP#|$p_a0~&ijLK_j%~43VvjYhpz#^$jEgxI<l4T
z*l{f*N2;op+*Wp;L2n$kDnFA9BobB<cFO~6w7?hxfyWM%0?@YgvGU{HFGB^XZIpzK
zVxt8%S3+&Efub_df+GT<1&yjkwPNU%28lCOk*?D2+uzaYM~D6T;(f|;XA+TKh;-Bn
zw3331fmQ@C&ImRbbD=4%l*+YQQFpUmf4(?9J(lHc3w!qI%}FMbAOhnYHKmcMHz1}Z
zjx{~3T0M*o?n21`jAEZ4E+WO@B@qWB1Ho+Qpaor;hTT1mMCUM~@Qgd0G9Nfz<u4HD
z!Nvg<JzIhPQDK2s0l*r08(n?ln}k!ATuGU5y83U`SaIW|7Y&?_ywNFtZe>qY!Ig;`
zt}ISsw6zFIxj;G%C=Rr3J`|vJT#%8GhSU}onS)}Z1wFff`C=6nZ6Jk!CZMH^Dj2*{
zG3;rNiD{M1H_}(!@l)r~AIgOT|0_!7k1M7xv`kcSeGzaXt&B3zh9adYk+GR=Ac81z
zxL^rwbOuUxMfKX`{Q23Fl+M1KY1FSaGFZ!qAcR1`0TzUCi&eZ5M%cJ|7#+5NmJ%cg
zngB*Dt}`0~Ax<_4W<%8qV95?7x<}ww=Fu%%*Uq=_=Eczde7?&M_T-J4s{Cm90?Pn!
zuep(pZ(GZiuPkX(Pv_{Cj~ip{UYvgE1zkHO_atY=mB`To8^;%d9r%LYhqZJJca)yT
zZtVe%1sDfL0oug$FQtJt0uA9}q0)dpJBNiz9Tfv8!9gH2q^i$JeV}3ZL0{N2d|;$e
zUvb@?U1M9v`Qax%(h|<gDwQnwkuK_><{dkBNG8rD4UtBxmBSrx{~aW(hiU$Ng*v;s
zIActhNH0cFRMgGJoM|>MXy2bJ6Q7Y_S8>ojn=#ko1i=k#t<l-^@ydx=Y}+t`6lrLw
z!HMEr1F^UhiJN66;95eJXCZo5A<@x~&_9Fz1m0Z^*a2+`f8#(Dt*AgwUA`@Z%d!lB
zts~>an_0{FNMr}s{2qbE>a$P%irbi!SBjV3{?qx>b}E?!Priacxi~2Y@Re{2{wv;v
z3GY09mQG*;D}qT0Z5&7yn*d)VFk7l2JaZlkr5Z{GFqQy7C@Vd8LFos4X1y5M$+LdP
zpqIVkw!3<J#&@26>4pC+W%xW#<||}GS=2r6<nc$NVl;QjqISdRHTcY@-)ovpf%m`v
zefsR#si-5D3r!RTywPf?YOPAmMwv%Jxv6w{j!?F3+-Nc0A;=&!8cC&)^#i<eW**yC
z^}$k27~U=}5doZH7BEXJU_p5e=vD<zt`An}JUSfzij2UO6)EQJPU-K>897z`;Vble
zm5U4zW`$;kCz9D~Y$vg$a_-Q7$cP~7>rIYcIkIZ6Aqy&M!chTI@Nl)M;%a#UCxb40
zCR~NzWY=S}UBpkR!x)c>;D#ZxvN%`w;LpsXRH$G<0g)xZL8wZ7eoo^bedZjF()qLg
z(3akwoj3gUqD&;Kr;hwvqgqErBHctpWu;l`^w}9%jOM@1jxz8(4~%88P$-zW3+Hj*
zkpnWxx!$Htl;$i<w3>m|QHz1KTF}8<qypO#`z_7~0x&S6kkSfaxsEgE9jqP9LPs7L
zu{H}(Tv##&L<|fZ90XM_Ky;14$#%gBW?6TFZm-tpQAY^x+TkdCx(Ye@+8e&CWElW~
z?Qrf%<|Z<G!)Ezefp9*bV)+$=gZ-(u{=%w8HVqLjKoyTePalGwISN)NV0Ey7|KeT1
z$?^;M)8r2PYR7fh=`P}q@ECf-8uZ)(qJ=VQ%0RI=)T(M-x<KM9Es=PEjjRd7(OvKA
zTC??C3x)E5uzvJUgTS97;WWWjiDzVEe%6bMg$MO_VpPUB3WX95A3B6$v4~=!fM&C)
zj{>w02sdTO*ltR3&J+X5mNBLfY0Kg4I>A}L1W_O*^2}g<ei5Zy65R<7qclw1XmAk(
z+JG1XXBL>>1PdCl)19yu=h5lNz2^ni`kG2wz#A6Olk)P82$lgLIA>fK4lu@;F-e<6
z>5QX>SFhilNavVHrNM^AfUWx>b%dx^1f4kue&RV;N1w;)$y4}v;ZZz#<}kk8e-(Z!
zdjm4nqu5?rz_5;!E5>NF!2B6I|8%Q&T=Ug?-YG`bZsw9#=g&=kv{5Y{P+EITST#eU
zqLZ~|c`^!TAAei{LHkY_01NT!7M^<Qk5H@mXti3{xpOD(yYD^#!0z3<@#67g$PW%8
z<#2^$B49yOHhzN}71#}9QYB?lHe>s2PI)Ofq*CZ2!r600<X84WNFRpB9Yrv#ogpMJ
z6Q`dU2-GaYO83BWlSl@&eAc3?TOmIrGQ7E|L&+x#(3f+?_+k`52DUA1lC>wS^w2Nt
z*}UzY{dv~i)!DgAFoG=@1QdAW!4QK^cR_Ev8Nt?@fMx|Wa}wh4W7ze=qu4of2#=S~
z;15n3{8f4n+zimqTFANrL86P2<EyU<Sz6@M?Cgbe=l&W|_2E_&7MZX^B2yKit}@4M
z%}qt}<;NdVQlGlymPY{G0^olk2EfOczv4I!ve_*4_xIEO{coYGuYMED=MzjeTR^j6
z5JaJ>E>ujdBK#;!7NdZPprx&_`BtWtqjiL=mQXc=a>YY`w*w<17$U?`VVeagP9O`$
zA%g~3suNZ+2hpgb!!~<LP4;=kSZ$<31zQVH&jZH&Au05Gm1O{A7*`3)qNLS2>5BTH
zJ$v5#pZand^K*+37KbI`R4WldFV%3PAa2YM4&=(M2v%(eZhk*7H-)~he-R&<{|6jD
zdl)Y|gIMgGK#)k6>#!y<H$52!jc2N$qsp>MWH|w6c3m1?vl6@siD0U<AWuJbNWWV7
zK+FKnYd%O%PY-O{rrU16os3rSyoQ>dSx}Qx5i?M^?vBpE(G@G!Wt^20Dcc@$6UiQn
zbB9{ZM0I{vE!3)zr6NpW4!T-Gw$Q}>o(yu47dMwM9`~4;wnG>PhG1HP1r1nEGVWcl
z<R;fLD_api=jLT=XU0V5>o5$L=edGq0CY1bH)BP~1X*Ll;@nWT9hHhDi*p9cvX}Gh
z0ARF^J9n_u!J|MjiYsYCpxN0EZ~wayZGQ`To_zwlAG#mKBM0>J^`VEGiLNKB$=noj
zy+!S&YfM;m%~*pOv}_f63vlJsp@&s*>ah843amm1NGY*n#}1r2b;?XlO`BT12Ej#k
z^Oh~wtQudlf9>iudxwSwH}nq-B$LU6uq^9hGbs@?F+@tC83d@;YN#yCV_{|%-_QYa
zg-K-RPhldON1ySQ3s7;xVcQG@E$~DZ!g649nN3^R>PbAW9n`xM2t^%w<_Dv{f3YkB
zptq~bq&k_lnN$-i`Zox{tuPE>TUM-mA;1`0ZoP`nTbNe^0RU-@=3)`j58xXEx$O!h
zx9o)f)vp}$9)0df=A@3nNuHC8R}8V1(T<m32*bLRr_N5PGgAk(@~6M+53uLTt8neL
z*P+#F0U&6N^_^W^@4MyJTi(8Y&Dz!Zjy!|WXf&IsRjW9A;XEpp3YyJ^@qAxtsSJqV
z*cKO-#can#DwDyg4eQX|(+4+`MPYscj~_n*cKm5f6pvtonTKU57$Pv@U{L_(7zo>e
z#hXYAY^X5a8G={xUDDrHfSNIvr!%+=fYFsUF-BxUSY6%uF{Ko=(y)>igy8Ke8!an(
zN%>2&HR7ZxAj1H@?<0ydq#r<sA+*+}63NFhJ^5oIWTzx}F*M{w%0ykZuTH-_uP0AG
zu7hy)pTA)tASJ*#aNF%ahV|<=0sx3;<LKzful~eO{P>+K$Hx;=N)!t7c<RZcIDP6=
zc<R)t;+e@ar9!b-u2!qnR;%UJYBf(vsWeEAb!5l4cVuqVjsxu`VP|vb9h<<uH|@u&
z4I8lQx;MeU>Ux|$aU4gU|0Y&lcmmtlG+d?-X#=K0aLWNBLPD4khwC9N=t7u6YcK<8
z)u1oOBLx@p0NE^5!z0V(>As%cu^<TJZ?FV7W8kb!|CcCzxf#<e)zBF{uZc(*gkcET
zZryHFt25G=7xVo+=j}?p5VlP1mB|@(zIsku<!KWr561lS-4wP>bjvNb<6Ga#nEm_T
ziZyFD!}tB}zP_ISbmNWtKeTquYRB_hc=7Nd96EG3eEOMZW?p{z$mI0&%(UlwCB%~-
ze8eF{gt&AC0GKH*zI3&v)+am+*MbPONa4_-=TLs(35=~-i{6dfv1ZqmSi5dL*oF-_
z^70M%+b8eC_R;~YVizE#2hIgJ=dif!PFie8f*(~@RPD0Ch5?$q3^Ril!@yP(0E0G=
zlV>ImW^=g_A$W?j_(M?}05Ar6iS7~a{3S*p2KcQeq&AQ;g4P;DK&@6iYLba**KsQr
zvfjKmBWKP$tf3=(w@oyIgM)Pa_4}}P?U->~!pc?K5c=UASMJ&UhkLKwGoh5kp@RqU
z_+yXOzxD8eqlaERe8ls-a{vkesvxQ|qN*`y0VXs+&_<mBz#?OOL$vMM-uwqjL4;Zm
zVon-JuLg1KSxg;y5;F(x#Y<cFV#D<}Ve{7Q2-d8{laK7g(HH(6R|T)Ywc;)%!H{y8
z>2;V%k_+C|4c1u#CNDenUjhKlnNfxmDcO4Y<(D7m?;BXLcJ11$<Hm}M^baDC)~^OZ
z`+cP(!YG2$21+RyW1y8XP0xEpI8K=iZ}56OdhyI5^Suz_#*G{4t#5rRf*>${Fo*vB
znv-ycKYGXQZ~C_@R*d4*iIX^R;6QNiefJ)I?)m4Rl~SGoFi(ulF=C6_=(5qKsg3cR
zWZuhlbgNu0i;jFAnOr9rV<<;JU+Lr*)?4KdsALK<vQagJIom>K)<vmaMWH&2#czBL
zj~sdwr>=f0cHMLb-g@&}@zU5TeEGq@#qQd}$kQAcLD(EgM{5xhcp0DufnY9U2B=r7
zn)6i1$TS#3m2<9z5MZ2vSUVF2Tm-=-Ot2(cNkmdY8v_;hWh07Y&GWq}K-3j80q=3u
z{6gWoUWnDJSJV67|2_mkXwFW}fEr%U%9U$BbK7mV+{B6S@I&9kKYZz)sr&E0|Dk%L
z@ghLeoQqiiC8cCdb5R=_nFu#-y~4Wcs;fG-ZeG7;WMX5kw<F>9cDfcZAsItZY+<qT
z!~rk(v;W*kwi@X~)WQT~s3csZJ5p#SH7*1WE_fl%HRdq))lcGU$DYCLZSTY08*W73
zPktB=eYqcFCq9c_oMarF0HGLDMraLw*{MF3WdIZl3%aADM-q{5S=@IMu0!pT=+Xg8
z0I&A=m!7vH10^M*NXGpDCO(oCw3-DIG&MK!001BWNkl<ZsUm=u(K4#E8s@u=h}W-Q
zPj}vVCwxCNVJP9c$<a-lHh%fmTW{W0E|u_&uYX;B>eHWo?8TQ}dI-Q#F2oc-1tp`Z
zo9d`ux9?5j-9Pb;bvN$cziWK7XA^)f#8xW;-~nhZU41FEdam2+Pd#_#0xeufTR{_+
z-$2qRbf!24nTL^t!GfzWEf}Uf;OxoA@xq@UM``L9Zg|K0amRb!i~GKm!s7FvvQyzX
zYmp_Qz=h(8IU{g+_6#orAeBlZlFGP3D5DJo=Qh#B-M?f4$XpW7Tr!q~h#+OuKA0&H
zw`&vpM!h7XphDaVgl);EzWJ2#Jnx^qvEJTZeDtFqHP1f#9GWd3Q521C-@ff1Z@cB@
zt><QEaL+yWH2(6hK6USfxeE_5#*Z_`=A@Jr;iMOT@;&c!-}lo$d&iruz2bJkX?6Qo
zR@zq!7ZvXTXqhE25Npz|Yv(2B6U?&WP9?vEx?>^q8{k0`y*faqQAK|4JTm9c;ndkP
zn0n+M+}HB3|DEr{+u!j{JRlf9`QpR9o@8!dh&9bQl#V<BsLL-BTn2#SxajD}qq0~A
z8M1`1Qp;!T=-cnuf68icf+#k11^{G;pjxeKLrus~c4fQtjVt%#{K4}`A+`K-3=E4{
zL>cAf_c-TJN~2n9z!-FG*s%T!x8CyBtur&z`2630zH;|peDZIq)#^i>i!%Tgr81?R
zd#-K$+OL1)EpNYV|1WWd^#JMsiipSiG!QF#DGCVx$zw!9wAiMd73KR-wu8uVpu7fr
z%K}o__90UaAuNnUAyUN!q)weg>iAJio;iaD?!O;5-Sif`<+iuse(qc|b@uEb6*P-g
z->p}YLOVh2qBDJ&$T9#T8KT~-5(|AsoO3Wva5I3N1gr#%;PKgggSHc>mxnnlNj$7c
zwOj3%&-w*qWTeQbvqz30fB%4a58l&0#~+IW2aoZ`QQKKZTBM<rLN1rX*|XEoT4Qu%
z<o~_>wp({E%+KQsU-&}h&p&zhU({-~uL)t#DkUqzPS5|+UBA-x(ck&V$6Q<7iCED^
z!~j@Q`jVoTlpX>I%_YwPgeD5L2?HptppAkF0}u=-h*^smgC+uJ9DP0ANGB6Wr!(MA
z6331n#RCs~4Y%EXE8cX&b$wsG-~Z{Usk4*yns=@{pMx=-_zrvN4U=U6gbj~maf&jI
zLqvw0XYM9@W*BU6HK=zK)IAK7>H<grOaNTKa0|v^Fzv&dux-G004?KruUrCJLPwEe
zfGKDncl&<`iPzT09O2@_*ZvX`i6pev&|2g4nMvewxsTj>+s*F`d=K~Cdtd95pZw%s
z)oQi-gk_(Xk*o|1k1c%s6aRDPyWes1-H7K+UjR@=toTcJ_|ogwfB>;i5P~3;lxisl
zV%s*plfPnMpp`-<oyNL#Yrz;nMj>8#`4xQafv@2m?|28Ux%$e9;zHq<T^CPx4xBs1
zF0<VaTmk@N9tGwch?D~o0H1lvh!Yj?WFF)s!R<5zPXVbOm}EC}vJ1-1wXY0xx&urD
ze7*?sCCEy^ST;x-p{rFGK~OUKj^oUX(I^&+a9wv90FL8cf8Dj${6<%2C%$^$S8(@V
zeDZG=%jGW#F6Lwul}9Jm7ykBhpSk&}Jv%;)c#hK?V%xq%^FCfn`BD42boWOD$VjRS
z)mpuF(YVE#j!TcB<I?BGKxqxfaWFnU0nhW%Xf$#B_;Gymo8Q76cf1X|cJ0`;SYG^h
z&p!9;FVq_iTy7w^m<fF3airWnL*01;@G!JQ-6S$FOvJW5Yyl<&Z&U$!CeESB_AoEQ
zp?CtmorU}2DPX<~k6CDdL3ea#S^uajp(qL@aiVXV{4vI$P$<B*Z5U&~7)$KickS<Q
z-@eU0bnpdy_OqY8e`;##?-}C@%9!fPbz2L6^O;ZIv1iwo&m-1Y5wG6i|CIJG-SwBg
zjtG#A2&XSp<zy&TuVabj83S4=FwSEKnCQ}BM9ULOwAQd~3!|f>sFW+HR;&1jd%kqI
ztE;2$s;l?)pPici`RAT{=1bF4XCH8!*H$v$NLdB|dnq!VI~UAiLmDzHQkl><F161`
zFc{)6Bw&~TF%EDJBM7iqe4I)XECPrTgi;Wp1XBh=n=WH0DV5}_>prSl)1%)eB^pH$
zzVY=3mKXZpy!U-~-MIfvyBA9(+;`u7XP$cY*}ux>y9()aM{C258|HuWH-2s3o?YXg
zLOgH!pDKTu*3HF~@5ReNVyTIpU}~W`J6qS2Qko27Y;}C3Jf13Y>5Up(97MGo4x9LW
zsWgPJFf=@jN~MN-@4ffMkAM7+!tL94d|>b1Jvejb%<t^nx%*p;u>hBmECXOI0jFgI
z;kC3O?t8AO8t~Y$TlVWOSq_SG{{~ntt8zx*t_>qNEEre>I7;@jQZX;I5o)o{JpG+R
zp(u*8gFQXHE3Ucb>bv@Sd+?R}zJdq8`OVK{b6u02-Gjl#9oJWW;X@x@yKmRXrvT&u
zlyQkiZ!S`N1hcICD4s@u_EZ9B0Ga`)2IlOArk-S+b2JvmV01s@Hi&T;t>fkoCScmb
zr<N>O+$~N^gUX<_fm8~X?V_)L0Q>e`*Zp^Y_qhkZ_{A?C`{|$gnRV;duiJI}*zupV
zEbFf>S;R}o<c;wTmjQ5v1(Y3_y4K17QKYCMb)4pn6F(RK#r6;J2)3nBEJnkEhLuV}
z2@YGU7y!m(6H%}-iqzA_C@};C2Z8_J+UV8S?ECqB*Id(oZgv(AKJ?(jwR-E3{=qT1
za_#QcEqDBs+P8b;cL7Ww_VRrIfibW4<`FCXRl9!~1O|!#YDhCX@0l~i$Yu<IQQ=+!
z5=0D)GnjUzgA1$eyATYhz5m&(l3`lMmy`;Q<KoAD{Ks$Z>h2o5=SyFH_{JM=T(xKS
zZgJ}5sb5k`{T&f`K<xLJcElv*8`C(p41l|vfL$b$=wgbDk)fgmsWmj>>Dz|I%`mYI
zY+vo?#0aDTVKhX_1-ArjsbOotH9!h_Tho{?kt3{;AY=&x)x6{;dU|@OySv*QJ$e+`
zT(1Ad8*hAXHk-wxj~ob&9y@tYPya}3Xl!$^=ek>??*0)vU+}*+G2q^gSfSyi%5OV%
zOG;O55G*U+AXa{$Q7QyD2?m>i2u3AktA0HfR(y1vb7-Z(7+>Z-TJ8|0`17|xU<{yi
zJhWOV1!4?6UHw?MVMF-WfBor~zxvg$zVyKlesKHf=*YIyXC{B#65?+FpjeoP@B1hg
zi#TxL0RAQZ!Jq!gAAeszx9pPM-2xhO#t2f185XueGaD)sX>Ho8r(u?jL7Vpouc9!L
zA<`)qI_bjU3@#(sjF97O7iVTj6WmV0#O_NRY9gY+!9nD5IRL=Qm8;*iXU`SG<x&yP
zJ@@=$8vK=k;nixxmc8NV#Cl0&(kIS&|9id?eH3vPV%eiNShnrb#0(%2lbF)6@-^Zw
zdZhrz6~H)=!x@o|f)z$a`<dWijK_TkQ2@(H#yG$9!-8N8!%{+AYYnB^|B2Ed#*j*<
zp_KJ}I@>k%*kg|$Tr8K(rcIkbz<U8e$_Pp+D5aKne-H%U_x1hCG5}_bF@srSLZKv>
z4kK+!o;0O++r-sBZQ@h1c$Gg8mw|}@(h4a{fMru~Y!0^#f()b43}bsh<iNG8m6rg(
zb;q%0%@(THY5-tebImpH9_a7Ki4!Nx^vt=3yL(5%!O?Zms&(7d+VR{b$EGAP${aoC
z|M_A=eU<=msoghAet>~82GW?=MKxHSL4{gmCIe%9!O3BqI1`Xzqw+QadN_}}pO)-8
zx9v9A<6gk!eyH|vO4CM|)*4F2EWiZ^5zyJc`pLB$c9jdI(&-lt9-LmaawW3a?DfW&
zjZqX{j4a+jc~wyQ`7(^<OAY8iYAV(POfSXc+8F3pF+ki06t9C>p2_Dx!tKg|IW`i4
zA;Ad=B6L~&R+~{z=#o3^fUjzUU}z{ojzd@|EFhUo?cA|_`xSt}iIXSKNX<_64NYKp
zY-2dKVxVj1>eOGaA5Ff8G1A14I9&+-M?KJAX9U~C6dxILk?Kv{x*89iiw!yjz<k7M
znsd@&sO=!s8L#25kmbTpC6W$oTfnj`NEv}~0nWuG{2w0`Gqlta(*{7B`lV7(+Q71H
zG+I&MnT}K2cE72b$#xZ<eg64l$%KR9;UPyUealiu)f+9ZIvl#Y1awHH3Pb_HRO%6(
z4Yj$#ZnJ<g2AVV&Gz_t&O%Q960gMrh3ek~EVIiABLTUI$!qo~LV7tql?Qa<N*)S>m
zn*ymzfKKIX)@;;Op-{x;En9C|zhS*tER`@jd;X<tzPr}lH)eVU#{7}K<ZS>(MthxK
zt_S*fv7ru14Su#1{n^SMn-YT7sEc0ylE<%?BDHn~x4KXciZ7ig+)`Rtyy4i%g_X&q
z=+sh)z6@5Rd%Cf4lw%;t5e5OAY(7>tW6ODgi?ayhK3`)Dq}Gt_KU$%U(YE6@O4X2_
zd2#;T>&G_!kCkgSRnN`No+_0}Zyp~X6Gx98yMb~3-;6P^EQ>M5-mogss~F(FNn@sK
zOB0jOs)godKhlxZ8nSHyw7DcCBm<BJu_b2^AT5y=fauCXBy1!(A;Abq0tOxNe$M!W
z5l$ju!Fs!Gu@#9l9e(*`1Hf9fYSrG}o*v9ym_y48j&*hqqO)gIcXf572D`2O?b~$M
z47&fZBP~`D!3va#rpod!TT;JB1glN=O2_jijUi~x;rpRVKKR7xJ3jg8hd=Yo6Nf&w
zSSpQf-#+r(jz06vE2bYD>YIF?DlZ(weFskC{>RQ@;n*3ZiZc*l3lJ8JlY|i#Ks*Kn
z;xKTj`9-#`Na5^!EBnrf<?ayN<Q5y|=5-r(77eH{Gd(juI5-F)#BSG3b*Iu9xULJ&
z^WL!Z;A`dshy`dnrz2^h8Avl#3(aiC*5i_ENT%b%A;iFpZqMvD7oEZOqmVv2Ix;Ah
z>qrI>0;LgYgB+tZ1D5#U`5^jTk+NknnFZDBIyHA55Z0=7>(;MvYzy-X^EJb)nSAFU
z&vx{oBkK-ll43i6rZ%WsoCeqQ*>{~NM1K$&G(u(6Y)yY*C`)g1I1TGKIb#@ulp1ns
zy0rJ%!_(JR>h=20?PH%?w|4O9WIl7&vEccCcJFWT`bo=G4#-KMpt^A=ScwN&KTe$~
zVh?{1!(BFH{|bctt6@6&VVo35*nrm1(vL?SD;<}^Me<oq_5~@8%w-Y<&yTiFjI4R2
zqqDa<Gdr`eZo~SaOeWJ=sZ`e|+~lK;MpcJl_=Y(GuK_@<03-%=L>bdmjOI$7d8s$4
z#v`pDHHRbv!D4TKVB+2127@v2u_>)2a<+p?cOJ|Ok%}au_8h=|!S9TK;{}7y*i2C9
zwOUcV0Vk6g85kJo2Y_m|I+w|G1esh9bCX&0cG?>_LrQD342+Zpo^8>}@h<BF(^dJ`
z(!h%}%!Q`@T5pnF>v9@k458<%<O?rPzoSs9j;vhO_u1~@EuT##xi1xLEg%~I_=TUv
z(ZlcIxh@z%umr=P8=zmmf`HH9kzfq}nAnK1bF;YO?6=S_z66=c!|xe~>RtieJqDTR
zhLi+F0tyz$$v(k3%fP5mYTc<dsZ73?`ud0cO0`<xj3JlJvQnwE#Z4q0?d|PGUtced
zA3sh(5d6@cg4Y1xcOs+jzJV#9oEB+at@`XxGt@WPTssldu$YEI><6&+Am-Q<AO?eu
zLqZ<;=<P`1Ts4Vg7$TC(&LkhU#9a(jo-^`(KWW)C)?e;LVnugnmm7s4TAp7>W%5xn
z)4^@WVXjSU0B{2n$N2HADL-k`x{;i?^ISvSqXA!OV7_G@@6XV>s2T2f^5EnxnUpB+
z+q>ZtCSgAoNLWFDBpfv5Gta!mJn`WFV`s7uHV5YfBwREFM~)d}q6*&04q`eui-Va>
z_`G==Cd>tF_70=_<l~@Y-$ck=cp?EW(Sw%Vg)ljCQmnt_q%q8@R2n0ta((aEVBaS|
zcB+4HMOZ1Gt|_IE$z%XvSZj?Sj9}Z2dBZb-m&%1Hqxx2cK^WS#mcsF(XO5+9wN)~O
zh%pFaU`)m5VhjT<`2z7orPwKy3TY_h`#Mo=`N&2JT7}T@OunuWNBoA?h8kKuGSRnU
z=zJt6(%B3JK>%$~OK0+M+>CH+E1ge^ek{fH8d6gn?@NuqwP@vFhTk^dGT%@@VB0J>
ze7a1>kDUIA9UBLZu30(sl?YfU2N1+y!9i2LaPWHd)zAG0+jU&qu^|}19UH!F!Q}u`
zAtKuWF@q7RW7vNj7pyKk%huxl{O!mDB}~Xu=<v^if)b+gQAE{6SUdjB{UVWS%wH(2
zfAN)>f7jiSInvdUIUOmad-{h}rFgm#MUhOUlLEj15g`mCFlO*ZMT6fK056}185xPf
zkVMTGK3{0ziN2KHYH<ZiaY)kOq`_#31<;<(tYbhh0GwcCfSz;`t^O{kNFk#XOdvr<
zgBj`_<NP;+$p4=goaA&ao4dlYErd}B&Mn_gW-QB2NFi7z;jj*45Eu<<5c{Ku8>}QW
zLWk2xUy|NZmh|xXx$3ItpE>edy@S199vB<?h5|-f5dv@sFi82#(>Ln}|KaCtAySrO
zgENA#1wzLH5y6Fu|FQ_T0Wyf%;O;{ix9BG@<8|PayB3G7J)rD02x>K?k|j{8q=mJ0
zOa1v%n~R0Ymd<?osfp3P&$L=Ht+hcqog>Fd22x7nI4%J60kI3^`{5h*XG^~=0RG-L
z<}Y@T(jBr%nilI3J5=)Y>4Z=#L#`kU12+tuR6M5LP@EJc12D7n7klEDp@-q_G$w-(
zu2RSv4~P_)(GZ~SttR;Q^?K>ar``0Z0U?ScIA_X9BrRdtk`WxnD5>M=aZA}eWlTJY
zrd_LwY(bqlt#7>lg)=t}4E8*8<=(Yl@+4TOFl#Kd;Dwp!kq6$6Lr>gp*%r6#1OyQ*
ziz9MuC?aH7Ji(l}4KTz>FVfItAR(Y2(W9%#2Tx+PejXQsUd-wq)Qyd(Z~G)=233w^
zWu$+_$5To7wC|~;F@|YljN>LnE}K(IDNk^2VL2HV=M#4B+6^h?4?QvT9mm8ybQbEG
ztPUb>%EsuK3r+TDr>j<SrXYxelLB9!%in%%S4Sw02f-MFRtA;~uwt+iQ&Pe)2Dz3G
z9%*<+!__LaCaAsncx_R7z7H8m5HVj^woQy{0D=Hp8zT+OQj#Zj^bO2XX-a8?Gv`Xz
z?^xSy4UZ3fD=<hJ4y}MlojkS0JpJH1X#U(PE1iyyx)C5O4ryCZL`abVbO=~Bz}gv4
zYR?C3|5Jt#5l2J{WI}X@XOZ!bp{^3O#5H^VoOKONOFy!FKeBvZW|s;`Fvi%n&6BAV
zk6Q{ZZKE>~LSWy%>weI>{<iWR0q{f_Si2y@OutoUghDOEQwuG#*X43;$QT3>I2eex
zO@UD$)^3<ssu;q6A#SR0b%4>4UQ7e97Ana5AuOq&VZgK|<+ZGOy$;#ki71jIjQBx-
zk^cYM`|=>Ws{73EoO8FgFWv9;-fF3(ZY?cj)__4Qwz0>?iH%Zr#xpRfNis<$c*9@<
zQ*kQ9P9}Dev6IS_Lj~IbLA)RgCdLMAj96r}parzITIxmJ>izA@-Of4l$GNY&A;xAA
zo2S33r}w(L``*_5eP{bE-%mgn6227RLIj3iC`MB(pp^1Lx!yUGueGmV+xo+3gmy3o
z(c0u0&3}I9W(*&{KqEra5(zLyzzD!J4Zg0yCqR@yHIkzGl94YViHZg)<8yFH;1dBK
z6dt8;n1-qVwEnA}*0Q|?w^q-3o|3|U$&@ZNjWNqIbxqTlr=;#*G}LYTtw|eySptkm
zDL<AX;@!<&O&a<fxEwoEAwNl(VkM*8U_=QfQA$*aGzcVkps^Qt%&0)4gj#SPAqw<#
zWiZAV_;d~l*9YeuQA!|f8~I!gWK|CgL%Ym0L=z|W0m1cCjw|XRlkvc>-|+1V076pA
zeE?Il<+ZKNk+Be@TR%CxQA~~ZXlKSc<m@D6kq8*0U_^N<sjk6cN)%F!d>@jjk>5Dc
z0Ez&MqhBeAaKhn%!WR^t6p+czX=}rKb_w5)ODS3Kn~RCDQi4)QjS*^DmZ@pFY1eH)
zMKIrT{8Fjd`|?tJZ3FSpN=g8os`>J{iHh80Y5rzP2^b-ugs5;ZRlUC!8Z=O*j)V;o
z5CX|LEa_lXXBrchj?zp4&7Oy}kTA;*3i%u~O$Vct85$WNdTjv2FITEz9x@}63u#CY
z2L!eRYzc&6*NIcDg(_9ADK$T3)`tt%idxMil7ndsh{eHzFfL;hQqy1)K%)c}QGE)*
zbVv#i5=1&0?~oAS;8G}eFJbUFhc7ui;=_Z4HSqo?XgKBhc0B?tMx7RX&;rmHk-Elc
zC}c({qqI`30tC}<f_;A_ex+9M&?NYVj9;%1eb$h2Y`R7sOBiBJEA?9!_5cl6KqD?d
z0w42BNB|H>F2MXcRy0RYh*~J-%8&wxSs|3Gb?CZ|P{@L=F%ZLm=hIl-cHnsiJYS@O
z1Qqpc2_Y;uL&~`_LS_P%Q;I`KFw0a0EOh~97>Wpt!J`C{5SUa#mqJOtu!a)YqTvyw
zf(UR3NmYP>a^>xl96sgn1c%mr-t$(^xkJ9^CZr@p2)QuoRf@b?2Mmo!LnkC;nMo-@
zOQjMBAyaRdRbK^uB?0~^C*{AKLp-C&DG6AUoa4x784rgvemy`8+EB^Rh&l?A;G#qZ
zB%pwxAVh!!29TUU_%@P;j(B?#RZB<ASczJ_4$3H!i8w4%2eV96>Jp9{h)*sQoiwys
z2#8_9(^VHSP168IRW}eR0bPe65%?^~<tKniB#2aoC3^6mBtanyY3wSLr&CA<j$rh2
zrkoH`z?BYUtUVuIf8{PI5s^Z$1;YoeZ)A`m1V~sWlez|KS!UX{9TbZtP)c993dS3V
zS0opI{}J%_UC3==`t!PEV-=6?7%ib|4dw5r#9v61Buf7gpa2UzLW%_H`wg*0KrOf6
z9(1>cw*CS1cU_9(gD2oPE}GJ55RF2&bhv_`<_P$HLy1In36X>Z`Fa#oXVAF>(HI~Z
zBs2&q;BpSBX@TJZ8dQVJhPNsRVK+W6j(%16!h_hd+V~0hP*XqGbU!rkzNcw8<@=5u
zUFdZr7md%kdTERx9MXhFJu_rkskvMpwOWl6LJpoyL%vqLA_6?(OZnF+;*$ZVN?}fG
zltkxkJQAvimL8LBV$1?z6ohFYjDZlQdjEhy%3zL=L`kjjpoJS$2N4hfoOd}AGz)WN
z1aouq=;~_6+*}@p4roN8Qgu;xIZQ)?Y*ZvcMdJ{p`v^k8HB(hAK?0J4=^Ch1@~)5q
z0t^dvu8mP2d`2++3n_wkl}*A0hfgGY2zZjiClto&3!c-OyXUy;#v2BgLPBu$;ylO^
z<Pu?%A{t_xpq?^KGd(eJ2EOml>bid9?3(hm;T3lb`CoY{zOae7nXF&%eRi5i5+1M7
z2XxJiuL#FivQQL^5>TcE@pB4L1`P~&5ebM|dnG`)fXuXmUhp0yjt;>zO^l3=Vr_pP
z@~nh#*n}-8iX|77st-e>;Egm~0FV+sD5$Q1NeU1n@G?pe;e+d38FL|*Z!wE$F|$=2
z`<5oY3b8o)xlrd%9|FGbLhD?A%<Nb<%6%^`gdl3FSMg`n<U)W837;z=t!P+7G^}wZ
zM8*fgV`F0g$WEy0rMDcfs%Ox#gW&7daeE@==QQ0I5uoO1g?x|A7Or2>lWb?9sM-cF
zrfLTW0SE&FMWZ<j0Z~K{1aRu`He3SI)P{6&7KwNq6BB3PxGr>!0^CK!ilI`IC{_g$
z@kKp<bxBQ0wMhvd43g<UFnS>w#FC_yg+}8GX??+Z-|#3AvG7@lAOU8<s2p6lU~Ro4
zM#uUgA$Ux1L4?4<NLN`w!O!~w+*8wkJgOmL5$@H|p3fICIXMN!=%Z)LfUg&?iU9Ws
zDSy9-`2A_G3Tn-OKo?ZgM=R8#r^i3h-P@O?iDnRR5XK-0g``xyLphG9^0cVuZ&~1L
zFNCJ+XiBG%NF*>lJ&RMrBUshbjk;Y%IFW>@GnA`7Dm5P=iv=DaHT@Hbpn!wIrzQx5
zlH!m8f@wiNVJIgR)NUVG82iD$i!*@AA5+E`QW@44E@*S-xYn}zloT=|d_fw9S4LOH
z7hHh*GU$mUkc{a_#SN)5Zg5JnCx(Vluh%QOu0L{i%=h~7s{00hV_wQ{XNh0zt5@t$
zbW%#fJgU)CRVw(&lOJ2P*6L)L4tNOG>R=|2Adr-THRb^>fN%<;b1j%q)xgco%{X&r
z5{C~R#`<;rD3xYlXdKaqhH{N#Ht(W68(LVqN#iI-HAtz!XL=Bm2;8kw1V=n9rmiiS
z`qihUGIugaB2+F%!6kfd1BvD-t$D?`6e7yGAbiOt??o?P!uJI{kAqQybWB4!u5*Z5
zrc$kkjvhM>Lg-@vMqaPs&K6!%=g?2gNb&FhaSukTCC$?&m=17eV8kW9d+g{()=2av
zd)7A!s1{W=8^VkrV4e%PauY~2rP9cv5wx^q(bSa2@W>d($0v|ZCE?TxNJO(JRyYb}
zAJMRnP>2B{s7w-Sh7pp$Cwe1WD=@22j;bK5R}o-|x(OD4R{53%Bn{k*g2VS+iFo_8
z7H^&vLPYqIk*`L-8u`Ab4Db5_p07?U>9~$`%0x6o;Mk&N@Wcts%*=o>cF*fI+S$Zw
z?j3y1At~&uiF<;2MMG**N>6}<{WCILbB><);2PV$uw~#9Ld`II;R6jH0HLbgqrpKs
z`oS0jqz|g=Xl-pniji2z00EO2Z07(Nd`Uz>R5~?+nb}$F+_eWE`|WFy%jb|uWRZ;N
zsMLH+&pT+#hJrjzp+q+bg8+p~G%zfVc!|I@u`vB(aV9{6Bn<)tCkrXTeILFAC-K%<
zYDLR}%dp@AFPip!u`uEnjPFT!j(}-UWKssQDN{<}MvH|~bl<)M0I-7)@`Km<%-;yS
zuI}N#{Szr3`~Y=NnY1W<CUhx$Ksq@iQ$093H(M?~a^=eNFN;Ll`@khvBa9F*DIpCD
zdS(R(1VGj1u(`Pjt!-_{<#RYSJc^-Hr_kNmj(T|xP03c2t3GD(F6Q$Nl5rg%1XQSv
zrjP`lR4r(L#&oYnKMfobWQp+?GcX#$myP^>AA%SziKdERhTy)4NhucE-f{6#<EyVd
zPr!AQPC|3iK(@(5G(?D9cT)#mIEcx~N$9%vHFfTN``~pE002Jvs1Sej0qXU~XxaBH
zp%du};@cH7T{}`Eb3;2%e&qaBv&qg)mw?8z5Zs029<*c!gb@J~fyO8SLZL9ay1Fnm
zHHAW<h^L-<2G?Kr2{?8I(YT9jlZBeiF_(7%LJ$ryb)p~yf)Kbq0b{|4r-7hzkjA~}
zs$R;1rI6r)OHj*&VLC#>kRG>0;N9a~m468?7mV(E628Zk@m*CIl1}JoZ8DKfn^JJw
z7@s&}?B25ngpi;4KEMB$JxduBn7kB(5O|&k*LBZ&zQF4y007+as1P6DNWBX>wF(g8
zl1f+j+@Z{}hmB3yvEkCim!G~HJ?CDQYT9rKm~H{7cBL-EeUKokNC?o{+JcUbc2p{5
z44ycNr=H${tKWMSiup-oGCio<CTvGwX5K+MX}~n-g25dSu*NY{s%m8d5=1N!kY&*w
zu<$S&Zd|5GfH28rSPDr*Aaf&@Z2AOOqu%!gd{1ro97n)&IN}ivZ5b2onGkg9BbP6+
zC!c&8#X^yfkDvaM=Xvs_MwU`_JZa<##-dU6{ly(CT-U{h4I8jw{d%}T1+{Dh!-G`)
z*NU@3006k}kQC?Sr@iKl5pmjU=NwW9rb`p2esrek{VR9Z%EOb-?#gx^KeV>zoQon&
zSFV9Zsp`@N2_Xn5l`u>b9UYyRot;HTdkqH<9z<7XC)TW9g<5$Qo!J(6zQpM%8}oSw
ziI@SyU_rN0fQkk80~k}G0YVW(EgP+7v9KXrfGYc<QVObS$byJoW8D`rXmq_u0MFxa
z9Rb(nh=v&2GbTDRVZ_1&wOSoJpWTg9r-m^!H26=ucI|vZa1O&Tkw_#KR8TC-#I@IM
z0igtI*RI3Bh7GVC8;mkgLcs-x=X*#cQ%EEes`wO2vR?=h#2jAxs&du{005y0Dci~;
z{!^Elc0~5%g%@K~2u{mmKOK!-b|qu-;j-_)aAxP84eg@2uj`6fGLufgvP@8>Y7C^1
z$Ye6;=<GzLQbna&#bZDHDN^Z=A)QPBei19$5|9#@n6XhPxrl@{MFNck?OdSByBUFG
zDpcK=VHODRAEwgANuUwOUv%>DAh5G^?N`%2hvy1JLkt~R3tg=tG$j~Zr-uCpUcl4O
z?7-OQ=(A65f8tBFZNoGS-2Rt;iOrig!*LvNuG-dicC<qR@O>XrNQA;6P|Cn4T__->
zl%ig%Lr8H}3Bdm1FaF|nn0yhp-+nt7fSr!S(@sUUw{DarHzaHt19ywVo}THbnmy<0
zyzrz<bsQ@ReSBtSx-c`Br`2jLEQHWh6G}ig4OpfDyIzOy`>2#F7#tizUw<D61VSc7
zA|3@G;d&C4svmg&)GQzb7N+&!<3f~9EHP}OreC~tlnZ5K&egi^`vTlkM?B9H@LU1M
z=HOf+8Pm|&5<+)t2+c_yu2aL&ql38r{s-XL4o(go|NDBa_C$C03jE)%e;u1IzZ|-z
zArgro910_3S@1j;w&Or>4nhdHSQODwRY!h6VpWmcP@R=>G4Z6OrR6o*?W_`D2*61I
z^^!n~*(rH<v-It_tV8Fh%{=dG@klAu_a4E$)0BD#1R-NJ+Zmgkn>{l%IpxgE%*G1E
zl36KN7Yt+9ZD_g{oD4?LySf*YC=w(SQ59{LK()@{x@wcwaO^A%%L;+TfKBlAQUa&|
zPT<aMxOF{s#`ip_)_YgNbvRs?gA#&F(m-d6g|3#s_--A?kDtJO+rAIZIo7RTho+{c
zi+s=Bo5^N|FTdgnghEOLOG>#gx*Mr<gph@v41@$pG*ShqD5Y-*0nX|Y(13uz_M=aV
zi{k&&OJoyON0f*sb)nCVe9Li4d!6K}ExDQ)NQ=szgyS9xo9=L}Zch@8#X)JTSSo^2
z2F`s{YgJ54oZ;ni3AtR3KJdT~$Zvl5LtvD_v^Z9FBoVe4B6Buo3m&RA5A=FS(C2`F
zF#^g+@PMI?kH26u-I(?l-WN81!G<qrEguarG^Y%-q)oIoTZmW$^?D8a_aDIbANT=Q
ztmwv-S6qQZM~))hoJp_SFmT_{;Nb7LuAAeWn~bq%vD6*;7UB&d004My9lQ2C!dGAO
z2{+AR72S6^7h2S>)%H2g(WCW9(?z97^Hrg`ae2gW=1q+YM>p(l%c{l0!ZUTIgNChU
zYS8EQ?w#JVdsju*jcBc2Z*srynpeN?J?QOS1tI3qo=G7V(GiQ-m@Bv_ls(w4a?CJB
zpfLibsnY^ovJZICad64{zjRh;Z2SNqWHO}U8k!RZGHDY{Ndp??D3wZh^2w+0&<}rv
z)|M8$|LUvJ+q()Nz_U9`=<exBUGw1&-G9-A7h3s3LC@#&|Hm+lTcI=!-cr0_1ONcv
zK7tbm@AWrc{D-o|^+c&oeVtk%jl0|}=ALkC`5mqqS!G8O10hRmbG@0}rTp~%WXNZ_
zPNRUCD7dMfqU`d_=*UcQeyVcx=rPapWYTur_=OjoM=rYHJU|LW!cna5iXfdZFkf(x
zFZ(E0Jk(qP#}R-dKp9!^48C+D_@a%U1SD6-ER7Mw!W!aH4XK!hri6)f!a&#}@O>BK
z<I{NJiS5|)++IviO^$bUw9Qtk)pN(jPGfa%FF+_}rl--_*%1>$qG!blSf=&4GgFgm
zG{$}(s-MAIhBuS|0Kf;2;n?ZBIp6##8ET#4Aztx3n>rlS6t3XhuMJ9B9X7ZgC4{A1
zO5+6=5h;b`)IBR#8A;at`08l;`OVUt_RGcD+`eOT&eTjUR;!lIpO`okx#W`HKzCOM
zOw&PgJc4vQic*!MP<BzOc&OAl>Nbbt1xGlphWpYvScMDJ5@9k5(_#o)6wxq4EUF_B
z)sT$p2w4<T_$U<0ICSU;cKrP3n4O)&<mBZ3r=HsWPd|C=5uY)3!+WoO|3#Ei#G?`H
zeeN{&?ca}hJdXEXbtU@y`(Rn-Z;p(PJq{_aV~oA<M%&@#K+cv*#V_|z^#JsDV0QkD
zwDg=uJ6hr_3|;eWqB9|NJxcUw*wEu)O;1LlMM8{8BK2C?iR6k^D_5!-m8z%bW+!XI
zLkB9A!gN}2FV@|?;+)GiU-6&2SFGq=+qVYqde<hjwqy|sg`gV-B+=n`1l78aYRyO8
z;c#35H*nz!5d?;a@)Ky9>W^p{6qdyhu^1v@4Plc)*9fHWQLa>Q>eL8!?S2l!!y~9x
zEB5~Vd+*=1Yv(@;&gTKFGEKAfPj9{L4>oVU{Nl;UNzCWwA%s9fg7(sPUxLdwUk2N@
zF?eDqFF5}nl(G8>0W_w83;v>GpwE41ng)$&FMA9;=bVkN$!>4>44^;&;lLT&Bge)L
z^2yAlqUYS-=2`8y=b2#|ry6mpgw;%tFfkD)6dr+QySC-H(&Vm$&)xc5X{ubBA145^
z0J_J<M!jwKeRt&C^Uizk{M_7!hE5H~dsp^g{rYuiZ*N638ilDF2q$%9k`{cfj)`6n
zvll`v5`YqDjH(8i8dSk3Bao8A_Z&=57ce|Lf)@@R!r0gts?|EiMo0Gi{Ml#jotd6~
z48REh1^~@*9Dd~R;peZo;);tc%Y<Q=s8%ZwLZDbG;og7yHVz#+g#UK^b=WwtAvJj7
z#C^qL>CeNV(3jpEdo1EjBEVAE@McfRp(l>>llr%LQ(qe`JJ+CGj1cd<d7PWkkg};f
zGhZcTN3T2iqUPEjCMsorV&aqsRS+@`rTgFMx=wx9&S$qBKX!D_rgxop)zswV=Hr7W
z64`79Ju6nAySo$3&CQ5LqX=0hOvYeoK{6@TK!Xr9=Un9)3l1(gYBd|hVhPjJGZ-Eo
z!N|xc=5smJ>vcIXF@9j*-sc_~9UXZ}N_iB(bntiiP$yv$i$!TmOABn<4wS$=)ay2?
zl?vwO=J5URKY+uBkKm@y-H86aJ~BK!^2OP?x!!0b@)-hBdb6zYCM^Lg0el3&*Iwr9
z8v#55XeXfQ8Z^P-B8=u$7ZR&H#JD&Yl`3Sh_+yS2cispAXboOz0O43H*1Bd*|AlMT
z^j+B0oLQYn#I-~sfmAAqrluw&6A8p(QCOA<T{l1pg^&WC=b~;qsFX{{<qDXe&tX27
zL%Cc=-L_FFmuAPt#`YgScJ%4-@zZ;ylqUg9K#5bo6n)`v_{y(-^{c;o$)%URd-BXA
zN~JPR4G&{vWCXLbvv6Gp^;#X_a2Pj!_A|KRipw!IHI0dhi5-S%{1?WwF&4Oje+`y^
zUj+%k27DjBABf2t5;L=N5_2QI8t@tcoTYgjfRcb80gwZb0gx$|%jJFho*O%GVBb$$
zT3Wl?J37~Qbabprr<;00p-|d1E!{A5=(<t>Yji^4oWt`xc)kzMb%kx$tF>Bv^325e
z(8R>Vp^=f{!=C4kLn)F^K}poU-01OYwc5;Wx7~L4zub9eeBIi01Jg6J@O=;S^YaVs
z?g;_r=X3btU;Q=4#>Q~{_17U14qrNWa_A`o<ad}(cfB#sdl7FF0{mhuTDzh2x{%Gk
z^ubH04BHZb8K{{cC4`7gPM(>aoIG=2-(C{cG%cP?rBcn!nHI~m(we442_+U5v~MA~
z&r7c7mP)14%+%zWGrsQ^IOn<G`gtf(>LPx%6K5L0NG_KnpS$tKJMX&t?wc~1OqUQG
zD_5>WwOR!r5e`R?NF*^cGlOq`_j||{iujX1{zGisuwliqW5*wL9Ow6RUH|@Bd6+MQ
zw>1HN0e;zomrx`q0XPF73Lp+3CZ!B{o@dR@%owvXGYm`0LYDllz+ywGhU$3ZdJRqD
zSBe_cUO*ci9VMUn^k?q4^Ugazn{G-suk==+P$*(#WCT*mU`dK0lgVJ$uAL~AiulwG
ze}aLH1Bs(Yj()dRuitDK`aisid%r5Yy}B2iJ-ATI!U%vP01g2-7`zSxI1aUIA6)V}
z7JRSqb1y&{aTc%6_zjc+3;~#U{`mt(Z@u-_Z)l9wnwrvBx3(WmO=(oCRk*%~csz!#
zu1>7&UyIXYr}34){d<g`9><0a>$PYk^0iv6{&#PbaKx`G0hWS8jmSLI)I1Jg7+8p1
zodj?Sz!+4!nH<!{?v*w*{beWw_nChD@t^Mbt1o@&u2eE5v)K$bZXAFW3ZYyo!M1If
zripAei@yFo)NLDI`^SI8;Uh=T-`|I9Hgi*@Qr#*cO@gyag#RB1@K$3UiUf1t`ObHq
z+`9Gd2U=TO(cadEjROOa637<{s8(yxG=`>h6M9$oA`}keU+(-ScJ11Yl|4OZZ)?4-
zSS&ptrA(bo4!qO$0Pj>xLp^K#_S<iNu&Jpjea$r=zLIke$FXtb$WavXdFZ;1R5FQV
zA^}s^F*QAnZ-4iDD3!{%`s(+BY1#)*pB}$I7L8s{Kqk({AGS<@HxE+)OaR&!zVL;6
zJ3G758#Zh>hx<Mp$HnmQFtmIgnx-L@OduXlK-UczhJhdb_z_fVReba#zXeUxt{Ofy
z{BR^1`7J`o*z0Xayu1XwdEij{kC9@rIQ7}je&)`Znd#GQ?d|CATZ68yE>tTO<nwuy
z%N0lf@pufK9i8ax>cr2sZ^!rU+lJ<*CahkwdXr;24+$Z<U+*8aOn^5RE`U)0r^m*|
z#y<JUPk!BVo%y!5HmqCMkJh#}RH_x^iv?6FWdJ}t9!FPa2iEki#_rvFaM#^i5s$^N
zX3gqNwiA%xb?gb23Gn8l4t467c>ek4kKK6VjbFD+quSEag8u$KWSW~%tyEDc6i}{I
zK?qSK=;}mY-x?e~d<6e`*H(l=A@uk4ZL%HvA;Dk!Ot4IVw+3aX<LA`&?c1OKvp@T@
zZ={kbuQi)R|C%*OCK4!>$|w}_s8q@eB<Sqy#K6D+hDU~R_dWL_5(;DO+O?Z($9ZVq
zzWuL>1j__?>ySs_BiOcW+m5e%`ETyZWHKU?&0_WHUPPl26bnV<aye8gD&7>2$I;Qz
zj*SBY7#khK)_d<oG!n-8b?Y|Sj{VTyefwTD36=@))?yZFCYZb9jyoRz<~P5wt*xyU
z*-Qq#y}by9L&)a~n46zRrBZ>E5|Ky*t*xyX7}$WZ)2DIIzkLVMXas$0)@&-3$`3ua
z_tlYLnE-D+rl8!?b6@=87azQ5>pc&4cXuP(+>DhyD`8m{^7(np&CR1+F29%r8#Z8k
zd>r4~c0Zb%o3U<f|E6-e{DWP)_q4y#n=cdKt%raLUY!Im|L1@Hg$K56yYI0TD^?(r
zX-4;oZkVQpx%nJs=jKo<m6Y~SG=lba<xM<&`ZWIi;fK-M+KRPn``=Y6mAC%<*`3K(
za`R<J(AxtXDi*<n5cH;-ZoWqXWXqN<SIa;KXJT>^x%nIzrC^L9olYYfjY8LTFvf7~
z*fBheAK{v7J_O(Q-}C(Q2k+bQ?9Pu}ddbCwUv}eV0=#{|p?m~X2u^Ok`KGN>N^H4S
zkpKjknw~~JUjStqD5c0WHz68{prfM$nx^5{v19o0Bah;P|LFs;>-F~?J3jbtJAVG`
zmP_A#$;(DFmkIFpf(I3;B!UZi%gs0611WLsmMvEUD(!A=ZVrV)9-2m>YZ{s}8N^~r
z0$<ZK96LUUXP()C%PzYV68PZY;Lx2rckcSVi!c6-Unow!On|o^JOncV7eapi^S9h1
zC2;MQYlE49AeYOjnILF!o5^GlkH(-e4UAD7I&uVrQe67(OW->0e;pYal?Ynaz7)#@
zczeQznh78Tm$%&V`K^G&M?b1aKnOvxP(VJHS4P(uvY9Mm@t7*J2f@LEhhUl}E;#=@
z2q~|7=-+=h{ae5J;hSH2qh$iTeX)cD0=N9>En9_@xc1sDSC5X401_yb%gE<*K>;j7
zYqkZ+L;{pD2r02||9%*{j&si02+wtI`r*SrazA{{hyK^nn=BLH?F}0$ZomZ>xb;tO
z-3kd@yJgGOqoboBl%QU#qfjV8V;Xc#M_XH~65A$#;2h8F*a6)zaQ^w{Vb61WZ~M`Y
zAI*K}gCF?2#toMJ0B?UdP&2_vA^6;Fx81sR>(;w}(9zzGcr=D^Bm~nkQLa>w%jHoh
z7C{J*&1A4@)hhJ%_G0_??KpYz6fV5rd?XU_zkT$vpZsp);>!ehXP|L9IKere`ODjH
z|L(W`^;`FKc6J~Zjlnbwn5Kzhsf5|tIplJA00b>9Dz4Dc(TPVMdkmA4lX&+f7sIlw
ze}3e#pIiYf6X2bM#_8ZBfcdX{`O6P}^IPAzud|~A(P&I*B2t2UK98yCDa_8z0#c%_
ztqp6}_M;`6#e+ZicjOBNocpd#Rz8>iIIz42c&DL30s#PD`SMpDEEY=D8*aGaIzow7
zDwRPgP$(1^bdj>zEZSOI;5utjtL?|(Lr1WA^QCY-cMMo2z&jC3Ng(dH<DY+Q+jZ~r
zx7_mIDIr>+Pz2F6l*?rxXn@h&)P&Zy77V!SK^eufJ9j=cF){H~V3`2#RB!;Np(>hs
z@4D-*$E($<f9tKc{Vt^>oXZyg5L7BPNI3(}IZ~+<R`vGcg%@6!{Da^Bz0VB}4!XcH
z0p7`IB$)~Ta@)3TkC)5k`d|O=zxiWIXn1Zu2SB1$17>F=48uS!moI+)=9_LD930%+
zxXAJ*@STkY2?hboKKkgR&wl39pZ*6zNG{uwh3ENjT^FDP`}ZH1{P@Q|cEj%7yT7;e
z0?Pz==R-o}6AS{Fdghs@_k8-(pZbS-tvcDWvImA~V*3+M9RBpDK6%5z7hd>|e2E~$
z@)Gdt0V$=NB7_J4V&A@f<d6R75C8r>SG{-h#Kc75XFq%VF59-Bky8GLddFn~{2D<@
zIYS8H0Q{3fC;gK{Cyya;AW12Ip(f!n0e;OOrJN^(_)t~O4uCViXyi9=)--~a@y^8m
Y1F4`rfN3>^-~a#s07*qoM6N<$f@plx0{{R3
new file mode 100644
--- /dev/null
+++ b/libgui/src/icons/icons_license
@@ -0,0 +1,323 @@
+Icons license for: chat.png help_index.png terminal.png
+jabber_protocol.png
+
+by http://www.everaldo.com/ on 17.07.2011:
+
+The Crystal Project are released under LGPL. GNU General Public License.
+
+This License Agreement applies to any software library or other program
+which contains a notice placed by the copyright holder or other
+authorized party saying it may be distributed under the terms of this
+Lesser General Public License (also called "this License"). Each
+licensee is addressed as "you".
+
+A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+The "Library", below, refers to any such software library or work which
+has been distributed under these terms. A "work based on the Library"
+means either the Library or any derivative work under copyright law:
+that is to say, a work containing the Library or a portion of it, either
+verbatim or with modifications and/or translated straightforwardly into
+another language. (Hereinafter, translation is included without
+limitation in the term "modification".)
+
+"Source code" for a work means the preferred form of the work for making
+modifications to it. For a library, complete source code means all the
+source code for all modules it contains, plus any associated interface
+definition files, plus the scripts used to control compilation and
+installation of the library.
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of running
+a program using the Library is not restricted, and output from such a
+program is covered only if its contents constitute a work based on the
+Library (independent of the use of the Library in a tool for writing
+it). Whether that is true depends on what the Library does and what the
+program that uses the Library does.
+
+You may copy and distribute verbatim copies of the Library's complete
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the notices
+that refer to this License and to the absence of any warranty; and
+distribute a copy of this License along with the Library.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+You may modify your copy or copies of the Library or any portion of it,
+thus forming a work based on the Library, and copy and distribute such
+modifications or work under the terms of Section 1 above, provided that
+you also meet all of these conditions:
+
+The modified work must itself be a software library. You must cause the
+files modified to carry prominent notices stating that you changed the
+files and the date of any change. You must cause the whole of the work
+to be licensed at no charge to all third parties under the terms of this
+License. If a facility in the modified Library refers to a function or a
+table of data to be supplied by an application program that uses the
+facility, other than as an argument passed when the facility is invoked,
+then you must make a good faith effort to ensure that, in the event an
+application does not supply such function or table, the facility still
+operates, and performs whatever part of its purpose remains meaningful.
+(For example, a function in a library to compute square roots has a
+purpose that is entirely well-defined independent of the application.
+Therefore, Subsection 2d requires that any application-supplied function
+or table used by this function must be optional: if the application does
+not supply it, the square root function must still compute square
+roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library, and
+can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based on
+the Library, the distribution of the whole must be on the terms of this
+License, whose permissions for other licensees extend to the entire
+whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of a
+storage or distribution medium does not bring the other work under the
+scope of this License.
+
+You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so that
+they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in these
+notices.
+
+Once this change is made in a given copy, it is irreversible for that
+copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+This option is useful when you wish to copy part of the code of the
+Library into a program that is not a library.
+
+You may copy and distribute the Library (or a portion or derivative of
+it, under Section 2) in object code or executable form under the terms
+of Sections 1 and 2 above provided that you accompany it with the
+complete corresponding machine-readable source code, which must be
+distributed under the terms of Sections 1 and 2 above on a medium
+customarily used for software interchange.
+
+If distribution of object code is made by offering access to copy from a
+designated place, then offering equivalent access to copy the source
+code from the same place satisfies the requirement to distribute the
+source code, even though third parties are not compelled to copy the
+source along with the object code.
+
+A program that contains no derivative of any portion of the Library, but
+is designed to work with the Library by being compiled or linked with
+it, is called a "work that uses the Library". Such a work, in isolation,
+is not a derivative work of the Library, and therefore falls outside the
+scope of this License.
+
+However, linking a "work that uses the Library" with the Library creates
+an executable that is a derivative of the Library (because it contains
+portions of the Library), rather than a "work that uses the library".
+The executable is therefore covered by this License. Section 6 states
+terms for distribution of such executables. When a "work that uses the
+Library" uses material from a header file that is part of the Library,
+the object code for the work may be a derivative work of the Library
+even though the source code is not. Whether this is true is especially
+significant if the work can be linked without the Library, or if the
+work is itself a library. The threshold for this to be true is not
+precisely defined by law.
+
+If such an object file uses only numerical parameters, data structure
+layouts and accessors, and small macros and small inline functions (ten
+lines or less in length), then the use of the object file is
+unrestricted, regardless of whether it is legally a derivative work.
+(Executables containing this object code plus portions of the Library
+will still fall under Section 6.)
+
+Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6, whether
+or not they are linked directly with the Library itself.
+
+As an exception to the Sections above, you may also combine or link a
+"work that uses the Library" with the Library to produce a work
+containing portions of the Library, and distribute that work under terms
+of your choice, provided that the terms permit modification of the work
+for the customer's own use and reverse engineering for debugging such
+modifications.
+
+You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work during
+execution displays copyright notices, you must include the copyright
+notice for the Library among them, as well as a reference directing the
+user to the copy of this License. Also, you must do one of these things:
+
+Accompany the work with the complete corresponding machine-readable
+source code for the Library including whatever changes were used in the
+work (which must be distributed under Sections 1 and 2 above); and, if
+the work is an executable linked with the Library, with the complete
+machine-readable "work that uses the Library", as object code and/or
+source code, so that the user can modify the Library and then relink to
+produce a modified executable containing the modified Library. (It is
+understood that the user who changes the contents of definitions files
+in the Library will not necessarily be able to recompile the application
+to use the modified definitions.) . Use a suitable shared library
+mechanism for linking with the Library. A suitable mechanism is one that
+(1) uses at run time a copy of the library already present on the user's
+computer system, rather than copying library functions into the
+executable, and (2) will operate properly with a modified version of the
+library, if the user installs one, as long as the modified version is
+interface-compatible with the version that the work was made with.
+Accompany the work with a written offer, valid for at least three years,
+to give the same user the materials specified in Subsection 6a, above,
+for a charge no more than the cost of performing this distribution. If
+distribution of the work is made by offering access to copy from a
+designated place, offer equivalent access to copy the above specified
+materials from the same place. Verify that the user has already received
+a copy of these materials or that you have already sent this user a
+copy. For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception, the
+materials to be distributed need not include anything that is normally
+distributed (in either source or binary form) with the major components
+(compiler, kernel, and so on) of the operating system on which the
+executable runs, unless that component itself accompanies the
+executable.
+
+It may happen that this requirement contradicts the license restrictions
+of other proprietary libraries that do not normally accompany the
+operating system. Such a contradiction means you cannot use both them
+and the Library together in an executable that you distribute.
+
+You may place library facilities that are a work based on the Library
+side-by-side in a single library together with other library facilities
+not covered by this License, and distribute such a combined library,
+provided that the separate distribution of the work based on the Library
+and of the other library facilities is otherwise permitted, and provided
+that you do these two things:
+
+Accompany the combined library with a copy of the same work based on the
+Library, uncombined with any other library facilities. This must be
+distributed under the terms of the Sections above.
+
+Give prominent notice with the combined library of the fact that part of
+it is a work based on the Library, and explaining where to find the
+accompanying uncombined form of the same work.
+
+You may not copy, modify, sublicense, link with, or distribute the
+Library except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense, link with, or distribute the
+Library is void, and will automatically terminate your rights under this
+License. However, parties who have received copies, or rights, from you
+under this License will not have their licenses terminated so long as
+such parties remain in full compliance.
+
+You are not required to accept this License, since you have not signed
+it. However, nothing else grants you permission to modify or distribute
+the Library or its derivative works. These actions are prohibited by law
+if you do not accept this License. Therefore, by modifying or
+distributing the Library (or any work based on the Library), you
+indicate your acceptance of this License to do so, and all its terms and
+conditions for copying, distributing or modifying the Library or works
+based on it.
+
+Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot distribute
+so as to satisfy simultaneously your obligations under this License and
+any other pertinent obligations, then as a consequence you may not
+distribute the Library at all. For example, if a patent license would
+not permit royalty-free redistribution of the Library by all those who
+receive copies directly or indirectly through you, then the only way you
+could satisfy both it and this License would be to refrain entirely from
+distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply, and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is implemented
+by public license practices. Many people have made generous
+contributions to the wide range of software distributed through that
+system in reliance on consistent application of that system; it is up to
+the author/donor to decide if he or she is willing to distribute
+software through any other system and a licensee cannot impose that
+choice.
+
+This section is intended to make thoroughly clear what is believed to be
+a consequence of the rest of this License.
+
+If the distribution and/or use of the Library is restricted in certain
+countries either by patents or by copyrighted interfaces, the original
+copyright holder who places the Library under this License may add an
+explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+The Free Software Foundation may publish revised and/or new versions of
+the Lesser General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in
+detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a license
+version number, you may choose any version ever published by the Free
+Software Foundation.
+
+If you wish to incorporate parts of the Library into other free programs
+whose distribution conditions are incompatible with these, write to the
+author to ask for permission. For software which is copyrighted by the
+Free Software Foundation, write to the Free Software Foundation; we
+sometimes make exceptions for this. Our decision will be guided by the
+two goals of preserving the free status of all derivatives of our free
+software and of promoting the sharing and reuse of software generally.
+
+No Warranty
+
+Because the library is licensed free of charge, there is no warranty for
+the library, to the extent permitted by applicable law. Except when
+otherwise stated in writing the copyright holders and/or other parties
+provide the library "as is" without warranty of any kind, either
+expressed or implied, including, but not limited to, the implied
+warranties of merchantability and fitness for a particular purpose. The
+entire risk as to the quality and performance of the library is with
+you. Should the library prove defective, you assume the cost of all
+necessary servicing, repair or correction.
+
+In no event unless required by applicable law or agreed to in writing
+will any copyright holder, or any other party who may modify and/or
+redistribute the library as permitted above, be liable to you for
+damages, including any general, special, incidental or consequential
+damages arising out of the use or inability to use the library
+(including but not limited to loss of data or data being rendered
+inaccurate or losses sustained by you or third parties or a failure of
+the library to operate with any other software), even if such holder or
+other party has been advised of the possibility of such damages.
new file mode 100644
index 0000000000000000000000000000000000000000..e9fc4a5d7c42135d794836c183ac877465c485d7
GIT binary patch
literal 11050
zc$@($E7jDAP)<h;3K|Lk000e1NJLTq004jh004jp1^@s6!#-il001BWNkl<Zc%1E>
zdAuc8UEsgJQ+1cO^-FiUJ9Ih;Sx6v6*+o$yG9xp<fU*rJs2>NNQQT0O5TXbq0%L-F
zl+TA@5D+7yPO~I~ARr*hfDCE~iL6;5AqiPJozCm-_uk#A>ip)9b57N%y0<%>?)$p?
zX83j2yH%%7)vbGe`*Kc+s`5Sf{}<BZ{Q%Q~(cekEp*lPX*a@8BKR1hTGOz^1)Ng=+
zD!YOGz;579;3i-dD4=l#5csF_jM-$QhYSIDFu-}h_XAG^o&=l)Ec-15P<x0wRD@%J
zHDCp}2e=0KGVl%Ht3Yqs4}UyBW?cmgKP~gX<3)G|@MAav*b(<Bar$6>Y9vq^m#yNY
z!oL6?SLIsZ?pc)pGfM!&Ps!N`F94nk{IE2onL5N-bz-^zNChjP0u~v&rvRdgQ71~0
zsBOG=Nf<W)pFnv(a9!u$>0nyF@mRpj5y0@1@+5>`0$u=Y0ne-+(bhtdK%OShITcwr
zAG7#ql!D$}e}dW!Bss)4X!#*{LQo~Kkf5ZVK&0Lq9F2Vr<vqaFoqs<YgfKG%F!)<}
zGQz9Gar_+MS=^0$o`B9j3^x4`>E<6HUH$>m?%7~E7_$f{`@i|080`KalC}={T{>wm
z5QHa&mMW=Qk|MgU5))qp-iGp#?lZN2)IWX$;e;oE!6)Pq2p0iA4J@G`>O^}kP%NB+
z+43}64|_4Kr6-Ygc7n7(M`+PQb%YipL=y7BE$sj1ODP7oBc^?bZ*7|T^+W3$#X5=5
zDU`HulA-J_DDclHZw5ZrebymO&*KIsECKXCF7qP%XW%u!!@win!YBdV@>p7@{tTV1
zKS4Top1(>_+ehsHGzXib_)pD{q{DFU$65W>Z{pB+Fja660x0Faj`d2c(#n-~t|Y3l
zG{}LgRk>{L+4}V(9gmHI6OsV>ACo5`Tmd{C+_+oo#JoNEF|^NkCEaZ=#w3gG0xeJ-
zg3VA0hkVUYPXum10}7B1y*sX;f6tXj(uSsar?n5pjx?qQ9qTWubTUgjw-{Sf3-<w+
zqP%PFKj`S_Mre9)!Vy6KWAY2YAL0TyV7;i{d?xKPf1B=(mt)L=@2w8GHUrHa!u_UX
z5%Qx?K#NsYzx|u!>t92X?)XED4T;uv$7}>uN`mlzja51$OFOfO)(GLFs=Q+UIeO<2
z4$)NMgdu?5M`an|jli#<7y$|k*<6?OtY2XM;g^uKcSctfXyFhK8LEXR28V2LVjo*n
z1mVw%X_K#C&)TiOgW7d44Wm#GdeCU9*k9{A{zyr4OLt&N3Jtaazzx7F=bxjWI+C%P
zCY%ri(EEry9O2IhBHuzLP;9$^xkvpW-ObOeI;&D5S98=BK#%}|>%H!e)c{#3A=DO#
z=`h@T6}`LPftU_ss-Ov4{yAuy#>eG{A_|>BL3?CfyZfqD;Ntn`>i>Aq12#oC?gX&@
z*K&afR{@U%7p5I`AUW%2SUBe`B&~-<y|vQkB{Fkjf^Y_(YpWALL^PV?oJXa1*W1bV
ze-<%wwXbRHOb`k>`8c|^Y!>&CW(D1z#S~Q_LE#E4uU&YaW=Ar9M+?W50M<V&PeFJe
z@Q4t|$rjqQ&cBSs(=V=f)}rEaB7JYO2;rU}w8`-qm6XW+y)qQg?0$N8{SkKb9gxoC
z2c5+IG&sK5FWT2g8kj=quIHp#%~N=rD*tuydEQ7lhH%^nVC}>57=e!grv>B>mzS9T
z{<kx?{paePWAR=hziIeI2#*QC7LgZ_k6i;PdGD+AcfZrMNy?btcPR0%Q8!f>lLYna
zt%6ZYXRRO|SQlz^Xa5l8)r-$Rwg@>c1h96soCjQua6uTu(U$EjKJH37Cp|0bsWow5
ziT8|}#UGGsE0qAjAe=w|p^tjwQ4+F!pJKT3(aH9}1i$}~YM{I%_7bW->YF;N8Lhsp
zzD{^6%BvS&aO{Fc=2(4EfYqyH2k?I20<0T|(UwgtKK^}m<ZA(T<TmvdJR{Khrq=J<
z5vn7QaL$W;M(#S?v3lZg?e4x5Yotp*NIL&$(BVO!U5H3yqRm)I44Kdz4g?T^(Nc?i
z&Qx@xyb8GNFotnza7-n@>W5?z;R8U4>EY%s3y=9z=C;1H>KKdihR#=S(T|D$H~>^~
zcwUnrN+d~$j7D<6V6%G|-uG8%vF2651Za+zDmD3_6Z+QNL>;@feIO(4*_cp%W$A^-
z#ydFH65ur`&k9ML;SzMuy(B`u;>5cT?%2k@%_?aS@B7cP51Eq=K@yaNP~Ec(5|Mdn
z(?imeXf6E^7(oJ?mY>c2Y7-Ge3?k;BecgwEm`arRYqL!)if)1weh8F5SpA?}cq|Zd
z%p|~p56W|a4+0&rFj|20+@E6ky#MLAO>M-bb@#18U{N;!i9)?pHbE8mY3lsgMXVcy
zrE91;*@3^O7~JfVN;S}ko2%pMun|C39dEBmg<wP~k}Ivf8D>-(hS#Ayd((^co}(T6
zL%}hT00%xGJ5jDc=}<u40ZzSu#WOGW$S+*hF4pBb0-TNy$F+96eGqiH*Xu!o)TBd@
zDpdA?2JR<Ffedtrl9Mbv7D-RS<qqOs5^-~MTp4lxxIC2c_VP1a52#>MA>W*$iMTwK
z@_67))5XL%92*s&{0_>au%IdATM`z}yo{uCh9CIK(2MsqYIBJ62-kr8z~xzl*byZm
z1jLpEQd$4y)*v2qfS4}H-1&8+1(6=)w@4+)kvgH2{h~|D_IkH)tti-bLcW}aF$3l2
z54>MqG)+`AVZ&9x{#|k*@M)lh!suk^ob^&Ro%@$w^p2>zbCIZz+&<^djZizpA<<Sk
z9)L(al!jg8>O~^H<|=AKb(BV>C11Y=JGuuER~$Ck*c(>^lkx&Y>OkYRD4w9+eMt9a
zBnR@qo;LzdTmC7%_o$IE0XDQMc>n*B6nF#B!a}hKY~ITJ&WivdWKItBsQNg+4V*0`
z={86gL0V|BismcW><(800F^yJ9@z{&9zaAGQL?DAA0k&#A!(lp#r>#S9Ir-EAL{sx
zTPoRLqi}Gf8o&{Pgp{%q0pS~p<rLE|kW4{%B=8%+YmXKmlVC#$KrJss_%RgJ2>G%y
zx9ugQ^N&M|b;r@MYgPtp3UAE^;uv7klQHcxkz}Fz0&k;fem2?a7qG={z|^gKS1?8`
zd>ls;DZD!H1QHvYNf&9If{yN-=oZEVp;0Skiz&}m(xXlY&2~{m+lKt4lyr9%q`)io
z{iW<W>1F!0Bf-O=V8d*HeSaYfz^?|E&u&u8(st&y{h}As!%CM2L$9WfgF)9v(rqMj
z=hu-Rfu!4MZF)MAoCLNH66yOfJD{QS86marbk~S?B_%x>N#>Zu@3m(@OS>)@cJbMo
z_SeucxP}em(SluUq1`0pthNBZe#i$nLf9|@P~};wJXI~&)KF}K_VSOD&Oh3TZmMWq
zX~la#UP~izfY2i8oOO^#RWG`SkZdBIf3nNGX@y8^<pl&{D1$?>9Z*IHt9~#-#9-3R
z-tLQheG`0o<Mxf)7yl1~@8kE&SV1@kF%eY6<IPGV6ep!+*jSYpt^9>NX4-h#NH5@J
zf%|pQAnlaS=I1%xXNUD5PaL2rUA`Rb2-Dh%m<d%oXer{=2Xaih4N13y9a6;#0)nI1
z0abKSH3#v}5*dOTR0AV0a~RXE1#e2GjlF|O$c_U-!Qz)dB#nR)(XoOqBxu)EQb2jh
zw2`zS1aSYK%M;adp<1W=?ItDZK9Y3d@o2H;2itR}*10~8@~Ms>U7qj_9{K8#PvMCH
zOuF4kgeYKCx{D=uyK@p;L(P#$We6GK)q#>ZA1#@$MeqXmOGyv`*&!MTASJR(&X1yn
zW6?%qO5y^6M6f5doCL6-mgn97=dx{@xY{TQ@GM}n<NgG?O1k(2Olv#Vt~oBp1!ii&
zo#5}+e1B=&I=FPPtLNNFB}b%12nClqUB}fxP4$%fBbqjY1Suei-zp!!lG}LZo)F{-
zpOe}M$esY+j?je!?U+!D{%GLeJ~&hy8m3MFd;d(@D9<U~<xMG=l-A-?P#r?h{c*-_
zEGXj;;ta7kGiv>DUg!LBKQHgEC4odiq3GUqRZuq?H6|`EF$9Z9Qc3(0*-<pm6M+zO
zcP(5L1&yL$Q4syn{mQecflVodQUm4r)4`O3jgSD}ugdvqL0bkE62vT!bk7AlC|xus
z=BwykUH|)in^9Tcp}4c~etF3LRRy2o?^_~UD};uuqC;lb_t!~8gx(#j5m8V_qNNBI
zBZx6ol80arQrQ9EuvpXe)Kx+mRgBe$5UUEi=t9Km(&tav`(8O^TF9C{0Vq#E*+c<4
zpFmoWv`@pNTm7VsQK|dOa;?(pkB>cKz3eOXeJJ_z!JRk>6i4`K+#6f@B_WJzeJa<n
z3L8t1N|J#TjsQGzn;AbTGl-@_UeM{j+eD*p%u|R|M!0q^fsP3h;B?@Jr-iPm62N_b
zDobj4vZqv7ND*Uz0-Ns!5|6BrHv~r|LQ2G!soY>BI<a3Bat02KtAOjtohqv5y?{6~
z7=l0{I8<_ZR5Ks}@u8pf##s^>e046ZrG`t9Uhh{~`BVsw493z0Y}yUR+X6*798a7U
z&Za8?lt%zRhysZq^9h&^#qbu^Z~raw-Zfy_5b5TsVyBVBVFV1RkX}XfO6z<qpc4$r
zaU-v`$pncIBVKb<8WN}kiT+aQ?rIFG^Aij_nQ$=PP3oZ|0p^pq;}h?Dk34+*?hhWO
zN&u>yg>p6)NCi3xs3K+#JGzzi?_NZ<|6@L8rr!M<mBE^LmQSn#G&1%yi268z6S<9X
z?Vr?)JGV)VXmUh6A$S!a!4=dTL8*d1vAY&?JN0N@%?60wze?wq0VSBALK>1FKqrAJ
zRs0x~v!{WxX-j}JROzS%S_aw%d{j%41t|8@-~AQ_d*6fFp3AZYm#<OJU-|GMeqY56
zV$Y#;?aHX1N3K+aP{jc9ikRZUlQGF+BM}|>`ZPs8b<rQi2Wom99~3HeK3?KS_al5C
zW3~kV9fPJO7=l|>Icpjyn{G15@^FL{1#MRb5T#D*00r5~hp@vN>1=)pN&75pFv_$N
z^QD`n1)>GEv;iW-MFbPFg)W|u<7BbBMkPx8#K|G?_pC(-wbI|<?^DU@dICtOycFLh
zRQ~#Cp6lv%1aVbDC1bl;Lt5(p(9gP5g1UPMps7Mz+^R)F8#wc*aOGjTDgd@?sC#Ui
zN<BsjQ6xo@dF<fp^zXfb;r^?kSas5X0*Amz7i)&C6@J8p9wX49k1q@><1*;-NY9HG
z??QE6N|jKF{JIrRwIg`!R>$tNR0wTY?=|1vpRbt=QFu5SsOq!U?j&j$Uv=KVQNwg4
zfU?<tA}te9HPL|i&CG+2$oBs=MgPmR7Jn4eIp2v-hLH^r`Rt_y??rrBL=ucYK^Y-h
zAfis(lOa-%9!e<%d^IuN#q<17GA#s_MniT_LWIi`L6{jV)Jp>WIV~AGbZ}zc2@3W7
zi260Z#$D&6K<NqsEFKw>>M&ITP>q&uNurpz#I8-mJ*EY;(Bf`J`>(=u&L*9EBBphk
zA29Ft$CEotbx}?GE<FjA((rRb=95JYLl93G>RmklFyU8FJ)nYmqL47zU#Mz&yt?pW
zUl24V5I}sfN3D?5n|C#O@x`Ila#X&DhTxMTErYEH;N&C0Q4^*u0jkd$vc2)+!5LHG
zKnQd4Y<3G-b_b??8m4nDl5F=Q6Hf<g)cR>a{s_cL0A~QY_yZBQJ6EqN4=b(wh9eeN
zdyR|d`d*3JCf$I0cCX8W_9!_Y5D8^wK@3FFz~4k90coK!ENP;;=;&eE62R|JaX=$^
zQj-Lf%@rZ2Vzb+@`5l;Ko?`xoNX#bOj2+uZ+Eg(Fw;%*a$OMWZaJxjDUrG@J@x;6s
zq}c!wXU0^ap2H&%9_}GddXz?=DA-8+mk9PmRF;joduosr$(-*$L=ocYhtq&*OMo1_
zky5zm88xeS9L7$GfV2@5TdbhPZnW5nYR^dy3{FtSo<fET8Yz_vm=KHnQVob5|JHG1
zzVUQr<f3s+bz!-uwGQ>0*X#ktuPwoknOOkox*ST}@dPG-J>bW96n?Z<1C4B#+nv-#
zX)TJRpaaMKb{#EKx&^B01+Y&Hk-0~(E3Us7@aL2Q7yX;O;3H7!Zg=3HD?Zlhc~!kV
zr{!~(?pj?3cuC-mNU8L{?=`Lt{C$lqfXvqhmyyN<FqNfhr>z3+b335@!V!8Y?qegc
z86Sva;!%G!*z9JK_M@oH>M2vc!7vPYe@l^l3)THd_-T<|t`5eYoG1YsI@dYARN($L
zURl?;UcCAU?J@J0PCzB@%hP_xc@2ulJd$kkgrhj!CTMPB6|nzsaPmMfZ3%D(ehR$p
zS=0vZ=O8-Y9n}&d#BB-1@LH1Y596wGeHnQzSQNs#VC`<y-h-Hg8m8r7h_5}-gw_T@
z2my-(tcgD#+%?pc1X9kq@FHIXSI!W53XyjRY7x^#lFc~##KnDGp^Kn>bxqE6x$jWF
z=x|}$xqxq~vI<TDXg~L%%my-OBAlwNq5)_97Wa_#K7vCul%eC&_s<=E?0$6gueiWY
zJ<eVOImlM))3`2{TD5bP3M+d@_mld8Ymul^P2yR%s%g3vr0rCgv^>QWsDkaec?PQF
zs@%jBVA{EWn^3-jfc7kQweap=%>8xb*S#=5(BY}PXJCh4B457>wR@rg4#s5x_8yAS
zKcRZRlN1e`Lc9%9*5^(7SH|<B-!nmSL?%jor>Vw>q+f&3>%`)bFKwi?1I%3M`XMcZ
zAz~CASQr#xocE*Le7I;i6inL&xEZ%j?o%ni?is?VbCsS4YE?B54Z>tQzztvvJNhbG
zd>3h*g_upg(+KQ+XmOXz1(+6N13XE*H=DG6QUZZ_1zn2%$OsG?ygV1&UjIkq`_Y&f
zB5oL*hA0qeA?Xf8=5YBCPgH8L+IRH;>jgHfCZc=;xb+aIIBb}z1laj1Rp1{`3Jer`
zMliBek-$pym3F})kstaSFdbCa(9!kS!56Tjf5MKwgw1b7DG<{tIXR9%a?s<$-`u5<
zifY(1W98qaB&n{ceoJT%V!uVw+KEY)aM{5WBt@h}Su`s`u_q6O&!Bv6=c{xoDq!kU
z!_@M5;0A;Xiq(Srt|6^+7M$G{^k72=)&>yY$CM|dKB<3X&q*dhVtr5j9`1j19DN+}
zH`GIbf$QA8d|X4rcLg_Y!gWG$7u^M7f)NO4?hL+kC&;`zA;y1^Hzw_V5JiVdaj%O6
zs*;QFxd;9ghX+%y2|Vp0T}Sz=;IC%iSx1L{(St(<TcUw$A}JgPF<hz;Gj{FxWe+}T
zBH$u?;UMhC*&Z3&IUL&ZzpVhXNYXwBV@|@Ao2MX&i+xB3bbuBIkknAzJ;EL+0+n5_
z%Kv%LKk6W`G4leHt5NR8K)yF4|Ly=uJ<@929@_y>Ne2&s`-8}o3Mpe%I3j*&mr$`A
z2qjG2lKOP6c&nWcDhGETyippae;HGLzX**Y(b)cw>h}^oI|Y(##<b7%kv@Ph=OAnb
zo9_Xm=s+3W(yRP`<;v48I>bs=4-z(n08YDDZ%}1d$XyR_SjF}VS0)BjIvHZbx&f8i
z;FXAuENzJg)Ze3Or|dhX%RSQK**wzxo_LGyBf&V7Fl<$O?HV(FFL&(bcbV2slJ>b6
z)Ai?5#H5valMWOIP`e+}l<by1cE#l`RQZM~S4|UF8#gylc{|GOVxZWcGrVCHlbA9q
zSQ%{oXu_b^xZX6l-V=-X37L}-UPpG_AdI&<!5xYqB-kf4qKuxcBn<q`0m%{RVmgmR
zT4&>2JQwPAmBvo=yO&rL*!)hU1^K-r1~;u$DF@}hpZ=QZt{Jpp1aSH#dJFItRUm=E
zH&@AS>mj~QumlOeE)3R$TxZRKE*mS3m$J#V3uA_6*<li5OV*C>7jt|=azXujCmEOm
zVJ?BBJ20KcBFPRMB?mvh;(Vw3TWEG0m>$|!2G{OGhu-K^J_)?{kb`~%u#vNaLHQGu
zj{}H>^=s~@xIaVE8pdjppppju*zcDdHHO!!q2$~#!iYHkU=T}#^3h_^A3gIy2&}4m
zaPfOFn=tL~!?eyvWWluujwiw8D^gDo9c=bpEW05SdjGtSVsGx=Z{=QQ`Kr?|nf{BY
zHhhhs+utPTsqz`%G|iy3qr=j_IR)vaE^82stf)xDO(r2ieqDS^IM*bQ5_wHzQ9B+3
zt?$HHI>LTfE>`1nKHeWPLN@pL{{>946EUX%Z9k9EM)!)oPZiY`n%|Ahzk(eUtpDE?
zMz{45_gbSIc-g~Ws~>pa(SGo7Ox6j!?f2y;am&MYG>6VP3oKo@9W~<0@nXXdYNEN4
zz}_-%7<y9fhhNl`7!8a!kD)?f<G3u;2<Jl%$0IJx+g1vnuv<dR4oDt`bLFgi*A3D2
z>hD|LFU98fVT<e0exJ2}^vG|OPjb=2e^1}~;79%N;Fv8GdD~@jk-`-KWY9f-iG`<b
zcOu)Wn@1Nq2Ujabpc%LRE5oa7m`o5cOe6rEd|VO&5$9UZwSJx!T|_oRvIAi=j%~vn
zE`O5=(!-rf&|(ioaXrP#0oML;AK6`lczwz%&U~FV*3F+T9LskHzZLgN*WV(A{?}Gf
zg-sWp;ulABL;z3~LWWBx7+Djbxr*2L`9s6OS;6Pz@o{>YLu3ieR>W*YSnv$(MZFEv
zgS2ti5ak0%QF}M4*OTA9kJZnwQ0&cId8Dg*dp*Ki9^jFW8jk5=(cigL5>@##gr7wf
z9l_l9EwgmtcBcl45a}C_=~ov2Btwyi^JDIhq{<}DFQKlNtLf*0D=kZa1u)CNNr-Gl
zm;=Q34YOf2D%gm`e2^q%(kMmktrVkwWpLvPYhPT!4lL3VT%MbY&w7LX<D(t#!+~S|
zzJOcbU=~%m5_lni=E~d!o7nUtr(n7Xn!A{|m<qv7ub@P>3B*9%dY^>&8vbqcSru`B
zfTjrZz#_;3$P%!On~akJrZVa@QV%s`LuKGmHENjHaU;e0S6RL0K6+nS1yv*wP*#9n
zI{Q-l!J{1J!-nJX!iZa5Z#G%v9l*<+Bv87KSY-1vc3|dHG}oF0sA>mIweLNLn$8yh
zMMA~R1mugP2raLxJ3tp#dp8FxqRcz@OgfG*P+S_Wip63}%fRFPfd~N56zF03D%m|Z
zu>bS-F}StwTw>=sensGy&$-loaZ1B{Sa9548S|~zCoOe$!LI}8z|!71&z5KHpmlN=
z^=ahN7z{IV12#=KXG+9l7BI3I=REg8I;eCobU?bmykBuFWEDG<t4(_Bl@@*tsT%d6
zLVC@pYq)nd90*DZ_HJx(Exns=WB=z?$oFL~DCU07)q?)&BQCWYx-$4AIIb^^y7_fU
zs_<Hr*CHf3u(Y;yIQf~U(%HFy&26OnO+(Z-k9}BJPJ-kVL{0_Sf=I^?ay-vJAb3KX
z0%cvkH!7RO_}2BWklt_?33OplYf)~XSig<~*WAPEmsZh2gTC(r|IG+jJmRuqY6+eP
z1IPWfaR4{|Uixdew}o~zvm^^CTb{9lg-0!;xt3l*?Dmy5f`s{e;n+G$n-*eDLd?Su
z*#WW*$Mt?jkcUZo?ywOTDE)UzMA!9uObm|e)$Rkn%y92b-2a(9^uN_Z(z4d!yTB_R
z`TP0b9PRiW4V(}J0C2-=)Bgy(6WF4KBB`+D>8G&#gp<RvC{Yq7iUCYIE*$|+4AMbl
z3nJ$r=HXudhbiPVL^<{Lu+xkQ0NBRL-zaDTYOwZ3;4AcRyPNwyc`u`TN0>_Fe;Rn@
zqu!W*bDCp#ByhqI0KhkYw{;<KC2*z|3f8juX{WIHsoS0VTu@~b%U7>Nwn4c9N7HLi
zDj)u2O!64uOe)`=2F^9&Xb+JZsNMt;U1$|0!M(QrpRmP^?7wb>mCxNz(a$lh1f2N!
zV?kg4s5j>8(;T}ag%gSZ0KW0Nt@D6)0T-%OG_x%Kz*e^X_`{G^f)?(1#Y8J^Ld5x|
zN^u2uu$BlaygE4#ktY+>f&-000ucekMxY*q0NkPoSo@C@>;KGse}91e*X?uhtV96r
z0bcp&H)R_V(?3!;;RpcW>%ZIDjLN%!7olJ?%hCnQobv3Qn1vM0v{VPp>1DO>a2!4^
zV+!DqHbUe)kf-8SFRRDw$E^B@7@D?#`)q-^mBGCq;ogtm#rh3vm~OeS({-Rfcfp&p
zsW10_w6L-1;3I?!-juBXKd;JrRe+Y^z}NP3*Z;nQd^IEKCiM$SJAf)45ZuQyJ`e?r
z#DH{Bz6JaXm0M^i%d_Ioa&x(Sm&T3SrGshr=->HS?)t!YSi5l@nM>RXFUnO4&pr{6
z4<{%A09^3q(YnGbRCyaJNGoCOhE=}%{@WSeH*nlF1|_z~+A5bZHWu5c-T>T!NEZn;
zc^IFwH{P{OJkbP%8(co$Akrr3CLFlo<J|F=*V4Z;N7@N$MXi;~5q|dj-aI<y{{7*?
z38?~_@RiqeE>ZVJ&D0KZI@{+s{l#a{J$(Vqysu8(E`Z<}P{j<&@NszsZcXA%h&&&3
zf$+K*8Y-Z!_i^D{F_?Cnz1Mt@JFor-c9goMao_-O(PRH$_^u5dm?^+a5CFjSuj&3g
z@OEIq4hve#ZFWBYbT&PD89TI|u^R+%7<PhM1syn}kY}S<${83nBQLfKTwEe)b=dQT
zk8<aSccFzr+6lm2z%M@T4+ft&HY0O%Ff#-IaNWh-=c2p^VY?k!()pBApK~f(p0t%>
z)F1*5j{sb}-hv$>@}nR>f}3<2GJGB)hmGWE000W*Nkl<Z0uYm8QepQ$e1tpy#^r4!
zO+dLtgqJ+-^1+vm;jkPP%oG6teEHSgr-S@CaJtPbk_u<M=nOVLeoL82tQ&=4J_3xZ
zfQZRMfrmU5ksrjFN24l06slWkBeKHo&wq%!{^pZ_L6QW}e-+`UAAkAaxCeJ044kk=
z;KAStR}B6^mFKDQ4M`0}-?H-6eO2Hm&e}z2)<|~~^{AqNf{LK_v#9+r=-ogYSODfh
z=21q7T*vAy@8Qmme*)D6OoA%^qAJgwHRQvwtq7VLJn=34FMsKxxyyiEh+xvV`ljgx
z)CqwyxibOOxq)iGf$A;5PDD=jZL3&&H=5i_F<b-dl1%De?D&!=y`_K0^ndBb!%PwY
zfV$;AaVrH$8NH3sucCgMfq>{C*Q=^jp#UA+Qgk<?dUIqa7)V?#LAeyHatrXC4f>fI
z4l_#tR-O8?8U^vdGkLJw1G@bpj}kBPShE5usZbVi7@*^it2}_aLgNJ+lSG<J%FhnW
zECGnkvC_hZ1(`fMDvE>>FSTe{L^2`67emeWkCQ=K9pj>l0;sw*`&v?9?aY}{CCn@V
zSn2lCV%4qrs6EnTK#A0b+ZX2os^ZY*XS^SCyx;dlAQ++B&FPv9v6c~O{-M23;mI5G
zGdCP&#tnS+t6%*S?RNVG-A*S@=1<PH+S|`r&hL2!rp5fWIZk@SlH*PjEkC1Ru~=)d
zg;LnUZFxbS=VW<CmgQtwMm8ET9E}(aqr#kKGDs9LFglR4`mG)bmVL$icW)k?`nU6D
zr0N)IKk!GpcI~?T7!T1A!AwYiOD?%&ORLp-bGzNXpxx=vPKJyY&Sj<ZSlaCt14-C-
zyTK$W#+Y(hVpS-L0&6|OJ+g<RA=zleU@)NH?=u(-=@0s>udT7ZzRoDi4r(j{NMbN;
z*TaaOHfKh^*kGd;@M{|~7*mFsAb?J%(-M*SPNze=-6l;_+KHttL)xOW+HKNQNRk3$
zT#Oz-)nctu6iS{ed2Y!vOM9pchn7}LX|<r;hE@w&sUb}by<S046jcNfp$Z-fuC9Y9
z%IL$&l{7u=7!J=-!AuZ9yWLh}j7`&&ty{P9l&3s}R;xvr4V)y=+q@!BRq{NqZKKhM
zEXx>;Mhu5ThQlF)!JyonL>Mp{jl9&z#`eRt;ke)L1F*ET6uvq?wj*@pFe?OrF@`iv
zSz21+oO8}OqWf5DQB``q9xE#=WLZ`sz2EQC>-9?HXIVCpI0CYZq9}=>*Xv=7i3wn4
zU?vD4P1BM9j4>2NL6S_W2RJks6JGuxCGxT?t8sRG9QKRC*$_oh)HZ8vxizKFtia3=
zK$0Y+X-b+-=aJP1cmg7eqA1%`wM1-CBVj+Z#{`h)Gb8cGU?w6MNs?fUAxV-_-ybc+
zh>nq|S`~jZ+pM4K-z1*UXBJ^*2q4~$7A7G+M)V{}5OaGhHDYxzi!c)eV2r74M+*V5
zlQ?;jh>wvyX+IFfEW*qYz%*czE^q4nrj$6CMEITrIL0t7YkLv`ABg)WNr8Bq=JOpZ
zm<a-i4YO$&Ta!3BzHh7+CV2&uJc92Tfg1=-!)zMRM1Io<oMaRpO#EkAHnXvSnIM3G
zjHA`HP4{k+@z*4ZN!uhNFwgUulmasm2nvB1;6Yp4laMmW@{c+FP<lQlj?flA->kt*
zNPs314#jCrT^{epND7E<>iRe$I7tmOpCxdAJ$pDiFf$S$xPT8d(6O;7B4fld$<>?W
z@*S=k2wB2el>jqA09lq{jC&7n80>Hib=ND76*LXUKoqep5kk!I=cIQDG>yS#?qF77
zCJ10O8kLB-|Ni^=%x6AByWJ*95?ZYmi;Ih;9$s2n;?z@5t*MF_QE8fT&pr3>^{;=u
zymyvmB_|Ju!&*8x-UfpKy<U%2tHtKco7uE!6I-`#<%~1VpxtiIBq7WS0T^RU+Ze-v
z0|&V2rkiND+qBzly4`M>lW(`%?AWn``T6-WLl>(7Yb~u-i#>bxaO<tNmZ{~qU?ik~
zn*|_oeZaPD+nAf1D_y_v9g!O79G{VT@GuhuFdPo|8)Lo%oDO8h81;xtN28Ik)^f@z
zr!Y4+$EHp0or06Zc2FT{nzCif7Jw4blPZQrqfwcP4oN6gB}tOlj>xFWN5d4QPaoqU
zI%1d!0=WG0%lj8!eDQxNisJ2go=cwR1t58zzah`_r=@Ai^71lsb92ni&DE}*6yp~W
z78e&w?oZRS<ou9x2zEv67EVY<e;fF1U?0^IBR$}nV>C2J4KqOi0GD5W`F+6O$8A?!
zamBA>Sw^?pWqEm-#l^)Efz2E~P_qN(=jY2PUMMta)*3YZ{RsrH3Va?|*|lrehL6EU
zz|0Up6E3~<QX?WMK&#c_j5E$)d3l-9XjEGIlQvaladDCD+qc(5eJJ!C3<l+AtJSJ`
z20@ZUo`#z*KEp7x1kmgCN=|II+w^)p(ljkShPak5HtMXktgNiCd-v|K>fo3FngyYu
zD74q>v3>h?mX?-g(&}%*%o4!*`g&=Br)kQbJ$u}w4sW={W!v#q6a~9?@8;Xz{x%~&
zIV60>`!Qj}*AE5*78Vv*US6Kr;7<%QO8{$YYc&b5efxGcZQ4Yy*TY&{LtMNcjJ;UY
zH@Uqj0m5;=-zUp5=I7@h65J0nOaOy{dxKh06wJ@h({8s}TwE+&v~IUs6aBG&zqq)_
z;^JZ{C7R;DIS-)M>(TG`SzB9UFc{G3bRH7i4>L>v0Rp!lIB<Y8P3iahsA?_3*W~`S
zwKY~&R>nm8Bti&85Tby+UXR7aMLM0%LqZD7JOPA&&%S;8%4u3fQPA)AYdSne@PPvd
z*t>V{nC0Kx4_h1}9t;L7FE4-31~`!*sDYh3cb1&p>2zuc?sPgOLW3K3Fwr0MeSE&v
zYL%YG!oot}{@Kg_Hei+sK!H}8rW`nMfcL-u{k;6;FK64fZLF@YmNr0hGH8}%^!t6b
zY}qo=1)MY&u;1^qzP`@d+8PTB3uP3MhX4W0L_x?T*tKhyf_pD<yWQq%U;7$wd)wQ%
z`R1GHcDulMEn%D(iqpS`+TzII$tR!8)~#FP$M`#7_c8j(8v-*+006so?Rp3B3Shn4
z?Q;9=xATs7yo2knzrHlmnzMQiRsMajQt&*_nVXwqVPPTG`|k!`bKHLXlwhU_0ASay
zUGD^53he20I_%%SpDVAtk}rJW3#4gU3*p8kT?ecBnbh8Hx0#!pi>>~50>27O{cYaI
z8fKmV0Cw%#^%3AFfg3xW4tbt))m2yVsZV{XEFp`ha2=}hcha=)G)-gVzXSLUAUj^a
zcbf2!AOL`(D85(}#WP2v(HDdM{_JNz%O^hZ35LTVolb{Vt3|8Ts^$1&T_2}_Lw!I4
z-i=HDJ|vJ2v+V`cU}<RyYwdTkEPGB-6z{UuzOdD5aou&-vAVj-x#yl+iwMTczBH?U
z@;qlS7?9_AYy`d=$N9(Q{eBw-GqX(G13}0R7Dd6e*IqmSzW2TFt@q!5|1ZzY&5f09
z$G<tY@?$B`Saax4fLC$|<bSUo;5ftl{CwDz3opE|clzn4zvA8Re)p}n+;YohNs@Fz
zNmpDdc9`&X9%5oYhKGy<Xn+Ci>gp=5d)@1P^3FT&d{&yK;SJD-O8_n4OTc@n-Ya)d
km{kezP$hux!C}Jx18B#A2(P4o<NyEw07*qoM6N<$g75DXS^xk5
new file mode 100644
index 0000000000000000000000000000000000000000..fc69dce64993a4906bc5c99a55e379e3dda36ec2
GIT binary patch
literal 1811
zc$@(f2kiKXP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyz<
z6&o-6u$%e-00xsuL_t(o!>yNlY*fb;hre^?uD!eFZNMf#cnC@pP{Bcofl>lgZD_$L
zNdr~V0#W{|l!r(gsZvmBR5h)tl9VQunxeGA1eLm>LI_m_L?NJt00EL>Q{(U`FM}<>
z7<-M^yZ6rNAND#i4`V||THQJK&Yt<^%$eWJ2zMy6|9&(UI34a(mZ(tbR7zB&z^SyT
zNTaHJq#`?<${tnf)=wMb=|z$5KF-`yHPMOu*r_aWDyRx7pei^KoC@0U?5O`)M1JR#
z%JS0Dsk;U!*;MKB#mbyYxr+2t5mdpcc61JXV@m%(i8(<;$zY@+a*!1&@<w^-=#TFT
zVCvug{R1bgR+W5JF()FbpdySZh%u#q9%GUL#rcjr6(WqL5H4mS&bN7LS|i#_>Yehd
z!w-*o=ZHvaj{zoE9G;_2*Q;<}`^ekF9dp9BixWIHG|BKp(Cw&BwuV%uB0jthMduEz
zUG&E%{{Vn;Ehe0pyqWAR0Uq3NxX3B*s<1#s$&ETsg(ai<@|_WVdXr!L=TtR$6)!P1
zU3*F}OQ$o^($ezN2P&fVxi(#f;>~7Q#9URusmHv68jlQ$_qua{u~$!!XscylVc}SS
zR4PR_o0+&}YUIie5p@9=SAHN7c|Ti4l6b(t)JQtz)dvRks^eF_Kkp0H{j8my#>`Mv
z1SIA@kG$q8A&iK;&5X?Oxu5sUElP0D#SA)prt=D7$7juVHvts1H4c&}ykEi)3qvdl
zF&|P^9KYxO&t3~T*A!A0CfHW`@>h2~x9LlrIZ*i&1M-DOD=Syd-92>nV3Bqz5djf~
z7Yrs-G@iV1)9xA|x#Gk2Cvf1b?eE)kVbQbu&(y3f9hC`G<tP0L3xD_xJxy8tJC<7=
zxk^i2g6omey6|-p56!>lXsjG&Fa6>yd&O)sa43kyV$T;97lWDIN*D5gg0?o!9NgFi
z;AHg?c5L3j*^@Pxj~F&`EVI7#1d~f=bqg>!rp)LU%-Gu$esAf%)1L-G5aa`9-iyfX
zw+4+eo%N6RY^P$)n_a%2IZ@4fZ&!2v^ocu0VS2xSe_hKyDI%}smSMM@ceDWD(#7*^
z{L|Z=uM-7*So-1$#!Q&Ve`}7i?ycAF2rxX~;k`8o_PF+T4)<)`L=<)^DRaxd%lJtp
z1hG8EPby*V!o@xEGqZnCVz9W^0LQC7>0(csI{gNFMvwfAi8~^1kK_QXrvQx&m%7;f
z1`fW#F6@z?0fFMp`fGdg-)Z`#UCsWFMFqT>X&8p*!%Rl#5FVsM1;ngf4Lng>E5U$~
z?c{|+x;SdOdie(XN{;|C-tZm?vf1p*7whU?iv__jz|tCvrzKv1v};0$QXT&?i3b-k
z4H!SMgv)goIvpK7ypP%QpX#)$4t>-kfQxMrk(mUO-e=>Xg-w+}-@s#Ohc2J8>i4Zd
zpQ$1S;%JH&GNE}G(}1r%_BaPV*hUnE0PNgS!SK=JI+x+jEfqaW=2VFH=5D?CSMPn=
z5w1~@J}Tf8Vgk=i7{sfShqC{Jt-Sy4>RbMGPT691ZTV}LcdOQKy{X;v$69I3WV!X(
zYWa)}{ATCVm@YuT5Q#*1?|1_vk};Ofo=4%(Vf=IRUpRa67-pX0kz<%O?+K<%d-Ns%
zfOORkGSz!f4X90LnA4c1X882mAItTPUHM>DDl*Qgn5u{q!8u`NNfArO4eW8ohqXt^
z{B{9Dh7JV-!BC9)x;ne95cwa?X)}`rk+-XnA>NxsW<=ij*(de<{L^~sTeCeok2KVh
zOeTpZlOz&x;)w)#$pZQe7%1H;p}jJv#>AfS-Y!ID;tlf#-i-3&S6Q~_9RE1q%(<5C
zK_U^rkQ=nb%y4(a-@fjId~?}hL`nsQv>&Af5uq{b*<PEX@@ksP>4=6*L@MiP%0@J1
zJm;=wscKB~*{K>Po!Lr$pMG67x7OBHq^I-f-rV)D3cpm5ud9B39do(6g9`CLxGxc-
zAm)fUp(TPVnJizqbdd5RFAy6w5xnmNxLjY~g9zlpwXOVuoA>N?L>dK|4iak@&UOVA
zz#BA&o`#I)O2(54J!XPe$GEzK#2e1g*xW*MQxnbCuF;%I9h2T_c(8hR5Qt3{kr!2E
zSs=MftKd}3sfg>iKdMu6A`*x(Fx$w;)ahTZ*tdL5GJD-;MJ1c{EpoS;N&Kzd&WRK`
zl^0ZGfvQYWLB4QP&P`LRQ&}hKR(<x&LpL3l{s&uOo48bDqR0RM002ovPDHLkV1nEm
Bag_i7
new file mode 100644
index 0000000000000000000000000000000000000000..f1346267374d7556080c8e9fb4868596fe0d3192
GIT binary patch
literal 1879
zc$@)O2dMaoP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyz<
z6&)LlUdYJ+00!4dL_t(o!>yNnY}Hp8$3M?=e)qQbmY2Saw&Sgo@LnbZWCcV8M$|Y!
zGj-|=U`TW%Ze&i3iZ9FDe9J&!G3v<7RwNn{3F@LUSY%WOlQ$hLZe>6QrO=L2Zrj`Y
z_Pf7x{G+{PcO5Tne3FyjInQ~1&-p&jd4AvDIl?Vu@n24bJfmZb$|@CVjmm5lDKaWO
zDiTwb!z%K!QK?s@b?5wQ%OFH<Ho54<#u_8?Eu*r^sGusSfU00bFe+%@v#<X<5&4Bt
z8tQ5%#D@%E_MQe)AZ~?GsZ)^=DuOB))xO1Hct{!PDIp_>C>b2_fE>tODzdq*cEZsi
z0hqh{^>s$rswxGl;*5x>f{IXG6yolYVXC7Zl?8^d3IUF;EL_e6TufV<k^yNaZASUo
ziFsAOJ}HvCZ2+@&omiqqcd9VDH}c+ehm7#a$_O7Xk1{6W-88DR$t(@=fL9Yx(R}2E
z&;929X8}+;L&BL^f5LxX05g7nqQWT8sjyr{$weJjVO7;|J~MXMVCswio_mAvuJuez
zwVV^2OQkZ>)6?_#^j*QuoK0RR*13f)V5zEL)Z(myI_@bg9Q5J<6R({il5U}-tZX7c
zJRZmQGc_;H4a|z;1bF}^)g6fh)-G0&C>C(w)Dbnx#_6RDMV$3P4QdR|IaCz^37PAe
z*IXwHV*~3J1<qk}&03aLL>RJ&f^+@NI!7v86ng6;_n83ziqf%C39{oQo5f|bxFCzO
zSyogQ4tf3Xl!bI?F&8?sG<Rib%|>{s_Uj)yuy)UsevA#DrMN)&XhY@vr3cFwuNUb>
zB_bfgV>9kRDkc-2G@t*6tiRx%3Hymo5qau`+NzA4dO$Xpm6bgf4SN&@DVGD5>-1=Z
zM4;G}KO!>czC34{bc&<(`)NFOh|A6ANc6-BhYKhlJ&u`k7qW2KatfnGdGECQmLFe8
z9uio;WB!EWa{5c*)Z{5s3UJQdh?p|zH0Os+qvWg4_v>0OzRmMnp5SWR<r_v@QdZ8|
z4Nq|AxavIpAFiZ1)Ro;L@J;nRuK;k)T6uTD<TXHpOuvIfyqoPm-Ppgl7Yg%*hc@u!
z_T4=4_!dga$^p1`^&Osj`uik%@_!2pMtE4~?zd2sD?$;GTU7M*`B(nBo32<#|M=dO
zpXY-gUPdHZMAhW!d}{T&{<+SMcIx-;$#XTPz+kQGuz~%w4yBMz9Y35mzH8p1d;*$w
z*G=sK7LD{~J9xkw3V@C)t$E{3-+t((_U&z#2I#5_4F|9J_vA9*2E}l0Q08RPsR6oT
zPqEI8^lrzQi1ZgDK<TIo-nrD=KmOjf-%?yQYEYn5z&htNo6TO#W->w_@gRLHAkOu&
zfh9;M@ruXwzNpHK*|mAjP9FK^ptmt&9o8ad-89?m`+iL_k?`X2c%nU#cC85)Zcq5q
zp73c+SYGv}(6R6<jIA7vbB;U5S97#}KYk_+z`3SIqD8|QS$YSa7b4yj<HFe{j{Rdl
zf86m)7A{*c06;^x&+Fa36@cR_nF<W|EG}ixNAKSBtE4w<u80FMbQP8{b>bxI7LD$A
zaN%qdb=#h#v!nf%(QewgcYyBM^KlNxGWPvH{;h|;Xvl6?kzp!e6hZ=Pr<SsDR(Zc!
zD$&EgUfIj36R**F@jR(S95sd!#if*w9#8eu8fxY&pmJ>0fF-{6W|COOzwxQqZ29}2
z6<ywU3Kk<mp(lK2Rt2jkmkfH(Q;jc^d7~axkCs%1hFFTGF$-=CKsO&K0N1D@lZ=YX
zfiOn+!R!iFPr7{&*_Kmewk>B=c{w-`9Ezi@wbk8_3GFwQq@9!Hfpymchgj=e;2eQ<
z{P5pxJoTS8+LHe5@kU1r(P)&yXp~5#kitlWaI}bF#U*l6Ds~%|G&yk(TI((a&WUw6
z>%clk-CNgKQ{T+rE_T!0b8{ep2;h+SaE@~hb4&R9cASxqtvP{6t-z?>qqHC*#C*%X
zmN*U9QnaT6Ix+!q-_qp=#4?uVgim8E#p!cR%sjuBf?*@_es0NR61m-dG(SHuPlcbT
z$i1r9uVW^6chKG<9UTc#6f%U2&=bJbjL!$I9HZ{!!-T48z}kKQ?QLzhk%3&gUaGrf
zKJn#!h{Ob0021mY&Rzx;z&hy8S~@b8s~Jl?YjIAnYM9h|jKYrd#JYRv?&_kuvy<+4
z{7o6`=j3fY=y~F1iO3_Wvc{9#rByI0&Zvm#yFaQ?XGFvkM~NR}T>R~)zx&#w+oOKM
z`l90dwnrGE6h3p%7?BF2^0105SCyG6$h&UJxot`sl^vpH)9DB2oO!RG{{g5K(}sK>
R|5X40002ovPDHLkV1nmcn_K_@
new file mode 100644
index 0000000000000000000000000000000000000000..539aed7163882bf4dc990b6cfe261e34401175d3
GIT binary patch
literal 1669
zc$@)+27394P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyz<
z6&fq$#%`hj00sp~L_t(o!^M|>Y?W6T$3Nfayl;Q<s}$QZm<$5L4KiSa6*}U8MO_pY
zGsQ%dAO9>aIu~XZm&|M~8fO-nF2?9wG+7Z{s#^?_WgA&WV8|E(ZWP20Brs^9%1VFS
z%e}q#zUTNydw~Kilr;JzH}5&`Irlu@=g0ef&LgfNOI|w^N6scW(`pm-&NR=YN@q%&
z)M=)7O?u0jc9?Ny)558qVTguWT)gGrEGIqgOsky<GhqTV;Ut_1>wor-{~+lX&S-9|
zza@3U0OtL<*_A4+aHd9+#+ZZ|IJ17`FgiBIMn>#}WaJ2>5{e+3OnR=d{+7Sp5P<ow
ze(;bJ&zq^#Ou<Pq1Cy9q88dfm2~#T~>Pj6YCK3YO1vs5cIMwTE$t3g!wL9b4{R^hN
za6rmjH-I@!`<I%tO(t&Yv%JsUu@j%KE9Y}H6-+9RhP3KmnF7tJgukAL+LL=;TKU@t
zehq-p6^o;DHj}?9fZJc*U+awDm{@KyidL7HSUqJlUz$8>IQhjtjvc0?=@F)7TaSql
zve}%{>Gbz+Yf3g1_Y5$_htLobmYE4>p5P5EaM$><VJioicJ3(Uy{%MLS5E^-rBdYc
zxmjE0CvL?)k^umwH|{A<ykBBc1s(_xEKuQ$CvF?hjY#l$Fo!uu2mv!gpx9mX`~?67
zm~1{Q4tA+aJj-e;hg5QC|890}-AwE8qh!)4LI@Yuez^W22;sudhd{QZGCuO@dmVdT
zD+~Zo+1oij8;|;=ya*D(AedNDS2n2fzwg?{?|=F1pz9^KHqi0<IMQ7OAdvOtyjlN^
zyWd&--CNmE(hLwaf0=Qm;-2Q_r<QH6Su#Na10;dOq{<28YG+U~ec=@f-rn-Z0rOSg
ze4M!p@4@V%8>^n&d0|`u?D;6XH@drR<+}Gyw7gV5B^R0L$uZT{-}#IkXGQx9MgOTd
zNS`U^d}3to{}JVPeqn&Zf47|+Fu!BL-2;?gO`e(<9(m>?b}59-z`iJs<8Rg0)zKfk
zD|n#<sO;_K#NJn~0FWew0rMy>xn^Qch>eCZQNyn8!q?X9KK_0bMNugbg7=aJFAbLD
zE{q@h`h8d3bLsmHo8B1otVLrYc6Q|-ko0sh35QhPzk`vINu>_&Lx%`ojBezBqIH*h
zVkoPxsI+6Fc{{rbUorkqGPTT+_;6PdK=@w+7#A5ngt2xha}6GT^|9FqiV1uO!3u@K
zsX{I%`iTeivw%YAV*^jpn;{x^bKf6rWTKYy0q;?i&*vXKedf&5aTHAiLe}E4tja1;
zA14$r4wrq3^4nLk5b)lQ2!PYQ2}uZwX8(y-_TAsz42+IEA?vX9b2t1d6OEcL1(2h=
zteTlU6InQdAvlsM;C*lr!2G|^GGKLS!*h<pizbaSfipPU*3B~?L_9I4W<&rS$T;$f
z?CLzQzTstl_V!l^wj4n~N+f=Fq=U&7F>7X24O?OM;9KMl@4zggHJf8;XO@;pi--ol
zOlW0-KNzIxK)_J806%!Y9RzEpUq6UK>mmHc2bow?0|Dv?EFjSSPE#0?U$tS|ObG8f
zXH`xFGpX1Etea8AgEPldTOMB%K)!h^@vDzgT~mXKNi1=$qk|#8sqom+mY}f8`_Ptz
zARh=mfDeJjBj;GV<0P-2>fvNMKO}%e0s^{>OF{^^Yr@~U@u)t#c0W?R;1hjUX(5Tu
zyk~1`iso}!&Sn!jatW!tr#qj}ne&`HpXXp_mJg4$F#E(Cl#UuRptxl+8Lqp;xu0%Z
zVB*In-D`HS9dpIr!9-akZYqzdj2*EP=>$H`<+<ZOducrIF!7XGa7hTxwzpr02a4``
zv$4(Hw{9y^r_dr$+((>!3@X3}=qY$Qa-NTKo>ajTg7D^;er7La9Vh7QNz>EaO;1-B
zJ*m_`hh5~O=eI|Z!W>E8Hq+Wj#ims_Q*gyZ6_~T&Bt;5T<vY1Kb^Isa+r9q9iu`$>
zmnon3=^MUfl>L0Wb5gA{J#5l)GtD-kOFHFZm@>|^QRX&$xa!WMm!I=r;L1;uI2!>c
P00000NkvXXu0mjfrx+52
new file mode 100644
index 0000000000000000000000000000000000000000..df8099f4da979116b503edca617c2decabd99d6f
GIT binary patch
literal 1729
zc$@*j20r<TP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyz<
z6&xDkLdhNg00u!xL_t(o!>w0+Y?W6T|NWlxzU}?!CuMC}nS7+843w`xp)QW1j>VN_
zVPYcMvG|8EaV|`kXtoT$F)HY0O!lEByOT(8TNa!jjGzSKaAUwW+6}uh1WHRASt+;o
za_@aV&f_1qx9pBm+OAJ>@}4)(bI$WS&w0-8oQJrMtp4j;u4AOZ2-}2cGQuT7#*Hv7
z<e&)uE#y8UJSc*`9V_QpOh7o6@|G7n78vq7M%ZSA5Fvzs2w_MVA!PVF-2WrV-xxuA
zqG@(&(g2pc&~8ep>x?iVWQC9r0gTA7bD-Q6R5}9J5Tw9^A{C+la+i?X6HT*Un-qX$
z&%gO~Lp&<NQW2^lDFO(IIdK<@D@!mZ=AgdRphSoeievzs_d=Y@S#)MX<dpqJ@Uvsf
zXFYM8%#0hrqFu*Y#K;aIZp^PdA8ywWpRbQ%ZEXw<QD@9my_*Tpo(l2uWuUJ6@Y5T9
zzy3)8fZ&o#oLsaU{-^+M-g&If2!1C-t58r_b%_vdv&wPz%(98(7v4T~0wufd$J}hs
zDMB@y^_Whlzc+tZxT9cGv=pn_tRdEj5JoK23LuIV(;^dg4ghm6o<ua)gX)@^xd4z#
zrQrMCf)|&CX5CSQMF1KThohmjtA&ig0#HCj5i^2^=1(h{_`$E-Ui80h$DUCEsPzFc
z5M!XK5D^fdYpz6I3Y`F$8Ctz1RD~@xYq6#-ib)FvP#tMj71@%w+x6)?%vAv5xxr}+
zgO4x>pg{l)1E>wKu0Aqp|0VO9F(6eqdnrJ7GC*Gt#Y;^Od}{w!Uzj(N1MOcxRVi_6
zd;69(2WnSOC-bOC0wfyZ)8W;96eW!-Ck((;)S~*4e~tXd031H6ua+l!H{AQ`na-!1
zW_gYXAE~IR`PS#;G}iS$p@rZTI_bVBE{B55oj*Zz=^gm6vSo(ezx6B*QFS+fqmJvk
z->9pv2UK-5UMK+&&*gCD$a7-?Xn*Zx9QfPw=so)`0Al9sMtt_JjhOd|rA2nrT|sk&
z(|jlyeEFVNPQM|J<CFqWwU+Nsn4$(iLhqW+_dJ_G;;|p$bl2PPayfXpEKYTH;I}`2
z7+oE&UuD0l!huy?Z-ICr2}$xg8GUX2p?~}ZU;FM>{NV9FVfn4MT{(uT*tdJ<RrU>~
z2G;6;4eecmDUh{yw_)DGrHGeTVD0+0BHg+Fc8z}1Rys=*_~MiRn7??%NWZMIsz{g1
zj(!i#i5P@dR}=u~hXGJgU32B=8E0H$svLn;trXSk`zAS(jH8L;xW%^P5FubyRe~Tm
z7kC~qOg!K)3s5!B1{Ps11E=by{6LwKU4v&8)`E`j`wyJ&>-)azI5PlfR@_LIkvN#=
zgaCpQk&h#K^9HO0V6B}J0OxZdLRC5opT%=W?@YD>D0eJ0Yap8!Z+krBlr19_pg}TH
zgO3f(z)DP=bfp4VtNDys_Gfe!X<M4N8w5`YStbOG02g|b*!re}hZfaN34r4n1D}qJ
zp0b;pcj8z7{1Q}JK|n!<B>vDffSECOQVz2n`{1282oVQ8Sr09PS#&n6y7seNw(l<m
zv_r^7BUBO6kT8bWvZN08G**w>dC>C~yvJH`Lv1af0HF{l`uqCynkj9+-I7yfYiRXi
zsGzl~p(;YF_~GmQ`0*S4=+F4$0-ysuh{a-v#A1j>BZx$!D2c^UR#nY0&y+sc(y7#q
z)@pC4N~=(-fK^4J>moKC?8e{E4WT<dHjt16px_6%L{(v~3xDr3CwbeZV<4Ld+>n1t
z6C^R{TkP#gq5WbO7qTG+ybvkhBI$=1^ennB`{)?V;+<2SSa@a+O3NyWF1Ji31CDne
z%`f*a7viTven#X<Ic5sAgAfsixH0M??i#p;NQc0Co{vxd?+6md?}IyQ0Z`x(5*PaW
z#}R=-xL!*1n%nQ)3v!U)Du8aDIP(lj09Jvaz+%9&c+ay)1s1A=6@$jUBZv%~!QfCD
zL&+qDE?vS<D)k>u^f)<>9&jA$B9h+};U<TLqLna0HA0%<`caIiA?Z+2?GNIn)ahS5
z{L1F1V*X|8Q|S9P&B+o;<kts`A?u9rJ|SC0xKIebuTm~-Q^p9Np_py&Y+QQsgY*0!
X@0){LQk?!k00000NkvXXu0mjfHLNDj
new file mode 100644
index 0000000000000000000000000000000000000000..1f23c74cf28e36acad285ff232eb4eaa3d3c6b62
GIT binary patch
literal 1816
zc$@(k2j}>SP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyz<
z6&nJ+Z^w@S00x*zL_t(o!@XC1Y?aj+|NWlx-rIX`3;mL|d^jkUB2=kBN((mQ!^DwM
z%;F}?T#&`Y#bk~+wq=`3wq-$=WiXK}@grMi3E4u_kj=R%AtNOMQv}6=TBtB+3#~2X
zw!L4y@B5x-f85@>t8HnUWl!?vJ?FgVeV*U*oag+`d5D|Hy4TJH93yj$aH|mYMz~za
zd?Snt85Q9PArBkjQ4w_SZ>Y4Gf^edbjjx`qG31YoaH|nQgb)HEgdt&skdgOD`%ff)
zX9TUy^$TLt2C)2KtI4BoHo|5hX9@`sz=(_(2WA8Wg^nO#2vU%SBIY9t@_>-Lo9h>x
zoECtUubg?*5PL+JCqgwOMF1gDnIFJig+WwC98}~P1cmUS81#T^X&;@#7Hvr%!^$2b
z`1R?!`Om#iCMOM`_Q2`&Vr0J%b26T1!W}Tgmn*{fQdtCZ!_I_WeVp{r8uM{10hD*V
z{o(_Exc_+ofM6g%wAcOx?wA0U{`qvd5&T|=CZQnfbx??{^Jn0z^9rVtU-;nShX@|n
zj)keNi-c+_m1aC1|M`*w{{HNo99OLB8uhV3gfL>ERsd0~DhW;5H~=iX(T?zN7m7<u
z7Xm;m7K7`iYhGRHo6V=-=K!c`emm@2yH3amEC2;m6cHnMVo3?6BWhhh48$0yDntYX
z7%-nkUa}1jnCDw<^i^TAkG0rP9>%nV0;rBYRu!pWe&E6vH<`}?$RCcD(D%MT&x3j%
z)c2s)!{&<6wCxA0*PvgDaAm+l$DoI9FN`<pzjybMhYwbdVr=~yit>oHtrZO$TFTaK
zCo`x>0wi`Uy#*{^gkV(z{ui?SitY`%i2;&3U#y>>=D980U0PbYBNB8F@>7}xmTkl(
zjD#<+_dSX5icLAnto6})@;J`C)q>7T7Z4ka!uNa>mfV8dmM%m6+KpIHy)@^aKG))@
zE6L*ow(o0LaEj-@8B8szuFiw1jz>)C;bB}ZxE;mc{^RIae{VPT?R^rRmo7}`@vi-^
ze{SsM-eDXc^qwa0L&tHPJOHZJk{thN5I;TIP9+m~?x`Q6zqfmItZwbSSik83l$Om#
zG7-bYwzD{X_-|wCT0PUjn*;9sB!7|Jh7%eenK9aI`THw5#+R;Wz}FwyG1@PfS%hVE
zjaXLKIHsz(c?Q;MKcQcd=_FF?$zwVF4NY67tfR5eS+2mAX#u$Y$+et*+1y*FtfMky
z;9Fgl1)%spOOYe6s)dqC{+lg7Gi){@rDd~ozJJoyF=YTkz^bZvp4aK6)5HkzfFmqG
z)eIY0_`^v!MVT;*2=1)AJ4e}(*It@3fV5Ru3z|o7w;itQ)+7@NCl-q(`Vzz1ozP%k
z!ew8=MR&sDm{X1ZHIHCk#T=+A<}IkgyC+(ZO2h#Gz1KQ1(BFr$+4B&J<Rcl6q5XsR
zaB$zVSlM{b*oi#k;>?h12>_?=!(sq491Beu$m4hIdN%14tRxkn!C<Hqix*a*xp7WT
zA~rv>6IU;PJY^yRfafpAa3Y$vV{iUF$G>6Vy&z<P5HJD+2t2&F1W(kKjZX7@AFU_f
z#F@8_qVrNah6ZlHS|3FvvvAvzJF#lrMpRbUjA`OKA0-h@yW`)A&C~z<t3aAYZoxDp
zLJskh+HyR!sCde2o;rIN=?{-W#6edojn-%iZF5(T4?uPw$piGPkX1&gSrEn$KU-do
zhpHwI!s|MR^fOJERaOQlKqv%?p6+fPmx%25*AJ_*$+vpLSI}BjUlqPp{PNu%?0l~W
zJxO<RH>3V8L?RJ{A`yhcA%wzV1S9z<C@SWJOsGFt-=@?Dt<|f(Dy>4T0#+5x7j9tN
z(GL8ha|j*riGlbe00lq8IjRbCQ}~DWwe#L>r$N>en3cIo6C@FJEe>_X(0U_<zLbyt
zw2zo;G3fe;rY$-WF3v_%IDfGXcU*oQc?C0b4!2}72~Kt$&2Nv?3Gpi-?-BX595dP4
zK{81?CmcY2z#w3VxDQ-UyI9uy4w~P841xJIfVHCl`g(dM5rJ&D-e|sRHh$|6$SA?p
z00SA~%rGbcSOtbWi~h95^|VFIvrr|h7*ut?gHZovM2F%S8XUyXzyO9~v5z>_?d0rf
zaU5zb$?uAAo5O6;N*JLUA<anrC`Qzfbf_qHqqsHp@8A6NUyr{KaTC_1&~<H`(>={X
zds~bl%Z>0cA)7>ahY<X)N;$hsNh91xF}uz`xT5{Ddj11$-?f)E=L7)&0000<MNUMn
GLSTYIOIl$7
new file mode 100644
index 0000000000000000000000000000000000000000..f7567a7b98c76cc8e0ef78cbc6eb9f2b0949c4c2
GIT binary patch
literal 1926
zc$@)-2YL93P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800001b5ch_0Itp)
z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyz<
z6&oEhXUcj200#z1L_t(o!>yNlY+S_^#((F`z3bhzotH^$VrXn)8xlJY6M>Ty6+){%
zLxs{pB@j^cuRhWUXjR%Gm8wEi1=3Q~s+6`8Mp3J%tx!RI5TQm%l@#)VV28wslaePk
zB#vXRv+LcxbNa_VoDI#xQI9mbGxyG&`OY_IzBwaY!fyNPo-lCQ=v3}gq06assz|j{
z8B>vARr$AyyyjFkt1_@|X|rb%CKvm7%PYO@PUI1%a-UN{RZsy{!HM8h(BiXL|GkL(
z!YMu7T}`Pg2GIFZkE;^9!>M$u$P^Vp6`X2ua;OcJseuwYK}5-7q#{Zn*Q?0d?yjco
zR|H_mpLc)N3D2lXm8zH%5mitTnyW(=PmR%>3}~ow#8ikdM)L4pHsaX0r!O5bZZhbU
zpX|D6&U0^zq%Rx5qV>C0sMB>S%r1CdpgVNJXB!fHYF3iQL~v2B4yN<;q$0MQh5Do0
zUbyRbt9}iDawZh|7yX6Y{{%4q54-A}@>>;FswgF|V=CM?r<N~VQ!|<P;+;c#iLGD5
zb(!Ob1hY&gD`R70kIh>jtt<7ZaK)P~w}{(S1*abK3ToUuBR=WL0j@jUPh$Ky)9dQ4
z14yM(<Z{{eSC&NXj-5mm09v}YB_i){Q;{SdFfcWePWk@48C;2(&w)DBIm`@IML<F~
z!Mv6#dAKI>c1vW2FBR{(y*|Men<$u-i#H<^s}2u*>~roz0IJ7_XGoO)h~)EFK95Ct
z%;&kIA%4a4$J&-Nq|-QZCeP84JOlXzuXa83(T!husjZB$=Zj3M5^n8jSbF=WS+}hb
zDWDP&5aHqZS0VMS#9Ef}|FAVj?AciE>=_Yx{DrPLS=n>9tgWl7dpH>jh({SK0V`F;
zG{M<OdFuT(hDS!q1AXn$Cz(5MApq&I6pwxVOZX@P;5$$LhFP<(1)%?(-8}ciBjx|5
z&1_(3^)I&yta)*1(@qV;@Ei3F4b)Drv+$}$DHdYIGJVDjW==`al+0Cla^&E?a=mxw
z*7D>4Jv+9X)32}MzZ*I_Sw1CLZgB7YufOXw2!blW%zHUEU@8hQcdDxd&_6No?l=Bb
z@vUe31c1Z+dn>-Rc673AN`N<8<)OM1gd%d$bBU&DG0yFCxX3_yEXDrbU4@{lssiBH
ze-1Ew>Vpq4AR@H3chXqp@ZN@e<nPqW4W4AE%$_s1+#Wf7iZeqeE9n2ko%dEO!|9Xn
zGdes}e%Cl>F3FnO!bv+d=rp)nClkSK9i0{J!w2`3=}*>7;nvTrqPli!Aue`ot%#En
z{UvLTJ0fp4mjKx10BAiAK;P~iW%}nWz6lou%v*dj0EhPV^3I!Yoaexe6T2Z$yxCMW
zyY$>50%kO~br6JM`Th3I8_M*z-?*&!Ea-)qXV;dE<-S1}($v;oZmWPdGtKAo$MV^%
zP!t}dr~+bEPy<gio+g-fEnzH1^YtAQhnFv8U(N-zEhu=`wqQvaq}fDv*4)-X7>kwL
zS#Nlc1i4)9q4x#`ei#P9)qrI*jAtZXjT8=yJj&kq4J78@#ZsWPy^{mIZ&olgcm6`+
zi6j73@i?vRo$P&UTP6JqDwprQ@rcMwf{s7(r=6c4=>cj3k7XSC;Nqu$l@4l_h!}`t
zBwok$qgS)E7>IvcU%5mj+RtsD51_TZ62O5}9`DTs083t`Qm$4kU+c&}uOc-n;1o`t
z7~zTC0pDFv*h*(pqZ5ftXC;97on4h%xTcoIrk09#Z>JqO3G{;M<9_zfmla)E%!0*<
z5D$d!Evo1K*6EWzgfhLak=?r))qvxfEIq>+`WlyAI4#$;8>_&2RiwqKSP6u4!Vfy@
zxxeM|LFA9`A^Y={%$zj~3<N_l1_uW0f<olKwPM^%Rz}`VM}~NB7MT%w<411}^7vbW
z45o9Jml+KmCz(tVPbNtu;=~gPV##W1rcIZNDxrOQMW2b?<Gr1T%)}e!4ZIoM2Tt?A
z=A-=m*eFNGE)FCT0Sq}$bIc5PN%$LH?3YhIunUncftiI=S`ZP2bDj;yQ}mq9a557y
zl#NK`JR`Y?;jHKA*&MyY8TKFQqvP;DsH&NAuDX#<r!Rgrs|d=UZoEl_AFIg6RVS`v
zu5@?MLXgf*gj9!)&<SG^oXX}{_`wdk-(F2PryYvog$O4H2QPzx5?!x$pKzc4@&-hP
z1z83X7KF2)paOV<(Y$9U>p7M6r1Bm!!K<TXU<dJ`!wip(F*-8B=$SK&rc(Q4vfC+m
zW>XM|EfSG$s>%a_lrF7;Q!%F^u6Tb`r{+W?5Mz37m}^t-KK1D94?dsFo%K0U$>sdm
zqydyH{_G~_MCzT&Y86?jDjh1wIXC6fGNql$i=yu7{rBA1fBrcC1>ro!m-if+B>(^b
M07*qoM6N<$g0E1d_y7O^
new file mode 100644
index 0000000000000000000000000000000000000000..5953c2dc24b9e6d54335d4a7ef80b8b2f4f19d5a
GIT binary patch
literal 9816
zc$^(tby!qS7v7~imhJ_XkPa!Sr5BNumXMZ`?k;Iq79>O|LAo3125C^51*B8D;p6w+
z`^?NU@AE$AJ#+5Nne)eu)=*Qz$Dzgn008*PFnO)#aqz!}h4I{%>sMqw4?s69C0Rhl
z813%!1jAfKNgnX@-<#7`nEZ@jJHrgz004R0{~EBt^Pu7x#B^6yRlr=rKqtg`#fpt?
z0RVsj%JMSW-V2A{e7@3pWIQ3&FTQ3lCqrei7zc?{_?p3Ah-AS_tFHIqc!jh~id|ML
zG3za*nqEP9;BaRuOBtX+IwcY5eQr0LNER!E2(iXzgd!Hcl-&Gt|K?#*PshVU{p!v5
z8wO+|?})pXhmObZvx@C&lTb~&QN7qO6J(~wm6U!9p?M<OrHmDXNhdg>2pt5~fucm=
z=mXKvJsA&}^2Mv>B6iedL%yNSDL}oZ7EZABMjZGlUWu@5fkbC!w7Zq+|5nM75bbHw
z;R~RspcHWcV$2m9^hm?8uqHXFZ{CrW4U%2@i`=%&Asyr{0_0Z)YF3mE37eevblv3e
zz+t8R{eW_denu7&88(!^G92A{{bn<ORD}-c`jS+GDeyNr*FLI40K>1quuix&HNmj}
zt36;hi1#Eh#x}exxhfq^yZ?<bt>QNlxcmwUX&r9$3RJE#w2Ys=AAm4k?(pSWUM_q;
zqzt9&jeAS?jwKRe-5Q3id>~J%B8B1e`DlWA<y%Y0jX8~*aIht%Y<W?>LW11JjPvzI
zIQY~n2x>0Yn&1^QA1+@u*lf>Ph4Su8(@s<nWvy^<{vSHk-`ct+SYIRTd}O^hFr)MN
z_F97>Kdv+!^YYIWsIBX0NJN5r>pytB2$`6VGQpea#S^p}>_dqz%5x8`2W4(IeHg~D
z*z3cKDse^*lT<aMP)5Ma2esqifT9BZ7UDA2{JJ6S?ihTyX{7{cvKcG#6&|rEEGl@4
z6V|Pp)&U1p;d;k>*|QN1Fe>DKlEv6~EG*qAxe?Z9>%~V}MWNzh=OFaEhJ|3-WJ%<!
z%BZh%QC!DyFTm3BRAi6nsV(3xv$$Qk^_LCZkr01JPv-lKy}b@94ICi+#*W{5Gfk66
zDaz|<2N$CMQ7$paL=@gMHi?SOp2r<^VPm+TwRVasjz@ljHQ4q`k%;Stk?HM{%Od~^
zI^&4I!+vidt{JG*v!R0#?~k&PMPZ$L8jvGwT_-8Cj>Da2tk8?3A%#FD?blJGK~f0}
zkhQ0GN<|w$p0EGZQDGJPM-(*Br%|_l48-Fn`2w0)wt3=v61PH68mKEMfr1Cs{$ps8
zU%aq2*WS(2UJ%TDfD@*khm{Ro1yZwC2nKJE)9L|D2|B7k_)gB?=rA}gT(o008?GNb
z`U?$}&}Fih4g=nmQsR6S;{$dx>QBOkXv&S_fe0-h(3IVSQ+8OZge|Hw;DIq#9!&1c
z?$fFwR-P2!+~2Cb(1@ig0+uV(W2o47mMBo-*Dw?b@xeb}noGiZHa4HFa{Ns&IXMQ~
zG%@ZFgKP|hW8wKlfdzy^g`N9Yl`^Yz92||7^*@y?EP@llF28FNbXs$jSYYqiXp~l%
zf;CCq$=vUMP`;AeA^@LlzdP`oQV&ixR?NVMnJb#FaiCt!?5%LZ>d2CWis~_bo(WZ?
zH`{7dY=?0UXlT94AR-|qKz&_<6J14CPciAdA&vnLnaCqUqO?uSzV}0o4vHvc07pl7
z?`vk|xA^*ud0;s>@O-a5<13qh^nO8UQTGIE(o9M_j}Zr*8Zn^4bT3Lb3&ZZ`9NmY&
zF057bFad5<8yscxr*d+5$JFl&Qn$n#KBpt!zrV6sKF~$-(dA2U!^}<QX+8q;oF;W#
zy%<^lg%J)`rp7CwTmh`2vj9W`Q5|S7iIsd_cvCx)1mb{sRM>LM>$4ni-~I!KWA6v^
zE1FF>9$49-xzU|a=1yuX`?drKdDrq#(8j(SNR*WHNOTQdkGa951nodQ_=Rp^T`WcM
zm4`|i>hkWwc`R+A5Zdm?2sbt<Eq2D)Rbb8Y`CIT2;hS`v2vj^mRW50TEW)v3hM&HN
z`!%~SG=%ajE;as0aJ@6F5|!He-L~eC2p^=bbJt|V8>5zh9vMDnN8M-lf^2bMzS*r;
z6FKR5_BemUQ_!4NYrZ23($80i4POtdVXEOJ?vE3JJ`;kyIq~0mQ9%VN^}ogMCHnUi
zrzgE8fHEZ#b2Qhc-!V<j8O3{kO(<uR%aIUN?-tf3pWyTP4ulvl-`w+Y-JojFgn`K*
z*osmBc+pWmBHOL+e3McEYQRtXbDc@M9Zm(&70>f>J=(BFg&FFUQUu2AQDI~3<A(4;
z##-~!99gn5cc1gs>@LnjxD)L|bZ)m2Vfm}C&|Q|IqfB84lQ83c;8<qU2mrC*M;krZ
z7A>a4fhFOiY`XYbOYT%j_;E9BB-_dQ#hYDKYE-@>Z3jsj_N$1E<c`MES@Fg<^G$VS
zui14J)Tv)@e{I{<W~s$VGiPqKiS+hZ|K6&X9z5d2VP-jRE>GzCaDD(qY@B6*T|8Bj
zkZyf-5fKYaOX@d6&Ie<$!Q%s9+nf9|X@*zzN3Ct?)9OkAD+Dg{&=3LV;Cs6pvZBX#
zbwx*^y$@)w2|>qx0U`36GVPu-m2rJnT8U+1)J-Y%>W2omTZCiC((r)0o2c?s=aXy2
zM-9s0r3U|(ED{7swoptIkls{fv1_Vd)9KD#+~+IJjzItH!bkT%rv0f33-!0A;=v~u
zvGY^enAI2?g=kIm1x$8b?<30%By;Q}#$^B9Nz|xroT0hT;09PSfF6t{29crQC9~DR
zgfH1r`|Fm@SRWXk&ZhZR8}6^bUOZ1+RlVQbL^)JX_-P=jD{U4$U&$&~8a}hfk4Wy3
zTP(~^-ik>Oj<{3*8GPM<$7@r_a$dZX8&l{0w!S!ik}=+M5i_UOf>P-1@ekxe@hvi}
zD3E2BgpNl3UQ(g=b{XlG2XRqn3d|O#mq4s4>k1xxkLWL}b&u_t4M3c=EeLoX7<XN^
zcM~_;8@}t$O8V?=WAK8ZCKmgK#+=)*f!F!VfXb(M9ffWTdlHj#0UXsPAtoS51Z_PO
za&o2(clcEEl#|P7`9@r2<u8gNC`(oP2P2DRo8UGa1Y)h9Cc4|^1v56IF%kuAu!Vb?
zIDsO2fm);pOP}c8kduf(k0k=_N{f$ySA@et%6$CVgwi)PAIq@sNK1pJ!yi#Mwtv}c
zY&D(Hk`36O;5WCz^D|r7WJ7Tg&XqF^f{lZ(=%_c@!9u=3m`*pzH+l}$fMVx@P_zeT
zw?dJOcOPF~2fq|f%bgS}?;Y3o`y`K$WulT}I>;Av&TL**Yz7YgaV$h-Ue{rd-Xfug
zO~F>)>NHJ7^!`CN5)5d3W{82z4NT*x%H<j1@~CQTKI&!8EVAok_O$ph!GoOs0b6gk
zbZIs*z_@yULdTq`N^wEN*{!|E!G~n8CxI%{chTj`M7JGV!Ze!%;3*FY&$9YyvjYxn
zM!nNkNE=RCDPElVyQrmXz3CH5GE}f@Nf6o4UGK5gX;vNHL4^Dw`!wb#x9~6>^yotg
z#<vVe2syG9vb-T#E>QJdX43lql~v;$d!z(x$RUq;<STZaX~B!>4N2X#7%0<=h1c3Y
zu@^c78)w-Y0h(gm)<uuaGKf|Pqt8_&nuOIV1g?JynH{;ESu**)1l-sn`<zp2Bqpo=
zP=wfKvDIzz7k{-d_s40pTxggZIxI`l6P6d{hh{UEECv}uT+NX2n7u%X?xDKb$GhSZ
zRkN{e(JF(x3TGV+hy19?c-FAp-o?A}VI~bduBD(N+)oiHLw@S;9r{oBeqBqt-<ME(
ztr5TA4`5|BUS(WFzSZgv*>pZJBxy+w`nZ1l$IKcBhQjF|Gj}UK$GOdfgLJCjgEcFp
zG}_@X4C7hBGUo`9fQ9t^PWvg;Iux3($A<@bJRg)We_a^kI2>CxT|IcDaZ82t*JEDJ
zI&lsqTw%S5p={{~5WUQD6D>R;2I^c1GbPvtqAB&$XMK=i@`<){5KjK*8@!&*SRKJ_
z%o*2AkbtK9!vD{%%*y;|*YAP@Y^*M+j5PCl^y0mm?~V>;j(h6?inLns;T8GCyOASV
zbR()zZB}M}r`2$X-5@;{Egb6o2^8%^L5S847lp<^^G@;3YJ)=Jre2!IGQ^IGb;9*`
z3Q`XC@+vwKd|cl>NMil1vLekUkff_I%^6aQVtF+$h)fAOny@gDt<iEekN9=bjME@t
zGvfa5<r?vd&e|QSN9#c2nW(AX>O}e|*mPsEp4siC^6YKY_bByKCMgR+-w_o7*b2#T
zr(-3RAe|+Q+JN0zY{DsQnp9SLdBj+{>7eg$Z8-3N(NK~7d@~S>?(S=jo(1L?7uA~=
zQk+6-8B4176q|2sZZ*lqsU!SHeh++gc=J-E?#TZ#jmT6dor4c}YcyFyCJb(Mco82N
zwELU6N_5z(&v=7}nzeGcfYwqQ^41wLOMN8BvNs|>(`Fpg3eh>GFMa-eSV2m0SA#6-
zr+f@R>AgnOuf!jIywp!rP<05+)&EmMG0|jh+(2${=odwX2$0OxmiW4-GZ^txvwGm@
z1rwHiya9O<PsYq^DEYvtI;}9v4C80h;cv9^DBlrmTk-?eO^l5Au&+MK=2xU5keCy2
z-w(03skyEDxY)iDDkhTeJKf-0V%m$t^2B!EkAL&p@Fuih(;_8H-J(&q1x8Dh)!C@E
zif`}mx9>_~KDC$-yp%GcqEjlGL-Y3PW=_Xm$1#pC9mxBmzD~YwB=iPpGnSHl=^>M!
z65Q$`_5G*ZNOejv2d#1w<KS@euSODY^ffY_R8{?v<o-Myjl@=0eh#*~isT|+hHbj)
zGE;y-5KkI-3Fl#ULa@_!3dd#hT4~;)tOVXV81wod#uOk&0+wkIa2>b^ur*Wvhq1rS
zXZJu$uXODQ>;nE%5Qm<%VDJd*>Ok$%ClmVQ67EGFR~y}(8VDqX?UjAcXsuC3J2TLI
z#Ui6mJD;zUva>T*?U#GR2xb%c>tKCGHUX|~4DGR;>gL%)zG_c6K85Due4iYA&O!h@
zw+UR}Ky}wnoiL#X+x$#Xdexxg9$s{Sr8!9zli=#U+qxy<jm^jThAal<j|JMH{r7n#
z(P5BGanGIv@Y*fg6~5(m!$8))zMRvLVthwnrV_1S!XsK+8vA9`@nGMe1vkX=m-(q#
z;y*77;|N4mWkzCuDpjH|l(U3;=8u2m^nk}DN3We!+H|Y4eyHS+n8eFUYm4@7AYWZv
zs+^rqV+rXjtpU#GhEb<CMLN(u0`BMw94}8xvf|u=ay{duGBUR!?X}qzLPgzw<GEI(
zy}kA<<hj*44qWw1xw+k%`^eSI{u&&43U%YiJ&b{gXi<n=c0Yq2;SeP}*BMfkeKyL-
zQg@`&l_1;Vnfm@%BwQ7n{|C8)OrEIKI~Aj_puZLgB_FuOge-n)T9sUlPRilbmgkhD
zG%RSf?vv2lmX!p%uWeZO269T_7NUYU-Epoe%ZLAU?Fqv{u}4M~S{FKUuWc_{bsCQ(
z2!vC0U<m0x>lJs|JS~}s03&O9`K90#Oi<baH#_t`Fq@iJOXHQ(@IKbNY7#K;+<Sa@
zpcvT2KS7@(0DrhBcT*+<zCyp!<~M)q^t^j$quBqwDPwD{t+A>VQTd}bhDM~9Aqc*C
zH>G;KkgL1y#3iV!^S;Ev6vsVG6$K(A$xi}}i^Ea38Fc^}kkPAbM9A;k8VL;p%(a(r
zhLB8BJ-E?1Atd-<#lG^`9}dvX9yAzW=GCXWl}f%~O0q`nFGg++W=iB{Q?E-J#{Un!
zmM!g;tCfUDVKscU1n_fw6ne89F}O(lTnIpx6a_x@>k;rj^L)|^c*SLTFd@N?s)GNY
z|85>mPV3cUslD+pN%cUD(j*Qy5Nrs0;8{_AjV5!@=Kb$?*s~)F^wvYaitsBodzs-W
z0;B);G_{o!qX!d|p2amH@N6rRC*vHuyRZVlNif7mZy-MQ9|^RA<E2+m!l>!@1=w5E
zM7CazMWF`EQyzZV!T0N#AhB12j8oqr3WMDGQpV~r*ggAhV*D7vz4|q|6IGc{!|56D
zY}+)P8^?}zPJgyBM{*(3^CGfvQp1s`zxsnm@iUfAa^Xc=n%j4l^lxA5(=a0j(f4(o
z%#W^I`%1D?JOV4vLakrK>+v&<l^LrKd+?qE%N;wqmfI)=XaD=bj^n@3RJ*_Rzpy%{
z&erPR`Xcuq<v_MOIemaN^{k?vCz1*p7c&=9^@7~65A5>E(6{JWHi|CF!IL`)9L32{
zZ58w!yAuwL_C+$SK1n4~M4Nt7?$WdHS6>VNcU)p#vY<)_gPHnx;b*PFtyp|_2<vvj
zu&(k|;Ip^pYBP&@LA_^0n2-j?=M~!>M(b6Q>anO0RrOOoE9+0~@tkl}45t?SN8Vxv
znK!q7VrI~^CykE>J_}cGfn}6Lu6DF0$NIYgw6Ff#O8NA?JT4wRr(yY=qW^cK=0$WR
z*?I`%wOVJze=9D=OhPzEZHDw_)M295|7Unq=5=0vxT%WywnB9&_fj9X?CYGI%2+1P
zb*BRX^0)3B@!Mcw9(~B4hx|V%E1rR+lJZuJrk@jtHuo|xOu7Hi_`PT#iUmQt;qr3a
zg-S9+<<;^&eK&1mL}U^E#tY8}tEn<XQ!`v&&fH5Hh$ynCw&U(|q?O5>8Y8ko$AyXL
zWHoxKd53$&_mPs&aul^SGN-t{dHVZip}rqvR)2MuxiHsARH<SwBIoHPICIu;Lf`iT
z*(yw$KO%^Lqrt+d?e*rM!Yx@fG9?Wjd}Z*8=yH9UMapmg_=vOk$lqGlv?$)5cYs77
z!K$ByEcg%ejCPj?*ys-aOOvuq^fH;9k>v-ojz8s;LMZkJ+<sQ4o2yKqGBabW(%bEa
z_F@n(qKMvK-5aF%wW%*9zMFsgE_pyvch-3R^Vxuxr<=2VBaP>CqFoorNOa`-G3N@O
zi1N0g=(-G(M{^JtmeDm3oAvZ`0abOlng0Aqwa}8e7X$i#-pBaBi#ze{=MBXad0w6*
z%t|S0*iuJ~EYNw5`F>eng&&29nF&8MhAd3JT3+KNN_6N4Jh)4Th1VG^kG3~0<<XKU
z47<+r?cV^L?b4&$D4QeE?cMs9S>|yC>~2JtiSNN<=d|x!WI{g~8LJYQj<~Kmvyb$8
z*obgnWEM*M58S8}Y8am2l1u4)EGxKP!fc?AfvtO=!}iwZX4H0Kbvn|yFJi@TH?`i|
z<Qk<$iqx8K<zqe#HH&-=<>(BV)0w3Xdm-@faa2DCXHg~;7v$j?(8%(;edSg5<TB%y
z{;)P#0-BUcR-Eh-ndSJIxcA-KXzRnmb?hhp{o(IM9ykibyS)w80>|lBahs&kM?t%!
zDfSbv$K1SxVbvvJF5o8fkR@`|t*GI1G}FxGg~Yxo%?%Z6_T=hdg^(HZ_I$BTs@e9X
zuBC-e9}X6#8eLD(czl8*TlKf%@d)n_y4taXH|Q4HJ1xhXPG<9Lea9WBh@Jgw)N=-b
z4{W|FZ|Q`cfF3Voh>p(}LD_r1u$4!46zH674dGZ%eT@k}`}Ea`cSK6bfp^S%!QC;7
zT6ol?n{8dVX%*kvNY4K_j})F5hRQ!~#}OLu582XEolxPEGYC)($U{!)Jn~2q#Xs*G
z{9D?NzaaJXu5ZApAMmE{40RlE91@ET+ZpQ`Wec@xL|tS$(Hzfd0!N>>ju1c!idIIu
zKiBui;OKXa6-Vh4lOWJwAcxTf;ih1JCu`in_=LC~22xWP?Q(K0N;ECB>cQGV0lnOU
z>B<xY#*SS7C|)xsd`(uIn&idQx~V+6oFm$%i~>o5m-52ppXxVMxIVPZ&1nKlTohRH
zOq~@N)nL6Af`D8N0)W8NKOTn%y=?WR9MK^8n%4YAxTv&T;8?lJ097mpU;Vr35P?=Y
zP#auS?`xj>yN`9Y{@dYJV8Xr@s=JW&b5`XuMAV7O6n58CNIs~Zf$s(uGL&ji5!EFY
zGeH3&uCsr4^zwGz3MuEIbe*3ZGWB+F^X=Lm8N`*{b0A<OvC`8nWuV1Jfn{e~QmnkG
zKj%)Tp~S9nivT=J_keBw5GmdP6TN|rt&zB1P=Q*rEQLLm-j|gEv?<cb2r5B&M9N?4
zVm+svud|l+gawZ0{DRXY-du;R<2T<AcT&mZNx=v8^sC$}s;eYYOM-=akBeC=?hn%H
zO6$p7%S}H=nMYPAV&4Sp02M%4SQQ(_HK@^hLDj3x$#Dgn#eqLvG5G#`4)W$qZ&&`=
zp6M41F!Ea8*Iy#8G`|T!pn%ducF`eY11jDfz?3JmwVIRug;Nd2=1vdkE_|h_d`XFP
z9udE-R6&Mw3(Q?acV_Py!T}lzla<TUh<AMAZRBQf<l;$mACGyFlkK)aPT-V_5U?do
zX^np(d8OoTG3^p1g|DBG@abq93K?{7kDBu`Ux?>OGQp@$uq}Qisu<PtyIB*-tl`W0
z^vW%{y8UtbQ*6=UPQKJv{VNlaOIklPKL&4hXwzLwzj!4EN_WWgp6L72e}hf39ukIO
zc*RnYpL%{m3M*%LvmdaBua*-g2}v1X&i6Yb;FE({r~r|nm(-mKJe%nav&7K{sDqmg
z{IK+@>hT>*t;vtIeqU(yTxY>_#n3VlX9@WYHWR1CAw9K~jO5CAavFpiwUF$i&(E5s
z9_|gW?6P{gGiR*x$QllIHT{~_sv9cR{LE**``%a9<&`Fvhx<q0{;2&b{8rR{sH*F#
zCnD(v805tAAYjNP;HlYBhP;yMwdq*z9q>kQ**?&c15JN@KAWE!-69z<3gT}>{&NTf
zfC%cxfb`1V($*vELv&Li5P^RjW)q(YAuB*V41`0M3+tMJyDO(N_UVphqKn!i0LA(3
zv~iS420esFqXsM5+uqU)mg3gzd5PJ-F|Bt-`-$@<>i4h5Y5MN7pR2zMK$VIWsyY&!
zICcG^VkDPm>M%%HUt+E;-72PT5Q0T2i{!=iLJ|flxwS38kVps+ZX&n7Jg)1oZ@x8Z
zX!S-~_1J|6sc_wV*7jWe(rb(=rQ#hpq-A^Z-6wmB6m@>N?W0YSR;e1zoJ`QCK%pb9
zB_lkU+*soE@oG#ypV3*#2)!18_+HhDq&|o?ay=mUAI>4p`DY$btoUN{ztA2aUtZ{;
zPC=dbN(IuHdh@1Uajn&2)@;Ag{L?-<%R9K`0-RD;Y|g9p{cdCY%@r3}f^&NXS8lzu
zTuIi;GA=WMrm0K2y)!4`@qM*xq4o46W6Ay_+-O1XJrYQMxO}hd1+w{~S=`ovN02gq
zrfZDixiH2!v*ZX!;N_E&)@xo4+LwS!`!VH_!msO+uVvS%{#Ic3@Fh1U1-o^Q`Z(OW
zV~bQ$eiVg~S@j7~=IW>qG=kyT!7pEiV|_LWt{U@7cQk~rBH^%_Px8kTMlgW{NXsE!
zS%uZo!prF@c*ii(W2!@>79GVV_#<{>ZLB3mG;5?h35VrLgf7A>$t%(<H25HP*n&&{
zmciOR4`{i1acCheyYVKap$ce&7u}Qo4f*S}6{nUJIc`&G?w{l}6QCjnJY=SIzBELo
zidhaXStgVh@{w@0y!Kqo*6RW{^R@D-7&({tK>9bJ<@<|oe;E`u?y9jV@4=Jdl<e`R
zPN|4X(Qu*nyz74oyj<>(mjYWh04f+PFvQtO3wDoi(3`4w_*!RA`}(&Snu>{e*A(Xm
z2Rur_m%(^(h8z1iDxfxn?rDkIVcnX1NgpW$#MX<hmf##iIQ~8}Lv#@!!1qO3e2{)0
zB}GZHU#${xX?X*4Fr})m6L0w>7K!_oP-2LCoO|QPkG6PaYUnKkLRXAoQxiEc_;hlV
zU1w8Tuq@5s(#?)VK~!b3@uxt~?eDZs|4V%E1Fo{;Av${^3t_$1CNo5RA$gPeT$sVd
zCqK6{k-gIUGy1r({SRrO;PdP)wZk7jF8wE@Me$xeXxP6$Bfc7;9_EAZSBsmhH5AOc
zZJ+hT6+eq(BKC5(b1O9McOwk*=cU%O6DNN8qj}+W%z)MnTMmD7`5#3t-H!zJTR!Wr
zD%(**v;JK%70Z?b?HNwIQ^P;<{btuA#%di2Eg*E;uc=K(e(=Smf!<<+f_T^UZdK{+
z)+p?fKHgzTZZWUK7*Z<Yu8B^V^807ka~WMCm+lYNd^~umGk-O?-Pqo^wrFW5hV}OY
z7>?SA*7kYaM*cW2$Fb$P(JcnNnSErgEZ?c7O;!r;K*r6f=bq9o+LVtDv6LVCo(RHr
zj2y<~^FKb+DycgMO4J~@nK|a9^b0BKuv^<=$9-3uTAKjTduiiisLjBc7#iD=yZ~#Z
z6Uq{|TQHYzaDL=&*jM-mS}s+T=w5NJW^gQ>if0~I&(wC+L4lE^->)3WIH_ePl)UMX
z?;$VNkaSW{7vuC6fFaxE8F%44LcnKRKjNLj3{8J<7eARbC5AL?M$qxc-#KdI<2y&~
z+0YA&9hwwFC)eNn;x&Pi6y-b-6=B%((;7ce-xAY-#MNh=bcKR9!ajcd5>uYYd@zj)
zeqgX`#v8%}ZC58p7^*?@poUV}FEWW&<h^O!Y3vT6^C5$3+MYxybWm{}D=YVg&zgo>
zid8@HUjNGdnG#%2C~QI8A4(g%U_pEt|AvEJD#(RR>j;UmpZ(1sn=qL43Y_IrtLHW?
zDA;++ykj;wmGZYg1{W01vPPY8VQitpUA6-#xwgp*jZtim^veeQ0<S|AkO_2p=1TES
z#cM+6=4=~}Z<4AaiJj_s0_nTk*}n(Ro3S&0n}wV@*;@WQ$}z`AlS|5A4|6#tMc17X
z@3Fd$|7Yo!bmnEO=i(#rwr|)aU^_f$f=&WsZ9WT^dg#c$21DNWqm|cVrsl2){n?G)
z43p#+$MKb~XXJkGuDc4KzOV{AuqITwzmjqKUV`+wrxq6m0MJMN`xhVv2+4MTQ2tp|
z@jwyo=eH!RBa$+r#K^j!mdAgoeH)KyxBj+0L6+%SB(x<IdLj!F`RL&bMG(qeUgmqs
zA-ovdfRK{rw?8wy?v1#3P#s--BDGB*%MHZRmB}ugKewYD|I(jklCJDD!1m6xu4GfO
zSGbFvR3+3?NPqd#Ku>jN#~$g-gXqsU>sq7k!p;Y3Y&d6XjK!1lb9K9mS+VOic;6gp
zs06gaN{|T1OpOa>P=i1b>VT}&fZmQk@HOi(Tf36Sp-a)q4hNFe59P=2zq5svx|ed?
zH6S~dEoLbn`Rr5T`H6naG1WymZM-dRCqh<w<R=ddxHjXgSHcqzD2YF}zE6yZP@`fy
zkP4{BV4iU$t54ow<{^@h%xUXT4~WG=`8VRZ;!gEJ<o7p5jPjuQ1hr3oYBdks-aUXR
zi$Ra>+9F!)(-a2g$5Zd5EYKzWo!y1Nj4PEFbuPJ7ZmKEE_&)c`_^QdX)h0KUo5d_n
zR)%_kADr^L&=nIM%eORlbrF>7&2KA(xmY2eg7MtXYV~sO@z}j2p?581vLjl8hozgd
z-P!rTNss${{HSRB%=TpibDCxv;p7J?#+47$j`9a{(<i-xh4|7Ruqv9nxw<M|Sn2fv
z$_b|yR6Ww@nzIu!&3X=^V-4&8L)s!dlJMXF&Jwml3`mcTM{<SvCaQ8tyJ3Knl{y;Z
zLVe#|Mof>_c~i=_e#80i(r%+9K|ulA@izKmx?Eao4cPG;T})ZcMf(W>**>-7^5-bp
z!mR3lrUw;3AWsC_!O9D@zG=lI<)TfBnio``4A0xn#WzP>3fqUjeR;>dUwU|YJv@v7
zH_>ZR^Nz#$7Cu}KBg}=?808m+8z<Lids_sk2Dav(;T3+cI&Lo6OinM<y#3reb^OCg
zI_N(9w36qsDl9(CU+E`N;Pq}Ht<WyeFgcAY-Zv?e>l@%wHf1+@c~NqC%@3y@<VKvW
z!P)ciq?y#N@08f%sr@o_4E5+$K;P^DpRF%lWITHT(k6@aL!((ad*xhr-gAJqk2&IN
zGzo}58u(J}1cg})+0phV>pCGxvHjeGhCr9??y-q9?cyg_D0`n?1RBMAS*Zt4cqC-`
zLkudBbPUIN7G5?7`W$N(jfdX5EfgJo$9nysz3Ia}*;&l%CNr142TEv7`MWQB8f_R&
zIQb2FCXjL$=0LdRmntRZmx&b02MgIapn*UHG%qmXy}Ayk!mPK3LIJKy(9mq+4Kk$l
z8wNZOJ;Eu^C?4i$ZKg|T0$I$}J#WQenK_M+m&9K5>-1{2+gd~opn1M|%4r^7rPNH7
z61QXHsV?v!gm@8Uj*w9emE?m$_1x4%n}3A$_h18AtE=%Q|I3^*vkw3&c5eTY)c2b@
zogx-u!%&~3l~0B*fJavv`$D}f(M}`!g6WN;0D+0yn^Wr7VW#LjO6SltO%~_`CNDz5
zOkH?h4xyofXw1J-DPlP`TWtI{YB0XheJBu&XZ?FWZJa)gB`qQ?DY-`GjH#K}&QYN`
zJ}EPGVuEP+^P(kS2>s#U#w;b02f(8sI)V;6Zo_(*6GmV;RLXHLqo2~eLcQX5QuM1>
zrbdNT>~2|^cGmDJh|v^{&Bc2E^~=4&7JneMi$I!U-)Cw3GHu#AA2VvB!+;y<Sh!Kq
zNN0pN<2d7RU=|!I+%lVuD;5>hQ2jEI9W?0{s+As#Tzn50q8XoZ#~K`p`Wm;Vsh{9N
z(#CsdonCdtF|&YwDj^&@A9#){CdOR?%<ptpdMm`3p&Ioa%7$_grISp?JGB@tNpDyG
z{tT4Inbi5Zf&Rg|UB(RXqBmyl@RyWa6n3Y4imyBy3Nx(^(=DUfvEnu5Ih}U5hC}A>
zuj5ckXpFK*J0GHE>_J8`{K*2X%Ig|Ax4)J|%M=Ad3(d)OrU>M`H=INFk2+=i$N!I!
kQObOl|A`Aid4K){9GdcB4n7(B4S0T(71ZP_WZ#GW4-eLb>i_@%
new file mode 100755
index 0000000000000000000000000000000000000000..ab86df2f5872b0126a27b09d5e711db515d4e301
GIT binary patch
literal 1518
zc$@+51rhp*P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000HGNkl<ZScT=+
zeQXnT9LMp`@9uiP>$Tmw2iCFe=4e6OSa}o((1hRv0i6W?5DkW?(Fkfx{6~!vgNc6;
zC5G@INVhRiL?9THASxn4Kv>z6o23QT0UKjX+O6B#Zg<!F`3C_(7#qlg3E$-R-~I0W
z%01+AgfWKuIoy4%KQI8>XGFYjfD|uLdQae(Yen|Zdk(Ob5=A&IRc?BFll!3yBb!Gr
zcTKow09zSRgeK}MU9=%P<Zr}d)28!$SUMuVNv=WM6@aab<ntlwD_vCXsHv>QUurwf
zb+kaV@d6(ef2RxnLELeG%}W%%kye&2DtA;Lt3{U)MZ$<<U*lfXU8u(pm)(>m*$>mF
z$+$ZXu&pBsAEG|*;xb2dO*Oh%6bZzz|J*M)qc?-g0FcFy%_*W0<GSfALT(7i-D=}<
zx2E*_>fA8?IZ?PKlh6A`nWNfYg>E5=1dZcB=RTYfnjz)@mK+I|h73HM>nfJ4d{f^Z
z#)N;LD0_?99IrAq8^p-Vf&5(S{CH@fcxo9@$QhH*`&OBws<9G1v<H2x7l+z^LyOP?
zIg5u`kdgdJfJlVmgMkCV?p<mU0Lazfg0ynZ9BW`({7Zv#B+iVH%kurw!+c42q2APA
ze8^@|(M}NG`o*P=>a)iXOU9tGJ{%1n#<@f@BuZfxWJI<n5O3`%CL#&;e6Q=5_g?|n
zR}iT;gl`TmIWniGrxO;=2D?2S?q!93Td`1b@dfQVMDBL0(ibp%YhPRMsB5i3EE$7l
zs5sVn6m7ldK&4CZ)-NOIYVLAFWP!vkreA#y!We_&6WN>|9=c`a>#OFdstUq5#Pk>h
zo=3Jl2am1v`0ZollGbNqR}cj|)0E!h$;vgauFL+Ttqutz29>F(?W)2B^*ku0kT?k;
zZyTcR9mO1nVEnsl;{ZUc9}$yy*1EO)-3@c8D1s0UomvMpra^}WffrygS@B}|0)NK1
zl#<Y#aMOt0SxVfm`&PcZ+Tp+0fP@i;1`YK+HE7o^K%x|sGvm*dO^C)LZeBznw(<Hn
z0B}r$%z<<HnvdY)h9&UF{(wm|!QhifaynwH2a#kL6|a0<6s?bcH|giX1=d53x;3w^
zbp)fwq46r1iQ$CqN4L-gd#W9FOB#-Q&md}!xJ4)FHx2;2X(}|w(9GIaU-)U4%W2)&
zwGBMaBhRY9;0)+QhelK+NDR-9U6{2m^y|D&7cQ6UyK12k6-hpclX?JA(gBNXfmO1i
zYE1yq)QfJZfCQuO8~w(wc?d@?&G*<k(kn8jraI5(oW^j=Bbc7?I4pt{y(|Hp=n#ki
zi(x|>-vR~(ooG0z1`sjApdy9DOE|Qq7TvapTYQKG&(BY2H;Z2b0D#<g(x&NQY;r!S
z3^R=)FcUK-rA$K}RiF|TI&=`8Kw~O&q9LT8L?<E;g-h}M-b$$HF}JLkg29<>1IDid
z0D%1i!K1dbjblsP!?MQNp(a&0=?Dy$MuO*fXhcJj=s0aOB8m=BfkNad_EsDQ$xFJ^
zvn;_QlLLc_-w*%*_T`+X?-Z$+@Z>nBYepUtdK{^|9R=cW$efI`tO;GD6I7ruaUyn?
z?T1vzyK^!!gFhA>9dx{3003l`n>=wJDkjaE;2br3IQsNn2%HErXNJo4fpQcgD0Y<o
zfK<2aF38IbZp;1Ymf|-B06_k?DbqUkX`3cKHGbIS*`uLB2L~Q9WKbqyW9c?zPt0(S
zaOMZUux-8N_<#Ta81-|Wr)77f!ZUY@bLR9J000xCSXWk#;;BXMqC(fHC0N#bJ8=L2
zV{E`RrLxeI_MSB~Z%+x^+~;MFmX2Ys9e=5K2m6W+X8+CBpbwncFxiv+Vdm*ctH-lv
z0#6igV5|OfoG~`=Ex0_hf>VfDmZx$==qSihLd!Yt?O*n*X3&7UH4nzG+5Z~wHz#We
UggAPbj{pDw07*qoM6N<$f})Gi!vFvP
new file mode 100644
index 0000000000000000000000000000000000000000..9cc2a8b0892852068bd18c7660c0e254d261ba4f
GIT binary patch
literal 1903
zc$@)m2ax!QP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800004XF*Lt006JZ
zHwB960000PbVXQnQ*UN;cVTj606}DLVr3vnZDD6+Qe|Oed2z{QJOBU(0ZBwbRCwBA
z{Qv(y!$1On0AgYoU;q$61MUET02*)y00a;tF^c$fD-{_S7!83;AZE13rtkm%KbL{T
z!~cK3ANX=(@;RW;ACNF1vjGAKrvv!(Y6Ten{|jPZWXuQJrza}J!=NB71jZ@~!VF?S
zKFsuUSD!Gv`|zFN!P9pP*Y3Ok+574Lzu(*b{d_m&>+RX6@Hqw`fEck`UegG)G#_Xw
ze~5=3gPW}ygQ|iE11}F70~;$d0}~S?&|QomZ!`P@8v74Ofbh5PzZpJ!`oXaG*lmX0
zM{YChJ8>K6hu<gu{diga_0IegK%;-7I|Lwr7*T_|+K_>fX+F?m{ls8Xh6o=627W$v
z24*HE24-ePAcoQ)2QV>$jRINx7li-*17au*<p28hm*M)IR}52^90NP#-|tTozg(YK
z3$*4N5dVeQ2@pWcXqNAHvQ(AtukvHCH&<rhU}pjPmI-Vjhz9wbi4jTz9m0SV3je|Q
zKLZ#-{U|KR&ER6K3XC>khU1r>TQKq)YW{kCd?!%q7c3+I0*D#e@`NBW{*n|222mky
zpd}0ti-0sEILH~m!OqA8v6qnnW+{^8Ao|~bIR78iAxd(>3~KVC42RD?)?nn**ZlS7
z1l$n-0R(mcyM)6DM{^bN^ax7^Awf=vg~*m7(TG$J!Lay;v*BV;$NYmhMqGp!5)v1m
zssCe>c>eptmFpl!00a;dpKeVeFh$EJg;+4Kvok||@*l%z|Nj4nTLzD7Acl!SEJxOh
zO0xi?Oi5Ol!OLEYftg#r0%*A?5VHXU5EC#g3w#{48Th!_!M=oB{10Ln$R}`%Q7lJd
z|ASyu$H3AA!V#dv?Bl4#z{AZg&LQLN29)9f2p~|5>RB2pfD_g4-+v*Bp}zTtOv4@V
z4=L6EgF6NzB#@#5Wce?k*`UPC3-qYAsssZwhqwjE0RRC6E{Y|9@dJ_sDf|k|%P5v2
zXD=l7A2>z}5wISZ{(oQ(fy6$4`2|hXObm)L!m#wm1rR_i;0ggO0l|NM|6}<6;|~KT
z2Mbbp3p9uU;y^~m|Bylmo*1FQ3=4L&X!!l-AH$cgzrYC?WIjmkx9`6|8bO9I0R#{z
z1U_B`7N5wD0BQd5^AA`vBCZiW{eu(&s6K~A576hof$SeZkAN`9!Ep0|)?T^&0_f0R
zUqBuJ2p}d<nZ4)OEwCgg8bGBTOffk4{v*XHEFJtob<{sFMwEzu{y?G&J#<0%_4}_3
z_n*9F`2FtuaZu3=5I{`-|9n}p>&Q)p`;XtjUCIo_Ow3GhHn<38VPaqbVm3A)W`$r@
zVBG)`hZWIGX!;<&hGHPQfBr#+e?MLw{QdFz1E2%G0t67#mm5>|{QvWHUhTx~4Bvhr
z;tIndK+M97s1sONnBa8-3sfG%Vl=#d_hp7lHy(fc@$%qOpyls@_!B??fl}f>VEMfN
z7q@ZHsmo79tbkdPpN|u%@?k=R05c=BZeW7@3{g^I)~f%JO3nFePch71d4l2Rt0S$y
z-<~}K6n+9qe*ggltBn2ttE=rFfAZ;XJ9Jk;QAUVC8CZTZGcm!_1tf@>;AsTJ28R~N
z0a$GQ4=I5dp1u6U&@yc|!^Yj0zWsQ%vkK^0P__IRh+l(>Vt@dGIpF`_Z%;o1CAa?L
zRASnF{E6P#D^J<@c{zZM4-qs6z!EAGv|WJNtN_^!vUusH^9)UscQM?$egE3`$D5jd
zf4F=RDD?=4Ujp$DkWzpELU%l<T;OBjQ&r)R@@QmY<+GKR6yy%^&}Aq}vO_q8nF&@C
zqZCe;Z@yqSe*PiDi3^XwjgtSrKVSRx{=$l%FAjiOMQ?!^)LeQ4#6Mv%1Q0-sI2x)P
zKrG0@qo~Lw>szg@t?sdXZZb6SF*1Dp_KTsme;31}XYav|`1tt;!`0g_Aw|~jZx8?e
zczNpg#~Vj~y*YIa6wgr0-vRL#^yV2r0I^_kz&~iK<=3At_df}VNa&<Tm_wRRK<6&m
zaGqiE!lMjt-@Ll^>)V?ve}8>`@%zWS=l}kE{rvU$(c4f9z60@RP%4Mg-;f(2$N(UK
zSnxDh|CstsG~wi6lW_pHj_y8u%P@WEafY*(AAS4u>e}k3XXmT}s`&u*)lX=9?>E#U
zWQ@0U3=ly09KayJ%b8%TE6cF!&@G15+b%PF`SkMit)tT>e*O6LDKsIyf%^6jH01t5
zX`=gk00D%vSsqugQsC$BKcK>b;rFkfudbipI`#UQwI`w3=Owft`2n?%Yyc2II75Jo
zgE@$Yi;dy=vpWmcFDP9N4enP^U&9g;#Q-3H@b!#Xfmj68T!6;yD`<-TMM@A80ssNT
pNTA=y4#mHr!Tp!oeM5i%0|32t1-lwDV{rfg002ovPDHLkV1n(Fe$W5_
new file mode 100644
index 0000000000000000000000000000000000000000..afa477274e2bb7c27cb67bad87551e5910880b71
GIT binary patch
literal 494
zc%17D@N?(olHy`uVBq!ia0vp^d?3uh1|;P@bT0xa&H|6fVg?3oArNM~bhqvgP>?0v
z(btiIVPjv-@4(4GzCyA`kS_y6l_~>6Lo)-z&;LOBB?CjL0RzLU1O^7H84L{K`IF+0
zx-l>?rg*wIhE&{2`t$$4J+mc)LPLZDi?Xuv4CBd-j*K2xnF|>NxE-$6Fg)UQxHIG2
zfe#ES44Zfq8YB*~1SkhgW(>&LUs%=CFl!wL^ZWPHd3f&cH?FDsJN4nUpXog5{4uPO
z4>+#WFfL(NXgDC1ZfMk$V<o?5MYzL{r*>>@=j9t`)j56O7x>%#@U6O7+t%6n%_h>z
z{{H_DbjFMY=T@@cWV!Z*Ggg@6e}cfj-+c!oTB8|WiLx~?G-dKISn|6HbJRPh{Z9yZ
z{P!foS9@j$hK&xUTn>M}FlU_B*D-T4(0?q?7O{YlMS$C;W`Aw7*0F^jzspZ~!N8#~
zBiJ73Ox}0$Jj<O-|Ni3cmjj!6r{MJ=<0%IkZg-?yKD%9Ds{)fkLxPmF<Hs-GjHOo@
zPc+&4_uPSkca}G{xe3TCG#Cgo7@W9TQD^YM=x?hve~Pfj<@5VHSQrEx3VN5QSvD{v
gshCe>W|3g97rDFIe2w@bVB9cxy85}Sb4q9e07w(HNB{r;
new file mode 100644
index 0000000000000000000000000000000000000000..fea4842cb2278d7d6efbc0daa3919598f2e179a3
GIT binary patch
literal 1895
zc$@)e2blPYP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000LrNkl<ZScS!x
zO^h5z6~}+?RrP$&?#_OBcfI~vJBGwcVmonA4nU$DkircK34|0PMLFcc2?-=54hSI*
zAmxhiB@%GVg;R)vf<+X-it}M%yoqh_I`*!;>zUcz>FJ*C=_(FAyV-HP>xc`l^`ugD
z*ZcqLU-e#9i}#-Yr^(1K3wc8XvBJj17&!)oaiKn5q1Y%eePADr*8{RwiqP|j6IwUh
zsL?%xdpu4(Cu<LJ?%D;~%@)lM6ZjYwj?U7Yy^B>tVSIT)uU%b+<Is4n!05ynUq5o1
z55iB9=G~?nis}Fl-g~yxlRYS0IQenjJT~b1&hQtO5{|0CBv6IgScTE?8r6DDi@peV
z?+pof&-i?UXgvnm9e(ijo@TY6m`V;#2};!x)zK=Ia+x5qyT<g+Q!Ezt1ae=5fI*-n
zPzDN6tQ4u#%M{Bcg2H_Wkjszc-v<)x8r*re>$@#eQE_6uBfw#CLD9NOrR<7@QvcGs
zi@Qe{>;r2J#_BF^c<$Cydn=H6@7fbB$E%>n;iJn}`RKq^-W)qey-|7K48mTQdZ~ur
zUYj8eP=sIeBmUO=fTb%pIRDqnunNbg=4sm&)~Ft7Y&Q1YdFj)ho5Vl$)h~1G_)&94
zPFDZ8@~2CmT)eWj8@M1KpjL6-;hi5&2@h}1{5@|MffEDYsQ~Z@!f685QM|*WqQ+nw
zK66cA&6B6x)+}WUMe_RbpT#8(9X~LXngCy<$f<MgxQ8bZPNSUaJ9kQuQx10~&9Z%c
zpOI!MZ~o*X{@gf^3_!Qs7=v2n#?_lR=jjG<;k}nHT}=CqG|e7Jz<S3a)PD(23vm4`
z!Fi_{>2#K4(@C20;fX8T1G-5U^_u6uLibh|V+`JVmX}u0Ih~yyn>lu%J^%K#^3`V^
ztU%@t_>37~o{aglm(Hh2I-mG>Hi?tT)o+GF1ENk$6vjkhM06`cRY5^au12R7_8Z5h
z?JFmK@I-h!ymEio9Rz&O&->JmkTQv5su!nINiUg-vtGI1OQ-K0kVbv_Q6IPN5F<m&
zAtLlQ(^A;qwEyJ&;#Z!2YT>ar7B==IK*XF+5Hd<6l;dt(?rz4#IEm>c>Davk`n^8=
zj>{{sfY*F;dORp(v2(GHSmbiB<gUv@r;gSaemB$Koj`(01Vlg|;xM5bhIG0iVHSq>
z4v2dRUK|-2na^;UBg?XFk2>+q4k5R=MRz6U`km|STbMFOelv65qGo-F^8wHSMj+lu
zX|J!-n5#4KtNKf|pI0BXBU(qqY~}q1z2SP}J>KD6&uwalBlX8Ucas+3dPuh!(OkPp
zp;3|fpH63={_Kt!BH$vB1Zd?1k`YJR?s0u>i6>utZ1T*L!SjvD2Gv51F~%9srl?WF
zk{?9Qcs6~Trn$pyZX@q>S($C|;mt)ltqvO-n{?U{-L;63sHEfHt7pyMZ*G&Ybb%7k
z1nS_baC@cATk(17M{3mLI`#Dm)zLDQQiZyXP#!#j&?6xtq(exY#B@$}xx0Lqa3!SM
zib*#5_|Q;pd7>LVW@~dg`>koW{Q4c;Cg7_cVqh7t&?ct65ku65I_M~96-*IK0SLeV
z>J6qZXlgM%i%l&W1(?WUx&h_h7`1GgAT1D>0(QorRb}ebq#XUmA%FFa>tbC8@e}zD
zrUg_%ra>&I1I@ssf=v~JVlqJ!MZG~YMfwJf1W6Rrw@7Tzo`J;RyWrL{`gan1CnF0i
z1zSV{CELt*k<B(Tll0R3uowl(;4|<7qTmgDmU9A5@y_5;a0X2ck}AGy$a(@jL3?0h
zk8cSy1ql_gim54cGjqIi_8cq!SQP+k<G`Lce1c^DGE^KoDo9n(GT3n?s9J)u!4?9n
zRg5U=Ek+bc1Ti*es)BQ#5*0Q#H&|P0VmhFypn;%O$-#enj+G0m+h?Zr*8Jszw=X}u
z-f0`Pl3~Q7u;rrp<hLC@mx5cJzVE|Yt$Hx)`kBVzG1M9)5TvTi9h~F6*WMcf2N1JQ
z$sz{<kODEd`2H6mJ)@MLQ3?eMB8Ygr2-v|9?STx^ca2|o^f1mlOxbYoz(Fql;UcTk
z%i=;$($0AHk!ShWrA6$}bSzK=EhsMeJPCLHv%ZO6R3IBnMhCJCVyP8O+2Vc5{=;*;
zfA)gkc(|!_K{P)_b45K$HW;`iu^Etfz)y!6Riu=kg1MHTxu_sxu>Z(Bi?1!xe!RJB
zF!iY)Vvp`1p}Uh<`(YO|u1I+YiGg|J+5gCXuARNc>J!U*{WuI1*r~ScAYu0)k;3ZB
zUChKli5)QYV1!Rzy~66(ZtMvTpd;TevAqn#)bc&Cn+-^>z8E4EV228|jT(z@eZ24>
zZ~%4do^2I&xkIWdFMRifVKsI%r65DM;nk;?Wc0_Se}6Foo1W2c?@(bUiJbxt0M#lQ
h=+L|ETJb;Fe*x2YI^BO|KdS%$002ovPDHLkV1lFuqBj5l
new file mode 100755
index 0000000000000000000000000000000000000000..0b7754cdcb36186295ff86c50d1f3560a0cf0674
GIT binary patch
literal 2013
zc$@*<2O{{1P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000N1Nkl<ZScScp
zX^dZ06~KS@-naah**epOb~>e{3~f<Lq<|)XMNqb4)k+1FXp~6!fPOI&(HQxp32M;R
zB_&Xd5s3?nh}udNMbv^Mgn|Jq(@q_rlv)4VTkpNc4^wK%6zYeGC%JhidFS2pduO}v
zAtKD@TEF&`&%OJc4R`;q_VemoM7VlM?>*1_<8j&Wj?=c+73xIxnt7J0@$$}7mvR3+
zJ8nAXtTp#6R?57c{k#KIjHf-imleH=pM3Y$YtLM}@<&Uq58l$xyaPnaNj`p%#^^uk
zml?i)>kZdkw72JxMR!*f!1~)xQA=;^QE%7>Zzxxuy*#Xh^kq}8&|B5iL#TyN31(Mh
zAk<(KO6gf}5rr3U0;Pve=DHRyTfVfIIYi+t&RKdx%@;nt^&)rsy}S7|m+ZZHzpVTA
z;86f2A^=={{)(@EWN6(jl!;dg6dt8OtJ$kk9;F08DFhJk4iUk7!8^fPPZ(9zxtrFI
zb~4J+VQood6fYkx+5W(vcR%#6^s-|kb~FMtl?{II`i+D((N0RVc9_7T1B*5ev;_sI
zBagTeTnc3Zc}|g8^30QUGCGZYxWtkrj!tSR%aT~bHSbw@>DD#fzxl<Btxa<Px<l`q
zukDA{G@>j~?1*AZ7&)TAVnQIOgQ)@r#DmMAXhJrP$y!8NhD#k$=E)O_v>ip;(`Y-2
z(h(`)!r=v1Y*|~o@BSB(kG=_@9(p<xV@PA1AhJkgAu0(fB|7#{>4%DeFyaW!EQm1>
z1{kX`Iwh1Tw6j=&eAWWzp_zh0k&0qr$5!U1AaJxN#xU(ysni@Z9mhbIrmsIlb)N*$
zG6<GKZ3)DE5L7{F5DP^I(n;tXLI?ZkPM^cN4lM^o35^_HNi<duFg-H!yF12;xhbdy
zLY_@iu?=w0g<{c)(>X9&N%sEgKo(VIl-AFpf(T5&(GC`mc#roETNJ);a9Qob3(lza
z%X1)Y@)FWqQK|u+d3JKwj)U%s;}>Cw!YE7#aR9w_MHtul!_S}IbK^*HadES%s0cz2
zL>ja@QU`*w(6P{Sn`C#ci5}m$dFy$~W%SC6EY>BBU@?z9Huc9HBkuBLKOU&})?)ws
zRj;OR0;mKO$|wRuS`DBpuA}0fsu9};h;EaNw-5vL9MQvoQY}~oHbeOiS=ICC-<p5_
z>jP`9iyu&H7U_Niw16=<W)j8$uW7|-U>K<xMofKRL{|q6dZ!A2jZa^^W!<*bcfA$F
zQ5bDdy+hEyn(1he?>*ccop|)hTXbR10)|lxi^$-d6vT!xr5FhmNn|us2O#dPb(~4w
zw`c8pS5KdPpB`xMIS~LRf`zBT$W#9A9Zx*<@YW@hSLA+!wdIlNr$X<24D5MR1VY0k
zaKON*Hqj_??<hgfGwBEVdL=t)_qCT_P0$^?6ZscWI(c$8cYJB*!~3=kZxO48iy}X>
zD9bbOoPp;|XWgnf5ip7wFC0`tt_eU_I=@zj&fE2|6`Rkwa9E8pLT1ww2B2OskNxb6
z+gdk_x(}VV|NQlpC|Q{0*@isNMJ$M=Do8R1Kx-P#F(!^uiEce)U%B`z<NK~T<@^<D
zx;4RA_dybu9N+6PvgL`%ufC!Cq*YZ$_a#ZEH%oJo0wfa+9Gn9HGz-hCammz!&R+ic
z_Mw~lR(I+4%nXs%jK_z`n`ylMw<m|yh1F^hhAIdRMr)MPpdeL1=_tL&&ZJ3rzz^XJ
z&303zom@!<Bp`~p$FT@aWBm(1&CTX-q~X`n<&(xV3gW<EjK+k9)$!1~Mqhk=%8$he
z5uyS-29#jMAy^6#tS_-8^k#iQb&;acY>;+xqz%#liT?Z6M*%k7**yH^&o2GsFKa`$
z+k7gBCj*Mu(FqeY2JeN%?_Xpt=-JR!i|cfoZfbN95+VpW8BLnB%O<T(i*~0?D{V71
zKE?RNBzeQ4rhpDe^*8{ZxU{-?@9C%RT)Aw}3}z_~kIhRYvxxF^T*>}?jFG8>NbHcv
z;zNhm9;X}*i!Dov!cn9pMZ3hdJmri~P78h<WE_Y<GMNkTdWX8Vm^ciP(xNg8(_j_g
z9o~ajkIz9O!AIa@!3Q3v9S)Ckg13U?AO&~};y`j>8c2Z{<d|kUItLzkJiT{#-)q<J
zdufEI8lzC?jzW)Xm{dqZ;hGB72_cEld4w(^Oc`NpjJ6TlM;ITW3DG)2DT7k8MXGx=
zYJo;Y8rMEf3IHD5HNNwbbA#Z3(K}9FIYgEu=v3nijY>ReCzqLaLogy}nLPv)palUu
ze)ea>YrG3F&Va=SRuBt;3Z%a>5CujZngj5?s|M7B>f`rM+B-gcVV8MH>mLjbokW(V
zXseM%z{L3Yzw^rU1%yN@P)Y@WR;VLQB_5OmWcD+G638eeMSKcbTX;E3br;=}a{wj|
zx9MNJU^WteYX9&vm(_wNQQMXdEh0-&G>S&EmE_y~81pDc0dD<EF2~;3xhvUTUspH5
zCT?H2Y=F$>Xs_n(Fkb-2lg{&<@AM3J2W*mW4xB!Kl=61w^A7;f+}HY6ZAo=%&8O5|
vwX`<#e+K|a4yQX;4X>)zPOER6Z-D;*^=ohDk=S=*00000NkvXXu0mjf^Q5|F
new file mode 100644
index 0000000000000000000000000000000000000000..88c6eb1d5eb0279b63fc845f25d3a2ba3d811e2e
GIT binary patch
literal 1567
zc$@(r2H^RLP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000H%Nkl<ZScS!w
ze{fXQ6~{ksf4p5byCl2$K|;DfvIb}()Dlyerclicf>w)?Qq)4VYDY(B`s<I{T9~19
zXenY<hKNmNqS%qBgeYJ^hy+(-0*JI|B$jMK2r)m%l4Qf%?C;Y*vc%9v+f4z#GiTns
z`|i2-bI*DA+^dKPU#1LS^zqKSerR&JT*bLLQx}9I;T!~$Q8jjV_jr#tHJv=L?fK_A
z{$Bv)^CIy3^-tXE%+7pt_v_WxSF5U;fHOb@m^7=PVCKq|E0ZnO<iEXnpk~#s*LHMX
zHh|La-IcU->5{+h+5P&w%F4<Oz&rT`vkePwxY1xTO}KFGTwmYLoz?n))^oihCFv)B
zdTL8<?V)#8JYP|Ma9ji;GGdDs-)7vt{gv7&PNy5lU$bW2JtDGQM7D{@??mJQ5h)Q7
zhlrq0otq4-+fr6G_=A=Am5d(if3-_qHg0_K>3Ky(?*Ta;Puq(k(k3FiL}a~)JS-v$
zMI?E&&#W6BQGnl;mzTFLzGX>zq5!&)Tqw#M)u7zbaP-)NXS=mu<>pRV1~dbmz#!lS
zPIN(_3#_NX`k{ukqH42o?k$f!^>XFQEro?&e=N}qi~uZJwCJI?>rd3I-s}!!XIMS}
zngAc50YktkA1F4+uz)=Y?6xHAijGOEA77`BPMBG4w^?poeDinH69!Ne#d&>U;XG^F
z?Ao=D6mN=wJq(Y>CyxT>{17%nmLAd!kY<83Go+a<q*-lbmn?a>C5ADW>TrB35rB(z
zAU|tzwmEHju>r`_!Bl}wKn-vW;MYMGpt~3{ecVhc7<4ejl^@V`wRYM(pUeiT69t%T
zPt8=!Svjc;?{!TN-vR2va7MtU1KU{PQvgK)lbJxe(-qe1^~vLjK**$;REx!$0fc~X
zeC)63p(O-^x>5hjXbBJ%P;>+{9I5tTFccaOK*xD+mmwoh_mwCF^~3EZAQFMh7}#~g
zK*Zt}jZ=n0;J*MCm9RyPX7%;;pBfLqCkNi#+flOQ{``--7|PFNViY6>Y8X@<#3G|t
z3<QAy!;|;-BiA}He(E`8^`7sqPZ&T%Iu%8E<B3h)Uv~|rwltebN>0HHM060*gXrT9
z7gs+7Xnyc|AsQl9Fqy1X&m4IFQ0@MY69M?FB*HZhJ@{i!NF?^ganb6|i2sC7w5Et?
zZ6ey)xV4FB%~8?*?h~!XBU;5<qV)u2$nAEAvYpdzOtcbSau_L!a^Gv!)z98~`|ZZv
zM<J|(^i;6fz@QHIiAG^agLAzw&<6{Pz!vj!(@hKa)z{bEoY3mwKLCutqpws}u3ol$
zx%xpn{PWCk$PMc7HVB77qLAf)k^=B}T4G0!9*gC;T#?*qQx7>(?SIhgbnb*xFe())
zaDQoOX>&(Mw}^-gL`B+sBCP`=Js}xUSy`C|{08{>M~zML<fhHi-P1c1i9{b5R|+l(
zjiP)N`2L*hu3LOZX=&b!88d9Es_HsBI|2u54xW9rs;U<Fi-;Uo6lL<7wQF}fozvzt
z96ro1e)dyl&dA$%zQ6yMj+B%yyz_l7Kpa8=9Ke+LQvv#b(<0*ix4sLuR#d#;8}v_W
zZ*S+$<;y54oU=po`|nM%ShR5gBq~KwmhRfKXKTyp_LNXCz`VKNV1Ds8-wuVsOI6i)
zek`9c%j<Y0B0E>yefOVd6%>RfCQsyaTRZPH9R9Yd8u#`0`!cUM0D#ZuTlJ%RR#aSD
zkS|7~fj}U@KR#?MN=cbm^=Vg^eJtwBZoq`;)2DBHx2|6H?yr%?#*@<QX_ZhY;`X$*
zU2>(nA^>p+tIL)5qWj%CscSeQJw3hB+1(=pKHt9jh9eWMIKXERu5IqRI{B#aq=X_7
z8Swd}x7WMl$ot2VuQ)&)!jhexz4fg_?ue(gO``E4_H23iAFm2P9KxKQp1x)8{+gig
zf+p)XY&ZsFUNwL?gwbZRJzYG1{!755i|v=S5dAkPieicHJpV}B)dUzz{{qwtDjYiM
Ruzvsm002ovPDHLkV1mrp2BH7}
new file mode 100644
index 0000000000000000000000000000000000000000..058efcf4ba174495d8d89d1916c3ccebf393a2af
GIT binary patch
literal 1468
zc$@*e1w;CYP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800004XF*Lt007q5
z)K6G40000PbVXQnQ*UN;cVTj606}DLVr3vnZDD6+Qe|Oed2z{QJOBU%PDw;TRCwCN
zmwRkeWfZ{AcYE9J(Z{y#5w?Ue!AaNzvxPtviOz^b6N8xjXJS&Oe@tNdhd~+tOycW5
zOiYXmOVDUyP?Ud$gc!0YasB~eTPL)GiS4$Iy<cr_+uM6T&vzePU)ws++2r(l+}rQ`
z&iT%F&R0Syh5z%zv#-w1&WBp$_3bB$v3cYx&!+>}N+@!!zvcc7D~w{e$0UcZJIgN|
z!l7e5>pnEVk(##CP;cHzYm8u_GjHNlElS>o0JsX<8b~EMMJo(ItBt^mu^OD-f@0Ya
z0AiQV(K>TtoNo=<uqoOQ546Brr-{@2c=DXxJjIkV2=jjm;DTcfq>(>G9fs5+Wse&z
zFjua5faH7(Rf}3(F~~PXz%qIsI<DeWR6A0cuCIhMa$}~Ksg;9D@NOQ0y@fbrbn%=3
zj=<3-4x}#A9tlij0p1852f7GLqG0q$ll-3&7<@4(xQVY$+u?pIappapHGLsKDflZ9
zK#zl9P5@o-`85|D_i_%yV_+sgIc0OKJV$o(oV=UNi%=Mk0GWsbEj0qQ8`M-oQXNe<
z@wi~5fQ5q=2f<upK<a~ot#W@{fH1DiBt(IPWJSQtDb~?i69Vv%ct=2qpf6%5ajI-s
zwRLc-4JIpb&4OIwfUsJirDAIXbT>C{{ke-)8C5hzNM@g;&!hGF7{NGC420Q2w>-u5
zgu&i(5l&peCqlNEN(NxdmOKw%wr|-s_zo@RvMc8@m8XnJQlF_C6M;-gAkLU>gcmKB
zgW$M&3EKX^ClOXNk^%HBsW`-ca<;5`^hGG(QmmzGDPOJ6*1;_!(-P3@v0wnUw<E~6
z>3M*K*3`xLd&d_2j+?N=_L?U4oM4|Qt=?DT1VU=ez-oQA213vZ9ymK#;$VImb?xA@
z#05LMW50{dt<Q{q{X<@Hs7g7}ibXWZI-0PMWO<hG7FnJrOA>_rg^|I91Kxgkp`QgR
zzd~?EN1%RSDO&P<{`}(Gi7j9tJob(0uFeEYff6VP6NM4?V$)DR9ANq69tyiV4DqX+
z5TVF8S;ev&3nn6=yID|0Wi_~nnnfrBVq(%1k|Yoj70+8E?r@6YTPR-UWt4>#0Wdp0
z%N5DZkk0_nr4mtEz?MkrnP+3d@_;0((WAhqP(sueamSupQL&z;R|Ft=v;)fdgwo_T
z6Gk874@GpHV2xaW_Fn|BxpAfs#gnc$qZp-G-$bg&K3c#OkgO1?Fq${wY8wvO!h&qO
zi=!SC=7G7D3R6}9Vu22J!(j{4BxNZuaeW>VbBTAO82T}o#wR{jz*w1BvmB>bzl%rf
zxeSY$0y2r4jmZSc@knHOM`;&`ew?M%lxO!q1=k^OHfk=_77Swlo(TTHj(}gR_uq#7
zw_jTL?5Rz4!?ij@vUf_k5q2{+X?Ft18NdZcU**cUeR4igOUH-^i=LvOcg{I{2b|t8
z*hVzB`nuz7-@S6{;}0CW?(bm`DO;tgwP+Bz1IWN{;|B$hXSt{^uruI+C+}j;X2HZ1
z|Aq25%7h+NKZ)<V4i9{Ewxn^=2^KC97ql1&mL9+Z=itm2Pr&85zQ95KUgy)!@F=Sh
zz?M}GT4G;^e~g`MIeY^loKq?U^Mo<?`(=7D67XWujV+V&D3?%rS;|D2L5ZaWRaA$V
z?JettC{+U!Q*|l$iZl<9^#CyI#!*-T8Pt+TXpR4R%Mibn_L6G?kYN#uVVwP6%!f7n
zku49%>-lq;0uepgvVZcMcMTxc-GRMsSgsoD0(j7m0`V)n_93>9YFjn7*46wU0R{lz
WQ-?g>7HstZ0000<MNUMnLSTZnY^yy0
new file mode 100644
index 0000000000000000000000000000000000000000..f6357ee4d9aab6ab05fa4ba7fa8715595482567e
GIT binary patch
literal 358
zc%17D@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`Y)RhkE)4%caKYZ?lYt_f1s;*b
z3=G_YAk0{w5<d|r$X?><>&kwejh{zL(}4fnL!i)SPZ!4!i_=FZ8|Jkb2)ND<Ji?lB
zLar&vzoAFuC(oS&&mWqUe9>@R_JCuzo*19QV-xSBJ#LFSrszjX)&H)qwn_ex&+&k{
zV$PlaqRQ(VtS#?3f4nWmbNIj}oi(qy9A+)sEwNzLD(M2oceC|wHf_tD7_?~0A&J8#
zz7oj+UW!YXysw_MjB!V+`A(*F>$0CKn_Z8xUi(!~_M^!Uozs&l=Sd#__;g~|B8AhN
zWUrUX9(a0O;e0W}nynVk>rSh%+>YYNew!_tWU;EN_?+s#<cgx6@0N-!9*gdN75S}Z
z_;DS7AB*Di?(*6KwuKeD586(9?3nfFeEnnd;+=DZ@}dicfZk{DboFyt=akR{0ELZ_
A761SM
new file mode 100644
index 0000000000000000000000000000000000000000..a7230e4fc22daeb0d5d71faedee86e1eafe65771
GIT binary patch
literal 7757
zc$}44RajJQwB9oeF!T%!5;H?LD5ca8(g@PhA-~dL5E26tLx+@-Drr#CAVa4Lf|N82
zpmcYf@$y`pi}O9tj*IoIZ`J#*Z|xmza8HAZoRu5^04gm_HABJ^^Y4O^5bhm{_5%RG
zL9eBzZ0wi4X>FOvu2FOKAz*t~#G4lCtpWulQy6MW_EYIZqg7(UJB4UNFg@~s(mbAN
zr*+}=HRkCL_+mD{W^$ZHlB_pmcVaiGZ+>@TiDfWOA>->K-_biXGamy?o|*V=H%#_@
zs|sk`s(bd?WOOP9>jjBoI{3=b3ZJ%=MPXE_H6UKS3s`{qHXFPZ8N~&b#e1m%QEUm&
z`J@gwh|TB!5E`POyIRLxueMERjs}+(pI<5leB}tZR6P625#z^6M@MJy;Zr_9OnhYt
zVYsj}F)zKj!V1u5Y`@`Mi*h#c{eb))(R?BJnX;+m!`k@p;-SN#iAissYLe~e&wImI
zXt#yAqn${b1(B=BryB8Y`qRjct|<!&RQqGe#fni2rHgh7v1wuyM7;lrp4!>L%i^Ew
zPJa#qdIJ;=0$8eS$`Ro<b5t+~%vC;5!pG|8o#QTk5EG<sk#cGoS8Zgyc@A@^S~B~X
zz+T!OD`k>kPeck?Y98akQha)Bib}VMq%sTImC9A5dJKVj>^`*alpvl7R0$Ko?Sq1>
z>5^YvNP#QHR0L{j8*7gYaJJq-I9tuI=wO21-L`mc&@ZxrTNyH5!8yPkui$vVq1S^8
zQw`Ci#kA(THpK&Ya|o<W^^=qY*?h6L?BEk~SCHN3Kq4#*V_KML+SM*pnEy06pF#G0
zrX-h&S5$Vzfa#TS{fzM&L*P`$ShNCPOv}QtaH@Gcev8>CbLFgL1y#YYJalK#q=tki
zMIgoW6~}A}@qW@8y>WFheYIglT;3iMCH7;zudW5#t3W9Qwp+s!uZFPpUo#0;snY5T
z%`?BA>)b8NMQ8WyhW<G|`%qZp?Q52h;ZCuY@N2i5a&Dy*EBJj^8^-S2cc>-6kE)wR
z!Yf#JFi;4+KK{%$9^f8zjaW<s8y9(RoOmDb@p`!}PL#no`7kaKQ}GJ8@_;N4Nzt~C
zJtG^~r*j?#$&!;%+~&#v$Cs1!TZ{(*h_FX^EpN{_@5SIJPv~m-t>i0L+94X&3<{_b
z){ZuqnW(KgZmy$`jxRqoa=7s6P-CW_z#Ca>XInOb2SuskcX}yCteOin3(1{3FByW6
zzY|r_LmU~8cJ6Wm#_y`IDYhgKn7lV@%;Y<UpTVE9U7LiXG#jcYiy6|D{LgYb+(_L#
zJsl-k7tZId6%*K%sF{tb>E1RrLJS%$O7{AyD1Eo4+nTPAaVJZh*Vvzr>A8y7l^;{E
zK{Wf?Ds1cCAMcMz)v=c?&;;)g$zL9foE(;i#Pi+DRkNYr`j6=GXNt0)zr8C&4+q9u
zj-;9ohIKM?a=PgB<w1_RPtm1*g6`P|Gh<36PhZ!KyH~Z50uR#dW!W5pgJ%m_9KFsC
z{=RDt)OP;q0a3r}eAj7E@m$!(f0=<`vIeQbJ-_0^78mzK%XFUo;bGdM;$nqZ-1z!!
zfgfv8Ce%ula0UaGw;nS2L0@mP#)~sk9)$zcs6bqtV|lxUE3>1xoLuZjv+}BK5~(DV
zlEZsIf&mk=Wa1p?Y{FuvEil;e6erwokA&6sh*~#>Pt|!6l}rIY#4tc6><zRv8kns}
zy{GE@TE}rQ*gUlZP2b#;M{w=iH_F<&x>qFCMl-@!NLi&J(0zvd`yST{m$q<X8D8s{
z<A6}=JAp};P7fmE<Eg9~e28OXV}Zua+=3I|Z#0sGEtXlQaO>LO>Qc=4>nv(iGn2cs
zHFnN*yv+W;|43f8<<l)Hn8|_C`_Y}0akS{&)};%<Sy9kKmIkNEzbb(y?biLfZ=63%
zFjI=(y7h8>yqxII)~($iAcN9SW^OlN;k9WYyTOGwRWUcP%5VjlvtfROq;}0ruB)%d
z65`?D=t$IhLj5HMuv(g_4Ye>MrM1|<k5N%3`mT-u<gZSaPJZ~dyd+329&JuZp&B@!
zu3a*dkgIx1vf4j?&iLfX6X5x(fXG1$`gVhw87~T??RB{pgXkAgenl?(WQB4z_}u;5
z;Na55>Hf)12Tf%~#e5)%MEh<2oB&*8X#0@mg9mMo@`56pe7C_9xA%k?(3q%g(Vn(A
zx7srXfND@w^AuFD<-ga*x4WNr&F1;_kWtj88N0taxYVB}G%-DWu*O~x{FSp~xb&8c
zOvdxI4Q6t(*0{M3VBk3s_6e}Vj%lQVp%zxYXJzK*c0U<ZApI=G5%33j@kc|cJ<GEt
zT3_)LVq|1=(xY@0T3E=#r+hL~#M|Pc)^;!F^=p<-Wo6)rrVfd}(05g~id}98MEswH
z9#Y^chD%tUza=-&whs>Gz+G;7?rwY;T#T2QZPgL`8cxa?2(xh2y?4*S$A@;j%(|oD
z$?DEA?wWnP+_vZF=qSOYBO@8@N42`LA}%8n_49Fcv6UFRGNghR?H5j^#;&}$7`F0w
znQ1<{(-`;|SyLkwxYI^@f`6sI^W8I;P7HT((<bEdS>SQgT!bO{+}T*&POR+(Sn2Yw
zzW46p-RA47^ZLNksxN*<M_tNM$M3D5uLWM6uA1A}kW?sXET(bh;{#!`+(;kB`6-Yv
zRkf^A#x(0a!*0@-peq8T7xo90dR}aQje3;pPoi|So4C6eE4GO5dnI+aGmg7r;0!u|
zr)Olis&#M9=`VP%iK{R&GVXLS+1kmnZB1E2eQB{V`^uwEOr=Ec%I4Q((f)}snxNZS
zr_}b&&SW||IwvPfiMzjy^cT|1Y}zKjJo@+Uzh>{@L5;h<+?G&K2(r}-oq-W^<>uV6
z4czTAFPomh2$C3}a!o=%|573QDP+ILKT#Zd<~(2D=t-bbvofnT0vKmsY%4S${dPT>
z91M=^;S6B|b~ZgjZs;prN-7fQswCN83E^*5W@};5zOf-(TU$$wCo#6iG1!$VO8-;J
z&_kgDi+}RcolS7$;aA}Sua$2s&1Y*L{SHUXc6+%J{ZuD@|NgK^+2UsZS!z$dhhVLz
zu&}V7s}~~wbc*KfDZ_LE2I<YEIh|#cc5l8TIu*`LG0;))icf#>bTzN%pR0QVVoQ}h
z9Q$W2fu}cTL#~6Y>b*cfOSK@{HJ*^@Z$Ex)O{6t3Aw)u8p~Be;tuO_O5|3@hlX2~7
z{M|2bsPQWk?YHCW3j`e<cs%#NIv^ApYT%~XBU!e^_6UlT0o$vvkgNSX^9K)hp&J7Q
z;EB>Fo4=*3aKS;G*>`4IwcN<NStrTVS}1AxuH&9=Ynsb-c3uF@JqrGN+`0ZMEZGV#
z7|XvNvF7?Ml9lI0L=fxh>Djxukmm&*u@Hjhvbj~m(~?IB!Pxk?gq&QHtJ#)^a${J>
zNUI^UtmYIj%w}xTahJ=P!E5c8z&~Z4&ATMLe0&lT5(|4+=*Y;3tnU_EQBjfCQa2Ue
zpCgU`+&*nvBa<xH-X65Szu&umk&B!qTDB$QdP~k~g7Msaf5xwhJ>+HB`MMoMgF727
zZ@$Y+NmB2%0G<sxwzg_~O7`*N$6Ty_Y069Jc2RJ;6M-2zYh1@Gs;U;pR)aBn{3Yg=
zfY%m+b9f5f0-$~n<MDn%(39z*?PG=Fp40tR@2%<E-@bkO)ftF|PMR{O@4nEZm&bK=
z-6gP>%<N#3S$;lSF_SAbv^+_O2?twzK_t%!VDQcexILl%n8a*4=dO-qvXw$OWIU#K
z6z#R6PsKU75@1_hqROuEo16bwaQmZ>@A$kLdY8TyO{$T!4_TYP<LAZ7OgEz~psTOH
zl;b<wwz9$tsKEz^Y9|bT<thfT(kNYsR|$6<9Z7r4G%hEk(|}LqkJHi^2<m)W@_fZw
zn`l~1m7bY^F5K<>Q3c2xbQ%@R2n4V#-VU<zNQ}^U51$QK7rEHWz=a!<cPzkgr{6uj
z{tg!sDJ#l7^O&ypw)+RJX6hA9v@kB)b{P7pEP}|(_Uue1%y4=<d_#Pe=i9vkI=*`V
zkie;w;MkL}X<qe|Os5R@WR-elb+xjlX1RO65Rg78MTObX!EkWn-9RU(c4Dq1-pcme
z?x_TAoW#V$gjdVKg4aZ!b@Pb)N`NCJ!JCLI8PC~U#Xs&TXZXGEhhiSlrzX|Y7?c3k
zXOQX-qR~LfgWYq1NEVimvynV;DXHbS3d=f=hL@%0m*(=#?{dMjvm(O6^IJ1bLl!SQ
zc8U}mt3wd2oh}3GcDm&5w3r#(Xz>EZiwJmZ2719l5;K@%W@<WZBUk96LLHB^D$)ug
z`7l^cAhJqAGyM73ILP@1%X>GS?xr8ExYij`ued=+HTS?i%eH=Niak$=1fM2X#pA$j
znCM#pG2WCctO`o8T7r-pJMq@<Su&NiwJU+F_EQ1^?G!@R%Sh#Ft#4l;(nQgC>sC=g
z^fc6a6=X4LjP7rr6KS8}2M;=${jta$kZ2zp8zbN#o^@O%UdGr+0+pmR{Y#BfptM#f
z=`z%gYmW4;XoP7KX6<3pNK+2U)<YFNlCk>k47Nx7d&_=)FaCA%(a}-$GMZ5|WrF|;
z8ZF|c(NbvNWaQx09q^MDFFHgPN{ea&HlqVgf|>LC^B59NL3jv$-Z56}_KR$?zD5bG
zh^cN&uQXv*5VUP>Zr-!vL`i&GZ@=^rU9e0LQ-{j&K(FuAhalKyh-G8M>O#_x6PN3D
zEGt^hGn;j#Jg7zl&NVBJ-jVWOI2#+u-!1Z)aEDuot)ljud_pGFwRt+B$kbZvXk}%8
zK^(gAumChvO~HS|`xroZ%ufUX4fC@YT4<b}EPY+6pXK=iYBz0z(2gldh_)TH>BJ44
zvaC&jRd3c1S)sWFzrsOe#Dzzvfi-}vWOp+LrEvlm%3e>E4exxQy6rwaqozhnwxkJJ
zIU}6pn%@6081F%3+s45j+AyK!Io+w}D90=`GIgO6oic?W{%o`W7`}`5_Nt^9D%2?T
zI~m9~fB&|3BSmzsvRQnV8|2VBHP&W_SzdNp)uOx`OljE78FkzbP{R4#0p4&?L-dth
zfszN*F-ff%gV+8Oev;_@#{)iXs%TnnLYnS0J~mcC2#KREUuTb9IiUh}Vxxm!k8_jN
zbLi0WV&2)EY9JJw88R;-V7|ALM((nl#@l^r39MV*{#75#lA7X5z_7<$OZ@lmdWq{<
zZV}RQ4pt1}TSsE_m-Ydgly5B-Dy(jxjx|ogES`g!>5_1N2LurVRh0+Lafz`9Wy3@}
z$zLifLq|tV@cuTcfoA8Sa5~i!8*dz&4&_41mkvK&*51ZtO@&~-bSU^8j_yw$DPueO
zi>0gqskPd3I&aA|eWZ{v@u&5D`JUguSqY@iKJGiIUbOM1A~Exq4!q6A?fQ)@J6eym
zw?VM5Qv+cv5tPMMa&pHQWttY9##KVLYaOkcPSxRlxQwd2^ZWPj_O-PStNroFmc9fm
z+>P#j_%8kN_QP|TgxQQlU!Mn8_CNTl5)jObGGU!z^h#7c7KnrkShDqDNG9V_IKBAz
z4M(rlAMBsX%bDnCdsibS{)(#jy!td(1Xcm3Oiw*KAFn3DBJ&1V9R>gDnIKx5UY<yc
z&o55Uy)?Edk$xCpIa86XJ2gAoP4I?ret%!vC;LH7C2n1{Aj&DLUa1iL(9$|i@inKa
zA{`^Wkhkc|ep<v@EtM{kFY+62XYrm<_H4v{G<1D^oxp3D8fn2jN5TBq$BFSWl7LYy
zI_BIc(pLANIElSmHM;egKa+v~h4xsnkNl1_=sN_#uH<9ieo#y7wsgSzBg4V6)ZvBi
z@s_nOlM>IKkzoGElSfILPw#`+JQsr>bbE`esas<===YrNTyKkvX0*yD?#-OJ+eJ?^
z^ALHxlkO%)vz`h_!N#bPxsR)}va<d$Z7i|}&ehM`SqE2%>oBrxH|Inie_3GCCW`cy
z57DDl5iq&zkFAHUWnJq9W9){7rSb2&7{6$V6ci{=kQi7Gq&$n4Ft@es@sf>0S==dV
zEWu=Mr9D}Z?vSL8szqDM;_Y5D-muKLg@K(`(JVu2@P2g^=yT~I*Q9|eW_3A-sad3^
zXhMww8}+M3MYW@^hM=2?9VzQhlcH0&q>l|by!ZjhkOVxPa+c5p9j)3Hvelo+u@;1z
zItUW9_OVKL67RMnG}VrU3g(iXB^j;I3Qn7RQA5r4dO-wZy49fCq|-Um$oZb=f0_vS
zklSX3sTC*0zb)C7hh35cF@+ez&sJF}F!zAW0mAGkSC)|wpXsL`eIY7{xC^zPTKa(D
zC92Rm&><2xRpen;>BIj{l?i1NGm3DOoB-$*jT@}84g$02HQ^wA#jZnpB>{n?HAlWh
z&Yfs`D+U;AAnjxoWyP(*Jp7sX_juwRwcvUh%^RU%`>HYSH^EMCzEL!2r~hm`N!uU*
zmf6uoE}2(gM2hW(<&92RrF78_y=k$5-s&8`D?<{L&bP1;cyk}!H98EKE&wa=cZFnS
zZnx)TOA`h<W=h~>O83D%(NEI?l1L?EG9M3jwIoBLC7+O~Be7IUfkDnFqu$kk+?eM^
z!pp$@$6)T~poK*P9!V9cR%e0t;%S4$zLu7jz5DWOA&*gSQjx5Yw_A)D40LgmyB*Gz
zK5rM8egmcKm`?-#m9>-5)JK$~`SomEIq{(%G@ml%Bluh1*c*d^nG4`;87FlVGj){5
zkfCpcJ^5MsW*irBd!UUbnfs}|MGUmj<JwRTQ(;xIt=btS*gDGR({1N8BIQmL%?7I1
zpe%Bxm^fIesA23_7`n_%aT8OA=-t8Tk!yYx>2hPzLaYicS(~6oj>LFb>aDN`uv3Z7
zf#x&4RTnPvO~{AoKhi_{#Hr59{H~fha8=>#)rOu!``6M_D0M6A0zk}wa@YEH%U|xK
z4m}dPxG$mF<vj;2+;-9PsqC;Huh`LedZlgPjt5bLbQ(pM4#P;Lo(rbrMC`k2S>mX3
z3fO+i>c3(^MC3+NrUQwk8Ikygl3F^OBju^YRsvE{3ou?tMt5zKkeb>JGknAHeP~Bt
zRPgiUhAxhHT+tv^iW92W9G`XU)EnB#2x11Fn}GDDX?`gkK}XDKH|S3#!2B9~R&6DJ
zF;Gyij~kJ3x?|iE$9HV}!BdYUSx2XPknr$@ia6a@6f-8|olHfObj;mNX8`v?pNRDz
zFm+*cDr6Y55p%&0GH|*uS+V^{o}{k&ppVg8-Q(L0ez@o7ySc04-Le!)JZna0N@{`F
z3TZhtQI{Bmp>x$W%=yLF%UGmonPb25FB33~F0_J}+h4{H{FMpaLWAf!^v{*E7R$MV
ztRs4cf_5~`P)7=)QS}sYAHfgv48INdWHZY3Bu;{>g8cXS(z~66xGF9Ny3tr8$yw5T
z?dvbBXbU_Yd{6$E+RMRd3Y)KG*z0Rvq(>Y+qz;kzv09<#6LUVLrj#^xUil(aelSyw
ztmkd2V2(c?5)wLiR{n+89rIy9J8q{vqF1WBm3fJT#o|=powJIM3n`2%MOpxs?wJC~
z&KN#jV#Nsj6zj=Q38q`*d8@@#nRNqr+vQ5CLV5oNdW#V{T~dC_-$0;DU%?6|@;R0Y
zk$mG7Sb|~5<f3U5F=wvhjT2@%N>lN8HKE@S?3ifSA4K=(Bc}gislJX2{R-k$U<41x
z2lpKg53TQst2kuOJ|vWZI(hFMJy?wP>)9eO-V$~5*T{>|i&Q~=+WB9;4tFZQ0AW7V
z5NAze3UM~-uY*Ys^q(mQmnar|yrmZC_VZx_J-oMCJg68pmeI`~Wps8sjc>hA@_{t{
zcBw`%$JTF=>ypS)4IYf4%0@;c!T@`2RD5rtVKsL@*od#DhturhiL6`H+jyYeOL&&2
zJlfpBADM!bEsF+J&M{c@SimDOse6y2r_s>jdpUwvGQ&GNO5oiuK%td}Jd2|Uhd&;E
zf#*|dli|1|5jIiW;F=&yReNV}m7DmbDoCeUM@Mbma{fWOy|*{~->hh_yAibzh?NV2
zEYSguRQGc3L~vg12y^)DfRez|GU0}L^|Hj@BfN3)q%O~04mCcJ^*z+|SZ6(MI-=t7
zETNC%XRG>jqgG3~fiU~t*P{GcdE43W;%1f<V|ss`NXJ;1aGM2Dp`?x9E)St?zwFH?
zTdWI<mJ=aT>wQX6$PoDwc}90>+WE?yA-cIp*8fW}_pp{Q!vFFG2-$UU=iQ@_X`5qX
zp^P|<e%@q##kc2#gc4sS)l_u1PN)ptaJ0`v=u+z#uk0s#({$q>hn;-3BksBC%z24U
z$HcinDfzm3%e`%COb_cf%p|RE<Ys83IFsk_F<GWHK#oW1M&FrQ74z?8GsH8930jJF
zS=%GN{1!Sdf9LelN7#lp-*}R@Z*jT$W214x>xW7g@4pY1n0`3fB^ge5K;~x0%XlBX
zpP?KE#@^ud>-|m9`NE39E3q@J#P~Aat4Zbv!BNEYgf6J7Ae8%46%~(b_&!yCBvruP
zyT!M|Cy|;oYb1_S6pv5D3oOKauyzjs&#|Vvf&2zX;NAOj+~%@-Yrd+@Y;!h9o1!il
zZh+m5i@Q8r*-g%`7C&*9`jgNi8M>lrC)U{6rxFkDt7=k_KMm?NE5J$K{HQrzrN@?A
zn|4Iw0!eaueGA35D%W{Sq?2SK+z;EuLbn^P(vuMFSH7M9iP;*wd$)KA(Zbqxndo=g
zrWX&8yhPs1mfh-vuLr9K?iP@2=tPPSW;HQ+PX12j)ZYZRHwR4al?$g-&zBYogB{#v
zgCi~bS3a*@0ij7w3V8n-DPv?t^XW<!&E=NwwZG%yMCY#Xz|i*L&-LS&V>Ql8o5Azf
zCNyo3L0Lh=`x@BZ$0~uhZjSidTXMuGtn5<_@%zSVmsY)q^7{}KRvWXK2fANLRh=G0
z)ICMw(<njmFm@A_9MSiEKF9ZJX_rRn#EuF^ix{}+6!-SY>W`lqoFNB)-`ifFsX``%
z2a=pv0>0`xHELW&UwMCidQYu3I}Dsfg@C2qC|b1M@`FY=xA`weewscvRwS*vZ}c~U
zJi0r+&9;|$@8w;0l@{|ua|#sqv^_n(aPm!zKfhVCSBa_33zJVI$O|R(=LnIzl{F9@
z2ukOn2plxV3R`^uZVMBJCr21slz;wQ7W8xh3?lx)0ADy=%`<!SBm4fpuhIw6gt^+>
zwZ>3;x%;tT`)fl%u6K%n)93F7FoQ&F0B{qv=%pVy;AfgHFpE)#kMUIQ=o<;~ax}C%
zOv=wa(W3mpwTV?V;c+<+WRQk!jP^v)MoZPzYiMiVhCG>2&=#O*1u6{s1relnX@(7k
z{rT8cZGmm7!Z^VtHRDthadN?NiyM}*5Z$r$NnO{fF$>3Urn##}C%a1pSZK&e2PZvT
zz%h<BUR_(jsb=gA_G!A)Z{}BNyBu&Q?a~&*7_xkt{NmI#y8HS9qp$ut*^s>B06lmh
zrV9VBKn^cdm<iwoY?u@Cl*M~ymiD7N?P;Um|1}h+1=%H1fhvqoJls$57pZ@5W0G}O
zB~d>9R;B_@{ZHSg5)8?5di{OhiYVW)CxHRt^>>)(u$71=e|)_(EsdeD#*~hZPH^C6
zn$zoH3s*<oqSRp?Fu^`D1fAxf0iv02)<%&IgMe7mh6S=o<fo9synzI$pbg)DYIy)R
zTnh`o5AjbG<de1Fe#OL?O-&C~XOUUX(thRwWFoR->r{n%kl2?EILaG9w}oq(p}MP{
zf9{n0AQ{Hm*0wl`GdMF&;u#kVD6_?taReRQmp)3ZF$EdC|Eb9?_gt4@^8+PAig~IW
zctHm4RQPLNl9%4P#mT%yHLOG{c3zpA?L{I5eRD^3QIGoUMJB>6Oq?#1La6W)0`?%i
zFp38?Y%%rov6{BPu!SYiTNM}Cfn;&~)!$F9aEgEBhIuyrLXEpYsJ2z&;ZBEHfP<zJ
z$`Gp=rY5fr(LShT3WuTQV*E1r)Bz;2pg-I`A?h+}>ER*mD+4L!Sl~HO*=0(#P$Zv^
zLcJa<v?2dnc`y+ssRg2z(ZUu<ySNlM3G4lJ?D%m-8nHE0ok<Ehx2NL3pB%FvWdU1K
tfrUvmoI{(}-g05(!vDWNssCH(Bn0onhY4i2e*+Mf*4=w*Wh!=I{{!`aj5PoN
new file mode 100644
index 0000000000000000000000000000000000000000..fcebab0bf03520ebbc1df2ff759fea1c720ca4dd
GIT binary patch
literal 2035
zc$@+A2MqX$P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000NNNkl<ZScRpR
z%a0^S5ypR!nN`)@)#K^yd3a_#w!F*OyT(Qc32S8m2P6bXxFCVJax{W}fD@7h2#}F@
zNL;Yw3kU=UeB%JZ#%3iRUNBy*!D!aY;(7Kw`cco!;7~m?J3G6!1tFEHx;iT2i-<2H
zBgHHVp;Rz{01Ei&l}+!!Q<tCOl`F4+fQW#Cssix9bA9}FAmj=`pjN1X0z#o^1!M{Z
z_>saSaIyac*WY*p!#jzdJZ4#b7(!^?>FNKpR5ZM!rF+WV0USA)8ol(`#d_rvi!%UN
zP^;(^!RqsKgs~oH>i-9D<h*KrE<U`Nzy9}Y_P*K1KQRyi0;|u>;decng9bfg>b;1&
zr}GlJ%V}}zUvI_$gVAoIGXr>d;M;xtt|t`#yYsUE0u6a`Sh%!MUU~Jm(QErxi9^h!
z$QqqCEPts-z2~QnkC=NDfPgBhAYn?>X<&M!b{k%I{9)jj`S-2OR6qUokKC&_udsV-
zkGbAFSup{i`&mahs2ZC_5i6$y2p&9W4dNkqMQfmL?plG?0q;Wt(kx1|e6(>s_gK&W
z;AdYmTl+f<HueY=L@pt59lrCz_g~y7c3zHJvLF_#4#YM|Pz8d57w`(TKnYqjP9@WZ
zD`P}*+V`(4J#zDf|9nVfUeHXTg7$K|{>IP0Y&Qp69Bhmz3q_*<snTES)0^w#;)t1a
zh9vHgBngpCu#rW?A!0Dv@LFrd`#@cll(mP-V`_`>j`RKV{PHKi;F&LeOPmIU5|ZUs
z_Vjl@ZLj_NDuay)K36nRLMK2=8C2V}_PWGTLTl0@PTC~x1Z!ig6;vDum>{SZd>IJ7
zrp_wzqQvie?8sq?m>aztT;IIba3Jgi<{mp&e&Op+MYpo+3~pr<8H7$CbZRt(IEhJY
zhuV1}8<9zjB_`GcON2!TDrhaJS3(u2i<&C)6j@G@XB0an@>Ya7bR4YgGV}*0B#e7e
zurbJ?&@nM)rly>)sb(Q+M?^`CYl9>K+8#}6>Xzc83ao$;G=TRI3h>m_RYk5PlX5~f
z$;rzcQHvQyOx_yfUETn&%NDJ*_2Xw>9IafOPuF*EU>*|0LPuM4>5|56x@pS7a+jo?
z(uvx1=#Vl)jKdQsDH$?k!k9@>lJA#f(U^U^$7nQRs6*%oB#wivJ^J(AX$FjdQx12=
z-LhS6N9WV|VLGOjfV2#*8xhU7S?xZ=?Ax=<TxhXSEYas2QJvz9Lr|(IfJ3v(ZWxfI
z83&uYtX*GX_~9Whz4}*1RYut<D9GtlwgDi3nx+_qmJ6*Y9$Z*kIyY_)>Gftgx7cI;
z!9LfX{U;lL+y0|bb3+oDK@bsX`Vhi#H)tA;f`)Jy2A3Xu=rfl;^}){7xi>LtIH*RD
zfh2NAClnBY{n4n;4gdE0KlbQSK06{km(okm;o=>l&-*8>F?2dDY+|sn#aM%gG!R15
zmVM=^sM-Jh9_t^u^@k7mi<j@~&7e6Hc}3N)kZJcc+_sGhU<CFj+4A~7ZcZ-r-bcF7
zW}XF7x+LA?{_boWgJ8tq#9?g%!di=w+rW5b`QyvXn2znXQd%=@l6I_dl&I-gG~q0O
zqb!Jpt;0e3=a>Joxnfs&oF{y0Qf%9)>qI2I1ohKCADRLPCqs&_19Sa8NfHysahAjh
zNjoW%c3dW{xQyDiqSJUbS^;+q6Jo$R*d7m-e)pRfUti;r%$lCY-Dnae5pfdJol6OI
zKvj>gpn*^a79N<x#SRxo#7Q(rqE^*vB_r30Mp5iWF1BNd$r=t+fIZpJj!R*{Im^yu
z@c1{cK67QTK6x_jwPzw9j|77tL}|ouYly)R2m~KkesCG@1E81?z{#LRYaAu+Ac}0T
z&SI@|MkE1n?XSS(d($l3v8@|1#4h5d+_-#@Rj)nLUD>8Gh@R|#>G=*D>zkmkdVYoA
z6)^_T>2_>(EzzEFvLnU>V+FB9(u_7Z1t@9efIH_35sX-ziCFz){|UjMdU^oyc<S1-
z_UHw?4;Xt=Ptic|YzwlfYPM-cRzRE>(_{dF&Q}eS=ffE;++LECCq15qp#ihDcAgM?
z6SZ(0$#hk1d+PPz{jP=(f>%NvB4nBY?9@^L>YFL%y^3-|K0TE_Io80)R!;V2UDkVb
z<%9Pg4Z#Nd2>=!7JZ;E-70#C7T_klK!aZj4=~%W^g=)Pj>w~JSsH>W)s*O5h8vxOC
z?E_i@9^}1%kY@c?Wqo^%PD#*!*YH+R=0!Hj^RlQYiwd84Llj&Cz%>~_pz}FH_NQ=a
zXuPX$5isCKo=U2F>IDKpbu-H*oB3!$Hq0pUf_fCtj?n*Mf)l4r1XIRn1ya9D^ahME
zWJT8W?t5ealz^Jaq%h-yjBK1!OiI`TMDei(C+_5IB0%?}j?vBf%<=1XB_oFI^&PCW
z$ECQtdqs_!jFB1dkC}`zsy$D%8$sFtcgCC;J`Tlm*D^FJf_0WMt1zy9R{$88gb9ax
zL-KtO8=$*NxmZ(&fHNX@x?uL<h`hdgZH+aozjOl|S&o*l-fQUyU?ptt>@nQ*$PVZ_
z)O$6ny=97`4o>APdPSzE-P4ATwpuX)c1p%~5(6R<j5UGj8A5IIKA482{{`~H`a6_8
RtN#E1002ovPDHLkV1i_e(pdli
new file mode 100644
index 0000000000000000000000000000000000000000..366c2cf3e4729324aece1a645a0ff297b13372d3
GIT binary patch
literal 1604
zc$@)52D|x*P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F8000IHNkl<ZScR>Z
zTW?)Q6~}*T&77MZJFy)*ZbK8(v}vL`O)F?6KnRd3qP9YyR*JYt@ClHRctt|I@qqe8
zc!ItlL<B-el$SISq?FWAAtdB#H}*M>&pvx*Egtr^b9{}1SkfHr*)x0AfBk3Oj_~#O
z7?u_p@qo7#RmDO84R|Bc=mdy@hbGbreCDY!?mQ@<5okn3f|68`0F6e(B|<Pv1BP(+
z`8L<D8ia_9wDDj67Uc=Vy&7glPB!7$-OV35jz7skL-K?GoSck2$j^S^)!C)Su}LOJ
zwPVgrcm5|3`vTy2rMxt9k*3bQK6mZ<_!J8_AF|v{oS0}m?Ug(+ipK(2r#+XMvOjp`
z+&50$zcM+)-P>IbXriCsMmO`^Ob2tiULpSf0C2A@A7t!ddGOocf9c}YXJ&bDt4kY0
zMQEr{SmxSd$>}4V16J{X?-RtX04mF!TqLYlOn>XU^A9c^pW*JmS7~}C0Ae6yB2c(<
zZKY&>wv9P|ufXqV9pb(-0C&gDNJYZBMdv#|{_@>xUpmU2Pcj`d#H`vkWJN<^weKvf
zBu*b`pK_<zD>@__YhpV9aBy={k;p6k6X$>Qm4}yJJ;cogXb(!13?kbOR-h4~-_QKB
z3(w88nmD(%ZFImK&zX^LzPSZ}gPD{1319BdeeY*)EqwUZNtUicr^u)oi0sO$0x<^G
z2APEinWqoNS+7E9I}<rWF+lMeRh41L{SsU5zx;!rzWK?Y&yI5Y3bc#bS$5aG8H9pm
zxLq1EV=WB&8+wMBP6;I&WP{S7pRkoa=YRgz2OoTKobJcaDXT+mt8%HWkcvbbS_)LJ
zQ-=H5IC7xXa`F2pLvCNicVx9>16{v->Fsylx%{`+M_68f@d-B8Y&p>DHyIgZygp|g
zlL2Lhd;l6Ms0$$o5`;`(si_<v>r82r+Zvd)AvWY!7j9G!?u3;6C-=s<+&aYcYL|dx
z0!0Diq2RR>W4w367%vCtpu|4yQQTjp7-=#!)1ZB&#o{w1@o<w!KpFuFiXCdO@+YTr
z!I}P{{lkiIYCUVlcYpVvno%d3-<$Be)18OHibSG15`^x+IW;%N`Q;UU*_-6xXoNvo
zRY^0-4Cm%MT)phvdtd2|evC&&rG=<L6S4_|&%HqLp*-I>36d%j;-!D}9yyTvv!m@e
zzqV$*mg>M8N)F-?UHWKYu=tB5_3<-DA*T%r9Uwz@#o!HS|3?2XSk<pd42T9KDl|Yd
zD1xXX^2i@!yD{WlF1^^$_caNkiZm1n0w!n(xRaYP1gzZTkLExU=o*7#<?j!+j`QhX
zucHcxRDNoJ3&`exR7Fr(A0Q%Cs8>IjLw1;(ZjoFA==SWj?o=7HX(JMi>DP{7Wrkd*
z<XuwY?zI5N+)3uVd~B4Ijcf+kqmT<*KFWa8^6Xe?OnrV9PgYa3GXmXdq0UJpbLNkY
zQ6?u_UE#Lo0}s{V>!#GHmh4!{9D3ylmJGM`#jOCgmMnM7AZO?F+&F{M$yU8H->P3B
z7(0o(gMlYw;>8)PbUd>;V*!fUM%Up~wZO9R;>iih<m^~h*XOc#2lNPpGj(<nPi#x6
zO3JuZO5B{BoinEolag(8L%WIwkopRCK~j}=#}ka4xeKOsGzcPsTFMNMLvx3#JF6R#
zokghQ3W9E<bvufBWTiKI3nd~F5DCO1FFb|CSk-v19EUxX4_ikS>$#fOICRG^T>wW=
z7ME^pTzSk6o`)!O9@FLL&C}ZZJpmEaXaw1<)v6#2yK*!Emmv;!t@)0N-_z2k5pW40
zC8*%$tYv5iaKcSP_R*A98=^xUqmPj)ST0IR=RAZy&_k;{8^}@)Y%-{z!9NOGU(G%w
zy6>aSVcn19FNmLXxGBOK35bfsECchgrpi%suIK$41;p-PpF0gS`2~ucWW3o6QTq}^
zf;f&#KhYi=<6x2Pjv;%sj++5Yb@s`XJDT*5i}xN}EIQ48&|pY_7zmQ-t|tAgjEv47
zmR^v3wT~5m{r-cgd`57gx9xbT8){h2J9WT&$bSJnh<z6CAP<fJ0000<MNUMnLSTZ`
Cum5}i
new file mode 100644
index 0000000000000000000000000000000000000000..63b3bd031ed91915dd2ddf38e4bd5ac5d812c890
GIT binary patch
literal 1871
zc$@)G2e9~wP)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800009a7bBm000}W
z000}W0bUxB8~^|S2XskIMF-am3IGxu1y`re00006VoOIv0RI600RN!9r;`8x2HZ(R
zK~#9!#g=<eQ+F1}0|=tst~2Y-v{Oed$~rE%w6s&)@d?PIB1kdB$L<sjB|s1;PXk0A
zt2`23AqgabKzJw;gn&RI&p={octi+LMT7tvAQ32)0_KIezrA;-v;Xc)5cfNCX72p%
zz2EbhbARXDAL@U|Y{!lr7CU$Dw6eCgwz9Oev_RHSTP;V&uPph3hiIv^w@yAhq8uI>
z-H^*iHiqQG%Eym;>-c;D+Ro12^1UbCzJ0qHgUNIfiNwRgZV^PxD26;Pr$S$TOE7-n
zNid%DOM=1)6sVrp1bRfGVFrWg^gb(MMy1jGJ3G7HrstMJ4rl*mwD&DA;7Edv2!_ZI
z!4&Jm@;mg77YlVqyfWV5<8q-EK3_wn($Mb(A|WB+WPLqP6P{RTJmQn5_fO=l<BFv#
zH0kVWPM>Op+&jMvUoVGOJy}E(8<!pZ=^Atp396~#YT$QIY%2Ng-Mjw)mwqgb%r@G3
zW^2zSK2XQ-#uUtvU*-j~>&sYH4+t#o0S{-_)%1~H6e+EWvG3COFaL5be>IFigIFxq
z7~)|vKy-9;5WAFPbUaVi{XO*V%Ow8fQ0h;rzDmXFvqqKnMaW$l2))w}?$2vRS(B@>
z^!|mOo9)v-x!q`dao8(oy^z6%Vq#)~OwGS7B_&0eoLTa2uV?P-^M!pKQC&)Yh~#y3
z`ovl@aa!Aal_P@!N~9oGp=n5)TyMhnE>_~&l{J3sq2|wh>C<5e3}b3qS{LGF3c#N-
zGBTC}qFIJR-<J=$ls_x;@0ep<ee!F;tr;zcG;gT8!XAP!^vB@Vte%^x)Kvw_SMvRZ
zD!TKX=S(|1SK=L1sLRSCEhAp00DPXEoelZni?t3h%^hd!6(uf-Ex;>V0xmE|0EROT
zFzjc*CtnI&5}Uy{L8aht7xRJLg&c5(H&yU;YUhJf0nF9BygUf;G6mou83w>aa5P^f
zcQ$!7%@jF?)q&&5BH&T*GdRytg0n^A;AEN@d=Xp&Y`k;9r^l226Yedqa*yUbu5ree
ztWYQg5aMMDz-PB_-(Cqxs?s|qwej5=rzyU&6=J}1P1JRT4xgyhhn+8-FuG<+z>SwW
zT*Q<v^xC-Q#|!dRg2%(zY$uYW786ymP9~FA5HC{zK8lZzAIL7`zOxIhmAKwl(0pZY
zh)9y?8C~$Lc|(W~YZP)Li9za|0UP^LkNe?;HsZqYDgmj$mjuB>V($G70)a4qc$orV
ze);m{l<Mjl$o+b?@)YN3iMM1a4XHrPj6OI^y@B&C?1$V*LXe@_2#9~B#|6I7MEVZA
zA-ZxW=tuGQ#_!cO7_VIUM+)MFGDTKaRtMmXI9FQTw()hmpwsQaOde)r?Z)*f9Ue{^
z>_rg+_smw1uG+X7Ijsx5@^n4++xGdaqv<^l@;Dv({QUem!~?YnnY+2U1y@(!GZftu
zzdfG$sL4~HBwrd`iwlP#QsB}f<^OS77xK?%Z)3c=U*A4OAK<2Q#J@E+w?LJZmCc6^
z9kQ^qvoqfe#LkPCE@ki<8VwEYGCh{n-{*37oO!PM^)0mQO``vkl?0zhi>dDQQ`Ae$
z0ZDc1kgm0@9aL0SfmxLbh{fXWs;a6AKR>^ZHwEG0;Tc|DUa6M$_Co^6Q*BxI<Wz3w
z%n-R_TFw$GrW(X!+CG^aR94+ldwcstm6eq>aBFLggL1iXZe9giT3WiUUAy+lW*{uK
zZL>Ur4g4XOLZ$tDzmB)o(J3@`c6A%;>KoPy;5FnP@(l8<v$OMG(P;EqQc@C-4GsbI
z!U7P9MDnPpC|lGfWdX;Z;c$TC^zY&D`<lgnr`W-RADupZ`VJP0h2rAkfauX97-A6&
z4i3&FCntZickf=*mdn=G*4o9zr8p!c1d51=0DOS}%&FC2e0+Qf9#CHP_V!zUj@-Y0
zzZDEYiHwXihK7cM8ZH;iyix+CQn}7xFtEpt9W&o@2pbz4OIKIdba=A9!{hOww6qjF
zpO^p(3kwFgLlWUu-?rrtd-m+HfFa^;-n^-YHzJ_XXh1$P3YM0Zj65EX>g(%kz2y)G
z4jeFtKSv<^lY2`f5<yN*4(RRc2aAh~P+MCY7ask8+;WJ0`}Uc^5Z}R@@Yk%YERdO*
z3A%ekK&4hAZ7Rg!aGz{B#I9YtQ1F~MMWIksbUGctCoj<2+6rDNl|U+$%41_=ZBZXW
z@SJccDk_@ba5#WOB7w%nMld-!34}u70O~{O#EBC&#l^+LT(~{qihzoW3LTY7MWa5X
zoSd9KW3$;(IJ6iH26y=IVKdZ+mV<-C?lWi3oP*mHN&f%WzX3})x($zUN7n!V002ov
JPDHLkV1mfBh8O?<
new file mode 100644
index 0000000000000000000000000000000000000000..b56a0bb79fc0403afca890a53945c9feba7a2092
GIT binary patch
literal 1866
zc$@)B2etT#P)<h;3K|Lk000e1NJLTq001BW001Be1^@s6b9#F800009a7bBm000}W
z000}W0bUxB8~^|S2XskIMF-am3IGBt_b3pM00006VoOIv0RI600RN!9r;`8x2G>bM
zK~#9!&6jOxTjv$WpXa{l>fM$l+mdBlwq;9BY`KwJyG??@!$~)?Eo=<Bj<V8ETh<RP
zY!CutU()XLx_;SO2K875W2`1*4o$kHTOiafW}Z{q@%xKp%P+Ftb)~EO@;uLuhQVL9
z78@_@FAn!|xt#OUx&L!67o#s0wpc72#+av+A_CHNox*j7PD%d}AR6r#-+KG)t935d
z%NDEkc>wS+$`Jf^m9p|#Hk<jw_3PK~Jb5y&pDKVPN%$A<yfbk2%-Qz|WqqGaETO5{
z9hA&f7-I-Itvr4vRF8%SJFweb^LXLO!Vg}5{YO*Pj+_Pn{^h&xeg}&G_Or)ZmOnm-
zGh(VC7tVKKv(v^9#*8Q`nwVT>x||n=&Pv>s;qJ=%+WPn3eDjU5lS1(5P&aPe80rpp
zkKO-t(>y*U8{xi?8XD+UBZDDg^LkW=x31!A_UJZ`t0IY#HoI2FvCV{eAmYE;)z$g%
z(W6K4lK=<^<aWF5t%1OMb88vt-gH?D_lI(=&xJ}|oeh?N%PegxL?H-~fR&f9%~GnX
zuhobsT0fs!u4|l0+WXqu-iI86>2z8?Q3tMFyY{Nr+w|J4zovC(tAGFerRagh<19AR
zS(qRR$__=zGUf_)6K`k;%PQis08x@<l|G(3usqjg^#xk}8xs=~(<kYG;BYv;7f%{2
zrSiFGZ|8E^ENKek@*>3!Sz)Az1WMq>jKcQqh~xJu&KXEBIl2Ow%F?#@B(4YQoz9ox
zmQe`fxByOY|GA|DN-YiUoubXYwM#hNE}2v;2x^_c+eC&~6~KlOpkSRyrc9AH#GJ*N
zvo_Vc;;B?qOVAvx=BjcY8$c9ASFwUsbG<udvzy7Mzq#{6-r+-kv$zq$9AcFmBJv)h
z<rJb?2|`9xmC*~=fBLIJgF9W=$Z95&=sGC?&#EVa$OM~3;Y7j67YXbH5t$veNHmLx
z=Ly2Bh%}>s47G$*7)MPmAs##-*sTi3^OWQGqp3P3fTF2tq0S*#Rte!1M%8cr{MDN^
zHc_#QoCdqc5V#=0aHCEcS0PN04Q47-3~4`+vok`u`Wlm<Y1u+G*Kq+jh<u??SPnLs
zcr}x+Av)z{O0_a1(>Wwl0T(zC=P?9>bDhUBR4L1hsT7JsT}P<dDrGX6<!Y{z04Q5q
zTjPEg<NUl4FyxAvR1A?;cOSyY#A9L=ux=HxF2OkmtpHDAq7i|VR7oo2J9=6KE*{?+
zKWPW(*x1;uL}F{_yBFNP(n74gl9nBcMocPYJf#R%AtVlyDwIkXujo`%vt@f}HPQ0Y
zfTw*gvAO%<hkv?N&2^$hL<q?<#)<>c?ki_}9{)dA3OQyqm#M|1BMvjd5LYsom{F-E
ztq@x-DZ5IG+rcYta`~*MY{3{moSmJ0ud%Ta9~>O8le`Pq`uh5UAPW2o=Ym5Q0`AV;
zSW!x3HMK+$pVg@OKsM~Dbh$Pk%lK;Jd*@&25JrN|f-RLw;gQRi!$TJ@4n-o7VaWAh
zadA;QE<jcK{QUf6E}KhswRs0#?Dd5EokFCAl6H@x1$~Or8)22fVTU&SVt{oV#O70@
zAAIn$a5$vw?d^qqO-*f)NMF?F^$x;fyFW8CQ#uB~5yaZs+CT2zz59_t3`Jl{okvjo
z0khK5#N`{gT+Fn+GP8bn{LjC8>*md$EG{nGg$a7Rv9a-5a(`cHZf!-~XU=rAG&f(W
zt*w19IXU^IO9_7ooC~7q@K{wAV(0Kk5GWW7+M1i2f8Ej1@d~^V@i(qsMd5Ha+S%UP
zynXxjOQWNsQ!r&;P~^XhL6jl(A!3KIe|U|dLuIpB9ai~AVB!XNsr4@}En%zGiaJA~
z+U`*3+ch;c^Sisdt6<J!031`WgbV=qm{RJ1Nf=yMSim6E*4|<5i$uN!k7E}=KZj1R
zQwBIvKA$I0^b=jz`L?#Uiz_QDTt!ik*Y7ty8;xFZxm<d&Se%4uqo)jTq+BjXHBEa6
zQ3{8{!`s{2d^Vj%b)I_u+5YHP8X6j0s;d5dX=%wg0yt&CzhuyfNtljAPfyQf=#03N
zNFckziO-#TW)KY9Wf;cCb8~a*=>r@YlYt**p!hsMe3cMl+1OY|CdrI@dV6}?+uNT9
z<KCa1o-Um}z>z1aAd9jrPxSWoeht2`9BZqqhy!zm!r^up-+%849{mpm&l_!SZpJE=
z%3lED5*X19CPccXA?Sh^JaL{!PeHL*Y#%%^4iLj$5SSCeUQl5yf6Sw&q<B1@OD2<d
z0OEqlWU9Y+@7^1*@_&z>w)*<|+#@3+U-$d{82vx!Ul0{#Wq9p+B>(^b07*qoM6N<$
Eg7rj$G5`Po
new file mode 100644
--- /dev/null
+++ b/libgui/src/m-editor/file-editor-interface.h
@@ -0,0 +1,83 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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/>.
+
+*/
+
+#ifndef FILEEDITORINTERFACE_H
+#define FILEEDITORINTERFACE_H
+
+#include <QMenu>
+#include <QToolBar>
+#include "octave-dock-widget.h"
+
+class file_editor_interface : public octave_dock_widget
+{
+  Q_OBJECT
+
+  public:
+  file_editor_interface (QWidget *p)
+    : octave_dock_widget (p)
+  {
+    setObjectName ("FileEditor");
+  }
+
+  virtual ~file_editor_interface () { }
+
+  virtual QMenu *get_mru_menu ( ) = 0;
+  virtual QMenu *debug_menu () = 0;
+  virtual QToolBar *toolbar () = 0;
+
+  virtual void handle_enter_debug_mode (void) = 0;
+  virtual void handle_exit_debug_mode (void) = 0;
+
+  virtual void
+  handle_insert_debugger_pointer_request (const QString& file, int line) = 0;
+
+  virtual void
+  handle_delete_debugger_pointer_request (const QString& file, int line) = 0;
+
+  virtual void
+  handle_update_breakpoint_marker_request (bool insert, const QString& file,
+                                           int line) = 0;
+
+  virtual void handle_edit_file_request (const QString& file) = 0;
+
+  virtual void set_focus () = 0;
+
+  virtual void connect_visibility_changed (void) = 0;
+
+public slots:
+  virtual void request_new_file (const QString& command = QString ()) = 0;
+  virtual void request_new_script (const QString& command = QString ()) = 0;
+  virtual void request_new_function (const QString& command = QString ()) = 0;
+  virtual void request_open_file () = 0;
+  virtual void request_open_file (const QString& openFileName, int line = -1,
+                                  bool debug_pointer = false,
+                                  bool breakpoint_marker = false,
+                                  bool insert = true) = 0;
+//signals:
+
+//protected:
+
+//protected slots:
+
+};
+
+#endif // FILEEDITORINTERFACE_H
new file mode 100644
--- /dev/null
+++ b/libgui/src/m-editor/file-editor-tab.cc
@@ -0,0 +1,1299 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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
+
+#ifdef HAVE_QSCINTILLA
+
+#include <Qsci/qsciapis.h>
+// Not available in the Debian repos yet!
+// #include <Qsci/qscilexeroctave.h>
+#include "lexer-octave-gui.h"
+#include <Qsci/qscilexercpp.h>
+#include <Qsci/qscilexerbash.h>
+#include <Qsci/qscilexerperl.h>
+#include <Qsci/qscilexerbatch.h>
+#include <Qsci/qscilexerdiff.h>
+#include <Qsci/qsciprinter.h>
+#include "resource-manager.h"
+#include <QApplication>
+#include <QFileDialog>
+#include <QMessageBox>
+#include <QTextStream>
+#include <QVBoxLayout>
+#include <QInputDialog>
+#include <QPrintDialog>
+
+#include "file-editor-tab.h"
+#include "file-editor.h"
+
+#include "cmd-edit.h"
+
+#include "builtin-defun-decls.h"
+#include "debug.h"
+#include "load-path.h"
+#include "octave-link.h"
+#include "oct-env.h"
+#include "utils.h"
+
+// Make parent null for the file editor tab so that warning
+// WindowModal messages don't affect grandparents.
+file_editor_tab::file_editor_tab (const QString& directory_arg)
+{
+  QString directory = directory_arg;
+
+  // Make sure there is a slash at the end of the directory name
+  // for identification when saved later.
+  if (directory.count () && directory.at (directory.count () - 1) != '/')
+    directory.append ("/");
+
+  _file_name = directory;
+
+  _edit_area = new QsciScintilla (this);
+
+  // Leave the find dialog box out of memory until requested.
+  _find_dialog = 0;
+  _find_dialog_is_visible = false;
+
+  // symbols
+  _edit_area->setMarginType (1, QsciScintilla::SymbolMargin);
+  _edit_area->setMarginSensitivity (1, true);
+  _edit_area->markerDefine (QsciScintilla::RightTriangle, bookmark);
+  _edit_area->markerDefine (QPixmap (":/actions/icons/redled.png"),
+                            breakpoint);
+  _edit_area->markerDefine (QPixmap (":/actions/icons/arrow_right.png"),
+                            debugger_position);
+
+  connect (_edit_area, SIGNAL (marginClicked (int, int,
+                                              Qt::KeyboardModifiers)),
+           this, SLOT (handle_margin_clicked (int, int,
+                                              Qt::KeyboardModifiers)));
+
+  // line numbers
+  _edit_area->setMarginsForegroundColor (QColor (96, 96, 96));
+  _edit_area->setMarginsBackgroundColor (QColor (232, 232, 220));
+  _edit_area->setMarginType (2, QsciScintilla::TextMargin);
+
+  // code folding
+  _edit_area->setMarginType (3, QsciScintilla::SymbolMargin);
+  _edit_area->setFolding (QsciScintilla::BoxedTreeFoldStyle , 3);
+
+  //highlight current line color
+  _edit_area->setCaretLineBackgroundColor (QColor (245, 245, 245));
+
+  // other features
+  _edit_area->setBraceMatching (QsciScintilla::StrictBraceMatch);
+  _edit_area->setAutoIndent (true);
+  _edit_area->setIndentationWidth (2);
+  _edit_area->setIndentationsUseTabs (false);
+
+  _edit_area->setUtf8 (true);
+
+  // auto completion
+  _edit_area->autoCompleteFromAll ();
+  _edit_area->setAutoCompletionSource (QsciScintilla::AcsAll);
+
+  QVBoxLayout *edit_area_layout = new QVBoxLayout ();
+  edit_area_layout->addWidget (_edit_area);
+  edit_area_layout->setMargin (0);
+  setLayout (edit_area_layout);
+
+  // connect modified signal
+  connect (_edit_area, SIGNAL (modificationChanged (bool)),
+           this, SLOT (update_window_title (bool)));
+
+  connect (_edit_area, SIGNAL (copyAvailable (bool)),
+           this, SLOT (handle_copy_available (bool)));
+
+  connect (&_file_system_watcher, SIGNAL (fileChanged (const QString&)),
+           this, SLOT (file_has_changed (const QString&)));
+
+  QSettings *settings = resource_manager::get_settings ();
+  if (settings)
+    notice_settings (settings);
+}
+
+file_editor_tab::~file_editor_tab (void)
+{
+  // Destroy items attached to _edit_area.
+  QsciLexer *lexer = _edit_area->lexer ();
+  if (lexer)
+    {
+      delete lexer;
+      _edit_area->setLexer (0);
+    }
+  if (_find_dialog)
+    {
+      delete _find_dialog;
+      _find_dialog = 0;
+    }
+
+  // Destroy _edit_area.
+  delete _edit_area;
+}
+
+void
+file_editor_tab::closeEvent (QCloseEvent *e)
+{
+  // ignore close event if file is not saved and user cancels
+  // closing this window
+  if (check_file_modified () == QMessageBox::Cancel)
+    e->ignore ();
+  else
+    e->accept ();
+}
+
+void
+file_editor_tab::set_file_name (const QString& fileName)
+{
+  // update tracked file if we really have a file on disk
+  QStringList trackedFiles = _file_system_watcher.files ();
+  if (!trackedFiles.isEmpty ())
+    _file_system_watcher.removePath (_file_name);
+  if (!fileName.isEmpty ())
+    _file_system_watcher.addPath (fileName);
+  _file_name = fileName;
+
+  // update lexer after _file_name change
+  update_lexer ();
+
+  // update the file editor with current editing directory
+  emit editor_state_changed (_copy_available, QDir::cleanPath (_file_name));
+  // add the new file to the mru list
+  emit mru_add_file (QDir::cleanPath (_file_name));
+}
+
+void
+file_editor_tab::handle_margin_clicked (int margin, int line,
+                                       Qt::KeyboardModifiers state)
+{
+  if (margin == 1)
+    {
+      unsigned int markers_mask = _edit_area->markersAtLine (line);
+
+      if (state & Qt::ControlModifier)
+        {
+          if (markers_mask && (1 << bookmark))
+            _edit_area->markerDelete (line, bookmark);
+          else
+            _edit_area->markerAdd (line, bookmark);
+        }
+      else
+        {
+          if (markers_mask && (1 << breakpoint))
+            request_remove_breakpoint (line);
+          else
+            request_add_breakpoint (line);
+        }
+    }
+}
+
+void
+file_editor_tab::update_lexer ()
+{
+  QsciLexer *lexer = _edit_area->lexer ();
+  delete lexer;
+
+  if (_file_name.endsWith (".m")
+      || _file_name.endsWith (".M")
+      || _file_name.endsWith ("octaverc"))
+    {
+      lexer = new lexer_octave_gui ();
+    }
+  else if (_file_name.endsWith (".c")
+           || _file_name.endsWith (".cc")
+           || _file_name.endsWith (".cpp")
+           || _file_name.endsWith (".cxx")
+           || _file_name.endsWith (".c++")
+           || _file_name.endsWith (".h")
+           || _file_name.endsWith (".hh")
+           || _file_name.endsWith (".hpp")
+           || _file_name.endsWith (".h++"))
+    {
+      lexer = new QsciLexerCPP ();
+    }
+  else if (_file_name.endsWith (".pl"))
+    {
+      lexer = new QsciLexerPerl ();
+    }
+  else if (_file_name.endsWith (".bat"))
+    {
+      lexer = new QsciLexerBatch ();
+    }
+  else if (_file_name.endsWith (".diff"))
+    {
+      lexer = new QsciLexerDiff ();
+    }
+  else // Default to bash lexer.
+    {
+      lexer = new QsciLexerBash ();
+    }
+
+  QSettings *settings = resource_manager::get_settings ();
+  if (settings)
+    lexer->readSettings (*settings);
+  _edit_area->setLexer (lexer);
+
+}
+
+// slot for fetab_set_focus: sets the focus to the current edit area
+void
+file_editor_tab::set_focus (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+  _edit_area->setFocus ();
+}
+
+void
+file_editor_tab::undo (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  _edit_area->undo ();
+}
+
+void
+file_editor_tab::redo (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  _edit_area->redo ();
+}
+
+void
+file_editor_tab::copy (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  _edit_area->copy ();
+}
+
+void
+file_editor_tab::cut (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  _edit_area->cut ();
+}
+
+void
+file_editor_tab::paste (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  _edit_area->paste ();
+}
+
+void
+file_editor_tab::save_file (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  save_file (_file_name);
+}
+void
+
+file_editor_tab::save_file (const QWidget *ID, const QString& fileName,
+                            bool remove_on_success)
+{
+  if (ID != this)
+    return;
+
+  save_file (fileName, remove_on_success);
+}
+
+void
+file_editor_tab::save_file_as (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  save_file_as ();
+}
+
+void
+file_editor_tab::print_file (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  QsciPrinter *printer = new QsciPrinter (QPrinter::HighResolution);
+
+  QPrintDialog printDlg (printer, this);
+
+  if (printDlg.exec () == QDialog::Accepted)
+    printer->printRange (_edit_area);
+
+  delete printer;
+}
+
+
+void
+file_editor_tab::run_file_callback (const bp_info& info)
+{
+  if (file_in_path (info.file, info.dir))
+    {
+      std::string pending_input = command_editor::get_current_line ();
+
+      command_editor::set_initial_input (pending_input);
+
+      command_editor::replace_line (info.function_name);
+      command_editor::redisplay ();
+
+      // We are executing inside the command editor event loop.  Force
+      // the current line to be returned for processing.
+      command_editor::interrupt ();
+    }
+}
+
+void
+file_editor_tab::run_file (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  if (_edit_area->isModified ())
+    save_file (_file_name);
+
+  QFileInfo file_info (_file_name);
+  QString dir = file_info.absolutePath ();
+  QString function_name = file_info.fileName ();
+  function_name.chop (file_info.suffix ().length () + 1);
+
+  bp_info info (_file_name, dir, function_name, 1);
+
+  octave_link::post_event (this, &file_editor_tab::run_file_callback, info);
+}
+
+void
+file_editor_tab::toggle_bookmark (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  int line, cur;
+  _edit_area->getCursorPosition (&line, &cur);
+
+  if (_edit_area->markersAtLine (line) && (1 << bookmark))
+    _edit_area->markerDelete (line, bookmark);
+  else
+    _edit_area->markerAdd (line, bookmark);
+}
+
+void
+file_editor_tab::next_bookmark (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  int line, cur;
+  _edit_area->getCursorPosition (&line, &cur);
+
+  if (_edit_area->markersAtLine (line) && (1 << bookmark))
+    line++; // we have a breakpoint here, so start search from next line
+
+  int nextline = _edit_area->markerFindNext (line, (1 << bookmark));
+
+  _edit_area->setCursorPosition (nextline, 0);
+}
+
+void
+file_editor_tab::previous_bookmark (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  int line, cur;
+  _edit_area->getCursorPosition (&line, &cur);
+
+  if (_edit_area->markersAtLine (line) && (1 << bookmark))
+    line--; // we have a breakpoint here, so start search from prev line
+
+  int prevline = _edit_area->markerFindPrevious (line, (1 << bookmark));
+
+  _edit_area->setCursorPosition (prevline, 0);
+}
+
+void
+file_editor_tab::remove_bookmark (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  _edit_area->markerDeleteAll (bookmark);
+}
+
+bool
+file_editor_tab::file_in_path (const std::string& file, const std::string& dir)
+{
+  bool ok = false;
+  bool addpath_option = true;
+
+  std::string curr_dir = octave_env::get_current_directory ();
+
+  if (same_file (curr_dir, dir))
+    ok = true;
+  else
+    {
+      bool dir_in_load_path = load_path::contains_canonical (dir);
+
+      std::string base_file = octave_env::base_pathname (file);
+      std::string lp_file = load_path::find_file (base_file);
+
+      if (dir_in_load_path)
+        {
+          if (same_file (lp_file, file))
+            ok = true;
+        }
+      else
+        {
+          // File directory is not in path.  Is the file in the path in
+          // the current directory?  If so, then changing the current
+          // directory will be needed.  Adding directory to path is
+          // not enough because the file in the current directory would
+          // still be found.
+
+          if (same_file (lp_file, base_file))
+            {
+              if (same_file (curr_dir, dir))
+                ok = true;
+              else
+                addpath_option = false;
+            }
+        }
+    }
+
+  if (! ok)
+    {
+      int action
+        = octave_link::debug_cd_or_addpath_error (file, dir, addpath_option);
+      switch (action)
+        {
+        case 1:
+          Fcd (ovl (dir));
+          ok = true;
+          break;
+
+        case 2:
+          load_path::prepend (dir);
+          ok = true;
+          break;
+
+        default:
+          break;
+        }
+    }
+
+  return ok;
+}
+
+void
+file_editor_tab::add_breakpoint_callback (const bp_info& info)
+{
+  bp_table::intmap line_info;
+  line_info[0] = info.line;
+
+  if (file_in_path (info.file, info.dir))
+    bp_table::add_breakpoint (info.function_name, line_info);
+}
+
+void
+file_editor_tab::remove_breakpoint_callback (const bp_info& info)
+{
+  bp_table::intmap line_info;
+  line_info[0] = info.line;
+
+  if (file_in_path (info.file, info.dir))
+    bp_table::remove_breakpoint (info.function_name, line_info);
+}
+
+void
+file_editor_tab::remove_all_breakpoints_callback (const bp_info& info)
+{
+  if (file_in_path (info.file, info.dir))
+    bp_table::remove_all_breakpoints_in_file (info.function_name, true);
+}
+
+void
+file_editor_tab::request_add_breakpoint (int line)
+{
+  QFileInfo file_info (_file_name);
+  QString dir = file_info.absolutePath ();
+  QString function_name = file_info.fileName ();
+
+  // We have to cut off the suffix, because octave appends it.
+  function_name.chop (file_info.suffix ().length () + 1);
+
+  bp_info info (_file_name, dir, function_name, line+1);
+
+  octave_link::post_event
+    (this, &file_editor_tab::add_breakpoint_callback, info);
+}
+
+void
+file_editor_tab::request_remove_breakpoint (int line)
+{
+  QFileInfo file_info (_file_name);
+  QString dir = file_info.absolutePath ();
+  QString function_name = file_info.fileName ();
+
+  // We have to cut off the suffix, because octave appends it.
+  function_name.chop (file_info.suffix ().length () + 1);
+
+  bp_info info (_file_name, dir, function_name, line+1);
+
+  octave_link::post_event
+    (this, &file_editor_tab::remove_breakpoint_callback, info);
+}
+
+void
+file_editor_tab::toggle_breakpoint (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  int line, cur;
+  _edit_area->getCursorPosition (&line, &cur);
+
+  if (_edit_area->markersAtLine (line) && (1 << breakpoint))
+    request_remove_breakpoint (line);
+  else
+    request_add_breakpoint (line);
+}
+
+void
+file_editor_tab::next_breakpoint (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  int line, cur;
+  _edit_area->getCursorPosition (&line, &cur);
+
+  if (_edit_area->markersAtLine (line) && (1 << breakpoint))
+    line++; // we have a breakpoint here, so start search from next line
+
+  int nextline = _edit_area->markerFindNext (line, (1 << breakpoint));
+
+  _edit_area->setCursorPosition (nextline, 0);
+}
+
+void
+file_editor_tab::previous_breakpoint (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  int line, cur, prevline;
+  _edit_area->getCursorPosition (&line, &cur);
+
+  if (_edit_area->markersAtLine (line) && (1 << breakpoint))
+    line--; // we have a breakpoint here, so start search from prev line
+
+  prevline = _edit_area->markerFindPrevious (line, (1 << breakpoint));
+
+  _edit_area->setCursorPosition (prevline, 0);
+}
+
+void
+file_editor_tab::remove_all_breakpoints (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  QFileInfo file_info (_file_name);
+  QString dir = file_info.absolutePath ();
+  QString function_name = file_info.fileName ();
+
+  // We have to cut off the suffix, because octave appends it.
+  function_name.chop (file_info.suffix ().length () + 1);
+
+  bp_info info (_file_name, dir, function_name, 0);
+
+  octave_link::post_event
+    (this, &file_editor_tab::remove_all_breakpoints_callback, info);
+}
+
+void
+file_editor_tab::comment_selected_text (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  do_comment_selected_text (true);
+}
+
+void
+file_editor_tab::uncomment_selected_text (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  do_comment_selected_text (false);
+}
+
+void
+file_editor_tab::handle_find_dialog_finished (int)
+{
+  // Find dialog is going to hide.  Save location of window for
+  // when it is reshown.
+  _find_dialog_geometry = _find_dialog->geometry ();
+  _find_dialog_is_visible = false;
+}
+
+void
+file_editor_tab::find (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  // The find_dialog feature doesn't need a slot for return info.
+  // Rather than Qt::DeleteOnClose, let the find feature hang about
+  // in case it contains useful information like previous searches
+  // and so on.  Perhaps one find dialog for the whole editor is
+  // better, but individual find dialogs has the nice feature of
+  // retaining position per file editor tabs, which can be undocked.
+
+  if (!_find_dialog)
+    {
+      _find_dialog = new find_dialog (_edit_area, 
+                                      qobject_cast<QWidget *> (sender ()));
+      connect (_find_dialog, SIGNAL (finished (int)),
+               this, SLOT (handle_find_dialog_finished (int)));
+      _find_dialog->setWindowModality (Qt::NonModal);
+      _find_dialog_geometry = _find_dialog->geometry ();
+    }
+
+  if (!_find_dialog->isVisible ())
+    {
+      _find_dialog->setGeometry (_find_dialog_geometry);
+      _find_dialog->show ();
+      _find_dialog_is_visible = true;
+    }
+
+  _find_dialog->activateWindow ();
+  _find_dialog->init_search_text ();
+
+}
+
+void
+file_editor_tab::goto_line (const QWidget *ID, int line)
+{
+  if (ID != this)
+    return;
+
+  if (line <= 0)  // ask for desired line
+    {
+      bool ok = false;
+      int index;
+      _edit_area->getCursorPosition (&line, &index);
+      line = QInputDialog::getInt (_edit_area, tr ("Goto line"),
+                                   tr ("Line number"), line+1, 1,
+                                   _edit_area->lines (), 1, &ok);
+      if (ok)
+        {
+          _edit_area->setCursorPosition (line-1, 0);
+          center_current_line ();
+        }
+    }
+  else  // go to given line without dialog
+    _edit_area->setCursorPosition (line-1, 0);
+}
+
+
+void
+file_editor_tab::do_comment_selected_text (bool comment)
+{
+  if (_edit_area->hasSelectedText ())
+    {
+      int lineFrom, lineTo, colFrom, colTo;
+      _edit_area->getSelection (&lineFrom, &colFrom, &lineTo, &colTo);
+
+      if (colTo == 0)  // the beginning of last line is not selected
+        lineTo--;        // stop at line above
+
+      _edit_area->beginUndoAction ();
+
+      for (int i = lineFrom; i <= lineTo; i++)
+        {
+          if (comment)
+            _edit_area->insertAt ("%", i, 0);
+          else
+            {
+              QString line (_edit_area->text (i));
+              if (line.startsWith ("%"))
+                {
+                  _edit_area->setSelection (i, 0, i, 1);
+                  _edit_area->removeSelectedText ();
+                }
+            }
+        }
+
+      _edit_area->endUndoAction ();
+    }
+}
+
+void
+file_editor_tab::update_window_title (bool modified)
+{
+  QString title ("");
+  QString tooltip ("");
+
+  if (_file_name.isEmpty () || _file_name.at (_file_name.count () - 1) == '/')
+    title = tr ("<unnamed>");
+  else
+    {
+      if (_long_title)
+        title = _file_name;
+      else
+        {
+          QFileInfo file (_file_name);
+          title = file.fileName ();
+          tooltip = _file_name;
+        }
+    }
+
+  if (modified)
+    emit file_name_changed (title.prepend ("* "), tooltip);
+  else
+    emit file_name_changed (title, tooltip);
+}
+
+void
+file_editor_tab::handle_copy_available (bool enableCopy)
+{
+  _copy_available = enableCopy;
+  emit editor_state_changed (_copy_available, QDir::cleanPath (_file_name));
+}
+
+int
+file_editor_tab::check_file_modified ()
+{
+  int decision = QMessageBox::Yes;
+  if (_edit_area->isModified ())
+    {
+      // File is modified but not saved, ask user what to do.  The file
+      // editor tab can't be made parent because it may be deleted depending
+      // upon the response.  Instead, change the _edit_area to read only.
+      QMessageBox* msgBox
+        = new QMessageBox (QMessageBox::Warning, tr ("Octave Editor"),
+                           tr ("The file\n"
+                               "%1\n"
+                               "is about to be closed but has been modified.\n"
+                               "Do you want to cancel closing, save or discard the changes?").
+                           arg (_file_name),
+                           QMessageBox::Save | QMessageBox::Cancel | QMessageBox::Discard, 0);
+
+      msgBox->setDefaultButton (QMessageBox::Save);
+      _edit_area->setReadOnly (true);
+      connect (msgBox, SIGNAL (finished (int)),
+               this, SLOT (handle_file_modified_answer (int)));
+      msgBox->setWindowModality (Qt::NonModal);
+      msgBox->setAttribute (Qt::WA_DeleteOnClose);
+      msgBox->show ();
+
+      return QMessageBox::Cancel;
+    }
+  else
+    {
+      // Nothing was modified, just remove from editor.
+      emit tab_remove_request ();
+    }
+ 
+  return decision;
+}
+
+void
+file_editor_tab::handle_file_modified_answer (int decision)
+{
+  if (decision == QMessageBox::Save)
+    {
+      // Save file, then remove from editor.
+      save_file (_file_name, true);
+    }
+  else if (decision == QMessageBox::Discard)
+    {
+      // User doesn't want to save, just remove from editor.
+      emit tab_remove_request ();
+    }
+  else
+    {
+      // User canceled, allow editing again.
+      _edit_area->setReadOnly (false);
+    }
+}
+
+void
+file_editor_tab::set_modified (bool modified)
+{
+  _edit_area->setModified (modified);
+}
+
+QString
+file_editor_tab::load_file (const QString& fileName)
+{
+  QFile file (fileName);
+  if (!file.open (QFile::ReadOnly))
+    return file.errorString ();
+
+  QTextStream in (&file);
+  QApplication::setOverrideCursor (Qt::WaitCursor);
+  _edit_area->setText (in.readAll ());
+  QApplication::restoreOverrideCursor ();
+
+  set_file_name (fileName);
+  update_window_title (false); // window title (no modification)
+  _edit_area->setModified (false); // loaded file is not modified yet
+
+  return QString ();
+}
+
+void
+file_editor_tab::new_file (const QString &commands)
+{
+  update_window_title (false); // window title (no modification)
+  _edit_area->setText (commands);
+  _edit_area->setModified (false); // new file is not modified yet
+}
+
+void
+file_editor_tab::save_file (const QString& saveFileName, bool remove_on_success)
+{
+  // If it is a new file with no name, signal that saveFileAs
+  // should be performed.
+  if (saveFileName.isEmpty ()
+      || saveFileName.at (saveFileName.count () - 1) == '/')
+     {
+      save_file_as (remove_on_success);
+      return;
+    }
+
+  // stop watching file
+  QStringList trackedFiles = _file_system_watcher.files ();
+  if (!trackedFiles.isEmpty ())
+    _file_system_watcher.removePath (saveFileName);
+
+  // open the file for writing
+  QFile file (saveFileName);
+  if (!file.open (QIODevice::WriteOnly))
+    {
+      // Unsuccessful, begin watching file again if it was being
+      // watched previously.
+      if (trackedFiles.contains (saveFileName))
+        _file_system_watcher.addPath (saveFileName);
+
+      // Create a NonModal message about error.
+      QMessageBox* msgBox
+        = new QMessageBox (QMessageBox::Critical,
+                           tr ("Octave Editor"),
+                           tr ("Could not open file %1 for write:\n%2.").
+                           arg (saveFileName).arg (file.errorString ()),
+                           QMessageBox::Ok, 0);
+      msgBox->setWindowModality (Qt::NonModal);
+      msgBox->setAttribute (Qt::WA_DeleteOnClose);
+      msgBox->show ();
+
+      return;
+    }
+
+  // save the contents into the file
+  QTextStream out (&file);
+  QApplication::setOverrideCursor (Qt::WaitCursor);
+  out << _edit_area->text ();
+  QApplication::restoreOverrideCursor ();
+  file.close ();
+
+  // save file name after closing file as set_file_name starts watching again
+  set_file_name (saveFileName);
+
+  // set the window title to actual file name (not modified)
+  update_window_title (false);
+
+  // files is save -> not modified
+  _edit_area->setModified (false);
+
+  if (remove_on_success)
+    {
+      emit tab_remove_request ();
+      return;  // Don't touch member variables after removal
+    }
+}
+
+void
+file_editor_tab::save_file_as (bool remove_on_success)
+{
+  // Simply put up the file chooser dialog box with a slot connection
+  // then return control to the system waiting for a file selection.
+
+  // If the tab is removed in response to a QFileDialog signal, the tab
+  // can't be a parent.
+  QFileDialog* fileDialog;
+  if (remove_on_success)
+    {
+      // If tab is closed, "this" cannot be parent in which case modality
+      // has no effect.  Disable editing instead.
+      _edit_area->setReadOnly (true);
+      fileDialog = new QFileDialog ();
+    }
+  else
+    fileDialog = new QFileDialog (this);
+
+  if (!_file_name.isEmpty () && _file_name.at (_file_name.count () - 1) != '/')
+    {
+      fileDialog->selectFile (_file_name);
+    }
+  else
+    {
+      fileDialog->selectFile ("");
+
+      if (_file_name.isEmpty ())
+        fileDialog->setDirectory (QDir::currentPath ());
+      else
+        {
+          // The file name is actually the directory name from the
+          // constructor argument.
+          fileDialog->setDirectory (_file_name);
+        }
+    }
+
+  fileDialog->setNameFilter (tr ("Octave Files (*.m);;All Files (*)"));
+  fileDialog->setDefaultSuffix ("m");
+  fileDialog->setAcceptMode (QFileDialog::AcceptSave);
+  fileDialog->setViewMode (QFileDialog::Detail);
+
+  if (remove_on_success)
+    {
+      connect (fileDialog, SIGNAL (fileSelected (const QString&)),
+               this, SLOT (handle_save_file_as_answer_close (const QString&)));
+
+      connect (fileDialog, SIGNAL (rejected ()),
+               this, SLOT (handle_save_file_as_answer_cancel ()));
+    }
+  else
+    {
+      connect (fileDialog, SIGNAL (fileSelected (const QString&)),
+               this, SLOT (handle_save_file_as_answer (const QString&)));
+    }
+
+  fileDialog->setWindowModality (Qt::WindowModal);
+  fileDialog->setAttribute (Qt::WA_DeleteOnClose);
+  fileDialog->show ();
+}
+
+void
+file_editor_tab::message_duplicate_file_name (const QString& saveFileName)
+{
+  // Could overwrite the file here (and tell user the file was
+  // overwritten), but the user could have unintentionally
+  // selected the same name not intending to overwrite.
+
+  // Create a NonModal message about error.
+  QMessageBox* msgBox
+    = new QMessageBox (QMessageBox::Critical, tr ("Octave Editor"),
+                       tr ("File not saved! The selected file name\n%1\n"
+                           "is the same as the current file name").
+                       arg (saveFileName),
+                       QMessageBox::Ok, 0);
+
+  msgBox->setWindowModality (Qt::NonModal);
+  msgBox->setAttribute (Qt::WA_DeleteOnClose);
+  msgBox->show ();
+}
+
+void
+file_editor_tab::handle_save_file_as_answer (const QString& saveFileName)
+{
+  if (saveFileName == _file_name)
+    {
+      message_duplicate_file_name (saveFileName);
+      // Nothing done, allow editing again.
+      _edit_area->setReadOnly (false);
+    }
+  else
+    {
+      // Have editor check for conflict, do not delete tab after save.
+      emit editor_check_conflict_save (saveFileName, false);
+    }
+}
+
+void
+file_editor_tab::handle_save_file_as_answer_close (const QString& saveFileName)
+{
+  if (saveFileName == _file_name)
+    {
+      message_duplicate_file_name (saveFileName);
+      // Nothing done, allow editing again.
+      _edit_area->setReadOnly (false);
+    }
+  else
+    {
+      // Have editor check for conflict, delete tab after save.
+      emit editor_check_conflict_save (saveFileName, true);
+    }
+}
+
+void
+file_editor_tab::handle_save_file_as_answer_cancel ()
+{
+  // User canceled, allow editing again.
+  _edit_area->setReadOnly (false);
+}
+
+void
+file_editor_tab::file_has_changed (const QString&)
+{
+  // Prevent popping up multiple message boxes when the file has
+  // been changed multiple times by temporarily removing from the
+  // file watcher.
+  QStringList trackedFiles = _file_system_watcher.files ();
+  if (!trackedFiles.isEmpty ())
+    _file_system_watcher.removePath (_file_name);
+
+  if (QFile::exists (_file_name))
+    {
+      // Create a WindowModal message that blocks the edit area
+      // by making _edit_area parent.
+      QMessageBox* msgBox
+        = new QMessageBox (QMessageBox::Warning,
+                           tr ("Octave Editor"),
+                           tr ("It seems that \'%1\' has been modified by another application. Do you want to reload it?").
+                           arg (_file_name),
+                           QMessageBox::Yes | QMessageBox::No, this);
+
+      connect (msgBox, SIGNAL (finished (int)),
+               this, SLOT (handle_file_reload_answer (int)));
+
+      msgBox->setWindowModality (Qt::WindowModal);
+      msgBox->setAttribute (Qt::WA_DeleteOnClose);
+      msgBox->show ();
+    }
+  else
+    {
+      QString modified = "";
+      if (_edit_area->isModified ())
+        modified = tr ("\n\nWarning: The contents in the editor is modified!");
+
+      // Create a WindowModal message. The file editor tab can't be made
+      // parent because it may be deleted depending upon the response.
+      // Instead, change the _edit_area to read only.
+      QMessageBox* msgBox
+        = new QMessageBox (QMessageBox::Warning, tr ("Octave Editor"),
+                           tr ("It seems that the file\n"
+                               "%1\n"
+                               "has been deleted or renamed. Do you want to save it now?%2").
+                           arg (_file_name).arg (modified),
+                           QMessageBox::Save | QMessageBox::Close, 0);
+
+      _edit_area->setReadOnly (true);
+
+      connect (msgBox, SIGNAL (finished (int)),
+               this, SLOT (handle_file_resave_answer (int)));
+
+      msgBox->setWindowModality (Qt::WindowModal);
+      msgBox->setAttribute (Qt::WA_DeleteOnClose);
+      msgBox->show ();
+    }
+}
+
+void
+file_editor_tab::notice_settings (const QSettings *settings)
+{
+  // QSettings pointer is checked before emitting.
+
+  update_lexer ();
+
+  QFontMetrics lexer_font_metrics (_edit_area->lexer ()->defaultFont (0));
+
+  _edit_area->setCaretLineVisible
+    (settings->value ("editor/highlightCurrentLine", true).toBool ());
+
+  if (settings->value ("editor/codeCompletion", true).toBool ())
+    _edit_area->setAutoCompletionThreshold (1);
+  else
+    _edit_area->setAutoCompletionThreshold (-1);
+
+  if (settings->value ("editor/showLineNumbers", true).toBool ())
+    {
+      _edit_area->setMarginLineNumbers (2, true);
+      _edit_area->setMarginWidth (2, lexer_font_metrics.width ("9999"));
+    }
+  else
+    {
+      _edit_area->setMarginLineNumbers (2, false);
+      _edit_area->setMarginWidth (2, 0);
+    }
+
+  _long_title = settings->value ("editor/longWindowTitle", false).toBool ();
+
+  update_window_title (false);
+}
+
+void
+file_editor_tab::conditional_close (const QWidget *ID)
+{
+  if (ID != this)
+    return;
+
+  close ();
+}
+
+void
+file_editor_tab::change_editor_state (const QWidget *ID)
+{
+  if (ID != this)
+    {
+      // Widget may be going out of focus.  If so, record location.
+      if (_find_dialog)
+        {
+          if (_find_dialog->isVisible ())
+            {
+              _find_dialog_geometry = _find_dialog->geometry ();
+              _find_dialog->hide ();
+            }
+        }
+      return;
+    }
+
+  if (_find_dialog && _find_dialog_is_visible)
+    {
+      _find_dialog->setGeometry (_find_dialog_geometry);
+      _find_dialog->show ();
+    }
+
+  emit editor_state_changed (_copy_available, QDir::cleanPath (_file_name));
+}
+
+void
+file_editor_tab::file_name_query (const QWidget *ID)
+{
+  // A zero (null pointer) means that all file editor tabs
+  // should respond, otherwise just the desired file editor tab.
+  if (ID != this && ID != 0)
+    return;
+
+  // Unnamed files shouldn't be transmitted.
+  if (!_file_name.isEmpty ())
+    emit add_filename_to_list (_file_name, this);
+}
+
+void
+file_editor_tab::handle_file_reload_answer (int decision)
+{
+  if (decision == QMessageBox::Yes)
+    {
+      // reload: file is readded to the file watcher in set_file_name ()
+      load_file (_file_name);
+    }
+  else
+    {
+      // do not reload: readd to the file watche
+      _file_system_watcher.addPath (_file_name);
+    }
+}
+
+void
+file_editor_tab::handle_file_resave_answer (int decision)
+{
+  // check decision of user in dialog
+  if (decision == QMessageBox::Save)
+    {
+      save_file (_file_name);  // readds file to watcher in set_file_name ()
+      _edit_area->setReadOnly (false);  // delete read only flag
+    }
+  else
+    {
+      // Definitely close the file.
+      // Set modified to false to prevent the dialog box when the close event
+      // is posted. If the user cancels the close in this dialog the tab is
+      // left open with a non-existing file.
+      _edit_area->setModified (false);
+      close ();
+    }
+}
+
+void
+file_editor_tab::insert_debugger_pointer (const QWidget *ID, int line)
+{
+  if (ID != this || ID == 0)
+    return;
+
+  if (line > 0)
+    {
+      _edit_area->markerAdd (line-1, debugger_position);
+      center_current_line ();
+    }
+}
+
+void
+file_editor_tab::delete_debugger_pointer (const QWidget *ID, int line)
+{
+  if (ID != this || ID == 0)
+    return;
+
+  if (line > 0)
+    _edit_area->markerDelete (line-1, debugger_position);
+}
+
+void
+file_editor_tab::do_breakpoint_marker (bool insert, const QWidget *ID, int line)
+{
+  if (ID != this || ID == 0)
+    return;
+
+  if (line > 0)
+    {
+      if (insert)
+        _edit_area->markerAdd (line-1, breakpoint);
+      else
+        _edit_area->markerDelete (line-1, breakpoint);
+    }
+}
+
+
+void
+file_editor_tab::center_current_line ()
+{
+  long int visible_lines
+    = _edit_area->SendScintilla (QsciScintillaBase::SCI_LINESONSCREEN);
+
+  if (visible_lines > 2)
+    {
+      int line, index;
+      _edit_area->getCursorPosition (&line, &index);
+
+      int first_line = _edit_area->firstVisibleLine ();
+      first_line = first_line + (line - first_line - (visible_lines-1)/2);
+
+      _edit_area->SendScintilla (2613,first_line); // SCI_SETFIRSTVISIBLELINE
+    }
+}
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libgui/src/m-editor/file-editor-tab.h
@@ -0,0 +1,197 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 (file_editor_tab_h)
+#define file_editor_tab_h 1
+
+#include <QWidget>
+#include <QCloseEvent>
+#include <QFileSystemWatcher>
+#include <QSettings>
+
+#include <Qsci/qsciscintilla.h>
+
+#include "find-dialog.h"
+
+class file_editor;
+
+class file_editor_tab : public QWidget
+{
+  Q_OBJECT
+
+public:
+
+  file_editor_tab (const QString& directory = "");
+
+  ~file_editor_tab (void);
+
+public slots:
+
+  void update_window_title (bool modified);
+  void handle_copy_available (bool enableCopy);
+  void handle_margin_clicked (int line, int margin,
+                              Qt::KeyboardModifiers state);
+
+  // Tells the editor tab to react on changed settings.
+  void notice_settings (const QSettings *settings);
+
+  // Will initiate close if associated with the identifier tag.
+  void conditional_close (const QWidget *ID);
+
+  // Change to a different editor tab by identifier tag.
+  void change_editor_state (const QWidget *ID);
+
+  // Simply transmit file name.
+  void file_name_query (const QWidget *ID);
+
+  void set_focus (const QWidget *ID);
+  void undo (const QWidget *ID);
+  void redo (const QWidget *ID);
+  void copy (const QWidget *ID);
+  void cut (const QWidget *ID);
+  void paste (const QWidget *ID);
+  void save_file (const QWidget *ID);
+  void save_file (const QWidget *ID, const QString& fileName,
+                  bool remove_on_success);
+  void save_file_as (const QWidget *ID);
+  void print_file (const QWidget *ID);
+  void run_file (const QWidget *ID);
+  void toggle_bookmark (const QWidget *ID);
+  void next_bookmark (const QWidget *ID);
+  void previous_bookmark (const QWidget *ID);
+  void remove_bookmark (const QWidget *ID);
+
+  void toggle_breakpoint (const QWidget *ID);
+  void next_breakpoint (const QWidget *ID);
+  void previous_breakpoint (const QWidget *ID);
+  void remove_all_breakpoints (const QWidget *ID);
+
+  void comment_selected_text (const QWidget *ID);
+  void uncomment_selected_text (const QWidget *ID);
+  void find (const QWidget *ID);
+  void goto_line (const QWidget *ID, int line = -1);
+
+  void insert_debugger_pointer (const QWidget *ID, int line = -1);
+  void delete_debugger_pointer (const QWidget *ID, int line = -1);
+
+  void do_breakpoint_marker (bool insert, const QWidget *ID, int line = -1);
+
+  void set_modified (bool modified = true);
+
+  QString load_file (const QString& fileName);
+  void new_file (const QString& commands = QString ());
+
+  void file_has_changed (const QString& fileName);
+
+signals:
+
+  void file_name_changed (const QString& fileName, const QString& toolTip);
+  void editor_state_changed (bool copy_available, const QString& fileName);
+  void tab_remove_request ();
+  void add_filename_to_list (const QString&, QWidget *);
+  void mru_add_file (const QString& file_name);
+  void editor_check_conflict_save (const QString& saveFileName,
+                                   bool remove_on_success);
+  void process_octave_code (const QString& command);
+
+protected:
+
+  void closeEvent (QCloseEvent *event);
+  void set_file_name (const QString& fileName);
+
+private slots:
+
+  // When user closes message box for reload question.
+  void handle_file_reload_answer (int decision);
+
+  // When user closes message box for resave question.
+  void handle_file_resave_answer (int decision);
+
+  // When user closes message box for modified question.
+  void handle_file_modified_answer (int decision);
+
+  // When user closes find_dialog box.
+  void handle_find_dialog_finished (int decision);
+
+  // When user closes QFileDialog box.
+  void handle_save_file_as_answer (const QString& fileName);
+  void handle_save_file_as_answer_close (const QString& fileName);
+  void handle_save_file_as_answer_cancel ();
+
+private:
+
+  enum editor_markers
+    {
+      bookmark,
+      breakpoint,
+      debugger_position
+    };
+
+  struct bp_info
+  {
+    bp_info (const QString& f, const QString& d, const QString& fn, int l)
+      : file (f.toStdString ()), dir (d.toStdString ()),
+        function_name (fn.toStdString ()), line (l)
+    { }
+
+    std::string file;
+    std::string dir;
+    std::string function_name;
+    int line;
+  };
+
+  void save_file (const QString& saveFileName, bool remove_on_success = false);
+  void save_file_as (bool remove_on_success = false);
+  void message_duplicate_file_name (const QString& fileName);
+
+  void update_lexer ();
+  void request_add_breakpoint (int line);
+  void request_remove_breakpoint (int line);
+
+  int check_file_modified ();
+  void do_comment_selected_text (bool comment);
+
+  void run_file_callback (const bp_info& info);
+
+  bool file_in_path (const std::string& file, const std::string& dir);
+
+  void add_breakpoint_callback (const bp_info& info);
+  void remove_breakpoint_callback (const bp_info& info);
+  void remove_all_breakpoints_callback (const bp_info& info);
+  void center_current_line ();
+
+  QsciScintilla *_edit_area;
+
+  QString _file_name;
+  QString _file_name_short;
+
+  bool _long_title;
+  bool _copy_available;
+
+  QFileSystemWatcher _file_system_watcher;
+
+  find_dialog *_find_dialog;
+  bool _find_dialog_is_visible;
+  QRect _find_dialog_geometry;
+};
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libgui/src/m-editor/file-editor.cc
@@ -0,0 +1,1142 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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
+
+#ifdef HAVE_QSCINTILLA
+
+#include "file-editor.h"
+#include "resource-manager.h"
+#include <QVBoxLayout>
+#include <QApplication>
+#include <QFile>
+#include <QFont>
+#include <QFileDialog>
+#include <QMessageBox>
+#include <QStyle>
+#include <QTextStream>
+#include <QProcess>
+
+#include "octave-link.h"
+#include "utils.h"
+
+file_editor::file_editor (QWidget *p)
+  : file_editor_interface (p)
+{
+  // Set current editing directory before construct because loaded
+  // files will change ced accordingly.
+  ced = QDir::currentPath ();
+
+  construct ();
+
+  setVisible (false);
+}
+
+file_editor::~file_editor (void)
+{
+  QSettings *settings = resource_manager::get_settings ();
+
+  editor_tab_map.clear ();
+
+  if (settings->value ("editor/restoreSession", true).toBool ())
+    {
+      // Have all file editor tabs signal what their file names are.
+      emit fetab_file_name_query (0);
+    }
+  QStringList fetFileNames;
+  for (editor_tab_map_const_iterator p = editor_tab_map.begin ();
+       p != editor_tab_map.end (); p++)
+    fetFileNames.append (p->first);
+
+  settings->setValue ("editor/savedSessionTabs", fetFileNames);
+  settings->sync ();
+
+  if (_mru_file_menu)
+    delete _mru_file_menu;
+}
+
+void
+file_editor::focus (void)
+{
+  set_focus ();
+}
+
+void
+file_editor::handle_visibility (bool visible)
+{
+  if (visible && ! isFloating ())
+    focus ();
+}
+
+void
+file_editor::connect_visibility_changed (void)
+{
+  connect (this, SIGNAL (visibilityChanged (bool)),
+           this, SLOT (handle_visibility (bool)));
+}
+
+// set focus to editor and its current tab
+void
+file_editor::set_focus (void)
+{
+  if (!isVisible ())
+    setVisible (true);
+  setFocus ();
+  activateWindow ();
+  raise ();
+  QWidget *fileEditorTab = _tab_widget->currentWidget ();
+  if (fileEditorTab)
+    emit fetab_set_focus (fileEditorTab);
+}
+
+QMenu *
+file_editor::debug_menu (void)
+{
+  return _debug_menu;
+}
+
+QToolBar *
+file_editor::toolbar (void)
+{
+  return _tool_bar;
+}
+
+void
+file_editor::handle_enter_debug_mode (void)
+{
+  _run_action->setEnabled (false);
+}
+
+void
+file_editor::handle_exit_debug_mode (void)
+{
+  _run_action->setEnabled (true);
+}
+
+void
+file_editor::request_new_file (const QString& commands)
+{
+  // New file isn't a file_editor_tab function since the file
+  // editor tab has yet to be created and there is no object to
+  // pass a signal to.  Hence, functionality is here.
+
+  file_editor_tab *fileEditorTab = new file_editor_tab (ced);
+  if (fileEditorTab)
+    {
+      add_file_editor_tab (fileEditorTab, "");  // new tab with empty title
+      fileEditorTab->new_file (commands);       // title is updated here
+      set_focus ();                             // focus editor and new tab
+    }
+}
+
+void
+file_editor::request_new_script (const QString& commands)
+{
+  request_new_file (commands);
+}
+
+void
+file_editor::request_new_function (const QString& commands)
+{
+  QString text = commands;
+
+  if (text.isEmpty ())
+    text = "## Copyright (C)\n"
+      "\n"
+      "## -*- texinfo -*-\n"
+      "## @deftypefn {Function File} {[outputs] =} unamed_function (inputs)\n"
+      "## @end deftypefn\n"
+      "\n"
+      "function [outputs] = unnamed_function (inputs)\n"
+      "\n"
+      "endfunction\n";
+
+  request_new_file (text);
+}
+
+void
+file_editor::request_open_file (void)
+{
+  // Open file isn't a file_editor_tab function since the file
+  // editor tab has yet to be created and there is no object to
+  // pass a signal to.  Hence, functionality is here.
+
+  // Create a NonModal message.
+  QFileDialog *fileDialog = new QFileDialog (this);
+  fileDialog->setNameFilter (tr ("Octave Files (*.m);;All Files (*)"));
+  fileDialog->setAcceptMode (QFileDialog::AcceptOpen);
+  fileDialog->setViewMode (QFileDialog::Detail);
+  fileDialog->setDirectory (ced);
+
+  connect (fileDialog, SIGNAL (fileSelected (const QString&)),
+           this, SLOT (request_open_file (const QString&)));
+
+  fileDialog->setWindowModality (Qt::NonModal);
+  fileDialog->setAttribute (Qt::WA_DeleteOnClose);
+  fileDialog->show ();
+}
+
+// Check whether this file is already open in the editor.
+QWidget *
+file_editor::find_tab_widget (const QString& file) const
+{
+  QWidget *retval = 0;
+
+  for (editor_tab_map_const_iterator p = editor_tab_map.begin ();
+       p != editor_tab_map.end (); p++)
+    {
+      QString tab_file = p->first;
+
+      if (same_file (file.toStdString (), tab_file.toStdString ()))
+        {
+          retval = p->second;
+          break;
+        }
+    }
+
+  return retval;
+}    
+
+void
+file_editor::request_open_file (const QString& openFileName, int line,
+                                bool debug_pointer,
+                                bool breakpoint_marker, bool insert)
+{
+  // Check if the user wants to use a custom file editor.
+  QSettings *settings = resource_manager::get_settings ();
+  if (settings->value ("useCustomFileEditor").toBool ())
+    {
+      QString editor = settings->value ("customFileEditor").toString ();
+      editor.replace ("%f", openFileName);
+      editor.replace ("%l", QString::number (line));
+      QProcess::startDetached (editor);
+      if (line < 0)
+        handle_mru_add_file (QDir::cleanPath (openFileName));
+      return;
+    }
+
+  if (openFileName.isEmpty ())
+    {
+      // ??  Not sure this will happen.  This routine isn't even called
+      // if the user hasn't selected a file.
+    }
+  else
+    {
+      // Have all file editor tabs signal what their file names are.
+      editor_tab_map.clear ();
+      emit fetab_file_name_query (0);
+
+      // Check whether this file is already open in the editor.
+      QWidget *tab = find_tab_widget (openFileName);
+
+      if (tab)
+        {
+          _tab_widget->setCurrentWidget (tab);
+
+          if (line > 0)
+            {
+              emit fetab_goto_line (tab, line);
+
+              if (debug_pointer)
+                emit fetab_insert_debugger_pointer (tab, line);
+
+              if (breakpoint_marker)
+                emit fetab_do_breakpoint_marker (insert, tab, line);
+            }
+
+          emit fetab_set_focus (tab);
+        }
+      else
+        {
+          file_editor_tab *fileEditorTab = new file_editor_tab ();
+          if (fileEditorTab)
+            {
+              QString result = fileEditorTab->load_file (openFileName);
+              if (result == "")
+                {
+                  // Supply empty title then have the file_editor_tab update
+                  // with full or short name.
+                  add_file_editor_tab (fileEditorTab, "");
+                  fileEditorTab->update_window_title (false);
+                  // file already loaded, add file to mru list here
+                  handle_mru_add_file (QDir::cleanPath (openFileName));
+
+                  if (line > 0)
+                    {
+                      emit fetab_goto_line (fileEditorTab, line);
+
+                      if (debug_pointer)
+                        emit fetab_insert_debugger_pointer (fileEditorTab,
+                                                            line);
+                      if (breakpoint_marker)
+                        emit fetab_do_breakpoint_marker (insert, fileEditorTab,
+                                                         line);
+                    }
+                }
+              else
+                {
+                  delete fileEditorTab;
+                  // Create a NonModal message about error.
+                  QMessageBox *msgBox
+                    = new QMessageBox (QMessageBox::Critical,
+                                       tr ("Octave Editor"),
+                                       tr ("Could not open file %1 for read:\n%2.").
+                                       arg (openFileName).arg (result),
+                                       QMessageBox::Ok, 0);
+
+                  msgBox->setWindowModality (Qt::NonModal);
+                  msgBox->setAttribute (Qt::WA_DeleteOnClose);
+                  msgBox->show ();
+                }
+            }
+
+          // really show editor and the current editor tab
+          set_focus ();
+        }
+    }
+}
+
+// open a file from the mru list
+void
+file_editor::request_mru_open_file (void)
+{
+  QAction *action = qobject_cast<QAction *> (sender ());
+  if (action)
+    {
+      request_open_file (action->data ().toString ());
+    }
+}
+
+
+void
+file_editor::check_conflict_save (const QString& saveFileName, bool remove_on_success)
+{
+  // Have all file editor tabs signal what their file names are.
+  editor_tab_map.clear ();
+  emit fetab_file_name_query (0);
+
+  // Check whether this file is already open in the editor.
+  QWidget *tab = find_tab_widget (saveFileName);
+
+  if (tab)
+    {
+      // Note: to overwrite the contents of some other file editor tab
+      // with the same name requires identifying which file editor tab
+      // that is (not too difficult) then close that tab.  Of course,
+      // that could trigger another dialog box if the file editor tab
+      // with the same name has modifications in it.  This could become
+      // somewhat confusing to the user.  For now, opt to do nothing.
+
+      // Create a NonModal message about error.
+      QMessageBox *msgBox
+        = new QMessageBox (QMessageBox::Critical, tr ("Octave Editor"),
+                           tr ("File not saved! A file with the selected name\n%1\n"
+                               "is already open in the editor").
+                           arg (saveFileName),
+                           QMessageBox::Ok, 0);
+
+      msgBox->setWindowModality (Qt::NonModal);
+      msgBox->setAttribute (Qt::WA_DeleteOnClose);
+      msgBox->show ();
+
+      return;
+    }
+
+  QObject *saveFileObject = sender ();
+  QWidget *saveFileWidget = 0;
+
+  for (int i = 0; i < _tab_widget->count (); i++)
+    {
+      if (_tab_widget->widget (i) == saveFileObject)
+        {
+          saveFileWidget = _tab_widget->widget (i);
+          break;
+        }
+    }
+  if (!saveFileWidget)
+    {
+      // Create a NonModal message about error.
+      QMessageBox *msgBox
+        = new QMessageBox (QMessageBox::Critical, tr ("Octave Editor"),
+                           tr ("The associated file editor tab has disappeared.  It was likely closed by some means."),
+                           QMessageBox::Ok, 0);
+
+      msgBox->setWindowModality (Qt::NonModal);
+      msgBox->setAttribute (Qt::WA_DeleteOnClose);
+      msgBox->show ();
+
+      return;
+    }
+
+  // Can save without conflict, have the file editor tab do so.
+  emit fetab_save_file (saveFileWidget, saveFileName, remove_on_success);
+}
+
+void
+file_editor::handle_insert_debugger_pointer_request (const QString& file,
+                                                     int line)
+{
+  request_open_file (file, line, true);
+}
+
+void
+file_editor::handle_delete_debugger_pointer_request (const QString& file,
+                                                     int line)
+{
+  if (! file.isEmpty ())
+    {
+      // Have all file editor tabs signal what their file names are.
+      editor_tab_map.clear ();
+      emit fetab_file_name_query (0);
+
+      // Check whether this file is already open in the editor.
+      QWidget *tab = find_tab_widget (file);
+
+      if (tab)
+        {
+          _tab_widget->setCurrentWidget (tab);
+
+          if (line > 0)
+            emit fetab_delete_debugger_pointer (tab, line);
+
+          emit fetab_set_focus (tab);
+        }
+    }
+}
+
+void
+file_editor::handle_update_breakpoint_marker_request (bool insert,
+                                                      const QString& file,
+                                                      int line)
+{
+  request_open_file (file, line, false, true, insert);
+}
+
+void
+file_editor::handle_edit_file_request (const QString& file)
+{
+  request_open_file (file);
+}
+
+void
+file_editor::request_undo (void)
+{
+  emit fetab_undo (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_redo (void)
+{
+  emit fetab_redo (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_copy (void)
+{
+  emit fetab_copy (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_cut (void)
+{
+  emit fetab_cut (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_paste (void)
+{
+  emit fetab_paste (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_save_file (void)
+{
+  emit fetab_save_file (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_save_file_as (void)
+{
+   emit fetab_save_file_as (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_print_file (void)
+{
+   emit fetab_print_file (_tab_widget->currentWidget ());
+}
+
+
+void
+file_editor::request_run_file (void)
+{
+  emit fetab_run_file (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_toggle_bookmark (void)
+{
+  emit fetab_toggle_bookmark (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_next_bookmark (void)
+{
+  emit fetab_next_bookmark (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_previous_bookmark (void)
+{
+  emit fetab_previous_bookmark (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_remove_bookmark (void)
+{
+  emit fetab_remove_bookmark (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_toggle_breakpoint (void)
+{
+  emit fetab_toggle_breakpoint (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_next_breakpoint (void)
+{
+  emit fetab_next_breakpoint (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_previous_breakpoint (void)
+{
+  emit fetab_previous_breakpoint (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_remove_breakpoint (void)
+{
+  emit fetab_remove_all_breakpoints (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_comment_selected_text (void)
+{
+  emit fetab_comment_selected_text (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_uncomment_selected_text (void)
+{
+  emit fetab_uncomment_selected_text (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_find (void)
+{
+  emit fetab_find (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_goto_line (void)
+{
+  emit fetab_goto_line (_tab_widget->currentWidget ());
+}
+
+
+void
+file_editor::handle_mru_add_file (const QString& file_name)
+{
+  _mru_files.removeAll (file_name);
+  _mru_files.prepend (file_name);
+  mru_menu_update ();
+}
+
+void
+file_editor::mru_menu_update (void)
+{
+  int num_files = qMin (_mru_files.size (), int (MaxMRUFiles));
+
+  // configure and show active actions of mru-menu
+  for (int i = 0; i < num_files; ++i)
+    {
+      QString text = tr ("&%1 %2").
+          arg ((i+1) % int (MaxMRUFiles)).arg (_mru_files.at (i));
+      _mru_file_actions[i]->setText (text);
+      _mru_file_actions[i]->setData (_mru_files.at (i));
+      _mru_file_actions[i]->setVisible (true);
+    }
+
+    // hide unused mru-menu entries
+    for (int j = num_files; j < MaxMRUFiles; ++j)
+      _mru_file_actions[j]->setVisible (false);
+
+    // delete entries in string-list beyond MaxMRUFiles
+    while (_mru_files.size () > MaxMRUFiles)
+      _mru_files.removeLast ();
+
+    // save actual mru-list in settings
+    QSettings *settings = resource_manager::get_settings ();
+
+    // FIXME -- what should happen if settings is 0?
+    settings->setValue ("editor/mru_file_list", _mru_files);
+    settings->sync ();
+}
+
+void
+file_editor::handle_file_name_changed (const QString& fname,
+                                       const QString& tip)
+{
+  QObject *fileEditorTab = sender ();
+  if (fileEditorTab)
+    {
+      for (int i = 0; i < _tab_widget->count (); i++)
+        {
+          if (_tab_widget->widget (i) == fileEditorTab)
+            {
+              _tab_widget->setTabText (i, fname);
+              _tab_widget->setTabToolTip (i, tip);
+            }
+        }
+    }
+}
+
+void
+file_editor::handle_tab_close_request (int index)
+{
+  // Signal to the tabs a request to close whomever matches the identifying
+  // tag (i.e., unique widget pointer).  The reason for this indirection is
+  // that it will enable a file editor widget to toss up a non-static
+  // dialog box and later signal that it wants to be removed.
+  QWidget *tabID = _tab_widget->widget (index);
+  emit fetab_close_request (tabID);
+}
+
+void
+file_editor::handle_tab_remove_request (void)
+{
+  QObject *fileEditorTab = sender ();
+  if (fileEditorTab)
+    {
+      for (int i = 0; i < _tab_widget->count (); i++)
+        {
+          if (_tab_widget->widget (i) == fileEditorTab)
+            {
+              _tab_widget->removeTab (i);
+              delete fileEditorTab;
+            }
+        }
+    }
+}
+
+void
+file_editor::handle_add_filename_to_list (const QString& fileName, QWidget *ID)
+{
+  // Should we allow multiple tabs for a single file?
+
+  editor_tab_map[fileName] = ID;
+}
+
+void
+file_editor::active_tab_changed (int index)
+{
+  emit fetab_change_request (_tab_widget->widget (index));
+}
+
+void
+file_editor::handle_editor_state_changed (bool copy_available,
+                                          const QString& file_name)
+{
+  // In case there is some scenario where traffic could be coming from
+  // all the file editor tabs, just process info from the current active tab.
+  if (sender () == _tab_widget->currentWidget ())
+    {
+      _copy_action->setEnabled (copy_available);
+      _cut_action->setEnabled (copy_available);
+
+      if (!file_name.isEmpty ())
+        {
+          ced = QDir::cleanPath (file_name);
+          int lastslash = ced.lastIndexOf ('/');
+
+          // Test against > 0 because if somehow the directory is "/" the
+          // slash should be retained.  Otherwise, last slash is removed.
+          if (lastslash > 0 && lastslash != ced.count ())
+            ced = ced.left (lastslash);
+        }
+
+      setFocusProxy (_tab_widget->currentWidget ());
+    }
+}
+
+void
+file_editor::notice_settings (const QSettings *settings)
+{
+  int icon_size = settings->value ("toolbar_icon_size", 24).toInt ();
+  _tool_bar->setIconSize (QSize (icon_size, icon_size));
+  // Relay signal to file editor tabs.
+  emit fetab_settings_changed (settings);
+}
+
+void
+file_editor::construct (void)
+{
+  QWidget *editor_widget = new QWidget (this);
+
+  // FIXME -- what was the intended purpose of this unused variable?
+  // QStyle *editor_style = QApplication::style ();
+
+  _menu_bar = new QMenuBar (editor_widget);
+  _tool_bar = new QToolBar (editor_widget);
+  _tab_widget = new QTabWidget (editor_widget);
+  _tab_widget->setTabsClosable (true);
+
+  QAction *new_action = new QAction (QIcon (":/actions/icons/filenew.png"),
+                                     tr ("&New File"), _tool_bar);
+
+  QAction *open_action = new QAction (QIcon (":/actions/icons/fileopen.png"),
+                                      tr ("&Open File"), _tool_bar);
+
+  QAction *save_action = new QAction (QIcon (":/actions/icons/filesave.png"),
+                                      tr ("&Save File"), _tool_bar);
+
+  QAction *save_as_action
+    = new QAction (QIcon (":/actions/icons/filesaveas.png"),
+                   tr ("Save File &As"), _tool_bar);
+
+  QAction *print_action
+    = new QAction ( QIcon (":/actions/icons/fileprint.png"),
+                    tr ("Print"), _tool_bar);
+
+  QAction *undo_action = new QAction (QIcon (":/actions/icons/undo.png"),
+                                      tr ("&Undo"), _tool_bar);
+
+  QAction *redo_action = new QAction (QIcon (":/actions/icons/redo.png"),
+                                      tr ("&Redo"), _tool_bar);
+
+  _copy_action = new QAction (QIcon (":/actions/icons/editcopy.png"),
+                              tr ("&Copy"), _tool_bar);
+
+  _cut_action = new QAction (QIcon (":/actions/icons/editcut.png"),
+                              tr ("Cu&t"), _tool_bar);
+
+  QAction *paste_action
+    = new QAction (QIcon (":/actions/icons/editpaste.png"),
+                   tr ("Paste"), _tool_bar);
+
+  QAction *next_bookmark_action
+    = new QAction (tr ("&Next Bookmark"), _tool_bar);
+
+  QAction *previous_bookmark_action
+    = new QAction (tr ("Pre&vious Bookmark"), _tool_bar);
+
+  QAction *toggle_bookmark_action
+    = new QAction (tr ("Toggle &Bookmark"), _tool_bar);
+
+  QAction *remove_bookmark_action
+    = new QAction (tr ("&Remove All Bookmarks"), _tool_bar);
+
+  QAction *next_breakpoint_action
+    = new QAction (QIcon (":/actions/icons/bp_next.png"),
+                   tr ("&Next breakpoint"), _tool_bar);
+  QAction *previous_breakpoint_action
+    = new QAction (QIcon (":/actions/icons/bp_prev.png"),
+                   tr ("Pre&vious breakpoint"), _tool_bar);
+  QAction *toggle_breakpoint_action
+    = new QAction (QIcon (":/actions/icons/bp_toggle.png"),
+                   tr ("Toggle &breakpoint"), _tool_bar);
+  QAction *remove_all_breakpoints_action
+    = new QAction (QIcon (":/actions/icons/bp_rm_all.png"),
+                   tr ("&Remove All breakpoints"), _tool_bar);
+
+  QAction *comment_selection_action
+    = new QAction (tr ("&Comment Selected Text"), _tool_bar);
+
+  QAction *uncomment_selection_action
+    = new QAction (tr ("&Uncomment Selected Text"), _tool_bar);
+
+  QAction *find_action = new QAction (QIcon (":/actions/icons/search.png"),
+                                      tr ("&Find and Replace"), _tool_bar);
+
+  _run_action = new QAction (QIcon (":/actions/icons/artsbuilderexecute.png"),
+                             tr ("Save File And Run"), _tool_bar);
+
+  QAction *goto_line_action = new QAction (tr ("Go&to Line"), _tool_bar);
+
+  // the mru-list and an empty array of actions
+  QSettings *settings = resource_manager::get_settings ();
+  // FIXME -- what should happen if settings is 0?
+  _mru_files = settings->value ("editor/mru_file_list").toStringList ();
+  for (int i = 0; i < MaxMRUFiles; ++i)
+    {
+       _mru_file_actions[i] = new QAction (this);
+       _mru_file_actions[i]->setVisible (false);
+    }
+
+  // some actions are disabled from the beginning
+  _copy_action->setEnabled (false);
+  _cut_action->setEnabled (false);
+  _run_action->setShortcut (Qt::ControlModifier+ Qt::Key_R);
+  _run_action->setShortcutContext (Qt::WindowShortcut);
+  save_action->setShortcut (QKeySequence::Save);
+  save_action->setShortcutContext (Qt::WindowShortcut);
+  save_as_action->setShortcut (QKeySequence::SaveAs);
+  save_as_action->setShortcutContext (Qt::WindowShortcut);
+
+  print_action->setShortcut (QKeySequence::Print);
+  print_action->setShortcutContext (Qt::WindowShortcut);
+
+  next_bookmark_action->setShortcut (Qt::Key_F2);
+  next_bookmark_action->setShortcutContext (Qt::WindowShortcut);
+  previous_bookmark_action->setShortcut (Qt::SHIFT + Qt::Key_F2);
+  previous_bookmark_action->setShortcutContext (Qt::WindowShortcut);
+  toggle_bookmark_action->setShortcut (Qt::Key_F7);
+  toggle_bookmark_action->setShortcutContext (Qt::WindowShortcut);
+  comment_selection_action->setShortcut (Qt::ControlModifier + Qt::Key_7);
+  comment_selection_action->setShortcutContext (Qt::WindowShortcut);
+  uncomment_selection_action->setShortcut (Qt::ControlModifier + Qt::Key_8);
+  uncomment_selection_action->setShortcutContext (Qt::WindowShortcut);
+  find_action->setShortcut (QKeySequence::Find);
+  find_action->setShortcutContext (Qt::WindowShortcut);
+  goto_line_action->setShortcut (Qt::ControlModifier+ Qt::Key_G);
+  goto_line_action->setShortcutContext (Qt::WindowShortcut);
+
+  // toolbar
+  _tool_bar->addAction (new_action);
+  _tool_bar->addAction (open_action);
+  _tool_bar->addAction (save_action);
+  _tool_bar->addAction (save_as_action);
+  _tool_bar->addSeparator ();
+  _tool_bar->addAction (print_action);
+  _tool_bar->addSeparator ();
+  _tool_bar->addAction (undo_action);
+  _tool_bar->addAction (redo_action);
+  _tool_bar->addAction (_copy_action);
+  _tool_bar->addAction (_cut_action);
+  _tool_bar->addAction (paste_action);
+  _tool_bar->addSeparator ();
+  _tool_bar->addAction (find_action);
+  _tool_bar->addAction (_run_action);
+  _tool_bar->addSeparator ();
+  _tool_bar->addAction (toggle_breakpoint_action);
+  _tool_bar->addAction (next_breakpoint_action);
+  _tool_bar->addAction (previous_breakpoint_action);
+  _tool_bar->addAction (remove_all_breakpoints_action);
+
+  // menu bar
+  QMenu *fileMenu = new QMenu (tr ("&File"), _menu_bar);
+  fileMenu->addAction (new_action);
+  fileMenu->addAction (open_action);
+  fileMenu->addAction (save_action);
+  fileMenu->addAction (save_as_action);
+  fileMenu->addSeparator ();
+  _mru_file_menu = new QMenu (tr ("&Recent Editor Files"), fileMenu);
+
+  for (int i = 0; i < MaxMRUFiles; ++i)
+    _mru_file_menu->addAction (_mru_file_actions[i]);
+
+  fileMenu->addMenu (_mru_file_menu);
+  _menu_bar->addMenu (fileMenu);
+
+  fileMenu->addSeparator ();
+  fileMenu->addAction (print_action);
+
+  QMenu *editMenu = new QMenu (tr ("&Edit"), _menu_bar);
+  editMenu->addAction (undo_action);
+  editMenu->addAction (redo_action);
+  editMenu->addSeparator ();
+  editMenu->addAction (_copy_action);
+  editMenu->addAction (_cut_action);
+  editMenu->addAction (paste_action);
+  editMenu->addSeparator ();
+  editMenu->addAction (find_action);
+  editMenu->addSeparator ();
+  editMenu->addAction (comment_selection_action);
+  editMenu->addAction (uncomment_selection_action);
+  editMenu->addSeparator ();
+  editMenu->addAction (toggle_bookmark_action);
+  editMenu->addAction (next_bookmark_action);
+  editMenu->addAction (previous_bookmark_action);
+  editMenu->addAction (remove_bookmark_action);
+  editMenu->addSeparator ();
+  editMenu->addAction (goto_line_action);
+  _menu_bar->addMenu (editMenu);
+
+  _debug_menu = new QMenu (tr ("&Debug"), _menu_bar);
+  _debug_menu->addAction (toggle_breakpoint_action);
+  _debug_menu->addAction (next_breakpoint_action);
+  _debug_menu->addAction (previous_breakpoint_action);
+  _debug_menu->addAction (remove_all_breakpoints_action);
+  _debug_menu->addSeparator ();
+  // The other debug actions will be added by the main window.
+  _menu_bar->addMenu (_debug_menu);
+
+  QMenu *_run_menu = new QMenu (tr ("&Run"), _menu_bar);
+  _run_menu->addAction (_run_action);
+  _menu_bar->addMenu (_run_menu);
+
+  QVBoxLayout *vbox_layout = new QVBoxLayout ();
+  vbox_layout->addWidget (_menu_bar);
+  vbox_layout->addWidget (_tool_bar);
+  vbox_layout->addWidget (_tab_widget);
+  vbox_layout->setMargin (0);
+  editor_widget->setLayout (vbox_layout);
+  setWidget (editor_widget);
+
+  connect (parent (), SIGNAL (settings_changed (const QSettings *)),
+           this, SLOT (notice_settings (const QSettings *)));
+
+  connect (parent (), SIGNAL (new_file_signal (const QString&)),
+           this, SLOT (request_new_file (const QString&)));
+
+  connect (parent (), SIGNAL (open_file_signal (const QString&)),
+           this, SLOT (request_open_file (const QString&)));
+
+  connect (new_action, SIGNAL (triggered ()),
+           this, SLOT (request_new_file ()));
+
+  connect (open_action, SIGNAL (triggered ()),
+           this, SLOT (request_open_file ()));
+
+  connect (undo_action, SIGNAL (triggered ()),
+           this, SLOT (request_undo ()));
+
+  connect (redo_action, SIGNAL (triggered ()),
+           this, SLOT (request_redo ()));
+
+  connect (_copy_action, SIGNAL (triggered ()),
+           this, SLOT (request_copy ()));
+
+  connect (_cut_action, SIGNAL (triggered ()),
+           this, SLOT (request_cut ()));
+
+  connect (paste_action, SIGNAL (triggered ()),
+           this, SLOT (request_paste ()));
+
+  connect (save_action, SIGNAL (triggered ()),
+           this, SLOT (request_save_file ()));
+
+  connect (save_as_action, SIGNAL (triggered ()),
+           this, SLOT (request_save_file_as ()));
+
+  connect (print_action, SIGNAL (triggered ()),
+           this, SLOT (request_print_file ()));
+
+  connect (_run_action, SIGNAL (triggered ()),
+           this, SLOT (request_run_file ()));
+
+  connect (toggle_bookmark_action, SIGNAL (triggered ()),
+           this, SLOT (request_toggle_bookmark ()));
+
+  connect (next_bookmark_action, SIGNAL (triggered ()),
+           this, SLOT (request_next_bookmark ()));
+
+  connect (previous_bookmark_action, SIGNAL (triggered ()),
+           this, SLOT (request_previous_bookmark ()));
+
+  connect (remove_bookmark_action, SIGNAL (triggered ()),
+           this, SLOT (request_remove_bookmark ()));
+
+  connect (toggle_breakpoint_action, SIGNAL (triggered ()),
+           this, SLOT (request_toggle_breakpoint ()));
+
+  connect (next_breakpoint_action, SIGNAL (triggered ()),
+           this, SLOT (request_next_breakpoint ()));
+
+  connect (previous_breakpoint_action, SIGNAL (triggered ()),
+           this, SLOT (request_previous_breakpoint ()));
+
+  connect (remove_all_breakpoints_action, SIGNAL (triggered ()),
+           this, SLOT (request_remove_breakpoint ()));
+
+  connect (comment_selection_action, SIGNAL (triggered ()),
+           this, SLOT (request_comment_selected_text ()));
+
+  connect (uncomment_selection_action, SIGNAL (triggered ()),
+           this, SLOT (request_uncomment_selected_text ()));
+
+  connect (find_action, SIGNAL (triggered ()),
+           this, SLOT (request_find ()));
+
+  connect (goto_line_action, SIGNAL (triggered ()),
+           this, SLOT (request_goto_line ()));
+
+  // The actions of the mru file menu
+  for (int i = 0; i < MaxMRUFiles; ++i)
+    {
+      connect (_mru_file_actions[i], SIGNAL (triggered ()),
+               this, SLOT (request_mru_open_file ()));
+    }
+
+  mru_menu_update ();
+
+  connect (_tab_widget, SIGNAL (tabCloseRequested (int)),
+           this, SLOT (handle_tab_close_request (int)));
+
+  connect (_tab_widget, SIGNAL (currentChanged (int)),
+           this, SLOT (active_tab_changed (int)));
+
+  resize (500, 400);
+  setWindowIcon (QIcon (":/actions/icons/logo.png"));
+  setWindowTitle ("Editor");
+
+  //restore previous session
+  if (settings->value ("editor/restoreSession", true).toBool ())
+    {
+      QStringList sessionFileNames
+        = settings->value ("editor/savedSessionTabs", QStringList ()).toStringList ();
+
+      for (int n = 0; n < sessionFileNames.count (); ++n)
+        request_open_file (sessionFileNames.at (n));
+    }
+}
+
+void
+file_editor::add_file_editor_tab (file_editor_tab *f, const QString& fn)
+{
+  _tab_widget->addTab (f, fn);
+
+  // Signals from the file editor_tab
+  connect (f, SIGNAL (file_name_changed (const QString&, const QString&)),
+           this, SLOT (handle_file_name_changed (const QString&,
+                                                 const QString&)));
+
+  connect (f, SIGNAL (editor_state_changed (bool, const QString&)),
+           this, SLOT (handle_editor_state_changed (bool, const QString&)));
+
+  connect (f, SIGNAL (tab_remove_request ()),
+           this, SLOT (handle_tab_remove_request ()));
+
+  connect (f, SIGNAL (add_filename_to_list (const QString&, QWidget*)),
+           this, SLOT (handle_add_filename_to_list (const QString&, QWidget*)));
+
+  connect (f, SIGNAL (editor_check_conflict_save (const QString&, bool)),
+           this, SLOT (check_conflict_save (const QString&, bool)));
+
+  connect (f, SIGNAL (mru_add_file (const QString&)),
+           this, SLOT (handle_mru_add_file (const QString&)));
+
+  connect (f, SIGNAL (process_octave_code (const QString&)),
+           parent (), SLOT (execute_command_in_terminal (const QString&)));
+  
+  // Signals from the file_editor non-trivial operations
+  connect (this, SIGNAL (fetab_settings_changed (const QSettings *)),
+           f, SLOT (notice_settings (const QSettings *)));
+
+  connect (this, SIGNAL (fetab_close_request (const QWidget*)),
+           f, SLOT (conditional_close (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_change_request (const QWidget*)),
+           f, SLOT (change_editor_state (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_file_name_query (const QWidget*)),
+           f, SLOT (file_name_query (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_save_file (const QWidget*, const QString&,
+                                          bool)),
+           f, SLOT (save_file (const QWidget*, const QString&, bool)));
+
+  // Signals from the file_editor trivial operations
+  connect (this, SIGNAL (fetab_undo (const QWidget*)),
+           f, SLOT (undo (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_redo (const QWidget*)),
+           f, SLOT (redo (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_copy (const QWidget*)),
+           f, SLOT (copy (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_cut (const QWidget*)),
+           f, SLOT (cut (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_paste (const QWidget*)),
+           f, SLOT (paste (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_save_file (const QWidget*)),
+           f, SLOT (save_file (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_save_file_as (const QWidget*)),
+           f, SLOT (save_file_as (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_print_file (const QWidget*)),
+           f, SLOT (print_file (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_run_file (const QWidget*)),
+           f, SLOT (run_file (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_toggle_bookmark (const QWidget*)),
+           f, SLOT (toggle_bookmark (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_next_bookmark (const QWidget*)),
+           f, SLOT (next_bookmark (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_previous_bookmark (const QWidget*)),
+           f, SLOT (previous_bookmark (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_remove_bookmark (const QWidget*)),
+           f, SLOT (remove_bookmark (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_toggle_breakpoint (const QWidget*)),
+           f, SLOT (toggle_breakpoint (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_next_breakpoint (const QWidget*)),
+           f, SLOT (next_breakpoint (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_previous_breakpoint (const QWidget*)),
+           f, SLOT (previous_breakpoint (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_remove_all_breakpoints (const QWidget*)),
+           f, SLOT (remove_all_breakpoints (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_comment_selected_text (const QWidget*)),
+           f, SLOT (comment_selected_text (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_uncomment_selected_text (const QWidget*)),
+           f, SLOT (uncomment_selected_text (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_find (const QWidget*)),
+           f, SLOT (find (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_goto_line (const QWidget*, int)),
+           f, SLOT (goto_line (const QWidget*, int)));
+
+  connect (this, SIGNAL (fetab_set_focus (const QWidget*)),
+           f, SLOT (set_focus (const QWidget*)));
+
+  connect (this, SIGNAL (fetab_insert_debugger_pointer (const QWidget*, int)),
+           f, SLOT (insert_debugger_pointer (const QWidget*, int)));
+
+  connect (this, SIGNAL (fetab_delete_debugger_pointer (const QWidget*, int)),
+           f, SLOT (delete_debugger_pointer (const QWidget*, int)));
+
+  connect (this, SIGNAL (fetab_do_breakpoint_marker (bool, const QWidget*,
+                                                     int)),
+           f, SLOT (do_breakpoint_marker (bool, const QWidget*, int)));
+
+  _tab_widget->setCurrentWidget (f);
+}
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libgui/src/m-editor/file-editor.h
@@ -0,0 +1,191 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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/>.
+
+*/
+
+#ifndef FILEEDITORMDISUBWINDOW_H
+#define FILEEDITORMDISUBWINDOW_H
+
+#include <QToolBar>
+#include <QAction>
+#include <QMenuBar>
+#include <QStatusBar>
+#include <QCloseEvent>
+#include <QTabWidget>
+#include <QSettings>
+
+#include <map>
+
+#include "file-editor-interface.h"
+#include "file-editor-tab.h"
+
+class file_editor : public file_editor_interface
+{
+  Q_OBJECT
+
+public:
+
+  typedef std::map<QString, QWidget *>::iterator editor_tab_map_iterator;
+  typedef std::map<QString, QWidget *>::const_iterator editor_tab_map_const_iterator;
+
+  file_editor (QWidget *p);
+  ~file_editor (void);
+
+  void connect_visibility_changed (void);
+
+  void loadFile (const QString& fileName);
+
+  QMenu *get_mru_menu (void) { return _mru_file_menu; }
+  QMenu *debug_menu (void);
+  QToolBar *toolbar (void);
+
+  void set_focus (void);
+  void handle_enter_debug_mode (void);
+  void handle_exit_debug_mode (void);
+
+signals:
+
+  void fetab_settings_changed (const QSettings *settings);
+  void fetab_close_request (const QWidget* ID);
+  void fetab_change_request (const QWidget* ID);
+  void fetab_file_name_query (const QWidget* ID);
+  // Save is a ping-pong type of communication
+  void fetab_save_file (const QWidget* ID, const QString& fileName,
+                        bool remove_on_success);
+  // No fetab_open, functionality in editor
+  // No fetab_new, functionality in editor
+  void fetab_undo (const QWidget* ID);
+  void fetab_redo (const QWidget* ID);
+  void fetab_copy (const QWidget* ID);
+  void fetab_cut (const QWidget* ID);
+  void fetab_paste (const QWidget* ID);
+  void fetab_save_file (const QWidget* ID);
+  void fetab_save_file_as (const QWidget* ID);
+  void fetab_print_file (const QWidget* ID);
+  void fetab_run_file (const QWidget* ID);
+  void fetab_toggle_bookmark (const QWidget* ID);
+  void fetab_next_bookmark (const QWidget* ID);
+  void fetab_previous_bookmark (const QWidget* ID);
+  void fetab_remove_bookmark (const QWidget* ID);
+  void fetab_toggle_breakpoint (const QWidget* ID);
+  void fetab_next_breakpoint (const QWidget* ID);
+  void fetab_previous_breakpoint (const QWidget* ID);
+  void fetab_remove_all_breakpoints (const QWidget* ID);
+  void fetab_comment_selected_text (const QWidget* ID);
+  void fetab_uncomment_selected_text (const QWidget* ID);
+  void fetab_find (const QWidget* ID);
+  void fetab_goto_line (const QWidget* ID, int line = -1);
+  void fetab_insert_debugger_pointer (const QWidget* ID, int line = -1);
+  void fetab_delete_debugger_pointer (const QWidget* ID, int line = -1);
+  void fetab_do_breakpoint_marker (bool insert, const QWidget* ID,
+                                   int line = -1);
+  void fetab_set_focus (const QWidget* ID);
+
+public slots:
+  void focus (void);
+  void handle_visibility (bool visible);
+
+  void request_new_file (const QString& commands);
+  void request_new_script (const QString& commands);
+  void request_new_function (const QString& commands);
+  void request_open_file (void);
+  void request_mru_open_file (void);
+  void request_print_file (void);
+
+  void request_undo (void);
+  void request_redo (void);
+  void request_copy (void);
+  void request_cut (void);
+  void request_paste (void);
+  void request_save_file (void);
+  void request_save_file_as (void);
+  void request_run_file (void);
+  void request_toggle_bookmark (void);
+  void request_next_bookmark (void);
+  void request_previous_bookmark (void);
+  void request_remove_bookmark (void);
+
+  void request_toggle_breakpoint (void);
+  void request_next_breakpoint (void);
+  void request_previous_breakpoint (void);
+  void request_remove_breakpoint (void);
+
+  void request_comment_selected_text (void);
+  void request_uncomment_selected_text (void);
+  void request_find (void);
+
+  void request_goto_line (void);
+
+  void handle_file_name_changed (const QString& fileName,
+                                 const QString& toolTip);
+  void handle_tab_close_request (int index);
+  void handle_tab_remove_request (void);
+  void handle_add_filename_to_list (const QString& fileName, QWidget *ID);
+  void active_tab_changed (int index);
+  void handle_editor_state_changed (bool enableCopy, const QString& fileName);
+  void handle_mru_add_file (const QString& file_name);
+  void check_conflict_save (const QString& fileName, bool remove_on_success);
+
+  void handle_insert_debugger_pointer_request (const QString& file, int line);
+  void handle_delete_debugger_pointer_request (const QString& file, int line);
+  void handle_update_breakpoint_marker_request (bool insert,
+                                                const QString& file, int line);
+
+  void handle_edit_file_request (const QString& file);
+
+  // Tells the editor to react on changed settings.
+  void notice_settings (const QSettings *settings);
+
+private slots:
+
+  void request_open_file (const QString& fileName, int line = -1,
+                          bool debug_pointer = false,
+                          bool breakpoint_marker = false, bool insert = true);
+
+private:
+
+  void construct (void);
+  void add_file_editor_tab (file_editor_tab *f, const QString& fn);
+  void save_file_as (QWidget *fetabID = 0);
+  void mru_menu_update (void);
+
+  QWidget *find_tab_widget (const QString& openFileName) const;
+
+  std::map<QString, QWidget *> editor_tab_map;
+
+  QString ced;
+
+  QMenuBar *_menu_bar;
+  QToolBar *_tool_bar;
+  QMenu *_debug_menu;
+  QAction *_copy_action;
+  QAction *_cut_action;
+  QAction *_run_action;
+  QTabWidget *_tab_widget;
+  int _marker_breakpoint;
+
+  enum { MaxMRUFiles = 10 };
+  QMenu *_mru_file_menu;
+  QAction *_mru_file_actions[MaxMRUFiles];
+  QStringList _mru_files;
+
+};
+
+#endif // FILEEDITORMDISUBWINDOW_H
new file mode 100644
--- /dev/null
+++ b/libgui/src/m-editor/find-dialog.cc
@@ -0,0 +1,306 @@
+/****************************************************************************
+
+Find dialog derived from an example from Qt Toolkit (license below (**))
+
+Copyright (C) 2012-2013 Torsten <ttl@justmail.de>
+Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+ All rights reserved.
+ Contact: Nokia Corporation (qt-info@nokia.com)
+
+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/>.
+
+** This file is part of the examples of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial Usage
+** Licensees holding valid Qt Commercial licenses may use this file in
+** accordance with the Qt Commercial License Agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Nokia.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file.  Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights.  These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file.  Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#ifdef HAVE_QSCINTILLA
+
+#include <QtGui>
+#include <QIcon>
+#include "find-dialog.h"
+
+find_dialog::find_dialog (QsciScintilla* edit_area, QWidget *p)
+  : QDialog (p)
+{
+  setWindowTitle ("Find and Replace");
+  setWindowIcon (QIcon(":/actions/icons/search.png"));
+
+  _search_label = new QLabel (tr ("Find &what:"));
+  _search_line_edit = new QLineEdit;
+  _search_label->setBuddy (_search_line_edit);
+  _replace_label = new QLabel (tr ("Re&place with:"));
+  _replace_line_edit = new QLineEdit;
+  _replace_label->setBuddy (_replace_line_edit);
+
+  _case_check_box = new QCheckBox (tr ("Match &case"));
+  _from_start_check_box = new QCheckBox (tr ("Search from &start"));
+  _wrap_check_box = new QCheckBox (tr ("&Wrap while searching"));
+  _wrap_check_box->setChecked(true);
+  _find_next_button = new QPushButton (tr ("&Find Next"));
+  _find_prev_button = new QPushButton (tr ("Find &Previous"));
+  _replace_button = new QPushButton (tr ("&Replace"));
+  _replace_all_button = new QPushButton (tr ("Replace &All"));
+
+  _more_button = new QPushButton (tr ("&More"));
+  _more_button->setCheckable (true);
+  _more_button->setAutoDefault (false);
+
+  _button_box = new QDialogButtonBox (Qt::Vertical);
+  _button_box->addButton (_find_next_button, QDialogButtonBox::ActionRole);
+  _button_box->addButton (_find_prev_button, QDialogButtonBox::ActionRole);
+  _button_box->addButton (_replace_button, QDialogButtonBox::ActionRole);
+  _button_box->addButton (_replace_all_button, QDialogButtonBox::ActionRole);
+  _button_box->addButton (_more_button, QDialogButtonBox::ActionRole);
+  _button_box->addButton (QDialogButtonBox::Close);
+
+  _extension = new QWidget (this);
+  _whole_words_check_box = new QCheckBox (tr ("&Whole words"));
+  _regex_check_box = new QCheckBox (tr ("Regular E&xpressions"));
+  _backward_check_box = new QCheckBox (tr ("Search &backward"));
+  _search_selection_check_box = new QCheckBox (tr ("Search se&lection"));
+  _search_selection_check_box->setCheckable (false); // TODO: Not implemented.
+  _search_selection_check_box->setEnabled (false);
+
+  _edit_area = edit_area;
+  connect (_find_next_button,   SIGNAL (clicked ()),
+           this,                SLOT (find_next ()));
+  connect (_find_prev_button,   SIGNAL (clicked ()),
+           this,                SLOT (find_prev ()));
+  connect (_more_button,        SIGNAL (toggled (bool)),
+           _extension,          SLOT (setVisible (bool)));
+  connect (_replace_button,     SIGNAL (clicked ()),
+           this,                SLOT (replace ()));
+  connect (_replace_all_button, SIGNAL (clicked ()),
+           this,                SLOT (replace_all ()));
+  connect (_backward_check_box, SIGNAL (stateChanged (int)),
+           this,                SLOT (handle_backward_search_changed (int)));
+  connect (_button_box,         SIGNAL (rejected ()),
+           this,                SLOT (close ()));
+
+  QVBoxLayout *extension_layout = new QVBoxLayout ();
+  extension_layout->setMargin (0);
+  extension_layout->addWidget (_whole_words_check_box);
+  extension_layout->addWidget (_backward_check_box);
+  extension_layout->addWidget (_search_selection_check_box);
+  _extension->setLayout (extension_layout);
+
+  QGridLayout *top_left_layout = new QGridLayout;
+  top_left_layout->addWidget (_search_label, 1, 1);
+  top_left_layout->addWidget (_search_line_edit, 1, 2);
+  top_left_layout->addWidget (_replace_label, 2, 1);
+  top_left_layout->addWidget (_replace_line_edit, 2, 2);
+
+  QVBoxLayout *left_layout = new QVBoxLayout;
+  left_layout->addLayout (top_left_layout);
+  left_layout->insertStretch (1, 5);
+  left_layout->addWidget (_case_check_box);
+  left_layout->addWidget (_from_start_check_box);
+  left_layout->addWidget (_wrap_check_box);
+  left_layout->addWidget (_regex_check_box);
+
+  QGridLayout *main_layout = new QGridLayout;
+  main_layout->setSizeConstraint (QLayout::SetFixedSize);
+  main_layout->addLayout (left_layout, 0, 0);
+  main_layout->addWidget (_button_box, 0, 1);
+  main_layout->addWidget (_extension, 1, 0);
+  setLayout (main_layout);
+
+  _extension->hide ();
+  _find_next_button->setDefault (true);
+  _find_result_available = false;
+
+  move (p->x() + p->frameGeometry ().width (), p->y());
+
+}
+
+// set text of "search from start" depending on backward search
+void
+find_dialog::handle_backward_search_changed (int backward)
+{
+  if (backward)
+    _from_start_check_box->setText (tr ("Search from end"));
+  else
+    _from_start_check_box->setText (tr ("Search from start"));
+}
+
+// initialize search text with selected text if this is in one single line
+void
+find_dialog::init_search_text ()
+{
+  if (_edit_area->hasSelectedText ())
+    {
+      int lbeg, lend, cbeg, cend;
+      _edit_area->getSelection(&lbeg,&cbeg,&lend,&cend);
+      if (lbeg == lend)
+        _search_line_edit->setText (_edit_area->selectedText ());
+    }
+}
+
+void
+find_dialog::find_next ()
+{
+  find (!_backward_check_box->isChecked ());
+}
+
+void
+find_dialog::find_prev ()
+{
+  find (_backward_check_box->isChecked ());
+}
+
+void
+find_dialog::find (bool forward)
+{
+  int line = -1, col = -1;
+  bool do_wrap = _wrap_check_box->isChecked ();
+  bool do_forward = true;
+
+  if (_find_result_available)
+    { // we found a match last time, cursor is at the end of the match
+      if (!forward)
+        {  // backward: go back one position or we will find the same again
+          do_forward = false;
+          _edit_area->getCursorPosition (&line,&col);
+          if (col > 0)
+            _edit_area->setCursorPosition (line,--col);
+        }
+    }
+
+  _find_result_available = false;
+
+  if (_from_start_check_box->isChecked ())
+    {
+      line = 0;
+      col  = 0;
+      if (_backward_check_box->isChecked ())
+        do_wrap = true;
+    }
+
+  if (_edit_area)
+    {
+      _find_result_available = _edit_area->findFirst (_search_line_edit->text (),
+                                                      _regex_check_box->isChecked (),
+                                                      _case_check_box->isChecked (),
+                                                      _whole_words_check_box->isChecked (),
+                                                      do_wrap,
+                                                      do_forward,
+                                                      line,col,
+                                                      true
+#ifdef HAVE_FINDFIRST_MODERN
+                                                      , true
+#endif
+                                                      );
+    }
+  if (_find_result_available)
+    _from_start_check_box->setChecked (0);
+  else
+    no_matches_message ();
+}
+
+
+void
+find_dialog::replace ()
+{
+  if (_edit_area)
+    {
+      _edit_area->replace (_replace_line_edit->text ());
+      if (!_edit_area->findNext())
+        no_matches_message ();
+    }
+}
+
+void
+find_dialog::replace_all ()
+{
+  int count = 0;
+
+  // check whether find & replace srings are different (avoid endless loop!)
+  int strDiff;
+  Qt::CaseSensitivity cs;
+  if (_case_check_box->isChecked())
+    {
+      cs = Qt::CaseSensitive;
+    }
+  else
+    {
+      cs = Qt::CaseInsensitive;
+    }
+  strDiff = QString::compare(_search_line_edit->text(),_replace_line_edit->text(),cs);
+
+  // replace all if strings are different
+  if (_edit_area && strDiff )
+    {
+      find (!_backward_check_box->isChecked ());  // find first occurence
+      while (_find_result_available)   // while search string is found
+        {
+          _edit_area->replace (_replace_line_edit->text ());   // replace
+          count++;                                             // inc counter
+          _find_result_available = _edit_area->findNext();     // and find next
+        }
+      QMessageBox msg_box (QMessageBox::Information, tr ("Replace Result"),
+                           tr ("%1 items replaced").arg(count),
+                           QMessageBox::Ok, this);
+      msg_box.exec ();
+    }
+  // TODO: Show number of replaced strings
+}
+
+void
+find_dialog::no_matches_message ()
+{
+ 	QMessageBox msg_box (QMessageBox::Information, tr ("Find Result"),
+                       tr ("No more matches found"), QMessageBox::Ok, this);
+  msg_box.exec ();
+}
+
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libgui/src/m-editor/find-dialog.h
@@ -0,0 +1,114 @@
+/****************************************************************************
+
+Find dialog derived from an example from Qt Toolkit (license below (**))
+
+Copyright (C) 2012-2013 Torsten <ttl@justmail.de>
+Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+ All rights reserved.
+ Contact: Nokia Corporation (qt-info@nokia.com)
+
+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/>.
+
+** This file is part of the examples of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial Usage
+** Licensees holding valid Qt Commercial licenses may use this file in
+** accordance with the Qt Commercial License Agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Nokia.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file.  Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights.  These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file.  Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef FIND_DIALOG_H
+#define FIND_DIALOG_H
+
+#include <QDialog>
+#include <Qsci/qsciscintilla.h>
+
+class QCheckBox;
+class QDialogButtonBox;
+class QGroupBox;
+class QLabel;
+class QLineEdit;
+class QPushButton;
+
+class find_dialog : public QDialog
+{
+  Q_OBJECT
+  public:
+  find_dialog (QsciScintilla* edit_area, QWidget *parent = 0);
+  void init_search_text ();
+
+private slots:
+  void handle_backward_search_changed (int);
+  void find (bool forward = true);
+  void find_next ();
+  void find_prev ();
+  void replace ();
+  void replace_all ();
+
+private:
+  void no_matches_message ();
+  QLabel            *_search_label;
+  QLineEdit         *_search_line_edit;
+  QLabel            *_replace_label;
+  QLineEdit         *_replace_line_edit;
+  QCheckBox         *_case_check_box;
+  QCheckBox         *_from_start_check_box;
+  QCheckBox         *_wrap_check_box;
+  QCheckBox         *_whole_words_check_box;
+  QCheckBox         *_regex_check_box;
+  QCheckBox         *_search_selection_check_box;
+  QCheckBox         *_backward_check_box;
+  QDialogButtonBox  *_button_box;
+  QPushButton       *_find_next_button;
+  QPushButton       *_find_prev_button;
+  QPushButton       *_replace_button;
+  QPushButton       *_replace_all_button;
+  QPushButton       *_more_button;
+  QWidget           *_extension;
+  QsciScintilla     *_edit_area;
+  bool               _find_result_available;
+};
+
+#endif // FIND_DIALOG_H
+
new file mode 100644
--- /dev/null
+++ b/libgui/src/m-editor/lexer-octave-gui.cc
@@ -0,0 +1,176 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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
+
+#ifdef HAVE_QSCINTILLA
+
+#include "lexer-octave-gui.h"
+#include <qcolor.h>
+#include <qfont.h>
+
+// -----------------------------------------------------
+// Some basic functions
+// -----------------------------------------------------
+lexer_octave_gui::lexer_octave_gui (QObject *p)
+  : QsciLexer (p)
+{
+  // The API info that is used for auto completion
+  // TODO: Where to store a file with API info (raw or prepared?)?
+  // TODO: Also provide infos on octave-forge functions?
+  // TODO: Also provide infos on function parameters?
+  // By now, use the keywords-list from syntax highlighting
+  QString keyword;
+  QStringList keywordList;
+  keyword = this->keywords (1);           // get whole string with all keywords
+  keywordList = keyword.split (QRegExp ("\\s+"));  // split into single strings
+  lexer_api = new QsciAPIs (this);
+  if (lexer_api)
+    {
+      for (int i = 0; i < keywordList.size (); i++)  // add all keywords to API
+        lexer_api->add (keywordList.at (i));
+      lexer_api->prepare ();   // prepare API info ... this may take some time
+    }
+}
+
+lexer_octave_gui::~lexer_octave_gui()
+{
+  if (lexer_api)
+    delete lexer_api;
+}
+
+// -----------------------------------------------------------------------------
+// Redefined functions to make an octave lexer from the abtract class Qscilexer.
+//   Scintilla has an octave/matlab-lexer but the interface in Qscintilla is
+//   only available in version 2.5.1. Redefining the following purely virtual
+//   functions of the class QsciLexer () and the enum of available styles (see
+//   lexer-octave-gui.h provides the functionality of the octave lexer.
+// -----------------------------------------------------------------------------
+const char *
+lexer_octave_gui::language() const
+{
+  return "Octave";  // return the name of the language
+}
+
+const char *
+lexer_octave_gui::lexer() const
+{
+  return "octave";  // return the name of the lexer
+}
+
+QString
+lexer_octave_gui::description(int style) const
+{
+    switch (style)
+    {
+    case Default:
+        return tr("Default");
+    case Comment:
+        return tr("Comment");
+    case Command:
+        return tr("Command");
+    case Number:
+        return tr("Number");
+    case Keyword:
+        return tr("Keyword");
+    case SingleQuotedString:
+        return tr("Single-quoted string");
+    case Operator:
+        return tr("Operator");
+    case Identifier:
+        return tr("Identifier");
+    case DoubleQuotedString:
+        return tr("Double-quoted string");
+    }
+    return QString();  // no valid style, return empty string
+}
+
+
+// -----------------------------------------------------
+// The set of default colors
+// -----------------------------------------------------
+QColor
+lexer_octave_gui::defaultColor (int style) const
+{
+  switch (style)
+    {
+      case Default:
+      case Operator:
+        return QColor (0x00,0x00,0x00);
+
+      case Comment:
+        return QColor (0x00,0x7f,0x00);
+
+      case Command:
+        return QColor (0x7f,0x7f,0x00);
+
+      case Number:
+        return QColor (0x00,0x7f,0x7f);
+
+      case Keyword:
+        return QColor (0x00,0x00,0x7f);
+
+      case SingleQuotedString:
+      case DoubleQuotedString:
+        return QColor (0x7f,0x00,0x7f);
+    }
+
+    return QsciLexer::defaultColor (style);
+}
+
+// -----------------------------------------------------
+// The defaulot fonts
+// -----------------------------------------------------
+QFont
+lexer_octave_gui::defaultFont (int style) const
+{
+  QFont font;
+
+  switch (style)
+    {
+      case Keyword:
+        font = QsciLexer::defaultFont (style);
+        font.setBold(true);
+        break;
+
+      default:
+        font = QsciLexer::defaultFont (style);
+    }
+
+  return font;
+}
+
+// -----------------------------------------------------
+// The set of keywords for highlighting
+// -----------------------------------------------------
+const char *
+lexer_octave_gui::keywords(int set) const
+{
+  if (set == 1)
+      return resource_manager::octave_keywords ();
+
+  return 0;
+}
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libgui/src/m-editor/lexer-octave-gui.h
@@ -0,0 +1,66 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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/>.
+
+*/
+
+#ifndef LEXEROCTAVE_H
+#define LEXEROCTAVE_H
+
+#include "resource-manager.h"
+#include <QObject>
+#include <Qsci/qsciglobal.h>
+#include <Qsci/qscilexer.h>
+#include <Qsci/qsciapis.h>
+
+class lexer_octave_gui : public QsciLexer
+{
+  Q_OBJECT
+
+public:
+
+  enum {
+        Default = 0,
+        Comment = 1,
+        Command = 2,
+        Number = 3,
+        Keyword = 4,
+        SingleQuotedString = 5,
+        Operator = 6,
+        Identifier = 7,
+        DoubleQuotedString = 8
+    };
+
+
+  lexer_octave_gui (QObject *parent = 0);
+  ~lexer_octave_gui ();
+  virtual const char *keywords (int set) const;
+  virtual const char *lexer () const;
+  virtual const char *language () const;
+  QString description (int style) const;
+  QColor defaultColor (int style) const;
+  QFont defaultFont (int style) const;
+
+private:
+  lexer_octave_gui (const lexer_octave_gui &);
+  lexer_octave_gui &operator= (const lexer_octave_gui &);
+  QsciAPIs *lexer_api;
+};
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libgui/src/main-window.cc
@@ -0,0 +1,1563 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 <QApplication>
+#include <QLabel>
+#include <QMenuBar>
+#include <QMenu>
+#include <QAction>
+#include <QSettings>
+#include <QStyle>
+#include <QToolBar>
+#include <QDesktopServices>
+#include <QDesktopWidget>
+#include <QFileDialog>
+#include <QMessageBox>
+#include <QIcon>
+
+#include <utility>
+
+#ifdef HAVE_QSCINTILLA
+#include "file-editor.h"
+#endif
+#include "main-window.h"
+#include "settings-dialog.h"
+
+#include "cmd-edit.h"
+
+#include "builtin-defun-decls.h"
+#include "defaults.h"
+#include "symtab.h"
+#include "version.h"
+
+static file_editor_interface *
+create_default_editor (QWidget *p)
+{
+#ifdef HAVE_QSCINTILLA
+  return new file_editor (p);
+#else
+  return 0;
+#endif
+}
+
+main_window::main_window (QWidget *p)
+  : QMainWindow (p),
+    _workspace_model (new workspace_model ()),
+    status_bar (new QStatusBar ()),
+    command_window (new terminal_dock_widget (this)),
+    history_window (new history_dock_widget (this)),
+    file_browser_window (new files_dock_widget (this)),
+    doc_browser_window (new documentation_dock_widget (this)),
+    editor_window (create_default_editor (this)),
+    workspace_window (new workspace_view (this)),
+    find_files_dlg (0),
+    _octave_main_thread (0),
+    _octave_qt_link (0)
+{
+  // We have to set up all our windows, before we finally launch octave.
+  construct ();
+}
+
+main_window::~main_window (void)
+{
+  // Destroy the terminal first so that STDERR stream is redirected back
+  // to its original pipe to capture error messages at exit.
+
+  delete command_window;
+  delete workspace_window;
+  delete editor_window;
+  delete doc_browser_window;
+  delete file_browser_window;
+  delete history_window;
+  delete status_bar;
+  delete _workspace_model;
+  if (find_files_dlg) 
+    {
+      delete find_files_dlg;
+      find_files_dlg = 0;
+    }
+  delete _octave_main_thread;
+  delete _octave_qt_link;
+}
+
+bool
+main_window::command_window_has_focus (void) const
+{
+  return command_window->has_focus ();
+}
+
+void
+main_window::focus_command_window (void)
+{
+  command_window->focus ();
+}
+
+void
+main_window::new_file (const QString& commands)
+{
+  emit new_file_signal (commands);
+}
+
+void
+main_window::open_file (const QString& file_name)
+{
+  emit open_file_signal (file_name);
+}
+
+void
+main_window::report_status_message (const QString& statusMessage)
+{
+  status_bar->showMessage (statusMessage, 1000);
+}
+
+void
+main_window::handle_save_workspace_request (void)
+{
+  QString file =
+    QFileDialog::getSaveFileName (this, tr ("Save Workspace As"), ".");
+
+  if (! file.isEmpty ())
+    octave_link::post_event (this, &main_window::save_workspace_callback,
+                             file.toStdString ());
+}
+
+void
+main_window::handle_load_workspace_request (const QString& file_arg)
+{
+  QString file = file_arg;
+
+  if (file.isEmpty ())
+    file = QFileDialog::getOpenFileName (this, tr ("Load Workspace"), ".");
+
+  if (! file.isEmpty ())
+    octave_link::post_event (this, &main_window::load_workspace_callback,
+                             file.toStdString ());
+}
+
+void
+main_window::handle_clear_workspace_request (void)
+{
+  octave_link::post_event (this, &main_window::clear_workspace_callback);
+}
+
+void
+main_window::handle_rename_variable_request (const QString& old_name,
+                                             const QString& new_name)
+
+{
+  name_pair names (old_name.toStdString (), new_name.toStdString ());
+
+  octave_link::post_event (this, &main_window::rename_variable_callback,
+                           names);
+}
+
+void
+main_window::handle_undo_request (void)
+{
+  octave_link::post_event (this, &main_window::command_window_undo_callback);
+}
+
+void
+main_window::handle_clear_command_window_request (void)
+{
+  octave_link::post_event (this, &main_window::clear_command_window_callback);
+}
+
+void
+main_window::handle_clear_history_request (void)
+{
+  octave_link::post_event (this, &main_window::clear_history_callback);
+}
+
+void
+main_window::execute_command_in_terminal (const QString& command)
+{
+  octave_link::post_event (this, &main_window::execute_command_callback,
+                           command.toStdString ());
+
+  focus_command_window ();
+}
+
+void
+main_window::handle_new_figure_request (void)
+{
+  octave_link::post_event (this, &main_window::new_figure_callback);
+}
+
+void
+main_window::handle_new_variable_request (void)
+{
+  QMessageBox::about (this, tr ("New Variable"),
+                      tr ("The new variable action is not implemented."));
+}
+
+void
+main_window::open_online_documentation_page (void)
+{
+  QDesktopServices::openUrl (QUrl ("http://gnu.org/software/octave/doc/interpreter"));
+}
+
+void
+main_window::open_bug_tracker_page (void)
+{
+  QDesktopServices::openUrl (QUrl ("http://bugs.octave.org"));
+}
+
+void
+main_window::open_octave_forge_page (void)
+{
+  QDesktopServices::openUrl (QUrl ("http://octave.sourceforge.net/"));
+}
+
+void
+main_window::open_agora_page (void)
+{
+  QDesktopServices::openUrl (QUrl ("http://agora.octave.org/"));
+}
+
+void
+main_window::process_settings_dialog_request (void)
+{
+  settings_dialog *settingsDialog = new settings_dialog (this);
+  int change_settings = settingsDialog->exec ();
+  if (change_settings == QDialog::Accepted)
+    {
+      settingsDialog->write_changed_settings ();
+      QSettings *settings = resource_manager::get_settings ();
+      if (settings)
+        emit settings_changed (settings);
+    }
+  delete settingsDialog;
+}
+
+
+void
+main_window::notice_settings (const QSettings *settings)
+{
+  // QSettings pointer is checked before emitting.
+
+  // the widget's icons (when floating)
+  QString icon_set
+    = settings->value ("DockWidgets/widget_icon_set", "NONE").toString ();
+
+  static struct
+    {
+      QString name;
+      QString path;
+    }
+
+  widget_icon_data[] =
+    { // array of possible icon sets (name, path (complete for NONE))
+      // the first entry here is the default!
+      {"NONE",    ":/actions/icons/logo.png"},
+      {"GRAPHIC", ":/actions/icons/graphic_logo_"},
+      {"LETTER",  ":/actions/icons/letter_logo_"},
+      {"", ""} // end marker has empty name
+    };
+
+  int count = 0;
+  int icon_set_found = 0; // default
+
+  while (!widget_icon_data[count].name.isEmpty ())
+    { // while not end of data
+      if (widget_icon_data[count].name == icon_set)
+        { // data of desired icon set found
+          icon_set_found = count;
+          break;
+        }
+      count++;
+    }
+
+  QString icon;
+  foreach (QObject *obj, children ())
+    {
+      QString name = obj->objectName ();
+      if (obj->inherits ("QDockWidget") && ! name.isEmpty ())
+        { // if children is a dock widget with a name
+          QDockWidget *widget = qobject_cast<QDockWidget *> (obj);
+          icon = widget_icon_data[icon_set_found].path; // prefix or octave-logo
+          if (widget_icon_data[icon_set_found].name != "NONE")
+            icon = icon + name + ".png"; // add widget name and ext.
+          widget->setWindowIcon (QIcon (icon));
+        }
+    }
+
+  int icon_size = settings->value ("toolbar_icon_size",24).toInt ();
+  _main_tool_bar->setIconSize (QSize (icon_size,icon_size));
+
+  resource_manager::update_network_settings ();
+}
+
+
+void
+main_window::prepare_to_exit (void)
+{
+  write_settings ();
+}
+
+void
+main_window::exit (int status)
+{
+  qApp->exit (status);
+}
+
+void
+main_window::reset_windows (void)
+{
+  QSettings *settings = resource_manager::get_default_settings ();
+
+  set_window_layout (settings);
+}
+
+void
+main_window::change_directory (const QString& dir)
+{
+  // Remove existing entry, if any, then add new directory at top and
+  // mark it as the current directory.  Finally, update the file list
+  // widget.
+
+  int index = _current_directory_combo_box->findText (dir);
+
+  if (index >= 0)
+    _current_directory_combo_box->removeItem (index);
+
+  _current_directory_combo_box->insertItem (0, dir);
+  _current_directory_combo_box->setCurrentIndex (0);
+
+  file_browser_window->update_octave_directory (dir);
+}
+
+void
+main_window::browse_for_directory (void)
+{
+  QString dir
+    = QFileDialog::getExistingDirectory (this, tr ("Set working directory"));
+
+  set_current_working_directory (dir);
+
+  // FIXME -- on Windows systems, the command window freezes after the
+  // previous actions.  Forcing the focus appears to unstick it.
+
+  focus_command_window ();
+}
+
+void
+main_window::set_current_working_directory (const QString& dir)
+{
+  // Change to dir if it is an existing directory.
+
+  QString xdir = dir.isEmpty () ? "." : dir;
+    
+  QFileInfo fileInfo (xdir);
+
+  if (fileInfo.exists () && fileInfo.isDir ())
+    octave_link::post_event (this, &main_window::change_directory_callback,
+                             xdir.toStdString ());
+}
+
+void
+main_window::change_directory_up (void)
+{
+  set_current_working_directory ("..");
+}
+
+// Slot that is called if return is pressed in the line edit of the
+// combobox to change to a new directory or a directory that is already
+// in the drop down list.
+
+void
+main_window::accept_directory_line_edit (void)
+{
+  // Get new directory name, and change to it if it is new.  Otherwise,
+  // the combo box will triggers the "activated" signal to change to the
+  // directory.
+
+  QString dir = _current_directory_combo_box->currentText ();
+
+  int index = _current_directory_combo_box->findText (dir);
+
+  if (index < 0)
+    set_current_working_directory (dir);
+}
+
+void
+main_window::handle_enter_debugger (void)
+{
+  setWindowTitle ("Octave (Debugging)");
+
+  _debug_continue->setEnabled (true);
+  _debug_step_into->setEnabled (true);
+  _debug_step_over->setEnabled (true);
+  _debug_step_out->setEnabled (true);
+  _debug_quit->setEnabled (true);
+
+#ifdef HAVE_QSCINTILLA
+  editor_window->handle_enter_debug_mode ();
+#endif
+}
+
+void
+main_window::handle_exit_debugger (void)
+{
+  setWindowTitle ("Octave");
+
+  _debug_continue->setEnabled (false);
+  _debug_step_into->setEnabled (false);
+  _debug_step_over->setEnabled (false);
+  _debug_step_out->setEnabled (false);
+  _debug_quit->setEnabled (false);
+
+#ifdef HAVE_QSCINTILLA
+  editor_window->handle_exit_debug_mode ();
+#endif
+}
+
+void
+main_window::debug_continue (void)
+{
+  octave_link::post_event (this, &main_window::debug_continue_callback);
+}
+
+void
+main_window::debug_step_into (void)
+{
+  octave_link::post_event (this, &main_window::debug_step_into_callback);
+}
+
+void
+main_window::debug_step_over (void)
+{
+  octave_link::post_event (this, &main_window::debug_step_over_callback);
+}
+
+void
+main_window::debug_step_out (void)
+{
+  octave_link::post_event (this, &main_window::debug_step_out_callback);
+}
+
+void
+main_window::debug_quit (void)
+{
+  octave_link::post_event (this, &main_window::debug_quit_callback);
+}
+
+void
+main_window::handle_insert_debugger_pointer_request (const QString& file,
+                                                     int line)
+{
+  bool cmd_focus = command_window_has_focus ();
+
+  emit insert_debugger_pointer_signal (file, line);
+
+  if (cmd_focus)
+    focus_command_window ();
+}
+
+void
+main_window::handle_delete_debugger_pointer_request (const QString& file,
+                                                     int line)
+{
+  bool cmd_focus = command_window_has_focus ();
+
+  emit delete_debugger_pointer_signal (file, line);
+
+  if (cmd_focus)
+    focus_command_window ();
+}
+
+void
+main_window::handle_update_breakpoint_marker_request (bool insert,
+                                                      const QString& file,
+                                                      int line)
+{
+  bool cmd_focus = command_window_has_focus ();
+
+  emit update_breakpoint_marker_signal (insert, file, line);
+
+  if (cmd_focus)
+    focus_command_window ();
+}
+
+void
+main_window::show_about_octave (void)
+{
+  QString message = OCTAVE_STARTUP_MESSAGE;
+
+  QMessageBox::about (this, tr ("About Octave"), message);
+}
+
+void
+main_window::closeEvent (QCloseEvent *e)
+{
+  e->ignore ();
+  octave_link::post_event (this, &main_window::exit_callback);
+}
+
+void
+main_window::read_settings (void)
+{
+  QSettings *settings = resource_manager::get_settings ();
+
+  if (!settings)
+    {
+      qDebug("Error: QSettings pointer from resource manager is NULL.");
+      return;
+    }
+
+  set_window_layout (settings);
+
+  // restore the list of the last directories
+  QStringList curr_dirs = settings->value ("MainWindow/current_directory_list").toStringList ();
+  for (int i=0; i < curr_dirs.size (); i++)
+    {
+      _current_directory_combo_box->addItem (curr_dirs.at (i));
+    }
+  emit settings_changed (settings);
+}
+
+void
+main_window::set_window_layout (QSettings *settings)
+{
+  restoreState (settings->value ("MainWindow/windowState").toByteArray ());
+
+  settings->beginGroup ("DockWidgets");
+
+  // Restore the geometry of all dock-widgets
+  foreach (QObject *obj, children ())
+    {
+      QString name = obj->objectName ();
+
+      if (obj->inherits ("QDockWidget") && ! name.isEmpty ())
+        {
+          QDockWidget *widget = qobject_cast<QDockWidget *> (obj);
+          QVariant val = settings->value (name);
+
+          widget->restoreGeometry (val.toByteArray ());
+
+          // If floating, make window from widget.
+          bool floating = settings->value (name+"Floating", false).toBool ();
+          if (floating)
+            widget->setWindowFlags (Qt::Window);
+
+          // make widget visible if desired (setWindowFlags hides widget).
+          bool visible = settings->value (name+"Visible", true).toBool ();
+          widget->setVisible (visible);
+        }
+    }
+
+  settings->endGroup ();
+
+  restoreGeometry (settings->value ("MainWindow/geometry").toByteArray ());
+}
+
+void
+main_window::write_settings (void)
+{
+  QSettings *settings = resource_manager::get_settings ();
+  if (!settings)
+    {
+      qDebug("Error: QSettings pointer from resource manager is NULL.");
+      return;
+    }
+
+  settings->setValue ("MainWindow/geometry", saveGeometry ());
+  settings->beginGroup ("DockWidgets");
+  // saving the geometry of all widgets
+  foreach (QObject *obj, children())
+    {
+      QString name = obj->objectName ();
+      if (obj->inherits ("QDockWidget") && ! name.isEmpty ())
+        {
+          QDockWidget *widget = qobject_cast<QDockWidget *> (obj);
+          settings->setValue (name, widget->saveGeometry ());
+          bool floating = widget->isFloating ();
+          bool visible = widget->isVisible ();
+          settings->setValue (name+"Floating", floating);  // store floating state
+          settings->setValue (name+"Visible", visible);    // store visibility
+          if (floating)
+            widget->setWindowFlags (Qt::Widget); // if floating, recover the widget state such that the widget's
+        }                                       // state is correctly saved by the saveSate () below
+    }
+  settings->endGroup();
+  settings->setValue ("MainWindow/windowState", saveState ());
+  // write the list of recent used directories
+  QStringList curr_dirs;
+  for (int i=0; i<_current_directory_combo_box->count (); i++)
+    {
+      curr_dirs.append (_current_directory_combo_box->itemText (i));
+    }
+  settings->setValue ("MainWindow/current_directory_list", curr_dirs);
+  settings->sync ();
+}
+
+
+// Connecting the signals emitted when the visibility of a widget changes.
+// This has to be done after the window is shown (see octave-gui.cc)
+void
+main_window::connect_visibility_changed (void)
+{
+  command_window->connect_visibility_changed ();
+  history_window->connect_visibility_changed ();
+  file_browser_window->connect_visibility_changed ();
+  doc_browser_window->connect_visibility_changed ();
+#ifdef HAVE_QSCINTILLA
+  editor_window->connect_visibility_changed ();
+#endif
+  workspace_window->connect_visibility_changed ();
+}
+
+// Connect the signals emitted when the Octave thread wants to create
+// a dialog box of some sort.  Perhaps a better place for this would be
+// as part of the QUIWidgetCreator class.  However, mainWindow currently
+// is not a global variable and not accessible for connecting.
+
+void
+main_window::connect_uiwidget_links ()
+{
+  connect (&uiwidget_creator,
+           SIGNAL (create_dialog (const QString&, const QString&,
+                                  const QString&, const QStringList&,
+                                  const QString&, const QStringList&)),
+           this,
+           SLOT (handle_create_dialog (const QString&, const QString&,
+                                       const QString&, const QStringList&,
+                                       const QString&, const QStringList&)));
+
+  // Register QIntList so that list of ints may be part of a signal.
+  qRegisterMetaType<QIntList> ("QIntList");
+  connect (&uiwidget_creator,
+           SIGNAL (create_listview (const QStringList&, const QString&,
+                                    int, int, const QIntList&,
+                                    const QString&, const QStringList&,
+                                    const QString&, const QString&)),
+           this,
+           SLOT (handle_create_listview (const QStringList&, const QString&,
+                                         int, int, const QIntList&,
+                                         const QString&, const QStringList&,
+                                         const QString&, const QString&)));
+
+  // Register QFloatList so that list of floats may be part of a signal.
+  qRegisterMetaType<QFloatList> ("QFloatList");
+  connect (&uiwidget_creator,
+           SIGNAL (create_inputlayout (const QStringList&, const QString&,
+                                       const QFloatList&, const QFloatList&,
+                                       const QStringList&)),
+           this,
+           SLOT (handle_create_inputlayout (const QStringList&, const QString&,
+                                            const QFloatList&, const QFloatList&,
+                                            const QStringList&)));
+
+  connect (&uiwidget_creator,
+           SIGNAL (create_filedialog (const QStringList &,const QString&,
+                                      const QString&, const QString&, const QString&)),
+           this,
+           SLOT (handle_create_filedialog (const QStringList &, const QString&,
+                                           const QString&, const QString&,
+                                           const QString&)));
+}
+
+// Create a message dialog with specified string, buttons and decorative
+// text.
+
+void
+main_window::handle_create_dialog (const QString& message,
+                                   const QString& title,
+                                   const QString& icon,
+                                   const QStringList& button,
+                                   const QString& defbutton,
+                                   const QStringList& role)
+{
+  MessageDialog *message_dialog = new MessageDialog (message, title, icon,
+                                                     button, defbutton, role);
+  message_dialog->setAttribute (Qt::WA_DeleteOnClose);
+  message_dialog->show ();
+}
+
+// Create a list dialog with specified list, initially selected, mode,
+// view size and decorative text.
+
+void
+main_window::handle_create_listview (const QStringList& list,
+                                     const QString& mode,
+                                     int wd, int ht,
+                                     const QIntList& initial,
+                                     const QString& name,
+                                     const QStringList& prompt,
+                                     const QString& ok_string,
+                                     const QString& cancel_string)
+{
+  ListDialog *list_dialog = new ListDialog (list, mode, wd, ht,
+                                            initial, name, prompt,
+                                            ok_string, cancel_string);
+
+  list_dialog->setAttribute (Qt::WA_DeleteOnClose);
+  list_dialog->show ();
+}
+
+// Create an input dialog with specified prompts and defaults, title and
+// row/column size specifications.
+void
+main_window::handle_create_inputlayout (const QStringList& prompt,
+                                        const QString& title,
+                                        const QFloatList& nr,
+                                        const QFloatList& nc,
+                                        const QStringList& defaults)
+{
+  InputDialog *input_dialog = new InputDialog (prompt, title, nr, nc,
+                                               defaults);
+
+  input_dialog->setAttribute (Qt::WA_DeleteOnClose);
+  input_dialog->show ();
+}
+
+void
+main_window::handle_create_filedialog (const QStringList& filters,
+                                       const QString& title, 
+                                       const QString& filename, 
+                                       const QString& dirname,
+                                       const QString& multimode)
+{
+  FileDialog *file_dialog = new FileDialog (filters, title, filename,
+                                            dirname, multimode);
+
+  file_dialog->setAttribute (Qt::WA_DeleteOnClose);
+  file_dialog->show ();
+}
+
+// Main subroutine of the constructor
+void
+main_window::construct (void)
+{
+  _closing = false;   // flag for editor files when closed
+  setWindowIcon (QIcon (":/actions/icons/logo.png"));
+
+  workspace_window->setModel (_workspace_model);
+  connect (_workspace_model, SIGNAL (model_changed (void)),
+           workspace_window, SLOT (handle_model_changed (void)));
+
+  // 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);
+  dummyWidget->setSizePolicy (QSizePolicy::Minimum, QSizePolicy::Minimum);
+  dummyWidget->hide ();
+  setCentralWidget (dummyWidget);
+
+  construct_menu_bar ();
+
+  construct_tool_bar ();
+
+  connect (qApp, SIGNAL (aboutToQuit ()),
+           this, SLOT (prepare_to_exit ()));
+
+  connect (this, SIGNAL (settings_changed (const QSettings *)),
+           this, SLOT (notice_settings (const QSettings *)));
+
+  connect (file_browser_window, SIGNAL (load_file_signal (const QString&)),
+           this, SLOT (handle_load_workspace_request (const QString&)));
+
+  connect_uiwidget_links ();
+
+  setWindowTitle ("Octave");
+
+  setDockOptions (QMainWindow::AnimatedDocks
+                  | QMainWindow::AllowNestedDocks
+                  | QMainWindow::AllowTabbedDocks);
+
+  addDockWidget (Qt::RightDockWidgetArea, command_window);
+  addDockWidget (Qt::RightDockWidgetArea, doc_browser_window);
+  tabifyDockWidget (command_window, doc_browser_window);
+
+#ifdef HAVE_QSCINTILLA
+  addDockWidget (Qt::RightDockWidgetArea, editor_window);
+  tabifyDockWidget (command_window, editor_window);
+#endif
+
+  addDockWidget (Qt::LeftDockWidgetArea, file_browser_window);
+  addDockWidget (Qt::LeftDockWidgetArea, workspace_window);
+  addDockWidget (Qt::LeftDockWidgetArea, history_window);
+
+  int win_x = QApplication::desktop()->width();
+  int win_y = QApplication::desktop()->height();
+
+  if (win_x > 960)
+    win_x = 960;
+
+  if (win_y > 720)
+    win_y = 720;
+
+  setGeometry (0, 0, win_x, win_y);
+
+  setStatusBar (status_bar);
+
+  construct_octave_qt_link ();
+
+  connect (this,
+           SIGNAL (insert_debugger_pointer_signal (const QString&, int)),
+           editor_window,
+           SLOT (handle_insert_debugger_pointer_request (const QString&, int)));
+
+  connect (this,
+           SIGNAL (delete_debugger_pointer_signal (const QString&, int)),
+           editor_window,
+           SLOT (handle_delete_debugger_pointer_request (const QString&, int)));
+
+  connect (this,
+           SIGNAL (update_breakpoint_marker_signal (bool, const QString&, int)),
+           editor_window,
+           SLOT (handle_update_breakpoint_marker_request (bool, const QString&, int)));
+
+  QDir curr_dir;
+  set_current_working_directory (curr_dir.absolutePath ());
+
+  octave_link::post_event (this, &main_window::resize_command_window_callback);
+}
+
+void
+main_window::construct_octave_qt_link (void)
+{
+  _octave_main_thread = new octave_main_thread ();
+
+  _octave_qt_link = new octave_qt_link (_octave_main_thread);
+
+  connect (_octave_qt_link, SIGNAL (exit_signal (int)),
+           this, SLOT (exit (int)));
+
+  connect (_octave_qt_link,
+           SIGNAL (set_workspace_signal
+                   (bool, const QString&, const QStringList&,
+                    const QStringList&, const QStringList&,
+                    const QStringList&)),
+           _workspace_model,
+           SLOT (set_workspace
+                 (bool, const QString&, const QStringList&,
+                  const QStringList&, const QStringList&,
+                  const QStringList&)));
+
+  connect (_octave_qt_link, SIGNAL (clear_workspace_signal ()),
+           _workspace_model, SLOT (clear_workspace ()));
+
+  connect (_octave_qt_link, SIGNAL (change_directory_signal (QString)),
+           this, SLOT (change_directory (QString)));
+
+  connect (_octave_qt_link,
+           SIGNAL (execute_command_in_terminal_signal (QString)),
+           this, SLOT (execute_command_in_terminal (QString)));
+
+  connect (_octave_qt_link,
+           SIGNAL (set_history_signal (const QStringList&)),
+           history_window, SLOT (set_history (const QStringList&)));
+
+  connect (_octave_qt_link,
+           SIGNAL (append_history_signal (const QString&)),
+           history_window, SLOT (append_history (const QString&)));
+
+  connect (_octave_qt_link,
+           SIGNAL (clear_history_signal (void)),
+           history_window, SLOT (clear_history (void)));
+
+  connect (_octave_qt_link, SIGNAL (enter_debugger_signal ()),
+           this, SLOT (handle_enter_debugger ()));
+
+  connect (_octave_qt_link, SIGNAL (exit_debugger_signal ()),
+           this, SLOT (handle_exit_debugger ()));
+
+  connect (_octave_qt_link,
+           SIGNAL (edit_file_signal (const QString&)),
+           editor_window,
+           SLOT (handle_edit_file_request (const QString&)));
+
+  connect (_octave_qt_link,
+           SIGNAL (insert_debugger_pointer_signal (const QString&, int)),
+           this,
+           SLOT (handle_insert_debugger_pointer_request (const QString&, int)));
+
+  connect (_octave_qt_link,
+           SIGNAL (delete_debugger_pointer_signal (const QString&, int)),
+           this,
+           SLOT (handle_delete_debugger_pointer_request (const QString&, int)));
+
+  connect (_octave_qt_link,
+           SIGNAL (update_breakpoint_marker_signal (bool, const QString&, int)),
+           this,
+           SLOT (handle_update_breakpoint_marker_request (bool, const QString&, int)));
+
+  connect (_workspace_model,
+           SIGNAL (rename_variable (const QString&, const QString&)),
+           this,
+           SLOT (handle_rename_variable_request (const QString&,
+                                                 const QString&)));
+
+  _octave_qt_link->execute_interpreter ();
+
+  octave_link::connect_link (_octave_qt_link);
+}
+
+void
+main_window::construct_menu_bar (void)
+{
+  QMenuBar *menu_bar = menuBar ();
+
+  construct_file_menu (menu_bar);
+
+  construct_edit_menu (menu_bar);
+
+  construct_debug_menu (menu_bar);
+
+  construct_window_menu (menu_bar);
+
+  construct_help_menu (menu_bar);
+}
+
+void
+main_window::construct_file_menu (QMenuBar *p)
+{
+  QMenu *file_menu = p->addMenu (tr ("&File"));
+
+  construct_new_menu (file_menu);
+
+  _open_action
+    = file_menu->addAction (QIcon (":/actions/icons/fileopen.png"),
+                            tr ("Open..."));
+  _open_action->setShortcut (QKeySequence::Open);
+  _open_action->setShortcutContext (Qt::ApplicationShortcut);
+
+#ifdef HAVE_QSCINTILLA
+  file_menu->addMenu (editor_window->get_mru_menu ());
+#endif
+
+  file_menu->addSeparator ();
+
+  QAction *load_workspace_action
+    = file_menu->addAction (tr ("Load workspace"));
+
+  QAction *save_workspace_action
+    = file_menu->addAction (tr ("Save Workspace As"));
+
+  file_menu->addSeparator ();
+
+  QAction *preferences_action
+    = file_menu->addAction (QIcon (":/actions/icons/configure.png"),
+                            tr ("Preferences..."));
+
+  file_menu->addSeparator ();
+
+  QAction *exit_action = file_menu->addAction (tr ("Exit"));
+  exit_action->setShortcut (QKeySequence::Quit);
+
+  connect (preferences_action, SIGNAL (triggered ()),
+           this, SLOT (process_settings_dialog_request ()));
+
+  connect (_open_action, SIGNAL (triggered ()),
+           editor_window, SLOT (request_open_file ()));
+
+  connect (load_workspace_action, SIGNAL (triggered ()),
+           this, SLOT (handle_load_workspace_request ()));
+
+  connect (save_workspace_action, SIGNAL (triggered ()),
+           this, SLOT (handle_save_workspace_request ()));
+
+  connect (exit_action, SIGNAL (triggered ()),
+           this, SLOT (close ()));
+}
+
+void
+main_window::construct_new_menu (QMenu *p)
+{
+  QMenu *new_menu = p->addMenu (tr ("New"));
+
+  _new_script_action
+    = new_menu->addAction (QIcon (":/actions/icons/filenew.png"),
+                           tr ("Script"));
+
+  QAction *new_function_action = new_menu->addAction (tr ("Function"));
+  new_function_action->setEnabled (true);
+
+  QAction *new_figure_action = new_menu->addAction (tr ("Figure"));
+  new_figure_action->setEnabled (true);
+
+  QAction *new_variable_action = new_menu->addAction (tr ("Variable"));
+  new_variable_action->setEnabled (true);
+
+  connect (_new_script_action, SIGNAL (triggered ()),
+           editor_window, SLOT (request_new_script ()));
+
+  connect (new_function_action, SIGNAL (triggered ()),
+           editor_window, SLOT (request_new_function ()));
+
+  connect (new_figure_action, SIGNAL (triggered ()),
+           this, SLOT (handle_new_figure_request ()));
+
+  connect (new_variable_action, SIGNAL (triggered ()),
+           this, SLOT (handle_new_variable_request ()));
+}
+
+void
+main_window::construct_edit_menu (QMenuBar *p)
+{
+  QMenu *edit_menu = p->addMenu (tr ("&Edit"));
+
+  QKeySequence ctrl_shift = Qt::ControlModifier + Qt::ShiftModifier;
+
+  _undo_action
+    = edit_menu->addAction (QIcon (":/actions/icons/undo.png"), tr ("Undo"));
+  _undo_action->setShortcut (QKeySequence::Undo);
+
+  edit_menu->addSeparator ();
+
+  _cut_action
+    = edit_menu->addAction (QIcon (":/actions/icons/editcut.png"), tr ("Cut"));
+  _cut_action->setShortcut (ctrl_shift + Qt::Key_X);
+
+  _copy_action
+    = edit_menu->addAction (QIcon (":/actions/icons/editcopy.png"), tr ("Copy"));
+  _copy_action->setShortcut (ctrl_shift + Qt::Key_C);
+
+  _paste_action
+    = edit_menu->addAction (QIcon (":/actions/icons/editpaste.png"), tr ("Paste"));
+  _paste_action->setShortcut (ctrl_shift + Qt::Key_V);
+
+  QAction *select_all_action
+    = edit_menu->addAction (tr ("Select All"));
+  select_all_action->setEnabled (false); // TODO: Make this work.
+
+  QAction *delete_action
+    = edit_menu->addAction (tr ("Delete"));
+  delete_action->setShortcut (Qt::Key_Delete);
+  delete_action->setEnabled (false); // TODO: Make this work.
+
+  edit_menu->addSeparator ();
+
+  QAction *find_files_action
+    = edit_menu->addAction (tr ("Find Files..."));
+  find_files_action->setShortcut (ctrl_shift + Qt::Key_F);
+
+  edit_menu->addSeparator ();
+
+  QAction *clear_command_window_action
+    = edit_menu->addAction (tr ("Clear Command Window"));
+
+  QAction *clear_command_history
+    = edit_menu->addAction(tr ("Clear Command History"));
+
+  QAction *clear_workspace_action
+    = edit_menu->addAction (tr ("Clear Workspace"));
+
+  connect (_copy_action, SIGNAL (triggered()),
+           command_window, SLOT (copyClipboard ()));
+
+  connect (_paste_action, SIGNAL (triggered()),
+           command_window, SLOT (pasteClipboard ()));
+
+  connect (find_files_action, SIGNAL (triggered()),
+           this, SLOT (find_files ()));
+
+  connect (clear_command_window_action, SIGNAL (triggered ()),
+           this, SLOT (handle_clear_command_window_request ()));
+
+  connect (clear_command_history, SIGNAL (triggered ()),
+           this, SLOT (handle_clear_history_request ()));
+
+  connect (clear_workspace_action, SIGNAL (triggered ()),
+           this, SLOT (handle_clear_workspace_request ()));
+}
+
+QAction *
+main_window::construct_debug_menu_item (const char *icon_file,
+                                        const QString& item,
+                                        const QKeySequence& key)
+{
+  QAction *action = _debug_menu->addAction (QIcon (icon_file), item);
+
+  action->setEnabled (false);
+  action->setShortcut (key);
+
+#ifdef HAVE_QSCINTILLA
+  editor_window->debug_menu ()->addAction (action);
+  editor_window->toolbar ()->addAction (action);
+#endif
+
+  return action;
+}
+
+void
+main_window::construct_debug_menu (QMenuBar *p)
+{
+  _debug_menu = p->addMenu (tr ("De&bug"));
+
+  _debug_step_over = construct_debug_menu_item
+    (":/actions/icons/db_step.png", tr ("Step"), Qt::Key_F10);
+
+  _debug_step_into = construct_debug_menu_item
+    (":/actions/icons/db_step_in.png", tr ("Step in"), Qt::Key_F11);
+
+  _debug_step_out = construct_debug_menu_item
+    (":/actions/icons/db_step_out.png", tr ("Step out"),
+     Qt::ShiftModifier + Qt::Key_F11);
+
+  _debug_continue = construct_debug_menu_item
+    (":/actions/icons/db_cont.png", tr ("Continue"), Qt::Key_F5);
+
+  _debug_menu->addSeparator ();
+#ifdef HAVE_QSCINTILLA
+  editor_window->debug_menu ()->addSeparator ();
+#endif
+
+  _debug_quit = construct_debug_menu_item
+    (":/actions/icons/db_stop.png", tr ("Exit Debug Mode"),
+     Qt::ShiftModifier + Qt::Key_F5);
+
+  connect (_debug_step_over, SIGNAL (triggered ()),
+           this, SLOT (debug_step_over ()));
+
+  connect (_debug_step_into, SIGNAL (triggered ()),
+           this, SLOT (debug_step_into ()));
+
+  connect (_debug_step_out, SIGNAL (triggered ()),
+           this, SLOT (debug_step_out ()));
+
+  connect (_debug_continue, SIGNAL (triggered ()),
+           this, SLOT (debug_continue ()));
+
+  connect (_debug_quit, SIGNAL (triggered ()),
+           this, SLOT (debug_quit ()));
+}
+
+QAction *
+main_window::construct_window_menu_item (QMenu *p, const QString& item,
+                                         bool checkable,
+                                         const QKeySequence& key)
+{
+  QAction *action = p->addAction (item);
+
+  action->setCheckable (checkable);
+  action->setShortcut (key);
+  action->setShortcutContext (Qt::ApplicationShortcut);
+
+  return action;
+}
+
+void
+main_window::construct_window_menu (QMenuBar *p)
+{
+  QMenu *window_menu = p->addMenu (tr ("&Window"));
+
+  QKeySequence ctrl = Qt::ControlModifier;
+  QKeySequence ctrl_shift = Qt::ControlModifier + Qt::ShiftModifier;
+
+  QAction *show_command_window_action = construct_window_menu_item
+    (window_menu, tr ("Show Command Window"), true, ctrl_shift + Qt::Key_0);
+
+  QAction *show_history_action = construct_window_menu_item
+    (window_menu, tr ("Show Command History"), true, ctrl_shift + Qt::Key_1);
+
+  QAction *show_file_browser_action =  construct_window_menu_item
+    (window_menu, tr ("Show File Browser"), true, ctrl_shift + Qt::Key_2);
+
+  QAction *show_workspace_action = construct_window_menu_item
+    (window_menu, tr ("Show Workspace"), true, ctrl_shift + Qt::Key_3);
+
+  QAction *show_editor_action = construct_window_menu_item
+    (window_menu, tr ("Show Editor"), true, ctrl_shift + Qt::Key_4);
+
+  QAction *show_documentation_action = construct_window_menu_item
+    (window_menu, tr ("Show Documentation"), true, ctrl_shift + Qt::Key_5);
+
+  window_menu->addSeparator ();
+
+  QAction *command_window_action = construct_window_menu_item
+    (window_menu, tr ("Command Window"), false, ctrl + Qt::Key_0);
+
+  QAction *history_action = construct_window_menu_item
+    (window_menu, tr ("Command History"), false, ctrl + Qt::Key_1);
+
+  QAction *file_browser_action = construct_window_menu_item
+    (window_menu, tr ("File Browser"), false, ctrl + Qt::Key_2);
+
+  QAction *workspace_action = construct_window_menu_item
+    (window_menu, tr ("Workspace"), false, ctrl + Qt::Key_3);
+
+  QAction *editor_action = construct_window_menu_item
+    (window_menu, tr ("Editor"), false, ctrl + Qt::Key_4);
+
+  QAction *documentation_action = construct_window_menu_item
+    (window_menu, tr ("Documentation"), false, ctrl + Qt::Key_5);
+
+  window_menu->addSeparator ();
+
+  QAction *reset_windows_action
+    = window_menu->addAction (tr ("Reset Default Window Layout"));
+
+  connect (show_command_window_action, SIGNAL (toggled (bool)),
+           command_window, SLOT (setVisible (bool)));
+
+  connect (command_window, SIGNAL (active_changed (bool)),
+           show_command_window_action, SLOT (setChecked (bool)));
+
+  connect (show_workspace_action, SIGNAL (toggled (bool)),
+           workspace_window, SLOT (setVisible (bool)));
+
+  connect (workspace_window, SIGNAL (active_changed (bool)),
+           show_workspace_action, SLOT (setChecked (bool)));
+
+  connect (show_history_action, SIGNAL (toggled (bool)),
+           history_window, SLOT (setVisible (bool)));
+
+  connect (history_window, SIGNAL (active_changed (bool)),
+           show_history_action, SLOT (setChecked (bool)));
+
+  connect (show_file_browser_action, SIGNAL (toggled (bool)),
+           file_browser_window, SLOT (setVisible (bool)));
+
+  connect (file_browser_window, SIGNAL (active_changed (bool)),
+           show_file_browser_action, SLOT (setChecked (bool)));
+
+#ifdef HAVE_QSCINTILLA
+  connect (show_editor_action, SIGNAL (toggled (bool)),
+           editor_window, SLOT (setVisible (bool)));
+
+  connect (editor_window, SIGNAL (active_changed (bool)),
+           show_editor_action, SLOT (setChecked (bool)));
+#endif
+
+  connect (show_documentation_action, SIGNAL (toggled (bool)),
+           doc_browser_window, SLOT (setVisible (bool)));
+
+  connect (doc_browser_window, SIGNAL (active_changed (bool)),
+           show_documentation_action, SLOT (setChecked (bool)));
+
+  connect (command_window_action, SIGNAL (triggered ()),
+           command_window, SLOT (focus ()));
+
+  connect (workspace_action, SIGNAL (triggered ()),
+           workspace_window, SLOT (focus ()));
+
+  connect (history_action, SIGNAL (triggered ()),
+           history_window, SLOT (focus ()));
+
+  connect (file_browser_action, SIGNAL (triggered ()),
+           file_browser_window, SLOT (focus ()));
+
+  connect (editor_action, SIGNAL (triggered ()),
+           editor_window, SLOT (focus ()));
+
+  connect (documentation_action, SIGNAL (triggered ()),
+           doc_browser_window, SLOT (focus ()));
+
+  connect (reset_windows_action, SIGNAL (triggered ()),
+           this, SLOT (reset_windows ()));
+}
+
+void
+main_window::construct_help_menu (QMenuBar *p)
+{
+  QMenu *help_menu = p->addMenu (tr ("&Help"));
+
+  construct_documentation_menu (help_menu);
+
+  help_menu->addSeparator ();
+
+  QAction *report_bug_action
+    = help_menu->addAction (tr ("Report Bug"));
+
+  QAction *octave_forge_action
+    = help_menu->addAction (tr ("Visit Octave Forge"));
+
+  QAction *agora_action
+    = help_menu->addAction (tr ("Visit Agora"));
+
+  help_menu->addSeparator ();
+
+  QAction *about_octave_action
+    = help_menu->addAction (tr ("About Octave"));
+
+  connect (report_bug_action, SIGNAL (triggered ()),
+           this, SLOT (open_bug_tracker_page ()));
+
+  connect (octave_forge_action, SIGNAL (triggered ()),
+           this, SLOT (open_octave_forge_page ()));
+
+  connect (agora_action, SIGNAL (triggered ()),
+           this, SLOT (open_agora_page ()));
+
+  connect (about_octave_action, SIGNAL (triggered ()),
+           this, SLOT (show_about_octave ()));
+}
+
+void
+main_window::construct_documentation_menu (QMenu *p)
+{
+  QMenu *documentation_menu = p->addMenu (tr ("Documentation"));
+
+  QAction *ondisk_documentation_action
+    = documentation_menu->addAction (tr ("On Disk"));
+
+  QAction *online_documentation_action
+    = documentation_menu->addAction (tr ("Online"));
+
+  connect (ondisk_documentation_action, SIGNAL (triggered ()),
+           doc_browser_window, SLOT (focus ()));
+
+  connect (online_documentation_action, SIGNAL (triggered ()),
+           this, SLOT (open_online_documentation_page ()));
+}
+
+void
+main_window::construct_tool_bar (void)
+{
+  _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 ();
+
+  _main_tool_bar->addAction (_cut_action);
+  _main_tool_bar->addAction (_copy_action);
+  _main_tool_bar->addAction (_paste_action);
+  _main_tool_bar->addAction (_undo_action);
+
+  _main_tool_bar->addSeparator ();
+
+  _current_directory_combo_box = new QComboBox (this);
+  _current_directory_combo_box->setFixedWidth (current_directory_width);
+  _current_directory_combo_box->setEditable (true);
+  _current_directory_combo_box->setInsertPolicy(QComboBox::NoInsert);
+  _current_directory_combo_box->setToolTip (tr ("Enter directory name"));
+  _current_directory_combo_box->setMaxVisibleItems (current_directory_max_visible);
+  _current_directory_combo_box->setMaxCount (current_directory_max_count);
+  QSizePolicy sizePol(QSizePolicy::Expanding, QSizePolicy::Preferred);
+  _current_directory_combo_box->setSizePolicy(sizePol);
+
+  // 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);
+  QAction *current_dir_up = _main_tool_bar->addAction (
+                                          QIcon (":/actions/icons/up.png"),
+                                          tr ("One directory up"));
+  QAction *current_dir_search = _main_tool_bar->addAction (
+                                          QIcon (":/actions/icons/search.png"),
+                                          tr ("Browse directories"));
+
+  connect (_current_directory_combo_box, SIGNAL (activated (QString)),
+           this, SLOT (set_current_working_directory (QString)));
+
+  connect (_current_directory_combo_box->lineEdit(), SIGNAL (returnPressed ()),
+            this, SLOT (accept_directory_line_edit ()));
+
+  connect (current_dir_search, SIGNAL (triggered ()),
+           this, SLOT (browse_for_directory ()));
+
+  connect (current_dir_up, SIGNAL (triggered ()),
+           this, SLOT (change_directory_up ()));
+
+  connect (_undo_action, SIGNAL (triggered ()),
+           this, SLOT (handle_undo_request ()));
+}
+
+void
+main_window::save_workspace_callback (const std::string& file)
+{
+  Fsave (ovl (file));
+}
+
+void
+main_window::load_workspace_callback (const std::string& file)
+{
+  Fload (ovl (file));
+
+  octave_link::set_workspace (true, symbol_table::workspace_info ());
+}
+
+void
+main_window::clear_workspace_callback (void)
+{
+  Fclear ();
+}
+
+void
+main_window::rename_variable_callback (const main_window::name_pair& names)
+{
+  /* bool status = */ symbol_table::rename (names.first, names.second);
+
+  // if (status)
+    octave_link::set_workspace (true, symbol_table::workspace_info ());
+
+  //  else
+  //    ; // we need an octave_link action that runs a GUI error option.
+}
+
+void
+main_window::command_window_undo_callback (void)
+{
+  command_editor::undo ();
+  command_editor::redisplay ();
+}
+
+void
+main_window::clear_command_window_callback (void)
+{
+  Fclc ();
+  command_editor::interrupt (true);
+}
+
+void
+main_window::resize_command_window_callback (void)
+{
+  command_editor::resize_terminal ();
+}
+
+void
+main_window::clear_history_callback (void)
+{
+  Fhistory (ovl ("-c"));
+}
+
+void
+main_window::execute_command_callback (const std::string& command)
+{
+  std::string pending_input = command_editor::get_current_line ();
+
+  command_editor::set_initial_input (pending_input);
+
+  command_editor::replace_line (command);
+  command_editor::redisplay ();
+
+  // We are executing inside the command editor event loop.  Force
+  // the current line to be returned for processing.
+  command_editor::interrupt ();
+}
+
+void
+main_window::new_figure_callback (void)
+{
+  Fbuiltin (ovl ("figure"));
+  Fdrawnow ();
+}
+
+void
+main_window::change_directory_callback (const std::string& directory)
+{
+  Fcd (ovl (directory));
+}
+
+void
+main_window::debug_continue_callback (void)
+{
+  Fdbcont ();
+
+  command_editor::interrupt (true);
+}
+
+// The next three callbacks are invoked by GUI buttons.  Those buttons
+// should only be active when we are doing debugging, which means that
+// Octave is waiting for input in get_debug_input.  Calling
+// command_editor::interrupt will force readline to return even if it
+// has not read any input, and then get_debug_input will return,
+// allowing the evaluator to continue and execute the next statement.
+
+void
+main_window::debug_step_into_callback (void)
+{
+  Fdbstep (ovl ("in"));
+
+  command_editor::interrupt (true);
+}
+
+void
+main_window::debug_step_over_callback (void)
+{
+  Fdbstep ();
+
+  command_editor::interrupt (true);
+}
+
+void
+main_window::debug_step_out_callback (void)
+{
+  Fdbstep (ovl ("out"));
+
+  command_editor::interrupt (true);
+}
+
+void
+main_window::debug_quit_callback (void)
+{
+  Fdbquit ();
+
+  command_editor::interrupt (true);
+}
+
+void
+main_window::exit_callback (void)
+{
+  Fquit ();
+}
+
+void
+main_window::find_files(const QString &start_dir)
+{
+
+  if (! find_files_dlg)
+    {
+      find_files_dlg = new find_files_dialog (this);
+
+      connect (find_files_dlg, SIGNAL (finished (int)),
+               this, SLOT (find_files_finished (int)));
+
+      connect (find_files_dlg, SIGNAL (dir_selected(const QString &)),
+               file_browser_window, SLOT(set_current_directory(const QString&)));
+
+      connect (find_files_dlg, SIGNAL (file_selected(const QString &)),
+               this, SLOT(open_file(const QString &)));
+
+      find_files_dlg->setWindowModality (Qt::NonModal);
+    }
+
+  if (! find_files_dlg->isVisible ())
+    {
+      find_files_dlg->show ();
+    }
+
+  find_files_dlg->set_search_dir(start_dir);
+
+  find_files_dlg->activateWindow ();
+
+}
+
+void 
+main_window::find_files_finished(int)
+{
+
+}
+
new file mode 100644
--- /dev/null
+++ b/libgui/src/main-window.h
@@ -0,0 +1,282 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 (main_window_h)
+#define main_window_h 1
+
+// Qt includes
+#include <QtGui/QMainWindow>
+#include <QThread>
+#include <QTabWidget>
+#include <QMdiArea>
+#include <QStatusBar>
+#include <QToolBar>
+#include <QQueue>
+#include <QMdiSubWindow>
+#include <QCloseEvent>
+#include <QToolButton>
+#include <QComboBox>
+
+// Editor includes
+#include "file-editor-interface.h"
+
+// QTerminal includes
+#include "QTerminal.h"
+
+// Own includes
+#include "dialog.h"
+#include "resource-manager.h"
+#include "workspace-model.h"
+#include "workspace-view.h"
+#include "history-dock-widget.h"
+#include "files-dock-widget.h"
+#include "terminal-dock-widget.h"
+#include "documentation-dock-widget.h"
+#include "octave-qt-link.h"
+#include "find-files-dialog.h"
+
+/**
+ * \class MainWindow
+ *
+ * Represents the main window.
+ */
+class main_window : public QMainWindow
+{
+  Q_OBJECT
+
+public:
+
+  typedef std::pair <std::string, std::string> name_pair;
+
+  main_window (QWidget *parent = 0);
+
+  ~main_window (void);
+
+  bool command_window_has_focus (void) const;
+
+  void focus_command_window (void);
+
+signals:
+  void settings_changed (const QSettings *);
+  void new_file_signal (const QString&);
+  void open_file_signal (const QString&);
+
+  void insert_debugger_pointer_signal (const QString& file, int line);
+  void delete_debugger_pointer_signal (const QString& file, int line);
+  void update_breakpoint_marker_signal (bool insert, const QString& file,
+                                        int line);
+
+public slots:
+  void report_status_message (const QString& statusMessage);
+  void handle_save_workspace_request (void);
+  void handle_load_workspace_request (const QString& file = QString ());
+  void handle_clear_command_window_request (void);
+  void handle_clear_workspace_request (void);
+  void handle_clear_history_request (void);
+  void handle_rename_variable_request (const QString& old_name,
+                                       const QString& new_name);
+  void handle_undo_request (void);
+  void new_file (const QString& commands = QString ());
+  void open_file (const QString& file_name = QString ());
+  void open_online_documentation_page (void);
+  void open_bug_tracker_page (void);
+  void open_octave_forge_page (void);
+  void open_agora_page (void);
+  void process_settings_dialog_request (void);
+  void show_about_octave (void);
+  void notice_settings (const QSettings *settings);
+  void prepare_to_exit (void);
+  void exit (int status);
+  void reset_windows (void);
+
+  void change_directory (const QString& dir);
+  void browse_for_directory (void);
+  void set_current_working_directory (const QString& dir);
+  void change_directory_up (void);
+  void accept_directory_line_edit (void);
+
+  void execute_command_in_terminal(const QString& dir);
+
+  void handle_new_figure_request (void);
+
+  void handle_new_variable_request (void);
+
+  void handle_enter_debugger (void);
+  void handle_exit_debugger (void);
+  void debug_continue (void);
+  void debug_step_into (void);
+  void debug_step_over (void);
+  void debug_step_out (void);
+  void debug_quit (void);
+
+  void handle_insert_debugger_pointer_request (const QString& file, int line);
+  void handle_delete_debugger_pointer_request (const QString& file, int line);
+  void handle_update_breakpoint_marker_request (bool insert,
+                                                const QString& file, int line);
+
+  void read_settings (void);
+  void set_window_layout (QSettings *settings);
+  void write_settings (void);
+  void connect_visibility_changed (void);
+
+  void connect_uiwidget_links ();
+
+  void handle_create_dialog (const QString& message, const QString& title,
+                             const QString& icon, const QStringList& button,
+                             const QString& defbutton,
+                             const QStringList& role);
+
+  void handle_create_listview (const QStringList& list, const QString& mode,
+                               int width, int height,
+                               const QIntList& initial,
+                               const QString& name,
+                               const QStringList& prompt,
+                               const QString& ok_string,
+                               const QString& cancel_string);
+
+  void handle_create_inputlayout (const QStringList&, const QString&,
+                                  const QFloatList&, const QFloatList&,
+                                  const QStringList&);
+
+  void handle_create_filedialog (const QStringList &filters, 
+                                 const QString& title, const QString& filename, 
+                                 const QString &dirname,
+                                 const QString& multimode);
+
+  // find files dialog 
+  void find_files(const QString &startdir=QDir::currentPath());
+  void find_files_finished(int);
+protected:
+  void closeEvent (QCloseEvent * closeEvent);
+
+private:
+
+  void construct (void);
+
+  void construct_octave_qt_link (void);
+
+  void construct_menu_bar (void);
+  void construct_file_menu (QMenuBar *p);
+  void construct_new_menu (QMenu *p);
+  void construct_edit_menu (QMenuBar *p);
+  void construct_debug_menu_item (QMenu *p, const QString& item,
+                                  const QKeySequence& key);
+  QAction *construct_debug_menu_item (const char *icon_file,
+                                      const QString& item,
+                                      const QKeySequence& key);
+  void construct_debug_menu (QMenuBar *p);
+  QAction *construct_window_menu_item (QMenu *p, const QString& item,
+                                       bool checkable,
+                                       const QKeySequence& key);
+  void construct_window_menu (QMenuBar *p);
+  void construct_help_menu (QMenuBar *p);
+  void construct_documentation_menu (QMenu *p);
+
+  void construct_tool_bar (void);
+
+  void establish_octave_link (void);
+
+  void save_workspace_callback (const std::string& file);
+
+  void load_workspace_callback (const std::string& file);
+
+  void rename_variable_callback (const name_pair& names);
+
+  void command_window_undo_callback (void);
+
+  void clear_command_window_callback (void);
+
+  void resize_command_window_callback (void);
+
+  void clear_workspace_callback (void);
+
+  void clear_history_callback (void);
+
+  void execute_command_callback (const std::string& command);
+
+  void new_figure_callback (void);
+
+  void change_directory_callback (const std::string& directory);
+
+  void debug_continue_callback (void);
+
+  void debug_step_into_callback (void);
+
+  void debug_step_over_callback (void);
+
+  void debug_step_out_callback (void);
+
+  void debug_quit_callback (void);
+
+  void exit_callback (void);
+
+  // Data models.
+  workspace_model *_workspace_model;
+
+  // Toolbars.
+  QStatusBar *status_bar;
+
+  // Subwindows.
+  terminal_dock_widget *command_window;
+  history_dock_widget *history_window;
+  files_dock_widget *file_browser_window;
+  documentation_dock_widget *doc_browser_window;
+  file_editor_interface *editor_window;
+  workspace_view *workspace_window;
+
+  QToolBar *_main_tool_bar;
+  QMenu *_debug_menu;
+
+  QAction *_debug_continue;
+  QAction *_debug_step_into;
+  QAction *_debug_step_over;
+  QAction *_debug_step_out;
+  QAction *_debug_quit;
+
+  QAction *_new_script_action;
+  QAction *_open_action;
+
+  QAction *_cut_action;
+  QAction *_copy_action;
+  QAction *_paste_action;
+  QAction *_undo_action;
+
+  // Toolbars.
+  QComboBox *_current_directory_combo_box;
+  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;
+
+  // Find files dialog
+  find_files_dialog * find_files_dlg;
+
+  octave_main_thread *_octave_main_thread;
+
+  octave_qt_link *_octave_qt_link;
+
+  // Flag for closing whole application.
+  bool _closing;
+};
+
+#endif // MAINWINDOW_H
new file mode 100644
--- /dev/null
+++ b/libgui/src/module.mk
@@ -0,0 +1,187 @@
+EXTRA_DIST += \
+  src/module.mk \
+  src/resource.qrc \
+  $(octave_gui_UI) \
+  $(octave_gui_ICONS)
+
+octave_gui_ICONS = \
+  src/icons/arrow_right.png \
+  src/icons/artsbuilderexecute.png \
+  src/icons/bookmark.png \
+  src/icons/bp_next.png \
+  src/icons/bp_prev.png \
+  src/icons/bp_rm_all.png \
+  src/icons/bp_toggle.png \
+  src/icons/chat.png \
+  src/icons/configure.png \
+  src/icons/db_cont.png \
+  src/icons/db_step_in.png \
+  src/icons/db_step_out.png \
+  src/icons/db_step.png \
+  src/icons/db_stop.png \
+  src/icons/editcopy.png \
+  src/icons/editcut.png \
+  src/icons/editdelete.png \
+  src/icons/editpaste.png \
+  src/icons/filenew.png \
+  src/icons/fileopen.png \
+  src/icons/fileprint.png \
+  src/icons/filesaveas.png \
+  src/icons/filesave.png \
+  src/icons/find.png \
+  src/icons/gear.png \
+  src/icons/folder_new.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/ok.png \
+  src/icons/question.png \
+  src/icons/redled.png \
+  src/icons/redo.png \
+  src/icons/reload.png \
+  src/icons/search.png \
+  src/icons/star.png \
+  src/icons/stop.png \
+  src/icons/terminal.png \
+  src/icons/undo.png \
+  src/icons/up.png \
+  src/icons/zoom-in.png \
+  src/icons/zoom-out.png
+
+octave_gui_MOC =
+
+if AMCOND_HAVE_QSCINTILLA
+octave_gui_MOC += \
+  src/m-editor/moc-file-editor-interface.cc \
+  src/m-editor/moc-file-editor-tab.cc \
+  src/m-editor/moc-file-editor.cc \
+  src/m-editor/moc-find-dialog.cc \
+  src/m-editor/moc-lexer-octave-gui.cc
+endif
+
+octave_gui_MOC += \
+  src/moc-dialog.cc \
+  src/moc-documentation-dock-widget.cc \
+  src/moc-files-dock-widget.cc \
+  src/moc-history-dock-widget.cc \
+  src/moc-main-window.cc \
+  src/moc-octave-qt-link.cc \
+  src/moc-settings-dialog.cc \
+  src/moc-terminal-dock-widget.cc \
+  src/moc-color-picker.cc \
+  src/moc-welcome-wizard.cc \
+  src/moc-workspace-model.cc \
+  src/moc-workspace-view.cc \
+  src/moc-find-files-dialog.cc \
+  src/qtinfo/moc-parser.cc \
+  src/qtinfo/moc-webinfo.cc \
+  src/moc-octave-dock-widget.cc
+
+octave_gui_RC = src/qrc-resource.cc
+
+octave_gui_UI = \
+  src/settings-dialog.ui \
+  src/welcome-wizard.ui
+
+octave_gui_UI_H = $(patsubst src/%.ui, src/ui-%.h, $(octave_gui_UI))
+
+BUILT_SOURCES += $(octave_gui_UI_H)
+
+noinst_HEADERS += \
+  src/dialog.h \
+  src/octave-dock-widget.h \
+  src/documentation-dock-widget.h \
+  src/files-dock-widget.h \
+  src/history-dock-widget.h \
+  src/m-editor/file-editor-interface.h \
+  src/m-editor/file-editor-tab.h \
+  src/m-editor/file-editor.h \
+  src/m-editor/find-dialog.h \
+  src/m-editor/lexer-octave-gui.h \
+  src/main-window.h \
+  src/octave-gui.h \
+  src/octave-main-thread.h \
+  src/octave-qt-link.h \
+  src/qtinfo/parser.h \
+  src/qtinfo/webinfo.h \
+  src/resource-manager.h \
+  src/settings-dialog.h \
+  src/terminal-dock-widget.h \
+  src/color-picker.h \
+  src/welcome-wizard.h \
+  src/find-files-dialog.h \
+  src/find-files-model.h \
+  src/workspace-model.h \
+  src/workspace-view.h
+
+src_libgui_src_la_SOURCES = \
+  src/dialog.cc \
+  src/documentation-dock-widget.cc \
+  src/files-dock-widget.cc \
+  src/history-dock-widget.cc \
+  src/m-editor/file-editor-tab.cc \
+  src/m-editor/file-editor.cc \
+  src/m-editor/find-dialog.cc \
+  src/m-editor/lexer-octave-gui.cc \
+  src/main-window.cc \
+  src/octave-gui.cc \
+  src/octave-main-thread.cc \
+  src/octave-qt-link.cc \
+  src/qtinfo/parser.cc \
+  src/qtinfo/webinfo.cc \
+  src/resource-manager.cc \
+  src/settings-dialog.cc \
+  src/terminal-dock-widget.cc \
+  src/color-picker.cc \
+  src/welcome-wizard.cc \
+  src/find-files-dialog.cc \
+  src/find-files-model.cc \
+  src/workspace-model.cc \
+  src/workspace-view.cc
+
+nodist_src_libgui_src_la_SOURCES = $(octave_gui_MOC) $(octave_gui_RC)
+
+src_libgui_src_la_CPPFLAGS = \
+  $(AM_CPPFLAGS) \
+  @OCTGUI_DLL_DEFS@ \
+  @QT_CPPFLAGS@ \
+  -I$(srcdir)/qterminal/libqterminal \
+  -Isrc -I$(srcdir)/src \
+  -I$(srcdir)/src/m-editor \
+  -I$(srcdir)/src/qtinfo \
+  -I$(top_srcdir)/liboctave/cruft/misc \
+  -I$(top_srcdir)/liboctave/array \
+  -I$(top_builddir)/liboctave/numeric -I$(top_srcdir)/liboctave/numeric \
+  -I$(top_builddir)/liboctave/operators -I$(top_srcdir)/liboctave/operators \
+  -I$(top_srcdir)/liboctave/system \
+  -I$(top_srcdir)/liboctave/util \
+  -I$(top_builddir)/libinterp -I$(top_srcdir)/libinterp \
+  -I$(top_builddir)/libinterp/parse-tree -I$(top_srcdir)/libinterp/parse-tree \
+  -I$(top_builddir)/libinterp/interp-core -I$(top_srcdir)/libinterp/interp-core \
+  -I$(top_builddir)/libinterp/interpfcn -I$(top_srcdir)/libinterp/interpfcn \
+  -I$(top_srcdir)/libinterp/octave-value
+
+src_libgui_src_la_CFLAGS = $(AM_CFLAGS) $(WARN_CFLAGS)
+
+src_libgui_src_la_CXXFLAGS = $(AM_CXXFLAGS) $(WARN_CXXFLAGS)
+
+noinst_LTLIBRARIES += src/libgui-src.la
+
+CLEANFILES += \
+  $(octave_gui_MOC) \
+  $(octave_gui_UI_H) \
+  $(octave_gui_RC)
+
new file mode 100644
--- /dev/null
+++ b/libgui/src/octave-dock-widget.h
@@ -0,0 +1,107 @@
+/*
+
+Copyright (C) 2012-2013 Richard Crozier
+
+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_dock_widget_h)
+#define octave_dock_widget_h 1
+
+#include <QDockWidget>
+
+class octave_dock_widget : public QDockWidget
+{
+  Q_OBJECT
+
+public:
+
+  octave_dock_widget (QWidget *p)
+    : QDockWidget (p)
+  {
+    connect (this, SIGNAL (visibilityChanged (bool)),
+             this, SLOT (handle_visibility_changed (bool)));
+
+    connect (this, SIGNAL (topLevelChanged (bool)),
+             this, SLOT (top_level_changed (bool)));
+  }
+
+  virtual ~octave_dock_widget () { }
+
+  virtual void connect_visibility_changed (void)
+  {
+    connect (this, SIGNAL (visibilityChanged (bool)),
+             this, SLOT (handle_visibility (bool)));
+  }
+
+signals:
+
+  /** Custom signal that tells whether a user has clicked away
+   *  that dock widget, i.e the active dock widget has
+   *  changed. */
+  void active_changed (bool active);
+
+protected:
+
+  virtual void closeEvent (QCloseEvent *e)
+  {
+    emit active_changed (false);
+    QDockWidget::closeEvent (e);
+  }
+
+public slots:
+
+  virtual void focus (void)
+  {
+    if (! isVisible ())
+      setVisible (true);
+
+    setFocus ();
+    activateWindow ();
+    raise ();
+  }
+
+  virtual void handle_visibility (bool visible)
+  {
+    if (visible && ! isFloating ())
+      focus ();
+  }
+
+protected slots:
+
+  /** Slot to steer changing visibility from outside. */
+  virtual void handle_visibility_changed (bool visible)
+  {
+    if (visible)
+      emit active_changed (true);
+  }
+
+  /** Slot when floating property changes */
+  virtual void top_level_changed (bool floating)
+  {
+    if (floating)
+      {
+        // Make a window from the widget when floating and make it
+        // visible again since setWindowFlags hides it.
+        setWindowFlags (Qt::Window);
+        show();
+      }
+  }
+};
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libgui/src/octave-gui.cc
@@ -0,0 +1,140 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 <QtGui/QApplication>
+#include <QTranslator>
+
+#include <iostream>
+
+#include <fcntl.h>
+
+#if defined (HAVE_SYS_IOCTL_H)
+#include <sys/ioctl.h>
+#endif
+
+#include "lo-utils.h"
+#include "oct-env.h"
+#include "syswait.h"
+
+#include "welcome-wizard.h"
+#include "resource-manager.h"
+#include "main-window.h"
+#include "octave-gui.h"
+
+// Dissociate from the controlling terminal, if any.
+
+static void
+dissociate_terminal (void)
+{
+#if ! defined (__WIN32__) || defined (__CYGWIN__)
+# if defined (HAVE_SYS_IOCTL_H) && defined (TIOCNOTTY)
+
+  ioctl (0, TIOCNOTTY);
+
+# else
+ 
+  pid_t pid = fork ();
+
+  if (pid < 0)
+    {
+      std::cerr << "fork failed!" << std::endl;;
+      exit (1);
+    }
+  else if (pid == 0)
+    {
+      // Child.
+
+      if (setsid () < 0)
+        {
+          std::cerr << "setsid error" << std::endl;
+          exit (1);
+        }
+    }
+  else
+    {
+      // Parent
+
+      int status;
+
+      waitpid (pid, &status, 0);
+
+      exit (octave_wait::ifexited (status)
+            ? octave_wait::exitstatus (status) : 127);
+    }
+
+# endif
+#endif
+}
+
+int
+octave_start_gui (int argc, char *argv[])
+{
+  dissociate_terminal ();
+
+  QApplication application (argc, argv);
+
+  while (true)
+    {
+      if (resource_manager::is_first_run ())
+        {
+          welcome_wizard welcomeWizard;
+          welcomeWizard.exec ();
+          resource_manager::reload_settings ();
+        }
+      else
+        {
+          // install translators for the gui and qt text
+          QTranslator gui_translator, qt_translator;
+          resource_manager::config_translators (&gui_translator,&qt_translator);
+          application.installTranslator (&qt_translator);
+          application.installTranslator (&gui_translator);
+
+          // update network-settings
+          resource_manager::update_network_settings ();
+
+#if ! defined (__WIN32__) || defined (__CYGWIN__)
+          // If we were started from a launcher, TERM might not be
+          // defined, but we provide a terminal with xterm
+          // capabilities.
+
+          std::string term = octave_env::getenv ("TERM");
+
+          if (term.empty ())
+            octave_env::putenv ("TERM", "xterm");
+#endif
+
+          // create main window, read settings, and show window
+          main_window w;
+          w.read_settings ();  // get widget settings after construction
+                               // but before showing
+          w.show ();
+          w.focus_command_window ();
+          w.connect_visibility_changed (); // connect signals for changes in
+                                           // visibility not before w is shown
+          return application.exec ();
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/libgui/src/octave-gui.h
@@ -0,0 +1,28 @@
+/*
+
+Copyright (C) 2012 John W. Eaton
+
+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_octave_gui_h)
+#define octave_octave_gui_h 1
+
+extern OCTGUI_API int octave_start_gui (int argc, char **argv);
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libgui/src/octave-main-thread.cc
@@ -0,0 +1,55 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 <clocale>
+#include <string>
+
+#include "builtin-defun-decls.h"
+#include "octave.h"
+#include "ov-builtin.h"
+#include "ov-fcn-handle.h"
+
+#include "octave-main-thread.h"
+#include "octave-link.h"
+
+void
+octave_main_thread::run (void)
+{
+  // Matlab uses "C" locale for LC_NUMERIC class regardless of local setting
+  setlocale (LC_NUMERIC, "C");
+
+  octave_initialize_interpreter (octave_cmdline_argc, octave_cmdline_argv,
+                                 octave_embedded);
+
+  octave_execute_interpreter ();
+}
+
+void
+octave_main_thread::execute_interpreter (void)
+{
+  start ();
+}
new file mode 100644
--- /dev/null
+++ b/libgui/src/octave-main-thread.h
@@ -0,0 +1,49 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2011-2012 Jacob Dawid
+
+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/>.
+
+*/
+
+#ifndef OCTAVEMAINTHREAD_H
+#define OCTAVEMAINTHREAD_H
+
+#include <QThread>
+
+/**
+  * \class octave_main
+  * \brief This class represents a thread just running octave_main.
+  * \author Jacob Dawid
+  */
+class octave_main_thread : public QThread
+{
+public:
+  // Create a new thread for running the octave interpreter.
+  octave_main_thread (void) : QThread () { }
+
+  // Start the thread and initialize and execute the octave
+  // interpreter.
+  void execute_interpreter (void);
+
+protected:
+  // Avoid exec.  Run the octave interpreter in the new thread.
+  void run (void);
+};
+
+#endif // OCTAVEMAINTHREAD_H
new file mode 100644
--- /dev/null
+++ b/libgui/src/octave-qt-link.cc
@@ -0,0 +1,425 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2011-2012 Jacob Dawid
+Copyright (C) 2011-2012 John P. Swensen
+
+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 <QStringList>
+
+#include "str-vec.h"
+
+#include "dialog.h"
+#include "error.h"
+#include "workspace-element.h"
+
+#include "octave-qt-link.h"
+
+octave_qt_link::octave_qt_link (octave_main_thread *mt)
+  : octave_link (), main_thread (mt)
+{ }
+
+octave_qt_link::~octave_qt_link (void) { }
+
+void
+octave_qt_link::execute_interpreter (void)
+{
+  main_thread->execute_interpreter ();
+}
+
+bool
+octave_qt_link::do_exit (int status)
+{
+  emit exit_signal (status);
+
+  return true;
+}
+
+bool
+octave_qt_link::do_edit_file (const std::string& file)
+{
+  emit edit_file_signal (QString::fromStdString (file));
+
+  return true;
+}
+
+int
+octave_qt_link::do_message_dialog (const std::string& dlg,
+                                   const std::string& msg,
+                                   const std::string& title)
+{
+  uiwidget_creator.signal_dialog (QString::fromStdString (msg),
+                                  QString::fromStdString (title),
+                                  QString::fromStdString (dlg),
+                                  QStringList (), QString (),
+                                  QStringList ());
+
+  // Wait while the user is responding to message box.
+  uiwidget_creator.wait ();
+
+  // The GUI has sent a signal and the process has been awakened.
+  return uiwidget_creator.get_dialog_result ();
+}
+
+std::string
+octave_qt_link::do_question_dialog (const std::string& msg,
+                                    const std::string& title,
+                                    const std::string& btn1,
+                                    const std::string& btn2,
+                                    const std::string& btn3,
+                                    const std::string& btndef)
+{
+  QStringList btn;
+  QStringList role;
+  role << "AcceptRole" << "AcceptRole" << "AcceptRole";
+  btn << QString::fromStdString (btn1);
+  if (btn2 == "")
+    role.removeAt (0);
+  else
+    btn << QString::fromStdString (btn2);
+  btn << QString::fromStdString (btn3);
+
+  uiwidget_creator.signal_dialog (QString::fromStdString (msg),
+                                  QString::fromStdString (title),
+                                  "quest",
+                                  btn,
+                                  QString::fromStdString (btndef),
+                                  role);
+
+  // Wait while the user is responding to message box.
+  uiwidget_creator.wait ();
+
+  // The GUI has sent a signal and the process has been awakened.
+  return uiwidget_creator.get_dialog_button().toStdString ();
+}
+
+static QStringList
+make_qstring_list (const std::list<std::string>& lst)
+{
+  QStringList retval;
+
+  for (std::list<std::string>::const_iterator it = lst.begin ();
+       it != lst.end (); it++)
+    {
+      retval.append (QString::fromStdString (*it));
+    }
+
+  return retval;
+}
+
+static QStringList
+make_filter_list (const octave_link::filter_list& lst)
+{
+  QStringList retval;
+
+  // We have pairs of data, first being the list of extensions
+  // exta;exb;extc etc second the name to use as filter name
+  // (optional).  Qt wants a a list of filters in the format of
+  // 'FilterName (space separated exts)'.
+
+  for (octave_link::filter_list::const_iterator it = lst.begin ();
+       it != lst.end (); it++)
+    {
+      QString ext = QString::fromStdString (it->first);
+      QString name = QString::fromStdString (it->second);
+
+      // Strip out extensions from name and replace ';' with spaces in
+      // list.
+
+      name.replace (QRegExp ("\\(.*\\)"), "");
+      ext.replace (";", " ");
+
+      if (name.length() == 0)
+        {
+          // No name field.  Build one from the extensions.
+          name = ext.toUpper() + " Files";
+        }
+
+      retval.append (name + " (" + ext + ")");
+    }
+
+  return retval;
+}
+
+std::pair<std::list<int>, int>
+octave_qt_link::do_list_dialog (const std::list<std::string>& list,
+                                const std::string& mode,
+                                int width, int height,
+                                const std::list<int>& initial,
+                                const std::string& name,
+                                const std::list<std::string>& prompt,
+                                const std::string& ok_string,
+                                const std::string& cancel_string)
+{
+  uiwidget_creator.signal_listview (make_qstring_list (list),
+                                    QString::fromStdString (mode),
+                                    width, height,
+                                    QList<int>::fromStdList (initial),
+                                    QString::fromStdString (name),
+                                    make_qstring_list (prompt),
+                                    QString::fromStdString (ok_string),
+                                    QString::fromStdString (cancel_string));
+
+  // Wait while the user is responding to message box.
+  uiwidget_creator.wait ();
+
+  // The GUI has sent a signal and the process has been awakened.
+  const QIntList *selected = uiwidget_creator.get_list_index ();
+  int ok = uiwidget_creator.get_dialog_result ();
+
+  return std::pair<std::list<int>, int> (selected->toStdList (), ok);
+}
+
+std::list<std::string>
+octave_qt_link::do_input_dialog (const std::list<std::string>& prompt,
+                                 const std::string& title,
+                                 const std::list<float>& nr,
+                                 const std::list<float>& nc,
+                                 const std::list<std::string>& defaults)
+{
+  std::list<std::string> retval;
+
+  uiwidget_creator.signal_inputlayout (make_qstring_list (prompt),
+                                       QString::fromStdString (title),
+                                       QFloatList::fromStdList (nr),
+                                       QFloatList::fromStdList (nc),
+                                       make_qstring_list (defaults));
+
+  // Wait while the user is responding to message box.
+  uiwidget_creator.wait ();
+
+  // The GUI has sent a signal and the process has been awakened.
+  const QStringList *inputLine = uiwidget_creator.get_string_list ();
+
+  for (QStringList::const_iterator it = inputLine->begin ();
+       it != inputLine->end (); it++)
+    {
+      retval.push_back (it->toStdString ());
+    }
+
+  return retval;
+}
+
+std::list<std::string>
+octave_qt_link::do_file_dialog (const filter_list& filter,
+                                const std::string& title,
+                                const std::string& filename,
+                                const std::string& dirname,
+                                const std::string& multimode)
+{
+  std::list<std::string> retval;
+
+  uiwidget_creator.signal_filedialog (make_filter_list (filter),
+                                      QString::fromStdString (title),
+                                      QString::fromStdString (filename),
+                                      QString::fromStdString (dirname),
+                                      QString::fromStdString (multimode));
+
+  // Wait while the user is responding to dialog.
+  uiwidget_creator.wait ();
+
+  // Add all the file dialog results to a string list.
+  const QStringList *inputLine = uiwidget_creator.get_string_list ();
+
+  for (QStringList::const_iterator it = inputLine->begin ();
+       it != inputLine->end (); it++)
+    retval.push_back (it->toStdString ());
+
+  retval.push_back (uiwidget_creator.get_dialog_path ()->toStdString ());
+  retval.push_back ((QString ("%1").arg (uiwidget_creator.get_dialog_result ())).toStdString ());
+
+  return retval;
+}
+
+int
+octave_qt_link::do_debug_cd_or_addpath_error (const std::string& file,
+                                              const std::string& dir,
+                                              bool addpath_option)
+{
+  int retval = -1;
+
+  QString qdir = QString::fromStdString (dir);
+  QString qfile = QString::fromStdString (file);
+
+  QString msg
+    = (addpath_option
+       ? tr ("The file %1 does not exist in the load path.  To debug the function you are editing, you must either change to the directory %2 or add that directory to the load path.").arg(qfile).arg(qdir)
+       : tr ("The file %1 is shadowed by a file with the same name in the load path.  To debug the function you are editing, change to the directory %2.").arg(qfile).arg(qdir));
+
+  QString title = tr ("Change Directory or Add Directory to Load Path");
+
+  QString cd_txt = tr ("Change Directory");
+  QString addpath_txt = tr ("Add Directory to Load Path");
+  QString cancel_txt = tr ("Cancel");
+
+  QStringList btn;
+  QStringList role;
+  btn << cd_txt;
+  role << "AcceptRole";
+  if (addpath_option)
+    {
+      btn << addpath_txt;
+      role << "AcceptRole";
+    }
+  btn << cancel_txt;
+  role << "AcceptRole";
+
+  uiwidget_creator.signal_dialog (msg, title, "quest", btn, cancel_txt, role);
+
+  // Wait while the user is responding to message box.
+  uiwidget_creator.wait ();
+
+  QString result = uiwidget_creator.get_dialog_button ();
+
+  if (result == cd_txt)
+    retval = 1;
+  else if (result == addpath_txt)
+    retval = 2;
+
+  return retval;
+}
+
+void
+octave_qt_link::do_change_directory (const std::string& dir)
+{
+  emit change_directory_signal (QString::fromStdString (dir));
+}
+
+void
+octave_qt_link::do_execute_command_in_terminal (const std::string& command)
+{
+  emit execute_command_in_terminal_signal (QString::fromStdString (command));
+}
+
+void
+octave_qt_link::do_set_workspace (bool top_level,
+                                  const std::list<workspace_element>& ws)
+{
+  QString scopes;
+  QStringList symbols;
+  QStringList class_names;
+  QStringList dimensions;
+  QStringList values;
+
+  for (std::list<workspace_element>::const_iterator it = ws.begin ();
+       it != ws.end (); it++)
+    {
+      scopes.append (it->scope ());
+      symbols.append (QString::fromStdString (it->symbol ()));
+      class_names.append (QString::fromStdString (it->class_name ()));
+      dimensions.append (QString::fromStdString (it->dimension ()));
+      values.append (QString::fromStdString (it->value ()));
+    }
+
+  emit set_workspace_signal (top_level, scopes, symbols, class_names,
+                             dimensions, values);
+}
+
+void
+octave_qt_link::do_clear_workspace (void)
+{
+  emit clear_workspace_signal ();
+}
+
+void
+octave_qt_link::do_set_history (const string_vector& hist)
+{
+  QStringList qt_hist;
+
+  for (octave_idx_type i = 0; i < hist.length (); i++)
+    qt_hist.append (QString::fromStdString (hist[i]));
+
+  emit set_history_signal (qt_hist);
+}
+
+void
+octave_qt_link::do_append_history (const std::string& hist_entry)
+{
+  emit append_history_signal (QString::fromStdString (hist_entry));
+}
+
+void
+octave_qt_link::do_clear_history (void)
+{
+  emit clear_history_signal ();
+}
+
+void
+octave_qt_link::do_pre_input_event (void)
+{
+}
+
+void
+octave_qt_link::do_post_input_event (void)
+{
+}
+
+void
+octave_qt_link::do_enter_debugger_event (const std::string& file, int line)
+{
+  do_insert_debugger_pointer (file, line);
+
+  emit enter_debugger_signal ();
+}
+
+void
+octave_qt_link::do_execute_in_debugger_event (const std::string& file, int line)
+{
+  do_delete_debugger_pointer (file, line);
+}
+
+void
+octave_qt_link::do_exit_debugger_event (void)
+{
+  emit exit_debugger_signal ();
+}
+
+void
+octave_qt_link::do_update_breakpoint (bool insert,
+                                      const std::string& file, int line)
+{
+  emit update_breakpoint_marker_signal (insert, QString::fromStdString (file), line);
+}
+
+void
+octave_qt_link::do_set_default_prompts (std::string& ps1, std::string& ps2,
+                                        std::string& ps4)
+{
+  ps1 = ">> ";
+  ps2 = "";
+  ps4 = "";
+}
+
+
+void
+octave_qt_link::do_insert_debugger_pointer (const std::string& file, int line)
+{
+  emit insert_debugger_pointer_signal (QString::fromStdString (file), line);
+}
+
+void
+octave_qt_link::do_delete_debugger_pointer (const std::string& file, int line)
+{
+  emit delete_debugger_pointer_signal (QString::fromStdString (file), line);
+}
new file mode 100644
--- /dev/null
+++ b/libgui/src/octave-qt-link.h
@@ -0,0 +1,170 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2011-2012 Jacob Dawid
+Copyright (C) 2011-2012 John P. Swensen
+
+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/>.
+
+*/
+
+#ifndef OCTAVE_QT_LINK_H
+#define OCTAVE_QT_LINK_H
+
+#include <list>
+#include <string>
+
+#include <QList>
+#include <QObject>
+#include <QString>
+
+#include "octave-link.h"
+#include "octave-main-thread.h"
+
+// \class OctaveLink
+// \brief Provides threadsafe access to octave.
+// \author Jacob Dawid
+//
+// This class is a wrapper around octave and provides thread safety by
+// buffering access operations to octave and executing them in the
+// readline event hook, which lives in the octave thread.
+
+class octave_qt_link : public QObject, public octave_link
+{
+  Q_OBJECT
+
+public:
+
+  octave_qt_link (octave_main_thread *mt);
+
+  ~octave_qt_link (void);
+
+  void execute_interpreter (void);
+
+  bool do_exit (int status);
+
+  bool do_edit_file (const std::string& file);
+
+  int do_message_dialog (const std::string& dlg, const std::string& msg,
+                         const std::string& title);
+
+  std::string
+  do_question_dialog (const std::string& msg, const std::string& title,
+                      const std::string& btn1, const std::string& btn2,
+                      const std::string& btn3, const std::string& btndef);
+
+  std::pair<std::list<int>, int>
+  do_list_dialog (const std::list<std::string>& list,
+                  const std::string& mode,
+                  int width, int height,
+                  const std::list<int>& initial_value,
+                  const std::string& name,
+                  const std::list<std::string>& prompt,
+                  const std::string& ok_string,
+                  const std::string& cancel_string);
+
+  std::list<std::string>
+  do_input_dialog (const std::list<std::string>& prompt,
+                   const std::string& title,
+                   const std::list<float>& nr,
+                   const std::list<float>& nc,
+                   const std::list<std::string>& defaults);
+
+  std::list<std::string>
+  do_file_dialog (const filter_list& filter, const std::string& title, 
+                  const std::string &filename, const std::string &pathname,
+                  const std::string& multimode);
+
+  int
+  do_debug_cd_or_addpath_error (const std::string& file,
+                                const std::string& dir,
+                                bool addpath_option);
+
+  void do_change_directory (const std::string& dir);
+
+  void do_execute_command_in_terminal (const std::string& command);
+
+  void do_set_workspace (bool top_level,
+                         const std::list<workspace_element>& ws);
+
+  void do_clear_workspace (void);
+
+  void do_set_history (const string_vector& hist);
+  void do_append_history (const std::string& hist_entry);
+  void do_clear_history (void);
+
+  void do_pre_input_event (void);
+  void do_post_input_event (void);
+
+  void do_enter_debugger_event (const std::string& file, int line);
+  void do_execute_in_debugger_event (const std::string& file, int line);
+  void do_exit_debugger_event (void);
+
+  void do_update_breakpoint (bool insert, const std::string& file, int line);
+
+  void do_set_default_prompts (std::string& ps1, std::string& ps2,
+                               std::string& ps4);
+
+
+private:
+
+  // No copying!
+
+  octave_qt_link (const octave_qt_link&);
+
+  octave_qt_link& operator = (const octave_qt_link&);
+
+  void do_insert_debugger_pointer (const std::string& file, int line);
+  void do_delete_debugger_pointer (const std::string& file, int line);
+
+  // Thread running octave_main.
+  octave_main_thread *main_thread;
+
+signals:
+
+  void exit_signal (int status);
+
+  void edit_file_signal (const QString& file);
+
+  void change_directory_signal (const QString& dir);
+
+  void execute_command_in_terminal_signal (const QString& command);
+
+  void set_workspace_signal (bool top_level,
+                             const QString& scopes,
+                             const QStringList& symbols,
+                             const QStringList& class_names,
+                             const QStringList& dimensions,
+                             const QStringList& values);
+
+  void clear_workspace_signal (void);
+
+  void set_history_signal (const QStringList& hist);
+  void append_history_signal (const QString& hist_entry);
+  void clear_history_signal (void);
+
+  void enter_debugger_signal (void);
+  void exit_debugger_signal (void);
+
+  void update_breakpoint_marker_signal (bool insert, const QString& file,
+                                        int line);
+
+  void insert_debugger_pointer_signal (const QString&, int);
+  void delete_debugger_pointer_signal (const QString&, int);
+};
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libgui/src/qtinfo/parser.cc
@@ -0,0 +1,587 @@
+/* Copyright (C) 2009 P.L. Lucas
+ * Copyright (C) 2012 Jacob Dawid <jacob.dawid@gmail.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., 59 Temple Place, Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include "parser.h"
+#include <QFileInfo>
+#include <QDir>
+#include <QFile>
+#include <QUrl>
+#include <QRegExp>
+#include <QProcess>
+#include <QBuffer>
+
+parser::parser(QObject *p)
+  : QObject(p)
+{
+  _compressors_map.insert ("bz2",  "bzip2 -dc \"%1\"");
+  _compressors_map.insert ("gz",   "gzip -dc \"%1\"");
+  _compressors_map.insert ("lzma", "lzma -dc \"%1\"");
+  _compressors_map.insert ("xz",   "xz -dc \"%1\"");
+  _compressors_map.insert ("Z",    "gunzip -c \"%1\"");
+}
+
+void
+parser::set_info_path (const QString& infoPath)
+{
+  this->_info_path = infoPath;
+
+  _info_files.clear ();
+
+  QFileInfo info (infoPath);
+
+  QString path = info.absolutePath ();
+  QString fileName = info.fileName ();
+
+  QDir infoDir (path);
+  QStringList filter;
+  filter.append (fileName + "*");
+
+  _info_files = infoDir.entryInfoList (filter, QDir::Files);
+  parse_info_map ();
+}
+
+QString
+parser::get_info_path ()
+{
+  return _info_path;
+}
+
+QIODevice *
+parser::open_file (QFileInfo & file_info)
+{
+  QIODevice *iodevice=NULL;
+  if ( _compressors_map.contains(file_info.suffix ()))
+    {
+      QProcess gzip;
+      gzip.start (_compressors_map.value (file_info.suffix ()).arg (file_info.absoluteFilePath ()));
+
+      if (!gzip.waitForFinished ())
+        return NULL;
+
+      QByteArray result = gzip.readAll ();
+
+      QBuffer *io = new QBuffer (this);
+      io->setData (result);
+
+      if (!io->open (QIODevice::ReadOnly | QIODevice::Text))
+        return NULL;
+
+      iodevice = io;
+    }
+  else
+    {
+      QFile *io = new QFile (file_info.absoluteFilePath ());
+      if (!io->open (QIODevice::ReadOnly | QIODevice::Text))
+        return NULL;
+      iodevice = io;
+    }
+
+  return iodevice;
+}
+
+int
+parser::is_ref (const QString& node)
+{
+  if (_ref_map.contains (node))
+    {
+      node_position ref = _ref_map [node];
+
+      return ref.pos-_node_map [ref._node_name].pos;
+    }
+  return -1;
+}
+
+QString
+parser::search_node (const QString& node_arg)
+{
+  QString node = node_arg;
+
+  QFileInfo file_info;
+  QString ref;
+
+  if (_ref_map.contains (node))
+    {
+      ref = node;
+      node = _ref_map [ref]._node_name;
+    }
+
+  if (_node_map.contains (node))
+    {
+      int pos = _node_map [node].pos;
+      int realPos;
+
+      real_position (pos, file_info, realPos);
+
+      QIODevice *io = open_file (file_info);
+      if (io == NULL)
+        {
+          return QString ();
+        }
+
+      seek (io, realPos);
+
+      QString text = get_next_node (io);
+      if (!text.isEmpty())
+        {
+          return text;
+        }
+
+      io->close ();
+      delete io;
+    }
+
+  return QString ();
+}
+
+QString
+parser::search_node (const QString& node, QIODevice *io)
+{
+  while (!io->atEnd ())
+    {
+      QString text = get_next_node (io);
+      if(node == get_node_name (text))
+        {
+          return text;
+        }
+    }
+
+  return QString ();
+}
+
+QString
+parser::get_next_node (QIODevice *io)
+{
+  QString text;
+  while (!io->atEnd ())
+    {
+      QByteArray line = io->readLine ();
+      if (line.at(0) == 31)
+        {
+          break;
+        }
+      else
+        {
+          text.append (line);
+        }
+    }
+  return text;
+}
+
+static QString
+get_first_line (const QString& text)
+{
+  int n = text.indexOf ("\n");
+
+  if (n < 0)
+    {
+      return QString ();
+    }
+
+  QString first_line = text.left (n);
+  return first_line;
+}
+
+static QString
+parser_node (const QString& text, const QString& node_name)
+{
+  QString firstLine = get_first_line (text);
+  QStringList nodes = firstLine.split (",");
+  for (int i = 0;i < nodes.size (); i++)
+    {
+      QString node = nodes.at (i).trimmed ();
+
+      if (node.startsWith (node_name))
+        {
+          return node.remove (0, node_name.size ()).trimmed ();
+        }
+    }
+  return QString ();
+}
+
+QString
+parser::get_node_name (const QString& text)
+{
+  return parser_node (text, "Node:");
+}
+
+QString
+parser::get_node_up (const QString& text)
+{
+  return parser_node (text, "Up:");
+}
+
+QString
+parser::get_node_next (const QString& text)
+{
+  return parser_node (text, "Next:");
+}
+
+QString
+parser::get_node_prev (const QString& text)
+{
+  return parser_node (text, "Prev:");
+}
+
+static void
+replace_links (QString& text)
+{
+  QRegExp re ("(\\*[N|n]ote|\n\\*)([ |\n]+)([^:]+):([^:\\.,]*)([:,\\.])");
+  int i = 0, f;
+
+  while ( (i = re.indexIn (text,i)) != -1)
+    {
+      QString type     = re.cap (1);
+      QString note     = re.cap (3);
+      QString url_link = re.cap (4);
+      QString link     = re.cap (4);
+
+      if (url_link.isEmpty ())
+        {
+          url_link = note;
+        }
+
+      url_link = url_link.trimmed ();
+      url_link.replace ("\n"," ");
+      url_link.replace (QRegExp ("  +")," ");
+      url_link.replace ("<b>","");
+      url_link.replace ("</b>","");
+      url_link = QUrl::toPercentEncoding (url_link, "", "'");
+
+      QString href;
+      if (type=="\n*")
+        {
+          href="\n<img src=':/actions/icons/bookmark.png'/>";
+        }
+      else
+        {
+          href="<img src=':/actions/icons/bookmark.png'/>";
+        }
+      href += re.cap (2) + "<a href='" + url_link + "'>" + note + ":" + link + re.cap (5) + "</a>";
+      f = re.matchedLength ();
+      text.replace (i,f,href);
+      i += href.size ();
+    }
+}
+
+static void
+replace_colons (QString& text)
+{
+  QRegExp re ("`([^']+)'");
+  int i = 0, f;
+  while ( (i = re.indexIn (text, i)) != -1)
+    {
+      QString t = re.cap (1);
+      QString bold = "<b>`" + t + "</b>'";
+
+      f = re.matchedLength ();
+      text.replace (i,f,bold);
+      i += bold.size ();
+    }
+}
+
+static void
+info_to_html (QString& text)
+{
+  text.replace ("&", "&amp;");
+  text.replace ("<", "&lt;");
+  text.replace (">", "&gt;");
+
+  text.replace ("\n* Menu:", "\n<b>Menu:</b>");
+  text.replace ("*See also:*", "<b>See also:</b>");
+  replace_colons (text);
+  replace_links (text);
+}
+
+QString
+parser::node_text_to_html (const QString& text_arg, int anchorPos,
+                           const QString& anchor)
+{
+  QString text = text_arg;
+
+  QString nodeName = get_node_name (text);
+  QString nodeUp   = get_node_up (text);
+  QString nodeNext = get_node_next (text);
+  QString nodePrev = get_node_prev (text);
+
+  if (anchorPos > -1)
+    {
+      QString text1 = text.left (anchorPos);
+      QString text2 = text.mid (anchorPos);
+
+      int n = text1.indexOf ("\n");
+      text1.remove (0, n);
+
+      info_to_html (text1);
+      info_to_html (text2);
+
+      text = text1 + "<a name='" + anchor + "' /><img src=':/actions/icons/stop.png'>" + text2;
+    }
+  else
+    {
+      int n = text.indexOf ("\n");
+      text.remove (0, n);
+      info_to_html (text);
+    }
+
+  QString navigationLinks = QString (
+        "<img src=':/actions/icons/arrow_right.png'/> <b>Section:</b> %1<br>"
+        "<b>Previous Section:</b> <a href='%2'>%3</a><br>"
+        "<b>Next Section:</b> <a href='%4'>%5</a><br>"
+        "<b>Up:</b> <a href='%6'>%7</a><br>\n"
+        )
+      .arg (nodeName)
+      .arg (QString (QUrl::toPercentEncoding (nodePrev, "", "'")))
+      .arg (nodePrev)
+      .arg (QString (QUrl::toPercentEncoding (nodeNext, "", "'")))
+      .arg (nodeNext)
+      .arg (QString (QUrl::toPercentEncoding (nodeUp, "", "'")))
+      .arg (nodeUp);
+
+
+  text.prepend ("<hr>\n<pre>");
+  text.append ("</pre>\n<hr><hr>\n");
+  text.prepend (navigationLinks);
+  text.append (navigationLinks);
+  text.prepend ("<html><body>\n");
+  text.append ("</body></html>\n");
+  return text;
+}
+
+void
+parser::parse_info_map ()
+{
+  QRegExp re ("(Node|Ref): ([^\\0177]+)\\0177(\\d+)\n");
+  QRegExp re_files ("([^:]+): (\\d+)\n");
+  int foundCount = 0;
+
+  for(int i = 0; i < _info_files.size (); i++)
+    {
+      QFileInfo fileInfo = _info_files.at (i);
+
+      QIODevice *io = open_file (fileInfo);
+      if (io == NULL)
+        {
+          continue;
+        }
+
+      QString nodeText;
+      while (! (nodeText=get_next_node (io)).isEmpty () && foundCount < 2)
+        {
+          QString first_line = get_first_line (nodeText);
+          if (first_line.startsWith ("Tag") )
+            {
+              foundCount++;
+              int pos = 0;
+              QString last_node;
+
+              while ((pos = re.indexIn (nodeText, pos)) != -1) {
+                  QString type = re.cap (1);
+                  QString node = re.cap (2);
+                  int index = re.cap (3).toInt ();
+
+                  if (type == "Node")
+                    {
+                      node_map_item item;
+                      item.pos = index;
+                      _node_map [node] = item;
+                      last_node = node;
+                    }
+                  else if (type == "Ref")
+                    {
+                      node_position item;
+                      item._node_name = last_node;
+                      item.pos = index;
+                      _ref_map [node] = item;
+                    }
+                  pos += re.matchedLength ();
+                }
+              break;
+            }
+          else if (first_line.startsWith ("Indirect:"))
+            {
+              foundCount++;
+              int pos = 0;
+
+              while ( (pos = re_files.indexIn (nodeText, pos)) != -1) {
+                  QString fileCap = re_files.cap (1).trimmed ();
+                  int index = re_files.cap (2).toInt ();
+
+                  info_file_item item;
+                  for (int j = 0;j < _info_files.size (); j++)
+                    {
+                      QFileInfo info = _info_files.at (j);
+                      if (info.fileName ().startsWith (fileCap))
+                        {
+                          item.file_info = info;
+                          break;
+                        }
+                    }
+                  item.real_size = index;
+                  _info_file_real_size_list.append (item);
+                  pos += re_files.matchedLength ();
+                }
+
+            }
+        }
+      io->close ();
+      delete io;
+    }
+}
+
+void
+parser::real_position (int pos, QFileInfo & file_info, int & real_pos)
+{
+  int header = -1, sum = 0;
+  for (int i = 0; i < _info_file_real_size_list.size (); i++)
+    {
+      info_file_item item = _info_file_real_size_list.at (i);
+      if (header == -1)
+        {
+          file_info = item.file_info;
+          header = item.real_size;
+        }
+
+      if (pos < item.real_size)
+        {
+          break;
+        }
+
+      file_info = item.file_info;
+      sum = item.real_size;
+    }
+  real_pos = pos - sum + header + 2;
+}
+
+void
+parser::seek (QIODevice *io, int pos)
+{
+  char ch;
+  while (!io->atEnd () && pos > 0)
+    {
+      io->getChar (&ch);
+      pos--;
+    }
+}
+
+static void
+replace (QString& text, const QRegExp& re, const QString& after)
+{
+  int pos = 0;
+
+  while ( (pos = re.indexIn (text, pos)) != -1)
+    {
+      QString cap = text.mid (pos,re.matchedLength ());
+      QString a (after);
+      a = a.arg (cap);
+      text.remove (pos, re.matchedLength ());
+      text.insert (pos, a);
+      pos += a.size ();
+    }
+}
+
+QString
+parser::global_search (const QString& text, int max_founds)
+{
+  QString results;
+  QStringList words = text.split (" ",QString::SkipEmptyParts);
+
+  QString re_program ("(" + words.at (0));
+  for (int i = 1; i < words.size (); i++)
+    {
+      re_program += "|" + words.at (i);
+    }
+  re_program += ")";
+
+  QRegExp re (re_program, Qt::CaseInsensitive);
+
+  results.append ("<html><body>\n<h1>Search results</h1>\n<b>Results for:</b> ");
+  results.append (text);
+  results.append ("<br>\n");
+
+  for (int i = 0; i < _info_files.size (); i++)
+    {
+      QFileInfo file_info = _info_files.at (i);
+      QIODevice *io = open_file (file_info);
+      if (io == NULL)
+        {
+          continue;
+        }
+
+      QString node_text;
+      while ( !(node_text = get_next_node (io)).isEmpty ())
+        {
+          QString firstLine = get_first_line (node_text);
+          QString node = get_node_name (node_text);
+          if (node.isEmpty ())
+            {
+              continue;
+            }
+
+          int n = node_text.indexOf ("\n");
+          node_text.remove (0, n);
+
+          int pos = 0;
+          int founds = 0;
+
+          for (; founds < words.size () && node_text.indexOf (words.at (founds)) >= 0; founds++)
+            { }
+
+          if (founds<words.size ())
+            {
+              continue;
+            }
+          founds = 0;
+
+          while ( (pos = re.indexIn (node_text, pos)) != -1 && founds < max_founds)
+            {
+              int line_start, line_end;
+              line_start = node_text.lastIndexOf ("\n", pos);
+              line_end = node_text.indexOf ("\n", pos);
+              QString line = node_text.mid (line_start, line_end - line_start).trimmed ();
+
+              if (founds == 0)
+                {
+                  results.append(
+                        "<br>\n<img src=':/actions/icons/bookmark.png'> <a href='"
+                        + QString(QUrl::toPercentEncoding(node,"","'")) +
+                        "'>");
+                  results.append (node);
+                  results.append ("</a><br>\n");
+                }
+
+              replace (line, re, "<i>%1</i>");
+              results.append (line);
+              results.append ("<br>\n");
+
+              founds++;
+
+              pos += re.matchedLength ();
+            }
+        }
+      io->close ();
+      delete io;
+    }
+
+  results.append ("</body></html>");
+  return results;
+}
new file mode 100644
--- /dev/null
+++ b/libgui/src/qtinfo/parser.h
@@ -0,0 +1,112 @@
+/* Copyright (C) 2009 P.L. Lucas
+ * Copyright (C) 2012 Jacob Dawid <jacob.dawid@gmail.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., 59 Temple Place, Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#include <QStringList>
+#include <QIODevice>
+#include <QFileInfoList>
+#include <QHash>
+
+/**
+ * \class parser
+ * This class gets nodes and searchs inside of 'info files'.
+ * <p>Each info file has nodes. Every node has the documentation.
+ * Info files contains a map with position of each node.</p>
+ * <p>What is position?
+ * There is a simple answer:
+ * If you make a queue with info files, position will be the number of bytes
+ * from begining to node position.</p>
+ * <p>
+ * But is not so easy. There is headers, and qtinfo must not take these headers into account.
+ * </p>
+ * <p>
+ * This class also translates info files to html.
+ * </p>
+ */
+class parser
+    : public QObject
+{
+  Q_OBJECT
+
+public:
+  parser (QObject *parent = 0);
+  void set_info_path (const QString& _info_path);
+  QString get_info_path ();
+  QString search_node (const QString& node);
+  QString global_search (const QString& text, int maxFounds);
+
+  /** Checks if this node is reference. If node is reference, it will be returned its position
+    * in text, else  it will be returned -1.
+    */
+  int is_ref (const QString& node);
+
+  /**Translates text of node to Html. If anchorPos is not -1, then anchor is inserted in that
+    * position.
+    */
+  QString node_text_to_html (const QString& text, int anchorPos = -1,
+                             const QString& anchor = QString ());
+
+private:
+  struct node_position
+  {
+    QString _node_name;
+    int pos;
+  };
+
+  struct node_map_item
+  {
+    int pos;
+  };
+
+  struct info_file_item
+  {
+    QFileInfo file_info;
+    int real_size;
+  };
+
+  QString search_node (const QString& node, QIODevice * io);
+  QString get_next_node (QIODevice * io);
+  QString get_node_name (const QString& text);
+  QString get_node_up (const QString& text);
+  QString get_node_next (const QString& text);
+  QString get_node_prev (const QString& text);
+
+  /** Parses info files and gets map of node positions.*/
+  void parse_info_map();
+
+  /** Open info files and uncompress them. */
+  QIODevice *open_file(QFileInfo & fileInfo);
+
+  /** Calculates real position of nodes.
+    * \param pos position from info file.
+    * \param fileInfo returns file what contains that position.
+    * \param realPos returns real position inside of fileInfo.
+    */
+  void real_position (int pos, QFileInfo & file_info, int & real_pos);
+
+  /** Seeks to position pos. */
+  void seek (QIODevice *io, int pos);
+
+
+  QString                       _info_path;
+  QFileInfoList                 _info_files;
+  QHash<QString, node_map_item> _node_map;
+  QHash<QString, node_position> _ref_map;
+  QList<info_file_item>         _info_file_real_size_list;
+  QHash<QString, QString>       _compressors_map;
+};
new file mode 100644
--- /dev/null
+++ b/libgui/src/qtinfo/webinfo.cc
@@ -0,0 +1,213 @@
+/* Copyright (C) 2009 P.L. Lucas
+ * Copyright (C) 2012 Jacob Dawid <jacob.dawid@gmail.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., 59 Temple Place, Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include "webinfo.h"
+#include <QVBoxLayout>
+#include <QHBoxLayout>
+
+#include "file-ops.h"
+#include "help.h"
+#include "defaults.h"
+
+
+webinfo::webinfo (QWidget *p)
+  : QWidget (p)
+{
+  _font_web = font ();
+
+  QVBoxLayout *vbox_layout = new QVBoxLayout ();
+  vbox_layout->setMargin (0);
+  setLayout (vbox_layout);
+
+  QHBoxLayout *hbox_layout = new QHBoxLayout ();
+  hbox_layout->setMargin (2);
+  vbox_layout->addLayout (hbox_layout);
+
+  _tab_bar = new QTabBar (this);
+  _tab_bar->setSizePolicy (QSizePolicy::Preferred,QSizePolicy::Preferred);
+  _tab_bar->setExpanding (false);
+  _tab_bar->setTabsClosable (true);
+  _tab_bar->setMovable (true);
+  hbox_layout->addWidget (_tab_bar);
+
+  _zoom_in_button = new QToolButton (this);
+  _zoom_in_button->setSizePolicy (QSizePolicy::Fixed,QSizePolicy::Preferred);
+  _zoom_in_button->setIcon (QIcon (":/actions/icons/zoom-in.png"));
+  hbox_layout->addWidget (_zoom_in_button);
+
+  _zoom_out_button = new QToolButton (this);
+  _zoom_out_button->setSizePolicy (QSizePolicy::Fixed,QSizePolicy::Preferred);
+  _zoom_out_button->setIcon (QIcon (":/actions/icons/zoom-out.png"));
+  hbox_layout->addWidget (_zoom_out_button);
+
+  _stacked_widget = new QStackedWidget (this);
+  vbox_layout->addWidget (_stacked_widget);
+
+  hbox_layout = new QHBoxLayout ();
+  vbox_layout->addLayout (hbox_layout);
+
+  _search_line_edit = new QLineEdit(this);
+#ifdef HAVE_SETPLACEHOLDERTEXT
+  _search_line_edit->setPlaceholderText (tr ("Type here and press \'Return\' to search"));
+#endif
+  hbox_layout->addWidget (_search_line_edit);
+
+  _search_check_box = new QCheckBox (tr ("Global search"));
+  hbox_layout->addWidget (_search_check_box);
+
+  connect (_tab_bar, SIGNAL (tabCloseRequested (int)), this, SLOT (close_tab (int)));
+  connect (_tab_bar, SIGNAL (currentChanged (int)), this, SLOT (current_tab_changed (int)));
+  connect (_zoom_in_button, SIGNAL (clicked ()), this, SLOT (zoom_in ()));
+  connect (_zoom_out_button, SIGNAL (clicked ()), this, SLOT (zoom_out ()));
+  connect (_search_line_edit, SIGNAL (returnPressed ()), this, SLOT (search ()));
+
+  resize (500, 300);
+
+  set_info_path (QString::fromStdString (Vinfo_file));
+}
+
+void
+webinfo::set_info_path (const QString& info_path)
+{
+  _parser.set_info_path (info_path);
+  load_node ("Top");
+}
+
+void
+webinfo::load_node (const QString& node_name)
+{
+  //Check if node has been already opened.
+  for (int i = 0;i < _tab_bar->count (); i++)
+    {
+      if (node_name == _tab_bar->tabText (i))
+        {
+          _tab_bar->setCurrentIndex (i);
+          return;
+        }
+    }
+
+  QString text = _parser.search_node (node_name);
+  int i = _parser.is_ref (node_name);
+  _text_browser = addNewTab (node_name);
+  _text_browser->setHtml (_parser.node_text_to_html (text, i - 1, "anchor"));
+
+  if (i != -1)
+    {
+      _text_browser->scrollToAnchor ("anchor");
+    }
+}
+
+void
+webinfo::link_clicked (const QUrl & link)
+{
+  QString node = link.toString ();
+  load_node (node);
+}
+
+void
+webinfo::current_tab_changed (int index)
+{
+  QVariant tab_data = _tab_bar->tabData (index);
+  _text_browser = static_cast<QTextBrowser*> (tab_data.value<void*> ());
+
+  _stacked_widget->setCurrentIndex (_stacked_widget->indexOf (_text_browser));
+
+  if (_text_browser->font () != _font_web)
+    {
+      _text_browser->setFont (_font_web);
+    }
+}
+
+QTextBrowser *
+webinfo::addNewTab (const QString& name)
+{
+  _text_browser = new QTextBrowser (this);
+  _text_browser->setOpenLinks (false);
+  _text_browser->show ();
+
+  connect (_text_browser, SIGNAL (anchorClicked (const QUrl &)), this, SLOT (link_clicked (const QUrl &)) );
+  disconnect(_tab_bar, SIGNAL (currentChanged(int)), this, SLOT (current_tab_changed (int)));
+
+  int ns = _stacked_widget->addWidget (_text_browser);
+  _stacked_widget->setCurrentIndex (ns);
+
+  int nt = _tab_bar->addTab (name);
+  _tab_bar->setCurrentIndex (nt);
+  QVariant tab_data;
+  tab_data.setValue (static_cast<void*> (_text_browser));
+  _tab_bar->setTabData (nt, tab_data);
+
+  connect (_tab_bar, SIGNAL (currentChanged (int)), this, SLOT (current_tab_changed (int)));
+
+  if (_text_browser->font () != _font_web)
+    {
+      _text_browser->setFont (_font_web);
+    }
+  return _text_browser;
+}
+
+void
+webinfo::close_tab (int index)
+{
+  if (_tab_bar->count () > 1)
+    {
+      QVariant tab_data = _tab_bar->tabData (index);
+      QWidget *w = static_cast<QWidget*> (tab_data.value<void*> ());
+      _stacked_widget->removeWidget (w);
+      delete w;
+
+      _tab_bar->removeTab (index);
+    }
+}
+
+void
+webinfo::search ()
+{
+  if (_search_check_box->isChecked ())
+    {
+      // Global search
+      QString results = _parser.global_search (_search_line_edit->text (), 5);
+      _text_browser=addNewTab ("Results for: " + _search_line_edit->text ());
+      _text_browser->setHtml (results);
+    }
+  else
+    {
+      // Local search
+      _text_browser->find (_search_line_edit->text ());
+    }
+}
+
+void
+webinfo::zoom_in ()
+{
+  _font_web.setPointSize (_font_web.pointSize() + 1);
+  _text_browser->setFont (_font_web);
+}
+
+void
+webinfo::zoom_out ()
+{
+  _font_web.setPointSize (_font_web.pointSize() - 1);
+  _text_browser->setFont (_font_web);
+}
+
new file mode 100644
--- /dev/null
+++ b/libgui/src/qtinfo/webinfo.h
@@ -0,0 +1,58 @@
+/* Copyright (C) 2009 P.L. Lucas
+ * Copyright (C) 2012 Jacob Dawid <jacob.dawid@gmail.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., 59 Temple Place, Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#include <QTextBrowser>
+#include "parser.h"
+#include <QStackedWidget>
+#include <QTabBar>
+#include <QPushButton>
+#include <QLineEdit>
+#include <QCheckBox>
+#include <QToolButton>
+
+class webinfo : public QWidget
+{
+  Q_OBJECT
+public:
+  webinfo (QWidget *parent = 0);
+  void set_info_path (const QString& info_path);
+  void load_node (const QString& node_name);
+
+public slots:
+  void link_clicked (const QUrl& link);
+  void current_tab_changed (int index);
+  void close_tab (int index);
+  void search ();
+  void zoom_in ();
+  void zoom_out ();
+
+private:
+  QTextBrowser        *_text_browser;
+  QTabBar             *_tab_bar;
+  QStackedWidget      *_stacked_widget;
+  QLineEdit           *_search_line_edit;
+  QCheckBox           *_search_check_box;
+  QToolButton         *_zoom_in_button;
+  QToolButton         *_zoom_out_button;
+
+  parser              _parser;
+  QFont               _font_web;
+
+  QTextBrowser *addNewTab (const QString& name);
+};
new file mode 100644
--- /dev/null
+++ b/libgui/src/resource-manager.cc
@@ -0,0 +1,1756 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 <string>
+
+#include <QFile>
+#include <QDir>
+#include <QNetworkProxy>
+ #include <QLibraryInfo>
+
+#include "error.h"
+#include "file-ops.h"
+#include "oct-env.h"
+#include "singleton-cleanup.h"
+
+#include "defaults.h"
+
+#include "resource-manager.h"
+
+resource_manager *resource_manager::instance = 0;
+
+static QString
+default_qt_settings_file (void)
+{
+  std::string dsf = octave_env::getenv ("OCTAVE_DEFAULT_QT_SETTINGS");
+
+  if (dsf.empty ())
+    dsf = Voct_etc_dir + file_ops::dir_sep_str () + "default-qt-settings";
+
+  return QString::fromStdString (dsf);
+}
+
+resource_manager::resource_manager (void)
+  : settings (0), home_path (), first_run (false)
+{
+  do_reload_settings ();
+
+  default_settings = new QSettings (default_qt_settings_file (),
+                                    QSettings::IniFormat);
+}
+
+resource_manager::~resource_manager (void)
+{
+  delete settings;
+  delete default_settings;
+}
+
+
+QString
+resource_manager::get_gui_translation_dir (void)
+{
+  // get environment variable for the locale dir (e.g. from run-octave)
+  std::string dldir = octave_env::getenv ("OCTAVE_LOCALE_DIR");
+  if (dldir.empty ())
+    dldir = Voct_locale_dir; // env-var empty, load the default location
+  return QString::fromStdString (dldir);
+}
+
+void
+resource_manager::config_translators (QTranslator *qt_tr,QTranslator *gui_tr)
+{
+  QSettings *settings = resource_manager::get_settings ();
+  // FIXME -- what should happen if settings is 0?
+  // get the locale from the settings
+  QString language = settings->value ("language","SYSTEM").toString ();
+  if (language == "SYSTEM")
+      language = QLocale::system().name();    // get system wide locale
+  // load the translator file for qt strings
+  qt_tr->load("qt_" + language,
+              QLibraryInfo::location(QLibraryInfo::TranslationsPath));
+  // load the translator file for gui strings
+  gui_tr->load (language, get_gui_translation_dir ());
+}
+
+bool
+resource_manager::instance_ok (void)
+{
+  bool retval = true;
+
+  if (! instance)
+    {
+      instance = new resource_manager ();
+
+      if (instance)
+        singleton_cleanup_list::add (cleanup_instance);
+    }
+
+  if (! instance)
+    {
+      ::error ("unable to create resource_manager object!");
+
+      retval = false;
+    }
+
+  return retval;
+}
+
+QSettings *
+resource_manager::do_get_settings (void) const
+{
+  return settings;
+}
+
+QSettings *
+resource_manager::do_get_default_settings (void) const
+{
+  return default_settings;
+}
+
+QString
+resource_manager::do_get_home_path (void) const
+{
+  return home_path;
+}
+
+void
+resource_manager::do_reload_settings (void)
+{
+  QDesktopServices desktopServices;
+  home_path = desktopServices.storageLocation (QDesktopServices::HomeLocation);
+  QString settings_path = home_path + "/.config/octave/";
+  QString settings_file = settings_path + "qt-settings";
+
+  if (!QFile::exists (settings_file))
+    {
+      QDir("/").mkpath (settings_path);
+      QFile::copy (default_qt_settings_file (), settings_file);
+      first_run = true;
+    }
+  else
+    first_run = false;
+
+  do_set_settings (settings_file);
+}
+
+void
+resource_manager::do_set_settings (const QString& file)
+{
+  delete settings;
+  settings = new QSettings (file, QSettings::IniFormat);
+}
+
+bool
+resource_manager::do_is_first_run (void) const
+{
+  return first_run;
+}
+
+void
+resource_manager::do_update_network_settings (void)
+{
+  QNetworkProxy::ProxyType proxyType = QNetworkProxy::NoProxy;
+
+  if (settings->value ("useProxyServer",false).toBool ())
+    {
+      QString proxyTypeString = settings->value ("proxyType").toString ();
+
+      if (proxyTypeString == "Socks5Proxy")
+        proxyType = QNetworkProxy::Socks5Proxy;
+      else if (proxyTypeString == "HttpProxy")
+        proxyType = QNetworkProxy::HttpProxy;
+    }
+
+  QNetworkProxy proxy;
+
+  proxy.setType (proxyType);
+  proxy.setHostName (settings->value ("proxyHostName").toString ());
+  proxy.setPort (settings->value ("proxyPort",80).toInt ());
+  proxy.setUser (settings->value ("proxyUserName").toString ());
+  proxy.setPassword (settings->value ("proxyPassword").toString ());
+
+  QNetworkProxy::setApplicationProxy (proxy);
+}
+
+const char*
+resource_manager::octave_keywords (void)
+{
+  return
+      ".nargin. "
+      "EDITOR "
+      "EXEC_PATH "
+      "F_DUPFD "
+      "F_GETFD "
+      "F_GETFL "
+      "F_SETFD "
+      "F_SETFL "
+      "I "
+      "IMAGE_PATH "
+      "Inf "
+      "J "
+      "NA "
+      "NaN "
+      "OCTAVE_HOME "
+      "OCTAVE_VERSION "
+      "O_APPEND "
+      "O_ASYNC "
+      "O_CREAT "
+      "O_EXCL "
+      "O_NONBLOCK "
+      "O_RDONLY "
+      "O_RDWR "
+      "O_SYNC "
+      "O_TRUNC "
+      "O_WRONLY "
+      "PAGER "
+      "PAGER_FLAGS "
+      "PS1 "
+      "PS2 "
+      "PS4 "
+      "P_tmpdir "
+      "SEEK_CUR "
+      "SEEK_END "
+      "SEEK_SET "
+      "SIG "
+      "S_ISBLK "
+      "S_ISCHR "
+      "S_ISDIR "
+      "S_ISFIFO "
+      "S_ISLNK "
+      "S_ISREG "
+      "S_ISSOCK "
+      "WCONTINUE "
+      "WCOREDUMP "
+      "WEXITSTATUS "
+      "WIFCONTINUED "
+      "WIFEXITED "
+      "WIFSIGNALED "
+      "WIFSTOPPED "
+      "WNOHANG "
+      "WSTOPSIG "
+      "WTERMSIG "
+      "WUNTRACED "
+      "__accumarray_max__ "
+      "__accumarray_min__ "
+      "__accumarray_sum__ "
+      "__accumdim_sum__ "
+      "__all_opts__ "
+      "__builtins__ "
+      "__calc_dimensions__ "
+      "__contourc__ "
+      "__current_scope__ "
+      "__delaunayn__ "
+      "__dispatch__ "
+      "__display_tokens__ "
+      "__dsearchn__ "
+      "__dump_symtab_info__ "
+      "__end__ "
+      "__error_text__ "
+      "__finish__ "
+      "__fltk_ginput__ "
+      "__fltk_print__ "
+      "__fltk_uigetfile__ "
+      "__ftp__ "
+      "__ftp_ascii__ "
+      "__ftp_binary__ "
+      "__ftp_close__ "
+      "__ftp_cwd__ "
+      "__ftp_delete__ "
+      "__ftp_dir__ "
+      "__ftp_mget__ "
+      "__ftp_mkdir__ "
+      "__ftp_mode__ "
+      "__ftp_mput__ "
+      "__ftp_pwd__ "
+      "__ftp_rename__ "
+      "__ftp_rmdir__ "
+      "__get__ "
+      "__glpk__ "
+      "__gnuplot_drawnow__ "
+      "__gnuplot_get_var__ "
+      "__gnuplot_ginput__ "
+      "__gnuplot_has_feature__ "
+      "__gnuplot_open_stream__ "
+      "__gnuplot_print__ "
+      "__gnuplot_version__ "
+      "__go_axes__ "
+      "__go_axes_init__ "
+      "__go_close_all__ "
+      "__go_delete__ "
+      "__go_draw_axes__ "
+      "__go_draw_figure__ "
+      "__go_execute_callback__ "
+      "__go_figure__ "
+      "__go_figure_handles__ "
+      "__go_handles__ "
+      "__go_hggroup__ "
+      "__go_image__ "
+      "__go_line__ "
+      "__go_patch__ "
+      "__go_surface__ "
+      "__go_text__ "
+      "__go_uimenu__ "
+      "__gud_mode__ "
+      "__image_pixel_size__ "
+      "__init_fltk__ "
+      "__isa_parent__ "
+      "__keywords__ "
+      "__lexer_debug_flag__ "
+      "__lin_interpn__ "
+      "__list_functions__ "
+      "__magick_finfo__ "
+      "__magick_format_list__ "
+      "__magick_read__ "
+      "__magick_write__ "
+      "__makeinfo__ "
+      "__marching_cube__ "
+      "__next_line_color__ "
+      "__next_line_style__ "
+      "__operators__ "
+      "__parent_classes__ "
+      "__parser_debug_flag__ "
+      "__pathorig__ "
+      "__pchip_deriv__ "
+      "__plt_get_axis_arg__ "
+      "__print_parse_opts__ "
+      "__qp__ "
+      "__request_drawnow__ "
+      "__sort_rows_idx__ "
+      "__strip_html_tags__ "
+      "__token_count__ "
+      "__unimplemented__ "
+      "__varval__ "
+      "__version_info__ "
+      "__voronoi__ "
+      "__which__ "
+      "abs "
+      "accumarray "
+      "accumdim "
+      "acos "
+      "acosd "
+      "acosh "
+      "acot "
+      "acotd "
+      "acoth "
+      "acsc "
+      "acscd "
+      "acsch "
+      "add_input_event_hook "
+      "addlistener "
+      "addpath "
+      "addproperty "
+      "addtodate "
+      "airy "
+      "all "
+      "allchild "
+      "allow_noninteger_range_as_index "
+      "amd "
+      "ancestor "
+      "and "
+      "angle "
+      "anova "
+      "ans "
+      "any "
+      "arch_fit "
+      "arch_rnd "
+      "arch_test "
+      "area "
+      "arg "
+      "argnames "
+      "argv "
+      "arma_rnd "
+      "arrayfun "
+      "asctime "
+      "asec "
+      "asecd "
+      "asech "
+      "asin "
+      "asind "
+      "asinh "
+      "assert "
+      "assignin "
+      "atan "
+      "atan2 "
+      "atand "
+      "atanh "
+      "atexit "
+      "autocor "
+      "autocov "
+      "autoload "
+      "autoreg_matrix "
+      "autumn "
+      "available_graphics_toolkits "
+      "axes "
+      "axis "
+      "balance "
+      "bar "
+      "barh "
+      "bartlett "
+      "bartlett_test "
+      "base2dec "
+      "beep "
+      "beep_on_error "
+      "bessel "
+      "besselh "
+      "besseli "
+      "besselj "
+      "besselk "
+      "bessely "
+      "beta "
+      "betacdf "
+      "betai "
+      "betainc "
+      "betainv "
+      "betaln "
+      "betapdf "
+      "betarnd "
+      "bicgstab "
+      "bicubic "
+      "bin2dec "
+      "bincoeff "
+      "binocdf "
+      "binoinv "
+      "binopdf "
+      "binornd "
+      "bitand "
+      "bitcmp "
+      "bitget "
+      "bitmax "
+      "bitor "
+      "bitpack "
+      "bitset "
+      "bitshift "
+      "bitunpack "
+      "bitxor "
+      "blackman "
+      "blanks "
+      "blkdiag "
+      "blkmm "
+      "bone "
+      "box "
+      "break "
+      "brighten "
+      "bsxfun "
+      "bug_report "
+      "builtin "
+      "bunzip2 "
+      "bzip2 "
+      "calendar "
+      "canonicalize_file_name "
+      "cart2pol "
+      "cart2sph "
+      "case "
+      "cast "
+      "cat "
+      "catch "
+      "cauchy_cdf "
+      "cauchy_inv "
+      "cauchy_pdf "
+      "cauchy_rnd "
+      "caxis "
+      "cbrt "
+      "ccolamd "
+      "cd "
+      "ceil "
+      "cell "
+      "cell2mat "
+      "cell2struct "
+      "celldisp "
+      "cellfun "
+      "cellidx "
+      "cellindexmat "
+      "cellslices "
+      "cellstr "
+      "center "
+      "cgs "
+      "char "
+      "chdir "
+      "chi2cdf "
+      "chi2inv "
+      "chi2pdf "
+      "chi2rnd "
+      "chisquare_test_homogeneity "
+      "chisquare_test_independence "
+      "chol "
+      "chol2inv "
+      "choldelete "
+      "cholinsert "
+      "cholinv "
+      "cholshift "
+      "cholupdate "
+      "chop "
+      "circshift "
+      "cla "
+      "clabel "
+      "class "
+      "clc "
+      "clear "
+      "clf "
+      "clg "
+      "clock "
+      "cloglog "
+      "close "
+      "closereq "
+      "colamd "
+      "colloc "
+      "colon "
+      "colorbar "
+      "colormap "
+      "colperm "
+      "colstyle "
+      "columns "
+      "comet "
+      "comet3 "
+      "comma "
+      "command_line_path "
+      "common_size "
+      "commutation_matrix "
+      "compan "
+      "compare_versions "
+      "compass "
+      "complement "
+      "completion_append_char "
+      "completion_matches "
+      "complex "
+      "computer "
+      "cond "
+      "condest "
+      "confirm_recursive_rmdir "
+      "conj "
+      "continue "
+      "contour "
+      "contour3 "
+      "contourc "
+      "contourf "
+      "contrast "
+      "conv "
+      "conv2 "
+      "convhull "
+      "convhulln "
+      "convn "
+      "cool "
+      "copper "
+      "copyfile "
+      "cor "
+      "cor_test "
+      "corrcoef "
+      "cos "
+      "cosd "
+      "cosh "
+      "cot "
+      "cotd "
+      "coth "
+      "cov "
+      "cplxpair "
+      "cputime "
+      "cquad "
+      "crash_dumps_octave_core "
+      "create_set "
+      "cross "
+      "csc "
+      "cscd "
+      "csch "
+      "cstrcat "
+      "csvread "
+      "csvwrite "
+      "csymamd "
+      "ctime "
+      "ctranspose "
+      "cummax "
+      "cummin "
+      "cumprod "
+      "cumsum "
+      "cumtrapz "
+      "curl "
+      "cut "
+      "cylinder "
+      "daspect "
+      "daspk "
+      "daspk_options "
+      "dasrt "
+      "dasrt_options "
+      "dassl "
+      "dassl_options "
+      "date "
+      "datenum "
+      "datestr "
+      "datetick "
+      "datevec "
+      "dbclear "
+      "dbcont "
+      "dbdown "
+      "dblquad "
+      "dbnext "
+      "dbquit "
+      "dbstack "
+      "dbstatus "
+      "dbstep "
+      "dbstop "
+      "dbtype "
+      "dbup "
+      "dbwhere "
+      "deal "
+      "deblank "
+      "debug "
+      "debug_on_error "
+      "debug_on_interrupt "
+      "debug_on_warning "
+      "dec2base "
+      "dec2bin "
+      "dec2hex "
+      "deconv "
+      "default_save_options "
+      "del2 "
+      "delaunay "
+      "delaunay3 "
+      "delaunayn "
+      "delete "
+      "dellistener "
+      "demo "
+      "det "
+      "detrend "
+      "diag "
+      "diary "
+      "diff "
+      "diffpara "
+      "diffuse "
+      "dir "
+      "discrete_cdf "
+      "discrete_inv "
+      "discrete_pdf "
+      "discrete_rnd "
+      "disp "
+      "dispatch "
+      "display "
+      "divergence "
+      "dlmread "
+      "dlmwrite "
+      "dmperm "
+      "dmult "
+      "do "
+      "do_braindead_shortcircuit_evaluation "
+      "do_string_escapes "
+      "doc "
+      "doc_cache_file "
+      "dos "
+      "dot "
+      "double "
+      "drawnow "
+      "dsearch "
+      "dsearchn "
+      "dump_prefs "
+      "dup2 "
+      "duplication_matrix "
+      "durbinlevinson "
+      "e "
+      "echo "
+      "echo_executing_commands "
+      "edit "
+      "edit_history "
+      "eig "
+      "eigs "
+      "ellipsoid "
+      "else "
+      "elseif "
+      "empirical_cdf "
+      "empirical_inv "
+      "empirical_pdf "
+      "empirical_rnd "
+      "end "
+      "end_try_catch "
+      "end_unwind_protect "
+      "endfor "
+      "endfunction "
+      "endgrent "
+      "endif "
+      "endpwent "
+      "endswitch "
+      "endwhile "
+      "eomday "
+      "eps "
+      "eq "
+      "erf "
+      "erfc "
+      "erfcx "
+      "erfinv "
+      "errno "
+      "errno_list "
+      "error "
+      "error_text "
+      "errorbar "
+      "etime "
+      "etree "
+      "etreeplot "
+      "eval "
+      "evalin "
+      "example "
+      "exec "
+      "exist "
+      "exit "
+      "exp "
+      "expcdf "
+      "expinv "
+      "expm "
+      "expm1 "
+      "exppdf "
+      "exprnd "
+      "eye "
+      "ezcontour "
+      "ezcontourf "
+      "ezmesh "
+      "ezmeshc "
+      "ezplot "
+      "ezplot3 "
+      "ezpolar "
+      "ezsurf "
+      "ezsurfc "
+      "f_test_regression "
+      "factor "
+      "factorial "
+      "fail "
+      "false "
+      "fcdf "
+      "fclear "
+      "fclose "
+      "fcntl "
+      "fdisp "
+      "feather "
+      "feof "
+      "ferror "
+      "feval "
+      "fflush "
+      "fft "
+      "fft2 "
+      "fftconv "
+      "fftfilt "
+      "fftn "
+      "fftshift "
+      "fftw "
+      "fgetl "
+      "fgets "
+      "fieldnames "
+      "figure "
+      "file_in_loadpath "
+      "file_in_path "
+      "fileattrib "
+      "filemarker "
+      "fileparts "
+      "fileread "
+      "filesep "
+      "fill "
+      "filter "
+      "filter2 "
+      "find "
+      "find_dir_in_path "
+      "findall "
+      "findobj "
+      "findstr "
+      "finite "
+      "finv "
+      "fix "
+      "fixed_point_format "
+      "flag "
+      "flipdim "
+      "fliplr "
+      "flipud "
+      "floor "
+      "fminbnd "
+      "fminunc "
+      "fmod "
+      "fnmatch "
+      "fopen "
+      "for "
+      "fork "
+      "format "
+      "formula "
+      "fpdf "
+      "fplot "
+      "fprintf "
+      "fputs "
+      "fractdiff "
+      "fread "
+      "freport "
+      "freqz "
+      "freqz_plot "
+      "frewind "
+      "frnd "
+      "fscanf "
+      "fseek "
+      "fskipl "
+      "fsolve "
+      "fstat "
+      "ftell "
+      "full "
+      "fullfile "
+      "func2str "
+      "function "
+      "functions "
+      "fwrite "
+      "fzero "
+      "gamcdf "
+      "gaminv "
+      "gamma "
+      "gammai "
+      "gammainc "
+      "gammaln "
+      "gampdf "
+      "gamrnd "
+      "gca "
+      "gcbf "
+      "gcbo "
+      "gcd "
+      "gcf "
+      "ge "
+      "gen_doc_cache "
+      "genpath "
+      "genvarname "
+      "geocdf "
+      "geoinv "
+      "geopdf "
+      "geornd "
+      "get "
+      "get_first_help_sentence "
+      "get_help_text "
+      "get_help_text_from_file "
+      "getappdata "
+      "getegid "
+      "getenv "
+      "geteuid "
+      "getfield "
+      "getgid "
+      "getgrent "
+      "getgrgid "
+      "getgrnam "
+      "gethostname "
+      "getpgrp "
+      "getpid "
+      "getppid "
+      "getpwent "
+      "getpwnam "
+      "getpwuid "
+      "getrusage "
+      "getuid "
+      "ginput "
+      "givens "
+      "glob "
+      "global "
+      "glpk "
+      "glpkmex "
+      "gls "
+      "gmap40 "
+      "gmres "
+      "gmtime "
+      "gnuplot_binary "
+      "gplot "
+      "gradient "
+      "graphics_toolkit "
+      "gray "
+      "gray2ind "
+      "grid "
+      "griddata "
+      "griddata3 "
+      "griddatan "
+      "gt "
+      "gtext "
+      "gunzip "
+      "gzip "
+      "hadamard "
+      "hamming "
+      "hankel "
+      "hanning "
+      "help "
+      "hess "
+      "hex2dec "
+      "hex2num "
+      "hggroup "
+      "hidden "
+      "hilb "
+      "hist "
+      "histc "
+      "history "
+      "history_control "
+      "history_file "
+      "history_size "
+      "history_timestamp_format_string "
+      "hold "
+      "home "
+      "horzcat "
+      "hot "
+      "hotelling_test "
+      "hotelling_test_2 "
+      "housh "
+      "hsv "
+      "hsv2rgb "
+      "hurst "
+      "hygecdf "
+      "hygeinv "
+      "hygepdf "
+      "hygernd "
+      "hypot "
+      "i "
+      "idivide "
+      "if "
+      "ifelse "
+      "ifft "
+      "ifft2 "
+      "ifftn "
+      "ifftshift "
+      "ignore_function_time_stamp "
+      "imag "
+      "image "
+      "imagesc "
+      "imfinfo "
+      "imread "
+      "imshow "
+      "imwrite "
+      "ind2gray "
+      "ind2rgb "
+      "ind2sub "
+      "index "
+      "inf "
+      "inferiorto "
+      "info "
+      "info_file "
+      "info_program "
+      "inline "
+      "inpolygon "
+      "input "
+      "inputname "
+      "int16 "
+      "int2str "
+      "int32 "
+      "int64 "
+      "int8 "
+      "interp1 "
+      "interp1q "
+      "interp2 "
+      "interp3 "
+      "interpft "
+      "interpn "
+      "intersect "
+      "intmax "
+      "intmin "
+      "intwarning "
+      "inv "
+      "inverse "
+      "invhilb "
+      "ipermute "
+      "iqr "
+      "is_absolute_filename "
+      "is_duplicate_entry "
+      "is_global "
+      "is_leap_year "
+      "is_rooted_relative_filename "
+      "is_valid_file_id "
+      "isa "
+      "isalnum "
+      "isalpha "
+      "isappdata "
+      "isargout "
+      "isascii "
+      "isbool "
+      "iscell "
+      "iscellstr "
+      "ischar "
+      "iscntrl "
+      "iscolumn "
+      "iscommand "
+      "iscomplex "
+      "isdebugmode "
+      "isdefinite "
+      "isdeployed "
+      "isdigit "
+      "isdir "
+      "isempty "
+      "isequal "
+      "isequalwithequalnans "
+      "isfield "
+      "isfigure "
+      "isfinite "
+      "isfloat "
+      "isglobal "
+      "isgraph "
+      "ishandle "
+      "ishermitian "
+      "ishghandle "
+      "ishold "
+      "isieee "
+      "isindex "
+      "isinf "
+      "isinteger "
+      "iskeyword "
+      "isletter "
+      "islogical "
+      "islower "
+      "ismac "
+      "ismatrix "
+      "ismember "
+      "ismethod "
+      "isna "
+      "isnan "
+      "isnull "
+      "isnumeric "
+      "isobject "
+      "isocolors "
+      "isonormals "
+      "isosurface "
+      "ispc "
+      "isprime "
+      "isprint "
+      "isprop "
+      "ispunct "
+      "israwcommand "
+      "isreal "
+      "isrow "
+      "isscalar "
+      "issorted "
+      "isspace "
+      "issparse "
+      "issquare "
+      "isstr "
+      "isstrprop "
+      "isstruct "
+      "issymmetric "
+      "isunix "
+      "isupper "
+      "isvarname "
+      "isvector "
+      "isxdigit "
+      "j "
+      "jet "
+      "kbhit "
+      "kendall "
+      "keyboard "
+      "kill "
+      "kolmogorov_smirnov_cdf "
+      "kolmogorov_smirnov_test "
+      "kolmogorov_smirnov_test_2 "
+      "kron "
+      "kruskal_wallis_test "
+      "krylov "
+      "krylovb "
+      "kurtosis "
+      "laplace_cdf "
+      "laplace_inv "
+      "laplace_pdf "
+      "laplace_rnd "
+      "lasterr "
+      "lasterror "
+      "lastwarn "
+      "lchol "
+      "lcm "
+      "ldivide "
+      "le "
+      "legend "
+      "legendre "
+      "length "
+      "lgamma "
+      "license "
+      "lin2mu "
+      "line "
+      "link "
+      "linkprop "
+      "linspace "
+      "list "
+      "list_in_columns "
+      "list_primes "
+      "load "
+      "loadaudio "
+      "loadimage "
+      "loadobj "
+      "localtime "
+      "log "
+      "log10 "
+      "log1p "
+      "log2 "
+      "logical "
+      "logistic_cdf "
+      "logistic_inv "
+      "logistic_pdf "
+      "logistic_regression "
+      "logistic_rnd "
+      "logit "
+      "loglog "
+      "loglogerr "
+      "logm "
+      "logncdf "
+      "logninv "
+      "lognpdf "
+      "lognrnd "
+      "logspace "
+      "lookfor "
+      "lookup "
+      "lower "
+      "ls "
+      "ls_command "
+      "lsode "
+      "lsode_options "
+      "lsqnonneg "
+      "lstat "
+      "lt "
+      "lu "
+      "luinc "
+      "luupdate "
+      "magic "
+      "mahalanobis "
+      "make_absolute_filename "
+      "makeinfo_program "
+      "manova "
+      "mark_as_command "
+      "mark_as_rawcommand "
+      "mat2cell "
+      "mat2str "
+      "matlabroot "
+      "matrix_type "
+      "max "
+      "max_recursion_depth "
+      "mcnemar_test "
+      "md5sum "
+      "mean "
+      "meansq "
+      "median "
+      "menu "
+      "merge "
+      "mesh "
+      "meshc "
+      "meshgrid "
+      "meshz "
+      "methods "
+      "mex "
+      "mexext "
+      "mfilename "
+      "mgorth "
+      "min "
+      "minus "
+      "mislocked "
+      "missing_function_hook "
+      "mist "
+      "mkdir "
+      "mkfifo "
+      "mkoctfile "
+      "mkpp "
+      "mkstemp "
+      "mktime "
+      "mldivide "
+      "mlock "
+      "mod "
+      "mode "
+      "moment "
+      "more "
+      "most "
+      "movefile "
+      "mpoles "
+      "mpower "
+      "mrdivide "
+      "mtimes "
+      "mu2lin "
+      "munlock "
+      "namelengthmax "
+      "nan "
+      "nargchk "
+      "nargin "
+      "nargout "
+      "nargoutchk "
+      "native_float_format "
+      "nbincdf "
+      "nbininv "
+      "nbinpdf "
+      "nbinrnd "
+      "nchoosek "
+      "ndgrid "
+      "ndims "
+      "ne "
+      "newplot "
+      "news "
+      "nextpow2 "
+      "nfields "
+      "nnz "
+      "nonzeros "
+      "norm "
+      "normcdf "
+      "normest "
+      "norminv "
+      "normpdf "
+      "normrnd "
+      "not "
+      "now "
+      "nproc "
+      "nth_element "
+      "nthroot "
+      "ntsc2rgb "
+      "null "
+      "num2cell "
+      "num2hex "
+      "num2str "
+      "numel "
+      "nzmax "
+      "ocean "
+      "octave_config_info "
+      "octave_core_file_limit "
+      "octave_core_file_name "
+      "octave_core_file_options "
+      "octave_tmp_file_name "
+      "ols "
+      "onCleanup "
+      "onenormest "
+      "ones "
+      "optimget "
+      "optimize_subsasgn_calls "
+      "optimset "
+      "or "
+      "orderfields "
+      "orient "
+      "orth "
+      "otherwise "
+      "output_max_field_width "
+      "output_precision "
+      "pack "
+      "page_output_immediately "
+      "page_screen_output "
+      "paren "
+      "pareto "
+      "parseparams "
+      "pascal "
+      "patch "
+      "path "
+      "pathdef "
+      "pathsep "
+      "pause "
+      "pbaspect "
+      "pcg "
+      "pchip "
+      "pclose "
+      "pcolor "
+      "pcr "
+      "peaks "
+      "periodogram "
+      "perl "
+      "perms "
+      "permute "
+      "perror "
+      "persistent "
+      "pi "
+      "pie "
+      "pie3 "
+      "pink "
+      "pinv "
+      "pipe "
+      "pkg "
+      "planerot "
+      "playaudio "
+      "plot "
+      "plot3 "
+      "plotmatrix "
+      "plotyy "
+      "plus "
+      "poisscdf "
+      "poissinv "
+      "poisspdf "
+      "poissrnd "
+      "pol2cart "
+      "polar "
+      "poly "
+      "polyaffine "
+      "polyarea "
+      "polyder "
+      "polyderiv "
+      "polyfit "
+      "polygcd "
+      "polyint "
+      "polyout "
+      "polyreduce "
+      "polyval "
+      "polyvalm "
+      "popen "
+      "popen2 "
+      "postpad "
+      "pow2 "
+      "power "
+      "powerset "
+      "ppder "
+      "ppint "
+      "ppjumps "
+      "ppplot "
+      "ppval "
+      "pqpnonneg "
+      "prctile "
+      "prepad "
+      "primes "
+      "print "
+      "print_empty_dimensions "
+      "print_struct_array_contents "
+      "print_usage "
+      "printf "
+      "prism "
+      "probit "
+      "prod "
+      "program_invocation_name "
+      "program_name "
+      "prop_test_2 "
+      "putenv "
+      "puts "
+      "pwd "
+      "qp "
+      "qqplot "
+      "qr "
+      "qrdelete "
+      "qrinsert "
+      "qrshift "
+      "qrupdate "
+      "quad "
+      "quad_options "
+      "quadcc "
+      "quadgk "
+      "quadl "
+      "quadv "
+      "quantile "
+      "quit "
+      "quiver "
+      "quiver3 "
+      "qz "
+      "qzhess "
+      "rainbow "
+      "rand "
+      "rande "
+      "randg "
+      "randi "
+      "randn "
+      "randp "
+      "randperm "
+      "range "
+      "rank "
+      "ranks "
+      "rat "
+      "rats "
+      "rcond "
+      "rdivide "
+      "re_read_readline_init_file "
+      "read_readline_init_file "
+      "readdir "
+      "readlink "
+      "real "
+      "reallog "
+      "realmax "
+      "realmin "
+      "realpow "
+      "realsqrt "
+      "record "
+      "rectangle "
+      "rectint "
+      "refresh "
+      "refreshdata "
+      "regexp "
+      "regexpi "
+      "regexprep "
+      "regexptranslate "
+      "rehash "
+      "rem "
+      "remove_input_event_hook "
+      "rename "
+      "repelems "
+      "replot "
+      "repmat "
+      "reset "
+      "reshape "
+      "residue "
+      "resize "
+      "restoredefaultpath "
+      "rethrow "
+      "return "
+      "rgb2hsv "
+      "rgb2ind "
+      "rgb2ntsc "
+      "ribbon "
+      "rindex "
+      "rmappdata "
+      "rmdir "
+      "rmfield "
+      "rmpath "
+      "roots "
+      "rose "
+      "rosser "
+      "rot90 "
+      "rotdim "
+      "round "
+      "roundb "
+      "rows "
+      "rref "
+      "rsf2csf "
+      "run "
+      "run_count "
+      "run_history "
+      "run_test "
+      "rundemos "
+      "runlength "
+      "runtests "
+      "save "
+      "save_header_format_string "
+      "save_precision "
+      "saveas "
+      "saveaudio "
+      "saveimage "
+      "saveobj "
+      "savepath "
+      "saving_history "
+      "scanf "
+      "scatter "
+      "scatter3 "
+      "schur "
+      "sec "
+      "secd "
+      "sech "
+      "semicolon "
+      "semilogx "
+      "semilogxerr "
+      "semilogy "
+      "semilogyerr "
+      "set "
+      "setappdata "
+      "setaudio "
+      "setdiff "
+      "setenv "
+      "setfield "
+      "setgrent "
+      "setpwent "
+      "setstr "
+      "setxor "
+      "shading "
+      "shell_cmd "
+      "shg "
+      "shift "
+      "shiftdim "
+      "sighup_dumps_octave_core "
+      "sign "
+      "sign_test "
+      "sigterm_dumps_octave_core "
+      "silent_functions "
+      "sin "
+      "sinc "
+      "sind "
+      "sinetone "
+      "sinewave "
+      "single "
+      "sinh "
+      "size "
+      "size_equal "
+      "sizemax "
+      "sizeof "
+      "skewness "
+      "sleep "
+      "slice "
+      "sombrero "
+      "sort "
+      "sortrows "
+      "source "
+      "spalloc "
+      "sparse "
+      "sparse_auto_mutate "
+      "spatan2 "
+      "spaugment "
+      "spchol "
+      "spchol2inv "
+      "spcholinv "
+      "spconvert "
+      "spcumprod "
+      "spcumsum "
+      "spdet "
+      "spdiag "
+      "spdiags "
+      "spearman "
+      "spectral_adf "
+      "spectral_xdf "
+      "specular "
+      "speed "
+      "spencer "
+      "speye "
+      "spfind "
+      "spfun "
+      "sph2cart "
+      "sphcat "
+      "sphere "
+      "spinmap "
+      "spinv "
+      "spkron "
+      "splchol "
+      "spline "
+      "split "
+      "split_long_rows "
+      "splu "
+      "spmax "
+      "spmin "
+      "spones "
+      "spparms "
+      "spprod "
+      "spqr "
+      "sprand "
+      "sprandn "
+      "sprandsym "
+      "sprank "
+      "spring "
+      "sprintf "
+      "spstats "
+      "spsum "
+      "spsumsq "
+      "spvcat "
+      "spy "
+      "sqp "
+      "sqrt "
+      "sqrtm "
+      "squeeze "
+      "sscanf "
+      "stairs "
+      "stat "
+      "static "
+      "statistics "
+      "std "
+      "stderr "
+      "stdin "
+      "stdnormal_cdf "
+      "stdnormal_inv "
+      "stdnormal_pdf "
+      "stdnormal_rnd "
+      "stdout "
+      "stem "
+      "stem3 "
+      "stft "
+      "str2double "
+      "str2func "
+      "str2mat "
+      "str2num "
+      "strcat "
+      "strchr "
+      "strcmp "
+      "strcmpi "
+      "strerror "
+      "strfind "
+      "strftime "
+      "string_fill_char "
+      "strjust "
+      "strmatch "
+      "strncmp "
+      "strncmpi "
+      "strptime "
+      "strread "
+      "strrep "
+      "strsplit "
+      "strtok "
+      "strtrim "
+      "strtrunc "
+      "struct "
+      "struct2cell "
+      "struct_levels_to_print "
+      "structfun "
+      "strvcat "
+      "studentize "
+      "sub2ind "
+      "subplot "
+      "subsasgn "
+      "subsindex "
+      "subspace "
+      "subsref "
+      "substr "
+      "substruct "
+      "sum "
+      "summer "
+      "sumsq "
+      "superiorto "
+      "suppress_verbose_help_message "
+      "surf "
+      "surface "
+      "surfc "
+      "surfl "
+      "surfnorm "
+      "svd "
+      "svd_driver "
+      "svds "
+      "swapbytes "
+      "switch "
+      "syl "
+      "sylvester_matrix "
+      "symamd "
+      "symbfact "
+      "symlink "
+      "symrcm "
+      "symvar "
+      "synthesis "
+      "system "
+      "t_test "
+      "t_test_2 "
+      "t_test_regression "
+      "table "
+      "tan "
+      "tand "
+      "tanh "
+      "tar "
+      "tcdf "
+      "tempdir "
+      "tempname "
+      "terminal_size "
+      "test "
+      "test2 "
+      "test3 "
+      "text "
+      "textread "
+      "textscan "
+      "tic "
+      "tilde_expand "
+      "time "
+      "times "
+      "tinv "
+      "title "
+      "tmpfile "
+      "tmpnam "
+      "toascii "
+      "toc "
+      "toeplitz "
+      "tolower "
+      "toupper "
+      "tpdf "
+      "trace "
+      "transpose "
+      "trapz "
+      "treelayout "
+      "treeplot "
+      "tril "
+      "trimesh "
+      "triplequad "
+      "triplot "
+      "trisurf "
+      "triu "
+      "trnd "
+      "true "
+      "try "
+      "tsearch "
+      "tsearchn "
+      "type "
+      "typecast "
+      "typeinfo "
+      "u_test "
+      "uigetdir "
+      "uigetfile "
+      "uimenu "
+      "uint16 "
+      "uint32 "
+      "uint64 "
+      "uint8 "
+      "uiputfile "
+      "umask "
+      "uminus "
+      "uname "
+      "undo_string_escapes "
+      "unidcdf "
+      "unidinv "
+      "unidpdf "
+      "unidrnd "
+      "unifcdf "
+      "unifinv "
+      "unifpdf "
+      "unifrnd "
+      "union "
+      "unique "
+      "unix "
+      "unlink "
+      "unmark_command "
+      "unmark_rawcommand "
+      "unmkpp "
+      "unpack "
+      "untabify "
+      "untar "
+      "until "
+      "unwind_protect "
+      "unwind_protect_cleanup "
+      "unwrap "
+      "unzip "
+      "uplus "
+      "upper "
+      "urlread "
+      "urlwrite "
+      "usage "
+      "usleep "
+      "validatestring "
+      "values "
+      "vander "
+      "var "
+      "var_test "
+      "varargin "
+      "varargout "
+      "vec "
+      "vech "
+      "vectorize "
+      "ver "
+      "version "
+      "vertcat "
+      "view "
+      "voronoi "
+      "voronoin "
+      "waitforbuttonpress "
+      "waitpid "
+      "warning "
+      "warning_ids "
+      "warranty "
+      "wavread "
+      "wavwrite "
+      "wblcdf "
+      "wblinv "
+      "wblpdf "
+      "wblrnd "
+      "weekday "
+      "weibcdf "
+      "weibinv "
+      "weibpdf "
+      "weibrnd "
+      "welch_test "
+      "what "
+      "which "
+      "while "
+      "white "
+      "whitebg "
+      "who "
+      "whos "
+      "whos_line_format "
+      "wienrnd "
+      "wilcoxon_test "
+      "wilkinson "
+      "winter "
+      "xlabel "
+      "xlim "
+      "xor "
+      "yes_or_no "
+      "ylabel "
+      "ylim "
+      "yulewalker "
+      "z_test "
+      "z_test_2 "
+      "zeros "
+      "zip "
+      "zlabel "
+      "zlim ";
+  /*            "break case catch continue do else elseif end end_unwind_protect "
+              "endfor endfunction endif endswitch endwhile for function "
+              "global if otherwise persistent return switch try until "
+              "unwind_protect unwind_protect_cleanup while";
+  */
+}
new file mode 100644
--- /dev/null
+++ b/libgui/src/resource-manager.h
@@ -0,0 +1,124 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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/>.
+
+*/
+
+#ifndef RESOURCEMANAGER_H
+#define RESOURCEMANAGER_H
+
+#include <QDesktopServices>
+#include <QIcon>
+#include <QMap>
+#include <QSettings>
+#include <QTranslator>
+
+class resource_manager
+{
+protected:
+
+  resource_manager (void);
+
+public:
+
+  ~resource_manager ();
+
+  static QSettings *get_settings (void)
+  {
+    return instance_ok () ? instance->do_get_settings () : 0;
+  }
+
+  static QSettings *get_default_settings (void)
+  {
+    return instance_ok () ? instance->do_get_default_settings () : 0;
+  }
+
+  static QString get_home_path (void)
+  {
+    return instance_ok () ? instance->do_get_home_path () : QString ();
+  }
+
+  static void reload_settings (void)
+  {
+    if (instance_ok ())
+      instance->do_reload_settings ();
+  }
+
+  static void set_settings (const QString& file)
+  {
+    if (instance_ok ())
+      instance->do_set_settings (file);
+  }
+
+  static QString get_gui_translation_dir (void);
+
+  static void config_translators (QTranslator*, QTranslator*);
+
+  static void update_network_settings (void)
+  {
+    if (instance_ok ())
+      instance->do_update_network_settings ();
+  }
+
+  static bool is_first_run (void)
+  {
+    return instance_ok () ? instance->do_is_first_run () : true;
+  }
+
+  static const char *octave_keywords (void);
+
+private:
+
+  static resource_manager *instance;
+
+  static void cleanup_instance (void) { delete instance; instance = 0; }
+
+  // No copying!
+
+  resource_manager (const resource_manager&);
+
+  resource_manager& operator = (const resource_manager&);
+
+  static bool instance_ok (void);
+
+  QSettings *settings;
+
+  QSettings *default_settings;
+
+  QString home_path;
+
+  bool first_run;
+
+  QSettings *do_get_settings (void) const;
+
+  QSettings *do_get_default_settings (void) const;
+
+  QString do_get_home_path (void) const;
+
+  void do_reload_settings (void);
+
+  void do_set_settings (const QString& file);
+
+  void do_update_network_settings (void);
+
+  bool do_is_first_run (void) const;
+
+};
+
+#endif // RESOURCEMANAGER_H
new file mode 100644
--- /dev/null
+++ b/libgui/src/resource.qrc
@@ -0,0 +1,58 @@
+<RCC>
+    <qresource prefix="/actions">
+        <file>icons/artsbuilderexecute.png</file>
+        <file>icons/editcopy.png</file>
+        <file>icons/editcut.png</file>
+        <file>icons/editdelete.png</file>
+        <file>icons/editpaste.png</file>
+        <file>icons/filenew.png</file>
+        <file>icons/fileopen.png</file>
+        <file>icons/filesave.png</file>
+        <file>icons/fileprint.png</file>
+        <file>icons/folder_new.png</file>
+        <file>icons/ok.png</file>
+        <file>icons/redo.png</file>
+        <file>icons/reload.png</file>
+        <file>icons/search.png</file>
+        <file>icons/undo.png</file>
+        <file>icons/up.png</file>
+        <file>icons/configure.png</file>
+        <file>icons/filesaveas.png</file>
+        <file>icons/redled.png</file>
+        <file>icons/arrow_right.png</file>
+        <file>icons/bookmark.png</file>
+        <file>icons/question.png</file>
+        <file>icons/star.png</file>
+        <file>icons/stop.png</file>
+        <file>icons/zoom-in.png</file>
+        <file>icons/zoom-out.png</file>
+        <file>icons/find.png</file>
+        <file>icons/gear.png</file>
+        <file>icons/chat.png</file>
+        <file>icons/help_index.png</file>
+        <file>icons/jabber_protocol.png</file>
+        <file>icons/logo.png</file>
+        <file>icons/terminal.png</file>
+        <file>icons/bp_toggle.png</file>
+        <file>icons/bp_rm_all.png</file>
+        <file>icons/bp_prev.png</file>
+        <file>icons/bp_next.png</file>
+        <file>icons/db_cont.png</file>
+        <file>icons/db_step.png</file>
+        <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>
new file mode 100644
--- /dev/null
+++ b/libgui/src/settings-dialog.cc
@@ -0,0 +1,384 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 "resource-manager.h"
+#include "settings-dialog.h"
+#include "ui-settings-dialog.h"
+#include <QSettings>
+#include <QDir>
+#include <QFileInfo>
+
+#ifdef HAVE_QSCINTILLA
+#include <QScrollArea>
+#include "color-picker.h"
+#include <Qsci/qscilexercpp.h>
+#include <Qsci/qscilexerbash.h>
+#include <Qsci/qscilexerperl.h>
+#include <Qsci/qscilexerbatch.h>
+#include <Qsci/qscilexerdiff.h>
+#endif
+
+settings_dialog::settings_dialog (QWidget *p):
+  QDialog (p), ui (new Ui::settings_dialog)
+{
+  ui->setupUi (this);
+
+  QSettings *settings = resource_manager::get_settings ();
+  // FIXME -- what should happen if settings is 0?
+
+  // look for available language files and the actual settings
+  QString qm_dir_name = resource_manager::get_gui_translation_dir ();
+  QDir qm_dir (qm_dir_name);
+  QFileInfoList qm_files = qm_dir.entryInfoList (QStringList ("*.qm"),
+                                                 QDir::Files | QDir::Readable,
+                                                 QDir::Name);
+  for (int i = 0; i < qm_files.length (); i++)    // insert available languages
+    ui->comboBox_language->addItem (qm_files.at (i).baseName ());
+  ui->comboBox_language->insertItem (0,tr("System setting")); // System at beginning
+  ui->comboBox_language->insertSeparator (1);         // separator after System
+  QString language = settings->value ("language","SYSTEM").toString ();
+  if (language == "SYSTEM")
+    language = tr("System setting");
+  int selected = ui->comboBox_language->findText (language);
+  if (selected >= 0)
+    ui->comboBox_language->setCurrentIndex (selected);
+  else
+    ui->comboBox_language->setCurrentIndex (0);  // System is default
+
+  ui->toolbar_icon_size->setValue (settings->value ("toolbar_icon_size",24).toInt ());
+
+  // which icon has to be selected
+  QString widget_icon_set =
+      settings->value ("DockWidgets/widget_icon_set","NONE").toString ();
+  ui->general_icon_octave-> setChecked (true);  // the default (if invalid set)
+  ui->general_icon_octave-> setChecked (widget_icon_set == "NONE");
+  ui->general_icon_graphic-> setChecked (widget_icon_set == "GRAPHIC");
+  ui->general_icon_letter-> setChecked (widget_icon_set == "LETTER");
+
+  ui->useCustomFileEditor->setChecked (settings->value ("useCustomFileEditor",false).toBool ());
+  ui->customFileEditor->setText (settings->value ("customFileEditor").toString ());
+  ui->editor_showLineNumbers->setChecked (settings->value ("editor/showLineNumbers",true).toBool () );
+  ui->editor_highlightCurrentLine->setChecked (settings->value ("editor/highlightCurrentLine",true).toBool () );
+  ui->editor_codeCompletion->setChecked (settings->value ("editor/codeCompletion",true).toBool () );
+  ui->editor_longWindowTitle->setChecked (settings->value ("editor/longWindowTitle",false).toBool ());
+  ui->editor_restoreSession->setChecked (settings->value ("editor/restoreSession",true).toBool ());
+  ui->terminal_fontName->setCurrentFont (QFont (settings->value ("terminal/fontName","Courier New").toString()) );
+  ui->terminal_fontSize->setValue (settings->value ("terminal/fontSize",10).toInt ());
+  ui->showFileSize->setChecked (settings->value ("filesdockwidget/showFileSize",false).toBool());
+  ui->showFileType->setChecked (settings->value ("filesdockwidget/showFileType",false).toBool());
+  ui->showLastModified->setChecked (settings->value ("filesdockwidget/showLastModified",false).toBool());
+  ui->showHiddenFiles->setChecked (settings->value ("filesdockwidget/showHiddenFiles",false).toBool());
+  ui->useAlternatingRowColors->setChecked (settings->value ("filesdockwidget/useAlternatingRowColors",true).toBool());
+  ui->sync_octave_directory->setChecked (settings->value ("filesdockwidget/sync_octave_directory",true).toBool());
+  ui->useProxyServer->setChecked (settings->value ("useProxyServer",false).toBool ());
+  ui->proxyHostName->setText (settings->value ("proxyHostName").toString ());
+  ui->terminal_cursorBlinking->setChecked (settings->value ("terminal/cursorBlinking",true).toBool ());
+
+  QString cursorType = settings->value ("terminal/cursorType","ibeam").toString ();
+
+  QStringList items;
+  items << QString("0") << QString("1") << QString("2");
+  ui->terminal_cursorType->addItems(items);
+  ui->terminal_cursorType->setItemText (0, "IBeam Cursor");
+  ui->terminal_cursorType->setItemText (1, "Block Cursor");
+  ui->terminal_cursorType->setItemText (2, "Underline Cursor");
+
+  if (cursorType == "ibeam")
+    ui->terminal_cursorType->setCurrentIndex (0);
+  else if (cursorType == "block")
+    ui->terminal_cursorType->setCurrentIndex (1);
+  else if (cursorType == "underline")
+    ui->terminal_cursorType->setCurrentIndex (2);
+
+  int currentIndex = 0;
+  QString proxyTypeString = settings->value ("proxyType").toString ();
+  while ( (currentIndex < ui->proxyType->count ()) && (ui->proxyType->currentText () != proxyTypeString))
+    {
+      currentIndex++;
+      ui->proxyType->setCurrentIndex (currentIndex);
+    }
+
+  ui->proxyPort->setText (settings->value ("proxyPort").toString ());
+  ui->proxyUserName->setText (settings->value ("proxyUserName").toString ());
+  ui->proxyPassword->setText (settings->value ("proxyPassword").toString ());
+
+#ifdef HAVE_QSCINTILLA
+  // editor styles: create lexer, read settings, and create dialog elements
+  QsciLexer *lexer;
+  lexer = new lexer_octave_gui ();
+  read_lexer_settings (lexer,settings);
+  delete lexer;
+  lexer = new QsciLexerCPP ();
+  read_lexer_settings (lexer,settings);
+  delete lexer;
+  lexer = new QsciLexerPerl ();
+  read_lexer_settings (lexer,settings);
+  delete lexer;
+  lexer = new QsciLexerBatch ();
+  read_lexer_settings (lexer,settings);
+  delete lexer;
+  lexer = new QsciLexerDiff ();
+  read_lexer_settings (lexer,settings);
+  delete lexer;
+  lexer = new QsciLexerBash ();
+  read_lexer_settings (lexer,settings);
+  delete lexer;
+#endif    
+}
+
+settings_dialog::~settings_dialog ()
+{
+  delete ui;
+}
+
+
+#ifdef HAVE_QSCINTILLA
+int
+settings_dialog::get_valid_lexer_styles (QsciLexer *lexer, int styles[])
+{
+  int max_style = 0;
+  int actual_style = 0;
+  while (actual_style < MaxStyleNumber && max_style < MaxLexerStyles)
+    {
+      if ((lexer->description(actual_style)) != "")  // valid style
+        styles[max_style++] = actual_style;
+      actual_style++;
+    }
+  return max_style;
+}
+
+void
+settings_dialog::read_lexer_settings (QsciLexer *lexer, QSettings *settings)
+{
+  lexer->readSettings (*settings);
+  int styles[MaxLexerStyles];  // array for saving valid styles (enum is not continuous)
+  int max_style = get_valid_lexer_styles (lexer, styles);
+  QGridLayout *style_grid = new QGridLayout ();
+  QLabel *description[max_style];
+  QFontComboBox *select_font[max_style];
+  QSpinBox *font_size[max_style];
+  QCheckBox *attrib_font[3][max_style];
+  color_picker *color[max_style];
+  int default_size = 10;
+  QFont default_font = QFont ();
+  for (int i = 0; i < max_style; i++)  // create dialog elements for all styles
+    {
+      QString actual_name = lexer->description (styles[i]);
+      QFont   actual_font = lexer->font (styles[i]);
+      description[i] = new QLabel (actual_name);
+      description[i]->setWordWrap (true);
+      description[i]->setMaximumSize (180,QWIDGETSIZE_MAX);
+      description[i]->setMinimumSize (180,1);
+      select_font[i] = new QFontComboBox ();
+      select_font[i]->setObjectName (actual_name+"_font");
+      font_size[i] = new QSpinBox ();
+      font_size[i]->setObjectName (actual_name+"_size");
+      if (styles[i] == 0) // the default
+        {
+          select_font[i]->setCurrentFont (actual_font);
+          default_font = actual_font;
+          font_size[i]->setRange (6,24);
+          default_size = actual_font.pointSize ();
+          font_size[i]->setValue (default_size);
+        }
+      else   // other styles
+        {
+          select_font[i]->setCurrentFont (actual_font);
+          if (actual_font.family () == default_font.family ())
+            select_font[i]->setEditText (lexer->description (0));
+          font_size[i]->setRange (-4,4);
+          font_size[i]->setValue (actual_font.pointSize ()-default_size);
+          font_size[i]->setToolTip ("Difference to the defalt size");
+        }
+      attrib_font[0][i] = new QCheckBox (tr("b"));
+      attrib_font[1][i] = new QCheckBox (tr("i"));
+      attrib_font[2][i] = new QCheckBox (tr("u"));
+      attrib_font[0][i]->setChecked(Qt::Checked && actual_font.bold ());
+      attrib_font[0][i]->setObjectName (actual_name+"_bold");
+      attrib_font[1][i]->setChecked(Qt::Checked && actual_font.italic ());
+      attrib_font[1][i]->setObjectName (actual_name+"_italic");
+      attrib_font[2][i]->setChecked(Qt::Checked && actual_font.underline ());
+      attrib_font[2][i]->setObjectName (actual_name+"_underline");
+      color[i] = new color_picker (lexer->color (styles[i]));
+      color[i]->setObjectName (actual_name+"_color");
+      int column = 1;
+      style_grid->addWidget (description[i],   i,column++);
+      style_grid->addWidget (select_font[i],   i,column++);
+      style_grid->addWidget (font_size[i],     i,column++);
+      style_grid->addWidget (attrib_font[0][i],i,column++);
+      style_grid->addWidget (attrib_font[1][i],i,column++);
+      style_grid->addWidget (attrib_font[2][i],i,column++);
+      style_grid->addWidget (color[i],         i,column++);
+    }
+  // place grid with elements into the tab
+  QScrollArea *scroll_area = new QScrollArea ();
+  QWidget *scroll_area_contents = new QWidget ();
+  scroll_area_contents->setObjectName (QString (lexer->language ())+"_styles");
+  scroll_area_contents->setLayout (style_grid);
+  scroll_area->setWidget (scroll_area_contents);
+  ui->tabs_editor_styles->addTab (scroll_area,lexer->language ());
+}
+#endif  
+
+
+void
+settings_dialog::write_changed_settings ()
+{
+  QSettings *settings = resource_manager::get_settings ();
+  // FIXME -- what should happen if settings is 0?
+
+  // the icon set
+  QString widget_icon_set = "NONE";
+  if (ui->general_icon_letter->isChecked ())
+    widget_icon_set = "LETTER";
+  else if (ui->general_icon_graphic->isChecked ())
+    widget_icon_set = "GRAPHIC";
+  settings->setValue ("DockWidgets/widget_icon_set",widget_icon_set);
+
+  // language
+  QString language = ui->comboBox_language->currentText ();
+  if (language == tr("System setting"))
+    language = "SYSTEM";
+  settings->setValue ("language", language);
+
+  // other settings
+  settings->setValue ("toolbar_icon_size", ui->toolbar_icon_size->value ());
+  settings->setValue ("useCustomFileEditor", ui->useCustomFileEditor->isChecked ());
+  settings->setValue ("customFileEditor", ui->customFileEditor->text ());
+  settings->setValue ("editor/showLineNumbers", ui->editor_showLineNumbers->isChecked ());
+  settings->setValue ("editor/highlightCurrentLine", ui->editor_highlightCurrentLine->isChecked ());
+  settings->setValue ("editor/codeCompletion", ui->editor_codeCompletion->isChecked ());
+  settings->setValue ("editor/longWindowTitle", ui->editor_longWindowTitle->isChecked());
+  settings->setValue ("editor/restoreSession", ui->editor_restoreSession->isChecked ());
+  settings->setValue ("terminal/fontSize", ui->terminal_fontSize->value());
+  settings->setValue ("terminal/fontName", ui->terminal_fontName->currentFont().family());
+  settings->setValue ("filesdockwidget/showFileSize", ui->showFileSize->isChecked ());
+  settings->setValue ("filesdockwidget/showFileType", ui->showFileType->isChecked ());
+  settings->setValue ("filesdockwidget/showLastModified", ui->showLastModified->isChecked ());
+  settings->setValue ("filesdockwidget/showHiddenFiles", ui->showHiddenFiles->isChecked ());
+  settings->setValue ("filesdockwidget/useAlternatingRowColors", ui->useAlternatingRowColors->isChecked ());
+  settings->setValue ("filesdockwidget/sync_octave_directory", ui->sync_octave_directory->isChecked ());
+  settings->setValue ("useProxyServer", ui->useProxyServer->isChecked ());
+  settings->setValue ("proxyType", ui->proxyType->currentText ());
+  settings->setValue ("proxyHostName", ui->proxyHostName->text ());
+  settings->setValue ("proxyPort", ui->proxyPort->text ());
+  settings->setValue ("proxyUserName", ui->proxyUserName->text ());
+  settings->setValue ("proxyPassword", ui->proxyPassword->text ());
+  settings->setValue ("terminal/cursorBlinking", ui->terminal_cursorBlinking->isChecked ());
+
+  // the cursor
+  QString cursorType;
+  switch (ui->terminal_cursorType->currentIndex ())
+    {
+    case 0: cursorType = "ibeam"; break;
+    case 1: cursorType = "block"; break;
+    case 2: cursorType = "underline";  break;
+    }
+  settings->setValue ("terminal/cursorType", cursorType);
+  settings->sync ();
+
+#ifdef HAVE_QSCINTILLA
+  // editor styles: create lexer, get dialog contents, and write settings
+  QsciLexer *lexer;
+  lexer = new lexer_octave_gui ();
+  write_lexer_settings (lexer,settings);
+  delete lexer;
+  lexer = new QsciLexerCPP ();
+  write_lexer_settings (lexer,settings);
+  delete lexer;
+  lexer = new QsciLexerPerl ();
+  write_lexer_settings (lexer,settings);
+  delete lexer;
+  lexer = new QsciLexerBatch ();
+  write_lexer_settings (lexer,settings);
+  delete lexer;
+  lexer = new QsciLexerDiff ();
+  write_lexer_settings (lexer,settings);
+  delete lexer;
+  lexer = new QsciLexerBash ();
+  write_lexer_settings (lexer,settings);
+  delete lexer;
+#endif
+}
+
+#ifdef HAVE_QSCINTILLA
+void
+settings_dialog::write_lexer_settings (QsciLexer *lexer, QSettings *settings)
+{
+  QWidget *tab = ui->tabs_editor_styles->
+            findChild <QWidget *>(QString (lexer->language ())+"_styles");
+  int styles[MaxLexerStyles];  // array for saving valid styles (enum is not continuous)
+  int max_style = get_valid_lexer_styles (lexer, styles);
+  QFontComboBox *select_font;
+  QSpinBox *font_size;
+  QCheckBox *attrib_font[3];
+  color_picker *color;
+  int default_size = 10;
+  QFont default_font = QFont ("Courier New",10,-1,0);
+  for (int i = 0; i < max_style; i++)  // get dialog elements and their contents
+    {
+      QString actual_name = lexer->description (styles[i]);
+      select_font    = tab->findChild <QFontComboBox *>(actual_name+"_font");
+      font_size      = tab->findChild <QSpinBox *>(actual_name+"_size");
+      attrib_font[0] = tab->findChild <QCheckBox *>(actual_name+"_bold");
+      attrib_font[1] = tab->findChild <QCheckBox *>(actual_name+"_italic");
+      attrib_font[2] = tab->findChild <QCheckBox *>(actual_name+"_underline");
+      color          = tab->findChild <color_picker *>(actual_name+"_color");
+      QFont new_font = default_font;
+      if (select_font)
+        {
+          new_font = select_font->currentFont ();
+          if (styles[i] == 0)
+            default_font = new_font;
+          else
+            if (select_font->currentText () == lexer->description (0))
+              new_font = default_font;
+        }
+      if (font_size)
+        {
+          if (styles[i] == 0)
+            {
+              default_size = font_size->value ();
+              new_font.setPointSize (font_size->value ());
+            }
+          else
+            new_font.setPointSize (font_size->value ()+default_size);
+        }
+      if (attrib_font[0])
+        new_font.setBold (attrib_font[0]->isChecked ());
+      if (attrib_font[1])
+        new_font.setItalic (attrib_font[1]->isChecked ());
+      if (attrib_font[2])
+        new_font.setUnderline (attrib_font[2]->isChecked ());
+      lexer->setFont (new_font,styles[i]);
+      if (styles[i] == 0)
+        lexer->setDefaultFont (new_font);
+      if (color)
+        lexer->setColor (color->color (),styles[i]);
+    }
+  lexer->writeSettings (*settings);
+}
+#endif
new file mode 100644
--- /dev/null
+++ b/libgui/src/settings-dialog.h
@@ -0,0 +1,54 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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/>.
+
+*/
+
+#ifndef SETTINGSDIALOG_H
+#define SETTINGSDIALOG_H
+
+#include <QDialog>
+#ifdef HAVE_QSCINTILLA
+#include "lexer-octave-gui.h"
+#endif
+
+namespace Ui
+{
+  class settings_dialog;
+}
+
+class settings_dialog:public QDialog
+{
+  Q_OBJECT public:
+  explicit settings_dialog (QWidget * parent);
+  ~settings_dialog ();
+  void write_changed_settings ();
+
+private:
+  Ui::settings_dialog * ui;
+#ifdef HAVE_QSCINTILLA
+  void read_lexer_settings (QsciLexer *lexer, QSettings *settings);
+  void write_lexer_settings (QsciLexer *lexer, QSettings *settings);
+  int  get_valid_lexer_styles (QsciLexer *lexer, int styles[]);
+  enum { MaxLexerStyles = 64,
+         MaxStyleNumber = 128 };
+#endif
+};
+
+#endif // SETTINGSDIALOG_H
new file mode 100644
--- /dev/null
+++ b/libgui/src/settings-dialog.ui
@@ -0,0 +1,857 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>settings_dialog</class>
+ <widget class="QDialog" name="settings_dialog">
+  <property name="windowModality">
+   <enum>Qt::ApplicationModal</enum>
+  </property>
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>700</width>
+    <height>480</height>
+   </rect>
+  </property>
+  <property name="minimumSize">
+   <size>
+    <width>700</width>
+    <height>480</height>
+   </size>
+  </property>
+  <property name="maximumSize">
+   <size>
+    <width>700</width>
+    <height>480</height>
+   </size>
+  </property>
+  <property name="windowTitle">
+   <string>Settings</string>
+  </property>
+  <layout class="QVBoxLayout" name="verticalLayout_2">
+   <item>
+    <widget class="QTabWidget" name="tabWidget">
+     <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="QWidget" name="verticalLayoutWidget">
+       <property name="geometry">
+        <rect>
+         <x>9</x>
+         <y>10</y>
+         <width>651</width>
+         <height>371</height>
+        </rect>
+       </property>
+       <layout class="QVBoxLayout" name="verticalLayout_7">
+        <item>
+         <layout class="QGridLayout" name="gridLayout">
+          <item row="3" column="0">
+           <widget class="QLabel" name="label_9">
+            <property name="text">
+             <string>Icon set for dock widgets</string>
+            </property>
+           </widget>
+          </item>
+          <item row="1" column="0">
+           <widget class="QLabel" name="label_2">
+            <property name="text">
+             <string>Language (requires restart)</string>
+            </property>
+           </widget>
+          </item>
+          <item row="2" column="0">
+           <widget class="QLabel" name="label_8">
+            <property name="text">
+             <string>Icon size</string>
+            </property>
+           </widget>
+          </item>
+          <item row="2" column="2">
+           <layout class="QHBoxLayout" name="horizontalLayout_6">
+            <item>
+             <widget class="QSpinBox" name="toolbar_icon_size">
+              <property name="minimum">
+               <number>16</number>
+              </property>
+              <property name="maximum">
+               <number>32</number>
+              </property>
+              <property name="singleStep">
+               <number>4</number>
+              </property>
+              <property name="value">
+               <number>24</number>
+              </property>
+             </widget>
+            </item>
+            <item>
+             <spacer name="horizontalSpacer_4">
+              <property name="orientation">
+               <enum>Qt::Horizontal</enum>
+              </property>
+              <property name="sizeHint" stdset="0">
+               <size>
+                <width>40</width>
+                <height>20</height>
+               </size>
+              </property>
+             </spacer>
+            </item>
+           </layout>
+          </item>
+          <item row="1" column="2">
+           <layout class="QHBoxLayout" name="horizontalLayout_8">
+            <item>
+             <widget class="QComboBox" name="comboBox_language">
+              <property name="insertPolicy">
+               <enum>QComboBox::InsertAtBottom</enum>
+              </property>
+             </widget>
+            </item>
+            <item>
+             <spacer name="horizontalSpacer_3">
+              <property name="orientation">
+               <enum>Qt::Horizontal</enum>
+              </property>
+              <property name="sizeHint" stdset="0">
+               <size>
+                <width>40</width>
+                <height>20</height>
+               </size>
+              </property>
+             </spacer>
+            </item>
+           </layout>
+          </item>
+          <item row="3" column="2">
+           <layout class="QHBoxLayout" name="horizontalLayout_9">
+            <item>
+             <widget class="QRadioButton" name="general_icon_octave">
+              <property name="text">
+               <string>Octave logo only</string>
+              </property>
+              <property name="checked">
+               <bool>true</bool>
+              </property>
+             </widget>
+            </item>
+            <item>
+             <widget class="QRadioButton" name="general_icon_letter">
+              <property name="text">
+               <string>Letter icons</string>
+              </property>
+             </widget>
+            </item>
+            <item>
+             <widget class="QRadioButton" name="general_icon_graphic">
+              <property name="text">
+               <string>Graphic  icons</string>
+              </property>
+             </widget>
+            </item>
+            <item>
+             <spacer name="horizontalSpacer_6">
+              <property name="orientation">
+               <enum>Qt::Horizontal</enum>
+              </property>
+              <property name="sizeHint" stdset="0">
+               <size>
+                <width>40</width>
+                <height>20</height>
+               </size>
+              </property>
+             </spacer>
+            </item>
+           </layout>
+          </item>
+         </layout>
+        </item>
+        <item>
+         <spacer name="verticalSpacer_4">
+          <property name="orientation">
+           <enum>Qt::Vertical</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>20</width>
+            <height>40</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+       </layout>
+      </widget>
+     </widget>
+     <widget class="QWidget" name="tab">
+      <attribute name="title">
+       <string>Editor</string>
+      </attribute>
+      <layout class="QVBoxLayout" name="verticalLayout_6">
+       <item>
+        <layout class="QVBoxLayout" name="verticalLayout_5">
+         <item>
+          <layout class="QHBoxLayout" name="horizontalLayout_4"/>
+         </item>
+         <item>
+          <widget class="QCheckBox" name="editor_showLineNumbers">
+           <property name="enabled">
+            <bool>true</bool>
+           </property>
+           <property name="text">
+            <string>Show line numbers</string>
+           </property>
+          </widget>
+         </item>
+         <item>
+          <widget class="QCheckBox" name="editor_highlightCurrentLine">
+           <property name="enabled">
+            <bool>true</bool>
+           </property>
+           <property name="text">
+            <string>Highlight current line</string>
+           </property>
+          </widget>
+         </item>
+         <item>
+          <widget class="QCheckBox" name="editor_codeCompletion">
+           <property name="enabled">
+            <bool>true</bool>
+           </property>
+           <property name="text">
+            <string>Code completion</string>
+           </property>
+           <property name="checked">
+            <bool>false</bool>
+           </property>
+          </widget>
+         </item>
+         <item>
+          <widget class="QCheckBox" name="editor_longWindowTitle">
+           <property name="text">
+            <string>Show complete path in window title</string>
+           </property>
+          </widget>
+         </item>
+         <item>
+          <widget class="QCheckBox" name="editor_restoreSession">
+           <property name="text">
+            <string>Restore tabs from previous session on startup</string>
+           </property>
+          </widget>
+         </item>
+        </layout>
+       </item>
+       <item>
+        <spacer name="verticalSpacer">
+         <property name="orientation">
+          <enum>Qt::Vertical</enum>
+         </property>
+         <property name="sizeHint" stdset="0">
+          <size>
+           <width>20</width>
+           <height>40</height>
+          </size>
+         </property>
+        </spacer>
+       </item>
+       <item>
+        <widget class="QCheckBox" name="useCustomFileEditor">
+         <property name="enabled">
+          <bool>true</bool>
+         </property>
+         <property name="text">
+          <string>Use custom file editor</string>
+         </property>
+        </widget>
+       </item>
+       <item>
+        <layout class="QHBoxLayout" name="horizontalLayout">
+         <item>
+          <widget class="QLabel" name="customEditorLabel">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
+           <property name="text">
+            <string>Command  line (%f=file, %l=line):</string>
+           </property>
+          </widget>
+         </item>
+         <item>
+          <widget class="QLineEdit" name="customFileEditor">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
+           <property name="text">
+            <string>emacs</string>
+           </property>
+          </widget>
+         </item>
+        </layout>
+       </item>
+      </layout>
+     </widget>
+     <widget class="QWidget" name="tab_6">
+      <attribute name="title">
+       <string>Editor Styles</string>
+      </attribute>
+      <widget class="QTabWidget" name="tabs_editor_styles">
+       <property name="geometry">
+        <rect>
+         <x>2</x>
+         <y>9</y>
+         <width>671</width>
+         <height>381</height>
+        </rect>
+       </property>
+      </widget>
+     </widget>
+     <widget class="QWidget" name="tab_5">
+      <attribute name="title">
+       <string>Terminal</string>
+      </attribute>
+      <layout class="QVBoxLayout" name="verticalLayout">
+       <item>
+        <layout class="QHBoxLayout" name="horizontalLayout_5">
+         <item>
+          <widget class="QLabel" name="label_11">
+           <property name="text">
+            <string>Font</string>
+           </property>
+          </widget>
+         </item>
+         <item>
+          <widget class="QFontComboBox" name="terminal_fontName">
+           <property name="editable">
+            <bool>false</bool>
+           </property>
+           <property name="fontFilters">
+            <set>QFontComboBox::MonospacedFonts</set>
+           </property>
+          </widget>
+         </item>
+         <item>
+          <widget class="QLabel" name="label_12">
+           <property name="text">
+            <string>Font Size</string>
+           </property>
+          </widget>
+         </item>
+         <item>
+          <widget class="QSpinBox" name="terminal_fontSize">
+           <property name="minimum">
+            <number>2</number>
+           </property>
+           <property name="maximum">
+            <number>96</number>
+           </property>
+           <property name="value">
+            <number>10</number>
+           </property>
+          </widget>
+         </item>
+         <item>
+          <spacer name="horizontalSpacer_5">
+           <property name="orientation">
+            <enum>Qt::Horizontal</enum>
+           </property>
+           <property name="sizeHint" stdset="0">
+            <size>
+             <width>40</width>
+             <height>20</height>
+            </size>
+           </property>
+          </spacer>
+         </item>
+        </layout>
+       </item>
+       <item>
+        <layout class="QHBoxLayout" name="horizontalLayout_3">
+         <item>
+          <widget class="QLabel" name="label">
+           <property name="text">
+            <string>Cursor type:</string>
+           </property>
+          </widget>
+         </item>
+         <item>
+          <widget class="QComboBox" name="terminal_cursorType"/>
+         </item>
+         <item>
+          <spacer name="horizontalSpacer">
+           <property name="orientation">
+            <enum>Qt::Horizontal</enum>
+           </property>
+           <property name="sizeHint" stdset="0">
+            <size>
+             <width>40</width>
+             <height>20</height>
+            </size>
+           </property>
+          </spacer>
+         </item>
+        </layout>
+       </item>
+       <item>
+        <layout class="QHBoxLayout" name="horizontalLayout_2">
+         <item>
+          <widget class="QCheckBox" name="terminal_cursorBlinking">
+           <property name="text">
+            <string>Cursor blinking</string>
+           </property>
+          </widget>
+         </item>
+         <item>
+          <spacer name="horizontalSpacer_2">
+           <property name="orientation">
+            <enum>Qt::Horizontal</enum>
+           </property>
+           <property name="sizeHint" stdset="0">
+            <size>
+             <width>40</width>
+             <height>20</height>
+            </size>
+           </property>
+          </spacer>
+         </item>
+        </layout>
+       </item>
+       <item>
+        <spacer name="verticalSpacer_3">
+         <property name="orientation">
+          <enum>Qt::Vertical</enum>
+         </property>
+         <property name="sizeHint" stdset="0">
+          <size>
+           <width>20</width>
+           <height>321</height>
+          </size>
+         </property>
+        </spacer>
+       </item>
+      </layout>
+     </widget>
+     <widget class="QWidget" name="tab_2">
+      <attribute name="title">
+       <string>File Browser</string>
+      </attribute>
+      <layout class="QVBoxLayout" name="verticalLayout_3">
+       <item>
+        <widget class="QCheckBox" name="showFileSize">
+         <property name="text">
+          <string>Show file size</string>
+         </property>
+        </widget>
+       </item>
+       <item>
+        <widget class="QCheckBox" name="showFileType">
+         <property name="text">
+          <string>Show file type</string>
+         </property>
+        </widget>
+       </item>
+       <item>
+        <widget class="QCheckBox" name="showLastModified">
+         <property name="text">
+          <string>Show date of last modification</string>
+         </property>
+        </widget>
+       </item>
+       <item>
+        <widget class="QCheckBox" name="showHiddenFiles">
+         <property name="text">
+          <string>Show hidden files</string>
+         </property>
+        </widget>
+       </item>
+       <item>
+        <widget class="QCheckBox" name="sync_octave_directory">
+         <property name="text">
+          <string>Synchronize octave directory with the file browser</string>
+         </property>
+        </widget>
+       </item>
+       <item>
+        <widget class="QCheckBox" name="useAlternatingRowColors">
+         <property name="text">
+          <string>Alternating row colors</string>
+         </property>
+        </widget>
+       </item>
+       <item>
+        <spacer name="verticalSpacer_2">
+         <property name="orientation">
+          <enum>Qt::Vertical</enum>
+         </property>
+         <property name="sizeHint" stdset="0">
+          <size>
+           <width>20</width>
+           <height>360</height>
+          </size>
+         </property>
+        </spacer>
+       </item>
+      </layout>
+     </widget>
+     <widget class="QWidget" name="tab_3">
+      <attribute name="title">
+       <string>Network</string>
+      </attribute>
+      <layout class="QVBoxLayout" name="verticalLayout_4">
+       <item>
+        <widget class="QCheckBox" name="useProxyServer">
+         <property name="text">
+          <string>Use proxy server</string>
+         </property>
+        </widget>
+       </item>
+       <item>
+        <layout class="QFormLayout" name="formLayout">
+         <item row="0" column="0">
+          <widget class="QLabel" name="label_3">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
+           <property name="text">
+            <string>Proxy Type:</string>
+           </property>
+          </widget>
+         </item>
+         <item row="0" column="1">
+          <widget class="QComboBox" name="proxyType">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
+           <item>
+            <property name="text">
+             <string>HttpProxy</string>
+            </property>
+           </item>
+           <item>
+            <property name="text">
+             <string>Socks5Proxy</string>
+            </property>
+           </item>
+          </widget>
+         </item>
+         <item row="1" column="0">
+          <widget class="QLabel" name="label_4">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
+           <property name="text">
+            <string>Hostname:</string>
+           </property>
+          </widget>
+         </item>
+         <item row="1" column="1">
+          <widget class="QLineEdit" name="proxyHostName">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
+          </widget>
+         </item>
+         <item row="2" column="0">
+          <widget class="QLabel" name="label_5">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
+           <property name="text">
+            <string>Port:</string>
+           </property>
+          </widget>
+         </item>
+         <item row="2" column="1">
+          <widget class="QLineEdit" name="proxyPort">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
+          </widget>
+         </item>
+         <item row="3" column="0">
+          <widget class="QLabel" name="label_6">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
+           <property name="text">
+            <string>Username:</string>
+           </property>
+          </widget>
+         </item>
+         <item row="3" column="1">
+          <widget class="QLineEdit" name="proxyUserName">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
+          </widget>
+         </item>
+         <item row="4" column="0">
+          <widget class="QLabel" name="label_7">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
+           <property name="text">
+            <string>Password:</string>
+           </property>
+          </widget>
+         </item>
+         <item row="4" column="1">
+          <widget class="QLineEdit" name="proxyPassword">
+           <property name="enabled">
+            <bool>false</bool>
+           </property>
+           <property name="echoMode">
+            <enum>QLineEdit::Password</enum>
+           </property>
+          </widget>
+         </item>
+        </layout>
+       </item>
+      </layout>
+     </widget>
+    </widget>
+   </item>
+   <item>
+    <widget class="QDialogButtonBox" name="buttonBox">
+     <property name="standardButtons">
+      <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+     </property>
+    </widget>
+   </item>
+  </layout>
+ </widget>
+ <resources/>
+ <connections>
+  <connection>
+   <sender>useProxyServer</sender>
+   <signal>toggled(bool)</signal>
+   <receiver>label_4</receiver>
+   <slot>setEnabled(bool)</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>249</x>
+     <y>59</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>69</x>
+     <y>122</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>useProxyServer</sender>
+   <signal>toggled(bool)</signal>
+   <receiver>label_3</receiver>
+   <slot>setEnabled(bool)</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>249</x>
+     <y>59</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>59</x>
+     <y>91</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>useProxyServer</sender>
+   <signal>toggled(bool)</signal>
+   <receiver>label_5</receiver>
+   <slot>setEnabled(bool)</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>249</x>
+     <y>59</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>44</x>
+     <y>152</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>useProxyServer</sender>
+   <signal>toggled(bool)</signal>
+   <receiver>proxyType</receiver>
+   <slot>setEnabled(bool)</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>249</x>
+     <y>59</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>291</x>
+     <y>91</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>useProxyServer</sender>
+   <signal>toggled(bool)</signal>
+   <receiver>proxyHostName</receiver>
+   <slot>setEnabled(bool)</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>249</x>
+     <y>59</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>291</x>
+     <y>124</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>useProxyServer</sender>
+   <signal>toggled(bool)</signal>
+   <receiver>proxyPort</receiver>
+   <slot>setEnabled(bool)</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>249</x>
+     <y>59</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>364</x>
+     <y>154</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>useCustomFileEditor</sender>
+   <signal>toggled(bool)</signal>
+   <receiver>customFileEditor</receiver>
+   <slot>setEnabled(bool)</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>111</x>
+     <y>62</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>343</x>
+     <y>63</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>useProxyServer</sender>
+   <signal>toggled(bool)</signal>
+   <receiver>label_7</receiver>
+   <slot>setEnabled(bool)</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>249</x>
+     <y>59</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>67</x>
+     <y>212</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>useProxyServer</sender>
+   <signal>toggled(bool)</signal>
+   <receiver>proxyUserName</receiver>
+   <slot>setEnabled(bool)</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>249</x>
+     <y>59</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>364</x>
+     <y>184</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>useProxyServer</sender>
+   <signal>toggled(bool)</signal>
+   <receiver>proxyPassword</receiver>
+   <slot>setEnabled(bool)</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>249</x>
+     <y>59</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>364</x>
+     <y>214</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>useProxyServer</sender>
+   <signal>toggled(bool)</signal>
+   <receiver>label_6</receiver>
+   <slot>setEnabled(bool)</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>249</x>
+     <y>59</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>68</x>
+     <y>182</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>buttonBox</sender>
+   <signal>accepted()</signal>
+   <receiver>settings_dialog</receiver>
+   <slot>accept()</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>299</x>
+     <y>366</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>299</x>
+     <y>199</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>buttonBox</sender>
+   <signal>rejected()</signal>
+   <receiver>settings_dialog</receiver>
+   <slot>reject()</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>299</x>
+     <y>366</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>299</x>
+     <y>199</y>
+    </hint>
+   </hints>
+  </connection>
+  <connection>
+   <sender>useCustomFileEditor</sender>
+   <signal>toggled(bool)</signal>
+   <receiver>customEditorLabel</receiver>
+   <slot>setEnabled(bool)</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>349</x>
+     <y>383</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>111</x>
+     <y>413</y>
+    </hint>
+   </hints>
+  </connection>
+ </connections>
+</ui>
new file mode 100644
--- /dev/null
+++ b/libgui/src/terminal-dock-widget.cc
@@ -0,0 +1,95 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 "terminal-dock-widget.h"
+
+terminal_dock_widget::terminal_dock_widget (QWidget *p)
+  : octave_dock_widget (p), terminal (new QTerminal (p))
+{
+  terminal->setObjectName ("OctaveTerminal");
+  terminal->setFocusPolicy (Qt::StrongFocus);
+
+  setObjectName ("TerminalDockWidget");
+  setWindowIcon (QIcon(":/actions/icons/logo.png"));
+  setWindowTitle (tr ("Command Window"));
+  setWidget (terminal);
+
+  connect (parent (), SIGNAL (settings_changed (const QSettings *)),
+           this, SLOT (notice_settings (const QSettings *)));
+
+  connect (this, SIGNAL (visibilityChanged (bool)),
+           this, SLOT (handle_visibility (bool)));
+
+  // Forward signals to QTerminal widget.
+
+  connect (this, SIGNAL (notice_settings_signal (const QSettings *)),
+           terminal, SLOT (notice_settings (const QSettings *)));
+
+  connect (this, SIGNAL (copyClipboard_signal (void)),
+           terminal, SLOT (copyClipboard (void)));
+
+  connect (this, SIGNAL (pasteClipboard_signal (void)),
+           terminal, SLOT (pasteClipboard (void)));
+}
+
+bool
+terminal_dock_widget::has_focus (void) const
+{
+  QWidget *w = widget ();
+
+  return w->hasFocus ();
+}
+
+void
+terminal_dock_widget::notice_settings (const QSettings *settings)
+{
+  emit notice_settings_signal (settings);
+}
+
+void
+terminal_dock_widget::copyClipboard (void)
+{
+  emit copyClipboard_signal ();
+}
+
+void
+terminal_dock_widget::pasteClipboard (void)
+{
+  emit pasteClipboard_signal ();
+}
+
+void
+terminal_dock_widget::focus (void)
+{
+  octave_dock_widget::focus ();
+
+  QWidget *w = widget ();
+
+  w->setFocus ();
+  w->activateWindow ();
+  w->raise ();
+}
new file mode 100644
--- /dev/null
+++ b/libgui/src/terminal-dock-widget.h
@@ -0,0 +1,67 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2011-2012 Jacob Dawid
+
+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/>.
+
+*/
+
+#ifndef TERMINALDOCKWIDGET_H
+#define TERMINALDOCKWIDGET_H
+
+#include <QString>
+
+#include "QTerminal.h"
+#include "octave-dock-widget.h"
+
+class terminal_dock_widget : public octave_dock_widget
+{
+  Q_OBJECT
+
+public:
+
+  terminal_dock_widget (QWidget *parent = 0);
+
+  bool has_focus (void) const;
+
+signals:
+
+public slots:
+
+  void notice_settings (const QSettings *settings);
+
+  void copyClipboard (void);
+
+  void pasteClipboard (void);
+
+  void focus (void);
+
+signals:
+
+  void notice_settings_signal (const QSettings *settings); 
+
+  void copyClipboard_signal (void);
+
+  void pasteClipboard_signal (void);
+
+private:
+
+  QTerminal *terminal;
+};
+
+#endif // TERMINALDOCKWIDGET_H
new file mode 100644
--- /dev/null
+++ b/libgui/src/welcome-wizard.cc
@@ -0,0 +1,61 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 "welcome-wizard.h"
+#include "ui-welcome-wizard.h"
+
+welcome_wizard::welcome_wizard (QWidget *p)
+  : QDialog (p), _ui (new Ui::welcome_wizard)
+{
+  _ui->setupUi (this);
+  connect (_ui->nextButton1, SIGNAL (clicked ()), this, SLOT (next ()));
+  connect (_ui->nextButton2, SIGNAL (clicked ()), this, SLOT (next ()));
+  connect (_ui->nextButton3, SIGNAL (clicked ()), this, SLOT (next ()));
+  connect (_ui->nextButton4, SIGNAL (clicked ()), this, SLOT (next ()));
+
+  connect (_ui->previousButton2, SIGNAL (clicked ()), this, SLOT (previous ()));
+  connect (_ui->previousButton3, SIGNAL (clicked ()), this, SLOT (previous ()));
+  connect (_ui->previousButton4, SIGNAL (clicked ()), this, SLOT (previous ()));
+  connect (_ui->previousButton5, SIGNAL (clicked ()), this, SLOT (previous ()));
+}
+
+welcome_wizard::~welcome_wizard()
+{
+  delete _ui;
+}
+
+void
+welcome_wizard::next ()
+{
+  _ui->stackedWidget->setCurrentIndex (_ui->stackedWidget->currentIndex () + 1);
+}
+
+void
+welcome_wizard::previous ()
+{
+  _ui->stackedWidget->setCurrentIndex (_ui->stackedWidget->currentIndex () - 1);
+}
+
new file mode 100644
--- /dev/null
+++ b/libgui/src/welcome-wizard.h
@@ -0,0 +1,48 @@
+/*
+
+Copyright (C) 2011-2012 Jacob Dawid
+
+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/>.
+
+*/
+
+#ifndef WELCOMEWIZARD_H
+#define WELCOMEWIZARD_H
+
+#include <QDialog>
+
+namespace Ui {
+  class welcome_wizard;
+}
+
+class welcome_wizard : public QDialog
+{
+  Q_OBJECT
+
+  public:
+  explicit welcome_wizard (QWidget *parent = 0);
+  ~welcome_wizard ();
+
+public slots:
+  void next ();
+  void previous ();
+
+private:
+  Ui::welcome_wizard *_ui;
+};
+
+#endif // WELCOMEWIZARD_H
new file mode 100644
--- /dev/null
+++ b/libgui/src/welcome-wizard.ui
@@ -0,0 +1,354 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>welcome_wizard</class>
+ <widget class="QDialog" name="welcome_wizard">
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>647</width>
+    <height>400</height>
+   </rect>
+  </property>
+  <property name="minimumSize">
+   <size>
+    <width>647</width>
+    <height>400</height>
+   </size>
+  </property>
+  <property name="maximumSize">
+   <size>
+    <width>647</width>
+    <height>400</height>
+   </size>
+  </property>
+  <property name="windowTitle">
+   <string>Welcome to GNU Octave</string>
+  </property>
+  <layout class="QVBoxLayout" name="verticalLayout_2">
+   <item>
+    <widget class="QStackedWidget" name="stackedWidget">
+     <property name="currentIndex">
+      <number>4</number>
+     </property>
+     <widget class="QWidget" name="page">
+      <layout class="QVBoxLayout" name="verticalLayout">
+       <item>
+        <widget class="QLabel" name="label">
+         <property name="text">
+          <string>It appears that you have launched Octave GUI for the first time on this computer, since no configuration file could be found at '~/.octave-gui'. This wizard will guide you through the essential settings you should make before you can start using Octave GUI. If you want to transfer your settings you have previously made just close this dialog and copy over the settings file to your home folder. The presence of that file will automatically be detected and will skip this wizard. IMPORTANT: This wizard is not fully functional yet. Just click your way to the end and it will create a standard settings file.</string>
+         </property>
+         <property name="alignment">
+          <set>Qt::AlignJustify|Qt::AlignVCenter</set>
+         </property>
+         <property name="wordWrap">
+          <bool>true</bool>
+         </property>
+        </widget>
+       </item>
+       <item>
+        <spacer name="verticalSpacer">
+         <property name="orientation">
+          <enum>Qt::Vertical</enum>
+         </property>
+         <property name="sizeHint" stdset="0">
+          <size>
+           <width>20</width>
+           <height>218</height>
+          </size>
+         </property>
+        </spacer>
+       </item>
+       <item>
+        <layout class="QHBoxLayout" name="horizontalLayout_2">
+         <item>
+          <spacer name="horizontalSpacer">
+           <property name="orientation">
+            <enum>Qt::Horizontal</enum>
+           </property>
+           <property name="sizeHint" stdset="0">
+            <size>
+             <width>40</width>
+             <height>20</height>
+            </size>
+           </property>
+          </spacer>
+         </item>
+         <item>
+          <widget class="QPushButton" name="nextButton1">
+           <property name="text">
+            <string>Next</string>
+           </property>
+          </widget>
+         </item>
+        </layout>
+       </item>
+      </layout>
+     </widget>
+     <widget class="QWidget" name="page_2">
+      <layout class="QVBoxLayout" name="verticalLayout_4">
+       <item>
+        <layout class="QVBoxLayout" name="verticalLayout_3">
+         <item>
+          <spacer name="verticalSpacer_2">
+           <property name="orientation">
+            <enum>Qt::Vertical</enum>
+           </property>
+           <property name="sizeHint" stdset="0">
+            <size>
+             <width>20</width>
+             <height>40</height>
+            </size>
+           </property>
+          </spacer>
+         </item>
+         <item>
+          <layout class="QHBoxLayout" name="horizontalLayout">
+           <item>
+            <widget class="QPushButton" name="previousButton2">
+             <property name="text">
+              <string>Previous</string>
+             </property>
+            </widget>
+           </item>
+           <item>
+            <spacer name="horizontalSpacer_2">
+             <property name="orientation">
+              <enum>Qt::Horizontal</enum>
+             </property>
+             <property name="sizeHint" stdset="0">
+              <size>
+               <width>40</width>
+               <height>20</height>
+              </size>
+             </property>
+            </spacer>
+           </item>
+           <item>
+            <widget class="QPushButton" name="nextButton2">
+             <property name="text">
+              <string>Next</string>
+             </property>
+            </widget>
+           </item>
+          </layout>
+         </item>
+        </layout>
+       </item>
+      </layout>
+     </widget>
+     <widget class="QWidget" name="page_3">
+      <layout class="QHBoxLayout" name="horizontalLayout_4">
+       <item>
+        <layout class="QVBoxLayout" name="verticalLayout_5">
+         <item>
+          <spacer name="verticalSpacer_3">
+           <property name="orientation">
+            <enum>Qt::Vertical</enum>
+           </property>
+           <property name="sizeHint" stdset="0">
+            <size>
+             <width>20</width>
+             <height>40</height>
+            </size>
+           </property>
+          </spacer>
+         </item>
+         <item>
+          <layout class="QHBoxLayout" name="horizontalLayout_3">
+           <item>
+            <widget class="QPushButton" name="previousButton3">
+             <property name="text">
+              <string>Previous</string>
+             </property>
+            </widget>
+           </item>
+           <item>
+            <spacer name="horizontalSpacer_3">
+             <property name="orientation">
+              <enum>Qt::Horizontal</enum>
+             </property>
+             <property name="sizeHint" stdset="0">
+              <size>
+               <width>40</width>
+               <height>20</height>
+              </size>
+             </property>
+            </spacer>
+           </item>
+           <item>
+            <widget class="QPushButton" name="nextButton3">
+             <property name="text">
+              <string>Next</string>
+             </property>
+            </widget>
+           </item>
+          </layout>
+         </item>
+        </layout>
+       </item>
+      </layout>
+     </widget>
+     <widget class="QWidget" name="page_4">
+      <layout class="QHBoxLayout" name="horizontalLayout_6">
+       <item>
+        <layout class="QVBoxLayout" name="verticalLayout_6">
+         <item>
+          <spacer name="verticalSpacer_4">
+           <property name="orientation">
+            <enum>Qt::Vertical</enum>
+           </property>
+           <property name="sizeHint" stdset="0">
+            <size>
+             <width>20</width>
+             <height>40</height>
+            </size>
+           </property>
+          </spacer>
+         </item>
+         <item>
+          <layout class="QHBoxLayout" name="horizontalLayout_5">
+           <item>
+            <widget class="QPushButton" name="previousButton4">
+             <property name="text">
+              <string>Previous</string>
+             </property>
+            </widget>
+           </item>
+           <item>
+            <spacer name="horizontalSpacer_4">
+             <property name="orientation">
+              <enum>Qt::Horizontal</enum>
+             </property>
+             <property name="sizeHint" stdset="0">
+              <size>
+               <width>40</width>
+               <height>20</height>
+              </size>
+             </property>
+            </spacer>
+           </item>
+           <item>
+            <widget class="QPushButton" name="nextButton4">
+             <property name="text">
+              <string>Next</string>
+             </property>
+            </widget>
+           </item>
+          </layout>
+         </item>
+        </layout>
+       </item>
+      </layout>
+     </widget>
+     <widget class="QWidget" name="page_5">
+      <layout class="QHBoxLayout" name="horizontalLayout_8">
+       <item>
+        <layout class="QVBoxLayout" name="verticalLayout_7">
+         <item>
+          <widget class="QLabel" name="label_2">
+           <property name="font">
+            <font>
+             <pointsize>20</pointsize>
+            </font>
+           </property>
+           <property name="text">
+            <string>Welcome to Octave!</string>
+           </property>
+          </widget>
+         </item>
+         <item>
+          <widget class="QLabel" name="label_3">
+           <property name="text">
+            <string>This is the development version of Octave with the first official GUI.</string>
+           </property>
+           <property name="wordWrap">
+            <bool>true</bool>
+           </property>
+          </widget>
+         </item>
+         <item>
+          <widget class="QLabel" name="label_4">
+           <property name="text">
+            <string>You seem to run Octave GUI for the first time on this computer. This assistant will help you to configure this software installation. Click 'Finish' to write a configuration file and launch Octave GUI.</string>
+           </property>
+           <property name="wordWrap">
+            <bool>true</bool>
+           </property>
+          </widget>
+         </item>
+         <item>
+          <spacer name="verticalSpacer_5">
+           <property name="orientation">
+            <enum>Qt::Vertical</enum>
+           </property>
+           <property name="sizeHint" stdset="0">
+            <size>
+             <width>20</width>
+             <height>40</height>
+            </size>
+           </property>
+          </spacer>
+         </item>
+         <item>
+          <layout class="QHBoxLayout" name="horizontalLayout_7">
+           <item>
+            <widget class="QPushButton" name="previousButton5">
+             <property name="enabled">
+              <bool>false</bool>
+             </property>
+             <property name="text">
+              <string>Previous</string>
+             </property>
+            </widget>
+           </item>
+           <item>
+            <spacer name="horizontalSpacer_5">
+             <property name="orientation">
+              <enum>Qt::Horizontal</enum>
+             </property>
+             <property name="sizeHint" stdset="0">
+              <size>
+               <width>40</width>
+               <height>20</height>
+              </size>
+             </property>
+            </spacer>
+           </item>
+           <item>
+            <widget class="QPushButton" name="finishButton">
+             <property name="text">
+              <string>Finish</string>
+             </property>
+            </widget>
+           </item>
+          </layout>
+         </item>
+        </layout>
+       </item>
+      </layout>
+     </widget>
+    </widget>
+   </item>
+  </layout>
+ </widget>
+ <resources/>
+ <connections>
+  <connection>
+   <sender>finishButton</sender>
+   <signal>clicked()</signal>
+   <receiver>welcome_wizard</receiver>
+   <slot>accept()</slot>
+   <hints>
+    <hint type="sourcelabel">
+     <x>577</x>
+     <y>372</y>
+    </hint>
+    <hint type="destinationlabel">
+     <x>323</x>
+     <y>199</y>
+    </hint>
+   </hints>
+  </connection>
+ </connections>
+</ui>
new file mode 100644
--- /dev/null
+++ b/libgui/src/workspace-model.cc
@@ -0,0 +1,215 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 <QTreeWidget>
+
+#include "utils.h"
+
+#include "workspace-model.h"
+
+workspace_model::workspace_model (QObject *p)
+  : QAbstractTableModel (p)
+{
+  _columnNames.append (tr ("Name"));
+  _columnNames.append (tr ("Class"));
+  _columnNames.append (tr ("Dimension"));
+  _columnNames.append (tr ("Value"));
+  _columnNames.append (tr ("Storage Class"));
+}
+
+int
+workspace_model::rowCount(const QModelIndex& p) const
+{
+  return _symbols.size ();
+}
+
+int
+workspace_model::columnCount (const QModelIndex& p) const
+{
+  return _columnNames.size ();
+}
+
+Qt::ItemFlags
+workspace_model::flags (const QModelIndex& idx) const
+{
+  Qt::ItemFlags retval = 0;
+
+  if (idx.isValid ())
+    {
+      retval |= Qt::ItemIsEnabled;
+
+      if (_top_level && idx.column () == 0)
+        retval |= Qt::ItemIsSelectable;
+    }
+
+  return retval;
+}
+
+QVariant
+workspace_model::headerData (int section, Qt::Orientation orientation,
+                             int role) const
+{
+  if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
+    return _columnNames[section];
+  else
+    return QVariant();
+}
+
+QVariant
+workspace_model::data (const QModelIndex& idx, int role) const
+{
+  QVariant retval;
+
+  if (idx.isValid ()
+      && (role == Qt::DisplayRole
+          || (idx.column () == 0 && (role == Qt::EditRole
+                                     || role == Qt::ToolTipRole))))
+    {
+      switch (idx.column ())
+        {
+        case 0:
+          if (role == Qt::ToolTipRole)
+            retval = QVariant (tr ("Right click to copy, rename, or display"));
+          else
+            retval = QVariant (_symbols[idx.row()]);
+          break;
+
+        case 1:
+          retval = QVariant (_class_names[idx.row()]);
+          break;
+
+        case 2:
+          retval = QVariant (_dimensions[idx.row()]);
+          break;
+
+        case 3:
+          retval = QVariant (_values[idx.row()]);
+          break;
+
+        case 4:
+          {
+            QChar c = _scopes[idx.row()];
+
+            if (c == 'g')
+              retval = QVariant (tr ("global"));
+            else if (c == 'p')
+              retval = QVariant (tr ("persistent"));
+            else if (c == 'a')
+              retval = QVariant (tr ("automatic"));
+            else if (c == 'f')
+              retval = QVariant (tr ("function parameter"));
+            else if (c == 'h')
+              retval = QVariant (tr ("hidden"));
+            else if (c == 'i')
+              retval = QVariant (tr ("inherited"));
+          }
+
+        default:
+          break;
+        }
+    }
+
+  return retval;
+}
+
+bool
+workspace_model::setData (const QModelIndex& idx, const QVariant& value,
+                          int role)
+{
+  bool retval = false;
+
+  if (idx.column () == 0 && role == Qt::EditRole)
+    {
+      QString qold_name = _symbols[idx.row()];
+
+      QString qnew_name = value.toString ();
+
+      std::string new_name = qnew_name.toStdString ();
+
+      if (valid_identifier (new_name))
+        {
+          emit rename_variable (qold_name, qnew_name);
+
+          retval = true;
+        }
+    }
+
+  return retval;
+}
+
+
+void
+workspace_model::set_workspace (bool top_level,
+                                const QString& scopes,
+                                const QStringList& symbols,
+                                const QStringList& class_names,
+                                const QStringList& dimensions,
+                                const QStringList& values)
+{
+  _top_level = top_level;
+  _scopes = scopes;
+  _symbols = symbols;
+  _class_names = class_names;
+  _dimensions = dimensions;
+  _values = values;
+
+  update_table ();
+
+  emit model_changed ();
+}
+
+void
+workspace_model::clear_workspace (void)
+{
+  clear_data ();
+  update_table ();
+
+  emit model_changed ();
+}
+
+void
+workspace_model::clear_data (void)
+{
+  _top_level = false;
+  _scopes = QString ();
+  _symbols = QStringList ();
+  _class_names = QStringList ();
+  _dimensions = QStringList ();
+  _values = QStringList ();
+}
+
+void
+workspace_model::update_table (void)
+{
+  beginResetModel();
+
+  // Nothing to do except tell the world to recalc.
+
+  endResetModel ();
+
+  emit model_changed ();
+}
new file mode 100644
--- /dev/null
+++ b/libgui/src/workspace-model.h
@@ -0,0 +1,91 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 (workspace_model_h)
+#define workspace_model_h 1
+
+#include <QAbstractTableModel>
+#include <QVector>
+#include <QSemaphore>
+#include <QStringList>
+
+class workspace_model
+  : public QAbstractTableModel
+{
+  Q_OBJECT
+
+public:
+
+  workspace_model (QObject *parent = 0);
+
+  ~workspace_model (void) { }
+
+  QVariant data (const QModelIndex& index, int role) const;
+
+  bool setData (const QModelIndex& index, const QVariant& value,
+                int role = Qt::EditRole);
+
+  Qt::ItemFlags flags (const QModelIndex& index) const;
+
+  QVariant headerData (int section, Qt::Orientation orientation,
+                       int role = Qt::DisplayRole) const;
+
+  int rowCount (const QModelIndex& parent = QModelIndex ()) const;
+
+  int columnCount (const QModelIndex& parent = QModelIndex ()) const;
+
+  bool is_top_level (void) const { return _top_level; }
+
+public slots:
+
+  void set_workspace (bool top_level,
+                      const QString& scopes,
+                      const QStringList& symbols,
+                      const QStringList& class_names,
+                      const QStringList& dimensions,
+                      const QStringList& values);
+
+  void clear_workspace (void);
+
+signals:
+
+  void model_changed (void);
+
+  void rename_variable (const QString& old_name, const QString& new_name);
+
+private:
+
+  void clear_data (void);
+  void update_table (void);
+
+  bool _top_level;
+  QString _scopes;
+  QStringList _symbols;
+  QStringList _class_names;
+  QStringList _dimensions;
+  QStringList _values;
+
+  QStringList _columnNames;
+};
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libgui/src/workspace-view.cc
@@ -0,0 +1,244 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 <QInputDialog>
+#include <QApplication>
+#include <QClipboard>
+#include <QMessageBox>
+#include <QLineEdit>
+#include <QHeaderView>
+#include <QHBoxLayout>
+#include <QVBoxLayout>
+#include <QPushButton>
+#include <QMenu>
+
+#include "workspace-view.h"
+#include "resource-manager.h"
+
+workspace_view::workspace_view (QWidget *p)
+  : octave_dock_widget (p), view (new QTableView (this))
+{
+  setObjectName ("WorkspaceView");
+  setWindowIcon (QIcon (":/actions/icons/logo.png"));
+  setWindowTitle (tr ("Workspace"));
+  setStatusTip (tr ("View the variables in the active workspace."));
+
+  view->setWordWrap (false);
+  view->setContextMenuPolicy (Qt::CustomContextMenu);
+  view_previous_row_count = 0;
+
+  // Set an empty widget, so we can assign a layout to it.
+  setWidget (new QWidget (this));
+
+  // Create a new layout and add widgets to it.
+  QVBoxLayout *vbox_layout = new QVBoxLayout ();
+  vbox_layout->addWidget (view);
+  vbox_layout->setMargin (2);
+
+  // Set the empty widget to have our layout.
+  widget ()->setLayout (vbox_layout);
+
+  // Initialize collapse/expand state of the workspace subcategories.
+
+  QSettings *settings = resource_manager::get_settings ();
+
+  // Initialize column order and width of the workspace
+  
+  view->horizontalHeader ()->restoreState (settings->value ("workspaceview/column_state").toByteArray ());
+
+  // Connect signals and slots.
+
+  connect (view, SIGNAL (customContextMenuRequested (const QPoint&)),
+           this, SLOT(contextmenu_requested (const QPoint&)));
+
+  connect (this, SIGNAL (command_requested (const QString&)),
+           p, SLOT (execute_command_in_terminal (const QString&)));
+}
+
+workspace_view::~workspace_view (void)
+{
+  QSettings *settings = resource_manager::get_settings ();
+
+  settings->setValue("workspaceview/column_state",
+                     view->horizontalHeader ()->saveState ());
+
+  settings->sync ();
+}
+
+void
+workspace_view::closeEvent (QCloseEvent *e)
+{
+  emit active_changed (false);
+  QDockWidget::closeEvent (e);
+}
+
+void
+workspace_view::contextmenu_requested (const QPoint& qpos)
+{
+  QMenu menu (this);
+
+  QModelIndex index = view->indexAt (qpos);
+  QAbstractItemModel *m = view->model ();
+
+  // if it isnt Local, Glocal etc, allow the ctx menu
+  if (index.isValid() && index.column () == 0)
+    {
+      index = index.sibling (index.row(), 0);
+
+      QMap<int, QVariant> item_data = m->itemData (index);
+  
+      QString var_name = item_data[0].toString ();
+
+      menu.addAction (tr ("Copy"), this,
+                      SLOT (handle_contextmenu_copy ()));
+
+      QAction *rename = menu.addAction (tr ("Rename"), this,
+                                        SLOT (handle_contextmenu_rename ()));
+
+      const workspace_model *wm = static_cast<const workspace_model *> (m);
+
+      if (! wm->is_top_level ())
+        {
+          rename->setDisabled (true);
+          rename->setToolTip (tr ("Only top-level symbols may be renamed."));
+        }
+
+      menu.addSeparator ();
+
+      menu.addAction ("disp(" + var_name + ")", this,
+                      SLOT (handle_contextmenu_disp ()));
+
+      menu.addAction ("plot(" + var_name + ")", this,
+                      SLOT (handle_contextmenu_plot ()));
+
+      menu.addAction ("stem(" + var_name + ")", this,
+                      SLOT (handle_contextmenu_stem ()));
+
+      menu.exec (view->mapToGlobal (qpos));
+    }
+}
+
+void
+workspace_view::handle_contextmenu_copy (void)
+{
+  QModelIndex index = view->currentIndex ();
+
+  if (index.isValid ())
+    {
+      index = index.sibling(index.row(), 0);
+
+      QAbstractItemModel *m = view->model ();
+
+      QMap<int, QVariant> item_data = m->itemData (index);
+  
+      QString var_name = item_data[0].toString ();
+
+      QClipboard *clipboard = QApplication::clipboard ();
+
+      clipboard->setText (var_name);
+    }
+}
+
+void
+workspace_view::handle_contextmenu_rename (void)
+{
+  QModelIndex index = view->currentIndex ();
+
+  if (index.isValid ())
+    {
+      index = index.sibling(index.row(), 0);
+
+      QAbstractItemModel *m = view->model ();
+
+      QMap<int, QVariant> item_data = m->itemData (index);
+  
+      QString var_name = item_data[0].toString ();
+
+      QInputDialog* inputDialog = new QInputDialog ();
+
+      inputDialog->setOptions (QInputDialog::NoButtons);
+
+      bool ok = false;
+
+      QString new_name
+        =  inputDialog->getText (0, "Rename Variable", "New name:",
+                                 QLineEdit::Normal, var_name, &ok);
+
+      if (ok && ! new_name.isEmpty ())
+        m->setData (index, new_name, Qt::EditRole);
+    }
+}
+
+void
+workspace_view::handle_contextmenu_disp (void)
+{
+  relay_contextmenu_command ("disp");
+}
+
+void
+workspace_view::handle_contextmenu_plot (void)
+{
+  relay_contextmenu_command ("figure (); plot");
+}
+
+void
+workspace_view::handle_contextmenu_stem (void)
+{
+  relay_contextmenu_command ("figure (); stem");
+}
+
+void
+workspace_view::relay_contextmenu_command (const QString& cmdname)
+{
+  QModelIndex index = view->currentIndex ();
+
+  if (index.isValid ())
+    {
+      index = index.sibling(index.row(), 0);
+
+      QAbstractItemModel *m = view->model ();
+
+      QMap<int, QVariant> item_data = m->itemData (index);
+  
+      QString var_name = item_data[0].toString ();
+
+      emit command_requested (cmdname + " (" + var_name + ");");
+    }
+}
+
+void
+workspace_view::handle_model_changed (void)
+{
+  // Just modify those rows that have been added rather than go through
+  // the whole list.  For-loop test will handle when number of rows reduced.
+  QFontMetrics fm = view->fontMetrics ();
+  int row_height =  fm.height ();
+  int new_row_count = view->model ()->rowCount ();
+  for (int i = view_previous_row_count; i < new_row_count; i++)
+    view->setRowHeight (i, row_height);
+  view_previous_row_count = new_row_count;
+}
new file mode 100644
--- /dev/null
+++ b/libgui/src/workspace-view.h
@@ -0,0 +1,78 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2011-2012 Jacob Dawid
+
+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 (workspace_view_h)
+#define workspace_view_h 1
+
+#include <QItemDelegate>
+#include <QTableView>
+#include <QSemaphore>
+
+#include "octave-dock-widget.h"
+#include "workspace-model.h"
+
+class workspace_view : public octave_dock_widget
+{
+  Q_OBJECT
+
+public:
+
+  workspace_view (QWidget *parent = 0);
+
+  ~workspace_view (void);
+
+public:
+
+  void setModel (workspace_model *model) { view->setModel (model); }
+
+signals:
+
+  /** signal that user had requested a command on a variable */
+  void command_requested (const QString& cmd);
+
+protected:
+
+  void closeEvent (QCloseEvent *event);
+
+protected slots:
+
+  void contextmenu_requested (const QPoint& pos);
+
+  // context menu slots
+  void handle_contextmenu_copy (void);
+  void handle_contextmenu_rename (void);
+  void handle_contextmenu_disp (void);
+  void handle_contextmenu_plot (void);
+  void handle_contextmenu_stem (void);
+
+  void handle_model_changed (void);
+
+private:
+
+  void relay_contextmenu_command (const QString& cmdname);
+
+  QTableView *view;
+  int view_previous_row_count;
+};
+
+#endif
copy from src/Makefile.am
copy to libinterp/Makefile.am
--- a/src/Makefile.am
+++ b/libinterp/Makefile.am
@@ -1,4 +1,4 @@
-# Makefile for octave's src directory
+# Makefile for Octave's libinterp directory
 #
 # Copyright (C) 1993-2012 John W. Eaton
 #
@@ -20,75 +20,65 @@
 
 include $(top_srcdir)/build-aux/common.mk
 
+AUTOMAKE_OPTIONS = subdir-objects
+
 ## Search local directories before those specified by the user.
 AM_CPPFLAGS = \
-  -I../libgnu -I$(top_srcdir)/libgnu \
-  -I$(top_srcdir)/libcruft/misc \
-  -I../liboctave -I$(top_srcdir)/liboctave \
-  -I. -I$(srcdir) \
-  @CPPFLAGS@
+  -I$(top_srcdir)/liboctave/cruft/misc \
+  -I$(top_srcdir)/liboctave/array \
+  -I$(top_builddir)/liboctave/numeric -I$(top_srcdir)/liboctave/numeric \
+  -I$(top_builddir)/liboctave/operators -I$(top_srcdir)/liboctave/operators \
+  -I$(top_srcdir)/liboctave/system \
+  -I$(top_srcdir)/liboctave/util \
+  -I$(srcdir)/octave-value \
+  -I$(srcdir)/operators \
+  -Iparse-tree -I$(srcdir)/parse-tree \
+  -Iinterp-core -I$(srcdir)/interp-core \
+  -Iinterpfcn -I$(srcdir)/interpfcn \
+  -Icorefcn \
+  -I$(top_builddir)/libgnu -I$(top_srcdir)/libgnu
 
-AUTOMAKE_OPTIONS = subdir-objects
+AM_CFLAGS += $(WARN_CFLAGS)
+
+AM_CXXFLAGS += $(WARN_CXXFLAGS)
 
 octlib_LTLIBRARIES = liboctinterp.la
 
-if AMCOND_BUILD_COMPILED_AUX_PROGRAMS
-bin_PROGRAMS = \
-  mkoctfile \
-  octave \
-  octave-config
-
-mkoctfile_SOURCES =
-nodist_mkoctfile_SOURCES = mkoctfile.cc
-mkoctfile_LDADD = ../libgnu/libgnu.la $(LIBS)
-
-octave_config_SOURCES =
-nodist_octave_config_SOURCES = octave-config.cc
-octave_config_LDADD = ../libgnu/libgnu.la $(LIBS)
-
-BUILT_SOURCES_EXTRA = \
-  mkoctfile.cc \
-  octave-config.cc
-else
-bin_PROGRAMS = \
-  octave
-
-bin_SCRIPTS = \
-  mkoctfile \
-  octave-config
-endif
-
 ## Order matters here.  Leave builtins.cc last, because it depends on
 ## $(DEF_FILES), and building those requires all the sources
 ## (except builtins.cc) to be available.
 BUILT_SOURCES = \
-  $(BUILT_SOURCES_EXTRA) \
-  defaults.h \
-  graphics.h \
-  graphics-props.cc \
-  lex.cc \
-  mxarray.h \
+  interp-core/mxarray.h \
+  interp-core/oct-errno.cc \
+  interpfcn/defaults.h \
+  interpfcn/graphics-props.cc \
+  interpfcn/graphics.h \
+  operators/ops.cc \
+  parse-tree/lex.cc \
+  parse-tree/oct-gperf.h \
+  parse-tree/oct-parse.cc \
   oct-conf.h \
-  oct-errno.cc \
-  oct-gperf.h \
-  oct-parse.cc \
-  ops.cc \
+  oct-conf-features.h \
   version.h \
+  builtin-defun-decls.h \
   builtins.cc
 
 BUILT_DISTFILES = \
-  oct-gperf.h \
-  oct-parse.h
+  parse-tree/oct-gperf.h \
+  parse-tree/oct-parse.h \
+  parse-tree/oct-parse.yy
 
 ## Files that are created during build process and installed,
 ## BUT not distributed in tarball.
 BUILT_NODISTFILES = \
-  defaults.h \
-  graphics.h \
+  interp-core/mxarray.h \
+  interp-core/oct-errno.cc \
+  interpfcn/defaults.h \
+  interpfcn/graphics.h \
+  builtin-defun-decls.h \
+  operators/ops.cc \
   oct-conf.h \
-  oct-errno.cc \
-  ops.cc \
-  mxarray.h \
+  oct-conf-features.h \
   version.h \
   $(OPT_HANDLERS) \
   $(OPT_INC) \
@@ -97,413 +87,89 @@
 
 EXTRA_DIST = \
   Makefile.in \
-  defaults.h.in \
   DOCSTRINGS \
+  config-features.sh \
   find-defun-files.sh \
   gendoc.pl \
   genprops.awk \
-  gl2ps.c \
-  graphics.h.in \
   mk-errno-list \
   mk-pkg-add \
   mkbuiltins \
   mkdefs \
-  mkoctfile.cc.in \
-  mkoctfile.in \
   mkops \
-  mxarray.h.in \
-  oct-conf.h.in \
-  oct-errno.cc.in \
-  octave-config.cc.in \
-  octave-config.in \
-  octave.gperf \
-  version.h.in \
+  oct-conf.in.h \
+  parse-tree/oct-parse.in.yy \
+  version.in.h \
   $(BUILT_DISTFILES)
 
-OPT_HANDLERS = \
-  DASPK-opts.cc \
-  DASRT-opts.cc \
-  DASSL-opts.cc \
-  LSODE-opts.cc \
-  Quad-opts.cc
-
-OPT_INC = \
-  ../liboctave/DASPK-opts.h \
-  ../liboctave/DASRT-opts.h \
-  ../liboctave/DASSL-opts.h \
-  ../liboctave/LSODE-opts.h \
-  ../liboctave/Quad-opts.h
-
-OV_INTTYPE_INC = \
-  ov-base-int.h \
-  ov-base-int.cc \
-  ov-int-traits.h \
-  ov-int16.h \
-  ov-int32.h \
-  ov-int64.h \
-  ov-int8.h \
-  ov-intx.h \
-  ov-uint16.h \
-  ov-uint32.h \
-  ov-uint64.h \
-  ov-uint8.h
-
-OV_INCLUDES = \
-  ov-base-diag.h \
-  ov-base-diag.cc \
-  ov-base-mat.h \
-  ov-base-mat.cc \
-  ov-base-scalar.h \
-  ov-base-scalar.cc \
-  ov-base.h \
-  ov-bool-mat.h \
-  ov-bool-mat.cc \
-  ov-bool.h \
-  ov-builtin.h \
-  ov-cell.h \
-  ov-ch-mat.h \
-  ov-class.h \
-  ov-colon.h \
-  ov-complex.h \
-  ov-cs-list.h \
-  ov-cx-diag.h \
-  ov-cx-mat.h \
-  ov-dld-fcn.h \
-  ov-fcn-handle.h \
-  ov-fcn-inline.h \
-  ov-fcn.h \
-  ov-float.h \
-  ov-flt-complex.h \
-  ov-flt-cx-diag.h \
-  ov-flt-cx-mat.h \
-  ov-flt-re-diag.h \
-  ov-flt-re-mat.h \
-  ov-lazy-idx.h \
-  ov-mex-fcn.h \
-  ov-null-mat.h \
-  ov-oncleanup.h \
-  ov-perm.h \
-  ov-range.h \
-  ov-re-diag.h \
-  ov-re-mat.h \
-  ov-scalar.h \
-  ov-str-mat.h \
-  ov-struct.h \
-  ov-type-conv.h \
-  ov-typeinfo.h \
-  ov-usr-fcn.h \
-  ov.h \
-  $(OV_INTTYPE_INC)
-
-OV_SPARSE_INCLUDES = \
-  ov-base-sparse.h \
-  ov-bool-sparse.h \
-  ov-cx-sparse.h \
-  ov-re-sparse.h
-
-PT_INCLUDES = \
-  pt-all.h \
-  pt-arg-list.h \
-  pt-assign.h \
-  pt-binop.h \
-  pt-bp.h \
-  pt-cbinop.h \
-  pt-cell.h \
-  pt-check.h \
-  pt-cmd.h \
-  pt-colon.h \
-  pt-const.h \
-  pt-decl.h \
-  pt-eval.h \
-  pt-except.h \
-  pt-exp.h \
-  pt-fcn-handle.h \
-  pt-id.h \
-  pt-idx.h \
-  pt-jump.h \
-  pt-loop.h \
-  pt-mat.h \
-  pt-misc.h \
-  pt-pr-code.h \
-  pt-select.h \
-  pt-stmt.h \
-  pt-unop.h \
-  pt-walk.h \
-  pt.h
-
 octinclude_HEADERS = \
-  Cell.h \
+  interpfcn/graphics-props.cc \
+  parse-tree/oct-gperf.h \
   builtins.h \
-  c-file-ptr-stream.h \
-  comment-list.h \
-  cutils.h \
-  data.h \
-  debug.h \
-  defun-dld.h \
-  defun-int.h \
-  defun.h \
-  dirfns.h \
-  display.h \
-  dynamic-ld.h \
-  error.h \
-  file-io.h \
-  gl-render.h \
-  gl2ps.h \
-  gl2ps-renderer.h \
-  graphics-props.cc \
-  gripes.h \
-  help.h \
-  input.h \
-  lex.h \
-  load-path.h \
-  load-save.h \
-  ls-ascii-helper.h \
-  ls-hdf5.h \
-  ls-mat-ascii.h \
-  ls-mat4.h \
-  ls-mat5.h \
-  ls-oct-ascii.h \
-  ls-oct-binary.h \
-  ls-utils.h \
-  mex.h \
-  mexproto.h \
-  oct-errno.h \
-  oct-fstrm.h \
-  oct-gperf.h \
-  oct-hdf5.h \
-  oct-hist.h \
-  oct-iostrm.h \
-  oct-lvalue.h \
-  oct-map.h \
-  oct-obj.h \
-  oct-prcstrm.h \
-  oct-procbuf.h \
-  oct-stdstrm.h \
-  oct-stream.h \
-  oct-strstrm.h \
-  oct.h \
+  builtin-defun-decls.h \
   octave.h \
-  ops.h \
-  pager.h \
-  parse.h \
-  pr-output.h \
-  procstream.h \
-  profiler.h \
-  sighandlers.h \
-  siglist.h \
-  sparse-xdiv.h \
-  sparse-xpow.h \
-  symtab.h \
-  sysdep.h \
-  token.h \
-  toplev.h \
-  txt-eng-ft.h \
-  txt-eng.h \
-  unwind-prot.h \
-  utils.h \
-  variables.h \
-  xdiv.h \
-  xnorm.h \
-  xpow.h \
-  zfstream.h \
-  $(OV_INCLUDES) \
-  $(OV_SPARSE_INCLUDES) \
-  $(PT_INCLUDES)
+  $(OCTAVE_VALUE_INC) \
+  $(PARSE_TREE_INC) \
+  $(PARSER_INC) \
+  $(OPERATORS_INC) \
+  $(INTERP_CORE_INC) \
+  $(INTERPFCN_INC)
 
 nodist_octinclude_HEADERS = \
-  defaults.h \
-  graphics.h \
+  interp-core/mxarray.h \
+  interpfcn/defaults.h \
+  interpfcn/graphics.h \
   oct-conf.h \
-  mxarray.h \
   version.h
 
-OV_INTTYPE_SRC = \
-  ov-int16.cc \
-  ov-int32.cc \
-  ov-int64.cc \
-  ov-int8.cc \
-  ov-uint16.cc \
-  ov-uint32.cc \
-  ov-uint64.cc \
-  ov-uint8.cc
-
-OV_SPARSE_SRC = \
-  ov-base-sparse.cc \
-  ov-bool-sparse.cc \
-  ov-cx-sparse.cc \
-  ov-re-sparse.cc
+DIST_SRC = \
+  octave.cc \
+  $(OCTAVE_VALUE_SRC) \
+  $(PARSE_TREE_SRC) \
+  $(PARSER_SRC) \
+  $(INTERP_CORE_SRC) \
+  $(INTERPFCN_SRC) \
+  $(COREFCN_SRC)
 
-OV_SRC = \
-  ov-base.cc \
-  ov-bool-mat.cc \
-  ov-bool.cc \
-  ov-builtin.cc \
-  ov-cell.cc \
-  ov-ch-mat.cc \
-  ov-class.cc \
-  ov-colon.cc \
-  ov-complex.cc \
-  ov-cs-list.cc \
-  ov-cx-diag.cc \
-  ov-cx-mat.cc \
-  ov-dld-fcn.cc \
-  ov-fcn-handle.cc \
-  ov-fcn-inline.cc \
-  ov-fcn.cc \
-  ov-float.cc \
-  ov-flt-complex.cc \
-  ov-flt-cx-diag.cc \
-  ov-flt-cx-mat.cc \
-  ov-flt-re-diag.cc \
-  ov-flt-re-mat.cc \
-  ov-lazy-idx.cc \
-  ov-mex-fcn.cc \
-  ov-null-mat.cc \
-  ov-oncleanup.cc \
-  ov-perm.cc \
-  ov-range.cc \
-  ov-re-diag.cc \
-  ov-re-mat.cc \
-  ov-scalar.cc \
-  ov-str-mat.cc \
-  ov-struct.cc \
-  ov-typeinfo.cc \
-  ov-usr-fcn.cc \
-  ov.cc \
-  $(OV_INTTYPE_SRC) \
-  $(OV_SPARSE_SRC)
+noinst_LTLIBRARIES =
 
-PT_SRC = \
-  pt-arg-list.cc \
-  pt-assign.cc \
-  pt-binop.cc \
-  pt-bp.cc \
-  pt-cbinop.cc \
-  pt-cell.cc \
-  pt-check.cc \
-  pt-cmd.cc \
-  pt-colon.cc \
-  pt-const.cc \
-  pt-decl.cc \
-  pt-eval.cc \
-  pt-except.cc \
-  pt-exp.cc \
-  pt-fcn-handle.cc \
-  pt-id.cc \
-  pt-idx.cc \
-  pt-jump.cc \
-  pt-loop.cc \
-  pt-mat.cc \
-  pt-misc.cc \
-  pt-pr-code.cc \
-  pt-select.cc \
-  pt-stmt.cc \
-  pt-unop.cc \
-  pt.cc
+include parse-tree/module.mk
+include octave-value/module.mk
+include operators/module.mk
+include template-inst/module.mk
+include interp-core/module.mk
+include interpfcn/module.mk
+include corefcn/module.mk
+include dldfcn/module.mk
 
-DIST_SRC = \
-  Cell.cc \
-  bitfcns.cc \
-  c-file-ptr-stream.cc \
-  comment-list.cc \
-  cutils.c \
-  data.cc \
-  debug.cc \
-  defaults.cc \
-  defun.cc \
-  dirfns.cc \
-  display.cc \
-  dynamic-ld.cc \
-  error.cc \
-  file-io.cc \
-  gl-render.cc \
-  gl2ps-renderer.cc \
-  graphics.cc \
-  gripes.cc \
-  help.cc \
-  input.cc \
-  lex.ll \
-  load-path.cc \
-  load-save.cc \
-  ls-ascii-helper.cc \
-  ls-hdf5.cc \
-  ls-mat-ascii.cc \
-  ls-mat4.cc \
-  ls-mat5.cc \
-  ls-oct-ascii.cc \
-  ls-oct-binary.cc \
-  ls-utils.cc \
-  mappers.cc \
-  matherr.c \
-  mex.cc \
-  oct-fstrm.cc \
-  oct-hist.cc \
-  oct-iostrm.cc \
-  oct-lvalue.cc \
-  oct-map.cc \
-  oct-obj.cc \
-  oct-parse.yy \
-  oct-prcstrm.cc \
-  oct-procbuf.cc \
-  oct-stream.cc \
-  oct-strstrm.cc \
-  octave.cc \
-  pager.cc \
-  pr-output.cc \
-  procstream.cc \
-  profiler.cc \
-  sighandlers.cc \
-  siglist.c \
-  sparse.cc \
-  sparse-xdiv.cc \
-  sparse-xpow.cc \
-  strfns.cc \
-  symtab.cc \
-  syscalls.cc \
-  sysdep.cc \
-  token.cc \
-  toplev.cc \
-  txt-eng-ft.cc \
-  unwind-prot.cc \
-  utils.cc \
-  variables.cc \
-  xdiv.cc \
-  xgl2ps.c \
-  xnorm.cc \
-  xpow.cc \
-  zfstream.cc \
-  $(OV_SRC) \
-  $(PT_SRC)
-
-include DLD-FUNCTIONS/module.mk
-
-$(srcdir)/DLD-FUNCTIONS/module.mk: $(srcdir)/DLD-FUNCTIONS/config-module.sh $(srcdir)/DLD-FUNCTIONS/config-module.awk $(srcdir)/DLD-FUNCTIONS/module-files
-	$(srcdir)/DLD-FUNCTIONS/config-module.sh $(top_srcdir)
-
-include OPERATORS/module.mk
-include TEMPLATE-INST/module.mk
+$(srcdir)/dldfcn/module.mk: $(srcdir)/dldfcn/config-module.sh $(srcdir)/dldfcn/config-module.awk $(srcdir)/dldfcn/module-files
+	$(srcdir)/dldfcn/config-module.sh $(top_srcdir)
 
 if AMCOND_ENABLE_DYNAMIC_LINKING
-  OCT_FILES = $(DLD_FUNCTIONS_LIBS:.la=.oct)
-  OCT_STAMP_FILES = $(subst DLD-FUNCTIONS/,DLD-FUNCTIONS/$(am__leading_dot),$(DLD_FUNCTIONS_LIBS:.la=.oct-stamp))
+  OCT_FILES = $(DLDFCN_LIBS:.la=.oct)
+  OCT_STAMP_FILES = $(subst dldfcn/,dldfcn/$(am__leading_dot),$(DLDFCN_LIBS:.la=.oct-stamp))
+  DLD_LIBOCTINTERP_LIBADD = liboctinterp.la
 else
   OCT_FILES =
   OCT_STAMP_FILES =
+  DLD_LIBOCTINTERP_LIBADD =
 endif
 
 liboctinterp_la_SOURCES = \
-  $(DIST_SRC) \
+  octave.cc \
   $(OPERATORS_SRC) \
   $(TEMPLATE_INST_SRC)
 
 nodist_liboctinterp_la_SOURCES = \
+  interp-core/mxarray.h \
+  interp-core/oct-errno.cc \
+  interpfcn/defaults.h \
+  interpfcn/graphics.h \
+  operators/ops.cc \
+  builtin-defun-decls.h \
   builtins.cc \
-  defaults.h \
-  graphics.h \
-  mxarray.h \
   oct-conf.h \
-  oct-errno.cc \
-  ops.cc \
+  oct-conf-features.h \
   version.h \
   $(OPT_INC)
 
@@ -512,13 +178,18 @@
 include link-deps.mk
 
 liboctinterp_la_LIBADD = \
-  ../liboctave/liboctave.la \
-  ../libcruft/libcruft.la \
+  octave-value/liboctave-value.la \
+  parse-tree/libparse-tree.la \
+  parse-tree/libparser.la \
+  interp-core/libinterp-core.la \
+  interpfcn/libinterpfcn.la \
+  corefcn/libcorefcn.la \
+  $(top_builddir)/liboctave/liboctave.la \
   $(LIBOCTINTERP_LINK_DEPS)
 
 # Increment these as needed and according to the rules in the libtool manual:
 liboctinterp_current = 1
-liboctinterp_revision = 2
+liboctinterp_revision = 1
 liboctinterp_age = 0
 
 liboctinterp_version_info = $(liboctinterp_current):$(liboctinterp_revision):$(liboctinterp_age)
@@ -529,49 +200,59 @@
   -bindir $(bindir) \
   $(LIBOCTINTERP_LINK_OPTS)
 
-display.df display.lo: CPPFLAGS += $(X11_FLAGS)
-
-octave_SOURCES = main.c
+## Section for defining and creating DEF_FILES
 
-octave_LDADD = \
-  liboctinterp.la \
-  ../liboctave/liboctave.la \
-  ../libcruft/libcruft.la \
-  $(OCTAVE_LINK_DEPS)
+ULT_DIST_SRC := \
+  $(filter-out parse-tree/oct-parse.yy, $(DIST_SRC)) parse-tree/oct-parse.in.yy
 
-octave_LDFLAGS = \
-  $(NO_UNDEFINED_LDFLAG) \
-  $(OCTAVE_LINK_OPTS)
+SRC_DEF_FILES := $(shell $(srcdir)/find-defun-files.sh "$(srcdir)" $(ULT_DIST_SRC))
 
-## Section for defining and creating DEF_FILES
-SRC_DEF_FILES := $(shell $(srcdir)/find-defun-files.sh "$(srcdir)" $(DIST_SRC))
-
-DLD_FUNCTIONS_DEF_FILES = $(DLD_FUNCTIONS_SRC:.cc=.df)
+DLDFCN_DEF_FILES = $(DLDFCN_SRC:.cc=.df)
 
 ## builtins.cc depends on $(DEF_FILES), so DEF_FILES should only include
 ## .df files that correspond to sources included in liboctave.
 if AMCOND_ENABLE_DYNAMIC_LINKING
   DEF_FILES = $(SRC_DEF_FILES)
 else
-  DEF_FILES = $(SRC_DEF_FILES) $(DLD_FUNCTIONS_DEF_FILES)
+  DEF_FILES = $(SRC_DEF_FILES) $(DLDFCN_DEF_FILES)
 endif
 
-ALL_DEF_FILES = $(SRC_DEF_FILES) $(DLD_FUNCTIONS_DEF_FILES)
+ALL_DEF_FILES = $(SRC_DEF_FILES) $(DLDFCN_DEF_FILES)
 
 $(SRC_DEF_FILES): mkdefs Makefile
 
 $(DEF_FILES): $(OPT_HANDLERS) $(OPT_INC)
 
+## FIXME: The following two variables are deprecated and should be removed
+##        in Octave version 3.12.
 DLL_CDEFS = @OCTINTERP_DLL_DEFS@
 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 $@
 
+## Rules to build test files
+
+TST_FILES_SRC := $(shell $(top_srcdir)/build-aux/find-files-with-tests.sh "$(srcdir)" $(ULT_DIST_SRC) $(DLDFCN_SRC))
+
+TST_FILES := $(addsuffix -tst,$(TST_FILES_SRC))
+
+libinterptestsdir := $(octtestsdir)/libinterp
+
+nobase_libinterptests_DATA = $(TST_FILES)
+
 ## Override Automake's rule that forces a .hh extension on us even
 ## though we don't want it.  It would be super awesome if automake
 ## would allow users to choose the header file extension.
@@ -581,36 +262,20 @@
 ## Special rules:
 ## Mostly for sources which must be built before rest of compilation.
 
-## defaults.h and oct-conf.h must depend on Makefile.  Calling configure
-## may change default/config values.  However, calling configure will also
-## regenerate the Makefiles from Makefile.am and trigger the rules below.
-defaults.h: defaults.h.in Makefile
-	@$(do_subst_default_vals)
-
-graphics.h: graphics.h.in genprops.awk Makefile
-	$(AWK) -f $(srcdir)/genprops.awk $< > $@-t
-	mv $@-t $@
-
-oct-conf.h: oct-conf.h.in Makefile
+## oct-conf.h must depend on Makefile.
+## Calling configure may change default/config values.
+## However, calling configure will also regenerate the Makefiles from
+## Makefile.am and trigger the rules below.
+oct-conf.h: oct-conf.in.h Makefile
 	@$(do_subst_config_vals)
 
-## Don't use a pipeline to process gperf output since if gperf
-## is missing but sed is not, the exit status of the pipeline
-## will still be success and we will end up creating an empty
-## oct-gperf.h file.
-oct-gperf.h: octave.gperf
-	$(GPERF) -t -C -D -G -L C++ -Z octave_kw_hash $< > $@-t1
-	$(SED) 's,lookup\[,gperf_lookup[,' < $@-t1 > $@-t
-	mv $@-t $@
-	rm -f $@-t1
-
-mxarray.h: mxarray.h.in Makefile
-	$(SED) < $< \
-	  -e "s|%OCTAVE_IDX_TYPE%|${OCTAVE_IDX_TYPE}|" > $@-t
+oct-conf-features.h: $(top_builddir)/config.h config-features.sh
+	$(srcdir)/config-features.sh $< > $@-t
 	mv $@-t $@
 
-version.h: version.h.in Makefile
+version.h: version.in.h Makefile
 	$(SED) < $< \
+	  -e "s|%NO_EDIT_WARNING%|DO NOT EDIT!  Generated automatically from $(<F) by Make.|" \
 	  -e "s|%OCTAVE_API_VERSION_NUMBER%|${OCTAVE_API_VERSION_NUMBER}|" \
 	  -e "s|%OCTAVE_API_VERSION%|\"${OCTAVE_API_VERSION}\"|" \
 	  -e "s|%OCTAVE_COPYRIGHT%|\"${OCTAVE_COPYRIGHT}\"|" \
@@ -619,51 +284,21 @@
 	mv $@-t $@
 
 builtins.cc: $(DEF_FILES) mkbuiltins
-	$(srcdir)/mkbuiltins $(DEF_FILES) > $@-t
-	mv $@-t $@
-
-graphics-props.cc: graphics.h.in genprops.awk Makefile
-	$(AWK) -v emit_graphics_props=1 -f $(srcdir)/genprops.awk $< > $@-t
+	$(srcdir)/mkbuiltins --source $(DEF_FILES) > $@-t
 	mv $@-t $@
 
-ops.cc: $(OPERATORS_SRC) mkops
-	$(srcdir)/mkops $(OPERATORS_SRC) > $@-t
-	mv $@-t $@
-
-oct-errno.cc: oct-errno.cc.in Makefile
-	if test -n "$(PERL)"; then \
-	  $(srcdir)/mk-errno-list --perl "$(PERL)" < $< > $@-t; \
-	elif test -n "$(PYTHON)"; then \
-	  $(srcdir)/mk-errno-list --python "$(PYTHON)" < $< > $@-t; \
-	else \
-	  $(SED) '/@SYSDEP_ERRNO_LIST@/D' $< > $@-t; \
-	fi
+builtin-defun-decls.h: $(SRC_DEF_FILES) mkbuiltins
+	$(srcdir)/mkbuiltins --header $(SRC_DEF_FILES) > $@-t
 	mv $@-t $@
 
-$(OPT_HANDLERS) : %.cc : $(top_srcdir)/liboctave/%.in $(top_srcdir)/build-aux/mk-opts.pl
-	$(PERL) $(top_srcdir)/build-aux/mk-opts.pl --opt-handler-fcns $< > $@-t
-	mv $@-t $@
+if AMCOND_ENABLE_DYNAMIC_LINKING
+DLDFCN_PKG_ADD_FILE = dldfcn/PKG_ADD
 
-$(OPT_INC) : %.h : %.in
-	$(MAKE) -C $(@D) $(@F)
-
-if AMCOND_ENABLE_DYNAMIC_LINKING
-DLD_FUNCTIONS_PKG_ADD_FILE = DLD-FUNCTIONS/PKG_ADD
-
-DLD-FUNCTIONS/PKG_ADD: $(DLD_FUNCTIONS_DEF_FILES) mk-pkg-add
-	$(srcdir)/mk-pkg-add $(DLD_FUNCTIONS_DEF_FILES) > $@-t
+dldfcn/PKG_ADD: $(DLDFCN_DEF_FILES) mk-pkg-add
+	$(srcdir)/mk-pkg-add $(DLDFCN_DEF_FILES) > $@-t
 	mv $@-t $@
 endif
 
-lex.lo lex.o oct-parse.lo oct-parse.o: \
-  AM_CXXFLAGS := $(filter-out -Wold-style-cast, $(AM_CXXFLAGS))
-
-__fltk_uigetfile__.lo __fltk_uigetfile__.o: \
-  AM_CXXFLAGS := $(filter-out $(DLL_CXXDEFS), $(AM_CXXFLAGS) $(GRAPHICS_CFLAGS))
-
-__init_fltk__.lo __init_fltk__.o: \
-  AM_CXXFLAGS := $(filter-out $(DLL_CXXDEFS), $(AM_CXXFLAGS) $(GRAPHICS_CFLAGS))
-
 if AMCOND_BUILD_DOCS
 .DOCSTRINGS: $(ALL_DEF_FILES) gendoc.pl
 	if [ "x$(srcdir)" != "x." ] && [ -f $(srcdir)/DOCSTRINGS ] && [ ! -f DOCSTRINGS ]; then \
@@ -675,67 +310,27 @@
 	$(top_srcdir)/build-aux/move-if-change $@ DOCSTRINGS
 	touch $@
 
-all-local: $(OCT_STAMP_FILES) $(DLD_FUNCTIONS_PKG_ADD_FILE) .DOCSTRINGS
+all-local: $(OCT_STAMP_FILES) $(DLDFCN_PKG_ADD_FILE) .DOCSTRINGS
 else
-all-local: $(OCT_STAMP_FILES) $(DLD_FUNCTIONS_PKG_ADD_FILE)
-endif
-
-if AMCOND_BUILD_COMPILED_AUX_PROGRAMS
-octave-config.cc: octave-config.cc.in Makefile
-	@$(do_subst_default_vals)
-
-mkoctfile.cc: mkoctfile.cc.in Makefile
-	@$(do_subst_config_vals)
-else
-octave-config: octave-config.in Makefile
-	@$(do_subst_default_vals)
-	chmod a+rx $@
-
-mkoctfile: mkoctfile.in Makefile
-	@$(do_subst_config_vals)
-	chmod a+rx $@
+all-local: $(OCT_STAMP_FILES) $(DLDFCN_PKG_ADD_FILE)
 endif
 
-install-exec-hook: make-version-links
-
-install-data-hook: install-oct
-
-uninstall-local: remove-version-links uninstall-oct
-
-make-version-links:
-	cd $(DESTDIR)$(bindir) && \
-	for f in $(basename $(bin_PROGRAMS)); do \
-	  mv $$f$(EXEEXT) $$f-$(version)$(EXEEXT) && \
-	    $(LN_S) $$f-$(version)$(EXEEXT) $$f$(EXEEXT); \
-	done
-if ! AMCOND_BUILD_COMPILED_AUX_PROGRAMS
-	cd $(DESTDIR)$(bindir) && \
-	for f in $(basename $(bin_SCRIPTS)); do \
-	  mv $$f $$f-$(version) && \
-	    $(LN_S) $$f-$(version) $$f; \
-	done
+if AMCOND_BUILD_DOCS
+install-data-hook: install-oct install-built-in-docstrings
+else
+install-data-hook: install-oct uninstall-built-in-docstrings
 endif
 
-remove-version-links:
-	for f in $(basename $(bin_PROGRAMS)); do \
-	  rm -f $(DESTDIR)$(bindir)/$$f-$(version)$(EXEEXT); \
-	done
-if ! AMCOND_BUILD_COMPILED_AUX_PROGRAMS
-	for f in $(basename $(bin_SCRIPTS)); do \
-	  rm -f $(DESTDIR)$(bindir)/$$f-$(version); \
-	done
-endif
-
-.PHONY: make-version-links remove-version-links
+uninstall-local: uninstall-oct uninstall-built-in-docstrings
 
 if AMCOND_ENABLE_DYNAMIC_LINKING
 install-oct:
 	$(top_srcdir)/build-aux/mkinstalldirs $(DESTDIR)$(octfiledir)
-	if [ -n "`cat $(DLD_FUNCTIONS_PKG_ADD_FILE)`" ]; then \
-	  $(INSTALL_DATA) $(DLD_FUNCTIONS_PKG_ADD_FILE) $(DESTDIR)$(octfiledir)/PKG_ADD; \
+	if [ -n "`cat $(DLDFCN_PKG_ADD_FILE)`" ]; then \
+	  $(INSTALL_DATA) $(DLDFCN_PKG_ADD_FILE) $(DESTDIR)$(octfiledir)/PKG_ADD; \
 	fi
 	cd $(DESTDIR)$(octlibdir) && \
-	for ltlib in $(DLD_FUNCTIONS_LIBS); do \
+	for ltlib in $(DLDFCN_LIBS); do \
 	  f=`echo $$ltlib | $(SED) 's,.*/,,'`; \
 	  dl=`$(SED) -n -e "s/dlname='\([^']*\)'/\1/p" < $$f`; \
 	  if [ -n "$$dl" ]; then \
@@ -758,18 +353,29 @@
 endif
 .PHONY: install-oct uninstall-oct
 
+if AMCOND_BUILD_DOCS
+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 uninstall-built-in-docstrings
+
 CLEANFILES = \
-  $(bin_SCRIPTS) \
-  $(DLD_FUNCTIONS_PKG_ADD_FILE) \
-  graphics-props.cc \
-  oct-parse.output
+  $(DLDFCN_PKG_ADD_FILE) \
+  interpfcn/graphics-props.cc \
+  parse-tree/oct-parse.output
 
 DISTCLEANFILES = \
   .DOCSTRINGS \
   DOCSTRINGS \
   $(BUILT_NODISTFILES) \
   $(OCT_FILES) \
-  $(OCT_STAMP_FILES)
+  $(OCT_STAMP_FILES) \
+  $(TST_FILES)
 
 MAINTAINERCLEANFILES = \
   $(BUILT_DISTFILES)
+
rename from src/builtins.h
rename to libinterp/builtins.h
--- a/src/builtins.h
+++ b/libinterp/builtins.h
@@ -23,6 +23,10 @@
 #if !defined (octave_builtins_h)
 #define octave_builtins_h 1
 
+#if !defined (MAKE_BUILTINS)
+#include "builtin-defun-decls.h"
+#endif
+
 extern OCTINTERP_API void install_builtins (void);
 
 #endif
new file mode 100755
--- /dev/null
+++ b/libinterp/config-features.sh
@@ -0,0 +1,36 @@
+#! /bin/sh
+
+set -e
+AWK=${AWK:-awk}
+
+conffile=$1
+
+cat << EOF
+// DO NOT EDIT!  Generated automatically from $conffile by Make."
+
+#include "oct-map.h"
+#include "ov.h"
+
+octave_scalar_map
+octave_config_features (void)
+{
+  octave_scalar_map m;
+
+EOF
+
+$AWK \
+  '/#define HAVE_/ {
+     sub (/HAVE_/, "", $2);
+     printf ("  m.assign (\"%s\", octave_value (true));\n", $2);
+   }
+   /\/\* #undef HAVE_/ {
+     sub (/HAVE_/, "", $3);
+     printf ("  m.assign (\"%s\", octave_value (false));\n", $3);
+   } {
+   }' $conffile
+
+cat << EOF
+
+  return m;
+}
+EOF
rename from src/DLD-FUNCTIONS/__contourc__.cc
rename to libinterp/corefcn/__contourc__.cc
--- a/src/DLD-FUNCTIONS/__contourc__.cc
+++ b/libinterp/corefcn/__contourc__.cc
@@ -40,7 +40,7 @@
 
 #include "quit.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "oct-obj.h"
 
@@ -97,54 +97,87 @@
         unsigned int start_edge, bool first, charMatrix& mark)
 {
   double px[4], py[4], pz[4], tmp;
-  unsigned int stop_edge, next_edge, pt[2];
-  int next_r, next_c;
+  unsigned int stop_edge, pt[2];
+
+  // Continue while next facet is not done yet.
+  while (r >= 0 && c >= 0 && r < mark.rows () && c < mark.cols ()
+         && mark(r, c) > 0)
+    {
 
-  //get x, y, and z - lvl for current facet
-  px[0] = px[3] = X(c);
-  px[1] = px[2] = X(c+1);
+      //get x, y, and z - lvl for current facet
+      px[0] = px[3] = X(c);
+      px[1] = px[2] = X(c+1);
 
-  py[0] = py[1] = Y(r);
-  py[2] = py[3] = Y(r+1);
+      py[0] = py[1] = Y(r);
+      py[2] = py[3] = Y(r+1);
+
+      pz[3] = Z(r+1, c) - lvl;
+      pz[2] = Z(r+1, c + 1) - lvl;
+      pz[1] = Z(r, c+1) - lvl;
+      pz[0] = Z(r, c) - lvl;
 
-  pz[3] = Z(r+1, c) - lvl;
-  pz[2] = Z(r+1, c + 1) - lvl;
-  pz[1] = Z(r, c+1) - lvl;
-  pz[0] = Z(r, c) - lvl;
+      // Facet edge and point naming assignment.
+      //
+      //  0-----1   .-0-.
+      //  |     |   |   |
+      //  |     |   3   1
+      //  |     |   |   |
+      //  3-----2   .-2-.
 
-  // Facet edge and point naming assignment.
-  //
-  //  0-----1   .-0-.
-  //  |     |   |   |
-  //  |     |   3   1
-  //  |     |   |   |
-  //  3-----2   .-2-.
+      // Get mark value of current facet.
+      char id = static_cast<char> (mark(r, c));
+
+      // Check startedge s.
+      if (start_edge == 255)
+        {
+          // Find start edge.
+          for (unsigned int k = 0; k < 4; k++)
+            if (static_cast<char> (1 << k) & id)
+              start_edge = k;
+        }
 
-  // Get mark value of current facet.
-  char id = static_cast<char> (mark(r, c));
+      if (start_edge == 255)
+        break;
+
+      // Decrease mark value of current facet for start edge.
+      mark(r, c) -= static_cast<char> (1 << start_edge);
 
-  // Check startedge s.
-  if (start_edge == 255)
-    {
-      // Find start edge.
-      for (unsigned int k = 0; k < 4; k++)
-        if (static_cast<char> (1 << k) & id)
-          start_edge = k;
-    }
+      // Next point (clockwise).
+      pt[0] = start_edge;
+      pt[1] = (pt[0] + 1) % 4;
+
+      // Calculate contour segment start if first of contour.
+      if (first)
+        {
+          tmp = fabs (pz[pt[1]]) / fabs (pz[pt[0]]);
 
-  if (start_edge == 255)
-    return;
+          if (xisnan (tmp))
+            ct_x = ct_y = 0.5;
+          else
+            {
+              ct_x = px[pt[0]] + (px[pt[1]] - px[pt[0]])/(1 + tmp);
+              ct_y = py[pt[0]] + (py[pt[1]] - py[pt[0]])/(1 + tmp);
+            }
 
-  // Decrease mark value of current facet for start edge.
-  mark(r, c) -= static_cast<char> (1 << start_edge);
+          start_contour (lvl, ct_x, ct_y);
+          first = false;
+        }
 
-  // Next point (clockwise).
-  pt[0] = start_edge;
-  pt[1] = (pt[0] + 1) % 4;
+      // Find stop edge.
+      // FIXME -- perhaps this should use a while loop?
+      for (unsigned int k = 1; k <= 4; k++)
+        {
+          if (start_edge == 0 || start_edge == 2)
+            stop_edge = (start_edge + k) % 4;
+          else
+            stop_edge = (start_edge - k) % 4;
 
-  // Calculate contour segment start if first of contour.
-  if (first)
-    {
+          if (static_cast<char> (1 << stop_edge) & id)
+            break;
+        }
+
+      pt[0] = stop_edge;
+      pt[1] = (pt[0] + 1) % 4;
       tmp = fabs (pz[pt[1]]) / fabs (pz[pt[0]]);
 
       if (xisnan (tmp))
@@ -155,60 +188,25 @@
           ct_y = py[pt[0]] + (py[pt[1]] - py[pt[0]])/(1 + tmp);
         }
 
-      start_contour (lvl, ct_x, ct_y);
-    }
+      // Add point to contour.
+      add_point (ct_x, ct_y);
 
-  // Find stop edge.
-  // FIXME -- perhaps this should use a while loop?
-  for (unsigned int k = 1; k <= 4; k++)
-    {
-      if (start_edge == 0 || start_edge == 2)
-        stop_edge = (start_edge + k) % 4;
-      else
-        stop_edge = (start_edge - k) % 4;
-
-      if (static_cast<char> (1 << stop_edge) & id)
-        break;
-    }
-
-  pt[0] = stop_edge;
-  pt[1] = (pt[0] + 1) % 4;
-  tmp = fabs (pz[pt[1]]) / fabs (pz[pt[0]]);
+      // Decrease id value of current facet for start edge.
+      mark(r, c) -= static_cast<char> (1 << stop_edge);
 
-  if (xisnan (tmp))
-    ct_x = ct_y = 0.5;
-  else
-    {
-      ct_x = px[pt[0]] + (px[pt[1]] - px[pt[0]])/(1 + tmp);
-      ct_y = py[pt[0]] + (py[pt[1]] - py[pt[0]])/(1 + tmp);
-    }
-
-  // Add point to contour.
-  add_point (ct_x, ct_y);
-
-  // Decrease id value of current facet for start edge.
-  mark(r, c) -= static_cast<char> (1 << stop_edge);
+      // Find next facet.
+      if (stop_edge == 0)
+        r--;
+      else if (stop_edge == 1)
+        c++;
+      else if (stop_edge == 2)
+        r++;
+      else if (stop_edge == 3)
+        c--;
 
-  // Find next facet.
-  next_c = c;
-  next_r = r;
+      // Go to next facet.
+      start_edge = (stop_edge + 2) % 4;
 
-  if (stop_edge == 0)
-    next_r--;
-  else if (stop_edge == 1)
-    next_c++;
-  else if (stop_edge == 2)
-    next_r++;
-  else if (stop_edge == 3)
-    next_c--;
-
-  // Check if next facet is not done yet.
-  // Go to next facet.
-  if (next_r >= 0 && next_c >= 0 && next_r < mark.rows ()
-      && next_c < mark.cols () && mark(next_r, next_c) > 0)
-    {
-      next_edge = (stop_edge + 2) % 4;
-      drawcn (X, Y, Z, lvl, next_r, next_c, ct_x, ct_y, next_edge, false, mark);
     }
 }
 
@@ -229,8 +227,8 @@
         f[2] = Z(r+1, c+1) - lvl;
 
         for (unsigned int i = 0; i < 4; i++)
-          if (fabs(f[i]) < DBL_EPSILON)
-            f[i] = DBL_EPSILON;
+          if (fabs(f[i]) < std::numeric_limits<double>::epsilon ())
+            f[i] = std::numeric_limits<double>::epsilon ();
 
         if (f[1] * f[2] < 0)
           mark(r, c) += 2;
@@ -248,8 +246,8 @@
         f[2] = Z(r+1, c+1) - lvl;
 
         for (unsigned int i = 0; i < 4; i++)
-          if (fabs(f[i]) < DBL_EPSILON)
-            f[i] = DBL_EPSILON;
+          if (fabs(f[i]) < std::numeric_limits<double>::epsilon ())
+            f[i] = std::numeric_limits<double>::epsilon ();
 
         if (f[0] * f[1] < 0)
           mark(r, c) += 1;
@@ -299,9 +297,9 @@
         drawcn (X, Y, Z, lvl, r, c, 0.0, 0.0, 255, true, mark);
 }
 
-DEFUN_DLD (__contourc__, args, ,
+DEFUN (__contourc__, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} __contourc__ (@var{x}, @var{y}, @var{z}, @var{levels})\n\
+@deftypefn {Built-in Function} {} __contourc__ (@var{x}, @var{y}, @var{z}, @var{levels})\n\
 Undocumented internal function.\n\
 @end deftypefn")
 {
@@ -335,8 +333,6 @@
 }
 
 /*
-
 ## No test needed for internal helper function.
 %!assert (1)
-
 */
rename from src/DLD-FUNCTIONS/__dispatch__.cc
rename to libinterp/corefcn/__dispatch__.cc
--- a/src/DLD-FUNCTIONS/__dispatch__.cc
+++ b/libinterp/corefcn/__dispatch__.cc
@@ -30,7 +30,7 @@
 
 #include "Cell.h"
 #include "oct-map.h"
-#include "defun-dld.h"
+#include "defun.h"
 #include "ov.h"
 #include "ov-fcn.h"
 #include "ov-typeinfo.h"
@@ -39,7 +39,7 @@
 #include "symtab.h"
 #include "variables.h"
 
-DEFUN_DLD (__dispatch__, args, nargout,
+DEFUN (__dispatch__, args, nargout,
   "Undocumented internal function")
 {
   octave_value retval;
@@ -131,8 +131,6 @@
 }
 
 /*
-
 ## No test needed for internal helper function.
 %!assert (1)
-
 */
rename from src/DLD-FUNCTIONS/__lin_interpn__.cc
rename to libinterp/corefcn/__lin_interpn__.cc
--- a/src/DLD-FUNCTIONS/__lin_interpn__.cc
+++ b/libinterp/corefcn/__lin_interpn__.cc
@@ -28,7 +28,7 @@
 #include "dNDArray.h"
 #include "oct-locbuf.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "oct-obj.h"
 
@@ -195,7 +195,7 @@
   for (int i = 0; i < n; i++)
     {
       y[i] = Y[i].data ();
-      size[i] =  V.dims()(i);
+      size[i] =  V.dims ()(i);
     }
 
   OCTAVE_LOCAL_BUFFER (const T *, x, n);
@@ -267,9 +267,9 @@
 //
 //This function only performs linear interpolation.
 
-DEFUN_DLD (__lin_interpn__, args, ,
+DEFUN (__lin_interpn__, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{vi} =} __lin_interpn__ (@var{x1}, @var{x2}, @dots{}, @var{xn}, @var{v}, @var{y1}, @var{y2}, @dots{}, @var{yn})\n\
+@deftypefn {Built-in Function} {@var{vi} =} __lin_interpn__ (@var{x1}, @var{x2}, @dots{}, @var{xn}, @var{v}, @var{y1}, @var{y2}, @dots{}, @var{yn})\n\
 Undocumented internal function.\n\
 @end deftypefn")
 {
@@ -286,7 +286,7 @@
   // dimension of the problem
   int n = (nargin-1)/2;
 
-  if (args(n).is_single_type())
+  if (args(n).is_single_type ())
     {
       OCTAVE_LOCAL_BUFFER (FloatNDArray, X, n);
       OCTAVE_LOCAL_BUFFER (FloatNDArray, Y, n);
@@ -357,8 +357,6 @@
 }
 
 /*
-
 ## No test needed for internal helper function.
 %!assert (1)
-
 */
rename from src/DLD-FUNCTIONS/__pchip_deriv__.cc
rename to libinterp/corefcn/__pchip_deriv__.cc
--- a/src/DLD-FUNCTIONS/__pchip_deriv__.cc
+++ b/libinterp/corefcn/__pchip_deriv__.cc
@@ -25,7 +25,7 @@
 #include <config.h>
 #endif
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -50,16 +50,16 @@
 // Wrapper for SLATEC/PCHIP function DPCHIM to calculate the derivates
 // for piecewise polynomials.
 
-DEFUN_DLD (__pchip_deriv__, args, ,
+DEFUN (__pchip_deriv__, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} __pchip_deriv__ (@var{x}, @var{y}, @var{dim})\n\
+@deftypefn {Built-in Function} {} __pchip_deriv__ (@var{x}, @var{y}, @var{dim})\n\
 Undocumented internal function.\n\
 @end deftypefn")
 {
   octave_value retval;
   const int nargin = args.length ();
 
-  bool rows = (nargin == 3 && args (2).uint_value() == 2);
+  bool rows = (nargin == 3 && args (2).uint_value () == 2);
 
   if (nargin >= 2)
     {
@@ -163,8 +163,6 @@
 }
 
 /*
-
 ## No test needed for internal helper function.
 %!assert (1)
-
 */
rename from src/DLD-FUNCTIONS/__qp__.cc
rename to libinterp/corefcn/__qp__.cc
--- a/src/DLD-FUNCTIONS/__qp__.cc
+++ b/libinterp/corefcn/__qp__.cc
@@ -31,7 +31,7 @@
 #include "mx-m-dm.h"
 #include "EIG.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -51,7 +51,7 @@
 
       DiagMatrix S = A_svd.singular_values ();
 
-      ColumnVector s = S.diag ();
+      ColumnVector s = S.extract_diag ();
 
       Matrix V = A_svd.right_singular_matrix ();
 
@@ -60,7 +60,7 @@
 
       octave_idx_type tmp = A_nr > A_nc ? A_nr : A_nc;
 
-      double tol = tmp * s(0) * DBL_EPSILON;
+      double tol = tmp * s(0) * std::numeric_limits<double>::epsilon ();
 
       octave_idx_type n = s.length ();
 
@@ -76,7 +76,7 @@
         retval.resize (A_nc, 0);
 
       for (octave_idx_type i = 0; i < retval.numel (); i++)
-        if (std::abs (retval(i)) < DBL_EPSILON)
+        if (std::abs (retval(i)) < std::numeric_limits<double>::epsilon ())
           retval(i) = 0;
     }
 
@@ -94,7 +94,7 @@
 
   iter = 0;
 
-  double rtol = sqrt (DBL_EPSILON);
+  double rtol = sqrt (std::numeric_limits<double>::epsilon ());
 
   // Problem dimension.
   octave_idx_type n = x.length ();
@@ -209,7 +209,7 @@
 
               // Following the negative curvature of H.
 
-              if (p.transpose () * g > DBL_EPSILON)
+              if (p.transpose () * g > std::numeric_limits<double>::epsilon ())
                 p = -p;
 
               info = 1;
@@ -307,7 +307,7 @@
               // Computing the step pz.
               p = Z * eVrH;
 
-              if (p.transpose () * g > DBL_EPSILON)
+              if (p.transpose () * g > std::numeric_limits<double>::epsilon ())
                 p = -p;
             }
         }
@@ -479,9 +479,9 @@
   return info;
 }
 
-DEFUN_DLD (__qp__, args, ,
+DEFUN (__qp__, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {[@var{x}, @var{lambda}, @var{info}, @var{iter}] =} __qp__ (@var{x0}, @var{H}, @var{q}, @var{Aeq}, @var{beq}, @var{Ain}, @var{bin}, @var{maxit})\n\
+@deftypefn {Built-in Function} {[@var{x}, @var{lambda}, @var{info}, @var{iter}] =} __qp__ (@var{x0}, @var{H}, @var{q}, @var{Aeq}, @var{beq}, @var{Ain}, @var{bin}, @var{maxit})\n\
 Undocumented internal function.\n\
 @end deftypefn")
 {
@@ -530,8 +530,6 @@
 }
 
 /*
-
 ## No test needed for internal helper function.
 %!assert (1)
-
 */
rename from src/DLD-FUNCTIONS/balance.cc
rename to libinterp/corefcn/balance.cc
--- a/src/DLD-FUNCTIONS/balance.cc
+++ b/libinterp/corefcn/balance.cc
@@ -39,20 +39,20 @@
 #include "floatGEPBAL.h"
 #include "quit.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "f77-fcn.h"
 #include "gripes.h"
 #include "oct-obj.h"
 #include "utils.h"
 
-DEFUN_DLD (balance, args, nargout,
+DEFUN (balance, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{AA} =} balance (@var{A})\n\
-@deftypefnx {Loadable Function} {@var{AA} =} balance (@var{A}, @var{opt})\n\
-@deftypefnx {Loadable Function} {[@var{DD}, @var{AA}] =} balance (@var{A}, @var{opt})\n\
-@deftypefnx {Loadable Function} {[@var{D}, @var{P}, @var{AA}] =} balance (@var{A}, @var{opt})\n\
-@deftypefnx {Loadable Function} {[@var{CC}, @var{DD}, @var{AA}, @var{BB}] =} balance (@var{A}, @var{B}, @var{opt})\n\
+@deftypefn  {Built-in Function} {@var{AA} =} balance (@var{A})\n\
+@deftypefnx {Built-in Function} {@var{AA} =} balance (@var{A}, @var{opt})\n\
+@deftypefnx {Built-in Function} {[@var{DD}, @var{AA}] =} balance (@var{A}, @var{opt})\n\
+@deftypefnx {Built-in Function} {[@var{D}, @var{P}, @var{AA}] =} balance (@var{A}, @var{opt})\n\
+@deftypefnx {Built-in Function} {[@var{CC}, @var{DD}, @var{AA}, @var{BB}] =} balance (@var{A}, @var{B}, @var{opt})\n\
 \n\
 Compute @code{@var{AA} = @var{DD} \\ @var{A} * @var{DD}} in which @var{AA}\n\
 is a matrix whose row and column norms are roughly equal in magnitude, and\n\
@@ -104,14 +104,14 @@
   // problem dimension
   octave_idx_type nn = args(0).rows ();
 
-  if (nn != args(0).columns())
+  if (nn != args(0).columns ())
     {
       gripe_square_matrix_required ("balance");
       return retval;
     }
 
   bool isfloat = args(0).is_single_type () ||
-    (! AEPcase && args(1).is_single_type());
+    (! AEPcase && args(1).is_single_type ());
 
   bool complex_case = (args(0).is_complex_type () ||
                        (! AEPcase && args(1).is_complex_type ()));
rename from src/DLD-FUNCTIONS/besselj.cc
rename to libinterp/corefcn/besselj.cc
--- a/src/DLD-FUNCTIONS/besselj.cc
+++ b/libinterp/corefcn/besselj.cc
@@ -27,7 +27,7 @@
 #include "lo-specfun.h"
 #include "quit.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -376,33 +376,33 @@
   return retval;
 }
 
-DEFUN_DLD (besselj, args, nargout,
+DEFUN (besselj, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {[@var{j}, @var{ierr}] =} besselj (@var{alpha}, @var{x}, @var{opt})\n\
-@deftypefnx {Loadable Function} {[@var{y}, @var{ierr}] =} bessely (@var{alpha}, @var{x}, @var{opt})\n\
-@deftypefnx {Loadable Function} {[@var{i}, @var{ierr}] =} besseli (@var{alpha}, @var{x}, @var{opt})\n\
-@deftypefnx {Loadable Function} {[@var{k}, @var{ierr}] =} besselk (@var{alpha}, @var{x}, @var{opt})\n\
-@deftypefnx {Loadable Function} {[@var{h}, @var{ierr}] =} besselh (@var{alpha}, @var{k}, @var{x}, @var{opt})\n\
+@deftypefn  {Built-in Function} {[@var{j}, @var{ierr}] =} besselj (@var{alpha}, @var{x}, @var{opt})\n\
+@deftypefnx {Built-in Function} {[@var{y}, @var{ierr}] =} bessely (@var{alpha}, @var{x}, @var{opt})\n\
+@deftypefnx {Built-in Function} {[@var{i}, @var{ierr}] =} besseli (@var{alpha}, @var{x}, @var{opt})\n\
+@deftypefnx {Built-in Function} {[@var{k}, @var{ierr}] =} besselk (@var{alpha}, @var{x}, @var{opt})\n\
+@deftypefnx {Built-in Function} {[@var{h}, @var{ierr}] =} besselh (@var{alpha}, @var{k}, @var{x}, @var{opt})\n\
 Compute Bessel or Hankel functions of various kinds:\n\
 \n\
 @table @code\n\
 @item besselj\n\
 Bessel functions of the first kind.  If the argument @var{opt} is supplied,\n\
-the result is multiplied by @code{exp(-abs(imag(@var{x})))}.\n\
+the result is multiplied by @code{exp (-abs (imag (@var{x})))}.\n\
 \n\
 @item bessely\n\
 Bessel functions of the second kind.  If the argument @var{opt} is supplied,\n\
-the result is multiplied by @code{exp(-abs(imag(@var{x})))}.\n\
+the result is multiplied by @code{exp (-abs (imag (@var{x})))}.\n\
 \n\
 @item besseli\n\
 \n\
 Modified Bessel functions of the first kind.  If the argument @var{opt} is\n\
-supplied, the result is multiplied by @code{exp(-abs(real(@var{x})))}.\n\
+supplied, the result is multiplied by @code{exp (-abs (real (@var{x})))}.\n\
 \n\
 @item besselk\n\
 \n\
 Modified Bessel functions of the second kind.  If the argument @var{opt} is\n\
-supplied, the result is multiplied by @code{exp(@var{x})}.\n\
+supplied, the result is multiplied by @code{exp (@var{x})}.\n\
 \n\
 @item besselh\n\
 Compute Hankel functions of the first (@var{k} = 1) or second (@var{k}\n\
@@ -450,36 +450,36 @@
   return do_bessel (BESSEL_J, "besselj", args, nargout);
 }
 
-DEFUN_DLD (bessely, args, nargout,
+DEFUN (bessely, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {[@var{y}, @var{ierr}] =} bessely (@var{alpha}, @var{x}, @var{opt})\n\
+@deftypefn {Built-in Function} {[@var{y}, @var{ierr}] =} bessely (@var{alpha}, @var{x}, @var{opt})\n\
 See besselj.\n\
 @end deftypefn")
 {
   return do_bessel (BESSEL_Y, "bessely", args, nargout);
 }
 
-DEFUN_DLD (besseli, args, nargout,
+DEFUN (besseli, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {[@var{i}, @var{ierr}] =} besseli (@var{alpha}, @var{x}, @var{opt})\n\
+@deftypefn {Built-in Function} {[@var{i}, @var{ierr}] =} besseli (@var{alpha}, @var{x}, @var{opt})\n\
 See besselj.\n\
 @end deftypefn")
 {
   return do_bessel (BESSEL_I, "besseli", args, nargout);
 }
 
-DEFUN_DLD (besselk, args, nargout,
+DEFUN (besselk, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {[@var{k}, @var{ierr}] =} besselk (@var{alpha}, @var{x}, @var{opt})\n\
+@deftypefn {Built-in Function} {[@var{k}, @var{ierr}] =} besselk (@var{alpha}, @var{x}, @var{opt})\n\
 See besselj.\n\
 @end deftypefn")
 {
   return do_bessel (BESSEL_K, "besselk", args, nargout);
 }
 
-DEFUN_DLD (besselh, args, nargout,
+DEFUN (besselh, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {[@var{h}, @var{ierr}] =} besselh (@var{alpha}, @var{k}, @var{x}, @var{opt})\n\
+@deftypefn {Built-in Function} {[@var{h}, @var{ierr}] =} besselh (@var{alpha}, @var{k}, @var{x}, @var{opt})\n\
 See besselj.\n\
 @end deftypefn")
 {
@@ -521,9 +521,9 @@
   return retval;
 }
 
-DEFUN_DLD (airy, args, nargout,
+DEFUN (airy, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {[@var{a}, @var{ierr}] =} airy (@var{k}, @var{z}, @var{opt})\n\
+@deftypefn {Built-in Function} {[@var{a}, @var{ierr}] =} airy (@var{k}, @var{z}, @var{opt})\n\
 Compute Airy functions of the first and second kind, and their\n\
 derivatives.\n\
 \n\
@@ -533,8 +533,8 @@
 ---  --------   ---------------------------------------\n\
  0   Ai (Z)     exp ((2/3) * Z * sqrt (Z))\n\
  1   dAi(Z)/dZ  exp ((2/3) * Z * sqrt (Z))\n\
- 2   Bi (Z)     exp (-abs (real ((2/3) * Z *sqrt (Z))))\n\
- 3   dBi(Z)/dZ  exp (-abs (real ((2/3) * Z *sqrt (Z))))\n\
+ 2   Bi (Z)     exp (-abs (real ((2/3) * Z * sqrt (Z))))\n\
+ 3   dBi(Z)/dZ  exp (-abs (real ((2/3) * Z * sqrt (Z))))\n\
 @end group\n\
 @end example\n\
 \n\
@@ -654,92 +654,92 @@
 %!shared alpha, x, jx, yx, ix, kx, nix
 %!
 %! # Bessel functions, even order, positive and negative x
-%! alpha = 2; x = 1.25;
+%! alpha = 2;  x = 1.25;
 %! jx = 0.1710911312405234823613091417;
 %! yx = -1.193199310178553861283790424;
 %! ix = 0.2220184483766341752692212604;
 %! kx = 0.9410016167388185767085460540;
 %!
-%!assert(besselj(alpha,x), jx, 100*eps)
-%!assert(bessely(alpha,x), yx, 100*eps)
-%!assert(besseli(alpha,x), ix, 100*eps)
-%!assert(besselk(alpha,x), kx, 100*eps)
-%!assert(besselh(alpha,1,x), jx + I*yx, 100*eps)
-%!assert(besselh(alpha,2,x), jx - I*yx, 100*eps)
+%!assert (besselj (alpha,x), jx, 100*eps)
+%!assert (bessely (alpha,x), yx, 100*eps)
+%!assert (besseli (alpha,x), ix, 100*eps)
+%!assert (besselk (alpha,x), kx, 100*eps)
+%!assert (besselh (alpha,1,x), jx + I*yx, 100*eps)
+%!assert (besselh (alpha,2,x), jx - I*yx, 100*eps)
 %!
-%!assert(besselj(alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
+%!assert (besselj (alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
 %!
-%!assert(besselj(-alpha,x), jx, 100*eps)
-%!assert(bessely(-alpha,x), yx, 100*eps)
-%!assert(besseli(-alpha,x), ix, 100*eps)
-%!assert(besselk(-alpha,x), kx, 100*eps)
-%!assert(besselh(-alpha,1,x), jx + I*yx, 100*eps)
-%!assert(besselh(-alpha,2,x), jx - I*yx, 100*eps)
+%!assert (besselj (-alpha,x), jx, 100*eps)
+%!assert (bessely (-alpha,x), yx, 100*eps)
+%!assert (besseli (-alpha,x), ix, 100*eps)
+%!assert (besselk (-alpha,x), kx, 100*eps)
+%!assert (besselh (-alpha,1,x), jx + I*yx, 100*eps)
+%!assert (besselh (-alpha,2,x), jx - I*yx, 100*eps)
 %!
-%!assert(besselj(-alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(-alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(-alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(-alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(-alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(-alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
+%!assert (besselj (-alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (-alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (-alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (-alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (-alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (-alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
 %!
 %! x *= -1;
 %! yx = -1.193199310178553861283790424 + 0.3421822624810469647226182835*I;
 %! kx = 0.9410016167388185767085460540 - 0.6974915263814386815610060884*I;
 %!
-%!assert(besselj(alpha,x), jx, 100*eps)
-%!assert(bessely(alpha,x), yx, 100*eps)
-%!assert(besseli(alpha,x), ix, 100*eps)
-%!assert(besselk(alpha,x), kx, 100*eps)
-%!assert(besselh(alpha,1,x), jx + I*yx, 100*eps)
-%!assert(besselh(alpha,2,x), jx - I*yx, 100*eps)
+%!assert (besselj (alpha,x), jx, 100*eps)
+%!assert (bessely (alpha,x), yx, 100*eps)
+%!assert (besseli (alpha,x), ix, 100*eps)
+%!assert (besselk (alpha,x), kx, 100*eps)
+%!assert (besselh (alpha,1,x), jx + I*yx, 100*eps)
+%!assert (besselh (alpha,2,x), jx - I*yx, 100*eps)
 %!
-%!assert(besselj(alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
+%!assert (besselj (alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
 %!
 %! # Bessel functions, odd order, positive and negative x
-%! alpha = 3; x = 2.5;
+%! alpha = 3;  x = 2.5;
 %! jx = 0.2166003910391135247666890035;
 %! yx = -0.7560554967536709968379029772;
 %! ix = 0.4743704087780355895548240179;
 %! kx = 0.2682271463934492027663765197;
 %!
-%!assert(besselj(alpha,x), jx, 100*eps)
-%!assert(bessely(alpha,x), yx, 100*eps)
-%!assert(besseli(alpha,x), ix, 100*eps)
-%!assert(besselk(alpha,x), kx, 100*eps)
-%!assert(besselh(alpha,1,x), jx + I*yx, 100*eps)
-%!assert(besselh(alpha,2,x), jx - I*yx, 100*eps)
+%!assert (besselj (alpha,x), jx, 100*eps)
+%!assert (bessely (alpha,x), yx, 100*eps)
+%!assert (besseli (alpha,x), ix, 100*eps)
+%!assert (besselk (alpha,x), kx, 100*eps)
+%!assert (besselh (alpha,1,x), jx + I*yx, 100*eps)
+%!assert (besselh (alpha,2,x), jx - I*yx, 100*eps)
 %!
-%!assert(besselj(alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
+%!assert (besselj (alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
 %!
-%!assert(besselj(-alpha,x), -jx, 100*eps)
-%!assert(bessely(-alpha,x), -yx, 100*eps)
-%!assert(besseli(-alpha,x), ix, 100*eps)
-%!assert(besselk(-alpha,x), kx, 100*eps)
-%!assert(besselh(-alpha,1,x), -(jx + I*yx), 100*eps)
-%!assert(besselh(-alpha,2,x), -(jx - I*yx), 100*eps)
+%!assert (besselj (-alpha,x), -jx, 100*eps)
+%!assert (bessely (-alpha,x), -yx, 100*eps)
+%!assert (besseli (-alpha,x), ix, 100*eps)
+%!assert (besselk (-alpha,x), kx, 100*eps)
+%!assert (besselh (-alpha,1,x), -(jx + I*yx), 100*eps)
+%!assert (besselh (-alpha,2,x), -(jx - I*yx), 100*eps)
 %!
-%!assert(besselj(-alpha,x,1), -jx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(-alpha,x,1), -yx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(-alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(-alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(-alpha,1,x,1), -(jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(-alpha,2,x,1), -(jx - I*yx)*exp(I*x), 100*eps)
+%!assert (besselj (-alpha,x,1), -jx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (-alpha,x,1), -yx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (-alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (-alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (-alpha,1,x,1), -(jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (-alpha,2,x,1), -(jx - I*yx)*exp(I*x), 100*eps)
 %!
 %! x *= -1;
 %! jx = -jx;
@@ -747,57 +747,57 @@
 %! ix = -ix;
 %! kx = -0.2682271463934492027663765197 - 1.490278591297463775542004240*I;
 %!
-%!assert(besselj(alpha,x), jx, 100*eps)
-%!assert(bessely(alpha,x), yx, 100*eps)
-%!assert(besseli(alpha,x), ix, 100*eps)
-%!assert(besselk(alpha,x), kx, 100*eps)
-%!assert(besselh(alpha,1,x), jx + I*yx, 100*eps)
-%!assert(besselh(alpha,2,x), jx - I*yx, 100*eps)
+%!assert (besselj (alpha,x), jx, 100*eps)
+%!assert (bessely (alpha,x), yx, 100*eps)
+%!assert (besseli (alpha,x), ix, 100*eps)
+%!assert (besselk (alpha,x), kx, 100*eps)
+%!assert (besselh (alpha,1,x), jx + I*yx, 100*eps)
+%!assert (besselh (alpha,2,x), jx - I*yx, 100*eps)
 %!
-%!assert(besselj(alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
+%!assert (besselj (alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
 %!
 %! # Bessel functions, fractional order, positive and negative x
 %!
-%! alpha = 3.5; x = 2.75;
+%! alpha = 3.5;  x = 2.75;
 %! jx = 0.1691636439842384154644784389;
 %! yx = -0.8301381935499356070267953387;
 %! ix = 0.3930540878794826310979363668;
 %! kx = 0.2844099013460621170288192503;
 %!
-%!assert(besselj(alpha,x), jx, 100*eps)
-%!assert(bessely(alpha,x), yx, 100*eps)
-%!assert(besseli(alpha,x), ix, 100*eps)
-%!assert(besselk(alpha,x), kx, 100*eps)
-%!assert(besselh(alpha,1,x), jx + I*yx, 100*eps)
-%!assert(besselh(alpha,2,x), jx - I*yx, 100*eps)
+%!assert (besselj (alpha,x), jx, 100*eps)
+%!assert (bessely (alpha,x), yx, 100*eps)
+%!assert (besseli (alpha,x), ix, 100*eps)
+%!assert (besselk (alpha,x), kx, 100*eps)
+%!assert (besselh (alpha,1,x), jx + I*yx, 100*eps)
+%!assert (besselh (alpha,2,x), jx - I*yx, 100*eps)
 %!
-%!assert(besselj(alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
+%!assert (besselj (alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
 %!
 %! nix = 0.2119931212254662995364461998;
 %!
-%!assert(besselj(-alpha,x), yx, 100*eps)
-%!assert(bessely(-alpha,x), -jx, 100*eps)
-%!assert(besseli(-alpha,x), nix, 100*eps)
-%!assert(besselk(-alpha,x), kx, 100*eps)
-%!assert(besselh(-alpha,1,x), -I*(jx + I*yx), 100*eps)
-%!assert(besselh(-alpha,2,x), I*(jx - I*yx), 100*eps)
+%!assert (besselj (-alpha,x), yx, 100*eps)
+%!assert (bessely (-alpha,x), -jx, 100*eps)
+%!assert (besseli (-alpha,x), nix, 100*eps)
+%!assert (besselk (-alpha,x), kx, 100*eps)
+%!assert (besselh (-alpha,1,x), -I*(jx + I*yx), 100*eps)
+%!assert (besselh (-alpha,2,x), I*(jx - I*yx), 100*eps)
 %!
-%!assert(besselj(-alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(-alpha,x,1), -jx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(-alpha,x,1), nix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(-alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(-alpha,1,x,1), -I*(jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(-alpha,2,x,1), I*(jx - I*yx)*exp(I*x), 100*eps)
+%!assert (besselj (-alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (-alpha,x,1), -jx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (-alpha,x,1), nix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (-alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (-alpha,1,x,1), -I*(jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (-alpha,2,x,1), I*(jx - I*yx)*exp(I*x), 100*eps)
 %!
 %! x *= -1;
 %! jx *= -I;
@@ -805,55 +805,55 @@
 %! ix *= -I;
 %! kx = -0.9504059335995575096509874508*I;
 %!
-%!assert(besselj(alpha,x), jx, 100*eps)
-%!assert(bessely(alpha,x), yx, 100*eps)
-%!assert(besseli(alpha,x), ix, 100*eps)
-%!assert(besselk(alpha,x), kx, 100*eps)
-%!assert(besselh(alpha,1,x), jx + I*yx, 100*eps)
-%!assert(besselh(alpha,2,x), jx - I*yx, 100*eps)
+%!assert (besselj (alpha,x), jx, 100*eps)
+%!assert (bessely (alpha,x), yx, 100*eps)
+%!assert (besseli (alpha,x), ix, 100*eps)
+%!assert (besselk (alpha,x), kx, 100*eps)
+%!assert (besselh (alpha,1,x), jx + I*yx, 100*eps)
+%!assert (besselh (alpha,2,x), jx - I*yx, 100*eps)
 %!
-%!assert(besselj(alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
+%!assert (besselj (alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
 %!
 %! # Bessel functions, even order, complex x
 %!
-%! alpha = 2; x = 1.25 + 3.625 * I;
+%! alpha = 2;  x = 1.25 + 3.625 * I;
 %! jx = -1.299533366810794494030065917 + 4.370833116012278943267479589*I;
 %! yx = -4.370357232383223896393056727 - 1.283083391453582032688834041*I;
 %! ix = -0.6717801680341515541002273932 - 0.2314623443930774099910228553*I;
 %! kx = -0.01108009888623253515463783379 + 0.2245218229358191588208084197*I;
 %!
-%!assert(besselj(alpha,x), jx, 100*eps)
-%!assert(bessely(alpha,x), yx, 100*eps)
-%!assert(besseli(alpha,x), ix, 100*eps)
-%!assert(besselk(alpha,x), kx, 100*eps)
-%!assert(besselh(alpha,1,x), jx + I*yx, 100*eps)
-%!assert(besselh(alpha,2,x), jx - I*yx, 100*eps)
+%!assert (besselj (alpha,x), jx, 100*eps)
+%!assert (bessely (alpha,x), yx, 100*eps)
+%!assert (besseli (alpha,x), ix, 100*eps)
+%!assert (besselk (alpha,x), kx, 100*eps)
+%!assert (besselh (alpha,1,x), jx + I*yx, 100*eps)
+%!assert (besselh (alpha,2,x), jx - I*yx, 100*eps)
 %!
-%!assert(besselj(alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
+%!assert (besselj (alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
 %!
-%!assert(besselj(-alpha,x), jx, 100*eps)
-%!assert(bessely(-alpha,x), yx, 100*eps)
-%!assert(besseli(-alpha,x), ix, 100*eps)
-%!assert(besselk(-alpha,x), kx, 100*eps)
-%!assert(besselh(-alpha,1,x), jx + I*yx, 100*eps)
-%!assert(besselh(-alpha,2,x), jx - I*yx, 100*eps)
+%!assert (besselj (-alpha,x), jx, 100*eps)
+%!assert (bessely (-alpha,x), yx, 100*eps)
+%!assert (besseli (-alpha,x), ix, 100*eps)
+%!assert (besselk (-alpha,x), kx, 100*eps)
+%!assert (besselh (-alpha,1,x), jx + I*yx, 100*eps)
+%!assert (besselh (-alpha,2,x), jx - I*yx, 100*eps)
 %!
-%!assert(besselj(-alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(-alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(-alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(-alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(-alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(-alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
+%!assert (besselj (-alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (-alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (-alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (-alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (-alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (-alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
 %!
 %! # Bessel functions, odd order, complex x
 %!
@@ -863,69 +863,384 @@
 %! ix = -0.6182064685486998097516365709 + 0.4677561094683470065767989920*I;
 %! kx = -0.1568585587733540007867882337 - 0.05185853709490846050505141321*I;
 %!
-%!assert(besselj(alpha,x), jx, 100*eps)
-%!assert(bessely(alpha,x), yx, 100*eps)
-%!assert(besseli(alpha,x), ix, 100*eps)
-%!assert(besselk(alpha,x), kx, 100*eps)
-%!assert(besselh(alpha,1,x), jx + I*yx, 100*eps)
-%!assert(besselh(alpha,2,x), jx - I*yx, 100*eps)
+%!assert (besselj (alpha,x), jx, 100*eps)
+%!assert (bessely (alpha,x), yx, 100*eps)
+%!assert (besseli (alpha,x), ix, 100*eps)
+%!assert (besselk (alpha,x), kx, 100*eps)
+%!assert (besselh (alpha,1,x), jx + I*yx, 100*eps)
+%!assert (besselh (alpha,2,x), jx - I*yx, 100*eps)
 %!
-%!assert(besselj(alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
+%!assert (besselj (alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
 %!
-%!assert(besselj(-alpha,x), -jx, 100*eps)
-%!assert(bessely(-alpha,x), -yx, 100*eps)
-%!assert(besseli(-alpha,x), ix, 100*eps)
-%!assert(besselk(-alpha,x), kx, 100*eps)
-%!assert(besselh(-alpha,1,x), -(jx + I*yx), 100*eps)
-%!assert(besselh(-alpha,2,x), -(jx - I*yx), 100*eps)
+%!assert (besselj (-alpha,x), -jx, 100*eps)
+%!assert (bessely (-alpha,x), -yx, 100*eps)
+%!assert (besseli (-alpha,x), ix, 100*eps)
+%!assert (besselk (-alpha,x), kx, 100*eps)
+%!assert (besselh (-alpha,1,x), -(jx + I*yx), 100*eps)
+%!assert (besselh (-alpha,2,x), -(jx - I*yx), 100*eps)
 %!
-%!assert(besselj(-alpha,x,1), -jx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(-alpha,x,1), -yx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(-alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(-alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(-alpha,1,x,1), -(jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(-alpha,2,x,1), -(jx - I*yx)*exp(I*x), 100*eps)
+%!assert (besselj (-alpha,x,1), -jx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (-alpha,x,1), -yx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (-alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (-alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (-alpha,1,x,1), -(jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (-alpha,2,x,1), -(jx - I*yx)*exp(I*x), 100*eps)
 %!
 %! # Bessel functions, fractional order, complex x
 %!
-%! alpha = 3.5; x = 1.75 + 4.125 * I;
+%! alpha = 3.5;  x = 1.75 + 4.125 * I;
 %! jx = -3.018566131370455929707009100 - 0.7585648436793900607704057611*I;
 %! yx = 0.7772278839106298215614791107 - 3.018518722313849782683792010*I;
 %! ix = 0.2100873577220057189038160913 - 0.6551765604618246531254970926*I;
 %! kx = 0.1757147290513239935341488069 + 0.08772348296883849205562558311*I;
 %!
-%!assert(besselj(alpha,x), jx, 100*eps)
-%!assert(bessely(alpha,x), yx, 100*eps)
-%!assert(besseli(alpha,x), ix, 100*eps)
-%!assert(besselk(alpha,x), kx, 100*eps)
-%!assert(besselh(alpha,1,x), jx + I*yx, 100*eps)
-%!assert(besselh(alpha,2,x), jx - I*yx, 100*eps)
+%!assert (besselj (alpha,x), jx, 100*eps)
+%!assert (bessely (alpha,x), yx, 100*eps)
+%!assert (besseli (alpha,x), ix, 100*eps)
+%!assert (besselk (alpha,x), kx, 100*eps)
+%!assert (besselh (alpha,1,x), jx + I*yx, 100*eps)
+%!assert (besselh (alpha,2,x), jx - I*yx, 100*eps)
 %!
-%!assert(besselj(alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
+%!assert (besselj (alpha,x,1), jx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (alpha,x,1), ix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (alpha,1,x,1), (jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (alpha,2,x,1), (jx - I*yx)*exp(I*x), 100*eps)
 %!
 %!  nix = 0.09822388691172060573913739253 - 0.7110230642207380127317227407*I;
 %!
-%!assert(besselj(-alpha,x), yx, 100*eps)
-%!assert(bessely(-alpha,x), -jx, 100*eps)
-%!assert(besseli(-alpha,x), nix, 100*eps)
-%!assert(besselk(-alpha,x), kx, 100*eps)
-%!assert(besselh(-alpha,1,x), -I*(jx + I*yx), 100*eps)
-%!assert(besselh(-alpha,2,x), I*(jx - I*yx), 100*eps)
+%!assert (besselj (-alpha,x), yx, 100*eps)
+%!assert (bessely (-alpha,x), -jx, 100*eps)
+%!assert (besseli (-alpha,x), nix, 100*eps)
+%!assert (besselk (-alpha,x), kx, 100*eps)
+%!assert (besselh (-alpha,1,x), -I*(jx + I*yx), 100*eps)
+%!assert (besselh (-alpha,2,x), I*(jx - I*yx), 100*eps)
+%!
+%!assert (besselj (-alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
+%!assert (bessely (-alpha,x,1), -jx*exp(-abs(imag(x))), 100*eps)
+%!assert (besseli (-alpha,x,1), nix*exp(-abs(real(x))), 100*eps)
+%!assert (besselk (-alpha,x,1), kx*exp(x), 100*eps)
+%!assert (besselh (-alpha,1,x,1), -I*(jx + I*yx)*exp(-I*x), 100*eps)
+%!assert (besselh (-alpha,2,x,1), I*(jx - I*yx)*exp(I*x), 100*eps)
+
+
+Tests contributed by Robert T. Short.
+Tests are based on the properties and tables in A&S:
+ Abramowitz and Stegun, "Handbook of Mathematical Functions",
+ 1972.
+
+For regular Bessel functions, there are 3 tests. These compare octave
+results against Tables 9.1, 9.2, and 9.4 in A&S. Tables 9.1 and 9.2
+are good to only a few decimal places, so any failures should be
+considered a broken implementation. Table 9.4 is an extended table
+for larger orders and arguments. There are some differences between
+Octave and Table 9.4, mostly in the last decimal place but in a very
+few instances the errors are in the last two places. The comparison
+tolerance has been changed to reflect this.
+
+Similarly for modifed Bessel functions, there are 3 tests. These
+compare octave results against Tables 9.8, 9.9, and 9.11 in A&S.
+Tables 9.8 and 9.9 are good to only a few decimal places, so any
+failures should be considered a broken implementation. Table 9.11 is
+an extended table for larger orders and arguments. There are some
+differences between octave and Table 9.11, mostly in the last decimal
+place but in a very few instances the errors are in the last two
+places. The comparison tolerance has been changed to reflect this.
+
+For spherical Bessel functions, there are also three tests, comparing
+octave results to Tables 10.1, 10.2, and 10.4 in A&S. Very similar
+comments may be made here as in the previous lines. At this time,
+modified spherical Bessel function tests are not included.
+
+% Table 9.1 - J and Y for integer orders 0, 1, 2.
+% Compare against excerpts of Table 9.1, Abramowitz and Stegun.
+%!test
+%! n = 0:2;
+%! z = (0:2.5:17.5)';
+%!
+%! Jt = [[ 1.000000000000000,  0.0000000000,  0.0000000000];
+%!       [-0.048383776468198,  0.4970941025,  0.4460590584];
+%!       [-0.177596771314338, -0.3275791376,  0.0465651163];
+%!       [ 0.266339657880378,  0.1352484276, -0.2302734105];
+%!       [-0.245935764451348,  0.0434727462,  0.2546303137];
+%!       [ 0.146884054700421, -0.1654838046, -0.1733614634];
+%!       [-0.014224472826781,  0.2051040386,  0.0415716780];
+%!       [-0.103110398228686, -0.1634199694,  0.0844338303]];
+%!
+%! Yt = [[-Inf,          -Inf,          -Inf        ];
+%!       [ 0.4980703596,  0.1459181380, -0.38133585 ];
+%!       [-0.3085176252,  0.1478631434,  0.36766288 ];
+%!       [ 0.1173132861, -0.2591285105, -0.18641422 ];
+%!       [ 0.0556711673,  0.2490154242, -0.00586808 ];
+%!       [-0.1712143068, -0.1538382565,  0.14660019 ];
+%!       [ 0.2054642960,  0.0210736280, -0.20265448 ];
+%!       [-0.1604111925,  0.0985727987,  0.17167666 ]];
+%!
+%! J = besselj (n,z);
+%! Y = bessely (n,z);
+%! assert (Jt(:,1), J(:,1), 0.5e-10);
+%! assert (Yt(:,1), Y(:,1), 0.5e-10);
+%! assert (Jt(:,2:3), J(:,2:3), 0.5e-10);
+
+Table 9.2 - J and Y for integer orders 3-9.
+
+%!test
+%! n = (3:9);
+%! z = (0:2:20).';
+%!
+%! Jt = [[ 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00];
+%!       [ 1.2894e-01, 3.3996e-02, 7.0396e-03, 1.2024e-03, 1.7494e-04, 2.2180e-05, 2.4923e-06];
+%!       [ 4.3017e-01, 2.8113e-01, 1.3209e-01, 4.9088e-02, 1.5176e-02, 4.0287e-03, 9.3860e-04];
+%!       [ 1.1477e-01, 3.5764e-01, 3.6209e-01, 2.4584e-01, 1.2959e-01, 5.6532e-02, 2.1165e-02];
+%!       [-2.9113e-01,-1.0536e-01, 1.8577e-01, 3.3758e-01, 3.2059e-01, 2.2345e-01, 1.2632e-01];
+%!       [ 5.8379e-02,-2.1960e-01,-2.3406e-01,-1.4459e-02, 2.1671e-01, 3.1785e-01, 2.9186e-01];
+%!       [ 1.9514e-01, 1.8250e-01,-7.3471e-02,-2.4372e-01,-1.7025e-01, 4.5095e-02, 2.3038e-01];
+%!       [-1.7681e-01, 7.6244e-02, 2.2038e-01, 8.1168e-02,-1.5080e-01,-2.3197e-01,-1.1431e-01];
+%!       [-4.3847e-02,-2.0264e-01,-5.7473e-02, 1.6672e-01, 1.8251e-01,-7.0211e-03,-1.8953e-01];
+%!       [ 1.8632e-01, 6.9640e-02,-1.5537e-01,-1.5596e-01, 5.1399e-02, 1.9593e-01, 1.2276e-01];
+%!       [-9.8901e-02, 1.3067e-01, 1.5117e-01,-5.5086e-02,-1.8422e-01,-7.3869e-02, 1.2513e-01]];
+%!
+%! Yt = [[       -Inf,       -Inf,       -Inf,       -Inf,       -Inf,       -Inf,       -Inf];
+%!       [-1.1278e+00,-2.7659e+00,-9.9360e+00,-4.6914e+01,-2.7155e+02,-1.8539e+03,-1.4560e+04];
+%!       [-1.8202e-01,-4.8894e-01,-7.9585e-01,-1.5007e+00,-3.7062e+00,-1.1471e+01,-4.2178e+01];
+%!       [ 3.2825e-01, 9.8391e-02,-1.9706e-01,-4.2683e-01,-6.5659e-01,-1.1052e+00,-2.2907e+00];
+%!       [ 2.6542e-02, 2.8294e-01, 2.5640e-01, 3.7558e-02,-2.0006e-01,-3.8767e-01,-5.7528e-01];
+%!       [-2.5136e-01,-1.4495e-01, 1.3540e-01, 2.8035e-01, 2.0102e-01, 1.0755e-03,-1.9930e-01];
+%!       [ 1.2901e-01,-1.5122e-01,-2.2982e-01,-4.0297e-02, 1.8952e-01, 2.6140e-01, 1.5902e-01];
+%!       [ 1.2350e-01, 2.0393e-01,-6.9717e-03,-2.0891e-01,-1.7209e-01, 3.6816e-02, 2.1417e-01];
+%!       [-1.9637e-01,-7.3222e-05, 1.9633e-01, 1.2278e-01,-1.0425e-01,-2.1399e-01,-1.0975e-01];
+%!       [ 3.3724e-02,-1.7722e-01,-1.1249e-01, 1.1472e-01, 1.8897e-01, 3.2253e-02,-1.6030e-01];
+%!       [ 1.4967e-01, 1.2409e-01,-1.0004e-01,-1.7411e-01,-4.4312e-03, 1.7101e-01, 1.4124e-01]];
+%!
+%! n = (3:9);
+%! z = (0:2:20).';
+%! J = besselj (n,z);
+%! Y = bessely (n,z);
+%!
+%! assert (J(1,:), zeros (1, columns (J)));
+%! assert (J(2:end,:), Jt(2:end,:), -5e-5);
+%! assert (Yt(1,:), Y(1,:));
+%! assert (Y(2:end,:), Yt(2:end,:), -5e-5);
+
+Table 9.4 - J and Y for various integer orders and arguments.
+
+%!test
+%! Jt = [[ 7.651976866e-01,   2.238907791e-01,  -1.775967713e-01,  -2.459357645e-01,  5.581232767e-02,  1.998585030e-02];
+%!       [ 2.497577302e-04,   7.039629756e-03,   2.611405461e-01,  -2.340615282e-01, -8.140024770e-02, -7.419573696e-02];
+%!       [ 2.630615124e-10,   2.515386283e-07,   1.467802647e-03,   2.074861066e-01, -1.138478491e-01, -5.473217694e-02];
+%!       [ 2.297531532e-17,   7.183016356e-13,   4.796743278e-07,   4.507973144e-03, -1.082255990e-01,  1.519812122e-02];
+%!       [ 3.873503009e-25,   3.918972805e-19,   2.770330052e-11,   1.151336925e-05, -1.167043528e-01,  6.221745850e-02];
+%!       [ 3.482869794e-42,   3.650256266e-33,   2.671177278e-21,   1.551096078e-12,  4.843425725e-02,  8.146012958e-02];
+%!       [ 1.107915851e-60,   1.196077458e-48,   8.702241617e-33,   6.030895312e-21, -1.381762812e-01,  7.270175482e-02];
+%!       [ 2.906004948e-80,   3.224095839e-65,   2.294247616e-45,   1.784513608e-30,  1.214090219e-01, -3.869833973e-02];
+%!       [ 8.431828790e-189,  1.060953112e-158,  6.267789396e-119,  6.597316064e-89,  1.115927368e-21,  9.636667330e-02]];
+%!
+%! Yt = [[ 8.825696420e-02,   5.103756726e-01,  -3.085176252e-01,   5.567116730e-02, -9.806499547e-02, -7.724431337e-02]
+%!       [-2.604058666e+02,  -9.935989128e+00,  -4.536948225e-01,   1.354030477e-01, -7.854841391e-02, -2.948019628e-02]
+%!       [-1.216180143e+08,  -1.291845422e+05,  -2.512911010e+01,  -3.598141522e-01,  5.723897182e-03,  5.833157424e-02]
+%!       [-9.256973276e+14,  -2.981023646e+10,  -4.694049564e+04,  -6.364745877e+00,  4.041280205e-02,  7.879068695e-02]
+%!       [-4.113970315e+22,  -4.081651389e+16,  -5.933965297e+08,  -1.597483848e+03,  1.644263395e-02,  5.124797308e-02]
+%!       [-3.048128783e+39,  -2.913223848e+30,  -4.028568418e+18,  -7.256142316e+09, -1.164572349e-01,  6.138839212e-03]
+%!       [-7.184874797e+57,  -6.661541235e+45,  -9.216816571e+29,  -1.362803297e+18, -4.530801120e-02,  4.074685217e-02]
+%!       [-2.191142813e+77,  -1.976150576e+62,  -2.788837017e+42,  -3.641066502e+27, -2.103165546e-01,  7.650526394e-02]
+%!       [-3.775287810e+185, -3.000826049e+155, -5.084863915e+115, -4.849148271e+85, -3.293800188e+18, -1.669214114e-01]];
+%!
+%! n = [(0:5:20).';30;40;50;100];
+%! z = [1,2,5,10,50,100];
+%! J = besselj (n.', z.').';
+%! Y = bessely (n.', z.').';
+%! assert (J, Jt, -1e-9);
+%! assert (Y, Yt, -1e-9);
+
+Table 9.8 - I and K for integer orders 0, 1, 2.
+
+%!test
+%! n  = 0:2;
+%! z1 = [0.1;2.5;5.0];
+%! z2 = [7.5;10.0;15.0;20.0];
+%! rtbl = [[ 0.9071009258   0.0452984468   0.1251041992   2.6823261023  10.890182683    1.995039646  ];
+%!         [ 0.2700464416   0.2065846495   0.2042345837   0.7595486903   0.9001744239   0.759126289  ];
+%!         [ 0.1835408126   0.1639722669   0.7002245988   0.5478075643   0.6002738588   0.132723593  ];
+%!         [ 0.1483158301   0.1380412115   0.111504840    0.4505236991   0.4796689336   0.57843541   ];
+%!         [ 0.1278333372   0.1212626814   0.103580801    0.3916319344   0.4107665704   0.47378525   ];
+%!         [ 0.1038995314   0.1003741751   0.090516308    0.3210023535   0.3315348950   0.36520701   ];
+%!         [ 0.0897803119   0.0875062222   0.081029690    0.2785448768   0.2854254970   0.30708743   ]];
+%!
+%! tbl = [besseli(n,z1,1), besselk(n,z1,1)];
+%! tbl(:,3) = tbl(:,3) .* (exp (z1) .* z1.^(-2));
+%! tbl(:,6) = tbl(:,6) .* (exp (-z1) .* z1.^(2));
+%! tbl = [tbl;[besseli(n,z2,1),besselk(n,z2,1)]];
 %!
-%!assert(besselj(-alpha,x,1), yx*exp(-abs(imag(x))), 100*eps)
-%!assert(bessely(-alpha,x,1), -jx*exp(-abs(imag(x))), 100*eps)
-%!assert(besseli(-alpha,x,1), nix*exp(-abs(real(x))), 100*eps)
-%!assert(besselk(-alpha,x,1), kx*exp(x), 100*eps)
-%!assert(besselh(-alpha,1,x,1), -I*(jx + I*yx)*exp(-I*x), 100*eps)
-%!assert(besselh(-alpha,2,x,1), I*(jx - I*yx)*exp(I*x), 100*eps)
+%! assert (tbl, rtbl, -2e-8);
+
+Table 9.9 - I and K for orders 3-9.
+
+%!test
+%! It = [[  0.0000e+00  0.0000e+00  0.0000e+00  0.0000e+00  0.0000e+00  0.0000e+00  0.0000e+00];
+%!       [  2.8791e-02  6.8654e-03  1.3298e-03  2.1656e-04  3.0402e-05  3.7487e-06  4.1199e-07];
+%!       [  6.1124e-02  2.5940e-02  9.2443e-03  2.8291e-03  7.5698e-04  1.7968e-04  3.8284e-05];
+%!       [  7.4736e-02  4.1238e-02  1.9752e-02  8.3181e-03  3.1156e-03  1.0484e-03  3.1978e-04];
+%!       [  7.9194e-02  5.0500e-02  2.8694e-02  1.4633e-02  6.7449e-03  2.8292e-03  1.0866e-03];
+%!       [  7.9830e-02  5.5683e-02  3.5284e-02  2.0398e-02  1.0806e-02  5.2694e-03  2.3753e-03];
+%!       [  7.8848e-02  5.8425e-02  3.9898e-02  2.5176e-02  1.4722e-02  8.0010e-03  4.0537e-03];
+%!       [  7.7183e-02  5.9723e-02  4.3056e-02  2.8969e-02  1.8225e-02  1.0744e-02  5.9469e-03];
+%!       [  7.5256e-02  6.0155e-02  4.5179e-02  3.1918e-02  2.1240e-02  1.3333e-02  7.9071e-03];
+%!       [  7.3263e-02  6.0059e-02  4.6571e-02  3.4186e-02  2.3780e-02  1.5691e-02  9.8324e-03];
+%!       [  7.1300e-02  5.9640e-02  4.7444e-02  3.5917e-02  2.5894e-02  1.7792e-02  1.1661e-02]];
+%!
+%! Kt = [[ Inf         Inf         Inf         Inf         Inf         Inf         Inf];
+%!      [  4.7836e+00  1.6226e+01  6.9687e+01  3.6466e+02  2.2576e+03  1.6168e+04  1.3160e+05];
+%!      [  1.6317e+00  3.3976e+00  8.4268e+00  2.4465e+01  8.1821e+01  3.1084e+02  1.3252e+03];
+%!      [  9.9723e-01  1.6798e+00  3.2370e+00  7.0748e+00  1.7387e+01  4.7644e+01  1.4444e+02];
+%!      [  7.3935e-01  1.1069e+00  1.8463e+00  3.4148e+00  6.9684e+00  1.5610e+01  3.8188e+01];
+%!      [  6.0028e-01  8.3395e-01  1.2674e+00  2.1014e+00  3.7891e+00  7.4062e+00  1.5639e+01];
+%!      [  5.1294e-01  6.7680e-01  9.6415e-01  1.4803e+00  2.4444e+00  4.3321e+00  8.2205e+00];
+%!      [  4.5266e-01  5.7519e-01  7.8133e-01  1.1333e+00  1.7527e+00  2.8860e+00  5.0510e+00];
+%!      [  4.0829e-01  5.0414e-01  6.6036e-01  9.1686e-01  1.3480e+00  2.0964e+00  3.4444e+00];
+%!      [  3.7411e-01  4.5162e-01  5.7483e-01  7.7097e-01  1.0888e+00  1.6178e+00  2.5269e+00];
+%!      [  3.4684e-01  4.1114e-01  5.1130e-01  6.6679e-01  9.1137e-01  1.3048e+00  1.9552e+00]];
+%!
+%! n = (3:9);
+%! z = (0:2:20).';
+%! I = besseli (n,z,1);
+%! K = besselk (n,z,1);
+%!
+%! assert (abs (I(1,:)), zeros (1, columns (I)));
+%! assert (I(2:end,:), It(2:end,:), -5e-5);
+%! assert (Kt(1,:), K(1,:));
+%! assert (K(2:end,:), Kt(2:end,:), -5e-5);
+
+Table 9.11 - I and K for various integer orders and arguments.
+
+%!test
+%! It = [[   1.266065878e+00    2.279585302e+00    2.723987182e+01    2.815716628e+03     2.93255378e+20     1.07375171e+42 ];
+%!       [   2.714631560e-04    9.825679323e-03    2.157974547e+00    7.771882864e+02     2.27854831e+20     9.47009387e+41 ];
+%!       [   2.752948040e-10    3.016963879e-07    4.580044419e-03    2.189170616e+01     1.07159716e+20     6.49897552e+41 ];
+%!       [   2.370463051e-17    8.139432531e-13    1.047977675e-06    1.043714907e-01     3.07376455e+19     3.47368638e+41 ];
+%!       [   3.966835986e-25    4.310560576e-19    5.024239358e-11    1.250799736e-04     5.44200840e+18     1.44834613e+41 ];
+%!       [   3.539500588e-42    3.893519664e-33    3.997844971e-21    7.787569783e-12     4.27499365e+16     1.20615487e+40 ];
+%!       [   1.121509741e-60    1.255869192e-48    1.180426980e-32    2.042123274e-20     6.00717897e+13     3.84170550e+38 ];
+%!       [   2.934635309e-80    3.353042830e-65    2.931469647e-45    4.756894561e-30     1.76508024e+10     4.82195809e+36 ];
+%!       [   8.473674008e-189   1.082171475e-158   7.093551489e-119   1.082344202e-88     2.72788795e-16     4.64153494e+21 ]];
+%!
+%! Kt = [[   4.210244382e-01    1.138938727e-01    3.691098334e-03    1.778006232e-05     3.41016774e-23     4.65662823e-45 ];
+%!       [   3.609605896e+02    9.431049101e+00    3.270627371e-02    5.754184999e-05     4.36718224e-23     5.27325611e-45 ];
+%!       [   1.807132899e+08    1.624824040e+05    9.758562829e+00    1.614255300e-03     9.15098819e-23     7.65542797e-45 ];
+%!       [   1.403066801e+15    4.059213332e+10    3.016976630e+04    2.656563849e-01     3.11621117e-22     1.42348325e-44 ];
+%!       [   6.294369360e+22    5.770856853e+16    4.827000521e+08    1.787442782e+02     1.70614838e-21     3.38520541e-44 ];
+%!       [   4.706145527e+39    4.271125755e+30    4.112132063e+18    2.030247813e+09     2.00581681e-19     3.97060205e-43 ];
+%!       [   1.114220651e+58    9.940839886e+45    1.050756722e+30    5.938224681e+17     1.29986971e-16     1.20842080e-41 ];
+%!       [   3.406896854e+77    2.979981740e+62    3.394322243e+42    2.061373775e+27     4.00601349e-13     9.27452265e-40 ];
+%!       [   5.900333184e+185   4.619415978e+155   7.039860193e+115   4.596674084e+85     1.63940352e+13     7.61712963e-25 ]];
+%!
+%! n = [(0:5:20).';30;40;50;100];
+%! z = [1,2,5,10,50,100];
+%! I = besseli (n.', z.').';
+%! K = besselk (n.', z.').';
+%! assert (I, It, -5e-9);
+%! assert (K, Kt, -5e-9);
+
+The next section checks that negative integer orders and positive
+integer orders are appropriately related.
+
+%!test
+%! n = (0:2:20);
+%! assert (besselj (n,1), besselj (-n,1), 1e-8);
+%! assert (-besselj (n+1,1), besselj (-n-1,1), 1e-8);
+
+besseli (n,z) = besseli (-n,z);
+
+%!test
+%! n = (0:2:20);
+%! assert (besseli (n,1), besseli (-n,1), 1e-8);
+
+Table 10.1 - j and y for integer orders 0, 1, 2.
+Compare against excerpts of Table 10.1, Abramowitz and Stegun.
+
+%!test
+%! n = (0:2);
+%! z = [0.1;(2.5:2.5:10.0).'];
+%!
+%! jt = [[ 9.9833417e-01  3.33000119e-02  6.6619061e-04 ];
+%!       [ 2.3938886e-01  4.16212989e-01  2.6006673e-01 ];
+%!       [-1.9178485e-01 -9.50894081e-02  1.3473121e-01 ];
+%!       [    1.2507e-01     -2.9542e-02    -1.3688e-01 ];
+%!       [   -5.4402e-02      7.8467e-02     7.7942e-02 ]];
+%!
+%! yt = [[-9.9500417e+00  -1.0049875e+02 -3.0050125e+03 ];
+%!       [ 3.2045745e-01  -1.1120588e-01 -4.5390450e-01 ];
+%!       [-5.6732437e-02   1.8043837e-01  1.6499546e-01 ];
+%!       [   -4.6218e-02     -1.3123e-01    -6.2736e-03 ];
+%!       [    8.3907e-02      6.2793e-02    -6.5069e-02 ]];
+%!
+%! j = sqrt ((pi/2)./z) .* besselj (n+1/2,z);
+%! y = sqrt ((pi/2)./z) .* bessely (n+1/2,z);
+%! assert (jt, j, -5e-5);
+%! assert (yt, y, -5e-5);
+
+Table 10.2 - j and y for orders 3-8.
+Compare against excerpts of Table 10.2, Abramowitzh and Stegun.
+
+ Important note: In A&S, y_4(0.1) = -1.0507e+7, but Octave returns
+ y_4(0.1) = -1.0508e+07 (-10507503.75).  If I compute the same term using
+ a series, the difference is in the eighth significant digit so I left
+ the Octave results in place.
+
+%!test
+%! n = (3:8);
+%! z = (0:2.5:10).';  z(1) = 0.1;
+%!
+%! jt = [[ 9.5185e-06  1.0577e-07  9.6163e-10  7.3975e-12  4.9319e-14  2.9012e-16];
+%!       [ 1.0392e-01  3.0911e-02  7.3576e-03  1.4630e-03  2.5009e-04  3.7516e-05];
+%!       [ 2.2982e-01  1.8702e-01  1.0681e-01  4.7967e-02  1.7903e-02  5.7414e-03];
+%!       [-6.1713e-02  7.9285e-02  1.5685e-01  1.5077e-01  1.0448e-01  5.8188e-02];
+%!       [-3.9496e-02 -1.0559e-01 -5.5535e-02  4.4501e-02  1.1339e-01  1.2558e-01]];
+%!
+%! yt = [[-1.5015e+05 -1.0508e+07 -9.4553e+08 -1.0400e+11 -1.3519e+13 -2.0277e+15];
+%!       [-7.9660e-01 -1.7766e+00 -5.5991e+00 -2.2859e+01 -1.1327e+02 -6.5676e+02];
+%!       [-1.5443e-02 -1.8662e-01 -3.2047e-01 -5.1841e-01 -1.0274e+00 -2.5638e+00];
+%!       [ 1.2705e-01  1.2485e-01  2.2774e-02 -9.1449e-02 -1.8129e-01 -2.7112e-01];
+%!       [-9.5327e-02 -1.6599e-03  9.3834e-02  1.0488e-01  4.2506e-02 -4.1117e-02]];
+%!
+%! j = sqrt ((pi/2)./z) .* besselj (n+1/2,z);
+%! y = sqrt ((pi/2)./z) .* bessely (n+1/2,z);
+%!
+%! assert (jt, j, -5e-5);
+%! assert (yt, y, -5e-5);
+
+Table 10.4 - j and y for various integer orders and arguments.
+
+%!test
+%! jt = [[ 8.414709848e-01    4.546487134e-01   -1.917848549e-01   -5.440211109e-02   -5.247497074e-03   -5.063656411e-03];
+%!       [ 9.256115861e-05    2.635169770e-03    1.068111615e-01   -5.553451162e-02   -2.004830056e-02   -9.290148935e-03];
+%!       [ 7.116552640e-11    6.825300865e-08    4.073442442e-04    6.460515449e-02   -1.503922146e-02   -1.956578597e-04];
+%!       [ 5.132686115e-18    1.606982166e-13    1.084280182e-07    1.063542715e-03   -1.129084539e-02    7.877261748e-03];
+%!       [ 7.537795722e-26    7.632641101e-20    5.427726761e-12    2.308371961e-06   -1.578502990e-02    1.010767128e-02];
+%!       [ 5.566831267e-43    5.836617888e-34    4.282730217e-22    2.512057385e-13   -1.494673454e-03    8.700628514e-03];
+%!       [ 1.538210374e-61    1.660978779e-49    1.210347583e-33    8.435671634e-22   -2.606336952e-02    1.043410851e-02];
+%!       [ 3.615274717e-81    4.011575290e-66    2.857479350e-46    2.230696023e-31    1.882910737e-02    5.797140882e-04];
+%!       [7.444727742e-190   9.367832591e-160   5.535650303e-120    5.832040182e-90    1.019012263e-22    1.088047701e-02]];
+%!
+%! yt = [[ -5.403023059e-01    2.080734183e-01   -5.673243709e-02    8.390715291e-02   -1.929932057e-02   -8.623188723e-03]
+%!       [ -9.994403434e+02   -1.859144531e+01   -3.204650467e-01    9.383354168e-02   -6.971131965e-04    3.720678486e-03]
+%!       [ -6.722150083e+08   -3.554147201e+05   -2.665611441e+01   -1.724536721e-01    1.352468751e-02    1.002577737e-02]
+%!       [ -6.298007233e+15   -1.012182944e+11   -6.288146513e+04   -3.992071745e+00    1.712319725e-02    6.258641510e-03]
+%!       [ -3.239592219e+23   -1.605436493e+17   -9.267951403e+08   -1.211210605e+03    1.375953130e-02    5.631729379e-05]
+%!       [ -2.946428547e+40   -1.407393871e+31   -7.760717570e+18   -6.908318646e+09   -2.241226812e-02   -5.412929349e-03]
+%!       [ -8.028450851e+58   -3.720929322e+46   -2.055758716e+30   -1.510304919e+18    4.978797221e-05   -7.048420407e-04]
+%!       [ -2.739192285e+78   -1.235021944e+63   -6.964109188e+42   -4.528227272e+27   -4.190000150e-02    1.074782297e-02]
+%!       [-6.683079463e+186  -2.655955830e+156  -1.799713983e+116   -8.573226309e+85   -1.125692891e+18   -2.298385049e-02]];
+%!
+%! n = [(0:5:20).';30;40;50;100];
+%! z = [1,2,5,10,50,100];
+%! j = sqrt ((pi/2)./z) .* besselj ((n+1/2).', z.').';
+%! y = sqrt ((pi/2)./z) .* bessely ((n+1/2).', z.').';
+%! assert (j, jt, -1e-9);
+%! assert (y, yt, -1e-9);
 */
rename from src/DLD-FUNCTIONS/betainc.cc
rename to libinterp/corefcn/betainc.cc
--- a/src/DLD-FUNCTIONS/betainc.cc
+++ b/libinterp/corefcn/betainc.cc
@@ -26,13 +26,16 @@
 
 #include "lo-specfun.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
 #include "utils.h"
 
-DEFUN_DLD (betainc, args, ,
+// FIXME: These functions do not need to be dynamically loaded.  They should
+//        be placed elsewhere in the Octave code hierarchy.
+
+DEFUN (betainc, args, ,
   "-*- texinfo -*-\n\
 @deftypefn {Mapping Function} {} betainc (@var{x}, @var{a}, @var{b})\n\
 Return the regularized incomplete Beta function,\n\
@@ -46,12 +49,11 @@
 \n\
 @smallexample\n\
 @group\n\
-@c spacing appears odd here, but is correct after Makeinfo\n\
-                                     x\n\
-                          1         /\n\
-betainc (x, a, b) = -----------    | t^(a-1) (1-t)^(b-1) dt.\n\
-                     beta (a, b)    /\n\
-                                 t=0\n\
+                                   x\n\
+                          1       /\n\
+betainc (x, a, b) = -----------   | t^(a-1) (1-t)^(b-1) dt.\n\
+                    beta (a, b)   /\n\
+                               t=0\n\
 @end group\n\
 @end smallexample\n\
 \n\
@@ -60,6 +62,7 @@
 If @var{x} has more than one component, both @var{a} and @var{b} must be\n\
 scalars.  If @var{x} is a scalar, @var{a} and @var{b} must be of\n\
 compatible dimensions.\n\
+@seealso{betaincinv, beta, betaln}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -95,7 +98,7 @@
                         }
                       else
                         {
-                          FloatNDArray b = b_arg.float_array_value ();
+                          Array<float> b = b_arg.float_array_value ();
 
                           if (! error_state)
                             retval = betainc (x, a, b);
@@ -104,7 +107,7 @@
                 }
               else
                 {
-                  FloatNDArray a = a_arg.float_array_value ();
+                  Array<float> a = a_arg.float_array_value ();
 
                   if (! error_state)
                     {
@@ -117,7 +120,7 @@
                         }
                       else
                         {
-                          FloatNDArray b = b_arg.float_array_value ();
+                          Array<float> b = b_arg.float_array_value ();
 
                           if (! error_state)
                             retval = betainc (x, a, b);
@@ -127,7 +130,7 @@
             }
           else
             {
-              FloatNDArray x = x_arg.float_array_value ();
+              Array<float> x = x_arg.float_array_value ();
 
               if (a_arg.is_scalar_type ())
                 {
@@ -144,7 +147,7 @@
                         }
                       else
                         {
-                          FloatNDArray b = b_arg.float_array_value ();
+                          Array<float> b = b_arg.float_array_value ();
 
                           if (! error_state)
                             retval = betainc (x, a, b);
@@ -153,7 +156,7 @@
                 }
               else
                 {
-                  FloatNDArray a = a_arg.float_array_value ();
+                  Array<float> a = a_arg.float_array_value ();
 
                   if (! error_state)
                     {
@@ -166,7 +169,7 @@
                         }
                       else
                         {
-                          FloatNDArray b = b_arg.float_array_value ();
+                          Array<float> b = b_arg.float_array_value ();
 
                           if (! error_state)
                             retval = betainc (x, a, b);
@@ -196,7 +199,7 @@
                         }
                       else
                         {
-                          NDArray b = b_arg.array_value ();
+                          Array<double> b = b_arg.array_value ();
 
                           if (! error_state)
                             retval = betainc (x, a, b);
@@ -205,7 +208,7 @@
                 }
               else
                 {
-                  NDArray a = a_arg.array_value ();
+                  Array<double> a = a_arg.array_value ();
 
                   if (! error_state)
                     {
@@ -218,7 +221,7 @@
                         }
                       else
                         {
-                          NDArray b = b_arg.array_value ();
+                          Array<double> b = b_arg.array_value ();
 
                           if (! error_state)
                             retval = betainc (x, a, b);
@@ -228,7 +231,7 @@
             }
           else
             {
-              NDArray x = x_arg.array_value ();
+              Array<double> x = x_arg.array_value ();
 
               if (a_arg.is_scalar_type ())
                 {
@@ -245,7 +248,7 @@
                         }
                       else
                         {
-                          NDArray b = b_arg.array_value ();
+                          Array<double> b = b_arg.array_value ();
 
                           if (! error_state)
                             retval = betainc (x, a, b);
@@ -254,7 +257,7 @@
                 }
               else
                 {
-                  NDArray a = a_arg.array_value ();
+                  Array<double> a = a_arg.array_value ();
 
                   if (! error_state)
                     {
@@ -267,7 +270,7 @@
                         }
                       else
                         {
-                          NDArray b = b_arg.array_value ();
+                          Array<double> b = b_arg.array_value ();
 
                           if (! error_state)
                             retval = betainc (x, a, b);
@@ -284,50 +287,205 @@
 }
 
 /*
-
-%% test/octave.test/arith/betainc-1.m
+## Double precision
 %!test
-%! a=[1, 1.5, 2, 3];
-%! b=[4, 3, 2, 1];
-%! v1=betainc(1,a,b);
-%! v2=[1,1,1,1];
+%! a = [1, 1.5, 2, 3];
+%! b = [4, 3, 2, 1];
+%! v1 = betainc (1,a,b);
+%! v2 = [1,1,1,1];
 %! x = [.2, .4, .6, .8];
-%! v3=betainc(x, a, b);
-%! v4 = 1-betainc(1.-x, b, a);
-%! assert(v1, v2, sqrt(eps));
-%! assert(v3, v4, sqrt(eps));
+%! v3 = betainc (x, a, b);
+%! v4 = 1 - betainc (1.-x, b, a);
+%! assert (v1, v2, sqrt (eps));
+%! assert (v3, v4, sqrt (eps));
 
-%% Single precision
+## Single precision
 %!test
-%! a=single ([1, 1.5, 2, 3]);
-%! b=single ([4, 3, 2, 1]);
-%! v1=betainc(1,a,b);
-%! v2=single ([1,1,1,1]);
+%! a = single ([1, 1.5, 2, 3]);
+%! b = single ([4, 3, 2, 1]);
+%! v1 = betainc (1,a,b);
+%! v2 = single ([1,1,1,1]);
 %! x = single ([.2, .4, .6, .8]);
-%! v3=betainc(x, a, b);
-%! v4 = 1-betainc(1.-x, b, a);
-%! assert(v1, v2, sqrt(eps ('single')));
-%! assert(v3, v4, sqrt(eps ('single')));
+%! v3 = betainc (x, a, b);
+%! v4 = 1 - betainc (1.-x, b, a);
+%! assert (v1, v2, sqrt (eps ("single")));
+%! assert (v3, v4, sqrt (eps ("single")));
 
-%% Mixed double/single precision
+## Mixed double/single precision
 %!test
-%! a=single ([1, 1.5, 2, 3]);
-%! b=[4, 3, 2, 1];
-%! v1=betainc(1,a,b);
-%! v2=single ([1,1,1,1]);
+%! a = single ([1, 1.5, 2, 3]);
+%! b = [4, 3, 2, 1];
+%! v1 = betainc (1,a,b);
+%! v2 = single ([1,1,1,1]);
 %! x = [.2, .4, .6, .8];
-%! v3=betainc(x, a, b);
-%! v4 = 1-betainc(1.-x, b, a);
-%! assert(v1, v2, sqrt(eps ('single')));
-%! assert(v3, v4, sqrt(eps ('single')));
+%! v3 = betainc (x, a, b);
+%! v4 = 1-betainc (1.-x, b, a);
+%! assert (v1, v2, sqrt (eps ("single")));
+%! assert (v3, v4, sqrt (eps ("single")));
+
+%!error betainc ()
+%!error betainc (1)
+%!error betainc (1,2)
+%!error betainc (1,2,3,4)
+*/
+
+DEFUN (betaincinv, args, ,
+    "-*- texinfo -*-\n\
+@deftypefn {Mapping Function} {} betaincinv (@var{y}, @var{a}, @var{b})\n\
+Compute the inverse of the incomplete Beta function, i.e., @var{x} such that\n\
+\n\
+@example\n\
+@var{y} == betainc (@var{x}, @var{a}, @var{b}) \n\
+@end example\n\
+@seealso{betainc, beta, betaln}\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+  int nargin = args.length ();
+
+  if (nargin == 3)
+    {
+      octave_value x_arg = args(0);
+      octave_value a_arg = args(1);
+      octave_value b_arg = args(2);
+
+      if (x_arg.is_scalar_type ())
+        {
+          double x = x_arg.double_value ();
+
+          if (a_arg.is_scalar_type ())
+            {
+              double a = a_arg.double_value ();
 
-%% test/octave.test/arith/betainc-2.m
-%!error <Invalid call to betainc> betainc();
+              if (! error_state)
+                {
+                  if (b_arg.is_scalar_type ())
+                    {
+                      double b = b_arg.double_value ();
+
+                      if (! error_state)
+                        retval = betaincinv (x, a, b);
+                    }
+                  else
+                    {
+                      Array<double> b = b_arg.array_value ();
+
+                      if (! error_state)
+                        retval = betaincinv (x, a, b);
+                    }
+                }
+            }
+          else
+            {
+              Array<double> a = a_arg.array_value ();
+
+              if (! error_state)
+                {
+                  if (b_arg.is_scalar_type ())
+                    {
+                      double b = b_arg.double_value ();
+
+                      if (! error_state)
+                        retval = betaincinv (x, a, b);
+                    }
+                  else
+                    {
+                      Array<double> b = b_arg.array_value ();
+
+                      if (! error_state)
+                        retval = betaincinv (x, a, b);
+                    }
+                }
+            }
+        }
+      else
+        {
+          Array<double> x = x_arg.array_value ();
 
-%% test/octave.test/arith/betainc-3.m
-%!error <Invalid call to betainc> betainc(1);
+          if (a_arg.is_scalar_type ())
+            {
+              double a = a_arg.double_value ();
+
+              if (! error_state)
+                {
+                  if (b_arg.is_scalar_type ())
+                    {
+                      double b = b_arg.double_value ();
+
+                      if (! error_state)
+                        retval = betaincinv (x, a, b);
+                    }
+                  else
+                    {
+                      Array<double> b = b_arg.array_value ();
+
+                      if (! error_state)
+                        retval = betaincinv (x, a, b);
+                    }
+                }
+            }
+          else
+            {
+              Array<double> a = a_arg.array_value ();
+
+              if (! error_state)
+                {
+                  if (b_arg.is_scalar_type ())
+                    {
+                      double b = b_arg.double_value ();
+
+                      if (! error_state)
+                        retval = betaincinv (x, a, b);
+                    }
+                  else
+                    {
+                      Array<double> b = b_arg.array_value ();
 
-%% test/octave.test/arith/betainc-4.m
-%!error <Invalid call to betainc> betainc(1,2);
+                      if (! error_state)
+                        retval = betaincinv (x, a, b);
+                    }
+                }
+            }
+        }
+
+      // FIXME: It would be better to have an algorithm for betaincinv which
+      // accepted float inputs and returned float outputs.  As it is, we do
+      // extra work to calculate betaincinv to double precision and then throw
+      // that precision away.
+      if (x_arg.is_single_type () || a_arg.is_single_type () ||
+          b_arg.is_single_type ())
+        {
+          retval = Array<float> (retval.array_value ());
+        }
+    }
+  else
+    print_usage ();
+
+  return retval;
+}
 
+/*
+%!assert (betaincinv ([0.875 0.6875], [1 2], 3), [0.5 0.5], sqrt (eps))
+%!assert (betaincinv (0.5, 3, 3), 0.5, sqrt (eps))
+%!assert (betaincinv (0.34375, 4, 3), 0.5, sqrt (eps))
+%!assert (betaincinv (0.2265625, 5, 3), 0.5, sqrt (eps))
+%!assert (betaincinv (0.14453125, 6, 3), 0.5, sqrt (eps))
+%!assert (betaincinv (0.08984375, 7, 3), 0.5, sqrt (eps))
+%!assert (betaincinv (0.0546875, 8, 3), 0.5, sqrt (eps))
+%!assert (betaincinv (0.03271484375, 9, 3), 0.5, sqrt (eps))
+%!assert (betaincinv (0.019287109375, 10, 3), 0.5, sqrt (eps))
+
+## Test class single as well
+%!assert (betaincinv ([0.875 0.6875], [1 2], single (3)), [0.5 0.5], sqrt (eps ("single")))
+%!assert (betaincinv (0.5, 3, single (3)), 0.5, sqrt (eps ("single")))
+%!assert (betaincinv (0.34375, 4, single (3)), 0.5, sqrt (eps ("single")))
+
+## Extreme values
+%!assert (betaincinv (0, 42, 42), 0, sqrt (eps))
+%!assert (betaincinv (1, 42, 42), 1, sqrt (eps))
+
+%!error betaincinv ()
+%!error betaincinv (1, 2)
 */
+
rename from src/bitfcns.cc
rename to libinterp/corefcn/bitfcns.cc
--- a/src/bitfcns.cc
+++ b/libinterp/corefcn/bitfcns.cc
@@ -42,224 +42,274 @@
 #include "ov-re-mat.h"
 #include "ov-bool.h"
 
-// FIXME -- could probably eliminate some code duplication by
-// clever use of templates.
+#include <functional>
+
+#if !defined (HAVE_CXX_BITWISE_OP_TEMPLATES)
+namespace std 
+{
+  template <typename T>
+  struct bit_and 
+  {
+  public: 
+    T operator() (const T & op1, const T & op2) const { return (op1 & op2); }
+  };
+
+  template <typename T>
+  struct bit_or 
+  {
+  public: 
+    T operator() (const T & op1, const T & op2) const { return (op1 | op2); }
+  };
+
+  template <typename T>
+  struct bit_xor 
+  {
+  public: 
+    T operator() (const T & op1, const T & op2) const { return (op1 ^ op2); }
+  };
+}
+#endif
+
+template <typename OP, typename T>
+octave_value
+bitopxx (const OP& op, const std::string& fname,
+         const Array<T>& x, const Array<T>& y)
+{
+  int nelx = x.numel ();
+  int nely = y.numel ();
+
+  bool is_scalar_op = (nelx == 1 || nely == 1);
+
+  dim_vector dvx = x.dims ();
+  dim_vector dvy = y.dims ();
+
+  bool is_array_op = (dvx == dvy);
+
+  octave_value retval;
+  if (is_array_op || is_scalar_op)
+    {
+      Array<T> result;
+
+      if (nelx != 1)
+        result.resize (dvx);
+      else
+        result.resize (dvy);
+
+      for (int i = 0; i < nelx; i++)
+        if (is_scalar_op)
+          for (int k = 0; k < nely; k++)
+            result(i+k) = op (x(i), y(k));
+        else
+          result(i) = op (x(i), y(i));
 
-#define BITOPX(OP, FNAME, RET) \
-      { \
-        int nelx = x.numel (); \
-        int nely = y.numel (); \
- \
-        bool is_scalar_op = (nelx == 1 || nely == 1); \
- \
-        dim_vector dvx = x.dims (); \
-        dim_vector dvy = y.dims (); \
- \
-        bool is_array_op = (dvx == dvy); \
- \
-        if (is_array_op || is_scalar_op) \
-          { \
-            RET result; \
- \
-            if (nelx != 1) \
-              result.resize (dvx); \
-            else \
-              result.resize (dvy); \
- \
-            for (int i = 0; i < nelx; i++) \
-              if (is_scalar_op) \
-                for (int k = 0; k < nely; k++) \
-                  result(i+k) = x(i) OP y(k); \
-              else \
-                result(i) = x(i) OP y(i); \
- \
-              retval = result; \
-          } \
-        else \
-          error ("%s: size of X and Y must match, or one operand must be a scalar", FNAME); \
-      }
+      retval = result;
+    }
+  else
+    error ("%s: size of X and Y must match, or one operand must be a scalar",
+           fname.c_str ());
+
+  return retval;
+}
+
+// Trampoline function, instantiates the proper template above, with
+// reflective information hardwired. We can't hardwire this information
+// in Fbitxxx DEFUNs below, because at that moment, we still don't have
+// information about which integer types we need to instantiate.
+template<typename T>
+octave_value
+bitopx (const std::string& fname, const Array<T>& x, const Array<T>& y)
+{
+  if (fname == "bitand")
+    return bitopxx (std::bit_and<T>(), fname, x, y);
+  if (fname == "bitor")
+    return bitopxx (std::bit_or<T>(), fname, x, y);
+
+  //else (fname == "bitxor")
+  return bitopxx (std::bit_xor<T>(), fname, x, y);
+}
+
+octave_value
+bitop (const std::string& fname, const octave_value_list& args)
+{
+  octave_value retval;
+
+  int nargin = args.length ();
+
+  if (nargin == 2)
+    {
+      if ((args(0).class_name () == octave_scalar::static_class_name ())
+          || (args(0).class_name () == octave_bool::static_class_name ())
+          || (args(1).class_name () == octave_scalar::static_class_name ())
+          || (args(1).class_name () == octave_bool::static_class_name ()))
+        {
+          bool arg0_is_int = (args(0).class_name () !=
+                              octave_scalar::static_class_name () &&
+                              args(0).class_name () !=
+                              octave_bool::static_class_name ());
+          bool arg1_is_int = (args(1).class_name () !=
+                              octave_scalar::static_class_name () &&
+                              args(1).class_name () !=
+                              octave_bool::static_class_name ());
+
+          if (! (arg0_is_int || arg1_is_int))
+            {
+              uint64NDArray x (args(0).array_value ());
+              uint64NDArray y (args(1).array_value ());
+              if (! error_state)
+                retval = bitopx (fname, x, y).array_value ();
+            }
+          else
+            {
+              int p = (arg0_is_int ? 1 : 0);
+              int q = (arg0_is_int ? 0 : 1);
+
+              NDArray dx = args(p).array_value ();
 
-#define BITOP(OP, FNAME) \
- \
-  octave_value retval; \
- \
-  int nargin = args.length (); \
- \
-  if (nargin == 2) \
-    { \
-      if ((args(0).class_name () == octave_scalar::static_class_name ()) \
-          || (args(0).class_name () == octave_bool::static_class_name ()) \
-          || (args(1).class_name () == octave_scalar::static_class_name ()) \
-          || (args(1).class_name () == octave_bool::static_class_name ())) \
-        { \
-          bool arg0_is_int = (args(0).class_name () !=  \
-                              octave_scalar::static_class_name () && \
-                              args(0).class_name () != \
-                              octave_bool::static_class_name ()); \
-          bool arg1_is_int = (args(1).class_name () !=  \
-                              octave_scalar::static_class_name () && \
-                              args(1).class_name () != \
-                              octave_bool::static_class_name ()); \
-          \
-          if (! (arg0_is_int || arg1_is_int))   \
-            { \
-              uint64NDArray x (args(0).array_value ()); \
-              uint64NDArray y (args(1).array_value ()); \
-              if (! error_state) \
-                BITOPX (OP, FNAME, uint64NDArray); \
-              retval = retval.array_value (); \
-            } \
-          else \
-            { \
-              int p = (arg0_is_int ? 1 : 0); \
-              int q = (arg0_is_int ? 0 : 1); \
- \
-              NDArray dx = args(p).array_value (); \
- \
-              if (args(q).type_id () == octave_uint64_matrix::static_type_id () \
-                  || args(q).type_id () == octave_uint64_scalar::static_type_id ()) \
-                { \
-                  uint64NDArray x (dx); \
-                  uint64NDArray y = args(q).uint64_array_value (); \
-                  if (! error_state) \
-                    BITOPX (OP, FNAME, uint64NDArray); \
-                 } \
-              else if (args(q).type_id () == octave_uint32_matrix::static_type_id () \
-                       || args(q).type_id () == octave_uint32_scalar::static_type_id ()) \
-                { \
-                  uint32NDArray x (dx); \
-                  uint32NDArray y = args(q).uint32_array_value (); \
-                  if (! error_state) \
-                    BITOPX (OP, FNAME, uint32NDArray); \
-                } \
-              else if (args(q).type_id () == octave_uint16_matrix::static_type_id () \
-                       || args(q).type_id () == octave_uint16_scalar::static_type_id ()) \
-                { \
-                  uint16NDArray x (dx); \
-                  uint16NDArray y = args(q).uint16_array_value (); \
-                  if (! error_state) \
-                    BITOPX (OP, FNAME, uint16NDArray); \
-                } \
-              else if (args(q).type_id () == octave_uint8_matrix::static_type_id () \
-                       || args(q).type_id () == octave_uint8_scalar::static_type_id ()) \
-                { \
-                  uint8NDArray x (dx); \
-                  uint8NDArray y = args(q).uint8_array_value (); \
-                  if (! error_state) \
-                    BITOPX (OP, FNAME, uint8NDArray); \
-                } \
-              else if (args(q).type_id () == octave_int64_matrix::static_type_id () \
-                       || args(q).type_id () == octave_int64_scalar::static_type_id ()) \
-                { \
-                  int64NDArray x (dx); \
-                  int64NDArray y = args(q).int64_array_value (); \
-                  if (! error_state) \
-                    BITOPX (OP, FNAME, int64NDArray); \
-                } \
-              else if (args(q).type_id () == octave_int32_matrix::static_type_id () \
-                       || args(q).type_id () == octave_int32_scalar::static_type_id ()) \
-                { \
-                  int32NDArray x (dx); \
-                  int32NDArray y = args(q).int32_array_value (); \
-                  if (! error_state) \
-                    BITOPX (OP, FNAME, int32NDArray); \
-                } \
-              else if (args(q).type_id () == octave_int16_matrix::static_type_id () \
-                       || args(q).type_id () == octave_int16_scalar::static_type_id ()) \
-                { \
-                  int16NDArray x (dx); \
-                  int16NDArray y = args(q).int16_array_value (); \
-                  if (! error_state) \
-                    BITOPX (OP, FNAME, int16NDArray); \
-                } \
-              else if (args(q).type_id () == octave_int8_matrix::static_type_id () \
-                       || args(q).type_id () == octave_int8_scalar::static_type_id ()) \
-                { \
-                  int8NDArray x (dx); \
-                  int8NDArray y = args(q).int8_array_value (); \
-                  if (! error_state) \
-                    BITOPX (OP, FNAME, int8NDArray); \
-                } \
-              else \
-                error ("%s: invalid operand type", FNAME); \
-            } \
-        } \
-      else if (args(0).class_name () == args(1).class_name ()) \
-        { \
-          if (args(0).type_id () == octave_uint64_matrix::static_type_id () \
-              || args(0).type_id () == octave_uint64_scalar::static_type_id ()) \
-            { \
-              uint64NDArray x = args(0).uint64_array_value (); \
-              uint64NDArray y = args(1).uint64_array_value (); \
-              if (! error_state) \
-                BITOPX (OP, FNAME, uint64NDArray); \
-            } \
-          else if (args(0).type_id () == octave_uint32_matrix::static_type_id () \
-                   || args(0).type_id () == octave_uint32_scalar::static_type_id ()) \
-            { \
-              uint32NDArray x = args(0).uint32_array_value (); \
-              uint32NDArray y = args(1).uint32_array_value (); \
-              if (! error_state) \
-                BITOPX (OP, FNAME, uint32NDArray); \
-            } \
-          else if (args(0).type_id () == octave_uint16_matrix::static_type_id () \
-                   || args(0).type_id () == octave_uint16_scalar::static_type_id ()) \
-            { \
-              uint16NDArray x = args(0).uint16_array_value (); \
-              uint16NDArray y = args(1).uint16_array_value (); \
-              if (! error_state) \
-                BITOPX (OP, FNAME, uint16NDArray); \
-            } \
-          else if (args(0).type_id () == octave_uint8_matrix::static_type_id () \
-                   || args(0).type_id () == octave_uint8_scalar::static_type_id ()) \
-            { \
-              uint8NDArray x = args(0).uint8_array_value (); \
-              uint8NDArray y = args(1).uint8_array_value (); \
-              if (! error_state) \
-                BITOPX (OP, FNAME, uint8NDArray); \
-            } \
-          else if (args(0).type_id () == octave_int64_matrix::static_type_id () \
-                   || args(0).type_id () == octave_int64_scalar::static_type_id ()) \
-            { \
-              int64NDArray x = args(0).int64_array_value (); \
-              int64NDArray y = args(1).int64_array_value (); \
-              if (! error_state) \
-                BITOPX (OP, FNAME, int64NDArray); \
-            } \
-          else if (args(0).type_id () == octave_int32_matrix::static_type_id () \
-                   || args(0).type_id () == octave_int32_scalar::static_type_id ()) \
-            { \
-              int32NDArray x = args(0).int32_array_value (); \
-              int32NDArray y = args(1).int32_array_value (); \
-              if (! error_state) \
-                BITOPX (OP, FNAME, int32NDArray); \
-            } \
-          else if (args(0).type_id () == octave_int16_matrix::static_type_id () \
-                   || args(0).type_id () == octave_int16_scalar::static_type_id ()) \
-            { \
-              int16NDArray x = args(0).int16_array_value (); \
-              int16NDArray y = args(1).int16_array_value (); \
-              if (! error_state) \
-                BITOPX (OP, FNAME, int16NDArray); \
-            } \
-          else if (args(0).type_id () == octave_int8_matrix::static_type_id () \
-                   || args(0).type_id () == octave_int8_scalar::static_type_id ()) \
-            { \
-              int8NDArray x = args(0).int8_array_value (); \
-              int8NDArray y = args(1).int8_array_value (); \
-              if (! error_state) \
-                BITOPX (OP, FNAME, int8NDArray); \
-            } \
-          else \
-            error ("%s: invalid operand type", FNAME); \
-        } \
-      else \
-        error ("%s: must have matching operand types", FNAME); \
-    } \
-  else \
-    print_usage (); \
- \
-  return retval
+              if (args(q).type_id () == octave_uint64_matrix::static_type_id ()
+                  || args(q).type_id () == octave_uint64_scalar::static_type_id ())
+                {
+                  uint64NDArray x (dx);
+                  uint64NDArray y = args(q).uint64_array_value ();
+                  if (! error_state)
+                    retval = bitopx (fname, x, y);
+                }
+              else if (args(q).type_id () == octave_uint32_matrix::static_type_id ()
+                       || args(q).type_id () == octave_uint32_scalar::static_type_id ())
+                {
+                  uint32NDArray x (dx);
+                  uint32NDArray y = args(q).uint32_array_value ();
+                  if (! error_state)
+                    retval = bitopx (fname, x, y);
+                }
+              else if (args(q).type_id () == octave_uint16_matrix::static_type_id ()
+                       || args(q).type_id () == octave_uint16_scalar::static_type_id ())
+                {
+                  uint16NDArray x (dx);
+                  uint16NDArray y = args(q).uint16_array_value ();
+                  if (! error_state)
+                    retval = bitopx (fname, x, y);
+                }
+              else if (args(q).type_id () == octave_uint8_matrix::static_type_id ()
+                       || args(q).type_id () == octave_uint8_scalar::static_type_id ())
+                {
+                  uint8NDArray x (dx);
+                  uint8NDArray y = args(q).uint8_array_value ();
+                  if (! error_state)
+                    retval = bitopx (fname, x, y);
+                }
+              else if (args(q).type_id () == octave_int64_matrix::static_type_id ()
+                       || args(q).type_id () == octave_int64_scalar::static_type_id ())
+                {
+                  int64NDArray x (dx);
+                  int64NDArray y = args(q).int64_array_value ();
+                  if (! error_state)
+                    retval = bitopx (fname, x, y);
+                }
+              else if (args(q).type_id () == octave_int32_matrix::static_type_id ()
+                       || args(q).type_id () == octave_int32_scalar::static_type_id ())
+                {
+                  int32NDArray x (dx);
+                  int32NDArray y = args(q).int32_array_value ();
+                  if (! error_state)
+                    retval = bitopx (fname, x, y);
+                }
+              else if (args(q).type_id () == octave_int16_matrix::static_type_id ()
+                       || args(q).type_id () == octave_int16_scalar::static_type_id ())
+                {
+                  int16NDArray x (dx);
+                  int16NDArray y = args(q).int16_array_value ();
+                  if (! error_state)
+                    retval  = bitopx (fname, x, y);
+                }
+              else if (args(q).type_id () == octave_int8_matrix::static_type_id ()
+                       || args(q).type_id () == octave_int8_scalar::static_type_id ())
+                {
+                  int8NDArray x (dx);
+                  int8NDArray y = args(q).int8_array_value ();
+                  if (! error_state)
+                    retval = bitopx (fname, x, y);
+                }
+              else
+                error ("%s: invalid operand type", fname.c_str ());
+            }
+        }
+      else if (args(0).class_name () == args(1).class_name ())
+        {
+          if (args(0).type_id () == octave_uint64_matrix::static_type_id ()
+              || args(0).type_id () == octave_uint64_scalar::static_type_id ())
+            {
+              uint64NDArray x = args(0).uint64_array_value ();
+              uint64NDArray y = args(1).uint64_array_value ();
+              if (! error_state)
+                retval = bitopx (fname, x, y);
+            }
+          else if (args(0).type_id () == octave_uint32_matrix::static_type_id ()
+                   || args(0).type_id () == octave_uint32_scalar::static_type_id ())
+            {
+              uint32NDArray x = args(0).uint32_array_value ();
+              uint32NDArray y = args(1).uint32_array_value ();
+              if (! error_state)
+                retval = bitopx (fname, x, y);
+            }
+          else if (args(0).type_id () == octave_uint16_matrix::static_type_id ()
+                   || args(0).type_id () == octave_uint16_scalar::static_type_id ())
+            {
+              uint16NDArray x = args(0).uint16_array_value ();
+              uint16NDArray y = args(1).uint16_array_value ();
+              if (! error_state)
+                retval = bitopx (fname, x, y);
+            }
+          else if (args(0).type_id () == octave_uint8_matrix::static_type_id ()
+                   || args(0).type_id () == octave_uint8_scalar::static_type_id ())
+            {
+              uint8NDArray x = args(0).uint8_array_value ();
+              uint8NDArray y = args(1).uint8_array_value ();
+              if (! error_state)
+                retval = bitopx (fname, x, y);
+            }
+          else if (args(0).type_id () == octave_int64_matrix::static_type_id ()
+                   || args(0).type_id () == octave_int64_scalar::static_type_id ())
+            {
+              int64NDArray x = args(0).int64_array_value ();
+              int64NDArray y = args(1).int64_array_value ();
+              if (! error_state)
+                retval = bitopx (fname, x, y);
+            }
+          else if (args(0).type_id () == octave_int32_matrix::static_type_id ()
+                   || args(0).type_id () == octave_int32_scalar::static_type_id ())
+            {
+              int32NDArray x = args(0).int32_array_value ();
+              int32NDArray y = args(1).int32_array_value ();
+              if (! error_state)
+                retval = bitopx (fname, x, y);
+            }
+          else if (args(0).type_id () == octave_int16_matrix::static_type_id ()
+                   || args(0).type_id () == octave_int16_scalar::static_type_id ())
+            {
+              int16NDArray x = args(0).int16_array_value ();
+              int16NDArray y = args(1).int16_array_value ();
+              if (! error_state)
+                retval = bitopx (fname, x, y);
+            }
+          else if (args(0).type_id () == octave_int8_matrix::static_type_id ()
+                   || args(0).type_id () == octave_int8_scalar::static_type_id ())
+            {
+              int8NDArray x = args(0).int8_array_value ();
+              int8NDArray y = args(1).int8_array_value ();
+              if (! error_state)
+                retval = bitopx (fname, x, y);
+            }
+          else
+            error ("%s: invalid operand type", fname.c_str ());
+        }
+      else
+        error ("%s: must have matching operand types", fname.c_str ());
+    }
+  else
+    print_usage ();
+
+  return retval;
+}
 
 DEFUN (bitand, args, ,
   "-*- texinfo -*-\n\
@@ -269,7 +319,7 @@
 @seealso{bitor, bitxor, bitset, bitget, bitcmp, bitshift, bitmax}\n\
 @end deftypefn")
 {
-  BITOP (&, "bitand");
+  return bitop ("bitand", args);
 }
 
 DEFUN (bitor, args, ,
@@ -280,7 +330,7 @@
 @seealso{bitor, bitxor, bitset, bitget, bitcmp, bitshift, bitmax}\n\
 @end deftypefn")
 {
-  BITOP (|, "bitor");
+  return bitop ("bitor", args);
 }
 
 DEFUN (bitxor, args, ,
@@ -291,7 +341,7 @@
 @seealso{bitand, bitor, bitset, bitget, bitcmp, bitshift, bitmax}\n\
 @end deftypefn")
 {
-  BITOP (^, "bitxor");
+  return bitop ("bitxor", args);
 }
 
 static int64_t
@@ -665,7 +715,7 @@
   if (cname == "uint8")
     retval = octave_uint8 (std::numeric_limits<uint8_t>::min ());
   else if (cname == "uint16")
-    retval = octave_uint16 (std::numeric_limits<uint16_t>::min());
+    retval = octave_uint16 (std::numeric_limits<uint16_t>::min ());
   else if (cname == "uint32")
     retval = octave_uint32 (std::numeric_limits<uint32_t>::min ());
   else if (cname == "uint64")
rename from src/DLD-FUNCTIONS/bsxfun.cc
rename to libinterp/corefcn/bsxfun.cc
--- a/src/DLD-FUNCTIONS/bsxfun.cc
+++ b/libinterp/corefcn/bsxfun.cc
@@ -32,7 +32,7 @@
 #include "lo-mappers.h"
 
 #include "oct-map.h"
-#include "defun-dld.h"
+#include "defun.h"
 #include "parse.h"
 #include "variables.h"
 #include "ov-colon.h"
@@ -233,9 +233,9 @@
       for (octave_idx_type j = 1; j < nd; j++)
         {
           if (dva (j) == 1)
-            idx (j) = octave_value (1);
+            idx(j) = octave_value (1);
           else
-            idx (j) = octave_value ((i % dvc(j)) + 1);
+            idx(j) = octave_value ((i % dvc(j)) + 1);
 
           i = i / dvc (j);
         }
@@ -309,9 +309,9 @@
     }
 }
 
-DEFUN_DLD (bsxfun, args, ,
+DEFUN (bsxfun, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} bsxfun (@var{f}, @var{A}, @var{B})\n\
+@deftypefn {Built-in Function} {} bsxfun (@var{f}, @var{A}, @var{B})\n\
 The binary singleton expansion function applier performs broadcasting,\n\
 that is, applies a binary function @var{f} element-by-element to two\n\
 array arguments @var{A} and @var{B}, and expands as necessary\n\
@@ -442,7 +442,7 @@
                   octave_value_list idxB;
                   octave_value C;
                   octave_value_list inputs;
-                  Array<int> ra_idx (dim_vector (dvc.length(), 1), 0);
+                  Array<int> ra_idx (dim_vector (dvc.length (), 1), 0);
 
 
                   for (octave_idx_type i = 0; i < ncount; i++)
@@ -549,7 +549,7 @@
                                       result_ComplexNDArray =
                                         ComplexNDArray (result_FloatNDArray);
                                       result_ComplexNDArray.insert
-                                        (tmp(0).complex_array_value(), ra_idx);
+                                        (tmp(0).complex_array_value (), ra_idx);
                                       have_FloatComplexNDArray = false;
                                       have_ComplexNDArray = true;
                                     }
@@ -558,20 +558,20 @@
                                       result_NDArray =
                                         NDArray (result_FloatNDArray);
                                       result_NDArray.insert
-                                        (tmp(0).array_value(), ra_idx);
+                                        (tmp(0).array_value (), ra_idx);
                                       have_FloatNDArray = false;
                                       have_NDArray = true;
                                     }
                                 }
                               else if (tmp(0).is_real_type ())
                                 result_FloatNDArray.insert
-                                  (tmp(0).float_array_value(), ra_idx);
+                                  (tmp(0).float_array_value (), ra_idx);
                               else
                                 {
                                   result_FloatComplexNDArray =
                                     FloatComplexNDArray (result_FloatNDArray);
                                   result_FloatComplexNDArray.insert
-                                    (tmp(0).float_complex_array_value(), ra_idx);
+                                    (tmp(0).float_complex_array_value (), ra_idx);
                                   have_FloatNDArray = false;
                                   have_FloatComplexNDArray = true;
                                 }
@@ -585,14 +585,14 @@
                                   C = do_cat_op (C, tmp(0), ra_idx);
                                 }
                               else if (tmp(0).is_real_type ())
-                                result_NDArray.insert (tmp(0).array_value(),
+                                result_NDArray.insert (tmp(0).array_value (),
                                                        ra_idx);
                               else
                                 {
                                   result_ComplexNDArray =
                                     ComplexNDArray (result_NDArray);
                                   result_ComplexNDArray.insert
-                                    (tmp(0).complex_array_value(), ra_idx);
+                                    (tmp(0).complex_array_value (), ra_idx);
                                   have_NDArray = false;
                                   have_ComplexNDArray = true;
                                 }
@@ -630,7 +630,7 @@
 
 #define BSXEND(T) \
                   (have_ ## T) \
-                    retval (0) = result_ ## T;
+                    retval(0) = result_ ## T;
 
                   if BSXEND(NDArray)
                   else if BSXEND(ComplexNDArray)
@@ -662,17 +662,17 @@
 %! b = mean (a, 1);
 %! c = mean (a, 2);
 %! f = @minus;
-%!error(bsxfun (f));
-%!error(bsxfun (f, a));
-%!error(bsxfun (a, b));
-%!error(bsxfun (a, b, c));
-%!error(bsxfun (f, a, b, c));
-%!error(bsxfun (f, ones(4, 0), ones(4, 4)))
-%!assert(bsxfun (f, ones(4, 0), ones(4, 1)), zeros(4, 0));
-%!assert(bsxfun (f, ones(1, 4), ones(4, 1)), zeros(4, 4));
-%!assert(bsxfun (f, a, b), a - repmat(b, 4, 1));
-%!assert(bsxfun (f, a, c), a - repmat(c, 1, 4));
-%!assert(bsxfun ("minus", ones(1, 4), ones(4, 1)), zeros(4, 4));
+%!error (bsxfun (f))
+%!error (bsxfun (f, a))
+%!error (bsxfun (a, b))
+%!error (bsxfun (a, b, c))
+%!error (bsxfun (f, a, b, c))
+%!error (bsxfun (f, ones (4, 0), ones (4, 4)))
+%!assert (bsxfun (f, ones (4, 0), ones (4, 1)), zeros (4, 0))
+%!assert (bsxfun (f, ones (1, 4), ones (4, 1)), zeros (4, 4))
+%!assert (bsxfun (f, a, b), a - repmat (b, 4, 1))
+%!assert (bsxfun (f, a, c), a - repmat (c, 1, 4))
+%!assert (bsxfun ("minus", ones (1, 4), ones (4, 1)), zeros (4, 4))
 
 %!shared a, b, c, f
 %! a = randn (4, 4);
@@ -680,17 +680,17 @@
 %! b = mean (a, 1);
 %! c = mean (a, 2);
 %! f = @minus;
-%!error(bsxfun (f));
-%!error(bsxfun (f, a));
-%!error(bsxfun (a, b));
-%!error(bsxfun (a, b, c));
-%!error(bsxfun (f, a, b, c));
-%!error(bsxfun (f, ones(4, 0), ones(4, 4)))
-%!assert(bsxfun (f, ones(4, 0), ones(4, 1)), zeros(4, 0));
-%!assert(bsxfun (f, ones(1, 4), ones(4, 1)), zeros(4, 4));
-%!assert(bsxfun (f, a, b), a - repmat(b, 4, 1));
-%!assert(bsxfun (f, a, c), a - repmat(c, 1, 4));
-%!assert(bsxfun ("minus", ones(1, 4), ones(4, 1)), zeros(4, 4));
+%!error (bsxfun (f))
+%!error (bsxfun (f, a))
+%!error (bsxfun (a, b))
+%!error (bsxfun (a, b, c))
+%!error (bsxfun (f, a, b, c))
+%!error (bsxfun (f, ones (4, 0), ones (4, 4)))
+%!assert (bsxfun (f, ones (4, 0), ones (4, 1)), zeros (4, 0))
+%!assert (bsxfun (f, ones (1, 4), ones (4, 1)), zeros (4, 4))
+%!assert (bsxfun (f, a, b), a - repmat (b, 4, 1))
+%!assert (bsxfun (f, a, c), a - repmat (c, 1, 4))
+%!assert (bsxfun ("minus", ones (1, 4), ones (4, 1)), zeros (4, 4))
 
 %!shared a, b, c, f
 %! a = randn (4, 4);
@@ -698,33 +698,33 @@
 %! b = mean (a, 1);
 %! c = mean (a, 2);
 %! f = @minus;
-%!error(bsxfun (f));
-%!error(bsxfun (f, a));
-%!error(bsxfun (a, b));
-%!error(bsxfun (a, b, c));
-%!error(bsxfun (f, a, b, c));
-%!error(bsxfun (f, ones(4, 0), ones(4, 4)))
-%!assert(bsxfun (f, ones(4, 0), ones(4, 1)), zeros(4, 0));
-%!assert(bsxfun (f, ones(1, 4), ones(4, 1)), zeros(4, 4));
-%!assert(bsxfun (f, a, b), a - repmat(b, 4, 1));
-%!assert(bsxfun (f, a, c), a - repmat(c, 1, 4));
-%!assert(bsxfun ("minus", ones(1, 4), ones(4, 1)), zeros(4, 4));
+%!error (bsxfun (f))
+%!error (bsxfun (f, a))
+%!error (bsxfun (a, b))
+%!error (bsxfun (a, b, c))
+%!error (bsxfun (f, a, b, c))
+%!error (bsxfun (f, ones (4, 0), ones (4, 4)))
+%!assert (bsxfun (f, ones (4, 0), ones (4, 1)), zeros (4, 0))
+%!assert (bsxfun (f, ones (1, 4), ones (4, 1)), zeros (4, 4))
+%!assert (bsxfun (f, a, b), a - repmat (b, 4, 1))
+%!assert (bsxfun (f, a, c), a - repmat (c, 1, 4))
+%!assert (bsxfun ("minus", ones (1, 4), ones (4, 1)), zeros (4, 4))
 
 %!shared a, b, c, f
 %! a = randn (4, 4);
 %! b = a (1, :);
 %! c = a (:, 1);
 %! f = @(x, y) x == y;
-%!error(bsxfun (f));
-%!error(bsxfun (f, a));
-%!error(bsxfun (a, b));
-%!error(bsxfun (a, b, c));
-%!error(bsxfun (f, a, b, c));
-%!error(bsxfun (f, ones(4, 0), ones(4, 4)))
-%!assert(bsxfun (f, ones(4, 0), ones(4, 1)), zeros(4, 0, "logical"));
-%!assert(bsxfun (f, ones(1, 4), ones(4, 1)), ones(4, 4, "logical"));
-%!assert(bsxfun (f, a, b), a == repmat(b, 4, 1));
-%!assert(bsxfun (f, a, c), a == repmat(c, 1, 4));
+%!error (bsxfun (f))
+%!error (bsxfun (f, a))
+%!error (bsxfun (a, b))
+%!error (bsxfun (a, b, c))
+%!error (bsxfun (f, a, b, c))
+%!error (bsxfun (f, ones (4, 0), ones (4, 4)))
+%!assert (bsxfun (f, ones (4, 0), ones (4, 1)), zeros (4, 0, "logical"))
+%!assert (bsxfun (f, ones (1, 4), ones (4, 1)), ones (4, 4, "logical"))
+%!assert (bsxfun (f, a, b), a == repmat (b, 4, 1))
+%!assert (bsxfun (f, a, c), a == repmat (c, 1, 4))
 
 %!shared a, b, c, d, f
 %! a = randn (4, 4, 4);
@@ -732,43 +732,43 @@
 %! c = mean (a, 2);
 %! d = mean (a, 3);
 %! f = @minus;
-%!error(bsxfun (f, ones([4, 0, 4]), ones([4, 4, 4])));
-%!assert(bsxfun (f, ones([4, 0, 4]), ones([4, 1, 4])), zeros([4, 0, 4]));
-%!assert(bsxfun (f, ones([4, 4, 0]), ones([4, 1, 1])), zeros([4, 4, 0]));
-%!assert(bsxfun (f, ones([1, 4, 4]), ones([4, 1, 4])), zeros([4, 4, 4]));
-%!assert(bsxfun (f, ones([4, 4, 1]), ones([4, 1, 4])), zeros([4, 4, 4]));
-%!assert(bsxfun (f, ones([4, 1, 4]), ones([1, 4, 4])), zeros([4, 4, 4]));
-%!assert(bsxfun (f, ones([4, 1, 4]), ones([1, 4, 1])), zeros([4, 4, 4]));
-%!assert(bsxfun (f, a, b), a - repmat(b, [4, 1, 1]));
-%!assert(bsxfun (f, a, c), a - repmat(c, [1, 4, 1]));
-%!assert(bsxfun (f, a, d), a - repmat(d, [1, 1, 4]));
-%!assert(bsxfun ("minus", ones([4, 0, 4]), ones([4, 1, 4])), zeros([4, 0, 4]));
+%!error (bsxfun (f, ones ([4, 0, 4]), ones ([4, 4, 4])))
+%!assert (bsxfun (f, ones ([4, 0, 4]), ones ([4, 1, 4])), zeros ([4, 0, 4]))
+%!assert (bsxfun (f, ones ([4, 4, 0]), ones ([4, 1, 1])), zeros ([4, 4, 0]))
+%!assert (bsxfun (f, ones ([1, 4, 4]), ones ([4, 1, 4])), zeros ([4, 4, 4]))
+%!assert (bsxfun (f, ones ([4, 4, 1]), ones ([4, 1, 4])), zeros ([4, 4, 4]))
+%!assert (bsxfun (f, ones ([4, 1, 4]), ones ([1, 4, 4])), zeros ([4, 4, 4]))
+%!assert (bsxfun (f, ones ([4, 1, 4]), ones ([1, 4, 1])), zeros ([4, 4, 4]))
+%!assert (bsxfun (f, a, b), a - repmat (b, [4, 1, 1]))
+%!assert (bsxfun (f, a, c), a - repmat (c, [1, 4, 1]))
+%!assert (bsxfun (f, a, d), a - repmat (d, [1, 1, 4]))
+%!assert (bsxfun ("minus", ones ([4, 0, 4]), ones ([4, 1, 4])), zeros ([4, 0, 4]))
 
-%% The below is a very hard case to treat
-%!assert(bsxfun (f, ones([4, 1, 4, 1]), ones([1, 4, 1, 4])), zeros([4, 4, 4, 4]));
+%% The test below is a very hard case to treat
+%!assert (bsxfun (f, ones ([4, 1, 4, 1]), ones ([1, 4, 1, 4])), zeros ([4, 4, 4, 4]));
 
 %!shared a, b, aa, bb
 %! a = randn (3, 1, 3);
 %! aa = a(:, ones (1, 3), :, ones (1, 3));
 %! b = randn (1, 3, 3, 3);
 %! bb = b(ones (1, 3), :, :, :);
-%!assert (bsxfun (@plus, a, b), aa + bb);
-%!assert (bsxfun (@minus, a, b), aa - bb);
-%!assert (bsxfun (@times, a, b), aa .* bb);
-%!assert (bsxfun (@rdivide, a, b), aa ./ bb);
-%!assert (bsxfun (@ldivide, a, b), aa .\ bb);
-%!assert (bsxfun (@power, a, b), aa .^ bb);
-%!assert (bsxfun (@power, abs (a), b), abs (aa) .^ bb);
-%!assert (bsxfun (@eq, round (a), round (b)), round (aa) == round (bb));
-%!assert (bsxfun (@ne, round (a), round (b)), round (aa) != round (bb));
-%!assert (bsxfun (@lt, a, b), aa < bb);
-%!assert (bsxfun (@le, a, b), aa <= bb);
-%!assert (bsxfun (@gt, a, b), aa > bb);
-%!assert (bsxfun (@ge, a, b), aa >= bb);
-%!assert (bsxfun (@min, a, b), min (aa, bb));
-%!assert (bsxfun (@max, a, b), max (aa, bb));
-%!assert (bsxfun (@and, a > 0, b > 0), (aa > 0) & (bb > 0));
-%!assert (bsxfun (@or, a > 0, b > 0), (aa > 0) | (bb > 0));
+%!assert (bsxfun (@plus, a, b), aa + bb)
+%!assert (bsxfun (@minus, a, b), aa - bb)
+%!assert (bsxfun (@times, a, b), aa .* bb)
+%!assert (bsxfun (@rdivide, a, b), aa ./ bb)
+%!assert (bsxfun (@ldivide, a, b), aa .\ bb)
+%!assert (bsxfun (@power, a, b), aa .^ bb)
+%!assert (bsxfun (@power, abs (a), b), abs (aa) .^ bb)
+%!assert (bsxfun (@eq, round (a), round (b)), round (aa) == round (bb))
+%!assert (bsxfun (@ne, round (a), round (b)), round (aa) != round (bb))
+%!assert (bsxfun (@lt, a, b), aa < bb)
+%!assert (bsxfun (@le, a, b), aa <= bb)
+%!assert (bsxfun (@gt, a, b), aa > bb)
+%!assert (bsxfun (@ge, a, b), aa >= bb)
+%!assert (bsxfun (@min, a, b), min (aa, bb))
+%!assert (bsxfun (@max, a, b), max (aa, bb))
+%!assert (bsxfun (@and, a > 0, b > 0), (aa > 0) & (bb > 0))
+%!assert (bsxfun (@or, a > 0, b > 0), (aa > 0) | (bb > 0))
 
 %% Test automatic bsxfun
 %
@@ -779,14 +779,14 @@
 %!
 %! float_types = {@single, @double};
 %! int_types = {@int8, @int16, @int32, @int64, \
-%!             @uint8, @uint16, @uint32, @uint64};
+%!              @uint8, @uint16, @uint32, @uint64};
 %!
-%! x = rand (3)*10-5;
-%! y = rand (3,1)*10-5;
+%! x = rand (3) * 10-5;
+%! y = rand (3,1) * 10-5;
 %!
 %! for i=1:length (funs)
-%!   for j = 1:length(float_types)
-%!     for k = 1:length(int_types)
+%!   for j = 1:length (float_types)
+%!     for k = 1:length (int_types)
 %!
 %!       fun = funs{i};
 %!       f_type = float_types{j};
rename from src/DLD-FUNCTIONS/cellfun.cc
rename to libinterp/corefcn/cellfun.cc
--- a/src/DLD-FUNCTIONS/cellfun.cc
+++ b/libinterp/corefcn/cellfun.cc
@@ -38,7 +38,7 @@
 
 #include "Cell.h"
 #include "oct-map.h"
-#include "defun-dld.h"
+#include "defun.h"
 #include "parse.h"
 #include "variables.h"
 #include "ov-colon.h"
@@ -123,42 +123,42 @@
     {
       boolNDArray result (f_args.dims ());
       for (octave_idx_type count = 0; count < k; count++)
-        result(count) = f_args.elem(count).is_empty ();
+        result(count) = f_args.elem (count).is_empty ();
       retval(0) = result;
     }
   else if (name == "islogical")
     {
       boolNDArray result (f_args.dims ());
       for (octave_idx_type  count= 0; count < k; count++)
-        result(count) = f_args.elem(count).is_bool_type ();
+        result(count) = f_args.elem (count).is_bool_type ();
       retval(0) = result;
     }
   else if (name == "isreal")
     {
       boolNDArray result (f_args.dims ());
       for (octave_idx_type  count= 0; count < k; count++)
-        result(count) = f_args.elem(count).is_real_type ();
+        result(count) = f_args.elem (count).is_real_type ();
       retval(0) = result;
     }
   else if (name == "length")
     {
       NDArray result (f_args.dims ());
       for (octave_idx_type  count= 0; count < k; count++)
-        result(count) = static_cast<double> (f_args.elem(count).length ());
+        result(count) = static_cast<double> (f_args.elem (count).length ());
       retval(0) = result;
     }
   else if (name == "ndims")
     {
       NDArray result (f_args.dims ());
       for (octave_idx_type count = 0; count < k; count++)
-        result(count) = static_cast<double> (f_args.elem(count).ndims ());
+        result(count) = static_cast<double> (f_args.elem (count).ndims ());
       retval(0) = result;
     }
   else if (name == "prodofsize" || name == "numel")
     {
       NDArray result (f_args.dims ());
       for (octave_idx_type count = 0; count < k; count++)
-        result(count) = static_cast<double> (f_args.elem(count).numel ());
+        result(count) = static_cast<double> (f_args.elem (count).numel ());
       retval(0) = result;
     }
   else if (name == "size")
@@ -175,7 +175,7 @@
               NDArray result (f_args.dims ());
               for (octave_idx_type count = 0; count < k; count++)
                 {
-                  dim_vector dv = f_args.elem(count).dims ();
+                  dim_vector dv = f_args.elem (count).dims ();
                   if (d < dv.length ())
                     result(count) = static_cast<double> (dv(d));
                   else
@@ -191,10 +191,10 @@
     {
       if (nargin == 3)
         {
-          std::string class_name = args(2).string_value();
+          std::string class_name = args(2).string_value ();
           boolNDArray result (f_args.dims ());
           for (octave_idx_type count = 0; count < k; count++)
-            result(count) = (f_args.elem(count).class_name() == class_name);
+            result(count) = (f_args.elem (count).class_name () == class_name);
 
           retval(0) = result;
         }
@@ -216,7 +216,7 @@
       size_t compare_len = std::max (arg.length (), static_cast<size_t> (2));
 
       if (arg.compare ("uniformoutput", compare_len))
-        uniform_output = args(nargin-1).bool_value();
+        uniform_output = args(nargin-1).bool_value ();
       else if (arg.compare ("errorhandler", compare_len))
         {
           if (args(nargin-1).is_function_handle ()
@@ -246,7 +246,7 @@
       else
         {
           error ("cellfun: unrecognized parameter %s",
-                 arg.c_str());
+                 arg.c_str ());
           break;
         }
 
@@ -256,16 +256,16 @@
   nargin -= 1;
 }
 
-DEFUN_DLD (cellfun, args, nargout,
+DEFUN (cellfun, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} cellfun (@var{name}, @var{C})\n\
-@deftypefnx {Loadable Function} {} cellfun (\"size\", @var{C}, @var{k})\n\
-@deftypefnx {Loadable Function} {} cellfun (\"isclass\", @var{C}, @var{class})\n\
-@deftypefnx {Loadable Function} {} cellfun (@var{func}, @var{C})\n\
-@deftypefnx {Loadable Function} {} cellfun (@var{func}, @var{C}, @var{D})\n\
-@deftypefnx {Loadable Function} {[@var{a}, @dots{}] =} cellfun (@dots{})\n\
-@deftypefnx {Loadable Function} {} cellfun (@dots{}, 'ErrorHandler', @var{errfunc})\n\
-@deftypefnx {Loadable Function} {} cellfun (@dots{}, 'UniformOutput', @var{val})\n\
+@deftypefn  {Built-in Function} {} cellfun (@var{name}, @var{C})\n\
+@deftypefnx {Built-in Function} {} cellfun (\"size\", @var{C}, @var{k})\n\
+@deftypefnx {Built-in Function} {} cellfun (\"isclass\", @var{C}, @var{class})\n\
+@deftypefnx {Built-in Function} {} cellfun (@var{func}, @var{C})\n\
+@deftypefnx {Built-in Function} {} cellfun (@var{func}, @var{C}, @var{D})\n\
+@deftypefnx {Built-in Function} {[@var{a}, @dots{}] =} cellfun (@dots{})\n\
+@deftypefnx {Built-in Function} {} cellfun (@dots{}, \"ErrorHandler\", @var{errfunc})\n\
+@deftypefnx {Built-in Function} {} cellfun (@dots{}, \"UniformOutput\", @var{val})\n\
 \n\
 Evaluate the function named @var{name} on the elements of the cell array\n\
 @var{C}.  Elements in @var{C} are passed on to the named function\n\
@@ -310,7 +310,7 @@
 @example\n\
 @group\n\
 cellfun (\"atan2\", @{1, 0@}, @{0, 1@})\n\
-     @result{}ans = [1.57080   0.00000]\n\
+     @result{} [ 1.57080   0.00000 ]\n\
 @end group\n\
 @end example\n\
 \n\
@@ -324,7 +324,7 @@
   a = x;\n\
   b = x*x;\n\
 endfunction\n\
-[aa, bb] = cellfun(@@twoouts, @{1, 2, 3@})\n\
+[aa, bb] = cellfun (@@twoouts, @{1, 2, 3@})\n\
      @result{}\n\
         aa =\n\
            1 2 3\n\
@@ -337,21 +337,21 @@
 the input arguments.  Input arguments that are singleton (1x1) cells will be\n\
 automatically expanded to the size of the other arguments.\n\
 \n\
-If the parameter 'UniformOutput' is set to true (the default), then the\n\
+If the parameter \"UniformOutput\" is set to true (the default), then the\n\
 function must return scalars which will be concatenated into the return\n\
-array(s).  If 'UniformOutput' is false, the outputs are concatenated into a\n\
+array(s).  If \"UniformOutput\" is false, the outputs are concatenated into a\n\
 cell array (or cell arrays).  For example:\n\
 \n\
 @example\n\
 @group\n\
 cellfun (\"tolower\", @{\"Foo\", \"Bar\", \"FooBar\"@},\n\
-         \"UniformOutput\",false)\n\
-@result{} ans = @{\"foo\", \"bar\", \"foobar\"@}\n\
+         \"UniformOutput\", false)\n\
+@result{} @{\"foo\", \"bar\", \"foobar\"@}\n\
 @end group\n\
 @end example\n\
 \n\
-Given the parameter 'ErrorHandler', then @var{errfunc} defines a function to\n\
-call in case @var{func} generates an error.  The form of the function is\n\
+Given the parameter \"ErrorHandler\", then @var{errfunc} defines a function\n\
+to call in case @var{func} generates an error.  The form of the function is\n\
 \n\
 @example\n\
 function [@dots{}] = errfunc (@var{s}, @dots{})\n\
@@ -367,8 +367,8 @@
 @example\n\
 @group\n\
 function y = foo (s, x), y = NaN; endfunction\n\
-cellfun (\"factorial\", @{-1,2@}, 'ErrorHandler', @@foo)\n\
-@result{} ans = [NaN 2]\n\
+cellfun (\"factorial\", @{-1,2@}, \"ErrorHandler\", @@foo)\n\
+@result{} [NaN 2]\n\
 @end group\n\
 @end example\n\
 \n\
@@ -382,7 +382,7 @@
 @example\n\
 @group\n\
 a = @{@dots{}@}\n\
-v = cellfun (@@(x) det(x), a); # compute determinants\n\
+v = cellfun (@@(x) det (x), a); # compute determinants\n\
 v = cellfun (@@det, a); # faster\n\
 @end group\n\
 @end example\n\
@@ -719,309 +719,310 @@
 /*
 
 %!function r = __f11 (x)
-%!  global __cellfun_test_num_outputs__
+%!  global __cellfun_test_num_outputs__;
 %!  __cellfun_test_num_outputs__ = nargout;
 %!  r = x;
 %!endfunction
 
 %!function __f01 (x)
-%!  global __cellfun_test_num_outputs__
+%!  global __cellfun_test_num_outputs__;
 %!  __cellfun_test_num_outputs__ = nargout;
 %!endfunction
 
 %!test
-%! global __cellfun_test_num_outputs__
+%! global __cellfun_test_num_outputs__;
 %! cellfun (@__f11, {1});
-%! assert (__cellfun_test_num_outputs__, 0)
+%! assert (__cellfun_test_num_outputs__, 0);
 %! x = cellfun (@__f11, {1});
-%! assert (__cellfun_test_num_outputs__, 1)
+%! assert (__cellfun_test_num_outputs__, 1);
 
 %!test
-%! global __cellfun_test_num_outputs__
+%! global __cellfun_test_num_outputs__;
 %! cellfun (@__f01, {1});
-%! assert (__cellfun_test_num_outputs__, 0)
+%! assert (__cellfun_test_num_outputs__, 0);
 
 %!error x = cellfun (@__f01, {1, 2});
 
 %!test
-%! assert (cellfun (@__f11, {1, 2}), [1, 2])
-%! assert (cellfun (@__f11, {1, 2}, 'uniformoutput', false), {1, 2})
+%! assert (cellfun (@__f11, {1, 2}), [1, 2]);
+%! assert (cellfun (@__f11, {1, 2}, 'uniformoutput', false), {1, 2});
 
 %!test
-%!  [a,b] = cellfun (@(x) x, cell (2, 0));
-%!  assert (a, zeros (2, 0));
-%!  assert (b, zeros (2, 0));
+%! [a,b] = cellfun (@(x) x, cell (2, 0));
+%! assert (a, zeros (2, 0));
+%! assert (b, zeros (2, 0));
 
 %!test
-%!  [a,b] = cellfun (@(x) x, cell (2, 0), "uniformoutput", false);
-%!  assert (a, cell (2, 0));
-%!  assert (b, cell (2, 0));
+%! [a,b] = cellfun (@(x) x, cell (2, 0), "uniformoutput", false);
+%! assert (a, cell (2, 0));
+%! assert (b, cell (2, 0));
 
 %% Test function to check the "Errorhandler" option
-%!function [z] = __cellfunerror (S, varargin)
+%!function z = __cellfunerror (S, varargin)
 %!  z = S;
 %!endfunction
 
 %% First input argument can be a string, an inline function,
 %% a function_handle or an anonymous function
 %!test
-%!  A = cellfun ("islogical", {true, 0.1, false, i*2});
-%!  assert (A, [true, false, true, false]);
+%! A = cellfun ("islogical", {true, 0.1, false, i*2});
+%! assert (A, [true, false, true, false]);
 %!test
-%!  A = cellfun (inline ("islogical (x)", "x"), {true, 0.1, false, i*2});
-%!  assert (A, [true, false, true, false]);
+%! A = cellfun (inline ("islogical (x)", "x"), {true, 0.1, false, i*2});
+%! assert (A, [true, false, true, false]);
 %!test
-%!  A = cellfun (@islogical, {true, 0.1, false, i*2});
-%!  assert (A, [true, false, true, false]);
+%! A = cellfun (@islogical, {true, 0.1, false, i*2});
+%! assert (A, [true, false, true, false]);
 %!test
-%!  A = cellfun (@(x) islogical(x), {true, 0.1, false, i*2});
-%!  assert (A, [true, false, true, false]);
+%! A = cellfun (@(x) islogical (x), {true, 0.1, false, i*2});
+%! assert (A, [true, false, true, false]);
 
 %% First input argument can be the special string "isreal",
 %% "isempty", "islogical", "length", "ndims" or "prodofsize"
 %!test
-%!  A = cellfun ("isreal", {true, 0.1, {}, i*2, [], "abc"});
-%!  assert (A, [true, true, false, false, true, true]);
+%! A = cellfun ("isreal", {true, 0.1, {}, i*2, [], "abc"});
+%! assert (A, [true, true, false, false, true, true]);
 %!test
-%!  A = cellfun ("isempty", {true, 0.1, false, i*2, [], "abc"});
-%!  assert (A, [false, false, false, false, true, false]);
+%! A = cellfun ("isempty", {true, 0.1, false, i*2, [], "abc"});
+%! assert (A, [false, false, false, false, true, false]);
 %!test
-%!  A = cellfun ("islogical", {true, 0.1, false, i*2, [], "abc"});
-%!  assert (A, [true, false, true, false, false, false]);
+%! A = cellfun ("islogical", {true, 0.1, false, i*2, [], "abc"});
+%! assert (A, [true, false, true, false, false, false]);
 %!test
-%!  A = cellfun ("length", {true, 0.1, false, i*2, [], "abc"});
-%!  assert (A, [1, 1, 1, 1, 0, 3]);
+%! A = cellfun ("length", {true, 0.1, false, i*2, [], "abc"});
+%! assert (A, [1, 1, 1, 1, 0, 3]);
 %!test
-%!  A = cellfun ("ndims", {[1, 2; 3, 4]; (cell (1,2,3,4))});
-%!  assert (A, [2; 4]);
+%! A = cellfun ("ndims", {[1, 2; 3, 4]; (cell (1,2,3,4))});
+%! assert (A, [2; 4]);
 %!test
-%!  A = cellfun ("prodofsize", {[1, 2; 3, 4], (cell (1,2,3,4))});
-%!  assert (A, [4, 24]);
+%! A = cellfun ("prodofsize", {[1, 2; 3, 4], (cell (1,2,3,4))});
+%! assert (A, [4, 24]);
 
 %% Number of input and output arguments may not be limited to one
 %!test
-%!  A = cellfun (@(x,y,z) x + y + z, {1, 1, 1}, {2, 2, 2}, {3, 4, 5});
-%!  assert (A, [6, 7, 8]);
+%! A = cellfun (@(x,y,z) x + y + z, {1, 1, 1}, {2, 2, 2}, {3, 4, 5});
+%! assert (A, [6, 7, 8]);
 %!test
-%!  A = cellfun (@(x,y,z) x + y + z, {1, 1, 1}, {2, 2, 2}, {3, 4, 5}, \
-%!    "UniformOutput", false);
-%!  assert (A, {6, 7, 8});
+%! A = cellfun (@(x,y,z) x + y + z, {1, 1, 1}, {2, 2, 2}, {3, 4, 5}, \
+%!              "UniformOutput", false);
+%! assert (A, {6, 7, 8});
 %!test %% Two input arguments of different types
-%!  A = cellfun (@(x,y) islogical (x) && ischar (y), {false, true}, {"a", 3});
-%!  assert (A, [true, false]);
+%! A = cellfun (@(x,y) islogical (x) && ischar (y), {false, true}, {"a", 3});
+%! assert (A, [true, false]);
 %!test %% Pass another variable to the anonymous function
-%!  y = true; A = cellfun (@(x) islogical (x) && y, {false, 0.3});
-%!  assert (A, [true, false]);
+%! y = true;
+%! A = cellfun (@(x) islogical (x) && y, {false, 0.3});
+%! assert (A, [true, false]);
 %!test %% Three ouptut arguments of different type
-%!  [A, B, C] = cellfun (@find, {10, 11; 0, 12}, "UniformOutput", false);
-%!  assert (isequal (A, {true, true; [], true}));
-%!  assert (isequal (B, {true, true; [], true}));
-%!  assert (isequal (C, {10, 11; [], 12}));
+%! [A, B, C] = cellfun (@find, {10, 11; 0, 12}, "UniformOutput", false);
+%! assert (isequal (A, {true, true; [], true}));
+%! assert (isequal (B, {true, true; [], true}));
+%! assert (isequal (C, {10, 11; [], 12}));
 
 %% Input arguments can be of type cell array of logical
 %!test
-%!  A = cellfun (@(x,y) x == y, {false, true}, {true, true});
-%!  assert (A, [false, true]);
+%! A = cellfun (@(x,y) x == y, {false, true}, {true, true});
+%! assert (A, [false, true]);
 %!test
-%!  A = cellfun (@(x,y) x == y, {false; true}, {true; true}, \
-%!    "UniformOutput", true);
-%!  assert (A, [false; true]);
+%! A = cellfun (@(x,y) x == y, {false; true}, {true; true}, \
+%!              "UniformOutput", true);
+%! assert (A, [false; true]);
 %!test
-%!  A = cellfun (@(x) x, {false, true; false, true}, "UniformOutput", false);
-%!  assert (A, {false, true; false, true});
+%! A = cellfun (@(x) x, {false, true; false, true}, "UniformOutput", false);
+%! assert (A, {false, true; false, true});
 %!test %% Three ouptut arguments of same type
-%!  [A, B, C] = cellfun (@find, {true, false; false, true}, \
-%!    "UniformOutput", false);
-%!  assert (isequal (A, {true, []; [], true}));
-%!  assert (isequal (B, {true, []; [], true}));
-%!  assert (isequal (C, {true, []; [], true}));
+%! [A, B, C] = cellfun (@find, {true, false; false, true}, \
+%!                      "UniformOutput", false);
+%! assert (isequal (A, {true, []; [], true}));
+%! assert (isequal (B, {true, []; [], true}));
+%! assert (isequal (C, {true, []; [], true}));
 %!test
-%!  A = cellfun (@(x,y) cell2str (x,y), {true}, {true}, \
-%!    "ErrorHandler", @__cellfunerror);
-%!  assert (isfield (A, "identifier"), true);
-%!  assert (isfield (A, "message"), true);
-%!  assert (isfield (A, "index"), true);
-%!  assert (isempty (A.message), false);
-%!  assert (A.index, 1);
+%! A = cellfun (@(x,y) cell2str (x,y), {true}, {true}, \
+%!              "ErrorHandler", @__cellfunerror);
+%! assert (isfield (A, "identifier"), true);
+%! assert (isfield (A, "message"), true);
+%! assert (isfield (A, "index"), true);
+%! assert (isempty (A.message), false);
+%! assert (A.index, 1);
 %!test %% Overwriting setting of "UniformOutput" true
-%!  A = cellfun (@(x,y) cell2str (x,y), {true}, {true}, \
-%!    "UniformOutput", true, "ErrorHandler", @__cellfunerror);
-%!  assert (isfield (A, "identifier"), true);
-%!  assert (isfield (A, "message"), true);
-%!  assert (isfield (A, "index"), true);
-%!  assert (isempty (A.message), false);
-%!  assert (A.index, 1);
+%! A = cellfun (@(x,y) cell2str (x,y), {true}, {true}, \
+%!              "UniformOutput", true, "ErrorHandler", @__cellfunerror);
+%! assert (isfield (A, "identifier"), true);
+%! assert (isfield (A, "message"), true);
+%! assert (isfield (A, "index"), true);
+%! assert (isempty (A.message), false);
+%! assert (A.index, 1);
 
 %% Input arguments can be of type cell array of numeric
 %!test
-%!  A = cellfun (@(x,y) x>y, {1.1, 4.2}, {3.1, 2+3*i});
-%!  assert (A, [false, true]);
+%! A = cellfun (@(x,y) x>y, {1.1, 4.2}, {3.1, 2+3*i});
+%! assert (A, [false, true]);
 %!test
-%!  A = cellfun (@(x,y) x>y, {1.1, 4.2; 2, 4}, {3.1, 2; 2, 4+2*i}, \
-%!    "UniformOutput", true);
-%!  assert (A, [false, true; false, false]);
+%! A = cellfun (@(x,y) x>y, {1.1, 4.2; 2, 4}, {3.1, 2; 2, 4+2*i}, \
+%!              "UniformOutput", true);
+%! assert (A, [false, true; false, false]);
 %!test
-%!  A = cellfun (@(x,y) x:y, {1.1, 4}, {3.1, 6}, "UniformOutput", false);
-%!  assert (isequal (A{1}, [1.1, 2.1, 3.1]));
-%!  assert (isequal (A{2}, [4, 5, 6]));
+%! A = cellfun (@(x,y) x:y, {1.1, 4}, {3.1, 6}, "UniformOutput", false);
+%! assert (isequal (A{1}, [1.1, 2.1, 3.1]));
+%! assert (isequal (A{2}, [4, 5, 6]));
 %!test %% Three ouptut arguments of different type
-%!  [A, B, C] = cellfun (@find, {10, 11; 0, 12}, "UniformOutput", false);
-%!  assert (isequal (A, {true, true; [], true}));
-%!  assert (isequal (B, {true, true; [], true}));
-%!  assert (isequal (C, {10, 11; [], 12}));
+%! [A, B, C] = cellfun (@find, {10, 11; 0, 12}, "UniformOutput", false);
+%! assert (isequal (A, {true, true; [], true}));
+%! assert (isequal (B, {true, true; [], true}));
+%! assert (isequal (C, {10, 11; [], 12}));
 %!test
-%!  A = cellfun (@(x,y) cell2str(x,y), {1.1, 4}, {3.1, 6}, \
-%!    "ErrorHandler", @__cellfunerror);
-%!  B = isfield (A(1), "message") && isfield (A(1), "index");
-%!  assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
-%!  assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
-%!  assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
-%!  assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
-%!  assert ([A(1).index, A(2).index], [1, 2]);
+%! A = cellfun (@(x,y) cell2str (x,y), {1.1, 4}, {3.1, 6}, \
+%!              "ErrorHandler", @__cellfunerror);
+%! B = isfield (A(1), "message") && isfield (A(1), "index");
+%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
+%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
+%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
+%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
+%! assert ([A(1).index, A(2).index], [1, 2]);
 %!test %% Overwriting setting of "UniformOutput" true
-%!  A = cellfun (@(x,y) cell2str(x,y), {1.1, 4}, {3.1, 6}, \
-%!    "UniformOutput", true, "ErrorHandler", @__cellfunerror);
-%!  B = isfield (A(1), "message") && isfield (A(1), "index");
-%!  assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
-%!  assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
-%!  assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
-%!  assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
-%!  assert ([A(1).index, A(2).index], [1, 2]);
+%! A = cellfun (@(x,y) cell2str (x,y), {1.1, 4}, {3.1, 6}, \
+%!              "UniformOutput", true, "ErrorHandler", @__cellfunerror);
+%! B = isfield (A(1), "message") && isfield (A(1), "index");
+%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
+%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
+%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
+%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
+%! assert ([A(1).index, A(2).index], [1, 2]);
 
 %% Input arguments can be of type cell arrays of character or strings
 %!error %% "UniformOutput" false should be used
-%!  A = cellfun (@(x,y) x>y, {"ad", "c", "ghi"}, {"cc", "d", "fgh"});
+%! A = cellfun (@(x,y) x>y, {"ad", "c", "ghi"}, {"cc", "d", "fgh"});
 %!test
-%!  A = cellfun (@(x,y) x>y, {"a"; "f"}, {"c"; "d"}, "UniformOutput", true);
-%!  assert (A, [false; true]);
+%! A = cellfun (@(x,y) x>y, {"a"; "f"}, {"c"; "d"}, "UniformOutput", true);
+%! assert (A, [false; true]);
 %!test
-%!  A = cellfun (@(x,y) x:y, {"a", "d"}, {"c", "f"}, "UniformOutput", false);
-%!  assert (A, {"abc", "def"});
+%! A = cellfun (@(x,y) x:y, {"a", "d"}, {"c", "f"}, "UniformOutput", false);
+%! assert (A, {"abc", "def"});
 %!test
-%!  A = cellfun (@(x,y) cell2str(x,y), {"a", "d"}, {"c", "f"}, \
-%!    "ErrorHandler", @__cellfunerror);
-%!  assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
-%!  assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
-%!  assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
-%!  assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
-%!  assert ([A(1).index, A(2).index], [1, 2]);
+%! A = cellfun (@(x,y) cell2str (x,y), {"a", "d"}, {"c", "f"}, \
+%!              "ErrorHandler", @__cellfunerror);
+%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
+%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
+%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
+%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
+%! assert ([A(1).index, A(2).index], [1, 2]);
 %!test %% Overwriting setting of "UniformOutput" true
-%!  A = cellfun (@(x,y) cell2str(x,y), {"a", "d"}, {"c", "f"}, \
-%!    "UniformOutput", true, "ErrorHandler", @__cellfunerror);
-%!  assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
-%!  assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
-%!  assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
-%!  assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
-%!  assert ([A(1).index, A(2).index], [1, 2]);
+%! A = cellfun (@(x,y) cell2str (x,y), {"a", "d"}, {"c", "f"}, \
+%!              "UniformOutput", true, "ErrorHandler", @__cellfunerror);
+%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
+%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
+%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
+%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
+%! assert ([A(1).index, A(2).index], [1, 2]);
 
 %% Structures cannot be handled by cellfun
 %!error
-%!  vst1.a = 1.1; vst1.b = 4.2; vst2.a = 3.1; vst2.b = 2;
-%!  A = cellfun (@(x,y) (x.a < y.a) && (x.b > y.b), vst1, vst2);
+%! vst1.a = 1.1;  vst1.b = 4.2;  vst2.a = 3.1;  vst2.b = 2;
+%! A = cellfun (@(x,y) (x.a < y.a) && (x.b > y.b), vst1, vst2);
 
 %% Input arguments can be of type cell array of cell arrays
 %!test
-%!  A = cellfun (@(x,y) x{1} < y{1}, {{1.1}, {4.2}}, {{3.1}, {2}});
-%!  assert (A, [1, 0], 1e-16);
+%! A = cellfun (@(x,y) x{1} < y{1}, {{1.1}, {4.2}}, {{3.1}, {2}});
+%! assert (A, [1, 0], 1e-16);
 %!test
-%!  A = cellfun (@(x,y) x{1} < y{1}, {{1.1}; {4.2}}, {{3.1}; {2}}, \
-%!    "UniformOutput", true);
-%!  assert (A, [1; 0], 1e-16);
+%! A = cellfun (@(x,y) x{1} < y{1}, {{1.1}; {4.2}}, {{3.1}; {2}}, \
+%!              "UniformOutput", true);
+%! assert (A, [1; 0], 1e-16);
 %!test
-%!  A = cellfun (@(x,y) x{1} < y{1}, {{1.1}, {4.2}}, {{3.1}, {2}}, \
-%!    "UniformOutput", false);
-%!  assert (A, {true, false});
+%! A = cellfun (@(x,y) x{1} < y{1}, {{1.1}, {4.2}}, {{3.1}, {2}}, \
+%!              "UniformOutput", false);
+%! assert (A, {true, false});
 %!test
-%!  A = cellfun (@(x,y) mat2str(x,y), {{1.1}, {4.2}}, {{3.1}, {2}}, \
-%!    "ErrorHandler", @__cellfunerror);
-%!  assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
-%!  assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
-%!  assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
-%!  assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
-%!  assert ([A(1).index, A(2).index], [1, 2]);
+%! A = cellfun (@(x,y) mat2str (x,y), {{1.1}, {4.2}}, {{3.1}, {2}}, \
+%!              "ErrorHandler", @__cellfunerror);
+%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
+%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
+%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
+%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
+%! assert ([A(1).index, A(2).index], [1, 2]);
 %!test %% Overwriting setting of "UniformOutput" true
-%!  A = cellfun (@(x,y) mat2str(x,y), {{1.1}, {4.2}}, {{3.1}, {2}}, \
-%!    "UniformOutput", true, "ErrorHandler", @__cellfunerror);
-%!  assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
-%!  assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
-%!  assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
-%!  assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
-%!  assert ([A(1).index, A(2).index], [1, 2]);
+%! A = cellfun (@(x,y) mat2str (x,y), {{1.1}, {4.2}}, {{3.1}, {2}}, \
+%!              "UniformOutput", true, "ErrorHandler", @__cellfunerror);
+%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
+%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
+%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
+%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
+%! assert ([A(1).index, A(2).index], [1, 2]);
 
 %% Input arguments can be of type cell array of structure arrays
 %!test
-%!  a = struct ("a", 1, "b", 2); b = struct ("a", 1, "b", 3);
-%!  A = cellfun (@(x,y) (x.a == y.a) && (x.b < y.b), {a}, {b});
-%!  assert (A, true);
+%! a = struct ("a", 1, "b", 2);  b = struct ("a", 1, "b", 3);
+%! A = cellfun (@(x,y) (x.a == y.a) && (x.b < y.b), {a}, {b});
+%! assert (A, true);
 %!test
-%!  a = struct ("a", 1, "b", 2); b = struct ("a", 1, "b", 3);
-%!  A = cellfun (@(x,y) (x.a == y.a) && (x.b < y.b) , {a}, {b}, \
-%!    "UniformOutput", true);
-%!  assert (A, true);
+%! a = struct ("a", 1, "b", 2);  b = struct ("a", 1, "b", 3);
+%! A = cellfun (@(x,y) (x.a == y.a) && (x.b < y.b) , {a}, {b}, \
+%!              "UniformOutput", true);
+%! assert (A, true);
 %!test
-%!  a = struct ("a", 1, "b", 2); b = struct ("a", 1, "b", 3);
-%!  A = cellfun (@(x,y) (x.a == y.a) && (x.b < y.b) , {a}, {b}, \
-%!    "UniformOutput", false);
-%!  assert (A, {true});
+%! a = struct ("a", 1, "b", 2);  b = struct ("a", 1, "b", 3);
+%! A = cellfun (@(x,y) (x.a == y.a) && (x.b < y.b) , {a}, {b}, \
+%!              "UniformOutput", false);
+%! assert (A, {true});
 %!test
-%!  a = struct ("a", 1, "b", 2); b = struct ("a", 1, "b", 3);
-%!  A = cellfun (@(x,y) cell2str (x.a, y.a), {a}, {b}, \
-%!    "ErrorHandler", @__cellfunerror);
-%!  assert (isfield (A, "identifier"), true);
-%!  assert (isfield (A, "message"), true);
-%!  assert (isfield (A, "index"), true);
-%!  assert (isempty (A.message), false);
-%!  assert (A.index, 1);
+%! a = struct ("a", 1, "b", 2);  b = struct ("a", 1, "b", 3);
+%! A = cellfun (@(x,y) cell2str (x.a, y.a), {a}, {b}, \
+%!              "ErrorHandler", @__cellfunerror);
+%! assert (isfield (A, "identifier"), true);
+%! assert (isfield (A, "message"), true);
+%! assert (isfield (A, "index"), true);
+%! assert (isempty (A.message), false);
+%! assert (A.index, 1);
 %!test %% Overwriting setting of "UniformOutput" true
-%!  a = struct ("a", 1, "b", 2); b = struct ("a", 1, "b", 3);
-%!  A = cellfun (@(x,y) cell2str (x.a, y.a), {a}, {b}, \
-%!    "UniformOutput", true, "ErrorHandler", @__cellfunerror);
-%!  assert (isfield (A, "identifier"), true);
-%!  assert (isfield (A, "message"), true);
-%!  assert (isfield (A, "index"), true);
-%!  assert (isempty (A.message), false);
-%!  assert (A.index, 1);
+%! a = struct ("a", 1, "b", 2);  b = struct ("a", 1, "b", 3);
+%! A = cellfun (@(x,y) cell2str (x.a, y.a), {a}, {b}, \
+%!              "UniformOutput", true, "ErrorHandler", @__cellfunerror);
+%! assert (isfield (A, "identifier"), true);
+%! assert (isfield (A, "message"), true);
+%! assert (isfield (A, "index"), true);
+%! assert (isempty (A.message), false);
+%! assert (A.index, 1);
 
 %% A lot of other tests
-%!error(cellfun(1))
-%!error(cellfun('isclass',1))
-%!error(cellfun('size',1))
-%!error(cellfun(@sin,{[]},'BadParam',false))
-%!error(cellfun(@sin,{[]},'UniformOuput'))
-%!error(cellfun(@sin,{[]},'ErrorHandler'))
-%!assert(cellfun(@sin,{0,1}),sin([0,1]))
-%!assert(cellfun(inline('sin(x)'),{0,1}),sin([0,1]))
-%!assert(cellfun('sin',{0,1}),sin([0,1]))
-%!assert(cellfun('isempty',{1,[]}),[false,true])
-%!assert(cellfun('islogical',{false,pi}),[true,false])
-%!assert(cellfun('isreal',{1i,1}),[false,true])
-%!assert(cellfun('length',{zeros(2,2),1}),[2,1])
-%!assert(cellfun('prodofsize',{zeros(2,2),1}),[4,1])
-%!assert(cellfun('ndims',{zeros([2,2,2]),1}),[3,2])
-%!assert(cellfun('isclass',{zeros([2,2,2]),'test'},'double'),[true,false])
-%!assert(cellfun('size',{zeros([1,2,3]),1},1),[1,1])
-%!assert(cellfun('size',{zeros([1,2,3]),1},2),[2,1])
-%!assert(cellfun('size',{zeros([1,2,3]),1},3),[3,1])
-%!assert(cellfun(@atan2,{1,1},{1,2}),[atan2(1,1),atan2(1,2)])
-%!assert(cellfun(@atan2,{1,1},{1,2},'UniformOutput',false),{atan2(1,1),atan2(1,2)})
-%!assert(cellfun(@sin,{1,2;3,4}),sin([1,2;3,4]))
-%!assert(cellfun(@atan2,{1,1;1,1},{1,2;1,2}),atan2([1,1;1,1],[1,2;1,2]))
-%!error(cellfun(@factorial,{-1,3}))
-%!assert(cellfun(@factorial,{-1,3},'ErrorHandler',@(x,y) NaN),[NaN,6])
+%!assert (cellfun (@sin, {0,1}), sin ([0,1]))
+%!assert (cellfun (inline ("sin (x)"), {0,1}), sin ([0,1]))
+%!assert (cellfun ("sin", {0,1}), sin ([0,1]))
+%!assert (cellfun ("isempty", {1,[]}), [false,true])
+%!assert (cellfun ("islogical", {false,pi}), [true,false])
+%!assert (cellfun ("isreal", {1i,1}), [false,true])
+%!assert (cellfun ("length", {zeros(2,2),1}), [2,1])
+%!assert (cellfun ("prodofsize", {zeros(2,2),1}), [4,1])
+%!assert (cellfun ("ndims", {zeros([2,2,2]),1}), [3,2])
+%!assert (cellfun ("isclass", {zeros([2,2,2]),"test"}, "double"), [true,false])
+%!assert (cellfun ("size", {zeros([1,2,3]),1}, 1), [1,1])
+%!assert (cellfun ("size", {zeros([1,2,3]),1}, 2), [2,1])
+%!assert (cellfun ("size", {zeros([1,2,3]),1}, 3), [3,1])
+%!assert (cellfun (@atan2, {1,1}, {1,2}), [atan2(1,1), atan2(1,2)])
+%!assert (cellfun (@atan2, {1,1}, {1,2},"UniformOutput", false), {atan2(1,1), atan2(1,2)})
+%!assert (cellfun (@sin, {1,2;3,4}), sin ([1,2;3,4]))
+%!assert (cellfun (@atan2, {1,1;1,1}, {1,2;1,2}), atan2 ([1,1;1,1],[1,2;1,2]))
+%!error cellfun (@factorial, {-1,3})
+%!assert (cellfun (@factorial,{-1,3},"ErrorHandler",@(x,y) NaN), [NaN,6])
 %!assert (cellfun (@(x) x(2),{[1],[1,2]},"ErrorHandler",@(x,y) NaN), [NaN,2])
 %!test
-%! [a,b,c]=cellfun(@fileparts,{fullfile("a","b","c.d"),fullfile("e","f","g.h")},'UniformOutput',false);
-%! assert(a,{fullfile("a","b"),fullfile("e","f")})
-%! assert(b,{'c','g'})
-%! assert(c,{'.d','.h'})
+%! [a,b,c] = cellfun (@fileparts, {fullfile("a","b","c.d"), fullfile("e","f","g.h")}, "UniformOutput", false);
+%! assert (a, {fullfile("a","b"), fullfile("e","f")});
+%! assert (b, {"c", "g"});
+%! assert (c, {".d", ".h"});
 
+%!error cellfun (1)
+%!error cellfun ("isclass", 1)
+%!error cellfun ("size", 1)
+%!error cellfun (@sin, {[]}, "BadParam", false)
+%!error cellfun (@sin, {[]}, "UniformOuput")
+%!error cellfun (@sin, {[]}, "ErrorHandler")
 */
 
 // Arrayfun was originally a .m file written by Bill Denney and Jaroslav
 // Hajek.  It was converted to C++ by jwe so that it could properly
 // handle the nargout = 0 case.
 
-DEFUN_DLD (arrayfun, args, nargout,
+DEFUN (arrayfun, args, nargout,
   "-*- texinfo -*-\n\
 @deftypefn  {Function File} {} arrayfun (@var{func}, @var{A})\n\
 @deftypefnx {Function File} {@var{x} =} arrayfun (@var{func}, @var{A})\n\
@@ -1050,7 +1051,7 @@
 @example\n\
 @group\n\
 arrayfun (@@atan2, [1, 0], [0, 1])\n\
-@result{} ans = [1.5708   0.0000]\n\
+     @result{} [ 1.5708   0.0000 ]\n\
 @end group\n\
 @end example\n\
 \n\
@@ -1064,12 +1065,12 @@
 @example\n\
 @group\n\
 arrayfun (@@(x,y) x:y, \"abc\", \"def\", \"UniformOutput\", false)\n\
-@result{} ans =\n\
-    @{\n\
-      [1,1] = abcd\n\
-      [1,2] = bcde\n\
-      [1,3] = cdef\n\
-    @}\n\
+@result{}\n\
+   @{\n\
+     [1,1] = abcd\n\
+     [1,2] = bcde\n\
+     [1,3] = cdef\n\
+   @}\n\
 @end group\n\
 @end example\n\
 \n\
@@ -1083,18 +1084,18 @@
 @result{}\n\
 A =\n\
 @{\n\
-  [1,1] =  1\n\
-  [2,1] = [](0x0)\n\
+   [1,1] =  1\n\
+   [2,1] = [](0x0)\n\
 @}\n\
 B =\n\
 @{\n\
-  [1,1] =  1\n\
-  [2,1] = [](0x0)\n\
+   [1,1] =  1\n\
+   [2,1] = [](0x0)\n\
 @}\n\
 C =\n\
 @{\n\
-  [1,1] =  10\n\
-  [2,1] = [](0x0)\n\
+   [1,1] =  10\n\
+   [2,1] = [](0x0)\n\
 @}\n\
 @end group\n\
 @end example\n\
@@ -1123,11 +1124,11 @@
 @group\n\
 function y = ferr (s, x), y = \"MyString\"; endfunction\n\
 arrayfun (@@str2num, [1234],\n\
-           \"UniformOutput\", false, \"ErrorHandler\", @@ferr)\n\
-@result{} ans =\n\
-    @{\n\
+          \"UniformOutput\", false, \"ErrorHandler\", @@ferr)\n\
+@result{}\n\
+   @{\n\
      [1,1] = MyString\n\
-    @}\n\
+   @}\n\
 @end group\n\
 @end example\n\
 \n\
@@ -1140,7 +1141,8 @@
 
   if (nargin < 2)
     {
-      error ("arrayfun: function requires at least 2 arguments");
+      error_with_id ("Octave:invalid-fun-call", 
+                     "arrayfun: function requires at least 2 arguments");
       print_usage ();
       return retval;
     }
@@ -1171,7 +1173,9 @@
           func = symbol_table::find_function (name);
 
           if (func.is_undefined ())
-            error ("arrayfun: invalid function NAME: %s", name.c_str ());
+            error_with_id ("Octave:invalid-input-arg",
+                           "arrayfun: invalid function NAME: %s",
+                           name.c_str ());
 
           symbol_table_lookup = true;
         }
@@ -1249,7 +1253,8 @@
                 {
                   if (mask[i] && inputs[i].dims () != fdims)
                     {
-                      error ("arrayfun: dimensions mismatch");
+                      error_with_id ("Octave:invalid-input-arg", 
+                                     "arrayfun: dimensions mismatch");
                       return retval;
                     }
                 }
@@ -1296,7 +1301,8 @@
 
               if (nargout > 0 && tmp.length () < nargout)
                 {
-                  error ("arrayfun: function returned fewer than nargout values");
+                  error_with_id ("Octave:invalid-fun-call", 
+                                 "arrayfun: function returned fewer than nargout values");
                   return retval;
                 }
 
@@ -1321,7 +1327,8 @@
                                 retv[j] = val.resize (fdims);
                               else
                                 {
-                                  error ("arrayfun: all values must be scalars when UniformOutput = true");
+                                  error_with_id ("Octave:invalid-fun-call",
+                                                 "arrayfun: all values must be scalars when UniformOutput = true");
                                   break;
                                 }
                             }
@@ -1348,7 +1355,8 @@
                                     }
                                   else
                                     {
-                                      error ("arrayfun: all values must be scalars when UniformOutput = true");
+                                      error_with_id ("Octave:invalid-fun-call",
+                                                     "arrayfun: all values must be scalars when UniformOutput = true");
                                       break;
                                     }
                                 }
@@ -1406,7 +1414,8 @@
 
               if (nargout > 0 && tmp.length () < nargout)
                 {
-                  error ("arrayfun: function returned fewer than nargout values");
+                  error_with_id ("Octave:invalid-fun-call", 
+                                 "arrayfun: function returned fewer than nargout values");
                   return retval;
                 }
 
@@ -1437,221 +1446,226 @@
         }
     }
   else
-    error ("arrayfun: argument NAME must be a string or function handle");
+    error_with_id ("Octave:invalid-fun-call", 
+                   "arrayfun: argument NAME must be a string or function handle");
 
   return retval;
 }
 
 /*
 %!function r = __f11 (x)
-%!  global __arrayfun_test_num_outputs__
+%!  global __arrayfun_test_num_outputs__;
 %!  __arrayfun_test_num_outputs__ = nargout;
 %!  r = x;
 %!endfunction
 
 %!function __f01 (x)
-%!  global __arrayfun_test_num_outputs__
+%!  global __arrayfun_test_num_outputs__;
 %!  __arrayfun_test_num_outputs__ = nargout;
 %!endfunction
 
 %!test
-%! global __arrayfun_test_num_outputs__
+%! global __arrayfun_test_num_outputs__;
 %! arrayfun (@__f11, {1});
-%! assert (__arrayfun_test_num_outputs__, 0)
+%! assert (__arrayfun_test_num_outputs__, 0);
 %! x = arrayfun (@__f11, {1});
-%! assert (__arrayfun_test_num_outputs__, 1)
+%! assert (__arrayfun_test_num_outputs__, 1);
 
 %!test
-%! global __arrayfun_test_num_outputs__
+%! global __arrayfun_test_num_outputs__;
 %! arrayfun (@__f01, {1});
-%! assert (__arrayfun_test_num_outputs__, 0)
+%! assert (__arrayfun_test_num_outputs__, 0);
 
 %!error x = arrayfun (@__f01, [1, 2]);
 
 %!test
-%! assert (arrayfun (@__f11, [1, 2]), [1, 2])
-%! assert (arrayfun (@__f11, [1, 2], 'uniformoutput', false), {1, 2});
-%! assert (arrayfun (@__f11, {1, 2}), {1, 2})
-%! assert (arrayfun (@__f11, {1, 2}, 'uniformoutput', false), {{1}, {2}});
+%! assert (arrayfun (@__f11, [1, 2]), [1, 2]);
+%! assert (arrayfun (@__f11, [1, 2], "uniformoutput", false), {1, 2});
+%! assert (arrayfun (@__f11, {1, 2}), {1, 2});
+%! assert (arrayfun (@__f11, {1, 2}, "uniformoutput", false), {{1}, {2}});
 
-%!assert (arrayfun (@ones, 1, [2,3], 'uniformoutput', false), {[1,1], [1,1,1]});
+%!assert (arrayfun (@ones, 1, [2,3], "uniformoutput", false), {[1,1], [1,1,1]})
 
 %% Test function to check the "Errorhandler" option
-%!function [z] = __arrayfunerror (S, varargin)
-%!      z = S;
+%!function z = __arrayfunerror (S, varargin)
+%!  z = S;
 %!endfunction
 %% First input argument can be a string, an inline function, a
 %% function_handle or an anonymous function
 %!test
-%!  arrayfun (@isequal, [false, true], [true, true]); %% No output argument
+%! arrayfun (@isequal, [false, true], [true, true]); %% No output argument
 %!error
-%!  arrayfun (@isequal); %% One or less input arguments
+%! arrayfun (@isequal); %% One or less input arguments
 %!test
-%!  A = arrayfun ("isequal", [false, true], [true, true]);
-%!  assert (A, [false, true]);
+%! A = arrayfun ("isequal", [false, true], [true, true]);
+%! assert (A, [false, true]);
 %!test
-%!  A = arrayfun (inline ("(x == y)", "x", "y"), [false, true], [true, true]);
-%!  assert (A, [false, true]);
+%! A = arrayfun (inline ("(x == y)", "x", "y"), [false, true], [true, true]);
+%! assert (A, [false, true]);
 %!test
-%!  A = arrayfun (@isequal, [false, true], [true, true]);
-%!  assert (A, [false, true]);
+%! A = arrayfun (@isequal, [false, true], [true, true]);
+%! assert (A, [false, true]);
 %!test
-%!  A = arrayfun (@(x,y) isequal(x,y), [false, true], [true, true]);
-%!  assert (A, [false, true]);
+%! A = arrayfun (@(x,y) isequal (x,y), [false, true], [true, true]);
+%! assert (A, [false, true]);
 
 %% Number of input and output arguments may be greater than one
 %#!test
-%!  A = arrayfun (@(x) islogical (x), false);
-%!  assert (A, true);
+%! A = arrayfun (@(x) islogical (x), false);
+%! assert (A, true);
 %!test
-%!  A = arrayfun (@(x,y,z) x + y + z, [1, 1, 1], [2, 2, 2], [3, 4, 5]);
-%!  assert (A, [6, 7, 8], 1e-16);
+%! A = arrayfun (@(x,y,z) x + y + z, [1, 1, 1], [2, 2, 2], [3, 4, 5]);
+%! assert (A, [6, 7, 8], 1e-16);
 %!test %% Two input arguments of different types
-%!  A = arrayfun (@(x,y) islogical (x) && ischar (y), false, "a");
-%!  assert (A, true);
+%! A = arrayfun (@(x,y) islogical (x) && ischar (y), false, "a");
+%! assert (A, true);
 %!test %% Pass another variable to the anonymous function
-%!  y = true; A = arrayfun (@(x) islogical (x && y), false);
-%!  assert (A, true);
+%! y = true;
+%! A = arrayfun (@(x) islogical (x && y), false);
+%! assert (A, true);
 %!test %% Three ouptut arguments of different type
-%!  [A, B, C] = arrayfun (@find, [10, 11; 0, 12], "UniformOutput", false);
-%!  assert (isequal (A, {true, true; [], true}));
-%!  assert (isequal (B, {true, true; [], true}));
-%!  assert (isequal (C, {10, 11; [], 12}));
+%! [A, B, C] = arrayfun (@find, [10, 11; 0, 12], "UniformOutput", false);
+%! assert (isequal (A, {true, true; [], true}));
+%! assert (isequal (B, {true, true; [], true}));
+%! assert (isequal (C, {10, 11; [], 12}));
 
 %% Input arguments can be of type logical
 %!test
-%!  A = arrayfun (@(x,y) x == y, [false, true], [true, true]);
-%!  assert (A, [false, true]);
+%! A = arrayfun (@(x,y) x == y, [false, true], [true, true]);
+%! assert (A, [false, true]);
 %!test
-%!  A = arrayfun (@(x,y) x == y, [false; true], [true; true], "UniformOutput", true);
-%!  assert (A, [false; true]);
+%! A = arrayfun (@(x,y) x == y, [false; true], [true; true], "UniformOutput", true);
+%! assert (A, [false; true]);
 %!test
-%!  A = arrayfun (@(x) x, [false, true, false, true], "UniformOutput", false);
-%!  assert (A, {false, true, false, true});
+%! A = arrayfun (@(x) x, [false, true, false, true], "UniformOutput", false);
+%! assert (A, {false, true, false, true});
 %!test %% Three ouptut arguments of same type
-%!  [A, B, C] = arrayfun (@find, [true, false; false, true], "UniformOutput", false);
-%!  assert (isequal (A, {true, []; [], true}));
-%!  assert (isequal (B, {true, []; [], true}));
-%!  assert (isequal (C, {true, []; [], true}));
+%! [A, B, C] = arrayfun (@find, [true, false; false, true], "UniformOutput", false);
+%! assert (isequal (A, {true, []; [], true}));
+%! assert (isequal (B, {true, []; [], true}));
+%! assert (isequal (C, {true, []; [], true}));
 %!test
-%!  A = arrayfun (@(x,y) array2str (x,y), true, true, "ErrorHandler", @__arrayfunerror);
-%!  assert (isfield (A, "identifier"), true);
-%!  assert (isfield (A, "message"), true);
-%!  assert (isfield (A, "index"), true);
-%!  assert (isempty (A.message), false);
-%!  assert (A.index, 1);
+%! A = arrayfun (@(x,y) array2str (x,y), true, true, \
+%!               "ErrorHandler", @__arrayfunerror);
+%! assert (isfield (A, "identifier"), true);
+%! assert (isfield (A, "message"), true);
+%! assert (isfield (A, "index"), true);
+%! assert (isempty (A.message), false);
+%! assert (A.index, 1);
 %!test %% Overwriting setting of "UniformOutput" true
-%!  A = arrayfun (@(x,y) array2str (x,y), true, true, \
-%!                "UniformOutput", true, "ErrorHandler", @__arrayfunerror);
-%!  assert (isfield (A, "identifier"), true);
-%!  assert (isfield (A, "message"), true);
-%!  assert (isfield (A, "index"), true);
-%!  assert (isempty (A.message), false);
-%!  assert (A.index, 1);
+%! A = arrayfun (@(x,y) array2str (x,y), true, true, "UniformOutput", true, \
+%!               "ErrorHandler", @__arrayfunerror);
+%! assert (isfield (A, "identifier"), true);
+%! assert (isfield (A, "message"), true);
+%! assert (isfield (A, "index"), true);
+%! assert (isempty (A.message), false);
+%! assert (A.index, 1);
 
 %% Input arguments can be of type numeric
 %!test
-%!  A = arrayfun (@(x,y) x>y, [1.1, 4.2], [3.1, 2+3*i]);
-%!  assert (A, [false, true]);
+%! A = arrayfun (@(x,y) x>y, [1.1, 4.2], [3.1, 2+3*i]);
+%! assert (A, [false, true]);
 %!test
-%!  A = arrayfun (@(x,y) x>y, [1.1, 4.2; 2, 4], [3.1, 2; 2, 4+2*i], "UniformOutput", true);
-%!  assert (A, [false, true; false, false]);
+%! A = arrayfun (@(x,y) x>y, [1.1, 4.2; 2, 4], [3.1, 2; 2, 4+2*i], "UniformOutput", true);
+%! assert (A, [false, true; false, false]);
 %!test
-%!  A = arrayfun (@(x,y) x:y, [1.1, 4], [3.1, 6], "UniformOutput", false);
-%!  assert (isequal (A{1}, [1.1, 2.1, 3.1]));
-%!  assert (isequal (A{2}, [4, 5, 6]));
+%! A = arrayfun (@(x,y) x:y, [1.1, 4], [3.1, 6], "UniformOutput", false);
+%! assert (isequal (A{1}, [1.1, 2.1, 3.1]));
+%! assert (isequal (A{2}, [4, 5, 6]));
 %!test %% Three ouptut arguments of different type
-%!  [A, B, C] = arrayfun (@find, [10, 11; 0, 12], "UniformOutput", false);
-%!  assert (isequal (A, {true, true; [], true}));
-%!  assert (isequal (B, {true, true; [], true}));
-%!  assert (isequal (C, {10, 11; [], 12}));
+%! [A, B, C] = arrayfun (@find, [10, 11; 0, 12], "UniformOutput", false);
+%! assert (isequal (A, {true, true; [], true}));
+%! assert (isequal (B, {true, true; [], true}));
+%! assert (isequal (C, {10, 11; [], 12}));
 %!test
-%!  A = arrayfun (@(x,y) array2str(x,y), {1.1, 4}, {3.1, 6}, "ErrorHandler", @__arrayfunerror);
-%!  B = isfield (A(1), "message") && isfield (A(1), "index");
-%!  assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
-%!  assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
-%!  assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
-%!  assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
-%!  assert ([A(1).index, A(2).index], [1, 2]);
+%! A = arrayfun (@(x,y) array2str (x,y), {1.1, 4}, {3.1, 6}, \
+%!               "ErrorHandler", @__arrayfunerror);
+%! B = isfield (A(1), "message") && isfield (A(1), "index");
+%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
+%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
+%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
+%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
+%! assert ([A(1).index, A(2).index], [1, 2]);
 %!test %% Overwriting setting of "UniformOutput" true
-%!  A = arrayfun (@(x,y) array2str(x,y), {1.1, 4}, {3.1, 6}, \
-%!                "UniformOutput", true, "ErrorHandler", @__arrayfunerror);
-%!  B = isfield (A(1), "message") && isfield (A(1), "index");
-%!  assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
-%!  assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
-%!  assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
-%!  assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
-%!  assert ([A(1).index, A(2).index], [1, 2]);
+%! A = arrayfun (@(x,y) array2str (x,y), {1.1, 4}, {3.1, 6}, \
+%!               "UniformOutput", true, "ErrorHandler", @__arrayfunerror);
+%! B = isfield (A(1), "message") && isfield (A(1), "index");
+%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
+%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
+%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
+%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
+%! assert ([A(1).index, A(2).index], [1, 2]);
 
 %% Input arguments can be of type character or strings
 %!test
-%!  A = arrayfun (@(x,y) x>y, ["ad", "c", "ghi"], ["cc", "d", "fgh"]);
-%!  assert (A, [false, true, false, true, true, true]);
+%! A = arrayfun (@(x,y) x>y, ["ad", "c", "ghi"], ["cc", "d", "fgh"]);
+%! assert (A, [false, true, false, true, true, true]);
 %!test
-%!  A = arrayfun (@(x,y) x>y, ["a"; "f"], ["c"; "d"], "UniformOutput", true);
-%!  assert (A, [false; true]);
+%! A = arrayfun (@(x,y) x>y, ["a"; "f"], ["c"; "d"], "UniformOutput", true);
+%! assert (A, [false; true]);
 %!test
-%!  A = arrayfun (@(x,y) x:y, ["a", "d"], ["c", "f"], "UniformOutput", false);
-%!  assert (A, {"abc", "def"});
-%! %#!test
-%!   A = arrayfun (@(x,y) cell2str(x,y), ["a", "d"], ["c", "f"], "ErrorHandler", @__arrayfunerror);
-%!   B = isfield (A(1), "identifier") && isfield (A(1), "message") && isfield (A(1), "index");
-%!   assert (B, true);
+%! A = arrayfun (@(x,y) x:y, ["a", "d"], ["c", "f"], "UniformOutput", false);
+%! assert (A, {"abc", "def"});
+%!test
+%! A = arrayfun (@(x,y) cell2str (x,y), ["a", "d"], ["c", "f"], \
+%!               "ErrorHandler", @__arrayfunerror);
+%! B = isfield (A(1), "identifier") && isfield (A(1), "message") && isfield (A(1), "index");
+%! assert (B, true);
 
 %% Input arguments can be of type structure
 %!test
-%!  a = struct ("a", 1.1, "b", 4.2); b = struct ("a", 3.1, "b", 2);
-%!  A = arrayfun (@(x,y) (x.a < y.a) && (x.b > y.b), a, b);
-%!  assert (A, true);
+%! a = struct ("a", 1.1, "b", 4.2);  b = struct ("a", 3.1, "b", 2);
+%! A = arrayfun (@(x,y) (x.a < y.a) && (x.b > y.b), a, b);
+%! assert (A, true);
 %!test
-%!  a = struct ("a", 1.1, "b", 4.2); b = struct ("a", 3.1, "b", 2);
-%!  A = arrayfun (@(x,y) (x.a < y.a) && (x.b > y.b), a, b, "UniformOutput", true);
-%!  assert (A, true);
+%! a = struct ("a", 1.1, "b", 4.2);  b = struct ("a", 3.1, "b", 2);
+%! A = arrayfun (@(x,y) (x.a < y.a) && (x.b > y.b), a, b, "UniformOutput", true);
+%! assert (A, true);
 %!test
-%!  a = struct ("a", 1.1, "b", 4.2); b = struct ("a", 3.1, "b", 2);
-%!  A = arrayfun (@(x,y) x.a:y.a, a, b, "UniformOutput", false);
-%!  assert (isequal (A, {[1.1, 2.1, 3.1]}));
+%! a = struct ("a", 1.1, "b", 4.2);  b = struct ("a", 3.1, "b", 2);
+%! A = arrayfun (@(x,y) x.a:y.a, a, b, "UniformOutput", false);
+%! assert (isequal (A, {[1.1, 2.1, 3.1]}));
 %!test
-%!  A = arrayfun (@(x) mat2str(x), "a", "ErrorHandler", @__arrayfunerror);
-%!  assert (isfield (A, "identifier"), true);
-%!  assert (isfield (A, "message"), true);
-%!  assert (isfield (A, "index"), true);
-%!  assert (isempty (A.message), false);
-%!  assert (A.index, 1);
+%! A = arrayfun (@(x) mat2str(x), "a", "ErrorHandler", @__arrayfunerror);
+%! assert (isfield (A, "identifier"), true);
+%! assert (isfield (A, "message"), true);
+%! assert (isfield (A, "index"), true);
+%! assert (isempty (A.message), false);
+%! assert (A.index, 1);
 %!test %% Overwriting setting of "UniformOutput" true
-%!  A = arrayfun (@(x) mat2str(x), "a", "UniformOutput", true, \
-%!                "ErrorHandler", @__arrayfunerror);
-%!  assert (isfield (A, "identifier"), true);
-%!  assert (isfield (A, "message"), true);
-%!  assert (isfield (A, "index"), true);
-%!  assert (isempty (A.message), false);
-%!  assert (A.index, 1);
+%! A = arrayfun (@(x) mat2str(x), "a", "UniformOutput", true, \
+%!               "ErrorHandler", @__arrayfunerror);
+%! assert (isfield (A, "identifier"), true);
+%! assert (isfield (A, "message"), true);
+%! assert (isfield (A, "index"), true);
+%! assert (isempty (A.message), false);
+%! assert (A.index, 1);
 
 %% Input arguments can be of type cell array
 %!test
-%!  A = arrayfun (@(x,y) x{1} < y{1}, {1.1, 4.2}, {3.1, 2});
-%!  assert (A, [true, false]);
+%! A = arrayfun (@(x,y) x{1} < y{1}, {1.1, 4.2}, {3.1, 2});
+%! assert (A, [true, false]);
 %!test
-%!  A = arrayfun (@(x,y) x{1} < y{1}, {1.1; 4.2}, {3.1; 2}, "UniformOutput", true);
-%!  assert (A, [true; false]);
+%! A = arrayfun (@(x,y) x{1} < y{1}, {1.1; 4.2}, {3.1; 2}, "UniformOutput", true);
+%! assert (A, [true; false]);
 %!test
-%!  A = arrayfun (@(x,y) x{1} < y{1}, {1.1, 4.2}, {3.1, 2}, "UniformOutput", false);
-%!  assert (A, {true, false});
+%! A = arrayfun (@(x,y) x{1} < y{1}, {1.1, 4.2}, {3.1, 2}, "UniformOutput", false);
+%! assert (A, {true, false});
 %!test
-%!  A = arrayfun (@(x,y) num2str(x,y), {1.1, 4.2}, {3.1, 2}, "ErrorHandler", @__arrayfunerror);
-%!  assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
-%!  assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
-%!  assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
-%!  assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
-%!  assert ([A(1).index, A(2).index], [1, 2]);
+%! A = arrayfun (@(x,y) num2str(x,y), {1.1, 4.2}, {3.1, 2}, "ErrorHandler", @__arrayfunerror);
+%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
+%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
+%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
+%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
+%! assert ([A(1).index, A(2).index], [1, 2]);
 %!test
-%!  A = arrayfun (@(x,y) num2str(x,y), {1.1, 4.2}, {3.1, 2}, \
-%!                "UniformOutput", true, "ErrorHandler", @__arrayfunerror);
-%!  assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
-%!  assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
-%!  assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
-%!  assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
-%!  assert ([A(1).index, A(2).index], [1, 2]);
+%! A = arrayfun (@(x,y) num2str (x,y), {1.1, 4.2}, {3.1, 2}, \
+%!               "UniformOutput", true, "ErrorHandler", @__arrayfunerror);
+%! assert ([(isfield (A(1), "identifier")), (isfield (A(2), "identifier"))], [true, true]);
+%! assert ([(isfield (A(1), "message")), (isfield (A(2), "message"))], [true, true]);
+%! assert ([(isfield (A(1), "index")), (isfield (A(2), "index"))], [true, true]);
+%! assert ([(isempty (A(1).message)), (isempty (A(2).message))], [false, false]);
+%! assert ([A(1).index, A(2).index], [1, 2]);
 */
 
 static void
@@ -1793,7 +1807,7 @@
 
               idx(0) = double (i+1);
 
-              retval.xelem(i) = array.single_subsref ("(", idx);
+              retval.xelem (i) = array.single_subsref ("(", idx);
 
               if (error_state)
                 break;
@@ -1808,41 +1822,41 @@
   return retval;
 }
 
-DEFUN_DLD (num2cell, args, ,
+DEFUN (num2cell, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{C} =} num2cell (@var{A})\n\
-@deftypefnx {Loadable Function} {@var{C} =} num2cell (@var{A}, @var{dim})\n\
+@deftypefn  {Built-in Function} {@var{C} =} num2cell (@var{A})\n\
+@deftypefnx {Built-in Function} {@var{C} =} num2cell (@var{A}, @var{dim})\n\
 Convert the numeric matrix @var{A} to a cell array.  If @var{dim} is\n\
 defined, the value @var{C} is of dimension 1 in this dimension and the\n\
 elements of @var{A} are placed into @var{C} in slices.  For example:\n\
 \n\
 @example\n\
 @group\n\
-num2cell([1,2;3,4])\n\
-     @result{} ans =\n\
-        @{\n\
-          [1,1] =  1\n\
-          [2,1] =  3\n\
-          [1,2] =  2\n\
-          [2,2] =  4\n\
-        @}\n\
-num2cell([1,2;3,4],1)\n\
-     @result{} ans =\n\
-        @{\n\
-          [1,1] =\n\
-             1\n\
-             3\n\
-          [1,2] =\n\
-             2\n\
-             4\n\
-        @}\n\
+num2cell ([1,2;3,4])\n\
+   @result{}\n\
+      @{\n\
+        [1,1] =  1\n\
+        [2,1] =  3\n\
+        [1,2] =  2\n\
+        [2,2] =  4\n\
+      @}\n\
+num2cell ([1,2;3,4],1)\n\
+   @result{}\n\
+      @{\n\
+        [1,1] =\n\
+           1\n\
+           3\n\
+        [1,2] =\n\
+           2\n\
+           4\n\
+      @}\n\
 @end group\n\
 @end example\n\
 \n\
 @seealso{mat2cell}\n\
 @end deftypefn")
 {
-  int nargin =  args.length();
+  int nargin =  args.length ();
   octave_value retval;
 
   if (nargin < 1 || nargin > 2)
@@ -1912,11 +1926,9 @@
 }
 
 /*
-
-%!assert(num2cell([1,2;3,4]),{1,2;3,4})
-%!assert(num2cell([1,2;3,4],1),{[1;3],[2;4]})
-%!assert(num2cell([1,2;3,4],2),{[1,2];[3,4]})
-
+%!assert (num2cell ([1,2;3,4]), {1,2;3,4})
+%!assert (num2cell ([1,2;3,4], 1), {[1;3],[2;4]})
+%!assert (num2cell ([1,2;3,4], 2), {[1,2];[3,4]})
 */
 
 static bool
@@ -2139,11 +2151,11 @@
   return retval;
 }
 
-DEFUN_DLD (mat2cell, args, ,
+DEFUN (mat2cell, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{C} =} mat2cell (@var{A}, @var{m}, @var{n})\n\
-@deftypefnx {Loadable Function} {@var{C} =} mat2cell (@var{A}, @var{d1}, @var{d2}, @dots{})\n\
-@deftypefnx {Loadable Function} {@var{C} =} mat2cell (@var{A}, @var{r})\n\
+@deftypefn  {Built-in Function} {@var{C} =} mat2cell (@var{A}, @var{m}, @var{n})\n\
+@deftypefnx {Built-in Function} {@var{C} =} mat2cell (@var{A}, @var{d1}, @var{d2}, @dots{})\n\
+@deftypefnx {Built-in Function} {@var{C} =} mat2cell (@var{A}, @var{r})\n\
 Convert the matrix @var{A} to a cell array.  If @var{A} is 2-D, then\n\
 it is required that @code{sum (@var{m}) == size (@var{A}, 1)} and\n\
 @code{sum (@var{n}) == size (@var{A}, 2)}.  Similarly, if @var{A} is\n\
@@ -2157,31 +2169,32 @@
 An example of the use of mat2cell is\n\
 \n\
 @example\n\
-mat2cell (reshape(1:16,4,4),[3,1],[3,1])\n\
-@result{} @{\n\
-  [1,1] =\n\
+mat2cell (reshape (1:16,4,4), [3,1], [3,1])\n\
+@result{}\n\
+@{\n\
+   [1,1] =\n\
 \n\
-     1   5   9\n\
-     2   6  10\n\
-     3   7  11\n\
-\n\
-  [2,1] =\n\
+      1   5   9\n\
+      2   6  10\n\
+      3   7  11\n\
 \n\
-     4   8  12\n\
+   [2,1] =\n\
 \n\
-  [1,2] =\n\
+      4   8  12\n\
+\n\
+   [1,2] =\n\
 \n\
-    13\n\
-    14\n\
-    15\n\
+     13\n\
+     14\n\
+     15\n\
 \n\
-  [2,2] = 16\n\
+   [2,2] = 16\n\
 @}\n\
 @end example\n\
 @seealso{num2cell, cell2mat}\n\
 @end deftypefn")
 {
-  int nargin = args.length();
+  int nargin = args.length ();
   octave_value retval;
 
   if (nargin < 2)
@@ -2259,18 +2272,16 @@
 }
 
 /*
+%!test
+%! x = reshape (1:20, 5, 4);
+%! c = mat2cell (x, [3,2], [3,1]);
+%! assert (c, {[1,6,11;2,7,12;3,8,13],[16;17;18];[4,9,14;5,10,15],[19;20]});
 
 %!test
-%! x = reshape(1:20,5,4);
-%! c = mat2cell(x,[3,2],[3,1]);
-%! assert(c,{[1,6,11;2,7,12;3,8,13],[16;17;18];[4,9,14;5,10,15],[19;20]})
-
-%!test
-%! x = 'abcdefghij';
-%! c = mat2cell(x,1,[0,4,2,0,4,0]);
-%! empty1by0str = resize('',1,0);
-%! assert(c,{empty1by0str,'abcd','ef',empty1by0str,'ghij',empty1by0str})
-
+%! x = "abcdefghij";
+%! c = mat2cell (x, 1, [0,4,2,0,4,0]);
+%! empty1by0str = resize ("", 1, 0);
+%! assert (c, {empty1by0str,"abcd","ef",empty1by0str,"ghij",empty1by0str});
 */
 
 // FIXME: it would be nice to allow ranges being handled without a conversion.
@@ -2310,9 +2321,9 @@
   return retval;
 }
 
-DEFUN_DLD (cellslices, args, ,
+DEFUN (cellslices, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{sl} =} cellslices (@var{x}, @var{lb}, @var{ub}, @var{dim})\n\
+@deftypefn {Built-in Function} {@var{sl} =} cellslices (@var{x}, @var{lb}, @var{ub}, @var{dim})\n\
 Given an array @var{x}, this function produces a cell array of slices from\n\
 the array determined by the index vectors @var{lb}, @var{ub}, for lower and\n\
 upper bounds, respectively.  In other words, it is equivalent to the\n\
@@ -2431,17 +2442,17 @@
 %! assert (c, {[1, 2; 5, 6; 9, 10], [2, 3; 6, 7; 10, 11]});
 */
 
-DEFUN_DLD (cellindexmat, args, ,
+DEFUN (cellindexmat, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{y} =} cellindexmat (@var{x}, @var{varargin})\n\
+@deftypefn {Built-in Function} {@var{y} =} cellindexmat (@var{x}, @var{varargin})\n\
 Given a cell array of matrices @var{x}, this function computes\n\
 \n\
 @example\n\
 @group\n\
-  Y = cell (size (X));\n\
-  for i = 1:numel (X)\n\
-    Y@{i@} = X@{i@}(varargin@{:@});\n\
-  endfor\n\
+Y = cell (size (X));\n\
+for i = 1:numel (X)\n\
+  Y@{i@} = X@{i@}(varargin@{:@});\n\
+endfor\n\
 @end group\n\
 @end example\n\
 @seealso{cellslices, cellfun}\n\
rename from src/DLD-FUNCTIONS/colloc.cc
rename to libinterp/corefcn/colloc.cc
--- a/src/DLD-FUNCTIONS/colloc.cc
+++ b/libinterp/corefcn/colloc.cc
@@ -29,14 +29,14 @@
 #include "CollocWt.h"
 #include "lo-mappers.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "oct-obj.h"
 #include "utils.h"
 
-DEFUN_DLD (colloc, args, ,
+DEFUN (colloc, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {[@var{r}, @var{amat}, @var{bmat}, @var{q}] =} colloc (@var{n}, \"left\", \"right\")\n\
+@deftypefn {Built-in Function} {[@var{r}, @var{amat}, @var{bmat}, @var{q}] =} colloc (@var{n}, \"left\", \"right\")\n\
 Compute derivative and integral weight matrices for orthogonal\n\
 collocation using the subroutines given in J. Villadsen and\n\
 M. L. Michelsen, @cite{Solution of Differential Equation Models by\n\
rename from src/DLD-FUNCTIONS/conv2.cc
rename to libinterp/corefcn/conv2.cc
--- a/src/DLD-FUNCTIONS/conv2.cc
+++ b/libinterp/corefcn/conv2.cc
@@ -27,18 +27,18 @@
 
 #include "oct-convn.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "oct-obj.h"
 #include "utils.h"
 
 enum Shape { SHAPE_FULL, SHAPE_SAME, SHAPE_VALID };
 
-DEFUN_DLD (conv2, args, ,
+DEFUN (conv2, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} conv2 (@var{A}, @var{B})\n\
-@deftypefnx {Loadable Function} {} conv2 (@var{v1}, @var{v2}, @var{m})\n\
-@deftypefnx {Loadable Function} {} conv2 (@dots{}, @var{shape})\n\
+@deftypefn  {Built-in Function} {} conv2 (@var{A}, @var{B})\n\
+@deftypefnx {Built-in Function} {} conv2 (@var{v1}, @var{v2}, @var{m})\n\
+@deftypefnx {Built-in Function} {} conv2 (@dots{}, @var{shape})\n\
 Return the 2-D convolution of @var{A} and @var{B}.  The size of the result\n\
 is determined by the optional @var{shape} argument which takes the following\n\
 values\n\
@@ -88,6 +88,12 @@
       shape = args(3).string_value ();
     }
 
+  if (args(0).ndims () > 2 || args(1).ndims () > 2)
+    {
+      error ("conv2: A and B must be 1-D vectors or 2-D matrices");
+      return retval;
+    }
+
   if (shape == "full")
     ct = convn_full;
   else if (shape == "same")
@@ -101,125 +107,125 @@
       return retval;
     }
 
-   if (separable)
-     {
-      // If user requests separable, check first two params are vectors
+  if (separable)
+    {
+     // If user requests separable, check first two params are vectors
 
-       if (! (1 == args(0).rows () || 1 == args(0).columns ())
-           || ! (1 == args(1).rows () || 1 == args(1).columns ()))
-         {
-           print_usage ();
-           return retval;
-         }
+      if (! (1 == args(0).rows () || 1 == args(0).columns ())
+          || ! (1 == args(1).rows () || 1 == args(1).columns ()))
+        {
+          print_usage ();
+          return retval;
+        }
 
-       if (args(0).is_single_type () || args(1).is_single_type ()
-           || args(2).is_single_type ())
-         {
-           if (args(0).is_complex_type () || args(1).is_complex_type ()
-               || args(2).is_complex_type ())
-             {
-               FloatComplexMatrix a (args(2).float_complex_matrix_value ());
-               if (args(1).is_real_type () && args(2).is_real_type ())
-                 {
-                   FloatColumnVector v1 (args(0).float_vector_value ());
-                   FloatRowVector v2 (args(1).float_vector_value ());
-                   retval = convn (a, v1, v2, ct);
-                 }
-               else
-                 {
-                   FloatComplexColumnVector v1 (args(0).float_complex_vector_value ());
-                   FloatComplexRowVector v2 (args(1).float_complex_vector_value ());
-                   retval = convn (a, v1, v2, ct);
-                 }
-             }
-           else
-             {
-               FloatColumnVector v1 (args(0).float_vector_value ());
-               FloatRowVector v2 (args(1).float_vector_value ());
-               FloatMatrix a (args(2).float_matrix_value ());
-               retval = convn (a, v1, v2, ct);
-             }
-         }
-       else
-         {
-           if (args(0).is_complex_type () || args(1).is_complex_type ()
-               || args(2).is_complex_type ())
-             {
-               ComplexMatrix a (args(2).complex_matrix_value ());
-               if (args(1).is_real_type () && args(2).is_real_type ())
-                 {
-                   ColumnVector v1 (args(0).vector_value ());
-                   RowVector v2 (args(1).vector_value ());
-                   retval = convn (a, v1, v2, ct);
-                 }
-               else
-                 {
-                   ComplexColumnVector v1 (args(0).complex_vector_value ());
-                   ComplexRowVector v2 (args(1).complex_vector_value ());
-                   retval = convn (a, v1, v2, ct);
-                 }
-             }
-           else
-             {
-               ColumnVector v1 (args(0).vector_value ());
-               RowVector v2 (args(1).vector_value ());
-               Matrix a (args(2).matrix_value ());
-               retval = convn (a, v1, v2, ct);
-             }
-         }
-     } // if (separable)
-   else
-     {
-       if (args(0).is_single_type () || args(1).is_single_type ())
-         {
-           if (args(0).is_complex_type () || args(1).is_complex_type ())
-             {
-               FloatComplexMatrix a (args(0).float_complex_matrix_value ());
-               if (args(1).is_real_type ())
-                 {
-                   FloatMatrix b (args(1).float_matrix_value ());
-                   retval = convn (a, b, ct);
-                 }
-               else
-                 {
-                   FloatComplexMatrix b (args(1).float_complex_matrix_value ());
-                   retval = convn (a, b, ct);
-                 }
-             }
-           else
-             {
-               FloatMatrix a (args(0).float_matrix_value ());
-               FloatMatrix b (args(1).float_matrix_value ());
-               retval = convn (a, b, ct);
-             }
-         }
-       else
-         {
-           if (args(0).is_complex_type () || args(1).is_complex_type ())
-             {
-               ComplexMatrix a (args(0).complex_matrix_value ());
-               if (args(1).is_real_type ())
-                 {
-                   Matrix b (args(1).matrix_value ());
-                   retval = convn (a, b, ct);
-                 }
-               else
-                 {
-                   ComplexMatrix b (args(1).complex_matrix_value ());
-                   retval = convn (a, b, ct);
-                 }
-             }
-           else
-             {
-               Matrix a (args(0).matrix_value ());
-               Matrix b (args(1).matrix_value ());
-               retval = convn (a, b, ct);
-             }
-         }
+      if (args(0).is_single_type () || args(1).is_single_type ()
+          || args(2).is_single_type ())
+        {
+          if (args(0).is_complex_type () || args(1).is_complex_type ()
+              || args(2).is_complex_type ())
+            {
+              FloatComplexMatrix a (args(2).float_complex_matrix_value ());
+              if (args(1).is_real_type () && args(2).is_real_type ())
+                {
+                  FloatColumnVector v1 (args(0).float_vector_value ());
+                  FloatRowVector v2 (args(1).float_vector_value ());
+                  retval = convn (a, v1, v2, ct);
+                }
+              else
+                {
+                  FloatComplexColumnVector v1 (args(0).float_complex_vector_value ());
+                  FloatComplexRowVector v2 (args(1).float_complex_vector_value ());
+                  retval = convn (a, v1, v2, ct);
+                }
+            }
+          else
+            {
+              FloatColumnVector v1 (args(0).float_vector_value ());
+              FloatRowVector v2 (args(1).float_vector_value ());
+              FloatMatrix a (args(2).float_matrix_value ());
+              retval = convn (a, v1, v2, ct);
+            }
+        }
+      else
+        {
+          if (args(0).is_complex_type () || args(1).is_complex_type ()
+              || args(2).is_complex_type ())
+            {
+              ComplexMatrix a (args(2).complex_matrix_value ());
+              if (args(1).is_real_type () && args(2).is_real_type ())
+                {
+                  ColumnVector v1 (args(0).vector_value ());
+                  RowVector v2 (args(1).vector_value ());
+                  retval = convn (a, v1, v2, ct);
+                }
+              else
+                {
+                  ComplexColumnVector v1 (args(0).complex_vector_value ());
+                  ComplexRowVector v2 (args(1).complex_vector_value ());
+                  retval = convn (a, v1, v2, ct);
+                }
+            }
+          else
+            {
+              ColumnVector v1 (args(0).vector_value ());
+              RowVector v2 (args(1).vector_value ());
+              Matrix a (args(2).matrix_value ());
+              retval = convn (a, v1, v2, ct);
+            }
+        }
+    } // if (separable)
+  else
+    {
+      if (args(0).is_single_type () || args(1).is_single_type ())
+        {
+          if (args(0).is_complex_type () || args(1).is_complex_type ())
+            {
+              FloatComplexMatrix a (args(0).float_complex_matrix_value ());
+              if (args(1).is_real_type ())
+                {
+                  FloatMatrix b (args(1).float_matrix_value ());
+                  retval = convn (a, b, ct);
+                }
+              else
+                {
+                  FloatComplexMatrix b (args(1).float_complex_matrix_value ());
+                  retval = convn (a, b, ct);
+                }
+            }
+          else
+            {
+              FloatMatrix a (args(0).float_matrix_value ());
+              FloatMatrix b (args(1).float_matrix_value ());
+              retval = convn (a, b, ct);
+            }
+        }
+      else
+        {
+          if (args(0).is_complex_type () || args(1).is_complex_type ())
+            {
+              ComplexMatrix a (args(0).complex_matrix_value ());
+              if (args(1).is_real_type ())
+                {
+                  Matrix b (args(1).matrix_value ());
+                  retval = convn (a, b, ct);
+                }
+              else
+                {
+                  ComplexMatrix b (args(1).complex_matrix_value ());
+                  retval = convn (a, b, ct);
+                }
+            }
+          else
+            {
+              Matrix a (args(0).matrix_value ());
+              Matrix b (args(1).matrix_value ());
+              retval = convn (a, b, ct);
+            }
+        }
 
-     } // if (separable)
+    } // if (separable)
 
-   return retval;
+  return retval;
 }
 
 /*
@@ -260,10 +266,10 @@
 %!shared
 
 %% Test cases from Bug #34893
-%!assert (conv2 ([1:5;1:5], [1:2], 'same'), [4 7 10 13 10; 4 7 10 13 10])
-%!assert (conv2 ([1:5;1:5]', [1:2]', 'same'), [4 7 10 13 10; 4 7 10 13 10]')
-%!assert (conv2 ([1:5;1:5], [1:2], 'valid'), [4 7 10 13; 4 7 10 13])
-%!assert (conv2 ([1:5;1:5]', [1:2]', 'valid'), [4 7 10 13; 4 7 10 13]')
+%!assert (conv2 ([1:5;1:5], [1:2], "same"), [4 7 10 13 10; 4 7 10 13 10])
+%!assert (conv2 ([1:5;1:5]', [1:2]', "same"), [4 7 10 13 10; 4 7 10 13 10]')
+%!assert (conv2 ([1:5;1:5], [1:2], "valid"), [4 7 10 13; 4 7 10 13])
+%!assert (conv2 ([1:5;1:5]', [1:2]', "valid"), [4 7 10 13; 4 7 10 13]')
 
 %!test
 %! rand ("seed", 42);
@@ -277,17 +283,17 @@
 %% Test input validation
 %!error conv2 ()
 %!error conv2 (1)
+%!error <must be 1-D vectors or 2-D matrices> conv2 (ones (2), ones (2,2,2))
 %!error <SHAPE type not valid> conv2 (1,2, "NOT_A_SHAPE")
 %% Test alternate calling form which should be 2 vectors and a matrix
 %!error conv2 (ones (2), 1, 1)
 %!error conv2 (1, ones (2), 1)
-
 */
 
-DEFUN_DLD (convn, args, ,
+DEFUN (convn, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{C} =} convn (@var{A}, @var{B})\n\
-@deftypefnx {Loadable Function} {@var{C} =} convn (@var{A}, @var{B}, @var{shape})\n\
+@deftypefn  {Built-in Function} {@var{C} =} convn (@var{A}, @var{B})\n\
+@deftypefnx {Built-in Function} {@var{C} =} convn (@var{A}, @var{B}, @var{shape})\n\
 Return the n-D convolution of @var{A} and @var{B}.  The size of the result\n\
 is determined by the optional @var{shape} argument which takes the following\n\
 values\n\
@@ -386,7 +392,7 @@
         }
     }
 
-   return retval;
+  return retval;
 }
 
 /*
rename from src/DLD-FUNCTIONS/daspk.cc
rename to libinterp/corefcn/daspk.cc
--- a/src/DLD-FUNCTIONS/daspk.cc
+++ b/libinterp/corefcn/daspk.cc
@@ -31,7 +31,7 @@
 
 #include "DASPK.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -170,9 +170,9 @@
     } \
   while (0)
 
-DEFUN_DLD (daspk, args, nargout,
+DEFUN (daspk, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {[@var{x}, @var{xdot}, @var{istate}, @var{msg}] =} daspk (@var{fcn}, @var{x_0}, @var{xdot_0}, @var{t}, @var{t_crit})\n\
+@deftypefn {Built-in Function} {[@var{x}, @var{xdot}, @var{istate}, @var{msg}] =} daspk (@var{fcn}, @var{x_0}, @var{xdot_0}, @var{t}, @var{t_crit})\n\
 Solve the set of differential-algebraic equations\n\
 @tex\n\
 $$ 0 = f (x, \\dot{x}, t) $$\n\
@@ -297,9 +297,9 @@
       if (f_arg.is_cell ())
         {
           Cell c = f_arg.cell_value ();
-          if (c.length() == 1)
+          if (c.length () == 1)
             f_arg = c(0);
-          else if (c.length() == 2)
+          else if (c.length () == 2)
             {
               if (c(0).is_function_handle () || c(0).is_inline_function ())
                 daspk_fcn = c(0).function_value ();
@@ -321,14 +321,14 @@
                     {
                       jac_name = unique_symbol_name ("__daspk_jac__");
                       jname = "function jac = ";
-                      jname.append(jac_name);
+                      jname.append (jac_name);
                       jname.append (" (x, xdot, t, cj) jac = ");
                       daspk_jac = extract_function
                         (c(1), "daspk", jac_name, jname, "; endfunction");
 
                       if (!daspk_jac)
                         {
-                          if (fcn_name.length())
+                          if (fcn_name.length ())
                             clear_function (fcn_name);
                           daspk_fcn = 0;
                         }
@@ -339,7 +339,7 @@
             DASPK_ABORT1 ("incorrect number of elements in cell array");
         }
 
-      if (!daspk_fcn && ! f_arg.is_cell())
+      if (!daspk_fcn && ! f_arg.is_cell ())
         {
           if (f_arg.is_function_handle () || f_arg.is_inline_function ())
             daspk_fcn = f_arg.function_value ();
@@ -377,7 +377,7 @@
                           {
                             jac_name = unique_symbol_name ("__daspk_jac__");
                             jname = "function jac = ";
-                            jname.append(jac_name);
+                            jname.append (jac_name);
                             jname.append (" (x, xdot, t, cj) jac = ");
                             daspk_jac = extract_function
                               (tmp(1), "daspk", jac_name, jname,
@@ -385,7 +385,7 @@
 
                             if (!daspk_jac)
                               {
-                                if (fcn_name.length())
+                                if (fcn_name.length ())
                                   clear_function (fcn_name);
                                 daspk_fcn = 0;
                               }
@@ -446,9 +446,9 @@
       else
         output = dae.integrate (out_times, deriv_output);
 
-      if (fcn_name.length())
+      if (fcn_name.length ())
         clear_function (fcn_name);
-      if (jac_name.length())
+      if (jac_name.length ())
         clear_function (jac_name);
 
       if (! error_state)
rename from src/DLD-FUNCTIONS/dasrt.cc
rename to libinterp/corefcn/dasrt.cc
--- a/src/DLD-FUNCTIONS/dasrt.cc
+++ b/libinterp/corefcn/dasrt.cc
@@ -30,7 +30,7 @@
 #include "DASRT.h"
 #include "lo-mappers.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -206,12 +206,12 @@
     } \
   while (0)
 
-DEFUN_DLD (dasrt, args, nargout,
+DEFUN (dasrt, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {[@var{x}, @var{xdot}, @var{t_out}, @var{istat}, @var{msg}] =} dasrt (@var{fcn}, [], @var{x_0}, @var{xdot_0}, @var{t})\n\
-@deftypefnx {Loadable Function} {@dots{} =} dasrt (@var{fcn}, @var{g}, @var{x_0}, @var{xdot_0}, @var{t})\n\
-@deftypefnx {Loadable Function} {@dots{} =} dasrt (@var{fcn}, [], @var{x_0}, @var{xdot_0}, @var{t}, @var{t_crit})\n\
-@deftypefnx {Loadable Function} {@dots{} =} dasrt (@var{fcn}, @var{g}, @var{x_0}, @var{xdot_0}, @var{t}, @var{t_crit})\n\
+@deftypefn  {Built-in Function} {[@var{x}, @var{xdot}, @var{t_out}, @var{istat}, @var{msg}] =} dasrt (@var{fcn}, [], @var{x_0}, @var{xdot_0}, @var{t})\n\
+@deftypefnx {Built-in Function} {@dots{} =} dasrt (@var{fcn}, @var{g}, @var{x_0}, @var{xdot_0}, @var{t})\n\
+@deftypefnx {Built-in Function} {@dots{} =} dasrt (@var{fcn}, [], @var{x_0}, @var{xdot_0}, @var{t}, @var{t_crit})\n\
+@deftypefnx {Built-in Function} {@dots{} =} dasrt (@var{fcn}, @var{g}, @var{x_0}, @var{xdot_0}, @var{t}, @var{t_crit})\n\
 Solve the set of differential-algebraic equations\n\
 @tex\n\
 $$ 0 = f (x, \\dot{x}, t) $$\n\
@@ -385,9 +385,9 @@
   if (f_arg.is_cell ())
     {
       Cell c = f_arg.cell_value ();
-      if (c.length() == 1)
+      if (c.length () == 1)
         f_arg = c(0);
-      else if (c.length() == 2)
+      else if (c.length () == 2)
         {
           if (c(0).is_function_handle () || c(0).is_inline_function ())
             dasrt_f = c(0).function_value ();
@@ -409,14 +409,14 @@
                 {
                   jac_name = unique_symbol_name ("__dasrt_jac__");
                   jname = "function jac = ";
-                  jname.append(jac_name);
+                  jname.append (jac_name);
                   jname.append (" (x, xdot, t, cj) jac = ");
                   dasrt_j = extract_function
                     (c(1), "dasrt", jac_name, jname, "; endfunction");
 
                   if (!dasrt_j)
                     {
-                      if (fcn_name.length())
+                      if (fcn_name.length ())
                         clear_function (fcn_name);
                       dasrt_f = 0;
                     }
@@ -427,7 +427,7 @@
         DASRT_ABORT1 ("incorrect number of elements in cell array");
     }
 
-  if (!dasrt_f && ! f_arg.is_cell())
+  if (!dasrt_f && ! f_arg.is_cell ())
     {
       if (f_arg.is_function_handle () || f_arg.is_inline_function ())
         dasrt_f = f_arg.function_value ();
@@ -461,7 +461,7 @@
                       {
                         jac_name = unique_symbol_name ("__dasrt_jac__");
                         jname = "function jac = ";
-                        jname.append(jac_name);
+                        jname.append (jac_name);
                         jname.append (" (x, xdot, t, cj) jac = ");
                         dasrt_j = extract_function
                           (tmp(1), "dasrt", jac_name, jname, "; endfunction");
@@ -487,9 +487,9 @@
 
   argp++;
 
-  if (args(1).is_function_handle() || args(1).is_inline_function())
+  if (args(1).is_function_handle () || args(1).is_inline_function ())
     {
-      dasrt_cf = args(1).function_value();
+      dasrt_cf = args(1).function_value ();
 
       if (! dasrt_cf)
         DASRT_ABORT1 ("expecting function name as argument 2");
@@ -557,9 +557,9 @@
   else
     output = dae.integrate (out_times);
 
-  if (fcn_name.length())
+  if (fcn_name.length ())
     clear_function (fcn_name);
-  if (jac_name.length())
+  if (jac_name.length ())
     clear_function (jac_name);
 
   if (! error_state)
rename from src/DLD-FUNCTIONS/dassl.cc
rename to libinterp/corefcn/dassl.cc
--- a/src/DLD-FUNCTIONS/dassl.cc
+++ b/libinterp/corefcn/dassl.cc
@@ -31,7 +31,7 @@
 
 #include "DASSL.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -170,9 +170,9 @@
     } \
   while (0)
 
-DEFUN_DLD (dassl, args, nargout,
+DEFUN (dassl, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {[@var{x}, @var{xdot}, @var{istate}, @var{msg}] =} dassl (@var{fcn}, @var{x_0}, @var{xdot_0}, @var{t}, @var{t_crit})\n\
+@deftypefn {Built-in Function} {[@var{x}, @var{xdot}, @var{istate}, @var{msg}] =} dassl (@var{fcn}, @var{x_0}, @var{xdot_0}, @var{t}, @var{t_crit})\n\
 Solve the set of differential-algebraic equations\n\
 @tex\n\
 $$ 0 = f (x, \\dot{x}, t) $$\n\
@@ -298,9 +298,9 @@
       if (f_arg.is_cell ())
         {
           Cell c = f_arg.cell_value ();
-          if (c.length() == 1)
+          if (c.length () == 1)
             f_arg = c(0);
-          else if (c.length() == 2)
+          else if (c.length () == 2)
             {
               if (c(0).is_function_handle () || c(0).is_inline_function ())
                 dassl_fcn = c(0).function_value ();
@@ -322,14 +322,14 @@
                     {
                         jac_name = unique_symbol_name ("__dassl_jac__");
                         jname = "function jac = ";
-                        jname.append(jac_name);
+                        jname.append (jac_name);
                         jname.append (" (x, xdot, t, cj) jac = ");
                         dassl_jac = extract_function
                           (c(1), "dassl", jac_name, jname, "; endfunction");
 
                         if (!dassl_jac)
                           {
-                            if (fcn_name.length())
+                            if (fcn_name.length ())
                               clear_function (fcn_name);
                             dassl_fcn = 0;
                           }
@@ -340,7 +340,7 @@
             DASSL_ABORT1 ("incorrect number of elements in cell array");
         }
 
-      if (!dassl_fcn && ! f_arg.is_cell())
+      if (!dassl_fcn && ! f_arg.is_cell ())
         {
           if (f_arg.is_function_handle () || f_arg.is_inline_function ())
             dassl_fcn = f_arg.function_value ();
@@ -378,7 +378,7 @@
                           {
                             jac_name = unique_symbol_name ("__dassl_jac__");
                             jname = "function jac = ";
-                            jname.append(jac_name);
+                            jname.append (jac_name);
                             jname.append (" (x, xdot, t, cj) jac = ");
                             dassl_jac = extract_function
                               (tmp(1), "dassl", jac_name, jname,
@@ -386,7 +386,7 @@
 
                             if (!dassl_jac)
                               {
-                                if (fcn_name.length())
+                                if (fcn_name.length ())
                                   clear_function (fcn_name);
                                 dassl_fcn = 0;
                               }
@@ -448,9 +448,9 @@
       else
         output = dae.integrate (out_times, deriv_output);
 
-      if (fcn_name.length())
+      if (fcn_name.length ())
         clear_function (fcn_name);
-      if (jac_name.length())
+      if (jac_name.length ())
         clear_function (jac_name);
 
       if (! error_state)
@@ -482,25 +482,24 @@
 }
 
 /*
-
-%% dassl-1.m
-%%
-%% Test dassl() function
-%%
-%% Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
-%%         Comalco Research and Technology
-%%         20 May 1998
-%%
-%% Problem
-%%
-%%    y1' = -y2,   y1(0) = 1
-%%    y2' =  y1,   y2(0) = 0
-%%
-%% Solution
-%%
-%%    y1(t) = cos(t)
-%%    y2(t) = sin(t)
-
+## dassl-1.m
+##
+## Test dassl() function
+##
+## Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
+##         Comalco Research and Technology
+##         20 May 1998
+##
+## Problem
+##
+##    y1' = -y2,   y1(0) = 1
+##    y2' =  y1,   y2(0) = 0
+##
+## Solution
+##
+##    y1(t) = cos(t)
+##    y2(t) = sin(t)
+##
 %!function res = __f (x, xdot, t)
 %!  res = [xdot(1)+x(2); xdot(2)-x(1)];
 %!endfunction
@@ -513,34 +512,33 @@
 %!
 %! tol = 100 * dassl_options ("relative tolerance");
 %!
-%!
 %! [x, xdot] = dassl ("__f", x0, xdot0, t);
 %!
 %! y = [cos(t), sin(t)];
 %!
-%! assert(all (all (abs (x - y) < tol)));
+%! assert (x, y, tol);
 
-%% dassl-2.m
-%%
-%% Test dassl() function
-%%
-%% Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
-%%         Comalco Research and Technology
-%%         20 May 1998
-%%
-%% Based on SLATEC quick check for DASSL by Linda Petzold
-%%
-%% Problem
-%%
-%%   x1' + 10*x1 = 0,   x1(0) = 1
-%%   x1  + x2    = 1,   x2(0) = 0
-%%
-%%
-%% Solution
-%%
-%%  x1(t) = exp(-10*t)
-%%  x2(t) = 1 - x(1)
-
+## dassl-2.m
+##
+## Test dassl() function
+##
+## Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
+##         Comalco Research and Technology
+##         20 May 1998
+##
+## Based on SLATEC quick check for DASSL by Linda Petzold
+##
+## Problem
+##
+##   x1' + 10*x1 = 0,   x1(0) = 1
+##   x1  + x2    = 1,   x2(0) = 0
+##
+##
+## Solution
+##
+##  x1(t) = exp(-10*t)
+##  x2(t) = 1 - x(1)
+##
 %!function res = __f (x, xdot, t)
 %!  res = [xdot(1)+10*x(1); x(1)+x(2)-1];
 %!endfunction
@@ -553,17 +551,15 @@
 %!
 %! tol = 500 * dassl_options ("relative tolerance");
 %!
-%!
 %! [x, xdot] = dassl ("__f", x0, xdot0, t);
 %!
 %! y = [exp(-10*t), 1-exp(-10*t)];
 %!
-%! assert(all (all (abs (x - y) < tol)));
+%! assert (x, y, tol);
 
 %!test
 %! dassl_options ("absolute tolerance", eps);
-%! assert(dassl_options ("absolute tolerance") == eps);
+%! assert (dassl_options ("absolute tolerance") == eps);
 
-%!error <Invalid call to dassl_options> dassl_options ("foo", 1, 2);
-
+%!error dassl_options ("foo", 1, 2)
 */
rename from src/DLD-FUNCTIONS/det.cc
rename to libinterp/corefcn/det.cc
--- a/src/DLD-FUNCTIONS/det.cc
+++ b/libinterp/corefcn/det.cc
@@ -26,7 +26,7 @@
 
 #include "DET.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -47,10 +47,10 @@
   const CLASS *VAR = arg.type_id () == CLASS::static_type_id () ? \
    dynamic_cast<const CLASS *> (&arg.get_rep ()) : 0
 
-DEFUN_DLD (det, args, nargout,
+DEFUN (det, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} det (@var{A})\n\
-@deftypefnx {Loadable Function} {[@var{d}, @var{rcond}] =} det (@var{A})\n\
+@deftypefn  {Built-in Function} {} det (@var{A})\n\
+@deftypefnx {Built-in Function} {[@var{d}, @var{rcond}] =} det (@var{A})\n\
 Compute the determinant of @var{A}.\n\
 \n\
 Return an estimate of the reciprocal condition number if requested.\n\
@@ -245,11 +245,9 @@
 }
 
 /*
-
-%!assert(det ([1, 2; 3, 4]), -2, 10 * eps);
-%!assert(det (single([1, 2; 3, 4])), single(-2), 10 * eps ('single'));
-%!error <Invalid call to det> det ();
-%!error <Invalid call to det> det (1, 2);
-%!error det ([1, 2; 3, 4; 5, 6]);
-
+%!assert (det ([1, 2; 3, 4]), -2, 10*eps)
+%!assert (det (single ([1, 2; 3, 4])), single (-2), 10*eps ("single"))
+%!error det ()
+%!error det (1, 2)
+%!error <argument must be a square matrix> det ([1, 2; 3, 4; 5, 6])
 */
rename from src/DLD-FUNCTIONS/dlmread.cc
rename to libinterp/corefcn/dlmread.cc
--- a/src/DLD-FUNCTIONS/dlmread.cc
+++ b/libinterp/corefcn/dlmread.cc
@@ -35,7 +35,7 @@
 #include "file-ops.h"
 #include "lo-ieee.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "oct-stream.h"
 #include "error.h"
 #include "oct-obj.h"
@@ -155,13 +155,13 @@
   return stat;
 }
 
-DEFUN_DLD (dlmread, args, ,
+DEFUN (dlmread, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{data} =} dlmread (@var{file})\n\
-@deftypefnx {Loadable Function} {@var{data} =} dlmread (@var{file}, @var{sep})\n\
-@deftypefnx {Loadable Function} {@var{data} =} dlmread (@var{file}, @var{sep}, @var{r0}, @var{c0})\n\
-@deftypefnx {Loadable Function} {@var{data} =} dlmread (@var{file}, @var{sep}, @var{range})\n\
-@deftypefnx {Loadable Function} {@var{data} =} dlmread (@dots{}, \"emptyvalue\", @var{EMPTYVAL})\n\
+@deftypefn  {Built-in Function} {@var{data} =} dlmread (@var{file})\n\
+@deftypefnx {Built-in Function} {@var{data} =} dlmread (@var{file}, @var{sep})\n\
+@deftypefnx {Built-in Function} {@var{data} =} dlmread (@var{file}, @var{sep}, @var{r0}, @var{c0})\n\
+@deftypefnx {Built-in Function} {@var{data} =} dlmread (@var{file}, @var{sep}, @var{range})\n\
+@deftypefnx {Built-in Function} {@var{data} =} dlmread (@dots{}, \"emptyvalue\", @var{EMPTYVAL})\n\
 Read the matrix @var{data} from a text file.  If not defined the separator\n\
 between fields is determined from the file itself.  Otherwise the\n\
 separation character is defined by @var{sep}.\n\
@@ -173,7 +173,7 @@
 The @var{range} parameter may be a 4-element vector containing the upper\n\
 left and lower right corner @code{[@var{R0},@var{C0},@var{R1},@var{C1}]}\n\
 where the lowest index value is zero.  Alternatively, a spreadsheet style\n\
-range such as 'A2..Q15' or 'T1:AA5' can be used.  The lowest alphabetical\n\
+range such as \"A2..Q15\" or \"T1:AA5\" can be used.  The lowest alphabetical\n\
 index 'A' refers to the first column.  The lowest row index is 1.\n\
 \n\
 @var{file} should be a file name or file id given by @code{fopen}.  In the\n\
@@ -480,21 +480,20 @@
 }
 
 /*
-
 %!shared file
 %! file = tmpnam ();
 %! fid = fopen (file, "wt");
 %! fwrite (fid, "1, 2, 3\n4, 5, 6\n7, 8, 9\n10, 11, 12");
 %! fclose (fid);
 
-%!assert (dlmread (file), [1, 2, 3; 4, 5, 6; 7, 8, 9;10, 11, 12]);
-%!assert (dlmread (file, ","), [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12]);
-%!assert (dlmread (file, ",", [1, 0, 2, 1]), [4, 5; 7, 8]);
-%!assert (dlmread (file, ",", "B1..C2"), [2, 3; 5, 6]);
-%!assert (dlmread (file, ",", "B1:C2"), [2, 3; 5, 6]);
-%!assert (dlmread (file, ",", "..C2"), [1, 2, 3; 4, 5, 6]);
-%!assert (dlmread (file, ",", 0, 1), [2, 3; 5, 6; 8, 9; 11, 12]);
-%!assert (dlmread (file, ",", "B1.."), [2, 3; 5, 6; 8, 9; 11, 12]);
+%!assert (dlmread (file), [1, 2, 3; 4, 5, 6; 7, 8, 9;10, 11, 12])
+%!assert (dlmread (file, ","), [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12])
+%!assert (dlmread (file, ",", [1, 0, 2, 1]), [4, 5; 7, 8])
+%!assert (dlmread (file, ",", "B1..C2"), [2, 3; 5, 6])
+%!assert (dlmread (file, ",", "B1:C2"), [2, 3; 5, 6])
+%!assert (dlmread (file, ",", "..C2"), [1, 2, 3; 4, 5, 6])
+%!assert (dlmread (file, ",", 0, 1), [2, 3; 5, 6; 8, 9; 11, 12])
+%!assert (dlmread (file, ",", "B1.."), [2, 3; 5, 6; 8, 9; 11, 12])
 %!error (dlmread (file, ",", [0 1]))
 
 %!test
@@ -506,17 +505,16 @@
 %! fwrite (fid, "1, 2, 3\n4+4i, 5, 6\n7, 8, 9\n10, 11, 12");
 %! fclose (fid);
 
-%!assert (dlmread (file), [1, 2, 3; 4 + 4i, 5, 6; 7, 8, 9; 10, 11, 12]);
-%!assert (dlmread (file, ","), [1, 2, 3; 4 + 4i, 5, 6; 7, 8, 9; 10, 11, 12]);
-%!assert (dlmread (file, ",", [1, 0, 2, 1]), [4 + 4i, 5; 7, 8]);
-%!assert (dlmread (file, ",", "A2..B3"), [4 + 4i, 5; 7, 8]);
-%!assert (dlmread (file, ",", "A2:B3"), [4 + 4i, 5; 7, 8]);
-%!assert (dlmread (file, ",", "..B3"), [1, 2; 4 + 4i, 5; 7, 8]);
-%!assert (dlmread (file, ",", 1, 0), [4 + 4i, 5, 6; 7, 8, 9; 10, 11, 12]);
-%!assert (dlmread (file, ",", "A2.."), [4 + 4i, 5, 6; 7, 8, 9; 10, 11, 12]);
+%!assert (dlmread (file), [1, 2, 3; 4 + 4i, 5, 6; 7, 8, 9; 10, 11, 12])
+%!assert (dlmread (file, ","), [1, 2, 3; 4 + 4i, 5, 6; 7, 8, 9; 10, 11, 12])
+%!assert (dlmread (file, ",", [1, 0, 2, 1]), [4 + 4i, 5; 7, 8])
+%!assert (dlmread (file, ",", "A2..B3"), [4 + 4i, 5; 7, 8])
+%!assert (dlmread (file, ",", "A2:B3"), [4 + 4i, 5; 7, 8])
+%!assert (dlmread (file, ",", "..B3"), [1, 2; 4 + 4i, 5; 7, 8])
+%!assert (dlmread (file, ",", 1, 0), [4 + 4i, 5, 6; 7, 8, 9; 10, 11, 12])
+%!assert (dlmread (file, ",", "A2.."), [4 + 4i, 5, 6; 7, 8, 9; 10, 11, 12])
 %!error (dlmread (file, ",", [0 1]))
 
 %!test
 %! unlink (file);
-
 */
rename from src/DLD-FUNCTIONS/dot.cc
rename to libinterp/corefcn/dot.cc
--- a/src/DLD-FUNCTIONS/dot.cc
+++ b/libinterp/corefcn/dot.cc
@@ -27,7 +27,7 @@
 #include "f77-fcn.h"
 #include "mx-base.h"
 #include "error.h"
-#include "defun-dld.h"
+#include "defun.h"
 #include "parse.h"
 
 extern "C"
@@ -103,9 +103,9 @@
     }
 }
 
-DEFUN_DLD (dot, args, ,
+DEFUN (dot, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} dot (@var{x}, @var{y}, @var{dim})\n\
+@deftypefn {Built-in Function} {} dot (@var{x}, @var{y}, @var{dim})\n\
 Compute the dot product of two vectors.  If @var{x} and @var{y}\n\
 are matrices, calculate the dot products along the first\n\
 non-singleton dimension.  If the optional argument @var{dim} is\n\
@@ -215,7 +215,7 @@
                 {
                   // Non-optimized evaluation.
                   octave_value_list tmp;
-                  tmp(1) = args(2);
+                  tmp(1) = dim + 1;
                   tmp(0) = do_binary_op (octave_value::op_el_mul, argx, argy);
                   if (! error_state)
                     {
@@ -237,23 +237,34 @@
 }
 
 /*
-
-%! assert(dot ([1, 2], [2, 3]), 11);
+%!assert (dot ([1, 2], [2, 3]), 8)
 
 %!test
 %! x = [2, 1; 2, 1];
 %! y = [-0.5, 2; 0.5, -2];
-%! assert(dot (x, y), [0 0]);
+%! assert (dot (x, y), [0 0]);
+
+%!test
+%! x = [1+i, 3-i; 1-i, 3-i];
+%! assert (dot (x, x), [4, 20]);
 
 %!test
-%! x = [ 1+i, 3-i; 1-i, 3-i];
-%! assert(dot (x, x), [4, 20]);
+%! x = int8 ([1 2]);
+%! y = int8 ([2 3]);
+%! assert (dot (x, y), 8);
+
+%!test
+%! x = int8 ([1 2; 3 4]);
+%! y = int8 ([5 6; 7 8]);
+%! assert (dot (x, y), [26 44]);
+%! assert (dot (x, y, 2), [17; 53]);
+%! assert (dot (x, y, 3), [5 12; 21 32]);
 
 */
 
-DEFUN_DLD (blkmm, args, ,
+DEFUN (blkmm, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} blkmm (@var{A}, @var{B})\n\
+@deftypefn {Built-in Function} {} blkmm (@var{A}, @var{B})\n\
 Compute products of matrix blocks.  The blocks are given as\n\
 2-dimensional subarrays of the arrays @var{A}, @var{B}.\n\
 The size of @var{A} must have the form @code{[m,k,@dots{}]} and\n\
@@ -262,9 +273,9 @@
 \n\
 @example\n\
 @group\n\
-  for i = 1:prod (size (@var{A})(3:end))\n\
-    @var{C}(:,:,i) = @var{A}(:,:,i) * @var{B}(:,:,i)\n\
-  endfor\n\
+for i = 1:prod (size (@var{A})(3:end))\n\
+  @var{C}(:,:,i) = @var{A}(:,:,i) * @var{B}(:,:,i)\n\
+endfor\n\
 @end group\n\
 @end example\n\
 @end deftypefn")
@@ -357,12 +368,10 @@
 }
 
 /*
-
 %!test
 %! x(:,:,1) = [1 2; 3 4];
 %! x(:,:,2) = [1 1; 1 1];
 %! z(:,:,1) = [7 10; 15 22];
 %! z(:,:,2) = [2 2; 2 2];
-%! assert(blkmm (x,x),z);
-
+%! assert (blkmm (x,x), z);
 */
rename from src/DLD-FUNCTIONS/eig.cc
rename to libinterp/corefcn/eig.cc
--- a/src/DLD-FUNCTIONS/eig.cc
+++ b/libinterp/corefcn/eig.cc
@@ -27,24 +27,24 @@
 #include "EIG.h"
 #include "fEIG.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
 #include "utils.h"
 
-DEFUN_DLD (eig, args, nargout,
+DEFUN (eig, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{lambda} =} eig (@var{A})\n\
-@deftypefnx {Loadable Function} {@var{lambda} =} eig (@var{A}, @var{B})\n\
-@deftypefnx {Loadable Function} {[@var{V}, @var{lambda}] =} eig (@var{A})\n\
-@deftypefnx {Loadable Function} {[@var{V}, @var{lambda}] =} eig (@var{A}, @var{B})\n\
-Compute the eigenvalues and eigenvectors of a matrix.\n\
+@deftypefn  {Built-in Function} {@var{lambda} =} eig (@var{A})\n\
+@deftypefnx {Built-in Function} {@var{lambda} =} eig (@var{A}, @var{B})\n\
+@deftypefnx {Built-in Function} {[@var{V}, @var{lambda}] =} eig (@var{A})\n\
+@deftypefnx {Built-in Function} {[@var{V}, @var{lambda}] =} eig (@var{A}, @var{B})\n\
+Compute the eigenvalues (and optionally the eigenvectors) of a matrix\n\
+or a pair of matrices\n\
 \n\
-Eigenvalues are computed in a several step process which begins with a\n\
-Hessenberg decomposition, followed by a Schur@tie{}decomposition, from which\n\
-the eigenvalues are apparent.  The eigenvectors, when desired, are computed\n\
-by further manipulations of the Schur@tie{}decomposition.\n\
+The algorithm used depends on whether there are one or two input\n\
+matrices, if they are real or complex and if they are symmetric\n\
+(Hermitian if complex) or non-symmetric.\n\
 \n\
 The eigenvalues returned by @code{eig} are not ordered.\n\
 @seealso{eigs, svd}\n\
@@ -93,7 +93,7 @@
       else if (arg_is_empty > 0)
         return octave_value_list (2, Matrix ());
 
-      if (!(arg_b.is_single_type() || arg_b.is_double_type ()))
+      if (!(arg_b.is_single_type () || arg_b.is_double_type ()))
         {
           gripe_wrong_type_arg ("eig", arg_b);
           return retval;
@@ -254,83 +254,81 @@
 }
 
 /*
-
-%!assert(eig ([1, 2; 2, 1]), [-1; 3], sqrt (eps));
+%!assert (eig ([1, 2; 2, 1]), [-1; 3], sqrt (eps))
 
 %!test
 %! [v, d] = eig ([1, 2; 2, 1]);
 %! x = 1 / sqrt (2);
-%! assert(d, [-1, 0; 0, 3], sqrt (eps));
-%! assert(v, [-x, x; x, x], sqrt (eps));
+%! assert (d, [-1, 0; 0, 3], sqrt (eps));
+%! assert (v, [-x, x; x, x], sqrt (eps));
 
-%!assert(eig (single ([1, 2; 2, 1])), single([-1; 3]), sqrt (eps('single')));
+%!assert (eig (single ([1, 2; 2, 1])), single ([-1; 3]), sqrt (eps ("single")))
 
 %!test
-%! [v, d] = eig (single([1, 2; 2, 1]));
-%! x = single(1 / sqrt (2));
-%! assert(d, single([-1, 0; 0, 3]), sqrt (eps('single')));
-%! assert(v, [-x, x; x, x], sqrt (eps('single')));
+%! [v, d] = eig (single ([1, 2; 2, 1]));
+%! x = single (1 / sqrt (2));
+%! assert (d, single ([-1, 0; 0, 3]), sqrt (eps ("single")));
+%! assert (v, [-x, x; x, x], sqrt (eps ("single")));
 
 %!test
-%! A = [1, 2; -1, 1]; B = [3, 3; 1, 2];
+%! A = [1, 2; -1, 1];  B = [3, 3; 1, 2];
 %! [v, d] = eig (A, B);
-%! assert(A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps));
-%! assert(A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps));
+%! assert (A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps));
+%! assert (A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps));
 
 %!test
-%! A = single([1, 2; -1, 1]); B = single([3, 3; 1, 2]);
+%! A = single ([1, 2; -1, 1]);  B = single ([3, 3; 1, 2]);
 %! [v, d] = eig (A, B);
-%! assert(A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps('single')));
-%! assert(A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps('single')));
+%! assert (A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps ("single")));
+%! assert (A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps ("single")));
 
 %!test
-%! A = [1, 2; 2, 1]; B = [3, -2; -2, 3];
+%! A = [1, 2; 2, 1];  B = [3, -2; -2, 3];
 %! [v, d] = eig (A, B);
-%! assert(A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps));
-%! assert(A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps));
+%! assert (A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps));
+%! assert (A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps));
 
 %!test
-%! A = single([1, 2; 2, 1]); B = single([3, -2; -2, 3]);
+%! A = single ([1, 2; 2, 1]);  B = single ([3, -2; -2, 3]);
 %! [v, d] = eig (A, B);
-%! assert(A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps('single')));
-%! assert(A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps('single')));
+%! assert (A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps ("single")));
+%! assert (A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps ("single")));
 
 %!test
-%! A = [1+3i, 2+i; 2-i, 1+3i]; B = [5+9i, 2+i; 2-i, 5+9i];
+%! A = [1+3i, 2+i; 2-i, 1+3i];  B = [5+9i, 2+i; 2-i, 5+9i];
 %! [v, d] = eig (A, B);
-%! assert(A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps));
-%! assert(A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps));
+%! assert (A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps));
+%! assert (A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps));
 
 %!test
-%! A = single([1+3i, 2+i; 2-i, 1+3i]); B = single([5+9i, 2+i; 2-i, 5+9i]);
+%! A = single ([1+3i, 2+i; 2-i, 1+3i]);  B = single ([5+9i, 2+i; 2-i, 5+9i]);
 %! [v, d] = eig (A, B);
-%! assert(A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps('single')));
-%! assert(A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps('single')));
+%! assert (A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps ("single")));
+%! assert (A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps ("single")));
 
 %!test
-%! A = [1+3i, 2+3i; 3-8i, 8+3i]; B = [8+i, 3+i; 4-9i, 3+i];
+%! A = [1+3i, 2+3i; 3-8i, 8+3i];  B = [8+i, 3+i; 4-9i, 3+i];
 %! [v, d] = eig (A, B);
-%! assert(A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps));
-%! assert(A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps));
+%! assert (A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps));
+%! assert (A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps));
 
 %!test
-%! A = single([1+3i, 2+3i; 3-8i, 8+3i]); B = single([8+i, 3+i; 4-9i, 3+i]);
+%! A = single ([1+3i, 2+3i; 3-8i, 8+3i]);  B = single ([8+i, 3+i; 4-9i, 3+i]);
 %! [v, d] = eig (A, B);
-%! assert(A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps('single')));
-%! assert(A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps('single')));
+%! assert (A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps ("single")));
+%! assert (A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps ("single")));
 
 %!test
-%! A = [1, 2; 3, 8]; B = [8, 3; 4, 3];
+%! A = [1, 2; 3, 8];  B = [8, 3; 4, 3];
 %! [v, d] = eig (A, B);
-%! assert(A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps));
-%! assert(A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps));
+%! assert (A * v(:, 1), d(1, 1) * B * v(:, 1), sqrt (eps));
+%! assert (A * v(:, 2), d(2, 2) * B * v(:, 2), sqrt (eps));
 
-%!error <Invalid call to eig> eig ();
-%!error <Invalid call to eig> eig ([1, 2; 3, 4], [4, 3; 2, 1], 1);
-%!error eig ([1, 2; 3, 4], 2);
-%!error eig ([1, 2; 3, 4; 5, 6]);
-%!error eig ("abcd");
-%!error eig ([1 2 ; 2 3], "abcd");
-%!error eig (false, [1 2 ; 2 3]);
-
+%!error eig ()
+%!error eig ([1, 2; 3, 4], [4, 3; 2, 1], 1)
+%!error <EIG requires same size matrices> eig ([1, 2; 3, 4], 2)
+%!error <argument must be a square matrix> eig ([1, 2; 3, 4; 5, 6])
+%!error <wrong type argument> eig ("abcd")
+%!error <wrong type argument> eig ([1 2 ; 2 3], "abcd")
+%!error <wrong type argument> eig (false, [1 2 ; 2 3])
 */
new file mode 100644
--- /dev/null
+++ b/libinterp/corefcn/ellipj.cc
@@ -0,0 +1,946 @@
+/*
+
+Copyright (C) 2001 Leopoldo Cerbaro <redbliss@libero.it>
+
+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"
+#include "lo-ieee.h"
+
+static void
+gripe_ellipj_arg (const char *arg)
+{
+  error ("ellipj: expecting scalar or matrix as %s argument", arg);
+}
+
+static void
+sncndn (double u, double m, double& sn, double& cn, double& dn, double& err)
+{
+  static const int Nmax = 16;
+  double m1, t=0, si_u, co_u, se_u, ta_u, b, c[Nmax], a[Nmax], phi;
+  int n, Nn, ii;
+
+  if (m < 0 || m > 1)
+    {
+      warning ("ellipj: expecting 0 <= m <= 1"); /* -lc- */
+      sn = cn = dn = lo_ieee_nan_value ();
+      return;
+    }
+
+  double sqrt_eps = sqrt (std::numeric_limits<double>::epsilon ());
+  if (m < sqrt_eps)
+    {
+      /*  # For small m, ( Abramowitz and Stegun, Section 16.13 ) */
+      si_u = sin (u);
+      co_u = cos (u);
+      t = 0.25*m*(u - si_u*co_u);
+      sn = si_u - t * co_u;
+      cn = co_u + t * si_u;
+      dn = 1 - 0.5*m*si_u*si_u;
+    }
+  else if ((1 - m) < sqrt_eps)
+    {
+      /*  For m1 = (1-m) small ( Abramowitz and Stegun, Section 16.15 ) */
+      m1 = 1 - m;
+      si_u = sinh (u);
+      co_u = cosh (u);
+      ta_u = tanh (u);
+      se_u = 1/co_u;
+      sn = ta_u + 0.25*m1*(si_u*co_u - u)*se_u*se_u;
+      cn = se_u - 0.25*m1*(si_u*co_u - u)*ta_u*se_u;
+      dn = se_u + 0.25*m1*(si_u*co_u + u)*ta_u*se_u;
+    }
+  else
+    {
+      /*
+      //  Arithmetic-Geometric Mean (AGM) algorithm
+      //    ( Abramowitz and Stegun, Section 16.4 )
+      */
+
+      a[0] = 1;
+      b    = sqrt (1 - m);
+      c[0] = sqrt (m);
+      for (n = 1; n < Nmax; ++n)
+        {
+          a[n] = (a[n - 1] + b)/2;
+          c[n] = (a[n - 1] - b)/2;
+          b = sqrt (a[n - 1]*b);
+          if (c[n]/a[n] < std::numeric_limits<double>::epsilon ()) break;
+        }
+      if (n >= Nmax - 1)
+        {
+          err = 1;
+          return;
+        }
+      Nn = n;
+      for (ii = 1; n > 0; ii = ii*2, --n) ; // ii = pow(2,Nn)
+      phi = ii*a[Nn]*u;
+      for (n = Nn; n > 0; --n)
+        {
+          t = phi;
+          phi = (asin ((c[n]/a[n])* sin (phi)) + phi)/2;
+        }
+      sn = sin (phi);
+      cn = cos (phi);
+      dn = cn/cos (t - phi);
+    }
+}
+
+static void
+sncndn (Complex& u, double m, Complex& sn, Complex& cn, Complex& dn,
+        double& err)
+{
+  double m1 = 1 - m, ss1, cc1, dd1;
+
+  sncndn (imag (u), m1, ss1, cc1, dd1, err);
+  if (real (u) == 0)
+    {
+      /* u is pure imag: Jacoby imag. transf. */
+      sn = Complex (0, ss1/cc1);
+      cn = 1/cc1;         //    cn.imag = 0;
+      dn = dd1/cc1;       //    dn.imag = 0;
+    }
+  else
+    {
+      /* u is generic complex */
+      double ss, cc, dd, ddd;
+
+      sncndn (real (u), m, ss, cc, dd, err);
+      ddd = cc1*cc1 + m*ss*ss*ss1*ss1;
+      sn = Complex (ss*dd1/ddd, cc*dd*ss1*cc1/ddd);
+      cn = Complex (cc*cc1/ddd, -ss*dd*ss1*dd1/ddd);
+      dn = Complex (dd*cc1*dd1/ddd, -m*ss*cc*ss1/ddd);
+    }
+}
+
+DEFUN (ellipj, args, nargout,
+  "-*- texinfo -*-\n\
+@deftypefn  {Built-in Function} {[@var{sn}, @var{cn}, @var{dn}, @var{err}] =} ellipj (@var{u}, @var{m})\n\
+@deftypefnx {Built-in Function} {[@var{sn}, @var{cn}, @var{dn}, @var{err}] =} ellipj (@var{u}, @var{m}, @var{tol})\n\
+Compute the Jacobi elliptic functions @var{sn}, @var{cn}, and @var{dn}\n\
+of complex argument @var{u} and real parameter @var{m}.\n\
+\n\
+If @var{m} is a scalar, the results are the same size as @var{u}.\n\
+If @var{u} is a scalar, the results are the same size as @var{m}.\n\
+If @var{u} is a column vector and @var{m} is a row vector, the\n\
+results are matrices with @code{length (@var{u})} rows and\n\
+@code{length (@var{m})} columns.  Otherwise, @var{u} and\n\
+@var{m} must conform and the results will be the same size.\n\
+\n\
+The value of @var{u} may be complex.\n\
+The value of @var{m} must be 0 <= m <= 1.\n\
+\n\
+@var{tol} is currently ignored (@sc{Matlab} uses this to allow faster,\n\
+less accurate approximation).\n\
+\n\
+If requested, @var{err} contains the following status information\n\
+and is the same size as the result.\n\
+\n\
+@enumerate 0\n\
+@item\n\
+Normal return.\n\
+@item\n\
+Error---no computation, algorithm termination condition not met,\n\
+return @code{NaN}.\n\
+@end enumerate\n\
+ Ref: Abramowitz, Milton and Stegun, Irene A\n\
+      Handbook of Mathematical Functions, Dover, 1965\n\
+      Chapter 16 (Sections 16.4, 16.13 and 16.15)\n\
+@seealso{ellipke}\n\
+@end deftypefn")
+{
+  octave_value_list retval;
+
+  int nargin = args.length ();
+
+  if (nargin < 2 || nargin > 3)
+    {
+      print_usage ();
+      return retval;
+    }
+
+  octave_value u_arg = args(0);
+  octave_value m_arg = args(1);
+
+  if (m_arg.is_scalar_type ())
+    {
+      double m = args(1).double_value ();
+
+      if (error_state)
+        {
+          gripe_ellipj_arg ("second");
+          return retval;
+        }
+
+      if (u_arg.is_scalar_type ())
+        {
+          if (u_arg.is_real_type ())
+            {  // u real
+              double u = args(0).double_value ();
+
+              if (error_state)
+                {
+                  gripe_ellipj_arg ("first");
+                  return retval;
+                }
+              double sn, cn, dn;
+              double err = 0;
+
+              sncndn (u, m, sn, cn, dn, err);
+              retval (0) = sn;
+              retval (1) = cn;
+              retval (2) = dn;
+              if (nargout > 3) retval(3) =  err;
+            }
+          else
+            {  // u complex
+              Complex u = u_arg.complex_value ();
+
+              if (error_state)
+                {
+                  gripe_ellipj_arg ("second");
+                  return retval;
+                }
+
+              Complex sn, cn, dn;
+              double err;
+
+              sncndn (u, m, sn, cn, dn, err);
+
+              retval (0) = sn;
+              retval (1) = cn;
+              retval (2) = dn;
+              if (nargout > 3) retval(3) = err;
+            }
+        }
+      else
+        {  /* u is matrix ( m is scalar ) */
+          ComplexMatrix u = u_arg.complex_matrix_value ();
+
+          if (error_state)
+            {
+              gripe_ellipj_arg ("first");
+              return retval;
+            }
+
+          octave_idx_type nr = u.rows ();
+          octave_idx_type nc = u.cols ();
+
+          ComplexMatrix sn (nr, nc), cn (nr, nc), dn (nr, nc);
+          Matrix err (nr, nc);
+
+          for (octave_idx_type j = 0; j < nc; j++)
+            for (octave_idx_type i = 0; i < nr; i++)
+              sncndn (u(i,j), m, sn(i,j), cn(i,j), dn(i,j), err(i,j));
+
+          retval (0) = sn;
+          retval (1) = cn;
+          retval (2) = dn;
+          if (nargout > 3) retval(3) = err;
+        }
+    }
+  else
+    {
+      Matrix m = args(1).matrix_value ();
+
+      if (error_state)
+        {
+          gripe_ellipj_arg ("second");
+          return retval;
+        }
+
+      octave_idx_type mr = m.rows ();
+      octave_idx_type mc = m.cols ();
+
+      if (u_arg.is_scalar_type ())
+        {    /* u is scalar */
+          octave_idx_type nr = m.rows ();
+          octave_idx_type nc = m.cols ();
+          Matrix err (nr, nc);
+
+          if (u_arg.is_real_type ())
+            {
+              double u = u_arg.double_value ();
+
+              if (error_state)
+                {
+                  gripe_ellipj_arg ("first");
+                  return retval;
+                }
+
+              Matrix sn (nr, nc), cn (nr, nc), dn (nr, nc);
+              for (octave_idx_type j = 0; j < nc; j++)
+                for (octave_idx_type i = 0; i < nr; i++)
+                  sncndn (u, m(i,j), sn(i,j), cn(i,j), dn(i,j), err(i,j));
+
+              retval (0) = sn;
+              retval (1) = cn;
+              retval (2) = dn;
+              if (nargout > 3)  retval(3) = err;
+            }
+          else
+            {
+              Complex u = u_arg.complex_value ();
+              if (error_state)
+                {
+                  gripe_ellipj_arg ("first");
+                  return retval;
+                }
+
+              ComplexMatrix sn (nr, nc), cn (nr, nc), dn (nr, nc);
+              for (octave_idx_type j = 0; j < nc; j++)
+                for (octave_idx_type i = 0; i < nr; i++)
+                  sncndn (u, m(i,j), sn(i,j), cn(i,j), dn(i,j), err(i,j));
+              retval (0) = sn;
+              retval (1) = cn;
+              retval (2) = dn;
+              if (nargout > 3)  retval(3) = err;
+            }
+        }
+      else
+        {    // u is matrix  (m is matrix)
+          if (u_arg.is_real_type ())
+            {  // u real matrix
+
+              Matrix u = u_arg.matrix_value ();
+              if (error_state)
+                {
+                  gripe_ellipj_arg ("first ");
+                  return retval;
+                }
+
+              octave_idx_type ur = u.rows ();
+              octave_idx_type uc = u.cols ();
+
+              if (mr == 1 && uc == 1)
+                {  // u column, m row
+                  RowVector rm = m.row (0);
+                  ColumnVector cu = u.column (0);
+
+                  Matrix sn (ur, mc), cn (ur, mc), dn (ur, mc);
+                  Matrix err (ur,mc);
+
+                  for (octave_idx_type j = 0; j < mc; j++)
+                    for (octave_idx_type i = 0; i < ur; i++)
+                      sncndn (cu(i), rm(j), sn(i,j), cn(i,j), dn(i,j), err(i,j));
+
+                  retval (0) = sn;
+                  retval (1) = cn;
+                  retval (2) = dn;
+                  if (nargout > 3)  retval(3) = err;
+                }
+              else if (ur == mr && uc == mc)
+                {
+                  Matrix sn (ur, mc), cn (ur, mc), dn (ur, mc);
+                  Matrix err (ur,mc);
+
+                  for (octave_idx_type j = 0; j < uc; j++)
+                    for (octave_idx_type i = 0; i < ur; i++)
+                      sncndn (u(i,j), m(i,j), sn(i,j), cn(i,j), dn(i,j), err(i,j));
+
+                  retval (0) = sn;
+                  retval (1) = cn;
+                  retval (2) = dn;
+                  if (nargout > 3)  retval(3) = err;
+                }
+              else
+                error ("u m invalid");
+            }
+          else
+            {  // u complex matrix
+              ComplexMatrix u = u_arg.complex_matrix_value ();
+              if (error_state)
+                {
+                  gripe_ellipj_arg ("second");
+                  return retval;
+                }
+
+              octave_idx_type ur = u.rows ();
+              octave_idx_type uc = u.cols ();
+
+              if (mr == 1 && uc == 1)
+                {
+                  RowVector rm = m.row (0);
+                  ComplexColumnVector cu = u.column (0);
+
+                  ComplexMatrix sn (ur, mc), cn (ur, mc), dn (ur, mc);
+                  Matrix err (ur,mc);
+
+                  for (octave_idx_type j = 0; j < mc; j++)
+                    for (octave_idx_type i = 0; i < ur; i++)
+                      sncndn (cu(i), rm(j), sn(i,j), cn(i,j), dn(i,j), err(i,j));
+
+                  retval (0) = sn;
+                  retval (1) = cn;
+                  retval (2) = dn;
+                  if (nargout > 3)  retval(3) = err;
+                }
+              else if (ur == mr && uc == mc)
+                {
+                  ComplexMatrix sn (ur, mc), cn (ur, mc), dn (ur, mc);
+                  Matrix err (ur,mc);
+
+                  for (octave_idx_type j = 0; j < uc; j++)
+                    for (octave_idx_type i = 0; i < ur; i++)
+                      sncndn (u(i,j), m(i,j), sn(i,j), cn(i,j), dn(i,j), err(i,j));
+
+                  retval (0) = sn;
+                  retval (1) = cn;
+                  retval (2) = dn;
+                  if (nargout > 3)  retval(3) = err;
+                }
+              else
+                error ("u m invalid");
+            }
+        }
+    }  // m matrix
+
+  return retval;
+}
+
+/*
+## demos taken from inst/ellipj.m
+
+%!demo
+%! N = 150;
+%! % m = [1-logspace(0,log(eps),N-1), 1]; ## m near 1
+%! % m = [0, logspace(log(eps),0,N-1)];   ## m near 0
+%!   m = linspace(0,1,N);                 ## m equally spaced
+%! u = linspace(-20,20,N);
+%! M = ones(length(u),1) * m;
+%! U = u' * ones(1, length(m));
+%! [sn, cn, dn] = ellipj(U,M);
+%!
+%! %% Plotting
+%! c = colormap(hot(64));
+%! data = {sn,cn,dn};
+%! dname = {"sn","cn","dn"};
+%! for i=1:3
+%!   subplot(1,3,i);
+%!   data{i}(data{i} > 1) = 1;
+%!   data{i}(data{i} < -1) = -1;
+%!   image(m,u,32*data{i}+32);
+%!   title(dname{i});
+%! end
+%! colormap(c);
+
+%!demo
+%! N = 200;
+%! % m = [1-logspace(0,log(eps),N-1), 1]; ## m near 1
+%! % m = [0, logspace(log(eps),0,N-1)];   ## m near 0
+%!   m = linspace(0,1,N);                 ## m equally spaced
+%! u = linspace(0,20,5);
+%! M = ones(length(u),1) * m;
+%! U = u' * ones(1, length(m));
+%! [sn, cn, dn] = ellipj(U,M);
+%!
+%! %% Plotting
+%! data = {sn,cn,dn};
+%! dname = {"sn","cn","dn"};
+%! for i=1:3
+%!   subplot(1,3,i);
+%!   plot(m, data{i});
+%!   title(dname{i});
+%!   grid on;
+%! end
+*/
+
+/*
+## tests taken from inst/test_sncndn.m
+
+%!test
+%! k = (tan(pi/8.))^2; m = k*k;
+%! SN = [
+%! -1. + I * 0. ,  -0.8392965923 + 0. * I
+%! -1. + I * 0.2 ,  -0.8559363407 + 0.108250955 * I
+%! -1. + I * 0.4 ,  -0.906529758 + 0.2204040232 * I
+%! -1. + I * 0.6 ,  -0.9931306727 + 0.3403783409 * I
+%! -1. + I * 0.8 ,  -1.119268095 + 0.4720784944 * I
+%! -1. + I * 1. ,  -1.29010951 + 0.6192468708 * I
+%! -1. + I * 1.2 ,  -1.512691987 + 0.7850890595 * I
+%! -1. + I * 1.4 ,  -1.796200374 + 0.9714821804 * I
+%! -1. + I * 1.6 ,  -2.152201882 + 1.177446413 * I
+%! -1. + I * 1.8 ,  -2.594547417 + 1.396378892 * I
+%! -1. + I * 2. ,  -3.138145339 + 1.611394819 * I
+%! -0.8 + I * 0. ,  -0.7158157937 + 0. * I
+%! -0.8 + I * 0.2 ,  -0.7301746722 + 0.1394690862 * I
+%! -0.8 + I * 0.4 ,  -0.7738940898 + 0.2841710966 * I
+%! -0.8 + I * 0.6 ,  -0.8489542135 + 0.4394411376 * I
+%! -0.8 + I * 0.8 ,  -0.9588386397 + 0.6107824358 * I
+%! -0.8 + I * 1. ,  -1.108848724 + 0.8038415767 * I
+%! -0.8 + I * 1.2 ,  -1.306629972 + 1.024193359 * I
+%! -0.8 + I * 1.4 ,  -1.563010199 + 1.276740951 * I
+%! -0.8 + I * 1.6 ,  -1.893274688 + 1.564345558 * I
+%! -0.8 + I * 1.8 ,  -2.318944084 + 1.88491973 * I
+%! -0.8 + I * 2. ,  -2.869716809 + 2.225506523 * I
+%! -0.6 + I * 0. ,  -0.5638287208 + 0. * I
+%! -0.6 + I * 0.2 ,  -0.5752723012 + 0.1654722474 * I
+%! -0.6 + I * 0.4 ,  -0.610164314 + 0.3374004736 * I
+%! -0.6 + I * 0.6 ,  -0.6702507087 + 0.5224614298 * I
+%! -0.6 + I * 0.8 ,  -0.7586657365 + 0.7277663879 * I
+%! -0.6 + I * 1. ,  -0.8803349115 + 0.9610513652 * I
+%! -0.6 + I * 1.2 ,  -1.042696526 + 1.230800819 * I
+%! -0.6 + I * 1.4 ,  -1.256964505 + 1.546195843 * I
+%! -0.6 + I * 1.6 ,  -1.540333527 + 1.916612621 * I
+%! -0.6 + I * 1.8 ,  -1.919816065 + 2.349972151 * I
+%! -0.6 + I * 2. ,  -2.438761841 + 2.848129496 * I
+%! -0.4 + I * 0. ,  -0.3891382858 + 0. * I
+%! -0.4 + I * 0.2 ,  -0.3971152026 + 0.1850563793 * I
+%! -0.4 + I * 0.4 ,  -0.4214662882 + 0.3775700801 * I
+%! -0.4 + I * 0.6 ,  -0.4635087491 + 0.5853434119 * I
+%! -0.4 + I * 0.8 ,  -0.5256432877 + 0.8168992398 * I
+%! -0.4 + I * 1. ,  -0.611733177 + 1.081923504 * I
+%! -0.4 + I * 1.2 ,  -0.7278102331 + 1.391822501 * I
+%! -0.4 + I * 1.4 ,  -0.8833807998 + 1.760456461 * I
+%! -0.4 + I * 1.6 ,  -1.093891878 + 2.205107766 * I
+%! -0.4 + I * 1.8 ,  -1.385545188 + 2.747638761 * I
+%! -0.4 + I * 2. ,  -1.805081271 + 3.41525351 * I
+%! -0.2 + I * 0. ,  -0.1986311721 + 0. * I
+%! -0.2 + I * 0.2 ,  -0.2027299916 + 0.1972398665 * I
+%! -0.2 + I * 0.4 ,  -0.2152524522 + 0.402598347 * I
+%! -0.2 + I * 0.6 ,  -0.2369100139 + 0.6246336356 * I
+%! -0.2 + I * 0.8 ,  -0.2690115146 + 0.8728455227 * I
+%! -0.2 + I * 1. ,  -0.3136938773 + 1.158323088 * I
+%! -0.2 + I * 1.2 ,  -0.3743615191 + 1.494672508 * I
+%! -0.2 + I * 1.4 ,  -0.4565255082 + 1.899466033 * I
+%! -0.2 + I * 1.6 ,  -0.5694611346 + 2.39667232 * I
+%! -0.2 + I * 1.8 ,  -0.7296612675 + 3.020990664 * I
+%! -0.2 + I * 2. ,  -0.9685726188 + 3.826022536 * I
+%! 0. + I * 0. ,  0. + 0. * I
+%! 0. + I * 0.2 ,  0. + 0.201376364 * I
+%! 0. + I * 0.4 ,  0. + 0.4111029248 * I
+%! 0. + I * 0.6 ,  0. + 0.6380048435 * I
+%! 0. + I * 0.8 ,  0. + 0.8919321473 * I
+%! 0. + I * 1. ,  0. + 1.184486615 * I
+%! 0. + I * 1.2 ,  0. + 1.530096023 * I
+%! 0. + I * 1.4 ,  0. + 1.947754612 * I
+%! 0. + I * 1.6 ,  0. + 2.464074356 * I
+%! 0. + I * 1.8 ,  0. + 3.119049475 * I
+%! 0. + I * 2. ,  0. + 3.97786237 * I
+%! 0.2 + I * 0. ,  0.1986311721 + 0. * I
+%! 0.2 + I * 0.2 ,  0.2027299916 + 0.1972398665 * I
+%! 0.2 + I * 0.4 ,  0.2152524522 + 0.402598347 * I
+%! 0.2 + I * 0.6 ,  0.2369100139 + 0.6246336356 * I
+%! 0.2 + I * 0.8 ,  0.2690115146 + 0.8728455227 * I
+%! 0.2 + I * 1. ,  0.3136938773 + 1.158323088 * I
+%! 0.2 + I * 1.2 ,  0.3743615191 + 1.494672508 * I
+%! 0.2 + I * 1.4 ,  0.4565255082 + 1.899466033 * I
+%! 0.2 + I * 1.6 ,  0.5694611346 + 2.39667232 * I
+%! 0.2 + I * 1.8 ,  0.7296612675 + 3.020990664 * I
+%! 0.2 + I * 2. ,  0.9685726188 + 3.826022536 * I
+%! 0.4 + I * 0. ,  0.3891382858 + 0. * I
+%! 0.4 + I * 0.2 ,  0.3971152026 + 0.1850563793 * I
+%! 0.4 + I * 0.4 ,  0.4214662882 + 0.3775700801 * I
+%! 0.4 + I * 0.6 ,  0.4635087491 + 0.5853434119 * I
+%! 0.4 + I * 0.8 ,  0.5256432877 + 0.8168992398 * I
+%! 0.4 + I * 1. ,  0.611733177 + 1.081923504 * I
+%! 0.4 + I * 1.2 ,  0.7278102331 + 1.391822501 * I
+%! 0.4 + I * 1.4 ,  0.8833807998 + 1.760456461 * I
+%! 0.4 + I * 1.6 ,  1.093891878 + 2.205107766 * I
+%! 0.4 + I * 1.8 ,  1.385545188 + 2.747638761 * I
+%! 0.4 + I * 2. ,  1.805081271 + 3.41525351 * I
+%! 0.6 + I * 0. ,  0.5638287208 + 0. * I
+%! 0.6 + I * 0.2 ,  0.5752723012 + 0.1654722474 * I
+%! 0.6 + I * 0.4 ,  0.610164314 + 0.3374004736 * I
+%! 0.6 + I * 0.6 ,  0.6702507087 + 0.5224614298 * I
+%! 0.6 + I * 0.8 ,  0.7586657365 + 0.7277663879 * I
+%! 0.6 + I * 1. ,  0.8803349115 + 0.9610513652 * I
+%! 0.6 + I * 1.2 ,  1.042696526 + 1.230800819 * I
+%! 0.6 + I * 1.4 ,  1.256964505 + 1.546195843 * I
+%! 0.6 + I * 1.6 ,  1.540333527 + 1.916612621 * I
+%! 0.6 + I * 1.8 ,  1.919816065 + 2.349972151 * I
+%! 0.6 + I * 2. ,  2.438761841 + 2.848129496 * I
+%! 0.8 + I * 0. ,  0.7158157937 + 0. * I
+%! 0.8 + I * 0.2 ,  0.7301746722 + 0.1394690862 * I
+%! 0.8 + I * 0.4 ,  0.7738940898 + 0.2841710966 * I
+%! 0.8 + I * 0.6 ,  0.8489542135 + 0.4394411376 * I
+%! 0.8 + I * 0.8 ,  0.9588386397 + 0.6107824358 * I
+%! 0.8 + I * 1. ,  1.108848724 + 0.8038415767 * I
+%! 0.8 + I * 1.2 ,  1.306629972 + 1.024193359 * I
+%! 0.8 + I * 1.4 ,  1.563010199 + 1.276740951 * I
+%! 0.8 + I * 1.6 ,  1.893274688 + 1.564345558 * I
+%! 0.8 + I * 1.8 ,  2.318944084 + 1.88491973 * I
+%! 0.8 + I * 2. ,  2.869716809 + 2.225506523 * I
+%! 1. + I * 0. ,  0.8392965923 + 0. * I
+%! 1. + I * 0.2 ,  0.8559363407 + 0.108250955 * I
+%! 1. + I * 0.4 ,  0.906529758 + 0.2204040232 * I
+%! 1. + I * 0.6 ,  0.9931306727 + 0.3403783409 * I
+%! 1. + I * 0.8 ,  1.119268095 + 0.4720784944 * I
+%! 1. + I * 1. ,  1.29010951 + 0.6192468708 * I
+%! 1. + I * 1.2 ,  1.512691987 + 0.7850890595 * I
+%! 1. + I * 1.4 ,  1.796200374 + 0.9714821804 * I
+%! 1. + I * 1.6 ,  2.152201882 + 1.177446413 * I
+%! 1. + I * 1.8 ,  2.594547417 + 1.396378892 * I
+%! 1. + I * 2. ,  3.138145339 + 1.611394819 * I
+%! ];
+%! CN = [
+%! -1. + I * 0. , 0.5436738271 + 0. * I
+%! -1. + I * 0.2 , 0.5541219664 + 0.1672121517 * I
+%! -1. + I * 0.4 , 0.5857703552 + 0.3410940893 * I
+%! -1. + I * 0.6 , 0.6395034233 + 0.5285979063 * I
+%! -1. + I * 0.8 , 0.716688504 + 0.7372552987 * I
+%! -1. + I * 1. , 0.8189576795 + 0.9755037374 * I
+%! -1. + I * 1.2 , 0.9477661951 + 1.253049471 * I
+%! -1. + I * 1.4 , 1.103540657 + 1.581252712 * I
+%! -1. + I * 1.6 , 1.284098214 + 1.973449038 * I
+%! -1. + I * 1.8 , 1.481835651 + 2.4449211 * I
+%! -1. + I * 2. , 1.679032464 + 3.011729224 * I
+%! -0.8 + I * 0. , 0.6982891589 + 0. * I
+%! -0.8 + I * 0.2 , 0.71187169 + 0.1430549855 * I
+%! -0.8 + I * 0.4 , 0.7530744458 + 0.2920273465 * I
+%! -0.8 + I * 0.6 , 0.8232501212 + 0.4531616768 * I
+%! -0.8 + I * 0.8 , 0.9245978896 + 0.6334016187 * I
+%! -0.8 + I * 1. , 1.060030206 + 0.8408616109 * I
+%! -0.8 + I * 1.2 , 1.232861756 + 1.085475913 * I
+%! -0.8 + I * 1.4 , 1.446126965 + 1.379933558 * I
+%! -0.8 + I * 1.6 , 1.701139468 + 1.741030588 * I
+%! -0.8 + I * 1.8 , 1.994526268 + 2.191509596 * I
+%! -0.8 + I * 2. , 2.312257188 + 2.762051518 * I
+%! -0.6 + I * 0. , 0.8258917445 + 0. * I
+%! -0.6 + I * 0.2 , 0.842151698 + 0.1130337928 * I
+%! -0.6 + I * 0.4 , 0.8915487431 + 0.2309124769 * I
+%! -0.6 + I * 0.6 , 0.975948103 + 0.3588102098 * I
+%! -0.6 + I * 0.8 , 1.098499209 + 0.5026234141 * I
+%! -0.6 + I * 1. , 1.263676101 + 0.6695125973 * I
+%! -0.6 + I * 1.2 , 1.477275851 + 0.8687285705 * I
+%! -0.6 + I * 1.4 , 1.746262523 + 1.112955966 * I
+%! -0.6 + I * 1.6 , 2.078179075 + 1.420581466 * I
+%! -0.6 + I * 1.8 , 2.479425208 + 1.819580713 * I
+%! -0.6 + I * 2. , 2.950586798 + 2.354077344 * I
+%! -0.4 + I * 0. , 0.9211793498 + 0. * I
+%! -0.4 + I * 0.2 , 0.9395019377 + 0.07822091534 * I
+%! -0.4 + I * 0.4 , 0.9952345231 + 0.1598950363 * I
+%! -0.4 + I * 0.6 , 1.090715991 + 0.2487465067 * I
+%! -0.4 + I * 0.8 , 1.229998843 + 0.34910407 * I
+%! -0.4 + I * 1. , 1.419103868 + 0.4663848201 * I
+%! -0.4 + I * 1.2 , 1.666426377 + 0.607877235 * I
+%! -0.4 + I * 1.4 , 1.983347336 + 0.7841054404 * I
+%! -0.4 + I * 1.6 , 2.385101684 + 1.01134031 * I
+%! -0.4 + I * 1.8 , 2.89185416 + 1.316448705 * I
+%! -0.4 + I * 2. , 3.529393374 + 1.74670531 * I
+%! -0.2 + I * 0. , 0.9800743122 + 0. * I
+%! -0.2 + I * 0.2 , 0.9997019476 + 0.03999835809 * I
+%! -0.2 + I * 0.4 , 1.059453907 + 0.08179712295 * I
+%! -0.2 + I * 0.6 , 1.16200643 + 0.1273503824 * I
+%! -0.2 + I * 0.8 , 1.312066413 + 0.1789585449 * I
+%! -0.2 + I * 1. , 1.516804331 + 0.2395555269 * I
+%! -0.2 + I * 1.2 , 1.786613221 + 0.313189147 * I
+%! -0.2 + I * 1.4 , 2.136422971 + 0.405890925 * I
+%! -0.2 + I * 1.6 , 2.588021972 + 0.527357091 * I
+%! -0.2 + I * 1.8 , 3.174302819 + 0.6944201617 * I
+%! -0.2 + I * 2. , 3.947361147 + 0.9387994989 * I
+%! 0. + I * 0. , 1. + 0. * I
+%! 0. + I * 0.2 , 1.020074723 + 0. * I
+%! 0. + I * 0.4 , 1.08120563 + 0. * I
+%! 0. + I * 0.6 , 1.18619146 + 0. * I
+%! 0. + I * 0.8 , 1.339978715 + 0. * I
+%! 0. + I * 1. , 1.550164037 + 0. * I
+%! 0. + I * 1.2 , 1.827893279 + 0. * I
+%! 0. + I * 1.4 , 2.189462954 + 0. * I
+%! 0. + I * 1.6 , 2.659259752 + 0. * I
+%! 0. + I * 1.8 , 3.275434266 + 0. * I
+%! 0. + I * 2. , 4.101632484 + 0. * I
+%! 0.2 + I * 0. , 0.9800743122 + 0. * I
+%! 0.2 + I * 0.2 , 0.9997019476 - 0.03999835809 * I
+%! 0.2 + I * 0.4 , 1.059453907 - 0.08179712295 * I
+%! 0.2 + I * 0.6 , 1.16200643 - 0.1273503824 * I
+%! 0.2 + I * 0.8 , 1.312066413 - 0.1789585449 * I
+%! 0.2 + I * 1. , 1.516804331 - 0.2395555269 * I
+%! 0.2 + I * 1.2 , 1.786613221 - 0.313189147 * I
+%! 0.2 + I * 1.4 , 2.136422971 - 0.405890925 * I
+%! 0.2 + I * 1.6 , 2.588021972 - 0.527357091 * I
+%! 0.2 + I * 1.8 , 3.174302819 - 0.6944201617 * I
+%! 0.2 + I * 2. , 3.947361147 - 0.9387994989 * I
+%! 0.4 + I * 0. , 0.9211793498 + 0. * I
+%! 0.4 + I * 0.2 , 0.9395019377 - 0.07822091534 * I
+%! 0.4 + I * 0.4 , 0.9952345231 - 0.1598950363 * I
+%! 0.4 + I * 0.6 , 1.090715991 - 0.2487465067 * I
+%! 0.4 + I * 0.8 , 1.229998843 - 0.34910407 * I
+%! 0.4 + I * 1. , 1.419103868 - 0.4663848201 * I
+%! 0.4 + I * 1.2 , 1.666426377 - 0.607877235 * I
+%! 0.4 + I * 1.4 , 1.983347336 - 0.7841054404 * I
+%! 0.4 + I * 1.6 , 2.385101684 - 1.01134031 * I
+%! 0.4 + I * 1.8 , 2.89185416 - 1.316448705 * I
+%! 0.4 + I * 2. , 3.529393374 - 1.74670531 * I
+%! 0.6 + I * 0. , 0.8258917445 + 0. * I
+%! 0.6 + I * 0.2 , 0.842151698 - 0.1130337928 * I
+%! 0.6 + I * 0.4 , 0.8915487431 - 0.2309124769 * I
+%! 0.6 + I * 0.6 , 0.975948103 - 0.3588102098 * I
+%! 0.6 + I * 0.8 , 1.098499209 - 0.5026234141 * I
+%! 0.6 + I * 1. , 1.263676101 - 0.6695125973 * I
+%! 0.6 + I * 1.2 , 1.477275851 - 0.8687285705 * I
+%! 0.6 + I * 1.4 , 1.746262523 - 1.112955966 * I
+%! 0.6 + I * 1.6 , 2.078179075 - 1.420581466 * I
+%! 0.6 + I * 1.8 , 2.479425208 - 1.819580713 * I
+%! 0.6 + I * 2. , 2.950586798 - 2.354077344 * I
+%! 0.8 + I * 0. , 0.6982891589 + 0. * I
+%! 0.8 + I * 0.2 , 0.71187169 - 0.1430549855 * I
+%! 0.8 + I * 0.4 , 0.7530744458 - 0.2920273465 * I
+%! 0.8 + I * 0.6 , 0.8232501212 - 0.4531616768 * I
+%! 0.8 + I * 0.8 , 0.9245978896 - 0.6334016187 * I
+%! 0.8 + I * 1. , 1.060030206 - 0.8408616109 * I
+%! 0.8 + I * 1.2 , 1.232861756 - 1.085475913 * I
+%! 0.8 + I * 1.4 , 1.446126965 - 1.379933558 * I
+%! 0.8 + I * 1.6 , 1.701139468 - 1.741030588 * I
+%! 0.8 + I * 1.8 , 1.994526268 - 2.191509596 * I
+%! 0.8 + I * 2. , 2.312257188 - 2.762051518 * I
+%! 1. + I * 0. , 0.5436738271 + 0. * I
+%! 1. + I * 0.2 , 0.5541219664 - 0.1672121517 * I
+%! 1. + I * 0.4 , 0.5857703552 - 0.3410940893 * I
+%! 1. + I * 0.6 , 0.6395034233 - 0.5285979063 * I
+%! 1. + I * 0.8 , 0.716688504 - 0.7372552987 * I
+%! 1. + I * 1. , 0.8189576795 - 0.9755037374 * I
+%! 1. + I * 1.2 , 0.9477661951 - 1.253049471 * I
+%! 1. + I * 1.4 , 1.103540657 - 1.581252712 * I
+%! 1. + I * 1.6 , 1.284098214 - 1.973449038 * I
+%! 1. + I * 1.8 , 1.481835651 - 2.4449211 * I
+%! 1. + I * 2. , 1.679032464 - 3.011729224 * I
+%! ];
+%! DN = [
+%! -1. + I * 0. , 0.9895776106 + 0. * I
+%! -1. + I * 0.2 , 0.9893361555 + 0.002756935338 * I
+%! -1. + I * 0.4 , 0.9885716856 + 0.005949639805 * I
+%! -1. + I * 0.6 , 0.9871564855 + 0.01008044183 * I
+%! -1. + I * 0.8 , 0.9848512162 + 0.01579337596 * I
+%! -1. + I * 1. , 0.9812582484 + 0.02396648455 * I
+%! -1. + I * 1.2 , 0.9757399152 + 0.0358288294 * I
+%! -1. + I * 1.4 , 0.9672786056 + 0.0531049859 * I
+%! -1. + I * 1.6 , 0.954237868 + 0.0781744383 * I
+%! -1. + I * 1.8 , 0.933957524 + 0.1141918269 * I
+%! -1. + I * 2. , 0.9020917489 + 0.1650142936 * I
+%! -0.8 + I * 0. , 0.992429635 + 0. * I
+%! -0.8 + I * 0.2 , 0.9924147861 + 0.003020708044 * I
+%! -0.8 + I * 0.4 , 0.99236555 + 0.00652359532 * I
+%! -0.8 + I * 0.6 , 0.9922655715 + 0.0110676219 * I
+%! -0.8 + I * 0.8 , 0.9920785856 + 0.01737733806 * I
+%! -0.8 + I * 1. , 0.9917291795 + 0.02645738598 * I
+%! -0.8 + I * 1.2 , 0.9910606387 + 0.03974949378 * I
+%! -0.8 + I * 1.4 , 0.9897435004 + 0.05935252515 * I
+%! -0.8 + I * 1.6 , 0.987077644 + 0.08832675281 * I
+%! -0.8 + I * 1.8 , 0.9815667458 + 0.1310872821 * I
+%! -0.8 + I * 2. , 0.970020127 + 0.1938136793 * I
+%! -0.6 + I * 0. , 0.9953099088 + 0. * I
+%! -0.6 + I * 0.2 , 0.995526009 + 0.002814772354 * I
+%! -0.6 + I * 0.4 , 0.9962071136 + 0.006083312292 * I
+%! -0.6 + I * 0.6 , 0.9974557125 + 0.01033463525 * I
+%! -0.6 + I * 0.8 , 0.9994560563 + 0.01626207722 * I
+%! -0.6 + I * 1. , 1.00249312 + 0.02484336286 * I
+%! -0.6 + I * 1.2 , 1.006973922 + 0.0375167093 * I
+%! -0.6 + I * 1.4 , 1.013436509 + 0.05645315628 * I
+%! -0.6 + I * 1.6 , 1.022504295 + 0.08499262247 * I
+%! -0.6 + I * 1.8 , 1.034670023 + 0.1283564595 * I
+%! -0.6 + I * 2. , 1.049599899 + 0.194806122 * I
+%! -0.4 + I * 0. , 0.9977686897 + 0. * I
+%! -0.4 + I * 0.2 , 0.9981836165 + 0.002167241934 * I
+%! -0.4 + I * 0.4 , 0.9994946045 + 0.004686808612 * I
+%! -0.4 + I * 0.6 , 1.001910789 + 0.00797144174 * I
+%! -0.4 + I * 0.8 , 1.005817375 + 0.01256717724 * I
+%! -0.4 + I * 1. , 1.011836374 + 0.01925509038 * I
+%! -0.4 + I * 1.2 , 1.020923572 + 0.02920828367 * I
+%! -0.4 + I * 1.4 , 1.034513743 + 0.04425213602 * I
+%! -0.4 + I * 1.6 , 1.054725746 + 0.06732276244 * I
+%! -0.4 + I * 1.8 , 1.08462027 + 0.1033236812 * I
+%! -0.4 + I * 2. , 1.128407402 + 0.1608240664 * I
+%! -0.2 + I * 0. , 0.9994191176 + 0. * I
+%! -0.2 + I * 0.2 , 0.9999683719 + 0.001177128019 * I
+%! -0.2 + I * 0.4 , 1.001705496 + 0.00254669712 * I
+%! -0.2 + I * 0.6 , 1.004913944 + 0.004334880912 * I
+%! -0.2 + I * 0.8 , 1.010120575 + 0.006842775622 * I
+%! -0.2 + I * 1. , 1.018189543 + 0.01050520136 * I
+%! -0.2 + I * 1.2 , 1.030482479 + 0.01598431001 * I
+%! -0.2 + I * 1.4 , 1.049126108 + 0.02433134655 * I
+%! -0.2 + I * 1.6 , 1.077466003 + 0.0372877718 * I
+%! -0.2 + I * 1.8 , 1.120863308 + 0.05789156398 * I
+%! -0.2 + I * 2. , 1.188162088 + 0.09181238708 * I
+%! 0. + I * 0. , 1. + 0. * I
+%! 0. + I * 0.2 , 1.000596698 + 0. * I
+%! 0. + I * 0.4 , 1.002484444 + 0. * I
+%! 0. + I * 0.6 , 1.005973379 + 0. * I
+%! 0. + I * 0.8 , 1.011641536 + 0. * I
+%! 0. + I * 1. , 1.020441432 + 0. * I
+%! 0. + I * 1.2 , 1.033885057 + 0. * I
+%! 0. + I * 1.4 , 1.054361188 + 0. * I
+%! 0. + I * 1.6 , 1.085694733 + 0. * I
+%! 0. + I * 1.8 , 1.134186672 + 0. * I
+%! 0. + I * 2. , 1.210701071 + 0. * I
+%! 0.2 + I * 0. , 0.9994191176 + 0. * I
+%! 0.2 + I * 0.2 , 0.9999683719 - 0.001177128019 * I
+%! 0.2 + I * 0.4 , 1.001705496 - 0.00254669712 * I
+%! 0.2 + I * 0.6 , 1.004913944 - 0.004334880912 * I
+%! 0.2 + I * 0.8 , 1.010120575 - 0.006842775622 * I
+%! 0.2 + I * 1. , 1.018189543 - 0.01050520136 * I
+%! 0.2 + I * 1.2 , 1.030482479 - 0.01598431001 * I
+%! 0.2 + I * 1.4 , 1.049126108 - 0.02433134655 * I
+%! 0.2 + I * 1.6 , 1.077466003 - 0.0372877718 * I
+%! 0.2 + I * 1.8 , 1.120863308 - 0.05789156398 * I
+%! 0.2 + I * 2. , 1.188162088 - 0.09181238708 * I
+%! 0.4 + I * 0. , 0.9977686897 + 0. * I
+%! 0.4 + I * 0.2 , 0.9981836165 - 0.002167241934 * I
+%! 0.4 + I * 0.4 , 0.9994946045 - 0.004686808612 * I
+%! 0.4 + I * 0.6 , 1.001910789 - 0.00797144174 * I
+%! 0.4 + I * 0.8 , 1.005817375 - 0.01256717724 * I
+%! 0.4 + I * 1. , 1.011836374 - 0.01925509038 * I
+%! 0.4 + I * 1.2 , 1.020923572 - 0.02920828367 * I
+%! 0.4 + I * 1.4 , 1.034513743 - 0.04425213602 * I
+%! 0.4 + I * 1.6 , 1.054725746 - 0.06732276244 * I
+%! 0.4 + I * 1.8 , 1.08462027 - 0.1033236812 * I
+%! 0.4 + I * 2. , 1.128407402 - 0.1608240664 * I
+%! 0.6 + I * 0. , 0.9953099088 + 0. * I
+%! 0.6 + I * 0.2 , 0.995526009 - 0.002814772354 * I
+%! 0.6 + I * 0.4 , 0.9962071136 - 0.006083312292 * I
+%! 0.6 + I * 0.6 , 0.9974557125 - 0.01033463525 * I
+%! 0.6 + I * 0.8 , 0.9994560563 - 0.01626207722 * I
+%! 0.6 + I * 1. , 1.00249312 - 0.02484336286 * I
+%! 0.6 + I * 1.2 , 1.006973922 - 0.0375167093 * I
+%! 0.6 + I * 1.4 , 1.013436509 - 0.05645315628 * I
+%! 0.6 + I * 1.6 , 1.022504295 - 0.08499262247 * I
+%! 0.6 + I * 1.8 , 1.034670023 - 0.1283564595 * I
+%! 0.6 + I * 2. , 1.049599899 - 0.194806122 * I
+%! 0.8 + I * 0. , 0.992429635 + 0. * I
+%! 0.8 + I * 0.2 , 0.9924147861 - 0.003020708044 * I
+%! 0.8 + I * 0.4 , 0.99236555 - 0.00652359532 * I
+%! 0.8 + I * 0.6 , 0.9922655715 - 0.0110676219 * I
+%! 0.8 + I * 0.8 , 0.9920785856 - 0.01737733806 * I
+%! 0.8 + I * 1. , 0.9917291795 - 0.02645738598 * I
+%! 0.8 + I * 1.2 , 0.9910606387 - 0.03974949378 * I
+%! 0.8 + I * 1.4 , 0.9897435004 - 0.05935252515 * I
+%! 0.8 + I * 1.6 , 0.987077644 - 0.08832675281 * I
+%! 0.8 + I * 1.8 , 0.9815667458 - 0.1310872821 * I
+%! 0.8 + I * 2. , 0.970020127 - 0.1938136793 * I
+%! 1. + I * 0. , 0.9895776106 + 0. * I
+%! 1. + I * 0.2 , 0.9893361555 - 0.002756935338 * I
+%! 1. + I * 0.4 , 0.9885716856 - 0.005949639805 * I
+%! 1. + I * 0.6 , 0.9871564855 - 0.01008044183 * I
+%! 1. + I * 0.8 , 0.9848512162 - 0.01579337596 * I
+%! 1. + I * 1. , 0.9812582484 - 0.02396648455 * I
+%! 1. + I * 1.2 , 0.9757399152 - 0.0358288294 * I
+%! 1. + I * 1.4 , 0.9672786056 - 0.0531049859 * I
+%! 1. + I * 1.6 , 0.954237868 - 0.0781744383 * I
+%! 1. + I * 1.8 , 0.933957524 - 0.1141918269 * I
+%! 1. + I * 2. , 0.9020917489 - 0.1650142936 * I
+%! ];
+%! tol = 1e-9;
+%! for x = 0:10
+%!   for y = 0:10
+%!     ur = -1 + x * 0.2;
+%!     ui =  y * 0.2;
+%!     ii = 1 + y + x*11;
+%!     [sn, cn, dn] = ellipj (ur + I * ui, m);
+%!     assert (SN (ii, 2), sn, tol);
+%!     assert (CN (ii, 2), cn, tol);
+%!     assert (DN (ii, 2), dn, tol);
+%!   endfor
+%! endfor
+
+## tests taken from test_ellipj.m
+%!test
+%! u1 = pi/3; m1 = 0;
+%! res1 = [sin(pi/3), cos(pi/3), 1];
+%! [sn,cn,dn]=ellipj(u1,m1);
+%! assert([sn,cn,dn], res1, 10*eps);
+
+%!test
+%! u2 = log(2); m2 = 1;
+%! res2 = [ 3/5, 4/5, 4/5 ];
+%! [sn,cn,dn]=ellipj(u2,m2);
+%! assert([sn,cn,dn], res2, 10*eps);
+
+%!test
+%! u3 = log(2)*1i; m3 = 0;
+%! res3 = [3i/4,5/4,1];
+%! [sn,cn,dn]=ellipj(u3,m3);
+%! assert([sn,cn,dn], res3, 10*eps);
+
+%!test
+%! u4 = -1; m4 = tan(pi/8)^4;
+%! res4 = [-0.8392965923,0.5436738271,0.9895776106];
+%! [sn,cn,dn]=ellipj(u4, m4);
+%! assert([sn,cn,dn], res4, 1e-10);
+
+%!test
+%! u5 = -0.2 + 0.4i; m5 = tan(pi/8)^4;
+%! res5 = [ -0.2152524522 + 0.402598347i, ...
+%!           1.059453907  + 0.08179712295i, ...
+%!           1.001705496  + 0.00254669712i ];
+%! [sn,cn,dn]=ellipj(u5,m5);
+%! assert([sn,cn,dn], res5, 1e-9);
+
+%!test
+%! u6 = 0.2 + 0.6i; m6 = tan(pi/8)^4;
+%! res6 = [ 0.2369100139 + 0.624633635i, ...
+%!          1.16200643   - 0.1273503824i, ...
+%!          1.004913944 - 0.004334880912i ];
+%! [sn,cn,dn]=ellipj(u6,m6);
+%! assert([sn,cn,dn], res6, 1e-8);
+
+%!test
+%! u7 = 0.8 + 0.8i; m7 = tan(pi/8)^4;
+%! res7 = [0.9588386397 + 0.6107824358i, ...
+%!         0.9245978896 - 0.6334016187i, ...
+%!         0.9920785856 - 0.01737733806i ];
+%! [sn,cn,dn]=ellipj(u7,m7);
+%! assert([sn,cn,dn], res7, 1e-10);
+
+%!test
+%! u=[0,pi/6,pi/4,pi/2]; m=0;
+%! res = [0,1/2,1/sqrt(2),1;1,cos(pi/6),1/sqrt(2),0;1,1,1,1];
+%! [sn,cn,dn]=ellipj(u,m);
+%! assert([sn;cn;dn],res, 100*eps);
+%! [sn,cn,dn]=ellipj(u',0);
+%! assert([sn,cn,dn],res', 100*eps);
+
+## XXX FIXME XXX
+## need to check [real,complex]x[scalar,rowvec,colvec,matrix]x[u,m]
+
+%!test
+%! ## Test Jacobi elliptic functions
+%! ## against "exact" solution from Mathematica 3.0
+%! ## David Billinghurst <David.Billinghurst@riotinto.com>
+%! ## 1 February 2001
+%! u = [ 0.25; 0.25; 0.20; 0.20; 0.672; 0.5];
+%! m = [ 0.0;  1.0;  0.19; 0.81; 0.36;  0.9999999999];
+%! S = [ sin(0.25); tanh(0.25);
+%!  0.19842311013970879516;
+%!  0.19762082367187648571;
+%!  0.6095196917919021945;
+%!  0.4621171572617320908 ];
+%! C = [ cos(0.25); sech(0.25);
+%!  0.9801164570409401062;
+%!  0.9802785369736752032;
+%!  0.7927709286533560550;
+%!  0.8868188839691764094 ];
+%! D = [ 1.0;  sech(0.25);
+%!  0.9962526643271134302;
+%!  0.9840560289645665155;
+%!  0.9307281387786906491;
+%!  0.8868188839812167635 ];
+%! [sn,cn,dn] = ellipj(u,m);
+%! assert(sn,S,8*eps);
+%! assert(cn,C,8*eps);
+%! assert(dn,D,8*eps);
+
+%!error ellipj ()
+%!error ellipj (1)
+%!error ellipj (1,2,3,4)
+*/
rename from src/DLD-FUNCTIONS/fft.cc
rename to libinterp/corefcn/fft.cc
--- a/src/DLD-FUNCTIONS/fft.cc
+++ b/libinterp/corefcn/fft.cc
@@ -27,7 +27,7 @@
 
 #include "lo-mappers.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -177,32 +177,31 @@
 }
 
 /*
+%!assert (fft ([]), [])
+%!assert (fft (zeros (10,0)), zeros (10,0))
+%!assert (fft (zeros (0,10)), zeros (0,10))
+%!assert (fft (0), 0)
+%!assert (fft (1), 1)
+%!assert (fft (ones (2,2)), [2,2; 0,0])
+%!assert (fft (eye (2,2)), [1,1; 1,-1])
 
-%!error(fft())
-%!assert(fft([]), [])
-%!assert(fft(zeros(10,0)), zeros(10,0))
-%!assert(fft(zeros(0,10)), zeros(0,10))
-%!assert(fft(0), 0)
-%!assert(fft(1), 1)
-%!assert(fft(ones(2,2)), [2,2; 0,0])
-%!assert(fft(eye(2,2)), [1,1; 1,-1])
+%!assert (fft (single ([])), single ([]))
+%!assert (fft (zeros (10,0,"single")), zeros (10,0,"single"))
+%!assert (fft (zeros (0,10,"single")), zeros (0,10,"single"))
+%!assert (fft (single (0)), single (0))
+%!assert (fft (single (1)), single (1))
+%!assert (fft (ones (2,2,"single")), single ([2,2; 0,0]))
+%!assert (fft (eye (2,2,"single")), single ([1,1; 1,-1]))
 
-%!assert(fft(single([])), single([]))
-%!assert(fft(zeros(10,0,'single')), zeros(10,0,'single'))
-%!assert(fft(zeros(0,10,'single')), zeros(0,10,'single'))
-%!assert(fft(single(0)), single(0))
-%!assert(fft(single(1)), single(1))
-%!assert(fft(ones(2,2,'single')), single([2,2; 0,0]))
-%!assert(fft(eye(2,2,'single')), single([1,1; 1,-1]))
-
+%!error (fft ())
 */
 
 
-DEFUN_DLD (fft, args, ,
+DEFUN (fft, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} fft (@var{x})\n\
-@deftypefnx {Loadable Function} {} fft (@var{x}, @var{n})\n\
-@deftypefnx {Loadable Function} {} fft (@var{x}, @var{n}, @var{dim})\n\
+@deftypefn  {Built-in Function} {} fft (@var{x})\n\
+@deftypefnx {Built-in Function} {} fft (@var{x}, @var{n})\n\
+@deftypefnx {Built-in Function} {} fft (@var{x}, @var{n}, @var{dim})\n\
 Compute the discrete Fourier transform of @var{A} using\n\
 a Fast Fourier Transform (FFT) algorithm.\n\
 \n\
@@ -227,11 +226,11 @@
 }
 
 
-DEFUN_DLD (ifft, args, ,
+DEFUN (ifft, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} ifft (@var{x})\n\
-@deftypefnx {Loadable Function} {} ifft (@var{x}, @var{n})\n\
-@deftypefnx {Loadable Function} {} ifft (@var{x}, @var{n}, @var{dim})\n\
+@deftypefn  {Built-in Function} {} ifft (@var{x})\n\
+@deftypefnx {Built-in Function} {} ifft (@var{x}, @var{n})\n\
+@deftypefnx {Built-in Function} {} ifft (@var{x}, @var{n}, @var{dim})\n\
 Compute the inverse discrete Fourier transform of @var{A}\n\
 using a Fast Fourier Transform (FFT) algorithm.\n\
 \n\
@@ -256,67 +255,65 @@
 }
 
 /*
-
 %% Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
 %%         Comalco Research and Technology
 %%         02 May 2000
 %!test
-%! N=64;
-%! n=4;
+%! N = 64;
+%! n = 4;
 %! t = 2*pi*(0:1:N-1)/N;
-%! s = cos(n*t);
-%! S = fft(s);
+%! s = cos (n*t);
+%! S = fft (s);
 %!
-%! answer = zeros (size(t));
+%! answer = zeros (size (t));
 %! answer(n+1) = N/2;
 %! answer(N-n+1) = N/2;
 %!
-%! assert(S, answer, 4*N*eps);
+%! assert (S, answer, 4*N*eps);
 
 %% Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
 %%         Comalco Research and Technology
 %%         02 May 2000
 %!test
-%! N=64;
-%! n=7;
+%! N = 64;
+%! n = 7;
 %! t = 2*pi*(0:1:N-1)/N;
-%! s = cos(n*t);
+%! s = cos (n*t);
 %!
-%! S = zeros (size(t));
+%! S = zeros (size (t));
 %! S(n+1) = N/2;
 %! S(N-n+1) = N/2;
 %!
-%! assert(ifft(S), s, 4*N*eps);
+%! assert (ifft (S), s, 4*N*eps);
 
 %% Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
 %%         Comalco Research and Technology
 %%         02 May 2000
 %!test
-%! N=64;
-%! n=4;
+%! N = 64;
+%! n = 4;
 %! t = single (2*pi*(0:1:N-1)/N);
-%! s = cos(n*t);
-%! S = fft(s);
+%! s = cos (n*t);
+%! S = fft (s);
 %!
-%! answer = zeros (size(t),'single');
+%! answer = zeros (size (t), "single");
 %! answer(n+1) = N/2;
 %! answer(N-n+1) = N/2;
 %!
-%! assert(S, answer, 4*N*eps('single'));
+%! assert (S, answer, 4*N*eps ("single"));
 
 %% Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
 %%         Comalco Research and Technology
 %%         02 May 2000
 %!test
-%! N=64;
-%! n=7;
+%! N = 64;
+%! n = 7;
 %! t = 2*pi*(0:1:N-1)/N;
-%! s = cos(n*t);
+%! s = cos (n*t);
 %!
-%! S = zeros (size(t),'single');
+%! S = zeros (size (t), "single");
 %! S(n+1) = N/2;
 %! S(N-n+1) = N/2;
 %!
-%! assert(ifft(S), s, 4*N*eps('single'));
-
+%! assert (ifft (S), s, 4*N*eps ("single"));
 */
rename from src/DLD-FUNCTIONS/fft2.cc
rename to libinterp/corefcn/fft2.cc
--- a/src/DLD-FUNCTIONS/fft2.cc
+++ b/libinterp/corefcn/fft2.cc
@@ -27,7 +27,7 @@
 
 #include "lo-mappers.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -167,10 +167,10 @@
   return retval;
 }
 
-DEFUN_DLD (fft2, args, ,
+DEFUN (fft2, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} fft2 (@var{A})\n\
-@deftypefnx {Loadable Function} {} fft2 (@var{A}, @var{m}, @var{n})\n\
+@deftypefn  {Built-in Function} {} fft2 (@var{A})\n\
+@deftypefnx {Built-in Function} {} fft2 (@var{A}, @var{m}, @var{n})\n\
 Compute the two-dimensional discrete Fourier transform of @var{A} using\n\
 a Fast Fourier Transform (FFT) algorithm.\n\
 \n\
@@ -188,10 +188,10 @@
 }
 
 
-DEFUN_DLD (ifft2, args, ,
+DEFUN (ifft2, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} ifft2 (@var{A})\n\
-@deftypefnx {Loadable Function} {} ifft2 (@var{A}, @var{m}, @var{n})\n\
+@deftypefn  {Built-in Function} {} ifft2 (@var{A})\n\
+@deftypefnx {Built-in Function} {} ifft2 (@var{A}, @var{m}, @var{n})\n\
 Compute the inverse two-dimensional discrete Fourier transform of @var{A}\n\
 using a Fast Fourier Transform (FFT) algorithm.\n\
 \n\
@@ -209,88 +209,86 @@
 }
 
 /*
+%% Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
+%%         Comalco Research and Technology
+%%         02 May 2000
+%!test
+%! M = 16;
+%! N = 8;
+%!
+%! m = 5;
+%! n = 3;
+%!
+%! x = 2*pi*(0:1:M-1)/M;
+%! y = 2*pi*(0:1:N-1)/N;
+%! sx = cos (m*x);
+%! sy = sin (n*y);
+%! s = kron (sx',sy);
+%! S = fft2 (s);
+%! answer = kron (fft (sx)', fft (sy));
+%! assert (S, answer, 4*M*N*eps);
 
 %% Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
 %%         Comalco Research and Technology
 %%         02 May 2000
 %!test
-%! M=16;
-%! N=8;
-%!
-%! m=5;
-%! n=3;
+%! M = 12;
+%! N = 7;
 %!
-%! x = 2*pi*(0:1:M-1)/M;
-%! y = 2*pi*(0:1:N-1)/N;
-%! sx = cos(m*x);
-%! sy = sin(n*y);
-%! s=kron(sx',sy);
-%! S = fft2(s);
-%! answer = kron(fft(sx)',fft(sy));
-%! assert(S, answer, 4*M*N*eps);
-
-%% Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
-%%         Comalco Research and Technology
-%%         02 May 2000
-%!test
-%! M=12;
-%! N=7;
-%!
-%! m=3;
-%! n=2;
+%! m = 3;
+%! n = 2;
 %!
 %! x = 2*pi*(0:1:M-1)/M;
 %! y = 2*pi*(0:1:N-1)/N;
 %!
-%! sx = cos(m*x);
-%! sy = cos(n*y);
+%! sx = cos (m*x);
+%! sy = cos (n*y);
 %!
-%! S = kron(fft(sx)',fft(sy));
-%! answer=kron(sx',sy);
-%! s = ifft2(S);
+%! S = kron (fft (sx)', fft (sy));
+%! answer = kron (sx', sy);
+%! s = ifft2 (S);
 %!
-%! assert(s, answer, 30*eps);
+%! assert (s, answer, 30*eps);
 
 
 %% Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
 %%         Comalco Research and Technology
 %%         02 May 2000
 %!test
-%! M=16;
-%! N=8;
+%! M = 16;
+%! N = 8;
 %!
-%! m=5;
-%! n=3;
+%! m = 5;
+%! n = 3;
 %!
 %! x = 2*pi*(0:1:M-1)/M;
 %! y = 2*pi*(0:1:N-1)/N;
-%! sx = single(cos(m*x));
-%! sy = single(sin(n*y));
-%! s=kron(sx',sy);
-%! S = fft2(s);
-%! answer = kron(fft(sx)',fft(sy));
-%! assert(S, answer, 4*M*N*eps('single'));
+%! sx = single (cos (m*x));
+%! sy = single (sin (n*y));
+%! s = kron (sx', sy);
+%! S = fft2 (s);
+%! answer = kron (fft (sx)', fft (sy));
+%! assert (S, answer, 4*M*N*eps ("single"));
 
 %% Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
 %%         Comalco Research and Technology
 %%         02 May 2000
 %!test
-%! M=12;
-%! N=7;
+%! M = 12;
+%! N = 7;
 %!
-%! m=3;
-%! n=2;
+%! m = 3;
+%! n = 2;
 %!
-%! x = single(2*pi*(0:1:M-1)/M);
-%! y = single(2*pi*(0:1:N-1)/N);
+%! x = single (2*pi*(0:1:M-1)/M);
+%! y = single (2*pi*(0:1:N-1)/N);
 %!
-%! sx = cos(m*x);
-%! sy = cos(n*y);
+%! sx = cos (m*x);
+%! sy = cos (n*y);
 %!
-%! S = kron(fft(sx)',fft(sy));
-%! answer=kron(sx',sy);
-%! s = ifft2(S);
+%! S = kron (fft (sx)', fft (sy));
+%! answer = kron (sx', sy);
+%! s = ifft2 (S);
 %!
-%! assert(s, answer, 30*eps('single'));
-
+%! assert (s, answer, 30*eps ("single"));
 */
rename from src/DLD-FUNCTIONS/fftn.cc
rename to libinterp/corefcn/fftn.cc
--- a/src/DLD-FUNCTIONS/fftn.cc
+++ b/libinterp/corefcn/fftn.cc
@@ -26,7 +26,7 @@
 
 #include "lo-mappers.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -149,10 +149,10 @@
   return retval;
 }
 
-DEFUN_DLD (fftn, args, ,
+DEFUN (fftn, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} fftn (@var{A})\n\
-@deftypefnx {Loadable Function} {} fftn (@var{A}, @var{size})\n\
+@deftypefn  {Built-in Function} {} fftn (@var{A})\n\
+@deftypefnx {Built-in Function} {} fftn (@var{A}, @var{size})\n\
 Compute the N-dimensional discrete Fourier transform of @var{A} using\n\
 a Fast Fourier Transform (FFT) algorithm.\n\
 \n\
@@ -168,10 +168,10 @@
   return do_fftn (args, "fftn", 0);
 }
 
-DEFUN_DLD (ifftn, args, ,
+DEFUN (ifftn, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} ifftn (@var{A})\n\
-@deftypefnx {Loadable Function} {} ifftn (@var{A}, @var{size})\n\
+@deftypefn  {Built-in Function} {} ifftn (@var{A})\n\
+@deftypefnx {Built-in Function} {} ifftn (@var{A}, @var{size})\n\
 Compute the inverse N-dimensional discrete Fourier transform of @var{A}\n\
 using a Fast Fourier Transform (FFT) algorithm.\n\
 \n\
rename from src/DLD-FUNCTIONS/filter.cc
rename to libinterp/corefcn/filter.cc
--- a/src/DLD-FUNCTIONS/filter.cc
+++ b/libinterp/corefcn/filter.cc
@@ -34,7 +34,7 @@
 
 #include "quit.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "oct-obj.h"
 
@@ -252,7 +252,7 @@
 MArray<T>
 filter (MArray<T>& b, MArray<T>& a, MArray<T>& x, int dim = -1)
 {
-  dim_vector x_dims = x.dims();
+  dim_vector x_dims = x.dims ();
 
   if (dim < 0)
     {
@@ -285,12 +285,12 @@
   return filter (b, a, x, si, dim);
 }
 
-DEFUN_DLD (filter, args, nargout,
+DEFUN (filter, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {y =} filter (@var{b}, @var{a}, @var{x})\n\
-@deftypefnx {Loadable Function} {[@var{y}, @var{sf}] =} filter (@var{b}, @var{a}, @var{x}, @var{si})\n\
-@deftypefnx {Loadable Function} {[@var{y}, @var{sf}] =} filter (@var{b}, @var{a}, @var{x}, [], @var{dim})\n\
-@deftypefnx {Loadable Function} {[@var{y}, @var{sf}] =} filter (@var{b}, @var{a}, @var{x}, @var{si}, @var{dim})\n\
+@deftypefn  {Built-in Function} {y =} filter (@var{b}, @var{a}, @var{x})\n\
+@deftypefnx {Built-in Function} {[@var{y}, @var{sf}] =} filter (@var{b}, @var{a}, @var{x}, @var{si})\n\
+@deftypefnx {Built-in Function} {[@var{y}, @var{sf}] =} filter (@var{b}, @var{a}, @var{x}, [], @var{dim})\n\
+@deftypefnx {Built-in Function} {[@var{y}, @var{sf}] =} filter (@var{b}, @var{a}, @var{x}, @var{si}, @var{dim})\n\
 Return the solution to the following linear, time-invariant difference\n\
 equation:\n\
 @tex\n\
@@ -304,9 +304,9 @@
 \n\
 @smallexample\n\
 @group\n\
-   N                   M\n\
-  SUM a(k+1) y(n-k) = SUM b(k+1) x(n-k)      for 1<=n<=length(x)\n\
-  k=0                 k=0\n\
+ N                   M\n\
+SUM a(k+1) y(n-k) = SUM b(k+1) x(n-k)    for 1<=n<=length(x)\n\
+k=0                 k=0\n\
 @end group\n\
 @end smallexample\n\
 \n\
@@ -315,13 +315,15 @@
 @noindent\n\
 where\n\
 @ifnottex\n\
- N=length(a)-1 and M=length(b)-1.\n\
+N=length(a)-1 and M=length(b)-1.\n\
 @end ifnottex\n\
 @tex\n\
- $a \\in \\Re^{N-1}$, $b \\in \\Re^{M-1}$, and $x \\in \\Re^P$.\n\
+$a \\in \\Re^{N-1}$, $b \\in \\Re^{M-1}$, and $x \\in \\Re^P$.\n\
 @end tex\n\
-over the first non-singleton dimension of @var{x} or over @var{dim} if\n\
-supplied.  An equivalent form of this equation is:\n\
+The result is calculated over the first non-singleton dimension of @var{x}\n\
+or over @var{dim} if supplied.\n\
+\n\
+An equivalent form of the equation is:\n\
 @tex\n\
 $$\n\
 y_n = -\\sum_{k=1}^N c_{k+1} y_{n-k} + \\sum_{k=0}^M d_{k+1} x_{n-k}, \\qquad\n\
@@ -333,9 +335,9 @@
 \n\
 @smallexample\n\
 @group\n\
-            N                   M\n\
-  y(n) = - SUM c(k+1) y(n-k) + SUM d(k+1) x(n-k)  for 1<=n<=length(x)\n\
-           k=1                 k=0\n\
+          N                   M\n\
+y(n) = - SUM c(k+1) y(n-k) + SUM d(k+1) x(n-k)  for 1<=n<=length(x)\n\
+         k=1                 k=0\n\
 @end group\n\
 @end smallexample\n\
 \n\
@@ -370,13 +372,13 @@
 \n\
 @example\n\
 @group\n\
-             M\n\
-            SUM d(k+1) z^(-k)\n\
-            k=0\n\
-  H(z) = ----------------------\n\
-               N\n\
-          1 + SUM c(k+1) z^(-k)\n\
-              k=1\n\
+          M\n\
+         SUM d(k+1) z^(-k)\n\
+         k=0\n\
+H(z) = ---------------------\n\
+            N\n\
+       1 + SUM c(k+1) z^(-k)\n\
+           k=1\n\
 @end group\n\
 @end example\n\
 \n\
@@ -401,7 +403,7 @@
 
   if (nargin == 5)
     {
-      dim = args(4).nint_value() - 1;
+      dim = args(4).nint_value () - 1;
       if (dim < 0 || dim >= x_dims.length ())
         {
           error ("filter: DIM must be a valid dimension");
@@ -661,73 +663,76 @@
 /*
 %!shared a, b, x, r
 %!test
-%!  a = [1 1];
-%!  b = [1 1];
-%!  x = zeros (1,10); x(1) = 1;
-%!  assert(filter(b,   [1], x  ), [1 1 0 0 0 0 0 0 0 0]);
-%!  assert(filter(b,   [1], x.'), [1 1 0 0 0 0 0 0 0 0].');
-%!  assert(filter(b.', [1], x  ), [1 1 0 0 0 0 0 0 0 0]  );
-%!  assert(filter(b.', [1], x.'), [1 1 0 0 0 0 0 0 0 0].');
-%!  assert(filter([1], a,   x  ), [+1 -1 +1 -1 +1 -1 +1 -1 +1 -1]  );
-%!  assert(filter([1], a,   x.'), [+1 -1 +1 -1 +1 -1 +1 -1 +1 -1].');
-%!  assert(filter([1], a.', x  ), [+1 -1 +1 -1 +1 -1 +1 -1 +1 -1]  );
-%!  assert(filter([1], a.', x.'), [+1 -1 +1 -1 +1 -1 +1 -1 +1 -1].');
-%!  assert(filter(b,   a,   x  ), [1 0 0 0 0 0 0 0 0 0]  );
-%!  assert(filter(b.', a,   x  ), [1 0 0 0 0 0 0 0 0 0]  );
-%!  assert(filter(b,   a.', x  ), [1 0 0 0 0 0 0 0 0 0]  );
-%!  assert(filter(b.', a,   x  ), [1 0 0 0 0 0 0 0 0 0]  );
-%!  assert(filter(b,   a,   x.'), [1 0 0 0 0 0 0 0 0 0].');
-%!  assert(filter(b.', a,   x.'), [1 0 0 0 0 0 0 0 0 0].');
-%!  assert(filter(b,   a.', x.'), [1 0 0 0 0 0 0 0 0 0].');
-%!  assert(filter(b.', a,   x.'), [1 0 0 0 0 0 0 0 0 0].');
-%!
+%! a = [1 1];
+%! b = [1 1];
+%! x = zeros (1,10);  x(1) = 1;
+%! assert (filter (b,   [1], x  ), [1 1 0 0 0 0 0 0 0 0]);
+%! assert (filter (b,   [1], x.'), [1 1 0 0 0 0 0 0 0 0].');
+%! assert (filter (b.', [1], x  ), [1 1 0 0 0 0 0 0 0 0]  );
+%! assert (filter (b.', [1], x.'), [1 1 0 0 0 0 0 0 0 0].');
+%! assert (filter ([1], a,   x  ), [+1 -1 +1 -1 +1 -1 +1 -1 +1 -1]  );
+%! assert (filter ([1], a,   x.'), [+1 -1 +1 -1 +1 -1 +1 -1 +1 -1].');
+%! assert (filter ([1], a.', x  ), [+1 -1 +1 -1 +1 -1 +1 -1 +1 -1]  );
+%! assert (filter ([1], a.', x.'), [+1 -1 +1 -1 +1 -1 +1 -1 +1 -1].');
+%! assert (filter (b,   a,   x  ), [1 0 0 0 0 0 0 0 0 0]  );
+%! assert (filter (b.', a,   x  ), [1 0 0 0 0 0 0 0 0 0]  );
+%! assert (filter (b,   a.', x  ), [1 0 0 0 0 0 0 0 0 0]  );
+%! assert (filter (b.', a,   x  ), [1 0 0 0 0 0 0 0 0 0]  );
+%! assert (filter (b,   a,   x.'), [1 0 0 0 0 0 0 0 0 0].');
+%! assert (filter (b.', a,   x.'), [1 0 0 0 0 0 0 0 0 0].');
+%! assert (filter (b,   a.', x.'), [1 0 0 0 0 0 0 0 0 0].');
+%! assert (filter (b.', a,   x.'), [1 0 0 0 0 0 0 0 0 0].');
+
 %!test
-%!  r = sqrt(1/2)*(1+i);
-%!  a = a*r;
-%!  b = b*r;
-%!  assert(filter(b, [1], x   ), r*[1 1 0 0 0 0 0 0 0 0]   );
-%!  assert(filter(b, [1], r*x ), r*r*[1 1 0 0 0 0 0 0 0 0] );
-%!  assert(filter(b, [1], x.' ), r*[1 1 0 0 0 0 0 0 0 0].' );
-%!  assert(filter(b, a,   x   ),   [1 0 0 0 0 0 0 0 0 0]   );
-%!  assert(filter(b, a,   r*x ), r*[1 0 0 0 0 0 0 0 0 0]   );
-%!
+%! r = sqrt (1/2) * (1+i);
+%! a = a*r;
+%! b = b*r;
+%! assert (filter (b, [1], x   ), r*[1 1 0 0 0 0 0 0 0 0]   );
+%! assert (filter (b, [1], r*x ), r*r*[1 1 0 0 0 0 0 0 0 0] );
+%! assert (filter (b, [1], x.' ), r*[1 1 0 0 0 0 0 0 0 0].' );
+%! assert (filter (b, a,   x   ),   [1 0 0 0 0 0 0 0 0 0]   );
+%! assert (filter (b, a,   r*x ), r*[1 0 0 0 0 0 0 0 0 0]   );
+
 %!shared a, b, x, y, so
 %!test
-%!  a = [1,1]; b = [1,1];
-%!  x = zeros (1,10); x(1) = 1;
-%!  [y, so] = filter (b, [1], x, [-1]);
-%!  assert(y, [0 1 0 0 0 0 0 0 0 0]);
-%!  assert(so,0);
-%!
+%! a = [1,1];
+%! b = [1,1];
+%! x = zeros (1,10);  x(1) = 1;
+%! [y, so] = filter (b, [1], x, [-1]);
+%! assert (y, [0 1 0 0 0 0 0 0 0 0]);
+%! assert (so, 0);
+
 %!test
-%!  x  = zeros (10,3); x(1,1)=-1; x(1,2)=1;
-%!  y0 = zeros (10,3); y0(1:2,1)=-1; y0(1:2,2)=1;
-%!  y = filter (b, [1], x);
-%!  assert(y,y0);
-%!
+%! x  = zeros (10,3);  x(1,1) = -1;  x(1,2) = 1;
+%! y0 = zeros (10,3); y0(1:2,1) = -1;  y0(1:2,2) = 1;
+%! y = filter (b, [1], x);
+%! assert (y, y0);
+
 %!test
-%!  a = [1,1]; b=[1,1];
-%!  x = zeros (4,4,2); x(1,1:4,1) = +1; x(1,1:4,2) = -1;
-%!  y0 = zeros (4,4,2); y0(1:2,1:4,1) = +1; y0(1:2,1:4,2) = -1;
-%!  y = filter (b, [1], x);
-%!  assert(y, y0);
-%!
-%!assert(filter (1, ones(10,1)/10, []), []);
-%!assert(filter (1, ones(10,1)/10, zeros(0,10)), zeros(0,10));
-%!assert(filter (1, ones(10,1)/10, single (1:5)), repmat (single (10), 1, 5));
+%! a = [1,1];
+%! b=[1,1];
+%! x = zeros (4,4,2);  x(1,1:4,1) = +1;  x(1,1:4,2) = -1;
+%! y0 = zeros (4,4,2);  y0(1:2,1:4,1) = +1;  y0(1:2,1:4,2) = -1;
+%! y = filter (b, [1], x);
+%! assert (y, y0);
+
+%!assert (filter (1, ones (10,1) / 10, []), [])
+%!assert (filter (1, ones (10,1) / 10, zeros (0,10)), zeros (0,10))
+%!assert (filter (1, ones (10,1) / 10, single (1:5)), repmat (single (10), 1, 5))
+
 %% Test using initial conditions
-%!assert(filter([1, 1, 1], [1, 1], [1 2], [1, 1]), [2 2]);
-%!assert(filter([1, 1, 1], [1, 1], [1 2], [1, 1]'), [2 2]);
-%!assert(filter([1, 3], [1], [1 2; 3 4; 5 6], [4, 5]), [5 7; 6 10; 14 18]);
-%!error (filter([1, 3], [1], [1 2; 3 4; 5 6], [4, 5]'));
-%!assert(filter([1, 3, 2], [1], [1 2; 3 4; 5 6], [1 0 0; 1 0 0], 2), [2 6; 3 13; 5 21]);
-%% Test of DIM parameter
+%!assert (filter ([1, 1, 1], [1, 1], [1 2], [1, 1]), [2 2])
+%!assert (filter ([1, 1, 1], [1, 1], [1 2], [1, 1]'), [2 2])
+%!assert (filter ([1, 3], [1], [1 2; 3 4; 5 6], [4, 5]), [5 7; 6 10; 14 18])
+%!error (filter ([1, 3], [1], [1 2; 3 4; 5 6], [4, 5]'))
+%!assert (filter ([1, 3, 2], [1], [1 2; 3 4; 5 6], [1 0 0; 1 0 0], 2), [2 6; 3 13; 5 21])
+
+## Test of DIM parameter
 %!test
 %! x = ones (2, 1, 3, 4);
 %! x(1,1,:,:) = [1 2 3 4; 5 6 7 8; 9 10 11 12];
 %! y0 = [1 1 6 2 15 3 2 1 8 2 18 3 3 1 10 2 21 3 4 1 12 2 24 3];
 %! y0 = reshape (y0, size (x));
-%! y = filter([1 1 1], 1, x, [], 3);
+%! y = filter ([1 1 1], 1, x, [], 3);
 %! assert (y, y0);
-
 */
rename from src/DLD-FUNCTIONS/find.cc
rename to libinterp/corefcn/find.cc
--- a/src/DLD-FUNCTIONS/find.cc
+++ b/libinterp/corefcn/find.cc
@@ -26,7 +26,7 @@
 
 #include "quit.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -89,9 +89,9 @@
   octave_value_list retval ((nargout == 0 ? 1 : nargout), Matrix ());
 
 
-  octave_idx_type nc = v.cols();
-  octave_idx_type nr = v.rows();
-  octave_idx_type nz = v.nnz();
+  octave_idx_type nc = v.cols ();
+  octave_idx_type nr = v.rows ();
+  octave_idx_type nz = v.nnz ();
 
   // Search in the default range.
   octave_idx_type start_nc = -1;
@@ -111,9 +111,9 @@
       for (octave_idx_type j = 0; j < nc; j++)
         {
           OCTAVE_QUIT;
-          if (v.cidx(j) == 0 && v.cidx(j+1) != 0)
+          if (v.cidx (j) == 0 && v.cidx (j+1) != 0)
             start_nc = j;
-          if (v.cidx(j+1) >= n_to_find)
+          if (v.cidx (j+1) >= n_to_find)
             {
               end_nc = j + 1;
               break;
@@ -125,9 +125,9 @@
       for (octave_idx_type j = nc; j > 0; j--)
         {
           OCTAVE_QUIT;
-          if (v.cidx(j) == nz && v.cidx(j-1) != nz)
+          if (v.cidx (j) == nz && v.cidx (j-1) != nz)
             end_nc = j;
-          if (nz - v.cidx(j-1) >= n_to_find)
+          if (nz - v.cidx (j-1) >= n_to_find)
             {
               start_nc = j - 1;
               break;
@@ -135,8 +135,8 @@
         }
     }
 
-  count = (n_to_find > v.cidx(end_nc) - v.cidx(start_nc) ?
-           v.cidx(end_nc) - v.cidx(start_nc) : n_to_find);
+  count = (n_to_find > v.cidx (end_nc) - v.cidx (start_nc) ?
+           v.cidx (end_nc) - v.cidx (start_nc) : n_to_find);
 
   // If the original argument was a row vector, force a row vector of
   // the overall indices to be returned.  But see below for scalar
@@ -168,14 +168,14 @@
       // there are elements to be found using the count that we want
       // to find.
       for (octave_idx_type j = start_nc, cx = 0; j < end_nc; j++)
-        for (octave_idx_type i = v.cidx(j); i < v.cidx(j+1); i++ )
+        for (octave_idx_type i = v.cidx (j); i < v.cidx (j+1); i++ )
           {
             OCTAVE_QUIT;
             if (direction < 0 && i < nz - count)
               continue;
-            i_idx(cx) = static_cast<double> (v.ridx(i) + 1);
+            i_idx(cx) = static_cast<double> (v.ridx (i) + 1);
             j_idx(cx) = static_cast<double> (j + 1);
-            idx(cx) = j * nr + v.ridx(i) + 1;
+            idx(cx) = j * nr + v.ridx (i) + 1;
             val(cx) = v.data(i);
             cx++;
             if (cx == count)
@@ -231,7 +231,7 @@
   // There are far fewer special cases to handle for a PermMatrix.
   octave_value_list retval ((nargout == 0 ? 1 : nargout), Matrix ());
 
-  octave_idx_type nc = v.cols();
+  octave_idx_type nc = v.cols ();
   octave_idx_type start_nc, count;
 
   // Determine the range to search.
@@ -332,13 +332,13 @@
   return retval;
 }
 
-DEFUN_DLD (find, args, nargout,
+DEFUN (find, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{idx} =} find (@var{x})\n\
-@deftypefnx {Loadable Function} {@var{idx} =} find (@var{x}, @var{n})\n\
-@deftypefnx {Loadable Function} {@var{idx} =} find (@var{x}, @var{n}, @var{direction})\n\
-@deftypefnx {Loadable Function} {[i, j] =} find (@dots{})\n\
-@deftypefnx {Loadable Function} {[i, j, v] =} find (@dots{})\n\
+@deftypefn  {Built-in Function} {@var{idx} =} find (@var{x})\n\
+@deftypefnx {Built-in Function} {@var{idx} =} find (@var{x}, @var{n})\n\
+@deftypefnx {Built-in Function} {@var{idx} =} find (@var{x}, @var{n}, @var{direction})\n\
+@deftypefnx {Built-in Function} {[i, j] =} find (@dots{})\n\
+@deftypefnx {Built-in Function} {[i, j, v] =} find (@dots{})\n\
 Return a vector of indices of nonzero elements of a matrix, as a row if\n\
 @var{x} is a row vector or as a column otherwise.  To obtain a single index\n\
 for each matrix element, Octave pretends that the columns of a matrix form\n\
@@ -347,7 +347,7 @@
 @example\n\
 @group\n\
 find (eye (2))\n\
-     @result{} [ 1; 4 ]\n\
+  @result{} [ 1; 4 ]\n\
 @end group\n\
 @end example\n\
 \n\
@@ -357,8 +357,8 @@
 @example\n\
 @group\n\
 [i, j] = find (2 * eye (2))\n\
-     @result{} i = [ 1; 2 ]\n\
-     @result{} j = [ 1; 2 ]\n\
+    @result{} i = [ 1; 2 ]\n\
+    @result{} j = [ 1; 2 ]\n\
 @end group\n\
 @end example\n\
 \n\
@@ -368,9 +368,9 @@
 @example\n\
 @group\n\
 [i, j, v] = find (3 * eye (2))\n\
-     @result{} i = [ 1; 2 ]\n\
-     @result{} j = [ 1; 2 ]\n\
-     @result{} v = [ 3; 3 ]\n\
+       @result{} i = [ 1; 2 ]\n\
+       @result{} j = [ 1; 2 ]\n\
+       @result{} v = [ 3; 3 ]\n\
 @end group\n\
 @end example\n\
 \n\
@@ -570,28 +570,28 @@
 }
 
 /*
-%!assert(find (char ([0, 97])), 2);
-%!assert(find ([1, 0, 1, 0, 1]), [1, 3, 5]);
-%!assert(find ([1; 0; 3; 0; 1]), [1; 3; 5]);
-%!assert(find ([0, 0, 2; 0, 3, 0; -1, 0, 0]), [3; 5; 7]);
+%!assert (find (char ([0, 97])), 2)
+%!assert (find ([1, 0, 1, 0, 1]), [1, 3, 5])
+%!assert (find ([1; 0; 3; 0; 1]), [1; 3; 5])
+%!assert (find ([0, 0, 2; 0, 3, 0; -1, 0, 0]), [3; 5; 7])
 
 %!test
 %! [i, j, v] = find ([0, 0, 2; 0, 3, 0; -1, 0, 0]);
 %!
-%! assert(i, [3; 2; 1]);
-%! assert(j, [1; 2; 3]);
-%! assert(v, [-1; 3; 2]);
+%! assert (i, [3; 2; 1]);
+%! assert (j, [1; 2; 3]);
+%! assert (v, [-1; 3; 2]);
 
-%!assert(find (single([1, 0, 1, 0, 1])), [1, 3, 5]);
-%!assert(find (single([1; 0; 3; 0; 1])), [1; 3; 5]);
-%!assert(find (single([0, 0, 2; 0, 3, 0; -1, 0, 0])), [3; 5; 7]);
+%!assert (find (single ([1, 0, 1, 0, 1])), [1, 3, 5])
+%!assert (find (single ([1; 0; 3; 0; 1])), [1; 3; 5])
+%!assert (find (single ([0, 0, 2; 0, 3, 0; -1, 0, 0])), [3; 5; 7])
 
 %!test
-%! [i, j, v] = find (single([0, 0, 2; 0, 3, 0; -1, 0, 0]));
+%! [i, j, v] = find (single ([0, 0, 2; 0, 3, 0; -1, 0, 0]));
 %!
-%! assert(i, [3; 2; 1]);
-%! assert(j, [1; 2; 3]);
-%! assert(v, single([-1; 3; 2]));
+%! assert (i, [3; 2; 1]);
+%! assert (j, [1; 2; 3]);
+%! assert (v, single ([-1; 3; 2]));
 
 %!test
 %! pcol = [5 1 4 3 2];
@@ -617,6 +617,5 @@
 %!assert (find ([2 0 1 0 5 0], Inf), [1, 3, 5])
 %!assert (find ([2 0 1 0 5 0], Inf, "last"), [1, 3, 5])
 
-%!error <Invalid call to find> find ();
-
+%!error find ()
 */
rename from src/DLD-FUNCTIONS/gammainc.cc
rename to libinterp/corefcn/gammainc.cc
--- a/src/DLD-FUNCTIONS/gammainc.cc
+++ b/libinterp/corefcn/gammainc.cc
@@ -26,13 +26,13 @@
 
 #include "lo-specfun.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
 #include "utils.h"
 
-DEFUN_DLD (gammainc, args, ,
+DEFUN (gammainc, args, ,
   "-*- texinfo -*-\n\
 @deftypefn  {Mapping Function} {} gammainc (@var{x}, @var{a})\n\
 @deftypefnx {Mapping Function} {} gammainc (@var{x}, @var{a}, \"lower\")\n\
@@ -47,11 +47,11 @@
 \n\
 @example\n\
 @group\n\
-                                 x\n\
-                       1        /\n\
+                                x\n\
+                       1       /\n\
 gammainc (x, a) = ---------    | exp (-t) t^(a-1) dt\n\
-                   gamma (a)    /\n\
-                             t=0\n\
+                  gamma (a)    /\n\
+                            t=0\n\
 @end group\n\
 @end example\n\
 \n\
@@ -208,23 +208,23 @@
 }
 
 /*
-
 %!test
 %! a = [.5 .5 .5 .5 .5];
 %! x = [0 1 2 3 4];
-%! v1 = sqrt(pi)*erf(x)./gamma(a);
-%! v3 = gammainc(x.*x,a);
-%! assert(v1, v3, sqrt(eps));
+%! v1 = sqrt (pi)*erf (x)./gamma (a);
+%! v3 = gammainc (x.*x, a);
+%! assert (v1, v3, sqrt (eps));
 
-%!assert (gammainc(0:4,0.5,"upper"), 1-gammainc(0:4,0.5),1e-10)
+%!assert (gammainc (0:4,0.5, "upper"), 1-gammainc (0:4,0.5), 1e-10)
 
 %!test
 %! a = single ([.5 .5 .5 .5 .5]);
-%! x = single([0 1 2 3 4]);
-%! v1 = sqrt(pi('single'))*erf(x)./gamma(a);
-%! v3 = gammainc(x.*x,a);
-%! assert(v1, v3, sqrt(eps('single')));
+%! x = single ([0 1 2 3 4]);
+%! v1 = sqrt (pi ("single"))*erf (x)./gamma (a);
+%! v3 = gammainc (x.*x, a);
+%! assert (v1, v3, sqrt (eps ("single")));
 
-%!assert (gammainc(single(0:4),single(0.5),"upper"), single(1)-gammainc(single(0:4),single(0.5)),single(1e-7))
-
+%!assert (gammainc (single (0:4), single (0.5), "upper"), 
+%!        single (1)-gammainc (single (0:4), single (0.5)),
+%!        single (1e-7))
 */
rename from src/DLD-FUNCTIONS/gcd.cc
rename to libinterp/corefcn/gcd.cc
--- a/src/DLD-FUNCTIONS/gcd.cc
+++ b/libinterp/corefcn/gcd.cc
@@ -32,7 +32,7 @@
 #include "lo-mappers.h"
 #include "oct-binmap.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "oct-obj.h"
 
@@ -76,8 +76,8 @@
 static std::complex<FP>
 simple_gcd (const std::complex<FP>& a, const std::complex<FP>& b)
 {
-  if (! xisinteger (a.real ()) || ! xisinteger(a.imag ())
-      || ! xisinteger (b.real ()) || ! xisinteger(b.imag ()))
+  if (! xisinteger (a.real ()) || ! xisinteger (a.imag ())
+      || ! xisinteger (b.real ()) || ! xisinteger (b.imag ()))
     (*current_liboctave_error_handler)
       ("gcd: all complex parts must be integers");
 
@@ -156,8 +156,8 @@
 extended_gcd (const std::complex<FP>& a, const std::complex<FP>& b,
               std::complex<FP>& x, std::complex<FP>& y)
 {
-  if (! xisinteger (a.real ()) || ! xisinteger(a.imag ())
-      || ! xisinteger (b.real ()) || ! xisinteger(b.imag ()))
+  if (! xisinteger (a.real ()) || ! xisinteger (a.imag ())
+      || ! xisinteger (b.real ()) || ! xisinteger (b.imag ()))
     (*current_liboctave_error_handler)
       ("gcd: all complex parts must be integers");
 
@@ -432,10 +432,10 @@
   return retval;
 }
 
-DEFUN_DLD (gcd, args, nargout,
+DEFUN (gcd, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{g} =} gcd (@var{a1}, @var{a2}, @dots{})\n\
-@deftypefnx {Loadable Function} {[@var{g}, @var{v1}, @dots{}] =} gcd (@var{a1}, @var{a2}, @dots{})\n\
+@deftypefn  {Built-in Function} {@var{g} =} gcd (@var{a1}, @var{a2}, @dots{})\n\
+@deftypefnx {Built-in Function} {[@var{g}, @var{v1}, @dots{}] =} gcd (@var{a1}, @var{a2}, @dots{})\n\
 \n\
 Compute the greatest common divisor of @var{a1}, @var{a2}, @dots{}.  If more\n\
 than one argument is given all arguments must be the same size or scalar.\n\
@@ -443,15 +443,14 @@
 individually.  All elements must be ordinary or Gaussian (complex)\n\
 integers.  Note that for Gaussian integers, the gcd is not unique up to\n\
 units (multiplication by 1, -1, @var{i} or -@var{i}), so an arbitrary\n\
-greatest common divisor amongst four possible is returned.  For example,\n\
+greatest common divisor amongst four possible is returned.\n\
 \n\
-@noindent\n\
-and\n\
+Example code:\n\
 \n\
 @example\n\
 @group\n\
 gcd ([15, 9], [20, 18])\n\
-    @result{}  5  9\n\
+   @result{}  5  9\n\
 @end group\n\
 @end example\n\
 \n\
@@ -516,16 +515,14 @@
 }
 
 /*
+%!assert (gcd (200, 300, 50, 35), 5)
+%!assert (gcd (int16 (200), int16 (300), int16 (50), int16 (35)), int16 (5))
+%!assert (gcd (uint64 (200), uint64 (300), uint64 (50), uint64 (35)), uint64 (5))
+%!assert (gcd (18-i, -29+3i), -3-4i)
 
-%!assert(gcd (200, 300, 50, 35), 5)
-%!assert(gcd (int16(200), int16(300), int16(50), int16(35)), int16(5))
-%!assert(gcd (uint64(200), uint64(300), uint64(50), uint64(35)), uint64(5))
-%!assert(gcd (18-i, -29+3i), -3-4i)
-
-%!error <Invalid call to gcd> gcd ();
+%!error gcd ()
 
 %!test
 %! s.a = 1;
-%! fail("gcd (s)");
-
+%! fail ("gcd (s)");
 */
rename from src/DLD-FUNCTIONS/getgrent.cc
rename to libinterp/corefcn/getgrent.cc
--- a/src/DLD-FUNCTIONS/getgrent.cc
+++ b/libinterp/corefcn/getgrent.cc
@@ -30,7 +30,7 @@
 
 #include "oct-group.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-map.h"
@@ -62,9 +62,9 @@
   return retval;
 }
 
-DEFUN_DLD (getgrent, args, ,
+DEFUN (getgrent, args, ,
  "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{grp_struct} =} getgrent ()\n\
+@deftypefn {Built-in Function} {@var{grp_struct} =} getgrent ()\n\
 Return an entry from the group database, opening it if necessary.\n\
 Once the end of data has been reached, @code{getgrent} returns 0.\n\
 @end deftypefn")
@@ -89,9 +89,9 @@
   return retval;
 }
 
-DEFUN_DLD (getgrgid, args, ,
+DEFUN (getgrgid, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{grp_struct} =} getgrgid (@var{gid}).\n\
+@deftypefn {Built-in Function} {@var{grp_struct} =} getgrgid (@var{gid}).\n\
 Return the first entry from the group database with the group ID\n\
 @var{gid}.  If the group ID does not exist in the database,\n\
 @code{getgrgid} returns 0.\n\
@@ -129,9 +129,9 @@
   return retval;
 }
 
-DEFUN_DLD (getgrnam, args, ,
+DEFUN (getgrnam, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{grp_struct} =} getgrnam (@var{name})\n\
+@deftypefn {Built-in Function} {@var{grp_struct} =} getgrnam (@var{name})\n\
 Return the first entry from the group database with the group name\n\
 @var{name}.  If the group name does not exist in the database,\n\
 @code{getgrnam} returns 0.\n\
@@ -162,9 +162,9 @@
   return retval;
 }
 
-DEFUN_DLD (setgrent, args, ,
+DEFUN (setgrent, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} setgrent ()\n\
+@deftypefn {Built-in Function} {} setgrent ()\n\
 Return the internal pointer to the beginning of the group database.\n\
 @end deftypefn")
 {
@@ -188,9 +188,9 @@
   return retval;
 }
 
-DEFUN_DLD (endgrent, args, ,
+DEFUN (endgrent, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} endgrent ()\n\
+@deftypefn {Built-in Function} {} endgrent ()\n\
 Close the group database.\n\
 @end deftypefn")
 {
rename from src/DLD-FUNCTIONS/getpwent.cc
rename to libinterp/corefcn/getpwent.cc
--- a/src/DLD-FUNCTIONS/getpwent.cc
+++ b/libinterp/corefcn/getpwent.cc
@@ -30,7 +30,7 @@
 
 #include "oct-passwd.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-map.h"
@@ -65,9 +65,9 @@
   return retval;
 }
 
-DEFUN_DLD (getpwent, args, ,
+DEFUN (getpwent, args, ,
  "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{pw_struct} =} getpwent ()\n\
+@deftypefn {Built-in Function} {@var{pw_struct} =} getpwent ()\n\
 Return a structure containing an entry from the password database,\n\
 opening it if necessary.  Once the end of the data has been reached,\n\
 @code{getpwent} returns 0.\n\
@@ -93,9 +93,9 @@
   return retval;
 }
 
-DEFUN_DLD (getpwuid, args, ,
+DEFUN (getpwuid, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{pw_struct} =} getpwuid (@var{uid}).\n\
+@deftypefn {Built-in Function} {@var{pw_struct} =} getpwuid (@var{uid}).\n\
 Return a structure containing the first entry from the password database\n\
 with the user ID @var{uid}.  If the user ID does not exist in the\n\
 database, @code{getpwuid} returns 0.\n\
@@ -133,9 +133,9 @@
   return retval;
 }
 
-DEFUN_DLD (getpwnam, args, ,
+DEFUN (getpwnam, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{pw_struct} =} getpwnam (@var{name})\n\
+@deftypefn {Built-in Function} {@var{pw_struct} =} getpwnam (@var{name})\n\
 Return a structure containing the first entry from the password database\n\
 with the user name @var{name}.  If the user name does not exist in the\n\
 database, @code{getpwname} returns 0.\n\
@@ -166,9 +166,9 @@
   return retval;
 }
 
-DEFUN_DLD (setpwent, args, ,
+DEFUN (setpwent, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} setpwent ()\n\
+@deftypefn {Built-in Function} {} setpwent ()\n\
 Return the internal pointer to the beginning of the password database.\n\
 @end deftypefn")
 {
@@ -192,9 +192,9 @@
   return retval;
 }
 
-DEFUN_DLD (endpwent, args, ,
+DEFUN (endpwent, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} endpwent ()\n\
+@deftypefn {Built-in Function} {} endpwent ()\n\
 Close the password database.\n\
 @end deftypefn")
 {
rename from src/DLD-FUNCTIONS/getrusage.cc
rename to libinterp/corefcn/getrusage.cc
--- a/src/DLD-FUNCTIONS/getrusage.cc
+++ b/libinterp/corefcn/getrusage.cc
@@ -36,7 +36,7 @@
 #include <sys/param.h>
 #endif
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "oct-map.h"
 #include "sysdep.h"
 #include "ov.h"
@@ -59,9 +59,9 @@
 
 // System resource functions.
 
-DEFUN_DLD (getrusage, , ,
+DEFUN (getrusage, , ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} getrusage ()\n\
+@deftypefn {Built-in Function} {} getrusage ()\n\
 Return a structure containing a number of statistics about the current\n\
 Octave process.  Not all fields are available on all systems.  If it is\n\
 not possible to get CPU time statistics, the CPU time slots are set to\n\
rename from src/DLD-FUNCTIONS/givens.cc
rename to libinterp/corefcn/givens.cc
--- a/src/DLD-FUNCTIONS/givens.cc
+++ b/libinterp/corefcn/givens.cc
@@ -26,14 +26,14 @@
 #include <config.h>
 #endif
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "oct-obj.h"
 
-DEFUN_DLD (givens, args, nargout,
+DEFUN (givens, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{g} =} givens (@var{x}, @var{y})\n\
-@deftypefnx {Loadable Function} {[@var{c}, @var{s}] =} givens (@var{x}, @var{y})\n\
+@deftypefn  {Built-in Function} {@var{g} =} givens (@var{x}, @var{y})\n\
+@deftypefnx {Built-in Function} {[@var{c}, @var{s}] =} givens (@var{x}, @var{y})\n\
 @tex\n\
 Return a $2\\times 2$ orthogonal matrix\n\
 $$\n\
@@ -56,8 +56,8 @@
 @example\n\
 @group\n\
 givens (1, 1)\n\
-     @result{}   0.70711   0.70711\n\
-         -0.70711   0.70711\n\
+   @result{}   0.70711   0.70711\n\
+       -0.70711   0.70711\n\
 @end group\n\
 @end example\n\
 @end deftypefn")
@@ -205,11 +205,10 @@
 }
 
 /*
+%!assert (givens (1,1), [1, 1; -1, 1] / sqrt (2), 2*eps)
+%!assert (givens (1,0), eye (2))
+%!assert (givens (0,1), [0, 1; -1 0])
 
-%!assert (givens (1,1), [1, 1; -1, 1]/sqrt(2), 2*eps);
-%!assert (givens (1,0), eye(2));
-%!assert (givens (0,1), [0, 1; -1 0]);
-%!error givens(1);
-%!error givens()
-
+%!error givens ()
+%!error givens (1)
 */
rename from src/DLD-FUNCTIONS/hess.cc
rename to libinterp/corefcn/hess.cc
--- a/src/DLD-FUNCTIONS/hess.cc
+++ b/libinterp/corefcn/hess.cc
@@ -29,16 +29,16 @@
 #include "fCmplxHESS.h"
 #include "floatHESS.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
 #include "utils.h"
 
-DEFUN_DLD (hess, args, nargout,
+DEFUN (hess, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{H} =} hess (@var{A})\n\
-@deftypefnx {Loadable Function} {[@var{P}, @var{H}] =} hess (@var{A})\n\
+@deftypefn  {Built-in Function} {@var{H} =} hess (@var{A})\n\
+@deftypefnx {Built-in Function} {[@var{P}, @var{H}] =} hess (@var{A})\n\
 @cindex Hessenberg decomposition\n\
 Compute the Hessenberg decomposition of the matrix @var{A}.\n\
 \n\
@@ -173,19 +173,17 @@
 }
 
 /*
-
 %!test
 %! a = [1, 2, 3; 5, 4, 6; 8, 7, 9];
 %! [p, h] = hess (a);
-%! assert(p * h * p', a, sqrt(eps));
+%! assert (p * h * p', a, sqrt (eps));
 
 %!test
-%! a = single([1, 2, 3; 5, 4, 6; 8, 7, 9]);
+%! a = single ([1, 2, 3; 5, 4, 6; 8, 7, 9]);
 %! [p, h] = hess (a);
-%! assert(p * h * p', a, sqrt(eps ('single')));
+%! assert (p * h * p', a, sqrt (eps ("single")));
 
-%!error <Invalid call to hess> hess ();
-%!error <Invalid call to hess> hess ([1, 2; 3, 4], 2);
-%!error hess ([1, 2; 3, 4; 5, 6]);
-
+%!error hess ()
+%!error hess ([1, 2; 3, 4], 2)
+%!error <argument must be a square matrix> hess ([1, 2; 3, 4; 5, 6])
 */
rename from src/DLD-FUNCTIONS/hex2num.cc
rename to libinterp/corefcn/hex2num.cc
--- a/src/DLD-FUNCTIONS/hex2num.cc
+++ b/libinterp/corefcn/hex2num.cc
@@ -26,15 +26,15 @@
 
 #include <algorithm>
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
 #include "utils.h"
 
-DEFUN_DLD (hex2num, args, ,
+DEFUN (hex2num, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{n} =} hex2num (@var{s})\n\
+@deftypefn {Built-in Function} {@var{n} =} hex2num (@var{s})\n\
 Typecast the 16 character hexadecimal character string to an IEEE 754\n\
 double precision number.  If fewer than 16 characters are given the\n\
 strings are right padded with '0' characters.\n\
@@ -44,8 +44,8 @@
 \n\
 @example\n\
 @group\n\
-hex2num ([\"4005bf0a8b145769\";\"4024000000000000\"])\n\
-@result{} [2.7183; 10.000]\n\
+hex2num ([\"4005bf0a8b145769\"; \"4024000000000000\"])\n\
+   @result{} [2.7183; 10.000]\n\
 @end group\n\
 @end example\n\
 @seealso{num2hex, hex2dec, dec2hex}\n\
@@ -119,18 +119,18 @@
 }
 
 /*
-%!assert (hex2num(['c00';'bff';'000';'3ff';'400']),[-2:2]')
+%!assert (hex2num (["c00";"bff";"000";"3ff";"400"]), [-2:2]')
 */
 
-DEFUN_DLD (num2hex, args, ,
+DEFUN (num2hex, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{s} =} num2hex (@var{n})\n\
+@deftypefn {Built-in Function} {@var{s} =} num2hex (@var{n})\n\
 Typecast a double precision number or vector to a 16 character hexadecimal\n\
 string of the IEEE 754 representation of the number.  For example:\n\
 \n\
 @example\n\
 @group\n\
-num2hex ([-1, 1, e, Inf, NaN, NA]);\n\
+num2hex ([-1, 1, e, Inf, NaN, NA])\n\
 @result{} \"bff0000000000000\n\
     3ff0000000000000\n\
     4005bf0a8b145769\n\
@@ -188,5 +188,5 @@
 }
 
 /*
-%!assert (num2hex (-2:2),['c000000000000000';'bff0000000000000';'0000000000000000';'3ff0000000000000';'4000000000000000'])
+%!assert (num2hex (-2:2), ["c000000000000000";"bff0000000000000";"0000000000000000";"3ff0000000000000";"4000000000000000"])
 */
rename from src/DLD-FUNCTIONS/inv.cc
rename to libinterp/corefcn/inv.cc
--- a/src/DLD-FUNCTIONS/inv.cc
+++ b/libinterp/corefcn/inv.cc
@@ -24,7 +24,7 @@
 #include <config.h>
 #endif
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -36,10 +36,10 @@
 #include "ov-perm.h"
 #include "utils.h"
 
-DEFUN_DLD (inv, args, nargout,
+DEFUN (inv, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{x} =} inv (@var{A})\n\
-@deftypefnx {Loadable Function} {[@var{x}, @var{rcond}] =} inv (@var{A})\n\
+@deftypefn  {Built-in Function} {@var{x} =} inv (@var{A})\n\
+@deftypefnx {Built-in Function} {[@var{x}, @var{rcond}] =} inv (@var{A})\n\
 Compute the inverse of the square matrix @var{A}.  Return an estimate\n\
 of the reciprocal condition number if requested, otherwise warn of an\n\
 ill-conditioned matrix if the reciprocal condition number is small.\n\
@@ -224,24 +224,22 @@
 }
 
 /*
-
-%!assert(inv ([1, 2; 3, 4]), [-2, 1; 1.5, -0.5], sqrt (eps))
-%!assert(inv (single([1, 2; 3, 4])), single([-2, 1; 1.5, -0.5]), sqrt (eps ('single')))
+%!assert (inv ([1, 2; 3, 4]), [-2, 1; 1.5, -0.5], sqrt (eps))
+%!assert (inv (single ([1, 2; 3, 4])), single ([-2, 1; 1.5, -0.5]), sqrt (eps ("single")))
 
-%!error <Invalid call to inv> inv ();
-%!error <Invalid call to inv> inv ([1, 2; 3, 4], 2);
-%!error inv ([1, 2; 3, 4; 5, 6]);
-
- */
+%!error inv ()
+%!error inv ([1, 2; 3, 4], 2)
+%!error <argument must be a square matrix> inv ([1, 2; 3, 4; 5, 6])
+*/
 
 // FIXME -- this should really be done with an alias, but
 // alias_builtin() won't do the right thing if we are actually using
 // dynamic linking.
 
-DEFUN_DLD (inverse, args, nargout,
+DEFUN (inverse, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{x} =} inverse (@var{A})\n\
-@deftypefnx {Loadable Function} {[@var{x}, @var{rcond}] =} inverse (@var{A})\n\
+@deftypefn  {Built-in Function} {@var{x} =} inverse (@var{A})\n\
+@deftypefnx {Built-in Function} {[@var{x}, @var{rcond}] =} inverse (@var{A})\n\
 Compute the inverse of the square matrix @var{A}.\n\
 \n\
 This is an alias for @code{inv}.\n\
rename from src/DLD-FUNCTIONS/kron.cc
rename to libinterp/corefcn/kron.cc
--- a/src/DLD-FUNCTIONS/kron.cc
+++ b/libinterp/corefcn/kron.cc
@@ -44,7 +44,7 @@
 #include "mx-inlines.cc"
 #include "quit.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "oct-obj.h"
 
@@ -82,13 +82,13 @@
   octave_idx_type nra = a.rows (), nrb = b.rows (), dla = a.diag_length ();
   octave_idx_type nca = a.cols (), ncb = b.cols ();
 
-  MArray<T> c (dim_vector (nra*nrb, nca*ncb), T());
+  MArray<T> c (dim_vector (nra*nrb, nca*ncb), T ());
 
   for (octave_idx_type ja = 0; ja < dla; ja++)
     for (octave_idx_type jb = 0; jb < ncb; jb++)
       {
         octave_quit ();
-        mx_inline_mul (nrb, &c.xelem(ja*nrb, ja*ncb + jb), a.dgelem (ja), b.data () + nrb*jb);
+        mx_inline_mul (nrb, &c.xelem (ja*nrb, ja*ncb + jb), a.dgelem (ja), b.data () + nrb*jb);
       }
 
   return c;
@@ -110,7 +110,7 @@
         octave_quit ();
         for (octave_idx_type Ai = A.cidx (Aj); Ai < A.cidx (Aj+1); Ai++)
           {
-            octave_idx_type Ci = A.ridx(Ai) * B.rows ();
+            octave_idx_type Ci = A.ridx (Ai) * B.rows ();
             const T v = A.data (Ai);
 
             for (octave_idx_type Bi = B.cidx (Bj); Bi < B.cidx (Bj+1); Bi++)
@@ -177,6 +177,13 @@
   octave_value retval;
   if (a.is_perm_matrix () && b.is_perm_matrix ())
     retval = do_kron<PermMatrix, PermMatrix> (a, b);
+  else if (a.is_sparse_type () || b.is_sparse_type ())
+    {
+      if (a.is_complex_type () || b.is_complex_type ())
+        retval = do_kron<SparseComplexMatrix, SparseComplexMatrix> (a, b);
+      else
+        retval = do_kron<SparseMatrix, SparseMatrix> (a, b);
+    }
   else if (a.is_diag_matrix ())
     {
       if (b.is_diag_matrix () && a.rows () == a.columns ()
@@ -214,13 +221,6 @@
             retval = do_kron<DiagMatrix, Matrix> (a, b);
         }
     }
-  else if (a.is_sparse_type () || b.is_sparse_type ())
-    {
-      if (a.is_complex_type () || b.is_complex_type ())
-        retval = do_kron<SparseComplexMatrix, SparseComplexMatrix> (a, b);
-      else
-        retval = do_kron<SparseMatrix, SparseMatrix> (a, b);
-    }
   else if (a.is_single_type () || b.is_single_type ())
     {
       if (a.is_complex_type ())
@@ -243,14 +243,14 @@
 }
 
 
-DEFUN_DLD (kron, args, , "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} kron (@var{A}, @var{B})\n\
-@deftypefnx {Loadable Function} {} kron (@var{A1}, @var{A2}, @dots{})\n\
+DEFUN (kron, args, , "-*- texinfo -*-\n\
+@deftypefn  {Built-in Function} {} kron (@var{A}, @var{B})\n\
+@deftypefnx {Built-in Function} {} kron (@var{A1}, @var{A2}, @dots{})\n\
 Form the Kronecker product of two or more matrices, defined block by \n\
 block as\n\
 \n\
 @example\n\
-x = [a(i, j) b]\n\
+x = [ a(i,j)*b ]\n\
 @end example\n\
 \n\
 For example:\n\
@@ -258,9 +258,9 @@
 @example\n\
 @group\n\
 kron (1:4, ones (3, 1))\n\
-      @result{}  1  2  3  4\n\
-          1  2  3  4\n\
-          1  2  3  4\n\
+     @result{}  1  2  3  4\n\
+         1  2  3  4\n\
+         1  2  3  4\n\
 @end group\n\
 @end example\n\
 \n\
@@ -295,8 +295,8 @@
 
 /*
 %!test
-%! x = ones(2);
-%! assert( kron (x, x), ones (4));
+%! x = ones (2);
+%! assert (kron (x, x), ones (4));
 
 %!shared x, y, z
 %! x =  [1, 2];
@@ -306,7 +306,6 @@
 %!assert (kron (x, y, z), kron (kron (x, y), z))
 %!assert (kron (x, y, z), kron (x, kron (y, z)))
 
-
 %!assert (kron (diag ([1, 2]), diag ([3, 4])), diag ([3, 4, 6, 8]))
 
 %% Test for two diag matrices.  See the comments above in
rename from src/DLD-FUNCTIONS/lookup.cc
rename to libinterp/corefcn/lookup.cc
--- a/src/DLD-FUNCTIONS/lookup.cc
+++ b/libinterp/corefcn/lookup.cc
@@ -34,7 +34,7 @@
 #include "CNDArray.h"
 
 #include "Cell.h"
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -70,7 +70,7 @@
 {
   return std::lexicographical_compare (a.begin (), a.end (),
                                        b.begin (), b.end (),
-                                       icmp_char_lt());
+                                       icmp_char_lt ());
 }
 
 // case-insensitive descending comparator
@@ -79,7 +79,7 @@
 {
   return std::lexicographical_compare (a.begin (), a.end (),
                                        b.begin (), b.end (),
-                                       icmp_char_gt());
+                                       icmp_char_gt ());
 }
 #endif
 
@@ -186,10 +186,10 @@
   return retval;
 }
 
-DEFUN_DLD (lookup, args, ,
+DEFUN (lookup, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{idx} =} lookup (@var{table}, @var{y})\n\
-@deftypefnx {Loadable Function} {@var{idx} =} lookup (@var{table}, @var{y}, @var{opt})\n\
+@deftypefn  {Built-in Function} {@var{idx} =} lookup (@var{table}, @var{y})\n\
+@deftypefnx {Built-in Function} {@var{idx} =} lookup (@var{table}, @var{y}, @var{opt})\n\
 Lookup values in a sorted table.  Usually used as a prelude to\n\
 interpolation.\n\
 \n\
@@ -373,25 +373,25 @@
 }
 
 /*
-%!assert (lookup(1:3, 0.5), 0)     # value before table
-%!assert (lookup(1:3, 3.5), 3)     # value after table error
-%!assert (lookup(1:3, 1.5), 1)     # value within table error
-%!assert (lookup(1:3, [3,2,1]), [3,2,1])
-%!assert (lookup([1:4]', [1.2, 3.5]'), [1, 3]');
-%!assert (lookup([1:4], [1.2, 3.5]'), [1, 3]');
-%!assert (lookup([1:4]', [1.2, 3.5]), [1, 3]);
-%!assert (lookup([1:4], [1.2, 3.5]), [1, 3]);
-%!assert (lookup(1:3, [3, 2, 1]), [3, 2, 1]);
-%!assert (lookup([3:-1:1], [3.5, 3, 1.2, 2.5, 2.5]), [0, 1, 2, 1, 1])
-%!assert (isempty(lookup([1:3], [])))
-%!assert (isempty(lookup([1:3]', [])))
-%!assert (lookup(1:3, [1, 2; 3, 0.5]), [1, 2; 3, 0]);
-%!assert (lookup(1:4, [1, 1.2; 3, 2.5], "m"), [1, 0; 3, 0]);
-%!assert (lookup(4:-1:1, [1, 1.2; 3, 2.5], "m"), [4, 0; 2, 0]);
-%!assert (lookup(1:4, [1, 1.2; 3, 2.5], "b"), logical ([1, 0; 3, 0]));
-%!assert (lookup(4:-1:1, [1, 1.2; 3, 2.5], "b"), logical ([4, 0; 2, 0]));
+%!assert (lookup (1:3, 0.5), 0)     # value before table
+%!assert (lookup (1:3, 3.5), 3)     # value after table error
+%!assert (lookup (1:3, 1.5), 1)     # value within table error
+%!assert (lookup (1:3, [3,2,1]), [3,2,1])
+%!assert (lookup ([1:4]', [1.2, 3.5]'), [1, 3]')
+%!assert (lookup ([1:4], [1.2, 3.5]'), [1, 3]')
+%!assert (lookup ([1:4]', [1.2, 3.5]), [1, 3])
+%!assert (lookup ([1:4], [1.2, 3.5]), [1, 3])
+%!assert (lookup (1:3, [3, 2, 1]), [3, 2, 1])
+%!assert (lookup ([3:-1:1], [3.5, 3, 1.2, 2.5, 2.5]), [0, 1, 2, 1, 1])
+%!assert (isempty (lookup ([1:3], [])))
+%!assert (isempty (lookup ([1:3]', [])))
+%!assert (lookup (1:3, [1, 2; 3, 0.5]), [1, 2; 3, 0])
+%!assert (lookup (1:4, [1, 1.2; 3, 2.5], "m"), [1, 0; 3, 0])
+%!assert (lookup (4:-1:1, [1, 1.2; 3, 2.5], "m"), [4, 0; 2, 0])
+%!assert (lookup (1:4, [1, 1.2; 3, 2.5], "b"), logical ([1, 0; 3, 0]))
+%!assert (lookup (4:-1:1, [1, 1.2; 3, 2.5], "b"), logical ([4, 0; 2, 0]))
 %!
-%!assert (lookup({"apple","lemon","orange"}, {"banana","kiwi"; "ananas","mango"}), [1,1;0,2])
-%!assert (lookup({"apple","lemon","orange"}, "potato"), 3)
-%!assert (lookup({"orange","lemon","apple"}, "potato"), 0)
+%!assert (lookup ({"apple","lemon","orange"}, {"banana","kiwi"; "ananas","mango"}), [1,1;0,2])
+%!assert (lookup ({"apple","lemon","orange"}, "potato"), 3)
+%!assert (lookup ({"orange","lemon","apple"}, "potato"), 0)
 */
rename from src/DLD-FUNCTIONS/lsode.cc
rename to libinterp/corefcn/lsode.cc
--- a/src/DLD-FUNCTIONS/lsode.cc
+++ b/libinterp/corefcn/lsode.cc
@@ -32,7 +32,7 @@
 #include "LSODE.h"
 #include "lo-mappers.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -156,10 +156,10 @@
     } \
   while (0)
 
-DEFUN_DLD (lsode, args, nargout,
+DEFUN (lsode, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {[@var{x}, @var{istate}, @var{msg}] =} lsode (@var{fcn}, @var{x_0}, @var{t})\n\
-@deftypefnx {Loadable Function} {[@var{x}, @var{istate}, @var{msg}] =} lsode (@var{fcn}, @var{x_0}, @var{t}, @var{t_crit})\n\
+@deftypefn  {Built-in Function} {[@var{x}, @var{istate}, @var{msg}] =} lsode (@var{fcn}, @var{x_0}, @var{t})\n\
+@deftypefnx {Built-in Function} {[@var{x}, @var{istate}, @var{msg}] =} lsode (@var{fcn}, @var{x_0}, @var{t}, @var{t_crit})\n\
 Solve the set of differential equations\n\
 @tex\n\
 $$ {dx \\over dt} = f (x, t) $$\n\
@@ -171,7 +171,7 @@
 @example\n\
 @group\n\
 dx\n\
--- = f(x, t)\n\
+-- = f (x, t)\n\
 dt\n\
 @end group\n\
 @end example\n\
@@ -298,9 +298,9 @@
       if (f_arg.is_cell ())
         {
           Cell c = f_arg.cell_value ();
-          if (c.length() == 1)
+          if (c.length () == 1)
             f_arg = c(0);
-          else if (c.length() == 2)
+          else if (c.length () == 2)
             {
               if (c(0).is_function_handle () || c(0).is_inline_function ())
                 lsode_fcn = c(0).function_value ();
@@ -322,14 +322,14 @@
                     {
                         jac_name = unique_symbol_name ("__lsode_jac__");
                         jname = "function jac = ";
-                        jname.append(jac_name);
+                        jname.append (jac_name);
                         jname.append (" (x, t) jac = ");
                         lsode_jac = extract_function
                           (c(1), "lsode", jac_name, jname, "; endfunction");
 
                       if (!lsode_jac)
                         {
-                          if (fcn_name.length())
+                          if (fcn_name.length ())
                             clear_function (fcn_name);
                           lsode_fcn = 0;
                         }
@@ -340,7 +340,7 @@
             LSODE_ABORT1 ("incorrect number of elements in cell array");
         }
 
-      if (!lsode_fcn && ! f_arg.is_cell())
+      if (!lsode_fcn && ! f_arg.is_cell ())
         {
           if (f_arg.is_function_handle () || f_arg.is_inline_function ())
             lsode_fcn = f_arg.function_value ();
@@ -378,7 +378,7 @@
                           {
                             jac_name = unique_symbol_name ("__lsode_jac__");
                             jname = "function jac = ";
-                            jname.append(jac_name);
+                            jname.append (jac_name);
                             jname.append (" (x, t) jac = ");
                             lsode_jac = extract_function
                               (tmp(1), "lsode", jac_name, jname,
@@ -386,7 +386,7 @@
 
                             if (!lsode_jac)
                               {
-                                if (fcn_name.length())
+                                if (fcn_name.length ())
                                   clear_function (fcn_name);
                                 lsode_fcn = 0;
                               }
@@ -444,9 +444,9 @@
       else
         output = ode.integrate (out_times);
 
-      if (fcn_name.length())
+      if (fcn_name.length ())
         clear_function (fcn_name);
-      if (jac_name.length())
+      if (jac_name.length ())
         clear_function (jac_name);
 
       if (! error_state)
@@ -475,25 +475,27 @@
 
 /*
 
-%% dassl-1.m
-%%
-%% Test lsode() function
-%%
-%% Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
-%%         Comalco Research and Technology
-%%         20 May 1998
-%%
-%% Problem
-%%
-%%    y1' = -y2,   y1(0) = 1
-%%    y2' =  y1,   y2(0) = 0
-%%
-%% Solution
-%%
-%%    y1(t) = cos(t)
-%%    y2(t) = sin(t)
+## dassl-1.m
+##
+## Test lsode() function
+##
+## Author: David Billinghurst (David.Billinghurst@riotinto.com.au)
+##         Comalco Research and Technology
+##         20 May 1998
+##
+## Problem
+##
+##    y1' = -y2,   y1(0) = 1
+##    y2' =  y1,   y2(0) = 0
+##
+## Solution
+##
+##    y1(t) = cos(t)
+##    y2(t) = sin(t)
+##
 %!function xdot = __f (x, t)
 %!  xdot = [-x(2); x(1)];
+%!endfunction
 %!test
 %!
 %! x0 = [1; 0];
@@ -502,15 +504,15 @@
 %!
 %! tol = 500 * lsode_options ("relative tolerance");
 %!
-%!
 %! x = lsode ("__f", x0, t);
 %!
 %! y = [cos(t), sin(t)];
 %!
-%! assert(all (all (abs (x - y) < tol)));
+%! assert (x, y, tol);
 
 %!function xdotdot = __f (x, t)
 %!  xdotdot = [x(2); -x(1)];
+%!endfunction
 %!test
 %!
 %! x0 = [1; 0];
@@ -521,10 +523,11 @@
 %!
 %! y = [1, 0; 1, 0];
 %!
-%! assert(all (all (abs (x - y) < tol)));
+%! assert (x, y, tol);
 
 %!function xdot = __f (x, t)
 %!  xdot = x;
+%!endfunction
 %!test
 %!
 %! x0 = 1;
@@ -535,12 +538,11 @@
 %!
 %! y = [1; e];
 %!
-%! assert(all (all (abs (x - y) < tol)));
+%! assert (x, y, tol);
 
 %!test
 %! lsode_options ("absolute tolerance", eps);
-%! assert(lsode_options ("absolute tolerance") == eps);
+%! assert (lsode_options ("absolute tolerance") == eps);
 
-%!error <Invalid call to lsode_options> lsode_options ("foo", 1, 2);
-
+%!error lsode_options ("foo", 1, 2)
 */
rename from src/DLD-FUNCTIONS/lu.cc
rename to libinterp/corefcn/lu.cc
--- a/src/DLD-FUNCTIONS/lu.cc
+++ b/libinterp/corefcn/lu.cc
@@ -31,7 +31,7 @@
 #include "SparseCmplxLU.h"
 #include "SparsedbleLU.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -61,15 +61,15 @@
     return U;
 }
 
-DEFUN_DLD (lu, args, nargout,
+DEFUN (lu, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {[@var{L}, @var{U}] =} lu (@var{A})\n\
-@deftypefnx {Loadable Function} {[@var{L}, @var{U}, @var{P}] =} lu (@var{A})\n\
-@deftypefnx {Loadable Function} {[@var{L}, @var{U}, @var{P}, @var{Q}] =} lu (@var{S})\n\
-@deftypefnx {Loadable Function} {[@var{L}, @var{U}, @var{P}, @var{Q}, @var{R}] =} lu (@var{S})\n\
-@deftypefnx {Loadable Function} {[@dots{}] =} lu (@var{S}, @var{thres})\n\
-@deftypefnx {Loadable Function} {@var{y} =} lu (@dots{})\n\
-@deftypefnx {Loadable Function} {[@dots{}] =} lu (@dots{}, 'vector')\n\
+@deftypefn  {Built-in Function} {[@var{L}, @var{U}] =} lu (@var{A})\n\
+@deftypefnx {Built-in Function} {[@var{L}, @var{U}, @var{P}] =} lu (@var{A})\n\
+@deftypefnx {Built-in Function} {[@var{L}, @var{U}, @var{P}, @var{Q}] =} lu (@var{S})\n\
+@deftypefnx {Built-in Function} {[@var{L}, @var{U}, @var{P}, @var{Q}, @var{R}] =} lu (@var{S})\n\
+@deftypefnx {Built-in Function} {[@dots{}] =} lu (@var{S}, @var{thres})\n\
+@deftypefnx {Built-in Function} {@var{y} =} lu (@dots{})\n\
+@deftypefnx {Built-in Function} {[@dots{}] =} lu (@dots{}, \"vector\")\n\
 @cindex LU decomposition\n\
 Compute the LU@tie{}decomposition of @var{A}.  If @var{A} is full\n\
 subroutines from\n\
@@ -125,7 +125,7 @@
 pivoting strategy and the second for the symmetric strategy.  By default,\n\
 the values defined by @code{spparms} are used ([0.1, 0.001]).\n\
 \n\
-Given the string argument 'vector', @code{lu} returns the values of @var{P}\n\
+Given the string argument \"vector\", @code{lu} returns the values of @var{P}\n\
 and @var{Q} as vector values, such that for full matrix, @code{@var{A}\n\
 (@var{P},:) = @var{L} * @var{U}}, and @code{@var{R}(@var{P},:) * @var{A}\n\
 (:, @var{Q}) = @var{L} * @var{U}}.\n\
@@ -179,7 +179,7 @@
                 error ("lu: can not define pivoting threshold THRES for full matrices");
               else if (tmp.nelem () == 1)
                 {
-                  thres.resize(1,2);
+                  thres.resize (1,2);
                   thres(0) = tmp(0);
                   thres(1) = tmp(0);
                 }
@@ -226,7 +226,7 @@
                 SparseLU fact (m, Qinit, thres, false, true);
 
                 if (nargout < 2)
-                  retval (0) = fact.Y ();
+                  retval(0) = fact.Y ();
                 else
                   {
                     PermMatrix P = fact.Pr_mat ();
@@ -246,7 +246,7 @@
                 SparseLU fact (m, Qinit, thres, false, true);
 
                 if (vecout)
-                  retval (2) = fact.Pr_vec ();
+                  retval(2) = fact.Pr_vec ();
                 else
                   retval(2) = fact.Pr_mat ();
 
@@ -296,7 +296,7 @@
                 SparseComplexLU fact (m, Qinit, thres, false, true);
 
                 if (nargout < 2)
-                  retval (0) = fact.Y ();
+                  retval(0) = fact.Y ();
                 else
                   {
                     PermMatrix P = fact.Pr_mat ();
@@ -316,7 +316,7 @@
                 SparseComplexLU fact (m, Qinit, thres, false, true);
 
                 if (vecout)
-                  retval (2) = fact.Pr_vec ();
+                  retval(2) = fact.Pr_vec ();
                 else
                   retval(2) = fact.Pr_mat ();
 
@@ -529,61 +529,59 @@
 }
 
 /*
-
 %!assert(lu ([1, 2; 3, 4]), [3, 4; 1/3, 2/3], eps);
 
 %!test
 %! [l, u] = lu ([1, 2; 3, 4]);
-%! assert(l, [1/3, 1; 1, 0], sqrt (eps));
-%! assert(u, [3, 4; 0, 2/3], sqrt (eps));
+%! assert (l, [1/3, 1; 1, 0], sqrt (eps));
+%! assert (u, [3, 4; 0, 2/3], sqrt (eps));
 
 %!test
 %! [l, u, p] = lu ([1, 2; 3, 4]);
-%! assert(l, [1, 0; 1/3, 1], sqrt (eps));
-%! assert(u, [3, 4; 0, 2/3], sqrt (eps));
-%! assert(p(:,:), [0, 1; 1, 0], sqrt (eps));
+%! assert (l, [1, 0; 1/3, 1], sqrt (eps));
+%! assert (u, [3, 4; 0, 2/3], sqrt (eps));
+%! assert (p(:,:), [0, 1; 1, 0], sqrt (eps));
 
 %!test
-%! [l, u, p] = lu ([1, 2; 3, 4],'vector');
-%! assert(l, [1, 0; 1/3, 1], sqrt (eps));
-%! assert(u, [3, 4; 0, 2/3], sqrt (eps));
-%! assert(p, [2;1], sqrt (eps));
+%! [l, u, p] = lu ([1, 2; 3, 4], "vector");
+%! assert (l, [1, 0; 1/3, 1], sqrt (eps));
+%! assert (u, [3, 4; 0, 2/3], sqrt (eps));
+%! assert (p, [2;1], sqrt (eps));
 
 %!test
-%! [l u p] = lu ([1, 2; 3, 4; 5, 6]);
-%! assert(l, [1, 0; 1/5, 1; 3/5, 1/2], sqrt (eps));
-%! assert(u, [5, 6; 0, 4/5], sqrt (eps));
-%! assert(p(:,:), [0, 0, 1; 1, 0, 0; 0 1 0], sqrt (eps));
+%! [l, u, p] = lu ([1, 2; 3, 4; 5, 6]);
+%! assert (l, [1, 0; 1/5, 1; 3/5, 1/2], sqrt (eps));
+%! assert (u, [5, 6; 0, 4/5], sqrt (eps));
+%! assert (p(:,:), [0, 0, 1; 1, 0, 0; 0 1 0], sqrt (eps));
 
-%!assert(lu (single([1, 2; 3, 4])), single([3, 4; 1/3, 2/3]), eps('single'));
+%!assert (lu (single ([1, 2; 3, 4])), single ([3, 4; 1/3, 2/3]), eps ("single"))
 
 %!test
-%! [l, u] = lu (single([1, 2; 3, 4]));
-%! assert(l, single([1/3, 1; 1, 0]), sqrt (eps('single')));
-%! assert(u, single([3, 4; 0, 2/3]), sqrt (eps('single')));
+%! [l, u] = lu (single ([1, 2; 3, 4]));
+%! assert (l, single ([1/3, 1; 1, 0]), sqrt (eps ("single")));
+%! assert (u, single ([3, 4; 0, 2/3]), sqrt (eps ("single")));
 
 %!test
-%! [l, u, p] = lu (single([1, 2; 3, 4]));
-%! assert(l, single([1, 0; 1/3, 1]), sqrt (eps('single')));
-%! assert(u, single([3, 4; 0, 2/3]), sqrt (eps('single')));
-%! assert(p(:,:), single([0, 1; 1, 0]), sqrt (eps('single')));
+%! [l, u, p] = lu (single ([1, 2; 3, 4]));
+%! assert (l, single ([1, 0; 1/3, 1]), sqrt (eps ("single")));
+%! assert (u, single ([3, 4; 0, 2/3]), sqrt (eps ("single")));
+%! assert (p(:,:), single ([0, 1; 1, 0]), sqrt (eps ("single")));
 
 %!test
-%! [l, u, p] = lu (single([1, 2; 3, 4]),'vector');
-%! assert(l, single([1, 0; 1/3, 1]), sqrt (eps('single')));
-%! assert(u, single([3, 4; 0, 2/3]), sqrt (eps('single')));
-%! assert(p, single([2;1]), sqrt (eps('single')));
+%! [l, u, p] = lu (single ([1, 2; 3, 4]), "vector");
+%! assert (l, single ([1, 0; 1/3, 1]), sqrt (eps ("single")));
+%! assert (u, single ([3, 4; 0, 2/3]), sqrt (eps ("single")));
+%! assert (p, single ([2;1]), sqrt (eps ("single")));
 
 %!test
-%! [l u p] = lu (single([1, 2; 3, 4; 5, 6]));
-%! assert(l, single([1, 0; 1/5, 1; 3/5, 1/2]), sqrt (eps('single')));
-%! assert(u, single([5, 6; 0, 4/5]), sqrt (eps('single')));
-%! assert(p(:,:), single([0, 0, 1; 1, 0, 0; 0 1 0]), sqrt (eps('single')));
+%! [l u p] = lu (single ([1, 2; 3, 4; 5, 6]));
+%! assert (l, single ([1, 0; 1/5, 1; 3/5, 1/2]), sqrt (eps ("single")));
+%! assert (u, single ([5, 6; 0, 4/5]), sqrt (eps ("single")));
+%! assert (p(:,:), single ([0, 0, 1; 1, 0, 0; 0 1 0]), sqrt (eps ("single")));
 
-%!error <Invalid call to lu> lu ();
-%!error lu ([1, 2; 3, 4], 2);
-
- */
+%!error lu ()
+%!error <can not define pivoting threshold> lu ([1, 2; 3, 4], 2)
+*/
 
 static
 bool check_lu_dims (const octave_value& l, const octave_value& u,
@@ -595,10 +593,10 @@
             (p.is_undefined () || p.rows () == m));
 }
 
-DEFUN_DLD (luupdate, args, ,
+DEFUN (luupdate, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {[@var{L}, @var{U}] =} luupdate (@var{L}, @var{U}, @var{x}, @var{y})\n\
-@deftypefnx {Loadable Function} {[@var{L}, @var{U}, @var{P}] =} luupdate (@var{L}, @var{U}, @var{P}, @var{x}, @var{y})\n\
+@deftypefn  {Built-in Function} {[@var{L}, @var{U}] =} luupdate (@var{L}, @var{U}, @var{x}, @var{y})\n\
+@deftypefnx {Built-in Function} {[@var{L}, @var{U}, @var{P}] =} luupdate (@var{L}, @var{U}, @var{P}, @var{x}, @var{y})\n\
 Given an LU@tie{}factorization of a real or complex matrix\n\
 @w{@var{A} = @var{L}*@var{U}}, @var{L}@tie{}lower unit trapezoidal and\n\
 @var{U}@tie{}upper trapezoidal, return the LU@tie{}factorization\n\
@@ -612,7 +610,7 @@
 as obtained by @code{lu}:\n\
 \n\
 @example\n\
-  [@var{L}, @var{U}, @var{P}] = lu (@var{A});\n\
+[@var{L}, @var{U}, @var{P}] = lu (@var{A});\n\
 @end example\n\
 \n\
 @noindent\n\
@@ -620,14 +618,14 @@
 either as\n\
 \n\
 @example\n\
-  [@var{L1}, @var{U1}] = lu (@var{L}, @var{U}, @var{P}*@var{x}, @var{y})\n\
+[@var{L1}, @var{U1}] = lu (@var{L}, @var{U}, @var{P}*@var{x}, @var{y})\n\
 @end example\n\
 \n\
 @noindent\n\
 or\n\
 \n\
 @example\n\
-  [@var{L1}, @var{U1}, @var{P1}] = lu (@var{L}, @var{U}, @var{P}, @var{x}, @var{y})\n\
+[@var{L1}, @var{U1}, @var{P1}] = lu (@var{L}, @var{U}, @var{P}, @var{x}, @var{y})\n\
 @end example\n\
 \n\
 The first form uses the unpivoted algorithm, which is faster, but less\n\
@@ -785,75 +783,75 @@
 %!      0.43167 ];
 %!
 %! Ac = [0.620405 + 0.956953i  0.480013 + 0.048806i  0.402627 + 0.338171i;
-%!      0.589077 + 0.658457i  0.013205 + 0.279323i  0.229284 + 0.721929i;
-%!      0.092758 + 0.345687i  0.928679 + 0.241052i  0.764536 + 0.832406i;
-%!      0.912098 + 0.721024i  0.049018 + 0.269452i  0.730029 + 0.796517i;
-%!      0.112849 + 0.603871i  0.486352 + 0.142337i  0.355646 + 0.151496i ];
+%!       0.589077 + 0.658457i  0.013205 + 0.279323i  0.229284 + 0.721929i;
+%!       0.092758 + 0.345687i  0.928679 + 0.241052i  0.764536 + 0.832406i;
+%!       0.912098 + 0.721024i  0.049018 + 0.269452i  0.730029 + 0.796517i;
+%!       0.112849 + 0.603871i  0.486352 + 0.142337i  0.355646 + 0.151496i ];
 %!
 %! uc = [0.20351 + 0.05401i;
-%!      0.13141 + 0.43708i;
-%!      0.29808 + 0.08789i;
-%!      0.69821 + 0.38844i;
-%!      0.74871 + 0.25821i ];
+%!       0.13141 + 0.43708i;
+%!       0.29808 + 0.08789i;
+%!       0.69821 + 0.38844i;
+%!       0.74871 + 0.25821i ];
 %!
 %! vc = [0.85839 + 0.29468i;
-%!      0.20820 + 0.93090i;
-%!      0.86184 + 0.34689i ];
+%!       0.20820 + 0.93090i;
+%!       0.86184 + 0.34689i ];
 %!
 
 %!testif HAVE_QRUPDATE_LUU
-%! [L,U,P] = lu(A);
-%! [L,U] = luupdate(L,U,P*u,v);
-%! assert(norm(vec(tril(L)-L),Inf) == 0)
-%! assert(norm(vec(triu(U)-U),Inf) == 0)
-%! assert(norm(vec(P'*L*U - A - u*v.'),Inf) < norm(A)*1e1*eps)
+%! [L,U,P] = lu (A);
+%! [L,U] = luupdate (L,U,P*u,v);
+%! assert (norm (vec (tril (L)-L), Inf) == 0);
+%! assert (norm (vec (triu (U)-U), Inf) == 0);
+%! assert (norm (vec (P'*L*U - A - u*v.'), Inf) < norm (A)*1e1*eps);
 %!
 %!testif HAVE_QRUPDATE_LUU
-%! [L,U,P] = lu(Ac);
-%! [L,U] = luupdate(L,U,P*uc,vc);
-%! assert(norm(vec(tril(L)-L),Inf) == 0)
-%! assert(norm(vec(triu(U)-U),Inf) == 0)
-%! assert(norm(vec(P'*L*U - Ac - uc*vc.'),Inf) < norm(Ac)*1e1*eps)
+%! [L,U,P] = lu (Ac);
+%! [L,U] = luupdate (L,U,P*uc,vc);
+%! assert (norm (vec (tril (L)-L), Inf) == 0);
+%! assert (norm (vec (triu (U)-U), Inf) == 0);
+%! assert (norm (vec (P'*L*U - Ac - uc*vc.'), Inf) < norm (Ac)*1e1*eps);
 
 %!testif HAVE_QRUPDATE_LUU
-%! [L,U,P] = lu(single(A));
-%! [L,U] = luupdate(L,U,P*single(u),single(v));
-%! assert(norm(vec(tril(L)-L),Inf) == 0)
-%! assert(norm(vec(triu(U)-U),Inf) == 0)
-%! assert(norm(vec(P'*L*U - single(A) - single(u)*single(v).'),Inf) < norm(single(A))*1e1*eps('single'))
+%! [L,U,P] = lu (single (A));
+%! [L,U] = luupdate (L,U,P*single (u), single (v));
+%! assert (norm (vec (tril (L)-L), Inf) == 0);
+%! assert (norm (vec (triu (U)-U), Inf) == 0);
+%! assert (norm (vec (P'*L*U - single (A) - single (u)*single (v).'), Inf) < norm (single (A))*1e1*eps ("single"));
 %!
 %!testif HAVE_QRUPDATE_LUU
-%! [L,U,P] = lu(single(Ac));
-%! [L,U] = luupdate(L,U,P*single(uc),single(vc));
-%! assert(norm(vec(tril(L)-L),Inf) == 0)
-%! assert(norm(vec(triu(U)-U),Inf) == 0)
-%! assert(norm(vec(P'*L*U - single(Ac) - single(uc)*single(vc).'),Inf) < norm(single(Ac))*1e1*eps('single'))
+%! [L,U,P] = lu (single (Ac));
+%! [L,U] = luupdate (L,U,P*single (uc),single (vc));
+%! assert (norm (vec (tril (L)-L), Inf) == 0);
+%! assert (norm (vec (triu (U)-U), Inf) == 0);
+%! assert (norm (vec (P'*L*U - single (Ac) - single (uc)*single (vc).'), Inf) < norm (single (Ac))*1e1*eps ("single"));
 
 %!testif HAVE_QRUPDATE_LUU
-%! [L,U,P] = lu(A);
-%! [L,U,P] = luupdate(L,U,P,u,v);
-%! assert(norm(vec(tril(L)-L),Inf) == 0)
-%! assert(norm(vec(triu(U)-U),Inf) == 0)
-%! assert(norm(vec(P'*L*U - A - u*v.'),Inf) < norm(A)*1e1*eps)
+%! [L,U,P] = lu (A);
+%! [L,U,P] = luupdate (L,U,P,u,v);
+%! assert (norm (vec (tril (L)-L), Inf) == 0);
+%! assert (norm (vec (triu (U)-U), Inf) == 0);
+%! assert (norm (vec (P'*L*U - A - u*v.'), Inf) < norm (A)*1e1*eps);
 %!
 %!testif HAVE_QRUPDATE_LUU
-%! [L,U,P] = lu(Ac);
-%! [L,U,P] = luupdate(L,U,P,uc,vc);
-%! assert(norm(vec(tril(L)-L),Inf) == 0)
-%! assert(norm(vec(triu(U)-U),Inf) == 0)
-%! assert(norm(vec(P'*L*U - Ac - uc*vc.'),Inf) < norm(Ac)*1e1*eps)
+%! [L,U,P] = lu (Ac);
+%! [L,U,P] = luupdate (L,U,P,uc,vc);
+%! assert (norm (vec (tril (L)-L), Inf) == 0);
+%! assert (norm (vec (triu (U)-U), Inf) == 0);
+%! assert (norm (vec (P'*L*U - Ac - uc*vc.'), Inf) < norm (Ac)*1e1*eps);
 
 %!testif HAVE_QRUPDATE_LUU
-%! [L,U,P] = lu(single(A));
-%! [L,U,P] = luupdate(L,U,P,single(u),single(v));
-%! assert(norm(vec(tril(L)-L),Inf) == 0)
-%! assert(norm(vec(triu(U)-U),Inf) == 0)
-%! assert(norm(vec(P'*L*U - single(A) - single(u)*single(v).'),Inf) < norm(single(A))*1e1*eps('single'))
+%! [L,U,P] = lu (single (A));
+%! [L,U,P] = luupdate (L,U,P,single (u),single (v));
+%! assert (norm (vec (tril (L)-L), Inf) == 0);
+%! assert (norm (vec (triu (U)-U), Inf) == 0);
+%! assert (norm (vec (P'*L*U - single (A) - single (u)*single (v).'), Inf) < norm (single (A))*1e1*eps ("single"));
 %!
 %!testif HAVE_QRUPDATE_LUU
-%! [L,U,P] = lu(single(Ac));
-%! [L,U,P] = luupdate(L,U,P,single(uc),single(vc));
-%! assert(norm(vec(tril(L)-L),Inf) == 0)
-%! assert(norm(vec(triu(U)-U),Inf) == 0)
-%! assert(norm(vec(P'*L*U - single(Ac) - single(uc)*single(vc).'),Inf) < norm(single(Ac))*1e1*eps('single'))
+%! [L,U,P] = lu (single (Ac));
+%! [L,U,P] = luupdate (L,U,P,single (uc),single (vc));
+%! assert (norm (vec (tril (L)-L), Inf) == 0);
+%! assert (norm (vec (triu (U)-U), Inf) == 0);
+%! assert (norm (vec (P'*L*U - single (Ac) - single (uc)*single (vc).'), Inf) < norm (single (Ac))*1e1*eps ("single"));
 */
rename from src/DLD-FUNCTIONS/luinc.cc
rename to libinterp/corefcn/luinc.cc
--- a/src/DLD-FUNCTIONS/luinc.cc
+++ b/libinterp/corefcn/luinc.cc
@@ -24,7 +24,7 @@
 #include <config.h>
 #endif
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -37,11 +37,11 @@
 #include "ov-re-sparse.h"
 #include "ov-cx-sparse.h"
 
-DEFUN_DLD (luinc, args, nargout,
+DEFUN (luinc, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {[@var{L}, @var{U}, @var{P}, @var{Q}] =} luinc (@var{A}, '0')\n\
-@deftypefnx {Loadable Function} {[@var{L}, @var{U}, @var{P}, @var{Q}] =} luinc (@var{A}, @var{droptol})\n\
-@deftypefnx {Loadable Function} {[@var{L}, @var{U}, @var{P}, @var{Q}] =} luinc (@var{A}, @var{opts})\n\
+@deftypefn  {Built-in Function} {[@var{L}, @var{U}, @var{P}, @var{Q}] =} luinc (@var{A}, '0')\n\
+@deftypefnx {Built-in Function} {[@var{L}, @var{U}, @var{P}, @var{Q}] =} luinc (@var{A}, @var{droptol})\n\
+@deftypefnx {Built-in Function} {[@var{L}, @var{U}, @var{P}, @var{Q}] =} luinc (@var{A}, @var{opts})\n\
 @cindex LU decomposition\n\
 Produce the incomplete LU@tie{}factorization of the sparse matrix @var{A}.\n\
 Two types of incomplete factorization are possible, and the type\n\
@@ -91,7 +91,7 @@
 All other fields in @var{opts} are ignored.  The outputs from @code{luinc}\n\
 are the same as for @code{lu}.\n\
 \n\
-Given the string argument 'vector', @code{luinc} returns the values of\n\
+Given the string argument \"vector\", @code{luinc} returns the values of\n\
 @var{p} @var{q} as vector values.\n\
 @seealso{sparse, lu}\n\
 @end deftypefn")
@@ -154,7 +154,7 @@
 
                   if (thresh.nelem () == 1)
                     {
-                      thresh.resize(1,2);
+                      thresh.resize (1,2);
                       thresh(1) = thresh(0);
                     }
                   else if (thresh.nelem () != 2)
@@ -365,21 +365,19 @@
 }
 
 /*
+%!testif HAVE_UMFPACK
+%! a = sparse ([1,2,0,0;0,1,2,0;1e-14,0,3,0;0,0,0,1]);
+%! [l,u] = luinc (a, 1e-10);
+%! assert (l*u, sparse ([1,2,0,0;0,1,2,0;0,0,3,0;0,0,0,1]), 1e-10);
+%! opts.droptol = 1e-10;
+%! [l,u] = luinc (a, opts);
+%! assert (l*u, sparse ([1,2,0,0;0,1,2,0;0,0,3,0;0,0,0,1]), 1e-10);
 
 %!testif HAVE_UMFPACK
-%! a=sparse([1,2,0,0;0,1,2,0;1e-14,0,3,0;0,0,0,1]);
-%! [l,u]=luinc(a,1e-10);
-%! assert(l*u, sparse([1,2,0,0;0,1,2,0;0,0,3,0;0,0,0,1]),1e-10);
-%! opts.droptol=1e-10;
-%! [l,u]=luinc(a,opts);
-%! assert(l*u, sparse([1,2,0,0;0,1,2,0;0,0,3,0;0,0,0,1]),1e-10);
-
-%!testif HAVE_UMFPACK
-%! a=sparse([1i,2,0,0;0,1,2,0;1e-14,0,3,0;0,0,0,1]);
-%! [l,u]=luinc(a,1e-10);
-%! assert(l*u, sparse([1i,2,0,0;0,1,2,0;0,0,3,0;0,0,0,1]),1e-10);
-%! opts.droptol=1e-10;
-%! [l,u]=luinc(a,opts);
-%! assert(l*u, sparse([1i,2,0,0;0,1,2,0;0,0,3,0;0,0,0,1]),1e-10);
-
+%! a = sparse ([1i,2,0,0;0,1,2,0;1e-14,0,3,0;0,0,0,1]);
+%! [l,u] = luinc (a, 1e-10);
+%! assert (l*u, sparse ([1i,2,0,0;0,1,2,0;0,0,3,0;0,0,0,1]), 1e-10);
+%! opts.droptol = 1e-10;
+%! [l,u] = luinc (a, opts);
+%! assert (l*u, sparse ([1i,2,0,0;0,1,2,0;0,0,3,0;0,0,0,1]), 1e-10);
 */
rename from src/mappers.cc
rename to libinterp/corefcn/mappers.cc
--- a/src/mappers.cc
+++ b/libinterp/corefcn/mappers.cc
@@ -112,7 +112,7 @@
 %!test
 %! x = single ([1, rt3/2, rt2/2, 1/2, 0, -1/2, -rt2/2, -rt3/2, -1]);
 %! v = single ([0, pi/6, pi/4, pi/3, pi/2, 2*pi/3, 3*pi/4, 5*pi/6, pi]);
-%! assert (acos (x), v, sqrt (eps ('single')));
+%! assert (acos (x), v, sqrt (eps ("single")));
 
 %!error acos ()
 %!error acos (1, 2)
@@ -143,7 +143,7 @@
 %!test
 %! x = single ([1, 0, -1, 0]);
 %! v = single ([0, pi/2*i, pi*i, pi/2*i]);
-%! assert (acosh (x), v, sqrt (eps ('single')));
+%! assert (acosh (x), v, sqrt (eps ("single")));
 
 %!error acosh ()
 %!error acosh (1, 2)
@@ -213,7 +213,7 @@
 %!   assert (arg (single (-1)), single (pi));
 %! endif
 %!assert (arg (single (-i)), single (-pi/2))
-%!assert (arg (single ([1, i; -1, -i])), single ([0, pi/2; pi, -pi/2]), 2e1*eps ('single'))
+%!assert (arg (single ([1, i; -1, -i])), single ([0, pi/2; pi, -pi/2]), 2e1*eps ("single"))
 
 %!error arg ()
 %!error arg (1, 2)
@@ -272,7 +272,7 @@
 %!test
 %! v = single ([0, pi/2*i, 0, -pi/2*i]);
 %! x = single ([0, i, 0, -i]);
-%! assert (asinh (x), v,  sqrt (eps ('single')));
+%! assert (asinh (x), v,  sqrt (eps ("single")));
 
 %!error asinh ()
 %!error asinh (1, 2)
@@ -307,7 +307,7 @@
 %!test
 %! v = single ([0, pi/6, pi/4, pi/3, -pi/3, -pi/4, -pi/6, 0]);
 %! x = single ([0, rt3/3, 1, rt3, -rt3, -1, -rt3/3, 0]);
-%! assert (atan (x), v, sqrt (eps ('single')));
+%! assert (atan (x), v, sqrt (eps ("single")));
 
 %!error atan ()
 %!error atan (1, 2)
@@ -338,7 +338,7 @@
 %!test
 %! v = single ([0, 0]);
 %! x = single ([0, 0]);
-%! assert (atanh (x), v, sqrt (eps ('single')));
+%! assert (atanh (x), v, sqrt (eps ("single")));
 
 %!error atanh ()
 %!error atanh (1, 2)
@@ -386,7 +386,7 @@
 @example\n\
 @group\n\
 ceil ([-2.7, 2.7])\n\
-   @result{}  -2   3\n\
+    @result{} -2    3\n\
 @end group\n\
 @end example\n\
 @seealso{floor, round, fix}\n\
@@ -402,16 +402,16 @@
 }
 
 /*
-%% double precision
+## double precision
 %!assert (ceil ([2, 1.1, -1.1, -1]), [2, 2, -1, -1])
 
-%% complex double precison
+## complex double precison
 %!assert (ceil ([2+2i, 1.1+1.1i, -1.1-1.1i, -1-i]), [2+2i, 2+2i, -1-i, -1-i])
 
-%% single precision
+## single precision
 %!assert (ceil (single ([2, 1.1, -1.1, -1])), single ([2, 2, -1, -1]))
 
-%% complex single precision
+## complex single precision
 %!assert (ceil (single ([2+2i, 1.1+1.1i, -1.1-1.1i, -1-i])), single ([2+2i, 2+2i, -1-i, -1-i]))
 
 %!error ceil ()
@@ -488,7 +488,7 @@
 %! rt3 = sqrt (3);
 %! x = single ([0, pi/6, pi/4, pi/3, pi/2, 2*pi/3, 3*pi/4, 5*pi/6, pi]);
 %! v = single ([1, rt3/2, rt2/2, 1/2, 0, -1/2, -rt2/2, -rt3/2, -1]);
-%! assert (cos (x), v, sqrt (eps ('single')));
+%! assert (cos (x), v, sqrt (eps ("single")));
 
 %!error cos ()
 %!error cos (1, 2)
@@ -519,7 +519,7 @@
 %!test
 %! x = single ([0, pi/2*i, pi*i, 3*pi/2*i]);
 %! v = single ([1, 0, -1, 0]);
-%! assert (cosh (x), v, sqrt (eps ('single')));
+%! assert (cosh (x), v, sqrt (eps ("single")));
 
 %!error cosh ()
 %!error cosh (1, 2)
@@ -538,17 +538,16 @@
 \n\
 @example\n\
 @group\n\
-@c spacing appears odd here, but is correct after Makeinfo\n\
-                          z\n\
-                         /\n\
-erf (z) = (2/sqrt (pi)) | e^(-t^2) dt\n\
-                         /\n\
-                      t=0\n\
+                        z\n\
+              2        /\n\
+erf (z) = --------- *  | e^(-t^2) dt\n\
+          sqrt (pi)    /\n\
+                    t=0\n\
 @end group\n\
 @end example\n\
 \n\
 @end ifnottex\n\
-@seealso{erfc, erfcx, erfinv}\n\
+@seealso{erfc, erfcx, erfi, dawson, erfinv, erfcinv}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -568,10 +567,10 @@
 %!test
 %! x = [0,.5,1];
 %! v = [0, .520499877813047, .842700792949715];
-%! assert (all (abs (erf (x)-v) < 1.e-10));
-%! assert (all (abs (erf (-x)+v) < 1.e-10));
-%! assert (all (abs (erfc (x)+v-1) < 1.e-10));
-%! assert (all (abs (erfinv (v)-x) < 1.e-10));
+%! assert (erf (x), v, 1.e-10);
+%! assert (erf (-x), -v, 1.e-10);
+%! assert (erfc (x), 1-v, 1.e-10);
+%! assert (erfinv (v), x, 1.e-10);
 
 %!test
 %! a = -1i*sqrt (single (-1/(6.4187*6.4187)));
@@ -580,10 +579,17 @@
 %!test
 %! x = single ([0,.5,1]);
 %! v = single ([0, .520499877813047, .842700792949715]);
-%! assert (all (abs (erf (x)-v) < 1.e-6));
-%! assert (all (abs (erf (-x)+v) < 1.e-6));
-%! assert (all (abs (erfc (x)+v-1) < 1.e-6));
-%! assert (all (abs (erfinv (v)-x) < 1.e-6));
+%! assert (erf (x), v, 1.e-6);
+%! assert (erf (-x), -v, 1.e-6);
+%! 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)
@@ -595,9 +601,9 @@
 Compute the inverse error function, i.e., @var{y} such that\n\
 \n\
 @example\n\
-  erf (@var{y}) == @var{x}\n\
+erf (@var{y}) == @var{x}\n\
 @end example\n\
-@seealso{erf, erfc, erfcx}\n\
+@seealso{erf, erfc, erfcx, erfi, dawson, erfcinv}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -610,16 +616,16 @@
 }
 
 /*
-%% middle region
+## middle region
 %!assert (erf (erfinv ([-0.9 -0.3 0 0.4 0.8])), [-0.9 -0.3 0 0.4 0.8], eps)
-%!assert (erf (erfinv (single ([-0.9 -0.3 0 0.4 0.8]))), single ([-0.9 -0.3 0 0.4 0.8]), 1e-8)
-%% tail region
+%!assert (erf (erfinv (single ([-0.9 -0.3 0 0.4 0.8]))), single ([-0.9 -0.3 0 0.4 0.8]), eps ("single"))
+## tail region
 %!assert (erf (erfinv ([-0.999 -0.99 0.9999 0.99999])), [-0.999 -0.99 0.9999 0.99999], eps)
-%!assert (erf (erfinv (single ([-0.999 -0.99 0.9999 0.99999]))), single ([-0.999 -0.99 0.9999 0.99999]), 1e-8)
-%% backward - loss of accuracy
+%!assert (erf (erfinv (single ([-0.999 -0.99 0.9999 0.99999]))), single ([-0.999 -0.99 0.9999 0.99999]), eps ("single"))
+## backward - loss of accuracy
 %!assert (erfinv (erf ([-3 -1 -0.4 0.7 1.3 2.8])), [-3 -1 -0.4 0.7 1.3 2.8], -1e-12)
 %!assert (erfinv (erf (single ([-3 -1 -0.4 0.7 1.3 2.8]))), single ([-3 -1 -0.4 0.7 1.3 2.8]), -1e-4)
-%% exceptional
+## exceptional
 %!assert (erfinv ([-1, 1, 1.1, -2.1]), [-Inf, Inf, NaN, NaN])
 %!error erfinv (1+2i)
 
@@ -627,6 +633,44 @@
 %!error erfinv (1, 2)
 */
 
+DEFUN (erfcinv, args, ,
+    "-*- texinfo -*-\n\
+@deftypefn {Mapping Function} {} erfcinv (@var{x})\n\
+Compute the inverse complementary error function, i.e., @var{y} such that\n\
+\n\
+@example\n\
+erfc (@var{y}) == @var{x}\n\
+@end example\n\
+@seealso{erfc, erf, erfcx, erfi, dawson, erfinv}\n\
+@end deftypefn")
+{
+  octave_value retval;
+  if (args.length () == 1)
+    retval = args(0).erfcinv ();
+  else
+    print_usage ();
+
+  return retval;
+}
+
+/*
+## middle region
+%!assert (erfc (erfcinv ([1.9 1.3 1 0.6 0.2])), [1.9 1.3 1 0.6 0.2], eps)
+%!assert (erfc (erfcinv (single ([1.9 1.3 1 0.6 0.2]))), single ([1.9 1.3 1 0.6 0.2]), eps ("single"))
+## tail region
+%!assert (erfc (erfcinv ([0.001 0.01 1.9999 1.99999])), [0.001 0.01 1.9999 1.99999], eps)
+%!assert (erfc (erfcinv (single ([0.001 0.01 1.9999 1.99999]))), single ([0.001 0.01 1.9999 1.99999]), eps ("single"))
+## backward - loss of accuracy
+%!assert (erfcinv (erfc ([-3 -1 -0.4 0.7 1.3 2.8])), [-3 -1 -0.4 0.7 1.3 2.8], -1e-12)
+%!assert (erfcinv (erfc (single ([-3 -1 -0.4 0.7 1.3 2.8]))), single ([-3 -1 -0.4 0.7 1.3 2.8]), -1e-4)
+## exceptional
+%!assert (erfcinv ([2, 0, -0.1, 2.1]), [-Inf, Inf, NaN, NaN])
+%!error erfcinv (1+2i)
+
+%!error erfcinv ()
+%!error erfcinv (1, 2)
+*/
+
 DEFUN (erfc, args, ,
     "-*- texinfo -*-\n\
 @deftypefn {Mapping Function} {} erfc (@var{z})\n\
@@ -637,7 +681,7 @@
 @ifnottex\n\
 @w{@code{1 - erf (@var{z})}}.\n\
 @end ifnottex\n\
-@seealso{erfcx, erf, erfinv}\n\
+@seealso{erfcinv, erfcx, erfi, dawson, erf, erfinv}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -670,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}\n\
+@seealso{erfc, erf, erfi, dawson, erfinv, erfcinv}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -687,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\
@@ -720,8 +850,8 @@
 /*
 %!assert (exp ([0, 1, -1, -1000]), [1, e, 1/e, 0], sqrt (eps))
 %!assert (exp (1+i), e * (cos (1) + sin (1) * i), sqrt (eps))
-%!assert (exp (single ([0, 1, -1, -1000])), single ([1, e, 1/e, 0]), sqrt (eps ('single')))
-%!assert (exp (single (1+i)), single (e * (cos (1) + sin (1) * i)), sqrt (eps ('single')))
+%!assert (exp (single ([0, 1, -1, -1000])), single ([1, e, 1/e, 0]), sqrt (eps ("single")))
+%!assert (exp (single (1+i)), single (e * (cos (1) + sin (1) * i)), sqrt (eps ("single")))
 
 %!assert (exp ([Inf, -Inf, NaN]), [Inf 0 NaN])
 %!assert (exp (single ([Inf, -Inf, NaN])), single ([Inf 0 NaN]))
@@ -812,7 +942,7 @@
 @example\n\
 @group\n\
 fix ([-2.7, 2.7])\n\
-   @result{} -2   2\n\
+   @result{} -2    2\n\
 @end group\n\
 @end example\n\
 @seealso{ceil, floor, round}\n\
@@ -847,7 +977,7 @@
 @example\n\
 @group\n\
 floor ([-2.7, 2.7])\n\
-     @result{} -3   2\n\
+     @result{} -3    2\n\
 @end group\n\
 @end example\n\
 @seealso{ceil, round, fix}\n\
@@ -885,12 +1015,11 @@
 \n\
 @example\n\
 @group\n\
-@c spacing appears odd here, but is correct after Makeinfo\n\
-              infinity\n\
-             /\n\
+             infinity\n\
+            /\n\
 gamma (z) = | t^(z-1) exp (-t) dt.\n\
-             /\n\
-          t=0\n\
+            /\n\
+         t=0\n\
 @end group\n\
 @end example\n\
 \n\
@@ -924,7 +1053,7 @@
 %!test
 %! x = single ([.5, 1, 1.5, 2, 3, 4, 5]);
 %! v = single ([sqrt(pi), 1, .5*sqrt(pi), 1, 2, 6, 24]);
-%! assert (gamma (x), v, sqrt (eps ('single')));
+%! assert (gamma (x), v, sqrt (eps ("single")));
 
 %!test
 %! x = [-1, 0, 1, Inf];
@@ -961,7 +1090,7 @@
 %!assert (imag (single (1)), single (0))
 %!assert (imag (single (i)), single (1))
 %!assert (imag (single (1+i)), single (1))
-%!assert (imag (single ([i, 1; 1, i])), full (eye (2,'single')))
+%!assert (imag (single ([i, 1; 1, i])), full (eye (2,"single")))
 
 %!error imag ()
 %!error imag (1, 2)
@@ -992,7 +1121,7 @@
 %! result(toascii ("A":"Z") + 1) = true;
 %! result(toascii ("0":"9") + 1) = true;
 %! result(toascii ("a":"z") + 1) = true;
-%! assert (all (isalnum (charset) == result));
+%! assert (isalnum (charset), result);
 
 %!error isalnum ()
 %!error isalnum (1, 2)
@@ -1022,7 +1151,7 @@
 %! result = false (1, 128);
 %! result(toascii ("A":"Z") + 1) = true;
 %! result(toascii ("a":"z") + 1) = true;
-%! assert (all (isalpha (charset) == result));
+%! assert (isalpha (charset), result);
 
 %!error isalpha ()
 %!error isalpha (1, 2)
@@ -1049,7 +1178,7 @@
 %!test
 %! charset = char (0:127);
 %! result = true (1, 128);
-%! assert (all (isascii (charset) == result));
+%! assert (isascii (charset), result);
 
 %!error isascii ()
 %!error isascii (1, 2)
@@ -1078,7 +1207,7 @@
 %! result = false (1, 128);
 %! result(1:32) = true;
 %! result(128) = true;
-%! assert (all (iscntrl (charset) == result));
+%! assert (iscntrl (charset), result);
 
 %!error iscntrl ()
 %!error iscntrl (1, 2)
@@ -1106,7 +1235,7 @@
 %! charset = char (0:127);
 %! result = false (1, 128);
 %! result(toascii ("0":"9") + 1) = true;
-%! assert (all (isdigit (charset) == result));
+%! assert (isdigit (charset), result);
 
 %!error isdigit ()
 %!error isdigit (1, 2)
@@ -1122,7 +1251,7 @@
 @example\n\
 @group\n\
 isinf ([13, Inf, NA, NaN])\n\
-     @result{} [ 0, 1, 0, 0 ]\n\
+      @result{} [ 0, 1, 0, 0 ]\n\
 @end group\n\
 @end example\n\
 @seealso{isfinite, isnan, isna}\n\
@@ -1141,13 +1270,13 @@
 %!assert (isinf (Inf))
 %!assert (!isinf (NaN))
 %!assert (!isinf (NA))
-%!assert (isinf (rand(1,10)), false (1,10))
+%!assert (isinf (rand (1,10)), false (1,10))
 %!assert (isinf ([NaN -Inf -1 0 1 Inf NA]), [false, true, false, false, false, true, false])
 
 %!assert (isinf (single (Inf)))
 %!assert (!isinf (single (NaN)))
 %!assert (!isinf (single (NA)))
-%!assert (isinf (single (rand(1,10))), false (1,10))
+%!assert (isinf (single (rand (1,10))), false (1,10))
 %!assert (isinf (single ([NaN -Inf -1 0 1 Inf NA])), [false, true, false, false, false, true, false])
 
 %!error isinf ()
@@ -1177,7 +1306,7 @@
 %! charset = char (0:127);
 %! result = false (1, 128);
 %! result(34:127) = true;
-%! assert (all (isgraph (charset) == result));
+%! assert (isgraph (charset), result);
 
 %!error isgraph ()
 %!error isgraph (1, 2)
@@ -1205,7 +1334,7 @@
 %! charset = char (0:127);
 %! result = false (1, 128);
 %! result(toascii ("a":"z") + 1) = true;
-%! assert (all (islower (charset) == result));
+%! assert (islower (charset), result);
 
 %!error islower ()
 %!error islower (1, 2)
@@ -1240,13 +1369,13 @@
 %!assert (!isna (Inf))
 %!assert (!isna (NaN))
 %!assert (isna (NA))
-%!assert (isna (rand(1,10)), false (1,10))
+%!assert (isna (rand (1,10)), false (1,10))
 %!assert (isna ([NaN -Inf -1 0 1 Inf NA]), [false, false, false, false, false, false, true])
 
 %!assert (!isna (single (Inf)))
 %!assert (!isna (single (NaN)))
 %!assert (isna (single (NA)))
-%!assert (isna (single (rand(1,10))), false (1,10))
+%!assert (isna (single (rand (1,10))), false (1,10))
 %!assert (isna (single ([NaN -Inf -1 0 1 Inf NA])), [false, false, false, false, false, false, true])
 
 %!error isna ()
@@ -1263,7 +1392,7 @@
 @example\n\
 @group\n\
 isnan ([13, Inf, NA, NaN])\n\
-     @result{} [ 0, 0, 1, 1 ]\n\
+      @result{} [ 0, 0, 1, 1 ]\n\
 @end group\n\
 @end example\n\
 @seealso{isna, isinf, isfinite}\n\
@@ -1282,13 +1411,13 @@
 %!assert (!isnan (Inf))
 %!assert (isnan (NaN))
 %!assert (isnan (NA))
-%!assert (isnan (rand(1,10)), false (1,10))
+%!assert (isnan (rand (1,10)), false (1,10))
 %!assert (isnan ([NaN -Inf -1 0 1 Inf NA]), [true, false, false, false, false, false, true])
 
 %!assert (!isnan (single (Inf)))
 %!assert (isnan (single (NaN)))
 %!assert (isnan (single (NA)))
-%!assert (isnan (single (rand(1,10))), false (1,10))
+%!assert (isnan (single (rand (1,10))), false (1,10))
 %!assert (isnan (single ([NaN -Inf -1 0 1 Inf NA])), [true, false, false, false, false, false, true])
 
 %!error isnan ()
@@ -1318,7 +1447,7 @@
 %! charset = char (0:127);
 %! result = false (1, 128);
 %! result(33:127) = true;
-%! assert (all (isprint (charset) == result));
+%! assert (isprint (charset), result);
 
 %!error isprint ()
 %!error isprint (1, 2)
@@ -1349,7 +1478,7 @@
 %! result(59:65) = true;
 %! result(92:97) = true;
 %! result(124:127) = true;
-%! assert (all (ispunct (charset) == result));
+%! assert (ispunct (charset), result);
 
 %!error ispunct ()
 %!error ispunct (1, 2)
@@ -1378,7 +1507,7 @@
 %! charset = char (0:127);
 %! result = false (1, 128);
 %! result(toascii (" \f\n\r\t\v") + 1) = true;
-%! assert (all (isspace (charset) == result));
+%! assert (isspace (charset), result);
 
 %!error isspace ()
 %!error isspace (1, 2)
@@ -1406,7 +1535,7 @@
 %! charset = char (0:127);
 %! result = false (1, 128);
 %! result(toascii ("A":"Z") + 1) = true;
-%! assert (all (isupper (charset) == result));
+%! assert (isupper (charset), result);
 
 %!error isupper ()
 %!error isupper (1, 2)
@@ -1436,7 +1565,7 @@
 %! result(toascii ("A":"F") + 1) = true;
 %! result(toascii ("0":"9") + 1) = true;
 %! result(toascii ("a":"f") + 1) = true;
-%! assert (all (isxdigit (charset) == result));
+%! assert (isxdigit (charset), result);
 
 %!error isxdigit ()
 %!error isxdigit (1, 2)
@@ -1462,30 +1591,30 @@
 /*
 %!test
 %! a = -1i*sqrt (-1/(6.4187*6.4187));
-%! assert (lgamma(a), lgamma(real(a)));
+%! assert (lgamma (a), lgamma (real (a)));
 
 %!test
 %! x = [.5, 1, 1.5, 2, 3, 4, 5];
 %! v = [sqrt(pi), 1, .5*sqrt(pi), 1, 2, 6, 24];
-%! assert (lgamma(x), log(v), sqrt (eps))
+%! assert (lgamma (x), log (v), sqrt (eps))
 
 %!test
 %! a = single (-1i*sqrt (-1/(6.4187*6.4187)));
-%! assert (lgamma(a), lgamma(real(a)));
+%! assert (lgamma (a), lgamma (real (a)));
 
 %!test
 %! x = single ([.5, 1, 1.5, 2, 3, 4, 5]);
 %! v = single ([sqrt(pi), 1, .5*sqrt(pi), 1, 2, 6, 24]);
-%! assert (lgamma(x), log(v), sqrt (eps ('single')))
+%! assert (lgamma (x), log (v), sqrt (eps ("single")))
 
 %!test
 %! x = [-1, 0, 1, Inf];
 %! v = [Inf, Inf, 0, Inf];
-%! assert (lgamma(x), v);
-%! assert (lgamma(single (x)), single (v));
+%! assert (lgamma (x), v);
+%! assert (lgamma (single (x)), single (v));
 
-%!error lgamma()
-%!error lgamma(1,2)
+%!error lgamma ()
+%!error lgamma (1,2)
 */
 
 DEFUN (log, args, ,
@@ -1514,10 +1643,10 @@
 
 /*
 %!assert (log ([1, e, e^2]), [0, 1, 2], sqrt (eps))
-%!assert (log ([-0.5, -1.5, -2.5]), log([0.5, 1.5, 2.5]) + pi*1i, sqrt (eps))
+%!assert (log ([-0.5, -1.5, -2.5]), log ([0.5, 1.5, 2.5]) + pi*1i, sqrt (eps))
 
-%!assert (log (single ([1, e, e^2])), single ([0, 1, 2]), sqrt (eps ('single')))
-%!assert (log (single ([-0.5, -1.5, -2.5])), single (log([0.5, 1.5, 2.5]) + pi*1i), 4*eps ('single'))
+%!assert (log (single ([1, e, e^2])), single ([0, 1, 2]), sqrt (eps ("single")))
+%!assert (log (single ([-0.5, -1.5, -2.5])), single (log ([0.5, 1.5, 2.5]) + pi*1i), 4*eps ("single"))
 
 %!error log ()
 %!error log (1, 2)
@@ -1541,7 +1670,7 @@
 
 /*
 %!assert (log10 ([0.01, 0.1, 1, 10, 100]), [-2, -1, 0, 1, 2], sqrt (eps))
-%!assert (log10 (single ([0.01, 0.1, 1, 10, 100])), single ([-2, -1, 0, 1, 2]), sqrt (eps ('single')))
+%!assert (log10 (single ([0.01, 0.1, 1, 10, 100])), single ([-2, -1, 0, 1, 2]), sqrt (eps ("single")))
 
 %!error log10 ()
 %!error log10 (1, 2)
@@ -1572,7 +1701,7 @@
 
 /*
 %!assert (log1p ([0, 2*eps, -2*eps]), [0, 2*eps, -2*eps], 1e-29)
-%!assert (log1p (single ([0, 2*eps, -2*eps])), single([0, 2*eps, -2*eps]), 1e-29)
+%!assert (log1p (single ([0, 2*eps, -2*eps])), single ([0, 2*eps, -2*eps]), 1e-29)
 
 %!error log1p ()
 %!error log1p (1, 2)
@@ -1603,7 +1732,7 @@
 %!assert (real (single (1)), single (1))
 %!assert (real (single (i)), single (0))
 %!assert (real (single (1+i)), single (1))
-%!assert (real (single ([1, i; i, 1])), full (eye (2,'single')))
+%!assert (real (single ([1, i; i, 1])), full (eye (2,"single")))
 
 %!error real ()
 %!error real (1, 2)
@@ -1619,7 +1748,7 @@
 @example\n\
 @group\n\
 round ([-2.7, 2.7])\n\
-     @result{} -3   3\n\
+     @result{} -3    3\n\
 @end group\n\
 @end example\n\
 @seealso{ceil, floor, fix, roundb}\n\
@@ -1718,6 +1847,12 @@
 @end ifnottex\n\
 \n\
 For complex arguments, @code{sign} returns @code{x ./ abs (@var{x})}.\n\
+\n\
+Note that @code{sign (-0.0)} is 0.\n\
+Although IEEE 754 floating point\n\
+allows zero to be signed, 0.0 and -0.0 compare equal.  If you must test\n\
+whether zero is signed, use the @code{signbit} function.\n\
+@seealso{signbit}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -1744,6 +1879,45 @@
 %!error sign (1, 2)
 */
 
+DEFUNX ("signbit", Fsignbit, args, ,
+    "-*- texinfo -*-\n\
+@deftypefn {Mapping Function} {} signbit (@var{x})\n\
+Return logical true if the value of @var{x} has its sign bit set.\n\
+Otherwise return logical false.  This behavior is consistent with the other\n\
+logical functions. See@ref{Logical Values}.  The behavior differs from the\n\
+C language function which returns non-zero if the sign bit is set.\n\
+\n\
+This is not the same as @code{x < 0.0}, because IEEE 754 floating point\n\
+allows zero to be signed.  The comparison @code{-0.0 < 0.0} is false,\n\
+but @code{signbit (-0.0)} will return a nonzero value.\n\
+@seealso{sign}\n\
+@end deftypefn")
+{
+  octave_value retval;
+  if (args.length () == 1) {
+    retval = args(0).xsignbit ();
+    retval = (retval != 0); }
+  else
+    print_usage ();
+
+  return retval;
+}
+
+/*
+%!assert (signbit (1) == 0)
+%!assert (signbit (-2) != 0)
+%!assert (signbit (0) == 0)
+%!assert (signbit (-0) != 0)
+
+%!assert (signbit (single (1)) == 0)
+%!assert (signbit (single (-2)) != 0)
+%!assert (signbit (single (0)) == 0)
+%!assert (signbit (single (-0)) != 0)
+
+%!error sign ()
+%!error sign (1, 2)
+*/
+
 DEFUN (sin, args, ,
     "-*- texinfo -*-\n\
 @deftypefn {Mapping Function} {} sin (@var{x})\n\
@@ -1773,7 +1947,7 @@
 %!test
 %! x = single ([0, pi/6, pi/4, pi/3, pi/2, 2*pi/3, 3*pi/4, 5*pi/6, pi]);
 %! v = single ([0, 1/2, rt2/2, rt3/2, 1, rt3/2, rt2/2, 1/2, 0]);
-%! assert (sin (x), v, sqrt (eps ('single')));
+%! assert (sin (x), v, sqrt (eps ("single")));
 
 %!error sin ()
 %!error sin (1, 2)
@@ -1804,7 +1978,7 @@
 %!test
 %! x = single ([0, pi/2*i, pi*i, 3*pi/2*i]);
 %! v = single ([0, i, 0, -i]);
-%! assert (sinh (x), v, sqrt (eps ('single')));
+%! assert (sinh (x), v, sqrt (eps ("single")));
 
 %!error sinh ()
 %!error sinh (1, 2)
@@ -1836,8 +2010,8 @@
 
 %!assert (sqrt (single (4)), single (2))
 %!assert (sqrt (single (-1)), single (i))
-%!assert (sqrt (single (1+i)), single (exp (0.5 * log (1+i))), sqrt (eps ('single')))
-%!assert (sqrt (single ([4, -4; i, 1-i])), single ([2, 2i; exp(0.5 * log (i)), exp(0.5 * log (1-i))]), sqrt (eps ('single')))
+%!assert (sqrt (single (1+i)), single (exp (0.5 * log (1+i))), sqrt (eps ("single")))
+%!assert (sqrt (single ([4, -4; i, 1-i])), single ([2, 2i; exp(0.5 * log (i)), exp(0.5 * log (1-i))]), sqrt (eps ("single")))
 
 %!error sqrt ()
 %!error sqrt (1, 2)
@@ -1872,7 +2046,7 @@
 %!test
 %! x = single ([0, pi/6, pi/4, pi/3, 2*pi/3, 3*pi/4, 5*pi/6, pi]);
 %! v = single ([0, rt3/3, 1, rt3, -rt3, -1, -rt3/3, 0]);
-%! assert (tan (x), v,  sqrt (eps ('single')));
+%! assert (tan (x), v,  sqrt (eps ("single")));
 
 %!error tan ()
 %!error tan (1, 2)
@@ -1903,7 +2077,7 @@
 %!test
 %! x = single ([0, pi*i]);
 %! v = single ([0, 0]);
-%! assert (tanh (x), v, sqrt (eps ('single')));
+%! assert (tanh (x), v, sqrt (eps ("single")));
 
 %!error tanh ()
 %!error tanh (1, 2)
@@ -1956,7 +2130,7 @@
 @example\n\
 @group\n\
 tolower (\"MiXeD cAsE 123\")\n\
-     @result{} \"mixed case 123\"\n\
+      @result{} \"mixed case 123\"\n\
 @end group\n\
 @end example\n\
 @seealso{toupper}\n\
@@ -1974,25 +2148,25 @@
 DEFALIAS (lower, tolower);
 
 /*
-%!assert (tolower("OCTAVE"), "octave")
-%!assert (tolower("123OCTave!_&"), "123octave!_&")
-%!assert (tolower({"ABC", "DEF", {"GHI", {"JKL"}}}), {"abc", "def", {"ghi", {"jkl"}}})
-%!assert (tolower(["ABC"; "DEF"]), ["abc"; "def"])
-%!assert (tolower({["ABC"; "DEF"]}), {["abc";"def"]})
-%!assert (tolower(68), "d")
-%!assert (tolower({[68, 68; 68, 68]}), {["dd";"dd"]})
+%!assert (tolower ("OCTAVE"), "octave")
+%!assert (tolower ("123OCTave!_&"), "123octave!_&")
+%!assert (tolower ({"ABC", "DEF", {"GHI", {"JKL"}}}), {"abc", "def", {"ghi", {"jkl"}}})
+%!assert (tolower (["ABC"; "DEF"]), ["abc"; "def"])
+%!assert (tolower ({["ABC"; "DEF"]}), {["abc";"def"]})
+%!assert (tolower (68), "d")
+%!assert (tolower ({[68, 68; 68, 68]}), {["dd";"dd"]})
 %!test
-%!  a(3,3,3,3) = "D";
-%!  assert(tolower(a)(3,3,3,3), "d");
+%! a(3,3,3,3) = "D";
+%! assert (tolower (a)(3,3,3,3), "d");
 
 %!test
 %! charset = char (0:127);
 %! result = charset;
-%! result(toascii ("A":"Z") + 1) = result(toascii ("a":"z") + 1);
-%! assert (all (tolower (charset) == result));
+%! result (toascii ("A":"Z") + 1) = result (toascii ("a":"z") + 1);
+%! assert (tolower (charset), result);
 
-%!error <Invalid call to tolower> tolower()
-%!error <Invalid call to tolower> lower()
+%!error <Invalid call to tolower> lower ()
+%!error <Invalid call to tolower> tolower ()
 %!error tolower (1, 2)
 */
 
@@ -2007,7 +2181,7 @@
 @example\n\
 @group\n\
 toupper (\"MiXeD cAsE 123\")\n\
-     @result{} \"MIXED CASE 123\"\n\
+      @result{} \"MIXED CASE 123\"\n\
 @end group\n\
 @end example\n\
 @seealso{tolower}\n\
@@ -2033,16 +2207,16 @@
 %!assert (toupper (100), "D")
 %!assert (toupper ({[100, 100; 100, 100]}), {["DD";"DD"]})
 %!test
-%!  a(3,3,3,3) = "d";
-%!  assert(toupper (a)(3,3,3,3), "D");
+%! a(3,3,3,3) = "d";
+%! assert (toupper (a)(3,3,3,3), "D");
 %!test
 %! charset = char (0:127);
 %! result = charset;
-%! result(toascii  ("a":"z") + 1) = result(toascii  ("A":"Z") + 1);
-%! assert (all (toupper (charset) == result));
+%! result (toascii  ("a":"z") + 1) = result (toascii  ("A":"Z") + 1);
+%! assert (toupper (charset), result);
 
-%!error <Invalid call to toupper> toupper()
-%!error <Invalid call to toupper> upper()
+%!error <Invalid call to toupper> toupper ()
+%!error <Invalid call to toupper> upper ()
 %!error toupper (1, 2)
 */
 
rename from src/DLD-FUNCTIONS/matrix_type.cc
rename to libinterp/corefcn/matrix_type.cc
--- a/src/DLD-FUNCTIONS/matrix_type.cc
+++ b/libinterp/corefcn/matrix_type.cc
@@ -27,7 +27,7 @@
 #include <algorithm>
 
 #include "ov.h"
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "ov-re-mat.h"
 #include "ov-cx-mat.h"
@@ -36,62 +36,62 @@
 #include "MatrixType.h"
 #include "oct-locbuf.h"
 
-DEFUN_DLD (matrix_type, args, ,
+DEFUN (matrix_type, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{type} =} matrix_type (@var{A})\n\
-@deftypefnx {Loadable Function} {@var{type} =} matrix_type (@var{A}, 'nocompute')\n\
-@deftypefnx {Loadable Function} {@var{A} =} matrix_type (@var{A}, @var{type})\n\
-@deftypefnx {Loadable Function} {@var{A} =} matrix_type (@var{A}, 'upper', @var{perm})\n\
-@deftypefnx {Loadable Function} {@var{A} =} matrix_type (@var{A}, 'lower', @var{perm})\n\
-@deftypefnx {Loadable Function} {@var{A} =} matrix_type (@var{A}, 'banded', @var{nl}, @var{nu})\n\
+@deftypefn  {Built-in Function} {@var{type} =} matrix_type (@var{A})\n\
+@deftypefnx {Built-in Function} {@var{type} =} matrix_type (@var{A}, \"nocompute\")\n\
+@deftypefnx {Built-in Function} {@var{A} =} matrix_type (@var{A}, @var{type})\n\
+@deftypefnx {Built-in Function} {@var{A} =} matrix_type (@var{A}, \"upper\", @var{perm})\n\
+@deftypefnx {Built-in Function} {@var{A} =} matrix_type (@var{A}, \"lower\", @var{perm})\n\
+@deftypefnx {Built-in Function} {@var{A} =} matrix_type (@var{A}, \"banded\", @var{nl}, @var{nu})\n\
 Identify the matrix type or mark a matrix as a particular type.  This allows\n\
 more rapid solutions of linear equations involving @var{A} to be performed.\n\
 Called with a single argument, @code{matrix_type} returns the type of the\n\
 matrix and caches it for future use.  Called with more than one argument,\n\
 @code{matrix_type} allows the type of the matrix to be defined.\n\
 \n\
-If the option 'nocompute' is given, the function will not attempt to guess\n\
+If the option \"nocompute\" is given, the function will not attempt to guess\n\
 the type if it is still unknown.  This is useful for debugging purposes.\n\
 \n\
 The possible matrix types depend on whether the matrix is full or sparse, and\n\
 can be one of the following\n\
 \n\
 @table @asis\n\
-@item 'unknown'\n\
+@item \"unknown\"\n\
 Remove any previously cached matrix type, and mark type as unknown.\n\
 \n\
-@item 'full'\n\
+@item \"full\"\n\
 Mark the matrix as full.\n\
 \n\
-@item 'positive definite'\n\
+@item \"positive definite\"\n\
 Probable full positive definite matrix.\n\
 \n\
-@item 'diagonal'\n\
+@item \"diagonal\"\n\
 Diagonal matrix.  (Sparse matrices only)\n\
 \n\
-@item 'permuted diagonal'\n\
+@item \"permuted diagonal\"\n\
 Permuted Diagonal matrix.  The permutation does not need to be specifically\n\
 indicated, as the structure of the matrix explicitly gives this.  (Sparse\n\
 matrices only)\n\
 \n\
-@item 'upper'\n\
+@item \"upper\"\n\
 Upper triangular.  If the optional third argument @var{perm} is given, the\n\
 matrix is assumed to be a permuted upper triangular with the permutations\n\
 defined by the vector @var{perm}.\n\
 \n\
-@item 'lower'\n\
+@item \"lower\"\n\
 Lower triangular.  If the optional third argument @var{perm} is given, the\n\
 matrix is assumed to be a permuted lower triangular with the permutations\n\
 defined by the vector @var{perm}.\n\
 \n\
-@item 'banded'\n\
-@itemx 'banded positive definite'\n\
+@item \"banded\"\n\
+@itemx \"banded positive definite\"\n\
 Banded matrix with the band size of @var{nl} below the diagonal and @var{nu}\n\
 above it.  If @var{nl} and @var{nu} are 1, then the matrix is tridiagonal and\n\
 treated with specialized code.  In addition the matrix can be marked as\n\
 probably a positive definite.  (Sparse matrices only)\n\
 \n\
-@item 'singular'\n\
+@item \"singular\"\n\
 The matrix is assumed to be singular and will be treated with a minimum norm\n\
 solution.\n\
 \n\
@@ -129,7 +129,7 @@
           autocomp = false;
         }
 
-      if (args(0).is_scalar_type())
+      if (args(0).is_scalar_type ())
         {
           if (nargin == 1)
             retval = octave_value ("Diagonal");
@@ -198,7 +198,7 @@
                 retval = octave_value ("Positive Definite");
               else if (typ == MatrixType::Rectangular)
                 {
-                  if (args(0).rows() == args(0).columns())
+                  if (args(0).rows () == args(0).columns ())
                     retval = octave_value ("Singular");
                   else
                     retval = octave_value ("Rectangular");
@@ -270,7 +270,7 @@
                   else if (str_typ == "unknown")
                     mattyp.invalidate_type ();
                   else
-                    error ("matrix_type: Unknown matrix type %s", str_typ.c_str());
+                    error ("matrix_type: Unknown matrix type %s", str_typ.c_str ());
 
                   if (! error_state)
                     {
@@ -394,7 +394,7 @@
                 retval = octave_value ("Positive Definite");
               else if (typ == MatrixType::Rectangular)
                 {
-                  if (args(0).rows() == args(0).columns())
+                  if (args(0).rows () == args(0).columns ())
                     retval = octave_value ("Singular");
                   else
                     retval = octave_value ("Rectangular");
@@ -436,7 +436,7 @@
                   else if (str_typ == "unknown")
                     mattyp.invalidate_type ();
                   else
-                    error ("matrix_type: Unknown matrix type %s", str_typ.c_str());
+                    error ("matrix_type: Unknown matrix type %s", str_typ.c_str ());
 
                   if (! error_state)
                     {
@@ -477,7 +477,7 @@
                           // Set the matrix type
                           if (args(0).is_single_type ())
                             {
-                              if (args(0).is_complex_type())
+                              if (args(0).is_complex_type ())
                                 retval = octave_value
                                   (args(0).float_complex_matrix_value (),
                                    mattyp);
@@ -488,7 +488,7 @@
                             }
                           else
                             {
-                              if (args(0).is_complex_type())
+                              if (args(0).is_complex_type ())
                                 retval = octave_value
                                   (args(0).complex_matrix_value (),
                                    mattyp);
@@ -508,110 +508,114 @@
 }
 
 /*
-
-## FIXME
+## FIXME:
 ## Disable tests for lower under-determined and upper over-determined
 ## matrices as this detection is disabled in MatrixType due to issues
 ## of non minimum norm solution being found.
 
-%!assert(matrix_type(speye(10,10)),"Diagonal");
-%!assert(matrix_type(speye(10,10)([2:10,1],:)),"Permuted Diagonal");
-%!assert(matrix_type([[speye(10,10);sparse(1,10)],[1;sparse(9,1);1]]),"Upper");
-%!assert(matrix_type([[speye(10,10);sparse(1,10)],[1;sparse(9,1);1]](:,[2,1,3:11])),"Permuted Upper");
-%!assert(matrix_type([speye(10,10),sparse(10,1);1,sparse(1,9),1]),"Lower");
-%!assert(matrix_type([speye(10,10),sparse(10,1);1,sparse(1,9),1]([2,1,3:11],:)),"Permuted Lower");
-%!test
-%! bnd=spparms("bandden");
-%! spparms("bandden",0.5);
-%! a = spdiags(rand(10,3)-0.5,[-1,0,1],10,10);
-%! assert(matrix_type(a),"Tridiagonal");
-%! assert(matrix_type(a'+a+2*speye(10)),"Tridiagonal Positive Definite");
-%! spparms("bandden",bnd);
-%!test
-%! bnd=spparms("bandden");
-%! spparms("bandden",0.5);
-%! a = spdiags(randn(10,4),[-2:1],10,10);
-%! assert(matrix_type(a),"Banded");
-%! assert(matrix_type(a'*a),"Banded Positive Definite");
-%! spparms("bandden",bnd);
-%!test
-%! a=[speye(10,10),[sparse(9,1);1];-1,sparse(1,9),1];
-%! assert(matrix_type(a),"Full");
-%! assert(matrix_type(a'*a),"Positive Definite");
-%!assert(matrix_type(speye(10,11)),"Diagonal");
-%!assert(matrix_type(speye(10,11)([2:10,1],:)),"Permuted Diagonal");
-%!assert(matrix_type(speye(11,10)),"Diagonal");
-%!assert(matrix_type(speye(11,10)([2:11,1],:)),"Permuted Diagonal");
-%#!assert(matrix_type([[speye(10,10);sparse(1,10)],[[1,1];sparse(9,2);[1,1]]]),"Upper");
-%#!assert(matrix_type([[speye(10,10);sparse(1,10)],[[1,1];sparse(9,2);[1,1]]](:,[2,1,3:12])),"Permuted Upper");
-%!assert(matrix_type([speye(11,9),[1;sparse(8,1);1;0]]),"Upper");
-%!assert(matrix_type([speye(11,9),[1;sparse(8,1);1;0]](:,[2,1,3:10])),"Permuted Upper");
-%#!assert(matrix_type([speye(10,10),sparse(10,1);[1;1],sparse(2,9),[1;1]]),"Lower");
-%#!assert(matrix_type([speye(10,10),sparse(10,1);[1;1],sparse(2,9),[1;1]]([2,1,3:12],:)),"Permuted Lower");
-%!assert(matrix_type([speye(9,11);[1,sparse(1,8),1,0]]),"Lower");
-%!assert(matrix_type([speye(9,11);[1,sparse(1,8),1,0]]([2,1,3:10],:)),"Permuted Lower");
-%!assert(matrix_type(spdiags(randn(10,4),[-2:1],10,9)),"Rectangular")
+%!assert (matrix_type (speye (10,10)), "Diagonal")
+%!assert (matrix_type (speye (10,10)([2:10,1],:)), "Permuted Diagonal")
+%!assert (matrix_type ([[speye(10,10);sparse(1,10)],[1;sparse(9,1);1]]), "Upper")
+%!assert (matrix_type ([[speye(10,10);sparse(1,10)],[1;sparse(9,1);1]](:,[2,1,3:11])), "Permuted Upper")
+%!assert (matrix_type ([speye(10,10),sparse(10,1);1,sparse(1,9),1]), "Lower")
+%!assert (matrix_type ([speye(10,10),sparse(10,1);1,sparse(1,9),1]([2,1,3:11],:)), "Permuted Lower")
 
-%!assert(matrix_type(1i*speye(10,10)),"Diagonal");
-%!assert(matrix_type(1i*speye(10,10)([2:10,1],:)),"Permuted Diagonal");
-%!assert(matrix_type([[speye(10,10);sparse(1,10)],[1i;sparse(9,1);1]]),"Upper");
-%!assert(matrix_type([[speye(10,10);sparse(1,10)],[1i;sparse(9,1);1]](:,[2,1,3:11])),"Permuted Upper");
-%!assert(matrix_type([speye(10,10),sparse(10,1);1i,sparse(1,9),1]),"Lower");
-%!assert(matrix_type([speye(10,10),sparse(10,1);1i,sparse(1,9),1]([2,1,3:11],:)),"Permuted Lower");
 %!test
-%! bnd=spparms("bandden");
-%! spparms("bandden",0.5);
-%! assert(matrix_type(spdiags(1i*randn(10,3),[-1,0,1],10,10)),"Tridiagonal");
-%! a = 1i*(rand(9,1)-0.5);a=[[a;0],ones(10,1),[0;-a]];
-%! assert(matrix_type(spdiags(a,[-1,0,1],10,10)),"Tridiagonal Positive Definite");
-%! spparms("bandden",bnd);
+%! bnd = spparms ("bandden");
+%! spparms ("bandden", 0.5);
+%! a = spdiags (rand (10,3)-0.5,[-1,0,1],10,10);
+%! assert (matrix_type (a), "Tridiagonal");
+%! assert (matrix_type (a'+a+2*speye (10)), "Tridiagonal Positive Definite");
+%! spparms ("bandden", bnd);
+%!test
+%! bnd=spparms ("bandden");
+%! spparms ("bandden", 0.5);
+%! a = spdiags (randn (10,4),[-2:1],10,10);
+%! assert (matrix_type (a), "Banded");
+%! assert (matrix_type (a'*a), "Banded Positive Definite");
+%! spparms ("bandden", bnd);
 %!test
-%! bnd=spparms("bandden");
-%! spparms("bandden",0.5);
-%! assert(matrix_type(spdiags(1i*randn(10,4),[-2:1],10,10)),"Banded");
-%! a = 1i*(rand(9,2)-0.5);a=[[a;[0,0]],ones(10,1),[[0;-a(:,2)],[0;0;-a(1:8,1)]]];
-%! assert(matrix_type(spdiags(a,[-2:2],10,10)),"Banded Positive Definite");
-%! spparms("bandden",bnd);
-%!test
-%! a=[speye(10,10),[sparse(9,1);1i];-1,sparse(1,9),1];
-%! assert(matrix_type(a),"Full");
-%! assert(matrix_type(a'*a),"Positive Definite");
-%!assert(matrix_type(1i*speye(10,11)),"Diagonal");
-%!assert(matrix_type(1i*speye(10,11)([2:10,1],:)),"Permuted Diagonal");
-%!assert(matrix_type(1i*speye(11,10)),"Diagonal");
-%!assert(matrix_type(1i*speye(11,10)([2:11,1],:)),"Permuted Diagonal");
-%#!assert(matrix_type([[speye(10,10);sparse(1,10)],[[1i,1i];sparse(9,2);[1i,1i]]]),"Upper");
-%#!assert(matrix_type([[speye(10,10);sparse(1,10)],[[1i,1i];sparse(9,2);[1i,1i]]](:,[2,1,3:12])),"Permuted Upper");
-%!assert(matrix_type([speye(11,9),[1i;sparse(8,1);1i;0]]),"Upper");
-%!assert(matrix_type([speye(11,9),[1i;sparse(8,1);1i;0]](:,[2,1,3:10])),"Permuted Upper");
-%#!assert(matrix_type([speye(10,10),sparse(10,1);[1i;1i],sparse(2,9),[1i;1i]]),"Lower");
-%#!assert(matrix_type([speye(10,10),sparse(10,1);[1i;1i],sparse(2,9),[1i;1i]]([2,1,3:12],:)),"Permuted Lower");
-%!assert(matrix_type([speye(9,11);[1i,sparse(1,8),1i,0]]),"Lower");
-%!assert(matrix_type([speye(9,11);[1i,sparse(1,8),1i,0]]([2,1,3:10],:)),"Permuted Lower");
-%!assert(matrix_type(1i*spdiags(randn(10,4),[-2:1],10,9)),"Rectangular")
+%! a = [speye(10,10),[sparse(9,1);1];-1,sparse(1,9),1];
+%! assert (matrix_type (a), "Full");
+%! assert (matrix_type (a'*a), "Positive Definite");
+
+%!assert (matrix_type (speye (10,11)), "Diagonal")
+%!assert (matrix_type (speye (10,11)([2:10,1],:)), "Permuted Diagonal")
+%!assert (matrix_type (speye (11,10)), "Diagonal")
+%!assert (matrix_type (speye (11,10)([2:11,1],:)), "Permuted Diagonal")
+%#!assert (matrix_type ([[speye(10,10);sparse(1,10)],[[1,1];sparse(9,2);[1,1]]]), "Upper")
+%#!assert (matrix_type ([[speye(10,10);sparse(1,10)],[[1,1];sparse(9,2);[1,1]]](:,[2,1,3:12])), "Permuted Upper")
+%!assert (matrix_type ([speye(11,9),[1;sparse(8,1);1;0]]), "Upper")
+%!assert (matrix_type ([speye(11,9),[1;sparse(8,1);1;0]](:,[2,1,3:10])), "Permuted Upper")
+%#!assert (matrix_type ([speye(10,10),sparse(10,1);[1;1],sparse(2,9),[1;1]]), "Lower")
+%#!assert (matrix_type ([speye(10,10),sparse(10,1);[1;1],sparse(2,9),[1;1]]([2,1,3:12],:)), "Permuted Lower")
+%!assert (matrix_type ([speye(9,11);[1,sparse(1,8),1,0]]), "Lower")
+%!assert (matrix_type ([speye(9,11);[1,sparse(1,8),1,0]]([2,1,3:10],:)), "Permuted Lower")
+%!assert (matrix_type (spdiags (randn (10,4),[-2:1],10,9)), "Rectangular")
+
+%!assert (matrix_type (1i*speye (10,10)), "Diagonal")
+%!assert (matrix_type (1i*speye (10,10)([2:10,1],:)), "Permuted Diagonal")
+%!assert (matrix_type ([[speye(10,10);sparse(1,10)],[1i;sparse(9,1);1]]), "Upper")
+%!assert (matrix_type ([[speye(10,10);sparse(1,10)],[1i;sparse(9,1);1]](:,[2,1,3:11])), "Permuted Upper")
+%!assert (matrix_type ([speye(10,10),sparse(10,1);1i,sparse(1,9),1]), "Lower")
+%!assert (matrix_type ([speye(10,10),sparse(10,1);1i,sparse(1,9),1]([2,1,3:11],:)), "Permuted Lower")
 
 %!test
-%! a = matrix_type(spdiags(randn(10,3),[-1,0,1],10,10),"Singular");
-%! assert(matrix_type(a),"Singular");
-
-%!assert(matrix_type(triu(ones(10,10))),"Upper");
-%!assert(matrix_type(triu(ones(10,10),-1)),"Full");
-%!assert(matrix_type(tril(ones(10,10))),"Lower");
-%!assert(matrix_type(tril(ones(10,10),1)),"Full");
-%!assert(matrix_type(10*eye(10,10) + ones(10,10)), "Positive Definite");
-%!assert(matrix_type(ones(11,10)),"Rectangular")
+%! bnd = spparms ("bandden");
+%! spparms ("bandden", 0.5);
+%! assert (matrix_type (spdiags (1i*randn (10,3),[-1,0,1],10,10)), "Tridiagonal");
+%! a = 1i*(rand (9,1)-0.5);
+%! a = [[a;0],ones(10,1),[0;-a]];
+%! assert (matrix_type (spdiags (a,[-1,0,1],10,10)), "Tridiagonal Positive Definite");
+%! spparms ("bandden", bnd);
+%!test
+%! bnd = spparms ("bandden");
+%! spparms ("bandden", 0.5);
+%! assert (matrix_type (spdiags (1i*randn (10,4),[-2:1],10,10)), "Banded");
+%! a = 1i*(rand (9,2)-0.5);
+%! a = [[a;[0,0]],ones(10,1),[[0;-a(:,2)],[0;0;-a(1:8,1)]]];
+%! assert (matrix_type (spdiags (a,[-2:2],10,10)), "Banded Positive Definite");
+%! spparms ("bandden", bnd);
 %!test
-%! a = matrix_type(ones(10,10),"Singular");
-%! assert(matrix_type(a),"Singular");
+%! a = [speye(10,10),[sparse(9,1);1i];-1,sparse(1,9),1];
+%! assert (matrix_type (a), "Full");
+%! assert (matrix_type (a'*a), "Positive Definite");
+
+%!assert (matrix_type (1i*speye (10,11)), "Diagonal")
+%!assert (matrix_type (1i*speye (10,11)([2:10,1],:)), "Permuted Diagonal")
+%!assert (matrix_type (1i*speye (11,10)), "Diagonal")
+%!assert (matrix_type (1i*speye (11,10)([2:11,1],:)), "Permuted Diagonal")
+%#!assert (matrix_type ([[speye(10,10);sparse(1,10)],[[1i,1i];sparse(9,2);[1i,1i]]]), "Upper")
+%#!assert (matrix_type ([[speye(10,10);sparse(1,10)],[[1i,1i];sparse(9,2);[1i,1i]]](:,[2,1,3:12])), "Permuted Upper")
+%!assert (matrix_type ([speye(11,9),[1i;sparse(8,1);1i;0]]), "Upper")
+%!assert (matrix_type ([speye(11,9),[1i;sparse(8,1);1i;0]](:,[2,1,3:10])), "Permuted Upper")
+%#!assert (matrix_type ([speye(10,10),sparse(10,1);[1i;1i],sparse(2,9),[1i;1i]]), "Lower")
+%#!assert (matrix_type ([speye(10,10),sparse(10,1);[1i;1i],sparse(2,9),[1i;1i]]([2,1,3:12],:)), "Permuted Lower")
+%!assert (matrix_type ([speye(9,11);[1i,sparse(1,8),1i,0]]), "Lower")
+%!assert (matrix_type ([speye(9,11);[1i,sparse(1,8),1i,0]]([2,1,3:10],:)), "Permuted Lower")
+%!assert (matrix_type (1i*spdiags(randn(10,4),[-2:1],10,9)), "Rectangular")
 
-%!assert(matrix_type(triu(1i*ones(10,10))),"Upper");
-%!assert(matrix_type(triu(1i*ones(10,10),-1)),"Full");
-%!assert(matrix_type(tril(1i*ones(10,10))),"Lower");
-%!assert(matrix_type(tril(1i*ones(10,10),1)),"Full");
-%!assert(matrix_type(10*eye(10,10) + 1i*triu(ones(10,10),1) -1i*tril(ones(10,10),-1)), "Positive Definite");
-%!assert(matrix_type(ones(11,10)),"Rectangular")
+%!test
+%! a = matrix_type (spdiags (randn (10,3),[-1,0,1],10,10), "Singular");
+%! assert (matrix_type (a), "Singular");
+
+%!assert (matrix_type (triu (ones(10,10))), "Upper")
+%!assert (matrix_type (triu (ones(10,10),-1)), "Full")
+%!assert (matrix_type (tril (ones(10,10))), "Lower")
+%!assert (matrix_type (tril (ones(10,10),1)), "Full")
+%!assert (matrix_type (10*eye (10,10) + ones (10,10)), "Positive Definite")
+%!assert (matrix_type (ones (11,10)), "Rectangular")
 %!test
-%! a = matrix_type(ones(10,10),"Singular");
-%! assert(matrix_type(a),"Singular");
+%! a = matrix_type (ones (10,10), "Singular");
+%! assert (matrix_type (a), "Singular");
 
+%!assert (matrix_type (triu (1i*ones (10,10))), "Upper")
+%!assert (matrix_type (triu (1i*ones (10,10),-1)), "Full")
+%!assert (matrix_type (tril (1i*ones (10,10))), "Lower")
+%!assert (matrix_type (tril (1i*ones (10,10),1)), "Full")
+%!assert (matrix_type (10*eye (10,10) + 1i*triu (ones (10,10),1) -1i*tril (ones (10,10),-1)), "Positive Definite")
+%!assert (matrix_type (ones (11,10)), "Rectangular")
+%!test
+%! a = matrix_type (ones (10,10), "Singular");
+%! assert (matrix_type (a), "Singular");
 */
rename from src/DLD-FUNCTIONS/max.cc
rename to libinterp/corefcn/max.cc
--- a/src/DLD-FUNCTIONS/max.cc
+++ b/libinterp/corefcn/max.cc
@@ -32,7 +32,7 @@
 #include "CNDArray.h"
 #include "quit.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -74,6 +74,47 @@
   return retval;
 }
 
+// Matlab returns double arrays for min/max operations on character
+// arrays, so we specialize here to get that behavior.  Other possible
+// solutions are to convert the argument to double here and call the
+// code for double, but that could waste memory, or to have the
+// underlying charNDArray::min/max functions return NDArray instead of
+// charNDArray, but that is inconsistent with the way other min/max
+// functions work.
+
+template <>
+octave_value_list
+do_minmax_red_op<charNDArray> (const octave_value& arg,
+                               int nargout, int dim, bool ismin)
+{
+  octave_value_list retval;
+  charNDArray array = octave_value_extract<charNDArray> (arg);
+
+  if (error_state)
+    return retval;
+
+  if (nargout == 2)
+    {
+      retval.resize (2);
+      Array<octave_idx_type> idx;
+      if (ismin)
+        retval(0) = NDArray (array.min (idx, dim));
+      else
+        retval(0) = NDArray (array.max (idx, dim));
+
+      retval(1) = octave_value (idx, true, true);
+    }
+  else
+    {
+      if (ismin)
+        retval(0) = NDArray (array.min (dim));
+      else
+        retval(0) = NDArray (array.max (dim));
+    }
+
+  return retval;
+}
+
 // Specialization for bool arrays.
 template <>
 octave_value_list
@@ -154,6 +195,61 @@
   return retval;
 }
 
+// Matlab returns double arrays for min/max operations on character
+// arrays, so we specialize here to get that behavior.  Other possible
+// solutions are to convert the arguments to double here and call the
+// code for double, but that could waste a lot of memory, or to have the
+// underlying charNDArray::min/max functions return NDArray instead of
+// charNDArray, but that is inconsistent with the way other min/max
+// functions work.
+
+template <>
+octave_value
+do_minmax_bin_op<charNDArray> (const octave_value& argx,
+                               const octave_value& argy, bool ismin)
+{
+  octave_value retval;
+
+  if (argx.is_scalar_type () == 1)
+    {
+      char x = octave_value_extract<char> (argx);
+      charNDArray y = octave_value_extract<charNDArray> (argy);
+
+      if (error_state)
+        ;
+      else if (ismin)
+        retval = NDArray (min (x, y));
+      else
+        retval = NDArray (max (x, y));
+    }
+  else if (argy.is_scalar_type () == 1)
+    {
+      charNDArray x = octave_value_extract<charNDArray> (argx);
+      char y = octave_value_extract<char> (argy);
+
+      if (error_state)
+        ;
+      else if (ismin)
+        retval = NDArray (min (x, y));
+      else
+        retval = NDArray (max (x, y));
+    }
+  else
+    {
+      charNDArray x = octave_value_extract<charNDArray> (argx);
+      charNDArray y = octave_value_extract<charNDArray> (argy);
+
+      if (error_state)
+        ;
+      else if (ismin)
+        retval = NDArray (min (x, y));
+      else
+        retval = NDArray (max (x, y));
+    }
+
+  return retval;
+}
+
 static octave_value_list
 do_minmax_body (const octave_value_list& args,
                 int nargout, bool ismin)
@@ -227,6 +323,9 @@
         case btyp_float_complex:
           retval = do_minmax_red_op<FloatComplexNDArray> (arg, nargout, dim, ismin);
           break;
+        case btyp_char:
+          retval = do_minmax_red_op<charNDArray> (arg, nargout, dim, ismin);
+          break;
 #define MAKE_INT_BRANCH(X) \
         case btyp_ ## X: \
           retval = do_minmax_red_op<X ## NDArray> (arg, nargout, dim, ismin); \
@@ -251,7 +350,11 @@
     {
       octave_value argx = args(0), argy = args(1);
       builtin_type_t xtyp = argx.builtin_type (), ytyp = argy.builtin_type ();
-      builtin_type_t rtyp = btyp_mixed_numeric (xtyp, ytyp);
+      builtin_type_t rtyp;
+      if (xtyp == btyp_char && ytyp == btyp_char)
+        rtyp = btyp_char;
+      else
+        rtyp = btyp_mixed_numeric (xtyp, ytyp);
 
       switch (rtyp)
         {
@@ -281,6 +384,9 @@
         case btyp_float_complex:
           retval = do_minmax_bin_op<FloatComplexNDArray> (argx, argy, ismin);
           break;
+        case btyp_char:
+          retval = do_minmax_bin_op<charNDArray> (argx, argy, ismin);
+          break;
 #define MAKE_INT_BRANCH(X) \
         case btyp_ ## X: \
           retval = do_minmax_bin_op<X ## NDArray> (argx, argy, ismin); \
@@ -305,13 +411,13 @@
   return retval;
 }
 
-DEFUN_DLD (min, args, nargout,
+DEFUN (min, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} min (@var{x})\n\
-@deftypefnx {Loadable Function} {} min (@var{x}, @var{y})\n\
-@deftypefnx {Loadable Function} {} min (@var{x}, [], @var{dim})\n\
-@deftypefnx {Loadable Function} {} min (@var{x}, @var{y}, @var{dim})\n\
-@deftypefnx {Loadable Function} {[@var{w}, @var{iw}] =} min (@var{x})\n\
+@deftypefn  {Built-in Function} {} min (@var{x})\n\
+@deftypefnx {Built-in Function} {} min (@var{x}, @var{y})\n\
+@deftypefnx {Built-in Function} {} min (@var{x}, [], @var{dim})\n\
+@deftypefnx {Built-in Function} {} min (@var{x}, @var{y}, @var{dim})\n\
+@deftypefnx {Built-in Function} {[@var{w}, @var{iw}] =} min (@var{x})\n\
 For a vector argument, return the minimum value.  For a matrix\n\
 argument, return the minimum value from each column, as a row\n\
 vector, or over the dimension @var{dim} if defined, in which case @var{y} \n\
@@ -358,39 +464,35 @@
 }
 
 /*
-
-%% test/octave.test/arith/min-1.m
-%!assert (min ([1, 4, 2, 3]) == 1);
-%!assert (min ([1; -10; 5; -2]) == -10);
-
-%% test/octave.test/arith/min-2.m
-%!assert(all (min ([4, i; -2, 2]) == [-2, i]));
-
-%% test/octave.test/arith/min-3.m
-%!error <Invalid call to min> min ();
-
-%% test/octave.test/arith/min-4.m
-%!error <Invalid call to min> min (1, 2, 3, 4);
+%!assert (min ([1, 4, 2, 3]), 1)
+%!assert (min ([1; -10; 5; -2]), -10)
+%!assert (min ([4, i; -2, 2]), [-2, i])
+%!assert (min (char(42)), 42)
+%!assert (min (char(21), char(3)), 3)
+%!assert (min([char(21), char(3)]), 3)
+%!assert (min([char(100) char(3)], [char(42) char(42)]), [42 3])
 
 %!test
-%! x = reshape (1:8,[2,2,2]);
-%! assert (max (x,[],1), reshape ([2, 4, 6, 8], [1,2,2]));
-%! assert (max (x,[],2), reshape ([3, 4, 7, 8], [2,1,2]));
-%! [y, i ] = max (x, [], 3);
+%! x = reshape (1:8, [2,2,2]);
+%! assert (max (x, [], 1), reshape ([2, 4, 6, 8], [1,2,2]));
+%! assert (max (x, [], 2), reshape ([3, 4, 7, 8], [2,1,2]));
+%! [y, i] = max (x, [], 3);
+%! assert (ndims (y), 2);
 %! assert (y, [5, 7; 6, 8]);
-%! assert (ndims(y), 2);
+%! assert (ndims (i), 2);
 %! assert (i, [2, 2; 2, 2]);
-%! assert (ndims(i), 2);
 
+%!error min ()
+%!error min (1, 2, 3, 4)
 */
 
-DEFUN_DLD (max, args, nargout,
+DEFUN (max, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} max (@var{x})\n\
-@deftypefnx {Loadable Function} {} max (@var{x}, @var{y})\n\
-@deftypefnx {Loadable Function} {} max (@var{x}, [], @var{dim})\n\
-@deftypefnx {Loadable Function} {} max (@var{x}, @var{y}, @var{dim})\n\
-@deftypefnx {Loadable Function} {[@var{w}, @var{iw}] =} max (@var{x})\n\
+@deftypefn  {Built-in Function} {} max (@var{x})\n\
+@deftypefnx {Built-in Function} {} max (@var{x}, @var{y})\n\
+@deftypefnx {Built-in Function} {} max (@var{x}, [], @var{dim})\n\
+@deftypefnx {Built-in Function} {} max (@var{x}, @var{y}, @var{dim})\n\
+@deftypefnx {Built-in Function} {[@var{w}, @var{iw}] =} max (@var{x})\n\
 For a vector argument, return the maximum value.  For a matrix\n\
 argument, return the maximum value from each column, as a row\n\
 vector, or over the dimension @var{dim} if defined, in which case @var{y} \n\
@@ -437,31 +539,22 @@
 }
 
 /*
-
-%% test/octave.test/arith/max-1.m
-%!assert (max ([1, 4, 2, 3]) == 4);
-%!assert (max ([1; -10; 5; -2]) == 5);
-
-%% test/octave.test/arith/max-2.m
-%!assert(all (max ([4, i 4.999; -2, 2, 3+4i]) == [4, 2, 3+4i]));
-
-%% test/octave.test/arith/max-3.m
-%!error <Invalid call to max> max ();
-
-%% test/octave.test/arith/max-4.m
-%!error <Invalid call to max> max (1, 2, 3, 4);
+%!assert (max ([1, 4, 2, 3]), 4)
+%!assert (max ([1; -10; 5; -2]), 5)
+%!assert (max ([4, i 4.999; -2, 2, 3+4i]), [4, 2, 3+4i])
 
 %!test
-%! x = reshape (1:8,[2,2,2]);
-%! assert (min (x,[],1), reshape ([1, 3, 5, 7], [1,2,2]));
-%! assert (min (x,[],2), reshape ([1, 2, 5, 6], [2,1,2]));
-%! [y, i ] = min (x, [], 3);
+%! x = reshape (1:8, [2,2,2]);
+%! assert (min (x, [], 1), reshape ([1, 3, 5, 7], [1,2,2]));
+%! assert (min (x, [], 2), reshape ([1, 2, 5, 6], [2,1,2]));
+%! [y, i] = min (x, [], 3);
+%! assert (ndims(y), 2);
 %! assert (y, [1, 3; 2, 4]);
-%! assert (ndims(y), 2);
+%! assert (ndims(i), 2);
 %! assert (i, [1, 1; 1, 1]);
-%! assert (ndims(i), 2);
 
-
+%!error max ()
+%!error max (1, 2, 3, 4)
 */
 
 template <class ArrayType>
@@ -565,18 +658,18 @@
   return retval;
 }
 
-DEFUN_DLD (cummin, args, nargout,
+DEFUN (cummin, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} cummin (@var{x})\n\
-@deftypefnx {Loadable Function} {} cummin (@var{x}, @var{dim})\n\
-@deftypefnx {Loadable Function} {[@var{w}, @var{iw}] =} cummin (@var{x})\n\
+@deftypefn  {Built-in Function} {} cummin (@var{x})\n\
+@deftypefnx {Built-in Function} {} cummin (@var{x}, @var{dim})\n\
+@deftypefnx {Built-in Function} {[@var{w}, @var{iw}] =} cummin (@var{x})\n\
 Return the cumulative minimum values along dimension @var{dim}.  If @var{dim}\n\
 is unspecified it defaults to column-wise operation.  For example:\n\
 \n\
 @example\n\
 @group\n\
 cummin ([5 4 6 2 3 1])\n\
-    @result{}  5  4  4  2  2  1\n\
+   @result{}  5  4  4  2  2  1\n\
 @end group\n\
 @end example\n\
 \n\
@@ -607,18 +700,18 @@
   return do_cumminmax_body (args, nargout, true);
 }
 
-DEFUN_DLD (cummax, args, nargout,
+DEFUN (cummax, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} cummax (@var{x})\n\
-@deftypefnx {Loadable Function} {} cummax (@var{x}, @var{dim})\n\
-@deftypefnx {Loadable Function} {[@var{w}, @var{iw}] =} cummax (@var{x})\n\
+@deftypefn  {Built-in Function} {} cummax (@var{x})\n\
+@deftypefnx {Built-in Function} {} cummax (@var{x}, @var{dim})\n\
+@deftypefnx {Built-in Function} {[@var{w}, @var{iw}] =} cummax (@var{x})\n\
 Return the cumulative maximum values along dimension @var{dim}.  If @var{dim}\n\
 is unspecified it defaults to column-wise operation.  For example:\n\
 \n\
 @example\n\
 @group\n\
 cummax ([1 3 2 6 4 5])\n\
-    @result{}  1  3  3  6  6  6\n\
+   @result{}  1  3  3  6  6  6\n\
 @end group\n\
 @end example\n\
 \n\
rename from src/DLD-FUNCTIONS/md5sum.cc
rename to libinterp/corefcn/md5sum.cc
--- a/src/DLD-FUNCTIONS/md5sum.cc
+++ b/libinterp/corefcn/md5sum.cc
@@ -28,7 +28,7 @@
 #include <string>
 #include <vector>
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "file-stat.h"
 #include "file-ops.h"
 #include "gripes.h"
@@ -36,10 +36,10 @@
 #include "oct-env.h"
 #include "oct-md5.h"
 
-DEFUN_DLD (md5sum, args, ,
+DEFUN (md5sum, args, ,
    "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} md5sum (@var{file})\n\
-@deftypefnx {Loadable Function} {} md5sum (@var{str}, @var{opt})\n\
+@deftypefn  {Built-in Function} {} md5sum (@var{file})\n\
+@deftypefnx {Built-in Function} {} md5sum (@var{str}, @var{opt})\n\
 Calculate the MD5 sum of the file @var{file}.  If the second parameter\n\
 @var{opt} exists and is true, then calculate the MD5 sum of the\n\
 string @var{str}.\n\
@@ -49,14 +49,14 @@
   int nargin = args.length ();
 
   if (nargin != 1 && nargin != 2)
-    print_usage();
+    print_usage ();
   else
     {
       bool have_str = false;
-      std::string str = args(0).string_value();
+      std::string str = args(0).string_value ();
 
       if (nargin == 2)
-        have_str = args(1).bool_value();
+        have_str = args(1).bool_value ();
 
       if (!error_state)
         {
rename from src/DLD-FUNCTIONS/mgorth.cc
rename to libinterp/corefcn/mgorth.cc
--- a/src/DLD-FUNCTIONS/mgorth.cc
+++ b/libinterp/corefcn/mgorth.cc
@@ -26,7 +26,7 @@
 #endif
 
 #include "oct-norm.h"
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 
@@ -48,18 +48,19 @@
     x = x / h(Vc);
 }
 
-DEFUN_DLD (mgorth, args, nargout,
+DEFUN (mgorth, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {[@var{y}, @var{h}] =} mgorth (@var{x}, @var{v})\n\
-Orthogonalize a given column vector @var{x} with respect to a given\n\
-orthonormal basis @var{v} using a modified Gram-Schmidt orthogonalization.  \n\
+@deftypefn {Built-in Function} {[@var{y}, @var{h}] =} mgorth (@var{x}, @var{v})\n\
+Orthogonalize a given column vector @var{x} with respect to a set of\n\
+orthonormal vectors comprising the columns of @var{v}\n\
+using the modified Gram-Schmidt method.\n\
 On exit, @var{y} is a unit vector such that:\n\
 \n\
 @example\n\
 @group\n\
   norm (@var{y}) = 1\n\
   @var{v}' * @var{y} = 0\n\
-  @var{x} = @var{h}*[@var{v}, @var{y}]\n\
+  @var{x} = [@var{v}, @var{y}]*@var{h}'\n\
 @end group\n\
 @end example\n\
 \n\
@@ -67,7 +68,7 @@
 {
   octave_value_list retval;
 
-  int nargin = args.length();
+  int nargin = args.length ();
 
   if (nargin != 2 || nargout > 2)
   {
@@ -81,7 +82,7 @@
   if (arg_v.ndims () != 2 || arg_x.ndims () != 2 || arg_x.columns () != 1
       || arg_v.rows () != arg_x.rows ())
     {
-      error ("mgorth: V should me a matrix, and X a column vector with"
+      error ("mgorth: V should be a matrix, and X a column vector with"
              " the same number of rows as V.");
       return retval;
     }
@@ -139,9 +140,10 @@
 }
 
 /*
-
 %!test
-%! for ii=1:100; assert (abs (mgorth (randn (5, 1), eye (5, 4))), [0 0 0 0 1]', eps); endfor
+%! for ii=1:100
+%!   assert (abs (mgorth (randn (5, 1), eye (5, 4))), [0 0 0 0 1]', eps);
+%! endfor
 
 %!test
 %! a = hilb (5);
@@ -150,5 +152,4 @@
 %!   a(:, ii) = mgorth (a(:, ii), a(:, 1:ii-1));
 %! endfor
 %! assert (a' * a, eye (5), 1e10);
-
 */
new file mode 100644
--- /dev/null
+++ b/libinterp/corefcn/module.mk
@@ -0,0 +1,100 @@
+EXTRA_DIST += \
+  corefcn/module.mk
+
+## Options functions for Fortran packages like LSODE, DASPK.
+## These are generated automagically by configure and Perl.
+OPT_HANDLERS = \
+  corefcn/DASPK-opts.cc \
+  corefcn/DASRT-opts.cc \
+  corefcn/DASSL-opts.cc \
+  corefcn/LSODE-opts.cc \
+  corefcn/Quad-opts.cc
+
+OPT_INC = \
+  $(top_builddir)/liboctave/numeric/DASPK-opts.h \
+  $(top_builddir)/liboctave/numeric/DASRT-opts.h \
+  $(top_builddir)/liboctave/numeric/DASSL-opts.h \
+  $(top_builddir)/liboctave/numeric/LSODE-opts.h \
+  $(top_builddir)/liboctave/numeric/Quad-opts.h
+
+$(OPT_HANDLERS): corefcn/%.cc : $(top_builddir)/liboctave/numeric/%.in
+	$(PERL) $(top_srcdir)/build-aux/mk-opts.pl --opt-handler-fcns $< > $@-t
+	mv $@-t $@
+
+$(OPT_INC) : %.h : %.in
+	$(MAKE) -C $(top_builddir)/liboctave/numeric $(@F)
+
+COREFCN_SRC = \
+  corefcn/__contourc__.cc \
+  corefcn/__dispatch__.cc \
+  corefcn/__lin_interpn__.cc \
+  corefcn/__pchip_deriv__.cc \
+  corefcn/__qp__.cc \
+  corefcn/balance.cc \
+  corefcn/besselj.cc \
+  corefcn/betainc.cc \
+  corefcn/bitfcns.cc \
+  corefcn/bsxfun.cc \
+  corefcn/cellfun.cc \
+  corefcn/colloc.cc \
+  corefcn/conv2.cc \
+  corefcn/daspk.cc \
+  corefcn/dasrt.cc \
+  corefcn/dassl.cc \
+  corefcn/det.cc \
+  corefcn/dlmread.cc \
+  corefcn/dot.cc \
+  corefcn/eig.cc \
+  corefcn/ellipj.cc \
+  corefcn/fft.cc \
+  corefcn/fft2.cc \
+  corefcn/fftn.cc \
+  corefcn/filter.cc \
+  corefcn/find.cc \
+  corefcn/gammainc.cc \
+  corefcn/gcd.cc \
+  corefcn/getgrent.cc \
+  corefcn/getpwent.cc \
+  corefcn/getrusage.cc \
+  corefcn/givens.cc \
+  corefcn/hess.cc \
+  corefcn/hex2num.cc \
+  corefcn/inv.cc \
+  corefcn/kron.cc \
+  corefcn/lookup.cc \
+  corefcn/lsode.cc \
+  corefcn/lu.cc \
+  corefcn/luinc.cc \
+  corefcn/mappers.cc \
+  corefcn/matrix_type.cc \
+  corefcn/max.cc \
+  corefcn/md5sum.cc \
+  corefcn/mgorth.cc \
+  corefcn/nproc.cc \
+  corefcn/pinv.cc \
+  corefcn/quad.cc \
+  corefcn/quadcc.cc \
+  corefcn/qz.cc \
+  corefcn/rand.cc \
+  corefcn/rcond.cc \
+  corefcn/regexp.cc \
+  corefcn/schur.cc \
+  corefcn/sparse.cc \
+  corefcn/spparms.cc \
+  corefcn/sqrtm.cc \
+  corefcn/str2double.cc \
+  corefcn/strfind.cc \
+  corefcn/strfns.cc \
+  corefcn/sub2ind.cc \
+  corefcn/svd.cc \
+  corefcn/syl.cc \
+  corefcn/syscalls.cc \
+  corefcn/time.cc \
+  corefcn/tril.cc \
+  corefcn/typecast.cc
+
+noinst_LTLIBRARIES += corefcn/libcorefcn.la
+
+corefcn_libcorefcn_la_SOURCES = $(COREFCN_SRC)
+corefcn_libcorefcn_la_CPPFLAGS = $(liboctinterp_la_CPPFLAGS) $(FFTW_XCPPFLAGS)
+
rename from src/DLD-FUNCTIONS/nproc.cc
rename to libinterp/corefcn/nproc.cc
--- a/src/DLD-FUNCTIONS/nproc.cc
+++ b/libinterp/corefcn/nproc.cc
@@ -24,17 +24,18 @@
 #include <config.h>
 #endif
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "nproc.h"
 
-DEFUN_DLD (nproc, args, nargout,
+DEFUN (nproc, args, nargout,
    "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} nproc ()\n\
-@deftypefnx {Loadable Function} {} nproc (@var{query})\n\
+@deftypefn  {Built-in Function} {} nproc ()\n\
+@deftypefnx {Built-in Function} {} nproc (@var{query})\n\
 Return the current number of available processors.\n\
 \n\
 If called with the optional argument @var{query}, modify how processors\n\
 are counted as follows:\n\
+\n\
 @table @code\n\
 @item all\n\
 total number of processors.\n\
@@ -84,8 +85,6 @@
 }
 
 /*
-
-%% Must always report at least 1 cpu available
+## Must always report at least 1 cpu available
 %!assert (nproc () >= 1);
-
 */
rename from src/DLD-FUNCTIONS/pinv.cc
rename to libinterp/corefcn/pinv.cc
--- a/src/DLD-FUNCTIONS/pinv.cc
+++ b/libinterp/corefcn/pinv.cc
@@ -24,7 +24,7 @@
 #include <config.h>
 #endif
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -36,10 +36,10 @@
 #include "ov-flt-cx-diag.h"
 #include "ov-perm.h"
 
-DEFUN_DLD (pinv, args, ,
+DEFUN (pinv, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} pinv (@var{x})\n\
-@deftypefnx {Loadable Function} {} pinv (@var{x}, @var{tol})\n\
+@deftypefn  {Built-in Function} {} pinv (@var{x})\n\
+@deftypefnx {Built-in Function} {} pinv (@var{x}, @var{tol})\n\
 Return the pseudoinverse of @var{x}.  Singular values less than\n\
 @var{tol} are ignored.\n\
 \n\
rename from src/DLD-FUNCTIONS/quad.cc
rename to libinterp/corefcn/quad.cc
--- a/src/DLD-FUNCTIONS/quad.cc
+++ b/libinterp/corefcn/quad.cc
@@ -32,7 +32,7 @@
 #include "Quad.h"
 #include "lo-mappers.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "pager.h"
@@ -150,7 +150,7 @@
 #define QUAD_ABORT() \
   do \
     { \
-      if (fcn_name.length()) \
+      if (fcn_name.length ()) \
         clear_function (fcn_name); \
       return retval; \
     } \
@@ -172,12 +172,12 @@
     } \
   while (0)
 
-DEFUN_DLD (quad, args, nargout,
+DEFUN (quad, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{q} =} quad (@var{f}, @var{a}, @var{b})\n\
-@deftypefnx {Loadable Function} {@var{q} =} quad (@var{f}, @var{a}, @var{b}, @var{tol})\n\
-@deftypefnx {Loadable Function} {@var{q} =} quad (@var{f}, @var{a}, @var{b}, @var{tol}, @var{sing})\n\
-@deftypefnx {Loadable Function} {[@var{q}, @var{ier}, @var{nfun}, @var{err}] =} quad (@dots{})\n\
+@deftypefn  {Built-in Function} {@var{q} =} quad (@var{f}, @var{a}, @var{b})\n\
+@deftypefnx {Built-in Function} {@var{q} =} quad (@var{f}, @var{a}, @var{b}, @var{tol})\n\
+@deftypefnx {Built-in Function} {@var{q} =} quad (@var{f}, @var{a}, @var{b}, @var{tol}, @var{sing})\n\
+@deftypefnx {Built-in Function} {[@var{q}, @var{ier}, @var{nfun}, @var{err}] =} quad (@dots{})\n\
 Numerically evaluate the integral of @var{f} from @var{a} to @var{b} using\n\
 Fortran routines from @w{@sc{quadpack}}.  @var{f} is a function handle,\n\
 inline function, or a string containing the name of the function to\n\
@@ -192,7 +192,7 @@
 absolute tolerance, and the second element is the desired relative\n\
 tolerance.  To choose a relative test only, set the absolute\n\
 tolerance to zero.  To choose an absolute test only, set the relative\n\
-tolerance to zero.  Both tolerances default to @code{sqrt(eps)} or\n\
+tolerance to zero.  Both tolerances default to @code{sqrt (eps)} or\n\
 approximately @math{1.5e^{-8}}.\n\
 \n\
 The optional argument @var{sing} is a vector of values at which the\n\
@@ -463,7 +463,7 @@
           retval(0) = val;
         }
 
-      if (fcn_name.length())
+      if (fcn_name.length ())
         clear_function (fcn_name);
     }
   else
@@ -473,19 +473,23 @@
 }
 
 /*
-
 %!function y = __f (x)
-%! y = x + 1;
+%!  y = x + 1;
 %!endfunction
 
 %!test
 %! [v, ier, nfun, err] = quad ("__f", 0, 5);
-%! assert(ier == 0 && abs (v - 17.5) < sqrt (eps) && nfun > 0 &&
-%!        err < sqrt (eps))
+%! assert (ier, 0);
+%! assert (v, 17.5, sqrt (eps));
+%! assert (nfun > 0);
+%! assert (err < sqrt (eps));
+
 %!test
-%! [v, ier, nfun, err] = quad ("__f", single(0), single(5));
-%! assert(ier == 0 && abs (v - 17.5) < sqrt (eps ("single")) && nfun > 0 &&
-%!        err < sqrt (eps ("single")))
+%! [v, ier, nfun, err] = quad ("__f", single (0), single (5));
+%! assert (ier, 0);
+%! assert (v, 17.5, sqrt (eps ("single")));
+%! assert (nfun > 0);
+%! assert (err < sqrt (eps ("single")));
 
 %!function y = __f (x)
 %!  y = x .* sin (1 ./ x) .* sqrt (abs (1 - x));
@@ -493,19 +497,22 @@
 
 %!test
 %!  [v, ier, nfun, err] = quad ("__f", 0.001, 3);
-%! assert((ier == 0 || ier == 1) && abs (v - 1.98194120273598) < sqrt (eps) && nfun > 0);
+%! assert (ier == 0 || ier == 1);
+%! assert (v, 1.98194120273598, sqrt (eps));
+%! assert (nfun > 0);
+
 %!test
-%!  [v, ier, nfun, err] = quad ("__f", single(0.001), single(3));
-%! assert((ier == 0 || ier == 1) && abs (v - 1.98194120273598) < sqrt (eps ("single")) && nfun > 0);
+%!  [v, ier, nfun, err] = quad ("__f", single (0.001), single (3));
+%! assert (ier == 0 || ier == 1);
+%! assert (v, 1.98194120273598, sqrt (eps ("single")));
+%! assert (nfun > 0);
 
-%!error <Invalid call to quad> quad ();
-
-%!error <Invalid call to quad> quad ("__f", 1, 2, 3, 4, 5);
+%!error quad ()
+%!error quad ("__f", 1, 2, 3, 4, 5)
 
 %!test
 %! quad_options ("absolute tolerance", eps);
-%! assert(quad_options ("absolute tolerance") == eps);
+%! assert (quad_options ("absolute tolerance") == eps);
 
-%!error <Invalid call to quad_options> quad_options (1, 2, 3);
-
+%!error quad_options (1, 2, 3)
 */
rename from src/DLD-FUNCTIONS/quadcc.cc
rename to libinterp/corefcn/quadcc.cc
--- a/src/DLD-FUNCTIONS/quadcc.cc
+++ b/libinterp/corefcn/quadcc.cc
@@ -24,15 +24,21 @@
 #include <config.h>
 #endif
 
-#include <stdlib.h>
-#include "lo-math.h"
 #include "lo-ieee.h"
-#include "oct.h"
 #include "parse.h"
-#include "ov-fcn-handle.h"
+#include "variables.h"
+
+#include "defun.h"
+#include "error.h"
+#include "oct-obj.h"
+#include "utils.h"
 
-/* Define the size of the interval heap. */
-#define cquad_heapsize                  200
+
+/* Extended debugging */
+#define DEBUG_QUADCC 0
+
+/* Define the minimum size of the interval heap. */
+#define min_cquad_heapsize  200 
 
 
 /* Data of a single interval */
@@ -1469,7 +1475,7 @@
 
 /* The actual integration routine.  */
 
-DEFUN_DLD (quadcc, args, nargout,
+DEFUN (quadcc, args, nargout,
 "-*- texinfo -*-\n\
 @deftypefn  {Function File} {@var{q} =} quadcc (@var{f}, @var{a}, @var{b})\n\
 @deftypefnx {Function File} {@var{q} =} quadcc (@var{f}, @var{a}, @var{b}, @var{tol})\n\
@@ -1485,7 +1491,7 @@
 values if given a vector of input values.  For example,\n\
 \n\
 @example\n\
-   f = @@(x) x .* sin (1./x) .* sqrt (abs (1 - x));\n\
+f = @@(x) x .* sin (1./x) .* sqrt (abs (1 - x));\n\
 @end example\n\
 \n\
 @noindent\n\
@@ -1493,7 +1499,7 @@
 \n\
 @var{a} and @var{b} are the lower and upper limits of integration.  Either\n\
 or both limits may be infinite.  @code{quadcc} handles an inifinite limit\n\
-by substituting the variable of integration with @code{x=tan(pi/2*u)}.\n\
+by substituting the variable of integration with @code{x = tan (pi/2*u)}.\n\
 \n\
 The optional argument @var{tol} defines the relative tolerance used to stop\n\
 the integration procedure.  The default value is @math{1e^{-6}}.\n\
@@ -1505,7 +1511,7 @@
 @code{quadcc} would be as follows\n\
 \n\
 @example\n\
-   int = quadcc (f, a, b, 1.0e-6, [ 1 ]);\n\
+int = quadcc (f, a, b, 1.0e-6, [ 1 ]);\n\
 @end example\n\
 \n\
 The result of the integration is returned in @var{q}.\n\
@@ -1546,14 +1552,10 @@
   static const double w = M_SQRT2 / 2;
   static const int ndiv_max = 20;
 
-  /* The interval heap. */
-  cquad_ival ivals[cquad_heapsize];
-  int heap[cquad_heapsize];
-
   /* Arguments left and right */
   int nargin = args.length ();
   octave_function *fcn;
-  double a, b, tol, iivals[cquad_heapsize], *sing;
+  double a, b, tol, *sing;
 
   /* Variables needed for transforming the integrand. */
   bool wrap = false;
@@ -1583,7 +1585,7 @@
     fcn = args(0).function_value ();
   else
     {
-       std::string fcn_name = unique_symbol_name ("__quadcc_fcn_");
+       std::string fcn_name = unique_symbol_name ("__quadcc_fcn__");
        std::string fname = "function y = ";
        fname.append (fcn_name);
        fname.append ("(x) y = ");
@@ -1591,7 +1593,7 @@
                                "; endfunction");
     }
 
-  if (!args(1).is_real_scalar ())
+  if (! args(1).is_real_scalar ())
     {
       error ("quadcc: lower limit of integration (A) must be a single real scalar");
       return retval;
@@ -1599,7 +1601,7 @@
   else
     a = args(1).double_value ();
 
-  if (!args(2).is_real_scalar ())
+  if (! args(2).is_real_scalar ())
     {
       error ("quadcc: upper limit of integration (B) must be a single real scalar");
       return retval;
@@ -1609,7 +1611,7 @@
 
   if (nargin < 4 || args(3).is_empty ())
     tol = 1.0e-6;
-  else if (!args(3).is_real_scalar () || args(3).double_value () <= 0)
+  else if (! args(3).is_real_scalar () || args(3).double_value () <= 0)
     {
       error ("quadcc: tolerance (TOL) must be a single real scalar > 0");
       return retval;
@@ -1620,8 +1622,6 @@
   if (nargin < 5)
     {
       nivals = 1;
-      iivals[0] = a;
-      iivals[1] = b;
     }
   else if (!(args(4).is_real_scalar () || args(4).is_real_matrix ()))
     {
@@ -1630,16 +1630,27 @@
     }
   else
     {
-      nivals = 1 + args(4).length ();
-      if (nivals > cquad_heapsize)
-        {
-          error ("quadcc: maximum number of singular points is limited to %i",
-                 cquad_heapsize-1);
-          return retval;
-        }
+      nivals = 1 + args(4).numel ();
+    }
+
+  int cquad_heapsize = (nivals >= min_cquad_heapsize ? nivals + 1 
+                                                     : min_cquad_heapsize);
+  /* The interval heap. */
+  OCTAVE_LOCAL_BUFFER (cquad_ival, ivals, cquad_heapsize);
+  OCTAVE_LOCAL_BUFFER (double, iivals, cquad_heapsize);
+  OCTAVE_LOCAL_BUFFER (int, heap, cquad_heapsize);
+
+  if (nivals == 1)
+    {
+      iivals[0] = a;
+      iivals[1] = b;
+    }
+  else
+    {
+      // Intervals around singularities
       sing = args(4).array_value ().fortran_vec ();
       iivals[0] = a;
-      for (i = 0; i < nivals - 2; i++)
+      for (i = 0; i < nivals - 1; i++)
         iivals[i + 1] = sing[i];
       iivals[nivals] = b;
     }
@@ -1648,7 +1659,7 @@
   if (xisinf (a) || xisinf (b))
     {
       wrap = true;
-      for (i = 0; i <= nivals; i++)
+      for (i = 0; i < nivals + 1; i++)
         if (xisinf (iivals[i]))
           iivals[i] = gnulib::copysign (1.0, iivals[i]);
         else
@@ -1660,7 +1671,6 @@
   for (i = 0; i < cquad_heapsize; i++)
     heap[i] = i;
 
-
   /* Create the first interval(s). */
   igral = 0.0;
   err = 0.0;
@@ -1676,16 +1686,16 @@
       if (wrap)
         {
           for (i = 0; i <= n[3]; i++)
-            ex (i) = tan (M_PI / 2 * (m + xi[i] * h));
+            ex(i) = tan (M_PI / 2 * (m + xi[i] * h));
         }
       else
         {
           for (i = 0; i <= n[3]; i++)
-            ex (i) = m + xi[i] * h;
+            ex(i) = m + xi[i] * h;
         }
       fargs(0) = ex;
       fvals = feval (fcn, fargs, 1);
-      if (fvals.length () != 1 || !fvals(0).is_real_matrix ())
+      if (fvals.length () != 1 || ! fvals(0).is_real_matrix ())
         {
           error ("quadcc: integrand F must return a single, real-valued vector");
           return retval;
@@ -1698,14 +1708,14 @@
         }
       for (i = 0; i <= n[3]; i++)
         {
-          iv->fx[i] = effex (i);
+          iv->fx[i] = effex(i);
           if (wrap)
             {
               xw = ex(i);
               iv->fx[i] *= (1.0 + xw * xw) * M_PI / 2;
             }
           neval++;
-          if (!xfinite (iv->fx[i]))
+          if (! xfinite (iv->fx[i]))
             {
               nans[nnans++] = i;
               iv->fx[i] = 0.0;
@@ -1777,10 +1787,12 @@
       m = (iv->a + iv->b) / 2;
       h = (iv->b - iv->a) / 2;
 
-/*      printf
+#if (DEBUG_QUADCC)
+      printf
         ("quadcc: processing ival %i (of %i) with [%e,%e] int=%e, err=%e, depth=%i\n",
          heap[0], nivals, iv->a, iv->b, iv->igral, iv->err, iv->depth);
-*/
+#endif
+
       /* Should we try to increase the degree? */
       if (iv->depth < 3)
         {
@@ -1794,17 +1806,16 @@
             if (wrap)
               {
                 for (i = 0; i < n[d] / 2; i++)
-                  ex (i) =
-                    tan (M_PI / 2 * (m + xi[(2 * i + 1) * skip[d]] * h));
+                  ex(i) = tan (M_PI / 2 * (m + xi[(2 * i + 1) * skip[d]] * h));
               }
             else
               {
                 for (i = 0; i < n[d] / 2; i++)
-                  ex (i) = m + xi[(2 * i + 1) * skip[d]] * h;
+                  ex(i) = m + xi[(2 * i + 1) * skip[d]] * h;
               }
             fargs(0) = ex;
             fvals = feval (fcn, fargs, 1);
-            if (fvals.length () != 1 || !fvals(0).is_real_matrix ())
+            if (fvals.length () != 1 || ! fvals(0).is_real_matrix ())
               {
                 error ("quadcc: integrand F must return a single, real-valued vector");
                 return retval;
@@ -1819,7 +1830,7 @@
             for (i = 0; i < n[d] / 2; i++)
               {
                 j = (2 * i + 1) * skip[d];
-                iv->fx[j] = effex (i);
+                iv->fx[j] = effex(i);
                 if (wrap)
                   {
                     xw = ex(i);
@@ -1830,7 +1841,7 @@
           nnans = 0;
           for (i = 0; i <= 32; i += skip[d])
             {
-              if (!xfinite (iv->fx[i]))
+              if (! xfinite (iv->fx[i]))
                 {
                   nans[nnans++] = i;
                   iv->fx[i] = 0.0;
@@ -1880,14 +1891,16 @@
       /* Should we drop this interval? */
       if ((m + h * xi[0]) >= (m + h * xi[1])
           || (m + h * xi[31]) >= (m + h * xi[32])
-          || iv->err < fabs (iv->igral) * DBL_EPSILON * 10)
+          || iv->err < fabs (iv->igral) * std::numeric_limits<double>::epsilon () * 10)
         {
 
-/*          printf
+#if (DEBUG_QUADCC)
+          printf
             ("quadcc: dropping ival %i (of %i) with [%e,%e] int=%e, err=%e, depth=%i\n",
              heap[0], nivals, iv->a, iv->b, iv->igral, iv->err,
              iv->depth);
-*/
+#endif
+
           /* Keep this interval's contribution */
           err_final += iv->err;
           igral_final += iv->igral;
@@ -1900,7 +1913,6 @@
           i = 0;
           while (2 * i + 1 < nivals)
             {
-
               /* Get the kids */
               j = 2 * i + 1;
               /* If the j+1st entry exists and is larger than the jth,
@@ -1943,16 +1955,16 @@
             if (wrap)
               {
                 for (i = 0; i < n[0] - 1; i++)
-                  ex (i) = tan (M_PI / 2 * (ml + xi[(i + 1) * skip[0]] * hl));
+                  ex(i) = tan (M_PI / 2 * (ml + xi[(i + 1) * skip[0]] * hl));
               }
             else
               {
                 for (i = 0; i < n[0] - 1; i++)
-                  ex (i) = ml + xi[(i + 1) * skip[0]] * hl;
+                  ex(i) = ml + xi[(i + 1) * skip[0]] * hl;
               }
             fargs(0) = ex;
             fvals = feval (fcn, fargs, 1);
-            if (fvals.length () != 1 || !fvals(0).is_real_matrix ())
+            if (fvals.length () != 1 || ! fvals(0).is_real_matrix ())
               {
                 error ("quadcc: integrand F must return a single, real-valued vector");
                 return retval;
@@ -1967,7 +1979,7 @@
             for (i = 0; i < n[0] - 1; i++)
               {
                 j = (i + 1) * skip[0];
-                ivl->fx[j] = effex (i);
+                ivl->fx[j] = effex(i);
                 if (wrap)
                   {
                     xw = ex(i);
@@ -1978,7 +1990,7 @@
           nnans = 0;
           for (i = 0; i <= 32; i += skip[0])
             {
-              if (!xfinite (ivl->fx[i]))
+              if (! xfinite (ivl->fx[i]))
                 {
                   nans[nnans++] = i;
                   ivl->fx[i] = 0.0;
@@ -2039,16 +2051,16 @@
             if (wrap)
               {
                 for (i = 0; i < n[0] - 1; i++)
-                  ex (i) = tan (M_PI / 2 * (mr + xi[(i + 1) * skip[0]] * hr));
+                  ex(i) = tan (M_PI / 2 * (mr + xi[(i + 1) * skip[0]] * hr));
               }
             else
               {
                 for (i = 0; i < n[0] - 1; i++)
-                  ex (i) = mr + xi[(i + 1) * skip[0]] * hr;
+                  ex(i) = mr + xi[(i + 1) * skip[0]] * hr;
               }
             fargs(0) = ex;
             fvals = feval (fcn, fargs, 1);
-            if (fvals.length () != 1 || !fvals(0).is_real_matrix ())
+            if (fvals.length () != 1 || ! fvals(0).is_real_matrix ())
               {
                 error ("quadcc: integrand F must return a single, real-valued vector");
                 return retval;
@@ -2063,7 +2075,7 @@
             for (i = 0; i < n[0] - 1; i++)
               {
                 j = (i + 1) * skip[0];
-                ivr->fx[j] = effex (i);
+                ivr->fx[j] = effex(i);
                 if (wrap)
                   {
                     xw = ex(i);
@@ -2074,7 +2086,7 @@
           nnans = 0;
           for (i = 0; i <= 32; i += skip[0])
             {
-              if (!xfinite (ivr->fx[i]))
+              if (! xfinite (ivr->fx[i]))
                 {
                   nans[nnans++] = i;
                   ivr->fx[i] = 0.0;
@@ -2190,16 +2202,16 @@
 
         }
 
-      /* If the heap is about to overflow, remove the last two
-         intervals. */
+      /* If the heap is about to overflow, remove the last two intervals. */
       while (nivals > cquad_heapsize - 2)
         {
           iv = &(ivals[heap[nivals - 1]]);
-/*          printf
+#if (DEBUG_QUADCC)
+          printf
             ("quadcc: dropping ival %i (of %i) with [%e,%e] int=%e, err=%e, depth=%i\n",
              heap[0], nivals, iv->a, iv->b, iv->igral, iv->err,
              iv->depth);
-*/
+#endif
           err_final += iv->err;
           igral_final += iv->igral;
           nivals--;
@@ -2217,7 +2229,8 @@
     }
 
   /* Dump the contents of the heap. */
-/*  for (i = 0; i < nivals; i++)
+#if (DEBUG_QUADCC)
+  for (i = 0; i < nivals; i++)
     {
       iv = &(ivals[heap[i]]);
       printf
@@ -2225,7 +2238,8 @@
          i, heap[i], iv->a, iv->b, iv->igral, iv->err, iv->depth,
          iv->rdepth, iv->ndiv);
     }
-*/
+#endif
+
   /* Clean up and present the results. */
   if (nargout > 2)
     retval(2) = neval;
@@ -2238,18 +2252,17 @@
 
 
 /*
-
-%!assert (quadcc(@sin,-pi,pi), 0, 1e-6)
-%!assert (quadcc(inline('sin'),-pi,pi), 0, 1e-6)
-%!assert (quadcc('sin',-pi,pi), 0, 1e-6)
+%!assert (quadcc (@sin, -pi, pi), 0, 1e-6)
+%!assert (quadcc (inline ("sin"),- pi, pi), 0, 1e-6)
+%!assert (quadcc ("sin", -pi, pi), 0, 1e-6)
 
-%!assert (quadcc(@sin,-pi,0), -2, 1e-6)
-%!assert (quadcc(@sin,0,pi), 2, 1e-6)
-%!assert (quadcc(@(x) 1./sqrt(x), 0, 1), 2, 1e-6)
-%!assert (quadcc(@(x) 1./(sqrt(x).*(x+1)), 0, Inf), pi, 1e-6)
+%!assert (quadcc (@sin, -pi, 0), -2, 1e-6)
+%!assert (quadcc (@sin, 0, pi), 2, 1e-6)
+%!assert (quadcc (@(x) 1./sqrt (x), 0, 1), 2, 1e-6)
+%!assert (quadcc (@(x) 1./(sqrt (x).*(x+1)), 0, Inf), pi, 1e-6)
 
-%!assert (quadcc (@(x) exp(-x .^ 2), -Inf, Inf), sqrt(pi), 1e-6)
-%!assert (quadcc (@(x) exp(-x .^ 2), -Inf, 0), sqrt(pi)/2, 1e-6)
+%!assert (quadcc (@(x) exp (-x .^ 2), -Inf, Inf), sqrt (pi), 1e-6)
+%!assert (quadcc (@(x) exp (-x .^ 2), -Inf, 0), sqrt (pi)/2, 1e-6)
 
 ## Test function with NaNs in interval 
 %!function y = __nansin (x)
@@ -2261,18 +2274,17 @@
 
 %!test
 %! [q, err, npoints] = quadcc ("__nansin", -pi, pi); 
-%! assert (q, 0, eps);
+%! assert (q, 0, 1e-6);
 %! assert (err, 0, 15*eps);
 
 %% Test input validation
 %!error (quadcc ())
 %!error (quadcc (@sin))
 %!error (quadcc (@sin, 0))
-%!error (quadcc (@sin, ones(2), pi))
+%!error (quadcc (@sin, ones (2), pi))
 %!error (quadcc (@sin, -i, pi))
-%!error (quadcc (@sin, 0, ones(2)))
+%!error (quadcc (@sin, 0, ones (2)))
 %!error (quadcc (@sin, 0, i))
 %!error (quadcc (@sin, 0, pi, 0))
 %!error (quadcc (@sin, 0, pi, 1e-6, [ i ]))
-
 */
rename from src/DLD-FUNCTIONS/qz.cc
rename to libinterp/corefcn/qz.cc
--- a/src/DLD-FUNCTIONS/qz.cc
+++ b/libinterp/corefcn/qz.cc
@@ -44,7 +44,7 @@
 #include "lo-math.h"
 #include "quit.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -290,10 +290,10 @@
 
 //FIXME: Matlab does not produce lambda as the first output argument.
 //       Compatibility problem?
-DEFUN_DLD (qz, args, nargout,
+DEFUN (qz, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{lambda} =} qz (@var{A}, @var{B})\n\
-@deftypefnx {Loadable Function} {@var{lambda} =} qz (@var{A}, @var{B}, @var{opt})\n\
+@deftypefn  {Built-in Function} {@var{lambda} =} qz (@var{A}, @var{B})\n\
+@deftypefnx {Built-in Function} {@var{lambda} =} qz (@var{A}, @var{B}, @var{opt})\n\
 QZ@tie{}decomposition of the generalized eigenvalue problem\n\
 (@math{A x = s B x}).  There are three ways to call this function:\n\
 @enumerate\n\
@@ -322,9 +322,9 @@
 @example\n\
 @group\n\
 \n\
-    A * V = B * V * diag (@var{lambda})\n\
-    W' * A = diag (@var{lambda}) * W' * B\n\
-    AA = Q * A * Z, BB = Q * B * Z\n\
+A * V = B * V * diag (@var{lambda})\n\
+W' * A = diag (@var{lambda}) * W' * B\n\
+AA = Q * A * Z, BB = Q * B * Z\n\
 \n\
 @end group\n\
 @end example\n\
@@ -344,6 +344,7 @@
 @item opt\n\
 for ordering eigenvalues of the GEP pencil.  The leading block\n\
 of the revised pencil contains all eigenvalues that satisfy:\n\
+\n\
 @table @asis\n\
 @item \"N\"\n\
 = unordered (default)\n\
@@ -533,7 +534,7 @@
   ComplexMatrix CQ(nn,nn), CZ(nn,nn), CVR(nn,nn), CVL(nn,nn);
   octave_idx_type ilo, ihi, info;
   char compq = (nargout >= 3 ? 'V' : 'N');
-  char compz = (nargout >= 4 ? 'V' : 'N');
+  char compz = ((nargout >= 4 || nargin == 3)? 'V' : 'N');
 
   // Initialize Q, Z to identity if we need either of them.
   if (compq == 'V' || compz == 'V')
@@ -848,7 +849,7 @@
                      nn, nn, aa.data (), nn, work.fortran_vec (), inf_norm
                      F77_CHAR_ARG_LEN (1)));
 
-          double eps = DBL_EPSILON * inf_norm * nn;
+          double eps = std::numeric_limits<double>::epsilon () * inf_norm * nn;
 
 #ifdef DEBUG_SORT
           std::cout << "qz: calling dsubsp: aa=" << std::endl;
@@ -1181,7 +1182,12 @@
 
     case 3:
       if (nargin == 3)
-        retval(2) = CZ;
+        {
+          if (complex_case)
+            retval(2) = CZ;
+          else
+            retval(2) = ZZ;
+        }
       else
         {
           if (complex_case)
@@ -1195,7 +1201,7 @@
         if (complex_case)
           {
 #ifdef DEBUG
-            std::cout << "qz: retval (1) = cbb = " << std::endl;
+            std::cout << "qz: retval(1) = cbb = " << std::endl;
             octave_print_internal (std::cout, cbb, 0);
             std::cout << std::endl << "qz: retval(0) = caa = " <<std::endl;
             octave_print_internal (std::cout, caa, 0);
@@ -1207,7 +1213,7 @@
       else
         {
 #ifdef DEBUG
-          std::cout << "qz: retval (1) = bb = " << std::endl;
+          std::cout << "qz: retval(1) = bb = " << std::endl;
           octave_print_internal (std::cout, bb, 0);
           std::cout << std::endl << "qz: retval(0) = aa = " <<std::endl;
           octave_print_internal (std::cout, aa, 0);
@@ -1242,27 +1248,31 @@
 
 /*
 %!shared a, b, c
-%!  a = [1 2; 0 3];
-%!  b = [1 0; 0 0];
-%!  c = [0 1; 0 0];
-%!assert(qz (a,b), 1);
-%!assert(isempty (qz (a,c)));
+%! a = [1 2; 0 3];
+%! b = [1 0; 0 0];
+%! c = [0 1; 0 0];
+%!assert (qz (a,b), 1)
+%!assert (isempty (qz (a,c)))
 
-%% Exaple 7.7.3 in Golub & Van Loan
+## Exaple 7.7.3 in Golub & Van Loan
 %!test
 %! a = [ 10  1  2;
 %!        1  2 -1;
 %!        1  1  2];
-%! b = reshape(1:9,3,3);
+%! b = reshape (1:9,3,3);
 %! [aa, bb, q, z, v, w, lambda] = qz (a, b);
-%! sz = length(lambda);
-%! observed =  (b * v * diag ([lambda;0])) (:, 1:sz);
+%! sz = length (lambda);
+%! observed = (b * v * diag ([lambda;0])) (:, 1:sz);
 %! assert ( (a*v) (:, 1:sz), observed, norm (observed) * 1e-14);
 %! observed = (diag ([lambda;0]) * w' * b) (1:sz, :);
 %! assert ( (w'*a) (1:sz, :) , observed, norm (observed) * 1e-13);
 %! assert (q * a * z, aa, norm (aa) * 1e-14);
 %! assert (q * b * z, bb, norm (bb) * 1e-14);
 
-%% FIXME: Still need a test for third form of calling qz
-
+%!test
+%! A = [0, 0, -1, 0; 1, 0, 0, 0; -1, 0, -2, -1; 0, -1, 1, 0];
+%! B = [0, 0, 0, 0; 0, 1, 0, 0; 0, 0, 1, 0; 0, 0, 0, 1];
+%! [AA, BB, Q, Z1] = qz (A, B);
+%! [AA, BB, Z2] = qz (A, B, '-');
+%! assert (Z1, Z2);
 */
rename from src/DLD-FUNCTIONS/rand.cc
rename to libinterp/corefcn/rand.cc
--- a/src/DLD-FUNCTIONS/rand.cc
+++ b/libinterp/corefcn/rand.cc
@@ -1,3 +1,4 @@
+
 /*
 
 Copyright (C) 1996-2012 John W. Eaton
@@ -38,7 +39,7 @@
 #include "oct-rand.h"
 #include "quit.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -48,7 +49,7 @@
 
 /*
 %!shared __random_statistical_tests__
-%! % Flag whether the statistical tests should be run in "make check" or not
+%! # Flag whether the statistical tests should be run in "make check" or not
 %! __random_statistical_tests__ = 0;
 */
 
@@ -60,6 +61,7 @@
   NDArray a;
   int idx = 0;
   dim_vector dims;
+  bool is_single = false;
 
   unwind_protect frame;
   // Restore current distribution on any exit.
@@ -68,6 +70,19 @@
 
   octave_rand::distribution (distribution);
 
+  if (nargin > 0 && args(nargin-1).is_string ())
+    {
+      std::string s_arg = args(nargin-1).string_value ();
+
+      if (s_arg == "single")
+        {
+          is_single = true;
+          nargin--;
+        }
+      else if (s_arg == "double")
+        nargin--;
+    }
+
   if (additional_arg)
     {
       if (nargin == 0)
@@ -75,7 +90,7 @@
           error ("%s: expecting at least one argument", fcn);
           goto done;
         }
-      else if (args(0).is_string())
+      else if (args(0).is_string ())
         additional_arg = false;
       else
         {
@@ -246,7 +261,7 @@
                       octave_rand::seed (d);
                   }
                 else if (args(idx+1).is_string ()
-                         && args(idx+1).string_value() == "reset")
+                         && args(idx+1).string_value () == "reset")
                   octave_rand::reset ();
                 else
                   error ("%s: seed must be a real scalar", fcn);
@@ -254,7 +269,7 @@
             else if (ts == "state" || ts == "twister")
               {
                 if (args(idx+1).is_string ()
-                    && args(idx+1).string_value() == "reset")
+                    && args(idx+1).string_value () == "reset")
                   octave_rand::reset (fcn);
                 else
                   {
@@ -298,40 +313,69 @@
 
   dims.chop_trailing_singletons ();
 
-  if (additional_arg)
+  if (is_single)
     {
-      if (a.length() == 1)
-        return octave_rand::nd_array (dims, a(0));
-      else
+      if (additional_arg)
         {
-          if (a.dims() != dims)
+          if (a.length () == 1)
+            return octave_rand::float_nd_array (dims, a(0));
+          else
             {
-              error ("%s: mismatch in argument size", fcn);
-              return retval;
+              if (a.dims () != dims)
+                {
+                  error ("%s: mismatch in argument size", fcn);
+                  return retval;
+                }
+              octave_idx_type len = a.length ();
+              FloatNDArray m (dims);
+              float *v = m.fortran_vec ();
+              for (octave_idx_type i = 0; i < len; i++)
+                v[i] = octave_rand::float_scalar (a(i));
+              return m;
             }
-          octave_idx_type len = a.length ();
-          NDArray m (dims);
-          double *v = m.fortran_vec ();
-          for (octave_idx_type i = 0; i < len; i++)
-            v[i] = octave_rand::scalar (a(i));
-          return m;
         }
+      else
+        return octave_rand::float_nd_array (dims);
     }
   else
-    return octave_rand::nd_array (dims);
+    {
+      if (additional_arg)
+        {
+          if (a.length () == 1)
+            return octave_rand::nd_array (dims, a(0));
+          else
+            {
+              if (a.dims () != dims)
+                {
+                  error ("%s: mismatch in argument size", fcn);
+                  return retval;
+                }
+              octave_idx_type len = a.length ();
+              NDArray m (dims);
+              double *v = m.fortran_vec ();
+              for (octave_idx_type i = 0; i < len; i++)
+                v[i] = octave_rand::scalar (a(i));
+              return m;
+            }
+        }
+      else
+        return octave_rand::nd_array (dims);
+    }
 }
 
-DEFUN_DLD (rand, args, ,
+DEFUN (rand, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} rand (@var{n})\n\
-@deftypefnx {Loadable Function} {} rand (@var{n}, @var{m}, @dots{})\n\
-@deftypefnx {Loadable Function} {} rand ([@var{n} @var{m} @dots{}])\n\
-@deftypefnx {Loadable Function} {@var{v} =} rand (\"state\")\n\
-@deftypefnx {Loadable Function} {} rand (\"state\", @var{v})\n\
-@deftypefnx {Loadable Function} {} rand (\"state\", \"reset\")\n\
-@deftypefnx {Loadable Function} {@var{v} =} rand (\"seed\")\n\
-@deftypefnx {Loadable Function} {} rand (\"seed\", @var{v})\n\
-@deftypefnx {Loadable Function} {} rand (\"seed\", \"reset\")\n\
+@deftypefn  {Built-in Function} {} rand (@var{n})\n\
+@deftypefnx {Built-in Function} {} rand (@var{n}, @var{m}, @dots{})\n\
+@deftypefnx {Built-in Function} {} rand ([@var{n} @var{m} @dots{}])\n\
+@deftypefnx {Built-in Function} {@var{v} =} rand (\"state\")\n\
+@deftypefnx {Built-in Function} {} rand (\"state\", @var{v})\n\
+@deftypefnx {Built-in Function} {} rand (\"state\", \"reset\")\n\
+@deftypefnx {Built-in Function} {@var{v} =} rand (\"seed\")\n\
+@deftypefnx {Built-in Function} {} rand (\"seed\", @var{v})\n\
+@deftypefnx {Built-in Function} {} rand (\"seed\", \"reset\")\n\
+@deftypefnx {Built-in Function} {} rand (@dots{}, \"single\")\n\
+@deftypefnx {Built-in Function} {} rand (@dots{}, \"double\")\n\
 Return a matrix with random elements uniformly distributed on the\n\
 interval (0, 1).  The arguments are handled the same as the arguments\n\
 for @code{eye}.\n\
@@ -358,7 +402,10 @@
 \n\
 By default, the generator is initialized from @code{/dev/urandom} if it is\n\
 available, otherwise from CPU time, wall clock time, and the current\n\
-fraction of a second.\n\
+fraction of a second.  Note that this differs from @sc{matlab}, which\n\
+always initializes the state to the same state at startup.  To obtain\n\
+behavior comparable to @sc{matlab}, initialize with a deterministic state\n\
+vector in Octave's startup files (@pxref{Startup Files}).\n\
 \n\
 To compute the pseudo-random sequence, @code{rand} uses the Mersenne\n\
 Twister with a period of @math{2^{19937}-1} (See M. Matsumoto and\n\
@@ -399,6 +446,9 @@
 \n\
 The state or seed of the generator can be reset to a new random value\n\
 using the \"reset\" keyword.\n\
+\n\
+The class of the value returned can be controlled by a trailing \"double\"\n\
+or \"single\" argument.  These are the only valid classes.\n\
 @seealso{randn, rande, randg, randp}\n\
 @end deftypefn")
 {
@@ -415,88 +465,89 @@
 // work properly if compiled to use 64-bit integers.
 
 /*
-%!test # 'state' can be a scalar
-%! rand('state',12); x = rand(1,4);
-%! rand('state',12); y = rand(1,4);
-%! assert(x,y);
-%!test # 'state' can be a vector
-%! rand('state',[12,13]); x=rand(1,4);
-%! rand('state',[12;13]); y=rand(1,4);
-%! assert(x,y);
-%!test # querying 'state' doesn't disturb sequence
-%! rand('state',12); rand(1,2); x=rand(1,2);
-%! rand('state',12); rand(1,2);
-%! s=rand('state'); y=rand(1,2);
-%! assert(x,y);
-%! rand('state',s); z=rand(1,2);
-%! assert(x,z);
-%!test # 'seed' must be a scalar
-%! rand('seed',12); x = rand(1,4);
-%! rand('seed',12); y = rand(1,4);
-%! assert(x,y);
-%!error(rand('seed',[12,13]))
-%!test # querying 'seed' returns a value which can be used later
-%! s=rand('seed'); x=rand(1,2);
-%! rand('seed',s); y=rand(1,2);
-%! assert(x,y);
-%!test # querying 'seed' doesn't disturb sequence
-%! rand('seed',12); rand(1,2); x=rand(1,2);
-%! rand('seed',12); rand(1,2);
-%! s=rand('seed'); y=rand(1,2);
-%! assert(x,y);
-%! rand('seed',s); z=rand(1,2);
-%! assert(x,z);
+%!test  # "state" can be a scalar
+%! rand ("state", 12);  x = rand (1,4);
+%! rand ("state", 12);  y = rand (1,4);
+%! assert (x, y);
+%!test  # "state" can be a vector
+%! rand ("state", [12,13]);  x = rand (1,4);
+%! rand ("state", [12;13]);  y = rand (1,4);
+%! assert (x, y);
+%!test  # querying "state" doesn't disturb sequence
+%! rand ("state", 12);  rand (1,2);  x = rand (1,2);
+%! rand ("state", 12);  rand (1,2);
+%! s = rand ("state");  y = rand (1,2);
+%! assert (x, y);
+%! rand ("state", s);  z = rand (1,2);
+%! assert (x, z);
+%!test  # "seed" must be a scalar
+%! rand ("seed", 12);  x = rand (1,4);
+%! rand ("seed", 12);  y = rand (1,4);
+%! assert (x, y);
+%!error <seed must be a real scalar> rand ("seed", [12,13])
+%!test  # querying "seed" returns a value which can be used later
+%! s = rand ("seed");  x = rand (1,2);
+%! rand ("seed", s);  y = rand (1,2);
+%! assert (x, y);
+%!test  # querying "seed" doesn't disturb sequence
+%! rand ("seed", 12);  rand (1,2);  x = rand (1,2);
+%! rand ("seed", 12);  rand (1,2);
+%! s = rand ("seed");  y = rand (1,2);
+%! assert (x, y);
+%! rand ("seed", s);  z = rand (1,2);
+%! assert (x, z);
 */
 
 /*
 %!test
-%! % Test fixed state
-%! rand("state",1);
-%! assert (rand(1,6), [0.1343642441124013 0.8474337369372327 0.763774618976614 0.2550690257394218 0.495435087091941 0.4494910647887382],1e-6);
+%! # Test fixed state
+%! rand ("state", 1);
+%! assert (rand (1,6), [0.1343642441124013 0.8474337369372327 0.763774618976614 0.2550690257394218 0.495435087091941 0.4494910647887382], 1e-6);
 %!test
-%! % Test fixed seed
-%! rand("seed",1);
-%! assert (rand(1,6), [0.8668024251237512 0.9126510815694928 0.09366085007786751 0.1664607301354408 0.7408077004365623 0.7615650338120759],1e-6);
+%! # Test fixed seed
+%! rand ("seed", 1);
+%! assert (rand (1,6), [0.8668024251237512 0.9126510815694928 0.09366085007786751 0.1664607301354408 0.7408077004365623 0.7615650338120759], 1e-6);
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   rand("state",12);
-%!   x = rand(100000,1);
-%!   assert(max(x)<1.); %*** Please report this!!! ***
-%!   assert(min(x)>0.); %*** Please report this!!! ***
-%!   assert(mean(x),0.5,0.0024);
-%!   assert(var(x),1/48,0.0632);
-%!   assert(skewness(x),0,0.012);
-%!   assert(kurtosis(x),-6/5,0.0094);
+%!   # statistical tests may fail occasionally.
+%!   rand ("state", 12);
+%!   x = rand (100000, 1);
+%!   assert (max (x) < 1);   #*** Please report this!!! ***
+%!   assert (min (x) > 0);   #*** Please report this!!! ***
+%!   assert (mean (x), 0.5, 0.0024);
+%!   assert (var (x), 1/48, 0.0632);
+%!   assert (skewness (x), 0, 0.012);
+%!   assert (kurtosis (x), -6/5, 0.0094);
 %! endif
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   rand("seed",12);
-%!   x = rand(100000,1);
-%!   assert(max(x)<1.); %*** Please report this!!! ***
-%!   assert(min(x)>0.); %*** Please report this!!! ***
-%!   assert(mean(x),0.5,0.0024);
-%!   assert(var(x),1/48,0.0632);
-%!   assert(skewness(x),0,0.012);
-%!   assert(kurtosis(x),-6/5,0.0094);
+%!   # statistical tests may fail occasionally.
+%!   rand ("seed", 12);
+%!   x = rand (100000, 1);
+%!   assert (max (x) < 1);   #*** Please report this!!! ***
+%!   assert (min (x) > 0);   #*** Please report this!!! ***
+%!   assert (mean (x), 0.5, 0.0024);
+%!   assert (var (x), 1/48, 0.0632);
+%!   assert (skewness (x), 0, 0.012);
+%!   assert (kurtosis (x), -6/5, 0.0094);
 %! endif
 */
 
-
 static std::string current_distribution = octave_rand::distribution ();
 
-DEFUN_DLD (randn, args, ,
+DEFUN (randn, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} randn (@var{n})\n\
-@deftypefnx {Loadable Function} {} randn (@var{n}, @var{m}, @dots{})\n\
-@deftypefnx {Loadable Function} {} randn ([@var{n} @var{m} @dots{}])\n\
-@deftypefnx {Loadable Function} {@var{v} =} randn (\"state\")\n\
-@deftypefnx {Loadable Function} {} randn (\"state\", @var{v})\n\
-@deftypefnx {Loadable Function} {} randn (\"state\", \"reset\")\n\
-@deftypefnx {Loadable Function} {@var{v} =} randn (\"seed\")\n\
-@deftypefnx {Loadable Function} {} randn (\"seed\", @var{v})\n\
-@deftypefnx {Loadable Function} {} randn (\"seed\", \"reset\")\n\
+@deftypefn  {Built-in Function} {} randn (@var{n})\n\
+@deftypefnx {Built-in Function} {} randn (@var{n}, @var{m}, @dots{})\n\
+@deftypefnx {Built-in Function} {} randn ([@var{n} @var{m} @dots{}])\n\
+@deftypefnx {Built-in Function} {@var{v} =} randn (\"state\")\n\
+@deftypefnx {Built-in Function} {} randn (\"state\", @var{v})\n\
+@deftypefnx {Built-in Function} {} randn (\"state\", \"reset\")\n\
+@deftypefnx {Built-in Function} {@var{v} =} randn (\"seed\")\n\
+@deftypefnx {Built-in Function} {} randn (\"seed\", @var{v})\n\
+@deftypefnx {Built-in Function} {} randn (\"seed\", \"reset\")\n\
+@deftypefnx {Built-in Function} {} randn (@dots{}, \"single\")\n\
+@deftypefnx {Built-in Function} {} randn (@dots{}, \"double\")\n\
 Return a matrix with normally distributed random\n\
 elements having zero mean and variance one.  The arguments are\n\
 handled the same as the arguments for @code{rand}.\n\
@@ -504,6 +555,9 @@
 By default, @code{randn} uses the Marsaglia and Tsang ``Ziggurat technique''\n\
 to transform from a uniform to a normal distribution.\n\
 \n\
+The class of the value returned can be controlled by a trailing \"double\"\n\
+or \"single\" argument.  These are the only valid classes.\n\
+\n\
 Reference: G. Marsaglia and W.W. Tsang,\n\
 @cite{Ziggurat Method for Generating Random Variables},\n\
 J. Statistical Software, vol 5, 2000,\n\
@@ -523,52 +577,57 @@
 
 /*
 %!test
-%! % Test fixed state
-%! randn("state",1);
-%! assert (randn(1,6), [-2.666521678978671 -0.7381719971724564 1.507903992673601 0.6019427189162239 -0.450661261143348 -0.7054431351574116],1e-6);
+%! # Test fixed state
+%! randn ("state", 1);
+%! assert (randn (1, 6), [-2.666521678978671 -0.7381719971724564 1.507903992673601 0.6019427189162239 -0.450661261143348 -0.7054431351574116], 1e-6);
 %!test
-%! % Test fixed seed
-%! randn("seed",1);
-%! assert (randn(1,6), [-1.039402365684509 -1.25938892364502 0.1968704611063004 0.3874166905879974 -0.5976632833480835 -0.6615074276924133],1e-6);
+%! # Test fixed seed
+%! randn ("seed", 1);
+%! assert (randn (1, 6), [-1.039402365684509 -1.25938892364502 0.1968704611063004 0.3874166905879974 -0.5976632833480835 -0.6615074276924133], 1e-6);
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randn("state",12);
-%!   x = randn(100000,1);
-%!   assert(mean(x),0,0.01);
-%!   assert(var(x),1,0.02);
-%!   assert(skewness(x),0,0.02);
-%!   assert(kurtosis(x),0,0.04);
+%!   # statistical tests may fail occasionally.
+%!   randn ("state", 12);
+%!   x = randn (100000, 1);
+%!   assert (mean (x), 0, 0.01);
+%!   assert (var (x), 1, 0.02);
+%!   assert (skewness (x), 0, 0.02);
+%!   assert (kurtosis (x), 0, 0.04);
 %! endif
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randn("seed",12);
-%!   x = randn(100000,1);
-%!   assert(mean(x),0,0.01);
-%!   assert(var(x),1,0.02);
-%!   assert(skewness(x),0,0.02);
-%!   assert(kurtosis(x),0,0.04);
+%!   # statistical tests may fail occasionally.
+%!   randn ("seed", 12);
+%!   x = randn (100000, 1);
+%!   assert (mean (x), 0, 0.01);
+%!   assert (var (x), 1, 0.02);
+%!   assert (skewness (x), 0, 0.02);
+%!   assert (kurtosis (x), 0, 0.04);
 %! endif
 */
 
-DEFUN_DLD (rande, args, ,
+DEFUN (rande, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} rande (@var{n})\n\
-@deftypefnx {Loadable Function} {} rande (@var{n}, @var{m}, @dots{})\n\
-@deftypefnx {Loadable Function} {} rande ([@var{n} @var{m} @dots{}])\n\
-@deftypefnx {Loadable Function} {@var{v} =} rande (\"state\")\n\
-@deftypefnx {Loadable Function} {} rande (\"state\", @var{v})\n\
-@deftypefnx {Loadable Function} {} rande (\"state\", \"reset\")\n\
-@deftypefnx {Loadable Function} {@var{v} =} rande (\"seed\")\n\
-@deftypefnx {Loadable Function} {} rande (\"seed\", @var{v})\n\
-@deftypefnx {Loadable Function} {} rande (\"seed\", \"reset\")\n\
+@deftypefn  {Built-in Function} {} rande (@var{n})\n\
+@deftypefnx {Built-in Function} {} rande (@var{n}, @var{m}, @dots{})\n\
+@deftypefnx {Built-in Function} {} rande ([@var{n} @var{m} @dots{}])\n\
+@deftypefnx {Built-in Function} {@var{v} =} rande (\"state\")\n\
+@deftypefnx {Built-in Function} {} rande (\"state\", @var{v})\n\
+@deftypefnx {Built-in Function} {} rande (\"state\", \"reset\")\n\
+@deftypefnx {Built-in Function} {@var{v} =} rande (\"seed\")\n\
+@deftypefnx {Built-in Function} {} rande (\"seed\", @var{v})\n\
+@deftypefnx {Built-in Function} {} rande (\"seed\", \"reset\")\n\
+@deftypefnx {Built-in Function} {} rande (@dots{}, \"single\")\n\
+@deftypefnx {Built-in Function} {} rande (@dots{}, \"double\")\n\
 Return a matrix with exponentially distributed random elements.  The\n\
 arguments are handled the same as the arguments for @code{rand}.\n\
 \n\
 By default, @code{randn} uses the Marsaglia and Tsang ``Ziggurat technique''\n\
 to transform from a uniform to an exponential distribution.\n\
 \n\
+The class of the value returned can be controlled by a trailing \"double\"\n\
+or \"single\" argument.  These are the only valid classes.\n\
+\n\
 Reference: G. Marsaglia and W.W. Tsang,\n\
 @cite{Ziggurat Method for Generating Random Variables},\n\
 J. Statistical Software, vol 5, 2000,\n\
@@ -588,49 +647,51 @@
 
 /*
 %!test
-%! % Test fixed state
-%! rande("state",1);
-%! assert (rande(1,6), [3.602973885835625 0.1386190677555021 0.6743112889616958 0.4512830847258422 0.7255744741233175 0.3415969205292291],1e-6);
+%! # Test fixed state
+%! rande ("state", 1);
+%! assert (rande (1, 6), [3.602973885835625 0.1386190677555021 0.6743112889616958 0.4512830847258422 0.7255744741233175 0.3415969205292291], 1e-6);
 %!test
-%! % Test fixed seed
-%! rande("seed",1);
-%! assert (rande(1,6), [0.06492075175653866 1.717980206012726 0.4816154008731246 0.5231300676241517 0.103910739364359 1.668931916356087],1e-6);
+%! # Test fixed seed
+%! rande ("seed", 1);
+%! assert (rande (1, 6), [0.06492075175653866 1.717980206012726 0.4816154008731246 0.5231300676241517 0.103910739364359 1.668931916356087], 1e-6);
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally
-%!   rande("state",1);
-%!   x = rande(100000,1);
-%!   assert(min(x)>0); % *** Please report this!!! ***
-%!   assert(mean(x),1,0.01);
-%!   assert(var(x),1,0.03);
-%!   assert(skewness(x),2,0.06);
-%!   assert(kurtosis(x),6,0.7);
+%!   # statistical tests may fail occasionally
+%!   rande ("state", 1);
+%!   x = rande (100000, 1);
+%!   assert (min (x) > 0);   # *** Please report this!!! ***
+%!   assert (mean (x), 1, 0.01);
+%!   assert (var (x), 1, 0.03);
+%!   assert (skewness (x), 2, 0.06);
+%!   assert (kurtosis (x), 6, 0.7);
 %! endif
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally
-%!   rande("seed",1);
-%!   x = rande(100000,1);
-%!   assert(min(x)>0); % *** Please report this!!! ***
-%!   assert(mean(x),1,0.01);
-%!   assert(var(x),1,0.03);
-%!   assert(skewness(x),2,0.06);
-%!   assert(kurtosis(x),6,0.7);
+%!   # statistical tests may fail occasionally
+%!   rande ("seed", 1);
+%!   x = rande (100000, 1);
+%!   assert (min (x)>0);   # *** Please report this!!! ***
+%!   assert (mean (x), 1, 0.01);
+%!   assert (var (x), 1, 0.03);
+%!   assert (skewness (x), 2, 0.06);
+%!   assert (kurtosis (x), 6, 0.7);
 %! endif
 */
 
-DEFUN_DLD (randg, args, ,
+DEFUN (randg, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} randg (@var{n})\n\
-@deftypefnx {Loadable Function} {} randg (@var{n}, @var{m}, @dots{})\n\
-@deftypefnx {Loadable Function} {} randg ([@var{n} @var{m} @dots{}])\n\
-@deftypefnx {Loadable Function} {@var{v} =} randg (\"state\")\n\
-@deftypefnx {Loadable Function} {} randg (\"state\", @var{v})\n\
-@deftypefnx {Loadable Function} {} randg (\"state\", \"reset\")\n\
-@deftypefnx {Loadable Function} {@var{v} =} randg (\"seed\")\n\
-@deftypefnx {Loadable Function} {} randg (\"seed\", @var{v})\n\
-@deftypefnx {Loadable Function} {} randg (\"seed\", \"reset\")\n\
-Return a matrix with @code{gamma(@var{a},1)} distributed random elements.\n\
+@deftypefn  {Built-in Function} {} randg (@var{n})\n\
+@deftypefnx {Built-in Function} {} randg (@var{n}, @var{m}, @dots{})\n\
+@deftypefnx {Built-in Function} {} randg ([@var{n} @var{m} @dots{}])\n\
+@deftypefnx {Built-in Function} {@var{v} =} randg (\"state\")\n\
+@deftypefnx {Built-in Function} {} randg (\"state\", @var{v})\n\
+@deftypefnx {Built-in Function} {} randg (\"state\", \"reset\")\n\
+@deftypefnx {Built-in Function} {@var{v} =} randg (\"seed\")\n\
+@deftypefnx {Built-in Function} {} randg (\"seed\", @var{v})\n\
+@deftypefnx {Built-in Function} {} randg (\"seed\", \"reset\")\n\
+@deftypefnx {Built-in Function} {} randg (@dots{}, \"single\")\n\
+@deftypefnx {Built-in Function} {} randg (@dots{}, \"double\")\n\
+Return a matrix with @code{gamma (@var{a},1)} distributed random elements.\n\
 The arguments are handled the same as the arguments for @code{rand},\n\
 except for the argument @var{a}.\n\
 \n\
@@ -709,6 +770,9 @@
 @end example\n\
 \n\
 @end table\n\
+\n\
+The class of the value returned can be controlled by a trailing \"double\"\n\
+or \"single\" argument.  These are the only valid classes.\n\
 @seealso{rand, randn, rande, randp}\n\
 @end deftypefn")
 {
@@ -726,167 +790,178 @@
 
 /*
 %!test
-%! randg("state",12)
-%!assert(randg([-inf,-1,0,inf,nan]),[nan,nan,nan,nan,nan]) % *** Please report
-
+%! randg ("state", 12)
+%! assert (randg ([-inf, -1, 0, inf, nan]), [nan, nan, nan, nan, nan]); # *** Please report
 
 %!test
-%! % Test fixed state
-%! randg("state",1);
-%! assert (randg(0.1,1,6), [0.0103951513331241 8.335671459898252e-05 0.00138691397249762 0.000587308416993855 0.495590518784736 2.3921917414795e-12],1e-6);
+%! # Test fixed state
+%! randg ("state", 1);
+%! assert (randg (0.1, 1, 6), [0.0103951513331241 8.335671459898252e-05 0.00138691397249762 0.000587308416993855 0.495590518784736 2.3921917414795e-12], 1e-6);
 %!test
-%! % Test fixed state
-%! randg("state",1);
-%! assert (randg(0.95,1,6), [3.099382433255327 0.3974529788871218 0.644367450750855 1.143261091802246 1.964111762696822 0.04011915547957939],1e-6);
+%! # Test fixed state
+%! randg ("state", 1);
+%! assert (randg (0.95, 1, 6), [3.099382433255327 0.3974529788871218 0.644367450750855 1.143261091802246 1.964111762696822 0.04011915547957939], 1e-6);
 %!test
-%! % Test fixed state
-%! randg("state",1);
-%! assert (randg(1,1,6), [0.2273389379645993 1.288822625058359 0.2406335209340746 1.218869553370733 1.024649860162554 0.09631230343599533],1e-6);
+%! # Test fixed state
+%! randg ("state", 1);
+%! assert (randg (1, 1, 6), [0.2273389379645993 1.288822625058359 0.2406335209340746 1.218869553370733 1.024649860162554 0.09631230343599533], 1e-6);
 %!test
-%! % Test fixed state
-%! randg("state",1);
-%! assert (randg(10,1,6), [3.520369644331133 15.15369864472106 8.332112081991205 8.406211067432674 11.81193475187611 10.88792728177059],1e-5);
+%! # Test fixed state
+%! randg ("state", 1);
+%! assert (randg (10, 1, 6), [3.520369644331133 15.15369864472106 8.332112081991205 8.406211067432674 11.81193475187611 10.88792728177059], 1e-5);
 %!test
-%! % Test fixed state
-%! randg("state",1);
-%! assert (randg(100,1,6), [75.34570255262264 115.4911985594699 95.23493031356388 95.48926019250911 106.2397448229803 103.4813150404118],1e-4);
+%! # Test fixed state
+%! randg ("state", 1);
+%! assert (randg (100, 1, 6), [75.34570255262264 115.4911985594699 95.23493031356388 95.48926019250911 106.2397448229803 103.4813150404118], 1e-4);
 %!test
-%! % Test fixed seed
-%! randg("seed",1);
-%! assert (randg(0.1,1,6), [0.07144210487604141 0.460641473531723 0.4749028384685516 0.06823389977216721 0.000293838675133884 1.802567535340305e-12],1e-6);
+%! # Test fixed seed
+%! randg ("seed", 1);
+%! assert (randg (0.1, 1, 6), [0.07144210487604141 0.460641473531723 0.4749028384685516 0.06823389977216721 0.000293838675133884 1.802567535340305e-12], 1e-6);
 %!test
-%! % Test fixed seed
-%! randg("seed",1);
-%! assert (randg(0.95,1,6), [1.664905071258545 1.879976987838745 1.905677795410156 0.9948706030845642 0.5606933236122131 0.0766092911362648],1e-6);
+%! # Test fixed seed
+%! randg ("seed", 1);
+%! assert (randg (0.95, 1, 6), [1.664905071258545 1.879976987838745 1.905677795410156 0.9948706030845642 0.5606933236122131 0.0766092911362648], 1e-6);
 %!test
-%! % Test fixed seed
-%! randg("seed",1);
-%! assert (randg(1,1,6), [0.03512085229158401 0.6488978862762451 0.8114678859710693 0.1666885763406754 1.60791552066803 1.90356981754303],1e-6);
+%! # Test fixed seed
+%! randg ("seed", 1);
+%! assert (randg (1, 1, 6), [0.03512085229158401 0.6488978862762451 0.8114678859710693 0.1666885763406754 1.60791552066803 1.90356981754303], 1e-6);
 %!test
-%! % Test fixed seed
-%! randg("seed",1);
-%! assert (randg(10,1,6), [6.566435813903809 10.11648464202881 10.73162078857422 7.747178077697754 6.278522491455078 6.240195751190186],1e-5);
+%! # Test fixed seed
+%! randg ("seed", 1);
+%! assert (randg (10, 1, 6), [6.566435813903809 10.11648464202881 10.73162078857422 7.747178077697754 6.278522491455078 6.240195751190186], 1e-5);
 %!test
-%! % Test fixed seed
-%! randg("seed",1);
-%! assert (randg(100,1,6), [89.40208435058594 101.4734725952148 103.4020004272461 93.62763214111328 88.33104705810547 88.1871337890625],1e-4);
+%! # Test fixed seed
+%! randg ("seed", 1);
+%! assert (randg (100, 1, 6), [89.40208435058594 101.4734725952148 103.4020004272461 93.62763214111328 88.33104705810547 88.1871337890625], 1e-4);
+
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randg("state",12)
-%!   a=0.1; x = randg(a,100000,1);
-%!   assert(mean(x),    a,         0.01);
-%!   assert(var(x),     a,         0.01);
-%!   assert(skewness(x),2/sqrt(a), 1.);
-%!   assert(kurtosis(x),6/a,       50.);
+%!   # statistical tests may fail occasionally.
+%!   randg ("state", 12);
+%!   a = 0.1;
+%!   x = randg (a, 100000, 1);
+%!   assert (mean (x),     a,          0.01);
+%!   assert (var (x),      a,          0.01);
+%!   assert (skewness (x), 2/sqrt (a), 1);
+%!   assert (kurtosis (x), 6/a,        50);
 %! endif
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randg("state",12)
-%!   a=0.95; x = randg(a,100000,1);
-%!   assert(mean(x),    a,         0.01);
-%!   assert(var(x),     a,         0.04);
-%!   assert(skewness(x),2/sqrt(a), 0.2);
-%!   assert(kurtosis(x),6/a,       2.);
+%!   # statistical tests may fail occasionally.
+%!   randg ("state", 12);
+%!   a = 0.95;
+%!   x = randg (a, 100000, 1);
+%!   assert (mean (x),     a,          0.01);
+%!   assert (var (x),      a,          0.04);
+%!   assert (skewness (x), 2/sqrt (a), 0.2);
+%!   assert (kurtosis (x), 6/a,        2);
 %! endif
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randg("state",12)
-%!   a=1; x = randg(a,100000,1);
-%!   assert(mean(x),a,             0.01);
-%!   assert(var(x),a,              0.04);
-%!   assert(skewness(x),2/sqrt(a), 0.2);
-%!   assert(kurtosis(x),6/a,       2.);
+%!   # statistical tests may fail occasionally.
+%!   randg ("state", 12);
+%!   a = 1;
+%!   x = randg (a, 100000, 1);
+%!   assert (mean (x),     a,          0.01);
+%!   assert (var (x),      a,          0.04);
+%!   assert (skewness (x), 2/sqrt (a), 0.2);
+%!   assert (kurtosis (x), 6/a,        2);
 %! endif
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randg("state",12)
-%!   a=10; x = randg(a,100000,1);
-%!   assert(mean(x),    a,         0.1);
-%!   assert(var(x),     a,         0.5);
-%!   assert(skewness(x),2/sqrt(a), 0.1);
-%!   assert(kurtosis(x),6/a,       0.5);
+%!   # statistical tests may fail occasionally.
+%!   randg ("state", 12);
+%!   a = 10;
+%!   x = randg (a, 100000, 1);
+%!   assert (mean (x),     a,          0.1);
+%!   assert (var (x),      a,          0.5);
+%!   assert (skewness (x), 2/sqrt (a), 0.1);
+%!   assert (kurtosis (x), 6/a,        0.5);
 %! endif
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randg("state",12)
-%!   a=100; x = randg(a,100000,1);
-%!   assert(mean(x),    a,         0.2);
-%!   assert(var(x),     a,         2.);
-%!   assert(skewness(x),2/sqrt(a), 0.05);
-%!   assert(kurtosis(x),6/a,       0.2);
+%!   # statistical tests may fail occasionally.
+%!   randg ("state", 12);
+%!   a = 100;
+%!   x = randg (a, 100000, 1);
+%!   assert (mean (x),     a,          0.2);
+%!   assert (var (x),      a,          2);
+%!   assert (skewness (x), 2/sqrt (a), 0.05);
+%!   assert (kurtosis (x), 6/a,        0.2);
 %! endif
 %!test
-%! randg("seed",12)
-%!assert(randg([-inf,-1,0,inf,nan]),[nan,nan,nan,nan,nan]) % *** Please report
+%! randg ("seed", 12);
+%!assert (randg ([-inf, -1, 0, inf, nan]), [nan, nan, nan, nan, nan]) # *** Please report
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randg("seed",12)
-%!   a=0.1; x = randg(a,100000,1);
-%!   assert(mean(x),    a,         0.01);
-%!   assert(var(x),     a,         0.01);
-%!   assert(skewness(x),2/sqrt(a), 1.);
-%!   assert(kurtosis(x),6/a,       50.);
+%!   # statistical tests may fail occasionally.
+%!   randg ("seed", 12);
+%!   a = 0.1;
+%!   x = randg (a, 100000, 1);
+%!   assert (mean (x),     a,          0.01);
+%!   assert (var (x),      a,          0.01);
+%!   assert (skewness (x), 2/sqrt (a), 1);
+%!   assert (kurtosis (x), 6/a,        50);
 %! endif
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randg("seed",12)
-%!   a=0.95; x = randg(a,100000,1);
-%!   assert(mean(x),    a,         0.01);
-%!   assert(var(x),     a,         0.04);
-%!   assert(skewness(x),2/sqrt(a), 0.2);
-%!   assert(kurtosis(x),6/a,       2.);
+%!   # statistical tests may fail occasionally.
+%!   randg ("seed", 12);
+%!   a = 0.95;
+%!   x = randg (a, 100000, 1);
+%!   assert (mean (x),     a,          0.01);
+%!   assert (var (x),      a,          0.04);
+%!   assert (skewness (x), 2/sqrt (a), 0.2);
+%!   assert (kurtosis (x), 6/a,        2);
 %! endif
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randg("seed",12)
-%!   a=1; x = randg(a,100000,1);
-%!   assert(mean(x),a,             0.01);
-%!   assert(var(x),a,              0.04);
-%!   assert(skewness(x),2/sqrt(a), 0.2);
-%!   assert(kurtosis(x),6/a,       2.);
+%!   # statistical tests may fail occasionally.
+%!   randg ("seed", 12);
+%!   a = 1;
+%!   x = randg (a, 100000, 1);
+%!   assert (mean (x),     a,          0.01);
+%!   assert (var (x),      a,          0.04);
+%!   assert (skewness (x), 2/sqrt (a), 0.2);
+%!   assert (kurtosis (x), 6/a,        2);
 %! endif
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randg("seed",12)
-%!   a=10; x = randg(a,100000,1);
-%!   assert(mean(x),    a,         0.1);
-%!   assert(var(x),     a,         0.5);
-%!   assert(skewness(x),2/sqrt(a), 0.1);
-%!   assert(kurtosis(x),6/a,       0.5);
+%!   # statistical tests may fail occasionally.
+%!   randg ("seed", 12);
+%!   a = 10;
+%!   x = randg (a, 100000, 1);
+%!   assert (mean (x),     a,          0.1);
+%!   assert (var (x),      a,          0.5);
+%!   assert (skewness (x), 2/sqrt (a), 0.1);
+%!   assert (kurtosis (x), 6/a,        0.5);
 %! endif
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randg("seed",12)
-%!   a=100; x = randg(a,100000,1);
-%!   assert(mean(x),    a,         0.2);
-%!   assert(var(x),     a,         2.);
-%!   assert(skewness(x),2/sqrt(a), 0.05);
-%!   assert(kurtosis(x),6/a,       0.2);
+%!   # statistical tests may fail occasionally.
+%!   randg ("seed", 12);
+%!   a = 100;
+%!   x = randg (a, 100000, 1);
+%!   assert (mean (x),     a,          0.2);
+%!   assert (var (x),      a,          2);
+%!   assert (skewness (x), 2/sqrt (a), 0.05);
+%!   assert (kurtosis (x), 6/a,        0.2);
 %! endif
 */
 
-
-DEFUN_DLD (randp, args, ,
+DEFUN (randp, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} randp (@var{l}, @var{n})\n\
-@deftypefnx {Loadable Function} {} randp (@var{l}, @var{n}, @var{m}, @dots{})\n\
-@deftypefnx {Loadable Function} {} randp (@var{l}, [@var{n} @var{m} @dots{}])\n\
-@deftypefnx {Loadable Function} {@var{v} =} randp (\"state\")\n\
-@deftypefnx {Loadable Function} {} randp (\"state\", @var{v})\n\
-@deftypefnx {Loadable Function} {} randp (\"state\", \"reset\")\n\
-@deftypefnx {Loadable Function} {@var{v} =} randp (\"seed\")\n\
-@deftypefnx {Loadable Function} {} randp (\"seed\", @var{v})\n\
-@deftypefnx {Loadable Function} {} randp (\"seed\", \"reset\")\n\
+@deftypefn  {Built-in Function} {} randp (@var{l}, @var{n})\n\
+@deftypefnx {Built-in Function} {} randp (@var{l}, @var{n}, @var{m}, @dots{})\n\
+@deftypefnx {Built-in Function} {} randp (@var{l}, [@var{n} @var{m} @dots{}])\n\
+@deftypefnx {Built-in Function} {@var{v} =} randp (\"state\")\n\
+@deftypefnx {Built-in Function} {} randp (\"state\", @var{v})\n\
+@deftypefnx {Built-in Function} {} randp (\"state\", \"reset\")\n\
+@deftypefnx {Built-in Function} {@var{v} =} randp (\"seed\")\n\
+@deftypefnx {Built-in Function} {} randp (\"seed\", @var{v})\n\
+@deftypefnx {Built-in Function} {} randp (\"seed\", \"reset\")\n\
+@deftypefnx {Built-in Function} {} randp (@dots{}, \"single\")\n\
+@deftypefnx {Built-in Function} {} randp (@dots{}, \"double\")\n\
 Return a matrix with Poisson distributed random elements with mean value\n\
 parameter given by the first argument, @var{l}.  The arguments\n\
 are handled the same as the arguments for @code{rand}, except for the\n\
@@ -917,6 +992,9 @@
 L. Montanet, et al., @cite{Review of Particle Properties}, Physical Review\n\
 D 50 p1284, 1994.\n\
 @end table\n\
+\n\
+The class of the value returned can be controlled by a trailing \"double\"\n\
+or \"single\" argument.  These are the only valid classes.\n\
 @seealso{rand, randn, rande, randg}\n\
 @end deftypefn")
 {
@@ -934,100 +1012,100 @@
 
 /*
 %!test
-%! randp("state",12)
-%!assert(randp([-inf,-1,0,inf,nan]),[nan,nan,0,nan,nan]); % *** Please report
+%! randp ("state", 12);
+%! assert (randp ([-inf, -1, 0, inf, nan]), [nan, nan, 0, nan, nan]);   # *** Please report
 %!test
-%! % Test fixed state
-%! randp("state",1);
-%! assert(randp(5,1,6),[5 5 3 7 7 3])
+%! # Test fixed state
+%! randp ("state", 1);
+%! assert (randp (5, 1, 6), [5 5 3 7 7 3])
 %!test
-%! % Test fixed state
-%! randp("state",1);
-%! assert(randp(15,1,6),[13 15 8 18 18 15])
+%! # Test fixed state
+%! randp ("state", 1);
+%! assert (randp (15, 1, 6), [13 15 8 18 18 15])
 %!test
-%! % Test fixed state
-%! randp("state",1);
-%! assert(randp(1e9,1,6),[999915677 999976657 1000047684 1000019035 999985749 999977692],-1e-6)
+%! # Test fixed state
+%! randp ("state", 1);
+%! assert (randp (1e9, 1, 6), [999915677 999976657 1000047684 1000019035 999985749 999977692], -1e-6)
 %!test
-%! % Test fixed state
-%! randp("seed",1);
-%! %%assert(randp(5,1,6),[8 2 3 6 6 8])
-%! assert(randp(5,1,5),[8 2 3 6 6])
+%! # Test fixed state
+%! randp ("seed", 1);
+%! %%assert (randp (5, 1, 6), [8 2 3 6 6 8])
+%! assert (randp (5, 1, 5), [8 2 3 6 6])
 %!test
-%! % Test fixed state
-%! randp("seed",1);
-%! assert(randp(15,1,6),[15 16 12 10 10 12])
+%! # Test fixed state
+%! randp ("seed", 1);
+%! assert (randp (15, 1, 6), [15 16 12 10 10 12])
 %!test
-%! % Test fixed state
-%! randp("seed",1);
-%! assert(randp(1e9,1,6),[1000006208 1000012224 999981120 999963520 999963072 999981440],-1e-6)
+%! # Test fixed state
+%! randp ("seed", 1);
+%! assert (randp (1e9, 1, 6), [1000006208 1000012224 999981120 999963520 999963072 999981440], -1e-6)
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randp("state",12)
-%!   for a=[5, 15, 1e9; 0.03, 0.03, -5e-3; 0.03, 0.03, 0.03]
-%!     x = randp(a(1),100000,1);
-%!     assert(min(x)>=0); % *** Please report this!!! ***
-%!     assert(mean(x),a(1),a(2));
-%!     assert(var(x),a(1),0.02*a(1));
-%!     assert(skewness(x),1/sqrt(a(1)),a(3));
-%!     assert(kurtosis(x),1/a(1),3*a(3));
+%!   # statistical tests may fail occasionally.
+%!   randp ("state", 12);
+%!   for a = [5, 15, 1e9; 0.03, 0.03, -5e-3; 0.03, 0.03, 0.03]
+%!     x = randp (a (1), 100000, 1);
+%!     assert (min (x) >= 0);   # *** Please report this!!! ***
+%!     assert (mean (x), a(1), a(2));
+%!     assert (var (x), a(1), 0.02*a(1));
+%!     assert (skewness (x), 1/sqrt (a(1)), a(3));
+%!     assert (kurtosis (x), 1/a(1), 3*a(3));
 %!   endfor
 %! endif
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randp("state",12)
-%!   for a=[5, 15, 1e9; 0.03, 0.03, -5e-3; 0.03, 0.03, 0.03]
-%!     x = randp(a(1)*ones(100000,1),100000,1);
-%!     assert(min(x)>=0); % *** Please report this!!! ***
-%!     assert(mean(x),a(1),a(2));
-%!     assert(var(x),a(1),0.02*a(1));
-%!     assert(skewness(x),1/sqrt(a(1)),a(3));
-%!     assert(kurtosis(x),1/a(1),3*a(3));
+%!   # statistical tests may fail occasionally.
+%!   randp ("state", 12);
+%!   for a = [5, 15, 1e9; 0.03, 0.03, -5e-3; 0.03, 0.03, 0.03]
+%!     x = randp (a(1)*ones (100000, 1), 100000, 1);
+%!     assert (min (x) >= 0);   # *** Please report this!!! ***
+%!     assert (mean (x), a(1), a(2));
+%!     assert (var (x), a(1), 0.02*a(1));
+%!     assert (skewness (x), 1/sqrt (a(1)), a(3));
+%!     assert (kurtosis (x), 1/a(1), 3*a(3));
 %!   endfor
 %! endif
 %!test
-%! randp("seed",12)
-%!assert(randp([-inf,-1,0,inf,nan]),[nan,nan,0,nan,nan]); % *** Please report
+%! randp ("seed", 12);
+%! assert (randp ([-inf, -1, 0, inf, nan]), [nan, nan, 0, nan, nan]);   # *** Please report
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randp("seed",12)
-%!   for a=[5, 15, 1e9; 0.03, 0.03, -5e-3; 0.03, 0.03, 0.03]
-%!     x = randp(a(1),100000,1);
-%!     assert(min(x)>=0); % *** Please report this!!! ***
-%!     assert(mean(x),a(1),a(2));
-%!     assert(var(x),a(1),0.02*a(1));
-%!     assert(skewness(x),1/sqrt(a(1)),a(3));
-%!     assert(kurtosis(x),1/a(1),3*a(3));
+%!   # statistical tests may fail occasionally.
+%!   randp ("seed", 12);
+%!   for a = [5, 15, 1e9; 0.03, 0.03, -5e-3; 0.03, 0.03, 0.03]
+%!     x = randp (a(1), 100000, 1);
+%!     assert (min (x) >= 0);   # *** Please report this!!! ***
+%!     assert (mean (x), a(1), a(2));
+%!     assert (var (x), a(1), 0.02*a(1));
+%!     assert (skewness (x), 1/sqrt (a(1)), a(3));
+%!     assert (kurtosis (x), 1/a(1), 3*a(3));
 %!   endfor
 %! endif
 %!test
 %! if (__random_statistical_tests__)
-%!   % statistical tests may fail occasionally.
-%!   randp("seed",12)
-%!   for a=[5, 15, 1e9; 0.03, 0.03, -5e-3; 0.03, 0.03, 0.03]
-%!     x = randp(a(1)*ones(100000,1),100000,1);
-%!     assert(min(x)>=0); % *** Please report this!!! ***
-%!     assert(mean(x),a(1),a(2));
-%!     assert(var(x),a(1),0.02*a(1));
-%!     assert(skewness(x),1/sqrt(a(1)),a(3));
-%!     assert(kurtosis(x),1/a(1),3*a(3));
+%!   # statistical tests may fail occasionally.
+%!   randp ("seed", 12);
+%!   for a = [5, 15, 1e9; 0.03, 0.03, -5e-3; 0.03, 0.03, 0.03]
+%!     x = randp (a(1)*ones (100000, 1), 100000, 1);
+%!     assert (min (x) >= 0);   # *** Please report this!!! ***
+%!     assert (mean (x), a(1), a(2));
+%!     assert (var (x), a(1), 0.02*a(1));
+%!     assert (skewness (x), 1/sqrt (a(1)), a(3));
+%!     assert (kurtosis (x), 1/a(1), 3*a(3));
 %!   endfor
 %! endif
 */
 
-DEFUN_DLD (randperm, args, ,
+DEFUN (randperm, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} randperm (@var{n})\n\
-@deftypefnx {Loadable Function} {} randperm (@var{n}, @var{m})\n\
+@deftypefn  {Built-in Function} {} randperm (@var{n})\n\
+@deftypefnx {Built-in Function} {} randperm (@var{n}, @var{m})\n\
 Return a row vector containing a random permutation of @code{1:@var{n}}.\n\
 If @var{m} is supplied, return @var{m} unique entries, sampled without\n\
 replacement from @code{1:@var{n}}.  The complexity is O(@var{n}) in\n\
 memory and O(@var{m}) in time, unless @var{m} < @var{n}/5, in which case\n\
 O(@var{m}) memory is used as well.  The randomization is performed using\n\
-rand(). All permutations are equally likely.\n\
+rand().  All permutations are equally likely.\n\
 @seealso{perms}\n\
 @end deftypefn")
 {
rename from src/DLD-FUNCTIONS/rcond.cc
rename to libinterp/corefcn/rcond.cc
--- a/src/DLD-FUNCTIONS/rcond.cc
+++ b/libinterp/corefcn/rcond.cc
@@ -24,15 +24,15 @@
 #include <config.h>
 #endif
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
 #include "utils.h"
 
-DEFUN_DLD (rcond, args, ,
+DEFUN (rcond, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{c} =} rcond (@var{A})\n\
+@deftypefn {Built-in Function} {@var{c} =} rcond (@var{A})\n\
 Compute the 1-norm estimate of the reciprocal condition number as returned\n\
 by @sc{lapack}.  If the matrix is well-conditioned then @var{c} will be near\n\
 1 and if the matrix is poorly conditioned it will be close to zero.\n\
@@ -87,11 +87,10 @@
 }
 
 /*
-
-%!assert( rcond (eye (2)), 1)
-%!assert( rcond (ones (2)), 0)
-%!assert( rcond ([1 1; 2 1]), 1/9)
-%!assert( rcond (magic (4)), 0, eps)
+%!assert (rcond (eye (2)), 1)
+%!assert (rcond (ones (2)), 0)
+%!assert (rcond ([1 1; 2 1]), 1/9)
+%!assert (rcond (magic (4)), 0, eps)
 
 %!shared x, sx
 %! x = [-5.25, -2.25; -2.25, 1] * eps () + ones (2) / 2;
rename from src/DLD-FUNCTIONS/regexp.cc
rename to libinterp/corefcn/regexp.cc
--- a/src/DLD-FUNCTIONS/regexp.cc
+++ b/libinterp/corefcn/regexp.cc
@@ -36,7 +36,7 @@
 #include "regexp.h"
 #include "str-vec.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "Cell.h"
 #include "error.h"
 #include "gripes.h"
@@ -44,6 +44,134 @@
 #include "oct-obj.h"
 #include "utils.h"
 
+// Replace backslash escapes in a string with the real values.  We need
+// two special functions instead of the one in utils.cc because the set
+// of escape sequences used for regexp patterns and replacement strings
+// is different from those used in the *printf functions.
+
+static std::string
+do_regexp_ptn_string_escapes (const std::string& s)
+{
+  std::string retval;
+
+  size_t i = 0;
+  size_t j = 0;
+  size_t len = s.length ();
+
+  retval.resize (len);
+
+  while (j < len)
+    {
+      if (s[j] == '\\' && j+1 < len)
+        {
+          switch (s[++j])
+            {
+            case 'b': // backspace
+              retval[i] = '\b';
+              break;
+
+#if 0
+// FIXME : To be complete, we need to handle \oN, \o{N}.
+//         The PCRE library already handles \N where N
+//         is an octal number.  New code needs to merely
+//         replace \oN or \o{N} with \N.
+            case 'o': // octal number
+#endif
+
+            default:  // pass escape sequence through
+              retval[i] = '\\';
+              retval[++i] = s[j];
+              break;
+            }
+        }
+      else
+        {
+          retval[i] = s[j];
+        }
+
+      i++;
+      j++;
+    }
+
+  retval.resize (i);
+
+  return retval;
+}
+
+static std::string
+do_regexp_rep_string_escapes (const std::string& s)
+{
+  std::string retval;
+
+  size_t i = 0;
+  size_t j = 0;
+  size_t len = s.length ();
+
+  retval.resize (len);
+
+  while (j < len)
+    {
+      if (s[j] == '\\' && j+1 < len)
+        {
+          switch (s[++j])
+            {
+            case 'a': // alarm
+              retval[i] = '\a';
+              break;
+
+            case 'b': // backspace
+              retval[i] = '\b';
+              break;
+
+            case 'f': // formfeed
+              retval[i] = '\f';
+              break;
+
+            case 'n': // newline
+              retval[i] = '\n';
+              break;
+
+            case 'r': // carriage return
+              retval[i] = '\r';
+              break;
+
+            case 't': // horizontal tab
+              retval[i] = '\t';
+              break;
+
+            case 'v': // vertical tab
+              retval[i] = '\v';
+              break;
+
+#if 0
+// FIXME -- to be complete, we need to handle \oN, \o{N}, \xN, and
+// \x{N}.  Hex digits may be upper or lower case.  Brackets are
+// optional, so \x5Bz is the same as \x{5B}z.
+
+            case 'o': // octal number
+            case 'x': // hex number
+#endif
+ 
+            default:  // pass escape sequence through
+              retval[i] = '\\';
+              retval[++i] = s[j];
+              break;
+            }
+        }
+      else
+        {
+          retval[i] = s[j];
+        }
+
+      i++;
+      j++;
+    }
+
+  retval.resize (i);
+
+  return retval;
+}
+
 static void
 parse_options (regexp::opts& options, const octave_value_list& args,
                const std::string& who, int skip, bool& extra_args)
@@ -77,12 +205,16 @@
         options.lineanchors (false);
       else if (str.find ("literalspacing", 0) == 0)
         options.freespacing (false);
+      else if (str.find ("noemptymatch", 0) == 0)
+        options.emptymatch (false);
       else if (str.find ("dotexceptnewline", 0) == 0)
         options.dotexceptnewline (true);
       else if (str.find ("lineanchors", 0) == 0)
         options.lineanchors (true);
       else if (str.find ("freespacing", 0) == 0)
         options.freespacing (true);
+      else if (str.find ("emptymatch", 0) == 0)
+        options.emptymatch (true);
       else if (str.find ("start", 0) == 0
                || str.find ("end", 0) == 0
                || str.find ("tokenextents", 0) == 0
@@ -109,9 +241,12 @@
   if (error_state)
     return retval;
 
-  const std::string pattern = args(1).string_value ();
+  std::string pattern = args(1).string_value ();
   if (error_state)
     return retval;
+  // Matlab compatibility.
+  if (args(1).is_sq_string ())
+    pattern = do_regexp_ptn_string_escapes (pattern);
 
   regexp::opts options;
   options.case_insensitive (case_insensitive);
@@ -137,7 +272,7 @@
 
       if (sz == 1)
         {
-          string_vector named_tokens = rx_lst.begin()->named_tokens ();
+          string_vector named_tokens = rx_lst.begin ()->named_tokens ();
 
           for (int j = 0; j < named_pats.length (); j++)
             nmap.assign (named_pats(j), named_tokens(j));
@@ -257,7 +392,9 @@
                   || str.find ("dotall", 0) == 0
                   || str.find ("dotexceptnewline", 0) == 0
                   || str.find ("literalspacing", 0) == 0
-                  || str.find ("freespacing", 0) == 0)
+                  || str.find ("freespacing", 0) == 0
+                  || str.find ("noemptymatch", 0) == 0
+                  || str.find ("emptymatch", 0) == 0)
                 continue;
               else if (str.find ("start", 0) == 0)
                 k = 0;
@@ -412,7 +549,7 @@
       Cell cellpat = args(1).cell_value ();
 
       for (int j = 0; j < nargout; j++)
-        newretval[j].resize(cellpat.dims ());
+        newretval[j].resize (cellpat.dims ());
 
       for (octave_idx_type i = 0; i < cellpat.numel (); i++)
         {
@@ -440,10 +577,10 @@
 
 }
 
-DEFUN_DLD (regexp, args, nargout,
+DEFUN (regexp, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {[@var{s}, @var{e}, @var{te}, @var{m}, @var{t}, @var{nm}] =} regexp (@var{str}, @var{pat})\n\
-@deftypefnx {Loadable Function} {[@dots{}] =} regexp (@var{str}, @var{pat}, \"@var{opt1}\", @dots{})\n\
+@deftypefn  {Built-in Function} {[@var{s}, @var{e}, @var{te}, @var{m}, @var{t}, @var{nm}, @var{sp}] =} regexp (@var{str}, @var{pat})\n\
+@deftypefnx {Built-in Function} {[@dots{}] =} regexp (@var{str}, @var{pat}, \"@var{opt1}\", @dots{})\n\
 Regular expression string matching.  Search for @var{pat} in @var{str} and\n\
 return the positions and substrings of any matches, or empty values if there\n\
 are none.\n\
@@ -457,6 +594,7 @@
 \n\
 @item * + ? @{@}\n\
 Repetition operators, representing\n\
+\n\
 @table @code\n\
 @item *\n\
 Match zero or more times\n\
@@ -487,8 +625,8 @@
 operators.  For example, a template for a floating point number might be\n\
 @code{[-+.\\d]+}.\n\
 \n\
-@item ()\n\
-Grouping operator\n\
+@item () (?:)\n\
+Grouping operator.  The first form, parentheses only, also creates a token.\n\
 \n\
 @item |\n\
 Alternation operator.  Match one of a choice of regular expressions.  The\n\
@@ -499,10 +637,7 @@
 end (@code{$}) of the string.\n\
 @end table\n\
 \n\
-In addition, the following escaped characters have special meaning.  Note,\n\
-it is recommended to quote @var{pat} in single quotes, rather than double\n\
-quotes, to avoid the escape sequences being interpreted by Octave before\n\
-being passed to @code{regexp}.\n\
+In addition, the following escaped characters have special meaning.\n\
 \n\
 @table @code\n\
 @item \\b\n\
@@ -536,6 +671,12 @@
 Match any non-digit\n\
 @end table\n\
 \n\
+Implementation Note: For compatibility with @sc{matlab}, ordinary escape\n\
+sequences (e.g., \"\\n\" => newline) are processed in @var{pat}\n\
+regardless of whether @var{pat} has been defined within single quotes.  Use\n\
+a second backslash to stop interpolation of the escape sequence (e.g.,\n\
+\"\\\\n\") or use the @code{regexptranslate} function.\n\
+\n\
 The outputs of @code{regexp} default to the order given below\n\
 \n\
 @table @var\n\
@@ -561,7 +702,8 @@
 @code{(?<name>@dots{})}.\n\
 \n\
 @item sp\n\
-A cell array of the text not returned by match.\n\
+A cell array of the text not returned by match, i.e., what remains if you\n\
+split the string based on @var{pat}.\n\
 @end table\n\
 \n\
 Particular output arguments, or the order of the output arguments, can be\n\
@@ -629,6 +771,15 @@
 \n\
 Alternatively, use (?x) in the pattern.\n\
 \n\
+@item noemptymatch\n\
+Zero-length matches are not returned.  (default)\n\
+\n\
+@item emptymatch\n\
+Return zero-length matches.\n\
+\n\
+@code{regexp ('a', 'b*', 'emptymatch'} returns @code{[1 2]} because there are\n\
+zero or more 'b' characters at positions 1 and end-of-string.\n\
+\n\
 @end table\n\
 @seealso{regexpi, strfind, regexprep}\n\
 @end deftypefn")
@@ -640,7 +791,7 @@
   if (nargin < 2)
     print_usage ();
   else if (args(0).is_cell () || args(1).is_cell ())
-    retval = octcellregexp (args, nargout, "regexp");
+    retval = octcellregexp (args, (nargout > 0 ? nargout : 1), "regexp");
   else
     retval = octregexp (args, nargout, "regexp");
 
@@ -648,130 +799,129 @@
 }
 
 /*
-
 ## PCRE_ERROR_MATCHLIMIT test
 %!test
-%! s=sprintf('\t4\n0000\t-0.00\t-0.0000\t4\t-0.00\t-0.0000\t4\n0000\t-0.00\t-0.0000\t0\t-0.00\t-');
-%! ws = warning("query");
+%! s = sprintf ('\t4\n0000\t-0.00\t-0.0000\t4\t-0.00\t-0.0000\t4\n0000\t-0.00\t-0.0000\t0\t-0.00\t-');
+%! ws = warning ("query");
 %! unwind_protect
-%!   warning("off");
-%!   regexp(s, '(\s*-*\d+[.]*\d*\s*)+\n');
+%!   warning ("off");
+%!   regexp (s, '(\s*-*\d+[.]*\d*\s*)+\n');
 %! unwind_protect_cleanup
-%!   warning(ws);
+%!   warning (ws);
 %! end_unwind_protect
 
-## seg-fault test
-%!assert(regexp("abcde","."),[1,2,3,4,5])
+## segfault test
+%!assert (regexp ("abcde", "."), [1,2,3,4,5])
 ## Infinite loop test
-%!assert (isempty (regexp("abcde", "")))
+%!assert (isempty (regexp ("abcde", "")))
 
 ## Check that anchoring of pattern works correctly
-%!assert(regexp('abcabc','^abc'),1);
-%!assert(regexp('abcabc','abc$'),4);
-%!assert(regexp('abcabc','^abc$'),zeros(1,0));
+%!assert (regexp ('abcabc', '^abc'), 1)
+%!assert (regexp ('abcabc', 'abc$'), 4)
+%!assert (regexp ('abcabc', '^abc$'), zeros (1,0))
 
 %!test
-%! [s, e, te, m, t] = regexp(' No Match ', 'f(.*)uck');
-%! assert (s,zeros(1,0))
-%! assert (e,zeros(1,0))
-%! assert (te,cell(1,0))
-%! assert (m, cell(1,0))
-%! assert (t, cell(1,0))
+%! [s, e, te, m, t] = regexp (' No Match ', 'f(.*)uck');
+%! assert (s, zeros (1,0));
+%! assert (e, zeros (1,0));
+%! assert (te, cell (1,0));
+%! assert (m, cell (1,0));
+%! assert (t, cell (1,0));
 
 %!test
-%! [s, e, te, m, t] = regexp(' FiRetrUck ', 'f(.*)uck');
-%! assert (s,zeros(1,0))
-%! assert (e,zeros(1,0))
-%! assert (te,cell(1,0))
-%! assert (m, cell(1,0))
-%! assert (t, cell(1,0))
+%! [s, e, te, m, t] = regexp (' FiRetrUck ', 'f(.*)uck');
+%! assert (s, zeros (1,0));
+%! assert (e, zeros (1,0));
+%! assert (te, cell (1,0));
+%! assert (m, cell (1,0));
+%! assert (t, cell (1,0));
 
 %!test
-%! [s, e, te, m, t] = regexp(' firetruck ', 'f(.*)uck');
-%! assert (s,2)
-%! assert (e,10)
-%! assert (te{1},[3,7])
-%! assert (m{1}, 'firetruck')
-%! assert (t{1}{1}, 'iretr')
+%! [s, e, te, m, t] = regexp (' firetruck ', 'f(.*)uck');
+%! assert (s, 2);
+%! assert (e, 10);
+%! assert (te{1}, [3, 7]);
+%! assert (m{1}, 'firetruck');
+%! assert (t{1}{1}, 'iretr');
 
 %!test
-%! [s, e, te, m, t] = regexp('short test string','\w*r\w*');
-%! assert (s,[1,12])
-%! assert (e,[5,17])
-%! assert (size(te), [1,2])
-%! assert (isempty(te{1}))
-%! assert (isempty(te{2}))
-%! assert (m{1},'short')
-%! assert (m{2},'string')
-%! assert (size(t), [1,2])
-%! assert (isempty(t{1}))
-%! assert (isempty(t{2}))
+%! [s, e, te, m, t] = regexp ('short test string', '\w*r\w*');
+%! assert (s, [1, 12]);
+%! assert (e, [5, 17]);
+%! assert (size (te), [1, 2]);
+%! assert (isempty (te{1}));
+%! assert (isempty (te{2}));
+%! assert (m{1}, 'short');
+%! assert (m{2}, 'string');
+%! assert (size (t), [1, 2]);
+%! assert (isempty (t{1}));
+%! assert (isempty (t{2}));
 
 %!test
-%! [s, e, te, m, t] = regexp('short test string','\w*r\w*','once');
-%! assert (s,1)
-%! assert (e,5)
-%! assert (isempty(te))
-%! assert (m,'short')
-%! assert (isempty(t))
+%! [s, e, te, m, t] = regexp ('short test string', '\w*r\w*', 'once');
+%! assert (s, 1);
+%! assert (e, 5);
+%! assert (isempty (te));
+%! assert (m, 'short');
+%! assert (isempty (t));
 
 %!test
-%! [m, te, e, s, t] = regexp('short test string','\w*r\w*','once', 'match', 'tokenExtents', 'end', 'start', 'tokens');
-%! assert (s,1)
-%! assert (e,5)
-%! assert (isempty(te))
-%! assert (m,'short')
-%! assert (isempty(t))
+%! [m, te, e, s, t] = regexp ('short test string', '\w*r\w*', 'once', 'match', 'tokenExtents', 'end', 'start', 'tokens');
+%! assert (s, 1);
+%! assert (e, 5);
+%! assert (isempty (te));
+%! assert (m, 'short');
+%! assert (isempty (t));
 
 %!test
-%! [s, e, te, m, t, nm] = regexp('short test string','(?<word1>\w*t)\s*(?<word2>\w*t)');
-%! assert (s,1)
-%! assert (e,10)
-%! assert (size(te), [1,1])
-%! assert (te{1}, [1 5; 7, 10])
-%! assert (m{1},'short test')
-%! assert (size(t),[1,1])
-%! assert (t{1}{1},'short')
-%! assert (t{1}{2},'test')
-%! assert (size(nm), [1,1])
-%! assert (!isempty(fieldnames(nm)))
-%! assert (sort(fieldnames(nm)),{'word1';'word2'})
-%! assert (nm.word1,'short')
-%! assert (nm.word2,'test')
+%! [s, e, te, m, t, nm] = regexp ('short test string', '(?<word1>\w*t)\s*(?<word2>\w*t)');
+%! assert (s, 1);
+%! assert (e, 10);
+%! assert (size (te), [1, 1]);
+%! assert (te{1}, [1,5; 7,10]);
+%! assert (m{1}, 'short test');
+%! assert (size (t), [1, 1]);
+%! assert (t{1}{1}, 'short');
+%! assert (t{1}{2}, 'test');
+%! assert (size (nm), [1, 1]);
+%! assert (! isempty (fieldnames (nm)));
+%! assert (sort (fieldnames (nm)), {'word1';'word2'});
+%! assert (nm.word1, 'short');
+%! assert (nm.word2, 'test');
 
 %!test
-%! [nm, m, te, e, s, t] = regexp('short test string','(?<word1>\w*t)\s*(?<word2>\w*t)', 'names', 'match', 'tokenExtents', 'end', 'start', 'tokens');
-%! assert (s,1)
-%! assert (e,10)
-%! assert (size(te), [1,1])
-%! assert (te{1}, [1 5; 7, 10])
-%! assert (m{1},'short test')
-%! assert (size(t),[1,1])
-%! assert (t{1}{1},'short')
-%! assert (t{1}{2},'test')
-%! assert (size(nm), [1,1])
-%! assert (!isempty(fieldnames(nm)))
-%! assert (sort(fieldnames(nm)),{'word1';'word2'})
-%! assert (nm.word1,'short')
-%! assert (nm.word2,'test')
+%! [nm, m, te, e, s, t] = regexp ('short test string', '(?<word1>\w*t)\s*(?<word2>\w*t)', 'names', 'match', 'tokenExtents', 'end', 'start', 'tokens');
+%! assert (s, 1);
+%! assert (e, 10);
+%! assert (size (te), [1, 1]);
+%! assert (te{1}, [1,5; 7,10]);
+%! assert (m{1}, 'short test');
+%! assert (size (t), [1, 1]);
+%! assert (t{1}{1}, 'short');
+%! assert (t{1}{2}, 'test');
+%! assert (size (nm), [1, 1]);
+%! assert (!isempty (fieldnames (nm)));
+%! assert (sort (fieldnames (nm)), {'word1';'word2'});
+%! assert (nm.word1, 'short');
+%! assert (nm.word2, 'test');
 
 %!test
-%! [t, nm] = regexp("John Davis\nRogers, James",'(?<first>\w+)\s+(?<last>\w+)|(?<last>\w+),\s+(?<first>\w+)','tokens','names');
-%! assert (size(t), [1,2]);
-%! assert (t{1}{1},'John');
-%! assert (t{1}{2},'Davis');
-%! assert (t{2}{1},'Rogers');
-%! assert (t{2}{2},'James');
-%! assert (size(nm), [1,1]);
-%! assert (nm.first{1},'John');
-%! assert (nm.first{2},'James');
-%! assert (nm.last{1},'Davis');
-%! assert (nm.last{2},'Rogers');
+%! [t, nm] = regexp ("John Davis\nRogers, James", '(?<first>\w+)\s+(?<last>\w+)|(?<last>\w+),\s+(?<first>\w+)', 'tokens', 'names');
+%! assert (size (t), [1, 2]);
+%! assert (t{1}{1}, 'John');
+%! assert (t{1}{2}, 'Davis');
+%! assert (t{2}{1}, 'Rogers');
+%! assert (t{2}{2}, 'James');
+%! assert (size (nm), [1, 1]);
+%! assert (nm.first{1}, 'John');
+%! assert (nm.first{2}, 'James');
+%! assert (nm.last{1}, 'Davis');
+%! assert (nm.last{2}, 'Rogers');
 
 ## Tests for named tokens
 %!test
 %! # Parenthesis in named token (ie (int)) causes a problem
-%! assert (regexp('qwe int asd', ['(?<typestr>(int))'], 'names'), struct ('typestr', 'int'));
+%! assert (regexp ('qwe int asd', ['(?<typestr>(int))'], 'names'), struct ('typestr', 'int'));
 
 %!test
 %! ## Mix of named and unnamed tokens can cause segfault (bug #35683)
@@ -782,51 +932,90 @@
 %! assert (tokens.T1, "a");
 %! assert (tokens.T2, "de");
 
-%!assert(regexp("abc\nabc",'.'),[1:7])
-%!assert(regexp("abc\nabc",'.','dotall'),[1:7])
+%!assert (regexp ("abc\nabc", '.'), [1:7])
+%!assert (regexp ("abc\nabc", '.', 'dotall'), [1:7])
 %!test
-%! assert(regexp("abc\nabc",'(?s).'),[1:7])
-%! assert(regexp("abc\nabc",'.','dotexceptnewline'),[1,2,3,5,6,7])
-%! assert(regexp("abc\nabc",'(?-s).'),[1,2,3,5,6,7])
+%! assert (regexp ("abc\nabc", '(?s).'), [1:7]);
+%! assert (regexp ("abc\nabc", '.', 'dotexceptnewline'), [1,2,3,5,6,7]);
+%! assert (regexp ("abc\nabc", '(?-s).'), [1,2,3,5,6,7]);
+
+%!assert (regexp ("caseCaSe", 'case'), 1)
+%!assert (regexp ("caseCaSe", 'case', "matchcase"), 1)
+%!assert (regexp ("caseCaSe", 'case', "ignorecase"), [1,5])
+%!test
+%! assert (regexp ("caseCaSe", '(?-i)case'), 1);
+%! assert (regexp ("caseCaSe", '(?i)case'), [1, 5]);
 
-%!assert(regexp("caseCaSe",'case'),1)
-%!assert(regexp("caseCaSe",'case',"matchcase"),1)
-%!assert(regexp("caseCaSe",'case',"ignorecase"),[1,5])
+%!assert (regexp ("abc\nabc", 'c$'), 7)
+%!assert (regexp ("abc\nabc", 'c$', "stringanchors"), 7)
 %!test
-%! assert(regexp("caseCaSe",'(?-i)case'),1)
-%! assert(regexp("caseCaSe",'(?i)case'),[1,5])
+%! assert (regexp ("abc\nabc", '(?-m)c$'), 7);
+%! assert (regexp ("abc\nabc", 'c$',"lineanchors"), [3, 7]);
+%! assert (regexp ("abc\nabc", '(?m)c$'), [3,7]);
 
-%!assert (regexp("abc\nabc",'c$'),7)
-%!assert (regexp("abc\nabc",'c$',"stringanchors"),7)
+%!assert (regexp ("this word", 's w'), 4)
+%!assert (regexp ("this word", 's w', 'literalspacing'), 4)
+%!test
+%! assert (regexp ("this word", '(?-x)s w', 'literalspacing'), 4);
+%! assert (regexp ("this word", 's w', 'freespacing'), zeros (1,0));
+%! assert (regexp ("this word", '(?x)s w'), zeros (1,0));
+
 %!test
-%! assert (regexp("abc\nabc",'(?-m)c$'),7)
-%! assert (regexp("abc\nabc",'c$',"lineanchors"),[3,7])
-%! assert (regexp("abc\nabc",'(?m)c$'),[3,7])
+%! [s, e, te, m, t, nm, sp] = regexp ('OCTAVE', '[VOCT]*', 'noemptymatch');
+%! assert (s, [1 5]);
+%! assert (e, [3 5]);
+%! assert (te, { zeros(0,2), zeros(0,2) });
+%! assert (m, { "OCT", "V" });
+%! assert (t, { cell(1,0), cell(1,0) });
+%! assert (isempty (fieldnames (nm)));
+%! assert (sp, { "", "A", "E" });
 
-%!assert (regexp("this word",'s w'),4)
-%!assert (regexp("this word",'s w','literalspacing'),4)
+%!test
+%! [s, e, te, m, t, nm, sp] = regexp ('OCTAVE', '([VOCT]*)', 'noemptymatch');
+%! assert (s, [1 5]);
+%! assert (e, [3 5]);
+%! assert (te, { [1 3], [5 5] });
+%! assert (m, { "OCT", "V" });
+%! assert (t, { {"OCT"}, {"V"} });
+%! assert (isempty (fieldnames (nm)));
+%! assert (sp, { "", "A", "E" });
+
 %!test
-%! assert (regexp("this word",'(?-x)s w','literalspacing'),4)
-%! assert (regexp("this word",'s w','freespacing'),zeros(1,0))
-%! assert (regexp("this word",'(?x)s w'),zeros(1,0))
+%! [s, e, te, m, t, nm, sp] = regexp ('OCTAVE', '[VOCT]*', 'emptymatch');
+%! assert (s, [1 4 5 6 7]);
+%! assert (e, [3 3 5 5 6]);
+%! assert (te, repmat ({zeros(0,2)}, [1, 5]));
+%! assert (m, { "OCT", "", "V", "", "" });
+%! assert (t, repmat({cell(1,0)}, [1, 5]));
+%! assert (isempty (fieldnames (nm)));
+%! assert (sp, { "", "", "A", "", "E", "" });
 
-%!error regexp('string', 'tri', 'BadArg');
-%!error regexp('string');
+%!test
+%! [s, e, te, m, t, nm, sp] = regexp ('OCTAVE', '([VOCT]*)', 'emptymatch');
+%! assert (s, [1 4 5 6 7]);
+%! assert (e, [3 3 5 5 6]);
+%! assert (te, { [1 3], [4 3], [5 5], [6 5], [7 6] });
+%! assert (m, { "OCT", "", "V", "", "" });
+%! assert (t, { {"OCT"}, {""}, {"V"}, {""}, {""} });
+%! assert (isempty (fieldnames (nm)));
+%! assert (sp, { "", "", "A", "", "E", "" });
 
-%!assert(regexp({'asdfg-dfd';'-dfd-dfd-';'qasfdfdaq'},'-'),{6;[1,5,9];zeros(1,0)})
-%!assert(regexp({'asdfg-dfd','-dfd-dfd-','qasfdfdaq'},'-'),{6,[1,5,9],zeros(1,0)})
-%!assert(regexp({'asdfg-dfd';'-dfd-dfd-';'qasfdfdaq'},{'-';'f';'q'}),{6;[3,7];[1,9]})
-%!assert(regexp('Strings',{'t','s'}),{2,7})
+%!error regexp ('string', 'tri', 'BadArg')
+%!error regexp ('string')
+
+%!assert (regexp ({'asdfg-dfd';'-dfd-dfd-';'qasfdfdaq'}, '-'), {6;[1,5,9];zeros(1,0)})
+%!assert (regexp ({'asdfg-dfd';'-dfd-dfd-';'qasfdfdaq'}, {'-';'f';'q'}), {6;[3,7];[1,9]})
+%!assert (regexp ('Strings', {'t','s'}), {2, 7})
 
 ## Test case for lookaround operators
 %!test
-%! assert(regexp('Iraq','q(?!u)'),4)
-%! assert(regexp('quit','q(?!u)'), zeros(1,0))
-%! assert(regexp('quit','q(?=u)','match'), {'q'})
-%! assert(regexp("quit",'q(?=u+)','match'), {'q'})
-%! assert(regexp("qit",'q(?=u+)','match'), cell(1,0))
-%! assert(regexp("qit",'q(?=u*)','match'), {'q'})
-%! assert(regexp('thingamabob','(?<=a)b'), 9)
+%! assert (regexp ('Iraq', 'q(?!u)'), 4);
+%! assert (regexp ('quit', 'q(?!u)'), zeros (1, 0));
+%! assert (regexp ('quit', 'q(?=u)' , 'match'), {'q'});
+%! assert (regexp ("quit", 'q(?=u+)', 'match'), {'q'});
+%! assert (regexp ("qit",  'q(?=u+)', 'match'), cell (1, 0));
+%! assert (regexp ("qit",  'q(?=u*)', 'match'), {'q'});
+%! assert (regexp ('thingamabob', '(?<=a)b'), 9);
 
 ## Tests for split option.
 %!shared str
@@ -845,8 +1034,8 @@
 %! assert (b, {"foo bar foo"});
 %!test
 %! [a, b] = regexp (str, "fx.", "match", "split", "once");
-%! assert (a, "");
-%! assert (b, "foo bar foo")
+%! assert (a, "");;
+%! assert (b, "foo bar foo");
 
 %!shared str
 %! str = "foo bar";
@@ -867,12 +1056,14 @@
 %! assert (a, {"oo"});
 %! assert (b, {"f", " bar"});
 
+%!assert (regexp ("\n", '\n'), 1);
+%!assert (regexp ("\n", "\n"), 1);
 */
 
-DEFUN_DLD (regexpi, args, nargout,
+DEFUN (regexpi, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {[@var{s}, @var{e}, @var{te}, @var{m}, @var{t}, @var{nm}] =} regexpi (@var{str}, @var{pat})\n\
-@deftypefnx {Loadable Function} {[@dots{}] =} regexpi (@var{str}, @var{pat}, \"@var{opt1}\", @dots{})\n\
+@deftypefn  {Built-in Function} {[@var{s}, @var{e}, @var{te}, @var{m}, @var{t}, @var{nm}, @var{sp}] =} regexpi (@var{str}, @var{pat})\n\
+@deftypefnx {Built-in Function} {[@dots{}] =} regexpi (@var{str}, @var{pat}, \"@var{opt1}\", @dots{})\n\
 \n\
 Case insensitive regular expression string matching.  Search for @var{pat} in\n\
 @var{str} and return the positions and substrings of any matches, or empty\n\
@@ -888,7 +1079,7 @@
   if (nargin < 2)
     print_usage ();
   else if (args(0).is_cell () || args(1).is_cell ())
-    retval = octcellregexp (args, nargout, "regexpi", true);
+    retval = octcellregexp (args, (nargout > 0 ? nargout : 1), "regexpi", true);
   else
     retval = octregexp (args, nargout, "regexpi", true);
 
@@ -896,139 +1087,139 @@
 }
 
 /*
-
-## seg-fault test
-%!assert(regexpi("abcde","."),[1,2,3,4,5])
+## segfault test
+%!assert (regexpi ("abcde", "."), [1,2,3,4,5])
 
 ## Check that anchoring of pattern works correctly
-%!assert(regexpi('abcabc','^ABC'),1);
-%!assert(regexpi('abcabc','ABC$'),4);
-%!assert(regexpi('abcabc','^ABC$'),zeros(1,0));
+%!assert (regexpi ('abcabc', '^ABC'), 1)
+%!assert (regexpi ('abcabc', 'ABC$'), 4)
+%!assert (regexpi ('abcabc', '^ABC$'), zeros (1,0))
 
 %!test
-%! [s, e, te, m, t] = regexpi(' No Match ', 'f(.*)uck');
-%! assert (s,zeros(1,0))
-%! assert (e,zeros(1,0))
-%! assert (te,cell(1,0))
-%! assert (m, cell(1,0))
-%! assert (t, cell(1,0))
+%! [s, e, te, m, t] = regexpi (' No Match ', 'f(.*)uck');
+%! assert (s, zeros (1,0));
+%! assert (e, zeros (1,0));
+%! assert (te, cell (1,0));
+%! assert (m, cell (1,0));
+%! assert (t, cell (1,0));
 
 %!test
-%! [s, e, te, m, t] = regexpi(' FiRetrUck ', 'f(.*)uck');
-%! assert (s,2)
-%! assert (e,10)
-%! assert (te{1},[3,7])
-%! assert (m{1}, 'FiRetrUck')
-%! assert (t{1}{1}, 'iRetr')
+%! [s, e, te, m, t] = regexpi (' FiRetrUck ', 'f(.*)uck');
+%! assert (s, 2);
+%! assert (e, 10);
+%! assert (te{1}, [3, 7]);
+%! assert (m{1}, 'FiRetrUck');
+%! assert (t{1}{1}, 'iRetr');
 
 %!test
-%! [s, e, te, m, t] = regexpi(' firetruck ', 'f(.*)uck');
-%! assert (s,2)
-%! assert (e,10)
-%! assert (te{1},[3,7])
-%! assert (m{1}, 'firetruck')
-%! assert (t{1}{1}, 'iretr')
+%! [s, e, te, m, t] = regexpi (' firetruck ', 'f(.*)uck');
+%! assert (s, 2);
+%! assert (e, 10);
+%! assert (te{1}, [3, 7]);
+%! assert (m{1}, 'firetruck');
+%! assert (t{1}{1}, 'iretr');
 
 %!test
-%! [s, e, te, m, t] = regexpi('ShoRt Test String','\w*r\w*');
-%! assert (s,[1,12])
-%! assert (e,[5,17])
-%! assert (size(te), [1,2])
-%! assert (isempty(te{1}))
-%! assert (isempty(te{2}))
-%! assert (m{1},'ShoRt')
-%! assert (m{2},'String')
-%! assert (size(t), [1,2])
-%! assert (isempty(t{1}))
-%! assert (isempty(t{2}))
+%! [s, e, te, m, t] = regexpi ('ShoRt Test String', '\w*r\w*');
+%! assert (s, [1, 12]);
+%! assert (e, [5, 17]);
+%! assert (size (te), [1, 2]);
+%! assert (isempty (te{1}));
+%! assert (isempty (te{2}));
+%! assert (m{1}, 'ShoRt');
+%! assert (m{2}, 'String');
+%! assert (size (t), [1, 2]);
+%! assert (isempty (t{1}));
+%! assert (isempty (t{2}));
 
 %!test
-%! [s, e, te, m, t] = regexpi('ShoRt Test String','\w*r\w*','once');
-%! assert (s,1)
-%! assert (e,5)
-%! assert (isempty(te))
-%! assert (m,'ShoRt')
-%! assert (isempty(t))
+%! [s, e, te, m, t] = regexpi ('ShoRt Test String', '\w*r\w*', 'once');
+%! assert (s, 1);
+%! assert (e, 5);
+%! assert (isempty (te));
+%! assert (m, 'ShoRt');
+%! assert (isempty (t));
 
 %!test
-%! [m, te, e, s, t] = regexpi('ShoRt Test String','\w*r\w*','once', 'match', 'tokenExtents', 'end', 'start', 'tokens');
-%! assert (s,1)
-%! assert (e,5)
-%! assert (isempty(te))
-%! assert (m,'ShoRt')
-%! assert (isempty(t))
+%! [m, te, e, s, t] = regexpi ('ShoRt Test String', '\w*r\w*', 'once', 'match', 'tokenExtents', 'end', 'start', 'tokens');
+%! assert (s, 1);
+%! assert (e, 5);
+%! assert (isempty (te));
+%! assert (m, 'ShoRt');
+%! assert (isempty (t));
 
 %!test
-%! [s, e, te, m, t, nm] = regexpi('ShoRt Test String','(?<word1>\w*t)\s*(?<word2>\w*t)');
-%! assert (s,1)
-%! assert (e,10)
-%! assert (size(te), [1,1])
-%! assert (te{1}, [1 5; 7, 10])
-%! assert (m{1},'ShoRt Test')
-%! assert (size(t),[1,1])
-%! assert (t{1}{1},'ShoRt')
-%! assert (t{1}{2},'Test')
-%! assert (size(nm), [1,1])
-%! assert (!isempty(fieldnames(nm)))
-%! assert (sort(fieldnames(nm)),{'word1';'word2'})
-%! assert (nm.word1,'ShoRt')
-%! assert (nm.word2,'Test')
+%! [s, e, te, m, t, nm] = regexpi ('ShoRt Test String', '(?<word1>\w*t)\s*(?<word2>\w*t)');
+%! assert (s, 1);
+%! assert (e, 10);
+%! assert (size (te), [1, 1]);
+%! assert (te{1}, [1,5; 7,10]);
+%! assert (m{1}, 'ShoRt Test');
+%! assert (size (t), [1, 1]);
+%! assert (t{1}{1}, 'ShoRt');
+%! assert (t{1}{2}, 'Test');
+%! assert (size (nm), [1, 1]);
+%! assert (! isempty (fieldnames (nm)));
+%! assert (sort (fieldnames (nm)), {'word1';'word2'});
+%! assert (nm.word1, 'ShoRt');
+%! assert (nm.word2, 'Test');
 
 %!test
-%! [nm, m, te, e, s, t] = regexpi('ShoRt Test String','(?<word1>\w*t)\s*(?<word2>\w*t)', 'names', 'match', 'tokenExtents', 'end', 'start', 'tokens');
-%! assert (s,1)
-%! assert (e,10)
-%! assert (size(te), [1,1])
-%! assert (te{1}, [1 5; 7, 10])
-%! assert (m{1},'ShoRt Test')
-%! assert (size(t),[1,1])
-%! assert (t{1}{1},'ShoRt')
-%! assert (t{1}{2},'Test')
-%! assert (size(nm), [1,1])
-%! assert (!isempty(fieldnames(nm)))
-%! assert (sort(fieldnames(nm)),{'word1';'word2'})
-%! assert (nm.word1,'ShoRt')
-%! assert (nm.word2,'Test')
+%! [nm, m, te, e, s, t] = regexpi ('ShoRt Test String', '(?<word1>\w*t)\s*(?<word2>\w*t)', 'names', 'match', 'tokenExtents', 'end', 'start', 'tokens');
+%! assert (s, 1);
+%! assert (e, 10);
+%! assert (size (te), [1, 1]);
+%! assert (te{1}, [1,5; 7,10]);
+%! assert (m{1}, 'ShoRt Test');
+%! assert (size (t), [1, 1]);
+%! assert (t{1}{1}, 'ShoRt');
+%! assert (t{1}{2}, 'Test');
+%! assert (size (nm), [1, 1]);
+%! assert (!isempty (fieldnames (nm)));
+%! assert (sort (fieldnames (nm)), {'word1';'word2'});
+%! assert (nm.word1, 'ShoRt');
+%! assert (nm.word2, 'Test');
 
-%!assert(regexpi("abc\nabc",'.'),[1:7])
-%!assert(regexpi("abc\nabc",'.','dotall'),[1:7])
+%!assert (regexpi ("abc\nabc", '.'), [1:7])
+%!assert (regexpi ("abc\nabc", '.', 'dotall'), [1:7])
 %!test
-%! assert(regexpi("abc\nabc",'(?s).'),[1:7])
-%! assert(regexpi("abc\nabc",'.','dotexceptnewline'),[1,2,3,5,6,7])
-%! assert(regexpi("abc\nabc",'(?-s).'),[1,2,3,5,6,7])
+%! assert (regexpi ("abc\nabc", '(?s).'), [1:7]);
+%! assert (regexpi ("abc\nabc", '.', 'dotexceptnewline'), [1,2,3,5,6,7]);
+%! assert (regexpi ("abc\nabc", '(?-s).'), [1,2,3,5,6,7]);
 
-%!assert(regexpi("caseCaSe",'case'),[1,5])
-%!assert(regexpi("caseCaSe",'case',"matchcase"),1)
-%!assert(regexpi("caseCaSe",'case',"ignorecase"),[1,5])
+%!assert (regexpi ("caseCaSe", 'case'), [1, 5])
+%!assert (regexpi ("caseCaSe", 'case', "matchcase"), 1)
+%!assert (regexpi ("caseCaSe", 'case', "ignorecase"), [1, 5])
 %!test
-%! assert(regexpi("caseCaSe",'(?-i)case'),1)
-%! assert(regexpi("caseCaSe",'(?i)case'),[1,5])
+%! assert (regexpi ("caseCaSe", '(?-i)case'), 1);
+%! assert (regexpi ("caseCaSe", '(?i)case'), [1, 5]);
 
-%!assert (regexpi("abc\nabc",'C$'),7)
-%!assert (regexpi("abc\nabc",'C$',"stringanchors"),7)
+%!assert (regexpi ("abc\nabc", 'C$'), 7)
+%!assert (regexpi ("abc\nabc", 'C$', "stringanchors"), 7)
 %!test
-%! assert (regexpi("abc\nabc",'(?-m)C$'),7)
-%! assert (regexpi("abc\nabc",'C$',"lineanchors"),[3,7])
-%! assert (regexpi("abc\nabc",'(?m)C$'),[3,7])
+%! assert (regexpi ("abc\nabc", '(?-m)C$'), 7);
+%! assert (regexpi ("abc\nabc", 'C$', "lineanchors"), [3, 7]);
+%! assert (regexpi ("abc\nabc", '(?m)C$'), [3, 7]);
 
-%!assert (regexpi("this word",'S w'),4)
-%!assert (regexpi("this word",'S w','literalspacing'),4)
+%!assert (regexpi ("this word", 'S w'), 4)
+%!assert (regexpi ("this word", 'S w', 'literalspacing'), 4)
 %!test
-%! assert (regexpi("this word",'(?-x)S w','literalspacing'),4)
-%! assert (regexpi("this word",'S w','freespacing'),zeros(1,0))
-%! assert (regexpi("this word",'(?x)S w'),zeros(1,0))
+%! assert (regexpi ("this word", '(?-x)S w', 'literalspacing'), 4);
+%! assert (regexpi ("this word", 'S w', 'freespacing'), zeros (1,0));
+%! assert (regexpi ("this word", '(?x)S w'), zeros (1,0));
 
-%!error regexpi('string', 'tri', 'BadArg');
-%!error regexpi('string');
+%!error regexpi ('string', 'tri', 'BadArg')
+%!error regexpi ('string')
 
-%!assert(regexpi({'asdfg-dfd';'-dfd-dfd-';'qasfdfdaq'},'-'),{6;[1,5,9];zeros(1,0)})
-%!assert(regexpi({'asdfg-dfd','-dfd-dfd-','qasfdfdaq'},'-'),{6,[1,5,9],zeros(1,0)})
-%!assert(regexpi({'asdfg-dfd';'-dfd-dfd-';'qasfdfdaq'},{'-';'f';'q'}),{6;[3,7];[1,9]})
-%!assert(regexpi('Strings',{'t','s'}),{2,[1,7]})
+%!assert (regexpi ({'asdfg-dfd';'-dfd-dfd-';'qasfdfdaq'}, '-'), {6;[1,5,9];zeros(1, 0)})
+%!assert (regexpi ({'asdfg-dfd', '-dfd-dfd-', 'qasfdfdaq'}, '-'), {6, [1,5,9], zeros(1,0)})
+%!assert (regexpi ({'asdfg-dfd';'-dfd-dfd-';'qasfdfdaq'}, {'-';'f';'q'}), {6;[3,7];[1,9]})
+%!assert (regexpi ('Strings', {'t', 's'}), {2, [1, 7]})
 
+%!assert (regexpi ("\n", '\n'), 1);
+%!assert (regexpi ("\n", "\n"), 1);
 */
 
-
 static octave_value
 octregexprep (const octave_value_list &args, const std::string &who)
 {
@@ -1041,13 +1232,19 @@
   if (error_state)
     return retval;
 
-  const std::string pattern = args(1).string_value ();
+  std::string pattern = args(1).string_value ();
   if (error_state)
     return retval;
+  // Matlab compatibility.
+  if (args(1).is_sq_string ())
+    pattern = do_regexp_ptn_string_escapes (pattern);
 
-  const std::string replacement = args(2).string_value ();
+  std::string replacement = args(2).string_value ();
   if (error_state)
     return retval;
+  // Matlab compatibility.
+  if (args(2).is_sq_string ())
+    replacement = do_regexp_rep_string_escapes (replacement);
 
   // Pack options excluding 'tokenize' and various output
   // reordering strings into regexp arg list
@@ -1075,10 +1272,10 @@
   return regexp_replace (pattern, buffer, replacement, options, who);
 }
 
-DEFUN_DLD (regexprep, args, ,
+DEFUN (regexprep, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{outstr} =} regexprep (@var{string}, @var{pat}, @var{repstr})\n\
-@deftypefnx {Loadable Function} {@var{outstr} =} regexprep (@var{string}, @var{pat}, @var{repstr}, \"@var{opt1}\", @dots{})\n\
+@deftypefn  {Built-in Function} {@var{outstr} =} regexprep (@var{string}, @var{pat}, @var{repstr})\n\
+@deftypefnx {Built-in Function} {@var{outstr} =} regexprep (@var{string}, @var{pat}, @var{repstr}, \"@var{opt1}\", @dots{})\n\
 Replace occurrences of pattern @var{pat} in @var{string} with @var{repstr}.\n\
 \n\
 The pattern is a regular expression as documented for @code{regexp}.\n\
@@ -1088,7 +1285,7 @@
 for the ith set of parentheses in the match string.  For example,\n\
 \n\
 @example\n\
-regexprep(\"Bill Dunn\",'(\\w+) (\\w+)','$2, $1')\n\
+regexprep (\"Bill Dunn\", '(\\w+) (\\w+)', '$2, $1')\n\
 @end example\n\
 \n\
 @noindent\n\
@@ -1105,6 +1302,11 @@
 This option is present for compatibility but is ignored.\n\
 \n\
 @end table\n\
+\n\
+Implementation Note: For compatibility with @sc{matlab}, ordinary escape\n\
+sequences (e.g., \"\\n\" => newline) are processed in both @var{pat}\n\
+and @var{repstr} regardless of whether they were defined within single quotes.  Use a second backslash to stop interpolation of the escape sequence (e.g.,\n\
+\"\\\\n\") or use the @code{regexptranslate} function.\n\
 @seealso{regexp, regexpi, strrep}\n\
 @end deftypefn")
 {
@@ -1158,9 +1360,9 @@
           for (octave_idx_type i = 0; i < dv0.numel (); i++)
             {
               new_args(0) = str(i);
-              if (pat.numel() == 1)
+              if (pat.numel () == 1)
                 new_args(1) = pat(0);
-              if (rep.numel() == 1)
+              if (rep.numel () == 1)
                 new_args(2) = rep(0);
 
               for (octave_idx_type j = 0; j < dv1.numel (); j++)
@@ -1195,56 +1397,61 @@
 /*
 %!test  # Replace with empty
 %! xml = '<!-- This is some XML --> <tag v="hello">some stuff<!-- sample tag--></tag>';
-%! t = regexprep(xml,'<[!?][^>]*>','');
-%! assert(t,' <tag v="hello">some stuff</tag>')
+%! t = regexprep (xml, '<[!?][^>]*>', '');
+%! assert (t, ' <tag v="hello">some stuff</tag>');
 
 %!test  # Replace with non-empty
 %! xml = '<!-- This is some XML --> <tag v="hello">some stuff<!-- sample tag--></tag>';
-%! t = regexprep(xml,'<[!?][^>]*>','?');
-%! assert(t,'? <tag v="hello">some stuff?</tag>')
+%! t = regexprep (xml, '<[!?][^>]*>', '?');
+%! assert (t, '? <tag v="hello">some stuff?</tag>');
 
 %!test  # Check that 'tokenize' is ignored
 %! xml = '<!-- This is some XML --> <tag v="hello">some stuff<!-- sample tag--></tag>';
-%! t = regexprep(xml,'<[!?][^>]*>','','tokenize');
-%! assert(t,' <tag v="hello">some stuff</tag>')
+%! t = regexprep (xml, '<[!?][^>]*>', '', 'tokenize');
+%! assert (t, ' <tag v="hello">some stuff</tag>');
 
 ## Test capture replacement
 %!test
 %! data = "Bob Smith\nDavid Hollerith\nSam Jenkins";
 %! result = "Smith, Bob\nHollerith, David\nJenkins, Sam";
-%! t = regexprep(data,'(?m)^(\w+)\s+(\w+)$','$2, $1');
-%! assert(t,result)
+%! t = regexprep (data, '(?m)^(\w+)\s+(\w+)$', '$2, $1');
+%! assert (t, result);
 
 ## Return the original if no match
-%!assert(regexprep('hello','world','earth'),'hello')
+%!assert (regexprep ('hello', 'world', 'earth'), 'hello')
+
+## Test emptymatch
+%!assert (regexprep ('World', '^', 'Hello '), 'World')
+%!assert (regexprep ('World', '^', 'Hello ', 'emptymatch'), 'Hello World')
 
 ## Test a general replacement
-%!assert(regexprep("a[b]c{d}e-f=g", "[^A-Za-z0-9_]", "_"), "a_b_c_d_e_f_g");
+%!assert (regexprep ("a[b]c{d}e-f=g", "[^A-Za-z0-9_]", "_"), "a_b_c_d_e_f_g")
 
 ## Make sure it works at the beginning and end
-%!assert(regexprep("a[b]c{d}e-f=g", "a", "_"), "_[b]c{d}e-f=g");
-%!assert(regexprep("a[b]c{d}e-f=g", "g", "_"), "a[b]c{d}e-f=_");
+%!assert (regexprep ("a[b]c{d}e-f=g", "a", "_"), "_[b]c{d}e-f=g")
+%!assert (regexprep ("a[b]c{d}e-f=g", "g", "_"), "a[b]c{d}e-f=_")
 
 ## Options
-%!assert(regexprep("a[b]c{d}e-f=g", "[^A-Za-z0-9_]", "_", "once"), "a_b]c{d}e-f=g");
-%!assert(regexprep("a[b]c{d}e-f=g", "[^A-Z0-9_]", "_", "ignorecase"), "a_b_c_d_e_f_g");
+%!assert (regexprep ("a[b]c{d}e-f=g", "[^A-Za-z0-9_]", "_", "once"), "a_b]c{d}e-f=g")
+%!assert (regexprep ("a[b]c{d}e-f=g", "[^A-Z0-9_]", "_", "ignorecase"), "a_b_c_d_e_f_g")
 
 ## Option combinations
-%!assert(regexprep("a[b]c{d}e-f=g", "[^A-Z0-9_]", "_", "once", "ignorecase"), "a_b]c{d}e-f=g");
+%!assert (regexprep ("a[b]c{d}e-f=g", "[^A-Z0-9_]", "_", "once", "ignorecase"), "a_b]c{d}e-f=g")
 
 ## End conditions on replacement
-%!assert(regexprep("abc","(b)",".$1"),"a.bc");
-%!assert(regexprep("abc","(b)","$1"),"abc");
-%!assert(regexprep("abc","(b)","$1."),"ab.c");
-%!assert(regexprep("abc","(b)","$1.."),"ab..c");
+%!assert (regexprep ("abc", "(b)", ".$1"), "a.bc");
+%!assert (regexprep ("abc", "(b)", "$1"), "abc");
+%!assert (regexprep ("abc", "(b)", "$1."), "ab.c");
+%!assert (regexprep ("abc", "(b)", "$1.."), "ab..c");
 
 ## Test cell array arguments
-%!assert(regexprep("abc",{"b","a"},"?"),"??c")
-%!assert(regexprep({"abc","cba"},"b","?"),{"a?c","c?a"})
-%!assert(regexprep({"abc","cba"},{"b","a"},{"?","!"}),{"!?c","c?!"})
+%!assert (regexprep ("abc", {"b","a"}, "?"), "??c")
+%!assert (regexprep ({"abc","cba"}, "b", "?"), {"a?c","c?a"})
+%!assert (regexprep ({"abc","cba"}, {"b","a"}, {"?","!"}), {"!?c","c?!"})
 
 # Nasty lookbehind expression
-%!test
-%! assert(regexprep('x^(-1)+y(-1)+z(-1)=0','(?<=[a-z]+)\(\-[1-9]*\)','_minus1'),'x^(-1)+y_minus1+z_minus1=0')
+%!assert (regexprep ('x^(-1)+y(-1)+z(-1)=0', '(?<=[a-z]+)\(\-[1-9]*\)', '_minus1'),'x^(-1)+y_minus1+z_minus1=0')
 
+%!assert (regexprep ("\n", '\n', "X"), "X");
+%!assert (regexprep ("\n", "\n", "X"), "X");
 */
rename from src/DLD-FUNCTIONS/schur.cc
rename to libinterp/corefcn/schur.cc
--- a/src/DLD-FUNCTIONS/schur.cc
+++ b/libinterp/corefcn/schur.cc
@@ -31,7 +31,7 @@
 #include "fCmplxSCHUR.h"
 #include "floatSCHUR.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -57,13 +57,13 @@
   return retval;
 }
 
-DEFUN_DLD (schur, args, nargout,
+DEFUN (schur, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{S} =} schur (@var{A})\n\
-@deftypefnx {Loadable Function} {@var{S} =} schur (@var{A}, \"real\")\n\
-@deftypefnx {Loadable Function} {@var{S} =} schur (@var{A}, \"complex\")\n\
-@deftypefnx {Loadable Function} {@var{S} =} schur (@var{A}, @var{opt})\n\
-@deftypefnx {Loadable Function} {[@var{U}, @var{S}] =} schur (@var{A}, @dots{})\n\
+@deftypefn  {Built-in Function} {@var{S} =} schur (@var{A})\n\
+@deftypefnx {Built-in Function} {@var{S} =} schur (@var{A}, \"real\")\n\
+@deftypefnx {Built-in Function} {@var{S} =} schur (@var{A}, \"complex\")\n\
+@deftypefnx {Built-in Function} {@var{S} =} schur (@var{A}, @var{opt})\n\
+@deftypefnx {Built-in Function} {[@var{U}, @var{S}] =} schur (@var{A}, @dots{})\n\
 @cindex Schur decomposition\n\
 Compute the Schur@tie{}decomposition of @var{A}\n\
 @tex\n\
@@ -275,26 +275,24 @@
 }
 
 /*
-
 %!test
 %! a = [1, 2, 3; 4, 5, 9; 7, 8, 6];
 %! [u, s] = schur (a);
-%! assert(u' * a * u, s, sqrt (eps));
+%! assert (u' * a * u, s, sqrt (eps));
 
 %!test
-%! a = single([1, 2, 3; 4, 5, 9; 7, 8, 6]);
+%! a = single ([1, 2, 3; 4, 5, 9; 7, 8, 6]);
 %! [u, s] = schur (a);
-%! assert(u' * a * u, s, sqrt (eps('single')));
+%! assert (u' * a * u, s, sqrt (eps ("single")));
 
 %!test
-%! fail("schur ([1, 2; 3, 4], 2)","warning");
+%! fail ("schur ([1, 2; 3, 4], 2)", "warning");
 
-%!error <Invalid call to schur> schur ();
-%!error schur ([1, 2, 3; 4, 5, 6]);
-
+%!error schur ()
+%!error <argument must be a square matrix> schur ([1, 2, 3; 4, 5, 6])
 */
 
-DEFUN_DLD (rsf2csf, args, nargout,
+DEFUN (rsf2csf, args, nargout,
   "-*- texinfo -*-\n\
 @deftypefn {Function File} {[@var{U}, @var{T}] =} rsf2csf (@var{UR}, @var{TR})\n\
 Convert a real, upper quasi-triangular Schur@tie{}form @var{TR} to a complex,\n\
@@ -361,24 +359,23 @@
 }
 
 /*
-
 %!test
 %! A = [1, 1, 1, 2; 1, 2, 1, 1; 1, 1, 3, 1; -2, 1, 1, 1];
 %! [u, t] = schur (A);
 %! [U, T] = rsf2csf (u, t);
-%! assert (norm (u * t * u' - U * T * U'), 0, 1e-12)
-%! assert (norm (A - U * T * U'), 0, 1e-12)
+%! assert (norm (u * t * u' - U * T * U'), 0, 1e-12);
+%! assert (norm (A - U * T * U'), 0, 1e-12);
 
 %!test
 %! A = rand (10);
 %! [u, t] = schur (A);
 %! [U, T] = rsf2csf (u, t);
-%! assert (norm (tril (T, -1)), 0)
-%! assert (norm (U * U'), 1, 1e-14)
+%! assert (norm (tril (T, -1)), 0);
+%! assert (norm (U * U'), 1, 1e-14);
 
 %!test
 %! A = [0, 1;-1, 0];
 %! [u, t] = schur (A);
 %! [U, T] = rsf2csf (u,t);
-%! assert (U * T * U', A, 1e-14)
+%! assert (U * T * U', A, 1e-14);
 */
rename from src/sparse.cc
rename to libinterp/corefcn/sparse.cc
--- a/src/sparse.cc
+++ b/libinterp/corefcn/sparse.cc
@@ -43,12 +43,12 @@
 
 DEFUN (issparse, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} issparse (@var{x})\n\
+@deftypefn {Built-in Function} {} issparse (@var{x})\n\
 Return true if @var{x} is a sparse matrix.\n\
 @seealso{ismatrix}\n\
 @end deftypefn")
 {
-   if (args.length() != 1)
+   if (args.length () != 1)
      {
        print_usage ();
        return octave_value ();
@@ -59,11 +59,11 @@
 
 DEFUN (sparse, args, ,
     "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{s} =} sparse (@var{a})\n\
-@deftypefnx {Loadable Function} {@var{s} =} sparse (@var{i}, @var{j}, @var{sv}, @var{m}, @var{n}, @var{nzmax})\n\
-@deftypefnx {Loadable Function} {@var{s} =} sparse (@var{i}, @var{j}, @var{sv})\n\
-@deftypefnx {Loadable Function} {@var{s} =} sparse (@var{i}, @var{j}, @var{s}, @var{m}, @var{n}, \"unique\")\n\
-@deftypefnx {Loadable Function} {@var{s} =} sparse (@var{m}, @var{n})\n\
+@deftypefn  {Built-in Function} {@var{s} =} sparse (@var{a})\n\
+@deftypefnx {Built-in Function} {@var{s} =} sparse (@var{i}, @var{j}, @var{sv}, @var{m}, @var{n}, @var{nzmax})\n\
+@deftypefnx {Built-in Function} {@var{s} =} sparse (@var{i}, @var{j}, @var{sv})\n\
+@deftypefnx {Built-in Function} {@var{s} =} sparse (@var{i}, @var{j}, @var{s}, @var{m}, @var{n}, \"unique\")\n\
+@deftypefnx {Built-in Function} {@var{s} =} sparse (@var{m}, @var{n})\n\
 Create a sparse matrix from the full matrix or row, column, value triplets.\n\
 If @var{a} is a full matrix, convert it to a sparse matrix representation,\n\
 removing all zero values in the process.\n\
@@ -78,7 +78,8 @@
 \n\
 @strong{Note}: if multiple values are specified with the same\n\
 @var{i}, @var{j} indices, the corresponding values in @var{s} will\n\
-be added.\n\
+be added.  See @code{accumarray} for an example of how to produce different\n\
+behavior, such as taking the minimum instead.\n\
 \n\
 The following are all equivalent:\n\
 \n\
@@ -93,12 +94,12 @@
 Given the option \"unique\". if more than two values are specified for the\n\
 same @var{i}, @var{j} indices, the last specified value will be used.\n\
 \n\
-@code{sparse(@var{m}, @var{n})} is equivalent to\n\
+@code{sparse (@var{m}, @var{n})} is equivalent to\n\
 @code{sparse ([], [], [], @var{m}, @var{n}, 0)}\n\
 \n\
 If any of @var{sv}, @var{i} or @var{j} are scalars, they are expanded\n\
 to have a common size.\n\
-@seealso{full}\n\
+@seealso{full, accumarray}\n\
 @end deftypefn")
 {
    octave_value retval;
@@ -208,7 +209,7 @@
 
 DEFUN (spalloc, args, ,
     "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{s} =} spalloc (@var{m}, @var{n}, @var{nz})\n\
+@deftypefn {Built-in Function} {@var{s} =} spalloc (@var{m}, @var{n}, @var{nz})\n\
 Create an @var{m}-by-@var{n} sparse matrix with pre-allocated space for at\n\
 most @var{nz} nonzero elements.  This is useful for building the matrix\n\
 incrementally by a sequence of indexed assignments.  Subsequent indexed\n\
@@ -226,9 +227,9 @@
 @b{and} that the following conditions are met:\n\
 \n\
 @itemize\n\
-@item the assignment does not decrease nnz(@var{S}).\n\
+@item the assignment does not decrease nnz (@var{S}).\n\
 \n\
-@item after the assignment, nnz(@var{S}) does not exceed @var{nz}.\n\
+@item after the assignment, nnz (@var{S}) does not exceed @var{nz}.\n\
 \n\
 @item no index is out of bounds.\n\
 @end itemize\n\
rename from src/DLD-FUNCTIONS/spparms.cc
rename to libinterp/corefcn/spparms.cc
--- a/src/DLD-FUNCTIONS/spparms.cc
+++ b/libinterp/corefcn/spparms.cc
@@ -25,7 +25,7 @@
 #include <config.h>
 #endif
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "ov.h"
 #include "pager.h"
 #include "error.h"
@@ -33,16 +33,16 @@
 
 #include "oct-spparms.h"
 
-DEFUN_DLD (spparms, args, nargout,
+DEFUN (spparms, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} { } spparms ()\n\
-@deftypefnx {Loadable Function} {@var{vals} =} spparms ()\n\
-@deftypefnx {Loadable Function} {[@var{keys}, @var{vals}] =} spparms ()\n\
-@deftypefnx {Loadable Function} {@var{val} =} spparms (@var{key})\n\
-@deftypefnx {Loadable Function} { } spparms (@var{vals})\n\
-@deftypefnx {Loadable Function} { } spparms ('defaults')\n\
-@deftypefnx {Loadable Function} { } spparms ('tight')\n\
-@deftypefnx {Loadable Function} { } spparms (@var{key}, @var{val})\n\
+@deftypefn  {Built-in Function} { } spparms ()\n\
+@deftypefnx {Built-in Function} {@var{vals} =} spparms ()\n\
+@deftypefnx {Built-in Function} {[@var{keys}, @var{vals}] =} spparms ()\n\
+@deftypefnx {Built-in Function} {@var{val} =} spparms (@var{key})\n\
+@deftypefnx {Built-in Function} { } spparms (@var{vals})\n\
+@deftypefnx {Built-in Function} { } spparms (\"defaults\")\n\
+@deftypefnx {Built-in Function} { } spparms (\"tight\")\n\
+@deftypefnx {Built-in Function} { } spparms (@var{key}, @var{val})\n\
 Query or set the parameters used by the sparse solvers and factorization\n\
 functions.  The first four calls above get information about the current\n\
 settings, while the others change the current settings.  The parameters are\n\
@@ -97,9 +97,9 @@
 The value of individual keys can be set with\n\
 @code{spparms (@var{key}, @var{val})}.\n\
 The default values can be restored with the special keyword\n\
-'defaults'.  The special keyword 'tight' can be used to set the mmd solvers\n\
-to attempt a sparser solution at the potential cost of longer running\n\
-time.\n\
+\"defaults\".  The special keyword \"tight\" can be used to set the mmd\n\
+solvers to attempt a sparser solution at the potential cost of longer\n\
+running time.\n\
 @end deftypefn")
 {
   octave_value_list retval;
@@ -113,8 +113,8 @@
         retval(0) =  octave_sparse_params::get_vals ();
       else if (nargout == 2)
         {
-          retval (1) = octave_sparse_params::get_vals ();
-          retval (0) = octave_sparse_params::get_keys ();
+          retval(1) = octave_sparse_params::get_vals ();
+          retval(0) = octave_sparse_params::get_keys ();
         }
       else
         error ("spparms: too many output arguments");
@@ -126,7 +126,7 @@
           std::string str = args(0).string_value ();
           int len = str.length ();
           for (int i = 0; i < len; i++)
-            str [i] = tolower (str [i]);
+            str[i] = tolower (str[i]);
 
           if (str == "defaults")
             octave_sparse_params::defaults ();
@@ -138,7 +138,7 @@
               if (xisnan (val))
                 error ("spparms: KEY not recognized");
               else
-                retval (0) = val;
+                retval(0) = val;
             }
         }
       else
@@ -178,7 +178,6 @@
 }
 
 /*
-
 %!test
 %! old_vals = spparms ();  # save state
 %! spparms ("defaults");
@@ -196,13 +195,14 @@
 %! spparms (old_vals);     # restore state
 
 %% Test input validation
-%!error (spparms (1, 2, 3))
-%!error ([x, y, z] = spparms ())
-%!error (spparms ("UNKNOWN_KEY"))
-%!error (spparms ({1, 2, 3}))
-%!error (spparms (ones (14, 1)))
-%!error (spparms (1, 1))
-%!error (spparms ("ths_rel", "hello"))
-%!error (spparms ("UNKNOWN_KEY", 1))
-
+%!error <too many input arguments> spparms (1, 2, 3)
+%!error <too many output arguments> [x, y, z] = spparms ()
+%!error <KEY not recognized> spparms ("UNKNOWN_KEY")
+%!#error <input must be a string> spparms ({1, 2, 3})
+%!error spparms ({1, 2, 3})
+%!error <too many elements in vector VALS> spparms (ones (14, 1))
+%!error <first argument must be a string> spparms (1, 1)
+%!#error <second argument must be a real scalar> spparms ("ths_rel", "hello")
+%!error spparms ("ths_rel", "hello")
+%!error <KEY not found> spparms ("UNKNOWN_KEY", 1)
 */
rename from src/DLD-FUNCTIONS/sqrtm.cc
rename to libinterp/corefcn/sqrtm.cc
--- a/src/DLD-FUNCTIONS/sqrtm.cc
+++ b/libinterp/corefcn/sqrtm.cc
@@ -33,7 +33,7 @@
 #include "lo-mappers.h"
 #include "oct-norm.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "utils.h"
@@ -199,10 +199,10 @@
   return retval;
 }
 
-DEFUN_DLD (sqrtm, args, nargout,
+DEFUN (sqrtm, args, nargout,
  "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{s} =} sqrtm (@var{A})\n\
-@deftypefnx {Loadable Function} {[@var{s}, @var{error_estimate}] =} sqrtm (@var{A})\n\
+@deftypefn  {Built-in Function} {@var{s} =} sqrtm (@var{A})\n\
+@deftypefnx {Built-in Function} {[@var{s}, @var{error_estimate}] =} sqrtm (@var{A})\n\
 Compute the matrix square root of the square matrix @var{A}.\n\
 \n\
 Ref: N.J. Higham.  @cite{A New sqrtm for @sc{matlab}}.  Numerical\n\
@@ -260,20 +260,17 @@
 }
 
 /*
-
 %!assert (sqrtm (2*ones (2)), ones (2), 3*eps)
 
 ## The following two tests are from the reference in the docstring above.
-
 %!test
 %! x = [0 1; 0 0];
-%! assert (any (isnan (sqrtm (x))(:) ))
+%! assert (any (isnan (sqrtm (x))(:)));
 
 %!test
-%! x = eye (4); x(2,2) = x(3,3) = 2^-26; x(1,4) = 1;
-%! z = eye (4); z(2,2) = z(3,3) = 2^-13; z(1,4) = 0.5;
-%! [y, err] = sqrtm(x);
-%! assert (y, z)
-%! assert (err, 0)   ## Yes, this one has to hold exactly
-
+%! x = eye (4);  x(2,2) = x(3,3) = 2^-26;  x(1,4) = 1;
+%! z = eye (4);  z(2,2) = z(3,3) = 2^-13;  z(1,4) = 0.5;
+%! [y, err] = sqrtm (x);
+%! assert (y, z);
+%! assert (err, 0);   ## Yes, this one has to hold exactly
 */
rename from src/DLD-FUNCTIONS/str2double.cc
rename to libinterp/corefcn/str2double.cc
--- a/src/DLD-FUNCTIONS/str2double.cc
+++ b/libinterp/corefcn/str2double.cc
@@ -34,7 +34,7 @@
 
 #include "Cell.h"
 #include "ov.h"
-#include "defun-dld.h"
+#include "defun.h"
 #include "gripes.h"
 #include "utils.h"
 
@@ -54,15 +54,15 @@
       c = is.peek ();
     }
 
-  if (c == 'I')
+  if (std::toupper (c) == 'I')
     {
       // It's infinity.
       is.get ();
       char c1 = is.get (), c2 = is.get ();
-      if (c1 == 'n' && c2 == 'f')
+      if (std::tolower (c1) == 'n' && std::tolower (c2) == 'f')
         {
           num = octave_Inf;
-          is.peek (); // May sets EOF bit.
+          is.peek (); // May set EOF bit.
         }
       else
         is.setstate (std::ios::failbit); // indicate that read has failed.
@@ -127,13 +127,37 @@
       c = is.peek ();
     }
 
-  // It's i*num or just i.
-  if (is_imag_unit (c))
+  // Imaginary number (i*num or just i), or maybe 'inf'.
+  if (c == 'i')
     {
-      imag = true;
+      // possible infinity.
       is.get ();
       c = is.peek ();
 
+      if (is.eof ())
+        {
+          // just 'i' and string is finished.  Return immediately.
+          imag = true;
+          num = 1.0;
+          if (negative)
+            num = -num;
+          return is;
+        }
+      else
+        { 
+          if (std::tolower (c) != 'n')
+            imag = true;
+          is.unget ();
+        }
+    }
+  else if (c == 'j')
+    imag = true;
+    
+  // It's i*num or just i
+  if (imag)
+    {
+      is.get ();
+      c = is.peek ();
       // Skip spaces after imaginary unit.
       while (isspace (c))
         {
@@ -270,7 +294,7 @@
   return val;
 }
 
-DEFUN_DLD (str2double, args, ,
+DEFUN (str2double, args, ,
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} str2double (@var{s})\n\
 Convert a string to a real or complex number.\n\
@@ -350,10 +374,9 @@
 }
 
 /*
-
 %!assert (str2double ("1"), 1)
 %!assert (str2double ("-.1e-5"), -1e-6)
-%!assert (str2double (char ("1", "2 3", "4i")), [1; NaN; 4i]);
+%!assert (str2double (char ("1", "2 3", "4i")), [1; NaN; 4i])
 %!assert (str2double ("-.1e-5"), -1e-6)
 %!assert (str2double ("1,222.5"), 1222.5)
 %!assert (str2double ("i"), i)
@@ -370,13 +393,14 @@
 %!assert (str2double ("NaN"), NaN)
 %!assert (str2double ("NA"), NA)
 %!assert (str2double ("Inf"), Inf)
+%!assert (str2double ("iNF"), Inf)
 %!assert (str2double ("-Inf"), -Inf)
 %!assert (str2double ("Inf*i"), complex (0, Inf))
+%!assert (str2double ("iNF*i"), complex (0, Inf))
 %!assert (str2double ("NaN + Inf*i"), complex (NaN, Inf))
 %!assert (str2double ("Inf - Inf*i"), complex (Inf, -Inf))
 %!assert (str2double ("-i*NaN - Inf"), complex (-Inf, -NaN))
 %!assert (str2double ({"abc", "4i"}), [NaN + 0i, 4i])
 %!assert (str2double ({2, "4i"}), [NaN + 0i, 4i])
-%!assert (str2double (zeros(3,1,2)), NaN (3,1,2))
-
+%!assert (str2double (zeros (3,1,2)), NaN (3,1,2))
 */
rename from src/DLD-FUNCTIONS/strfind.cc
rename to libinterp/corefcn/strfind.cc
--- a/src/DLD-FUNCTIONS/strfind.cc
+++ b/libinterp/corefcn/strfind.cc
@@ -25,27 +25,27 @@
 #include <config.h>
 #endif
 
-#include <string>
-#include <climits>
 #include <algorithm>
 #include <deque>
+#include <limits>
+#include <string>
 
 #include "Cell.h"
 #include "ov.h"
-#include "defun-dld.h"
+#include "defun.h"
 #include "unwind-prot.h"
 #include "gripes.h"
 #include "utils.h"
 
 // This allows safe indexing with char. In C++, char may be (and often is) signed!
 #define ORD(ch) static_cast<unsigned char>(ch)
-#define TABSIZE (UCHAR_MAX + 1)
+#define TABSIZE (std::numeric_limits<unsigned char>::max () + 1)
 
 // This is the quick search algorithm, as described at
 // http://www-igm.univ-mlv.fr/~lecroq/string/node19.html
 static void
 qs_preprocess (const Array<char>& needle,
-               octave_idx_type table[TABSIZE])
+               octave_idx_type *table)
 {
   const char *x = needle.data ();
   octave_idx_type m = needle.numel ();
@@ -60,7 +60,7 @@
 static Array<octave_idx_type>
 qs_search (const Array<char>& needle,
            const Array<char>& haystack,
-           const octave_idx_type table[TABSIZE],
+           const octave_idx_type *table,
            bool overlaps = true)
 {
   const char *x = needle.data ();
@@ -145,10 +145,10 @@
   return result;
 }
 
-DEFUN_DLD (strfind, args, ,
+DEFUN (strfind, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{idx} =} strfind (@var{str}, @var{pattern})\n\
-@deftypefnx {Loadable Function} {@var{idx} =} strfind (@var{cellstr}, @var{pattern})\n\
+@deftypefn  {Built-in Function} {@var{idx} =} strfind (@var{str}, @var{pattern})\n\
+@deftypefnx {Built-in Function} {@var{idx} =} strfind (@var{cellstr}, @var{pattern})\n\
 Search for @var{pattern} in the string @var{str} and return the\n\
 starting index of every such occurrence in the vector @var{idx}.\n\
 If there is no such occurrence, or if @var{pattern} is longer\n\
@@ -164,7 +164,7 @@
      @result{} [1, 3, 5]\n\
 \n\
 strfind (@{\"abababa\", \"bebebe\", \"ab\"@}, \"aba\")\n\
-     @result{} ans =\n\
+     @result{}\n\
         @{\n\
           [1,1] =\n\
 \n\
@@ -247,23 +247,21 @@
 }
 
 /*
-
-%!error strfind ();
-%!error strfind ("foo", "bar", 1);
-%!error strfind ("foo", 100);
-%!error strfind (100, "foo");
+%!assert (strfind ("abababa", "aba"), [1, 3, 5])
+%!assert (strfind ("abababa", "aba", "overlaps", false), [1, 5])
+%!assert (strfind ({"abababa", "bla", "bla"}, "a"), {[1, 3, 5, 7], 3, 3})
+%!assert (strfind ("Linux _is_ user-friendly. It just isn't ignorant-friendly or idiot-friendly.", "friendly"), [17, 50, 68])
 
-%!assert (strfind ("abababa", "aba"), [1, 3, 5]);
-%!assert (strfind ("abababa", "aba", "overlaps", false), [1, 5]);
-%!assert (strfind ({"abababa", "bla", "bla"}, "a"), {[1, 3, 5, 7], 3, 3});
-%!assert (strfind ("Linux _is_ user-friendly. It just isn't ignorant-friendly or idiot-friendly.", "friendly"), [17, 50, 68]);
-
+%!error strfind ()
+%!error strfind ("foo", "bar", 1)
+%!error <PATTERN must be a string> strfind ("foo", 100)
+%!error <first argument must be a string> strfind (100, "foo")
 */
 
 static Array<char>
 qs_replace (const Array<char>& str, const Array<char>& pat,
             const Array<char>& rep,
-            const octave_idx_type table[TABSIZE],
+            const octave_idx_type *table,
             bool overlaps = true)
 {
   Array<char> ret = str;
@@ -321,17 +319,17 @@
   return ret;
 }
 
-DEFUN_DLD (strrep, args, ,
+DEFUN (strrep, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} strrep (@var{s}, @var{ptn}, @var{rep})\n\
-@deftypefnx {Loadable Function} {} strrep (@var{s}, @var{ptn}, @var{rep}, \"overlaps\", @var{o})\n\
+@deftypefn  {Built-in Function} {} strrep (@var{s}, @var{ptn}, @var{rep})\n\
+@deftypefnx {Built-in Function} {} strrep (@var{s}, @var{ptn}, @var{rep}, \"overlaps\", @var{o})\n\
 Replace all occurrences of the substring @var{ptn} in the string @var{s}\n\
 with the string @var{rep} and return the result.  For example:\n\
 \n\
 @example\n\
 @group\n\
 strrep (\"This is a test string\", \"is\", \"&%$\")\n\
-     @result{} \"Th&%$ &%$ a test string\"\n\
+    @result{}  \"Th&%$ &%$ a test string\"\n\
 @end group\n\
 @end example\n\
 \n\
@@ -407,14 +405,11 @@
 }
 
 /*
-
-%!assert(strcmp (strrep ("This is a test string", "is", "&%$"),
-%! "Th&%$ &%$ a test string"));
-%!assert(strrep ("abababc", "abab", "xyz"), "xyzxyzc");
-%!assert(strrep ("abababc", "abab", "xyz", "overlaps", false), "xyzabc");
+%!assert (strrep ("This is a test string", "is", "&%$"),
+%!                "Th&%$ &%$ a test string")
+%!assert (strrep ("abababc", "abab", "xyz"), "xyzxyzc")
+%!assert (strrep ("abababc", "abab", "xyz", "overlaps", false), "xyzabc")
 
-%!error strrep ();
-
-%!error strrep ("foo", "bar", 3, 4);
-
+%!error strrep ()
+%!error strrep ("foo", "bar", 3, 4)
 */
rename from src/strfns.cc
rename to libinterp/corefcn/strfns.cc
--- a/src/strfns.cc
+++ b/libinterp/corefcn/strfns.cc
@@ -64,13 +64,13 @@
 @example\n\
 @group\n\
 char ([97, 98, 99], \"\", @{\"98\", \"99\", 100@}, \"str1\", [\"ha\", \"lf\"])\n\
-     @result{} [\"abc    \"\n\
-         \"       \"\n\
-         \"98     \"\n\
-         \"99     \"\n\
-         \"d      \"\n\
-         \"str1   \"\n\
-         \"half   \"]\n\
+   @result{} [\"abc    \"\n\
+       \"       \"\n\
+       \"98     \"\n\
+       \"99     \"\n\
+       \"d      \"\n\
+       \"str1   \"\n\
+       \"half   \"]\n\
 @end group\n\
 @end example\n\
 @seealso{strvcat, cellstr}\n\
@@ -152,23 +152,23 @@
 
 /*
 %!assert (char (), '');
-%!assert (char (100) == "d");
-%!assert (all(char (100,100) == ["d";"d"]));
-%!assert (all(char ({100,100}) == ["d";"d"]));
-%!assert (all(char ([100,100]) == ["dd"]));
-%!assert (all(char ({100,{100}}) == ["d";"d"]));
-%!assert (all(char (100, [], 100) == ["d";" ";"d"]))
-%!assert (all(char ({100, [], 100}) == ["d";" ";"d"]))
-%!assert (all(char ({100,{100, {""}}}) == ["d";"d";" "]))
-%!assert (all(char (["a";"be"], {"c", 100}) == ["a";"be";"c";"d"]))
-%!assert(strcmp (char ("a", "bb", "ccc"), ["a  "; "bb "; "ccc"]));
-%!assert(strcmp (char ([65, 83, 67, 73, 73]), "ASCII"));
+%!assert (char (100), "d");
+%!assert (char (100,100), ["d";"d"])
+%!assert (char ({100,100}), ["d";"d"])
+%!assert (char ([100,100]), ["dd"])
+%!assert (char ({100,{100}}), ["d";"d"])
+%!assert (char (100, [], 100), ["d";" ";"d"])
+%!assert (char ({100, [], 100}), ["d";" ";"d"])
+%!assert (char ({100,{100, {""}}}), ["d";"d";" "])
+%!assert (char (["a";"be"], {"c", 100}), ["a";"be";"c";"d"])
+%!assert (char ("a", "bb", "ccc"), ["a  "; "bb "; "ccc"])
+%!assert (char ([65, 83, 67, 73, 73]), "ASCII")
 
 %!test
 %! x = char ("foo", "bar", "foobar");
-%! assert((strcmp (x(1,:), "foo   ")
-%! && strcmp (x(2,:), "bar   ")
-%! && strcmp (x(3,:), "foobar")));
+%! assert (x(1,:), "foo   ");
+%! assert (x(2,:), "bar   ");
+%! assert (x(3,:), "foobar");
 */
 
 DEFUN (strvcat, args, ,
@@ -195,12 +195,12 @@
 @example\n\
 @group\n\
 strvcat ([97, 98, 99], \"\", @{\"98\", \"99\", 100@}, \"str1\", [\"ha\", \"lf\"])\n\
-     @result{} [\"abc    \"\n\
-         \"98     \"\n\
-         \"99     \"\n\
-         \"d      \"\n\
-         \"str1   \"\n\
-         \"half   \"]\n\
+      @result{} [\"abc    \"\n\
+          \"98     \"\n\
+          \"99     \"\n\
+          \"d      \"\n\
+          \"str1   \"\n\
+          \"half   \"]\n\
 @end group\n\
 @end example\n\
 @seealso{char, strcat, cstrcat}\n\
@@ -286,18 +286,19 @@
 }
 
 /*
-%!error <Invalid call to strvcat> strvcat()
 %!assert (strvcat (""), "");
 %!assert (strvcat (100) == "d");
-%!assert (all(strvcat (100,100) == ["d";"d"]));
-%!assert (all(strvcat ({100,100}) == ["d";"d"]));
-%!assert (all(strvcat ([100,100]) == ["dd"]));
-%!assert (all(strvcat ({100,{100}}) == ["d";"d"]));
-%!assert (all(strvcat (100, [], 100) == ["d";"d"]))
-%!assert (all(strvcat ({100, [], 100}) == ["d";"d"]))
-%!assert (all(strvcat ({100,{100, {""}}}) == ["d";"d"]))
-%!assert (all(strvcat (["a";"be"], {"c", 100}) == ["a";"be";"c";"d"]))
-%!assert(strcmp (strvcat ("a", "bb", "ccc"), ["a  "; "bb "; "ccc"]));
+%!assert (strvcat (100,100), ["d";"d"])
+%!assert (strvcat ({100,100}), ["d";"d"])
+%!assert (strvcat ([100,100]), ["dd"])
+%!assert (strvcat ({100,{100}}), ["d";"d"])
+%!assert (strvcat (100, [], 100), ["d";"d"])
+%!assert (strvcat ({100, [], 100}), ["d";"d"])
+%!assert (strvcat ({100,{100, {""}}}), ["d";"d"])
+%!assert (strvcat (["a";"be"], {"c", 100}), ["a";"be";"c";"d"])
+%!assert (strvcat ("a", "bb", "ccc"), ["a  "; "bb "; "ccc"])
+
+%!error strvcat ()
 */
 
 
@@ -321,19 +322,20 @@
 }
 
 /*
-%!assert (ischar ("a"), logical (1));
-%!assert (ischar (["ab";"cd"]), logical (1));
-%!assert (ischar ({"ab"}), logical (0));
-%!assert (ischar (1), logical (0));
-%!assert(ischar ([1, 2]), logical (0));
-%!assert(ischar ([]), logical (0));
-%!assert(ischar ([1, 2; 3, 4]), logical (0));
-%!assert(ischar (""), logical (1));
-%!assert(ischar ("test"), logical (1));
-%!assert(ischar (["test"; "ing"]), logical (1));
-%!assert(ischar (struct ("foo", "bar")), logical (0));
-%!error <Invalid call to ischar> ischar ();
-%!error <Invalid call to ischar> ischar ("test", 1);
+%!assert (ischar ("a"), true)
+%!assert (ischar (["ab";"cd"]), true)
+%!assert (ischar ({"ab"}), false)
+%!assert (ischar (1), false)
+%!assert (ischar ([1, 2]), false)
+%!assert (ischar ([]), false)
+%!assert (ischar ([1, 2; 3, 4]), false)
+%!assert (ischar (""), true)
+%!assert (ischar ("test"), true)
+%!assert (ischar (["test"; "ing"]), true)
+%!assert (ischar (struct ("foo", "bar")), false)
+
+%!error ischar ()
+%!error ischar ("test", 1)
 */
 
 static octave_value
@@ -589,51 +591,51 @@
 }
 
 /*
-%!error <Invalid call to strcmp> strcmp ();
-%!error <Invalid call to strcmp> strcmp ("foo", "bar", 3);
-%!
 %!shared x
-%!  x = char (zeros (0, 2));
-%!assert (strcmp ('', x) == false);
-%!assert (strcmp (x, '') == false);
-%!assert (strcmp (x, x) == true);
-## %!assert (strcmp ({''}, x) == true);
-## %!assert (strcmp ({x}, '') == false);
-## %!assert (strcmp ({x}, x) == true);
-## %!assert (strcmp ('', {x}) == false);
-## %!assert (strcmp (x, {''}) == false);
-## %!assert (strcmp (x, {x}) == true);
-## %!assert (all (strcmp ({x; x}, '') == [false; false]));
-## %!assert (all (strcmp ({x; x}, {''}) == [false; false]));
-## %!assert (all (strcmp ('', {x; x}) == [false; false]));
-## %!assert (all (strcmp ({''}, {x; x}) == [false; false]));
-%!assert (strcmp ({'foo'}, x) == false);
-%!assert (strcmp ({'foo'}, 'foo') == true);
-%!assert (strcmp ({'foo'}, x) == false);
-%!assert (strcmp (x, {'foo'}) == false);
-%!assert (strcmp ('foo', {'foo'}) == true);
-%!assert (strcmp (x, {'foo'}) == false);
+%! x = char (zeros (0, 2));
+%!assert (strcmp ("", x), false)
+%!assert (strcmp (x, ""), false)
+%!assert (strcmp (x, x), true)
+## %!assert (strcmp ({""}, x), true)
+## %!assert (strcmp ({x}, ""), false)
+## %!assert (strcmp ({x}, x), true)
+## %!assert (strcmp ("", {x}), false)
+## %!assert (strcmp (x, {""}), false)
+## %!assert (strcmp (x, {x}), true)
+## %!assert (strcmp ({x; x}, ""), [false; false])
+## %!assert (strcmp ({x; x}, {""}), [false; false])
+## %!assert (strcmp ("", {x; x}), [false; false])
+## %!assert (strcmp ({""}, {x; x}), [false; false])
+%!assert (strcmp ({"foo"}, x), false)
+%!assert (strcmp ({"foo"}, "foo"), true)
+%!assert (strcmp ({"foo"}, x), false)
+%!assert (strcmp (x, {"foo"}), false)
+%!assert (strcmp ("foo", {"foo"}), true)
+%!assert (strcmp (x, {"foo"}), false)
 %!shared y
-%!  y = char (zeros (2, 0));
-%!assert (strcmp ('', y) == false);
-%!assert (strcmp (y, '') == false);
-%!assert (strcmp (y, y) == true);
-%!assert (all (strcmp ({''}, y) == [true; true]));
-%!assert (strcmp ({y}, '') == true);
-%!assert (all (strcmp ({y}, y) == [true; true]));
-%!assert (all (strcmp ('', {y}) == [true; true]));
-%!assert (all (strcmp (y, {''}) == [true; true]));
-%!assert (all (strcmp (y, {y}) == [true; true]));
-%!assert (all (strcmp ({y; y}, '') == [true; true]));
-%!assert (all (strcmp ({y; y}, {''}) == [true; true]));
-%!assert (all (strcmp ('', {y; y}) == [true; true]));
-%!assert (all (strcmp ({''}, {y; y}) == [true; true]));
-%!assert (all (strcmp ({'foo'}, y) == [false; false]));
-%!assert (all (strcmp ({'foo'}, y) == [false; false]));
-%!assert (all (strcmp (y, {'foo'}) == [false; false]));
-%!assert (all (strcmp (y, {'foo'}) == [false; false]));
-%!assert (strcmp ("foobar", "foobar"), true);
-%!assert (strcmp ("fooba", "foobar"), false);
+%! y = char (zeros (2, 0));
+%!assert (strcmp ("", y), false)
+%!assert (strcmp (y, ""), false)
+%!assert (strcmp (y, y), true)
+%!assert (strcmp ({""}, y), [true; true])
+%!assert (strcmp ({y}, ""), true)
+%!assert (strcmp ({y}, y), [true; true])
+%!assert (strcmp ("", {y}), true)
+%!assert (strcmp (y, {""}), [true; true])
+%!assert (strcmp (y, {y}), [true; true])
+%!assert (strcmp ({y; y}, ""), [true; true])
+%!assert (strcmp ({y; y}, {""}), [true; true])
+%!assert (strcmp ("", {y; y}), [true; true])
+%!assert (strcmp ({""}, {y; y}), [true; true])
+%!assert (strcmp ({"foo"}, y), [false; false])
+%!assert (strcmp ({"foo"}, y), [false; false])
+%!assert (strcmp (y, {"foo"}), [false; false])
+%!assert (strcmp (y, {"foo"}), [false; false])
+%!assert (strcmp ("foobar", "foobar"), true)
+%!assert (strcmp ("fooba", "foobar"), false)
+
+%!error strcmp ()
+%!error strcmp ("foo", "bar", 3)
 */
 
 // Apparently, Matlab ignores the dims with strncmp. It also
@@ -665,7 +667,7 @@
 @example\n\
 @group\n\
 strncmp (\"abce\", \"abcd\", 3)\n\
-     @result{} 1\n\
+      @result{} 1\n\
 @end group\n\
 @end example\n\
 \n\
@@ -712,15 +714,16 @@
 }
 
 /*
-%!error <Invalid call to strncmp> strncmp ();
-%!error <Invalid call to strncmp> strncmp ("abc", "def");
-%!assert (strncmp ("abce", "abc", 3) == 1)
-%!assert (strncmp (100, 100, 1) == 0)
-%!assert (all (strncmp ("abce", {"abcd", "bca", "abc"}, 3) == [1, 0, 1]))
-%!assert (all (strncmp ("abc",  {"abcd", "bca", "abc"}, 4) == [0, 0, 0]))
-%!assert (all (strncmp ({"abcd", "bca", "abc"},"abce", 3) == [1, 0, 1]))
-%!assert (all (strncmp ({"abcd", "bca", "abc"},{"abcd", "bca", "abe"}, 3) == [1, 1, 0]))
-%!assert (all (strncmp("abc", {"abcd", 10}, 2) == [1, 0]))
+%!assert (strncmp ("abce", "abc", 3), true)
+%!assert (strncmp (100, 100, 1), false)
+%!assert (strncmp ("abce", {"abcd", "bca", "abc"}, 3), logical ([1, 0, 1]))
+%!assert (strncmp ("abc",  {"abcd", "bca", "abc"}, 4), logical ([0, 0, 0]))
+%!assert (strncmp ({"abcd", "bca", "abc"},"abce", 3), logical ([1, 0, 1]))
+%!assert (strncmp ({"abcd", "bca", "abc"},{"abcd", "bca", "abe"}, 3), logical ([1, 1, 0]))
+%!assert (strncmp ("abc", {"abcd", 10}, 2), logical ([1, 0]))
+
+%!error strncmp ()
+%!error strncmp ("abc", "def")
 */
 
 // case-insensitive character equality functor
@@ -783,7 +786,7 @@
 }
 
 /*
-%!assert (strcmpi("abc123", "ABC123"), logical(1));
+%!assert (strcmpi ("abc123", "ABC123"), true)
 */
 
 // Like strncmp.
@@ -850,16 +853,18 @@
 }
 
 /*
-%!assert (strncmpi("abc123", "ABC456", 3), logical(1));
+%!assert (strncmpi ("abc123", "ABC456", 3), true)
 */
 
 DEFUN (list_in_columns, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {} list_in_columns (@var{arg}, @var{width})\n\
+@deftypefn {Built-in Function} {} list_in_columns (@var{arg}, @var{width}, @var{prefix})\n\
 Return a string containing the elements of @var{arg} listed in\n\
-columns with an overall maximum width of @var{width}.  The argument\n\
-@var{arg} must be a cell array of character strings or a character array.\n\
-If @var{width} is not specified, the width of the terminal screen is used.\n\
+columns with an overall maximum width of @var{width} and optional\n\
+prefix @var{prefix}.  The argument @var{arg} must be a cell array\n\
+of character strings or a character array.  If @var{width} is not\n\
+specified or is an empty matrix, or less than or equal to zero,\n\
+the width of the terminal screen is used.\n\
 Newline characters are used to break the lines in the output string.\n\
 For example:\n\
 @c Set example in small font to prevent overfull line\n\
@@ -867,9 +872,9 @@
 @smallexample\n\
 @group\n\
 list_in_columns (@{\"abc\", \"def\", \"ghijkl\", \"mnop\", \"qrs\", \"tuv\"@}, 20)\n\
-     @result{} ans = abc     mnop\n\
-            def     qrs\n\
-            ghijkl  tuv\n\
+     @result{} abc     mnop\n\
+        def     qrs\n\
+        ghijkl  tuv\n\
 \n\
 whos ans\n\
      @result{}\n\
@@ -890,48 +895,79 @@
 
   int nargin = args.length ();
 
-  if (nargin == 1 || nargin == 2)
+  if (nargin < 1 || nargin > 3)
     {
-      string_vector s = args(0).all_strings ();
+      print_usage ();
+      return retval;
+    }
+
+  string_vector s = args(0).all_strings ();
 
-      if (! error_state)
-        {
-          std::ostringstream buf;
+  if (error_state)
+    {
+      error ("list_in_columns: expecting cellstr or char array");
+      return retval;
+    }
+
+  int width = -1;
+
+  if (nargin > 1 && ! args(1).is_empty ())
+    {
+      width = args(1).int_value ();
 
-          if (nargin == 1)
-            // Let list_in_columns query terminal width.
-            s.list_in_columns (buf);
-          else
-            {
-              int width = args(1).int_value ();
+      if (error_state)
+        {
+          error ("list_in_columns: WIDTH must be an integer");
+          return retval;
+        }
+    }
+                
+  std::string prefix;
 
-              if (! error_state)
-                s.list_in_columns (buf, width);
-              else
-                error ("list_in_columns: WIDTH must be an integer");
+  if (nargin > 2)
+    {
+      if (args(2).is_string ())
+        {
+          prefix = args(2).string_value ();
+
+          if (error_state)
+            {
+              error ("list_in_columns: PREFIX must be a character string");
+              return retval;
             }
-
-          retval = buf.str ();
         }
       else
-        error ("list_in_columns: expecting cellstr or char array");
+        {
+          error ("list_in_columns: PREFIX must be a character string");
+          return retval;
+        }
     }
-  else
-    print_usage ();
+
+  std::ostringstream buf;
+
+  s.list_in_columns (buf, width, prefix);
+
+  retval = buf.str ();
 
   return retval;
 }
 
 /*
-%!error <Invalid call to list_in_columns> list_in_columns ();
-%!error <Invalid call to list_in_columns> list_in_columns (["abc", "def"], 20, 2);
-%!error <invalid conversion from string to real scalar> list_in_columns (["abc", "def"], "a");
+%!test
+%! input  = {"abc", "def", "ghijkl", "mnop", "qrs", "tuv"};
+%! result = "abc     mnop\ndef     qrs\nghijkl  tuv\n";
+%! assert (list_in_columns (input, 20), result);
+%!test
+%! input  = ["abc"; "def"; "ghijkl"; "mnop"; "qrs"; "tuv"];
+%! result = "abc     mnop  \ndef     qrs   \nghijkl  tuv   \n";
+%! assert (list_in_columns (input, 20), result);
 %!test
-%!  input  = {"abc", "def", "ghijkl", "mnop", "qrs", "tuv"};
-%!  result = "abc     mnop\ndef     qrs\nghijkl  tuv\n";
-%!  assert (list_in_columns (input, 20) == result);
-%!test
-%!  input  = ["abc"; "def"; "ghijkl"; "mnop"; "qrs"; "tuv"];
-%!  result = "abc     mnop  \ndef     qrs   \nghijkl  tuv   \n";
-%!  assert (list_in_columns (input, 20) == result);
+%! input  = ["abc"; "def"; "ghijkl"; "mnop"; "qrs"; "tuv"];
+%! result = "  abc     mnop  \n  def     qrs   \n  ghijkl  tuv   \n";
+%! assert (list_in_columns (input, 20, "  "), result);
+
+%!error list_in_columns ()
+%!error list_in_columns (["abc", "def"], 20, 2)
+%!error list_in_columns (["abc", "def"], 20, "  ", 3)
+%!error <invalid conversion from string to real scalar> list_in_columns (["abc", "def"], "a")
 */
rename from src/DLD-FUNCTIONS/sub2ind.cc
rename to libinterp/corefcn/sub2ind.cc
--- a/src/DLD-FUNCTIONS/sub2ind.cc
+++ b/libinterp/corefcn/sub2ind.cc
@@ -26,7 +26,7 @@
 
 #include "quit.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -61,7 +61,7 @@
   return dv;
 }
 
-DEFUN_DLD (sub2ind, args, ,
+DEFUN (sub2ind, args, ,
   "-*- texinfo -*-\n\
 @deftypefn  {Function File} {@var{ind} =} sub2ind (@var{dims}, @var{i}, @var{j})\n\
 @deftypefnx {Function File} {@var{ind} =} sub2ind (@var{dims}, @var{s1}, @var{s2}, @dots{}, @var{sN})\n\
@@ -123,54 +123,51 @@
 }
 
 /*
-
-# Test input validation
-%!error <sub2ind: dimension vector > sub2ind([10 10.5], 1, 1);
-%!error <subscript indices > sub2ind([10 10], 1.5, 1);
-%!error <subscript indices > sub2ind([10 10], 1, 1.5);
-
-# Test evaluation
-%!shared s1, s2, s3, in
-%! s1 = [   1   1   1   1 ;   2   2   2   2 ];
-%! s2 = [   1   1   2   2 ;   1   1   2   2 ];
-%! s3 = [   1   2   1   2 ;   1   2   1   2 ];
-%! in = [   1 101  11 111 ;   2 102  12 112 ];
-%!assert (sub2ind([10 10 10], s1, s2, s3), in);
-%!shared
+## Test evaluation
+%!test
+%! s1 = [ 1   1   1   1 ; 2   2   2   2 ];
+%! s2 = [ 1   1   2   2 ; 1   1   2   2 ];
+%! s3 = [ 1   2   1   2 ; 1   2   1   2 ];
+%! in = [ 1 101  11 111 ; 2 102  12 112 ];
+%! assert (sub2ind ([10 10 10], s1, s2, s3), in);
 
 # Test low index
-%!assert (sub2ind([10 10 10], 1, 1, 1), 1);
-%!error <subscript indices > sub2ind([10 10 10], 0, 1, 1);
-%!error <subscript indices > sub2ind([10 10 10], 1, 0, 1);
-%!error <subscript indices > sub2ind([10 10 10], 1, 1, 0);
+%!assert (sub2ind ([10 10 10], 1, 1, 1), 1)
+%!error <subscript indices> sub2ind ([10 10 10], 0, 1, 1)
+%!error <subscript indices> sub2ind ([10 10 10], 1, 0, 1)
+%!error <subscript indices> sub2ind ([10 10 10], 1, 1, 0)
 
 # Test high index
-%!assert (sub2ind([10 10 10], 10, 10, 10), 1000);
-%!error <sub2ind: index out of range> sub2ind([10 10 10], 11, 10, 10);
-%!error <sub2ind: index out of range> sub2ind([10 10 10], 10, 11, 10);
-%!error <sub2ind: index out of range> sub2ind([10 10 10], 10, 10, 11);
+%!assert (sub2ind ([10 10 10], 10, 10, 10), 1000)
+%!error <index out of range> sub2ind ([10 10 10], 11, 10, 10)
+%!error <index out of range> sub2ind ([10 10 10], 10, 11, 10)
+%!error <index out of range> sub2ind ([10 10 10], 10, 10, 11)
 
 # Test high index in the trailing dimensions
-%!assert (sub2ind([10, 1], 2, 1, 1), 2);
-%!error <sub2ind: index out of range> sub2ind([10, 1], 1, 2, 1);
-%!error <sub2ind: index out of range> sub2ind([10, 1], 1, 1, 2);
-%!assert (sub2ind([10 10], 2, 2, 1), 12);
-%!error <sub2ind: index out of range> sub2ind([10 10], 2, 1, 2);
-%!error <sub2ind: index out of range> sub2ind([10 10], 1, 2, 2);
+%!assert (sub2ind ([10, 1], 2, 1, 1), 2)
+%!error <index out of range> sub2ind ([10, 1], 1, 2, 1)
+%!error <index out of range> sub2ind ([10, 1], 1, 1, 2)
+%!assert (sub2ind ([10 10], 2, 2, 1), 12)
+%!error <index out of range> sub2ind ([10 10], 2, 1, 2)
+%!error <index out of range> sub2ind ([10 10], 1, 2, 2)
 
 # Test handling of empty arguments
-%!assert (sub2ind([10 10], zeros(0,0), zeros(0,0)), zeros(0,0));
-%!assert (sub2ind([10 10], zeros(2,0), zeros(2,0)), zeros(2,0));
-%!assert (sub2ind([10 10], zeros(0,2), zeros(0,2)), zeros(0,2));
-%!error <sub2ind: all subscripts .* same size> sub2ind([10 10 10], zeros(0,2), zeros(2,0));
+%!assert (sub2ind ([10 10], zeros (0,0), zeros (0,0)), zeros (0,0))
+%!assert (sub2ind ([10 10], zeros (2,0), zeros (2,0)), zeros (2,0))
+%!assert (sub2ind ([10 10], zeros (0,2), zeros (0,2)), zeros (0,2))
+%!error <all subscripts .* same size> sub2ind ([10 10 10], zeros (0,2), zeros (2,0))
 
 # Test handling of arguments of different size
-%!error <sub2ind: all subscripts .* same size> sub2ind([10 10], ones(1,2), ones(1,3));
-%!error <sub2ind: all subscripts .* same size> sub2ind([10 10], ones(1,2), ones(2,1));
+%!error <all subscripts .* same size> sub2ind ([10 10], ones (1,2), ones (1,3))
+%!error <all subscripts .* same size> sub2ind ([10 10], ones (1,2), ones (2,1))
 
+## Test input validation
+%!error <dimension vector> sub2ind ([10 10.5], 1, 1)
+%!error <subscript indices> sub2ind ([10 10], 1.5, 1)
+%!error <subscript indices> sub2ind ([10 10], 1, 1.5)
 */
 
-DEFUN_DLD (ind2sub, args, nargout,
+DEFUN (ind2sub, args, nargout,
   "-*- texinfo -*-\n\
 @deftypefn {Function File} {[@var{s1}, @var{s2}, @dots{}, @var{sN}] =} ind2sub (@var{dims}, @var{ind})\n\
 Convert a linear index to subscripts.\n\
@@ -182,8 +179,8 @@
 @example\n\
 @group\n\
 [r, c] = ind2sub ([3, 3], 8)\n\
-@result{} r =  2\n\
-   c =  3\n\
+    @result{} r =  2\n\
+    @result{} c =  3\n\
 @end group\n\
 @end example\n\
 @seealso{sub2ind}\n\
rename from src/DLD-FUNCTIONS/svd.cc
rename to libinterp/corefcn/svd.cc
--- a/src/DLD-FUNCTIONS/svd.cc
+++ b/libinterp/corefcn/svd.cc
@@ -29,7 +29,7 @@
 #include "fCmplxSVD.h"
 #include "floatSVD.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -39,11 +39,11 @@
 
 static int Vsvd_driver = SVD::GESVD;
 
-DEFUN_DLD (svd, args, nargout,
+DEFUN (svd, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{s} =} svd (@var{A})\n\
-@deftypefnx {Loadable Function} {[@var{U}, @var{S}, @var{V}] =} svd (@var{A})\n\
-@deftypefnx {Loadable Function} {[@var{U}, @var{S}, @var{V}] =} svd (@var{A}, @var{econ})\n\
+@deftypefn  {Built-in Function} {@var{s} =} svd (@var{A})\n\
+@deftypefnx {Built-in Function} {[@var{U}, @var{S}, @var{V}] =} svd (@var{A})\n\
+@deftypefnx {Built-in Function} {[@var{U}, @var{S}, @var{V}] =} svd (@var{A}, @var{econ})\n\
 @cindex singular value decomposition\n\
 Compute the singular value decomposition of @var{A}\n\
 @tex\n\
@@ -216,7 +216,7 @@
 
                   if (nargout == 0 || nargout == 1)
                     {
-                      retval(0) = sigma.diag ();
+                      retval(0) = sigma.extract_diag ();
                     }
                   else
                     {
@@ -244,7 +244,7 @@
 
                   if (nargout == 0 || nargout == 1)
                     {
-                      retval(0) = sigma.diag ();
+                      retval(0) = sigma.extract_diag ();
                     }
                   else
                     {
@@ -275,7 +275,7 @@
 
                   if (nargout == 0 || nargout == 1)
                     {
-                      retval(0) = sigma.diag ();
+                      retval(0) = sigma.extract_diag ();
                     }
                   else
                     {
@@ -303,7 +303,7 @@
 
                   if (nargout == 0 || nargout == 1)
                     {
-                      retval(0) = sigma.diag ();
+                      retval(0) = sigma.extract_diag ();
                     }
                   else
                     {
@@ -325,8 +325,7 @@
 }
 
 /*
-
-%!assert(svd ([1, 2; 2, 1]), [3; 1], sqrt (eps));
+%!assert (svd ([1, 2; 2, 1]), [3; 1], sqrt (eps))
 
 %!test
 %! [u, s, v] = svd ([1, 2; 2, 1]);
@@ -355,34 +354,34 @@
 %! [u, s, v] = svd (a, 1);
 %! assert (u * s * v', a, sqrt (eps));
 
-%!assert(svd (single([1, 2; 2, 1])), single([3; 1]), sqrt (eps('single')));
+%!assert (svd (single ([1, 2; 2, 1])), single ([3; 1]), sqrt (eps ("single")))
 
 %!test
-%! [u, s, v] = svd (single([1, 2; 2, 1]));
+%! [u, s, v] = svd (single ([1, 2; 2, 1]));
 %! x = single (1 / sqrt (2));
-%! assert (u, [-x, -x; -x, x], sqrt (eps('single')));
-%! assert (s, single([3, 0; 0, 1]), sqrt (eps('single')));
-%! assert (v, [-x, x; -x, -x], sqrt (eps('single')));
+%! assert (u, [-x, -x; -x, x], sqrt (eps ("single")));
+%! assert (s, single ([3, 0; 0, 1]), sqrt (eps ("single")));
+%! assert (v, [-x, x; -x, -x], sqrt (eps ("single")));
 
 %!test
-%! a = single([1, 2, 3; 4, 5, 6]);
+%! a = single ([1, 2, 3; 4, 5, 6]);
 %! [u, s, v] = svd (a);
-%! assert (u * s * v', a, sqrt (eps('single')));
+%! assert (u * s * v', a, sqrt (eps ("single")));
 
 %!test
-%! a = single([1, 2; 3, 4; 5, 6]);
+%! a = single ([1, 2; 3, 4; 5, 6]);
 %! [u, s, v] = svd (a);
-%! assert (u * s * v', a, sqrt (eps('single')));
+%! assert (u * s * v', a, sqrt (eps ("single")));
 
 %!test
-%! a = single([1, 2, 3; 4, 5, 6]);
+%! a = single ([1, 2, 3; 4, 5, 6]);
 %! [u, s, v] = svd (a, 1);
-%! assert (u * s * v', a, sqrt (eps('single')));
+%! assert (u * s * v', a, sqrt (eps ("single")));
 
 %!test
-%! a = single([1, 2; 3, 4; 5, 6]);
+%! a = single ([1, 2; 3, 4; 5, 6]);
 %! [u, s, v] = svd (a, 1);
-%! assert (u * s * v', a, sqrt (eps('single')));
+%! assert (u * s * v', a, sqrt (eps ("single")));
 
 %!test
 %! a = zeros (0, 5);
@@ -398,17 +397,16 @@
 %! assert (size (s), [0, 0]);
 %! assert (size (v), [0, 0]);
 
-%!error <Invalid call to svd> svd ();
-%!error <Invalid call to svd> svd ([1, 2; 4, 5], 2, 3);
-%!error <Invalid call to svd> [u, v] = svd ([1, 2; 3, 4]);
-
+%!error svd ()
+%!error svd ([1, 2; 4, 5], 2, 3)
+%!error [u, v] = svd ([1, 2; 3, 4])
 */
 
-DEFUN_DLD (svd_driver, args, nargout,
+DEFUN (svd_driver, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{val} =} svd_driver ()\n\
-@deftypefnx {Loadable Function} {@var{old_val} =} svd_driver (@var{new_val})\n\
-@deftypefnx {Loadable Function} {} svd_driver (@var{new_val}, \"local\")\n\
+@deftypefn  {Built-in Function} {@var{val} =} svd_driver ()\n\
+@deftypefnx {Built-in Function} {@var{old_val} =} svd_driver (@var{new_val})\n\
+@deftypefnx {Built-in Function} {} svd_driver (@var{new_val}, \"local\")\n\
 Query or set the underlying @sc{lapack} driver used by @code{svd}.\n\
 Currently recognized values are \"gesvd\" and \"gesdd\".  The default\n\
 is \"gesvd\".\n\
rename from src/DLD-FUNCTIONS/syl.cc
rename to libinterp/corefcn/syl.cc
--- a/src/DLD-FUNCTIONS/syl.cc
+++ b/libinterp/corefcn/syl.cc
@@ -26,15 +26,15 @@
 #include <config.h>
 #endif
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
 #include "utils.h"
 
-DEFUN_DLD (syl, args, nargout,
+DEFUN (syl, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{x} =} syl (@var{A}, @var{B}, @var{C})\n\
+@deftypefn {Built-in Function} {@var{x} =} syl (@var{A}, @var{B}, @var{C})\n\
 Solve the Sylvester equation\n\
 @tex\n\
 $$\n\
@@ -53,7 +53,7 @@
 @example\n\
 @group\n\
 syl ([1, 2; 3, 4], [5, 6; 7, 8], [9, 10; 11, 12])\n\
-     @result{} [ -0.50000, -0.66667; -0.66667, -0.50000 ]\n\
+   @result{} [ -0.50000, -0.66667; -0.66667, -0.50000 ]\n\
 @end group\n\
 @end example\n\
 @end deftypefn")
@@ -209,12 +209,10 @@
 }
 
 /*
-
-%!assert(syl ([1, 2; 3, 4], [5, 6; 7, 8], [9, 10; 11, 12]), [-1/2, -2/3; -2/3, -1/2], sqrt (eps));
-%!assert(syl (single([1, 2; 3, 4]), single([5, 6; 7, 8]), single([9, 10; 11, 12])), single([-1/2, -2/3; -2/3, -1/2]), sqrt (eps('single')));
+%!assert (syl ([1, 2; 3, 4], [5, 6; 7, 8], [9, 10; 11, 12]), [-1/2, -2/3; -2/3, -1/2], sqrt (eps))
+%!assert (syl (single ([1, 2; 3, 4]), single ([5, 6; 7, 8]), single ([9, 10; 11, 12])), single ([-1/2, -2/3; -2/3, -1/2]), sqrt (eps ("single")))
 
-%!error <Invalid call to syl> syl ();
-%!error <Invalid call to syl> syl (1, 2, 3, 4);
-%!error syl ([1, 2; 3, 4], [1, 2, 3; 4, 5, 6], [4, 3]);
-
+%!error syl ()
+%!error syl (1, 2, 3, 4)
+%!error <must be a square matrix> syl ([1, 2; 3, 4], [1, 2, 3; 4, 5, 6], [4, 3])
 */
rename from src/syscalls.cc
rename to libinterp/corefcn/syscalls.cc
--- a/src/syscalls.cc
+++ b/libinterp/corefcn/syscalls.cc
@@ -269,10 +269,11 @@
 until (done)\n\
 fclose (out);\n\
 waitpid (pid);\n\
-     @print{} these\n\
-     @print{} strings\n\
-     @print{} some\n\
-     @print{} are\n\
+\n\
+   @print{} these\n\
+   @print{} strings\n\
+   @print{} some\n\
+   @print{} are\n\
 @end example\n\
 \n\
 Note that @code{popen2}, unlike @code{popen}, will not \"reap\" the\n\
@@ -290,7 +291,7 @@
 
   if (nargin >= 1 && nargin <= 3)
     {
-      std::string exec_file = args(0).string_value();
+      std::string exec_file = args(0).string_value ();
 
       if (! error_state)
         {
@@ -323,7 +324,7 @@
 
           if (! error_state)
             {
-              bool sync_mode = (nargin == 3 ? args(2).bool_value() : false);
+              bool sync_mode = (nargin == 3 ? args(2).bool_value () : false);
 
               if (! error_state)
                 {
@@ -368,46 +369,44 @@
 }
 
 /*
-
 %!test
-%!  if (isunix())
-%!    [in, out, pid] = popen2 ("sort", "-r");
-%!    EAGAIN = errno ("EAGAIN");
-%!  else
-%!    [in, out, pid] = popen2 ("sort", "/R");
-%!    EAGAIN = errno ("EINVAL");
-%!  endif
-%!  fputs (in, "these\nare\nsome\nstrings\n");
-%!  fclose (in);
-%!  done = false;
-%!  str = {};
-%!  idx = 0;
-%!  errs = 0;
-%!  do
-%!     if (!isunix())
-%!       errno (0);
-%!     endif
-%!     s = fgets (out);
-%!     if (ischar (s))
-%!       idx++;
-%!       str{idx} = s;
-%!     elseif (errno () == EAGAIN)
-%!       fclear (out);
-%!       sleep (0.1);
-%!       if (++errs == 100)
-%!         done = true;
-%!       endif
-%!     else
+%! if (isunix ())
+%!   [in, out, pid] = popen2 ("sort", "-r");
+%!   EAGAIN = errno ("EAGAIN");
+%! else
+%!   [in, out, pid] = popen2 ("sort", "/R");
+%!   EAGAIN = errno ("EINVAL");
+%! endif
+%! fputs (in, "these\nare\nsome\nstrings\n");
+%! fclose (in);
+%! done = false;
+%! str = {};
+%! idx = 0;
+%! errs = 0;
+%! do
+%!   if (!isunix ())
+%!     errno (0);
+%!   endif
+%!   s = fgets (out);
+%!   if (ischar (s))
+%!     idx++;
+%!     str{idx} = s;
+%!   elseif (errno () == EAGAIN)
+%!     fclear (out);
+%!     sleep (0.1);
+%!     if (++errs == 100)
 %!       done = true;
 %!     endif
-%!  until (done)
-%!  fclose (out);
-%!  if (isunix())
-%!    assert(str,{"these\n","strings\n","some\n","are\n"})
-%!  else
-%!    assert(str,{"these\r\n","strings\r\n","some\r\n","are\r\n"})
-%!  end
-
+%!   else
+%!     done = true;
+%!   endif
+%! until (done)
+%! fclose (out);
+%! if (isunix ())
+%!   assert (str, {"these\n","strings\n","some\n","are\n"});
+%! else
+%!   assert (str, {"these\r\n","strings\r\n","some\r\n","are\r\n"});
+%! endif
 */
 
 DEFUNX ("fcntl", Ffcntl, args, ,
@@ -937,7 +936,7 @@
 @end table\n\
 \n\
 If the call is successful @var{err} is 0 and @var{msg} is an empty\n\
-string.  If the file does not exist, or some other error occurs, @var{s}\n\
+string.  If the file does not exist, or some other error occurs, @var{info}\n\
 is an empty matrix, @var{err} is @minus{}1, and @var{msg} contains the\n\
 corresponding system error message.\n\
 \n\
@@ -948,26 +947,26 @@
 For example:\n\
 \n\
 @example\n\
-[s, err, msg] = stat (\"/vmlinuz\")\n\
-      @result{} s =\n\
-        @{\n\
-          atime = 855399756\n\
-          rdev = 0\n\
-          ctime = 847219094\n\
-          uid = 0\n\
-          size = 389218\n\
-          blksize = 4096\n\
-          mtime = 847219094\n\
-          gid = 6\n\
-          nlink = 1\n\
-          blocks = 768\n\
-          mode = -rw-r--r--\n\
-          modestr = -rw-r--r--\n\
-          ino = 9316\n\
-          dev = 2049\n\
-        @}\n\
-     @result{} err = 0\n\
-     @result{} msg =\n\
+[info, err, msg] = stat (\"/vmlinuz\")\n\
+  @result{} info =\n\
+     @{\n\
+       atime = 855399756\n\
+       rdev = 0\n\
+       ctime = 847219094\n\
+       uid = 0\n\
+       size = 389218\n\
+       blksize = 4096\n\
+       mtime = 847219094\n\
+       gid = 6\n\
+       nlink = 1\n\
+       blocks = 768\n\
+       mode = -rw-r--r--\n\
+       modestr = -rw-r--r--\n\
+       ino = 9316\n\
+       dev = 2049\n\
+     @}\n\
+  @result{} err = 0\n\
+  @result{} msg =\n\
 @end example\n\
 @end deftypefn")
 {
@@ -1203,13 +1202,13 @@
 @example\n\
 @group\n\
 uname ()\n\
-     @result{} @{\n\
-           sysname = x86_64\n\
-           nodename = segfault\n\
-           release = 2.6.15-1-amd64-k8-smp\n\
-           version = Linux\n\
-           machine = #2 SMP Thu Feb 23 04:57:49 UTC 2006\n\
-         @}\n\
+   @result{} @{\n\
+         sysname = x86_64\n\
+         nodename = segfault\n\
+         release = 2.6.15-1-amd64-k8-smp\n\
+         version = Linux\n\
+         machine = #2 SMP Thu Feb 23 04:57:49 UTC 2006\n\
+      @}\n\
 @end group\n\
 @end example\n\
 \n\
@@ -1377,21 +1376,17 @@
 @seealso{waitpid, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WCOREDUMP, WIFSTOPPED, WSTOPSIG, WIFCONTINUED}\n\
 @end deftypefn")
 {
-  octave_value retval = 0.0;
+  octave_value retval = false;
 
-#if defined (WIFEXITED)
   if (args.length () == 1)
     {
       int status = args(0).int_value ();
 
       if (! error_state)
-        retval = WIFEXITED (status);
+        retval = octave_wait::ifexited (status);
       else
         error ("WIFEXITED: STATUS must be an integer");
     }
-#else
-  warning ("WIFEXITED always returns false in this version of Octave");
-#endif
 
   return retval;
 }
@@ -1405,21 +1400,17 @@
 @seealso{waitpid, WIFEXITED, WIFSIGNALED, WTERMSIG, WCOREDUMP, WIFSTOPPED, WSTOPSIG, WIFCONTINUED}\n\
 @end deftypefn")
 {
-  octave_value retval = 0.0;
+  octave_value retval = 0;
 
-#if defined (WEXITSTATUS)
   if (args.length () == 1)
     {
       int status = args(0).int_value ();
 
       if (! error_state)
-        retval = WEXITSTATUS (status);
+        retval = octave_wait::exitstatus (status);
       else
         error ("WEXITSTATUS: STATUS must be an integer");
     }
-#else
-  warning ("WEXITSTATUS always returns false in this version of Octave");
-#endif
 
   return retval;
 }
@@ -1432,21 +1423,17 @@
 @seealso{waitpid, WIFEXITED, WEXITSTATUS, WTERMSIG, WCOREDUMP, WIFSTOPPED, WSTOPSIG, WIFCONTINUED}\n\
 @end deftypefn")
 {
-  octave_value retval = 0.0;
+  octave_value retval = false;
 
-#if defined (WIFSIGNALED)
   if (args.length () == 1)
     {
       int status = args(0).int_value ();
 
       if (! error_state)
-        retval = WIFSIGNALED (status);
+        retval = octave_wait::ifsignaled (status);
       else
         error ("WIFSIGNALED: STATUS must be an integer");
     }
-#else
-  warning ("WIFSIGNALED always returns false in this version of Octave");
-#endif
 
   return retval;
 }
@@ -1460,21 +1447,17 @@
 @seealso{waitpid, WIFEXITED, WEXITSTATUS, WIFSIGNALED, WCOREDUMP, WIFSTOPPED, WSTOPSIG, WIFCONTINUED}\n\
 @end deftypefn")
 {
-  octave_value retval = 0.0;
+  octave_value retval = 0;
 
-#if defined (WTERMSIG)
   if (args.length () == 1)
     {
       int status = args(0).int_value ();
 
       if (! error_state)
-        retval = WTERMSIG (status);
+        retval = octave_wait::termsig (status);
       else
         error ("WTERMSIG: STATUS must be an integer");
     }
-#else
-  warning ("WTERMSIG always returns false in this version of Octave");
-#endif
 
   return retval;
 }
@@ -1490,21 +1473,17 @@
 @seealso{waitpid, WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WIFSTOPPED, WSTOPSIG, WIFCONTINUED}\n\
 @end deftypefn")
 {
-  octave_value retval = 0.0;
+  octave_value retval = false;
 
-#if defined (WCOREDUMP)
   if (args.length () == 1)
     {
       int status = args(0).int_value ();
 
       if (! error_state)
-        retval = WCOREDUMP (status);
+        retval = octave_wait::coredump (status);
       else
         error ("WCOREDUMP: STATUS must be an integer");
     }
-#else
-  warning ("WCOREDUMP always returns false in this version of Octave");
-#endif
 
   return retval;
 }
@@ -1519,21 +1498,17 @@
 @seealso{waitpid, WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WCOREDUMP, WSTOPSIG, WIFCONTINUED}\n\
 @end deftypefn")
 {
-  octave_value retval = 0.0;
+  octave_value retval = false;
 
-#if defined (WIFSTOPPED)
   if (args.length () == 1)
     {
       int status = args(0).int_value ();
 
       if (! error_state)
-        retval = WIFSTOPPED (status);
+        retval = octave_wait::ifstopped (status);
       else
         error ("WIFSTOPPED: STATUS must be an integer");
     }
-#else
-  warning ("WIFSTOPPED always returns false in this version of Octave");
-#endif
 
   return retval;
 }
@@ -1547,21 +1522,17 @@
 @seealso{waitpid, WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WCOREDUMP, WIFSTOPPED, WIFCONTINUED}\n\
 @end deftypefn")
 {
-  octave_value retval = 0.0;
+  octave_value retval = 0;
 
-#if defined (WSTOPSIG)
   if (args.length () == 1)
     {
       int status = args(0).int_value ();
 
       if (! error_state)
-        retval = WSTOPSIG (status);
+        retval = octave_wait::stopsig (status);
       else
         error ("WSTOPSIG: STATUS must be an integer");
     }
-#else
-  warning ("WSTOPSIG always returns false in this version of Octave");
-#endif
 
   return retval;
 }
@@ -1574,29 +1545,27 @@
 @seealso{waitpid, WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WCOREDUMP, WIFSTOPPED, WSTOPSIG}\n\
 @end deftypefn")
 {
-  octave_value retval = 0.0;
+  octave_value retval = false;
 
-#if defined (WIFCONTINUED)
   if (args.length () == 1)
     {
       int status = args(0).int_value ();
 
       if (! error_state)
-        retval = WIFCONTINUED (status);
+        retval = octave_wait::ifcontinued (status);
       else
         error ("WIFCONTINUED: STATUS must be an integer");
     }
-#else
-  warning ("WIFCONTINUED always returns false in this version of Octave");
-#endif
 
   return retval;
 }
 
 DEFUNX ("canonicalize_file_name", Fcanonicalize_file_name, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {[@var{cname}, @var{status}, @var{msg}]} canonicalize_file_name (@var{name})\n\
-Return the canonical name of file @var{name}.\n\
+@deftypefn {Built-in Function} {[@var{cname}, @var{status}, @var{msg}] =} canonicalize_file_name (@var{fname})\n\
+Return the canonical name of file @var{fname}.  If the file does not exist\n\
+the empty string (\"\") is returned.\n\
+@seealso{make_absolute_filename, is_absolute_filename, is_rooted_relative_filename}\n\
 @end deftypefn")
 {
   octave_value_list retval;
rename from src/DLD-FUNCTIONS/time.cc
rename to libinterp/corefcn/time.cc
--- a/src/DLD-FUNCTIONS/time.cc
+++ b/libinterp/corefcn/time.cc
@@ -26,7 +26,7 @@
 
 #include <string>
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "oct-map.h"
 #include "oct-time.h"
@@ -101,9 +101,9 @@
   return tm;
 }
 
-DEFUN_DLD (time, args, ,
+DEFUN (time, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{seconds} =} time ()\n\
+@deftypefn {Built-in Function} {@var{seconds} =} time ()\n\
 Return the current time as the number of seconds since the epoch.  The\n\
 epoch is referenced to 00:00:00 CUT (Coordinated Universal Time) 1 Jan\n\
 1970.  For example, on Monday February 17, 1997 at 07:15:06 CUT, the\n\
@@ -122,14 +122,12 @@
 }
 
 /*
-
-%!assert(time () > 0);
-
+%!assert (time () > 0)
 */
 
-DEFUN_DLD (gmtime, args, ,
+DEFUN (gmtime, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{tm_struct} =} gmtime (@var{t})\n\
+@deftypefn {Built-in Function} {@var{tm_struct} =} gmtime (@var{t})\n\
 Given a value returned from @code{time}, or any non-negative integer,\n\
 return a time structure corresponding to CUT (Coordinated Universal Time).\n\
 For example:\n\
@@ -149,7 +147,7 @@
            yday = 47\n\
            isdst = 0\n\
            zone = CST\n\
-         @}\n\
+        @}\n\
 @end group\n\
 @end example\n\
 @seealso{strftime, strptime, localtime, mktime, time, now, date, clock, datenum, datestr, datevec, calendar, weekday}\n\
@@ -171,30 +169,27 @@
 }
 
 /*
-
 %!test
 %! ts = gmtime (time ());
-%! assert((isstruct (ts)
-%! && isfield (ts, "usec")
-%! && isfield (ts, "year")
-%! && isfield (ts, "mon")
-%! && isfield (ts, "mday")
-%! && isfield (ts, "sec")
-%! && isfield (ts, "min")
-%! && isfield (ts, "wday")
-%! && isfield (ts, "hour")
-%! && isfield (ts, "isdst")
-%! && isfield (ts, "yday")));
+%! assert (isstruct (ts));
+%! assert (isfield (ts, "usec"));
+%! assert (isfield (ts, "year"));
+%! assert (isfield (ts, "mon"));
+%! assert (isfield (ts, "mday"));
+%! assert (isfield (ts, "sec"));
+%! assert (isfield (ts, "min"));
+%! assert (isfield (ts, "wday"));
+%! assert (isfield (ts, "hour"));
+%! assert (isfield (ts, "isdst"));
+%! assert (isfield (ts, "yday"));
 
-%!error <Invalid call to gmtime> gmtime ();
-
-%!error <Invalid call to gmtime> gmtime (1, 2);
-
+%!error gmtime ()
+%!error gmtime (1, 2)
 */
 
-DEFUN_DLD (localtime, args, ,
+DEFUN (localtime, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{tm_struct} =} localtime (@var{t})\n\
+@deftypefn {Built-in Function} {@var{tm_struct} =} localtime (@var{t})\n\
 Given a value returned from @code{time}, or any non-negative integer,\n\
 return a time structure corresponding to the local time zone.\n\
 \n\
@@ -213,7 +208,7 @@
            yday = 47\n\
            isdst = 0\n\
            zone = CST\n\
-         @}\n\
+        @}\n\
 @end group\n\
 @end example\n\
 @seealso{strftime, strptime, gmtime, mktime, time, now, date, clock, datenum, datestr, datevec, calendar, weekday}\n\
@@ -235,30 +230,27 @@
 }
 
 /*
-
 %!test
 %! ts = localtime (time ());
-%! assert((isstruct (ts)
-%! && isfield (ts, "usec")
-%! && isfield (ts, "year")
-%! && isfield (ts, "mon")
-%! && isfield (ts, "mday")
-%! && isfield (ts, "sec")
-%! && isfield (ts, "min")
-%! && isfield (ts, "wday")
-%! && isfield (ts, "hour")
-%! && isfield (ts, "isdst")
-%! && isfield (ts, "yday")));
+%! assert (isstruct (ts));
+%! assert (isfield (ts, "usec"));
+%! assert (isfield (ts, "year"));
+%! assert (isfield (ts, "mon"));
+%! assert (isfield (ts, "mday"));
+%! assert (isfield (ts, "sec"));
+%! assert (isfield (ts, "min"));
+%! assert (isfield (ts, "wday"));
+%! assert (isfield (ts, "hour"));
+%! assert (isfield (ts, "isdst"));
+%! assert (isfield (ts, "yday"));
 
-%!error <Invalid call to localtime> localtime ();
-
-%!error <Invalid call to localtime> localtime (1, 2);
-
+%!error localtime ()
+%!error localtime (1, 2)
 */
 
-DEFUN_DLD (mktime, args, ,
+DEFUN (mktime, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{seconds} =} mktime (@var{tm_struct})\n\
+@deftypefn {Built-in Function} {@var{seconds} =} mktime (@var{tm_struct})\n\
 Convert a time structure corresponding to the local time to the number\n\
 of seconds since the epoch.  For example:\n\
 \n\
@@ -296,26 +288,23 @@
 }
 
 /*
-
 %!test
 %! t = time ();
-%! assert(fix (mktime (localtime (t))) == fix (t));
-
-%!error <Invalid call to mktime> mktime ();
+%! assert (fix (mktime (localtime (t))) == fix (t));
 
-%!error <Invalid call to mktime> mktime (1, 2, 3);
-
-%% These tests fail on systems with mktime functions of limited
-%% intelligence:
+## These tests fail on systems with mktime functions of limited
+## intelligence:
 %!assert (datestr (datenum (1969, 1, 1), 0), "01-Jan-1969 00:00:00")
 %!assert (datestr (datenum (1901, 1, 1), 0), "01-Jan-1901 00:00:00")
 %!assert (datestr (datenum (1795, 1, 1), 0), "01-Jan-1795 00:00:00")
 
+%!error mktime ()
+%!error mktime (1, 2, 3)
 */
 
-DEFUN_DLD (strftime, args, ,
+DEFUN (strftime, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} strftime (@var{fmt}, @var{tm_struct})\n\
+@deftypefn {Built-in Function} {} strftime (@var{fmt}, @var{tm_struct})\n\
 Format the time structure @var{tm_struct} in a flexible way using the\n\
 format string @var{fmt} that contains @samp{%} substitutions\n\
 similar to those in @code{printf}.  Except where noted, substituted\n\
@@ -329,7 +318,7 @@
 @example\n\
 @group\n\
 strftime (\"%r (%Z) %A %e %B %Y\", localtime (time ()))\n\
-     @result{} \"01:15:06 AM (CST) Monday 17 February 1997\"\n\
+      @result{} \"01:15:06 AM (CST) Monday 17 February 1997\"\n\
 @end group\n\
 @end example\n\
 \n\
@@ -498,22 +487,19 @@
 }
 
 /*
+%!assert (ischar (strftime ("%%%n%t%H%I%k%l", localtime (time ()))));
+%!assert (ischar (strftime ("%M%p%r%R%s%S%T", localtime (time ()))));
+%!assert (ischar (strftime ("%X%Z%z%a%A%b%B", localtime (time ()))));
+%!assert (ischar (strftime ("%c%C%d%e%D%h%j", localtime (time ()))));
+%!assert (ischar (strftime ("%m%U%w%W%x%y%Y", localtime (time ()))));
 
-%!assert((ischar (strftime ("%%%n%t%H%I%k%l", localtime (time ())))
-%! && ischar (strftime ("%M%p%r%R%s%S%T", localtime (time ())))
-%! && ischar (strftime ("%X%Z%z%a%A%b%B", localtime (time ())))
-%! && ischar (strftime ("%c%C%d%e%D%h%j", localtime (time ())))
-%! && ischar (strftime ("%m%U%w%W%x%y%Y", localtime (time ())))));
-
-%!error <Invalid call to strftime> strftime ();
-
-%!error <Invalid call to strftime> strftime ("foo", localtime (time ()), 1);
-
+%!error strftime ()
+%!error strftime ("foo", localtime (time ()), 1)
 */
 
-DEFUN_DLD (strptime, args, ,
+DEFUN (strptime, args, ,
  "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {[@var{tm_struct}, @var{nchars}] =} strptime (@var{str}, @var{fmt})\n\
+@deftypefn {Built-in Function} {[@var{tm_struct}, @var{nchars}] =} strptime (@var{str}, @var{fmt})\n\
 Convert the string @var{str} to the time structure @var{tm_struct} under\n\
 the control of the format string @var{fmt}.\n\
 \n\
rename from src/DLD-FUNCTIONS/tril.cc
rename to libinterp/corefcn/tril.cc
--- a/src/DLD-FUNCTIONS/tril.cc
+++ b/libinterp/corefcn/tril.cc
@@ -33,7 +33,7 @@
 #include "ov.h"
 #include "Cell.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "oct-obj.h"
 
@@ -69,7 +69,7 @@
       for (octave_idx_type j = 0; j < nc; j++)
         {
           octave_idx_type ii = std::min (std::max (zero, j - k), nr);
-          std::fill (rvec, rvec + ii, T());
+          std::fill (rvec, rvec + ii, T ());
           std::copy (avec + ii, avec + nr, rvec + ii);
           avec += nr;
           rvec += nr;
@@ -111,7 +111,7 @@
         {
           octave_idx_type ii = std::min (std::max (zero, j + 1 - k), nr);
           std::copy (avec, avec + ii, rvec);
-          std::fill (rvec + ii, rvec + nr, T());
+          std::fill (rvec + ii, rvec + nr, T ());
           avec += nr;
           rvec += nr;
         }
@@ -134,11 +134,11 @@
     }
 
   Sparse<T> m = a;
-  octave_idx_type nc = m.cols();
+  octave_idx_type nc = m.cols ();
 
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++)
-      if (m.ridx(i) < j-k)
+    for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++)
+      if (m.ridx (i) < j-k)
         m.data(i) = 0.;
 
   m.maybe_compress (true);
@@ -156,11 +156,11 @@
     }
 
   Sparse<T> m = a;
-  octave_idx_type nc = m.cols();
+  octave_idx_type nc = m.cols ();
 
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++)
-      if (m.ridx(i) > j-k)
+    for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++)
+      if (m.ridx (i) > j-k)
         m.data(i) = 0.;
 
   m.maybe_compress (true);
@@ -290,8 +290,8 @@
                 idx_tmp.push_back (ov_idx);
                 ov_idx(1) = static_cast<double> (nc);
                 tmp = tmp.resize (dim_vector (0,0));
-                tmp = tmp.subsasgn("(",idx_tmp, arg.do_index_op (ov_idx));
-                tmp = tmp.resize(dims);
+                tmp = tmp.subsasgn ("(",idx_tmp, arg.do_index_op (ov_idx));
+                tmp = tmp.resize (dims);
 
                 if (lower)
                   {
@@ -305,7 +305,7 @@
                         std::list<octave_value_list> idx;
                         idx.push_back (ov_idx);
 
-                        tmp = tmp.subsasgn ("(", idx, arg.do_index_op(ov_idx));
+                        tmp = tmp.subsasgn ("(", idx, arg.do_index_op (ov_idx));
 
                         if (error_state)
                           return retval;
@@ -323,7 +323,7 @@
                         std::list<octave_value_list> idx;
                         idx.push_back (ov_idx);
 
-                        tmp = tmp.subsasgn ("(", idx, arg.do_index_op(ov_idx));
+                        tmp = tmp.subsasgn ("(", idx, arg.do_index_op (ov_idx));
 
                         if (error_state)
                           return retval;
@@ -339,7 +339,7 @@
   return retval;
 }
 
-DEFUN_DLD (tril, args, ,
+DEFUN (tril, args, ,
   "-*- texinfo -*-\n\
 @deftypefn  {Function File} {} tril (@var{A})\n\
 @deftypefnx {Function File} {} tril (@var{A}, @var{k})\n\
@@ -395,7 +395,7 @@
   return do_trilu ("tril", args);
 }
 
-DEFUN_DLD (triu, args, ,
+DEFUN (triu, args, ,
   "-*- texinfo -*-\n\
 @deftypefn  {Function File} {} triu (@var{A})\n\
 @deftypefnx {Function File} {} triu (@var{A}, @var{k})\n\
@@ -407,7 +407,6 @@
 }
 
 /*
-
 %!test
 %! a = [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12];
 %!
@@ -419,10 +418,13 @@
 %! lm3 = [0, 0, 0; 0, 0, 0; 0, 0, 0; 10, 0, 0];
 %! lm4 = [0, 0, 0; 0, 0, 0; 0, 0, 0; 0, 0, 0];
 %!
-%! assert((tril (a, -4) == lm4 && tril (a, -3) == lm3
-%! && tril (a, -2) == lm2 && tril (a, -1) == lm1
-%! && tril (a) == l0 && tril (a, 1) == l1 && tril (a, 2) == l2));
+%! assert (tril (a, -4), lm4); 
+%! assert (tril (a, -3), lm3);
+%! assert (tril (a, -2), lm2);
+%! assert (tril (a, -1), lm1);
+%! assert (tril (a), l0);
+%! assert (tril (a, 1), l1);
+%! assert (tril (a, 2), l2);
 
-%!error tril ();
-
+%!error tril ()
 */
rename from src/DLD-FUNCTIONS/typecast.cc
rename to libinterp/corefcn/typecast.cc
--- a/src/DLD-FUNCTIONS/typecast.cc
+++ b/libinterp/corefcn/typecast.cc
@@ -25,9 +25,11 @@
 #include <config.h>
 #endif
 
+#include <climits>
+
 #include "mx-base.h"
 
-#include "defun-dld.h"
+#include "defun.h"
 #include "error.h"
 #include "gripes.h"
 #include "oct-obj.h"
@@ -86,29 +88,29 @@
 }
 
 
-DEFUN_DLD (typecast, args, ,
+DEFUN (typecast, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} typecast (@var{x}, @var{class})\n\
+@deftypefn {Built-in Function} {} typecast (@var{x}, @var{class})\n\
 Return a new array @var{y} resulting from interpreting the data of\n\
 @var{x} in memory as data of the numeric class @var{class}.  Both the class\n\
 of @var{x} and @var{class} must be one of the built-in numeric classes:\n\
 \n\
 @example\n\
 @group\n\
-  \"logical\"\n\
-  \"char\"\n\
-  \"int8\"\n\
-  \"int16\"\n\
-  \"int32\"\n\
-  \"int64\"\n\
-  \"uint8\"\n\
-  \"uint16\"\n\
-  \"uint32\"\n\
-  \"uint64\"\n\
-  \"double\"\n\
-  \"single\"\n\
-  \"double complex\"\n\
-  \"single complex\"\n\
+\"logical\"\n\
+\"char\"\n\
+\"int8\"\n\
+\"int16\"\n\
+\"int32\"\n\
+\"int64\"\n\
+\"uint8\"\n\
+\"uint16\"\n\
+\"uint32\"\n\
+\"uint64\"\n\
+\"double\"\n\
+\"single\"\n\
+\"double complex\"\n\
+\"single complex\"\n\
 @end group\n\
 @end example\n\
 \n\
@@ -129,7 +131,7 @@
 @example\n\
 @group\n\
 @var{x} = uint16 ([1, 65535]);\n\
-typecast (@var{x}, 'uint8')\n\
+typecast (@var{x}, \"uint8\")\n\
 @result{} [   1,   0, 255, 255]\n\
 @end group\n\
 @end example\n\
@@ -271,26 +273,26 @@
     }
 }
 
-DEFUN_DLD (bitpack, args, ,
+DEFUN (bitpack, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{y} =} bitpack (@var{x}, @var{class})\n\
+@deftypefn {Built-in Function} {@var{y} =} bitpack (@var{x}, @var{class})\n\
 Return a new array @var{y} resulting from interpreting an array\n\
 @var{x} as raw bit patterns for data of the numeric class @var{class}.\n\
 @var{class} must be one of the built-in numeric classes:\n\
 \n\
 @example\n\
 @group\n\
-  \"char\"\n\
-  \"int8\"\n\
-  \"int16\"\n\
-  \"int32\"\n\
-  \"int64\"\n\
-  \"uint8\"\n\
-  \"uint16\"\n\
-  \"uint32\"\n\
-  \"uint64\"\n\
-  \"double\"\n\
-  \"single\"\n\
+\"char\"\n\
+\"int8\"\n\
+\"int16\"\n\
+\"int32\"\n\
+\"int64\"\n\
+\"uint8\"\n\
+\"uint16\"\n\
+\"uint32\"\n\
+\"uint64\"\n\
+\"double\"\n\
+\"single\"\n\
 @end group\n\
 @end example\n\
 \n\
@@ -380,25 +382,25 @@
   return retval;
 }
 
-DEFUN_DLD (bitunpack, args, ,
+DEFUN (bitunpack, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{y} =} bitunpack (@var{x})\n\
+@deftypefn {Built-in Function} {@var{y} =} bitunpack (@var{x})\n\
 Return an array @var{y} corresponding to the raw bit patterns of\n\
 @var{x}.  @var{x} must belong to one of the built-in numeric classes:\n\
 \n\
 @example\n\
 @group\n\
-  \"char\"\n\
-  \"int8\"\n\
-  \"int16\"\n\
-  \"int32\"\n\
-  \"int64\"\n\
-  \"uint8\"\n\
-  \"uint16\"\n\
-  \"uint32\"\n\
-  \"uint64\"\n\
-  \"double\"\n\
-  \"single\"\n\
+\"char\"\n\
+\"int8\"\n\
+\"int16\"\n\
+\"int32\"\n\
+\"int64\"\n\
+\"uint8\"\n\
+\"uint16\"\n\
+\"uint32\"\n\
+\"uint64\"\n\
+\"double\"\n\
+\"single\"\n\
 @end group\n\
 @end example\n\
 \n\
rename from src/DLD-FUNCTIONS/__delaunayn__.cc
rename to libinterp/dldfcn/__delaunayn__.cc
--- a/src/DLD-FUNCTIONS/__delaunayn__.cc
+++ b/libinterp/dldfcn/__delaunayn__.cc
@@ -124,7 +124,7 @@
       boolT ismalloc = false;
 
       // Qhull flags argument is not const char*
-      OCTAVE_LOCAL_BUFFER (char, flags, 9 + options.length());
+      OCTAVE_LOCAL_BUFFER (char, flags, 9 + options.length ());
 
       sprintf (flags, "qhull d %s", options.c_str ());
 
@@ -224,8 +224,6 @@
 }
 
 /*
-
 ## No test needed for internal helper function.
 %!assert (1)
-
 */
rename from src/DLD-FUNCTIONS/__dsearchn__.cc
rename to libinterp/dldfcn/__dsearchn__.cc
--- a/src/DLD-FUNCTIONS/__dsearchn__.cc
+++ b/libinterp/dldfcn/__dsearchn__.cc
@@ -40,7 +40,7 @@
 Undocumented internal function.\n\
 @end deftypefn")
 {
-  int nargin = args.length();
+  int nargin = args.length ();
   octave_value_list retval;
 
   if (nargin != 2)
@@ -49,18 +49,18 @@
       return retval;
     }
 
-  Matrix x = args(0).matrix_value().transpose ();
-  Matrix xi = args(1).matrix_value().transpose ();
+  Matrix x = args(0).matrix_value ().transpose ();
+  Matrix xi = args(1).matrix_value ().transpose ();
 
   if (! error_state)
     {
-      if (x.rows() != xi.rows() || x.columns() < 1)
+      if (x.rows () != xi.rows () || x.columns () < 1)
         error ("__dsearch__: number of rows of X and XI must match");
       else
         {
-          octave_idx_type n = x.rows();
-          octave_idx_type nx = x.columns();
-          octave_idx_type nxi = xi.columns();
+          octave_idx_type n = x.rows ();
+          octave_idx_type nx = x.columns ();
+          octave_idx_type nxi = xi.columns ();
 
           ColumnVector idx (nxi);
           double *pidx = idx.fortran_vec ();
@@ -110,8 +110,6 @@
 }
 
 /*
-
 ## No test needed for internal helper function.
 %!assert (1)
-
 */
rename from src/DLD-FUNCTIONS/__fltk_uigetfile__.cc
rename to libinterp/dldfcn/__fltk_uigetfile__.cc
--- a/src/DLD-FUNCTIONS/__fltk_uigetfile__.cc
+++ b/libinterp/dldfcn/__fltk_uigetfile__.cc
@@ -24,7 +24,7 @@
 #include <config.h>
 #endif
 
-#if defined (HAVE_FLTK)
+#ifdef HAVE_FLTK
 
 #ifdef WIN32
 #define WIN32_LEAN_AND_MEAN
@@ -39,6 +39,8 @@
 // headers which may require Octave's Complex typedef.
 #undef Complex
 
+#endif
+
 #include "defun-dld.h"
 #include "file-ops.h"
 
@@ -48,6 +50,7 @@
 Undocumented internal function.\n\
 @end deftypefn")
 {
+#ifdef HAVE_FLTK
   // Expected argument list:
   //
   //   args(0) ... FileFilter in fltk format
@@ -58,15 +61,15 @@
 
   octave_value_list retval (3, octave_value (0));
 
-  std::string file_filter = args(0).string_value();
-  std::string title = args(1).string_value();
-  std::string default_name = args(2).string_value();
-  Matrix pos = args(3).matrix_value();
+  std::string file_filter = args(0).string_value ();
+  std::string title = args(1).string_value ();
+  std::string default_name = args(2).string_value ();
+  Matrix pos = args(3).matrix_value ();
 
   int multi_type = Fl_File_Chooser::SINGLE;
   std::string flabel = "Filename:";
 
-  std::string multi = args(4).string_value();
+  std::string multi = args(4).string_value ();
   if (multi == "on")
     multi_type = Fl_File_Chooser::MULTI;
   else if (multi == "dir")
@@ -92,7 +95,7 @@
   while (fc.shown ())
     Fl::wait ();
 
-  if (fc.value())
+  if (fc.value ())
     {
       int file_count = fc.count ();
       std::string fname;
@@ -109,7 +112,7 @@
         }
       else
         {
-          Cell file_cell = Cell(file_count, 1);
+          Cell file_cell = Cell (file_count, 1);
           for (octave_idx_type n = 1; n <= file_count; n++)
             {
               fname = fc.value (n);
@@ -132,13 +135,14 @@
   Fl::flush ();
 
   return retval;
+#else
+  error ("__fltk_uigetfile__: not available without OpenGL and FLTK libraries");
+  return octave_value ();
+#endif
 }
 
 /*
-
 ## No test needed for internal helper function.
 %!assert (1)
-
 */
 
-#endif
rename from src/DLD-FUNCTIONS/__glpk__.cc
rename to libinterp/dldfcn/__glpk__.cc
--- a/src/DLD-FUNCTIONS/__glpk__.cc
+++ b/libinterp/dldfcn/__glpk__.cc
@@ -118,8 +118,8 @@
   1e-7,
   1e-7,
   1e-9,
-  -DBL_MAX,
-  DBL_MAX,
+  -std::numeric_limits<double>::max (),
+  std::numeric_limits<double>::max (),
   -1.0,
   0.0,
   1e-6,
@@ -168,7 +168,7 @@
   int typx = 0;
   int method;
 
-  clock_t t_start = clock();
+  clock_t t_start = clock ();
 
 #if 0
 #ifdef GLPK_PRE_4_14
@@ -282,7 +282,7 @@
     }
 
   //-- scale the problem data (if required)
-  //-- if (scale && (!presol || method == 1)) lpx_scale_prob(lp);
+  //-- if (scale && (!presol || method == 1)) lpx_scale_prob (lp);
   //-- LPX_K_SCALE=IParam[1]  LPX_K_PRESOL=IParam[16]
   if (lpxIntParam[1] && (! lpxIntParam[16] || lpsolver != 1))
     lpx_scale_prob (lp);
@@ -291,7 +291,7 @@
   if (lpsolver == 1 && ! lpxIntParam[16])
     lpx_adv_basis (lp);
 
-  for(int i = 0; i < NIntP; i++)
+  for (int i = 0; i < NIntP; i++)
     lpx_set_int_parm (lp, IParam[i], lpxIntParam[i]);
 
   for (int i = 0; i < NRealP; i++)
@@ -313,12 +313,12 @@
             errnum = lpx_integer (lp);
           }
         else
-          errnum = lpx_simplex(lp);
+          errnum = lpx_simplex (lp);
       }
      break;
 
     case 'T':
-      errnum = lpx_interior(lp);
+      errnum = lpx_interior (lp);
       break;
 
     default:
@@ -488,7 +488,7 @@
 
   //-- 1nd Input. A column array containing the objective function
   //--            coefficients.
-  volatile int mrowsc = args(0).rows();
+  volatile int mrowsc = args(0).rows ();
 
   Matrix C (args(0).matrix_value ());
 
@@ -531,10 +531,10 @@
         }
 
       for (octave_idx_type j = 0; j < Anc; j++)
-        for (octave_idx_type i = A.cidx(j); i < A.cidx(j+1); i++)
+        for (octave_idx_type i = A.cidx (j); i < A.cidx (j+1); i++)
           {
             nz++;
-            rn(nz) = A.ridx(i) + 1;
+            rn(nz) = A.ridx (i) + 1;
             cn(nz) = j + 1;
             a(nz) = A.data(i);
           }
@@ -856,8 +856,6 @@
 }
 
 /*
-
 ## No test needed for internal helper function.
 %!assert (1)
-
 */
rename from src/DLD-FUNCTIONS/__init_fltk__.cc
rename to libinterp/dldfcn/__init_fltk__.cc
--- a/src/DLD-FUNCTIONS/__init_fltk__.cc
+++ b/libinterp/dldfcn/__init_fltk__.cc
@@ -29,16 +29,18 @@
 
 */
 
-// PKG_ADD: register_graphics_toolkit ("fltk");
+// PKG_ADD: if (__have_fltk__ ()) register_graphics_toolkit ("fltk"); endif
 
 #ifdef HAVE_CONFIG_H
 #include <config.h>
 #endif
 
+#include "builtin-defun-decls.h"
 #include "defun-dld.h"
 #include "error.h"
+#include "ov-fcn-handle.h"
 
-#if defined (HAVE_FLTK)
+#ifdef HAVE_FLTK
 
 #include <map>
 #include <set>
@@ -179,7 +181,7 @@
     if (print_mode)
       {
         FILE *fp = octave_popen (print_cmd.c_str (), "w");
-        glps_renderer rend (fileno (fp), print_term);
+        glps_renderer rend (fp, print_term);
 
         rend.draw (gh_manager::get_object (number));
 
@@ -257,7 +259,7 @@
 // Parameter controlling the GUI mode.
 static enum { pan_zoom, rotate_zoom, none } gui_mode;
 
-void script_cb(Fl_Widget*, void* data)
+void script_cb (Fl_Widget*, void* data)
   {
     static_cast<uimenu::properties*> (data)->execute_callback ();
   }
@@ -269,7 +271,7 @@
   fltk_uimenu (int xx, int yy, int ww, int hh)
     {
       menubar = new
-        Fl_Menu_Bar(xx, yy, ww, hh);
+        Fl_Menu_Bar (xx, yy, ww, hh);
     }
 
   int items_to_show (void)
@@ -668,6 +670,14 @@
     callback (window_close, static_cast<void*> (this));
     size_range (4*status_h, 2*status_h);
 
+    // FIXME: The function below is only available in FLTK >= 1.3
+    // At some point support for FLTK 1.1 will be dropped in Octave.
+    // At that point this function should be uncommented.
+    // The current solution is to call xclass() before show() for each window.
+    // Set WM_CLASS which allows window managers to properly group related
+    // windows.  Otherwise, the class is just "FLTK"
+    //default_xclass ("Octave");
+
     begin ();
     {
 
@@ -677,7 +687,7 @@
       uimenu->hide ();
 
       bottom = new Fl_Box (0, hh - status_h, ww, status_h);
-      bottom->box(FL_FLAT_BOX);
+      bottom->box (FL_FLAT_BOX);
 
       ndim = calc_dimensions (gh_manager::get_object (fp.get___myhandle__ ()));
 
@@ -722,8 +732,15 @@
       canvas->mode (FL_DEPTH | FL_DOUBLE );
       if (fp.is_visible ())
         {
+          // FIXME: This code should be removed when Octave drops support
+          // for FLTK 1.1.  Search for default_xclass in this file to find
+          // code that should be uncommented to take its place.
+          //
+          // Set WM_CLASS which allows window managers to properly group
+          // related windows.  Otherwise, the class is just "FLTK"
+          xclass ("Octave");
           show ();
-          if (fp.get_currentaxes ().ok())
+          if (fp.get_currentaxes ().ok ())
             show_canvas ();
           else
             hide_canvas ();
@@ -865,7 +882,7 @@
         else
           hide_menubar ();
 
-        mark_modified();
+        mark_modified ();
       }
   }
 
@@ -1168,12 +1185,12 @@
     pos(2) = ww;
     pos(3) = hh - status_h - menu_h;
 
-    fp.set_position (pos);
+    fp.set_boundingbox (pos, true);
   }
 
   void draw (void)
   {
-    Matrix pos = fp.get_position ().matrix_value ();
+    Matrix pos = fp.get_boundingbox (true);
     Fl_Window::resize (pos(0), pos(1), pos(2), pos(3) + status_h + menu_h);
 
     return Fl_Window::draw ();
@@ -1296,12 +1313,12 @@
                       dynamic_cast<axes::properties&> (ax_obj.get_properties ());
 
                     double x0, y0, x1, y1;
-                    Matrix pos = fp.get_position ().matrix_value ();
+                    Matrix pos = fp.get_boundingbox (true);
                     pixel2pos (ax_obj, pos_x, pos_y, x0, y0);
                     pixel2pos (ax_obj, Fl::event_x (), Fl::event_y (), x1, y1);
 
                     if (gui_mode == pan_zoom)
-                      ap.translate_view (x0 - x1, y0 - y1);
+                      ap.translate_view (x0, x1, y0, y1);
                     else if (gui_mode == rotate_zoom)
                       {
                         double daz, del;
@@ -1390,31 +1407,38 @@
                         axes::properties& ap =
                           dynamic_cast<axes::properties&> (ax_obj.get_properties ());
                         pixel2pos (ax_obj, pos_x, pos_y, x0, y0);
-                        pixel2pos (ax_obj, Fl::event_x (), Fl::event_y (),
-                                   x1, y1);
+                        int pos_x1 = Fl::event_x ();
+                        int pos_y1 = Fl::event_y ();
+                        pixel2pos (ax_obj, pos_x1, pos_y1, x1, y1);
                         Matrix xl (1,2,0);
                         Matrix yl (1,2,0);
-                        if (x0 < x1)
+                        int dx = abs (pos_x - pos_x1);
+                        int dy = abs (pos_y - pos_y1);
+                        // Smallest zoom box must be 4 pixels square
+                        if ((dx > 4) && (dy > 4))
                           {
-                            xl(0) = x0;
-                            xl(1) = x1;
-                          }
-                        else
-                          {
-                            xl(0) = x1;
-                            xl(1) = x0;
+                            if (x0 < x1)
+                              {
+                                xl(0) = x0;
+                                xl(1) = x1;
+                              }
+                            else
+                              {
+                                xl(0) = x1;
+                                xl(1) = x0;
+                              }
+                            if (y0 < y1)
+                              {
+                                yl(0) = y0;
+                                yl(1) = y1;
+                              }
+                            else
+                              {
+                                yl(0) = y1;
+                                yl(1) = y0;
+                              }
+                            ap.zoom (xl, yl);
                           }
-                        if (y0 < y1)
-                          {
-                            yl(0) = y0;
-                            yl(1) = y1;
-                          }
-                        else
-                          {
-                            yl(0) = y1;
-                            yl(1) = y0;
-                          }
-                        ap.zoom (xl, yl);
                         mark_modified ();
                       }
                   }
@@ -1812,7 +1836,9 @@
 {
 public:
   fltk_graphics_toolkit (void)
-    : base_graphics_toolkit (FLTK_GRAPHICS_TOOLKIT_NAME) { }
+    : base_graphics_toolkit (FLTK_GRAPHICS_TOOLKIT_NAME),
+      input_event_hook_fcn_id ()
+  { }
 
   ~fltk_graphics_toolkit (void) { }
 
@@ -1902,8 +1928,8 @@
         if (id == uimenu::properties::ID_LABEL)
           uimenu_set_fltk_label (go);
 
-        graphics_object fig = go.get_ancestor("figure");
-        figure_manager::uimenu_update(fig.get_handle (), go.get_handle (), id);
+        graphics_object fig = go.get_ancestor ("figure");
+        figure_manager::uimenu_update (fig.get_handle (), go.get_handle (), id);
       }
   }
 
@@ -1949,49 +1975,83 @@
         munlock ("__init_fltk__");
 
         figure_manager::close_all ();
-        gtk_manager::unload_toolkit (FLTK_GRAPHICS_TOOLKIT_NAME);
-        toolkit_loaded = false;
 
-        octave_value_list args;
-        args(0) = "__fltk_redraw__";
-        feval ("remove_input_event_hook", args, 0);
+        octave_value_list args = input_event_hook_fcn_id;
+        args.append (false);
+        Fremove_input_event_hook (args, 0);
+
+        input_event_hook_fcn_id = octave_value_list ();
 
         // FIXME ???
         Fl::wait (fltk_maxtime);
       }
   }
+
+  void set_input_event_hook_id (const octave_value_list& id)
+  {
+    input_event_hook_fcn_id = id;
+  }
+
+private:
+  octave_value_list input_event_hook_fcn_id;
 };
 
+#endif
+
+DEFUN_DLD (__fltk_redraw__, , ,
+  "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} {} __fltk_redraw__ ()\n\
+Undocumented internal function.\n\
+@end deftypefn")
+{
+#ifdef HAVE_FLTK
+  __fltk_redraw__ ();
+#else
+  error ("__fltk_redraw__: not available without OpenGL and FLTK libraries");
+#endif
+
+  return octave_value ();
+}
+
 // Initialize the fltk graphics toolkit.
 
-DEFUN_DLD (__init_fltk__, , , "")
+DEFUN_DLD (__init_fltk__, , ,
+  "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} {} __init_fltk__ ()\n\
+Undocumented internal function.\n\
+@end deftypefn")
 {
+#ifdef HAVE_FLTK
   if (! toolkit_loaded)
     {
       mlock ();
 
-      graphics_toolkit tk (new fltk_graphics_toolkit ());
+      fltk_graphics_toolkit *fltk = new fltk_graphics_toolkit ();
+      graphics_toolkit tk (fltk);
       gtk_manager::load_toolkit (tk);
       toolkit_loaded = true;
 
-      octave_value_list args;
-      args(0) = "__fltk_redraw__";
-      feval ("add_input_event_hook", args, 0);
-    }
+      octave_value fcn (new octave_builtin (F__fltk_redraw__));
+      octave_value fcn_handle (new octave_fcn_handle (fcn, "@__fltk_redraw__"));
+      octave_value_list id = Fadd_input_event_hook (fcn_handle, 1);
 
-  octave_value retval;
-  return retval;
-}
-
-DEFUN_DLD (__fltk_redraw__, , , "")
-{
-  __fltk_redraw__ ();
+      fltk->set_input_event_hook_id (id);
+    }
+#else
+  error ("__init_fltk__: not available without OpenGL and FLTK libraries");
+#endif
 
   return octave_value ();
 }
 
-DEFUN_DLD (__fltk_maxtime__, args, ,"")
+DEFUN_DLD (__fltk_maxtime__, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn  {Loadable Function} {@var{maxtime} =} __fltk_maxtime__ ()\n\
+@deftypefnx {Loadable Function} {} __fltk_maxtime__ (@var{maxtime})\n\
+Undocumented internal function.\n\
+@end deftypefn")
 {
+#ifdef HAVE_FLTK
   octave_value retval = fltk_maxtime;
 
   if (args.length () == 1)
@@ -2003,10 +2063,29 @@
     }
 
   return retval;
+#else
+  error ("__fltk_maxtime__: not available without OpenGL and FLTK libraries");
+  return octave_value ();
+#endif
 }
 
+DEFUN_DLD (__have_fltk__, , ,
+  "-*- texinfo -*-\n\
+@deftypefn  {Loadable Function} {@var{FLTK_available} =} __have_fltk__ ()\n\
+Undocumented internal function.\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+#ifdef HAVE_FLTK
+  retval = true;
+#else
+  retval = false;
 #endif
 
+  return retval;
+}
+
 // FIXME -- This function should be abstracted and made potentially
 // available to all graphics toolkits.  This suggests putting it in
 // graphics.cc as is done for drawnow() and having the master
@@ -2024,7 +2103,7 @@
 @seealso{gui_mode}\n\
 @end deftypefn")
 {
-#if defined (HAVE_FLTK)
+#ifdef HAVE_FLTK
   octave_value retval = wheel_zoom_speed;
 
   if (args.length () == 1)
@@ -2036,7 +2115,7 @@
     }
 
   return retval;
-#else 
+#else
   error ("mouse_wheel_zoom: not available without OpenGL and FLTK libraries");
   return octave_value ();
 #endif
@@ -2048,6 +2127,7 @@
 @deftypefnx {Built-in Function} {} gui_mode (@var{mode})\n\
 Query or set the GUI mode for the current graphics toolkit.\n\
 The @var{mode} argument can be one of the following strings:\n\
+\n\
 @table @asis\n\
 @item '2d'\n\
 Allows panning and zooming of current axes.\n\
@@ -2063,7 +2143,7 @@
 @seealso{mouse_wheel_zoom}\n\
 @end deftypefn")
 {
-#if defined (HAVE_FLTK)
+#ifdef HAVE_FLTK
   caseless_str mode_str;
 
   if (gui_mode == pan_zoom)
@@ -2099,8 +2179,7 @@
 
   return octave_value (mode_str);
 #else
-  error ("mouse_wheel_zoom: not available without OpenGL and FLTK libraries");
+  error ("gui_mode: not available without OpenGL and FLTK libraries");
   return octave_value ();
 #endif
 }
-
rename from src/DLD-FUNCTIONS/__init_gnuplot__.cc
rename to libinterp/dldfcn/__init_gnuplot__.cc
--- a/src/DLD-FUNCTIONS/__init_gnuplot__.cc
+++ b/libinterp/dldfcn/__init_gnuplot__.cc
@@ -33,6 +33,7 @@
 #include <config.h>
 #endif
 
+#include "builtins.h"
 #include "defun-dld.h"
 #include "error.h"
 #include "graphics.h"
@@ -148,24 +149,17 @@
 
           if (! error_state)
             {
-              args(1) = "\nquit;\n";
-              args(0) = fids(0);
-              feval ("fputs", args);
+              Ffputs (ovl (fids(0), "\nquit;\n"));
 
-              args.resize (1);
-              feval ("fflush", args);
-              feval ("pclose", args);
+              Ffflush (ovl (fids(0)));
+              Fpclose (ovl (fids(0)));
 
               if (fids.numel () > 1)
                 {
-                  args(0) = fids(1);
-                  feval ("pclose", args);
+                  Fpclose (ovl (fids(1)));
 
                   if (fids.numel () > 2)
-                    {
-                      args(0) = fids(2);
-                      feval ("waitpid", args);
-                    }
+                    Fwaitpid (ovl (fids(2)));
                 }
             }
         }
rename from src/DLD-FUNCTIONS/__magick_read__.cc
rename to libinterp/dldfcn/__magick_read__.cc
--- a/src/DLD-FUNCTIONS/__magick_read__.cc
+++ b/libinterp/dldfcn/__magick_read__.cc
@@ -381,7 +381,7 @@
 
   if (! initialized)
     {
-      // Save the locale as GraphicsMagick might change this (depending on version)
+      // Save locale as GraphicsMagick might change this (depending on version)
       const char *static_locale = setlocale (LC_ALL, NULL);
       const std::string locale (static_locale);
 
@@ -403,9 +403,9 @@
 
 DEFUN_DLD (__magick_read__, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Function File} {@var{m} =} __magick_read__(@var{fname}, @var{index})\n\
-@deftypefnx {Function File} {[@var{m}, @var{colormap}] =} __magick_read__(@var{fname}, @var{index})\n\
-@deftypefnx {Function File} {[@var{m}, @var{colormap}, @var{alpha}] =} __magick_read__(@var{fname}, @var{index})\n\
+@deftypefn  {Loadable Function} {@var{m} =} __magick_read__ (@var{fname}, @var{index})\n\
+@deftypefnx {Loadable Function} {[@var{m}, @var{colormap}] =} __magick_read__ (@var{fname}, @var{index})\n\
+@deftypefnx {Loadable Function} {[@var{m}, @var{colormap}, @var{alpha}] =} __magick_read__ (@var{fname}, @var{index})\n\
 Read images with ImageMagick++.  In general you should not be using this\n\
 function.  Instead use @code{imread}.\n\
 @seealso{imread}\n\
@@ -428,14 +428,14 @@
   bool all_frames = false;
 
   if (args.length () == 2 && args(1).is_real_type ())
-    frameidx = args(1).int_vector_value();
+    frameidx = args(1).int_vector_value ();
   else if (args.length () == 3 && args(1).is_string ()
-           && args(1).string_value() == "frames")
+           && args(1).string_value () == "frames")
     {
-      if (args(2).is_string () && args(2).string_value() == "all")
+      if (args(2).is_string () && args(2).string_value () == "all")
         all_frames = true;
       else if (args(2).is_real_type ())
-        frameidx = args(2).int_vector_value();
+        frameidx = args(2).int_vector_value ();
     }
   else
     {
@@ -533,10 +533,8 @@
 }
 
 /*
-
 ## No test needed for internal helper function.
 %!assert (1)
-
 */
 
 #ifdef HAVE_MAGICK
@@ -606,7 +604,7 @@
 
   for (unsigned int ii = 0; ii < nframes; ii++)
     {
-      Magick::Image im(Magick::Geometry (columns, rows), "black");
+      Magick::Image im (Magick::Geometry (columns, rows), "black");
       im.classType (Magick::DirectClass);
       im.depth (1);
 
@@ -873,8 +871,8 @@
 
 DEFUN_DLD (__magick_write__, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Function File} {} __magick_write__(@var{fname}, @var{fmt}, @var{img})\n\
-@deftypefnx {Function File} {} __magick_write__(@var{fname}, @var{fmt}, @var{img}, @var{map})\n\
+@deftypefn  {Loadable Function} {} __magick_write__ (@var{fname}, @var{fmt}, @var{img})\n\
+@deftypefnx {Loadable Function} {} __magick_write__ (@var{fname}, @var{fmt}, @var{img}, @var{map})\n\
 Write images with ImageMagick++.  In general you should not be using this\n\
 function.  Instead use @code{imwrite}.\n\
 @seealso{imread}\n\
@@ -903,7 +901,7 @@
                 if (args(3).is_real_type ())
                   write_image (filename, fmt, args(2), args(3));
                 else
-                  write_image (filename, fmt, args(2), octave_value(), args(3));
+                  write_image (filename, fmt, args(2), octave_value (), args(3));
               else
                 write_image (filename, fmt, args(2));
             }
@@ -925,10 +923,8 @@
 }
 
 /*
-
 ## No test needed for internal helper function.
 %!assert (1)
-
 */
 
 #ifdef HAVE_MAGICK
@@ -1011,7 +1007,7 @@
 
 DEFUN_DLD (__magick_finfo__, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} __magick_finfo__(@var{fname})\n\
+@deftypefn {Loadable Function} {} __magick_finfo__ (@var{fname})\n\
 Read image information with GraphicsMagick++.  In general you should\n\
 not be using this function.  Instead use @code{imfinfo}.\n\
 @seealso{imfinfo, imread}\n\
@@ -1150,10 +1146,8 @@
 }
 
 /*
-
 ## No test needed for internal helper function.
 %!assert (1)
-
 */
 
 #undef GET_PARAM
@@ -1165,7 +1159,7 @@
 
 DEFUN_DLD (__magick_format_list__, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Function File} {} __magick_format_list__ (@var{formats})\n\
+@deftypefn {Loadable Function} {} __magick_format_list__ (@var{formats})\n\
 Undocumented internal function.\n\
 @end deftypefn")
 {
@@ -1217,8 +1211,6 @@
 }
 
 /*
-
 ## No test needed for internal helper function.
 %!assert (1)
-
 */
rename from src/DLD-FUNCTIONS/__voronoi__.cc
rename to libinterp/dldfcn/__voronoi__.cc
--- a/src/DLD-FUNCTIONS/__voronoi__.cc
+++ b/libinterp/dldfcn/__voronoi__.cc
@@ -90,7 +90,7 @@
 
   std::string options;
 
-  if (dim <= 4)
+  if (dim <= 3)
     options = " Qbb";
   else
     options = " Qbb Qx";
@@ -329,8 +329,6 @@
 }
 
 /*
-
 ## No test needed for internal helper function.
 %!assert (1)
-
 */
rename from src/DLD-FUNCTIONS/amd.cc
rename to libinterp/dldfcn/amd.cc
--- a/src/DLD-FUNCTIONS/amd.cc
+++ b/libinterp/dldfcn/amd.cc
@@ -44,7 +44,7 @@
 #include "oct-sparse.h"
 #include "oct-locbuf.h"
 
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
 #define AMD_NAME(name) amd_l ## name
 #else
 #define AMD_NAME(name) amd ## name
@@ -190,7 +190,7 @@
                     for (octave_idx_type i = 0; i < n_col; i++)
                       Pout.xelem (i) = P[i] + 1;
 
-                    retval (0) = Pout;
+                    retval(0) = Pout;
                   }
                 }
             }
rename from src/DLD-FUNCTIONS/ccolamd.cc
rename to libinterp/dldfcn/ccolamd.cc
--- a/src/DLD-FUNCTIONS/ccolamd.cc
+++ b/libinterp/dldfcn/ccolamd.cc
@@ -43,7 +43,7 @@
 #include "oct-sparse.h"
 #include "oct-locbuf.h"
 
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
 #define CCOLAMD_NAME(name) ccolamd_l ## name
 #define CSYMAMD_NAME(name) csymamd_l ## name
 #else
@@ -103,7 +103,7 @@
 range 1 to\n\
 n).  In the output permutation @var{p}, all columns in set 1 appear\n\
 first, followed by all columns in set 2, and so on.  @code{@var{cmember} =\n\
-ones(1,n)} if not present or empty.\n\
+ones (1,n)} if not present or empty.\n\
 @code{ccolamd (@var{S}, [], 1 : n)} returns @code{1 : n}\n\
 \n\
 @code{@var{p} = ccolamd (@var{S})} is about the same as\n\
@@ -164,53 +164,53 @@
           int nel_User_knobs = User_knobs.length ();
 
           if (nel_User_knobs > 0)
-            knobs [CCOLAMD_LU] = (User_knobs (0) != 0);
+            knobs[CCOLAMD_LU] = (User_knobs(0) != 0);
           if (nel_User_knobs > 1)
-            knobs [CCOLAMD_DENSE_ROW]  = User_knobs (1);
+            knobs[CCOLAMD_DENSE_ROW] = User_knobs(1);
           if (nel_User_knobs > 2)
-            knobs [CCOLAMD_DENSE_COL]  = User_knobs (2);
+            knobs[CCOLAMD_DENSE_COL] = User_knobs(2);
           if (nel_User_knobs > 3)
-            knobs [CCOLAMD_AGGRESSIVE] = (User_knobs (3) != 0);
+            knobs[CCOLAMD_AGGRESSIVE] = (User_knobs(3) != 0);
           if (nel_User_knobs > 4)
-            spumoni = (User_knobs (4) != 0);
+            spumoni = (User_knobs(4) != 0);
 
           // print knob settings if spumoni is set
           if (spumoni)
             {
               octave_stdout << "\nccolamd version " << CCOLAMD_MAIN_VERSION << "."
                             <<  CCOLAMD_SUB_VERSION << ", " << CCOLAMD_DATE
-                            << ":\nknobs(1): " << User_knobs (0) << ", order for ";
-              if ( knobs [CCOLAMD_LU] != 0)
-                octave_stdout << "lu(A)\n";
+                            << ":\nknobs(1): " << User_knobs(0) << ", order for ";
+              if (knobs[CCOLAMD_LU] != 0)
+                octave_stdout << "lu (A)\n";
               else
-                octave_stdout << "chol(A'*A)\n";
+                octave_stdout << "chol (A'*A)\n";
 
-              if (knobs [CCOLAMD_DENSE_ROW] >= 0)
-                octave_stdout << "knobs(2): " << User_knobs (1)
-                              << ", rows with > max(16,"
-                              << knobs [CCOLAMD_DENSE_ROW] << "*sqrt(size(A,2)))"
+              if (knobs[CCOLAMD_DENSE_ROW] >= 0)
+                octave_stdout << "knobs(2): " << User_knobs(1)
+                              << ", rows with > max (16,"
+                              << knobs[CCOLAMD_DENSE_ROW] << "*sqrt (size(A,2)))"
                               << " entries removed\n";
               else
-                octave_stdout << "knobs(2): " << User_knobs (1)
+                octave_stdout << "knobs(2): " << User_knobs(1)
                               << ", no dense rows removed\n";
 
-              if (knobs [CCOLAMD_DENSE_COL] >= 0)
-                octave_stdout << "knobs(3): " << User_knobs (2)
-                              << ", cols with > max(16,"
-                              << knobs [CCOLAMD_DENSE_COL] << "*sqrt(size(A)))"
+              if (knobs[CCOLAMD_DENSE_COL] >= 0)
+                octave_stdout << "knobs(3): " << User_knobs(2)
+                              << ", cols with > max (16,"
+                              << knobs[CCOLAMD_DENSE_COL] << "*sqrt (size(A)))"
                               << " entries removed\n";
               else
-                octave_stdout << "knobs(3): " << User_knobs (2)
+                octave_stdout << "knobs(3): " << User_knobs(2)
                               << ", no dense columns removed\n";
 
-              if (knobs [CCOLAMD_AGGRESSIVE] != 0)
+              if (knobs[CCOLAMD_AGGRESSIVE] != 0)
                 octave_stdout << "knobs(4): " << User_knobs(3)
                               << ", aggressive absorption: yes";
               else
                 octave_stdout << "knobs(4): " << User_knobs(3)
                               << ", aggressive absorption: no";
 
-              octave_stdout << "knobs(5): " << User_knobs (4)
+              octave_stdout << "knobs(5): " << User_knobs(4)
                             << ", statistics and knobs printed\n";
             }
         }
@@ -259,19 +259,19 @@
       // Allocate workspace for ccolamd
       OCTAVE_LOCAL_BUFFER (octave_idx_type, p, n_col+1);
       for (octave_idx_type i = 0; i < n_col+1; i++)
-        p[i] = cidx [i];
+        p[i] = cidx[i];
 
       octave_idx_type Alen = CCOLAMD_NAME (_recommended) (nnz, n_row, n_col);
       OCTAVE_LOCAL_BUFFER (octave_idx_type, A, Alen);
       for (octave_idx_type i = 0; i < nnz; i++)
-        A[i] = ridx [i];
+        A[i] = ridx[i];
 
       OCTAVE_LOCAL_BUFFER (octave_idx_type, stats, CCOLAMD_STATS);
 
       if (nargin > 2)
         {
-          NDArray in_cmember = args(2).array_value();
-          octave_idx_type cslen = in_cmember.length();
+          NDArray in_cmember = args(2).array_value ();
+          octave_idx_type cslen = in_cmember.length ();
           OCTAVE_LOCAL_BUFFER (octave_idx_type, cmember, cslen);
           for (octave_idx_type i = 0; i < cslen; i++)
             // convert cmember from 1-based to 0-based
@@ -302,9 +302,9 @@
       // return the permutation vector
       NDArray out_perm (dim_vector (1, n_col));
       for (octave_idx_type i = 0; i < n_col; i++)
-        out_perm(i) = p [i] + 1;
+        out_perm(i) = p[i] + 1;
 
-      retval (0) = out_perm;
+      retval(0) = out_perm;
 
       // print stats if spumoni > 0
       if (spumoni > 0)
@@ -315,7 +315,7 @@
         {
           NDArray out_stats (dim_vector (1, CCOLAMD_STATS));
           for (octave_idx_type i = 0 ; i < CCOLAMD_STATS ; i++)
-            out_stats (i) = stats [i] ;
+            out_stats(i) = stats[i] ;
           retval(1) = out_stats;
 
           // fix stats (5) and (6), for 1-based information on
@@ -372,11 +372,11 @@
 on the ordering.  If @code{@var{cmember}(j) = @var{S}}, then row/column j is\n\
 in constraint set @var{c} (@var{c} must be in the range 1 to n).  In the\n\
 output permutation @var{p}, rows/columns in set 1 appear first, followed\n\
-by all rows/columns in set 2, and so on.  @code{@var{cmember} = ones(1,n)}\n\
-if not present or empty.  @code{csymamd(@var{S},[],1:n)} returns @code{1:n}.\n\
+by all rows/columns in set 2, and so on.  @code{@var{cmember} = ones (1,n)}\n\
+if not present or empty.  @code{csymamd (@var{S},[],1:n)} returns @code{1:n}.\n\
 \n\
-@code{@var{p} = csymamd(@var{S})} is about the same as @code{@var{p} =\n\
-symamd(@var{S})}.  @var{knobs} and its default values differ.\n\
+@code{@var{p} = csymamd (@var{S})} is about the same as @code{@var{p} =\n\
+symamd (@var{S})}.  @var{knobs} and its default values differ.\n\
 \n\
 @code{@var{stats}(4:7)} provide information if CCOLAMD was able to\n\
 continue.  The matrix is OK if @code{@var{stats}(4)} is zero, or 1 if\n\
@@ -419,11 +419,11 @@
           int nel_User_knobs = User_knobs.length ();
 
           if (nel_User_knobs > 0)
-            knobs [CCOLAMD_DENSE_ROW] = User_knobs (0);
+            knobs[CCOLAMD_DENSE_ROW] = User_knobs(0);
           if (nel_User_knobs > 0)
-            knobs [CCOLAMD_AGGRESSIVE] = User_knobs (1);
+            knobs[CCOLAMD_AGGRESSIVE] = User_knobs(1);
           if (nel_User_knobs > 1)
-            spumoni = static_cast<int> (User_knobs (2));
+            spumoni = static_cast<int> (User_knobs(2));
 
           // print knob settings if spumoni is set
           if (spumoni)
@@ -431,16 +431,16 @@
               octave_stdout << "\ncsymamd version " << CCOLAMD_MAIN_VERSION << "."
                             <<  CCOLAMD_SUB_VERSION << ", " << CCOLAMD_DATE << "\n";
 
-              if (knobs [CCOLAMD_DENSE_ROW] >= 0)
-                octave_stdout << "knobs(1): " << User_knobs (0)
-                              << ", rows/cols with > max(16,"
-                              << knobs [CCOLAMD_DENSE_ROW] << "*sqrt(size(A,2)))"
+              if (knobs[CCOLAMD_DENSE_ROW] >= 0)
+                octave_stdout << "knobs(1): " << User_knobs(0)
+                              << ", rows/cols with > max (16,"
+                              << knobs[CCOLAMD_DENSE_ROW] << "*sqrt (size(A,2)))"
                               << " entries removed\n";
               else
-                octave_stdout << "knobs(1): " << User_knobs (0)
+                octave_stdout << "knobs(1): " << User_knobs(0)
                               << ", no dense rows/cols removed\n";
 
-              if (knobs [CCOLAMD_AGGRESSIVE] != 0)
+              if (knobs[CCOLAMD_AGGRESSIVE] != 0)
                 octave_stdout << "knobs(2): " << User_knobs(1)
                               << ", aggressive absorption: yes";
               else
@@ -448,7 +448,7 @@
                               << ", aggressive absorption: no";
 
 
-              octave_stdout << "knobs(3): " << User_knobs (2)
+              octave_stdout << "knobs(3): " << User_knobs(2)
                             << ", statistics and knobs printed\n";
             }
         }
@@ -502,8 +502,8 @@
 
       if (nargin > 2)
         {
-          NDArray in_cmember = args(2).array_value();
-          octave_idx_type cslen = in_cmember.length();
+          NDArray in_cmember = args(2).array_value ();
+          octave_idx_type cslen = in_cmember.length ();
           OCTAVE_LOCAL_BUFFER (octave_idx_type, cmember, cslen);
           for (octave_idx_type i = 0; i < cslen; i++)
             // convert cmember from 1-based to 0-based
@@ -534,16 +534,16 @@
       // return the permutation vector
       NDArray out_perm (dim_vector (1, n_col));
       for (octave_idx_type i = 0; i < n_col; i++)
-        out_perm(i) = perm [i] + 1;
+        out_perm(i) = perm[i] + 1;
 
-      retval (0) = out_perm;
+      retval(0) = out_perm;
 
       // Return the stats vector
       if (nargout == 2)
         {
           NDArray out_stats (dim_vector (1, CCOLAMD_STATS));
           for (octave_idx_type i = 0 ; i < CCOLAMD_STATS ; i++)
-            out_stats (i) = stats [i] ;
+            out_stats(i) = stats[i] ;
           retval(1) = out_stats;
 
           // fix stats (5) and (6), for 1-based information on
@@ -562,7 +562,7 @@
         {
           NDArray out_stats (dim_vector (1, CCOLAMD_STATS));
           for (octave_idx_type i = 0 ; i < CCOLAMD_STATS ; i++)
-            out_stats (i) = stats [i] ;
+            out_stats(i) = stats[i] ;
           retval(1) = out_stats;
 
           // fix stats (5) and (6), for 1-based information on
rename from src/DLD-FUNCTIONS/chol.cc
rename to libinterp/dldfcn/chol.cc
--- a/src/DLD-FUNCTIONS/chol.cc
+++ b/libinterp/dldfcn/chol.cc
@@ -65,9 +65,9 @@
 @deftypefn  {Loadable Function} {@var{R} =} chol (@var{A})\n\
 @deftypefnx {Loadable Function} {[@var{R}, @var{p}] =} chol (@var{A})\n\
 @deftypefnx {Loadable Function} {[@var{R}, @var{p}, @var{Q}] =} chol (@var{S})\n\
-@deftypefnx {Loadable Function} {[@var{R}, @var{p}, @var{Q}] =} chol (@var{S}, 'vector')\n\
-@deftypefnx {Loadable Function} {[@var{L}, @dots{}] =} chol (@dots{}, 'lower')\n\
-@deftypefnx {Loadable Function} {[@var{L}, @dots{}] =} chol (@dots{}, 'upper')\n\
+@deftypefnx {Loadable Function} {[@var{R}, @var{p}, @var{Q}] =} chol (@var{S}, \"vector\")\n\
+@deftypefnx {Loadable Function} {[@var{L}, @dots{}] =} chol (@dots{}, \"lower\")\n\
+@deftypefnx {Loadable Function} {[@var{L}, @dots{}] =} chol (@dots{}, \"upper\")\n\
 @cindex Cholesky factorization\n\
 Compute the Cholesky@tie{}factor, @var{R}, of the symmetric positive definite\n\
 matrix @var{A}, where\n\
@@ -103,7 +103,7 @@
 @end ifnottex\n\
 \n\
 The sparsity preserving permutation is generally returned as a matrix.\n\
-However, given the flag 'vector', @var{Q} will be returned as a vector\n\
+However, given the flag \"vector\", @var{Q} will be returned as a vector\n\
 such that\n\
 @tex\n\
 $ R^T R = A (Q, Q)$.\n\
@@ -116,7 +116,7 @@
 \n\
 @end ifnottex\n\
 \n\
-Called with either a sparse or full matrix and using the 'lower' flag,\n\
+Called with either a sparse or full matrix and using the \"lower\" flag,\n\
 @code{chol} returns the lower triangular factorization such that\n\
 @tex\n\
 $ L L^T = A $.\n\
@@ -129,9 +129,9 @@
 \n\
 @end ifnottex\n\
 \n\
-For full matrices, if the 'lower' flag is set only the lower triangular part\n\
-of the matrix is used for the factorization, otherwise the upper triangular\n\
-part is used.\n\
+For full matrices, if the \"lower\" flag is set only the lower triangular\n\
+part of the matrix is used for the factorization, otherwise the upper\n\
+triangular part is used.\n\
 \n\
 In general the lower triangular factorization is significantly faster for\n\
 sparse matrices.\n\
@@ -180,7 +180,6 @@
 
       octave_idx_type nr = arg.rows ();
       octave_idx_type nc = arg.columns ();
-      bool natural = (nargout != 3);
 
       int arg_is_empty = empty_arg ("chol", nr, nc);
 
@@ -191,29 +190,33 @@
 
       if (arg.is_sparse_type ())
         {
+          octave_idx_type info;
+          bool natural = (nargout != 3);
+          bool force = nargout > 1;
+
           if (arg.is_real_type ())
             {
               SparseMatrix m = arg.sparse_matrix_value ();
 
               if (! error_state)
                 {
-                  octave_idx_type info;
-                  SparseCHOL fact (m, info, natural);
+                  SparseCHOL fact (m, info, natural, force);
+
                   if (nargout == 3)
                     {
                       if (vecout)
                         retval(2) = fact.perm ();
                       else
-                        retval(2) = fact.Q();
+                        retval(2) = fact.Q ();
                     }
 
                   if (nargout > 1 || info == 0)
                     {
-                      retval(1) = fact.P();
+                      retval(1) = fact.P ();
                       if (LLt)
-                        retval(0) = fact.L();
+                        retval(0) = fact.L ();
                       else
-                        retval(0) = fact.R();
+                        retval(0) = fact.R ();
                     }
                   else
                     error ("chol: input matrix must be positive definite");
@@ -225,24 +228,23 @@
 
               if (! error_state)
                 {
-                  octave_idx_type info;
-                  SparseComplexCHOL fact (m, info, natural);
+                  SparseComplexCHOL fact (m, info, natural, force);
 
                   if (nargout == 3)
                     {
                       if (vecout)
                         retval(2) = fact.perm ();
                       else
-                        retval(2) = fact.Q();
+                        retval(2) = fact.Q ();
                     }
 
                   if (nargout > 1 || info == 0)
                     {
-                      retval(1) = fact.P();
+                      retval(1) = fact.P ();
                       if (LLt)
-                        retval(0) = fact.L();
+                        retval(0) = fact.L ();
                       else
-                        retval(0) = fact.R();
+                        retval(0) = fact.R ();
                     }
                   else
                     error ("chol: input matrix must be positive definite");
@@ -371,16 +373,14 @@
 }
 
 /*
-
-%!assert(chol ([2, 1; 1, 1]), [sqrt(2), 1/sqrt(2); 0, 1/sqrt(2)], sqrt (eps));
-%!assert(chol (single([2, 1; 1, 1])), single([sqrt(2), 1/sqrt(2); 0, 1/sqrt(2)]), sqrt (eps('single')));
+%!assert (chol ([2, 1; 1, 1]), [sqrt(2), 1/sqrt(2); 0, 1/sqrt(2)], sqrt (eps))
+%!assert (chol (single ([2, 1; 1, 1])), single ([sqrt(2), 1/sqrt(2); 0, 1/sqrt(2)]), sqrt (eps ("single")))
 
-%!error chol ([1, 2; 3, 4]);
-%!error chol ([1, 2; 3, 4; 5, 6]);
-%!error <Invalid call to chol> chol ();
-%!error <unexpected second or third input> chol (1, 2);
-
- */
+%!error chol ()
+%!error <matrix must be positive definite> chol ([1, 2; 3, 4])
+%!error <requires square matrix> chol ([1, 2; 3, 4; 5, 6])
+%!error <unexpected second or third input> chol (1, 2)
+*/
 
 DEFUN_DLD (cholinv, args, ,
   "-*- texinfo -*-\n\
@@ -407,14 +407,16 @@
         {
           if (arg.is_sparse_type ())
             {
+              octave_idx_type info;
+
               if (arg.is_real_type ())
                 {
                   SparseMatrix m = arg.sparse_matrix_value ();
 
                   if (! error_state)
                     {
-                      octave_idx_type info;
                       SparseCHOL chol (m, info);
+
                       if (info == 0)
                         retval = chol.inverse ();
                       else
@@ -427,8 +429,8 @@
 
                   if (! error_state)
                     {
-                      octave_idx_type info;
                       SparseComplexCHOL chol (m, info);
+
                       if (info == 0)
                         retval = chol.inverse ();
                       else
@@ -513,20 +515,18 @@
 }
 
 /*
-
 %!shared A, Ainv
 %! A = [2,0.2;0.2,1];
-%! Ainv = inv(A);
+%! Ainv = inv (A);
 %!test
-%! Ainv1 = cholinv(A);
-%! assert (norm(Ainv-Ainv1),0,1e-10)
+%! Ainv1 = cholinv (A);
+%! assert (norm (Ainv-Ainv1), 0, 1e-10);
 %!testif HAVE_CHOLMOD
-%! Ainv2 = inv(sparse(A));
-%! assert (norm(Ainv-Ainv2),0,1e-10)
+%! Ainv2 = inv (sparse (A));
+%! assert (norm (Ainv-Ainv2), 0, 1e-10);
 %!testif HAVE_CHOLMOD
-%! Ainv3 = cholinv(sparse(A));
-%! assert (norm(Ainv-Ainv3),0,1e-10)
-
+%! Ainv3 = cholinv (sparse (A));
+%! assert (norm (Ainv-Ainv3), 0, 1e-10);
 */
 
 DEFUN_DLD (chol2inv, args, ,
@@ -627,6 +627,7 @@
 Update or downdate a Cholesky@tie{}factorization.  Given an upper triangular\n\
 matrix @var{R} and a column vector @var{u}, attempt to determine another\n\
 upper triangular matrix @var{R1} such that\n\
+\n\
 @itemize @bullet\n\
 @item\n\
 @var{R1}'*@var{R1} = @var{R}'*@var{R} + @var{u}*@var{u}'\n\
@@ -638,6 +639,7 @@
 @end itemize\n\
 \n\
 If @var{op} is \"-\", @var{info} is set to\n\
+\n\
 @itemize\n\
 @item 0 if the downdate was successful,\n\
 \n\
@@ -786,59 +788,45 @@
 %!        0.83760 + 0.68977i ;
 %!        0.39160 + 0.90378i ];
 
-
+%!test
+%! R = chol (A);
+%! R1 = cholupdate (R, u);
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (R1'*R1 - R'*R - u*u', Inf) < 1e1*eps);
+%!
+%! R1 = cholupdate (R1, u, "-");
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (R1 - R, Inf) < 1e1*eps);
 
 %!test
-%! R = chol(A);
-%!
-%! R1 = cholupdate(R,u);
-%!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - R'*R - u*u',Inf) < 1e1*eps)
-%!
-%! R1 = cholupdate(R1,u,"-");
-%!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1 - R,Inf) < 1e1*eps)
+%! R = chol (Ac);
+%! R1 = cholupdate (R, uc);
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (R1'*R1 - R'*R - uc*uc', Inf) < 1e1*eps);
 %!
-%!test
-%! R = chol(Ac);
-%!
-%! R1 = cholupdate(R,uc);
-%!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - R'*R - uc*uc',Inf) < 1e1*eps)
-%!
-%! R1 = cholupdate(R1,uc,"-");
-%!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1 - R,Inf) < 1e1*eps)
+%! R1 = cholupdate (R1, uc, "-");
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (R1 - R, Inf) < 1e1*eps);
 
 %!test
-%! R = chol(single(A));
-%!
-%! R1 = cholupdate(R,single(u));
-%!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - R'*R - single(u*u'),Inf) < 1e1*eps('single'))
-%!
-%! R1 = cholupdate(R1,single(u),"-");
-%!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1 - R,Inf) < 2e1*eps('single'))
+%! R = chol (single (A));
+%! R1 = cholupdate (R, single (u));
+%! assert (norm (triu (R1)-R1, Inf), single (0));
+%! assert (norm (R1'*R1 - R'*R - single (u*u'), Inf) < 1e1*eps ("single"));
 %!
+%! R1 = cholupdate (R1, single (u), "-");
+%! assert (norm (triu (R1)-R1, Inf), single (0));
+%! assert (norm (R1 - R, Inf) < 2e1*eps ("single"));
+
 %!test
-%! R = chol(single(Ac));
-%!
-%! R1 = cholupdate(R,single(uc));
+%! R = chol (single (Ac));
+%! R1 = cholupdate (R, single (uc));
+%! assert (norm (triu (R1)-R1, Inf), single (0));
+%! assert (norm (R1'*R1 - R'*R - single (uc*uc'), Inf) < 1e1*eps ("single"));
 %!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - R'*R - single(uc*uc'),Inf) < 1e1*eps('single'))
-%!
-%! R1 = cholupdate(R1,single(uc),"-");
-%!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1 - R,Inf) < 2e1*eps('single'))
+%! R1 = cholupdate (R1, single (uc), "-");
+%! assert (norm (triu (R1)-R1, Inf), single (0));
+%! assert (norm (R1 - R, Inf) < 2e1*eps ("single"));
 */
 
 DEFUN_DLD (cholinsert, args, nargout,
@@ -851,6 +839,7 @@
 @var{A1}, where @w{A1(p,p) = A}, @w{A1(:,j) = A1(j,:)' = u} and\n\
 @w{p = [1:j-1,j+1:n+1]}.  @w{u(j)} should be positive.\n\
 On return, @var{info} is set to\n\
+\n\
 @itemize\n\
 @item 0 if the insertion was successful,\n\
 \n\
@@ -972,14 +961,15 @@
 %!        -0.13825 ;
 %!         0.45266 ];
 %!
-%! R = chol(A);
+%! R = chol (A);
 %!
-%! j = 3; p = [1:j-1, j+1:5];
-%! R1 = cholinsert(R,j,u2); A1 = R1'*R1;
+%! j = 3;  p = [1:j-1, j+1:5];
+%! R1 = cholinsert (R, j, u2);
+%! A1 = R1'*R1;
 %!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(A1(p,p) - A,Inf) < 1e1*eps)
-%!
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (A1(p,p) - A, Inf) < 1e1*eps);
+
 %!test
 %! u2 = [  0.35080  + 0.04298i;
 %!         0.63930  + 0.23778i;
@@ -987,14 +977,14 @@
 %!        -0.13825  + 0.19879i;
 %!         0.45266  + 0.50020i];
 %!
-%! R = chol(Ac);
+%! R = chol (Ac);
 %!
-%! j = 3; p = [1:j-1, j+1:5];
-%! R1 = cholinsert(R,j,u2); A1 = R1'*R1;
+%! j = 3;  p = [1:j-1, j+1:5];
+%! R1 = cholinsert (R, j, u2);
+%! A1 = R1'*R1;
 %!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(A1(p,p) - Ac,Inf) < 1e1*eps)
-%!
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (A1(p,p) - Ac, Inf) < 1e1*eps);
 
 %!test
 %! u2 = single ([  0.35080 ;
@@ -1003,14 +993,15 @@
 %!                -0.13825 ;
 %!                 0.45266 ]);
 %!
-%! R = chol(single(A));
+%! R = chol (single (A));
 %!
-%! j = 3; p = [1:j-1, j+1:5];
-%! R1 = cholinsert(R,j,u2); A1 = R1'*R1;
+%! j = 3;  p = [1:j-1, j+1:5];
+%! R1 = cholinsert (R, j, u2);
+%! A1 = R1'*R1;
 %!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(A1(p,p) - A,Inf) < 1e1*eps('single'))
-%!
+%! assert (norm (triu (R1)-R1, Inf), single (0));
+%! assert (norm (A1(p,p) - A, Inf) < 1e1*eps ("single"));
+
 %!test
 %! u2 = single ([  0.35080  + 0.04298i;
 %!                 0.63930  + 0.23778i;
@@ -1018,55 +1009,55 @@
 %!                -0.13825  + 0.19879i;
 %!                 0.45266  + 0.50020i]);
 %!
-%! R = chol(single(Ac));
+%! R = chol (single (Ac));
 %!
-%! j = 3; p = [1:j-1, j+1:5];
-%! R1 = cholinsert(R,j,u2); A1 = R1'*R1;
+%! j = 3;  p = [1:j-1, j+1:5];
+%! R1 = cholinsert (R, j, u2);
+%! A1 = R1'*R1;
 %!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(A1(p,p) - single(Ac),Inf) < 2e1*eps('single'))
-%!
+%! assert (norm (triu (R1)-R1, Inf), single (0));
+%! assert (norm (A1(p,p) - single (Ac), Inf) < 2e1*eps ("single"));
 
 %!test
-%! cu = chol (triu (A), 'upper');
-%! cl = chol (tril (A), 'lower');
-%! assert (cu, cl', eps)
-%!
+%! cu = chol (triu (A), "upper");
+%! cl = chol (tril (A), "lower");
+%! assert (cu, cl', eps);
+
 %!test
 %! cca  = chol (Ac);
 %!
-%! ccal  = chol (Ac, 'lower');
-%! ccal2 = chol (tril (Ac), 'lower');
+%! ccal  = chol (Ac, "lower");
+%! ccal2 = chol (tril (Ac), "lower");
 %!
-%! ccau  = chol (Ac, 'upper');
-%! ccau2 = chol (triu (Ac), 'upper');
+%! ccau  = chol (Ac, "upper");
+%! ccau2 = chol (triu (Ac), "upper");
 %!
-%! assert (cca'*cca,     Ac, eps)
-%! assert (ccau'*ccau,   Ac, eps)
-%! assert (ccau2'*ccau2, Ac, eps)
+%! assert (cca'*cca,     Ac, eps);
+%! assert (ccau'*ccau,   Ac, eps);
+%! assert (ccau2'*ccau2, Ac, eps);
 %!
-%! assert (cca, ccal',  eps)
-%! assert (cca, ccau,   eps)
-%! assert (cca, ccal2', eps)
-%! assert (cca, ccau2,  eps)
-%!
+%! assert (cca, ccal',  eps);
+%! assert (cca, ccau,   eps);
+%! assert (cca, ccal2', eps);
+%! assert (cca, ccau2,  eps);
+
 %!test
 %! cca  = chol (single (Ac));
 %!
-%! ccal  = chol (single (Ac), 'lower');
-%! ccal2 = chol (tril (single (Ac)), 'lower');
+%! ccal  = chol (single (Ac), "lower");
+%! ccal2 = chol (tril (single (Ac)), "lower");
 %!
-%! ccau  = chol (single (Ac), 'upper');
-%! ccau2 = chol (triu (single (Ac)), 'upper');
+%! ccau  = chol (single (Ac), "upper");
+%! ccau2 = chol (triu (single (Ac)), "upper");
 %!
-%! assert (cca'*cca,     single (Ac), eps ('single'))
-%! assert (ccau'*ccau,   single (Ac), eps ('single'))
-%! assert (ccau2'*ccau2, single (Ac), eps ('single'))
+%! assert (cca'*cca,     single (Ac), eps ("single"));
+%! assert (ccau'*ccau,   single (Ac), eps ("single"));
+%! assert (ccau2'*ccau2, single (Ac), eps ("single"));
 %!
-%! assert (cca, ccal',  eps ('single'))
-%! assert (cca, ccau,   eps ('single'))
-%! assert (cca, ccal2', eps ('single'))
-%! assert (cca, ccau2,  eps ('single'))
+%! assert (cca, ccal',  eps ("single"));
+%! assert (cca, ccau,   eps ("single"));
+%! assert (cca, ccal2', eps ("single"));
+%! assert (cca, ccau2,  eps ("single"));
 
 %!test
 %! a = [12,  2,  3,  4;
@@ -1083,21 +1074,20 @@
 %!   
 %! cca  = chol (ca);
 %!
-%! ccal  = chol (ca, 'lower');
-%! ccal2 = chol (tril (ca), 'lower');
+%! ccal  = chol (ca, "lower");
+%! ccal2 = chol (tril (ca), "lower");
 %!
-%! ccau  = chol (ca, 'upper');
-%! ccau2 = chol (triu (ca), 'upper');
+%! ccau  = chol (ca, "upper");
+%! ccau2 = chol (triu (ca), "upper");
 %!
-%! assert (cca'*cca,     ca, 16*eps)
-%! assert (ccau'*ccau,   ca, 16*eps)
-%! assert (ccau2'*ccau2, ca, 16*eps)
+%! assert (cca'*cca,     ca, 16*eps);
+%! assert (ccau'*ccau,   ca, 16*eps);
+%! assert (ccau2'*ccau2, ca, 16*eps);
 %!
-%! assert (cca, ccal',  16*eps)
-%! assert (cca, ccau,   16*eps)
-%! assert (cca, ccal2', 16*eps)
-%! assert (cca, ccau2,  16*eps)
-
+%! assert (cca, ccal',  16*eps);
+%! assert (cca, ccau,   16*eps);
+%! assert (cca, ccal2', 16*eps);
+%! assert (cca, ccau2,  16*eps);
 */
 
 DEFUN_DLD (choldelete, args, ,
@@ -1197,40 +1187,40 @@
 
 /*
 %!test
-%! R = chol(A);
-%!
-%! j = 3; p = [1:j-1,j+1:4];
-%! R1 = choldelete(R,j);
-%!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - A(p,p),Inf) < 1e1*eps)
+%! R = chol (A);
 %!
-%!test
-%! R = chol(Ac);
+%! j = 3;  p = [1:j-1,j+1:4];
+%! R1 = choldelete (R, j);
 %!
-%! j = 3; p = [1:j-1,j+1:4];
-%! R1 = choldelete(R,j);
-%!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - Ac(p,p),Inf) < 1e1*eps)
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (R1'*R1 - A(p,p), Inf) < 1e1*eps);
 
 %!test
-%! R = chol(single(A));
+%! R = chol (Ac);
+%!
+%! j = 3;  p = [1:j-1,j+1:4];
+%! R1 = choldelete (R, j);
 %!
-%! j = 3; p = [1:j-1,j+1:4];
-%! R1 = choldelete(R,j);
-%!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - single(A(p,p)),Inf) < 1e1*eps('single'))
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (R1'*R1 - Ac(p,p), Inf) < 1e1*eps);
+
+%!test
+%! R = chol (single (A));
 %!
-%!test
-%! R = chol(single(Ac));
+%! j = 3;  p = [1:j-1,j+1:4];
+%! R1 = choldelete (R, j);
 %!
-%! j = 3; p = [1:j-1,j+1:4];
-%! R1 = choldelete(R,j);
+%! assert (norm (triu (R1)-R1, Inf), single (0));
+%! assert (norm (R1'*R1 - single (A(p,p)), Inf) < 1e1*eps ("single"));
+
+%!test
+%! R = chol (single (Ac));
 %!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - single(Ac(p,p)),Inf) < 1e1*eps('single'))
+%! j = 3;  p = [1:j-1,j+1:4];
+%! R1 = choldelete (R,j);
+%!
+%! assert (norm (triu (R1)-R1, Inf), single (0));
+%! assert (norm (R1'*R1 - single (Ac(p,p)), Inf) < 1e1*eps ("single"));
 */
 
 DEFUN_DLD (cholshift, args, ,
@@ -1338,62 +1328,62 @@
 
 /*
 %!test
-%! R = chol(A);
+%! R = chol (A);
 %!
-%! i = 1; j = 3; p = [1:i-1, shift(i:j,-1), j+1:4];
-%! R1 = cholshift(R,i,j);
+%! i = 1;  j = 3;  p = [1:i-1, shift(i:j,-1), j+1:4];
+%! R1 = cholshift (R, i, j);
 %!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - A(p,p),Inf) < 1e1*eps)
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (R1'*R1 - A(p,p), Inf) < 1e1*eps);
 %!
-%! j = 1; i = 3; p = [1:j-1, shift(j:i,+1), i+1:4];
-%! R1 = cholshift(R,i,j);
-%!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - A(p,p),Inf) < 1e1*eps)
+%! j = 1;  i = 3;  p = [1:j-1, shift(j:i,+1), i+1:4];
+%! R1 = cholshift (R, i, j);
 %!
+%! assert (norm (triu (R1) - R1, Inf), 0);
+%! assert (norm (R1'*R1 - A(p,p), Inf) < 1e1*eps);
+
 %!test
-%! R = chol(Ac);
+%! R = chol (Ac);
 %!
-%! i = 1; j = 3; p = [1:i-1, shift(i:j,-1), j+1:4];
-%! R1 = cholshift(R,i,j);
+%! i = 1;  j = 3;  p = [1:i-1, shift(i:j,-1), j+1:4];
+%! R1 = cholshift (R, i, j);
 %!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - Ac(p,p),Inf) < 1e1*eps)
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (R1'*R1 - Ac(p,p), Inf) < 1e1*eps);
 %!
-%! j = 1; i = 3; p = [1:j-1, shift(j:i,+1), i+1:4];
-%! R1 = cholshift(R,i,j);
+%! j = 1;  i = 3;  p = [1:j-1, shift(j:i,+1), i+1:4];
+%! R1 = cholshift (R, i, j);
 %!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - Ac(p,p),Inf) < 1e1*eps)
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (R1'*R1 - Ac(p,p), Inf) < 1e1*eps);
 
 %!test
-%! R = chol(single(A));
+%! R = chol (single (A));
+%! 
+%! i = 1;  j = 3;  p = [1:i-1, shift(i:j,-1), j+1:4];
+%! R1 = cholshift (R, i, j);
+%!
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (R1'*R1 - single (A(p,p)), Inf) < 1e1*eps ("single"));
+%!
+%! j = 1;  i = 3;  p = [1:j-1, shift(j:i,+1), i+1:4];
+%! R1 = cholshift (R, i, j);
 %!
-%! i = 1; j = 3; p = [1:i-1, shift(i:j,-1), j+1:4];
-%! R1 = cholshift(R,i,j);
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (R1'*R1 - single (A(p,p)), Inf) < 1e1*eps ("single"));
+
+%!test
+%! R = chol (single (Ac));
 %!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - single(A(p,p)),Inf) < 1e1*eps('single'))
+%! i = 1;  j = 3;  p = [1:i-1, shift(i:j,-1), j+1:4];
+%! R1 = cholshift (R, i, j);
+%!
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (R1'*R1 - single (Ac(p,p)), Inf) < 1e1*eps ("single"));
 %!
 %! j = 1; i = 3; p = [1:j-1, shift(j:i,+1), i+1:4];
-%! R1 = cholshift(R,i,j);
-%!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - single(A(p,p)),Inf) < 1e1*eps('single'))
-%!
-%!test
-%! R = chol(single(Ac));
+%! R1 = cholshift (R, i, j);
 %!
-%! i = 1; j = 3; p = [1:i-1, shift(i:j,-1), j+1:4];
-%! R1 = cholshift(R,i,j);
-%!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - single(Ac(p,p)),Inf) < 1e1*eps('single'))
-%!
-%! j = 1; i = 3; p = [1:j-1, shift(j:i,+1), i+1:4];
-%! R1 = cholshift(R,i,j);
-%!
-%! assert(norm(triu(R1)-R1,Inf) == 0)
-%! assert(norm(R1'*R1 - single(Ac(p,p)),Inf) < 1e1*eps('single'))
+%! assert (norm (triu (R1)-R1, Inf), 0);
+%! assert (norm (R1'*R1 - single (Ac(p,p)), Inf) < 1e1*eps ("single"));
 */
rename from src/DLD-FUNCTIONS/colamd.cc
rename to libinterp/dldfcn/colamd.cc
--- a/src/DLD-FUNCTIONS/colamd.cc
+++ b/libinterp/dldfcn/colamd.cc
@@ -44,7 +44,7 @@
 #include "oct-sparse.h"
 #include "oct-locbuf.h"
 
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
 #define COLAMD_NAME(name) colamd_l ## name
 #define SYMAMD_NAME(name) symamd_l ## name
 #else
@@ -63,28 +63,28 @@
   if (P)
     // If P is present then compute Pinv, the inverse of P
     for (octave_idx_type k = 0 ; k < n ; k++)
-      Pinv [P [k]] = k ;
+      Pinv[P[k]] = k ;
 
   for (octave_idx_type k = 0 ; k < n ; k++)
     {
       // L(k,:) pattern: all nodes reachable in etree from nz in A(0:k-1,k)
-      Parent [k] = n ;                // parent of k is not yet known
-      Flag [k] = k ;                  // mark node k as visited
-      octave_idx_type kk = (P) ? (P [k]) : (k) ;  // kth original, or permuted, column
-      octave_idx_type p2 = cidx [kk+1] ;
-      for (octave_idx_type p = cidx [kk] ; p < p2 ; p++)
+      Parent[k] = n ;                // parent of k is not yet known
+      Flag[k] = k ;                  // mark node k as visited
+      octave_idx_type kk = (P) ? (P[k]) : (k) ;  // kth original, or permuted, column
+      octave_idx_type p2 = cidx[kk+1] ;
+      for (octave_idx_type p = cidx[kk] ; p < p2 ; p++)
         {
           // A (i,k) is nonzero (original or permuted A)
-          octave_idx_type i = (Pinv) ? (Pinv [ridx [p]]) : (ridx [p]) ;
+          octave_idx_type i = (Pinv) ? (Pinv[ridx[p]]) : (ridx[p]) ;
           if (i < k)
             {
               // follow path from i to root of etree, stop at flagged node
-              for ( ; Flag [i] != k ; i = Parent [i])
+              for ( ; Flag[i] != k ; i = Parent[i])
                 {
                   // find parent of i if not yet determined
-                  if (Parent [i] == n)
-                    Parent [i] = k ;
-                  Flag [i] = k ;        // mark i as visited
+                  if (Parent[i] == n)
+                    Parent[i] = k ;
+                  Flag[i] = k ;        // mark i as visited
                 }
             }
         }
@@ -226,7 +226,7 @@
 @var{knobs} is an optional one- to three-element input vector.  If @var{S} is\n\
 m-by-n, then rows with more than @code{max(16,@var{knobs}(1)*sqrt(n))}\n\
 entries are ignored.  Columns with more than\n\
-@code{max(16,@var{knobs}(2)*sqrt(min(m,n)))} entries are removed prior to\n\
+@code{max (16,@var{knobs}(2)*sqrt(min(m,n)))} entries are removed prior to\n\
 ordering, and ordered last in the output permutation @var{p}.  Only\n\
 completely dense rows or columns are removed if @code{@var{knobs}(1)} and\n\
 @code{@var{knobs}(2)} are < 0, respectively.  If @code{@var{knobs}(3)} is\n\
@@ -299,11 +299,11 @@
           int nel_User_knobs = User_knobs.length ();
 
           if (nel_User_knobs > 0)
-            knobs [COLAMD_DENSE_ROW] = User_knobs (0);
+            knobs[COLAMD_DENSE_ROW] = User_knobs(0);
           if (nel_User_knobs > 1)
-            knobs [COLAMD_DENSE_COL] = User_knobs (1) ;
+            knobs[COLAMD_DENSE_COL] = User_knobs(1) ;
           if (nel_User_knobs > 2)
-            spumoni = static_cast<int> (User_knobs (2));
+            spumoni = static_cast<int> (User_knobs(2));
 
           // print knob settings if spumoni is set
           if (spumoni)
@@ -312,19 +312,19 @@
               octave_stdout << "\ncolamd version " << COLAMD_MAIN_VERSION << "."
                             <<  COLAMD_SUB_VERSION << ", " << COLAMD_DATE << ":\n";
 
-              if (knobs [COLAMD_DENSE_ROW] >= 0)
+              if (knobs[COLAMD_DENSE_ROW] >= 0)
                 octave_stdout << "knobs(1): " << User_knobs (0)
-                              << ", rows with > max(16,"
-                              << knobs [COLAMD_DENSE_ROW] << "*sqrt(size(A,2)))"
+                              << ", rows with > max (16,"
+                              << knobs[COLAMD_DENSE_ROW] << "*sqrt (size(A,2)))"
                               << " entries removed\n";
               else
                 octave_stdout << "knobs(1): " << User_knobs (0)
                               << ", only completely dense rows removed\n";
 
-              if (knobs [COLAMD_DENSE_COL] >= 0)
+              if (knobs[COLAMD_DENSE_COL] >= 0)
                 octave_stdout << "knobs(2): " << User_knobs (1)
-                              << ", cols with > max(16,"
-                              << knobs [COLAMD_DENSE_COL] << "*sqrt(size(A)))"
+                              << ", cols with > max (16,"
+                              << knobs[COLAMD_DENSE_COL] << "*sqrt (size(A)))"
                               << " entries removed\n";
               else
                 octave_stdout << "knobs(2): " << User_knobs (1)
@@ -380,12 +380,12 @@
       // Allocate workspace for colamd
       OCTAVE_LOCAL_BUFFER (octave_idx_type, p, n_col+1);
       for (octave_idx_type i = 0; i < n_col+1; i++)
-        p[i] = cidx [i];
+        p[i] = cidx[i];
 
       octave_idx_type Alen = COLAMD_NAME (_recommended) (nnz, n_row, n_col);
       OCTAVE_LOCAL_BUFFER (octave_idx_type, A, Alen);
       for (octave_idx_type i = 0; i < nnz; i++)
-        A[i] = ridx [i];
+        A[i] = ridx[i];
 
       // Order the columns (destroys A)
       OCTAVE_LOCAL_BUFFER (octave_idx_type, stats, COLAMD_STATS);
@@ -415,7 +415,7 @@
       // return the permutation vector
       NDArray out_perm (dim_vector (1, n_col));
       for (octave_idx_type i = 0; i < n_col; i++)
-        out_perm(i) = p [colbeg [i]] + 1;
+        out_perm(i) = p[colbeg[i]] + 1;
 
       retval(0) = out_perm;
 
@@ -428,7 +428,7 @@
         {
           NDArray out_stats (dim_vector (1, COLAMD_STATS));
           for (octave_idx_type i = 0 ; i < COLAMD_STATS ; i++)
-            out_stats (i) = stats [i] ;
+            out_stats(i) = stats[i] ;
           retval(1) = out_stats;
 
           // fix stats (5) and (6), for 1-based information on
@@ -464,7 +464,7 @@
 \n\
 @var{knobs} is an optional one- to two-element input vector.  If @var{S} is\n\
 n-by-n, then rows and columns with more than\n\
-@code{max(16,@var{knobs}(1)*sqrt(n))} entries are removed prior to ordering,\n\
+@code{max (16,@var{knobs}(1)*sqrt(n))} entries are removed prior to ordering,\n\
 and ordered last in the output permutation @var{p}.  No rows/columns are\n\
 removed if @code{@var{knobs}(1) < 0}.  If @code{@var{knobs} (2)} is nonzero,\n\
 @code{stats} and @var{knobs} are printed.  The default is @code{@var{knobs}\n\
@@ -534,7 +534,7 @@
           int nel_User_knobs = User_knobs.length ();
 
           if (nel_User_knobs > 0)
-            knobs [COLAMD_DENSE_ROW] = User_knobs (COLAMD_DENSE_ROW);
+            knobs[COLAMD_DENSE_ROW] = User_knobs(COLAMD_DENSE_ROW);
           if (nel_User_knobs > 1)
             spumoni = static_cast<int> (User_knobs (1));
         }
@@ -542,7 +542,7 @@
       // print knob settings if spumoni is set
       if (spumoni > 0)
         octave_stdout << "symamd: dense row/col fraction: "
-                      << knobs [COLAMD_DENSE_ROW] << std::endl;
+                      << knobs[COLAMD_DENSE_ROW] << std::endl;
 
       octave_idx_type n_row, n_col;
       octave_idx_type *ridx, *cidx;
@@ -608,7 +608,7 @@
       // return the permutation vector
       NDArray out_perm (dim_vector (1, n_col));
       for (octave_idx_type i = 0; i < n_col; i++)
-        out_perm(i) = perm [post [i]] + 1;
+        out_perm(i) = perm[post[i]] + 1;
 
       retval(0) = out_perm;
 
@@ -621,7 +621,7 @@
         {
           NDArray out_stats (dim_vector (1, COLAMD_STATS));
           for (octave_idx_type i = 0 ; i < COLAMD_STATS ; i++)
-            out_stats (i) = stats [i] ;
+            out_stats(i) = stats[i] ;
           retval(1) = out_stats;
 
           // fix stats (5) and (6), for 1-based information on
@@ -651,7 +651,7 @@
 is assumed to be symmetric and the symmetric elimination tree is\n\
 returned.  The argument @var{typ} controls whether a symmetric or\n\
 column elimination tree is returned.  Valid values of @var{typ} are\n\
-'sym' or 'col', for symmetric or column elimination tree respectively\n\
+\"sym\" or \"col\", for symmetric or column elimination tree respectively\n\
 \n\
 Called with a second argument, @code{etree} also returns the postorder\n\
 permutations on the tree.\n\
rename from src/DLD-FUNCTIONS/config-module.awk
rename to libinterp/dldfcn/config-module.awk
--- a/src/DLD-FUNCTIONS/config-module.awk
+++ b/libinterp/dldfcn/config-module.awk
@@ -5,10 +5,10 @@
   print "## DO NOT EDIT -- generated from module-files by config-module.awk";
   print ""
   print "EXTRA_DIST += \\"
-  print "  DLD-FUNCTIONS/config-module.sh \\"
-  print "  DLD-FUNCTIONS/config-module.awk \\"
-  print "  DLD-FUNCTIONS/module-files \\"
-  print "  DLD-FUNCTIONS/oct-qhull.h"
+  print "  dldfcn/config-module.sh \\"
+  print "  dldfcn/config-module.awk \\"
+  print "  dldfcn/module-files \\"
+  print "  dldfcn/oct-qhull.h"
   print ""
 }
 /^#.*/ { next; }
@@ -20,20 +20,20 @@
   libraries[nfiles] = $4;
 } END {
   sep = " \\\n";
-  print "DLD_FUNCTIONS_SRC = \\";
+  print "DLDFCN_SRC = \\";
   for (i = 1; i <= nfiles; i++) {
     if (i == nfiles)
       sep = "\n";
-    printf ("  DLD-FUNCTIONS/%s%s", files[i], sep);
+    printf ("  dldfcn/%s%s", files[i], sep);
   }
   print "";
 
   sep = " \\\n";
-  print "DLD_FUNCTIONS_LIBS = $(DLD_FUNCTIONS_SRC:.cc=.la)";
+  print "DLDFCN_LIBS = $(DLDFCN_SRC:.cc=.la)";
   print "";
   print "if AMCOND_ENABLE_DYNAMIC_LINKING";
   print "";
-  print "octlib_LTLIBRARIES += $(DLD_FUNCTIONS_LIBS)";
+  print "octlib_LTLIBRARIES += $(DLDFCN_LIBS)";
   print "";
   print "## Use stamp files to avoid problems with checking timestamps";
   print "## of symbolic links";
@@ -41,18 +41,18 @@
   for (i = 1; i <= nfiles; i++) {
     basename = files[i];
     sub (/\.cc$/, "", basename);
-    printf ("DLD-FUNCTIONS/$(am__leading_dot)%s.oct-stamp: DLD-FUNCTIONS/%s.la\n", basename, basename);
+    printf ("dldfcn/$(am__leading_dot)%s.oct-stamp: dldfcn/%s.la\n", basename, basename);
     print "\trm -f $(<:.la=.oct)";
     print "\tla=$(<F) && \\";
     print "\t  of=$(<F:.la=.oct) && \\";
-    print "\t  cd DLD-FUNCTIONS && \\";
+    print "\t  cd dldfcn && \\";
     print "\t  $(LN_S) .libs/`$(SED) -n -e \"s/dlname='\\([^']*\\)'/\\1/p\" < $$la` $$of && \\";
     print "\t  touch $(@F)";
     print "";
   }
   print "else";
   print "";
-  print "noinst_LTLIBRARIES = $(DLD_FUNCTIONS_LIBS)";
+  print "noinst_LTLIBRARIES += $(DLDFCN_LIBS)";
   print "";
   print "endif";
 
@@ -60,18 +60,18 @@
     basename = files[i];
     sub (/\.cc$/, "", basename);
     print "";
-    printf ("DLD_FUNCTIONS_%s_la_SOURCES = DLD-FUNCTIONS/%s\n",
+    printf ("dldfcn_%s_la_SOURCES = dldfcn/%s\n",
 	    basename, files[i]);
     if (cppflags[i])
       {
-        printf ("DLD-FUNCTIONS/%s.df: CPPFLAGS += %s\n",
+        printf ("dldfcn/%s.df: CPPFLAGS += %s\n",
                 basename, cppflags[i]);
-        printf ("DLD_FUNCTIONS_%s_la_CPPFLAGS = $(AM_CPPFLAGS) %s\n",
+        printf ("dldfcn_%s_la_CPPFLAGS = $(AM_CPPFLAGS) %s\n",
                 basename, cppflags[i]);
       }
-    printf ("DLD_FUNCTIONS_%s_la_LDFLAGS = -avoid-version -module $(NO_UNDEFINED_LDFLAG) %s $(OCT_LINK_OPTS)\n",
+    printf ("dldfcn_%s_la_LDFLAGS = -avoid-version -module $(NO_UNDEFINED_LDFLAG) %s $(OCT_LINK_OPTS)\n",
             basename, ldflags[i]);
-    printf ("DLD_FUNCTIONS_%s_la_LIBADD = liboctinterp.la ../liboctave/liboctave.la ../libcruft/libcruft.la %s $(OCT_LINK_DEPS)\n",
+    printf ("dldfcn_%s_la_LIBADD = $(DLD_LIBOCTINTERP_LIBADD) ../liboctave/liboctave.la %s $(OCT_LINK_DEPS)\n",
             basename, libraries[i]);
   }
 }
rename from src/DLD-FUNCTIONS/config-module.sh
rename to libinterp/dldfcn/config-module.sh
--- a/src/DLD-FUNCTIONS/config-module.sh
+++ b/libinterp/dldfcn/config-module.sh
@@ -12,7 +12,7 @@
 
 move_if_change="$top_srcdir/build-aux/move-if-change"
 
-dld_dir=$top_srcdir/src/DLD-FUNCTIONS
+dld_dir=$top_srcdir/libinterp/dldfcn
 
 $AWK -f $dld_dir/config-module.awk < $dld_dir/module-files > $dld_dir/module.mk-t
 
rename from src/DLD-FUNCTIONS/convhulln.cc
rename to libinterp/dldfcn/convhulln.cc
--- a/src/DLD-FUNCTIONS/convhulln.cc
+++ b/libinterp/dldfcn/convhulln.cc
@@ -295,7 +295,7 @@
 %! assert (h, [1 2 4; 1 2 6; 1 4 8; 1 5 6; 1 5 8; 2 3 4; 2 3 7; 2 6 7; 3 4 7; 4 7 8; 5 6 7; 5 7 8]);
 %! assert (v, 1, 10*eps);
 %! [h2, v2] = convhulln (cube); % Test defaut option = "Qt"
-%! assert (size (h2), size (h))
+%! assert (size (h2), size (h));
 %! h2 = sortrows (sort (h2, 2), [1:3]);
 %! assert (h2, h);
 %! assert (v2, v, 10*eps);
rename from src/DLD-FUNCTIONS/dmperm.cc
rename to libinterp/dldfcn/dmperm.cc
--- a/src/DLD-FUNCTIONS/dmperm.cc
+++ b/libinterp/dldfcn/dmperm.cc
@@ -37,7 +37,7 @@
 #include "SparseQR.h"
 #include "SparseCmplxQR.h"
 
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
 #define CXSPARSE_NAME(name) cs_dl ## name
 #else
 #define CXSPARSE_NAME(name) cs_di ## name
@@ -48,7 +48,7 @@
 {
   RowVector ret (n);
   for (octave_idx_type i = 0; i < n; i++)
-    ret.xelem(i) = p[i] + 1;
+    ret.xelem (i) = p[i] + 1;
   return ret;
 }
 
@@ -70,14 +70,14 @@
   if (arg.is_real_type ())
     {
       m = arg.sparse_matrix_value ();
-      csm.nzmax = m.nnz();
+      csm.nzmax = m.nnz ();
       csm.p = m.xcidx ();
       csm.i = m.xridx ();
     }
   else
     {
       cm = arg.sparse_complex_matrix_value ();
-      csm.nzmax = cm.nnz();
+      csm.nzmax = cm.nnz ();
       csm.p = cm.xcidx ();
       csm.i = cm.xridx ();
     }
@@ -153,7 +153,7 @@
 @seealso{colamd, ccolamd}\n\
 @end deftypefn")
 {
-  int nargin = args.length();
+  int nargin = args.length ();
   octave_value_list retval;
 
   if (nargin != 1)
@@ -172,20 +172,19 @@
 }
 
 /*
-
 %!testif HAVE_CXSPARSE
-%! n=20;
-%! a=speye(n,n);a=a(randperm(n),:);
-%! assert(a(dmperm(a),:),speye(n))
+%! n = 20;
+%! a = speye (n,n);
+%! a = a(randperm (n),:);
+%! assert (a(dmperm (a),:), speye (n));
 
 %!testif HAVE_CXSPARSE
-%! n=20;
-%! d=0.2;
-%! a=tril(sprandn(n,n,d),-1)+speye(n,n);
-%! a=a(randperm(n),randperm(n));
-%! [p,q,r,s]=dmperm(a);
-%! assert(tril(a(p,q),-1),sparse(n,n))
-
+%! n = 20;
+%! d = 0.2;
+%! a = tril (sprandn (n,n,d), -1) + speye (n,n);
+%! a = a(randperm (n), randperm (n));
+%! [p,q,r,s] = dmperm (a);
+%! assert (tril (a(p,q), -1), sparse (n, n));
 */
 
 DEFUN_DLD (sprank, args, nargout,
@@ -202,7 +201,7 @@
 @seealso{dmperm}\n\
 @end deftypefn")
 {
-  int nargin = args.length();
+  int nargin = args.length ();
   octave_value_list retval;
 
   if (nargin != 1)
@@ -221,11 +220,10 @@
 }
 
 /*
-
-%!error(sprank(1,2));
+%!testif HAVE_CXSPARSE
+%! assert (sprank (speye (20)), 20)
 %!testif HAVE_CXSPARSE
-%! assert(sprank(speye(20)), 20)
-%!testif HAVE_CXSPARSE
-%! assert(sprank([1,0,2,0;2,0,4,0]),2)
+%! assert (sprank ([1,0,2,0;2,0,4,0]), 2)
 
+%!error sprank (1,2)
 */
rename from src/DLD-FUNCTIONS/eigs.cc
rename to libinterp/dldfcn/eigs.cc
--- a/src/DLD-FUNCTIONS/eigs.cc
+++ b/libinterp/dldfcn/eigs.cc
@@ -184,32 +184,32 @@
 @var{sigma} is a string, it must have one of the following values.\n\
 \n\
 @table @asis\n\
-@item 'lm'\n\
+@item \"lm\"\n\
 Largest Magnitude (default).\n\
 \n\
-@item 'sm'\n\
+@item \"sm\"\n\
 Smallest Magnitude.\n\
 \n\
-@item 'la'\n\
+@item \"la\"\n\
 Largest Algebraic (valid only for real symmetric problems).\n\
 \n\
-@item 'sa'\n\
+@item \"sa\"\n\
 Smallest Algebraic (valid only for real symmetric problems).\n\
 \n\
-@item 'be'\n\
+@item \"be\"\n\
 Both Ends, with one more from the high-end if @var{k} is odd (valid only for\n\
 real symmetric problems).\n\
 \n\
-@item 'lr'\n\
+@item \"lr\"\n\
 Largest Real part (valid only for complex or unsymmetric problems).\n\
 \n\
-@item 'sr'\n\
+@item \"sr\"\n\
 Smallest Real part (valid only for complex or unsymmetric problems).\n\
 \n\
-@item 'li'\n\
+@item \"li\"\n\
 Largest Imaginary part (valid only for complex or unsymmetric problems).\n\
 \n\
-@item 'si'\n\
+@item \"si\"\n\
 Smallest Imaginary part (valid only for complex or unsymmetric problems).\n\
 @end table\n\
 \n\
@@ -258,6 +258,7 @@
 default is @code{1:@var{n}}.\n\
 \n\
 @end table\n\
+\n\
 It is also possible to represent @var{A} by a function denoted @var{af}.\n\
 @var{af} must be followed by a scalar argument @var{n} defining the length\n\
 of the vector argument accepted by @var{af}.  @var{af} can be\n\
@@ -270,10 +271,10 @@
 \n\
 @table @code\n\
 @item A * x\n\
-if @var{sigma} is not given or is a string other than 'sm'.\n\
+if @var{sigma} is not given or is a string other than \"sm\".\n\
 \n\
 @item A \\ x\n\
-if @var{sigma} is 0 or 'sm'.\n\
+if @var{sigma} is 0 or \"sm\".\n\
 \n\
 @item (A - sigma * I) \\ x\n\
 for the standard eigenvalue problem, where @code{I} is the identity matrix of\n\
@@ -328,7 +329,7 @@
   bool a_is_sparse = false;
   ColumnVector permB;
   int arg_offset = 0;
-  double tol = DBL_EPSILON;
+  double tol = std::numeric_limits<double>::epsilon ();
   int maxit = 300;
   int disp = 0;
   octave_idx_type p = -1;
@@ -346,7 +347,7 @@
   if (call_depth > 1)
     {
       error ("eigs: invalid recursive call");
-      if (fcn_name.length())
+      if (fcn_name.length ())
         clear_function (fcn_name);
       return retval;
     }
@@ -393,11 +394,11 @@
         {
           if (args(0).is_sparse_type ())
             {
-              ascm = (args(0).sparse_complex_matrix_value());
+              ascm = (args(0).sparse_complex_matrix_value ());
               a_is_sparse = true;
             }
           else
-            acm = (args(0).complex_matrix_value());
+            acm = (args(0).complex_matrix_value ());
           a_is_complex = true;
           symmetric = false; // ARPACK doesn't special case complex symmetric
           sym_tested = true;
@@ -406,12 +407,12 @@
         {
           if (args(0).is_sparse_type ())
             {
-              asmm = (args(0).sparse_matrix_value());
+              asmm = (args(0).sparse_matrix_value ());
               a_is_sparse = true;
             }
           else
             {
-              amm = (args(0).matrix_value());
+              amm = (args(0).matrix_value ());
             }
         }
 
@@ -547,9 +548,9 @@
   if (!sym_tested && !have_a_fun)
     {
       if (a_is_sparse)
-        symmetric = asmm.is_symmetric();
+        symmetric = asmm.is_symmetric ();
       else
-        symmetric = amm.is_symmetric();
+        symmetric = amm.is_symmetric ();
     }
 
   if (have_b)
@@ -613,7 +614,7 @@
             }
 
           if (nargout < 2)
-            retval (0) = eig_val;
+            retval(0) = eig_val;
           else
             {
               retval(2) = double (info);
@@ -646,7 +647,7 @@
             }
 
           if (nargout < 2)
-            retval (0) = eig_val;
+            retval(0) = eig_val;
           else
             {
               retval(2) = double (info);
@@ -694,7 +695,7 @@
                 }
 
               if (nargout < 2)
-                retval (0) = eig_val;
+                retval(0) = eig_val;
               else
                 {
                   retval(2) = double (info);
@@ -740,7 +741,7 @@
                 }
 
               if (nargout < 2)
-                retval (0) = eig_val;
+                retval(0) = eig_val;
               else
                 {
                   retval(2) = double (info);
@@ -769,764 +770,752 @@
 /* #### SPARSE MATRIX VERSIONS #### */
 
 /*
-
-%% Real positive definite tests, n must be even
+## Real positive definite tests, n must be even
 %!shared n, k, A, d0, d2
 %! n = 20;
 %! k = 4;
-%! A = sparse([3:n,1:n,1:(n-2)],[1:(n-2),1:n,3:n],[ones(1,n-2),4*ones(1,n),ones(1,n-2)]);
+%! A = sparse ([3:n,1:n,1:(n-2)],[1:(n-2),1:n,3:n],[ones(1,n-2),4*ones(1,n),ones(1,n-2)]);
 %! d0 = eig (A);
 %! d2 = sort (d0);
-%! [~, idx] = sort (abs(d0));
+%! [~, idx] = sort (abs (d0));
 %! d0 = d0(idx);
-%! rand("state", 42); % initialize generator to make eigs behavior reproducible
+%! rand ("state", 42); # initialize generator to make eigs behavior reproducible
 %!testif HAVE_ARPACK
 %! d1 = eigs (A, k);
 %! assert (d1, d0(end:-1:(end-k+1)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A,k+1);
-%! assert (d1, d0(end:-1:(end-k)),1e-11);
+%! d1 = eigs (A, k+1);
+%! assert (d1, d0(end:-1:(end-k)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'lm');
+%! d1 = eigs (A, k, "lm");
 %! assert (d1, d0(end:-1:(end-k+1)), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! d1 = eigs (A, k, 'sm');
+%! d1 = eigs (A, k, "sm");
 %! assert (d1, d0(k:-1:1), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'la');
+%! d1 = eigs (A, k, "la");
 %! assert (d1, d2(end:-1:(end-k+1)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'sa');
+%! d1 = eigs (A, k, "sa");
 %! assert (d1, d2(1:k), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'be');
+%! d1 = eigs (A, k, "be");
 %! assert (d1, d2([1:floor(k/2), (end - ceil(k/2) + 1):end]), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k+1, 'be');
+%! d1 = eigs (A, k+1, "be");
 %! assert (d1, d2([1:floor((k+1)/2), (end - ceil((k+1)/2) + 1):end]), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
 %! d1 = eigs (A, k, 4.1);
-%! [~,idx0] = sort (abs(d0 - 4.1));
-%! [~,idx1] = sort (abs(d1 - 4.1));
+%! [~, idx0] = sort (abs (d0 - 4.1));
+%! [~, idx1] = sort (abs (d1 - 4.1));
 %! assert (d1(idx1), d0(idx0(1:k)), 1e-11);
 %!testif HAVE_ARPACK, HAVE_CHOLMOD
-%! d1 = eigs(A, speye(n), k, 'lm');
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! d1 = eigs (A, speye (n), k, "lm");
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! assert (eigs(A,k,4.1), eigs(A,speye(n),k,4.1), 1e-11);
+%! assert (eigs (A, k, 4.1), eigs (A, speye (n), k, 4.1), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
-%! d1 = eigs(A, speye(n), k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.cholB = true;
+%! d1 = eigs (A, speye (n), k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
+%! opts.cholB = true;
 %! q = [2:n,1];
-%! opts.permB=q;
-%! d1 = eigs(A, speye(n)(q,q), k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.permB = q;
+%! d1 = eigs (A, speye (n)(q,q), k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! opts.cholB=true;
-%! d1 = eigs(A, speye(n), k, 4.1, opts);
-%! assert (abs(d1), eigs(A,k,4.1), 1e-11);
+%! opts.cholB = true;
+%! d1 = eigs (A, speye (n), k, 4.1, opts);
+%! assert (abs (d1), eigs (A, k, 4.1), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! opts.cholB=true;
+%! opts.cholB = true;
 %! q = [2:n,1];
-%! opts.permB=q;
-%! d1 = eigs(A, speye(n)(q,q), k, 4.1, opts);
-%! assert (abs(d1), eigs(A,k,4.1), 1e-11);
+%! opts.permB = q;
+%! d1 = eigs (A, speye (n)(q,q), k, 4.1, opts);
+%! assert (abs (d1), eigs (A, k, 4.1), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! assert (eigs(A,k,4.1), eigs(A,speye(n),k,4.1), 1e-11);
+%! assert (eigs (A, k, 4.1), eigs (A, speye (n), k, 4.1), 1e-11);
 %!testif HAVE_ARPACK
 %! fn = @(x) A * x;
-%! opts.issym = 1; opts.isreal = 1;
-%! d1 = eigs (fn, n, k, 'lm', opts);
+%! opts.issym = 1;  opts.isreal = 1;
+%! d1 = eigs (fn, n, k, "lm", opts);
 %! assert (d1, d0(end:-1:(end-k+1)), 1e-11);
 %!testif HAVE_ARPACK
 %! fn = @(x) A \ x;
-%! opts.issym = 1; opts.isreal = 1;
-%! d1 = eigs (fn, n, k, 'sm', opts);
+%! opts.issym = 1;  opts.isreal = 1;
+%! d1 = eigs (fn, n, k, "sm", opts);
 %! assert (d1, d0(k:-1:1), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! fn = @(x) (A - 4.1 * eye(n)) \ x;
-%! opts.issym = 1; opts.isreal = 1;
+%! fn = @(x) (A - 4.1 * eye (n)) \ x;
+%! opts.issym = 1;  opts.isreal = 1;
 %! d1 = eigs (fn, n, k, 4.1, opts);
-%! assert (d1, eigs(A,k,4.1), 1e-11);
+%! assert (d1, eigs (A, k, 4.1), 1e-11);
 %!testif HAVE_ARPACK
 %! AA = speye (10);
 %! fn = @(x) AA * x;
-%! opts.issym = 1; opts.isreal = 1;
-%! assert (eigs (fn, 10, AA, 3, 'lm', opts), [1; 1; 1],10*eps);
+%! opts.issym = 1;  opts.isreal = 1;
+%! assert (eigs (fn, 10, AA, 3, "lm", opts), [1; 1; 1], 10*eps);
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'lm');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "lm");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! [v1,d1] = eigs(A, k, 'sm');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "sm");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'la');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "la");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'sa');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "sa");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'be');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "be");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
-
 */
 
 /*
-
-%% Real unsymmetric tests
+## Real unsymmetric tests
 %!shared n, k, A, d0
 %! n = 20;
 %! k = 4;
-%! A =  sparse([3:n,1:n,1:(n-2)],[1:(n-2),1:n,3:n],[ones(1,n-2),1:n,-ones(1,n-2)]);
+%! A =  sparse ([3:n,1:n,1:(n-2)],[1:(n-2),1:n,3:n],[ones(1,n-2),1:n,-ones(1,n-2)]);
 %! d0 = eig (A);
-%! [~, idx] = sort (abs(d0));
+%! [~, idx] = sort (abs (d0));
 %! d0 = d0(idx);
-%! rand("state", 42); % initialize generator to make eigs behavior reproducible
+%! rand ("state", 42); % initialize generator to make eigs behavior reproducible
 %!testif HAVE_ARPACK
 %! d1 = eigs (A, k);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A,k+1);
-%! assert (abs(d1), abs(d0(end:-1:(end-k))),1e-11);
+%! d1 = eigs (A, k+1);
+%! assert (abs (d1), abs (d0(end:-1:(end-k))),1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'lm');
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! d1 = eigs (A, k, "lm");
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! d1 = eigs (A, k, 'sm');
-%! assert (abs(d1), abs(d0(1:k)), 1e-11);
+%! d1 = eigs (A, k, "sm");
+%! assert (abs (d1), abs (d0(1:k)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'lr');
-%! [~, idx] = sort (real(d0));
+%! d1 = eigs (A, k, "lr");
+%! [~, idx] = sort (real (d0));
 %! d2 = d0(idx);
-%! assert (real(d1), real(d2(end:-1:(end-k+1))), 1e-11);
+%! assert (real (d1), real (d2(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'sr');
-%! [~, idx] = sort (real(abs(d0)));
+%! d1 = eigs (A, k, "sr");
+%! [~, idx] = sort (real (abs (d0)));
 %! d2 = d0(idx);
-%! assert (real(d1), real(d2(1:k)), 1e-11);
+%! assert (real (d1), real (d2(1:k)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'li');
-%! [~, idx] = sort (imag(abs(d0)));
+%! d1 = eigs (A, k, "li");
+%! [~, idx] = sort (imag (abs (d0)));
 %! d2 = d0(idx);
-%! assert (sort(imag(d1)), sort(imag(d2(end:-1:(end-k+1)))), 1e-11);
+%! assert (sort (imag (d1)), sort (imag (d2(end:-1:(end-k+1)))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'si');
-%! [~, idx] = sort (imag(abs(d0)));
+%! d1 = eigs (A, k, "si");
+%! [~, idx] = sort (imag (abs (d0)));
 %! d2 = d0(idx);
-%! assert (sort(imag(d1)), sort(imag(d2(1:k))), 1e-11);
+%! assert (sort (imag (d1)), sort (imag (d2(1:k))), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
 %! d1 = eigs (A, k, 4.1);
-%! [~,idx0] = sort (abs(d0 - 4.1));
-%! [~,idx1] = sort (abs(d1 - 4.1));
-%! assert (abs(d1(idx1)), abs(d0(idx0(1:k))), 1e-11);
-%! assert (sort(imag(d1(idx1))), sort(imag(d0(idx0(1:k)))), 1e-11);
+%! [~, idx0] = sort (abs (d0 - 4.1));
+%! [~, idx1] = sort (abs (d1 - 4.1));
+%! assert (abs (d1(idx1)), abs (d0(idx0(1:k))), 1e-11);
+%! assert (sort (imag (d1(idx1))), sort (imag (d0(idx0(1:k)))), 1e-11);
 %!testif HAVE_ARPACK, HAVE_CHOLMOD
-%! d1 = eigs(A, speye(n), k, 'lm');
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! d1 = eigs (A, speye (n), k, "lm");
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
-%! d1 = eigs(A, speye(n), k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.cholB = true;
+%! d1 = eigs (A, speye (n), k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
+%! opts.cholB = true;
 %! q = [2:n,1];
-%! opts.permB=q;
-%! d1 = eigs(A, speye(n)(q,q), k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.permB = q;
+%! d1 = eigs (A, speye (n)(q,q), k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! opts.cholB=true;
-%! d1 = eigs(A, speye(n), k, 4.1, opts);
-%! assert (abs(d1), eigs(A,k,4.1), 1e-11);
+%! opts.cholB = true;
+%! d1 = eigs (A, speye (n), k, 4.1, opts);
+%! assert (abs (d1), eigs (A, k, 4.1), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! opts.cholB=true;
+%! opts.cholB = true;
 %! q = [2:n,1];
-%! opts.permB=q;
-%! d1 = eigs(A, speye(n)(q,q), k, 4.1, opts);
-%! assert (abs(d1), eigs(A,k,4.1), 1e-11);
+%! opts.permB = q;
+%! d1 = eigs (A, speye (n)(q,q), k, 4.1, opts);
+%! assert (abs (d1), eigs (A, k, 4.1), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! assert (abs(eigs(A,k,4.1)), abs(eigs(A,speye(n),k,4.1)), 1e-11);
+%! assert (abs (eigs (A, k, 4.1)), abs (eigs (A, speye (n), k, 4.1)), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! assert (sort(imag(eigs(A,k,4.1))), sort(imag(eigs(A,speye(n),k,4.1))), 1e-11);
+%! assert (sort (imag (eigs (A, k, 4.1))), sort (imag (eigs (A, speye (n), k, 4.1))), 1e-11);
 %!testif HAVE_ARPACK
 %! fn = @(x) A * x;
-%! opts.issym = 0; opts.isreal = 1;
-%! d1 = eigs (fn, n, k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.issym = 0;  opts.isreal = 1;
+%! d1 = eigs (fn, n, k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
 %! fn = @(x) A \ x;
-%! opts.issym = 0; opts.isreal = 1;
-%! d1 = eigs (fn, n, k, 'sm', opts);
-%! assert (abs(d1), d0(1:k), 1e-11);
+%! opts.issym = 0;  opts.isreal = 1;
+%! d1 = eigs (fn, n, k, "sm", opts);
+%! assert (abs (d1), d0(1:k), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! fn = @(x) (A - 4.1 * eye(n)) \ x;
-%! opts.issym = 0; opts.isreal = 1;
+%! fn = @(x) (A - 4.1 * eye (n)) \ x;
+%! opts.issym = 0;  opts.isreal = 1;
 %! d1 = eigs (fn, n, k, 4.1, opts);
-%! assert (abs(d1), eigs(A,k,4.1), 1e-11);
+%! assert (abs (d1), eigs (A, k, 4.1), 1e-11);
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'lm');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "lm");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! [v1,d1] = eigs(A, k, 'sm');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "sm");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'lr');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "lr");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'sr');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "sr");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'li');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "li");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'si');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "si");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
-
 */
 
 /*
-
-%% Complex hermitian tests
+## Complex hermitian tests
 %!shared n, k, A, d0
 %! n = 20;
 %! k = 4;
-%! A = sparse([3:n,1:n,1:(n-2)],[1:(n-2),1:n,3:n],[1i*ones(1,n-2),4*ones(1,n),-1i*ones(1,n-2)]);
+%! A = sparse ([3:n,1:n,1:(n-2)],[1:(n-2),1:n,3:n],[1i*ones(1,n-2),4*ones(1,n),-1i*ones(1,n-2)]);
 %! d0 = eig (A);
-%! [~, idx] = sort (abs(d0));
+%! [~, idx] = sort (abs (d0));
 %! d0 = d0(idx);
-%! rand("state", 42); % initialize generator to make eigs behavior reproducible
+%! rand ("state", 42); % initialize generator to make eigs behavior reproducible
 %!testif HAVE_ARPACK
 %! d1 = eigs (A, k);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A,k+1);
-%! assert (abs(d1), abs(d0(end:-1:(end-k))),1e-11);
+%! d1 = eigs (A, k+1);
+%! assert (abs (d1), abs (d0(end:-1:(end-k))),1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'lm');
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! d1 = eigs (A, k, "lm");
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! d1 = eigs (A, k, 'sm');
-%! assert (abs(d1), abs(d0(1:k)), 1e-11);
+%! d1 = eigs (A, k, "sm");
+%! assert (abs (d1), abs (d0(1:k)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'lr');
-%! [~, idx] = sort (real(abs(d0)));
+%! d1 = eigs (A, k, "lr");
+%! [~, idx] = sort (real (abs (d0)));
 %! d2 = d0(idx);
-%! assert (real(d1), real(d2(end:-1:(end-k+1))), 1e-11);
+%! assert (real (d1), real (d2(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'sr');
-%! [~, idx] = sort (real(abs(d0)));
+%! d1 = eigs (A, k, "sr");
+%! [~, idx] = sort (real (abs (d0)));
 %! d2 = d0(idx);
-%! assert (real(d1), real(d2(1:k)), 1e-11);
+%! assert (real (d1), real (d2(1:k)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'li');
-%! [~, idx] = sort (imag(abs(d0)));
+%! d1 = eigs (A, k, "li");
+%! [~, idx] = sort (imag (abs (d0)));
 %! d2 = d0(idx);
-%! assert (sort(imag(d1)), sort(imag(d2(end:-1:(end-k+1)))), 1e-11);
+%! assert (sort (imag (d1)), sort (imag (d2(end:-1:(end-k+1)))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'si');
-%! [~, idx] = sort (imag(abs(d0)));
+%! d1 = eigs (A, k, "si");
+%! [~, idx] = sort (imag (abs (d0)));
 %! d2 = d0(idx);
-%! assert (sort(imag(d1)), sort(imag(d2(1:k))), 1e-11);
+%! assert (sort (imag (d1)), sort (imag (d2(1:k))), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
 %! d1 = eigs (A, k, 4.1);
-%! [~,idx0] = sort (abs(d0 - 4.1));
-%! [~,idx1] = sort (abs(d1 - 4.1));
-%! assert (abs(d1(idx1)), abs(d0(idx0(1:k))), 1e-11);
-%! assert (sort(imag(d1(idx1))), sort(imag(d0(idx0(1:k)))), 1e-11);
+%! [~, idx0] = sort (abs (d0 - 4.1));
+%! [~, idx1] = sort (abs (d1 - 4.1));
+%! assert (abs (d1(idx1)), abs (d0(idx0(1:k))), 1e-11);
+%! assert (sort (imag (d1(idx1))), sort (imag (d0(idx0(1:k)))), 1e-11);
 %!testif HAVE_ARPACK, HAVE_CHOLMOD
-%! d1 = eigs(A, speye(n), k, 'lm');
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! d1 = eigs (A, speye (n), k, "lm");
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
-%! d1 = eigs(A, speye(n), k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.cholB = true;
+%! d1 = eigs (A, speye (n), k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
+%! opts.cholB = true;
 %! q = [2:n,1];
-%! opts.permB=q;
-%! d1 = eigs(A, speye(n)(q,q), k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.permB = q;
+%! d1 = eigs (A, speye (n)(q,q), k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! opts.cholB=true;
-%! d1 = eigs(A, speye(n), k, 4.1, opts);
-%! assert (abs(abs(d1)), abs(eigs(A,k,4.1)), 1e-11);
-%! assert (sort(imag(abs(d1))), sort(imag(eigs(A,k,4.1))), 1e-11);
+%! opts.cholB = true;
+%! d1 = eigs (A, speye (n), k, 4.1, opts);
+%! assert (abs (abs (d1)), abs (eigs (A, k, 4.1)), 1e-11);
+%! assert (sort (imag (abs (d1))), sort (imag (eigs (A, k, 4.1))), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! opts.cholB=true;
+%! opts.cholB = true;
 %! q = [2:n,1];
-%! opts.permB=q;
-%! d1 = eigs(A, speye(n)(q,q), k, 4.1, opts);
-%! assert (abs(abs(d1)), abs(eigs(A,k,4.1)), 1e-11);
-%! assert (sort(imag(abs(d1))), sort(imag(eigs(A,k,4.1))), 1e-11);
+%! opts.permB = q;
+%! d1 = eigs (A, speye (n)(q,q), k, 4.1, opts);
+%! assert (abs (abs (d1)), abs (eigs (A, k, 4.1)), 1e-11);
+%! assert (sort (imag (abs (d1))), sort (imag (eigs (A, k, 4.1))), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! assert (abs(eigs(A,k,4.1)), abs(eigs(A,speye(n),k,4.1)), 1e-11);
+%! assert (abs (eigs (A, k, 4.1)), abs (eigs (A, speye (n), k, 4.1)), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! assert (sort(imag(eigs(A,k,4.1))), sort(imag(eigs(A,speye(n),k,4.1))), 1e-11);
+%! assert (sort (imag (eigs (A, k, 4.1))), sort (imag (eigs (A, speye (n), k, 4.1))), 1e-11);
 %!testif HAVE_ARPACK
 %! fn = @(x) A * x;
-%! opts.issym = 0; opts.isreal = 0;
-%! d1 = eigs (fn, n, k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.issym = 0;  opts.isreal = 0;
+%! d1 = eigs (fn, n, k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
 %! fn = @(x) A \ x;
-%! opts.issym = 0; opts.isreal = 0;
-%! d1 = eigs (fn, n, k, 'sm', opts);
-%! assert (abs(d1), d0(1:k), 1e-11);
+%! opts.issym = 0;  opts.isreal = 0;
+%! d1 = eigs (fn, n, k, "sm", opts);
+%! assert (abs (d1), d0(1:k), 1e-11);
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! fn = @(x) (A - 4.1 * eye(n)) \ x;
-%! opts.issym = 0; opts.isreal = 0;
+%! fn = @(x) (A - 4.1 * eye (n)) \ x;
+%! opts.issym = 0;  opts.isreal = 0;
 %! d1 = eigs (fn, n, k, 4.1, opts);
-%! assert (abs(d1), eigs(A,k,4.1), 1e-11);
+%! assert (abs (d1), eigs (A, k, 4.1), 1e-11);
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'lm');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "lm");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! [v1,d1] = eigs(A, k, 'sm');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "sm");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'lr');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "lr");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'sr');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "sr");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'li');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "li");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'si');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "si");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*speye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*speye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
-
 */
 
 /* #### FULL MATRIX VERSIONS #### */
 
 /*
-
-%% Real positive definite tests, n must be even
+## Real positive definite tests, n must be even
 %!shared n, k, A, d0, d2
 %! n = 20;
 %! k = 4;
-%! A = full(sparse([3:n,1:n,1:(n-2)],[1:(n-2),1:n,3:n],[ones(1,n-2),4*ones(1,n),ones(1,n-2)]));
+%! A = full (sparse ([3:n,1:n,1:(n-2)],[1:(n-2),1:n,3:n],[ones(1,n-2),4*ones(1,n),ones(1,n-2)]));
 %! d0 = eig (A);
 %! d2 = sort (d0);
-%! [~, idx] = sort (abs(d0));
+%! [~, idx] = sort (abs (d0));
 %! d0 = d0(idx);
-%! rand("state", 42); % initialize generator to make eigs behavior reproducible
+%! rand ("state", 42); % initialize generator to make eigs behavior reproducible
 %!testif HAVE_ARPACK
 %! d1 = eigs (A, k);
 %! assert (d1, d0(end:-1:(end-k+1)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A,k+1);
+%! d1 = eigs (A, k+1);
 %! assert (d1, d0(end:-1:(end-k)),1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'lm');
+%! d1 = eigs (A, k, "lm");
 %! assert (d1, d0(end:-1:(end-k+1)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'sm');
+%! d1 = eigs (A, k, "sm");
 %! assert (d1, d0(k:-1:1), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'la');
+%! d1 = eigs (A, k, "la");
 %! assert (d1, d2(end:-1:(end-k+1)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'sa');
+%! d1 = eigs (A, k, "sa");
 %! assert (d1, d2(1:k), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'be');
+%! d1 = eigs (A, k, "be");
 %! assert (d1, d2([1:floor(k/2), (end - ceil(k/2) + 1):end]), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k+1, 'be');
+%! d1 = eigs (A, k+1, "be");
 %! assert (d1, d2([1:floor((k+1)/2), (end - ceil((k+1)/2) + 1):end]), 1e-11);
 %!testif HAVE_ARPACK
 %! d1 = eigs (A, k, 4.1);
-%! [~,idx0] = sort (abs(d0 - 4.1));
-%! [~,idx1] = sort (abs(d1 - 4.1));
+%! [~, idx0] = sort (abs (d0 - 4.1));
+%! [~, idx1] = sort (abs (d1 - 4.1));
 %! assert (d1(idx1), d0(idx0(1:k)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs(A, eye(n), k, 'lm');
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! d1 = eigs (A, eye (n), k, "lm");
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! assert (eigs(A,k,4.1), eigs(A,eye(n),k,4.1), 1e-11);
+%! assert (eigs (A, k, 4.1), eigs (A, eye (n), k, 4.1), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
-%! d1 = eigs(A, eye(n), k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.cholB = true;
+%! d1 = eigs (A, eye (n), k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
+%! opts.cholB = true;
 %! q = [2:n,1];
-%! opts.permB=q;
-%! d1 = eigs(A, eye(n)(q,q), k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.permB = q;
+%! d1 = eigs (A, eye (n)(q,q), k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
-%! d1 = eigs(A, eye(n), k, 4.1, opts);
-%! assert (abs(d1), eigs(A,k,4.1), 1e-11);
+%! opts.cholB = true;
+%! d1 = eigs (A, eye (n), k, 4.1, opts);
+%! assert (abs (d1), eigs (A, k, 4.1), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
+%! opts.cholB = true;
 %! q = [2:n,1];
-%! opts.permB=q;
-%! d1 = eigs(A, eye(n)(q,q), k, 4.1, opts);
-%! assert (abs(d1), eigs(A,k,4.1), 1e-11);
+%! opts.permB = q;
+%! d1 = eigs (A, eye (n)(q,q), k, 4.1, opts);
+%! assert (abs (d1), eigs (A, k, 4.1), 1e-11);
 %!testif HAVE_ARPACK
-%! assert (eigs(A,k,4.1), eigs(A,eye(n),k,4.1), 1e-11);
+%! assert (eigs (A, k, 4.1), eigs (A, eye (n), k, 4.1), 1e-11);
 %!testif HAVE_ARPACK
 %! fn = @(x) A * x;
-%! opts.issym = 1; opts.isreal = 1;
-%! d1 = eigs (fn, n, k, 'lm', opts);
+%! opts.issym = 1;  opts.isreal = 1;
+%! d1 = eigs (fn, n, k, "lm", opts);
 %! assert (d1, d0(end:-1:(end-k+1)), 1e-11);
 %!testif HAVE_ARPACK
 %! fn = @(x) A \ x;
-%! opts.issym = 1; opts.isreal = 1;
-%! d1 = eigs (fn, n, k, 'sm', opts);
+%! opts.issym = 1;  opts.isreal = 1;
+%! d1 = eigs (fn, n, k, "sm", opts);
 %! assert (d1, d0(k:-1:1), 1e-11);
 %!testif HAVE_ARPACK
-%! fn = @(x) (A - 4.1 * eye(n)) \ x;
-%! opts.issym = 1; opts.isreal = 1;
+%! fn = @(x) (A - 4.1 * eye (n)) \ x;
+%! opts.issym = 1;  opts.isreal = 1;
 %! d1 = eigs (fn, n, k, 4.1, opts);
-%! assert (d1, eigs(A,k,4.1), 1e-11);
+%! assert (d1, eigs (A, k, 4.1), 1e-11);
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'lm');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "lm");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'sm');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "sm");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'la');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "la");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'sa');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "sa");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'be');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "be");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
-
 */
 
 /*
-
-%% Real unsymmetric tests
+## Real unsymmetric tests
 %!shared n, k, A, d0
 %! n = 20;
 %! k = 4;
-%! A =  full(sparse([3:n,1:n,1:(n-2)],[1:(n-2),1:n,3:n],[ones(1,n-2),1:n,-ones(1,n-2)]));
+%! A =  full (sparse ([3:n,1:n,1:(n-2)],[1:(n-2),1:n,3:n],[ones(1,n-2),1:n,-ones(1,n-2)]));
 %! d0 = eig (A);
-%! [~, idx] = sort (abs(d0));
+%! [~, idx] = sort (abs (d0));
 %! d0 = d0(idx);
-%! rand("state", 42); % initialize generator to make eigs behavior reproducible
+%! rand ("state", 42); % initialize generator to make eigs behavior reproducible
 %!testif HAVE_ARPACK
 %! d1 = eigs (A, k);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A,k+1);
-%! assert (abs(d1), abs(d0(end:-1:(end-k))),1e-11);
+%! d1 = eigs (A, k+1);
+%! assert (abs (d1), abs (d0(end:-1:(end-k))),1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'lm');
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! d1 = eigs (A, k, "lm");
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'sm');
-%! assert (abs(d1), abs(d0(1:k)), 1e-11);
+%! d1 = eigs (A, k, "sm");
+%! assert (abs (d1), abs (d0(1:k)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'lr');
-%! [~, idx] = sort (real(d0));
+%! d1 = eigs (A, k, "lr");
+%! [~, idx] = sort (real (d0));
 %! d2 = d0(idx);
-%! assert (real(d1), real(d2(end:-1:(end-k+1))), 1e-11);
+%! assert (real (d1), real (d2(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'sr');
-%! [~, idx] = sort (real(abs(d0)));
+%! d1 = eigs (A, k, "sr");
+%! [~, idx] = sort (real (abs (d0)));
 %! d2 = d0(idx);
-%! assert (real(d1), real(d2(1:k)), 1e-11);
+%! assert (real (d1), real (d2(1:k)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'li');
-%! [~, idx] = sort (imag(abs(d0)));
+%! d1 = eigs (A, k, "li");
+%! [~, idx] = sort (imag (abs (d0)));
 %! d2 = d0(idx);
-%! assert (sort(imag(d1)), sort(imag(d2(end:-1:(end-k+1)))), 1e-11);
+%! assert (sort (imag (d1)), sort (imag (d2(end:-1:(end-k+1)))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'si');
-%! [~, idx] = sort (imag(abs(d0)));
+%! d1 = eigs (A, k, "si");
+%! [~, idx] = sort (imag (abs (d0)));
 %! d2 = d0(idx);
-%! assert (sort(imag(d1)), sort(imag(d2(1:k))), 1e-11);
+%! assert (sort (imag (d1)), sort (imag (d2(1:k))), 1e-11);
 %!testif HAVE_ARPACK
 %! d1 = eigs (A, k, 4.1);
-%! [~,idx0] = sort (abs(d0 - 4.1));
-%! [~,idx1] = sort (abs(d1 - 4.1));
-%! assert (abs(d1(idx1)), abs(d0(idx0(1:k))), 1e-11);
-%! assert (sort(imag(d1(idx1))), sort(imag(d0(idx0(1:k)))), 1e-11);
+%! [~, idx0] = sort (abs (d0 - 4.1));
+%! [~, idx1] = sort (abs (d1 - 4.1));
+%! assert (abs (d1(idx1)), abs (d0(idx0(1:k))), 1e-11);
+%! assert (sort (imag (d1(idx1))), sort (imag (d0(idx0(1:k)))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs(A, eye(n), k, 'lm');
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! d1 = eigs (A, eye (n), k, "lm");
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
-%! d1 = eigs(A, eye(n), k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.cholB = true;
+%! d1 = eigs (A, eye (n), k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
+%! opts.cholB = true;
 %! q = [2:n,1];
-%! opts.permB=q;
-%! d1 = eigs(A, eye(n)(q,q), k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.permB = q;
+%! d1 = eigs (A, eye (n)(q,q), k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
-%! d1 = eigs(A, eye(n), k, 4.1, opts);
-%! assert (abs(d1), eigs(A,k,4.1), 1e-11);
+%! opts.cholB = true;
+%! d1 = eigs (A, eye (n), k, 4.1, opts);
+%! assert (abs (d1), eigs (A, k, 4.1), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
+%! opts.cholB = true;
 %! q = [2:n,1];
-%! opts.permB=q;
-%! d1 = eigs(A, eye(n)(q,q), k, 4.1, opts);
-%! assert (abs(d1), eigs(A,k,4.1), 1e-11);
+%! opts.permB = q;
+%! d1 = eigs (A, eye (n)(q,q), k, 4.1, opts);
+%! assert (abs (d1), eigs (A, k, 4.1), 1e-11);
 %!testif HAVE_ARPACK
-%! assert (abs(eigs(A,k,4.1)), abs(eigs(A,eye(n),k,4.1)), 1e-11);
+%! assert (abs (eigs (A, k, 4.1)), abs (eigs (A, eye (n), k, 4.1)), 1e-11);
 %!testif HAVE_ARPACK
-%! assert (sort(imag(eigs(A,k,4.1))), sort(imag(eigs(A,eye(n),k,4.1))), 1e-11);
+%! assert (sort (imag (eigs (A, k, 4.1))), sort (imag (eigs (A, eye (n), k, 4.1))), 1e-11);
 %!testif HAVE_ARPACK
 %! fn = @(x) A * x;
-%! opts.issym = 0; opts.isreal = 1;
-%! d1 = eigs (fn, n, k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.issym = 0;  opts.isreal = 1;
+%! d1 = eigs (fn, n, k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
 %! fn = @(x) A \ x;
-%! opts.issym = 0; opts.isreal = 1;
-%! d1 = eigs (fn, n, k, 'sm', opts);
-%! assert (abs(d1), d0(1:k), 1e-11);
+%! opts.issym = 0;  opts.isreal = 1;
+%! d1 = eigs (fn, n, k, "sm", opts);
+%! assert (abs (d1), d0(1:k), 1e-11);
 %!testif HAVE_ARPACK
-%! fn = @(x) (A - 4.1 * eye(n)) \ x;
-%! opts.issym = 0; opts.isreal = 1;
+%! fn = @(x) (A - 4.1 * eye (n)) \ x;
+%! opts.issym = 0;  opts.isreal = 1;
 %! d1 = eigs (fn, n, k, 4.1, opts);
-%! assert (abs(d1), eigs(A,k,4.1), 1e-11);
+%! assert (abs (d1), eigs (A, k, 4.1), 1e-11);
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'lm');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "lm");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'sm');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "sm");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'lr');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "lr");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'sr');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "sr");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'li');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "li");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'si');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "si");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
-
 */
 
 /*
-
-%% Complex hermitian tests
+## Complex hermitian tests
 %!shared n, k, A, d0
 %! n = 20;
 %! k = 4;
-%! A = full(sparse([3:n,1:n,1:(n-2)],[1:(n-2),1:n,3:n],[1i*ones(1,n-2),4*ones(1,n),-1i*ones(1,n-2)]));
+%! A = full (sparse ([3:n,1:n,1:(n-2)],[1:(n-2),1:n,3:n],[1i*ones(1,n-2),4*ones(1,n),-1i*ones(1,n-2)]));
 %! d0 = eig (A);
-%! [~, idx] = sort (abs(d0));
+%! [~, idx] = sort (abs (d0));
 %! d0 = d0(idx);
-%! rand("state", 42); % initialize generator to make eigs behavior reproducible
+%! rand ("state", 42); % initialize generator to make eigs behavior reproducible
 %!testif HAVE_ARPACK
 %! d1 = eigs (A, k);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A,k+1);
-%! assert (abs(d1), abs(d0(end:-1:(end-k))),1e-11);
+%! d1 = eigs (A, k+1);
+%! assert (abs (d1), abs (d0(end:-1:(end-k))),1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'lm');
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! d1 = eigs (A, k, "lm");
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'sm');
-%! assert (abs(d1), abs(d0(1:k)), 1e-11);
+%! d1 = eigs (A, k, "sm");
+%! assert (abs (d1), abs (d0(1:k)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'lr');
-%! [~, idx] = sort (real(abs(d0)));
+%! d1 = eigs (A, k, "lr");
+%! [~, idx] = sort (real (abs (d0)));
 %! d2 = d0(idx);
-%! assert (real(d1), real(d2(end:-1:(end-k+1))), 1e-11);
+%! assert (real (d1), real (d2(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'sr');
-%! [~, idx] = sort (real(abs(d0)));
+%! d1 = eigs (A, k, "sr");
+%! [~, idx] = sort (real (abs (d0)));
 %! d2 = d0(idx);
-%! assert (real(d1), real(d2(1:k)), 1e-11);
+%! assert (real (d1), real (d2(1:k)), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'li');
-%! [~, idx] = sort (imag(abs(d0)));
+%! d1 = eigs (A, k, "li");
+%! [~, idx] = sort (imag (abs (d0)));
 %! d2 = d0(idx);
-%! assert (sort(imag(d1)), sort(imag(d2(end:-1:(end-k+1)))), 1e-11);
+%! assert (sort (imag (d1)), sort (imag (d2(end:-1:(end-k+1)))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs (A, k, 'si');
-%! [~, idx] = sort (imag(abs(d0)));
+%! d1 = eigs (A, k, "si");
+%! [~, idx] = sort (imag (abs (d0)));
 %! d2 = d0(idx);
-%! assert (sort(imag(d1)), sort(imag(d2(1:k))), 1e-11);
+%! assert (sort (imag (d1)), sort (imag (d2(1:k))), 1e-11);
 %!testif HAVE_ARPACK
 %! d1 = eigs (A, k, 4.1);
-%! [~,idx0] = sort (abs(d0 - 4.1));
-%! [~,idx1] = sort (abs(d1 - 4.1));
-%! assert (abs(d1(idx1)), abs(d0(idx0(1:k))), 1e-11);
-%! assert (sort(imag(d1(idx1))), sort(imag(d0(idx0(1:k)))), 1e-11);
+%! [~, idx0] = sort (abs (d0 - 4.1));
+%! [~, idx1] = sort (abs (d1 - 4.1));
+%! assert (abs (d1(idx1)), abs (d0(idx0(1:k))), 1e-11);
+%! assert (sort (imag (d1(idx1))), sort (imag (d0(idx0(1:k)))), 1e-11);
 %!testif HAVE_ARPACK
-%! d1 = eigs(A, eye(n), k, 'lm');
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! d1 = eigs (A, eye (n), k, "lm");
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
-%! d1 = eigs(A, eye(n), k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.cholB = true;
+%! d1 = eigs (A, eye (n), k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
+%! opts.cholB = true;
 %! q = [2:n,1];
-%! opts.permB=q;
-%! d1 = eigs(A, eye(n)(q,q), k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.permB = q;
+%! d1 = eigs (A, eye (n)(q,q), k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
-%! d1 = eigs(A, eye(n), k, 4.1, opts);
-%! assert (abs(abs(d1)), abs(eigs(A,k,4.1)), 1e-11);
-%! assert (sort(imag(abs(d1))), sort(imag(eigs(A,k,4.1))), 1e-11);
+%! opts.cholB = true;
+%! d1 = eigs (A, eye (n), k, 4.1, opts);
+%! assert (abs (abs (d1)), abs (eigs (A, k, 4.1)), 1e-11);
+%! assert (sort (imag (abs (d1))), sort (imag (eigs (A, k, 4.1))), 1e-11);
 %!testif HAVE_ARPACK
-%! opts.cholB=true;
+%! opts.cholB = true;
 %! q = [2:n,1];
-%! opts.permB=q;
-%! d1 = eigs(A, eye(n)(q,q), k, 4.1, opts);
-%! assert (abs(abs(d1)), abs(eigs(A,k,4.1)), 1e-11);
-%! assert (sort(imag(abs(d1))), sort(imag(eigs(A,k,4.1))), 1e-11);
+%! opts.permB = q;
+%! d1 = eigs (A, eye (n)(q,q), k, 4.1, opts);
+%! assert (abs (abs (d1)), abs (eigs (A, k, 4.1)), 1e-11);
+%! assert (sort (imag (abs (d1))), sort (imag (eigs (A, k, 4.1))), 1e-11);
 %!testif HAVE_ARPACK
-%! assert (abs(eigs(A,k,4.1)), abs(eigs(A,eye(n),k,4.1)), 1e-11);
+%! assert (abs (eigs (A, k, 4.1)), abs (eigs (A, eye (n), k, 4.1)), 1e-11);
 %!testif HAVE_ARPACK
-%! assert (sort(imag(eigs(A,k,4.1))), sort(imag(eigs(A,eye(n),k,4.1))), 1e-11);
+%! assert (sort (imag (eigs (A, k, 4.1))), sort (imag (eigs (A, eye (n), k, 4.1))), 1e-11);
 %!testif HAVE_ARPACK
 %! fn = @(x) A * x;
-%! opts.issym = 0; opts.isreal = 0;
-%! d1 = eigs (fn, n, k, 'lm', opts);
-%! assert (abs(d1), abs(d0(end:-1:(end-k+1))), 1e-11);
+%! opts.issym = 0;  opts.isreal = 0;
+%! d1 = eigs (fn, n, k, "lm", opts);
+%! assert (abs (d1), abs (d0(end:-1:(end-k+1))), 1e-11);
 %!testif HAVE_ARPACK
 %! fn = @(x) A \ x;
-%! opts.issym = 0; opts.isreal = 0;
-%! d1 = eigs (fn, n, k, 'sm', opts);
-%! assert (abs(d1), d0(1:k), 1e-11);
+%! opts.issym = 0;  opts.isreal = 0;
+%! d1 = eigs (fn, n, k, "sm", opts);
+%! assert (abs (d1), d0(1:k), 1e-11);
 %!testif HAVE_ARPACK
-%! fn = @(x) (A - 4.1 * eye(n)) \ x;
-%! opts.issym = 0; opts.isreal = 0;
+%! fn = @(x) (A - 4.1 * eye (n)) \ x;
+%! opts.issym = 0;  opts.isreal = 0;
 %! d1 = eigs (fn, n, k, 4.1, opts);
-%! assert (abs(d1), eigs(A,k,4.1), 1e-11);
+%! assert (abs (d1), eigs (A, k, 4.1), 1e-11);
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'lm');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "lm");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'sm');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "sm");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'lr');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "lr");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'sr');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "sr");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'li');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "li");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
 %!testif HAVE_ARPACK
-%! [v1,d1] = eigs(A, k, 'si');
-%! d1 = diag(d1);
+%! [v1,d1] = eigs (A, k, "si");
+%! d1 = diag (d1);
 %! for i=1:k
-%!  assert(max(abs((A - d1(i)*eye(n))*v1(:,i))),0.,1e-11)
+%!   assert (max (abs ((A - d1(i)*eye (n))*v1(:,i))), 0, 1e-11);
 %! endfor
-
 */
rename from src/DLD-FUNCTIONS/fftw.cc
rename to libinterp/dldfcn/fftw.cc
--- a/src/DLD-FUNCTIONS/fftw.cc
+++ b/libinterp/dldfcn/fftw.cc
@@ -34,10 +34,12 @@
 
 DEFUN_DLD (fftw, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{method} =} fftw ('planner')\n\
-@deftypefnx {Loadable Function} {} fftw ('planner', @var{method})\n\
-@deftypefnx {Loadable Function} {@var{wisdom} =} fftw ('dwisdom')\n\
-@deftypefnx {Loadable Function} {} fftw ('dwisdom', @var{wisdom})\n\
+@deftypefn  {Loadable Function} {@var{method} =} fftw (\"planner\")\n\
+@deftypefnx {Loadable Function} {} fftw (\"planner\", @var{method})\n\
+@deftypefnx {Loadable Function} {@var{wisdom} =} fftw (\"dwisdom\")\n\
+@deftypefnx {Loadable Function} {} fftw (\"dwisdom\", @var{wisdom})\n\
+@deftypefnx {Loadable Function} {} fftw (\"threads\", @var{nthreads})\n\
+@deftypefnx {Loadable Function} {@var{nthreads} =} fftw (\"threads\")\n\
 \n\
 Manage @sc{fftw} wisdom data.  Wisdom data can be used to significantly\n\
 accelerate the calculation of the FFTs, but implies an initial cost\n\
@@ -47,7 +49,7 @@
 the @code{fftw} function can be used to import wisdom.  For example,\n\
 \n\
 @example\n\
-@var{wisdom} = fftw ('dwisdom')\n\
+@var{wisdom} = fftw (\"dwisdom\")\n\
 @end example\n\
 \n\
 @noindent\n\
@@ -57,10 +59,10 @@
 reimported as follows\n\
 \n\
 @example\n\
-fftw ('dwisdom', @var{wisdom})\n\
+fftw (\"dwisdom\", @var{wisdom})\n\
 @end example\n\
 \n\
-If @var{wisdom} is an empty matrix, then the wisdom used is cleared.\n\
+If @var{wisdom} is an empty string, then the wisdom used is cleared.\n\
 \n\
 During the calculation of Fourier transforms further wisdom is generated.\n\
 The fashion in which this wisdom is generated is also controlled by\n\
@@ -68,54 +70,65 @@
 wisdom can be treated:\n\
 \n\
 @table @asis\n\
-@item 'estimate'\n\
+@item \"estimate\"\n\
 Specifies that no run-time measurement of the optimal means of\n\
 calculating a particular is performed, and a simple heuristic is used\n\
 to pick a (probably sub-optimal) plan.  The advantage of this method is\n\
 that there is little or no overhead in the generation of the plan, which\n\
 is appropriate for a Fourier transform that will be calculated once.\n\
 \n\
-@item 'measure'\n\
+@item \"measure\"\n\
 In this case a range of algorithms to perform the transform is considered\n\
 and the best is selected based on their execution time.\n\
 \n\
-@item 'patient'\n\
-Similar to 'measure', but a wider range of algorithms is considered.\n\
+@item \"patient\"\n\
+Similar to \"measure\", but a wider range of algorithms is considered.\n\
 \n\
-@item 'exhaustive'\n\
-Like 'measure', but all possible algorithms that may be used to\n\
+@item \"exhaustive\"\n\
+Like \"measure\", but all possible algorithms that may be used to\n\
 treat the transform are considered.\n\
 \n\
-@item 'hybrid'\n\
+@item \"hybrid\"\n\
 As run-time measurement of the algorithm can be expensive, this is a\n\
-compromise where 'measure' is used for transforms up to the size of 8192\n\
-and beyond that the 'estimate' method is used.\n\
+compromise where \"measure\" is used for transforms up to the size of 8192\n\
+and beyond that the \"estimate\" method is used.\n\
 @end table\n\
 \n\
-The default method is 'estimate'.  The current method can\n\
+The default method is \"estimate\".  The current method can\n\
 be queried with\n\
 \n\
 @example\n\
-@var{method} = fftw ('planner')\n\
+@var{method} = fftw (\"planner\")\n\
 @end example\n\
 \n\
 @noindent\n\
 or set by using\n\
 \n\
 @example\n\
-fftw ('planner', @var{method})\n\
+fftw (\"planner\", @var{method})\n\
 @end example\n\
 \n\
 Note that calculated wisdom will be lost when restarting Octave.  However,\n\
 the wisdom data can be reloaded if it is saved to a file as described\n\
 above.  Saved wisdom files should not be used on different platforms since\n\
 they will not be efficient and the point of calculating the wisdom is lost.\n\
+\n\
+The number of threads used for computing the plans and executing the\n\
+transforms can be set with\n\
+\n\
+@example\n\
+fftw (\"threads\", @var{NTHREADS})\n\
+@end example\n\
+\n\
+Note that octave must be compiled with multi-threaded FFTW support for this feature.\n\
+The number of processors available to the current process is used per default.\n\
+\n\
 @seealso{fft, ifft, fft2, ifft2, fftn, ifftn}\n\
 @end deftypefn")
 {
   octave_value retval;
 
-  int nargin = args.length();
+  int nargin = args.length ();
 
   if (nargin < 1 || nargin > 2)
     {
@@ -127,106 +140,76 @@
   if (args(0).is_string ())
     {
       std::string arg0 = args(0).string_value ();
-
       if (!error_state)
         {
-          // Use STL function to convert to lower case
-          std::transform (arg0.begin (), arg0.end (), arg0.begin (), tolower);
-
-          if (nargin == 2)
+          if (arg0 == "planner")
             {
-              std::string arg1 = args(1).string_value ();
-              if (!error_state)
+              if (nargin == 2)  //planner setter
                 {
-                  if (arg0 == "planner")
+                  if (args(1).is_string ())
                     {
-                      std::transform (arg1.begin (), arg1.end (),
-                                      arg1.begin (), tolower);
-                      octave_fftw_planner::FftwMethod meth
-                        = octave_fftw_planner::UNKNOWN;
-                      octave_float_fftw_planner::FftwMethod methf
-                        = octave_float_fftw_planner::UNKNOWN;
-
-                      if (arg1 == "estimate")
-                        {
-                          meth = octave_fftw_planner::ESTIMATE;
-                          methf = octave_float_fftw_planner::ESTIMATE;
-                        }
-                      else if (arg1 == "measure")
-                        {
-                          meth = octave_fftw_planner::MEASURE;
-                          methf = octave_float_fftw_planner::MEASURE;
-                        }
-                      else if (arg1 == "patient")
-                        {
-                          meth = octave_fftw_planner::PATIENT;
-                          methf = octave_float_fftw_planner::PATIENT;
-                        }
-                      else if (arg1 == "exhaustive")
-                        {
-                          meth = octave_fftw_planner::EXHAUSTIVE;
-                          methf = octave_float_fftw_planner::EXHAUSTIVE;
-                        }
-                      else if (arg1 == "hybrid")
-                        {
-                          meth = octave_fftw_planner::HYBRID;
-                          methf = octave_float_fftw_planner::HYBRID;
-                        }
-                      else
-                        error ("unrecognized planner METHOD");
-
+                      // Use STL function to convert to lower case
+                      std::transform (arg0.begin (), arg0.end (), arg0.begin (), tolower);
+                      std::string arg1 = args(1).string_value ();
                       if (!error_state)
                         {
-                          meth = octave_fftw_planner::method (meth);
-                          octave_float_fftw_planner::method (methf);
+                          std::transform (arg1.begin (), arg1.end (),
+                                          arg1.begin (), tolower);
+                          octave_fftw_planner::FftwMethod meth
+                            = octave_fftw_planner::UNKNOWN;
+                          octave_float_fftw_planner::FftwMethod methf
+                            = octave_float_fftw_planner::UNKNOWN;
 
-                          if (meth == octave_fftw_planner::MEASURE)
-                            retval = octave_value ("measure");
-                          else if (meth == octave_fftw_planner::PATIENT)
-                            retval = octave_value ("patient");
-                          else if (meth == octave_fftw_planner::EXHAUSTIVE)
-                            retval = octave_value ("exhaustive");
-                          else if (meth == octave_fftw_planner::HYBRID)
-                            retval = octave_value ("hybrid");
+                          if (arg1 == "estimate")
+                            {
+                              meth = octave_fftw_planner::ESTIMATE;
+                              methf = octave_float_fftw_planner::ESTIMATE;
+                            }
+                          else if (arg1 == "measure")
+                            {
+                              meth = octave_fftw_planner::MEASURE;
+                              methf = octave_float_fftw_planner::MEASURE;
+                            }
+                          else if (arg1 == "patient")
+                            {
+                              meth = octave_fftw_planner::PATIENT;
+                              methf = octave_float_fftw_planner::PATIENT;
+                            }
+                          else if (arg1 == "exhaustive")
+                            {
+                              meth = octave_fftw_planner::EXHAUSTIVE;
+                              methf = octave_float_fftw_planner::EXHAUSTIVE;
+                            }
+                          else if (arg1 == "hybrid")
+                            {
+                              meth = octave_fftw_planner::HYBRID;
+                              methf = octave_float_fftw_planner::HYBRID;
+                            }
                           else
-                            retval = octave_value ("estimate");
+                            error ("unrecognized planner METHOD");
+
+                          if (!error_state)
+                            {
+                              meth = octave_fftw_planner::method (meth);
+                              octave_float_fftw_planner::method (methf);
+
+                              if (meth == octave_fftw_planner::MEASURE)
+                                retval = octave_value ("measure");
+                              else if (meth == octave_fftw_planner::PATIENT)
+                                retval = octave_value ("patient");
+                              else if (meth == octave_fftw_planner::EXHAUSTIVE)
+                                retval = octave_value ("exhaustive");
+                              else if (meth == octave_fftw_planner::HYBRID)
+                                retval = octave_value ("hybrid");
+                              else
+                                retval = octave_value ("estimate");
+                            }
                         }
                     }
-                  else if (arg0 == "dwisdom")
-                    {
-                      char *str = fftw_export_wisdom_to_string ();
-
-                      if (arg1.length() < 1)
-                        fftw_forget_wisdom ();
-                      else if (! fftw_import_wisdom_from_string (arg1.c_str()))
-                        error ("could not import supplied WISDOM");
-
-                      if (!error_state)
-                        retval = octave_value (std::string (str));
-
-                      free (str);
-                    }
-                  else if (arg0 == "swisdom")
-                    {
-                      char *str = fftwf_export_wisdom_to_string ();
-
-                      if (arg1.length() < 1)
-                        fftwf_forget_wisdom ();
-                      else if (! fftwf_import_wisdom_from_string (arg1.c_str()))
-                        error ("could not import supplied WISDOM");
-
-                      if (!error_state)
-                        retval = octave_value (std::string (str));
-
-                      free (str);
-                    }
                   else
-                    error ("unrecognized argument");
+                    error ("fftw planner expects a string value as METHOD");
                 }
-            }
-          else
-            {
-              if (arg0 == "planner")
+              else //planner getter
                 {
                   octave_fftw_planner::FftwMethod meth =
                     octave_fftw_planner::method ();
@@ -242,23 +225,111 @@
                   else
                     retval = octave_value ("estimate");
                 }
-              else if (arg0 == "dwisdom")
+            }
+          else if (arg0 == "dwisdom")
+            {
+              if (nargin == 2)  //dwisdom setter
+                {
+                  if (args(1).is_string ())
+                    {
+                      // Use STL function to convert to lower case
+                      std::transform (arg0.begin (), arg0.end (), arg0.begin (), tolower);
+                      std::string arg1 = args(1).string_value ();
+                      if (!error_state)
+                        {
+                          char *str = fftw_export_wisdom_to_string ();
+
+                          if (arg1.length () < 1)
+                            fftw_forget_wisdom ();
+                          else if (! fftw_import_wisdom_from_string (arg1.c_str ()))
+                            error ("could not import supplied WISDOM");
+
+                          if (!error_state)
+                            retval = octave_value (std::string (str));
+
+                          free (str);
+                        }
+                    }
+                }
+              else //dwisdom getter
                 {
                   char *str = fftw_export_wisdom_to_string ();
                   retval = octave_value (std::string (str));
                   free (str);
                 }
-              else if (arg0 == "swisdom")
+            }
+          else if (arg0 == "swisdom")
+            {
+              //swisdom uses fftwf_ functions (float), dwisdom fftw_ (real)
+              if (nargin == 2)  //swisdom setter
+                {
+                  if (args(1).is_string ())
+                    {
+                      // Use STL function to convert to lower case
+                      std::transform (arg0.begin (), arg0.end (), arg0.begin (), tolower);
+                      std::string arg1 = args(1).string_value ();
+                      if (!error_state)
+                        {
+                          char *str = fftwf_export_wisdom_to_string ();
+
+                          if (arg1.length () < 1)
+                            fftwf_forget_wisdom ();
+                          else if (! fftwf_import_wisdom_from_string (arg1.c_str ()))
+                            error ("could not import supplied WISDOM");
+
+                          if (!error_state)
+                            retval = octave_value (std::string (str));
+
+                          free (str);
+                        }
+                    }
+                }
+              else //swisdom getter
                 {
                   char *str = fftwf_export_wisdom_to_string ();
                   retval = octave_value (std::string (str));
                   free (str);
                 }
-              else
-                error ("unrecognized argument");
             }
+          else if (arg0 == "threads")
+            {
+              if (nargin == 2)  //threads setter
+                {
+                  if (args(1).is_real_scalar ())
+                    {
+                      int nthreads = args(1).int_value();
+                      if ( nthreads >= 1)
+                        {
+#if defined (HAVE_FFTW3_THREADS)
+                          octave_fftw_planner::threads (nthreads);
+#else
+                          warning ("this copy of Octave was not configured to use the multithreaded fftw libraries.");
+#endif
+#if defined (HAVE_FFTW3F_THREADS)
+                          octave_float_fftw_planner::threads (nthreads);
+#else
+                          warning ("this copy of Octave was not configured to use the multithreaded fftwf libraries.");
+#endif
+                        }
+                      else
+                        error ("number of threads must be >=1");
+                    }
+                  else
+                    error ("setting threads needs one integer argument.");
+                }
+              else //threads getter
+#if defined (HAVE_FFTW3_THREADS)              
+                retval = octave_value (octave_fftw_planner::threads());
+#else
+                retval = 1;
+#endif
+            }
+          else
+            error ("unrecognized argument");
         }
     }
+  else
+    error ("unrecognized argument");
 #else
 
   warning ("fftw: this copy of Octave was not configured to use the FFTW3 planner");
@@ -269,7 +340,6 @@
 }
 
 /*
-
 %!testif HAVE_FFTW
 %! def_method = fftw ("planner");
 %! unwind_protect
@@ -295,4 +365,12 @@
 %!error <Invalid call to fftw> fftw ();
 %!error <Invalid call to fftw> fftw ("planner", "estimate", "measure");
 
+%!testif HAVE_FFTW3_THREADS
+%! n = fftw ("threads");
+%! unwind_protect
+%!   fftw ("threads", 3);
+%!   assert (fftw ("threads"), 3);
+%! unwind_protect_cleanup
+%!   fftw ("threads", n);
+%! end_unwind_protect
  */
rename from src/DLD-FUNCTIONS/module-files
rename to libinterp/dldfcn/module-files
--- a/src/DLD-FUNCTIONS/module-files
+++ b/libinterp/dldfcn/module-files
@@ -1,83 +1,22 @@
 # FILE|CPPFLAGS|LDFLAGS|LIBRARIES
-__contourc__.cc
 __delaunayn__.cc|$(QHULL_CPPFLAGS)|$(QHULL_LDFLAGS)|$(QHULL_LIBS)
-__dispatch__.cc
 __dsearchn__.cc
 __fltk_uigetfile__.cc|$(GRAPHICS_CFLAGS) $(FT2_CPPFLAGS)|$(GRAPHICS_LDFLAGS) $(FT2_LDFLAGS)|$(GRAPHICS_LIBS) $(FT2_LIBS)
 __glpk__.cc|$(GLPK_CPPFLAGS)|$(GLPK_LDFLAGS)|$(GLPK_LIBS)
 __init_fltk__.cc|$(GRAPHICS_CFLAGS) $(FT2_CPPFLAGS)|$(GRAPHICS_LDFLAGS) $(FT2_LDFLAGS)|$(GRAPHICS_LIBS) $(FT2_LIBS)
 __init_gnuplot__.cc
-__lin_interpn__.cc
 __magick_read__.cc|$(MAGICK_CPPFLAGS)|$(MAGICK_LDFLAGS)|$(MAGICK_LIBS)
-__pchip_deriv__.cc
-__qp__.cc
 __voronoi__.cc|$(QHULL_CPPFLAGS)|$(QHULL_LDFLAGS)|$(QHULL_LIBS)
 amd.cc|$(SPARSE_XCPPFLAGS)|$(SPARSE_XLDFLAGS)|$(SPARSE_XLIBS)
-balance.cc
-besselj.cc
-betainc.cc
-bsxfun.cc
 ccolamd.cc|$(SPARSE_XCPPFLAGS)|$(SPARSE_XLDFLAGS)|$(SPARSE_XLIBS)
-cellfun.cc
-chol.cc|$(QRUPDATE_CPPFLAGS) $(SPARSE_XCPPFLAGS)|$(QRUPDATE_LDFLAGS) $(SPARSE_XLDFLAGS)|$(QRUPDATE_LIBS) $(SPARSE_XLIBS)
+chol.cc|$(SPARSE_XCPPFLAGS)|$(SPARSE_XLDFLAGS)|$(SPARSE_XLIBS)
 colamd.cc|$(SPARSE_XCPPFLAGS)|$(SPARSE_XLDFLAGS)|$(SPARSE_XLIBS)
-colloc.cc
-conv2.cc
 convhulln.cc|$(QHULL_CPPFLAGS)|$(QHULL_LDFLAGS)|$(QHULL_LIBS)
-daspk.cc
-dasrt.cc
-dassl.cc
-det.cc
-dlmread.cc
 dmperm.cc|$(SPARSE_XCPPFLAGS)|$(SPARSE_XLDFLAGS)|$(SPARSE_XLIBS)
-dot.cc
-eig.cc
 eigs.cc|$(ARPACK_CPPFLAGS) $(SPARSE_XCPPFLAGS)|$(ARPACK_LDFLAGS) $(SPARSE_XLDFLAGS)|$(ARPACK_LIBS) $(SPARSE_XLIBS) $(LAPACK_LIBS) $(BLAS_LIBS)
-fft.cc|$(FFTW_XCPPFLAGS)|$(FFTW_XLDFLAGS)|$(FFTW_XLIBS)
-fft2.cc|$(FFTW_XCPPFLAGS)|$(FFTW_XLDFLAGS)|$(FFTW_XLIBS)
-fftn.cc|$(FFTW_XCPPFLAGS)|$(FFTW_XLDFLAGS)|$(FFTW_XLIBS)
 fftw.cc|$(FFTW_XCPPFLAGS)|$(FFTW_XLDFLAGS)|$(FFTW_XLIBS)
-filter.cc
-find.cc
-gammainc.cc
-gcd.cc
-getgrent.cc
-getpwent.cc
-getrusage.cc
-givens.cc
-hess.cc
-hex2num.cc
-inv.cc
-kron.cc
-lookup.cc
-lsode.cc
-lu.cc
-luinc.cc
-matrix_type.cc
-max.cc
-md5sum.cc
-mgorth.cc
-nproc.cc
-pinv.cc
 qr.cc|$(QRUPDATE_CPPFLAGS) $(SPARSE_XCPPFLAGS)|$(QRUPDATE_LDFLAGS) $(SPARSE_XLDFLAGS)|$(QRUPDATE_LIBS) $(SPARSE_XLIBS)
-quad.cc
-quadcc.cc
-qz.cc|||$(LAPACK_LIBS) $(BLAS_LIBS)
-rand.cc
-rcond.cc
-regexp.cc|$(REGEX_CPPFLAGS)|$(REGEX_LDFLAGS)|$(REGEX_LIBS)
-schur.cc
-spparms.cc
-sqrtm.cc
-strfind.cc
-str2double.cc
-sub2ind.cc
-svd.cc
-syl.cc
 symbfact.cc|$(SPARSE_XCPPFLAGS)|$(SPARSE_XLDFLAGS)|$(SPARSE_XLIBS)
 symrcm.cc|$(SPARSE_XCPPFLAGS)|$(SPARSE_XLDFLAGS)|$(SPARSE_XLIBS)
-time.cc
-tril.cc
 tsearch.cc
-typecast.cc
 urlwrite.cc|$(CURL_CPPFLAGS)|$(CURL_LDFLAGS)|$(CURL_LIBS)
rename from src/DLD-FUNCTIONS/oct-qhull.h
rename to libinterp/dldfcn/oct-qhull.h
rename from src/DLD-FUNCTIONS/qr.cc
rename to libinterp/dldfcn/qr.cc
--- a/src/DLD-FUNCTIONS/qr.cc
+++ b/libinterp/dldfcn/qr.cc
@@ -113,7 +113,7 @@
 @ifnottex\n\
 \n\
 @example\n\
-@code{min norm(A x - b)}\n\
+min norm(A x - b)\n\
 @end example\n\
 \n\
 @end ifnottex\n\
@@ -200,7 +200,7 @@
 
   int nargin = args.length ();
 
-  if (nargin < 1 || nargin > (args(0).is_sparse_type() ? 3 : 2))
+  if (nargin < 1 || nargin > (args(0).is_sparse_type () ? 3 : 2))
     {
       print_usage ();
       return retval;
@@ -250,7 +250,7 @@
                     {
                       retval(1) = q.R (economy);
                       retval(0) = q.C (args(have_b).complex_matrix_value ());
-                      if (arg.rows() < arg.columns())
+                      if (arg.rows () < arg.columns ())
                         warning ("qr: non minimum norm solution for under-determined problem");
                     }
                   else if (nargout > 1)
@@ -271,7 +271,7 @@
                     {
                       retval(1) = q.R (economy);
                       retval(0) = q.C (args(have_b).matrix_value ());
-                      if (args(0).rows() < args(0).columns())
+                      if (args(0).rows () < args(0).columns ())
                         warning ("qr: non minimum norm solution for under-determined problem");
                     }
                   else if (nargout > 1)
@@ -456,12 +456,10 @@
 }
 
 /*
-
 %!test
 %! a = [0, 2, 1; 2, 1, 2];
 %!
 %! [q, r] = qr (a);
-%!
 %! [qe, re] = qr (a, 0);
 %!
 %! assert (q * r, a, sqrt (eps));
@@ -470,8 +468,7 @@
 %!test
 %! a = [0, 2, 1; 2, 1, 2];
 %!
-%! [q, r, p] = qr (a);  # not giving right dimensions. FIXME
-%!
+%! [q, r, p] = qr (a);  # FIXME: not giving right dimensions. 
 %! [qe, re, pe] = qr (a, 0);
 %!
 %! assert (q * r, a * p, sqrt (eps));
@@ -481,7 +478,6 @@
 %! a = [0, 2; 2, 1; 1, 2];
 %!
 %! [q, r] = qr (a);
-%!
 %! [qe, re] = qr (a, 0);
 %!
 %! assert (q * r, a, sqrt (eps));
@@ -491,27 +487,26 @@
 %! a = [0, 2; 2, 1; 1, 2];
 %!
 %! [q, r, p] = qr (a);
-%!
 %! [qe, re, pe] = qr (a, 0);
 %!
 %! assert (q * r, a * p, sqrt (eps));
 %! assert (qe * re, a(:, pe), sqrt (eps));
 
-%!error <Invalid call to qr> qr ();
-%!error <Invalid call to qr> qr ([1, 2; 3, 4], 0, 2);
+%!error qr ()
+%!error qr ([1, 2; 3, 4], 0, 2)
 
 %!function retval = __testqr (q, r, a, p)
-%!  tol = 100*eps (class(q));
+%!  tol = 100*eps (class (q));
 %!  retval = 0;
 %!  if (nargin == 3)
-%!    n1 = norm (q*r-a);
-%!    n2 = norm (q'*q-eye(columns(q)));
+%!    n1 = norm (q*r - a);
+%!    n2 = norm (q'*q - eye (columns (q)));
 %!    retval = (n1 < tol && n2 < tol);
 %!  else
-%!    n1 = norm (q'*q-eye(columns(q)));
+%!    n1 = norm (q'*q - eye (columns (q)));
 %!    retval = (n1 < tol);
 %!    if (isvector (p))
-%!      n2 = norm (q*r-a(:,p));
+%!      n2 = norm (q*r - a(:,p));
 %!      retval = (retval && n2 < tol);
 %!    else
 %!      n2 = norm (q*r - a*p);
@@ -521,237 +516,226 @@
 %!endfunction
 
 %!test
-%!
 %! t = ones (24, 1);
 %! j = 1;
 %!
-%! if false # eliminate big matrix tests
-%!   a = rand(5000,20);
-%!   [q,r]=qr(a,0); t(j++) = __testqr(q,r,a);
-%!   [q,r]=qr(a',0); t(j++) = __testqr(q,r,a');
-%!   [q,r,p]=qr(a,0); t(j++) = __testqr(q,r,a,p);
-%!   [q,r,p]=qr(a',0); t(j++) = __testqr(q,r,a',p);
+%! if (false)  # eliminate big matrix tests
+%!   a = rand (5000, 20);
+%!   [q,r]   = qr (a, 0);  t(j++) = __testqr (q, r, a);
+%!   [q,r]   = qr (a',0);  t(j++) = __testqr (q, r, a');
+%!   [q,r,p] = qr (a, 0);  t(j++) = __testqr (q, r, a, p);
+%!   [q,r,p] = qr (a',0);  t(j++) = __testqr (q, r, a', p);
 %!
 %!   a = a+1i*eps;
-%!   [q,r]=qr(a,0); t(j++) = __testqr(q,r,a);
-%!   [q,r]=qr(a',0); t(j++) = __testqr(q,r,a');
-%!   [q,r,p]=qr(a,0); t(j++) = __testqr(q,r,a,p);
-%!   [q,r,p]=qr(a',0); t(j++) = __testqr(q,r,a',p);
+%!   [q,r]   = qr (a, 0);  t(j++) = __testqr (q, r, a);
+%!   [q,r]   = qr (a',0);  t(j++) = __testqr (q, r, a');
+%!   [q,r,p] = qr (a, 0);  t(j++) = __testqr (q, r, a, p);
+%!   [q,r,p] = qr (a',0);  t(j++) = __testqr (q, r, a', p);
 %! endif
 %!
 %! a = [ ones(1,15); sqrt(eps)*eye(15) ];
-%! [q,r]=qr(a); t(j++) = __testqr(q,r,a);
-%! [q,r]=qr(a'); t(j++) = __testqr(q,r,a');
-%! [q,r,p]=qr(a); t(j++) = __testqr(q,r,a,p);
-%! [q,r,p]=qr(a'); t(j++) = __testqr(q,r,a',p);
-%!
-%! a = a+1i*eps;
-%! [q,r]=qr(a); t(j++) = __testqr(q,r,a);
-%! [q,r]=qr(a'); t(j++) = __testqr(q,r,a');
-%! [q,r,p]=qr(a); t(j++) = __testqr(q,r,a,p);
-%! [q,r,p]=qr(a'); t(j++) = __testqr(q,r,a',p);
-%!
-%! a = [ ones(1,15); sqrt(eps)*eye(15) ];
-%! [q,r]=qr(a,0); t(j++) = __testqr(q,r,a);
-%! [q,r]=qr(a',0); t(j++) = __testqr(q,r,a');
-%! [q,r,p]=qr(a,0); t(j++) = __testqr(q,r,a,p);
-%! [q,r,p]=qr(a',0); t(j++) = __testqr(q,r,a',p);
+%! [q,r]   = qr (a);   t(j++) = __testqr (q, r, a);
+%! [q,r]   = qr (a');  t(j++) = __testqr (q, r, a');
+%! [q,r,p] = qr (a);   t(j++) = __testqr (q, r, a, p);
+%! [q,r,p] = qr (a');  t(j++) = __testqr (q, r, a', p);
 %!
 %! a = a+1i*eps;
-%! [q,r]=qr(a,0); t(j++) = __testqr(q,r,a);
-%! [q,r]=qr(a',0); t(j++) = __testqr(q,r,a');
-%! [q,r,p]=qr(a,0); t(j++) = __testqr(q,r,a,p);
-%! [q,r,p]=qr(a',0); t(j++) = __testqr(q,r,a',p);
+%! [q,r]   = qr (a);   t(j++) = __testqr (q, r, a);
+%! [q,r]   = qr (a');  t(j++) = __testqr (q, r, a');
+%! [q,r,p] = qr (a);   t(j++) = __testqr (q, r, a, p);
+%! [q,r,p] = qr (a');  t(j++) = __testqr (q, r, a', p);
+%!
+%! a = [ ones(1,15); sqrt(eps)*eye(15) ];
+%! [q,r]   = qr (a, 0);  t(j++) = __testqr (q, r, a);
+%! [q,r]   = qr (a',0);  t(j++) = __testqr (q, r, a');
+%! [q,r,p] = qr (a, 0);  t(j++) = __testqr (q, r, a, p);
+%! [q,r,p] = qr (a',0);  t(j++) = __testqr (q, r, a', p);
 %!
-%! a = [
-%! 611   196  -192   407    -8   -52   -49    29
-%! 196   899   113  -192   -71   -43    -8   -44
-%! -192   113   899   196    61    49     8    52
-%! 407  -192   196   611     8    44    59   -23
-%! -8   -71    61     8   411  -599   208   208
-%! -52   -43    49    44  -599   411   208   208
-%! -49    -8     8    59   208   208    99  -911
-%! 29   -44    52   -23   208   208  -911    99
-%! ];
-%! [q,r] = qr(a);
+%! a = a+1i*eps;
+%! [q,r]   = qr (a, 0);  t(j++) = __testqr (q, r, a);
+%! [q,r]   = qr (a',0);  t(j++) = __testqr (q, r, a');
+%! [q,r,p] = qr (a, 0);  t(j++) = __testqr (q, r, a, p);
+%! [q,r,p] = qr (a',0);  t(j++) = __testqr (q, r, a', p);
 %!
-%! assert(all (t) && norm(q*r-a) < 5000*eps);
+%! a = [ 611   196  -192   407    -8   -52   -49    29
+%!       196   899   113  -192   -71   -43    -8   -44
+%!      -192   113   899   196    61    49     8    52
+%!       407  -192   196   611     8    44    59   -23
+%!        -8   -71    61     8   411  -599   208   208
+%!       -52   -43    49    44  -599   411   208   208
+%!       -49    -8     8    59   208   208    99  -911
+%!        29   -44    52   -23   208   208  -911    99 ];
+%! [q,r] = qr (a);
+%!
+%! assert (all (t) && norm (q*r - a) < 5000*eps);
 
 %!test
 %! a = single ([0, 2, 1; 2, 1, 2]);
 %!
 %! [q, r] = qr (a);
-%!
 %! [qe, re] = qr (a, 0);
 %!
-%! assert (q * r, a, sqrt (eps ('single')));
-%! assert (qe * re, a, sqrt (eps ('single')));
+%! assert (q * r, a, sqrt (eps ("single")));
+%! assert (qe * re, a, sqrt (eps ("single")));
 
 %!test
-%! a = single([0, 2, 1; 2, 1, 2]);
+%! a = single ([0, 2, 1; 2, 1, 2]);
 %!
-%! [q, r, p] = qr (a);  # not giving right dimensions. FIXME
-%!
+%! [q, r, p] = qr (a);  # FIXME: not giving right dimensions.
 %! [qe, re, pe] = qr (a, 0);
 %!
-%! assert (q * r, a * p, sqrt (eps('single')));
-%! assert (qe * re, a(:, pe), sqrt (eps('single')));
+%! assert (q * r, a * p, sqrt (eps ("single")));
+%! assert (qe * re, a(:, pe), sqrt (eps ("single")));
 
 %!test
-%! a = single([0, 2; 2, 1; 1, 2]);
+%! a = single ([0, 2; 2, 1; 1, 2]);
 %!
 %! [q, r] = qr (a);
-%!
 %! [qe, re] = qr (a, 0);
 %!
-%! assert (q * r, a, sqrt (eps('single')));
-%! assert (qe * re, a, sqrt (eps('single')));
+%! assert (q * r, a, sqrt (eps ("single")));
+%! assert (qe * re, a, sqrt (eps ("single")));
 
 %!test
-%! a = single([0, 2; 2, 1; 1, 2]);
+%! a = single ([0, 2; 2, 1; 1, 2]);
 %!
 %! [q, r, p] = qr (a);
-%!
 %! [qe, re, pe] = qr (a, 0);
 %!
-%! assert (q * r, a * p, sqrt (eps('single')));
-%! assert (qe * re, a(:, pe), sqrt (eps('single')));
+%! assert (q * r, a * p, sqrt (eps ("single")));
+%! assert (qe * re, a(:, pe), sqrt (eps ("single")));
 
-%!error <Invalid call to qr> qr ();
-%!error <Invalid call to qr> qr ([1, 2; 3, 4], 0, 2);
+%!error qr ()
+%!error qr ([1, 2; 3, 4], 0, 2)
 
 %!test
-%!
 %! t = ones (24, 1);
 %! j = 1;
 %!
-%! if false # eliminate big matrix tests
-%!   a = rand(5000,20);
-%!   [q,r]=qr(a,0); t(j++) = __testqr(q,r,a);
-%!   [q,r]=qr(a',0); t(j++) = __testqr(q,r,a');
-%!   [q,r,p]=qr(a,0); t(j++) = __testqr(q,r,a,p);
-%!   [q,r,p]=qr(a',0); t(j++) = __testqr(q,r,a',p);
+%! if (false)  # eliminate big matrix tests
+%!   a = rand (5000,20);
+%!   [q,r]   = qr (a, 0);  t(j++) = __testqr (q, r, a);
+%!   [q,r]   = qr (a',0);  t(j++) = __testqr (q, r, a');
+%!   [q,r,p] = qr (a, 0);  t(j++) = __testqr (q, r, a, p);
+%!   [q,r,p] = qr (a',0);  t(j++) = __testqr (q, r, a', p);
 %!
-%!   a = a+1i*eps('single');
-%!   [q,r]=qr(a,0); t(j++) = __testqr(q,r,a);
-%!   [q,r]=qr(a',0); t(j++) = __testqr(q,r,a');
-%!   [q,r,p]=qr(a,0); t(j++) = __testqr(q,r,a,p);
-%!   [q,r,p]=qr(a',0); t(j++) = __testqr(q,r,a',p);
+%!   a = a+1i*eps ("single");
+%!   [q,r]   = qr (a, 0);  t(j++) = __testqr (q, r, a);
+%!   [q,r]   = qr (a',0);  t(j++) = __testqr (q, r, a');
+%!   [q,r,p] = qr (a, 0);  t(j++) = __testqr (q, r, a, p);
+%!   [q,r,p] = qr (a',0);  t(j++) = __testqr (q, r, a', p);
 %! endif
 %!
-%! a = [ ones(1,15); sqrt(eps('single'))*eye(15) ];
-%! [q,r]=qr(a); t(j++) = __testqr(q,r,a);
-%! [q,r]=qr(a'); t(j++) = __testqr(q,r,a');
-%! [q,r,p]=qr(a); t(j++) = __testqr(q,r,a,p);
-%! [q,r,p]=qr(a'); t(j++) = __testqr(q,r,a',p);
+%! a = [ ones(1,15); sqrt(eps("single"))*eye(15) ];
+%! [q,r]   = qr (a);   t(j++) = __testqr (q, r, a);
+%! [q,r]   = qr (a');  t(j++) = __testqr (q, r, a');
+%! [q,r,p] = qr (a);   t(j++) = __testqr (q, r, a, p);
+%! [q,r,p] = qr (a');  t(j++) = __testqr (q, r, a', p);
 %!
-%! a = a+1i*eps('single');
-%! [q,r]=qr(a); t(j++) = __testqr(q,r,a);
-%! [q,r]=qr(a'); t(j++) = __testqr(q,r,a');
-%! [q,r,p]=qr(a); t(j++) = __testqr(q,r,a,p);
-%! [q,r,p]=qr(a'); t(j++) = __testqr(q,r,a',p);
+%! a = a+1i*eps ("single");
+%! [q,r]   = qr (a);   t(j++) = __testqr (q, r, a);
+%! [q,r]   = qr (a');  t(j++) = __testqr (q, r, a');
+%! [q,r,p] = qr (a);   t(j++) = __testqr (q, r, a, p);
+%! [q,r,p] = qr (a');  t(j++) = __testqr (q, r, a', p);
 %!
-%! a = [ ones(1,15); sqrt(eps('single'))*eye(15) ];
-%! [q,r]=qr(a,0); t(j++) = __testqr(q,r,a);
-%! [q,r]=qr(a',0); t(j++) = __testqr(q,r,a');
-%! [q,r,p]=qr(a,0); t(j++) = __testqr(q,r,a,p);
-%! [q,r,p]=qr(a',0); t(j++) = __testqr(q,r,a',p);
+%! a = [ ones(1,15); sqrt(eps("single"))*eye(15) ];
+%! [q,r]   = qr (a, 0);  t(j++) = __testqr (q, r, a);
+%! [q,r]   = qr (a',0);  t(j++) = __testqr (q, r, a');
+%! [q,r,p] = qr (a, 0);  t(j++) = __testqr (q, r, a, p);
+%! [q,r,p] = qr (a',0);  t(j++) = __testqr (q, r, a', p);
 %!
-%! a = a+1i*eps('single');
-%! [q,r]=qr(a,0); t(j++) = __testqr(q,r,a);
-%! [q,r]=qr(a',0); t(j++) = __testqr(q,r,a');
-%! [q,r,p]=qr(a,0); t(j++) = __testqr(q,r,a,p);
-%! [q,r,p]=qr(a',0); t(j++) = __testqr(q,r,a',p);
+%! a = a+1i*eps ("single");
+%! [q,r]   = qr (a, 0);  t(j++) = __testqr (q, r, a);
+%! [q,r]   = qr (a',0);  t(j++) = __testqr (q, r, a');
+%! [q,r,p] = qr (a, 0);  t(j++) = __testqr (q, r, a, p);
+%! [q,r,p] = qr (a',0);  t(j++) = __testqr (q, r, a',p);
 %!
-%! a = [
-%! 611   196  -192   407    -8   -52   -49    29
-%! 196   899   113  -192   -71   -43    -8   -44
-%! -192   113   899   196    61    49     8    52
-%! 407  -192   196   611     8    44    59   -23
-%! -8   -71    61     8   411  -599   208   208
-%! -52   -43    49    44  -599   411   208   208
-%! -49    -8     8    59   208   208    99  -911
-%! 29   -44    52   -23   208   208  -911    99
-%! ];
-%! [q,r] = qr(a);
+%! a = [ 611   196  -192   407    -8   -52   -49    29
+%!       196   899   113  -192   -71   -43    -8   -44
+%!      -192   113   899   196    61    49     8    52
+%!       407  -192   196   611     8    44    59   -23
+%!        -8   -71    61     8   411  -599   208   208
+%!       -52   -43    49    44  -599   411   208   208
+%!       -49    -8     8    59   208   208    99  -911
+%!        29   -44    52   -23   208   208  -911    99 ];
+%! [q,r] = qr (a);
 %!
-%! assert(all (t) && norm(q*r-a) < 5000*eps('single'));
+%! assert (all (t) && norm (q*r-a) < 5000*eps ("single"));
 
-%% The deactivated tests below can't be tested till rectangular back-subs is
-%% implemented for sparse matrices.
+## The deactivated tests below can't be tested till rectangular back-subs is
+## implemented for sparse matrices.
 
 %!testif HAVE_CXSPARSE
-%! n = 20; d= 0.2;
-%! a = sprandn(n,n,d)+speye(n,n);
-%! r = qr(a);
-%! assert(r'*r,a'*a,1e-10)
+%! n = 20;  d = 0.2;
+%! a = sprandn (n,n,d) + speye (n,n);
+%! r = qr (a);
+%! assert (r'*r, a'*a, 1e-10)
 
 %!testif HAVE_COLAMD
-%! n = 20; d= 0.2;
-%! a = sprandn(n,n,d)+speye(n,n);
-%! q = symamd(a);
+%! n = 20;  d = 0.2;
+%! a = sprandn (n,n,d) + speye (n,n);
+%! q = symamd (a);
 %! a = a(q,q);
-%! r = qr(a);
-%! assert(r'*r,a'*a,1e-10)
+%! r = qr (a);
+%! assert (r'*r, a'*a, 1e-10)
 
 %!testif HAVE_CXSPARSE
-%! n = 20; d= 0.2;
-%! a = sprandn(n,n,d)+speye(n,n);
-%! [c,r] = qr(a,ones(n,1));
-%! assert (r\c,full(a)\ones(n,1),10e-10)
+%! n = 20;  d = 0.2;
+%! a = sprandn (n,n,d) + speye (n,n);
+%! [c,r] = qr (a, ones (n,1));
+%! assert (r\c, full (a)\ones (n,1), 10e-10)
 
 %!testif HAVE_CXSPARSE
-%! n = 20; d= 0.2;
-%! a = sprandn(n,n,d)+speye(n,n);
-%! b = randn(n,2);
-%! [c,r] = qr(a,b);
-%! assert (r\c,full(a)\b,10e-10)
+%! n = 20;  d = 0.2;
+%! a = sprandn (n,n,d) + speye (n,n);
+%! b = randn (n,2);
+%! [c,r] = qr (a, b);
+%! assert (r\c, full (a)\b, 10e-10)
 
 %% Test under-determined systems!!
 %!#testif HAVE_CXSPARSE
-%! n = 20; d= 0.2;
-%! a = sprandn(n,n+1,d)+speye(n,n+1);
-%! b = randn(n,2);
-%! [c,r] = qr(a,b);
-%! assert (r\c,full(a)\b,10e-10)
+%! n = 20;  d = 0.2;
+%! a = sprandn (n,n+1,d) + speye (n,n+1);
+%! b = randn (n,2);
+%! [c,r] = qr (a, b);
+%! assert (r\c, full (a)\b, 10e-10)
 
 %!testif HAVE_CXSPARSE
-%! n = 20; d= 0.2;
-%! a = 1i*sprandn(n,n,d)+speye(n,n);
-%! r = qr(a);
-%! assert(r'*r,a'*a,1e-10)
+%! n = 20;  d = 0.2;
+%! a = 1i*sprandn (n,n,d) + speye (n,n);
+%! r = qr (a);
+%! assert (r'*r,a'*a,1e-10)
 
 %!testif HAVE_COLAMD
-%! n = 20; d= 0.2;
-%! a = 1i*sprandn(n,n,d)+speye(n,n);
-%! q = symamd(a);
+%! n = 20;  d = 0.2;
+%! a = 1i*sprandn (n,n,d) + speye (n,n);
+%! q = symamd (a);
 %! a = a(q,q);
-%! r = qr(a);
-%! assert(r'*r,a'*a,1e-10)
+%! r = qr (a);
+%! assert (r'*r, a'*a, 1e-10)
 
 %!testif HAVE_CXSPARSE
-%! n = 20; d= 0.2;
-%! a = 1i*sprandn(n,n,d)+speye(n,n);
-%! [c,r] = qr(a,ones(n,1));
-%! assert (r\c,full(a)\ones(n,1),10e-10)
+%! n = 20;  d = 0.2;
+%! a = 1i*sprandn (n,n,d) + speye (n,n);
+%! [c,r] = qr (a, ones (n,1));
+%! assert (r\c, full (a)\ones (n,1), 10e-10)
 
 %!testif HAVE_CXSPARSE
-%! n = 20; d= 0.2;
-%! a = 1i*sprandn(n,n,d)+speye(n,n);
-%! b = randn(n,2);
-%! [c,r] = qr(a,b);
-%! assert (r\c,full(a)\b,10e-10)
+%! n = 20;  d = 0.2;
+%! a = 1i*sprandn (n,n,d) + speye (n,n);
+%! b = randn (n,2);
+%! [c,r] = qr (a, b);
+%! assert (r\c, full (a)\b, 10e-10)
 
 %% Test under-determined systems!!
 %!#testif HAVE_CXSPARSE
-%! n = 20; d= 0.2;
-%! a = 1i*sprandn(n,n+1,d)+speye(n,n+1);
-%! b = randn(n,2);
-%! [c,r] = qr(a,b);
-%! assert (r\c,full(a)\b,10e-10)
+%! n = 20;  d = 0.2;
+%! a = 1i*sprandn (n,n+1,d) + speye (n,n+1);
+%! b = randn (n,2);
+%! [c,r] = qr (a, b);
+%! assert (r\c, full (a)\b, 10e-10)
 
-%!error qr(sprandn(10,10,0.2),ones(10,1));
-
+%!error qr (sprandn (10,10,0.2), ones (10,1))
 */
 
 static
@@ -885,6 +869,7 @@
 
   return retval;
 }
+
 /*
 %!shared A, u, v, Ac, uc, vc
 %! A = [0.091364  0.613038  0.999083;
@@ -921,32 +906,32 @@
 %!
 
 %!test
-%! [Q,R] = qr(A);
-%! [Q,R] = qrupdate(Q,R,u,v);
-%! assert(norm(vec(Q'*Q - eye(5)),Inf) < 1e1*eps)
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - A - u*v'),Inf) < norm(A)*1e1*eps)
+%! [Q,R] = qr (A);
+%! [Q,R] = qrupdate (Q, R, u, v);
+%! assert (norm (vec (Q'*Q - eye (5)), Inf) < 1e1*eps);
+%! assert (norm (vec (triu (R)-R), Inf) == 0);
+%! assert (norm (vec (Q*R - A - u*v'), Inf) < norm (A)*1e1*eps);
 %!
 %!test
-%! [Q,R] = qr(Ac);
-%! [Q,R] = qrupdate(Q,R,uc,vc);
-%! assert(norm(vec(Q'*Q - eye(5)),Inf) < 1e1*eps)
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - Ac - uc*vc'),Inf) < norm(Ac)*1e1*eps)
+%! [Q,R] = qr (Ac);
+%! [Q,R] = qrupdate (Q, R, uc, vc);
+%! assert (norm (vec (Q'*Q - eye (5)), Inf) < 1e1*eps);
+%! assert (norm (vec (triu (R)-R), Inf) == 0);
+%! assert (norm (vec (Q*R - Ac - uc*vc'), Inf) < norm (Ac)*1e1*eps);
 
 %!test
-%! [Q,R] = qr(single(A));
-%! [Q,R] = qrupdate(Q,R,single(u),single(v));
-%! assert(norm(vec(Q'*Q - eye(5,'single')),Inf) < 1e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - single(A) - single(u)*single(v)'),Inf) < norm(single(A))*1e1*eps('single'))
+%! [Q,R] = qr (single (A));
+%! [Q,R] = qrupdate (Q, R, single (u), single (v));
+%! assert (norm (vec (Q'*Q - eye (5,"single")), Inf) < 1e1*eps ("single"));
+%! assert (norm (vec (triu (R)-R), Inf) == 0);
+%! assert (norm (vec (Q*R - single (A) - single (u)*single (v)'), Inf) < norm (single (A))*1e1*eps ("single"));
 %!
 %!test
-%! [Q,R] = qr(single(Ac));
-%! [Q,R] = qrupdate(Q,R,single(uc),single(vc));
-%! assert(norm(vec(Q'*Q - eye(5,'single')),Inf) < 1e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - single(Ac) - single(uc)*single(vc)'),Inf) < norm(single(Ac))*1e1*eps('single'))
+%! [Q,R] = qr (single (Ac));
+%! [Q,R] = qrupdate (Q, R, single (uc), single (vc));
+%! assert (norm (vec (Q'*Q - eye (5,"single")), Inf) < 1e1*eps ("single"));
+%! assert (norm (vec (triu (R)-R), Inf) == 0);
+%! assert (norm (vec (Q*R - single (Ac) - single (uc)*single (vc)'), Inf) < norm (single (Ac))*1e1*eps ("single"));
 */
 
 DEFUN_DLD (qrinsert, args, ,
@@ -1110,62 +1095,62 @@
 
 /*
 %!test
-%! [Q,R] = qr(A);
-%! [Q,R] = qrinsert(Q,R,3,u);
-%! assert(norm(vec(Q'*Q - eye(5)),Inf) < 1e1*eps)
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - [A(:,1:2) u A(:,3)]),Inf) < norm(A)*1e1*eps)
+%! [Q,R] = qr (A);
+%! [Q,R] = qrinsert (Q, R, 3, u);
+%! assert (norm (vec (Q'*Q - eye (5)), Inf) < 1e1*eps);
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - [A(:,1:2) u A(:,3)]), Inf) < norm (A)*1e1*eps);
 %!test
-%! [Q,R] = qr(Ac);
-%! [Q,R] = qrinsert(Q,R,3,uc);
-%! assert(norm(vec(Q'*Q - eye(5)),Inf) < 1e1*eps)
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - [Ac(:,1:2) uc Ac(:,3)]),Inf) < norm(Ac)*1e1*eps)
+%! [Q,R] = qr (Ac);
+%! [Q,R] = qrinsert (Q, R, 3, uc);
+%! assert (norm (vec (Q'*Q - eye (5)), Inf) < 1e1*eps);
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - [Ac(:,1:2) uc Ac(:,3)]), Inf) < norm (Ac)*1e1*eps);
 %!test
 %! x = [0.85082  0.76426  0.42883 ];
 %!
-%! [Q,R] = qr(A);
-%! [Q,R] = qrinsert(Q,R,3,x,'row');
-%! assert(norm(vec(Q'*Q - eye(6)),Inf) < 1e1*eps)
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - [A(1:2,:);x;A(3:5,:)]),Inf) < norm(A)*1e1*eps)
+%! [Q,R] = qr (A);
+%! [Q,R] = qrinsert (Q, R, 3, x, "row");
+%! assert (norm (vec (Q'*Q - eye (6)), Inf) < 1e1*eps);
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - [A(1:2,:);x;A(3:5,:)]), Inf) < norm (A)*1e1*eps);
 %!test
 %! x = [0.20351 + 0.05401i  0.13141 + 0.43708i  0.29808 + 0.08789i ];
 %!
-%! [Q,R] = qr(Ac);
-%! [Q,R] = qrinsert(Q,R,3,x,'row');
-%! assert(norm(vec(Q'*Q - eye(6)),Inf) < 1e1*eps)
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - [Ac(1:2,:);x;Ac(3:5,:)]),Inf) < norm(Ac)*1e1*eps)
+%! [Q,R] = qr (Ac);
+%! [Q,R] = qrinsert (Q, R, 3, x, "row");
+%! assert (norm (vec (Q'*Q - eye (6)), Inf) < 1e1*eps);
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - [Ac(1:2,:);x;Ac(3:5,:)]), Inf) < norm (Ac)*1e1*eps);
 
 %!test
-%! [Q,R] = qr(single(A));
-%! [Q,R] = qrinsert(Q,R,3,single(u));
-%! assert(norm(vec(Q'*Q - eye(5,'single')),Inf) < 1e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - single([A(:,1:2) u A(:,3)])),Inf) < norm(single(A))*1e1*eps('single'))
+%! [Q,R] = qr (single (A));
+%! [Q,R] = qrinsert (Q, R, 3, single (u));
+%! assert (norm (vec (Q'*Q - eye (5,"single")), Inf) < 1e1*eps ("single"));
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - single ([A(:,1:2) u A(:,3)])), Inf) < norm (single (A))*1e1*eps ("single"));
 %!test
-%! [Q,R] = qr(single(Ac));
-%! [Q,R] = qrinsert(Q,R,3,single(uc));
-%! assert(norm(vec(Q'*Q - eye(5,'single')),Inf) < 1e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - single([Ac(:,1:2) uc Ac(:,3)])),Inf) < norm(single(Ac))*1e1*eps('single'))
+%! [Q,R] = qr (single (Ac));
+%! [Q,R] = qrinsert (Q, R, 3, single (uc));
+%! assert (norm (vec (Q'*Q - eye (5,"single")), Inf) < 1e1*eps ("single"));
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - single ([Ac(:,1:2) uc Ac(:,3)])), Inf) < norm (single (Ac))*1e1*eps ("single"));
 %!test
-%! x = single([0.85082  0.76426  0.42883 ]);
+%! x = single ([0.85082  0.76426  0.42883 ]);
 %!
-%! [Q,R] = qr(single(A));
-%! [Q,R] = qrinsert(Q,R,3,x,'row');
-%! assert(norm(vec(Q'*Q - eye(6,'single')),Inf) < 1e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - single([A(1:2,:);x;A(3:5,:)])),Inf) < norm(single(A))*1e1*eps('single'))
+%! [Q,R] = qr (single (A));
+%! [Q,R] = qrinsert (Q, R, 3, x, "row");
+%! assert (norm (vec (Q'*Q - eye (6,"single")), Inf) < 1e1*eps ("single"));
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - single ([A(1:2,:);x;A(3:5,:)])), Inf) < norm (single (A))*1e1*eps ("single"));
 %!test
-%! x = single([0.20351 + 0.05401i  0.13141 + 0.43708i  0.29808 + 0.08789i ]);
+%! x = single ([0.20351 + 0.05401i  0.13141 + 0.43708i  0.29808 + 0.08789i ]);
 %!
-%! [Q,R] = qr(single(Ac));
-%! [Q,R] = qrinsert(Q,R,3,x,'row');
-%! assert(norm(vec(Q'*Q - eye(6,'single')),Inf) < 1e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - single([Ac(1:2,:);x;Ac(3:5,:)])),Inf) < norm(single(Ac))*1e1*eps('single'))
+%! [Q,R] = qr (single (Ac));
+%! [Q,R] = qrinsert (Q, R, 3, x, "row");
+%! assert (norm (vec (Q'*Q - eye (6,"single")), Inf) < 1e1*eps ("single"));
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - single ([Ac(1:2,:);x;Ac(3:5,:)])), Inf) < norm (single (Ac))*1e1*eps ("single"));
 */
 
 DEFUN_DLD (qrdelete, args, ,
@@ -1176,7 +1161,7 @@
 @var{R}@tie{}upper trapezoidal, return the QR@tie{}factorization of\n\
 @w{[A(:,1:j-1) A(:,j+1:n)]}, i.e., @var{A} with one column deleted\n\
 (if @var{orient} is \"col\"), or the QR@tie{}factorization of\n\
-@w{[A(1:j-1,:);A(j+1:n,:)]}, i.e., @var{A} with one row deleted (if\n   \
+@w{[A(1:j-1,:);A(j+1:n,:)]}, i.e., @var{A} with one row deleted (if\n\
 @var{orient} is \"row\").\n\
 \n\
 The default value of @var{orient} is \"col\".\n\
@@ -1322,11 +1307,11 @@
 %!       0.265712  0.268003  0.783553  0.238409;
 %!       0.669966  0.743851  0.457255  0.445057 ];
 %!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrdelete(Q,R,3);
-%! assert(norm(vec(Q'*Q - eye(5)),Inf) < 16*eps)
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - [AA(:,1:2) AA(:,4)]),Inf) < norm(AA)*1e1*eps)
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrdelete (Q, R, 3);
+%! assert (norm (vec (Q'*Q - eye (5)), Inf) < 16*eps);
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - [AA(:,1:2) AA(:,4)]), Inf) < norm (AA)*1e1*eps);
 %!
 %!test
 %! AA = [0.364554 + 0.993117i  0.669818 + 0.510234i  0.426568 + 0.041337i  0.847051 + 0.233291i;
@@ -1335,11 +1320,11 @@
 %!       0.694986 + 0.000571i  0.682327 + 0.841712i  0.807537 + 0.166086i  0.192767 + 0.358098i;
 %!       0.945002 + 0.066788i  0.350492 + 0.642638i  0.579629 + 0.048102i  0.600170 + 0.636938i ] * I;
 %!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrdelete(Q,R,3);
-%! assert(norm(vec(Q'*Q - eye(5)),Inf) < 16*eps)
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - [AA(:,1:2) AA(:,4)]),Inf) < norm(AA)*1e1*eps)
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrdelete (Q, R, 3);
+%! assert (norm (vec (Q'*Q - eye (5)), Inf) < 16*eps);
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - [AA(:,1:2) AA(:,4)]), Inf) < norm (AA)*1e1*eps);
 %!
 %!test
 %! AA = [0.091364  0.613038  0.027504  0.999083;
@@ -1348,11 +1333,11 @@
 %!       0.265712  0.268003  0.783553  0.238409;
 %!       0.669966  0.743851  0.457255  0.445057 ];
 %!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrdelete(Q,R,3,'row');
-%! assert(norm(vec(Q'*Q - eye(4)),Inf) < 1e1*eps)
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - [AA(1:2,:);AA(4:5,:)]),Inf) < norm(AA)*1e1*eps)
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrdelete (Q, R, 3, "row");
+%! assert (norm (vec (Q'*Q - eye (4)), Inf) < 1e1*eps);
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - [AA(1:2,:);AA(4:5,:)]), Inf) < norm (AA)*1e1*eps);
 %!
 %!test
 %! AA = [0.364554 + 0.993117i  0.669818 + 0.510234i  0.426568 + 0.041337i  0.847051 + 0.233291i;
@@ -1361,76 +1346,76 @@
 %!       0.694986 + 0.000571i  0.682327 + 0.841712i  0.807537 + 0.166086i  0.192767 + 0.358098i;
 %!       0.945002 + 0.066788i  0.350492 + 0.642638i  0.579629 + 0.048102i  0.600170 + 0.636938i ] * I;
 %!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrdelete(Q,R,3,'row');
-%! assert(norm(vec(Q'*Q - eye(4)),Inf) < 1e1*eps)
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - [AA(1:2,:);AA(4:5,:)]),Inf) < norm(AA)*1e1*eps)
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrdelete (Q, R, 3, "row");
+%! assert (norm (vec (Q'*Q - eye (4)), Inf) < 1e1*eps);
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - [AA(1:2,:);AA(4:5,:)]), Inf) < norm (AA)*1e1*eps);
 
 %!test
-%! AA = single([0.091364  0.613038  0.027504  0.999083;
-%!              0.594638  0.425302  0.562834  0.603537;
-%!              0.383594  0.291238  0.742073  0.085574;
-%!              0.265712  0.268003  0.783553  0.238409;
-%!              0.669966  0.743851  0.457255  0.445057 ]);
+%! AA = single ([0.091364  0.613038  0.027504  0.999083;
+%!               0.594638  0.425302  0.562834  0.603537;
+%!               0.383594  0.291238  0.742073  0.085574;
+%!               0.265712  0.268003  0.783553  0.238409;
+%!               0.669966  0.743851  0.457255  0.445057 ]);
+%!
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrdelete (Q, R, 3);
+%! assert (norm (vec (Q'*Q - eye (5,"single")), Inf) < 1e1*eps ("single"));
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - [AA(:,1:2) AA(:,4)]), Inf) < norm (AA)*1e1*eps ("single"));
 %!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrdelete(Q,R,3);
-%! assert(norm(vec(Q'*Q - eye(5,'single')),Inf) < 1e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - [AA(:,1:2) AA(:,4)]),Inf) < norm(AA)*1e1*eps('single'))
+%!test
+%! AA = single ([0.364554 + 0.993117i  0.669818 + 0.510234i  0.426568 + 0.041337i  0.847051 + 0.233291i;
+%!               0.049600 + 0.242783i  0.448946 + 0.484022i  0.141155 + 0.074420i  0.446746 + 0.392706i;
+%!               0.581922 + 0.657416i  0.581460 + 0.030016i  0.219909 + 0.447288i  0.201144 + 0.069132i;
+%!               0.694986 + 0.000571i  0.682327 + 0.841712i  0.807537 + 0.166086i  0.192767 + 0.358098i;
+%!               0.945002 + 0.066788i  0.350492 + 0.642638i  0.579629 + 0.048102i  0.600170 + 0.636938i ]) * I;
+%!
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrdelete (Q, R, 3);
+%! assert (norm (vec (Q'*Q - eye (5,"single")), Inf) < 1e1*eps ("single"));
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - [AA(:,1:2) AA(:,4)]), Inf) < norm (AA)*1e1*eps ("single"));
 %!
 %!test
-%! AA = single([0.364554 + 0.993117i  0.669818 + 0.510234i  0.426568 + 0.041337i  0.847051 + 0.233291i;
+%! AA = single ([0.091364  0.613038  0.027504  0.999083;
+%!               0.594638  0.425302  0.562834  0.603537;
+%!               0.383594  0.291238  0.742073  0.085574;
+%!               0.265712  0.268003  0.783553  0.238409;
+%!               0.669966  0.743851  0.457255  0.445057 ]);
+%!
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrdelete (Q, R, 3, "row");
+%! assert (norm (vec (Q'*Q - eye (4,"single")), Inf) < 1.5e1*eps ("single"));
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - [AA(1:2,:);AA(4:5,:)]), Inf) < norm (AA)*1e1*eps ("single"));
+%!testif HAVE_QRUPDATE
+%! # Same test as above but with more precicision
+%! AA = single ([0.091364  0.613038  0.027504  0.999083;
+%!               0.594638  0.425302  0.562834  0.603537;
+%!               0.383594  0.291238  0.742073  0.085574;
+%!               0.265712  0.268003  0.783553  0.238409;
+%!               0.669966  0.743851  0.457255  0.445057 ]);
+%!
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrdelete (Q, R, 3, "row");
+%! assert (norm (vec (Q'*Q - eye (4,"single")), Inf) < 1e1*eps ("single"));
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - [AA(1:2,:);AA(4:5,:)]), Inf) < norm (AA)*1e1*eps ("single"));
+%!
+%!test
+%! AA = single ([0.364554 + 0.993117i  0.669818 + 0.510234i  0.426568 + 0.041337i  0.847051 + 0.233291i;
 %!              0.049600 + 0.242783i  0.448946 + 0.484022i  0.141155 + 0.074420i  0.446746 + 0.392706i;
 %!              0.581922 + 0.657416i  0.581460 + 0.030016i  0.219909 + 0.447288i  0.201144 + 0.069132i;
 %!              0.694986 + 0.000571i  0.682327 + 0.841712i  0.807537 + 0.166086i  0.192767 + 0.358098i;
 %!              0.945002 + 0.066788i  0.350492 + 0.642638i  0.579629 + 0.048102i  0.600170 + 0.636938i ]) * I;
 %!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrdelete(Q,R,3);
-%! assert(norm(vec(Q'*Q - eye(5,'single')),Inf) < 1e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - [AA(:,1:2) AA(:,4)]),Inf) < norm(AA)*1e1*eps('single'))
-%!
-%!test
-%! AA = single([0.091364  0.613038  0.027504  0.999083;
-%!              0.594638  0.425302  0.562834  0.603537;
-%!              0.383594  0.291238  0.742073  0.085574;
-%!              0.265712  0.268003  0.783553  0.238409;
-%!              0.669966  0.743851  0.457255  0.445057 ]);
-%!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrdelete(Q,R,3,'row');
-%! assert(norm(vec(Q'*Q - eye(4,'single')),Inf) < 1.5e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - [AA(1:2,:);AA(4:5,:)]),Inf) < norm(AA)*1e1*eps('single'))
-%!testif HAVE_QRUPDATE
-%! # Same test as above but with more precicision
-%! AA = single([0.091364  0.613038  0.027504  0.999083;
-%!              0.594638  0.425302  0.562834  0.603537;
-%!              0.383594  0.291238  0.742073  0.085574;
-%!              0.265712  0.268003  0.783553  0.238409;
-%!              0.669966  0.743851  0.457255  0.445057 ]);
-%!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrdelete(Q,R,3,'row');
-%! assert(norm(vec(Q'*Q - eye(4,'single')),Inf) < 1e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - [AA(1:2,:);AA(4:5,:)]),Inf) < norm(AA)*1e1*eps('single'))
-%!
-%!test
-%! AA = single([0.364554 + 0.993117i  0.669818 + 0.510234i  0.426568 + 0.041337i  0.847051 + 0.233291i;
-%!              0.049600 + 0.242783i  0.448946 + 0.484022i  0.141155 + 0.074420i  0.446746 + 0.392706i;
-%!              0.581922 + 0.657416i  0.581460 + 0.030016i  0.219909 + 0.447288i  0.201144 + 0.069132i;
-%!              0.694986 + 0.000571i  0.682327 + 0.841712i  0.807537 + 0.166086i  0.192767 + 0.358098i;
-%!              0.945002 + 0.066788i  0.350492 + 0.642638i  0.579629 + 0.048102i  0.600170 + 0.636938i ]) * I;
-%!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrdelete(Q,R,3,'row');
-%! assert(norm(vec(Q'*Q - eye(4,'single')),Inf) < 1e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - [AA(1:2,:);AA(4:5,:)]),Inf) < norm(AA)*1e1*eps('single'))
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrdelete (Q, R, 3, "row");
+%! assert (norm (vec (Q'*Q - eye (4,"single")), Inf) < 1e1*eps ("single"));
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - [AA(1:2,:);AA(4:5,:)]), Inf) < norm (AA)*1e1*eps ("single"));
 */
 
 DEFUN_DLD (qrshift, args, ,
@@ -1537,77 +1522,77 @@
 
   return retval;
 }
+
 /*
 %!test
 %! AA = A.';
-%! i = 2; j = 4; p = [1:i-1, shift(i:j,-1), j+1:5];
+%! i = 2;  j = 4;  p = [1:i-1, shift(i:j,-1), j+1:5];
 %!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrshift(Q,R,i,j);
-%! assert(norm(vec(Q'*Q - eye(3)),Inf) < 1e1*eps)
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - AA(:,p)),Inf) < norm(AA)*1e1*eps)
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrshift (Q, R, i, j);
+%! assert (norm (vec (Q'*Q - eye (3)), Inf) < 1e1*eps);
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - AA(:,p)), Inf) < norm (AA)*1e1*eps);
 %!
-%! j = 2; i = 4; p = [1:j-1, shift(j:i,+1), i+1:5];
+%! j = 2;  i = 4;  p = [1:j-1, shift(j:i,+1), i+1:5];
 %!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrshift(Q,R,i,j);
-%! assert(norm(vec(Q'*Q - eye(3)),Inf) < 1e1*eps)
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - AA(:,p)),Inf) < norm(AA)*1e1*eps)
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrshift (Q, R, i, j);
+%! assert (norm (vec (Q'*Q - eye (3)), Inf) < 1e1*eps);
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - AA(:,p)), Inf) < norm (AA)*1e1*eps);
 %!
 %!test
 %! AA = Ac.';
-%! i = 2; j = 4; p = [1:i-1, shift(i:j,-1), j+1:5];
+%! i = 2;  j = 4;  p = [1:i-1, shift(i:j,-1), j+1:5];
 %!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrshift(Q,R,i,j);
-%! assert(norm(vec(Q'*Q - eye(3)),Inf) < 1e1*eps)
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - AA(:,p)),Inf) < norm(AA)*1e1*eps)
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrshift (Q, R, i, j);
+%! assert (norm (vec (Q'*Q - eye (3)), Inf) < 1e1*eps);
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - AA(:,p)), Inf) < norm (AA)*1e1*eps);
 %!
-%! j = 2; i = 4; p = [1:j-1, shift(j:i,+1), i+1:5];
+%! j = 2;  i = 4;  p = [1:j-1, shift(j:i,+1), i+1:5];
 %!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrshift(Q,R,i,j);
-%! assert(norm(vec(Q'*Q - eye(3)),Inf) < 1e1*eps)
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - AA(:,p)),Inf) < norm(AA)*1e1*eps)
-
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrshift (Q, R, i, j);
+%! assert (norm (vec (Q'*Q - eye (3)), Inf) < 1e1*eps);
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - AA(:,p)), Inf) < norm (AA)*1e1*eps);
 
 %!test
 %! AA = single (A).';
-%! i = 2; j = 4; p = [1:i-1, shift(i:j,-1), j+1:5];
+%! i = 2;  j = 4;  p = [1:i-1, shift(i:j,-1), j+1:5];
 %!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrshift(Q,R,i,j);
-%! assert(norm(vec(Q'*Q - eye(3,'single')),Inf) < 1e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - AA(:,p)),Inf) < norm(AA)*1e1*eps('single'))
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrshift (Q, R, i, j);
+%! assert (norm (vec (Q'*Q - eye (3,"single")), Inf) < 1e1*eps ("single"));
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - AA(:,p)), Inf) < norm (AA)*1e1*eps ("single"));
 %!
-%! j = 2; i = 4; p = [1:j-1, shift(j:i,+1), i+1:5];
+%! j = 2;  i = 4;  p = [1:j-1, shift(j:i,+1), i+1:5];
 %!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrshift(Q,R,i,j);
-%! assert(norm(vec(Q'*Q - eye(3,'single')),Inf) < 1e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - AA(:,p)),Inf) < norm(AA)*1e1*eps('single'))
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrshift (Q, R, i, j);
+%! assert (norm (vec (Q'*Q - eye (3,"single")), Inf) < 1e1*eps ("single"));
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - AA(:,p)), Inf) < norm (AA)*1e1*eps ("single"));
 %!
 %!test
-%! AA = single(Ac).';
-%! i = 2; j = 4; p = [1:i-1, shift(i:j,-1), j+1:5];
+%! AA = single (Ac).';
+%! i = 2;  j = 4;  p = [1:i-1, shift(i:j,-1), j+1:5];
 %!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrshift(Q,R,i,j);
-%! assert(norm(vec(Q'*Q - eye(3,'single')),Inf) < 1e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - AA(:,p)),Inf) < norm(AA)*1e1*eps('single'))
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrshift (Q, R, i, j);
+%! assert (norm (vec (Q'*Q - eye (3,"single")), Inf) < 1e1*eps ("single"));
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - AA(:,p)), Inf) < norm (AA)*1e1*eps ("single"));
 %!
-%! j = 2; i = 4; p = [1:j-1, shift(j:i,+1), i+1:5];
+%! j = 2;  i = 4;  p = [1:j-1, shift(j:i,+1), i+1:5];
 %!
-%! [Q,R] = qr(AA);
-%! [Q,R] = qrshift(Q,R,i,j);
-%! assert(norm(vec(Q'*Q - eye(3,'single')),Inf) < 1e1*eps('single'))
-%! assert(norm(vec(triu(R)-R),Inf) == 0)
-%! assert(norm(vec(Q*R - AA(:,p)),Inf) < norm(AA)*1e1*eps('single'))
+%! [Q,R] = qr (AA);
+%! [Q,R] = qrshift (Q, R, i, j);
+%! assert (norm (vec (Q'*Q - eye (3,"single")), Inf) < 1e1*eps ("single"));
+%! assert (norm (vec (triu (R) - R), Inf) == 0);
+%! assert (norm (vec (Q*R - AA(:,p)), Inf) < norm (AA)*1e1*eps ("single"));
 */
rename from src/DLD-FUNCTIONS/symbfact.cc
rename to libinterp/dldfcn/symbfact.cc
--- a/src/DLD-FUNCTIONS/symbfact.cc
+++ b/libinterp/dldfcn/symbfact.cc
@@ -132,7 +132,7 @@
   A->packed = true;
   A->sorted = true;
   A->nz = 0;
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
   A->itype = CHOLMOD_LONG;
 #else
   A->itype = CHOLMOD_INT;
@@ -143,29 +143,29 @@
 
   if (args(0).is_real_type ())
     {
-      const SparseMatrix a = args(0).sparse_matrix_value();
-      A->nrow = a.rows();
-      A->ncol = a.cols();
-      A->p = a.cidx();
-      A->i = a.ridx();
-      A->nzmax = a.nnz();
+      const SparseMatrix a = args(0).sparse_matrix_value ();
+      A->nrow = a.rows ();
+      A->ncol = a.cols ();
+      A->p = a.cidx ();
+      A->i = a.ridx ();
+      A->nzmax = a.nnz ();
       A->xtype = CHOLMOD_REAL;
 
-      if (a.rows() > 0 && a.cols() > 0)
-        A->x = a.data();
+      if (a.rows () > 0 && a.cols () > 0)
+        A->x = a.data ();
     }
   else if (args(0).is_complex_type ())
     {
-      const SparseComplexMatrix a = args(0).sparse_complex_matrix_value();
-      A->nrow = a.rows();
-      A->ncol = a.cols();
-      A->p = a.cidx();
-      A->i = a.ridx();
-      A->nzmax = a.nnz();
+      const SparseComplexMatrix a = args(0).sparse_complex_matrix_value ();
+      A->nrow = a.rows ();
+      A->ncol = a.cols ();
+      A->p = a.cidx ();
+      A->i = a.ridx ();
+      A->nzmax = a.nnz ();
       A->xtype = CHOLMOD_COMPLEX;
 
-      if (a.rows() > 0 && a.cols() > 0)
-        A->x = a.data();
+      if (a.rows () > 0 && a.cols () > 0)
+        A->x = a.data ();
     }
   else
     gripe_wrong_type_arg ("symbfact", args(0));
@@ -176,8 +176,8 @@
   if (nargin > 1)
     {
       char ch;
-      std::string str = args(1).string_value();
-      ch = tolower (str.c_str()[0]);
+      std::string str = args(1).string_value ();
+      ch = tolower (str.c_str ()[0]);
       if (ch == 'r')
         A->stype = 0;
       else if (ch == 'c')
@@ -223,13 +223,13 @@
 
       if (cm->status < CHOLMOD_OK)
         {
-          error("matrix corrupted");
+          error ("matrix corrupted");
           goto symbfact_error;
         }
 
       if (CHOLMOD_NAME(postorder) (Parent, n, 0, Post, cm) != n)
         {
-          error("postorder failed");
+          error ("postorder failed");
           goto symbfact_error;
         }
 
@@ -238,7 +238,7 @@
 
       if (cm->status < CHOLMOD_OK)
         {
-          error("matrix corrupted");
+          error ("matrix corrupted");
           goto symbfact_error;
         }
 
@@ -270,7 +270,7 @@
           // count the total number of entries in L
           octave_idx_type lnz = 0 ;
           for (octave_idx_type j = 0 ; j < n ; j++)
-            lnz += ColCount [j] ;
+            lnz += ColCount[j];
 
 
           // allocate the output matrix L (pattern-only)
@@ -281,7 +281,7 @@
           for (octave_idx_type j = 0 ; j < n ; j++)
             {
               L.xcidx(j) = lnz;
-              lnz += ColCount [j];
+              lnz += ColCount[j];
             }
           L.xcidx(n) = lnz;
 
@@ -289,11 +289,12 @@
           /* create a copy of the column pointers */
           octave_idx_type *W = First;
           for (octave_idx_type j = 0 ; j < n ; j++)
-            W [j] = L.xcidx(j);
+            W[j] = L.xcidx (j);
 
           // get workspace for computing one row of L
-          cholmod_sparse *R = cholmod_allocate_sparse (n, 1, n, false, true,
-                                                       0, CHOLMOD_PATTERN, cm);
+          cholmod_sparse *R
+            = CHOLMOD_NAME (allocate_sparse) (n, 1, n, false, true,
+                                              0, CHOLMOD_PATTERN, cm);
           octave_idx_type *Rp = static_cast<octave_idx_type *>(R->p);
           octave_idx_type *Ri = static_cast<octave_idx_type *>(R->i);
 
@@ -302,15 +303,15 @@
             {
               // get the kth row of L and store in the columns of L
               CHOLMOD_NAME (row_subtree) (A1, A2, k, Parent, R, cm) ;
-              for (octave_idx_type p = 0 ; p < Rp [1] ; p++)
-                L.xridx (W [Ri [p]]++) = k ;
+              for (octave_idx_type p = 0 ; p < Rp[1] ; p++)
+                L.xridx (W[Ri[p]]++) = k ;
 
               // add the diagonal entry
-              L.xridx (W [k]++) = k ;
+              L.xridx (W[k]++) = k ;
             }
 
           // free workspace
-          cholmod_free_sparse (&R, cm) ;
+          CHOLMOD_NAME (free_sparse) (&R, cm) ;
 
 
           // transpose L to get R, or leave as is
rename from src/DLD-FUNCTIONS/symrcm.cc
rename to libinterp/dldfcn/symrcm.cc
--- a/src/DLD-FUNCTIONS/symrcm.cc
+++ b/libinterp/dldfcn/symrcm.cc
@@ -135,9 +135,7 @@
 
       if (smallest != j)
         {
-          CMK_Node tmp = A[j];
-          A[j] = A[smallest];
-          A[smallest] = tmp;
+          std::swap (A[j], A[smallest]);
           j = smallest;
         }
       else
@@ -161,9 +159,7 @@
       octave_idx_type p = PARENT(i);
       if (H[i].deg < H[p].deg)
         {
-          CMK_Node tmp = H[i];
-          H[i] = H[p];
-          H[p] = tmp;
+          std::swap (H[i], H[p]);
 
           i = p;
         }
@@ -182,7 +178,7 @@
   CMK_Node r = H[0];
   H[0] = H[--h];
   if (reorg)
-    H_heapify_min(H, 0, h);
+    H_heapify_min (H, 0, h);
   return r;
 }
 
@@ -409,7 +405,7 @@
     for (octave_idx_type k = cidx[j]; k < cidx[j + 1]; k++)
       {
         OCTAVE_QUIT;
-        octave_idx_type q = w [ridx[k]]++;
+        octave_idx_type q = w[ridx[k]]++;
         ridx2[q] = j;
       }
 }
@@ -422,7 +418,7 @@
 @var{p} is a permutation vector such that\n\
 @code{@var{S}(@var{p}, @var{p})} tends to have its diagonal elements\n\
 closer to the diagonal than @var{S}.  This is a good preordering for LU\n\
-or Cholesky@tie{}factorization of matrices that come from 'long, skinny'\n\
+or Cholesky@tie{}factorization of matrices that come from ``long, skinny''\n\
 problems.  It works for both symmetric and asymmetric @var{S}.\n\
 \n\
 The algorithm represents a heuristic approach to the NP-complete\n\
@@ -601,7 +597,7 @@
                       w.id = r2;
                       w.deg = D[r2];
                       w.dist = v.dist+1;
-                      H_insert(S, s, w);
+                      H_insert (S, s, w);
                       visit[r2] = true;
                     }
                 }
@@ -613,7 +609,7 @@
                       w.id = r1;
                       w.deg = D[r1];
                       w.dist = v.dist+1;
-                      H_insert(S, s, w);
+                      H_insert (S, s, w);
                       visit[r1] = true;
                     }
                 }
@@ -628,7 +624,7 @@
                           w.id = r1;
                           w.deg = D[r1];
                           w.dist = v.dist+1;
-                          H_insert(S, s, w);
+                          H_insert (S, s, w);
                           visit[r1] = true;
                         }
                       j1++;
@@ -642,7 +638,7 @@
                           w.id = r2;
                           w.deg = D[r2];
                           w.dist = v.dist+1;
-                          H_insert(S, s, w);
+                          H_insert (S, s, w);
                           visit[r2] = true;
                         }
                       j2++;
@@ -656,7 +652,7 @@
               OCTAVE_QUIT;
 
               // locate a neighbor of i with minimal degree in O(log(N))
-              v = H_remove_min(S, s, 1);
+              v = H_remove_min (S, s, 1);
 
               // entered the BFS a new level?
               if (v.dist > level)
@@ -699,11 +695,7 @@
   // compute the reverse-ordering
   s = N / 2 - 1;
   for (octave_idx_type i = 0, j = N - 1; i <= s; i++, j--)
-    {
-      double tmp = P.elem(i);
-      P.elem(i) = P.elem(j);
-      P.elem(j) = tmp;
-    }
+    std::swap (P.elem (i), P.elem (j));
 
   // increment all indices, since Octave is not C
   return octave_value (P+1);
rename from src/DLD-FUNCTIONS/tsearch.cc
rename to libinterp/dldfcn/tsearch.cc
--- a/src/DLD-FUNCTIONS/tsearch.cc
+++ b/libinterp/dldfcn/tsearch.cc
@@ -176,11 +176,11 @@
 %! x = [-1;-1;1];
 %! y = [-1;1;-1];
 %! tri = [1, 2, 3];
-%!error (tsearch())
 %!assert (tsearch (x,y,tri,-1,-1), 1)
 %!assert (tsearch (x,y,tri, 1,-1), 1)
 %!assert (tsearch (x,y,tri,-1, 1), 1)
 %!assert (tsearch (x,y,tri,-1/3, -1/3), 1)
 %!assert (tsearch (x,y,tri, 1, 1), NaN)
 
+%!error tsearch ()
 */
rename from src/DLD-FUNCTIONS/urlwrite.cc
rename to libinterp/dldfcn/urlwrite.cc
--- a/src/DLD-FUNCTIONS/urlwrite.cc
+++ b/libinterp/dldfcn/urlwrite.cc
@@ -144,6 +144,8 @@
 
     octave_refcount<size_t> count;
     std::string host;
+    std::string url;
+    std::string userpwd;
     bool valid;
     bool ascii;
     mutable CURLcode errnum;
@@ -182,8 +184,8 @@
       rep->host = _host;
       init (user, passwd, std::cin, octave_stdout);
 
-      std::string url = "ftp://" + _host;
-      setopt (CURLOPT_URL, url.c_str());
+      rep->url = "ftp://" + _host;
+      setopt (CURLOPT_URL, rep->url.c_str ());
 
       // Setup the link, with no transfer
       if (!error_state)
@@ -200,6 +202,11 @@
 
       setopt (CURLOPT_NOBODY, 0);
 
+      // Restore the default HTTP request method to GET after setting
+      // NOBODY to true and back to false.  This is needed for backward
+      // compatibility with versions of libcurl < 7.18.2.
+      setopt (CURLOPT_HTTPGET, 1);
+
       // Don't need to store the parameters here as we can't change
       // the URL after the handle is created
       std::string query_string = form_query_string (param);
@@ -215,7 +222,7 @@
           setopt (CURLOPT_POSTFIELDS, query_string.c_str ());
         }
       else
-        setopt (CURLOPT_URL, url.c_str());
+        setopt (CURLOPT_URL, url.c_str ());
 
       if (!error_state)
         retval = perform (false);
@@ -291,7 +298,7 @@
     {
       struct curl_slist *slist = 0;
       std::string cmd = "cwd " + path;
-      slist = curl_slist_append (slist, cmd.c_str());
+      slist = curl_slist_append (slist, cmd.c_str ());
       setopt (CURLOPT_POSTQUOTE, slist);
       if (! error_state)
         perform ();
@@ -303,7 +310,7 @@
     {
       struct curl_slist *slist = 0;
       std::string cmd = "dele " + file;
-      slist = curl_slist_append (slist, cmd.c_str());
+      slist = curl_slist_append (slist, cmd.c_str ());
       setopt (CURLOPT_POSTQUOTE, slist);
       if (! error_state)
         perform ();
@@ -315,7 +322,7 @@
     {
       struct curl_slist *slist = 0;
       std::string cmd = "rmd " + path;
-      slist = curl_slist_append (slist, cmd.c_str());
+      slist = curl_slist_append (slist, cmd.c_str ());
       setopt (CURLOPT_POSTQUOTE, slist);
       if (! error_state)
         perform ();
@@ -328,7 +335,7 @@
       bool retval = false;
       struct curl_slist *slist = 0;
       std::string cmd = "mkd " + path;
-      slist = curl_slist_append (slist, cmd.c_str());
+      slist = curl_slist_append (slist, cmd.c_str ());
       setopt (CURLOPT_POSTQUOTE, slist);
       if (! error_state)
         retval = perform (curlerror);
@@ -341,9 +348,9 @@
     {
       struct curl_slist *slist = 0;
       std::string cmd = "rnfr " + oldname;
-      slist = curl_slist_append (slist, cmd.c_str());
+      slist = curl_slist_append (slist, cmd.c_str ());
       cmd = "rnto " + newname;
-      slist = curl_slist_append (slist, cmd.c_str());
+      slist = curl_slist_append (slist, cmd.c_str ());
       setopt (CURLOPT_POSTQUOTE, slist);
       if (! error_state)
         perform ();
@@ -353,8 +360,8 @@
 
   void put (const std::string& file, std::istream& is) const
     {
-      std::string url = "ftp://" + rep->host + "/" + file;
-      setopt (CURLOPT_URL, url.c_str());
+      rep->url = "ftp://" + rep->host + "/" + file;
+      setopt (CURLOPT_URL, rep->url.c_str ());
       setopt (CURLOPT_UPLOAD, 1);
       setopt (CURLOPT_NOBODY, 0);
       set_istream (is);
@@ -363,51 +370,51 @@
       set_istream (std::cin);
       setopt (CURLOPT_NOBODY, 1);
       setopt (CURLOPT_UPLOAD, 0);
-      url = "ftp://" + rep->host;
-      setopt (CURLOPT_URL, url.c_str());
+      rep->url = "ftp://" + rep->host;
+      setopt (CURLOPT_URL, rep->url.c_str ());
     }
 
   void get (const std::string& file, std::ostream& os) const
     {
-      std::string url = "ftp://" + rep->host + "/" + file;
-      setopt (CURLOPT_URL, url.c_str());
+      rep->url = "ftp://" + rep->host + "/" + file;
+      setopt (CURLOPT_URL, rep->url.c_str ());
       setopt (CURLOPT_NOBODY, 0);
       set_ostream (os);
       if (! error_state)
         perform ();
       set_ostream (octave_stdout);
       setopt (CURLOPT_NOBODY, 1);
-      url = "ftp://" + rep->host;
-      setopt (CURLOPT_URL, url.c_str());
+      rep->url = "ftp://" + rep->host;
+      setopt (CURLOPT_URL, rep->url.c_str ());
     }
 
   void dir (void) const
     {
-      std::string url = "ftp://" + rep->host + "/";
-      setopt (CURLOPT_URL, url.c_str());
+      rep->url = "ftp://" + rep->host + "/";
+      setopt (CURLOPT_URL, rep->url.c_str ());
       setopt (CURLOPT_NOBODY, 0);
       if (! error_state)
         perform ();
       setopt (CURLOPT_NOBODY, 1);
-      url = "ftp://" + rep->host;
-      setopt (CURLOPT_URL, url.c_str());
+      rep->url = "ftp://" + rep->host;
+      setopt (CURLOPT_URL, rep->url.c_str ());
     }
 
   string_vector list (void) const
     {
       std::ostringstream buf;
-      std::string url = "ftp://" + rep->host + "/";
+      rep->url = "ftp://" + rep->host + "/";
       setopt (CURLOPT_WRITEDATA, static_cast<void*> (&buf));
-      setopt (CURLOPT_URL, url.c_str());
+      setopt (CURLOPT_URL, rep->url.c_str ());
       setopt (CURLOPT_DIRLISTONLY, 1);
       setopt (CURLOPT_NOBODY, 0);
       if (! error_state)
         perform ();
       setopt (CURLOPT_NOBODY, 1);
-      url = "ftp://" + rep->host;
+      rep->url = "ftp://" + rep->host;
       setopt (CURLOPT_WRITEDATA, static_cast<void*> (&octave_stdout));
       setopt (CURLOPT_DIRLISTONLY, 0);
-      setopt (CURLOPT_URL, url.c_str());
+      setopt (CURLOPT_URL, rep->url.c_str ());
 
       // Count number of directory entries
       std::string str = buf.str ();
@@ -415,7 +422,7 @@
       size_t pos = 0;
       while (true)
         {
-          pos = str.find_first_of('\n', pos);
+          pos = str.find_first_of ('\n', pos);
           if (pos == std::string::npos)
             break;
           pos++;
@@ -425,7 +432,7 @@
       pos = 0;
       for (octave_idx_type i = 0; i < n; i++)
         {
-          size_t newpos = str.find_first_of('\n', pos);
+          size_t newpos = str.find_first_of ('\n', pos);
           if (newpos == std::string::npos)
             break;
 
@@ -438,10 +445,10 @@
   void get_fileinfo (const std::string& filename, double& filesize,
                      time_t& filetime, bool& fileisdir) const
     {
-      std::string path = pwd();
+      std::string path = pwd ();
 
-      std::string url = "ftp://" + rep->host + "/" + path + "/" + filename;
-      setopt (CURLOPT_URL, url.c_str());
+      rep->url = "ftp://" + rep->host + "/" + path + "/" + filename;
+      setopt (CURLOPT_URL, rep->url.c_str ());
       setopt (CURLOPT_FILETIME, 1);
       setopt (CURLOPT_HEADERFUNCTION, throw_away);
       setopt (CURLOPT_WRITEFUNCTION, throw_away);
@@ -462,11 +469,11 @@
             {
               fileisdir = false;
               time_t ft;
-              curl_easy_getinfo(rep->handle (), CURLINFO_FILETIME, &ft);
+              curl_easy_getinfo (rep->handle (), CURLINFO_FILETIME, &ft);
               filetime = ft;
               double fs;
-              curl_easy_getinfo(rep->handle (),
-                                CURLINFO_CONTENT_LENGTH_DOWNLOAD, &fs);
+              curl_easy_getinfo (rep->handle (),
+                                 CURLINFO_CONTENT_LENGTH_DOWNLOAD, &fs);
               filesize = fs;
             }
         }
@@ -474,8 +481,8 @@
       setopt (CURLOPT_WRITEFUNCTION, write_data);
       setopt (CURLOPT_HEADERFUNCTION, 0);
       setopt (CURLOPT_FILETIME, 0);
-      url = "ftp://" + rep->host;
-      setopt (CURLOPT_URL, url.c_str());
+      rep->url = "ftp://" + rep->host;
+      setopt (CURLOPT_URL, rep->url.c_str ());
 
       // The MDTM command seems to reset the path to the root with the
       // servers I tested with, so cd again into the correct path. Make
@@ -498,12 +505,12 @@
       if (! error_state)
         {
           perform ();
-          retval = buf.str();
+          retval = buf.str ();
 
           // Can I assume that the path is alway in "" on the last line
           size_t pos2 = retval.rfind ('"');
           size_t pos1 = retval.rfind ('"', pos2 - 1);
-          retval = retval.substr(pos1 + 1, pos2 - pos1 - 1);
+          retval = retval.substr (pos1 + 1, pos2 - pos1 - 1);
         }
       setopt (CURLOPT_HEADERFUNCTION, 0);
       setopt (CURLOPT_WRITEHEADER, 0);
@@ -531,9 +538,9 @@
           std::string text = param(i+1).string_value ();
 
           // Encode strings.
-          char *enc_name = curl_easy_escape (rep->handle(), name.c_str (),
+          char *enc_name = curl_easy_escape (rep->handle (), name.c_str (),
                                              name.length ());
-          char *enc_text = curl_easy_escape (rep->handle(), text.c_str (),
+          char *enc_text = curl_easy_escape (rep->handle (), text.c_str (),
                                              text.length ());
 
           query << enc_name << "=" << enc_text;
@@ -541,7 +548,7 @@
           curl_free (enc_name);
           curl_free (enc_text);
 
-          if (i < param.numel()-1)
+          if (i < param.numel ()-1)
             query << "&";
         }
 
@@ -557,11 +564,11 @@
       setopt (CURLOPT_NOBODY, 1);
 
       // Set the username and password
-      std::string userpwd = user;
+      rep->userpwd = user;
       if (! passwd.empty ())
-        userpwd += ":" + passwd;
-      if (! userpwd.empty ())
-        setopt (CURLOPT_USERPWD, userpwd.c_str ());
+        rep->userpwd += ":" + passwd;
+      if (! rep->userpwd.empty ())
+        setopt (CURLOPT_USERPWD, rep->userpwd.c_str ());
 
       // Define our callback to get called when there's data to be written.
       setopt (CURLOPT_WRITEFUNCTION, write_data);
@@ -603,14 +610,14 @@
 
   curl_handles (void) : map ()
    {
-     curl_global_init(CURL_GLOBAL_DEFAULT);
+     curl_global_init (CURL_GLOBAL_DEFAULT);
    }
 
   ~curl_handles (void)
     {
       // Remove the elements of the map explicitly as they should
       // be deleted before the call to curl_global_cleanup
-      map.erase (begin(), end());
+      map.erase (begin (), end ());
 
       curl_global_cleanup ();
     }
@@ -736,7 +743,7 @@
       return retval;
     }
 
-  std::string url = args(0).string_value();
+  std::string url = args(0).string_value ();
 
   if (error_state)
     {
@@ -745,7 +752,7 @@
     }
 
   // name to store the file if download is succesful
-  std::string filename = args(1).string_value();
+  std::string filename = args(1).string_value ();
 
   if (error_state)
     {
@@ -758,7 +765,7 @@
 
   if (nargin == 4)
     {
-      method = args(2).string_value();
+      method = args(2).string_value ();
 
       if (error_state)
         {
@@ -772,7 +779,7 @@
           return retval;
         }
 
-      param = args(3).cell_value();
+      param = args(3).cell_value ();
 
       if (error_state)
         {
@@ -794,7 +801,7 @@
 
   file_stat fs (filename);
 
-  std::ofstream ofile (filename.c_str(), std::ios::out | std::ios::binary);
+  std::ofstream ofile (filename.c_str (), std::ios::out | std::ios::binary);
 
   if (! ofile.is_open ())
     {
@@ -876,7 +883,7 @@
 @example\n\
 @group\n\
 s = urlread (\"http://www.google.com/search\", \"get\",\n\
-             @{\"query\", \"octave\"@});\n\
+            @{\"query\", \"octave\"@});\n\
 @end group\n\
 @end example\n\
 @seealso{urlwrite}\n\
@@ -896,7 +903,7 @@
       return retval;
     }
 
-  std::string url = args(0).string_value();
+  std::string url = args(0).string_value ();
 
   if (error_state)
     {
@@ -909,7 +916,7 @@
 
   if (nargin == 3)
     {
-      method = args(1).string_value();
+      method = args(1).string_value ();
 
       if (error_state)
         {
@@ -923,7 +930,7 @@
           return retval;
         }
 
-      param = args(2).cell_value();
+      param = args(2).cell_value ();
 
       if (error_state)
         {
@@ -1263,7 +1270,7 @@
           const curl_handle curl = handles.contents (handle);
 
           if (curl.is_valid ())
-            retval = (curl.is_ascii() ? "ascii" : "binary");
+            retval = (curl.is_ascii () ? "ascii" : "binary");
           else
             error ("__ftp_binary__: invalid ftp handle");
         }
@@ -1417,7 +1424,7 @@
 
   if (! curl.mkdir (dir, false))
     warning ("__ftp_mput__: can not create the remote directory ""%s""",
-             (base.length() == 0 ? dir : base +
+             (base.length () == 0 ? dir : base +
               file_ops::dir_sep_str () + dir).c_str ());
 
   curl.cwd (dir);
@@ -1428,7 +1435,7 @@
 
       frame.add_fcn (reset_path, curl);
 
-      std::string realdir = base.length() == 0 ? dir : base +
+      std::string realdir = base.length () == 0 ? dir : base +
                          file_ops::dir_sep_str () + dir;
 
       dir_entry dirlist (realdir);
@@ -1464,7 +1471,7 @@
               else
                 {
                   // FIXME Does ascii mode need to be flagged here?
-                  std::ifstream ifile (realfile.c_str(), std::ios::in |
+                  std::ifstream ifile (realfile.c_str (), std::ios::in |
                                        std::ios::binary);
 
                   if (! ifile.is_open ())
@@ -1487,7 +1494,7 @@
         }
       else
         error ("__ftp_mput__: can not read the directory ""%s""",
-               realdir.c_str());
+               realdir.c_str ());
     }
 
   return retval;
@@ -1542,7 +1549,7 @@
                   else
                     {
                       // FIXME Does ascii mode need to be flagged here?
-                      std::ifstream ifile (file.c_str(), std::ios::in |
+                      std::ifstream ifile (file.c_str (), std::ios::in |
                                            std::ios::binary);
 
                       if (! ifile.is_open ())
@@ -1588,7 +1595,7 @@
 
       if (status < 0)
         error ("__ftp_mget__: can't create directory %s%s%s. %s",
-               target.c_str(), sep.c_str(), dir.c_str(), msg.c_str());
+               target.c_str (), sep.c_str (), dir.c_str (), msg.c_str ());
     }
 
   if (! error_state)
@@ -1616,7 +1623,7 @@
               else
                 {
                   std::string realfile = target + dir + sep + sv(i);
-                  std::ofstream ofile (realfile.c_str(),
+                  std::ofstream ofile (realfile.c_str (),
                                        std::ios::out |
                                        std::ios::binary);
 
@@ -1694,7 +1701,7 @@
                         getallfiles (curl, sv(i), target);
                       else
                         {
-                          std::ofstream ofile ((target + sv(i)).c_str(),
+                          std::ofstream ofile ((target + sv(i)).c_str (),
                                                std::ios::out |
                                                std::ios::binary);
 
rename from src/find-defun-files.sh
rename to libinterp/find-defun-files.sh
--- a/src/find-defun-files.sh
+++ b/libinterp/find-defun-files.sh
@@ -21,6 +21,6 @@
     file="$srcdir/$arg"
   fi
   if [ "`$EGREP -l "$DEFUN_PATTERN" $file`" ]; then
-    echo "$file" | $SED 's,.*/,,; s/\.cc$/.df/; s/\.ll$/.df/; s/\.yy$/.df/';
+    echo "$file" | $SED "s,\\$srcdir/,," | $SED 's/\.cc$/.df/; s/\.ll$/.df/; s/\.in.yy$/.df/';
   fi
 done
rename from src/gendoc.pl
rename to libinterp/gendoc.pl
rename from src/genprops.awk
rename to libinterp/genprops.awk
rename from src/Cell.cc
rename to libinterp/interp-core/Cell.cc
--- a/src/Cell.cc
+++ b/libinterp/interp-core/Cell.cc
@@ -97,7 +97,7 @@
 // SV as possible.
 
 Cell::Cell (const dim_vector& dv, const string_vector& sv, bool trim)
-  : Array<octave_value> (dv, resize_fill_value ())
+  : Array<octave_value> (dv, Matrix ())
 {
   octave_idx_type n = sv.length ();
 
@@ -173,8 +173,7 @@
         idx_vector i = idx_arg(0).index_vector ();
 
         if (! error_state)
-          retval = Array<octave_value>::index (i, resize_ok,
-                                               resize_fill_value ());
+          retval = Array<octave_value>::index (i, resize_ok, Matrix ());
       }
       break;
 
@@ -187,8 +186,7 @@
             idx_vector j = idx_arg(1).index_vector ();
 
             if (! error_state)
-              retval = Array<octave_value>::index (i, j, resize_ok,
-                                                    resize_fill_value ());
+              retval = Array<octave_value>::index (i, j, resize_ok, Matrix ());
           }
       }
       break;
@@ -206,8 +204,7 @@
           }
 
         if (!error_state)
-          retval = Array<octave_value>::index (iv, resize_ok,
-                                                resize_fill_value ());
+          retval = Array<octave_value>::index (iv, resize_ok, Matrix ());
       }
       break;
     }
@@ -315,3 +312,9 @@
 {
   return Array<octave_value>::diag (k);
 }
+
+Cell
+Cell::diag (octave_idx_type m, octave_idx_type n) const
+{
+  return Array<octave_value>::diag (m, n);
+}
rename from src/Cell.h
rename to libinterp/interp-core/Cell.h
--- a/src/Cell.h
+++ b/libinterp/interp-core/Cell.h
@@ -48,10 +48,10 @@
   Cell (const octave_value_list& ovl);
 
   Cell (octave_idx_type n, octave_idx_type m,
-        const octave_value& val = resize_fill_value ())
+        const octave_value& val = Matrix ())
     : Array<octave_value> (dim_vector (n, m), val) { }
 
-  Cell (const dim_vector& dv, const octave_value& val = resize_fill_value ())
+  Cell (const dim_vector& dv, const octave_value& val = Matrix ())
     : Array<octave_value> (dv, val) { }
 
   Cell (const Array<octave_value>& c)
@@ -86,7 +86,7 @@
   using Array<octave_value>::assign;
 
   void assign (const octave_value_list& idx, const Cell& rhs,
-               const octave_value& fill_val = resize_fill_value ());
+               const octave_value& fill_val = Matrix ());
 
   Cell reshape (const dim_vector& new_dims) const
     { return Array<octave_value>::reshape (new_dims); }
@@ -110,10 +110,16 @@
   bool any_element_is_nan (void) const { return false; }
   bool is_true (void) const { return false; }
 
-  static octave_value resize_fill_value (void) { return Matrix (); }
+  octave_value resize_fill_value (void) const
+  {
+    static Matrix rfv;
+    return rfv;
+  }
 
   Cell diag (octave_idx_type k = 0) const;
 
+  Cell diag (octave_idx_type m, octave_idx_type n) const;
+
   Cell xisalnum (void) const { return map (&octave_value::xisalnum); }
   Cell xisalpha (void) const { return map (&octave_value::xisalpha); }
   Cell xisascii (void) const { return map (&octave_value::xisascii); }
new file mode 100644
--- /dev/null
+++ b/libinterp/interp-core/action-container.h
@@ -0,0 +1,341 @@
+/*
+
+Copyright (C) 1993-2012 John W. Eaton
+Copyright (C) 2009-2010 VZLU Prague
+
+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_action_container_h)
+#define octave_action_container_h 1
+
+// This class allows registering actions in a list for later
+// execution, either explicitly or when the container goes out of
+// scope.
+
+// FIXME -- is there a better name for this class?
+
+class
+action_container
+{
+public:
+
+  // A generic unwind_protect element. Knows how to run itself and
+  // discard itself.  Also, contains a pointer to the next element.
+  class elem
+  {
+  public:
+    elem (void) { }
+
+    virtual void run (void) { }
+
+    virtual ~elem (void) { }
+
+    friend class action_container;
+
+  private:
+
+    // No copying!
+
+    elem (const elem&);
+
+    elem& operator = (const elem&);
+  };
+
+  // An element that merely runs a void (*)(void) function.
+
+  class fcn_elem : public elem
+  {
+  public:
+    fcn_elem (void (*fptr) (void))
+      : e_fptr (fptr) { }
+
+    void run (void) { e_fptr (); }
+
+  private:
+    void (*e_fptr) (void);
+  };
+
+  // An element that stores a variable of type T along with a void (*) (T)
+  // function pointer, and calls the function with the parameter.
+
+  template <class T>
+  class fcn_arg_elem : public elem
+  {
+  public:
+    fcn_arg_elem (void (*fcn) (T), T arg)
+      : e_fcn (fcn), e_arg (arg) { }
+
+    void run (void) { e_fcn (e_arg); }
+
+  private:
+
+    // No copying!
+
+    fcn_arg_elem (const fcn_arg_elem&);
+
+    fcn_arg_elem& operator = (const fcn_arg_elem&);
+
+    void (*e_fcn) (T);
+    T e_arg;
+  };
+
+  // An element that stores a variable of type T along with a
+  // void (*) (const T&) function pointer, and calls the function with
+  // the parameter.
+
+  template <class T>
+  class fcn_crefarg_elem : public elem
+  {
+  public:
+    fcn_crefarg_elem (void (*fcn) (const T&), const T& arg)
+      : e_fcn (fcn), e_arg (arg) { }
+
+    void run (void) { e_fcn (e_arg); }
+
+  private:
+    void (*e_fcn) (const T&);
+    T e_arg;
+  };
+
+  // An element for calling a member function.
+
+  template <class T>
+  class method_elem : public elem
+  {
+  public:
+    method_elem (T *obj, void (T::*method) (void))
+      : e_obj (obj), e_method (method) { }
+
+    void run (void) { (e_obj->*e_method) (); }
+
+  private:
+
+    T *e_obj;
+    void (T::*e_method) (void);
+
+    // No copying!
+
+    method_elem (const method_elem&);
+
+    method_elem operator = (const method_elem&);
+  };
+
+  // An element for calling a member function with a single argument
+
+  template <class T, class A>
+  class method_arg_elem : public elem
+  {
+  public:
+    method_arg_elem (T *obj, void (T::*method) (A), A arg)
+      : e_obj (obj), e_method (method), e_arg (arg) { }
+
+    void run (void) { (e_obj->*e_method) (e_arg); }
+
+  private:
+
+    T *e_obj;
+    void (T::*e_method) (A);
+    A e_arg;
+
+    // No copying!
+
+    method_arg_elem (const method_arg_elem&);
+
+    method_arg_elem operator = (const method_arg_elem&);
+  };
+
+  // An element for calling a member function with a single argument
+
+  template <class T, class A>
+  class method_crefarg_elem : public elem
+  {
+  public:
+    method_crefarg_elem (T *obj, void (T::*method) (const A&), const A& arg)
+      : e_obj (obj), e_method (method), e_arg (arg) { }
+
+    void run (void) { (e_obj->*e_method) (e_arg); }
+
+  private:
+
+    T *e_obj;
+    void (T::*e_method) (const A&);
+    A e_arg;
+
+    // No copying!
+
+    method_crefarg_elem (const method_crefarg_elem&);
+
+    method_crefarg_elem operator = (const method_crefarg_elem&);
+  };
+
+  // An element that stores arbitrary variable, and restores it.
+
+  template <class T>
+  class restore_var_elem : public elem
+  {
+  public:
+    restore_var_elem (T& ref, const T& val)
+      : e_ptr (&ref), e_val (val) { }
+
+    void run (void) { *e_ptr = e_val; }
+
+  private:
+
+    // No copying!
+
+    restore_var_elem (const restore_var_elem&);
+
+    restore_var_elem& operator = (const restore_var_elem&);
+
+    T *e_ptr, e_val;
+  };
+
+  // Deletes a class allocated using new.
+
+  template <class T>
+  class delete_ptr_elem : public elem
+  {
+  public:
+    delete_ptr_elem (T *ptr)
+      : e_ptr (ptr) { }
+
+    void run (void) { delete e_ptr; }
+
+  private:
+
+    T *e_ptr;
+
+    // No copying!
+
+    delete_ptr_elem (const delete_ptr_elem&);
+
+    delete_ptr_elem operator = (const delete_ptr_elem&);
+  };
+
+  action_container (void) { }
+
+  virtual ~action_container (void) { }
+
+  virtual void add (elem *new_elem) = 0;
+
+  // Call to void func (void).
+  void add_fcn (void (*fcn) (void))
+  {
+    add (new fcn_elem (fcn));
+  }
+
+  // Call to void func (T).
+  template <class T>
+  void add_fcn (void (*action) (T), T val)
+  {
+    add (new fcn_arg_elem<T> (action, val));
+  }
+
+  // Call to void func (const T&).
+  template <class T>
+  void add_fcn (void (*action) (const T&), const T& val)
+  {
+    add (new fcn_crefarg_elem<T> (action, val));
+  }
+
+  // Call to T::method (void).
+  template <class T>
+  void add_method (T *obj, void (T::*method) (void))
+  {
+    add (new method_elem<T> (obj, method));
+  }
+
+  // Call to T::method (A).
+  template <class T, class A>
+  void add_method (T *obj, void (T::*method) (A), A arg)
+  {
+    add (new method_arg_elem<T, A> (obj, method, arg));
+  }
+
+  // Call to T::method (const A&).
+  template <class T, class A>
+  void add_method (T *obj, void (T::*method) (const A&), const A& arg)
+  {
+    add (new method_crefarg_elem<T, A> (obj, method, arg));
+  }
+
+  // Call to delete (T*).
+
+  template <class T>
+  void add_delete (T *obj)
+  {
+    add (new delete_ptr_elem<T> (obj));
+  }
+
+  // Protect any variable.
+  template <class T>
+  void protect_var (T& var)
+  {
+    add (new restore_var_elem<T> (var, var));
+  }
+
+  // Protect any variable, value given.
+  template <class T>
+  void protect_var (T& var, const T& val)
+  {
+    add (new restore_var_elem<T> (var, val));
+  }
+
+  operator bool (void) const { return ! empty (); }
+
+  virtual void run_first (void) = 0;
+
+  void run (size_t num)
+  {
+    if (num > size ())
+      num = size ();
+
+    for (size_t i = 0; i < num; i++)
+      run_first ();
+  }
+
+  void run (void) { run (size ()); }
+
+  virtual void discard_first (void) = 0;
+
+  void discard (size_t num)
+  {
+    if (num > size ())
+      num = size ();
+
+    for (size_t i = 0; i < num; i++)
+      discard_first ();
+  }
+
+  void discard (void) { discard (size ()); }
+
+  virtual size_t size (void) const = 0;
+
+  bool empty (void) const { return size () == 0; }
+
+private:
+
+  // No copying!
+
+  action_container (const action_container&);
+
+  action_container& operator = (const action_container&);
+};
+
+#endif
rename from src/c-file-ptr-stream.cc
rename to libinterp/interp-core/c-file-ptr-stream.cc
--- a/src/c-file-ptr-stream.cc
+++ b/libinterp/interp-core/c-file-ptr-stream.cc
@@ -193,15 +193,15 @@
 }
 
 int
-c_file_ptr_buf::seek (long offset, int origin)
+c_file_ptr_buf::seek (off_t offset, int origin)
 {
-  return f ? gnulib::fseek (f, offset, origin) : -1;
+  return f ? gnulib::fseeko (f, offset, origin) : -1;
 }
 
-long
+off_t
 c_file_ptr_buf::tell (void)
 {
-  return f ? gnulib::ftell (f) : -1;
+  return f ? gnulib::ftello (f) : -1;
 }
 
 int
rename from src/c-file-ptr-stream.h
rename to libinterp/interp-core/c-file-ptr-stream.h
--- a/src/c-file-ptr-stream.h
+++ b/libinterp/interp-core/c-file-ptr-stream.h
@@ -74,9 +74,9 @@
 
   int file_number () const { return f ? fileno (f) : -1; }
 
-  int seek (long offset, int origin);
+  int seek (off_t offset, int origin);
 
-  long tell (void);
+  off_t tell (void);
 
   void clear (void) { if (f) clearerr (f); }
 
@@ -117,10 +117,10 @@
 
   void stream_close (void) { if (buf) buf->buf_close (); }
 
-  int seek (long offset, int origin)
+  int seek (off_t offset, int origin)
     { return buf ? buf->seek (offset, origin) : -1; }
 
-  long tell (void) { return buf ? buf->tell () : -1; }
+  off_t tell (void) { return buf ? buf->tell () : -1; }
 
   void clear (void) { if (buf) buf->clear (); STREAM_T::clear (); }
 
@@ -192,10 +192,10 @@
 
   int file_number () const { return -1; }
 
-  int seek (long offset, int origin)
-    { return f ? gzseek (f, offset, origin) : -1; }
+  int seek (off_t offset, int origin)
+    { return f ? gzseek (f, offset, origin) >= 0 : -1; }
 
-  long tell (void) { return f ? gztell (f) : -1; }
+  off_t tell (void) { return f ? gztell (f) : -1; }
 
   void clear (void) { if (f) gzclearerr (f); }
 
rename from src/comment-list.cc
rename to libinterp/interp-core/comment-list.cc
--- a/src/comment-list.cc
+++ b/libinterp/interp-core/comment-list.cc
@@ -88,7 +88,7 @@
 octave_comment_buffer::do_append (const std::string& s,
                                   octave_comment_elt::comment_type t)
 {
-  comment_list->append(s, t);
+  comment_list->append (s, t);
 }
 
 octave_comment_list *
rename from src/comment-list.h
rename to libinterp/interp-core/comment-list.h
--- a/src/comment-list.h
+++ b/libinterp/interp-core/comment-list.h
@@ -42,6 +42,7 @@
   {
     unknown,
     block,
+    full_line,
     end_of_line,
     doc_string,
     copyright
rename from src/cutils.c
rename to libinterp/interp-core/cutils.c
rename from src/cutils.h
rename to libinterp/interp-core/cutils.h
rename from src/defun-dld.h
rename to libinterp/interp-core/defun-dld.h
rename from src/defun-int.h
rename to libinterp/interp-core/defun-int.h
--- a/src/defun-int.h
+++ b/libinterp/interp-core/defun-int.h
@@ -39,7 +39,7 @@
 
 extern OCTINTERP_API void
 install_builtin_function (octave_builtin::fcn f, const std::string& name,
-                          const std::string& doc,
+                          const std::string& file, const std::string& doc,
                           bool can_hide_function = true);
 
 extern OCTINTERP_API void
rename from src/display.cc
rename to libinterp/interp-core/display.cc
--- a/src/display.cc
+++ b/libinterp/interp-core/display.cc
@@ -41,6 +41,23 @@
 
 display_info *display_info::instance = 0;
 
+#if defined (HAVE_FRAMEWORK_CARBON) && ! defined (HAVE_CARBON_CGDISPLAYBITSPERPIXEL)
+// FIXME - This will only work for MacOS > 10.5. For earlier versions
+// this code is not needed (use CGDisplayBitsPerPixel instead).
+size_t DisplayBitsPerPixel (CGDirectDisplayID display)
+{
+  CGDisplayModeRef mode = CGDisplayCopyDisplayMode (display);
+  CFStringRef pixelEncoding = CGDisplayModeCopyPixelEncoding (mode);
+
+  if (CFStringCompare (pixelEncoding, CFSTR (IO32BitDirectPixels), 0) == 0)
+    return 32;
+  else if (CFStringCompare (pixelEncoding, CFSTR (IO16BitDirectPixels), 0) == 0)
+    return 16;
+  else 
+    return 8;
+}
+#endif
+
 void
 display_info::init (bool query)
 {
@@ -62,6 +79,8 @@
 
           rx = wd * 25.4 / wd_mm;
           ry = ht * 25.4 / ht_mm;
+
+          dpy_avail = true;
         }
       else
         warning ("no graphical display found");
@@ -72,21 +91,28 @@
 
       if (display)
         {
+#  if defined (HAVE_CARBON_CGDISPLAYBITSPERPIXEL)
+          // For MacOS < 10.7 use the line below
           dp = CGDisplayBitsPerPixel (display);
+#  else
+          // For MacOS > 10.5 use the line below
+          dp = DisplayBitsPerPixel (display);
+#  endif
 
           ht = CGDisplayPixelsHigh (display);
           wd = CGDisplayPixelsWide (display);
 
           CGSize sz_mm = CGDisplayScreenSize (display);
-
-          // On modern Mac systems (>= 10.5) CGSize is a struct keeping 2
-          // CGFloat values, but the CGFloat typedef is not present on
-          // older systems, so use double instead.
+          // For MacOS >= 10.6, CGSize is a struct keeping 2 CGFloat values,
+          // but the CGFloat typedef is not present on older systems,
+          // so use double instead.
           double ht_mm = sz_mm.height;
           double wd_mm = sz_mm.width;
 
           rx = wd * 25.4 / wd_mm;
           ry = ht * 25.4 / ht_mm;
+
+          dpy_avail = true;
         }
       else
         warning ("no graphical display found");
@@ -122,6 +148,8 @@
                 warning ("X11 display has no default screen");
 
               XCloseDisplay (display);
+
+              dpy_avail = true;
             }
           else
             warning ("unable to open X11 DISPLAY");
rename from src/display.h
rename to libinterp/interp-core/display.h
--- a/src/display.h
+++ b/libinterp/interp-core/display.h
@@ -30,7 +30,7 @@
 protected:
 
   display_info (bool query = true)
-    : ht (1), wd (1), dp (0), rx (72), ry (72)
+    : ht (1), wd (1), dp (0), rx (72), ry (72), dpy_avail (false)
   {
     init (query);
   }
@@ -62,6 +62,11 @@
     return instance_ok () ? instance->do_y_dpi () : 0;
   }
 
+  static bool display_available (void)
+  {
+    return instance_ok () ? instance->do_display_available () : false;
+  }
+
   // To disable querying the window system for defaults, this function
   // must be called before any other display_info function.
   static void no_window_system (void)
@@ -84,6 +89,8 @@
   double rx;
   double ry;
 
+  bool dpy_avail;
+
   int do_height (void) const { return ht; }
   int do_width (void) const { return wd; }
   int do_depth (void) const { return dp; }
@@ -91,6 +98,8 @@
   double do_x_dpi (void) const { return rx; }
   double do_y_dpi (void) const { return ry; }
 
+  bool do_display_available (void) const { return dpy_avail; }
+
   void init (bool query = true);
 
   static bool instance_ok (bool query = true);
rename from src/dynamic-ld.cc
rename to libinterp/interp-core/dynamic-ld.cc
--- a/src/dynamic-ld.cc
+++ b/libinterp/interp-core/dynamic-ld.cc
@@ -197,109 +197,6 @@
     instance->do_display ();
 }
 
-class
-octave_mex_file_list
-{
-public:
-
-  typedef std::list<octave_shlib>::iterator iterator;
-  typedef std::list<octave_shlib>::const_iterator const_iterator;
-
-  static void append (const octave_shlib& shl);
-
-  static void remove (octave_shlib& shl, octave_shlib::close_hook cl_hook = 0);
-
-private:
-
-  octave_mex_file_list (void) : file_list () { }
-
-  ~octave_mex_file_list (void) { }
-
-  void do_append (const octave_shlib& shl);
-
-  void do_remove (octave_shlib& shl, octave_shlib::close_hook cl_hook = 0);
-
-  static octave_mex_file_list *instance;
-
-  static void cleanup_instance (void) { delete instance; instance = 0; }
-
-  static bool instance_ok (void);
-
-  // List of libraries we have loaded.
-  std::list<octave_shlib> file_list;
-
-  // No copying!
-
-  octave_mex_file_list (const octave_mex_file_list&);
-
-  octave_mex_file_list& operator = (const octave_mex_file_list&);
-};
-
-octave_mex_file_list *octave_mex_file_list::instance = 0;
-
-void
-octave_mex_file_list::do_append (const octave_shlib& shl)
-{
-  file_list.push_back (shl);
-}
-
-void
-octave_mex_file_list::do_remove (octave_shlib& shl,
-                                 octave_shlib::close_hook cl_hook)
-{
-  for (iterator p = file_list.begin (); p != file_list.end (); p++)
-    {
-      if (*p == shl)
-        {
-          // Erase first to avoid potentially invalidating the pointer by the
-          // following hooks.
-          file_list.erase (p);
-
-          shl.close (cl_hook);
-
-          break;
-        }
-    }
-}
-
-bool
-octave_mex_file_list::instance_ok (void)
-{
-  bool retval = true;
-
-  if (! instance)
-    {
-      instance = new octave_mex_file_list ();
-
-      if (instance)
-        singleton_cleanup_list::add (cleanup_instance);
-    }
-
-  if (! instance)
-    {
-      ::error ("unable to create shared library list object!");
-
-      retval = false;
-    }
-
-  return retval;
-}
-
-void
-octave_mex_file_list::append (const octave_shlib& shl)
-{
-  if (instance_ok ())
-    instance->do_append (shl);
-}
-
-void
-octave_mex_file_list::remove (octave_shlib& shl,
-                              octave_shlib::close_hook cl_hook)
-{
-  if (instance_ok ())
-    instance->do_remove (shl, cl_hook);
-}
-
 octave_dynamic_loader *octave_dynamic_loader::instance = 0;
 
 bool octave_dynamic_loader::doing_load = false;
@@ -342,7 +239,7 @@
     {
       warning_with_id ("Octave:reload-forces-clear",
                        "reloading %s clears the following functions:",
-                       oct_file.file_name().c_str ());
+                       oct_file.file_name ().c_str ());
 
       octave_shlib_list::remove (oct_file, do_clear_function);
     }
@@ -444,8 +341,6 @@
 
           bool have_fmex = false;
 
-          octave_mex_file_list::append (mex_file);
-
           function = mex_file.search (fcn_name, mex_mangler);
 
           if (! function)
@@ -513,7 +408,7 @@
       retval = shl.remove (fcn_name);
 
       if (shl.number_of_functions_loaded () == 0)
-        octave_mex_file_list::remove (shl);
+        octave_shlib_list::remove (shl);
     }
 
   return retval;
rename from src/dynamic-ld.h
rename to libinterp/interp-core/dynamic-ld.h
new file mode 100644
--- /dev/null
+++ b/libinterp/interp-core/event-queue.h
@@ -0,0 +1,125 @@
+/*
+
+Copyright (C) 2012 John W. Eaton
+
+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_event_queue_h)
+#define octave_event_queue_h 1
+
+#include <queue>
+#include <memory>
+
+#include "action-container.h"
+
+class
+event_queue : public action_container
+{
+public:
+
+  event_queue (void) : fifo () { }
+
+  // Destructor should not raise an exception, so all actions
+  // registered should be exception-safe (but setting error_state is
+  // allowed). If you're not sure, see event_queue_safe.
+
+  ~event_queue (void) { run (); }
+
+  void add (elem *new_elem)
+  {
+    fifo.push (new_elem);
+  }
+
+  void run_first (void)
+  {
+    if (! empty ())
+      {
+        // No leak on exception!
+        std::auto_ptr<elem> ptr (fifo.front ());
+        fifo.pop ();
+        ptr->run ();
+      }
+  }
+
+  void discard_first (void)
+  {
+    if (! empty ())
+      {
+        elem *ptr = fifo.front ();
+        fifo.pop ();
+        delete ptr;
+      }
+  }
+
+  size_t size (void) const { return fifo.size (); }
+
+protected:
+
+  std::queue<elem *> fifo;
+
+private:
+
+  // No copying!
+
+  event_queue (const event_queue&);
+
+  event_queue& operator = (const event_queue&);
+};
+
+// Like event_queue, but this one will guard against the
+// possibility of seeing an exception (or interrupt) in the cleanup
+// actions. Not that we can do much about it, but at least we won't
+// crash.
+
+class
+event_queue_safe : public event_queue
+{
+private:
+
+  static void gripe_exception (void);
+
+public:
+
+  event_queue_safe (void) : event_queue () { }
+
+  ~event_queue_safe (void)
+    {
+      while (! empty ())
+        {
+          try
+            {
+              run_first ();
+            }
+          catch (...) // Yes, the black hole. Remember we're in a dtor.
+            {
+              gripe_exception ();
+            }
+        }
+    }
+
+private:
+
+  // No copying!
+
+  event_queue_safe (const event_queue_safe&);
+
+  event_queue_safe& operator = (const event_queue_safe&);
+};
+
+#endif
rename from src/gl-render.cc
rename to libinterp/interp-core/gl-render.cc
--- a/src/gl-render.cc
+++ b/libinterp/interp-core/gl-render.cc
@@ -135,7 +135,7 @@
 {
   int m = 1;
 
-  while (m < n && m < INT_MAX)
+  while (m < n && m < std::numeric_limits<int>::max ())
     m <<= 1;
 
   return m;
@@ -236,7 +236,7 @@
 
 public:
 
-  opengl_tesselator (void) : glu_tess (0), fill() { init (); }
+  opengl_tesselator (void) : glu_tess (0), fill () { init (); }
 
   virtual ~opengl_tesselator (void)
     { if (glu_tess) gluDeleteTess (glu_tess); }
@@ -416,7 +416,7 @@
 protected:
   void begin (GLenum type)
     {
-      //printf("patch_tesselator::begin (%d)\n", type);
+      //printf ("patch_tesselator::begin (%d)\n", type);
       first = true;
 
       if (color_mode == 2 || light_mode == 2)
@@ -432,7 +432,7 @@
 
   void end (void)
     {
-      //printf("patch_tesselator::end\n");
+      //printf ("patch_tesselator::end\n");
       glEnd ();
       renderer->set_polygon_offset (false);
     }
@@ -441,7 +441,7 @@
     {
       vertex_data::vertex_data_rep *v
           = reinterpret_cast<vertex_data::vertex_data_rep *> (data);
-      //printf("patch_tesselator::vertex (%g, %g, %g)\n", v->coords(0), v->coords(1), v->coords(2));
+      //printf ("patch_tesselator::vertex (%g, %g, %g)\n", v->coords(0), v->coords(1), v->coords(2));
 
       // FIXME: why did I need to keep the first vertex of the face
       // in JHandles? I think it's related to the fact that the
@@ -481,7 +481,7 @@
   void combine (GLdouble xyz[3], void *data[4], GLfloat w[4],
                 void **out_data)
     {
-      //printf("patch_tesselator::combine\n");
+      //printf ("patch_tesselator::combine\n");
 
       vertex_data::vertex_data_rep *v[4];
       int vmax = 4;
@@ -508,14 +508,14 @@
           cc.resize (1, 3, 0.0);
           for (int ic = 0; ic < 3; ic++)
             for (int iv = 0; iv < vmax; iv++)
-              cc(ic) += (w[iv] * v[iv]->color(ic));
+              cc(ic) += (w[iv] * v[iv]->color (ic));
         }
 
       if (v[0]->normal.numel () > 0)
         {
           for (int in = 0; in < 3; in++)
             for (int iv = 0; iv < vmax; iv++)
-              nn(in) += (w[iv] * v[iv]->normal(in));
+              nn(in) += (w[iv] * v[iv]->normal (in));
         }
 
       for (int iv = 0; iv < vmax; iv++)
@@ -552,6 +552,9 @@
 
   const base_properties& props = go.get_properties ();
 
+  if (! toolkit)
+    toolkit = props.get_toolkit ();
+
   if (go.isa ("figure"))
     draw_figure (dynamic_cast<const figure::properties&> (props));
   else if (go.isa ("axes"))
@@ -587,8 +590,6 @@
 void
 opengl_renderer::draw_figure (const figure::properties& props)
 {
-  toolkit = props.get_toolkit ();
-
   // Initialize OpenGL context
 
   init_gl_context (props.is___enhanced__ (), props.get_color_rgb ());
@@ -606,8 +607,6 @@
   const figure::properties& figProps =
     dynamic_cast<const figure::properties&> (fig.get_properties ());
 
-  toolkit = figProps.get_toolkit ();
-
   // Initialize OpenGL context 
 
   init_gl_context (figProps.is___enhanced__ (),
@@ -642,7 +641,7 @@
 
   // Clear background
 
-  if (c.length() >= 3)
+  if (c.length () >= 3)
     {
       glClearColor (c(0), c(1), c(2), 1);
       glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
@@ -808,7 +807,7 @@
 
   glMatrixMode (GL_MODELVIEW);
   glLoadIdentity ();
-  glScaled(1, 1, -1);
+  glScaled (1, 1, -1);
   glMultMatrixd (x_mat1.data ());
   glMatrixMode (GL_PROJECTION);
   glLoadIdentity ();
@@ -1017,14 +1016,14 @@
         {
           render_tickmarks (xticks, x_min, x_max, ypTick, ypTick,
                             zpTick, zpTickN, 0., 0.,
-                            signum(zpTick-zpTickN)*fz*xticklen,
+                            signum (zpTick-zpTickN)*fz*xticklen,
                             0, mirror);
         }
       else
         {
           render_tickmarks (xticks, x_min, x_max, ypTick, ypTickN,
                             zpTick, zpTick, 0.,
-                            signum(ypTick-ypTickN)*fy*xticklen,
+                            signum (ypTick-ypTickN)*fy*xticklen,
                             0., 0, mirror);
         }
 
@@ -1036,11 +1035,11 @@
 
           if (tick_along_z)
             render_ticktexts (xticks, xticklabels, x_min, x_max, ypTick,
-                              zpTick+signum(zpTick-zpTickN)*fz*xtickoffset,
+                              zpTick+signum (zpTick-zpTickN)*fz*xtickoffset,
                               0, halign, valign, wmax, hmax);
           else
             render_ticktexts (xticks, xticklabels, x_min, x_max,
-                              ypTick+signum(ypTick-ypTickN)*fy*xtickoffset,
+                              ypTick+signum (ypTick-ypTickN)*fy*xtickoffset,
                               zpTick, 0, halign, valign, wmax, hmax);
         }
 
@@ -1056,12 +1055,12 @@
           if (tick_along_z)
             render_tickmarks (xmticks, x_min, x_max, ypTick, ypTick,
                               zpTick, zpTickN, 0., 0.,
-                              signum(zpTick-zpTickN)*fz*xticklen/2,
+                              signum (zpTick-zpTickN)*fz*xticklen/2,
                               0, mirror);
           else
             render_tickmarks (xmticks, x_min, x_max, ypTick, ypTickN,
                               zpTick, zpTick, 0.,
-                              signum(ypTick-ypTickN)*fy*xticklen/2,
+                              signum (ypTick-ypTickN)*fy*xticklen/2,
                               0., 0, mirror);
         }
 
@@ -1124,12 +1123,12 @@
       if (tick_along_z)
         render_tickmarks (yticks, y_min, y_max, xpTick, xpTick,
                           zpTick, zpTickN, 0., 0.,
-                          signum(zpTick-zpTickN)*fz*yticklen,
+                          signum (zpTick-zpTickN)*fz*yticklen,
                           1, mirror);
       else
         render_tickmarks (yticks, y_min, y_max, xpTick, xpTickN,
                           zpTick, zpTick,
-                          signum(xPlaneN-xPlane)*fx*yticklen,
+                          signum (xPlaneN-xPlane)*fx*yticklen,
                           0., 0., 1, mirror);
 
       // tick texts
@@ -1141,11 +1140,11 @@
 
           if (tick_along_z)
             render_ticktexts (yticks, yticklabels, y_min, y_max, xpTick,
-                              zpTick+signum(zpTick-zpTickN)*fz*ytickoffset,
+                              zpTick+signum (zpTick-zpTickN)*fz*ytickoffset,
                               1, halign, valign, wmax, hmax);
           else
             render_ticktexts (yticks, yticklabels, y_min, y_max,
-                              xpTick+signum(xpTick-xpTickN)*fx*ytickoffset,
+                              xpTick+signum (xpTick-xpTickN)*fx*ytickoffset,
                               zpTick, 1, halign, valign, wmax, hmax);
         }
 
@@ -1161,12 +1160,12 @@
           if (tick_along_z)
             render_tickmarks (ymticks, y_min, y_max, xpTick, xpTick,
                               zpTick, zpTickN, 0., 0.,
-                              signum(zpTick-zpTickN)*fz*yticklen/2,
+                              signum (zpTick-zpTickN)*fz*yticklen/2,
                               1, mirror);
           else
             render_tickmarks (ymticks, y_min, y_max, xpTick, xpTickN,
                               zpTick, zpTick,
-                              signum(xpTick-xpTickN)*fx*yticklen/2,
+                              signum (xpTick-xpTickN)*fx*yticklen/2,
                               0., 0., 1, mirror);
         }
 
@@ -1221,12 +1220,12 @@
           if (xisinf (fy))
             render_tickmarks (zticks, z_min, z_max, xPlaneN, xPlane,
                               yPlane, yPlane,
-                              signum(xPlaneN-xPlane)*fx*zticklen,
+                              signum (xPlaneN-xPlane)*fx*zticklen,
                               0., 0., 2, mirror);
           else
             render_tickmarks (zticks, z_min, z_max, xPlaneN, xPlaneN,
                               yPlane, yPlane, 0.,
-                              signum(yPlane-yPlaneN)*fy*zticklen,
+                              signum (yPlane-yPlaneN)*fy*zticklen,
                               0., 2, false);
         }
       else
@@ -1234,12 +1233,12 @@
           if (xisinf (fx))
             render_tickmarks (zticks, z_min, z_max, xPlaneN, xPlane,
                               yPlaneN, yPlane, 0.,
-                              signum(yPlaneN-yPlane)*fy*zticklen,
+                              signum (yPlaneN-yPlane)*fy*zticklen,
                               0., 2, mirror);
           else
             render_tickmarks (zticks, z_min, z_max, xPlane, xPlane,
                               yPlaneN, yPlane,
-                              signum(xPlane-xPlaneN)*fx*zticklen,
+                              signum (xPlane-xPlaneN)*fx*zticklen,
                               0., 0., 2, false);
         }
 
@@ -1253,22 +1252,22 @@
             {
               if (xisinf (fy))
                 render_ticktexts (zticks, zticklabels, z_min, z_max,
-                                  xPlaneN+signum(xPlaneN-xPlane)*fx*ztickoffset,
+                                  xPlaneN+signum (xPlaneN-xPlane)*fx*ztickoffset,
                                   yPlane, 2, halign, valign, wmax, hmax);
               else
                 render_ticktexts (zticks, zticklabels, z_min, z_max, xPlaneN,
-                                  yPlane+signum(yPlane-yPlaneN)*fy*ztickoffset,
+                                  yPlane+signum (yPlane-yPlaneN)*fy*ztickoffset,
                                   2, halign, valign, wmax, hmax);
             }
           else
             {
               if (xisinf (fx))
                 render_ticktexts (zticks, zticklabels, z_min, z_max, xPlane,
-                                  yPlaneN+signum(yPlaneN-yPlane)*fy*ztickoffset,
+                                  yPlaneN+signum (yPlaneN-yPlane)*fy*ztickoffset,
                                   2, halign, valign, wmax, hmax);
               else
                 render_ticktexts (zticks, zticklabels, z_min, z_max,
-                                  xPlane+signum(xPlane-xPlaneN)*fx*ztickoffset,
+                                  xPlane+signum (xPlane-xPlaneN)*fx*ztickoffset,
                                   yPlaneN, 2, halign, valign, wmax, hmax);
             }
         }
@@ -1286,12 +1285,12 @@
               if (xisinf (fy))
                 render_tickmarks (zmticks, z_min, z_max, xPlaneN, xPlane,
                                   yPlane, yPlane,
-                                  signum(xPlaneN-xPlane)*fx*zticklen/2,
+                                  signum (xPlaneN-xPlane)*fx*zticklen/2,
                                   0., 0., 2, mirror);
               else
                 render_tickmarks (zmticks, z_min, z_max, xPlaneN, xPlaneN,
                                   yPlane, yPlane, 0.,
-                                  signum(yPlane-yPlaneN)*fy*zticklen/2,
+                                  signum (yPlane-yPlaneN)*fy*zticklen/2,
                                   0., 2, false);
             }
           else
@@ -1299,12 +1298,12 @@
               if (xisinf (fx))
                 render_tickmarks (zmticks, z_min, z_max, xPlane, xPlane,
                                   yPlaneN, yPlane, 0.,
-                                  signum(yPlaneN-yPlane)*fy*zticklen/2,
+                                  signum (yPlaneN-yPlane)*fy*zticklen/2,
                                   0., 2, mirror);
               else
                 render_tickmarks (zmticks, z_min, z_max, xPlane, xPlane,
                                   yPlaneN, yPlaneN,
-                                  signum(xPlane-xPlaneN)*fx*zticklen/2,
+                                  signum (xPlane-xPlaneN)*fx*zticklen/2,
                                   0., 0., 2, false);
             }
         }
@@ -1426,7 +1425,7 @@
   Matrix z = xform.zscale (props.get_zdata ().matrix_value ());
 
   bool has_z = (z.numel () > 0);
-  int n = static_cast<int> (::xmin (::xmin (x.numel (), y.numel ()), (has_z ? z.numel () : INT_MAX)));
+  int n = static_cast<int> (::xmin (::xmin (x.numel (), y.numel ()), (has_z ? z.numel () : std::numeric_limits<int>::max ())));
   octave_uint8 clip_mask = (props.is_clipping () ? 0x7F : 0x40), clip_ok (0x40);
 
   std::vector<octave_uint8> clip (n);
@@ -2105,16 +2104,16 @@
   bool has_facecolor = false;
   bool has_facealpha = false;
 
-  int fc_mode = ((props.facecolor_is("none")
+  int fc_mode = ((props.facecolor_is ("none")
                   || props.facecolor_is_rgb ()) ? 0 :
-                 (props.facecolor_is("flat") ? 1 : 2));
+                 (props.facecolor_is ("flat") ? 1 : 2));
   int fl_mode = (props.facelighting_is ("none") ? 0 :
                  (props.facelighting_is ("flat") ? 1 : 2));
   int fa_mode = (props.facealpha_is_double () ? 0 :
                  (props.facealpha_is ("flat") ? 1 : 2));
-  int ec_mode = ((props.edgecolor_is("none")
+  int ec_mode = ((props.edgecolor_is ("none")
                   || props.edgecolor_is_rgb ()) ? 0 :
-                 (props.edgecolor_is("flat") ? 1 : 2));
+                 (props.edgecolor_is ("flat") ? 1 : 2));
   int el_mode = (props.edgelighting_is ("none") ? 0 :
                  (props.edgelighting_is ("flat") ? 1 : 2));
   int ea_mode = (props.edgealpha_is_double () ? 0 :
@@ -2470,7 +2469,7 @@
   glEnable (GL_BLEND);
   glEnable (GL_ALPHA_TEST);
   glRasterPos3d (pos(0), pos(1), pos.numel () > 2 ? pos(2) : 0.0);
-  glBitmap(0, 0, 0, 0, bbox(0), bbox(1), 0);
+  glBitmap (0, 0, 0, 0, bbox(0), bbox(1), 0);
   glDrawPixels (bbox(2), bbox(3),
                 GL_RGBA, GL_UNSIGNED_BYTE, props.get_pixels ().data ());
   glDisable (GL_ALPHA_TEST);
@@ -2489,6 +2488,10 @@
   Matrix x = props.get_xdata ().matrix_value ();
   Matrix y = props.get_ydata ().matrix_value ();
 
+  // Someone wants us to draw an empty image? No way.
+  if (x.is_empty () || y.is_empty ())
+    return;
+
   if (w > 1 && x(1) == x(0))
     x(1) = x(1) + (w-1);
 
@@ -2554,7 +2557,7 @@
   else // clip to viewport
     {
       GLfloat vp[4];
-      glGetFloatv(GL_VIEWPORT, vp);
+      glGetFloatv (GL_VIEWPORT, vp);
       // FIXME -- actually add the code to do it!
 
     }
@@ -2863,7 +2866,7 @@
       glEnd ();
       break;
     case 'x':
-      glBegin(GL_LINES);
+      glBegin (GL_LINES);
       glVertex2f (-sz/2, -sz/2);
       glVertex2f (sz/2, sz/2);
       glVertex2f (-sz/2, sz/2);
@@ -2888,7 +2891,7 @@
 
         glBegin (GL_POLYGON);
         for (double ang = 0; ang < (2*M_PI); ang += ang_step)
-          glVertex2d (sz*cos(ang)/3, sz*sin(ang)/3);
+          glVertex2d (sz*cos (ang)/3, sz*sin (ang)/3);
         glEnd ();
       }
       break;
@@ -2898,7 +2901,7 @@
       glVertex2d (-sz/2, sz/2);
       glVertex2d (sz/2, sz/2);
       glVertex2d (sz/2, -sz/2);
-      glEnd();
+      glEnd ();
       break;
     case 'o':
       {
@@ -2906,7 +2909,7 @@
 
         glBegin ((filled ? GL_POLYGON : GL_LINE_LOOP));
         for (double ang = 0; ang < (2*M_PI); ang += ang_step)
-          glVertex2d (sz*cos(ang)/2, sz*sin(ang)/2);
+          glVertex2d (sz*cos (ang)/2, sz*sin (ang)/2);
         glEnd ();
       }
       break;
@@ -2916,7 +2919,7 @@
       glVertex2d (sz/2, 0);
       glVertex2d (0, sz/2);
       glVertex2d (-sz/2, 0);
-      glEnd();
+      glEnd ();
       break;
     case 'v':
       glBegin ((filled ? GL_POLYGON : GL_LINE_LOOP));
@@ -2950,14 +2953,14 @@
       {
         double ang;
         double r;
-        double dr = 1.0 - sin(M_PI/10)/sin(3*M_PI/10)*1.02;
+        double dr = 1.0 - sin (M_PI/10)/sin (3*M_PI/10)*1.02;
 
         glBegin ((filled ? GL_POLYGON : GL_LINE_LOOP));
         for (int i = 0; i < 2*5; i++)
           {
             ang = (-0.5 + double(i+1)/5) * M_PI;
-            r = 1.0 - (dr * fmod(double(i+1), 2.0));
-            glVertex2d (sz*r*cos(ang)/2, sz*r*sin(ang)/2);
+            r = 1.0 - (dr * fmod (double(i+1), 2.0));
+            glVertex2d (sz*r*cos (ang)/2, sz*r*sin (ang)/2);
           }
         glEnd ();
       }
@@ -2966,14 +2969,14 @@
       {
         double ang;
         double r;
-        double dr = 1.0 - 0.5/sin(M_PI/3)*1.02;
+        double dr = 1.0 - 0.5/sin (M_PI/3)*1.02;
 
         glBegin ((filled ? GL_POLYGON : GL_LINE_LOOP));
         for (int i = 0; i < 2*6; i++)
           {
             ang = (0.5 + double(i+1)/6.0) * M_PI;
-            r = 1.0 - (dr * fmod(double(i+1), 2.0));
-            glVertex2d (sz*r*cos(ang)/2, sz*r*sin(ang)/2);
+            r = 1.0 - (dr * fmod (double(i+1), 2.0));
+            glVertex2d (sz*r*cos (ang)/2, sz*r*sin (ang)/2);
           }
         glEnd ();
       }
rename from src/gl-render.h
rename to libinterp/interp-core/gl-render.h
--- a/src/gl-render.h
+++ b/libinterp/interp-core/gl-render.h
@@ -90,6 +90,7 @@
                              const graphics_object& go);
 
   virtual void init_gl_context (bool enhanced, const Matrix& backgroundColor);
+  virtual void setup_opengl_transformation (const axes::properties& props);
 
   virtual void set_color (const Matrix& c);
   virtual void set_polygon_offset (bool on, double offset = 0.0);
@@ -168,8 +169,6 @@
   unsigned int make_marker_list (const std::string& m, double size,
                                  bool filled) const;
 
-  void setup_opengl_transformation (const axes::properties& props);
-
   void draw_axes_planes (const axes::properties& props);
   void draw_axes_boxes (const axes::properties& props);
 
rename from src/gl2ps-renderer.cc
rename to libinterp/interp-core/gl2ps-renderer.cc
--- a/src/gl2ps-renderer.cc
+++ b/libinterp/interp-core/gl2ps-renderer.cc
@@ -43,14 +43,6 @@
     {
       in_draw = true;
 
-      FILE *fp = fdopen (fid, "wb");
-
-      if (! fp)
-        {
-          error ("gl2ps-renderer: fdopen failed");
-          return;
-        }
-
       GLint buffsize = 0, state = GL2PS_OVERFLOW;
       GLint viewport[4];
 
@@ -72,11 +64,15 @@
       GLint gl2ps_text = 0;
       if (term.find ("notxt") != std::string::npos) gl2ps_text = GL2PS_NO_TEXT;
 
+      // Default sort order optimizes for 3D plots
+      GLint gl2ps_sort = GL2PS_BSP_SORT;
+      if (term.find ("is2D") != std::string::npos) gl2ps_sort = GL2PS_NO_SORT;
+
       while (state == GL2PS_OVERFLOW)
         {
           buffsize += 1024*1024;
           gl2psBeginPage ("glps_renderer figure", "Octave", viewport,
-                          gl2ps_term, GL2PS_BSP_SORT,
+                          gl2ps_term, gl2ps_sort,
                           (GL2PS_SILENT | GL2PS_SIMPLE_LINE_OFFSET
                            | GL2PS_NO_BLENDING | GL2PS_OCCLUSION_CULL
                            | GL2PS_BEST_ROOT | gl2ps_text
@@ -88,8 +84,6 @@
           state = gl2psEndPage ();
         }
 
-      gnulib::fclose (fp);
-
       in_draw = 0;
     }
   else
@@ -223,7 +217,7 @@
 
   // FIXME: handle margin and surrounding box
 
-  glRasterPos3d (pos(0), pos(1), pos(2));
+  glRasterPos3d (pos(0), pos(1), pos.numel () > 2 ? pos(2) : 0.0);
 
   octave_value string_prop = props.get_string ();
 
rename from src/gl2ps-renderer.h
rename to libinterp/interp-core/gl2ps-renderer.h
--- a/src/gl2ps-renderer.h
+++ b/libinterp/interp-core/gl2ps-renderer.h
@@ -31,8 +31,8 @@
 glps_renderer : public opengl_renderer
 {
 public:
-  glps_renderer (const int _fid, const std::string& _term)
-    : opengl_renderer () , fid (_fid), term (_term),
+  glps_renderer (FILE *_fp, const std::string& _term)
+    : opengl_renderer () , fp (_fp), term (_term),
     fontsize (), fontname () { }
 
   ~glps_renderer (void) { }
@@ -52,13 +52,14 @@
   void draw_pixels (GLsizei w, GLsizei h, GLenum format,
                     GLenum type, const GLvoid *data);
 
-  void set_linestyle (const std::string& s, bool use_stipple)
+  void set_linestyle (const std::string& s, bool use_stipple = false)
   {
     opengl_renderer::set_linestyle (s, use_stipple);
-    if (use_stipple)
+
+    if (s == "-" && ! use_stipple)
+      gl2psDisable (GL2PS_LINE_STIPPLE);
+    else
       gl2psEnable (GL2PS_LINE_STIPPLE);
-    else
-      gl2psDisable (GL2PS_LINE_STIPPLE);
   }
 
   void set_polygon_offset (bool on, double offset = 0.0)
@@ -77,7 +78,7 @@
 
 private:
   int alignment_to_mode (int ha, int va) const;
-  int fid;
+  FILE *fp;
   caseless_str term;
   double fontsize;
   std::string fontname;
rename from src/gl2ps.c
rename to libinterp/interp-core/gl2ps.c
rename from src/gl2ps.h
rename to libinterp/interp-core/gl2ps.h
rename from src/gripes.cc
rename to libinterp/interp-core/gripes.cc
rename from src/gripes.h
rename to libinterp/interp-core/gripes.h
new file mode 100644
--- /dev/null
+++ b/libinterp/interp-core/jit-ir.cc
@@ -0,0 +1,838 @@
+/*
+
+Copyright (C) 2012 Max Brister <max@2bass.com>
+
+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/>.
+
+*/
+
+// defines required by llvm
+#define __STDC_LIMIT_MACROS
+#define __STDC_CONSTANT_MACROS
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#ifdef HAVE_LLVM
+
+#include "jit-ir.h"
+
+#include <llvm/BasicBlock.h>
+#include <llvm/Instructions.h>
+
+#include "error.h"
+
+// -------------------- jit_factory --------------------
+jit_factory::~jit_factory (void)
+{
+  for (value_list::iterator iter = all_values.begin ();
+       iter != all_values.end (); ++iter)
+    delete *iter;
+}
+
+void
+jit_factory::track_value (jit_value *value)
+{
+  if (value->type ())
+    mconstants.push_back (value);
+  all_values.push_back (value);
+}
+
+// -------------------- jit_block_list --------------------
+void
+jit_block_list::insert_after (iterator iter, jit_block *ablock)
+{
+  ++iter;
+  insert_before (iter, ablock);
+}
+
+void
+jit_block_list::insert_after (jit_block *loc, jit_block *ablock)
+{
+  insert_after (loc->location (), ablock);
+}
+
+void
+jit_block_list::insert_before (iterator iter, jit_block *ablock)
+{
+  iter = mlist.insert (iter, ablock);
+  ablock->stash_location (iter);
+}
+
+void
+jit_block_list::insert_before (jit_block *loc, jit_block *ablock)
+{
+  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
+{
+  os << "-------------------- " << header << " --------------------\n";
+  return os << *this;
+}
+
+std::ostream&
+jit_block_list::print_dom (std::ostream& os) const
+{
+  os << "-------------------- dom info --------------------\n";
+  for (const_iterator iter = begin (); iter != end (); ++iter)
+    {
+      assert (*iter);
+      (*iter)->print_dom (os);
+    }
+  os << std::endl;
+
+  return os;
+}
+
+void
+jit_block_list::push_back (jit_block *b)
+{
+  mlist.push_back (b);
+  iterator iter = mlist.end ();
+  b->stash_location (--iter);
+}
+
+std::ostream&
+operator<<(std::ostream& os, const jit_block_list& blocks)
+{
+  for (jit_block_list::const_iterator iter = blocks.begin ();
+       iter != blocks.end (); ++iter)
+    {
+      assert (*iter);
+      (*iter)->print (os, 0);
+    }
+  return os << std::endl;
+}
+
+// -------------------- jit_use --------------------
+jit_block *
+jit_use::user_parent (void) const
+{
+  return muser->parent ();
+}
+
+// -------------------- jit_value --------------------
+jit_value::~jit_value (void)
+{}
+
+jit_block *
+jit_value::first_use_block (void)
+{
+  jit_use *use = first_use ();
+  while (use)
+    {
+      if (! isa<jit_error_check> (use->user ()))
+        return use->user_parent ();
+
+      use = use->next ();
+    }
+
+  return 0;
+}
+
+void
+jit_value::replace_with (jit_value *value)
+{
+  while (first_use ())
+    {
+      jit_instruction *user = first_use ()->user ();
+      size_t idx = first_use ()->index ();
+      user->stash_argument (idx, value);
+    }
+}
+
+#define JIT_METH(clname)                                \
+  void                                                  \
+  jit_ ## clname::accept (jit_ir_walker& walker)        \
+  {                                                     \
+    walker.visit (*this);                               \
+  }
+
+JIT_VISIT_IR_NOTEMPLATE
+#undef JIT_METH
+
+std::ostream&
+operator<< (std::ostream& os, const jit_value& value)
+{
+  return value.short_print (os);
+}
+
+std::ostream&
+jit_print (std::ostream& os, jit_value *avalue)
+{
+  if (avalue)
+    return avalue->print (os);
+  return os << "NULL";
+}
+
+// -------------------- jit_instruction --------------------
+void
+jit_instruction::remove (void)
+{
+  if (mparent)
+    mparent->remove (mlocation);
+  resize_arguments (0);
+}
+
+llvm::BasicBlock *
+jit_instruction::parent_llvm (void) const
+{
+  return mparent->to_llvm ();
+}
+
+std::ostream&
+jit_instruction::short_print (std::ostream& os) const
+{
+  if (type ())
+    jit_print (os, type ()) << ": ";
+  return os << "#" << mid;
+}
+
+void
+jit_instruction::do_construct_ssa (size_t start, size_t end)
+{
+  for (size_t i = start; i < end; ++i)
+    {
+      jit_value *arg = argument (i);
+      jit_variable *var = dynamic_cast<jit_variable *> (arg);
+      if (var && var->has_top ())
+        stash_argument (i, var->top ());
+    }
+}
+
+// -------------------- jit_block --------------------
+void
+jit_block::replace_with (jit_value *value)
+{
+  assert (isa<jit_block> (value));
+  jit_block *block = static_cast<jit_block *> (value);
+
+  jit_value::replace_with (block);
+
+  while (ILIST_T::first_use ())
+    {
+      jit_phi_incomming *incomming = ILIST_T::first_use ();
+      incomming->stash_value (block);
+    }
+}
+
+void
+jit_block::replace_in_phi (jit_block *ablock, jit_block *with)
+{
+  jit_phi_incomming *node = ILIST_T::first_use ();
+  while (node)
+    {
+      jit_phi_incomming *prev = node;
+      node = node->next ();
+
+      if (prev->user_parent () == ablock)
+        prev->stash_value (with);
+    }
+}
+
+jit_block *
+jit_block::maybe_merge ()
+{
+  if (successor_count () == 1 && successor (0) != this
+      && (successor (0)->use_count () == 1 || instructions.size () == 1))
+    {
+      jit_block *to_merge = successor (0);
+      merge (*to_merge);
+      return to_merge;
+    }
+
+  return 0;
+}
+
+void
+jit_block::merge (jit_block& block)
+{
+  // the merge block will contain a new terminator
+  jit_terminator *old_term = terminator ();
+  if (old_term)
+    old_term->remove ();
+
+  bool was_empty = end () == begin ();
+  iterator merge_begin = end ();
+  if (! was_empty)
+    --merge_begin;
+
+  instructions.splice (end (), block.instructions);
+  if (was_empty)
+    merge_begin = begin ();
+  else
+    ++merge_begin;
+
+  // now merge_begin points to the start of the new instructions, we must
+  // update their parent information
+  for (iterator iter = merge_begin; iter != end (); ++iter)
+    {
+      jit_instruction *instr = *iter;
+      instr->stash_parent (this, iter);
+    }
+
+  block.replace_with (this);
+}
+
+jit_instruction *
+jit_block::prepend (jit_instruction *instr)
+{
+  instructions.push_front (instr);
+  instr->stash_parent (this, instructions.begin ());
+  return instr;
+}
+
+jit_instruction *
+jit_block::prepend_after_phi (jit_instruction *instr)
+{
+  // FIXME: Make this O(1)
+  for (iterator iter = begin (); iter != end (); ++iter)
+    {
+      jit_instruction *temp = *iter;
+      if (! isa<jit_phi> (temp))
+        {
+          insert_before (iter, instr);
+          return instr;
+        }
+    }
+
+  return append (instr);
+}
+
+void
+jit_block::internal_append (jit_instruction *instr)
+{
+  instructions.push_back (instr);
+  instr->stash_parent (this, --instructions.end ());
+}
+
+jit_instruction *
+jit_block::insert_before (iterator loc, jit_instruction *instr)
+{
+  iterator iloc = instructions.insert (loc, instr);
+  instr->stash_parent (this, iloc);
+  return instr;
+}
+
+jit_instruction *
+jit_block::insert_after (iterator loc, jit_instruction *instr)
+{
+  ++loc;
+  iterator iloc = instructions.insert (loc, instr);
+  instr->stash_parent (this, iloc);
+  return instr;
+}
+
+jit_terminator *
+jit_block::terminator (void) const
+{
+  assert (this);
+  if (instructions.empty ())
+    return 0;
+
+  jit_instruction *last = instructions.back ();
+  return dynamic_cast<jit_terminator *> (last);
+}
+
+bool
+jit_block::branch_alive (jit_block *asucc) const
+{
+  return terminator ()->alive (asucc);
+}
+
+jit_block *
+jit_block::successor (size_t i) const
+{
+  jit_terminator *term = terminator ();
+  return term->successor (i);
+}
+
+size_t
+jit_block::successor_count (void) const
+{
+  jit_terminator *term = terminator ();
+  return term ? term->successor_count () : 0;
+}
+
+llvm::BasicBlock *
+jit_block::to_llvm (void) const
+{
+  return llvm::cast<llvm::BasicBlock> (llvm_value);
+}
+
+std::ostream&
+jit_block::print_dom (std::ostream& os) const
+{
+  short_print (os);
+  os << ":\n";
+  os << "  mid: " << mid << std::endl;
+  os << "  predecessors: ";
+  for (jit_use *use = first_use (); use; use = use->next ())
+    os << *use->user_parent () << " ";
+  os << std::endl;
+
+  os << "  successors: ";
+  for (size_t i = 0; i < successor_count (); ++i)
+    os << *successor (i) << " ";
+  os << std::endl;
+
+  os << "  idom: ";
+  if (idom)
+    os << *idom;
+  else
+    os << "NULL";
+  os << std::endl;
+  os << "  df: ";
+  for (df_iterator iter = df_begin (); iter != df_end (); ++iter)
+    os << **iter << " ";
+  os << std::endl;
+
+  os << "  dom_succ: ";
+  for (size_t i = 0; i < dom_succ.size (); ++i)
+    os << *dom_succ[i] << " ";
+
+  return os << std::endl;
+}
+
+void
+jit_block::compute_df (size_t avisit_count)
+{
+  if (visited (avisit_count))
+    return;
+
+  if (use_count () >= 2)
+    {
+      for (jit_use *use = first_use (); use; use = use->next ())
+        {
+          jit_block *runner = use->user_parent ();
+          while (runner != idom)
+            {
+              runner->mdf.insert (this);
+              runner = runner->idom;
+            }
+        }
+    }
+
+  for (size_t i = 0; i < successor_count (); ++i)
+    successor (i)->compute_df (avisit_count);
+}
+
+bool
+jit_block::update_idom (size_t avisit_count)
+{
+  if (visited (avisit_count) || ! use_count ())
+    return false;
+
+  bool changed = false;
+  for (jit_use *use = first_use (); use; use = use->next ())
+    {
+      jit_block *pred = use->user_parent ();
+      changed = pred->update_idom (avisit_count) || changed;
+    }
+
+  jit_use *use = first_use ();
+  jit_block *new_idom = use->user_parent ();
+  use = use->next ();
+
+  for (; use; use = use->next ())
+    {
+      jit_block *pred = use->user_parent ();
+      jit_block *pidom = pred->idom;
+      if (pidom)
+        new_idom = idom_intersect (pidom, new_idom);
+    }
+
+  if (idom != new_idom)
+    {
+      idom = new_idom;
+      return true;
+    }
+
+  return changed;
+}
+
+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)
+    {
+      jit_instruction *instr = *iter;
+      instr->pop_variable ();
+    }
+}
+
+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)
+{
+  if (successor_count () > 1)
+    {
+      jit_terminator *term = terminator ();
+      size_t idx = term->successor_index (asuccessor);
+      jit_block *split = factory.create<jit_block> ("phi_split", mvisit_count);
+
+      // place after this to ensure define before use in the blocks list
+      blocks.insert_after (this, split);
+
+      term->stash_argument (idx, split);
+      jit_branch *br = split->append (factory.create<jit_branch> (asuccessor));
+      replace_in_phi (asuccessor, split);
+
+      if (alive ())
+        {
+          split->mark_alive ();
+          br->infer ();
+        }
+
+      return split;
+    }
+
+  return this;
+}
+
+void
+jit_block::create_dom_tree (size_t avisit_count)
+{
+  if (visited (avisit_count))
+    return;
+
+  if (idom != this)
+    idom->dom_succ.push_back (this);
+
+  for (size_t i = 0; i < successor_count (); ++i)
+    successor (i)->create_dom_tree (avisit_count);
+}
+
+jit_block *
+jit_block::idom_intersect (jit_block *i, jit_block *j)
+{
+  while (i && j && i != j)
+    {
+      while (i && i->id () > j->id ())
+        i = i->idom;
+
+      while (i && j && j->id () > i->id ())
+        j = j->idom;
+    }
+
+  return i ? i : j;
+}
+
+// -------------------- jit_phi_incomming --------------------
+
+jit_block *
+jit_phi_incomming::user_parent (void) const
+{ return muser->parent (); }
+
+// -------------------- jit_phi --------------------
+bool
+jit_phi::prune (void)
+{
+  jit_block *p = parent ();
+  size_t new_idx = 0;
+  jit_value *unique = argument (1);
+
+  for (size_t i = 0; i < argument_count (); ++i)
+    {
+      jit_block *inc = incomming (i);
+      if (inc->branch_alive (p))
+        {
+          if (unique != argument (i))
+            unique = 0;
+
+          if (new_idx != i)
+            {
+              stash_argument (new_idx, argument (i));
+              mincomming[new_idx].stash_value (inc);
+            }
+
+          ++new_idx;
+        }
+    }
+
+  if (new_idx != argument_count ())
+    {
+      resize_arguments (new_idx);
+      mincomming.resize (new_idx);
+    }
+
+  assert (argument_count () > 0);
+  if (unique)
+    {
+      replace_with (unique);
+      return true;
+    }
+
+  return false;
+}
+
+bool
+jit_phi::infer (void)
+{
+  jit_block *p = parent ();
+  if (! p->alive ())
+    return false;
+
+  jit_type *infered = 0;
+  for (size_t i = 0; i < argument_count (); ++i)
+    {
+      jit_block *inc = incomming (i);
+      if (inc->branch_alive (p))
+        infered = jit_typeinfo::join (infered, argument_type (i));
+    }
+
+  if (infered != type ())
+    {
+      stash_type (infered);
+      return true;
+    }
+
+  return false;
+}
+
+llvm::PHINode *
+jit_phi::to_llvm (void) const
+{
+  return llvm::cast<llvm::PHINode> (jit_value::to_llvm ());
+}
+
+// -------------------- jit_terminator --------------------
+size_t
+jit_terminator::successor_index (const jit_block *asuccessor) const
+{
+  size_t scount = successor_count ();
+  for (size_t i = 0; i < scount; ++i)
+    if (successor (i) == asuccessor)
+      return i;
+
+  panic_impossible ();
+}
+
+bool
+jit_terminator::infer (void)
+{
+  if (! parent ()->alive ())
+    return false;
+
+  bool changed = false;
+  for (size_t i = 0; i < malive.size (); ++i)
+    if (! malive[i] && check_alive (i))
+      {
+        changed = true;
+        malive[i] = true;
+        successor (i)->mark_alive ();
+      }
+
+  return changed;
+}
+
+llvm::TerminatorInst *
+jit_terminator::to_llvm (void) const
+{
+  return llvm::cast<llvm::TerminatorInst> (jit_value::to_llvm ());
+}
+
+// -------------------- 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
+  for (size_t i = 0; i < argument_count (); ++i)
+    {
+      already_infered[i] = argument_type (i);
+      if (! already_infered[i])
+        return false;
+    }
+
+  jit_type *infered = moperation.result (already_infered);
+  if (! infered && use_count ())
+    {
+      std::stringstream ss;
+      ss << "Missing overload in type inference for ";
+      print (ss, 0);
+      throw jit_fail_exception (ss.str ());
+    }
+
+  if (infered != type ())
+    {
+      stash_type (infered);
+      return true;
+    }
+
+  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)
+  : value (avalue), index (factory.create<jit_const_index> (aindex)),
+    count (factory.create<jit_const_index> (acount))
+{}
+
+jit_magic_end::jit_magic_end (const std::vector<context>& full_context)
+  : contexts (full_context)
+{
+  resize_arguments (contexts.size ());
+
+  size_t i;
+  std::vector<context>::const_iterator iter;
+  for (iter = contexts.begin (), i = 0; iter != contexts.end (); ++iter, ++i)
+    stash_argument (i, iter->value);
+}
+
+jit_magic_end::context
+jit_magic_end::resolve_context (void) const
+{
+  size_t idx;
+  for (idx = 0; idx < contexts.size (); ++idx)
+    {
+      jit_type *ctx_type = contexts[idx].value->type ();
+      if (! ctx_type || ctx_type->skip_paren ())
+        break;
+    }
+
+  if (idx >= contexts.size ())
+    idx = 0;
+
+  context ret = contexts[idx];
+  ret.value = argument (idx);
+  return ret;
+}
+
+bool
+jit_magic_end::infer (void)
+{
+  jit_type *new_type = overload ().result ();
+  if (new_type != type ())
+    {
+      stash_type (new_type);
+      return true;
+    }
+
+  return false;
+}
+
+std::ostream&
+jit_magic_end::print (std::ostream& os, size_t indent) const
+{
+  context ctx = resolve_context ();
+  short_print (print_indent (os, indent)) << " (" << *ctx.value << ", ";
+  return os << *ctx.index << ", " << *ctx.count << ")";
+}
+
+const jit_function&
+jit_magic_end::overload () const
+{
+  const context& ctx = resolve_context ();
+  return jit_typeinfo::end (ctx.value, ctx.index, ctx.count);
+}
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libinterp/interp-core/jit-ir.h
@@ -0,0 +1,1434 @@
+/*
+
+Copyright (C) 2012 Max Brister <max@2bass.com>
+
+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_jit_ir_h)
+#define octave_jit_ir_h 1
+
+#ifdef HAVE_LLVM
+
+#include <list>
+#include <stack>
+#include <set>
+
+#include "jit-typeinfo.h"
+
+// The low level octave jit ir
+// this ir is close to llvm, but contains information for doing type inference.
+// We convert the octave parse tree to this IR directly.
+
+#define JIT_VISIT_IR_NOTEMPLATE                 \
+  JIT_METH(block);                              \
+  JIT_METH(branch);                             \
+  JIT_METH(cond_branch);                        \
+  JIT_METH(call);                               \
+  JIT_METH(extract_argument);                   \
+  JIT_METH(store_argument);                     \
+  JIT_METH(return);                             \
+  JIT_METH(phi);                                \
+  JIT_METH(variable);                           \
+  JIT_METH(error_check);                        \
+  JIT_METH(assign)                              \
+  JIT_METH(argument)                            \
+  JIT_METH(magic_end)
+
+#define JIT_VISIT_IR_CONST                      \
+  JIT_METH(const_bool);                         \
+  JIT_METH(const_scalar);                       \
+  JIT_METH(const_complex);                      \
+  JIT_METH(const_index);                        \
+  JIT_METH(const_string);                       \
+  JIT_METH(const_range)
+
+#define JIT_VISIT_IR_CLASSES                    \
+  JIT_VISIT_IR_NOTEMPLATE                       \
+  JIT_VISIT_IR_CONST
+
+// forward declare all ir classes
+#define JIT_METH(cname)                         \
+  class jit_ ## cname;
+
+JIT_VISIT_IR_NOTEMPLATE
+
+#undef JIT_METH
+
+// ABCs which aren't included in  JIT_VISIT_IR_ALL
+class jit_instruction;
+class jit_terminator;
+
+template <typename T, jit_type *(*EXTRACT_T)(void), typename PASS_T = T,
+          bool QUOTE=false>
+class jit_const;
+
+typedef jit_const<bool, jit_typeinfo::get_bool> jit_const_bool;
+typedef jit_const<double, jit_typeinfo::get_scalar> jit_const_scalar;
+typedef jit_const<Complex, jit_typeinfo::get_complex> jit_const_complex;
+typedef jit_const<octave_idx_type, jit_typeinfo::get_index> jit_const_index;
+
+typedef jit_const<std::string, jit_typeinfo::get_string, const std::string&,
+                  true> jit_const_string;
+typedef jit_const<jit_range, jit_typeinfo::get_range, const jit_range&>
+jit_const_range;
+
+class jit_ir_walker;
+class jit_use;
+
+// Creates and tracks memory for jit_value and subclasses.
+// Memory managment is simple, all values that are created live as long as the
+// factory.
+class
+jit_factory
+{
+  typedef std::list<jit_value *> value_list;
+public:
+  ~jit_factory (void);
+
+  const value_list& constants (void) const { return mconstants; }
+
+  template <typename T>
+  T *create (void)
+  {
+    T *ret = new T ();
+    track_value (ret);
+    return ret;
+  }
+
+#define DECL_ARG(n) const ARG ## n& arg ## n
+#define JIT_CREATE(N)                                           \
+  template <typename T, OCT_MAKE_DECL_LIST (typename, ARG, N)>  \
+  T *create (OCT_MAKE_LIST (DECL_ARG, N))                       \
+  {                                                             \
+    T *ret = new T (OCT_MAKE_ARG_LIST (arg, N));                \
+    track_value (ret);                                          \
+    return ret;                                                 \
+  }
+
+  JIT_CREATE (1)
+  JIT_CREATE (2)
+  JIT_CREATE (3)
+  JIT_CREATE (4)
+
+#undef JIT_CREATE
+#undef DECL_ARG
+private:
+  void track_value (jit_value *v);
+
+  value_list all_values;
+
+  value_list mconstants;
+};
+
+// A list of basic blocks (jit_block) which form some body of code.
+//
+// We do not directly inherit from std::list because we need to update the
+// blocks stashed location in push_back and insert.
+class
+jit_block_list
+{
+public:
+  typedef std::list<jit_block *>::iterator iterator;
+  typedef std::list<jit_block *>::const_iterator const_iterator;
+
+  jit_block *back (void) const { return mlist.back (); }
+
+  iterator begin (void) { return mlist.begin (); }
+
+  const_iterator begin (void) const { return mlist.begin (); }
+
+  iterator end (void)  { return mlist.end (); }
+
+  const_iterator end (void) const  { return mlist.end (); }
+
+  iterator erase (iterator iter) { return mlist.erase (iter); }
+
+  jit_block *front (void) const { return mlist.front (); }
+
+  void insert_after (iterator iter, jit_block *ablock);
+
+  void insert_after (jit_block *loc, jit_block *ablock);
+
+  void insert_before (iterator iter, jit_block *ablock);
+
+  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;
+
+  void push_back (jit_block *b);
+private:
+  std::list<jit_block *> mlist;
+};
+
+std::ostream& operator<<(std::ostream& os, const jit_block_list& blocks);
+
+class
+jit_value : public jit_internal_list<jit_value, jit_use>
+{
+public:
+  jit_value (void) : llvm_value (0), ty (0), mlast_use (0),
+                     min_worklist (false) {}
+
+  virtual ~jit_value (void);
+
+  bool in_worklist (void) const
+  {
+    return min_worklist;
+  }
+
+  void stash_in_worklist (bool ain_worklist)
+  {
+    min_worklist = ain_worklist;
+  }
+
+  // The block of the first use which is not a jit_error_check
+  // So this is not necessarily first_use ()->parent ().
+  jit_block *first_use_block (void);
+
+  // replace all uses with
+  virtual void replace_with (jit_value *value);
+
+  jit_type *type (void) const { return ty; }
+
+  llvm::Type *type_llvm (void) const
+  {
+    return ty ? ty->to_llvm () : 0;
+  }
+
+  const std::string& type_name (void) const
+  {
+    return ty->name ();
+  }
+
+  void stash_type (jit_type *new_ty) { ty = new_ty; }
+
+  std::string print_string (void)
+  {
+    std::stringstream ss;
+    print (ss);
+    return ss.str ();
+  }
+
+  jit_instruction *last_use (void) const { return mlast_use; }
+
+  void stash_last_use (jit_instruction *alast_use)
+  {
+    mlast_use = alast_use;
+  }
+
+  virtual bool needs_release (void) const { return false; }
+
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const = 0;
+
+  virtual std::ostream& short_print (std::ostream& os) const
+  { return print (os); }
+
+  virtual void accept (jit_ir_walker& walker) = 0;
+
+  bool has_llvm (void) const
+  {
+    return llvm_value;
+  }
+
+  llvm::Value *to_llvm (void) const
+  {
+    assert (llvm_value);
+    return llvm_value;
+  }
+
+  void stash_llvm (llvm::Value *compiled)
+  {
+    llvm_value = compiled;
+  }
+
+protected:
+  std::ostream& print_indent (std::ostream& os, size_t indent = 0) const
+  {
+    for (size_t i = 0; i < indent * 8; ++i)
+      os << " ";
+    return os;
+  }
+
+  llvm::Value *llvm_value;
+private:
+  jit_type *ty;
+  jit_instruction *mlast_use;
+  bool min_worklist;
+};
+
+std::ostream& operator<< (std::ostream& os, const jit_value& value);
+std::ostream& jit_print (std::ostream& os, jit_value *avalue);
+
+class
+jit_use : public jit_internal_node<jit_value, jit_use>
+{
+public:
+  // some compilers don't allow us to use jit_internal_node without template
+  // paremeters
+  typedef jit_internal_node<jit_value, jit_use> PARENT_T;
+
+  jit_use (void) : muser (0), mindex (0) {}
+
+  // we should really have a move operator, but not until c++11 :(
+  jit_use (const jit_use& use) : muser (0), mindex (0)
+  {
+    *this = use;
+  }
+
+  jit_use& operator= (const jit_use& use)
+  {
+    stash_value (use.value (), use.user (), use.index ());
+    return *this;
+  }
+
+  size_t index (void) const { return mindex; }
+
+  jit_instruction *user (void) const { return muser; }
+
+  jit_block *user_parent (void) const;
+
+  std::list<jit_block *> user_parent_location (void) const;
+
+  void stash_value (jit_value *avalue, jit_instruction *auser = 0,
+                    size_t aindex = -1)
+  {
+    PARENT_T::stash_value (avalue);
+    mindex = aindex;
+    muser = auser;
+  }
+private:
+  jit_instruction *muser;
+  size_t mindex;
+};
+
+class
+jit_instruction : public jit_value
+{
+public:
+  // FIXME: this code could be so much pretier with varadic templates...
+  jit_instruction (void) : mid (next_id ()), mparent (0)
+  {}
+
+  jit_instruction (size_t nargs) : mid (next_id ()), mparent (0)
+  {
+    already_infered.reserve (nargs);
+    marguments.reserve (nargs);
+  }
+
+#define STASH_ARG(i) stash_argument (i, arg ## i);
+#define JIT_INSTRUCTION_CTOR(N)                                         \
+  jit_instruction (OCT_MAKE_DECL_LIST (jit_value *, arg, N))            \
+  : already_infered (N), marguments (N), mid (next_id ()), mparent (0)  \
+  {                                                                     \
+    OCT_ITERATE_MACRO (STASH_ARG, N);                                   \
+  }
+
+  JIT_INSTRUCTION_CTOR(1)
+  JIT_INSTRUCTION_CTOR(2)
+  JIT_INSTRUCTION_CTOR(3)
+  JIT_INSTRUCTION_CTOR(4)
+
+#undef STASH_ARG
+#undef JIT_INSTRUCTION_CTOR
+
+  jit_instruction (const std::vector<jit_value *>& aarguments)
+  : already_infered (aarguments.size ()), marguments (aarguments.size ()),
+    mid (next_id ()), mparent (0)
+  {
+    for (size_t i = 0; i < aarguments.size (); ++i)
+      stash_argument (i, aarguments[i]);
+  }
+
+  static void reset_ids (void)
+  {
+    next_id (true);
+  }
+
+  jit_value *argument (size_t i) const
+  {
+    return marguments[i].value ();
+  }
+
+  llvm::Value *argument_llvm (size_t i) const
+  {
+    assert (argument (i));
+    return argument (i)->to_llvm ();
+  }
+
+  jit_type *argument_type (size_t i) const
+  {
+    return argument (i)->type ();
+  }
+
+  llvm::Type *argument_type_llvm (size_t i) const
+  {
+    assert (argument (i));
+    return argument_type (i)->to_llvm ();
+  }
+
+  std::ostream& print_argument (std::ostream& os, size_t i) const
+  {
+    if (argument (i))
+      return argument (i)->short_print (os);
+    else
+      return os << "NULL";
+  }
+
+  void stash_argument (size_t i, jit_value *arg)
+  {
+    marguments[i].stash_value (arg, this, i);
+  }
+
+  void push_argument (jit_value *arg)
+  {
+    marguments.push_back (jit_use ());
+    stash_argument (marguments.size () - 1, arg);
+    already_infered.push_back (0);
+  }
+
+  size_t argument_count (void) const
+  {
+    return marguments.size ();
+  }
+
+  void resize_arguments (size_t acount, jit_value *adefault = 0)
+  {
+    size_t old = marguments.size ();
+    marguments.resize (acount);
+    already_infered.resize (acount);
+
+    if (adefault)
+      for (size_t i = old; i < acount; ++i)
+        stash_argument (i, adefault);
+  }
+
+  const std::vector<jit_use>& arguments (void) const { return marguments; }
+
+  // argument types which have been infered already
+  const std::vector<jit_type *>& argument_types (void) const
+  { return already_infered; }
+
+  virtual void push_variable (void) {}
+
+  virtual void pop_variable (void) {}
+
+  virtual void construct_ssa (void)
+  {
+    do_construct_ssa (0, argument_count ());
+  }
+
+  virtual bool infer (void) { return false; }
+
+  void remove (void);
+
+  virtual std::ostream& short_print (std::ostream& os) const;
+
+  jit_block *parent (void) const { return mparent; }
+
+  std::list<jit_instruction *>::iterator location (void) const
+  {
+    return mlocation;
+  }
+
+  llvm::BasicBlock *parent_llvm (void) const;
+
+  void stash_parent (jit_block *aparent,
+                     std::list<jit_instruction *>::iterator alocation)
+  {
+    mparent = aparent;
+    mlocation = alocation;
+  }
+
+  size_t id (void) const { return mid; }
+protected:
+
+  // Do SSA replacement on arguments in [start, end)
+  void do_construct_ssa (size_t start, size_t end);
+
+  std::vector<jit_type *> already_infered;
+private:
+  static size_t next_id (bool reset = false)
+  {
+    static size_t ret = 0;
+    if (reset)
+      return ret = 0;
+
+    return ret++;
+  }
+
+  std::vector<jit_use> marguments;
+
+  size_t mid;
+  jit_block *mparent;
+  std::list<jit_instruction *>::iterator mlocation;
+};
+
+// defnie accept methods for subclasses
+#define JIT_VALUE_ACCEPT                        \
+  virtual void accept (jit_ir_walker& walker);
+
+// for use as a dummy argument during conversion to LLVM
+class
+jit_argument : public jit_value
+{
+public:
+  jit_argument (jit_type *atype, llvm::Value *avalue)
+  {
+    stash_type (atype);
+    stash_llvm (avalue);
+  }
+
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const
+  {
+    print_indent (os, indent);
+    return jit_print (os, type ()) << ": DUMMY";
+  }
+
+  JIT_VALUE_ACCEPT;
+};
+
+template <typename T, jit_type *(*EXTRACT_T)(void), typename PASS_T,
+          bool QUOTE>
+class
+jit_const : public jit_value
+{
+public:
+  typedef PASS_T pass_t;
+
+  jit_const (PASS_T avalue) : mvalue (avalue)
+  {
+    stash_type (EXTRACT_T ());
+  }
+
+  PASS_T value (void) const { return mvalue; }
+
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const
+  {
+    print_indent (os, indent);
+    jit_print (os, type ()) << ": ";
+    if (QUOTE)
+      os << "\"";
+    os << mvalue;
+    if (QUOTE)
+      os << "\"";
+    return os;
+  }
+
+  JIT_VALUE_ACCEPT;
+private:
+  T mvalue;
+};
+
+class jit_phi_incomming;
+
+class
+jit_block : public jit_value, public jit_internal_list<jit_block,
+                                                       jit_phi_incomming>
+{
+  typedef jit_internal_list<jit_block, jit_phi_incomming> ILIST_T;
+public:
+  typedef std::list<jit_instruction *> instruction_list;
+  typedef instruction_list::iterator iterator;
+  typedef instruction_list::const_iterator const_iterator;
+
+  typedef std::set<jit_block *> df_set;
+  typedef df_set::const_iterator df_iterator;
+
+  static const size_t NO_ID = static_cast<size_t> (-1);
+
+  jit_block (const std::string& aname, size_t avisit_count = 0)
+    : mvisit_count (avisit_count), mid (NO_ID), idom (0), mname (aname),
+      malive (false)
+  {}
+
+  virtual void replace_with (jit_value *value);
+
+  void replace_in_phi (jit_block *ablock, jit_block *with);
+
+  // we have a new internal list, but we want to stay compatable with jit_value
+  jit_use *first_use (void) const { return jit_value::first_use (); }
+
+  size_t use_count (void) const { return jit_value::use_count (); }
+
+  // if a block is alive, then it might be visited during execution
+  bool alive (void) const { return malive; }
+
+  void mark_alive (void) { malive = true; }
+
+  // If we can merge with a successor, do so and return the now empty block
+  jit_block *maybe_merge ();
+
+  // merge another block into this block, leaving the merge block empty
+  void merge (jit_block& merge);
+
+  const std::string& name (void) const { return mname; }
+
+  jit_instruction *prepend (jit_instruction *instr);
+
+  jit_instruction *prepend_after_phi (jit_instruction *instr);
+
+  template <typename T>
+  T *append (T *instr)
+  {
+    internal_append (instr);
+    return instr;
+  }
+
+  jit_instruction *insert_before (iterator loc, jit_instruction *instr);
+
+  jit_instruction *insert_before (jit_instruction *loc, jit_instruction *instr)
+  {
+    return insert_before (loc->location (), instr);
+  }
+
+  jit_instruction *insert_after (iterator loc, jit_instruction *instr);
+
+  jit_instruction *insert_after (jit_instruction *loc, jit_instruction *instr)
+  {
+    return insert_after (loc->location (), instr);
+  }
+
+  iterator remove (iterator iter)
+  {
+    jit_instruction *instr = *iter;
+    iter = instructions.erase (iter);
+    instr->stash_parent (0, instructions.end ());
+    return iter;
+  }
+
+  jit_terminator *terminator (void) const;
+
+  // is the jump from pred alive?
+  bool branch_alive (jit_block *asucc) const;
+
+  jit_block *successor (size_t i) const;
+
+  size_t successor_count (void) const;
+
+  iterator begin (void) { return instructions.begin (); }
+
+  const_iterator begin (void) const { return instructions.begin (); }
+
+  iterator end (void) { return instructions.end (); }
+
+  const_iterator end (void) const { return instructions.end (); }
+
+  iterator phi_begin (void);
+
+  iterator phi_end (void);
+
+  iterator nonphi_begin (void);
+
+  // must label before id is valid
+  size_t id (void) const { return mid; }
+
+  // dominance frontier
+  const df_set& df (void) const { return mdf; }
+
+  df_iterator df_begin (void) const { return mdf.begin (); }
+
+  df_iterator df_end (void) const { return mdf.end (); }
+
+  // label with a RPO walk
+  void label (void)
+  {
+    size_t number = 0;
+    label (mvisit_count, 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).
+  // "A Simple, Fast Dominance Algorithm"
+  void compute_idom (jit_block& entry_block)
+  {
+    bool changed;
+    entry_block.idom = &entry_block;
+    do
+      changed = update_idom (mvisit_count);
+    while (changed);
+  }
+
+  // compute dominance frontier
+  void compute_df (void)
+  {
+    compute_df (mvisit_count);
+  }
+
+  void create_dom_tree (void)
+  {
+    create_dom_tree (mvisit_count);
+  }
+
+  jit_block *dom_successor (size_t idx) const
+  {
+    return dom_succ[idx];
+  }
+
+  size_t dom_successor_count (void) const
+  {
+    return dom_succ.size ();
+  }
+
+  // call pop_varaible on all instructions
+  void pop_all (void);
+
+  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);
+
+  jit_block *maybe_split (jit_factory& factory, jit_block_list& blocks,
+                          jit_block& asuccessor)
+  {
+    return maybe_split (factory, blocks, &asuccessor);
+  }
+
+  // print dominator infomration
+  std::ostream& print_dom (std::ostream& os) const;
+
+  virtual std::ostream& short_print (std::ostream& os) const
+  {
+    os << mname;
+    if (mid != NO_ID)
+      os << mid;
+    else
+      os << "!";
+    return os;
+  }
+
+  llvm::BasicBlock *to_llvm (void) const;
+
+  std::list<jit_block *>::iterator location (void) const
+  { return mlocation; }
+
+  void stash_location (std::list<jit_block *>::iterator alocation)
+  { mlocation = alocation; }
+
+  // used to prevent visiting the same node twice in the graph
+  size_t visit_count (void) const { return mvisit_count; }
+
+  // check if this node has been visited yet at the given visit count. If we
+  // have not been visited yet, mark us as visited.
+  bool visited (size_t avisit_count)
+  {
+    if (mvisit_count <= avisit_count)
+      {
+        mvisit_count = avisit_count + 1;
+        return false;
+      }
+
+    return true;
+  }
+
+  jit_instruction *front (void) { return instructions.front (); }
+
+  jit_instruction *back (void) { return instructions.back (); }
+
+  JIT_VALUE_ACCEPT;
+private:
+  void internal_append (jit_instruction *instr);
+
+  void compute_df (size_t avisit_count);
+
+  bool update_idom (size_t avisit_count);
+
+  void create_dom_tree (size_t avisit_count);
+
+  static jit_block *idom_intersect (jit_block *i, jit_block *j);
+
+  size_t mvisit_count;
+  size_t mid;
+  jit_block *idom;
+  df_set mdf;
+  std::vector<jit_block *> dom_succ;
+  std::string mname;
+  instruction_list instructions;
+  bool malive;
+  std::list<jit_block *>::iterator mlocation;
+};
+
+// keeps track of phi functions that use a block on incomming edges
+class
+jit_phi_incomming : public jit_internal_node<jit_block, jit_phi_incomming>
+{
+public:
+  jit_phi_incomming (void) : muser (0) {}
+
+  jit_phi_incomming (jit_phi *auser) : muser (auser) {}
+
+  jit_phi_incomming (const jit_phi_incomming& use)
+  {
+    *this = use;
+  }
+
+  jit_phi_incomming& operator= (const jit_phi_incomming& use)
+  {
+    stash_value (use.value ());
+    muser = use.muser;
+    return *this;
+  }
+
+  jit_phi *user (void) const { return muser; }
+
+  jit_block *user_parent (void) const;
+private:
+  jit_phi *muser;
+};
+
+// A non-ssa variable
+class
+jit_variable : public jit_value
+{
+public:
+  jit_variable (const std::string& aname) : mname (aname), mlast_use (0) {}
+
+  const std::string &name (void) const { return mname; }
+
+  // manipulate the value_stack, for use during SSA construction. The top of the
+  // value stack represents the current value for this variable
+  bool has_top (void) const
+  {
+    return ! value_stack.empty ();
+  }
+
+  jit_value *top (void) const
+  {
+    return value_stack.top ();
+  }
+
+  void push (jit_instruction *v)
+  {
+    value_stack.push (v);
+    mlast_use = v;
+  }
+
+  void pop (void)
+  {
+    value_stack.pop ();
+  }
+
+  jit_instruction *last_use (void) const
+  {
+    return mlast_use;
+  }
+
+  void stash_last_use (jit_instruction *instr)
+  {
+    mlast_use = instr;
+  }
+
+  // blocks in which we are used
+  void use_blocks (jit_block::df_set& result)
+  {
+    jit_use *use = first_use ();
+    while (use)
+      {
+        result.insert (use->user_parent ());
+        use = use->next ();
+      }
+  }
+
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const
+  {
+    return print_indent (os, indent) << mname;
+  }
+
+  JIT_VALUE_ACCEPT;
+private:
+  std::string mname;
+  std::stack<jit_value *> value_stack;
+  jit_instruction *mlast_use;
+};
+
+class
+jit_assign_base : public jit_instruction
+{
+public:
+  jit_assign_base (jit_variable *adest) : jit_instruction (), mdest (adest) {}
+
+  jit_assign_base (jit_variable *adest, size_t npred) : jit_instruction (npred),
+                                                        mdest (adest) {}
+
+  jit_assign_base (jit_variable *adest, jit_value *arg0, jit_value *arg1)
+    : jit_instruction (arg0, arg1), mdest (adest) {}
+
+  jit_variable *dest (void) const { return mdest; }
+
+  virtual void push_variable (void)
+  {
+    mdest->push (this);
+  }
+
+  virtual void pop_variable (void)
+  {
+    mdest->pop ();
+  }
+
+  virtual std::ostream& short_print (std::ostream& os) const
+  {
+    if (type ())
+      jit_print (os, type ()) << ": ";
+
+    dest ()->short_print (os);
+    return os << "#" << id ();
+  }
+private:
+  jit_variable *mdest;
+};
+
+class
+jit_assign : public jit_assign_base
+{
+public:
+  jit_assign (jit_variable *adest, jit_value *asrc)
+    : jit_assign_base (adest, adest, asrc), martificial (false) {}
+
+  jit_value *overwrite (void) const
+  {
+    return argument (0);
+  }
+
+  jit_value *src (void) const
+  {
+    return argument (1);
+  }
+
+  // variables don't get modified in an SSA, but COW requires we modify
+  // variables. An artificial assign is for when a variable gets modified. We
+  // need an assign in the SSA, but the reference counts shouldn't be updated.
+  bool artificial (void) const { return martificial; }
+
+  void mark_artificial (void) { martificial = true; }
+
+  virtual bool infer (void)
+  {
+    jit_type *stype = src ()->type ();
+    if (stype != type())
+      {
+        stash_type (stype);
+        return true;
+      }
+
+    return false;
+  }
+
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const
+  {
+    print_indent (os, indent) << *this << " = " << *src ();
+
+    if (artificial ())
+      os << " [artificial]";
+
+    return os;
+  }
+
+  JIT_VALUE_ACCEPT;
+private:
+  bool martificial;
+};
+
+class
+jit_phi : public jit_assign_base
+{
+public:
+  jit_phi (jit_variable *adest, size_t npred)
+    : jit_assign_base (adest, npred)
+  {
+    mincomming.reserve (npred);
+  }
+
+  // removes arguments form dead incomming jumps
+  bool prune (void);
+
+  void add_incomming (jit_block *from, jit_value *value)
+  {
+    push_argument (value);
+    mincomming.push_back (jit_phi_incomming (this));
+    mincomming[mincomming.size () - 1].stash_value (from);
+  }
+
+  jit_block *incomming (size_t i) const
+  {
+    return mincomming[i].value ();
+  }
+
+  llvm::BasicBlock *incomming_llvm (size_t i) const
+  {
+    return incomming (i)->to_llvm ();
+  }
+
+  virtual void construct_ssa (void) {}
+
+  virtual bool infer (void);
+
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const
+  {
+    std::stringstream ss;
+    print_indent (ss, indent);
+    short_print (ss) << " phi ";
+    std::string ss_str = ss.str ();
+    std::string indent_str (ss_str.size (), ' ');
+    os << ss_str;
+
+    for (size_t i = 0; i < argument_count (); ++i)
+      {
+        if (i > 0)
+          os << indent_str;
+        os << "| ";
+
+        os << *incomming (i) << " -> ";
+        os << *argument (i);
+
+        if (i + 1 < argument_count ())
+          os << std::endl;
+      }
+
+    return os;
+  }
+
+  llvm::PHINode *to_llvm (void) const;
+
+  JIT_VALUE_ACCEPT;
+private:
+  std::vector<jit_phi_incomming> mincomming;
+};
+
+class
+jit_terminator : public jit_instruction
+{
+public:
+#define JIT_TERMINATOR_CONST(N)                                         \
+  jit_terminator (size_t asuccessor_count,                              \
+                  OCT_MAKE_DECL_LIST (jit_value *, arg, N))             \
+    : jit_instruction (OCT_MAKE_ARG_LIST (arg, N)),                     \
+      malive (asuccessor_count, false) {}
+
+  JIT_TERMINATOR_CONST (1)
+  JIT_TERMINATOR_CONST (2)
+  JIT_TERMINATOR_CONST (3)
+
+#undef JIT_TERMINATOR_CONST
+
+  jit_block *successor (size_t idx = 0) const
+  {
+    return static_cast<jit_block *> (argument (idx));
+  }
+
+  llvm::BasicBlock *successor_llvm (size_t idx = 0) const
+  {
+    return successor (idx)->to_llvm ();
+  }
+
+  size_t successor_index (const jit_block *asuccessor) const;
+
+  std::ostream& print_successor (std::ostream& os, size_t idx = 0) const
+  {
+    if (alive (idx))
+      os << "[live] ";
+    else
+      os << "[dead] ";
+
+    return successor (idx)->short_print (os);
+  }
+
+  // Check if the jump to successor is live
+  bool alive (const jit_block *asuccessor) const
+  {
+    return alive (successor_index (asuccessor));
+  }
+
+  bool alive (size_t idx) const { return malive[idx]; }
+
+  bool alive (int idx) const { return malive[idx]; }
+
+  size_t successor_count (void) const { return malive.size (); }
+
+  virtual bool infer (void);
+
+  llvm::TerminatorInst *to_llvm (void) const;
+protected:
+  virtual bool check_alive (size_t) const { return true; }
+private:
+  std::vector<bool> malive;
+};
+
+class
+jit_branch : public jit_terminator
+{
+public:
+  jit_branch (jit_block *succ) : jit_terminator (1, succ) {}
+
+  virtual size_t successor_count (void) const { return 1; }
+
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const
+  {
+    print_indent (os, indent) << "branch: ";
+    return print_successor (os);
+  }
+
+  JIT_VALUE_ACCEPT;
+};
+
+class
+jit_cond_branch : public jit_terminator
+{
+public:
+  jit_cond_branch (jit_value *c, jit_block *ctrue, jit_block *cfalse)
+    : jit_terminator (2, ctrue, cfalse, c) {}
+
+  jit_value *cond (void) const { return argument (2); }
+
+  std::ostream& print_cond (std::ostream& os) const
+  {
+    return cond ()->short_print (os);
+  }
+
+  llvm::Value *cond_llvm (void) const
+  {
+    return cond ()->to_llvm ();
+  }
+
+  virtual size_t successor_count (void) const { return 2; }
+
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const
+  {
+    print_indent (os, indent) << "cond_branch: ";
+    print_cond (os) << ", ";
+    print_successor (os, 0) << ", ";
+    return print_successor (os, 1);
+  }
+
+  JIT_VALUE_ACCEPT;
+};
+
+class
+jit_call : public jit_instruction
+{
+public:
+  jit_call (const jit_operation& (*aoperation) (void))
+    : moperation (aoperation ())
+  {
+    const jit_function& ol = overload ();
+    if (ol.valid ())
+      stash_type (ol.result ());
+  }
+
+  jit_call (const jit_operation& aoperation) : moperation (aoperation)
+  {
+    const jit_function& ol = overload ();
+    if (ol.valid ())
+      stash_type (ol.result ());
+  }
+
+#define JIT_CALL_CONST(N)                                               \
+  jit_call (const jit_operation& aoperation,                            \
+            OCT_MAKE_DECL_LIST (jit_value *, arg, N))                   \
+    : jit_instruction (OCT_MAKE_ARG_LIST (arg, N)), moperation (aoperation) {} \
+                                                                        \
+  jit_call (const jit_operation& (*aoperation) (void),                  \
+            OCT_MAKE_DECL_LIST (jit_value *, arg, N))                   \
+    : jit_instruction (OCT_MAKE_ARG_LIST (arg, N)), moperation (aoperation ()) \
+  {}
+
+  JIT_CALL_CONST (1)
+  JIT_CALL_CONST (2)
+  JIT_CALL_CONST (3)
+  JIT_CALL_CONST (4)
+
+#undef JIT_CALL_CONST
+
+  jit_call (const jit_operation& aoperation,
+            const std::vector<jit_value *>& args)
+  : jit_instruction (args), moperation (aoperation)
+  {}
+
+  const jit_operation& operation (void) const { return moperation; }
+
+  bool can_error (void) const
+  {
+    return overload ().can_error ();
+  }
+
+  const jit_function& overload (void) const
+  {
+    return moperation.overload (argument_types ());
+  }
+
+  virtual bool needs_release (void) const;
+
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const
+  {
+    print_indent (os, indent);
+
+    if (use_count ())
+      short_print (os) << " = ";
+    os << "call " << moperation.name () << " (";
+
+    for (size_t i = 0; i < argument_count (); ++i)
+      {
+        print_argument (os, i);
+        if (i + 1 < argument_count ())
+          os << ", ";
+      }
+    return os << ")";
+  }
+
+  virtual bool infer (void);
+
+  JIT_VALUE_ACCEPT;
+private:
+  const jit_operation& moperation;
+};
+
+// FIXME: This is just ugly...
+// 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:
+  // 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;
+
+  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
+class
+jit_magic_end : public jit_instruction
+{
+public:
+  class
+  context
+  {
+  public:
+    context (void) : value (0), index (0), count (0)
+    {}
+
+    context (jit_factory& factory, jit_value *avalue, size_t aindex,
+             size_t acount);
+
+    jit_value *value;
+    jit_const_index *index;
+    jit_const_index *count;
+  };
+
+  jit_magic_end (const std::vector<context>& full_context);
+
+  virtual bool infer (void);
+
+  const jit_function& overload () const;
+
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const;
+
+  context resolve_context (void) const;
+
+  virtual std::ostream& short_print (std::ostream& os) const
+  {
+    return os << "magic_end" << "#" << id ();
+  }
+
+  JIT_VALUE_ACCEPT;
+private:
+  std::vector<context> contexts;
+};
+
+class
+jit_extract_argument : public jit_assign_base
+{
+public:
+  jit_extract_argument (jit_type *atype, jit_variable *adest)
+    : jit_assign_base (adest)
+  {
+    stash_type (atype);
+  }
+
+  const std::string& name (void) const
+  {
+    return dest ()->name ();
+  }
+
+  const jit_function& overload (void) const
+  {
+    return jit_typeinfo::cast (type (), jit_typeinfo::get_any ());
+  }
+
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const
+  {
+    print_indent (os, indent);
+
+    return short_print (os) << " = extract " << name ();
+  }
+
+  JIT_VALUE_ACCEPT;
+};
+
+class
+jit_store_argument : public jit_instruction
+{
+public:
+  jit_store_argument (jit_variable *var)
+  : jit_instruction (var), dest (var)
+  {}
+
+  const std::string& name (void) const
+  {
+    return dest->name ();
+  }
+
+  const jit_function& overload (void) const
+  {
+    return jit_typeinfo::cast (jit_typeinfo::get_any (), result_type ());
+  }
+
+  jit_value *result (void) const
+  {
+    return argument (0);
+  }
+
+  jit_type *result_type (void) const
+  {
+    return result ()->type ();
+  }
+
+  llvm::Value *result_llvm (void) const
+  {
+    return result ()->to_llvm ();
+  }
+
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const
+  {
+    jit_value *res = result ();
+    print_indent (os, indent) << "store ";
+    dest->short_print (os);
+
+    if (! isa<jit_variable> (res))
+      {
+        os << " = ";
+        res->short_print (os);
+      }
+
+    return os;
+  }
+
+  JIT_VALUE_ACCEPT;
+private:
+  jit_variable *dest;
+};
+
+class
+jit_return : public jit_instruction
+{
+public:
+  jit_return (void) {}
+
+  jit_return (jit_value *retval) : jit_instruction (retval) {}
+
+  jit_value *result (void) const
+  {
+    return argument_count () ? argument (0) : 0;
+  }
+
+  jit_type *result_type (void) const
+  {
+    jit_value *res = result ();
+    return res ? res->type () : 0;
+  }
+
+  virtual std::ostream& print (std::ostream& os, size_t indent = 0) const
+  {
+    print_indent (os, indent) << "return";
+
+    if (result ())
+      os << " " << *result ();
+
+    return os;
+  }
+
+  JIT_VALUE_ACCEPT;
+};
+
+class
+jit_ir_walker
+{
+public:
+  virtual ~jit_ir_walker () {}
+
+#define JIT_METH(clname) \
+  virtual void visit (jit_ ## clname&) = 0;
+
+  JIT_VISIT_IR_CLASSES;
+
+#undef JIT_METH
+};
+
+template <typename T, jit_type *(*EXTRACT_T)(void), typename PASS_T, bool QUOTE>
+void
+jit_const<T, EXTRACT_T, PASS_T, QUOTE>::accept (jit_ir_walker& walker)
+{
+  walker.visit (*this);
+}
+
+#undef JIT_VALUE_ACCEPT
+
+#endif
+#endif
new file mode 100644
--- /dev/null
+++ b/libinterp/interp-core/jit-typeinfo.cc
@@ -0,0 +1,2237 @@
+/*
+
+Copyright (C) 2012 Max Brister <max@2bass.com>
+
+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/>.
+
+*/
+
+// defines required by llvm
+#define __STDC_LIMIT_MACROS
+#define __STDC_CONSTANT_MACROS
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#ifdef HAVE_LLVM
+
+#include "jit-typeinfo.h"
+
+#include <llvm/Analysis/Verifier.h>
+#include <llvm/GlobalVariable.h>
+#include <llvm/ExecutionEngine/ExecutionEngine.h>
+#include <llvm/LLVMContext.h>
+#include <llvm/Function.h>
+#include <llvm/Instructions.h>
+#include <llvm/Intrinsics.h>
+#include <llvm/Support/IRBuilder.h>
+#include <llvm/Support/raw_os_ostream.h>
+
+#include "jit-ir.h"
+#include "ov.h"
+#include "ov-builtin.h"
+#include "ov-complex.h"
+#include "ov-scalar.h"
+#include "pager.h"
+
+static llvm::LLVMContext& context = llvm::getGlobalContext ();
+
+jit_typeinfo *jit_typeinfo::instance = 0;
+
+std::ostream& jit_print (std::ostream& os, jit_type *atype)
+{
+  if (! atype)
+    return os << "null";
+  return os << atype->name ();
+}
+
+// function that jit code calls
+extern "C" void
+octave_jit_print_any (const char *name, octave_base_value *obv)
+{
+  obv->print_with_name (octave_stdout, name, true);
+}
+
+extern "C" void
+octave_jit_print_scalar (const char *name, double value)
+{
+  // FIXME: We should avoid allocating a new octave_scalar each time
+  octave_value ov (value);
+  ov.print_with_name (octave_stdout, name);
+}
+
+extern "C" octave_base_value*
+octave_jit_binary_any_any (octave_value::binary_op op, octave_base_value *lhs,
+                           octave_base_value *rhs)
+{
+  octave_value olhs (lhs, true);
+  octave_value orhs (rhs, true);
+  octave_value result = do_binary_op (op, olhs, orhs);
+  octave_base_value *rep = result.internal_rep ();
+  rep->grab ();
+  return rep;
+}
+
+extern "C" octave_idx_type
+octave_jit_compute_nelem (double base, double limit, double inc)
+{
+  Range rng = Range (base, limit, inc);
+  return rng.nelem ();
+}
+
+extern "C" void
+octave_jit_release_any (octave_base_value *obv)
+{
+  obv->release ();
+}
+
+extern "C" void
+octave_jit_release_matrix (jit_matrix *m)
+{
+  delete m->array;
+}
+
+extern "C" octave_base_value *
+octave_jit_grab_any (octave_base_value *obv)
+{
+  obv->grab ();
+  return obv;
+}
+
+extern "C" jit_matrix
+octave_jit_grab_matrix (jit_matrix *m)
+{
+  return *m->array;
+}
+
+extern "C" octave_base_value *
+octave_jit_cast_any_matrix (jit_matrix *m)
+{
+  octave_value ret (*m->array);
+  octave_base_value *rep = ret.internal_rep ();
+  rep->grab ();
+  delete m->array;
+
+  return rep;
+}
+
+extern "C" jit_matrix
+octave_jit_cast_matrix_any (octave_base_value *obv)
+{
+  NDArray m = obv->array_value ();
+  obv->release ();
+  return m;
+}
+
+extern "C" octave_base_value *
+octave_jit_cast_any_range (jit_range *rng)
+{
+  Range temp (*rng);
+  octave_value ret (temp);
+  octave_base_value *rep = ret.internal_rep ();
+  rep->grab ();
+
+  return rep;
+}
+extern "C" jit_range
+octave_jit_cast_range_any (octave_base_value *obv)
+{
+
+  jit_range r (obv->range_value ());
+  obv->release ();
+  return r;
+}
+
+extern "C" double
+octave_jit_cast_scalar_any (octave_base_value *obv)
+{
+  double ret = obv->double_value ();
+  obv->release ();
+  return ret;
+}
+
+extern "C" octave_base_value *
+octave_jit_cast_any_scalar (double value)
+{
+  return new octave_scalar (value);
+}
+
+extern "C" Complex
+octave_jit_cast_complex_any (octave_base_value *obv)
+{
+  Complex ret = obv->complex_value ();
+  obv->release ();
+  return ret;
+}
+
+extern "C" octave_base_value *
+octave_jit_cast_any_complex (Complex c)
+{
+  if (c.imag () == 0)
+    return new octave_scalar (c.real ());
+  else
+    return new octave_complex (c);
+}
+
+extern "C" void
+octave_jit_gripe_nan_to_logical_conversion (void)
+{
+  try
+    {
+      gripe_nan_to_logical_conversion ();
+    }
+  catch (const octave_execution_exception&)
+    {
+      gripe_library_execution_error ();
+    }
+}
+
+extern "C" void
+octave_jit_ginvalid_index (void)
+{
+  try
+    {
+      gripe_invalid_index ();
+    }
+  catch (const octave_execution_exception&)
+    {
+      gripe_library_execution_error ();
+    }
+}
+
+extern "C" void
+octave_jit_gindex_range (int nd, int dim, octave_idx_type iext,
+                         octave_idx_type ext)
+{
+  try
+    {
+      gripe_index_out_of_range (nd, dim, iext, ext);
+    }
+  catch (const octave_execution_exception&)
+    {
+      gripe_library_execution_error ();
+    }
+}
+
+extern "C" jit_matrix
+octave_jit_paren_subsasgn_impl (jit_matrix *mat, octave_idx_type index,
+                                double value)
+{
+  NDArray *array = mat->array;
+  if (array->nelem () < index)
+    array->resize1 (index);
+
+  double *data = array->fortran_vec ();
+  data[index - 1] = value;
+
+  mat->update ();
+  return *mat;
+}
+
+static void
+make_indices (double *indices, octave_idx_type idx_count,
+              Array<idx_vector>& result)
+{
+  result.resize (dim_vector (1, idx_count));
+  for (octave_idx_type i = 0; i < idx_count; ++i)
+    result(i) = idx_vector (indices[i]);
+}
+
+extern "C" double
+octave_jit_paren_scalar (jit_matrix *mat, double *indicies,
+                         octave_idx_type idx_count)
+{
+  // FIXME: Replace this with a more optimal version
+  try
+    {
+      Array<idx_vector> idx;
+      make_indices (indicies, idx_count, idx);
+
+      Array<double> ret = mat->array->index (idx);
+      return ret.xelem (0);
+    }
+  catch (const octave_execution_exception&)
+    {
+      gripe_library_execution_error ();
+      return 0;
+    }
+}
+
+extern "C" jit_matrix
+octave_jit_paren_scalar_subsasgn (jit_matrix *mat, double *indices,
+                                  octave_idx_type idx_count, double value)
+{
+  // FIXME: Replace this with a more optimal version
+  jit_matrix ret;
+  try
+    {
+      Array<idx_vector> idx;
+      make_indices (indices, idx_count, idx);
+
+      Matrix temp (1, 1);
+      temp.xelem(0) = value;
+      mat->array->assign (idx, temp);
+      ret.update (mat->array);
+    }
+  catch (const octave_execution_exception&)
+    {
+      gripe_library_execution_error ();
+    }
+
+  return ret;
+}
+
+extern "C" jit_matrix
+octave_jit_paren_subsasgn_matrix_range (jit_matrix *mat, jit_range *index,
+                                        double value)
+{
+  NDArray *array = mat->array;
+  bool done = false;
+
+  // optimize for the simple case (no resizing and no errors)
+  if (*array->jit_ref_count () == 1
+      && index->all_elements_are_ints ())
+    {
+      // this code is similar to idx_vector::fill, but we avoid allocating an
+      // idx_vector and its associated rep
+      octave_idx_type start = static_cast<octave_idx_type> (index->base) - 1;
+      octave_idx_type step = static_cast<octave_idx_type> (index->inc);
+      octave_idx_type nelem = index->nelem;
+      octave_idx_type final = start + nelem * step;
+      if (step < 0)
+        {
+          step = -step;
+          std::swap (final, start);
+        }
+
+      if (start >= 0 && final < mat->slice_len)
+        {
+          done = true;
+
+          double *data = array->jit_slice_data ();
+          if (step == 1)
+            std::fill (data + start, data + start + nelem, value);
+          else
+            {
+              for (octave_idx_type i = start; i < final; i += step)
+                data[i] = value;
+            }
+        }
+    }
+
+  if (! done)
+    {
+      idx_vector idx (*index);
+      NDArray avalue (dim_vector (1, 1));
+      avalue.xelem (0) = value;
+      array->assign (idx, avalue);
+    }
+
+  jit_matrix ret;
+  ret.update (array);
+  return ret;
+}
+
+extern "C" double
+octave_jit_end_matrix (jit_matrix *mat, octave_idx_type idx,
+                       octave_idx_type count)
+{
+  octave_idx_type ndim = mat->dimensions[-1];
+  if (ndim == count)
+    return mat->dimensions[idx];
+  else if (ndim > count)
+    {
+      if (idx == count - 1)
+        {
+          double ret = mat->dimensions[idx];
+          for (octave_idx_type i = idx + 1; i < ndim; ++i)
+            ret *= mat->dimensions[idx];
+          return ret;
+        }
+
+      return mat->dimensions[idx];
+    }
+  else // ndim < count
+    return idx < ndim ? mat->dimensions[idx] : 1;
+}
+
+extern "C" octave_base_value *
+octave_jit_create_undef (void)
+{
+  octave_value undef;
+  octave_base_value *ret = undef.internal_rep ();
+  ret->grab ();
+
+  return ret;
+}
+
+extern "C" Complex
+octave_jit_complex_mul (Complex lhs, Complex rhs)
+{
+  if (lhs.imag () == 0 && rhs.imag() == 0)
+    return Complex (lhs.real () * rhs.real (), 0);
+
+  return lhs * rhs;
+}
+
+extern "C" Complex
+octave_jit_complex_div (Complex lhs, Complex rhs)
+{
+  // see src/OPERATORS/op-cs-cs.cc
+  if (rhs == 0.0)
+    gripe_divide_by_zero ();
+
+  return lhs / rhs;
+}
+
+// FIXME: CP form src/xpow.cc
+static inline int
+xisint (double x)
+{
+  return (D_NINT (x) == x
+          && ((x >= 0 && x < std::numeric_limits<int>::max ())
+              || (x <= 0 && x > std::numeric_limits<int>::min ())));
+}
+
+extern "C" Complex
+octave_jit_pow_scalar_scalar (double lhs, double rhs)
+{
+  // FIXME: almost CP from src/xpow.cc
+  if (lhs < 0.0 && ! xisint (rhs))
+    return std::pow (Complex (lhs), rhs);
+  return std::pow (lhs, rhs);
+}
+
+extern "C" Complex
+octave_jit_pow_complex_complex (Complex lhs, Complex rhs)
+{
+  if (lhs.imag () == 0 && rhs.imag () == 0)
+    return octave_jit_pow_scalar_scalar (lhs.real (), rhs.real ());
+  return std::pow (lhs, rhs);
+}
+
+extern "C" Complex
+octave_jit_pow_complex_scalar (Complex lhs, double rhs)
+{
+  if (lhs.imag () == 0)
+    return octave_jit_pow_scalar_scalar (lhs.real (), rhs);
+  return std::pow (lhs, rhs);
+}
+
+extern "C" Complex
+octave_jit_pow_scalar_complex (double lhs, Complex rhs)
+{
+  if (rhs.imag () == 0)
+    return octave_jit_pow_scalar_scalar (lhs, rhs.real ());
+  return std::pow (lhs, rhs);
+}
+
+extern "C" void
+octave_jit_print_matrix (jit_matrix *m)
+{
+  std::cout << *m << std::endl;
+}
+
+static void
+gripe_bad_result (void)
+{
+  error ("incorrect type information given to the JIT compiler");
+}
+
+// FIXME: Add support for multiple outputs
+extern "C" octave_base_value *
+octave_jit_call (octave_builtin::fcn fn, size_t nargin,
+                 octave_base_value **argin, jit_type *result_type)
+{
+  octave_value_list ovl (nargin);
+  for (size_t i = 0; i < nargin; ++i)
+    ovl.xelem (i) = octave_value (argin[i]);
+
+  ovl = fn (ovl, 1);
+
+  // FIXME: Check result_type somehow
+  if (result_type)
+    {
+      if (ovl.length () < 1)
+        {
+          gripe_bad_result ();
+          return 0;
+        }
+
+      octave_value result = ovl.xelem(0);
+      octave_base_value *ret = result.internal_rep ();
+      ret->grab ();
+      return ret;
+    }
+
+  if (! (ovl.length () == 0
+         || (ovl.length () == 1 && ovl.xelem (0).is_undefined ())))
+    gripe_bad_result ();
+
+  return 0;
+}
+
+// -------------------- jit_range --------------------
+bool
+jit_range::all_elements_are_ints () const
+{
+  Range r (*this);
+  return r.all_elements_are_ints ();
+}
+
+std::ostream&
+operator<< (std::ostream& os, const jit_range& rng)
+{
+  return os << "Range[" << rng.base << ", " << rng.limit << ", " << rng.inc
+            << ", " << rng.nelem << "]";
+}
+
+// -------------------- jit_matrix --------------------
+
+std::ostream&
+operator<< (std::ostream& os, const jit_matrix& mat)
+{
+  return os << "Matrix[" << mat.ref_count << ", " << mat.slice_data << ", "
+            << mat.slice_len << ", " << mat.dimensions << ", "
+            << mat.array << "]";
+}
+
+// -------------------- jit_type --------------------
+jit_type::jit_type (const std::string& aname, jit_type *aparent,
+                    llvm::Type *allvm_type, bool askip_paren, int aid) :
+  mname (aname), mparent (aparent), llvm_type (allvm_type), mid (aid),
+  mdepth (aparent ? aparent->mdepth + 1 : 0), mskip_paren (askip_paren)
+{
+  std::memset (msret, 0, sizeof (msret));
+  std::memset (mpointer_arg, 0, sizeof (mpointer_arg));
+  std::memset (mpack, 0, sizeof (mpack));
+  std::memset (munpack, 0, sizeof (munpack));
+
+  for (size_t i = 0; i < jit_convention::length; ++i)
+    mpacked_type[i] = llvm_type;
+}
+
+llvm::Type *
+jit_type::to_llvm_arg (void) const
+{
+  return llvm_type ? llvm_type->getPointerTo () : 0;
+}
+
+// -------------------- jit_function --------------------
+jit_function::jit_function () : module (0), llvm_function (0), mresult (0),
+                                call_conv (jit_convention::length),
+                                mcan_error (false)
+{}
+
+jit_function::jit_function (llvm::Module *amodule,
+                            jit_convention::type acall_conv,
+                            const llvm::Twine& aname, jit_type *aresult,
+                            const std::vector<jit_type *>& aargs)
+  : module (amodule), mresult (aresult), args (aargs), call_conv (acall_conv),
+    mcan_error (false)
+{
+  llvm::SmallVector<llvm::Type *, 15> llvm_args;
+
+  llvm::Type *rtype = llvm::Type::getVoidTy (context);
+  if (mresult)
+    {
+      rtype = mresult->packed_type (call_conv);
+      if (sret ())
+        {
+          llvm_args.push_back (rtype->getPointerTo ());
+          rtype = llvm::Type::getVoidTy (context);
+        }
+    }
+
+  for (std::vector<jit_type *>::const_iterator iter = args.begin ();
+       iter != args.end (); ++iter)
+    {
+      jit_type *ty = *iter;
+      assert (ty);
+      llvm::Type *argty = ty->packed_type (call_conv);
+      if (ty->pointer_arg (call_conv))
+        argty = argty->getPointerTo ();
+
+      llvm_args.push_back (argty);
+    }
+
+  // we mark all functinos as external linkage because this prevents llvm
+  // from getting rid of always inline functions
+  llvm::FunctionType *ft = llvm::FunctionType::get (rtype, llvm_args, false);
+  llvm_function = llvm::Function::Create (ft, llvm::Function::ExternalLinkage,
+                                          aname, module);
+
+  if (sret ())
+    llvm_function->addAttribute (1, llvm::Attribute::StructRet);
+
+  if (call_conv == jit_convention::internal)
+    llvm_function->addFnAttr (llvm::Attribute::AlwaysInline);
+}
+
+jit_function::jit_function (const jit_function& fn, jit_type *aresult,
+                            const std::vector<jit_type *>& aargs)
+  : module (fn.module), llvm_function (fn.llvm_function), mresult (aresult),
+    args (aargs), call_conv (fn.call_conv), mcan_error (fn.mcan_error)
+{
+}
+
+jit_function::jit_function (const jit_function& fn)
+  : module (fn.module), llvm_function (fn.llvm_function), mresult (fn.mresult),
+    args (fn.args), call_conv (fn.call_conv), mcan_error (fn.mcan_error)
+{}
+
+void
+jit_function::erase (void)
+{
+  if (! llvm_function)
+    return;
+
+  llvm_function->eraseFromParent ();
+  llvm_function = 0;
+}
+
+std::string
+jit_function::name (void) const
+{
+  return llvm_function->getName ();
+}
+
+llvm::BasicBlock *
+jit_function::new_block (const std::string& aname,
+                         llvm::BasicBlock *insert_before)
+{
+  return llvm::BasicBlock::Create (context, aname, llvm_function,
+                                   insert_before);
+}
+
+llvm::Value *
+jit_function::call (llvm::IRBuilderD& builder,
+                    const std::vector<jit_value *>& in_args) const
+{
+  if (! valid ())
+    throw jit_fail_exception ("Call not implemented");
+
+  assert (in_args.size () == args.size ());
+  std::vector<llvm::Value *> llvm_args (args.size ());
+  for (size_t i = 0; i < in_args.size (); ++i)
+    llvm_args[i] = in_args[i]->to_llvm ();
+
+  return call (builder, llvm_args);
+}
+
+llvm::Value *
+jit_function::call (llvm::IRBuilderD& builder,
+                    const std::vector<llvm::Value *>& in_args) const
+{
+  if (! valid ())
+    throw jit_fail_exception ("Call not implemented");
+
+  assert (in_args.size () == args.size ());
+  llvm::SmallVector<llvm::Value *, 10> llvm_args;
+  llvm_args.reserve (in_args.size () + sret ());
+
+  llvm::BasicBlock *insert_block = builder.GetInsertBlock ();
+  llvm::Function *parent = insert_block->getParent ();
+  assert (parent);
+
+  // we insert allocas inside the prelude block to prevent stack overflows
+  llvm::BasicBlock& prelude = parent->getEntryBlock ();
+  llvm::IRBuilder<> pre_builder (&prelude, prelude.begin ());
+
+  llvm::AllocaInst *sret_mem = 0;
+  if (sret ())
+    {
+      sret_mem = pre_builder.CreateAlloca (mresult->packed_type (call_conv));
+      llvm_args.push_back (sret_mem);
+    }
+
+  for (size_t i = 0; i < in_args.size (); ++i)
+    {
+      llvm::Value *arg = in_args[i];
+      jit_type::convert_fn convert = args[i]->pack (call_conv);
+      if (convert)
+        arg = convert (builder, arg);
+
+      if (args[i]->pointer_arg (call_conv))
+        {
+          llvm::Type *ty = args[i]->packed_type (call_conv);
+          llvm::Value *alloca = pre_builder.CreateAlloca (ty);
+          builder.CreateStore (arg, alloca);
+          arg = alloca;
+        }
+
+      llvm_args.push_back (arg);
+    }
+
+  llvm::CallInst *callinst = builder.CreateCall (llvm_function, llvm_args);
+  llvm::Value *ret = callinst;
+
+  if (sret ())
+    {
+      callinst->addAttribute (1, llvm::Attribute::StructRet);
+      ret = builder.CreateLoad (sret_mem);
+    }
+
+  if (mresult)
+    {
+      jit_type::convert_fn unpack = mresult->unpack (call_conv);
+      if (unpack)
+        ret = unpack (builder, ret);
+    }
+
+  return ret;
+}
+
+llvm::Value *
+jit_function::argument (llvm::IRBuilderD& builder, size_t idx) const
+{
+  assert (idx < args.size ());
+
+  // FIXME: We should be treating arguments like a list, not a vector. Shouldn't
+  // matter much for now, as the number of arguments shouldn't be much bigger
+  // than 4
+  llvm::Function::arg_iterator iter = llvm_function->arg_begin ();
+  if (sret ())
+    ++iter;
+
+  for (size_t i = 0; i < idx; ++i, ++iter);
+
+  if (args[idx]->pointer_arg (call_conv))
+    return builder.CreateLoad (iter);
+
+  return iter;
+}
+
+void
+jit_function::do_return (llvm::IRBuilderD& builder, llvm::Value *rval,
+                         bool verify)
+{
+  assert (! rval == ! mresult);
+
+  if (rval)
+    {
+      jit_type::convert_fn convert = mresult->pack (call_conv);
+      if (convert)
+        rval = convert (builder, rval);
+
+      if (sret ())
+        {
+          builder.CreateStore (rval, llvm_function->arg_begin ());
+          builder.CreateRetVoid ();
+        }
+      else
+        builder.CreateRet (rval);
+    }
+  else
+    builder.CreateRetVoid ();
+
+  if (verify)
+    llvm::verifyFunction (*llvm_function);
+}
+
+void
+jit_function::do_add_mapping (llvm::ExecutionEngine *engine, void *fn)
+{
+  assert (valid ());
+  engine->addGlobalMapping (llvm_function, fn);
+}
+
+std::ostream&
+operator<< (std::ostream& os, const jit_function& fn)
+{
+  llvm::Function *lfn = fn.to_llvm ();
+  os << "jit_function: cc=" << fn.call_conv;
+  llvm::raw_os_ostream llvm_out (os);
+  lfn->print (llvm_out);
+  llvm_out.flush ();
+  return os;
+}
+
+// -------------------- jit_operation --------------------
+jit_operation::~jit_operation (void)
+{
+  for (generated_map::iterator iter = generated.begin ();
+       iter != generated.end (); ++iter)
+    {
+      delete iter->first;
+      delete iter->second;
+    }
+}
+
+void
+jit_operation::add_overload (const jit_function& func,
+                            const std::vector<jit_type*>& args)
+{
+  if (args.size () >= overloads.size ())
+    overloads.resize (args.size () + 1);
+
+  Array<jit_function>& over = overloads[args.size ()];
+  dim_vector dv (over.dims ());
+  Array<octave_idx_type> idx = to_idx (args);
+  bool must_resize = false;
+
+  if (dv.length () != idx.numel ())
+    {
+      dv.resize (idx.numel ());
+      must_resize = true;
+    }
+
+  for (octave_idx_type i = 0; i < dv.length (); ++i)
+    if (dv(i) <= idx(i))
+      {
+        must_resize = true;
+        dv(i) = idx(i) + 1;
+      }
+
+  if (must_resize)
+    over.resize (dv);
+
+  over(idx) = func;
+}
+
+const jit_function&
+jit_operation::overload (const std::vector<jit_type*>& types) const
+{
+  static jit_function null_overload;
+  for (size_t i  =0; i < types.size (); ++i)
+    if (! types[i])
+      return null_overload;
+
+  if (types.size () >= overloads.size ())
+    return do_generate (types);
+
+  const Array<jit_function>& over = overloads[types.size ()];
+  dim_vector dv (over.dims ());
+  Array<octave_idx_type> idx = to_idx (types);
+  for (octave_idx_type i = 0; i < dv.length (); ++i)
+    if (idx(i) >= dv(i))
+      return do_generate (types);
+
+  const jit_function& ret = over(idx);
+  if (! ret.valid ())
+    return do_generate (types);
+
+  return ret;
+}
+
+Array<octave_idx_type>
+jit_operation::to_idx (const std::vector<jit_type*>& types) const
+{
+  octave_idx_type numel = types.size ();
+  numel = std::max (2, numel);
+
+  Array<octave_idx_type> idx (dim_vector (1, numel));
+  for (octave_idx_type i = 0; i < static_cast<octave_idx_type> (types.size ());
+       ++i)
+    idx(i) = types[i]->type_id ();
+
+  if (types.size () == 0)
+    idx(0) = idx(1) = 0;
+  if (types.size () == 1)
+    {
+      idx(1) = idx(0);
+      idx(0) = 0;
+    }
+
+  return idx;
+}
+
+const jit_function&
+jit_operation::do_generate (const signature_vec& types) const
+{
+  static jit_function null_overload;
+  generated_map::const_iterator find = generated.find (&types);
+  if (find != generated.end ())
+    {
+      if (find->second)
+        return *find->second;
+      else
+        return null_overload;
+    }
+
+  jit_function *ret = generate (types);
+  generated[new signature_vec (types)] = ret;
+  return ret ? *ret : null_overload;
+}
+
+jit_function *
+jit_operation::generate (const signature_vec&) const
+{
+  return 0;
+}
+
+bool
+jit_operation::signature_cmp
+::operator() (const signature_vec *lhs, const signature_vec *rhs)
+{
+  const signature_vec& l = *lhs;
+  const signature_vec& r = *rhs;
+
+  if (l.size () < r.size ())
+    return true;
+  else if (l.size () > r.size ())
+    return false;
+
+  for (size_t i = 0; i < l.size (); ++i)
+    {
+      if (l[i]->type_id () < r[i]->type_id ())
+        return true;
+      else if (l[i]->type_id () > r[i]->type_id ())
+        return false;
+    }
+
+  return false;
+}
+
+// -------------------- jit_index_operation --------------------
+jit_function *
+jit_index_operation::generate (const signature_vec& types) const
+{
+  if (types.size () > 2 && types[0] == jit_typeinfo::get_matrix ())
+    {
+      // indexing a matrix with scalars
+      jit_type *scalar = jit_typeinfo::get_scalar ();
+      for (size_t i = 1; i < types.size (); ++i)
+        if (types[i] != scalar)
+          return 0;
+
+      return generate_matrix (types);
+    }
+
+  return 0;
+}
+
+llvm::Value *
+jit_index_operation::create_arg_array (llvm::IRBuilderD& builder,
+                                       const jit_function &fn, size_t start_idx,
+                                       size_t end_idx) const
+{
+  size_t n = end_idx - start_idx;
+  llvm::Type *scalar_t = jit_typeinfo::get_scalar_llvm ();
+  llvm::ArrayType *array_t = llvm::ArrayType::get (scalar_t, n);
+  llvm::Value *array = llvm::UndefValue::get (array_t);
+  for (size_t i = start_idx; i < end_idx; ++i)
+    {
+      llvm::Value *idx = fn.argument (builder, i);
+      array = builder.CreateInsertValue (array, idx, i - start_idx);
+    }
+
+  llvm::Value *array_mem = builder.CreateAlloca (array_t);
+  builder.CreateStore (array, array_mem);
+  return builder.CreateBitCast (array_mem, scalar_t->getPointerTo ());
+}
+
+// -------------------- jit_paren_subsref --------------------
+jit_function *
+jit_paren_subsref::generate_matrix (const signature_vec& types) const
+{
+  std::stringstream ss;
+  ss << "jit_paren_subsref_matrix_scalar" << (types.size () - 1);
+
+  jit_type *scalar = jit_typeinfo::get_scalar ();
+  jit_function *fn = new jit_function (module, jit_convention::internal,
+                                       ss.str (), scalar, types);
+  fn->mark_can_error ();
+  llvm::BasicBlock *body = fn->new_block ();
+  llvm::IRBuilder<> builder (body);
+
+  llvm::Value *array = create_arg_array (builder, *fn, 1, types.size ());
+  jit_type *index = jit_typeinfo::get_index ();
+  llvm::Value *nelem = llvm::ConstantInt::get (index->to_llvm (),
+                                               types.size () - 1);
+  llvm::Value *mat = fn->argument (builder, 0);
+  llvm::Value *ret = paren_scalar.call (builder, mat, array, nelem);
+  fn->do_return (builder, ret);
+  return fn;
+}
+
+void
+jit_paren_subsref::do_initialize (void)
+{
+  std::vector<jit_type *> types (3);
+  types[0] = jit_typeinfo::get_matrix ();
+  types[1] = jit_typeinfo::get_scalar_ptr ();
+  types[2] = jit_typeinfo::get_index ();
+
+  jit_type *scalar = jit_typeinfo::get_scalar ();
+  paren_scalar = jit_function (module, jit_convention::external,
+                               "octave_jit_paren_scalar", scalar, types);
+  paren_scalar.add_mapping (engine, &octave_jit_paren_scalar);
+  paren_scalar.mark_can_error ();
+}
+
+// -------------------- jit_paren_subsasgn --------------------
+jit_function *
+jit_paren_subsasgn::generate_matrix (const signature_vec& types) const
+{
+  std::stringstream ss;
+  ss << "jit_paren_subsasgn_matrix_scalar" << (types.size () - 2);
+
+  jit_type *matrix = jit_typeinfo::get_matrix ();
+  jit_function *fn = new jit_function (module, jit_convention::internal,
+                                       ss.str (), matrix, types);
+  fn->mark_can_error ();
+  llvm::BasicBlock *body = fn->new_block ();
+  llvm::IRBuilder<> builder (body);
+
+  llvm::Value *array = create_arg_array (builder, *fn, 1, types.size () - 1);
+  jit_type *index = jit_typeinfo::get_index ();
+  llvm::Value *nelem = llvm::ConstantInt::get (index->to_llvm (),
+                                               types.size () - 2);
+
+  llvm::Value *mat = fn->argument (builder, 0);
+  llvm::Value *value = fn->argument (builder, types.size () - 1);
+  llvm::Value *ret = paren_scalar.call (builder, mat, array, nelem, value);
+  fn->do_return (builder, ret);
+  return fn;
+}
+
+void
+jit_paren_subsasgn::do_initialize (void)
+{
+  if (paren_scalar.valid ())
+    return;
+
+  jit_type *matrix = jit_typeinfo::get_matrix ();
+  std::vector<jit_type *> types (4);
+  types[0] = matrix;
+  types[1] = jit_typeinfo::get_scalar_ptr ();
+  types[2] = jit_typeinfo::get_index ();
+  types[3] = jit_typeinfo::get_scalar ();
+
+  paren_scalar = jit_function (module, jit_convention::external,
+                               "octave_jit_paren_scalar", matrix, types);
+  paren_scalar.add_mapping (engine, &octave_jit_paren_scalar_subsasgn);
+  paren_scalar.mark_can_error ();
+}
+
+// -------------------- jit_typeinfo --------------------
+void
+jit_typeinfo::initialize (llvm::Module *m, llvm::ExecutionEngine *e)
+{
+  new jit_typeinfo (m, e);
+}
+
+// wrap function names to simplify jit_typeinfo::create_external
+#define JIT_FN(fn) engine, &fn, #fn
+
+jit_typeinfo::jit_typeinfo (llvm::Module *m, llvm::ExecutionEngine *e)
+  : module (m), engine (e), next_id (0),
+    builder (*new llvm::IRBuilderD (context))
+{
+  instance = this;
+
+  // FIXME: We should be registering types like in octave_value_typeinfo
+  llvm::Type *any_t = llvm::StructType::create (context, "octave_base_value");
+  any_t = any_t->getPointerTo ();
+
+  llvm::Type *scalar_t = llvm::Type::getDoubleTy (context);
+  llvm::Type *bool_t = llvm::Type::getInt1Ty (context);
+  llvm::Type *string_t = llvm::Type::getInt8Ty (context);
+  string_t = string_t->getPointerTo ();
+  llvm::Type *index_t = llvm::Type::getIntNTy (context,
+                                               sizeof(octave_idx_type) * 8);
+
+  llvm::StructType *range_t = llvm::StructType::create (context, "range");
+  std::vector<llvm::Type *> range_contents (4, scalar_t);
+  range_contents[3] = index_t;
+  range_t->setBody (range_contents);
+
+  llvm::Type *refcount_t = llvm::Type::getIntNTy (context, sizeof(int) * 8);
+
+  llvm::StructType *matrix_t = llvm::StructType::create (context, "matrix");
+  llvm::Type *matrix_contents[5];
+  matrix_contents[0] = refcount_t->getPointerTo ();
+  matrix_contents[1] = scalar_t->getPointerTo ();
+  matrix_contents[2] = index_t;
+  matrix_contents[3] = index_t->getPointerTo ();
+  matrix_contents[4] = string_t;
+  matrix_t->setBody (llvm::makeArrayRef (matrix_contents, 5));
+
+  llvm::Type *complex_t = llvm::ArrayType::get (scalar_t, 2);
+
+  // complex_ret is what is passed to C functions in order to get calling
+  // convention right
+  llvm::Type *cmplx_inner_cont[] = {scalar_t, scalar_t};
+  llvm::StructType *cmplx_inner = llvm::StructType::create (cmplx_inner_cont);
+
+  complex_ret = llvm::StructType::create (context, "complex_ret");
+  {
+    llvm::Type *contents[] = {cmplx_inner};
+    complex_ret->setBody (contents);
+  }
+
+  // create types
+  any = new_type ("any", 0, any_t);
+  matrix = new_type ("matrix", any, matrix_t);
+  complex = new_type ("complex", any, complex_t);
+  scalar = new_type ("scalar", complex, scalar_t);
+  scalar_ptr = new_type ("scalar_ptr", 0, scalar_t->getPointerTo ());
+  any_ptr = new_type ("any_ptr", 0, any_t->getPointerTo ());
+  range = new_type ("range", any, range_t);
+  string = new_type ("string", any, string_t);
+  boolean = new_type ("bool", any, bool_t);
+  index = new_type ("index", any, index_t);
+
+  create_int (8);
+  create_int (16);
+  create_int (32);
+  create_int (64);
+
+  casts.resize (next_id + 1);
+  identities.resize (next_id + 1);
+
+  // specify calling conventions
+  // FIXME: We should detect architecture and do something sane based on that
+  // here we assume x86 or x86_64
+  matrix->mark_sret (jit_convention::external);
+  matrix->mark_pointer_arg (jit_convention::external);
+
+  range->mark_sret (jit_convention::external);
+  range->mark_pointer_arg (jit_convention::external);
+
+  complex->set_pack (jit_convention::external, &jit_typeinfo::pack_complex);
+  complex->set_unpack (jit_convention::external, &jit_typeinfo::unpack_complex);
+  complex->set_packed_type (jit_convention::external, complex_ret);
+
+  if (sizeof (void *) == 4)
+    complex->mark_sret (jit_convention::external);
+
+  paren_subsref_fn.initialize (module, engine);
+  paren_subsasgn_fn.initialize (module, engine);
+
+  // bind global variables
+  lerror_state = new llvm::GlobalVariable (*module, bool_t, false,
+                                           llvm::GlobalValue::ExternalLinkage,
+                                           0, "error_state");
+  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);
+    any_call = create_external (JIT_FN (octave_jit_call), any, int_t, int_t,
+                                any_ptr, int_t);
+  }
+
+  // any with anything is an any op
+  jit_function fn;
+  jit_type *binary_op_type = intN (sizeof (octave_value::binary_op) * 8);
+  llvm::Type *llvm_bo_type = binary_op_type->to_llvm ();
+  jit_function any_binary = create_external (JIT_FN (octave_jit_binary_any_any),
+                                             any, binary_op_type, any, any);
+  any_binary.mark_can_error ();
+  binary_ops.resize (octave_value::num_binary_ops);
+  for (size_t i = 0; i < octave_value::num_binary_ops; ++i)
+    {
+      octave_value::binary_op op = static_cast<octave_value::binary_op> (i);
+      std::string op_name = octave_value::binary_op_as_string (op);
+      binary_ops[i].stash_name ("binary" + op_name);
+    }
+
+  unary_ops.resize (octave_value::num_unary_ops);
+  for (size_t i = 0; i < octave_value::num_unary_ops; ++i)
+    {
+      octave_value::unary_op op = static_cast<octave_value::unary_op> (i);
+      std::string op_name = octave_value::unary_op_as_string (op);
+      unary_ops[i].stash_name ("unary" + op_name);
+    }
+
+  for (int op = 0; op < octave_value::num_binary_ops; ++op)
+    {
+      llvm::Twine fn_name ("octave_jit_binary_any_any_");
+      fn_name = fn_name + llvm::Twine (op);
+
+      fn = create_internal (fn_name, any, any, any);
+      fn.mark_can_error ();
+      llvm::BasicBlock *block = fn.new_block ();
+      builder.SetInsertPoint (block);
+      llvm::APInt op_int(sizeof (octave_value::binary_op) * 8, op,
+                         std::numeric_limits<octave_value::binary_op>::is_signed);
+      llvm::Value *op_as_llvm = llvm::ConstantInt::get (llvm_bo_type, op_int);
+      llvm::Value *ret = any_binary.call (builder, op_as_llvm,
+                                          fn.argument (builder, 0),
+                                          fn.argument (builder, 1));
+      fn.do_return (builder, ret);
+      binary_ops[op].add_overload (fn);
+    }
+
+  // grab matrix
+  fn = create_external (JIT_FN (octave_jit_grab_matrix), matrix, matrix);
+  grab_fn.add_overload (fn);
+
+  grab_fn.add_overload (create_identity (scalar));
+  grab_fn.add_overload (create_identity (scalar_ptr));
+  grab_fn.add_overload (create_identity (any_ptr));
+  grab_fn.add_overload (create_identity (boolean));
+  grab_fn.add_overload (create_identity (complex));
+  grab_fn.add_overload (create_identity (index));
+
+  // release any
+  fn = create_external (JIT_FN (octave_jit_release_any), 0, any);
+  release_fn.add_overload (fn);
+  release_fn.stash_name ("release");
+
+  // release matrix
+  fn = create_external (JIT_FN (octave_jit_release_matrix), 0, matrix);
+  release_fn.add_overload (fn);
+
+  // destroy
+  destroy_fn = release_fn;
+  destroy_fn.stash_name ("destroy");
+  destroy_fn.add_overload (create_identity(scalar));
+  destroy_fn.add_overload (create_identity(boolean));
+  destroy_fn.add_overload (create_identity(index));
+  destroy_fn.add_overload (create_identity(complex));
+
+  // now for binary scalar operations
+  add_binary_op (scalar, octave_value::op_add, llvm::Instruction::FAdd);
+  add_binary_op (scalar, octave_value::op_sub, llvm::Instruction::FSub);
+  add_binary_op (scalar, octave_value::op_mul, llvm::Instruction::FMul);
+  add_binary_op (scalar, octave_value::op_el_mul, llvm::Instruction::FMul);
+
+  add_binary_fcmp (scalar, octave_value::op_lt, llvm::CmpInst::FCMP_ULT);
+  add_binary_fcmp (scalar, octave_value::op_le, llvm::CmpInst::FCMP_ULE);
+  add_binary_fcmp (scalar, octave_value::op_eq, llvm::CmpInst::FCMP_UEQ);
+  add_binary_fcmp (scalar, octave_value::op_ge, llvm::CmpInst::FCMP_UGE);
+  add_binary_fcmp (scalar, octave_value::op_gt, llvm::CmpInst::FCMP_UGT);
+  add_binary_fcmp (scalar, octave_value::op_ne, llvm::CmpInst::FCMP_UNE);
+
+  jit_function gripe_div0 = create_external (JIT_FN (gripe_divide_by_zero), 0);
+  gripe_div0.mark_can_error ();
+
+  // divide is annoying because it might error
+  fn = create_internal ("octave_jit_div_scalar_scalar", scalar, scalar, scalar);
+  fn.mark_can_error ();
+
+  llvm::BasicBlock *body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::BasicBlock *warn_block = fn.new_block ("warn");
+    llvm::BasicBlock *normal_block = fn.new_block ("normal");
+
+    llvm::Value *zero = llvm::ConstantFP::get (scalar_t, 0);
+    llvm::Value *check = builder.CreateFCmpUEQ (zero, fn.argument (builder, 1));
+    builder.CreateCondBr (check, warn_block, normal_block);
+
+    builder.SetInsertPoint (warn_block);
+    gripe_div0.call (builder);
+    builder.CreateBr (normal_block);
+
+    builder.SetInsertPoint (normal_block);
+    llvm::Value *ret = builder.CreateFDiv (fn.argument (builder, 0),
+                                           fn.argument (builder, 1));
+    fn.do_return (builder, ret);
+  }
+  binary_ops[octave_value::op_div].add_overload (fn);
+  binary_ops[octave_value::op_el_div].add_overload (fn);
+
+  // ldiv is the same as div with the operators reversed
+  fn = mirror_binary (fn);
+  binary_ops[octave_value::op_ldiv].add_overload (fn);
+  binary_ops[octave_value::op_el_ldiv].add_overload (fn);
+
+  // In general, the result of scalar ^ scalar is a complex number. We might be
+  // able to improve on this if we keep track of the range of values varaibles
+  // can take on.
+  fn = create_external (JIT_FN (octave_jit_pow_scalar_scalar), complex, scalar,
+                        scalar);
+  binary_ops[octave_value::op_pow].add_overload (fn);
+  binary_ops[octave_value::op_el_pow].add_overload (fn);
+
+  // now for unary scalar operations
+  // FIXME: Impelment not
+  fn = create_internal ("octave_jit_++", scalar, scalar);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *one = llvm::ConstantFP::get (scalar_t, 1);
+    llvm::Value *val = fn.argument (builder, 0);
+    val = builder.CreateFAdd (val, one);
+    fn.do_return (builder, val);
+  }
+  unary_ops[octave_value::op_incr].add_overload (fn);
+
+  fn = create_internal ("octave_jit_--", scalar, scalar);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *one = llvm::ConstantFP::get (scalar_t, 1);
+    llvm::Value *val = fn.argument (builder, 0);
+    val = builder.CreateFSub (val, one);
+    fn.do_return (builder, val);
+  }
+  unary_ops[octave_value::op_decr].add_overload (fn);
+
+  fn = create_internal ("octave_jit_uminus", scalar, scalar);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *mone = llvm::ConstantFP::get (scalar_t, -1);
+    llvm::Value *val = fn.argument (builder, 0);
+    val = builder.CreateFMul (val, mone);
+    fn.do_return (builder, val);
+  }
+
+  fn = create_identity (scalar);
+  unary_ops[octave_value::op_uplus].add_overload (fn);
+  unary_ops[octave_value::op_transpose].add_overload (fn);
+  unary_ops[octave_value::op_hermitian].add_overload (fn);
+
+  // now for binary complex operations
+  fn = create_internal ("octave_jit_+_complex_complex", complex, complex,
+                        complex);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *lhs = fn.argument (builder, 0);
+    llvm::Value *rhs = fn.argument (builder, 1);
+    llvm::Value *real = builder.CreateFAdd (complex_real (lhs),
+                                            complex_real (rhs));
+    llvm::Value *imag = builder.CreateFAdd (complex_imag (lhs),
+                                            complex_imag (rhs));
+    fn.do_return (builder, complex_new (real, imag));
+  }
+  binary_ops[octave_value::op_add].add_overload (fn);
+
+  fn = create_internal ("octave_jit_-_complex_complex", complex, complex,
+                        complex);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *lhs = fn.argument (builder, 0);
+    llvm::Value *rhs = fn.argument (builder, 1);
+    llvm::Value *real = builder.CreateFSub (complex_real (lhs),
+                                            complex_real (rhs));
+    llvm::Value *imag = builder.CreateFSub (complex_imag (lhs),
+                                            complex_imag (rhs));
+    fn.do_return (builder, complex_new (real, imag));
+  }
+  binary_ops[octave_value::op_sub].add_overload (fn);
+
+  fn = create_external (JIT_FN (octave_jit_complex_mul),
+                        complex, complex, complex);
+  binary_ops[octave_value::op_mul].add_overload (fn);
+  binary_ops[octave_value::op_el_mul].add_overload (fn);
+
+  jit_function complex_div = create_external (JIT_FN (octave_jit_complex_div),
+                                              complex, complex, complex);
+  complex_div.mark_can_error ();
+  binary_ops[octave_value::op_div].add_overload (fn);
+  binary_ops[octave_value::op_ldiv].add_overload (fn);
+
+  fn = create_external (JIT_FN (octave_jit_pow_complex_complex), complex,
+                        complex, complex);
+  binary_ops[octave_value::op_pow].add_overload (fn);
+  binary_ops[octave_value::op_el_pow].add_overload (fn);
+
+  fn = create_internal ("octave_jit_*_scalar_complex", complex, scalar,
+                        complex);
+  jit_function mul_scalar_complex = fn;
+  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 *rhs = fn.argument (builder, 1);
+
+    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 (builder.CreateFMul (lhs, complex_real (rhs)),
+                        builder.CreateFMul (lhs, complex_imag (rhs)));
+    fn.do_return (builder, temp);
+  }
+  binary_ops[octave_value::op_mul].add_overload (fn);
+  binary_ops[octave_value::op_el_mul].add_overload (fn);
+
+
+  fn = mirror_binary (mul_scalar_complex);
+  binary_ops[octave_value::op_mul].add_overload (fn);
+  binary_ops[octave_value::op_el_mul].add_overload (fn);
+
+  fn = create_internal ("octave_jit_+_scalar_complex", complex, scalar,
+                        complex);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *lhs = fn.argument (builder, 0);
+    llvm::Value *rhs = fn.argument (builder, 1);
+    llvm::Value *real = builder.CreateFAdd (lhs, complex_real (rhs));
+    fn.do_return (builder, complex_real (rhs, real));
+  }
+  binary_ops[octave_value::op_add].add_overload (fn);
+
+  fn = mirror_binary (fn);
+  binary_ops[octave_value::op_add].add_overload (fn);
+
+  fn = create_internal ("octave_jit_-_complex_scalar", complex, complex,
+                        scalar);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *lhs = fn.argument (builder, 0);
+    llvm::Value *rhs = fn.argument (builder, 1);
+    llvm::Value *real = builder.CreateFSub (complex_real (lhs), rhs);
+    fn.do_return (builder, complex_real (lhs, real));
+  }
+  binary_ops[octave_value::op_sub].add_overload (fn);
+
+  fn = create_internal ("octave_jit_-_scalar_complex", complex, scalar,
+                        complex);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *lhs = fn.argument (builder, 0);
+    llvm::Value *rhs = fn.argument (builder, 1);
+    llvm::Value *real = builder.CreateFSub (lhs, complex_real (rhs));
+    fn.do_return (builder, complex_real (rhs, real));
+  }
+  binary_ops[octave_value::op_sub].add_overload (fn);
+
+  fn = create_external (JIT_FN (octave_jit_pow_scalar_complex), complex, scalar,
+                        complex);
+  binary_ops[octave_value::op_pow].add_overload (fn);
+  binary_ops[octave_value::op_el_pow].add_overload (fn);
+
+  fn = create_external (JIT_FN (octave_jit_pow_complex_scalar), complex,
+                        complex, scalar);
+  binary_ops[octave_value::op_pow].add_overload (fn);
+  binary_ops[octave_value::op_el_pow].add_overload (fn);
+
+  // now for binary index operators
+  add_binary_op (index, octave_value::op_add, llvm::Instruction::Add);
+
+  // and binary bool operators
+  add_binary_op (boolean, octave_value::op_el_or, llvm::Instruction::Or);
+  add_binary_op (boolean, octave_value::op_el_and, llvm::Instruction::And);
+
+  // now for printing functions
+  print_fn.stash_name ("print");
+  add_print (any, reinterpret_cast<void *> (&octave_jit_print_any));
+  add_print (scalar, reinterpret_cast<void *> (&octave_jit_print_scalar));
+
+  // initialize for loop
+  for_init_fn.stash_name ("for_init");
+
+  fn = create_internal ("octave_jit_for_range_init", index, range);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *zero = llvm::ConstantInt::get (index_t, 0);
+    fn.do_return (builder, zero);
+  }
+  for_init_fn.add_overload (fn);
+
+  // bounds check for for loop
+  for_check_fn.stash_name ("for_check");
+
+  fn = create_internal ("octave_jit_for_range_check", boolean, range, index);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *nelem
+      = builder.CreateExtractValue (fn.argument (builder, 0), 3);
+    llvm::Value *idx = fn.argument (builder, 1);
+    llvm::Value *ret = builder.CreateICmpULT (idx, nelem);
+    fn.do_return (builder, ret);
+  }
+  for_check_fn.add_overload (fn);
+
+  // index variabe for for loop
+  for_index_fn.stash_name ("for_index");
+
+  fn = create_internal ("octave_jit_for_range_idx", scalar, range, index);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *idx = fn.argument (builder, 1);
+    llvm::Value *didx = builder.CreateSIToFP (idx, scalar_t);
+    llvm::Value *rng = fn.argument (builder, 0);
+    llvm::Value *base = builder.CreateExtractValue (rng, 0);
+    llvm::Value *inc = builder.CreateExtractValue (rng, 2);
+
+    llvm::Value *ret = builder.CreateFMul (didx, inc);
+    ret = builder.CreateFAdd (base, ret);
+    fn.do_return (builder, ret);
+  }
+  for_index_fn.add_overload (fn);
+
+  // logically true
+  logically_true_fn.stash_name ("logically_true");
+
+  jit_function gripe_nantl
+    = create_external (JIT_FN (octave_jit_gripe_nan_to_logical_conversion), 0);
+  gripe_nantl.mark_can_error ();
+
+  fn = create_internal ("octave_jit_logically_true_scalar", boolean, scalar);
+  fn.mark_can_error ();
+
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::BasicBlock *error_block = fn.new_block ("error");
+    llvm::BasicBlock *normal_block = fn.new_block ("normal");
+
+    llvm::Value *check = builder.CreateFCmpUNE (fn.argument (builder, 0),
+                                                fn.argument (builder, 0));
+    builder.CreateCondBr (check, error_block, normal_block);
+
+    builder.SetInsertPoint (error_block);
+    gripe_nantl.call (builder);
+    builder.CreateBr (normal_block);
+    builder.SetInsertPoint (normal_block);
+
+    llvm::Value *zero = llvm::ConstantFP::get (scalar_t, 0);
+    llvm::Value *ret = builder.CreateFCmpONE (fn.argument (builder, 0), zero);
+    fn.do_return (builder, ret);
+  }
+  logically_true_fn.add_overload (fn);
+
+  // logically_true boolean
+  fn = create_identity (boolean);
+  logically_true_fn.add_overload (fn);
+
+  // make_range
+  // FIXME: May be benificial to implement all in LLVM
+  make_range_fn.stash_name ("make_range");
+  jit_function compute_nelem
+    = create_external (JIT_FN (octave_jit_compute_nelem),
+                       index, scalar, scalar, scalar);
+
+
+  fn = create_internal ("octave_jit_make_range", range, scalar, scalar, scalar);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *base = fn.argument (builder, 0);
+    llvm::Value *limit = fn.argument (builder, 1);
+    llvm::Value *inc = fn.argument (builder, 2);
+    llvm::Value *nelem = compute_nelem.call (builder, base, limit, inc);
+
+    llvm::Value *dzero = llvm::ConstantFP::get (scalar_t, 0);
+    llvm::Value *izero = llvm::ConstantInt::get (index_t, 0);
+    llvm::Value *rng = llvm::ConstantStruct::get (range_t, dzero, dzero, dzero,
+                                                  izero, NULL);
+    rng = builder.CreateInsertValue (rng, base, 0);
+    rng = builder.CreateInsertValue (rng, limit, 1);
+    rng = builder.CreateInsertValue (rng, inc, 2);
+    rng = builder.CreateInsertValue (rng, nelem, 3);
+    fn.do_return (builder, rng);
+  }
+  make_range_fn.add_overload (fn);
+
+  // paren_subsref
+  jit_type *jit_int = intN (sizeof (int) * 8);
+  llvm::Type *int_t = jit_int->to_llvm ();
+  jit_function ginvalid_index
+    = create_external (JIT_FN (octave_jit_ginvalid_index), 0);
+  jit_function gindex_range = create_external (JIT_FN (octave_jit_gindex_range),
+                                               0, jit_int, jit_int, index,
+                                               index);
+
+  fn = create_internal ("()subsref", scalar, matrix, scalar);
+  fn.mark_can_error ();
+
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *one = llvm::ConstantInt::get (index_t, 1);
+    llvm::Value *ione;
+    if (index_t == int_t)
+      ione = one;
+    else
+      ione = llvm::ConstantInt::get (int_t, 1);
+
+    llvm::Value *undef = llvm::UndefValue::get (scalar_t);
+    llvm::Value *mat = fn.argument (builder, 0);
+    llvm::Value *idx = fn.argument (builder, 1);
+
+    // convert index to scalar to integer, and check index >= 1
+    llvm::Value *int_idx = builder.CreateFPToSI (idx, index_t);
+    llvm::Value *check_idx = builder.CreateSIToFP (int_idx, scalar_t);
+    llvm::Value *cond0 = builder.CreateFCmpUNE (idx, check_idx);
+    llvm::Value *cond1 = builder.CreateICmpSLT (int_idx, one);
+    llvm::Value *cond = builder.CreateOr (cond0, cond1);
+
+    llvm::BasicBlock *done = fn.new_block ("done");
+    llvm::BasicBlock *conv_error = fn.new_block ("conv_error", done);
+    llvm::BasicBlock *normal = fn.new_block ("normal", done);
+    builder.CreateCondBr (cond, conv_error, normal);
+
+    builder.SetInsertPoint (conv_error);
+    ginvalid_index.call (builder);
+    builder.CreateBr (done);
+
+    builder.SetInsertPoint (normal);
+    llvm::Value *len = builder.CreateExtractValue (mat,
+                                                   llvm::ArrayRef<unsigned> (2));
+    cond = builder.CreateICmpSGT (int_idx, len);
+
+
+    llvm::BasicBlock *bounds_error = fn.new_block ("bounds_error", done);
+    llvm::BasicBlock *success = fn.new_block ("success", done);
+    builder.CreateCondBr (cond, bounds_error, success);
+
+    builder.SetInsertPoint (bounds_error);
+    gindex_range.call (builder, ione, ione, int_idx, len);
+    builder.CreateBr (done);
+
+    builder.SetInsertPoint (success);
+    llvm::Value *data = builder.CreateExtractValue (mat,
+                                                    llvm::ArrayRef<unsigned> (1));
+    llvm::Value *gep = builder.CreateInBoundsGEP (data, int_idx);
+    llvm::Value *ret = builder.CreateLoad (gep);
+    builder.CreateBr (done);
+
+    builder.SetInsertPoint (done);
+
+    llvm::PHINode *merge = llvm::PHINode::Create (scalar_t, 3);
+    builder.Insert (merge);
+    merge->addIncoming (undef, conv_error);
+    merge->addIncoming (undef, bounds_error);
+    merge->addIncoming (ret, success);
+    fn.do_return (builder, merge);
+  }
+  paren_subsref_fn.add_overload (fn);
+
+  // paren subsasgn
+  paren_subsasgn_fn.stash_name ("()subsasgn");
+
+  jit_function resize_paren_subsasgn
+    = create_external (JIT_FN (octave_jit_paren_subsasgn_impl), matrix, matrix,
+                       index, scalar);
+
+  fn = create_internal ("octave_jit_paren_subsasgn", matrix, matrix, scalar,
+                        scalar);
+  fn.mark_can_error ();
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *one = llvm::ConstantInt::get (index_t, 1);
+
+    llvm::Value *mat = fn.argument (builder, 0);
+    llvm::Value *idx = fn.argument (builder, 1);
+    llvm::Value *value = fn.argument (builder, 2);
+
+    llvm::Value *int_idx = builder.CreateFPToSI (idx, index_t);
+    llvm::Value *check_idx = builder.CreateSIToFP (int_idx, scalar_t);
+    llvm::Value *cond0 = builder.CreateFCmpUNE (idx, check_idx);
+    llvm::Value *cond1 = builder.CreateICmpSLT (int_idx, one);
+    llvm::Value *cond = builder.CreateOr (cond0, cond1);
+
+    llvm::BasicBlock *done = fn.new_block ("done");
+
+    llvm::BasicBlock *conv_error = fn.new_block ("conv_error", done);
+    llvm::BasicBlock *normal = fn.new_block ("normal", done);
+    builder.CreateCondBr (cond, conv_error, normal);
+    builder.SetInsertPoint (conv_error);
+    ginvalid_index.call (builder);
+    builder.CreateBr (done);
+
+    builder.SetInsertPoint (normal);
+    llvm::Value *len = builder.CreateExtractValue (mat, 2);
+    cond0 = builder.CreateICmpSGT (int_idx, len);
+
+    llvm::Value *rcount = builder.CreateExtractValue (mat, 0);
+    rcount = builder.CreateLoad (rcount);
+    cond1 = builder.CreateICmpSGT (rcount, one);
+    cond = builder.CreateOr (cond0, cond1);
+
+    llvm::BasicBlock *bounds_error = fn.new_block ("bounds_error", done);
+    llvm::BasicBlock *success = fn.new_block ("success", done);
+    builder.CreateCondBr (cond, bounds_error, success);
+
+    // resize on out of bounds access
+    builder.SetInsertPoint (bounds_error);
+    llvm::Value *resize_result = resize_paren_subsasgn.call (builder, mat,
+                                                             int_idx, value);
+    builder.CreateBr (done);
+
+    builder.SetInsertPoint (success);
+    llvm::Value *data = builder.CreateExtractValue (mat,
+                                                    llvm::ArrayRef<unsigned> (1));
+    llvm::Value *gep = builder.CreateInBoundsGEP (data, int_idx);
+    builder.CreateStore (value, gep);
+    builder.CreateBr (done);
+
+    builder.SetInsertPoint (done);
+
+    llvm::PHINode *merge = llvm::PHINode::Create (matrix_t, 3);
+    builder.Insert (merge);
+    merge->addIncoming (mat, conv_error);
+    merge->addIncoming (resize_result, bounds_error);
+    merge->addIncoming (mat, success);
+    fn.do_return (builder, merge);
+  }
+  paren_subsasgn_fn.add_overload (fn);
+
+  fn = create_external (JIT_FN (octave_jit_paren_subsasgn_matrix_range), matrix,
+                        matrix, range, scalar);
+  fn.mark_can_error ();
+  paren_subsasgn_fn.add_overload (fn);
+
+  end1_fn.stash_name ("end1");
+  fn = create_internal ("octave_jit_end1_matrix", scalar, matrix, index, index);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *mat = fn.argument (builder, 0);
+    llvm::Value *ret = builder.CreateExtractValue (mat, 2);
+    fn.do_return (builder, builder.CreateSIToFP (ret, scalar_t));
+  }
+  end1_fn.add_overload (fn);
+
+  end_fn.stash_name ("end");
+  fn = create_external (JIT_FN (octave_jit_end_matrix),scalar, matrix, index,
+                        index);
+  end_fn.add_overload (fn);
+
+  // -------------------- create_undef --------------------
+  create_undef_fn.stash_name ("create_undef");
+  fn = create_external (JIT_FN (octave_jit_create_undef), any);
+  create_undef_fn.add_overload (fn);
+
+  casts[any->type_id ()].stash_name ("(any)");
+  casts[scalar->type_id ()].stash_name ("(scalar)");
+  casts[complex->type_id ()].stash_name ("(complex)");
+  casts[matrix->type_id ()].stash_name ("(matrix)");
+  casts[range->type_id ()].stash_name ("(range)");
+
+  // cast any <- matrix
+  fn = create_external (JIT_FN (octave_jit_cast_any_matrix), any, matrix);
+  casts[any->type_id ()].add_overload (fn);
+
+  // cast matrix <- any
+  fn = create_external (JIT_FN (octave_jit_cast_matrix_any), matrix, any);
+  casts[matrix->type_id ()].add_overload (fn);
+
+  // cast any <- range
+  fn = create_external (JIT_FN (octave_jit_cast_any_range), any, range);
+  casts[any->type_id ()].add_overload (fn);
+
+  // cast range <- any
+  fn = create_external (JIT_FN (octave_jit_cast_range_any), range, any);
+  casts[range->type_id ()].add_overload (fn);
+
+  // cast any <- scalar
+  fn = create_external (JIT_FN (octave_jit_cast_any_scalar), any, scalar);
+  casts[any->type_id ()].add_overload (fn);
+
+  // cast scalar <- any
+  fn = create_external (JIT_FN (octave_jit_cast_scalar_any), scalar, any);
+  casts[scalar->type_id ()].add_overload (fn);
+
+  // cast any <- complex
+  fn = create_external (JIT_FN (octave_jit_cast_any_complex), any, complex);
+  casts[any->type_id ()].add_overload (fn);
+
+  // cast complex <- any
+  fn = create_external (JIT_FN (octave_jit_cast_complex_any), complex, any);
+  casts[complex->type_id ()].add_overload (fn);
+
+  // cast complex <- scalar
+  fn = create_internal ("octave_jit_cast_complex_scalar", complex, scalar);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  {
+    llvm::Value *zero = llvm::ConstantFP::get (scalar_t, 0);
+    fn.do_return (builder, complex_new (fn.argument (builder, 0), zero));
+  }
+  casts[complex->type_id ()].add_overload (fn);
+
+  // cast scalar <- complex
+  fn = create_internal ("octave_jit_cast_scalar_complex", scalar, complex);
+  body = fn.new_block ();
+  builder.SetInsertPoint (body);
+  fn.do_return (builder, complex_real (fn.argument (builder, 0)));
+  casts[scalar->type_id ()].add_overload (fn);
+
+  // cast any <- any
+  fn = create_identity (any);
+  casts[any->type_id ()].add_overload (fn);
+
+  // cast scalar <- scalar
+  fn = create_identity (scalar);
+  casts[scalar->type_id ()].add_overload (fn);
+
+  // cast complex <- complex
+  fn = create_identity (complex);
+  casts[complex->type_id ()].add_overload (fn);
+
+  // -------------------- builtin functions --------------------
+  add_builtin ("#unknown_function");
+  unknown_function = builtins["#unknown_function"];
+
+  add_builtin ("sin");
+  register_intrinsic ("sin", llvm::Intrinsic::sin, scalar, scalar);
+  register_generic ("sin", matrix, matrix);
+
+  add_builtin ("cos");
+  register_intrinsic ("cos", llvm::Intrinsic::cos, scalar, scalar);
+  register_generic ("cos", matrix, matrix);
+
+  add_builtin ("exp");
+  register_intrinsic ("exp", llvm::Intrinsic::cos, scalar, scalar);
+  register_generic ("exp", matrix, matrix);
+
+  add_builtin ("balance");
+  register_generic ("balance", matrix, matrix);
+
+  add_builtin ("cond");
+  register_generic ("cond", scalar, matrix);
+
+  add_builtin ("det");
+  register_generic ("det", scalar, matrix);
+
+  add_builtin ("norm");
+  register_generic ("norm", scalar, matrix);
+
+  add_builtin ("rand");
+  register_generic ("rand", matrix, scalar);
+  register_generic ("rand", matrix, std::vector<jit_type *> (2, scalar));
+
+  add_builtin ("magic");
+  register_generic ("magic", matrix, scalar);
+  register_generic ("magic", matrix, std::vector<jit_type *> (2, scalar));
+
+  add_builtin ("eye");
+  register_generic ("eye", matrix, scalar);
+  register_generic ("eye", matrix, std::vector<jit_type *> (2, scalar));
+
+  add_builtin ("mod");
+  register_generic ("mod", scalar, std::vector<jit_type *> (2, scalar));
+
+  casts.resize (next_id + 1);
+  jit_function any_id = create_identity (any);
+  jit_function grab_any = create_external (JIT_FN (octave_jit_grab_any),
+                                           any, any);
+  jit_function release_any = get_release (any);
+  std::vector<jit_type *> args;
+  args.resize (1);
+
+  for (std::map<std::string, jit_type *>::iterator iter = builtins.begin ();
+       iter != builtins.end (); ++iter)
+    {
+      jit_type *btype = iter->second;
+      args[0] = btype;
+
+      grab_fn.add_overload (jit_function (grab_any, btype, args));
+      release_fn.add_overload (jit_function (release_any, 0, args));
+      casts[any->type_id ()].add_overload (jit_function (any_id, any, args));
+
+      args[0] = any;
+      casts[btype->type_id ()].add_overload (jit_function (any_id, btype,
+                                                           args));
+    }
+}
+
+const jit_function&
+jit_typeinfo::do_end (jit_value *value, jit_value *idx, jit_value *count)
+{
+  jit_const_index *ccount = dynamic_cast<jit_const_index *> (count);
+  if (ccount && ccount->value () == 1)
+    return end1_fn.overload (value->type (), idx->type (), count->type ());
+
+  return end_fn.overload (value->type (), idx->type (), count->type ());
+}
+
+jit_type*
+jit_typeinfo::new_type (const std::string& name, jit_type *parent,
+                        llvm::Type *llvm_type, bool skip_paren)
+{
+  jit_type *ret = new jit_type (name, parent, llvm_type, skip_paren, next_id++);
+  id_to_type.push_back (ret);
+  return ret;
+}
+
+void
+jit_typeinfo::add_print (jit_type *ty, void *fptr)
+{
+  std::stringstream name;
+  name << "octave_jit_print_" << ty->name ();
+  jit_function fn = create_external (engine, fptr, name.str (), 0, intN (8), ty);
+  print_fn.add_overload (fn);
+}
+
+// FIXME: cp between add_binary_op, add_binary_icmp, and add_binary_fcmp
+void
+jit_typeinfo::add_binary_op (jit_type *ty, int op, int llvm_op)
+{
+  std::stringstream fname;
+  octave_value::binary_op ov_op = static_cast<octave_value::binary_op>(op);
+  fname << "octave_jit_" << octave_value::binary_op_as_string (ov_op)
+        << "_" << ty->name ();
+
+  jit_function fn = create_internal (fname.str (), ty, ty, ty);
+  llvm::BasicBlock *block = fn.new_block ();
+  builder.SetInsertPoint (block);
+  llvm::Instruction::BinaryOps temp
+    = static_cast<llvm::Instruction::BinaryOps>(llvm_op);
+
+  llvm::Value *ret = builder.CreateBinOp (temp, fn.argument (builder, 0),
+                                          fn.argument (builder, 1));
+  fn.do_return (builder, ret);
+  binary_ops[op].add_overload (fn);
+}
+
+void
+jit_typeinfo::add_binary_icmp (jit_type *ty, int op, int llvm_op)
+{
+  std::stringstream fname;
+  octave_value::binary_op ov_op = static_cast<octave_value::binary_op>(op);
+  fname << "octave_jit" << octave_value::binary_op_as_string (ov_op)
+        << "_" << ty->name ();
+
+  jit_function fn = create_internal (fname.str (), boolean, ty, ty);
+  llvm::BasicBlock *block = fn.new_block ();
+  builder.SetInsertPoint (block);
+  llvm::CmpInst::Predicate temp
+    = static_cast<llvm::CmpInst::Predicate>(llvm_op);
+  llvm::Value *ret = builder.CreateICmp (temp, fn.argument (builder, 0),
+                                         fn.argument (builder, 1));
+  fn.do_return (builder, ret);
+  binary_ops[op].add_overload (fn);
+}
+
+void
+jit_typeinfo::add_binary_fcmp (jit_type *ty, int op, int llvm_op)
+{
+  std::stringstream fname;
+  octave_value::binary_op ov_op = static_cast<octave_value::binary_op>(op);
+  fname << "octave_jit" << octave_value::binary_op_as_string (ov_op)
+        << "_" << ty->name ();
+
+  jit_function fn = create_internal (fname.str (), boolean, ty, ty);
+  llvm::BasicBlock *block = fn.new_block ();
+  builder.SetInsertPoint (block);
+  llvm::CmpInst::Predicate temp
+    = static_cast<llvm::CmpInst::Predicate>(llvm_op);
+  llvm::Value *ret = builder.CreateFCmp (temp, fn.argument (builder, 0),
+                                         fn.argument (builder, 1));
+  fn.do_return (builder, ret);
+  binary_ops[op].add_overload (fn);
+}
+
+jit_function
+jit_typeinfo::create_function (jit_convention::type cc, const llvm::Twine& name,
+                               jit_type *ret,
+                               const std::vector<jit_type *>& args)
+{
+  jit_function result (module, cc, name, ret, args);
+  return result;
+}
+
+jit_function
+jit_typeinfo::create_identity (jit_type *type)
+{
+  size_t id = type->type_id ();
+  if (id >= identities.size ())
+    identities.resize (id + 1);
+
+  if (! identities[id].valid ())
+    {
+      std::stringstream name;
+      name << "id_" << type->name ();
+
+      jit_function fn = create_internal (name.str (), type, type);
+      llvm::BasicBlock *body = fn.new_block ();
+      builder.SetInsertPoint (body);
+      fn.do_return (builder, fn.argument (builder, 0));
+      return identities[id] = fn;
+    }
+
+  return identities[id];
+}
+
+llvm::Value *
+jit_typeinfo::do_insert_error_check (llvm::IRBuilderD& abuilder)
+{
+  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)
+{
+  jit_type *btype = new_type (name, any, any->to_llvm (), true);
+  builtins[name] = btype;
+
+  octave_builtin *ov_builtin = find_builtin (name);
+  if (ov_builtin)
+    ov_builtin->stash_jit (*btype);
+}
+
+void
+jit_typeinfo::register_intrinsic (const std::string& name, size_t iid,
+                                  jit_type *result,
+                                  const std::vector<jit_type *>& args)
+{
+  jit_type *builtin_type = builtins[name];
+  size_t nargs = args.size ();
+  llvm::SmallVector<llvm::Type *, 5> llvm_args (nargs);
+  for (size_t i = 0; i < nargs; ++i)
+    llvm_args[i] = args[i]->to_llvm ();
+
+  llvm::Intrinsic::ID id = static_cast<llvm::Intrinsic::ID> (iid);
+  llvm::Function *ifun = llvm::Intrinsic::getDeclaration (module, id,
+                                                          llvm_args);
+  std::stringstream fn_name;
+  fn_name << "octave_jit_" << name;
+
+  std::vector<jit_type *> args1 (nargs + 1);
+  args1[0] = builtin_type;
+  std::copy (args.begin (), args.end (), args1.begin () + 1);
+
+  // The first argument will be the Octave function, but we already know that
+  // the function call is the equivalent of the intrinsic, so we ignore it and
+  // call the intrinsic with the remaining arguments.
+  jit_function fn = create_internal (fn_name.str (), result, args1);
+  llvm::BasicBlock *body = fn.new_block ();
+  builder.SetInsertPoint (body);
+
+  llvm::SmallVector<llvm::Value *, 5> fargs (nargs);
+  for (size_t i = 0; i < nargs; ++i)
+    fargs[i] = fn.argument (builder, i + 1);
+
+  llvm::Value *ret = builder.CreateCall (ifun, fargs);
+  fn.do_return (builder, ret);
+  paren_subsref_fn.add_overload (fn);
+}
+
+octave_builtin *
+jit_typeinfo::find_builtin (const std::string& name)
+{
+  // FIXME: Finalize what we want to store in octave_builtin, then add functions
+  // to access these values in octave_value
+  octave_value ov_builtin = symbol_table::find (name);
+  return dynamic_cast<octave_builtin *> (ov_builtin.internal_rep ());
+}
+
+void
+jit_typeinfo::register_generic (const std::string& name, jit_type *result,
+                                const std::vector<jit_type *>& args)
+{
+  octave_builtin *builtin = find_builtin (name);
+  if (! builtin)
+    return;
+
+  std::vector<jit_type *> fn_args (args.size () + 1);
+  fn_args[0] = builtins[name];
+  std::copy (args.begin (), args.end (), fn_args.begin () + 1);
+  jit_function fn = create_internal (name, result, fn_args);
+  fn.mark_can_error ();
+  llvm::BasicBlock *block = fn.new_block ();
+  builder.SetInsertPoint (block);
+  llvm::Type *any_t = any->to_llvm ();
+  llvm::ArrayType *array_t = llvm::ArrayType::get (any_t, args.size ());
+  llvm::Value *array = llvm::UndefValue::get (array_t);
+  for (size_t i = 0; i < args.size (); ++i)
+    {
+      llvm::Value *arg = fn.argument (builder, i + 1);
+      jit_function agrab = get_grab (args[i]);
+      if (agrab.valid ())
+        arg = agrab.call (builder, arg);
+      jit_function acast = cast (any, args[i]);
+      array = builder.CreateInsertValue (array, acast.call (builder, arg), i);
+    }
+
+  llvm::Value *array_mem = builder.CreateAlloca (array_t);
+  builder.CreateStore (array, array_mem);
+  array = builder.CreateBitCast (array_mem, any_t->getPointerTo ());
+
+  jit_type *jintTy = intN (sizeof (octave_builtin::fcn) * 8);
+  llvm::Type *intTy = jintTy->to_llvm ();
+  size_t fcn_int = reinterpret_cast<size_t> (builtin->function ());
+  llvm::Value *fcn = llvm::ConstantInt::get (intTy, fcn_int);
+  llvm::Value *nargin = llvm::ConstantInt::get (intTy, args.size ());
+  size_t result_int = reinterpret_cast<size_t> (result);
+  llvm::Value *res_llvm = llvm::ConstantInt::get (intTy, result_int);
+  llvm::Value *ret = any_call.call (builder, fcn, nargin, array, res_llvm);
+
+  jit_function cast_result = cast (result, any);
+  fn.do_return (builder, cast_result.call (builder, ret));
+  paren_subsref_fn.add_overload (fn);
+}
+
+jit_function
+jit_typeinfo::mirror_binary (const jit_function& fn)
+{
+  jit_function ret = create_internal (fn.name () + "_reverse",
+                                      fn.result (), fn.argument_type (1),
+                                      fn.argument_type (0));
+  if (fn.can_error ())
+    ret.mark_can_error ();
+
+  llvm::BasicBlock *body = ret.new_block ();
+  builder.SetInsertPoint (body);
+  llvm::Value *result = fn.call (builder, ret.argument (builder, 1),
+                                 ret.argument (builder, 0));
+  if (ret.result ())
+    ret.do_return (builder, result);
+  else
+    ret.do_return (builder);
+
+  return ret;
+}
+
+llvm::Value *
+jit_typeinfo::pack_complex (llvm::IRBuilderD& bld, llvm::Value *cplx)
+{
+  llvm::Type *complex_ret = instance->complex_ret;
+  llvm::Value *real = bld.CreateExtractValue (cplx, 0);
+  llvm::Value *imag = bld.CreateExtractValue (cplx, 1);
+  llvm::Value *ret = llvm::UndefValue::get (complex_ret);
+
+  unsigned int re_idx[] = {0, 0};
+  unsigned int im_idx[] = {0, 1};
+  ret = bld.CreateInsertValue (ret, real, re_idx);
+  return bld.CreateInsertValue (ret, imag, im_idx);
+}
+
+llvm::Value *
+jit_typeinfo::unpack_complex (llvm::IRBuilderD& bld, llvm::Value *result)
+{
+  unsigned int re_idx[] = {0, 0};
+  unsigned int im_idx[] = {0, 1};
+
+  llvm::Type *complex_t = get_complex ()->to_llvm ();
+  llvm::Value *real = bld.CreateExtractValue (result, re_idx);
+  llvm::Value *imag = bld.CreateExtractValue (result, im_idx);
+  llvm::Value *ret = llvm::UndefValue::get (complex_t);
+
+  ret = bld.CreateInsertValue (ret, real, 0);
+  return bld.CreateInsertValue (ret, imag, 1);
+}
+
+llvm::Value *
+jit_typeinfo::complex_real (llvm::Value *cx)
+{
+  return builder.CreateExtractValue (cx, 0);
+}
+
+llvm::Value *
+jit_typeinfo::complex_real (llvm::Value *cx, llvm::Value *real)
+{
+  return builder.CreateInsertValue (cx, real, 0);
+}
+
+llvm::Value *
+jit_typeinfo::complex_imag (llvm::Value *cx)
+{
+  return builder.CreateExtractValue (cx, 1);
+}
+
+llvm::Value *
+jit_typeinfo::complex_imag (llvm::Value *cx, llvm::Value *imag)
+{
+  return builder.CreateInsertValue (cx, imag, 1);
+}
+
+llvm::Value *
+jit_typeinfo::complex_new (llvm::Value *real, llvm::Value *imag)
+{
+  llvm::Value *ret = llvm::UndefValue::get (complex->to_llvm ());
+  ret = complex_real (ret, real);
+  return complex_imag (ret, imag);
+}
+
+void
+jit_typeinfo::create_int (size_t nbits)
+{
+  std::stringstream tname;
+  tname << "int" << nbits;
+  ints[nbits] = new_type (tname.str (), any, llvm::Type::getIntNTy (context,
+                                                                    nbits));
+}
+
+jit_type *
+jit_typeinfo::intN (size_t nbits) const
+{
+  std::map<size_t, jit_type *>::const_iterator iter = ints.find (nbits);
+  if (iter != ints.end ())
+    return iter->second;
+
+  throw jit_fail_exception ("No such integer type");
+}
+
+jit_type *
+jit_typeinfo::do_type_of (const octave_value &ov) const
+{
+  if (ov.is_function ())
+    {
+      // FIXME: This is ugly, we need to finalize how we want to to this, then
+      // have octave_value fully support the needed functionality
+      octave_builtin *builtin
+        = dynamic_cast<octave_builtin *> (ov.internal_rep ());
+      return builtin && builtin->to_jit () ? builtin->to_jit ()
+        : unknown_function;
+    }
+
+  if (ov.is_range ())
+    return get_range ();
+
+  if (ov.is_double_type () && ! ov.is_complex_type ())
+    {
+      if (ov.is_real_scalar ())
+        return get_scalar ();
+
+      if (ov.is_matrix_type ())
+        return get_matrix ();
+    }
+
+  if (ov.is_complex_scalar ())
+    {
+      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 ();
+}
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libinterp/interp-core/jit-typeinfo.h
@@ -0,0 +1,850 @@
+/*
+
+Copyright (C) 2012 Max Brister <max@2bass.com>
+
+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_jit_typeinfo_h)
+#define octave_jit_typeinfo_h 1
+
+#ifdef HAVE_LLVM
+
+#include <map>
+#include <vector>
+
+#include "Range.h"
+#include "jit-util.h"
+
+// Defines the type system used by jit and a singleton class, jit_typeinfo, to
+// manage the types.
+//
+// FIXME:
+// Operations are defined and implemented in jit_typeinfo. Eventually they
+// should be moved elsewhere. (just like with octave_typeinfo)
+
+// jit_range is compatable with the llvm range structure
+struct
+jit_range
+{
+  jit_range (const Range& from) : base (from.base ()), limit (from.limit ()),
+                                  inc (from.inc ()), nelem (from.nelem ())
+  {}
+
+  operator Range () const
+  {
+    return Range (base, limit, inc);
+  }
+
+  bool all_elements_are_ints () const;
+
+  double base;
+  double limit;
+  double inc;
+  octave_idx_type nelem;
+};
+
+std::ostream& operator<< (std::ostream& os, const jit_range& rng);
+
+// jit_array is compatable with the llvm array/matrix structures
+template <typename T, typename U>
+struct
+jit_array
+{
+  jit_array () : array (0) {}
+
+  jit_array (T& from) : array (new T (from))
+  {
+    update ();
+  }
+
+  void update (void)
+  {
+    ref_count = array->jit_ref_count ();
+    slice_data = array->jit_slice_data () - 1;
+    slice_len = array->capacity ();
+    dimensions = array->jit_dimensions ();
+  }
+
+  void update (T *aarray)
+  {
+    array = aarray;
+    update ();
+  }
+
+  operator T () const
+  {
+    return *array;
+  }
+
+  int *ref_count;
+
+  U *slice_data;
+  octave_idx_type slice_len;
+  octave_idx_type *dimensions;
+
+  T *array;
+};
+
+typedef jit_array<NDArray, double> jit_matrix;
+
+std::ostream& operator<< (std::ostream& os, const jit_matrix& mat);
+
+// calling convention
+namespace
+jit_convention
+{
+  enum
+  type
+  {
+    // internal to jit
+    internal,
+
+    // an external C call
+    external,
+
+    length
+  };
+}
+
+// Used to keep track of estimated (infered) types during JIT. This is a
+// hierarchical type system which includes both concrete and abstract types.
+//
+// The types form a lattice. Currently we only allow for one parent type, but
+// eventually we may allow for multiple predecessors.
+class
+jit_type
+{
+public:
+  typedef llvm::Value *(*convert_fn) (llvm::IRBuilderD&, llvm::Value *);
+
+  jit_type (const std::string& aname, jit_type *aparent, llvm::Type *allvm_type,
+            bool askip_paren, int aid);
+
+  // a user readable type name
+  const std::string& name (void) const { return mname; }
+
+  // a unique id for the type
+  int type_id (void) const { return mid; }
+
+  // An abstract base type, may be null
+  jit_type *parent (void) const { return mparent; }
+
+  // convert to an llvm type
+  llvm::Type *to_llvm (void) const { return llvm_type; }
+
+  // how this type gets passed as a function argument
+  llvm::Type *to_llvm_arg (void) const;
+
+  size_t depth (void) const { return mdepth; }
+
+  bool skip_paren (void) const { return mskip_paren; }
+
+  // -------------------- Calling Convention information --------------------
+
+  // A function declared like: mytype foo (int arg0, int arg1);
+  // Will be converted to: void foo (mytype *retval, int arg0, int arg1)
+  // if mytype is sret. The caller is responsible for allocating space for
+  // retval. (on the stack)
+  bool sret (jit_convention::type cc) const { return msret[cc]; }
+
+  void mark_sret (jit_convention::type cc)
+  { msret[cc] = true; }
+
+  // A function like: void foo (mytype arg0)
+  // Will be converted to: void foo (mytype *arg0)
+  // Basically just pass by reference.
+  bool pointer_arg (jit_convention::type cc) const { return mpointer_arg[cc]; }
+
+  void mark_pointer_arg (jit_convention::type cc)
+  { mpointer_arg[cc] = true; }
+
+  // Convert into an equivalent form before calling. For example, complex is
+  // represented as two values llvm vector, but we need to pass it as a two
+  // valued llvm structure to C functions.
+  convert_fn pack (jit_convention::type cc) { return mpack[cc]; }
+
+  void set_pack (jit_convention::type cc, convert_fn fn) { mpack[cc] = fn; }
+
+  // The inverse operation of pack.
+  convert_fn unpack (jit_convention::type cc) { return munpack[cc]; }
+
+  void set_unpack (jit_convention::type cc, convert_fn fn)
+  { munpack[cc] = fn; }
+
+  // The resulting type after pack is called.
+  llvm::Type *packed_type (jit_convention::type cc)
+  { return mpacked_type[cc]; }
+
+  void set_packed_type (jit_convention::type cc, llvm::Type *ty)
+  { mpacked_type[cc] = ty; }
+private:
+  std::string mname;
+  jit_type *mparent;
+  llvm::Type *llvm_type;
+  int mid;
+  size_t mdepth;
+  bool mskip_paren;
+
+  bool msret[jit_convention::length];
+  bool mpointer_arg[jit_convention::length];
+
+  convert_fn mpack[jit_convention::length];
+  convert_fn munpack[jit_convention::length];
+
+  llvm::Type *mpacked_type[jit_convention::length];
+};
+
+// seperate print function to allow easy printing if type is null
+std::ostream& jit_print (std::ostream& os, jit_type *atype);
+
+class jit_value;
+
+// An abstraction for calling llvm functions with jit_values. Deals with calling
+// convention details.
+class
+jit_function
+{
+  friend std::ostream& operator<< (std::ostream& os, const jit_function& fn);
+public:
+  // create a function in an invalid state
+  jit_function ();
+
+  jit_function (llvm::Module *amodule, jit_convention::type acall_conv,
+                const llvm::Twine& aname, jit_type *aresult,
+                const std::vector<jit_type *>& aargs);
+
+  // Use an existing function, but change the argument types. The new argument
+  // types must behave the same for the current calling convention.
+  jit_function (const jit_function& fn, jit_type *aresult,
+                const std::vector<jit_type *>& aargs);
+
+  jit_function (const jit_function& fn);
+
+  // erase the interal LLVM function (if it exists). Will become invalid.
+  void erase (void);
+
+  template <typename T>
+  void add_mapping (llvm::ExecutionEngine *engine, T fn)
+  {
+    do_add_mapping (engine, reinterpret_cast<void *> (fn));
+  }
+
+  bool valid (void) const { return llvm_function; }
+
+  std::string name (void) const;
+
+  llvm::BasicBlock *new_block (const std::string& aname = "body",
+                               llvm::BasicBlock *insert_before = 0);
+
+  llvm::Value *call (llvm::IRBuilderD& builder,
+                     const std::vector<jit_value *>& in_args) const;
+
+  llvm::Value *call (llvm::IRBuilderD& builder,
+                     const std::vector<llvm::Value *>& in_args
+                     = std::vector<llvm::Value *> ()) const;
+
+#define JIT_PARAM_ARGS llvm::IRBuilderD& builder,
+#define JIT_PARAMS builder,
+#define JIT_CALL(N) JIT_EXPAND (llvm::Value *, call, llvm::Value *, const, N)
+
+  JIT_CALL (1)
+  JIT_CALL (2)
+  JIT_CALL (3)
+  JIT_CALL (4)
+  JIT_CALL (5)
+
+#undef JIT_CALL
+
+#define JIT_CALL(N) JIT_EXPAND (llvm::Value *, call, jit_value *, const, N)
+
+  JIT_CALL (1);
+  JIT_CALL (2);
+  JIT_CALL (3);
+
+#undef JIT_CALL
+#undef JIT_PARAMS
+#undef JIT_PARAM_ARGS
+
+  llvm::Value *argument (llvm::IRBuilderD& builder, size_t idx) const;
+
+  void do_return (llvm::IRBuilderD& builder, llvm::Value *rval = 0,
+                  bool verify = true);
+
+  llvm::Function *to_llvm (void) const { return llvm_function; }
+
+  // If true, then the return value is passed as a pointer in the first argument
+  bool sret (void) const { return mresult && mresult->sret (call_conv); }
+
+  bool can_error (void) const { return mcan_error; }
+
+  void mark_can_error (void) { mcan_error = true; }
+
+  jit_type *result (void) const { return mresult; }
+
+  jit_type *argument_type (size_t idx) const
+  {
+    assert (idx < args.size ());
+    return args[idx];
+  }
+
+  const std::vector<jit_type *>& arguments (void) const { return args; }
+private:
+  void do_add_mapping (llvm::ExecutionEngine *engine, void *fn);
+
+  llvm::Module *module;
+  llvm::Function *llvm_function;
+  jit_type *mresult;
+  std::vector<jit_type *> args;
+  jit_convention::type call_conv;
+  bool mcan_error;
+};
+
+std::ostream& operator<< (std::ostream& os, const jit_function& fn);
+
+
+// Keeps track of information about how to implement operations (+, -, *, ect)
+// and their resulting types.
+class
+jit_operation
+{
+public:
+  // type signature vector
+  typedef std::vector<jit_type *> signature_vec;
+
+  virtual ~jit_operation (void);
+
+  void add_overload (const jit_function& func)
+  {
+    add_overload (func, func.arguments ());
+  }
+
+  void add_overload (const jit_function& func,
+                     const signature_vec& args);
+
+  const jit_function& overload (const signature_vec& types) const;
+
+  jit_type *result (const signature_vec& types) const
+  {
+    const jit_function& temp = overload (types);
+    return temp.result ();
+  }
+
+#define JIT_PARAMS
+#define JIT_PARAM_ARGS
+#define JIT_OVERLOAD(N)                                              \
+  JIT_EXPAND (const jit_function&, overload, jit_type *, const, N)   \
+  JIT_EXPAND (jit_type *, result, jit_type *, const, N)
+
+  JIT_OVERLOAD (1);
+  JIT_OVERLOAD (2);
+  JIT_OVERLOAD (3);
+
+#undef JIT_PARAMS
+#undef JIT_PARAM_ARGS
+
+  const std::string& name (void) const { return mname; }
+
+  void stash_name (const std::string& aname) { mname = aname; }
+protected:
+  virtual jit_function *generate (const signature_vec& types) const;
+private:
+  Array<octave_idx_type> to_idx (const signature_vec& types) const;
+
+  const jit_function& do_generate (const signature_vec& types) const;
+
+  struct signature_cmp
+  {
+    bool operator() (const signature_vec *lhs, const signature_vec *rhs);
+  };
+
+  typedef std::map<const signature_vec *, jit_function *, signature_cmp>
+  generated_map;
+
+  mutable generated_map generated;
+
+  std::vector<Array<jit_function> > overloads;
+
+  std::string mname;
+};
+
+class
+jit_index_operation : public jit_operation
+{
+public:
+  jit_index_operation (void) : module (0), engine (0) {}
+
+  void initialize (llvm::Module *amodule, llvm::ExecutionEngine *aengine)
+  {
+    module = amodule;
+    engine = aengine;
+    do_initialize ();
+  }
+protected:
+  virtual jit_function *generate (const signature_vec& types) const;
+
+  virtual jit_function *generate_matrix (const signature_vec& types) const = 0;
+
+  virtual void do_initialize (void) = 0;
+
+  // helper functions
+  // [start_idx, end_idx).
+  llvm::Value *create_arg_array (llvm::IRBuilderD& builder,
+                                 const jit_function &fn, size_t start_idx,
+                                 size_t end_idx) const;
+
+  llvm::Module *module;
+  llvm::ExecutionEngine *engine;
+};
+
+class
+jit_paren_subsref : public jit_index_operation
+{
+protected:
+  virtual jit_function *generate_matrix (const signature_vec& types) const;
+
+  virtual void do_initialize (void);
+private:
+  jit_function paren_scalar;
+};
+
+class
+jit_paren_subsasgn : public jit_index_operation
+{
+protected:
+  jit_function *generate_matrix (const signature_vec& types) const;
+
+  virtual void do_initialize (void);
+private:
+  jit_function paren_scalar;
+};
+
+// A singleton class which handles the construction of jit_types and
+// jit_operations.
+class
+jit_typeinfo
+{
+public:
+  static void initialize (llvm::Module *m, llvm::ExecutionEngine *e);
+
+  static jit_type *join (jit_type *lhs, jit_type *rhs)
+  {
+    return instance->do_join (lhs, rhs);
+  }
+
+  static jit_type *get_any (void) { return instance->any; }
+
+  static jit_type *get_matrix (void) { return instance->matrix; }
+
+  static jit_type *get_scalar (void) { return instance->scalar; }
+
+  static llvm::Type *get_scalar_llvm (void)
+  { return instance->scalar->to_llvm (); }
+
+  static jit_type *get_scalar_ptr (void) { return instance->scalar_ptr; }
+
+  static jit_type *get_any_ptr (void) { return instance->any_ptr; }
+
+  static jit_type *get_range (void) { return instance->range; }
+
+  static jit_type *get_string (void) { return instance->string; }
+
+  static jit_type *get_bool (void) { return instance->boolean; }
+
+  static jit_type *get_index (void) { return instance->index; }
+
+  static llvm::Type *get_index_llvm (void)
+  { return instance->index->to_llvm (); }
+
+  static jit_type *get_complex (void) { return instance->complex; }
+
+  // Get the jit_type of an octave_value
+  static jit_type *type_of (const octave_value& ov)
+  {
+    return instance->do_type_of (ov);
+  }
+
+  static const jit_operation& binary_op (int op)
+  {
+    return instance->do_binary_op (op);
+  }
+
+  static const jit_operation& unary_op (int op)
+  {
+    return instance->do_unary_op (op);
+  }
+
+  static const jit_operation& grab (void) { return instance->grab_fn; }
+
+  static const jit_function& get_grab (jit_type *type)
+  {
+    return instance->grab_fn.overload (type);
+  }
+
+  static const jit_operation& release (void)
+  {
+    return instance->release_fn;
+  }
+
+  static const jit_function& get_release (jit_type *type)
+  {
+    return instance->release_fn.overload (type);
+  }
+
+  static const jit_operation& destroy (void)
+  {
+    return instance->destroy_fn;
+  }
+
+  static const jit_operation& print_value (void)
+  {
+    return instance->print_fn;
+  }
+
+  static const jit_operation& for_init (void)
+  {
+    return instance->for_init_fn;
+  }
+
+  static const jit_operation& for_check (void)
+  {
+    return instance->for_check_fn;
+  }
+
+  static const jit_operation& for_index (void)
+  {
+    return instance->for_index_fn;
+  }
+
+  static const jit_operation& make_range (void)
+  {
+    return instance->make_range_fn;
+  }
+
+  static const jit_operation& paren_subsref (void)
+  {
+    return instance->paren_subsref_fn;
+  }
+
+  static const jit_operation& paren_subsasgn (void)
+  {
+    return instance->paren_subsasgn_fn;
+  }
+
+  static const jit_operation& logically_true (void)
+  {
+    return instance->logically_true_fn;
+  }
+
+  static const jit_operation& cast (jit_type *result)
+  {
+    return instance->do_cast (result);
+  }
+
+  static const jit_function& cast (jit_type *to, jit_type *from)
+  {
+    return instance->do_cast (to, from);
+  }
+
+  static llvm::Value *insert_error_check (llvm::IRBuilderD& bld)
+  {
+    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;
+  }
+
+  static const jit_function& end (jit_value *value, jit_value *index,
+                                  jit_value *count)
+  {
+    return instance->do_end (value, index, count);
+  }
+
+  static const jit_operation& create_undef (void)
+  {
+    return instance->create_undef_fn;
+  }
+
+  static llvm::Value *create_complex (llvm::Value *real, llvm::Value *imag)
+  {
+    return instance->complex_new (real, imag);
+  }
+private:
+  jit_typeinfo (llvm::Module *m, llvm::ExecutionEngine *e);
+
+  // FIXME: Do these methods really need to be in jit_typeinfo?
+  jit_type *do_join (jit_type *lhs, jit_type *rhs)
+  {
+    // empty case
+    if (! lhs)
+      return rhs;
+
+    if (! rhs)
+      return lhs;
+
+    // check for a shared parent
+    while (lhs != rhs)
+      {
+        if (lhs->depth () > rhs->depth ())
+          lhs = lhs->parent ();
+        else if (lhs->depth () < rhs->depth ())
+          rhs = rhs->parent ();
+        else
+          {
+            // we MUST have depth > 0 as any is the base type of everything
+            do
+              {
+                lhs = lhs->parent ();
+                rhs = rhs->parent ();
+              }
+            while (lhs != rhs);
+          }
+      }
+
+    return lhs;
+  }
+
+  jit_type *do_difference (jit_type *lhs, jit_type *)
+  {
+    // FIXME: Maybe we can do something smarter?
+    return lhs;
+  }
+
+  jit_type *do_type_of (const octave_value &ov) const;
+
+  const jit_operation& do_binary_op (int op) const
+  {
+    assert (static_cast<size_t>(op) < binary_ops.size ());
+    return binary_ops[op];
+  }
+
+  const jit_operation& do_unary_op (int op) const
+  {
+    assert (static_cast<size_t> (op) < unary_ops.size ());
+    return unary_ops[op];
+  }
+
+  const jit_operation& do_cast (jit_type *to)
+  {
+    static jit_operation null_function;
+    if (! to)
+      return null_function;
+
+    size_t id = to->type_id ();
+    if (id >= casts.size ())
+      return null_function;
+    return casts[id];
+  }
+
+  const jit_function& do_cast (jit_type *to, jit_type *from)
+  {
+    return do_cast (to).overload (from);
+  }
+
+  const jit_function& do_end (jit_value *value, jit_value *index,
+                              jit_value *count);
+
+  jit_type *new_type (const std::string& name, jit_type *parent,
+                      llvm::Type *llvm_type, bool skip_paren = false);
+
+
+  void add_print (jit_type *ty, void *fptr);
+
+  void add_binary_op (jit_type *ty, int op, int llvm_op);
+
+  void add_binary_icmp (jit_type *ty, int op, int llvm_op);
+
+  void add_binary_fcmp (jit_type *ty, int op, int llvm_op);
+
+  // create a function with an external calling convention
+  // forces the function pointer to be specified
+  template <typename T>
+  jit_function create_external (llvm::ExecutionEngine *ee, T fn,
+                                const llvm::Twine& name, jit_type *ret,
+                                const std::vector<jit_type *>& args
+                                = std::vector<jit_type *> ())
+  {
+    jit_function retval = create_function (jit_convention::external, name, ret,
+                                           args);
+    retval.add_mapping (ee, fn);
+    return retval;
+  }
+
+#define JIT_PARAM_ARGS llvm::ExecutionEngine *ee, T fn,     \
+    const llvm::Twine& name, jit_type *ret,
+#define JIT_PARAMS ee, fn, name, ret,
+#define CREATE_FUNCTION(N) JIT_EXPAND(template <typename T> jit_function, \
+                                      create_external,                  \
+                                      jit_type *, /* empty */, N)
+
+  CREATE_FUNCTION(1);
+  CREATE_FUNCTION(2);
+  CREATE_FUNCTION(3);
+  CREATE_FUNCTION(4);
+
+#undef JIT_PARAM_ARGS
+#undef JIT_PARAMS
+#undef CREATE_FUNCTION
+
+  // use create_external or create_internal directly
+  jit_function create_function (jit_convention::type cc,
+                                const llvm::Twine& name, jit_type *ret,
+                                const std::vector<jit_type *>& args
+                                = std::vector<jit_type *> ());
+
+  // create an internal calling convention (a function defined in llvm)
+  jit_function create_internal (const llvm::Twine& name, jit_type *ret,
+                                const std::vector<jit_type *>& args
+                                = std::vector<jit_type *> ())
+  {
+    return create_function (jit_convention::internal, name, ret, args);
+  }
+
+#define JIT_PARAM_ARGS const llvm::Twine& name, jit_type *ret,
+#define JIT_PARAMS name, ret,
+#define CREATE_FUNCTION(N) JIT_EXPAND(jit_function, create_internal,    \
+                                      jit_type *, /* empty */, N)
+
+  CREATE_FUNCTION(1);
+  CREATE_FUNCTION(2);
+  CREATE_FUNCTION(3);
+  CREATE_FUNCTION(4);
+
+#undef JIT_PARAM_ARGS
+#undef JIT_PARAMS
+#undef CREATE_FUNCTION
+
+  jit_function create_identity (jit_type *type);
+
+  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,
+                           jit_type *result, jit_type *arg0)
+  {
+    std::vector<jit_type *> args (1, arg0);
+    register_intrinsic (name, id, result, args);
+  }
+
+  void register_intrinsic (const std::string& name, size_t id, jit_type *result,
+                           const std::vector<jit_type *>& args);
+
+  void register_generic (const std::string& name, jit_type *result,
+                         jit_type *arg0)
+  {
+    std::vector<jit_type *> args (1, arg0);
+    register_generic (name, result, args);
+  }
+
+  void register_generic (const std::string& name, jit_type *result,
+                         const std::vector<jit_type *>& args);
+
+  octave_builtin *find_builtin (const std::string& name);
+
+  jit_function mirror_binary (const jit_function& fn);
+
+  llvm::Function *wrap_complex (llvm::Function *wrap);
+
+  static llvm::Value *pack_complex (llvm::IRBuilderD& bld,
+                                    llvm::Value *cplx);
+
+  static llvm::Value *unpack_complex (llvm::IRBuilderD& bld,
+                                      llvm::Value *result);
+
+  llvm::Value *complex_real (llvm::Value *cx);
+
+  llvm::Value *complex_real (llvm::Value *cx, llvm::Value *real);
+
+  llvm::Value *complex_imag (llvm::Value *cx);
+
+  llvm::Value *complex_imag (llvm::Value *cx, llvm::Value *imag);
+
+  llvm::Value *complex_new (llvm::Value *real, llvm::Value *imag);
+
+  void create_int (size_t nbits);
+
+  jit_type *intN (size_t nbits) const;
+
+  static jit_typeinfo *instance;
+
+  llvm::Module *module;
+  llvm::ExecutionEngine *engine;
+  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;
+  jit_type *matrix;
+  jit_type *scalar;
+  jit_type *scalar_ptr; // a fake type for interfacing with C++
+  jit_type *any_ptr; // a fake type for interfacing with C++
+  jit_type *range;
+  jit_type *string;
+  jit_type *boolean;
+  jit_type *index;
+  jit_type *complex;
+  jit_type *unknown_function;
+  std::map<size_t, jit_type *> ints;
+  std::map<std::string, jit_type *> builtins;
+
+  llvm::StructType *complex_ret;
+
+  std::vector<jit_operation> binary_ops;
+  std::vector<jit_operation> unary_ops;
+  jit_operation grab_fn;
+  jit_operation release_fn;
+  jit_operation destroy_fn;
+  jit_operation print_fn;
+  jit_operation for_init_fn;
+  jit_operation for_check_fn;
+  jit_operation for_index_fn;
+  jit_operation logically_true_fn;
+  jit_operation make_range_fn;
+  jit_paren_subsref paren_subsref_fn;
+  jit_paren_subsasgn paren_subsasgn_fn;
+  jit_operation end1_fn;
+  jit_operation end_fn;
+  jit_operation create_undef_fn;
+
+  jit_function any_call;
+
+  // type id -> cast function TO that type
+  std::vector<jit_operation> casts;
+
+  // type id -> identity function
+  std::vector<jit_function> identities;
+
+  llvm::IRBuilderD& builder;
+};
+
+#endif
+#endif
new file mode 100644
--- /dev/null
+++ b/libinterp/interp-core/jit-util.cc
@@ -0,0 +1,44 @@
+/*
+
+Copyright (C) 2012 Max Brister <max@2bass.com>
+
+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/>.
+
+*/
+
+// defines required by llvm
+#define __STDC_LIMIT_MACROS
+#define __STDC_CONSTANT_MACROS
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#ifdef HAVE_LLVM
+
+#include <llvm/Value.h>
+#include <llvm/Support/raw_os_ostream.h>
+
+std::ostream&
+operator<< (std::ostream& os, const llvm::Value& v)
+{
+  llvm::raw_os_ostream llvm_out (os);
+  v.print (llvm_out);
+  return os;
+}
+
+#endif
new file mode 100644
--- /dev/null
+++ b/libinterp/interp-core/jit-util.h
@@ -0,0 +1,203 @@
+/*
+
+Copyright (C) 2012 Max Brister <max@2bass.com>
+
+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/>.
+
+*/
+
+// Some utility classes and functions used throughout jit
+
+#if !defined (octave_jit_util_h)
+#define octave_jit_util_h 1
+
+#ifdef HAVE_LLVM
+
+#include <stdexcept>
+
+// we don't want to include llvm headers here, as they require
+// __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS be defined in the entire
+// compilation unit
+namespace llvm
+{
+  class Value;
+  class Module;
+  class FunctionPassManager;
+  class PassManager;
+  class ExecutionEngine;
+  class Function;
+  class BasicBlock;
+  class LLVMContext;
+  class Type;
+  class StructType;
+  class Twine;
+  class GlobalVariable;
+  class TerminatorInst;
+  class PHINode;
+
+  class ConstantFolder;
+
+  template <bool preserveNames>
+  class IRBuilderDefaultInserter;
+
+  template <bool preserveNames, typename T, typename Inserter>
+  class IRBuilder;
+
+typedef IRBuilder<true, ConstantFolder, IRBuilderDefaultInserter<true> >
+IRBuilderD;
+}
+
+class octave_base_value;
+class octave_builtin;
+class octave_value;
+class tree;
+class tree_expression;
+
+// thrown when we should give up on JIT and interpret
+class jit_fail_exception : public std::runtime_error
+{
+public:
+  jit_fail_exception (void) : std::runtime_error ("unknown"), mknown (false) {}
+  jit_fail_exception (const std::string& reason) : std::runtime_error (reason),
+                                                   mknown (true)
+  {}
+
+  bool known (void) const { return mknown; }
+private:
+  bool mknown;
+};
+
+// llvm doesn't provide this, and it's really useful for debugging
+std::ostream& operator<< (std::ostream& os, const llvm::Value& v);
+
+template <typename HOLDER_T, typename SUB_T>
+class jit_internal_node;
+
+// jit_internal_list and jit_internal_node implement generic embedded doubly
+// linked lists. List items extend from jit_internal_list, and can be placed
+// in nodes of type jit_internal_node. We use CRTP twice.
+template <typename LIST_T, typename NODE_T>
+class
+jit_internal_list
+{
+  friend class jit_internal_node<LIST_T, NODE_T>;
+public:
+  jit_internal_list (void) : use_head (0), use_tail (0), muse_count (0) {}
+
+  virtual ~jit_internal_list (void)
+  {
+    while (use_head)
+      use_head->stash_value (0);
+  }
+
+  NODE_T *first_use (void) const { return use_head; }
+
+  size_t use_count (void) const { return muse_count; }
+private:
+  NODE_T *use_head;
+  NODE_T *use_tail;
+  size_t muse_count;
+};
+
+// a node for internal linked lists
+template <typename LIST_T, typename NODE_T>
+class
+jit_internal_node
+{
+public:
+  typedef jit_internal_list<LIST_T, NODE_T> jit_ilist;
+
+  jit_internal_node (void) : mvalue (0), mnext (0), mprev (0) {}
+
+  ~jit_internal_node (void) { remove (); }
+
+  LIST_T *value (void) const { return mvalue; }
+
+  void stash_value (LIST_T *avalue)
+  {
+    remove ();
+
+    mvalue = avalue;
+
+    if (mvalue)
+      {
+        jit_ilist *ilist = mvalue;
+        NODE_T *sthis = static_cast<NODE_T *> (this);
+        if (ilist->use_head)
+          {
+            ilist->use_tail->mnext = sthis;
+            mprev = ilist->use_tail;
+          }
+        else
+          ilist->use_head = sthis;
+
+        ilist->use_tail = sthis;
+        ++ilist->muse_count;
+      }
+  }
+
+  NODE_T *next (void) const { return mnext; }
+
+  NODE_T *prev (void) const { return mprev; }
+private:
+  void remove ()
+  {
+    if (mvalue)
+      {
+        jit_ilist *ilist = mvalue;
+        if (mprev)
+          mprev->mnext = mnext;
+        else
+          // we are the use_head
+          ilist->use_head = mnext;
+
+        if (mnext)
+          mnext->mprev = mprev;
+        else
+          // we are the use tail
+          ilist->use_tail = mprev;
+
+        mnext = mprev = 0;
+        --ilist->muse_count;
+        mvalue = 0;
+      }
+  }
+
+  LIST_T *mvalue;
+  NODE_T *mnext;
+  NODE_T *mprev;
+};
+
+// Use like: isa<jit_phi> (value)
+// basically just a short cut type typing dyanmic_cast.
+template <typename T, typename U>
+bool isa (U *value)
+{
+  return dynamic_cast<T *> (value);
+}
+
+#define JIT_ASSIGN_ARG(i) the_args[i] = arg ## i;
+#define JIT_EXPAND(ret, fname, type, isconst, N)                        \
+  ret fname (JIT_PARAM_ARGS OCT_MAKE_DECL_LIST (type, arg, N)) isconst  \
+  {                                                                     \
+    std::vector<type> the_args (N);                                     \
+    OCT_ITERATE_MACRO (JIT_ASSIGN_ARG, N);                              \
+    return fname (JIT_PARAMS the_args);                                 \
+  }
+
+#endif
+#endif
rename from src/ls-ascii-helper.cc
rename to libinterp/interp-core/ls-ascii-helper.cc
rename from src/ls-ascii-helper.h
rename to libinterp/interp-core/ls-ascii-helper.h
rename from src/ls-hdf5.cc
rename to libinterp/interp-core/ls-hdf5.cc
--- a/src/ls-hdf5.cc
+++ b/libinterp/interp-core/ls-hdf5.cc
@@ -749,7 +749,7 @@
 int
 load_hdf5_empty (hid_t loc_id, const char *name, dim_vector &d)
 {
-  if (!hdf5_check_attr(loc_id, "OCTAVE_EMPTY_MATRIX"))
+  if (! hdf5_check_attr (loc_id, "OCTAVE_EMPTY_MATRIX"))
     return 0;
 
   hsize_t hdims, maxdims;
@@ -840,7 +840,7 @@
       || val.type_id () == octave_lazy_index::static_type_id ())
     val = val.full_value ();
 
-  std::string t = val.type_name();
+  std::string t = val.type_name ();
 #if HAVE_HDF5_18
   data_id = H5Gcreate (loc_id, name.c_str (), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
 #else
rename from src/ls-hdf5.h
rename to libinterp/interp-core/ls-hdf5.h
--- a/src/ls-hdf5.h
+++ b/libinterp/interp-core/ls-hdf5.h
@@ -202,7 +202,7 @@
 hdf5_add_scalar_attr (hid_t loc_id, hid_t type_id,
                       const char *attr_name, void *buf);
 
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
 #define H5T_NATIVE_IDX H5T_NATIVE_LONG
 #else
 #define H5T_NATIVE_IDX H5T_NATIVE_INT
rename from src/ls-mat-ascii.cc
rename to libinterp/interp-core/ls-mat-ascii.cc
--- a/src/ls-mat-ascii.cc
+++ b/libinterp/interp-core/ls-mat-ascii.cc
@@ -107,7 +107,10 @@
 }
 
 static void
-get_lines_and_columns (std::istream& is, const std::string& filename, octave_idx_type& nr, octave_idx_type& nc)
+get_lines_and_columns (std::istream& is, 
+                       octave_idx_type& nr, octave_idx_type& nc,
+                       const std::string& filename = std::string (),
+                       bool quiet = false, bool check_numeric = false)
 {
   std::streampos pos = is.tellg ();
 
@@ -147,6 +150,25 @@
 
           if (end != std::string::npos)
             {
+              if (check_numeric)
+                {
+                  std::istringstream tmp_stream (buf.substr (beg, end-beg));
+
+                  octave_read_double (tmp_stream);
+
+                  if (tmp_stream.fail ())
+                    {
+                      if (! quiet)
+                        error ("load: %s: non-numeric data found near line %d",
+                               filename.c_str (), file_line_number);
+
+                      nr = 0;
+                      nc = 0;
+
+                      goto done;
+                    }
+                }
+
               beg = buf.find_first_not_of (", \t", end);
 
               if (beg == std::string::npos || (buf[beg] == '\r' &&
@@ -172,14 +194,24 @@
           else if (nc == tmp_nc)
             nr++;
           else
-            error ("load: %s: inconsistent number of columns near line %d",
-                   filename.c_str (), file_line_number);
+            {
+              if (! quiet)
+                error ("load: %s: inconsistent number of columns near line %d",
+                       filename.c_str (), file_line_number);
+
+              nr = 0;
+              nc = 0;
+
+              goto done;
+            }
         }
     }
 
-  if (nr == 0 || nc == 0)
+  if (! quiet && (nr == 0 || nc == 0))
     error ("load: file '%s' seems to be empty!", filename.c_str ());
 
+ done:
+
   is.clear ();
   is.seekg (pos);
 }
@@ -233,7 +265,7 @@
 
       int total_count = 0;
 
-      get_lines_and_columns (is, filename, nr, nc);
+      get_lines_and_columns (is, nr, nc, filename);
 
       octave_quit ();
 
@@ -376,3 +408,23 @@
 
   return (os && success);
 }
+
+bool
+looks_like_mat_ascii_file (const std::string& filename)
+{
+  bool retval = false;
+
+  std::ifstream is (filename.c_str ());
+
+  if (is)
+    {
+      octave_idx_type nr = 0;
+      octave_idx_type nc = 0;
+
+      get_lines_and_columns (is, nr, nc, filename, true, true);
+
+      retval = (nr != 0 && nc != 0);
+    }
+
+  return retval;
+}
rename from src/ls-mat-ascii.h
rename to libinterp/interp-core/ls-mat-ascii.h
--- a/src/ls-mat-ascii.h
+++ b/libinterp/interp-core/ls-mat-ascii.h
@@ -31,4 +31,6 @@
 save_mat_ascii_data (std::ostream& os, const octave_value& val_arg,
                      int precision, bool tabs = false);
 
+extern bool looks_like_mat_ascii_file (const std::string& filename);
+
 #endif
rename from src/ls-mat4.cc
rename to libinterp/interp-core/ls-mat4.cc
--- a/src/ls-mat4.cc
+++ b/libinterp/interp-core/ls-mat4.cc
@@ -344,18 +344,18 @@
 
             read_mat_binary_data (is, dtmp, prec, nr, swap, flt_fmt);
             for (octave_idx_type i = 0; i < nr - 1; i++)
-              r.xelem(i) = dtmp[i] - 1;
+              r.xelem (i) = dtmp[i] - 1;
             nr_new = dtmp[nr - 1];
             read_mat_binary_data (is, dtmp, prec, nr, swap, flt_fmt);
             for (octave_idx_type i = 0; i < nr - 1; i++)
-              c.xelem(i) = dtmp[i] - 1;
+              c.xelem (i) = dtmp[i] - 1;
             nc_new = dtmp[nr - 1];
             read_mat_binary_data (is, dtmp, prec, nr - 1, swap, flt_fmt);
             read_mat_binary_data (is, ctmp, prec, 1, swap, flt_fmt);
             read_mat_binary_data (is, ctmp, prec, nr - 1, swap, flt_fmt);
 
             for (octave_idx_type i = 0; i < nr - 1; i++)
-              data.xelem(i) = Complex (dtmp[i], ctmp[i]);
+              data.xelem (i) = Complex (dtmp[i], ctmp[i]);
             read_mat_binary_data (is, ctmp, prec, 1, swap, flt_fmt);
 
             SparseComplexMatrix smc = SparseComplexMatrix (data, r, c,
@@ -373,11 +373,11 @@
 
             read_mat_binary_data (is, dtmp, prec, nr, swap, flt_fmt);
             for (octave_idx_type i = 0; i < nr - 1; i++)
-              r.xelem(i) = dtmp[i] - 1;
+              r.xelem (i) = dtmp[i] - 1;
             nr_new = dtmp[nr - 1];
             read_mat_binary_data (is, dtmp, prec, nr, swap, flt_fmt);
             for (octave_idx_type i = 0; i < nr - 1; i++)
-              c.xelem(i) = dtmp[i] - 1;
+              c.xelem (i) = dtmp[i] - 1;
             nc_new = dtmp[nr - 1];
             read_mat_binary_data (is, data.fortran_vec (), prec, nr - 1, swap, flt_fmt);
             read_mat_binary_data (is, dtmp, prec, 1, swap, flt_fmt);
@@ -509,7 +509,7 @@
           for (octave_idx_type j = 0; j < ncol; j++)
             buf[j*nrow+i] = static_cast<double> (*s++ & 0x00FF);
         }
-      os.write (reinterpret_cast<char *> (buf), nrow*ncol*sizeof(double));
+      os.write (reinterpret_cast<char *> (buf), nrow*ncol*sizeof (double));
     }
   else if (tc.is_range ())
     {
@@ -537,27 +537,27 @@
           SparseComplexMatrix m = tc.sparse_complex_matrix_value ();
 
           for (octave_idx_type i = 0; i < len; i++)
-            dtmp [i] = m.ridx(i) + 1;
+            dtmp[i] = m.ridx (i) + 1;
           os.write (reinterpret_cast<const char *> (dtmp), 8 * len);
           ds = nr;
           os.write (reinterpret_cast<const char *> (&ds), 8);
 
           octave_idx_type ii = 0;
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++)
+            for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++)
               dtmp[ii++] = j + 1;
           os.write (reinterpret_cast<const char *> (dtmp), 8 * len);
           ds = nc;
           os.write (reinterpret_cast<const char *> (&ds), 8);
 
           for (octave_idx_type i = 0; i < len; i++)
-            dtmp [i] = std::real (m.data(i));
+            dtmp[i] = std::real (m.data (i));
           os.write (reinterpret_cast<const char *> (dtmp), 8 * len);
           ds = 0.;
           os.write (reinterpret_cast<const char *> (&ds), 8);
 
           for (octave_idx_type i = 0; i < len; i++)
-            dtmp [i] = std::imag (m.data(i));
+            dtmp[i] = std::imag (m.data (i));
           os.write (reinterpret_cast<const char *> (dtmp), 8 * len);
           os.write (reinterpret_cast<const char *> (&ds), 8);
         }
@@ -566,14 +566,14 @@
           SparseMatrix m = tc.sparse_matrix_value ();
 
           for (octave_idx_type i = 0; i < len; i++)
-            dtmp [i] = m.ridx(i) + 1;
+            dtmp[i] = m.ridx (i) + 1;
           os.write (reinterpret_cast<const char *> (dtmp), 8 * len);
           ds = nr;
           os.write (reinterpret_cast<const char *> (&ds), 8);
 
           octave_idx_type ii = 0;
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++)
+            for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++)
               dtmp[ii++] = j + 1;
           os.write (reinterpret_cast<const char *> (dtmp), 8 * len);
           ds = nc;
rename from src/ls-mat4.h
rename to libinterp/interp-core/ls-mat4.h
rename from src/ls-mat5.cc
rename to libinterp/interp-core/ls-mat5.cc
--- a/src/ls-mat5.cc
+++ b/libinterp/interp-core/ls-mat5.cc
@@ -82,6 +82,7 @@
 #endif
 
 #define PAD(l) (((l) > 0 && (l) <= 4) ? 4 : (((l)+7)/8)*8)
+#define INT8(l) ((l) == miINT8 || (l) == miUINT8 || (l) == miUTF8)
 
 
 // The subsystem data block
@@ -514,9 +515,9 @@
   if (read_mat5_tag (is, swap, type, element_length))
     return retval;                      // EOF
 
-#ifdef HAVE_ZLIB
   if (type == miCOMPRESSED)
     {
+#ifdef HAVE_ZLIB
       // If C++ allowed us direct access to the file descriptor of an
       // ifstream in a uniform way, the code below could be vastly
       // simplified, and additional copies of the data in memory
@@ -598,8 +599,10 @@
         error ("load: error probing size of compressed data element");
 
       return retval;
+#else // HAVE_ZLIB
+      error ("load: zlib unavailable, cannot read compressed data element");
+#endif
     }
-#endif
 
   std::streampos pos;
 
@@ -667,12 +670,12 @@
   else
     {
       // Why did mathworks decide to not have dims for a workspace!!!
-      dims.resize(2);
+      dims.resize (2);
       dims(0) = 1;
       dims(1) = 1;
     }
 
-  if (read_mat5_tag (is, swap, type, len) || type != miINT8)
+  if (read_mat5_tag (is, swap, type, len) || !INT8(type))
     {
       error ("load: invalid array name subelement");
       goto early_read_error;
@@ -863,24 +866,24 @@
         // Octave can handle both "/" and "\" as a directry seperator
         // and so can ignore the seperator field of m0. I think the
         // sentinel field is also save to ignore.
-        Octave_map m0 = tc2.map_value();
-        Octave_map m1 = m0.contents("function_handle")(0).map_value();
-        std::string ftype = m1.contents("type")(0).string_value();
-        std::string fname = m1.contents("function")(0).string_value();
-        std::string fpath = m1.contents("file")(0).string_value();
+        Octave_map m0 = tc2.map_value ();
+        Octave_map m1 = m0.contents ("function_handle")(0).map_value ();
+        std::string ftype = m1.contents ("type")(0).string_value ();
+        std::string fname = m1.contents ("function")(0).string_value ();
+        std::string fpath = m1.contents ("file")(0).string_value ();
 
         if (ftype == "simple" || ftype == "scopedfunction")
           {
-            if (fpath.length() == 0)
+            if (fpath.length () == 0)
               // We have a builtin function
               tc = make_fcn_handle (fname);
             else
               {
                 std::string mroot =
-                  m0.contents("matlabroot")(0).string_value();
+                  m0.contents ("matlabroot")(0).string_value ();
 
                 if ((fpath.length () >= mroot.length ()) &&
-                    fpath.substr(0, mroot.length()) == mroot &&
+                    fpath.substr (0, mroot.length ()) == mroot &&
                     OCTAVE_EXEC_PREFIX != mroot)
                   {
                     // If fpath starts with matlabroot, and matlabroot
@@ -942,7 +945,7 @@
                         else
                           {
                             warning ("load: can't find the file %s",
-                                     fpath.c_str());
+                                     fpath.c_str ());
                             goto skip_ahead;
                           }
                       }
@@ -966,7 +969,7 @@
                     else
                       {
                         warning ("load: can't find the file %s",
-                                 fpath.c_str());
+                                 fpath.c_str ());
                         goto skip_ahead;
                       }
                   }
@@ -979,13 +982,13 @@
           }
         else if (ftype == "anonymous")
           {
-            Octave_map m2 = m1.contents("workspace")(0).map_value();
-            uint32NDArray MCOS = m2.contents("MCOS")(0).uint32_array_value();
+            Octave_map m2 = m1.contents ("workspace")(0).map_value ();
+            uint32NDArray MCOS = m2.contents ("MCOS")(0).uint32_array_value ();
             octave_idx_type off = static_cast<octave_idx_type>(MCOS(4).double_value ());
-            m2 = subsys_ov.map_value();
-            m2 = m2.contents("MCOS")(0).map_value();
-            tc2 = m2.contents("MCOS")(0).cell_value()(1 + off).cell_value()(1);
-            m2 = tc2.map_value();
+            m2 = subsys_ov.map_value ();
+            m2 = m2.contents ("MCOS")(0).map_value ();
+            tc2 = m2.contents ("MCOS")(0).cell_value ()(1 + off).cell_value ()(1);
+            m2 = tc2.map_value ();
 
             unwind_protect_safe frame;
 
@@ -1000,17 +1003,17 @@
             octave_call_stack::push (local_scope, 0);
             frame.add_fcn (octave_call_stack::pop);
 
-            if (m2.nfields() > 0)
+            if (m2.nfields () > 0)
               {
                 octave_value tmp;
 
-                for (Octave_map::iterator p0 = m2.begin() ;
-                     p0 != m2.end(); p0++)
+                for (Octave_map::iterator p0 = m2.begin () ;
+                     p0 != m2.end (); p0++)
                   {
-                    std::string key = m2.key(p0);
-                    octave_value val = m2.contents(p0)(0);
-
-                    symbol_table::varref (key, local_scope, 0) = val;
+                    std::string key = m2.key (p0);
+                    octave_value val = m2.contents (p0)(0);
+
+                    symbol_table::assign (key, val, local_scope, 0);
                   }
               }
 
@@ -1057,7 +1060,7 @@
           {
             int32_t fn_type;
             int32_t fn_len;
-            if (read_mat5_tag (is, swap, fn_type, fn_len) || fn_type != miINT8)
+            if (read_mat5_tag (is, swap, fn_type, fn_len) || !INT8(fn_type))
               {
                 error ("load: invalid field name subelement");
                 goto data_read_error;
@@ -1118,7 +1121,7 @@
       {
         isclass = true;
 
-        if (read_mat5_tag (is, swap, type, len) || type != miINT8)
+        if (read_mat5_tag (is, swap, type, len) || !INT8(type))
           {
             error ("load: invalid class name");
             goto skip_ahead;
@@ -1144,7 +1147,7 @@
       // Fall-through
     case MAT_FILE_STRUCT_CLASS:
       {
-        Octave_map m (dim_vector (1, 1));
+        Octave_map m (dims);
         int32_t fn_type;
         int32_t fn_len;
         int32_t field_name_length;
@@ -1168,7 +1171,7 @@
 
         // field name subelement.  The length of this subelement tells
         // us how many fields there are.
-        if (read_mat5_tag (is, swap, fn_type, fn_len) || fn_type != miINT8)
+        if (read_mat5_tag (is, swap, fn_type, fn_len) || !INT8(fn_type))
           {
             error ("load: invalid field name subelement");
             goto data_read_error;
@@ -1219,8 +1222,8 @@
                 // inline is not an object in Octave but rather an
                 // overload of a function handle. Special case.
                 tc =
-                  new octave_fcn_inline (m.contents("expr")(0).string_value(),
-                                         m.contents("args")(0).string_value());
+                  new octave_fcn_inline (m.contents ("expr")(0).string_value (),
+                                         m.contents ("args")(0).string_value ());
               }
             else
               {
@@ -1236,7 +1239,7 @@
 
                     tc = cls;
                     if (load_path::find_method (classname, "loadobj") !=
-                        std::string())
+                        std::string ())
                       {
                         octave_value_list tmp = feval ("loadobj", tc, 1);
 
@@ -1277,7 +1280,7 @@
             boolNDArray out (dims);
 
             for (octave_idx_type i = 0; i < nel; i++)
-              out (i) = in(i).bool_value ();
+              out(i) = in(i).bool_value ();
 
             tc = out;
           }
@@ -1563,7 +1566,7 @@
 
       if (tc.is_uint8_type ())
         {
-          const uint8NDArray itmp = tc.uint8_array_value();
+          const uint8NDArray itmp = tc.uint8_array_value ();
           octave_idx_type ilen = itmp.numel ();
 
           // Why should I have to initialize outbuf as just overwrite
@@ -1936,10 +1939,10 @@
           bool too_large_for_float = false;
           for (octave_idx_type i = 0; i < nel; i++)
             {
-              double tmp = val [i];
+              double tmp = val[i];
 
               if (! (xisnan (tmp) || xisinf (tmp))
-                  && fabs (tmp) > FLT_MAX)
+                  && fabs (tmp) > std::numeric_limits<float>::max ())
                 {
                   too_large_for_float = true;
                   break;
@@ -2100,7 +2103,7 @@
 save_mat5_element_length (const octave_value& tc, const std::string& name,
                           bool save_as_floats, bool mat7_format)
 {
-  size_t max_namelen = (mat7_format ? 63 : 31);
+  size_t max_namelen = 63;
   size_t len = name.length ();
   std::string cname = tc.class_name ();
   int ret = 32;
@@ -2284,7 +2287,7 @@
   int32_t flags = 0;
   int32_t nnz_32 = 0;
   std::string cname = tc.class_name ();
-  size_t max_namelen = (mat7_format ? 63 : 31);
+  size_t max_namelen = 63;
 
   dim_vector dv = tc.dims ();
   int nd = tc.ndims ();
@@ -2429,6 +2432,10 @@
     }
 
   os.write (reinterpret_cast<char *> (&flags), 4);
+  // Matlab seems to have trouble reading files that have nzmax == 0 at
+  // this point in the file.
+  if (nnz_32 == 0)
+    nnz_32 = 1;
   os.write (reinterpret_cast<char *> (&nnz_32), 4);
 
   write_mat5_tag (os, miINT32, dim_len);
@@ -2450,7 +2457,7 @@
     size_t namelen = name.length ();
 
     if (namelen > max_namelen)
-      namelen = max_namelen; // only 31 or 63 char names permitted in mat file
+      namelen = max_namelen;  // Truncate names if necessary
 
     int paddedlength = PAD (namelen);
 
@@ -2620,15 +2627,15 @@
           write_mat5_array (os, ::imag (m_cmplx), save_as_floats);
         }
     }
-  else if (tc.is_map () || tc.is_inline_function() || tc.is_object ())
+  else if (tc.is_map () || tc.is_inline_function () || tc.is_object ())
     {
       if (tc.is_inline_function () || tc.is_object ())
         {
-          std::string classname = tc.is_object() ? tc.class_name () : "inline";
+          std::string classname = tc.is_object () ? tc.class_name () : "inline";
           size_t namelen = classname.length ();
 
           if (namelen > max_namelen)
-            namelen = max_namelen; // only 31 or 63 char names permitted
+            namelen = max_namelen; // Truncate names if necessary
 
           int paddedlength = PAD (namelen);
 
@@ -2642,7 +2649,7 @@
       Octave_map m;
 
       if (tc.is_object () &&
-          load_path::find_method (tc.class_name (), "saveobj") != std::string())
+          load_path::find_method (tc.class_name (), "saveobj") != std::string ())
         {
           octave_value_list tmp = feval ("saveobj", tc, 1);
           if (! error_state)
rename from src/ls-mat5.h
rename to libinterp/interp-core/ls-mat5.h
--- a/src/ls-mat5.h
+++ b/libinterp/interp-core/ls-mat5.h
@@ -48,7 +48,7 @@
 extern int
 read_mat5_binary_file_header (std::istream& is, bool& swap,
                               bool quiet = false,
-                              const std::string& filename = std::string());
+                              const std::string& filename = std::string ());
 extern std::string
 read_mat5_binary_element (std::istream& is, const std::string& filename,
                           bool swap, bool& global, octave_value& tc);
rename from src/ls-oct-binary.cc
rename to libinterp/interp-core/ls-oct-binary.cc
rename from src/ls-oct-binary.h
rename to libinterp/interp-core/ls-oct-binary.h
rename from src/ls-utils.cc
rename to libinterp/interp-core/ls-utils.cc
rename from src/ls-utils.h
rename to libinterp/interp-core/ls-utils.h
rename from src/matherr.c
rename to libinterp/interp-core/matherr.c
rename from src/mex.cc
rename to libinterp/interp-core/mex.cc
--- a/src/mex.cc
+++ b/libinterp/interp-core/mex.cc
@@ -35,9 +35,9 @@
 #include "lo-ieee.h"
 #include "oct-locbuf.h"
 
+#include "Cell.h"
 // mxArray must be declared as a class before including mexproto.h.
-class mxArray;
-#include "Cell.h"
+#include "mxarray.h"
 #include "mexproto.h"
 #include "oct-map.h"
 #include "oct-obj.h"
@@ -104,175 +104,12 @@
 
 // ------------------------------------------------------------------
 
-// A class to provide the default implemenation of some of the virtual
-// functions declared in the mxArray class.
-
-class mxArray_base : public mxArray
+void
+mxArray_base::error (const char *msg) const
 {
-protected:
-
-  mxArray_base (void) : mxArray (xmxArray ()) { }
-
-public:
-
-  mxArray *dup (void) const = 0;
-
-  ~mxArray_base (void) { }
-
-  bool is_octave_value (void) const { return false; }
-
-  int is_cell (void) const = 0;
-
-  int is_char (void) const = 0;
-
-  int is_class (const char *name_arg) const
-  {
-    int retval = 0;
-
-    const char *cname = get_class_name ();
-
-    if (cname && name_arg)
-      retval = ! strcmp (cname, name_arg);
-
-    return retval;
-  }
-
-  int is_complex (void) const = 0;
-
-  int is_double (void) const = 0;
-
-  int is_function_handle (void) const = 0;
-
-  int is_int16 (void) const = 0;
-
-  int is_int32 (void) const = 0;
-
-  int is_int64 (void) const = 0;
-
-  int is_int8 (void) const = 0;
-
-  int is_logical (void) const = 0;
-
-  int is_numeric (void) const = 0;
-
-  int is_single (void) const = 0;
-
-  int is_sparse (void) const = 0;
-
-  int is_struct (void) const = 0;
-
-  int is_uint16 (void) const = 0;
-
-  int is_uint32 (void) const = 0;
-
-  int is_uint64 (void) const = 0;
-
-  int is_uint8 (void) const = 0;
-
-  int is_logical_scalar (void) const
-  {
-    return is_logical () && get_number_of_elements () == 1;
-  }
-
-  int is_logical_scalar_true (void) const = 0;
-
-  mwSize get_m (void) const = 0;
-
-  mwSize get_n (void) const = 0;
-
-  mwSize *get_dimensions (void) const = 0;
-
-  mwSize get_number_of_dimensions (void) const = 0;
-
-  void set_m (mwSize m) = 0;
-
-  void set_n (mwSize n) = 0;
-
-  void set_dimensions (mwSize *dims_arg, mwSize ndims_arg) = 0;
-
-  mwSize get_number_of_elements (void) const = 0;
-
-  int is_empty (void) const = 0;
-
-  mxClassID get_class_id (void) const = 0;
-
-  const char *get_class_name (void) const = 0;
-
-  void set_class_name (const char *name_arg) = 0;
-
-  mxArray *get_cell (mwIndex /*idx*/) const
-  {
-    invalid_type_error ();
-    return 0;
-  }
-
-  void set_cell (mwIndex idx, mxArray *val) = 0;
-
-  double get_scalar (void) const = 0;
-
-  void *get_data (void) const = 0;
-
-  void *get_imag_data (void) const = 0;
-
-  void set_data (void *pr) = 0;
-
-  void set_imag_data (void *pi) = 0;
-
-  mwIndex *get_ir (void) const = 0;
-
-  mwIndex *get_jc (void) const = 0;
-
-  mwSize get_nzmax (void) const = 0;
-
-  void set_ir (mwIndex *ir) = 0;
-
-  void set_jc (mwIndex *jc) = 0;
-
-  void set_nzmax (mwSize nzmax) = 0;
-
-  int add_field (const char *key) = 0;
-
-  void remove_field (int key_num) = 0;
-
-  mxArray *get_field_by_number (mwIndex index, int key_num) const = 0;
-
-  void set_field_by_number (mwIndex index, int key_num, mxArray *val) = 0;
-
-  int get_number_of_fields (void) const = 0;
-
-  const char *get_field_name_by_number (int key_num) const = 0;
-
-  int get_field_number (const char *key) const = 0;
-
-  int get_string (char *buf, mwSize buflen) const = 0;
-
-  char *array_to_string (void) const = 0;
-
-  mwIndex calc_single_subscript (mwSize nsubs, mwIndex *subs) const = 0;
-
-  size_t get_element_size (void) const = 0;
-
-  bool mutation_needed (void) const { return false; }
-
-  mxArray *mutate (void) const { return 0; }
-
-protected:
-
-  octave_value as_octave_value (void) const = 0;
-
-  mxArray_base (const mxArray_base&) : mxArray (xmxArray ()) { }
-
-  void invalid_type_error (void) const
-  {
-    error ("invalid type for operation");
-  }
-
-  void error (const char *msg) const
-  {
-    // FIXME
-    ::error ("%s", msg);
-  }
-};
+  // FIXME
+  ::error ("%s", msg);
+}
 
 static mwIndex
 calc_single_subscript_internal (mwSize ndims, const mwSize *dims,
@@ -327,14 +164,11 @@
     : mxArray_base (), val (ov), mutate_flag (false),
       id (mxUNKNOWN_CLASS), class_name (0), ndims (-1), dims (0) { }
 
-  mxArray *dup (void) const
+  mxArray_base *dup (void) const { return new mxArray_octave_value (*this); }
+
+  mxArray *as_mxArray (void) const
   {
-    mxArray *retval = val.as_mxArray ();
-
-    if (! retval)
-      retval = new mxArray_octave_value (*this);
-
-    return retval;
+    return val.as_mxArray ();
   }
 
   ~mxArray_octave_value (void)
@@ -397,7 +231,7 @@
     mwSize n = 1;
 
     // Force dims and ndims to be cached.
-    get_dimensions();
+    get_dimensions ();
 
     for (mwIndex i = ndims - 1; i > 0; i--)
       n *= dims[i];
@@ -411,7 +245,7 @@
       {
         ndims = val.ndims ();
 
-        dims = static_cast<mwSize *> (malloc (ndims * sizeof (mwSize)));
+        dims = static_cast<mwSize *> (mxArray::malloc (ndims * sizeof (mwSize)));
 
         dim_vector dv = val.dims ();
 
@@ -488,7 +322,7 @@
     if (! class_name)
       {
         std::string s = val.class_name ();
-        class_name = strsave (s.c_str ());
+        class_name = mxArray::strsave (s.c_str ());
       }
 
     return class_name;
@@ -629,7 +463,7 @@
       {
         mwSize nel = get_number_of_elements ();
 
-        buf = static_cast<char *> (malloc (nel + 1));
+        buf = static_cast<char *> (mxArray::malloc (nel + 1));
 
         if (buf)
           {
@@ -693,14 +527,15 @@
 
   mxArray *mutate (void) const { return val.as_mxArray (); }
 
+  octave_value as_octave_value (void) const { return val; }
+
 protected:
 
-  octave_value as_octave_value (void) const { return val; }
-
   mxArray_octave_value (const mxArray_octave_value& arg)
     : mxArray_base (arg), val (arg.val), mutate_flag (arg.mutate_flag),
-      id (arg.id), class_name (strsave (arg.class_name)), ndims (arg.ndims),
-      dims (ndims > 0 ? static_cast<mwSize *> (malloc (ndims * sizeof (mwSize))) : 0)
+      id (arg.id), class_name (mxArray::strsave (arg.class_name)),
+      ndims (arg.ndims),
+      dims (ndims > 0 ? static_cast<mwSize *> (mxArray::malloc (ndims * sizeof (mwSize))) : 0)
   {
     if (dims)
       {
@@ -743,7 +578,7 @@
   mxArray_matlab (mxClassID id_arg, mwSize ndims_arg, const mwSize *dims_arg)
     : mxArray_base (), class_name (0), id (id_arg),
       ndims (ndims_arg < 2 ? 2 : ndims_arg),
-      dims (static_cast<mwSize *> (malloc (ndims * sizeof (mwSize))))
+      dims (static_cast<mwSize *> (mxArray::malloc (ndims * sizeof (mwSize))))
   {
     if (ndims_arg < 2)
       {
@@ -766,7 +601,7 @@
   mxArray_matlab (mxClassID id_arg, const dim_vector& dv)
     : mxArray_base (), class_name (0), id (id_arg),
       ndims (dv.length ()),
-      dims (static_cast<mwSize *> (malloc (ndims * sizeof (mwSize))))
+      dims (static_cast<mwSize *> (mxArray::malloc (ndims * sizeof (mwSize))))
   {
     for (mwIndex i = 0; i < ndims; i++)
       dims[i] = dv(i);
@@ -782,7 +617,7 @@
 
   mxArray_matlab (mxClassID id_arg, mwSize m, mwSize n)
     : mxArray_base (), class_name (0), id (id_arg), ndims (2),
-      dims (static_cast<mwSize *> (malloc (ndims * sizeof (mwSize))))
+      dims (static_cast<mwSize *> (mxArray::malloc (ndims * sizeof (mwSize))))
   {
     dims[0] = m;
     dims[1] = n;
@@ -911,7 +746,7 @@
   void set_class_name (const char *name_arg)
   {
     mxFree (class_name);
-    class_name = static_cast<char *> (malloc (strlen (name_arg) + 1));
+    class_name = static_cast<char *> (mxArray::malloc (strlen (name_arg) + 1));
     strcpy (class_name, name_arg);
   }
 
@@ -1069,9 +904,9 @@
 protected:
 
   mxArray_matlab (const mxArray_matlab& val)
-    : mxArray_base (val), class_name (strsave (val.class_name)),
+    : mxArray_base (val), class_name (mxArray::strsave (val.class_name)),
       id (val.id), ndims (val.ndims),
-      dims (static_cast<mwSize *> (malloc (ndims * sizeof (mwSize))))
+      dims (static_cast<mwSize *> (mxArray::malloc (ndims * sizeof (mwSize))))
   {
     for (mwIndex i = 0; i < ndims; i++)
       dims[i] = val.dims[i];
@@ -1122,23 +957,23 @@
   mxArray_number (mxClassID id_arg, mwSize ndims_arg, const mwSize *dims_arg,
                   mxComplexity flag = mxREAL)
     : mxArray_matlab (id_arg, ndims_arg, dims_arg),
-      pr (calloc (get_number_of_elements (), get_element_size ())),
-      pi (flag == mxCOMPLEX ? calloc (get_number_of_elements (), get_element_size ()) : 0) { }
+      pr (mxArray::calloc (get_number_of_elements (), get_element_size ())),
+      pi (flag == mxCOMPLEX ? mxArray::calloc (get_number_of_elements (), get_element_size ()) : 0) { }
 
   mxArray_number (mxClassID id_arg, const dim_vector& dv,
                   mxComplexity flag = mxREAL)
     : mxArray_matlab (id_arg, dv),
-      pr (calloc (get_number_of_elements (), get_element_size ())),
-      pi (flag == mxCOMPLEX ? calloc (get_number_of_elements (), get_element_size ()) : 0) { }
+      pr (mxArray::calloc (get_number_of_elements (), get_element_size ())),
+      pi (flag == mxCOMPLEX ? mxArray::calloc (get_number_of_elements (), get_element_size ()) : 0) { }
 
   mxArray_number (mxClassID id_arg, mwSize m, mwSize n, mxComplexity flag = mxREAL)
     : mxArray_matlab (id_arg, m, n),
-      pr (calloc (get_number_of_elements (), get_element_size ())),
-      pi (flag == mxCOMPLEX ? calloc (get_number_of_elements (), get_element_size ()) : 0) { }
+      pr (mxArray::calloc (get_number_of_elements (), get_element_size ())),
+      pi (flag == mxCOMPLEX ? mxArray::calloc (get_number_of_elements (), get_element_size ()) : 0) { }
 
   mxArray_number (mxClassID id_arg, double val)
     : mxArray_matlab (id_arg, 1, 1),
-      pr (calloc (get_number_of_elements (), get_element_size ())),
+      pr (mxArray::calloc (get_number_of_elements (), get_element_size ())),
       pi (0)
   {
     double *dpr = static_cast<double *> (pr);
@@ -1147,7 +982,7 @@
 
   mxArray_number (mxClassID id_arg, mxLogical val)
     : mxArray_matlab (id_arg, 1, 1),
-      pr (calloc (get_number_of_elements (), get_element_size ())),
+      pr (mxArray::calloc (get_number_of_elements (), get_element_size ())),
       pi (0)
   {
     mxLogical *lpr = static_cast<mxLogical *> (pr);
@@ -1158,7 +993,7 @@
     : mxArray_matlab (mxCHAR_CLASS,
                       str ? (strlen (str) ? 1 : 0) : 0,
                       str ? strlen (str) : 0),
-      pr (calloc (get_number_of_elements (), get_element_size ())),
+      pr (mxArray::calloc (get_number_of_elements (), get_element_size ())),
       pi (0)
   {
     mxChar *cpr = static_cast<mxChar *> (pr);
@@ -1170,7 +1005,7 @@
   // FIXME??
   mxArray_number (mwSize m, const char **str)
     : mxArray_matlab (mxCHAR_CLASS, m, max_str_len (m, str)),
-      pr (calloc (get_number_of_elements (), get_element_size ())),
+      pr (mxArray::calloc (get_number_of_elements (), get_element_size ())),
       pi (0)
   {
     mxChar *cpr = static_cast<mxChar *> (pr);
@@ -1188,12 +1023,12 @@
         for (size_t i = 0; i < tmp_len; i++)
           cpr[m*i+j] = static_cast<mxChar> (ptr[i]);
 
-        for (size_t i = tmp_len; i < nc; i++)
+        for (size_t i = tmp_len; i < static_cast<size_t>(nc); i++)
           cpr[m*i+j] = static_cast<mxChar> (' ');
       }
   }
 
-  mxArray_number *dup (void) const { return new mxArray_number (*this); }
+  mxArray_base *dup (void) const { return new mxArray_number (*this); }
 
   ~mxArray_number (void)
   {
@@ -1305,7 +1140,7 @@
 
     mwSize nel = get_number_of_elements ();
 
-    char *buf = static_cast<char *> (malloc (nel + 1));
+    char *buf = static_cast<char *> (mxArray::malloc (nel + 1));
 
     if (buf)
       {
@@ -1320,35 +1155,6 @@
     return buf;
   }
 
-protected:
-
-  template <typename ELT_T, typename ARRAY_T, typename ARRAY_ELT_T>
-  octave_value
-  int_to_ov (const dim_vector& dv) const
-  {
-    octave_value retval;
-
-    mwSize nel = get_number_of_elements ();
-
-    ELT_T *ppr = static_cast<ELT_T *> (pr);
-
-    if (pi)
-      error ("complex integer types are not supported");
-    else
-      {
-        ARRAY_T val (dv);
-
-        ARRAY_ELT_T *ptr = val.fortran_vec ();
-
-        for (mwIndex i = 0; i < nel; i++)
-          ptr[i] = ppr[i];
-
-        retval = val;
-      }
-
-    return retval;
-  }
-
   octave_value as_octave_value (void) const
   {
     octave_value retval;
@@ -1483,10 +1289,39 @@
     return retval;
   }
 
+protected:
+
+  template <typename ELT_T, typename ARRAY_T, typename ARRAY_ELT_T>
+  octave_value
+  int_to_ov (const dim_vector& dv) const
+  {
+    octave_value retval;
+
+    mwSize nel = get_number_of_elements ();
+
+    ELT_T *ppr = static_cast<ELT_T *> (pr);
+
+    if (pi)
+      error ("complex integer types are not supported");
+    else
+      {
+        ARRAY_T val (dv);
+
+        ARRAY_ELT_T *ptr = val.fortran_vec ();
+
+        for (mwIndex i = 0; i < nel; i++)
+          ptr[i] = ppr[i];
+
+        retval = val;
+      }
+
+    return retval;
+  }
+
   mxArray_number (const mxArray_number& val)
     : mxArray_matlab (val),
-      pr (malloc (get_number_of_elements () * get_element_size ())),
-      pi (val.pi ? malloc (get_number_of_elements () * get_element_size ()) : 0)
+      pr (mxArray::malloc (get_number_of_elements () * get_element_size ())),
+      pi (val.pi ? mxArray::malloc (get_number_of_elements () * get_element_size ()) : 0)
   {
     size_t nbytes = get_number_of_elements () * get_element_size ();
 
@@ -1517,13 +1352,13 @@
   mxArray_sparse (mxClassID id_arg, mwSize m, mwSize n, mwSize nzmax_arg,
                   mxComplexity flag = mxREAL)
     : mxArray_matlab (id_arg, m, n), nzmax (nzmax_arg),
-      pr (calloc (nzmax, get_element_size ())),
-      pi (flag == mxCOMPLEX ? calloc (nzmax, get_element_size ()) : 0),
-      ir (static_cast<mwIndex *> (calloc (nzmax, sizeof (mwIndex)))),
-      jc (static_cast<mwIndex *> (calloc (n + 1, sizeof (mwIndex))))
+      pr (mxArray::calloc (nzmax, get_element_size ())),
+      pi (flag == mxCOMPLEX ? mxArray::calloc (nzmax, get_element_size ()) : 0),
+      ir (static_cast<mwIndex *> (mxArray::calloc (nzmax, sizeof (mwIndex)))),
+      jc (static_cast<mwIndex *> (mxArray::calloc (n + 1, sizeof (mwIndex))))
     { }
 
-  mxArray_sparse *dup (void) const { return new mxArray_sparse (*this); }
+  mxArray_base *dup (void) const { return new mxArray_sparse (*this); }
 
   ~mxArray_sparse (void)
   {
@@ -1557,8 +1392,6 @@
 
   void set_nzmax (mwSize nzmax_arg) { nzmax = nzmax_arg; }
 
-protected:
-
   octave_value as_octave_value (void) const
   {
     octave_value retval;
@@ -1576,12 +1409,12 @@
 
           for (mwIndex i = 0; i < nzmax; i++)
             {
-              val.xdata(i) = ppr[i];
-              val.xridx(i) = ir[i];
+              val.xdata (i) = ppr[i];
+              val.xridx (i) = ir[i];
             }
 
           for (mwIndex i = 0; i < get_n () + 1; i++)
-            val.xcidx(i) = jc[i];
+            val.xcidx (i) = jc[i];
 
           retval = val;
         }
@@ -1603,12 +1436,12 @@
 
               for (mwIndex i = 0; i < nzmax; i++)
                 {
-                  val.xdata(i) = Complex (ppr[i], ppi[i]);
-                  val.xridx(i) = ir[i];
+                  val.xdata (i) = Complex (ppr[i], ppi[i]);
+                  val.xridx (i) = ir[i];
                 }
 
               for (mwIndex i = 0; i < get_n () + 1; i++)
-                val.xcidx(i) = jc[i];
+                val.xcidx (i) = jc[i];
 
               retval = val;
             }
@@ -1621,12 +1454,12 @@
 
               for (mwIndex i = 0; i < nzmax; i++)
                 {
-                  val.xdata(i) = ppr[i];
-                  val.xridx(i) = ir[i];
+                  val.xdata (i) = ppr[i];
+                  val.xridx (i) = ir[i];
                 }
 
               for (mwIndex i = 0; i < get_n () + 1; i++)
-                val.xcidx(i) = jc[i];
+                val.xcidx (i) = jc[i];
 
               retval = val;
             }
@@ -1651,10 +1484,10 @@
 
   mxArray_sparse (const mxArray_sparse& val)
     : mxArray_matlab (val), nzmax (val.nzmax),
-      pr (malloc (nzmax * get_element_size ())),
-      pi (val.pi ? malloc (nzmax * get_element_size ()) : 0),
-      ir (static_cast<mwIndex *> (malloc (nzmax * sizeof (mwIndex)))),
-      jc (static_cast<mwIndex *> (malloc (nzmax * sizeof (mwIndex))))
+      pr (mxArray::malloc (nzmax * get_element_size ())),
+      pi (val.pi ? mxArray::malloc (nzmax * get_element_size ()) : 0),
+      ir (static_cast<mwIndex *> (mxArray::malloc (nzmax * sizeof (mwIndex)))),
+      jc (static_cast<mwIndex *> (mxArray::malloc (nzmax * sizeof (mwIndex))))
   {
     size_t nbytes = nzmax * get_element_size ();
 
@@ -1686,24 +1519,24 @@
   mxArray_struct (mwSize ndims_arg, const mwSize *dims_arg, int num_keys_arg,
                   const char **keys)
     : mxArray_matlab (mxSTRUCT_CLASS, ndims_arg, dims_arg), nfields (num_keys_arg),
-      fields (static_cast<char **> (calloc (nfields, sizeof (char *)))),
-      data (static_cast<mxArray **> (calloc (nfields * get_number_of_elements (), sizeof (mxArray *))))
+      fields (static_cast<char **> (mxArray::calloc (nfields, sizeof (char *)))),
+      data (static_cast<mxArray **> (mxArray::calloc (nfields * get_number_of_elements (), sizeof (mxArray *))))
   {
     init (keys);
   }
 
   mxArray_struct (const dim_vector& dv, int num_keys_arg, const char **keys)
     : mxArray_matlab (mxSTRUCT_CLASS, dv), nfields (num_keys_arg),
-      fields (static_cast<char **> (calloc (nfields, sizeof (char *)))),
-      data (static_cast<mxArray **> (calloc (nfields * get_number_of_elements (), sizeof (mxArray *))))
+      fields (static_cast<char **> (mxArray::calloc (nfields, sizeof (char *)))),
+      data (static_cast<mxArray **> (mxArray::calloc (nfields * get_number_of_elements (), sizeof (mxArray *))))
   {
     init (keys);
   }
 
   mxArray_struct (mwSize m, mwSize n, int num_keys_arg, const char **keys)
     : mxArray_matlab (mxSTRUCT_CLASS, m, n), nfields (num_keys_arg),
-      fields (static_cast<char **> (calloc (nfields, sizeof (char *)))),
-      data (static_cast<mxArray **> (calloc (nfields * get_number_of_elements (), sizeof (mxArray *))))
+      fields (static_cast<char **> (mxArray::calloc (nfields, sizeof (char *)))),
+      data (static_cast<mxArray **> (mxArray::calloc (nfields * get_number_of_elements (), sizeof (mxArray *))))
   {
     init (keys);
   }
@@ -1711,10 +1544,10 @@
   void init (const char **keys)
   {
     for (int i = 0; i < nfields; i++)
-      fields[i] = strsave (keys[i]);
+      fields[i] = mxArray::strsave (keys[i]);
   }
 
-  mxArray_struct *dup (void) const { return new mxArray_struct (*this); }
+  mxArray_base *dup (void) const { return new mxArray_struct (*this); }
 
   ~mxArray_struct (void)
   {
@@ -1743,13 +1576,13 @@
 
         if (fields)
           {
-            fields[nfields-1] = strsave (key);
+            fields[nfields-1] = mxArray::strsave (key);
 
             mwSize nel = get_number_of_elements ();
 
             mwSize ntot = nfields * nel;
 
-            mxArray **new_data = static_cast<mxArray **> (malloc (ntot * sizeof (mxArray *)));
+            mxArray **new_data = static_cast<mxArray **> (mxArray::malloc (ntot * sizeof (mxArray *)));
 
             if (new_data)
               {
@@ -1790,9 +1623,9 @@
 
         int new_nfields = nfields - 1;
 
-        char **new_fields = static_cast<char **> (malloc (new_nfields * sizeof (char *)));
-
-        mxArray **new_data = static_cast<mxArray **> (malloc (new_nfields * nel * sizeof (mxArray *)));
+        char **new_fields = static_cast<char **> (mxArray::malloc (new_nfields * sizeof (char *)));
+
+        mxArray **new_data = static_cast<mxArray **> (mxArray::malloc (new_nfields * nel * sizeof (mxArray *)));
 
         for (int i = 0; i < key_num; i++)
           new_fields[i] = fields[i];
@@ -1863,8 +1696,6 @@
 
   void set_data (void *data_arg) { data = static_cast<mxArray **> (data_arg); }
 
-protected:
-
   octave_value as_octave_value (void) const
   {
     dim_vector dv = dims_to_dim_vector ();
@@ -1901,11 +1732,11 @@
 
   mxArray_struct (const mxArray_struct& val)
     : mxArray_matlab (val), nfields (val.nfields),
-      fields (static_cast<char **> (malloc (nfields * sizeof (char *)))),
-      data (static_cast<mxArray **> (malloc (nfields * get_number_of_elements () * sizeof (mxArray *))))
+      fields (static_cast<char **> (mxArray::malloc (nfields * sizeof (char *)))),
+      data (static_cast<mxArray **> (mxArray::malloc (nfields * get_number_of_elements () * sizeof (mxArray *))))
   {
     for (int i = 0; i < nfields; i++)
-      fields[i] = strsave (val.fields[i]);
+      fields[i] = mxArray::strsave (val.fields[i]);
 
     mwSize nel = get_number_of_elements ();
 
@@ -1930,17 +1761,17 @@
 
   mxArray_cell (mwSize ndims_arg, const mwSize *dims_arg)
     : mxArray_matlab (mxCELL_CLASS, ndims_arg, dims_arg),
-      data (static_cast<mxArray **> (calloc (get_number_of_elements (), sizeof (mxArray *)))) { }
+      data (static_cast<mxArray **> (mxArray::calloc (get_number_of_elements (), sizeof (mxArray *)))) { }
 
   mxArray_cell (const dim_vector& dv)
     : mxArray_matlab (mxCELL_CLASS, dv),
-      data (static_cast<mxArray **> (calloc (get_number_of_elements (), sizeof (mxArray *)))) { }
+      data (static_cast<mxArray **> (mxArray::calloc (get_number_of_elements (), sizeof (mxArray *)))) { }
 
   mxArray_cell (mwSize m, mwSize n)
     : mxArray_matlab (mxCELL_CLASS, m, n),
-      data (static_cast<mxArray **> (calloc (get_number_of_elements (), sizeof (mxArray *)))) { }
-
-  mxArray_cell *dup (void) const { return new mxArray_cell (*this); }
+      data (static_cast<mxArray **> (mxArray::calloc (get_number_of_elements (), sizeof (mxArray *)))) { }
+
+  mxArray_base *dup (void) const { return new mxArray_cell (*this); }
 
   ~mxArray_cell (void)
   {
@@ -1963,8 +1794,6 @@
 
   void set_data (void *data_arg) { data = static_cast<mxArray **> (data_arg); }
 
-protected:
-
   octave_value as_octave_value (void) const
   {
     dim_vector dv = dims_to_dim_vector ();
@@ -1987,7 +1816,7 @@
 
   mxArray_cell (const mxArray_cell& val)
     : mxArray_matlab (val),
-      data (static_cast<mxArray **> (malloc (get_number_of_elements () * sizeof (mxArray *))))
+      data (static_cast<mxArray **> (mxArray::malloc (get_number_of_elements () * sizeof (mxArray *))))
   {
     mwSize nel = get_number_of_elements ();
 
@@ -2062,11 +1891,11 @@
 mxArray::set_name (const char *name_arg)
 {
   mxFree (name);
-  name = strsave (name_arg);
+  name = mxArray::strsave (name_arg);
 }
 
 octave_value
-mxArray::as_octave_value (mxArray *ptr)
+mxArray::as_octave_value (const mxArray *ptr)
 {
   return ptr ? ptr->as_octave_value () : octave_value (Matrix ());
 }
@@ -2513,7 +2342,7 @@
 double
 mxGetEps (void)
 {
-  return DBL_EPSILON;
+  return std::numeric_limits<double>::epsilon ();
 }
 
 double
@@ -2532,7 +2361,7 @@
 void *
 mxCalloc (size_t n, size_t size)
 {
-  return mex_context ? mex_context->calloc (n, size) : calloc (n, size);
+  return mex_context ? mex_context->calloc (n, size) : ::calloc (n, size);
 }
 
 void *
@@ -3121,7 +2950,7 @@
 
   mex context (curr_mex_fcn);
 
-  frame.add (mex::cleanup, static_cast<void *> (&context));
+  frame.add_fcn (mex::cleanup, static_cast<void *> (&context));
 
   for (int i = 0; i < nargin; i++)
     argin[i] = context.make_value (args(i));
@@ -3180,8 +3009,8 @@
 }
 
 int
-mexCallMATLAB (int nargout, mxArray *argout[], int nargin, mxArray *argin[],
-               const char *fname)
+mexCallMATLAB (int nargout, mxArray *argout[], int nargin,
+               mxArray *argin[], const char *fname)
 {
   octave_value_list args;
 
@@ -3386,7 +3215,7 @@
 }
 
 int
-mexPutVariable (const char *space, const char *name, mxArray *ptr)
+mexPutVariable (const char *space, const char *name, const mxArray *ptr)
 {
   if (! ptr)
     return 1;
@@ -3421,7 +3250,7 @@
           if (! error_state)
             frame.add_fcn (octave_call_stack::pop);
 
-          symbol_table::varref (name) = mxArray::as_octave_value (ptr);
+          symbol_table::assign (name, mxArray::as_octave_value (ptr));
         }
       else
         mexErrMsgTxt ("mexPutVariable: symbol table does not exist");
@@ -3463,7 +3292,7 @@
   mxArray *m = 0;
   octave_value ret = get_property_from_handle (handle, property, "mexGet");
 
-  if (!error_state && ret.is_defined())
+  if (!error_state && ret.is_defined ())
     m = ret.as_mxArray ();
   return m;
 }
rename from src/mex.h
rename to libinterp/interp-core/mex.h
rename from src/mexproto.h
rename to libinterp/interp-core/mexproto.h
--- a/src/mexproto.h
+++ b/libinterp/interp-core/mexproto.h
@@ -87,7 +87,8 @@
 extern OCTINTERP_API mxArray *mexGetVariable (const char *space, const char *name);
 extern OCTINTERP_API const mxArray *mexGetVariablePtr (const char *space, const char *name);
 
-extern OCTINTERP_API int mexPutVariable (const char *space, const char *name, mxArray *ptr);
+extern OCTINTERP_API int mexPutVariable (const char *space, const char *name,
+                                         const mxArray *ptr);
 
 extern OCTINTERP_API void mexMakeArrayPersistent (mxArray *ptr);
 extern OCTINTERP_API void mexMakeMemoryPersistent (void *ptr);
new file mode 100644
--- /dev/null
+++ b/libinterp/interp-core/module.mk
@@ -0,0 +1,140 @@
+EXTRA_DIST += \
+  interp-core/module.mk \
+  interp-core/gl2ps.c \
+  interp-core/mxarray.in.h \
+  interp-core/oct-errno.in.cc
+
+JIT_INC = \
+  interp-core/jit-util.h \
+  interp-core/jit-typeinfo.h \
+  interp-core/jit-ir.h \
+  interp-core/pt-jit.h
+
+INTERP_CORE_INC = \
+  interp-core/Cell.h \
+  interp-core/action-container.h \
+  interp-core/c-file-ptr-stream.h \
+  interp-core/comment-list.h \
+  interp-core/cutils.h \
+  interp-core/defun-dld.h \
+  interp-core/defun-int.h \
+  interp-core/display.h \
+  interp-core/dynamic-ld.h \
+  interp-core/event-queue.h \
+  interp-core/gl-render.h \
+  interp-core/gl2ps-renderer.h \
+  interp-core/gl2ps.h \
+  interp-core/gripes.h \
+  interp-core/ls-ascii-helper.h \
+  interp-core/ls-hdf5.h \
+  interp-core/ls-mat-ascii.h \
+  interp-core/ls-mat4.h \
+  interp-core/ls-mat5.h \
+  interp-core/ls-oct-binary.h \
+  interp-core/ls-utils.h \
+  interp-core/mex.h \
+  interp-core/mexproto.h \
+  interp-core/mxarray.in.h \
+  interp-core/oct-errno.h \
+  interp-core/oct-fstrm.h \
+  interp-core/oct-hdf5.h \
+  interp-core/oct-iostrm.h \
+  interp-core/oct-lvalue.h \
+  interp-core/oct-map.h \
+  interp-core/oct-obj.h \
+  interp-core/oct-prcstrm.h \
+  interp-core/oct-procbuf.h \
+  interp-core/oct-stdstrm.h \
+  interp-core/oct-stream.h \
+  interp-core/oct-strstrm.h \
+  interp-core/oct.h \
+  interp-core/procstream.h \
+  interp-core/siglist.h \
+  interp-core/sparse-xdiv.h \
+  interp-core/sparse-xpow.h \
+  interp-core/txt-eng-ft.h \
+  interp-core/txt-eng.h \
+  interp-core/unwind-prot.h \
+  interp-core/xdiv.h \
+  interp-core/xnorm.h \
+  interp-core/xpow.h \
+  interp-core/zfstream.h \
+  $(JIT_INC)
+
+JIT_SRC = \
+  interp-core/jit-util.cc \
+  interp-core/jit-typeinfo.cc \
+  interp-core/jit-ir.cc \
+  interp-core/pt-jit.cc
+
+C_INTERP_CORE_SRC = \
+  interp-core/cutils.c \
+  interp-core/matherr.c \
+  interp-core/siglist.c \
+  interp-core/xgl2ps.c
+
+INTERP_CORE_SRC = \
+  interp-core/Cell.cc \
+  interp-core/c-file-ptr-stream.cc \
+  interp-core/comment-list.cc \
+  interp-core/display.cc \
+  interp-core/dynamic-ld.cc \
+  interp-core/gl-render.cc \
+  interp-core/gl2ps-renderer.cc \
+  interp-core/gripes.cc \
+  interp-core/ls-ascii-helper.cc \
+  interp-core/ls-hdf5.cc \
+  interp-core/ls-mat-ascii.cc \
+  interp-core/ls-mat4.cc \
+  interp-core/ls-mat5.cc \
+  interp-core/ls-oct-binary.cc \
+  interp-core/ls-utils.cc \
+  interp-core/mex.cc \
+  interp-core/oct-fstrm.cc \
+  interp-core/oct-iostrm.cc \
+  interp-core/oct-lvalue.cc \
+  interp-core/oct-map.cc \
+  interp-core/oct-obj.cc \
+  interp-core/oct-prcstrm.cc \
+  interp-core/oct-procbuf.cc \
+  interp-core/oct-stream.cc \
+  interp-core/oct-strstrm.cc \
+  interp-core/procstream.cc \
+  interp-core/sparse-xdiv.cc \
+  interp-core/sparse-xpow.cc \
+  interp-core/txt-eng-ft.cc \
+  interp-core/unwind-prot.cc \
+  interp-core/xdiv.cc \
+  interp-core/xnorm.cc \
+  interp-core/xpow.cc \
+  interp-core/zfstream.cc \
+  $(JIT_SRC) \
+  $(C_INTERP_CORE_SRC)
+
+## FIXME: Automake does not support per-object rules.
+##        These rules could be emulated by creating a new convenience
+##        library and using per-library rules.  Or we can just live
+##        without the rule since there haven't been any problems. (09/18/2012)
+#display.df display.lo: CPPFLAGS += $(X11_FLAGS)
+
+## Special rules for sources which must be built before rest of compilation.
+interp-core/oct-errno.cc: interp-core/oct-errno.in.cc Makefile
+	if test -n "$(PERL)"; then \
+	  $(srcdir)/mk-errno-list --perl "$(PERL)" < $< > $@-t; \
+	elif test -n "$(PYTHON)"; then \
+	  $(srcdir)/mk-errno-list --python "$(PYTHON)" < $< > $@-t; \
+	else \
+	  $(SED) '/@SYSDEP_ERRNO_LIST@/D' $< > $@-t; \
+	fi
+	mv $@-t $@
+
+interp-core/mxarray.h: interp-core/mxarray.in.h Makefile
+	$(SED) < $< \
+	  -e "s|%NO_EDIT_WARNING%|DO NOT EDIT!  Generated automatically from $(<F) by Make.|" \
+	  -e "s|%OCTAVE_IDX_TYPE%|${OCTAVE_IDX_TYPE}|" > $@-t
+	mv $@-t $@
+
+noinst_LTLIBRARIES += interp-core/libinterp-core.la
+
+interp_core_libinterp_core_la_SOURCES = $(INTERP_CORE_SRC)
+interp_core_libinterp_core_la_CPPFLAGS = $(liboctinterp_la_CPPFLAGS)
rename from src/mxarray.h.in
rename to libinterp/interp-core/mxarray.in.h
--- a/src/mxarray.h.in
+++ b/libinterp/interp-core/mxarray.in.h
@@ -1,3 +1,4 @@
+// %NO_EDIT_WARNING%
 /*
 
 Copyright (C) 2001-2012 Paul Kienzle
@@ -87,6 +88,7 @@
  */
 typedef %OCTAVE_IDX_TYPE% mwSize;
 typedef %OCTAVE_IDX_TYPE% mwIndex;
+typedef %OCTAVE_IDX_TYPE% mwSignedIndex;
 
 #if ! defined (MXARRAY_TYPEDEFS_ONLY)
 
@@ -114,13 +116,174 @@
       rep->METHOD_CALL; \
     }
 
-// This just provides a way to avoid infinite recursion when building
-// mxArray objects.
+// A class to provide the default implemenation of some of the virtual
+// functions declared in the mxArray class.
+
+class mxArray;
+
+class mxArray_base
+{
+protected:
+
+  mxArray_base (void) { }
+
+public:
+
+  virtual mxArray_base *dup (void) const = 0;
+
+  virtual mxArray *as_mxArray (void) const { return 0; }
+
+  virtual ~mxArray_base (void) { }
+
+  virtual bool is_octave_value (void) const { return false; }
+
+  virtual int is_cell (void) const = 0;
+
+  virtual int is_char (void) const = 0;
+
+  virtual int is_class (const char *name_arg) const
+  {
+    int retval = 0;
+
+    const char *cname = get_class_name ();
+
+    if (cname && name_arg)
+      retval = ! strcmp (cname, name_arg);
+
+    return retval;
+  }
+
+  virtual int is_complex (void) const = 0;
+
+  virtual int is_double (void) const = 0;
+
+  virtual int is_function_handle (void) const = 0;
+
+  virtual int is_int16 (void) const = 0;
+
+  virtual int is_int32 (void) const = 0;
+
+  virtual int is_int64 (void) const = 0;
+
+  virtual int is_int8 (void) const = 0;
+
+  virtual int is_logical (void) const = 0;
+
+  virtual int is_numeric (void) const = 0;
+
+  virtual int is_single (void) const = 0;
+
+  virtual int is_sparse (void) const = 0;
+
+  virtual int is_struct (void) const = 0;
+
+  virtual int is_uint16 (void) const = 0;
+
+  virtual int is_uint32 (void) const = 0;
+
+  virtual int is_uint64 (void) const = 0;
+
+  virtual int is_uint8 (void) const = 0;
+
+  virtual int is_logical_scalar (void) const
+  {
+    return is_logical () && get_number_of_elements () == 1;
+  }
+
+  virtual int is_logical_scalar_true (void) const = 0;
+
+  virtual mwSize get_m (void) const = 0;
+
+  virtual mwSize get_n (void) const = 0;
+
+  virtual mwSize *get_dimensions (void) const = 0;
+
+  virtual mwSize get_number_of_dimensions (void) const = 0;
 
-struct
-xmxArray
-{
-  xmxArray (void) { }
+  virtual void set_m (mwSize m) = 0;
+
+  virtual void set_n (mwSize n) = 0;
+
+  virtual void set_dimensions (mwSize *dims_arg, mwSize ndims_arg) = 0;
+
+  virtual mwSize get_number_of_elements (void) const = 0;
+
+  virtual int is_empty (void) const = 0;
+
+  virtual mxClassID get_class_id (void) const = 0;
+
+  virtual const char *get_class_name (void) const = 0;
+
+  virtual void set_class_name (const char *name_arg) = 0;
+
+  virtual mxArray *get_cell (mwIndex /*idx*/) const
+  {
+    invalid_type_error ();
+    return 0;
+  }
+
+  virtual void set_cell (mwIndex idx, mxArray *val) = 0;
+
+  virtual double get_scalar (void) const = 0;
+
+  virtual void *get_data (void) const = 0;
+
+  virtual void *get_imag_data (void) const = 0;
+
+  virtual void set_data (void *pr) = 0;
+
+  virtual void set_imag_data (void *pi) = 0;
+
+  virtual mwIndex *get_ir (void) const = 0;
+
+  virtual mwIndex *get_jc (void) const = 0;
+
+  virtual mwSize get_nzmax (void) const = 0;
+
+  virtual void set_ir (mwIndex *ir) = 0;
+
+  virtual void set_jc (mwIndex *jc) = 0;
+
+  virtual void set_nzmax (mwSize nzmax) = 0;
+
+  virtual int add_field (const char *key) = 0;
+
+  virtual void remove_field (int key_num) = 0;
+
+  virtual mxArray *get_field_by_number (mwIndex index, int key_num) const = 0;
+
+  virtual void set_field_by_number (mwIndex index, int key_num, mxArray *val) = 0;
+
+  virtual int get_number_of_fields (void) const = 0;
+
+  virtual const char *get_field_name_by_number (int key_num) const = 0;
+
+  virtual int get_field_number (const char *key) const = 0;
+
+  virtual int get_string (char *buf, mwSize buflen) const = 0;
+
+  virtual char *array_to_string (void) const = 0;
+
+  virtual mwIndex calc_single_subscript (mwSize nsubs, mwIndex *subs) const = 0;
+
+  virtual size_t get_element_size (void) const = 0;
+
+  virtual bool mutation_needed (void) const { return false; }
+
+  virtual mxArray *mutate (void) const { return 0; }
+
+  virtual octave_value as_octave_value (void) const = 0;
+
+protected:
+
+  mxArray_base (const mxArray_base&) { }
+
+  void invalid_type_error (void) const
+  {
+    error ("invalid type for operation");
+  }
+
+  void error (const char *msg) const;
 };
 
 // The main interface class.  The representation can be based on an
@@ -163,138 +326,147 @@
 
   mxArray (mwSize m, mwSize n);
 
-  virtual mxArray *dup (void) const
+  mxArray *dup (void) const
   {
-    mxArray *new_rep = rep->dup ();
+    mxArray *retval = rep->as_mxArray ();
 
-    return new mxArray (new_rep, name);
+    if (retval)
+      retval->set_name (name);
+    else
+      {
+        mxArray_base *new_rep = rep->dup ();
+
+        retval = new mxArray (new_rep, name);
+      }
+
+    return retval;
   }
 
-  virtual ~mxArray (void);
+  ~mxArray (void);
 
-  virtual bool is_octave_value (void) const { return rep->is_octave_value (); }
+  bool is_octave_value (void) const { return rep->is_octave_value (); }
 
-  virtual int is_cell (void) const { return rep->is_cell (); }
+  int is_cell (void) const { return rep->is_cell (); }
 
-  virtual int is_char (void) const { return rep->is_char (); }
+  int is_char (void) const { return rep->is_char (); }
 
-  virtual int is_class (const char *name_arg) const { return rep->is_class (name_arg); }
+  int is_class (const char *name_arg) const { return rep->is_class (name_arg); }
 
-  virtual int is_complex (void) const { return rep->is_complex (); }
+  int is_complex (void) const { return rep->is_complex (); }
 
-  virtual int is_double (void) const { return rep->is_double (); }
+  int is_double (void) const { return rep->is_double (); }
 
-  virtual int is_function_handle (void) const { return rep->is_function_handle (); }
+  int is_function_handle (void) const { return rep->is_function_handle (); }
 
-  virtual int is_int16 (void) const { return rep->is_int16 (); }
+  int is_int16 (void) const { return rep->is_int16 (); }
 
-  virtual int is_int32 (void) const { return rep->is_int32 (); }
+  int is_int32 (void) const { return rep->is_int32 (); }
 
-  virtual int is_int64 (void) const { return rep->is_int64 (); }
+  int is_int64 (void) const { return rep->is_int64 (); }
 
-  virtual int is_int8 (void) const { return rep->is_int8 (); }
+  int is_int8 (void) const { return rep->is_int8 (); }
 
-  virtual int is_logical (void) const { return rep->is_logical (); }
+  int is_logical (void) const { return rep->is_logical (); }
 
-  virtual int is_numeric (void) const { return rep->is_numeric (); }
+  int is_numeric (void) const { return rep->is_numeric (); }
 
-  virtual int is_single (void) const { return rep->is_single (); }
+  int is_single (void) const { return rep->is_single (); }
 
-  virtual int is_sparse (void) const { return rep->is_sparse (); }
+  int is_sparse (void) const { return rep->is_sparse (); }
 
-  virtual int is_struct (void) const { return rep->is_struct (); }
+  int is_struct (void) const { return rep->is_struct (); }
 
-  virtual int is_uint16 (void) const { return rep->is_uint16 (); }
+  int is_uint16 (void) const { return rep->is_uint16 (); }
 
-  virtual int is_uint32 (void) const { return rep->is_uint32 (); }
+  int is_uint32 (void) const { return rep->is_uint32 (); }
 
-  virtual int is_uint64 (void) const { return rep->is_uint64 (); }
+  int is_uint64 (void) const { return rep->is_uint64 (); }
 
-  virtual int is_uint8 (void) const { return rep->is_uint8 (); }
+  int is_uint8 (void) const { return rep->is_uint8 (); }
 
-  virtual int is_logical_scalar (void) const { return rep->is_logical_scalar (); }
+  int is_logical_scalar (void) const { return rep->is_logical_scalar (); }
 
-  virtual int is_logical_scalar_true (void) const { return rep->is_logical_scalar_true (); }
+  int is_logical_scalar_true (void) const { return rep->is_logical_scalar_true (); }
 
-  virtual mwSize get_m (void) const { return rep->get_m (); }
+  mwSize get_m (void) const { return rep->get_m (); }
 
-  virtual mwSize get_n (void) const { return rep->get_n (); }
+  mwSize get_n (void) const { return rep->get_n (); }
 
-  virtual mwSize *get_dimensions (void) const { return rep->get_dimensions (); }
+  mwSize *get_dimensions (void) const { return rep->get_dimensions (); }
 
-  virtual mwSize get_number_of_dimensions (void) const { return rep->get_number_of_dimensions (); }
+  mwSize get_number_of_dimensions (void) const { return rep->get_number_of_dimensions (); }
 
-  virtual void set_m (mwSize m) { DO_VOID_MUTABLE_METHOD (set_m (m)); }
+  void set_m (mwSize m) { DO_VOID_MUTABLE_METHOD (set_m (m)); }
 
-  virtual void set_n (mwSize n) { DO_VOID_MUTABLE_METHOD (set_n (n)); }
+  void set_n (mwSize n) { DO_VOID_MUTABLE_METHOD (set_n (n)); }
 
-  virtual void set_dimensions (mwSize *dims_arg, mwSize ndims_arg) { DO_VOID_MUTABLE_METHOD (set_dimensions (dims_arg, ndims_arg)); }
+  void set_dimensions (mwSize *dims_arg, mwSize ndims_arg) { DO_VOID_MUTABLE_METHOD (set_dimensions (dims_arg, ndims_arg)); }
 
-  virtual mwSize get_number_of_elements (void) const { return rep->get_number_of_elements (); }
+  mwSize get_number_of_elements (void) const { return rep->get_number_of_elements (); }
 
-  virtual int is_empty (void) const { return get_number_of_elements () == 0; }
+  int is_empty (void) const { return get_number_of_elements () == 0; }
 
   const char *get_name (void) const { return name; }
 
   void set_name (const char *name_arg);
 
-  virtual mxClassID get_class_id (void) const { return rep->get_class_id (); }
+  mxClassID get_class_id (void) const { return rep->get_class_id (); }
 
-  virtual const char *get_class_name (void) const { return rep->get_class_name (); }
+  const char *get_class_name (void) const { return rep->get_class_name (); }
 
-  virtual void set_class_name (const char *name_arg) { DO_VOID_MUTABLE_METHOD (set_class_name (name_arg)); }
+  void set_class_name (const char *name_arg) { DO_VOID_MUTABLE_METHOD (set_class_name (name_arg)); }
 
-  virtual mxArray *get_cell (mwIndex idx) const { DO_MUTABLE_METHOD (mxArray *, get_cell (idx)); }
+  mxArray *get_cell (mwIndex idx) const { DO_MUTABLE_METHOD (mxArray *, get_cell (idx)); }
 
-  virtual void set_cell (mwIndex idx, mxArray *val) { DO_VOID_MUTABLE_METHOD (set_cell (idx, val)); }
+  void set_cell (mwIndex idx, mxArray *val) { DO_VOID_MUTABLE_METHOD (set_cell (idx, val)); }
 
-  virtual double get_scalar (void) const { return rep->get_scalar (); }
+  double get_scalar (void) const { return rep->get_scalar (); }
 
-  virtual void *get_data (void) const { DO_MUTABLE_METHOD (void *, get_data ()); }
+  void *get_data (void) const { DO_MUTABLE_METHOD (void *, get_data ()); }
 
-  virtual void *get_imag_data (void) const { DO_MUTABLE_METHOD (void *, get_imag_data ()); }
+  void *get_imag_data (void) const { DO_MUTABLE_METHOD (void *, get_imag_data ()); }
 
-  virtual void set_data (void *pr) { DO_VOID_MUTABLE_METHOD (set_data (pr)); }
+  void set_data (void *pr) { DO_VOID_MUTABLE_METHOD (set_data (pr)); }
 
-  virtual void set_imag_data (void *pi) { DO_VOID_MUTABLE_METHOD (set_imag_data (pi)); }
+  void set_imag_data (void *pi) { DO_VOID_MUTABLE_METHOD (set_imag_data (pi)); }
 
-  virtual mwIndex *get_ir (void) const { DO_MUTABLE_METHOD (mwIndex *, get_ir ()); }
+  mwIndex *get_ir (void) const { DO_MUTABLE_METHOD (mwIndex *, get_ir ()); }
 
-  virtual mwIndex *get_jc (void) const { DO_MUTABLE_METHOD (mwIndex *, get_jc ()); }
+  mwIndex *get_jc (void) const { DO_MUTABLE_METHOD (mwIndex *, get_jc ()); }
 
-  virtual mwSize get_nzmax (void) const { return rep->get_nzmax (); }
+  mwSize get_nzmax (void) const { return rep->get_nzmax (); }
 
-  virtual void set_ir (mwIndex *ir) { DO_VOID_MUTABLE_METHOD (set_ir (ir)); }
+  void set_ir (mwIndex *ir) { DO_VOID_MUTABLE_METHOD (set_ir (ir)); }
 
-  virtual void set_jc (mwIndex *jc) { DO_VOID_MUTABLE_METHOD (set_jc (jc)); }
+  void set_jc (mwIndex *jc) { DO_VOID_MUTABLE_METHOD (set_jc (jc)); }
 
-  virtual void set_nzmax (mwSize nzmax) { DO_VOID_MUTABLE_METHOD (set_nzmax (nzmax)); }
+  void set_nzmax (mwSize nzmax) { DO_VOID_MUTABLE_METHOD (set_nzmax (nzmax)); }
 
-  virtual int add_field (const char *key) { DO_MUTABLE_METHOD (int, add_field (key)); }
+  int add_field (const char *key) { DO_MUTABLE_METHOD (int, add_field (key)); }
 
-  virtual void remove_field (int key_num) { DO_VOID_MUTABLE_METHOD (remove_field (key_num)); }
+  void remove_field (int key_num) { DO_VOID_MUTABLE_METHOD (remove_field (key_num)); }
 
-  virtual mxArray *get_field_by_number (mwIndex index, int key_num) const { DO_MUTABLE_METHOD (mxArray *, get_field_by_number (index, key_num)); }
+  mxArray *get_field_by_number (mwIndex index, int key_num) const { DO_MUTABLE_METHOD (mxArray *, get_field_by_number (index, key_num)); }
 
-  virtual void set_field_by_number (mwIndex index, int key_num, mxArray *val) { DO_VOID_MUTABLE_METHOD (set_field_by_number (index, key_num, val)); }
+  void set_field_by_number (mwIndex index, int key_num, mxArray *val) { DO_VOID_MUTABLE_METHOD (set_field_by_number (index, key_num, val)); }
 
-  virtual int get_number_of_fields (void) const { return rep->get_number_of_fields (); }
+  int get_number_of_fields (void) const { return rep->get_number_of_fields (); }
 
-  virtual const char *get_field_name_by_number (int key_num) const { DO_MUTABLE_METHOD (const char*, get_field_name_by_number (key_num)); }
+  const char *get_field_name_by_number (int key_num) const { DO_MUTABLE_METHOD (const char*, get_field_name_by_number (key_num)); }
 
-  virtual int get_field_number (const char *key) const { DO_MUTABLE_METHOD (int, get_field_number (key)); }
+  int get_field_number (const char *key) const { DO_MUTABLE_METHOD (int, get_field_number (key)); }
 
-  virtual int get_string (char *buf, mwSize buflen) const { return rep->get_string (buf, buflen); }
+  int get_string (char *buf, mwSize buflen) const { return rep->get_string (buf, buflen); }
 
-  virtual char *array_to_string (void) const { return rep->array_to_string (); }
+  char *array_to_string (void) const { return rep->array_to_string (); }
 
-  virtual mwIndex calc_single_subscript (mwSize nsubs, mwIndex *subs) const { return rep->calc_single_subscript (nsubs, subs); }
+  mwIndex calc_single_subscript (mwSize nsubs, mwIndex *subs) const { return rep->calc_single_subscript (nsubs, subs); }
 
-  virtual size_t get_element_size (void) const { return rep->get_element_size (); }
+  size_t get_element_size (void) const { return rep->get_element_size (); }
 
-  virtual bool mutation_needed (void) const { return rep->mutation_needed (); }
+  bool mutation_needed (void) const { return rep->mutation_needed (); }
 
-  virtual mxArray *mutate (void) const { return rep->mutate (); }
+  mxArray *mutate (void) const { return rep->mutate (); }
 
   static void *malloc (size_t n);
 
@@ -314,22 +486,20 @@
     return retval;
   }
 
-  static octave_value as_octave_value (mxArray *ptr);
+  static octave_value as_octave_value (const mxArray *ptr);
 
 protected:
 
-  virtual octave_value as_octave_value (void) const;
-
-  mxArray (const xmxArray&) : rep (0), name (0) { }
+  octave_value as_octave_value (void) const;
 
 private:
 
-  mutable mxArray *rep;
+  mutable mxArray_base *rep;
 
   char *name;
 
-  mxArray (mxArray *r, const char *n)
-    : rep (r), name (strsave (n)) { }
+  mxArray (mxArray_base *r, const char *n)
+    : rep (r), name (mxArray::strsave (n)) { }
 
   void maybe_mutate (void) const;
 
rename from src/oct-errno.h
rename to libinterp/interp-core/oct-errno.h
rename from src/oct-errno.cc.in
rename to libinterp/interp-core/oct-errno.in.cc
--- a/src/oct-errno.cc.in
+++ b/libinterp/interp-core/oct-errno.in.cc
@@ -1,4 +1,4 @@
-// oct-errno.cc.in
+// DO NOT EDIT!  Generated automatically from oct-errno.in.cc by configure
 /*
 
 Copyright (C) 2005-2012 John W. Eaton
rename from src/oct-fstrm.cc
rename to libinterp/interp-core/oct-fstrm.cc
--- a/src/oct-fstrm.cc
+++ b/libinterp/interp-core/oct-fstrm.cc
@@ -62,7 +62,7 @@
 // Position a stream at OFFSET relative to ORIGIN.
 
 int
-octave_fstream::seek (long, int)
+octave_fstream::seek (off_t, int)
 {
   error ("fseek: invalid_operation");
   return -1;
@@ -70,7 +70,7 @@
 
 // Return current stream position.
 
-long
+off_t
 octave_fstream::tell (void)
 {
   error ("ftell: invalid_operation");
rename from src/oct-fstrm.h
rename to libinterp/interp-core/oct-fstrm.h
--- a/src/oct-fstrm.h
+++ b/libinterp/interp-core/oct-fstrm.h
@@ -46,11 +46,11 @@
 
   // Position a stream at OFFSET relative to ORIGIN.
 
-  int seek (long offset, int origin);
+  int seek (off_t offset, int origin);
 
   // Return current stream position.
 
-  long tell (void);
+  off_t tell (void);
 
   // Return non-zero if EOF has been reached on this stream.
 
rename from src/oct-hdf5.h
rename to libinterp/interp-core/oct-hdf5.h
rename from src/oct-iostrm.cc
rename to libinterp/interp-core/oct-iostrm.cc
--- a/src/oct-iostrm.cc
+++ b/libinterp/interp-core/oct-iostrm.cc
@@ -30,7 +30,7 @@
 // Position a stream at OFFSET relative to ORIGIN.
 
 int
-octave_base_iostream::seek (long, int)
+octave_base_iostream::seek (off_t, int)
 {
   invalid_operation ();
   return -1;
@@ -38,7 +38,7 @@
 
 // Return current stream position.
 
-long
+off_t
 octave_base_iostream::tell (void)
 {
   invalid_operation ();
rename from src/oct-iostrm.h
rename to libinterp/interp-core/oct-iostrm.h
--- a/src/oct-iostrm.h
+++ b/libinterp/interp-core/oct-iostrm.h
@@ -40,11 +40,11 @@
 
   // Position a stream at OFFSET relative to ORIGIN.
 
-  int seek (long offset, int origin);
+  int seek (off_t offset, int origin);
 
   // Return current stream position.
 
-  long tell (void);
+  off_t tell (void);
 
   // Return non-zero if EOF has been reached on this stream.
 
rename from src/oct-lvalue.cc
rename to libinterp/interp-core/oct-lvalue.cc
--- a/src/oct-lvalue.cc
+++ b/libinterp/interp-core/oct-lvalue.cc
@@ -32,12 +32,12 @@
 void
 octave_lvalue::assign (octave_value::assign_op op, const octave_value& rhs)
 {
-  if (val)
+  if (! is_black_hole ())
     {
       if (idx.empty ())
-        val->assign (op, rhs);
+        sym->assign (op, rhs);
       else
-        val->assign (op, type, idx, rhs);
+        sym->assign (op, type, idx, rhs);
     }
 }
 
@@ -57,33 +57,33 @@
 void
 octave_lvalue::do_unary_op (octave_value::unary_op op)
 {
-  if (val)
+  if (! is_black_hole ())
     {
       if (idx.empty ())
-        val->do_non_const_unary_op (op);
+        sym->do_non_const_unary_op (op);
       else
-        val->do_non_const_unary_op (op, type, idx);
+        sym->do_non_const_unary_op (op, type, idx);
     }
-  else
-    error ("internal: invalid operation on ~");
 }
 
 octave_value
-octave_lvalue::value (void)
+octave_lvalue::value (void) const
 {
   octave_value retval;
 
-  if (val)
+  if (! is_black_hole ())
     {
+      octave_value val = sym->varval ();
+
       if (idx.empty ())
-        retval = *val;
+        retval = val;
       else
         {
-          if (val->is_constant ())
-            retval = val->subsref (type, idx);
+          if (val.is_constant ())
+            retval = val.subsref (type, idx);
           else
             {
-              octave_value_list t = val->subsref (type, idx, 1);
+              octave_value_list t = val.subsref (type, idx, 1);
               if (t.length () > 0)
                 retval = t(0);
             }
rename from src/oct-lvalue.h
rename to libinterp/interp-core/oct-lvalue.h
--- a/src/oct-lvalue.h
+++ b/libinterp/interp-core/oct-lvalue.h
@@ -30,26 +30,27 @@
 
 #include "oct-obj.h"
 #include "pt-idx.h"
+#include "symtab.h"
 
 class
 octave_lvalue
 {
 public:
 
-  octave_lvalue (octave_value *v = 0)
-    : val (v), type (), idx (), nel (1)
-    { }
+  octave_lvalue (const symbol_table::symbol_reference& s
+                   = symbol_table::symbol_reference ())
+    : sym (s), type (), idx (), nel (1)
+  { }
 
   octave_lvalue (const octave_lvalue& vr)
-    : val (vr.val), type (vr.type), idx (vr.idx), nel (vr.nel)
-    {
-    }
+    : sym (vr.sym), type (vr.type), idx (vr.idx), nel (vr.nel)
+  { }
 
   octave_lvalue& operator = (const octave_lvalue& vr)
     {
       if (this != &vr)
         {
-          val = vr.val;
+          sym = vr.sym;
           type = vr.type;
           idx = vr.idx;
           nel = vr.nel;
@@ -60,19 +61,24 @@
 
   ~octave_lvalue (void) { }
 
-  bool is_black_hole (void) const { return val == 0; }
+  bool is_black_hole (void) const { return sym.is_black_hole (); }
 
-  bool is_defined (void) const { return val && val->is_defined (); }
-
-  bool is_undefined (void) const { return ! val || val->is_undefined (); }
+  bool is_defined (void) const
+  {
+    return ! is_black_hole () && sym->is_defined ();
+  }
 
-  bool is_map (void) const { return val && val->is_map (); }
+  bool is_undefined (void) const
+  {
+    return is_black_hole () || sym->is_undefined ();
+  }
 
-  void define (const octave_value& v)
-    {
-      if (val)
-        *val = v;
-    }
+  bool is_map (void) const
+  {
+    return value().is_map ();
+  }
+
+  void define (const octave_value& v) { sym->assign (v); }
 
   void assign (octave_value::assign_op, const octave_value&);
 
@@ -86,13 +92,11 @@
 
   void do_unary_op (octave_value::unary_op op);
 
-  octave_value value (void);
-
-  const octave_value *object (void) const { return val; }
+  octave_value value (void) const;
 
 private:
 
-  octave_value *val;
+  symbol_table::symbol_reference sym;
 
   std::string type;
 
rename from src/oct-map.cc
rename to libinterp/interp-core/oct-map.cc
--- a/src/oct-map.cc
+++ b/libinterp/interp-core/oct-map.cc
@@ -152,7 +152,7 @@
   string_vector retval(n);
 
   for (iterator p = begin (); p != end (); p++)
-    retval.xelem(p->second) = p->first;
+    retval.xelem (p->second) = p->first;
 
   return retval;
 }
@@ -197,7 +197,7 @@
 
   octave_idx_type nf = nfields ();
   for (octave_idx_type i = 0; i < nf; i++)
-    retval.xvals[i] = xvals[perm.xelem(i)];
+    retval.xvals[i] = xvals[perm.xelem (i)];
 
   return retval;
 }
@@ -215,7 +215,7 @@
         {
           octave_idx_type nf = nfields ();
           for (octave_idx_type i = 0; i < nf; i++)
-            retval.xvals[i] = xvals[perm.xelem(i)];
+            retval.xvals[i] = xvals[perm.xelem (i)];
         }
       else
         error ("orderfields: structs must have same fields up to order");
@@ -247,7 +247,7 @@
   for (octave_idx_type i = 0; i < nf; i++)
     {
       xvals.push_back (Cell (dimensions));
-      xvals[i].xelem(0) = m.xvals[i];
+      xvals[i].xelem (0) = m.xvals[i];
     }
 }
 
@@ -308,7 +308,7 @@
 
   octave_idx_type nf = nfields ();
   for (octave_idx_type i = 0; i < nf; i++)
-    retval.xvals[i] = xvals[perm.xelem(i)];
+    retval.xvals[i] = xvals[perm.xelem (i)];
 
   return retval;
 }
@@ -326,7 +326,7 @@
         {
           octave_idx_type nf = nfields ();
           for (octave_idx_type i = 0; i < nf; i++)
-            retval.xvals[i] = xvals[perm.xelem(i)];
+            retval.xvals[i] = xvals[perm.xelem (i)];
         }
       else
         error ("orderfields: structs must have same fields up to order");
@@ -448,10 +448,10 @@
 }
 
 /*
-%!# test preservation of xkeys by squeeze
+## test preservation of xkeys by squeeze
 %!test
-%!  x(1,1,1,1).d = 10; x(3,5,1,7).a = "b"; x(2,4,1,7).f = 27;
-%!  assert (fieldnames (squeeze (x)), {"d"; "a"; "f"});
+%! x(1,1,1,1).d = 10;  x(3,5,1,7).a = "b";  x(2,4,1,7).f = 27;
+%! assert (fieldnames (squeeze (x)), {"d"; "a"; "f"});
 */
 
 octave_map
@@ -482,10 +482,10 @@
 }
 
 /*
-%!# test preservation of key order by permute
+## test preservation of key order by permute
 %!test
-%!  x(1,1,1,1).d = 10; x(3,5,1,7).a = "b"; x(2,4,1,7).f = 27;
-%!  assert (fieldnames (permute (x, [3, 4, 1, 2])), {"d"; "a"; "f"});
+%! x(1,1,1,1).d = 10;  x(3,5,1,7).a = "b";  x(2,4,1,7).f = 27;
+%! assert (fieldnames (permute (x, [3, 4, 1, 2])), {"d"; "a"; "f"});
 */
 
 octave_map
@@ -507,12 +507,12 @@
 }
 
 /*
-%!# test preservation of key order by transpose
+## test preservation of key order by transpose
 %!test
-%!  x(1,1).d = 10; x(3,5).a = "b"; x(2,4).f = 27;
-%!  assert (fieldnames (transpose (x)), {"d"; "a"; "f"});
-%!  assert (fieldnames (x'), {"d"; "a"; "f"});
-%!  assert (fieldnames (x.'), {"d"; "a"; "f"});
+%! x(1,1).d = 10;  x(3,5).a = "b";  x(2,4).f = 27;
+%! assert (fieldnames (transpose (x)), {"d"; "a"; "f"});
+%! assert (fieldnames (x'), {"d"; "a"; "f"});
+%! assert (fieldnames (x.'), {"d"; "a"; "f"});
 */
 
 octave_map
@@ -542,10 +542,10 @@
 }
 
 /*
-%!# test preservation of key order by reshape
+## test preservation of key order by reshape
 %!test
-%!  x(1,1).d = 10; x(4,6).a = "b"; x(2,4).f = 27;
-%!  assert (fieldnames (reshape (x, 3, 8)), {"d"; "a"; "f"});
+%! x(1,1).d = 10;  x(4,6).a = "b";  x(2,4).f = 27;
+%! assert (fieldnames (reshape (x, 3, 8)), {"d"; "a"; "f"});
 */
 
 void
@@ -557,7 +557,7 @@
       for (octave_idx_type i = 0; i < nf; i++)
         {
           if (fill)
-            xvals[i].resize (dv, Cell::resize_fill_value ());
+            xvals[i].resize (dv, Matrix ());
           else
             xvals[i].resize (dv);
         }
@@ -591,7 +591,7 @@
       retval.xvals.push_back (Cell (rd));
       assert (retval.xvals[j].numel () == n);
       for (octave_idx_type i = 0; i < n; i++)
-        retval.xvals[j].xelem(i) = map_list[i].xvals[j];
+        retval.xvals[j].xelem (i) = map_list[i].xvals[j];
     }
 }
 
@@ -804,23 +804,23 @@
 }
 
 /*
-%!# test preservation of key order by concatenation
+## test preservation of key order by concatenation
 %!test
-%!  x(1, 1).d = 10; x(4, 6).a = "b"; x(2, 4).f = 27;
-%!  y(1, 6).f = 11; y(1, 6).a = "c"; y(1, 6).d = 33;
-%!  assert (fieldnames ([x; y]), {"d"; "a"; "f"});
+%! x(1, 1).d = 10;  x(4, 6).a = "b";  x(2, 4).f = 27;
+%! y(1, 6).f = 11;  y(1, 6).a = "c";  y(1, 6).d = 33;
+%! assert (fieldnames ([x; y]), {"d"; "a"; "f"});
 
 %!test
-%!  s = struct ();
-%!  sr = [s,s];
-%!  sc = [s;s];
-%!  sm = [s,s;s,s];
-%!  assert (nfields (sr), 0);
-%!  assert (nfields (sc), 0);
-%!  assert (nfields (sm), 0);
-%!  assert (size (sr), [1, 2]);
-%!  assert (size (sc), [2, 1]);
-%!  assert (size (sm), [2, 2]);
+%! s = struct ();
+%! sr = [s,s];
+%! sc = [s;s];
+%! sm = [s,s;s,s];
+%! assert (nfields (sr), 0);
+%! assert (nfields (sc), 0);
+%! assert (nfields (sm), 0);
+%! assert (size (sr), [1, 2]);
+%! assert (size (sc), [2, 1]);
+%! assert (size (sm), [2, 2]);
 */
 
 octave_map
@@ -1160,7 +1160,7 @@
       for (octave_idx_type i = 0; i < nf; i++)
         {
           if (&xvals[i] != &ref)
-            xvals[i].resize (dimensions, Cell::resize_fill_value ());
+            xvals[i].resize (dimensions, Matrix ());
         }
 
       optimize_dimensions ();
@@ -1257,10 +1257,10 @@
 }
 
 /*
-%!# test preservation of key order by indexing
+## test preservation of key order by indexing
 %!test
-%!  x(1, 1).d = 10; x(4, 6).a = "b"; x(2, 4).f = 27;
-%!  assert (fieldnames (x([1, 2], [2:5])), {"d"; "a"; "f"});
+%! x(1, 1).d = 10;  x(4, 6).a = "b";  x(2, 4).f = 27;
+%! assert (fieldnames (x([1, 2], [2:5])), {"d"; "a"; "f"});
 */
 
 octave_map
@@ -1278,7 +1278,7 @@
               break;
             }
 
-          contents(pa).insert (rb.contents(pb), ra_idx);
+          contents(pa).insert (rb.contents (pb), ra_idx);
         }
     }
   else
@@ -1426,7 +1426,7 @@
 string_vector
 Octave_map::keys (void) const
 {
-  assert (nfields () == key_list.size ());
+  assert (static_cast<size_t>(nfields ()) == key_list.size ());
 
   return string_vector (key_list);
 }
@@ -1489,7 +1489,7 @@
               Cell tmp = contents(p);
 
               if (fill)
-                tmp.resize (dv, Cell::resize_fill_value ());
+                tmp.resize (dv, Matrix ());
               else
                 tmp.resize (dv);
 
@@ -1559,8 +1559,8 @@
     }
   else
     {
-      string_vector a_keys = a.keys().sort ();
-      string_vector b_keys = b.keys().sort ();
+      string_vector a_keys = a.keys ().sort ();
+      string_vector b_keys = b.keys ().sort ();
 
       octave_idx_type a_len = a_keys.length ();
       octave_idx_type b_len = b_keys.length ();
@@ -1585,7 +1585,7 @@
 Octave_map&
 Octave_map::maybe_delete_elements (const octave_value_list& idx)
 {
-  string_vector t_keys = keys();
+  string_vector t_keys = keys ();
   octave_idx_type len = t_keys.length ();
 
   if (len > 0)
@@ -1601,7 +1601,7 @@
         }
 
       if (!error_state)
-        dimensions = contents(t_keys[0]).dims();
+        dimensions = contents(t_keys[0]).dims ();
     }
 
   return *this;
@@ -1669,7 +1669,7 @@
       if (tmp_dims != dimensions)
         {
           for (iterator p = begin (); p != end (); p++)
-            contents(p).resize (tmp_dims, Cell::resize_fill_value ());
+            contents(p).resize (tmp_dims, Matrix ());
 
           dimensions = tmp_dims;
         }
rename from src/oct-map.h
rename to libinterp/interp-core/oct-map.h
rename from src/oct-obj.cc
rename to libinterp/interp-core/oct-obj.cc
--- a/src/oct-obj.cc
+++ b/libinterp/interp-core/oct-obj.cc
@@ -157,7 +157,7 @@
     retval(k++) = elem (i);
 
   for (octave_idx_type i = 0; i < lst_len; i++)
-    retval(k++) = lst(i);
+    retval(k++) = lst (i);
 
   for (octave_idx_type i = offset + rep_length; i < len; i++)
     retval(k++) = elem (i);
rename from src/oct-obj.h
rename to libinterp/interp-core/oct-obj.h
--- a/src/oct-obj.h
+++ b/libinterp/interp-core/oct-obj.h
@@ -91,8 +91,7 @@
 
   bool empty (void) const { return length () == 0; }
 
-  void resize (octave_idx_type n, const octave_value& rfv
-               = Array<octave_value>::resize_fill_value ())
+  void resize (octave_idx_type n, const octave_value& rfv = octave_value ())
   {
     data.resize (dim_vector (1, n), rfv);
   }
@@ -127,7 +126,7 @@
 
   bool has_magic_colon (void) const;
 
-  string_vector make_argv (const std::string& = std::string()) const;
+  string_vector make_argv (const std::string& = std::string ()) const;
 
   void stash_name_tags (const string_vector& nm) { names = nm; }
 
@@ -167,4 +166,152 @@
   DECLARE_OCTAVE_ALLOCATOR
 };
 
+// Make it easy to build argument lists for built-in functions or for
+// returning values.
+
+inline octave_value_list
+ovl (const octave_value& a0)
+{
+  octave_value_list retval;
+  retval(0) = a0;
+  return retval;
+}
+
+inline octave_value_list
+ovl (const octave_value& a0, const octave_value& a1)
+{
+  octave_value_list retval;
+  retval(1) = a1;
+  retval(0) = a0;
+  return retval;
+}
+
+inline octave_value_list
+ovl (const octave_value& a0, const octave_value& a1,
+     const octave_value& a2)
+{
+  octave_value_list retval;
+  retval(2) = a2;
+  retval(1) = a1;
+  retval(0) = a0;
+  return retval;
+}
+
+inline octave_value_list
+ovl (const octave_value& a0, const octave_value& a1,
+     const octave_value& a2, const octave_value& a3)
+{
+  octave_value_list retval;
+  retval(3) = a3;
+  retval(2) = a2;
+  retval(1) = a1;
+  retval(0) = a0;
+  return retval;
+}
+
+inline octave_value_list
+ovl (const octave_value& a0, const octave_value& a1,
+     const octave_value& a2, const octave_value& a3,
+     const octave_value& a4)
+{
+  octave_value_list retval;
+  retval(4) = a4;
+  retval(3) = a3;
+  retval(2) = a2;
+  retval(1) = a1;
+  retval(0) = a0;
+  return retval;
+}
+
+inline octave_value_list
+ovl (const octave_value& a0, const octave_value& a1,
+     const octave_value& a2, const octave_value& a3,
+     const octave_value& a4, const octave_value& a5)
+{
+  octave_value_list retval;
+  retval(5) = a5;
+  retval(4) = a4;
+  retval(3) = a3;
+  retval(2) = a2;
+  retval(1) = a1;
+  retval(0) = a0;
+  return retval;
+}
+
+inline octave_value_list
+ovl (const octave_value& a0, const octave_value& a1,
+     const octave_value& a2, const octave_value& a3,
+     const octave_value& a4, const octave_value& a5,
+     const octave_value& a6)
+{
+  octave_value_list retval;
+  retval(6) = a6;
+  retval(5) = a5;
+  retval(4) = a4;
+  retval(3) = a3;
+  retval(2) = a2;
+  retval(1) = a1;
+  retval(0) = a0;
+  return retval;
+}
+
+inline octave_value_list
+ovl (const octave_value& a0, const octave_value& a1,
+     const octave_value& a2, const octave_value& a3,
+     const octave_value& a4, const octave_value& a5,
+     const octave_value& a6, const octave_value& a7)
+{
+  octave_value_list retval;
+  retval(7) = a7;
+  retval(6) = a6;
+  retval(5) = a5;
+  retval(4) = a4;
+  retval(3) = a3;
+  retval(2) = a2;
+  retval(1) = a1;
+  retval(0) = a0;
+  return retval;
+}
+
+inline octave_value_list
+ovl (const octave_value& a0, const octave_value& a1,
+     const octave_value& a2, const octave_value& a3,
+     const octave_value& a4, const octave_value& a5,
+     const octave_value& a6, const octave_value& a7,
+     const octave_value& a8)
+{
+  octave_value_list retval;
+  retval(8) = a8;
+  retval(7) = a7;
+  retval(6) = a6;
+  retval(5) = a5;
+  retval(4) = a4;
+  retval(3) = a3;
+  retval(2) = a2;
+  retval(1) = a1;
+  retval(0) = a0;
+  return retval;
+}
+
+inline octave_value_list
+ovl (const octave_value& a0, const octave_value& a1,
+     const octave_value& a2, const octave_value& a3,
+     const octave_value& a4, const octave_value& a5,
+     const octave_value& a6, const octave_value& a7,
+     const octave_value& a8, const octave_value& a9)
+{
+  octave_value_list retval;
+  retval(9) = a9;
+  retval(8) = a8;
+  retval(7) = a7;
+  retval(6) = a6;
+  retval(5) = a5;
+  retval(4) = a4;
+  retval(3) = a3;
+  retval(2) = a2;
+  retval(1) = a1;
+  retval(0) = a0;
+  return retval;
+}
+
 #endif
rename from src/oct-prcstrm.cc
rename to libinterp/interp-core/oct-prcstrm.cc
rename from src/oct-prcstrm.h
rename to libinterp/interp-core/oct-prcstrm.h
rename from src/oct-procbuf.cc
rename to libinterp/interp-core/oct-procbuf.cc
--- a/src/oct-procbuf.cc
+++ b/libinterp/interp-core/oct-procbuf.cc
@@ -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);
     }
rename from src/oct-procbuf.h
rename to libinterp/interp-core/oct-procbuf.h
rename from src/oct-stdstrm.h
rename to libinterp/interp-core/oct-stdstrm.h
--- a/src/oct-stdstrm.h
+++ b/libinterp/interp-core/oct-stdstrm.h
@@ -43,12 +43,12 @@
 
   // Position a stream at OFFSET relative to ORIGIN.
 
-  int seek (long offset, int origin)
+  int seek (off_t offset, int origin)
     { return s ? s->seek (offset, origin) : -1; }
 
   // Return current stream position.
 
-  long tell (void) { return s ? s->tell () : -1; }
+  off_t tell (void) { return s ? s->tell () : -1; }
 
   // Return non-zero if EOF has been reached on this stream.
 
rename from src/oct-stream.cc
rename to libinterp/interp-core/oct-stream.cc
--- a/src/oct-stream.cc
+++ b/libinterp/interp-core/oct-stream.cc
@@ -1028,10 +1028,10 @@
   return do_gets (max_len, err, false, who);
 }
 
-long
-octave_base_stream::skipl (long num, bool& err, const std::string& who)
+off_t
+octave_base_stream::skipl (off_t num, bool& err, const std::string& who)
 {
-  long cnt = -1;
+  off_t cnt = -1;
 
   if ((interactive || forced_interactive) && file_number () == 0)
     {
@@ -1107,9 +1107,12 @@
 
     case 'i':
       {
-        int c1 = is.get ();
-
-        if (! is.eof ())
+        int c1 = EOF;
+
+        while (is && (c1 = is.get ()) != EOF && isspace (c1))
+          /* skip whitespace */;
+
+        if (c1 != EOF)
           {
             if (c1 == '0')
               {
@@ -1442,7 +1445,7 @@
   do \
     { \
       if (! width) \
-        width = INT_MAX; \
+        width = std::numeric_limits<int>::max (); \
  \
       std::ostringstream buf; \
  \
@@ -1465,7 +1468,7 @@
             buf << static_cast<char> (c); \
         } \
  \
-      if (width == INT_MAX && c != EOF) \
+      if (width == std::numeric_limits<int>::max () && c != EOF) \
         is.putback (c); \
  \
       tmp = buf.str (); \
@@ -2135,7 +2138,7 @@
               else
                 {
                   if (tmp.is_defined ())
-                    retval (num_values++) = tmp;
+                    retval(num_values++) = tmp;
 
                   if (! ok ())
                     break;
@@ -2813,10 +2816,10 @@
   return retval;
 }
 
-long
-octave_stream::skipl (long count, bool& err, const std::string& who)
+off_t
+octave_stream::skipl (off_t count, bool& err, const std::string& who)
 {
-  long retval = -1;
+  off_t retval = -1;
 
   if (stream_ok ())
     retval = rep->skipl (count, err, who);
@@ -2824,10 +2827,10 @@
   return retval;
 }
 
-long
+off_t
 octave_stream::skipl (const octave_value& tc_count, bool& err, const std::string& who)
 {
-  long retval = -1;
+  off_t retval = -1;
 
   err = false;
 
@@ -2858,7 +2861,7 @@
 }
 
 int
-octave_stream::seek (long offset, int origin)
+octave_stream::seek (off_t offset, int origin)
 {
   int status = -1;
 
@@ -2868,7 +2871,7 @@
 
       // Find current position so we can return to it if needed.
 
-      long orig_pos = rep->tell ();
+      off_t orig_pos = rep->tell ();
 
       // Move to end of file.  If successful, find the offset of the end.
 
@@ -2876,7 +2879,7 @@
 
       if (status == 0)
         {
-          long eof_pos = rep->tell ();
+          off_t eof_pos = rep->tell ();
 
           if (origin == SEEK_CUR)
             {
@@ -2896,7 +2899,7 @@
             {
               // Where are we after moving to desired position?
 
-              long desired_pos = rep->tell ();
+              off_t desired_pos = rep->tell ();
 
               // I don't think save_pos can be less than zero, but we'll
               // check anyway...
@@ -2932,7 +2935,10 @@
 {
   int retval = -1;
 
-  long xoffset = tc_offset.long_value (true);
+  // FIXME -- should we have octave_value methods that handle off_t
+  // explicitly?
+  octave_int64 val = tc_offset.int64_scalar_value ();
+  off_t xoffset = val.value ();
 
   if (! error_state)
     {
@@ -2986,10 +2992,10 @@
   return retval;
 }
 
-long
+off_t
 octave_stream::tell (void)
 {
-  long retval = -1;
+  off_t retval = -1;
 
   if (stream_ok ())
     retval = rep->tell ();
@@ -3558,17 +3564,17 @@
               // Seek to skip when inside bounds of existing file.
               // Otherwise, write NUL to skip.
 
-              long orig_pos = tell ();
+              off_t orig_pos = tell ();
 
               seek (0, SEEK_END);
 
-              long eof_pos = tell ();
+              off_t eof_pos = tell ();
 
               // Is it possible for this to fail to return us to the
               // original position?
               seek (orig_pos, SEEK_SET);
 
-              long remaining = eof_pos - orig_pos;
+              off_t remaining = eof_pos - orig_pos;
 
               if (remaining < skip)
                 {
rename from src/oct-stream.h
rename to libinterp/interp-core/oct-stream.h
--- a/src/oct-stream.h
+++ b/libinterp/interp-core/oct-stream.h
@@ -345,11 +345,11 @@
 
   // Position a stream at OFFSET relative to ORIGIN.
 
-  virtual int seek (long offset, int origin) = 0;
+  virtual int seek (off_t offset, int origin) = 0;
 
   // Return current stream position.
 
-  virtual long tell (void) = 0;
+  virtual off_t tell (void) = 0;
 
   // Return TRUE if EOF has been reached on this stream.
 
@@ -454,7 +454,7 @@
 
   std::string getl (octave_idx_type max_len, bool& err, const std::string& who /* = "getl" */);
   std::string gets (octave_idx_type max_len, bool& err, const std::string& who /* = "gets" */);
-  long skipl (long count, bool& err, const std::string& who /* = "skipl" */);
+  off_t skipl (off_t count, bool& err, const std::string& who /* = "skipl" */);
 
   octave_value do_scanf (scanf_format_list& fmt_list, octave_idx_type nr, octave_idx_type nc,
                          bool one_elt_size_spec, octave_idx_type& count,
@@ -518,13 +518,13 @@
   std::string gets (const octave_value& max_len, bool& err,
                     const std::string& who /* = "gets" */);
 
-  long skipl (long count, bool& err, const std::string& who /* = "skipl" */);
-  long skipl (const octave_value& count, bool& err, const std::string& who /* = "skipl" */);
+  off_t skipl (off_t count, bool& err, const std::string& who /* = "skipl" */);
+  off_t skipl (const octave_value& count, bool& err, const std::string& who /* = "skipl" */);
 
-  int seek (long offset, int origin);
+  int seek (off_t offset, int origin);
   int seek (const octave_value& offset, const octave_value& origin);
 
-  long tell (void);
+  off_t tell (void);
 
   int rewind (void);
 
rename from src/oct-strstrm.cc
rename to libinterp/interp-core/oct-strstrm.cc
--- a/src/oct-strstrm.cc
+++ b/libinterp/interp-core/oct-strstrm.cc
@@ -29,7 +29,7 @@
 // Position a stream at OFFSET relative to ORIGIN.
 
 int
-octave_base_strstream::seek (long, int)
+octave_base_strstream::seek (off_t, int)
 {
   error ("fseek: invalid operation");
   return -1;
@@ -37,7 +37,7 @@
 
 // Return current stream position.
 
-long
+off_t
 octave_base_strstream::tell (void)
 {
   error ("ftell: invalid operation");
rename from src/oct-strstrm.h
rename to libinterp/interp-core/oct-strstrm.h
--- a/src/oct-strstrm.h
+++ b/libinterp/interp-core/oct-strstrm.h
@@ -40,11 +40,11 @@
 
   // Position a stream at OFFSET relative to ORIGIN.
 
-  int seek (long, int);
+  int seek (off_t, int);
 
   // Return current stream position.
 
-  virtual long tell (void);
+  virtual off_t tell (void);
 
   // The name of the file.
 
@@ -104,7 +104,7 @@
 
   std::ostream *output_stream (void) { return 0; }
 
-  long tell (void) { return is.tellg (); }
+  off_t tell (void) { return is.tellg (); }
 
   std::streambuf *rdbuf (void) { return is ? is.rdbuf () : 0; }
 
rename from src/oct.h
rename to libinterp/interp-core/oct.h
--- a/src/oct.h
+++ b/libinterp/interp-core/oct.h
@@ -28,7 +28,7 @@
 // config.h needs to be first because it includes #defines that can */
 // affect other header files.
 
-#include "config.h"
+#include <config.h>
 
 #include "Matrix.h"
 
rename from src/procstream.cc
rename to libinterp/interp-core/procstream.cc
rename from src/procstream.h
rename to libinterp/interp-core/procstream.h
--- a/src/procstream.h
+++ b/libinterp/interp-core/procstream.h
@@ -108,10 +108,10 @@
   oprocstream (void) : std::ostream (0), procstreambase () { }
 
   oprocstream (const std::string& name, int mode = std::ios::out)
-    : std::ostream (0), procstreambase(name, mode) { }
+    : std::ostream (0), procstreambase (name, mode) { }
 
   oprocstream (const char *name, int mode = std::ios::out)
-    : std::ostream (0), procstreambase(name, mode) { }
+    : std::ostream (0), procstreambase (name, mode) { }
 
   ~oprocstream (void) { }
 
new file mode 100644
--- /dev/null
+++ b/libinterp/interp-core/pt-jit.cc
@@ -0,0 +1,2691 @@
+/*
+
+Copyright (C) 2012 Max Brister <max@2bass.com>
+
+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/>.
+
+*/
+
+#define __STDC_LIMIT_MACROS
+#define __STDC_CONSTANT_MACROS
+
+#ifdef HAVE_CONFIG_H
+#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"
+
+#ifdef HAVE_LLVM
+
+static bool Venable_jit_debugging = false;
+
+static bool Venable_jit_compiler = true;
+
+#include <llvm/Analysis/CallGraph.h>
+#include <llvm/Analysis/Passes.h>
+#include <llvm/Analysis/Verifier.h>
+#include <llvm/Bitcode/ReaderWriter.h>
+#include <llvm/LLVMContext.h>
+#include <llvm/ExecutionEngine/ExecutionEngine.h>
+#include <llvm/ExecutionEngine/JIT.h>
+#include <llvm/Module.h>
+#include <llvm/PassManager.h>
+#include <llvm/Support/IRBuilder.h>
+#include <llvm/Support/raw_os_ostream.h>
+#include <llvm/Support/TargetSelect.h>
+#include <llvm/Target/TargetData.h>
+#include <llvm/Transforms/IPO.h>
+#include <llvm/Transforms/Scalar.h>
+
+static llvm::IRBuilder<> builder (llvm::getGlobalContext ());
+
+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)
+{
+  initialize (symbol_table::current_scope ());
+
+  if (for_bounds)
+    create_variable (next_for_bounds (false), for_bounds);
+
+  try
+    {
+      visit (tee);
+    }
+  catch (const jit_break_exception&)
+    {}
+
+  // breaks must have been handled by the top level loop
+  assert (breaks.empty ());
+  assert (continues.empty ());
+
+  block->append (factory.create<jit_branch> (final_block));
+  blocks.push_back (final_block);
+
+  for (variable_map::iterator iter = vmap.begin (); iter != vmap.end (); ++iter)
+    {
+      jit_variable *var = iter->second;
+      const std::string& name = var->name ();
+      if (name.size () && name[0] != '#')
+        final_block->append (factory.create<jit_store_argument> (var));
+    }
+
+  final_block->append (factory.create<jit_return> ());
+}
+
+jit_convert::jit_convert (octave_user_function& fcn,
+                          const std::vector<jit_type *>& args)
+  : converting_function (true)
+{
+  initialize (fcn.scope ());
+
+  tree_parameter_list *plist = fcn.parameter_list ();
+  tree_parameter_list *rlist = fcn.return_list ();
+  if (plist && plist->takes_varargs ())
+    throw jit_fail_exception ("varags not supported");
+
+  if (rlist && (rlist->size () > 1 || rlist->takes_varargs ()))
+    throw jit_fail_exception ("multiple returns not supported");
+
+  if (plist)
+    {
+      tree_parameter_list::iterator piter = plist->begin ();
+      for (size_t i = 0; i < args.size (); ++i, ++piter)
+        {
+          if (piter == plist->end ())
+            throw jit_fail_exception ("Too many parameter to function");
+
+          tree_decl_elt *elt = *piter;
+          std::string name = elt->name ();
+          create_variable (name, args[i]);
+        }
+    }
+
+  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;
+          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
+    {
+      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);
+    }
+
+  if (! all_breaking)
+    block->append (factory.create<jit_branch> (final_block));
+
+  blocks.push_back (final_block);
+  block = final_block;
+
+  if (! return_value && rlist && rlist->size () == 1)
+    {
+      tree_decl_elt *elt = rlist->front ();
+      return_value = get_variable (elt->name ());
+    }
+
+  // FIXME: We should use live range analysis to delete variables where needed.
+  // For now we just delete everything at the end of the function.
+  for (variable_map::iterator iter = vmap.begin (); iter != vmap.end (); ++iter)
+    {
+      if (iter->second != return_value)
+        {
+          jit_call *call;
+          call = factory.create<jit_call> (&jit_typeinfo::destroy,
+                                           iter->second);
+          final_block->append (call);
+        }
+    }
+
+  if (return_value)
+    final_block->append (factory.create<jit_return> (return_value));
+  else
+    final_block->append (factory.create<jit_return> ());
+}
+
+void
+jit_convert::visit_anon_fcn_handle (tree_anon_fcn_handle&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_argument_list (tree_argument_list&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_binary_expression (tree_binary_expression& be)
+{
+  if (be.op_type () >= octave_value::num_binary_ops)
+    {
+      tree_boolean_expression *boole;
+      boole = dynamic_cast<tree_boolean_expression *> (&be);
+      assert (boole);
+      bool is_and = boole->op_type () == tree_boolean_expression::bool_and;
+
+      std::string short_name = next_shortcircut_result ();
+      jit_variable *short_result = factory.create<jit_variable> (short_name);
+      vmap[short_name] = short_result;
+
+      jit_block *done = factory.create<jit_block> (block->name ());
+      tree_expression *lhs = be.lhs ();
+      jit_value *lhsv = visit (lhs);
+      lhsv = create_checked (&jit_typeinfo::logically_true, lhsv);
+
+      jit_block *short_early = factory.create<jit_block> ("short_early");
+      blocks.push_back (short_early);
+
+      jit_block *short_cont = factory.create<jit_block> ("short_cont");
+
+      if (is_and)
+        block->append (factory.create<jit_cond_branch> (lhsv, short_cont, short_early));
+      else
+        block->append (factory.create<jit_cond_branch> (lhsv, short_early, short_cont));
+
+      block = short_early;
+
+      jit_value *early_result = factory.create<jit_const_bool> (! is_and);
+      block->append (factory.create<jit_assign> (short_result, early_result));
+      block->append (factory.create<jit_branch> (done));
+
+      blocks.push_back (short_cont);
+      block = short_cont;
+
+      tree_expression *rhs = be.rhs ();
+      jit_value *rhsv = visit (rhs);
+      rhsv = create_checked (&jit_typeinfo::logically_true, rhsv);
+      block->append (factory.create<jit_assign> (short_result, rhsv));
+      block->append (factory.create<jit_branch> (done));
+
+      blocks.push_back (done);
+      block = done;
+      result = short_result;
+    }
+  else
+    {
+      tree_expression *lhs = be.lhs ();
+      jit_value *lhsv = visit (lhs);
+
+      tree_expression *rhs = be.rhs ();
+      jit_value *rhsv = visit (rhs);
+
+      const jit_operation& fn = jit_typeinfo::binary_op (be.op_type ());
+      result = create_checked (fn, lhsv, rhsv);
+    }
+}
+
+void
+jit_convert::visit_break_command (tree_break_command&)
+{
+  breaks.push_back (block);
+  throw jit_break_exception ();
+}
+
+void
+jit_convert::visit_colon_expression (tree_colon_expression& expr)
+{
+  // in the futher we need to add support for classes and deal with rvalues
+  jit_value *base = visit (expr.base ());
+  jit_value *limit = visit (expr.limit ());
+  jit_value *increment;
+  tree_expression *tinc = expr.increment ();
+
+  if (tinc)
+    increment = visit (tinc);
+  else
+    increment = factory.create<jit_const_scalar> (1);
+
+  result = block->append (factory.create<jit_call> (jit_typeinfo::make_range, base,
+                                            limit, increment));
+}
+
+void
+jit_convert::visit_continue_command (tree_continue_command&)
+{
+  continues.push_back (block);
+  throw jit_break_exception ();
+}
+
+void
+jit_convert::visit_global_command (tree_global_command&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_persistent_command (tree_persistent_command&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_decl_elt (tree_decl_elt&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_decl_init_list (tree_decl_init_list&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_simple_for_command (tree_simple_for_command& cmd)
+{
+  // Note we do an initial check to see if the loop will run atleast once.
+  // This allows us to get better type inference bounds on variables defined
+  // 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
+  unwind_protect prot;
+  prot.protect_var (breaks);
+  prot.protect_var (continues);
+  breaks.clear ();
+  continues.clear ();
+
+  // we need a variable for our iterator, because it is used in multiple blocks
+  std::string iter_name = next_iterator ();
+  jit_variable *iterator = factory.create<jit_variable> (iter_name);
+  factory.create<jit_variable> (iter_name);
+  vmap[iter_name] = iterator;
+
+  jit_block *body = factory.create<jit_block> ("for_body");
+  jit_block *tail = factory.create<jit_block> ("for_tail");
+
+  // do control expression, iter init, and condition check in prev_block (block)
+  // if we are the top level for loop, the bounds is an input argument.
+  jit_value *control = find_variable (next_for_bounds ());
+  if (! control)
+    control = visit (cmd.control_expr ());
+  jit_call *init_iter = factory.create<jit_call> (jit_typeinfo::for_init,
+                                                  control);
+  block->append (init_iter);
+  block->append (factory.create<jit_assign> (iterator, init_iter));
+
+  jit_call *check = factory.create<jit_call> (jit_typeinfo::for_check, control,
+                                              iterator);
+  block->append (check);
+  block->append (factory.create<jit_cond_branch> (check, body, tail));
+
+  blocks.push_back (body);
+  block = body;
+
+  // compute the syntactical iterator
+  jit_call *idx_rhs = factory.create<jit_call> (jit_typeinfo::for_index,
+                                                control, iterator);
+  block->append (idx_rhs);
+  do_assign (cmd.left_hand_side (), idx_rhs);
+
+  // do loop
+  tree_statement_list *pt_body = cmd.body ();
+  bool all_breaking = false;
+  try
+    {
+      pt_body->accept (*this);
+    }
+  catch (const jit_break_exception&)
+    {
+      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);
+
+  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);
+
+  block = check_block;
+  const jit_operation& add_fn = jit_typeinfo::binary_op (octave_value::op_add);
+  jit_value *one = factory.create<jit_const_index> (1);
+  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, 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);
+  finish_breaks (tail, breaks);
+  block = tail;
+}
+
+void
+jit_convert::visit_complex_for_command (tree_complex_for_command&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_octave_user_script (octave_user_script&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_octave_user_function (octave_user_function&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_octave_user_function_header (octave_user_function&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_octave_user_function_trailer (octave_user_function&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_function_def (tree_function_def&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_identifier (tree_identifier& ti)
+{
+  if (ti.has_magic_end ())
+    {
+      if (!end_context.size ())
+        throw jit_fail_exception ("Illegal end");
+      result = block->append (factory.create<jit_magic_end> (end_context));
+    }
+  else
+    {
+      jit_variable *var = get_variable (ti.name ());
+      jit_instruction *instr;
+      instr = factory.create<jit_call> (&jit_typeinfo::grab, var);
+      result = block->append (instr);
+    }
+}
+
+void
+jit_convert::visit_if_clause (tree_if_clause&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_if_command (tree_if_command& cmd)
+{
+  tree_if_command_list *lst = cmd.cmd_list ();
+  assert (lst); // jwe: Can this be null?
+  lst->accept (*this);
+}
+
+void
+jit_convert::visit_if_command_list (tree_if_command_list& lst)
+{
+  tree_if_clause *last = lst.back ();
+  size_t last_else = static_cast<size_t> (last->is_else_clause ());
+
+  // entry_blocks represents the block you need to enter in order to execute
+  // the condition check for the ith clause. For the else, it is simple the
+  // else body. If there is no else body, then it is padded with the tail
+  std::vector<jit_block *> entry_blocks (lst.size () + 1 - last_else);
+  std::vector<jit_block *> branch_blocks (lst.size (), 0); // final blocks
+  entry_blocks[0] = block;
+
+  // we need to construct blocks first, because they have jumps to eachother
+  tree_if_command_list::iterator iter = lst.begin ();
+  ++iter;
+  for (size_t i = 1; iter != lst.end (); ++iter, ++i)
+    {
+      tree_if_clause *tic = *iter;
+      if (tic->is_else_clause ())
+        entry_blocks[i] = factory.create<jit_block> ("else");
+      else
+        entry_blocks[i] = factory.create<jit_block> ("ifelse_cond");
+    }
+
+  jit_block *tail = factory.create<jit_block> ("if_tail");
+  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)
+    {
+      tree_if_clause *tic = *iter;
+      block = entry_blocks[i];
+      assert (block);
+
+      if (i) // the first block is prev_block, so it has already been added
+        blocks.push_back (entry_blocks[i]);
+
+      if (! tic->is_else_clause ())
+        {
+          tree_expression *expr = tic->condition ();
+          jit_value *cond = visit (expr);
+          jit_call *check = create_checked (&jit_typeinfo::logically_true,
+                                            cond);
+          jit_block *body = factory.create<jit_block> (i == 0 ? "if_body"
+                                                       : "ifelse_body");
+          blocks.push_back (body);
+
+          jit_instruction *br = factory.create<jit_cond_branch> (check, body,
+                                                        entry_blocks[i + 1]);
+          block->append (br);
+          block = body;
+        }
+
+      tree_statement_list *stmt_lst = tic->commands ();
+      assert (stmt_lst); // jwe: Can this be null?
+
+      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);
+      block = tail;
+    }
+  else
+    // every branch broke, so we don't have a tail
+    throw jit_break_exception ();
+}
+
+void
+jit_convert::visit_index_expression (tree_index_expression& exp)
+{
+  result = resolve (exp);
+}
+
+void
+jit_convert::visit_matrix (tree_matrix&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_cell (tree_cell&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_multi_assignment (tree_multi_assignment&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_no_op_command (tree_no_op_command&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_constant (tree_constant& tc)
+{
+  octave_value v = tc.rvalue1 ();
+  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 (ty == jit_typeinfo::get_range ())
+    {
+      Range rv = v.range_value ();
+      result = factory.create<jit_const_range> (rv);
+    }
+  else if (ty == jit_typeinfo::get_complex ())
+    {
+      Complex cv = v.complex_value ();
+      result = factory.create<jit_const_complex> (cv);
+    }
+  else
+    throw jit_fail_exception ("Unknown constant");
+}
+
+void
+jit_convert::visit_fcn_handle (tree_fcn_handle&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_parameter_list (tree_parameter_list&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_postfix_expression (tree_postfix_expression& tpe)
+{
+  octave_value::unary_op etype = tpe.op_type ();
+  tree_expression *operand = tpe.operand ();
+  jit_value *operandv = visit (operand);
+
+  const jit_operation& fn = jit_typeinfo::unary_op (etype);
+  result = create_checked (fn, operandv);
+
+  if (etype == octave_value::op_incr || etype == octave_value::op_decr)
+    {
+      jit_value *ret = create_checked (&jit_typeinfo::grab, operandv);
+      do_assign (operand, result);
+      result = ret;
+    }
+}
+
+void
+jit_convert::visit_prefix_expression (tree_prefix_expression& tpe)
+{
+  octave_value::unary_op etype = tpe.op_type ();
+  tree_expression *operand = tpe.operand ();
+  const jit_operation& fn = jit_typeinfo::unary_op (etype);
+  result = create_checked (fn, visit (operand));
+
+  if (etype == octave_value::op_incr || etype == octave_value::op_decr)
+    do_assign (operand, result);
+}
+
+void
+jit_convert::visit_return_command (tree_return_command&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_return_list (tree_return_list&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_simple_assignment (tree_simple_assignment& tsa)
+{
+  tree_expression *rhs = tsa.right_hand_side ();
+  jit_value *rhsv = visit (rhs);
+  octave_value::assign_op op = tsa.op_type ();
+
+  if (op != octave_value::op_asn_eq)
+    {
+      // do the equivlent binary operation, then assign. This is always correct,
+      // but isn't always optimal.
+      tree_expression *lhs = tsa.left_hand_side ();
+      jit_value *lhsv = visit (lhs);
+      octave_value::binary_op bop = octave_value::assign_op_to_binary_op (op);
+      const jit_operation& fn = jit_typeinfo::binary_op (bop);
+      rhsv = create_checked (fn, lhsv, rhsv);
+    }
+
+  result = do_assign (tsa.left_hand_side (), rhsv);
+}
+
+void
+jit_convert::visit_statement (tree_statement& stmt)
+{
+  tree_command *cmd = stmt.command ();
+  tree_expression *expr = stmt.expression ();
+
+  if (cmd)
+    visit (cmd);
+  else
+    {
+      // stolen from tree_evaluator::visit_statement
+      bool do_bind_ans = false;
+
+      if (expr->is_identifier ())
+        {
+          tree_identifier *id = dynamic_cast<tree_identifier *> (expr);
+
+          do_bind_ans = (! id->is_variable ());
+        }
+      else
+        do_bind_ans = (! expr->is_assignment_expression ());
+
+      jit_value *expr_result = visit (expr);
+
+      if (do_bind_ans)
+        do_assign ("ans", expr_result, expr->print_result ());
+      else if (expr->is_identifier () && expr->print_result ())
+        {
+          // FIXME: ugly hack, we need to come up with a way to pass
+          // nargout to visit_identifier
+          const jit_operation& fn = jit_typeinfo::print_value ();
+          jit_const_string *name = factory.create<jit_const_string> (expr->name ());
+          block->append (factory.create<jit_call> (fn, name, expr_result));
+        }
+    }
+}
+
+void
+jit_convert::visit_statement_list (tree_statement_list& lst)
+{
+  for (tree_statement_list::iterator iter = lst.begin (); iter != lst.end();
+       ++iter)
+    {
+      tree_statement *elt = *iter;
+      // jwe: Can this ever be null?
+      assert (elt);
+      elt->accept (*this);
+    }
+}
+
+void
+jit_convert::visit_switch_case (tree_switch_case&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_switch_case_list (tree_switch_case_list&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_switch_command (tree_switch_command&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_try_catch_command (tree_try_catch_command&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_unwind_protect_command (tree_unwind_protect_command&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::visit_while_command (tree_while_command& wc)
+{
+  unwind_protect prot;
+  prot.protect_var (breaks);
+  prot.protect_var (continues);
+  breaks.clear ();
+  continues.clear ();
+
+  jit_block *cond_check = factory.create<jit_block> ("while_cond_check");
+  block->append (factory.create<jit_branch> (cond_check));
+  blocks.push_back (cond_check);
+  block = cond_check;
+
+  tree_expression *expr = wc.condition ();
+  assert (expr && "While expression can not be null");
+  jit_value *check = visit (expr);
+  check = create_checked (&jit_typeinfo::logically_true, check);
+
+  jit_block *body = factory.create<jit_block> ("while_body");
+  blocks.push_back (body);
+
+  jit_block *tail = factory.create<jit_block> ("while_tail");
+  block->append (factory.create<jit_cond_branch> (check, body, tail));
+  block = body;
+
+  tree_statement_list *loop_body = wc.body ();
+  bool all_breaking = false;
+  if (loop_body)
+    {
+      try
+        {
+          loop_body->accept (*this);
+        }
+      catch (const jit_break_exception&)
+        {
+          all_breaking = true;
+        }
+    }
+
+  finish_breaks (tail, breaks);
+
+  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;
+}
+
+void
+jit_convert::visit_do_until_command (tree_do_until_command&)
+{
+  throw jit_fail_exception ();
+}
+
+void
+jit_convert::initialize (symbol_table::scope_id s)
+{
+  scope = s;
+  iterator_count = 0;
+  for_bounds_count = 0;
+  short_count = 0;
+  jit_instruction::reset_ids ();
+
+  entry_block = factory.create<jit_block> ("body");
+  final_block = factory.create<jit_block> ("final");
+  blocks.push_back (entry_block);
+  entry_block->mark_alive ();
+  block = entry_block;
+}
+
+jit_call *
+jit_convert::create_checked_impl (jit_call *ret)
+{
+  block->append (ret);
+
+  jit_block *normal = factory.create<jit_block> (block->name ());
+  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;
+
+  return ret;
+}
+
+jit_variable *
+jit_convert::find_variable (const std::string& vname) const
+{
+  variable_map::const_iterator iter;
+  iter = vmap.find (vname);
+  return iter != vmap.end () ? iter->second : 0;
+}
+
+jit_variable *
+jit_convert::get_variable (const std::string& vname)
+{
+  jit_variable *ret = find_variable (vname);
+  if (ret)
+    return ret;
+
+  symbol_table::symbol_record record = symbol_table::find_symbol (vname, scope);
+  if (record.is_persistent () || record.is_global ())
+    throw jit_fail_exception ("Persistent and global not yet supported");
+
+  if (converting_function)
+    return create_variable (vname, jit_typeinfo::get_any (), false);
+  else
+    {
+      octave_value val = record.varval ();
+      jit_type *type = jit_typeinfo::type_of (val);
+      bounds.push_back (type_bound (type, vname));
+
+      return create_variable (vname, type);
+    }
+}
+
+jit_variable *
+jit_convert::create_variable (const std::string& vname, jit_type *type,
+                              bool isarg)
+{
+  jit_variable *var = factory.create<jit_variable> (vname);
+
+  if (isarg)
+    {
+      jit_extract_argument *extract;
+      extract = factory.create<jit_extract_argument> (type, var);
+      entry_block->prepend (extract);
+    }
+  else
+    {
+      jit_call *init = factory.create<jit_call> (&jit_typeinfo::create_undef);
+      jit_assign *assign = factory.create<jit_assign> (var, init);
+      entry_block->prepend (assign);
+      entry_block->prepend (init);
+    }
+
+  return vmap[vname] = var;
+}
+
+std::string
+jit_convert::next_name (const char *prefix, size_t& count, bool inc)
+{
+  std::stringstream ss;
+  ss << prefix << count;
+  if (inc)
+    ++count;
+  return ss.str ();
+}
+
+jit_instruction *
+jit_convert::resolve (tree_index_expression& exp, jit_value *extra_arg,
+                      bool lhs)
+{
+  std::string type = exp.type_tags ();
+  if (! (type.size () == 1 && type[0] == '('))
+    throw jit_fail_exception ("Unsupported index operation");
+
+  std::list<tree_argument_list *> args = exp.arg_lists ();
+  if (args.size () != 1)
+    throw jit_fail_exception ("Bad number of arguments in "
+                              "tree_index_expression");
+
+  tree_argument_list *arg_list = args.front ();
+  if (! arg_list)
+    throw jit_fail_exception ("null argument list");
+
+  if (arg_list->size () < 1)
+    throw jit_fail_exception ("Empty arg_list");
+
+  tree_expression *tree_object = exp.expression ();
+  jit_value *object;
+  if (lhs)
+    {
+      tree_identifier *id = dynamic_cast<tree_identifier *> (tree_object);
+      if (! id)
+        throw jit_fail_exception ("expected identifier");
+      object = get_variable (id->name ());
+    }
+  else
+    object = visit (tree_object);
+
+  size_t narg = arg_list->size ();
+  tree_argument_list::iterator iter = arg_list->begin ();
+  bool have_extra = extra_arg;
+  std::vector<jit_value *> call_args (narg + 1 + have_extra);
+  call_args[0] = object;
+
+  for (size_t idx = 0; iter != arg_list->end (); ++idx, ++iter)
+    {
+      unwind_protect prot;
+      prot.add_method (&end_context,
+                       &std::vector<jit_magic_end::context>::pop_back);
+
+      jit_magic_end::context ctx (factory, object, idx, narg);
+      end_context.push_back (ctx);
+      call_args[idx + 1] = visit (*iter);
+    }
+
+  if (extra_arg)
+    call_args[call_args.size () - 1] = extra_arg;
+
+  const jit_operation& fres = lhs ? jit_typeinfo::paren_subsasgn ()
+    : jit_typeinfo::paren_subsref ();
+
+  return create_checked (fres, call_args);
+}
+
+jit_value *
+jit_convert::do_assign (tree_expression *exp, jit_value *rhs, bool artificial)
+{
+  if (! exp)
+    throw jit_fail_exception ("NULL lhs in assign");
+
+  if (isa<tree_identifier> (exp))
+    return do_assign (exp->name (), rhs, exp->print_result (), artificial);
+  else if (tree_index_expression *idx
+           = dynamic_cast<tree_index_expression *> (exp))
+    {
+      jit_value *new_object = resolve (*idx, rhs, true);
+      do_assign (idx->expression (), new_object, true);
+
+      // FIXME: Will not work for values that must be release/grabed
+      return rhs;
+    }
+  else
+    throw jit_fail_exception ("Unsupported assignment");
+}
+
+jit_value *
+jit_convert::do_assign (const std::string& lhs, jit_value *rhs,
+                        bool print, bool artificial)
+{
+  jit_variable *var = get_variable (lhs);
+  jit_assign *assign = block->append (factory.create<jit_assign> (var, rhs));
+
+  if (artificial)
+    assign->mark_artificial ();
+
+  if (print)
+    {
+      const jit_operation& print_fn = jit_typeinfo::print_value ();
+      jit_const_string *name = factory.create<jit_const_string> (lhs);
+      block->append (factory.create<jit_call> (print_fn, name, var));
+    }
+
+  return var;
+}
+
+jit_value *
+jit_convert::visit (tree& tee)
+{
+  unwind_protect prot;
+  prot.protect_var (result);
+
+  tee.accept (*this);
+  return result;
+}
+
+void
+jit_convert::finish_breaks (jit_block *dest, const block_list& lst)
+{
+  for (block_list::const_iterator iter = lst.begin (); iter != lst.end ();
+       ++iter)
+    {
+      jit_block *b = *iter;
+      b->append (factory.create<jit_branch> (dest));
+    }
+}
+
+// -------------------- jit_convert_llvm --------------------
+llvm::Function *
+jit_convert_llvm::convert_loop (llvm::Module *module,
+                                const jit_block_list& blocks,
+                                const std::list<jit_value *>& constants)
+{
+  converting_function = false;
+
+  // for now just init arguments from entry, later we will have to do something
+  // more interesting
+  jit_block *entry_block = blocks.front ();
+  for (jit_block::iterator iter = entry_block->begin ();
+       iter != entry_block->end (); ++iter)
+    if (jit_extract_argument *extract
+        = dynamic_cast<jit_extract_argument *> (*iter))
+      argument_vec.push_back (std::make_pair (extract->name (), true));
+
+
+  jit_type *any = jit_typeinfo::get_any ();
+
+  // argument is an array of octave_base_value*, or octave_base_value**
+  llvm::Type *arg_type = any->to_llvm (); // this is octave_base_value*
+  arg_type = arg_type->getPointerTo ();
+  llvm::FunctionType *ft = llvm::FunctionType::get (llvm::Type::getVoidTy (context),
+                                                    arg_type, false);
+  function = llvm::Function::Create (ft, llvm::Function::ExternalLinkage,
+                                     "foobar", module);
+
+  try
+    {
+      prelude = llvm::BasicBlock::Create (context, "prelude", function);
+      builder.SetInsertPoint (prelude);
+
+      llvm::Value *arg = function->arg_begin ();
+      for (size_t i = 0; i < argument_vec.size (); ++i)
+        {
+          llvm::Value *loaded_arg = builder.CreateConstInBoundsGEP1_32 (arg, i);
+          arguments[argument_vec[i].first] = loaded_arg;
+        }
+
+      convert (blocks, constants);
+    } catch (const jit_fail_exception& e)
+    {
+      function->eraseFromParent ();
+      throw;
+    }
+
+  return function;
+}
+
+
+jit_function
+jit_convert_llvm::convert_function (llvm::Module *module,
+                                    const jit_block_list& blocks,
+                                    const std::list<jit_value *>& constants,
+                                    octave_user_function& fcn,
+                                    const std::vector<jit_type *>& args)
+{
+  converting_function = true;
+
+  jit_block *final_block = blocks.back ();
+  jit_return *ret = dynamic_cast<jit_return *> (final_block->back ());
+  assert (ret);
+
+  creating = jit_function (module, jit_convention::internal,
+                           "foobar", ret->result_type (), args);
+  function = creating.to_llvm ();
+
+  try
+    {
+      prelude = creating.new_block ("prelude");
+      builder.SetInsertPoint (prelude);
+
+      tree_parameter_list *plist = fcn.parameter_list ();
+      if (plist)
+        {
+          tree_parameter_list::iterator piter = plist->begin ();
+          tree_parameter_list::iterator pend = plist->end ();
+          for (size_t i = 0; i < args.size () && piter != pend; ++i, ++piter)
+            {
+              tree_decl_elt *elt = *piter;
+              std::string arg_name = elt->name ();
+              arguments[arg_name] = creating.argument (builder, i);
+            }
+        }
+
+      convert (blocks, constants);
+    } catch (const jit_fail_exception& e)
+    {
+      function->eraseFromParent ();
+      throw;
+    }
+
+  return creating;
+}
+
+void
+jit_convert_llvm::convert (const jit_block_list& blocks,
+                           const std::list<jit_value *>& constants)
+{
+  std::list<jit_block *>::const_iterator biter;
+  for (biter = blocks.begin (); biter != blocks.end (); ++biter)
+    {
+      jit_block *jblock = *biter;
+      llvm::BasicBlock *block = llvm::BasicBlock::Create (context,
+                                                          jblock->name (),
+                                                          function);
+      jblock->stash_llvm (block);
+    }
+
+  jit_block *first = *blocks.begin ();
+  builder.CreateBr (first->to_llvm ());
+
+  // constants aren't in the IR, we visit those first
+  for (std::list<jit_value *>::const_iterator iter = constants.begin ();
+       iter != constants.end (); ++iter)
+    if (! isa<jit_instruction> (*iter))
+      visit (*iter);
+
+  // convert all instructions
+  for (biter = blocks.begin (); biter != blocks.end (); ++biter)
+    visit (*biter);
+
+  // now finish phi nodes
+  for (biter = blocks.begin (); biter != blocks.end (); ++biter)
+    {
+      jit_block& block = **biter;
+      for (jit_block::iterator piter = block.begin ();
+           piter != block.end () && isa<jit_phi> (*piter); ++piter)
+        {
+          jit_instruction *phi = *piter;
+          finish_phi (static_cast<jit_phi *> (phi));
+        }
+    }
+}
+
+void
+jit_convert_llvm::finish_phi (jit_phi *phi)
+{
+  llvm::PHINode *llvm_phi = phi->to_llvm ();
+  for (size_t i = 0; i < phi->argument_count (); ++i)
+    {
+      llvm::BasicBlock *pred = phi->incomming_llvm (i);
+      llvm_phi->addIncoming (phi->argument_llvm (i), pred);
+    }
+}
+
+void
+jit_convert_llvm::visit (jit_const_string& cs)
+{
+  cs.stash_llvm (builder.CreateGlobalStringPtr (cs.value ()));
+}
+
+void
+jit_convert_llvm::visit (jit_const_bool& cb)
+{
+  cb.stash_llvm (llvm::ConstantInt::get (cb.type_llvm (), cb.value ()));
+}
+
+void
+jit_convert_llvm::visit (jit_const_scalar& cs)
+{
+  cs.stash_llvm (llvm::ConstantFP::get (cs.type_llvm (), cs.value ()));
+}
+
+void
+jit_convert_llvm::visit (jit_const_complex& cc)
+{
+  llvm::Type *scalar_t = jit_typeinfo::get_scalar_llvm ();
+  Complex value = cc.value ();
+  llvm::Value *real = llvm::ConstantFP::get (scalar_t, value.real ());
+  llvm::Value *imag = llvm::ConstantFP::get (scalar_t, value.imag ());
+  cc.stash_llvm (jit_typeinfo::create_complex (real, imag));
+}
+
+void jit_convert_llvm::visit (jit_const_index& ci)
+{
+  ci.stash_llvm (llvm::ConstantInt::get (ci.type_llvm (), ci.value ()));
+}
+
+void
+jit_convert_llvm::visit (jit_const_range& cr)
+{
+  llvm::StructType *stype = llvm::cast<llvm::StructType>(cr.type_llvm ());
+  llvm::Type *scalar_t = jit_typeinfo::get_scalar_llvm ();
+  llvm::Type *idx = jit_typeinfo::get_index_llvm ();
+  const jit_range& rng = cr.value ();
+
+  llvm::Constant *constants[4];
+  constants[0] = llvm::ConstantFP::get (scalar_t, rng.base);
+  constants[1] = llvm::ConstantFP::get (scalar_t, rng.limit);
+  constants[2] = llvm::ConstantFP::get (scalar_t, rng.inc);
+  constants[3] = llvm::ConstantInt::get (idx, rng.nelem);
+
+  llvm::Value *as_llvm;
+  as_llvm = llvm::ConstantStruct::get (stype,
+                                       llvm::makeArrayRef (constants, 4));
+  cr.stash_llvm (as_llvm);
+}
+
+void
+jit_convert_llvm::visit (jit_block& b)
+{
+  llvm::BasicBlock *block = b.to_llvm ();
+  builder.SetInsertPoint (block);
+  for (jit_block::iterator iter = b.begin (); iter != b.end (); ++iter)
+    visit (*iter);
+}
+
+void
+jit_convert_llvm::visit (jit_branch& b)
+{
+  b.stash_llvm (builder.CreateBr (b.successor_llvm ()));
+}
+
+void
+jit_convert_llvm::visit (jit_cond_branch& cb)
+{
+  llvm::Value *cond = cb.cond_llvm ();
+  llvm::Value *br;
+  br = builder.CreateCondBr (cond, cb.successor_llvm (0),
+                             cb.successor_llvm (1));
+  cb.stash_llvm (br);
+}
+
+void
+jit_convert_llvm::visit (jit_call& call)
+{
+  const jit_function& ol = call.overload ();
+
+  std::vector<jit_value *> args (call.arguments ().size ());
+  for (size_t i = 0; i < args.size (); ++i)
+    args[i] = call.argument (i);
+
+  llvm::Value *ret = ol.call (builder, args);
+  call.stash_llvm (ret);
+}
+
+void
+jit_convert_llvm::visit (jit_extract_argument& extract)
+{
+  llvm::Value *arg = arguments[extract.name ()];
+  assert (arg);
+
+  if (converting_function)
+    extract.stash_llvm (arg);
+  else
+    {
+      arg = builder.CreateLoad (arg);
+
+      const jit_function& ol = extract.overload ();
+      extract.stash_llvm (ol.call (builder, arg));
+    }
+}
+
+void
+jit_convert_llvm::visit (jit_store_argument& store)
+{
+  const jit_function& ol = store.overload ();
+  llvm::Value *arg_value = ol.call (builder, store.result ());
+  llvm::Value *arg = arguments[store.name ()];
+  store.stash_llvm (builder.CreateStore (arg_value, arg));
+}
+
+void
+jit_convert_llvm::visit (jit_return& ret)
+{
+  jit_value *res = ret.result ();
+
+  if (converting_function)
+    creating.do_return (builder, res->to_llvm (), false);
+  else
+    {
+      if (res)
+        builder.CreateRet (res->to_llvm ());
+      else
+        builder.CreateRetVoid ();
+    }
+}
+
+void
+jit_convert_llvm::visit (jit_phi& phi)
+{
+  // we might not have converted all incoming branches, so we don't
+  // set incomming branches now
+  llvm::PHINode *node = llvm::PHINode::Create (phi.type_llvm (),
+                                               phi.argument_count ());
+  builder.Insert (node);
+  phi.stash_llvm (node);
+}
+
+void
+jit_convert_llvm::visit (jit_variable&)
+{
+  throw jit_fail_exception ("ERROR: SSA construction should remove all variables");
+}
+
+void
+jit_convert_llvm::visit (jit_error_check& check)
+{
+  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);
+}
+
+void
+jit_convert_llvm::visit (jit_assign& assign)
+{
+  jit_value *new_value = assign.src ();
+  assign.stash_llvm (new_value->to_llvm ());
+
+  if (assign.artificial ())
+    return;
+
+  jit_value *overwrite = assign.overwrite ();
+  if (isa<jit_assign_base> (overwrite))
+    {
+      const jit_function& ol = jit_typeinfo::get_release (overwrite->type ());
+      if (ol.valid ())
+        ol.call (builder, overwrite);
+    }
+}
+
+void
+jit_convert_llvm::visit (jit_argument&)
+{}
+
+void
+jit_convert_llvm::visit (jit_magic_end& me)
+{
+  const jit_function& ol = me.overload ();
+
+  jit_magic_end::context ctx = me.resolve_context ();
+  llvm::Value *ret = ol.call (builder, ctx.value, ctx.index, ctx.count);
+  me.stash_llvm (ret);
+}
+
+// -------------------- jit_infer --------------------
+jit_infer::jit_infer (jit_factory& afactory, jit_block_list& ablocks,
+                      const variable_map& avmap)
+  : blocks (ablocks), factory (afactory), vmap (avmap) {}
+
+void
+jit_infer::infer (void)
+{
+  construct_ssa ();
+
+  // initialize the worklist to instructions derived from constants
+  const std::list<jit_value *>& constants = factory.constants ();
+  for (std::list<jit_value *>::const_iterator iter = constants.begin ();
+       iter != constants.end (); ++iter)
+    append_users (*iter);
+
+  // the entry block terminator may be a regular branch statement
+  if (entry_block ().terminator ())
+    push_worklist (entry_block ().terminator ());
+
+  // FIXME: Describe algorithm here
+  while (worklist.size ())
+    {
+      jit_instruction *next = worklist.front ();
+      worklist.pop_front ();
+      next->stash_in_worklist (false);
+
+      if (next->infer ())
+        {
+          // terminators need to be handles specially
+          if (jit_terminator *term = dynamic_cast<jit_terminator *> (next))
+            append_users_term (term);
+          else
+            append_users (next);
+        }
+    }
+
+  remove_dead ();
+  blocks.label ();
+  place_releases ();
+  simplify_phi ();
+}
+
+void
+jit_infer::append_users (jit_value *v)
+{
+  for (jit_use *use = v->first_use (); use; use = use->next ())
+    push_worklist (use->user ());
+}
+
+void
+jit_infer::append_users_term (jit_terminator *term)
+{
+  for (size_t i = 0; i < term->successor_count (); ++i)
+    {
+      if (term->alive (i))
+        {
+          jit_block *succ = term->successor (i);
+          for (jit_block::iterator iter = succ->begin (); iter != succ->end ()
+                 && isa<jit_phi> (*iter); ++iter)
+            push_worklist (*iter);
+
+          jit_terminator *sterm = succ->terminator ();
+          if (sterm)
+            push_worklist (sterm);
+        }
+    }
+}
+
+void
+jit_infer::construct_ssa (void)
+{
+  blocks.label ();
+  final_block ().compute_idom (entry_block ());
+  entry_block ().compute_df ();
+  entry_block ().create_dom_tree ();
+
+  // insert phi nodes where needed, this is done on a per variable basis
+  for (variable_map::const_iterator iter = vmap.begin (); iter != vmap.end ();
+       ++iter)
+    {
+      jit_block::df_set visited, added_phi;
+      std::list<jit_block *> ssa_worklist;
+      iter->second->use_blocks (visited);
+      ssa_worklist.insert (ssa_worklist.begin (), visited.begin (),
+                           visited.end ());
+
+      while (ssa_worklist.size ())
+        {
+          jit_block *b = ssa_worklist.front ();
+          ssa_worklist.pop_front ();
+
+          for (jit_block::df_iterator diter = b->df_begin ();
+               diter != b->df_end (); ++diter)
+            {
+              jit_block *dblock = *diter;
+              if (! added_phi.count (dblock))
+                {
+                  jit_phi *phi = factory.create<jit_phi> (iter->second,
+                                                  dblock->use_count ());
+                  dblock->prepend (phi);
+                  added_phi.insert (dblock);
+                }
+
+              if (! visited.count (dblock))
+                {
+                  ssa_worklist.push_back (dblock);
+                  visited.insert (dblock);
+                }
+            }
+        }
+    }
+
+  do_construct_ssa (entry_block (), entry_block ().visit_count ());
+}
+
+void
+jit_infer::do_construct_ssa (jit_block& ablock, size_t avisit_count)
+{
+  if (ablock.visited (avisit_count))
+    return;
+
+  // replace variables with their current SSA value
+  for (jit_block::iterator iter = ablock.begin (); iter != ablock.end ();
+       ++iter)
+    {
+      jit_instruction *instr = *iter;
+      instr->construct_ssa ();
+      instr->push_variable ();
+    }
+
+  // finish phi nodes of successors
+  for (size_t i = 0; i < ablock.successor_count (); ++i)
+    {
+      jit_block *finish = ablock.successor (i);
+
+      for (jit_block::iterator iter = finish->begin (); iter != finish->end ()
+             && isa<jit_phi> (*iter);)
+        {
+          jit_phi *phi = static_cast<jit_phi *> (*iter);
+          jit_variable *var = phi->dest ();
+          ++iter;
+
+          if (var->has_top ())
+            phi->add_incomming (&ablock, var->top ());
+          else
+            {
+              // temporaries may have extranious phi nodes which can be removed
+              assert (! phi->use_count ());
+              assert (var->name ().size () && var->name ()[0] == '#');
+              phi->remove ();
+            }
+        }
+    }
+
+  for (size_t i = 0; i < ablock.dom_successor_count (); ++i)
+    do_construct_ssa (*ablock.dom_successor (i), avisit_count);
+
+  ablock.pop_all ();
+}
+
+void
+jit_infer::place_releases (void)
+{
+  std::set<jit_value *> temporaries;
+  for (jit_block_list::iterator iter = blocks.begin (); iter != blocks.end ();
+       ++iter)
+    {
+      jit_block& ablock = **iter;
+      if (ablock.id () != jit_block::NO_ID)
+        {
+          release_temp (ablock, temporaries);
+          release_dead_phi (ablock);
+        }
+    }
+}
+
+void
+jit_infer::push_worklist (jit_instruction *instr)
+{
+  if (! instr->in_worklist ())
+    {
+      instr->stash_in_worklist (true);
+      worklist.push_back (instr);
+    }
+}
+
+void
+jit_infer::remove_dead ()
+{
+  jit_block_list::iterator biter;
+  for (biter = blocks.begin (); biter != blocks.end (); ++biter)
+    {
+      jit_block *b = *biter;
+      if (b->alive ())
+        {
+          for (jit_block::iterator iter = b->begin (); iter != b->end ()
+                 && isa<jit_phi> (*iter);)
+            {
+              jit_phi *phi = static_cast<jit_phi *> (*iter);
+              if (phi->prune ())
+                iter = b->remove (iter);
+              else
+                ++iter;
+            }
+        }
+    }
+
+  for (biter = blocks.begin (); biter != blocks.end ();)
+    {
+      jit_block *b = *biter;
+      if (b->alive ())
+        {
+          // FIXME: A special case for jit_error_check, if we generalize to
+          // we will need to change!
+          jit_terminator *term = b->terminator ();
+          if (term && term->successor_count () == 2 && ! term->alive (0))
+            {
+              jit_block *succ = term->successor (1);
+              term->remove ();
+              jit_branch *abreak = factory.create<jit_branch> (succ);
+              b->append (abreak);
+              abreak->infer ();
+            }
+
+          ++biter;
+        }
+      else
+        {
+          jit_terminator *term = b->terminator ();
+          if (term)
+            term->remove ();
+          biter = blocks.erase (biter);
+        }
+    }
+}
+
+void
+jit_infer::release_dead_phi (jit_block& ablock)
+{
+  jit_block::iterator iter = ablock.begin ();
+  while (iter != ablock.end () && isa<jit_phi> (*iter))
+    {
+      jit_phi *phi = static_cast<jit_phi *> (*iter);
+      ++iter;
+
+      jit_use *use = phi->first_use ();
+      if (phi->use_count () == 1 && isa<jit_assign> (use->user ()))
+        {
+          // instead of releasing on assign, release on all incomming branches,
+          // this can get rid of casts inside loops
+          for (size_t i = 0; i < phi->argument_count (); ++i)
+            {
+              jit_value *arg = phi->argument (i);
+              if (! arg->needs_release ())
+                continue;
+
+              jit_block *inc = phi->incomming (i);
+              jit_block *split = inc->maybe_split (factory, blocks, ablock);
+              jit_terminator *term = split->terminator ();
+              jit_call *release
+                = factory.create<jit_call> (jit_typeinfo::release, arg);
+              release->infer ();
+              split->insert_before (term, release);
+            }
+
+          phi->replace_with (0);
+          phi->remove ();
+        }
+    }
+}
+
+void
+jit_infer::release_temp (jit_block& ablock, std::set<jit_value *>& temp)
+{
+  for (jit_block::iterator iter = ablock.begin (); iter != ablock.end ();
+       ++iter)
+    {
+      jit_instruction *instr = *iter;
+
+      // check for temporaries that require release and live across
+      // multiple blocks
+      if (instr->needs_release ())
+        {
+          jit_block *fu_block = instr->first_use_block ();
+          if (fu_block && fu_block != &ablock && instr->needs_release ())
+            temp.insert (instr);
+        }
+
+      if (isa<jit_call> (instr))
+        {
+          // place releases for temporary arguments
+          for (size_t i = 0; i < instr->argument_count (); ++i)
+            {
+              jit_value *arg = instr->argument (i);
+              if (! arg->needs_release ())
+                continue;
+
+              jit_call *release
+                = factory.create<jit_call> (&jit_typeinfo::release, arg);
+              release->infer ();
+              ablock.insert_after (iter, release);
+              ++iter;
+              temp.erase (arg);
+            }
+        }
+    }
+
+  if (! temp.size () || ! isa<jit_error_check> (ablock.terminator ()))
+    return;
+
+  // FIXME: If we support try/catch or unwind_protect final_block may not be the
+  // destination
+  jit_block *split = ablock.maybe_split (factory, blocks, final_block ());
+  jit_terminator *term = split->terminator ();
+  for (std::set<jit_value *>::const_iterator iter = temp.begin ();
+       iter != temp.end (); ++iter)
+    {
+      jit_value *value = *iter;
+      jit_call *release
+        = factory.create<jit_call> (&jit_typeinfo::release, value);
+      split->insert_before (term, release);
+      release->infer ();
+    }
+}
+
+void
+jit_infer::simplify_phi (void)
+{
+  for (jit_block_list::iterator biter = blocks.begin (); biter != blocks.end ();
+       ++biter)
+    {
+      jit_block &ablock = **biter;
+      for (jit_block::iterator iter = ablock.begin (); iter != ablock.end ()
+             && isa<jit_phi> (*iter); ++iter)
+        simplify_phi (*static_cast<jit_phi *> (*iter));
+    }
+}
+
+void
+jit_infer::simplify_phi (jit_phi& phi)
+{
+  jit_block& pblock = *phi.parent ();
+  const jit_operation& cast_fn = jit_typeinfo::cast (phi.type ());
+  jit_variable *dest = phi.dest ();
+  for (size_t i = 0; i < phi.argument_count (); ++i)
+    {
+      jit_value *arg = phi.argument (i);
+      if (arg->type () != phi.type ())
+        {
+          jit_block *pred = phi.incomming (i);
+          jit_block *split = pred->maybe_split (factory, blocks, pblock);
+          jit_terminator *term = split->terminator ();
+          jit_instruction *cast = factory.create<jit_call> (cast_fn, arg);
+          jit_assign *assign = factory.create<jit_assign> (dest, cast);
+
+          split->insert_before (term, cast);
+          split->insert_before (term, assign);
+          cast->infer ();
+          assign->infer ();
+          phi.stash_argument (i, assign);
+        }
+    }
+}
+
+// -------------------- tree_jit --------------------
+
+tree_jit::tree_jit (void) : module (0), engine (0)
+{
+}
+
+tree_jit::~tree_jit (void)
+{}
+
+bool
+tree_jit::execute (tree_simple_for_command& cmd, const octave_value& bounds)
+{
+  return instance ().do_execute (cmd, bounds);
+}
+
+bool
+tree_jit::execute (tree_while_command& cmd)
+{
+  return instance ().do_execute (cmd);
+}
+
+bool
+tree_jit::execute (octave_user_function& fcn, const octave_value_list& args,
+                   octave_value_list& retval)
+{
+  return instance ().do_execute (fcn, args, retval);
+}
+
+tree_jit&
+tree_jit::instance (void)
+{
+  static tree_jit ret;
+  return ret;
+}
+
+bool
+tree_jit::initialize (void)
+{
+  if (engine)
+    return true;
+
+  if (! module)
+    {
+      llvm::InitializeNativeTarget ();
+      module = new llvm::Module ("octave", context);
+    }
+
+  // sometimes this fails pre main
+  engine = llvm::ExecutionEngine::createJIT (module);
+
+  if (! engine)
+    return false;
+
+  module_pass_manager = new llvm::PassManager ();
+  module_pass_manager->add (llvm::createAlwaysInlinerPass ());
+
+  pass_manager = new llvm::FunctionPassManager (module);
+  pass_manager->add (new llvm::TargetData(*engine->getTargetData ()));
+  pass_manager->add (llvm::createCFGSimplificationPass ());
+  pass_manager->add (llvm::createBasicAliasAnalysisPass ());
+  pass_manager->add (llvm::createPromoteMemoryToRegisterPass ());
+  pass_manager->add (llvm::createInstructionCombiningPass ());
+  pass_manager->add (llvm::createReassociatePass ());
+  pass_manager->add (llvm::createGVNPass ());
+  pass_manager->add (llvm::createCFGSimplificationPass ());
+  pass_manager->doInitialization ();
+
+  jit_typeinfo::initialize (module, engine);
+
+  return true;
+}
+
+bool
+tree_jit::do_execute (tree_simple_for_command& cmd, const octave_value& bounds)
+{
+  const size_t MIN_TRIP_COUNT = 1000;
+
+  size_t tc = trip_count (bounds);
+  if (! tc || ! initialize () || ! enabled ())
+    return false;
+
+  jit_info::vmap extra_vars;
+  extra_vars["#for_bounds0"] = &bounds;
+
+  jit_info *info = cmd.get_info ();
+  if (! info || ! info->match (extra_vars))
+    {
+      if (tc < MIN_TRIP_COUNT)
+        return false;
+
+      delete info;
+      info = new jit_info (*this, cmd, bounds);
+      cmd.stash_info (info);
+    }
+
+  return info->execute (extra_vars);
+}
+
+bool
+tree_jit::do_execute (tree_while_command& cmd)
+{
+  if (! initialize () || ! enabled ())
+    return false;
+
+  jit_info *info = cmd.get_info ();
+  if (! info || ! info->match ())
+    {
+      delete info;
+      info = new jit_info (*this, cmd);
+      cmd.stash_info (info);
+    }
+
+  return info->execute ();
+}
+
+bool
+tree_jit::do_execute (octave_user_function& fcn, const octave_value_list& args,
+                      octave_value_list& retval)
+{
+  if (! initialize () || ! enabled ())
+    return false;
+
+  jit_function_info *info = fcn.get_info ();
+    if (! info || ! info->match (args))
+      {
+        delete info;
+        info = new jit_function_info (*this, fcn, args);
+        fcn.stash_info (info);
+      }
+
+    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
+{
+  if (bounds.is_range ())
+    {
+      Range rng = bounds.range_value ();
+      return rng.nelem ();
+    }
+
+  // unsupported type
+  return 0;
+}
+
+
+void
+tree_jit::optimize (llvm::Function *fn)
+{
+  if (Venable_jit_debugging)
+    llvm::verifyModule (*module);
+
+  module_pass_manager->run (*module);
+  pass_manager->run (*fn);
+
+  if (Venable_jit_debugging)
+    {
+      std::string error;
+      llvm::raw_fd_ostream fout ("test.bc", error,
+                                 llvm::raw_fd_ostream::F_Binary);
+      llvm::WriteBitcodeToFile (module, fout);
+    }
+}
+
+// -------------------- jit_function_info --------------------
+jit_function_info::jit_function_info (tree_jit& tjit,
+                                      octave_user_function& fcn,
+                                      const octave_value_list& ov_args)
+  : argument_types (ov_args.length ()), function (0)
+{
+  size_t nargs = ov_args.length ();
+  for (size_t i = 0; i < nargs; ++i)
+    argument_types[i] = jit_typeinfo::type_of (ov_args(i));
+
+  jit_function raw_fn;
+  jit_function wrapper;
+
+  try
+    {
+      jit_convert conv (fcn, argument_types);
+      jit_infer infer (conv.get_factory (), conv.get_blocks (),
+                       conv.get_variable_map ());
+      infer.infer ();
+
+      if (Venable_jit_debugging)
+        {
+          jit_block_list& blocks = infer.get_blocks ();
+          blocks.label ();
+          std::cout << "-------------------- Compiling function ";
+          std::cout << "--------------------\n";
+
+          tree_print_code tpc (std::cout);
+          tpc.visit_octave_user_function_header (fcn);
+          tpc.visit_statement_list (*fcn.body ());
+          tpc.visit_octave_user_function_trailer (fcn);
+          blocks.print (std::cout, "octave jit ir");
+        }
+
+      jit_factory& factory = conv.get_factory ();
+      llvm::Module *module = tjit.get_module ();
+      jit_convert_llvm to_llvm;
+      raw_fn = to_llvm.convert_function (module, infer.get_blocks (),
+                                         factory.constants (), fcn,
+                                         argument_types);
+
+      if (Venable_jit_debugging)
+        {
+          std::cout << "-------------------- raw function ";
+          std::cout << "--------------------\n";
+          std::cout << *raw_fn.to_llvm () << std::endl;
+          llvm::verifyFunction (*raw_fn.to_llvm ());
+        }
+
+      std::string wrapper_name = fcn.name () + "_wrapper";
+      jit_type *any_t = jit_typeinfo::get_any ();
+      std::vector<jit_type *> wrapper_args (1, jit_typeinfo::get_any_ptr ());
+      wrapper = jit_function (module, jit_convention::internal, wrapper_name,
+                              any_t, wrapper_args);
+
+      llvm::BasicBlock *wrapper_body = wrapper.new_block ();
+      builder.SetInsertPoint (wrapper_body);
+
+      llvm::Value *wrapper_arg = wrapper.argument (builder, 0);
+      std::vector<llvm::Value *> raw_args (nargs);
+      for (size_t i = 0; i < nargs; ++i)
+        {
+          llvm::Value *arg;
+          arg = builder.CreateConstInBoundsGEP1_32 (wrapper_arg, i);
+          arg = builder.CreateLoad (arg);
+
+          jit_type *arg_type = argument_types[i];
+          const jit_function& cast = jit_typeinfo::cast (arg_type, any_t);
+          raw_args[i] = cast.call (builder, arg);
+        }
+
+      llvm::Value *result = raw_fn.call (builder, raw_args);
+      if (raw_fn.result ())
+        {
+          jit_type *raw_result_t = raw_fn.result ();
+          const jit_function& cast = jit_typeinfo::cast (any_t, raw_result_t);
+          result = cast.call (builder, result);
+        }
+      else
+        {
+          llvm::Value *zero = builder.getInt32 (0);
+          result = builder.CreateBitCast (zero, any_t->to_llvm ());
+        }
+
+      wrapper.do_return (builder, result);
+
+      llvm::Function *llvm_function = wrapper.to_llvm ();
+      tjit.optimize (llvm_function);
+
+      if (Venable_jit_debugging)
+        {
+          std::cout << "-------------------- optimized and wrapped ";
+          std::cout << "--------------------\n";
+          std::cout << *llvm_function << std::endl;
+          llvm::verifyFunction (*llvm_function);
+        }
+
+      llvm::ExecutionEngine* engine = tjit.get_engine ();
+      void *void_fn = engine->getPointerToFunction (llvm_function);
+      function = reinterpret_cast<jited_function> (void_fn);
+    }
+  catch (const jit_fail_exception& e)
+    {
+      argument_types.clear ();
+
+      if (Venable_jit_debugging)
+        {
+          if (e.known ())
+            std::cout << "jit fail: " << e.what () << std::endl;
+        }
+
+      wrapper.erase ();
+      raw_fn.erase ();
+    }
+}
+
+bool
+jit_function_info::execute (const octave_value_list& ov_args,
+                            octave_value_list& retval) const
+{
+  if (! function)
+    return false;
+
+  // TODO figure out a way to delete ov_args so we avoid duplicating refcount
+  size_t nargs = ov_args.length ();
+  std::vector<octave_base_value *> args (nargs);
+  for (size_t i = 0; i < nargs; ++i)
+    {
+      octave_base_value *obv = ov_args(i).internal_rep ();
+      obv->grab ();
+      args[i] = obv;
+    }
+
+  octave_base_value *ret = function (&args[0]);
+  if (ret)
+    retval(0) = octave_value (ret);
+
+  octave_quit ();
+
+  return true;
+}
+
+bool
+jit_function_info::match (const octave_value_list& ov_args) const
+{
+  if (! function)
+    return true;
+
+  size_t nargs = ov_args.length ();
+  if (nargs != argument_types.size ())
+    return false;
+
+  for (size_t i = 0; i < nargs; ++i)
+    if (jit_typeinfo::type_of (ov_args(i)) != argument_types[i])
+      return false;
+
+  return true;
+}
+
+// -------------------- jit_info --------------------
+jit_info::jit_info (tree_jit& tjit, tree& tee)
+  : engine (tjit.get_engine ()), function (0), llvm_function (0)
+{
+  compile (tjit, tee);
+}
+
+jit_info::jit_info (tree_jit& tjit, tree& tee, const octave_value& for_bounds)
+  : engine (tjit.get_engine ()), function (0), llvm_function (0)
+{
+  compile (tjit, tee, jit_typeinfo::type_of (for_bounds));
+}
+
+jit_info::~jit_info (void)
+{
+  if (llvm_function)
+    llvm_function->eraseFromParent ();
+}
+
+bool
+jit_info::execute (const vmap& extra_vars) const
+{
+  if (! function)
+    return false;
+
+  std::vector<octave_base_value *> real_arguments (arguments.size ());
+  for (size_t i = 0; i < arguments.size (); ++i)
+    {
+      if (arguments[i].second)
+        {
+          octave_value current = find (extra_vars, arguments[i].first);
+          octave_base_value *obv = current.internal_rep ();
+          obv->grab ();
+          real_arguments[i] = obv;
+        }
+    }
+
+  function (&real_arguments[0]);
+
+  for (size_t i = 0; i < arguments.size (); ++i)
+    {
+      const std::string& name = arguments[i].first;
+
+      // do not store for loop bounds temporary
+      if (name.size () && name[0] != '#')
+        symbol_table::assign (arguments[i].first, real_arguments[i]);
+    }
+
+  octave_quit ();
+
+  return true;
+}
+
+bool
+jit_info::match (const vmap& extra_vars) const
+{
+  if (! function)
+    return true;
+
+  for (size_t i = 0; i < bounds.size (); ++i)
+    {
+      const std::string& arg_name = bounds[i].second;
+      octave_value value = find (extra_vars, arg_name);
+      jit_type *type = jit_typeinfo::type_of (value);
+
+      // FIXME: Check for a parent relationship
+      if (type != bounds[i].first)
+        return false;
+    }
+
+  return true;
+}
+
+void
+jit_info::compile (tree_jit& tjit, tree& tee, jit_type *for_bounds)
+{
+  try
+    {
+      jit_convert conv (tee, for_bounds);
+      jit_infer infer (conv.get_factory (), conv.get_blocks (),
+                       conv.get_variable_map ());
+
+      infer.infer ();
+
+      if (Venable_jit_debugging)
+        {
+          jit_block_list& blocks = infer.get_blocks ();
+          blocks.label ();
+          std::cout << "-------------------- Compiling tree --------------------\n";
+          std::cout << tee.str_print_code () << std::endl;
+          blocks.print (std::cout, "octave jit ir");
+        }
+
+      jit_factory& factory = conv.get_factory ();
+      jit_convert_llvm to_llvm;
+      llvm_function = to_llvm.convert_loop (tjit.get_module (),
+                                            infer.get_blocks (),
+                                            factory.constants ());
+      arguments = to_llvm.get_arguments ();
+      bounds = conv.get_bounds ();
+    }
+  catch (const jit_fail_exception& e)
+    {
+      if (Venable_jit_debugging)
+        {
+          if (e.known ())
+            std::cout << "jit fail: " << e.what () << std::endl;
+        }
+    }
+
+  if (llvm_function)
+    {
+      if (Venable_jit_debugging)
+        {
+          std::cout << "-------------------- llvm ir --------------------";
+          std::cout << *llvm_function << std::endl;
+          llvm::verifyFunction (*llvm_function);
+        }
+
+      tjit.optimize (llvm_function);
+
+      if (Venable_jit_debugging)
+        {
+          std::cout << "-------------------- optimized llvm ir "
+                    << "--------------------\n";
+          std::cout << *llvm_function << std::endl;
+        }
+
+      void *void_fn = engine->getPointerToFunction (llvm_function);
+      function = reinterpret_cast<jited_function> (void_fn);
+    }
+}
+
+octave_value
+jit_info::find (const vmap& extra_vars, const std::string& vname) const
+{
+  vmap::const_iterator iter = extra_vars.find (vname);
+  return iter == extra_vars.end () ? symbol_table::varval (vname)
+    : *iter->second;
+}
+
+#endif
+
+DEFUN (enable_jit_debugging, args, nargout,
+  "-*- texinfo -*-\n\
+@deftypefn  {Built-in Function} {@var{val} =} enable_jit_debugging ()\n\
+@deftypefnx {Built-in Function} {@var{old_val} =} enable_jit_debugging (@var{new_val})\n\
+@deftypefnx {Built-in Function} {} enable_jit_debugging (@var{new_val}, \"local\")\n\
+Query or set the internal variable that determines whether\n\
+debugging/tracing is enabled for Octave's JIT compiler.\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{enable_jit_compiler}\n\
+@end deftypefn")
+{
+#if defined (HAVE_LLVM)
+  return SET_INTERNAL_VARIABLE (enable_jit_debugging);
+#else
+  warning ("enable_jit_debugging: JIT compiling not available in this version of Octave");
+  return octave_value ();
+#endif
+}
+
+DEFUN (enable_jit_compiler, args, nargout,
+  "-*- texinfo -*-\n\
+@deftypefn  {Built-in Function} {@var{val} =} enable_jit_compiler ()\n\
+@deftypefnx {Built-in Function} {@var{old_val} =} enable_jit_compiler (@var{new_val})\n\
+@deftypefnx {Built-in Function} {} enable_jit_compiler (@var{new_val}, \"local\")\n\
+Query or set the internal variable that enables Octave's JIT compiler.\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{enable_jit_debugging}\n\
+@end deftypefn")
+{
+#if defined (HAVE_LLVM)
+  return SET_INTERNAL_VARIABLE (enable_jit_compiler);
+#else
+  warning ("enable_jit_compiler: JIT compiling not available in this version of Octave");
+  return octave_value ();
+#endif
+}
+
+/*
+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
+%!   result = result + inc * (1/3 * ii * ii);
+%! endfor
+%! assert (abs (result - 1/9) < 1e-5);
+
+%!test
+%! inc = 1e-5;
+%! result = 0;
+%! for ii = 0:inc:1
+%!   # the ^ operator's result is complex
+%!   result = result + inc * (1/3 * ii ^ 2);
+%! endfor
+%! 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
+%!   mat(i) = i;
+%! endfor
+%! assert (mat == 1:nr);
+
+%!test
+%! nr = 1001;
+%! mat = 1:nr;
+%! mat(end) = 0; # force mat to a matrix
+%! total = 0;
+%! for i = 1:nr
+%!   total = mat(i) + total;
+%! endfor
+%! assert (sum (mat) == total);
+
+%!test
+%! nr = 1001;
+%! mat = [3 1 5];
+%! try
+%!   for i = 1:nr
+%!     if i > 500
+%!       result = mat(100);
+%!     else
+%!       result = i;
+%!     endif
+%!   endfor
+%! catch
+%! end
+%! assert (result == 500);
+
+%!function result = gen_test (n)
+%!  result = double (rand (1, n) > .01);
+%!endfunction
+
+%!function z = vectorized (A, K)
+%!  temp = ones (1, K);
+%!  z = conv (A, temp);
+%!  z = z > K-1;
+%!  z = conv (z, temp);
+%!  z = z(K:end-K+1);
+%!  z = z >= 1;
+%!endfunction
+
+%!function z = loopy (A, K)
+%!  z = A;
+%!  n = numel (A);
+%!  counter = 0;
+%!  for ii=1:n
+%!    if z(ii)
+%!      counter = counter + 1;
+%!    else
+%!      if counter > 0 && counter < K
+%!        z(ii-counter:ii-1) = 0;
+%!      endif
+%!      counter = 0;
+%!    endif
+%!  endfor
+%!
+%!  if counter > 0 && counter < K
+%!    z(end-counter+1:end) = 0;
+%!  endif
+%!endfunction
+
+%!test
+%! test_set = gen_test (10000);
+%! assert (all (vectorized (test_set, 3) == loopy (test_set, 3)));
+
+%!test
+%! niter = 1001;
+%! i = 0;
+%! while (i < niter)
+%!   i = i + 1;
+%! endwhile
+%! assert (i == niter);
+
+%!test
+%! niter = 1001;
+%! result = 0;
+%! m = [5 10];
+%! for i=1:niter
+%!   result = result + m(end);
+%! endfor
+%! assert (result == m(end) * niter);
+
+%!test
+%! ndim = 100;
+%! result = 0;
+%! m = zeros (ndim);
+%! m(:) = 1:ndim^2;
+%! i = 1;
+%! while (i <= ndim)
+%!   for j = 1:ndim
+%!     result = result + m(i, j);
+%!    endfor
+%!   i = i + 1;
+%! endwhile
+%! assert (result == sum (sum (m)));
+
+%!test
+%! ndim = 100;
+%! m = zeros (ndim);
+%! i = 1;
+%! while (i <= ndim)
+%!   for j = 1:ndim
+%!     m(i, j) = (j - 1) * ndim + i;
+%!   endfor
+%!   i = i + 1;
+%! endwhile
+%! m2 = zeros (ndim);
+%! m2(:) = 1:(ndim^2);
+%! assert (all (m == m2));
+
+%!test
+%! ndim = 2;
+%! m = zeros (ndim, ndim, ndim, ndim);
+%! result = 0;
+%! i0 = 1;
+%! while (i0 <= ndim)
+%!   for i1 = 1:ndim
+%!     for i2 = 1:ndim
+%!       for i3 = 1:ndim
+%!         m(i0, i1, i2, i3) = 1;
+%!         m(i0, i1, i2, i3, 1, 1, 1, 1, 1, 1) = 1;
+%!         result = result + m(i0, i1, i2, i3);
+%!       endfor
+%!     endfor
+%!   endfor
+%!   i0 = i0 + 1;
+%! endwhile
+%! expected = ones (ndim, ndim, ndim, ndim);
+%! assert (all (m == expected));
+%! assert (result == sum (expected (:)));
+
+%!function test_divide ()
+%! state = warning ("query", "Octave:divide-by-zero").state;
+%! unwind_protect
+%!   warning ("error", "Octave:divide-by-zero");
+%!   for i=1:1e5
+%!     a = 1;
+%!     a / 0;
+%!   endfor
+%! unwind_protect_cleanup
+%!   warning (state, "Octave:divide-by-zero");
+%! end_unwind_protect
+%!endfunction
+
+%!error <division by zero> test_divide ()
+
+%!test
+%! while 1
+%!   a = 0;
+%!   result = a / 1;
+%!   break;
+%! endwhile
+%! assert (result, 0);
+
+%!test
+%! m = zeros (2, 1001);
+%! for i=1:1001
+%!   m(end, i) = i;
+%!   m(end - 1, end - i + 1) = i;
+%! endfor
+%! m2 = zeros (2, 1001);
+%! m2(1, :) = fliplr (1:1001);
+%! m2(2, :) = 1:1001;
+%! assert (m, m2);
+
+%!test
+%! m = [1 2 3];
+%! for i=1:1001
+%!   m = sin (m);
+%!   break;
+%! endfor
+%! assert (m == sin ([1  2 3]));
+
+%!test
+%! i = 0;
+%! while i < 10
+%!   i += 1;
+%! endwhile
+%! assert (i == 10);
+
+%!test
+%! i = 0;
+%! while i < 10
+%!   a = ++i;
+%! endwhile
+%! assert (i == 10);
+%! assert (a == 10);
+%!test
+%! i = 0;
+%! while i < 10
+%!   a = i++;
+%! endwhile
+%! assert (i == 10);
+%! assert (a == 9);
+
+%!test
+%! num = 2;
+%! a = zeros (1, num);
+%! i = 1;
+%! while i <= num
+%!   a(i) = norm (eye (i));
+%!   ++i;
+%! endwhile
+%! assert (a, ones (1, num));
+
+%!function test_compute_idom ()
+%! while (li <= length (l1) && si <= length (s1))
+%!   if (l1 (li) < s1 (si))
+%!     if (li == si)
+%!       break;
+%!     endif;
+%!     li++;
+%!   else
+%!     si++;
+%!   endif;
+%! endwhile
+
+%!error test_compute_idom ()
+
+%!function x = test_overload (a)
+%!  while 1
+%!    x = a;
+%!    break;
+%!  endwhile
+%!endfunction
+
+%!assert (test_overload (1), 1);
+%!assert (test_overload ([1 2]), [1 2]);
+
+%!function a = bubble (a = [3 2 1])
+%!  swapped = 1;
+%!  n = length (a);
+%!  while (swapped)
+%!    swapped = 0;
+%!    for i = 1:n-1
+%!      if a(i) > a(i + 1)
+%!        swapped = 1;
+%!        temp = a(i);
+%!        a(i) = a(i + 1);
+%!        a(i + 1) = temp;
+%!      endif
+%!    endfor
+%!  endwhile
+%!endfunction
+
+%!assert (bubble (), [1 2 3]);
+
+%!test
+%! a = 0;
+%! b = 1;
+%! for i=1:1e3
+%!   for j=1:2
+%!     a = a + b;
+%!   endfor
+%! endfor
+%! assert (a, 2000);
+%! assert (b, 1);
+
+%!test
+%! a = [1+1i 1+2i];
+%! b = 0;
+%! while 1
+%!   b = a(1);
+%!   break;
+%! endwhile
+%! assert (b, a(1));
+
+%!function test_undef ()
+%!  for i=1:1e7
+%!    XXX;
+%!  endfor
+%!endfunction
+
+%!error <undefined near> (test_undef);
+
+%!shared id
+%! id = @(x) x;
+
+%!assert (id (1), 1);
+%!assert (id (1+1i), 1+1i)
+%!assert (id (1, 2), 1)
+%!error <undefined> (id ())
+
+
+*/
new file mode 100644
--- /dev/null
+++ b/libinterp/interp-core/pt-jit.h
@@ -0,0 +1,442 @@
+/*
+
+Copyright (C) 2012 Max Brister <max@2bass.com>
+
+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_tree_jit_h)
+#define octave_tree_jit_h 1
+
+#ifdef HAVE_LLVM
+
+#include "jit-ir.h"
+#include "pt-walk.h"
+#include "symtab.h"
+
+class octave_value_list;
+
+// Convert from the parse tree (AST) to the low level Octave IR.
+class
+jit_convert : public tree_walker
+{
+public:
+  typedef std::pair<jit_type *, std::string> type_bound;
+  typedef std::vector<type_bound> type_bound_vector;
+  typedef std::map<std::string, jit_variable *> variable_map;
+
+  jit_convert (tree &tee, jit_type *for_bounds = 0);
+
+  jit_convert (octave_user_function& fcn, const std::vector<jit_type *>& args);
+
+#define DECL_ARG(n) const ARG ## n& arg ## n
+#define JIT_CREATE_CHECKED(N)                                           \
+  template <OCT_MAKE_DECL_LIST (typename, ARG, N)>                      \
+  jit_call *create_checked (OCT_MAKE_LIST (DECL_ARG, N))                \
+  {                                                                     \
+    jit_call *ret = factory.create<jit_call> (OCT_MAKE_ARG_LIST (arg, N)); \
+    return create_checked_impl (ret);                                   \
+  }
+
+  JIT_CREATE_CHECKED (1)
+  JIT_CREATE_CHECKED (2)
+  JIT_CREATE_CHECKED (3)
+  JIT_CREATE_CHECKED (4)
+
+#undef JIT_CREATE_CHECKED
+#undef DECL_ARG
+
+  jit_block_list& get_blocks (void) { return blocks; }
+
+  const type_bound_vector& get_bounds (void) const { return bounds; }
+
+  jit_factory& get_factory (void) { return factory; }
+
+  llvm::Function *get_function (void) const { return function; }
+
+  const variable_map &get_variable_map (void) const { return vmap; }
+
+  void visit_anon_fcn_handle (tree_anon_fcn_handle&);
+
+  void visit_argument_list (tree_argument_list&);
+
+  void visit_binary_expression (tree_binary_expression&);
+
+  void visit_break_command (tree_break_command&);
+
+  void visit_colon_expression (tree_colon_expression&);
+
+  void visit_continue_command (tree_continue_command&);
+
+  void visit_global_command (tree_global_command&);
+
+  void visit_persistent_command (tree_persistent_command&);
+
+  void visit_decl_elt (tree_decl_elt&);
+
+  void visit_decl_init_list (tree_decl_init_list&);
+
+  void visit_simple_for_command (tree_simple_for_command&);
+
+  void visit_complex_for_command (tree_complex_for_command&);
+
+  void visit_octave_user_script (octave_user_script&);
+
+  void visit_octave_user_function (octave_user_function&);
+
+  void visit_octave_user_function_header (octave_user_function&);
+
+  void visit_octave_user_function_trailer (octave_user_function&);
+
+  void visit_function_def (tree_function_def&);
+
+  void visit_identifier (tree_identifier&);
+
+  void visit_if_clause (tree_if_clause&);
+
+  void visit_if_command (tree_if_command&);
+
+  void visit_if_command_list (tree_if_command_list&);
+
+  void visit_index_expression (tree_index_expression&);
+
+  void visit_matrix (tree_matrix&);
+
+  void visit_cell (tree_cell&);
+
+  void visit_multi_assignment (tree_multi_assignment&);
+
+  void visit_no_op_command (tree_no_op_command&);
+
+  void visit_constant (tree_constant&);
+
+  void visit_fcn_handle (tree_fcn_handle&);
+
+  void visit_parameter_list (tree_parameter_list&);
+
+  void visit_postfix_expression (tree_postfix_expression&);
+
+  void visit_prefix_expression (tree_prefix_expression&);
+
+  void visit_return_command (tree_return_command&);
+
+  void visit_return_list (tree_return_list&);
+
+  void visit_simple_assignment (tree_simple_assignment&);
+
+  void visit_statement (tree_statement&);
+
+  void visit_statement_list (tree_statement_list&);
+
+  void visit_switch_case (tree_switch_case&);
+
+  void visit_switch_case_list (tree_switch_case_list&);
+
+  void visit_switch_command (tree_switch_command&);
+
+  void visit_try_catch_command (tree_try_catch_command&);
+
+  void visit_unwind_protect_command (tree_unwind_protect_command&);
+
+  void visit_while_command (tree_while_command&);
+
+  void visit_do_until_command (tree_do_until_command&);
+private:
+  std::vector<std::pair<std::string, bool> > arguments;
+  type_bound_vector bounds;
+
+  bool converting_function;
+
+  // the scope of the function we are converting, or the current scope
+  symbol_table::scope_id scope;
+
+  jit_factory factory;
+
+  // used instead of return values from visit_* functions
+  jit_value *result;
+
+  jit_block *entry_block;
+
+  jit_block *final_block;
+
+  jit_block *block;
+
+  llvm::Function *function;
+
+  jit_block_list blocks;
+
+  std::vector<jit_magic_end::context> end_context;
+
+  size_t iterator_count;
+  size_t for_bounds_count;
+  size_t short_count;
+
+  variable_map vmap;
+
+  void initialize (symbol_table::scope_id s);
+
+  jit_call *create_checked_impl (jit_call *ret);
+
+  // get an existing vairable. If the variable does not exist, it will not be
+  // created
+  jit_variable *find_variable (const std::string& vname) const;
+
+  // get a variable, create it if it does not exist. The type will default to
+  // the variable's current type in the symbol table.
+  jit_variable *get_variable (const std::string& vname);
+
+  // create a variable of the given name and given type. Will also insert an
+  // extract statement
+  jit_variable *create_variable (const std::string& vname, jit_type *type,
+                                 bool isarg = true);
+
+  // The name of the next for loop iterator. If inc is false, then the iterator
+  // counter will not be incremented.
+  std::string next_iterator (bool inc = true)
+  { return next_name ("#iter", iterator_count, inc); }
+
+  std::string next_for_bounds (bool inc = true)
+  { return next_name ("#for_bounds", for_bounds_count, inc); }
+
+  std::string next_shortcircut_result (bool inc = true)
+  { return next_name ("#shortcircut_result", short_count, inc); }
+
+  std::string next_name (const char *prefix, size_t& count, bool inc);
+
+  jit_instruction *resolve (tree_index_expression& exp,
+                            jit_value *extra_arg = 0, bool lhs = false);
+
+  jit_value *do_assign (tree_expression *exp, jit_value *rhs,
+                        bool artificial = false);
+
+  jit_value *do_assign (const std::string& lhs, jit_value *rhs, bool print,
+                        bool artificial = false);
+
+  jit_value *visit (tree *tee) { return visit (*tee); }
+
+  jit_value *visit (tree& tee);
+
+  typedef std::list<jit_block *> block_list;
+  block_list breaks;
+  block_list continues;
+
+  void finish_breaks (jit_block *dest, const block_list& lst);
+};
+
+// Convert from the low level Octave IR to LLVM
+class
+jit_convert_llvm : public jit_ir_walker
+{
+public:
+  llvm::Function *convert_loop (llvm::Module *module,
+                                const jit_block_list& blocks,
+                                const std::list<jit_value *>& constants);
+
+  jit_function convert_function (llvm::Module *module,
+                                 const jit_block_list& blocks,
+                                 const std::list<jit_value *>& constants,
+                                 octave_user_function& fcn,
+                                 const std::vector<jit_type *>& args);
+
+  // arguments to the llvm::Function for loops
+  const std::vector<std::pair<std::string, bool> >& get_arguments(void) const
+  { return argument_vec; }
+
+#define JIT_METH(clname)                        \
+  virtual void visit (jit_ ## clname&);
+
+  JIT_VISIT_IR_CLASSES;
+
+#undef JIT_METH
+private:
+  // name -> argument index (used for compiling functions)
+  std::map<std::string, int> argument_index;
+
+  std::vector<std::pair<std::string, bool> > argument_vec;
+
+  // name -> llvm argument (used for compiling loops)
+  std::map<std::string, llvm::Value *> arguments;
+
+  bool converting_function;
+
+  // only used if we are converting a function
+  jit_function creating;
+
+  llvm::Function *function;
+  llvm::BasicBlock *prelude;
+
+  void convert (const jit_block_list& blocks,
+                const std::list<jit_value *>& constants);
+
+  void finish_phi (jit_phi *phi);
+
+  void visit (jit_value *jvalue)
+  {
+    return visit (*jvalue);
+  }
+
+  void visit (jit_value &jvalue)
+  {
+    jvalue.accept (*this);
+  }
+};
+
+// type inference and SSA construction on the low level Octave IR
+class
+jit_infer
+{
+public:
+  typedef jit_convert::variable_map variable_map;
+
+  jit_infer (jit_factory& afactory, jit_block_list& ablocks,
+             const variable_map& avmap);
+
+  jit_block_list& get_blocks (void) const { return blocks; }
+
+  jit_factory& get_factory (void) const { return factory; }
+
+  void infer (void);
+private:
+  jit_block_list& blocks;
+  jit_factory& factory;
+  const variable_map& vmap;
+  std::list<jit_instruction *> worklist;
+
+  void append_users (jit_value *v);
+
+  void append_users_term (jit_terminator *term);
+
+  void construct_ssa (void);
+
+  void do_construct_ssa (jit_block& block, size_t avisit_count);
+
+  jit_block& entry_block (void) { return *blocks.front (); }
+
+  jit_block& final_block (void) { return *blocks.back (); }
+
+  void place_releases (void);
+
+  void push_worklist (jit_instruction *instr);
+
+  void remove_dead ();
+
+  void release_dead_phi (jit_block& ablock);
+
+  void release_temp (jit_block& ablock, std::set<jit_value *>& temp);
+
+  void simplify_phi (void);
+
+  void simplify_phi (jit_phi& phi);
+};
+
+class
+tree_jit
+{
+public:
+  ~tree_jit (void);
+
+  static bool execute (tree_simple_for_command& cmd,
+                       const octave_value& bounds);
+
+  static bool execute (tree_while_command& cmd);
+
+  static bool execute (octave_user_function& fcn, const octave_value_list& args,
+                       octave_value_list& retval);
+
+  llvm::ExecutionEngine *get_engine (void) const { return engine; }
+
+  llvm::Module *get_module (void) const { return module; }
+
+  void optimize (llvm::Function *fn);
+ private:
+  tree_jit (void);
+
+  static tree_jit& instance (void);
+
+  bool initialize (void);
+
+  bool do_execute (tree_simple_for_command& cmd, const octave_value& bounds);
+
+  bool do_execute (tree_while_command& cmd);
+
+  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;
+  llvm::PassManager *module_pass_manager;
+  llvm::FunctionPassManager *pass_manager;
+  llvm::ExecutionEngine *engine;
+};
+
+class
+jit_function_info
+{
+public:
+  jit_function_info (tree_jit& tjit, octave_user_function& fcn,
+                     const octave_value_list& ov_args);
+
+  bool execute (const octave_value_list& ov_args,
+                octave_value_list& retval) const;
+
+  bool match (const octave_value_list& ov_args) const;
+private:
+  typedef octave_base_value *(*jited_function)(octave_base_value**);
+
+  std::vector<jit_type *> argument_types;
+  jited_function function;
+};
+
+class
+jit_info
+{
+public:
+  // we use a pointer here so we don't have to include ov.h
+  typedef std::map<std::string, const octave_value *> vmap;
+
+  jit_info (tree_jit& tjit, tree& tee);
+
+  jit_info (tree_jit& tjit, tree& tee, const octave_value& for_bounds);
+
+  ~jit_info (void);
+
+  bool execute (const vmap& extra_vars = vmap ()) const;
+
+  bool match (const vmap& extra_vars = vmap ()) const;
+private:
+  typedef jit_convert::type_bound type_bound;
+  typedef jit_convert::type_bound_vector type_bound_vector;
+  typedef void (*jited_function)(octave_base_value**);
+
+  void compile (tree_jit& tjit, tree& tee, jit_type *for_bounds = 0);
+
+  octave_value find (const vmap& extra_vars, const std::string& vname) const;
+
+  llvm::ExecutionEngine *engine;
+  jited_function function;
+  llvm::Function *llvm_function;
+
+  std::vector<std::pair<std::string, bool> > arguments;
+  type_bound_vector bounds;
+};
+
+#endif
+#endif
rename from src/siglist.c
rename to libinterp/interp-core/siglist.c
rename from src/siglist.h
rename to libinterp/interp-core/siglist.h
rename from src/sparse-xdiv.cc
rename to libinterp/interp-core/sparse-xdiv.cc
--- a/src/sparse-xdiv.cc
+++ b/libinterp/interp-core/sparse-xdiv.cc
@@ -117,7 +117,7 @@
 INSTANTIATE_MX_DIV_CONFORM (SparseComplexMatrix, DiagMatrix);
 INSTANTIATE_MX_DIV_CONFORM (SparseComplexMatrix, ComplexDiagMatrix);
 
-// Right division functions.  X / Y = X * inv(Y) = (inv (Y') * X')'
+// Right division functions.  X / Y = X * inv (Y) = (inv (Y') * X')'
 //
 //                  Y / X:   m   cm   sm  scm
 //                   +--   +---+----+----+----+
@@ -384,10 +384,10 @@
 
 
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
+    for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
       {
         octave_quit ();
-        result.elem (b.ridx(i), j) = a / b.data (i);
+        result.elem (b.ridx (i), j) = a / b.data (i);
       }
 
   return result;
@@ -399,13 +399,13 @@
   octave_idx_type nr = b.rows ();
   octave_idx_type nc = b.cols ();
 
-  ComplexMatrix  result (nr, nc, Complex(octave_NaN, octave_NaN));
+  ComplexMatrix  result (nr, nc, Complex (octave_NaN, octave_NaN));
 
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
+    for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
       {
         octave_quit ();
-        result.elem (b.ridx(i), j) = a / b.data (i);
+        result.elem (b.ridx (i), j) = a / b.data (i);
       }
 
   return result;
@@ -420,10 +420,10 @@
   ComplexMatrix result (nr, nc, (a / 0.0));
 
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
+    for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
       {
         octave_quit ();
-        result.elem (b.ridx(i), j) = a / b.data (i);
+        result.elem (b.ridx (i), j) = a / b.data (i);
       }
 
   return result;
@@ -438,16 +438,16 @@
   ComplexMatrix result (nr, nc, (a / 0.0));
 
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
+    for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
       {
         octave_quit ();
-        result.elem (b.ridx(i), j) = a / b.data (i);
+        result.elem (b.ridx (i), j) = a / b.data (i);
       }
 
   return result;
 }
 
-// Left division functions.  X \ Y = inv(X) * Y
+// Left division functions.  X \ Y = inv (X) * Y
 //
 //               Y  \  X :   sm  scm  dm  dcm
 //                   +--   +---+----+
rename from src/sparse-xdiv.h
rename to libinterp/interp-core/sparse-xdiv.h
rename from src/sparse-xpow.cc
rename to libinterp/interp-core/sparse-xpow.cc
--- a/src/sparse-xpow.cc
+++ b/libinterp/interp-core/sparse-xpow.cc
@@ -26,7 +26,8 @@
 #endif
 
 #include <cassert>
-#include <climits>
+
+#include <limits>
 
 #include "Array-util.h"
 #include "oct-cmplx.h"
@@ -46,8 +47,8 @@
 xisint (double x)
 {
   return (D_NINT (x) == x
-          && ((x >= 0 && x < INT_MAX)
-              || (x <= 0 && x > INT_MIN)));
+          && ((x >= 0 && x < std::numeric_limits<int>::max ())
+              || (x <= 0 && x > std::numeric_limits<int>::min ())));
 }
 
 
@@ -273,7 +274,7 @@
           for (octave_idx_type i = 0; i < nr; i++)
             {
               octave_quit ();
-              result (i, j) = std::pow (atmp, b(i,j));
+              result(i, j) = std::pow (atmp, b(i,j));
             }
         }
 
@@ -288,7 +289,7 @@
           for (octave_idx_type i = 0; i < nr; i++)
             {
               octave_quit ();
-              result (i, j) = std::pow (a, b(i,j));
+              result(i, j) = std::pow (a, b(i,j));
             }
         }
 
@@ -313,7 +314,7 @@
       for (octave_idx_type i = 0; i < nr; i++)
         {
           octave_quit ();
-          result (i, j) = std::pow (atmp, b(i,j));
+          result(i, j) = std::pow (atmp, b(i,j));
         }
     }
 
@@ -346,13 +347,13 @@
           Complex btmp (b);
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+            for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
               {
                 octave_quit ();
 
                 Complex atmp (a.data (i));
 
-                result (a.ridx(i), j) = std::pow (atmp, btmp);
+                result(a.ridx (i), j) = std::pow (atmp, btmp);
               }
 
           retval = octave_value (result);
@@ -362,10 +363,10 @@
           Matrix result (nr, nc, (std::pow (0.0, b)));
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+            for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
               {
                 octave_quit ();
-                result (a.ridx(i), j) = std::pow (a.data (i), b);
+                result(a.ridx (i), j) = std::pow (a.data (i), b);
               }
 
           retval = octave_value (result);
@@ -433,11 +434,11 @@
 
   int convert_to_complex = 0;
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+    for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
       {
         if (a.data(i) < 0.0)
           {
-            double btmp = b (a.ridx(i), j);
+            double btmp = b (a.ridx (i), j);
             if (static_cast<int> (btmp) != btmp)
               {
                 convert_to_complex = 1;
@@ -455,15 +456,15 @@
 
   if (convert_to_complex)
     {
-      SparseComplexMatrix complex_result (nr, nc, Complex(1.0, 0.0));
+      SparseComplexMatrix complex_result (nr, nc, Complex (1.0, 0.0));
 
       for (octave_idx_type j = 0; j < nc; j++)
         {
-          for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+          for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
             {
               octave_quit ();
-              complex_result.xelem(a.ridx(i), j) =
-                std::pow (Complex(a.data(i)), Complex(b(a.ridx(i), j)));
+              complex_result.xelem (a.ridx (i), j) =
+                std::pow (Complex (a.data (i)), Complex (b(a.ridx (i), j)));
             }
         }
       complex_result.maybe_compress (true);
@@ -475,11 +476,11 @@
 
       for (octave_idx_type j = 0; j < nc; j++)
         {
-          for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+          for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
             {
               octave_quit ();
-              result.xelem(a.ridx(i), j) = std::pow (a.data(i),
-                                                     b (a.ridx(i), j));
+              result.xelem (a.ridx (i), j) = std::pow (a.data (i),
+                                                       b(a.ridx (i), j));
             }
         }
       result.maybe_compress (true);
@@ -536,13 +537,13 @@
       return octave_value ();
     }
 
-  SparseComplexMatrix result (nr, nc, Complex(1.0, 0.0));
+  SparseComplexMatrix result (nr, nc, Complex (1.0, 0.0));
   for (octave_idx_type j = 0; j < nc; j++)
     {
-      for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+      for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
         {
           octave_quit ();
-          result.xelem(a.ridx(i), j) = std::pow (a.data(i), b (a.ridx(i), j));
+          result.xelem (a.ridx(i), j) = std::pow (a.data (i), b(a.ridx (i), j));
         }
     }
 
@@ -610,20 +611,20 @@
       if (xisint (b))
         {
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+            for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
               {
                 octave_quit ();
-                result (a.ridx(i), j) =
+                result (a.ridx (i), j) =
                   std::pow (a.data (i), static_cast<int> (b));
               }
         }
       else
         {
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+            for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
               {
                 octave_quit ();
-                result (a.ridx(i), j) = std::pow (a.data (i), b);
+                result (a.ridx (i), j) = std::pow (a.data (i), b);
               }
         }
 
@@ -679,20 +680,20 @@
       return octave_value ();
     }
 
-  SparseComplexMatrix result (nr, nc, Complex(1.0, 0.0));
+  SparseComplexMatrix result (nr, nc, Complex (1.0, 0.0));
   for (octave_idx_type j = 0; j < nc; j++)
     {
-      for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+      for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
         {
           octave_quit ();
-          double btmp = b (a.ridx(i), j);
+          double btmp = b(a.ridx (i), j);
           Complex tmp;
 
           if (xisint (btmp))
-            result.xelem(a.ridx(i), j) = std::pow (a.data (i),
+            result.xelem (a.ridx (i), j) = std::pow (a.data (i),
                                               static_cast<int> (btmp));
           else
-            result.xelem(a.ridx(i), j) = std::pow (a.data (i), btmp);
+            result.xelem (a.ridx (i), j) = std::pow (a.data (i), btmp);
         }
     }
 
@@ -750,13 +751,13 @@
       return octave_value ();
     }
 
-  SparseComplexMatrix result (nr, nc, Complex(1.0, 0.0));
+  SparseComplexMatrix result (nr, nc, Complex (1.0, 0.0));
   for (octave_idx_type j = 0; j < nc; j++)
     {
-      for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+      for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
         {
           octave_quit ();
-          result.xelem(a.ridx(i), j) = std::pow (a.data (i), b (a.ridx(i), j));
+          result.xelem (a.ridx (i), j) = std::pow (a.data (i), b(a.ridx (i), j));
         }
     }
   result.maybe_compress (true);
rename from src/sparse-xpow.h
rename to libinterp/interp-core/sparse-xpow.h
rename from src/txt-eng-ft.cc
rename to libinterp/interp-core/txt-eng-ft.cc
--- a/src/txt-eng-ft.cc
+++ b/libinterp/interp-core/txt-eng-ft.cc
@@ -240,7 +240,7 @@
 ft_render::ft_render (void)
     : text_processor (), face (0), bbox (1, 4, 0.0),
       xoffset (0), yoffset (0), multiline_halign (0),
-      multiline_align_xoffsets(), mode (MODE_BBOX),
+      multiline_align_xoffsets (), mode (MODE_BBOX),
       red (0), green (0), blue (0)
 {
 }
@@ -314,7 +314,7 @@
       FT_UInt glyph_index, previous = 0;
 
       if (mode == MODE_BBOX)
-        multiline_align_xoffsets.clear();
+        multiline_align_xoffsets.clear ();
       else if (mode == MODE_RENDER)
         xoffset += multiline_align_xoffsets[line_index];
 
@@ -333,7 +333,7 @@
                 case MODE_RENDER:
                   if (str[i] == '\n')
                     {
-                    glyph_index = FT_Get_Char_Index(face, ' ');
+                    glyph_index = FT_Get_Char_Index (face, ' ');
                     if (!glyph_index || FT_Load_Glyph (face, glyph_index, FT_LOAD_DEFAULT))
                       {
                         gripe_missing_glyph (' ');
@@ -376,8 +376,8 @@
                         for (int c = 0; c < bitmap.width; c++)
                           {
                             unsigned char pix = bitmap.buffer[r*bitmap.width+c];
-                            if (x0+c < 0 || x0+c >= pixels.dim2()
-                                || y0-r < 0 || y0-r >= pixels.dim3())
+                            if (x0+c < 0 || x0+c >= pixels.dim2 ()
+                                || y0-r < 0 || y0-r >= pixels.dim3 ())
                               {
                                 //::error ("out-of-bound indexing!!");
                               }
@@ -397,7 +397,7 @@
                 case MODE_BBOX:
                   if (str[i] == '\n')
                     {
-                      glyph_index = FT_Get_Char_Index(face, ' ');
+                      glyph_index = FT_Get_Char_Index (face, ' ');
                       if (! glyph_index
                           || FT_Load_Glyph (face, glyph_index, FT_LOAD_DEFAULT))
                       {
@@ -405,7 +405,7 @@
                       }
                     else
                       {
-                        multiline_align_xoffsets.push_back(box_line_width);
+                        multiline_align_xoffsets.push_back (box_line_width);
                         // Reset the pixel width for this newline, so we don't
                         // allocate a bounding box larger than the horizontal
                         // width of the multi-line
@@ -465,9 +465,9 @@
       if (mode == MODE_BBOX)
         {
           /* Push last the width associated with the last line */
-          multiline_align_xoffsets.push_back(box_line_width);
+          multiline_align_xoffsets.push_back (box_line_width);
 
-          for (unsigned int i = 0; i < multiline_align_xoffsets.size(); i++)
+          for (unsigned int i = 0; i < multiline_align_xoffsets.size (); i++)
             {
             /* Center align */
             if (multiline_halign == 1)
@@ -529,7 +529,7 @@
 
               Array<idx_vector> idx (dim_vector (3, 1));
               idx(0) = idx_vector (':');
-              idx(1) = idx_vector (pixels.dim2()-1, -1, -1);
+              idx(1) = idx_vector (pixels.dim2 ()-1, -1, -1);
               idx(2) = idx_vector (':');
               pixels = uint8NDArray (pixels.index (idx));
             }
@@ -538,8 +538,8 @@
             {
               Array<idx_vector> idx (dim_vector (3, 1));
               idx(0) = idx_vector (':');
-              idx(1) = idx_vector (pixels.dim2()-1, -1, -1);
-              idx(2)=  idx_vector (pixels.dim3()-1, -1, -1);
+              idx(1) = idx_vector (pixels.dim2 ()-1, -1, -1);
+              idx(2)=  idx_vector (pixels.dim3 ()-1, -1, -1);
               pixels = uint8NDArray (pixels.index (idx));
             }
           break;
@@ -554,7 +554,7 @@
               Array<idx_vector> idx (dim_vector (3, 1));
               idx(0) = idx_vector (':');
               idx(1) = idx_vector (':');
-              idx(2) = idx_vector (pixels.dim3()-1, -1, -1);
+              idx(2) = idx_vector (pixels.dim3 ()-1, -1, -1);
               pixels = uint8NDArray (pixels.index (idx));
             }
           break;
@@ -564,6 +564,11 @@
   return pixels;
 }
 
+// Note:
+// x-extent accurately measures width of glyphs.
+// y-extent is overly large because it is measured from baseline-to-baseline.
+// Calling routines, such as ylabel, may need to account for this mismatch.
+
 Matrix
 ft_render::get_extent (text_element *elt, double rotation)
 {
@@ -645,6 +650,7 @@
     case 1: box(1) = -box(3)/2; break;
     case 2: box(1) = -box(3); break;
     case 3: break;
+    case 4: box(1) = -box(3)-box(1); break;
     }
 
   switch (rot_mode)
rename from src/txt-eng-ft.h
rename to libinterp/interp-core/txt-eng-ft.h
rename from src/txt-eng.h
rename to libinterp/interp-core/txt-eng.h
rename from src/unwind-prot.cc
rename to libinterp/interp-core/unwind-prot.cc
--- a/src/unwind-prot.cc
+++ b/libinterp/interp-core/unwind-prot.cc
@@ -25,12 +25,8 @@
 #include <config.h>
 #endif
 
-#include <cstddef>
-#include <cstring>
-
 #include "error.h"
 #include "unwind-prot.h"
-#include "utils.h"
 
 void unwind_protect_safe::gripe_exception (void)
 {
rename from src/unwind-prot.h
rename to libinterp/interp-core/unwind-prot.h
--- a/src/unwind-prot.h
+++ b/libinterp/interp-core/unwind-prot.h
@@ -24,289 +24,74 @@
 #if !defined (octave_unwind_prot_h)
 #define octave_unwind_prot_h 1
 
-#include <cstddef>
-
-#include <string>
+#include <stack>
 #include <memory>
 
-// This class allows registering cleanup actions.
+#include "action-container.h"
+
 class
 OCTINTERP_API
-unwind_protect
+unwind_protect : public action_container
 {
 public:
 
-  // A generic unwind_protect element. Knows how to run itself and discard itself.
-  // Also, contains a pointer to the next element.
-  class elem
-  {
-    elem *next;
-
-  public:
-    elem (void) : next (0) { }
-
-    virtual void run (void) { }
-
-    virtual ~elem (void) { }
-
-    friend class unwind_protect;
-
-  private:
-
-    // No copying!
-
-    elem (const elem&);
-
-    elem& operator = (const elem&);
-  };
-
-  // An element that merely runs a void (*)(void) function.
-
-  class fcn_elem : public elem
-  {
-  public:
-    fcn_elem (void (*fptr) (void))
-      : e_fptr (fptr) { }
+  unwind_protect (void) : lifo () { }
 
-    void run (void) { e_fptr (); }
-
-  private:
-    void (*e_fptr) (void);
-  };
-
-  // An element that stores a variable of type T along with a void (*) (T)
-  // function pointer, and calls the function with the parameter.
-
-  template <class T>
-  class fcn_arg_elem : public elem
-  {
-  public:
-    fcn_arg_elem (void (*fcn) (T), T arg)
-      : e_fcn (fcn), e_arg (arg) { }
+  // Destructor should not raise an exception, so all actions
+  // registered should be exception-safe (but setting error_state is
+  // allowed). If you're not sure, see unwind_protect_safe.
 
-    void run (void) { e_fcn (e_arg); }
-
-  private:
-
-    // No copying!
-
-    fcn_arg_elem (const fcn_arg_elem&);
-
-    fcn_arg_elem& operator = (const fcn_arg_elem&);
-
-    void (*e_fcn) (T);
-    T e_arg;
-  };
-
-  // An element that stores a variable of type T along with a void (*) (const T&)
-  // function pointer, and calls the function with the parameter.
+  ~unwind_protect (void) { run (); }
 
-  template <class T>
-  class fcn_crefarg_elem : public elem
+  virtual void add (elem *new_elem)
   {
-  public:
-    fcn_crefarg_elem (void (*fcn) (const T&), T arg)
-      : e_fcn (fcn), e_arg (arg) { }
-
-    void run (void) { e_fcn (e_arg); }
-
-  private:
-    void (*e_fcn) (const T&);
-    T e_arg;
-  };
-
-  // An element for calling a member function.
-
-  template <class T>
-  class method_elem : public elem
-  {
-  public:
-    method_elem (T *obj, void (T::*method) (void))
-      : e_obj (obj), e_method (method) { }
-
-    void run (void) { (e_obj->*e_method) (); }
-
-  private:
-
-    T *e_obj;
-    void (T::*e_method) (void);
-
-    // No copying!
-
-    method_elem (const method_elem&);
+    lifo.push (new_elem);
+  }
 
-    method_elem operator = (const method_elem&);
-  };
-
-  // An element that stores arbitrary variable, and restores it.
-
-  template <class T>
-  class restore_var_elem : public elem
+  void add (void (*fcn) (void *), void *ptr = 0) GCC_ATTR_DEPRECATED
   {
-  public:
-    restore_var_elem (T& ref, const T& val)
-      : e_ptr (&ref), e_val (val) { }
-
-    void run (void) { *e_ptr = e_val; }
-
-  private:
+    add (new fcn_arg_elem<void *> (fcn, ptr));
+  }
 
-    // No copying!
-
-    restore_var_elem (const restore_var_elem&);
-
-    restore_var_elem& operator = (const restore_var_elem&);
-
-    T *e_ptr, e_val;
-  };
+  operator bool (void) const { return ! empty (); }
 
-  // Deletes a class allocated using new.
-
-  template <class T>
-  class delete_ptr_elem : public elem
-  {
-  public:
-    delete_ptr_elem (T *ptr)
-      : e_ptr (ptr) { }
+  void run_top (void) GCC_ATTR_DEPRECATED { run_first (); }
 
-    void run (void) { delete e_ptr; }
-
-  private:
-
-    T *e_ptr;
-
-    // No copying!
-
-    delete_ptr_elem (const delete_ptr_elem&);
-
-    delete_ptr_elem operator = (const delete_ptr_elem&);
-  };
-
-  unwind_protect (void) : head () { }
-
-  void add (elem *new_elem)
-    {
-      new_elem->next = head;
-      head = new_elem;
-    }
-
-  // For backward compatibility.
-  void add (void (*fcn) (void *), void *ptr = 0)
-    {
-      add (new fcn_arg_elem<void *> (fcn, ptr));
-    }
+  void run_first (void)
+  {
+    if (! empty ())
+      {
+        // No leak on exception!
+        std::auto_ptr<elem> ptr (lifo.top ());
+        lifo.pop ();
+        ptr->run ();
+      }
+  }
 
-  // Call to void func (void).
-  void add_fcn (void (*fcn) (void))
-    {
-      add (new fcn_elem (fcn));
-    }
-
-  // Call to void func (T).
-  template <class T>
-  void add_fcn (void (*action) (T), T val)
-    {
-      add (new fcn_arg_elem<T> (action, val));
-    }
+  void run_top (int num) GCC_ATTR_DEPRECATED { run (num); }
 
-  // Call to void func (const T&).
-  template <class T>
-  void add_fcn (void (*action) (const T&), T val)
-    {
-      add (new fcn_crefarg_elem<T> (action, val));
-    }
-
-  // Call to T::method (void).
-  template <class T>
-  void add_method (T *obj, void (T::*method) (void))
-    {
-      add (new method_elem<T> (obj, method));
-    }
-
-  // Call to delete (T*).
-
-  template <class T>
-  void add_delete (T *obj)
-    {
-      add (new delete_ptr_elem<T> (obj));
-    }
+  void discard_top (void) GCC_ATTR_DEPRECATED { discard_first (); }
 
-  // Protect any variable.
-  template <class T>
-  void protect_var (T& var)
-    {
-      add (new restore_var_elem<T> (var, var));
-    }
-
-  // Protect any variable, value given.
-  template <class T>
-  void protect_var (T& var, const T& val)
-    {
-      add (new restore_var_elem<T> (var, val));
-    }
-
-  operator bool (void) const
-    {
-      return head != 0;
-    }
-
-  void run_top (void)
-    {
-      if (head)
-        {
-          // No leak on exception!
-          std::auto_ptr<elem> ptr (head);
-          head = ptr->next;
-          ptr->run ();
-        }
-    }
-
-  void run_top (int num)
-    {
-      while (num-- > 0)
-        run_top ();
-    }
+  void discard_first (void)
+  {
+    if (! empty ())
+      {
+        elem *ptr = lifo.top ();
+        lifo.pop ();
+        delete ptr;
+      }
+  }
 
-  void discard_top (void)
-    {
-      if (head)
-        {
-          elem *ptr = head;
-          head = ptr->next;
-          delete ptr;
-        }
-    }
+  void discard_top (int num) GCC_ATTR_DEPRECATED { discard (num); }
 
-  void discard_top (int num)
-    {
-      while (num-- > 0)
-        discard_top ();
-    }
+  size_t size (void) const { return lifo.size (); }
 
-  void run (void)
-    {
-      while (head)
-        run_top ();
-    }
+protected:
 
-  void discard (void)
-    {
-      while (head)
-        discard_top ();
-    }
-
-  // Destructor should not raise an exception, so all actions registered should
-  // be exception-safe (but setting error_state is allowed). If you're not sure,
-  // see unwind_protect_safe.
-  ~unwind_protect (void)
-    {
-      run ();
-    }
+  std::stack<elem *> lifo;
 
 private:
 
-  elem *head;
-
   // No copying!
 
   unwind_protect (const unwind_protect&);
@@ -314,24 +99,30 @@
   unwind_protect& operator = (const unwind_protect&);
 };
 
-// Like unwind_protect, but this one will guard against the possibility of seeing
-// an exception (or interrupt) in the cleanup actions. Not that we can do much about
-// it, but at least we won't crash.
+// Like unwind_protect, but this one will guard against the
+// possibility of seeing an exception (or interrupt) in the cleanup
+// actions. Not that we can do much about it, but at least we won't
+// crash.
 
 class
 OCTINTERP_API
 unwind_protect_safe : public unwind_protect
 {
+private:
+
   static void gripe_exception (void);
 
 public:
+
+  unwind_protect_safe (void) : unwind_protect () { }
+
   ~unwind_protect_safe (void)
     {
-      while (*this)
+      while (! empty ())
         {
           try
             {
-              run_top ();
+              run_first ();
             }
           catch (...) // Yes, the black hole. Remember we're in a dtor.
             {
@@ -339,6 +130,14 @@
             }
         }
     }
+
+private:
+
+  // No copying!
+
+  unwind_protect_safe (const unwind_protect_safe&);
+
+  unwind_protect_safe& operator = (const unwind_protect_safe&);
 };
 
 #endif
rename from src/xdiv.cc
rename to libinterp/interp-core/xdiv.cc
rename from src/xdiv.h
rename to libinterp/interp-core/xdiv.h
rename from src/xgl2ps.c
rename to libinterp/interp-core/xgl2ps.c
--- a/src/xgl2ps.c
+++ b/libinterp/interp-core/xgl2ps.c
@@ -20,8 +20,10 @@
 
 */
 
-// Wrapper for "imported" file gl2ps.c so that config.h will be included
-// before any other system or gnulib headers.
+/*
+ * Wrapper for "imported" file gl2ps.c so that config.h will be included
+ * before any other system or gnulib headers.
+ */
 
 #ifdef HAVE_CONFIG_H
 #include <config.h>
rename from src/xnorm.cc
rename to libinterp/interp-core/xnorm.cc
rename from src/xnorm.h
rename to libinterp/interp-core/xnorm.h
rename from src/xpow.cc
rename to libinterp/interp-core/xpow.cc
--- a/src/xpow.cc
+++ b/libinterp/interp-core/xpow.cc
@@ -26,7 +26,8 @@
 #endif
 
 #include <cassert>
-#include <climits>
+
+#include <limits>
 
 #include "Array-util.h"
 #include "CColVector.h"
@@ -59,8 +60,8 @@
 xisint (double x)
 {
   return (D_NINT (x) == x
-          && ((x >= 0 && x < INT_MAX)
-              || (x <= 0 && x > INT_MIN)));
+          && ((x >= 0 && x < std::numeric_limits<int>::max ())
+              || (x <= 0 && x > std::numeric_limits<int>::min ())));
 }
 
 // Safer pow functions.
@@ -1508,8 +1509,8 @@
 xisint (float x)
 {
   return (D_NINT (x) == x
-          && ((x >= 0 && x < INT_MAX)
-              || (x <= 0 && x > INT_MIN)));
+          && ((x >= 0 && x < std::numeric_limits<int>::max ())
+              || (x <= 0 && x > std::numeric_limits<int>::min ())));
 }
 
 // Safer pow functions.
rename from src/xpow.h
rename to libinterp/interp-core/xpow.h
rename from src/zfstream.cc
rename to libinterp/interp-core/zfstream.cc
--- a/src/zfstream.cc
+++ b/libinterp/interp-core/zfstream.cc
@@ -52,41 +52,41 @@
 /*****************************************************************************/
 
 // Default constructor
-gzfilebuf::gzfilebuf()
+gzfilebuf::gzfilebuf ()
 : file(0), io_mode(std::ios_base::openmode(0)), own_fd(false),
   buffer(0), buffer_size(BIGBUFSIZE), own_buffer(true)
 {
   // No buffers to start with
-  this->disable_buffer();
+  this->disable_buffer ();
 }
 
 // Destructor
-gzfilebuf::~gzfilebuf()
+gzfilebuf::~gzfilebuf ()
 {
   // Sync output buffer and close only if responsible for file
   // (i.e. attached streams should be left open at this stage)
-  this->sync();
+  this->sync ();
   if (own_fd)
-    this->close();
+    this->close ();
   // Make sure internal buffer is deallocated
-  this->disable_buffer();
+  this->disable_buffer ();
 }
 
 // Set compression level and strategy
 int
-gzfilebuf::setcompression(int comp_level,
-                          int comp_strategy)
+gzfilebuf::setcompression (int comp_level,
+                           int comp_strategy)
 {
-  return gzsetparams(file, comp_level, comp_strategy);
+  return gzsetparams (file, comp_level, comp_strategy);
 }
 
 // Open gzipped file
 gzfilebuf*
-gzfilebuf::open(const char *name,
-                std::ios_base::openmode mode)
+gzfilebuf::open (const char *name,
+                 std::ios_base::openmode mode)
 {
   // Fail if file already open
-  if (this->is_open())
+  if (this->is_open ())
     return 0;
   // Don't support simultaneous read/write access (yet)
   if ((mode & std::ios_base::in) && (mode & std::ios_base::out))
@@ -94,15 +94,15 @@
 
   // Build mode string for gzopen and check it [27.8.1.3.2]
   char char_mode[6] = "\0\0\0\0\0";
-  if (!this->open_mode(mode, char_mode))
+  if (! this->open_mode (mode, char_mode))
     return 0;
 
   // Attempt to open file
-  if ((file = gzopen(name, char_mode)) == 0)
+  if ((file = gzopen (name, char_mode)) == 0)
     return 0;
 
   // On success, allocate internal buffer and set flags
-  this->enable_buffer();
+  this->enable_buffer ();
   io_mode = mode;
   own_fd = true;
   return this;
@@ -110,11 +110,11 @@
 
 // Attach to gzipped file
 gzfilebuf*
-gzfilebuf::attach(int fd,
-                  std::ios_base::openmode mode)
+gzfilebuf::attach (int fd,
+                   std::ios_base::openmode mode)
 {
   // Fail if file already open
-  if (this->is_open())
+  if (this->is_open ())
     return 0;
   // Don't support simultaneous read/write access (yet)
   if ((mode & std::ios_base::in) && (mode & std::ios_base::out))
@@ -122,15 +122,15 @@
 
   // Build mode string for gzdopen and check it [27.8.1.3.2]
   char char_mode[6] = "\0\0\0\0\0";
-  if (!this->open_mode(mode, char_mode))
+  if (! this->open_mode (mode, char_mode))
     return 0;
 
   // Attempt to attach to file
-  if ((file = gzdopen(fd, char_mode)) == 0)
+  if ((file = gzdopen (fd, char_mode)) == 0)
     return 0;
 
   // On success, allocate internal buffer and set flags
-  this->enable_buffer();
+  this->enable_buffer ();
   io_mode = mode;
   own_fd = false;
   return this;
@@ -138,23 +138,23 @@
 
 // Close gzipped file
 gzfilebuf*
-gzfilebuf::close()
+gzfilebuf::close ()
 {
   // Fail immediately if no file is open
-  if (!this->is_open())
+  if (! this->is_open ())
     return 0;
   // Assume success
   gzfilebuf* retval = this;
   // Attempt to sync and close gzipped file
-  if (this->sync() == -1)
+  if (this->sync () == -1)
     retval = 0;
-  if (gzclose(file) < 0)
+  if (gzclose (file) < 0)
     retval = 0;
   // File is now gone anyway (postcondition [27.8.1.3.8])
   file = 0;
   own_fd = false;
   // Destroy internal buffer if it exists
-  this->disable_buffer();
+  this->disable_buffer ();
   return retval;
 }
 
@@ -162,8 +162,8 @@
 
 // Convert int open mode to mode string
 bool
-gzfilebuf::open_mode(std::ios_base::openmode mode,
-                     char* c_mode) const
+gzfilebuf::open_mode (std::ios_base::openmode mode,
+                      char* c_mode) const
 {
   // FIXME -- do we need testb?
   // bool testb = mode & std::ios_base::binary;
@@ -178,13 +178,13 @@
   // excessive though - keeping it at the default level
   // To change back, just append "9" to the next three mode strings
   if (!testi && testo && !testt && !testa)
-    strcpy(c_mode, "w");
+    strcpy (c_mode, "w");
   if (!testi && testo && !testt && testa)
-    strcpy(c_mode, "a");
+    strcpy (c_mode, "a");
   if (!testi && testo && testt && !testa)
-    strcpy(c_mode, "w");
+    strcpy (c_mode, "w");
   if (testi && !testo && !testt && !testa)
-    strcpy(c_mode, "r");
+    strcpy (c_mode, "r");
   // No read/write mode yet
 //  if (testi && testo && !testt && !testa)
 //    strcpy(c_mode, "r+");
@@ -192,24 +192,24 @@
 //    strcpy(c_mode, "w+");
 
   // Mode string should be empty for invalid combination of flags
-  if (strlen(c_mode) == 0)
+  if (strlen (c_mode) == 0)
     return false;
 
-  strcat(c_mode, "b");
+  strcat (c_mode, "b");
 
   return true;
 }
 
 // Determine number of characters in internal get buffer
 std::streamsize
-gzfilebuf::showmanyc()
+gzfilebuf::showmanyc ()
 {
   // Calls to underflow will fail if file not opened for reading
-  if (!this->is_open() || !(io_mode & std::ios_base::in))
+  if (! this->is_open () || !(io_mode & std::ios_base::in))
     return -1;
   // Make sure get area is in use
-  if (this->gptr() && (this->gptr() < this->egptr()))
-    return std::streamsize(this->egptr() - this->gptr());
+  if (this->gptr () && (this->gptr () < this->egptr ()))
+    return std::streamsize (this->egptr () - this->gptr ());
   else
     return 0;
 }
@@ -221,142 +221,142 @@
 gzfilebuf::int_type
 gzfilebuf::pbackfail (gzfilebuf::int_type c)
 {
-  if (this->is_open())
+  if (this->is_open ())
     {
-      if (gzseek (file, this->gptr() - this->egptr() - 1, SEEK_CUR) < 0)
-        return traits_type::eof();
+      if (gzseek (file, this->gptr () - this->egptr () - 1, SEEK_CUR) < 0)
+        return traits_type::eof ();
 
       // Invalidates contents of the buffer
       enable_buffer ();
 
       // Attempt to fill internal buffer from gzipped file
       // (buffer must be guaranteed to exist...)
-      int bytes_read = gzread(file, buffer, buffer_size);
+      int bytes_read = gzread (file, buffer, buffer_size);
       // Indicates error or EOF
       if (bytes_read <= 0)
         {
           // Reset get area
-          this->setg(buffer, buffer, buffer);
-          return traits_type::eof();
+          this->setg (buffer, buffer, buffer);
+          return traits_type::eof ();
         }
 
       // Make all bytes read from file available as get area
-      this->setg(buffer, buffer, buffer + bytes_read);
+      this->setg (buffer, buffer, buffer + bytes_read);
 
       // If next character in get area differs from putback character
       // flag a failure
-      gzfilebuf::int_type ret = traits_type::to_int_type(*(this->gptr()));
+      gzfilebuf::int_type ret = traits_type::to_int_type (*(this->gptr ()));
       if (ret != c)
-        return traits_type::eof();
+        return traits_type::eof ();
       else
         return ret;
     }
   else
-    return traits_type::eof();
+    return traits_type::eof ();
 }
 
 // Fill get area from gzipped file
 gzfilebuf::int_type
-gzfilebuf::underflow()
+gzfilebuf::underflow ()
 {
   // If something is left in the get area by chance, return it
   // (this shouldn't normally happen, as underflow is only supposed
   // to be called when gptr >= egptr, but it serves as error check)
-  if (this->gptr() && (this->gptr() < this->egptr()))
-    return traits_type::to_int_type(*(this->gptr()));
+  if (this->gptr () && (this->gptr () < this->egptr ()))
+    return traits_type::to_int_type (*(this->gptr ()));
 
   // If the file hasn't been opened for reading, produce error
-  if (!this->is_open() || !(io_mode & std::ios_base::in))
-    return traits_type::eof();
+  if (! this->is_open () || !(io_mode & std::ios_base::in))
+    return traits_type::eof ();
 
   // Copy the final characters to the front of the buffer
   int stash = 0;
-  if (this->eback() && buffer && buffer_size > STASHED_CHARACTERS)
+  if (this->eback () && buffer && buffer_size > STASHED_CHARACTERS)
     {
       char_type *ptr1 = buffer;
-      char_type *ptr2 = this->egptr() - STASHED_CHARACTERS + 1;
-      if (ptr2 > this->eback())
+      char_type *ptr2 = this->egptr () - STASHED_CHARACTERS + 1;
+      if (ptr2 > this->eback ())
         while (stash++ <= STASHED_CHARACTERS)
           *ptr1++ = *ptr2++;
     }
 
   // Attempt to fill internal buffer from gzipped file
   // (buffer must be guaranteed to exist...)
-  int bytes_read = gzread(file, buffer + stash, buffer_size - stash);
+  int bytes_read = gzread (file, buffer + stash, buffer_size - stash);
 
   // Indicates error or EOF
   if (bytes_read <= 0)
   {
     // Reset get area
-    this->setg(buffer, buffer, buffer);
-    return traits_type::eof();
+    this->setg (buffer, buffer, buffer);
+    return traits_type::eof ();
   }
   // Make all bytes read from file plus the stash available as get area
-  this->setg(buffer, buffer + stash, buffer + bytes_read + stash);
+  this->setg (buffer, buffer + stash, buffer + bytes_read + stash);
 
   // Return next character in get area
-  return traits_type::to_int_type(*(this->gptr()));
+  return traits_type::to_int_type (*(this->gptr ()));
 }
 
 // Write put area to gzipped file
 gzfilebuf::int_type
-gzfilebuf::overflow(int_type c)
+gzfilebuf::overflow (int_type c)
 {
   // Determine whether put area is in use
-  if (this->pbase())
+  if (this->pbase ())
   {
     // Double-check pointer range
-    if (this->pptr() > this->epptr() || this->pptr() < this->pbase())
-      return traits_type::eof();
+    if (this->pptr () > this->epptr () || this->pptr () < this->pbase ())
+      return traits_type::eof ();
     // Add extra character to buffer if not EOF
-    if (!traits_type::eq_int_type(c, traits_type::eof()))
+    if (! traits_type::eq_int_type (c, traits_type::eof ()))
     {
-      *(this->pptr()) = traits_type::to_char_type(c);
-      this->pbump(1);
+      *(this->pptr ()) = traits_type::to_char_type (c);
+      this->pbump (1);
     }
     // Number of characters to write to file
-    int bytes_to_write = this->pptr() - this->pbase();
+    int bytes_to_write = this->pptr () - this->pbase ();
     // Overflow doesn't fail if nothing is to be written
     if (bytes_to_write > 0)
     {
       // If the file hasn't been opened for writing, produce error
-      if (!this->is_open() || !(io_mode & std::ios_base::out))
-        return traits_type::eof();
+      if (! this->is_open () || !(io_mode & std::ios_base::out))
+        return traits_type::eof ();
       // If gzipped file won't accept all bytes written to it, fail
-      if (gzwrite(file, this->pbase(), bytes_to_write) != bytes_to_write)
-        return traits_type::eof();
+      if (gzwrite (file, this->pbase (), bytes_to_write) != bytes_to_write)
+        return traits_type::eof ();
       // Reset next pointer to point to pbase on success
-      this->pbump(-bytes_to_write);
+      this->pbump (-bytes_to_write);
     }
   }
   // Write extra character to file if not EOF
-  else if (!traits_type::eq_int_type(c, traits_type::eof()))
+  else if (! traits_type::eq_int_type (c, traits_type::eof ()))
   {
     // If the file hasn't been opened for writing, produce error
-    if (!this->is_open() || !(io_mode & std::ios_base::out))
-      return traits_type::eof();
+    if (! this->is_open () || !(io_mode & std::ios_base::out))
+      return traits_type::eof ();
     // Impromptu char buffer (allows "unbuffered" output)
-    char_type last_char = traits_type::to_char_type(c);
+    char_type last_char = traits_type::to_char_type (c);
     // If gzipped file won't accept this character, fail
-    if (gzwrite(file, &last_char, 1) != 1)
-      return traits_type::eof();
+    if (gzwrite (file, &last_char, 1) != 1)
+      return traits_type::eof ();
   }
 
   // If you got here, you have succeeded (even if c was EOF)
   // The return value should therefore be non-EOF
-  if (traits_type::eq_int_type(c, traits_type::eof()))
-    return traits_type::not_eof(c);
+  if (traits_type::eq_int_type (c, traits_type::eof ()))
+    return traits_type::not_eof (c);
   else
     return c;
 }
 
 // Assign new buffer
 std::streambuf*
-gzfilebuf::setbuf(char_type* p,
-                  std::streamsize n)
+gzfilebuf::setbuf (char_type* p,
+                   std::streamsize n)
 {
   // First make sure stuff is sync'ed, for safety
-  if (this->sync() == -1)
+  if (this->sync () == -1)
     return 0;
   // If buffering is turned off on purpose via setbuf(0,0), still allocate one...
   // "Unbuffered" only really refers to put [27.8.1.4.10], while get needs at
@@ -365,36 +365,36 @@
   if (!p || !n)
   {
     // Replace existing buffer (if any) with small internal buffer
-    this->disable_buffer();
+    this->disable_buffer ();
     buffer = 0;
     buffer_size = 0;
     own_buffer = true;
-    this->enable_buffer();
+    this->enable_buffer ();
   }
   else
   {
     // Replace existing buffer (if any) with external buffer
-    this->disable_buffer();
+    this->disable_buffer ();
     buffer = p;
     buffer_size = n;
     own_buffer = false;
-    this->enable_buffer();
+    this->enable_buffer ();
   }
   return this;
 }
 
 // Write put area to gzipped file (i.e. ensures that put area is empty)
 int
-gzfilebuf::sync()
+gzfilebuf::sync ()
 {
-  return traits_type::eq_int_type(this->overflow(), traits_type::eof()) ? -1 : 0;
+  return traits_type::eq_int_type (this->overflow (), traits_type::eof ()) ? -1 : 0;
 }
 
 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
 
 // Allocate internal buffer
 void
-gzfilebuf::enable_buffer()
+gzfilebuf::enable_buffer ()
 {
   // If internal buffer required, allocate one
   if (own_buffer && !buffer)
@@ -403,57 +403,57 @@
     if (buffer_size > 0)
     {
       // Allocate internal buffer
-      buffer = new char_type[buffer_size];
+      buffer = new char_type [buffer_size];
       // Get area starts empty and will be expanded by underflow as need arises
-      this->setg(buffer, buffer, buffer);
+      this->setg (buffer, buffer, buffer);
       // Setup entire internal buffer as put area.
       // The one-past-end pointer actually points to the last element of the buffer,
       // so that overflow(c) can safely add the extra character c to the sequence.
       // These pointers remain in place for the duration of the buffer
-      this->setp(buffer, buffer + buffer_size - 1);
+      this->setp (buffer, buffer + buffer_size - 1);
     }
     else
     {
       // Even in "unbuffered" case, (small?) get buffer is still required
       buffer_size = SMALLBUFSIZE;
-      buffer = new char_type[buffer_size];
-      this->setg(buffer, buffer, buffer);
+      buffer = new char_type [buffer_size];
+      this->setg (buffer, buffer, buffer);
       // "Unbuffered" means no put buffer
-      this->setp(0, 0);
+      this->setp (0, 0);
     }
   }
   else
   {
     // If buffer already allocated, reset buffer pointers just to make sure no
     // stale chars are lying around
-    this->setg(buffer, buffer, buffer);
-    this->setp(buffer, buffer + buffer_size - 1);
+    this->setg (buffer, buffer, buffer);
+    this->setp (buffer, buffer + buffer_size - 1);
   }
 }
 
 // Destroy internal buffer
 void
-gzfilebuf::disable_buffer()
+gzfilebuf::disable_buffer ()
 {
   // If internal buffer exists, deallocate it
   if (own_buffer && buffer)
   {
     // Preserve unbuffered status by zeroing size
-    if (!this->pbase())
+    if (! this->pbase ())
       buffer_size = 0;
     delete[] buffer;
     buffer = 0;
-    this->setg(0, 0, 0);
-    this->setp(0, 0);
+    this->setg (0, 0, 0);
+    this->setp (0, 0);
   }
   else
   {
     // Reset buffer pointers to initial state if external buffer exists
-    this->setg(buffer, buffer, buffer);
+    this->setg (buffer, buffer, buffer);
     if (buffer)
-      this->setp(buffer, buffer + buffer_size - 1);
+      this->setp (buffer, buffer + buffer_size - 1);
     else
-      this->setp(0, 0);
+      this->setp (0, 0);
   }
 }
 
@@ -461,17 +461,17 @@
 
 // Seek functions
 gzfilebuf::pos_type
-gzfilebuf::seekoff(off_type off, std::ios_base::seekdir way,
+gzfilebuf::seekoff (off_type off, std::ios_base::seekdir way,
                    std::ios_base::openmode)
 {
   pos_type ret = pos_type (off_type (-1));
 
-  if (this->is_open())
+  if (this->is_open ())
     {
       off_type computed_off = off;
 
       if ((io_mode & std::ios_base::in) && way == std::ios_base::cur)
-        computed_off += this->gptr() - this->egptr();
+        computed_off += this->gptr () - this->egptr ();
 
       // Handle tellg/tellp as a special case up front, no need to seek
       // or invalidate get/put buffers
@@ -498,7 +498,7 @@
 }
 
 gzfilebuf::pos_type
-gzfilebuf::seekpos(pos_type sp, std::ios_base::openmode)
+gzfilebuf::seekpos (pos_type sp, std::ios_base::openmode)
 {
   pos_type ret = pos_type (off_type (-1));
 
@@ -520,111 +520,111 @@
 /*****************************************************************************/
 
 // Default constructor initializes stream buffer
-gzifstream::gzifstream()
-: std::istream(0), sb()
-{ this->init(&sb); }
+gzifstream::gzifstream ()
+: std::istream (0), sb ()
+{ this->init (&sb); }
 
 // Initialize stream buffer and open file
-gzifstream::gzifstream(const char* name,
-                       std::ios_base::openmode mode)
-: std::istream(0), sb()
+gzifstream::gzifstream (const char* name,
+                        std::ios_base::openmode mode)
+: std::istream (0), sb ()
 {
-  this->init(&sb);
-  this->open(name, mode);
+  this->init (&sb);
+  this->open (name, mode);
 }
 
 // Initialize stream buffer and attach to file
-gzifstream::gzifstream(int fd,
-                       std::ios_base::openmode mode)
-: std::istream(0), sb()
+gzifstream::gzifstream (int fd,
+                        std::ios_base::openmode mode)
+: std::istream (0), sb ()
 {
-  this->init(&sb);
-  this->attach(fd, mode);
+  this->init (&sb);
+  this->attach (fd, mode);
 }
 
 // Open file and go into fail() state if unsuccessful
 void
-gzifstream::open(const char* name,
-                 std::ios_base::openmode mode)
+gzifstream::open (const char* name,
+                  std::ios_base::openmode mode)
 {
-  if (!sb.open(name, mode | std::ios_base::in))
-    this->setstate(std::ios_base::failbit);
+  if (! sb.open (name, mode | std::ios_base::in))
+    this->setstate (std::ios_base::failbit);
   else
-    this->clear();
+    this->clear ();
 }
 
 // Attach to file and go into fail() state if unsuccessful
 void
-gzifstream::attach(int fd,
-                   std::ios_base::openmode mode)
+gzifstream::attach (int fd,
+                    std::ios_base::openmode mode)
 {
-  if (!sb.attach(fd, mode | std::ios_base::in))
-    this->setstate(std::ios_base::failbit);
+  if (! sb.attach (fd, mode | std::ios_base::in))
+    this->setstate (std::ios_base::failbit);
   else
-    this->clear();
+    this->clear ();
 }
 
 // Close file
 void
-gzifstream::close()
+gzifstream::close ()
 {
-  if (!sb.close())
-    this->setstate(std::ios_base::failbit);
+  if (! sb.close ())
+    this->setstate (std::ios_base::failbit);
 }
 
 /*****************************************************************************/
 
 // Default constructor initializes stream buffer
-gzofstream::gzofstream()
-: std::ostream(0), sb()
-{ this->init(&sb); }
+gzofstream::gzofstream ()
+: std::ostream (0), sb ()
+{ this->init (&sb); }
 
 // Initialize stream buffer and open file
-gzofstream::gzofstream(const char* name,
-                       std::ios_base::openmode mode)
-: std::ostream(0), sb()
+gzofstream::gzofstream (const char* name,
+                        std::ios_base::openmode mode)
+: std::ostream (0), sb ()
 {
-  this->init(&sb);
-  this->open(name, mode);
+  this->init (&sb);
+  this->open (name, mode);
 }
 
 // Initialize stream buffer and attach to file
-gzofstream::gzofstream(int fd,
-                       std::ios_base::openmode mode)
-: std::ostream(0), sb()
+gzofstream::gzofstream (int fd,
+                        std::ios_base::openmode mode)
+: std::ostream (0), sb ()
 {
-  this->init(&sb);
-  this->attach(fd, mode);
+  this->init (&sb);
+  this->attach (fd, mode);
 }
 
 // Open file and go into fail() state if unsuccessful
 void
-gzofstream::open(const char* name,
-                 std::ios_base::openmode mode)
+gzofstream::open (const char* name,
+                  std::ios_base::openmode mode)
 {
-  if (!sb.open(name, mode | std::ios_base::out))
-    this->setstate(std::ios_base::failbit);
+  if (! sb.open (name, mode | std::ios_base::out))
+    this->setstate (std::ios_base::failbit);
   else
-    this->clear();
+    this->clear ();
 }
 
 // Attach to file and go into fail() state if unsuccessful
 void
-gzofstream::attach(int fd,
-                   std::ios_base::openmode mode)
+gzofstream::attach (int fd,
+                    std::ios_base::openmode mode)
 {
-  if (!sb.attach(fd, mode | std::ios_base::out))
-    this->setstate(std::ios_base::failbit);
+  if (! sb.attach (fd, mode | std::ios_base::out))
+    this->setstate (std::ios_base::failbit);
   else
-    this->clear();
+    this->clear ();
 }
 
 // Close file
 void
-gzofstream::close()
+gzofstream::close ()
 {
-  if (!sb.close())
-    this->setstate(std::ios_base::failbit);
+  if (! sb.close ())
+    this->setstate (std::ios_base::failbit);
 }
 
 #endif // HAVE_ZLIB
rename from src/zfstream.h
rename to libinterp/interp-core/zfstream.h
--- a/src/zfstream.h
+++ b/libinterp/interp-core/zfstream.h
@@ -53,11 +53,11 @@
 {
 public:
   //  Default constructor.
-  gzfilebuf();
+  gzfilebuf ();
 
   //  Destructor.
   virtual
-  ~gzfilebuf();
+  ~gzfilebuf ();
 
   /**
    *  @brief  Set compression level and strategy on the fly.
@@ -71,15 +71,15 @@
    *  setcompressionlevel(level).
   */
   int
-  setcompression(int comp_level,
-                 int comp_strategy = Z_DEFAULT_STRATEGY);
+  setcompression (int comp_level,
+                  int comp_strategy = Z_DEFAULT_STRATEGY);
 
   /**
    *  @brief  Check if file is open.
    *  @return  True if file is open.
   */
   bool
-  is_open() const { return (file != 0); }
+  is_open () const { return (file != 0); }
 
   /**
    *  @brief  Open gzipped file.
@@ -88,8 +88,8 @@
    *  @return  @c this on success, NULL on failure.
   */
   gzfilebuf*
-  open(const char* name,
-       std::ios_base::openmode mode);
+  open (const char* name,
+        std::ios_base::openmode mode);
 
   /**
    *  @brief  Attach to already open gzipped file.
@@ -98,15 +98,15 @@
    *  @return  @c this on success, NULL on failure.
   */
   gzfilebuf*
-  attach(int fd,
-         std::ios_base::openmode mode);
+  attach (int fd,
+          std::ios_base::openmode mode);
 
   /**
    *  @brief  Close gzipped file.
    *  @return  @c this on success, NULL on failure.
   */
   gzfilebuf*
-  close();
+  close ();
 
 protected:
   /**
@@ -114,8 +114,8 @@
    *  @return  True if valid mode flag combination.
   */
   bool
-  open_mode(std::ios_base::openmode mode,
-            char* c_mode) const;
+  open_mode (std::ios_base::openmode mode,
+             char* c_mode) const;
 
   /**
    *  @brief  Number of characters available in stream buffer.
@@ -125,7 +125,7 @@
    *  These characters can be read without accessing the gzipped file.
   */
   virtual std::streamsize
-  showmanyc();
+  showmanyc ();
 
   /**
    *  @brief  Fill get area from gzipped file.
@@ -135,7 +135,7 @@
    *  buffer. Always buffered.
   */
   virtual int_type
-  underflow();
+  underflow ();
 
   /**
    *  @brief  Write put area to gzipped file.
@@ -147,7 +147,7 @@
    *  character at a time.
   */
   virtual int_type
-  overflow(int_type c = traits_type::eof());
+  overflow (int_type c = traits_type::eof ());
 
   /**
    *  @brief  Installs external stream buffer.
@@ -158,8 +158,8 @@
    *  Call setbuf(0,0) to enable unbuffered output.
   */
   virtual std::streambuf*
-  setbuf(char_type* p,
-         std::streamsize n);
+  setbuf (char_type* p,
+          std::streamsize n);
 
   /**
    *  @brief  Flush stream buffer to file.
@@ -168,7 +168,7 @@
    *  This calls underflow(EOF) to do the job.
   */
   virtual int
-  sync();
+  sync ();
 
   /**
    *  @brief  Alters the stream positions.
@@ -176,9 +176,9 @@
    *  Each derived class provides its own appropriate behavior.
    */
   virtual pos_type
-  seekoff(off_type off, std::ios_base::seekdir way,
-          std::ios_base::openmode mode =
-          std::ios_base::in|std::ios_base::out);
+  seekoff (off_type off, std::ios_base::seekdir way,
+           std::ios_base::openmode mode =
+           std::ios_base::in|std::ios_base::out);
 
   /**
    *  @brief  Alters the stream positions.
@@ -186,11 +186,11 @@
    *  Each derived class provides its own appropriate behavior.
    */
   virtual pos_type
-  seekpos(pos_type sp, std::ios_base::openmode mode =
-          std::ios_base::in|std::ios_base::out);
+  seekpos (pos_type sp, std::ios_base::openmode mode =
+           std::ios_base::in|std::ios_base::out);
 
   virtual int_type
-  pbackfail (int_type c = traits_type::eof());
+  pbackfail (int_type c = traits_type::eof ());
 
 //
 // Some future enhancements
@@ -215,7 +215,7 @@
    *  reset to their original state.
   */
   void
-  enable_buffer();
+  enable_buffer ();
 
   /**
    *  @brief  Destroy internal buffer.
@@ -225,7 +225,7 @@
    *  case, it will also reset the buffer pointers.
   */
   void
-  disable_buffer();
+  disable_buffer ();
 
   /**
    *  Underlying file pointer.
@@ -282,7 +282,7 @@
 {
 public:
   //  Default constructor
-  gzifstream();
+  gzifstream ();
 
   /**
    *  @brief  Construct stream on gzipped file to be opened.
@@ -290,8 +290,8 @@
    *  @param  mode  Open mode flags (forced to contain ios::in).
   */
   explicit
-  gzifstream(const char* name,
-             std::ios_base::openmode mode = std::ios_base::in);
+  gzifstream (const char* name,
+              std::ios_base::openmode mode = std::ios_base::in);
 
   /**
    *  @brief  Construct stream on already open gzipped file.
@@ -299,14 +299,14 @@
    *  @param  mode  Open mode flags (forced to contain ios::in).
   */
   explicit
-  gzifstream(int fd,
-             std::ios_base::openmode mode = std::ios_base::in);
+  gzifstream (int fd,
+              std::ios_base::openmode mode = std::ios_base::in);
 
   /**
    *  Obtain underlying stream buffer.
   */
   gzfilebuf*
-  rdbuf() const
+  rdbuf () const
   { return const_cast<gzfilebuf*>(&sb); }
 
   /**
@@ -314,7 +314,7 @@
    *  @return  True if file is open.
   */
   bool
-  is_open() { return sb.is_open(); }
+  is_open () { return sb.is_open (); }
 
   /**
    *  @brief  Open gzipped file.
@@ -329,8 +329,8 @@
    *  convenience.
   */
   void
-  open(const char* name,
-       std::ios_base::openmode mode = std::ios_base::in);
+  open (const char* name,
+        std::ios_base::openmode mode = std::ios_base::in);
 
   /**
    *  @brief  Attach to already open gzipped file.
@@ -341,8 +341,8 @@
    *  in state fail().
   */
   void
-  attach(int fd,
-         std::ios_base::openmode mode = std::ios_base::in);
+  attach (int fd,
+          std::ios_base::openmode mode = std::ios_base::in);
 
   /**
    *  @brief  Close gzipped file.
@@ -350,7 +350,7 @@
    *  Stream will be in state fail() if close failed.
   */
   void
-  close();
+  close ();
 
 private:
   /**
@@ -371,7 +371,7 @@
 {
 public:
   //  Default constructor
-  gzofstream();
+  gzofstream ();
 
   /**
    *  @brief  Construct stream on gzipped file to be opened.
@@ -379,8 +379,8 @@
    *  @param  mode  Open mode flags (forced to contain ios::out).
   */
   explicit
-  gzofstream(const char* name,
-             std::ios_base::openmode mode = std::ios_base::out);
+  gzofstream (const char* name,
+              std::ios_base::openmode mode = std::ios_base::out);
 
   /**
    *  @brief  Construct stream on already open gzipped file.
@@ -388,14 +388,14 @@
    *  @param  mode  Open mode flags (forced to contain ios::out).
   */
   explicit
-  gzofstream(int fd,
-             std::ios_base::openmode mode = std::ios_base::out);
+  gzofstream (int fd,
+              std::ios_base::openmode mode = std::ios_base::out);
 
   /**
    *  Obtain underlying stream buffer.
   */
   gzfilebuf*
-  rdbuf() const
+  rdbuf () const
   { return const_cast<gzfilebuf*>(&sb); }
 
   /**
@@ -403,7 +403,7 @@
    *  @return  True if file is open.
   */
   bool
-  is_open() { return sb.is_open(); }
+  is_open () { return sb.is_open (); }
 
   /**
    *  @brief  Open gzipped file.
@@ -418,8 +418,8 @@
    *  convenience.
   */
   void
-  open(const char* name,
-       std::ios_base::openmode mode = std::ios_base::out);
+  open (const char* name,
+        std::ios_base::openmode mode = std::ios_base::out);
 
   /**
    *  @brief  Attach to already open gzipped file.
@@ -430,8 +430,8 @@
    *  in state fail().
   */
   void
-  attach(int fd,
-         std::ios_base::openmode mode = std::ios_base::out);
+  attach (int fd,
+          std::ios_base::openmode mode = std::ios_base::out);
 
   /**
    *  @brief  Close gzipped file.
@@ -439,7 +439,7 @@
    *  Stream will be in state fail() if close failed.
   */
   void
-  close();
+  close ();
 
 private:
   /**
@@ -467,9 +467,9 @@
                  const gzomanip2<Ta,Tb>&);
 
     // Constructor
-    gzomanip2(gzofstream& (*f)(gzofstream&, T1, T2),
-              T1 v1,
-              T2 v2);
+    gzomanip2 (gzofstream& (*f)(gzofstream&, T1, T2),
+               T1 v1,
+               T2 v2);
   private:
     // Underlying manipulator function
     gzofstream&
@@ -484,18 +484,18 @@
 
 // Manipulator function thunks through to stream buffer
 inline gzofstream&
-setcompression(gzofstream &gzs, int l, int s = Z_DEFAULT_STRATEGY)
+setcompression (gzofstream &gzs, int l, int s = Z_DEFAULT_STRATEGY)
 {
-  (gzs.rdbuf())->setcompression(l, s);
+  (gzs.rdbuf ())->setcompression (l, s);
   return gzs;
 }
 
 // Manipulator constructor stores arguments
 template<typename T1, typename T2>
   inline
-  gzomanip2<T1,T2>::gzomanip2(gzofstream &(*f)(gzofstream &, T1, T2),
-                              T1 v1,
-                              T2 v2)
+  gzomanip2<T1,T2>::gzomanip2 (gzofstream &(*f)(gzofstream &, T1, T2),
+                               T1 v1,
+                               T2 v2)
   : func(f), val1(v1), val2(v2)
   { }
 
@@ -507,7 +507,7 @@
 
 // Insert this onto stream to simplify setting of compression level
 inline gzomanip2<int,int>
-setcompression(int l, int s = Z_DEFAULT_STRATEGY)
+setcompression (int l, int s = Z_DEFAULT_STRATEGY)
 { return gzomanip2<int,int>(&setcompression, l, s); }
 
 #endif // HAVE_ZLIB
rename from src/data.cc
rename to libinterp/interpfcn/data.cc
--- a/src/data.cc
+++ b/libinterp/interpfcn/data.cc
@@ -3,6 +3,7 @@
 Copyright (C) 1994-2012 John W. Eaton
 Copyright (C) 2009 Jaroslav Hajek
 Copyright (C) 2009-2010 VZLU Prague
+Copyright (C) 2012 Carlo de Falco
 
 This file is part of Octave.
 
@@ -40,6 +41,7 @@
 
 #include "lo-ieee.h"
 #include "lo-math.h"
+#include "oct-base64.h"
 #include "oct-time.h"
 #include "str-vec.h"
 #include "quit.h"
@@ -119,7 +121,7 @@
 @example\n\
 @group\n\
 all ([2, 3; 1, 0]))\n\
-     @result{} [ 1, 0 ]\n\
+    @result{} [ 1, 0 ]\n\
 @end group\n\
 @end example\n\
 \n\
@@ -132,27 +134,25 @@
 }
 
 /*
-
 %!test
 %! x = ones (3);
 %! x(1,1) = 0;
-%! assert((all (all (rand (3) + 1) == [1, 1, 1]) == 1
-%! && all (all (x) == [0, 1, 1]) == 1
-%! && all (x, 1) == [0, 1, 1]
-%! && all (x, 2) == [0; 1; 1]));
+%! assert (all (all (rand (3) + 1) == [1, 1, 1]) == 1);
+%! assert (all (all (x) == [0, 1, 1]) == 1);
+%! assert (all (x, 1) == [0, 1, 1]);
+%! assert (all (x, 2) == [0; 1; 1]);
 
 %!test
-%! x = ones (3, 'single');
+%! x = ones (3, "single");
 %! x(1,1) = 0;
-%! assert((all (all (single (rand (3) + 1)) == [1, 1, 1]) == 1
-%! && all (all (x) == [0, 1, 1]) == 1
-%! && all (x, 1) == [0, 1, 1]
-%! && all (x, 2) == [0; 1; 1]));
-
-%!error <Invalid call to all> all ();
-%!error <Invalid call to all> all (1, 2, 3);
-
- */
+%! assert (all (all (single (rand (3) + 1)) == [1, 1, 1]) == 1);
+%! assert (all (all (x) == [0, 1, 1]) == 1);
+%! assert (all (x, 1) == [0, 1, 1]);
+%! assert (all (x, 2) == [0; 1; 1]);
+
+%!error all ()
+%!error all (1, 2, 3)
+*/
 
 DEFUN (any, args, ,
   "-*- texinfo -*-\n\
@@ -168,7 +168,7 @@
 @example\n\
 @group\n\
 any (eye (2, 4))\n\
-     @result{} [ 1, 1, 0, 0 ]\n\
+ @result{} [ 1, 1, 0, 0 ]\n\
 @end group\n\
 @end example\n\
 \n\
@@ -178,7 +178,7 @@
 @example\n\
 @group\n\
 any (eye (2, 4), 2)\n\
-     @result{} [ 1; 1 ]\n\
+ @result{} [ 1; 1 ]\n\
 @end group\n\
 @end example\n\
 @seealso{all}\n\
@@ -188,27 +188,25 @@
 }
 
 /*
-
 %!test
 %! x = zeros (3);
 %! x(3,3) = 1;
-%! assert((all (any (x) == [0, 0, 1]) == 1
-%! && all (any (ones (3)) == [1, 1, 1]) == 1
-%! && any (x, 1) == [0, 0, 1]
-%! && any (x, 2) == [0; 0; 1]));
+%! assert (all (any (x) == [0, 0, 1]) == 1);
+%! assert (all (any (ones (3)) == [1, 1, 1]) == 1);
+%! assert (any (x, 1) == [0, 0, 1]);
+%! assert (any (x, 2) == [0; 0; 1]);
 
 %!test
-%! x = zeros (3,'single');
+%! x = zeros (3, "single");
 %! x(3,3) = 1;
-%! assert((all (any (x) == [0, 0, 1]) == 1
-%! && all (any (ones (3, 'single')) == [1, 1, 1]) == 1
-%! && any (x, 1) == [0, 0, 1]
-%! && any (x, 2) == [0; 0; 1]));
-
-%!error <Invalid call to any> any ();
-%!error <Invalid call to any> any (1, 2, 3);
-
- */
+%! assert (all (any (x) == [0, 0, 1]) == 1);
+%! assert (all (any (ones (3, "single")) == [1, 1, 1]) == 1);
+%! assert (any (x, 1) == [0, 0, 1]);
+%! assert (any (x, 2) == [0; 0; 1]);
+
+%!error any ()
+%!error any (1, 2, 3)
+*/
 
 // These mapping functions may also be useful in other places, eh?
 
@@ -218,6 +216,7 @@
 Compute atan (@var{y} / @var{x}) for corresponding elements of @var{y}\n\
 and @var{x}.  Signal an error if @var{y} and @var{x} do not match in size\n\
 and orientation.\n\
+@seealso{tan, tand, tanh, atanh}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -283,19 +282,18 @@
 %! v = [0, pi/6, pi/4, pi/3, -pi/3, -pi/4, -pi/6, 0];
 %! y = [0, rt3, 1, rt3, -rt3, -1, -rt3, 0];
 %! x = [1, 3, 1, 1, 1, 1, 3, 1];
-%! assert(atan2 (y, x), v, sqrt (eps));
+%! assert (atan2 (y, x), v, sqrt (eps));
 
 %!test
 %! rt2 = sqrt (2);
 %! rt3 = sqrt (3);
-%! v = single([0, pi/6, pi/4, pi/3, -pi/3, -pi/4, -pi/6, 0]);
-%! y = single([0, rt3, 1, rt3, -rt3, -1, -rt3, 0]);
-%! x = single([1, 3, 1, 1, 1, 1, 3, 1]);
-%! assert(atan2 (y, x), v, sqrt (eps('single')));
-
-%!error <Invalid call to atan2> atan2 ();
-%!error <Invalid call to atan2> atan2 (1, 2, 3);
-
+%! v = single ([0, pi/6, pi/4, pi/3, -pi/3, -pi/4, -pi/6, 0]);
+%! y = single ([0, rt3, 1, rt3, -rt3, -1, -rt3, 0]);
+%! x = single ([1, 3, 1, 1, 1, 1, 3, 1]);
+%! assert (atan2 (y, x), v, sqrt (eps ("single")));
+
+%!error atan2 ()
+%!error atan2 (1, 2, 3)
 */
 
 
@@ -365,8 +363,8 @@
 \n\
 @example\n\
 @group\n\
-  hypot (hypot (@var{x}, @var{y}), @var{z})\n\
-  hypot (hypot (hypot (@var{x}, @var{y}), @var{z}), @var{w}), etc.\n\
+hypot (hypot (@var{x}, @var{y}), @var{z})\n\
+hypot (hypot (hypot (@var{x}, @var{y}), @var{z}), @var{w}), etc.\n\
 @end group\n\
 @end example\n\
 @end deftypefn")
@@ -397,8 +395,8 @@
 %!assert (size (hypot (rand (2, 3, 4), 1)), [2, 3, 4])
 %!assert (size (hypot (1, rand (2, 3, 4))), [2, 3, 4])
 %!assert (size (hypot (1, 2)), [1, 1])
-%!assert (hypot (1:10, 1:10), sqrt(2) * [1:10], 16*eps)
-%!assert (hypot (single(1:10), single(1:10)), single(sqrt(2) * [1:10]));
+%!assert (hypot (1:10, 1:10), sqrt (2) * [1:10], 16*eps)
+%!assert (hypot (single (1:10), single (1:10)), single (sqrt (2) * [1:10]))
 */
 
 template<typename T, typename ET>
@@ -454,8 +452,8 @@
               // FIXME -- should E be an int value?
               FloatMatrix e;
               map_2_xlog2 (x, f, e);
-              retval (1) = e;
-              retval (0) = f;
+              retval(1) = e;
+              retval(0) = f;
             }
           else if (args(0).is_complex_type ())
             {
@@ -464,8 +462,8 @@
               // FIXME -- should E be an int value?
               FloatNDArray e;
               map_2_xlog2 (x, f, e);
-              retval (1) = e;
-              retval (0) = f;
+              retval(1) = e;
+              retval(0) = f;
             }
         }
       else if (args(0).is_real_type ())
@@ -475,8 +473,8 @@
           // FIXME -- should E be an int value?
           Matrix e;
           map_2_xlog2 (x, f, e);
-          retval (1) = e;
-          retval (0) = f;
+          retval(1) = e;
+          retval(0) = f;
         }
       else if (args(0).is_complex_type ())
         {
@@ -485,8 +483,8 @@
           // FIXME -- should E be an int value?
           NDArray e;
           map_2_xlog2 (x, f, e);
-          retval (1) = e;
-          retval (0) = f;
+          retval(1) = e;
+          retval(0) = f;
         }
       else
         gripe_wrong_type_arg ("log2", args(0));
@@ -498,16 +496,16 @@
 }
 
 /*
-%!assert(log2 ([1/4, 1/2, 1, 2, 4]), [-2, -1, 0, 1, 2]);
-%!assert(log2(Inf), Inf);
-%!assert(isnan(log2(NaN)));
-%!assert(log2(4*i), 2 + log2(1*i));
-%!assert(log2(complex(0,Inf)), Inf + log2(i));
+%!assert (log2 ([1/4, 1/2, 1, 2, 4]), [-2, -1, 0, 1, 2])
+%!assert (log2 (Inf), Inf)
+%!assert (isnan (log2 (NaN)))
+%!assert (log2 (4*i), 2 + log2 (1*i))
+%!assert (log2 (complex (0,Inf)), Inf + log2 (i))
 
 %!test
 %! [f, e] = log2 ([0,-1; 2,-4; Inf,-Inf]);
 %! assert (f, [0,-0.5; 0.5,-0.5; Inf,-Inf]);
-%! assert (e(1:2,:), [0,1;2,3])
+%! assert (e(1:2,:), [0,1;2,3]);
 
 %!test
 %! [f, e] = log2 (complex (zeros (3, 2), [0,-1; 2,-4; Inf,-Inf]));
@@ -620,21 +618,21 @@
 }
 
 /*
-
-%!assert(rem ([1, 2, 3; -1, -2, -3], 2), [1, 0, 1; -1, 0, -1]);
-%!assert(rem ([1, 2, 3; -1, -2, -3], 2 * ones (2, 3)),[1, 0, 1; -1, 0, -1]);
-%!error rem ();
-%!error rem (1, 2, 3);
-%!error rem ([1, 2], [3, 4, 5]);
-%!error rem (i, 1);
-%!assert(rem (uint8([1, 2, 3; -1, -2, -3]), uint8 (2)), uint8([1, 0, 1; -1, 0, -1]));
-%!assert(uint8(rem ([1, 2, 3; -1, -2, -3], 2 * ones (2, 3))),uint8([1, 0, 1; -1, 0, -1]));
-%!error rem (uint(8),int8(5));
-%!error rem (uint8([1, 2]), uint8([3, 4, 5]));
-
+%!assert (rem ([1, 2, 3; -1, -2, -3], 2), [1, 0, 1; -1, 0, -1])
+%!assert (rem ([1, 2, 3; -1, -2, -3], 2 * ones (2, 3)),[1, 0, 1; -1, 0, -1])
+%!assert (rem (uint8 ([1, 2, 3; -1, -2, -3]), uint8 (2)), uint8 ([1, 0, 1; -1, 0, -1]))
+%!assert (uint8 (rem ([1, 2, 3; -1, -2, -3], 2 * ones (2, 3))),uint8 ([1, 0, 1; -1, 0, -1]))
+
+%!error rem (uint (8), int8 (5))
+%!error rem (uint8 ([1, 2]), uint8 ([3, 4, 5]))
+%!error rem ()
+%!error rem (1, 2, 3)
+%!error rem ([1, 2], [3, 4, 5])
+%!error rem (i, 1)
 */
 
 /*
+
 %!assert (size (fmod (zeros (0, 2), zeros (0, 2))), [0, 2])
 %!assert (size (fmod (rand (2, 3, 4), zeros (2, 3, 4))), [2, 3, 4])
 %!assert (size (fmod (rand (2, 3, 4), 1)), [2, 3, 4])
@@ -754,48 +752,48 @@
 
 /*
 ## empty input test
-%!assert (isempty(mod([], [])));
+%!assert (isempty (mod ([], [])))
 
 ## x mod y, y != 0 tests
-%!assert (mod(5, 3), 2);
-%!assert (mod(-5, 3), 1);
-%!assert (mod(0, 3), 0);
-%!assert (mod([-5, 5, 0], [3, 3, 3]), [1, 2, 0]);
-%!assert (mod([-5; 5; 0], [3; 3; 3]), [1; 2; 0]);
-%!assert (mod([-5, 5; 0, 3], [3, 3 ; 3, 1]), [1, 2 ; 0, 0]);
+%!assert (mod (5, 3), 2)
+%!assert (mod (-5, 3), 1)
+%!assert (mod (0, 3), 0)
+%!assert (mod ([-5, 5, 0], [3, 3, 3]), [1, 2, 0])
+%!assert (mod ([-5; 5; 0], [3; 3; 3]), [1; 2; 0])
+%!assert (mod ([-5, 5; 0, 3], [3, 3 ; 3, 1]), [1, 2 ; 0, 0])
 
 ## x mod 0 tests
-%!assert (mod(5, 0), 5);
-%!assert (mod(-5, 0), -5);
-%!assert (mod([-5, 5, 0], [3, 0, 3]), [1, 5, 0]);
-%!assert (mod([-5; 5; 0], [3; 0; 3]), [1; 5; 0]);
-%!assert (mod([-5, 5; 0, 3], [3, 0 ; 3, 1]), [1, 5 ; 0, 0]);
-%!assert (mod([-5, 5; 0, 3], [0, 0 ; 0, 0]), [-5, 5; 0, 3]);
+%!assert (mod (5, 0), 5)
+%!assert (mod (-5, 0), -5)
+%!assert (mod ([-5, 5, 0], [3, 0, 3]), [1, 5, 0])
+%!assert (mod ([-5; 5; 0], [3; 0; 3]), [1; 5; 0])
+%!assert (mod ([-5, 5; 0, 3], [3, 0 ; 3, 1]), [1, 5 ; 0, 0])
+%!assert (mod ([-5, 5; 0, 3], [0, 0 ; 0, 0]), [-5, 5; 0, 3])
 
 ## mixed scalar/matrix tests
-%!assert (mod([-5, 5; 0, 3], 0), [-5, 5; 0, 3]);
-%!assert (mod([-5, 5; 0, 3], 3), [1, 2; 0, 0]);
-%!assert (mod(-5,[0,0; 0,0]), [-5, -5; -5, -5]);
-%!assert (mod(-5,[3,0; 3,1]), [1, -5; 1, 0]);
-%!assert (mod(-5,[3,2; 3,1]), [1, 1; 1, 0]);
+%!assert (mod ([-5, 5; 0, 3], 0), [-5, 5; 0, 3])
+%!assert (mod ([-5, 5; 0, 3], 3), [1, 2; 0, 0])
+%!assert (mod (-5, [0,0; 0,0]), [-5, -5; -5, -5])
+%!assert (mod (-5, [3,0; 3,1]), [1, -5; 1, 0])
+%!assert (mod (-5, [3,2; 3,1]), [1, 1; 1, 0])
 
 ## integer types
-%!assert (mod(uint8(5),uint8(4)),uint8(1))
-%!assert (mod(uint8([1:5]),uint8(4)),uint8([1,2,3,0,1]))
-%!assert (mod(uint8([1:5]),uint8(0)),uint8([1:5]))
-%!error (mod(uint8(5),int8(4)))
+%!assert (mod (uint8 (5), uint8 (4)), uint8 (1))
+%!assert (mod (uint8 ([1:5]), uint8 (4)), uint8 ([1,2,3,0,1]))
+%!assert (mod (uint8 ([1:5]), uint8 (0)), uint8 ([1:5]))
+%!error (mod (uint8 (5), int8 (4)))
 
 ## mixed integer/real types
-%!assert (mod(uint8(5),4),uint8(1))
-%!assert (mod(5,uint8(4)),uint8(1))
-%!assert (mod(uint8([1:5]),4),uint8([1,2,3,0,1]))
+%!assert (mod (uint8 (5), 4), uint8 (1))
+%!assert (mod (5, uint8 (4)), uint8 (1))
+%!assert (mod (uint8 ([1:5]), 4), uint8 ([1,2,3,0,1]))
 
 ## non-integer real numbers
 %!assert (mod (2.1, 0.1), 0)
 %!assert (mod (2.1, 0.2), 0.1, eps)
 */
 
-// FIXME Need to convert the reduction functions of this file for single precision
+// FIXME: Need to convert the reduction functions of this file for single precision
 
 #define NATIVE_REDUCTION_1(FCN, TYPE, DIM) \
   (arg.is_ ## TYPE ## _type ()) \
@@ -1068,39 +1066,37 @@
 }
 
 /*
-
-%!assert (cumprod ([1, 2, 3]), [1, 2, 6]);
-%!assert (cumprod ([-1; -2; -3]), [-1; 2; -6]);
-%!assert (cumprod ([i, 2+i, -3+2i, 4]), [i, -1+2i, -1-8i, -4-32i]);
-%!assert (cumprod ([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i]), [1, 2, 3; i, 4i, 9i; -1+i, -8+8i, -27+27i]);
-
-%!assert (cumprod (single([1, 2, 3])), single([1, 2, 6]));
-%!assert (cumprod (single([-1; -2; -3])), single([-1; 2; -6]));
-%!assert (cumprod (single([i, 2+i, -3+2i, 4])), single([i, -1+2i, -1-8i, -4-32i]));
-%!assert (cumprod (single([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i])), single([1, 2, 3; i, 4i, 9i; -1+i, -8+8i, -27+27i]));
-
-%!error <Invalid call to cumprod> cumprod ();
-
-%!assert (cumprod ([2, 3; 4, 5], 1), [2, 3; 8, 15]);
-%!assert (cumprod ([2, 3; 4, 5], 2), [2, 6; 4, 20]);
-
-%!assert (cumprod (single([2, 3; 4, 5]), 1), single([2, 3; 8, 15]));
-%!assert (cumprod (single([2, 3; 4, 5]), 2), single([2, 6; 4, 20]));
-
- */
+%!assert (cumprod ([1, 2, 3]), [1, 2, 6])
+%!assert (cumprod ([-1; -2; -3]), [-1; 2; -6])
+%!assert (cumprod ([i, 2+i, -3+2i, 4]), [i, -1+2i, -1-8i, -4-32i])
+%!assert (cumprod ([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i]), [1, 2, 3; i, 4i, 9i; -1+i, -8+8i, -27+27i])
+
+%!assert (cumprod (single ([1, 2, 3])), single ([1, 2, 6]))
+%!assert (cumprod (single ([-1; -2; -3])), single ([-1; 2; -6]))
+%!assert (cumprod (single ([i, 2+i, -3+2i, 4])), single ([i, -1+2i, -1-8i, -4-32i]))
+%!assert (cumprod (single ([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i])), single ([1, 2, 3; i, 4i, 9i; -1+i, -8+8i, -27+27i]))
+
+%!assert (cumprod ([2, 3; 4, 5], 1), [2, 3; 8, 15])
+%!assert (cumprod ([2, 3; 4, 5], 2), [2, 6; 4, 20])
+
+%!assert (cumprod (single ([2, 3; 4, 5]), 1), single ([2, 3; 8, 15]))
+%!assert (cumprod (single ([2, 3; 4, 5]), 2), single ([2, 6; 4, 20]))
+
+%!error cumprod ()
+*/
 
 DEFUN (cumsum, args, ,
   "-*- texinfo -*-\n\
 @deftypefn  {Built-in Function} {} cumsum (@var{x})\n\
 @deftypefnx {Built-in Function} {} cumsum (@var{x}, @var{dim})\n\
-@deftypefnx {Built-in Function} {} cumsum (@dots{}, 'native')\n\
-@deftypefnx {Built-in Function} {} cumsum (@dots{}, 'double')\n\
-@deftypefnx {Built-in Function} {} cumsum (@dots{}, 'extra')\n\
+@deftypefnx {Built-in Function} {} cumsum (@dots{}, \"native\")\n\
+@deftypefnx {Built-in Function} {} cumsum (@dots{}, \"double\")\n\
+@deftypefnx {Built-in Function} {} cumsum (@dots{}, \"extra\")\n\
 Cumulative sum of elements along dimension @var{dim}.  If @var{dim}\n\
 is omitted, it defaults to the first non-singleton dimension.\n\
 \n\
-See @code{sum} for an explanation of the optional parameters 'native',\n\
-'double', and 'extra'.\n\
+See @code{sum} for an explanation of the optional parameters \"native\",\n\
+\"double\", and \"extra\".\n\
 @seealso{sum, cumprod}\n\
 @end deftypefn")
 {
@@ -1219,26 +1215,24 @@
 }
 
 /*
-
-%!assert (cumsum ([1, 2, 3]), [1, 3, 6]);
-%!assert (cumsum ([-1; -2; -3]), [-1; -3; -6]);
-%!assert (cumsum ([i, 2+i, -3+2i, 4]), [i, 2+2i, -1+4i, 3+4i]);
-%!assert (cumsum ([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i]), [1, 2, 3; 1+i, 2+2i, 3+3i; 2+2i, 4+4i, 6+6i]);
-
-%!assert (cumsum (single([1, 2, 3])), single([1, 3, 6]));
-%!assert (cumsum (single([-1; -2; -3])), single([-1; -3; -6]));
-%!assert (cumsum (single([i, 2+i, -3+2i, 4])), single([i, 2+2i, -1+4i, 3+4i]));
-%!assert (cumsum (single([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i])), single([1, 2, 3; 1+i, 2+2i, 3+3i; 2+2i, 4+4i, 6+6i]));
-
-%!error <Invalid call to cumsum> cumsum ();
-
-%!assert (cumsum ([1, 2; 3, 4], 1), [1, 2; 4, 6]);
-%!assert (cumsum ([1, 2; 3, 4], 2), [1, 3; 3, 7]);
-
-%!assert (cumsum (single([1, 2; 3, 4]), 1), single([1, 2; 4, 6]));
-%!assert (cumsum (single([1, 2; 3, 4]), 2), single([1, 3; 3, 7]));
-
- */
+%!assert (cumsum ([1, 2, 3]), [1, 3, 6])
+%!assert (cumsum ([-1; -2; -3]), [-1; -3; -6])
+%!assert (cumsum ([i, 2+i, -3+2i, 4]), [i, 2+2i, -1+4i, 3+4i])
+%!assert (cumsum ([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i]), [1, 2, 3; 1+i, 2+2i, 3+3i; 2+2i, 4+4i, 6+6i])
+
+%!assert (cumsum (single ([1, 2, 3])), single ([1, 3, 6]))
+%!assert (cumsum (single ([-1; -2; -3])), single ([-1; -3; -6]))
+%!assert (cumsum (single ([i, 2+i, -3+2i, 4])), single ([i, 2+2i, -1+4i, 3+4i]))
+%!assert (cumsum (single ([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i])), single ([1, 2, 3; 1+i, 2+2i, 3+3i; 2+2i, 4+4i, 6+6i]))
+
+%!assert (cumsum ([1, 2; 3, 4], 1), [1, 2; 4, 6])
+%!assert (cumsum ([1, 2; 3, 4], 2), [1, 3; 3, 7])
+
+%!assert (cumsum (single ([1, 2; 3, 4]), 1), single ([1, 2; 4, 6]))
+%!assert (cumsum (single ([1, 2; 3, 4]), 2), single ([1, 3; 3, 7]))
+
+%!error cumsum ()
+*/
 
 DEFUN (diag, args, ,
   "-*- texinfo -*-\n\
@@ -1256,10 +1250,10 @@
 @example\n\
 @group\n\
 diag ([1, 2, 3], 1)\n\
-     @result{}  0  1  0  0\n\
-         0  0  2  0\n\
-         0  0  0  3\n\
-         0  0  0  0\n\
+   @result{}  0  1  0  0\n\
+       0  0  2  0\n\
+       0  0  0  3\n\
+       0  0  0  0\n\
 @end group\n\
 @end example\n\
 \n\
@@ -1277,7 +1271,7 @@
   int nargin = args.length ();
 
   if (nargin == 1 && args(0).is_defined ())
-    retval = args(0).diag();
+    retval = args(0).diag ();
   else if (nargin == 2 && args(0).is_defined () && args(1).is_defined ())
     {
       octave_idx_type k = args(1).int_value ();
@@ -1285,29 +1279,19 @@
       if (error_state)
         error ("diag: invalid argument K");
       else
-        retval = args(0).diag(k);
+        retval = args(0).diag (k);
     }
   else if (nargin == 3)
     {
       octave_value arg0 = args(0);
-      if (arg0.ndims () == 2 && (args(0).rows () == 1 || args(0).columns () == 1))
+
+      if (arg0.ndims () == 2 && (arg0.rows () == 1 || arg0.columns () == 1))
         {
-          octave_idx_type m = args(1).int_value (), n = args(2).int_value ();
+          octave_idx_type m = args(1).int_value ();
+          octave_idx_type n = args(2).int_value ();
+
           if (! error_state)
-            {
-              if (arg0.is_cell ())
-                {
-                  Cell rhs = arg0.cell_value ();
-                  Cell tmp (m, n);
-
-                  for (octave_idx_type i = 0; i < rhs.numel (); i++)
-                    tmp.xelem (i, i) = rhs.xelem (i);
-
-                  retval = tmp;
-                }
-              else
-                retval = arg0.diag ().resize (dim_vector (m, n), true);
-            }
+            retval = arg0.diag (m, n);
           else
             error ("diag: invalid dimensions");
         }
@@ -1322,37 +1306,37 @@
 
 /*
 
-%!assert(full (diag ([1; 2; 3])), [1, 0, 0; 0, 2, 0; 0, 0, 3]);
-%!assert(diag ([1; 2; 3], 1), [0, 1, 0, 0; 0, 0, 2, 0; 0, 0, 0, 3; 0, 0, 0, 0]);
-%!assert(diag ([1; 2; 3], 2), [0, 0, 1, 0, 0; 0, 0, 0, 2, 0; 0, 0, 0, 0, 3; 0, 0, 0, 0, 0; 0, 0, 0, 0, 0]);
-%!assert(diag ([1; 2; 3],-1), [0, 0, 0, 0; 1, 0, 0, 0; 0, 2, 0, 0; 0, 0, 3, 0]);
-%!assert(diag ([1; 2; 3],-2), [0, 0, 0, 0, 0; 0, 0, 0, 0, 0; 1, 0, 0, 0, 0; 0, 2, 0, 0, 0; 0, 0, 3, 0, 0]);
-
-%!assert(diag ([1, 0, 0; 0, 2, 0; 0, 0, 3]), [1; 2; 3]);
-%!assert(diag ([0, 1, 0, 0; 0, 0, 2, 0; 0, 0, 0, 3; 0, 0, 0, 0], 1), [1; 2; 3]);
-%!assert(diag ([0, 0, 0, 0; 1, 0, 0, 0; 0, 2, 0, 0; 0, 0, 3, 0], -1), [1; 2; 3]);
-%!assert(diag (ones(1, 0), 2), zeros (2));
-%!assert(diag (1:3, 4, 2), [1, 0; 0, 2; 0, 0; 0, 0]);
-
-%!assert(full (diag (single([1; 2; 3]))), single([1, 0, 0; 0, 2, 0; 0, 0, 3]));
-%!assert(diag (single([1; 2; 3]), 1), single([0, 1, 0, 0; 0, 0, 2, 0; 0, 0, 0, 3; 0, 0, 0, 0]));
-%!assert(diag (single([1; 2; 3]), 2), single([0, 0, 1, 0, 0; 0, 0, 0, 2, 0; 0, 0, 0, 0, 3; 0, 0, 0, 0, 0; 0, 0, 0, 0, 0]));
-%!assert(diag (single([1; 2; 3]),-1), single([0, 0, 0, 0; 1, 0, 0, 0; 0, 2, 0, 0; 0, 0, 3, 0]));
-%!assert(diag (single([1; 2; 3]),-2), single([0, 0, 0, 0, 0; 0, 0, 0, 0, 0; 1, 0, 0, 0, 0; 0, 2, 0, 0, 0; 0, 0, 3, 0, 0]));
-
-%!assert(diag (single([1, 0, 0; 0, 2, 0; 0, 0, 3])), single([1; 2; 3]));
-%!assert(diag (single([0, 1, 0, 0; 0, 0, 2, 0; 0, 0, 0, 3; 0, 0, 0, 0]), 1), single([1; 2; 3]));
-%!assert(diag (single([0, 0, 0, 0; 1, 0, 0, 0; 0, 2, 0, 0; 0, 0, 3, 0]), -1), single([1; 2; 3]));
-
-%!assert(diag (int8([1; 2; 3])), int8([1, 0, 0; 0, 2, 0; 0, 0, 3]));
-%!assert(diag (int8([1; 2; 3]), 1), int8([0, 1, 0, 0; 0, 0, 2, 0; 0, 0, 0, 3; 0, 0, 0, 0]));
-%!assert(diag (int8([1; 2; 3]), 2), int8([0, 0, 1, 0, 0; 0, 0, 0, 2, 0; 0, 0, 0, 0, 3; 0, 0, 0, 0, 0; 0, 0, 0, 0, 0]));
-%!assert(diag (int8([1; 2; 3]),-1), int8([0, 0, 0, 0; 1, 0, 0, 0; 0, 2, 0, 0; 0, 0, 3, 0]));
-%!assert(diag (int8([1; 2; 3]),-2), int8([0, 0, 0, 0, 0; 0, 0, 0, 0, 0; 1, 0, 0, 0, 0; 0, 2, 0, 0, 0; 0, 0, 3, 0, 0]));
-
-%!assert(diag (int8([1, 0, 0; 0, 2, 0; 0, 0, 3])), int8([1; 2; 3]));
-%!assert(diag (int8([0, 1, 0, 0; 0, 0, 2, 0; 0, 0, 0, 3; 0, 0, 0, 0]), 1), int8([1; 2; 3]));
-%!assert(diag (int8([0, 0, 0, 0; 1, 0, 0, 0; 0, 2, 0, 0; 0, 0, 3, 0]), -1), int8([1; 2; 3]));
+%!assert (full (diag ([1; 2; 3])), [1, 0, 0; 0, 2, 0; 0, 0, 3])
+%!assert (diag ([1; 2; 3], 1), [0, 1, 0, 0; 0, 0, 2, 0; 0, 0, 0, 3; 0, 0, 0, 0])
+%!assert (diag ([1; 2; 3], 2), [0, 0, 1, 0, 0; 0, 0, 0, 2, 0; 0, 0, 0, 0, 3; 0, 0, 0, 0, 0; 0, 0, 0, 0, 0])
+%!assert (diag ([1; 2; 3],-1), [0, 0, 0, 0; 1, 0, 0, 0; 0, 2, 0, 0; 0, 0, 3, 0])
+%!assert (diag ([1; 2; 3],-2), [0, 0, 0, 0, 0; 0, 0, 0, 0, 0; 1, 0, 0, 0, 0; 0, 2, 0, 0, 0; 0, 0, 3, 0, 0])
+
+%!assert (diag ([1, 0, 0; 0, 2, 0; 0, 0, 3]), [1; 2; 3])
+%!assert (diag ([0, 1, 0, 0; 0, 0, 2, 0; 0, 0, 0, 3; 0, 0, 0, 0], 1), [1; 2; 3])
+%!assert (diag ([0, 0, 0, 0; 1, 0, 0, 0; 0, 2, 0, 0; 0, 0, 3, 0], -1), [1; 2; 3])
+%!assert (diag (ones (1, 0), 2), zeros (2))
+%!assert (diag (1:3, 4, 2), [1, 0; 0, 2; 0, 0; 0, 0])
+
+%!assert (full (diag (single ([1; 2; 3]))), single ([1, 0, 0; 0, 2, 0; 0, 0, 3]))
+%!assert (diag (single ([1; 2; 3]), 1), single ([0, 1, 0, 0; 0, 0, 2, 0; 0, 0, 0, 3; 0, 0, 0, 0]))
+%!assert (diag (single ([1; 2; 3]), 2), single ([0, 0, 1, 0, 0; 0, 0, 0, 2, 0; 0, 0, 0, 0, 3; 0, 0, 0, 0, 0; 0, 0, 0, 0, 0]))
+%!assert (diag (single ([1; 2; 3]),-1), single ([0, 0, 0, 0; 1, 0, 0, 0; 0, 2, 0, 0; 0, 0, 3, 0]))
+%!assert (diag (single ([1; 2; 3]),-2), single ([0, 0, 0, 0, 0; 0, 0, 0, 0, 0; 1, 0, 0, 0, 0; 0, 2, 0, 0, 0; 0, 0, 3, 0, 0]))
+
+%!assert (diag (single ([1, 0, 0; 0, 2, 0; 0, 0, 3])), single ([1; 2; 3]))
+%!assert (diag (single ([0, 1, 0, 0; 0, 0, 2, 0; 0, 0, 0, 3; 0, 0, 0, 0]), 1), single ([1; 2; 3]))
+%!assert (diag (single ([0, 0, 0, 0; 1, 0, 0, 0; 0, 2, 0, 0; 0, 0, 3, 0]), -1), single ([1; 2; 3]))
+
+%!assert (diag (int8 ([1; 2; 3])), int8 ([1, 0, 0; 0, 2, 0; 0, 0, 3]))
+%!assert (diag (int8 ([1; 2; 3]), 1), int8 ([0, 1, 0, 0; 0, 0, 2, 0; 0, 0, 0, 3; 0, 0, 0, 0]))
+%!assert (diag (int8 ([1; 2; 3]), 2), int8 ([0, 0, 1, 0, 0; 0, 0, 0, 2, 0; 0, 0, 0, 0, 3; 0, 0, 0, 0, 0; 0, 0, 0, 0, 0]))
+%!assert (diag (int8 ([1; 2; 3]),-1), int8 ([0, 0, 0, 0; 1, 0, 0, 0; 0, 2, 0, 0; 0, 0, 3, 0]))
+%!assert (diag (int8 ([1; 2; 3]),-2), int8 ([0, 0, 0, 0, 0; 0, 0, 0, 0, 0; 1, 0, 0, 0, 0; 0, 2, 0, 0, 0; 0, 0, 3, 0, 0]))
+
+%!assert (diag (int8 ([1, 0, 0; 0, 2, 0; 0, 0, 3])), int8 ([1; 2; 3]))
+%!assert (diag (int8 ([0, 1, 0, 0; 0, 0, 2, 0; 0, 0, 0, 3; 0, 0, 0, 0]), 1), int8 ([1; 2; 3]))
+%!assert (diag (int8 ([0, 0, 0, 0; 1, 0, 0, 0; 0, 2, 0, 0; 0, 0, 3, 0]), -1), int8 ([1; 2; 3]))
 
 ## bug #37411
 %!assert (diag (diag ([5, 2, 3])(:,1)), diag([5 0 0 ]))
@@ -1360,18 +1344,26 @@
 %!assert (diag (diag ([5, 2, 3])(:,1), -2), [[0 0 5 0 0]', zeros(5, 4)])
 
 ## Test non-square size
-%!assert(diag ([1,2,3], 6, 3), [1 0 0; 0 2 0; 0 0 3; 0 0 0; 0 0 0; 0 0 0])
+%!assert (diag ([1,2,3], 6, 3), [1 0 0; 0 2 0; 0 0 3; 0 0 0; 0 0 0; 0 0 0])
 %!assert (diag (1, 2, 3), [1,0,0; 0,0,0]);
 %!assert (diag ({1}, 2, 3), {1,[],[]; [],[],[]});
 %!assert (diag ({1,2}, 3, 4), {1,[],[],[]; [],2,[],[]; [],[],[],[]});
 
 %% Test input validation
-%!error <Invalid call to diag> diag ();
-%!error <Invalid call to diag> diag (1,2,3,4);
-%!error diag (ones (2), 3, 3);
-%!error diag (1:3, -4, 3);
-
- */
+%!error <Invalid call to diag> diag ()
+%!error <Invalid call to diag> diag (1,2,3,4)
+%!error diag (ones (2), 3, 3)
+%!error diag (1:3, -4, 3)
+
+%!assert (diag (1, 3, 3), diag ([1, 0, 0]))
+%!assert (diag (i, 3, 3), diag ([i, 0, 0]))
+%!assert (diag (single (1), 3, 3), diag ([single(1), 0, 0]))
+%!assert (diag (single (i), 3, 3), diag ([single(i), 0, 0]))
+%!assert (diag ([1, 2], 3, 3), diag ([1, 2, 0]))
+%!assert (diag ([1, 2]*i, 3, 3), diag ([1, 2, 0]*i))
+%!assert (diag (single ([1, 2]), 3, 3), diag (single ([1, 2, 0])))
+%!assert (diag (single ([1, 2]*i), 3, 3), diag (single ([1, 2, 0]*i)))
+*/
 
 DEFUN (prod, args, ,
   "-*- texinfo -*-\n\
@@ -1386,50 +1378,48 @@
 }
 
 /*
-
-%!assert (prod ([1, 2, 3]), 6);
-%!assert (prod ([-1; -2; -3]), -6);
-%!assert (prod ([i, 2+i, -3+2i, 4]), -4 - 32i);
-%!assert (prod ([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i]), [-1+i, -8+8i, -27+27i]);
-
-%!assert (prod (single([1, 2, 3])), single(6));
-%!assert (prod (single([-1; -2; -3])), single(-6));
-%!assert (prod (single([i, 2+i, -3+2i, 4])), single(-4 - 32i));
-%!assert (prod (single([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i])), single([-1+i, -8+8i, -27+27i]));
-
-%!error <Invalid call to prod> prod ();
-
-%!assert (prod ([1, 2; 3, 4], 1), [3, 8]);
-%!assert (prod ([1, 2; 3, 4], 2), [2; 12]);
-%!assert (prod (zeros (1, 0)), 1);
-%!assert (prod (zeros (1, 0), 1), zeros (1, 0));
-%!assert (prod (zeros (1, 0), 2), 1);
-%!assert (prod (zeros (0, 1)), 1);
-%!assert (prod (zeros (0, 1), 1), 1);
-%!assert (prod (zeros (0, 1), 2), zeros (0, 1));
-%!assert (prod (zeros (2, 0)), zeros (1, 0));
-%!assert (prod (zeros (2, 0), 1), zeros (1, 0));
-%!assert (prod (zeros (2, 0), 2), [1; 1]);
-%!assert (prod (zeros (0, 2)), [1, 1]);
-%!assert (prod (zeros (0, 2), 1), [1, 1]);
-%!assert (prod (zeros (0, 2), 2), zeros(0, 1));
-
-%!assert (prod (single([1, 2; 3, 4]), 1), single([3, 8]));
-%!assert (prod (single([1, 2; 3, 4]), 2), single([2; 12]));
-%!assert (prod (zeros (1, 0, 'single')), single(1));
-%!assert (prod (zeros (1, 0, 'single'), 1), zeros (1, 0, 'single'));
-%!assert (prod (zeros (1, 0, 'single'), 2), single(1));
-%!assert (prod (zeros (0, 1, 'single')), single(1));
-%!assert (prod (zeros (0, 1, 'single'), 1), single(1));
-%!assert (prod (zeros (0, 1, 'single'), 2), zeros (0, 1, 'single'));
-%!assert (prod (zeros (2, 0, 'single')), zeros (1, 0, 'single'));
-%!assert (prod (zeros (2, 0, 'single'), 1), zeros (1, 0, 'single'));
-%!assert (prod (zeros (2, 0, 'single'), 2), single([1; 1]));
-%!assert (prod (zeros (0, 2, 'single')), single([1, 1]));
-%!assert (prod (zeros (0, 2, 'single'), 1), single([1, 1]));
-%!assert (prod (zeros (0, 2, 'single'), 2), zeros(0, 1, 'single'));
-
- */
+%!assert (prod ([1, 2, 3]), 6)
+%!assert (prod ([-1; -2; -3]), -6)
+%!assert (prod ([i, 2+i, -3+2i, 4]), -4 - 32i)
+%!assert (prod ([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i]), [-1+i, -8+8i, -27+27i])
+
+%!assert (prod (single ([1, 2, 3])), single (6))
+%!assert (prod (single ([-1; -2; -3])), single (-6))
+%!assert (prod (single ([i, 2+i, -3+2i, 4])), single (-4 - 32i))
+%!assert (prod (single ([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i])), single ([-1+i, -8+8i, -27+27i]))
+
+%!assert (prod ([1, 2; 3, 4], 1), [3, 8])
+%!assert (prod ([1, 2; 3, 4], 2), [2; 12])
+%!assert (prod (zeros (1, 0)), 1)
+%!assert (prod (zeros (1, 0), 1), zeros (1, 0))
+%!assert (prod (zeros (1, 0), 2), 1)
+%!assert (prod (zeros (0, 1)), 1)
+%!assert (prod (zeros (0, 1), 1), 1)
+%!assert (prod (zeros (0, 1), 2), zeros (0, 1))
+%!assert (prod (zeros (2, 0)), zeros (1, 0))
+%!assert (prod (zeros (2, 0), 1), zeros (1, 0))
+%!assert (prod (zeros (2, 0), 2), [1; 1])
+%!assert (prod (zeros (0, 2)), [1, 1])
+%!assert (prod (zeros (0, 2), 1), [1, 1])
+%!assert (prod (zeros (0, 2), 2), zeros (0, 1))
+
+%!assert (prod (single ([1, 2; 3, 4]), 1), single ([3, 8]))
+%!assert (prod (single ([1, 2; 3, 4]), 2), single ([2; 12]))
+%!assert (prod (zeros (1, 0, "single")), single (1))
+%!assert (prod (zeros (1, 0, "single"), 1), zeros (1, 0, "single"))
+%!assert (prod (zeros (1, 0, "single"), 2), single (1))
+%!assert (prod (zeros (0, 1, "single")), single (1))
+%!assert (prod (zeros (0, 1, "single"), 1), single (1))
+%!assert (prod (zeros (0, 1, "single"), 2), zeros (0, 1, "single"))
+%!assert (prod (zeros (2, 0, "single")), zeros (1, 0, "single"))
+%!assert (prod (zeros (2, 0, "single"), 1), zeros (1, 0, "single"))
+%!assert (prod (zeros (2, 0, "single"), 2), single ([1; 1]))
+%!assert (prod (zeros (0, 2, "single")), single ([1, 1]))
+%!assert (prod (zeros (0, 2, "single"), 1), single ([1, 1]))
+%!assert (prod (zeros (0, 2, "single"), 2), zeros (0, 1, "single"))
+
+%!error prod ()
+*/
 
 static bool
 all_scalar_1x1 (const octave_value_list& args)
@@ -1852,7 +1842,7 @@
           for (int j = 0; j < n_args; j++)
             {
               // Can't fast return here to skip empty matrices as something
-              // like cat(1,[],single([])) must return an empty matrix of
+              // like cat (1,[],single ([])) must return an empty matrix of
               // the right type.
               tmp = do_cat_op (tmp, args (j), ra_idx);
 
@@ -1890,7 +1880,7 @@
 new matrices.  For example:\n\
 \n\
 @example\n\
-@var{hcat} = [ @var{array1}, @var{array2}, @dots{} ];\n\
+@var{hcat} = [ @var{array1}, @var{array2}, @dots{} ]\n\
 @end example\n\
 @seealso{cat, vertcat}\n\
 @end deftypefn")
@@ -1899,194 +1889,195 @@
 }
 
 /*
-%% test concatenation with all zero matrices
-%!assert(horzcat ('', 65*ones(1,10)), 'AAAAAAAAAA');
-%!assert(horzcat (65*ones(1,10), ''), 'AAAAAAAAAA');
-
-%!assert (class (horzcat (int64(1), int64(1))), 'int64')
-%!assert (class (horzcat (int64(1), int32(1))), 'int64')
-%!assert (class (horzcat (int64(1), int16(1))), 'int64')
-%!assert (class (horzcat (int64(1), int8(1))), 'int64')
-%!assert (class (horzcat (int64(1), uint64(1))), 'int64')
-%!assert (class (horzcat (int64(1), uint32(1))), 'int64')
-%!assert (class (horzcat (int64(1), uint16(1))), 'int64')
-%!assert (class (horzcat (int64(1), uint8(1))), 'int64')
-%!assert (class (horzcat (int64(1), single(1))), 'int64')
-%!assert (class (horzcat (int64(1), double(1))), 'int64')
-%!assert (class (horzcat (int64(1), cell(1))), 'cell')
-%!assert (class (horzcat (int64(1), true)), 'int64')
-%!assert (class (horzcat (int64(1), 'a')), 'char')
-
-%!assert (class (horzcat (int32(1), int64(1))), 'int32')
-%!assert (class (horzcat (int32(1), int32(1))), 'int32')
-%!assert (class (horzcat (int32(1), int16(1))), 'int32')
-%!assert (class (horzcat (int32(1), int8(1))), 'int32')
-%!assert (class (horzcat (int32(1), uint64(1))), 'int32')
-%!assert (class (horzcat (int32(1), uint32(1))), 'int32')
-%!assert (class (horzcat (int32(1), uint16(1))), 'int32')
-%!assert (class (horzcat (int32(1), uint8(1))), 'int32')
-%!assert (class (horzcat (int32(1), single(1))), 'int32')
-%!assert (class (horzcat (int32(1), double(1))), 'int32')
-%!assert (class (horzcat (int32(1), cell(1))), 'cell')
-%!assert (class (horzcat (int32(1), true)), 'int32')
-%!assert (class (horzcat (int32(1), 'a')), 'char')
-
-%!assert (class (horzcat (int16(1), int64(1))), 'int16')
-%!assert (class (horzcat (int16(1), int32(1))), 'int16')
-%!assert (class (horzcat (int16(1), int16(1))), 'int16')
-%!assert (class (horzcat (int16(1), int8(1))), 'int16')
-%!assert (class (horzcat (int16(1), uint64(1))), 'int16')
-%!assert (class (horzcat (int16(1), uint32(1))), 'int16')
-%!assert (class (horzcat (int16(1), uint16(1))), 'int16')
-%!assert (class (horzcat (int16(1), uint8(1))), 'int16')
-%!assert (class (horzcat (int16(1), single(1))), 'int16')
-%!assert (class (horzcat (int16(1), double(1))), 'int16')
-%!assert (class (horzcat (int16(1), cell(1))), 'cell')
-%!assert (class (horzcat (int16(1), true)), 'int16')
-%!assert (class (horzcat (int16(1), 'a')), 'char')
-
-%!assert (class (horzcat (int8(1), int64(1))), 'int8')
-%!assert (class (horzcat (int8(1), int32(1))), 'int8')
-%!assert (class (horzcat (int8(1), int16(1))), 'int8')
-%!assert (class (horzcat (int8(1), int8(1))), 'int8')
-%!assert (class (horzcat (int8(1), uint64(1))), 'int8')
-%!assert (class (horzcat (int8(1), uint32(1))), 'int8')
-%!assert (class (horzcat (int8(1), uint16(1))), 'int8')
-%!assert (class (horzcat (int8(1), uint8(1))), 'int8')
-%!assert (class (horzcat (int8(1), single(1))), 'int8')
-%!assert (class (horzcat (int8(1), double(1))), 'int8')
-%!assert (class (horzcat (int8(1), cell(1))), 'cell')
-%!assert (class (horzcat (int8(1), true)), 'int8')
-%!assert (class (horzcat (int8(1), 'a')), 'char')
-
-%!assert (class (horzcat (uint64(1), int64(1))), 'uint64')
-%!assert (class (horzcat (uint64(1), int32(1))), 'uint64')
-%!assert (class (horzcat (uint64(1), int16(1))), 'uint64')
-%!assert (class (horzcat (uint64(1), int8(1))), 'uint64')
-%!assert (class (horzcat (uint64(1), uint64(1))), 'uint64')
-%!assert (class (horzcat (uint64(1), uint32(1))), 'uint64')
-%!assert (class (horzcat (uint64(1), uint16(1))), 'uint64')
-%!assert (class (horzcat (uint64(1), uint8(1))), 'uint64')
-%!assert (class (horzcat (uint64(1), single(1))), 'uint64')
-%!assert (class (horzcat (uint64(1), double(1))), 'uint64')
-%!assert (class (horzcat (uint64(1), cell(1))), 'cell')
-%!assert (class (horzcat (uint64(1), true)), 'uint64')
-%!assert (class (horzcat (uint64(1), 'a')), 'char')
-
-%!assert (class (horzcat (uint32(1), int64(1))), 'uint32')
-%!assert (class (horzcat (uint32(1), int32(1))), 'uint32')
-%!assert (class (horzcat (uint32(1), int16(1))), 'uint32')
-%!assert (class (horzcat (uint32(1), int8(1))), 'uint32')
-%!assert (class (horzcat (uint32(1), uint64(1))), 'uint32')
-%!assert (class (horzcat (uint32(1), uint32(1))), 'uint32')
-%!assert (class (horzcat (uint32(1), uint16(1))), 'uint32')
-%!assert (class (horzcat (uint32(1), uint8(1))), 'uint32')
-%!assert (class (horzcat (uint32(1), single(1))), 'uint32')
-%!assert (class (horzcat (uint32(1), double(1))), 'uint32')
-%!assert (class (horzcat (uint32(1), cell(1))), 'cell')
-%!assert (class (horzcat (uint32(1), true)), 'uint32')
-%!assert (class (horzcat (uint32(1), 'a')), 'char')
-
-%!assert (class (horzcat (uint16(1), int64(1))), 'uint16')
-%!assert (class (horzcat (uint16(1), int32(1))), 'uint16')
-%!assert (class (horzcat (uint16(1), int16(1))), 'uint16')
-%!assert (class (horzcat (uint16(1), int8(1))), 'uint16')
-%!assert (class (horzcat (uint16(1), uint64(1))), 'uint16')
-%!assert (class (horzcat (uint16(1), uint32(1))), 'uint16')
-%!assert (class (horzcat (uint16(1), uint16(1))), 'uint16')
-%!assert (class (horzcat (uint16(1), uint8(1))), 'uint16')
-%!assert (class (horzcat (uint16(1), single(1))), 'uint16')
-%!assert (class (horzcat (uint16(1), double(1))), 'uint16')
-%!assert (class (horzcat (uint16(1), cell(1))), 'cell')
-%!assert (class (horzcat (uint16(1), true)), 'uint16')
-%!assert (class (horzcat (uint16(1), 'a')), 'char')
-
-%!assert (class (horzcat (uint8(1), int64(1))), 'uint8')
-%!assert (class (horzcat (uint8(1), int32(1))), 'uint8')
-%!assert (class (horzcat (uint8(1), int16(1))), 'uint8')
-%!assert (class (horzcat (uint8(1), int8(1))), 'uint8')
-%!assert (class (horzcat (uint8(1), uint64(1))), 'uint8')
-%!assert (class (horzcat (uint8(1), uint32(1))), 'uint8')
-%!assert (class (horzcat (uint8(1), uint16(1))), 'uint8')
-%!assert (class (horzcat (uint8(1), uint8(1))), 'uint8')
-%!assert (class (horzcat (uint8(1), single(1))), 'uint8')
-%!assert (class (horzcat (uint8(1), double(1))), 'uint8')
-%!assert (class (horzcat (uint8(1), cell(1))), 'cell')
-%!assert (class (horzcat (uint8(1), true)), 'uint8')
-%!assert (class (horzcat (uint8(1), 'a')), 'char')
-
-%!assert (class (horzcat (single(1), int64(1))), 'int64')
-%!assert (class (horzcat (single(1), int32(1))), 'int32')
-%!assert (class (horzcat (single(1), int16(1))), 'int16')
-%!assert (class (horzcat (single(1), int8(1))), 'int8')
-%!assert (class (horzcat (single(1), uint64(1))), 'uint64')
-%!assert (class (horzcat (single(1), uint32(1))), 'uint32')
-%!assert (class (horzcat (single(1), uint16(1))), 'uint16')
-%!assert (class (horzcat (single(1), uint8(1))), 'uint8')
-%!assert (class (horzcat (single(1), single(1))), 'single')
-%!assert (class (horzcat (single(1), double(1))), 'single')
-%!assert (class (horzcat (single(1), cell(1))), 'cell')
-%!assert (class (horzcat (single(1), true)), 'single')
-%!assert (class (horzcat (single(1), 'a')), 'char')
-
-%!assert (class (horzcat (double(1), int64(1))), 'int64')
-%!assert (class (horzcat (double(1), int32(1))), 'int32')
-%!assert (class (horzcat (double(1), int16(1))), 'int16')
-%!assert (class (horzcat (double(1), int8(1))), 'int8')
-%!assert (class (horzcat (double(1), uint64(1))), 'uint64')
-%!assert (class (horzcat (double(1), uint32(1))), 'uint32')
-%!assert (class (horzcat (double(1), uint16(1))), 'uint16')
-%!assert (class (horzcat (double(1), uint8(1))), 'uint8')
-%!assert (class (horzcat (double(1), single(1))), 'single')
-%!assert (class (horzcat (double(1), double(1))), 'double')
-%!assert (class (horzcat (double(1), cell(1))), 'cell')
-%!assert (class (horzcat (double(1), true)), 'double')
-%!assert (class (horzcat (double(1), 'a')), 'char')
-
-%!assert (class (horzcat (cell(1), int64(1))), 'cell')
-%!assert (class (horzcat (cell(1), int32(1))), 'cell')
-%!assert (class (horzcat (cell(1), int16(1))), 'cell')
-%!assert (class (horzcat (cell(1), int8(1))), 'cell')
-%!assert (class (horzcat (cell(1), uint64(1))), 'cell')
-%!assert (class (horzcat (cell(1), uint32(1))), 'cell')
-%!assert (class (horzcat (cell(1), uint16(1))), 'cell')
-%!assert (class (horzcat (cell(1), uint8(1))), 'cell')
-%!assert (class (horzcat (cell(1), single(1))), 'cell')
-%!assert (class (horzcat (cell(1), double(1))), 'cell')
-%!assert (class (horzcat (cell(1), cell(1))), 'cell')
-%!assert (class (horzcat (cell(1), true)), 'cell')
-%!assert (class (horzcat (cell(1), 'a')), 'cell')
-
-%!assert (class (horzcat (true, int64(1))), 'int64')
-%!assert (class (horzcat (true, int32(1))), 'int32')
-%!assert (class (horzcat (true, int16(1))), 'int16')
-%!assert (class (horzcat (true, int8(1))), 'int8')
-%!assert (class (horzcat (true, uint64(1))), 'uint64')
-%!assert (class (horzcat (true, uint32(1))), 'uint32')
-%!assert (class (horzcat (true, uint16(1))), 'uint16')
-%!assert (class (horzcat (true, uint8(1))), 'uint8')
-%!assert (class (horzcat (true, single(1))), 'single')
-%!assert (class (horzcat (true, double(1))), 'double')
-%!assert (class (horzcat (true, cell(1))), 'cell')
-%!assert (class (horzcat (true, true)), 'logical')
-%!assert (class (horzcat (true, 'a')), 'char')
-
-%!assert (class (horzcat ('a', int64(1))), 'char')
-%!assert (class (horzcat ('a', int32(1))), 'char')
-%!assert (class (horzcat ('a', int16(1))), 'char')
-%!assert (class (horzcat ('a', int8(1))), 'char')
-%!assert (class (horzcat ('a', int64(1))), 'char')
-%!assert (class (horzcat ('a', int32(1))), 'char')
-%!assert (class (horzcat ('a', int16(1))), 'char')
-%!assert (class (horzcat ('a', int8(1))), 'char')
-%!assert (class (horzcat ('a', single(1))), 'char')
-%!assert (class (horzcat ('a', double(1))), 'char')
-%!assert (class (horzcat ('a', cell(1))), 'cell')
-%!assert (class (horzcat ('a', true)), 'char')
-%!assert (class (horzcat ('a', 'a')), 'char')
-
-%!assert (class (horzcat (cell(1), struct('foo', 'bar'))), 'cell')
-%!error horzcat (struct('foo', 'bar'), cell(1));
+## Test concatenation with all zero matrices
+%!assert (horzcat ("", 65*ones (1,10)), "AAAAAAAAAA");
+%!assert (horzcat (65*ones (1,10), ""), "AAAAAAAAAA");
+
+%!assert (class (horzcat (int64 (1), int64 (1))), "int64")
+%!assert (class (horzcat (int64 (1), int32 (1))), "int64")
+%!assert (class (horzcat (int64 (1), int16 (1))), "int64")
+%!assert (class (horzcat (int64 (1), int8 (1))), "int64")
+%!assert (class (horzcat (int64 (1), uint64 (1))), "int64")
+%!assert (class (horzcat (int64 (1), uint32 (1))), "int64")
+%!assert (class (horzcat (int64 (1), uint16 (1))), "int64")
+%!assert (class (horzcat (int64 (1), uint8 (1))), "int64")
+%!assert (class (horzcat (int64 (1), single (1))), "int64")
+%!assert (class (horzcat (int64 (1), double (1))), "int64")
+%!assert (class (horzcat (int64 (1), cell (1))), "cell")
+%!assert (class (horzcat (int64 (1), true)), "int64")
+%!assert (class (horzcat (int64 (1), "a")), "char")
+
+%!assert (class (horzcat (int32 (1), int64 (1))), "int32")
+%!assert (class (horzcat (int32 (1), int32 (1))), "int32")
+%!assert (class (horzcat (int32 (1), int16 (1))), "int32")
+%!assert (class (horzcat (int32 (1), int8 (1))), "int32")
+%!assert (class (horzcat (int32 (1), uint64 (1))), "int32")
+%!assert (class (horzcat (int32 (1), uint32 (1))), "int32")
+%!assert (class (horzcat (int32 (1), uint16 (1))), "int32")
+%!assert (class (horzcat (int32 (1), uint8 (1))), "int32")
+%!assert (class (horzcat (int32 (1), single (1))), "int32")
+%!assert (class (horzcat (int32 (1), double (1))), "int32")
+%!assert (class (horzcat (int32 (1), cell (1))), "cell")
+%!assert (class (horzcat (int32 (1), true)), "int32")
+%!assert (class (horzcat (int32 (1), "a")), "char")
+
+%!assert (class (horzcat (int16 (1), int64 (1))), "int16")
+%!assert (class (horzcat (int16 (1), int32 (1))), "int16")
+%!assert (class (horzcat (int16 (1), int16 (1))), "int16")
+%!assert (class (horzcat (int16 (1), int8 (1))), "int16")
+%!assert (class (horzcat (int16 (1), uint64 (1))), "int16")
+%!assert (class (horzcat (int16 (1), uint32 (1))), "int16")
+%!assert (class (horzcat (int16 (1), uint16 (1))), "int16")
+%!assert (class (horzcat (int16 (1), uint8 (1))), "int16")
+%!assert (class (horzcat (int16 (1), single (1))), "int16")
+%!assert (class (horzcat (int16 (1), double (1))), "int16")
+%!assert (class (horzcat (int16 (1), cell (1))), "cell")
+%!assert (class (horzcat (int16 (1), true)), "int16")
+%!assert (class (horzcat (int16 (1), "a")), "char")
+
+%!assert (class (horzcat (int8 (1), int64 (1))), "int8")
+%!assert (class (horzcat (int8 (1), int32 (1))), "int8")
+%!assert (class (horzcat (int8 (1), int16 (1))), "int8")
+%!assert (class (horzcat (int8 (1), int8 (1))), "int8")
+%!assert (class (horzcat (int8 (1), uint64 (1))), "int8")
+%!assert (class (horzcat (int8 (1), uint32 (1))), "int8")
+%!assert (class (horzcat (int8 (1), uint16 (1))), "int8")
+%!assert (class (horzcat (int8 (1), uint8 (1))), "int8")
+%!assert (class (horzcat (int8 (1), single (1))), "int8")
+%!assert (class (horzcat (int8 (1), double (1))), "int8")
+%!assert (class (horzcat (int8 (1), cell (1))), "cell")
+%!assert (class (horzcat (int8 (1), true)), "int8")
+%!assert (class (horzcat (int8 (1), "a")), "char")
+
+%!assert (class (horzcat (uint64 (1), int64 (1))), "uint64")
+%!assert (class (horzcat (uint64 (1), int32 (1))), "uint64")
+%!assert (class (horzcat (uint64 (1), int16 (1))), "uint64")
+%!assert (class (horzcat (uint64 (1), int8 (1))), "uint64")
+%!assert (class (horzcat (uint64 (1), uint64 (1))), "uint64")
+%!assert (class (horzcat (uint64 (1), uint32 (1))), "uint64")
+%!assert (class (horzcat (uint64 (1), uint16 (1))), "uint64")
+%!assert (class (horzcat (uint64 (1), uint8 (1))), "uint64")
+%!assert (class (horzcat (uint64 (1), single (1))), "uint64")
+%!assert (class (horzcat (uint64 (1), double (1))), "uint64")
+%!assert (class (horzcat (uint64 (1), cell (1))), "cell")
+%!assert (class (horzcat (uint64 (1), true)), "uint64")
+%!assert (class (horzcat (uint64 (1), "a")), "char")
+
+%!assert (class (horzcat (uint32 (1), int64 (1))), "uint32")
+%!assert (class (horzcat (uint32 (1), int32 (1))), "uint32")
+%!assert (class (horzcat (uint32 (1), int16 (1))), "uint32")
+%!assert (class (horzcat (uint32 (1), int8 (1))), "uint32")
+%!assert (class (horzcat (uint32 (1), uint64 (1))), "uint32")
+%!assert (class (horzcat (uint32 (1), uint32 (1))), "uint32")
+%!assert (class (horzcat (uint32 (1), uint16 (1))), "uint32")
+%!assert (class (horzcat (uint32 (1), uint8 (1))), "uint32")
+%!assert (class (horzcat (uint32 (1), single (1))), "uint32")
+%!assert (class (horzcat (uint32 (1), double (1))), "uint32")
+%!assert (class (horzcat (uint32 (1), cell (1))), "cell")
+%!assert (class (horzcat (uint32 (1), true)), "uint32")
+%!assert (class (horzcat (uint32 (1), "a")), "char")
+
+%!assert (class (horzcat (uint16 (1), int64 (1))), "uint16")
+%!assert (class (horzcat (uint16 (1), int32 (1))), "uint16")
+%!assert (class (horzcat (uint16 (1), int16 (1))), "uint16")
+%!assert (class (horzcat (uint16 (1), int8 (1))), "uint16")
+%!assert (class (horzcat (uint16 (1), uint64 (1))), "uint16")
+%!assert (class (horzcat (uint16 (1), uint32 (1))), "uint16")
+%!assert (class (horzcat (uint16 (1), uint16 (1))), "uint16")
+%!assert (class (horzcat (uint16 (1), uint8 (1))), "uint16")
+%!assert (class (horzcat (uint16 (1), single (1))), "uint16")
+%!assert (class (horzcat (uint16 (1), double (1))), "uint16")
+%!assert (class (horzcat (uint16 (1), cell (1))), "cell")
+%!assert (class (horzcat (uint16 (1), true)), "uint16")
+%!assert (class (horzcat (uint16 (1), "a")), "char")
+
+%!assert (class (horzcat (uint8 (1), int64 (1))), "uint8")
+%!assert (class (horzcat (uint8 (1), int32 (1))), "uint8")
+%!assert (class (horzcat (uint8 (1), int16 (1))), "uint8")
+%!assert (class (horzcat (uint8 (1), int8 (1))), "uint8")
+%!assert (class (horzcat (uint8 (1), uint64 (1))), "uint8")
+%!assert (class (horzcat (uint8 (1), uint32 (1))), "uint8")
+%!assert (class (horzcat (uint8 (1), uint16 (1))), "uint8")
+%!assert (class (horzcat (uint8 (1), uint8 (1))), "uint8")
+%!assert (class (horzcat (uint8 (1), single (1))), "uint8")
+%!assert (class (horzcat (uint8 (1), double (1))), "uint8")
+%!assert (class (horzcat (uint8 (1), cell (1))), "cell")
+%!assert (class (horzcat (uint8 (1), true)), "uint8")
+%!assert (class (horzcat (uint8 (1), "a")), "char")
+
+%!assert (class (horzcat (single (1), int64 (1))), "int64")
+%!assert (class (horzcat (single (1), int32 (1))), "int32")
+%!assert (class (horzcat (single (1), int16 (1))), "int16")
+%!assert (class (horzcat (single (1), int8 (1))), "int8")
+%!assert (class (horzcat (single (1), uint64 (1))), "uint64")
+%!assert (class (horzcat (single (1), uint32 (1))), "uint32")
+%!assert (class (horzcat (single (1), uint16 (1))), "uint16")
+%!assert (class (horzcat (single (1), uint8 (1))), "uint8")
+%!assert (class (horzcat (single (1), single (1))), "single")
+%!assert (class (horzcat (single (1), double (1))), "single")
+%!assert (class (horzcat (single (1), cell (1))), "cell")
+%!assert (class (horzcat (single (1), true)), "single")
+%!assert (class (horzcat (single (1), "a")), "char")
+
+%!assert (class (horzcat (double (1), int64 (1))), "int64")
+%!assert (class (horzcat (double (1), int32 (1))), "int32")
+%!assert (class (horzcat (double (1), int16 (1))), "int16")
+%!assert (class (horzcat (double (1), int8 (1))), "int8")
+%!assert (class (horzcat (double (1), uint64 (1))), "uint64")
+%!assert (class (horzcat (double (1), uint32 (1))), "uint32")
+%!assert (class (horzcat (double (1), uint16 (1))), "uint16")
+%!assert (class (horzcat (double (1), uint8 (1))), "uint8")
+%!assert (class (horzcat (double (1), single (1))), "single")
+%!assert (class (horzcat (double (1), double (1))), "double")
+%!assert (class (horzcat (double (1), cell (1))), "cell")
+%!assert (class (horzcat (double (1), true)), "double")
+%!assert (class (horzcat (double (1), "a")), "char")
+
+%!assert (class (horzcat (cell (1), int64 (1))), "cell")
+%!assert (class (horzcat (cell (1), int32 (1))), "cell")
+%!assert (class (horzcat (cell (1), int16 (1))), "cell")
+%!assert (class (horzcat (cell (1), int8 (1))), "cell")
+%!assert (class (horzcat (cell (1), uint64 (1))), "cell")
+%!assert (class (horzcat (cell (1), uint32 (1))), "cell")
+%!assert (class (horzcat (cell (1), uint16 (1))), "cell")
+%!assert (class (horzcat (cell (1), uint8 (1))), "cell")
+%!assert (class (horzcat (cell (1), single (1))), "cell")
+%!assert (class (horzcat (cell (1), double (1))), "cell")
+%!assert (class (horzcat (cell (1), cell (1))), "cell")
+%!assert (class (horzcat (cell (1), true)), "cell")
+%!assert (class (horzcat (cell (1), "a")), "cell")
+
+%!assert (class (horzcat (true, int64 (1))), "int64")
+%!assert (class (horzcat (true, int32 (1))), "int32")
+%!assert (class (horzcat (true, int16 (1))), "int16")
+%!assert (class (horzcat (true, int8 (1))), "int8")
+%!assert (class (horzcat (true, uint64 (1))), "uint64")
+%!assert (class (horzcat (true, uint32 (1))), "uint32")
+%!assert (class (horzcat (true, uint16 (1))), "uint16")
+%!assert (class (horzcat (true, uint8 (1))), "uint8")
+%!assert (class (horzcat (true, single (1))), "single")
+%!assert (class (horzcat (true, double (1))), "double")
+%!assert (class (horzcat (true, cell (1))), "cell")
+%!assert (class (horzcat (true, true)), "logical")
+%!assert (class (horzcat (true, "a")), "char")
+
+%!assert (class (horzcat ("a", int64 (1))), "char")
+%!assert (class (horzcat ("a", int32 (1))), "char")
+%!assert (class (horzcat ("a", int16 (1))), "char")
+%!assert (class (horzcat ("a", int8 (1))), "char")
+%!assert (class (horzcat ("a", int64 (1))), "char")
+%!assert (class (horzcat ("a", int32 (1))), "char")
+%!assert (class (horzcat ("a", int16 (1))), "char")
+%!assert (class (horzcat ("a", int8 (1))), "char")
+%!assert (class (horzcat ("a", single (1))), "char")
+%!assert (class (horzcat ("a", double (1))), "char")
+%!assert (class (horzcat ("a", cell (1))), "cell")
+%!assert (class (horzcat ("a", true)), "char")
+%!assert (class (horzcat ("a", "a")), "char")
+
+%!assert (class (horzcat (cell (1), struct ("foo", "bar"))), "cell")
+
+%!error horzcat (struct ("foo", "bar"), cell (1))
 */
 
 DEFUN (vertcat, args, ,
@@ -2099,7 +2090,7 @@
 new matrices.  For example:\n\
 \n\
 @example\n\
-@var{vcat} = [ @var{array1}; @var{array2}; @dots{} ];\n\
+@var{vcat} = [ @var{array1}; @var{array2}; @dots{} ]\n\
 @end example\n\
 @seealso{cat, horzcat}\n\
 @end deftypefn")
@@ -2109,8 +2100,8 @@
 
 /*
 %!test
-%! c = {'foo'; 'bar'; 'bazoloa'};
-%! assert (vertcat (c, 'a', 'bc', 'def'), {'foo'; 'bar'; 'bazoloa'; 'a'; 'bc'; 'def'});
+%! c = {"foo"; "bar"; "bazoloa"};
+%! assert (vertcat (c, "a", "bc", "def"), {"foo"; "bar"; "bazoloa"; "a"; "bc"; "def"});
 */
 
 DEFUN (cat, args, ,
@@ -2124,17 +2115,17 @@
 A = ones (2, 2);\n\
 B = zeros (2, 2);\n\
 cat (2, A, B)\n\
-    @result{} 1 1 0 0\n\
-       1 1 0 0\n\
+  @result{} 1 1 0 0\n\
+     1 1 0 0\n\
 @end group\n\
 @end example\n\
 \n\
 Alternatively, we can concatenate @var{A} and @var{B} along the\n\
-second dimension the following way:\n\
+second dimension in the following way:\n\
 \n\
 @example\n\
 @group\n\
-[A, B].\n\
+[A, B]\n\
 @end group\n\
 @end example\n\
 \n\
@@ -2145,16 +2136,15 @@
 @example\n\
 @group\n\
 cat (4, ones (2, 2), zeros (2, 2))\n\
-    @result{} ans =\n\
-\n\
-       ans(:,:,1,1) =\n\
-\n\
-         1 1\n\
-         1 1\n\
-\n\
-       ans(:,:,1,2) =\n\
-         0 0\n\
-         0 0\n\
+  @result{} ans(:,:,1,1) =\n\
+\n\
+       1 1\n\
+       1 1\n\
+\n\
+     ans(:,:,1,2) =\n\
+\n\
+       0 0\n\
+       0 0\n\
 @end group\n\
 @end example\n\
 @seealso{horzcat, vertcat}\n\
@@ -2183,132 +2173,131 @@
 }
 
 /*
-
 %!function ret = __testcat (t1, t2, tr, cmplx)
-%! assert (cat (1, cast ([], t1), cast([], t2)), cast ([], tr));
-%!
-%! assert (cat (1, cast (1, t1), cast (2, t2)), cast ([1; 2], tr));
-%! assert (cat (1, cast (1, t1), cast ([2; 3], t2)), cast ([1; 2; 3], tr));
-%! assert (cat (1, cast ([1; 2], t1), cast (3, t2)), cast ([1; 2; 3], tr));
-%! assert (cat (1, cast ([1; 2], t1), cast ([3; 4], t2)), cast ([1; 2; 3; 4], tr));
-%! assert (cat (2, cast (1, t1), cast (2, t2)), cast ([1, 2], tr));
-%! assert (cat (2, cast (1, t1), cast ([2, 3], t2)), cast ([1, 2, 3], tr));
-%! assert (cat (2, cast ([1, 2], t1), cast (3, t2)), cast ([1, 2, 3], tr));
-%! assert (cat (2, cast ([1, 2], t1), cast ([3, 4], t2)), cast ([1, 2, 3, 4], tr));
-%!
-%! assert ([cast(1, t1); cast(2, t2)], cast ([1; 2], tr));
-%! assert ([cast(1, t1); cast([2; 3], t2)], cast ([1; 2; 3], tr));
-%! assert ([cast([1; 2], t1); cast(3, t2)], cast ([1; 2; 3], tr));
-%! assert ([cast([1; 2], t1); cast([3; 4], t2)], cast ([1; 2; 3; 4], tr));
-%! assert ([cast(1, t1), cast(2, t2)], cast ([1, 2], tr));
-%! assert ([cast(1, t1), cast([2, 3], t2)], cast ([1, 2, 3], tr));
-%! assert ([cast([1, 2], t1), cast(3, t2)], cast ([1, 2, 3], tr));
-%! assert ([cast([1, 2], t1), cast([3, 4], t2)], cast ([1, 2, 3, 4], tr));
-%!
-%! if (nargin == 3 || cmplx)
-%!   assert (cat (1, cast (1i, t1), cast (2, t2)), cast ([1i; 2], tr));
-%!   assert (cat (1, cast (1i, t1), cast ([2; 3], t2)), cast ([1i; 2; 3], tr));
-%!   assert (cat (1, cast ([1i; 2], t1), cast (3, t2)), cast ([1i; 2; 3], tr));
-%!   assert (cat (1, cast ([1i; 2], t1), cast ([3; 4], t2)), cast ([1i; 2; 3; 4], tr));
-%!   assert (cat (2, cast (1i, t1), cast (2, t2)), cast ([1i, 2], tr));
-%!   assert (cat (2, cast (1i, t1), cast ([2, 3], t2)), cast ([1i, 2, 3], tr));
-%!   assert (cat (2, cast ([1i, 2], t1), cast (3, t2)), cast ([1i, 2, 3], tr));
-%!   assert (cat (2, cast ([1i, 2], t1), cast ([3, 4], t2)), cast ([1i, 2, 3, 4], tr));
-%!
-%!   assert ([cast(1i, t1); cast(2, t2)], cast ([1i; 2], tr));
-%!   assert ([cast(1i, t1); cast([2; 3], t2)], cast ([1i; 2; 3], tr));
-%!   assert ([cast([1i; 2], t1); cast(3, t2)], cast ([1i; 2; 3], tr));
-%!   assert ([cast([1i; 2], t1); cast([3; 4], t2)], cast ([1i; 2; 3; 4], tr));
-%!   assert ([cast(1i, t1), cast(2, t2)], cast ([1i, 2], tr));
-%!   assert ([cast(1i, t1), cast([2, 3], t2)], cast ([1i, 2, 3], tr));
-%!   assert ([cast([1i, 2], t1), cast(3, t2)], cast ([1i, 2, 3], tr));
-%!   assert ([cast([1i, 2], t1), cast([3, 4], t2)], cast ([1i, 2, 3, 4], tr));
-%!
-%!   assert (cat (1, cast (1, t1), cast (2i, t2)), cast ([1; 2i], tr));
-%!   assert (cat (1, cast (1, t1), cast ([2i; 3], t2)), cast ([1; 2i; 3], tr));
-%!   assert (cat (1, cast ([1; 2], t1), cast (3i, t2)), cast ([1; 2; 3i], tr));
-%!   assert (cat (1, cast ([1; 2], t1), cast ([3i; 4], t2)), cast ([1; 2; 3i; 4], tr));
-%!   assert (cat (2, cast (1, t1), cast (2i, t2)), cast ([1, 2i], tr));
-%!   assert (cat (2, cast (1, t1), cast ([2i, 3], t2)), cast ([1, 2i, 3], tr));
-%!   assert (cat (2, cast ([1, 2], t1), cast (3i, t2)), cast ([1, 2, 3i], tr));
-%!   assert (cat (2, cast ([1, 2], t1), cast ([3i, 4], t2)), cast ([1, 2, 3i, 4], tr));
-%!
-%!   assert ([cast(1, t1); cast(2i, t2)], cast ([1; 2i], tr));
-%!   assert ([cast(1, t1); cast([2i; 3], t2)], cast ([1; 2i; 3], tr));
-%!   assert ([cast([1; 2], t1); cast(3i, t2)], cast ([1; 2; 3i], tr));
-%!   assert ([cast([1; 2], t1); cast([3i; 4], t2)], cast ([1; 2; 3i; 4], tr));
-%!   assert ([cast(1, t1), cast(2i, t2)], cast ([1, 2i], tr));
-%!   assert ([cast(1, t1), cast([2i, 3], t2)], cast ([1, 2i, 3], tr));
-%!   assert ([cast([1, 2], t1), cast(3i, t2)], cast ([1, 2, 3i], tr));
-%!   assert ([cast([1, 2], t1), cast([3i, 4], t2)], cast ([1, 2, 3i, 4], tr));
-%!
-%!   assert (cat (1, cast (1i, t1), cast (2i, t2)), cast ([1i; 2i], tr));
-%!   assert (cat (1, cast (1i, t1), cast ([2i; 3], t2)), cast ([1i; 2i; 3], tr));
-%!   assert (cat (1, cast ([1i; 2], t1), cast (3i, t2)), cast ([1i; 2; 3i], tr));
-%!   assert (cat (1, cast ([1i; 2], t1), cast ([3i; 4], t2)), cast ([1i; 2; 3i; 4], tr));
-%!   assert (cat (2, cast (1i, t1), cast (2i, t2)), cast ([1i, 2i], tr));
-%!   assert (cat (2, cast (1i, t1), cast ([2i, 3], t2)), cast ([1i, 2i, 3], tr));
-%!   assert (cat (2, cast ([1i, 2], t1), cast (3i, t2)), cast ([1i, 2, 3i], tr));
-%!   assert (cat (2, cast ([1i, 2], t1), cast ([3i, 4], t2)), cast ([1i, 2, 3i, 4], tr));
-%!
-%!   assert ([cast(1i, t1); cast(2i, t2)], cast ([1i; 2i], tr));
-%!   assert ([cast(1i, t1); cast([2i; 3], t2)], cast ([1i; 2i; 3], tr));
-%!   assert ([cast([1i; 2], t1); cast(3i, t2)], cast ([1i; 2; 3i], tr));
-%!   assert ([cast([1i; 2], t1); cast([3i; 4], t2)], cast ([1i; 2; 3i; 4], tr));
-%!   assert ([cast(1i, t1), cast(2i, t2)], cast ([1i, 2i], tr));
-%!   assert ([cast(1i, t1), cast([2i, 3], t2)], cast ([1i, 2i, 3], tr));
-%!   assert ([cast([1i, 2], t1), cast(3i, t2)], cast ([1i, 2, 3i], tr));
-%!   assert ([cast([1i, 2], t1), cast([3i, 4], t2)], cast ([1i, 2, 3i, 4], tr));
-%! endif
-%! ret = true;
+%!  assert (cat (1, cast ([], t1), cast ([], t2)), cast ([], tr));
+%! 
+%!  assert (cat (1, cast (1, t1), cast (2, t2)), cast ([1; 2], tr));
+%!  assert (cat (1, cast (1, t1), cast ([2; 3], t2)), cast ([1; 2; 3], tr));
+%!  assert (cat (1, cast ([1; 2], t1), cast (3, t2)), cast ([1; 2; 3], tr));
+%!  assert (cat (1, cast ([1; 2], t1), cast ([3; 4], t2)), cast ([1; 2; 3; 4], tr));
+%!  assert (cat (2, cast (1, t1), cast (2, t2)), cast ([1, 2], tr));
+%!  assert (cat (2, cast (1, t1), cast ([2, 3], t2)), cast ([1, 2, 3], tr));
+%!  assert (cat (2, cast ([1, 2], t1), cast (3, t2)), cast ([1, 2, 3], tr));
+%!  assert (cat (2, cast ([1, 2], t1), cast ([3, 4], t2)), cast ([1, 2, 3, 4], tr));
+%! 
+%!  assert ([cast(1, t1); cast(2, t2)], cast ([1; 2], tr));
+%!  assert ([cast(1, t1); cast([2; 3], t2)], cast ([1; 2; 3], tr));
+%!  assert ([cast([1; 2], t1); cast(3, t2)], cast ([1; 2; 3], tr));
+%!  assert ([cast([1; 2], t1); cast([3; 4], t2)], cast ([1; 2; 3; 4], tr));
+%!  assert ([cast(1, t1), cast(2, t2)], cast ([1, 2], tr));
+%!  assert ([cast(1, t1), cast([2, 3], t2)], cast ([1, 2, 3], tr));
+%!  assert ([cast([1, 2], t1), cast(3, t2)], cast ([1, 2, 3], tr));
+%!  assert ([cast([1, 2], t1), cast([3, 4], t2)], cast ([1, 2, 3, 4], tr));
+%! 
+%!  if (nargin == 3 || cmplx)
+%!    assert (cat (1, cast (1i, t1), cast (2, t2)), cast ([1i; 2], tr));
+%!    assert (cat (1, cast (1i, t1), cast ([2; 3], t2)), cast ([1i; 2; 3], tr));
+%!    assert (cat (1, cast ([1i; 2], t1), cast (3, t2)), cast ([1i; 2; 3], tr));
+%!    assert (cat (1, cast ([1i; 2], t1), cast ([3; 4], t2)), cast ([1i; 2; 3; 4], tr));
+%!    assert (cat (2, cast (1i, t1), cast (2, t2)), cast ([1i, 2], tr));
+%!    assert (cat (2, cast (1i, t1), cast ([2, 3], t2)), cast ([1i, 2, 3], tr));
+%!    assert (cat (2, cast ([1i, 2], t1), cast (3, t2)), cast ([1i, 2, 3], tr));
+%!    assert (cat (2, cast ([1i, 2], t1), cast ([3, 4], t2)), cast ([1i, 2, 3, 4], tr));
+%! 
+%!    assert ([cast(1i, t1); cast(2, t2)], cast ([1i; 2], tr));
+%!    assert ([cast(1i, t1); cast([2; 3], t2)], cast ([1i; 2; 3], tr));
+%!    assert ([cast([1i; 2], t1); cast(3, t2)], cast ([1i; 2; 3], tr));
+%!    assert ([cast([1i; 2], t1); cast([3; 4], t2)], cast ([1i; 2; 3; 4], tr));
+%!    assert ([cast(1i, t1), cast(2, t2)], cast ([1i, 2], tr));
+%!    assert ([cast(1i, t1), cast([2, 3], t2)], cast ([1i, 2, 3], tr));
+%!    assert ([cast([1i, 2], t1), cast(3, t2)], cast ([1i, 2, 3], tr));
+%!    assert ([cast([1i, 2], t1), cast([3, 4], t2)], cast ([1i, 2, 3, 4], tr));
+%! 
+%!    assert (cat (1, cast (1, t1), cast (2i, t2)), cast ([1; 2i], tr));
+%!    assert (cat (1, cast (1, t1), cast ([2i; 3], t2)), cast ([1; 2i; 3], tr));
+%!    assert (cat (1, cast ([1; 2], t1), cast (3i, t2)), cast ([1; 2; 3i], tr));
+%!    assert (cat (1, cast ([1; 2], t1), cast ([3i; 4], t2)), cast ([1; 2; 3i; 4], tr));
+%!    assert (cat (2, cast (1, t1), cast (2i, t2)), cast ([1, 2i], tr));
+%!    assert (cat (2, cast (1, t1), cast ([2i, 3], t2)), cast ([1, 2i, 3], tr));
+%!    assert (cat (2, cast ([1, 2], t1), cast (3i, t2)), cast ([1, 2, 3i], tr));
+%!    assert (cat (2, cast ([1, 2], t1), cast ([3i, 4], t2)), cast ([1, 2, 3i, 4], tr));
+%! 
+%!    assert ([cast(1, t1); cast(2i, t2)], cast ([1; 2i], tr));
+%!    assert ([cast(1, t1); cast([2i; 3], t2)], cast ([1; 2i; 3], tr));
+%!    assert ([cast([1; 2], t1); cast(3i, t2)], cast ([1; 2; 3i], tr));
+%!    assert ([cast([1; 2], t1); cast([3i; 4], t2)], cast ([1; 2; 3i; 4], tr));
+%!    assert ([cast(1, t1), cast(2i, t2)], cast ([1, 2i], tr));
+%!    assert ([cast(1, t1), cast([2i, 3], t2)], cast ([1, 2i, 3], tr));
+%!    assert ([cast([1, 2], t1), cast(3i, t2)], cast ([1, 2, 3i], tr));
+%!    assert ([cast([1, 2], t1), cast([3i, 4], t2)], cast ([1, 2, 3i, 4], tr));
+%! 
+%!    assert (cat (1, cast (1i, t1), cast (2i, t2)), cast ([1i; 2i], tr));
+%!    assert (cat (1, cast (1i, t1), cast ([2i; 3], t2)), cast ([1i; 2i; 3], tr));
+%!    assert (cat (1, cast ([1i; 2], t1), cast (3i, t2)), cast ([1i; 2; 3i], tr));
+%!    assert (cat (1, cast ([1i; 2], t1), cast ([3i; 4], t2)), cast ([1i; 2; 3i; 4], tr));
+%!    assert (cat (2, cast (1i, t1), cast (2i, t2)), cast ([1i, 2i], tr));
+%!    assert (cat (2, cast (1i, t1), cast ([2i, 3], t2)), cast ([1i, 2i, 3], tr));
+%!    assert (cat (2, cast ([1i, 2], t1), cast (3i, t2)), cast ([1i, 2, 3i], tr));
+%!    assert (cat (2, cast ([1i, 2], t1), cast ([3i, 4], t2)), cast ([1i, 2, 3i, 4], tr));
+%! 
+%!    assert ([cast(1i, t1); cast(2i, t2)], cast ([1i; 2i], tr));
+%!    assert ([cast(1i, t1); cast([2i; 3], t2)], cast ([1i; 2i; 3], tr));
+%!    assert ([cast([1i; 2], t1); cast(3i, t2)], cast ([1i; 2; 3i], tr));
+%!    assert ([cast([1i; 2], t1); cast([3i; 4], t2)], cast ([1i; 2; 3i; 4], tr));
+%!    assert ([cast(1i, t1), cast(2i, t2)], cast ([1i, 2i], tr));
+%!    assert ([cast(1i, t1), cast([2i, 3], t2)], cast ([1i, 2i, 3], tr));
+%!    assert ([cast([1i, 2], t1), cast(3i, t2)], cast ([1i, 2, 3i], tr));
+%!    assert ([cast([1i, 2], t1), cast([3i, 4], t2)], cast ([1i, 2, 3i, 4], tr));
+%!  endif
+%!  ret = true;
 %!endfunction
 
-%!assert (__testcat('double', 'double', 'double'))
-%!assert (__testcat('single', 'double', 'single'))
-%!assert (__testcat('double', 'single', 'single'))
-%!assert (__testcat('single', 'single', 'single'))
-
-%!assert (__testcat('double', 'int8', 'int8', false))
-%!assert (__testcat('int8', 'double', 'int8', false))
-%!assert (__testcat('single', 'int8', 'int8', false))
-%!assert (__testcat('int8', 'single', 'int8', false))
-%!assert (__testcat('int8', 'int8', 'int8', false))
-%!assert (__testcat('double', 'int16', 'int16', false))
-%!assert (__testcat('int16', 'double', 'int16', false))
-%!assert (__testcat('single', 'int16', 'int16', false))
-%!assert (__testcat('int16', 'single', 'int16', false))
-%!assert (__testcat('int16', 'int16', 'int16', false))
-%!assert (__testcat('double', 'int32', 'int32', false))
-%!assert (__testcat('int32', 'double', 'int32', false))
-%!assert (__testcat('single', 'int32', 'int32', false))
-%!assert (__testcat('int32', 'single', 'int32', false))
-%!assert (__testcat('int32', 'int32', 'int32', false))
-%!assert (__testcat('double', 'int64', 'int64', false))
-%!assert (__testcat('int64', 'double', 'int64', false))
-%!assert (__testcat('single', 'int64', 'int64', false))
-%!assert (__testcat('int64', 'single', 'int64', false))
-%!assert (__testcat('int64', 'int64', 'int64', false))
-
-%!assert (__testcat('double', 'uint8', 'uint8', false))
-%!assert (__testcat('uint8', 'double', 'uint8', false))
-%!assert (__testcat('single', 'uint8', 'uint8', false))
-%!assert (__testcat('uint8', 'single', 'uint8', false))
-%!assert (__testcat('uint8', 'uint8', 'uint8', false))
-%!assert (__testcat('double', 'uint16', 'uint16', false))
-%!assert (__testcat('uint16', 'double', 'uint16', false))
-%!assert (__testcat('single', 'uint16', 'uint16', false))
-%!assert (__testcat('uint16', 'single', 'uint16', false))
-%!assert (__testcat('uint16', 'uint16', 'uint16', false))
-%!assert (__testcat('double', 'uint32', 'uint32', false))
-%!assert (__testcat('uint32', 'double', 'uint32', false))
-%!assert (__testcat('single', 'uint32', 'uint32', false))
-%!assert (__testcat('uint32', 'single', 'uint32', false))
-%!assert (__testcat('uint32', 'uint32', 'uint32', false))
-%!assert (__testcat('double', 'uint64', 'uint64', false))
-%!assert (__testcat('uint64', 'double', 'uint64', false))
-%!assert (__testcat('single', 'uint64', 'uint64', false))
-%!assert (__testcat('uint64', 'single', 'uint64', false))
-%!assert (__testcat('uint64', 'uint64', 'uint64', false))
+%!assert (__testcat ("double", "double", "double"))
+%!assert (__testcat ("single", "double", "single"))
+%!assert (__testcat ("double", "single", "single"))
+%!assert (__testcat ("single", "single", "single"))
+
+%!assert (__testcat ("double", "int8", "int8", false))
+%!assert (__testcat ("int8", "double", "int8", false))
+%!assert (__testcat ("single", "int8", "int8", false))
+%!assert (__testcat ("int8", "single", "int8", false))
+%!assert (__testcat ("int8", "int8", "int8", false))
+%!assert (__testcat ("double", "int16", "int16", false))
+%!assert (__testcat ("int16", "double", "int16", false))
+%!assert (__testcat ("single", "int16", "int16", false))
+%!assert (__testcat ("int16", "single", "int16", false))
+%!assert (__testcat ("int16", "int16", "int16", false))
+%!assert (__testcat ("double", "int32", "int32", false))
+%!assert (__testcat ("int32", "double", "int32", false))
+%!assert (__testcat ("single", "int32", "int32", false))
+%!assert (__testcat ("int32", "single", "int32", false))
+%!assert (__testcat ("int32", "int32", "int32", false))
+%!assert (__testcat ("double", "int64", "int64", false))
+%!assert (__testcat ("int64", "double", "int64", false))
+%!assert (__testcat ("single", "int64", "int64", false))
+%!assert (__testcat ("int64", "single", "int64", false))
+%!assert (__testcat ("int64", "int64", "int64", false))
+
+%!assert (__testcat ("double", "uint8", "uint8", false))
+%!assert (__testcat ("uint8", "double", "uint8", false))
+%!assert (__testcat ("single", "uint8", "uint8", false))
+%!assert (__testcat ("uint8", "single", "uint8", false))
+%!assert (__testcat ("uint8", "uint8", "uint8", false))
+%!assert (__testcat ("double", "uint16", "uint16", false))
+%!assert (__testcat ("uint16", "double", "uint16", false))
+%!assert (__testcat ("single", "uint16", "uint16", false))
+%!assert (__testcat ("uint16", "single", "uint16", false))
+%!assert (__testcat ("uint16", "uint16", "uint16", false))
+%!assert (__testcat ("double", "uint32", "uint32", false))
+%!assert (__testcat ("uint32", "double", "uint32", false))
+%!assert (__testcat ("single", "uint32", "uint32", false))
+%!assert (__testcat ("uint32", "single", "uint32", false))
+%!assert (__testcat ("uint32", "uint32", "uint32", false))
+%!assert (__testcat ("double", "uint64", "uint64", false))
+%!assert (__testcat ("uint64", "double", "uint64", false))
+%!assert (__testcat ("single", "uint64", "uint64", false))
+%!assert (__testcat ("uint64", "single", "uint64", false))
+%!assert (__testcat ("uint64", "uint64", "uint64", false))
 
 %!assert (cat (3, [], [1,2;3,4]), [1,2;3,4])
 %!assert (cat (3, [1,2;3,4], []), [1,2;3,4])
@@ -2318,12 +2307,12 @@
 %!assert (cat (3, [], [], 1, 2), cat (3, 1, 2))
 %!assert (cat (3, [], [], [1,2;3,4]), [1,2;3,4])
 %!assert (cat (4, [], [], [1,2;3,4]), [1,2;3,4])
+
+%!assert ([zeros(3,2,2); ones(1,2,2)], repmat ([0;0;0;1],[1,2,2]) )
+%!assert ([zeros(3,2,2); ones(1,2,2)], vertcat (zeros (3,2,2), ones (1,2,2)) )
+
 %!error <dimension mismatch> cat (3, cat (3, [], []), [1,2;3,4])
 %!error <dimension mismatch> cat (3, zeros (0, 0, 2), [1,2;3,4])
-
-%!assert ([zeros(3,2,2); ones(1,2,2)], repmat([0;0;0;1],[1,2,2]) )
-%!assert ([zeros(3,2,2); ones(1,2,2)], vertcat(zeros(3,2,2), ones(1,2,2)) )
-
 */
 
 static octave_value
@@ -2359,7 +2348,7 @@
 @deftypefn {Built-in Function} {} permute (@var{A}, @var{perm})\n\
 Return the generalized transpose for an N-D array object @var{A}.\n\
 The permutation vector @var{perm} must contain the elements\n\
-@code{1:ndims(A)} (in any order, but each element must appear only once).\n\
+@code{1:ndims (A)} (in any order, but each element must appear only once).\n\
 @seealso{ipermute}\n\
 @end deftypefn")
 {
@@ -2389,6 +2378,7 @@
 Return the \"length\" of the object @var{a}.  For matrix objects, the\n\
 length is the number of rows or columns, whichever is greater (this\n\
 odd definition is used for compatibility with @sc{matlab}).\n\
+@seealso{size}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -2410,10 +2400,11 @@
 \n\
 @example\n\
 @group\n\
-  ndims (ones (4, 1, 2, 1))\n\
-     @result{} 3\n\
+ndims (ones (4, 1, 2, 1))\n\
+    @result{} 3\n\
 @end group\n\
 @end example\n\
+@seealso{size}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -2435,16 +2426,16 @@
 return the number of elements that would result from the indexing\n\
 \n\
 @example\n\
-  @var{a}(@var{idx1}, @var{idx2}, @dots{})\n\
+@var{a}(@var{idx1}, @var{idx2}, @dots{})\n\
 @end example\n\
 \n\
 Note that the indices do not have to be numerical.  For example,\n\
 \n\
 @example\n\
 @group\n\
-  @var{a} = 1;\n\
-  @var{b} = ones (2, 3);\n\
-  numel (@var{a}, @var{b});\n\
+@var{a} = 1;\n\
+@var{b} = ones (2, 3);\n\
+numel (@var{a}, @var{b})\n\
 @end group\n\
 @end example\n\
 \n\
@@ -2487,11 +2478,11 @@
 @example\n\
 @group\n\
 size ([1, 2; 3, 4; 5, 6])\n\
-     @result{} [ 3, 2 ]\n\
+   @result{} [ 3, 2 ]\n\
 \n\
 [nr, nc] = size ([1, 2; 3, 4; 5, 6])\n\
-     @result{} nr = 3\n\
-     @result{} nc = 2\n\
+    @result{} nr = 3\n\
+    @result{} nc = 2\n\
 @end group\n\
 @end example\n\
 \n\
@@ -2501,13 +2492,13 @@
 @example\n\
 @group\n\
 size ([1, 2; 3, 4; 5, 6], 2)\n\
-     @result{} 2\n\
+    @result{} 2\n\
 @end group\n\
 @end example\n\
 \n\
 @noindent\n\
 returns the number of columns in the given matrix.\n\
-@seealso{numel}\n\
+@seealso{numel, ndims, length, rows, columns}\n\
 @end deftypefn")
 {
   octave_value_list retval;
@@ -2570,7 +2561,7 @@
 Return true if the dimensions of all arguments agree.\n\
 Trailing singleton dimensions are ignored.\n\
 Called with a single or no argument, size_equal returns true.\n\
-@seealso{size, numel}\n\
+@seealso{size, numel, ndims}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -2602,7 +2593,7 @@
    "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {@var{scalar} =} nnz (@var{a})\n\
 Return the number of non zero elements in @var{a}.\n\
-@seealso{sparse}\n\
+@seealso{sparse, nzmax}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -2623,12 +2614,12 @@
 for sparse objects.  There are some cases of user created sparse objects\n\
 where the value returned by @dfn{nzmax} will not be the same as @dfn{nnz},\n\
 but in general they will give the same result.\n\
-@seealso{sparse, spalloc}\n\
+@seealso{nnz, spalloc, sparse}\n\
 @end deftypefn")
 {
   octave_value retval;
 
-  if (args.length() == 1)
+  if (args.length () == 1)
     retval = args(0).nzmax ();
   else
     print_usage ();
@@ -2674,31 +2665,32 @@
   "-*- texinfo -*-\n\
 @deftypefn  {Built-in Function} {} sum (@var{x})\n\
 @deftypefnx {Built-in Function} {} sum (@var{x}, @var{dim})\n\
-@deftypefnx {Built-in Function} {} sum (@dots{}, 'native')\n\
-@deftypefnx {Built-in Function} {} sum (@dots{}, 'double')\n\
-@deftypefnx {Built-in Function} {} sum (@dots{}, 'extra')\n\
+@deftypefnx {Built-in Function} {} sum (@dots{}, \"native\")\n\
+@deftypefnx {Built-in Function} {} sum (@dots{}, \"double\")\n\
+@deftypefnx {Built-in Function} {} sum (@dots{}, \"extra\")\n\
 Sum of elements along dimension @var{dim}.  If @var{dim} is\n\
 omitted, it defaults to the first non-singleton dimension.\n\
 \n\
-If the optional argument 'native' is given, then the sum is performed\n\
+If the optional argument \"native\" is given, then the sum is performed\n\
 in the same type as the original argument, rather than in the default\n\
 double type.  For example:\n\
 \n\
 @example\n\
 @group\n\
 sum ([true, true])\n\
-  @result{} 2\n\
-sum ([true, true], 'native')\n\
-  @result{} true\n\
+   @result{} 2\n\
+sum ([true, true], \"native\")\n\
+   @result{} true\n\
 @end group\n\
 @end example\n\
 \n\
-On the contrary, if 'double' is given, the sum is performed in double\n\
+On the contrary, if \"double\" is given, the sum is performed in double\n\
 precision even for single precision inputs.\n\
 \n\
-For double precision inputs, 'extra' indicates that a more accurate algorithm\n\
-than straightforward summation is to be used.  For single precision inputs,\n\
-'extra' is the same as 'double'.  Otherwise, 'extra' has no effect.\n\
+For double precision inputs, \"extra\" indicates that a more accurate\n\
+algorithm than straightforward summation is to be used.  For single precision\n\
+inputs, \"extra\" is the same as \"double\".  Otherwise, \"extra\" has no\n\
+effect.\n\
 @seealso{cumsum, sumsq, prod}\n\
 @end deftypefn")
 {
@@ -2800,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 ())
                 {
@@ -2827,64 +2825,65 @@
 }
 
 /*
-
-%!assert (sum([true,true]), 2)
-%!assert (sum([true,true],'native'), true)
-%!assert (sum(int8([127,10,-20])), 117);
-%!assert (sum(int8([127,10,-20]),'native'), int8(107));
-
-%!assert(sum ([1, 2, 3]), 6)
-%!assert(sum ([-1; -2; -3]), -6);
-%!assert(sum ([i, 2+i, -3+2i, 4]), 3+4i);
-%!assert(sum ([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i]), [2+2i, 4+4i, 6+6i]);
-
-%!assert(sum (single([1, 2, 3])), single(6))
-%!assert(sum (single([-1; -2; -3])), single(-6));
-%!assert(sum (single([i, 2+i, -3+2i, 4])), single(3+4i));
-%!assert(sum (single([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i])), single([2+2i, 4+4i, 6+6i]));
-
-%!error <Invalid call to sum> sum ();
-
-%!assert (sum ([1, 2; 3, 4], 1), [4, 6]);
-%!assert (sum ([1, 2; 3, 4], 2), [3; 7]);
-%!assert (sum (zeros (1, 0)), 0);
-%!assert (sum (zeros (1, 0), 1), zeros(1, 0));
-%!assert (sum (zeros (1, 0), 2), 0);
-%!assert (sum (zeros (0, 1)), 0);
-%!assert (sum (zeros (0, 1), 1), 0);
-%!assert (sum (zeros (0, 1), 2), zeros(0, 1));
-%!assert (sum (zeros (2, 0)),  zeros(1, 0));
-%!assert (sum (zeros (2, 0), 1), zeros(1, 0));
-%!assert (sum (zeros (2, 0), 2),  [0; 0]);
-%!assert (sum (zeros (0, 2)), [0, 0]);
-%!assert (sum (zeros (0, 2), 1), [0, 0]);
-%!assert (sum (zeros (0, 2), 2), zeros(0, 1));
-%!assert (sum (zeros (2, 2, 0, 3)), zeros(1, 2, 0, 3));
-%!assert (sum (zeros (2, 2, 0, 3), 2), zeros(2, 1, 0, 3));
-%!assert (sum (zeros (2, 2, 0, 3), 3), zeros(2, 2, 1, 3));
-%!assert (sum (zeros (2, 2, 0, 3), 4), zeros(2, 2, 0));
-%!assert (sum (zeros (2, 2, 0, 3), 7), zeros(2, 2, 0, 3));
-
-%!assert (sum (single([1, 2; 3, 4]), 1), single([4, 6]));
-%!assert (sum (single([1, 2; 3, 4]), 2), single([3; 7]));
-%!assert (sum (zeros (1, 0, 'single')), single(0));
-%!assert (sum (zeros (1, 0, 'single'), 1), zeros(1, 0, 'single'));
-%!assert (sum (zeros (1, 0, 'single'), 2), single(0));
-%!assert (sum (zeros (0, 1, 'single')), single(0));
-%!assert (sum (zeros (0, 1, 'single'), 1), single(0));
-%!assert (sum (zeros (0, 1, 'single'), 2), zeros(0, 1, 'single'));
-%!assert (sum (zeros (2, 0, 'single')),  zeros(1, 0, 'single'));
-%!assert (sum (zeros (2, 0, 'single'), 1), zeros(1, 0, 'single'));
-%!assert (sum (zeros (2, 0, 'single'), 2),  single([0; 0]));
-%!assert (sum (zeros (0, 2, 'single')), single([0, 0]));
-%!assert (sum (zeros (0, 2, 'single'), 1), single([0, 0]));
-%!assert (sum (zeros (0, 2, 'single'), 2), zeros(0, 1, 'single'));
-%!assert (sum (zeros (2, 2, 0, 3, 'single')), zeros(1, 2, 0, 3, 'single'));
-%!assert (sum (zeros (2, 2, 0, 3, 'single'), 2), zeros(2, 1, 0, 3, 'single'));
-%!assert (sum (zeros (2, 2, 0, 3, 'single'), 3), zeros(2, 2, 1, 3, 'single'));
-%!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 ([true,true]), 2)
+%!assert (sum ([true,true],"native"), true)
+%!assert (sum (int8 ([127,10,-20])), 117)
+%!assert (sum (int8 ([127,10,-20]),'native'), int8 (107))
+
+%!assert (sum ([1, 2, 3]), 6)
+%!assert (sum ([-1; -2; -3]), -6)
+%!assert (sum ([i, 2+i, -3+2i, 4]), 3+4i)
+%!assert (sum ([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i]), [2+2i, 4+4i, 6+6i])
+
+%!assert (sum (single ([1, 2, 3])), single (6))
+%!assert (sum (single ([-1; -2; -3])), single (-6))
+%!assert (sum (single ([i, 2+i, -3+2i, 4])), single (3+4i))
+%!assert (sum (single ([1, 2, 3; i, 2i, 3i; 1+i, 2+2i, 3+3i])), single ([2+2i, 4+4i, 6+6i]))
+
+%!assert (sum ([1, 2; 3, 4], 1), [4, 6])
+%!assert (sum ([1, 2; 3, 4], 2), [3; 7])
+%!assert (sum (zeros (1, 0)), 0)
+%!assert (sum (zeros (1, 0), 1), zeros (1, 0))
+%!assert (sum (zeros (1, 0), 2), 0)
+%!assert (sum (zeros (0, 1)), 0)
+%!assert (sum (zeros (0, 1), 1), 0)
+%!assert (sum (zeros (0, 1), 2), zeros (0, 1))
+%!assert (sum (zeros (2, 0)),  zeros (1, 0))
+%!assert (sum (zeros (2, 0), 1), zeros (1, 0))
+%!assert (sum (zeros (2, 0), 2),  [0; 0])
+%!assert (sum (zeros (0, 2)), [0, 0])
+%!assert (sum (zeros (0, 2), 1), [0, 0])
+%!assert (sum (zeros (0, 2), 2), zeros (0, 1))
+%!assert (sum (zeros (2, 2, 0, 3)), zeros (1, 2, 0, 3))
+%!assert (sum (zeros (2, 2, 0, 3), 2), zeros (2, 1, 0, 3))
+%!assert (sum (zeros (2, 2, 0, 3), 3), zeros (2, 2, 1, 3))
+%!assert (sum (zeros (2, 2, 0, 3), 4), zeros (2, 2, 0))
+%!assert (sum (zeros (2, 2, 0, 3), 7), zeros (2, 2, 0, 3))
+
+%!assert (sum (single ([1, 2; 3, 4]), 1), single ([4, 6]))
+%!assert (sum (single ([1, 2; 3, 4]), 2), single ([3; 7]))
+%!assert (sum (zeros (1, 0, "single")), single (0))
+%!assert (sum (zeros (1, 0, "single"), 1), zeros (1, 0, "single"))
+%!assert (sum (zeros (1, 0, "single"), 2), single (0))
+%!assert (sum (zeros (0, 1, "single")), single (0))
+%!assert (sum (zeros (0, 1, "single"), 1), single (0))
+%!assert (sum (zeros (0, 1, "single"), 2), zeros (0, 1, "single"))
+%!assert (sum (zeros (2, 0, "single")),  zeros (1, 0, "single"))
+%!assert (sum (zeros (2, 0, "single"), 1), zeros (1, 0, "single"))
+%!assert (sum (zeros (2, 0, "single"), 2),  single ([0; 0]))
+%!assert (sum (zeros (0, 2, "single")), single ([0, 0]))
+%!assert (sum (zeros (0, 2, "single"), 1), single ([0, 0]))
+%!assert (sum (zeros (0, 2, "single"), 2), zeros (0, 1, "single"))
+%!assert (sum (zeros (2, 2, 0, 3, "single")), zeros (1, 2, 0, 3, "single"))
+%!assert (sum (zeros (2, 2, 0, 3, "single"), 2), zeros (2, 1, 0, 3, "single"))
+%!assert (sum (zeros (2, 2, 0, 3, "single"), 3), zeros (2, 2, 1, 3, "single"))
+%!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 ()
 */
 
 DEFUN (sumsq, args, ,
@@ -2902,31 +2901,29 @@
 \n\
 @noindent\n\
 but it uses less memory and avoids calling @code{conj} if @var{x} is real.\n\
-@seealso{sum}\n\
+@seealso{sum, prod}\n\
 @end deftypefn")
 {
   DATA_REDUCTION (sumsq);
 }
 
 /*
-
-%!assert(sumsq ([1, 2, 3]), 14)
-%!assert(sumsq ([-1; -2; 4i]), 21);
-%!assert(sumsq ([1, 2, 3; 2, 3, 4; 4i, 6i, 2]), [21, 49, 29]);
-
-%!assert(sumsq (single([1, 2, 3])), single(14))
-%!assert(sumsq (single([-1; -2; 4i])), single(21));
-%!assert(sumsq (single([1, 2, 3; 2, 3, 4; 4i, 6i, 2])), single([21, 49, 29]));
-
-%!error <Invalid call to sumsq> sumsq ();
-
-%!assert (sumsq ([1, 2; 3, 4], 1), [10, 20]);
-%!assert (sumsq ([1, 2; 3, 4], 2), [5; 25]);
-
-%!assert (sumsq (single([1, 2; 3, 4]), 1), single([10, 20]));
-%!assert (sumsq (single([1, 2; 3, 4]), 2), single([5; 25]));
-
- */
+%!assert (sumsq ([1, 2, 3]), 14)
+%!assert (sumsq ([-1; -2; 4i]), 21)
+%!assert (sumsq ([1, 2, 3; 2, 3, 4; 4i, 6i, 2]), [21, 49, 29])
+
+%!assert (sumsq (single ([1, 2, 3])), single (14))
+%!assert (sumsq (single ([-1; -2; 4i])), single (21))
+%!assert (sumsq (single ([1, 2, 3; 2, 3, 4; 4i, 6i, 2])), single ([21, 49, 29]))
+
+%!assert (sumsq ([1, 2; 3, 4], 1), [10, 20])
+%!assert (sumsq ([1, 2; 3, 4], 2), [5; 25])
+
+%!assert (sumsq (single ([1, 2; 3, 4]), 1), single ([10, 20]))
+%!assert (sumsq (single ([1, 2; 3, 4]), 2), single ([5; 25]))
+
+%!error sumsq ()
+*/
 
 DEFUN (islogical, args, ,
   "-*- texinfo -*-\n\
@@ -2949,20 +2946,18 @@
 DEFALIAS (isbool, islogical);
 
 /*
-
-%!assert (islogical(true), true)
-%!assert (islogical(false), true)
-%!assert (islogical([true, false]), true)
-%!assert (islogical(1), false)
-%!assert (islogical(1i), false)
-%!assert (islogical([1,1]), false)
-%!assert (islogical(single(1)), false)
-%!assert (islogical(single(1i)), false)
-%!assert (islogical(single([1,1])), false)
-%!assert (islogical(sparse ([true, false])), true)
-%!assert (islogical(sparse ([1, 0])), false)
-
- */
+%!assert (islogical (true), true)
+%!assert (islogical (false), true)
+%!assert (islogical ([true, false]), true)
+%!assert (islogical (1), false)
+%!assert (islogical (1i), false)
+%!assert (islogical ([1,1]), false)
+%!assert (islogical (single (1)), false)
+%!assert (islogical (single (1i)), false)
+%!assert (islogical (single ([1,1])), false)
+%!assert (islogical (sparse ([true, false])), true)
+%!assert (islogical (sparse ([1, 0])), false)
+*/
 
 DEFUN (isinteger, args, ,
   "-*- texinfo -*-\n\
@@ -2987,7 +2982,7 @@
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} iscomplex (@var{x})\n\
 Return true if @var{x} is a complex-valued numeric object.\n\
-@seealso{isreal, isnumeric}\n\
+@seealso{isreal, isnumeric, islogical, ischar, isfloat, isa}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -3034,11 +3029,10 @@
 @example\n\
 @group\n\
 complex ([1, 2], [3, 4])\n\
-@result{}\n\
-   1 + 3i   2 + 4i\n\
+  @result{} [ 1 + 3i   2 + 4i ]\n\
 @end group\n\
 @end example\n\
-@seealso{real, imag, iscomplex}\n\
+@seealso{real, imag, iscomplex, abs, arg}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -3115,7 +3109,7 @@
                 {
                   SparseComplexMatrix result;
                   if (re_val.nnz () == 0)
-                    result = Complex(0, 1) * SparseComplexMatrix (im_val);
+                    result = Complex (0, 1) * SparseComplexMatrix (im_val);
                   else
                     {
                       result = SparseComplexMatrix (im_val.dims (), re_val (0));
@@ -3125,10 +3119,10 @@
                       for (octave_idx_type j = 0; j < nc; j++)
                         {
                           octave_idx_type off = j * nr;
-                          for (octave_idx_type i = im_val.cidx(j);
-                               i < im_val.cidx(j + 1); i++)
-                            result.data (im_val.ridx(i) + off) =
-                              result.data (im_val.ridx(i) + off) +
+                          for (octave_idx_type i = im_val.cidx (j);
+                               i < im_val.cidx (j + 1); i++)
+                            result.data (im_val.ridx (i) + off) =
+                              result.data (im_val.ridx (i) + off) +
                               Complex (0, im_val.data (i));
                         }
                     }
@@ -3141,17 +3135,17 @@
                     result = SparseComplexMatrix (re_val);
                   else
                     {
-                      result = SparseComplexMatrix (re_val.rows(), re_val.cols(), Complex(0, im_val (0)));
+                      result = SparseComplexMatrix (re_val.rows (), re_val.cols (), Complex (0, im_val (0)));
                       octave_idx_type nr = re_val.rows ();
                       octave_idx_type nc = re_val.cols ();
 
                       for (octave_idx_type j = 0; j < nc; j++)
                         {
                           octave_idx_type off = j * nr;
-                          for (octave_idx_type i = re_val.cidx(j);
-                               i < re_val.cidx(j + 1); i++)
-                            result.data (re_val.ridx(i) + off) =
-                              result.data (re_val.ridx(i) + off) +
+                          for (octave_idx_type i = re_val.cidx (j);
+                               i < re_val.cidx (j + 1); i++)
+                            result.data (re_val.ridx (i) + off) =
+                              result.data (re_val.ridx (i) + off) +
                               re_val.data (i);
                         }
                     }
@@ -3161,8 +3155,8 @@
                 {
                   if (re_val.dims () == im_val.dims ())
                     {
-                      SparseComplexMatrix result = SparseComplexMatrix(re_val)
-                        + Complex(0, 1) * SparseComplexMatrix (im_val);
+                      SparseComplexMatrix result = SparseComplexMatrix (re_val)
+                        + Complex (0, 1) * SparseComplexMatrix (im_val);
                       retval = octave_value (new octave_sparse_complex_matrix (result));
                     }
                   else
@@ -3317,7 +3311,7 @@
 Return true if @var{x} is a non-complex matrix or scalar.\n\
 For compatibility with @sc{matlab}, this includes logical and character\n\
 matrices.\n\
-@seealso{iscomplex, isnumeric}\n\
+@seealso{iscomplex, isnumeric, isa}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -3335,7 +3329,7 @@
 @deftypefn {Built-in Function} {} isempty (@var{a})\n\
 Return true if @var{a} is an empty matrix (any one of its dimensions is\n\
 zero).  Otherwise, return false.\n\
-@seealso{isnull}\n\
+@seealso{isnull, isa}\n\
 @end deftypefn")
 {
   octave_value retval = false;
@@ -3354,7 +3348,7 @@
 Return true if @var{x} is a numeric object, i.e., an integer, real, or\n\
 complex array.  Logical and character arrays are not considered to be\n\
 numeric.\n\
-@seealso{isinteger, isfloat, isreal, iscomplex, islogical, ischar, iscell, isstruct}\n\
+@seealso{isinteger, isfloat, isreal, iscomplex, islogical, ischar, iscell, isstruct, isa}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -3368,21 +3362,19 @@
 }
 
 /*
-
-%!assert (isnumeric(1), true)
-%!assert (isnumeric(1i), true)
-%!assert (isnumeric([1,1]), true)
-%!assert (isnumeric(single(1)), true)
-%!assert (isnumeric(single(1i)), true)
-%!assert (isnumeric(single([1,1])), true)
-%!assert (isnumeric(int8(1)), true)
-%!assert (isnumeric(uint8([1,1])), true)
-%!assert (isnumeric("Hello World"), false)
-%!assert (isnumeric(true), false)
-%!assert (isnumeric(false), false)
-%!assert (isnumeric([true, false]), false)
-%!assert (isnumeric(sparse ([true, false])), false)
-
+%!assert (isnumeric (1), true)
+%!assert (isnumeric (1i), true)
+%!assert (isnumeric ([1,1]), true)
+%!assert (isnumeric (single (1)), true)
+%!assert (isnumeric (single (1i)), true)
+%!assert (isnumeric (single ([1,1])), true)
+%!assert (isnumeric (int8 (1)), true)
+%!assert (isnumeric (uint8 ([1,1])), true)
+%!assert (isnumeric ("Hello World"), false)
+%!assert (isnumeric (true), false)
+%!assert (isnumeric (false), false)
+%!assert (isnumeric ([true, false]), false)
+%!assert (isnumeric (sparse ([true, false])), false)
 */
 
 DEFUN (ismatrix, args, ,
@@ -3392,7 +3384,7 @@
 Scalars (1x1 matrices) and vectors (@nospell{1xN} or @nospell{Nx1} matrices)\n\
 are subsets of the more general N-dimensional matrix and @code{ismatrix}\n\
 will return true for these objects as well.\n\
-@seealso{isscalar, isvector, iscell, isstruct, issparse}\n\
+@seealso{isscalar, isvector, iscell, isstruct, issparse, isa}\n\
 @end deftypefn")
 {
   octave_value retval = false;
@@ -3410,30 +3402,28 @@
 }
 
 /*
-
-%!assert(ismatrix ([]));
-%!assert(ismatrix (1));
-%!assert(ismatrix ([1, 2, 3]));
-%!assert(ismatrix ([1, 2; 3, 4]));
-%!assert(ismatrix (zeros (3, 2, 4)));
-
-%!assert(ismatrix (single([])));
-%!assert(ismatrix (single(1)));
-%!assert(ismatrix (single([1, 2, 3])));
-%!assert(ismatrix (single([1, 2; 3, 4])));
-
-%!assert(ismatrix ("t"));
-%!assert(ismatrix ("test"));
-%!assert(ismatrix (["test"; "ing"]));
+%!assert (ismatrix ([]))
+%!assert (ismatrix (1))
+%!assert (ismatrix ([1, 2, 3]))
+%!assert (ismatrix ([1, 2; 3, 4]))
+%!assert (ismatrix (zeros (3, 2, 4)))
+
+%!assert (ismatrix (single ([])))
+%!assert (ismatrix (single (1)))
+%!assert (ismatrix (single ([1, 2, 3])))
+%!assert (ismatrix (single ([1, 2; 3, 4])))
+
+%!assert (ismatrix ("t"))
+%!assert (ismatrix ("test"))
+%!assert (ismatrix (["test"; "ing"]))
 
 %!test
 %! s.a = 1;
-%! assert(ismatrix (s), false);
-
-%!error <Invalid call to ismatrix> ismatrix ();
-%!error <Invalid call to ismatrix> ismatrix ([1, 2; 3, 4], 2);
-
- */
+%! assert (ismatrix (s), false);
+
+%!error ismatrix ()
+%!error ismatrix ([1, 2; 3, 4], 2)
+*/
 
 static octave_value
 fill_matrix (const octave_value_list& args, int val, const char *fcn)
@@ -3887,23 +3877,21 @@
 }
 
 /*
-
-%!assert(ones (3), [1, 1, 1; 1, 1, 1; 1, 1, 1]);
-%!assert(ones (2, 3), [1, 1, 1; 1, 1, 1]);
-%!assert(ones (3, 2), [1, 1; 1, 1; 1, 1]);
-%!assert(size (ones (3, 4, 5)),  [3, 4, 5]);
-
-%!assert(ones (3,'single'), single([1, 1, 1; 1, 1, 1; 1, 1, 1]));
-%!assert(ones (2, 3,'single'), single([1, 1, 1; 1, 1, 1]));
-%!assert(ones (3, 2,'single'), single([1, 1; 1, 1; 1, 1]));
-%!assert(size (ones (3, 4, 5, 'single')),  [3, 4, 5]);
-
-%!assert(ones (3,'int8'), int8([1, 1, 1; 1, 1, 1; 1, 1, 1]));
-%!assert(ones (2, 3,'int8'), int8([1, 1, 1; 1, 1, 1]));
-%!assert(ones (3, 2,'int8'), int8([1, 1; 1, 1; 1, 1]));
-%!assert(size (ones (3, 4, 5, 'int8')),  [3, 4, 5]);
-
- */
+%!assert (ones (3), [1, 1, 1; 1, 1, 1; 1, 1, 1])
+%!assert (ones (2, 3), [1, 1, 1; 1, 1, 1])
+%!assert (ones (3, 2), [1, 1; 1, 1; 1, 1])
+%!assert (size (ones (3, 4, 5)), [3, 4, 5])
+
+%!assert (ones (3, "single"), single ([1, 1, 1; 1, 1, 1; 1, 1, 1]))
+%!assert (ones (2, 3, "single"), single ([1, 1, 1; 1, 1, 1]))
+%!assert (ones (3, 2, "single"), single ([1, 1; 1, 1; 1, 1]))
+%!assert (size (ones (3, 4, 5, "single")), [3, 4, 5])
+
+%!assert (ones (3, "int8"), int8 ([1, 1, 1; 1, 1, 1; 1, 1, 1]))
+%!assert (ones (2, 3, "int8"), int8 ([1, 1, 1; 1, 1, 1]))
+%!assert (ones (3, 2, "int8"), int8 ([1, 1; 1, 1; 1, 1]))
+%!assert (size (ones (3, 4, 5, "int8")), [3, 4, 5])
+*/
 
 DEFUN (zeros, args, ,
   "-*- texinfo -*-\n\
@@ -3931,23 +3919,21 @@
 }
 
 /*
-
-%!assert(zeros (3), [0, 0, 0; 0, 0, 0; 0, 0, 0]);
-%!assert(zeros (2, 3), [0, 0, 0; 0, 0, 0]);
-%!assert(zeros (3, 2), [0, 0; 0, 0; 0, 0]);
-%!assert(size (zeros (3, 4, 5)),  [3, 4, 5]);
-
-%!assert(zeros (3,'single'), single([0, 0, 0; 0, 0, 0; 0, 0, 0]));
-%!assert(zeros (2, 3,'single'), single([0, 0, 0; 0, 0, 0]));
-%!assert(zeros (3, 2,'single'), single([0, 0; 0, 0; 0, 0]));
-%!assert(size (zeros (3, 4, 5, 'single')),  [3, 4, 5]);
-
-%!assert(zeros (3,'int8'), int8([0, 0, 0; 0, 0, 0; 0, 0, 0]));
-%!assert(zeros (2, 3,'int8'), int8([0, 0, 0; 0, 0, 0]));
-%!assert(zeros (3, 2,'int8'), int8([0, 0; 0, 0; 0, 0]));
-%!assert(size (zeros (3, 4, 5, 'int8')),  [3, 4, 5]);
-
- */
+%!assert (zeros (3), [0, 0, 0; 0, 0, 0; 0, 0, 0])
+%!assert (zeros (2, 3), [0, 0, 0; 0, 0, 0])
+%!assert (zeros (3, 2), [0, 0; 0, 0; 0, 0])
+%!assert (size (zeros (3, 4, 5)), [3, 4, 5])
+
+%!assert (zeros (3, "single"), single ([0, 0, 0; 0, 0, 0; 0, 0, 0]))
+%!assert (zeros (2, 3, "single"), single ([0, 0, 0; 0, 0, 0]))
+%!assert (zeros (3, 2, "single"), single ([0, 0; 0, 0; 0, 0]))
+%!assert (size (zeros (3, 4, 5, "single")), [3, 4, 5])
+
+%!assert (zeros (3, "int8"), int8 ([0, 0, 0; 0, 0, 0; 0, 0, 0]))
+%!assert (zeros (2, 3, "int8"), int8 ([0, 0, 0; 0, 0, 0]))
+%!assert (zeros (3, 2, "int8"), int8 ([0, 0; 0, 0; 0, 0]))
+%!assert (size (zeros (3, 4, 5, "int8")), [3, 4, 5])
+*/
 
 DEFUN (Inf, args, ,
   "-*- texinfo -*-\n\
@@ -3968,9 +3954,8 @@
 \n\
 @example\n\
 @group\n\
-[1/0 e^800]\n\
-@result{}\n\
-Inf   Inf\n\
+[ 1/0 e^800 ]\n\
+@result{} Inf   Inf\n\
 @end group\n\
 @end example\n\
 \n\
@@ -3981,7 +3966,7 @@
 arguments specify additional matrix dimensions.\n\
 The optional argument @var{class} specifies the return type and may be\n\
 either \"double\" or \"single\".\n\
-@seealso{isinf}\n\
+@seealso{isinf, NaN}\n\
 @end deftypefn")
 {
   return fill_matrix (args, lo_ieee_inf_value (),
@@ -3991,23 +3976,21 @@
 DEFALIAS (inf, Inf);
 
 /*
-
-%!assert(inf (3), [Inf, Inf, Inf; Inf, Inf, Inf; Inf, Inf, Inf]);
-%!assert(inf (2, 3), [Inf, Inf, Inf; Inf, Inf, Inf]);
-%!assert(inf (3, 2), [Inf, Inf; Inf, Inf; Inf, Inf]);
-%!assert(size (inf (3, 4, 5)),  [3, 4, 5]);
-
-%!assert(inf (3,'single'), single([Inf, Inf, Inf; Inf, Inf, Inf; Inf, Inf, Inf]));
-%!assert(inf (2, 3,'single'), single([Inf, Inf, Inf; Inf, Inf, Inf]));
-%!assert(inf (3, 2,'single'), single([Inf, Inf; Inf, Inf; Inf, Inf]));
-%!assert(size (inf (3, 4, 5, 'single')),  [3, 4, 5]);
-
-%!error(inf (3,'int8'));
-%!error(inf (2, 3,'int8'));
-%!error(inf (3, 2,'int8'));
-%!error(inf (3, 4, 5, 'int8'));
-
- */
+%!assert (inf (3), [Inf, Inf, Inf; Inf, Inf, Inf; Inf, Inf, Inf])
+%!assert (inf (2, 3), [Inf, Inf, Inf; Inf, Inf, Inf])
+%!assert (inf (3, 2), [Inf, Inf; Inf, Inf; Inf, Inf])
+%!assert (size (inf (3, 4, 5)), [3, 4, 5])
+
+%!assert (inf (3, "single"), single ([Inf, Inf, Inf; Inf, Inf, Inf; Inf, Inf, Inf]))
+%!assert (inf (2, 3, "single"), single ([Inf, Inf, Inf; Inf, Inf, Inf]))
+%!assert (inf (3, 2, "single"), single ([Inf, Inf; Inf, Inf; Inf, Inf]))
+%!assert (size (inf (3, 4, 5, "single")), [3, 4, 5])
+
+%!error (inf (3, "int8"))
+%!error (inf (2, 3, "int8"))
+%!error (inf (3, 2, "int8"))
+%!error (inf (3, 4, 5, "int8"))
+*/
 
 DEFUN (NaN, args, ,
   "-*- texinfo -*-\n\
@@ -4042,7 +4025,7 @@
 arguments specify additional matrix dimensions.\n\
 The optional argument @var{class} specifies the return type and may be\n\
 either \"double\" or \"single\".\n\
-@seealso{isnan}\n\
+@seealso{isnan, Inf}\n\
 @end deftypefn")
 {
   return fill_matrix (args, lo_ieee_nan_value (),
@@ -4052,22 +4035,21 @@
 DEFALIAS (nan, NaN);
 
 /*
-%!assert(NaN (3), [NaN, NaN, NaN; NaN, NaN, NaN; NaN, NaN, NaN]);
-%!assert(NaN (2, 3), [NaN, NaN, NaN; NaN, NaN, NaN]);
-%!assert(NaN (3, 2), [NaN, NaN; NaN, NaN; NaN, NaN]);
-%!assert(size (NaN (3, 4, 5)),  [3, 4, 5]);
-
-%!assert(NaN (3,'single'), single([NaN, NaN, NaN; NaN, NaN, NaN; NaN, NaN, NaN]));
-%!assert(NaN (2, 3,'single'), single([NaN, NaN, NaN; NaN, NaN, NaN]));
-%!assert(NaN (3, 2,'single'), single([NaN, NaN; NaN, NaN; NaN, NaN]));
-%!assert(size (NaN (3, 4, 5, 'single')),  [3, 4, 5]);
-
-%!error(NaN (3,'int8'));
-%!error(NaN (2, 3,'int8'));
-%!error(NaN (3, 2,'int8'));
-%!error(NaN (3, 4, 5, 'int8'));
-
- */
+%!assert (NaN (3), [NaN, NaN, NaN; NaN, NaN, NaN; NaN, NaN, NaN])
+%!assert (NaN (2, 3), [NaN, NaN, NaN; NaN, NaN, NaN])
+%!assert (NaN (3, 2), [NaN, NaN; NaN, NaN; NaN, NaN])
+%!assert (size (NaN (3, 4, 5)), [3, 4, 5])
+
+%!assert (NaN (3, "single"), single ([NaN, NaN, NaN; NaN, NaN, NaN; NaN, NaN, NaN]))
+%!assert (NaN (2, 3, "single"), single ([NaN, NaN, NaN; NaN, NaN, NaN]))
+%!assert (NaN (3, 2, "single"), single ([NaN, NaN; NaN, NaN; NaN, NaN]))
+%!assert (size (NaN (3, 4, 5, "single")), [3, 4, 5])
+
+%!error (NaN (3, "int8"))
+%!error (NaN (2, 3, "int8"))
+%!error (NaN (3, 2, "int8"))
+%!error (NaN (3, 4, 5, "int8"))
+*/
 
 DEFUN (e, args, ,
   "-*- texinfo -*-\n\
@@ -4092,6 +4074,7 @@
 arguments specify additional matrix dimensions.\n\
 The optional argument @var{class} specifies the return type and may be\n\
 either \"double\" or \"single\".\n\
+@seealso{log, exp, pi, I}\n\
 @end deftypefn")
 {
 #if defined (M_E)
@@ -4124,7 +4107,7 @@
 for single precision.\n\
 \n\
 When called with no arguments, return a scalar with the value\n\
-@code{eps(1.0)}.\n\
+@code{eps (1.0)}.\n\
 Given a single argument @var{x}, return the distance between @var{x} and\n\
 the next largest value.\n\
 When called with more than one argument the first two arguments are taken as\n\
@@ -4132,6 +4115,7 @@
 arguments specify additional matrix dimensions.\n\
 The optional argument @var{class} specifies the return type and may be\n\
 either \"double\" or \"single\".\n\
+@seealso{realmax, realmin, intmax, bitmax}\n\
 @end deftypefn")
 {
   int nargin = args.length ();
@@ -4141,85 +4125,90 @@
     {
       if (args(0).is_single_type ())
         {
-          float val = args(0).float_value ();
+          Array<float> x = args(0).float_array_value ();
 
           if (! error_state)
-            {
-              val  = ::fabsf(val);
-              if (xisnan (val) || xisinf (val))
-                retval = fill_matrix (octave_value ("single"),
-                                      lo_ieee_nan_value (),
-                                      lo_ieee_float_nan_value (), "eps");
-              else if (val < FLT_MIN)
-                retval = fill_matrix (octave_value ("single"), 0e0,
-                                      powf (2.0, -149e0), "eps");
-              else
+            {              
+              Array<float> epsval (x.dims ());
+              
+              for (octave_idx_type i = 0; i < x.numel (); i++)
                 {
-                  int expon;
-                  frexpf (val, &expon);
-                  val = std::pow (static_cast <float> (2.0),
-                                  static_cast <float> (expon - 24));
-                  retval = fill_matrix (octave_value ("single"), DBL_EPSILON,
-                                        val, "eps");
+                  float val = ::fabsf (x(i));
+                  if (xisnan (val) || xisinf (val))
+                    epsval(i) = lo_ieee_nan_value ();
+                  else if (val < std::numeric_limits<float>::min ())
+                    epsval(i) = powf (2.0, -149e0);                  
+                  else
+                    {
+                      int expon;
+                      frexpf (val, &expon);
+                      epsval(i) = std::pow (static_cast <float> (2.0),
+                                            static_cast <float> (expon - 24));
+                    }
                 }
+              retval = epsval;
             }
         }
       else
         {
-          double val = args(0).double_value ();
+          Array<double> x = args(0).array_value ();
 
           if (! error_state)
             {
-              val  = ::fabs(val);
-              if (xisnan (val) || xisinf (val))
-                retval = fill_matrix (octave_value_list (),
-                                      lo_ieee_nan_value (),
-                                      lo_ieee_float_nan_value (), "eps");
-              else if (val < DBL_MIN)
-                retval = fill_matrix (octave_value_list (),
-                                      pow (2.0, -1074e0), 0e0, "eps");
-              else
+              Array<double> epsval (x.dims ());
+
+              for (octave_idx_type i = 0; i < x.numel (); i++)
                 {
-                  int expon;
-                  frexp (val, &expon);
-                  val = std::pow (static_cast <double> (2.0),
-                                  static_cast <double> (expon - 53));
-                  retval = fill_matrix (octave_value_list (), val,
-                                        FLT_EPSILON, "eps");
+                  double val = ::fabs (x(i));
+                  if (xisnan (val) || xisinf (val))
+                    epsval(i) = lo_ieee_nan_value ();
+                  else if (val < std::numeric_limits<double>::min ())
+                    epsval(i) = pow (2.0, -1074e0);
+                  else
+                    {
+                      int expon;
+                      frexp (val, &expon);
+                      epsval(i) = std::pow (static_cast <double> (2.0),
+                                            static_cast <double> (expon - 53));
+                    }
+                  retval = epsval;
                 }
             }
         }
     }
   else
-    retval = fill_matrix (args, DBL_EPSILON, FLT_EPSILON, "eps");
+    retval = fill_matrix (args, std::numeric_limits<double>::epsilon (),
+                          std::numeric_limits<float>::epsilon (), "eps");
 
   return retval;
 }
 
 /*
-
-%!assert(eps(1/2),2^(-53))
-%!assert(eps(1),2^(-52))
-%!assert(eps(2),2^(-51))
-%!assert(eps(realmax),2^971)
-%!assert(eps(0),2^(-1074))
-%!assert(eps(realmin/2),2^(-1074))
-%!assert(eps(realmin/16),2^(-1074))
-%!assert(eps(Inf),NaN)
-%!assert(eps(NaN),NaN)
-%!assert(eps(single(1/2)),single(2^(-24)))
-%!assert(eps(single(1)),single(2^(-23)))
-%!assert(eps(single(2)),single(2^(-22)))
-%!assert(eps(realmax('single')),single(2^104))
-%!assert(eps(single(0)),single(2^(-149)))
-%!assert(eps(realmin('single')/2),single(2^(-149)))
-%!assert(eps(realmin('single')/16),single(2^(-149)))
-%!assert(eps(single(Inf)),single(NaN))
-%!assert(eps(single(NaN)),single(NaN))
+%!assert (eps (1/2), 2^(-53))
+%!assert (eps (1), 2^(-52))
+%!assert (eps (2), 2^(-51))
+%!assert (eps (realmax), 2^971)
+%!assert (eps (0), 2^(-1074))
+%!assert (eps (realmin/2), 2^(-1074))
+%!assert (eps (realmin/16), 2^(-1074))
+%!assert (eps (Inf), NaN)
+%!assert (eps (NaN), NaN)
+%!assert (eps ([1/2 1 2 realmax 0 realmin/2 realmin/16 Inf NaN]), 
+%!             [2^(-53) 2^(-52) 2^(-51) 2^971 2^(-1074) 2^(-1074) 2^(-1074) NaN NaN])
+%!assert (eps (single (1/2)), single (2^(-24)))
+%!assert (eps (single (1)), single (2^(-23)))
+%!assert (eps (single (2)), single (2^(-22)))
+%!assert (eps (realmax ("single")), single (2^104))
+%!assert (eps (single (0)), single (2^(-149)))
+%!assert (eps (realmin ("single")/2), single (2^(-149)))
+%!assert (eps (realmin ("single")/16), single (2^(-149)))
+%!assert (eps (single (Inf)), single (NaN))
+%!assert (eps (single (NaN)), single (NaN))
+%!assert (eps (single ([1/2 1 2 realmax("single") 0 realmin("single")/2 realmin("single")/16 Inf NaN])), 
+%!             single ([2^(-24) 2^(-23) 2^(-22) 2^104 2^(-149) 2^(-149) 2^(-149) NaN NaN]))
 
 */
 
-
 DEFUN (pi, args, ,
   "-*- texinfo -*-\n\
 @deftypefn  {Built-in Function} {} pi\n\
@@ -4250,6 +4239,7 @@
 arguments specify additional matrix dimensions.\n\
 The optional argument @var{class} specifies the return type and may be\n\
 either \"double\" or \"single\".\n\
+@seealso{e, I}\n\
 @end deftypefn")
 {
 #if defined (M_PI)
@@ -4281,17 +4271,18 @@
 for single precision.\n\
 \n\
 When called with no arguments, return a scalar with the value\n\
-@code{realmax(\"double\")}.\n\
+@code{realmax (\"double\")}.\n\
 When called with a single argument, return a square matrix with the dimension\n\
 specified.  When called with more than one scalar argument the first two\n\
 arguments are taken as the number of rows and columns and any further\n\
 arguments specify additional matrix dimensions.\n\
 The optional argument @var{class} specifies the return type and may be\n\
 either \"double\" or \"single\".\n\
-@seealso{realmin, intmax, bitmax}\n\
+@seealso{realmin, intmax, bitmax, eps}\n\
 @end deftypefn")
 {
-  return fill_matrix (args, DBL_MAX, FLT_MAX, "realmax");
+  return fill_matrix (args, std::numeric_limits<double>::max (),
+                      std::numeric_limits<float>::max (), "realmax");
 }
 
 DEFUN (realmin, args, ,
@@ -4314,17 +4305,18 @@
 for single precision.\n\
 \n\
 When called with no arguments, return a scalar with the value\n\
-@code{realmin(\"double\")}.\n\
+@code{realmin (\"double\")}.\n\
 When called with a single argument, return a square matrix with the dimension\n\
 specified.  When called with more than one scalar argument the first two\n\
 arguments are taken as the number of rows and columns and any further\n\
 arguments specify additional matrix dimensions.\n\
 The optional argument @var{class} specifies the return type and may be\n\
 either \"double\" or \"single\".\n\
-@seealso{realmax, intmin}\n\
+@seealso{realmax, intmin, eps}\n\
 @end deftypefn")
 {
-  return fill_matrix (args, DBL_MIN, FLT_MIN, "realmin");
+  return fill_matrix (args, std::numeric_limits<double>::min (),
+                      std::numeric_limits<float>::min (), "realmin");
 }
 
 DEFUN (I, args, ,
@@ -4347,7 +4339,8 @@
 @ifnottex\n\
 @code{sqrt (-1)}.\n\
 @end ifnottex\n\
- I, and its equivalents i, J, and j, are functions so any of the names may\n\
+\n\
+I, and its equivalents i, j, and J, are functions so any of the names may\n\
 be reused for other purposes (such as i for a counter variable).\n\
 \n\
 When called with no arguments, return a scalar with the value @math{i}.  When\n\
@@ -4357,6 +4350,7 @@
 arguments specify additional matrix dimensions.\n\
 The optional argument @var{class} specifies the return type and may be\n\
 either \"double\" or \"single\".\n\
+@seealso{e, pi, log, exp}\n\
 @end deftypefn")
 {
   return fill_matrix (args, Complex (0.0, 1.0), "I");
@@ -4394,11 +4388,9 @@
 }
 
 /*
-
-%!assert(single(NA('double')),NA('single'))
-%!assert(double(NA('single')),NA('double'))
-
- */
+%!assert (single (NA ("double")), NA ("single"))
+%!assert (double (NA ("single")), NA ("double"))
+*/
 
 DEFUN (false, args, ,
   "-*- texinfo -*-\n\
@@ -4563,9 +4555,9 @@
 @example\n\
 @group\n\
 eye (3)\n\
-     @result{}  1  0  0\n\
-         0  1  0\n\
-         0  0  1\n\
+ @result{}  1  0  0\n\
+     0  1  0\n\
+     0  0  1\n\
 @end group\n\
 @end example\n\
 \n\
@@ -4591,7 +4583,7 @@
 Calling @code{eye} with no arguments is equivalent to calling it\n\
 with an argument of 1.  Any negative dimensions are treated as zero. \n\
 These odd definitions are for compatibility with @sc{matlab}.\n\
-@seealso{speye}\n\
+@seealso{speye, ones, zeros}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -4647,21 +4639,18 @@
   return retval;
 }
 
-
 /*
-
-%!assert (full (eye(3)), [1, 0, 0; 0, 1, 0; 0, 0, 1]);
-%!assert (full (eye(2, 3)), [1, 0, 0; 0, 1, 0]);
-
-%!assert (full (eye(3,'single')), single([1, 0, 0; 0, 1, 0; 0, 0, 1]));
-%!assert (full (eye(2, 3,'single')), single([1, 0, 0; 0, 1, 0]));
-
-%!assert (eye(3,'int8'), int8([1, 0, 0; 0, 1, 0; 0, 0, 1]));
-%!assert (eye(2, 3,'int8'), int8([1, 0, 0; 0, 1, 0]));
-
-%!error <Invalid call to eye> eye (1, 2, 3);
-
- */
+%!assert (full (eye (3)), [1, 0, 0; 0, 1, 0; 0, 0, 1])
+%!assert (full (eye (2, 3)), [1, 0, 0; 0, 1, 0])
+
+%!assert (full (eye (3,"single")), single ([1, 0, 0; 0, 1, 0; 0, 0, 1]))
+%!assert (full (eye (2, 3,"single")), single ([1, 0, 0; 0, 1, 0]))
+
+%!assert (eye (3, "int8"), int8 ([1, 0, 0; 0, 1, 0; 0, 0, 1]))
+%!assert (eye (2, 3, "int8"), int8 ([1, 0, 0; 0, 1, 0]))
+
+%!error eye (1, 2, 3)
+*/
 
 template <class MT>
 static octave_value
@@ -4724,6 +4713,7 @@
 \n\
 For compatibility with @sc{matlab}, return the second argument (@var{limit})\n\
 if fewer than two values are requested.\n\
+@seealso{logspace}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -4739,7 +4729,17 @@
     }
 
   if (nargin == 3)
-    npoints = args(2).idx_type_value ();
+    {
+      // Apparently undocumented Matlab.  If the third arg is an empty
+      // numeric value, the number of points defaults to 1.
+
+      octave_value arg_3 = args(2);
+
+      if (arg_3.is_numeric_type () && arg_3.is_empty ())
+        npoints = 1;
+      else
+        npoints = arg_3.idx_type_value ();
+    }
 
   if (! error_state)
     {
@@ -4770,24 +4770,20 @@
 
 
 /*
-
 %!test
 %! x1 = linspace (1, 2);
 %! x2 = linspace (1, 2, 10);
 %! x3 = linspace (1, -2, 10);
-%! assert((size (x1) == [1, 100] && x1(1) == 1 && x1(100) == 2
-%! && size (x2) == [1, 10] && x2(1) == 1 && x2(10) == 2
-%! && size (x3) == [1, 10] && x3(1) == 1 && x3(10) == -2));
-
-
-% assert(linspace ([1, 2; 3, 4], 5, 6), linspace (1, 5, 6));
-
-%!error <Invalid call to linspace> linspace ();
-%!error <Invalid call to linspace> linspace (1, 2, 3, 4);
-
-%!test
-%! fail("linspace ([1, 2; 3, 4], 5, 6)","warning");
-
+%! assert (size (x1) == [1, 100] && x1(1) == 1 && x1(100) == 2);
+%! assert (size (x2) == [1, 10] && x2(1) == 1 && x2(10) == 2);
+%! assert (size (x3) == [1, 10] && x3(1) == 1 && x3(10) == -2);
+
+%assert (linspace ([1, 2; 3, 4], 5, 6), linspace (1, 5, 6))
+
+%assert (linspace (0, 1, []), 1)
+
+%!error linspace ()
+%!error linspace (1, 2, 3, 4)
 */
 
 // FIXME -- should accept dimensions as separate args for N-d
@@ -4807,7 +4803,7 @@
 In other words, the statement\n\
 \n\
 @example\n\
-  y = resize (x, dv);\n\
+y = resize (x, dv)\n\
 @end example\n\
 \n\
 @noindent\n\
@@ -4815,10 +4811,12 @@
 \n\
 @example\n\
 @group\n\
-  y = zeros (dv, class (x));\n\
-  sz = min (dv, size (x));\n\
-  for i = 1:length (sz), idx@{i@} = 1:sz(i); endfor\n\
-  y(idx@{:@}) = x(idx@{:@});\n\
+y = zeros (dv, class (x));\n\
+sz = min (dv, size (x));\n\
+for i = 1:length (sz)\n\
+  idx@{i@} = 1:sz(i);\n\
+endfor\n\
+y(idx@{:@}) = x(idx@{:@});\n\
 @end group\n\
 @end example\n\
 \n\
@@ -4835,7 +4833,7 @@
 An object can be resized to more dimensions than it has;\n\
 in such case the missing dimensions are assumed to be 1.\n\
 Resizing an object to fewer dimensions is not possible.\n\
-@seealso{reshape, postpad}\n\
+@seealso{reshape, postpad, prepad, cat}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -4897,8 +4895,8 @@
 @example\n\
 @group\n\
 reshape ([1, 2, 3, 4], 2, 2)\n\
-     @result{}  1  3\n\
-         2  4\n\
+      @result{}  1  3\n\
+          2  4\n\
 @end group\n\
 @end example\n\
 \n\
@@ -4910,7 +4908,7 @@
 A single dimension of the return matrix may be left unspecified and Octave\n\
 will determine its size automatically.  An empty matrix ([]) is used to flag\n\
 the unspecified dimension.\n\
-@seealso{resize}\n\
+@seealso{resize, vec, postpad, cat, squeeze}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -5001,25 +4999,23 @@
 }
 
 /*
-
-%!assert(size (reshape (ones (4, 4), 2, 8)), [2, 8])
-%!assert(size (reshape (ones (4, 4), 8, 2)), [8, 2])
-%!assert(size (reshape (ones (15, 4), 1, 60)), [1, 60])
-%!assert(size (reshape (ones (15, 4), 60, 1)), [60, 1])
-
-%!assert(size (reshape (ones (4, 4, 'single'), 2, 8)), [2, 8])
-%!assert(size (reshape (ones (4, 4, 'single'), 8, 2)), [8, 2])
-%!assert(size (reshape (ones (15, 4, 'single'), 1, 60)), [1, 60])
-%!assert(size (reshape (ones (15, 4, 'single'), 60, 1)), [60, 1])
+%!assert (size (reshape (ones (4, 4), 2, 8)), [2, 8])
+%!assert (size (reshape (ones (4, 4), 8, 2)), [8, 2])
+%!assert (size (reshape (ones (15, 4), 1, 60)), [1, 60])
+%!assert (size (reshape (ones (15, 4), 60, 1)), [60, 1])
+
+%!assert (size (reshape (ones (4, 4, "single"), 2, 8)), [2, 8])
+%!assert (size (reshape (ones (4, 4, "single"), 8, 2)), [8, 2])
+%!assert (size (reshape (ones (15, 4, "single"), 1, 60)), [1, 60])
+%!assert (size (reshape (ones (15, 4, "single"), 60, 1)), [60, 1])
 
 %!test
 %! s.a = 1;
-%! fail("reshape (s, 2, 3)");
-
-%!error <Invalid call to reshape> reshape ();
-%!error reshape (1, 2, 3, 4);
-
- */
+%! fail ("reshape (s, 2, 3)");
+
+%!error reshape ()
+%!error reshape (1, 2, 3, 4)
+*/
 
 DEFUN (vec, args, ,
   "-*- texinfo -*-\n\
@@ -5030,7 +5026,7 @@
 @code{@var{x}(:)}.  If @var{dim} is supplied, the dimensions of @var{v}\n\
 are set to @var{dim} with all elements along the last dimension.\n\
 This is equivalent to @code{shiftdim (@var{x}(:), 1-@var{dim})}.\n\
-@seealso{vech}\n\
+@seealso{vech, resize, cat}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -5073,20 +5069,18 @@
 }
 
 /*
-
-%!assert(vec ([1, 2; 3, 4]), [1; 3; 2; 4])
-%!assert(vec ([1, 3, 2, 4]), [1; 3; 2; 4]);
-%!assert(vec ([1, 2, 3, 4], 2), [1, 2, 3, 4]);
-%!assert(vec ([1, 2; 3, 4]), vec ([1, 2; 3, 4], 1));
-%!assert(vec ([1, 2; 3, 4], 1), [1; 3; 2; 4]);
-%!assert(vec ([1, 2; 3, 4], 2), [1, 3, 2, 4]);
-%!assert(vec ([1, 3; 2, 4], 3), reshape ([1, 2, 3, 4], 1, 1, 4));
-%!assert(vec ([1, 3; 2, 4], 3), shiftdim (vec ([1, 3; 2, 4]), -2));
-
-%!error vec ();
-%!error vec (1, 2, 3);
-%!error vec ([1, 2; 3, 4], 0);
-
+%!assert (vec ([1, 2; 3, 4]), [1; 3; 2; 4])
+%!assert (vec ([1, 3, 2, 4]), [1; 3; 2; 4])
+%!assert (vec ([1, 2, 3, 4], 2), [1, 2, 3, 4])
+%!assert (vec ([1, 2; 3, 4]), vec ([1, 2; 3, 4], 1))
+%!assert (vec ([1, 2; 3, 4], 1), [1; 3; 2; 4])
+%!assert (vec ([1, 2; 3, 4], 2), [1, 3, 2, 4])
+%!assert (vec ([1, 3; 2, 4], 3), reshape ([1, 2, 3, 4], 1, 1, 4))
+%!assert (vec ([1, 3; 2, 4], 3), shiftdim (vec ([1, 3; 2, 4]), -2))
+
+%!error vec ()
+%!error vec (1, 2, 3)
+%!error vec ([1, 2; 3, 4], 0)
 */
 
 DEFUN (squeeze, args, ,
@@ -5095,6 +5089,7 @@
 Remove singleton dimensions from @var{x} and return the result.\n\
 Note that for compatibility with @sc{matlab}, all objects have\n\
 a minimum of two dimensions and row vectors are left unchanged.\n\
+@seealso{reshape}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -5109,7 +5104,7 @@
 
 DEFUN (full, args, ,
     "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{FM} =} full (@var{SM})\n\
+@deftypefn {Built-in Function} {@var{FM} =} full (@var{SM})\n\
 Return a full storage matrix from a sparse, diagonal, permutation matrix\n\
 or a range.\n\
 @seealso{sparse}\n\
@@ -5251,53 +5246,59 @@
 /*
 %!shared x
 %! x = [1, -3, 4, 5, -7];
-%!assert(norm(x,1), 20);
-%!assert(norm(x,2), 10);
-%!assert(norm(x,3), 8.24257059961711, -4*eps);
-%!assert(norm(x,Inf), 7);
-%!assert(norm(x,-Inf), 1);
-%!assert(norm(x,"inf"), 7);
-%!assert(norm(x,"fro"), 10, -eps);
-%!assert(norm(x), 10);
-%!assert(norm([1e200, 1]), 1e200);
-%!assert(norm([3+4i, 3-4i, sqrt(31)]), 9, -4*eps);
+%!assert (norm (x,1), 20)
+%!assert (norm (x,2), 10)
+%!assert (norm (x,3), 8.24257059961711, -4*eps)
+%!assert (norm (x,Inf), 7)
+%!assert (norm (x,-Inf), 1)
+%!assert (norm (x,"inf"), 7)
+%!assert (norm (x,"fro"), 10, -eps)
+%!assert (norm (x), 10)
+%!assert (norm ([1e200, 1]), 1e200)
+%!assert (norm ([3+4i, 3-4i, sqrt(31)]), 9, -4*eps)
 %!shared m
 %! m = magic (4);
-%!assert(norm(m,1), 34);
-%!assert(norm(m,2), 34, -eps);
-%!assert(norm(m,Inf), 34);
-%!assert(norm(m,"inf"), 34);
+%!assert (norm (m,1), 34)
+%!assert (norm (m,2), 34, -eps)
+%!assert (norm (m,Inf), 34)
+%!assert (norm (m,"inf"), 34)
 %!shared m2, flo, fhi
 %! m2 = [1,2;3,4];
 %! flo = 1e-300;
 %! fhi = 1e+300;
-%!assert (norm(flo*m2,"fro"), sqrt(30)*flo, -eps)
-%!assert (norm(fhi*m2,"fro"), sqrt(30)*fhi, -eps)
+%!assert (norm (flo*m2,"fro"), sqrt (30)*flo, -eps)
+%!assert (norm (fhi*m2,"fro"), sqrt (30)*fhi, -eps)
 
 %!shared x
-%! x = single([1, -3, 4, 5, -7]);
-%!assert(norm(x,1), single(20));
-%!assert(norm(x,2), single(10));
-%!assert(norm(x,3), single(8.24257059961711), -4*eps('single'));
-%!assert(norm(x,Inf), single(7));
-%!assert(norm(x,-Inf), single(1));
-%!assert(norm(x,"inf"), single(7));
-%!assert(norm(x,"fro"), single(10), -eps('single'));
-%!assert(norm(x), single(10));
-%!assert(norm(single([1e200, 1])), single(1e200));
-%!assert(norm(single([3+4i, 3-4i, sqrt(31)])), single(9), -4*eps('single'));
+%! x = single ([1, -3, 4, 5, -7]);
+%!assert (norm (x,1), single (20))
+%!assert (norm (x,2), single (10))
+%!assert (norm (x,3), single (8.24257059961711), -4*eps ("single"))
+%!assert (norm (x,Inf), single (7))
+%!assert (norm (x,-Inf), single (1))
+%!assert (norm (x,"inf"), single (7))
+%!assert (norm (x,"fro"), single (10), -eps ("single"))
+%!assert (norm (x), single (10))
+%!assert (norm (single ([1e200, 1])), single (1e200))
+%!assert (norm (single ([3+4i, 3-4i, sqrt(31)])), single (9), -4*eps ("single"))
 %!shared m
-%! m = single(magic (4));
-%!assert(norm(m,1), single(34));
-%!assert(norm(m,2), single(34), -eps('single'));
-%!assert(norm(m,Inf), single(34));
-%!assert(norm(m,"inf"), single(34));
+%! m = single (magic (4));
+%!assert (norm (m,1), single (34))
+%!assert (norm (m,2), single (34), -eps ("single"))
+%!assert (norm (m,Inf), single (34))
+%!assert (norm (m,"inf"), single (34))
 %!shared m2, flo, fhi
-%! m2 = single([1,2;3,4]);
-%! flo = single(1e-300);
-%! fhi = single(1e+300);
-%!assert (norm(flo*m2,"fro"), single(sqrt(30)*flo), -eps('single'))
-%!assert (norm(fhi*m2,"fro"), single(sqrt(30)*fhi), -eps('single'))
+%! m2 = single ([1,2;3,4]);
+%! flo = single (1e-300);
+%! fhi = single (1e+300);
+%!assert (norm (flo*m2,"fro"), single (sqrt (30)*flo), -eps ("single"))
+%!assert (norm (fhi*m2,"fro"), single (sqrt (30)*fhi), -eps ("single"))
+
+%!test
+%! ## Test for norm returning NaN on sparse matrix (bug #30631)
+%! A = sparse (2,2); 
+%! A(2,1) = 1;
+%! assert (norm (A), 1);
 */
 
 static octave_value
@@ -5328,6 +5329,7 @@
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} uplus (@var{x})\n\
 This function and @w{@xcode{+ x}} are equivalent.\n\
+@seealso{uminus, plus, minus}\n\
 @end deftypefn")
 {
   return unary_op_defun_body (octave_value::op_uplus, args);
@@ -5337,6 +5339,7 @@
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} uminus (@var{x})\n\
 This function and @w{@xcode{- x}} are equivalent.\n\
+@seealso{uplus, minus}\n\
 @end deftypefn")
 {
   return unary_op_defun_body (octave_value::op_uminus, args);
@@ -5354,25 +5357,23 @@
 }
 
 /*
-
-%!assert (2.', 2);
-%!assert (2i.',2i);
-%!assert ([1:4].',[1;2;3;4]);
-%!assert ([1;2;3;4].',[1:4]);
-%!assert ([1,2;3,4].',[1,3;2,4]);
-%!assert ([1,2i;3,4].',[1,3;2i,4]);
-
-%!assert (transpose ([1,2;3,4]),[1,3;2,4]);
-
-%!assert (single(2).', single(2));
-%!assert (single(2i).',single(2i));
-%!assert (single([1:4]).',single([1;2;3;4]));
-%!assert (single([1;2;3;4]).',single([1:4]));
-%!assert (single([1,2;3,4]).',single([1,3;2,4]));
-%!assert (single([1,2i;3,4]).',single([1,3;2i,4]));
-
-%!assert (transpose (single([1,2;3,4])),single([1,3;2,4]));
-
+%!assert (2.', 2)
+%!assert (2i.', 2i)
+%!assert ([1:4].', [1;2;3;4])
+%!assert ([1;2;3;4].', [1:4])
+%!assert ([1,2;3,4].', [1,3;2,4])
+%!assert ([1,2i;3,4].', [1,3;2i,4])
+
+%!assert (transpose ([1,2;3,4]), [1,3;2,4])
+
+%!assert (single (2).', single (2))
+%!assert (single (2i).', single (2i))
+%!assert (single ([1:4]).', single ([1;2;3;4]))
+%!assert (single ([1;2;3;4]).', single ([1:4]))
+%!assert (single ([1,2;3,4]).', single ([1,3;2,4]))
+%!assert (single ([1,2i;3,4]).', single ([1,3;2i,4]))
+
+%!assert (transpose (single ([1,2;3,4])), single ([1,3;2,4]))
 */
 
 DEFUN (ctranspose, args, ,
@@ -5387,25 +5388,23 @@
 }
 
 /*
-
-%!assert (2', 2);
-%!assert (2i',-2i);
-%!assert ([1:4]',[1;2;3;4]);
-%!assert ([1;2;3;4]',[1:4]);
-%!assert ([1,2;3,4]',[1,3;2,4]);
-%!assert ([1,2i;3,4]',[1,3;-2i,4]);
-
-%!assert (ctranspose ([1,2i;3,4]),[1,3;-2i,4]);
-
-%!assert (single(2)', single(2));
-%!assert (single(2i)',single(-2i));
-%!assert (single([1:4])',single([1;2;3;4]));
-%!assert (single([1;2;3;4])',single([1:4]));
-%!assert (single([1,2;3,4])',single([1,3;2,4]));
-%!assert (single([1,2i;3,4])',single([1,3;-2i,4]));
-
-%!assert (ctranspose (single([1,2i;3,4])),single([1,3;-2i,4]));
-
+%!assert (2', 2)
+%!assert (2i', -2i)
+%!assert ([1:4]', [1;2;3;4])
+%!assert ([1;2;3;4]', [1:4])
+%!assert ([1,2;3,4]', [1,3;2,4])
+%!assert ([1,2i;3,4]', [1,3;-2i,4])
+
+%!assert (ctranspose ([1,2i;3,4]), [1,3;-2i,4])
+
+%!assert (single (2)', single (2))
+%!assert (single (2i)', single (-2i))
+%!assert (single ([1:4])', single ([1;2;3;4]))
+%!assert (single ([1;2;3;4])', single ([1:4]))
+%!assert (single ([1,2;3,4])', single ([1,3;2,4]))
+%!assert (single ([1,2i;3,4])', single ([1,3;-2i,4]))
+
+%!assert (ctranspose (single ([1,2i;3,4])), single ([1,3;-2i,4]))
 */
 
 static octave_value
@@ -5460,11 +5459,11 @@
 cumulatively from left to right:\n\
 \n\
 @example\n\
-  (@dots{}((x1 + x2) + x3) + @dots{})\n\
+(@dots{}((x1 + x2) + x3) + @dots{})\n\
 @end example\n\
 \n\
 At least one argument is required.\n\
-@seealso{minus}\n\
+@seealso{minus, uplus}\n\
 @end deftypefn")
 {
   return binary_assoc_op_defun_body (octave_value::op_add,
@@ -5475,7 +5474,7 @@
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} minus (@var{x}, @var{y})\n\
 This function and @w{@xcode{x - y}} are equivalent.\n\
-@seealso{plus}\n\
+@seealso{plus, uminus}\n\
 @end deftypefn")
 {
   return binary_op_defun_body (octave_value::op_sub, args);
@@ -5491,11 +5490,11 @@
 cumulatively from left to right:\n\
 \n\
 @example\n\
-  (@dots{}((x1 * x2) * x3) * @dots{})\n\
+(@dots{}((x1 * x2) * x3) * @dots{})\n\
 @end example\n\
 \n\
 At least one argument is required.\n\
-@seealso{times}\n\
+@seealso{times, plus, minus, rdivide, mrdivide, mldivide, mpower}\n\
 @end deftypefn")
 {
   return binary_assoc_op_defun_body (octave_value::op_mul,
@@ -5507,7 +5506,7 @@
 @deftypefn {Built-in Function} {} mrdivide (@var{x}, @var{y})\n\
 Return the matrix right division of @var{x} and @var{y}.\n\
 This function and @w{@xcode{x / y}} are equivalent.\n\
-@seealso{mldivide, rdivide}\n\
+@seealso{mldivide, rdivide, plus, minus}\n\
 @end deftypefn")
 {
   return binary_op_defun_body (octave_value::op_div, args);
@@ -5518,7 +5517,7 @@
 @deftypefn {Built-in Function} {} mpower (@var{x}, @var{y})\n\
 Return the matrix power operation of @var{x} raised to the @var{y} power.\n\
 This function and @w{@xcode{x ^ y}} are equivalent.\n\
-@seealso{power}\n\
+@seealso{power, mtimes, plus, minus}\n\
 @end deftypefn")
 {
   return binary_op_defun_body (octave_value::op_pow, args);
@@ -5528,8 +5527,8 @@
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} mldivide (@var{x}, @var{y})\n\
 Return the matrix left division of @var{x} and @var{y}.\n\
-This function and @w{@xcode{x \\ y}} are equivalent.\n\
-@seealso{mrdivide, ldivide}\n\
+This function and @w{@xcode{x @xbackslashchar{} y}} are equivalent.\n\
+@seealso{mrdivide, ldivide, rdivide}\n\
 @end deftypefn")
 {
   return binary_op_defun_body (octave_value::op_ldiv, args);
@@ -5539,6 +5538,7 @@
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} lt (@var{x}, @var{y})\n\
 This function is equivalent to @w{@code{x < y}}.\n\
+@seealso{le, eq, ge, gt, ne}\n\
 @end deftypefn")
 {
   return binary_op_defun_body (octave_value::op_lt, args);
@@ -5548,6 +5548,7 @@
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} le (@var{x}, @var{y})\n\
 This function is equivalent to @w{@code{x <= y}}.\n\
+@seealso{eq, ge, gt, ne, lt}\n\
 @end deftypefn")
 {
   return binary_op_defun_body (octave_value::op_le, args);
@@ -5558,7 +5559,7 @@
 @deftypefn {Built-in Function} {} eq (@var{x}, @var{y})\n\
 Return true if the two inputs are equal.\n\
 This function is equivalent to @w{@code{x == y}}.\n\
-@seealso{ne, isequal}\n\
+@seealso{ne, isequal, le, ge, gt, ne, lt}\n\
 @end deftypefn")
 {
   return binary_op_defun_body (octave_value::op_eq, args);
@@ -5568,6 +5569,7 @@
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} ge (@var{x}, @var{y})\n\
 This function is equivalent to @w{@code{x >= y}}.\n\
+@seealso{le, eq, gt, ne, lt}\n\
 @end deftypefn")
 {
   return binary_op_defun_body (octave_value::op_ge, args);
@@ -5577,6 +5579,7 @@
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} gt (@var{x}, @var{y})\n\
 This function is equivalent to @w{@code{x > y}}.\n\
+@seealso{le, eq, ge, ne, lt}\n\
 @end deftypefn")
 {
   return binary_op_defun_body (octave_value::op_gt, args);
@@ -5587,7 +5590,7 @@
 @deftypefn {Built-in Function} {} ne (@var{x}, @var{y})\n\
 Return true if the two inputs are not equal.\n\
 This function is equivalent to @w{@code{x != y}}.\n\
-@seealso{eq, isequal}\n\
+@seealso{eq, isequal, le, ge, lt}\n\
 @end deftypefn")
 {
   return binary_op_defun_body (octave_value::op_ne, args);
@@ -5603,11 +5606,11 @@
 cumulatively from left to right:\n\
 \n\
 @example\n\
-  (@dots{}((x1 .* x2) .* x3) .* @dots{})\n\
+(@dots{}((x1 .* x2) .* x3) .* @dots{})\n\
 @end example\n\
 \n\
 At least one argument is required.\n\
-@seealso{mtimes}\n\
+@seealso{mtimes, rdivide}\n\
 @end deftypefn")
 {
   return binary_assoc_op_defun_body (octave_value::op_el_mul,
@@ -5619,7 +5622,7 @@
 @deftypefn {Built-in Function} {} rdivide (@var{x}, @var{y})\n\
 Return the element-by-element right division of @var{x} and @var{y}.\n\
 This function and @w{@xcode{x ./ y}} are equivalent.\n\
-@seealso{ldivide, mrdivide}\n\
+@seealso{ldivide, mrdivide, times, plus}\n\
 @end deftypefn")
 {
   return binary_op_defun_body (octave_value::op_el_div, args);
@@ -5645,8 +5648,8 @@
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} ldivide (@var{x}, @var{y})\n\
 Return the element-by-element left division of @var{x} and @var{y}.\n\
-This function and @w{@xcode{x .\\ y}} are equivalent.\n\
-@seealso{rdivide, mldivide}\n\
+This function and @w{@xcode{x .@xbackslashchar{} y}} are equivalent.\n\
+@seealso{rdivide, mldivide, times, plus}\n\
 @end deftypefn")
 {
   return binary_op_defun_body (octave_value::op_el_ldiv, args);
@@ -5662,7 +5665,7 @@
 cumulatively from left to right:\n\
 \n\
 @example\n\
-  (@dots{}((x1 & x2) & x3) & @dots{})\n\
+(@dots{}((x1 & x2) & x3) & @dots{})\n\
 @end example\n\
 \n\
 At least one argument is required.\n\
@@ -5683,7 +5686,7 @@
 cumulatively from left to right:\n\
 \n\
 @example\n\
-  (@dots{}((x1 | x2) | x3) | @dots{})\n\
+(@dots{}((x1 | x2) | x3) | @dots{})\n\
 @end example\n\
 \n\
 At least one argument is required.\n\
@@ -5699,10 +5702,14 @@
 DEFUN (tic, args, nargout,
   "-*- texinfo -*-\n\
 @deftypefn  {Built-in Function} {} tic ()\n\
+@deftypefnx {Built-in Function} {@var{id} =} tic ()\n\
 @deftypefnx {Built-in Function} {} toc ()\n\
+@deftypefnx {Built-in Function} {} toc (@var{id})\n\
+@deftypefnx {Built-in Function} {@var{val} =} toc (@dots{})\n\
 Set or check a wall-clock timer.  Calling @code{tic} without an\n\
-output argument sets the timer.  Subsequent calls to @code{toc}\n\
-return the number of seconds since the timer was set.  For example,\n\
+output argument sets the internal timer state.  Subsequent calls\n\
+to @code{toc} return the number of seconds since the timer was set.\n\
+For example,\n\
 \n\
 @example\n\
 @group\n\
@@ -5716,38 +5723,24 @@
 will set the variable @code{elapsed_time} to the number of seconds since\n\
 the most recent call to the function @code{tic}.\n\
 \n\
-If called with one output argument then this function returns a scalar\n\
-of type @code{uint64} and the wall-clock timer is not started.\n\
+If called with one output argument, @code{tic} returns a scalar\n\
+of type @code{uint64} that may be later passed to @code{toc}.\n\
 \n\
 @example\n\
 @group\n\
-t = tic; sleep (5); (double (tic ()) - double (t)) * 1e-6\n\
-     @result{} 5\n\
+id = tic; sleep (5); toc (id)\n\
+      @result{} 5.0010\n\
 @end group\n\
 @end example\n\
 \n\
-Nested timing with @code{tic} and @code{toc} is not supported.\n\
-Therefore @code{toc} will always return the elapsed time from the most\n\
-recent call to @code{tic}.\n\
+Calling @code{tic} and @code{toc} this way allows nested timing calls.\n\
 \n\
 If you are more interested in the CPU time that your process used, you\n\
 should use the @code{cputime} function instead.  The @code{tic} and\n\
 @code{toc} functions report the actual wall clock time that elapsed\n\
 between the calls.  This may include time spent processing other jobs or\n\
-doing nothing at all.  For example:\n\
-\n\
-@example\n\
-@group\n\
-tic (); sleep (5); toc ()\n\
-     @result{} 5\n\
-t = cputime (); sleep (5); cputime () - t\n\
-     @result{} 0\n\
-@end group\n\
-@end example\n\
-\n\
-@noindent\n\
-(This example also illustrates that the CPU timer may have a fairly\n\
-coarse resolution.)\n\
+doing nothing at all.\n\
+@seealso{toc, cputime}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -5762,7 +5755,13 @@
   double tmp = now.double_value ();
 
   if (nargout > 0)
-    retval = static_cast<octave_uint64> (1e6 * tmp);
+    {
+      double ip = 0.0;
+      double frac = modf (tmp, &ip);
+      uint64_t microsecs = static_cast<uint64_t> (CLOCKS_PER_SEC * frac);
+      microsecs += CLOCKS_PER_SEC * static_cast<uint64_t> (ip);
+      retval = octave_uint64 (microsecs);
+    }
   else
     tic_toc_timestamp = tmp;
 
@@ -5771,38 +5770,69 @@
 
 DEFUN (toc, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {} toc ()\n\
-See tic.\n\
+@deftypefn  {Built-in Function} {} toc ()\n\
+@deftypefnx {Built-in Function} {} toc (@var{id})\n\
+@deftypefnx {Built-in Function} {@var{val} =} toc (@dots{})\n\
+@seealso{tic, cputime}\n\
 @end deftypefn")
 {
   octave_value retval;
 
   int nargin = args.length ();
 
-  if (nargin != 0)
-    warning ("tic: ignoring extra arguments");
-
-  if (tic_toc_timestamp < 0)
-    {
-      warning ("toc called before timer set");
-      if (nargout > 0)
-        retval = Matrix ();
-    }
+  double start_time = tic_toc_timestamp;
+
+  if (nargin > 1)
+    print_usage ();
   else
     {
-      octave_time now;
-
-      double tmp = now.double_value () - tic_toc_timestamp;
-
-      if (nargout > 0)
-        retval = tmp;
-      else
-        octave_stdout << "Elapsed time is " << tmp << " seconds.\n";
+      if (nargin == 1)
+        {
+          octave_uint64 id = args(0).uint64_scalar_value ();
+
+          if (! error_state)
+            {
+              uint64_t val = id.value ();
+
+              start_time
+                = (static_cast<double> (val / CLOCKS_PER_SEC)
+                   + static_cast<double> (val % CLOCKS_PER_SEC) / CLOCKS_PER_SEC);
+
+              // FIXME -- should we also check to see whether the start
+              // time is after the beginning of this Octave session?
+            }
+          else
+            error ("toc: invalid ID");
+        }
+
+      if (! error_state)
+        {
+          if (start_time < 0)
+            error ("toc called before timer set");
+          else
+            {
+              octave_time now;
+
+              double tmp = now.double_value () - start_time;
+
+              if (nargout > 0)
+                retval = tmp;
+              else
+                octave_stdout << "Elapsed time is " << tmp << " seconds.\n";
+            }
+        }
     }
 
   return retval;
 }
 
+/*
+%!shared id
+%! id = tic ();
+%!assert (isa (id, "uint64"))
+%!assert (isa (toc (id), "double"))
+*/
+
 DEFUN (cputime, args, ,
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {[@var{total}, @var{user}, @var{system}] =} cputime ();\n\
@@ -5815,6 +5845,7 @@
 Note that because Octave used some CPU time to start, it is reasonable\n\
 to check to see if @code{cputime} works by checking to see if the total\n\
 CPU time used is nonzero.\n\
+@seealso{tic, toc}\n\
 @end deftypefn")
 {
   octave_value_list retval;
@@ -5863,19 +5894,19 @@
 
 #endif
 
-  retval (2) = sys;
-  retval (1) = usr;
-  retval (0) = sys + usr;
+  retval(2) = sys;
+  retval(1) = usr;
+  retval(0) = sys + usr;
 
   return retval;
 }
 
 DEFUN (sort, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {[@var{s}, @var{i}] =} sort (@var{x})\n\
-@deftypefnx {Loadable Function} {[@var{s}, @var{i}] =} sort (@var{x}, @var{dim})\n\
-@deftypefnx {Loadable Function} {[@var{s}, @var{i}] =} sort (@var{x}, @var{mode})\n\
-@deftypefnx {Loadable Function} {[@var{s}, @var{i}] =} sort (@var{x}, @var{dim}, @var{mode})\n\
+@deftypefn  {Built-in Function} {[@var{s}, @var{i}] =} sort (@var{x})\n\
+@deftypefnx {Built-in Function} {[@var{s}, @var{i}] =} sort (@var{x}, @var{dim})\n\
+@deftypefnx {Built-in Function} {[@var{s}, @var{i}] =} sort (@var{x}, @var{mode})\n\
+@deftypefnx {Built-in Function} {[@var{s}, @var{i}] =} sort (@var{x}, @var{dim}, @var{mode})\n\
 Return a copy of @var{x} with the elements arranged in increasing\n\
 order.  For matrices, @code{sort} orders the elements within columns\n\
 \n\
@@ -5884,16 +5915,16 @@
 @example\n\
 @group\n\
 sort ([1, 2; 2, 3; 3, 1])\n\
-     @result{}  1  1\n\
-         2  2\n\
-         3  3\n\
+   @result{}  1  1\n\
+       2  2\n\
+       3  3\n\
 @end group\n\
 @end example\n\
 \n\
 If the optional argument @var{dim} is given, then the matrix is sorted\n\
 along the dimension defined by @var{dim}.  The optional argument @code{mode}\n\
 defines the order in which the values will be sorted.  Valid values of\n\
-@code{mode} are `ascend' or `descend'.\n\
+@code{mode} are \"ascend\" or \"descend\".\n\
 \n\
 The @code{sort} function may also be used to produce a matrix\n\
 containing the original row indices of the elements in the sorted\n\
@@ -5902,12 +5933,12 @@
 @example\n\
 @group\n\
 [s, i] = sort ([1, 2; 2, 3; 3, 1])\n\
-     @result{} s = 1  1\n\
-            2  2\n\
-            3  3\n\
-     @result{} i = 1  3\n\
-            2  1\n\
-            3  2\n\
+  @result{} s = 1  1\n\
+         2  2\n\
+         3  3\n\
+  @result{} i = 1  3\n\
+         2  1\n\
+         3  2\n\
 @end group\n\
 @end example\n\
 \n\
@@ -5920,9 +5951,9 @@
 @example\n\
 @group\n\
 sort ([1+i; 1; 1-i])\n\
-     @result{} 1 + 0i\n\
-        1 - 1i\n\
-        1 + 1i\n\
+    @result{} 1 + 0i\n\
+       1 - 1i\n\
+       1 + 1i\n\
 @end group\n\
 @end example\n\
 \n\
@@ -5935,6 +5966,7 @@
 \n\
 The algorithm used in @code{sort} is optimized for the sorting of partially\n\
 ordered lists.\n\
+@seealso{sortrows, issorted}\n\
 @end deftypefn")
 {
   octave_value_list retval;
@@ -5957,7 +5989,7 @@
     {
       if (args(1).is_string ())
         {
-          std::string mode = args(1).string_value();
+          std::string mode = args(1).string_value ();
           if (mode == "ascend")
             smode = ASCENDING;
           else if (mode == "descend")
@@ -5985,7 +6017,7 @@
           error ("sort: MODE must be a string");
           return retval;
         }
-      std::string mode = args(2).string_value();
+      std::string mode = args(2).string_value ();
       if (mode == "ascend")
         smode = ASCENDING;
       else if (mode == "descend")
@@ -6018,8 +6050,8 @@
 
       Array<octave_idx_type> sidx;
 
-      retval (0) = arg.sort (sidx, dim, smode);
-      retval (1) = idx_vector (sidx, dv(dim)); // No checking, the extent is known.
+      retval(0) = arg.sort (sidx, dim, smode);
+      retval(1) = idx_vector (sidx, dv(dim)); // No checking, the extent is known.
     }
   else
     retval(0) = arg.sort (dim, smode);
@@ -6028,8 +6060,7 @@
 }
 
 /*
-
-%% Double
+## Double
 %!assert (sort ([NaN, 1, -1, 2, Inf]), [-1, 1, 2, Inf, NaN])
 %!assert (sort ([NaN, 1, -1, 2, Inf], 1), [NaN, 1, -1, 2, Inf])
 %!assert (sort ([NaN, 1, -1, 2, Inf], 2), [-1, 1, 2, Inf, NaN])
@@ -6045,10 +6076,10 @@
 
 %!test
 %! [v, i] = sort ([NaN, 1, -1, Inf, 1]);
-%! assert (v, [-1, 1, 1, Inf, NaN])
-%! assert (i, [3, 2, 5, 4, 1])
-
-%% Complex
+%! assert (v, [-1, 1, 1, Inf, NaN]);
+%! assert (i, [3, 2, 5, 4, 1]);
+
+## Complex
 %!assert (sort ([NaN, 1i, -1, 2, Inf]), [1i, -1, 2, Inf, NaN])
 %!assert (sort ([NaN, 1i, -1, 2, Inf], 1), [NaN, 1i, -1, 2, Inf])
 %!assert (sort ([NaN, 1i, -1, 2, Inf], 2), [1i, -1, 2, Inf, NaN])
@@ -6064,48 +6095,48 @@
 
 %!test
 %! [v, i] = sort ([NaN, 1i, -1, Inf, 1, 1i]);
-%! assert (v, [1, 1i, 1i, -1, Inf, NaN])
-%! assert (i, [5, 2, 6, 3, 4, 1])
-
-%% Single
-%!assert (sort (single([NaN, 1, -1, 2, Inf])), single([-1, 1, 2, Inf, NaN]))
-%!assert (sort (single([NaN, 1, -1, 2, Inf]), 1), single([NaN, 1, -1, 2, Inf]))
-%!assert (sort (single([NaN, 1, -1, 2, Inf]), 2), single([-1, 1, 2, Inf, NaN]))
-%!assert (sort (single([NaN, 1, -1, 2, Inf]), 3), single([NaN, 1, -1, 2, Inf]))
-%!assert (sort (single([NaN, 1, -1, 2, Inf]), "ascend"), single([-1, 1, 2, Inf, NaN]))
-%!assert (sort (single([NaN, 1, -1, 2, Inf]), 2, "ascend"), single([-1, 1, 2, Inf, NaN]))
-%!assert (sort (single([NaN, 1, -1, 2, Inf]), "descend"), single([NaN, Inf, 2, 1, -1]))
-%!assert (sort (single([NaN, 1, -1, 2, Inf]), 2, "descend"), single([NaN, Inf, 2, 1, -1]))
-%!assert (sort (single([3, 1, 7, 5; 8, 2, 6, 4])), single([3, 1, 6, 4; 8, 2, 7, 5]))
-%!assert (sort (single([3, 1, 7, 5; 8, 2, 6, 4]), 1), single([3, 1, 6, 4; 8, 2, 7, 5]))
-%!assert (sort (single([3, 1, 7, 5; 8, 2, 6, 4]), 2), single([1, 3, 5, 7; 2, 4, 6, 8]))
-%!assert (sort (single(1)), single(1))
+%! assert (v, [1, 1i, 1i, -1, Inf, NaN]);
+%! assert (i, [5, 2, 6, 3, 4, 1]);
+
+## Single
+%!assert (sort (single ([NaN, 1, -1, 2, Inf])), single ([-1, 1, 2, Inf, NaN]))
+%!assert (sort (single ([NaN, 1, -1, 2, Inf]), 1), single ([NaN, 1, -1, 2, Inf]))
+%!assert (sort (single ([NaN, 1, -1, 2, Inf]), 2), single ([-1, 1, 2, Inf, NaN]))
+%!assert (sort (single ([NaN, 1, -1, 2, Inf]), 3), single ([NaN, 1, -1, 2, Inf]))
+%!assert (sort (single ([NaN, 1, -1, 2, Inf]), "ascend"), single ([-1, 1, 2, Inf, NaN]))
+%!assert (sort (single ([NaN, 1, -1, 2, Inf]), 2, "ascend"), single ([-1, 1, 2, Inf, NaN]))
+%!assert (sort (single ([NaN, 1, -1, 2, Inf]), "descend"), single ([NaN, Inf, 2, 1, -1]))
+%!assert (sort (single ([NaN, 1, -1, 2, Inf]), 2, "descend"), single ([NaN, Inf, 2, 1, -1]))
+%!assert (sort (single ([3, 1, 7, 5; 8, 2, 6, 4])), single ([3, 1, 6, 4; 8, 2, 7, 5]))
+%!assert (sort (single ([3, 1, 7, 5; 8, 2, 6, 4]), 1), single ([3, 1, 6, 4; 8, 2, 7, 5]))
+%!assert (sort (single ([3, 1, 7, 5; 8, 2, 6, 4]), 2), single ([1, 3, 5, 7; 2, 4, 6, 8]))
+%!assert (sort (single (1)), single (1))
 
 %!test
-%! [v, i] = sort (single([NaN, 1, -1, Inf, 1]));
-%! assert (v, single([-1, 1, 1, Inf, NaN]))
-%! assert (i, [3, 2, 5, 4, 1])
-
-%% Single Complex
-%!assert (sort (single([NaN, 1i, -1, 2, Inf])), single([1i, -1, 2, Inf, NaN]))
-%!assert (sort (single([NaN, 1i, -1, 2, Inf]), 1), single([NaN, 1i, -1, 2, Inf]))
-%!assert (sort (single([NaN, 1i, -1, 2, Inf]), 2), single([1i, -1, 2, Inf, NaN]))
-%!assert (sort (single([NaN, 1i, -1, 2, Inf]), 3), single([NaN, 1i, -1, 2, Inf]))
-%!assert (sort (single([NaN, 1i, -1, 2, Inf]), "ascend"), single([1i, -1, 2, Inf, NaN]))
-%!assert (sort (single([NaN, 1i, -1, 2, Inf]), 2, "ascend"), single([1i, -1, 2, Inf, NaN]))
-%!assert (sort (single([NaN, 1i, -1, 2, Inf]), "descend"), single([NaN, Inf, 2, -1, 1i]))
-%!assert (sort (single([NaN, 1i, -1, 2, Inf]), 2, "descend"), single([NaN, Inf, 2, -1, 1i]))
-%!assert (sort (single([3, 1i, 7, 5; 8, 2, 6, 4])), single([3, 1i, 6, 4; 8, 2, 7, 5]))
-%!assert (sort (single([3, 1i, 7, 5; 8, 2, 6, 4]), 1), single([3, 1i, 6, 4; 8, 2, 7, 5]))
-%!assert (sort (single([3, 1i, 7, 5; 8, 2, 6, 4]), 2), single([1i, 3, 5, 7; 2, 4, 6, 8]))
-%!assert (sort (single(1i)),single( 1i))
+%! [v, i] = sort (single ([NaN, 1, -1, Inf, 1]));
+%! assert (v, single ([-1, 1, 1, Inf, NaN]));
+%! assert (i, [3, 2, 5, 4, 1]);
+
+## Single Complex
+%!assert (sort (single ([NaN, 1i, -1, 2, Inf])), single ([1i, -1, 2, Inf, NaN]))
+%!assert (sort (single ([NaN, 1i, -1, 2, Inf]), 1), single ([NaN, 1i, -1, 2, Inf]))
+%!assert (sort (single ([NaN, 1i, -1, 2, Inf]), 2), single ([1i, -1, 2, Inf, NaN]))
+%!assert (sort (single ([NaN, 1i, -1, 2, Inf]), 3), single ([NaN, 1i, -1, 2, Inf]))
+%!assert (sort (single ([NaN, 1i, -1, 2, Inf]), "ascend"), single ([1i, -1, 2, Inf, NaN]))
+%!assert (sort (single ([NaN, 1i, -1, 2, Inf]), 2, "ascend"), single ([1i, -1, 2, Inf, NaN]))
+%!assert (sort (single ([NaN, 1i, -1, 2, Inf]), "descend"), single ([NaN, Inf, 2, -1, 1i]))
+%!assert (sort (single ([NaN, 1i, -1, 2, Inf]), 2, "descend"), single ([NaN, Inf, 2, -1, 1i]))
+%!assert (sort (single ([3, 1i, 7, 5; 8, 2, 6, 4])), single ([3, 1i, 6, 4; 8, 2, 7, 5]))
+%!assert (sort (single ([3, 1i, 7, 5; 8, 2, 6, 4]), 1), single ([3, 1i, 6, 4; 8, 2, 7, 5]))
+%!assert (sort (single ([3, 1i, 7, 5; 8, 2, 6, 4]), 2), single ([1i, 3, 5, 7; 2, 4, 6, 8]))
+%!assert (sort (single (1i)), single (1i))
 
 %!test
-%! [v, i] = sort (single([NaN, 1i, -1, Inf, 1, 1i]));
-%! assert (v, single([1, 1i, 1i, -1, Inf, NaN]))
-%! assert (i, [5, 2, 6, 3, 4, 1])
-
-%% Bool
+%! [v, i] = sort (single ([NaN, 1i, -1, Inf, 1, 1i]));
+%! assert (v, single ([1, 1i, 1i, -1, Inf, NaN]));
+%! assert (i, [5, 2, 6, 3, 4, 1]);
+
+## Bool
 %!assert (sort ([true, false, true, false]), [false, false, true, true])
 %!assert (sort ([true, false, true, false], 1), [true, false, true, false])
 %!assert (sort ([true, false, true, false], 2), [false, false, true, true])
@@ -6118,10 +6149,10 @@
 
 %!test
 %! [v, i] = sort ([true, false, true, false]);
-%! assert (v, [false, false, true, true])
-%! assert (i, [2, 4, 1, 3])
-
-%% Sparse Double
+%! assert (v, [false, false, true, true]);
+%! assert (i, [2, 4, 1, 3]);
+
+## Sparse Double
 %!assert (sort (sparse ([0, NaN, 1, 0, -1, 2, Inf])), sparse ([-1, 0, 0, 1, 2, Inf, NaN]))
 %!assert (sort (sparse ([0, NaN, 1, 0, -1, 2, Inf]), 1), sparse ([0, NaN, 1, 0, -1, 2, Inf]))
 %!assert (sort (sparse ([0, NaN, 1, 0, -1, 2, Inf]), 2), sparse ([-1, 0, 0, 1, 2, Inf, NaN]))
@@ -6133,17 +6164,17 @@
 
 %!shared a
 %! a = randn (10, 10);
-%! a (a < 0) = 0;
+%! a(a < 0) = 0;
 %!assert (sort (sparse (a)), sparse (sort (a)))
 %!assert (sort (sparse (a), 1), sparse (sort (a, 1)))
 %!assert (sort (sparse (a), 2), sparse (sort (a, 2)))
 %!test
 %! [v, i] = sort (a);
 %! [vs, is] = sort (sparse (a));
-%! assert (vs, sparse (v))
-%! assert (is, i)
-
-%% Sparse Complex
+%! assert (vs, sparse (v));
+%! assert (is, i);
+
+## Sparse Complex
 %!assert (sort (sparse ([0, NaN, 1i, 0, -1, 2, Inf])), sparse ([0, 0, 1i, -1, 2, Inf, NaN]))
 %!assert (sort (sparse ([0, NaN, 1i, 0, -1, 2, Inf]), 1), sparse ([0, NaN, 1i, 0, -1, 2, Inf]))
 %!assert (sort (sparse ([0, NaN, 1i, 0, -1, 2, Inf]), 2), sparse ([0, 0, 1i, -1, 2, Inf, NaN]))
@@ -6155,7 +6186,7 @@
 
 %!shared a
 %! a = randn (10, 10);
-%! a (a < 0) = 0;
+%! a(a < 0) = 0;
 %! a = 1i * a;
 %!assert (sort (sparse (a)), sparse (sort (a)))
 %!assert (sort (sparse (a), 1), sparse (sort (a, 1)))
@@ -6163,30 +6194,30 @@
 %!test
 %! [v, i] = sort (a);
 %! [vs, is] = sort (sparse (a));
-%! assert (vs, sparse (v))
-%! assert (is, i)
-
-%% Sparse Bool
+%! assert (vs, sparse (v));
+%! assert (is, i);
+
+## Sparse Bool
 %!assert (sort (sparse ([true, false, true, false])), sparse ([false, false, true, true]))
-%!assert (sort (sparse([true, false, true, false]), 1), sparse ([true, false, true, false]))
+%!assert (sort (sparse ([true, false, true, false]), 1), sparse ([true, false, true, false]))
 %!assert (sort (sparse ([true, false, true, false]), 2), sparse ([false, false, true, true]))
 %!assert (sort (sparse ([true, false, true, false]), 3), sparse ([true, false, true, false]))
-%!assert (sort (sparse ([true, false, true, false]), "ascend"), sparse([false, false, true, true]))
-%!assert (sort (sparse ([true, false, true, false]), 2, "ascend"), sparse([false, false, true, true]))
+%!assert (sort (sparse ([true, false, true, false]), "ascend"), sparse ([false, false, true, true]))
+%!assert (sort (sparse ([true, false, true, false]), 2, "ascend"), sparse ([false, false, true, true]))
 %!assert (sort (sparse ([true, false, true, false]), "descend"), sparse ([true, true, false, false]))
-%!assert (sort (sparse ([true, false, true, false]), 2, "descend"), sparse([true, true, false, false]))
+%!assert (sort (sparse ([true, false, true, false]), 2, "descend"), sparse ([true, true, false, false]))
 
 %!test
-%! [v, i] = sort (sparse([true, false, true, false]));
-%! assert (v, sparse([false, false, true, true]))
-%! assert (i, [2, 4, 1, 3])
-
-%% Cell string array
+%! [v, i] = sort (sparse ([true, false, true, false]));
+%! assert (v, sparse ([false, false, true, true]));
+%! assert (i, [2, 4, 1, 3]);
+
+## Cell string array
 %!shared a, b, c
 %! a = {"Alice", "Cecile", "Eric", "Barry", "David"};
 %! b = {"Alice", "Barry", "Cecile", "David", "Eric"};
 %! c = {"Eric", "David", "Cecile", "Barry", "Alice"};
-%!assert (sort (a), b);
+%!assert (sort (a), b)
 %!assert (sort (a, 1), a)
 %!assert (sort (a, 2), b)
 %!assert (sort (a, 3), a)
@@ -6197,11 +6228,10 @@
 
 %!test
 %! [v, i] = sort (a);
-%! assert (i, [1, 4, 2, 5, 3])
-
-%!error <Invalid call to sort> sort ();
-%!error <Invalid call to sort> sort (1, 2, 3, 4);
-
+%! assert (i, [1, 4, 2, 5, 3]);
+
+%!error sort ()
+%!error sort (1, 2, 3, 4)
 */
 
 // Sort the rows of the matrix @var{a} according to the order
@@ -6229,7 +6259,7 @@
 
   if (nargin > 1)
     {
-      std::string mode = args(1).string_value();
+      std::string mode = args(1).string_value ();
       if (mode == "ascend")
         smode = ASCENDING;
       else if (mode == "descend")
@@ -6364,32 +6394,32 @@
 %! um = [3, 1; 2, 4];
 %! sv = [1, 2, 3, 4];
 %! uv = [2, 1, 4, 3];
-%!assert(issorted (sm, "rows"));
-%!assert(!issorted (um, "rows"));
-%!assert(issorted (sv));
-%!assert(!issorted (uv));
-%!assert(issorted (sv'));
-%!assert(!issorted (uv'));
-%!assert(issorted (sm, "rows", "ascending"));
-%!assert(!issorted (um, "rows", "ascending"));
-%!assert(issorted (sv, "ascending"));
-%!assert(!issorted (uv, "ascending"));
-%!assert(issorted (sv', "ascending"));
-%!assert(!issorted (uv', "ascending"));
-%!assert(!issorted (sm, "rows", "descending"));
-%!assert(issorted (flipud (sm), "rows", "descending"));
-%!assert(!issorted (sv, "descending"));
-%!assert(issorted (fliplr (sv), "descending"));
-%!assert(!issorted (sv', "descending"));
-%!assert(issorted (fliplr (sv)', "descending"));
-%!assert(!issorted (um, "rows", "either"));
-%!assert(!issorted (uv, "either"));
-%!assert(issorted (sm, "rows", "either"));
-%!assert(issorted (flipud (sm), "rows", "either"));
-%!assert(issorted (sv, "either"));
-%!assert(issorted (fliplr (sv), "either"));
-%!assert(issorted (sv', "either"));
-%!assert(issorted (fliplr (sv)', "either"));
+%!assert (issorted (sm, "rows"))
+%!assert (!issorted (um, "rows"))
+%!assert (issorted (sv))
+%!assert (!issorted (uv))
+%!assert (issorted (sv'))
+%!assert (!issorted (uv'))
+%!assert (issorted (sm, "rows", "ascending"))
+%!assert (!issorted (um, "rows", "ascending"))
+%!assert (issorted (sv, "ascending"))
+%!assert (!issorted (uv, "ascending"))
+%!assert (issorted (sv', "ascending"))
+%!assert (!issorted (uv', "ascending"))
+%!assert (!issorted (sm, "rows", "descending"))
+%!assert (issorted (flipud (sm), "rows", "descending"))
+%!assert (!issorted (sv, "descending"))
+%!assert (issorted (fliplr (sv), "descending"))
+%!assert (!issorted (sv', "descending"))
+%!assert (issorted (fliplr (sv)', "descending"))
+%!assert (!issorted (um, "rows", "either"))
+%!assert (!issorted (uv, "either"))
+%!assert (issorted (sm, "rows", "either"))
+%!assert (issorted (flipud (sm), "rows", "either"))
+%!assert (issorted (sv, "either"))
+%!assert (issorted (fliplr (sv), "either"))
+%!assert (issorted (sv', "either"))
+%!assert (issorted (fliplr (sv)', "either"))
 */
 
 DEFUN (nth_element, args, ,
@@ -6488,7 +6518,7 @@
   else if (idx.extent (n) > n)
     error ("accumarray: index out of range");
 
-  NDT retval (dim_vector (n, 1), T());
+  NDT retval (dim_vector (n, 1), T ());
 
   if (vals.numel () == 1)
     retval.idx_add (idx, vals (0));
@@ -6681,7 +6711,7 @@
 
   rdv(dim) = n;
 
-  NDT retval (rdv, T());
+  NDT retval (rdv, T ());
 
   if (idx.length () != vals_dim(dim))
     error ("accumdim: dimension mismatch");
@@ -6826,7 +6856,7 @@
 \n\
 @var{mask} can also be arbitrary numeric type, in which case\n\
 it is first converted to logical.\n\
-@seealso{logical}\n\
+@seealso{logical, diff}\n\
 @end deftypefn")
 {
   int nargin = args.length ();
@@ -7054,6 +7084,7 @@
 @var{k}-th order differences are calculated along this dimension.\n\
 In the case where @var{k} exceeds @code{size (@var{x}, @var{dim})}\n\
 an empty matrix is returned.\n\
+@seealso{sort, merge}\n\
 @end deftypefn")
 {
   int nargin = args.length ();
@@ -7095,21 +7126,16 @@
 }
 
 /*
-
 %!assert (diff ([1, 2, 3, 4]), [1, 1, 1])
 %!assert (diff ([1, 3, 7, 19], 2), [2, 8])
 %!assert (diff ([1, 2; 5, 4; 8, 7; 9, 6; 3, 1]), [4, 2; 3, 3; 1, -1; -6, -5])
 %!assert (diff ([1, 2; 5, 4; 8, 7; 9, 6; 3, 1], 3), [-1, -5; -5, 0])
-%!assert (isempty (diff (1)));
-
-%!error diff ([1, 2; 3, 4], -1);
-
-%!error diff ("foo");
-
-%!error diff ();
-
-%!error diff (1, 2, 3, 4);
-
+%!assert (isempty (diff (1)))
+
+%!error diff ()
+%!error diff (1, 2, 3, 4)
+%!error diff ("foo")
+%!error diff ([1, 2; 3, 4], -1)
 */
 
 template <class T>
@@ -7169,7 +7195,7 @@
 endfor\n\
 @end group\n\
 @end example\n\
-@seealso{repmat}\n\
+@seealso{repmat, cat}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -7239,3 +7265,163 @@
 
   return retval;
 }
+
+DEFUN (base64_encode, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {@var{s} =} base64_encode (@var{x})\n\
+Encode a double matrix or array @var{x} into the base64 format string\n\
+@var{s}.\n\
+\n\
+@seealso{base64_decode}\n\
+@end deftypefn")
+{
+  octave_value_list retval;
+  int nargin = args.length ();
+
+  if (nargin != 1)
+    print_usage ();
+  else 
+    {
+      if (! args(0).is_numeric_type ()) 
+        error ("base64_encode: encoding is supported only for numeric arrays");
+      else if (args(0).is_complex_type () 
+          || args(0).is_sparse_type ())
+        error ("base64_encode: encoding complex or sparse data is not supported");
+      else if (args(0).is_integer_type ())
+        {
+#define MAKE_INT_BRANCH(X)                                              \
+          if (args(0).is_ ## X ## _type ())                             \
+            {                                                           \
+              const X##NDArray in = args(0).  X## _array_value ();      \
+              size_t inlen =                                            \
+                in.numel () * sizeof (X## _t) / sizeof (char);          \
+              const char* inc =                                         \
+                reinterpret_cast<const char*> (in.data ());             \
+              char* out;                                                \
+              if (! error_state                                         \
+                  && octave_base64_encode (inc, inlen, &out))          \
+                retval(0) = octave_value (out);                         \
+            }
+                                          
+          MAKE_INT_BRANCH(int8)
+          else MAKE_INT_BRANCH(int16)
+          else MAKE_INT_BRANCH(int32)
+          else MAKE_INT_BRANCH(int64)
+          else MAKE_INT_BRANCH(uint8)
+          else MAKE_INT_BRANCH(uint16)
+          else MAKE_INT_BRANCH(uint32)
+          else MAKE_INT_BRANCH(uint64)
+#undef MAKE_INT_BRANCH
+
+          else
+            panic_impossible ();
+        }
+      else if (args(0).is_single_type ())
+        {
+          const Array<float> in = args(0).float_array_value ();
+          size_t inlen;
+          inlen = in.numel () * sizeof (float) / sizeof (char); 
+          const char*  inc;
+          inc = reinterpret_cast<const char*> (in.data ());  
+          char* out;
+          if (! error_state 
+              && octave_base64_encode (inc, inlen, &out))
+            retval(0) = octave_value (out);
+        }                 
+      else
+        {
+          const Array<double> in = args(0).array_value ();
+          size_t inlen;
+          inlen = in.numel () * sizeof (double) / sizeof (char); 
+          const char*  inc;
+          inc = reinterpret_cast<const char*> (in.data ());   
+          char* out;
+          if (! error_state 
+              && octave_base64_encode (inc, inlen, &out))
+            retval(0) = octave_value (out);
+        }
+    }  
+  return retval;
+}
+
+/*
+%!assert (base64_encode (single (pi)), "2w9JQA==")
+%!assert (base64_encode (uint8 ([0 0 0])), "AAAA")
+%!assert (base64_encode (uint16 ([0 0 0])), "AAAAAAAA")
+%!assert (base64_encode (uint32 ([0 0 0])), "AAAAAAAAAAAAAAAA")
+%!assert (base64_encode (uint64 ([0 0 0])), "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
+%!assert (base64_encode (uint8 ([255 255 255])), "////")
+
+%!error base64_encode ()
+%!error base64_encode (1,2)
+%!error base64_encode ("A string")
+%!error base64_encode ({"A cell array"})
+%!error base64_encode (struct ())
+*/
+
+DEFUN (base64_decode, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn  {Built-in Function} {@var{x} =} base64_decode (@var{s})\n\
+@deftypefnx {Built-in Function} {@var{x} =} base64_decode (@var{s}, @var{dims})\n\
+Decode the double matrix or array @var{x} from the base64 encoded string\n\
+@var{s}.  The optional input parameter @var{dims} should be a vector\n\
+containing the dimensions of the decoded array.\n\
+@seealso{base64_encode}\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+  int nargin = args.length ();
+
+  if (nargin < 1 || nargin > 2)
+    print_usage ();
+  else
+    {
+      dim_vector dims;
+
+      if (nargin > 1)
+        {
+          const Array<octave_idx_type> size =
+            args(1).octave_idx_type_vector_value ();
+
+          if (! error_state)
+            {
+              dims = dim_vector::alloc (size.length ());
+              for (octave_idx_type i = 0; i < size.length (); i++)
+                dims(i) = size(i);
+            }
+        }
+
+      const std::string str = args(0).string_value ();
+
+      if (! error_state)
+        {
+          Array<double> res = octave_base64_decode (str);
+
+          if (nargin > 1)
+            res = res.reshape (dims);
+
+          retval = res;
+        }        
+    }
+
+  return retval; 
+}
+
+/*
+%!assert (base64_decode (base64_encode (pi)), pi)
+%!
+%!test 
+%! in   = randn (10);
+%! outv = base64_decode (base64_encode (in));
+%! outm = base64_decode (base64_encode (in), size (in)); 
+%! assert (outv, in(:).');
+%! assert (outm, in);
+
+%!error base64_decode ()
+%!error base64_decode (1,2,3)
+%!error base64_decode (1, "this is not a valid set of dimensions")
+%!error <input was not valid base64> base64_decode (1)
+%!error <input was not valid base64> base64_decode ("AQ=")
+%!error <incorrect input size> base64_decode ("AQ==")
+*/
rename from src/data.h
rename to libinterp/interpfcn/data.h
rename from src/debug.cc
rename to libinterp/interpfcn/debug.cc
--- a/src/debug.cc
+++ b/libinterp/interpfcn/debug.cc
@@ -39,6 +39,7 @@
 #include "help.h"
 #include "input.h"
 #include "pager.h"
+#include "octave-link.h"
 #include "oct-obj.h"
 #include "utils.h"
 #include "parse.h"
@@ -209,7 +210,7 @@
       // Problem because parse_dbfunction_params() can only pass out a
       // single function
     }
-  else if (args(0).is_string())
+  else if (args(0).is_string ())
     {
       symbol_name = args(0).string_value ();
       if (error_state)
@@ -223,7 +224,7 @@
     {
       if (args(i).is_string ())
         {
-          int line = atoi (args(i).string_value().c_str ());
+          int line = atoi (args(i).string_value ().c_str ());
           if (error_state)
             break;
           lines[list_idx++] = line;
@@ -273,37 +274,61 @@
   return retval;
 }
 
+bool
+bp_table::do_add_breakpoint_1 (octave_user_code *fcn,
+                               const std::string& fname,
+                               const bp_table::intmap& line,
+                               bp_table::intmap& retval)
+{
+  bool found = false;
+
+  tree_statement_list *cmds = fcn->body ();
+
+  std::string file = fcn->fcn_file_name ();
+
+  if (cmds)
+    {
+      retval = cmds->add_breakpoint (file, line);
+
+      for (intmap_iterator p = retval.begin (); p != retval.end (); p++)
+        {
+          if (p->second != 0)
+            {
+              bp_set.insert (fname);
+              found = true;
+              break;
+            }
+        }
+    }
+
+  return found;
+}
+
 bp_table::intmap
 bp_table::do_add_breakpoint (const std::string& fname,
                              const bp_table::intmap& line)
 {
   intmap retval;
 
-  octave_idx_type len = line.size ();
-
   octave_user_code *dbg_fcn = get_user_code (fname);
 
   if (dbg_fcn)
     {
-      tree_statement_list *cmds = dbg_fcn->body ();
-
-      if (cmds)
+      if (! do_add_breakpoint_1 (dbg_fcn, fname, line, retval))
         {
-          for (int i = 0; i < len; i++)
-            {
-              const_intmap_iterator p = line.find (i);
+          typedef std::map<std::string, octave_value>::const_iterator
+            subfunction_map_const_iterator;
+
+          std::map<std::string, octave_value> subfcns
+            = dbg_fcn->subfunctions ();
 
-              if (p != line.end ())
-                {
-                  int lineno = p->second;
-
-                  retval[i] = cmds->set_breakpoint (lineno);
+          for (subfunction_map_const_iterator p = subfcns.begin ();
+               p != subfcns.end (); p++)
+            {
+              octave_user_code *dbg_subfcn = p->second.user_code_value ();
 
-                  if (retval[i] != 0)
-                    {
-                      bp_set.insert (fname);
-                    }
-                }
+              if (do_add_breakpoint_1 (dbg_subfcn, fname, line, retval))
+                break;
             }
         }
     }
@@ -335,8 +360,12 @@
 
       if (dbg_fcn)
         {
+          std::string file = dbg_fcn->fcn_file_name ();
+
           tree_statement_list *cmds = dbg_fcn->body ();
 
+          // FIXME -- move the operation on cmds to the
+          // tree_statement_list class?
           if (cmds)
             {
               octave_value_list results = cmds->list_breakpoints ();
@@ -348,7 +377,14 @@
                       const_intmap_iterator p = line.find (i);
 
                       if (p != line.end ())
-                        cmds->delete_breakpoint (p->second);
+                        {
+                          int lineno = p->second;
+
+                          cmds->delete_breakpoint (lineno);
+
+                          if (! file.empty ())
+                            octave_link::update_breakpoint (false, file, lineno);
+                        }
                     }
 
                   results = cmds->list_breakpoints ();
@@ -356,7 +392,6 @@
                   bp_set_iterator it = bp_set.find (fname);
                   if (results.length () == 0 && it != bp_set.end ())
                     bp_set.erase (it);
-
                 }
 
               retval = results.length ();
@@ -382,23 +417,17 @@
 
   if (dbg_fcn)
     {
+      std::string file = dbg_fcn->fcn_file_name ();
+
       tree_statement_list *cmds = dbg_fcn->body ();
 
       if (cmds)
         {
-          octave_value_list bkpts = cmds->list_breakpoints ();
-
-          for (int i = 0; i < bkpts.length (); i++)
-            {
-              int lineno = static_cast<int> (bkpts(i).int_value ());
-              cmds->delete_breakpoint (lineno);
-              retval[i] = lineno;
-            }
+          retval = cmds->remove_all_breakpoints (file);
 
           bp_set_iterator it = bp_set.find (fname);
           if (it != bp_set.end ())
             bp_set.erase (it);
-
         }
     }
   else if (! silent)
@@ -455,6 +484,8 @@
             {
               tree_statement_list *cmds = f->body ();
 
+              // FIXME -- move the operation on cmds to the
+              // tree_statement_list class?
               if (cmds)
                 {
                   octave_value_list bkpts = cmds->list_breakpoints ();
@@ -504,8 +535,8 @@
 
 DEFUN (dbstop, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {@var{rline} =} dbstop (\"@var{func}\")\n\
-@deftypefnx {Loadable Function} {@var{rline} =} dbstop (\"@var{func}\", @var{line}, @dots{})\n\
+@deftypefn  {Built-in Function} {@var{rline} =} dbstop (\"@var{func}\")\n\
+@deftypefnx {Built-in Function} {@var{rline} =} dbstop (\"@var{func}\", @var{line}, @dots{})\n\
 Set a breakpoint in function @var{func}.\n\
 \n\
 Arguments are\n\
@@ -548,8 +579,8 @@
 
 DEFUN (dbclear, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} dbclear (\"@var{func}\")\n\
-@deftypefnx {Loadable Function} {} dbclear (\"@var{func}\", @var{line}, @dots{})\n\
+@deftypefn  {Built-in Function} {} dbclear (\"@var{func}\")\n\
+@deftypefnx {Built-in Function} {} dbclear (\"@var{func}\", @var{line}, @dots{})\n\
 Delete a breakpoint in the function @var{func}.\n\
 \n\
 Arguments are\n\
@@ -585,9 +616,9 @@
 
 DEFUN (dbstatus, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} dbstatus ()\n\
-@deftypefnx {Loadable Function} {@var{brk_list} =} dbstatus ()\n\
-@deftypefnx {Loadable Function} {@var{brk_list} =} dbstatus (\"@var{func}\")\n\
+@deftypefn  {Built-in Function} {} dbstatus ()\n\
+@deftypefnx {Built-in Function} {@var{brk_list} =} dbstatus ()\n\
+@deftypefnx {Built-in Function} {@var{brk_list} =} dbstatus (\"@var{func}\")\n\
 Report the location of active breakpoints.\n\
 \n\
 When called with no input or output arguments, print the list of\n\
@@ -655,12 +686,16 @@
       for (bp_table::fname_line_map_iterator it = bp_list.begin ();
            it != bp_list.end (); it++)
         {
-          octave_stdout << "breakpoint in " << it->first << " at line(s) ";
-
           bp_table::intmap m = it->second;
 
           size_t nel = m.size ();
 
+          octave_stdout << "breakpoint in " << it->first;
+          if (nel > 1)
+            octave_stdout << " at lines ";
+          else
+            octave_stdout << " at line ";
+
           for (size_t j = 0; j < nel; j++)
             octave_stdout << m[j] << ((j < nel - 1) ? ", " : ".");
 
@@ -697,7 +732,7 @@
 
 DEFUN (dbwhere, , ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} dbwhere ()\n\
+@deftypefn {Command} {} dbwhere\n\
 In debugging mode, report the current file and line number where\n\
 execution is stopped.\n\
 @seealso{dbstatus, dbcont, dbstep, dbup}\n\
@@ -760,13 +795,18 @@
         {
           char ch;
           int line = 1;
-
-          if (line >= start && line <= end)
-            os << line << "\t";
+          bool isnewline = true;
 
-          while (fs.get (ch))
+          // FIXME: Why not use line-oriented input here [getline()]?
+          while (fs.get (ch) && line <= end)
             {
-              if (line >= start && line <= end)
+              if (isnewline && line >= start)
+                {
+                  os << line << "\t";
+                  isnewline = false;
+                }
+
+              if (line >= start)
                 {
                   os << ch;
                 }
@@ -774,8 +814,7 @@
               if (ch == '\n')
                 {
                   line++;
-                  if (line >= start && line <= end)
-                    os << line << "\t";
+                  isnewline = true;
                 }
             }
         }
@@ -790,17 +829,24 @@
 
 DEFUN (dbtype, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} dbtype ()\n\
-@deftypefnx {Loadable Function} {} dbtype (\"startl:endl\")\n\
-@deftypefnx {Loadable Function} {} dbtype (\"@var{func}\")\n\
-@deftypefnx {Loadable Function} {} dbtype (\"@var{func}\", \"startl:endl\")\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\
+@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;
@@ -817,46 +863,54 @@
           dbg_fcn = get_user_code ();
 
           if (dbg_fcn)
-            do_dbtype (octave_stdout, dbg_fcn->name (), 0, INT_MAX);
+            do_dbtype (octave_stdout, dbg_fcn->name (), 0,
+                       std::numeric_limits<int>::max ());
           else
             error ("dbtype: must be inside a user function to give no arguments to dbtype\n");
           break;
 
         case 1: // (dbtype func) || (dbtype start:end)
-          dbg_fcn = get_user_code (argv[1]);
+          {
+            std::string arg = argv[1];
+
+            size_t ind = arg.find (':');
+
+            if (ind != std::string::npos)  // (dbtype start:end)
+              {  
+                dbg_fcn = get_user_code ();
 
-          if (dbg_fcn)
-            do_dbtype (octave_stdout, dbg_fcn->name (), 0, INT_MAX);
-          else
-            {
-              dbg_fcn = get_user_code ();
+                if (dbg_fcn)
+                  {
+                    std::string start_str = arg.substr (0, ind);
+                    std::string end_str = arg.substr (ind + 1);
 
-              if (dbg_fcn)
-                {
-                  std::string arg = argv[1];
-
-                  size_t ind = arg.find (':');
+                    int start, end;
+                    start = atoi (start_str.c_str ());
+                    if (end_str == "end")
+                      end = std::numeric_limits<int>::max ();
+                    else
+                      end = atoi (end_str.c_str ());
 
-                  if (ind != std::string::npos)
-                    {
-                      std::string start_str = arg.substr (0, ind);
-                      std::string end_str = arg.substr (ind + 1);
-
-                      int start = atoi (start_str.c_str ());
-                      int end = atoi (end_str.c_str ());
+                    if (std::min (start, end) <= 0)
+                      error ("dbtype: start and end lines must be >= 1\n");
 
-                      if (std::min (start, end) <= 0)
-                        error ("dbtype: start and end lines must be >= 1\n");
+                    if (start <= end)
+                      do_dbtype (octave_stdout, dbg_fcn->name (), start, end);
+                    else
+                      error ("dbtype: start line must be less than end line\n");
+                  }
+              }
+            else  // (dbtype func)
+              {
+                dbg_fcn = get_user_code (arg);
 
-                      if (start <= end)
-                        do_dbtype (octave_stdout, dbg_fcn->name (), start, end);
-                      else
-                        error ("dbtype: start line must be less than end line\n");
-                    }
-                  else
-                    error ("dbtype: line specification must be 'start:end'");
-                }
-            }
+                if (dbg_fcn)
+                  do_dbtype (octave_stdout, dbg_fcn->name (), 0,
+                             std::numeric_limits<int>::max ());
+                else
+                  error ("dbtype: function <%s> not found\n", arg.c_str ());
+              }
+          }
           break;
 
         case 2: // (dbtype func start:end) , (dbtype func start)
@@ -865,8 +919,7 @@
           if (dbg_fcn)
             {
               std::string arg = argv[2];
-              int start = 0;
-              int end = 0;
+              int start, end;
               size_t ind = arg.find (':');
 
               if (ind != std::string::npos)
@@ -875,8 +928,10 @@
                   std::string end_str = arg.substr (ind + 1);
 
                   start = atoi (start_str.c_str ());
-                  end = atoi (end_str.c_str ());
-
+                  if (end_str == "end")
+                    end = std::numeric_limits<int>::max ();
+                  else
+                    end = atoi (end_str.c_str ());
                 }
               else
                 {
@@ -892,6 +947,9 @@
               else
                 error ("dbtype: start line must be less than end line\n");
             }
+          else
+            error ("dbtype: function <%s> not found\n", argv[1].c_str ());
+
           break;
 
         default:
@@ -1004,9 +1062,9 @@
 
 DEFUN (dbstack, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} dbstack ()\n\
-@deftypefnx {Loadable Function} {} dbstack (@var{n})\n\
-@deftypefnx {Loadable Function} {[@var{stack}, @var{idx}] =} dbstack (@dots{})\n\
+@deftypefn  {Command} {} dbstack\n\
+@deftypefnx {Command} {} dbstack @var{n}\n\
+@deftypefnx {Built-in Function} {[@var{stack}, @var{idx}] =} dbstack (@dots{})\n\
 Display or return current debugging function stack information.\n\
 With optional argument @var{n}, omit the @var{n} innermost stack frames.\n\
 \n\
@@ -1072,8 +1130,8 @@
 
 DEFUN (dbup, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} dbup\n\
-@deftypefnx {Loadable Function} {} dbup (@var{n})\n\
+@deftypefn  {Built-in Function} {} dbup\n\
+@deftypefnx {Built-in Function} {} dbup (@var{n})\n\
 In debugging mode, move up the execution stack @var{n} frames.\n\
 If @var{n} is omitted, move up one frame.\n\
 @seealso{dbstack, dbdown}\n\
@@ -1088,8 +1146,8 @@
 
 DEFUN (dbdown, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} dbdown\n\
-@deftypefnx {Loadable Function} {} dbdown (@var{n})\n\
+@deftypefn  {Built-in Function} {} dbdown\n\
+@deftypefnx {Built-in Function} {} dbdown (@var{n})\n\
 In debugging mode, move down the execution stack @var{n} frames.\n\
 If @var{n} is omitted, move down one frame.\n\
 @seealso{dbstack, dbup}\n\
@@ -1234,7 +1292,7 @@
 
 DEFUN (isdebugmode, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {} isdebugmode ()\n\
+@deftypefn {Built-in Function} {} isdebugmode ()\n\
 Return true if in debugging mode, otherwise false.\n\
 @seealso{dbwhere, dbstack, dbstatus}\n\
 @end deftypefn")
rename from src/debug.h
rename to libinterp/interpfcn/debug.h
--- a/src/debug.h
+++ b/libinterp/interpfcn/debug.h
@@ -115,6 +115,9 @@
 
   static void cleanup_instance (void) { delete instance; instance = 0; }
 
+  bool do_add_breakpoint_1 (octave_user_code *fcn, const std::string& fname,
+                            const intmap& line, intmap& retval);
+
   intmap do_add_breakpoint (const std::string& fname, const intmap& lines);
 
   int do_remove_breakpoint (const std::string&, const intmap& lines);
@@ -129,6 +132,6 @@
   bool do_have_breakpoints (void) { return (! bp_set.empty ()); }
 };
 
-std::string get_file_line (const std::string& fname, size_t line);
+extern std::string get_file_line (const std::string& fname, size_t line);
 
 #endif
rename from src/defaults.cc
rename to libinterp/interpfcn/defaults.cc
--- a/src/defaults.cc
+++ b/libinterp/interpfcn/defaults.cc
@@ -74,6 +74,9 @@
 std::string Vlocal_api_fcn_file_dir;
 std::string Vlocal_fcn_file_dir;
 
+std::string Voct_etc_dir;
+std::string Voct_locale_dir;
+
 std::string Voct_file_dir;
 std::string Vfcn_file_dir;
 
@@ -91,6 +94,8 @@
 std::string Vlocal_site_defaults_file;
 std::string Vsite_defaults_file;
 
+std::string Vbuilt_in_docstrings_file;
+
 std::string
 subst_octave_home (const std::string& s)
 {
@@ -214,6 +219,18 @@
 }
 
 static void
+set_default_oct_etc_dir (void)
+{
+  Voct_etc_dir = subst_octave_home (OCTAVE_OCTETCDIR);
+}
+
+static void
+set_default_oct_locale_dir (void)
+{
+  Voct_locale_dir = subst_octave_home (OCTAVE_OCTLOCALEDIR);
+}
+
+static void
 set_default_oct_file_dir (void)
 {
   Voct_file_dir = subst_octave_home (OCTAVE_OCTFILEDIR);
@@ -286,32 +303,54 @@
 static void
 set_default_doc_cache_file (void)
 {
-  std::string def_file = subst_octave_home (OCTAVE_DOC_CACHE_FILE);
+  if (Vdoc_cache_file.empty ())
+    {
+      std::string def_file = subst_octave_home (OCTAVE_DOC_CACHE_FILE);
+
+      std::string env_file = octave_env::getenv ("OCTAVE_DOC_CACHE_FILE");
+
+      Vdoc_cache_file = env_file.empty () ? def_file : env_file;
+    }
+}
 
-  std::string env_file = octave_env::getenv ("OCTAVE_DOC_CACHE_FILE");
+static void
+set_default_texi_macros_file (void)
+{
+  if (Vtexi_macros_file.empty ())
+    {
+      std::string def_file = subst_octave_home (OCTAVE_TEXI_MACROS_FILE);
 
-  Vdoc_cache_file = env_file.empty () ? def_file : env_file;
+      std::string env_file = octave_env::getenv ("OCTAVE_TEXI_MACROS_FILE");
+
+      Vtexi_macros_file = env_file.empty () ? def_file : env_file;
+    }
 }
 
 static void
 set_default_info_file (void)
 {
-  std::string std_info_file = subst_octave_home (OCTAVE_INFOFILE);
+  if (Vinfo_file.empty ())
+    {
+      std::string std_info_file = subst_octave_home (OCTAVE_INFOFILE);
 
-  std::string oct_info_file = octave_env::getenv ("OCTAVE_INFO_FILE");
+      std::string oct_info_file = octave_env::getenv ("OCTAVE_INFO_FILE");
 
-  Vinfo_file = oct_info_file.empty () ? std_info_file : oct_info_file;
+      Vinfo_file = oct_info_file.empty () ? std_info_file : oct_info_file;
+    }
 }
 
 static void
 set_default_info_prog (void)
 {
-  std::string oct_info_prog = octave_env::getenv ("OCTAVE_INFO_PROGRAM");
+  if (Vinfo_program.empty ())
+    {
+      std::string oct_info_prog = octave_env::getenv ("OCTAVE_INFO_PROGRAM");
 
-  if (oct_info_prog.empty ())
-    Vinfo_program = "info";
-  else
-    Vinfo_program = std::string (oct_info_prog);
+      if (oct_info_prog.empty ())
+        Vinfo_program = "info";
+      else
+        Vinfo_program = std::string (oct_info_prog);
+    }
 }
 
 static void
@@ -353,6 +392,21 @@
     Vsite_defaults_file = sf;
 }
 
+static void
+set_built_in_docstrings_file (void)
+{
+  if (Vbuilt_in_docstrings_file.empty ())
+    {
+      std::string df = octave_env::getenv ("OCTAVE_BUILT_IN_DOCSTRINGS_FILE");
+
+      if (df.empty ())
+        Vbuilt_in_docstrings_file
+          = Voct_etc_dir + file_ops::dir_sep_str () + "built-in-docstrings";
+      else
+        Vbuilt_in_docstrings_file = df;
+    }
+}
+
 void
 install_defaults (void)
 {
@@ -380,6 +434,9 @@
   set_default_local_api_fcn_file_dir ();
   set_default_local_fcn_file_dir ();
 
+  set_default_oct_etc_dir ();
+  set_default_oct_locale_dir ();
+
   set_default_fcn_file_dir ();
   set_default_oct_file_dir ();
 
@@ -393,6 +450,8 @@
 
   set_default_doc_cache_file ();
 
+  set_default_texi_macros_file ();
+
   set_default_info_file ();
 
   set_default_info_prog ();
@@ -402,6 +461,8 @@
   set_local_site_defaults_file ();
 
   set_site_defaults_file ();
+
+  set_built_in_docstrings_file ();
 }
 
 DEFUN (EDITOR, args, nargout,
@@ -425,7 +486,6 @@
 }
 
 /*
-%!error (EDITOR (1, 2));
 %!test
 %! orig_val = EDITOR ();
 %! old_val = EDITOR ("X");
@@ -433,6 +493,8 @@
 %! assert (EDITOR (), "X");
 %! EDITOR (orig_val);
 %! assert (EDITOR (), orig_val);
+
+%!error (EDITOR (1, 2))
 */
 
 DEFUN (EXEC_PATH, args, nargout,
@@ -460,7 +522,6 @@
 }
 
 /*
-%!error (EXEC_PATH (1, 2));
 %!test
 %! orig_val = EXEC_PATH ();
 %! old_val = EXEC_PATH ("X");
@@ -468,6 +529,8 @@
 %! assert (EXEC_PATH (), "X");
 %! EXEC_PATH (orig_val);
 %! assert (EXEC_PATH (), orig_val);
+
+%!error (EXEC_PATH (1, 2))
 */
 
 DEFUN (IMAGE_PATH, args, nargout,
@@ -487,7 +550,6 @@
 }
 
 /*
-%!error (IMAGE_PATH (1, 2));
 %!test
 %! orig_val = IMAGE_PATH ();
 %! old_val = IMAGE_PATH ("X");
@@ -495,6 +557,8 @@
 %! assert (IMAGE_PATH (), "X");
 %! IMAGE_PATH (orig_val);
 %! assert (IMAGE_PATH (), orig_val);
+
+%!error (IMAGE_PATH (1, 2))
 */
 
 DEFUN (OCTAVE_HOME, args, ,
@@ -514,8 +578,8 @@
 }
 
 /*
-%!error OCTAVE_HOME (1);
-%!assert (ischar (OCTAVE_HOME ()));
+%!assert (ischar (OCTAVE_HOME ()))
+%!error OCTAVE_HOME (1)
 */
 
 DEFUNX ("OCTAVE_VERSION", FOCTAVE_VERSION, args, ,
@@ -537,6 +601,6 @@
 }
 
 /*
-%!error OCTAVE_VERSION (1);
-%!assert (ischar (OCTAVE_VERSION ()));
+%!assert (ischar (OCTAVE_VERSION ()))
+%!error OCTAVE_VERSION (1)
 */
rename from src/defaults.h.in
rename to libinterp/interpfcn/defaults.in.h
--- a/src/defaults.h.in
+++ b/libinterp/interpfcn/defaults.in.h
@@ -1,4 +1,4 @@
-// defaults.h.in
+// %NO_EDIT_WARNING%
 /*
 
 Copyright (C) 1993-2012 John W. Eaton
@@ -56,6 +56,10 @@
 #define OCTAVE_DOC_CACHE_FILE %OCTAVE_DOC_CACHE_FILE%
 #endif
 
+#ifndef OCTAVE_TEXI_MACROS_FILE
+#define OCTAVE_TEXI_MACROS_FILE %OCTAVE_TEXI_MACROS_FILE%
+#endif
+
 #ifndef OCTAVE_EXEC_PREFIX
 #define OCTAVE_EXEC_PREFIX %OCTAVE_EXEC_PREFIX%
 #endif
@@ -152,6 +156,10 @@
 #define OCTAVE_OCTETCDIR %OCTAVE_OCTETCDIR%
 #endif
 
+#ifndef OCTAVE_OCTLOCALEDIR
+#define OCTAVE_OCTLOCALEDIR %OCTAVE_OCTLOCALEDIR%
+#endif
+
 #ifndef OCTAVE_OCTINCLUDEDIR
 #define OCTAVE_OCTINCLUDEDIR %OCTAVE_OCTINCLUDEDIR%
 #endif
@@ -160,6 +168,10 @@
 #define OCTAVE_OCTLIBDIR %OCTAVE_OCTLIBDIR%
 #endif
 
+#ifndef OCTAVE_OCTTESTSDIR
+#define OCTAVE_OCTTESTSDIR %OCTAVE_OCTTESTSDIR%
+#endif
+
 #ifndef OCTAVE_PREFIX
 #define OCTAVE_PREFIX %OCTAVE_PREFIX%
 #endif
@@ -172,43 +184,48 @@
 #define OCTAVE_RELEASE %OCTAVE_RELEASE%
 #endif
 
-extern std::string Voctave_home;
+extern OCTINTERP_API std::string Voctave_home;
 
-extern std::string Vbin_dir;
-extern std::string Vinfo_dir;
-extern std::string Vdata_dir;
-extern std::string Vlibexec_dir;
-extern std::string Varch_lib_dir;
-extern std::string Vlocal_arch_lib_dir;
-extern std::string Vlocal_ver_arch_lib_dir;
+extern OCTINTERP_API std::string Vbin_dir;
+extern OCTINTERP_API std::string Vinfo_dir;
+extern OCTINTERP_API std::string Vdata_dir;
+extern OCTINTERP_API std::string Vlibexec_dir;
+extern OCTINTERP_API std::string Varch_lib_dir;
+extern OCTINTERP_API std::string Vlocal_arch_lib_dir;
+extern OCTINTERP_API std::string Vlocal_ver_arch_lib_dir;
 
-extern std::string Vlocal_ver_oct_file_dir;
-extern std::string Vlocal_api_oct_file_dir;
-extern std::string Vlocal_oct_file_dir;
+extern OCTINTERP_API std::string Vlocal_ver_oct_file_dir;
+extern OCTINTERP_API std::string Vlocal_api_oct_file_dir;
+extern OCTINTERP_API std::string Vlocal_oct_file_dir;
+
+extern OCTINTERP_API std::string Vlocal_ver_fcn_file_dir;
+extern OCTINTERP_API std::string Vlocal_api_fcn_file_dir;
+extern OCTINTERP_API std::string Vlocal_fcn_file_dir;
 
-extern std::string Vlocal_ver_fcn_file_dir;
-extern std::string Vlocal_api_fcn_file_dir;
-extern std::string Vlocal_fcn_file_dir;
+extern OCTINTERP_API std::string Voct_etc_dir;
+extern OCTINTERP_API std::string Voct_locale_dir;
 
-extern std::string Voct_file_dir;
-extern std::string Vfcn_file_dir;
+extern OCTINTERP_API std::string Voct_file_dir;
+extern OCTINTERP_API std::string Vfcn_file_dir;
 
-extern std::string Vimage_dir;
+extern OCTINTERP_API std::string Vimage_dir;
 
 // Name of the editor to be invoked by the edit_history command.
-extern std::string VEDITOR;
+extern OCTINTERP_API std::string VEDITOR;
 
-extern std::string Vlocal_site_defaults_file;
-extern std::string Vsite_defaults_file;
+extern OCTINTERP_API std::string Vlocal_site_defaults_file;
+extern OCTINTERP_API std::string Vsite_defaults_file;
+
+extern OCTINTERP_API std::string Vbuilt_in_docstrings_file;
 
 // Name of the FFTW wisdom program.
 extern OCTINTERP_API std::string Vfftw_wisdom_program;
 
-extern std::string subst_octave_home (const std::string&);
+extern OCTINTERP_API std::string subst_octave_home (const std::string&);
 
-extern void install_defaults (void);
+extern OCTINTERP_API void install_defaults (void);
 
-extern void set_exec_path (const std::string& path = std::string ());
-extern void set_image_path (const std::string& path = std::string ());
+extern OCTINTERP_API void set_exec_path (const std::string& path = std::string ());
+extern OCTINTERP_API void set_image_path (const std::string& path = std::string ());
 
 #endif
rename from src/defun.cc
rename to libinterp/interpfcn/defun.cc
--- a/src/defun.cc
+++ b/libinterp/interpfcn/defun.cc
@@ -80,10 +80,10 @@
 
 void
 install_builtin_function (octave_builtin::fcn f, const std::string& name,
-                          const std::string& doc,
+                          const std::string& file, const std::string& doc,
                           bool /* can_hide_function -- not yet implemented */)
 {
-  octave_value fcn (new octave_builtin (f, name, doc));
+  octave_value fcn (new octave_builtin (f, name, file, doc));
 
   symbol_table::install_built_in_function (name, fcn);
 }
@@ -194,7 +194,7 @@
     for (int i = 0; i < nout; i++)
       isargout[i] = true;
 
-  for (int i = std::max(nargout, 1); i < nout; i++)
+  for (int i = std::max (nargout, 1); i < nout; i++)
     isargout[i] = false;
 }
 
rename from src/defun.h
rename to libinterp/interpfcn/defun.h
rename from src/dirfns.cc
rename to libinterp/interpfcn/dirfns.cc
--- a/src/dirfns.cc
+++ b/libinterp/interpfcn/dirfns.cc
@@ -51,6 +51,7 @@
 #include "gripes.h"
 #include "input.h"
 #include "load-path.h"
+#include "octave-link.h"
 #include "oct-obj.h"
 #include "pager.h"
 #include "procstream.h"
@@ -70,16 +71,20 @@
 static int
 octave_change_to_directory (const std::string& newdir)
 {
-  int cd_ok = octave_env::chdir (file_ops::tilde_expand (newdir));
+  std::string xdir = file_ops::tilde_expand (newdir);
+
+  int cd_ok = octave_env::chdir (xdir);
 
   if (cd_ok)
     {
       Vlast_chdir_time.stamp ();
 
-      // FIXME -- should this be handled as a list of functions
+      // FIXME -- should these actions be handled as a list of functions
       // to call so users can add their own chdir handlers?
 
       load_path::update ();
+
+      octave_link::change_directory (octave_env::get_current_directory ());
     }
   else
     error ("%s: %s", newdir.c_str (), gnulib::strerror (errno));
@@ -554,10 +559,11 @@
 them, or an empty cell array if no patterns match.  The pattern strings are\n\
 interpreted as filename globbing patterns (as they are used by Unix shells).\n\
 Within a pattern\n\
+\n\
 @table @code\n\
-@itemx *\n\
+@item *\n\
 matches any string, including the null string,\n\
-@itemx ?\n\
+@item ?\n\
 matches any single character, and\n\
 \n\
 @item [@dots{}]\n\
@@ -570,25 +576,25 @@
 \n\
 @example\n\
 ls\n\
-     @result{}\n\
-        file1  file2  file3  myfile1 myfile1b\n\
+   @result{}\n\
+      file1  file2  file3  myfile1 myfile1b\n\
 glob (\"*file1\")\n\
-     @result{}\n\
-        @{\n\
-          [1,1] = file1\n\
-          [2,1] = myfile1\n\
-        @}\n\
+   @result{}\n\
+      @{\n\
+        [1,1] = file1\n\
+        [2,1] = myfile1\n\
+      @}\n\
 glob (\"myfile?\")\n\
-     @result{}\n\
-        @{\n\
-          [1,1] = myfile1\n\
-        @}\n\
+   @result{}\n\
+      @{\n\
+        [1,1] = myfile1\n\
+      @}\n\
 glob (\"file[12]\")\n\
-     @result{}\n\
-        @{\n\
-          [1,1] = file1\n\
-          [2,1] = file2\n\
-        @}\n\
+   @result{}\n\
+      @{\n\
+        [1,1] = file1\n\
+        [2,1] = file2\n\
+      @}\n\
 @end example\n\
 @seealso{ls, dir, readdir}\n\
 @end deftypefn")
@@ -616,35 +622,34 @@
 
 /*
 %!test
-%!  tmpdir = tmpnam;
-%!  filename = {"file1", "file2", "file3", "myfile1", "myfile1b"};
-%!  if (mkdir (tmpdir))
-%!    cwd = pwd;
-%!    cd (tmpdir);
-%!    if strcmp (canonicalize_file_name (pwd), ...
-%!               canonicalize_file_name (tmpdir))
-%!      a = 0;
-%!      for n = 1:5
-%!        save (filename{n}, "a");
-%!      endfor
-%!    else
-%!      rmdir (tmpdir);
-%!      error ("Couldn't change to temporary dir");
-%!    endif
-%!  else
-%!    error ("Couldn't create temporary directory");
-%!  endif
-%!  result1 = glob ("*file1");
-%!  result2 = glob ("myfile?");
-%!  result3 = glob ("file[12]");
-%!  for n = 1:5
-%!    delete (filename{n});
-%!  endfor
-%!  cd (cwd);
-%!  rmdir (tmpdir);
-%!  assert (result1, {"file1"; "myfile1"});
-%!  assert (result2, {"myfile1"});
-%!  assert (result3, {"file1"; "file2"});
+%! tmpdir = tmpnam;
+%! filename = {"file1", "file2", "file3", "myfile1", "myfile1b"};
+%! if (mkdir (tmpdir))
+%!   cwd = pwd;
+%!   cd (tmpdir);
+%!   if strcmp (canonicalize_file_name (pwd), canonicalize_file_name (tmpdir))
+%!     a = 0;
+%!     for n = 1:5
+%!       save (filename{n}, "a");
+%!     endfor
+%!   else
+%!     rmdir (tmpdir);
+%!     error ("Couldn't change to temporary dir");
+%!   endif
+%! else
+%!   error ("Couldn't create temporary directory");
+%! endif
+%! result1 = glob ("*file1");
+%! result2 = glob ("myfile?");
+%! result3 = glob ("file[12]");
+%! for n = 1:5
+%!   delete (filename{n});
+%! endfor
+%! cd (cwd);
+%! rmdir (tmpdir);
+%! assert (result1, {"file1"; "myfile1"});
+%! assert (result2, {"myfile1"});
+%! assert (result3, {"file1"; "file2"});
 */
 
 DEFUNX ("fnmatch", Ffnmatch, args, ,
@@ -687,10 +692,10 @@
 DEFUN (filesep, args, ,
   "-*- texinfo -*-\n\
 @deftypefn  {Built-in Function} {} filesep ()\n\
-@deftypefnx {Built-in Function} {} filesep ('all')\n\
+@deftypefnx {Built-in Function} {} filesep (\"all\")\n\
 Return the system-dependent character used to separate directory names.\n\
 \n\
-If 'all' is given, the function returns all valid file separators in\n\
+If \"all\" is given, the function returns all valid file separators in\n\
 the form of a string.  The list of file separators is system-dependent.\n\
 It is @samp{/} (forward slash) under UNIX or @w{Mac OS X}, @samp{/} and\n\
 @samp{\\} (forward and backward slashes) under Windows.\n\
rename from src/dirfns.h
rename to libinterp/interpfcn/dirfns.h
--- a/src/dirfns.h
+++ b/libinterp/interpfcn/dirfns.h
@@ -29,11 +29,6 @@
 
 #include "oct-time.h"
 
-extern std::string polite_directory_format (const std::string&);
-extern std::string base_pathname (const std::string&);
-extern std::string make_absolute (const std::string&, const std::string&);
-extern std::string get_working_directory (const std::string&);
-
 // The time we last time we changed directories.
 extern octave_time Vlast_chdir_time;
 
rename from src/error.cc
rename to libinterp/interpfcn/error.cc
--- a/src/error.cc
+++ b/libinterp/interpfcn/error.cc
@@ -764,7 +764,7 @@
 
 static std::string
 handle_message (error_fun f, const char *id, const char *msg,
-                const octave_value_list& args)
+                const octave_value_list& args, bool have_fmt)
 {
   std::string retval;
 
@@ -776,7 +776,7 @@
     {
       octave_value arg;
 
-      if (nargin > 1)
+      if (have_fmt)
         {
           octave_value_list tmp = Fsprintf (args, 1);
           arg = tmp(0);
@@ -838,7 +838,7 @@
 @end deftypefn")
 {
   octave_value retval;
-  int nargin = args.length();
+  int nargin = args.length ();
 
   if (nargin != 1)
     print_usage ();
@@ -850,9 +850,9 @@
         {
           if (err.contains ("message") && err.contains ("identifier"))
             {
-              std::string msg = err.contents("message").string_value ();
-              std::string id = err.contents("identifier").string_value ();
-              int len = msg.length();
+              std::string msg = err.contents ("message").string_value ();
+              std::string id = err.contents ("identifier").string_value ();
+              int len = msg.length ();
 
               std::string file;
               std::string nm;
@@ -863,21 +863,21 @@
 
               if (err.contains ("stack"))
                 {
-                  err_stack = err.contents("stack").map_value ();
+                  err_stack = err.contents ("stack").map_value ();
 
                   if (err_stack.numel () > 0)
                     {
                       if (err_stack.contains ("file"))
-                        file = err_stack.contents("file")(0).string_value ();
+                        file = err_stack.contents ("file")(0).string_value ();
 
                       if (err_stack.contains ("name"))
-                        nm = err_stack.contents("name")(0).string_value ();
+                        nm = err_stack.contents ("name")(0).string_value ();
 
                       if (err_stack.contains ("line"))
-                        l = err_stack.contents("line")(0).nint_value ();
+                        l = err_stack.contents ("line")(0).nint_value ();
 
                       if (err_stack.contains ("column"))
-                        c = err_stack.contents("column")(0).nint_value ();
+                        c = err_stack.contents ("column")(0).nint_value ();
                     }
                 }
 
@@ -962,6 +962,57 @@
   return retval;
 }
 
+// Determine whether the first argument to error or warning function
+// should be handled as the message identifier or as the format string.
+
+static bool
+maybe_extract_message_id (const std::string& caller,
+                          const octave_value_list& args,
+                          octave_value_list& nargs,
+                          std::string& id)
+{
+  nargs = args;
+  id = std::string ();
+
+  int nargin = args.length ();
+
+  bool have_fmt = nargin > 1;
+
+  if (nargin > 0)
+    {
+      std::string arg1 = args(0).string_value ();
+
+      if (! error_state)
+        {
+          // For compatibility with Matlab, an identifier must contain
+          // ':', but not at the beginning or the end, and it must not
+          // contain '%' (even if it is not a valid conversion
+          // operator) or whitespace.
+
+          if (arg1.find_first_of ("% \f\n\r\t\v") == std::string::npos
+              && arg1.find (':') != std::string::npos
+              && arg1[0] != ':'
+              && arg1[arg1.length ()-1] != ':')
+            {
+              if (nargin > 1)
+                {
+                  id = arg1;
+
+                  nargs.resize (nargin-1);
+
+                  for (int i = 1; i < nargin; i++)
+                    nargs(i-1) = args(i);
+                }
+              else
+                nargs(0) = "call to " + caller
+                  + " with message identifier requires message";
+            }
+        }
+    }
+
+  return have_fmt;
+}
+
 DEFUN (error, args, ,
   "-*- texinfo -*-\n\
 @deftypefn  {Built-in Function} {} error (@var{template}, @dots{})\n\
@@ -1017,6 +1068,14 @@
 error: nargin != 1\n\
 @end group\n\
 @end example\n\
+\n\
+Implementation Note: For compatibility with @sc{matlab}, escape\n\
+sequences (e.g., \"\\n\" => newline) are processed in @var{template}\n\
+regardless of whether @var{template} has been defined within single quotes\n\
+as long as there are two or more input arguments.\n\
+Use a second backslash to stop interpolation of the escape sequence (e.g.,\n\
+\"\\\\n\") or use the @code{regexptranslate} function.\n\
+@seealso{warning, lasterror}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -1031,26 +1090,9 @@
     print_usage ();
   else
     {
-      if (nargin > 1)
-        {
-          std::string arg1 = args(0).string_value ();
-
-          if (! error_state)
-            {
-              if (arg1.find ('%') == std::string::npos)
-                {
-                  id = arg1;
+      bool have_fmt = false;
 
-                  nargs.resize (nargin-1);
-
-                  for (int i = 1; i < nargin; i++)
-                    nargs(i-1) = args(i);
-                }
-            }
-          else
-            return retval;
-        }
-      else if (nargin == 1 && args(0).is_map ())
+      if (nargin == 1 && args(0).is_map ())
         {
           // empty struct is not an error.  return and resume calling function.
           if (args(0).is_empty ())
@@ -1084,13 +1126,74 @@
           // structure, but that will require some more significant
           // surgery on handle_message, error_with_id, etc.
         }
+      else
+        {
+          have_fmt = maybe_extract_message_id ("error", args, nargs, id);
 
-      handle_message (error_with_id, id.c_str (), "unspecified error", nargs);
+          if (error_state)
+            return retval;
+        }
+
+      handle_message (error_with_id, id.c_str (), "unspecified error",
+                      nargs, have_fmt);
     }
 
   return retval;
 }
 
+static octave_scalar_map
+warning_query (const std::string& id_arg)
+{
+  octave_scalar_map retval;
+
+  std::string id = id_arg;
+
+  if (id == "last")
+    id = Vlast_warning_id;
+
+  Cell ident = warning_options.contents ("identifier");
+  Cell state = warning_options.contents ("state");
+
+  octave_idx_type nel = ident.numel ();
+
+  bool found = false;
+
+  std::string val;
+
+  for (octave_idx_type i = 0; i < nel; i++)
+    {
+      if (ident(i).string_value () == id)
+        {
+          val = state(i).string_value ();
+          found = true;
+          break;
+        }
+    }
+
+  if (! found)
+    {
+      for (octave_idx_type i = 0; i < nel; i++)
+        {
+          if (ident(i).string_value () == "all")
+            {
+              val = state(i).string_value ();
+              found = true;
+              break;
+            }
+        }
+    }
+
+  if (found)
+    {
+      retval.assign ("identifier", id);
+      retval.assign ("state", val);
+    }
+  else
+    error ("warning: unable to find default warning state!");
+
+  return retval;
+}
+
 DEFUN (warning, args, nargout,
   "-*- texinfo -*-\n\
 @deftypefn  {Built-in Function} {} warning (@var{template}, @dots{})\n\
@@ -1099,6 +1202,7 @@
 @deftypefnx {Built-in Function} {} warning (\"off\", @var{id})\n\
 @deftypefnx {Built-in Function} {} warning (\"query\", @var{id})\n\
 @deftypefnx {Built-in Function} {} warning (\"error\", @var{id})\n\
+@deftypefnx {Built-in Function} {} warning (@var{state}, @var{id}, \"local\")\n\
 Format the optional arguments under the control of the template string\n\
 @var{template} using the same rules as the @code{printf} family of\n\
 functions (@pxref{Formatted Output}) and print the resulting message\n\
@@ -1127,7 +1231,23 @@
 warning (\"error\");\n\
 @end group\n\
 @end example\n\
-@seealso{warning_ids}\n\
+\n\
+If the state is @samp{\"on\"}, @samp{\"off\"}, or @samp{\"error\"}\n\
+and the third argument is @samp{\"local\"}, then the warning state\n\
+will be set temporarily, until the end of the current function.\n\
+Changes to warning states that are set locally affect the current\n\
+function and all functions called from the current scope.  The\n\
+previous warning state is restored on return from the current\n\
+function.  The \"local\" option is ignored if used in the top-level\n\
+workspace.\n\
+\n\
+Implementation Note: For compatibility with @sc{matlab}, escape\n\
+sequences (e.g., \"\\n\" => newline) are processed in @var{template}\n\
+regardless of whether @var{template} has been defined within single quotes\n\
+as long as there are two or more input arguments.\n\
+Use a second backslash to stop interpolation of the escape sequence (e.g.,\n\
+\"\\\\n\") or use the @code{regexptranslate} function.\n\
+@seealso{warning_ids, lastwarn, error}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -1146,13 +1266,93 @@
           std::string arg1 = argv(1);
           std::string arg2 = "all";
 
-          if (argc == 3)
+          if (argc >= 3)
             arg2 = argv(2);
 
           if (arg1 == "on" || arg1 == "off" || arg1 == "error")
             {
               octave_map old_warning_options = warning_options;
 
+              if (argc == 4 && argv(3) == "local"
+                  && ! symbol_table::at_top_level ())
+                {
+                  symbol_table::scope_id scope
+                    = octave_call_stack::current_scope ();
+
+                  symbol_table::context_id context
+                    = octave_call_stack::current_context ();
+
+                  octave_scalar_map val = warning_query (arg2);
+
+                  octave_value curr_state = val.contents ("state");
+
+                  // FIXME -- this might be better with a dictionary
+                  // object.
+
+                  octave_value curr_warning_states
+                    = symbol_table::varval (".saved_warning_states.",
+                                            scope, context);
+
+                  octave_map m;
+
+                  if (curr_warning_states.is_defined ())
+                    m = curr_warning_states.map_value ();
+                  else
+                    {
+                      string_vector fields (2);
+
+                      fields(0) = "identifier";
+                      fields(1) = "state";
+
+                      m = octave_map (dim_vector (0, 1), fields);
+                    }
+
+                  if (error_state)
+                    panic_impossible ();
+
+                  Cell ids = m.contents ("identifier");
+                  Cell states = m.contents ("state");
+
+                  octave_idx_type nel = states.numel ();
+                  bool found = false;
+                  octave_idx_type i;
+                  for (i = 0; i < nel; i++)
+                    {
+                      std::string id = ids(i).string_value ();
+
+                      if (error_state)
+                        panic_impossible ();
+
+                      if (id == arg2)
+                        {
+                          states(i) = curr_state;
+                          found = true;
+                          break;
+                        }
+                    }
+
+                  if (! found)
+                    {
+                      m.resize (dim_vector (nel+1, 1));
+
+                      ids.resize (dim_vector (nel+1, 1));
+                      states.resize (dim_vector (nel+1, 1));
+
+                      ids(nel) = arg2;
+                      states(nel) = curr_state;
+                    }
+
+                  m.contents ("identifier") = ids;
+                  m.contents ("state") = states;
+
+                  symbol_table::assign
+                    (".saved_warning_states.", m, scope, context);
+
+                  // Now ignore the "local" argument and continue to
+                  // handle the current setting.
+                  argc--;
+                }
+                  
               if (arg2 == "all")
                 {
                   octave_map tmp;
@@ -1314,54 +1514,7 @@
                   retval = tmp;
                 }
               else
-                {
-                  if (arg2 == "last")
-                    arg2 = Vlast_warning_id;
-
-                  Cell ident = warning_options.contents ("identifier");
-                  Cell state = warning_options.contents ("state");
-
-                  octave_idx_type nel = ident.numel ();
-
-                  bool found = false;
-
-                  std::string val;
-
-                  for (octave_idx_type i = 0; i < nel; i++)
-                    {
-                      if (ident(i).string_value () == arg2)
-                        {
-                          val = state(i).string_value ();
-                          found = true;
-                          break;
-                        }
-                    }
-
-                  if (! found)
-                    {
-                      for (octave_idx_type i = 0; i < nel; i++)
-                        {
-                          if (ident(i).string_value () == "all")
-                            {
-                              val = state(i).string_value ();
-                              found = true;
-                              break;
-                            }
-                        }
-                    }
-
-                  if (found)
-                    {
-                      octave_scalar_map tmp;
-
-                      tmp.assign ("identifier", arg2);
-                      tmp.assign ("state", val);
-
-                      retval = tmp;
-                    }
-                  else
-                    error ("warning: unable to find default warning state!");
-                }
+                retval = warning_query (arg2);
 
               done = true;
             }
@@ -1401,30 +1554,16 @@
 
       std::string id;
 
-      if (nargin > 1)
-        {
-          std::string arg1 = args(0).string_value ();
-
-          if (! error_state)
-            {
-              if (arg1.find ('%') == std::string::npos)
-                {
-                  id = arg1;
+      bool have_fmt = maybe_extract_message_id ("warning", args, nargs, id);
 
-                  nargs.resize (nargin-1);
-
-                  for (int i = 1; i < nargin; i++)
-                    nargs(i-1) = args(i);
-                }
-            }
-          else
-            return retval;
-        }
+      if (error_state)
+        return retval;
 
       std::string prev_msg = Vlast_warning_message;
 
       std::string curr_msg = handle_message (warning_with_id, id.c_str (),
-                                             "unspecified warning", nargs);
+                                             "unspecified warning", nargs,
+                                             have_fmt);
 
       if (nargout > 0)
         retval = prev_msg;
@@ -1489,7 +1628,7 @@
   "-*- texinfo -*-\n\
 @deftypefn  {Built-in Function} {@var{lasterr} =} lasterror ()\n\
 @deftypefnx {Built-in Function} {} lasterror (@var{err})\n\
-@deftypefnx {Built-in Function} {} lasterror ('reset')\n\
+@deftypefnx {Built-in Function} {} lasterror (\"reset\")\n\
 Query or set the last error message structure.  When called without\n\
 arguments, return a structure containing the last error message and other\n\
 information related to this error.  The elements of the structure are:\n\
@@ -1525,13 +1664,13 @@
 as input.  Any fields of @var{err} that match those above are set while any\n\
 unspecified fields are initialized with default values.\n\
 \n\
-If @code{lasterror} is called with the argument 'reset', all fields are\n\
+If @code{lasterror} is called with the argument \"reset\", all fields are\n\
 set to their default values.\n\
-@seealso{lasterr}\n\
+@seealso{lasterr, error, lastwarn}\n\
 @end deftypefn")
 {
   octave_value retval;
-  int nargin = args.length();
+  int nargin = args.length ();
 
   unwind_protect frame;
 
@@ -1549,21 +1688,22 @@
 
       if (nargin == 1)
         {
-          if (args(0).is_string())
+          if (args(0).is_string ())
             {
               if (args(0).string_value () == "reset")
                 {
-                  Vlast_error_message = std::string();
-                  Vlast_error_id = std::string();
+                  Vlast_error_message = std::string ();
+                  Vlast_error_id = std::string ();
 
                   Vlast_error_stack = initialize_last_error_stack ();
                 }
               else
-                error("lasterror: unrecognized string argument");
+                error ("lasterror: unrecognized string argument");
             }
           else if (args(0).is_map ())
             {
               octave_scalar_map new_err = args(0).scalar_map_value ();
+              octave_scalar_map new_err_stack;
               std::string new_error_message;
               std::string new_error_id;
               std::string new_error_file;
@@ -1574,47 +1714,47 @@
               if (! error_state && new_err.contains ("message"))
                 {
                   const std::string tmp =
-                    new_err.getfield("message").string_value ();
+                    new_err.getfield ("message").string_value ();
                   new_error_message = tmp;
                 }
 
               if (! error_state && new_err.contains ("identifier"))
                 {
                   const std::string tmp =
-                    new_err.getfield("identifier").string_value ();
+                    new_err.getfield ("identifier").string_value ();
                   new_error_id = tmp;
                 }
 
               if (! error_state && new_err.contains ("stack"))
                 {
-                  octave_scalar_map new_err_stack =
-                    new_err.getfield("stack").scalar_map_value ();
+                  new_err_stack = 
+                    new_err.getfield ("stack").scalar_map_value ();
 
                   if (! error_state && new_err_stack.contains ("file"))
                     {
                       const std::string tmp =
-                        new_err_stack.getfield("file").string_value ();
+                        new_err_stack.getfield ("file").string_value ();
                       new_error_file = tmp;
                     }
 
                   if (! error_state && new_err_stack.contains ("name"))
                     {
                       const std::string tmp =
-                        new_err_stack.getfield("name").string_value ();
+                        new_err_stack.getfield ("name").string_value ();
                       new_error_name = tmp;
                     }
 
                   if (! error_state && new_err_stack.contains ("line"))
                     {
                       const int tmp =
-                        new_err_stack.getfield("line").nint_value ();
+                        new_err_stack.getfield ("line").nint_value ();
                       new_error_line = tmp;
                     }
 
                   if (! error_state && new_err_stack.contains ("column"))
                     {
                       const int tmp =
-                        new_err_stack.getfield("column").nint_value ();
+                        new_err_stack.getfield ("column").nint_value ();
                       new_error_column = tmp;
                     }
                 }
@@ -1624,10 +1764,22 @@
                   Vlast_error_message = new_error_message;
                   Vlast_error_id = new_error_id;
 
-                  octave_idx_type curr_frame = -1;
+                  if (new_err.contains ("stack"))
+                    {
+                      new_err_stack.setfield ("file", new_error_file);
+                      new_err_stack.setfield ("name", new_error_name);
+                      new_err_stack.setfield ("line", new_error_line);
+                      new_err_stack.setfield ("column", new_error_column);
+                      Vlast_error_stack = new_err_stack;
+                    }
+                  else
+                    {
+                      // No stack field.  Fill it in with backtrace info.
+                      octave_idx_type curr_frame = -1;
 
-                  Vlast_error_stack
-                    = octave_call_stack::backtrace (0, curr_frame);
+                      Vlast_error_stack
+                        = octave_call_stack::backtrace (0, curr_frame);
+                    }
                 }
             }
           else
@@ -1652,7 +1804,7 @@
 return the last error message and message identifier.  With one\n\
 argument, set the last error message to @var{msg}.  With two arguments,\n\
 also set the last message identifier.\n\
-@seealso{lasterror}\n\
+@seealso{lasterror, error, lastwarn}\n\
 @end deftypefn")
 {
   octave_value_list retval;
@@ -1696,10 +1848,14 @@
 
 DEFUN (lastwarn, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {[@var{msg}, @var{msgid}] =} lastwarn (@var{msg}, @var{msgid})\n\
-Without any arguments, return the last warning message.  With one\n\
+@deftypefn  {Built-in Function} {[@var{msg}, @var{msgid}] =} lastwarn ()\n\
+@deftypefnx {Built-in Function} {} lastwarn (@var{msg})\n\
+@deftypefnx {Built-in Function} {} lastwarn (@var{msg}, @var{msgid})\n\
+Query or set the last warning message.  When called without input arguments,\n\
+return the last warning message and message identifier.  With one\n\
 argument, set the last warning message to @var{msg}.  With two arguments,\n\
 also set the last message identifier.\n\
+@seealso{warning, lasterror, lasterr}\n\
 @end deftypefn")
 {
   octave_value_list retval;
@@ -1767,7 +1923,7 @@
 @end deftypefn")
 {
   octave_value_list retval;
-  handle_message (usage_with_id, "", "unknown", args);
+  handle_message (usage_with_id, "", "unknown", args, true);
   return retval;
 }
 
rename from src/error.h
rename to libinterp/interpfcn/error.h
rename from src/file-io.cc
rename to libinterp/interpfcn/file-io.cc
--- a/src/file-io.cc
+++ b/libinterp/interpfcn/file-io.cc
@@ -39,10 +39,10 @@
 #endif
 
 #include <cerrno>
-#include <climits>
 #include <cstdio>
 
 #include <iostream>
+#include <limits>
 #include <stack>
 #include <vector>
 
@@ -130,26 +130,25 @@
     }
 }
 
-static std::ios::openmode
-fopen_mode_to_ios_mode (const std::string& mode_arg)
+static void
+normalize_fopen_mode (std::string& mode, bool& use_zlib)
 {
-  std::ios::openmode retval = std::ios::in;
+  use_zlib = false;
 
-  if (! mode_arg.empty ())
+  if (! mode.empty ())
     {
       // Could probably be faster, but does it really matter?
 
-      std::string mode = mode_arg;
-
-      // 'W' and 'R' are accepted as 'w' and 'r', but we warn about
-      // them because Matlab says they perform "automatic flushing"
-      // but we don't know precisely what action that implies.
+      // Accept 'W', 'R', and 'A' as 'w', 'r', and 'a' but we warn about
+      // them because Matlab says they don't perform "automatic
+      // flushing" but we don't know precisely what action that implies.
 
       size_t pos = mode.find ('W');
 
       if (pos != std::string::npos)
         {
-          warning ("fopen: treating mode \"W\" as equivalent to \"w\"");
+          warning_with_id ("Octave:fopen-mode",
+                           "fopen: treating mode \"W\" as equivalent to \"w\"");
           mode[pos] = 'w';
         }
 
@@ -157,15 +156,26 @@
 
       if (pos != std::string::npos)
         {
-          warning ("fopen: treating mode \"R\" as equivalent to \"r\"");
+          warning_with_id ("Octave:fopen-mode",
+                           "fopen: treating mode \"R\" as equivalent to \"r\"");
           mode[pos] = 'r';
         }
 
+      pos = mode.find ('A');
+
+      if (pos != std::string::npos)
+        {
+          warning_with_id ("Octave:fopen-mode",
+                           "fopen: treating mode \"A\" as equivalent to \"a\"");
+          mode[pos] = 'a';
+        }
+
       pos = mode.find ('z');
 
       if (pos != std::string::npos)
         {
 #if defined (HAVE_ZLIB)
+          use_zlib = true;
           mode.erase (pos, 1);
 #else
           error ("this version of Octave does not support gzipped files");
@@ -174,36 +184,54 @@
 
       if (! error_state)
         {
-          if (mode == "rt")
-            retval = std::ios::in;
-          else if (mode == "wt")
-            retval = std::ios::out | std::ios::trunc;
-          else if (mode == "at")
-            retval = std::ios::out | std::ios::app;
-          else if (mode == "r+t" || mode == "rt+")
-            retval = std::ios::in | std::ios::out;
-          else if (mode == "w+t" || mode == "wt+")
-            retval = std::ios::in | std::ios::out | std::ios::trunc;
-          else if (mode == "a+t" || mode == "at+")
-            retval = std::ios::in | std::ios::out | std::ios::app;
-          else if (mode == "rb" || mode == "r")
-            retval = std::ios::in | std::ios::binary;
-          else if (mode == "wb" || mode == "w")
-            retval = std::ios::out | std::ios::trunc | std::ios::binary;
-          else if (mode == "ab" || mode == "a")
-            retval = std::ios::out | std::ios::app | std::ios::binary;
-          else if (mode == "r+b" || mode == "rb+" || mode == "r+")
-            retval = std::ios::in | std::ios::out | std::ios::binary;
-          else if (mode == "w+b" || mode == "wb+" || mode == "w+")
-            retval = (std::ios::in | std::ios::out | std::ios::trunc
-                      | std::ios::binary);
-          else if (mode == "a+b" || mode == "ab+" || mode == "a+")
-            retval = (std::ios::in | std::ios::out | std::ios::app
-                      | std::ios::binary);
-          else
-            ::error ("invalid mode specified");
+          // Use binary mode if 't' is not specified, but don't add
+          // 'b' if it is already present.
+
+          size_t bpos = mode.find ('b');
+          size_t tpos = mode.find ('t');
+
+          if (bpos == std::string::npos && tpos == std::string::npos)
+            mode += 'b';
         }
     }
+}
+
+static std::ios::openmode
+fopen_mode_to_ios_mode (const std::string& mode)
+{
+  std::ios::openmode retval = std::ios::in;
+
+  if (! error_state)
+    {
+      if (mode == "rt")
+        retval = std::ios::in;
+      else if (mode == "wt")
+        retval = std::ios::out | std::ios::trunc;
+      else if (mode == "at")
+        retval = std::ios::out | std::ios::app;
+      else if (mode == "r+t" || mode == "rt+")
+        retval = std::ios::in | std::ios::out;
+      else if (mode == "w+t" || mode == "wt+")
+        retval = std::ios::in | std::ios::out | std::ios::trunc;
+      else if (mode == "a+t" || mode == "at+")
+        retval = std::ios::in | std::ios::out | std::ios::app;
+      else if (mode == "rb" || mode == "r")
+        retval = std::ios::in | std::ios::binary;
+      else if (mode == "wb" || mode == "w")
+        retval = std::ios::out | std::ios::trunc | std::ios::binary;
+      else if (mode == "ab" || mode == "a")
+        retval = std::ios::out | std::ios::app | std::ios::binary;
+      else if (mode == "r+b" || mode == "rb+" || mode == "r+")
+        retval = std::ios::in | std::ios::out | std::ios::binary;
+      else if (mode == "w+b" || mode == "wb+" || mode == "w+")
+        retval = (std::ios::in | std::ios::out | std::ios::trunc
+                  | std::ios::binary);
+      else if (mode == "a+b" || mode == "ab+" || mode == "a+")
+        retval = (std::ios::in | std::ios::out | std::ios::app
+                  | std::ios::binary);
+      else
+        ::error ("invalid mode specified");
+    }
 
   return retval;
 }
@@ -215,7 +243,7 @@
 Close the specified file.  If successful, @code{fclose} returns 0,\n\
 otherwise, it returns -1.  The second form of the @code{fclose} call closes\n\
 all open files except @code{stdout}, @code{stderr}, and @code{stdin}.\n\
-@seealso{fopen, fseek, ftell}\n\
+@seealso{fopen, freport}\n\
 @end deftypefn")
 {
   octave_value retval = -1;
@@ -234,6 +262,7 @@
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} fclear (@var{fid})\n\
 Clear the stream state for the specified file.\n\
+@seealso{fopen}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -300,7 +329,8 @@
 
 DEFUN (fgetl, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {} fgetl (@var{fid}, @var{len})\n\
+@deftypefn  {Built-in Function} {@var{str} =} fgetl (@var{fid})\n\
+@deftypefnx {Built-in Function} {@var{str} =} fgetl (@var{fid}, @var{len})\n\
 Read characters from a file, stopping after a newline, or EOF,\n\
 or @var{len} characters have been read.  The characters read, excluding\n\
 the possible trailing newline, are returned as a string.\n\
@@ -309,7 +339,9 @@
 character.\n\
 \n\
 If there are no more characters to read, @code{fgetl} returns @minus{}1.\n\
-@seealso{fread, fscanf}\n\
+\n\
+To read a line and return the terminating newline see @code{fgets}.\n\
+@seealso{fgets, fscanf, fread, fopen}\n\
 @end deftypefn")
 {
   static std::string who = "fgetl";
@@ -348,8 +380,8 @@
 
 DEFUN (fgets, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Built-in Function} {} fgets (@var{fid})\n\
-@deftypefnx {Built-in Function} {} fgets (@var{fid}, @var{len})\n\
+@deftypefn  {Built-in Function} {@var{str} =} fgets (@var{fid})\n\
+@deftypefnx {Built-in Function} {@var{str} =} fgets (@var{fid}, @var{len})\n\
 Read characters from a file, stopping after a newline, or EOF,\n\
 or @var{len} characters have been read.  The characters read, including\n\
 the possible trailing newline, are returned as a string.\n\
@@ -358,7 +390,9 @@
 character.\n\
 \n\
 If there are no more characters to read, @code{fgets} returns @minus{}1.\n\
-@seealso{fputs, fopen, fread, fscanf}\n\
+\n\
+To read a line and discard the terminating newline see @code{fgetl}.\n\
+@seealso{fputs, fgetl, fscanf, fread, fopen}\n\
 @end deftypefn")
 {
   static std::string who = "fgets";
@@ -397,14 +431,19 @@
 
 DEFUN (fskipl, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {} fskipl (@var{fid}, @var{count})\n\
-Skip a given number of lines, i.e., discards characters until an end-of-line\n\
-is met exactly @var{count}-times, or end-of-file occurs.\n\
+@deftypefn  {Built-in Function} {@var{nlines} =} fskipl (@var{fid})\n\
+@deftypefnx {Built-in Function} {@var{nlines} =} fskipl (@var{fid}, @var{count})\n\
+@deftypefnx {Built-in Function} {@var{nlines} =} fskipl (@var{fid}, Inf)\n\
+Read and skip @var{count} lines from the file descriptor @var{fid}.\n\
+@code{fskipl} discards characters until an end-of-line is encountered exactly\n\
+@var{count}-times, or until the end-of-file marker is found.\n\
+\n\
+If @var{count} is omitted, it defaults to 1.  @var{count} may also be\n\
+@code{Inf}, in which case lines are skipped until the end of the file.\n\
+This form is suitable for counting the number of lines in a file.\n\
+\n\
 Returns the number of lines skipped (end-of-line sequences encountered).\n\
-If @var{count} is omitted, it defaults to 1. @var{count} may also be\n\
-@code{Inf}, in which case lines are skipped to the end of file.\n\
-This form is suitable for counting lines in a file.\n\
-@seealso{fgetl, fgets}\n\
+@seealso{fgetl, fgets, fscanf, fopen}\n\
 @end deftypefn")
 {
   static std::string who = "fskipl";
@@ -423,7 +462,7 @@
 
           bool err = false;
 
-          long tmp = os.skipl (count_arg, err, who);
+          off_t tmp = os.skipl (count_arg, err, who);
 
           if (! (error_state || err))
             retval = tmp;
@@ -437,13 +476,17 @@
 
 
 static octave_stream
-do_stream_open (const std::string& name, const std::string& mode,
+do_stream_open (const std::string& name, const std::string& mode_arg,
                 const std::string& arch, int& fid)
 {
   octave_stream retval;
 
   fid = -1;
 
+  std::string mode = mode_arg;
+  bool use_zlib = false;
+  normalize_fopen_mode (mode, use_zlib);
+
   std::ios::openmode md = fopen_mode_to_ios_mode (mode);
 
   if (! error_state)
@@ -477,29 +520,14 @@
 
           if (! fs.is_dir ())
             {
-              std::string tmode = mode;
-
-              // Use binary mode if 't' is not specified, but don't add
-              // 'b' if it is already present.
-
-              size_t bpos = tmode.find ('b');
-              size_t tpos = tmode.find ('t');
-
-              if (bpos == std::string::npos && tpos == std::string::npos)
-                tmode += 'b';
-
 #if defined (HAVE_ZLIB)
-              size_t pos = tmode.find ('z');
-
-              if (pos != std::string::npos)
+              if (use_zlib)
                 {
-                  tmode.erase (pos, 1);
-
-                  FILE *fptr = gnulib::fopen (fname.c_str (), tmode.c_str ());
+                  FILE *fptr = gnulib::fopen (fname.c_str (), mode.c_str ());
 
                   int fd = fileno (fptr);
 
-                  gzFile gzf = ::gzdopen (fd, tmode.c_str ());
+                  gzFile gzf = ::gzdopen (fd, mode.c_str ());
 
                   if (fptr)
                     retval = octave_zstdiostream::create (fname, gzf, fd,
@@ -510,7 +538,7 @@
               else
 #endif
                 {
-                  FILE *fptr = gnulib::fopen (fname.c_str (), tmode.c_str ());
+                  FILE *fptr = gnulib::fopen (fname.c_str (), mode.c_str ());
 
                   retval = octave_stdiostream::create (fname, fptr, md, flt_fmt);
 
@@ -633,30 +661,30 @@
 The parameter @var{arch} is a string specifying the default data format\n\
 for the file.  Valid values for @var{arch} are:\n\
 \n\
-@table @asis\n\
-@samp{native}\n\
+@table @samp\n\
+@item native\n\
 The format of the current machine (this is the default).\n\
 \n\
-@samp{ieee-be}\n\
+@item ieee-be\n\
 IEEE big endian format.\n\
 \n\
-@samp{ieee-le}\n\
+@item ieee-le\n\
 IEEE little endian format.\n\
 \n\
-@samp{vaxd}\n\
+@item vaxd\n\
 VAX D floating format.\n\
 \n\
-@samp{vaxg}\n\
+@item vaxg\n\
 VAX G floating format.\n\
 \n\
-@samp{cray}\n\
+@item cray\n\
 Cray floating format.\n\
 @end table\n\
 \n\
 @noindent\n\
 however, conversions are currently only supported for @samp{native}\n\
 @samp{ieee-be}, and @samp{ieee-le} formats.\n\
-@seealso{fclose, fgets, fputs, fread, fseek, ferror, fprintf, fscanf, ftell, fwrite}\n\
+@seealso{fclose, fgets, fgetl, fscanf, fread, fputs, fdisp, fprintf, fwrite, fskipl, fseek, frewind, ftell, feof, ferror, fclear, fflush, freport}\n\
 @end deftypefn")
 {
   octave_value_list retval;
@@ -741,6 +769,7 @@
      @print{}       3     r  myfile\n\
 @end group\n\
 @end example\n\
+@seealso{fopen, fclose}\n\
 @end deftypefn")
 {
   octave_value_list retval;
@@ -761,6 +790,7 @@
 Move the file pointer to the beginning of the file @var{fid}, returning\n\
 0 for success, and -1 if an error was encountered.  It is equivalent to\n\
 @code{fseek (@var{fid}, 0, SEEK_SET)}.\n\
+@seealso{fseek, ftell, fopen}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -787,18 +817,19 @@
 
 DEFUN (fseek, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {} fseek (@var{fid}, @var{offset}, @var{origin})\n\
+@deftypefn  {Built-in Function} {} fseek (@var{fid}, @var{offset})\n\
+@deftypefnx {Built-in Function} {} fseek (@var{fid}, @var{offset}, @var{origin})\n\
+@deftypefnx {Built-in Function} {@var{status} =} fseek (@dots{})\n\
 Set the file pointer to any location within the file @var{fid}.\n\
 \n\
 The pointer is positioned @var{offset} characters from the @var{origin},\n\
 which may be one of the predefined variables @w{@code{SEEK_CUR}} (current\n\
 position), @w{@code{SEEK_SET}} (beginning), or @w{@code{SEEK_END}} (end of\n\
 file) or strings \"cof\", \"bof\" or \"eof\".  If @var{origin} is omitted,\n\
-@w{@code{SEEK_SET}} is assumed.  The offset must be zero, or a value returned\n\
-by @code{ftell} (in which case @var{origin} must be @w{@code{SEEK_SET}}).\n\
+@w{@code{SEEK_SET}} is assumed.  @var{offset} may be positive, negative, or zero but not all combinations of @var{origin} and @var{offset} can be realized.\n\
 \n\
 Return 0 on success and -1 on error.\n\
-@seealso{ftell, fopen, fclose}\n\
+@seealso{fskipl, frewind, ftell, fopen}\n\
 @end deftypefn")
 {
   octave_value retval = -1;
@@ -828,7 +859,7 @@
 @deftypefn {Built-in Function} {} ftell (@var{fid})\n\
 Return the position of the file pointer as the number of characters\n\
 from the beginning of the file @var{fid}.\n\
-@seealso{fseek, fopen, fclose}\n\
+@seealso{fseek, feof, fopen}\n\
 @end deftypefn")
 {
   octave_value retval = -1;
@@ -854,7 +885,7 @@
 This function is just like @code{printf}, except that the output is\n\
 written to the stream @var{fid} instead of @code{stdout}.\n\
 If @var{fid} is omitted, the output is written to @code{stdout}.\n\
-@seealso{printf, sprintf, fread, fscanf, fopen, fclose}\n\
+@seealso{fputs, fdisp, fwrite, fscanf, printf, sprintf, fopen}\n\
 @end deftypefn")
 {
   static std::string who = "fprintf";
@@ -965,7 +996,7 @@
 Write a string to a file with no formatting.\n\
 \n\
 Return a non-negative number on success and EOF on error.\n\
-@seealso{scanf, sscanf, fread, fprintf, fgets, fscanf}\n\
+@seealso{fdisp, fprintf, fwrite, fopen}\n\
 @end deftypefn")
 {
   static std::string who = "fputs";
@@ -993,6 +1024,7 @@
 Write a string to the standard output with no formatting.\n\
 \n\
 Return a non-negative number on success and EOF on error.\n\
+@seealso{fputs, disp}\n\
 @end deftypefn")
 {
   static std::string who = "puts";
@@ -1115,7 +1147,7 @@
 See the Formatted Input section of the GNU Octave manual for a\n\
 complete description of the syntax of the template string.\n\
 @end ifclear\n\
-@seealso{scanf, sscanf, fread, fprintf, fgets, fputs}\n\
+@seealso{fgets, fgetl, fread, scanf, sscanf, fopen}\n\
 @end deftypefn")
 {
   static std::string who = "fscanf";
@@ -1546,7 +1578,7 @@
 \n\
 The data read from the file is returned in @var{val}, and the number of\n\
 values read is returned in @code{count}\n\
-@seealso{fwrite, fopen, fclose}\n\
+@seealso{fwrite, fgets, fgetl, fscanf, fopen}\n\
 @end deftypefn")
 {
   octave_value_list retval;
@@ -1663,7 +1695,7 @@
 \n\
 The behavior of @code{fwrite} is undefined if the values in @var{data}\n\
 are too large to fit in the specified precision.\n\
-@seealso{fread, fopen, fclose}\n\
+@seealso{fread, fputs, fprintf, fopen}\n\
 @end deftypefn")
 {
   octave_value retval = -1;
@@ -1716,7 +1748,7 @@
 file and 0 otherwise.  Note that it will only return 1 if the end of the\n\
 file has already been encountered, not if the next read operation will\n\
 result in an end-of-file condition.\n\
-@seealso{fread, fopen, fclose}\n\
+@seealso{fread, fopen}\n\
 @end deftypefn")
 {
   octave_value retval = -1;
@@ -1738,7 +1770,8 @@
 
 DEFUNX ("ferror", Fferror, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {[@var{err}, @var{msg}] =} ferror (@var{fid}, \"clear\")\n\
+@deftypefn  {Built-in Function} {[@var{err}, @var{msg}] =} ferror (@var{fid})\n\
+@deftypefnx {Built-in Function} {[@var{err}, @var{msg}] =} ferror (@var{fid}, \"clear\")\n\
 Return 1 if an error condition has been encountered for the file ID\n\
 @var{fid} and 0 otherwise.  Note that it will only return 1 if an error\n\
 has already been encountered, not if the next operation will result in\n\
@@ -1746,6 +1779,7 @@
 \n\
 The second argument is optional.  If it is supplied, also clear the\n\
 error condition.\n\
+@seealso{fclear, fopen}\n\
 @end deftypefn")
 {
   octave_value_list retval;
@@ -1810,9 +1844,10 @@
 while (ischar (s = fgets (fid)))\n\
   fputs (stdout, s);\n\
 endwhile\n\
-     @print{} drwxr-xr-x  33 root  root  3072 Feb 15 13:28 etc\n\
-     @print{} drwxr-xr-x   3 root  root  1024 Feb 15 13:28 lib\n\
-     @print{} drwxrwxrwt  15 root  root  2048 Feb 17 14:53 tmp\n\
+\n\
+   @print{} drwxr-xr-x  33 root  root  3072 Feb 15 13:28 etc\n\
+   @print{} drwxr-xr-x   3 root  root  1024 Feb 15 13:28 lib\n\
+   @print{} drwxrwxrwt  15 root  root  2048 Feb 17 14:53 tmp\n\
 @end group\n\
 @end example\n\
 @end deftypefn")
@@ -1858,7 +1893,7 @@
   return retval;
 }
 
-DEFUN (pclose, args, ,
+DEFUNX ("pclose", Fpclose, args, ,
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} pclose (@var{fid})\n\
 Close a file identifier that was opened by @code{popen}.  You may also\n\
@@ -1988,8 +2023,7 @@
 in binary mode and with the @w{@code{O_EXCL}} flag.\n\
 \n\
 If the optional argument @var{delete} is supplied and is true,\n\
-the file will be deleted automatically when Octave exits, or when\n\
-the function @code{purge_tmp_files} is called.\n\
+the file will be deleted automatically when Octave exits.\n\
 \n\
 If successful, @var{fid} is a valid file ID, @var{name} is the name of\n\
 the file, and @var{msg} is an empty string.  Otherwise, @var{fid}\n\
@@ -2183,6 +2217,7 @@
 @deftypefnx {Built-in Function} {} SEEK_END ()\n\
 Return the numerical value to pass to @code{fseek} to perform\n\
 one of the following actions:\n\
+\n\
 @table @code\n\
 @item SEEK_SET\n\
 Position file relative to the beginning.\n\
rename from src/file-io.h
rename to libinterp/interpfcn/file-io.h
rename from src/graphics.cc
rename to libinterp/interpfcn/graphics.cc
--- a/src/graphics.cc
+++ b/libinterp/interpfcn/graphics.cc
@@ -42,6 +42,7 @@
 #include "oct-locbuf.h"
 #include "singleton-cleanup.h"
 
+#include "builtins.h"
 #include "cutils.h"
 #include "defun.h"
 #include "display.h"
@@ -136,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
@@ -145,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;
@@ -1037,27 +1042,27 @@
 {
   double tmp_rgb[3] = {0, 0, 0};
   bool retval = true;
-  unsigned int len = str.length();
+  unsigned int len = str.length ();
 
   std::transform (str.begin (), str.end (), str.begin (), tolower);
 
-  if (str.compare(0, len, "blue", 0, len) == 0)
+  if (str.compare (0, len, "blue", 0, len) == 0)
     tmp_rgb[2] = 1;
-  else if (str.compare(0, len, "black", 0, len) == 0
-           || str.compare(0, len, "k", 0, len) == 0)
+  else if (str.compare (0, len, "black", 0, len) == 0
+           || str.compare (0, len, "k", 0, len) == 0)
     tmp_rgb[0] = tmp_rgb[1] = tmp_rgb[2] = 0;
-  else if (str.compare(0, len, "red", 0, len) == 0)
+  else if (str.compare (0, len, "red", 0, len) == 0)
     tmp_rgb[0] = 1;
-  else if (str.compare(0, len, "green", 0, len) == 0)
+  else if (str.compare (0, len, "green", 0, len) == 0)
     tmp_rgb[1] = 1;
-  else if (str.compare(0, len, "yellow", 0, len) == 0)
+  else if (str.compare (0, len, "yellow", 0, len) == 0)
     tmp_rgb[0] = tmp_rgb[1] = 1;
-  else if (str.compare(0, len, "magenta", 0, len) == 0)
+  else if (str.compare (0, len, "magenta", 0, len) == 0)
     tmp_rgb[0] = tmp_rgb[2] = 1;
-  else if (str.compare(0, len, "cyan", 0, len) == 0)
+  else if (str.compare (0, len, "cyan", 0, len) == 0)
     tmp_rgb[1] = tmp_rgb[2] = 1;
-  else if (str.compare(0, len, "white", 0, len) == 0
-           || str.compare(0, len, "w", 0, len) == 0)
+  else if (str.compare (0, len, "white", 0, len) == 0
+           || str.compare (0, len, "w", 0, len) == 0)
     tmp_rgb[0] = tmp_rgb[1] = tmp_rgb[2] = 1;
   else
     retval = false;
@@ -1123,7 +1128,7 @@
 
       if (m.numel () == 3)
         {
-          color_values col (m (0), m (1), m(2));
+          color_values col (m(0), m(1), m(2));
           if (! error_state)
             {
               if (current_type != color_t || col != color_val)
@@ -1201,10 +1206,14 @@
   // check value type
   if (type_constraints.size () > 0)
     {
-      for (std::list<std::string>::const_iterator it = type_constraints.begin ();
-           ! xok && it != type_constraints.end (); ++it)
-        if ((*it) == v.class_name ())
-          xok = true;
+      if(type_constraints.find (v.class_name()) != type_constraints.end())
+        xok = true;
+
+      // check if complex is allowed (it's also of class "double", so
+      // checking that alone is not enough to ensure real type)
+      if (type_constraints.find ("real") != type_constraints.end ()
+          && v.is_complex_type ())
+        xok = false;
     }
   else
     xok = v.is_numeric_type ();
@@ -1271,7 +1280,7 @@
                 } \
             }
 
-          if (data.is_double_type() || data.is_bool_type ())
+          if (data.is_double_type () || data.is_bool_type ())
             CHECK_ARRAY_EQUAL (double, , NDArray)
           else if (data.is_single_type ())
             CHECK_ARRAY_EQUAL (float, float_, FloatNDArray)
@@ -1428,7 +1437,7 @@
     // complete validation will be done at execution-time
     return true;
   else if (v.is_cell () && v.length () > 0
-           && (v.rows() == 1 || v.columns () == 1)
+           && (v.rows () == 1 || v.columns () == 1)
            && v.cell_value ()(0).is_function_handle ())
     return true;
   else if (v.is_empty ())
@@ -1780,9 +1789,9 @@
               bool remove = false;
               if (val.is_string ())
                 {
-                  caseless_str tval = val.string_value ();
-
-                  remove = tval.compare ("remove");
+                  std::string tval = val.string_value ();
+
+                  remove = (tval.compare ("remove") == 0);
                 }
 
               pval_map_type& pval_map = plist_map[pfx];
@@ -1967,13 +1976,13 @@
 }
 
 /*
-%!# test set with name, value pairs
+## test set with name, value pairs
 %!test
-%!  set(gcf, "visible", "off");
-%!  h = plot (1:10, 10:-1:1);
-%!  set (h, "linewidth", 10, "marker", "x");
-%!  assert (get (h, "linewidth"), 10);
-%!  assert (get (h, "marker"), "x");
+%! set (gcf, "visible", "off");
+%! h = plot (1:10, 10:-1:1);
+%! set (h, "linewidth", 10, "marker", "x");
+%! assert (get (h, "linewidth"), 10);
+%! assert (get (h, "marker"), "x");
 */
 
 // Set properties given in two cell arrays containing names and values.
@@ -1983,7 +1992,7 @@
 {
   if (names.numel () != values.columns ())
     {
-      error("set: number of names must match number of value columns (%d != %d)",
+      error ("set: number of names must match number of value columns (%d != %d)",
             names.numel (), values.columns ());
     }
 
@@ -2002,47 +2011,46 @@
 }
 
 /*
-%!# test set with cell array arguments
+## test set with cell array arguments
 %!test
-%!  set (gcf, "visible", "off");
-%!  h = plot (1:10, 10:-1:1);
-%!  set (h, {"linewidth", "marker"}, {10, "x"});
-%!  assert (get(h, "linewidth"), 10);
-%!  assert (get(h, "marker"), "x");
-
-%!# test set with multiple handles and cell array arguments
+%! set (gcf, "visible", "off");
+%! h = plot (1:10, 10:-1:1);
+%! set (h, {"linewidth", "marker"}, {10, "x"});
+%! assert (get (h, "linewidth"), 10);
+%! assert (get (h, "marker"), "x");
+
+## test set with multiple handles and cell array arguments
 %!test
-%!  set (gcf, "visible", "off");
-%!  h = plot (1:10, 10:-1:1, 1:10, 1:10);
-%!  set (h, {"linewidth", "marker"}, {10, "x"; 5, "o"});
-%!  assert (get (h, "linewidth"), {10; 5});
-%!  assert (get (h, "marker"), {"x"; "o"});
-%!  set (h, {"linewidth", "marker"}, {10, "x"});
-%!  assert (get (h, "linewidth"), {10; 10});
-%!  assert (get (h, "marker"), {"x"; "x"});
+%! set (gcf, "visible", "off");
+%! h = plot (1:10, 10:-1:1, 1:10, 1:10);
+%! set (h, {"linewidth", "marker"}, {10, "x"; 5, "o"});
+%! assert (get (h, "linewidth"), {10; 5});
+%! assert (get (h, "marker"), {"x"; "o"});
+%! set (h, {"linewidth", "marker"}, {10, "x"});
+%! assert (get (h, "linewidth"), {10; 10});
+%! assert (get (h, "marker"), {"x"; "x"});
 
 %!error <set: number of graphics handles must match number of value rows>
-%!  set (gcf, "visible", "off");
-%!  h = plot (1:10, 10:-1:1, 1:10, 1:10);
-%!  set (h, {"linewidth", "marker"}, {10, "x"; 5, "o"; 7, "."});
+%! set (gcf, "visible", "off");
+%! h = plot (1:10, 10:-1:1, 1:10, 1:10);
+%! set (h, {"linewidth", "marker"}, {10, "x"; 5, "o"; 7, "."});
 
 %!error <set: number of names must match number of value columns>
-%!  set (gcf, "visible", "off");
-%!  h = plot (1:10, 10:-1:1, 1:10, 1:10);
-%!  set (h, {"linewidth"}, {10, "x"; 5, "o"});
+%! set (gcf, "visible", "off");
+%! h = plot (1:10, 10:-1:1, 1:10, 1:10);
+%! set (h, {"linewidth"}, {10, "x"; 5, "o"});
 */
 
 // Set properties given in a struct array
 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)
@@ -2051,16 +2059,42 @@
 }
 
 /*
-%!# test set with struct arguments
+## test set with struct arguments
+%!test
+%! set (gcf, "visible", "off");
+%! h = plot (1:10, 10:-1:1);
+%! set (h, struct ("linewidth", 10, "marker", "x"));
+%! assert (get (h, "linewidth"), 10);
+%! assert (get (h, "marker"), "x");
+%! 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
-%!  set (gcf, "visible", "off");
-%!  h = plot (1:10, 10:-1:1);
-%!  set (h, struct ("linewidth", 10, "marker", "x"));
-%!  assert (get (h, "linewidth"), 10);
-%!  assert (get (h, "marker"), "x");
-%!  h = plot (1:10, 10:-1:1, 1:10, 1:10);
-%!  set (h, struct ("linewidth", {5, 10}));
-%!  assert (get(h, "linewidth"), {10; 10});
+%! 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.
@@ -2071,11 +2105,11 @@
 {
   if (val.is_string ())
     {
-      caseless_str tval = val.string_value ();
+      std::string tval = val.string_value ();
 
       octave_value default_val;
 
-      if (tval.compare ("default"))
+      if (tval.compare ("default") == 0)
         {
           default_val = get_default (name);
 
@@ -2084,7 +2118,7 @@
 
           rep->set (name, default_val);
         }
-      else if (tval.compare ("factory"))
+      else if (tval.compare ("factory") == 0)
         {
           default_val = get_factory_default (name);
 
@@ -2094,22 +2128,30 @@
           rep->set (name, default_val);
         }
       else
-        rep->set (name, val);
+        {
+          // Matlab specifically uses "\default" to escape string setting 
+          if (tval.compare ("\\default") == 0)
+            rep->set (name, "default");
+          else if (tval.compare ("\\factory") == 0)
+            rep->set (name, "factory");
+          else
+            rep->set (name, val);
+        }
     }
   else
     rep->set (name, val);
 }
 
 /*
-%!# test setting of default values
+## test setting of default values
 %!test
-%!  set (gcf, "visible", "off");
-%!  h = plot (1:10, 10:-1:1);
-%!  set (0, "defaultlinelinewidth", 20);
-%!  set (h, "linewidth", "default");
-%!  assert (get (h, "linewidth"), 20);
-%!  set (h, "linewidth", "factory");
-%!  assert (get (h, "linewidth"), 0.5);
+%! set (gcf, "visible", "off");
+%! h = plot (1:10, 10:-1:1);
+%! set (0, "defaultlinelinewidth", 20);
+%! set (h, "linewidth", "default");
+%! assert (get (h, "linewidth"), 20);
+%! set (h, "linewidth", "factory");
+%! assert (get (h, "linewidth"), 0.5);
 */
 
 static double
@@ -3029,6 +3071,8 @@
   else if (xunits.compare ("normalized"))
     {
       ss = Matrix (1, 4, 1.0);
+      ss(0) = 0;
+      ss(1) = 0;
     }
   else if (xunits.compare ("points"))
     {
@@ -3041,6 +3085,33 @@
   set_screensize (ss);
 }
 
+Matrix
+root_figure::properties::get_boundingbox (bool, const Matrix&) const
+{
+  Matrix screen_size = screen_size_pixels ();
+  Matrix pos = Matrix (1, 4, 0);
+  pos(2) = screen_size(0);
+  pos(3) = screen_size(1);
+  return pos;
+}
+
+/*
+%!test
+%! set (0, "units", "pixels");
+%! sz = get (0, "screensize") - [1, 1, 0, 0];
+%! dpi = get (0, "screenpixelsperinch");
+%! set (0, "units", "inches");
+%! assert (get (0, "screensize"), sz / dpi, 0.5 / dpi);
+%! set (0, "units", "centimeters");
+%! assert (get (0, "screensize"), sz / dpi * 2.54, 0.5 / dpi * 2.54);
+%! set (0, "units", "points");
+%! assert (get (0, "screensize"), sz / dpi * 72, 0.5 / dpi * 72);
+%! set (0, "units", "normalized");
+%! assert (get (0, "screensize"), [0.0, 0.0, 1.0, 1.0]);
+%! set (0, "units", "pixels");
+%! assert (get (0, "screensize"), sz + [1, 1, 0, 0]);
+*/
+
 void
 root_figure::properties::remove_child (const graphics_handle& gh)
 {
@@ -3225,10 +3296,11 @@
   if (! error_state)
     {
       Matrix old_bb, new_bb;
-
-      old_bb = get_boundingbox ();
-      position.set (v, true, do_notify_toolkit);
-      new_bb = get_boundingbox ();
+      bool modified = false;
+
+      old_bb = get_boundingbox (true);
+      modified = position.set (v, false, do_notify_toolkit);
+      new_bb = get_boundingbox (true);
 
       if (old_bb != new_bb)
         {
@@ -3239,7 +3311,11 @@
             }
         }
 
-      mark_modified ();
+      if (modified)
+        {
+          position.run_listeners (POSTSET);
+          mark_modified ();
+        }
     }
 }
 
@@ -3465,11 +3541,12 @@
   Matrix pos = get_paperposition ().matrix_value ();
   Matrix sz = get_papersize ().matrix_value ();
 
-  pos (0) = pos (0) / sz(0);
-  pos (1) = pos (1) / sz(1);
-  pos (2) = pos (2) / sz(0);
-  pos (3) = pos (3) / sz(1);
-
+  pos(0) /= sz(0);
+  pos(1) /= sz(1);
+  pos(2) /= sz(0);
+  pos(3) /= sz(1);
+
+  std::string porient = get_paperorientation ();
   caseless_str punits = get_paperunits ();
   caseless_str typ = get_papertype ();
 
@@ -3477,33 +3554,37 @@
     {
       if (old_paperunits.compare ("centimeters"))
         {
-          sz (0) = sz (0) / 2.54;
-          sz (1) = sz (1) / 2.54;
+          sz(0) /= 2.54;
+          sz(1) /= 2.54;
         }
       else if (old_paperunits.compare ("points"))
         {
-          sz (0) = sz (0) / 72.0;
-          sz (1) = sz (1) / 72.0;
+          sz(0) /= 72.0;
+          sz(1) /= 72.0;
         }
 
       if (punits.compare ("centimeters"))
         {
-          sz(0) = sz(0) * 2.54;
-          sz(1) = sz(1) * 2.54;
-        }
-      else if (old_paperunits.compare ("points"))
-        {
-          sz (0) = sz (0) * 72.0;
-          sz (1) = sz (1) * 72.0;
+          sz(0) *= 2.54;
+          sz(1) *= 2.54;
+        }
+      else if (punits.compare ("points"))
+        {
+          sz(0) *= 72.0;
+          sz(1) *= 72.0;
         }
     }
   else
-    sz = papersize_from_type (punits, typ);
-
-  pos (0) = pos (0) * sz(0);
-  pos (1) = pos (1) * sz(1);
-  pos (2) = pos (2) * sz(0);
-  pos (3) = pos (3) * sz(1);
+    {
+      sz = papersize_from_type (punits, typ);
+      if (porient == "landscape")
+        std::swap (sz(0), sz(1));
+    }
+
+  pos(0) *= sz(0);
+  pos(1) *= sz(1);
+  pos(2) *= sz(0);
+  pos(3) *= sz(1);
 
   papersize.set (octave_value (sz));
   paperposition.set (octave_value (pos));
@@ -3513,18 +3594,193 @@
 figure::properties::update_papertype (void)
 {
   caseless_str typ = get_papertype ();
-
   if (! typ.compare ("<custom>"))
-    // Call papersize.set rather than set_papersize to avoid loops between
-    // update_papersize and update_papertype
-    papersize.set (octave_value (papersize_from_type (get_paperunits (), typ)));
+    {
+      Matrix sz = papersize_from_type (get_paperunits (), typ);
+      if (get_paperorientation () == "landscape")
+        std::swap (sz(0), sz(1));
+      // Call papersize.set rather than set_papersize to avoid loops
+      // between update_papersize and update_papertype
+      papersize.set (octave_value (sz));
+    }
 }
 
 void
 figure::properties::update_papersize (void)
 {
-  papertype.set ("<custom>");
-}
+  Matrix sz = get_papersize ().matrix_value ();
+  if (sz(0) > sz(1))
+    {
+      std::swap (sz(0), sz(1));
+      papersize.set (octave_value (sz));
+      paperorientation.set (octave_value ("landscape"));
+    }
+  else
+    {
+      paperorientation.set ("portrait");
+    }
+  std::string punits = get_paperunits ();
+  if (punits == "centimeters")
+    {
+      sz(0) /= 2.54;
+      sz(1) /= 2.54;
+    }
+  else if (punits == "points")
+    {
+      sz(0) /= 72.0;
+      sz(1) /= 72.0;
+    }
+  if (punits == "normalized")
+    {
+      caseless_str typ = get_papertype ();
+      if (get_papertype () == "<custom>")
+        error ("set: can't set the papertype to <custom> when the paperunits is normalized");
+    }
+  else
+    {
+      // TODO - the papersizes info is also in papersize_from_type().
+      // Both should be rewritten to avoid the duplication.
+      std::string typ = "<custom>";
+      const double mm2in = 1.0 / 25.4;
+      const double tol = 0.01;
+
+      if (std::abs (sz(0) - 8.5) + std::abs (sz(1) - 11.0) < tol)
+        typ = "usletter";
+      else if (std::abs (sz(0) - 8.5) + std::abs (sz(1) - 14.0) < tol)
+        typ = "uslegal";
+      else if (std::abs (sz(0) - 11.0) + std::abs (sz(1) - 17.0) < tol)
+        typ = "tabloid";
+      else if (std::abs (sz(0) - 841.0 * mm2in) + std::abs (sz(1) - 1198.0 * mm2in) < tol)
+        typ = "a0";
+      else if (std::abs (sz(0) - 594.0 * mm2in) + std::abs (sz(1) - 841.0 * mm2in) < tol)
+        typ = "a1";
+      else if (std::abs (sz(0) - 420.0 * mm2in) + std::abs (sz(1) - 594.0 * mm2in) < tol)
+        typ = "a2";
+      else if (std::abs (sz(0) - 297.0 * mm2in) + std::abs (sz(1) - 420.0 * mm2in) < tol)
+        typ = "a3";
+      else if (std::abs (sz(0) - 210.0 * mm2in) + std::abs (sz(1) - 297.0 * mm2in) < tol)
+        typ = "a4";
+      else if (std::abs (sz(0) - 148.0 * mm2in) + std::abs (sz(1) - 210.0 * mm2in) < tol)
+        typ = "a5";
+      else if (std::abs (sz(0) - 1029.0 * mm2in) + std::abs (sz(1) - 1456.0 * mm2in) < tol)
+        typ = "b0";
+      else if (std::abs (sz(0) - 728.0 * mm2in) + std::abs (sz(1) - 1028.0 * mm2in) < tol)
+        typ = "b1";
+      else if (std::abs (sz(0) - 514.0 * mm2in) + std::abs (sz(1) - 728.0 * mm2in) < tol)
+        typ = "b2";
+      else if (std::abs (sz(0) - 364.0 * mm2in) + std::abs (sz(1) - 514.0 * mm2in) < tol)
+        typ = "b3";
+      else if (std::abs (sz(0) - 257.0 * mm2in) + std::abs (sz(1) - 364.0 * mm2in) < tol)
+        typ = "b4";
+      else if (std::abs (sz(0) - 182.0 * mm2in) + std::abs (sz(1) - 257.0 * mm2in) < tol)
+        typ = "b5";
+      else if (std::abs (sz(0) - 9.0)  + std::abs (sz(1) - 12.0) < tol)
+        typ = "arch-a";
+      else if (std::abs (sz(0) - 12.0) + std::abs (sz(1) - 18.0) < tol)
+        typ = "arch-b";
+      else if (std::abs (sz(0) - 18.0) + std::abs (sz(1) - 24.0) < tol)
+        typ = "arch-c";
+      else if (std::abs (sz(0) - 24.0) + std::abs (sz(1) - 36.0) < tol)
+        typ = "arch-d";
+      else if (std::abs (sz(0) - 36.0) + std::abs (sz(1) - 48.0) < tol)
+        typ = "arch-e";
+      else if (std::abs (sz(0) - 8.5)  + std::abs (sz(1) - 11.0) < tol)
+        typ = "a";
+      else if (std::abs (sz(0) - 11.0) + std::abs (sz(1) - 17.0) < tol)
+        typ = "b";
+      else if (std::abs (sz(0) - 17.0) + std::abs (sz(1) - 22.0) < tol)
+        typ = "c";
+      else if (std::abs (sz(0) - 22.0) + std::abs (sz(1) - 34.0) < tol)
+        typ = "d";
+      else if (std::abs (sz(0) - 34.0) + std::abs (sz(1) - 43.0) < tol)
+        typ = "e";
+      // Call papertype.set rather than set_papertype to avoid loops between
+      // update_papersize and update_papertype
+      papertype.set (typ);
+    }
+  if (punits == "centimeters")
+    {
+      sz(0) *= 2.54;
+      sz(1) *= 2.54;
+    }
+  else if (punits == "points")
+    {
+      sz(0) *= 72.0;
+      sz(1) *= 72.0;
+    }
+  if (get_paperorientation () == "landscape")
+    {
+      std::swap (sz(0), sz(1));
+      papersize.set (octave_value (sz));
+    }
+}
+
+/*
+%!test
+%! figure (1, "visible", "off");
+%! set (1, "paperunits", "inches");
+%! set (1, "papersize", [5, 4])
+%! set (1, "paperunits", "points");
+%! assert (get (1, "papersize"), [5, 4] * 72, 1)
+%! papersize = get (gcf, "papersize");
+%! set (1, "papersize", papersize + 1);
+%! set (1, "papersize", papersize)
+%! assert (get (1, "papersize"), [5, 4] * 72, 1)
+%! close (1)
+%!test
+%! figure (1, "visible", "off");
+%! set (1, "paperunits", "inches");
+%! set (1, "papersize", [5, 4])
+%! set (1, "paperunits", "centimeters");
+%! assert (get (1, "papersize"), [5, 4] * 2.54, 2.54/72)
+%! papersize = get (gcf, "papersize");
+%! set (1, "papersize", papersize + 1);
+%! set (1, "papersize", papersize)
+%! assert (get (1, "papersize"), [5, 4] * 2.54, 2.54/72)
+%! close (1)
+*/
+
+void
+figure::properties::update_paperorientation (void)
+{
+  std::string porient = get_paperorientation ();
+  Matrix sz = get_papersize ().matrix_value ();
+  Matrix pos = get_paperposition ().matrix_value ();
+  if ((sz(0) > sz(1) && porient == "portrait")
+      || (sz(0) < sz(1) && porient == "landscape"))
+    {
+      std::swap (sz(0), sz(1));
+      std::swap (pos(0), pos(1));
+      std::swap (pos(2), pos(3));
+      // Call papertype.set rather than set_papertype to avoid loops
+      // between update_papersize and update_papertype
+      papersize.set (octave_value (sz));
+      paperposition.set (octave_value (pos));
+    }
+}
+
+/*
+%!test
+%! figure (1, "visible", false);
+%! tol = 100 * eps ();
+%! ## UPPER case and MiXed case is part of test and should not be changed.
+%! set (gcf (), "paperorientation", "PORTRAIT");
+%! set (gcf (), "paperunits", "inches");
+%! set (gcf (), "papertype", "USletter");
+%! assert (get (gcf (), "papersize"), [8.5, 11.0], tol);
+%! set (gcf (), "paperorientation", "Landscape");
+%! assert (get (gcf (), "papersize"), [11.0, 8.5], tol);
+%! set (gcf (), "paperunits", "centimeters");
+%! assert (get (gcf (), "papersize"), [11.0, 8.5] * 2.54, tol);
+%! set (gcf (), "papertype", "a4");
+%! assert (get (gcf (), "papersize"), [29.7, 21.0], tol);
+%! set (gcf (), "paperunits", "inches", "papersize", [8.5, 11.0]);
+%! assert (get (gcf (), "papertype"), "usletter");
+%! assert (get (gcf (), "paperorientation"), "portrait");
+%! set (gcf (), "papersize", [11.0, 8.5]);
+%! assert (get (gcf (), "papertype"), "usletter");
+%! assert (get (gcf (), "paperorientation"), "landscape");
+*/
 
 void
 figure::properties::set_units (const octave_value& v)
@@ -3543,9 +3799,20 @@
 void
 figure::properties::update_units (const caseless_str& old_units)
 {
-  set_position (convert_position (get_position ().matrix_value (), old_units,
-                                  get_units (), screen_size_pixels ()));
-}
+  position.set (convert_position (get_position ().matrix_value (), old_units,
+                                  get_units (), screen_size_pixels ()), false);
+}
+
+/*
+%!test
+%! figure (1, "visible", false);
+%! set (0, "units", "pixels");
+%! rsz = get (0, "screensize");
+%! set (gcf (), "units", "pixels");
+%! fsz = get (gcf (), "position");
+%! set (gcf (), "units", "normalized");
+%! assert (get (gcf (), "position"), (fsz - [1, 1, 0, 0]) ./ rsz([3, 4, 3, 4]));
+*/
 
 std::string
 figure::properties::get_title (void) const
@@ -3645,7 +3912,7 @@
   xset (title.handle_value (), "horizontalalignment", "center");
   xset (title.handle_value (), "horizontalalignmentmode", "auto");
 
-  xset (xlabel.handle_value (), "verticalalignment", "cap");
+  xset (xlabel.handle_value (), "verticalalignment", "top");
   xset (xlabel.handle_value (), "verticalalignmentmode", "auto");
   xset (ylabel.handle_value (), "verticalalignment", "bottom");
   xset (ylabel.handle_value (), "verticalalignmentmode", "auto");
@@ -3738,20 +4005,20 @@
                  {
                    axes::properties& props =
                      dynamic_cast<axes::properties&> (go.get_properties ());
-                   if (props.autopos_tag_is("subplot"))
+                   if (props.autopos_tag_is ("subplot"))
                      {
                        Matrix outpos = go.get ("outerposition").matrix_value ();
-                       bool l_align=(std::abs (outpos(0)-ref_outbox(0)) < 1e-15);
-                       bool b_align=(std::abs (outpos(1)-ref_outbox(1)) < 1e-15);
-                       bool r_align=(std::abs (outpos(0)+outpos(2)-ref_outbox(2)) < 1e-15);
-                       bool t_align=(std::abs (outpos(1)+outpos(3)-ref_outbox(3)) < 1e-15);
+                       bool l_align = (std::abs (outpos(0)-ref_outbox(0)) < 1e-15);
+                       bool b_align = (std::abs (outpos(1)-ref_outbox(1)) < 1e-15);
+                       bool r_align = (std::abs (outpos(0)+outpos(2)-ref_outbox(2)) < 1e-15);
+                       bool t_align = (std::abs (outpos(1)+outpos(3)-ref_outbox(3)) < 1e-15);
                        if (l_align || b_align || r_align || t_align)
                          {
-                           aligned.push_back(kids(i));
-                           l_aligned.push_back(l_align);
-                           b_aligned.push_back(b_align);
-                           r_aligned.push_back(r_align);
-                           t_aligned.push_back(t_align);
+                           aligned.push_back (kids(i));
+                           l_aligned.push_back (l_align);
+                           b_aligned.push_back (b_align);
+                           r_aligned.push_back (r_align);
+                           t_aligned.push_back (t_align);
                            // FIXME: the temporarily deleted tags should be
                            //        protected from interrupts
                            props.set_autopos_tag ("none");
@@ -3760,7 +4027,7 @@
                  }
              }
            // Determine a minimum box which aligns the subplots
-           Matrix ref_box(1, 4, 0.);
+           Matrix ref_box (1, 4, 0.);
            ref_box(2) = 1.;
            ref_box(3) = 1.;
            for (size_t i = 0; i < aligned.size (); i++)
@@ -4059,7 +4326,7 @@
   xticklabelmode = "auto";
   yticklabelmode = "auto";
   zticklabelmode = "auto";
-  color = "none";
+  color = color_values ("white");
   xcolor = color_values ("black");
   ycolor = color_values ("black");
   zcolor = color_values ("black");
@@ -4153,7 +4420,7 @@
   xset (title.handle_value (), "horizontalalignment", "center");
   xset (title.handle_value (), "horizontalalignmentmode", "auto");
 
-  xset (xlabel.handle_value (), "verticalalignment", "cap");
+  xset (xlabel.handle_value (), "verticalalignment", "top");
   xset (xlabel.handle_value (), "verticalalignmentmode", "auto");
   xset (ylabel.handle_value (), "verticalalignment", "bottom");
   xset (ylabel.handle_value (), "verticalalignmentmode", "auto");
@@ -4315,7 +4582,7 @@
 inline void
 normalize (ColumnVector& v)
 {
-  double fact = 1.0/sqrt(v(0)*v(0)+v(1)*v(1)+v(2)*v(2));
+  double fact = 1.0 / sqrt (v(0)*v(0)+v(1)*v(1)+v(2)*v(2));
   scale (v, fact, fact, fact);
 }
 
@@ -4354,7 +4621,7 @@
       0,1,1,1,
       1,1,1,1};
   Matrix m (4, 8);
-  memcpy (m.fortran_vec (), data, sizeof(double)*32);
+  memcpy (m.fortran_vec (), data, sizeof (double)*32);
   return m;
 }
 
@@ -4362,7 +4629,7 @@
 cam2xform (const Array<double>& m)
 {
   ColumnVector retval (4, 1.0);
-  memcpy (retval.fortran_vec (), m.fortran_vec (), sizeof(double)*3);
+  memcpy (retval.fortran_vec (), m.fortran_vec (), sizeof (double)*3);
   return retval;
 }
 
@@ -4393,7 +4660,7 @@
                   && cameratargetmode_is ("auto")
                   && cameraupvectormode_is ("auto")
                   && cameraviewanglemode_is ("auto"));
-  bool dowarp = (autocam && dataaspectratiomode_is("auto")
+  bool dowarp = (autocam && dataaspectratiomode_is ("auto")
                  && plotboxaspectratiomode_is ("auto"));
 
   ColumnVector c_eye (xform_vector ());
@@ -4415,17 +4682,17 @@
     {
       Matrix tview = get_view ().matrix_value ();
       double az = tview(0), el = tview(1);
-      double d = 5*sqrt(pb(0)*pb(0)+pb(1)*pb(1)+pb(2)*pb(2));
+      double d = 5 * sqrt (pb(0)*pb(0)+pb(1)*pb(1)+pb(2)*pb(2));
 
       if (el == 90 || el == -90)
-        c_eye(2) = d*signum(el);
+        c_eye(2) = d*signum (el);
       else
         {
           az *= M_PI/180.0;
           el *= M_PI/180.0;
-          c_eye(0) = d*cos(el)*sin(az);
-          c_eye(1) = -d*cos(el)*cos(az);
-          c_eye(2) = d*sin(el);
+          c_eye(0) = d * cos (el) * sin (az);
+          c_eye(1) = -d* cos (el) * cos (az);
+          c_eye(2) = d * sin (el);
         }
       c_eye(0) = c_eye(0)*(xlimits(1)-xlimits(0))/(xd*pb(0))+c_center(0);
       c_eye(1) = c_eye(1)*(ylimits(1)-ylimits(0))/(yd*pb(1))+c_center(1);
@@ -4444,9 +4711,9 @@
       if (el == 90 || el == -90)
         {
           c_upv(0) =
-            -signum(el)*sin(az*M_PI/180.0)*(xlimits(1)-xlimits(0))/pb(0);
+            -signum (el) *sin (az*M_PI/180.0)*(xlimits(1)-xlimits(0))/pb(0);
           c_upv(1) =
-            signum(el)*cos(az*M_PI/180.0)*(ylimits(1)-ylimits(0))/pb(1);
+            signum (el) * cos (az*M_PI/180.0)*(ylimits(1)-ylimits(0))/pb(1);
         }
       else
         c_upv(2) = 1;
@@ -4483,7 +4750,7 @@
 
   if (std::abs (dot (f, UP)) > 1e-15)
     {
-      double fa = 1/sqrt(1-f(2)*f(2));
+      double fa = 1 / sqrt(1-f(2)*f(2));
       scale (UP, fa, fa, fa);
     }
 
@@ -4641,7 +4908,7 @@
     xPlane = (dir(2) < 0 ? x_min : x_max);
 
   xPlaneN = (xPlane == x_min ? x_max : x_min);
-  fx = (x_max-x_min)/sqrt(dir(0)*dir(0)+dir(1)*dir(1));
+  fx = (x_max-x_min) / sqrt (dir(0)*dir(0)+dir(1)*dir(1));
 
   p1 = xform.transform ((x_min+x_max)/2, y_min, (z_min+z_max)/2, false);
   p2 = xform.transform ((x_min+x_max)/2, y_max, (z_min+z_max)/2, false);
@@ -4669,11 +4936,11 @@
     yPlane = (dir(2) < 0 ? y_min : y_max);
 
   yPlaneN = (yPlane == y_min ? y_max : y_min);
-  fy = (y_max-y_min)/sqrt(dir(0)*dir(0)+dir(1)*dir(1));
-
-  p1 = xform.transform((x_min+x_max)/2, (y_min+y_max)/2, z_min, false);
-  p2 = xform.transform((x_min+x_max)/2, (y_min+y_max)/2, z_max, false);
-  dir(0) = xround(p2(0)-p1(0));
+  fy = (y_max-y_min) / sqrt (dir(0)*dir(0)+dir(1)*dir(1));
+
+  p1 = xform.transform ((x_min+x_max)/2, (y_min+y_max)/2, z_min, false);
+  p2 = xform.transform ((x_min+x_max)/2, (y_min+y_max)/2, z_max, false);
+  dir(0) = xround (p2(0)-p1(0));
   dir(1) = xround (p2(1)-p1(1));
   dir(2) = (p2(2)-p1(2));
   if (dir(0) == 0 && dir(1) == 0)
@@ -4697,7 +4964,7 @@
     zPlane = (dir(2) < 0 ? z_min : z_max);
 
   zPlaneN = (zPlane == z_min ? z_max : z_min);
-  fz = (z_max-z_min)/sqrt(dir(0)*dir(0)+dir(1)*dir(1));
+  fz = (z_max-z_min) / sqrt (dir(0)*dir(0)+dir(1)*dir(1));
 
   unwind_protect frame;
   frame.protect_var (updating_axes_layout);
@@ -4747,34 +5014,31 @@
   }
 
   Matrix viewmat = get_view ().matrix_value ();
-  nearhoriz = std::abs(viewmat(1)) <= 5;
-
-  update_ticklengths ();
-}
-
-void
-axes::properties::update_ticklengths (void)
+  nearhoriz = std::abs (viewmat(1)) <= 5;
+
+  update_ticklength ();
+}
+
+void
+axes::properties::update_ticklength (void)
 {
   bool mode2d = (((xstate > AXE_DEPTH_DIR ? 1 : 0) +
                   (ystate > AXE_DEPTH_DIR ? 1 : 0) +
                   (zstate > AXE_DEPTH_DIR ? 1 : 0)) == 2);
+
   if (tickdirmode_is ("auto"))
-  {
-    // FIXME: tickdir should be updated (code below comes
-    //        from JHandles)
-    //autoMode++;
-    //TickDir.set(mode2d ? "in" : "out", true);
-    //autoMode--;
-  }
-
-  //double ticksign = (tickdir_is ("in") ? -1 : 1);
-  double ticksign = (tickdirmode_is ("auto") ?
-                     (mode2d ? -1 : 1) :
-                     (tickdir_is ("in") ? -1 : 1));
-  // FIXME: use ticklength property
-  xticklen = ticksign*7;
-  yticklen = ticksign*7;
-  zticklen = ticksign*7;
+    tickdir.set (mode2d ? "in" : "out", true);
+
+  double ticksign = (tickdir_is ("in") ? -1 : 1);
+
+  Matrix bbox = get_boundingbox (true);
+  Matrix ticklen = get_ticklength ().matrix_value ();
+  ticklen(0) = ticklen(0) * std::max (bbox(2), bbox(3));
+  ticklen(1) = ticklen(1) * std::max (bbox(2), bbox(3));
+
+  xticklen = ticksign * (mode2d ? ticklen(0) : ticklen(1));
+  yticklen = ticksign * (mode2d ? ticklen(0) : ticklen(1));
+  zticklen = ticksign * (mode2d ? ticklen(0) : ticklen(1));
 
   xtickoffset = (mode2d ? std::max (0., xticklen) : std::abs (xticklen)) + 5;
   ytickoffset = (mode2d ? std::max (0., yticklen) : std::abs (yticklen)) + 5;
@@ -4786,6 +5050,24 @@
   update_title_position ();
 }
 
+/*
+## FIXME: A demo can't be called in a C++ file.  This should be made a test
+## or moved to a .m file where it can be called.
+%!demo
+%! clf;
+%! subplot (2,1,1);
+%! plot (rand (3));
+%! xlabel xlabel;
+%! ylabel ylabel;
+%! title title;
+%! subplot (2,1,2);
+%! plot (rand (3));
+%! set (gca, "ticklength", get (gca, "ticklength") * 2, "tickdir", "out");
+%! xlabel xlabel;
+%! ylabel ylabel;
+%! title title;
+*/
+
 static bool updating_xlabel_position = false;
 
 void
@@ -4839,9 +5121,9 @@
 
       bool tick_along_z = nearhoriz || xisinf (fy);
       if (tick_along_z)
-        p(2) += (signum(zpTick-zpTickN)*fz*xtickoffset);
+        p(2) += (signum (zpTick-zpTickN)*fz*xtickoffset);
       else
-        p(1) += (signum(ypTick-ypTickN)*fy*xtickoffset);
+        p(1) += (signum (ypTick-ypTickN)*fy*xtickoffset);
 
       p = xform.transform (p(0), p(1), p(2), false);
 
@@ -4920,19 +5202,28 @@
       graphics_xform xform = get_transform ();
 
       Matrix ext (1, 2, 0.0);
+
+      // The underlying get_extents() from FreeType produces mismatched values.
+      // x-extent accurately measures the width of the glyphs.
+      // y-extent instead measures from baseline-to-baseline.
+      // Pad x-extent (+4) so that it approximately matches y-extent.
+      // This keeps ylabels about the same distance from y-axis as
+      // xlabels are from x-axis.
+      // ALWAYS use an even number for padding or horizontal alignment
+      // will be off.
       ext = get_ticklabel_extents (get_ytick ().matrix_value (),
                                    get_yticklabel ().all_strings (),
                                    get_ylim ().matrix_value ());
 
-      double wmax = ext(0), hmax = ext(1), angle = 0;
+      double wmax = ext(0)+4, hmax = ext(1), angle = 0;
       ColumnVector p =
         graphics_xform::xform_vector (xpTick, (ypTickN+ypTick)/2, zpTick);
 
       bool tick_along_z = nearhoriz || xisinf (fx);
       if (tick_along_z)
-        p(2) += (signum(zpTick-zpTickN)*fz*ytickoffset);
+        p(2) += (signum (zpTick-zpTickN)*fz*ytickoffset);
       else
-        p(0) += (signum(xpTick-xpTickN)*fx*ytickoffset);
+        p(0) += (signum (xpTick-xpTickN)*fx*ytickoffset);
 
       p = xform.transform (p(0), p(1), p(2), false);
 
@@ -5024,18 +5315,18 @@
           p = graphics_xform::xform_vector (xPlaneN, yPlane,
                                             (zpTickN+zpTick)/2);
           if (xisinf (fy))
-            p(0) += (signum(xPlaneN-xPlane)*fx*ztickoffset);
+            p(0) += (signum (xPlaneN-xPlane)*fx*ztickoffset);
           else
-            p(1) += (signum(yPlane-yPlaneN)*fy*ztickoffset);
+            p(1) += (signum (yPlane-yPlaneN)*fy*ztickoffset);
         }
       else
         {
           p = graphics_xform::xform_vector (xPlane, yPlaneN,
                                             (zpTickN+zpTick)/2);
           if (xisinf (fx))
-            p(1) += (signum(yPlaneN-yPlane)*fy*ztickoffset);
+            p(1) += (signum (yPlaneN-yPlane)*fy*ztickoffset);
           else
-            p(0) += (signum(xPlane-xPlaneN)*fx*ztickoffset);
+            p(0) += (signum (xPlane-xPlaneN)*fx*ztickoffset);
         }
 
       p = xform.transform (p(0), p(1), p(2), false);
@@ -5119,7 +5410,7 @@
 
       p = xform.untransform (p(0), p(1), p(2), true);
 
-      title_props.set_position (p.extract_n(0, 3).transpose ());
+      title_props.set_position (p.extract_n (0, 3).transpose ());
       title_props.set_positionmode ("auto");
     }
 }
@@ -5372,7 +5663,7 @@
           text::properties& text_props = reinterpret_cast<text::properties&>
             (gh_manager::get_object (text_handle).get_properties ());
 
-          Matrix text_pos = text_props.get_position ().matrix_value ();
+          Matrix text_pos = text_props.get_data_position ();
           text_pos = xform.transform (text_pos(0), text_pos(1), text_pos(2));
           if (text_props.get_string ().is_empty ())
             {
@@ -5389,7 +5680,7 @@
               bool ignore_vertical = false;
               if (only_text_height)
                 {
-                  double text_rotation = text_props.get_rotation();
+                  double text_rotation = text_props.get_rotation ();
                   if (text_rotation == 0. || text_rotation == 180.)
                       ignore_horizontal = true;
                   else if (text_rotation == 90. || text_rotation == 270.)
@@ -5437,9 +5728,9 @@
   graphics_object obj = gh_manager::get_object (get_parent ());
   Matrix parent_bb = obj.get_properties ().get_boundingbox (true).extract_n (0, 2, 1, 2);
   caseless_str new_units = get_units ();
-  position.set (octave_value (convert_position (get_position().matrix_value(), old_units, new_units, parent_bb)), false);
-  outerposition.set (octave_value (convert_position (get_outerposition().matrix_value(), old_units, new_units, parent_bb)), false);
-  tightinset.set (octave_value (convert_position (get_tightinset().matrix_value(), old_units, new_units, parent_bb)), false);
+  position.set (octave_value (convert_position (get_position ().matrix_value (), old_units, new_units, parent_bb)), false);
+  outerposition.set (octave_value (convert_position (get_outerposition ().matrix_value (), old_units, new_units, parent_bb)), false);
+  tightinset.set (octave_value (convert_position (get_tightinset ().matrix_value (), old_units, new_units, parent_bb)), false);
 }
 
 void
@@ -5475,7 +5766,7 @@
   double parent_height = box_pix_height;
 
   if (fontunits_is ("normalized") && parent_height <= 0)
-    parent_height = get_boundingbox (true).elem(3);
+    parent_height = get_boundingbox (true).elem (3);
 
   return convert_font_size (fs, get_fontunits (), "points", parent_height);
 }
@@ -5686,10 +5977,19 @@
               min_val = min_pos;
             }
           // FIXME -- maybe this test should also be relative?
-          if (std::abs (min_val - max_val) < sqrt (DBL_EPSILON))
-            {
-              min_val *= 0.9;
-              max_val *= 1.1;
+          if (std::abs (min_val - max_val) < sqrt (std::numeric_limits<double>::epsilon ()))
+            {
+              // Widen range when too small
+              if (min_val >= 0)
+                {
+                  min_val *= 0.9;
+                  max_val *= 1.1;
+                }
+              else
+                {
+                  min_val *= 1.1;
+                  max_val *= 0.9;
+                }
             }
           if (min_val > 0)
             {
@@ -5712,7 +6012,7 @@
               max_val = 1;
             }
           // FIXME -- maybe this test should also be relative?
-          else if (std::abs (min_val - max_val) < sqrt (DBL_EPSILON))
+          else if (std::abs (min_val - max_val) < sqrt (std::numeric_limits<double>::epsilon ()))
             {
               min_val -= 0.1 * std::abs (min_val);
               max_val += 0.1 * std::abs (max_val);
@@ -5919,7 +6219,7 @@
           hmax = std::max (hmax, ext(1));
 #else
           //FIXME: find a better approximation
-          int len = ticklabels(i).length();
+          int len = ticklabels(i).length ();
           wmax = std::max (wmax, 0.5*fontsize*len);
           hmax = fontsize;
 #endif
@@ -6037,7 +6337,7 @@
   double val;
 
 #define FIX_LIMITS \
-  if (limits.numel() == 4) \
+  if (limits.numel () == 4) \
     { \
       val = limits(0); \
       if (! (xisinf (val) || xisnan (val))) \
@@ -6054,7 +6354,7 @@
     } \
   else \
     { \
-      limits.resize(4, 1); \
+      limits.resize (4, 1); \
       limits(0) = min_val; \
       limits(1) = max_val; \
       limits(2) = min_pos; \
@@ -6463,11 +6763,8 @@
   double max_neg_y = -octave_Inf;
   get_children_limits (miny, maxy, min_pos_y, max_neg_y, kids, 'y');
 
-  if (! (xscale_is ("log") && xlims(0) < 0 && xlims(1) < 0))
-    xlims = do_zoom (x, factor, xlims, xscale_is ("log"));
-
-  if (! (yscale_is ("log") && ylims(0) < 0 && ylims(1) < 0))
-    ylims = do_zoom (y, factor, ylims, yscale_is ("log"));
+  xlims = do_zoom (x, factor, xlims, xscale_is ("log"));
+  ylims = do_zoom (y, factor, ylims, yscale_is ("log"));
 
   zoom (xlims, ylims, push_to_zoom_stack);
 }
@@ -6475,14 +6772,6 @@
 void
 axes::properties::zoom (const Matrix& xl, const Matrix& yl, bool push_to_zoom_stack)
 {
-  // FIXME: Do we need error checking here?
-  Matrix xlims = get_xlim ().matrix_value ();
-  Matrix ylims = get_ylim ().matrix_value ();
-
-  if ((xscale_is ("log") && xlims(0) < 0 && xlims(1) < 0)
-      || (yscale_is ("log") && ylims(0) < 0 && ylims(1) < 0))
-    return;
-
   if (push_to_zoom_stack)
     {
       zoom_stack.push_front (xlimmode.get ());
@@ -6501,8 +6790,68 @@
   update_ylim (false);
 }
 
-void
-axes::properties::translate_view (double delta_x, double delta_y)
+static Matrix
+do_translate (double x0, double x1, const Matrix& lims, bool is_logscale)
+{
+  Matrix new_lims = lims;
+
+  double lo = lims(0);
+  double hi = lims(1);
+
+  bool is_negative = lo < 0 && hi < 0;
+
+  double delta;
+
+  if (is_logscale)
+    {
+      if (is_negative)
+        {
+          double tmp = hi;
+          hi = std::log10 (-lo);
+          lo = std::log10 (-tmp);
+          x0 = -x0;
+          x1 = -x1;
+        }
+      else
+        {
+          hi = std::log10 (hi);
+          lo = std::log10 (lo);
+        }
+
+      delta = std::log10 (x0) - std::log10 (x1);
+    }
+  else
+    {
+      delta = x0 - x1;
+    }
+
+  // Perform the translation
+  lo += delta;
+  hi += delta;
+
+  if (is_logscale)
+    {
+      if (is_negative)
+        {
+          double tmp = -std::pow (10.0, hi);
+          hi = -std::pow (10.0, lo);
+          lo = tmp;
+        }
+      else
+        {
+          lo = std::pow (10.0, lo);
+          hi = std::pow (10.0, hi);
+        }
+    }
+
+  new_lims(0) = lo;
+  new_lims(1) = hi;
+
+  return new_lims;
+}
+
+void
+axes::properties::translate_view (double x0, double x1, double y0, double y1)
 {
   // FIXME: Do we need error checking here?
   Matrix xlims = get_xlim ().matrix_value ();
@@ -6522,17 +6871,8 @@
   double max_neg_y = -octave_Inf;
   get_children_limits (miny, maxy, min_pos_y, max_neg_y, kids, 'y');
 
-  if (! xscale_is ("log"))
-    {
-      xlims (0) += delta_x;
-      xlims (1) += delta_x;
-    }
-
-  if (! yscale_is ("log"))
-    {
-      ylims (0) += delta_y;
-      ylims (1) += delta_y;
-    }
+  xlims = do_translate (x0, x1, xlims, xscale_is ("log"));
+  ylims = do_translate (y0, y1, ylims, yscale_is ("log"));
 
   zoom (xlims, ylims, false);
 }
@@ -6542,17 +6882,17 @@
 {
   Matrix v = get_view ().matrix_value ();
 
-  v (1) += delta_el;
-
-  if(v(1) > 90)
+  v(1) += delta_el;
+
+  if (v(1) > 90)
     v(1) = 90;
-  if(v(1) < -90)
+  if (v(1) < -90)
     v(1) = -90;
 
-  v (0) = fmod(v(0) - delta_az + 720,360);
-
-  set_view(v);
-  update_transform();
+  v(0) = fmod (v(0) - delta_az + 720,360);
+
+  set_view (v);
+  update_transform ();
 }
 
 void
@@ -6645,13 +6985,21 @@
 Matrix
 text::properties::get_extent_matrix (void) const
 {
+  // FIXME: Should this function also add the (x,y) base position?
   return extent.get ().matrix_value ();
 }
 
 octave_value
 text::properties::get_extent (void) const
 {
+  // FIXME: This doesn't work right for 3D plots.
+  // (It doesn't in Matlab either, at least not in version 6.5.)
   Matrix m = extent.get ().matrix_value ();
+  Matrix pos = get_position ().matrix_value ();
+  Matrix p = convert_text_position (pos, *this, get_units (), "pixels");
+
+  m(0) += p(0);
+  m(1) += p(1);
 
   return convert_text_position (m, *this, "pixels", get_units ());
 }
@@ -6682,12 +7030,14 @@
   else if (horizontalalignment_is ("right"))
     halign = 2;
 
-  if (verticalalignment_is ("top"))
+  if (verticalalignment_is ("middle"))
+    valign = 1;
+  else if (verticalalignment_is ("top"))
     valign = 2;
   else if (verticalalignment_is ("baseline"))
     valign = 3;
-  else if (verticalalignment_is ("middle"))
-    valign = 1;
+  else if (verticalalignment_is ("cap"))
+    valign = 4;
 
   Matrix bbox;
 
@@ -6699,6 +7049,10 @@
 
   renderer.text_to_pixels (sv.join ("\n"), pixels, bbox,
                            halign, valign, get_rotation ());
+  /* The bbox is relative to the text's position.
+     We'll leave it that way, because get_position () does not return
+     valid results when the text is first constructed.
+     Conversion to proper coordinates is performed in get_extent. */
   set_extent (bbox);
 
 #endif
@@ -6756,7 +7110,7 @@
       graphics_object go (gh_manager::get_object (get___myhandle__ ()));
       graphics_object ax (go.get_ancestor ("axes"));
 
-      parent_height = ax.get_properties ().get_boundingbox (true).elem(3);
+      parent_height = ax.get_properties ().get_boundingbox (true).elem (3);
     }
 
   return convert_font_size (fs, get_fontunits (), "points", parent_height);
@@ -6776,7 +7130,7 @@
 octave_value
 patch::properties::get_color_data (void) const
 {
-  octave_value fvc = get_facevertexcdata();
+  octave_value fvc = get_facevertexcdata ();
   if (fvc.is_undefined () || fvc.is_empty ())
     return Matrix ();
   else
@@ -6956,7 +7310,7 @@
       update_type = 'a';
     }
 
-  if (limits.numel() == 4)
+  if (limits.numel () == 4)
     {
       val = limits(0);
       if (! (xisinf (val) || xisnan (val)))
@@ -6973,7 +7327,7 @@
     }
   else
     {
-      limits.resize(4,1);
+      limits.resize (4,1);
       limits(0) = min_val;
       limits(1) = max_val;
       limits(2) = min_pos;
@@ -7179,7 +7533,7 @@
 void
 uicontrol::properties::set_style (const octave_value& st)
 {
-  if (get___object__ ().is_empty())
+  if (get___object__ ().is_empty ())
     style = st;
   else
     error ("set: cannot change the style of a uicontrol object after creation.");
@@ -7242,7 +7596,7 @@
   double parent_height = box_pix_height;
 
   if (fontunits_is ("normalized") && parent_height <= 0)
-    parent_height = get_boundingbox (false).elem(3);
+    parent_height = get_boundingbox (false).elem (3);
 
   return convert_font_size (fs, get_fontunits (), "points", parent_height);
 }
@@ -7378,7 +7732,7 @@
   double parent_height = box_pix_height;
 
   if (fontunits_is ("normalized") && parent_height <= 0)
-    parent_height = get_boundingbox (false).elem(3);
+    parent_height = get_boundingbox (false).elem (3);
 
   return convert_font_size (fs, get_fontunits (), "points", parent_height);
 }
@@ -7897,7 +8251,7 @@
 
   if (Vdrawnow_requested && ! old_Vdrawnow_requested)
     {
-      feval ("drawnow");
+      Fdrawnow ();
 
       Vdrawnow_requested = false;
     }
@@ -8127,7 +8481,7 @@
                         }
                       else
                         {
-                          error("set: number of graphics handles must match number of value rows (%d != %d)",
+                          error ("set: number of graphics handles must match number of value rows (%d != %d)",
                                 hcv.length (), args(2).cell_value ().rows ());
                           break;
 
@@ -8214,7 +8568,7 @@
 
   if (nargin == 1 || nargin == 2)
     {
-      if (args(0).is_empty())
+      if (args(0).is_empty ())
         {
           retval = Matrix ();
           return retval;
@@ -8359,7 +8713,7 @@
 }
 
 /*
-%!assert (get (findobj (0, 'Tag', 'nonexistenttag'), 'nonexistentproperty'), [])
+%!assert (get (findobj (0, "Tag", "nonexistenttag"), "nonexistentproperty"), [])
 */
 
 // Return all properties from the graphics handle @var{h}.
@@ -8617,7 +8971,7 @@
   if ((go.isa ("line") || go.isa ("patch")) && ! go.get("zdata").is_empty ())
     nd = 3;
 
-  Matrix kids = go.get_properties().get_children ();
+  Matrix kids = go.get_properties ().get_children ();
 
   for (octave_idx_type i = 0; i < kids.length (); i++)
     {
@@ -8625,9 +8979,9 @@
 
       if (hnd.ok ())
         {
-          const graphics_object& kid = gh_manager::get_object(hnd);
-
-          if (kid.valid_object())
+          const graphics_object& kid = gh_manager::get_object (hnd);
+
+          if (kid.valid_object ())
             nd = calc_dimensions (kid);
 
           if (nd == 3)
@@ -9556,7 +9910,7 @@
   if (obj)
     retval = obj.get (caseless_str (property));
   else
-    error ("%s: invalid handle (= %g)", func.c_str(), handle);
+    error ("%s: invalid handle (= %g)", func.c_str (), handle);
 
   return retval;
 }
@@ -9578,7 +9932,7 @@
         ret = true;
     }
   else
-    error ("%s: invalid handle (= %g)", func.c_str(), handle);
+    error ("%s: invalid handle (= %g)", func.c_str (), handle);
 
   return ret;
 }
@@ -9646,11 +10000,11 @@
 }
 
 static void
-cleanup_waitfor_postset_listener(const octave_value& listener)
+cleanup_waitfor_postset_listener (const octave_value& listener)
 { do_cleanup_waitfor_listener (listener, POSTSET); }
 
 static void
-cleanup_waitfor_predelete_listener(const octave_value& listener)
+cleanup_waitfor_predelete_listener (const octave_value& listener)
 { do_cleanup_waitfor_listener (listener, PREDELETE); }
 
 static octave_value_list
rename from src/graphics.h.in
rename to libinterp/interpfcn/graphics.in.h
--- a/src/graphics.h.in
+++ b/libinterp/interpfcn/graphics.in.h
@@ -222,10 +222,7 @@
     {
       Matrix retval (m.rows (), m.cols ());
 
-      if (m.any_element_is_positive ())
-        do_scale (m.data (), retval.fortran_vec (), m.numel ());
-      else
-        do_neg_scale (m.data (), retval.fortran_vec (), m.numel ());
+      do_scale (m.data (), retval.fortran_vec (), m.numel ());
 
       return retval;
     }
@@ -234,10 +231,7 @@
     {
       NDArray retval (m.dims ());
 
-      if (m.any_element_is_positive ())
-        do_scale (m.data (), retval.fortran_vec (), m.numel ());
-      else
-        do_neg_scale (m.data (), retval.fortran_vec (), m.numel ());
+      do_scale (m.data (), retval.fortran_vec (), m.numel ());
 
       return retval;
     }
@@ -255,13 +249,47 @@
   void do_scale (const double *src, double *dest, int n) const
     {
       for (int i = 0; i < n; i++)
-        dest[i] = log10(src[i]);
+        dest[i] = log10 (src[i]);
+    }
+};
+
+class neg_log_scaler : public base_scaler
+{
+public:
+  neg_log_scaler (void) { }
+
+  Matrix scale (const Matrix& m) const
+    {
+      Matrix retval (m.rows (), m.cols ());
+
+      do_scale (m.data (), retval.fortran_vec (), m.numel ());
+
+      return retval;
     }
 
-  void do_neg_scale (const double *src, double *dest, int n) const
+  NDArray scale (const NDArray& m) const
+    {
+      NDArray retval (m.dims ());
+
+      do_scale (m.data (), retval.fortran_vec (), m.numel ());
+
+      return retval;
+    }
+
+  double scale (double d) const
+    { return -log10 (-d); }
+
+  double unscale (double d) const
+    { return -pow (10.0, -d); }
+
+  base_scaler* clone (void) const
+    { return new neg_log_scaler (); }
+
+private:
+  void do_scale (const double *src, double *dest, int n) const
     {
       for (int i = 0; i < n; i++)
-        dest[i] = -log10(-src[i]);
+        dest[i] = -log10 (-src[i]);
     }
 };
 
@@ -270,12 +298,13 @@
 public:
   scaler (void) : rep (new base_scaler ()) { }
 
-  scaler (const scaler& s) : rep (s.rep->clone()) { }
+  scaler (const scaler& s) : rep (s.rep->clone ()) { }
 
   scaler (const std::string& s)
     : rep (s == "log"
            ? new log_scaler ()
-           : (s == "linear" ? new lin_scaler () : new base_scaler ()))
+           : (s == "neglog" ? new neg_log_scaler ()
+              : (s == "linear" ? new lin_scaler () : new base_scaler ())))
     { }
 
   ~scaler (void) { delete rep; }
@@ -318,6 +347,8 @@
 
       if (s == "log")
         rep = new log_scaler ();
+      else if (s == "neglog")
+        rep = new neg_log_scaler ();
       else if (s == "linear")
         rep = new lin_scaler ();
       else
@@ -433,8 +464,8 @@
             }
           if (found)
             {
-              for (int j = i; j < l.length() - 1; j++)
-                l(j) = l (j + 1);
+              for (int j = i; j < l.length () - 1; j++)
+                l(j) = l(j + 1);
 
               l.resize (l.length () - 1);
             }
@@ -1363,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 ()
     {
@@ -1382,7 +1413,7 @@
   octave_value get (void) const { return data; }
 
   void add_constraint (const std::string& type)
-    { type_constraints.push_back (type); }
+    { type_constraints.insert (type); }
 
   void add_constraint (const dim_vector& dims)
     { size_constraints.push_back (dims); }
@@ -1423,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 ();
 
@@ -1455,7 +1488,7 @@
   double xmax;
   double xminp;
   double xmaxp;
-  std::list<std::string> type_constraints;
+  std::set<std::string> type_constraints;
   std::list<dim_vector> size_constraints;
 };
 
@@ -2310,7 +2343,7 @@
 
   ~gtk_manager (void) { }
 
-  static void create_instance (void);
+  OCTINTERP_API static void create_instance (void);
 
   static bool instance_ok (void)
   {
@@ -2331,7 +2364,7 @@
 
   static void cleanup_instance (void) { delete instance; instance = 0; }
 
-  static gtk_manager *instance;
+  OCTINTERP_API static gtk_manager *instance;
 
   // The name of the default toolkit.
   std::string dtk;
@@ -3123,6 +3156,9 @@
   public:
     void remove_child (const graphics_handle& h);
 
+    Matrix get_boundingbox (bool internal = false,
+                            const Matrix& parent_pix_size = Matrix ()) const;
+
     // See the genprops.awk script for an explanation of the
     // properties declarations.
 
@@ -3216,7 +3252,7 @@
         retval = factory_properties.lookup (name);
 
         if (retval.is_undefined ())
-          error ("get: invalid default property `%s'", name.c_str ());
+          error ("get: invalid default property '%s'", name.c_str ());
       }
 
     return retval;
@@ -3227,7 +3263,7 @@
     octave_value retval = factory_properties.lookup (name);
 
     if (retval.is_undefined ())
-      error ("get: invalid factory default property `%s'", name.c_str ());
+      error ("get: invalid factory default property '%s'", name.c_str ());
 
     return retval;
   }
@@ -3340,7 +3376,7 @@
       callback_property closerequestfcn , "closereq"
       handle_property currentaxes S , graphics_handle ()
       array_property colormap , jet_colormap ()
-      radio_property paperorientation , "{portrait}|landscape|rotated"
+      radio_property paperorientation U , "{portrait}|landscape|rotated"
       color_property color , color_property (color_values (1, 1, 1), radio_values ("none"))
       array_property alphamap , Matrix (64, 1, 1)
       string_property currentcharacter r , ""
@@ -3663,7 +3699,7 @@
     void zoom_about_point (double x, double y, double factor,
                            bool push_to_zoom_stack = true);
     void zoom (const Matrix& xl, const Matrix& yl, bool push_to_zoom_stack = true);
-    void translate_view (double delta_x, double delta_y);
+    void translate_view (double x0, double x1, double y0, double y1);
     void rotate_view (double delta_az, double delta_el);
     void unzoom (void);
     void clear_zoom_stack (void);
@@ -3790,7 +3826,7 @@
       radio_property projection , "{orthographic}|perpective"
       radio_property tickdir mu , "{in}|out"
       radio_property tickdirmode u , "{auto}|manual"
-      array_property ticklength , default_axes_ticklength ()
+      array_property ticklength u , default_axes_ticklength ()
       array_property tightinset r , Matrix (1, 4, 0.0)
       // FIXME -- uicontextmenu should be moved here.
       radio_property units SU , "{normalized}|inches|centimeters|points|pixels|characters"
@@ -3814,9 +3850,32 @@
     void init (void);
 
   private:
-    void update_xscale (void) { sx = get_xscale (); }
-    void update_yscale (void) { sy = get_yscale (); }
-    void update_zscale (void) { sz = get_zscale (); }
+
+    std::string
+    get_scale (const std::string& scale, const Matrix& lims)
+    {
+      std::string retval = scale;
+
+      if (scale == "log" && lims.numel () > 1 && lims(0) < 0 && lims(1) < 0)
+        retval = "neglog";
+
+      return retval;
+    }
+
+    void update_xscale (void)
+    {
+      sx = get_scale (get_xscale (), xlim.get ().matrix_value ());
+    }
+
+    void update_yscale (void)
+    {
+      sy = get_scale (get_yscale (), ylim.get ().matrix_value ());
+    }
+
+    void update_zscale (void)
+    {
+      sz = get_scale (get_zscale (), zlim.get ().matrix_value ());
+    }
 
     void update_view (void) { sync_positions (); }
     void update_dataaspectratio (void) { sync_positions (); }
@@ -3840,9 +3899,9 @@
     void update_ydir (void) { update_camera (); update_axes_layout (); }
     void update_zdir (void) { update_camera (); update_axes_layout (); }
 
-    void update_ticklengths (void);
-    void update_tickdir (void) { update_ticklengths (); }
-    void update_tickdirmode (void) { update_ticklengths (); }
+    void update_ticklength (void);
+    void update_tickdir (void) { update_ticklength (); }
+    void update_tickdirmode (void) { update_ticklength (); }
 
     void update_xtick (void)
       {
@@ -3968,6 +4027,8 @@
 
       fix_limits (xlim);
 
+      update_xscale ();
+
       if (do_clr_zoom)
         zoom_stack.clear ();
 
@@ -3983,6 +4044,8 @@
 
       fix_limits (ylim);
 
+      update_yscale ();
+
       if (do_clr_zoom)
         zoom_stack.clear ();
 
@@ -3998,6 +4061,8 @@
 
       fix_limits (zlim);
 
+      update_zscale ();
+
       zoom_stack.clear ();
 
       update_axes_layout ();
@@ -4172,13 +4237,38 @@
   public:
     double get_fontsize_points (double box_pix_height = 0) const;
 
+    void set_position (const octave_value& val)
+    {
+      if (! error_state)
+        {
+          octave_value new_val (val);
+    
+          if (new_val.numel () == 2)
+            {
+              dim_vector dv (1, 3);
+    
+              new_val = new_val.resize (dv, true);
+            }
+
+          if (position.set (new_val, false))
+            {
+              set_positionmode ("manual");
+              update_position ();
+              position.run_listeners (POSTSET);
+              mark_modified ();
+            }
+          else
+            set_positionmode ("manual");
+        }
+    }
+
     // See the genprops.awk script for an explanation of the
     // properties declarations.
 
     BEGIN_PROPERTIES (text)
       text_label_property string u , ""
       radio_property units u , "{data}|pixels|normalized|inches|centimeters|points"
-      array_property position mu , Matrix (1, 3, 0.0)
+      array_property position smu , Matrix (1, 3, 0.0)
       double_property rotation mu , 0
       radio_property horizontalalignment mu , "{left}|center|right"
       color_property color u , color_values (0, 0, 0)
@@ -4224,7 +4314,6 @@
   protected:
     void init (void)
       {
-        position.add_constraint (dim_vector (1, 2));
         position.add_constraint (dim_vector (1, 3));
         cached_units = get_units ();
         update_font ();
@@ -4326,9 +4415,9 @@
       array_property cdata u , Matrix ()
       radio_property cdatamapping al , "{scaled}|direct"
       // hidden properties for limit computation
-      row_vector_property xlim hlr , Matrix()
-      row_vector_property ylim hlr , Matrix()
-      row_vector_property clim hlr , Matrix()
+      row_vector_property xlim hlr , Matrix ()
+      row_vector_property ylim hlr , Matrix ()
+      row_vector_property clim hlr , Matrix ()
       bool_property xliminclude hl , "on"
       bool_property yliminclude hl , "on"
       bool_property climinclude hlg , "on"
@@ -4345,6 +4434,7 @@
         cdata.add_constraint ("uint8");
         cdata.add_constraint ("uint16");
         cdata.add_constraint ("int16");
+        cdata.add_constraint ("real");
         cdata.add_constraint (dim_vector (-1, -1));
         cdata.add_constraint (dim_vector (-1, -1, 3));
       }
@@ -4722,12 +4812,14 @@
     // properties declarations.
 
     BEGIN_PROPERTIES (hggroup)
+      string_property displayname , ""
+      radio_property erasemode , "{normal}|none|xor|background"
       // hidden properties for limit computation
-      row_vector_property xlim hr , Matrix()
-      row_vector_property ylim hr , Matrix()
-      row_vector_property zlim hr , Matrix()
-      row_vector_property clim hr , Matrix()
-      row_vector_property alim hr , Matrix()
+      row_vector_property xlim hr , Matrix ()
+      row_vector_property ylim hr , Matrix ()
+      row_vector_property zlim hr , Matrix ()
+      row_vector_property clim hr , Matrix ()
+      row_vector_property alim hr , Matrix ()
       bool_property xliminclude h , "on"
       bool_property yliminclude h , "on"
       bool_property zliminclude h , "on"
@@ -4795,7 +4887,7 @@
     BEGIN_PROPERTIES (uimenu)
       any_property __object__ , Matrix ()
       string_property accelerator , ""
-      callback_property callback , Matrix()
+      callback_property callback , Matrix ()
       bool_property checked , "off"
       bool_property enable , "on"
       color_property foregroundcolor , color_values (0, 0, 0)
@@ -4843,7 +4935,7 @@
 
     BEGIN_PROPERTIES (uicontextmenu)
       any_property __object__ , Matrix ()
-      callback_property callback , Matrix()
+      callback_property callback , Matrix ()
       array_property position , Matrix (1, 2, 0.0)
     END_PROPERTIES
 
@@ -5136,7 +5228,7 @@
     BEGIN_PROPERTIES (uipushtool)
       any_property __object__ , Matrix ()
       array_property cdata , Matrix ()
-      callback_property clickedcallback , Matrix()
+      callback_property clickedcallback , Matrix ()
       bool_property enable , "on"
       bool_property separator , "off"
       string_property tooltipstring , ""
@@ -5186,10 +5278,10 @@
     BEGIN_PROPERTIES (uitoggletool)
       any_property __object__ , Matrix ()
       array_property cdata , Matrix ()
-      callback_property clickedcallback , Matrix()
+      callback_property clickedcallback , Matrix ()
       bool_property enable , "on"
-      callback_property offcallback , Matrix()
-      callback_property oncallback , Matrix()
+      callback_property offcallback , Matrix ()
+      callback_property oncallback , Matrix ()
       bool_property separator , "off"
       bool_property state , "off"
       string_property tooltipstring , ""
rename from src/help.cc
rename to libinterp/interpfcn/help.cc
--- a/src/help.cc
+++ b/libinterp/interpfcn/help.cc
@@ -71,6 +71,11 @@
 // (--doc-cache-file file)
 std::string Vdoc_cache_file;
 
+// Name of the file containing local Texinfo macros that are prepended
+// to doc strings before processing.
+// (--texi-macros-file)
+std::string Vtexi_macros_file;
+
 // Name of the info file specified on command line.
 // (--info-file file)
 std::string Vinfo_file;
@@ -139,14 +144,14 @@
     "-*- texinfo -*-\n\
 @deftypefn {Operator} {} #\n\
 Begin comment character.\n\
-@seealso{%, #@{}\n\
+@seealso{%, #@\\{}\n\
 @end deftypefn"),
 
   pair_type ("%",
     "-*- texinfo -*-\n\
 @deftypefn {Operator} {} %\n\
 Begin comment character.\n\
-@seealso{#, %@{}\n\
+@seealso{#, %@\\{}\n\
 @end deftypefn"),
 
   pair_type ("#{",
@@ -155,7 +160,7 @@
 Begin block comment.  There must be nothing else, other than\n\
 whitespace, in the line both before and after @code{#@{}.\n\
 It is possible to nest block comments.\n\
-@seealso{%@{, #@}, #}\n\
+@seealso{%@\\{, #@\\}, #}\n\
 @end deftypefn"),
 
   pair_type ("%{",
@@ -164,7 +169,7 @@
 Begin block comment.  There must be nothing else, other than\n\
 whitespace, in the line both before and after @code{%@{}.\n\
 It is possible to nest block comments.\n\
-@seealso{#@{, %@}, %}\n\
+@seealso{#@\\{, %@\\}, %}\n\
 @end deftypefn"),
 
   pair_type ("#}",
@@ -173,7 +178,7 @@
 Close block comment.  There must be nothing else, other than\n\
 whitespace, in the line both before and after @code{#@}}.\n\
 It is possible to nest block comments.\n\
-@seealso{%@}, #@{, #}\n\
+@seealso{%@\\}, #@\\{, #}\n\
 @end deftypefn"),
 
   pair_type ("%}",
@@ -182,7 +187,7 @@
 Close block comment.  There must be nothing else, other than\n\
 whitespace, in the line both before and after @code{%@}}.\n\
 It is possible to nest block comments.\n\
-@seealso{#@}, %@{, %}\n\
+@seealso{#@\\}, %@\\{, %}\n\
 @end deftypefn"),
 
   pair_type ("...",
@@ -473,7 +478,16 @@
 @deftypefn {Keyword} {} do\n\
 Begin a do-until loop.  This differs from a do-while loop in that the\n\
 body of the loop is executed at least once.\n\
-@seealso{while}\n\
+\n\
+@example\n\
+@group\n\
+i = 0;\n\
+do\n\
+  i++\n\
+until (i == 10)\n\
+@end group\n\
+@end example\n\
+@seealso{for, until, while}\n\
 @end deftypefn"),
 
   pair_type ("else",
@@ -587,7 +601,7 @@
 @example\n\
 @group\n\
 global @var{x};\n\
-if isempty (@var{x})\n\
+if (isempty (@var{x}))\n\
   x = 1;\n\
 endif\n\
 @end group\n\
@@ -703,7 +717,7 @@
   pair_type ("until",
     "-*- texinfo -*-\n\
 @deftypefn {Keyword} {} until\n\
-End a do-until loop.\n\
+End a do-until loop.  See @code{do} for an example.\n\
 @seealso{do}\n\
 @end deftypefn"),
 
@@ -746,7 +760,16 @@
     "-*- texinfo -*-\n\
 @deftypefn {Keyword} {} while\n\
 Begin a while loop.\n\
-@seealso{do}\n\
+\n\
+@example\n\
+@group\n\
+i = 0;\n\
+while (i < 10)\n\
+  i++\n\
+endwhile\n\
+@end group\n\
+@end example\n\
+@seealso{do, endwhile, for, until}\n\
 @end deftypefn"),
 };
 
@@ -757,7 +780,7 @@
   string_vector retval (lst.size ());
   int j = 0;
   for (map_iter iter = lst.begin (); iter != lst.end (); iter ++)
-    retval [j++] = iter->first;
+    retval[j++] = iter->first;
   return retval;
 }
 
@@ -879,11 +902,6 @@
 {
   bool retval = false;
 
-  // FIXME -- this is a bit of a kluge...
-  unwind_protect frame;
-  frame.protect_var (reading_script_file);
-  reading_script_file = true;
-
   h = get_help_from_file (nm, symbol_found, file);
 
   if (h.length () > 0)
@@ -917,6 +935,95 @@
   return h;
 }
 
+
+DEFUN (built_in_docstrings_file, args, nargout,
+  "-*- texinfo -*-\n\
+@deftypefn  {Built-in Function} {@var{val} =} built_in_docstrings_file ()\n\
+@deftypefnx {Built-in Function} {@var{old_val} =} built_in_docstrings_file (@var{new_val})\n\
+@deftypefnx {Built-in Function} {} built_in_docstrings_file (@var{new_val}, \"local\")\n\
+Query or set the internal variable that specifies the name of the\n\
+file containing docstrings for built-in Octave functions.\n\
+\n\
+Note that this variable is only used when Octave is initializing itself,\n\
+so setting it will have no effect.\n\
+@end deftypefn")
+{
+  return SET_NONEMPTY_INTERNAL_STRING_VARIABLE (built_in_docstrings_file);
+}
+
+void
+install_built_in_docstrings (void)
+{
+  std::string fname = Vbuilt_in_docstrings_file;
+
+  std::ifstream file (fname.c_str (), std::ios::in | std::ios::binary);
+
+  if (file)
+    {
+      // Ignore header;
+      file.ignore (1000, 0x1f);
+
+      if (file.gcount () == 1000)
+        {
+          // We use std::cerr here instead of calling Octave's warning
+          // function because install_built_in_docstrings is called
+          // before the interpreter is initialized, so warning messages
+          // won't work properly.
+
+          std::cerr << "warning: is builtin-docstrings file corrupted?"
+                    << std::endl;
+          return;
+        }
+
+      // FIXME -- eliminate fixed buffer size.
+      size_t bufsize = 100000;
+
+      OCTAVE_LOCAL_BUFFER (char, buf, bufsize);
+
+      while (! file.eof ())
+        {
+          file.getline (buf, bufsize, 0x1f);
+
+          std::string tmp (buf);
+
+          size_t pos = tmp.find ('\n');
+
+          std::string fcn = tmp.substr (0, pos);
+
+          octave_value ov = symbol_table::find_built_in_function (fcn);
+
+          if (ov.is_defined ())
+            {
+              octave_function *fp = ov.function_value ();
+
+              if (fp)
+                {
+                  tmp = tmp.substr (pos+1);
+
+                  // Strip @c FILENAME which is part of current DOCSTRINGS
+                  // syntax.  This may disappear if a specific format for
+                  // docstring files is developed.
+                  while (tmp.length () > 2 && tmp[0] == '@' && tmp[1] == 'c')
+                    {
+                      pos = tmp.find ('\n');
+                      tmp = tmp.substr (pos+1);
+                    }
+
+                  fp->document (tmp);
+                }
+            }
+        }
+    }
+  else
+    {
+      // See note above about using std::cerr instead of warning.
+
+      std::cerr << "warning: docstring file '" << fname << "' not found"
+                << std::endl;
+    }
+
+}
+
 static void
 do_get_help_text (const std::string& name, std::string& text,
                   std::string& format)
@@ -949,7 +1056,7 @@
 }
 
 DEFUN (get_help_text, args, , "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {[@var{text}, @var{format}] =} get_help_text (@var{name})\n\
+@deftypefn {Built-in Function} {[@var{text}, @var{format}] =} get_help_text (@var{name})\n\
 Return the raw help text of function @var{name}.\n\
 \n\
 The raw help text is returned in @var{text} and the format in @var{format}\n\
@@ -1018,7 +1125,7 @@
 
 DEFUN (get_help_text_from_file, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {[@var{text}, @var{format}] =} get_help_text_from_file (@var{fname})\n\
+@deftypefn {Built-in Function} {[@var{text}, @var{format}] =} get_help_text_from_file (@var{fname})\n\
 Return the raw help text from the file @var{fname}.\n\
 \n\
 The raw help text is returned in @var{text} and the format in @var{format}\n\
@@ -1113,7 +1220,10 @@
                   if (fcn->is_user_function ())
                     type = "command-line function";
                   else
-                    type = "built-in function";
+                    {
+                      file = fcn->src_file_name ();
+                      type = "built-in function";
+                    }
                 }
               else
                 type = val.is_user_script ()
@@ -1210,11 +1320,11 @@
     {
       const int dir_len = dir.size ();
       const int filename_len = filename.size ();
-      const int max_allowed_seps = file_ops::is_dir_sep (dir [dir_len-1]) ? 0 : 1;
+      const int max_allowed_seps = file_ops::is_dir_sep (dir[dir_len-1]) ? 0 : 1;
 
       int num_seps = 0;
       for (int i = dir_len; i < filename_len; i++)
-        if (file_ops::is_dir_sep (filename [i]))
+        if (file_ops::is_dir_sep (filename[i]))
           num_seps ++;
 
       return (num_seps <= max_allowed_seps);
@@ -1291,6 +1401,30 @@
   return SET_NONEMPTY_INTERNAL_STRING_VARIABLE (doc_cache_file);
 }
 
+DEFUN (texi_macros_file, args, nargout,
+  "-*- texinfo -*-\n\
+@deftypefn  {Built-in Function} {@var{val} =} texi_macros_file ()\n\
+@deftypefnx {Built-in Function} {@var{old_val} =} texi_macros_file (@var{new_val})\n\
+@deftypefnx {Built-in Function} {} texi_macros_file (@var{new_val}, \"local\")\n\
+Query or set the internal variable that specifies the name of the\n\
+file containing Texinfo macros that are prepended to documentation strings\n\
+before they are passed to makeinfo.  The default value is \n\
+@file{@var{octave-home}/share/octave/@var{version}/etc/macros.texi},\n\
+in which @var{octave-home} is the root directory of the Octave installation,\n\
+and @var{version} is the Octave version number.\n\
+The default value may be overridden by the environment variable\n\
+@w{@env{OCTAVE_TEXI_MACROS_FILE}}, or the command line argument\n\
+@samp{--texi-macros-file NAME}.\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{makeinfo_program}\n\
+@end deftypefn")
+{
+  return SET_NONEMPTY_INTERNAL_STRING_VARIABLE (texi_macros_file);
+}
+
 DEFUN (info_file, args, nargout,
   "-*- texinfo -*-\n\
 @deftypefn  {Built-in Function} {@var{val} =} info_file ()\n\
@@ -1349,7 +1483,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{info_file, info_program, doc, help}\n\
+@seealso{texi_macros_file, info_file, info_program, doc, help}\n\
 @end deftypefn")
 {
   return SET_NONEMPTY_INTERNAL_STRING_VARIABLE (makeinfo_program);
rename from src/help.h
rename to libinterp/interpfcn/help.h
--- a/src/help.h
+++ b/libinterp/interpfcn/help.h
@@ -32,18 +32,25 @@
 
 extern OCTINTERP_API std::string raw_help (const std::string&, bool&);
 
+extern OCTINTERP_API void install_built_in_docstrings (void);
+
 // 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 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
new file mode 100644
--- /dev/null
+++ b/libinterp/interpfcn/hook-fcn.cc
@@ -0,0 +1,41 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+
+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/>.
+
+*/
+
+#include <config.h>
+
+#include "hook-fcn.h"
+
+hook_function::hook_function (const octave_value& f, const octave_value& d)
+{
+  if (f.is_string ())
+    {
+      std::string name = f.string_value ();
+
+      rep = new named_hook_function (name, d);
+    }
+  else if (f.is_function_handle ())
+    {
+      rep = new fcn_handle_hook_function (f, d);
+    }
+  else
+    error ("invalid hook function");
+}
new file mode 100644
--- /dev/null
+++ b/libinterp/interpfcn/hook-fcn.h
@@ -0,0 +1,262 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+
+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_hook_fcn_h)
+#define octave_hook_fcn_h 1
+
+#include <string>
+
+#include "oct-obj.h"
+#include "ov.h"
+#include "ov-fcn-handle.h"
+#include "parse.h"
+#include "variables.h"
+
+class
+base_hook_function
+{
+public:
+
+  friend class hook_function;
+
+  base_hook_function (void) : count (1) { }
+
+  base_hook_function (const base_hook_function&) : count (1) { }
+
+  virtual ~base_hook_function (void) { }
+
+  virtual std::string id (void) { return std::string (); }
+
+  virtual bool is_valid (void) { return false; }
+
+  virtual void eval (const octave_value_list&) { }
+
+protected:
+
+  size_t count;
+};
+
+class
+hook_function
+{
+public:
+
+  hook_function (void)
+  {
+    static base_hook_function nil_rep;
+    rep = &nil_rep;
+    rep->count++;
+  }
+
+  hook_function (const octave_value& f,
+                 const octave_value& d = octave_value ());
+
+  ~hook_function (void)
+  {
+    if (--rep->count == 0)
+      delete rep;
+  }
+
+  hook_function (const hook_function& hf)
+    : rep (hf.rep)
+  {
+    rep->count++;
+  }
+
+  hook_function& operator = (const hook_function& hf)
+  {
+    if (rep != hf.rep)
+      {
+        if (--rep->count == 0)
+          delete rep;
+
+        rep = hf.rep;
+        rep->count++;
+      }
+
+    return *this;
+  }
+
+  std::string id (void) { return rep->id (); }
+
+  bool is_valid (void) { return rep->is_valid (); }
+
+  void eval (const octave_value_list& initial_args)
+  {
+    rep->eval (initial_args);
+  }
+
+private:
+
+  base_hook_function *rep;
+};
+
+class
+named_hook_function : public base_hook_function
+{
+public:
+
+  named_hook_function (const std::string& n, const octave_value& d)
+    : name (n), data (d)
+  { }
+
+  void eval (const octave_value_list& initial_args)
+  {
+    octave_value_list args = initial_args;
+
+    if (data.is_defined ())
+      args.append (data);
+
+    feval (name, args, 0);
+  }
+
+  std::string id (void) { return name; }
+
+  bool is_valid (void) { return is_valid_function (name); }
+
+private:
+
+  std::string name;
+
+  octave_value data;
+};
+
+class
+fcn_handle_hook_function : public base_hook_function
+{
+public:
+
+  fcn_handle_hook_function (const octave_value& fh_arg, const octave_value& d)
+    : ident (), valid (false), fcn_handle (fh_arg), data (d)
+  {
+    octave_fcn_handle *fh = fcn_handle.fcn_handle_value (true);
+
+    if (fh)
+      {
+        valid = true;
+
+        std::ostringstream buf;
+        buf << fh;
+        ident = fh->fcn_name () + ":" + buf.str ();
+      }
+  }
+
+  void eval (const octave_value_list& initial_args)
+  {
+    octave_value_list args = initial_args;
+
+    if (data.is_defined ())
+      args.append (data);
+
+    fcn_handle.do_multi_index_op (0, args);
+  }
+
+  std::string id (void) { return ident; }
+
+  bool is_valid (void) { return valid; }
+
+private:
+
+  std::string ident;
+
+  bool valid;
+
+  octave_value fcn_handle;
+
+  octave_value data;
+};
+
+class
+hook_function_list
+{
+public:
+
+  typedef std::map<std::string, hook_function> map_type;
+
+  typedef map_type::iterator iterator;
+  typedef map_type::const_iterator const_iterator;
+
+  hook_function_list (void) : fcn_map () { }
+
+  ~hook_function_list (void) { }
+
+  hook_function_list (const hook_function_list& lst)
+    : fcn_map (lst.fcn_map)
+  { }
+
+  hook_function_list& operator = (const hook_function_list& lst)
+  {
+    if (&lst != this)
+      fcn_map = lst.fcn_map;
+
+    return *this;
+  }
+
+  bool empty (void) const { return fcn_map.empty (); }
+
+  void clear (void) { fcn_map.clear (); }
+
+  void insert (const std::string& id, const hook_function& f)
+  {
+    fcn_map[id] = f;
+  }
+
+  iterator find (const std::string& id)
+  {
+    return fcn_map.find (id);
+  }
+
+  const_iterator find (const std::string& id) const
+  {
+    return fcn_map.find (id);
+  }
+
+  iterator end (void) { return fcn_map.end (); }
+
+  const_iterator end (void) const { return fcn_map.end (); }
+
+  void erase (iterator p) { fcn_map.erase (p); }
+
+  void run (const octave_value_list& initial_args = octave_value_list ())
+  {
+    iterator p = fcn_map.begin ();
+
+    while (p != fcn_map.end ())
+      {
+        std::string hook_fcn_id = p->first;
+        hook_function hook_fcn = p->second;
+
+        iterator q = p++;
+
+        if (hook_fcn.is_valid ())
+          hook_fcn.eval (initial_args);
+        else
+          fcn_map.erase (q);
+      }
+  }
+
+private:
+
+  map_type fcn_map;
+};
+
+#endif
rename from src/input.cc
rename to libinterp/interpfcn/input.cc
--- a/src/input.cc
+++ b/libinterp/interpfcn/input.cc
@@ -49,13 +49,17 @@
 #include "error.h"
 #include "gripes.h"
 #include "help.h"
+#include "hook-fcn.h"
 #include "input.h"
 #include "lex.h"
 #include "load-path.h"
+#include "octave-link.h"
 #include "oct-map.h"
 #include "oct-hist.h"
 #include "toplev.h"
+#include "octave-link.h"
 #include "oct-obj.h"
+#include "ov-fcn-handle.h"
 #include "pager.h"
 #include "parse.h"
 #include "pathlen.h"
@@ -64,6 +68,7 @@
 #include "pt-eval.h"
 #include "pt-stmt.h"
 #include "sighandlers.h"
+#include "symtab.h"
 #include "sysdep.h"
 #include "toplev.h"
 #include "unwind-prot.h"
@@ -71,10 +76,10 @@
 #include "variables.h"
 
 // Primary prompt string.
-static std::string VPS1 = "\\s:\\#> ";
+static std::string VPS1;
 
 // Secondary prompt string.
-static std::string VPS2 = "> ";
+static std::string VPS2;
 
 // String printed before echoed input (enabled by --echo-input).
 std::string VPS4 = "+ ";
@@ -94,53 +99,12 @@
 // Character to append after successful command-line completion attempts.
 static char Vcompletion_append_char = ' ';
 
-// Global pointer for eval().
-std::string current_eval_string;
-
-// TRUE means get input from current_eval_string.
-bool get_input_from_eval_string = false;
-
-// TRUE means we haven't been asked for the input from
-// current_eval_string yet.
-bool input_from_eval_string_pending = false;
-
-// TRUE means that input is coming from a file that was named on
-// the command line.
-bool input_from_command_line_file = false;
-
-// TRUE means that stdin is a terminal, not a pipe or redirected file.
-bool stdin_is_tty = false;
-
-// TRUE means we're parsing a function file.
-bool reading_fcn_file = false;
-
-// TRUE means we're parsing a classdef file.
-bool reading_classdef_file = false;
-
-// Simple name of function file we are reading.
-std::string curr_fcn_file_name;
-
-// Full name of file we are reading.
-std::string curr_fcn_file_full_name;
-
-// TRUE means we're parsing a script file.
-bool reading_script_file = false;
-
-// If we are reading from an M-file, this is it.
-FILE *ff_instream = 0;
-
 // TRUE means this is an interactive shell.
 bool interactive = false;
 
 // TRUE means the user forced this shell to be interactive (-i).
 bool forced_interactive = false;
 
-// Should we issue a prompt?
-int promptflag = 1;
-
-// The current line of input, from wherever.
-std::string current_input_line;
-
 // TRUE after a call to completion_matches.
 bool octave_completion_matches_called = false;
 
@@ -153,7 +117,7 @@
 
 // If we are in debugging mode, this is the last command entered, so
 // that we can repeat the previous command if the user just types RET.
-static std::string last_debugging_command;
+static std::string last_debugging_command = "\n";
 
 // TRUE if we are running in the Emacs GUD mode.
 static bool Vgud_mode = false;
@@ -161,10 +125,29 @@
 // The filemarker used to separate filenames from subfunction names
 char Vfilemarker = '>';
 
-static void
-do_input_echo (const std::string& input_string)
+static hook_function_list input_event_hook_functions;
+
+// For octave_quit.
+void
+remove_input_event_hook_functions (void)
+{
+  input_event_hook_functions.clear ();
+}
+
+void
+set_default_prompts (void)
 {
-  int do_echo = reading_script_file ?
+  VPS1 = "\\s:\\#> ";
+  VPS2 = "> ";
+  VPS4 = "+ ";
+
+  octave_link::set_default_prompts (VPS1, VPS2, VPS4);
+}
+
+void
+octave_base_reader::do_input_echo (const std::string& input_string) const
+{
+  int do_echo = LEXER->reading_script_file ?
     (Vecho_executing_commands & ECHO_SCRIPTS)
       : (Vecho_executing_commands & ECHO_CMD_LINE) && ! forced_interactive;
 
@@ -172,7 +155,7 @@
     {
       if (forced_interactive)
         {
-          if (promptflag > 0)
+          if (pflag > 0)
             octave_stdout << command_editor::decode_prompt_string (VPS1);
           else
             octave_stdout << command_editor::decode_prompt_string (VPS2);
@@ -190,45 +173,23 @@
     }
 }
 
-std::string
-gnu_readline (const std::string& s, bool force_readline)
+static std::string
+gnu_readline (const std::string& s, bool& eof)
 {
   octave_quit ();
 
-  std::string retval;
-
-  if (line_editing || force_readline)
-    {
-      bool eof;
-
-      retval = command_editor::readline (s, eof);
+  eof = false;
 
-      if (! eof && retval.empty ())
-        retval = "\n";
-    }
-  else
-    {
-      if (! s.empty () && (interactive || forced_interactive))
-        {
-          FILE *stream = command_editor::get_output_stream ();
+  std::string retval = command_editor::readline (s, eof);
 
-          gnulib::fputs (s.c_str (), stream);
-          gnulib::fflush (stream);
-        }
-
-      FILE *curr_stream = command_editor::get_input_stream ();
-
-      if (reading_fcn_file || reading_script_file || reading_classdef_file)
-        curr_stream = ff_instream;
-
-      retval = octave_fgets (curr_stream);
-    }
+  if (! eof && retval.empty ())
+    retval = "\n";
 
   return retval;
 }
 
 static inline std::string
-interactive_input (const std::string& s, bool force_readline = false)
+interactive_input (const std::string& s, bool& eof)
 {
   Vlast_prompt_time.stamp ();
 
@@ -247,201 +208,93 @@
         return "\n";
     }
 
-  return gnu_readline (s, force_readline);
+  return gnu_readline (s, eof);
 }
 
-static std::string
-octave_gets (void)
+std::string
+octave_base_reader::octave_gets (bool& eof)
 {
   octave_quit ();
 
-  std::string retval;
-
-  bool history_skip_auto_repeated_debugging_command = false;
-
-  if ((interactive || forced_interactive)
-      && (! (reading_fcn_file
-             || reading_classdef_file
-             || reading_script_file
-             || get_input_from_eval_string
-             || input_from_startup_file
-             || input_from_command_line_file)))
-    {
-      std::string ps = (promptflag > 0) ? VPS1 : VPS2;
-
-      std::string prompt = command_editor::decode_prompt_string (ps);
-
-      pipe_handler_error_count = 0;
-
-      flush_octave_stdout ();
-
-      octave_pager_stream::reset ();
-      octave_diary_stream::reset ();
-
-      octave_diary << prompt;
-
-      retval = interactive_input (prompt);
-
-      // There is no need to update the load_path cache if there is no
-      // user input.
-      if (! retval.empty ()
-          && retval.find_first_not_of (" \t\n\r") != std::string::npos)
-        {
-          load_path::update ();
-
-          if (Vdebugging)
-            last_debugging_command = retval;
-          else
-            last_debugging_command = std::string ();
-        }
-      else if (Vdebugging)
-        {
-          retval = last_debugging_command;
-          history_skip_auto_repeated_debugging_command = true;
-        }
-    }
-  else
-    retval = gnu_readline ("");
-
-  current_input_line = retval;
-
-  if (! current_input_line.empty ())
-    {
-      if (! (input_from_startup_file || input_from_command_line_file
-             || history_skip_auto_repeated_debugging_command))
-        command_history::add (current_input_line);
-
-      if (! (reading_fcn_file || reading_script_file || reading_classdef_file))
-        {
-          octave_diary << current_input_line;
-
-          if (current_input_line[current_input_line.length () - 1] != '\n')
-            octave_diary << "\n";
-        }
-
-      do_input_echo (current_input_line);
-    }
-  else if (! (reading_fcn_file || reading_script_file || reading_classdef_file))
-    octave_diary << "\n";
-
-  return retval;
-}
-
-// Read a line from the input stream.
-
-static std::string
-get_user_input (void)
-{
-  octave_quit ();
+  eof = false;
 
   std::string retval;
 
-  if (get_input_from_eval_string)
-    {
-      if (input_from_eval_string_pending)
-        {
-          input_from_eval_string_pending = false;
-
-          retval = current_eval_string;
-
-          size_t len = retval.length ();
-
-          if (len > 0 && retval[len-1] != '\n')
-            retval.append ("\n");
-        }
-    }
-  else
-    retval = octave_gets ();
-
-  current_input_line = retval;
+  // Process pre input event hook function prior to flushing output and
+  // printing the prompt.
 
-  return retval;
-}
-
-int
-octave_read (char *buf, unsigned max_size)
-{
-  // FIXME -- is this a safe way to buffer the input?
+  if (interactive || forced_interactive)
+    {
+      if (! Vdebugging)
+        octave_link::exit_debugger_event ();
 
-  static const char * const eol = "\n";
-  static std::string input_buf;
-  static const char *pos = 0;
-  static size_t chars_left = 0;
+      octave_link::pre_input_event ();
 
-  int status = 0;
-  if (chars_left == 0)
-    {
-      pos = 0;
-
-      input_buf = get_user_input ();
-
-      chars_left = input_buf.length ();
-
-      pos = input_buf.c_str ();
+      octave_link::set_workspace ();
     }
 
-  if (chars_left > 0)
-    {
-      size_t len = max_size > chars_left ? chars_left : max_size;
-      assert (len > 0);
+  bool history_skip_auto_repeated_debugging_command = false;
+
+  std::string ps = (pflag > 0) ? VPS1 : VPS2;
+
+  std::string prompt = command_editor::decode_prompt_string (ps);
+
+  pipe_handler_error_count = 0;
+
+  flush_octave_stdout ();
+
+  octave_pager_stream::reset ();
+  octave_diary_stream::reset ();
+
+  octave_diary << prompt;
+
+  retval = interactive_input (prompt, eof);
 
-      memcpy (buf, pos, len);
+  // There is no need to update the load_path cache if there is no
+  // user input.
+  if (retval != "\n"
+      && retval.find_first_not_of (" \t\n\r") != std::string::npos)
+    {
+      load_path::update ();
 
-      chars_left -= len;
-      pos += len;
+      if (Vdebugging)
+        last_debugging_command = retval;
+      else
+        last_debugging_command = "\n";
+    }
+  else if (Vdebugging)
+    {
+      retval = last_debugging_command;
+      history_skip_auto_repeated_debugging_command = true;
+    }
 
-      // Make sure input ends with a new line character.
-      if (chars_left == 0 && buf[len-1] != '\n')
+  if (retval != "\n")
+    {
+      if (! history_skip_auto_repeated_debugging_command)
         {
-          if (len < max_size)
-            {
-              // There is enough room to plug the newline character in
-              // the buffer.
-              buf[len++] = '\n';
-            }
-          else
-            {
-              // There isn't enough room to plug the newline character
-              // in the buffer so make sure it is returned on the next
-              // octave_read call.
-              pos = eol;
-              chars_left = 1;
-            }
+          command_history::add (retval);
+
+          if (! command_history::ignoring_entries ())
+            octave_link::append_history (retval);
         }
 
-      status = len;
+      octave_diary << retval;
 
-    }
-  else if (chars_left == 0)
-    {
-      status = 0;
+      if (retval[retval.length () - 1] != '\n')
+        octave_diary << "\n";
+
+      do_input_echo (retval);
     }
   else
-    status = -1;
-
-  return status;
-}
+    octave_diary << "\n";
 
-// Fix things up so that input can come from file 'name', printing a
-// warning if the file doesn't exist.
-
-FILE *
-get_input_from_file (const std::string& name, int warn)
-{
-  FILE *instream = 0;
+  // Process post input event hook function after the internal history
+  // list has been updated.
 
-  if (name.length () > 0)
-    instream = gnulib::fopen (name.c_str (), "rb");
-
-  if (! instream && warn)
-    warning ("%s: no such file or directory", name.c_str ());
+  if (interactive || forced_interactive)
+    octave_link::post_input_event ();
 
-  if (reading_fcn_file || reading_script_file || reading_classdef_file)
-    ff_instream = instream;
-  else
-    command_editor::set_input_stream (instream);
-
-  return instream;
+  return retval;
 }
 
 // Fix things up so that input can come from the standard input.  This
@@ -626,8 +479,16 @@
 }
 
 static void
+execute_in_debugger_handler (const std::pair<std::string, int>& arg)
+{
+  octave_link::execute_in_debugger_event (arg.first, arg.second);
+}
+
+static void
 get_debug_input (const std::string& prompt)
 {
+  unwind_protect frame;
+
   octave_user_code *caller = octave_call_stack::caller_user_code ();
   std::string nm;
 
@@ -670,6 +531,13 @@
 
           if (have_file)
             {
+              octave_link::enter_debugger_event (nm, curr_debug_line);
+
+              octave_link::set_workspace ();
+
+              frame.add_fcn (execute_in_debugger_handler,
+                             std::pair<std::string, int> (nm, curr_debug_line));
+
               std::string line_buf
                 = get_file_line (nm, curr_debug_line);
 
@@ -684,91 +552,98 @@
   if (! msg.empty ())
     std::cerr << msg << std::endl;
 
-  unwind_protect frame;
-
   frame.protect_var (VPS1);
   VPS1 = prompt;
 
   if (! (interactive || forced_interactive)
-      || (reading_fcn_file
-          || reading_classdef_file
-          || reading_script_file
-          || get_input_from_eval_string
-          || input_from_startup_file
-          || input_from_command_line_file))
+      || LEXER->reading_fcn_file
+      || LEXER->reading_classdef_file
+      || LEXER->reading_script_file
+      || LEXER->input_from_eval_string ())
     {
       frame.protect_var (forced_interactive);
       forced_interactive = true;
-
-      frame.protect_var (reading_fcn_file);
-      reading_fcn_file = false;
-
-      frame.protect_var (reading_classdef_file);
-      reading_classdef_file = false;
-
-      frame.protect_var (reading_script_file);
-      reading_script_file = false;
-
-      frame.protect_var (input_from_startup_file);
-      input_from_startup_file = false;
+    }
 
-      frame.protect_var (input_from_command_line_file);
-      input_from_command_line_file = false;
-
-      frame.protect_var (get_input_from_eval_string);
-      get_input_from_eval_string = false;
+  // octave_parser constructor sets this for us.
+  frame.protect_var (LEXER);
 
-      YY_BUFFER_STATE old_buf = current_buffer ();
-      YY_BUFFER_STATE new_buf = create_buffer (get_input_from_stdin ());
-
-      // FIXME: are these safe?
-      frame.add_fcn (switch_to_buffer, old_buf);
-      frame.add_fcn (delete_buffer, new_buf);
-
-      switch_to_buffer (new_buf);
-    }
+  octave_parser curr_parser;
 
   while (Vdebugging)
     {
+      unwind_protect middle_frame;
+
       reset_error_handler ();
 
-      reset_parser ();
+      curr_parser.reset ();
+
+      int retval = curr_parser.run ();
 
-      // Save current value of global_command.
-      frame.protect_var (global_command);
+      if (command_editor::interrupt (false))
+        break;
+      else
+        {
+          if (retval == 0 && curr_parser.stmt_list)
+            {
+              curr_parser.stmt_list->accept (*current_evaluator);
 
-      global_command = 0;
+              if (octave_completion_matches_called)
+                octave_completion_matches_called = false;
+            }
 
-      // Do this with an unwind-protect cleanup function so that the
-      // forced variables will be unmarked in the event of an interrupt.
-      symbol_table::scope_id scope = symbol_table::top_scope ();
-      frame.add_fcn (symbol_table::unmark_forced_variables, scope);
+          octave_quit ();
+        }
+    }
+}
+
+const std::string octave_base_reader::in_src ("invalid");
 
-      // This is the same as yyparse in parse.y.
-      int retval = octave_parse ();
+const std::string octave_terminal_reader::in_src ("terminal");
 
-      if (retval == 0 && global_command)
-        {
-          unwind_protect inner_frame;
+std::string
+octave_terminal_reader::get_input (bool& eof)
+{
+  octave_quit ();
+
+  eof = false;
 
-          // Use an unwind-protect cleanup function so that the
-          // global_command list will be deleted in the event of an
-          // interrupt.
+  return octave_gets (eof);
+}
+
+const std::string octave_file_reader::in_src ("file");
 
-          inner_frame.add_fcn (cleanup_statement_list, &global_command);
+std::string
+octave_file_reader::get_input (bool& eof)
+{
+  octave_quit ();
 
-          global_command->accept (*current_evaluator);
+  eof = false;
+
+  return octave_fgets (file, eof);
+}
+
+const std::string octave_eval_string_reader::in_src ("eval_string");
 
-          if (octave_completion_matches_called)
-            octave_completion_matches_called = false;
-        }
+std::string
+octave_eval_string_reader::get_input (bool& eof)
+{
+  octave_quit ();
+
+  eof = false;
+
+  std::string retval;
 
-      // Unmark forced variables.
-      // Restore previous value of global_command.
-      frame.run_top (2);
+  retval = eval_string;
 
-      octave_quit ();
-    }
+  // Clear the eval string so that the next call will return
+  // an empty character string with EOF = true.
+  eval_string = "";
+
+  if (retval.empty ())
+    eof = true;
+
+  return retval;
 }
 
 // If the user simply hits return, this will produce an empty matrix.
@@ -800,13 +675,12 @@
 
   octave_diary << prompt;
 
-  std::string input_buf = interactive_input (prompt.c_str (), true);
+  bool eof = false;
+
+  std::string input_buf = interactive_input (prompt.c_str (), eof);
 
   if (! (error_state || input_buf.empty ()))
     {
-      if (! input_from_startup_file)
-        command_history::add (input_buf);
-
       size_t len = input_buf.length ();
 
       octave_diary << input_buf;
@@ -843,8 +717,8 @@
 
 DEFUN (input, args, nargout,
   "-*- texinfo -*-\n\
-@deftypefn  {Built-in Function} {} input (@var{prompt})\n\
-@deftypefnx {Built-in Function} {} input (@var{prompt}, \"s\")\n\
+@deftypefn  {Built-in Function} {@var{ans} =} input (@var{prompt})\n\
+@deftypefnx {Built-in Function} {@var{ans} =} input (@var{prompt}, \"s\")\n\
 Print a prompt and wait for user input.  For example,\n\
 \n\
 @example\n\
@@ -874,7 +748,8 @@
 Because there may be output waiting to be displayed by the pager, it is\n\
 a good idea to always call @code{fflush (stdout)} before calling\n\
 @code{input}.  This will ensure that all pending output is written to\n\
-the screen before your prompt.  @xref{Input and Output}.\n\
+the screen before your prompt.\n\
+@seealso{yes_or_no, kbhit}\n\
 @end deftypefn")
 {
   octave_value_list retval;
@@ -896,7 +771,9 @@
 
   while (1)
     {
-      std::string input_buf = interactive_input (prompt_string, true);
+      bool eof = false;
+
+      std::string input_buf = interactive_input (prompt_string, eof);
 
       if (input_buf == "yes")
         return true;
@@ -909,12 +786,14 @@
 
 DEFUN (yes_or_no, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {} yes_or_no (@var{prompt})\n\
-Ask the user a yes-or-no question.  Return 1 if the answer is yes.\n\
-Takes one argument, which is the string to display to ask the\n\
-question.  It should end in a space; @samp{yes-or-no-p} adds\n\
-@samp{(yes or no) } to it.  The user must confirm the answer with\n\
-RET and can edit it until it has been confirmed.\n\
+@deftypefn {Built-in Function} {@var{ans} =} yes_or_no (\"@var{prompt}\")\n\
+Ask the user a yes-or-no question.  Return logical true if the answer is yes\n\
+or false if the answer is no.  Takes one argument, @var{prompt}, which is\n\
+the string to display when asking the question.  @var{prompt} should end in\n\
+a space; @code{yes-or-no} adds the string @samp{(yes or no) } to it.  The\n\
+user must confirm the answer with @key{RET} and can edit it until it has\n\
+been confirmed.\n\
+@seealso{input}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -986,7 +865,7 @@
 DEFUN (keyboard, args, ,
   "-*- texinfo -*-\n\
 @deftypefn  {Built-in Function} {} keyboard ()\n\
-@deftypefnx {Built-in Function} {} keyboard (@var{prompt})\n\
+@deftypefnx {Built-in Function} {} keyboard (\"@var{prompt}\")\n\
 This function is normally used for simple debugging.  When the\n\
 @code{keyboard} function is executed, Octave prints a prompt and waits\n\
 for user input.  The input strings are then evaluated and the results\n\
@@ -1234,47 +1113,22 @@
   return retval;
 }
 
-typedef std::map<std::string, octave_value> hook_fcn_map_type;
-
-static hook_fcn_map_type hook_fcn_map;
-
 static int
-input_event_hook (void)
+internal_input_event_hook_fcn (void)
 {
-  if (! lexer_flags.defining_func)
-    {
-      hook_fcn_map_type::iterator p = hook_fcn_map.begin ();
-
-      while (p != hook_fcn_map.end ())
-        {
-          std::string hook_fcn = p->first;
-          octave_value user_data = p->second;
+  input_event_hook_functions.run ();
 
-          hook_fcn_map_type::iterator q = p++;
-
-          if (is_valid_function (hook_fcn))
-            {
-              if (user_data.is_defined ())
-                feval (hook_fcn, user_data, 0);
-              else
-                feval (hook_fcn, octave_value_list (), 0);
-            }
-          else
-            hook_fcn_map.erase (q);
-        }
-
-      if (hook_fcn_map.empty ())
-        command_editor::remove_event_hook (input_event_hook);
-    }
+  if (input_event_hook_functions.empty ())
+    command_editor::remove_event_hook (internal_input_event_hook_fcn);
 
   return 0;
 }
 
 DEFUN (add_input_event_hook, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Built-in Function} {} add_input_event_hook (@var{fcn})\n\
-@deftypefnx {Built-in Function} {} add_input_event_hook (@var{fcn}, @var{data})\n\
-Add the named function @var{fcn} to the list of functions to call\n\
+@deftypefn  {Built-in Function} {@var{id} =} add_input_event_hook (@var{fcn})\n\
+@deftypefnx {Built-in Function} {@var{id} =} add_input_event_hook (@var{fcn}, @var{data})\n\
+Add the named function or function handle @var{fcn} to the list of functions to call\n\
 periodically when Octave is waiting for input.  The function should\n\
 have the form\n\
 \n\
@@ -1284,10 +1138,13 @@
 \n\
 If @var{data} is omitted, Octave calls the function without any\n\
 arguments.\n\
+\n\
+The returned identifier may be used to remove the function handle from\n\
+the list of input hook functions.\n\
 @seealso{remove_input_event_hook}\n\
 @end deftypefn")
 {
-  octave_value_list retval;
+  octave_value retval;
 
   int nargin = args.length ();
 
@@ -1298,17 +1155,19 @@
       if (nargin == 2)
         user_data = args(1);
 
-      std::string hook_fcn = args(0).string_value ();
+      hook_function hook_fcn (args(0), user_data);
 
       if (! error_state)
         {
-          if (hook_fcn_map.empty ())
-            command_editor::add_event_hook (input_event_hook);
+          if (input_event_hook_functions.empty ())
+            command_editor::add_event_hook (internal_input_event_hook_fcn);
 
-          hook_fcn_map[hook_fcn] = user_data;
+          input_event_hook_functions.insert (hook_fcn.id (), hook_fcn);
+
+          retval = hook_fcn.id ();
         }
       else
-        error ("add_input_event_hook: expecting string as first arg");
+        error ("add_input_event_hook: expecting function handle or character string as first argument");
     }
   else
     print_usage ();
@@ -1318,9 +1177,11 @@
 
 DEFUN (remove_input_event_hook, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {} remove_input_event_hook (@var{fcn})\n\
-Remove the named function @var{fcn} from the list of functions to call\n\
-periodically when Octave is waiting for input.\n\
+@deftypefn {Built-in Function} {} remove_input_event_hook (@var{name})\n\
+@deftypefnx {Built-in Function} {} remove_input_event_hook (@var{fcn_id})\n\
+Remove the named function or function handle with the given identifier\n\
+from the list of functions to call periodically when Octave is waiting\n\
+for input.\n\
 @seealso{add_input_event_hook}\n\
 @end deftypefn")
 {
@@ -1328,25 +1189,28 @@
 
   int nargin = args.length ();
 
-  if (nargin == 1)
+  if (nargin == 1 || nargin == 2)
     {
-      std::string hook_fcn = args(0).string_value ();
+      std::string hook_fcn_id = args(0).string_value ();
+
+      bool warn = (nargin < 2);
 
       if (! error_state)
         {
-          hook_fcn_map_type::iterator p = hook_fcn_map.find (hook_fcn);
+          hook_function_list::iterator p
+            = input_event_hook_functions.find (hook_fcn_id);
 
-          if (p != hook_fcn_map.end ())
-            hook_fcn_map.erase (p);
-          else
-            error ("remove_input_event_hook: %s not found in list",
-                   hook_fcn.c_str ());
+          if (p != input_event_hook_functions.end ())
+            input_event_hook_functions.erase (p);
+          else if (warn)
+            warning ("remove_input_event_hook: %s not found in list",
+                     hook_fcn_id.c_str ());
 
-          if (hook_fcn_map.empty ())
-            command_editor::remove_event_hook (input_event_hook);
+          if (input_event_hook_functions.empty ())
+            command_editor::remove_event_hook (internal_input_event_hook_fcn);
         }
       else
-        error ("remove_input_event_hook: expecting string as first arg");
+        error ("remove_input_event_hook: argument not valid as a hook function name or id");
     }
   else
     print_usage ();
@@ -1539,9 +1403,9 @@
 @end example\n\
 \n\
 @noindent\n\
-returns the help string associated with the sub-function @code{mysubfunc}\n\
+returns the help string associated with the subfunction @code{mysubfunc}\n\
 of the function @code{myfunc}.  Another use of @code{filemarker} is when\n\
-debugging it allows easier placement of breakpoints within sub-functions.\n\
+debugging it allows easier placement of breakpoints within subfunctions.\n\
 For example,\n\
 \n\
 @example\n\
rename from src/input.h
rename to libinterp/interpfcn/input.h
--- a/src/input.h
+++ b/libinterp/interpfcn/input.h
@@ -35,57 +35,14 @@
 
 class octave_value;
 
-extern OCTINTERP_API int octave_read (char *buf, unsigned max_size);
-extern OCTINTERP_API FILE *get_input_from_file (const std::string& name, int warn = 1);
 extern OCTINTERP_API FILE *get_input_from_stdin (void);
 
-// Global pointer for eval().
-extern std::string current_eval_string;
-
-// TRUE means get input from current_eval_string.
-extern bool get_input_from_eval_string;
-
-// TRUE means we haven't been asked for the input from
-// current_eval_string yet.
-extern bool input_from_eval_string_pending;
-
-// TRUE means that input is coming from a file that was named on
-// the command line.
-extern bool input_from_command_line_file;
-
-// TRUE means that stdin is a terminal, not a pipe or redirected file.
-extern bool stdin_is_tty;
-
-// TRUE means we're parsing a function file.
-extern bool reading_fcn_file;
-
-// Simple name of function file we are reading.
-extern std::string curr_fcn_file_name;
-
-// Full name of file we are reading.
-extern std::string curr_fcn_file_full_name;
-
-// TRUE means we're parsing a script file.
-extern bool reading_script_file;
-
-// TRUE means we're parsing a classdef file.
-extern bool reading_classdef_file;
-
-// If we are reading from an M-file, this is it.
-extern FILE *ff_instream;
-
 // TRUE means this is an interactive shell.
 extern bool interactive;
 
 // TRUE means the user forced this shell to be interactive (-i).
 extern bool forced_interactive;
 
-// Should we issue a prompt?
-extern int promptflag;
-
-// A line of input.
-extern std::string current_input_line;
-
 // TRUE after a call to completion_matches.
 extern bool octave_completion_matches_called;
 
@@ -96,14 +53,16 @@
 // TRUE if we are in debugging mode.
 extern OCTINTERP_API bool Vdebugging;
 
-extern std::string gnu_readline (const std::string& s, bool force_readline = false);
-
 extern void initialize_command_input (void);
 
 extern bool octave_yes_or_no (const std::string& prompt);
 
 extern octave_value do_keyboard (const octave_value_list& args = octave_value_list ());
 
+extern void remove_input_event_hook_functions (void);
+
+extern void set_default_prompts (void);
+
 extern std::string VPS4;
 
 extern char Vfilemarker;
@@ -120,4 +79,168 @@
 
 extern octave_time Vlast_prompt_time;
 
+class
+octave_base_reader
+{
+public:
+
+  friend class octave_input_reader;
+
+  octave_base_reader (void) : count (1), pflag (0) { }
+
+  octave_base_reader (const octave_base_reader&) : count (1) { }
+
+  virtual ~octave_base_reader (void) { }
+
+  virtual std::string get_input (bool& eof) = 0;
+
+  virtual std::string input_source (void) const { return in_src; }
+
+  void reset (void) { promptflag (1); }
+
+  void increment_promptflag (void) { pflag++; }
+
+  void decrement_promptflag (void) { pflag--; }
+
+  int promptflag (void) const { return pflag; }
+
+  int promptflag (int n)
+  {
+    int retval = pflag;
+    pflag = n;
+    return retval;
+  }
+
+  std::string octave_gets (bool& eof);
+
+private:
+
+  int count;
+
+  int pflag;
+
+  void do_input_echo (const std::string&) const;
+
+  static const std::string in_src;
+};
+
+class
+octave_terminal_reader : public octave_base_reader
+{
+public:
+
+  octave_terminal_reader (void) : octave_base_reader () { }
+
+  std::string get_input (bool& eof);
+
+  std::string input_source (void) const { return in_src; }
+
+private:
+
+  static const std::string in_src;
+};
+
+class
+octave_file_reader : public octave_base_reader
+{
+public:
+
+  octave_file_reader (FILE *f_arg)
+    : octave_base_reader (), file (f_arg) { }
+
+  std::string get_input (bool& eof);
+
+  std::string input_source (void) const { return in_src; }
+
+private:
+
+  FILE *file;
+
+  static const std::string in_src;
+};
+
+class
+octave_eval_string_reader : public octave_base_reader
+{
+public:
+
+  octave_eval_string_reader (const std::string& str)
+    : octave_base_reader (), eval_string (str)
+  { }
+
+  std::string get_input (bool& eof);
+
+  std::string input_source (void) const { return in_src; }
+
+private:
+
+  std::string eval_string;
+
+  static const std::string in_src;
+};
+
+class
+octave_input_reader
+{
+public:
+  octave_input_reader (void)
+    : rep (new octave_terminal_reader ())
+  { }
+
+  octave_input_reader (FILE *file)
+    : rep (new octave_file_reader (file))
+  { }
+
+  octave_input_reader (const std::string& str)
+    : rep (new octave_eval_string_reader (str))
+  { }
+
+  octave_input_reader (const octave_input_reader& ir)
+  {
+    rep = ir.rep;
+    rep->count++;
+  }
+
+  octave_input_reader& operator = (const octave_input_reader& ir)
+  {
+    if (&ir != this)
+      {
+        rep = ir.rep;
+        rep->count++;
+      }
+
+    return *this;
+  }
+
+  ~octave_input_reader (void)
+  {
+    if (--rep->count == 0)
+      delete rep;
+  }
+
+  void reset (void) { return rep->reset (); }
+
+  void increment_promptflag (void) { rep->increment_promptflag (); }
+
+  void decrement_promptflag (void) { rep->decrement_promptflag (); }
+
+  int promptflag (void) const { return rep->promptflag (); }
+
+  int promptflag (int n) { return rep->promptflag (n); }
+
+  std::string get_input (bool& eof)
+  {
+    return rep->get_input (eof);
+  }
+
+  std::string input_source (void) const
+  {
+    return rep->input_source ();
+  }
+
+private:
+
+  octave_base_reader *rep;
+};
+
 #endif
rename from src/load-path.cc
rename to libinterp/interpfcn/load-path.cc
--- a/src/load-path.cc
+++ b/libinterp/interpfcn/load-path.cc
@@ -353,6 +353,25 @@
   return find_dir_info (dir) != dir_info_list.end ();
 }
 
+bool
+load_path::do_contains_canonical (const std::string& dir) const
+{
+  bool retval = false;
+
+  for (const_dir_info_list_iterator i = dir_info_list.begin ();
+       i != dir_info_list.end ();
+       i++)
+    {
+      if (same_file (dir, i->dir_name))
+        {
+          retval = true;
+          break;
+        }
+    }
+
+  return retval;
+}
+
 void
 load_path::move_fcn_map (const std::string& dir_name,
                          const string_vector& fcn_files, bool at_end)
@@ -519,7 +538,7 @@
   else
     xpath = sys_path;
 
-  do_set (xpath, false);
+  do_set (xpath, false, true);
 }
 
 void
@@ -565,10 +584,30 @@
 }
 
 void
-load_path::do_set (const std::string& p, bool warn)
+load_path::do_set (const std::string& p, bool warn, bool is_init)
 {
+  // Use a list when we need to preserve order.
   std::list<std::string> elts = split_path (p);
 
+  // Use a set when we need to search and order is not important.
+  std::set<std::string> elts_set (elts.begin (), elts.end ());
+
+  if (is_init)
+    init_dirs = elts_set;
+  else
+    {
+      for (std::set<std::string>::const_iterator it = init_dirs.begin ();
+           it != init_dirs.end (); it++)
+        {
+          if (elts_set.find (*it) == elts_set.end ())
+            {
+              warning_with_id ("Octave:remove-init-dir",
+                               "default load path altered.  Some built-in functions may not be found.  Try restoredefaultpath() to recover it.");
+              break;
+            }
+        }
+    }
+
   // Temporarily disable add hook.
 
   unwind_protect frame;
@@ -579,12 +618,11 @@
   do_clear ();
 
   for (std::list<std::string>::const_iterator i = elts.begin ();
-       i != elts.end ();
-       i++)
+       i != elts.end (); i++)
     do_append (*i, warn);
 
   // Restore add hook and execute for all newly added directories.
-  frame.run_top ();
+  frame.run_first ();
 
   for (dir_info_list_iterator i = dir_info_list.begin ();
        i != dir_info_list.end ();
@@ -1768,7 +1806,11 @@
                   // way we look for old.dir_name in sys_path to avoid
                   // partial matches?
 
-                  if (sys_path.find (old.dir_name) != std::string::npos
+                  // Don't warn about Contents.m files since we expect
+                  // more than one to exist in the load path.
+
+                  if (fname != "Contents.m"
+                      && sys_path.find (old.dir_name) != std::string::npos
                       && in_path_list (sys_path, old.dir_name))
                     {
                       std::string fcn_path = file_ops::concat (dir_name, fname);
@@ -1933,10 +1975,6 @@
 
   unwind_protect frame;
 
-  frame.protect_var (input_from_startup_file);
-
-  input_from_startup_file = true;
-
   std::string file = file_ops::concat (dir, script_file);
 
   file_stat fs (file);
@@ -2127,7 +2165,7 @@
   "-*- texinfo -*-\n\
 @deftypefn  {Built-in Function} {} addpath (@var{dir1}, @dots{})\n\
 @deftypefnx {Built-in Function} {} addpath (@var{dir1}, @dots{}, @var{option})\n\
-Add @var{dir1}, @dots{} to the current function search path.  If\n\
+Add named directories to the function search path.  If\n\
 @var{option} is \"-begin\" or 0 (the default), prepend the\n\
 directory name to the current path.  If @var{option} is \"-end\"\n\
 or 1, append the directory name to the current path.\n\
@@ -2137,7 +2175,7 @@
 directory names separated by @code{pathsep} are also accepted.  For example:\n\
 \n\
 @example\n\
-addpath (\"dir1:/dir2:~/dir3\");\n\
+addpath (\"dir1:/dir2:~/dir3\")\n\
 @end example\n\
 @seealso{path, rmpath, genpath, pathdef, savepath, pathsep}\n\
 @end deftypefn")
@@ -2248,7 +2286,7 @@
 directory names separated by @code{pathsep} are also accepted.  For example:\n\
 \n\
 @example\n\
-rmpath (\"dir1:/dir2:~/dir3\");\n\
+rmpath (\"dir1:/dir2:~/dir3\")\n\
 @end example\n\
 @seealso{path, addpath, genpath, pathdef, savepath, pathsep}\n\
 @end deftypefn")
rename from src/load-path.h
rename to libinterp/interpfcn/load-path.h
--- a/src/load-path.h
+++ b/libinterp/interpfcn/load-path.h
@@ -39,7 +39,8 @@
 protected:
 
   load_path (void)
-    : dir_info_list (), fcn_map (), private_fcn_map (), method_map () { }
+    : dir_info_list (), fcn_map (), private_fcn_map (), method_map (),
+      init_dirs () { }
 
 public:
 
@@ -88,6 +89,11 @@
       instance->do_update ();
   }
 
+  static bool contains_canonical (const std::string& dir_name)
+  {
+    return instance_ok () ? instance->do_contains_canonical (dir_name) : false;
+  }
+
   static std::string find_method (const std::string& class_name,
                                   const std::string& meth,
                                   std::string& dir_name)
@@ -294,14 +300,14 @@
     // constructor for any other purpose.
     dir_info (void)
       : dir_name (), abs_dir_name (), is_relative (false),
-        dir_mtime (), dir_time_last_checked (), all_files (),
-        fcn_files (), private_file_map (), method_file_map ()
+        dir_mtime (), dir_time_last_checked (),
+        all_files (), fcn_files (), private_file_map (), method_file_map ()
       { }
 
     dir_info (const std::string& d)
       : dir_name (d), abs_dir_name (), is_relative (false),
-        dir_mtime (), dir_time_last_checked (), all_files (),
-        fcn_files (), private_file_map (), method_file_map ()
+        dir_mtime (), dir_time_last_checked (),
+        all_files (), fcn_files (), private_file_map (), method_file_map ()
     {
       initialize ();
     }
@@ -441,6 +447,8 @@
 
   mutable method_map_type method_map;
 
+  mutable std::set<std::string> init_dirs;
+
   static load_path *instance;
 
   static void cleanup_instance (void) { delete instance; instance = 0; }
@@ -462,6 +470,8 @@
 
   bool contains (const std::string& dir) const;
 
+  bool do_contains_canonical (const std::string& dir) const;
+
   void move_fcn_map (const std::string& dir,
                      const string_vector& fcn_files, bool at_end);
 
@@ -473,7 +483,7 @@
 
   void do_clear (void);
 
-  void do_set (const std::string& p, bool warn);
+  void do_set (const std::string& p, bool warn, bool is_init = false);
 
   void do_append (const std::string& dir, bool warn);
 
rename from src/load-save.cc
rename to libinterp/interpfcn/load-save.cc
--- a/src/load-save.cc
+++ b/libinterp/interpfcn/load-save.cc
@@ -91,7 +91,7 @@
 #include "zfstream.h"
 #endif
 
-// Write octave-core file if Octave crashes or is killed by a signal.
+// Write octave-workspace file if Octave crashes or is killed by a signal.
 static bool Vcrash_dumps_octave_core = true;
 
 // The maximum amount of memory (in kilobytes) that we will attempt to
@@ -99,7 +99,7 @@
 static double Voctave_core_file_limit = -1.0;
 
 // The name of the Octave core file.
-static std::string Voctave_core_file_name = "octave-core";
+static std::string Voctave_core_file_name = "octave-workspace";
 
 // The default output format.  May be one of "binary", "text",
 // "mat-binary", or "hdf5".
@@ -146,13 +146,12 @@
 {
   if (global)
     {
-      symbol_table::symbol_record& sr = symbol_table::insert (name);
-      sr.clear ();
-      sr.mark_global ();
-      sr.varref () = val;
+      symbol_table::clear (name);
+      symbol_table::mark_global (name);
+      symbol_table::global_assign (name, val);
     }
   else
-    symbol_table::varref (name) = val;
+    symbol_table::assign (name, val);
 }
 
 // Return TRUE if NAME matches one of the given globbing PATTERNS.
@@ -243,7 +242,8 @@
 
       int32_t mopt, nr, nc, imag, len;
 
-      int err = read_mat_file_header (file, swap, mopt, nr, nc, imag, len, 1);
+      int err = read_mat_file_header (file, swap, mopt, nr, nc, imag, len,
+                                      true);
 
       if (! err)
         retval = LS_MAT_BINARY;
@@ -278,7 +278,7 @@
 
 static load_save_format
 get_file_format (const std::string& fname, const std::string& orig_fname,
-                 bool &use_zlib)
+                 bool &use_zlib, bool quiet = false)
 {
   load_save_format retval = LS_UNKNOWN;
 
@@ -310,19 +310,16 @@
         }
 #endif
 
-      if (retval == LS_UNKNOWN)
-        {
-          // Try reading the file as numbers only, determining the
-          // number of rows and columns from the data.  We don't
-          // even bother to check to see if the first item in the
-          // file is a number, so that get_complete_line() can
-          // skip any comments that might appear at the top of the
-          // file.
+      // FIXME -- looks_like_mat_ascii_file does not check to see
+      // whether the file contains numbers.  It just skips comments and
+      // checks for the same number of words on each line.  We may need
+      // a better check here.  The best way to do that might be just
+      // to try to read the file and see if it works.
 
-          retval = LS_MAT_ASCII;
-        }
+      if (retval == LS_UNKNOWN && looks_like_mat_ascii_file (fname))
+        retval = LS_MAT_ASCII;
     }
-  else
+  else if (! quiet)
     gripe_file_open ("load", orig_fname);
 
   return retval;
@@ -538,6 +535,12 @@
   return fname;
 }
 
+bool
+is_octave_data_file (const std::string& fname)
+{
+  bool use_zlib = false;
+  return get_file_format (fname, fname, use_zlib, true) != LS_UNKNOWN;
+}
 
 DEFUN (load, args, nargout,
   "-*- texinfo -*-\n\
@@ -649,7 +652,7 @@
   std::string orig_fname = "";
 
   // Function called with Matlab-style ["filename", options] syntax
-  if (argc > 1 && ! argv[1].empty () && argv[1].at(0) != '-')
+  if (argc > 1 && ! argv[1].empty () && argv[1].at (0) != '-')
     {
       orig_fname = argv[1];
       i++;
@@ -1001,7 +1004,7 @@
     {
       std::string empty_str;
 
-      if (pat.match(m.key (p)))
+      if (pat.match (m.key (p)))
         {
           do_save (os, m.contents (p), m.key (p), empty_str,
                    0, fmt, save_as_floats);
@@ -1121,6 +1124,14 @@
           use_zlib  = true;
         }
 #endif
+      else if (argv[i] == "-struct")
+        {
+          retval.append (argv[i]);
+        }
+      else if (argv[i][0] == '-')
+        {
+          error ("save: Unrecognized option '%s'", argv[i].c_str ());
+        }
       else
         retval.append (argv[i]);
     }
@@ -1273,7 +1284,7 @@
           return;
         }
 
-      octave_value struct_var = symbol_table::varref (struct_name);
+      octave_value struct_var = symbol_table::varval (struct_name);
 
       if (! struct_var.is_map () || struct_var.numel () != 1)
         {
@@ -1443,7 +1454,6 @@
     }
 }
 
-
 DEFUN (save, args, ,
   "-*- texinfo -*-\n\
 @deftypefn  {Command} {} save file\n\
@@ -1532,6 +1542,7 @@
 \n\
 The list of variables to save may use wildcard patterns containing\n\
 the following special characters:\n\
+\n\
 @table @code\n\
 @item ?\n\
 Match any single character.\n\
@@ -1750,7 +1761,7 @@
 @deftypefnx {Built-in Function} {@var{old_val} =} crash_dumps_octave_core (@var{new_val})\n\
 @deftypefnx {Built-in Function} {} crash_dumps_octave_core (@var{new_val}, \"local\")\n\
 Query or set the internal variable that controls whether Octave tries\n\
-to save all current variables to the file \"octave-core\" if it\n\
+to save all current variables to the file \"octave-workspace\" if it\n\
 crashes or receives a hangup, terminate or similar signal.\n\
 \n\
 When called from inside a function with the \"local\" option, the variable is\n\
@@ -1811,7 +1822,7 @@
 @deftypefnx {Built-in Function} {} octave_core_file_name (@var{new_val}, \"local\")\n\
 Query or set the internal variable that specifies the name of the file\n\
 used for saving data from the top-level workspace if Octave aborts.\n\
-The default value is @code{\"octave-core\"}\n\
+The default value is @code{\"octave-workspace\"}\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\
rename from src/load-save.h
rename to libinterp/interpfcn/load-save.h
--- a/src/load-save.h
+++ b/libinterp/interpfcn/load-save.h
@@ -26,6 +26,9 @@
 #include <iosfwd>
 #include <string>
 
+#include "mach-info.h"
+#include "symtab.h"
+
 class octave_value;
 
 // FIXME: maybe MAT5 and MAT7 should be options to MAT_BINARY.
@@ -80,6 +83,8 @@
          bool list_only, bool swap, bool verbose,
          const string_vector& argv, int argv_idx, int argc, int nargout);
 
+extern bool is_octave_data_file (const std::string& file);
+
 extern void
 do_save (std::ostream& os, const symbol_table::symbol_record& sr,
          load_save_format fmt, bool save_as_floats);
rename from src/ls-oct-ascii.cc
rename to libinterp/interpfcn/ls-oct-ascii.cc
--- a/src/ls-oct-ascii.cc
+++ b/libinterp/interpfcn/ls-oct-ascii.cc
@@ -110,7 +110,7 @@
               while (is.get (c) && (c == ' ' || c == '\t' || c == ':'))
                 ; // Skip whitespace and the colon.
 
-              is.putback(c);
+              is.putback (c);
               retval = read_until_newline (is, false);
               break;
             }
@@ -323,7 +323,7 @@
   if (mark_as_global)
     os << "# type: global " << val.type_name () << "\n";
   else
-    os << "# type: " << val.type_name() << "\n";
+    os << "# type: " << val.type_name () << "\n";
 
   if (! precision)
     precision = Vsave_precision;
@@ -428,5 +428,6 @@
 variable value is restored when exiting the function.\n\
 @end deftypefn")
 {
-  return SET_INTERNAL_VARIABLE_WITH_LIMITS (save_precision, -1, INT_MAX);
+  return SET_INTERNAL_VARIABLE_WITH_LIMITS (save_precision, -1,
+                                            std::numeric_limits<int>::max ());
 }
rename from src/ls-oct-ascii.h
rename to libinterp/interpfcn/ls-oct-ascii.h
--- a/src/ls-oct-ascii.h
+++ b/libinterp/interpfcn/ls-oct-ascii.h
@@ -38,7 +38,7 @@
 // Used when converting Inf to something that gnuplot can read.
 
 #ifndef OCT_RBV
-#define OCT_RBV DBL_MAX / 100.0
+#define OCT_RBV (std::numeric_limits<double>::max () / 100.0)
 #endif
 
 extern OCTINTERP_API std::string
@@ -74,7 +74,7 @@
                  const bool next_only = false)
 {
   bool status = false;
-  value = T();
+  value = T ();
 
   char c;
   while (is.get (c))
new file mode 100644
--- /dev/null
+++ b/libinterp/interpfcn/module.mk
@@ -0,0 +1,76 @@
+EXTRA_DIST += \
+  interpfcn/module.mk \
+  interpfcn/defaults.in.h \
+  interpfcn/graphics.in.h
+
+INTERPFCN_INC = \
+  interpfcn/data.h \
+  interpfcn/debug.h \
+  interpfcn/defun.h \
+  interpfcn/dirfns.h \
+  interpfcn/error.h \
+  interpfcn/file-io.h \
+  interpfcn/help.h \
+  interpfcn/hook-fcn.h \
+  interpfcn/input.h \
+  interpfcn/load-path.h \
+  interpfcn/load-save.h \
+  interpfcn/ls-oct-ascii.h \
+  interpfcn/octave-link.h \
+  interpfcn/oct-hist.h \
+  interpfcn/pager.h \
+  interpfcn/pr-output.h \
+  interpfcn/profiler.h \
+  interpfcn/sighandlers.h \
+  interpfcn/symtab.h \
+  interpfcn/sysdep.h \
+  interpfcn/toplev.h \
+  interpfcn/utils.h \
+  interpfcn/variables.h \
+  interpfcn/workspace-element.h
+
+INTERPFCN_SRC = \
+  interpfcn/data.cc \
+  interpfcn/debug.cc \
+  interpfcn/defaults.cc \
+  interpfcn/defun.cc \
+  interpfcn/dirfns.cc \
+  interpfcn/error.cc \
+  interpfcn/file-io.cc \
+  interpfcn/graphics.cc \
+  interpfcn/help.cc \
+  interpfcn/hook-fcn.cc \
+  interpfcn/input.cc \
+  interpfcn/load-path.cc \
+  interpfcn/load-save.cc \
+  interpfcn/ls-oct-ascii.cc \
+  interpfcn/octave-link.cc \
+  interpfcn/oct-hist.cc \
+  interpfcn/pager.cc \
+  interpfcn/pr-output.cc \
+  interpfcn/profiler.cc \
+  interpfcn/sighandlers.cc \
+  interpfcn/symtab.cc \
+  interpfcn/sysdep.cc \
+  interpfcn/toplev.cc \
+  interpfcn/utils.cc \
+  interpfcn/variables.cc
+
+## defaults.h and graphics.h must depend on Makefile.  Calling configure
+## may change default/config values.  However, calling configure will also
+## regenerate the Makefiles from Makefile.am and trigger the rules below.
+interpfcn/defaults.h: interpfcn/defaults.in.h Makefile
+	@$(do_subst_default_vals)
+
+interpfcn/graphics.h: interpfcn/graphics.in.h genprops.awk Makefile
+	$(AWK) -f $(srcdir)/genprops.awk $< > $@-t
+	mv $@-t $@
+
+interpfcn/graphics-props.cc: interpfcn/graphics.in.h genprops.awk Makefile
+	$(AWK) -v emit_graphics_props=1 -f $(srcdir)/genprops.awk $< > $@-t
+	mv $@-t $@
+
+noinst_LTLIBRARIES += interpfcn/libinterpfcn.la
+
+interpfcn_libinterpfcn_la_SOURCES = $(INTERPFCN_SRC)
+interpfcn_libinterpfcn_la_CPPFLAGS = $(liboctinterp_la_CPPFLAGS)
rename from src/oct-hist.cc
rename to libinterp/interpfcn/oct-hist.cc
--- a/src/oct-hist.cc
+++ b/libinterp/interpfcn/oct-hist.cc
@@ -48,6 +48,7 @@
 #include "cmd-hist.h"
 #include "file-ops.h"
 #include "lo-mappers.h"
+#include "octave-link.h"
 #include "oct-env.h"
 #include "oct-time.h"
 #include "str-vec.h"
@@ -91,7 +92,7 @@
 static int
 default_history_size (void)
 {
-  int size = 1024;
+  int size = 1000;
 
   std::string env_size = octave_env::getenv ("OCTAVE_HISTSIZE");
 
@@ -128,25 +129,54 @@
 // 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 (-1 = all)
+  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 ();
+          if (limit < 0)
+            limit = -limit;
+          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.
@@ -157,53 +187,73 @@
             command_history::write ();
 
           else if (option == "-r")
-            // Read entire file.
-            command_history::read ();
+            {
+              // Read entire file.
+              command_history::read ();
+              octave_link::set_history (command_history::list ());
+            }
 
           else if (option == "-n")
-            // Read 'new' history from file.
-            command_history::read_range ();
+            {
+              // Read 'new' history from file.
+              command_history::read_range ();
+              octave_link::set_history (command_history::list ());
+            }
 
           else
             panic_impossible ();
 
-          return;
+          return hlist;
         }
-      else if (argv[i] == "-q")
-        numbered_output = 0;
-      else if (argv[i] == "--")
+      else if (option == "-c")
+        {
+          command_history::clear ();
+          octave_link::clear_history ();
+        }
+      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)
+            {
+              if (tmp > 0)
+                limit = tmp;
+              else
+                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 (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
@@ -266,6 +316,11 @@
 // appear in the history list.  This way you can do 'run_history' to
 // your heart's content.
 
+// FIXME: Don't delete this block of code until memory
+//        leak in edit_history has been plugged and
+//        it is clear that this code can be removed.
+//        See additional FIXME in do_edit_history.
+/*
 static void
 edit_history_repl_hist (const std::string& command)
 {
@@ -296,6 +351,7 @@
         }
     }
 }
+*/
 
 static void
 edit_history_add_hist (const std::string& line)
@@ -310,67 +366,94 @@
         tmp.resize (len - 1);
 
       if (! tmp.empty ())
-        command_history::add (tmp);
+        {
+          command_history::add (tmp);
+          octave_link::append_history (tmp);
+        }
     }
 }
 
+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;
 
   string_vector hlist = command_history::list ();
 
-  int hist_count = hlist.length ();
+  int hist_count = hlist.length () - 1;  // switch to zero-based indexing
 
   // The current command line is already part of the history list by
-  // the time we get to this point.  Delete it from the list.
-
-  hist_count -= 2;
+  // the time we get to this point.  Delete the cmd from the list when
+  // executing 'edit_history' so that it doesn't show up in the history
+  // but the actual commands performed will.
 
   if (! insert_curr)
     command_history::remove (hist_count);
 
-  hist_count--;
+  hist_count--;  // skip last entry in history list
 
   // If no numbers have been specified, the default is to edit the
   // last command in the history list.
 
+  int hist_beg = hist_count;
   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--;
+          if (hist_beg < 0)
+            hist_beg += (hist_count + 1);
+          else
+            hist_beg--;
+          if (hist_end < 0)
+            hist_end += (hist_count + 1);
+          else
+            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--;
+          if (hist_beg < 0)
+            hist_beg += (hist_count + 1);
+          else
+            hist_beg--;
           hist_end = hist_beg;
         }
-    }
-
-  if (hist_beg < 0 || hist_end < 0 || hist_beg > hist_count
-      || hist_end > hist_count)
-    {
-      error ("%s: history specification out of range", warn_for);
-      return retval;
+      else
+        usage_error = true;
     }
 
   if (usage_error)
@@ -379,12 +462,16 @@
       return retval;
     }
 
+  if (hist_beg > hist_count || hist_end > hist_count)
+    {
+      error ("%s: history specification out of range", warn_for);
+      return retval;
+    }
+
   if (hist_end < hist_beg)
     {
-      int t = hist_end;
-      hist_end = hist_beg;
-      hist_beg = t;
-      reverse = 1;
+      std::swap (hist_end, hist_beg);
+      reverse = true;
     }
 
   std::string name = octave_tempnam ("", "oct-");
@@ -421,9 +508,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;
@@ -431,9 +518,7 @@
   // Call up our favorite editor on the file of commands.
 
   std::string cmd = VEDITOR;
-  cmd.append (" \"");
-  cmd.append (name);
-  cmd.append ("\"");
+  cmd.append (" \"" + name + "\"");
 
   // Ignore interrupts while we are off editing commands.  Should we
   // maybe avoid using system()?
@@ -441,17 +526,25 @@
   volatile octave_interrupt_handler old_interrupt_handler
     = octave_ignore_interrupts ();
 
-  system (cmd.c_str ());
+  int status = system (cmd.c_str ());
 
   octave_set_interrupt_handler (old_interrupt_handler);
 
+  // Check if text edition was successfull.  Abort the operation
+  // in case of failure.
+  if (status != EXIT_SUCCESS)
+    {
+      error ("edit_history: text editor command failed");
+      return;
+    }
+
   // Write the commands to the history file since source_file
   // disables command line history while it executes.
 
   std::fstream file (name.c_str (), std::ios::in);
 
   char *line;
-  int first = 1;
+  //int first = 1;
   while ((line = edit_history_readline (file)) != 0)
     {
       // Skip blank lines.
@@ -462,13 +555,19 @@
           continue;
         }
 
-      if (first)
-        {
-          first = 0;
-          edit_history_repl_hist (line);
-        }
-      else
-        edit_history_add_hist (line);
+      // FIXME: Don't delete this block of code until memory
+      //        leak in edit_history has been plugged and
+      //        it is clear that this code can be removed.
+      // Command 'edit history' has already been removed in mk_tmp_hist_file ()
+      //if (first)
+      //  {
+      //    first = 0;
+      //    edit_history_repl_hist (line);
+      //  }
+      //else
+      edit_history_add_hist (line);
+
+      delete [] line;
     }
 
   file.close ();
@@ -489,15 +588,14 @@
 }
 
 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, false, "run_history");
 
   if (name.empty ())
     return;
 
-  // Turn on command echo so the output from this will make better
-  // sense.
+  // Turn on command echo so the output from this will make better sense.
 
   unwind_protect frame;
 
@@ -518,6 +616,8 @@
                                default_history_file (),
                                default_history_size (),
                                octave_env::getenv ("OCTAVE_HISTCONTROL"));
+
+  octave_link::set_history (command_history::list ());
 }
 
 void
@@ -528,121 +628,158 @@
   std::string timestamp = now.strftime (Vhistory_timestamp_format_string);
 
   if (! timestamp.empty ())
-    command_history::add (timestamp);
+    {
+      command_history::add (timestamp); 
+      octave_link::append_history (timestamp);
+   }
 }
 
 DEFUN (edit_history, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Command} {} edit_history [@var{first}] [@var{last}]\n\
-If invoked with no arguments, @code{edit_history} allows you to edit the\n\
-history list using the editor named by the variable @w{@env{EDITOR}}.  The\n\
-commands to be edited are first copied to a temporary file.  When you\n\
-exit the editor, Octave executes the commands that remain in the file.\n\
-It is often more convenient to use @code{edit_history} to define functions\n\
+@deftypefn  {Command} {} edit_history\n\
+@deftypefnx {Command} {} edit_history @var{cmd_number}\n\
+@deftypefnx {Command} {} edit_history @var{first} @var{last}\n\
+Edit the history list using the editor named by the variable\n\
+@w{@env{EDITOR}}.\n\
+\n\
+The commands to be edited are first copied to a temporary file.  When you\n\
+exit the editor, Octave executes the commands that remain in the file.  It\n\
+is often more convenient to use @code{edit_history} to define functions\n\
 rather than attempting to enter them directly on the command line.\n\
-By default, the block of commands is executed as soon as you exit the\n\
-editor.  To avoid executing any commands, simply delete all the lines\n\
-from the buffer before exiting the editor.\n\
+The block of commands is executed as soon as you exit the editor.\n\
+To avoid executing any commands, simply delete all the lines from the buffer\n\
+before leaving the editor.\n\
 \n\
-The @code{edit_history} command takes two optional arguments specifying\n\
-the history numbers of first and last commands to edit.  For example,\n\
-the command\n\
+When invoked with no arguments, edit the previously executed command;\n\
+With one argument, edit the specified command @var{cmd_number};\n\
+With two arguments, edit the list of commands between @var{first} and\n\
+@var{last}.  Command number specifiers may also be negative where -1\n\
+refers to the most recently executed command.\n\
+The following are equivalent and edit the most recently executed command.\n\
 \n\
 @example\n\
-edit_history 13\n\
+@group\n\
+edit_history\n\
+edit_history -1\n\
+@end group\n\
 @end example\n\
 \n\
-@noindent\n\
-extracts all the commands from the 13th through the last in the history\n\
-list.  The command\n\
-\n\
-@example\n\
-edit_history 13 169\n\
-@end example\n\
-\n\
-@noindent\n\
-only extracts commands 13 through 169.  Specifying a larger number for\n\
-the first command than the last command reverses the list of commands\n\
-before placing them in the buffer to be edited.  If both arguments are\n\
-omitted, the previous command in the history list is used.\n\
+When using ranges, specifying a larger number for the first command than the\n\
+last command reverses the list of commands before they are placed in the\n\
+buffer to be edited.\n\
 @seealso{run_history}\n\
 @end deftypefn")
 {
   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\n\
+@deftypefnx {Command} {} history @var{opt1} @dots{}\n\
+@deftypefnx {Built-in Function} {@var{h} =} history ()\n\
+@deftypefnx {Built-in Function} {@var{h} =} history (@var{opt1}, @dots{})\n\
 If invoked with no arguments, @code{history} displays a list of commands\n\
 that you have executed.  Valid options are:\n\
 \n\
 @table @code\n\
-@item -w @var{file}\n\
-Write the current history to the file @var{file}.  If the name is\n\
-omitted, use the default history file (normally @file{~/.octave_hist}).\n\
+@item   @var{n}\n\
+@itemx -@var{n}\n\
+Display only the most recent @var{n} lines of history.\n\
+\n\
+@item -c\n\
+Clear the history list.\n\
+\n\
+@item -q\n\
+Don't number the displayed lines of history.  This is useful for cutting\n\
+and pasting commands using the X Window System.\n\
 \n\
 @item -r @var{file}\n\
 Read the file @var{file}, appending its contents to the current\n\
 history list.  If the name is omitted, use the default history file\n\
 (normally @file{~/.octave_hist}).\n\
 \n\
-@item @var{n}\n\
-Display only the most recent @var{n} lines of history.\n\
-\n\
-@item -q\n\
-Don't number the displayed lines of history.  This is useful for cutting\n\
-and pasting commands using the X Window System.\n\
+@item -w @var{file}\n\
+Write the current history to the file @var{file}.  If the name is\n\
+omitted, use the default history file (normally @file{~/.octave_hist}).\n\
 @end table\n\
 \n\
 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;
 }
 
 DEFUN (run_history, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Command} {} run_history [@var{first}] [@var{last}]\n\
-Similar to @code{edit_history}, except that the editor is not invoked,\n\
-and the commands are simply executed as they appear in the history list.\n\
+@deftypefn  {Command} {} run_history\n\
+@deftypefnx {Command} {} run_history @var{cmd_number}\n\
+@deftypefnx {Command} {} run_history @var{first} @var{last}\n\
+Run commands from the history list.\n\
+\n\
+When invoked with no arguments, run the previously executed command;\n\
+With one argument, run the specified command @var{cmd_number};\n\
+With two arguments, run the list of commands between @var{first} and\n\
+@var{last}.  Command number specifiers may also be negative where -1\n\
+refers to the most recently executed command.\n\
+For example, the command\n\
+\n\
+@example\n\
+@group\n\
+run_history\n\
+     OR\n\
+run_history -1\n\
+@end group\n\
+@end example\n\
+\n\
+@noindent\n\
+executes the most recent command again.\n\
+The command\n\
+\n\
+@example\n\
+run_history 13 169\n\
+@end example\n\
+\n\
+@noindent\n\
+executes commands 13 through 169.\n\
+\n\
+Specifying a larger number for the first command than the last command\n\
+reverses the list of commands before executing them.\n\
+For example:\n\
+\n\
+@example\n\
+@group\n\
+disp (1)\n\
+disp (2)\n\
+run_history -1 -2\n\
+@result{}\n\
+ 2\n\
+ 1\n\
+@end group\n\
+@end example\n\
+\n\
 @seealso{edit_history}\n\
 @end deftypefn")
 {
   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;
 }
@@ -688,7 +825,7 @@
 @deftypefn  {Built-in Function} {@var{val} =} history_size ()\n\
 @deftypefnx {Built-in Function} {@var{old_val} =} history_size (@var{new_val})\n\
 Query or set the internal variable that specifies how many entries\n\
-to store in the history file.  The default value is @code{1024},\n\
+to store in the history file.  The default value is @code{1000},\n\
 but may be overridden by the environment variable @w{@env{OCTAVE_HISTSIZE}}.\n\
 @seealso{history_file, history_timestamp_format_string, saving_history}\n\
 @end deftypefn")
@@ -698,7 +835,8 @@
   int tmp = old_history_size;
 
   octave_value retval = set_internal_variable (tmp, args, nargout,
-                                               "history_size", -1, INT_MAX);
+                                               "history_size", -1,
+                                               std::numeric_limits<int>::max ());
 
   if (tmp != old_history_size)
     command_history::set_size (tmp);
rename from src/oct-hist.h
rename to libinterp/interpfcn/oct-hist.h
new file mode 100644
--- /dev/null
+++ b/libinterp/interpfcn/octave-link.cc
@@ -0,0 +1,404 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2011-2012 Jacob Dawid
+Copyright (C) 2011-2012 John P. Swensen
+
+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 "cmd-edit.h"
+#include "defun.h"
+#include "oct-env.h"
+#include "oct-mutex.h"
+#include "singleton-cleanup.h"
+#include "toplev.h"
+
+#include "octave-link.h"
+
+static int
+octave_readline_hook (void)
+{
+  octave_link::entered_readline_hook ();
+  octave_link::generate_events ();
+  octave_link::process_events ();
+  octave_link::finished_readline_hook ();
+
+  return 0;
+}
+
+octave_link *octave_link::instance = 0;
+
+octave_link::octave_link (void)
+  : event_queue_mutex (new octave_mutex ()), gui_event_queue (),
+    debugging (false), link_enabled (true)
+{
+  command_editor::add_event_hook (octave_readline_hook);
+}
+
+void
+octave_link::set_workspace (void)
+{
+  if (enabled ())
+    instance->do_set_workspace ((symbol_table::current_scope ()
+                                 == symbol_table::top_scope ()),
+                                symbol_table::workspace_info ());
+}
+
+// OBJ should be an object of a class that is derived from the base
+// class octave_link, or 0 to disconnect the link.  It is the
+// responsibility of the caller to delete obj.
+
+void
+octave_link::connect_link (octave_link* obj)
+{
+  if (obj && instance)
+    ::error ("octave_link is already linked!");
+  else
+    instance = obj;
+}
+
+void
+octave_link::do_generate_events (void)
+{
+}
+
+void
+octave_link::do_process_events (void)
+{
+  event_queue_mutex->lock ();
+
+  gui_event_queue.run ();
+
+  event_queue_mutex->unlock ();
+}
+
+void
+octave_link::do_discard_events (void)
+{
+  event_queue_mutex->lock ();
+
+  gui_event_queue.discard ();
+
+  event_queue_mutex->unlock ();
+}
+
+DEFUN (__octave_link_enabled__, , ,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {} __octave_link_enabled__ ()\n\
+Undocumented internal function.\n\
+@end deftypefn")
+{
+  return octave_value (octave_link::enabled ());
+}
+
+DEFUN (__octave_link_edit_file__, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {} __octave_link_edit_file__ (@var{file})\n\
+Undocumented internal function.\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+  if (args.length () == 1)
+    {
+      std::string file = args(0).string_value ();
+
+      if (! error_state)
+        {
+          flush_octave_stdout ();
+
+          retval = octave_link::edit_file (file);
+        }
+      else
+        error ("expecting file name as argument");
+    }
+
+  return retval;
+}
+
+DEFUN (__octave_link_message_dialog__, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {} __octave_link_message_dialog__ (@var{dlg}, @var{msg}, @var{title})\n\
+Undocumented internal function.\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+  if (args.length () == 3)
+    {
+      std::string dlg = args(0).string_value ();
+      std::string msg = args(1).string_value ();
+      std::string title = args(2).string_value ();
+
+      if (! error_state)
+        {
+          flush_octave_stdout ();
+
+          retval = octave_link::message_dialog (dlg, msg, title);
+        }
+      else
+        error ("invalid arguments");
+    }
+
+  return retval;
+}
+
+DEFUN (__octave_link_question_dialog__, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {} __octave_link_question_dialog__ (@var{msg}, @var{title}, @var{btn1}, @var{btn2}, @var{btn3}, @var{default})\n\
+Undocumented internal function.\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+  if (args.length () == 6)
+    {
+      std::string msg = args(0).string_value ();
+      std::string title = args(1).string_value ();
+      std::string btn1 = args(2).string_value ();
+      std::string btn2 = args(3).string_value ();
+      std::string btn3 = args(4).string_value ();
+      std::string btndef = args(5).string_value ();
+
+      if (! error_state)
+        {
+          flush_octave_stdout ();
+
+          retval = octave_link::question_dialog (msg, title, btn1, btn2, btn3, btndef);
+        }
+      else
+        error ("invalid arguments");
+    }
+
+  return retval;
+}
+
+DEFUN (__octave_link_file_dialog__, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {} __octave_link_file_dialog__ (@var{filterlist}, @var{title}, @var{filename}, @var{size} @var{multiselect}, @var{pathname})\n\
+Undocumented internal function.\n\
+@end deftypefn")
+{
+  octave_value_list retval;
+
+  if (args.length () == 6)
+    {
+
+      const Array<std::string> flist = args(0).cellstr_value ();
+      std::string title = args(1).string_value ();
+      std::string filename = args(2).string_value ();
+      Matrix pos = args(3).matrix_value ();
+      std::string multi_on = args(4).string_value (); // on, off, create
+      std::string pathname = args(5).string_value ();
+
+      octave_idx_type nel = flist.numel ();
+      octave_link::filter_list filter_lst;
+
+      for (octave_idx_type i = 0; i < flist.rows (); i++)
+        filter_lst.push_back (std::make_pair (flist(i,0),
+                                              (flist.columns () > 1
+                                               ? flist(i,1) : "")));
+
+      if (! error_state)
+        {
+          flush_octave_stdout ();
+
+          std::list<std::string> items_lst
+            = octave_link::file_dialog (filter_lst, title, filename, pathname,
+                                        multi_on);
+
+          nel = items_lst.size ();
+
+          retval.resize (3);
+
+          // If 3, then is filename, directory and selected index.
+          if (nel <= 3)
+            {
+              int idx = 0;
+              for (std::list<std::string>::iterator it = items_lst.begin ();
+                   it != items_lst.end (); it++)
+                {
+                  retval(idx++) = *it;
+
+                  if (idx == 1 && retval(0).string_value ().length () == 0)
+                    retval(0) = 0;
+
+                  if (idx == 3)
+                    retval(2) = atoi (retval(2).string_value ().c_str ());
+                }
+            }
+          else
+            {
+              // Multiple files.
+              nel = items_lst.size ();
+              Cell items (dim_vector (1, nel));
+
+              std::list<std::string>::iterator it = items_lst.begin ();
+
+              for (int idx = 0; idx < items_lst.size ()-2; idx++)
+                {
+                  items.xelem (idx) = *it;
+                  it++;
+                }
+
+              retval(0) = items;
+              retval(1) = *it++;
+              retval(2) = atoi (it->c_str ());
+            }
+        }
+      else
+        error ("invalid arguments");
+    }
+
+  return retval;
+}
+
+DEFUN (__octave_link_list_dialog__, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {} __octave_link_list_dialog__ (@var{list}, @var{mode}, @var{size}, @var{intial}, @var{name}, @var{prompt}, @var{ok_string}, @var{cancel_string})\n\
+Undocumented internal function.\n\
+@end deftypefn")
+{
+  octave_value_list retval;
+
+  if (args.length () == 8)
+    {
+      Cell list = args(0).cell_value ();
+      const Array<std::string> tlist = list.cellstr_value ();
+      octave_idx_type nel = tlist.numel ();
+      std::list<std::string> list_lst;
+      for (octave_idx_type i = 0; i < nel; i++)
+        list_lst.push_back (tlist(i));
+
+      std::string mode = args(1).string_value ();
+
+      Matrix size_matrix = args(2).matrix_value ();
+      int width = size_matrix(0);
+      int height = size_matrix(1);
+
+      Matrix initial_matrix = args(3).matrix_value ();
+      nel = initial_matrix.numel ();
+      std::list<int> initial_lst;
+      for (octave_idx_type i = 0; i < nel; i++)
+        initial_lst.push_back (initial_matrix(i));
+
+      std::string name = args(4).string_value ();
+      list = args(5).cell_value ();
+      const Array<std::string> plist = list.cellstr_value ();
+      nel = plist.numel ();
+      std::list<std::string> prompt_lst;
+      for (octave_idx_type i = 0; i < nel; i++)
+        prompt_lst.push_back (plist(i));
+      std::string ok_string = args(6).string_value ();
+      std::string cancel_string = args(7).string_value ();
+
+      if (! error_state)
+        {
+          flush_octave_stdout ();
+
+          std::pair<std::list<int>, int> result
+            = octave_link::list_dialog (list_lst, mode, width, height,
+                                        initial_lst, name, prompt_lst,
+                                        ok_string, cancel_string);
+
+          std::list<int> items_lst = result.first;
+          nel = items_lst.size ();
+          Matrix items (dim_vector (1, nel));
+          octave_idx_type i = 0;
+          for (std::list<int>::iterator it = items_lst.begin ();
+               it != items_lst.end (); it++)
+            {
+              items.xelem(i++) = *it;
+            }
+
+          retval(1) = result.second;
+          retval(0) = items;
+        }
+      else
+        error ("invalid arguments");
+    }
+
+  return retval;
+}
+
+DEFUN (__octave_link_input_dialog__, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {} __octave_link_input_dialog__ (@var{prompt}, @var{title}, @var{rowscols}, @var{defaults})\n\
+Undocumented internal function.\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+  if (args.length () == 4)
+    {
+      Cell prompt = args(0).cell_value ();
+      Array<std::string> tmp = prompt.cellstr_value ();
+      octave_idx_type nel = tmp.numel ();
+      std::list<std::string> prompt_lst;
+      for (octave_idx_type i = 0; i < nel; i++)
+        prompt_lst.push_back (tmp(i));
+
+      std::string title = args(1).string_value ();
+
+      Matrix rc = args(2).matrix_value ();
+      nel = rc.rows ();
+      std::list<float> nr;
+      std::list<float> nc;
+      for (octave_idx_type i = 0; i < nel; i++)
+        {
+          nr.push_back (rc(i,0));
+          nc.push_back (rc(i,1));
+        }
+
+      Cell defaults = args(3).cell_value ();
+      tmp = defaults.cellstr_value ();
+      nel = tmp.numel ();
+      std::list<std::string> defaults_lst;
+      for (octave_idx_type i = 0; i < nel; i++)
+        defaults_lst.push_back (tmp(i));
+
+      if (! error_state)
+        {
+          flush_octave_stdout ();
+
+          std::list<std::string> items_lst
+            = octave_link::input_dialog (prompt_lst, title, nr, nc,
+                                         defaults_lst);
+
+          nel = items_lst.size ();
+          Cell items (dim_vector (1, nel));
+          octave_idx_type i = 0;
+          for (std::list<std::string>::iterator it = items_lst.begin ();
+               it != items_lst.end (); it++)
+            {
+              items.xelem(i++) = *it;
+            }
+
+          retval = items;
+        }
+      else
+        error ("invalid arguments");
+    }
+
+  return retval;
+}
new file mode 100644
--- /dev/null
+++ b/libinterp/interpfcn/octave-link.h
@@ -0,0 +1,428 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+Copyright (C) 2011-2012 Jacob Dawid
+Copyright (C) 2011-2012 John P. Swensen
+
+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_link_h)
+#define octave_link_h 1
+
+#include <string>
+
+#include "event-queue.h"
+
+class octave_mutex;
+class string_vector;
+class workspace_element;
+
+// \class OctaveLink
+// \brief Provides threadsafe access to octave.
+// \author Jacob Dawid
+//
+// This class is a wrapper around octave and provides thread safety by
+// buffering access operations to octave and executing them in the
+// readline event hook, which lives in the octave thread.
+
+class octave_link
+{
+protected:
+
+  octave_link (void);
+
+public:
+
+  virtual ~octave_link (void) { }
+
+  static void generate_events (void)
+  {
+    if (enabled ())
+      instance->do_generate_events ();
+  }
+
+  // If disable is TRUE, then no additional events will be processed
+  // other than exit.
+
+  static void process_events (bool disable = false)
+  {
+    if (enabled ())
+      {
+        if (disable)
+          instance->link_enabled = false;
+
+        instance->do_process_events ();
+      }
+  }
+
+  static void discard_events (void)
+  {
+    if (enabled ())
+      instance->do_discard_events ();
+  }
+
+  static bool exit (int status)
+  {
+    bool retval = false;
+
+    if (instance_ok ())
+      retval = instance->do_exit (status);
+
+    return retval;
+  }
+
+  template <class T>
+  static void post_event (T *obj, void (T::*method) (void))
+  {
+    if (enabled ())
+      instance->do_post_event (obj, method);
+  }
+
+  template <class T, class A>
+  static void post_event (T *obj, void (T::*method) (A), A arg)
+  {
+    if (enabled ())
+      instance->do_post_event (obj, method, arg);
+  }
+
+  template <class T, class A>
+  static void post_event (T *obj, void (T::*method) (const A&), const A& arg)
+  {
+    if (enabled ())
+      instance->do_post_event (obj, method, arg);
+  }
+
+  template <class T, class A, class B>
+  static void post_event (T *obj, void (T::*method) (const A&, const B&),
+                          const A& arg_a, const B& arg_b)
+  {
+    if (enabled ())
+      instance->do_post_event (obj, method, arg_a, arg_b);
+  }
+
+  static void entered_readline_hook (void)
+  {
+    if (enabled ())
+      instance->do_entered_readline_hook ();
+  }
+
+  static void finished_readline_hook (void)
+  {
+    if (enabled ())
+      instance->do_finished_readline_hook ();
+  }
+
+  static bool
+  edit_file (const std::string& file)
+  {
+    return enabled () ? instance->do_edit_file (file) : false;
+  }
+
+  static int
+  message_dialog (const std::string& dlg, const std::string& msg,
+                  const std::string& title)
+  {
+    return enabled () ? instance->do_message_dialog (dlg, msg, title) : 0;
+  }
+
+  static std::string
+  question_dialog (const std::string& msg, const std::string& title,
+                   const std::string& btn1, const std::string& btn2,
+                   const std::string& btn3, const std::string& btndef)
+  {
+    return enabled () ? instance->do_question_dialog (msg, title, btn1,
+                                                      btn2, btn3, btndef) : 0;
+  }
+
+  static std::pair<std::list<int>, int>
+  list_dialog (const std::list<std::string>& list,
+               const std::string& mode,
+               int width, int height,
+               const std::list<int>& initial_value,
+               const std::string& name,
+               const std::list<std::string>& prompt,
+               const std::string& ok_string,
+               const std::string& cancel_string)
+  {
+    return enabled ()
+      ? instance->do_list_dialog (list, mode, width, height,
+                                  initial_value, name, prompt,
+                                  ok_string, cancel_string)
+      : std::pair<std::list<int>, int> ();
+  }
+
+  static std::list<std::string>
+  input_dialog (const std::list<std::string>& prompt,
+                const std::string& title,
+                const std::list<float>& nr,
+                const std::list<float>& nc,
+                const std::list<std::string>& defaults)
+  {
+    return enabled ()
+      ? instance->do_input_dialog (prompt, title, nr, nc, defaults)
+      : std::list<std::string> ();
+  }
+
+  typedef std::list<std::pair<std::string, std::string> > filter_list;
+
+  static std::list<std::string>
+  file_dialog (const filter_list& filter, const std::string& title,
+               const std::string& filename, const std::string& dirname,
+               const std::string& multimode)
+  {
+    return enabled ()
+      ? instance->do_file_dialog (filter, title, filename, dirname, multimode)
+      : std::list<std::string> ();
+  }
+
+
+  static int debug_cd_or_addpath_error (const std::string& file,
+                                        const std::string& dir,
+                                        bool addpath_option)
+  {
+    return enabled ()
+      ? instance->do_debug_cd_or_addpath_error (file, dir, addpath_option) : 0;
+  }
+
+  static void change_directory (const std::string& dir)
+  {
+    if (enabled ())
+      instance->do_change_directory (dir);
+  }
+
+  // Preserves pending input.
+  static void execute_command_in_terminal (const std::string& command)
+  {
+    if (enabled ())
+      instance->do_execute_command_in_terminal (command);
+  }
+
+  static void set_workspace (void);
+
+  static void set_workspace (bool top_level,
+                             const std::list<workspace_element>& ws)
+  {
+    if (enabled ())
+      instance->do_set_workspace (top_level, ws);
+  }
+
+  static void clear_workspace (void)
+  {
+    if (enabled ())
+      instance->do_clear_workspace ();
+  }
+
+  static void set_history (const string_vector& hist)
+  {
+    if (enabled ())
+      instance->do_set_history (hist);
+  }
+
+  static void append_history (const std::string& hist_entry)
+  {
+    if (enabled ())
+      instance->do_append_history (hist_entry);
+  }
+
+  static void clear_history (void)
+  {
+    if (enabled ())
+      instance->do_clear_history ();
+  }
+
+  static void pre_input_event (void)
+  {
+    if (enabled ())
+      instance->do_pre_input_event ();
+  }
+
+  static void post_input_event (void)
+  {
+    if (enabled ())
+      instance->do_post_input_event ();
+  }
+
+  static void enter_debugger_event (const std::string& file, int line)
+  {
+    if (enabled ())
+      {
+        instance->debugging = true;
+
+        instance->do_enter_debugger_event (file, line);
+      }
+  }
+
+  static void execute_in_debugger_event (const std::string& file, int line)
+  {
+    if (enabled ())
+      instance->do_execute_in_debugger_event (file, line);
+  }
+
+  static void exit_debugger_event (void)
+  {
+    if (enabled () && instance->debugging)
+      {
+        instance->debugging = false;
+
+        instance->do_exit_debugger_event ();
+      }
+  }
+
+  static void
+  update_breakpoint (bool insert, const std::string& file, int line)
+  {
+    if (enabled ())
+      instance->do_update_breakpoint (insert, file, line);
+  }
+
+  static void connect_link (octave_link *);
+
+  static void set_default_prompts (std::string& ps1, std::string& ps2,
+                                   std::string& ps4)
+  {
+    if (enabled ())
+      instance->do_set_default_prompts (ps1, ps2, ps4);
+  }
+
+  static bool enabled (void)
+  {
+    return instance_ok () ? instance->link_enabled : false;
+  }
+
+private:
+
+  static octave_link *instance;
+
+  // No copying!
+
+  octave_link (const octave_link&);
+
+  octave_link& operator = (const octave_link&);
+
+  static bool instance_ok (void) { return instance != 0; }
+
+protected:
+
+  // Semaphore to lock access to the event queue.
+  octave_mutex *event_queue_mutex;
+
+  // Event Queue.
+  event_queue gui_event_queue;
+
+  bool debugging;
+  bool link_enabled;
+
+  void do_generate_events (void);
+  void do_process_events (void);
+  void do_discard_events (void);
+
+  template <class T>
+  void do_post_event (T *obj, void (T::*method) (void))
+  {
+    gui_event_queue.add_method (obj, method);
+  }
+
+  template <class T, class A>
+  void do_post_event (T *obj, void (T::*method) (A), A arg)
+  {
+    gui_event_queue.add_method (obj, method, arg);
+  }
+
+  template <class T, class A>
+  void do_post_event (T *obj, void (T::*method) (const A&), const A& arg)
+  {
+    gui_event_queue.add_method (obj, method, arg);
+  }
+
+  void do_entered_readline_hook (void) { }
+  void do_finished_readline_hook (void) { }
+
+  virtual bool do_exit (int status) = 0;
+
+  virtual bool do_edit_file (const std::string& file) = 0;
+
+  virtual int
+  do_message_dialog (const std::string& dlg, const std::string& msg,
+                     const std::string& title) = 0;
+
+  virtual std::string
+  do_question_dialog (const std::string& msg, const std::string& title,
+                      const std::string& btn1, const std::string& btn2,
+                      const std::string& btn3, const std::string& btndef) = 0;
+
+  virtual std::pair<std::list<int>, int>
+  do_list_dialog (const std::list<std::string>& list,
+                  const std::string& mode,
+                  int width, int height,
+                  const std::list<int>& initial_value,
+                  const std::string& name,
+                  const std::list<std::string>& prompt,
+                  const std::string& ok_string,
+                  const std::string& cancel_string) = 0;
+
+  virtual std::list<std::string>
+  do_input_dialog (const std::list<std::string>& prompt,
+                   const std::string& title,
+                   const std::list<float>& nr,
+                   const std::list<float>& nc,
+                   const std::list<std::string>& defaults) = 0;
+
+  virtual std::list<std::string>
+  do_file_dialog (const filter_list& filter, const std::string& title,
+                  const std::string& filename, const std::string& dirname,
+                  const std::string& multimode) = 0;
+
+  virtual int
+  do_debug_cd_or_addpath_error (const std::string& file,
+                                const std::string& dir,
+                                bool addpath_option) = 0;
+
+  virtual void do_change_directory (const std::string& dir) = 0;
+
+  virtual void do_execute_command_in_terminal (const std::string& command) = 0;
+
+  virtual void
+  do_set_workspace (bool top_level,
+                    const std::list<workspace_element>& ws) = 0;
+
+  virtual void do_clear_workspace (void) = 0;
+
+  virtual void do_set_history (const string_vector& hist) = 0;
+  virtual void do_append_history (const std::string& hist_entry) = 0;
+  virtual void do_clear_history (void) = 0;
+
+  virtual void do_pre_input_event (void) = 0;
+  virtual void do_post_input_event (void) = 0;
+
+  virtual void
+  do_enter_debugger_event (const std::string& file, int line) = 0;
+
+  virtual void
+  do_execute_in_debugger_event (const std::string& file, int line) = 0;
+
+  virtual void do_exit_debugger_event (void) = 0;
+
+  virtual void do_update_breakpoint (bool insert,
+                                     const std::string& file, int line) = 0;
+
+  virtual void do_set_default_prompts (std::string& ps1, std::string& ps2,
+                                       std::string& ps4) = 0;
+};
+
+#endif // OCTAVELINK_H
rename from src/pager.cc
rename to libinterp/interpfcn/pager.cc
--- a/src/pager.cc
+++ b/libinterp/interpfcn/pager.cc
@@ -108,7 +108,7 @@
 
   if (pid > 0)
     {
-      if (WIFEXITED (status) || WIFSIGNALLED (status))
+      if (octave_wait::ifexited (status) || octave_wait::ifsignaled (status))
         {
           // Avoid warning() since that will put us back in the pager,
           // which would be bad news.
@@ -591,6 +591,7 @@
 Turn output pagination on or off.  Without an argument, @code{more}\n\
 toggles the current state.\n\
 The current state can be determined via @code{page_screen_output}.\n\
+@seealso{page_screen_output, page_output_immediately, PAGER, PAGER_FLAGS}\n\
 @end deftypefn")
 {
   octave_value_list retval;
@@ -650,6 +651,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{page_screen_output, more, PAGER, PAGER_FLAGS}\n\
 @end deftypefn")
 {
   return SET_INTERNAL_VARIABLE (page_output_immediately);
@@ -669,6 +671,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{more, page_output_immediately, PAGER, PAGER_FLAGS}\n\
 @end deftypefn")
 {
   return SET_INTERNAL_VARIABLE (page_screen_output);
@@ -688,7 +691,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{more, page_screen_output, page_output_immediately, PAGER_FLAGS}\n\
+@seealso{PAGER_FLAGS, page_output_immediately, more, page_screen_output}\n\
 @end deftypefn")
 {
   return SET_NONEMPTY_INTERNAL_STRING_VARIABLE (PAGER);
@@ -705,7 +708,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{PAGER}\n\
+@seealso{PAGER, more, page_screen_output, page_output_immediately}\n\
 @end deftypefn")
 {
   return SET_NONEMPTY_INTERNAL_STRING_VARIABLE (PAGER_FLAGS);
rename from src/pager.h
rename to libinterp/interpfcn/pager.h
rename from src/pr-output.cc
rename to libinterp/interpfcn/pr-output.cc
--- a/src/pr-output.cc
+++ b/libinterp/interpfcn/pr-output.cc
@@ -303,8 +303,8 @@
   else
     os << std::setw (0) << "e+";
 
-  os << std::setw (pef.f.ex - 2) << std::setfill('0') << ex
-     << std::setfill(' ');
+  os << std::setw (pef.f.ex - 2) << std::setfill ('0') << ex
+     << std::setfill (' ');
 
   os.flags (oflags);
 
@@ -356,11 +356,13 @@
     s = "1/0";
   else if (xisnan (val))
     s = "0/0";
-  else if (val < INT_MIN || val > INT_MAX || D_NINT (val) == val)
+  else if (val < std::numeric_limits<int>::min ()
+           || val > std::numeric_limits<int>::max ()
+           || D_NINT (val) == val)
     {
       std::ostringstream buf;
       buf.flags (std::ios::fixed);
-      buf << std::setprecision (0) << xround(val);
+      buf << std::setprecision (0) << xround (val);
       s = buf.str ();
     }
   else
@@ -375,7 +377,7 @@
       std::ostringstream buf2;
       buf2.flags (std::ios::fixed);
       buf2 << std::setprecision (0) << static_cast<int>(n);
-      s = buf2.str();
+      s = buf2.str ();
 
       while (1)
         {
@@ -385,7 +387,7 @@
           double nextd = d;
 
           // Have we converged to 1/intmax ?
-          if (m > 100 || fabs (frac) < 1 / static_cast<double>(INT_MAX))
+          if (m > 100 || fabs (frac) < 1 / static_cast<double> (std::numeric_limits<int>::max ()))
             {
               lastn = n;
               lastd = d;
@@ -407,15 +409,15 @@
           if (n < 0 && d < 0)
             {
               // Double negative, string can be two characters longer..
-              if (buf.str().length() > static_cast<unsigned int>(len + 2) &&
+              if (buf.str ().length () > static_cast<unsigned int>(len + 2) &&
                   m > 1)
                 break;
             }
-          else if (buf.str().length() > static_cast<unsigned int>(len) &&
+          else if (buf.str ().length () > static_cast<unsigned int>(len) &&
                    m > 1)
             break;
 
-          s = buf.str();
+          s = buf.str ();
         }
 
       if (lastd < 0.)
@@ -427,7 +429,7 @@
           buf.flags (std::ios::fixed);
           buf << std::setprecision (0) << static_cast<int>(lastn)
                << "/" << static_cast<int>(lastd);
-          s = buf.str();
+          s = buf.str ();
         }
     }
 
@@ -460,7 +462,7 @@
     os.flags (static_cast<std::ios::fmtflags>
               (prf.f.fmt | prf.f.up | prf.f.sp));
 
-  if (fw > 0 && s.length() > static_cast<unsigned int>(fw))
+  if (fw > 0 && s.length () > static_cast<unsigned int>(fw))
     os << "*";
   else
     os << s;
@@ -483,7 +485,7 @@
   octave_idx_type nr = m.rows ();
   octave_idx_type nc = m.columns ();
 
-  double result = -DBL_MAX;
+  double result = -std::numeric_limits<double>::max ();
 
   bool all_inf_or_nan = true;
 
@@ -512,7 +514,7 @@
   octave_idx_type nr = m.rows ();
   octave_idx_type nc = m.columns ();
 
-  double result = DBL_MAX;
+  double result = std::numeric_limits<double>::max ();
 
   bool all_inf_or_nan = true;
 
@@ -603,23 +605,24 @@
         fmt = float_format ();
       else
         {
-          int ex = 4;
-          if (digits > 100)
-            ex++;
+          // e+ddd
+          int ex = 5;
 
           if (print_eng)
             {
-              fw = 4 + prec + ex;
+              // -ddd.
+              fw = 5 + prec + ex;
               if (inf_or_nan && fw < 6)
                 fw = 6;
               fmt = float_format (fw, ex, prec - 1, std::ios::fixed);
             }
           else
             {
-              fw = 2 + prec + ex;
+              // -d.
+              fw = 3 + prec + ex;
               if (inf_or_nan && fw < 4)
                 fw = 4;
-              fmt = float_format (fw, prec - 1, std::ios::scientific);
+              fmt = float_format (fw, ex, prec - 1, std::ios::scientific);
             }
         }
 
@@ -2004,8 +2007,8 @@
 }
 
 template <typename NDA_T, typename ELT_T, typename MAT_T>
-void print_nd_array(std::ostream& os, const NDA_T& nda,
-                    bool pr_as_read_syntax)
+void print_nd_array (std::ostream& os, const NDA_T& nda,
+                     bool pr_as_read_syntax)
 {
 
   if (nda.is_empty ())
@@ -2722,14 +2725,17 @@
                 {
                   octave_quit ();
 
-                  double val = base + i * increment;
+                  double val;
+                  if (i == 0)
+                    val = base;
+                  else
+                    val = base + i * increment;
 
                   if (i == num_elem - 1)
                     {
                       // See the comments in Range::matrix_value.
-
-                      if ((increment > 0 && val > limit)
-                          || (increment < 0 && val < limit))
+                      if ((increment > 0 && val >= limit)
+                          || (increment < 0 && val <= limit))
                         val = limit;
                     }
 
@@ -2964,8 +2970,8 @@
 /* static */ inline void
 pr_int (std::ostream& os, const T& d, int fw = 0)
 {
-  size_t sz = d.byte_size();
-  const unsigned char * tmpi = d.iptr();
+  size_t sz = d.byte_size ();
+  const unsigned char * tmpi = d.iptr ();
 
   // Unless explicitly asked for, always print in big-endian
   // format for hex and bit formats.
@@ -3376,8 +3382,8 @@
 \n\
 @example\n\
 @group\n\
-   r = rats(hilb(4));\n\
-   x = str2num(r)\n\
+r = rats (hilb (4));\n\
+x = str2num (r)\n\
 @end group\n\
 @end example\n\
 \n\
@@ -3554,13 +3560,13 @@
 %! foo.char = repmat ("- Hello World -", [3, 20]);
 %! foo.cell = {foo.real, foo.complex, foo.char};
 %! fields = fieldnames (foo);
-%! for f = 1:numel(fields)
-%!   format loose
+%! for f = 1:numel (fields)
+%!   format loose;
 %!   loose = disp (foo.(fields{f}));
-%!   format compact
+%!   format compact;
 %!   compact = disp (foo.(fields{f}));
 %!   expected = strrep (loose, "\n\n", "\n");
-%!   assert (expected, compact)
+%!   assert (expected, compact);
 %! endfor
 */
 
@@ -4068,7 +4074,8 @@
 @seealso{format, fixed_point_format, output_precision}\n\
 @end deftypefn")
 {
-  return SET_INTERNAL_VARIABLE_WITH_LIMITS (output_max_field_width, 0, INT_MAX);
+  return SET_INTERNAL_VARIABLE_WITH_LIMITS (output_max_field_width, 0,
+                                            std::numeric_limits<int>::max ());
 }
 
 DEFUN (output_precision, args, nargout,
@@ -4085,5 +4092,6 @@
 @seealso{format, fixed_point_format, output_max_field_width}\n\
 @end deftypefn")
 {
-  return SET_INTERNAL_VARIABLE_WITH_LIMITS (output_precision, -1, INT_MAX);
+  return SET_INTERNAL_VARIABLE_WITH_LIMITS (output_precision, -1,
+                                            std::numeric_limits<int>::max ());
 }
rename from src/pr-output.h
rename to libinterp/interpfcn/pr-output.h
rename from src/profiler.cc
rename to libinterp/interpfcn/profiler.cc
rename from src/profiler.h
rename to libinterp/interpfcn/profiler.h
rename from src/sighandlers.cc
rename to libinterp/interpfcn/sighandlers.cc
--- a/src/sighandlers.cc
+++ b/libinterp/interpfcn/sighandlers.cc
@@ -61,9 +61,9 @@
 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-core for SIGHUP (sent by
+// Allow users to avoid writing octave-workspace for SIGHUP (sent by
 // closing gnome-terminal, for example).  Note that this variable has
 // no effect if Vcrash_dumps_octave_core is FALSE.
 static bool Vsighup_dumps_octave_core = true;
@@ -147,12 +147,12 @@
 #endif
 
             case SIGFPE:
-              std::cerr << "warning: floating point exception -- trying to return to prompt" << std::endl;
+              std::cerr << "warning: floating point exception" << std::endl;
               break;
 
 #ifdef SIGPIPE
             case SIGPIPE:
-              std::cerr << "warning: broken pipe -- some output may be lost" << std::endl;
+              std::cerr << "warning: broken pipe" << std::endl;
               break;
 #endif
             }
@@ -252,7 +252,7 @@
 
   octave_signals_caught[SIGCHLD] = true;
 }
-#endif /* defined(SIGCHLD) */
+#endif /* defined (SIGCHLD) */
 
 #ifdef SIGFPE
 #if defined (__alpha__)
@@ -268,8 +268,8 @@
       octave_interrupt_state++;
     }
 }
-#endif /* defined(__alpha__) */
-#endif /* defined(SIGFPE) */
+#endif /* defined (__alpha__) */
+#endif /* defined (SIGFPE) */
 
 #if defined (SIGHUP) || defined (SIGTERM)
 static void
@@ -378,14 +378,7 @@
 static void
 sigint_handler (int sig)
 {
-#ifdef USE_W32_SIGINT
-  if (w32_in_main_thread ())
-    user_abort (strsignal (sig), sig);
-  else
-    w32_raise (sig);
-#else
   user_abort (strsignal (sig), sig);
-#endif
 }
 
 #ifdef SIGPIPE
@@ -401,61 +394,7 @@
   if (pipe_handler_error_count++ > 100 && octave_interrupt_state >= 0)
     octave_interrupt_state++;
 }
-#endif /* defined(SIGPIPE) */
-
-#ifdef USE_W32_SIGINT
-static BOOL CALLBACK
-w32_sigint_handler (DWORD sig)
-{
-  const char *sig_name;
-
-  switch(sig)
-    {
-      case CTRL_BREAK_EVENT:
-        sig_name = "Ctrl-Break";
-        break;
-      case CTRL_C_EVENT:
-        sig_name = "Ctrl-C";
-        break;
-      case CTRL_CLOSE_EVENT:
-        sig_name = "close console";
-        break;
-      case CTRL_LOGOFF_EVENT:
-        sig_name = "logoff";
-        break;
-      case CTRL_SHUTDOWN_EVENT:
-        sig_name = "shutdown";
-        break;
-      default:
-        sig_name = "unknown console event";
-        break;
-    }
-
-  switch(sig)
-    {
-      case CTRL_BREAK_EVENT:
-      case CTRL_C_EVENT:
-        w32_raise (SIGINT);
-        break;
-
-      case CTRL_CLOSE_EVENT:
-      case CTRL_LOGOFF_EVENT:
-      case CTRL_SHUTDOWN_EVENT:
-      default:
-        // We should do the following:
-        //    clean_up_and_exit (0);
-        // We can't because we aren't running in the normal Octave thread.
-        user_abort(sig_name, sig);
-        break;
-    }
-
-  // Return TRUE if the event was handled, or FALSE if another handler
-  // should be called.
-  // FIXME check that windows terminates the thread.
-  return TRUE;
-}
-#endif /* w32_sigint_handler */
-
+#endif /* defined (SIGPIPE) */
 
 octave_interrupt_handler
 octave_catch_interrupts (void)
@@ -470,22 +409,6 @@
   retval.brk_handler = octave_set_signal_handler (SIGBREAK, sigint_handler);
 #endif
 
-#ifdef USE_W32_SIGINT
-
-  // Intercept windows console control events.
-  // Note that the windows console signal handlers chain, so if
-  // install_signal_handlers is called more than once in the same program,
-  // then first call the following to avoid duplicates:
-  //
-  //   SetConsoleCtrlHandler (w32_sigint_handler, FALSE);
-
-  if (! SetConsoleCtrlHandler (w32_sigint_handler, TRUE))
-    error ("SetConsoleCtrlHandler failed with %ld\n", GetLastError ());
-
-  w32_set_quiet_shutdown ();
-
-#endif
-
   return retval;
 }
 
@@ -957,9 +880,10 @@
 }
 
 /*
-%!error SIG (1);
-%!assert (isstruct (SIG ()));
-%!assert (! isempty (SIG ()));
+%!assert (isstruct (SIG ()))
+%!assert (! isempty (SIG ()))
+
+%!error SIG (1)
 */
 
 DEFUN (debug_on_interrupt, args, nargout,
@@ -982,7 +906,6 @@
 }
 
 /*
-%!error (debug_on_interrupt (1, 2));
 %!test
 %! orig_val = debug_on_interrupt ();
 %! old_val = debug_on_interrupt (! orig_val);
@@ -990,6 +913,8 @@
 %! assert (debug_on_interrupt (), ! orig_val);
 %! debug_on_interrupt (orig_val);
 %! assert (debug_on_interrupt (), orig_val);
+
+%!error (debug_on_interrupt (1, 2))
 */
 
 DEFUN (sighup_dumps_octave_core, args, nargout,
@@ -998,7 +923,7 @@
 @deftypefnx {Built-in Function} {@var{old_val} =} sighup_dumps_octave_core (@var{new_val})\n\
 @deftypefnx {Built-in Function} {} sighup_dumps_octave_core (@var{new_val}, \"local\")\n\
 Query or set the internal variable that controls whether Octave tries\n\
-to save all current variables to the file \"octave-core\" if it receives\n\
+to save all current variables to the file \"octave-workspace\" if it receives\n\
 a hangup signal.\n\
 \n\
 When called from inside a function with the \"local\" option, the variable is\n\
@@ -1010,7 +935,6 @@
 }
 
 /*
-%!error (sighup_dumps_octave_core (1, 2));
 %!test
 %! orig_val = sighup_dumps_octave_core ();
 %! old_val = sighup_dumps_octave_core (! orig_val);
@@ -1018,6 +942,8 @@
 %! assert (sighup_dumps_octave_core (), ! orig_val);
 %! sighup_dumps_octave_core (orig_val);
 %! assert (sighup_dumps_octave_core (), orig_val);
+
+%!error (sighup_dumps_octave_core (1, 2))
 */
 
 DEFUN (sigterm_dumps_octave_core, args, nargout,
@@ -1026,7 +952,7 @@
 @deftypefnx {Built-in Function} {@var{old_val} =} sigterm_dumps_octave_core (@var{new_val})\n\
 @deftypefnx {Built-in Function} {} sigterm_dumps_octave_core (@var{new_val}, \"local\")\n\
 Query or set the internal variable that controls whether Octave tries\n\
-to save all current variables to the file \"octave-core\" if it receives\n\
+to save all current variables to the file \"octave-workspace\" if it receives\n\
 a terminate signal.\n\
 \n\
 When called from inside a function with the \"local\" option, the variable is\n\
@@ -1038,7 +964,6 @@
 }
 
 /*
-%!error (sigterm_dumps_octave_core (1, 2));
 %!test
 %! orig_val = sigterm_dumps_octave_core ();
 %! old_val = sigterm_dumps_octave_core (! orig_val);
@@ -1046,4 +971,6 @@
 %! assert (sigterm_dumps_octave_core (), ! orig_val);
 %! sigterm_dumps_octave_core (orig_val);
 %! assert (sigterm_dumps_octave_core (), orig_val);
+
+%!error (sigterm_dumps_octave_core (1, 2))
 */
rename from src/sighandlers.h
rename to libinterp/interpfcn/sighandlers.h
--- a/src/sighandlers.h
+++ b/libinterp/interpfcn/sighandlers.h
@@ -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
rename from src/symtab.cc
rename to libinterp/interpfcn/symtab.cc
--- a/src/symtab.cc
+++ b/libinterp/interpfcn/symtab.cc
@@ -78,11 +78,25 @@
   singleton_cleanup_list::add (cleanup_instance);
 }
 
+symbol_table::context_id
+symbol_table::symbol_record::symbol_record_rep::active_context (void) const
+{
+  octave_user_function *fcn = curr_fcn;
+
+  // FIXME -- If active_context () == -1, then it does not make much
+  // sense to use this symbol_record. This means an attempt at accessing
+  // a variable from a function that has not been called yet is
+  // happening. This should be cleared up when an implementing closures.
+
+  return fcn && fcn->active_context () != static_cast<context_id> (-1)
+    ? fcn->active_context () : xcurrent_context;
+}
+
 void
 symbol_table::symbol_record::symbol_record_rep::dump
   (std::ostream& os, const std::string& prefix) const
 {
-  octave_value val = varval (xcurrent_context);
+  octave_value val = varval ();
 
   os << prefix << name;
 
@@ -109,7 +123,7 @@
   octave_value retval;
 
   if (is_global ())
-    retval = symbol_table::global_varref (name ());
+    retval = symbol_table::global_varval (name ());
   else
     {
       retval = varval ();
@@ -625,40 +639,23 @@
       // subfunctions if we are currently executing a function defined
       // from a .m file.
 
-      scope_val_iterator r = subfunctions.find (xcurrent_scope);
-
       octave_user_function *curr_fcn = symbol_table::get_curr_fcn ();
 
-      if (r != subfunctions.end ())
+      for (scope_id scope = xcurrent_scope; scope >= 0;)
         {
-          // FIXME -- out-of-date check here.
-
-          return r->second;
-        }
-      else
-        {
-          if (curr_fcn)
+          scope_val_iterator r = subfunctions.find (scope);
+          if (r != subfunctions.end ())
             {
-              // FIXME -- maybe it would be better if we could just get
-              // a pointer to the parent function so we would have
-              // access to all info about it instead of only being able
-              // to query the current function for specific bits of info
-              // about its parent function?
+              // FIXME -- out-of-date check here.
 
-              scope_id pscope = curr_fcn->parent_fcn_scope ();
+              return r->second;
+            }
 
-              if (pscope > 0)
-                {
-                  r = subfunctions.find (pscope);
-
-                  if (r != subfunctions.end ())
-                    {
-                      // FIXME -- out-of-date check here.
-
-                      return r->second;
-                    }
-                }
-            }
+          octave_user_function *scope_curr_fcn = get_curr_fcn (scope);
+          if (scope_curr_fcn)
+            scope = scope_curr_fcn->parent_fcn_scope ();
+          else
+            scope = -1;
         }
 
       // Private function.
@@ -896,29 +893,21 @@
   // subfunctions if we are currently executing a function defined
   // from a .m file.
 
-  scope_val_iterator r = subfunctions.find (xcurrent_scope);
-
-  if (r != subfunctions.end ())
+  for (scope_id scope = xcurrent_scope; scope >= 0;)
     {
-      // FIXME -- out-of-date check here.
-
-      return r->second;
-    }
-  else if (curr_fcn)
-    {
-      scope_id pscope = curr_fcn->parent_fcn_scope ();
+      scope_val_iterator r = subfunctions.find (scope);
+      if (r != subfunctions.end ())
+        {
+          // FIXME -- out-of-date check here.
 
-      if (pscope > 0)
-        {
-          r = subfunctions.find (pscope);
+          return r->second;
+        }
 
-          if (r != subfunctions.end ())
-            {
-              // FIXME -- out-of-date check here.
-
-              return r->second;
-            }
-        }
+      octave_user_function *scope_curr_fcn = get_curr_fcn (scope);
+      if (scope_curr_fcn)
+        scope = scope_curr_fcn->parent_fcn_scope ();
+      else
+        scope = -1;
     }
 
   return octave_value ();
@@ -1024,20 +1013,12 @@
 symbol_table::set_class_relationship (const std::string& sup_class,
                                       const std::string& inf_class)
 {
-  class_precedence_table_const_iterator p
-    = class_precedence_table.find (inf_class);
-
-  if (p != class_precedence_table.end ())
-    {
-      const std::set<std::string>& inferior_classes = p->second;
+  if (is_superiorto (inf_class, sup_class))
+    return false;
 
-      std::set<std::string>::const_iterator q
-        = inferior_classes.find (sup_class);
-
-      if (q != inferior_classes.end ())
-        return false;
-    }
-
+  // If sup_class doesn't have an entry in the precedence table,
+  // this will automatically create it, and associate to it a
+  // singleton set {inf_class} of inferior classes.
   class_precedence_table[sup_class].insert (inf_class);
 
   return true;
@@ -1045,7 +1026,7 @@
 
 // Has class A been marked as superior to class B?  Also returns
 // TRUE if B has been marked as inferior to A, since we only keep
-// one table, and convert inferiort information to a superiorto
+// one table, and convert inferiorto information to a superiorto
 // relationship.  Two calls are required to determine whether there
 // is no relationship between two classes:
 //
@@ -1059,20 +1040,14 @@
 bool
 symbol_table::is_superiorto (const std::string& a, const std::string& b)
 {
-  bool retval = false;
-
   class_precedence_table_const_iterator p = class_precedence_table.find (a);
+  // If a has no entry in the precedence table, return false
+  if (p == class_precedence_table.end ())
+    return false;
 
-  if (p != class_precedence_table.end ())
-    {
-      const std::set<std::string>& inferior_classes = p->second;
-      std::set<std::string>::const_iterator q = inferior_classes.find (b);
-
-      if (q != inferior_classes.end ())
-        retval = true;
-    }
-
-  return retval;
+  const std::set<std::string>& inferior_classes = p->second;
+  std::set<std::string>::const_iterator q = inferior_classes.find (b);
+  return (q != inferior_classes.end ());
 }
 
 static std::string
@@ -1144,6 +1119,23 @@
     }
 }
 
+void
+symbol_table::install_nestfunction (const std::string& name,
+                                    const octave_value& fcn,
+                                    scope_id parent_scope)
+{
+  install_subfunction (name, fcn, parent_scope);
+
+  // Stash the nest_parent for resolving variables after parsing is done.
+  octave_function *fv = fcn.function_value ();
+
+  symbol_table *fcn_table_loc = get_instance (fv->scope ());
+
+  symbol_table *parent_table = get_instance (parent_scope);
+
+  parent_table->add_nest_child (*fcn_table_loc);
+}
+
 octave_value
 symbol_table::find (const std::string& name,
                     const octave_value_list& args,
@@ -1195,7 +1187,7 @@
           std::string fcn_scope = name.substr (0, pos);
           scope_id stored_scope = xcurrent_scope;
           xcurrent_scope = xtop_scope;
-          octave_value parent = find_function (name.substr(0, pos),
+          octave_value parent = find_function (name.substr (0, pos),
                                                octave_value_list (), false);
 
           if (parent.is_defined ())
@@ -1333,13 +1325,11 @@
         {
           symbol_record sr = p->second;
 
-          // FIXME -- should we be using something other than varref here?
-
           if (sr.is_global ())
-            return symbol_table::global_varref (name);
+            return symbol_table::global_varval (name);
           else
             {
-              octave_value& val = sr.varref ();
+              octave_value val = sr.varval ();
 
               if (val.is_defined ())
                 return val;
@@ -1390,6 +1380,49 @@
   return retval;
 }
 
+std::list<workspace_element>
+symbol_table::do_workspace_info (void) const
+{
+  std::list<workspace_element> retval;
+
+  for (table_const_iterator p = table.begin (); p != table.end (); p++)
+    {
+      std::string nm = p->first;
+      symbol_record sr = p->second;
+
+      if (! sr.is_hidden ())
+        {
+          octave_value val = sr.varval ();
+
+          if (val.is_defined ())
+            {
+              dim_vector dv = val.dims ();
+
+              char storage = ' ';
+              if (sr.is_global ())
+                storage = 'g';
+              else if (sr.is_persistent ())
+                storage = 'p';
+              else if (sr.is_automatic ())
+                storage = 'a';
+              else if (sr.is_formal ())
+                storage = 'f';
+              else if (sr.is_hidden ())
+                storage = 'h';
+              else if (sr.is_inherited ())
+                storage = 'i';
+
+              workspace_element elt (storage, nm, val.class_name (),
+                                     val.short_disp (), dv.str ());
+
+              retval.push_back (elt);
+            }
+        }
+    }
+
+  return retval;
+}
+
 void
 symbol_table::do_dump (std::ostream& os)
 {
@@ -1456,6 +1489,47 @@
     }
 }
 
+void
+symbol_table::do_update_nest (void)
+{
+  if (nest_parent || nest_children.size ())
+    curr_fcn->mark_as_nested_function ();
+
+  if (nest_parent)
+    {
+      // fix bad symbol_records
+      for (table_iterator ti = table.begin (); ti != table.end (); ++ti)
+        {
+          symbol_record &ours = ti->second;
+          symbol_record parents;
+          if (! ours.is_formal ()
+              && nest_parent->look_nonlocal (ti->first, parents))
+            {
+              if (ours.is_global () || ours.is_persistent ())
+                ::error ("global and persistent may only be used in the topmost level in which a nested variable is used");
+
+              if (! ours.is_formal ())
+                {
+                  ours.invalidate ();
+                  ti->second = parents;
+                }
+            }
+          else
+            ours.set_curr_fcn (curr_fcn);
+        }
+    }
+  else if (nest_children.size ())
+    {
+      static_workspace = true;
+      for (table_iterator ti = table.begin (); ti != table.end (); ++ti)
+        ti->second.set_curr_fcn (curr_fcn);
+    }
+
+  for (std::vector<symbol_table*>::iterator iter = nest_children.begin ();
+       iter != nest_children.end (); ++iter)
+    (*iter)->do_update_nest ();
+}
+
 DEFUN (ignore_function_time_stamp, args, nargout,
     "-*- texinfo -*-\n\
 @deftypefn  {Built-in Function} {@var{val} =} ignore_function_time_stamp ()\n\
@@ -1531,11 +1605,10 @@
 %! assert (ignore_function_time_stamp (), "system");
 %! ignore_function_time_stamp (old_state);
 
-%% Test input validation
+## Test input validation
 %!error (ignore_function_time_stamp ("all", "all"))
 %!error (ignore_function_time_stamp ("UNKNOWN_VALUE"))
 %!error (ignore_function_time_stamp (42))
-
 */
 
 DEFUN (__current_scope__, , ,
@@ -1635,7 +1708,7 @@
       std::string name = args(0).string_value ();
 
       if (! error_state)
-        symbol_table::varref (name) = args(1);
+        symbol_table::assign (name, args(1));
       else
         error ("set_variable: expecting variable name as first argument");
     }
@@ -1670,3 +1743,32 @@
   return retval;
 }
 #endif
+
+
+/*
+bug #34497: 'clear -f' does not work for command line functions
+
+This test relies on bar being a core function that is implemented in an m-file.
+If the first assert fails, this is no longer the case and the tests need to be
+updated to use some other function.
+
+%!assert (! strcmp (which ("bar"), ""));
+
+%!function x = bar ()
+%!  x = 5;
+%!endfunction
+%!test
+%! assert (bar == 5);
+%! assert (strcmp (which ("bar"), ""));
+%! clear -f bar;
+%! assert (! strcmp (which ("bar"), ""));
+
+%!function x = bar ()
+%!  x = 5;
+%!endfunction
+%!test
+%! assert (bar == 5);
+%! assert (strcmp (which ("bar"), ""));
+%! clear bar;
+%! assert (! strcmp (which ("bar"), ""));
+ */
rename from src/symtab.h
rename to libinterp/interpfcn/symtab.h
--- a/src/symtab.h
+++ b/libinterp/interpfcn/symtab.h
@@ -37,6 +37,7 @@
 class octave_user_function;
 
 #include "oct-obj.h"
+#include "workspace-element.h"
 #include "oct-refcount.h"
 #include "ov.h"
 
@@ -196,8 +197,9 @@
     // not cleared at function exit
     static const unsigned int persistent = 64;
 
-    // temporary variables forced into symbol table for parsing
-    static const unsigned int forced = 128;
+    // this symbol may NOT become a variable.
+    // (symbol added to a static workspace)
+    static const unsigned int added_static = 128;
 
   private:
 
@@ -206,29 +208,76 @@
     {
     public:
 
-      symbol_record_rep (const std::string& nm, const octave_value& v,
-                         unsigned int sc)
-        : name (nm), value_stack (), storage_class (sc), finfo (), count (1)
+      symbol_record_rep (scope_id s, const std::string& nm,
+                         const octave_value& v, unsigned int sc)
+        : decl_scope (s), curr_fcn (0), name (nm), value_stack (),
+          storage_class (sc), finfo (), valid (true), count (1)
       {
         value_stack.push_back (v);
       }
 
-      void force_variable (context_id context)
+      void assign (const octave_value& value,
+                   context_id context = xdefault_context)
+      {
+        varref (context) = value;
+      }
+
+      void assign (octave_value::assign_op op,
+                   const std::string& type,
+                   const std::list<octave_value_list>& idx,
+                   const octave_value& value,
+                   context_id context = xdefault_context)
       {
-        octave_value& val = varref (context);
-
-        if (! val.is_defined ())
-          mark_forced ();
+        varref(context).assign (op, type, idx, value);
+      }
+
+      void assign (octave_value::assign_op op, const octave_value& value,
+                   context_id context = xdefault_context)
+      {
+        varref(context).assign (op, value);
+      }
+
+      void do_non_const_unary_op (octave_value::unary_op op,
+                                  context_id context = xdefault_context)
+      {
+        varref(context).do_non_const_unary_op (op);
       }
 
-      octave_value& varref (context_id context)
+      void do_non_const_unary_op (octave_value::unary_op op,
+                                  const std::string& type,
+                                  const std::list<octave_value_list>& idx,
+                                  context_id context = xdefault_context)
       {
+        varref(context).do_non_const_unary_op (op, type, idx);
+      }
+
+      octave_value& varref (context_id context = xdefault_context)
+      {
+        // We duplicate global_varref and persistent_varref here to
+        // avoid calling deprecated functions.
+
         if (is_global ())
-          return symbol_table::global_varref (name);
+          {
+            symbol_table::global_table_iterator p
+              = symbol_table::global_table.find (name);
+
+            return (p == symbol_table::global_table.end ())
+              ? symbol_table::global_table[name] : p->second;
+          }
         else if (is_persistent ())
-          return symbol_table::persistent_varref (name);
+          {
+            static octave_value foobar;
+
+            symbol_table *inst
+              = symbol_table::get_instance (symbol_table::current_scope ());
+
+            return inst ? inst->do_persistent_varref (name) : foobar;
+          }
         else
           {
+            if (context == xdefault_context)
+              context = active_context ();
+
             context_id n = value_stack.size ();
             while (n++ <= context)
               value_stack.push_back (octave_value ());
@@ -237,7 +286,7 @@
           }
       }
 
-      octave_value varval (context_id context) const
+      octave_value varval (context_id context = xdefault_context) const
       {
         if (is_global ())
           return symbol_table::global_varval (name);
@@ -245,6 +294,9 @@
           return symbol_table::persistent_varval (name);
         else
           {
+            if (context == xdefault_context)
+              context = active_context ();
+
             if (context < value_stack.size ())
               return value_stack[context];
             else
@@ -252,9 +304,10 @@
           }
       }
 
-      void push_context (void)
+      void push_context (scope_id s)
       {
-        if (! (is_persistent () || is_global ()))
+        if (! (is_persistent () || is_global ())
+            && s == scope ())
           value_stack.push_back (octave_value ());
       }
 
@@ -272,11 +325,12 @@
       //
       // Here, X should only exist in the final stack frame.
 
-      size_t pop_context (void)
+      size_t pop_context (scope_id s)
       {
         size_t retval = 1;
 
-        if (! (is_persistent () || is_global ()))
+        if (! (is_persistent () || is_global ())
+            && s == scope ())
           {
             value_stack.pop_back ();
             retval = value_stack.size ();
@@ -285,33 +339,46 @@
         return retval;
       }
 
-      void clear (void)
+      void clear (void) { clear (scope ()); }
+
+      void clear (scope_id s)
       {
-        if (! (is_hidden () || is_inherited ()))
+        if (! (is_hidden () || is_inherited ())
+            && s == scope ())
           {
             if (is_global ())
               unmark_global ();
 
             if (is_persistent ())
               {
-                symbol_table::persistent_varref (name)
-                  = varval (xcurrent_context);
+                symbol_table::persistent_assign (name, varval ());
 
                 unmark_persistent ();
               }
 
-            varref (xcurrent_context) = octave_value ();
+            assign (octave_value ());
           }
       }
 
-      bool is_defined (context_id context) const
+      bool is_defined (context_id context = xdefault_context) const
       {
+        if (context == xdefault_context)
+          context = active_context ();
+
         return varval (context).is_defined ();
       }
 
+      bool is_valid (void) const
+      {
+        return valid;
+      }
+
       bool is_variable (context_id context) const
       {
-        return (! is_local () || is_defined (context) || is_forced ());
+        if (context == xdefault_context)
+          context = active_context ();
+
+        return (! is_local () || is_defined (context));
       }
 
       bool is_local (void) const { return storage_class & local; }
@@ -321,7 +388,7 @@
       bool is_inherited (void) const { return storage_class & inherited; }
       bool is_global (void) const { return storage_class & global; }
       bool is_persistent (void) const { return storage_class & persistent; }
-      bool is_forced (void) const { return storage_class & forced; }
+      bool is_added_static (void) const {return storage_class & added_static; }
 
       void mark_local (void) { storage_class |= local; }
       void mark_automatic (void) { storage_class |= automatic; }
@@ -342,7 +409,7 @@
         else
           storage_class |= persistent;
       }
-      void mark_forced (void) { storage_class |= forced; }
+      void mark_added_static (void) { storage_class |= added_static; }
 
       void unmark_local (void) { storage_class &= ~local; }
       void unmark_automatic (void) { storage_class &= ~automatic; }
@@ -351,35 +418,53 @@
       void unmark_inherited (void) { storage_class &= ~inherited; }
       void unmark_global (void) { storage_class &= ~global; }
       void unmark_persistent (void) { storage_class &= ~persistent; }
-      void unmark_forced (void) { storage_class &= ~forced; }
+      void unmark_added_static (void) { storage_class &= ~added_static; }
 
       void init_persistent (void)
       {
-        if (! is_defined (xcurrent_context))
+        if (! is_defined ())
           {
             mark_persistent ();
 
-            varref (xcurrent_context) = symbol_table::persistent_varval (name);
+            assign (symbol_table::persistent_varval (name));
           }
         // FIXME -- this causes trouble with recursive calls.
         // else
         //   error ("unable to declare existing variable persistent");
       }
 
+      void invalidate (void)
+      {
+        valid = false;
+      }
+
       void erase_persistent (void)
       {
         unmark_persistent ();
         symbol_table::erase_persistent (name);
       }
 
-      symbol_record_rep *dup (void) const
+      OCTINTERP_API context_id active_context (void) const;
+
+      scope_id scope (void) const { return decl_scope; }
+
+      void set_curr_fcn (octave_user_function *fcn)
       {
-        return new symbol_record_rep (name, varval (xcurrent_context),
+        curr_fcn = fcn;
+      }
+
+      symbol_record_rep *dup (scope_id new_scope) const
+      {
+        return new symbol_record_rep (new_scope, name, varval (),
                                       storage_class);
       }
 
       void dump (std::ostream& os, const std::string& prefix) const;
 
+      scope_id decl_scope;
+
+      octave_user_function* curr_fcn;
+
       std::string name;
 
       std::deque<octave_value> value_stack;
@@ -388,6 +473,8 @@
 
       fcn_info *finfo;
 
+      bool valid;
+
       octave_refcount<size_t> count;
 
     private:
@@ -401,10 +488,11 @@
 
   public:
 
-    symbol_record (const std::string& nm = std::string (),
+    symbol_record (scope_id s = xcurrent_scope,
+                   const std::string& nm = std::string (),
                    const octave_value& v = octave_value (),
                    unsigned int sc = local)
-      : rep (new symbol_record_rep (nm, v, sc)) { }
+      : rep (new symbol_record_rep (s, nm, v, sc)) { }
 
     symbol_record (const symbol_record& sr)
       : rep (sr.rep)
@@ -432,39 +520,86 @@
         delete rep;
     }
 
-    symbol_record dup (void) const { return symbol_record (rep->dup ()); }
-
-    std::string name (void) const { return rep->name; }
-
-    octave_value find (const octave_value_list& args = octave_value_list ()) const;
-
-    void force_variable (context_id context = xcurrent_context)
+    symbol_record dup (scope_id new_scope) const
+    {
+      return symbol_record (rep->dup (new_scope));
+    }
+
+    const std::string& name (void) const { return rep->name; }
+
+    void rename (const std::string& new_name) { rep->name = new_name; }
+
+    octave_value
+    find (const octave_value_list& args = octave_value_list ()) const;
+
+    void assign (const octave_value& value,
+                 context_id context = xdefault_context)
+    {
+      rep->assign (value, context);
+    }
+
+    void assign (octave_value::assign_op op,
+                 const std::string& type,
+                 const std::list<octave_value_list>& idx,
+                 const octave_value& value,
+                 context_id context = xdefault_context)
     {
-      rep->force_variable (context);
+      rep->assign (op, type, idx, value, context);
+    }
+
+    void assign (octave_value::assign_op op, const octave_value& value,
+                 context_id context = xdefault_context)
+    {
+      rep->assign (op, value, context);
     }
 
-    octave_value& varref (context_id context = xcurrent_context)
+    void do_non_const_unary_op (octave_value::unary_op op)
+    {
+      rep->do_non_const_unary_op (op);
+    }
+
+    void do_non_const_unary_op (octave_value::unary_op op,
+                                const std::string& type,
+                                const std::list<octave_value_list>& idx)
+    {
+      rep->do_non_const_unary_op (op, type, idx);
+    }
+
+    // Delete when deprecated varref functions are removed.
+    octave_value& varref (context_id context = xdefault_context)
     {
       return rep->varref (context);
     }
 
-    octave_value varval (context_id context = xcurrent_context) const
+    octave_value varval (context_id context = xdefault_context) const
     {
       return rep->varval (context);
     }
 
-    void push_context (void) { rep->push_context (); }
-
-    size_t pop_context (void) { return rep->pop_context (); }
+    void push_context (scope_id s) { rep->push_context (s); }
+
+    size_t pop_context (scope_id s) { return rep->pop_context (s); }
 
     void clear (void) { rep->clear (); }
 
-    bool is_defined (context_id context = xcurrent_context) const
+    void clear (scope_id s) { rep->clear (s); }
+
+    bool is_defined (context_id context = xdefault_context) const
     {
       return rep->is_defined (context);
     }
 
-    bool is_variable (context_id context = xcurrent_context) const
+    bool is_undefined (context_id context = xdefault_context) const
+    {
+      return ! rep->is_defined (context);
+    }
+
+    bool is_valid (void) const
+    {
+      return rep->is_valid ();
+    }
+
+    bool is_variable (context_id context = xdefault_context) const
     {
       return rep->is_variable (context);
     }
@@ -476,7 +611,7 @@
     bool is_hidden (void) const { return rep->is_hidden (); }
     bool is_inherited (void) const { return rep->is_inherited (); }
     bool is_persistent (void) const { return rep->is_persistent (); }
-    bool is_forced (void) const { return rep->is_forced (); }
+    bool is_added_static (void) const { return rep->is_added_static (); }
 
     void mark_local (void) { rep->mark_local (); }
     void mark_automatic (void) { rep->mark_automatic (); }
@@ -485,7 +620,7 @@
     void mark_inherited (void) { rep->mark_inherited (); }
     void mark_global (void) { rep->mark_global (); }
     void mark_persistent (void) { rep->mark_persistent (); }
-    void mark_forced (void) { rep->mark_forced (); }
+    void mark_added_static (void) { rep->mark_added_static (); }
 
     void unmark_local (void) { rep->unmark_local (); }
     void unmark_automatic (void) { rep->unmark_automatic (); }
@@ -494,14 +629,22 @@
     void unmark_inherited (void) { rep->unmark_inherited (); }
     void unmark_global (void) { rep->unmark_global (); }
     void unmark_persistent (void) { rep->unmark_persistent (); }
-    void unmark_forced (void) { rep->unmark_forced (); }
+    void unmark_added_static (void) { rep->unmark_added_static (); }
 
     void init_persistent (void) { rep->init_persistent (); }
 
     void erase_persistent (void) { rep->erase_persistent (); }
 
+    void invalidate (void) { rep->invalidate (); }
+
+    context_id active_context (void) const { return rep->active_context (); }
+
+    scope_id scope (void) const { return rep->scope (); }
+
     unsigned int xstorage_class (void) const { return rep->storage_class; }
 
+    void set_curr_fcn (octave_user_function *fcn) { rep->set_curr_fcn (fcn); }
+
     void
     dump (std::ostream& os, const std::string& prefix = std::string ()) const
     {
@@ -515,6 +658,78 @@
     symbol_record (symbol_record_rep *new_rep) : rep (new_rep) { }
   };
 
+  // Always access a symbol from the current scope.
+  // Useful for scripts, as they may be executed in more than one scope.
+  class
+  symbol_reference
+  {
+  public:
+
+    symbol_reference (void) : scope (-1) { }
+
+    symbol_reference (const symbol_record& record,
+                      scope_id curr_scope = symbol_table::current_scope ())
+      : scope (curr_scope), sym (record)
+    { }
+
+    symbol_reference (const symbol_reference& ref)
+      : scope (ref.scope), sym (ref.sym)
+    { }
+
+    symbol_reference& operator = (const symbol_reference& ref)
+    {
+      if (this != &ref)
+        {
+          scope = ref.scope;
+          sym = ref.sym;
+        }
+      return *this;
+    }
+
+    bool is_black_hole (void) const { return scope < 0; }
+
+    // The name is the same regardless of scope.
+    const std::string& name (void) const { return sym.name (); }
+
+    symbol_record *operator-> (void)
+    {
+      update ();
+      return &sym;
+    }
+
+    symbol_record *operator-> (void) const
+    {
+      update ();
+      return &sym;
+    }
+
+    // can be used to place symbol_reference in maps, we don't overload < as
+    // it doesn't make any sense for symbol_reference
+    struct comparator
+    {
+      bool operator ()(const symbol_reference& lhs,
+                       const symbol_reference& rhs) const
+      {
+        return lhs.name () < rhs.name ();
+      }
+    };
+  private:
+
+    void update (void) const
+    {
+      scope_id curr_scope = symbol_table::current_scope ();
+
+      if (scope != curr_scope || ! sym.is_valid ())
+        {
+          scope = curr_scope;
+          sym = symbol_table::insert (sym.name ());
+        }
+    }
+
+    mutable scope_id scope;
+    mutable symbol_record sym;
+  };
+
   class
   fcn_info
   {
@@ -642,20 +857,14 @@
           }
       }
 
-      void clear_cmdline_function (void)
-      {
-        if (! cmdline_function.islocked ())
-          cmdline_function = octave_value ();
-      }
-
       void clear_autoload_function (void)
       {
         if (! autoload_function.islocked ())
           autoload_function = octave_value ();
       }
 
-      // FIXME -- should this also clear the cmdline and other "user
-      // defined" functions?
+      // We also clear command line functions here, as these are both
+      // "user defined"
       void clear_user_function (void)
       {
         if (! function_on_path.islocked ())
@@ -664,6 +873,9 @@
 
             function_on_path = octave_value ();
           }
+
+        if (! cmdline_function.islocked ())
+          cmdline_function = octave_value ();
       }
 
       void clear_mex_function (void)
@@ -678,7 +890,6 @@
         clear_unlocked (private_functions);
         clear_unlocked (class_constructors);
         clear_unlocked (class_methods);
-        clear_cmdline_function ();
         clear_autoload_function ();
         clear_user_function ();
       }
@@ -928,7 +1139,7 @@
 
         if (p == all_instances.end ())
           {
-            symbol_table *inst = new symbol_table ();
+            symbol_table *inst = new symbol_table (scope);
 
             if (inst)
               all_instances[scope] = instance = inst;
@@ -1009,7 +1220,7 @@
       {
         scope_id new_scope = alloc_scope ();
 
-        symbol_table *new_symbol_table = new symbol_table ();
+        symbol_table *new_symbol_table = new symbol_table (scope);
 
         if (new_symbol_table)
           {
@@ -1034,7 +1245,8 @@
   {
     symbol_table *inst = get_instance (scope);
 
-    return inst ? inst->do_find_symbol (name) : symbol_record ();
+    return inst ? inst->do_find_symbol (name) :
+      symbol_record (scope);
   }
 
   static void
@@ -1063,47 +1275,102 @@
   static octave_value builtin_find (const std::string& name);
 
   // Insert a new name in the table.
-  static symbol_record& insert (const std::string& name)
+  static symbol_record& insert (const std::string& name,
+                                scope_id scope = xcurrent_scope)
   {
     static symbol_record foobar;
 
-    symbol_table *inst = get_instance (xcurrent_scope);
+    symbol_table *inst = get_instance (scope);
 
     return inst ? inst->do_insert (name) : foobar;
   }
 
-  static void force_variable (const std::string& name,
-                              scope_id scope = xcurrent_scope,
-                              context_id context = xcurrent_context)
+  static void rename (const std::string& old_name,
+                      const std::string& new_name,
+                      scope_id scope = xcurrent_scope)
   {
     symbol_table *inst = get_instance (scope);
 
     if (inst)
-      inst->do_force_variable (name, context);
+      inst->do_rename (old_name, new_name);
   }
 
-  static octave_value& varref (const std::string& name,
-                               scope_id scope = xcurrent_scope,
-                               context_id context = xcurrent_context)
+  static void assign (const std::string& name,
+                      const octave_value& value = octave_value (),
+                      scope_id scope = xcurrent_scope,
+                      context_id context = xdefault_context,
+                      bool force_add = false)
+  {
+    static octave_value foobar;
+
+    symbol_table *inst = get_instance (scope);
+
+    if (inst)
+      inst->do_assign (name, value, context, force_add);
+  }
+
+  // Use assign (name, value, scope, context, force_add) instead.
+  static octave_value&
+  varref (const std::string& name, scope_id scope = xcurrent_scope,
+          context_id context = xdefault_context, bool force_add = false)
+          GCC_ATTR_DEPRECATED
   {
     static octave_value foobar;
 
     symbol_table *inst = get_instance (scope);
 
-    return inst ? inst->do_varref (name, context) : foobar;
+    return inst ? inst->do_varref (name, context, force_add) : foobar;
+  }
+
+  // Convenience function to simplify
+  // octave_user_function::bind_automatic_vars
+
+  static void force_assign (const std::string& name,
+                            const octave_value& value = octave_value (),
+                            scope_id scope = xcurrent_scope,
+                            context_id context = xdefault_context)
+  {
+    assign (name, value, scope, context, true);
+  }
+
+  // Use force_assign (name, value, scope, context) instead.
+  static octave_value&
+  force_varref (const std::string& name, scope_id scope = xcurrent_scope,
+                context_id context = xdefault_context) GCC_ATTR_DEPRECATED
+  {
+    static octave_value foobar;
+
+    symbol_table *inst = get_instance (scope);
+
+    return inst ? inst->do_varref (name, context, true) : foobar;
   }
 
   static octave_value varval (const std::string& name,
                               scope_id scope = xcurrent_scope,
-                              context_id context = xcurrent_context)
+                              context_id context = xdefault_context)
   {
     symbol_table *inst = get_instance (scope);
 
     return inst ? inst->do_varval (name, context) : octave_value ();
   }
 
+  static void
+  global_assign (const std::string& name,
+                 const octave_value& value = octave_value ())
+
+  {
+    global_table_iterator p = global_table.find (name);
+
+    if (p == global_table.end ())
+      global_table[name] = value;
+    else
+      p->second = value;
+  }
+
+  // Use global_assign (name, value) instead.
   static octave_value&
-  global_varref (const std::string& name)
+  global_varref (const std::string& name) GCC_ATTR_DEPRECATED
+
   {
     global_table_iterator p = global_table.find (name);
 
@@ -1118,10 +1385,22 @@
     return (p != global_table.end ()) ? p->second : octave_value ();
   }
 
+  static void
+  top_level_assign (const std::string& name,
+                    const octave_value& value = octave_value ())
+  {
+    assign (name, value, top_scope (), 0);
+  }
+
+  // Use top_level_assign (name, value) instead.
   static octave_value&
-  top_level_varref (const std::string& name)
+  top_level_varref (const std::string& name) GCC_ATTR_DEPRECATED
   {
-    return varref (name, top_scope (), 0);
+    static octave_value foobar;
+
+    symbol_table *inst = get_instance (top_scope ());
+
+    return inst ? inst->do_varref (name, 0, true) : foobar;
   }
 
   static octave_value
@@ -1130,7 +1409,19 @@
     return varval (name, top_scope (), 0);
   }
 
+  static void
+  persistent_assign (const std::string& name,
+                     const octave_value& value = octave_value ())
+  {
+    symbol_table *inst = get_instance (xcurrent_scope);
+
+    if (inst)
+      inst->do_persistent_assign (name, value);
+  }
+
+  // Use persistent_assign (name, value) instead.
   static octave_value& persistent_varref (const std::string& name)
+  GCC_ATTR_DEPRECATED
   {
     static octave_value foobar;
 
@@ -1263,6 +1554,17 @@
       }
   }
 
+  static void install_nestfunction (const std::string& name,
+                                    const octave_value& fcn,
+                                    scope_id parent_scope);
+
+  static void update_nest (scope_id scope)
+  {
+    symbol_table *inst = get_instance (scope);
+    if (inst)
+      inst->do_update_nest ();
+  }
+
   static void install_user_function (const std::string& name,
                                      const octave_value& fcn)
   {
@@ -1341,14 +1643,6 @@
       inst->do_clear_objects ();
   }
 
-  static void unmark_forced_variables (scope_id scope = xcurrent_scope)
-  {
-    symbol_table *inst = get_instance (scope);
-
-    if (inst)
-      inst->do_unmark_forced_variables ();
-  }
-
   static void clear_functions (void)
   {
     for (fcn_table_iterator p = fcn_table.begin (); p != fcn_table.end (); p++)
@@ -1618,15 +1912,18 @@
       inst->do_mark_global (name);
   }
 
+  // exclude: Storage classes to exclude, you can OR them together
   static std::list<symbol_record>
   all_variables (scope_id scope = xcurrent_scope,
-                 context_id context = xcurrent_context,
-                 bool defined_only = true)
+                 context_id context = xdefault_context,
+                 bool defined_only = true,
+                 unsigned int exclude = symbol_record::hidden)
   {
     symbol_table *inst = get_instance (scope);
 
     return inst
-      ? inst->do_all_variables (context, defined_only) : std::list<symbol_record> ();
+      ? inst->do_all_variables (context, defined_only, exclude)
+      : std::list<symbol_record> ();
   }
 
   static std::list<symbol_record> glob (const std::string& pattern)
@@ -1672,7 +1969,8 @@
         // may be handled the same way.
 
         if (pat.match (p->first))
-          retval.push_back (symbol_record (p->first, p->second,
+          retval.push_back (symbol_record (xglobal_scope, 
+                                           p->first, p->second,
                                            symbol_record::global));
       }
 
@@ -1694,7 +1992,8 @@
         // may be handled the same way.
 
         if (pat.is_match (p->first))
-          retval.push_back (symbol_record (p->first, p->second,
+          retval.push_back (symbol_record (xglobal_scope,
+                                           p->first, p->second,
                                            symbol_record::global));
       }
 
@@ -1840,6 +2139,14 @@
       }
   }
 
+  static std::list<workspace_element> workspace_info (void)
+  {
+    symbol_table *inst = get_instance (xcurrent_scope);
+
+    return inst
+      ? inst->do_workspace_info () : std::list<workspace_element> ();
+  }
+
   static void dump (std::ostream& os, scope_id scope = xcurrent_scope);
 
   static void dump_global (std::ostream& os);
@@ -1868,6 +2175,26 @@
       p->second.unlock_subfunction (scope);
   }
 
+  static std::map<std::string, octave_value>
+  subfunctions_defined_in_scope (scope_id scope = xcurrent_scope)
+  {
+    std::map<std::string, octave_value> retval;
+
+    for (fcn_table_const_iterator p = fcn_table.begin ();
+         p != fcn_table.end (); p++)
+      {
+        std::pair<std::string, octave_value> tmp
+          = p->second.subfunction_defined_in_scope (scope);
+
+        std::string nm = tmp.first;
+
+        if (! nm.empty ())
+          retval[nm] = tmp.second;
+      }
+
+    return retval;
+  }
+
   static void free_scope (scope_id scope)
   {
     if (scope == xglobal_scope || scope == xtop_scope)
@@ -1924,7 +2251,8 @@
       symbol_table *inst = get_instance (scope);
       // FIXME: normally, functions should not usurp each other's scope.
       // If for any incredible reason this is needed, call
-      // set_user_function (0, scope) first.
+      // set_user_function (0, scope) first. This may cause problems with
+      // nested functions, as the curr_fcn of symbol_records must be updated.
       assert (inst->curr_fcn == 0 || curr_fcn == 0);
       inst->curr_fcn = curr_fcn;
     }
@@ -1953,6 +2281,9 @@
 
   typedef std::map<std::string, fcn_info>::const_iterator fcn_table_const_iterator;
   typedef std::map<std::string, fcn_info>::iterator fcn_table_iterator;
+  
+  // The scope of this symbol table.
+  scope_id my_scope;
 
   // Name for this table (usually the file name of the function
   // corresponding to the scope);
@@ -1961,9 +2292,18 @@
   // Map from symbol names to symbol info.
   std::map<std::string, symbol_record> table;
 
+  // Child nested functions.
+  std::vector<symbol_table*> nest_children;
+
+  // Parent nested function (may be null).
+  symbol_table *nest_parent;
+
   // The associated user code (may be null).
   octave_user_function *curr_fcn;
 
+  // If true then no variables can be added.
+  bool static_workspace;
+
   // Map from names of global variables to values.
   static std::map<std::string, octave_value> global_table;
 
@@ -2000,8 +2340,11 @@
 
   static context_id xcurrent_context;
 
-  symbol_table (void)
-    : table_name (), table (), curr_fcn (0), persistent_table () { }
+  static const context_id xdefault_context = static_cast<context_id> (-1);
+
+  symbol_table (scope_id scope)
+    : my_scope (scope), table_name (), table (), nest_children (), nest_parent (0),
+    curr_fcn (0), static_workspace (false), persistent_table () { }
 
   ~symbol_table (void) { }
 
@@ -2017,7 +2360,7 @@
           {
             if (! instance && create)
               {
-                symbol_table *inst = new symbol_table ();
+                symbol_table *inst = new symbol_table (scope);
 
                 if (inst)
                   {
@@ -2041,7 +2384,7 @@
               {
                 if (create)
                   {
-                    retval = new symbol_table ();
+                    retval = new symbol_table (scope);
 
                     if (retval)
                       all_instances[scope] = retval;
@@ -2063,6 +2406,13 @@
     return retval;
   }
 
+  void add_nest_child (symbol_table& st)
+  {
+    assert (!st.nest_parent);
+    nest_children.push_back (&st);
+    st.nest_parent = this;
+  }
+
   void insert_symbol_record (const symbol_record& sr)
   {
     table[sr.name ()] = sr;
@@ -2072,7 +2422,7 @@
   do_dup_scope (symbol_table& new_symbol_table) const
   {
     for (table_const_iterator p = table.begin (); p != table.end (); p++)
-      new_symbol_table.insert_symbol_record (p->second.dup ());
+      new_symbol_table.insert_symbol_record (p->second.dup (new_symbol_table.my_scope));
   }
 
   symbol_record do_find_symbol (const std::string& name)
@@ -2101,7 +2451,7 @@
 
                 if (val.is_defined ())
                   {
-                    sr.varref (0) = val;
+                    sr.assign (val, 0);
 
                     sr.mark_inherited ();
                   }
@@ -2122,35 +2472,69 @@
 
   octave_value do_builtin_find (const std::string& name);
 
-  symbol_record& do_insert (const std::string& name)
-  {
-    table_iterator p = table.find (name);
-
-    return p == table.end ()
-      ? (table[name] = symbol_record (name)) : p->second;
-  }
-
-  void do_force_variable (const std::string& name, context_id context)
+  symbol_record& do_insert (const std::string& name, bool force_add = false)
   {
     table_iterator p = table.find (name);
 
     if (p == table.end ())
       {
-        symbol_record& sr = do_insert (name);
-
-        sr.force_variable (context);
+        symbol_record ret (my_scope, name);
+
+        if (nest_parent && nest_parent->look_nonlocal (name, ret))
+          return table[name] = ret;
+        else
+          {
+            if (static_workspace && ! force_add)
+              ret.mark_added_static ();
+
+            return table[name] = ret;
+          }
       }
     else
-      p->second.force_variable (context);
+      return p->second;
   }
 
-  octave_value& do_varref (const std::string& name, context_id context)
+  void do_rename (const std::string& old_name, const std::string& new_name)
+  {
+    table_iterator p = table.find (old_name);
+
+    if (p != table.end ())
+      {
+        symbol_record sr = p->second;
+
+        sr.rename (new_name);
+
+        table.erase (p);
+
+        table[new_name] = sr;
+      }
+  }
+
+  void do_assign (const std::string& name, const octave_value& value,
+                  context_id context, bool force_add)
   {
     table_iterator p = table.find (name);
 
     if (p == table.end ())
       {
-        symbol_record& sr = do_insert (name);
+        symbol_record& sr = do_insert (name, force_add);
+
+        sr.assign (value, context);
+      }
+    else
+      p->second.assign (value, context);
+  }
+
+  // Use do_assign (name, value, context, force_add) instead.
+  // Delete when deprecated varref functions are removed.
+  octave_value& do_varref (const std::string& name, context_id context,
+                           bool force_add)
+  {
+    table_iterator p = table.find (name);
+
+    if (p == table.end ())
+      {
+        symbol_record& sr = do_insert (name, force_add);
 
         return sr.varref (context);
       }
@@ -2165,6 +2549,19 @@
     return (p != table.end ()) ? p->second.varval (context) : octave_value ();
   }
 
+  void do_persistent_assign (const std::string& name,
+                             const octave_value& value)
+  {
+    persistent_table_iterator p = persistent_table.find (name);
+
+    if (p == persistent_table.end ())
+      persistent_table[name] = value;
+    else
+      p->second = value;
+  }
+
+  // Use do_persistent_assign (name, value) instead.
+  // Delete when deprecated varref functions are removed.
   octave_value& do_persistent_varref (const std::string& name)
   {
     persistent_table_iterator p = persistent_table.find (name);
@@ -2207,15 +2604,15 @@
   void do_push_context (void)
   {
     for (table_iterator p = table.begin (); p != table.end (); p++)
-      p->second.push_context ();
+      p->second.push_context (my_scope);
   }
 
   void do_pop_context (void)
   {
     for (table_iterator p = table.begin (); p != table.end (); )
       {
-        if (p->second.pop_context () == 0)
-          table.erase (p++);
+        if (p->second.pop_context (my_scope) == 0)
+            table.erase (p++);
         else
           p++;
       }
@@ -2224,7 +2621,7 @@
   void do_clear_variables (void)
   {
     for (table_iterator p = table.begin (); p != table.end (); p++)
-      p->second.clear ();
+      p->second.clear (my_scope);
   }
 
   void do_clear_objects (void)
@@ -2232,18 +2629,12 @@
     for (table_iterator p = table.begin (); p != table.end (); p++)
       {
         symbol_record& sr = p->second;
-        octave_value& val = sr.varref ();
-        if (val.is_object())
-          p->second.clear ();
+        octave_value val = sr.varval ();
+        if (val.is_object ())
+          p->second.clear (my_scope);
       }
   }
 
- void do_unmark_forced_variables (void)
-  {
-    for (table_iterator p = table.begin (); p != table.end (); p++)
-      p->second.unmark_forced ();
-  }
-
   void do_clear_global (const std::string& name)
   {
     table_iterator p = table.find (name);
@@ -2268,7 +2659,7 @@
     table_iterator p = table.find (name);
 
     if (p != table.end ())
-      p->second.clear ();
+      p->second.clear (my_scope);
   }
 
   void do_clear_global_pattern (const std::string& pat)
@@ -2308,7 +2699,7 @@
         if (sr.is_defined () || sr.is_global ())
           {
             if (pattern.match (sr.name ()))
-              sr.clear ();
+              sr.clear (my_scope);
           }
       }
   }
@@ -2324,7 +2715,7 @@
         if (sr.is_defined () || sr.is_global ())
           {
             if (pattern.is_match (sr.name ()))
-              sr.clear ();
+              sr.clear (my_scope);
           }
       }
   }
@@ -2345,7 +2736,8 @@
   }
 
   std::list<symbol_record>
-  do_all_variables (context_id context, bool defined_only) const
+  do_all_variables (context_id context, bool defined_only,
+                    unsigned int exclude) const
   {
     std::list<symbol_record> retval;
 
@@ -2353,7 +2745,8 @@
       {
         const symbol_record& sr = p->second;
 
-        if (defined_only && ! sr.is_defined (context))
+        if ((defined_only && ! sr.is_defined (context))
+            || (sr.xstorage_class () & exclude))
           continue;
 
         retval.push_back (sr);
@@ -2423,26 +2816,6 @@
     return retval;
   }
 
-  static std::map<std::string, octave_value>
-  subfunctions_defined_in_scope (scope_id scope = xcurrent_scope)
-  {
-    std::map<std::string, octave_value> retval;
-
-    for (fcn_table_const_iterator p = fcn_table.begin ();
-         p != fcn_table.end (); p++)
-      {
-        std::pair<std::string, octave_value> tmp
-          = p->second.subfunction_defined_in_scope (scope);
-
-        std::string nm = tmp.first;
-
-        if (! nm.empty ())
-          retval[nm] = tmp.second;
-      }
-
-    return retval;
-  }
-
   bool do_is_local_variable (const std::string& name) const
   {
     table_const_iterator p = table.find (name);
@@ -2459,9 +2832,30 @@
     return p != table.end () && p->second.is_global ();
   }
 
+  std::list<workspace_element> do_workspace_info (void) const;
+
   void do_dump (std::ostream& os);
 
   void do_cache_name (const std::string& name) { table_name = name; }
+
+  void do_update_nest (void);
+
+  bool look_nonlocal (const std::string& name, symbol_record& result)
+  {
+    table_iterator p = table.find (name);
+    if (p == table.end ())
+      {
+        if (nest_parent)
+          return nest_parent->look_nonlocal (name, result);
+      }
+    else if (! p->second.is_automatic ())
+      {
+        result = p->second;
+        return true;
+      }
+
+    return false;
+  }
 };
 
 extern bool out_of_date_check (octave_value& function,
rename from src/sysdep.cc
rename to libinterp/interpfcn/sysdep.cc
--- a/src/sysdep.cc
+++ b/libinterp/interpfcn/sysdep.cc
@@ -69,6 +69,7 @@
 #include "quit.h"
 
 #include "Cell.h"
+#include "builtins.h"
 #include "defun.h"
 #include "error.h"
 #include "input.h"
@@ -124,21 +125,21 @@
       mod_info.dwSize = sizeof (mod_info);
 
       if (Module32First (h, &mod_info))
-	{
-	  do
-	    {
-	      std::string mod_name (mod_info.szModule);
+        {
+          do
+            {
+              std::string mod_name (mod_info.szModule);
 
-	      if (mod_name.find ("octinterp") != std::string::npos)
-		{
-		  bin_dir = mod_info.szExePath;
-		  if (bin_dir[bin_dir.length () - 1] != '\\')
-		    bin_dir.append (1, '\\');
-		  break;
-		}
-	    }
-	  while (Module32Next (h, &mod_info));
-	}
+              if (mod_name.find ("octinterp") != std::string::npos)
+                {
+                  bin_dir = mod_info.szExePath;
+                  if (bin_dir[bin_dir.length () - 1] != '\\')
+                    bin_dir.append (1, '\\');
+                  break;
+                }
+            }
+          while (Module32Next (h, &mod_info));
+       }
 
       CloseHandle (h);
     }
@@ -166,8 +167,6 @@
 MINGW_signal_cleanup (void)
 {
   w32_set_quiet_shutdown ();
-
-  w32_raise_final ();
 }
 #endif
 
@@ -176,11 +175,6 @@
 MINGW_init (void)
 {
   w32_set_octave_home ();
-
-  // Init mutex to protect setjmp/longjmp and get main thread context
-  w32_sigint_init ();
-
-  w32_set_quiet_shutdown ();
 }
 #endif
 
@@ -189,11 +183,6 @@
 MSVC_init (void)
 {
   w32_set_octave_home ();
-
-  // Init mutex to protect setjmp/longjmp and get main thread context
-  w32_sigint_init ();
-
-  w32_set_quiet_shutdown ();
 }
 #endif
 
@@ -207,16 +196,26 @@
 
   bool retval = false;
 
+  const char *f1 = file1.c_str ();
+  const char *f2 = file2.c_str ();
+
+  bool f1_is_dir = GetFileAttributes (f1) & FILE_ATTRIBUTE_DIRECTORY;
+  bool f2_is_dir = GetFileAttributes (f2) & FILE_ATTRIBUTE_DIRECTORY;
+
   // Windows native code
   // Reference: http://msdn2.microsoft.com/en-us/library/aa363788.aspx
 
-  HANDLE hfile1 = CreateFile (file1.c_str (), 0, FILE_SHARE_READ, 0,
-                              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
+  DWORD share = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;
+
+  HANDLE hfile1
+    = CreateFile (f1, 0, share, 0, OPEN_EXISTING,
+                  f1_is_dir ? FILE_FLAG_BACKUP_SEMANTICS : 0, 0);
 
   if (hfile1 != INVALID_HANDLE_VALUE)
     {
-      HANDLE hfile2 = CreateFile (file2.c_str (), 0, FILE_SHARE_READ, 0,
-                                  OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
+      HANDLE hfile2
+        = CreateFile (f2, 0, share, 0, OPEN_EXISTING,
+                      f2_is_dir ? FILE_FLAG_BACKUP_SEMANTICS : 0, 0);
 
       if (hfile2 != INVALID_HANDLE_VALUE)
         {
@@ -225,10 +224,11 @@
 
           if (GetFileInformationByHandle (hfile1, &hfi1)
               && GetFileInformationByHandle (hfile2, &hfi2))
-
-            retval = (hfi1.dwVolumeSerialNumber == hfi2.dwVolumeSerialNumber
-                      && hfi1.nFileIndexHigh == hfi2.nFileIndexHigh
-                      && hfi1.nFileIndexLow == hfi2.nFileIndexLow);
+            {
+              retval = (hfi1.dwVolumeSerialNumber == hfi2.dwVolumeSerialNumber
+                        && hfi1.nFileIndexHigh == hfi2.nFileIndexHigh
+                        && hfi1.nFileIndexLow == hfi2.nFileIndexLow);
+            }
 
           CloseHandle (hfile2);
         }
@@ -255,7 +255,7 @@
 void
 sysdep_init (void)
 {
-#if defined (__386BSD__) || defined (__FreeBSD__) || defined(__NetBSD__)
+#if defined (__386BSD__) || defined (__FreeBSD__) || defined (__NetBSD__)
   BSD_init ();
 #elif defined (__MINGW32__)
   MINGW_init ();
@@ -534,7 +534,9 @@
 Clear the terminal screen and move the cursor to the upper left corner.\n\
 @end deftypefn")
 {
-  command_editor::clear_screen ();
+  bool skip_redisplay = true;
+
+  command_editor::clear_screen (skip_redisplay);
 
   return octave_value_list ();
 }
@@ -608,7 +610,7 @@
 DEFALIAS (setenv, putenv);
 
 /*
-%!assert (ischar (getenv ("OCTAVE_HOME")));
+%!assert (ischar (getenv ("OCTAVE_HOME")))
 %!test
 %! setenv ("dummy_variable_that_cannot_matter", "foobar");
 %! assert (getenv ("dummy_variable_that_cannot_matter"), "foobar");
@@ -618,8 +620,9 @@
 
 DEFUN (kbhit, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {} kbhit ()\n\
-Read a single keystroke from the keyboard.  If called with one\n\
+@deftypefn  {Built-in Function} {} kbhit ()\n\
+@deftypefnx {Built-in Function} {} kbhit (1)\n\
+Read a single keystroke from the keyboard.  If called with an\n\
 argument, don't wait for a keypress.  For example,\n\
 \n\
 @example\n\
@@ -635,8 +638,9 @@
 @end example\n\
 \n\
 @noindent\n\
-identical to the above example, but don't wait for a keypress,\n\
+is identical to the above example, but doesn't wait for a keypress,\n\
 returning the empty string if no key is available.\n\
+@seealso{input}\n\
 @end deftypefn")
 {
   octave_value retval;
@@ -645,16 +649,15 @@
 
   if (interactive || forced_interactive)
     {
-      feval ("drawnow");
+      Fdrawnow ();
 
       int c = octave_kbhit (args.length () == 0);
 
       if (c == -1)
         c = 0;
 
-      char *s = new char [2];
-      s[0] = c;
-      s[1] = '\0';
+      char s[2] = { static_cast<char> (c), '\0' };
+
       retval = s;
     }
 
@@ -697,7 +700,7 @@
         {
           if (! xisnan (dval))
             {
-              feval ("drawnow");
+              Fdrawnow ();
 
               if (xisinf (dval))
                 {
@@ -713,7 +716,7 @@
     }
   else
     {
-      feval ("drawnow");
+      Fdrawnow ();
       flush_octave_stdout ();
       octave_kbhit ();
     }
@@ -722,9 +725,10 @@
 }
 
 /*
-%!error (pause (1, 2));
 %!test
 %! pause (1);
+
+%!error (pause (1, 2))
 */
 
 DEFUN (sleep, args, ,
@@ -745,7 +749,7 @@
             warning ("sleep: NaN is an invalid delay");
           else
             {
-              feval ("drawnow");
+              Fdrawnow ();
               octave_sleep (dval);
             }
         }
@@ -757,10 +761,11 @@
 }
 
 /*
-%!error (sleep ());
-%!error (sleep (1, 2));
 %!test
 %! sleep (1);
+
+%!error (sleep ())
+%!error (sleep (1, 2))
 */
 
 DEFUN (usleep, args, ,
@@ -784,7 +789,7 @@
             warning ("usleep: NaN is an invalid delay");
           else
             {
-              feval ("drawnow");
+              Fdrawnow ();
 
               int delay = NINT (dval);
 
@@ -800,10 +805,11 @@
 }
 
 /*
-%!error (usleep ());
-%!error (usleep (1, 2));
 %!test
 %! usleep (1000);
+
+%!error (usleep ())
+%!error (usleep (1, 2))
 */
 
 // FIXME -- maybe this should only return 1 if IEEE floating
@@ -823,7 +829,7 @@
 }
 
 /*
-%!assert (islogical (isieee ()));
+%!assert (islogical (isieee ()))
 */
 
 DEFUN (native_float_format, , ,
@@ -838,7 +844,7 @@
 }
 
 /*
-%!assert (ischar (native_float_format ()));
+%!assert (ischar (native_float_format ()))
 */
 
 DEFUN (tilde_expand, args, ,
rename from src/sysdep.h
rename to libinterp/interpfcn/sysdep.h
--- a/src/sysdep.h
+++ b/libinterp/interpfcn/sysdep.h
@@ -30,9 +30,9 @@
 #include "lo-ieee.h"
 #include "lo-sysdep.h"
 
-extern void sysdep_init (void);
+extern OCTINTERP_API void sysdep_init (void);
 
-extern void sysdep_cleanup (void);
+extern OCTINTERP_API void sysdep_cleanup (void);
 
 extern OCTINTERP_API void raw_mode (bool, bool wait = true);
 
@@ -47,7 +47,6 @@
 
 #if defined (__WIN32__) && ! defined (_POSIX_VERSION)
 extern void MINGW_signal_cleanup (void);
-#define USE_W32_SIGINT 1
 #define MINGW_SIGNAL_CLEANUP() MINGW_signal_cleanup ()
 #else
 #define MINGW_SIGNAL_CLEANUP() do { } while (0)
rename from src/toplev.cc
rename to libinterp/interpfcn/toplev.cc
--- a/src/toplev.cc
+++ b/libinterp/interpfcn/toplev.cc
@@ -35,6 +35,7 @@
 #include <sstream>
 #include <string>
 
+#include <sys/select.h>
 #include <sys/types.h>
 #include <unistd.h>
 
@@ -56,7 +57,9 @@
 #include "graphics.h"
 #include "input.h"
 #include "lex.h"
+#include "octave-link.h"
 #include "oct-conf.h"
+#include "oct-conf-features.h"
 #include "oct-hist.h"
 #include "oct-map.h"
 #include "oct-obj.h"
@@ -77,6 +80,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.
@@ -94,9 +101,6 @@
 // TRUE means we've processed all the init code and we are good to go.
 bool octave_initialized = false;
 
-// Current command to execute.
-tree_statement_list *global_command = 0;
-
 octave_call_stack *octave_call_stack::instance = 0;
 
 void
@@ -115,17 +119,29 @@
 int
 octave_call_stack::do_current_line (void) const
 {
-  tree_statement *stmt = do_current_statement ();
+  int retval = -1;
 
-  return stmt ? stmt->line () : -1;
+  if (! cs.empty ())
+    {
+      const call_stack_elt& elt = cs[curr_frame];
+      retval = elt.line;
+    }
+
+  return retval;
 }
 
 int
 octave_call_stack::do_current_column (void) const
 {
-  tree_statement *stmt = do_current_statement ();
+  int retval = -1;
 
-  return stmt ? stmt->column () : -1;
+  if (! cs.empty ())
+    {
+      const call_stack_elt& elt = cs[curr_frame];
+      retval = elt.column;
+    }
+
+  return retval;
 }
 
 int
@@ -143,11 +159,9 @@
 
       if (f && f->is_user_code ())
         {
-          tree_statement *stmt = elt.stmt;
-
-          if (stmt)
+          if (elt.line > 0)
             {
-              retval = stmt->line ();
+              retval = elt.line;
               break;
             }
         }
@@ -171,11 +185,9 @@
 
       if (f && f->is_user_code ())
         {
-          tree_statement *stmt = elt.stmt;
-
-          if (stmt)
+          if (elt.column)
             {
-              retval = stmt->column ();
+              retval = elt.column;
               break;
             }
         }
@@ -307,18 +319,8 @@
                   else
                     name(k) = f->parent_fcn_name () + Vfilemarker + f->name ();
 
-                  tree_statement *stmt = elt.stmt;
-
-                  if (stmt)
-                    {
-                      line(k) = stmt->line ();
-                      column(k) = stmt->column ();
-                    }
-                  else
-                    {
-                      line(k) = -1;
-                      column(k) = -1;
-                    }
+                  line(k) = elt.line;
+                  column(k) = elt.column;
 
                   k++;
                 }
@@ -349,17 +351,9 @@
           octave_function *f = elt.fcn;
           std::string nm = f ? f->name () : std::string ("<unknown>");
 
-          tree_statement *s = elt.stmt;
-          int l = -1;
-          int c = -1;
-          if (s)
-            {
-              l = s->line ();
-              c = s->column ();
-            }
-
           octave_stdout << "stopped in " << nm
-                        << " at line " << l << " column " << c
+                        << " at line " << elt.line
+                        << " column " << elt.column
                         << " (" << elt.scope << "[" << elt.context << "])"
                         << std::endl;
         }
@@ -413,14 +407,8 @@
                   std::ostringstream buf;
 
                   if (f)
-                    {
-                      tree_statement *s = elt.stmt;
-
-                      int l = s ? s->line () : -1;
-
-                      buf << "stopped in " << f->name ()
-                          << " at line " << l << std::endl;
-                    }
+                    buf << "stopped in " << f->name ()
+                        << " at line " << elt.line << std::endl;
                   else
                     buf << "at top level" << std::endl;
 
@@ -506,7 +494,6 @@
       const call_stack_elt& elt = cs.back ();
 
       octave_function *fcn = elt.fcn;
-      tree_statement *stmt = elt.stmt;
 
       std::string fcn_name = "?unknown?";
 
@@ -518,11 +505,8 @@
             fcn_name = fcn->name ();
         }
 
-      int line = stmt ? stmt->line () : -1;
-      int column = stmt ? stmt->column () : -1;
-
       error ("  %s at line %d, column %d",
-             fcn_name.c_str (), line, column);
+             fcn_name.c_str (), elt.line, elt.column);
     }
 }
 
@@ -555,44 +539,38 @@
 
   // The big loop.
 
+  unwind_protect frame;
+
+  // octave_parser constructor sets this for us.
+  frame.protect_var (LEXER);
+
+  octave_lexer *lxr = ((interactive || forced_interactive)
+                       ? new octave_lexer ()
+                       : new octave_lexer (stdin));
+
+  octave_parser parser (*lxr);
+
   int retval = 0;
   do
     {
       try
         {
-          unwind_protect frame;
+          unwind_protect inner_frame;
 
           reset_error_handler ();
 
-          reset_parser ();
+          parser.reset ();
 
           if (symbol_table::at_top_level ())
             tree_evaluator::reset_debug_state ();
 
-          // Do this with an unwind-protect cleanup function so that
-          // the forced variables will be unmarked in the event of an
-          // interrupt.
-          symbol_table::scope_id scope = symbol_table::top_scope ();
-          frame.add_fcn (symbol_table::unmark_forced_variables, scope);
-
-          frame.protect_var (global_command);
-
-          global_command = 0;
-
-          // This is the same as yyparse in parse.y.
-          retval = octave_parse ();
+          retval = parser.run ();
 
           if (retval == 0)
             {
-              if (global_command)
+              if (parser.stmt_list)
                 {
-                  // Use an unwind-protect cleanup function so that the
-                  // global_command list will be deleted in the event of
-                  // an interrupt.
-
-                  frame.add_fcn (cleanup_statement_list, &global_command);
-
-                  global_command->accept (*current_evaluator);
+                  parser.stmt_list->accept (*current_evaluator);
 
                   octave_quit ();
 
@@ -628,7 +606,7 @@
                         command_editor::increment_current_command_number ();
                     }
                 }
-              else if (parser_end_of_input)
+              else if (parser.lexer.end_of_input)
                 break;
             }
         }
@@ -637,10 +615,7 @@
           recover_from_exception ();
           octave_stdout << "\n";
           if (quitting_gracefully)
-            {
-              clean_up_and_exit (exit_status);
-              break; // If user has overriden the exit func.
-            }
+            return exit_status;
         }
       catch (octave_execution_exception)
         {
@@ -653,7 +628,7 @@
         {
           recover_from_exception ();
           std::cerr
-            << "error: memory exhausted or requested size too large for range of Octave's index type -- trying to return to prompt"
+            << "error: out of memory -- trying to return to prompt"
             << std::endl;
         }
     }
@@ -664,13 +639,120 @@
 
 // Fix up things before exiting.
 
+static std::list<std::string> octave_atexit_functions;
+
+static void
+do_octave_atexit (void)
+{
+  static bool deja_vu = false;
+
+  OCTAVE_SAFE_CALL (remove_input_event_hook_functions, ());
+
+  while (! octave_atexit_functions.empty ())
+    {
+      std::string fcn = octave_atexit_functions.front ();
+
+      octave_atexit_functions.pop_front ();
+
+      OCTAVE_SAFE_CALL (reset_error_handler, ());
+
+      OCTAVE_SAFE_CALL (feval, (fcn, octave_value_list (), 0));
+
+      OCTAVE_SAFE_CALL (flush_octave_stdout, ());
+    }
+
+  if (! deja_vu)
+    {
+      deja_vu = true;
+
+      // Process pending events and disasble octave_link event
+      // processing with this call.
+
+      octave_link::process_events (true);
+
+      // Do this explicitly so that destructors for mex file objects
+      // are called, so that functions registered with mexAtExit are
+      // called.
+      OCTAVE_SAFE_CALL (clear_mex_functions, ());
+
+      OCTAVE_SAFE_CALL (command_editor::restore_terminal_state, ());
+
+      // FIXME -- is this needed?  Can it cause any trouble?
+      OCTAVE_SAFE_CALL (raw_mode, (0));
+
+      OCTAVE_SAFE_CALL (octave_history_write_timestamp, ());
+
+      if (! command_history::ignoring_entries ())
+        OCTAVE_SAFE_CALL (command_history::clean_up_and_save, ());
+
+      OCTAVE_SAFE_CALL (gh_manager::close_all_figures, ());
+
+      OCTAVE_SAFE_CALL (gtk_manager::unload_all_toolkits, ());
+
+      OCTAVE_SAFE_CALL (close_files, ());
+
+      OCTAVE_SAFE_CALL (cleanup_tmp_files, ());
+
+      OCTAVE_SAFE_CALL (symbol_table::cleanup, ());
+
+      OCTAVE_SAFE_CALL (sysdep_cleanup, ());
+
+      OCTAVE_SAFE_CALL (flush_octave_stdout, ());
+
+      if (! quitting_gracefully && (interactive || forced_interactive))
+        {
+          octave_stdout << "\n";
+
+          // Yes, we want this to be separate from the call to
+          // flush_octave_stdout above.
+
+          OCTAVE_SAFE_CALL (flush_octave_stdout, ());
+        }
+
+      // Don't call singleton_cleanup_list::cleanup until we have the
+      // problems with registering/unregistering types worked out.  For
+      // example, uncomment the following line, then use the make_int
+      // function from the examples directory to create an integer
+      // object and then exit Octave.  Octave should crash with a
+      // segfault when cleaning up the typinfo singleton.  We need some
+      // way to force new octave_value_X types that are created in
+      // .oct files to be unregistered when the .oct file shared library
+      // is unloaded.
+      //
+      // OCTAVE_SAFE_CALL (singleton_cleanup_list::cleanup, ());
+
+      OCTAVE_SAFE_CALL (octave_chunk_buffer::clear, ());
+    }
+}
+
 void
-clean_up_and_exit (int retval)
+clean_up_and_exit (int retval, bool safe_to_return)
 {
   do_octave_atexit ();
 
-  if (octave_exit)
-    (*octave_exit) (retval == EOF ? 0 : retval);
+  if (octave_link::exit (retval))
+    {
+      if (safe_to_return)
+        return;
+      else
+        {
+          // What should we do here?  We might be called from some
+          // location other than the end of octave_execute_interpreter,
+          // so it might not be safe to return.
+
+          // We have nothing else to do at this point, and the
+          // octave_link::exit function is supposed to take care of
+          // exiting for us.  Assume that job won't take more than a
+          // day...
+
+          gnulib::sleep (86400);
+        }
+    }
+  else
+    {
+      if (octave_exit)
+        (*octave_exit) (retval == EOF ? 0 : retval);
+    }
 }
 
 DEFUN (quit, args, ,
@@ -808,8 +890,8 @@
 
       int cmd_status = cmd->close ();
 
-      if (WIFEXITED (cmd_status))
-        cmd_status = WEXITSTATUS (cmd_status);
+      if (octave_wait::ifexited (cmd_status))
+        cmd_status = octave_wait::exitstatus (cmd_status);
       else
         cmd_status = 127;
 
@@ -950,7 +1032,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 ();
@@ -962,7 +1044,7 @@
               PROCESS_INFORMATION pi;
               ZeroMemory (&si, sizeof (si));
               ZeroMemory (&pi, sizeof (pi));
-              OCTAVE_LOCAL_BUFFER (char, xcmd_str, cmd_str.length()+1);
+              OCTAVE_LOCAL_BUFFER (char, xcmd_str, cmd_str.length ()+1);
               strcpy (xcmd_str, cmd_str.c_str ());
 
               if (! CreateProcess (0, xcmd_str, 0, 0, FALSE, 0, 0, 0, &si, &pi))
@@ -988,8 +1070,8 @@
               // status of the command.  Otherwise, return 127 as a
               // failure code.
 
-              if (WIFEXITED (status))
-                status = WEXITSTATUS (status);
+              if (octave_wait::ifexited (status))
+                status = octave_wait::exitstatus (status);
 
               retval(0) = status;
             }
@@ -1015,89 +1097,6 @@
 %!error system (1, 2, 3)
 */
 
-// FIXME -- this should really be static, but that causes
-// problems on some systems.
-std::list<std::string> octave_atexit_functions;
-
-void
-do_octave_atexit (void)
-{
-  static bool deja_vu = false;
-
-  while (! octave_atexit_functions.empty ())
-    {
-      std::string fcn = octave_atexit_functions.front ();
-
-      octave_atexit_functions.pop_front ();
-
-      OCTAVE_SAFE_CALL (reset_error_handler, ());
-
-      OCTAVE_SAFE_CALL (feval, (fcn, octave_value_list (), 0));
-
-      OCTAVE_SAFE_CALL (flush_octave_stdout, ());
-    }
-
-  if (! deja_vu)
-    {
-      deja_vu = true;
-
-      // Do this explicitly so that destructors for mex file objects
-      // are called, so that functions registered with mexAtExit are
-      // called.
-      OCTAVE_SAFE_CALL (clear_mex_functions, ());
-
-      OCTAVE_SAFE_CALL (command_editor::restore_terminal_state, ());
-
-      // FIXME -- is this needed?  Can it cause any trouble?
-      OCTAVE_SAFE_CALL (raw_mode, (0));
-
-      OCTAVE_SAFE_CALL (octave_history_write_timestamp, ());
-
-      if (! command_history::ignoring_entries ())
-        OCTAVE_SAFE_CALL (command_history::clean_up_and_save, ());
-
-      OCTAVE_SAFE_CALL (gh_manager::close_all_figures, ());
-
-      OCTAVE_SAFE_CALL (gtk_manager::unload_all_toolkits, ());
-
-      OCTAVE_SAFE_CALL (close_files, ());
-
-      OCTAVE_SAFE_CALL (cleanup_tmp_files, ());
-
-      OCTAVE_SAFE_CALL (symbol_table::cleanup, ());
-
-      OCTAVE_SAFE_CALL (cleanup_parser, ());
-
-      OCTAVE_SAFE_CALL (sysdep_cleanup, ());
-
-      OCTAVE_SAFE_CALL (flush_octave_stdout, ());
-
-      if (! quitting_gracefully && (interactive || forced_interactive))
-        {
-          octave_stdout << "\n";
-
-          // Yes, we want this to be separate from the call to
-          // flush_octave_stdout above.
-
-          OCTAVE_SAFE_CALL (flush_octave_stdout, ());
-        }
-
-      // Don't call singleton_cleanup_list::cleanup until we have the
-      // problems with registering/unregistering types worked out.  For
-      // example, uncomment the following line, then use the make_int
-      // function from the examples directory to create an integer
-      // object and then exit Octave.  Octave should crash with a
-      // segfault when cleaning up the typinfo singleton.  We need some
-      // way to force new octave_value_X types that are created in
-      // .oct files to be unregistered when the .oct file shared library
-      // is unloaded.
-      //
-      // OCTAVE_SAFE_CALL (singleton_cleanup_list::cleanup, ());
-
-      OCTAVE_SAFE_CALL (octave_chunk_buffer::clear, ());
-    }
-}
-
 void
 octave_add_atexit_function (const std::string& fname)
 {
@@ -1249,11 +1248,12 @@
       { false, "ARPACK_LDFLAGS", OCTAVE_CONF_ARPACK_LDFLAGS },
       { false, "ARPACK_LIBS", OCTAVE_CONF_ARPACK_LIBS },
       { false, "BLAS_LIBS", OCTAVE_CONF_BLAS_LIBS },
-      { false, "CARBON_LIBS", OCTAVE_CONF_CARBON_LIBS },
       { false, "CAMD_CPPFLAGS", OCTAVE_CONF_CAMD_CPPFLAGS },
       { false, "CAMD_LDFLAGS", OCTAVE_CONF_CAMD_LDFLAGS },
       { false, "CAMD_LIBS", OCTAVE_CONF_CAMD_LIBS },
+      { false, "CARBON_LIBS", OCTAVE_CONF_CARBON_LIBS },
       { false, "CC", OCTAVE_CONF_CC },
+      // FIXME: CC_VERSION is deprecated.  Remove in version 3.12
       { false, "CC_VERSION", OCTAVE_CONF_CC_VERSION },
       { false, "CCOLAMD_CPPFLAGS", OCTAVE_CONF_CCOLAMD_CPPFLAGS },
       { false, "CCOLAMD_LDFLAGS", OCTAVE_CONF_CCOLAMD_LDFLAGS },
@@ -1277,12 +1277,15 @@
       { false, "CXXCPP", OCTAVE_CONF_CXXCPP },
       { false, "CXXFLAGS", OCTAVE_CONF_CXXFLAGS },
       { false, "CXXPICFLAG", OCTAVE_CONF_CXXPICFLAG },
+      // FIXME: CXX_VERSION is deprecated.  Remove in version 3.12
       { false, "CXX_VERSION", OCTAVE_CONF_CXX_VERSION },
       { false, "DEFAULT_PAGER", OCTAVE_DEFAULT_PAGER },
       { false, "DEFS", OCTAVE_CONF_DEFS },
       { false, "DL_LD", OCTAVE_CONF_DL_LD },
       { false, "DL_LDFLAGS", OCTAVE_CONF_DL_LDFLAGS },
       { false, "DL_LIBS", OCTAVE_CONF_DL_LIBS },
+      { false, "GCC_VERSION", OCTAVE_CONF_GCC_VERSION },
+      { false, "GXX_VERSION", OCTAVE_CONF_GXX_VERSION },
       { false, "ENABLE_DYNAMIC_LINKING", OCTAVE_CONF_ENABLE_DYNAMIC_LINKING },
       { false, "EXEEXT", OCTAVE_CONF_EXEEXT },
       { false, "F77", OCTAVE_CONF_F77 },
@@ -1298,16 +1301,17 @@
       { false, "FFTW3F_LIBS", OCTAVE_CONF_FFTW3F_LIBS },
       { false, "FLIBS", OCTAVE_CONF_FLIBS },
       { false, "FPICFLAG", OCTAVE_CONF_FPICFLAG },
+      { false, "FT2_CFLAGS", OCTAVE_CONF_FT2_CFLAGS },
       { false, "FT2_LIBS", OCTAVE_CONF_FT2_LIBS },
       { false, "GLPK_CPPFLAGS", OCTAVE_CONF_GLPK_CPPFLAGS },
       { false, "GLPK_LDFLAGS", OCTAVE_CONF_GLPK_LDFLAGS },
       { false, "GLPK_LIBS", OCTAVE_CONF_GLPK_LIBS },
       { false, "GNUPLOT", OCTAVE_CONF_GNUPLOT },
+      { false, "GRAPHICS_CFLAGS", OCTAVE_CONF_GRAPHICS_CFLAGS },
       { false, "GRAPHICS_LIBS", OCTAVE_CONF_GRAPHICS_LIBS },
       { false, "HDF5_CPPFLAGS", OCTAVE_CONF_HDF5_CPPFLAGS },
       { false, "HDF5_LDFLAGS", OCTAVE_CONF_HDF5_LDFLAGS },
       { false, "HDF5_LIBS", OCTAVE_CONF_HDF5_LIBS },
-      { false, "INCFLAGS", OCTAVE_CONF_INCFLAGS },
       { false, "LAPACK_LIBS", OCTAVE_CONF_LAPACK_LIBS },
       { false, "LDFLAGS", OCTAVE_CONF_LDFLAGS },
       { false, "LD_CXX", OCTAVE_CONF_LD_CXX },
@@ -1315,12 +1319,14 @@
       { false, "LEX", OCTAVE_CONF_LEX },
       { false, "LEXLIB", OCTAVE_CONF_LEXLIB },
       { false, "LFLAGS", OCTAVE_CONF_LFLAGS },
-      { false, "LIBCRUFT", OCTAVE_CONF_LIBCRUFT },
       { false, "LIBEXT", OCTAVE_CONF_LIBEXT },
       { false, "LIBFLAGS", OCTAVE_CONF_LIBFLAGS },
       { false, "LIBOCTAVE", OCTAVE_CONF_LIBOCTAVE },
       { false, "LIBOCTINTERP", OCTAVE_CONF_LIBOCTINTERP },
       { false, "LIBS", OCTAVE_CONF_LIBS },
+      { false, "LLVM_CPPFLAGS", OCTAVE_CONF_LLVM_CPPFLAGS },
+      { false, "LLVM_LDFLAGS", OCTAVE_CONF_LLVM_LDFLAGS },
+      { false, "LLVM_LIBS", OCTAVE_CONF_LLVM_LIBS },
       { false, "LN_S", OCTAVE_CONF_LN_S },
       { false, "MAGICK_CPPFLAGS", OCTAVE_CONF_MAGICK_CPPFLAGS },
       { false, "MAGICK_LDFLAGS", OCTAVE_CONF_MAGICK_LDFLAGS },
@@ -1339,6 +1345,9 @@
       { false, "QRUPDATE_CPPFLAGS", OCTAVE_CONF_QRUPDATE_CPPFLAGS },
       { false, "QRUPDATE_LDFLAGS", OCTAVE_CONF_QRUPDATE_LDFLAGS },
       { false, "QRUPDATE_LIBS", OCTAVE_CONF_QRUPDATE_LIBS },
+      { 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 },
@@ -1352,11 +1361,12 @@
       { false, "SONAME_FLAGS", OCTAVE_CONF_SONAME_FLAGS },
       { false, "STATIC_LIBS", OCTAVE_CONF_STATIC_LIBS },
       { false, "TERM_LIBS", OCTAVE_CONF_TERM_LIBS },
-      { false, "UGLY_DEFS", OCTAVE_CONF_UGLY_DEFS },
       { false, "UMFPACK_CPPFLAGS", OCTAVE_CONF_UMFPACK_CPPFLAGS },
       { false, "UMFPACK_LDFLAGS", OCTAVE_CONF_UMFPACK_LDFLAGS },
       { false, "UMFPACK_LIBS", OCTAVE_CONF_UMFPACK_LIBS },
       { false, "USE_64_BIT_IDX_T", OCTAVE_CONF_USE_64_BIT_IDX_T },
+      { false, "WARN_CFLAGS", OCTAVE_CONF_WARN_CFLAGS },
+      { false, "WARN_CXXFLAGS", OCTAVE_CONF_WARN_CXXFLAGS },
       { false, "X11_INCFLAGS", OCTAVE_CONF_X11_INCFLAGS },
       { false, "X11_LIBS", OCTAVE_CONF_X11_LIBS },
       { false, "XTRA_CFLAGS", OCTAVE_CONF_XTRA_CFLAGS },
@@ -1398,6 +1408,7 @@
       { true, "octetcdir", OCTAVE_OCTETCDIR },
       { true, "octincludedir", OCTAVE_OCTINCLUDEDIR },
       { true, "octlibdir", OCTAVE_OCTLIBDIR },
+      { true, "octtestsdir", OCTAVE_OCTTESTSDIR },
       { true, "prefix", OCTAVE_PREFIX },
       { true, "startupfiledir", OCTAVE_STARTUPFILEDIR },
       { false, "version", OCTAVE_VERSION },
@@ -1418,6 +1429,8 @@
       m.assign ("words_little_endian",
                 octave_value (oct_mach_info::words_little_endian ()));
 
+      m.assign ("features", octave_value (octave_config_features ()));
+
       int i = 0;
 
       while (true)
@@ -1467,12 +1480,17 @@
 
       if (! error_state)
         {
-          Cell c = m.contents (arg.c_str ());
+          if (m.isfield (arg))
+            {
+              Cell c = m.contents (arg);
 
-          if (c.is_empty ())
-            error ("octave_config_info: no info for '%s'", arg.c_str ());
+              if (c.is_empty ())
+                error ("octave_config_info: no info for '%s'", arg.c_str ());
+              else
+                retval = c(0);
+            }
           else
-            retval = c(0);
+            error ("octave_config_info: invalid parameter '%s'", arg.c_str ());
         }
     }
   else if (nargin == 0)
@@ -1484,12 +1502,13 @@
 }
 
 /*
-%!error octave_config_info (1, 2);
-%!assert (ischar (octave_config_info ("version")));
+%!assert (ischar (octave_config_info ("version")))
 %!test
 %! x = octave_config_info ();
 %! assert (isstruct (x));
 %! assert (! isempty (x));
+
+%!error octave_config_info (1, 2)
 */
 
 #if defined (__GNUG__) && defined (DEBUG_NEW_DELETE)
@@ -1507,11 +1526,11 @@
   /* malloc (0) is unpredictable; avoid it.  */
   if (sz == 0)
     sz = 1;
-  p = malloc (sz);
+  p = gnulib::malloc (sz);
   while (p == 0)
     {
       (*__new_handler) ();
-      p = malloc (sz);
+      p = gnulib::malloc (sz);
     }
 
   if (debug_new_delete)
rename from src/toplev.h
rename to libinterp/interpfcn/toplev.h
--- a/src/toplev.h
+++ b/libinterp/interpfcn/toplev.h
@@ -52,24 +52,18 @@
 extern OCTINTERP_API int exit_status;
 
 extern OCTINTERP_API void
-clean_up_and_exit (int);
+clean_up_and_exit (int status, bool safe_to_return = false);
 
 extern OCTINTERP_API void recover_from_exception (void);
 
 extern OCTINTERP_API int main_loop (void);
 
 extern OCTINTERP_API void
-do_octave_atexit (void);
-
-extern OCTINTERP_API void
 octave_add_atexit_function (const std::string& fname);
 
 extern OCTINTERP_API bool
 octave_remove_atexit_function (const std::string& fname);
 
-// Current command to execute.
-extern OCTINTERP_API tree_statement_list *global_command;
-
 // TRUE means we are ready to interpret commands, but not everything
 // is ready for interactive use.
 extern OCTINTERP_API bool octave_interpreter_ready;
@@ -87,14 +81,17 @@
   {
     call_stack_elt (octave_function *f, symbol_table::scope_id s,
                     symbol_table::context_id c, size_t p = 0)
-      : fcn (f), stmt (0), scope (s), context (c), prev (p) { }
+      : fcn (f), line (-1), column (-1), scope (s), context (c), prev (p)
+    { }
 
     call_stack_elt (const call_stack_elt& elt)
-      : fcn (elt.fcn), stmt (elt.stmt), scope (elt.scope),
-        context (elt.context), prev (elt.prev) { }
+      : fcn (elt.fcn), line (elt.line), column (elt.column),
+        scope (elt.scope), context (elt.context), prev (elt.prev)
+    { }
 
     octave_function *fcn;
-    tree_statement *stmt;
+    int line;
+    int column;
     symbol_table::scope_id scope;
     symbol_table::context_id context;
     size_t prev;
@@ -137,12 +134,6 @@
     return instance_ok () ? instance->do_current () : 0;
   }
 
-  // Current statement (top of stack).
-  static tree_statement *current_statement (void)
-  {
-    return instance_ok () ? instance->do_current_statement () : 0;
-  }
-
   // Current line in current function.
   static int current_line (void)
   {
@@ -229,10 +220,22 @@
       instance->do_push (0, scope, context);
   }
 
-  static void set_statement (tree_statement *s)
+  static void set_location (int l, int c)
   {
     if (instance_ok ())
-      instance->do_set_statement (s);
+      instance->do_set_location (l, c);
+  }
+
+  static void set_line (int l)
+  {
+    if (instance_ok ())
+      instance->do_set_line (l);
+  }
+
+  static void set_column (int c)
+  {
+    if (instance_ok ())
+      instance->do_set_column (c);
   }
 
   static bool goto_frame (size_t n = 0, bool verbose = false)
@@ -368,25 +371,34 @@
     return retval;
   }
 
-  tree_statement *do_current_statement (void) const
-  {
-    tree_statement *retval = 0;
-
-    if (! cs.empty ())
-      {
-        const call_stack_elt& elt = cs[curr_frame];
-        retval = elt.stmt;
-      }
-
-    return retval;
-  }
-
-  void do_set_statement (tree_statement *s)
+  void do_set_location (int l, int c)
   {
     if (! cs.empty ())
       {
         call_stack_elt& elt = cs.back ();
-        elt.stmt = s;
+
+        elt.line = l;
+        elt.column = c;
+      }
+  }
+
+  void do_set_line (int l)
+  {
+    if (! cs.empty ())
+      {
+        call_stack_elt& elt = cs.back ();
+
+        elt.line = l;
+      }
+  }
+
+  void do_set_column (int c)
+  {
+    if (! cs.empty ())
+      {
+        call_stack_elt& elt = cs.back ();
+
+        elt.column = c;
       }
   }
 
rename from src/utils.cc
rename to libinterp/interpfcn/utils.cc
--- a/src/utils.cc
+++ b/libinterp/interpfcn/utils.cc
@@ -26,11 +26,11 @@
 #endif
 
 #include <cerrno>
-#include <climits>
 #include <cstring>
 
 #include <fstream>
 #include <iostream>
+#include <limits>
 #include <string>
 
 #include <sys/types.h>
@@ -99,32 +99,31 @@
 @seealso{iskeyword, exist, who}\n\
 @end deftypefn")
 {
-  octave_value retval;
+  octave_value retval = false;
 
-  int argc = args.length () + 1;
-
-  string_vector argv = args.make_argv ("isvarname");
+  int nargin = args.length ();
 
-  if (error_state)
-    return retval;
-
-  if (argc == 2)
-    retval = valid_identifier (argv[1]) && ! is_keyword (argv[1]);
-  else
+  if (nargin != 1)
     print_usage ();
+  else if (args(0).is_string ())
+    {
+      std::string varname = args(0).string_value ();
+      retval = valid_identifier (varname) && ! is_keyword (varname);
+    }
 
   return retval;
 }
 
 /*
-%!error isvarname ();
-%!error isvarname ("foo", "bar");
+%!assert (isvarname ("foo"), true)
+%!assert (isvarname ("_foo"), true)
+%!assert (isvarname ("_1"), true)
+%!assert (isvarname ("1foo"), false)
+%!assert (isvarname (""), false)
+%!assert (isvarname (12), false)
 
-%!assert (isvarname ("foo"), true);
-%!assert (isvarname ("_foo"), true);
-%!assert (isvarname ("_1"), true);
-%!assert (isvarname ("1foo"), false);
-%!assert (isvarname (""), false);
+%!error isvarname ()
+%!error isvarname ("foo", "bar");
 */
 
 // Return TRUE if F and G are both names for the same file.
@@ -339,9 +338,6 @@
 }
 
 /*
-%!error file_in_loadpath ();
-%!error file_in_loadpath ("foo", "bar", 1);
-
 %!test
 %! f = file_in_loadpath ("plot.m");
 %! assert (ischar (f));
@@ -354,6 +350,9 @@
 %!test
 %! lst = file_in_loadpath ("$$probably_!!_not_&&_a_!!_file$$", "all");
 %! assert (lst, {});
+
+%!error file_in_loadpath ()
+%!error file_in_loadpath ("foo", "bar", 1)
 */
 
 DEFUN (file_in_path, args, ,
@@ -422,10 +421,6 @@
 }
 
 /*
-%!error file_in_path ();
-%!error file_in_path ("foo");
-%!error file_in_path ("foo", "bar", "baz", 1);
-
 %!test
 %! f = file_in_path (path (), "plot.m");
 %! assert (ischar (f));
@@ -438,6 +433,10 @@
 %!test
 %! lst = file_in_path (path (), "$$probably_!!_not_&&_a_!!_file$$", "all");
 %! assert (lst, {});
+
+%!error file_in_path ()
+%!error file_in_path ("foo")
+%!error file_in_path ("foo", "bar", "baz", 1)
 */
 
 std::string
@@ -470,7 +469,7 @@
           if (fs.exists ())
             retval = name;
         }
-      else if (len > 2 && name [len - 2] == '.' && name [len - 1] == 'm')
+      else if (len > 2 && name[len - 2] == '.' && name[len - 1] == 'm')
         retval = load_path::find_fcn_file (name.substr (0, len-2));
       else
         {
@@ -527,8 +526,8 @@
           if (fs.exists ())
             retval = name;
         }
-      else if (len > 4 && name [len - 4] == '.' && name [len - 3] == 'o'
-               && name [len - 2] == 'c' && name [len - 1] == 't')
+      else if (len > 4 && name[len - 4] == '.' && name[len - 3] == 'o'
+               && name[len - 2] == 'c' && name[len - 1] == 't')
         retval = load_path::find_oct_file (name.substr (0, len-4));
       else
         retval = load_path::find_oct_file (name);
@@ -556,8 +555,8 @@
           if (fs.exists ())
             retval = name;
         }
-      else if (len > 4 && name [len - 4] == '.' && name [len - 3] == 'm'
-               && name [len - 2] == 'e' && name [len - 1] == 'x')
+      else if (len > 4 && name[len - 4] == '.' && name[len - 3] == 'm'
+               && name[len - 2] == 'e' && name[len - 1] == 'x')
         retval = load_path::find_mex_file (name.substr (0, len-4));
       else
         retval = load_path::find_mex_file (name);
@@ -674,19 +673,19 @@
 }
 
 /*
-%!error do_string_escapes ();
-%!error do_string_escapes ("foo", "bar");
+%!assert (do_string_escapes ('foo\nbar'), "foo\nbar")
+%!assert (do_string_escapes ("foo\\nbar"), "foo\nbar")
+%!assert (do_string_escapes ("foo\\nbar"), ["foo", char(10), "bar"])
+%!assert ("foo\nbar", ["foo", char(10), "bar"])
 
-%!assert (do_string_escapes ('foo\nbar'), "foo\nbar");
-%!assert (do_string_escapes ("foo\\nbar"), "foo\nbar");
-%!assert (do_string_escapes ("foo\\nbar"), ["foo", char(10), "bar"]);
-%!assert ("foo\nbar", ["foo", char(10), "bar"]);
+%!assert (do_string_escapes ('\a\b\f\n\r\t\v'), "\a\b\f\n\r\t\v")
+%!assert (do_string_escapes ("\\a\\b\\f\\n\\r\\t\\v"), "\a\b\f\n\r\t\v")
+%!assert (do_string_escapes ("\\a\\b\\f\\n\\r\\t\\v"),
+%!        char ([7, 8, 12, 10, 13, 9, 11]))
+%!assert ("\a\b\f\n\r\t\v", char ([7, 8, 12, 10, 13, 9, 11]))
 
-%!assert (do_string_escapes ('\a\b\f\n\r\t\v'), "\a\b\f\n\r\t\v");
-%!assert (do_string_escapes ("\\a\\b\\f\\n\\r\\t\\v"), "\a\b\f\n\r\t\v");
-%!assert (do_string_escapes ("\\a\\b\\f\\n\\r\\t\\v"),
-%!        char ([7, 8, 12, 10, 13, 9, 11]));
-%!assert ("\a\b\f\n\r\t\v", char ([7, 8, 12, 10, 13, 9, 11]));
+%!error do_string_escapes ()
+%!error do_string_escapes ("foo", "bar")
 */
 
 const char *
@@ -796,17 +795,17 @@
 }
 
 /*
-%!error undo_string_escapes ();
-%!error undo_string_escapes ("foo", "bar");
+%!assert (undo_string_escapes ("foo\nbar"), 'foo\nbar')
+%!assert (undo_string_escapes ("foo\nbar"), "foo\\nbar")
+%!assert (undo_string_escapes (["foo", char(10), "bar"]), "foo\\nbar")
 
-%!assert (undo_string_escapes ("foo\nbar"), 'foo\nbar');
-%!assert (undo_string_escapes ("foo\nbar"), "foo\\nbar");
-%!assert (undo_string_escapes (["foo", char(10), "bar"]), "foo\\nbar");
+%!assert (undo_string_escapes ("\a\b\f\n\r\t\v"), '\a\b\f\n\r\t\v')
+%!assert (undo_string_escapes ("\a\b\f\n\r\t\v"), "\\a\\b\\f\\n\\r\\t\\v")
+%!assert (undo_string_escapes (char ([7, 8, 12, 10, 13, 9, 11])),
+%!        "\\a\\b\\f\\n\\r\\t\\v")
 
-%!assert (undo_string_escapes ("\a\b\f\n\r\t\v"), '\a\b\f\n\r\t\v');
-%!assert (undo_string_escapes ("\a\b\f\n\r\t\v"), "\\a\\b\\f\\n\\r\\t\\v");
-%!assert (undo_string_escapes (char ([7, 8, 12, 10, 13, 9, 11])),
-%!        "\\a\\b\\f\\n\\r\\t\\v");
+%!error undo_string_escapes ()
+%!error undo_string_escapes ("foo", "bar")
 */
 
 DEFUN (is_absolute_filename, args, ,
@@ -828,10 +827,10 @@
 }
 
 /*
-%!error is_absolute_filename ();
-%!error is_absolute_filename ("foo", "bar");
+## FIXME: We need system-dependent tests here.
 
-FIXME -- we need system-dependent tests here.
+%!error is_absolute_filename ()
+%!error is_absolute_filename ("foo", "bar")
 */
 
 DEFUN (is_rooted_relative_filename, args, ,
@@ -853,17 +852,18 @@
 }
 
 /*
-%!error is_rooted_relative_filename ();
-%!error is_rooted_relative_filename ("foo", "bar");
+## FIXME: We need system-dependent tests here.
 
-FIXME -- we need system-dependent tests here.
+%!error is_rooted_relative_filename ()
+%!error is_rooted_relative_filename ("foo", "bar")
 */
 
 DEFUN (make_absolute_filename, args, ,
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} make_absolute_filename (@var{file})\n\
-Return the full name of @var{file}, relative to the current directory.\n\
-@seealso{is_absolute_filename, is_rooted_relative_filename, isdir}\n\
+Return the full name of @var{file} beginning from the root of the file\n\
+system.  No check is done for the existence of @var{file}.\n\
+@seealso{canonicalize_file_name, is_absolute_filename, is_rooted_relative_filename, isdir}\n\
 @end deftypefn")
 {
   octave_value retval = std::string ();
@@ -884,10 +884,10 @@
 }
 
 /*
-%!error make_absolute_filename ();
-%!error make_absolute_filename ("foo", "bar");
+## FIXME: We need system-dependent tests here.
 
-FIXME -- we need system-dependent tests here.
+%!error make_absolute_filename ()
+%!error make_absolute_filename ("foo", "bar")
 */
 
 DEFUN (find_dir_in_path, args, ,
@@ -931,10 +931,10 @@
 }
 
 /*
-%!error find_dir_in_path ();
-%!error find_dir_in_path ("foo", "bar", 1);
+## FIXME: We need system-dependent tests here.
 
-FIXME -- need to create tests using current path, pathsep, and dirsep.
+%!error find_dir_in_path ()
+%!error find_dir_in_path ("foo", "bar", 1)
 */
 
 DEFUNX ("errno", Ferrno, args, ,
@@ -982,9 +982,7 @@
 }
 
 /*
-%!error errno ("foo", 1);
-
-%!assert (isnumeric (errno ()));
+%!assert (isnumeric (errno ()))
 
 %!test
 %! lst = errno_list ();
@@ -994,6 +992,8 @@
 %! errno (oldval);
 %! newval = errno ();
 %! assert (oldval, newval);
+
+%!error errno ("foo", 1)
 */
 
 DEFUN (errno_list, args, ,
@@ -1013,9 +1013,9 @@
 }
 
 /*
-%!error errno_list ("foo");
+%!assert (isstruct (errno_list ()))
 
-%!assert (isstruct (errno_list ()));
+%!error errno_list ("foo")
 */
 
 static void
@@ -1265,7 +1265,9 @@
         = static_cast<unsigned int> (modf (seconds, &t) * 1000000);
 
       unsigned int sec
-        = (t > UINT_MAX) ? UINT_MAX : static_cast<unsigned int> (t);
+        = ((t > std::numeric_limits<unsigned int>::max ())
+           ? std::numeric_limits<unsigned int>::max ()
+           : static_cast<unsigned int> (t));
 
       // Versions of these functions that accept unsigned int args are
       // defined in cutils.c.
@@ -1331,11 +1333,11 @@
 }
 
 /*
-%!error isindex ();
+%!assert (isindex ([1, 2, 3]))
+%!assert (isindex (1:3))
+%!assert (isindex ([1, 2, -3]), false)
 
-%!assert (isindex ([1, 2, 3]));
-%!assert (isindex (1:3));
-%!assert (isindex ([1, 2, -3]), false);
+%!error isindex ()
 */
 
 octave_value_list
rename from src/utils.h
rename to libinterp/interpfcn/utils.h
rename from src/variables.cc
rename to libinterp/interpfcn/variables.cc
--- a/src/variables.cc
+++ b/libinterp/interpfcn/variables.cc
@@ -49,6 +49,7 @@
 #include "input.h"
 #include "lex.h"
 #include "load-path.h"
+#include "octave-link.h"
 #include "oct-map.h"
 #include "oct-obj.h"
 #include "ov.h"
@@ -282,7 +283,7 @@
 
           frame.run ();
 
-          if (tmp.is_defined () && tmp.is_map ())
+          if (tmp.is_defined () && (tmp.is_map () || tmp.is_java ()))
             names = tmp.map_keys ();
         }
     }
@@ -361,7 +362,7 @@
 @group\n\
 global x\n\
 isglobal (\"x\")\n\
-     @result{} 1\n\
+   @result{} 1\n\
 @end group\n\
 @end example\n\
 @seealso{isvarname, exist}\n\
@@ -543,12 +544,13 @@
 Check only for built-in functions.\n\
 \n\
 @item \"file\"\n\
-Check only for files.\n\
+Check only for files and directories.\n\
 \n\
 @item \"dir\"\n\
 Check only for directories.\n\
 @end table\n\
-@seealso{file_in_loadpath}\n\
+\n\
+@seealso{file_in_loadpath, file_in_path, stat}\n\
 @end deftypefn")
 {
   octave_value retval = false;
@@ -580,17 +582,17 @@
 
 /*
 %!test
-%!  if (isunix ())
-%!    assert (exist ("/tmp") == 7);
-%!    assert (exist ("/tmp", "file") == 7);
-%!    assert (exist ("/tmp", "dir") == 7);
-%!    assert (exist ("/bin/sh") == 2);
-%!    assert (exist ("/bin/sh", "file") == 2);
-%!    assert (exist ("/bin/sh", "dir") == 0);
-%!    assert (exist ("/dev/null") == 2);
-%!    assert (exist ("/dev/null", "file") == 2);
-%!    assert (exist ("/dev/null", "dir") == 0);
-%!  endif
+%! if (isunix ())
+%!   assert (exist ("/tmp") == 7);
+%!   assert (exist ("/tmp", "file") == 7);
+%!   assert (exist ("/tmp", "dir") == 7);
+%!   assert (exist ("/bin/sh") == 2);
+%!   assert (exist ("/bin/sh", "file") == 2);
+%!   assert (exist ("/bin/sh", "dir") == 0);
+%!   assert (exist ("/dev/null") == 2);
+%!   assert (exist ("/dev/null", "file") == 2);
+%!   assert (exist ("/dev/null", "dir") == 0);
+%! endif
 */
 
 octave_value
@@ -615,7 +617,7 @@
 void
 set_global_value (const std::string& nm, const octave_value& val)
 {
-  symbol_table::global_varref (nm) = val;
+  symbol_table::global_assign (nm, val);
 }
 
 octave_value
@@ -632,7 +634,7 @@
 void
 set_top_level_value (const std::string& nm, const octave_value& val)
 {
-  symbol_table::top_level_varref (nm) = val;
+  symbol_table::top_level_assign (nm, val);
 }
 
 // Variable values.
@@ -1336,7 +1338,7 @@
     param_names(pos_t) = "Type";
 
     for (size_t i = 0; i < param_string.length (); i++)
-      param_length(i) = param_names(i) . length ();
+      param_length(i) = param_names(i).length ();
 
     // The attribute column needs size 5.
     param_length(pos_a) = 5;
@@ -1519,7 +1521,7 @@
             // Push parameter into list ...
             idx += text.length ();
             param.text=text;
-            param.line.assign (text.length(), ' ');
+            param.line.assign (text.length (), ' ');
             params.push_back (param);
           }
       }
@@ -1558,7 +1560,7 @@
             error ("whos: -file argument must be followed by a file name");
           else
             {
-              std::string nm = argv [i + 1];
+              std::string nm = argv[i + 1];
 
               unwind_protect frame;
 
@@ -1798,6 +1800,7 @@
 @table @asis\n\
 @item Attr\n\
 Attributes of the listed variable.  Possible attributes are:\n\
+\n\
 @table @asis\n\
 @item blank\n\
 Variable in local scope\n\
@@ -1879,7 +1882,7 @@
         }
       else
         {
-          symbol_table::varref (ans) = val;
+          symbol_table::force_assign (ans, val);
 
           if (print)
             val.print_with_name (octave_stdout, ans);
@@ -1975,7 +1978,7 @@
 {
   octave_value_list retval;
 
-  if (args.length() == 1)
+  if (args.length () == 1)
     {
       std::string name = args(0).string_value ();
 
@@ -2011,7 +2014,7 @@
 {
   octave_value retval;
 
-  if (args.length() == 1)
+  if (args.length () == 1)
     {
       std::string name = args(0).string_value ();
 
@@ -2298,6 +2301,7 @@
 clear the function definition.\n\
 \n\
 The following options are available in both long and short form\n\
+\n\
 @table @code\n\
 @item -all, -a\n\
 Clears all local and global user-defined variables and all functions\n\
@@ -2322,6 +2326,7 @@
 The arguments are treated as regular expressions as any variables that\n\
 match will be cleared.\n\
 @end table\n\
+\n\
 With the exception of @code{exclusive}, all long options can be used\n\
 without the dash as well.\n\
 @end deftypefn")
@@ -2336,8 +2341,10 @@
     {
       if (argc == 1)
         {
-          do_clear_globals (argv, argc, 1);
-          do_clear_variables (argv, argc, 1);
+          do_clear_globals (argv, argc, true);
+          do_clear_variables (argv, argc, true);
+
+          octave_link::clear_workspace ();
         }
       else
         {
@@ -2449,6 +2456,8 @@
                       do_clear_symbols (argv, argc, idx, exclusive);
                     }
                 }
+
+              octave_link::set_workspace ();
             }
         }
     }
@@ -2532,7 +2541,7 @@
   return SET_INTERNAL_VARIABLE (whos_line_format);
 }
 
-static std::string Vmissing_function_hook = "unimplemented";
+static std::string Vmissing_function_hook = "__unimplemented__";
 
 DEFUN (missing_function_hook, args, nargout,
     "-*- texinfo -*-\n\
@@ -2555,16 +2564,21 @@
   // Don't do this if we're handling errors.
   if (buffer_error_messages == 0 && ! Vmissing_function_hook.empty ())
     {
-      // Ensure auto-restoration.
-      unwind_protect frame;
-      frame.protect_var (Vmissing_function_hook);
-
-      // Clear the variable prior to calling the function.
-      const std::string func_name = Vmissing_function_hook;
-      Vmissing_function_hook.clear ();
-
-      // Call.
-      feval (func_name, octave_value (name));
+      octave_value val = symbol_table::find_function (Vmissing_function_hook);
+
+      if (val.is_defined ())
+        {
+          // Ensure auto-restoration.
+          unwind_protect frame;
+          frame.protect_var (Vmissing_function_hook);
+
+          // Clear the variable prior to calling the function.
+          const std::string func_name = Vmissing_function_hook;
+          Vmissing_function_hook.clear ();
+
+          // Call.
+          feval (func_name, octave_value (name));
+        }
     }
 }
 
rename from src/variables.h
rename to libinterp/interpfcn/variables.h
--- a/src/variables.h
+++ b/libinterp/interpfcn/variables.h
@@ -32,11 +32,13 @@
 class octave_builtin;
 class string_vector;
 
-#include <climits>
 #include <cfloat>
 
+#include <limits>
 #include <string>
 
+#include "lo-ieee.h"
+
 #include "ov.h"
 #include "ov-builtin.h"
 #include "symtab.h"
@@ -97,12 +99,14 @@
 extern OCTINTERP_API octave_value
 set_internal_variable (int& var, const octave_value_list& args,
                        int nargout, const char *nm,
-                       int minval = INT_MIN, int maxval = INT_MAX);
+                       int minval = std::numeric_limits<int>::min (),
+                       int maxval = std::numeric_limits<int>::max ());
 
 extern OCTINTERP_API octave_value
 set_internal_variable (double& var, const octave_value_list& args,
                        int nargout, const char *nm,
-                       double minval = DBL_MIN, double maxval = DBL_MAX);
+                       double minval = -octave_Inf,
+                       double maxval = octave_Inf);
 
 extern OCTINTERP_API octave_value
 set_internal_variable (std::string& var, const octave_value_list& args,
@@ -132,7 +136,8 @@
 extern OCTINTERP_API void bind_ans (const octave_value& val, bool print);
 
 extern OCTINTERP_API void
-bind_internal_variable (const std::string& fname, const octave_value& val);
+bind_internal_variable (const std::string& fname,
+                        const octave_value& val) GCC_ATTR_DEPRECATED;
 
 extern OCTINTERP_API void mlock (void);
 extern OCTINTERP_API void munlock (const std::string&);
new file mode 100644
--- /dev/null
+++ b/libinterp/interpfcn/workspace-element.h
@@ -0,0 +1,84 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+
+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_workspace_element_h)
+#define octave_workspace_element_h 1
+
+#include <string>
+
+class workspace_element
+{
+public:
+
+  workspace_element (char scope_arg = 'l',
+                     const std::string& symbol_arg = "<name>",
+                     const std::string& class_name_arg = "<class>",
+                     const std::string& value_arg = "<value>",
+                     const std::string& dimension_arg = "<dimension>")
+    : xscope (scope_arg), xsymbol (symbol_arg),
+      xclass_name (class_name_arg), xvalue (value_arg),
+      xdimension (dimension_arg)
+  { }
+
+  workspace_element (const workspace_element& ws_elt)
+    : xscope (ws_elt.xscope), xsymbol (ws_elt.xsymbol),
+      xclass_name (ws_elt.xclass_name), xvalue (ws_elt.xvalue),
+      xdimension (ws_elt.xdimension)
+  { }
+
+  workspace_element operator = (const workspace_element& ws_elt)
+  {
+    if (this != &ws_elt)
+      {
+        xscope = ws_elt.xscope;
+        xsymbol = ws_elt.xsymbol;
+        xclass_name = ws_elt.xclass_name;
+        xvalue = ws_elt.xvalue;
+        xdimension = ws_elt.xdimension;
+      }
+
+    return *this;
+  }
+
+  ~workspace_element (void) { }
+
+  char scope (void) const { return xscope; }
+
+  std::string symbol (void) const { return xsymbol; }
+
+  std::string class_name (void) const { return xclass_name; }
+
+  std::string value (void) const { return xvalue; }
+
+  std::string dimension (void) const { return xdimension; }
+
+private:
+
+  // [g]lobal, [p]ersistent, [l]ocal
+  char xscope;
+  std::string xsymbol;
+  std::string xclass_name;
+  std::string xvalue;
+  std::string xdimension;
+};
+
+#endif
rename from src/link-deps.mk
rename to libinterp/link-deps.mk
--- a/src/link-deps.mk
+++ b/libinterp/link-deps.mk
@@ -1,26 +1,31 @@
-include ../liboctave/link-deps.mk
+include $(top_srcdir)/liboctave/link-deps.mk
 
 if AMCOND_ENABLE_DYNAMIC_LINKING
   LIBOCTINTERP_LINK_DEPS =
 else
-  LIBOCTINTERP_LINK_DEPS = $(DLD_FUNCTIONS_LIBS)
+  LIBOCTINTERP_LINK_DEPS = $(DLDFCN_LIBS)
 endif
 
 LIBOCTINTERP_LINK_DEPS += \
-  $(GRAPHICS_LIBS) \
   $(FT2_LIBS) \
   $(HDF5_LIBS) \
   $(Z_LIBS) \
+  $(FFTW_XLIBS) \
+  $(REGEX_LIBS) \
   $(OPENGL_LIBS) \
   $(X11_LIBS) \
-  $(CARBON_LIBS)
+  $(CARBON_LIBS) \
+  $(LLVM_LIBS) \
+  $(JAVA_LIBS) \
+  $(LAPACK_LIBS)
 
 LIBOCTINTERP_LINK_OPTS = \
-  $(GRAPHICS_LDFLAGS) \
   $(FT2_LDFLAGS) \
   $(HDF5_LDFLAGS) \
   $(Z_LDFLAGS) \
-  $(REGEX_LDFLAGS)
+  $(REGEX_LDFLAGS) \
+  $(FFTW_XLDFLAGS) \
+  $(LLVM_LDFLAGS)
 
 OCT_LINK_DEPS =
 
rename from src/mk-errno-list
rename to libinterp/mk-errno-list
--- a/src/mk-errno-list
+++ b/libinterp/mk-errno-list
@@ -41,7 +41,7 @@
 
 t = "#if defined (%s)\n    { \"%s\", %s, },\n#endif\n"
 errstr = ""
-for k in errorcode.keys():
+for k in errorcode.keys ():
     errstr += t % tuple(3*[errorcode[k]])
 
 for l in stdin:
rename from src/mk-pkg-add
rename to libinterp/mk-pkg-add
rename from src/mkbuiltins
rename to libinterp/mkbuiltins
--- a/src/mkbuiltins
+++ b/libinterp/mkbuiltins
@@ -18,21 +18,67 @@
 # along with Octave; see the file COPYING.  If not, see
 # <http://www.gnu.org/licenses/>.
 
-if test $# -eq 0; then
-  echo "usage: mkbuiltins f1 f2 ..." 1>&2
+if test $# -lt 2; then
+  echo "usage: mkbuiltins --header|--source f1 f2 ..." 1>&2
   exit 1
 fi
 
 SED=${SED:-'sed'}
 
-cat << \EOF
+make_header=false
+make_source=false
+case "$1" in
+  --header)
+    make_header=true
+    shift
+  ;;
+  --source)
+    make_source=true
+    shift
+  ;;
+  *)
+    echo "mkbuiltins: unrecognized option: $1" 1>&2
+    exit 1
+  ;;
+esac
+
+if $make_header; then
+
+  cat << \EOF
+// DO NOT EDIT!  Generated automatically by mkbuiltins.
+
+#if !defined (octave_builtin_defun_decls_h)
+#define octave_builtin_defun_decls_h 1
+
+#include "oct-obj.h"
+
+#define DEFUN_DECL(name) \
+  extern OCTINTERP_API octave_value_list \
+  name (const octave_value_list& = octave_value_list (), int = 0);
+
+EOF
+
+ $SED -n -e 's/ *\(XDEFUN\|XDEFCONSTFUN\)_INTERNAL *( *\([_A-Za-z][_A-Za-z0-9]*\) *,.*$/DEFUN_DECL (F\2);/p; s/^ *XDEFUNX_INTERNAL *( *"\([_A-Za-z][_A-Za-z0-9]*\)" *,.*$/DEFUN_DECL (F\1);/p' "$@"
+
+  cat << \EOF
+
+#undef DEFUN_DECL
+
+#endif
+
+EOF
+
+else
+
+  cat << \EOF
 // DO NOT EDIT!  Generated automatically by mkbuiltins.
 
 #ifdef HAVE_CONFIG_H
-#include "config.h"
+#include <config.h>
 #endif
 
 #include "defun.h"
+#include "help.h"
 #include "oct-obj.h"
 #include "variables.h"
 #include "builtins.h"
@@ -57,19 +103,20 @@
 
 #endif
 
-#define XDEFUN_FILE_NAME(name)
+#define XDEFUN_FILE_NAME(name) \
+  std::string file = name;
 
 #define XDEFUN_INTERNAL(name, args_name, nargout_name, doc) \
   extern DECLARE_FUN (name, args_name, nargout_name); \
-  install_builtin_function (F ## name, #name, doc); \
+  install_builtin_function (F ## name, #name, file, doc); \
 
 #define XDEFCONSTFUN_INTERNAL(name, args_name, nargout_name, doc) \
   extern DECLARE_FUN (name, args_name, nargout_name); \
-  install_builtin_function (F ## name, #name, doc, false); \
+  install_builtin_function (F ## name, #name, file, doc, false); \
 
 #define XDEFUNX_INTERNAL(name, fname, args_name, nargout_name, doc) \
   extern DECLARE_FUNX (fname, args_name, nargout_name); \
-  install_builtin_function (fname, name, doc); \
+  install_builtin_function (fname, name, file, doc); \
 
 #define XDEFALIAS_INTERNAL(alias, name) \
   alias_builtin (#alias, #name);
@@ -78,33 +125,37 @@
 
 EOF
 
-for arg
-do
-  fcn=`echo "$arg" | $SED 's,.*/,,; s/\.df//; s/-/_/g;'`
-  echo "static void"
-  echo "install_${fcn}_fcns (void)"
-  echo "{"
-  cat "$arg"
-  echo "}"
-  echo ""
-done
+  for arg
+  do
+    fcn=`echo "$arg" | $SED 's,.*/,,; s/\.df//; s/-/_/g;'`
+    echo "static void"
+    echo "install_${fcn}_fcns (void)"
+    echo "{"
+    cat "$arg"
+    echo "}"
+    echo ""
+  done
 
-cat << \EOF
+  cat << \EOF
 
 void
 install_builtins (void)
 {
 EOF
 
-for arg
-do
-  fcn=`echo "$arg" | $SED 's,.*/,,; s/\.df//; s/-/_/g;'`
-  echo "  install_${fcn}_fcns ();"
-done
+  for arg
+  do
+    fcn=`echo "$arg" | $SED 's,.*/,,; s/\.df//; s/-/_/g;'`
+    echo "  install_${fcn}_fcns ();"
+  done
 
-cat << \EOF
+  cat << \EOF
+
+  install_built_in_docstrings ();
 }
 
 EOF
 
+fi
+
 exit 0
rename from src/mkdefs
rename to libinterp/mkdefs
--- a/src/mkdefs
+++ b/libinterp/mkdefs
@@ -31,10 +31,10 @@
 echo "// DO NOT EDIT!  Generated automatically by mkdefs."
 case "$file" in
   $srcdir/*)
-    xsrcdir=`echo "$file" | sed "s,^$srcdir,src,"`
+    xsrcdir=`echo "$file" | sed "s,^$srcdir,libinterp,"`
   ;;
   *)
-    xsrcdir="src/$file"
+    xsrcdir="libinterp/$file"
   ;;
 esac
 echo " XDEFUN_FILE_NAME (\"$xsrcdir\")"
rename from src/mkdocs
rename to libinterp/mkdocs
rename from src/mkops
rename to libinterp/mkops
--- a/src/mkops
+++ b/libinterp/mkops
@@ -21,10 +21,10 @@
 SED=${SED:-'sed'}
 
 cat << \EOF
-// DO NOT EDIT!  Generated automatically by mkbuiltins.
+// DO NOT EDIT!  Generated automatically by mkops.
 
 #ifdef HAVE_CONFIG_H
-#include "config.h"
+#include <config.h>
 #endif
 
 extern void install_base_type_conversions (void);
@@ -32,7 +32,7 @@
 EOF
 
 for file in "$@"; do
-  f=`echo $file | $SED 's,^\./,,; s%^OPERATORS/op-%%; s%\.cc%%; s%-%_%g'`
+  f=`echo $file | $SED 's,^\./,,; s%^operators/op-%%; s%\.cc%%; s%-%_%g'`
   echo "extern void install_${f}_ops (void);"
 done
 
@@ -46,7 +46,7 @@
 EOF
 
 for file in "$@"; do
-  f=`echo $file | $SED 's,^\./,,; s%^OPERATORS/op-%%; s%\.cc%%; s%-%_%g'`
+  f=`echo $file | $SED 's,^\./,,; s%^operators/op-%%; s%\.cc%%; s%-%_%g'`
   echo "  install_${f}_ops ();"
 done
 
rename from src/oct-conf.h.in
rename to libinterp/oct-conf.in.h
--- a/src/oct-conf.h.in
+++ b/libinterp/oct-conf.in.h
@@ -1,4 +1,4 @@
-// oct-conf.h.in
+// %NO_EDIT_WARNING%
 /*
 
 Copyright (C) 1996-2012 John W. Eaton
@@ -96,6 +96,7 @@
 #define OCTAVE_CONF_CC %OCTAVE_CONF_CC%
 #endif
 
+// FIXME: OCTAVE_CONF_CCC_VERSION is deprecated.  Remove in version 3.12
 #ifndef OCTAVE_CONF_CC_VERSION
 #define OCTAVE_CONF_CC_VERSION %OCTAVE_CONF_CC_VERSION%
 #endif
@@ -188,6 +189,7 @@
 #define OCTAVE_CONF_CXX %OCTAVE_CONF_CXX%
 #endif
 
+// FIXME: OCTAVE_CONF_CXX_VERSION is deprecated.  Remove in version 3.12
 #ifndef OCTAVE_CONF_CXX_VERSION
 #define OCTAVE_CONF_CXX_VERSION %OCTAVE_CONF_CXX_VERSION%
 #endif
@@ -212,10 +214,22 @@
 #define OCTAVE_CONF_DL_LIBS %OCTAVE_CONF_DL_LIBS%
 #endif
 
+#ifndef OCTAVE_CONF_ENABLE_DYNAMIC_LINKING
+#define OCTAVE_CONF_ENABLE_DYNAMIC_LINKING %OCTAVE_CONF_ENABLE_DYNAMIC_LINKING%
+#endif
+
 #ifndef OCTAVE_CONF_EXEEXT
 #define OCTAVE_CONF_EXEEXT %OCTAVE_CONF_EXEEXT%
 #endif
 
+#ifndef OCTAVE_CONF_GCC_VERSION
+#define OCTAVE_CONF_GCC_VERSION %OCTAVE_CONF_GCC_VERSION%
+#endif
+
+#ifndef OCTAVE_CONF_GXX_VERSION
+#define OCTAVE_CONF_GXX_VERSION %OCTAVE_CONF_GXX_VERSION%
+#endif
+
 #ifndef OCTAVE_CONF_F77
 #define OCTAVE_CONF_F77 %OCTAVE_CONF_F77%
 #endif
@@ -268,6 +282,10 @@
 #define OCTAVE_CONF_FPICFLAG %OCTAVE_CONF_FPICFLAG%
 #endif
 
+#ifndef OCTAVE_CONF_FT2_CFLAGS
+#define OCTAVE_CONF_FT2_CFLAGS %OCTAVE_CONF_FT2_CFLAGS%
+#endif
+
 #ifndef OCTAVE_CONF_FT2_LIBS
 #define OCTAVE_CONF_FT2_LIBS %OCTAVE_CONF_FT2_LIBS%
 #endif
@@ -288,6 +306,10 @@
 #define OCTAVE_CONF_GNUPLOT %OCTAVE_CONF_GNUPLOT%
 #endif
 
+#ifndef OCTAVE_CONF_GRAPHICS_CFLAGS
+#define OCTAVE_CONF_GRAPHICS_CFLAGS %OCTAVE_CONF_GRAPHICS_CFLAGS%
+#endif
+
 #ifndef OCTAVE_CONF_GRAPHICS_LIBS
 #define OCTAVE_CONF_GRAPHICS_LIBS %OCTAVE_CONF_GRAPHICS_LIBS%
 #endif
@@ -340,10 +362,6 @@
 #define OCTAVE_CONF_LFLAGS %OCTAVE_CONF_LFLAGS%
 #endif
 
-#ifndef OCTAVE_CONF_LIBCRUFT
-#define OCTAVE_CONF_LIBCRUFT %OCTAVE_CONF_LIBCRUFT%
-#endif
-
 #ifndef OCTAVE_CONF_LIBEXT
 #define OCTAVE_CONF_LIBEXT %OCTAVE_CONF_LIBEXT%
 #endif
@@ -384,6 +402,18 @@
 #define OCTAVE_CONF_MAGICK_LIBS %OCTAVE_CONF_MAGICK_LIBS%
 #endif
 
+#ifndef OCTAVE_CONF_LLVM_CPPFLAGS
+#define OCTAVE_CONF_LLVM_CPPFLAGS %OCTAVE_CONF_LLVM_CPPFLAGS%
+#endif
+
+#ifndef OCTAVE_CONF_LLVM_LDFLAGS
+#define OCTAVE_CONF_LLVM_LDFLAGS %OCTAVE_CONF_LLVM_LDFLAGS%
+#endif
+
+#ifndef OCTAVE_CONF_LLVM_LIBS
+#define OCTAVE_CONF_LLVM_LIBS %OCTAVE_CONF_LLVM_LIBS%
+#endif
+
 #ifndef OCTAVE_CONF_MKOCTFILE_DL_LDFLAGS
 #define OCTAVE_CONF_MKOCTFILE_DL_LDFLAGS %OCTAVE_CONF_MKOCTFILE_DL_LDFLAGS%
 #endif
@@ -452,6 +482,18 @@
 #define OCTAVE_CONF_QRUPDATE_LIBS %OCTAVE_CONF_QRUPDATE_LIBS%
 #endif
 
+#ifndef OCTAVE_CONF_QT_CPPFLAGS
+#define OCTAVE_CONF_QT_CPPFLAGS %OCTAVE_CONF_QT_CPPFLAGS%
+#endif
+
+#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
 #define OCTAVE_CONF_RANLIB %OCTAVE_CONF_RANLIB%
 #endif
@@ -504,10 +546,6 @@
 #define OCTAVE_CONF_TERM_LIBS %OCTAVE_CONF_TERM_LIBS%
 #endif
 
-#ifndef OCTAVE_CONF_UGLY_DEFS
-#define OCTAVE_CONF_UGLY_DEFS %OCTAVE_CONF_UGLY_DEFS%
-#endif
-
 #ifndef OCTAVE_CONF_UMFPACK_CPPFLAGS
 #define OCTAVE_CONF_UMFPACK_CPPFLAGS %OCTAVE_CONF_UMFPACK_CPPFLAGS%
 #endif
@@ -524,8 +562,12 @@
 #define OCTAVE_CONF_USE_64_BIT_IDX_T %OCTAVE_CONF_USE_64_BIT_IDX_T%
 #endif
 
-#ifndef OCTAVE_CONF_ENABLE_DYNAMIC_LINKING
-#define OCTAVE_CONF_ENABLE_DYNAMIC_LINKING %OCTAVE_CONF_ENABLE_DYNAMIC_LINKING%
+#ifndef OCTAVE_CONF_WARN_CFLAGS
+#define OCTAVE_CONF_WARN_CFLAGS %OCTAVE_CONF_WARN_CFLAGS%
+#endif
+
+#ifndef OCTAVE_CONF_WARN_CXXFLAGS
+#define OCTAVE_CONF_WARN_CXXFLAGS %OCTAVE_CONF_WARN_CXXFLAGS%
 #endif
 
 #ifndef OCTAVE_CONF_X11_INCFLAGS
new file mode 100644
--- /dev/null
+++ b/libinterp/octave-value/module.mk
@@ -0,0 +1,143 @@
+EXTRA_DIST += \
+  octave-value/module.mk
+
+OV_INTTYPE_INC = \
+  octave-value/ov-base-int.h \
+  octave-value/ov-base-int.cc \
+  octave-value/ov-int-traits.h \
+  octave-value/ov-int16.h \
+  octave-value/ov-int32.h \
+  octave-value/ov-int64.h \
+  octave-value/ov-int8.h \
+  octave-value/ov-intx.h \
+  octave-value/ov-uint16.h \
+  octave-value/ov-uint32.h \
+  octave-value/ov-uint64.h \
+  octave-value/ov-uint8.h
+
+OV_SPARSE_INC = \
+  octave-value/ov-base-sparse.h \
+  octave-value/ov-bool-sparse.h \
+  octave-value/ov-cx-sparse.h \
+  octave-value/ov-re-sparse.h
+
+OCTAVE_VALUE_INC = \
+  octave-value/ov-base-diag.h \
+  octave-value/ov-base-diag.cc \
+  octave-value/ov-base-mat.h \
+  octave-value/ov-base-mat.cc \
+  octave-value/ov-base-scalar.h \
+  octave-value/ov-base-scalar.cc \
+  octave-value/ov-base.h \
+  octave-value/ov-bool-mat.h \
+  octave-value/ov-bool-mat.cc \
+  octave-value/ov-bool.h \
+  octave-value/ov-builtin.h \
+  octave-value/ov-cell.h \
+  octave-value/ov-ch-mat.h \
+  octave-value/ov-class.h \
+  octave-value/ov-colon.h \
+  octave-value/ov-complex.h \
+  octave-value/ov-cs-list.h \
+  octave-value/ov-cx-diag.h \
+  octave-value/ov-cx-mat.h \
+  octave-value/ov-dld-fcn.h \
+  octave-value/ov-fcn-handle.h \
+  octave-value/ov-fcn-inline.h \
+  octave-value/ov-fcn.h \
+  octave-value/ov-float.h \
+  octave-value/ov-flt-complex.h \
+  octave-value/ov-flt-cx-diag.h \
+  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 \
+  octave-value/ov-oncleanup.h \
+  octave-value/ov-perm.h \
+  octave-value/ov-range.h \
+  octave-value/ov-re-diag.h \
+  octave-value/ov-re-mat.h \
+  octave-value/ov-scalar.h \
+  octave-value/ov-str-mat.h \
+  octave-value/ov-struct.h \
+  octave-value/ov-type-conv.h \
+  octave-value/ov-typeinfo.h \
+  octave-value/ov-usr-fcn.h \
+  octave-value/ov.h \
+  $(OV_INTTYPE_INC) \
+  $(OV_SPARSE_INC)
+
+OV_INTTYPE_SRC = \
+  octave-value/ov-int16.cc \
+  octave-value/ov-int32.cc \
+  octave-value/ov-int64.cc \
+  octave-value/ov-int8.cc \
+  octave-value/ov-uint16.cc \
+  octave-value/ov-uint32.cc \
+  octave-value/ov-uint64.cc \
+  octave-value/ov-uint8.cc
+
+OV_SPARSE_SRC = \
+  octave-value/ov-base-sparse.cc \
+  octave-value/ov-bool-sparse.cc \
+  octave-value/ov-cx-sparse.cc \
+  octave-value/ov-re-sparse.cc
+
+OCTAVE_VALUE_SRC = \
+  octave-value/ov-base.cc \
+  octave-value/ov-bool-mat.cc \
+  octave-value/ov-bool.cc \
+  octave-value/ov-builtin.cc \
+  octave-value/ov-cell.cc \
+  octave-value/ov-ch-mat.cc \
+  octave-value/ov-class.cc \
+  octave-value/ov-colon.cc \
+  octave-value/ov-complex.cc \
+  octave-value/ov-cs-list.cc \
+  octave-value/ov-cx-diag.cc \
+  octave-value/ov-cx-mat.cc \
+  octave-value/ov-dld-fcn.cc \
+  octave-value/ov-fcn-handle.cc \
+  octave-value/ov-fcn-inline.cc \
+  octave-value/ov-fcn.cc \
+  octave-value/ov-float.cc \
+  octave-value/ov-flt-complex.cc \
+  octave-value/ov-flt-cx-diag.cc \
+  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 \
+  octave-value/ov-oncleanup.cc \
+  octave-value/ov-perm.cc \
+  octave-value/ov-range.cc \
+  octave-value/ov-re-diag.cc \
+  octave-value/ov-re-mat.cc \
+  octave-value/ov-scalar.cc \
+  octave-value/ov-str-mat.cc \
+  octave-value/ov-struct.cc \
+  octave-value/ov-typeinfo.cc \
+  octave-value/ov-usr-fcn.cc \
+  octave-value/ov.cc \
+  $(OV_INTTYPE_SRC) \
+  $(OV_SPARSE_SRC)
+
+noinst_LTLIBRARIES += octave-value/liboctave-value.la
+
+octave_value_liboctave_value_la_SOURCES = $(OCTAVE_VALUE_SRC)
+
+## 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)
rename from src/ov-base-diag.cc
rename to libinterp/octave-value/ov-base-diag.cc
--- a/src/ov-base-diag.cc
+++ b/libinterp/octave-value/ov-base-diag.cc
@@ -29,6 +29,7 @@
 #include "mach-info.h"
 #include "lo-ieee.h"
 
+#include "mxarray.h"
 #include "ov-base.h"
 #include "ov-base-mat.h"
 #include "pr-output.h"
@@ -108,7 +109,7 @@
 
       if (idx0.is_scalar () && idx1.is_scalar ())
         {
-          retval = matrix.elem (idx0(0), idx1(0));
+          retval = matrix.checkelem (idx0(0), idx1(0));
         }
       else
         {
@@ -243,7 +244,7 @@
 
   if (numel () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  type_name (), "real scalar");
 
       retval = helper_getreal (el_type (matrix (0, 0)));
@@ -267,7 +268,7 @@
 
   if (numel () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  type_name (), "real scalar");
 
       retval = helper_getreal (el_type (matrix (0, 0)));
@@ -288,7 +289,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  type_name (), "complex scalar");
 
       retval = matrix (0, 0);
@@ -309,7 +310,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  type_name (), "complex scalar");
 
       retval = matrix (0, 0);
@@ -425,7 +426,7 @@
   os << "# rows: " << matrix.rows () << "\n"
     << "# columns: " << matrix.columns () << "\n";
 
-  os << matrix.diag ();
+  os << matrix.extract_diag ();
 
   return true;
 }
rename from src/ov-base-diag.h
rename to libinterp/octave-value/ov-base-diag.h
rename from src/ov-base-int.cc
rename to libinterp/octave-value/ov-base-int.cc
--- a/src/ov-base-int.cc
+++ b/libinterp/octave-value/ov-base-int.cc
@@ -24,9 +24,8 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 #include <vector>
 
 #include "lo-ieee.h"
@@ -65,7 +64,10 @@
 struct octave_base_int_helper
 {
   static bool
-  char_value_out_of_range (T val) { return val < 0 || val > UCHAR_MAX; }
+  char_value_out_of_range (T val)
+  {
+    return val < 0 || val > std::numeric_limits<unsigned char>::max ();
+  }
 };
 
 template <class T>
@@ -77,7 +79,10 @@
 template <class T>
 struct octave_base_int_helper<T, false, true>
 {
-  static bool char_value_out_of_range (T val) { return val > UCHAR_MAX; }
+  static bool char_value_out_of_range (T val)
+  {
+    return val > std::numeric_limits<unsigned char>::max ();
+  }
 };
 
 template <class T>
@@ -239,11 +244,11 @@
 octave_base_int_matrix<T>::save_binary (std::ostream& os, bool&)
 {
   dim_vector d = this->dims ();
-  if (d.length() < 1)
+  if (d.length () < 1)
     return false;
 
   // Use negative value for ndims to differentiate with old format!!
-  int32_t tmp = - d.length();
+  int32_t tmp = - d.length ();
   os.write (reinterpret_cast<char *> (&tmp), 4);
   for (int i=0; i < d.length (); i++)
     {
@@ -251,7 +256,7 @@
       os.write (reinterpret_cast<char *> (&tmp), 4);
     }
 
-  os.write (reinterpret_cast<const char *> (this->matrix.data()), this->byte_size());
+  os.write (reinterpret_cast<const char *> (this->matrix.data ()), this->byte_size ());
 
   return true;
 }
@@ -303,7 +308,7 @@
   if (swap)
     {
       int nel = dv.numel ();
-      int bytes = nel / m.byte_size();
+      int bytes = nel / m.byte_size ();
       for (int i = 0; i < nel; i++)
         switch (bytes)
           {
@@ -364,7 +369,7 @@
     }
 
   retval = H5Dwrite (data_hid, save_type_hid, H5S_ALL, H5S_ALL,
-                     H5P_DEFAULT, this->matrix.data()) >= 0;
+                     H5P_DEFAULT, this->matrix.data ()) >= 0;
 
   H5Dclose (data_hid);
   H5Sclose (space_hid);
@@ -381,7 +386,7 @@
   dim_vector dv;
   int empty = load_hdf5_empty (loc_id, name, dv);
   if (empty > 0)
-    this->matrix.resize(dv);
+    this->matrix.resize (dv);
   if (empty)
       return (empty > 0);
 
@@ -422,7 +427,7 @@
 
   T m (dv);
   if (H5Dread (data_hid, save_type_hid, H5S_ALL, H5S_ALL,
-               H5P_DEFAULT, m.fortran_vec()) >= 0)
+               H5P_DEFAULT, m.fortran_vec ()) >= 0)
     {
       retval = true;
       this->matrix = m;
@@ -501,7 +506,7 @@
 bool
 octave_base_int_scalar<T>::save_binary (std::ostream& os, bool&)
 {
-  os.write (reinterpret_cast<char *> (&(this->scalar)), this->byte_size());
+  os.write (reinterpret_cast<char *> (&(this->scalar)), this->byte_size ());
   return true;
 }
 
@@ -511,11 +516,11 @@
                                         oct_mach_info::float_format)
 {
   T tmp;
-  if (! is.read (reinterpret_cast<char *> (&tmp), this->byte_size()))
+  if (! is.read (reinterpret_cast<char *> (&tmp), this->byte_size ()))
     return false;
 
   if (swap)
-    switch (this->byte_size())
+    switch (this->byte_size ())
       {
       case 8:
         swap_bytes<8> (&tmp);
rename from src/ov-base-int.h
rename to libinterp/octave-value/ov-base-int.h
rename from src/ov-base-mat.cc
rename to libinterp/octave-value/ov-base-mat.cc
--- a/src/ov-base-mat.cc
+++ b/libinterp/octave-value/ov-base-mat.cc
@@ -475,7 +475,7 @@
       // Set up the pointer to the proper place.
       void *here = reinterpret_cast<void *> (&matrix(n));
       // Ask x to store there if it can.
-      return x.get_rep().fast_elem_insert_self (here, btyp);
+      return x.get_rep ().fast_elem_insert_self (here, btyp);
     }
   else
     return false;
rename from src/ov-base-mat.h
rename to libinterp/octave-value/ov-base-mat.h
--- a/src/ov-base-mat.h
+++ b/libinterp/octave-value/ov-base-mat.h
@@ -53,7 +53,7 @@
 
   octave_base_matrix (const MT& m, const MatrixType& t = MatrixType ())
     : octave_base_value (), matrix (m),
-      typ (t.is_known () ? new MatrixType(t) : 0), idx_cache ()
+      typ (t.is_known () ? new MatrixType (t) : 0), idx_cache ()
   {
     if (matrix.ndims () == 0)
       matrix.resize (dim_vector (0, 0));
@@ -123,6 +123,9 @@
   octave_value diag (octave_idx_type k = 0) const
     { return octave_value (matrix.diag (k)); }
 
+  octave_value diag (octave_idx_type m, octave_idx_type n) const
+    { return octave_value (matrix.diag (m, n)); }
+
   octave_value sort (octave_idx_type dim = 0, sortmode mode = ASCENDING) const
     { return octave_value (matrix.sort (dim, mode)); }
   octave_value sort (Array<octave_idx_type> &sidx, octave_idx_type dim = 0,
rename from src/ov-base-scalar.cc
rename to libinterp/octave-value/ov-base-scalar.cc
--- a/src/ov-base-scalar.cc
+++ b/libinterp/octave-value/ov-base-scalar.cc
@@ -121,6 +121,13 @@
 }
 
 template <class ST>
+octave_value
+octave_base_scalar<ST>::diag (octave_idx_type m, octave_idx_type n) const
+{
+  return Array<ST> (dim_vector (1, 1), scalar).diag (m, n);
+}
+
+template <class ST>
 bool
 octave_base_scalar<ST>::is_true (void) const
 {
@@ -162,6 +169,15 @@
 }
 
 template <class ST>
+std::string
+octave_base_scalar<ST>::short_disp (void) const
+{
+  std::ostringstream buf;
+  octave_print_internal (buf, scalar);
+  return buf.str ();
+}
+
+template <class ST>
 bool
 octave_base_scalar<ST>::fast_elem_insert_self (void *where, builtin_type_t btyp) const
 {
rename from src/ov-base-scalar.h
rename to libinterp/octave-value/ov-base-scalar.h
--- a/src/ov-base-scalar.h
+++ b/libinterp/octave-value/ov-base-scalar.h
@@ -98,6 +98,8 @@
 
   octave_value diag (octave_idx_type k = 0) const;
 
+  octave_value diag (octave_idx_type m, octave_idx_type n) const;
+
   octave_value sort (octave_idx_type, sortmode) const
     { return octave_value (scalar); }
   octave_value sort (Array<octave_idx_type> &sidx, octave_idx_type,
@@ -136,6 +138,8 @@
 
   bool print_name_tag (std::ostream& os, const std::string& name) const;
 
+  std::string short_disp (void) const;
+
   // Unsafe.  This function exists to support the MEX interface.
   // You should not use it anywhere else.
   void *mex_get_data (void) const { return const_cast<ST *> (&scalar); }
rename from src/ov-base-sparse.cc
rename to libinterp/octave-value/ov-base-sparse.cc
--- a/src/ov-base-sparse.cc
+++ b/libinterp/octave-value/ov-base-sparse.cc
@@ -370,13 +370,13 @@
           // at all the nonzero values and display them with the same
           // formatting rules that apply to columns of a matrix.
 
-          for (octave_idx_type i = matrix.cidx(j); i < matrix.cidx(j+1); i++)
+          for (octave_idx_type i = matrix.cidx (j); i < matrix.cidx (j+1); i++)
             {
               os << "\n";
-              os << "  (" << matrix.ridx(i)+1 <<
+              os << "  (" << matrix.ridx (i)+1 <<
                 ", "  << j+1 << ") -> ";
 
-              octave_print_internal (os, matrix.data(i), pr_as_read_syntax);
+              octave_print_internal (os, matrix.data (i), pr_as_read_syntax);
             }
         }
     }
rename from src/ov-base-sparse.h
rename to libinterp/octave-value/ov-base-sparse.h
rename from src/ov-base.cc
rename to libinterp/octave-value/ov-base.cc
--- a/src/ov-base.cc
+++ b/libinterp/octave-value/ov-base.cc
@@ -25,15 +25,15 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 
 #include "lo-ieee.h"
 #include "lo-mappers.h"
 
 #include "defun.h"
 #include "gripes.h"
+#include "mxarray.h"
 #include "oct-map.h"
 #include "oct-obj.h"
 #include "oct-lvalue.h"
@@ -449,7 +449,7 @@
   os << "no info for type: " << type_name () << "\n";
 }
 
-#define INT_CONV_METHOD(T, F, MIN_LIMIT, MAX_LIMIT) \
+#define INT_CONV_METHOD(T, F) \
   T \
   octave_base_value::F ## _value (bool require_int, bool frc_str_conv) const \
   { \
@@ -461,10 +461,10 @@
       { \
         if (require_int && D_NINT (d) != d) \
           error_with_cfn ("conversion of %g to " #T " value failed", d); \
-        else if (d < MIN_LIMIT) \
-          retval = MIN_LIMIT; \
-        else if (d > MAX_LIMIT) \
-          retval = MAX_LIMIT; \
+        else if (d < std::numeric_limits<T>::min ()) \
+          retval = std::numeric_limits<T>::min (); \
+        else if (d > std::numeric_limits<T>::max ()) \
+          retval = std::numeric_limits<T>::max (); \
         else \
           retval = static_cast<T> (::fix (d));  \
       } \
@@ -475,14 +475,17 @@
     return retval; \
   }
 
-INT_CONV_METHOD (short int, short, SHRT_MIN, SHRT_MAX)
-INT_CONV_METHOD (unsigned short int, ushort, 0, USHRT_MAX)
+INT_CONV_METHOD (short int, short)
+INT_CONV_METHOD (unsigned short int, ushort)
+
+INT_CONV_METHOD (int, int)
+INT_CONV_METHOD (unsigned int, uint)
 
-INT_CONV_METHOD (int, int, INT_MIN, INT_MAX)
-INT_CONV_METHOD (unsigned int, uint, 0, UINT_MAX)
+INT_CONV_METHOD (long int, long)
+INT_CONV_METHOD (unsigned long int, ulong)
 
-INT_CONV_METHOD (long int, long, LONG_MIN, LONG_MAX)
-INT_CONV_METHOD (unsigned long int, ulong, 0, ULONG_MAX)
+INT_CONV_METHOD (int64_t, int64)
+INT_CONV_METHOD (uint64_t, uint64)
 
 int
 octave_base_value::nint_value (bool frc_str_conv) const
@@ -1117,7 +1120,15 @@
 {
   gripe_wrong_type_arg ("octave_base_value::diag ()", type_name ());
 
-  return octave_value();
+  return octave_value ();
+}
+
+octave_value
+octave_base_value::diag (octave_idx_type, octave_idx_type) const
+{
+  gripe_wrong_type_arg ("octave_base_value::diag ()", type_name ());
+
+  return octave_value ();
 }
 
 octave_value
@@ -1125,7 +1136,7 @@
 {
   gripe_wrong_type_arg ("octave_base_value::sort ()", type_name ());
 
-  return octave_value();
+  return octave_value ();
 }
 
 octave_value
@@ -1134,7 +1145,7 @@
 {
   gripe_wrong_type_arg ("octave_base_value::sort ()", type_name ());
 
-  return octave_value();
+  return octave_value ();
 }
 
 sortmode
@@ -1183,7 +1194,11 @@
       "cosh",
       "erf",
       "erfinv",
+      "erfcinv",
       "erfc",
+      "erfcx",
+      "erfi",
+      "dawson",
       "exp",
       "expm1",
       "finite",
@@ -1220,6 +1235,7 @@
       "isspace",
       "isupper",
       "isxdigit",
+      "signbit",
       "toascii",
       "tolower",
       "toupper"
@@ -1538,11 +1554,11 @@
 @example\n\
 @group\n\
 s = speye (3);\n\
-sparse_auto_mutate (false)\n\
+sparse_auto_mutate (false);\n\
 s(:, 1) = 1;\n\
 typeinfo (s)\n\
 @result{} sparse matrix\n\
-sparse_auto_mutate (true)\n\
+sparse_auto_mutate (true);\n\
 s(1, :) = 1;\n\
 typeinfo (s)\n\
 @result{} matrix\n\
@@ -1558,14 +1574,13 @@
 }
 
 /*
-
 %!test
- s = speye(3);
- sparse_auto_mutate (false);
- s(:, 1) = 1;
- assert (typeinfo (s), "sparse matrix");
- sparse_auto_mutate (true);
- s(1, :) = 1;
- assert (typeinfo (s), "matrix");
-
+%! s = speye (3);
+%! sparse_auto_mutate (false);
+%! s(:, 1) = 1;
+%! assert (typeinfo (s), "sparse matrix");
+%! sparse_auto_mutate (true);
+%! s(1, :) = 1;
+%! assert (typeinfo (s), "matrix");
+%! sparse_auto_mutate (false);
 */
rename from src/ov-base.h
rename to libinterp/octave-value/ov-base.h
--- a/src/ov-base.h
+++ b/libinterp/octave-value/ov-base.h
@@ -32,7 +32,6 @@
 
 #include "Range.h"
 #include "data-conv.h"
-#include "mxarray.h"
 #include "mx-base.h"
 #include "str-vec.h"
 
@@ -40,6 +39,7 @@
 #include "oct-hdf5.h"
 
 class Cell;
+class mxArray;
 class octave_map;
 class octave_scalar_map;
 class octave_value;
@@ -341,8 +341,6 @@
 
   virtual bool is_real_matrix (void) const { return false; }
 
-  virtual bool is_real_nd_array (void) const { return false; }
-
   virtual bool is_complex_scalar (void) const { return false; }
 
   virtual bool is_complex_matrix (void) const { return false; }
@@ -367,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; }
@@ -461,6 +461,10 @@
 
   virtual unsigned long int ulong_value (bool = false, bool = false) const;
 
+  virtual int64_t int64_value (bool = false, bool = false) const;
+
+  virtual uint64_t uint64_value (bool = false, bool = false) const;
+
   virtual double double_value (bool = false) const;
 
   virtual float float_value (bool = false) const;
@@ -612,6 +616,8 @@
   print_with_name (std::ostream& output_buf, const std::string& name,
                    bool print_padding = true);
 
+  virtual std::string short_disp (void) const { return "..."; }
+
   virtual void print_info (std::ostream& os, const std::string& prefix) const;
 
   virtual bool save_ascii (std::ostream& os);
@@ -646,6 +652,8 @@
 
   virtual octave_value diag (octave_idx_type k = 0) const;
 
+  virtual octave_value diag (octave_idx_type m, octave_idx_type n) const;
+
   virtual octave_value sort (octave_idx_type dim = 0,
                              sortmode mode = ASCENDING) const;
   virtual octave_value sort (Array<octave_idx_type> &sidx,
@@ -686,8 +694,11 @@
       umap_cosh,
       umap_erf,
       umap_erfinv,
+      umap_erfcinv,
       umap_erfc,
       umap_erfcx,
+      umap_erfi,
+      umap_dawson,
       umap_exp,
       umap_expm1,
       umap_finite,
@@ -724,6 +735,7 @@
       umap_xisspace,
       umap_xisupper,
       umap_xisxdigit,
+      umap_xsignbit,
       umap_xtoascii,
       umap_xtolower,
       umap_xtoupper,
@@ -753,6 +765,21 @@
   virtual bool
   fast_elem_insert_self (void *where, builtin_type_t btyp) const;
 
+  // Grab the reference count. For use by jit.
+  void
+  grab (void)
+  {
+    ++count;
+  }
+
+  // Release the reference count. For use by jit.
+  void
+  release (void)
+  {
+    if (--count == 0)
+      delete this;
+  }
+
 protected:
 
   // This should only be called for derived types.
@@ -785,9 +812,9 @@
   // (think of an empty cell array with >2G elements).
   octave_refcount<octave_idx_type> count;
 
-private:
+  static const char *get_umap_name (unary_mapper_t);
 
-  static const char *get_umap_name (unary_mapper_t);
+private:
 
   static int curr_print_indent_level;
   static bool beginning_of_line;
rename from src/ov-bool-mat.cc
rename to libinterp/octave-value/ov-bool-mat.cc
--- a/src/ov-bool-mat.cc
+++ b/libinterp/octave-value/ov-bool-mat.cc
@@ -34,6 +34,7 @@
 
 #include "defun.h"
 #include "gripes.h"
+#include "mxarray.h"
 #include "oct-obj.h"
 #include "ops.h"
 #include "ov-base.h"
@@ -97,7 +98,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "bool matrix", "real scalar");
 
       retval = matrix (0, 0);
@@ -115,7 +116,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "bool matrix", "real scalar");
 
       retval = matrix (0, 0);
@@ -135,7 +136,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "bool matrix", "complex scalar");
 
       retval = matrix (0, 0);
@@ -155,7 +156,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "bool matrix", "complex scalar");
 
       retval = matrix (0, 0);
@@ -329,11 +330,11 @@
 {
 
   dim_vector d = dims ();
-  if (d.length() < 1)
+  if (d.length () < 1)
     return false;
 
   // Use negative value for ndims to differentiate with old format!!
-  int32_t tmp = - d.length();
+  int32_t tmp = - d.length ();
   os.write (reinterpret_cast<char *> (&tmp), 4);
   for (int i = 0; i < d.length (); i++)
     {
@@ -469,7 +470,7 @@
   dim_vector dv;
   int empty = load_hdf5_empty (loc_id, name, dv);
   if (empty > 0)
-    matrix.resize(dv);
+    matrix.resize (dv);
   if (empty)
     return (empty > 0);
 
@@ -577,11 +578,10 @@
 }
 
 /*
-%!shared m, s, c
+%!test
 %! m = eye (2) != 0;
 %! s = !0;
 %! c = {"double", "single", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", "logical"};
-%!test
 %! for i = 1:numel (c)
 %!   assert (logical (eye (2, c{i})), m)
 %!   assert (logical (eye (1, c{i})), s)
rename from src/ov-bool-mat.h
rename to libinterp/octave-value/ov-bool-mat.h
rename from src/ov-bool-sparse.cc
rename to libinterp/octave-value/ov-bool-sparse.cc
--- a/src/ov-bool-sparse.cc
+++ b/libinterp/octave-value/ov-bool-sparse.cc
@@ -25,11 +25,13 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 #include <vector>
 
+#include "dim-vector.h"
+
+#include "mxarray.h"
 #include "ov-base.h"
 #include "ov-scalar.h"
 #include "ov-bool.h"
@@ -100,7 +102,7 @@
   if (numel () > 0)
     {
       if (numel () > 1)
-        gripe_implicit_conversion ("Octave:array-as-scalar",
+        gripe_implicit_conversion ("Octave:array-to-scalar",
                                    "bool sparse matrix", "real scalar");
 
       retval = matrix (0, 0);
@@ -121,7 +123,7 @@
   if (rows () > 0 && columns () > 0)
     {
       if (numel () > 1)
-        gripe_implicit_conversion ("Octave:array-as-scalar",
+        gripe_implicit_conversion ("Octave:array-to-scalar",
                                    "bool sparse matrix", "complex scalar");
 
       retval = matrix (0, 0);
@@ -163,7 +165,7 @@
 NDArray
 octave_sparse_bool_matrix::array_value (bool) const
 {
-  return NDArray (Matrix(matrix.matrix_value ()));
+  return NDArray (Matrix (matrix.matrix_value ()));
 }
 
 charNDArray
@@ -174,8 +176,8 @@
   octave_idx_type nr = matrix.rows ();
 
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = matrix.cidx(j); i < matrix.cidx(j+1); i++)
-      retval(matrix.ridx(i) + nr * j) = static_cast<char>(matrix.data (i));
+    for (octave_idx_type i = matrix.cidx (j); i < matrix.cidx (j+1); i++)
+      retval(matrix.ridx (i) + nr * j) = static_cast<char>(matrix.data (i));
 
   return retval;
 }
@@ -209,7 +211,7 @@
 octave_sparse_bool_matrix::save_binary (std::ostream& os, bool&)
 {
   dim_vector d = this->dims ();
-  if (d.length() < 1)
+  if (d.length () < 1)
     return false;
 
   // Ensure that additional memory is deallocated
@@ -238,14 +240,14 @@
   for (int i = 0; i < nc+1; i++)
     {
       octave_quit ();
-      itmp = matrix.cidx(i);
+      itmp = matrix.cidx (i);
       os.write (reinterpret_cast<char *> (&itmp), 4);
     }
 
   for (int i = 0; i < nz; i++)
     {
       octave_quit ();
-      itmp = matrix.ridx(i);
+      itmp = matrix.ridx (i);
       os.write (reinterpret_cast<char *> (&itmp), 4);
     }
 
@@ -300,7 +302,7 @@
         return false;
       if (swap)
         swap_bytes<4> (&tmp);
-      m.cidx(i) = tmp;
+      m.cidx (i) = tmp;
     }
 
   for (int i = 0; i < nz; i++)
@@ -310,7 +312,7 @@
         return false;
       if (swap)
         swap_bytes<4> (&tmp);
-      m.ridx(i) = tmp;
+      m.ridx (i) = tmp;
     }
 
   if (error_state || ! is)
@@ -440,7 +442,7 @@
 
   H5Sclose (space_hid);
 
-  hdims[0] = m.cols() + 1;
+  hdims[0] = m.cols () + 1;
   hdims[1] = 1;
 
   space_hid = H5Screate_simple (2, hdims, 0);
@@ -551,7 +553,7 @@
   dim_vector dv;
   int empty = load_hdf5_empty (loc_id, name, dv);
   if (empty > 0)
-    matrix.resize(dv);
+    matrix.resize (dv);
   if (empty)
     return (empty > 0);
 
@@ -782,12 +784,12 @@
 
   for (mwIndex i = 0; i < nz; i++)
     {
-      pr[i] = matrix.data(i);
-      ir[i] = matrix.ridx(i);
+      pr[i] = matrix.data (i);
+      ir[i] = matrix.ridx (i);
     }
 
   for (mwIndex i = 0; i < columns () + 1; i++)
-    jc[i] = matrix.cidx(i);
+    jc[i] = matrix.cidx (i);
 
   return retval;
 }
rename from src/ov-bool-sparse.h
rename to libinterp/octave-value/ov-bool-sparse.h
rename from src/ov-bool.cc
rename to libinterp/octave-value/ov-bool.cc
--- a/src/ov-bool.cc
+++ b/libinterp/octave-value/ov-bool.cc
@@ -29,6 +29,7 @@
 #include "mx-base.h"
 
 #include "gripes.h"
+#include "mxarray.h"
 #include "oct-obj.h"
 #include "ops.h"
 #include "ov-bool.h"
@@ -89,14 +90,14 @@
   if (fill)
     {
       boolNDArray retval (dv, false);
-      if (dv.numel())
+      if (dv.numel ())
         retval(0) = scalar;
       return retval;
     }
   else
     {
       boolNDArray retval (dv);
-      if (dv.numel())
+      if (dv.numel ())
         retval(0) = scalar;
       return retval;
     }
rename from src/ov-bool.h
rename to libinterp/octave-value/ov-bool.h
rename from src/ov-builtin.cc
rename to libinterp/octave-value/ov-builtin.cc
--- a/src/ov-builtin.cc
+++ b/libinterp/octave-value/ov-builtin.cc
@@ -152,5 +152,22 @@
   return retval;
 }
 
+jit_type *
+octave_builtin::to_jit (void) const
+{
+  return jtype;
+}
+
+void
+octave_builtin::stash_jit (jit_type &type)
+{
+  jtype = &type;
+}
+
+octave_builtin::fcn
+octave_builtin::function (void) const
+{
+  return f;
+}
 
 const std::list<octave_lvalue> *octave_builtin::curr_lvalue_list = 0;
rename from src/ov-builtin.h
rename to libinterp/octave-value/ov-builtin.h
--- a/src/ov-builtin.h
+++ b/libinterp/octave-value/ov-builtin.h
@@ -30,6 +30,7 @@
 
 class octave_value;
 class octave_value_list;
+class jit_type;
 
 // Builtin functions.
 
@@ -39,16 +40,22 @@
 {
 public:
 
-  octave_builtin (void) : octave_function (), f (0) { }
+  octave_builtin (void) : octave_function (), f (0), file (), jtype (0) { }
 
   typedef octave_value_list (*fcn) (const octave_value_list&, int);
 
   octave_builtin (fcn ff, const std::string& nm = std::string (),
                   const std::string& ds = std::string ())
-    : octave_function (nm, ds), f (ff) { }
+    : octave_function (nm, ds), f (ff), file (), jtype (0) { }
+
+  octave_builtin (fcn ff, const std::string& nm, const std::string& fnm,
+                  const std::string& ds)
+    : octave_function (nm, ds), f (ff), file (fnm), jtype (0) { }
 
   ~octave_builtin (void) { }
 
+  std::string src_file_name (void) const { return file; }
+
   octave_value subsref (const std::string& type,
                         const std::list<octave_value_list>& idx)
     {
@@ -75,6 +82,12 @@
   do_multi_index_op (int nargout, const octave_value_list& args,
                      const std::list<octave_lvalue>* lvalue_list);
 
+  jit_type *to_jit (void) const;
+
+  void stash_jit (jit_type& type);
+
+  fcn function (void) const;
+
   static const std::list<octave_lvalue> *curr_lvalue_list;
 
 protected:
@@ -82,6 +95,12 @@
   // A pointer to the actual function.
   fcn f;
 
+  // The name of the file where this function was defined.
+  std::string file;
+
+  // A pointer to the jit type that represents the function.
+  jit_type *jtype;
+
 private:
 
   // No copying!
rename from src/ov-cell.cc
rename to libinterp/octave-value/ov-cell.cc
--- a/src/ov-cell.cc
+++ b/libinterp/octave-value/ov-cell.cc
@@ -39,6 +39,7 @@
 
 #include "defun.h"
 #include "error.h"
+#include "mxarray.h"
 #include "ov-cell.h"
 #include "oct-obj.h"
 #include "unwind-prot.h"
@@ -135,7 +136,8 @@
 octave_value_list
 octave_cell::subsref (const std::string& type,
                       const std::list<octave_value_list>& idx,
-                      int nargout)
+                      int nargout,
+                      const std::list<octave_lvalue> *lvalue_list)
 {
   octave_value_list retval;
 
@@ -177,7 +179,9 @@
   // octave_user_function::subsref.
 
   if (idx.size () > 1)
-    retval = retval(0).next_subsref (nargout, type, idx);
+    retval = (lvalue_list
+              ? retval(0).next_subsref (nargout, type, idx, lvalue_list)
+              : retval(0).next_subsref (nargout, type, idx));
 
   return retval;
 }
@@ -944,7 +948,7 @@
     return false;
 
   // Use negative value for ndims
-  int32_t di = - d.length();
+  int32_t di = - d.length ();
   os.write (reinterpret_cast<char *> (&di), 4);
   for (int i = 0; i < d.length (); i++)
     {
@@ -1155,7 +1159,7 @@
   dim_vector dv;
   int empty = load_hdf5_empty (loc_id, name, dv);
   if (empty > 0)
-    matrix.resize(dv);
+    matrix.resize (dv);
   if (empty)
     return (empty > 0);
 
@@ -1395,24 +1399,24 @@
 \n\
 @example\n\
 @group\n\
-  s = struct('name', @{'Peter', 'Hannah', 'Robert'@},\n\
-             'age', @{23, 16, 3@});\n\
-  c = struct2cell(s)\n\
-     @result{} c = @{1x1x3 Cell Array@}\n\
-  c(1,1,:)(:)\n\
-     @result{} ans =\n\
-        @{\n\
-          [1,1] = Peter\n\
-          [2,1] = Hannah\n\
-          [3,1] = Robert\n\
-        @}\n\
-  c(2,1,:)(:)\n\
-     @result{} ans =\n\
-        @{\n\
-          [1,1] = 23\n\
-          [2,1] = 16\n\
-          [3,1] = 3\n\
-        @}\n\
+s = struct (\"name\", @{\"Peter\", \"Hannah\", \"Robert\"@},\n\
+           \"age\", @{23, 16, 3@});\n\
+c = struct2cell (s)\n\
+   @result{} c = @{2x1x3 Cell Array@}\n\
+c(1,1,:)(:)\n\
+   @result{}\n\
+      @{\n\
+        [1,1] = Peter\n\
+        [2,1] = Hannah\n\
+        [3,1] = Robert\n\
+      @}\n\
+c(2,1,:)(:)\n\
+   @result{}\n\
+      @{\n\
+        [1,1] = 23\n\
+        [2,1] = 16\n\
+        [3,1] = 3\n\
+      @}\n\
 @end group\n\
 @end example\n\
 \n\
@@ -1471,14 +1475,14 @@
 
 /*
 %!test
-%!  keys = cellstr (char (floor (rand (11,10)*24+65)))';
-%!  vals = cellfun(@(x) mat2cell(rand (19,1), ones (19,1), 1), ...
-%!           mat2cell([1:11]', ones(11,1), 1), "uniformoutput", false)';
-%!  s = struct ([keys; vals]{:});
-%!  t = cell2struct ([vals{:}], keys, 2);
-%!  assert (s, t);
-%!  assert (struct2cell (s), [vals{:}]');
-%!  assert (fieldnames (s), keys');
+%! keys = cellstr (char (floor (rand (11,10)*24+65)))';
+%! vals = cellfun (@(x) mat2cell (rand (19,1), ones (19,1), 1), ...
+%!          mat2cell ([1:11]', ones (11,1), 1), "uniformoutput", false)';
+%! s = struct ([keys; vals]{:});
+%! t = cell2struct ([vals{:}], keys, 2);
+%! assert (s, t);
+%! assert (struct2cell (s), [vals{:}]');
+%! assert (fieldnames (s), keys');
 */
 
 mxArray *
rename from src/ov-cell.h
rename to libinterp/octave-value/ov-cell.h
--- a/src/ov-cell.h
+++ b/libinterp/octave-value/ov-cell.h
@@ -79,7 +79,16 @@
     }
 
   octave_value_list subsref (const std::string& type,
-                             const std::list<octave_value_list>& idx, int);
+                             const std::list<octave_value_list>& idx,
+                             int nargout)
+  {
+    return subsref (type, idx, nargout, 0);
+  }
+
+  octave_value_list subsref (const std::string& type,
+                             const std::list<octave_value_list>& idx,
+                             int nargout,
+                             const std::list<octave_lvalue> *lvalue_list);
 
   octave_value subsref (const std::string& type,
                         const std::list<octave_value_list>& idx,
rename from src/ov-ch-mat.cc
rename to libinterp/octave-value/ov-ch-mat.cc
--- a/src/ov-ch-mat.cc
+++ b/libinterp/octave-value/ov-ch-mat.cc
@@ -31,6 +31,7 @@
 #include "lo-ieee.h"
 #include "mx-base.h"
 
+#include "mxarray.h"
 #include "ov-base.h"
 #include "ov-base-mat.h"
 #include "ov-base-mat.cc"
@@ -57,7 +58,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "character matrix", "real scalar");
 
       retval = static_cast<unsigned char> (matrix (0, 0));
@@ -75,7 +76,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "character matrix", "real scalar");
 
       retval = static_cast<unsigned char> (matrix (0, 0));
@@ -95,7 +96,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "character matrix", "complex scalar");
 
       retval = static_cast<unsigned char> (matrix (0, 0));
@@ -115,7 +116,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "character matrix", "complex scalar");
 
       retval = static_cast<unsigned char> (matrix (0, 0));
@@ -151,21 +152,34 @@
   return retval;
 }
 
-// The C++ standard guarantees cctype defines functions, not macros (and hence macros *CAN'T*
-// be defined if only cctype is included)
-// so there's no need to f*ck around. The exceptions are isascii and toascii,
-// which are not C++.
-// Oddly enough, all those character functions are int (*) (int), even
-// in C++. Wicked!
+// The C++ standard guarantees cctype defines functions, not macros (and
+// hence macros *CAN'T* be defined if only cctype is included) so
+// there's no need to fuck around.  The exceptions are isascii and
+// toascii, which are not C++.  Oddly enough, all those character
+// functions are int (*) (int), even in C++.  Wicked!
 static inline int xisascii (int c)
-{ return isascii (c); }
+{
+#ifdef HAVE_ISASCII
+  return isascii (c);
+#else
+  return (c >= 0x00 && c <= 0x7f);
+#endif
+}
 
 static inline int xtoascii (int c)
-{ return toascii (c); }
+{
+#ifdef HAVE_TOASCII
+  return toascii (c);
+#else
+  return (c & 0x7F);
+#endif
+}
 
 octave_value
 octave_char_matrix::map (unary_mapper_t umap) const
 {
+  octave_value retval;
+
   switch (umap)
     {
 #define STRING_MAPPER(UMAP,FCN,TYPE) \
@@ -188,10 +202,26 @@
     STRING_MAPPER (xtolower, std::tolower, char);
     STRING_MAPPER (xtoupper, std::toupper, char);
 
-    default:
+    // For Matlab compatibility, these should work on ASCII values
+    // without error or warning.
+    case umap_abs:
+    case umap_ceil:
+    case umap_fix:
+    case umap_floor:
+    case umap_imag:
+    case umap_isinf:
+    case umap_isnan:
+    case umap_real:
+    case umap_round:
       {
         octave_matrix m (array_value (true));
         return m.map (umap);
       }
+
+    default:
+      error ("%s: expecting numeric argument", get_umap_name (umap));
+      break;
     }
+
+  return retval;
 }
rename from src/ov-ch-mat.h
rename to libinterp/octave-value/ov-ch-mat.h
rename from src/ov-class.cc
rename to libinterp/octave-value/ov-class.cc
--- a/src/ov-class.cc
+++ b/libinterp/octave-value/ov-class.cc
@@ -42,8 +42,12 @@
 #include "ls-oct-ascii.h"
 #include "ls-oct-binary.h"
 #include "ls-utils.h"
+#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"
@@ -142,7 +146,7 @@
                         = parent.parent_class_name_list ();
 
                       for (octave_idx_type i = 0; i < p_nel; i++)
-                        c(i) = octave_value (pmap.index(i), pcnm, plist);
+                        c(i) = octave_value (pmap.index (i), pcnm, plist);
 
                       map.assign (pcnm, c);
                     }
@@ -187,7 +191,7 @@
                         = parent.parent_class_name_list ();
 
                       for (octave_idx_type i = 0; i < p_nel; i++)
-                        c(i) = octave_value (pmap.index(i), pcnm, plist);
+                        c(i) = octave_value (pmap.index (i), pcnm, plist);
 
                       map.assign (pcnm, c);
                     }
@@ -521,7 +525,7 @@
 
         case '.':
           {
-            if (map.numel() > 0)
+            if (map.numel () > 0)
               {
                 Cell t = dotref (idx.front ());
 
@@ -705,7 +709,7 @@
 
           if (tmp.length () > 1)
             error ("expecting single return value from @%s/subsasgn",
-                   class_name().c_str ());
+                   class_name ().c_str ());
 
           else
             retval = tmp(0);
@@ -914,7 +918,7 @@
                   {
                     if (t_rhs.is_empty ())
                       {
-                        map.delete_elements (idx.front());
+                        map.delete_elements (idx.front ());
 
                         if (! error_state)
                           {
@@ -999,7 +1003,7 @@
 
       if (!error_state && tmp.length () >= 1)
         {
-          if (tmp(0).is_object())
+          if (tmp(0).is_object ())
             error ("subsindex function must return a valid index vector");
           else
             // Index vector returned by subsindex is zero based
@@ -1012,7 +1016,7 @@
     }
   else
     error ("no subsindex method defined for class %s",
-           class_name().c_str ());
+           class_name ().c_str ());
 
   return retval;
 }
@@ -1136,7 +1140,7 @@
         }
     }
   else
-    error ("no char method defined for class %s", class_name().c_str ());
+    error ("no char method defined for class %s", class_name ().c_str ());
 
   return retval;
 }
@@ -1274,10 +1278,10 @@
     {
       std::string  key = map.key (p);
       Cell         val = map.contents (p);
-      if ( val(0).is_object() )
+      if ( val(0).is_object () )
         {
           dbgstr = "blork";
-          if( key == val(0).class_name() )
+          if ( key == val(0).class_name () )
             {
               might_have_inheritance = true;
               dbgstr = "cork";
@@ -1444,7 +1448,7 @@
 bool
 octave_class::save_binary (std::ostream& os, bool& save_as_floats)
 {
-  int32_t classname_len = class_name().length ();
+  int32_t classname_len = class_name ().length ();
 
   os.write (reinterpret_cast<char *> (&classname_len), 4);
   os << class_name ();
@@ -1462,7 +1466,7 @@
   else
     m = map_value ();
 
-  int32_t len = m.nfields();
+  int32_t len = m.nfields ();
   os.write (reinterpret_cast<char *> (&len), 4);
 
   octave_map::iterator i = m.begin ();
@@ -1920,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;
@@ -1936,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 ();
@@ -1995,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\
@@ -2102,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;
 }
@@ -2186,42 +2191,34 @@
   octave_value retval;
 
   octave_function *fcn = octave_call_stack::caller ();
-
-  if (fcn && fcn->is_class_constructor ())
+  if ((! fcn) || (! fcn->is_class_constructor ()))
     {
-      for (int i = 0; i < args.length(); i++)
-        {
-          std::string class_name = args(i).string_value ();
-
-          if (! error_state)
-            {
-              if (! is_built_in_class (class_name))
-                {
-                  std::string this_class_name = fcn->name ();
+      error ("superiorto: invalid call from outside class constructor");
+      return retval;
+    }
 
-                  if (! symbol_table::set_class_relationship (this_class_name,
-                                                              class_name))
-                    {
-                      error ("superiorto: precedence already set for %s and %s",
-                             this_class_name.c_str (), class_name.c_str ());
-                      break;
-                    }
-                }
-              else
-                {
-                  // User defined classes always have higher precedence
-                  // than built-in classes.
-                }
-            }
-          else
-            {
+  for (int i = 0; i < args.length (); i++)
+    {
+      std::string inf_class = args(i).string_value ();
+      if (error_state)
+        {
               error ("superiorto: expecting argument to be class name");
               break;
-            }
+        }
+
+      // User defined classes always have higher precedence
+      // than built-in classes
+      if (is_built_in_class (inf_class))
+        break;
+
+      std::string sup_class = fcn->name ();
+      if (! symbol_table::set_class_relationship (sup_class, inf_class))
+        {
+          error ("superiorto: opposite precedence already set for %s and %s",
+                 sup_class.c_str (), inf_class.c_str ());
+          break;
         }
     }
-  else
-    error ("superiorto: invalid call from outside class constructor");
 
   return retval;
 }
@@ -2238,45 +2235,36 @@
   octave_value retval;
 
   octave_function *fcn = octave_call_stack::caller ();
-
-  if (fcn && fcn->is_class_constructor ())
+  if ((! fcn) || (! fcn->is_class_constructor ()))
     {
-      for (int i = 0; i < args.length(); i++)
-        {
-          std::string class_name = args(i).string_value ();
-
-          if (! error_state)
-            {
-              if (! is_built_in_class (class_name))
-                {
-                  std::string this_class_name = fcn->name ();
-
-                  symbol_table::set_class_relationship (class_name,
-                                                        this_class_name);
+      error ("inferiorto: invalid call from outside class constructor");
+      return retval;
+    }
 
-                  if (! symbol_table::set_class_relationship (this_class_name,
-                                                              class_name))
-                    {
-                      error ("inferiorto: precedence already set for %s and %s",
-                             this_class_name.c_str (), class_name.c_str ());
-                      break;
-                    }
-                }
-              else
-                {
-                  error ("inferiorto: cannot give user-defined class lower precedence than built-in class");
-                  break;
-                }
-            }
-          else
-            {
-              error ("inferiorto: expecting argument to be class name");
-              break;
-            }
+  for (int i = 0; i < args.length (); i++)
+    {
+      std::string sup_class = args(i).string_value ();
+      if (error_state)
+        {
+          error ("inferiorto: expecting argument to be class name");
+          break;
+        }
+
+      if (is_built_in_class (sup_class))
+        {
+          error ("inferiorto: cannot give user-defined class lower "
+                 "precedence than built-in class");
+          break;
+        }
+
+      std::string inf_class = fcn->name ();
+      if (! symbol_table::set_class_relationship (sup_class, inf_class))
+        {
+          error ("inferiorto: opposite precedence already set for %s and %s",
+                 inf_class.c_str (), sup_class.c_str ());
+          break;
         }
     }
-  else
-    error ("inferiorto: invalid call from outside class constructor");
 
   return retval;
 }
rename from src/ov-class.h
rename to libinterp/octave-value/ov-class.h
--- a/src/ov-class.h
+++ b/libinterp/octave-value/ov-class.h
@@ -136,7 +136,7 @@
   octave_value reshape (const dim_vector& new_dims) const
     {
       octave_class retval = octave_class (*this);
-      retval.map = retval.map_value().reshape (new_dims);
+      retval.map = retval.map_value ().reshape (new_dims);
       return octave_value (new octave_class (retval));
     }
 
rename from src/ov-colon.cc
rename to libinterp/octave-value/ov-colon.cc
rename from src/ov-colon.h
rename to libinterp/octave-value/ov-colon.h
rename from src/ov-complex.cc
rename to libinterp/octave-value/ov-complex.cc
--- a/src/ov-complex.cc
+++ b/libinterp/octave-value/ov-complex.cc
@@ -30,6 +30,7 @@
 #include "lo-specfun.h"
 #include "lo-mappers.h"
 
+#include "mxarray.h"
 #include "oct-obj.h"
 #include "oct-stream.h"
 #include "ops.h"
@@ -65,8 +66,8 @@
 octave_base_value::type_conv_info
 octave_complex::numeric_demotion_function (void) const
 {
-  return octave_base_value::type_conv_info(default_numeric_demotion_function,
-                                           octave_float_complex::static_type_id ());
+  return octave_base_value::type_conv_info (default_numeric_demotion_function,
+                                            octave_float_complex::static_type_id ());
 }
 
 octave_base_value *
@@ -225,7 +226,7 @@
 {
   if (fill)
     {
-      ComplexNDArray retval (dv, ComplexNDArray::resize_fill_value ());
+      ComplexNDArray retval (dv, Complex (0));
 
       if (dv.numel ())
         retval(0) = scalar;
@@ -243,6 +244,12 @@
     }
 }
 
+octave_value
+octave_complex::diag (octave_idx_type m, octave_idx_type n) const
+{
+  return ComplexDiagMatrix (Array<Complex> (dim_vector (1, 1), scalar), m, n);
+}
+
 bool
 octave_complex::save_ascii (std::ostream& os)
 {
@@ -424,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);
rename from src/ov-complex.h
rename to libinterp/octave-value/ov-complex.h
--- a/src/ov-complex.h
+++ b/libinterp/octave-value/ov-complex.h
@@ -163,6 +163,8 @@
     return boolNDArray (dim_vector (1, 1), scalar != 0.0);
   }
 
+  octave_value diag (octave_idx_type m, octave_idx_type n) const;
+
   void increment (void) { scalar += 1.0; }
 
   void decrement (void) { scalar -= 1.0; }
rename from src/ov-cs-list.cc
rename to libinterp/octave-value/ov-cs-list.cc
rename from src/ov-cs-list.h
rename to libinterp/octave-value/ov-cs-list.h
rename from src/ov-cx-diag.cc
rename to libinterp/octave-value/ov-cx-diag.cc
--- a/src/ov-cx-diag.cc
+++ b/libinterp/octave-value/ov-cx-diag.cc
@@ -149,7 +149,7 @@
       return ::imag (matrix);
     case umap_sqrt:
       {
-        ComplexColumnVector tmp = matrix.diag ().map<Complex> (std::sqrt);
+        ComplexColumnVector tmp = matrix.extract_diag ().map<Complex> (std::sqrt);
         ComplexDiagMatrix retval (tmp);
         retval.resize (matrix.rows (), matrix.columns ());
         return retval;
@@ -167,7 +167,7 @@
   os.write (reinterpret_cast<char *> (&r), 4);
   os.write (reinterpret_cast<char *> (&c), 4);
 
-  ComplexMatrix m = ComplexMatrix (matrix.diag ());
+  ComplexMatrix m = ComplexMatrix (matrix.extract_diag ());
   save_type st = LS_DOUBLE;
   if (save_as_floats)
     {
rename from src/ov-cx-diag.h
rename to libinterp/octave-value/ov-cx-diag.h
rename from src/ov-cx-mat.cc
rename to libinterp/octave-value/ov-cx-mat.cc
--- a/src/ov-cx-mat.cc
+++ b/libinterp/octave-value/ov-cx-mat.cc
@@ -37,6 +37,7 @@
 #include "oct-locbuf.h"
 
 #include "gripes.h"
+#include "mxarray.h"
 #include "oct-obj.h"
 #include "oct-stream.h"
 #include "ops.h"
@@ -73,8 +74,8 @@
 octave_base_value::type_conv_info
 octave_complex_matrix::numeric_demotion_function (void) const
 {
-  return octave_base_value::type_conv_info(default_numeric_demotion_function,
-                                           octave_float_complex_matrix::static_type_id ());
+  return octave_base_value::type_conv_info (default_numeric_demotion_function,
+                                            octave_float_complex_matrix::static_type_id ());
 }
 
 octave_base_value *
@@ -108,7 +109,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "complex matrix", "real scalar");
 
       retval = std::real (matrix (0, 0));
@@ -130,7 +131,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "complex matrix", "real scalar");
 
       retval = std::real (matrix (0, 0));
@@ -178,7 +179,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "complex matrix", "complex scalar");
 
       retval = matrix (0, 0);
@@ -198,7 +199,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "complex matrix", "complex scalar");
 
       retval = matrix (0, 0);
@@ -292,6 +293,24 @@
   return retval;
 }
 
+octave_value
+octave_complex_matrix::diag (octave_idx_type m, octave_idx_type n) const
+{
+  octave_value retval;
+
+  if (matrix.ndims () == 2
+      && (matrix.rows () == 1 || matrix.columns () == 1))
+    {
+      ComplexMatrix mat = matrix.matrix_value ();
+
+      retval = mat.diag (m, n);
+    }
+  else
+    error ("diag: expecting vector argument");
+
+  return retval;
+}
+
 bool
 octave_complex_matrix::save_ascii (std::ostream& os)
 {
@@ -419,11 +438,11 @@
 octave_complex_matrix::save_binary (std::ostream& os, bool& save_as_floats)
 {
   dim_vector d = dims ();
-  if (d.length() < 1)
+  if (d.length () < 1)
     return false;
 
   // Use negative value for ndims to differentiate with old format!!
-  int32_t tmp = - d.length();
+  int32_t tmp = - d.length ();
   os.write (reinterpret_cast<char *> (&tmp), 4);
   for (int i = 0; i < d.length (); i++)
     {
@@ -626,7 +645,7 @@
   dim_vector dv;
   int empty = load_hdf5_empty (loc_id, name, dv);
   if (empty > 0)
-    matrix.resize(dv);
+    matrix.resize (dv);
   if (empty)
       return (empty > 0);
 
@@ -758,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);
rename from src/ov-cx-mat.h
rename to libinterp/octave-value/ov-cx-mat.h
--- a/src/ov-cx-mat.h
+++ b/libinterp/octave-value/ov-cx-mat.h
@@ -135,6 +135,8 @@
 
   octave_value diag (octave_idx_type k = 0) const;
 
+  octave_value diag (octave_idx_type m, octave_idx_type n) const;
+
   void increment (void) { matrix += Complex (1.0); }
 
   void decrement (void) { matrix -= Complex (1.0); }
rename from src/ov-cx-sparse.cc
rename to libinterp/octave-value/ov-cx-sparse.cc
--- a/src/ov-cx-sparse.cc
+++ b/libinterp/octave-value/ov-cx-sparse.cc
@@ -25,15 +25,15 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 #include <vector>
 
 #include "lo-specfun.h"
 #include "lo-mappers.h"
 #include "oct-locbuf.h"
 
+#include "mxarray.h"
 #include "ov-base.h"
 #include "ov-scalar.h"
 #include "ov-complex.h"
@@ -114,7 +114,7 @@
   if (numel () > 0)
     {
       if (numel () > 1)
-        gripe_implicit_conversion ("Octave:array-as-scalar",
+        gripe_implicit_conversion ("Octave:array-to-scalar",
                                    "complex sparse matrix", "real scalar");
 
       retval = std::real (matrix (0, 0));
@@ -150,7 +150,7 @@
   if (numel () > 0)
     {
       if (numel () > 1)
-        gripe_implicit_conversion ("Octave:array-as-scalar",
+        gripe_implicit_conversion ("Octave:array-to-scalar",
                                    "complex sparse matrix", "real scalar");
 
       retval = matrix (0, 0);
@@ -188,8 +188,8 @@
       octave_idx_type nr = matrix.rows ();
 
       for (octave_idx_type j = 0; j < nc; j++)
-        for (octave_idx_type i = matrix.cidx(j); i < matrix.cidx(j+1); i++)
-          retval(matrix.ridx(i) + nr * j) =
+        for (octave_idx_type i = matrix.cidx (j); i < matrix.cidx (j+1); i++)
+          retval(matrix.ridx (i) + nr * j) =
             static_cast<char>(std::real (matrix.data (i)));
     }
 
@@ -228,7 +228,7 @@
                                            bool&save_as_floats)
 {
   dim_vector d = this->dims ();
-  if (d.length() < 1)
+  if (d.length () < 1)
     return false;
 
   // Ensure that additional memory is deallocated
@@ -275,18 +275,18 @@
    for (int i = 0; i < nc+1; i++)
      {
        octave_quit ();
-       itmp = matrix.cidx(i);
+       itmp = matrix.cidx (i);
        os.write (reinterpret_cast<char *> (&itmp), 4);
      }
 
    for (int i = 0; i < nz; i++)
      {
        octave_quit ();
-       itmp = matrix.ridx(i);
+       itmp = matrix.ridx (i);
        os.write (reinterpret_cast<char *> (&itmp), 4);
      }
 
-   write_doubles (os, reinterpret_cast<const double *> (matrix.data()), st, 2 * nz);
+   write_doubles (os, reinterpret_cast<const double *> (matrix.data ()), st, 2 * nz);
 
   return true;
 }
@@ -334,7 +334,7 @@
         return false;
       if (swap)
         swap_bytes<4> (&tmp);
-      m.cidx(i) = tmp;
+      m.cidx (i) = tmp;
     }
 
   for (int i = 0; i < nz; i++)
@@ -344,7 +344,7 @@
         return false;
       if (swap)
         swap_bytes<4> (&tmp);
-      m.ridx(i) = tmp;
+      m.ridx (i) = tmp;
     }
 
   if (! is.read (reinterpret_cast<char *> (&ctmp), 1))
@@ -476,7 +476,7 @@
 
   H5Sclose (space_hid);
 
-  hdims[0] = m.cols() + 1;
+  hdims[0] = m.cols () + 1;
   hdims[1] = 1;
 
   space_hid = H5Screate_simple (2, hdims, 0);
@@ -622,7 +622,7 @@
   dim_vector dv;
   int empty = load_hdf5_empty (loc_id, name, dv);
   if (empty > 0)
-    matrix.resize(dv);
+    matrix.resize (dv);
   if (empty)
     return (empty > 0);
 
@@ -862,14 +862,14 @@
 
   for (mwIndex i = 0; i < nz; i++)
     {
-      Complex val = matrix.data(i);
+      Complex val = matrix.data (i);
       pr[i] = std::real (val);
       pi[i] = std::imag (val);
-      ir[i] = matrix.ridx(i);
+      ir[i] = matrix.ridx (i);
     }
 
-  for (mwIndex i = 0; i < columns() + 1; i++)
-    jc[i] = matrix.cidx(i);
+  for (mwIndex i = 0; i < columns () + 1; i++)
+    jc[i] = matrix.cidx (i);
 
   return retval;
 }
@@ -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);
rename from src/ov-cx-sparse.h
rename to libinterp/octave-value/ov-cx-sparse.h
rename from src/ov-dld-fcn.cc
rename to libinterp/octave-value/ov-dld-fcn.cc
rename from src/ov-dld-fcn.h
rename to libinterp/octave-value/ov-dld-fcn.h
rename from src/ov-fcn-handle.cc
rename to libinterp/octave-value/ov-fcn-handle.cc
--- a/src/ov-fcn-handle.cc
+++ b/libinterp/octave-value/ov-fcn-handle.cc
@@ -80,6 +80,9 @@
 
   if (uf && nm != anonymous)
     symbol_table::cache_name (uf->scope (), nm);
+
+  if (uf && uf->is_nested_function ())
+    ::error ("handles to nested functions are not yet supported");
 }
 
 octave_value_list
@@ -372,7 +375,7 @@
           for (std::list<symbol_table::symbol_record>::const_iterator p = vars.begin ();
                p != vars.end (); p++)
             {
-              if (! save_ascii_data (os, p->varval (), p->name (), false, 0))
+              if (! save_ascii_data (os, p->varval (0), p->name (), false, 0))
                 return os;
             }
         }
@@ -398,14 +401,14 @@
 
   std::streampos pos = is.tellg ();
   std::string octaveroot = extract_keyword (is, "octaveroot", true);
-  if (octaveroot.length() == 0)
+  if (octaveroot.length () == 0)
     {
       is.seekg (pos);
       is.clear ();
     }
   pos = is.tellg ();
   std::string fpath = extract_keyword (is, "path", true);
-  if (fpath.length() == 0)
+  if (fpath.length () == 0)
     {
       is.seekg (pos);
       is.clear ();
@@ -463,7 +466,7 @@
                       break;
                     }
 
-                  symbol_table::varref (name, local_scope, 0) = t2;
+                  symbol_table::assign (name, t2, local_scope, 0);
                 }
             }
         }
@@ -530,7 +533,7 @@
       else
         nmbuf << nm;
 
-      std::string buf_str = nmbuf.str();
+      std::string buf_str = nmbuf.str ();
       int32_t tmp = buf_str.length ();
       os.write (reinterpret_cast<char *> (&tmp), 4);
       os.write (buf_str.c_str (), buf_str.length ());
@@ -547,7 +550,7 @@
           for (std::list<symbol_table::symbol_record>::const_iterator p = vars.begin ();
                p != vars.end (); p++)
             {
-              if (! save_binary_data (os, p->varval (), p->name (),
+              if (! save_binary_data (os, p->varval (0), p->name (),
                                       "", 0, save_as_floats))
                 return os;
             }
@@ -595,11 +598,11 @@
 
   size_t anl = anonymous.length ();
 
-  if (nm.length() >= anl && nm.substr (0, anl) == anonymous)
+  if (nm.length () >= anl && nm.substr (0, anl) == anonymous)
     {
       octave_idx_type len = 0;
 
-      if (nm.length() > anl)
+      if (nm.length () > anl)
         {
           std::istringstream nm_is (nm.substr (anl));
           nm_is >> len;
@@ -648,7 +651,7 @@
                   break;
                 }
 
-              symbol_table::varref (name, local_scope) = t2;
+              symbol_table::assign (name, t2, local_scope);
             }
         }
 
@@ -836,7 +839,7 @@
           for (std::list<symbol_table::symbol_record>::const_iterator p = vars.begin ();
                p != vars.end (); p++)
             {
-              if (! add_hdf5_data (data_hid, p->varval (), p->name (),
+              if (! add_hdf5_data (data_hid, p->varval (0), p->name (),
                                    "", false, save_as_floats))
                 break;
             }
@@ -1156,7 +1159,7 @@
                       break;
                     }
 
-                  symbol_table::varref (dsub.name, local_scope) = dsub.tc;
+                  symbol_table::assign (dsub.name, dsub.tc, local_scope);
                 }
             }
         }
@@ -1288,7 +1291,6 @@
 #endif
 
 /*
-
 %!test
 %! a = 2;
 %! f = @(x) a + x;
@@ -1302,26 +1304,80 @@
 %! hdld2 = hdld;
 %! hbi2 = hbi;
 %! modes = {"-text", "-binary"};
-%! if (!isempty(findstr(octave_config_info ("DEFS"),"HAVE_HDF5")))
+%! if (isfield (octave_config_info, "HAVE_HDF5")
+%!     && octave_config_info ("HAVE_HDF5"))
 %!   modes(end+1) = "-hdf5";
 %! endif
 %! for i = 1:numel (modes)
 %!   mode = modes{i};
-%!   nm = tmpnam();
+%!   nm = tmpnam ();
 %!   unwind_protect
+%!     f2 (1); # bug #33857
 %!     save (mode, nm, "f2", "g2", "hm2", "hdld2", "hbi2");
 %!     clear f2 g2 hm2 hdld2 hbi2
 %!     load (nm);
-%!     assert (f(2),f2(2));
-%!     assert (g(2),g2(2));
-%!     assert (g(3),g2(3));
+%!     assert (f (2), f2 (2));
+%!     assert (g (2), g2 (2));
+%!     assert (g (3), g2 (3));
 %!     unlink (nm);
 %!     save (mode, nm, "f2", "g2", "hm2", "hdld2", "hbi2");
 %!   unwind_protect_cleanup
 %!     unlink (nm);
 %!   end_unwind_protect
 %! endfor
+*/
 
+/*
+%!function fcn_handle_save_recurse (n, mode, nm, f2, g2, hm2, hdld2, hbi2)
+%!  if n == 0
+%!    save (mode, nm, "f2", "g2", "hm2", "hdld2", "hbi2");
+%!  else
+%!    fcn_handle_save_recurse (n - 1, mode, nm, f2, g2, hm2, hdld2, hbi2);
+%!  endif
+%!endfunction
+%!function [f2, g2, hm2, hdld2, hbi2] = fcn_handle_load_recurse (n, nm)
+%!  if n == 0
+%!    load (nm)
+%!  else
+%!    [f2, g2, hm2, hdld2, hbi2] = fcn_handle_load_recurse (n - 1, nm);
+%!  endif
+%!endfunction
+
+Test for bug #35876
+%!test
+%! a = 2;
+%! f = @(x) a + x;
+%! g = @(x) 2 * x;
+%! hm = @version;
+%! hdld = @svd;
+%! hbi = @log2;
+%! f2 = f;
+%! g2 = g;
+%! hm2 = hm;
+%! hdld2 = hdld;
+%! hbi2 = hbi;
+%! modes = {"-text", "-binary"};
+%! if (isfield (octave_config_info, "HAVE_HDF5")
+%!     && octave_config_info ("HAVE_HDF5"))
+%!   modes(end+1) = "-hdf5";
+%! endif
+%! for i = 1:numel (modes)
+%!   mode = modes{i};
+%!   nm = tmpnam ();
+%!   unwind_protect
+%!     fcn_handle_save_recurse (2, mode, nm, f2, g2, hm2, hdld2, hbi2);
+%!     clear f2 g2 hm2 hdld2 hbi2
+%!     [f2, f2, hm2, hdld2, hbi2] = fcn_handle_load_recurse (2, nm);
+%!     load (nm);
+%!     assert (f (2), f2 (2));
+%!     assert (g (2), g2 (2));
+%!     assert (g (3), g2 (3));
+%!     unlink (nm);
+%!     fcn_handle_save_recurse (2, mode, nm, f2, g2, hm2, hdld2, hbi2);
+%!   unwind_protect_cleanup
+%!     unlink (nm);
+%!   end_unwind_protect
+%! endfor
 */
 
 void
@@ -1592,7 +1648,7 @@
 %!      "&", "and";
 %!      "|", "or"};
 %! for i = 1:rows (x)
-%!   assert (functions (str2func (x{i,1})).function, x{i,2})
+%!   assert (functions (str2func (x{i,1})).function, x{i,2});
 %! endfor
 */
 
@@ -1635,8 +1691,8 @@
                     {
                       m.setfield ("type", "subfunction");
                       Cell parentage (dim_vector (1, 2));
-                      parentage.elem(0) = fh_nm;
-                      parentage.elem(1) = fcn->parent_fcn_name ();
+                      parentage.elem (0) = fh_nm;
+                      parentage.elem (1) = fcn->parent_fcn_name ();
                       m.setfield ("parentage", octave_value (parentage));
                     }
                   else if (fcn->is_private_function ())
@@ -1759,7 +1815,6 @@
 }
 
 /*
-
 %!function y = __testrecursionfunc (f, x, n)
 %!  if (nargin < 3)
 %!    n = 0;
@@ -1768,12 +1823,11 @@
 %!    y = f (x);
 %!  else
 %!    n++;
-%!    y = __testrecursionfunc (@(x) f(2*x), x, n);
+%!    y = __testrecursionfunc (@(x) f (2*x), x, n);
 %!  endif
 %!endfunction
 %!
 %!assert (__testrecursionfunc (@(x) x, 1), 8)
-
 */
 
 DEFUN (is_function_handle, args, ,
@@ -1802,12 +1856,11 @@
 %!assert (is_function_handle (fh))
 %!assert (! is_function_handle ({fh}))
 %!assert (! is_function_handle (1))
-%!error is_function_handle ();
-%!error is_function_handle (1, 2);
 
+%!error is_function_handle ()
+%!error is_function_handle (1, 2)
 */
 
-
 octave_fcn_binder::octave_fcn_binder (const octave_value& f,
                                       const octave_value& root,
                                       const octave_value_list& templ,
rename from src/ov-fcn-handle.h
rename to libinterp/octave-value/ov-fcn-handle.h
rename from src/ov-fcn-inline.cc
rename to libinterp/octave-value/ov-fcn-inline.cc
--- a/src/ov-fcn-inline.cc
+++ b/libinterp/octave-value/ov-fcn-inline.cc
@@ -645,7 +645,8 @@
 be noted that i, and j are ignored as arguments due to the\n\
 ambiguity between their use as a variable or their use as an inbuilt\n\
 constant.  All arguments followed by a parenthesis are considered\n\
-to be functions.\n\
+to be functions. If no arguments are found, a function taking a single\n\
+argument named @code{x} will be created.\n\
 \n\
 If the second and subsequent arguments are character strings,\n\
 they are the names of the arguments of the function.\n\
@@ -752,15 +753,19 @@
 
               // Sort the arguments into ascii order.
               fargs.sort ();
+
+              if (fargs.length () == 0)
+                fargs.append (std::string ("x"));
+
             }
           else if (nargin == 2 && args(1).is_numeric_type ())
             {
-              if (! args(1).is_scalar_type ()) 
+              if (! args(1).is_scalar_type ())
                 {
                   error ("inline: N must be an integer");
                   return retval;
                 }
-              
+
               int n = args(1).int_value ();
 
               if (! error_state)
@@ -825,9 +830,11 @@
 %! fn = inline ("x.^2 + 1");
 %!assert (feval (fn, 6), 37)
 %!assert (fn (6), 37)
-%% FIXME: Need tests for other 2 calling forms of inline()
+%!assert (feval (inline ("sum (x(:))"), [1 2; 3 4]), 10)
+%!assert (feval (inline ("sqrt (x^2 + y^2)", "x", "y"), 3, 4), 5)
+%!assert (feval (inline ("exp (P1*x) + P2", 3), 3, 4, 5), exp(3*4) + 5)
 
-%% Test input validation 
+## Test input validation
 %!error inline ()
 %!error <STR argument must be a string> inline (1)
 %!error <N must be an integer> inline ("2", ones (2,2))
@@ -867,7 +874,7 @@
 %!assert (formula (fn), "x.^2 + 1")
 %!assert (formula (fn), char (fn))
 
-%% Test input validation
+## Test input validation
 %!error formula ()
 %!error formula (1, 2)
 %!error <FUN must be an inline function> formula (1)
@@ -914,7 +921,7 @@
 %!assert (argnames (inline ("1e-3*y + 2e4*z")), {"y"; "z"})
 %!assert (argnames (inline ("2", 2)), {"x"; "P1"; "P2"})
 
-%% Test input validation
+## Test input validation
 %!error argnames ()
 %!error argnames (1, 2)
 %!error <FUN must be an inline function> argnames (1)
@@ -1012,9 +1019,8 @@
 %!assert (vectorize ("1e-3*y + 2e4*z"), "1e-3.*y + 2e4.*z")
 %!assert (vectorize ("2**x^5"), "2.**x.^5")
 
-%% Test input validation
+## Test input validation
 %!error vectorize ()
 %!error vectorize (1, 2)
 %!error <FUN must be a string or inline function> vectorize (1)
 */
-
rename from src/ov-fcn-inline.h
rename to libinterp/octave-value/ov-fcn-inline.h
rename from src/ov-fcn.cc
rename to libinterp/octave-value/ov-fcn.cc
rename from src/ov-fcn.h
rename to libinterp/octave-value/ov-fcn.h
--- a/src/ov-fcn.h
+++ b/libinterp/octave-value/ov-fcn.h
@@ -61,6 +61,8 @@
 
   virtual std::string fcn_file_name (void) const { return std::string (); }
 
+  virtual std::string src_file_name (void) const { return std::string (); }
+
   // The name to show in the profiler (also used as map-key).
   virtual std::string profiler_name (void) const { return name (); }
 
rename from src/ov-float.cc
rename to libinterp/octave-value/ov-float.cc
--- a/src/ov-float.cc
+++ b/libinterp/octave-value/ov-float.cc
@@ -33,6 +33,7 @@
 
 #include "defun.h"
 #include "gripes.h"
+#include "mxarray.h"
 #include "oct-obj.h"
 #include "oct-stream.h"
 #include "ov-scalar.h"
@@ -79,7 +80,7 @@
 {
   if (fill)
     {
-      FloatNDArray retval (dv, NDArray::resize_fill_value());
+      FloatNDArray retval (dv, 0);
 
       if (dv.numel ())
         retval(0) = scalar;
@@ -98,6 +99,12 @@
 }
 
 octave_value
+octave_float_scalar::diag (octave_idx_type m, octave_idx_type n) const
+{
+  return FloatDiagMatrix (Array<float> (dim_vector (1, 1), scalar), m, n);
+}
+
+octave_value
 octave_float_scalar::convert_to_str_internal (bool, bool, char type) const
 {
   octave_value retval;
@@ -108,7 +115,7 @@
     {
       int ival = NINT (scalar);
 
-      if (ival < 0 || ival > UCHAR_MAX)
+      if (ival < 0 || ival > std::numeric_limits<unsigned char>::max ())
         {
           // FIXME -- is there something better we could do?
 
@@ -285,8 +292,11 @@
       SCALAR_MAPPER (atanh, rc_atanh);
       SCALAR_MAPPER (erf, ::erff);
       SCALAR_MAPPER (erfinv, ::erfinv);
+      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);
@@ -296,7 +306,7 @@
       SCALAR_MAPPER (exp, ::expf);
       SCALAR_MAPPER (expm1, ::expm1f);
       SCALAR_MAPPER (fix, ::fix);
-      SCALAR_MAPPER (floor, ::floorf);
+      SCALAR_MAPPER (floor, gnulib::floorf);
       SCALAR_MAPPER (log, rc_log);
       SCALAR_MAPPER (log2, rc_log2);
       SCALAR_MAPPER (log10, rc_log10);
@@ -313,6 +323,7 @@
       SCALAR_MAPPER (isinf, xisinf);
       SCALAR_MAPPER (isna, octave_is_NA);
       SCALAR_MAPPER (isnan, xisnan);
+      SCALAR_MAPPER (xsignbit, xsignbit);
 
     default:
       return octave_base_value::map (umap);
rename from src/ov-float.h
rename to libinterp/octave-value/ov-float.h
--- a/src/ov-float.h
+++ b/libinterp/octave-value/ov-float.h
@@ -211,6 +211,8 @@
     return boolNDArray (dim_vector (1, 1), scalar);
   }
 
+  octave_value diag (octave_idx_type m, octave_idx_type n) const;
+
   octave_value convert_to_str_internal (bool pad, bool force, char type) const;
 
   void increment (void) { ++scalar; }
rename from src/ov-flt-complex.cc
rename to libinterp/octave-value/ov-flt-complex.cc
--- a/src/ov-flt-complex.cc
+++ b/libinterp/octave-value/ov-flt-complex.cc
@@ -30,6 +30,7 @@
 #include "lo-specfun.h"
 #include "lo-mappers.h"
 
+#include "mxarray.h"
 #include "oct-obj.h"
 #include "oct-stream.h"
 #include "ops.h"
@@ -210,7 +211,7 @@
 {
   if (fill)
     {
-      FloatComplexNDArray retval (dv, FloatComplexNDArray::resize_fill_value ());
+      FloatComplexNDArray retval (dv, FloatComplex (0));
 
       if (dv.numel ())
         retval(0) = scalar;
@@ -228,6 +229,12 @@
     }
 }
 
+octave_value
+octave_float_complex::diag (octave_idx_type m, octave_idx_type n) const
+{
+  return FloatComplexDiagMatrix (Array<FloatComplex> (dim_vector (1, 1), scalar), m, n);
+}
+
 bool
 octave_float_complex::save_ascii (std::ostream& os)
 {
@@ -409,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);
rename from src/ov-flt-complex.h
rename to libinterp/octave-value/ov-flt-complex.h
--- a/src/ov-flt-complex.h
+++ b/libinterp/octave-value/ov-flt-complex.h
@@ -152,6 +152,8 @@
     return boolNDArray (dim_vector (1, 1), scalar != 1.0f);
   }
 
+  octave_value diag (octave_idx_type m, octave_idx_type n) const;
+
   void increment (void) { scalar += 1.0; }
 
   void decrement (void) { scalar -= 1.0; }
rename from src/ov-flt-cx-diag.cc
rename to libinterp/octave-value/ov-flt-cx-diag.cc
--- a/src/ov-flt-cx-diag.cc
+++ b/libinterp/octave-value/ov-flt-cx-diag.cc
@@ -133,7 +133,7 @@
       return ::imag (matrix);
     case umap_sqrt:
       {
-        FloatComplexColumnVector tmp = matrix.diag ().map<FloatComplex> (std::sqrt);
+        FloatComplexColumnVector tmp = matrix.extract_diag ().map<FloatComplex> (std::sqrt);
         FloatComplexDiagMatrix retval (tmp);
         retval.resize (matrix.rows (), matrix.columns ());
         return retval;
@@ -153,7 +153,7 @@
   os.write (reinterpret_cast<char *> (&r), 4);
   os.write (reinterpret_cast<char *> (&c), 4);
 
-  FloatComplexMatrix m = FloatComplexMatrix (matrix.diag ());
+  FloatComplexMatrix m = FloatComplexMatrix (matrix.extract_diag ());
   save_type st = LS_FLOAT;
   if (matrix.length () > 4096) // FIXME -- make this configurable.
     {
rename from src/ov-flt-cx-diag.h
rename to libinterp/octave-value/ov-flt-cx-diag.h
rename from src/ov-flt-cx-mat.cc
rename to libinterp/octave-value/ov-flt-cx-mat.cc
--- a/src/ov-flt-cx-mat.cc
+++ b/libinterp/octave-value/ov-flt-cx-mat.cc
@@ -37,6 +37,7 @@
 #include "oct-locbuf.h"
 
 #include "gripes.h"
+#include "mxarray.h"
 #include "oct-obj.h"
 #include "oct-stream.h"
 #include "ops.h"
@@ -97,7 +98,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "complex matrix", "real scalar");
 
       retval = std::real (matrix (0, 0));
@@ -119,7 +120,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "complex matrix", "real scalar");
 
       retval = std::real (matrix (0, 0));
@@ -167,7 +168,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "complex matrix", "complex scalar");
 
       retval = matrix (0, 0);
@@ -187,7 +188,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "complex matrix", "complex scalar");
 
       retval = matrix (0, 0);
@@ -281,6 +282,24 @@
   return retval;
 }
 
+octave_value
+octave_float_complex_matrix::diag (octave_idx_type m, octave_idx_type n) const
+{
+  octave_value retval;
+
+  if (matrix.ndims () == 2
+      && (matrix.rows () == 1 || matrix.columns () == 1))
+    {
+      FloatComplexMatrix mat = matrix.matrix_value ();
+
+      retval = mat.diag (m, n);
+    }
+  else
+    error ("diag: expecting vector argument");
+
+  return retval;
+}
+
 bool
 octave_float_complex_matrix::save_ascii (std::ostream& os)
 {
@@ -408,11 +427,11 @@
 octave_float_complex_matrix::save_binary (std::ostream& os, bool&)
 {
   dim_vector d = dims ();
-  if (d.length() < 1)
+  if (d.length () < 1)
     return false;
 
   // Use negative value for ndims to differentiate with old format!!
-  int32_t tmp = - d.length();
+  int32_t tmp = - d.length ();
   os.write (reinterpret_cast<char *> (&tmp), 4);
   for (int i = 0; i < d.length (); i++)
     {
@@ -593,7 +612,7 @@
   dim_vector dv;
   int empty = load_hdf5_empty (loc_id, name, dv);
   if (empty > 0)
-    matrix.resize(dv);
+    matrix.resize (dv);
   if (empty)
       return (empty > 0);
 
@@ -725,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);
rename from src/ov-flt-cx-mat.h
rename to libinterp/octave-value/ov-flt-cx-mat.h
--- a/src/ov-flt-cx-mat.h
+++ b/libinterp/octave-value/ov-flt-cx-mat.h
@@ -133,6 +133,8 @@
 
   octave_value diag (octave_idx_type k = 0) const;
 
+  octave_value diag (octave_idx_type m, octave_idx_type n) const;
+
   void increment (void) { matrix += FloatComplex (1.0); }
 
   void decrement (void) { matrix -= FloatComplex (1.0); }
rename from src/ov-flt-re-diag.cc
rename to libinterp/octave-value/ov-flt-re-diag.cc
--- a/src/ov-flt-re-diag.cc
+++ b/libinterp/octave-value/ov-flt-re-diag.cc
@@ -103,7 +103,7 @@
       return DiagMatrix (matrix.rows (), matrix.cols (), 0.0);
     case umap_sqrt:
       {
-        FloatComplexColumnVector tmp = matrix.diag ().map<FloatComplex> (rc_sqrt);
+        FloatComplexColumnVector tmp = matrix.extract_diag ().map<FloatComplex> (rc_sqrt);
         FloatComplexDiagMatrix retval (tmp);
         retval.resize (matrix.rows (), matrix.columns ());
         return retval;
@@ -122,7 +122,7 @@
   os.write (reinterpret_cast<char *> (&r), 4);
   os.write (reinterpret_cast<char *> (&c), 4);
 
-  FloatMatrix m = FloatMatrix (matrix.diag ());
+  FloatMatrix m = FloatMatrix (matrix.extract_diag ());
   save_type st = LS_FLOAT;
   if (matrix.length () > 8192) // FIXME -- make this configurable.
     {
rename from src/ov-flt-re-diag.h
rename to libinterp/octave-value/ov-flt-re-diag.h
rename from src/ov-flt-re-mat.cc
rename to libinterp/octave-value/ov-flt-re-mat.cc
--- a/src/ov-flt-re-mat.cc
+++ b/libinterp/octave-value/ov-flt-re-mat.cc
@@ -25,9 +25,8 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 #include <vector>
 
 #include "data-conv.h"
@@ -42,6 +41,7 @@
 
 #include "defun.h"
 #include "gripes.h"
+#include "mxarray.h"
 #include "oct-obj.h"
 #include "oct-lvalue.h"
 #include "oct-stream.h"
@@ -68,10 +68,6 @@
 #include "ls-utils.h"
 #include "ls-hdf5.h"
 
-#if ! defined (UCHAR_MAX)
-#define UCHAR_MAX 255
-#endif
-
 template class octave_base_matrix<FloatNDArray>;
 
 DEFINE_OCTAVE_ALLOCATOR (octave_float_matrix);
@@ -96,7 +92,7 @@
 
   if (numel () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "real matrix", "real scalar");
 
       retval = matrix (0, 0);
@@ -114,7 +110,7 @@
 
   if (numel () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "real matrix", "real scalar");
 
       retval = matrix (0, 0);
@@ -148,7 +144,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "real matrix", "complex scalar");
 
       retval = matrix (0, 0);
@@ -168,7 +164,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "real matrix", "complex scalar");
 
       retval = matrix (0, 0);
@@ -264,6 +260,24 @@
 }
 
 octave_value
+octave_float_matrix::diag (octave_idx_type m, octave_idx_type n) const
+{
+  octave_value retval;
+
+  if (matrix.ndims () == 2
+      && (matrix.rows () == 1 || matrix.columns () == 1))
+    {
+      FloatMatrix mat = matrix.matrix_value ();
+
+      retval = mat.diag (m, n);
+    }
+  else
+    error ("diag: expecting vector argument");
+
+  return retval;
+}
+
+octave_value
 octave_float_matrix::convert_to_str_internal (bool, bool, char type) const
 {
   octave_value retval;
@@ -289,7 +303,7 @@
         {
           int ival = NINT (d);
 
-          if (ival < 0 || ival > UCHAR_MAX)
+          if (ival < 0 || ival > std::numeric_limits<unsigned char>::max ())
             {
               // FIXME -- is there something
               // better we could do?
@@ -441,11 +455,11 @@
 {
 
   dim_vector d = dims ();
-  if (d.length() < 1)
+  if (d.length () < 1)
     return false;
 
   // Use negative value for ndims to differentiate with old format!!
-  int32_t tmp = - d.length();
+  int32_t tmp = - d.length ();
   os.write (reinterpret_cast<char *> (&tmp), 4);
   for (int i = 0; i < d.length (); i++)
     {
@@ -606,7 +620,7 @@
   dim_vector dv;
   int empty = load_hdf5_empty (loc_id, name, dv);
   if (empty > 0)
-    matrix.resize(dv);
+    matrix.resize (dv);
   if (empty)
       return (empty > 0);
 
@@ -766,8 +780,11 @@
       RC_ARRAY_MAPPER (atanh, FloatComplex, rc_atanh);
       ARRAY_MAPPER (erf, float, ::erff);
       ARRAY_MAPPER (erfinv, float, ::erfinv);
+      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);
@@ -791,6 +808,7 @@
       ARRAY_MAPPER (tan, float, ::tanf);
       ARRAY_MAPPER (tanh, float, ::tanhf);
       ARRAY_MAPPER (isna, bool, octave_is_NA);
+      ARRAY_MAPPER (xsignbit, float, xsignbit);
 
     default:
       return octave_base_value::map (umap);
@@ -841,9 +859,8 @@
 }
 
 /*
-
-%!assert (class (single(1)), "single")
-%!assert (class (single(1 + i)), "single")
+%!assert (class (single (1)), "single")
+%!assert (class (single (1 + i)), "single")
 %!assert (class (single (int8 (1))), "single")
 %!assert (class (single (uint8 (1))), "single")
 %!assert (class (single (int16 (1))), "single")
@@ -865,6 +882,4 @@
 %! y = single (x);
 %! assert (class (x), "double");
 %! assert (class (y), "single");
-
 */
-
rename from src/ov-flt-re-mat.h
rename to libinterp/octave-value/ov-flt-re-mat.h
--- a/src/ov-flt-re-mat.h
+++ b/libinterp/octave-value/ov-flt-re-mat.h
@@ -164,6 +164,8 @@
 
   octave_value diag (octave_idx_type k = 0) const;
 
+  octave_value diag (octave_idx_type m, octave_idx_type n) const;
+
   // Use matrix_ref here to clear index cache.
   void increment (void) { matrix_ref () += 1.0; }
 
rename from src/ov-int-traits.h
rename to libinterp/octave-value/ov-int-traits.h
rename from src/ov-int16.cc
rename to libinterp/octave-value/ov-int16.cc
--- a/src/ov-int16.cc
+++ b/libinterp/octave-value/ov-int16.cc
@@ -24,9 +24,8 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 
 #include "lo-ieee.h"
 #include "lo-utils.h"
@@ -84,13 +83,10 @@
 }
 
 /*
-
 %!assert (class (int16 (1)), "int16")
 %!assert (int16 (1.25), int16 (1))
 %!assert (int16 (1.5), int16 (2))
 %!assert (int16 (-1.5), int16 (-2))
 %!assert (int16 (2^17), int16 (2^16-1))
 %!assert (int16 (-2^17), int16 (-2^16))
-
 */
-
rename from src/ov-int16.h
rename to libinterp/octave-value/ov-int16.h
rename from src/ov-int32.cc
rename to libinterp/octave-value/ov-int32.cc
--- a/src/ov-int32.cc
+++ b/libinterp/octave-value/ov-int32.cc
@@ -24,9 +24,8 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 
 #include "lo-ieee.h"
 #include "lo-utils.h"
@@ -84,13 +83,10 @@
 }
 
 /*
-
 %!assert (class (int32 (1)), "int32")
 %!assert (int32 (1.25), int32 (1))
 %!assert (int32 (1.5), int32 (2))
 %!assert (int32 (-1.5), int32 (-2))
 %!assert (int32 (2^33), int32 (2^32-1))
 %!assert (int32 (-2^33), int32 (-2^32))
-
 */
-
rename from src/ov-int32.h
rename to libinterp/octave-value/ov-int32.h
rename from src/ov-int64.cc
rename to libinterp/octave-value/ov-int64.cc
--- a/src/ov-int64.cc
+++ b/libinterp/octave-value/ov-int64.cc
@@ -24,9 +24,8 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 
 #include "lo-ieee.h"
 #include "lo-utils.h"
@@ -84,13 +83,10 @@
 }
 
 /*
-
 %!assert (class (int64 (1)), "int64")
 %!assert (int64 (1.25), int64 (1))
 %!assert (int64 (1.5), int64 (2))
 %!assert (int64 (-1.5), int64 (-2))
 %!assert (int64 (2^65), int64 (2^64-1))
 %!assert (int64 (-2^65), int64 (-2^64))
-
 */
-
rename from src/ov-int64.h
rename to libinterp/octave-value/ov-int64.h
rename from src/ov-int8.cc
rename to libinterp/octave-value/ov-int8.cc
--- a/src/ov-int8.cc
+++ b/libinterp/octave-value/ov-int8.cc
@@ -24,9 +24,8 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 
 #include "lo-ieee.h"
 #include "lo-utils.h"
@@ -84,12 +83,10 @@
 }
 
 /*
-
 %!assert (class (int8 (1)), "int8")
 %!assert (int8 (1.25), int8 (1))
 %!assert (int8 (1.5), int8 (2))
 %!assert (int8 (-1.5), int8 (-2))
 %!assert (int8 (2^9), int8 (2^8-1))
 %!assert (int8 (-2^9), int8 (-2^8))
-
 */
rename from src/ov-int8.h
rename to libinterp/octave-value/ov-int8.h
rename from src/ov-intx.h
rename to libinterp/octave-value/ov-intx.h
--- a/src/ov-intx.h
+++ b/libinterp/octave-value/ov-intx.h
@@ -31,6 +31,7 @@
 #include "str-vec.h"
 
 #include "error.h"
+#include "mxarray.h"
 #include "oct-stream.h"
 #include "ov-base.h"
 #include "ov-base-int.h"
@@ -104,7 +105,7 @@
 
       if (numel () > 0)
         {
-          gripe_implicit_conversion ("Octave:array-as-scalar",
+          gripe_implicit_conversion ("Octave:array-to-scalar",
                                      type_name (), "real scalar");
 
           retval = matrix(0).double_value ();
@@ -123,7 +124,7 @@
 
       if (numel () > 0)
         {
-          gripe_implicit_conversion ("Octave:array-as-scalar",
+          gripe_implicit_conversion ("Octave:array-to-scalar",
                                      type_name (), "real scalar");
 
           retval = matrix(0).float_value ();
@@ -145,7 +146,7 @@
       Matrix retval;
       dim_vector dv = dims ();
       if (dv.length () > 2)
-        error ("invalid conversion of %s to Matrix", type_name().c_str ());
+        error ("invalid conversion of %s to Matrix", type_name ().c_str ());
       else
         {
           retval = Matrix (dv(0), dv(1));
@@ -163,7 +164,7 @@
       FloatMatrix retval;
       dim_vector dv = dims ();
       if (dv.length () > 2)
-        error ("invalid conversion of %s to FloatMatrix", type_name().c_str ());
+        error ("invalid conversion of %s to FloatMatrix", type_name ().c_str ());
       else
         {
           retval = FloatMatrix (dv(0), dv(1));
@@ -179,9 +180,9 @@
   complex_matrix_value (bool = false) const
     {
       ComplexMatrix retval;
-      dim_vector dv = dims();
+      dim_vector dv = dims ();
       if (dv.length () > 2)
-        error ("invalid conversion of %s to Matrix", type_name().c_str ());
+        error ("invalid conversion of %s to Matrix", type_name ().c_str ());
       else
         {
           retval = ComplexMatrix (dv(0), dv(1));
@@ -197,9 +198,9 @@
   float_complex_matrix_value (bool = false) const
     {
       FloatComplexMatrix retval;
-      dim_vector dv = dims();
+      dim_vector dv = dims ();
       if (dv.length () > 2)
-        error ("invalid conversion of %s to FloatMatrix", type_name().c_str ());
+        error ("invalid conversion of %s to FloatMatrix", type_name ().c_str ());
       else
         {
           retval = FloatComplexMatrix (dv(0), dv(1));
@@ -289,12 +290,12 @@
   // Use matrix_ref here to clear index cache.
   void increment (void)
    {
-     matrix_ref() += OCTAVE_INT_T (1);
+     matrix_ref () += OCTAVE_INT_T (1);
    }
 
   void decrement (void)
    {
-     matrix_ref() -= OCTAVE_INT_T (1);
+     matrix_ref () -= OCTAVE_INT_T (1);
    }
 
   void changesign (void)
@@ -479,14 +480,14 @@
       if (fill)
         {
           intNDArray<OCTAVE_INT_T> retval (dv, 0);
-          if (dv.numel())
+          if (dv.numel ())
             retval(0) = scalar;
           return retval;
         }
       else
         {
           intNDArray<OCTAVE_INT_T> retval (dv);
-          if (dv.numel())
+          if (dv.numel ())
             retval(0) = scalar;
           return retval;
         }
new file mode 100644
--- /dev/null
+++ b/libinterp/octave-value/ov-java.cc
@@ -0,0 +1,2386 @@
+/*
+
+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"
+#include "fpucw.h"
+
+#if HAVE_FPU_CONTROL_H
+#include <fpu_control.h>
+#endif
+
+#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;
+};
+
+#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;
+}
+
+#ifndef _FPU_DEFAULT
+#if defined __i386__ || defined __x86_64__
+#define _FPU_DEFAULT 0x037f
+#else
+#define _FPU_DEFAULT 0
+#endif
+#endif
+
+static void
+restore_fpu_state (void)
+{
+  fpucw_t cw = GET_FPUCW ();
+  if (cw != _FPU_DEFAULT)
+    SET_FPUCW (_FPU_DEFAULT);
+}
+
+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 ();
+
+      restore_fpu_state ();
+    }
+}
+
+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");
+  jmethodID 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++;
+    }
+
+  restore_fpu_state ();
+
+  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);
+
+  restore_fpu_state ();
+
+  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);
+  jobject_ref 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);
+
+  restore_fpu_state ();
+
+  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;");
+      jmethodID 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)));
+      jobjectArray_ref fList (jni_env, reinterpret_cast<jobjectArray> (jni_env->CallObjectMethod (cls, getFields_ID)));
+      int mLen = jni_env->GetArrayLength (mList);
+      int fLen = jni_env->GetArrayLength (fList);
+      jclass_ref mCls (jni_env, jni_env->FindClass ("java/lang/reflect/Method"));
+      jclass_ref fCls (jni_env, jni_env->FindClass ("java/lang/reflect/Field"));
+      jmethodID m_getName_ID = jni_env->GetMethodID (mCls, "getName", "()Ljava/lang/String;");
+      jmethodID 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));
+        }
+
+      restore_fpu_state ();
+    }
+
+  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");
+
+      restore_fpu_state ();
+    }
+
+  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));
+
+  restore_fpu_state ();
+
+  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 if (val.is_bool_type ())
+        {
+          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
+        {
+          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_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 ());
+      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);
+
+      restore_fpu_state ();
+    }
+
+  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 ());
+        }
+
+      restore_fpu_state ();
+    }
+}
+
+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 ("");
+}
+
+void
+octave_java::print (std::ostream& os, bool) const
+{
+  print_raw (os);
+  newline (os);
+}
+
+void
+octave_java::print_raw (std::ostream& os, bool) const
+{
+  os << "<Java object: " << java_classname << ">";
+}
+
+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);
+        }
+
+      restore_fpu_state ();
+    }
+
+  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);
+        }
+
+      restore_fpu_state ();
+    }
+
+  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);
+        }
+
+      restore_fpu_state ();
+    }
+
+  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);
+
+      restore_fpu_state ();
+    }
+
+  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);
+
+      restore_fpu_state ();
+    }
+
+  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);
+        }
+
+      restore_fpu_state ();
+    }
+
+  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);
+        }
+
+      restore_fpu_state ();
+    }
+
+  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 (__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")
+{
+
+#ifdef HAVE_JAVA
+  octave_value retval;
+
+  retval = 0;
+
+  initialize_java ();
+
+  if (! error_state)
+    retval = 1;
+
+  return retval;
+#else
+  error ("__java_init__: Octave was not compiled with Java interface");
+  return octave_value ();
+#endif
+}
+
+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")
+{
+#ifdef HAVE_JAVA
+  terminate_jvm ();
+#else
+  error ("__java_init__: Octave was not compiled with Java interface");
+#endif
+
+  return octave_value ();
+}
+
+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;
+}
+
new file mode 100644
--- /dev/null
+++ b/libinterp/octave-value/ov-java.h
@@ -0,0 +1,314 @@
+/*
+
+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;
+
+  void print_raw (std::ostream& os, bool pr_as_read_syntax = false) const;
+
+  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
rename from src/ov-lazy-idx.cc
rename to libinterp/octave-value/ov-lazy-idx.cc
rename from src/ov-lazy-idx.h
rename to libinterp/octave-value/ov-lazy-idx.h
rename from src/ov-mex-fcn.cc
rename to libinterp/octave-value/ov-mex-fcn.cc
rename from src/ov-mex-fcn.h
rename to libinterp/octave-value/ov-mex-fcn.h
rename from src/ov-null-mat.cc
rename to libinterp/octave-value/ov-null-mat.cc
--- a/src/ov-null-mat.cc
+++ b/libinterp/octave-value/ov-null-mat.cc
@@ -96,6 +96,7 @@
 delete array elements.  This function should be used when overloading\n\
 indexed assignment for user-defined classes instead of @code{isempty}, to\n\
 distinguish the cases:\n\
+\n\
 @table @asis\n\
 @item @code{A(I) = []}\n\
 This should delete elements if @code{I} is nonempty.\n\
@@ -119,7 +120,6 @@
 }
 
 /*
-
 %!assert (isnull ([]), true)
 %!assert (isnull ([1]), false)
 %!assert (isnull (zeros (0,3)), false)
@@ -130,5 +130,4 @@
 %!test
 %! x = [];
 %! assert (isnull (x), false);
-
 */
rename from src/ov-null-mat.h
rename to libinterp/octave-value/ov-null-mat.h
rename from src/ov-oncleanup.cc
rename to libinterp/octave-value/ov-oncleanup.cc
--- a/src/ov-oncleanup.cc
+++ b/libinterp/octave-value/ov-oncleanup.cc
@@ -92,11 +92,6 @@
       // Swallow the interrupt.
       warning ("onCleanup: interrupt occured in cleanup action");
     }
-  catch (std::bad_alloc)
-    {
-      // Swallow the exception.
-      warning ("onCleanup: out of memory occured in cleanup action");
-    }
   catch (...) // Yes, the black hole. We're in a d-tor.
     {
       // This shouldn't happen, in theory.
@@ -108,7 +103,7 @@
   // Otherwise, set it back to what it was before.
   if (error_state)
     {
-      frame.discard_top ();
+      frame.discard_first ();
       octave_call_stack::backtrace_error_message ();
     }
 }
@@ -191,7 +186,7 @@
 
 DEFUN (onCleanup, args, ,
   "-*- texinfo -*-\n\
-@deftypefn {Loadable Function} {@var{c} =} onCleanup (@var{action})\n\
+@deftypefn {Built-in Function} {@var{c} =} onCleanup (@var{action})\n\
 Create a special object that executes a given function upon destruction.\n\
 If the object is copied to multiple variables (or cell or struct array\n\
 elements) or returned from a function, @var{action} will be executed after\n\
@@ -211,17 +206,15 @@
 }
 
 /*
-
 %!test
 %! old_wstate = warning ("query");
 %! unwind_protect
 %!   trigger = onCleanup (@() warning ("on", "__MY_WARNING__"));
 %!   warning ("off", "__MY_WARNING__");
 %!   assert ((warning ("query", "__MY_WARNING__")).state, "off");
-%!   clear trigger
+%!   clear trigger;
 %!   assert ((warning ("query", "__MY_WARNING__")).state, "on");
 %! unwind_protect_cleanup
 %!   warning (old_wstate);
 %! end_unwind_protect
-
 */
rename from src/ov-oncleanup.h
rename to libinterp/octave-value/ov-oncleanup.h
rename from src/ov-perm.cc
rename to libinterp/octave-value/ov-perm.cc
--- a/src/ov-perm.cc
+++ b/libinterp/octave-value/ov-perm.cc
@@ -25,7 +25,9 @@
 #endif
 
 #include "byte-swap.h"
+#include "dim-vector.h"
 
+#include "mxarray.h"
 #include "ov-perm.h"
 #include "ov-re-mat.h"
 #include "ov-scalar.h"
@@ -135,7 +137,7 @@
 
   if (numel () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  type_name (), "real scalar");
 
       retval = matrix (0, 0);
@@ -153,7 +155,7 @@
 
   if (numel () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  type_name (), "real scalar");
 
       retval = matrix (0, 0);
@@ -173,7 +175,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  type_name (), "complex scalar");
 
       retval = matrix (0, 0);
@@ -193,7 +195,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  type_name (), "complex scalar");
 
       retval = matrix (0, 0);
rename from src/ov-perm.h
rename to libinterp/octave-value/ov-perm.h
rename from src/ov-range.cc
rename to libinterp/octave-value/ov-range.cc
--- a/src/ov-range.cc
+++ b/libinterp/octave-value/ov-range.cc
@@ -32,6 +32,7 @@
 #include "defun.h"
 #include "variables.h"
 #include "gripes.h"
+#include "mxarray.h"
 #include "ops.h"
 #include "oct-obj.h"
 #include "ov-range.h"
@@ -175,7 +176,7 @@
 
   if (nel > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "range", "real scalar");
 
       retval = range.base ();
@@ -195,7 +196,7 @@
 
   if (nel > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "range", "real scalar");
 
       retval = range.base ();
@@ -248,6 +249,13 @@
           : octave_value (range.diag (k)));
 }
 
+octave_value
+octave_range::diag (octave_idx_type m, octave_idx_type n) const
+{
+  Matrix mat = range.matrix_value ();
+
+  return mat.diag (m, n);
+}
 
 bool
 octave_range::is_true (void) const
@@ -277,7 +285,7 @@
 
   if (nel > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "range", "complex scalar");
 
       retval = range.base ();
@@ -299,7 +307,7 @@
 
   if (nel > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "range", "complex scalar");
 
       retval = range.base ();
@@ -328,7 +336,7 @@
 {
   NDArray retval = array_value ();
   if (fill)
-    retval.resize (dv, NDArray::resize_fill_value ());
+    retval.resize (dv, 0);
   else
     retval.resize (dv);
   return retval;
@@ -379,6 +387,31 @@
   return retval;
 }
 
+std::string
+octave_range::short_disp (void) const
+{
+  std::ostringstream buf;
+  
+  octave_idx_type len = range.nelem ();
+
+  if (len == 0)
+    buf << "[]";
+  else
+    {
+      buf << range.base () << ":";
+
+      if (len > 1)
+        {
+          if (range.inc () != 1)
+            buf << range.inc () << ":";
+
+          buf << range.limit ();
+        }
+    }
+
+  return buf.str ();
+}
+
 // Skip white space and comments on stream IS.
 
 static void
@@ -670,7 +703,7 @@
 %! warn_state = warning ("query", "Octave:noninteger-range-as-index");
 %! unwind_protect
 %!   allow_noninteger_range_as_index (false);
-%!   fail ('x(2.1:5)');
+%!   fail ("x(2.1:5)");
 %!   assert (x(2:5), 1:4);
 %!   allow_noninteger_range_as_index (true);
 %!   warning ("off", "Octave:noninteger-range-as-index");
rename from src/ov-range.h
rename to libinterp/octave-value/ov-range.h
--- a/src/ov-range.h
+++ b/libinterp/octave-value/ov-range.h
@@ -118,10 +118,10 @@
   size_t byte_size (void) const { return 3 * sizeof (double); }
 
   octave_value reshape (const dim_vector& new_dims) const
-    { return NDArray (array_value().reshape (new_dims)); }
+    { return NDArray (array_value ().reshape (new_dims)); }
 
   octave_value permute (const Array<int>& vec, bool inv = false) const
-    { return NDArray (array_value().permute (vec, inv)); }
+    { return NDArray (array_value ().permute (vec, inv)); }
 
   octave_value squeeze (void) const { return range; }
 
@@ -139,6 +139,8 @@
 
   octave_value diag (octave_idx_type k = 0) const;
 
+  octave_value diag (octave_idx_type m, octave_idx_type n) const;
+
   octave_value sort (octave_idx_type dim = 0, sortmode mode = ASCENDING) const
     { return range.sort (dim, mode); }
 
@@ -253,6 +255,8 @@
 
   bool print_name_tag (std::ostream& os, const std::string& name) const;
 
+  std::string short_disp (void) const;
+
   bool save_ascii (std::ostream& os);
 
   bool load_ascii (std::istream& is);
rename from src/ov-re-diag.cc
rename to libinterp/octave-value/ov-re-diag.cc
--- a/src/ov-re-diag.cc
+++ b/libinterp/octave-value/ov-re-diag.cc
@@ -163,7 +163,7 @@
       return DiagMatrix (matrix.rows (), matrix.cols (), 0.0);
     case umap_sqrt:
       {
-        ComplexColumnVector tmp = matrix.diag ().map<Complex> (rc_sqrt);
+        ComplexColumnVector tmp = matrix.extract_diag ().map<Complex> (rc_sqrt);
         ComplexDiagMatrix retval (tmp);
         retval.resize (matrix.rows (), matrix.columns ());
         return retval;
@@ -181,7 +181,7 @@
   os.write (reinterpret_cast<char *> (&r), 4);
   os.write (reinterpret_cast<char *> (&c), 4);
 
-  Matrix m = Matrix (matrix.diag ());
+  Matrix m = Matrix (matrix.extract_diag ());
   save_type st = LS_DOUBLE;
   if (save_as_floats)
     {
rename from src/ov-re-diag.h
rename to libinterp/octave-value/ov-re-diag.h
rename from src/ov-re-mat.cc
rename to libinterp/octave-value/ov-re-mat.cc
--- a/src/ov-re-mat.cc
+++ b/libinterp/octave-value/ov-re-mat.cc
@@ -25,9 +25,8 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 #include <vector>
 
 #include "data-conv.h"
@@ -42,6 +41,7 @@
 
 #include "defun.h"
 #include "gripes.h"
+#include "mxarray.h"
 #include "oct-obj.h"
 #include "oct-lvalue.h"
 #include "oct-stream.h"
@@ -68,10 +68,6 @@
 #include "ls-utils.h"
 #include "ls-hdf5.h"
 
-#if ! defined (UCHAR_MAX)
-#define UCHAR_MAX 255
-#endif
-
 template class octave_base_matrix<NDArray>;
 
 DEFINE_OCTAVE_ALLOCATOR (octave_matrix);
@@ -89,8 +85,8 @@
 octave_base_value::type_conv_info
 octave_matrix::numeric_demotion_function (void) const
 {
-  return octave_base_value::type_conv_info(default_numeric_demotion_function,
-                                           octave_float_matrix::static_type_id ());
+  return octave_base_value::type_conv_info (default_numeric_demotion_function,
+                                            octave_float_matrix::static_type_id ());
 }
 
 octave_base_value *
@@ -111,7 +107,7 @@
 
   if (numel () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "real matrix", "real scalar");
 
       retval = matrix (0, 0);
@@ -129,7 +125,7 @@
 
   if (numel () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "real matrix", "real scalar");
 
       retval = matrix (0, 0);
@@ -163,7 +159,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "real matrix", "complex scalar");
 
       retval = matrix (0, 0);
@@ -183,7 +179,7 @@
 
   if (rows () > 0 && columns () > 0)
     {
-      gripe_implicit_conversion ("Octave:array-as-scalar",
+      gripe_implicit_conversion ("Octave:array-to-scalar",
                                  "real matrix", "complex scalar");
 
       retval = matrix (0, 0);
@@ -272,6 +268,24 @@
   return retval;
 }
 
+octave_value
+octave_matrix::diag (octave_idx_type m, octave_idx_type n) const
+{
+  octave_value retval;
+
+  if (matrix.ndims () == 2
+      && (matrix.rows () == 1 || matrix.columns () == 1))
+    {
+      Matrix mat = matrix.matrix_value ();
+
+      retval = mat.diag (m, n);
+    }
+  else
+    error ("diag: expecting vector argument");
+
+  return retval;
+}
+
 // We override these two functions to allow reshaping both
 // the matrix and the index cache.
 octave_value
@@ -391,7 +405,7 @@
         {
           int ival = NINT (d);
 
-          if (ival < 0 || ival > UCHAR_MAX)
+          if (ival < 0 || ival > std::numeric_limits<unsigned char>::max ())
             {
               // FIXME -- is there something
               // better we could do?
@@ -543,11 +557,11 @@
 {
 
   dim_vector d = dims ();
-  if (d.length() < 1)
+  if (d.length () < 1)
     return false;
 
   // Use negative value for ndims to differentiate with old format!!
-  int32_t tmp = - d.length();
+  int32_t tmp = - d.length ();
   os.write (reinterpret_cast<char *> (&tmp), 4);
   for (int i = 0; i < d.length (); i++)
     {
@@ -729,7 +743,7 @@
   dim_vector dv;
   int empty = load_hdf5_empty (loc_id, name, dv);
   if (empty > 0)
-    matrix.resize(dv);
+    matrix.resize (dv);
   if (empty)
       return (empty > 0);
 
@@ -889,8 +903,11 @@
       RC_ARRAY_MAPPER (atanh, Complex, rc_atanh);
       ARRAY_MAPPER (erf, double, ::erf);
       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);
       RC_ARRAY_MAPPER (lgamma, Complex, rc_lgamma);
       ARRAY_MAPPER (cbrt, double, ::cbrt);
@@ -914,6 +931,7 @@
       ARRAY_MAPPER (tan, double, ::tan);
       ARRAY_MAPPER (tanh, double, ::tanh);
       ARRAY_MAPPER (isna, bool, octave_is_NA);
+      ARRAY_MAPPER (xsignbit, double, xsignbit);
 
     default:
       if (umap >= umap_xisalnum && umap <= umap_xtoupper)
@@ -981,7 +999,6 @@
 }
 
 /*
-
 %!assert (class (double (single (1))), "double")
 %!assert (class (double (single (1 + i))), "double")
 %!assert (class (double (int8 (1))), "double")
@@ -1010,5 +1027,4 @@
 %! y = double (x);
 %! assert (class (x), "single");
 %! assert (class (y), "double");
-
 */
rename from src/ov-re-mat.h
rename to libinterp/octave-value/ov-re-mat.h
--- a/src/ov-re-mat.h
+++ b/libinterp/octave-value/ov-re-mat.h
@@ -178,6 +178,8 @@
 
   octave_value diag (octave_idx_type k = 0) const;
 
+  octave_value diag (octave_idx_type m, octave_idx_type n) const;
+
   octave_value reshape (const dim_vector& new_dims) const;
 
   octave_value squeeze (void) const;
rename from src/ov-re-sparse.cc
rename to libinterp/octave-value/ov-re-sparse.cc
--- a/src/ov-re-sparse.cc
+++ b/libinterp/octave-value/ov-re-sparse.cc
@@ -25,15 +25,15 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 #include <vector>
 
 #include "lo-specfun.h"
 #include "lo-mappers.h"
 #include "oct-locbuf.h"
 
+#include "mxarray.h"
 #include "ov-base.h"
 #include "ov-scalar.h"
 #include "gripes.h"
@@ -100,7 +100,7 @@
   if (numel () > 0)
     {
       if (numel () > 1)
-        gripe_implicit_conversion ("Octave:array-as-scalar",
+        gripe_implicit_conversion ("Octave:array-to-scalar",
                                    "real sparse matrix", "real scalar");
 
       retval = matrix (0, 0);
@@ -122,7 +122,7 @@
   if (rows () > 0 && columns () > 0)
     {
       if (numel () > 1)
-        gripe_implicit_conversion ("Octave:array-as-scalar",
+        gripe_implicit_conversion ("Octave:array-to-scalar",
                                    "real sparse matrix", "complex scalar");
 
       retval = matrix (0, 0);
@@ -160,8 +160,8 @@
   octave_idx_type nr = matrix.rows ();
 
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = matrix.cidx(j); i < matrix.cidx(j+1); i++)
-      retval(matrix.ridx(i) + nr * j) = static_cast<char>(matrix.data (i));
+    for (octave_idx_type i = matrix.cidx (j); i < matrix.cidx (j+1); i++)
+      retval(matrix.ridx (i) + nr * j) = static_cast<char>(matrix.data (i));
 
   return retval;
 }
@@ -216,8 +216,8 @@
       bool warned = false;
 
       for (octave_idx_type j = 0; j < nc; j++)
-        for (octave_idx_type i = matrix.cidx(j);
-             i < matrix.cidx(j+1); i++)
+        for (octave_idx_type i = matrix.cidx (j);
+             i < matrix.cidx (j+1); i++)
           {
             octave_quit ();
 
@@ -232,7 +232,7 @@
                 {
                   int ival = NINT (d);
 
-                  if (ival < 0 || ival > UCHAR_MAX)
+                  if (ival < 0 || ival > std::numeric_limits<unsigned char>::max ())
                     {
                       // FIXME -- is there something
                       // better we could do?
@@ -246,7 +246,7 @@
                         }
                     }
 
-                  chm (matrix.ridx(i) + j * nr) =
+                  chm (matrix.ridx (i) + j * nr) =
                     static_cast<char> (ival);
                 }
           }
@@ -261,7 +261,7 @@
 octave_sparse_matrix::save_binary (std::ostream& os, bool&save_as_floats)
 {
   dim_vector d = this->dims ();
-  if (d.length() < 1)
+  if (d.length () < 1)
     return false;
 
   // Ensure that additional memory is deallocated
@@ -308,18 +308,18 @@
    for (int i = 0; i < nc+1; i++)
      {
        octave_quit ();
-       itmp = matrix.cidx(i);
+       itmp = matrix.cidx (i);
        os.write (reinterpret_cast<char *> (&itmp), 4);
      }
 
    for (int i = 0; i < nz; i++)
      {
        octave_quit ();
-       itmp = matrix.ridx(i);
+       itmp = matrix.ridx (i);
        os.write (reinterpret_cast<char *> (&itmp), 4);
      }
 
-   write_doubles (os, matrix.data(), st, nz);
+   write_doubles (os, matrix.data (), st, nz);
 
   return true;
 }
@@ -367,7 +367,7 @@
         return false;
       if (swap)
         swap_bytes<4> (&tmp);
-      m.xcidx(i) = tmp;
+      m.xcidx (i) = tmp;
     }
 
   for (int i = 0; i < nz; i++)
@@ -377,7 +377,7 @@
         return false;
       if (swap)
         swap_bytes<4> (&tmp);
-      m.xridx(i) = tmp;
+      m.xridx (i) = tmp;
     }
 
   if (! is.read (reinterpret_cast<char *> (&ctmp), 1))
@@ -506,7 +506,7 @@
 
   H5Sclose (space_hid);
 
-  hdims[0] = m.cols() + 1;
+  hdims[0] = m.cols () + 1;
   hdims[1] = 1;
 
   space_hid = H5Screate_simple (2, hdims, 0);
@@ -637,7 +637,7 @@
   dim_vector dv;
   int empty = load_hdf5_empty (loc_id, name, dv);
   if (empty > 0)
-    matrix.resize(dv);
+    matrix.resize (dv);
   if (empty)
     return (empty > 0);
 
@@ -857,22 +857,22 @@
 mxArray *
 octave_sparse_matrix::as_mxArray (void) const
 {
-  mwSize nz = nzmax();
-  mwSize nr = rows();
-  mwSize nc = columns();
+  mwSize nz = nzmax ();
+  mwSize nr = rows ();
+  mwSize nc = columns ();
   mxArray *retval = new mxArray (mxDOUBLE_CLASS, nr, nc, nz, mxREAL);
   double *pr = static_cast<double *> (retval->get_data ());
-  mwIndex *ir = retval->get_ir();
-  mwIndex *jc = retval->get_jc();
+  mwIndex *ir = retval->get_ir ();
+  mwIndex *jc = retval->get_jc ();
 
   for (mwIndex i = 0; i < nz; i++)
     {
-      pr[i] = matrix.data(i);
-      ir[i] = matrix.ridx(i);
+      pr[i] = matrix.data (i);
+      ir[i] = matrix.ridx (i);
     }
 
   for (mwIndex i = 0; i < nc + 1; i++)
-    jc[i] = matrix.cidx(i);
+    jc[i] = matrix.cidx (i);
 
   return retval;
 }
@@ -910,7 +910,11 @@
       ARRAY_MAPPER (atanh, Complex, rc_atanh);
       ARRAY_MAPPER (erf, double, ::erf);
       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);
rename from src/ov-re-sparse.h
rename to libinterp/octave-value/ov-re-sparse.h
rename from src/ov-scalar.cc
rename to libinterp/octave-value/ov-scalar.cc
--- a/src/ov-scalar.cc
+++ b/libinterp/octave-value/ov-scalar.cc
@@ -33,6 +33,7 @@
 
 #include "defun.h"
 #include "gripes.h"
+#include "mxarray.h"
 #include "oct-obj.h"
 #include "oct-stream.h"
 #include "ov-scalar.h"
@@ -67,8 +68,8 @@
 octave_base_value::type_conv_info
 octave_scalar::numeric_demotion_function (void) const
 {
-  return octave_base_value::type_conv_info(default_numeric_demotion_function,
-                                           octave_float_scalar::static_type_id ());
+  return octave_base_value::type_conv_info (default_numeric_demotion_function,
+                                            octave_float_scalar::static_type_id ());
 }
 
 octave_value
@@ -94,7 +95,7 @@
 {
   if (fill)
     {
-      NDArray retval (dv, NDArray::resize_fill_value());
+      NDArray retval (dv, 0);
 
       if (dv.numel ())
         retval(0) = scalar;
@@ -113,6 +114,12 @@
 }
 
 octave_value
+octave_scalar::diag (octave_idx_type m, octave_idx_type n) const
+{
+  return DiagMatrix (Array<double> (dim_vector (1, 1), scalar), m, n);
+}
+
+octave_value
 octave_scalar::convert_to_str_internal (bool, bool, char type) const
 {
   octave_value retval;
@@ -123,7 +130,7 @@
     {
       int ival = NINT (scalar);
 
-      if (ival < 0 || ival > UCHAR_MAX)
+      if (ival < 0 || ival > std::numeric_limits<unsigned char>::max ())
         {
           // FIXME -- is there something better we could do?
 
@@ -301,8 +308,11 @@
       SCALAR_MAPPER (atanh, rc_atanh);
       SCALAR_MAPPER (erf, ::erf);
       SCALAR_MAPPER (erfinv, ::erfinv);
+      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);
@@ -329,6 +339,7 @@
       SCALAR_MAPPER (isinf, xisinf);
       SCALAR_MAPPER (isna, octave_is_NA);
       SCALAR_MAPPER (isnan, xisnan);
+      SCALAR_MAPPER (xsignbit, xsignbit);
 
     default:
       if (umap >= umap_xisalnum && umap <= umap_xtoupper)
rename from src/ov-scalar.h
rename to libinterp/octave-value/ov-scalar.h
--- a/src/ov-scalar.h
+++ b/libinterp/octave-value/ov-scalar.h
@@ -212,6 +212,8 @@
     return boolNDArray (dim_vector (1, 1), scalar);
   }
 
+  octave_value diag (octave_idx_type m, octave_idx_type n) const;
+
   octave_value convert_to_str_internal (bool pad, bool force, char type) const;
 
   void increment (void) { ++scalar; }
rename from src/ov-str-mat.cc
rename to libinterp/octave-value/ov-str-mat.cc
--- a/src/ov-str-mat.cc
+++ b/libinterp/octave-value/ov-str-mat.cc
@@ -143,7 +143,7 @@
 {
   charNDArray retval (matrix);
   if (fill)
-    retval.resize (dv, charNDArray::resize_fill_value ());
+    retval.resize (dv, 0);
   else
     retval.resize (dv);
   return octave_value (retval, is_sq_string () ? '\'' : '"');
@@ -252,7 +252,7 @@
       octave_idx_type nr = chm.rows ();
       retval.clear (nr, 1);
       for (octave_idx_type i = 0; i < nr; i++)
-        retval.xelem(i) = chm.row_as_string (i);
+        retval.xelem (i) = chm.row_as_string (i);
     }
   else
     error ("cellstr: cannot convert multidimensional arrays");
@@ -465,11 +465,11 @@
                                      bool& /* save_as_floats */)
 {
   dim_vector d = dims ();
-  if (d.length() < 1)
+  if (d.length () < 1)
     return false;
 
   // Use negative value for ndims to differentiate with old format!!
-  int32_t tmp = - d.length();
+  int32_t tmp = - d.length ();
   os.write (reinterpret_cast<char *> (&tmp), 4);
   for (int i=0; i < d.length (); i++)
     {
@@ -615,7 +615,7 @@
   dim_vector dv;
   int empty = load_hdf5_empty (loc_id, name, dv);
   if (empty > 0)
-    matrix.resize(dv);
+    matrix.resize (dv);
   if (empty)
     return (empty > 0);
 
rename from src/ov-str-mat.h
rename to libinterp/octave-value/ov-str-mat.h
rename from src/ov-struct.cc
rename to libinterp/octave-value/ov-struct.cc
--- a/src/ov-struct.cc
+++ b/libinterp/octave-value/ov-struct.cc
@@ -30,6 +30,7 @@
 #include "defun.h"
 #include "error.h"
 #include "gripes.h"
+#include "mxarray.h"
 #include "oct-lvalue.h"
 #include "ov-struct.h"
 #include "unwind-prot.h"
@@ -84,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;
 }
@@ -115,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,
@@ -154,7 +172,7 @@
 
     case '.':
       {
-        if (map.numel() > 0)
+        if (map.numel () > 0)
           {
             const Cell t = dotref (idx.front ());
 
@@ -220,7 +238,7 @@
 
     case '.':
       {
-        if (map.numel() > 0)
+        if (map.numel () > 0)
           {
             const Cell t = dotref (idx.front (), auto_add);
 
@@ -249,7 +267,8 @@
 
 /*
 %!test
-%! x(1).a.a = 1; x(2).a.a = 2;
+%! x(1).a.a = 1;
+%! x(2).a.a = 2;
 %! assert (size (x), [1, 2]);
 %! assert (x(1).a.a, 1);
 %! assert (x(2).a.a, 2);
@@ -303,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
@@ -361,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 ());
@@ -429,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 ())
@@ -480,7 +514,7 @@
               }
             else
               {
-                if (t_rhs.is_map() || t_rhs.is_object ())
+                if (t_rhs.is_map () || t_rhs.is_object ())
                   {
                     octave_map rhs_map = t_rhs.map_value ();
 
@@ -501,9 +535,9 @@
                   }
                 else
                   {
-                    if (t_rhs.is_null_value())
+                    if (t_rhs.is_null_value ())
                       {
-                        map.delete_elements (idx.front());
+                        map.delete_elements (idx.front ());
 
                         if (! error_state)
                           {
@@ -528,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 ());
@@ -691,25 +730,6 @@
   return dims.length () == 2 && dims (0) == 1 && dims (1) == 1;
 }
 
-/*
-%!shared x
-%! x(1).a=1; x(2).a=2; x(1).b=3; x(2).b=3;
-%!assert(struct('a',1,'b',3),x(1))
-%!assert(isempty(x([])))
-%!assert(isempty(struct('a',{},'b',{})))
-%!assert(struct('a',{1,2},'b',{3,3}),x)
-%!assert(struct('a',{1,2},'b',3),x)
-%!assert(struct('a',{1,2},'b',{3}),x)
-%!assert(struct('b',3,'a',{1,2}),x)
-%!assert(struct('b',{3},'a',{1,2}),x)
-%!test x=struct([]);
-%!assert(size(x),[0,0]);
-%!assert(isstruct(x));
-%!assert(isempty(fieldnames(x)));
-%!fail("struct('a',{1,2},'b',{1,2,3})","dimensions of parameter 2 do not match those of parameter 4")
-%!fail("struct(1,2,3,4)","struct: expecting alternating \"field\", VALUE pairs");
-%!fail("struct('1',2,'3')","struct: expecting alternating \"field\", VALUE pairs");
-*/
 
 bool
 octave_struct::save_ascii (std::ostream& os)
@@ -841,7 +861,7 @@
     return false;
 
   // Use negative value for ndims
-  int32_t di = - d.length();
+  int32_t di = - d.length ();
   os.write (reinterpret_cast<char *> (&di), 4);
   for (int i = 0; i < d.length (); i++)
     {
@@ -1097,7 +1117,7 @@
       // itself.
       const octave_scalar_map *sm_ptr;
       void *here = reinterpret_cast<void *>(&sm_ptr);
-      return (x.get_rep().fast_elem_insert_self (here, btyp_struct)
+      return (x.get_rep ().fast_elem_insert_self (here, btyp_struct)
               && map.fast_elem_insert (n, *sm_ptr));
     }
 
@@ -1110,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;
 }
@@ -1189,7 +1217,8 @@
 
 /*
 %!test
-%! x(1).a.a = 1; x(2).a.a = 2;
+%! x(1).a.a = 1;
+%! x(2).a.a = 2;
 %! assert (size (x), [1, 2]);
 %! assert (x(1).a.a, 1);
 %! assert (x(2).a.a, 2);
@@ -1234,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);
@@ -1712,31 +1746,15 @@
   else
     return false;
 }
-/*
-%!shared x
-%! x(1).a=1; x(2).a=2; x(1).b=3; x(2).b=3;
-%!assert(struct('a',1,'b',3),x(1))
-%!assert(isempty(x([])))
-%!assert(isempty(struct('a',{},'b',{})))
-%!assert(struct('a',{1,2},'b',{3,3}),x)
-%!assert(struct('a',{1,2},'b',3),x)
-%!assert(struct('a',{1,2},'b',{3}),x)
-%!assert(struct('b',3,'a',{1,2}),x)
-%!assert(struct('b',{3},'a',{1,2}),x)
-%!test x=struct([]);
-%!assert(size(x),[0,0]);
-%!assert(isstruct(x));
-%!assert(isempty(fieldnames(x)));
-%!fail("struct('a',{1,2},'b',{1,2,3})","dimensions of parameter 2 do not match those of parameter 4")
-%!fail("struct(1,2,3,4)","struct: expecting alternating \"field\", VALUE pairs");
-%!fail("struct('1',2,'3')","struct: expecting alternating \"field\", VALUE pairs");
-*/
 
 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\
@@ -1745,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;
@@ -1840,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
@@ -1874,6 +1926,26 @@
   return octave_value (map);
 }
 
+/*
+%!shared x
+%! x(1).a=1;  x(2).a=2;  x(1).b=3;  x(2).b=3;
+%!assert (struct ("a",1, "b",3), x(1))
+%!assert (isempty (x([])))
+%!assert (isempty (struct ("a",{}, "b",{})))
+%!assert (struct ("a",{1,2}, "b",{3,3}), x)
+%!assert (struct ("a",{1,2}, "b",3), x)
+%!assert (struct ("a",{1,2}, "b",{3}), x)
+%!assert (struct ("b",3, "a",{1,2}), x)
+%!assert (struct ("b",{3}, "a",{1,2}), x)
+%!test x = struct ([]);
+%!assert (size (x), [0,0])
+%!assert (isstruct (x))
+%!assert (isempty (fieldnames (x)))
+%!fail ('struct ("a",{1,2},"b",{1,2,3})', 'dimensions of parameter 2 do not match those of parameter 4')
+%!fail ('struct (1,2,3,4)', 'struct: expecting alternating "field", VALUE pairs')
+%!fail ('struct ("1",2,"3")', 'struct: expecting alternating "field", VALUE pairs')
+*/
+
 DEFUN (isstruct, args, ,
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {} isstruct (@var{x})\n\
@@ -1891,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\
@@ -2012,15 +2068,15 @@
 }
 
 /*
-%!# test isfield
+## test isfield
 %!test
-%!  x(3).d=1; x(2).a=2; x(1).b=3; x(2).c=3;
-%!  assert (isfield (x, 'b'));
-%!assert (isfield (struct('a', '1'), 'a'));
-%!assert (isfield ({1}, 'c'), false);
-%!assert (isfield (struct('a', '1'), 10), false);
-%!assert (isfield (struct('a', 'b'), "a "), false);
-%!assert (isfield (struct('a', 1, 'b', 2), {'a', 'c'}), [true, false]);
+%! x(3).d=1;  x(2).a=2;  x(1).b=3;  x(2).c=3;
+%! assert (isfield (x, "b"));
+%!assert (isfield (struct ("a", "1"), "a"))
+%!assert (isfield ({1}, "c"), false)
+%!assert (isfield (struct ("a", "1"), 10), false)
+%!assert (isfield (struct ("a", "b"), "a "), false)
+%!assert (isfield (struct ("a", 1, "b", 2), {"a", "c"}), [true, false])
 */
 
 DEFUN (cell2struct, args, ,
@@ -2033,15 +2089,15 @@
 \n\
 @example\n\
 @group\n\
-A = cell2struct (@{'Peter', 'Hannah', 'Robert';\n\
+A = cell2struct (@{\"Peter\", \"Hannah\", \"Robert\";\n\
                    185, 170, 168@},\n\
-                 @{'Name','Height'@}, 1);\n\
+                 @{\"Name\",\"Height\"@}, 1);\n\
 A(1)\n\
-     @result{} ans =\n\
-        @{\n\
-          Name   = Peter\n\
-          Height = 185\n\
-        @}\n\
+   @result{}\n\
+      @{\n\
+        Name   = Peter\n\
+        Height = 185\n\
+      @}\n\
 \n\
 @end group\n\
 @end example\n\
@@ -2138,15 +2194,15 @@
 }
 
 /*
-%!# test cell2struct versus struct2cell
+## test cell2struct versus struct2cell
 %!test
-%!  keys = cellstr (char (floor (rand (100,10)*24+65)))';
-%!  vals = mat2cell(rand (100,1), ones (100,1), 1)';
-%!  s = struct ([keys; vals]{:});
-%!  t = cell2struct (vals, keys, 2);
-%!  assert (s, t);
-%!  assert (struct2cell (s), vals');
-%!  assert (fieldnames (s), keys');
+%! keys = cellstr (char (floor (rand (100,10)*24+65)))';
+%! vals = mat2cell (rand (100,1), ones (100,1), 1)';
+%! s = struct ([keys; vals]{:});
+%! t = cell2struct (vals, keys, 2);
+%! assert (s, t);
+%! assert (struct2cell (s), vals');
+%! assert (fieldnames (s), keys');
 
 %!assert (cell2struct ({1; 2}, {"a"; "b"}), struct ("a", 1, "b", 2));
 
@@ -2159,10 +2215,11 @@
 
 DEFUN (rmfield, args, ,
        "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {} rmfield (@var{s}, @var{f})\n\
+@deftypefn  {Built-in Function} {@var{s} =} rmfield (@var{s}, \"@var{f}\")\n\
+@deftypefnx {Built-in Function} {@var{s} =} rmfield (@var{s}, @var{f})\n\
 Return a copy of the structure (array) @var{s} with the field @var{f}\n\
 removed.  If @var{f} is a cell array of strings or a character array, remove\n\
-the named fields.\n\
+each of the named fields.\n\
 @seealso{cellstr, iscellstr, setfield}\n\
 @end deftypefn")
 {
@@ -2206,12 +2263,18 @@
 }
 
 /*
-%!# test rmfield
+## test rmfield
+%!shared x
+%! x(3).d=1;  x(2).a=2;  x(1).b=3;  x(2).c=3;  x(6).f="abc123";
+%!
 %!test
-%!  x(3).d=1; x(2).a=2; x(1).b=3; x(2).c=3; x(6).f="abc123";
-%!  y = rmfield (x, {"a", "f"});
-%!  assert (fieldnames (y), {"d"; "b"; "c"});
-%!  assert (size (y), [1, 6]);
+%! y = rmfield (x, "c");
+%! assert (fieldnames (y), {"d"; "a"; "b"; "f"});
+%! assert (size (y), [1, 6]);
+%!test
+%! y = rmfield (x, {"a", "f"});
+%! assert (fieldnames (y), {"d"; "b"; "c"});
+%! assert (size (y), [1, 6]);
 */
 
 DEFUN (struct_levels_to_print, args, nargout,
@@ -2227,8 +2290,8 @@
 variable value is restored when exiting the function.\n\
 @end deftypefn")
 {
-  return SET_INTERNAL_VARIABLE_WITH_LIMITS (struct_levels_to_print,
-                                            -1, INT_MAX);
+  return SET_INTERNAL_VARIABLE_WITH_LIMITS (struct_levels_to_print, -1,
+                                            std::numeric_limits<int>::max ());
 }
 
 DEFUN (print_struct_array_contents, args, nargout,
rename from src/ov-struct.h
rename to libinterp/octave-value/ov-struct.h
rename from src/ov-type-conv.h
rename to libinterp/octave-value/ov-type-conv.h
rename from src/ov-typeinfo.cc
rename to libinterp/octave-value/ov-typeinfo.cc
--- a/src/ov-typeinfo.cc
+++ b/libinterp/octave-value/ov-typeinfo.cc
@@ -620,72 +620,97 @@
 }
 
 /*
-%!error typeinfo ("foo", 1);
+%!assert (iscellstr (typeinfo ()))
 
-%!assert (iscellstr (typeinfo ()));
+%!assert (typeinfo ({"cell"}), "cell")
 
-%!assert (typeinfo (false), "bool");
-%!assert (typeinfo ([true, false]), "bool matrix");
-
-%!assert (typeinfo (1:2), "range");
+%!assert (typeinfo (1), "scalar")
+%!assert (typeinfo (double (1)), "scalar")
+%!assert (typeinfo (i), "complex scalar")
 
-%!assert (typeinfo ("string"), "string");
-%!assert (typeinfo ('string'), "sq_string");
-
+%!assert (typeinfo ([1, 2]), "matrix")
+%!assert (typeinfo (double ([1, 2])), "matrix")
 %!assert (typeinfo (diag ([1, 2])), "diagonal matrix")
+%!assert (typeinfo ([i, 2]), "complex matrix")
 %!assert (typeinfo (diag ([i, 2])), "complex diagonal matrix")
-%!assert (typeinfo (single (diag ([1, 2]))), "float diagonal matrix")
-%!assert (typeinfo (single (diag ([i, 2]))), "float complex diagonal matrix")
-%!assert (typeinfo (diag (single ([1, 2]))), "float diagonal matrix")
-%!assert (typeinfo (diag (single ([i, 2]))), "float complex diagonal matrix")
+
+%!assert (typeinfo (1:2), "range")
 
-%!assert (typeinfo ([]), "null_matrix");
-%!assert (typeinfo (""), "null_string");
-%!assert (typeinfo (''), "null_sq_string");
+%!assert (typeinfo (false), "bool")
+%!assert (typeinfo ([true, false]), "bool matrix")
+
+%!assert (typeinfo ("string"), "string")
+%!assert (typeinfo ('string'), "sq_string")
 
-%!assert (typeinfo (1), "scalar");
-%!assert (typeinfo (double (1)), "scalar");
-%!assert (typeinfo ([1, 2]), "matrix");
-%!assert (typeinfo (double ([1, 2])), "matrix");
-
-%!assert (typeinfo (i), "complex scalar");
-%!assert (typeinfo ([i, 2]), "complex matrix");
-
-%!assert (typeinfo (single (1)), "float scalar");
-%!assert (typeinfo (single ([1, 2])), "float matrix");
+%!assert (typeinfo (int8 (1)), "int8 scalar")
+%!assert (typeinfo (int16 (1)), "int16 scalar")
+%!assert (typeinfo (int32 (1)), "int32 scalar")
+%!assert (typeinfo (int64 (1)), "int64 scalar")
+%!assert (typeinfo (uint8 (1)), "uint8 scalar")
+%!assert (typeinfo (uint16 (1)), "uint16 scalar")
+%!assert (typeinfo (uint32 (1)), "uint32 scalar")
+%!assert (typeinfo (uint64 (1)), "uint64 scalar")
 
-%!assert (typeinfo (single (i)), "float complex scalar");
-%!assert (typeinfo (single ([i, 2])), "float complex matrix");
-
-%!assert (typeinfo (sparse (eye (10))), "sparse matrix");
-%!assert (typeinfo (sparse (i * eye (10))), "sparse complex matrix");
-%!assert (typeinfo (logical (sparse (i * eye (10)))), "sparse bool matrix");
+%!assert (typeinfo (int8 ([1,2])), "int8 matrix")
+%!assert (typeinfo (int16 ([1,2])), "int16 matrix")
+%!assert (typeinfo (int32 ([1,2])), "int32 matrix")
+%!assert (typeinfo (int64 ([1,2])), "int64 matrix")
+%!assert (typeinfo (uint8 ([1,2])), "uint8 matrix")
+%!assert (typeinfo (uint16 ([1,2])), "uint16 matrix")
+%!assert (typeinfo (uint32 ([1,2])), "uint32 matrix")
+%!assert (typeinfo (uint64 ([1,2])), "uint64 matrix")
 
-%!assert (typeinfo (int8 (1)), "int8 scalar");
-%!assert (typeinfo (int16 (1)), "int16 scalar");
-%!assert (typeinfo (int32 (1)), "int32 scalar");
-%!assert (typeinfo (int64 (1)), "int64 scalar");
-%!assert (typeinfo (uint8 (1)), "uint8 scalar");
-%!assert (typeinfo (uint16 (1)), "uint16 scalar");
-%!assert (typeinfo (uint32 (1)), "uint32 scalar");
-%!assert (typeinfo (uint64 (1)), "uint64 scalar");
+%!assert (typeinfo (sparse ([true, false])), "sparse bool matrix")
+%!assert (typeinfo (logical (sparse (i * eye (10)))), "sparse bool matrix")
+%!assert (typeinfo (sparse ([1,2])), "sparse matrix")
+%!assert (typeinfo (sparse (eye (10))), "sparse matrix")
+%!assert (typeinfo (sparse ([i,2])), "sparse complex matrix")
+%!assert (typeinfo (sparse (i * eye (10))), "sparse complex matrix")
+
+%!test
+%! s(2).a = 1;
+%! assert (typeinfo (s), "struct");
 
 %!test
 %! s.a = 1;
 %! assert (typeinfo (s), "scalar struct");
 
-%!test
-%! s(2).a = 1;
-%! assert (typeinfo (s), "struct");
+## FIXME: This doesn't work as a test for comma-separated list
+%!#test
+%! clist = {1, 2, 3};
+%! assert (typeinfo (clist{:}), "cs-list");
 
-%!assert (typeinfo ({"cell"}), "cell");
+%!assert (typeinfo (@sin), "function handle")
+%!assert (typeinfo (@(x) x), "function handle")
+
+%!assert (typeinfo (inline ("x^2")), "inline function")
 
-%!assert (typeinfo (@sin), "function handle");
-%!assert (typeinfo (@(x) x), "function handle");
+%!assert (typeinfo (single (1)), "float scalar")
+%!assert (typeinfo (single (i)), "float complex scalar")
+%!assert (typeinfo (single ([1, 2])), "float matrix")
 
-%!assert (typeinfo (inline ('x^2')), "inline function");
+%!assert (typeinfo (single (diag ([1, 2]))), "float diagonal matrix")
+%!assert (typeinfo (diag (single ([1, 2]))), "float diagonal matrix")
+%!assert (typeinfo (single (diag ([i, 2]))), "float complex diagonal matrix")
+%!assert (typeinfo (diag (single ([i, 2]))), "float complex diagonal matrix")
 
+%!assert (typeinfo (eye(3)(:,[1 3 2])), "permutation matrix")
 %!test
 %! [l, u, p] = lu (rand (3));
 %! assert (typeinfo (p), "permutation matrix");
+
+%!assert (typeinfo ([]), "null_matrix")
+%!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)
 */
rename from src/ov-typeinfo.h
rename to libinterp/octave-value/ov-typeinfo.h
rename from src/ov-uint16.cc
rename to libinterp/octave-value/ov-uint16.cc
--- a/src/ov-uint16.cc
+++ b/libinterp/octave-value/ov-uint16.cc
@@ -24,9 +24,8 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 
 #include "lo-ieee.h"
 #include "lo-utils.h"
@@ -84,13 +83,10 @@
 }
 
 /*
-
 %!assert (class (uint16 (1)), "uint16")
 %!assert (uint16 (1.25), uint16 (1))
 %!assert (uint16 (1.5), uint16 (2))
 %!assert (uint16 (-1.5), uint16 (0))
 %!assert (uint16 (2^17), uint16 (2^16-1))
 %!assert (uint16 (-2^17), uint16 (0))
-
 */
-
rename from src/ov-uint16.h
rename to libinterp/octave-value/ov-uint16.h
rename from src/ov-uint32.cc
rename to libinterp/octave-value/ov-uint32.cc
--- a/src/ov-uint32.cc
+++ b/libinterp/octave-value/ov-uint32.cc
@@ -24,9 +24,8 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 
 #include "lo-ieee.h"
 #include "lo-utils.h"
@@ -84,12 +83,10 @@
 }
 
 /*
-
 %!assert (class (uint32 (1)), "uint32")
 %!assert (uint32 (1.25), uint32 (1))
 %!assert (uint32 (1.5), uint32 (2))
 %!assert (uint32 (-1.5), uint32 (0))
 %!assert (uint32 (2^33), uint32 (2^32-1))
 %!assert (uint32 (-2^33), uint32 (0))
-
 */
rename from src/ov-uint32.h
rename to libinterp/octave-value/ov-uint32.h
rename from src/ov-uint64.cc
rename to libinterp/octave-value/ov-uint64.cc
--- a/src/ov-uint64.cc
+++ b/libinterp/octave-value/ov-uint64.cc
@@ -24,9 +24,8 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 
 #include "lo-ieee.h"
 #include "lo-utils.h"
@@ -84,12 +83,10 @@
 }
 
 /*
-
 %!assert (class (uint64 (1)), "uint64")
 %!assert (uint64 (1.25), uint64 (1))
 %!assert (uint64 (1.5), uint64 (2))
 %!assert (uint64 (-1.5), uint64 (0))
 %!assert (uint64 (2^65), uint64 (2^64-1))
 %!assert (uint64 (-2^65), uint64 (0))
-
 */
rename from src/ov-uint64.h
rename to libinterp/octave-value/ov-uint64.h
rename from src/ov-uint8.cc
rename to libinterp/octave-value/ov-uint8.cc
--- a/src/ov-uint8.cc
+++ b/libinterp/octave-value/ov-uint8.cc
@@ -24,9 +24,8 @@
 #include <config.h>
 #endif
 
-#include <climits>
-
 #include <iostream>
+#include <limits>
 
 #include "lo-ieee.h"
 #include "lo-utils.h"
@@ -84,12 +83,10 @@
 }
 
 /*
-
 %!assert (class (uint8 (1)), "uint8")
 %!assert (uint8 (1.25), uint8 (1))
 %!assert (uint8 (1.5), uint8 (2))
 %!assert (uint8 (-1.5), uint8 (0))
 %!assert (uint8 (2^9), uint8 (2^8-1))
 %!assert (uint8 (-2^9), uint8 (0))
-
 */
rename from src/ov-uint8.h
rename to libinterp/octave-value/ov-uint8.h
rename from src/ov-usr-fcn.cc
rename to libinterp/octave-value/ov-usr-fcn.cc
--- a/src/ov-usr-fcn.cc
+++ b/libinterp/octave-value/ov-usr-fcn.cc
@@ -30,6 +30,7 @@
 
 #include <defaults.h>
 #include "Cell.h"
+#include "builtins.h"
 #include "defun.h"
 #include "error.h"
 #include "gripes.h"
@@ -39,6 +40,7 @@
 #include "ov.h"
 #include "pager.h"
 #include "pt-eval.h"
+#include "pt-jit.h"
 #include "pt-jump.h"
 #include "pt-misc.h"
 #include "pt-pr-code.h"
@@ -51,10 +53,18 @@
 #include "parse.h"
 #include "profiler.h"
 #include "variables.h"
+#include "ov-fcn-handle.h"
 
 // Whether to optimize subsasgn method calls.
 static bool Voptimize_subsasgn_calls = true;
 
+
+std::map<std::string, octave_value>
+octave_user_code::subfunctions (void) const
+{
+  return std::map<std::string, octave_value> ();
+}
+
 // User defined scripts.
 
 DEFINE_OCTAVE_ALLOCATOR (octave_user_script);
@@ -94,6 +104,9 @@
 
 octave_user_script::~octave_user_script (void)
 {
+  if (cmd_list)
+    cmd_list->remove_all_breakpoints (file_name);
+
   delete cmd_list;
 }
 
@@ -187,9 +200,13 @@
     system_fcn_file (false), call_depth (-1),
     num_named_args (param_list ? param_list->length () : 0),
     subfunction (false), inline_function (false),
-    anonymous_function (false), class_constructor (false),
-    class_method (false), parent_scope (-1), local_scope (sid),
+    anonymous_function (false), nested_function (false),
+    class_constructor (false), class_method (false),
+    parent_scope (-1), local_scope (sid),
     curr_unwind_protect_frame (0)
+#ifdef HAVE_LLVM
+    , jit_info (0)
+#endif
 {
   if (cmd_list)
     cmd_list->mark_as_function_body ();
@@ -200,12 +217,19 @@
 
 octave_user_function::~octave_user_function (void)
 {
+  if (cmd_list)
+    cmd_list->remove_all_breakpoints (file_name);
+
   delete param_list;
   delete ret_list;
   delete cmd_list;
   delete lead_comm;
   delete trail_comm;
 
+#ifdef HAVE_LLVM
+  delete jit_info;
+#endif
+
   symbol_table::erase_scope (local_scope);
 }
 
@@ -259,10 +283,10 @@
       std::string ff_name = fcn_file_in_path (file_name);
 
       if (Vfcn_file_dir == ff_name.substr (0, Vfcn_file_dir.length ()))
-        system_fcn_file = 1;
+        system_fcn_file = true;
     }
   else
-    system_fcn_file = 0;
+    system_fcn_file = false;
 }
 
 bool
@@ -289,6 +313,12 @@
   symbol_table::unlock_subfunctions (local_scope);
 }
 
+std::map<std::string, octave_value>
+octave_user_function::subfunctions (void) const
+{
+  return symbol_table::subfunctions_defined_in_scope (local_scope);
+}
+
 octave_value_list
 octave_user_function::all_va_args (const octave_value_list& args)
 {
@@ -370,6 +400,12 @@
   if (! cmd_list)
     return retval;
 
+#ifdef HAVE_LLVM
+  if (is_special_expr ()
+      && tree_jit::execute (*this, args, retval))
+    return retval;
+#endif
+
   int nargin = args.length ();
 
   unwind_protect frame;
@@ -386,10 +422,12 @@
   // Save old and set current symbol table context, for
   // eval_undefined_error().
 
-  octave_call_stack::push (this, local_scope, call_depth);
+  int context = active_context ();
+
+  octave_call_stack::push (this, local_scope, context);
   frame.add_fcn (octave_call_stack::pop);
 
-  if (call_depth > 0)
+  if (call_depth > 0 && ! is_anonymous_function ())
     {
       symbol_table::push_context ();
 
@@ -437,6 +475,8 @@
   bind_automatic_vars (arg_names, nargin, nargout, all_va_args (args),
                        lvalue_list);
 
+  frame.add_method (this, &octave_user_function::restore_warning_states);
+
   bool echo_commands = (Vecho_executing_commands & ECHO_FUNCTIONS);
 
   if (echo_commands)
@@ -453,23 +493,16 @@
   frame.protect_var (tree_evaluator::statement_context);
   tree_evaluator::statement_context = tree_evaluator::function;
 
-  bool special_expr = (is_inline_function () || is_anonymous_function ());
-
   BEGIN_PROFILER_BLOCK (profiler_name ())
 
-  if (special_expr)
+  if (is_special_expr ())
     {
-      assert (cmd_list->length () == 1);
-
-      tree_statement *stmt = 0;
+      tree_expression *expr = special_expr ();
 
-      if ((stmt = cmd_list->front ())
-          && stmt->is_expression ())
-        {
-          tree_expression *expr = stmt->expression ();
-
-          retval = expr->rvalue (nargout);
-        }
+      if (expr)
+        retval = (lvalue_list
+                  ? expr->rvalue (nargout, lvalue_list)
+                  : expr->rvalue (nargout));
     }
   else
     cmd_list->accept (*current_evaluator);
@@ -493,7 +526,7 @@
 
   // Copy return values out.
 
-  if (ret_list && ! special_expr)
+  if (ret_list && ! is_special_expr ())
     {
       ret_list->initialize_undefined_elements (my_name, nargout, Matrix ());
 
@@ -525,6 +558,16 @@
   tw.visit_octave_user_function (*this);
 }
 
+tree_expression *
+octave_user_function::special_expr (void)
+{
+  assert (is_special_expr ());
+  assert (cmd_list->length () == 1);
+
+  tree_statement *stmt = cmd_list->front ();
+  return stmt->expression ();
+}
+
 bool
 octave_user_function::subsasgn_optimization_ok (void)
 {
@@ -577,8 +620,8 @@
       // which might be redefined in a function.  Keep the old argn name
       // for backward compatibility of functions that use it directly.
 
-      symbol_table::varref ("argn") = arg_names;
-      symbol_table::varref (".argn.") = Cell (arg_names);
+      symbol_table::force_assign ("argn", arg_names);
+      symbol_table::force_assign (".argn.", Cell (arg_names));
 
       symbol_table::mark_hidden (".argn.");
 
@@ -586,8 +629,8 @@
       symbol_table::mark_automatic (".argn.");
     }
 
-  symbol_table::varref (".nargin.") = nargin;
-  symbol_table::varref (".nargout.") = nargout;
+  symbol_table::force_assign (".nargin.", nargin);
+  symbol_table::force_assign (".nargout.", nargout);
 
   symbol_table::mark_hidden (".nargin.");
   symbol_table::mark_hidden (".nargout.");
@@ -595,11 +638,16 @@
   symbol_table::mark_automatic (".nargin.");
   symbol_table::mark_automatic (".nargout.");
 
+  symbol_table::assign (".saved_warning_states.");
+
+  symbol_table::mark_automatic (".saved_warning_states.");
+  symbol_table::mark_automatic (".saved_warning_states.");
+
   if (takes_varargs ())
-    symbol_table::varref ("varargin") = va_args.cell_value ();
+    symbol_table::assign ("varargin", va_args.cell_value ());
 
   // Force .ignored. variable to be undefined by default.
-  symbol_table::varref (".ignored.") = octave_value ();
+  symbol_table::assign (".ignored.");
 
   if (lvalue_list)
     {
@@ -621,7 +669,7 @@
               k += p->numel ();
             }
 
-          symbol_table::varref (".ignored.") = bh;
+          symbol_table::assign (".ignored.", bh);
         }
     }
 
@@ -629,15 +677,38 @@
   symbol_table::mark_automatic (".ignored.");
 }
 
+void
+octave_user_function::restore_warning_states (void)
+{
+  octave_value val = symbol_table::varval (".saved_warning_states.");
+
+  if (val.is_defined ())
+    {
+      octave_map m = val.map_value ();
+
+      if (error_state)
+        panic_impossible ();
+
+      Cell ids = m.contents ("identifier");
+      Cell states = m.contents ("state");
+
+      for (octave_idx_type i = 0; i < m.numel (); i++)
+        Fwarning (ovl (states(i), ids(i)));
+    }
+}
+
 DEFUN (nargin, args, ,
   "-*- texinfo -*-\n\
 @deftypefn  {Built-in Function} {} nargin ()\n\
-@deftypefnx {Built-in Function} {} nargin (@var{fcn_name})\n\
+@deftypefnx {Built-in Function} {} nargin (@var{fcn})\n\
 Within a function, return the number of arguments passed to the function.\n\
 At the top level, return the number of command line arguments passed to\n\
-Octave.  If called with the optional argument @var{fcn_name}, return the\n\
-maximum number of arguments the named function can accept, or -1 if the\n\
-function accepts a variable number of arguments.\n\
+Octave.\n\
+\n\
+If called with the optional argument @var{fcn}, a function name or handle,\n\
+return the declared number of arguments that the function can accept.\n\
+If the last argument is @var{varargin} the returned value is negative.\n\
+This feature does not work on builtin functions.\n\
 @seealso{nargout, varargin, isargout, varargout, nthargout}\n\
 @end deftypefn")
 {
@@ -647,40 +718,37 @@
 
   if (nargin == 1)
     {
-      std::string fname = args(0).string_value ();
+      octave_value func = args(0);
 
-      if (! error_state)
+      if (func.is_string ())
         {
-          octave_value fcn_val = symbol_table::find_function (fname);
-
-          if (fcn_val.is_user_function ())
-            {
-              octave_user_function *fcn = fcn_val.user_function_value (true);
+          std::string name = func.string_value ();
+          func = symbol_table::find_function (name);
+          if (func.is_undefined ())
+            error ("nargout: invalid function name: %s", name.c_str ());
+        }
 
-              if (fcn)
-                {
-                  if (fcn->takes_varargs ())
-                    retval = -1;
-                  else
-                    {
-                      tree_parameter_list *param_list = fcn->parameter_list ();
+      octave_function *fcn_val = func.function_value ();
+      if (fcn_val)
+        {
+          octave_user_function *fcn = fcn_val->user_function_value (true);
 
-                      retval = param_list ? param_list->length () : 0;
-                    }
-                }
-              else
-                error ("nargin: loading user-defined function failed");
+          if (fcn)
+            {
+              tree_parameter_list *param_list = fcn->parameter_list ();
+
+              retval = param_list ? param_list->length () : 0;
+              if (fcn->takes_varargs ())
+                retval = -1 - retval;
             }
           else
             {
-              // FIXME -- what about built-in functions or functions
-              // defined in .oct files or .mex files?
-
-              error ("nargin: FCN_NAME must be a user-defined function");
+              // Matlab gives up for histc, so maybe it's ok we give up somtimes too.
+              error ("nargin: nargin information not available for builtin functions");
             }
         }
       else
-        error ("nargin: FCN_NAME must be a string");
+        error ("nargin: FCN must be a string or function handle");
     }
   else if (nargin == 0)
     {
@@ -698,11 +766,12 @@
 DEFUN (nargout, args, ,
   "-*- texinfo -*-\n\
 @deftypefn  {Built-in Function} {} nargout ()\n\
-@deftypefnx {Built-in Function} {} nargout (@var{fcn_name})\n\
+@deftypefnx {Built-in Function} {} nargout (@var{fcn})\n\
 Within a function, return the number of values the caller expects to\n\
-receive.  If called with the optional argument @var{fcn_name}, return the\n\
-maximum number of values the named function can produce, or -1 if the\n\
-function can produce a variable number of values.\n\
+receive.  If called with the optional argument @var{fcn}, a function\n\
+name or handle, return the number of declared output values that the\n\
+function can produce.  If the final output argument is @var{varargout}\n\
+the returned value is negative.\n\
 \n\
 For example,\n\
 \n\
@@ -721,7 +790,25 @@
 will cause @code{nargout} to return 2 inside the function\n\
 @code{f}.\n\
 \n\
-At the top level, @code{nargout} is undefined.\n\
+In the second usage,\n\
+\n\
+@example\n\
+nargout (@@histc) \% or nargout ('histc')\n\
+@end example\n\
+\n\
+@noindent\n\
+will return 2, because @code{histc} has two outputs, whereas\n\
+\n\
+@example\n\
+nargout (@@deal)\n\
+@end example\n\
+\n\
+@noindent\n\
+will return -1, because @code{deal} has a variable number of outputs.\n\
+\n\
+At the top level, @code{nargout} with no argument is undefined.\n\
+@code{nargout} does not work on builtin functions.\n\
+@code{nargout} returns -1 for all anonymous functions.\n\
 @seealso{nargin, varargin, isargout, varargout, nthargout}\n\
 @end deftypefn")
 {
@@ -731,30 +818,58 @@
 
   if (nargin == 1)
     {
-      std::string fname = args(0).string_value ();
+      octave_value func = args(0);
 
-      if (! error_state)
+      if (func.is_string ())
+        {
+          std::string name = func.string_value ();
+          func = symbol_table::find_function (name);
+          if (func.is_undefined ())
+            error ("nargout: invalid function name: %s", name.c_str ());
+        }
+
+      if (func.is_inline_function ())
         {
-          octave_value fcn_val = symbol_table::find_user_function (fname);
+          retval = 1;
+          return retval;
+        }
+
+      if (func.is_function_handle ())
+        {
+          octave_fcn_handle *fh = func.fcn_handle_value ();
+          std::string fh_nm = fh->fcn_name ();
 
-          octave_user_function *fcn = fcn_val.user_function_value (true);
+          if (fh_nm == octave_fcn_handle::anonymous)
+            {
+              retval = -1;
+              return retval;
+            }
+        }
+
+      octave_function *fcn_val = func.function_value ();
+      if (fcn_val)
+        {
+          octave_user_function *fcn = fcn_val->user_function_value (true);
 
           if (fcn)
             {
+              tree_parameter_list *ret_list = fcn->return_list ();
+          
+              retval = ret_list ? ret_list->length () : 0;
+
               if (fcn->takes_var_return ())
-                retval = -1;
-              else
-                {
-                  tree_parameter_list *ret_list = fcn->return_list ();
-
-                  retval = ret_list ? ret_list->length () : 0;
-                }
+                retval = -1 - retval;
             }
           else
-            error ("nargout: invalid function");
+            {
+              // JWE said this information is not available (currently, 2011-03-10)
+              // without making intrusive changes to Octave.
+              // Matlab gives up for histc, so maybe it's ok we give up somtimes too.
+              error ("nargout: nargout information not available for builtin functions.");
+            }
         }
       else
-        error ("nargout: FCN_NAME must be a string");
+        error ("nargout: FCN must be a string or function handle");
     }
   else if (nargin == 0)
     {
@@ -820,7 +935,7 @@
 the tilde (~) special output argument.  Functions can use @code{isargout} to\n\
 avoid performing unnecessary calculations for outputs which are unwanted.\n\
 \n\
-If @var{k} is outside the range @code{1:max(nargout)}, the function returns\n\
+If @var{k} is outside the range @code{1:max (nargout)}, the function returns\n\
 false.  @var{k} can also be an array, in which case the function works\n\
 element-by-element and a logical array is returned.  At the top level,\n\
 @code{isargout} returns an error.\n\
@@ -912,4 +1027,24 @@
 %!test
 %! [x, y] = try_isargout ();
 %! assert ([x, y], [1, 2]);
+%!
+%% It should work without ():
+%!test
+%! [~, y] = try_isargout;
+%! assert (y, -2);
+%!
+%% It should work in function handles, anonymous functions, and cell
+%% arrays of handles or anonymous functions.
+%!test
+%! fh = @try_isargout;
+%! af = @() try_isargout;
+%! c = {fh, af};
+%! [~, y] = fh ();
+%! assert (y, -2);
+%! [~, y] = af ();
+%! assert (y, -2);
+%! [~, y] = c{1}();
+%! assert (y, -2);
+%! [~, y] = c{2}();
+%! assert (y, -2);
 */
rename from src/ov-usr-fcn.h
rename to libinterp/octave-value/ov-usr-fcn.h
--- a/src/ov-usr-fcn.h
+++ b/libinterp/octave-value/ov-usr-fcn.h
@@ -41,8 +41,13 @@
 class tree_parameter_list;
 class tree_statement_list;
 class tree_va_return_list;
+class tree_expression;
 class tree_walker;
 
+#ifdef HAVE_LLVM
+class jit_function_info;
+#endif
+
 class
 octave_user_code : public octave_function
 {
@@ -54,6 +59,8 @@
 
   bool is_user_code (void) const { return true; }
 
+  virtual std::map<std::string, octave_value> subfunctions (void) const;
+
   virtual tree_statement_list *body (void) = 0;
 
 protected:
@@ -177,6 +184,12 @@
 
   ~octave_user_function (void);
 
+  symbol_table::context_id active_context () const
+  {
+    return is_anonymous_function ()
+      ? 0 : static_cast<symbol_table::context_id>(call_depth);
+  }
+
   octave_function *function_value (bool = false) { return this; }
 
   octave_user_function *user_function_value (bool = false) { return this; }
@@ -251,6 +264,8 @@
 
   void unlock_subfunctions (void);
 
+  std::map<std::string, octave_value> subfunctions (void) const;
+
   octave_value_list all_va_args (const octave_value_list& args);
 
   void stash_function_name (const std::string& s) { my_name = s; }
@@ -272,11 +287,23 @@
   {
     return anonymous_function
       ? (cname.empty ()
-         ? (! dispatch_class().empty ())
+         ? (! dispatch_class ().empty ())
          : cname == dispatch_class ())
       : false;
   }
 
+  // If we are a special expression, then the function body consists of exactly
+  // one expression. The expression's result is the return value of the
+  // function.
+  bool is_special_expr (void) const
+  {
+    return is_inline_function () || is_anonymous_function ();
+  }
+
+  bool is_nested_function (void) const { return nested_function; }
+
+  void mark_as_nested_function (void) { nested_function = true; }
+
   void mark_as_class_constructor (void) { class_constructor = true; }
 
   bool is_class_constructor (const std::string& cname = std::string ()) const
@@ -325,6 +352,10 @@
 
   octave_comment_list *trailing_comment (void) { return trail_comm; }
 
+  // If is_special_expr is true, retrieve the sigular expression that forms the
+  // body. May be null (even if is_special_expr is true).
+  tree_expression *special_expr (void);
+
   bool subsasgn_optimization_ok (void);
 
   void accept (tree_walker& tw);
@@ -341,6 +372,12 @@
         return false;
     }
 
+#ifdef HAVE_LLVM
+  jit_function_info *get_info (void) { return jit_info; }
+
+  void stash_info (jit_function_info *info) { jit_info = info; }
+#endif
+
 #if 0
   void print_symtab_info (std::ostream& os) const;
 #endif
@@ -400,6 +437,9 @@
   // TRUE means this is an anonymous function.
   bool anonymous_function;
 
+  // TRUE means this is a nested function. (either a child or parent)
+  bool nested_function;
+
   // TRUE means this function is the constructor for class object.
   bool class_constructor;
 
@@ -414,18 +454,8 @@
   // pointer to the current unwind_protect frame of this function.
   unwind_protect *curr_unwind_protect_frame;
 
-#if 0
-  // The symbol record for argn in the local symbol table.
-  octave_value& argn_varref;
-
-  // The symbol record for nargin in the local symbol table.
-  octave_value& nargin_varref;
-
-  // The symbol record for nargout in the local symbol table.
-  octave_value& nargout_varref;
-
-  // The symbol record for varargin in the local symbol table.
-  octave_value& varargin_varref;
+#ifdef HAVE_LLVM
+  jit_function_info *jit_info;
 #endif
 
   void print_code_function_header (void);
@@ -436,6 +466,8 @@
                             int nargout, const octave_value_list& va_args,
                             const std::list<octave_lvalue> *lvalue_list);
 
+  void restore_warning_states (void);
+
   // No copying!
 
   octave_user_function (const octave_user_function& fn);
rename from src/ov.cc
rename to libinterp/octave-value/ov.cc
--- a/src/ov.cc
+++ b/libinterp/octave-value/ov.cc
@@ -76,6 +76,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"
@@ -483,6 +486,45 @@
   return retval;
 }
 
+octave_value::binary_op
+octave_value::assign_op_to_binary_op (assign_op op)
+{
+  switch (op)
+    {
+    case op_add_eq:
+      return op_add;
+    case op_sub_eq:
+      return op_sub;
+    case op_mul_eq:
+      return op_mul;
+    case op_div_eq:
+      return op_div;
+    case op_ldiv_eq:
+      return op_ldiv;
+    case op_pow_eq:
+      return op_pow;
+    case op_lshift_eq:
+      return op_lshift;
+    case op_rshift_eq:
+      return op_rshift;
+    case op_el_mul_eq:
+      return op_el_mul;
+    case op_el_div_eq:
+      return op_el_div;
+    case op_el_ldiv_eq:
+      return op_el_ldiv;
+    case op_el_pow_eq:
+      return op_el_pow;
+    case op_el_and_eq:
+      return op_el_and;
+    case op_el_or_eq:
+      return op_el_or;
+    default:
+      return unknown_binary_op;
+    }
+
+}
+
 octave_value::assign_op
 octave_value::binary_op_to_assign_op (binary_op op)
 {
@@ -1270,6 +1312,23 @@
     return *this;
 }
 
+octave_value_list
+octave_value::next_subsref (int nargout, const std::string& type,
+                            const std::list<octave_value_list>& idx,
+                            const std::list<octave_lvalue> *lvalue_list,
+                            size_t skip)
+{
+  if (! error_state && idx.size () > skip)
+    {
+      std::list<octave_value_list> new_idx (idx);
+      for (size_t i = 0; i < skip; i++)
+        new_idx.erase (new_idx.begin ());
+      return subsref (type.substr (skip), new_idx, nargout, lvalue_list);
+    }
+  else
+    return *this;
+}
+
 octave_value
 octave_value::next_subsref (bool auto_add, const std::string& type,
                             const std::list<octave_value_list>& idx,
@@ -1481,12 +1540,10 @@
 octave_idx_type
 octave_value::idx_type_value (bool req_int, bool frc_str_conv) const
 {
-#if SIZEOF_OCTAVE_IDX_TYPE == SIZEOF_LONG
-  return long_value (req_int, frc_str_conv);
-#elif SIZEOF_OCTAVE_IDX_TYPE == SIZEOF_INT
+#if defined (USE_64_BIT_IDX_T)
+  return int64_value (req_int, frc_str_conv);
+#else
   return int_value (req_int, frc_str_conv);
-#else
-#error "no octave_value extractor for octave_idx_type"
 #endif
 }
 
@@ -1555,7 +1612,7 @@
   if (retval.length () > 2 || (retval(0) != 1 && retval(1) != 1))
     {
       if (!force_vector_conversion)
-        gripe_implicit_conversion ("Octave:array-as-vector",
+        gripe_implicit_conversion ("Octave:array-to-vector",
                                    my_type.c_str (), wanted_type.c_str ());
       retval = dim_vector (nel, 1);
     }
@@ -2715,6 +2772,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, ,
@@ -2775,7 +2835,7 @@
                 type_string[k] = '.';
               else
                 {
-                  error("%s: invalid indexing type '%s'", name, item.c_str ());
+                  error ("%s: invalid indexing type '%s'", name, item.c_str ());
                   return;
                 }
             }
@@ -2834,13 +2894,13 @@
 \n\
 @example\n\
 @group\n\
-val = magic(3)\n\
-     @result{} val = [ 8   1   6\n\
-                3   5   7\n\
-                4   9   2 ]\n\
+val = magic (3)\n\
+    @result{} val = [ 8   1   6\n\
+               3   5   7\n\
+               4   9   2 ]\n\
 idx.type = \"()\";\n\
 idx.subs = @{\":\", 1:2@};\n\
-subsref(val, idx)\n\
+subsref (val, idx)\n\
      @result{} [ 8   1\n\
           3   5\n\
           4   9 ]\n\
@@ -2897,13 +2957,13 @@
 \n\
 @example\n\
 @group\n\
-val = magic(3);\n\
+val = magic (3);\n\
 idx.type = \"()\";\n\
 idx.subs = @{\":\", 1:2@};\n\
 subsasgn (val, idx, 0)\n\
-     @result{} [ 0   0   6\n\
-          0   0   7\n\
-          0   0   2 ]\n\
+     @result{}  [ 0   0   6\n\
+           0   0   7\n\
+           0   0   2 ]\n\
 @end group\n\
 @end example\n\
 \n\
@@ -2968,7 +3028,7 @@
 %!      0    8    0   18    0
 %!      0    0   14    0    0
 %!      0   10   15   20    0];
-%! assert (a,b);
+%! assert (a, b);
 
 %!test
 %! c = num2cell (reshape ([1:25],5,5));
@@ -2981,7 +3041,7 @@
 %! assert ({ subsref(c, idx1) }, {13});
 %! assert ({ subsref(c, idx2p) }, {7 9 17 19});
 %! assert ({ subsref(c, idx3p) }, num2cell ([1:5, 21:25]));
-%! assert (subsref(c, idx4), c);
+%! assert (subsref (c, idx4), c);
 %! c = subsasgn (c, idx1, 0);
 %! c = subsasgn (c, idx2, 0);
 %! c = subsasgn (c, idx3, 0);
@@ -3013,7 +3073,6 @@
 %! t.b = "There";
 %! t.c = 163;
 %! assert (s, t);
-
 */
 
 DEFUN (is_sq_string, args, ,
@@ -3034,10 +3093,11 @@
 }
 
 /*
-%!assert (is_sq_string ('foo'), true);
-%!assert (is_sq_string ("foo"), false);
-%!assert (is_sq_string (1.0), false);
-%!assert (is_sq_string ({2.0}), false);
+%!assert (is_sq_string ('foo'), true)
+%!assert (is_sq_string ("foo"), false)
+%!assert (is_sq_string (1.0), false)
+%!assert (is_sq_string ({2.0}), false)
+
 %!error is_sq_string ()
 %!error is_sq_string ('foo', 2)
 */
@@ -3060,10 +3120,11 @@
 }
 
 /*
-%!assert (is_dq_string ("foo"), true);
-%!assert (is_dq_string ('foo'), false);
-%!assert (is_dq_string (1.0), false);
-%!assert (is_dq_string ({2.0}), false);
+%!assert (is_dq_string ("foo"), true)
+%!assert (is_dq_string ('foo'), false)
+%!assert (is_dq_string (1.0), false)
+%!assert (is_dq_string ({2.0}), false)
+
 %!error is_dq_string ()
 %!error is_dq_string ("foo", 2)
 */
rename from src/ov.h
rename to libinterp/octave-value/ov.h
--- a/src/ov.h
+++ b/libinterp/octave-value/ov.h
@@ -34,7 +34,6 @@
 #include "data-conv.h"
 #include "idx-vector.h"
 #include "mach-info.h"
-#include "mxarray.h"
 #include "mx-base.h"
 #include "oct-alloc.h"
 #include "oct-time.h"
@@ -44,6 +43,7 @@
 #include "oct-sort.h"
 
 class Cell;
+class mxArray;
 class octave_map;
 class octave_scalar_map;
 class Octave_map;
@@ -145,6 +145,8 @@
     unknown_assign_op
   };
 
+  static binary_op assign_op_to_binary_op (assign_op);
+
   static assign_op binary_op_to_assign_op (binary_op);
 
   static std::string unary_op_as_string (unary_op);
@@ -194,8 +196,8 @@
   octave_value (float d);
   octave_value (const Array<octave_value>& a, bool is_cs_list = false);
   octave_value (const Cell& c, bool is_cs_list = false);
-  octave_value (const Matrix& m, const MatrixType& t = MatrixType());
-  octave_value (const FloatMatrix& m, const MatrixType& t = MatrixType());
+  octave_value (const Matrix& m, const MatrixType& t = MatrixType ());
+  octave_value (const FloatMatrix& m, const MatrixType& t = MatrixType ());
   octave_value (const NDArray& nda);
   octave_value (const FloatNDArray& nda);
   octave_value (const Array<double>& m);
@@ -212,8 +214,8 @@
   octave_value (const FloatColumnVector& v);
   octave_value (const Complex& C);
   octave_value (const FloatComplex& C);
-  octave_value (const ComplexMatrix& m, const MatrixType& t = MatrixType());
-  octave_value (const FloatComplexMatrix& m, const MatrixType& t = MatrixType());
+  octave_value (const ComplexMatrix& m, const MatrixType& t = MatrixType ());
+  octave_value (const FloatComplexMatrix& m, const MatrixType& t = MatrixType ());
   octave_value (const ComplexNDArray& cnda);
   octave_value (const FloatComplexNDArray& cnda);
   octave_value (const Array<Complex>& m);
@@ -226,7 +228,7 @@
   octave_value (const FloatComplexColumnVector& v);
   octave_value (const PermMatrix& p);
   octave_value (bool b);
-  octave_value (const boolMatrix& bm, const MatrixType& t = MatrixType());
+  octave_value (const boolMatrix& bm, const MatrixType& t = MatrixType ());
   octave_value (const boolNDArray& bnda);
   octave_value (const Array<bool>& bnda);
   octave_value (char c, char type = '\'');
@@ -319,7 +321,7 @@
     {
       if (rep->count > 1)
         {
-	  octave_base_value *r = rep->unique_clone ();
+          octave_base_value *r = rep->unique_clone ();
 
           if (--rep->count == 0)
             delete rep;
@@ -417,6 +419,12 @@
                                   std::list<octave_value_list>& idx,
                                   size_t skip = 1);
 
+  octave_value_list next_subsref (int nargout,
+                                  const std::string& type, const
+                                  std::list<octave_value_list>& idx,
+                                  const std::list<octave_lvalue> *lvalue_list,
+                                  size_t skip = 1);
+
   octave_value next_subsref (bool auto_add, const std::string& type, const
                              std::list<octave_value_list>& idx,
                              size_t skip = 1);
@@ -462,7 +470,7 @@
 
   int ndims (void) const { return rep->ndims (); }
 
-  bool all_zero_dims (void) const { return dims().all_zero (); }
+  bool all_zero_dims (void) const { return dims ().all_zero (); }
 
   octave_idx_type numel (void) const
     { return rep->numel (); }
@@ -522,9 +530,6 @@
   bool is_real_matrix (void) const
     { return rep->is_real_matrix (); }
 
-  bool is_real_nd_array (void) const
-    { return rep->is_real_nd_array (); }
-
   bool is_complex_scalar (void) const
     { return rep->is_complex_scalar (); }
 
@@ -564,6 +569,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 (); }
 
@@ -726,6 +734,14 @@
   ulong_value (bool req_int = false, bool frc_str_conv = false) const
     { return rep->ulong_value (req_int, frc_str_conv); }
 
+  int64_t
+  int64_value (bool req_int = false, bool frc_str_conv = false) const
+    { return rep->int64_value (req_int, frc_str_conv); }
+
+  uint64_t
+  uint64_value (bool req_int = false, bool frc_str_conv = false) const
+    { return rep->uint64_value (req_int, frc_str_conv); }
+
   octave_idx_type
   idx_type_value (bool req_int = false, bool frc_str_conv = false) const;
 
@@ -1006,6 +1022,8 @@
   void print_with_name (std::ostream& os, const std::string& name) const
   { rep->print_with_name (os, name, true); }
 
+  std::string short_disp (void) const { return rep->short_disp (); }
+
   int type_id (void) const { return rep->type_id (); }
 
   std::string type_name (void) const { return rep->type_name (); }
@@ -1079,6 +1097,9 @@
   octave_value diag (octave_idx_type k = 0) const
     { return rep->diag (k); }
 
+  octave_value diag (octave_idx_type m, octave_idx_type n) const
+    { return rep->diag (m, n); }
+
   octave_value sort (octave_idx_type dim = 0, sortmode mode = ASCENDING) const
     { return rep->sort (dim, mode); }
   octave_value sort (Array<octave_idx_type> &sidx, octave_idx_type dim = 0,
@@ -1121,8 +1142,11 @@
   MAPPER_FORWARD (cosh)
   MAPPER_FORWARD (erf)
   MAPPER_FORWARD (erfinv)
+  MAPPER_FORWARD (erfcinv)
   MAPPER_FORWARD (erfc)
   MAPPER_FORWARD (erfcx)
+  MAPPER_FORWARD (erfi)
+  MAPPER_FORWARD (dawson)
   MAPPER_FORWARD (exp)
   MAPPER_FORWARD (expm1)
   MAPPER_FORWARD (finite)
@@ -1163,6 +1187,7 @@
   MAPPER_FORWARD (xisspace)
   MAPPER_FORWARD (xisupper)
   MAPPER_FORWARD (xisxdigit)
+  MAPPER_FORWARD (xsignbit)
   MAPPER_FORWARD (xtoascii)
   MAPPER_FORWARD (xtolower)
   MAPPER_FORWARD (xtoupper)
rename from src/octave.cc
rename to libinterp/octave.cc
--- a/src/octave.cc
+++ b/libinterp/octave.cc
@@ -43,19 +43,21 @@
 #include "file-stat.h"
 #include "lo-error.h"
 #include "oct-env.h"
-#include "pathsearch.h"
 #include "str-vec.h"
 
-#include <defaults.h>
+#include "builtins.h"
+#include "defaults.h"
 #include "Cell.h"
 #include "defun.h"
 #include "display.h"
 #include "error.h"
 #include "file-io.h"
+#include "help.h"
 #include "input.h"
 #include "lex.h"
 #include "load-path.h"
 #include "octave.h"
+#include "oct-conf.h"
 #include "oct-hist.h"
 #include "oct-map.h"
 #include "oct-mutex.h"
@@ -81,6 +83,10 @@
 
 extern void install_builtins (void);
 
+int octave_cmdline_argc;
+char **octave_cmdline_argv;
+int octave_embedded;
+
 // The command-line options.
 static string_vector octave_argv;
 
@@ -91,6 +97,10 @@
 // The last component of octave_program_invocation_name.
 static std::string octave_program_name;
 
+// TRUE means we are using readline.
+// (--no-line-editing)
+static bool line_editing = true;
+
 // TRUE means we read ~/.octaverc and ./.octaverc.
 // (--norc; --no-init-file; -f)
 static bool read_init_files = true;
@@ -107,22 +117,52 @@
 // (--quiet; --silent; -q)
 static bool inhibit_startup_message = false;
 
-// TRUE means we turn on compatibility options.
-// (--traditional)
-static bool traditional = false;
-
 // If TRUE, print verbose info in some cases.
 // (--verbose; -V)
 static bool verbose_flag = false;
 
+// If TRUE, force the GUI to start.
+// (--force-gui)
+static bool force_gui_option = false;
+
+// If TRUE don't start the GUI.
+// (--no-gui)
+static bool no_gui_option = false;
+
+// If TRUE, force readline command line editing.
+// (--line-editing)
+static bool forced_line_editing = false;
+
+// If TRUE, initialize history list from saved history file.
+// (--no-history; -H)
+static bool read_history_file = true;
+
+// The value of "path" specified on the command line.
+// (--path; -p)
+static std::list<std::string> command_line_path;
+
+// The value for "EXEC_PATH" specified on the command line.
+// (--exec-path)
+static std::string exec_path;
+
+// The value for "IMAGE_PATH" specified on the command line.
+// (--image-path)
+static std::string image_path;
+
+// If TRUE, ignore the window system even if it is available.
+// (--no-window-system)
+static bool no_window_system = false;
+
 // Usage message
 static const char *usage_string =
   "octave [-HVdfhiqvx] [--debug] [--echo-commands] [--eval CODE]\n\
-       [--exec-path path] [--help] [--image-path path] [--info-file file]\n\
-       [--info-program prog] [--interactive] [--line-editing]\n\
-       [--no-history] [--no-init-file] [--no-init-path] [--no-line-editing]\n\
-       [--no-site-file] [--no-window-system] [-p path] [--path path]\n\
-       [--silent] [--traditional] [--verbose] [--version] [file]";
+       [--exec-path path] [--force-gui] [--help] [--image-path path]\n\
+       [--info-file file] [--info-program prog] [--interactive]\n\
+       [--jit-debugging] [--line-editing] [--no-gui] [--no-history]\n\
+       [--no-init-file] [--no-init-path] [--no-jit-compiler]\n\
+       [--no-line-editing] [--no-site-file] [--no-window-system]\n\
+       [-p path] [--path path] [--silent] [--traditional]\n\
+       [--verbose] [--version] [file]";
 
 // This is here so that it's more likely that the usage message and
 // the real set of options will agree.  Note: the '+' must come first
@@ -135,52 +175,69 @@
 // 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;
+
+// If TRUE use traditional settings (--traditional)
+static bool traditional = false;
+
 // Long options.  See the comments in getopt.h for the meanings of the
 // fields in this structure.
-#define DOC_CACHE_FILE_OPTION 1
-#define EVAL_OPTION 2
-#define EXEC_PATH_OPTION 3
-#define IMAGE_PATH_OPTION 4
-#define INFO_FILE_OPTION 5
-#define INFO_PROG_OPTION 6
-#define LINE_EDITING_OPTION 7
-#define NO_INIT_FILE_OPTION 8
-#define NO_INIT_PATH_OPTION 9
-#define NO_LINE_EDITING_OPTION 10
-#define NO_SITE_FILE_OPTION 11
-#define NO_WINDOW_SYSTEM_OPTION 12
-#define PERSIST_OPTION 13
-#define TRADITIONAL_OPTION 14
-struct option long_opts[] =
-  {
-    { "braindead",        no_argument,       0, TRADITIONAL_OPTION },
-    { "debug",            no_argument,       0, 'd' },
-    { "doc-cache-file",   required_argument, 0, DOC_CACHE_FILE_OPTION },
-    { "echo-commands",    no_argument,       0, 'x' },
-    { "eval",             required_argument, 0, EVAL_OPTION },
-    { "exec-path",        required_argument, 0, EXEC_PATH_OPTION },
-    { "help",             no_argument,       0, 'h' },
-    { "image-path",       required_argument, 0, IMAGE_PATH_OPTION },
-    { "info-file",        required_argument, 0, INFO_FILE_OPTION },
-    { "info-program",     required_argument, 0, INFO_PROG_OPTION },
-    { "interactive",      no_argument,       0, 'i' },
-    { "line-editing",     no_argument,       0, LINE_EDITING_OPTION },
-    { "no-history",       no_argument,       0, 'H' },
-    { "no-init-file",     no_argument,       0, NO_INIT_FILE_OPTION },
-    { "no-init-path",     no_argument,       0, NO_INIT_PATH_OPTION },
-    { "no-line-editing",  no_argument,       0, NO_LINE_EDITING_OPTION },
-    { "no-site-file",     no_argument,       0, NO_SITE_FILE_OPTION },
-    { "no-window-system", no_argument,       0, NO_WINDOW_SYSTEM_OPTION },
-    { "norc",             no_argument,       0, 'f' },
-    { "path",             required_argument, 0, 'p' },
-    { "persist",          no_argument,       0, PERSIST_OPTION },
-    { "quiet",            no_argument,       0, 'q' },
-    { "silent",           no_argument,       0, 'q' },
-    { "traditional",      no_argument,       0, TRADITIONAL_OPTION },
-    { "verbose",          no_argument,       0, 'V' },
-    { "version",          no_argument,       0, 'v' },
-    { 0,                  0,                 0, 0 }
-  };
+#define BUILT_IN_DOCSTRINGS_FILE_OPTION 1
+#define DOC_CACHE_FILE_OPTION 2
+#define EVAL_OPTION 3
+#define EXEC_PATH_OPTION 4
+#define FORCE_GUI_OPTION 5
+#define IMAGE_PATH_OPTION 6
+#define INFO_FILE_OPTION 7
+#define INFO_PROG_OPTION 8
+#define JIT_DEBUGGING_OPTION 9
+#define LINE_EDITING_OPTION 10
+#define NO_GUI_OPTION 11
+#define NO_INIT_FILE_OPTION 12
+#define NO_INIT_PATH_OPTION 13
+#define NO_JIT_COMPILER_OPTION 14
+#define NO_LINE_EDITING_OPTION 15
+#define NO_SITE_FILE_OPTION 16
+#define NO_WINDOW_SYSTEM_OPTION 17
+#define PERSIST_OPTION 18
+#define TEXI_MACROS_FILE_OPTION 19
+#define TRADITIONAL_OPTION 20
+struct option long_opts[] = {
+  { "braindead",                no_argument,       0, TRADITIONAL_OPTION },
+  { "built-in-docstrings-file", required_argument, 0, BUILT_IN_DOCSTRINGS_FILE_OPTION },
+  { "debug",                    no_argument,       0, 'd' },
+  { "doc-cache-file",           required_argument, 0, DOC_CACHE_FILE_OPTION },
+  { "echo-commands",            no_argument,       0, 'x' },
+  { "eval",                     required_argument, 0, EVAL_OPTION },
+  { "exec-path",                required_argument, 0, EXEC_PATH_OPTION },
+  { "force-gui",                no_argument,       0, FORCE_GUI_OPTION },
+  { "help",                     no_argument,       0, 'h' },
+  { "image-path",               required_argument, 0, IMAGE_PATH_OPTION },
+  { "info-file",                required_argument, 0, INFO_FILE_OPTION },
+  { "info-program",             required_argument, 0, INFO_PROG_OPTION },
+  { "interactive",              no_argument,       0, 'i' },
+  { "jit-debugging",            no_argument,       0, JIT_DEBUGGING_OPTION },
+  { "line-editing",             no_argument,       0, LINE_EDITING_OPTION },
+  { "no-gui",                   no_argument,       0, NO_GUI_OPTION },
+  { "no-history",               no_argument,       0, 'H' },
+  { "no-init-file",             no_argument,       0, NO_INIT_FILE_OPTION },
+  { "no-init-path",             no_argument,       0, NO_INIT_PATH_OPTION },
+  { "no-jit-compiler",          no_argument,       0, NO_JIT_COMPILER_OPTION },
+  { "no-line-editing",          no_argument,       0, NO_LINE_EDITING_OPTION },
+  { "no-site-file",             no_argument,       0, NO_SITE_FILE_OPTION },
+  { "no-window-system",         no_argument,       0, NO_WINDOW_SYSTEM_OPTION },
+  { "norc",                     no_argument,       0, 'f' },
+  { "path",                     required_argument, 0, 'p' },
+  { "persist",                  no_argument,       0, PERSIST_OPTION },
+  { "quiet",                    no_argument,       0, 'q' },
+  { "silent",                   no_argument,       0, 'q' },
+  { "texi-macros-file",         required_argument, 0, TEXI_MACROS_FILE_OPTION },
+  { "traditional",              no_argument,       0, TRADITIONAL_OPTION },
+  { "verbose",                  no_argument,       0, 'V' },
+  { "version",                  no_argument,       0, 'v' },
+  { 0,                          0,                 0, 0 }
+};
 
 // Store the command-line options for later use.
 
@@ -189,7 +246,7 @@
 {
   assert (symbol_table::at_top_level ());
 
-  symbol_table::varref (".nargin.") = argc - 1;
+  symbol_table::assign (".nargin.", argc - 1);
 
   symbol_table::mark_hidden (".nargin.");
 
@@ -204,24 +261,6 @@
     }
 }
 
-static void
-initialize_pathsearch (void)
-{
-  // This may seem odd, but doing it this way means that we don't have
-  // to modify the kpathsea library...
-
-  std::string odb = octave_env::getenv ("OCTAVE_DB_PATH");
-
-  // For backward compatibility.
-
-  if (odb.empty ())
-    odb = octave_env::getenv ("OCTAVE_DB_DIR");
-
-  if (odb.empty ())
-    odb = Vdata_dir + file_ops::dir_sep_str () + "octave:"
-      + Vlibexec_dir + file_ops::dir_sep_str () + "octave";
-}
-
 DEFUN (__version_info__, args, ,
   "-*- texinfo -*-\n\
 @deftypefn {Built-in Function} {retval =} __version_info__ (@var{name}, @var{version}, @var{release}, @var{date})\n\
@@ -314,13 +353,6 @@
       recover_from_exception ();
       gripe_safe_source_exception (file_name, "unhandled execution exception");
     }
-  catch (std::bad_alloc)
-    {
-      recover_from_exception ();
-      gripe_safe_source_exception
-        (file_name,
-         "memory exhausted or requested size too large for range of Octave's index type");
-    }
 }
 
 // Initialize by reading startup files.
@@ -330,10 +362,6 @@
 {
   unwind_protect frame;
 
-  frame.protect_var (input_from_startup_file);
-
-  input_from_startup_file = true;
-
   std::string context;
 
   bool verbose = (verbose_flag && ! inhibit_startup_message);
@@ -441,11 +469,6 @@
       std::cerr << "error: unhandled execution exception -- eval failed"
                 << std::endl;
     }
-  catch (std::bad_alloc)
-    {
-      std::cerr << "error: memory exhausted or requested size too large for range of Octave's index type -- eval failed"
-                << std::endl;
-    }
 
   return parse_status;
 }
@@ -468,30 +491,18 @@
   octave_initialized = true;
 
   frame.protect_var (interactive);
-  frame.protect_var (reading_script_file);
-  frame.protect_var (input_from_command_line_file);
-
-  frame.protect_var (curr_fcn_file_name);
-  frame.protect_var (curr_fcn_file_full_name);
 
   frame.protect_var (octave_program_invocation_name);
   frame.protect_var (octave_program_name);
 
   interactive = false;
-  reading_script_file = true;
-  input_from_command_line_file = true;
 
-  curr_fcn_file_name = fname;
-  curr_fcn_file_full_name = curr_fcn_file_name;
+  octave_program_invocation_name = fname;
 
-  octave_program_invocation_name = curr_fcn_file_name;
-
-  size_t pos = curr_fcn_file_name.find_last_of (file_ops::dir_sep_chars ());
+  size_t pos = fname.find_last_of (file_ops::dir_sep_chars ());
 
-  std::string tmp = (pos != std::string::npos)
-    ? curr_fcn_file_name.substr (pos+1) : curr_fcn_file_name;
-
-  octave_program_name = tmp;
+  octave_program_name
+    = (pos != std::string::npos) ? fname.substr (pos+1) : fname;
 
   std::string context;
   bool verbose = false;
@@ -516,15 +527,19 @@
   --echo-commands, -x     Echo commands as they are executed.\n\
   --eval CODE             Evaluate CODE.  Exit when done unless --persist.\n\
   --exec-path PATH        Set path for executing subprograms.\n\
+  --force-gui             Force graphical user interface to start.\n\
   --help, -h,             Print short help message and exit.\n\
   --image-path PATH       Add PATH to head of image search path.\n\
   --info-file FILE        Use top-level info file FILE.\n\
   --info-program PROGRAM  Use PROGRAM for reading info files.\n\
   --interactive, -i       Force interactive behavior.\n\
+  --jit-debug             Enable JIT compiler debugging/tracing.\n\
   --line-editing          Force readline use for command-line editing.\n\
+  --no-gui                Disable the graphical user interface.\n\
   --no-history, -H        Don't save commands to the history list\n\
   --no-init-file          Don't read the ~/.octaverc or .octaverc files.\n\
   --no-init-path          Don't initialize function search path.\n\
+  --no-jit-compiler       Disable the JIT compiler.\n\
   --no-line-editing       Don't use readline for command-line editing.\n\
   --no-site-file          Don't read the site-wide octaverc file.\n\
   --no-window-system      Disable window system, including graphics.\n\
@@ -532,6 +547,7 @@
   --path PATH, -p PATH    Add PATH to head of function search path.\n\
   --persist               Go interactive after --eval or reading from FILE.\n\
   --silent, -q            Don't print message at startup.\n\
+  --texi-macros-file FILE Use Texinfo macros in FILE for makeinfo command.\n\
   --traditional           Set variables for closer MATLAB compatibility.\n\
   --verbose, -V           Enable verbose output in some cases.\n\
   --version, -v           Print version number and exit.\n\
@@ -602,19 +618,19 @@
 {
   persist = true;
 
-  bind_internal_variable ("PS1", ">> ");
-  bind_internal_variable ("PS2", "");
-  bind_internal_variable ("allow_noninteger_range_as_index", true);
-  bind_internal_variable ("beep_on_error", true);
-  bind_internal_variable ("confirm_recursive_rmdir", false);
-  bind_internal_variable ("crash_dumps_octave_core", false);
-  bind_internal_variable ("default_save_options", "-mat-binary");
-  bind_internal_variable ("do_braindead_shortcircuit_evaluation", true);
-  bind_internal_variable ("fixed_point_format", true);
-  bind_internal_variable ("history_timestamp_format_string",
-                         "%%-- %D %I:%M %p --%%");
-  bind_internal_variable ("page_screen_output", false);
-  bind_internal_variable ("print_empty_dimensions", false);
+  FPS1 (octave_value (">> "));
+  FPS2 (octave_value (""));
+  FPS4 (octave_value (""));
+  Fallow_noninteger_range_as_index (octave_value (true));
+  Fbeep_on_error (octave_value (true));
+  Fconfirm_recursive_rmdir (octave_value (false));
+  Fcrash_dumps_octave_core (octave_value (false));
+  Fdefault_save_options (octave_value ("-mat-binary"));
+  Fdo_braindead_shortcircuit_evaluation (octave_value (true));
+  Ffixed_point_format (octave_value (true));
+  Fhistory_timestamp_format_string (octave_value ("%%-- %D %I:%M %p --%%"));
+  Fpage_screen_output (octave_value (false));
+  Fprint_empty_dimensions (octave_value (false));
 
   disable_warning ("Octave:abbreviated-property-match");
   disable_warning ("Octave:fopen-file-in-path");
@@ -623,63 +639,28 @@
   disable_warning ("Octave:possible-matlab-short-circuit-operator");
 }
 
-// You guessed it.
+// EMBEDDED is declared int instead of bool because this function is
+// declared extern "C".
 
 int
 octave_main (int argc, char **argv, int embedded)
 {
-  octave_env::set_program_name (argv[0]);
-
-  octave_program_invocation_name = octave_env::get_program_invocation_name ();
-  octave_program_name = octave_env::get_program_name ();
-
-  octave_thread::init ();
-
-  // The order of these calls is important.  The call to
-  // install_defaults must come before install_builtins because
-  // default variable values must be available for the variables to be
-  // installed, and the call to install_builtins must come before the
-  // options are processed because some command line options override
-  // defaults by calling bind_internal_variable.
-
-  init_signals ();
+  octave_process_command_line (argc, argv);
 
   sysdep_init ();
 
-  octave_ieee_init ();
-
-  // The idea here is to force xerbla to be referenced so that we will
-  // link to our own version instead of the one provided by the BLAS
-  // library.  But octave_NaN should never be -1, so we should never
-  // actually call xerbla.
-
-  if (octave_NaN == -1)
-    F77_FUNC (xerbla, XERBLA) ("octave", 13 F77_CHAR_ARG_LEN (6));
-
-  initialize_error_handlers ();
-
-  initialize_default_warning_state ();
-
   install_defaults ();
 
-  initialize_pathsearch ();
+  octave_initialize_interpreter (argc, argv, embedded);
 
-  if (! embedded)
-    install_signal_handlers ();
-  else
-    quit_allowed = false;
-
-  initialize_file_io ();
+  return octave_execute_interpreter ();
+}
 
-  install_types ();
-
-  install_ops ();
-
-  install_builtins ();
-
-  bool forced_line_editing = false;
-
-  bool read_history_file = true;
+void
+octave_process_command_line (int argc, char **argv)
+{
+  octave_cmdline_argc = argc;
+  octave_cmdline_argv = argv;
 
   while (true)
     {
@@ -700,8 +681,8 @@
           break;
 
         case 'H':
+          Fsaving_history (octave_value (false));
           read_history_file = false;
-          bind_internal_variable ("saving_history", false);
           break;
 
         case 'V':
@@ -728,7 +709,7 @@
 
         case 'p':
           if (optarg)
-            load_path::set_command_line_path (optarg);
+            command_line_path.push_back (optarg);
           break;
 
         case 'q':
@@ -737,8 +718,8 @@
 
         case 'x':
           {
-            double tmp = (ECHO_SCRIPTS | ECHO_FUNCTIONS | ECHO_CMD_LINE);
-            bind_internal_variable ("echo_executing_commands", tmp);
+            int val = ECHO_SCRIPTS | ECHO_FUNCTIONS | ECHO_CMD_LINE;
+            Fecho_executing_commands (octave_value (val));
           }
           break;
 
@@ -746,9 +727,14 @@
           print_version_and_exit ();
           break;
 
+        case BUILT_IN_DOCSTRINGS_FILE_OPTION:
+          if (optarg)
+            Fbuilt_in_docstrings_file (octave_value (optarg));
+          break;
+
         case DOC_CACHE_FILE_OPTION:
           if (optarg)
-            bind_internal_variable ("doc_cache_file", optarg);
+            Fdoc_cache_file (octave_value (optarg));
           break;
 
         case EVAL_OPTION:
@@ -763,28 +749,40 @@
 
         case EXEC_PATH_OPTION:
           if (optarg)
-            set_exec_path (optarg);
+            exec_path = optarg;
+          break;
+
+        case FORCE_GUI_OPTION:
+          force_gui_option = true;
           break;
 
         case IMAGE_PATH_OPTION:
           if (optarg)
-            set_image_path (optarg);
+            image_path = optarg;
           break;
 
         case INFO_FILE_OPTION:
           if (optarg)
-            bind_internal_variable ("info_file", optarg);
+            Finfo_file (octave_value (optarg));
           break;
 
         case INFO_PROG_OPTION:
           if (optarg)
-            bind_internal_variable ("info_program", optarg);
+            Finfo_program (octave_value (optarg));
+          break;
+
+        case JIT_DEBUGGING_OPTION:
+          Fenable_jit_debugging (octave_value (true));
           break;
 
         case LINE_EDITING_OPTION:
           forced_line_editing = true;
           break;
 
+        case NO_GUI_OPTION:
+          no_gui_option = true;
+          break;
+
         case NO_INIT_FILE_OPTION:
           read_init_files = false;
           break;
@@ -793,6 +791,10 @@
           set_initial_path = false;
           break;
 
+        case NO_JIT_COMPILER_OPTION:
+          Fenable_jit_compiler (octave_value (false));
+          break;
+
         case NO_LINE_EDITING_OPTION:
           line_editing = false;
           break;
@@ -802,13 +804,18 @@
           break;
 
         case NO_WINDOW_SYSTEM_OPTION:
-          display_info::no_window_system ();
+          no_window_system = true;
           break;
 
         case PERSIST_OPTION:
           persist = true;
           break;
 
+        case TEXI_MACROS_FILE_OPTION:
+          if (optarg)
+            Ftexi_macros_file (octave_value (optarg));
+          break;
+
         case TRADITIONAL_OPTION:
           traditional = true;
           break;
@@ -823,18 +830,81 @@
         }
     }
 
-  // Make sure we clean up when we exit.  Also allow users to register
-  // functions.  If we don't have atexit or on_exit, we're going to
-  // leave some junk files around if we exit abnormally.
+  if (force_gui_option && no_gui_option)
+    {
+      error ("error: only one of --force-gui and --no-gui may be used");
+      usage ();
+    }
+}
+
+// EMBEDDED is declared int instead of bool because this function is
+// declared extern "C".
+
+void
+octave_initialize_interpreter (int argc, char **argv, int embedded)
+{
+  octave_embedded = embedded;
+
+  octave_env::set_program_name (argv[0]);
+
+  octave_program_invocation_name = octave_env::get_program_invocation_name ();
+  octave_program_name = octave_env::get_program_name ();
+
+  octave_thread::init ();
+
+  set_default_prompts ();
+
+  if (traditional)
+    maximum_braindamage ();
+
+  init_signals ();
+
+  octave_ieee_init ();
 
-  atexit (do_octave_atexit);
+  // The idea here is to force xerbla to be referenced so that we will
+  // link to our own version instead of the one provided by the BLAS
+  // library.  But octave_NaN should never be -1, so we should never
+  // actually call xerbla.
+
+  if (octave_NaN == -1)
+    F77_FUNC (xerbla, XERBLA) ("octave", 13 F77_CHAR_ARG_LEN (6));
+
+  initialize_error_handlers ();
+
+  initialize_default_warning_state ();
+
+  if (! embedded)
+    install_signal_handlers ();
+  else
+    quit_allowed = false;
+
+  initialize_file_io ();
+
+  install_types ();
+
+  install_ops ();
+
+  install_builtins ();
+
+  for (std::list<std::string>::const_iterator it = command_line_path.begin ();
+       it != command_line_path.end (); it++)
+    load_path::set_command_line_path (*it);
+
+  if (! exec_path.empty ())
+    set_exec_path (exec_path);
+
+  if (! image_path.empty ())
+    set_image_path (image_path);
+
+  if (no_window_system)
+    display_info::no_window_system ();
 
   // Is input coming from a terminal?  If so, we are probably
   // interactive.
 
   // If stdin is not a tty, then we are reading commands from a pipe or
   // a redirected file.
-  stdin_is_tty = gnulib::isatty (fileno (stdin));
+  bool stdin_is_tty = gnulib::isatty (fileno (stdin));
 
   interactive = (! embedded && stdin_is_tty
                  && gnulib::isatty (fileno (stdout)));
@@ -852,12 +922,6 @@
   if (line_editing)
     initialize_command_input ();
 
-  if (! inhibit_startup_message)
-    std::cout << OCTAVE_STARTUP_MESSAGE "\n" << std::endl;
-
-  if (traditional)
-    maximum_braindamage ();
-
   octave_interpreter_ready = true;
 
   initialize_version_info ();
@@ -870,6 +934,13 @@
   load_path::initialize (set_initial_path);
 
   initialize_history (read_history_file);
+}
+
+int
+octave_execute_interpreter (void)
+{
+  if (! inhibit_startup_message)
+    std::cout << OCTAVE_STARTUP_MESSAGE "\n" << std::endl;
 
   execute_startup_files ();
 
@@ -882,7 +953,7 @@
 
   int last_arg_idx = optind;
 
-  int remaining_args = argc - last_arg_idx;
+  int remaining_args = octave_cmdline_argc - last_arg_idx;
 
   if (! code_to_eval.empty ())
     {
@@ -897,9 +968,9 @@
       // If we are running an executable script (#! /bin/octave) then
       // we should only see the args passed to the script.
 
-      intern_argv (remaining_args, argv+last_arg_idx);
+      intern_argv (remaining_args, octave_cmdline_argv+last_arg_idx);
 
-      execute_command_line_file (argv[last_arg_idx]);
+      execute_command_line_file (octave_cmdline_argv[last_arg_idx]);
 
       if (! persist)
         {
@@ -914,10 +985,7 @@
   command_editor::reset_current_command_number (1);
 
   // Now argv should have the full set of args.
-  intern_argv (argc, argv);
-
-  if (! embedded)
-    switch_to_buffer (create_buffer (get_input_from_stdin ()));
+  intern_argv (octave_cmdline_argc, octave_cmdline_argv);
 
   // Force input to be echoed if not really interactive, but the user
   // has forced interactive behavior.
@@ -928,10 +996,10 @@
 
       // FIXME -- is this the right thing to do?
 
-      bind_internal_variable ("echo_executing_commands", ECHO_CMD_LINE);
+      Fecho_executing_commands (octave_value (ECHO_CMD_LINE));
     }
 
-  if (embedded)
+  if (octave_embedded)
     {
       // FIXME -- do we need to do any cleanup here before
       // returning?  If we don't, what will happen to Octave functions
@@ -942,16 +1010,80 @@
 
   int retval = main_loop ();
 
-  if (retval == 1 && ! error_state)
-    retval = 0;
-
   quitting_gracefully = true;
 
-  clean_up_and_exit (retval);
+  clean_up_and_exit (retval, true);
+
+  return retval;
+}
+
+static bool
+check_starting_gui (void)
+{
+  if (no_window_system || ! display_info::display_available ())
+    return false;
+
+  if (force_gui_option)
+    return true;
+
+  if (no_gui_option)
+    return false;
+
+  if (persist)
+    return true;
+
+  // If stdin is not a tty, then assume we are reading commands from a
+  // pipe or a redirected file and the GUI should not start.  If this is
+  // not the case (for example, starting from a desktop "launcher" with
+  // no terminal) and you want to start the GUI, you may use the
+  // --force-gui option to start the GUI.
+
+  if (! gnulib::isatty (fileno (stdin)))
+    return false;
+
+  // If we have code to eval or execute from a file, and we are going to
+  // exit immediately after executing it, don't start the gui.
+
+  int last_arg_idx = optind;
+  int remaining_args = octave_cmdline_argc - last_arg_idx;
 
-  return 0;
+  if (! code_to_eval.empty () || remaining_args > 0)
+    return false;
+
+  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\
@@ -982,8 +1114,8 @@
 }
 
 /*
-%!error argv (1);
-%!assert (iscellstr (argv ()));
+%!assert (iscellstr (argv ()))
+%!error argv (1)
 */
 
 DEFUN (program_invocation_name, args, ,
@@ -1009,8 +1141,8 @@
 }
 
 /*
-%!error program_invocation_name (1);
-%!assert (ischar (program_invocation_name ()));
+%!assert (ischar (program_invocation_name ()))
+%!error program_invocation_name (1)
 */
 
 DEFUN (program_name, args, ,
@@ -1032,6 +1164,6 @@
 }
 
 /*
-%!error program_name (1);
-%!assert (ischar (program_name ()));
+%!assert (ischar (program_name ()))
+%!error program_name (1)
 */
rename from src/octave.h
rename to libinterp/octave.h
--- a/src/octave.h
+++ b/libinterp/octave.h
@@ -29,6 +29,19 @@
 
 extern OCTINTERP_API int octave_main (int argc, char **argv, int embedded);
 
+extern OCTINTERP_API void octave_process_command_line (int argc, char **argv);
+
+extern OCTINTERP_API void
+octave_initialize_interpreter (int argc, char **argv, int embedded);
+
+extern OCTINTERP_API int octave_execute_interpreter (void);
+
+extern OCTINTERP_API int octave_cmdline_argc;
+extern OCTINTERP_API char **octave_cmdline_argv;
+extern OCTINTERP_API int octave_embedded;
+
+extern OCTINTERP_API int octave_starting_gui (void);
+
 #ifdef  __cplusplus
 }
 #endif
rename from src/OPERATORS/module.mk
rename to libinterp/operators/module.mk
--- a/src/OPERATORS/module.mk
+++ b/libinterp/operators/module.mk
@@ -1,136 +1,144 @@
-EXTRA_DIST += OPERATORS/module.mk
+EXTRA_DIST += operators/module.mk
 
 OPERATORS_SRC = \
-  OPERATORS/op-b-b.cc \
-  OPERATORS/op-b-bm.cc \
-  OPERATORS/op-b-sbm.cc \
-  OPERATORS/op-bm-b.cc \
-  OPERATORS/op-bm-bm.cc \
-  OPERATORS/op-bm-sbm.cc \
-  OPERATORS/op-cdm-cdm.cc \
-  OPERATORS/op-cdm-cm.cc \
-  OPERATORS/op-cdm-cs.cc \
-  OPERATORS/op-cdm-dm.cc \
-  OPERATORS/op-cdm-m.cc \
-  OPERATORS/op-cdm-s.cc \
-  OPERATORS/op-cell.cc \
-  OPERATORS/op-chm.cc \
-  OPERATORS/op-class.cc \
-  OPERATORS/op-cm-cdm.cc \
-  OPERATORS/op-cm-cm.cc \
-  OPERATORS/op-cm-cs.cc \
-  OPERATORS/op-cm-dm.cc \
-  OPERATORS/op-cm-m.cc \
-  OPERATORS/op-cm-pm.cc \
-  OPERATORS/op-cm-s.cc \
-  OPERATORS/op-cm-scm.cc \
-  OPERATORS/op-cm-sm.cc \
-  OPERATORS/op-cs-cm.cc \
-  OPERATORS/op-cs-cs.cc \
-  OPERATORS/op-cs-m.cc \
-  OPERATORS/op-cs-s.cc \
-  OPERATORS/op-cs-scm.cc \
-  OPERATORS/op-cs-sm.cc \
-  OPERATORS/op-dm-cdm.cc \
-  OPERATORS/op-dm-cm.cc \
-  OPERATORS/op-dm-cs.cc \
-  OPERATORS/op-dm-dm.cc \
-  OPERATORS/op-dm-m.cc \
-  OPERATORS/op-dm-s.cc \
-  OPERATORS/op-dm-scm.cc \
-  OPERATORS/op-dm-sm.cc \
-  OPERATORS/op-double-conv.cc \
-  OPERATORS/op-fcdm-fcdm.cc \
-  OPERATORS/op-fcdm-fcm.cc \
-  OPERATORS/op-fcdm-fcs.cc \
-  OPERATORS/op-fcdm-fdm.cc \
-  OPERATORS/op-fcdm-fm.cc \
-  OPERATORS/op-fcdm-fs.cc \
-  OPERATORS/op-fcm-fcdm.cc \
-  OPERATORS/op-fcm-fcm.cc \
-  OPERATORS/op-fcm-fcs.cc \
-  OPERATORS/op-fcm-fdm.cc \
-  OPERATORS/op-fcm-fm.cc \
-  OPERATORS/op-fcm-fs.cc \
-  OPERATORS/op-fcm-pm.cc \
-  OPERATORS/op-fcn.cc \
-  OPERATORS/op-fcs-fcm.cc \
-  OPERATORS/op-fcs-fcs.cc \
-  OPERATORS/op-fcs-fm.cc \
-  OPERATORS/op-fcs-fs.cc \
-  OPERATORS/op-fdm-fcdm.cc \
-  OPERATORS/op-fdm-fcm.cc \
-  OPERATORS/op-fdm-fcs.cc \
-  OPERATORS/op-fdm-fdm.cc \
-  OPERATORS/op-fdm-fm.cc \
-  OPERATORS/op-fdm-fs.cc \
-  OPERATORS/op-float-conv.cc \
-  OPERATORS/op-fm-fcdm.cc \
-  OPERATORS/op-fm-fcm.cc \
-  OPERATORS/op-fm-fcs.cc \
-  OPERATORS/op-fm-fdm.cc \
-  OPERATORS/op-fm-fm.cc \
-  OPERATORS/op-fm-fs.cc \
-  OPERATORS/op-fm-pm.cc \
-  OPERATORS/op-fs-fcm.cc \
-  OPERATORS/op-fs-fcs.cc \
-  OPERATORS/op-fs-fm.cc \
-  OPERATORS/op-fs-fs.cc \
-  OPERATORS/op-i16-i16.cc \
-  OPERATORS/op-i32-i32.cc \
-  OPERATORS/op-i64-i64.cc \
-  OPERATORS/op-i8-i8.cc \
-  OPERATORS/op-int-concat.cc \
-  OPERATORS/op-int-conv.cc \
-  OPERATORS/op-m-cdm.cc \
-  OPERATORS/op-m-cm.cc \
-  OPERATORS/op-m-cs.cc \
-  OPERATORS/op-m-dm.cc \
-  OPERATORS/op-m-m.cc \
-  OPERATORS/op-m-pm.cc \
-  OPERATORS/op-m-s.cc \
-  OPERATORS/op-m-scm.cc \
-  OPERATORS/op-m-sm.cc \
-  OPERATORS/op-pm-cm.cc \
-  OPERATORS/op-pm-fcm.cc \
-  OPERATORS/op-pm-fm.cc \
-  OPERATORS/op-pm-m.cc \
-  OPERATORS/op-pm-pm.cc \
-  OPERATORS/op-pm-scm.cc \
-  OPERATORS/op-pm-sm.cc \
-  OPERATORS/op-range.cc \
-  OPERATORS/op-s-cm.cc \
-  OPERATORS/op-s-cs.cc \
-  OPERATORS/op-s-m.cc \
-  OPERATORS/op-s-s.cc \
-  OPERATORS/op-s-scm.cc \
-  OPERATORS/op-s-sm.cc \
-  OPERATORS/op-sbm-b.cc \
-  OPERATORS/op-sbm-bm.cc \
-  OPERATORS/op-sbm-sbm.cc \
-  OPERATORS/op-scm-cm.cc \
-  OPERATORS/op-scm-cs.cc \
-  OPERATORS/op-scm-m.cc \
-  OPERATORS/op-scm-s.cc \
-  OPERATORS/op-scm-scm.cc \
-  OPERATORS/op-scm-sm.cc \
-  OPERATORS/op-sm-cm.cc \
-  OPERATORS/op-sm-cs.cc \
-  OPERATORS/op-sm-m.cc \
-  OPERATORS/op-sm-s.cc \
-  OPERATORS/op-sm-scm.cc \
-  OPERATORS/op-sm-sm.cc \
-  OPERATORS/op-str-m.cc \
-  OPERATORS/op-str-s.cc \
-  OPERATORS/op-str-str.cc \
-  OPERATORS/op-struct.cc \
-  OPERATORS/op-ui16-ui16.cc \
-  OPERATORS/op-ui32-ui32.cc \
-  OPERATORS/op-ui64-ui64.cc \
-  OPERATORS/op-ui8-ui8.cc
+  operators/op-b-b.cc \
+  operators/op-b-bm.cc \
+  operators/op-b-sbm.cc \
+  operators/op-bm-b.cc \
+  operators/op-bm-bm.cc \
+  operators/op-bm-sbm.cc \
+  operators/op-cdm-cdm.cc \
+  operators/op-cdm-cm.cc \
+  operators/op-cdm-cs.cc \
+  operators/op-cdm-dm.cc \
+  operators/op-cdm-m.cc \
+  operators/op-cdm-s.cc \
+  operators/op-cell.cc \
+  operators/op-chm.cc \
+  operators/op-class.cc \
+  operators/op-cm-cdm.cc \
+  operators/op-cm-cm.cc \
+  operators/op-cm-cs.cc \
+  operators/op-cm-dm.cc \
+  operators/op-cm-m.cc \
+  operators/op-cm-pm.cc \
+  operators/op-cm-s.cc \
+  operators/op-cm-scm.cc \
+  operators/op-cm-sm.cc \
+  operators/op-cs-cm.cc \
+  operators/op-cs-cs.cc \
+  operators/op-cs-m.cc \
+  operators/op-cs-s.cc \
+  operators/op-cs-scm.cc \
+  operators/op-cs-sm.cc \
+  operators/op-dm-cdm.cc \
+  operators/op-dm-cm.cc \
+  operators/op-dm-cs.cc \
+  operators/op-dm-dm.cc \
+  operators/op-dm-m.cc \
+  operators/op-dm-s.cc \
+  operators/op-dm-scm.cc \
+  operators/op-dm-sm.cc \
+  operators/op-double-conv.cc \
+  operators/op-fcdm-fcdm.cc \
+  operators/op-fcdm-fcm.cc \
+  operators/op-fcdm-fcs.cc \
+  operators/op-fcdm-fdm.cc \
+  operators/op-fcdm-fm.cc \
+  operators/op-fcdm-fs.cc \
+  operators/op-fcm-fcdm.cc \
+  operators/op-fcm-fcm.cc \
+  operators/op-fcm-fcs.cc \
+  operators/op-fcm-fdm.cc \
+  operators/op-fcm-fm.cc \
+  operators/op-fcm-fs.cc \
+  operators/op-fcm-pm.cc \
+  operators/op-fcn.cc \
+  operators/op-fcs-fcm.cc \
+  operators/op-fcs-fcs.cc \
+  operators/op-fcs-fm.cc \
+  operators/op-fcs-fs.cc \
+  operators/op-fdm-fcdm.cc \
+  operators/op-fdm-fcm.cc \
+  operators/op-fdm-fcs.cc \
+  operators/op-fdm-fdm.cc \
+  operators/op-fdm-fm.cc \
+  operators/op-fdm-fs.cc \
+  operators/op-float-conv.cc \
+  operators/op-fm-fcdm.cc \
+  operators/op-fm-fcm.cc \
+  operators/op-fm-fcs.cc \
+  operators/op-fm-fdm.cc \
+  operators/op-fm-fm.cc \
+  operators/op-fm-fs.cc \
+  operators/op-fm-pm.cc \
+  operators/op-fs-fcm.cc \
+  operators/op-fs-fcs.cc \
+  operators/op-fs-fm.cc \
+  operators/op-fs-fs.cc \
+  operators/op-i16-i16.cc \
+  operators/op-i32-i32.cc \
+  operators/op-i64-i64.cc \
+  operators/op-i8-i8.cc \
+  operators/op-int-concat.cc \
+  operators/op-int-conv.cc \
+  operators/op-m-cdm.cc \
+  operators/op-m-cm.cc \
+  operators/op-m-cs.cc \
+  operators/op-m-dm.cc \
+  operators/op-m-m.cc \
+  operators/op-m-pm.cc \
+  operators/op-m-s.cc \
+  operators/op-m-scm.cc \
+  operators/op-m-sm.cc \
+  operators/op-pm-cm.cc \
+  operators/op-pm-fcm.cc \
+  operators/op-pm-fm.cc \
+  operators/op-pm-m.cc \
+  operators/op-pm-pm.cc \
+  operators/op-pm-scm.cc \
+  operators/op-pm-sm.cc \
+  operators/op-range.cc \
+  operators/op-s-cm.cc \
+  operators/op-s-cs.cc \
+  operators/op-s-m.cc \
+  operators/op-s-s.cc \
+  operators/op-s-scm.cc \
+  operators/op-s-sm.cc \
+  operators/op-sbm-b.cc \
+  operators/op-sbm-bm.cc \
+  operators/op-sbm-sbm.cc \
+  operators/op-scm-cm.cc \
+  operators/op-scm-cs.cc \
+  operators/op-scm-m.cc \
+  operators/op-scm-s.cc \
+  operators/op-scm-scm.cc \
+  operators/op-scm-sm.cc \
+  operators/op-sm-cm.cc \
+  operators/op-sm-cs.cc \
+  operators/op-sm-m.cc \
+  operators/op-sm-s.cc \
+  operators/op-sm-scm.cc \
+  operators/op-sm-sm.cc \
+  operators/op-str-m.cc \
+  operators/op-str-s.cc \
+  operators/op-str-str.cc \
+  operators/op-struct.cc \
+  operators/op-ui16-ui16.cc \
+  operators/op-ui32-ui32.cc \
+  operators/op-ui64-ui64.cc \
+  operators/op-ui8-ui8.cc
 
-octinclude_HEADERS += \
-  OPERATORS/op-dm-template.cc \
-  OPERATORS/op-dms-template.cc \
-  OPERATORS/op-int.h \
-  OPERATORS/op-pm-template.cc
+## These look like included header files to Autotools build process
+OPERATORS_INC = \
+  operators/op-dm-template.cc \
+  operators/op-dms-template.cc \
+  operators/op-int.h \
+  operators/op-pm-template.cc \
+  operators/ops.h
+
+## Special rules for sources which must be built before rest of compilation.
+operators/ops.cc: $(OPERATORS_SRC) mkops
+	$(srcdir)/mkops $(OPERATORS_SRC) > $@-t
+	mv $@-t $@
+
rename from src/OPERATORS/op-b-b.cc
rename to libinterp/operators/op-b-b.cc
rename from src/OPERATORS/op-b-bm.cc
rename to libinterp/operators/op-b-bm.cc
rename from src/OPERATORS/op-b-sbm.cc
rename to libinterp/operators/op-b-sbm.cc
rename from src/OPERATORS/op-bm-b.cc
rename to libinterp/operators/op-bm-b.cc
rename from src/OPERATORS/op-bm-bm.cc
rename to libinterp/operators/op-bm-bm.cc
--- a/src/OPERATORS/op-bm-bm.cc
+++ b/libinterp/operators/op-bm-bm.cc
@@ -66,7 +66,7 @@
       return octave_value ();
     }
   else
-    return octave_value (v.bool_matrix_value().transpose ());
+    return octave_value (v.bool_matrix_value ().transpose ());
 }
 
 // bool matrix by bool matrix ops.
rename from src/OPERATORS/op-bm-sbm.cc
rename to libinterp/operators/op-bm-sbm.cc
rename from src/OPERATORS/op-cdm-cdm.cc
rename to libinterp/operators/op-cdm-cdm.cc
--- a/src/OPERATORS/op-cdm-cdm.cc
+++ b/libinterp/operators/op-cdm-cdm.cc
@@ -43,13 +43,13 @@
 DEFUNOP (transpose, complex_diag_matrix)
 {
   CAST_UNOP_ARG (const octave_complex_diag_matrix&);
-  return octave_value (v.complex_diag_matrix_value().transpose ());
+  return octave_value (v.complex_diag_matrix_value ().transpose ());
 }
 
 DEFUNOP (hermitian, complex_diag_matrix)
 {
   CAST_UNOP_ARG (const octave_complex_diag_matrix&);
-  return octave_value (v.complex_diag_matrix_value().hermitian ());
+  return octave_value (v.complex_diag_matrix_value ().hermitian ());
 }
 
 // matrix by matrix ops.
rename from src/OPERATORS/op-cdm-cm.cc
rename to libinterp/operators/op-cdm-cm.cc
rename from src/OPERATORS/op-cdm-cs.cc
rename to libinterp/operators/op-cdm-cs.cc
rename from src/OPERATORS/op-cdm-dm.cc
rename to libinterp/operators/op-cdm-dm.cc
rename from src/OPERATORS/op-cdm-m.cc
rename to libinterp/operators/op-cdm-m.cc
rename from src/OPERATORS/op-cdm-s.cc
rename to libinterp/operators/op-cdm-s.cc
rename from src/OPERATORS/op-cell.cc
rename to libinterp/operators/op-cell.cc
--- a/src/OPERATORS/op-cell.cc
+++ b/libinterp/operators/op-cell.cc
@@ -46,7 +46,7 @@
       return octave_value ();
     }
   else
-    return octave_value (Cell (v.cell_value().transpose ()));
+    return octave_value (Cell (v.cell_value ().transpose ()));
 }
 
 DEFCATOP_FN (c_c, cell, cell, concat)
rename from src/OPERATORS/op-chm.cc
rename to libinterp/operators/op-chm.cc
--- a/src/OPERATORS/op-chm.cc
+++ b/libinterp/operators/op-chm.cc
@@ -41,7 +41,7 @@
 {
   CAST_UNOP_ARG (const octave_char_matrix&);
 
-  return octave_value (v.matrix_value().transpose ());
+  return octave_value (v.matrix_value ().transpose ());
 }
 
 DEFNDCATOP_FN (chm_chm, char_matrix, char_matrix, char_array, char_array,
rename from src/OPERATORS/op-class.cc
rename to libinterp/operators/op-class.cc
rename from src/OPERATORS/op-cm-cdm.cc
rename to libinterp/operators/op-cm-cdm.cc
rename from src/OPERATORS/op-cm-cm.cc
rename to libinterp/operators/op-cm-cm.cc
--- a/src/OPERATORS/op-cm-cm.cc
+++ b/libinterp/operators/op-cm-cm.cc
@@ -51,7 +51,7 @@
       return octave_value ();
     }
   else
-    return octave_value (v.complex_matrix_value().transpose ());
+    return octave_value (v.complex_matrix_value ().transpose ());
 }
 
 DEFUNOP (hermitian, complex_matrix)
@@ -64,7 +64,7 @@
       return octave_value ();
     }
   else
-    return octave_value (v.complex_matrix_value().hermitian ());
+    return octave_value (v.complex_matrix_value ().hermitian ());
 }
 
 DEFNCUNOP_METHOD (incr, complex_matrix, increment)
rename from src/OPERATORS/op-cm-cs.cc
rename to libinterp/operators/op-cm-cs.cc
rename from src/OPERATORS/op-cm-dm.cc
rename to libinterp/operators/op-cm-dm.cc
rename from src/OPERATORS/op-cm-m.cc
rename to libinterp/operators/op-cm-m.cc
rename from src/OPERATORS/op-cm-pm.cc
rename to libinterp/operators/op-cm-pm.cc
rename from src/OPERATORS/op-cm-s.cc
rename to libinterp/operators/op-cm-s.cc
rename from src/OPERATORS/op-cm-scm.cc
rename to libinterp/operators/op-cm-scm.cc
--- a/src/OPERATORS/op-cm-scm.cc
+++ b/libinterp/operators/op-cm-scm.cc
@@ -51,7 +51,7 @@
   CAST_BINOP_ARGS (const octave_complex_matrix&,
                    const octave_sparse_complex_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       Complex d = v2.complex_value ();
 
rename from src/OPERATORS/op-cm-sm.cc
rename to libinterp/operators/op-cm-sm.cc
--- a/src/OPERATORS/op-cm-sm.cc
+++ b/libinterp/operators/op-cm-sm.cc
@@ -50,7 +50,7 @@
 {
   CAST_BINOP_ARGS (const octave_complex_matrix&, const octave_sparse_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       double d = v2.scalar_value ();
 
rename from src/OPERATORS/op-cs-cm.cc
rename to libinterp/operators/op-cs-cm.cc
rename from src/OPERATORS/op-cs-cs.cc
rename to libinterp/operators/op-cs-cs.cc
rename from src/OPERATORS/op-cs-m.cc
rename to libinterp/operators/op-cs-m.cc
rename from src/OPERATORS/op-cs-s.cc
rename to libinterp/operators/op-cs-s.cc
rename from src/OPERATORS/op-cs-scm.cc
rename to libinterp/operators/op-cs-scm.cc
--- a/src/OPERATORS/op-cs-scm.cc
+++ b/libinterp/operators/op-cs-scm.cc
@@ -48,7 +48,7 @@
 {
   CAST_BINOP_ARGS (const octave_complex&, const octave_sparse_complex_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       Complex d = v2.complex_value ();
 
rename from src/OPERATORS/op-cs-sm.cc
rename to libinterp/operators/op-cs-sm.cc
--- a/src/OPERATORS/op-cs-sm.cc
+++ b/libinterp/operators/op-cs-sm.cc
@@ -50,7 +50,7 @@
 {
   CAST_BINOP_ARGS (const octave_complex&, const octave_sparse_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       double d = v2.scalar_value ();
 
rename from src/OPERATORS/op-dm-cdm.cc
rename to libinterp/operators/op-dm-cdm.cc
rename from src/OPERATORS/op-dm-cm.cc
rename to libinterp/operators/op-dm-cm.cc
rename from src/OPERATORS/op-dm-cs.cc
rename to libinterp/operators/op-dm-cs.cc
rename from src/OPERATORS/op-dm-dm.cc
rename to libinterp/operators/op-dm-dm.cc
--- a/src/OPERATORS/op-dm-dm.cc
+++ b/libinterp/operators/op-dm-dm.cc
@@ -43,7 +43,7 @@
 DEFUNOP (transpose, diag_matrix)
 {
   CAST_UNOP_ARG (const octave_diag_matrix&);
-  return octave_value (v.diag_matrix_value().transpose ());
+  return octave_value (v.diag_matrix_value ().transpose ());
 }
 
 // matrix by matrix ops.
rename from src/OPERATORS/op-dm-m.cc
rename to libinterp/operators/op-dm-m.cc
rename from src/OPERATORS/op-dm-s.cc
rename to libinterp/operators/op-dm-s.cc
rename from src/OPERATORS/op-dm-scm.cc
rename to libinterp/operators/op-dm-scm.cc
--- a/src/OPERATORS/op-dm-scm.cc
+++ b/libinterp/operators/op-dm-scm.cc
@@ -43,7 +43,7 @@
 {
   CAST_BINOP_ARGS (const octave_diag_matrix&, const octave_sparse_complex_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -66,7 +66,7 @@
 {
   CAST_BINOP_ARGS (const octave_complex_diag_matrix&, const octave_sparse_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -89,7 +89,7 @@
 {
   CAST_BINOP_ARGS (const octave_complex_diag_matrix&, const octave_sparse_complex_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -142,7 +142,7 @@
 {
   CAST_BINOP_ARGS (const octave_diag_matrix&, const octave_sparse_complex_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -158,7 +158,7 @@
 {
   CAST_BINOP_ARGS (const octave_complex_diag_matrix&, const octave_sparse_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -174,7 +174,7 @@
 {
   CAST_BINOP_ARGS (const octave_complex_diag_matrix&, const octave_sparse_complex_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -190,7 +190,7 @@
 {
   CAST_BINOP_ARGS (const octave_diag_matrix&, const octave_sparse_complex_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -206,7 +206,7 @@
 {
   CAST_BINOP_ARGS (const octave_complex_diag_matrix&, const octave_sparse_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -222,7 +222,7 @@
 {
   CAST_BINOP_ARGS (const octave_complex_diag_matrix&, const octave_sparse_complex_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -240,7 +240,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_diag_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     // If v1 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -263,7 +263,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_complex_diag_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     // If v1 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -286,7 +286,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_complex_diag_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     // If v1 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -294,7 +294,7 @@
 
       return octave_value (d * v2.complex_diag_matrix_value ());
     }
-  else if (v2.rows() == 1 && v2.columns() == 1)
+  else if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, don't bother with further dispatching.
     {
       std::complex<double> d = v2.complex_value ();
@@ -316,7 +316,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_diag_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       double d = v2.scalar_value ();
 
@@ -336,7 +336,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_complex_diag_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       std::complex<double> d = v2.complex_value ();
 
@@ -356,7 +356,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_complex_diag_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       std::complex<double> d = v2.complex_value ();
 
@@ -376,7 +376,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_complex_diag_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -392,7 +392,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_diag_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -408,7 +408,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_complex_diag_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -424,7 +424,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_complex_diag_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -440,7 +440,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_diag_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -456,7 +456,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_complex_diag_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
rename from src/OPERATORS/op-dm-sm.cc
rename to libinterp/operators/op-dm-sm.cc
--- a/src/OPERATORS/op-dm-sm.cc
+++ b/libinterp/operators/op-dm-sm.cc
@@ -41,7 +41,7 @@
 {
   CAST_BINOP_ARGS (const octave_diag_matrix&, const octave_sparse_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -72,7 +72,7 @@
 {
   CAST_BINOP_ARGS (const octave_diag_matrix&, const octave_sparse_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -88,7 +88,7 @@
 {
   CAST_BINOP_ARGS (const octave_diag_matrix&, const octave_sparse_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     // If v2 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -106,7 +106,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_diag_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     // If v1 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -129,7 +129,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_diag_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       double d = v2.scalar_value ();
 
@@ -149,7 +149,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_diag_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     // If v1 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
@@ -165,7 +165,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_diag_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     // If v1 is a scalar in disguise, return a diagonal matrix rather than
     // a sparse matrix.
     {
rename from src/OPERATORS/op-dm-template.cc
rename to libinterp/operators/op-dm-template.cc
rename from src/OPERATORS/op-dms-template.cc
rename to libinterp/operators/op-dms-template.cc
rename from src/OPERATORS/op-double-conv.cc
rename to libinterp/operators/op-double-conv.cc
rename from src/OPERATORS/op-fcdm-fcdm.cc
rename to libinterp/operators/op-fcdm-fcdm.cc
--- a/src/OPERATORS/op-fcdm-fcdm.cc
+++ b/libinterp/operators/op-fcdm-fcdm.cc
@@ -43,13 +43,13 @@
 DEFUNOP (transpose, float_complex_diag_matrix)
 {
   CAST_UNOP_ARG (const octave_float_complex_diag_matrix&);
-  return octave_value (v.float_complex_diag_matrix_value().transpose ());
+  return octave_value (v.float_complex_diag_matrix_value ().transpose ());
 }
 
 DEFUNOP (hermitian, float_complex_diag_matrix)
 {
   CAST_UNOP_ARG (const octave_float_complex_diag_matrix&);
-  return octave_value (v.float_complex_diag_matrix_value().hermitian ());
+  return octave_value (v.float_complex_diag_matrix_value ().hermitian ());
 }
 
 // matrix by matrix ops.
rename from src/OPERATORS/op-fcdm-fcm.cc
rename to libinterp/operators/op-fcdm-fcm.cc
rename from src/OPERATORS/op-fcdm-fcs.cc
rename to libinterp/operators/op-fcdm-fcs.cc
rename from src/OPERATORS/op-fcdm-fdm.cc
rename to libinterp/operators/op-fcdm-fdm.cc
rename from src/OPERATORS/op-fcdm-fm.cc
rename to libinterp/operators/op-fcdm-fm.cc
rename from src/OPERATORS/op-fcdm-fs.cc
rename to libinterp/operators/op-fcdm-fs.cc
rename from src/OPERATORS/op-fcm-fcdm.cc
rename to libinterp/operators/op-fcm-fcdm.cc
rename from src/OPERATORS/op-fcm-fcm.cc
rename to libinterp/operators/op-fcm-fcm.cc
--- a/src/OPERATORS/op-fcm-fcm.cc
+++ b/libinterp/operators/op-fcm-fcm.cc
@@ -51,7 +51,7 @@
       return octave_value ();
     }
   else
-    return octave_value (v.float_complex_matrix_value().transpose ());
+    return octave_value (v.float_complex_matrix_value ().transpose ());
 }
 
 DEFUNOP (hermitian, float_complex_matrix)
@@ -64,7 +64,7 @@
       return octave_value ();
     }
   else
-    return octave_value (v.float_complex_matrix_value().hermitian ());
+    return octave_value (v.float_complex_matrix_value ().hermitian ());
 }
 
 DEFNCUNOP_METHOD (incr, float_complex_matrix, increment)
rename from src/OPERATORS/op-fcm-fcs.cc
rename to libinterp/operators/op-fcm-fcs.cc
rename from src/OPERATORS/op-fcm-fdm.cc
rename to libinterp/operators/op-fcm-fdm.cc
rename from src/OPERATORS/op-fcm-fm.cc
rename to libinterp/operators/op-fcm-fm.cc
rename from src/OPERATORS/op-fcm-fs.cc
rename to libinterp/operators/op-fcm-fs.cc
rename from src/OPERATORS/op-fcm-pm.cc
rename to libinterp/operators/op-fcm-pm.cc
rename from src/OPERATORS/op-fcn.cc
rename to libinterp/operators/op-fcn.cc
rename from src/OPERATORS/op-fcs-fcm.cc
rename to libinterp/operators/op-fcs-fcm.cc
rename from src/OPERATORS/op-fcs-fcs.cc
rename to libinterp/operators/op-fcs-fcs.cc
rename from src/OPERATORS/op-fcs-fm.cc
rename to libinterp/operators/op-fcs-fm.cc
rename from src/OPERATORS/op-fcs-fs.cc
rename to libinterp/operators/op-fcs-fs.cc
rename from src/OPERATORS/op-fdm-fcdm.cc
rename to libinterp/operators/op-fdm-fcdm.cc
rename from src/OPERATORS/op-fdm-fcm.cc
rename to libinterp/operators/op-fdm-fcm.cc
rename from src/OPERATORS/op-fdm-fcs.cc
rename to libinterp/operators/op-fdm-fcs.cc
rename from src/OPERATORS/op-fdm-fdm.cc
rename to libinterp/operators/op-fdm-fdm.cc
--- a/src/OPERATORS/op-fdm-fdm.cc
+++ b/libinterp/operators/op-fdm-fdm.cc
@@ -43,7 +43,7 @@
 DEFUNOP (transpose, float_diag_matrix)
 {
   CAST_UNOP_ARG (const octave_float_diag_matrix&);
-  return octave_value (v.float_diag_matrix_value().transpose ());
+  return octave_value (v.float_diag_matrix_value ().transpose ());
 }
 
 // matrix by matrix ops.
rename from src/OPERATORS/op-fdm-fm.cc
rename to libinterp/operators/op-fdm-fm.cc
rename from src/OPERATORS/op-fdm-fs.cc
rename to libinterp/operators/op-fdm-fs.cc
rename from src/OPERATORS/op-float-conv.cc
rename to libinterp/operators/op-float-conv.cc
rename from src/OPERATORS/op-fm-fcdm.cc
rename to libinterp/operators/op-fm-fcdm.cc
rename from src/OPERATORS/op-fm-fcm.cc
rename to libinterp/operators/op-fm-fcm.cc
rename from src/OPERATORS/op-fm-fcs.cc
rename to libinterp/operators/op-fm-fcs.cc
rename from src/OPERATORS/op-fm-fdm.cc
rename to libinterp/operators/op-fm-fdm.cc
rename from src/OPERATORS/op-fm-fm.cc
rename to libinterp/operators/op-fm-fm.cc
--- a/src/OPERATORS/op-fm-fm.cc
+++ b/libinterp/operators/op-fm-fm.cc
@@ -51,7 +51,7 @@
       return octave_value ();
     }
   else
-    return octave_value (v.float_matrix_value().transpose ());
+    return octave_value (v.float_matrix_value ().transpose ());
 }
 
 DEFNCUNOP_METHOD (incr, float_matrix, increment)
rename from src/OPERATORS/op-fm-fs.cc
rename to libinterp/operators/op-fm-fs.cc
rename from src/OPERATORS/op-fm-pm.cc
rename to libinterp/operators/op-fm-pm.cc
rename from src/OPERATORS/op-fs-fcm.cc
rename to libinterp/operators/op-fs-fcm.cc
rename from src/OPERATORS/op-fs-fcs.cc
rename to libinterp/operators/op-fs-fcs.cc
rename from src/OPERATORS/op-fs-fm.cc
rename to libinterp/operators/op-fs-fm.cc
rename from src/OPERATORS/op-fs-fs.cc
rename to libinterp/operators/op-fs-fs.cc
rename from src/OPERATORS/op-i16-i16.cc
rename to libinterp/operators/op-i16-i16.cc
rename from src/OPERATORS/op-i32-i32.cc
rename to libinterp/operators/op-i32-i32.cc
rename from src/OPERATORS/op-i64-i64.cc
rename to libinterp/operators/op-i64-i64.cc
rename from src/OPERATORS/op-i8-i8.cc
rename to libinterp/operators/op-i8-i8.cc
rename from src/OPERATORS/op-int-concat.cc
rename to libinterp/operators/op-int-concat.cc
rename from src/OPERATORS/op-int-conv.cc
rename to libinterp/operators/op-int-conv.cc
rename from src/OPERATORS/op-int.h
rename to libinterp/operators/op-int.h
--- a/src/OPERATORS/op-int.h
+++ b/libinterp/operators/op-int.h
@@ -633,7 +633,7 @@
         return octave_value (); \
       } \
     else \
-      return octave_value (v.TYPE ## _array_value().transpose ()); \
+      return octave_value (v.TYPE ## _array_value ().transpose ()); \
   } \
  \
   DEFNCUNOP_METHOD (m_incr, TYPE ## _matrix, increment) \
rename from src/OPERATORS/op-m-cdm.cc
rename to libinterp/operators/op-m-cdm.cc
rename from src/OPERATORS/op-m-cm.cc
rename to libinterp/operators/op-m-cm.cc
rename from src/OPERATORS/op-m-cs.cc
rename to libinterp/operators/op-m-cs.cc
rename from src/OPERATORS/op-m-dm.cc
rename to libinterp/operators/op-m-dm.cc
rename from src/OPERATORS/op-m-m.cc
rename to libinterp/operators/op-m-m.cc
--- a/src/OPERATORS/op-m-m.cc
+++ b/libinterp/operators/op-m-m.cc
@@ -51,7 +51,7 @@
       return octave_value ();
     }
   else
-    return octave_value (v.matrix_value().transpose ());
+    return octave_value (v.matrix_value ().transpose ());
 }
 
 DEFNCUNOP_METHOD (incr, matrix, increment)
rename from src/OPERATORS/op-m-pm.cc
rename to libinterp/operators/op-m-pm.cc
rename from src/OPERATORS/op-m-s.cc
rename to libinterp/operators/op-m-s.cc
rename from src/OPERATORS/op-m-scm.cc
rename to libinterp/operators/op-m-scm.cc
--- a/src/OPERATORS/op-m-scm.cc
+++ b/libinterp/operators/op-m-scm.cc
@@ -51,7 +51,7 @@
 {
   CAST_BINOP_ARGS (const octave_matrix&, const octave_sparse_complex_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       Complex d = v2.complex_value ();
 
rename from src/OPERATORS/op-m-sm.cc
rename to libinterp/operators/op-m-sm.cc
--- a/src/OPERATORS/op-m-sm.cc
+++ b/libinterp/operators/op-m-sm.cc
@@ -50,7 +50,7 @@
 {
   CAST_BINOP_ARGS (const octave_matrix&, const octave_sparse_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       double d = v2.scalar_value ();
 
rename from src/OPERATORS/op-pm-cm.cc
rename to libinterp/operators/op-pm-cm.cc
rename from src/OPERATORS/op-pm-fcm.cc
rename to libinterp/operators/op-pm-fcm.cc
rename from src/OPERATORS/op-pm-fm.cc
rename to libinterp/operators/op-pm-fm.cc
rename from src/OPERATORS/op-pm-m.cc
rename to libinterp/operators/op-pm-m.cc
rename from src/OPERATORS/op-pm-pm.cc
rename to libinterp/operators/op-pm-pm.cc
--- a/src/OPERATORS/op-pm-pm.cc
+++ b/libinterp/operators/op-pm-pm.cc
@@ -37,7 +37,7 @@
 DEFUNOP (transpose, perm_matrix)
 {
   CAST_UNOP_ARG (const octave_perm_matrix&);
-  return octave_value (v.perm_matrix_value().transpose ());
+  return octave_value (v.perm_matrix_value ().transpose ());
 }
 
 DEFBINOP_OP (mul, perm_matrix, perm_matrix, *)
rename from src/OPERATORS/op-pm-scm.cc
rename to libinterp/operators/op-pm-scm.cc
--- a/src/OPERATORS/op-pm-scm.cc
+++ b/libinterp/operators/op-pm-scm.cc
@@ -39,13 +39,13 @@
 {
   CAST_BINOP_ARGS (const octave_perm_matrix&, const octave_sparse_complex_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       std::complex<double> d = v2.complex_value ();
 
       return octave_value (v1.sparse_matrix_value () * d);
     }
-  else if (v1.rows() == 1 && v1.columns() == 1)
+  else if (v1.rows () == 1 && v1.columns () == 1)
     return octave_value (v2.sparse_complex_matrix_value ());
   else
     return v1.perm_matrix_value  () * v2.sparse_complex_matrix_value ();
@@ -64,13 +64,13 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_perm_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     {
       std::complex<double> d = v1.scalar_value ();
 
       return octave_value (d * v2.sparse_matrix_value ());
     }
-  else if (v2.rows() == 1 && v2.columns() == 1)
+  else if (v2.rows () == 1 && v2.columns () == 1)
     return octave_value (v1.sparse_complex_matrix_value ());
   else
     return v1.sparse_complex_matrix_value  () * v2.perm_matrix_value ();
rename from src/OPERATORS/op-pm-sm.cc
rename to libinterp/operators/op-pm-sm.cc
--- a/src/OPERATORS/op-pm-sm.cc
+++ b/libinterp/operators/op-pm-sm.cc
@@ -82,13 +82,13 @@
 {
   CAST_BINOP_ARGS (const octave_perm_matrix&, const octave_sparse_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       double d = v2.scalar_value ();
 
       return octave_value (v1.sparse_matrix_value () * d);
     }
-  else if (v1.rows() == 1 && v1.columns() == 1)
+  else if (v1.rows () == 1 && v1.columns () == 1)
     return octave_value (v2.sparse_matrix_value ());
   else
     return v1.perm_matrix_value  () * v2.sparse_matrix_value ();
@@ -107,13 +107,13 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_perm_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     {
       double d = v1.scalar_value ();
 
       return octave_value (d * v2.sparse_matrix_value ());
     }
-  else if (v2.rows() == 1 && v2.columns() == 1)
+  else if (v2.rows () == 1 && v2.columns () == 1)
     return octave_value (v1.sparse_matrix_value ());
   else
     return v1.sparse_matrix_value  () * v2.perm_matrix_value ();
rename from src/OPERATORS/op-pm-template.cc
rename to libinterp/operators/op-pm-template.cc
rename from src/OPERATORS/op-range.cc
rename to libinterp/operators/op-range.cc
--- a/src/OPERATORS/op-range.cc
+++ b/libinterp/operators/op-range.cc
@@ -47,7 +47,7 @@
 {
   CAST_UNOP_ARG (const octave_range&);
 
-  return octave_value (! v.matrix_value());
+  return octave_value (! v.matrix_value ());
 }
 
 DEFUNOP_OP (uplus, range, /* no-op */)
@@ -57,7 +57,7 @@
 {
   CAST_UNOP_ARG (const octave_range&);
 
-  return octave_value (v.matrix_value().transpose ());
+  return octave_value (v.matrix_value ().transpose ());
 }
 
 DEFBINOP_OP (addrs, range, scalar, +)
rename from src/OPERATORS/op-s-cm.cc
rename to libinterp/operators/op-s-cm.cc
rename from src/OPERATORS/op-s-cs.cc
rename to libinterp/operators/op-s-cs.cc
rename from src/OPERATORS/op-s-m.cc
rename to libinterp/operators/op-s-m.cc
rename from src/OPERATORS/op-s-s.cc
rename to libinterp/operators/op-s-s.cc
rename from src/OPERATORS/op-s-scm.cc
rename to libinterp/operators/op-s-scm.cc
--- a/src/OPERATORS/op-s-scm.cc
+++ b/libinterp/operators/op-s-scm.cc
@@ -51,7 +51,7 @@
 {
   CAST_BINOP_ARGS (const octave_scalar&, const octave_sparse_complex_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       Complex d = v2.complex_value ();
 
rename from src/OPERATORS/op-s-sm.cc
rename to libinterp/operators/op-s-sm.cc
--- a/src/OPERATORS/op-s-sm.cc
+++ b/libinterp/operators/op-s-sm.cc
@@ -47,7 +47,7 @@
 {
   CAST_BINOP_ARGS (const octave_scalar&, const octave_sparse_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       double d = v2.scalar_value ();
 
rename from src/OPERATORS/op-sbm-b.cc
rename to libinterp/operators/op-sbm-b.cc
rename from src/OPERATORS/op-sbm-bm.cc
rename to libinterp/operators/op-sbm-bm.cc
rename from src/OPERATORS/op-sbm-sbm.cc
rename to libinterp/operators/op-sbm-sbm.cc
--- a/src/OPERATORS/op-sbm-sbm.cc
+++ b/libinterp/operators/op-sbm-sbm.cc
@@ -55,7 +55,7 @@
 DEFUNOP (transpose, sparse_bool_matrix)
 {
   CAST_UNOP_ARG (const octave_sparse_bool_matrix&);
-  return octave_value (v.sparse_bool_matrix_value().transpose ());
+  return octave_value (v.sparse_bool_matrix_value ().transpose ());
 }
 
 // sparse bool matrix by sparse bool matrix ops.
rename from src/OPERATORS/op-scm-cm.cc
rename to libinterp/operators/op-scm-cm.cc
--- a/src/OPERATORS/op-scm-cm.cc
+++ b/libinterp/operators/op-scm-cm.cc
@@ -69,7 +69,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_complex_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     {
       Complex d = v1.complex_value ();
 
rename from src/OPERATORS/op-scm-cs.cc
rename to libinterp/operators/op-scm-cs.cc
--- a/src/OPERATORS/op-scm-cs.cc
+++ b/libinterp/operators/op-scm-cs.cc
@@ -71,7 +71,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_complex&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     {
       Complex d = v1.complex_value ();
 
rename from src/OPERATORS/op-scm-m.cc
rename to libinterp/operators/op-scm-m.cc
--- a/src/OPERATORS/op-scm-m.cc
+++ b/libinterp/operators/op-scm-m.cc
@@ -70,7 +70,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     {
       Complex d = v1.complex_value ();
 
rename from src/OPERATORS/op-scm-s.cc
rename to libinterp/operators/op-scm-s.cc
--- a/src/OPERATORS/op-scm-s.cc
+++ b/libinterp/operators/op-scm-s.cc
@@ -79,7 +79,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_scalar&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     {
       Complex d = v1.complex_value ();
 
rename from src/OPERATORS/op-scm-scm.cc
rename to libinterp/operators/op-scm-scm.cc
--- a/src/OPERATORS/op-scm-scm.cc
+++ b/libinterp/operators/op-scm-scm.cc
@@ -60,7 +60,7 @@
 {
   CAST_UNOP_ARG (const octave_sparse_complex_matrix&);
   return octave_value
-    (v.sparse_complex_matrix_value().transpose (),
+    (v.sparse_complex_matrix_value ().transpose (),
      v.matrix_type ().transpose ());
 }
 
@@ -68,7 +68,7 @@
 {
   CAST_UNOP_ARG (const octave_sparse_complex_matrix&);
   return octave_value
-    (v.sparse_complex_matrix_value().hermitian (),
+    (v.sparse_complex_matrix_value ().hermitian (),
      v.matrix_type ().transpose ());
 }
 
@@ -100,7 +100,7 @@
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&,
                    const octave_sparse_complex_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       Complex d = v2.complex_value ();
 
@@ -131,7 +131,7 @@
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&,
                    const octave_sparse_complex_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     {
       Complex d = v1.complex_value ();
 
rename from src/OPERATORS/op-scm-sm.cc
rename to libinterp/operators/op-scm-sm.cc
--- a/src/OPERATORS/op-scm-sm.cc
+++ b/libinterp/operators/op-scm-sm.cc
@@ -49,7 +49,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_sparse_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       double d = v2.scalar_value ();
 
@@ -79,7 +79,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_complex_matrix&, const octave_sparse_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     {
       Complex d = v1.complex_value ();
 
rename from src/OPERATORS/op-sm-cm.cc
rename to libinterp/operators/op-sm-cm.cc
--- a/src/OPERATORS/op-sm-cm.cc
+++ b/libinterp/operators/op-sm-cm.cc
@@ -69,7 +69,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_complex_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     {
       double d = v1.scalar_value ();
 
rename from src/OPERATORS/op-sm-cs.cc
rename to libinterp/operators/op-sm-cs.cc
--- a/src/OPERATORS/op-sm-cs.cc
+++ b/libinterp/operators/op-sm-cs.cc
@@ -71,7 +71,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_complex&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     {
       double d = v1.scalar_value ();
 
rename from src/OPERATORS/op-sm-m.cc
rename to libinterp/operators/op-sm-m.cc
--- a/src/OPERATORS/op-sm-m.cc
+++ b/libinterp/operators/op-sm-m.cc
@@ -67,7 +67,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     {
       double d = v1.scalar_value ();
 
rename from src/OPERATORS/op-sm-s.cc
rename to libinterp/operators/op-sm-s.cc
--- a/src/OPERATORS/op-sm-s.cc
+++ b/libinterp/operators/op-sm-s.cc
@@ -73,7 +73,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_scalar&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     {
       double d = v1.scalar_value ();
 
rename from src/OPERATORS/op-sm-scm.cc
rename to libinterp/operators/op-sm-scm.cc
--- a/src/OPERATORS/op-sm-scm.cc
+++ b/libinterp/operators/op-sm-scm.cc
@@ -49,7 +49,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_sparse_complex_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       Complex d = v2.complex_value ();
 
@@ -79,7 +79,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_sparse_complex_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     {
       double d = v1.scalar_value ();
 
rename from src/OPERATORS/op-sm-sm.cc
rename to libinterp/operators/op-sm-sm.cc
--- a/src/OPERATORS/op-sm-sm.cc
+++ b/libinterp/operators/op-sm-sm.cc
@@ -46,7 +46,7 @@
 DEFUNOP (transpose, sparse_matrix)
 {
   CAST_UNOP_ARG (const octave_sparse_matrix&);
-  return octave_value (v.sparse_matrix_value().transpose (),
+  return octave_value (v.sparse_matrix_value ().transpose (),
                        v.matrix_type ().transpose ());
 }
 
@@ -72,7 +72,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_sparse_matrix&);
 
-  if (v2.rows() == 1 && v2.columns() == 1)
+  if (v2.rows () == 1 && v2.columns () == 1)
     {
       double d = v2.scalar_value ();
 
@@ -102,7 +102,7 @@
 {
   CAST_BINOP_ARGS (const octave_sparse_matrix&, const octave_sparse_matrix&);
 
-  if (v1.rows() == 1 && v1.columns() == 1)
+  if (v1.rows () == 1 && v1.columns () == 1)
     {
       double d = v1.double_value ();
 
rename from src/OPERATORS/op-str-m.cc
rename to libinterp/operators/op-str-m.cc
rename from src/OPERATORS/op-str-s.cc
rename to libinterp/operators/op-str-s.cc
rename from src/OPERATORS/op-str-str.cc
rename to libinterp/operators/op-str-str.cc
--- a/src/OPERATORS/op-str-str.cc
+++ b/libinterp/operators/op-str-str.cc
@@ -44,7 +44,7 @@
       return octave_value ();
     }
   else
-    return octave_value (v.char_matrix_value().transpose (),
+    return octave_value (v.char_matrix_value ().transpose (),
                          a.is_sq_string () ? '\'' : '"');
 }
 
rename from src/OPERATORS/op-struct.cc
rename to libinterp/operators/op-struct.cc
--- a/src/OPERATORS/op-struct.cc
+++ b/libinterp/operators/op-struct.cc
@@ -44,7 +44,7 @@
       return octave_value ();
     }
   else
-    return octave_value (v.map_value().transpose ());
+    return octave_value (v.map_value ().transpose ());
 }
 
 DEFUNOP (scalar_transpose, scalar_struct)
rename from src/OPERATORS/op-ui16-ui16.cc
rename to libinterp/operators/op-ui16-ui16.cc
rename from src/OPERATORS/op-ui32-ui32.cc
rename to libinterp/operators/op-ui32-ui32.cc
rename from src/OPERATORS/op-ui64-ui64.cc
rename to libinterp/operators/op-ui64-ui64.cc
rename from src/OPERATORS/op-ui8-ui8.cc
rename to libinterp/operators/op-ui8-ui8.cc
rename from src/ops.h
rename to libinterp/operators/ops.h
--- a/src/ops.h
+++ b/libinterp/operators/ops.h
@@ -341,12 +341,6 @@
     return octave_value (f (v1.CONCAT2(e1, _value) (), v2.CONCAT2(e2, _value) ())); \
   }
 
-#define BINOP_NONCONFORMANT(msg) \
-  gripe_nonconformant (msg, \
-                       a1.rows (), a1.columns (), \
-                       a2.rows (), a2.columns ()); \
-  return octave_value ()
-
 #define CATOPDECL(name, a1, a2) \
   static octave_value \
   CONCAT2(oct_catop_, name) (octave_base_value& a1, const octave_base_value& a2, \
rename from src/lex.h
rename to libinterp/parse-tree/lex.h
--- a/src/lex.h
+++ b/libinterp/parse-tree/lex.h
@@ -23,36 +23,19 @@
 #if !defined (octave_lex_h)
 #define octave_lex_h 1
 
+#include <deque>
+#include <limits>
 #include <list>
+#include <set>
 #include <stack>
 
-// FIXME -- these input buffer things should be members of a
-// parser input stream class.
-
-typedef struct yy_buffer_state *YY_BUFFER_STATE;
-
-// Associate a buffer with a new file to read.
-extern OCTINTERP_API YY_BUFFER_STATE create_buffer (FILE *f);
-
-// Report the current buffer.
-extern OCTINTERP_API YY_BUFFER_STATE current_buffer (void);
-
-// Connect to new buffer buffer.
-extern OCTINTERP_API void switch_to_buffer (YY_BUFFER_STATE buf);
-
-// Delete a buffer.
-extern OCTINTERP_API void delete_buffer (YY_BUFFER_STATE buf);
-
-extern OCTINTERP_API void clear_all_buffers (void);
-
-extern OCTINTERP_API void cleanup_parser (void);
+#include "comment-list.h"
+#include "input.h"
+#include "token.h"
 
 // Is the given string a keyword?
 extern bool is_keyword (const std::string& s);
 
-extern void prep_lexer_for_script_file (void);
-extern void prep_lexer_for_function_file (void);
-
 // For communication between the lexer and parser.
 
 class
@@ -60,141 +43,725 @@
 {
 public:
 
-  lexical_feedback (void)
+  // Track symbol table information when parsing functions.
+
+  class symbol_table_context
+  {
+  public:
+
+    symbol_table_context (void)
+      : frame_stack (), init_scope (symbol_table::current_scope ())
+    {
+      push (init_scope);
+    }
+
+    void clear (void)
+    {
+      while (! frame_stack.empty ())
+        frame_stack.pop ();
+
+      push (init_scope);
+    }
+
+    bool empty (void) const { return frame_stack.empty (); }
+
+    void pop (void)
+    {
+      frame_stack.pop ();
+    }
+
+    void push (symbol_table::scope_id scope)
+    {
+      frame_stack.push (scope);
+    }
+
+    void push (void)
+    {
+      push (symbol_table::current_scope ());
+    }
+
+    symbol_table::scope_id curr_scope (void) const
+    {
+      return frame_stack.top ();
+    }
+
+  private:
+
+    std::stack<symbol_table::scope_id> frame_stack;
+
+    symbol_table::scope_id init_scope;
+  };
+
+  // Track nesting of square brackets, curly braces, and parentheses.
+
+  class bbp_nesting_level
+  {
+  private:
 
-    : bracketflag (0), braceflag (0), looping (0),
-      convert_spaces_to_comma (true), at_beginning_of_statement (true),
-      defining_func (0), looking_at_function_handle (0),
-      looking_at_anon_fcn_args (true),
-      looking_at_return_list (false), looking_at_parameter_list (false),
-      looking_at_decl_list (false), looking_at_initializer_expression (false),
-      looking_at_matrix_or_assign_lhs (false), looking_at_object_index (),
-      looking_for_object_index (false), do_comma_insert (false),
-      looking_at_indirect_ref (false), parsed_function_name (),
-      parsing_class_method (false), maybe_classdef_get_set_method (false),
-      parsing_classdef (false), quote_is_transpose (false),
-      pending_local_variables ()
+    enum bracket_type
+      {
+        BRACKET = 1,
+        BRACE = 2,
+        PAREN = 3,
+        ANON_FCN_BODY = 4
+      };
+
+  public:
+
+    bbp_nesting_level (void) : context () { }
+
+    bbp_nesting_level (const bbp_nesting_level& nl) : context (nl.context) { }
+
+    bbp_nesting_level& operator = (const bbp_nesting_level& nl)
+    {
+      if (&nl != this)
+        context = nl.context;
+
+      return *this;
+    }
+
+    ~bbp_nesting_level (void) { }
+
+    void reset (void)
+    {
+      while (! context.empty ())
+        context.pop ();
+    }
 
+    void bracket (void) { context.push (BRACKET); }
+
+    bool is_bracket (void)
     {
-      init ();
+      return ! context.empty () && context.top () == BRACKET;
+    }
+
+    void brace (void) { context.push (BRACE); }
+
+    bool is_brace (void)
+    {
+      return ! context.empty () && context.top () == BRACE;
+    }
+
+    void paren (void) { context.push (PAREN); }
+
+    bool is_paren (void)
+    {
+      return ! context.empty () && context.top () == PAREN;
+    }
+
+    void anon_fcn_body (void) { context.push (ANON_FCN_BODY); }
+
+    bool is_anon_fcn_body (void)
+    {
+      return ! context.empty () && context.top () == ANON_FCN_BODY;
+    }
+
+    bool is_bracket_or_brace (void)
+    {
+      return (! context.empty ()
+              && (context.top () == BRACKET || context.top () == BRACE));
     }
 
-  ~lexical_feedback (void) { }
+    bool none (void) { return context.empty (); }
+
+    void remove (void)
+    {
+      if (! context.empty ())
+        context.pop ();
+    }
+
+    void clear (void)
+    {
+      while (! context.empty ())
+        context.pop ();
+    }
+
+  private:
+
+    std::stack<int> context;
+  };
+
+  class token_cache
+  {
+  public:
+
+    // Store an "unlimited" number of tokens.
+    token_cache (size_t sz_arg = std::numeric_limits<size_t>::max ())
+      : buffer (), sz (sz_arg)
+    { }
+
+    void push (token *tok)
+    {
+      if (buffer.size () == sz)
+        pop ();
+
+      buffer.push_front (tok);
+    }
+
+    void pop (void)
+    {
+      if (! empty ())
+        {
+          delete buffer.back ();
+          buffer.pop_back ();
+        }
+    }
+
+    // Direct access.
+    token *at (size_t n)
+    {
+      return empty () ? 0 : buffer.at (n);
+    }
+
+    const token *at (size_t n) const
+    {
+      return empty () ? 0 : buffer.at (n);
+    }
+
+    // Most recently pushed.
+    token *front (void)
+    {
+      return empty () ? 0 : buffer.front ();
+    }
+
+    const token *front (void) const
+    {
+      return empty () ? 0 : buffer.front ();
+    }
+
+    token *back (void)
+    {
+      return empty () ? 0 : buffer.back ();
+    }
+
+    const token *back (void) const
+    {
+      return empty () ? 0 : buffer.back ();
+    }
+
+    // Number of elements currently in the buffer, max of sz.
+    size_t size (void) const { return buffer.size (); }
+
+    bool empty (void) const { return buffer.empty (); }
+
+    void clear (void)
+    {
+      while (! empty ())
+        pop ();
+    }
+
+  private:
+
+    std::deque<token *> buffer;
+
+    size_t sz;
+
+    // No copying!
+
+    token_cache (const token_cache&);
+
+    token_cache& operator = (const token_cache&);
+  };
+  
+  lexical_feedback (void)
+    : end_of_input (false), at_beginning_of_statement (true),
+      looking_at_anon_fcn_args (false), looking_at_return_list (false),
+      looking_at_parameter_list (false), looking_at_decl_list (false),
+      looking_at_initializer_expression (false),
+      looking_at_matrix_or_assign_lhs (false),
+      looking_for_object_index (false), 
+      looking_at_indirect_ref (false), parsing_class_method (false),
+      maybe_classdef_get_set_method (false), parsing_classdef (false),
+      quote_is_transpose (false), force_script (false),
+      reading_fcn_file (false), reading_script_file (false),
+      reading_classdef_file (false),
+      input_line_number (1), current_input_column (1),
+      bracketflag (0), braceflag (0),
+      looping (0), defining_func (0), looking_at_function_handle (0),
+      block_comment_nesting_level (0), token_count (0),
+      current_input_line (), comment_text (), help_text (),
+      fcn_file_name (), fcn_file_full_name (), looking_at_object_index (),
+      parsed_function_name (), pending_local_variables (),
+      symtab_context (), nesting_level (), tokens ()
+  {
+    init ();
+  }
+
+  ~lexical_feedback (void);
 
   void init (void);
 
-  // Square bracket level count.
-  int bracketflag;
+  void reset (void);
+
+  int previous_token_value (void) const;
+
+  bool previous_token_value_is (int tok_val) const;
 
-  // Curly brace level count.
-  int braceflag;
+  void mark_previous_token_trailing_space (void);
+
+  bool space_follows_previous_token (void) const;
+
+  bool previous_token_is_binop (void) const;
 
-  // TRUE means we're in the middle of defining a loop.
-  int looping;
+  bool previous_token_is_keyword (void) const;
+
+  bool previous_token_may_be_command (void) const;
+
+  void maybe_mark_previous_token_as_variable (void);
 
-  // TRUE means that we should convert spaces to a comma inside a
-  // matrix definition.
-  bool convert_spaces_to_comma;
+  void mark_as_variable (const std::string& nm);
+  void mark_as_variables (const std::list<std::string>& lst);
 
-  // TRUE means we are at the beginning of a statement, where a
+  // true means that we have encountered eof on the input stream.
+  bool end_of_input;
+
+  // true means we are at the beginning of a statement, where a
   // command name is possible.
   bool at_beginning_of_statement;
 
-  // Nonzero means we're in the middle of defining a function.
-  int defining_func;
-
-  // Nonzero means we are parsing a function handle.
-  int looking_at_function_handle;
-
-  // TRUE means we are parsing an anonymous function argument list.
+  // true means we are parsing an anonymous function argument list.
   bool looking_at_anon_fcn_args;
 
-  // TRUE means we're parsing the return list for a function.
+  // true means we're parsing the return list for a function.
   bool looking_at_return_list;
 
-  // TRUE means we're parsing the parameter list for a function.
+  // true means we're parsing the parameter list for a function.
   bool looking_at_parameter_list;
 
-  // TRUE means we're parsing a declaration list (global or
+  // true means we're parsing a declaration list (global or
   // persistent).
   bool looking_at_decl_list;
 
-  // TRUE means we are looking at the initializer expression for a
+  // true means we are looking at the initializer expression for a
   // parameter list element.
   bool looking_at_initializer_expression;
 
-  // TRUE means we're parsing a matrix or the left hand side of
+  // true means we're parsing a matrix or the left hand side of
   // multi-value assignment statement.
   bool looking_at_matrix_or_assign_lhs;
 
-  // If the front of the list is TRUE, the closest paren, brace, or
+  // object index not possible until we've seen something.
+  bool looking_for_object_index;
+
+  // true means we're looking at an indirect reference to a
+  // structure element.
+  bool looking_at_indirect_ref;
+
+  // true means we are parsing a class method in function or classdef file.
+  bool parsing_class_method;
+
+  // true means we are parsing a class method declaration line in a
+  // classdef file and can accept a property get or set method name.
+  // for example, "get.propertyname" is recognized as a function name.
+  bool maybe_classdef_get_set_method;
+
+  // true means we are parsing a classdef file
+  bool parsing_classdef;
+
+  // return transpose or start a string?
+  bool quote_is_transpose;
+
+  // TRUE means treat the current file as a script even if the first
+  // token is "function" or "classdef".
+  bool force_script;
+
+  // TRUE means we're parsing a function file.
+  bool reading_fcn_file;
+
+  // TRUE means we're parsing a script file.
+  bool reading_script_file;
+
+  // TRUE means we're parsing a classdef file.
+  bool reading_classdef_file;
+
+  // the current input line number.
+  int input_line_number;
+
+  // the column of the current token.
+  int current_input_column;
+
+  // square bracket level count.
+  int bracketflag;
+
+  // curly brace level count.
+  int braceflag;
+
+  // true means we're in the middle of defining a loop.
+  int looping;
+
+  // nonzero means we're in the middle of defining a function.
+  int defining_func;
+
+  // nonzero means we are parsing a function handle.
+  int looking_at_function_handle;
+
+  // nestng level for blcok comments.
+  int block_comment_nesting_level;
+
+  // Count of tokens recognized by this lexer since initialized or
+  // since the last reset.
+  size_t token_count;
+
+  // The current line of input.
+  std::string current_input_line;
+
+  // The current comment text.
+  std::string comment_text;
+
+  // The current help text.
+  std::string help_text;
+
+  // Simple name of function file we are reading.
+  std::string fcn_file_name;
+
+  // Full name of file we are reading.
+  std::string fcn_file_full_name;
+
+  // if the front of the list is true, the closest paren, brace, or
   // bracket nesting is an index for an object.
   std::list<bool> looking_at_object_index;
 
-  // Object index not possible until we've seen something.
-  bool looking_for_object_index;
-
-  // GAG.  Stupid kludge so that [[1,2][3,4]] will work.
-  bool do_comma_insert;
-
-  // TRUE means we're looking at an indirect reference to a
-  // structure element.
-  bool looking_at_indirect_ref;
-
-  // If the top of the stack is TRUE, then we've already seen the name
-  // of the current function.  Should only matter if
+  // if the top of the stack is true, then we've already seen the name
+  // of the current function.  should only matter if
   // current_function_level > 0
   std::stack<bool> parsed_function_name;
 
-  // TRUE means we are parsing a class method in function or classdef file.
-  bool parsing_class_method;
-
-  // TRUE means we are parsing a class method declaration line in a
-  // classdef file and can accept a property get or set method name.
-  // For example, "get.PropertyName" is recognized as a function name.
-  bool maybe_classdef_get_set_method;
-
-  // TRUE means we are parsing a classdef file
-  bool parsing_classdef;
-
-  // Return transpose or start a string?
-  bool quote_is_transpose;
-
-  // Set of identifiers that might be local variable names.
+  // set of identifiers that might be local variable names.
   std::set<std::string> pending_local_variables;
 
+  // Track current symbol table scope and context.
+  symbol_table_context symtab_context;
+
+  // is the closest nesting level a square bracket, squiggly brace,
+  // a paren, or an anonymous function body?
+  bbp_nesting_level nesting_level;
+
+  // Tokens generated by the lexer.
+  token_cache tokens;
+
 private:
 
+  // No copying!
+
   lexical_feedback (const lexical_feedback&);
 
   lexical_feedback& operator = (const lexical_feedback&);
 };
 
+// octave_base_lexer inherits from lexical_feedback because we will
+// eventually have several different constructors and it is easier to
+// intialize if everything is grouped in a parent class rather than
+// listing all the members in the octave_base_lexer class.
+
 class
-stream_reader
+octave_base_lexer : public lexical_feedback
 {
 public:
-  virtual int getc (void) = 0;
-  virtual int ungetc (int c) = 0;
+
+  // Handle buffering of input for lexer.
+
+  class input_buffer
+  {
+  public:
+
+    input_buffer (void)
+      : buffer (), pos (0), chars_left (0), eof (false)
+    { }
+
+    void fill (const std::string& input, bool eof_arg);
+
+    // Copy at most max_size characters to buf.
+    int copy_chunk (char *buf, size_t max_size);
+
+    bool empty (void) const { return chars_left == 0; }
+
+    bool at_eof (void) const { return eof; }
+
+  private:
+
+    std::string buffer;
+    const char *pos;
+    size_t chars_left;
+    bool eof;
+  };
+
+  octave_base_lexer (void)
+    : lexical_feedback (), scanner (0), input_buf ()
+  {
+    init ();
+  }
+
+  virtual ~octave_base_lexer (void);
+
+  void init (void);
+
+  virtual bool is_push_lexer (void) const { return false; }
+
+  virtual void reset (void);
+
+  void prep_for_file (void);
+
+  virtual int fill_flex_buffer (char *buf, unsigned int max_size) = 0;
+
+  bool at_end_of_buffer (void) const { return input_buf.empty (); }
+
+  bool at_end_of_file (void) const { return input_buf.at_eof (); }
+
+  int handle_end_of_input (void);
+
+  char *flex_yytext (void);
+
+  int flex_yyleng (void);
+
+  int text_yyinput (void);
+
+  void xunput (char c, char *buf);
+
+  void xunput (char c);
+
+  bool looking_at_space (void);
+
+  bool inside_any_object_index (void);
+
+  bool is_variable (const std::string& name);
+
+  int is_keyword_token (const std::string& s);
+
+  bool whitespace_is_significant (void);
+
+  void handle_number (void);
+
+  void handle_continuation (void);
+
+  void finish_comment (octave_comment_elt::comment_type typ);
+
+  bool have_continuation (bool trailing_comments_ok = true);
+
+  bool have_ellipsis_continuation (bool trailing_comments_ok = true);
+
+  int handle_string (char delim);
+
+  int handle_close_bracket (int bracket_type);
+
+  bool looks_like_command_arg (void);
+
+  int handle_superclass_identifier (void);
+
+  int handle_meta_identifier (void);
+
+  int handle_identifier (void);
+
+  void maybe_warn_separator_insert (char sep);
+
+  void gripe_single_quote_string (void);
+
+  void gripe_matlab_incompatible (const std::string& msg);
+
+  void maybe_gripe_matlab_incompatible_comment (char c);
+
+  void gripe_matlab_incompatible_continuation (void);
+
+  void gripe_matlab_incompatible_operator (const std::string& op);
+
+  void push_token (token *);
+
+  token *current_token (void);
+
+  void display_token (int tok);
+
+  void fatal_error (const char *msg);
+
+  void lexer_debug (const char *pattern);
+
+  // Internal state of the flex-generated lexer.
+  void *scanner;
+
+  // Object that reads and buffers input.
+  input_buffer input_buf;
+
+  virtual void increment_promptflag (void) = 0;
+
+  virtual void decrement_promptflag (void) = 0;
+
+  virtual int promptflag (void) const = 0;
+
+  virtual int promptflag (int) = 0;
+
+  virtual std::string input_source (void) const { return "unknown"; }
+
+  virtual bool input_from_terminal (void) const { return false; }
+
+  virtual bool input_from_file (void) const { return false; }
+
+  virtual bool input_from_eval_string (void) const { return false; }
+
+  void push_start_state (int state);
+
+  void pop_start_state (void);
+
+  void clear_start_state (void);
+
+  int start_state (void) const { return start_state_stack.top (); }
+
+  void display_start_state (void) const;
+
+  int handle_op (const char *pattern, int tok, bool bos = false);
+
+  int handle_incompatible_op (const char *pattern, int tok, bool bos = false);
+
+  bool maybe_unput_comma_before_unary_op (int tok);
+
+  int handle_unary_op (int tok, bool bos = false);
+
+  int handle_incompatible_unary_op (int tok, bool bos = false);
+
+  int handle_assign_op (const char *pattern, int tok);
+
+  int handle_incompatible_assign_op (const char *pattern, int tok);
+
+  int handle_op_internal (int tok, bool bos, bool compat);
+
+  int handle_token (const std::string& name, int tok);
+
+  int handle_token (int tok, token *tok_val = 0);
+
+  int count_token (int tok);
+
+  int count_token_internal (int tok);
+
+  int show_token (int tok);
+
+  // For unwind protect.
+  static void cleanup (octave_base_lexer *lexer) { delete lexer; }
 
 protected:
-  stream_reader (void) { }
-  ~stream_reader (void) { }
 
-private:
+  std::stack<int> start_state_stack;
 
   // No copying!
-  stream_reader (const stream_reader&);
-  stream_reader& operator = (const stream_reader&);
+
+  octave_base_lexer (const octave_base_lexer&);
+
+  octave_base_lexer& operator = (const octave_base_lexer&);
 };
 
-extern std::string
-grab_comment_block (stream_reader& reader, bool at_bol, bool& eof);
+class
+octave_lexer : public octave_base_lexer
+{
+public:
+
+  octave_lexer (void)
+    : octave_base_lexer (), input_reader ()
+  { }
+
+  octave_lexer (FILE *file)
+    : octave_base_lexer (), input_reader (file)
+  { }
+
+  octave_lexer (const std::string& eval_string)
+    : octave_base_lexer (), input_reader (eval_string)
+  { }
+
+  void reset (void)
+  {
+    input_reader.reset ();
+
+    octave_base_lexer::reset ();
+  }
+
+  void increment_promptflag (void) { input_reader.increment_promptflag (); }
+
+  void decrement_promptflag (void) { input_reader.decrement_promptflag (); }
+
+  int promptflag (void) const { return input_reader.promptflag (); }
+
+  int promptflag (int n) { return input_reader.promptflag (n); }
+
+  std::string input_source (void) const
+  {
+    return input_reader.input_source ();
+  }
+
+  bool input_from_terminal (void) const
+  {
+    return input_source () == "terminal";
+  }
+
+  bool input_from_file (void) const
+  {
+    return input_source () == "file";
+  }
+
+  bool input_from_eval_string (void) const
+  {
+    return input_source () == "eval_string";
+  }
+
+  int fill_flex_buffer (char *buf, unsigned int max_size);
+
+  octave_input_reader input_reader;
+
+protected:
 
-// TRUE means that we have encountered EOF on the input stream.
-extern bool parser_end_of_input;
+  // No copying!
+
+  octave_lexer (const octave_lexer&);
+
+  octave_lexer& operator = (const octave_lexer&);
+};
+
+class
+octave_push_lexer : public octave_base_lexer
+{
+public:
+
+  octave_push_lexer (const std::string& input = std::string (),
+                     bool eof = false)
+    : octave_base_lexer (), pflag (1)
+  {
+    append_input (input, eof);
+  }
+
+  bool is_push_lexer (void) const { return true; }
+
+  void reset (void)
+  {
+    promptflag (1);
+
+    octave_base_lexer::reset ();
+  }
 
-// Flags that need to be shared between the lexer and parser.
-extern lexical_feedback lexer_flags;
+  void append_input (const std::string& input, bool eof)
+  {
+    input_buf.fill (input, eof);
+  }
+
+  void increment_promptflag (void) { pflag++; }
+
+  void decrement_promptflag (void) { pflag--; }
+
+  int promptflag (void) const { return pflag; }
+
+  int promptflag (int n)
+  {
+    int retval = pflag;
+    pflag = n;
+    return retval;
+  }
+
+  std::string input_source (void) const { return "push buffer"; }
+
+  int fill_flex_buffer (char *buf, unsigned int max_size);
+
+protected:
+
+  int pflag;
+
+  // No copying!
+
+  octave_push_lexer (const octave_push_lexer&);
+
+  octave_push_lexer& operator = (const octave_push_lexer&);
+};
 
 #endif
rename from src/lex.ll
rename to libinterp/parse-tree/lex.ll
--- a/src/lex.ll
+++ b/libinterp/parse-tree/lex.ll
@@ -20,7 +20,21 @@
 
 */
 
+/*
+We are using the pure parser interface and the reentrant lexer
+interface but the Octave parser and lexer are NOT properly
+reentrant because both still use many global variables.  It should be
+safe to create a parser object and call it while anotehr parser
+object is active (to parse a callback function while the main
+interactive parser is waiting for input, for example) if you take
+care to properly save and restore (typically with an unwind_protect
+object) relevant global values before and after the nested call.
+*/
+
 %option prefix = "octave_"
+%option noyywrap
+%option reentrant
+%option bison-bridge
 
 %top {
 #ifdef HAVE_CONFIG_H
@@ -32,8 +46,10 @@
 %s COMMAND_START
 %s MATRIX_START
 
-%x SCRIPT_FILE_BEGIN
-%x FUNCTION_FILE_BEGIN
+%x INPUT_FILE_START
+
+%x BLOCK_COMMENT_START
+%x LINE_COMMENT_START
 
 %{
 
@@ -53,9 +69,9 @@
 #include "quit.h"
 #include "lo-mappers.h"
 
-// These would be alphabetical, but y.tab.h must be included before
-// oct-gperf.h and y.tab.h must be included after token.h and the tree
-// class declarations.  We can't include y.tab.h in oct-gperf.h
+// These would be alphabetical, but oct-parse.h must be included before
+// oct-gperf.h and oct-parse.h must be included after token.h and the tree
+// class declarations.  We can't include oct-parse.h in oct-gperf.h
 // because it may not be protected to allow it to be included multiple
 // times.
 
@@ -94,7 +110,8 @@
 #error lex.l requires flex version 2.5.4 or later
 #endif
 
-#define yylval octave_lval
+#define YY_EXTRA_TYPE octave_base_lexer *
+#define curr_lexer yyextra
 
 // Arrange to get input via readline.
 
@@ -102,253 +119,93 @@
 #undef YY_INPUT
 #endif
 #define YY_INPUT(buf, result, max_size) \
-  if ((result = octave_read (buf, max_size)) < 0) \
-    YY_FATAL_ERROR ("octave_read () in flex scanner failed");
+  result = curr_lexer->fill_flex_buffer (buf, max_size)
 
 // Try to avoid crashing out completely on fatal scanner errors.
-// The call to yy_fatal_error should never happen, but it avoids a
-// 'static function defined but not used' warning from gcc.
 
 #ifdef YY_FATAL_ERROR
 #undef YY_FATAL_ERROR
 #endif
 #define YY_FATAL_ERROR(msg) \
-  do \
-    { \
-      error (msg); \
-      OCTAVE_QUIT; \
-      yy_fatal_error (msg); \
-    } \
-  while (0)
-
-#define DISPLAY_TOK_AND_RETURN(tok) \
+  (yyget_extra (yyscanner))->fatal_error (msg)
+
+#define CMD_OR_OP(PATTERN, TOK, COMPAT) \
+ \
   do \
     { \
-      int tok_val = tok; \
-      if (Vdisplay_tokens) \
-        display_token (tok_val); \
-      if (lexer_debug_flag) \
+      curr_lexer->lexer_debug (PATTERN); \
+ \
+      if (curr_lexer->looks_like_command_arg ()) \
         { \
-          std::cerr << "R: "; \
-          display_token (tok_val); \
-          std::cerr << std::endl;  \
+          yyless (0); \
+          curr_lexer->push_start_state (COMMAND_START); \
         } \
-      return tok_val; \
-    } \
-  while (0)
-
-#define COUNT_TOK_AND_RETURN(tok) \
-  do \
-    { \
-      Vtoken_count++; \
-      DISPLAY_TOK_AND_RETURN (tok); \
-    } \
-  while (0)
-
-#define TOK_RETURN(tok) \
-  do \
-    { \
-      current_input_column += yyleng; \
-      lexer_flags.quote_is_transpose = false; \
-      lexer_flags.convert_spaces_to_comma = true; \
-      COUNT_TOK_AND_RETURN (tok); \
+      else \
+        { \
+          return curr_lexer->handle_op_internal (TOK, false, COMPAT); \
+        } \
     } \
   while (0)
 
-#define TOK_PUSH_AND_RETURN(name, tok) \
-  do \
-    { \
-      yylval.tok_val = new token (name, input_line_number, \
-                                  current_input_column); \
-      token_stack.push (yylval.tok_val); \
-      TOK_RETURN (tok); \
-    } \
-  while (0)
-
-#define BIN_OP_RETURN_INTERNAL(tok, convert, bos, qit) \
-  do \
-    { \
-      yylval.tok_val = new token (input_line_number, current_input_column); \
-      token_stack.push (yylval.tok_val); \
-      current_input_column += yyleng; \
-      lexer_flags.quote_is_transpose = qit; \
-      lexer_flags.convert_spaces_to_comma = convert; \
-      lexer_flags.looking_for_object_index = false; \
-      lexer_flags.at_beginning_of_statement = bos; \
-      COUNT_TOK_AND_RETURN (tok); \
-    } \
-  while (0)
-
-#define XBIN_OP_RETURN_INTERNAL(tok, convert, bos, qit) \
-  do \
-    { \
-      gripe_matlab_incompatible_operator (yytext); \
-      BIN_OP_RETURN_INTERNAL (tok, convert, bos, qit); \
-    } \
-  while (0)
-
-#define BIN_OP_RETURN(tok, convert, bos) \
-  do \
-    { \
-      BIN_OP_RETURN_INTERNAL (tok, convert, bos, false); \
-    } \
-  while (0)
-
-#define XBIN_OP_RETURN(tok, convert, bos) \
+#define CMD_OR_UNARY_OP(PATTERN, TOK, COMPAT) \
+ \
   do \
     { \
-      gripe_matlab_incompatible_operator (yytext); \
-      BIN_OP_RETURN (tok, convert, bos); \
-    } \
-  while (0)
-
-#define LEXER_DEBUG(pattern) \
-  do \
-    { \
-      if (lexer_debug_flag) \
-        lexer_debug (pattern, yytext); \
+      curr_lexer->lexer_debug (PATTERN); \
+ \
+      if (curr_lexer->looks_like_command_arg ()) \
+        { \
+          yyless (0); \
+          curr_lexer->push_start_state (COMMAND_START); \
+        } \
+      else \
+        { \
+          int tok \
+            = (COMPAT \
+               ? curr_lexer->handle_unary_op (TOK) \
+               : curr_lexer->handle_incompatible_unary_op (TOK)); \
+ \
+          if (tok < 0) \
+            { \
+              yyless (0); \
+              curr_lexer->xunput (','); \
+              /* Adjust for comma that was not really in the input stream. */ \
+              curr_lexer->current_input_column--; \
+            } \
+          else \
+            { \
+              return tok; \
+            } \
+        } \
     } \
   while (0)
 
-// TRUE means that we have encountered EOF on the input stream.
-bool parser_end_of_input = false;
-
-// Flags that need to be shared between the lexer and parser.
-lexical_feedback lexer_flags;
-
-// Stack to hold tokens so that we can delete them when the parser is
-// reset and avoid growing forever just because we are stashing some
-// information.  This has to appear before lex.h is included, because
-// one of the macros defined there uses token_stack.
-//
-// FIXME -- this should really be static, but that causes
-// problems on some systems.
-std::stack <token*> token_stack;
-
-// Did eat_whitespace() eat a space or tab, or a newline, or both?
-
-typedef int yum_yum;
-
-const yum_yum ATE_NOTHING = 0;
-const yum_yum ATE_SPACE_OR_TAB = 1;
-const yum_yum ATE_NEWLINE = 2;
-
-// Is the closest nesting level a square bracket, squiggly brace or a paren?
-
-class bracket_brace_paren_nesting_level
-{
-public:
-
-  bracket_brace_paren_nesting_level (void) : context () { }
-
-  ~bracket_brace_paren_nesting_level (void) { }
-
-  void bracket (void) { context.push (BRACKET); }
-  bool is_bracket (void)
-    { return ! context.empty () && context.top () == BRACKET; }
-
-  void brace (void) {  context.push (BRACE); }
-  bool is_brace (void)
-    { return ! context.empty () && context.top () == BRACE; }
-
-  void paren (void) {  context.push (PAREN); }
-  bool is_paren (void)
-    { return ! context.empty () && context.top () == PAREN; }
-
-  bool is_bracket_or_brace (void)
-    { return (! context.empty ()
-              && (context.top () == BRACKET || context.top () == BRACE)); }
-
-  bool none (void) { return context.empty (); }
-
-  void remove (void) { if (! context.empty ()) context.pop (); }
-
-  void clear (void) { while (! context.empty ()) context.pop (); }
-
-private:
-
-  std::stack<int> context;
-
-  static const int BRACKET;
-  static const int BRACE;
-  static const int PAREN;
-
-  bracket_brace_paren_nesting_level (const bracket_brace_paren_nesting_level&);
-
-  bracket_brace_paren_nesting_level&
-  operator = (const bracket_brace_paren_nesting_level&);
-};
-
-const int bracket_brace_paren_nesting_level::BRACKET = 1;
-const int bracket_brace_paren_nesting_level::BRACE = 2;
-const int bracket_brace_paren_nesting_level::PAREN = 3;
-
-static bracket_brace_paren_nesting_level nesting_level;
-
 static bool Vdisplay_tokens = false;
 
 static unsigned int Vtoken_count = 0;
 
-// The start state that was in effect when the beginning of a block
-// comment was noticed.
-static int block_comment_nesting_level = 0;
-
 // Internal variable for lexer debugging state.
 static bool lexer_debug_flag = false;
 
 // Forward declarations for functions defined at the bottom of this
-// file.
-
-static int text_yyinput (void);
-static void xunput (char c, char *buf);
-static void fixup_column_count (char *s);
-static void do_comma_insert_check (void);
-static int is_keyword_token (const std::string& s);
-static int process_comment (bool start_in_block, bool& eof);
-static bool match_any (char c, const char *s);
-static bool next_token_is_sep_op (void);
-static bool next_token_is_bin_op (bool spc_prev);
-static bool next_token_is_postfix_unary_op (bool spc_prev);
+// file that are needed inside the lexer actions.
+
 static std::string strip_trailing_whitespace (char *s);
-static void handle_number (void);
-static int handle_string (char delim);
-static int handle_close_bracket (bool spc_gobbled, int bracket_type);
-static int handle_superclass_identifier (void);
-static int handle_meta_identifier (void);
-static int handle_identifier (void);
-static bool have_continuation (bool trailing_comments_ok = true);
-static bool have_ellipsis_continuation (bool trailing_comments_ok = true);
-static void scan_for_comments (const char *);
-static yum_yum eat_whitespace (void);
-static yum_yum eat_continuation (void);
-static void maybe_warn_separator_insert (char sep);
-static void gripe_single_quote_string (void);
-static void gripe_matlab_incompatible (const std::string& msg);
-static void maybe_gripe_matlab_incompatible_comment (char c);
-static void gripe_matlab_incompatible_continuation (void);
-static void gripe_matlab_incompatible_operator (const std::string& op);
-static void display_token (int tok);
-static void lexer_debug (const char *pattern, const char *text);
 
 %}
 
 D       [0-9]
 S       [ \t]
 NL      ((\n)|(\r)|(\r\n))
-SNL     ({S}|{NL})
-EL      (\.\.\.)
-BS      (\\)
-CONT    ({EL}|{BS})
+CONT    ((\.\.\.)|(\\))
 Im      [iIjJ]
 CCHAR   [#%]
-COMMENT ({CCHAR}.*{NL})
-SNLCMT  ({SNL}|{COMMENT})
-NOT     ((\~)|(\!))
-POW     ((\*\*)|(\^))
-EPOW    (\.{POW})
 IDENT   ([_$a-zA-Z][_$a-zA-Z0-9]*)
 EXPON   ([DdEe][+-]?{D}+)
 NUMBER  (({D}+\.?{D}*{EXPON}?)|(\.{D}+{EXPON}?)|(0[xX][0-9a-fA-F]+))
+
+ANY_INCLUDING_NL (.|{NL})
+
 %%
 
 %{
@@ -356,20 +213,18 @@
 // the parser go down a special path.
 %}
 
-<SCRIPT_FILE_BEGIN>. {
-    LEXER_DEBUG ("<SCRIPT_FILE_BEGIN>.");
-
-    BEGIN (INITIAL);
-    xunput (yytext[0], yytext);
-    COUNT_TOK_AND_RETURN (SCRIPT_FILE);
-  }
-
-<FUNCTION_FILE_BEGIN>. {
-    LEXER_DEBUG ("<FUNCTION_FILE_BEGIN>.");
-
-    BEGIN (INITIAL);
-    xunput (yytext[0], yytext);
-    COUNT_TOK_AND_RETURN (FUNCTION_FILE);
+<INPUT_FILE_START>{ANY_INCLUDING_NL} {
+    curr_lexer->lexer_debug ("<INPUT_FILE_START>{ANY_INCLUDING_NL}");
+
+    curr_lexer->xunput (yytext[0]);
+
+    // May be reset later if we see "function" or "classdef" appears
+    // as the first token.
+    curr_lexer->reading_script_file = true;
+
+    curr_lexer->pop_start_state ();
+
+    return curr_lexer->show_token (INPUT_FILE);
   }
 
 %{
@@ -377,54 +232,80 @@
 %}
 
 <COMMAND_START>{NL} {
-    LEXER_DEBUG ("<COMMAND_START>{NL}");
-
-    BEGIN (INITIAL);
-    input_line_number++;
-    current_input_column = 1;
-
-    lexer_flags.quote_is_transpose = false;
-    lexer_flags.convert_spaces_to_comma = true;
-    lexer_flags.looking_for_object_index = false;
-    lexer_flags.at_beginning_of_statement = true;
-
-    COUNT_TOK_AND_RETURN ('\n');
+    curr_lexer->lexer_debug ("<COMMAND_START>{NL}");
+
+    curr_lexer->input_line_number++;
+    curr_lexer->current_input_column = 1;
+
+    curr_lexer->looking_for_object_index = false;
+    curr_lexer->at_beginning_of_statement = true;
+
+    curr_lexer->pop_start_state ();
+
+    return curr_lexer->count_token ('\n');
   }
 
 <COMMAND_START>[\;\,] {
-    LEXER_DEBUG ("<COMMAND_START>[\\;\\,]");
-
-    lexer_flags.looking_for_object_index = false;
-    lexer_flags.at_beginning_of_statement = true;
-
-    BEGIN (INITIAL);
+    curr_lexer->lexer_debug ("<COMMAND_START>[\\;\\,]");
+
+    curr_lexer->looking_for_object_index = false;
+    curr_lexer->at_beginning_of_statement = true;
+
+    curr_lexer->pop_start_state ();
 
     if (strcmp (yytext, ",") == 0)
-      TOK_RETURN (',');
+      return curr_lexer->handle_token (',');
     else
-      TOK_RETURN (';');
+      return curr_lexer->handle_token (';');
   }
 
 <COMMAND_START>[\"\'] {
-    LEXER_DEBUG ("<COMMAND_START>[\\\"\\']");
-
-    lexer_flags.at_beginning_of_statement = false;
-
-    current_input_column++;
-    int tok = handle_string (yytext[0]);
-
-    COUNT_TOK_AND_RETURN (tok);
+    curr_lexer->lexer_debug ("<COMMAND_START>[\\\"\\']");
+
+    curr_lexer->at_beginning_of_statement = false;
+
+    curr_lexer->current_input_column++;
+    int tok = curr_lexer->handle_string (yytext[0]);
+
+    return curr_lexer->count_token_internal (tok);
   }
 
 <COMMAND_START>[^#% \t\r\n\;\,\"\'][^ \t\r\n\;\,]*{S}* {
-    LEXER_DEBUG ("<COMMAND_START>[^#% \\t\\r\\n\\;\\,\\\"\\'][^ \\t\\r\\n\\;\\,]*{S}*");
+    curr_lexer->lexer_debug ("<COMMAND_START>[^#% \\t\\r\\n\\;\\,\\\"\\'][^ \\t\\r\\n\\;\\,]*{S}*");
 
     std::string tok = strip_trailing_whitespace (yytext);
 
-    lexer_flags.looking_for_object_index = false;
-    lexer_flags.at_beginning_of_statement = false;
-
-    TOK_PUSH_AND_RETURN (tok, SQ_STRING);
+    curr_lexer->looking_for_object_index = false;
+    curr_lexer->at_beginning_of_statement = false;
+
+    return curr_lexer->handle_token (tok, SQ_STRING);
+  }
+
+<MATRIX_START>{S}* {
+    curr_lexer->lexer_debug ("<MATRIX_START>{S}*");
+
+    curr_lexer->mark_previous_token_trailing_space ();
+  }
+
+<MATRIX_START>{NL} {
+    curr_lexer->lexer_debug ("<MATRIX_START>{NL}");
+
+    curr_lexer->input_line_number++;
+    curr_lexer->current_input_column = 1;
+
+    if (curr_lexer->nesting_level.is_paren ())
+      curr_lexer->gripe_matlab_incompatible ("bare newline inside parentheses");
+    else
+      {
+        int tok = curr_lexer->previous_token_value ();
+
+        if (! (tok == ';' || tok == '[' || tok == '{'))
+          {
+            curr_lexer->xunput (';');
+            // Adjust for semicolon that was not really in the input stream.
+            curr_lexer->current_input_column--;
+          }
+      }
   }
 
 %{
@@ -441,222 +322,278 @@
 // FIXME -- we need to handle block comments here.
 %}
 
-<MATRIX_START>{SNLCMT}*\]{S}* {
-    LEXER_DEBUG ("<MATRIX_START>{SNLCMT}*\\]{S}*");
-
-    scan_for_comments (yytext);
-    fixup_column_count (yytext);
-
-    lexer_flags.looking_at_object_index.pop_front ();
-
-    lexer_flags.looking_for_object_index = true;
-    lexer_flags.at_beginning_of_statement = false;
-
-    int c = yytext[yyleng-1];
-    int cont_is_spc = eat_continuation ();
-    bool spc_gobbled = (cont_is_spc || c == ' ' || c == '\t');
-    int tok_to_return = handle_close_bracket (spc_gobbled, ']');
-
-    if (spc_gobbled)
-      xunput (' ', yytext);
-
-    COUNT_TOK_AND_RETURN (tok_to_return);
+<MATRIX_START>\] {
+    curr_lexer->lexer_debug ("<MATRIX_START>\\]");
+
+    curr_lexer->looking_at_object_index.pop_front ();
+
+    curr_lexer->looking_for_object_index = true;
+    curr_lexer->at_beginning_of_statement = false;
+
+    curr_lexer->handle_close_bracket (']');
+
+    return curr_lexer->count_token (']');
   }
 
 %{
 // FIXME -- we need to handle block comments here.
 %}
 
-<MATRIX_START>{SNLCMT}*\}{S}* {
-    LEXER_DEBUG ("<MATRIX_START>{SNLCMT}*\\}{S}*");
-
-    scan_for_comments (yytext);
-    fixup_column_count (yytext);
-
-    lexer_flags.looking_at_object_index.pop_front ();
-
-    lexer_flags.looking_for_object_index = true;
-    lexer_flags.at_beginning_of_statement = false;
-
-    int c = yytext[yyleng-1];
-    int cont_is_spc = eat_continuation ();
-    bool spc_gobbled = (cont_is_spc || c == ' ' || c == '\t');
-    int tok_to_return = handle_close_bracket (spc_gobbled, '}');
-
-    if (spc_gobbled)
-      xunput (' ', yytext);
-
-    COUNT_TOK_AND_RETURN (tok_to_return);
+<MATRIX_START>\} {
+    curr_lexer->lexer_debug ("<MATRIX_START>\\}*");
+
+    curr_lexer->looking_at_object_index.pop_front ();
+
+    curr_lexer->looking_for_object_index = true;
+    curr_lexer->at_beginning_of_statement = false;
+
+    curr_lexer->handle_close_bracket ('}');
+
+    return curr_lexer->count_token ('}');
+  }
+
+\[ {
+    curr_lexer->lexer_debug ("\\[");
+
+        bool unput_comma = false;
+
+    if (curr_lexer->whitespace_is_significant ()
+        && curr_lexer->space_follows_previous_token ())
+      {
+        int tok = curr_lexer->previous_token_value ();
+
+        if (! (tok == '[' || tok == '{'
+               || curr_lexer->previous_token_is_binop ()))
+          unput_comma = true;
+      }
+
+    if (unput_comma)
+      {
+        yyless (0);
+        curr_lexer->xunput (',');
+        // Adjust for comma that was not really in the input stream.
+        curr_lexer->current_input_column--;
+      }
+    else
+      {
+        curr_lexer->nesting_level.bracket ();
+
+        curr_lexer->looking_at_object_index.push_front (false);
+
+        curr_lexer->current_input_column += yyleng;
+        curr_lexer->looking_for_object_index = false;
+        curr_lexer->at_beginning_of_statement = false;
+
+        if (curr_lexer->defining_func
+            && ! curr_lexer->parsed_function_name.top ())
+          curr_lexer->looking_at_return_list = true;
+        else
+          curr_lexer->looking_at_matrix_or_assign_lhs = true;
+
+        curr_lexer->decrement_promptflag ();
+
+        curr_lexer->bracketflag++;
+
+        curr_lexer->push_start_state (MATRIX_START);
+
+        return curr_lexer->count_token ('[');
+      }
+  }
+
+\] {
+    curr_lexer->lexer_debug ("\\]");
+
+    curr_lexer->nesting_level.remove ();
+
+    curr_lexer->looking_at_object_index.pop_front ();
+
+    curr_lexer->looking_for_object_index = true;
+    curr_lexer->at_beginning_of_statement = false;
+
+    return curr_lexer->handle_token (']');
   }
 
 %{
-// Commas are element separators in matrix constants.  If we don't
-// check for continuations here we can end up inserting too many
-// commas.
+// Gobble comments.
+%}
+
+%{
+// Start of a block comment.  If the comment marker appears immediately
+// after a block of full-line comments, finish the full line comment
+// block.
 %}
 
-<MATRIX_START>{S}*\,{S}* {
-    LEXER_DEBUG ("<MATRIX_START>{S}*\\,{S}*");
-
-    current_input_column += yyleng;
-
-    int tmp = eat_continuation ();
-
-    lexer_flags.quote_is_transpose = false;
-    lexer_flags.convert_spaces_to_comma = true;
-    lexer_flags.looking_for_object_index = false;
-    lexer_flags.at_beginning_of_statement = false;
-
-    if (! lexer_flags.looking_at_object_index.front ())
+^{S}*{CCHAR}\{{S}*{NL} {
+    curr_lexer->lexer_debug ("^{S}*{CCHAR}\{{S}*{NL}");
+
+    yyless (0);
+
+    if (curr_lexer->start_state () == LINE_COMMENT_START)
       {
-        if ((tmp & ATE_NEWLINE) == ATE_NEWLINE)
-          {
-            maybe_warn_separator_insert (';');
-
-            xunput (';', yytext);
-          }
+        if (! curr_lexer->comment_text.empty ())
+          curr_lexer->finish_comment (octave_comment_elt::full_line);
+
+        curr_lexer->pop_start_state ();
       }
 
-    COUNT_TOK_AND_RETURN (',');
+    curr_lexer->decrement_promptflag ();
+
+    curr_lexer->push_start_state (BLOCK_COMMENT_START);
+
+  }
+
+<BLOCK_COMMENT_START>^{S}*{CCHAR}\{{S}*{NL} {
+    curr_lexer->lexer_debug ("<BLOCK_COMMENT_START>^{S}*{CCHAR}\{{S}*{NL}");
+
+    curr_lexer->input_line_number++;
+    curr_lexer->current_input_column = 1;
+
+    if (curr_lexer->block_comment_nesting_level)
+      curr_lexer->comment_text = "\n";
+
+    curr_lexer->block_comment_nesting_level++;
   }
 
 %{
-// In some cases, spaces in matrix constants can turn into commas.
-// If commas are required, spaces are not important in matrix
-// constants so we just eat them.  If we don't check for continuations
-// here we can end up inserting too many commas.
+// End of a block comment.  If this block comment is nested inside
+// another, wait for the outermost block comment block to be closed
+// before storing the comment.
 %}
 
-<MATRIX_START>{S}+ {
-    LEXER_DEBUG ("<MATRIX_START>{S}+");
-
-    current_input_column += yyleng;
-
-    lexer_flags.at_beginning_of_statement = false;
-
-    int tmp = eat_continuation ();
-
-    if (! lexer_flags.looking_at_object_index.front ())
+<BLOCK_COMMENT_START>^{S}*{CCHAR}\}{S}*{NL} {
+    curr_lexer->lexer_debug ("<BLOCK_COMMENT_START>^{S}*{CCHAR}\\}{S}*{NL}");
+
+    curr_lexer->input_line_number++;
+    curr_lexer->current_input_column = 1;
+
+    if (curr_lexer->block_comment_nesting_level > 1)
+      curr_lexer->comment_text = "\n";
+    else
+      curr_lexer->finish_comment (octave_comment_elt::block);
+
+    curr_lexer->block_comment_nesting_level--;
+
+    if (curr_lexer->block_comment_nesting_level == 0)
       {
-        bool bin_op = next_token_is_bin_op (true);
-        bool postfix_un_op = next_token_is_postfix_unary_op (true);
-        bool sep_op = next_token_is_sep_op ();
-
-        if (! (postfix_un_op || bin_op || sep_op)
-            && nesting_level.is_bracket_or_brace ()
-            && lexer_flags.convert_spaces_to_comma)
-          {
-            if ((tmp & ATE_NEWLINE) == ATE_NEWLINE)
-              {
-                maybe_warn_separator_insert (';');
-
-                xunput (';', yytext);
-              }
-
-            lexer_flags.quote_is_transpose = false;
-            lexer_flags.convert_spaces_to_comma = true;
-            lexer_flags.looking_for_object_index = false;
-
-            maybe_warn_separator_insert (',');
-
-            COUNT_TOK_AND_RETURN (',');
-          }
+        curr_lexer->increment_promptflag ();
+
+        curr_lexer->pop_start_state ();
       }
   }
 
 %{
-// Semicolons are handled as row seprators in matrix constants.  If we
-// don't eat whitespace here we can end up inserting too many
-// semicolons.
-
-// FIXME -- we need to handle block comments here.
+// Body of a block comment.
 %}
 
-<MATRIX_START>{SNLCMT}*;{SNLCMT}* {
-    LEXER_DEBUG ("<MATRIX_START>{SNLCMT}*;{SNLCMT}*");
-
-    scan_for_comments (yytext);
-    fixup_column_count (yytext);
-    eat_whitespace ();
-
-    lexer_flags.quote_is_transpose = false;
-    lexer_flags.convert_spaces_to_comma = true;
-    lexer_flags.looking_for_object_index = false;
-    lexer_flags.at_beginning_of_statement = false;
-
-    COUNT_TOK_AND_RETURN (';');
+<BLOCK_COMMENT_START>.*{NL} {
+    curr_lexer->lexer_debug ("<BLOCK_COMMENT_START>.*{NL}");
+
+    curr_lexer->input_line_number++;
+    curr_lexer->current_input_column = 1;
+    curr_lexer->comment_text += yytext;
   }
 
 %{
-// In some cases, new lines can also become row separators.  If we
-// don't eat whitespace here we can end up inserting too many
-// semicolons.
-
-// FIXME -- we need to handle block comments here.
+// Full-line or end-of-line comment.
 %}
 
-<MATRIX_START>{S}*{COMMENT}{SNLCMT}* |
-<MATRIX_START>{S}*{NL}{SNLCMT}* {
-    LEXER_DEBUG ("<MATRIX_START>{S}*{COMMENT}{SNLCMT}*|<MATRIX_START>{S}*{NL}{SNLCMT}*");
-
-    scan_for_comments (yytext);
-    fixup_column_count (yytext);
-    eat_whitespace ();
-
-    lexer_flags.quote_is_transpose = false;
-    lexer_flags.convert_spaces_to_comma = true;
-    lexer_flags.at_beginning_of_statement = false;
-
-    if (nesting_level.none ())
-      return LEXICAL_ERROR;
-
-    if (! lexer_flags.looking_at_object_index.front ()
-        && nesting_level.is_bracket_or_brace ())
+{S}*{CCHAR}.*{NL} {
+    curr_lexer->lexer_debug ("{S}*{CCHAR}.*{NL}");
+
+    curr_lexer->push_start_state (LINE_COMMENT_START);
+    yyless (0);
+  }
+
+<LINE_COMMENT_START>{S}*{CCHAR}.*{NL} {
+    curr_lexer->lexer_debug ("<LINE_COMMENT_START>{S}*{CCHAR}.*{NL}");
+
+    bool full_line_comment = curr_lexer->current_input_column == 1;
+    curr_lexer->input_line_number++;
+    curr_lexer->current_input_column = 1;
+
+    bool have_space = false;
+    size_t len = yyleng;
+    size_t i = 0;
+    while (i < len)
+      {
+        char c = yytext[i];
+        if (c == ' ' || c == '\t')
+          {
+            have_space = true;
+            i++;
+          }
+        else
+          break;
+      }
+
+    size_t num_comment_chars = 0;
+
+    while (i < len)
       {
-        maybe_warn_separator_insert (';');
-
-        COUNT_TOK_AND_RETURN (';');
+        char c = yytext[i];
+        if (c == '#' || c == '%')
+          {
+            num_comment_chars++;
+            i++;
+          }
+        else
+          break;
+      }
+
+    curr_lexer->comment_text += &yytext[i];
+
+    if (full_line_comment)
+      {
+        if (yytext[i++] == '{')
+          {
+            bool looks_like_block_comment = true;
+
+            while (i < len)
+              {
+                char c = yytext[i++];
+                if (! (c == ' ' || c == '\t' || c == '\n'))
+                  {
+                    looks_like_block_comment = false;
+                    break;
+                  }
+              }      
+
+            if (looks_like_block_comment)
+              {
+                yyless (0);
+
+                curr_lexer->finish_comment (octave_comment_elt::full_line);
+
+                curr_lexer->pop_start_state ();
+              }
+          }
+      }
+    else
+      {
+        if (have_space)
+          curr_lexer->mark_previous_token_trailing_space ();
+
+        curr_lexer->finish_comment (octave_comment_elt::end_of_line);
+
+        curr_lexer->pop_start_state ();
+
+        curr_lexer->xunput ('\n');
+        curr_lexer->input_line_number--;
       }
   }
 
-\[{S}* {
-    LEXER_DEBUG ("\\[{S}*");
-
-    nesting_level.bracket ();
-
-    lexer_flags.looking_at_object_index.push_front (false);
-
-    current_input_column += yyleng;
-    lexer_flags.quote_is_transpose = false;
-    lexer_flags.convert_spaces_to_comma = true;
-    lexer_flags.looking_for_object_index = false;
-    lexer_flags.at_beginning_of_statement = false;
-
-    if (lexer_flags.defining_func
-        && ! lexer_flags.parsed_function_name.top ())
-      lexer_flags.looking_at_return_list = true;
-    else
-      lexer_flags.looking_at_matrix_or_assign_lhs = true;
-
-    promptflag--;
-    eat_whitespace ();
-
-    lexer_flags.bracketflag++;
-    BEGIN (MATRIX_START);
-    COUNT_TOK_AND_RETURN ('[');
-  }
-
-\] {
-    LEXER_DEBUG ("\\]");
-
-    nesting_level.remove ();
-
-    lexer_flags.looking_at_object_index.pop_front ();
-
-    lexer_flags.looking_for_object_index = true;
-    lexer_flags.at_beginning_of_statement = false;
-
-    TOK_RETURN (']');
+%{
+// End of a block of full-line comments.
+%}
+
+<LINE_COMMENT_START>{ANY_INCLUDING_NL} {
+    curr_lexer->lexer_debug ("<LINE_COMMENT_START>{ANY_INCLUDING_NL}");
+
+    curr_lexer->xunput (yytext[0]);
+
+    curr_lexer->finish_comment (octave_comment_elt::full_line);  
+
+    curr_lexer->pop_start_state ();
   }
 
 %{
@@ -664,10 +601,32 @@
 %}
 
 {NUMBER}{Im} {
-    LEXER_DEBUG ("{NUMBER}{Im}");
-
-    handle_number ();
-    COUNT_TOK_AND_RETURN (IMAG_NUM);
+    curr_lexer->lexer_debug ("{NUMBER}{Im}");
+
+    if (curr_lexer->previous_token_may_be_command ()
+        &&  curr_lexer->space_follows_previous_token ())
+      {
+        yyless (0);
+        curr_lexer->push_start_state (COMMAND_START);
+      }
+    else
+      {
+        int tok = curr_lexer->previous_token_value ();
+
+        if (curr_lexer->whitespace_is_significant ()
+            && curr_lexer->space_follows_previous_token ()
+            && ! (tok == '[' || tok == '{'
+                  || curr_lexer->previous_token_is_binop ()))
+          {
+            yyless (0);
+            unput (',');
+          }
+        else
+          {
+            curr_lexer->handle_number ();
+            return curr_lexer->count_token_internal (IMAG_NUM);
+          }
+      }
   }
 
 %{
@@ -677,9 +636,32 @@
 
 {D}+/\.[\*/\\^\'] |
 {NUMBER} {
-    LEXER_DEBUG ("{D}+/\\.[\\*/\\^\\']|{NUMBER}");
-    handle_number ();
-    COUNT_TOK_AND_RETURN (NUM);
+    curr_lexer->lexer_debug ("{D}+/\\.[\\*/\\^\\']|{NUMBER}");
+
+    if (curr_lexer->previous_token_may_be_command ()
+        &&  curr_lexer->space_follows_previous_token ())
+      {
+        yyless (0);
+        curr_lexer->push_start_state (COMMAND_START);
+      }
+    else
+      {
+        int tok = curr_lexer->previous_token_value ();
+
+        if (curr_lexer->whitespace_is_significant ()
+            && curr_lexer->space_follows_previous_token ()
+            && ! (tok == '[' || tok == '{'
+                  || curr_lexer->previous_token_is_binop ()))
+          {
+            yyless (0);
+            unput (',');
+          }
+        else
+          {
+            curr_lexer->handle_number ();
+            return curr_lexer->count_token_internal (NUM);
+          }
+      }
   }
 
 %{
@@ -687,8 +669,10 @@
 // the <MATRIX_START> start state code above.
 %}
 
-{S}* {
-    current_input_column += yyleng;
+{S}+ {
+    curr_lexer->current_input_column += yyleng;
+
+    curr_lexer->mark_previous_token_trailing_space ();
   }
 
 %{
@@ -696,15 +680,10 @@
 %}
 
 {CONT}{S}*{NL} |
-{CONT}{S}*{COMMENT} {
-    LEXER_DEBUG ("{CONT}{S}*{NL}|{CONT}{S}*{COMMENT}");
-
-    if (yytext[0] == '\\')
-      gripe_matlab_incompatible_continuation ();
-    scan_for_comments (yytext);
-    promptflag--;
-    input_line_number++;
-    current_input_column = 1;
+{CONT}{S}*{CCHAR}.*{NL} {
+    curr_lexer->lexer_debug ("{CONT}{S}*{NL}|{CONT}{S}*{CCHAR}.*{NL}");
+
+    curr_lexer->handle_continuation ();
   }
 
 %{
@@ -712,50 +691,59 @@
 %}
 
 <<EOF>> {
-    LEXER_DEBUG ("<<EOF>>");
-
-    if (block_comment_nesting_level != 0)
-      {
-        warning ("block comment open at end of input");
-
-        if ((reading_fcn_file || reading_script_file || reading_classdef_file)
-            && ! curr_fcn_file_name.empty ())
-          warning ("near line %d of file '%s.m'",
-                   input_line_number, curr_fcn_file_name.c_str ());
-      }
-
-    TOK_RETURN (END_OF_INPUT);
+   return curr_lexer->handle_end_of_input ();
   }
 
 %{
-// Identifiers.  Truncate the token at the first space or tab but
-// don't write directly on yytext.
+// Identifiers.
 %}
 
-{IDENT}{S}* {
-    LEXER_DEBUG ("{IDENT}{S}*");
-
-    int id_tok = handle_identifier ();
-
-    if (id_tok >= 0)
-      COUNT_TOK_AND_RETURN (id_tok);
+{IDENT} {
+    curr_lexer->lexer_debug ("{IDENT}");
+
+    int tok = curr_lexer->previous_token_value ();
+
+    if (curr_lexer->whitespace_is_significant ()
+        && curr_lexer->space_follows_previous_token ()
+        && ! (tok == '[' || tok == '{'
+              || curr_lexer->previous_token_is_binop ()))
+      {
+        yyless (0);
+        unput (',');
+      }
+    else
+      {
+        if (! curr_lexer->looking_at_decl_list
+            && curr_lexer->previous_token_may_be_command ())
+          {
+            yyless (0);
+            curr_lexer->push_start_state (COMMAND_START);
+          }
+        else
+          {
+            int id_tok = curr_lexer->handle_identifier ();
+
+            if (id_tok >= 0)
+              return curr_lexer->count_token_internal (id_tok);
+          }
+      }
   }
 
 %{
 // Superclass method identifiers.
 %}
 
-{IDENT}@{IDENT}{S}* |
-{IDENT}@{IDENT}.{IDENT}{S}* {
-    LEXER_DEBUG ("{IDENT}@{IDENT}{S}*|{IDENT}@{IDENT}.{IDENT}{S}*");
-
-    int id_tok = handle_superclass_identifier ();
+{IDENT}@{IDENT} |
+{IDENT}@{IDENT}.{IDENT} {
+    curr_lexer->lexer_debug ("{IDENT}@{IDENT}|{IDENT}@{IDENT}.{IDENT}");
+
+    int id_tok = curr_lexer->handle_superclass_identifier ();
 
     if (id_tok >= 0)
       {
-        lexer_flags.looking_for_object_index = true;
-
-        COUNT_TOK_AND_RETURN (SUPERCLASSREF);
+        curr_lexer->looking_for_object_index = true;
+
+        return curr_lexer->count_token_internal (SUPERCLASSREF);
       }
   }
 
@@ -763,37 +751,39 @@
 // Metaclass query
 %}
 
-\?{IDENT}{S}* |
-\?{IDENT}.{IDENT}{S}* {
-    LEXER_DEBUG ("\?{IDENT}{S}* | \?{IDENT}.{IDENT}{S}*");
-
-    int id_tok = handle_meta_identifier ();
+\?{IDENT} |
+\?{IDENT}\.{IDENT} {
+    curr_lexer->lexer_debug ("\\?{IDENT}|\\?{IDENT}\\.{IDENT}");
+
+    int id_tok = curr_lexer->handle_meta_identifier ();
 
     if (id_tok >= 0)
       {
-        lexer_flags.looking_for_object_index = true;
-
-        COUNT_TOK_AND_RETURN (METAQUERY);
+        curr_lexer->looking_for_object_index = true;
+
+        return curr_lexer->count_token_internal (METAQUERY);
       }
   }
 
-%{
-// Function handles and superclass references
-%}
-
 "@" {
-    LEXER_DEBUG ("@");
-
-    current_input_column++;
-
-    lexer_flags.quote_is_transpose = false;
-    lexer_flags.convert_spaces_to_comma = false;
-    lexer_flags.looking_at_function_handle++;
-    lexer_flags.looking_for_object_index = false;
-    lexer_flags.at_beginning_of_statement = false;
-
-    COUNT_TOK_AND_RETURN ('@');
-
+    if (curr_lexer->previous_token_may_be_command ()
+        &&  curr_lexer->space_follows_previous_token ())
+      {
+        yyless (0);
+        curr_lexer->push_start_state (COMMAND_START);
+      }
+    else
+      {
+        curr_lexer->lexer_debug ("@");
+
+        curr_lexer->current_input_column++;
+
+        curr_lexer->looking_at_function_handle++;
+        curr_lexer->looking_for_object_index = false;
+        curr_lexer->at_beginning_of_statement = false;
+
+        return curr_lexer->count_token ('@');
+      }
   }
 
 %{
@@ -803,25 +793,24 @@
 %}
 
 {NL} {
-    LEXER_DEBUG ("{NL}");
-
-    input_line_number++;
-    current_input_column = 1;
-
-    lexer_flags.quote_is_transpose = false;
-    lexer_flags.convert_spaces_to_comma = true;
-
-    if (nesting_level.none ())
+    curr_lexer->lexer_debug ("{NL}");
+
+    curr_lexer->input_line_number++;
+    curr_lexer->current_input_column = 1;
+
+    if (curr_lexer->nesting_level.is_paren ())
       {
-        lexer_flags.at_beginning_of_statement = true;
-        COUNT_TOK_AND_RETURN ('\n');
+        curr_lexer->at_beginning_of_statement = false;
+        curr_lexer->gripe_matlab_incompatible
+          ("bare newline inside parentheses");
       }
-    else if (nesting_level.is_paren ())
+    else if (curr_lexer->nesting_level.none ()
+        || curr_lexer->nesting_level.is_anon_fcn_body ())
       {
-        lexer_flags.at_beginning_of_statement = false;
-        gripe_matlab_incompatible ("bare newline inside parentheses");
+        curr_lexer->at_beginning_of_statement = true;
+        return curr_lexer->count_token ('\n');
       }
-    else if (nesting_level.is_bracket_or_brace ())
+    else if (curr_lexer->nesting_level.is_bracket_or_brace ())
       return LEXICAL_ERROR;
   }
 
@@ -831,20 +820,64 @@
 %}
 
 "'" {
-    LEXER_DEBUG ("'");
-
-    current_input_column++;
-    lexer_flags.convert_spaces_to_comma = true;
-
-    if (lexer_flags.quote_is_transpose)
+    curr_lexer->lexer_debug ("'");
+
+    if (curr_lexer->previous_token_may_be_command ()
+        &&  curr_lexer->space_follows_previous_token ())
       {
-        do_comma_insert_check ();
-        COUNT_TOK_AND_RETURN (QUOTE);
+        yyless (0);
+        curr_lexer->push_start_state (COMMAND_START);
       }
     else
       {
-        int tok = handle_string ('\'');
-        COUNT_TOK_AND_RETURN (tok);
+        int tok = curr_lexer->previous_token_value ();
+
+        if (curr_lexer->whitespace_is_significant ())
+          {
+            if (curr_lexer->space_follows_previous_token ())
+              {
+                if (tok == '[' || tok == '{'
+                    || curr_lexer->previous_token_is_binop ())
+                  {
+                    curr_lexer->current_input_column++;
+                    int retval = curr_lexer->handle_string ('\'');
+                    return curr_lexer->count_token_internal (retval);
+                  }
+                else
+                  {
+                    yyless (0);
+                    curr_lexer->xunput (',');
+                    // Adjust for comma that was not really in the input stream.
+                    curr_lexer->current_input_column--;
+                  }
+              }
+            else
+              {
+                if (tok == '[' || tok == '{'
+                    || curr_lexer->previous_token_is_binop ()
+                    || curr_lexer->previous_token_is_keyword ())
+                  {
+                    curr_lexer->current_input_column++;
+                    int retval = curr_lexer->handle_string ('\'');
+                    return curr_lexer->count_token_internal (retval);
+                  }
+                else
+                  return curr_lexer->count_token (HERMITIAN);
+              }
+          }
+        else
+          {
+            if (! tok || tok == '[' || tok == '{' || tok == '('
+                || curr_lexer->previous_token_is_binop ()
+                || curr_lexer->previous_token_is_keyword ())
+              {
+                curr_lexer->current_input_column++;
+                int retval = curr_lexer->handle_string ('\'');
+                return curr_lexer->count_token_internal (retval);
+              }
+            else
+              return curr_lexer->count_token (HERMITIAN);
+          }
       }
   }
 
@@ -853,204 +886,316 @@
 %}
 
 \" {
-    LEXER_DEBUG ("\"");
-
-    current_input_column++;
-    int tok = handle_string ('"');
-
-    COUNT_TOK_AND_RETURN (tok);
-}
-
-%{
-// Gobble comments.
-%}
-
-{CCHAR} {
-    LEXER_DEBUG ("{CCHAR}");
-
-    lexer_flags.looking_for_object_index = false;
-
-    xunput (yytext[0], yytext);
-
-    bool eof = false;
-    int tok = process_comment (false, eof);
-
-    if (eof)
-      TOK_RETURN (END_OF_INPUT);
-    else if (tok > 0)
-      COUNT_TOK_AND_RETURN (tok);
-  }
-
-%{
-// Block comments.
-%}
-
-^{S}*{CCHAR}\{{S}*{NL} {
-    LEXER_DEBUG ("^{S}*{CCHAR}\\{{S}*{NL}");
-
-    lexer_flags.looking_for_object_index = false;
-
-    input_line_number++;
-    current_input_column = 1;
-    block_comment_nesting_level++;
-    promptflag--;
-
-    bool eof = false;
-    process_comment (true, eof);
+    curr_lexer->lexer_debug ("\"");
+
+    if (curr_lexer->previous_token_may_be_command ()
+        &&  curr_lexer->space_follows_previous_token ())
+      {
+        yyless (0);
+        curr_lexer->push_start_state (COMMAND_START);
+      }
+    else
+      {
+        int tok = curr_lexer->previous_token_value ();
+
+        if (curr_lexer->whitespace_is_significant ())
+          {
+            if (curr_lexer->space_follows_previous_token ())
+              {
+                if (tok == '[' || tok == '{'
+                    || curr_lexer->previous_token_is_binop ())
+                  {
+                    curr_lexer->current_input_column++;
+                    int retval = curr_lexer->handle_string ('"');
+                    return curr_lexer->count_token_internal (retval);
+                  }
+                else
+                  {
+                    yyless (0);
+                    curr_lexer->xunput (',');
+                    // Adjust for comma that was not really in the input stream.
+                    curr_lexer->current_input_column--;
+                  }
+              }
+            else
+              {
+                curr_lexer->current_input_column++;
+                int retval = curr_lexer->handle_string ('"');
+                return curr_lexer->count_token_internal (retval);
+              }
+          }
+        else
+          {
+            curr_lexer->current_input_column++;
+            int retval = curr_lexer->handle_string ('"');
+            return curr_lexer->count_token_internal (retval);
+          }
+      }
   }
 
 %{
 // Other operators.
 %}
 
-":"     { LEXER_DEBUG (":"); BIN_OP_RETURN (':', false, false); }
-
-".+"    { LEXER_DEBUG (".+"); XBIN_OP_RETURN (EPLUS, false, false); }
-".-"    { LEXER_DEBUG (".-"); XBIN_OP_RETURN (EMINUS, false, false); }
-".*"    { LEXER_DEBUG (".*"); BIN_OP_RETURN (EMUL, false, false); }
-"./"    { LEXER_DEBUG ("./"); BIN_OP_RETURN (EDIV, false, false); }
-".\\"   { LEXER_DEBUG (".\\"); BIN_OP_RETURN (ELEFTDIV, false, false); }
-".^"    { LEXER_DEBUG (".^"); BIN_OP_RETURN (EPOW, false, false); }
-".**"   { LEXER_DEBUG (".**"); XBIN_OP_RETURN (EPOW, false, false); }
-".'"    { LEXER_DEBUG (".'"); do_comma_insert_check (); BIN_OP_RETURN (TRANSPOSE, true, false); }
-"++"    { LEXER_DEBUG ("++"); do_comma_insert_check (); XBIN_OP_RETURN_INTERNAL (PLUS_PLUS, true, false, true); }
-"--"    { LEXER_DEBUG ("--"); do_comma_insert_check (); XBIN_OP_RETURN_INTERNAL (MINUS_MINUS, true, false, true); }
-"<="    { LEXER_DEBUG ("<="); BIN_OP_RETURN (EXPR_LE, false, false); }
-"=="    { LEXER_DEBUG ("=="); BIN_OP_RETURN (EXPR_EQ, false, false); }
-"~="    { LEXER_DEBUG ("~="); BIN_OP_RETURN (EXPR_NE, false, false); }
-"!="    { LEXER_DEBUG ("!="); XBIN_OP_RETURN (EXPR_NE, false, false); }
-">="    { LEXER_DEBUG (">="); BIN_OP_RETURN (EXPR_GE, false, false); }
-"&"     { LEXER_DEBUG ("&"); BIN_OP_RETURN (EXPR_AND, false, false); }
-"|"     { LEXER_DEBUG ("|"); BIN_OP_RETURN (EXPR_OR, false, false); }
-"<"     { LEXER_DEBUG ("<"); BIN_OP_RETURN (EXPR_LT, false, false); }
-">"     { LEXER_DEBUG (">"); BIN_OP_RETURN (EXPR_GT, false, false); }
-"+"     { LEXER_DEBUG ("+"); BIN_OP_RETURN ('+', false, false); }
-"-"     { LEXER_DEBUG ("-"); BIN_OP_RETURN ('-', false, false); }
-"*"     { LEXER_DEBUG ("*"); BIN_OP_RETURN ('*', false, false); }
-"/"     { LEXER_DEBUG ("/"); BIN_OP_RETURN ('/', false, false); }
-"\\"    { LEXER_DEBUG ("\\"); BIN_OP_RETURN (LEFTDIV, false, false); }
-";"     { LEXER_DEBUG (";"); BIN_OP_RETURN (';', true, true); }
-","     { LEXER_DEBUG (","); BIN_OP_RETURN (',', true, ! lexer_flags.looking_at_object_index.front ()); }
-"^"     { LEXER_DEBUG ("^"); BIN_OP_RETURN (POW, false, false); }
-"**"    { LEXER_DEBUG ("**"); XBIN_OP_RETURN (POW, false, false); }
-"="     { LEXER_DEBUG ("="); BIN_OP_RETURN ('=', true, false); }
-"&&"    { LEXER_DEBUG ("&&"); BIN_OP_RETURN (EXPR_AND_AND, false, false); }
-"||"    { LEXER_DEBUG ("||"); BIN_OP_RETURN (EXPR_OR_OR, false, false); }
-"<<"    { LEXER_DEBUG ("<<"); XBIN_OP_RETURN (LSHIFT, false, false); }
-">>"    { LEXER_DEBUG (">>"); XBIN_OP_RETURN (RSHIFT, false, false); }
-
-{NOT} {
-    LEXER_DEBUG ("{NOT}");
-
-    if (yytext[0] == '~')
-      BIN_OP_RETURN (EXPR_NOT, false, false);
+":"   { CMD_OR_OP (":", ':', true); }
+".+"  { CMD_OR_OP (".+", EPLUS, false); }
+".-"  { CMD_OR_OP (".-", EMINUS, false); }
+".*"  { CMD_OR_OP (".*", EMUL, true); }
+"./"  { CMD_OR_OP ("./", EDIV, true); }
+".\\" { CMD_OR_OP (".\\", ELEFTDIV, true); }
+".^"  { CMD_OR_OP (".^", EPOW, true); }
+".**" { CMD_OR_OP (".**", EPOW, false); }
+"<="  { CMD_OR_OP ("<=", EXPR_LE, true); }
+"=="  { CMD_OR_OP ("==", EXPR_EQ, true); }
+"~="  { CMD_OR_OP ("~=", EXPR_NE, true); }
+"!="  { CMD_OR_OP ("!=", EXPR_NE, false); }
+">="  { CMD_OR_OP (">=", EXPR_GE, true); }
+"&"   { CMD_OR_OP ("&", EXPR_AND, true); }
+"|"   { CMD_OR_OP ("|", EXPR_OR, true); }
+"<"   { CMD_OR_OP ("<", EXPR_LT, true); }
+">"   { CMD_OR_OP (">", EXPR_GT, true); }
+"*"   { CMD_OR_OP ("*", '*', true); }
+"/"   { CMD_OR_OP ("/", '/', true); }
+
+%{
+// In Matlab, '\' may also trigger command syntax.
+%}
+
+"\\"  { return curr_lexer->handle_op ("\\", LEFTDIV); }
+
+"^"   { CMD_OR_OP ("^", POW, true); }
+"**"  { CMD_OR_OP ("**", POW, false); }
+"&&"  { CMD_OR_OP ("&&", EXPR_AND_AND, true); }
+"||"  { CMD_OR_OP ("||", EXPR_OR_OR, true); }
+"<<"  { CMD_OR_OP ("<<", LSHIFT, false); }
+">>"  { CMD_OR_OP (">>", RSHIFT, false); }
+
+";" {
+    bool at_beginning_of_statement
+      = (! (curr_lexer->whitespace_is_significant ()
+            || curr_lexer->looking_at_object_index.front ()));
+
+    return curr_lexer->handle_op (";", ';', at_beginning_of_statement);
+  }
+
+"+" { CMD_OR_UNARY_OP ("+", '+', true); }
+"-" { CMD_OR_UNARY_OP ("-", '-', true); }
+
+"~" { CMD_OR_UNARY_OP ("~", EXPR_NOT, true); }
+"!" { CMD_OR_UNARY_OP ("!", EXPR_NOT, false); }
+
+"," {
+    bool at_beginning_of_statement
+      = (! (curr_lexer->whitespace_is_significant ()
+            || curr_lexer->looking_at_object_index.front ()));
+
+    return curr_lexer->handle_op (",", ',', at_beginning_of_statement);
+  }
+
+".'" {
+    return curr_lexer->handle_op (".'", TRANSPOSE, false);
+  }
+
+"++" {
+    curr_lexer->lexer_debug ("++");
+
+    int tok = curr_lexer->handle_incompatible_unary_op (PLUS_PLUS, false);
+
+    if (tok < 0)
+      {
+        yyless (0);
+        curr_lexer->xunput (',');
+        // Adjust for comma that was not really in the input stream.
+        curr_lexer->current_input_column--;
+      }
     else
-      XBIN_OP_RETURN (EXPR_NOT, false, false);
+      return tok;
+  }
+
+"--" {
+    curr_lexer->lexer_debug ("--");
+
+    int tok = curr_lexer->handle_incompatible_unary_op (MINUS_MINUS, false);
+
+    if (tok < 0)
+      {
+        yyless (0);
+        curr_lexer->xunput (',');
+        // Adjust for comma that was not really in the input stream.
+        curr_lexer->current_input_column--;
+      }
+    else
+      return tok;
   }
 
 "(" {
-    LEXER_DEBUG ("(");
-
-    // If we are looking for an object index, then push TRUE for
-    // looking_at_object_index.  Otherwise, just push whatever state
-    // is current (so that we can pop it off the stack when we find
-    // the matching close paren).
-
-    lexer_flags.looking_at_object_index.push_front
-      (lexer_flags.looking_for_object_index);
-
-    lexer_flags.looking_at_indirect_ref = false;
-    lexer_flags.looking_for_object_index = false;
-    lexer_flags.at_beginning_of_statement = false;
-
-    nesting_level.paren ();
-    promptflag--;
-
-    TOK_RETURN ('(');
+    curr_lexer->lexer_debug ("(");
+
+    bool unput_comma = false;
+
+    if (curr_lexer->whitespace_is_significant ()
+        && curr_lexer->space_follows_previous_token ())
+      {
+        int tok = curr_lexer->previous_token_value ();
+
+        if (! (tok == '[' || tok == '{'
+               || curr_lexer->previous_token_is_binop ()))
+          unput_comma = true;
+      }
+
+    if (unput_comma)
+      {
+        yyless (0);
+        curr_lexer->xunput (',');
+        // Adjust for comma that was not really in the input stream.
+        curr_lexer->current_input_column--;
+      }
+    else
+      {
+        // If we are looking for an object index, then push TRUE for
+        // looking_at_object_index.  Otherwise, just push whatever state
+        // is current (so that we can pop it off the stack when we find
+        // the matching close paren).
+
+        curr_lexer->looking_at_object_index.push_front
+          (curr_lexer->looking_for_object_index);
+
+        curr_lexer->looking_at_indirect_ref = false;
+        curr_lexer->looking_for_object_index = false;
+        curr_lexer->at_beginning_of_statement = false;
+
+        curr_lexer->nesting_level.paren ();
+        curr_lexer->decrement_promptflag ();
+
+        return curr_lexer->handle_token ('(');
+      }
   }
 
 ")" {
-    LEXER_DEBUG (")");
-
-    nesting_level.remove ();
-    current_input_column++;
-
-    lexer_flags.looking_at_object_index.pop_front ();
-
-    lexer_flags.quote_is_transpose = true;
-    lexer_flags.convert_spaces_to_comma
-      = (nesting_level.is_bracket_or_brace ()
-         && ! lexer_flags.looking_at_anon_fcn_args);
-    lexer_flags.looking_for_object_index = true;
-    lexer_flags.at_beginning_of_statement = false;
-
-    if (lexer_flags.looking_at_anon_fcn_args)
-      lexer_flags.looking_at_anon_fcn_args = false;
-
-    do_comma_insert_check ();
-
-    COUNT_TOK_AND_RETURN (')');
+    curr_lexer->lexer_debug (")");
+
+    curr_lexer->nesting_level.remove ();
+    curr_lexer->current_input_column++;
+
+    curr_lexer->looking_at_object_index.pop_front ();
+
+    curr_lexer->looking_for_object_index = true;
+    curr_lexer->at_beginning_of_statement = false;
+
+    if (curr_lexer->looking_at_anon_fcn_args)
+      {
+        curr_lexer->looking_at_anon_fcn_args = false;
+        curr_lexer->nesting_level.anon_fcn_body ();
+      }
+
+    return curr_lexer->count_token (')');
   }
 
 "." {
-    LEXER_DEBUG (".");
-
-    lexer_flags.looking_for_object_index = false;
-    lexer_flags.at_beginning_of_statement = false;
-
-    TOK_RETURN ('.');
+    curr_lexer->lexer_debug (".");
+
+    if (curr_lexer->previous_token_may_be_command ()
+        && curr_lexer->space_follows_previous_token ())
+      {
+        yyless (0);
+        curr_lexer->push_start_state (COMMAND_START);
+      }
+    else
+      {
+        curr_lexer->looking_for_object_index = false;
+        curr_lexer->at_beginning_of_statement = false;
+
+        return curr_lexer->handle_token ('.');
+      }
+  }
+
+%{
+// = and op= operators.
+%}
+
+"=" {
+    curr_lexer->maybe_mark_previous_token_as_variable ();
+
+    return curr_lexer->handle_op ("=", '=');
   }
 
-"+="    { LEXER_DEBUG ("+="); XBIN_OP_RETURN (ADD_EQ, false, false); }
-"-="    { LEXER_DEBUG ("-="); XBIN_OP_RETURN (SUB_EQ, false, false); }
-"*="    { LEXER_DEBUG ("*="); XBIN_OP_RETURN (MUL_EQ, false, false); }
-"/="    { LEXER_DEBUG ("/="); XBIN_OP_RETURN (DIV_EQ, false, false); }
-"\\="   { LEXER_DEBUG ("\\="); XBIN_OP_RETURN (LEFTDIV_EQ, false, false); }
-".+="   { LEXER_DEBUG (".+="); XBIN_OP_RETURN (ADD_EQ, false, false); }
-".-="   { LEXER_DEBUG (".-="); XBIN_OP_RETURN (SUB_EQ, false, false); }
-".*="   { LEXER_DEBUG (".*="); XBIN_OP_RETURN (EMUL_EQ, false, false); }
-"./="   { LEXER_DEBUG ("./="); XBIN_OP_RETURN (EDIV_EQ, false, false); }
-".\\="  { LEXER_DEBUG (".\\="); XBIN_OP_RETURN (ELEFTDIV_EQ, false, false); }
-{POW}=  { LEXER_DEBUG ("{POW}="); XBIN_OP_RETURN (POW_EQ, false, false); }
-{EPOW}= { LEXER_DEBUG ("{EPOW}="); XBIN_OP_RETURN (EPOW_EQ, false, false); }
-"&="    { LEXER_DEBUG ("&="); XBIN_OP_RETURN (AND_EQ, false, false); }
-"|="    { LEXER_DEBUG ("|="); XBIN_OP_RETURN (OR_EQ, false, false); }
-"<<="   { LEXER_DEBUG ("<<="); XBIN_OP_RETURN (LSHIFT_EQ, false, false); }
-">>="   { LEXER_DEBUG (">>="); XBIN_OP_RETURN (RSHIFT_EQ, false, false); }
-
-\{{S}* {
-    LEXER_DEBUG ("\\{{S}*");
-
-    nesting_level.brace ();
-
-    lexer_flags.looking_at_object_index.push_front
-      (lexer_flags.looking_for_object_index);
-
-    current_input_column += yyleng;
-    lexer_flags.quote_is_transpose = false;
-    lexer_flags.convert_spaces_to_comma = true;
-    lexer_flags.looking_for_object_index = false;
-    lexer_flags.at_beginning_of_statement = false;
-
-    promptflag--;
-    eat_whitespace ();
-
-    lexer_flags.braceflag++;
-    BEGIN (MATRIX_START);
-    COUNT_TOK_AND_RETURN ('{');
+"+="   { return curr_lexer->handle_incompatible_op ("+=", ADD_EQ); }
+"-="   { return curr_lexer->handle_incompatible_op ("-=", SUB_EQ); }
+"*="   { return curr_lexer->handle_incompatible_op ("*=", MUL_EQ); }
+"/="   { return curr_lexer->handle_incompatible_op ("/=", DIV_EQ); }
+"\\="  { return curr_lexer->handle_incompatible_op ("\\=", LEFTDIV_EQ); }
+".+="  { return curr_lexer->handle_incompatible_op (".+=", ADD_EQ); }
+".-="  { return curr_lexer->handle_incompatible_op (".-=", SUB_EQ); }
+".*="  { return curr_lexer->handle_incompatible_op (".*=", EMUL_EQ); }
+"./="  { return curr_lexer->handle_incompatible_op ("./=", EDIV_EQ); }
+".\\=" { return curr_lexer->handle_incompatible_op (".\\=", ELEFTDIV_EQ); }
+"^="   { return curr_lexer->handle_incompatible_op ("^=", POW_EQ); }
+"**="  { return curr_lexer->handle_incompatible_op ("^=", POW_EQ); }
+".^="  { return curr_lexer->handle_incompatible_op (".^=", EPOW_EQ); }
+".**=" { return curr_lexer->handle_incompatible_op (".^=", EPOW_EQ); }
+"&="   { return curr_lexer->handle_incompatible_op ("&=", AND_EQ); }
+"|="   { return curr_lexer->handle_incompatible_op ("|=", OR_EQ); }
+"<<="  { return curr_lexer->handle_incompatible_op ("<<=", LSHIFT_EQ); }
+">>="  { return curr_lexer->handle_incompatible_op (">>=", RSHIFT_EQ); }
+
+%{
+// In Matlab, '{' may also trigger command syntax.
+%}
+
+"{" {
+    curr_lexer->lexer_debug ("{");
+
+    bool unput_comma = false;
+
+    if (curr_lexer->whitespace_is_significant ()
+        && curr_lexer->space_follows_previous_token ())
+      {
+        int tok = curr_lexer->previous_token_value ();
+
+        if (! (tok == '[' || tok == '{'
+               || curr_lexer->previous_token_is_binop ()))
+          unput_comma = true;
+      }
+
+    if (unput_comma)
+      {
+        yyless (0);
+        curr_lexer->xunput (',');
+        // Adjust for comma that was not really in the input stream.
+        curr_lexer->current_input_column--;
+      }
+    else
+      {
+        curr_lexer->nesting_level.brace ();
+
+        curr_lexer->looking_at_object_index.push_front
+          (curr_lexer->looking_for_object_index);
+
+        curr_lexer->current_input_column += yyleng;
+        curr_lexer->looking_for_object_index = false;
+        curr_lexer->at_beginning_of_statement = false;
+
+        curr_lexer->decrement_promptflag ();
+
+        curr_lexer->braceflag++;
+
+        curr_lexer->push_start_state (MATRIX_START);
+
+        return curr_lexer->count_token ('{');
+      }
   }
 
 "}" {
-    LEXER_DEBUG ("}");
-
-    lexer_flags.looking_at_object_index.pop_front ();
-
-    lexer_flags.looking_for_object_index = true;
-    lexer_flags.at_beginning_of_statement = false;
-
-    nesting_level.remove ();
-
-    TOK_RETURN ('}');
+    curr_lexer->lexer_debug ("}");
+
+    curr_lexer->looking_at_object_index.pop_front ();
+
+    curr_lexer->looking_for_object_index = true;
+    curr_lexer->at_beginning_of_statement = false;
+
+    curr_lexer->nesting_level.remove ();
+
+    return curr_lexer->handle_token ('}');
   }
 
 %{
@@ -1058,108 +1203,30 @@
 %}
 
 . {
-    LEXER_DEBUG (".");
-
-    xunput (yytext[0], yytext);
-
-    int c = text_yyinput ();
-
-    if (c != EOF)
+    curr_lexer->lexer_debug (".");
+
+    curr_lexer->xunput (yytext[0]);
+
+    int c = curr_lexer->text_yyinput ();
+
+    if (c == 1)
+      return -1;
+    else if (c == EOF)
+      return curr_lexer->handle_end_of_input ();
+    else
       {
-        current_input_column++;
+        curr_lexer->current_input_column++;
 
         error ("invalid character '%s' (ASCII %d) near line %d, column %d",
                undo_string_escape (static_cast<char> (c)), c,
-               input_line_number, current_input_column);
+               curr_lexer->input_line_number, curr_lexer->current_input_column);
 
         return LEXICAL_ERROR;
       }
-    else
-      TOK_RETURN (END_OF_INPUT);
   }
 
 %%
 
-// GAG.
-//
-// If we're reading a matrix and the next character is '[', make sure
-// that we insert a comma ahead of it.
-
-void
-do_comma_insert_check (void)
-{
-  int spc_gobbled = eat_continuation ();
-
-  int c = text_yyinput ();
-
-  xunput (c, yytext);
-
-  if (spc_gobbled)
-    xunput (' ', yytext);
-
-  lexer_flags.do_comma_insert = (! lexer_flags.looking_at_object_index.front ()
-                                 && lexer_flags.bracketflag && c == '[');
-}
-
-// Fix things up for errors or interrupts.  The parser is never called
-// recursively, so it is always safe to reinitialize its state before
-// doing any parsing.
-
-void
-reset_parser (void)
-{
-  // Start off on the right foot.
-  BEGIN (INITIAL);
-
-  parser_end_of_input = false;
-
-  while (! symtab_context.empty ())
-    symtab_context.pop ();
-
-  // We do want a prompt by default.
-  promptflag = 1;
-
-  // We are not in a block comment.
-  block_comment_nesting_level = 0;
-
-  // Error may have occurred inside some brackets, braces, or parentheses.
-  nesting_level.clear ();
-
-  // Clear out the stack of token info used to track line and column
-  // numbers.
-  while (! token_stack.empty ())
-    {
-      delete token_stack.top ();
-      token_stack.pop ();
-    }
-
-  // Can be reset by defining a function.
-  if (! (reading_script_file || reading_fcn_file || reading_classdef_file))
-    {
-      current_input_column = 1;
-      input_line_number = command_editor::current_command_number ();
-    }
-
-  // Only ask for input from stdin if we are expecting interactive
-  // input.
-
-  if (! quitting_gracefully
-      && (interactive || forced_interactive)
-      && ! (reading_fcn_file
-            || reading_classdef_file
-            || reading_script_file
-            || get_input_from_eval_string
-            || input_from_startup_file))
-    yyrestart (stdin);
-
-  // Clear the buffer for help text.
-  while (! help_buf.empty ())
-    help_buf.pop ();
-
-  // Reset other flags.
-  lexer_flags.init ();
-}
-
 static void
 display_character (char c)
 {
@@ -1306,888 +1373,75 @@
       }
 }
 
-static int
-text_yyinput (void)
+bool
+is_keyword (const std::string& s)
 {
-  int c = yyinput ();
-
-  if (lexer_debug_flag)
-    {
-      std::cerr << "I: ";
-      display_character (c);
-      std::cerr << std::endl;
-    }
-
-  // Convert CRLF into just LF and single CR into LF.
-
-  if (c == '\r')
-    {
-      c = yyinput ();
-
-      if (lexer_debug_flag)
-        {
-          std::cerr << "I: ";
-          display_character (c);
-          std::cerr << std::endl;
-        }
-
-      if (c != '\n')
-        {
-          xunput (c, yytext);
-          c = '\n';
-        }
-    }
-
-  if (c == '\n')
-    input_line_number++;
-
-  return c;
-}
-
-static void
-xunput (char c, char *buf)
-{
-  if (lexer_debug_flag)
-    {
-      std::cerr << "U: ";
-      display_character (c);
-      std::cerr << std::endl;
-    }
-
-  if (c == '\n')
-    input_line_number--;
-
-  yyunput (c, buf);
-}
-
-// If we read some newlines, we need figure out what column we're
-// really looking at.
-
-static void
-fixup_column_count (char *s)
-{
-  char c;
-  while ((c = *s++) != '\0')
-    {
-      if (c == '\n')
-        {
-          input_line_number++;
-          current_input_column = 1;
-        }
-      else
-        current_input_column++;
-    }
-}
-
-// Include these so that we don't have to link to libfl.a.
-
-int
-yywrap (void)
-{
-  return 1;
+  // Parsing function names like "set.property_name" inside
+  // classdef-style class definitions is simplified by handling the
+  // "set" and "get" portions of the names using the same mechanism as
+  // is used for keywords.  However, they are not really keywords in
+  // the language, so omit them from the list of possible keywords.
+
+  return (octave_kw_hash::in_word_set (s.c_str (), s.length ()) != 0
+          && ! (s == "set" || s == "get"));
 }
 
-// Tell us all what the current buffer is.
-
-YY_BUFFER_STATE
-current_buffer (void)
-{
-  return YY_CURRENT_BUFFER;
-}
-
-// Create a new buffer.
-
-YY_BUFFER_STATE
-create_buffer (FILE *f)
-{
-  return yy_create_buffer (f, YY_BUF_SIZE);
-}
-
-// Start reading a new buffer.
-
-void
-switch_to_buffer (YY_BUFFER_STATE buf)
-{
-  yy_switch_to_buffer (buf);
-}
-
-// Delete a buffer.
-
-void
-delete_buffer (YY_BUFFER_STATE buf)
+DEFUN (iskeyword, args, ,
+  "-*- texinfo -*-\n\
+@deftypefn  {Built-in Function} {} iskeyword ()\n\
+@deftypefnx {Built-in Function} {} iskeyword (@var{name})\n\
+Return true if @var{name} is an Octave keyword.  If @var{name}\n\
+is omitted, return a list of keywords.\n\
+@seealso{isvarname, exist}\n\
+@end deftypefn")
 {
-  yy_delete_buffer (buf);
-}
-
-// Delete all buffers from the stack.
-void
-clear_all_buffers (void)
-{                 
-  while (current_buffer ())
-    octave_pop_buffer_state ();
-}
-
-void
-cleanup_parser (void)
-{
-  reset_parser ();
-
-  clear_all_buffers ();
-}
-
-// Restore a buffer (for unwind-prot).
-
-void
-restore_input_buffer (void *buf)
-{
-  switch_to_buffer (static_cast<YY_BUFFER_STATE> (buf));
-}
-
-// Delete a buffer (for unwind-prot).
-
-void
-delete_input_buffer (void *buf)
-{
-  delete_buffer (static_cast<YY_BUFFER_STATE> (buf));
-}
-
-static bool
-inside_any_object_index (void)
-{
-  bool retval = false;
-
-  for (std::list<bool>::const_iterator i = lexer_flags.looking_at_object_index.begin ();
-       i != lexer_flags.looking_at_object_index.end (); i++)
+  octave_value retval;
+
+  int argc = args.length () + 1;
+
+  string_vector argv = args.make_argv ("iskeyword");
+
+  if (error_state)
+    return retval;
+
+  if (argc == 1)
     {
-      if (*i)
+      // Neither set and get are keywords.  See the note in the
+      // is_keyword function for additional details.
+
+      string_vector lst (TOTAL_KEYWORDS);
+
+      int j = 0;
+
+      for (int i = 0; i < TOTAL_KEYWORDS; i++)
         {
-          retval = true;
-          break;
+          std::string tmp = wordlist[i].name;
+
+          if (! (tmp == "set" || tmp == "get"))
+            lst[j++] = tmp;
         }
+
+      lst.resize (j);
+
+      retval = Cell (lst.sort ());
     }
+  else if (argc == 2)
+    {
+      retval = is_keyword (argv[1]);
+    }
+  else
+    print_usage ();
 
   return retval;
 }
 
-// Handle keywords.  Return -1 if the keyword should be ignored.
-
-static int
-is_keyword_token (const std::string& s)
-{
-  int l = input_line_number;
-  int c = current_input_column;
-
-  int len = s.length ();
-
-  const octave_kw *kw = octave_kw_hash::in_word_set (s.c_str (), len);
-
-  if (kw)
-    {
-      yylval.tok_val = 0;
-
-      switch (kw->kw_id)
-        {
-        case break_kw:
-        case catch_kw:
-        case continue_kw:
-        case else_kw:
-        case otherwise_kw:
-        case return_kw:
-        case unwind_protect_cleanup_kw:
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-        case case_kw:
-        case elseif_kw:
-        case global_kw:
-        case static_kw:
-        case until_kw:
-          break;
-
-        case end_kw:
-          if (! reading_classdef_file
-              && (inside_any_object_index ()
-                  || (lexer_flags.defining_func
-                      && ! (lexer_flags.looking_at_return_list
-                            || lexer_flags.parsed_function_name.top ()))))
-            return 0;
-
-          yylval.tok_val = new token (token::simple_end, l, c);
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-        case end_try_catch_kw:
-          yylval.tok_val = new token (token::try_catch_end, l, c);
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-        case end_unwind_protect_kw:
-          yylval.tok_val = new token (token::unwind_protect_end, l, c);
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-        case endfor_kw:
-          yylval.tok_val = new token (token::for_end, l, c);
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-        case endfunction_kw:
-          yylval.tok_val = new token (token::function_end, l, c);
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-        case endif_kw:
-          yylval.tok_val = new token (token::if_end, l, c);
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-        case endparfor_kw:
-          yylval.tok_val = new token (token::parfor_end, l, c);
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-        case endswitch_kw:
-          yylval.tok_val = new token (token::switch_end, l, c);
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-        case endwhile_kw:
-          yylval.tok_val = new token (token::while_end, l, c);
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-        case endclassdef_kw:
-          yylval.tok_val = new token (token::classdef_end, l, c);
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-        case endenumeration_kw:
-          yylval.tok_val = new token (token::enumeration_end, l, c);
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-        case endevents_kw:
-          yylval.tok_val = new token (token::events_end, l, c);
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-        case endmethods_kw:
-          yylval.tok_val = new token (token::methods_end, l, c);
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-        case endproperties_kw:
-          yylval.tok_val = new token (token::properties_end, l, c);
-          lexer_flags.at_beginning_of_statement = true;
-          break;
-
-
-        case for_kw:
-        case parfor_kw:
-        case while_kw:
-          promptflag--;
-          lexer_flags.looping++;
-          break;
-
-        case do_kw:
-          lexer_flags.at_beginning_of_statement = true;
-          promptflag--;
-          lexer_flags.looping++;
-          break;
-
-        case try_kw:
-        case unwind_protect_kw:
-          lexer_flags.at_beginning_of_statement = true;
-          promptflag--;
-          break;
-
-        case if_kw:
-        case switch_kw:
-          promptflag--;
-          break;
-
-        case get_kw:
-        case set_kw:
-          // 'get' and 'set' are keywords in classdef method
-          // declarations.
-          if (! lexer_flags.maybe_classdef_get_set_method)
-            return 0;
-          break;
-
-        case enumeration_kw:
-        case events_kw:
-        case methods_kw:
-        case properties_kw:
-          // 'properties', 'methods' and 'events' are keywords for
-          // classdef blocks.
-          if (! lexer_flags.parsing_classdef)
-            return 0;
-          // fall through ...
-
-        case classdef_kw:
-          // 'classdef' is always a keyword.
-          promptflag--;
-          break;
-
-        case function_kw:
-          promptflag--;
-
-          lexer_flags.defining_func++;
-          lexer_flags.parsed_function_name.push (false);
-
-          if (! (reading_fcn_file || reading_script_file
-                 || reading_classdef_file))
-            input_line_number = 1;
-          break;
-
-        case magic_file_kw:
-          {
-            if ((reading_fcn_file || reading_script_file
-                 || reading_classdef_file)
-                && ! curr_fcn_file_full_name.empty ())
-              yylval.tok_val = new token (curr_fcn_file_full_name, l, c);
-            else
-              yylval.tok_val = new token ("stdin", l, c);
-          }
-          break;
-
-        case magic_line_kw:
-          yylval.tok_val = new token (static_cast<double> (l), "", l, c);
-          break;
-
-        default:
-          panic_impossible ();
-        }
-
-      if (! yylval.tok_val)
-        yylval.tok_val = new token (l, c);
-
-      token_stack.push (yylval.tok_val);
-
-      return kw->tok;
-    }
-
-  return 0;
-}
-
-static bool
-is_variable (const std::string& name)
-{
-  return (symbol_table::is_variable (name)
-          || (lexer_flags.pending_local_variables.find (name)
-              != lexer_flags.pending_local_variables.end ()));
-}
-
-static std::string
-grab_block_comment (stream_reader& reader, bool& eof)
-{
-  std::string buf;
-
-  bool at_bol = true;
-  bool look_for_marker = false;
-
-  bool warned_incompatible = false;
-
-  int c = 0;
-
-  while ((c = reader.getc ()) != EOF)
-    {
-      current_input_column++;
-
-      if (look_for_marker)
-        {
-          at_bol = false;
-          look_for_marker = false;
-
-          if (c == '{' || c == '}')
-            {
-              std::string tmp_buf (1, static_cast<char> (c));
-
-              int type = c;
-
-              bool done = false;
-
-              while ((c = reader.getc ()) != EOF && ! done)
-                {
-                  current_input_column++;
-
-                  switch (c)
-                    {
-                    case ' ':
-                    case '\t':
-                      tmp_buf += static_cast<char> (c);
-                      break;
-
-                    case '\n':
-                      {
-                        current_input_column = 0;
-                        at_bol = true;
-                        done = true;
-
-                        if (type == '{')
-                          {
-                            block_comment_nesting_level++;
-                            promptflag--;
-                          }
-                        else
-                          {
-                            block_comment_nesting_level--;
-                            promptflag++;
-
-                            if (block_comment_nesting_level == 0)
-                              {
-                                buf += grab_comment_block (reader, true, eof);
-
-                                return buf;
-                              }
-                          }
-                      }
-                      break;
-
-                    default:
-                      at_bol = false;
-                      tmp_buf += static_cast<char> (c);
-                      buf += tmp_buf;
-                      done = true;
-                      break;
-                    }
-                }
-            }
-        }
-
-      if (at_bol && (c == '%' || c == '#'))
-        {
-          if (c == '#' && ! warned_incompatible)
-            {
-              warned_incompatible = true;
-              maybe_gripe_matlab_incompatible_comment (c);
-            }
-
-          at_bol = false;
-          look_for_marker = true;
-        }
-      else
-        {
-          buf += static_cast<char> (c);
-
-          if (c == '\n')
-            {
-              current_input_column = 0;
-              at_bol = true;
-            }
-        }
-    }
-
-  if (c == EOF)
-    eof = true;
-
-  return buf;
-}
-
-std::string
-grab_comment_block (stream_reader& reader, bool at_bol,
-                    bool& eof)
-{
-  std::string buf;
-
-  // TRUE means we are at the beginning of a comment block.
-  bool begin_comment = false;
-
-  // TRUE means we are currently reading a comment block.
-  bool in_comment = false;
-
-  bool warned_incompatible = false;
-
-  int c = 0;
-
-  while ((c = reader.getc ()) != EOF)
-    {
-      current_input_column++;
-
-      if (begin_comment)
-        {
-          if (c == '%' || c == '#')
-            {
-              at_bol = false;
-              continue;
-            }
-          else if (at_bol && c == '{')
-            {
-              std::string tmp_buf (1, static_cast<char> (c));
-
-              bool done = false;
-
-              while ((c = reader.getc ()) != EOF && ! done)
-                {
-                  current_input_column++;
-
-                  switch (c)
-                    {
-                    case ' ':
-                    case '\t':
-                      tmp_buf += static_cast<char> (c);
-                      break;
-
-                    case '\n':
-                      {
-                        current_input_column = 0;
-                        at_bol = true;
-                        done = true;
-
-                        block_comment_nesting_level++;
-                        promptflag--;
-
-                        buf += grab_block_comment (reader, eof);
-
-                        in_comment = false;
-
-                        if (eof)
-                          goto done;
-                      }
-                      break;
-
-                    default:
-                      at_bol = false;
-                      tmp_buf += static_cast<char> (c);
-                      buf += tmp_buf;
-                      done = true;
-                      break;
-                    }
-                }
-            }
-          else
-            {
-              at_bol = false;
-              begin_comment = false;
-            }
-        }
-
-      if (in_comment)
-        {
-          buf += static_cast<char> (c);
-
-          if (c == '\n')
-            {
-              at_bol = true;
-              current_input_column = 0;
-              in_comment = false;
-
-              // FIXME -- bailing out here prevents things like
-              //
-              //    octave> # comment
-              //    octave> x = 1
-              //
-              // from failing at the command line, while still
-              // allowing blocks of comments to be grabbed properly
-              // for function doc strings.  But only the first line of
-              // a mult-line doc string will be picked up for
-              // functions defined on the command line.  We need a
-              // better way of collecting these comments...
-              if (! (reading_fcn_file || reading_script_file))
-                goto done;
-            }
-        }
-      else
-        {
-          switch (c)
-            {
-            case ' ':
-            case '\t':
-              break;
-
-            case '#':
-              if (! warned_incompatible)
-                {
-                  warned_incompatible = true;
-                  maybe_gripe_matlab_incompatible_comment (c);
-                }
-              // fall through...
-
-            case '%':
-              in_comment = true;
-              begin_comment = true;
-              break;
-
-            default:
-              current_input_column--;
-              reader.ungetc (c);
-              goto done;
-            }
-        }
-    }
-
- done:
-
-  if (c == EOF)
-    eof = true;
-
-  return buf;
-}
-
-class
-flex_stream_reader : public stream_reader
-{
-public:
-  flex_stream_reader (char *buf_arg) : stream_reader (), buf (buf_arg) { }
-
-  int getc (void) { return ::text_yyinput (); }
-  int ungetc (int c) { ::xunput (c, buf); return 0; }
-
-private:
-
-  // No copying!
-
-  flex_stream_reader (const flex_stream_reader&);
-
-  flex_stream_reader& operator = (const flex_stream_reader&);
-
-  char *buf;
-};
-
-static int
-process_comment (bool start_in_block, bool& eof)
-{
-  eof = false;
-
-  std::string help_txt;
-
-  if (! help_buf.empty ())
-    help_txt = help_buf.top ();
-
-  flex_stream_reader flex_reader (yytext);
-
-  // process_comment is only supposed to be called when we are not
-  // initially looking at a block comment.
-
-  std::string txt = start_in_block
-    ? grab_block_comment (flex_reader, eof)
-    : grab_comment_block (flex_reader, false, eof);
-
-  if (lexer_debug_flag)
-    std::cerr << "C: " << txt << std::endl;
-
-  if (help_txt.empty () && nesting_level.none ())
-    {
-      if (! help_buf.empty ())
-        help_buf.pop ();
-
-      help_buf.push (txt);
-    }
-
-  octave_comment_buffer::append (txt);
-
-  current_input_column = 1;
-  lexer_flags.quote_is_transpose = false;
-  lexer_flags.convert_spaces_to_comma = true;
-  lexer_flags.at_beginning_of_statement = true;
-
-  if (YY_START == COMMAND_START)
-    BEGIN (INITIAL);
-
-  if (nesting_level.none ())
-    return '\n';
-  else if (nesting_level.is_bracket_or_brace ())
-    return ';';
-  else
-    return 0;
-}
-
-// Return 1 if the given character matches any character in the given
-// string.
-
-static bool
-match_any (char c, const char *s)
-{
-  char tmp;
-  while ((tmp = *s++) != '\0')
-    {
-      if (c == tmp)
-        return true;
-    }
-  return false;
-}
-
-// Given information about the spacing surrounding an operator,
-// return 1 if it looks like it should be treated as a binary
-// operator.  For example,
-//
-//   [ 1 + 2 ]  or  [ 1+ 2]  or  [ 1+2 ]  ==>  binary
-//
-//   [ 1 +2 ]  ==>  unary
-
-static bool
-looks_like_bin_op (bool spc_prev, int next_char)
-{
-  bool spc_next = (next_char == ' ' || next_char == '\t');
-
-  return ((spc_prev && spc_next) || ! spc_prev);
-}
-
-// Recognize separators.  If the separator is a CRLF pair, it is
-// replaced by a single LF.
-
-static bool
-next_token_is_sep_op (void)
-{
-  bool retval = false;
-
-  int c = text_yyinput ();
-
-  retval = match_any (c, ",;\n]");
-
-  xunput (c, yytext);
-
-  return retval;
-}
-
-// Try to determine if the next token should be treated as a postfix
-// unary operator.  This is ugly, but it seems to do the right thing.
-
-static bool
-next_token_is_postfix_unary_op (bool spc_prev)
-{
-  bool un_op = false;
-
-  int c0 = text_yyinput ();
-
-  if (c0 == '\'' && ! spc_prev)
-    {
-      un_op = true;
-    }
-  else if (c0 == '.')
-    {
-      int c1 = text_yyinput ();
-      un_op = (c1 == '\'');
-      xunput (c1, yytext);
-    }
-  else if (c0 == '+')
-    {
-      int c1 = text_yyinput ();
-      un_op = (c1 == '+');
-      xunput (c1, yytext);
-    }
-  else if (c0 == '-')
-    {
-      int c1 = text_yyinput ();
-      un_op = (c1 == '-');
-      xunput (c1, yytext);
-    }
-
-  xunput (c0, yytext);
-
-  return un_op;
-}
-
-// Try to determine if the next token should be treated as a binary
-// operator.
-//
-// This kluge exists because whitespace is not always ignored inside
-// the square brackets that are used to create matrix objects (though
-// spacing only really matters in the cases that can be interpreted
-// either as binary ops or prefix unary ops: currently just +, -).
-//
-// Note that a line continuation directly following a + or - operator
-// (e.g., the characters '[' 'a' ' ' '+' '\' LFD 'b' ']') will be
-// parsed as a binary operator.
-
-static bool
-next_token_is_bin_op (bool spc_prev)
-{
-  bool bin_op = false;
-
-  int c0 = text_yyinput ();
-
-  switch (c0)
-    {
-    case '+':
-    case '-':
-      {
-        int c1 = text_yyinput ();
-
-        switch (c1)
-          {
-          case '+':
-          case '-':
-            // Unary ops, spacing doesn't matter.
-            break;
-
-          case '=':
-            // Binary ops, spacing doesn't matter.
-            bin_op = true;
-            break;
-
-          default:
-            // Could be either, spacing matters.
-            bin_op = looks_like_bin_op (spc_prev, c1);
-            break;
-          }
-
-        xunput (c1, yytext);
-      }
-      break;
-
-    case ':':
-    case '/':
-    case '\\':
-    case '^':
-      // Always a binary op (may also include /=, \=, and ^=).
-      bin_op = true;
-      break;
-
-    // .+ .- ./ .\ .^ .* .**
-    case '.':
-      {
-        int c1 = text_yyinput ();
-
-        if (match_any (c1, "+-/\\^*"))
-          // Always a binary op (may also include .+=, .-=, ./=, ...).
-          bin_op = true;
-        else if (! isdigit (c1) && c1 != ' ' && c1 != '\t' && c1 != '.')
-          // A structure element reference is a binary op.
-          bin_op = true;
-
-        xunput (c1, yytext);
-      }
-      break;
-
-    // = == & && | || * **
-    case '=':
-    case '&':
-    case '|':
-    case '*':
-      // Always a binary op (may also include ==, &&, ||, **).
-      bin_op = true;
-      break;
-
-    // < <= <> > >=
-    case '<':
-    case '>':
-      // Always a binary op (may also include <=, <>, >=).
-      bin_op = true;
-      break;
-
-    // ~= !=
-    case '~':
-    case '!':
-      {
-        int c1 = text_yyinput ();
-
-        // ~ and ! can be unary ops, so require following =.
-        if (c1 == '=')
-          bin_op = true;
-
-        xunput (c1, yytext);
-      }
-      break;
-
-    default:
-      break;
-    }
-
-  xunput (c0, yytext);
-
-  return bin_op;
-}
+/*
+
+%!assert (iskeyword ("for"))
+%!assert (iskeyword ("fort"), false)
+%!assert (iskeyword ("fft"), false)
+
+*/
 
 // Used to delete trailing white space from tokens.
 
@@ -2204,180 +1458,659 @@
   return retval;
 }
 
-// FIXME -- we need to handle block comments here.
-
-static void
-scan_for_comments (const char *text)
+DEFUN (__display_tokens__, args, nargout,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {} __display_tokens__ ()\n\
+Query or set the internal variable that determines whether Octave's\n\
+lexer displays tokens as they are read.\n\
+@end deftypefn")
+{
+  return SET_INTERNAL_VARIABLE (display_tokens);
+}
+
+DEFUN (__token_count__, , ,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {} __token_count__ ()\n\
+Number of language tokens processed since Octave startup.\n\
+@end deftypefn")
+{
+  return octave_value (Vtoken_count);
+}
+
+DEFUN (__lexer_debug_flag__, args, nargout,
+  "-*- texinfo -*-\n\
+@deftypefn {Built-in Function} {@var{old_val} =} __lexer_debug_flag__ (@var{new_val}))\n\
+Undocumented internal function.\n\
+@end deftypefn")
+{
+  octave_value retval;
+
+  retval = set_internal_variable (lexer_debug_flag, args, nargout,
+                                  "__lexer_debug_flag__");
+
+  return retval;
+}
+
+lexical_feedback::~lexical_feedback (void)
+{
+  tokens.clear ();
+}
+
+void
+lexical_feedback::init (void)
+{
+  // The closest paren, brace, or bracket nesting is not an object
+  // index.
+  looking_at_object_index.push_front (false);
+}
+
+void
+lexical_feedback::reset (void)
+{
+  end_of_input = false;
+  at_beginning_of_statement = true;
+  looking_at_anon_fcn_args = false;
+  looking_at_return_list = false;
+  looking_at_parameter_list = false;
+  looking_at_decl_list = false;
+  looking_at_initializer_expression = false;
+  looking_at_matrix_or_assign_lhs = false;
+  looking_for_object_index = false; 
+  looking_at_indirect_ref = false;
+  parsing_class_method = false;
+  maybe_classdef_get_set_method = false;
+  parsing_classdef = false;
+  force_script = false;
+  reading_fcn_file = false;
+  reading_script_file = false;
+  reading_classdef_file = false;
+  input_line_number = 1;
+  current_input_column = 1;
+  bracketflag = 0;
+  braceflag = 0;
+  looping = 0;
+  defining_func = 0;
+  looking_at_function_handle = 0;
+  block_comment_nesting_level = 0;
+  token_count = 0;
+  current_input_line = "";
+  comment_text = "";
+  help_text = "";
+  fcn_file_name = "";
+  fcn_file_full_name = "";
+  looking_at_object_index.clear ();
+  looking_at_object_index.push_front (false);
+
+  while (! parsed_function_name.empty ())
+    parsed_function_name.pop ();
+
+  nesting_level.reset ();
+
+  tokens.clear ();
+}
+
+int
+lexical_feedback::previous_token_value (void) const
+{
+  const token *tok = tokens.front ();
+  return tok ? tok->token_value () : 0;
+}
+
+bool
+lexical_feedback::previous_token_value_is (int tok_val) const
 {
-  std::string comment_buf;
-
-  bool in_comment = false;
-  bool beginning_of_comment = false;
-
-  int len = strlen (text);
-  int i = 0;
-
-  while (i < len)
+  const token *tok = tokens.front ();
+  return tok ? tok->token_value_is (tok_val) : false;
+}
+
+void
+lexical_feedback::mark_previous_token_trailing_space (void)
+{
+  token *tok = tokens.front ();
+  if (tok && ! previous_token_value_is ('\n'))
+    tok->mark_trailing_space ();
+}
+
+bool
+lexical_feedback::space_follows_previous_token (void) const
+{
+  const token *tok = tokens.front ();
+  return tok ? tok->space_follows_token () : false;
+}
+
+bool
+lexical_feedback::previous_token_is_binop (void) const
+{
+  int tok = previous_token_value ();
+
+  return (tok == '+' || tok == '-' || tok == '@'
+          || tok == ',' || tok == ';' || tok == '*' || tok == '/'
+          || tok == ':' || tok == '=' || tok == ADD_EQ
+          || tok == AND_EQ || tok == DIV_EQ || tok == EDIV
+          || tok == EDIV_EQ || tok == ELEFTDIV || tok == ELEFTDIV_EQ
+          || tok == EMINUS || tok == EMUL || tok == EMUL_EQ
+          || tok == EPOW || tok == EPOW_EQ || tok == EXPR_AND
+          || tok == EXPR_AND_AND || tok == EXPR_EQ || tok == EXPR_GE
+          || tok == EXPR_GT || tok == EXPR_LE || tok == EXPR_LT
+          || tok == EXPR_NE || tok == EXPR_NOT || tok == EXPR_OR
+          || tok == EXPR_OR_OR || tok == LEFTDIV || tok == LEFTDIV_EQ
+          || tok == LSHIFT || tok == LSHIFT_EQ || tok == MUL_EQ
+          || tok == OR_EQ || tok == POW || tok == POW_EQ
+          || tok == RSHIFT || tok == RSHIFT_EQ || tok == SUB_EQ);
+}
+
+bool
+lexical_feedback::previous_token_is_keyword (void) const
+{
+  const token *tok = tokens.front ();
+  return tok ? tok->is_keyword () : false;
+}
+
+bool
+lexical_feedback::previous_token_may_be_command (void) const
+{
+  const token *tok = tokens.front ();
+  return tok ? tok->may_be_command () : false;
+}
+
+void
+lexical_feedback::maybe_mark_previous_token_as_variable (void)
+{
+  token *tok = tokens.front ();
+  if (tok->is_symbol ())
+    pending_local_variables.insert (tok->symbol_name ());
+}
+
+void
+lexical_feedback::mark_as_variables (const std::list<std::string>& lst)
+{
+  for (std::list<std::string>::const_iterator p = lst.begin ();
+       p != lst.end (); p++)
     {
-      char c = text[i++];
-
-      switch (c)
+      pending_local_variables.insert (*p);
+    }
+}
+
+static bool
+looks_like_copyright (const std::string& s)
+{
+  bool retval = false;
+
+  if (! s.empty ())
+    {
+      size_t offset = s.find_first_not_of (" \t");
+
+      retval = (s.substr (offset, 9) == "Copyright" || s.substr (offset, 6) == "Author");
+    }
+
+  return retval;
+}
+
+void
+octave_base_lexer::input_buffer::fill (const std::string& input, bool eof_arg)
+{
+  buffer = input;
+  chars_left = buffer.length ();
+  pos = buffer.c_str ();
+  eof = eof_arg;
+}
+
+int
+octave_base_lexer::input_buffer::copy_chunk (char *buf, size_t max_size)
+{
+  static const char * const eol = "\n";
+
+  size_t len = max_size > chars_left ? chars_left : max_size;
+  assert (len > 0);
+
+  memcpy (buf, pos, len);
+
+  chars_left -= len;
+  pos += len;
+
+  // Make sure input ends with a new line character.
+  if (chars_left == 0 && buf[len-1] != '\n')
+    {
+      if (len < max_size)
         {
-        case '%':
-        case '#':
-          if (in_comment)
-            {
-              if (! beginning_of_comment)
-                comment_buf += static_cast<char> (c);
-            }
-          else
-            {
-              maybe_gripe_matlab_incompatible_comment (c);
-              in_comment = true;
-              beginning_of_comment = true;
-            }
-          break;
-
-        case '\n':
-          if (in_comment)
-            {
-              comment_buf += static_cast<char> (c);
-              octave_comment_buffer::append (comment_buf);
-              comment_buf.resize (0);
-              in_comment = false;
-              beginning_of_comment = false;
-            }
-          break;
-
-        default:
-          if (in_comment)
-            {
-              comment_buf += static_cast<char> (c);
-              beginning_of_comment = false;
-            }
+          // There is enough room to plug the newline character in
+          // the buffer.
+          buf[len++] = '\n';
+        }
+      else
+        {
+          // There isn't enough room to plug the newline character
+          // in the buffer so arrange to have it returned on the next
+          // call to octave_base_lexer::read.
+          pos = eol;
+          chars_left = 1;
+        }
+    }
+
+  return len;
+}
+
+octave_base_lexer::~octave_base_lexer (void)
+{
+  yylex_destroy (scanner);
+}
+
+void
+octave_base_lexer::init (void)
+{
+  yylex_init (&scanner);
+
+  // Make octave_base_lexer object available through yyextra in
+  // flex-generated lexer.
+  yyset_extra (this, scanner);
+
+  clear_start_state ();
+}
+
+// Inside Flex-generated functions, yyg is the scanner cast to its real
+// type.  Some flex macros that we use in octave_base_lexer member functions
+// (for example, BEGIN) use yyg.  If we could perform the actions of
+// these macros with functions instead, we could eliminate the
+// OCTAVE_YYG macro.
+
+#define OCTAVE_YYG \
+  struct yyguts_t *yyg = static_cast<struct yyguts_t*> (scanner)
+
+void
+octave_base_lexer::reset (void)
+{
+  // Start off on the right foot.
+  clear_start_state ();
+
+  symtab_context.clear ();
+
+  // We do want a prompt by default.
+  promptflag (1);
+
+  // Only ask for input from stdin if we are expecting interactive
+  // input.
+
+  if (! quitting_gracefully
+      && (interactive || forced_interactive)
+      && ! (reading_fcn_file
+            || reading_classdef_file
+            || reading_script_file
+            || input_from_eval_string ()))
+    yyrestart (stdin, scanner);
+
+  lexical_feedback::reset ();
+}
+
+void
+octave_base_lexer::prep_for_file (void)
+{
+  reading_script_file = true;
+
+  push_start_state (INPUT_FILE_START);
+}
+
+int
+octave_base_lexer::handle_end_of_input (void)
+{
+  lexer_debug ("<<EOF>>");
+
+  if (block_comment_nesting_level != 0)
+    {
+      warning ("block comment open at end of input");
+
+      if ((reading_fcn_file || reading_script_file || reading_classdef_file)
+          && ! fcn_file_name.empty ())
+        warning ("near line %d of file '%s.m'",
+                 input_line_number, fcn_file_name.c_str ());
+    }
+
+  return handle_token (END_OF_INPUT);
+}
+
+char *
+octave_base_lexer::flex_yytext (void)
+{
+  return yyget_text (scanner);
+}
+
+int
+octave_base_lexer::flex_yyleng (void)
+{
+  return yyget_leng (scanner);
+}
+
+int
+octave_base_lexer::text_yyinput (void)
+{
+  int c = yyinput (scanner);
+
+  if (lexer_debug_flag)
+    {
+      std::cerr << "I: ";
+      display_character (c);
+      std::cerr << std::endl;
+    }
+
+  // Convert CRLF into just LF and single CR into LF.
+
+  if (c == '\r')
+    {
+      c = yyinput (scanner);
+
+      if (lexer_debug_flag)
+        {
+          std::cerr << "I: ";
+          display_character (c);
+          std::cerr << std::endl;
+        }
+
+      if (c != '\n')
+        {
+          xunput (c);
+          c = '\n';
+        }
+    }
+
+  return c;
+}
+
+void
+octave_base_lexer::xunput (char c, char *buf)
+{
+  if (c != EOF)
+    {
+      if (lexer_debug_flag)
+        {
+          std::cerr << "U: ";
+          display_character (c);
+          std::cerr << std::endl;
+        }
+
+      yyunput (c, buf, scanner);
+    }
+}
+
+void
+octave_base_lexer::xunput (char c)
+{
+  char *yytxt = flex_yytext ();
+
+  xunput (c, yytxt);
+}
+
+bool
+octave_base_lexer::looking_at_space (void)
+{
+  int c = text_yyinput ();
+  xunput (c);
+  return (c == ' ' || c == '\t');
+}
+
+bool
+octave_base_lexer::inside_any_object_index (void)
+{
+  bool retval = false;
+
+  for (std::list<bool>::const_iterator i = looking_at_object_index.begin ();
+       i != looking_at_object_index.end (); i++)
+    {
+      if (*i)
+        {
+          retval = true;
           break;
         }
     }
 
-  if (! comment_buf.empty ())
-    octave_comment_buffer::append (comment_buf);
+  return retval;
+}
+
+bool
+octave_base_lexer::is_variable (const std::string& name)
+{
+  return (symbol_table::is_variable (name)
+          || (pending_local_variables.find (name)
+              != pending_local_variables.end ()));
 }
 
-// Discard whitespace, including comments and continuations.
-//
-// Return value is logical OR of the following values:
-//
-//  ATE_NOTHING      : no spaces to eat
-//  ATE_SPACE_OR_TAB : space or tab in input
-//  ATE_NEWLINE      : bare new line in input
-
-// FIXME -- we need to handle block comments here.
-
-static yum_yum
-eat_whitespace (void)
+// Handle keywords.  Return -1 if the keyword should be ignored.
+
+int
+octave_base_lexer::is_keyword_token (const std::string& s)
 {
-  yum_yum retval = ATE_NOTHING;
-
-  std::string comment_buf;
-
-  bool in_comment = false;
-  bool beginning_of_comment = false;
-
-  int c = 0;
-
-  while ((c = text_yyinput ()) != EOF)
+  int l = input_line_number;
+  int c = current_input_column;
+
+  int len = s.length ();
+
+  const octave_kw *kw = octave_kw_hash::in_word_set (s.c_str (), len);
+
+  if (kw)
     {
-      current_input_column++;
-
-      switch (c)
+      token *tok_val = 0;
+
+      switch (kw->kw_id)
         {
-        case ' ':
-        case '\t':
-          if (in_comment)
-            {
-              comment_buf += static_cast<char> (c);
-              beginning_of_comment = false;
-            }
-          retval |= ATE_SPACE_OR_TAB;
+        case break_kw:
+        case catch_kw:
+        case continue_kw:
+        case else_kw:
+        case otherwise_kw:
+        case return_kw:
+        case unwind_protect_cleanup_kw:
+          at_beginning_of_statement = true;
+          break;
+
+        case static_kw:
+          if ((reading_fcn_file || reading_script_file
+               || reading_classdef_file)
+              && ! fcn_file_full_name.empty ())
+            warning_with_id ("Octave:deprecated-keyword",
+                             "the 'static' keyword is obsolete and will be removed from a future version of Octave; please use 'persistent' instead; near line %d of file '%s'",
+                             input_line_number,
+                             fcn_file_full_name.c_str ());
+          else
+            warning_with_id ("Octave:deprecated-keyword",
+                             "the 'static' keyword is obsolete and will be removed from a future version of Octave; please use 'persistent' instead; near line %d",
+                             input_line_number);
+          // fall through ...
+
+        case persistent_kw:
+        case global_kw:
+          looking_at_decl_list = true;
+          break;
+
+        case case_kw:
+        case elseif_kw:
+        case until_kw:
+          break;
+
+        case end_kw:
+          if (inside_any_object_index ()
+              || (! reading_classdef_file
+                  && (defining_func
+                      && ! (looking_at_return_list
+                            || parsed_function_name.top ()))))
+            return 0;
+
+          tok_val = new token (end_kw, token::simple_end, l, c);
+          at_beginning_of_statement = true;
+          break;
+
+        case end_try_catch_kw:
+          tok_val = new token (end_try_catch_kw, token::try_catch_end, l, c);
+          at_beginning_of_statement = true;
+          break;
+
+        case end_unwind_protect_kw:
+          tok_val = new token (end_unwind_protect_kw,
+                               token::unwind_protect_end, l, c);
+          at_beginning_of_statement = true;
+          break;
+
+        case endfor_kw:
+          tok_val = new token (endfor_kw, token::for_end, l, c);
+          at_beginning_of_statement = true;
+          break;
+
+        case endfunction_kw:
+          tok_val = new token (endfunction_kw, token::function_end, l, c);
+          at_beginning_of_statement = true;
+          break;
+
+        case endif_kw:
+          tok_val = new token (endif_kw, token::if_end, l, c);
+          at_beginning_of_statement = true;
+          break;
+
+        case endparfor_kw:
+          tok_val = new token (endparfor_kw, token::parfor_end, l, c);
+          at_beginning_of_statement = true;
           break;
 
-        case '\n':
-          retval |= ATE_NEWLINE;
-          if (in_comment)
+        case endswitch_kw:
+          tok_val = new token (endswitch_kw, token::switch_end, l, c);
+          at_beginning_of_statement = true;
+          break;
+
+        case endwhile_kw:
+          tok_val = new token (endwhile_kw, token::while_end, l, c);
+          at_beginning_of_statement = true;
+          break;
+
+        case endclassdef_kw:
+          tok_val = new token (endclassdef_kw, token::classdef_end, l, c);
+          at_beginning_of_statement = true;
+          break;
+
+        case endenumeration_kw:
+          tok_val = new token (endenumeration_kw, token::enumeration_end, l, c);
+          at_beginning_of_statement = true;
+          break;
+
+        case endevents_kw:
+          tok_val = new token (endevents_kw, token::events_end, l, c);
+          at_beginning_of_statement = true;
+          break;
+
+        case endmethods_kw:
+          tok_val = new token (endmethods_kw, token::methods_end, l, c);
+          at_beginning_of_statement = true;
+          break;
+
+        case endproperties_kw:
+          tok_val = new token (endproperties_kw, token::properties_end, l, c);
+          at_beginning_of_statement = true;
+          break;
+
+
+        case for_kw:
+        case parfor_kw:
+        case while_kw:
+          decrement_promptflag ();
+          looping++;
+          break;
+
+        case do_kw:
+          at_beginning_of_statement = true;
+          decrement_promptflag ();
+          looping++;
+          break;
+
+        case try_kw:
+        case unwind_protect_kw:
+          at_beginning_of_statement = true;
+          decrement_promptflag ();
+          break;
+
+        case if_kw:
+        case switch_kw:
+          decrement_promptflag ();
+          break;
+
+        case get_kw:
+        case set_kw:
+          // 'get' and 'set' are keywords in classdef method
+          // declarations.
+          if (! maybe_classdef_get_set_method)
+            return 0;
+          break;
+
+        case enumeration_kw:
+        case events_kw:
+        case methods_kw:
+        case properties_kw:
+          // 'properties', 'methods' and 'events' are keywords for
+          // classdef blocks.
+          if (! parsing_classdef)
+            return 0;
+          // fall through ...
+
+        case classdef_kw:
+          // 'classdef' is always a keyword.
+          decrement_promptflag ();
+
+          if (! force_script && token_count == 0 && input_from_file ())
             {
-              comment_buf += static_cast<char> (c);
-              octave_comment_buffer::append (comment_buf);
-              comment_buf.resize (0);
-              in_comment = false;
-              beginning_of_comment = false;
-            }
-          current_input_column = 0;
-          break;
-
-        case '#':
-        case '%':
-          if (in_comment)
-            {
-              if (! beginning_of_comment)
-                comment_buf += static_cast<char> (c);
-            }
-          else
-            {
-              maybe_gripe_matlab_incompatible_comment (c);
-              in_comment = true;
-              beginning_of_comment = true;
+              reading_classdef_file = true;
+              reading_script_file = false;
             }
           break;
 
-        case '.':
-          if (in_comment)
+        case function_kw:
+          decrement_promptflag ();
+
+          defining_func++;
+          parsed_function_name.push (false);
+
+          if (! force_script && token_count == 0 && input_from_file ())
             {
-              comment_buf += static_cast<char> (c);
-              beginning_of_comment = false;
-              break;
-            }
-          else
-            {
-              if (have_ellipsis_continuation ())
-                break;
-              else
-                goto done;
+              reading_fcn_file = true;
+              reading_script_file = false;
             }
 
-        case '\\':
-          if (in_comment)
-            {
-              comment_buf += static_cast<char> (c);
-              beginning_of_comment = false;
-              break;
-            }
-          else
-            {
-              if (have_continuation ())
-                break;
-              else
-                goto done;
-            }
+          if (! (reading_fcn_file || reading_script_file
+                 || reading_classdef_file))
+            input_line_number = 1;
+          break;
+
+        case magic_file_kw:
+          {
+            if ((reading_fcn_file || reading_script_file
+                 || reading_classdef_file)
+                && ! fcn_file_full_name.empty ())
+              tok_val = new token (magic_file_kw, true,
+                                   fcn_file_full_name, l, c);
+            else
+              tok_val = new token (magic_file_kw, "stdin", l, c);
+          }
+          break;
+
+        case magic_line_kw:
+          tok_val = new token (magic_line_kw, static_cast<double> (l),
+                               "", l, c);
+          break;
 
         default:
-          if (in_comment)
-            {
-              comment_buf += static_cast<char> (c);
-              beginning_of_comment = false;
-              break;
-            }
-          else
-            goto done;
+          panic_impossible ();
         }
+
+      if (! tok_val)
+        tok_val = new token (kw->tok, true, l, c);
+
+      push_token (tok_val);
+
+      return kw->tok;
     }
 
-  if (! comment_buf.empty ())
-    octave_comment_buffer::append (comment_buf);
-
- done:
-  xunput (c, yytext);
-  current_input_column--;
-  return retval;
+  return 0;
+}
+
+bool
+octave_base_lexer::whitespace_is_significant (void)
+{
+  return (nesting_level.is_bracket ()
+          || (nesting_level.is_brace ()
+              && ! looking_at_object_index.front ()));
 }
 
 static inline bool
@@ -2386,23 +2119,25 @@
   return (len > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X'));
 }
 
-static void
-handle_number (void)
+void
+octave_base_lexer::handle_number (void)
 {
   double value = 0.0;
   int nread = 0;
 
-  if (looks_like_hex (yytext, strlen (yytext)))
+  char *yytxt = flex_yytext ();
+
+  if (looks_like_hex (yytxt, strlen (yytxt)))
     {
       unsigned long ival;
 
-      nread = sscanf (yytext, "%lx", &ival);
+      nread = sscanf (yytxt, "%lx", &ival);
 
       value = static_cast<double> (ival);
     }
   else
     {
-      char *tmp = strsave (yytext);
+      char *tmp = strsave (yytxt);
 
       char *idx = strpbrk (tmp, "Dd");
 
@@ -2418,19 +2153,85 @@
 
   assert (nread == 1);
 
-  lexer_flags.quote_is_transpose = true;
-  lexer_flags.convert_spaces_to_comma = true;
-  lexer_flags.looking_for_object_index = false;
-  lexer_flags.at_beginning_of_statement = false;
-
-  yylval.tok_val = new token (value, yytext, input_line_number,
-                              current_input_column);
-
-  token_stack.push (yylval.tok_val);
-
-  current_input_column += yyleng;
-
-  do_comma_insert_check ();
+  looking_for_object_index = false;
+  at_beginning_of_statement = false;
+
+  push_token (new token (NUM, value, yytxt, input_line_number,
+                         current_input_column));
+
+  current_input_column += flex_yyleng ();
+}
+
+void
+octave_base_lexer::handle_continuation (void)
+{
+  char *yytxt = flex_yytext ();
+  int yylng = flex_yyleng ();
+
+  int offset = 1;
+  if (yytxt[0] == '\\')
+    gripe_matlab_incompatible_continuation ();
+  else
+    offset = 3;
+
+  bool have_space = false;
+  while (offset < yylng)
+    {
+      char c = yytxt[offset];
+      if (c == ' ' || c == '\t')
+        {
+          have_space = true;
+          offset++;
+        }
+      else
+        break;
+    }
+
+  if (have_space)
+    mark_previous_token_trailing_space ();
+
+  bool have_comment = false;
+  while (offset < yylng)
+    {
+      char c = yytxt[offset];
+      if (c == '#' || c == '%')
+        {
+          have_comment = true;
+          offset++;
+        }
+      else
+        break;
+    }
+
+  if (have_comment)
+    {
+      comment_text = &yytxt[offset];
+
+      finish_comment (octave_comment_elt::end_of_line);
+    }
+
+  decrement_promptflag ();
+  input_line_number++;
+  current_input_column = 1;
+}
+
+void
+octave_base_lexer::finish_comment (octave_comment_elt::comment_type typ)
+{
+  bool copyright = looks_like_copyright (comment_text);
+
+  if (nesting_level.none () && help_text.empty ()
+    && ! comment_text.empty () && ! copyright)
+    help_text = comment_text;
+
+  if (copyright)
+    typ = octave_comment_elt::copyright;
+
+  octave_comment_buffer::append (comment_text, typ);
+
+  comment_text = "";
+
+  at_beginning_of_statement = true;
 }
 
 // We have seen a backslash and need to find out if it should be
@@ -2444,8 +2245,8 @@
 
 // FIXME -- we need to handle block comments here.
 
-static bool
-have_continuation (bool trailing_comments_ok)
+bool
+octave_base_lexer::have_continuation (bool trailing_comments_ok)
 {
   std::ostringstream buf;
 
@@ -2498,7 +2299,7 @@
               octave_comment_buffer::append (comment_buf);
             }
           current_input_column = 0;
-          promptflag--;
+          decrement_promptflag ();
           gripe_matlab_incompatible_continuation ();
           return true;
 
@@ -2514,7 +2315,7 @@
         }
     }
 
-  xunput (c, yytext);
+  xunput (c);
   return false;
 
 cleanup:
@@ -2523,7 +2324,7 @@
 
   int len = s.length ();
   while (len--)
-    xunput (s[len], yytext);
+    xunput (s[len]);
 
   return false;
 }
@@ -2532,8 +2333,8 @@
 // continuation.  If so, this eats it, up to and including the new
 // line character.
 
-static bool
-have_ellipsis_continuation (bool trailing_comments_ok)
+bool
+octave_base_lexer::have_ellipsis_continuation (bool trailing_comments_ok)
 {
   char c1 = text_yyinput ();
   if (c1 == '.')
@@ -2543,39 +2344,18 @@
         return true;
       else
         {
-          xunput (c2, yytext);
-          xunput (c1, yytext);
+          xunput (c2);
+          xunput (c1);
         }
     }
   else
-    xunput (c1, yytext);
+    xunput (c1);
 
   return false;
 }
 
-// See if we have a continuation line.  If so, eat it and the leading
-// whitespace on the next line.
-//
-// Return value is the same as described for eat_whitespace().
-
-static yum_yum
-eat_continuation (void)
-{
-  int retval = ATE_NOTHING;
-
-  int c = text_yyinput ();
-
-  if ((c == '.' && have_ellipsis_continuation ())
-      || (c == '\\' && have_continuation ()))
-    retval = eat_whitespace ();
-  else
-    xunput (c, yytext);
-
-  return retval;
-}
-
-static int
-handle_string (char delim)
+int
+octave_base_lexer::handle_string (char delim)
 {
   std::ostringstream buf;
 
@@ -2632,28 +2412,26 @@
               else
                 {
                   std::string s;
-                  xunput (c, yytext);
+                  xunput (c);
 
                   if (delim == '\'')
                     s = buf.str ();
                   else
                     s = do_string_escapes (buf.str ());
 
-                  lexer_flags.quote_is_transpose = true;
-                  lexer_flags.convert_spaces_to_comma = true;
-
-                  yylval.tok_val = new token (s, bos_line, bos_col);
-                  token_stack.push (yylval.tok_val);
-
                   if (delim == '"')
                     gripe_matlab_incompatible ("\" used as string delimiter");
                   else if (delim == '\'')
                     gripe_single_quote_string ();
 
-                  lexer_flags.looking_for_object_index = true;
-                  lexer_flags.at_beginning_of_statement = false;
-
-                  return delim == '"' ? DQ_STRING : SQ_STRING;
+                  looking_for_object_index = true;
+                  at_beginning_of_statement = false;
+
+                  int tok = delim == '"' ? DQ_STRING : SQ_STRING;
+
+                  push_token (new token (tok, s, bos_line, bos_col));
+
+                  return tok;
                 }
             }
         }
@@ -2668,100 +2446,8 @@
   return LEXICAL_ERROR;
 }
 
-static bool
-next_token_is_assign_op (void)
-{
-  bool retval = false;
-
-  int c0 = text_yyinput ();
-
-  switch (c0)
-    {
-    case '=':
-      {
-        int c1 = text_yyinput ();
-        xunput (c1, yytext);
-        if (c1 != '=')
-          retval = true;
-      }
-      break;
-
-    case '+':
-    case '-':
-    case '*':
-    case '/':
-    case '\\':
-    case '&':
-    case '|':
-      {
-        int c1 = text_yyinput ();
-        xunput (c1, yytext);
-        if (c1 == '=')
-          retval = true;
-      }
-      break;
-
-    case '.':
-      {
-        int c1 = text_yyinput ();
-        if (match_any (c1, "+-*/\\"))
-          {
-            int c2 = text_yyinput ();
-            xunput (c2, yytext);
-            if (c2 == '=')
-              retval = true;
-          }
-        xunput (c1, yytext);
-      }
-      break;
-
-    case '>':
-      {
-        int c1 = text_yyinput ();
-        if (c1 == '>')
-          {
-            int c2 = text_yyinput ();
-            xunput (c2, yytext);
-            if (c2 == '=')
-              retval = true;
-          }
-        xunput (c1, yytext);
-      }
-      break;
-
-    case '<':
-      {
-        int c1 = text_yyinput ();
-        if (c1 == '<')
-          {
-            int c2 = text_yyinput ();
-            xunput (c2, yytext);
-            if (c2 == '=')
-              retval = true;
-          }
-        xunput (c1, yytext);
-      }
-      break;
-
-    default:
-      break;
-    }
-
-  xunput (c0, yytext);
-
-  return retval;
-}
-
-static bool
-next_token_is_index_op (void)
-{
-  int c = text_yyinput ();
-  xunput (c, yytext);
-  return c == '(' || c == '{';
-}
-
-static int
-handle_close_bracket (bool spc_gobbled, int bracket_type)
+int
+octave_base_lexer::handle_close_bracket (int bracket_type)
 {
   int retval = bracket_type;
 
@@ -2770,372 +2456,34 @@
       nesting_level.remove ();
 
       if (bracket_type == ']')
-        lexer_flags.bracketflag--;
+        bracketflag--;
       else if (bracket_type == '}')
-        lexer_flags.braceflag--;
+        braceflag--;
       else
         panic_impossible ();
     }
 
-  if (lexer_flags.bracketflag == 0 && lexer_flags.braceflag == 0)
-    BEGIN (INITIAL);
-
-  if (bracket_type == ']'
-      && next_token_is_assign_op ()
-      && ! lexer_flags.looking_at_return_list)
-    {
-      retval = CLOSE_BRACE;
-    }
-  else if ((lexer_flags.bracketflag || lexer_flags.braceflag)
-           && lexer_flags.convert_spaces_to_comma
-           && (nesting_level.is_bracket ()
-               || (nesting_level.is_brace ()
-                   && ! lexer_flags.looking_at_object_index.front ())))
-    {
-      bool index_op = next_token_is_index_op ();
-
-      // Don't insert comma if we are looking at something like
-      //
-      //   [x{i}{j}] or [x{i}(j)]
-      //
-      // but do if we are looking at
-      //
-      //   [x{i} {j}] or [x{i} (j)]
-
-      if (spc_gobbled || ! (bracket_type == '}' && index_op))
-        {
-          bool bin_op = next_token_is_bin_op (spc_gobbled);
-
-          bool postfix_un_op = next_token_is_postfix_unary_op (spc_gobbled);
-
-          bool sep_op = next_token_is_sep_op ();
-
-          if (! (postfix_un_op || bin_op || sep_op))
-            {
-              maybe_warn_separator_insert (',');
-
-              xunput (',', yytext);
-              return retval;
-            }
-        }
-    }
-
-  lexer_flags.quote_is_transpose = true;
-  lexer_flags.convert_spaces_to_comma = true;
+  pop_start_state ();
 
   return retval;
 }
 
-static void
-maybe_unput_comma (int spc_gobbled)
-{
-  if (nesting_level.is_bracket ()
-      || (nesting_level.is_brace ()
-          && ! lexer_flags.looking_at_object_index.front ()))
-    {
-      int bin_op = next_token_is_bin_op (spc_gobbled);
-
-      int postfix_un_op = next_token_is_postfix_unary_op (spc_gobbled);
-
-      int c1 = text_yyinput ();
-      int c2 = text_yyinput ();
-
-      xunput (c2, yytext);
-      xunput (c1, yytext);
-
-      int sep_op = next_token_is_sep_op ();
-
-      int dot_op = (c1 == '.'
-                    && (isalpha (c2) || isspace (c2) || c2 == '_'));
-
-      if (postfix_un_op || bin_op || sep_op || dot_op)
-        return;
-
-      int index_op = (c1 == '(' || c1 == '{');
-
-      // If there is no space before the indexing op, we don't insert
-      // a comma.
-
-      if (index_op && ! spc_gobbled)
-        return;
-
-      maybe_warn_separator_insert (',');
-
-      xunput (',', yytext);
-    }
-}
-
-static bool
-next_token_can_follow_bin_op (void)
-{
-  std::stack<char> buf;
-
-  int c = EOF;
-
-  // Skip whitespace in current statement on current line
-  while (true)
-    {
-      c = text_yyinput ();
-
-      buf.push (c);
-
-      if (match_any (c, ",;\n") || (c != ' ' && c != '\t'))
-        break;
-    }
-
-  // Restore input.
-  while (! buf.empty ())
-    {
-      xunput (buf.top (), yytext);
-
-      buf.pop ();
-    }
-
-  return (isalnum (c) || match_any (c, "!\"'(-[_{~"));
-}
-
-static bool
-can_be_command (const std::string& tok)
-{
-  // Don't allow these names to be treated as commands to avoid
-  // surprises when parsing things like "NaN ^2".
-
-  return ! (tok == "e"
-            || tok == "I" || tok == "i"
-            || tok == "J" || tok == "j"
-            || tok == "Inf" || tok == "inf"
-            || tok == "NaN" || tok == "nan");
-}
-
-static bool
-looks_like_command_arg (void)
+bool
+octave_base_lexer::looks_like_command_arg (void)
 {
-  bool retval = true;
-
-  int c0 = text_yyinput ();
-
-  switch (c0)
-    {
-    // = ==
-    case '=':
-      {
-        int c1 = text_yyinput ();
-
-        if (c1 == '=')
-          {
-            int c2 = text_yyinput ();
-
-            if (! match_any (c2, ",;\n") && (c2 == ' ' || c2 == '\t')
-                && next_token_can_follow_bin_op ())
-              retval = false;
-
-            xunput (c2, yytext);
-          }
-        else
-          retval = false;
-
-        xunput (c1, yytext);
-      }
-      break;
-
-    case '(':
-    case '{':
-      // Indexing.
-      retval = false;
-      break;
-
-    case '\n':
-      // EOL.
-      break;
-
-    case '\'':
-    case '"':
-      // Beginning of a character string.
-      break;
-
-    // + - ++ -- += -=
-    case '+':
-    case '-':
-      {
-        int c1 = text_yyinput ();
-
-        switch (c1)
-          {
-          case '\n':
-            // EOL.
-          case '+':
-          case '-':
-            // Unary ops, spacing doesn't matter.
-            break;
-
-          case '\t':
-          case ' ':
-            {
-              if (next_token_can_follow_bin_op ())
-                retval = false;
-            }
-            break;
-
-          case '=':
-            {
-              int c2 = text_yyinput ();
-
-              if (! match_any (c2, ",;\n") && (c2 == ' ' || c2 == '\t')
-                  && next_token_can_follow_bin_op ())
-                retval = false;
-
-              xunput (c2, yytext);
-            }
-            break;
-          }
-
-        xunput (c1, yytext);
-      }
-      break;
-
-    case ':':
-    case '/':
-    case '\\':
-    case '^':
-      {
-        int c1 = text_yyinput ();
-
-        if (! match_any (c1, ",;\n") && (c1 == ' ' || c1 == '\t')
-            && next_token_can_follow_bin_op ())
-          retval = false;
-
-        xunput (c1, yytext);
-      }
-      break;
-
-    // .+ .- ./ .\ .^ .* .**
-    case '.':
-      {
-        int c1 = text_yyinput ();
-
-        if (match_any (c1, "+-/\\^*"))
-          {
-            int c2 = text_yyinput ();
-
-            if (c2 == '=')
-              {
-                int c3 = text_yyinput ();
-
-                if (! match_any (c3, ",;\n") && (c3 == ' ' || c3 == '\t')
-                    && next_token_can_follow_bin_op ())
-                  retval = false;
-
-                xunput (c3, yytext);
-              }
-            else if (! match_any (c2, ",;\n") && (c2 == ' ' || c2 == '\t')
-                     && next_token_can_follow_bin_op ())
-              retval = false;
-
-            xunput (c2, yytext);
-          }
-        else if (! match_any (c1, ",;\n")
-                 && (! isdigit (c1) && c1 != ' ' && c1 != '\t'
-                     && c1 != '.'))
-          {
-            // Structure reference.  FIXME -- is this a complete check?
-
-            retval = false;
-          }
-
-        xunput (c1, yytext);
-      }
-      break;
-
-    // & && | || * **
-    case '&':
-    case '|':
-    case '*':
-      {
-        int c1 = text_yyinput ();
-
-        if (c1 == c0)
-          {
-            int c2 = text_yyinput ();
-
-            if (! match_any (c2, ",;\n") && (c2 == ' ' || c2 == '\t')
-                && next_token_can_follow_bin_op ())
-              retval = false;
-
-            xunput (c2, yytext);
-          }
-        else if (! match_any (c1, ",;\n") && (c1 == ' ' || c1 == '\t')
-                 && next_token_can_follow_bin_op ())
-          retval = false;
-
-        xunput (c1, yytext);
-      }
-      break;
-
-    // < <= > >=
-    case '<':
-    case '>':
-      {
-        int c1 = text_yyinput ();
-
-        if (c1 == '=')
-          {
-            int c2 = text_yyinput ();
-
-            if (! match_any (c2, ",;\n") && (c2 == ' ' || c2 == '\t')
-                && next_token_can_follow_bin_op ())
-              retval = false;
-
-            xunput (c2, yytext);
-          }
-        else if (! match_any (c1, ",;\n") && (c1 == ' ' || c1 == '\t')
-                 && next_token_can_follow_bin_op ())
-          retval = false;
-
-        xunput (c1, yytext);
-      }
-      break;
-
-    // ~= !=
-    case '~':
-    case '!':
-      {
-        int c1 = text_yyinput ();
-
-        // ~ and ! can be unary ops, so require following =.
-        if (c1 == '=')
-          {
-            int c2 = text_yyinput ();
-
-            if (! match_any (c2, ",;\n") && (c2 == ' ' || c2 == '\t')
-                && next_token_can_follow_bin_op ())
-              retval = false;
-
-            xunput (c2, yytext);
-          }
-        else if (! match_any (c1, ",;\n") && (c1 == ' ' || c1 == '\t')
-                 && next_token_can_follow_bin_op ())
-          retval = false;
-
-        xunput (c1, yytext);
-      }
-      break;
-
-    default:
-      break;
-    }
-
-  xunput (c0, yytext);
-
-  return retval;
+  bool space_before = space_follows_previous_token ();
+  bool space_after = looking_at_space ();
+
+  return (space_before && ! space_after
+          && previous_token_may_be_command ());
 }
 
-static int
-handle_superclass_identifier (void)
+int
+octave_base_lexer::handle_superclass_identifier (void)
 {
-  eat_continuation ();
-
   std::string pkg;
-  std::string meth = strip_trailing_whitespace (yytext);
+  char *yytxt = flex_yytext ();
+  std::string meth = strip_trailing_whitespace (yytxt);
   size_t pos = meth.find ("@");
   std::string cls = meth.substr (pos).substr (1);
   meth = meth.substr (0, pos - 1);
@@ -3155,26 +2503,26 @@
       return LEXICAL_ERROR;
     }
 
-  yylval.tok_val
-    = new token (meth.empty () ? 0 : &(symbol_table::insert (meth)),
-                 cls.empty () ? 0 : &(symbol_table::insert (cls)),
-                 pkg.empty () ? 0 : &(symbol_table::insert (pkg)),
-                 input_line_number, current_input_column);
-  token_stack.push (yylval.tok_val);
-
-  lexer_flags.convert_spaces_to_comma = true;
-  current_input_column += yyleng;
+  symbol_table::scope_id sid = symtab_context.curr_scope ();
+
+  push_token (new token
+              (SUPERCLASSREF,
+               meth.empty () ? 0 : &(symbol_table::insert (meth, sid)),
+               cls.empty () ? 0 : &(symbol_table::insert (cls, sid)),
+               pkg.empty () ? 0 : &(symbol_table::insert (pkg, sid)),
+               input_line_number, current_input_column));
+
+  current_input_column += flex_yyleng ();
 
   return SUPERCLASSREF;
 }
 
-static int
-handle_meta_identifier (void)
+int
+octave_base_lexer::handle_meta_identifier (void)
 {
-  eat_continuation ();
-
   std::string pkg;
-  std::string cls = strip_trailing_whitespace (yytext).substr (1);
+  char *yytxt = flex_yytext ();
+  std::string cls = strip_trailing_whitespace (yytxt).substr (1);
   size_t pos = cls.find (".");
 
   if (pos != std::string::npos)
@@ -3190,15 +2538,15 @@
       return LEXICAL_ERROR;
     }
 
-  yylval.tok_val
-    = new token (cls.empty () ? 0 : &(symbol_table::insert (cls)),
-                 pkg.empty () ? 0 : &(symbol_table::insert (pkg)),
-                 input_line_number, current_input_column);
-
-  token_stack.push (yylval.tok_val);
-
-  lexer_flags.convert_spaces_to_comma = true;
-  current_input_column += yyleng;
+  symbol_table::scope_id sid = symtab_context.curr_scope ();
+
+  push_token (new token
+              (METAQUERY,
+               cls.empty () ? 0 : &(symbol_table::insert (cls, sid)),
+               pkg.empty () ? 0 : &(symbol_table::insert (pkg, sid)),
+               input_line_number, current_input_column));
+
+  current_input_column += flex_yyleng ();
 
   return METAQUERY;
 }
@@ -3207,58 +2555,43 @@
 // an identifier.  Handles keywords.  Return -1 if the identifier
 // should be ignored.
 
-static int
-handle_identifier (void)
+int
+octave_base_lexer::handle_identifier (void)
 {
-  bool at_bos = lexer_flags.at_beginning_of_statement;
-
-  std::string tok = strip_trailing_whitespace (yytext);
-
-  int c = yytext[yyleng-1];
-
-  int cont_is_spc = eat_continuation ();
-
-  int spc_gobbled = (cont_is_spc || c == ' ' || c == '\t');
+  char *yytxt = flex_yytext ();
+
+  std::string tok = yytxt;
 
   // If we are expecting a structure element, avoid recognizing
   // keywords and other special names and return STRUCT_ELT, which is
   // a string that is also a valid identifier.  But first, we have to
   // decide whether to insert a comma.
 
-  if (lexer_flags.looking_at_indirect_ref)
+  if (looking_at_indirect_ref)
     {
-      do_comma_insert_check ();
-
-      maybe_unput_comma (spc_gobbled);
-
-      yylval.tok_val = new token (tok, input_line_number,
-                                  current_input_column);
-
-      token_stack.push (yylval.tok_val);
-
-      lexer_flags.quote_is_transpose = true;
-      lexer_flags.convert_spaces_to_comma = true;
-      lexer_flags.looking_for_object_index = true;
-
-      current_input_column += yyleng;
+      push_token (new token (STRUCT_ELT, tok, input_line_number,
+                             current_input_column));
+
+      looking_for_object_index = true;
+
+      current_input_column += flex_yyleng ();
 
       return STRUCT_ELT;
     }
 
-  lexer_flags.at_beginning_of_statement = false;
-
   // The is_keyword_token may reset
-  // lexer_flags.at_beginning_of_statement.  For example, if it sees
+  // at_beginning_of_statement.  For example, if it sees
   // an else token, then the next token is at the beginning of a
   // statement.
 
+  // May set at_beginning_of_statement to true.
   int kw_token = is_keyword_token (tok);
 
   // If we found a keyword token, then the beginning_of_statement flag
   // is already set.  Otherwise, we won't be at the beginning of a
   // statement.
 
-  if (lexer_flags.looking_at_function_handle)
+  if (looking_at_function_handle)
     {
       if (kw_token)
         {
@@ -3268,15 +2601,13 @@
         }
       else
         {
-          yylval.tok_val = new token (tok, input_line_number,
-                                      current_input_column);
-
-          token_stack.push (yylval.tok_val);
-
-          current_input_column += yyleng;
-          lexer_flags.quote_is_transpose = false;
-          lexer_flags.convert_spaces_to_comma = true;
-          lexer_flags.looking_for_object_index = true;
+          push_token (new token (FCN_HANDLE, tok, input_line_number,
+                                 current_input_column));
+
+          current_input_column += flex_yyleng ();
+          looking_for_object_index = true;
+
+          at_beginning_of_statement = false;
 
           return FCN_HANDLE;
         }
@@ -3289,232 +2620,49 @@
     {
       if (kw_token >= 0)
         {
-          current_input_column += yyleng;
-          lexer_flags.quote_is_transpose = false;
-          lexer_flags.convert_spaces_to_comma = true;
-          lexer_flags.looking_for_object_index = false;
+          current_input_column += flex_yyleng ();
+          looking_for_object_index = false;
         }
 
       return kw_token;
     }
 
-  // See if we have a plot keyword (title, using, with, or clear).
-
-  int c1 = text_yyinput ();
-
-  bool next_tok_is_eq = false;
-  if (c1 == '=')
-    {
-      int c2 = text_yyinput ();
-      xunput (c2, yytext);
-
-      if (c2 != '=')
-        next_tok_is_eq = true;
-    }
-
-  xunput (c1, yytext);
-
-  // Kluge alert.
-  //
-  // If we are looking at a text style function, set up to gobble its
-  // arguments.
-  //
-  // If the following token is '=', or if we are parsing a function
-  // return list or function parameter list, or if we are looking at
-  // something like [ab,cd] = foo (), force the symbol to be inserted
-  // as a variable in the current symbol table.
-
-  if (! is_variable (tok))
-    {
-      if (at_bos && spc_gobbled && can_be_command (tok)
-          && looks_like_command_arg ())
-        {
-          BEGIN (COMMAND_START);
-        }
-      else if (next_tok_is_eq
-               || lexer_flags.looking_at_decl_list
-               || lexer_flags.looking_at_return_list
-               || (lexer_flags.looking_at_parameter_list
-                   && ! lexer_flags.looking_at_initializer_expression))
-        {
-          symbol_table::force_variable (tok);
-        }
-      else if (lexer_flags.looking_at_matrix_or_assign_lhs)
-        {
-          lexer_flags.pending_local_variables.insert (tok);
-        }
-    }
-
   // Find the token in the symbol table.  Beware the magic
   // transformation of the end keyword...
 
   if (tok == "end")
     tok = "__end__";
 
-  yylval.tok_val = new token (&(symbol_table::insert (tok)),
+  symbol_table::scope_id sid = symtab_context.curr_scope ();
+
+  token *tok_val = new token (NAME, &(symbol_table::insert (tok, sid)),
                               input_line_number, current_input_column);
 
-  token_stack.push (yylval.tok_val);
-
-  // After seeing an identifer, it is ok to convert spaces to a comma
-  // (if needed).
-
-  lexer_flags.convert_spaces_to_comma = true;
-
-  if (! (next_tok_is_eq || YY_START == COMMAND_START))
-    {
-      lexer_flags.quote_is_transpose = true;
-
-      do_comma_insert_check ();
-
-      maybe_unput_comma (spc_gobbled);
-    }
-
-  current_input_column += yyleng;
+  if (at_beginning_of_statement
+      && (! (is_variable (tok)
+             || tok == "e"
+             || tok == "I" || tok == "i"
+             || tok == "J" || tok == "j"
+             || tok == "Inf" || tok == "inf"
+             || tok == "NaN" || tok == "nan")))
+    tok_val->mark_may_be_command ();
+
+  push_token (tok_val);
+
+  current_input_column += flex_yyleng ();
 
   if (tok != "__end__")
-    lexer_flags.looking_for_object_index = true;
+    looking_for_object_index = true;
+
+  at_beginning_of_statement = false;
 
   return NAME;
 }
 
 void
-lexical_feedback::init (void)
+octave_base_lexer::maybe_warn_separator_insert (char sep)
 {
-  // Not initially defining a matrix list.
-  bracketflag = 0;
-
-  // Not initially defining a cell array list.
-  braceflag = 0;
-
-  // Not initially inside a loop or if statement.
-  looping = 0;
-
-  // Not initially defining a function.
-  defining_func = 0;
-
-  // Not parsing an object index.
-  while (! parsed_function_name.empty ())
-    parsed_function_name.pop ();
-
-  parsing_class_method = false;
-
-  // Not initially defining a class with classdef.
-  maybe_classdef_get_set_method = false;
-  parsing_classdef = false;
-
-  // Not initiallly looking at a function handle.
-  looking_at_function_handle = 0;
-
-  // Not initiallly looking at an anonymous function argument list.
-  looking_at_anon_fcn_args = 0;
-
-  // Not parsing a function return, parameter, or declaration list.
-  looking_at_return_list = false;
-  looking_at_parameter_list = false;
-  looking_at_decl_list = false;
-
-  // Not looking at an argument list initializer expression.
-  looking_at_initializer_expression = false;
-
-  // Not parsing a matrix or the left hand side of multi-value
-  // assignment statement.
-  looking_at_matrix_or_assign_lhs = false;
-
-  // Not parsing an object index.
-  while (! looking_at_object_index.empty ())
-    looking_at_object_index.pop_front ();
-
-  looking_at_object_index.push_front (false);
-
-  // Object index not possible until we've seen something.
-  looking_for_object_index = false;
-
-  // Yes, we are at the beginning of a statement.
-  at_beginning_of_statement = true;
-
-  // No need to do comma insert or convert spaces to comma at
-  // beginning of input.
-  convert_spaces_to_comma = true;
-  do_comma_insert = false;
-
-  // Not initially looking at indirect references.
-  looking_at_indirect_ref = false;
-
-  // Quote marks strings intially.
-  quote_is_transpose = false;
-
-  // Set of identifiers that might be local variable names is empty.
-  pending_local_variables.clear ();
-}
-
-bool
-is_keyword (const std::string& s)
-{
-  return octave_kw_hash::in_word_set (s.c_str (), s.length ()) != 0;
-}
-
-DEFUN (iskeyword, args, ,
-  "-*- texinfo -*-\n\
-@deftypefn  {Built-in Function} {} iskeyword ()\n\
-@deftypefnx {Built-in Function} {} iskeyword (@var{name})\n\
-Return true if @var{name} is an Octave keyword.  If @var{name}\n\
-is omitted, return a list of keywords.\n\
-@seealso{isvarname, exist}\n\
-@end deftypefn")
-{
-  octave_value retval;
-
-  int argc = args.length () + 1;
-
-  string_vector argv = args.make_argv ("iskeyword");
-
-  if (error_state)
-    return retval;
-
-  if (argc == 1)
-    {
-      string_vector lst (TOTAL_KEYWORDS);
-
-      for (int i = 0; i < TOTAL_KEYWORDS; i++)
-        lst[i] = wordlist[i].name;
-
-      retval = Cell (lst.sort ());
-    }
-  else if (argc == 2)
-    {
-      retval = is_keyword (argv[1]);
-    }
-  else
-    print_usage ();
-
-  return retval;
-}
-
-/*
-
-%!assert (iskeyword ("for"))
-%!assert (iskeyword ("fort"), false)
-%!assert (iskeyword ("fft"), false)
-
-*/
-
-void
-prep_lexer_for_script_file (void)
-{
-  BEGIN (SCRIPT_FILE_BEGIN);
-}
-
-void
-prep_lexer_for_function_file (void)
-{
-  BEGIN (FUNCTION_FILE_BEGIN);
-}
-
-static void
-maybe_warn_separator_insert (char sep)
-{
-  std::string nm = curr_fcn_file_full_name;
+  std::string nm = fcn_file_full_name;
 
   if (nm.empty ())
     warning_with_id ("Octave:separator-insert",
@@ -3526,10 +2674,10 @@
                      sep, input_line_number, nm.c_str ());
 }
 
-static void
-gripe_single_quote_string (void)
+void
+octave_base_lexer::gripe_single_quote_string (void)
 {
-  std::string nm = curr_fcn_file_full_name;
+  std::string nm = fcn_file_full_name;
 
   if (nm.empty ())
     warning_with_id ("Octave:single-quote-string",
@@ -3541,10 +2689,10 @@
                      input_line_number, nm.c_str ());
 }
 
-static void
-gripe_matlab_incompatible (const std::string& msg)
+void
+octave_base_lexer::gripe_matlab_incompatible (const std::string& msg)
 {
-  std::string nm = curr_fcn_file_full_name;
+  std::string nm = fcn_file_full_name;
 
   if (nm.empty ())
     warning_with_id ("Octave:matlab-incompatible",
@@ -3556,21 +2704,21 @@
                      msg.c_str (), input_line_number, nm.c_str ());
 }
 
-static void
-maybe_gripe_matlab_incompatible_comment (char c)
+void
+octave_base_lexer::maybe_gripe_matlab_incompatible_comment (char c)
 {
   if (c == '#')
     gripe_matlab_incompatible ("# used as comment character");
 }
 
-static void
-gripe_matlab_incompatible_continuation (void)
+void
+octave_base_lexer::gripe_matlab_incompatible_continuation (void)
 {
   gripe_matlab_incompatible ("\\ used as line continuation marker");
 }
 
-static void
-gripe_matlab_incompatible_operator (const std::string& op)
+void
+octave_base_lexer::gripe_matlab_incompatible_operator (const std::string& op)
 {
   std::string t = op;
   int n = t.length ();
@@ -3579,8 +2727,23 @@
   gripe_matlab_incompatible (t + " used as operator");
 }
 
-static void
-display_token (int tok)
+void
+octave_base_lexer::push_token (token *tok)
+{
+  YYSTYPE *lval = yyget_lval (scanner);
+  lval->tok_val = tok;
+  tokens.push (tok);
+}
+
+token *
+octave_base_lexer::current_token (void)
+{
+  YYSTYPE *lval = yyget_lval (scanner);
+  return lval->tok_val;
+}
+
+void
+octave_base_lexer::display_token (int tok)
 {
   switch (tok)
     {
@@ -3623,7 +2786,7 @@
     case ELEFTDIV: std::cerr << "ELEFTDIV\n"; break;
     case EPLUS: std::cerr << "EPLUS\n"; break;
     case EMINUS: std::cerr << "EMINUS\n"; break;
-    case QUOTE: std::cerr << "QUOTE\n"; break;
+    case HERMITIAN: std::cerr << "HERMITIAN\n"; break;
     case TRANSPOSE: std::cerr << "TRANSPOSE\n"; break;
     case PLUS_PLUS: std::cerr << "PLUS_PLUS\n"; break;
     case MINUS_MINUS: std::cerr << "MINUS_MINUS\n"; break;
@@ -3632,16 +2795,24 @@
 
     case NUM:
     case IMAG_NUM:
-      std::cerr << (tok == NUM ? "NUM" : "IMAG_NUM")
-                << " [" << yylval.tok_val->number () << "]\n";
+      {
+        token *tok_val = current_token ();
+        std::cerr << (tok == NUM ? "NUM" : "IMAG_NUM")
+                  << " [" << tok_val->number () << "]\n";
+      }
       break;
 
     case STRUCT_ELT:
-      std::cerr << "STRUCT_ELT [" << yylval.tok_val->text () << "]\n"; break;
+      {
+        token *tok_val = current_token ();
+        std::cerr << "STRUCT_ELT [" << tok_val->text () << "]\n";
+      }
+      break;
 
     case NAME:
       {
-        symbol_table::symbol_record *sr = yylval.tok_val->sym_rec ();
+        token *tok_val = current_token ();
+        symbol_table::symbol_record *sr = tok_val->sym_rec ();
         std::cerr << "NAME";
         if (sr)
           std::cerr << " [" << sr->name () << "]";
@@ -3653,8 +2824,12 @@
 
     case DQ_STRING:
     case SQ_STRING:
-      std::cerr << (tok == DQ_STRING ? "DQ_STRING" : "SQ_STRING")
-                << " [" << yylval.tok_val->text () << "]\n";
+      {
+        token *tok_val = current_token ();
+
+        std::cerr << (tok == DQ_STRING ? "DQ_STRING" : "SQ_STRING")
+                  << " [" << tok_val->text () << "]\n";
+      }
       break;
 
     case FOR: std::cerr << "FOR\n"; break;
@@ -3675,14 +2850,12 @@
     case TRY: std::cerr << "TRY\n"; break;
     case CATCH: std::cerr << "CATCH\n"; break;
     case GLOBAL: std::cerr << "GLOBAL\n"; break;
-    case STATIC: std::cerr << "STATIC\n"; break;
+    case PERSISTENT: std::cerr << "PERSISTENT\n"; break;
     case FCN_HANDLE: std::cerr << "FCN_HANDLE\n"; break;
     case END_OF_INPUT: std::cerr << "END_OF_INPUT\n\n"; break;
     case LEXICAL_ERROR: std::cerr << "LEXICAL_ERROR\n\n"; break;
     case FCN: std::cerr << "FCN\n"; break;
-    case CLOSE_BRACE: std::cerr << "CLOSE_BRACE\n"; break;
-    case SCRIPT_FILE: std::cerr << "SCRIPT_FILE\n"; break;
-    case FUNCTION_FILE: std::cerr << "FUNCTION_FILE\n"; break;
+    case INPUT_FILE: std::cerr << "INPUT_FILE\n"; break;
     case SUPERCLASSREF: std::cerr << "SUPERCLASSREF\n"; break;
     case METAQUERY: std::cerr << "METAQUERY\n"; break;
     case GET: std::cerr << "GET\n"; break;
@@ -3696,7 +2869,7 @@
     case '\t': std::cerr << "TAB\n"; break;
     default:
       {
-        if (tok < 256)
+        if (tok < 256 && tok > 31)
           std::cerr << static_cast<char> (tok) << "\n";
         else
           std::cerr << "UNKNOWN(" << tok << ")\n";
@@ -3705,12 +2878,65 @@
     }
 }
 
-static void
-display_state (void)
+void
+octave_base_lexer::fatal_error (const char *msg)
+{
+  error (msg);
+
+  OCTAVE_QUIT;
+
+  yy_fatal_error (msg, scanner);
+}
+
+void
+octave_base_lexer::lexer_debug (const char *pattern)
+{
+  if (lexer_debug_flag)
+    {
+      std::cerr << std::endl;
+
+      display_start_state ();
+
+      std::cerr << "P: " << pattern << std::endl;
+      std::cerr << "T: " << flex_yytext () << std::endl;
+    }
+}
+
+void
+octave_base_lexer::push_start_state (int state)
+{
+  OCTAVE_YYG;
+
+  start_state_stack.push (state);
+
+  BEGIN (start_state ());
+}
+
+void
+octave_base_lexer::pop_start_state (void)
+{
+  OCTAVE_YYG;
+
+  start_state_stack.pop ();
+
+  BEGIN (start_state ());
+}
+
+void
+octave_base_lexer::clear_start_state (void)
+{
+  while (! start_state_stack.empty ())
+    start_state_stack.pop ();
+
+  push_start_state (INITIAL);
+}
+
+void
+octave_base_lexer::display_start_state (void) const
 {
   std::cerr << "S: ";
 
-  switch (YY_START)
+  switch (start_state ())
     {
     case INITIAL:
       std::cerr << "INITIAL" << std::endl;
@@ -3724,12 +2950,16 @@
       std::cerr << "MATRIX_START" << std::endl;
       break;
 
-    case SCRIPT_FILE_BEGIN:
-      std::cerr << "SCRIPT_FILE_BEGIN" << std::endl;
+    case INPUT_FILE_START:
+      std::cerr << "INPUT_FILE_BEGIN" << std::endl;
       break;
 
-    case FUNCTION_FILE_BEGIN:
-      std::cerr << "FUNCTION_FILE_BEGIN" << std::endl;
+    case BLOCK_COMMENT_START:
+      std::cerr << "BLOCK_COMMENT_START" << std::endl;
+      break;
+
+    case LINE_COMMENT_START:
+      std::cerr << "LINE_COMMENT_START" << std::endl;
       break;
 
     default:
@@ -3738,46 +2968,177 @@
     }
 }
 
-static void
-lexer_debug (const char *pattern, const char *text)
+int
+octave_base_lexer::handle_op (const char *pattern, int tok, bool bos)
 {
-  std::cerr << std::endl;
-
-  display_state ();
-
-  std::cerr << "P: " << pattern << std::endl;
-  std::cerr << "T: " << text << std::endl;
+  lexer_debug (pattern);
+
+  return handle_op_internal (tok, bos, true);
+}
+
+int
+octave_base_lexer::handle_incompatible_op (const char *pattern, int tok,
+                                           bool bos)
+{
+  lexer_debug (pattern);
+
+  return handle_op_internal (tok, bos, false);
 }
 
-DEFUN (__display_tokens__, args, nargout,
-  "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {} __display_tokens__ ()\n\
-Query or set the internal variable that determines whether Octave's\n\
-lexer displays tokens as they are read.\n\
-@end deftypefn")
+bool
+octave_base_lexer::maybe_unput_comma_before_unary_op (int tok)
+{
+  int prev_tok = previous_token_value ();
+
+  bool unput_comma = false;
+
+  if (whitespace_is_significant () && space_follows_previous_token ())
+    {
+      int c = text_yyinput ();
+      xunput (c);
+
+      bool space_after = (c == ' ' || c == '\t');
+
+      if (! (prev_tok == '[' || prev_tok == '{'
+             || previous_token_is_binop ()
+             || ((tok == '+' || tok == '-') && space_after)))
+        unput_comma = true;
+    }
+
+  return unput_comma;
+}
+
+int
+octave_base_lexer::handle_unary_op (int tok, bool bos)
 {
-  return SET_INTERNAL_VARIABLE (display_tokens);
+  return maybe_unput_comma_before_unary_op (tok)
+    ? -1 : handle_op_internal (tok, bos, true);
+}
+
+int
+octave_base_lexer::handle_incompatible_unary_op (int tok, bool bos)
+{
+  return maybe_unput_comma_before_unary_op (tok)
+    ? -1 : handle_op_internal (tok, bos, false);
+}
+
+int
+octave_base_lexer::handle_op_internal (int tok, bool bos, bool compat)
+{
+  if (! compat)
+    gripe_matlab_incompatible_operator (flex_yytext ());
+
+  push_token (new token (tok, input_line_number, current_input_column));
+
+  current_input_column += flex_yyleng ();
+  looking_for_object_index = false;
+  at_beginning_of_statement = bos;
+
+  return count_token (tok);
+}
+
+int
+octave_base_lexer::handle_token (const std::string& name, int tok)
+{
+  token *tok_val = new token (tok, name, input_line_number,
+                              current_input_column);
+
+  return handle_token (tok, tok_val);
 }
 
-DEFUN (__token_count__, , ,
-  "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {} __token_count__ ()\n\
-Number of language tokens processed since Octave startup.\n\
-@end deftypefn")
+int
+octave_base_lexer::handle_token (int tok, token *tok_val)
+{
+  if (! tok_val)
+    tok_val = new token (tok, input_line_number, current_input_column);
+
+  push_token (tok_val);
+
+  current_input_column += flex_yyleng ();
+
+  return count_token_internal (tok);
+}
+
+int
+octave_base_lexer::count_token (int tok)
 {
-  return octave_value (Vtoken_count);
+  token *tok_val = new token (tok, input_line_number, current_input_column);
+
+  push_token (tok_val);
+
+  return count_token_internal (tok);
+}
+
+int
+octave_base_lexer::count_token_internal (int tok)
+{
+  if (tok != '\n')
+    {
+      Vtoken_count++;
+      token_count++;
+    }
+
+  return show_token (tok);
 }
 
-DEFUN (__lexer_debug_flag__, args, nargout,
-  "-*- texinfo -*-\n\
-@deftypefn {Built-in Function} {@var{old_val} =} __lexer_debug_flag__ (@var{new_val}))\n\
-Undocumented internal function.\n\
-@end deftypefn")
+int
+octave_base_lexer::show_token (int tok)
+{
+  if (Vdisplay_tokens)
+    display_token (tok);
+
+  if (lexer_debug_flag)
+    {
+      std::cerr << "R: ";
+      display_token (tok);
+      std::cerr << std::endl; 
+    }
+
+  return tok;
+}
+
+int
+octave_lexer::fill_flex_buffer (char *buf, unsigned max_size)
 {
-  octave_value retval;
-
-  retval = set_internal_variable (lexer_debug_flag, args, nargout,
-                                  "__lexer_debug_flag__");
-
-  return retval;
+  int status = 0;
+
+  if (input_buf.empty ())
+    {
+      bool eof = false;
+      current_input_line = input_reader.get_input (eof);
+      input_buf.fill (current_input_line, eof);
+    }
+
+  if (! input_buf.empty ())
+    status = input_buf.copy_chunk (buf, max_size);
+  else
+    {
+      status = YY_NULL;
+
+      if (! input_buf.at_eof ())
+        fatal_error ("octave_base_lexer::fill_flex_buffer failed");
+    }
+
+  return status;
 }
+
+int
+octave_push_lexer::fill_flex_buffer (char *buf, unsigned max_size)
+{
+  int status = 0;
+
+  if (input_buf.empty () && ! input_buf.at_eof ())
+    input_buf.fill (std::string (1, static_cast<char> (1)), false);
+ 
+  if (! input_buf.empty ())
+    status = input_buf.copy_chunk (buf, max_size);
+  else
+    {
+      status = YY_NULL;
+
+      if (! input_buf.at_eof ())
+        fatal_error ("octave_base_lexer::fill_flex_buffer failed");
+    }
+
+  return status;
+}
new file mode 100644
--- /dev/null
+++ b/libinterp/parse-tree/module.mk
@@ -0,0 +1,109 @@
+EXTRA_DIST += \
+  parse-tree/module.mk \
+  parse-tree/octave.gperf
+
+PARSER_INC = \
+  parse-tree/lex.h \
+  parse-tree/parse.h
+
+PARSER_SRC = \
+  parse-tree/lex.ll \
+  parse-tree/oct-parse.yy
+
+PARSE_TREE_INC = \
+  parse-tree/pt-all.h \
+  parse-tree/pt-arg-list.h \
+  parse-tree/pt-array-list.h \
+  parse-tree/pt-assign.h \
+  parse-tree/pt-binop.h \
+  parse-tree/pt-bp.h \
+  parse-tree/pt-cbinop.h \
+  parse-tree/pt-cell.h \
+  parse-tree/pt-check.h \
+  parse-tree/pt-cmd.h \
+  parse-tree/pt-colon.h \
+  parse-tree/pt-const.h \
+  parse-tree/pt-decl.h \
+  parse-tree/pt-eval.h \
+  parse-tree/pt-except.h \
+  parse-tree/pt-exp.h \
+  parse-tree/pt-fcn-handle.h \
+  parse-tree/pt-id.h \
+  parse-tree/pt-idx.h \
+  parse-tree/pt-jump.h \
+  parse-tree/pt-loop.h \
+  parse-tree/pt-mat.h \
+  parse-tree/pt-misc.h \
+  parse-tree/pt-pr-code.h \
+  parse-tree/pt-select.h \
+  parse-tree/pt-stmt.h \
+  parse-tree/pt-unop.h \
+  parse-tree/pt-walk.h \
+  parse-tree/pt.h \
+  parse-tree/token.h
+
+PARSE_TREE_SRC = \
+  parse-tree/pt-arg-list.cc \
+  parse-tree/pt-array-list.cc \
+  parse-tree/pt-assign.cc \
+  parse-tree/pt-binop.cc \
+  parse-tree/pt-bp.cc \
+  parse-tree/pt-cbinop.cc \
+  parse-tree/pt-cell.cc \
+  parse-tree/pt-check.cc \
+  parse-tree/pt-cmd.cc \
+  parse-tree/pt-colon.cc \
+  parse-tree/pt-const.cc \
+  parse-tree/pt-decl.cc \
+  parse-tree/pt-eval.cc \
+  parse-tree/pt-except.cc \
+  parse-tree/pt-exp.cc \
+  parse-tree/pt-fcn-handle.cc \
+  parse-tree/pt-id.cc \
+  parse-tree/pt-idx.cc \
+  parse-tree/pt-jump.cc \
+  parse-tree/pt-loop.cc \
+  parse-tree/pt-mat.cc \
+  parse-tree/pt-misc.cc \
+  parse-tree/pt-pr-code.cc \
+  parse-tree/pt-select.cc \
+  parse-tree/pt-stmt.cc \
+  parse-tree/pt-unop.cc \
+  parse-tree/pt.cc \
+  parse-tree/token.cc
+
+## Special rules for sources which must be built before rest of compilation.
+
+## Don't use a pipeline to process gperf output since if gperf
+## is missing but sed is not, the exit status of the pipeline
+## will still be success and we will end up creating an empty
+## oct-gperf.h file.
+parse-tree/oct-gperf.h: parse-tree/octave.gperf
+	$(GPERF) -t -C -D -G -L C++ -Z octave_kw_hash $< > $@-t1
+	$(SED) 's,lookup\[,gperf_lookup[,' < $@-t1 > $@-t
+	mv $@-t $@
+	rm -f $@-t1
+
+parse-tree/oct-parse.yy: parse-tree/oct-parse.in.yy
+	case "$(BISON_PUSH_PULL_DECL_STYLE)" in \
+          *quote*) quote='"' ;; \
+	  *) quote="" ;; \
+        esac; \
+        case "$(BISON_PUSH_PULL_DECL_STYLE)" in \
+          *dash*) decl="%define api.push-pull $${quote}both$${quote}"; ;; \
+          *underscore*) decl="%define api.push_pull $${quote}both$${quote}"; ;; \
+        esac; \
+	$(SED) "s/%PUSH_PULL_DECL%/$$decl/" $< > $@-t
+	mv $@-t $@
+
+noinst_LTLIBRARIES += \
+  parse-tree/libparse-tree.la \
+  parse-tree/libparser.la
+
+parse_tree_libparse_tree_la_SOURCES = $(PARSE_TREE_SRC)
+parse_tree_libparse_tree_la_CPPFLAGS = $(liboctinterp_la_CPPFLAGS)
+
+parse_tree_libparser_la_SOURCES = $(PARSER_SRC)
+parse_tree_libparser_la_CPPFLAGS = $(liboctinterp_la_CPPFLAGS)
+parse_tree_libparser_la_CXXFLAGS = \
+  $(filter-out -Wold-style-cast, $(AM_CXXFLAGS))
rename from src/oct-parse.yy
rename to libinterp/parse-tree/oct-parse.in.yy
--- a/src/oct-parse.yy
+++ b/libinterp/parse-tree/oct-parse.in.yy
@@ -76,6 +76,15 @@
 #include "utils.h"
 #include "variables.h"
 
+// oct-parse.h must be included after pt-all.h
+#include <oct-parse.h>
+
+extern int octave_lex (YYSTYPE *, void *);
+
+// Global access to currently active lexer.
+// FIXME -- to be removed after more parser+lexer refactoring.
+octave_base_lexer *LEXER = 0;
+
 #if defined (GNULIB_NAMESPACE)
 // Calls to the following functions appear in the generated output from
 // Bison without the namespace tag.  Redefine them so we will use them
@@ -85,270 +94,16 @@
 #define malloc GNULIB_NAMESPACE::malloc
 #endif
 
-// The current input line number.
-int input_line_number = 1;
-
-// The column of the current token.
-int current_input_column = 1;
-
-// Buffer for help text snagged from function files.
-std::stack<std::string> help_buf;
-
-// Buffer for comments appearing before a function statement.
-static std::string fcn_comment_header;
-
-// TRUE means we are using readline.
-// (--no-line-editing)
-bool line_editing = true;
-
 // TRUE means we printed messages about reading startup files.
 bool reading_startup_message_printed = false;
 
-// TRUE means input is coming from startup file.
-bool input_from_startup_file = false;
-
-// = 0 currently outside any function.
-// = 1 inside the primary function or a subfunction.
-// > 1 means we are looking at a function definition that seems to be
-//     inside a function. Note that the function still might not be a
-//     nested function.
-static int current_function_depth = 0;
-
-// Maximum function depth detected. Just here to determine whether
-// we have nested functions or just implicitly ended subfunctions.
-static int max_function_depth = 0;
-
-// FALSE if we are still at the primary function. Subfunctions can
-// only be declared inside function files.
-static int parsing_subfunctions = false;
-
-// Have we found an explicit end to a function?
-static bool endfunction_found = false;
-
-// Keep track of symbol table information when parsing functions.
-std::stack<symbol_table::scope_id> symtab_context;
-
-// Name of the current class when we are parsing class methods or
-// constructors.
-std::string current_class_name;
-
-// TRUE means we are in the process of autoloading a function.
-static bool autoloading = false;
-
-// TRUE means the current function file was found in a relative path
-// element.
-static bool fcn_file_from_relative_lookup = false;
-
-// Pointer to the primary user function or user script function.
-static octave_function *primary_fcn_ptr = 0;
-
-// Scope where we install all subfunctions and nested functions. Only
-// used while reading function files.
-static symbol_table::scope_id primary_fcn_scope;
-
 // List of autoloads (function -> file mapping).
 static std::map<std::string, std::string> autoload_map;
 
 // Forward declarations for some functions defined at the bottom of
 // the file.
 
-// Generic error messages.
-static void
-yyerror (const char *s);
-
-// Error mesages for mismatched end tokens.
-static void
-end_error (const char *type, token::end_tok_type ettype, int l, int c);
-
-// Check to see that end tokens are properly matched.
-static bool
-end_token_ok (token *tok, token::end_tok_type expected);
-
-// Maybe print a warning if an assignment expression is used as the
-// test in a logical expression.
-static void
-maybe_warn_assign_as_truth_value (tree_expression *expr);
-
-// Maybe print a warning about switch labels that aren't constants.
-static void
-maybe_warn_variable_switch_label (tree_expression *expr);
-
-// Finish building a range.
-static tree_expression *
-finish_colon_expression (tree_colon_expression *e);
-
-// Build a constant.
-static tree_constant *
-make_constant (int op, token *tok_val);
-
-// Build a function handle.
-static tree_fcn_handle *
-make_fcn_handle (token *tok_val);
-
-// Build an anonymous function handle.
-static tree_anon_fcn_handle *
-make_anon_fcn_handle (tree_parameter_list *param_list, tree_statement *stmt);
-
-// Build a binary expression.
-static tree_expression *
-make_binary_op (int op, tree_expression *op1, token *tok_val,
-                tree_expression *op2);
-
-// Build a boolean expression.
-static tree_expression *
-make_boolean_op (int op, tree_expression *op1, token *tok_val,
-                 tree_expression *op2);
-
-// Build a prefix expression.
-static tree_expression *
-make_prefix_op (int op, tree_expression *op1, token *tok_val);
-
-// Build a postfix expression.
-static tree_expression *
-make_postfix_op (int op, tree_expression *op1, token *tok_val);
-
-// Build an unwind-protect command.
-static tree_command *
-make_unwind_command (token *unwind_tok, tree_statement_list *body,
-                     tree_statement_list *cleanup, token *end_tok,
-                     octave_comment_list *lc, octave_comment_list *mc);
-
-// Build a try-catch command.
-static tree_command *
-make_try_command (token *try_tok, tree_statement_list *body,
-                  tree_statement_list *cleanup, token *end_tok,
-                  octave_comment_list *lc, octave_comment_list *mc);
-
-// Build a while command.
-static tree_command *
-make_while_command (token *while_tok, tree_expression *expr,
-                    tree_statement_list *body, token *end_tok,
-                    octave_comment_list *lc);
-
-// Build a do-until command.
-static tree_command *
-make_do_until_command (token *until_tok, tree_statement_list *body,
-                       tree_expression *expr, octave_comment_list *lc);
-
-// Build a for command.
-static tree_command *
-make_for_command (int tok_id, token *for_tok, tree_argument_list *lhs,
-                  tree_expression *expr, tree_expression *maxproc,
-                  tree_statement_list *body, token *end_tok,
-                  octave_comment_list *lc);
-
-// Build a break command.
-static tree_command *
-make_break_command (token *break_tok);
-
-// Build a continue command.
-static tree_command *
-make_continue_command (token *continue_tok);
-
-// Build a return command.
-static tree_command *
-make_return_command (token *return_tok);
-
-// Start an if command.
-static tree_if_command_list *
-start_if_command (tree_expression *expr, tree_statement_list *list);
-
-// Finish an if command.
-static tree_if_command *
-finish_if_command (token *if_tok, tree_if_command_list *list,
-                   token *end_tok, octave_comment_list *lc);
-
-// Build an elseif clause.
-static tree_if_clause *
-make_elseif_clause (token *elseif_tok, tree_expression *expr,
-                    tree_statement_list *list, octave_comment_list *lc);
-
-// Finish a switch command.
-static tree_switch_command *
-finish_switch_command (token *switch_tok, tree_expression *expr,
-                       tree_switch_case_list *list, token *end_tok,
-                       octave_comment_list *lc);
-
-// Build a switch case.
-static tree_switch_case *
-make_switch_case (token *case_tok, tree_expression *expr,
-                  tree_statement_list *list, octave_comment_list *lc);
-
-// Build an assignment to a variable.
-static tree_expression *
-make_assign_op (int op, tree_argument_list *lhs, token *eq_tok,
-                tree_expression *rhs);
-
-// Define a script.
-static void
-make_script (tree_statement_list *cmds, tree_statement *end_script);
-
-// Begin defining a function.
-static octave_user_function *
-start_function (tree_parameter_list *param_list, tree_statement_list *body,
-                tree_statement *end_function);
-
-// Create a no-op statement for end_function.
-static tree_statement *
-make_end (const std::string& type, int l, int c);
-
-// Do most of the work for defining a function.
-static octave_user_function *
-frob_function (const std::string& fname, octave_user_function *fcn);
-
-// Finish defining a function.
-static tree_function_def *
-finish_function (tree_parameter_list *ret_list,
-                 octave_user_function *fcn, octave_comment_list *lc);
-
-// Reset state after parsing function.
-static void
-recover_from_parsing_function (void);
-
-// Make an index expression.
-static tree_index_expression *
-make_index_expression (tree_expression *expr,
-                       tree_argument_list *args, char type);
-
-// Make an indirect reference expression.
-static tree_index_expression *
-make_indirect_ref (tree_expression *expr, const std::string&);
-
-// Make an indirect reference expression with dynamic field name.
-static tree_index_expression *
-make_indirect_ref (tree_expression *expr, tree_expression *field);
-
-// Make a declaration command.
-static tree_decl_command *
-make_decl_command (int tok, token *tok_val, tree_decl_init_list *lst);
-
-// Validate argument list forming a matrix or cell row.
-static tree_argument_list *
-validate_matrix_row (tree_argument_list *row);
-
-// Finish building a matrix list.
-static tree_expression *
-finish_matrix (tree_matrix *m);
-
-// Finish building a cell list.
-static tree_expression *
-finish_cell (tree_cell *c);
-
-// Maybe print a warning.  Duh.
-static void
-maybe_warn_missing_semi (tree_statement_list *);
-
-// Set the print flag for a statement based on the separator type.
-static tree_statement_list *
-set_stmt_print_flag (tree_statement_list *, char, bool);
-
-// Create a statement list.
-static tree_statement_list *make_statement_list (tree_statement *stmt);
-
-// Append a statement to an existing statement list.
-static tree_statement_list *
-append_statement_list (tree_statement_list *list, char sep,
-                       tree_statement *stmt, bool warn_missing_semi);
+static void yyerror (octave_base_parser& parser, const char *s);
 
 // Finish building a statement.
 template <class T>
@@ -363,20 +118,18 @@
 #define ABORT_PARSE \
   do \
     { \
-      global_command = 0; \
       yyerrok; \
-      if (! symtab_context.empty ()) \
-        { \
-          symbol_table::set_scope (symtab_context.top ()); \
-          symtab_context.pop (); \
-        } \
-      if (interactive || forced_interactive) \
+      if ((interactive || forced_interactive) \
+          && ! lexer.input_from_eval_string ()) \
         YYACCEPT; \
       else \
         YYABORT; \
     } \
   while (0)
 
+#define lexer parser.lexer
+#define scanner lexer.scanner
+
 %}
 
 // Bison declarations.
@@ -386,6 +139,20 @@
 
 %name-prefix="octave_"
 
+// We are using the pure parser interface and the reentrant lexer
+// interface but the Octave parser and lexer are NOT properly
+// reentrant because both still use many global variables.  It should be
+// safe to create a parser object and call it while anotehr parser
+// object is active (to parse a callback function while the main
+// interactive parser is waiting for input, for example) if you take
+// care to properly save and restore (typically with an unwind_protect
+// object) relevant global values before and after the nested call.
+
+%define api.pure
+%PUSH_PULL_DECL%
+%parse-param { octave_base_parser& parser }
+%lex-param { void *scanner }
+
 %union
 {
   // The type of the basic tokens returned by the lexer.
@@ -433,7 +200,7 @@
 %token <tok_val> EXPR_AND EXPR_OR EXPR_NOT
 %token <tok_val> EXPR_LT EXPR_LE EXPR_EQ EXPR_NE EXPR_GE EXPR_GT
 %token <tok_val> LEFTDIV EMUL EDIV ELEFTDIV EPLUS EMINUS
-%token <tok_val> QUOTE TRANSPOSE
+%token <tok_val> HERMITIAN TRANSPOSE
 %token <tok_val> PLUS_PLUS MINUS_MINUS POW EPOW
 %token <tok_val> NUM IMAG_NUM
 %token <tok_val> STRUCT_ELT
@@ -446,7 +213,7 @@
 %token <tok_val> BREAK CONTINUE FUNC_RET
 %token <tok_val> UNWIND CLEANUP
 %token <tok_val> TRY CATCH
-%token <tok_val> GLOBAL STATIC
+%token <tok_val> GLOBAL PERSISTENT
 %token <tok_val> FCN_HANDLE
 %token <tok_val> PROPERTIES METHODS EVENTS ENUMERATION
 %token <tok_val> METAQUERY
@@ -455,14 +222,13 @@
 
 // Other tokens.
 %token END_OF_INPUT LEXICAL_ERROR
-%token FCN SCRIPT_FILE FUNCTION_FILE CLASSDEF
+%token FCN INPUT_FILE CLASSDEF
 // %token VARARGIN VARARGOUT
-%token CLOSE_BRACE
 
 // Nonterminals we construct.
 %type <comment_type> stash_comment function_beg classdef_beg
 %type <comment_type> properties_beg methods_beg events_beg enum_beg
-%type <sep_type> sep_no_nl opt_sep_no_nl sep opt_sep
+%type <sep_type> sep_no_nl opt_sep_no_nl nl opt_nl sep opt_sep
 %type <tree_type> input
 %type <tree_constant_type> string constant magic_colon
 %type <tree_anon_fcn_handle_type> anon_fcn_handle
@@ -484,8 +250,7 @@
 %type <tree_parameter_list_type> superclasses opt_superclasses
 %type <tree_command_type> command select_command loop_command
 %type <tree_command_type> jump_command except_command function
-%type <tree_command_type> script_file classdef
-%type <tree_command_type> function_file function_list
+%type <tree_command_type> file classdef
 %type <tree_if_command_type> if_command
 %type <tree_if_clause_type> elseif_clause else_clause
 %type <tree_if_command_list_type> if_cmd_list1 if_cmd_list
@@ -527,7 +292,7 @@
 %left '-' '+' EPLUS EMINUS
 %left '*' '/' LEFTDIV EMUL EDIV ELEFTDIV
 %right UNARY EXPR_NOT
-%left POW EPOW QUOTE TRANSPOSE
+%left POW EPOW HERMITIAN TRANSPOSE
 %right PLUS_PLUS MINUS_MINUS
 %left '(' '.' '{'
 
@@ -542,12 +307,9 @@
 
 input           : input1
                   {
-                    global_command = $1;
-                    promptflag = 1;
+                    parser.stmt_list = $1;
                     YYACCEPT;
                   }
-                | function_file
-                  { YYACCEPT; }
                 | simple_list parse_error
                   { ABORT_PARSE; }
                 | parse_error
@@ -558,7 +320,7 @@
                   { $$ = 0; }
                 | END_OF_INPUT
                   {
-                    parser_end_of_input = 1;
+                    lexer.end_of_input = true;
                     $$ = 0;
                   }
                 | simple_list
@@ -570,13 +332,13 @@
                 ;
 
 simple_list     : simple_list1 opt_sep_no_nl
-                  { $$ = set_stmt_print_flag ($1, $2, false); }
+                  { $$ = parser.set_stmt_print_flag ($1, $2, false); }
                 ;
 
 simple_list1    : statement
-                  { $$ = make_statement_list ($1); }
+                  { $$ = parser.make_statement_list ($1); }
                 | simple_list1 sep_no_nl statement
-                  { $$ = append_statement_list ($1, $2, $3, false); }
+                  { $$ = parser.append_statement_list ($1, $2, $3, false); }
                 ;
 
 opt_list        : // empty
@@ -586,13 +348,13 @@
                 ;
 
 list            : list1 opt_sep
-                  { $$ = set_stmt_print_flag ($1, $2, true); }
+                  { $$ = parser.set_stmt_print_flag ($1, $2, true); }
                 ;
 
 list1           : statement
-                  { $$ = make_statement_list ($1); }
+                  { $$ = parser.make_statement_list ($1); }
                 | list1 sep statement
-                  { $$ = append_statement_list ($1, $2, $3, true); }
+                  { $$ = parser.append_statement_list ($1, $2, $3, true); }
                 ;
 
 statement       : expression
@@ -612,7 +374,11 @@
 // WHILE, etc.
 
 word_list_cmd   : identifier word_list
-                  { $$ = make_index_expression ($1, $2, '('); }
+                  {
+                    $$ = parser.make_index_expression ($1, $2, '(');
+                    if (! $$)
+                      ABORT_PARSE;
+                  }
                 ;
 
 word_list       : string
@@ -645,43 +411,27 @@
                 ;
 
 string          : DQ_STRING
-                  { $$ = make_constant (DQ_STRING, $1); }
+                  { $$ = parser.make_constant (DQ_STRING, $1); }
                 | SQ_STRING
-                  { $$ = make_constant (SQ_STRING, $1); }
+                  { $$ = parser.make_constant (SQ_STRING, $1); }
                 ;
 
 constant        : NUM
-                  { $$ = make_constant (NUM, $1); }
+                  { $$ = parser.make_constant (NUM, $1); }
                 | IMAG_NUM
-                  { $$ = make_constant (IMAG_NUM, $1); }
+                  { $$ = parser.make_constant (IMAG_NUM, $1); }
                 | string
                   { $$ = $1; }
                 ;
 
 matrix          : '[' ']'
-                  {
-                    $$ = new tree_constant (octave_null_matrix::instance);
-                    lexer_flags.looking_at_matrix_or_assign_lhs = false;
-                    lexer_flags.pending_local_variables.clear ();
-                  }
+                  { $$ = new tree_constant (octave_null_matrix::instance); }
                 | '[' ';' ']'
-                  {
-                    $$ = new tree_constant (octave_null_matrix::instance);
-                    lexer_flags.looking_at_matrix_or_assign_lhs = false;
-                    lexer_flags.pending_local_variables.clear ();
-                  }
+                  { $$ = new tree_constant (octave_null_matrix::instance); }
                 | '[' ',' ']'
-                  {
-                    $$ = new tree_constant (octave_null_matrix::instance);
-                    lexer_flags.looking_at_matrix_or_assign_lhs = false;
-                    lexer_flags.pending_local_variables.clear ();
-                  }
+                  { $$ = new tree_constant (octave_null_matrix::instance); }
                 | '[' matrix_rows ']'
-                  {
-                    $$ = finish_matrix ($2);
-                    lexer_flags.looking_at_matrix_or_assign_lhs = false;
-                    lexer_flags.pending_local_variables.clear ();
-                  }
+                  { $$ = parser.finish_matrix ($2); }
                 ;
 
 matrix_rows     : matrix_rows1
@@ -704,7 +454,7 @@
                 | '{' ';' '}'
                   { $$ = new tree_constant (octave_value (Cell ())); }
                 | '{' cell_rows '}'
-                  { $$ = finish_cell ($2); }
+                  { $$ = parser.finish_cell ($2); }
                 ;
 
 cell_rows       : cell_rows1
@@ -724,22 +474,22 @@
 
 cell_or_matrix_row
                 : arg_list
-                  { $$ = validate_matrix_row ($1); }
-                | arg_list ','  // Ignore trailing comma.
-                  { $$ = validate_matrix_row ($1); }
+                  { $$ = $1; }
+                | arg_list ','          // Ignore trailing comma.
+                  { $$ = $1; }
                 ;
 
 fcn_handle      : '@' FCN_HANDLE
                   {
-                    $$ = make_fcn_handle ($2);
-                    lexer_flags.looking_at_function_handle--;
+                    $$ = parser.make_fcn_handle ($2);
+                    lexer.looking_at_function_handle--;
                   }
                 ;
 
 anon_fcn_handle : '@' param_list statement
                   {
-                    lexer_flags.quote_is_transpose = false;
-                    $$ = make_anon_fcn_handle ($2, $3);
+                    $$ = parser.make_anon_fcn_handle ($2, $3);
+                    lexer.nesting_level.remove ();
                   }
                 ;
 
@@ -750,7 +500,10 @@
                 | fcn_handle
                   { $$ = $1; }
                 | matrix
-                  { $$ = $1; }
+                  {
+                    lexer.looking_at_matrix_or_assign_lhs = false;
+                    $$ = $1;
+                  }
                 | cell
                   { $$ = $1; }
                 | meta_identifier
@@ -798,69 +551,85 @@
                 ;
 
 indirect_ref_op : '.'
-                  { lexer_flags.looking_at_indirect_ref = true; }
+                  { lexer.looking_at_indirect_ref = true; }
                 ;
 
 oper_expr       : primary_expr
                   { $$ = $1; }
                 | oper_expr PLUS_PLUS
-                  { $$ = make_postfix_op (PLUS_PLUS, $1, $2); }
+                  { $$ = parser.make_postfix_op (PLUS_PLUS, $1, $2); }
                 | oper_expr MINUS_MINUS
-                  { $$ = make_postfix_op (MINUS_MINUS, $1, $2); }
+                  { $$ = parser.make_postfix_op (MINUS_MINUS, $1, $2); }
                 | oper_expr '(' ')'
-                  { $$ = make_index_expression ($1, 0, '('); }
+                  {
+                    $$ = parser.make_index_expression ($1, 0, '(');
+                    if (! $$)
+                      ABORT_PARSE;
+                  }
                 | oper_expr '(' arg_list ')'
-                  { $$ = make_index_expression ($1, $3, '('); }
+                  {
+                    $$ = parser.make_index_expression ($1, $3, '(');
+                    if (! $$)
+                      ABORT_PARSE;
+                  }
                 | oper_expr '{' '}'
-                  { $$ = make_index_expression ($1, 0, '{'); }
+                  {
+                    $$ = parser.make_index_expression ($1, 0, '{');
+                    if (! $$)
+                      ABORT_PARSE;
+                  }
                 | oper_expr '{' arg_list '}'
-                  { $$ = make_index_expression ($1, $3, '{'); }
-                | oper_expr QUOTE
-                  { $$ = make_postfix_op (QUOTE, $1, $2); }
+                  {
+                    $$ = parser.make_index_expression ($1, $3, '{');
+                    if (! $$)
+                      ABORT_PARSE;
+                  }
+                | oper_expr HERMITIAN
+                  { $$ = parser.make_postfix_op (HERMITIAN, $1, $2); }
                 | oper_expr TRANSPOSE
-                  { $$ = make_postfix_op (TRANSPOSE, $1, $2); }
+                  { $$ = parser.make_postfix_op (TRANSPOSE, $1, $2); }
                 | oper_expr indirect_ref_op STRUCT_ELT
-                  { $$ = make_indirect_ref ($1, $3->text ()); }
+                  { $$ = parser.make_indirect_ref ($1, $3->text ()); }
                 | oper_expr indirect_ref_op '(' expression ')'
-                  { $$ = make_indirect_ref ($1, $4); }
+                  { $$ = parser.make_indirect_ref ($1, $4); }
                 | PLUS_PLUS oper_expr %prec UNARY
-                  { $$ = make_prefix_op (PLUS_PLUS, $2, $1); }
+                  { $$ = parser.make_prefix_op (PLUS_PLUS, $2, $1); }
                 | MINUS_MINUS oper_expr %prec UNARY
-                  { $$ = make_prefix_op (MINUS_MINUS, $2, $1); }
+                  { $$ = parser.make_prefix_op (MINUS_MINUS, $2, $1); }
                 | EXPR_NOT oper_expr %prec UNARY
-                  { $$ = make_prefix_op (EXPR_NOT, $2, $1); }
+                  { $$ = parser.make_prefix_op (EXPR_NOT, $2, $1); }
                 | '+' oper_expr %prec UNARY
-                  { $$ = make_prefix_op ('+', $2, $1); }
+                  { $$ = parser.make_prefix_op ('+', $2, $1); }
                 | '-' oper_expr %prec UNARY
-                  { $$ = make_prefix_op ('-', $2, $1); }
+                  { $$ = parser.make_prefix_op ('-', $2, $1); }
                 | oper_expr POW oper_expr
-                  { $$ = make_binary_op (POW, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (POW, $1, $2, $3); }
                 | oper_expr EPOW oper_expr
-                  { $$ = make_binary_op (EPOW, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (EPOW, $1, $2, $3); }
                 | oper_expr '+' oper_expr
-                  { $$ = make_binary_op ('+', $1, $2, $3); }
+                  { $$ = parser.make_binary_op ('+', $1, $2, $3); }
                 | oper_expr '-' oper_expr
-                  { $$ = make_binary_op ('-', $1, $2, $3); }
+                  { $$ = parser.make_binary_op ('-', $1, $2, $3); }
                 | oper_expr '*' oper_expr
-                  { $$ = make_binary_op ('*', $1, $2, $3); }
+                  { $$ = parser.make_binary_op ('*', $1, $2, $3); }
                 | oper_expr '/' oper_expr
-                  { $$ = make_binary_op ('/', $1, $2, $3); }
+                  { $$ = parser.make_binary_op ('/', $1, $2, $3); }
                 | oper_expr EPLUS oper_expr
-                  { $$ = make_binary_op ('+', $1, $2, $3); }
+                  { $$ = parser.make_binary_op ('+', $1, $2, $3); }
                 | oper_expr EMINUS oper_expr
-                  { $$ = make_binary_op ('-', $1, $2, $3); }
+                  { $$ = parser.make_binary_op ('-', $1, $2, $3); }
                 | oper_expr EMUL oper_expr
-                  { $$ = make_binary_op (EMUL, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (EMUL, $1, $2, $3); }
                 | oper_expr EDIV oper_expr
-                  { $$ = make_binary_op (EDIV, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (EDIV, $1, $2, $3); }
                 | oper_expr LEFTDIV oper_expr
-                  { $$ = make_binary_op (LEFTDIV, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (LEFTDIV, $1, $2, $3); }
                 | oper_expr ELEFTDIV oper_expr
-                  { $$ = make_binary_op (ELEFTDIV, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (ELEFTDIV, $1, $2, $3); }
                 ;
 
 colon_expr      : colon_expr1
-                  { $$ = finish_colon_expression ($1); }
+                  { $$ = parser.finish_colon_expression ($1); }
                 ;
 
 colon_expr1     : oper_expr
@@ -875,87 +644,92 @@
 simple_expr     : colon_expr
                   { $$ = $1; }
                 | simple_expr LSHIFT simple_expr
-                  { $$ = make_binary_op (LSHIFT, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (LSHIFT, $1, $2, $3); }
                 | simple_expr RSHIFT simple_expr
-                  { $$ = make_binary_op (RSHIFT, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (RSHIFT, $1, $2, $3); }
                 | simple_expr EXPR_LT simple_expr
-                  { $$ = make_binary_op (EXPR_LT, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (EXPR_LT, $1, $2, $3); }
                 | simple_expr EXPR_LE simple_expr
-                  { $$ = make_binary_op (EXPR_LE, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (EXPR_LE, $1, $2, $3); }
                 | simple_expr EXPR_EQ simple_expr
-                  { $$ = make_binary_op (EXPR_EQ, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (EXPR_EQ, $1, $2, $3); }
                 | simple_expr EXPR_GE simple_expr
-                  { $$ = make_binary_op (EXPR_GE, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (EXPR_GE, $1, $2, $3); }
                 | simple_expr EXPR_GT simple_expr
-                  { $$ = make_binary_op (EXPR_GT, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (EXPR_GT, $1, $2, $3); }
                 | simple_expr EXPR_NE simple_expr
-                  { $$ = make_binary_op (EXPR_NE, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (EXPR_NE, $1, $2, $3); }
                 | simple_expr EXPR_AND simple_expr
-                  { $$ = make_binary_op (EXPR_AND, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (EXPR_AND, $1, $2, $3); }
                 | simple_expr EXPR_OR simple_expr
-                  { $$ = make_binary_op (EXPR_OR, $1, $2, $3); }
+                  { $$ = parser.make_binary_op (EXPR_OR, $1, $2, $3); }
                 | simple_expr EXPR_AND_AND simple_expr
-                  { $$ = make_boolean_op (EXPR_AND_AND, $1, $2, $3); }
+                  { $$ = parser.make_boolean_op (EXPR_AND_AND, $1, $2, $3); }
                 | simple_expr EXPR_OR_OR simple_expr
-                  { $$ = make_boolean_op (EXPR_OR_OR, $1, $2, $3); }
+                  { $$ = parser.make_boolean_op (EXPR_OR_OR, $1, $2, $3); }
                 ;
 
-// Arrange for the lexer to return CLOSE_BRACE for ']' by looking ahead
-// one token for an assignment op.
-
 assign_lhs      : simple_expr
                   {
-                    $$ = new tree_argument_list ($1);
-                    $$->mark_as_simple_assign_lhs ();
-                  }
-                | '[' arg_list CLOSE_BRACE
-                  {
-                    $$ = $2;
-                    lexer_flags.looking_at_matrix_or_assign_lhs = false;
-                    for (std::set<std::string>::const_iterator p = lexer_flags.pending_local_variables.begin ();
-                         p != lexer_flags.pending_local_variables.end ();
-                         p++)
+                    $$ = parser.validate_matrix_for_assignment ($1);
+
+                    if ($$)
+                      { lexer.looking_at_matrix_or_assign_lhs = false; }
+                    else
                       {
-                        symbol_table::force_variable (*p);
+                        // validate_matrix_for_assignment deleted $1.
+                        ABORT_PARSE;
                       }
-                    lexer_flags.pending_local_variables.clear ();
                   }
                 ;
 
 assign_expr     : assign_lhs '=' expression
-                  { $$ = make_assign_op ('=', $1, $2, $3); }
+                  { $$ = parser.make_assign_op ('=', $1, $2, $3); }
                 | assign_lhs ADD_EQ expression
-                  { $$ = make_assign_op (ADD_EQ, $1, $2, $3); }
+                  { $$ = parser.make_assign_op (ADD_EQ, $1, $2, $3); }
                 | assign_lhs SUB_EQ expression
-                  { $$ = make_assign_op (SUB_EQ, $1, $2, $3); }
+                  { $$ = parser.make_assign_op (SUB_EQ, $1, $2, $3); }
                 | assign_lhs MUL_EQ expression
-                  { $$ = make_assign_op (MUL_EQ, $1, $2, $3); }
+                  { $$ = parser.make_assign_op (MUL_EQ, $1, $2, $3); }
                 | assign_lhs DIV_EQ expression
-                  { $$ = make_assign_op (DIV_EQ, $1, $2, $3); }
+                  { $$ = parser.make_assign_op (DIV_EQ, $1, $2, $3); }
                 | assign_lhs LEFTDIV_EQ expression
-                  { $$ = make_assign_op (LEFTDIV_EQ, $1, $2, $3); }
+                  { $$ = parser.make_assign_op (LEFTDIV_EQ, $1, $2, $3); }
                 | assign_lhs POW_EQ expression
-                  { $$ = make_assign_op (POW_EQ, $1, $2, $3); }
+                  { $$ = parser.make_assign_op (POW_EQ, $1, $2, $3); }
                 | assign_lhs LSHIFT_EQ expression
-                  { $$ = make_assign_op (LSHIFT_EQ, $1, $2, $3); }
+                  { $$ = parser.make_assign_op (LSHIFT_EQ, $1, $2, $3); }
                 | assign_lhs RSHIFT_EQ expression
-                  { $$ = make_assign_op (RSHIFT_EQ, $1, $2, $3); }
+                  { $$ = parser.make_assign_op (RSHIFT_EQ, $1, $2, $3); }
                 | assign_lhs EMUL_EQ expression
-                  { $$ = make_assign_op (EMUL_EQ, $1, $2, $3); }
+                  { $$ = parser.make_assign_op (EMUL_EQ, $1, $2, $3); }
                 | assign_lhs EDIV_EQ expression
-                  { $$ = make_assign_op (EDIV_EQ, $1, $2, $3); }
+                  { $$ = parser.make_assign_op (EDIV_EQ, $1, $2, $3); }
                 | assign_lhs ELEFTDIV_EQ expression
-                  { $$ = make_assign_op (ELEFTDIV_EQ, $1, $2, $3); }
+                  { $$ = parser.make_assign_op (ELEFTDIV_EQ, $1, $2, $3); }
                 | assign_lhs EPOW_EQ expression
-                  { $$ = make_assign_op (EPOW_EQ, $1, $2, $3); }
+                  { $$ = parser.make_assign_op (EPOW_EQ, $1, $2, $3); }
                 | assign_lhs AND_EQ expression
-                  { $$ = make_assign_op (AND_EQ, $1, $2, $3); }
+                  { $$ = parser.make_assign_op (AND_EQ, $1, $2, $3); }
                 | assign_lhs OR_EQ expression
-                  { $$ = make_assign_op (OR_EQ, $1, $2, $3); }
+                  { $$ = parser.make_assign_op (OR_EQ, $1, $2, $3); }
                 ;
 
 expression      : simple_expr
-                  { $$ = $1; }
+                  {
+                    if ($1 && ($1->is_matrix () || $1->is_cell ()))
+                      {
+                        if (parser.validate_array_list ($1))
+                          $$ = $1;
+                        else
+                          {
+                            delete $1;
+                            ABORT_PARSE;
+                          }
+                      }
+                    else
+                      $$ = $1;
+                  }
                 | assign_expr
                   { $$ = $1; }
                 | anon_fcn_handle
@@ -978,7 +752,7 @@
                   { $$ = $1; }
                 | function
                   { $$ = $1; }
-                | script_file
+                | file
                   { $$ = $1; }
                 | classdef
                   { $$ = $1; }
@@ -988,19 +762,15 @@
 // Declaration statemnts
 // =====================
 
-parsing_decl_list
-                : // empty
-                  { lexer_flags.looking_at_decl_list = true; }
-
-declaration     : GLOBAL parsing_decl_list decl1
+declaration     : GLOBAL decl1
                   {
-                    $$ = make_decl_command (GLOBAL, $1, $3);
-                    lexer_flags.looking_at_decl_list = false;
+                    $$ = parser.make_decl_command (GLOBAL, $1, $2);
+                    lexer.looking_at_decl_list = false;
                   }
-                | STATIC parsing_decl_list decl1
+                | PERSISTENT decl1
                   {
-                    $$ = make_decl_command (STATIC, $1, $3);
-                    lexer_flags.looking_at_decl_list = false;
+                    $$ = parser.make_decl_command (PERSISTENT, $1, $2);
+                    lexer.looking_at_decl_list = false;
                   }
                 ;
 
@@ -1014,13 +784,13 @@
                 ;
 
 decl_param_init : // empty
-                { lexer_flags.looking_at_initializer_expression = true; }
+                { lexer.looking_at_initializer_expression = true; }
 
 decl2           : identifier
                   { $$ = new tree_decl_elt ($1); }
                 | identifier '=' decl_param_init expression
                   {
-                    lexer_flags.looking_at_initializer_expression = false;
+                    lexer.looking_at_initializer_expression = false;
                     $$ = new tree_decl_elt ($1, $4);
                   }
                 | magic_tilde
@@ -1045,7 +815,7 @@
 
 if_command      : IF stash_comment if_cmd_list END
                   {
-                    if (! ($$ = finish_if_command ($1, $3, $4, $2)))
+                    if (! ($$ = parser.finish_if_command ($1, $3, $4, $2)))
                       ABORT_PARSE;
                   }
                 ;
@@ -1061,9 +831,9 @@
 
 if_cmd_list1    : expression opt_sep opt_list
                   {
-                    $1->mark_braindead_shortcircuit (curr_fcn_file_full_name);
-
-                    $$ = start_if_command ($1, $3);
+                    $1->mark_braindead_shortcircuit (lexer.fcn_file_full_name);
+
+                    $$ = parser.start_if_command ($1, $3);
                   }
                 | if_cmd_list1 elseif_clause
                   {
@@ -1074,9 +844,9 @@
 
 elseif_clause   : ELSEIF stash_comment opt_sep expression opt_sep opt_list
                   {
-                    $4->mark_braindead_shortcircuit (curr_fcn_file_full_name);
-
-                    $$ = make_elseif_clause ($1, $4, $6, $2);
+                    $4->mark_braindead_shortcircuit (lexer.fcn_file_full_name);
+
+                    $$ = parser.make_elseif_clause ($1, $4, $6, $2);
                   }
                 ;
 
@@ -1090,7 +860,7 @@
 
 switch_command  : SWITCH stash_comment expression opt_sep case_list END
                   {
-                    if (! ($$ = finish_switch_command ($1, $3, $5, $6, $2)))
+                    if (! ($$ = parser.finish_switch_command ($1, $3, $5, $6, $2)))
                       ABORT_PARSE;
                   }
                 ;
@@ -1118,7 +888,7 @@
                 ;
 
 switch_case     : CASE stash_comment opt_sep expression opt_sep opt_list
-                  { $$ = make_switch_case ($1, $4, $6, $2); }
+                  { $$ = parser.make_switch_case ($1, $4, $6, $2); }
                 ;
 
 default_case    : OTHERWISE stash_comment opt_sep opt_list
@@ -1133,37 +903,37 @@
 
 loop_command    : WHILE stash_comment expression opt_sep opt_list END
                   {
-                    $3->mark_braindead_shortcircuit (curr_fcn_file_full_name);
-
-                    if (! ($$ = make_while_command ($1, $3, $5, $6, $2)))
+                    $3->mark_braindead_shortcircuit (lexer.fcn_file_full_name);
+
+                    if (! ($$ = parser.make_while_command ($1, $3, $5, $6, $2)))
                       ABORT_PARSE;
                   }
                 | DO stash_comment opt_sep opt_list UNTIL expression
                   {
-                    if (! ($$ = make_do_until_command ($5, $4, $6, $2)))
+                    if (! ($$ = parser.make_do_until_command ($5, $4, $6, $2)))
                       ABORT_PARSE;
                   }
                 | FOR stash_comment assign_lhs '=' expression opt_sep opt_list END
                   {
-                    if (! ($$ = make_for_command (FOR, $1, $3, $5, 0,
+                    if (! ($$ = parser.make_for_command (FOR, $1, $3, $5, 0,
                                                   $7, $8, $2)))
                       ABORT_PARSE;
                   }
                 | FOR stash_comment '(' assign_lhs '=' expression ')' opt_sep opt_list END
                   {
-                    if (! ($$ = make_for_command (FOR, $1, $4, $6, 0,
+                    if (! ($$ = parser.make_for_command (FOR, $1, $4, $6, 0,
                                                   $9, $10, $2)))
                       ABORT_PARSE;
                   }
                 | PARFOR stash_comment assign_lhs '=' expression opt_sep opt_list END
                   {
-                    if (! ($$ = make_for_command (PARFOR, $1, $3, $5,
+                    if (! ($$ = parser.make_for_command (PARFOR, $1, $3, $5,
                                                   0, $7, $8, $2)))
                       ABORT_PARSE;
                   }
                 | PARFOR stash_comment '(' assign_lhs '=' expression ',' expression ')' opt_sep opt_list END
                   {
-                    if (! ($$ = make_for_command (PARFOR, $1, $4, $6,
+                    if (! ($$ = parser.make_for_command (PARFOR, $1, $4, $6,
                                                   $8, $11, $12, $2)))
                       ABORT_PARSE;
                   }
@@ -1175,17 +945,17 @@
 
 jump_command    : BREAK
                   {
-                    if (! ($$ = make_break_command ($1)))
+                    if (! ($$ = parser.make_break_command ($1)))
                       ABORT_PARSE;
                   }
                 | CONTINUE
                   {
-                    if (! ($$ = make_continue_command ($1)))
+                    if (! ($$ = parser.make_continue_command ($1)))
                       ABORT_PARSE;
                   }
                 | FUNC_RET
                   {
-                    if (! ($$ = make_return_command ($1)))
+                    if (! ($$ = parser.make_return_command ($1)))
                       ABORT_PARSE;
                   }
                 ;
@@ -1197,18 +967,18 @@
 except_command  : UNWIND stash_comment opt_sep opt_list CLEANUP
                   stash_comment opt_sep opt_list END
                   {
-                    if (! ($$ = make_unwind_command ($1, $4, $8, $9, $2, $6)))
+                    if (! ($$ = parser.make_unwind_command ($1, $4, $8, $9, $2, $6)))
                       ABORT_PARSE;
                   }
                 | TRY stash_comment opt_sep opt_list CATCH
                   stash_comment opt_sep opt_list END
                   {
-                    if (! ($$ = make_try_command ($1, $4, $8, $9, $2, $6)))
+                    if (! ($$ = parser.make_try_command ($1, $4, $8, $9, $2, $6)))
                       ABORT_PARSE;
                   }
                 | TRY stash_comment opt_sep opt_list END
                   {
-                    if (! ($$ = make_try_command ($1, $4, 0, $5, $2, 0)))
+                    if (! ($$ = parser.make_try_command ($1, $4, 0, $5, $2, 0)))
                       ABORT_PARSE;
                   }
                 ;
@@ -1219,20 +989,25 @@
 
 push_fcn_symtab : // empty
                   {
-                    current_function_depth++;
-
-                    if (max_function_depth < current_function_depth)
-                      max_function_depth = current_function_depth;
-
-                    symtab_context.push (symbol_table::current_scope ());
-                    symbol_table::set_scope (symbol_table::alloc_scope ());
-
-                    if (! reading_script_file && current_function_depth == 1
-                        && ! parsing_subfunctions)
-                      primary_fcn_scope = symbol_table::current_scope ();
-
-                    if (reading_script_file && current_function_depth > 1)
-                      yyerror ("nested functions not implemented in this context");
+                    parser.curr_fcn_depth++;
+
+                    if (parser.max_fcn_depth < parser.curr_fcn_depth)
+                      parser.max_fcn_depth = parser.curr_fcn_depth;
+
+                    lexer.symtab_context.push (symbol_table::alloc_scope ());
+
+                    parser.function_scopes.push_back
+                     (lexer.symtab_context.curr_scope ());
+
+                    if (! lexer.reading_script_file
+                        && parser.curr_fcn_depth == 1
+                        && ! parser.parsing_subfunctions)
+                      parser.primary_fcn_scope
+                        = lexer.symtab_context.curr_scope ();
+
+                    if (lexer.reading_script_file
+                        && parser.curr_fcn_depth > 1)
+                      parser.bison_error ("nested functions not implemented in this context");
                   }
                 ;
 
@@ -1242,33 +1017,34 @@
 
 param_list_beg  : '('
                   {
-                    lexer_flags.looking_at_parameter_list = true;
-
-                    if (lexer_flags.looking_at_function_handle)
+                    lexer.looking_at_parameter_list = true;
+
+                    if (lexer.looking_at_function_handle)
                       {
-                        symtab_context.push (symbol_table::current_scope ());
-                        symbol_table::set_scope (symbol_table::alloc_scope ());
-                        lexer_flags.looking_at_function_handle--;
-                        lexer_flags.looking_at_anon_fcn_args = true;
+                        lexer.symtab_context.push (symbol_table::alloc_scope ());
+                        lexer.looking_at_function_handle--;
+                        lexer.looking_at_anon_fcn_args = true;
                       }
                   }
                 ;
 
 param_list_end  : ')'
                   {
-                    lexer_flags.looking_at_parameter_list = false;
-                    lexer_flags.looking_for_object_index = false;
+                    lexer.looking_at_parameter_list = false;
+                    lexer.looking_for_object_index = false;
                   }
                 ;
 
 param_list      : param_list_beg param_list1 param_list_end
                   {
-                    lexer_flags.quote_is_transpose = false;
+                    if ($2)
+                      lexer.mark_as_variables ($2->variable_names ());
+
                     $$ = $2;
                   }
                 | param_list_beg error
                   {
-                    yyerror ("invalid parameter list");
+                    parser.bison_error ("invalid parameter list");
                     $$ = 0;
                     ABORT_PARSE;
                   }
@@ -1280,7 +1056,10 @@
                   {
                     $1->mark_as_formal_parameters ();
                     if ($1->validate (tree_parameter_list::in))
-                      $$ = $1;
+                      {
+                        lexer.mark_as_variables ($1->variable_names ());
+                        $$ = $1;
+                      }
                     else
                       ABORT_PARSE;
                   }
@@ -1301,12 +1080,12 @@
 
 return_list     : '[' ']'
                   {
-                    lexer_flags.looking_at_return_list = false;
+                    lexer.looking_at_return_list = false;
                     $$ = new tree_parameter_list ();
                   }
                 | return_list1
                   {
-                    lexer_flags.looking_at_return_list = false;
+                    lexer.looking_at_return_list = false;
                     if ($1->validate (tree_parameter_list::out))
                       $$ = $1;
                     else
@@ -1314,7 +1093,7 @@
                   }
                 | '[' return_list1 ']'
                   {
-                    lexer_flags.looking_at_return_list = false;
+                    lexer.looking_at_return_list = false;
                     if ($2->validate (tree_parameter_list::out))
                       $$ = $2;
                     else
@@ -1331,34 +1110,26 @@
                   }
                 ;
 
-// ===========
-// Script file
-// ===========
-
-script_file     : SCRIPT_FILE opt_list END_OF_INPUT
+// =======================
+// Script or function file
+// =======================
+
+file            : INPUT_FILE opt_nl opt_list END_OF_INPUT
                   {
-                    tree_statement *end_of_script
-                      = make_end ("endscript", input_line_number,
-                                  current_input_column);
-
-                    make_script ($2, end_of_script);
+                    if (! lexer.reading_fcn_file)
+                      {
+                        tree_statement *end_of_script
+                          = parser.make_end ("endscript",
+                                                  lexer.input_line_number,
+                                                  lexer.current_input_column);
+
+                        parser.make_script ($3, end_of_script);
+                      }
 
                     $$ = 0;
                   }
                 ;
 
-// =============
-// Function file
-// =============
-
-function_file   : FUNCTION_FILE function_list opt_sep END_OF_INPUT
-                  { $$ = 0; }
-                ;
-
-function_list   : function
-                | function_list sep function
-                ;
-
 // ===================
 // Function definition
 // ===================
@@ -1366,21 +1137,21 @@
 function_beg    : push_fcn_symtab FCN stash_comment
                   {
                     $$ = $3;
-
-                    if (reading_classdef_file || lexer_flags.parsing_classdef)
-                      lexer_flags.maybe_classdef_get_set_method = true;
+                    if (lexer.reading_classdef_file
+                        || lexer.parsing_classdef)
+                      lexer.maybe_classdef_get_set_method = true;
                   }
                 ;
 
 function        : function_beg function1
                   {
-                    $$ = finish_function (0, $2, $1);
-                    recover_from_parsing_function ();
+                    $$ = parser.finish_function (0, $2, $1);
+                    parser.recover_from_parsing_function ();
                   }
                 | function_beg return_list '=' function1
                   {
-                    $$ = finish_function ($2, $4, $1);
-                    recover_from_parsing_function ();
+                    $$ = parser.finish_function ($2, $4, $1);
+                    parser.recover_from_parsing_function ();
                   }
                 ;
 
@@ -1388,19 +1159,21 @@
                   {
                     std::string id_name = $1->name ();
 
-                    lexer_flags.parsed_function_name.top () = true;
-                    lexer_flags.maybe_classdef_get_set_method = false;
+                    lexer.parsed_function_name.top () = true;
+                    lexer.maybe_classdef_get_set_method = false;
 
                     $$ = $1;
                   }
                 | GET '.' identifier
                   {
-                    lexer_flags.maybe_classdef_get_set_method = false;
+                    lexer.parsed_function_name.top () = true;
+                    lexer.maybe_classdef_get_set_method = false;
                     $$ = $3;
                   }
                 | SET '.' identifier
                   {
-                    lexer_flags.maybe_classdef_get_set_method = false;
+                    lexer.parsed_function_name.top () = true;
+                    lexer.maybe_classdef_get_set_method = false;
                     $$ = $3;
                   }
                 ;
@@ -1411,57 +1184,58 @@
 
                     delete $1;
 
-                    if (! ($$ = frob_function (fname, $2)))
+                    if (! ($$ = parser.frob_function (fname, $2)))
                       ABORT_PARSE;
                   }
                 ;
 
 function2       : param_list opt_sep opt_list function_end
-                  { $$ = start_function ($1, $3, $4); }
+                  { $$ = parser.start_function ($1, $3, $4); }
                 | opt_sep opt_list function_end
-                  { $$ = start_function (0, $2, $3); }
+                  { $$ = parser.start_function (0, $2, $3); }
                 ;
 
 function_end    : END
                   {
-                    endfunction_found = true;
-                    if (end_token_ok ($1, token::function_end))
-                      $$ = make_end ("endfunction", $1->line (), $1->column ());
+                    parser.endfunction_found = true;
+                    if (parser.end_token_ok ($1, token::function_end))
+                      $$ = parser.make_end ("endfunction", $1->line (), $1->column ());
                     else
                       ABORT_PARSE;
                   }
                 | END_OF_INPUT
                   {
 // A lot of tests are based on the assumption that this is OK
-//                  if (reading_script_file)
+//                  if (lexer.reading_script_file)
 //                    {
-//                      yyerror ("function body open at end of script");
+//                      parser.bison_error ("function body open at end of script");
 //                      YYABORT;
 //                    }
 
-                    if (endfunction_found)
+                    if (parser.endfunction_found)
                       {
-                        yyerror ("inconsistent function endings -- "
+                        parser.bison_error ("inconsistent function endings -- "
                                  "if one function is explicitly ended, "
                                  "so must all the others");
                         YYABORT;
                       }
 
-                    if (! (reading_fcn_file || reading_script_file
-                           || get_input_from_eval_string))
+                    if (! (lexer.reading_fcn_file || lexer.reading_script_file
+                           || lexer.input_from_eval_string ()))
                       {
-                        yyerror ("function body open at end of input");
+                        parser.bison_error ("function body open at end of input");
                         YYABORT;
                       }
 
-                    if (reading_classdef_file)
+                    if (lexer.reading_classdef_file)
                       {
-                        yyerror ("classdef body open at end of input");
+                        parser.bison_error ("classdef body open at end of input");
                         YYABORT;
                       }
 
-                    $$ = make_end ("endfunction", input_line_number,
-                                   current_input_column);
+                    $$ = parser.make_end ("endfunction",
+                                                lexer.input_line_number,
+                                                lexer.current_input_column);
                   }
                 ;
 
@@ -1472,16 +1246,16 @@
 classdef_beg    : CLASSDEF stash_comment
                   {
                     $$ = 0;
-                    lexer_flags.parsing_classdef = true;
+                    lexer.parsing_classdef = true;
                   }
                 ;
 
 classdef_end    : END
                   {
-                    lexer_flags.parsing_classdef = false;
-
-                    if (end_token_ok ($1, token::classdef_end))
-                      $$ = make_end ("endclassdef", $1->line (), $1->column ());
+                    lexer.parsing_classdef = false;
+
+                    if (parser.end_token_ok ($1, token::classdef_end))
+                      $$ = parser.make_end ("endclassdef", $1->line (), $1->column ());
                     else
                       ABORT_PARSE;
                   }
@@ -1631,7 +1405,7 @@
                 ;
 
 parse_error     : LEXICAL_ERROR
-                  { yyerror ("parse error"); }
+                  { parser.bison_error ("parse error"); }
                 | error
                 ;
 
@@ -1651,6 +1425,18 @@
                   { $$ = $1; }
                 ;
 
+opt_nl          : // empty
+                  { $$ = 0; }
+                | nl
+                  { $$ = $1; }
+                ;
+
+nl              : '\n'
+                  { $$ = '\n'; }
+                | nl '\n'
+                  { $$ = $1; }
+                ;
+
 sep             : ','
                   { $$ = ','; }
                 | ';'
@@ -1675,55 +1461,51 @@
 
 // Generic error messages.
 
+#undef lexer
+
 static void
-yyerror (const char *s)
+yyerror (octave_base_parser& parser, const char *s)
+{
+  parser.bison_error (s);
+}
+
+octave_base_parser::~octave_base_parser (void)
+{
+  delete stmt_list;
+
+  delete &lexer;
+}
+
+void octave_base_parser::init (void)
 {
-  int err_col = current_input_column - 1;
-
-  std::ostringstream output_buf;
-
-  if (reading_fcn_file || reading_script_file || reading_classdef_file)
-    output_buf << "parse error near line " << input_line_number
-               << " of file " << curr_fcn_file_full_name;
-  else
-    output_buf << "parse error:";
-
-  if (s && strcmp (s, "parse error") != 0)
-    output_buf << "\n\n  " << s;
-
-  output_buf << "\n\n";
-
-  if (! current_input_line.empty ())
-    {
-      size_t len = current_input_line.length ();
-
-      if (current_input_line[len-1] == '\n')
-        current_input_line.resize (len-1);
-
-      // Print the line, maybe with a pointer near the error token.
-
-      output_buf << ">>> " << current_input_line << "\n";
-
-      if (err_col == 0)
-        err_col = len;
-
-      for (int i = 0; i < err_col + 3; i++)
-        output_buf << " ";
-
-      output_buf << "^";
-    }
-
-  output_buf << "\n";
-
-  std::string msg = output_buf.str ();
-
-  parse_error ("%s", msg.c_str ());
+  LEXER = &lexer;
+}
+
+void
+octave_base_parser::reset (void)
+{
+  endfunction_found = false;
+  autoloading = false;
+  fcn_file_from_relative_lookup = false;
+  parsing_subfunctions = false;
+  max_fcn_depth = 0;
+  curr_fcn_depth = 0;
+  primary_fcn_scope = -1;
+  curr_class_name = "";
+  function_scopes.clear ();
+  primary_fcn_ptr  = 0;
+
+  delete stmt_list;
+  stmt_list = 0;
+
+  lexer.reset ();
 }
 
 // Error mesages for mismatched end tokens.
 
-static void
-end_error (const char *type, token::end_tok_type ettype, int l, int c)
+void
+octave_base_parser::end_error (const char *type, token::end_tok_type ettype,
+                               int l, int c)
 {
   static const char *fmt
     = "'%s' command matched by '%s' near line %d column %d";
@@ -1774,8 +1556,8 @@
 
 // Check to see that end tokens are properly matched.
 
-static bool
-end_token_ok (token *tok, token::end_tok_type expected)
+bool
+octave_base_parser::end_token_ok (token *tok, token::end_tok_type expected)
 {
   bool retval = true;
 
@@ -1785,7 +1567,7 @@
     {
       retval = false;
 
-      yyerror ("parse error");
+      bison_error ("parse error");
 
       int l = tok->line ();
       int c = tok->column ();
@@ -1844,13 +1626,13 @@
 // Maybe print a warning if an assignment expression is used as the
 // test in a logical expression.
 
-static void
-maybe_warn_assign_as_truth_value (tree_expression *expr)
+void
+octave_base_parser::maybe_warn_assign_as_truth_value (tree_expression *expr)
 {
   if (expr->is_assignment_expression ()
       && expr->paren_count () < 2)
     {
-      if (curr_fcn_file_full_name.empty ())
+      if (lexer.fcn_file_full_name.empty ())
         warning_with_id
           ("Octave:assign-as-truth-value",
            "suggest parenthesis around assignment used as truth value");
@@ -1858,25 +1640,25 @@
         warning_with_id
           ("Octave:assign-as-truth-value",
            "suggest parenthesis around assignment used as truth value near line %d, column %d in file '%s'",
-           expr->line (), expr->column (), curr_fcn_file_full_name.c_str ());
+           expr->line (), expr->column (), lexer.fcn_file_full_name.c_str ());
     }
 }
 
 // Maybe print a warning about switch labels that aren't constants.
 
-static void
-maybe_warn_variable_switch_label (tree_expression *expr)
+void
+octave_base_parser::maybe_warn_variable_switch_label (tree_expression *expr)
 {
   if (! expr->is_constant ())
     {
-      if (curr_fcn_file_full_name.empty ())
+      if (lexer.fcn_file_full_name.empty ())
         warning_with_id ("Octave:variable-switch-label",
                          "variable switch label");
       else
         warning_with_id
           ("Octave:variable-switch-label",
            "variable switch label near line %d, column %d in file '%s'",
-           expr->line (), expr->column (), curr_fcn_file_full_name.c_str ());
+           expr->line (), expr->column (), lexer.fcn_file_full_name.c_str ());
     }
 }
 
@@ -1971,8 +1753,8 @@
 
 // Finish building a range.
 
-static tree_expression *
-finish_colon_expression (tree_colon_expression *e)
+tree_expression *
+octave_base_parser::finish_colon_expression (tree_colon_expression *e)
 {
   tree_expression *retval = e;
 
@@ -2035,8 +1817,8 @@
 
 // Make a constant.
 
-static tree_constant *
-make_constant (int op, token *tok_val)
+tree_constant *
+octave_base_parser::make_constant (int op, token *tok_val)
 {
   int l = tok_val->line ();
   int c = tok_val->column ();
@@ -2098,8 +1880,8 @@
 
 // Make a function handle.
 
-static tree_fcn_handle *
-make_fcn_handle (token *tok_val)
+tree_fcn_handle *
+octave_base_parser::make_fcn_handle (token *tok_val)
 {
   int l = tok_val->line ();
   int c = tok_val->column ();
@@ -2111,23 +1893,22 @@
 
 // Make an anonymous function handle.
 
-static tree_anon_fcn_handle *
-make_anon_fcn_handle (tree_parameter_list *param_list, tree_statement *stmt)
+tree_anon_fcn_handle *
+octave_base_parser::make_anon_fcn_handle (tree_parameter_list *param_list,
+                                          tree_statement *stmt)
 {
   // FIXME -- need to get these from the location of the @ symbol.
-  int l = input_line_number;
-  int c = current_input_column;
+  int l = lexer.input_line_number;
+  int c = lexer.current_input_column;
 
   tree_parameter_list *ret_list = 0;
 
-  symbol_table::scope_id fcn_scope = symbol_table::current_scope ();
-
-  if (symtab_context.empty ())
+  symbol_table::scope_id fcn_scope = lexer.symtab_context.curr_scope ();
+
+  if (lexer.symtab_context.empty ())
     panic_impossible ();
 
-  symbol_table::set_scope (symtab_context.top ());
-
-  symtab_context.pop ();
+  lexer.symtab_context.pop ();
 
   stmt->set_print_flag (false);
 
@@ -2139,16 +1920,16 @@
     = new tree_anon_fcn_handle (param_list, ret_list, body, fcn_scope, l, c);
   // FIXME: Stash the filename.  This does not work and produces
   // errors when executed.
-  //retval->stash_file_name (curr_fcn_file_name);
+  //retval->stash_file_name (lexer.fcn_file_name);
 
   return retval;
 }
 
 // Build a binary expression.
 
-static tree_expression *
-make_binary_op (int op, tree_expression *op1, token *tok_val,
-                tree_expression *op2)
+tree_expression *
+octave_base_parser::make_binary_op (int op, tree_expression *op1,
+                                    token *tok_val, tree_expression *op2)
 {
   octave_value::binary_op t = octave_value::unknown_binary_op;
 
@@ -2250,9 +2031,9 @@
 
 // Build a boolean expression.
 
-static tree_expression *
-make_boolean_op (int op, tree_expression *op1, token *tok_val,
-                 tree_expression *op2)
+tree_expression *
+octave_base_parser::make_boolean_op (int op, tree_expression *op1,
+                                     token *tok_val, tree_expression *op2)
 {
   tree_boolean_expression::type t;
 
@@ -2282,8 +2063,9 @@
 
 // Build a prefix expression.
 
-static tree_expression *
-make_prefix_op (int op, tree_expression *op1, token *tok_val)
+tree_expression *
+octave_base_parser::make_prefix_op (int op, tree_expression *op1,
+                                    token *tok_val)
 {
   octave_value::unary_op t = octave_value::unknown_unary_op;
 
@@ -2325,14 +2107,15 @@
 
 // Build a postfix expression.
 
-static tree_expression *
-make_postfix_op (int op, tree_expression *op1, token *tok_val)
+tree_expression *
+octave_base_parser::make_postfix_op (int op, tree_expression *op1,
+                                     token *tok_val)
 {
   octave_value::unary_op t = octave_value::unknown_unary_op;
 
   switch (op)
     {
-    case QUOTE:
+    case HERMITIAN:
       t = octave_value::op_hermitian;
       break;
 
@@ -2364,10 +2147,13 @@
 
 // Build an unwind-protect command.
 
-static tree_command *
-make_unwind_command (token *unwind_tok, tree_statement_list *body,
-                     tree_statement_list *cleanup, token *end_tok,
-                     octave_comment_list *lc, octave_comment_list *mc)
+tree_command *
+octave_base_parser::make_unwind_command (token *unwind_tok,
+                                         tree_statement_list *body,
+                                         tree_statement_list *cleanup_stmts,
+                                         token *end_tok,
+                                         octave_comment_list *lc,
+                                         octave_comment_list *mc)
 {
   tree_command *retval = 0;
 
@@ -2378,7 +2164,7 @@
       int l = unwind_tok->line ();
       int c = unwind_tok->column ();
 
-      retval = new tree_unwind_protect_command (body, cleanup,
+      retval = new tree_unwind_protect_command (body, cleanup_stmts,
                                                 lc, mc, tc, l, c);
     }
 
@@ -2387,10 +2173,13 @@
 
 // Build a try-catch command.
 
-static tree_command *
-make_try_command (token *try_tok, tree_statement_list *body,
-                  tree_statement_list *cleanup, token *end_tok,
-                  octave_comment_list *lc, octave_comment_list *mc)
+tree_command *
+octave_base_parser::make_try_command (token *try_tok,
+                                      tree_statement_list *body,
+                                      tree_statement_list *cleanup_stmts,
+                                      token *end_tok,
+                                      octave_comment_list *lc,
+                                      octave_comment_list *mc)
 {
   tree_command *retval = 0;
 
@@ -2401,7 +2190,7 @@
       int l = try_tok->line ();
       int c = try_tok->column ();
 
-      retval = new tree_try_catch_command (body, cleanup,
+      retval = new tree_try_catch_command (body, cleanup_stmts,
                                            lc, mc, tc, l, c);
     }
 
@@ -2410,10 +2199,12 @@
 
 // Build a while command.
 
-static tree_command *
-make_while_command (token *while_tok, tree_expression *expr,
-                    tree_statement_list *body, token *end_tok,
-                    octave_comment_list *lc)
+tree_command *
+octave_base_parser::make_while_command (token *while_tok,
+                                        tree_expression *expr,
+                                        tree_statement_list *body,
+                                        token *end_tok,
+                                        octave_comment_list *lc)
 {
   tree_command *retval = 0;
 
@@ -2423,7 +2214,7 @@
     {
       octave_comment_list *tc = octave_comment_buffer::get_comment ();
 
-      lexer_flags.looping--;
+      lexer.looping--;
 
       int l = while_tok->line ();
       int c = while_tok->column ();
@@ -2436,9 +2227,11 @@
 
 // Build a do-until command.
 
-static tree_command *
-make_do_until_command (token *until_tok, tree_statement_list *body,
-                       tree_expression *expr, octave_comment_list *lc)
+tree_command *
+octave_base_parser::make_do_until_command (token *until_tok,
+                                           tree_statement_list *body,
+                                           tree_expression *expr,
+                                           octave_comment_list *lc)
 {
   tree_command *retval = 0;
 
@@ -2446,7 +2239,7 @@
 
   octave_comment_list *tc = octave_comment_buffer::get_comment ();
 
-  lexer_flags.looping--;
+  lexer.looping--;
 
   int l = until_tok->line ();
   int c = until_tok->column ();
@@ -2458,11 +2251,14 @@
 
 // Build a for command.
 
-static tree_command *
-make_for_command (int tok_id, token *for_tok, tree_argument_list *lhs,
-                  tree_expression *expr, tree_expression *maxproc,
-                  tree_statement_list *body, token *end_tok,
-                  octave_comment_list *lc)
+tree_command *
+octave_base_parser::make_for_command (int tok_id, token *for_tok,
+                                      tree_argument_list *lhs,
+                                      tree_expression *expr,
+                                      tree_expression *maxproc,
+                                      tree_statement_list *body,
+                                      token *end_tok,
+                                      octave_comment_list *lc)
 {
   tree_command *retval = 0;
 
@@ -2472,7 +2268,7 @@
     {
       octave_comment_list *tc = octave_comment_buffer::get_comment ();
 
-      lexer_flags.looping--;
+      lexer.looping--;
 
       int l = for_tok->line ();
       int c = for_tok->column ();
@@ -2489,7 +2285,7 @@
       else
         {
           if (parfor)
-            yyerror ("invalid syntax for parfor statement");
+            bison_error ("invalid syntax for parfor statement");
           else
             retval = new tree_complex_for_command (lhs, expr, body,
                                                    lc, tc, l, c);
@@ -2501,8 +2297,8 @@
 
 // Build a break command.
 
-static tree_command *
-make_break_command (token *break_tok)
+tree_command *
+octave_base_parser::make_break_command (token *break_tok)
 {
   tree_command *retval = 0;
 
@@ -2516,8 +2312,8 @@
 
 // Build a continue command.
 
-static tree_command *
-make_continue_command (token *continue_tok)
+tree_command *
+octave_base_parser::make_continue_command (token *continue_tok)
 {
   tree_command *retval = 0;
 
@@ -2531,8 +2327,8 @@
 
 // Build a return command.
 
-static tree_command *
-make_return_command (token *return_tok)
+tree_command *
+octave_base_parser::make_return_command (token *return_tok)
 {
   tree_command *retval = 0;
 
@@ -2546,8 +2342,9 @@
 
 // Start an if command.
 
-static tree_if_command_list *
-start_if_command (tree_expression *expr, tree_statement_list *list)
+tree_if_command_list *
+octave_base_parser::start_if_command (tree_expression *expr,
+                                      tree_statement_list *list)
 {
   maybe_warn_assign_as_truth_value (expr);
 
@@ -2558,9 +2355,11 @@
 
 // Finish an if command.
 
-static tree_if_command *
-finish_if_command (token *if_tok, tree_if_command_list *list,
-                   token *end_tok, octave_comment_list *lc)
+tree_if_command *
+octave_base_parser::finish_if_command (token *if_tok,
+                                       tree_if_command_list *list,
+                                       token *end_tok,
+                                       octave_comment_list *lc)
 {
   tree_if_command *retval = 0;
 
@@ -2590,9 +2389,11 @@
 
 // Build an elseif clause.
 
-static tree_if_clause *
-make_elseif_clause (token *elseif_tok, tree_expression *expr,
-                    tree_statement_list *list, octave_comment_list *lc)
+tree_if_clause *
+octave_base_parser::make_elseif_clause (token *elseif_tok,
+                                        tree_expression *expr,
+                                        tree_statement_list *list,
+                                        octave_comment_list *lc)
 {
   maybe_warn_assign_as_truth_value (expr);
 
@@ -2604,10 +2405,12 @@
 
 // Finish a switch command.
 
-static tree_switch_command *
-finish_switch_command (token *switch_tok, tree_expression *expr,
-                       tree_switch_case_list *list, token *end_tok,
-                       octave_comment_list *lc)
+tree_switch_command *
+octave_base_parser::finish_switch_command (token *switch_tok,
+                                           tree_expression *expr,
+                                           tree_switch_case_list *list,
+                                           token *end_tok,
+                                           octave_comment_list *lc)
 {
   tree_switch_command *retval = 0;
 
@@ -2637,9 +2440,11 @@
 
 // Build a switch case.
 
-static tree_switch_case *
-make_switch_case (token *case_tok, tree_expression *expr,
-                  tree_statement_list *list, octave_comment_list *lc)
+tree_switch_case *
+octave_base_parser::make_switch_case (token *case_tok,
+                                      tree_expression *expr,
+                                      tree_statement_list *list,
+                                      octave_comment_list *lc)
 {
   maybe_warn_variable_switch_label (expr);
 
@@ -2651,9 +2456,9 @@
 
 // Build an assignment to a variable.
 
-static tree_expression *
-make_assign_op (int op, tree_argument_list *lhs, token *eq_tok,
-                tree_expression *rhs)
+tree_expression *
+octave_base_parser::make_assign_op (int op, tree_argument_list *lhs,
+                                    token *eq_tok, tree_expression *rhs)
 {
   tree_expression *retval = 0;
 
@@ -2740,50 +2545,42 @@
   else if (t == octave_value::op_asn_eq)
     return new tree_multi_assignment (lhs, rhs, false, l, c);
   else
-    yyerror ("computed multiple assignment not allowed");
+    bison_error ("computed multiple assignment not allowed");
 
   return retval;
 }
 
 // Define a script.
 
-static void
-make_script (tree_statement_list *cmds, tree_statement *end_script)
+void
+octave_base_parser::make_script (tree_statement_list *cmds,
+                                 tree_statement *end_script)
 {
-  std::string doc_string;
-
-  if (! help_buf.empty ())
-    {
-      doc_string = help_buf.top ();
-      help_buf.pop ();
-    }
-
   if (! cmds)
     cmds = new tree_statement_list ();
 
   cmds->append (end_script);
 
   octave_user_script *script
-    = new octave_user_script (curr_fcn_file_full_name, curr_fcn_file_name,
-                              cmds, doc_string);
+    = new octave_user_script (lexer.fcn_file_full_name,
+                              lexer.fcn_file_name,
+                              cmds, lexer.help_text);
+
+  lexer.help_text = "";
 
   octave_time now;
 
   script->stash_fcn_file_time (now);
 
   primary_fcn_ptr = script;
-
-  // Unmark any symbols that may have been tagged as local variables
-  // while parsing (for example, by force_local_variable in lex.l).
-
-  symbol_table::unmark_forced_variables ();
 }
 
 // Begin defining a function.
 
-static octave_user_function *
-start_function (tree_parameter_list *param_list, tree_statement_list *body,
-                tree_statement *end_fcn_stmt)
+octave_user_function *
+octave_base_parser::start_function (tree_parameter_list *param_list,
+                                    tree_statement_list *body,
+                                    tree_statement *end_fcn_stmt)
 {
   // We'll fill in the return list later.
 
@@ -2793,7 +2590,7 @@
   body->append (end_fcn_stmt);
 
   octave_user_function *fcn
-    = new octave_user_function (symbol_table::current_scope (),
+    = new octave_user_function (lexer.symtab_context.curr_scope (),
                                 param_list, 0, body);
 
   if (fcn)
@@ -2806,16 +2603,17 @@
   return fcn;
 }
 
-static tree_statement *
-make_end (const std::string& type, int l, int c)
+tree_statement *
+octave_base_parser::make_end (const std::string& type, int l, int c)
 {
   return make_statement (new tree_no_op_command (type, l, c));
 }
 
 // Do most of the work for defining a function.
 
-static octave_user_function *
-frob_function (const std::string& fname, octave_user_function *fcn)
+octave_user_function *
+octave_base_parser::frob_function (const std::string& fname,
+                                   octave_user_function *fcn)
 {
   std::string id_name = fname;
 
@@ -2823,57 +2621,60 @@
   // the file does not match the name of the function stated in the
   // file.  Matlab doesn't provide a diagnostic (it ignores the stated
   // name).
-  if (! autoloading && reading_fcn_file
-      && (current_function_depth == 1
-          && ! (parsing_subfunctions || lexer_flags.parsing_class_method)))
+  if (! autoloading && lexer.reading_fcn_file
+      && curr_fcn_depth == 1 && ! parsing_subfunctions)
   {
-    // FIXME -- should curr_fcn_file_name already be
+    // FIXME -- should lexer.fcn_file_name already be
     // preprocessed when we get here?  It seems to only be a
     // problem with relative file names.
 
-    std::string nm = curr_fcn_file_name;
+    std::string nm = lexer.fcn_file_name;
 
     size_t pos = nm.find_last_of (file_ops::dir_sep_chars ());
 
     if (pos != std::string::npos)
-      nm = curr_fcn_file_name.substr (pos+1);
+      nm = lexer.fcn_file_name.substr (pos+1);
 
     if (nm != id_name)
       {
         warning_with_id
           ("Octave:function-name-clash",
            "function name '%s' does not agree with function file name '%s'",
-           id_name.c_str (), curr_fcn_file_full_name.c_str ());
+           id_name.c_str (), lexer.fcn_file_full_name.c_str ());
 
         id_name = nm;
       }
   }
 
-  if (reading_fcn_file || reading_classdef_file || autoloading)
+  if (lexer.reading_fcn_file || lexer.reading_classdef_file || autoloading)
     {
       octave_time now;
 
-      fcn->stash_fcn_file_name (curr_fcn_file_full_name);
+      fcn->stash_fcn_file_name (lexer.fcn_file_full_name);
       fcn->stash_fcn_file_time (now);
       fcn->mark_as_system_fcn_file ();
 
       if (fcn_file_from_relative_lookup)
         fcn->mark_relative ();
 
-      if (current_function_depth > 1 || parsing_subfunctions)
+      if (curr_fcn_depth > 1 || parsing_subfunctions)
         {
-          fcn->stash_parent_fcn_name (curr_fcn_file_name);
-          fcn->stash_parent_fcn_scope (primary_fcn_scope);
+          fcn->stash_parent_fcn_name (lexer.fcn_file_name);
+
+          if (curr_fcn_depth > 1)
+            fcn->stash_parent_fcn_scope (function_scopes[function_scopes.size ()-2]);
+          else
+            fcn->stash_parent_fcn_scope (primary_fcn_scope);
         }
 
-      if (lexer_flags.parsing_class_method)
+      if (lexer.parsing_class_method)
         {
-          if (current_class_name == id_name)
+          if (curr_class_name == id_name)
             fcn->mark_as_class_constructor ();
           else
             fcn->mark_as_class_method ();
 
-          fcn->stash_dispatch_class (current_class_name);
+          fcn->stash_dispatch_class (curr_class_name);
         }
 
       std::string nm = fcn->fcn_file_name ();
@@ -2884,35 +2685,38 @@
         warning_with_id ("Octave:future-time-stamp",
                          "time stamp for '%s' is in the future", nm.c_str ());
     }
-  else if (! (input_from_tmp_history_file || input_from_startup_file)
-           && reading_script_file
-           && curr_fcn_file_name == id_name)
+  else if (! input_from_tmp_history_file
+           && ! lexer.force_script
+           && lexer.reading_script_file
+           && lexer.fcn_file_name == id_name)
     {
       warning ("function '%s' defined within script file '%s'",
-               id_name.c_str (), curr_fcn_file_full_name.c_str ());
+               id_name.c_str (), lexer.fcn_file_full_name.c_str ());
     }
 
   fcn->stash_function_name (id_name);
-  fcn->stash_fcn_location (input_line_number, current_input_column);
-
-  if (! help_buf.empty () && current_function_depth == 1
+  fcn->stash_fcn_location (lexer.input_line_number,
+                           lexer.current_input_column);
+
+  if (! lexer.help_text.empty () && curr_fcn_depth == 1
       && ! parsing_subfunctions)
     {
-      fcn->document (help_buf.top ());
-
-      help_buf.pop ();
+      fcn->document (lexer.help_text);
+
+      lexer.help_text = "";
     }
 
-  if (reading_fcn_file && current_function_depth == 1
+  if (lexer.reading_fcn_file && curr_fcn_depth == 1
       && ! parsing_subfunctions)
     primary_fcn_ptr = fcn;
 
   return fcn;
 }
 
-static tree_function_def *
-finish_function (tree_parameter_list *ret_list,
-                 octave_user_function *fcn, octave_comment_list *lc)
+tree_function_def *
+octave_base_parser::finish_function (tree_parameter_list *ret_list,
+                                     octave_user_function *fcn,
+                                     octave_comment_list *lc)
 {
   tree_function_def *retval = 0;
 
@@ -2935,70 +2739,78 @@
 
       fcn->define_ret_list (ret_list);
 
-      if (current_function_depth > 1 || parsing_subfunctions)
+      if (curr_fcn_depth > 1 || parsing_subfunctions)
         {
           fcn->mark_as_subfunction ();
 
-          symbol_table::install_subfunction (nm, octave_value (fcn),
-                                             primary_fcn_scope);
+          if (endfunction_found && function_scopes.size () > 1)
+            {
+              symbol_table::scope_id pscope
+                = function_scopes[function_scopes.size ()-2];
+
+              symbol_table::install_nestfunction (nm, octave_value (fcn),
+                                                  pscope);
+            }
+          else
+            symbol_table::install_subfunction (nm, octave_value (fcn),
+                                               primary_fcn_scope);
         }
 
-      if (! reading_fcn_file)
+      if (curr_fcn_depth == 1 && fcn)
+        symbol_table::update_nest (fcn->scope ());
+
+      if (! lexer.reading_fcn_file && curr_fcn_depth == 1)
         {
           // We are either reading a script file or defining a function
           // at the command line, so this definition creates a
           // tree_function object that is placed in the parse tree.
           // Otherwise, it is just inserted in the symbol table,
-          // either as a subfunction (see above), or as the primary
-          // function for the file, via primary_fcn_ptr (see also
-          // load_fcn_from_file,, parse_fcn_file, and
+          // either as a subfunction or nested function (see above),
+          // or as the primary function for the file, via
+          // primary_fcn_ptr (see also load_fcn_from_file,,
+          // parse_fcn_file, and
           // symbol_table::fcn_info::fcn_info_rep::find_user_function).
 
           retval = new tree_function_def (fcn);
         }
-
-      // Unmark any symbols that may have been tagged as local
-      // variables while parsing (for example, by force_local_variable
-      // in lex.l).
-
-      symbol_table::unmark_forced_variables (fcn->scope ());
     }
 
   return retval;
 }
 
-static void
-recover_from_parsing_function (void)
+void
+octave_base_parser::recover_from_parsing_function (void)
 {
-  if (symtab_context.empty ())
+  if (lexer.symtab_context.empty ())
     panic_impossible ();
 
-  symbol_table::set_scope (symtab_context.top ());
-  symtab_context.pop ();
-
-  if (reading_fcn_file && current_function_depth == 1
+  lexer.symtab_context.pop ();
+
+  if (lexer.reading_fcn_file && curr_fcn_depth == 1
       && ! parsing_subfunctions)
     parsing_subfunctions = true;
 
-  current_function_depth--;
-
-  lexer_flags.defining_func--;
-  lexer_flags.parsed_function_name.pop ();
-  lexer_flags.looking_at_return_list = false;
-  lexer_flags.looking_at_parameter_list = false;
+  curr_fcn_depth--;
+  function_scopes.pop_back ();
+
+  lexer.defining_func--;
+  lexer.parsed_function_name.pop ();
+  lexer.looking_at_return_list = false;
+  lexer.looking_at_parameter_list = false;
 }
 
 // Make an index expression.
 
-static tree_index_expression *
-make_index_expression (tree_expression *expr, tree_argument_list *args,
-                       char type)
+tree_index_expression *
+octave_base_parser::make_index_expression (tree_expression *expr,
+                                           tree_argument_list *args,
+                                           char type)
 {
   tree_index_expression *retval = 0;
 
   if (args && args->has_magic_tilde ())
     {
-      yyerror ("invalid use of empty argument (~) in index expression");
+      bison_error ("invalid use of empty argument (~) in index expression");
       return retval;
     }
 
@@ -3023,8 +2835,9 @@
 
 // Make an indirect reference expression.
 
-static tree_index_expression *
-make_indirect_ref (tree_expression *expr, const std::string& elt)
+tree_index_expression *
+octave_base_parser::make_indirect_ref (tree_expression *expr,
+                                       const std::string& elt)
 {
   tree_index_expression *retval = 0;
 
@@ -3042,15 +2855,15 @@
   else
     retval = new tree_index_expression (expr, elt, l, c);
 
-  lexer_flags.looking_at_indirect_ref = false;
+  lexer.looking_at_indirect_ref = false;
 
   return retval;
 }
 
 // Make an indirect reference expression with dynamic field name.
 
-static tree_index_expression *
-make_indirect_ref (tree_expression *expr, tree_expression *elt)
+tree_index_expression *
+octave_base_parser::make_indirect_ref (tree_expression *expr, tree_expression *elt)
 {
   tree_index_expression *retval = 0;
 
@@ -3068,15 +2881,16 @@
   else
     retval = new tree_index_expression (expr, elt, l, c);
 
-  lexer_flags.looking_at_indirect_ref = false;
+  lexer.looking_at_indirect_ref = false;
 
   return retval;
 }
 
 // Make a declaration command.
 
-static tree_decl_command *
-make_decl_command (int tok, token *tok_val, tree_decl_init_list *lst)
+tree_decl_command *
+octave_base_parser::make_decl_command (int tok, token *tok_val,
+                                       tree_decl_init_list *lst)
 {
   tree_decl_command *retval = 0;
 
@@ -3089,14 +2903,14 @@
       retval = new tree_global_command (lst, l, c);
       break;
 
-    case STATIC:
-      if (current_function_depth > 0)
-        retval = new tree_static_command (lst, l, c);
+    case PERSISTENT:
+      if (curr_fcn_depth > 0)
+        retval = new tree_persistent_command (lst, l, c);
       else
         {
-          if (reading_script_file)
+          if (lexer.reading_script_file)
             warning ("ignoring persistent declaration near line %d of file '%s'",
-                     l, curr_fcn_file_full_name.c_str ());
+                     l, lexer.fcn_file_full_name.c_str ());
           else
             warning ("ignoring persistent declaration near line %d", l);
         }
@@ -3110,20 +2924,92 @@
   return retval;
 }
 
-static tree_argument_list *
-validate_matrix_row (tree_argument_list *row)
+bool
+octave_base_parser::validate_array_list (tree_expression *e)
 {
-  if (row && row->has_magic_tilde ())
-    yyerror ("invalid use of tilde (~) in matrix expression");
-  return row;
+  bool retval = true;
+
+  tree_array_list *al = dynamic_cast<tree_array_list *> (e);
+
+  for (tree_array_list::iterator i = al->begin (); i != al->end (); i++)
+    {
+      tree_argument_list *row = *i;
+
+      if (row && row->has_magic_tilde ())
+        {
+          retval = false;
+          if (e->is_matrix ())
+             bison_error ("invalid use of tilde (~) in matrix expression");
+           else
+             bison_error ("invalid use of tilde (~) in cell expression");
+          break;
+        }
+    }
+
+  return retval;
 }
 
-// Finish building a matrix list.
-
-static tree_expression *
-finish_matrix (tree_matrix *m)
+tree_argument_list *
+octave_base_parser::validate_matrix_for_assignment (tree_expression *e)
 {
-  tree_expression *retval = m;
+  tree_argument_list *retval = 0;
+
+  if (e->is_constant ())
+    {
+      octave_value ov = e->rvalue1 ();
+
+      if (ov.is_empty ())
+        bison_error ("invalid empty left hand side of assignment");
+      else
+        bison_error ("invalid constant left hand side of assignment");
+
+      delete e;
+    }
+  else
+    {
+      bool is_simple_assign = true;
+
+      tree_argument_list *tmp = 0;
+
+      if (e->is_matrix ())
+        {
+          tree_matrix *mat = dynamic_cast<tree_matrix *> (e);
+
+          if (mat && mat->size () == 1)
+            {
+              tmp = mat->front ();
+              mat->pop_front ();
+              delete e;
+              is_simple_assign = false;
+            }
+        }
+      else
+        tmp = new tree_argument_list (e);
+
+      if (tmp && tmp->is_valid_lvalue_list ())
+        {
+          lexer.mark_as_variables (tmp->variable_names ());
+          retval = tmp;
+        }
+      else
+        {
+          bison_error ("invalid left hand side of assignment");
+          delete tmp;
+        }
+
+      if (retval && is_simple_assign)
+        retval->mark_as_simple_assign_lhs ();
+    }
+
+  return retval;
+}
+
+// Finish building an array_list.
+
+tree_expression *
+octave_base_parser::finish_array_list (tree_array_list *array_list)
+{
+  tree_expression *retval = array_list;
 
   unwind_protect frame;
 
@@ -3136,24 +3022,25 @@
   discard_error_messages = true;
   discard_warning_messages = true;
 
-  if (m->all_elements_are_constant ())
+  if (array_list->all_elements_are_constant ())
     {
-      octave_value tmp = m->rvalue1 ();
+      octave_value tmp = array_list->rvalue1 ();
 
       if (! (error_state || warning_state))
         {
           tree_constant *tc_retval
-            = new tree_constant (tmp, m->line (), m->column ());
+            = new tree_constant (tmp, array_list->line (),
+                                 array_list->column ());
 
           std::ostringstream buf;
 
           tree_print_code tpc (buf);
 
-          m->accept (tpc);
+          array_list->accept (tpc);
 
           tc_retval->stash_original_text (buf.str ());
 
-          delete m;
+          delete array_list;
 
           retval = tc_retval;
         }
@@ -3162,32 +3049,40 @@
   return retval;
 }
 
-// Finish building a cell list.
-
-static tree_expression *
-finish_cell (tree_cell *c)
+// Finish building a matrix list.
+
+tree_expression *
+octave_base_parser::finish_matrix (tree_matrix *m)
 {
-  return finish_matrix (c);
+  return finish_array_list (m);
 }
 
-static void
-maybe_warn_missing_semi (tree_statement_list *t)
+// Finish building a cell list.
+
+tree_expression *
+octave_base_parser::finish_cell (tree_cell *c)
 {
-  if (current_function_depth > 0)
+  return finish_array_list (c);
+}
+
+void
+octave_base_parser::maybe_warn_missing_semi (tree_statement_list *t)
+{
+  if (curr_fcn_depth > 0)
     {
-      tree_statement *tmp = t->back();
+      tree_statement *tmp = t->back ();
 
       if (tmp->is_expression ())
         warning_with_id
           ("Octave:missing-semicolon",
            "missing semicolon near line %d, column %d in file '%s'",
-            tmp->line (), tmp->column (), curr_fcn_file_full_name.c_str ());
+            tmp->line (), tmp->column (), lexer.fcn_file_full_name.c_str ());
     }
 }
 
-static tree_statement_list *
-set_stmt_print_flag (tree_statement_list *list, char sep,
-                     bool warn_missing_semi)
+tree_statement_list *
+octave_base_parser::set_stmt_print_flag (tree_statement_list *list,
+                                         char sep, bool warn_missing_semi)
 {
   tree_statement *tmp = list->back ();
 
@@ -3222,15 +3117,16 @@
   return list;
 }
 
-static tree_statement_list *
-make_statement_list (tree_statement *stmt)
+tree_statement_list *
+octave_base_parser::make_statement_list (tree_statement *stmt)
 {
   return new tree_statement_list (stmt);
 }
 
-static tree_statement_list *
-append_statement_list (tree_statement_list *list, char sep,
-                       tree_statement *stmt, bool warn_missing_semi)
+tree_statement_list *
+octave_base_parser::append_statement_list (tree_statement_list *list,
+                                           char sep, tree_statement *stmt,
+                                           bool warn_missing_semi)
 {
   set_stmt_print_flag (list, sep, warn_missing_semi);
 
@@ -3239,6 +3135,106 @@
   return list;
 }
 
+void
+octave_base_parser::bison_error (const char *s)
+{
+  int err_col = lexer.current_input_column - 1;
+
+  std::ostringstream output_buf;
+
+  if (lexer.reading_fcn_file || lexer.reading_script_file || lexer.reading_classdef_file)
+    output_buf << "parse error near line " << lexer.input_line_number
+               << " of file " << lexer.fcn_file_full_name;
+  else
+    output_buf << "parse error:";
+
+  if (s && strcmp (s, "parse error") != 0)
+    output_buf << "\n\n  " << s;
+
+  output_buf << "\n\n";
+
+  std::string curr_line = lexer.current_input_line;
+
+  if (! curr_line.empty ())
+    {
+      size_t len = curr_line.length ();
+
+      if (curr_line[len-1] == '\n')
+        curr_line.resize (len-1);
+
+      // Print the line, maybe with a pointer near the error token.
+
+      output_buf << ">>> " << curr_line << "\n";
+
+      if (err_col == 0)
+        err_col = len;
+
+      for (int i = 0; i < err_col + 3; i++)
+        output_buf << " ";
+
+      output_buf << "^";
+    }
+
+  output_buf << "\n";
+
+  std::string msg = output_buf.str ();
+
+  parse_error ("%s", msg.c_str ());
+}
+
+int
+octave_parser::run (void)
+{
+  return octave_parse (*this);
+}
+
+octave_push_parser::~octave_push_parser (void)
+{
+  yypstate_delete (static_cast<yypstate *> (parser_state));
+}
+
+void
+octave_push_parser::init (void)
+{
+  parser_state = yypstate_new ();
+
+  octave_base_parser::init ();
+}
+
+// Parse input from INPUT.  Pass TRUE for EOF if the end of INPUT should
+// finish the parse.
+
+int
+octave_push_parser::run (const std::string& input, bool eof)
+{
+  int status = -1;
+
+  dynamic_cast<octave_push_lexer&> (lexer).append_input (input, eof);
+
+  do
+    {   
+      YYSTYPE lval;
+
+      int token = octave_lex (&lval, scanner);
+
+      if (token < 0)
+        {
+          if (! eof && lexer.at_end_of_buffer ())
+            {
+              status = -1;
+              break;
+            }
+        }
+
+      yypstate *pstate = static_cast<yypstate *> (parser_state);
+
+      status = octave_push_parse (pstate, token, &lval, *this);
+    }
+  while (status == YYPUSH_MORE);
+
+  return status;
+}
+
 static void
 safe_fclose (FILE *f)
 {
@@ -3255,182 +3251,11 @@
     fclose (static_cast<FILE *> (f));
 }
 
-static bool
-looks_like_copyright (const std::string& s)
-{
-  bool retval = false;
-
-  if (! s.empty ())
-    {
-      size_t offset = s.find_first_not_of (" \t");
-
-      retval = (s.substr (offset, 9) == "Copyright" || s.substr (offset, 6) == "Author");
-    }
-
-  return retval;
-}
-
-static int
-text_getc (FILE *f)
-{
-  int c = gnulib::getc (f);
-
-  // Convert CRLF into just LF and single CR into LF.
-
-  if (c == '\r')
-    {
-      c = gnulib::getc (f);
-
-      if (c != '\n')
-        {
-          ungetc (c, f);
-          c = '\n';
-        }
-    }
-
-  if (c == '\n')
-    input_line_number++;
-
-  return c;
-}
-
-class
-stdio_stream_reader : public stream_reader
-{
-public:
-  stdio_stream_reader (FILE *f_arg) : stream_reader (), f (f_arg) { }
-
-  int getc (void) { return ::text_getc (f); }
-  int ungetc (int c)
-  {
-    if (c == '\n')
-      input_line_number--;
-
-    return ::ungetc (c, f);
-  }
-
-private:
-  FILE *f;
-
-  // No copying!
-
-  stdio_stream_reader (const  stdio_stream_reader&);
-
-  stdio_stream_reader & operator = (const  stdio_stream_reader&);
-};
-
-static bool
-skip_white_space (stream_reader& reader)
-{
-  int c = 0;
-
-  while ((c = reader.getc ()) != EOF)
-    {
-      switch (c)
-        {
-        case ' ':
-        case '\t':
-          current_input_column++;
-          break;
-
-        case '\n':
-          current_input_column = 1;
-          break;
-
-        default:
-          reader.ungetc (c);
-          goto done;
-        }
-    }
-
- done:
-
-  return (c == EOF);
-}
-
-static bool
-looking_at_classdef_keyword (FILE *ffile)
-{
-  bool status = false;
-
-  long pos = gnulib::ftell (ffile);
-
-  char buf [10];
-  gnulib::fgets (buf, 10, ffile);
-  size_t len = strlen (buf);
-  if (len > 8 && strncmp (buf, "classdef", 8) == 0
-      && ! (isalnum (buf[8]) || buf[8] == '_'))
-    status = true;
-
-  gnulib::fseek (ffile, pos, SEEK_SET);
-
-  return status;
- }
-
-static std::string
-gobble_leading_white_space (FILE *ffile, bool& eof)
-{
-  std::string help_txt;
-
-  eof = false;
-
-  // TRUE means we have already cached the help text.
-  bool have_help_text = false;
-
-  std::string txt;
-
-  stdio_stream_reader stdio_reader (ffile);
-
-  while (true)
-    {
-      eof = skip_white_space (stdio_reader);
-
-      if (eof)
-        break;
-
-      txt = grab_comment_block (stdio_reader, true, eof);
-
-      if (txt.empty ())
-        break;
-
-      if (! (have_help_text || looks_like_copyright (txt)))
-        {
-          help_txt = txt;
-          have_help_text = true;
-        }
-
-      octave_comment_buffer::append (txt);
-
-      if (eof)
-        break;
-    }
-
-  return help_txt;
-}
-
-static bool
-looking_at_function_keyword (FILE *ffile)
-{
-  bool status = false;
-
-  long pos = gnulib::ftell (ffile);
-
-  char buf [10];
-  gnulib::fgets (buf, 10, ffile);
-  size_t len = strlen (buf);
-  if (len > 8 && strncmp (buf, "function", 8) == 0
-      && ! (isalnum (buf[8]) || buf[8] == '_'))
-    status = true;
-
-  gnulib::fseek (ffile, pos, SEEK_SET);
-
-  return status;
-}
-
 static octave_function *
-parse_fcn_file (const std::string& ff, const std::string& dispatch_type,
-                bool force_script = false, bool require_file = true,
-                const std::string& warn_for = std::string ())
+parse_fcn_file (const std::string& full_file, const std::string& file,
+                const std::string& dispatch_type,
+                bool require_file, bool force_script, bool autoload,    
+                bool relative_lookup, const std::string& warn_for)
 {
   unwind_protect frame;
 
@@ -3442,195 +3267,88 @@
 
   frame.add_fcn (command_editor::set_input_stream, in_stream);
 
-  frame.protect_var (ff_instream);
-
-  frame.protect_var (input_line_number);
-  frame.protect_var (current_input_column);
-  frame.protect_var (reading_fcn_file);
-  frame.protect_var (line_editing);
-  frame.protect_var (current_class_name);
-  frame.protect_var (current_function_depth);
-  frame.protect_var (max_function_depth);
-  frame.protect_var (parsing_subfunctions);
-  frame.protect_var (endfunction_found);
-
-  input_line_number = 1;
-  current_input_column = 1;
-  reading_fcn_file = true;
-  line_editing = false;
-  current_class_name = dispatch_type;
-  current_function_depth = 0;
-  max_function_depth = 0;
-  parsing_subfunctions = false;
-  endfunction_found = false;
-
   frame.add_fcn (command_history::ignore_entries,
                  command_history::ignoring_entries ());
 
   command_history::ignore_entries ();
 
-  FILE *ffile = get_input_from_file (ff, 0);
+  FILE *ffile = 0;
+
+  if (! full_file.empty ())
+    ffile = gnulib::fopen (full_file.c_str (), "rb");
 
   frame.add_fcn (safe_fclose, ffile);
 
   if (ffile)
     {
-      bool eof;
-
-      std::string help_txt = gobble_leading_white_space (ffile, eof);
-
-      if (! help_txt.empty ())
-        help_buf.push (help_txt);
-
-      if (! eof)
-        {
-          std::string file_type;
-
-          frame.protect_var (get_input_from_eval_string);
-          frame.protect_var (parser_end_of_input);
-          frame.protect_var (reading_fcn_file);
-          frame.protect_var (reading_script_file);
-          frame.protect_var (reading_classdef_file);
-          frame.protect_var (Vecho_executing_commands);
-
-
-          get_input_from_eval_string = false;
-          parser_end_of_input = false;
-
-          if (! force_script && looking_at_function_keyword (ffile))
-            {
-              file_type = "function";
-
-              Vecho_executing_commands = ECHO_OFF;
-
-              reading_classdef_file = false;
-              reading_fcn_file = true;
-              reading_script_file = false;
-            }
-          else if (! force_script && looking_at_classdef_keyword (ffile))
-            {
-              file_type = "classdef";
-
-              Vecho_executing_commands = ECHO_OFF;
-
-              reading_classdef_file = true;
-              reading_fcn_file = false;
-              reading_script_file = false;
-            }
-          else
-            {
-              file_type = "script";
-
-              Vecho_executing_commands = ECHO_OFF;
-
-              reading_classdef_file = false;
-              reading_fcn_file = false;
-              reading_script_file = true;
-            }
-
-          YY_BUFFER_STATE old_buf = current_buffer ();
-          YY_BUFFER_STATE new_buf = create_buffer (ffile);
-
-          frame.add_fcn (switch_to_buffer, old_buf);
-          frame.add_fcn (delete_buffer, new_buf);
-
-          switch_to_buffer (new_buf);
-
-          frame.protect_var (primary_fcn_ptr);
-          primary_fcn_ptr = 0;
-
-          reset_parser ();
-
-          // Do this with an unwind-protect cleanup function so that
-          // the forced variables will be unmarked in the event of an
-          // interrupt.
-          symbol_table::scope_id scope = symbol_table::top_scope ();
-          frame.add_fcn (symbol_table::unmark_forced_variables, scope);
-
-          if (! help_txt.empty ())
-            help_buf.push (help_txt);
-
-          if (reading_script_file)
-            prep_lexer_for_script_file ();
-          else
-            prep_lexer_for_function_file ();
-
-          lexer_flags.parsing_class_method = ! dispatch_type.empty ();
-
-          frame.protect_var (global_command);
-
-          global_command = 0;
-
-          int status = yyparse ();
-
-          // Use an unwind-protect cleanup function so that the
-          // global_command list will be deleted in the event of an
-          // interrupt.
-
-          frame.add_fcn (cleanup_statement_list, &global_command);
-
-          fcn_ptr = primary_fcn_ptr;
-
-          if (status != 0)
-            error ("parse error while reading %s file %s",
-                   file_type.c_str(), ff.c_str ());
-          else if (reading_fcn_file && endfunction_found
-                   && max_function_depth > 1)
-            warning_with_id ("Octave:nested-functions-coerced",
-                             "nested functions are coerced into subfunctions "
-                             "in file %s", ff.c_str ());
-        }
-      else
-        {
-          tree_statement *end_of_script
-            = make_end ("endscript", input_line_number, current_input_column);
-
-          make_script (0, end_of_script);
-
-          fcn_ptr = primary_fcn_ptr;
-        }
+      // octave_base_parser constructor sets this for us.
+      frame.protect_var (LEXER);
+
+      octave_parser parser (ffile);
+
+      parser.curr_class_name = dispatch_type;
+      parser.autoloading = autoload;
+      parser.fcn_file_from_relative_lookup = relative_lookup;
+
+      parser.lexer.force_script = force_script;
+      parser.lexer.prep_for_file ();
+      parser.lexer.parsing_class_method = ! dispatch_type.empty ();
+
+      parser.lexer.fcn_file_name = file;
+      parser.lexer.fcn_file_full_name = full_file;
+
+      int status = parser.run ();
+
+      fcn_ptr = parser.primary_fcn_ptr;
+
+      if (status != 0)
+        error ("parse error while reading file %s", full_file.c_str ());
     }
   else if (require_file)
-    error ("no such file, '%s'", ff.c_str ());
+    error ("no such file, '%s'", full_file.c_str ());
   else if (! warn_for.empty ())
-    error ("%s: unable to open file '%s'", warn_for.c_str (), ff.c_str ());
+    error ("%s: unable to open file '%s'", warn_for.c_str (),
+           full_file.c_str ());
 
   return fcn_ptr;
 }
 
 std::string
 get_help_from_file (const std::string& nm, bool& symbol_found,
-                    std::string& file)
+                    std::string& full_file)
 {
   std::string retval;
 
-  file = fcn_file_in_path (nm);
+  full_file = fcn_file_in_path (nm);
+
+  std::string file = full_file;
+
+  size_t file_len = file.length ();
+
+  if ((file_len > 4 && file.substr (file_len-4) == ".oct")
+      || (file_len > 4 && file.substr (file_len-4) == ".mex")
+      || (file_len > 2 && file.substr (file_len-2) == ".m"))
+    {
+      file = octave_env::base_pathname (file);
+      file = file.substr (0, file.find_last_of ('.'));
+
+      size_t pos = file.find_last_of (file_ops::dir_sep_str ());
+      if (pos != std::string::npos)
+        file = file.substr (pos+1);
+    }
 
   if (! file.empty ())
     {
       symbol_found = true;
 
-      FILE *fptr = gnulib::fopen (file.c_str (), "r");
-
-      if (fptr)
+      octave_function *fcn
+        = parse_fcn_file (full_file, file, "", true, false, false, false, "");
+
+      if (fcn)
         {
-          unwind_protect frame;
-          frame.add_fcn (safe_fclose, fptr);
-
-          bool eof;
-          retval = gobble_leading_white_space (fptr, eof);
-
-          if (retval.empty ())
-            {
-              octave_function *fcn = parse_fcn_file (file, "");
-
-              if (fcn)
-                {
-                  retval = fcn->doc_string ();
-
-                  delete fcn;
-                }
-            }
+          retval = fcn->doc_string ();
+
+          delete fcn;
         }
     }
 
@@ -3662,7 +3380,7 @@
 string_vector
 autoloaded_functions (void)
 {
-  string_vector names (autoload_map.size());
+  string_vector names (autoload_map.size ());
 
   octave_idx_type i = 0;
   typedef std::map<std::string, std::string>::const_iterator am_iter;
@@ -3700,9 +3418,7 @@
 
   std::string file;
 
-  frame.protect_var (fcn_file_from_relative_lookup);
-
-  fcn_file_from_relative_lookup = false;
+  bool relative_lookup = false;
 
   file = nm;
 
@@ -3718,13 +3434,7 @@
         nm = nm.substr (pos+1);
     }
 
-  if (autoload)
-    {
-      frame.protect_var (autoloading);
-      autoloading = true;
-    }
-
-  fcn_file_from_relative_lookup = ! octave_env::absolute_pathname (file);
+  relative_lookup = ! octave_env::absolute_pathname (file);
 
   file = octave_env::make_absolute (file);
 
@@ -3735,23 +3445,19 @@
       if (autoload && ! fcn_name.empty ())
         nm = fcn_name;
 
-      retval = octave_dynamic_loader::load_oct (nm, file, fcn_file_from_relative_lookup);
+      retval = octave_dynamic_loader::load_oct (nm, file, relative_lookup);
     }
   else if (len > 4 && file.substr (len-4, len-1) == ".mex")
     {
       // Temporarily load m-file version of mex-file, if it exists,
       // to get the help-string to use.
-      frame.protect_var (curr_fcn_file_name);
-      frame.protect_var (curr_fcn_file_full_name);
-
-      curr_fcn_file_name = nm;
-      curr_fcn_file_full_name = file.substr (0, len - 2);
 
       octave_function *tmpfcn = parse_fcn_file (file.substr (0, len - 2),
-                                                dispatch_type, autoloading,
-                                                false);
-
-      retval = octave_dynamic_loader::load_mex (nm, file, fcn_file_from_relative_lookup);
+                                                nm, dispatch_type, false,
+                                                autoload, autoload,
+                                                relative_lookup, "");
+
+      retval = octave_dynamic_loader::load_mex (nm, file, relative_lookup);
 
       if (tmpfcn)
         retval->document (tmpfcn->doc_string ());
@@ -3759,15 +3465,8 @@
     }
   else if (len > 2)
     {
-      // These are needed by yyparse.
-
-      frame.protect_var (curr_fcn_file_name);
-      frame.protect_var (curr_fcn_file_full_name);
-
-      curr_fcn_file_name = nm;
-      curr_fcn_file_full_name = file;
-
-      retval = parse_fcn_file (file, dispatch_type, autoloading);
+      retval = parse_fcn_file (file, nm, dispatch_type, true, autoload,
+                               autoload, relative_lookup, "");
     }
 
   if (retval)
@@ -3936,12 +3635,6 @@
 
   unwind_protect frame;
 
-  frame.protect_var (curr_fcn_file_name);
-  frame.protect_var (curr_fcn_file_full_name);
-
-  curr_fcn_file_name = file_name;
-  curr_fcn_file_full_name = file_full_name;
-
   if (source_call_depth.find (file_full_name) == source_call_depth.end ())
     source_call_depth[file_full_name] = -1;
 
@@ -3970,8 +3663,9 @@
 
   if (! error_state)
     {
-      octave_function *fcn = parse_fcn_file (file_full_name, "", true,
-                                             require_file, warn_for);
+      octave_function *fcn = parse_fcn_file (file_full_name, file_name,
+                                             "", require_file, true,
+                                             false, false, warn_for);
 
       if (! error_state)
         {
@@ -4217,9 +3911,9 @@
 @group\n\
 @var{f} = @@exp;\n\
 feval (@var{f}, 1)\n\
-     @result{} 2.7183\n\
+    @result{} 2.7183\n\
 @var{f} (1)\n\
-     @result{} 2.7183\n\
+    @result{} 2.7183\n\
 @end group\n\
 @end example\n\
 \n\
@@ -4276,89 +3970,35 @@
 }
 
 octave_value_list
-eval_string (const std::string& s, bool silent, int& parse_status, int nargout)
+eval_string (const std::string& eval_str, bool silent,
+             int& parse_status, int nargout)
 {
   octave_value_list retval;
 
   unwind_protect frame;
 
-  frame.protect_var (input_line_number);
-  frame.protect_var (current_input_column);
-  frame.protect_var (get_input_from_eval_string);
-  frame.protect_var (input_from_eval_string_pending);
-  frame.protect_var (parser_end_of_input);
-  frame.protect_var (line_editing);
-  frame.protect_var (current_eval_string);
-  frame.protect_var (current_function_depth);
-  frame.protect_var (max_function_depth);
-  frame.protect_var (parsing_subfunctions);
-  frame.protect_var (endfunction_found);
-  frame.protect_var (reading_fcn_file);
-  frame.protect_var (reading_script_file);
-  frame.protect_var (reading_classdef_file);
-
-  input_line_number = 1;
-  current_input_column = 1;
-  get_input_from_eval_string = true;
-  input_from_eval_string_pending = true;
-  parser_end_of_input = false;
-  line_editing = false;
-  current_function_depth = 0;
-  max_function_depth = 0;
-  parsing_subfunctions = false;
-  endfunction_found = false;
-  reading_fcn_file = false;
-  reading_script_file = false;
-  reading_classdef_file = false;
-
-  current_eval_string = s;
-
-  YY_BUFFER_STATE old_buf = current_buffer ();
-  YY_BUFFER_STATE new_buf = create_buffer (0);
-
-  frame.add_fcn (switch_to_buffer, old_buf);
-  frame.add_fcn (delete_buffer, new_buf);
-
-  switch_to_buffer (new_buf);
+  // octave_base_parser constructor sets this for us.
+  frame.protect_var (LEXER);
+
+  octave_parser parser (eval_str);
 
   do
     {
-      reset_parser ();
-
-      frame.protect_var (global_command);
-
-      global_command = 0;
-
-      // Do this with an unwind-protect cleanup function so that the
-      // forced variables will be unmarked in the event of an
-      // interrupt.
-      symbol_table::scope_id scope = symbol_table::top_scope ();
-      frame.add_fcn (symbol_table::unmark_forced_variables, scope);
-
-      parse_status = yyparse ();
-
-      tree_statement_list *command_list = global_command;
+      parser.reset ();
+
+      parse_status = parser.run ();
 
       // Unmark forced variables.
-      // Restore previous value of global_command.
-      frame.run_top (2);
+      frame.run (1);
 
       if (parse_status == 0)
         {
-          if (command_list)
+          if (parser.stmt_list)
             {
-              unwind_protect inner_frame;
-
-              // Use an unwind-protect cleanup function so that the
-              // global_command list will be deleted in the event of an
-              // interrupt.
-
-              inner_frame.add_fcn (cleanup_statement_list, &command_list);
-
               tree_statement *stmt = 0;
 
-              if (command_list->length () == 1
-                  && (stmt = command_list->front ())
+              if (parser.stmt_list->length () == 1
+                  && (stmt = parser.stmt_list->front ())
                   && stmt->is_expression ())
                 {
                   tree_expression *expr = stmt->expression ();
@@ -4387,7 +4027,7 @@
                     retval = octave_value_list ();
                 }
               else if (nargout == 0)
-                command_list->accept (*current_evaluator);
+                parser.stmt_list->accept (*current_evaluator);
               else
                 error ("eval: invalid use of statement list");
 
@@ -4397,7 +4037,7 @@
                   || tree_continue_command::continuing)
                 break;
             }
-          else if (parser_end_of_input)
+          else if (parser.lexer.end_of_input)
             break;
         }
     }
@@ -4407,11 +4047,11 @@
 }
 
 octave_value
-eval_string (const std::string& s, bool silent, int& parse_status)
+eval_string (const std::string& eval_str, bool silent, int& parse_status)
 {
   octave_value retval;
 
-  octave_value_list tmp = eval_string (s, silent, parse_status, 1);
+  octave_value_list tmp = eval_string (eval_str, silent, parse_status, 1);
 
   if (! tmp.empty ())
     retval = tmp(0);
@@ -4457,7 +4097,7 @@
 value 3.1416 available.\n\
 \n\
 @example\n\
-eval(\"a = acos(-1);\");\n\
+eval (\"a = acos(-1);\");\n\
 @end example\n\
 \n\
 If an error occurs during the evaluation of @var{try} the @var{catch}\n\
@@ -4551,6 +4191,11 @@
 %!endfunction
 %!assert (__f(), 2)
 
+% bug #35645
+%!test
+%! [a,] = gcd (1,2);
+%! [a,b,] = gcd (1, 2);
+
 */
 
 DEFUN (assignin, args, ,
@@ -4589,7 +4234,7 @@
               if (! error_state)
                 {
                   if (valid_identifier (nm))
-                    symbol_table::varref (nm) = args(2);
+                    symbol_table::assign (nm, args(2));
                   else
                     error ("assignin: invalid variable name in argument VARNAME");
                 }
rename from src/octave.gperf
rename to libinterp/parse-tree/octave.gperf
--- a/src/octave.gperf
+++ b/libinterp/parse-tree/octave.gperf
@@ -60,6 +60,7 @@
   methods_kw,
   otherwise_kw,
   parfor_kw,
+  persistent_kw,
   properties_kw,
   return_kw,
   set_kw,
@@ -106,11 +107,11 @@
 methods, METHODS, methods_kw
 otherwise, OTHERWISE, otherwise_kw
 parfor, PARFOR, parfor_kw
-persistent, STATIC, static_kw
+persistent, PERSISTENT, persistent_kw
 properties, PROPERTIES, properties_kw
 return, FUNC_RET, return_kw
 set, SET, set_kw
-static, STATIC, static_kw
+static, PERSISTENT, static_kw
 switch, SWITCH, switch_kw
 try, TRY, try_kw
 until, UNTIL, until_kw
rename from src/parse.h
rename to libinterp/parse-tree/parse.h
--- a/src/parse.h
+++ b/libinterp/parse-tree/parse.h
@@ -28,47 +28,52 @@
 #include <string>
 
 #include <stack>
+#include <vector>
+#include <map>
 
-extern void reset_parser (void);
-extern int octave_lex (void);
-extern int octave_parse (void);
+#include "lex.h"
+#include "symtab.h"
+#include "token.h"
 
+class octave_comment_list;
+class octave_function;
+class octave_user_function;
 class tree;
-class tree_matrix;
+class tree_anon_fcn_handle;
+class tree_argument_list;
+class tree_array_list;
+class tree_cell;
+class tree_colon_expression;
+class tree_command;
+class tree_constant;
+class tree_decl_command;
+class tree_decl_init_list;
+class tree_expression;
+class tree_fcn_handle;
+class tree_function_def;
 class tree_identifier;
+class tree_if_clause;
+class tree_if_command;
+class tree_if_command_list;
+class tree_index_expression;
+class tree_matrix;
+class tree_matrix;
+class tree_parameter_list;
+class tree_statement;
 class tree_statement_list;
-class octave_function;
+class tree_statement_listtree_statement;
+class tree_switch_case;
+class tree_switch_case_list;
+class tree_switch_command;
 
 #include "oct-obj.h"
 
 // Nonzero means print parser debugging info (-d).
 extern int octave_debug;
 
-// The current input line number.
-extern int input_line_number;
-
-// The column of the current token.
-extern int current_input_column;
-
-// Buffer for help text snagged from function files.
-extern std::stack<std::string> help_buf;
-
-// TRUE means we are using readline.
-extern bool line_editing;
-
 // TRUE means we printed messages about reading startup files.
 extern bool reading_startup_message_printed;
 
-// TRUE means input is coming from startup file.
-extern bool input_from_startup_file;
-
-// Keep track of symbol table information when parsing functions.
-extern std::stack<symbol_table::scope_id> symtab_context;
-
-// Name of the current class when we are parsing class methods or
-// constructors.
-extern std::string current_class_name;
-
 extern OCTINTERP_API std::string
 get_help_from_file (const std::string& nm, bool& symbol_found,
                     std::string& file);
@@ -116,4 +121,338 @@
 
 extern OCTINTERP_API void cleanup_statement_list (tree_statement_list **lst);
 
+// Global access to currently active lexer.
+// FIXME -- to be removed after more parser+lexer refactoring.
+extern octave_base_lexer *LEXER;
+
+class
+octave_base_parser
+{
+public:
+
+  octave_base_parser (octave_base_lexer& lxr)
+    : endfunction_found (false),
+      autoloading (false), fcn_file_from_relative_lookup (false),
+      parsing_subfunctions (false), max_fcn_depth (0),
+      curr_fcn_depth (0), primary_fcn_scope (-1),
+      curr_class_name (), function_scopes (), primary_fcn_ptr (0),
+      stmt_list (0),
+      lexer (lxr)
+  {
+    init ();
+  }
+
+  ~octave_base_parser (void);
+
+  void init (void);
+
+  void reset (void);
+
+  // Error mesages for mismatched end tokens.
+  void end_error (const char *type, token::end_tok_type ettype, int l, int c);
+
+  // Check to see that end tokens are properly matched.
+  bool end_token_ok (token *tok, token::end_tok_type expected);
+
+  // Maybe print a warning if an assignment expression is used as the
+  // test in a logical expression.
+  void maybe_warn_assign_as_truth_value (tree_expression *expr);
+
+  // Maybe print a warning about switch labels that aren't constants.
+  void maybe_warn_variable_switch_label (tree_expression *expr);
+
+  // Finish building a range.
+  tree_expression *finish_colon_expression (tree_colon_expression *e);
+
+  // Build a constant.
+  tree_constant *make_constant (int op, token *tok_val);
+
+  // Build a function handle.
+  tree_fcn_handle *make_fcn_handle (token *tok_val);
+
+  // Build an anonymous function handle.
+  tree_anon_fcn_handle *
+  make_anon_fcn_handle (tree_parameter_list *param_list, tree_statement *stmt);
+
+  // Build a binary expression.
+  tree_expression *
+  make_binary_op (int op, tree_expression *op1, token *tok_val,
+                  tree_expression *op2);
+
+  // Build a boolean expression.
+  tree_expression *
+  make_boolean_op (int op, tree_expression *op1, token *tok_val,
+                   tree_expression *op2);
+
+  // Build a prefix expression.
+  tree_expression *
+  make_prefix_op (int op, tree_expression *op1, token *tok_val);
+
+  // Build a postfix expression.
+  tree_expression *
+  make_postfix_op (int op, tree_expression *op1, token *tok_val);
+
+  // Build an unwind-protect command.
+  tree_command *
+  make_unwind_command (token *unwind_tok, tree_statement_list *body,
+                       tree_statement_list *cleanup, token *end_tok,
+                       octave_comment_list *lc, octave_comment_list *mc);
+
+  // Build a try-catch command.
+  tree_command *
+  make_try_command (token *try_tok, tree_statement_list *body,
+                    tree_statement_list *cleanup, token *end_tok,
+                    octave_comment_list *lc, octave_comment_list *mc);
+
+  // Build a while command.
+  tree_command *
+  make_while_command (token *while_tok, tree_expression *expr,
+                      tree_statement_list *body, token *end_tok,
+                      octave_comment_list *lc);
+
+  // Build a do-until command.
+  tree_command *
+  make_do_until_command (token *until_tok, tree_statement_list *body,
+                         tree_expression *expr, octave_comment_list *lc);
+
+  // Build a for command.
+  tree_command *
+  make_for_command (int tok_id, token *for_tok, tree_argument_list *lhs,
+                    tree_expression *expr, tree_expression *maxproc,
+                    tree_statement_list *body, token *end_tok,
+                    octave_comment_list *lc);
+
+  // Build a break command.
+  tree_command *make_break_command (token *break_tok);
+
+  // Build a continue command.
+  tree_command *make_continue_command (token *continue_tok);
+
+  // Build a return command.
+  tree_command *make_return_command (token *return_tok);
+
+  // Start an if command.
+  tree_if_command_list *
+  start_if_command (tree_expression *expr, tree_statement_list *list);
+
+  // Finish an if command.
+  tree_if_command *
+  finish_if_command (token *if_tok, tree_if_command_list *list,
+                     token *end_tok, octave_comment_list *lc);
+
+  // Build an elseif clause.
+  tree_if_clause *
+  make_elseif_clause (token *elseif_tok, tree_expression *expr,
+                      tree_statement_list *list, octave_comment_list *lc);
+
+  // Finish a switch command.
+  tree_switch_command *
+  finish_switch_command (token *switch_tok, tree_expression *expr,
+                         tree_switch_case_list *list, token *end_tok,
+                         octave_comment_list *lc);
+
+  // Build a switch case.
+  tree_switch_case *
+  make_switch_case (token *case_tok, tree_expression *expr,
+                    tree_statement_list *list, octave_comment_list *lc);
+
+  // Build an assignment to a variable.
+  tree_expression *
+  make_assign_op (int op, tree_argument_list *lhs, token *eq_tok,
+                  tree_expression *rhs);
+
+  // Define a script.
+  void make_script (tree_statement_list *cmds, tree_statement *end_script);
+
+  // Begin defining a function.
+  octave_user_function *
+  start_function (tree_parameter_list *param_list, tree_statement_list *body,
+                  tree_statement *end_function);
+
+  // Create a no-op statement for end_function.
+  tree_statement *make_end (const std::string& type, int l, int c);
+
+  // Do most of the work for defining a function.
+  octave_user_function *
+  frob_function (const std::string& fname, octave_user_function *fcn);
+
+  // Finish defining a function.
+  tree_function_def *
+  finish_function (tree_parameter_list *ret_list,
+                   octave_user_function *fcn, octave_comment_list *lc);
+
+  // Reset state after parsing function.
+  void
+  recover_from_parsing_function (void);
+
+  // Make an index expression.
+  tree_index_expression *
+  make_index_expression (tree_expression *expr,
+                         tree_argument_list *args, char type);
+
+  // Make an indirect reference expression.
+  tree_index_expression *
+  make_indirect_ref (tree_expression *expr, const std::string&);
+
+  // Make an indirect reference expression with dynamic field name.
+  tree_index_expression *
+  make_indirect_ref (tree_expression *expr, tree_expression *field);
+
+  // Make a declaration command.
+  tree_decl_command *
+  make_decl_command (int tok, token *tok_val, tree_decl_init_list *lst);
+
+  // Validate matrix or cell
+  bool validate_array_list (tree_expression *e);
+
+  // Validate matrix object used in "[lhs] = ..." assignments.
+  tree_argument_list *validate_matrix_for_assignment (tree_expression *e);
+
+  // Finish building an array_list (common action for finish_matrix
+  // and finish_cell).
+  tree_expression *finish_array_list (tree_array_list *a);
+
+  // Finish building a matrix list.
+  tree_expression *finish_matrix (tree_matrix *m);
+
+  // Finish building a cell list.
+  tree_expression *finish_cell (tree_cell *c);
+
+  // Maybe print a warning.  Duh.
+  void maybe_warn_missing_semi (tree_statement_list *);
+
+  // Set the print flag for a statement based on the separator type.
+  tree_statement_list *
+  set_stmt_print_flag (tree_statement_list *, char, bool);
+
+  // Create a statement list.
+  tree_statement_list *make_statement_list (tree_statement *stmt);
+
+  // Append a statement to an existing statement list.
+  tree_statement_list *
+  append_statement_list (tree_statement_list *list, char sep,
+                         tree_statement *stmt, bool warn_missing_semi);
+
+  // Generic error messages.
+  void bison_error (const char *s);
+
+  // Have we found an explicit end to a function?
+  bool endfunction_found;
+
+  // TRUE means we are in the process of autoloading a function.
+  bool autoloading;
+
+  // TRUE means the current function file was found in a relative path
+  // element.
+  bool fcn_file_from_relative_lookup;
+
+  // FALSE if we are still at the primary function. Subfunctions can
+  // only be declared inside function files.
+  bool parsing_subfunctions;
+
+  // Maximum function depth detected.  Used to determine whether
+  // we have nested functions or just implicitly ended subfunctions.
+  int max_fcn_depth;
+
+  // = 0 currently outside any function.
+  // = 1 inside the primary function or a subfunction.
+  // > 1 means we are looking at a function definition that seems to be
+  //     inside a function. Note that the function still might not be a
+  //     nested function.
+  int curr_fcn_depth;
+
+  // Scope where we install all subfunctions and nested functions. Only
+  // used while reading function files.
+  symbol_table::scope_id primary_fcn_scope;
+
+  // Name of the current class when we are parsing class methods or
+  // constructors.
+  std::string curr_class_name;
+
+  // A stack holding the nested function scopes being parsed.
+  // We don't use std::stack, because we want the clear method. Also, we
+  // must access one from the top
+  std::vector<symbol_table::scope_id> function_scopes;
+
+  // Pointer to the primary user function or user script function.
+  octave_function *primary_fcn_ptr;
+
+  // Result of parsing input.
+  tree_statement_list *stmt_list;
+
+  // State of the lexer.
+  octave_base_lexer& lexer;
+
+private:
+
+  // No copying!
+
+  octave_base_parser (const octave_base_parser&);
+
+  octave_base_parser& operator = (const octave_base_parser&);
+};
+
+class
+octave_parser : public octave_base_parser
+{
+public:
+
+  octave_parser (void)
+    : octave_base_parser (*(new octave_lexer ()))
+  { }
+
+  octave_parser (FILE *file)
+    : octave_base_parser (*(new octave_lexer (file)))
+  { }
+
+  octave_parser (const std::string& eval_string)
+    : octave_base_parser (*(new octave_lexer (eval_string)))
+  { }
+
+  octave_parser (octave_lexer& lxr)
+    : octave_base_parser (lxr)
+  { }
+
+  ~octave_parser (void) { }
+
+  int run (void);
+
+private:
+
+  // No copying!
+
+  octave_parser (const octave_parser&);
+
+  octave_parser& operator = (const octave_parser&);
+};
+
+class
+octave_push_parser : public octave_base_parser
+{
+public:
+
+  octave_push_parser (void)
+    : octave_base_parser (*(new octave_push_lexer ())), parser_state (0)
+  {
+    init ();
+  }
+
+  ~octave_push_parser (void);
+
+  void init (void);
+
+  int run (const std::string& input, bool eof);
+
+private:
+
+  // Internal state of the Bison parser.
+  void *parser_state;
+
+  // No copying!
+
+  octave_push_parser (const octave_push_parser&);
+
+  octave_push_parser& operator = (const octave_push_parser&);
+};
+
 #endif
rename from src/pt-all.h
rename to libinterp/parse-tree/pt-all.h
rename from src/pt-arg-list.cc
rename to libinterp/parse-tree/pt-arg-list.cc
--- a/src/pt-arg-list.cc
+++ b/libinterp/parse-tree/pt-arg-list.cc
@@ -99,6 +99,29 @@
   return true;
 }
 
+bool
+tree_argument_list::is_valid_lvalue_list (void) const
+{
+  bool retval = true;
+
+  for (const_iterator p = begin (); p != end (); p++)
+    {
+      tree_expression *elt = *p;
+
+      // There is no need for a separate check for the magic "~" because
+      // it represented by tree_black_hole, and that is derived from
+      // tree_identifier.
+
+      if (! (elt->is_identifier () || elt->is_index_expression ()))
+        {
+          retval = false;
+          break;
+        }
+    }
+
+  return retval;
+}
+
 static const octave_value *indexed_object = 0;
 static int index_position = 0;
 static int num_indices = 0;
@@ -260,6 +283,26 @@
   return retval;
 }
 
+std::list<std::string>
+tree_argument_list::variable_names (void) const
+{
+  std::list<std::string> retval;
+
+  for (const_iterator p = begin (); p != end (); p++)
+    {
+      tree_expression *elt = *p;
+
+      if (elt->is_identifier ())
+        {
+          tree_identifier *id = dynamic_cast<tree_identifier *> (elt);
+      
+          retval.push_back (id->name ());
+        }
+    }
+
+  return retval;
+}
+
 tree_argument_list *
 tree_argument_list::dup (symbol_table::scope_id scope,
                          symbol_table::context_id context) const
rename from src/pt-arg-list.h
rename to libinterp/parse-tree/pt-arg-list.h
--- a/src/pt-arg-list.h
+++ b/libinterp/parse-tree/pt-arg-list.h
@@ -33,6 +33,7 @@
 #include "str-vec.h"
 
 #include "base-list.h"
+#include "symtab.h"
 
 // Argument lists.  Used to hold the list of expressions that are the
 // arguments in a function call or index expression.
@@ -76,12 +77,16 @@
 
   bool all_elements_are_constant (void) const;
 
+  bool is_valid_lvalue_list (void) const;
+
   octave_value_list convert_to_const_vector (const octave_value *object = 0);
 
   std::list<octave_lvalue> lvalue_list (void);
 
   string_vector get_arg_names (void) const;
 
+  std::list<std::string> variable_names (void) const;
+
   tree_argument_list *dup (symbol_table::scope_id scope,
                            symbol_table::context_id context) const;
 
new file mode 100644
--- /dev/null
+++ b/libinterp/parse-tree/pt-array-list.cc
@@ -0,0 +1,108 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+
+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 <iostream>
+
+#include "error.h"
+#include "pt-array-list.h"
+
+tree_array_list::~tree_array_list (void)
+{
+  while (! empty ())
+    {
+      iterator p = begin ();
+      delete *p;
+      erase (p);
+    }
+}
+
+bool
+tree_array_list::all_elements_are_constant (void) const
+{
+  for (const_iterator p = begin (); p != end (); p++)
+    {
+      octave_quit ();
+
+      tree_argument_list *elt = *p;
+
+      if (! elt->all_elements_are_constant ())
+        return false;
+    }
+
+  return true;
+}
+
+bool
+tree_array_list::has_magic_end (void) const
+{
+  for (const_iterator p = begin (); p != end (); p++)
+    {
+      octave_quit ();
+
+      tree_argument_list *elt = *p;
+
+      if (elt && elt->has_magic_end ())
+        return true;
+    }
+
+  return false;
+}
+
+void
+tree_array_list::copy_base (const tree_array_list& array_list)
+{
+  tree_expression::copy_base (array_list);
+}
+
+void
+tree_array_list::copy_base (const tree_array_list& array_list,
+                            symbol_table::scope_id scope,
+                            symbol_table::context_id context)
+{
+  for (const_iterator p = array_list.begin (); p != array_list.end (); p++)
+    {
+      const tree_argument_list *elt = *p;
+
+      append (elt ? elt->dup (scope, context) : 0);
+    }
+
+  copy_base (*this);
+}
+
+tree_expression *
+tree_array_list::dup (symbol_table::scope_id,
+                      symbol_table::context_id) const
+{
+  panic_impossible ();
+  return 0;
+}
+
+void
+tree_array_list::accept (tree_walker&)
+{
+  panic_impossible ();
+}
+
new file mode 100644
--- /dev/null
+++ b/libinterp/parse-tree/pt-array-list.h
@@ -0,0 +1,75 @@
+/*
+
+Copyright (C) 2013 John W. Eaton
+
+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_tree_array_list_h)
+#define octave_tree_array_list_h 1
+
+#include "base-list.h"
+#include "pt-arg-list.h"
+#include "pt-exp.h"
+#include "symtab.h"
+
+// Base class for cell arrays and matrices.
+
+class
+tree_array_list : public tree_expression,
+                  public octave_base_list<tree_argument_list *>
+{
+public:
+
+  typedef octave_base_list<tree_argument_list *>::iterator iterator;
+  typedef octave_base_list<tree_argument_list *>::const_iterator const_iterator;
+
+  tree_array_list (tree_argument_list *row = 0, int l = -1, int c = -1)
+    : tree_expression (l, c), octave_base_list<tree_argument_list *> ()
+  {
+    if (row)
+      append (row);
+  }
+
+  ~tree_array_list (void);
+
+  bool all_elements_are_constant (void) const;
+
+  bool has_magic_end (void) const;
+
+  void copy_base (const tree_array_list& array_list);
+
+  void copy_base (const tree_array_list& array_list,
+                  symbol_table::scope_id scope,
+                  symbol_table::context_id context);
+
+  tree_expression *dup (symbol_table::scope_id scope,
+                        symbol_table::context_id context) const;
+
+  void accept (tree_walker& tw);
+
+private:
+
+  // No copying!
+
+  tree_array_list (const tree_array_list&);
+
+  tree_array_list& operator = (const tree_array_list&);
+};
+
+#endif
rename from src/pt-assign.cc
rename to libinterp/parse-tree/pt-assign.cc
--- a/src/pt-assign.cc
+++ b/libinterp/parse-tree/pt-assign.cc
@@ -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,
rename from src/pt-assign.h
rename to libinterp/parse-tree/pt-assign.h
rename from src/pt-binop.cc
rename to libinterp/parse-tree/pt-binop.cc
--- a/src/pt-binop.cc
+++ b/libinterp/parse-tree/pt-binop.cc
@@ -302,7 +302,6 @@
 }
 
 /*
-
 %!test
 %! x = 0;
 %! do_braindead_shortcircuit_evaluation (0);
@@ -313,6 +312,4 @@
 %! if (1 | (x = 0))
 %! endif
 %! assert (x, 1);
-
 */
-
rename from src/pt-binop.h
rename to libinterp/parse-tree/pt-binop.h
rename from src/pt-bp.cc
rename to libinterp/parse-tree/pt-bp.cc
--- a/src/pt-bp.cc
+++ b/libinterp/parse-tree/pt-bp.cc
@@ -111,7 +111,7 @@
 }
 
 void
-tree_breakpoint::visit_static_command (tree_static_command& cmd)
+tree_breakpoint::visit_persistent_command (tree_persistent_command& cmd)
 {
   do_decl_command (cmd);
 }
@@ -214,16 +214,10 @@
 void
 tree_breakpoint::visit_if_command (tree_if_command& cmd)
 {
-  if (cmd.line () >= line)
-    take_action (cmd);
+  tree_if_command_list *lst = cmd.cmd_list ();
 
-  if (! found)
-    {
-      tree_if_command_list *lst = cmd.cmd_list ();
-
-      if (lst)
-        lst->accept (*this);
-    }
+  if (lst)
+    lst->accept (*this);
 }
 
 void
rename from src/pt-bp.h
rename to libinterp/parse-tree/pt-bp.h
--- a/src/pt-bp.h
+++ b/libinterp/parse-tree/pt-bp.h
@@ -58,7 +58,7 @@
 
   void visit_global_command (tree_global_command&);
 
-  void visit_static_command (tree_static_command&);
+  void visit_persistent_command (tree_persistent_command&);
 
   void visit_decl_elt (tree_decl_elt&);
 
@@ -134,7 +134,7 @@
 
   octave_value_list get_list (void) { return bp_list; }
 
-  int get_line (void) { return line; }
+  int get_line (void) { return found ? line : 0; }
 
  private:
 
rename from src/pt-cbinop.cc
rename to libinterp/parse-tree/pt-cbinop.cc
rename from src/pt-cbinop.h
rename to libinterp/parse-tree/pt-cbinop.h
rename from src/pt-cell.cc
rename to libinterp/parse-tree/pt-cell.cc
--- a/src/pt-cell.cc
+++ b/libinterp/parse-tree/pt-cell.cc
@@ -27,17 +27,12 @@
 #include <iostream>
 
 #include "Cell.h"
-#include "defun.h"
-#include "error.h"
 #include "oct-obj.h"
 #include "pt-arg-list.h"
-#include "pt-bp.h"
 #include "pt-exp.h"
 #include "pt-cell.h"
 #include "pt-walk.h"
-#include "utils.h"
 #include "ov.h"
-#include "variables.h"
 
 octave_value
 tree_cell::rvalue1 (int)
@@ -107,14 +102,7 @@
 {
   tree_cell *new_cell = new tree_cell (0, line (), column ());
 
-  for (const_iterator p = begin (); p != end (); p++)
-    {
-      const tree_argument_list *elt = *p;
-
-      new_cell->append (elt ? elt->dup (scope, context) : 0);
-    }
-
-  new_cell->copy_base (*this);
+  new_cell->copy_base (*this, scope, context);
 
   return new_cell;
 }
rename from src/pt-cell.h
rename to libinterp/parse-tree/pt-cell.h
--- a/src/pt-cell.h
+++ b/libinterp/parse-tree/pt-cell.h
@@ -37,15 +37,18 @@
 // General cells.
 
 class
-tree_cell : public tree_matrix
+tree_cell : public tree_array_list
 {
 public:
 
   tree_cell (tree_argument_list *row = 0, int l = -1, int c = -1)
-    : tree_matrix (row, l, c) { }
+    : tree_array_list (row, l, c)
+  { }
 
   ~tree_cell (void) { }
 
+  bool is_cell (void) const { return true; }
+
   bool rvalue_ok (void) const { return true; }
 
   octave_value rvalue1 (int nargout = 1);
rename from src/pt-check.cc
rename to libinterp/parse-tree/pt-check.cc
--- a/src/pt-check.cc
+++ b/libinterp/parse-tree/pt-check.cc
@@ -105,7 +105,7 @@
 }
 
 void
-tree_checker::visit_static_command (tree_static_command& cmd)
+tree_checker::visit_persistent_command (tree_persistent_command& cmd)
 {
   do_decl_command (cmd);
 }
@@ -554,8 +554,8 @@
 void
 tree_checker::gripe (const std::string& msg, int line)
 {
-  if (curr_fcn_file_name.empty ())
+  if (file_name.empty ())
     error ("%s", msg.c_str ());
   else
-    error ("%s: %d: %s", curr_fcn_file_name.c_str (), line, msg.c_str ());
+    error ("%s: %d: %s", file_name.c_str (), line, msg.c_str ());
 }
rename from src/pt-check.h
rename to libinterp/parse-tree/pt-check.h
--- a/src/pt-check.h
+++ b/libinterp/parse-tree/pt-check.h
@@ -35,7 +35,7 @@
 public:
 
   tree_checker (void)
-    : do_lvalue_check (false) { }
+    : do_lvalue_check (false), file_name () { }
 
   ~tree_checker (void) { }
 
@@ -51,7 +51,7 @@
 
   void visit_global_command (tree_global_command&);
 
-  void visit_static_command (tree_static_command&);
+  void visit_persistent_command (tree_persistent_command&);
 
   void visit_decl_elt (tree_decl_elt&);
 
@@ -125,6 +125,8 @@
 
   bool do_lvalue_check;
 
+  std::string file_name;
+
   void do_decl_command (tree_decl_command&);
 
   void gripe (const std::string& msg, int line);
rename from src/pt-cmd.cc
rename to libinterp/parse-tree/pt-cmd.cc
rename from src/pt-cmd.h
rename to libinterp/parse-tree/pt-cmd.h
rename from src/pt-colon.cc
rename to libinterp/parse-tree/pt-colon.cc
rename from src/pt-colon.h
rename to libinterp/parse-tree/pt-colon.h
rename from src/pt-const.cc
rename to libinterp/parse-tree/pt-const.cc
rename from src/pt-const.h
rename to libinterp/parse-tree/pt-const.h
rename from src/pt-decl.cc
rename to libinterp/parse-tree/pt-decl.cc
--- a/src/pt-decl.cc
+++ b/libinterp/parse-tree/pt-decl.cc
@@ -132,16 +132,16 @@
 // Static.
 
 tree_command *
-tree_static_command::dup (symbol_table::scope_id scope,
+tree_persistent_command::dup (symbol_table::scope_id scope,
                           symbol_table::context_id context) const
 {
   return
-    new tree_static_command (init_list ? init_list->dup (scope, context) : 0,
-                             line (), column ());
+    new tree_persistent_command (init_list ? init_list->dup (scope, context) : 0,
+                                 line (), column ());
 }
 
 void
-tree_static_command::accept (tree_walker& tw)
+tree_persistent_command::accept (tree_walker& tw)
 {
-  tw.visit_static_command (*this);
+  tw.visit_persistent_command (*this);
 }
rename from src/pt-decl.h
rename to libinterp/parse-tree/pt-decl.h
--- a/src/pt-decl.h
+++ b/libinterp/parse-tree/pt-decl.h
@@ -84,6 +84,8 @@
 
   tree_identifier *ident (void) { return id; }
 
+  std::string name (void) { return id ? id->name () : ""; }
+
   tree_expression *expression (void) { return expr; }
 
   tree_decl_elt *dup (symbol_table::scope_id scope,
@@ -207,20 +209,20 @@
   tree_global_command& operator = (const tree_global_command&);
 };
 
-// Static.
+// Persistent.
 
 class
-tree_static_command : public tree_decl_command
+tree_persistent_command : public tree_decl_command
 {
 public:
 
-  tree_static_command (int l = -1, int c = -1)
-    : tree_decl_command ("static", l, c) { }
+  tree_persistent_command (int l = -1, int c = -1)
+    : tree_decl_command ("persistent", l, c) { }
 
-  tree_static_command (tree_decl_init_list *t, int l = -1, int c = -1)
-    : tree_decl_command ("static", t, l, c) { }
+  tree_persistent_command (tree_decl_init_list *t, int l = -1, int c = -1)
+    : tree_decl_command ("persistent", t, l, c) { }
 
-  ~tree_static_command (void) { }
+  ~tree_persistent_command (void) { }
 
   tree_command *dup (symbol_table::scope_id scope,
                      symbol_table::context_id context) const;
@@ -233,9 +235,9 @@
 
   // No copying!
 
-  tree_static_command (const tree_static_command&);
+  tree_persistent_command (const tree_persistent_command&);
 
-  tree_static_command& operator = (const tree_static_command&);
+  tree_persistent_command& operator = (const tree_persistent_command&);
 };
 
 #endif
rename from src/pt-eval.cc
rename to libinterp/parse-tree/pt-eval.cc
--- a/src/pt-eval.cc
+++ b/libinterp/parse-tree/pt-eval.cc
@@ -44,6 +44,9 @@
 #include "symtab.h"
 #include "unwind-prot.h"
 
+//FIXME: This should be part of tree_evaluator
+#include "pt-jit.h"
+
 static tree_evaluator std_evaluator;
 
 tree_evaluator *current_evaluator = &std_evaluator;
@@ -129,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)
 {
@@ -215,7 +225,7 @@
 }
 
 void
-tree_evaluator::visit_static_command (tree_static_command& cmd)
+tree_evaluator::visit_persistent_command (tree_persistent_command& cmd)
 {
   if (debug_mode)
     do_breakpoint (cmd.is_breakpoint ());
@@ -303,6 +313,11 @@
 
   octave_value rhs = expr->rvalue1 ();
 
+#if HAVE_LLVM
+  if (tree_jit::execute (cmd, rhs))
+    return;
+#endif
+
   if (error_state || rhs.is_undefined ())
     return;
 
@@ -523,7 +538,7 @@
       // Make sure that any variable with the same name as the new
       // function is cleared.
 
-      symbol_table::varref (nm) = octave_value ();
+      symbol_table::assign (nm);
     }
 }
 
@@ -542,9 +557,6 @@
 void
 tree_evaluator::visit_if_command (tree_if_command& cmd)
 {
-  if (debug_mode)
-    do_breakpoint (cmd.is_breakpoint ());
-
   tree_if_command_list *lst = cmd.cmd_list ();
 
   if (lst)
@@ -560,6 +572,9 @@
 
       tree_expression *expr = tic->condition ();
 
+      if (statement_context == function || statement_context == script)
+        octave_call_stack::set_location (tic->line (), tic->column ());
+
       if (debug_mode && ! tic->is_else_clause ())
         do_breakpoint (tic->is_breakpoint ());
 
@@ -688,7 +703,7 @@
           // the state of the program we are debugging.
 
           if (! Vdebugging)
-            octave_call_stack::set_statement (&stmt);
+            octave_call_stack::set_location (stmt.line (), stmt.column ());
 
           // FIXME -- we need to distinguish functions from scripts to
           // get this right.
@@ -709,10 +724,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
@@ -736,7 +747,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;
@@ -746,6 +758,19 @@
         {
           gripe_library_execution_error ();
         }
+      catch (std::bad_alloc)
+        {
+          // FIXME -- We want to use error_with_id here so that we set
+          // the error state, give users control over this error
+          // message, and so that we set the error_state appropriately
+          // so we'll get stack trace info when appropriate.  But
+          // error_with_id will require some memory allocations.  Is
+          // there anything we can do to make those more likely to
+          // succeed?
+
+          error_with_id ("Octave:bad-alloc",
+                         "out of memory or dimension too large for Octave's index type");
+        }
     }
 }
 
@@ -840,9 +865,6 @@
             {
               tree_switch_case *t = *p;
 
-              if (debug_mode && ! t->is_default_case ())
-                do_breakpoint (t->is_breakpoint ());
-
               if (t->is_default_case () || t->label_matches (val))
                 {
                   if (error_state)
@@ -886,7 +908,6 @@
   if (try_code)
     {
       try_code->accept (*this);
-      // FIXME: should std::bad_alloc be handled here?
     }
 
   if (error_state)
@@ -922,10 +943,12 @@
   frame.protect_var (error_state);
   error_state = 0;
 
-  // We want to preserve the last statement indicator for possible
+  // We want to preserve the last location info for possible
   // backtracking.
-  frame.add_fcn (octave_call_stack::set_statement,
-                 octave_call_stack::current_statement ());
+  frame.add_fcn (octave_call_stack::set_line,
+                 octave_call_stack::current_line ());
+  frame.add_fcn (octave_call_stack::set_column,
+                 octave_call_stack::current_column ());
 
   // Similarly, if we have seen a return or break statement, allow all
   // the cleanup code to run before returning or handling the break.
@@ -970,11 +993,11 @@
 
   if (tree_break_command::breaking || tree_return_command::returning)
     {
-      frame.discard_top (2);
+      frame.discard (2);
     }
   else
     {
-      frame.run_top (2);
+      frame.run (2);
     }
 
   // We don't want to ignore errors that occur in the cleanup code, so
@@ -982,9 +1005,9 @@
   // Otherwise, set it back to what it was before.
 
   if (error_state)
-    frame.discard_top (2);
+    frame.discard (2);
   else
-    frame.run_top (2);
+    frame.run (2);
 
   frame.run ();
 }
@@ -1023,6 +1046,11 @@
   if (error_state)
     return;
 
+#if HAVE_LLVM
+  if (tree_jit::execute (cmd))
+    return;
+#endif
+
   unwind_protect frame;
 
   frame.protect_var (in_loop_command);
@@ -1111,22 +1139,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;
@@ -1143,13 +1155,36 @@
 
       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;
+
+              dbstep_flag = 0;
+            }
+          else
+            {
+              // Executing "dbstep N".  Decrease N by one and continue.
+
+              dbstep_flag--;
+            }
+
+        }
+      else if (dbstep_flag == 1
+               && octave_call_stack::current_frame () < current_frame)
+        {
+          // We stepped out from the end of a function.
+
+          current_frame = octave_call_stack::current_frame ();
 
           break_on_this_statement = true;
 
@@ -1168,9 +1203,14 @@
     }
   else if (dbstep_flag == -2)
     {
-      // We get here if we are doing a "dbstep out".
+      // We get here if we are doing a "dbstep out".  Check for end of
+      // function and whether the current frame is the same as the
+      // cached value because we want to step out from the frame where
+      // "dbstep out" was evaluated, not from any functions called from
+      // that frame.
 
-      if (is_end_of_fcn_or_script)
+      if (is_end_of_fcn_or_script
+          && octave_call_stack::current_frame () == current_frame)
         dbstep_flag = -1;
     }
 
@@ -1207,7 +1247,6 @@
 }
 
 /*
-%!error (max_recursion_depth (1, 2));
 %!test
 %! orig_val = max_recursion_depth ();
 %! old_val = max_recursion_depth (2*orig_val);
@@ -1215,6 +1254,8 @@
 %! assert (max_recursion_depth (), 2*orig_val);
 %! max_recursion_depth (orig_val);
 %! assert (max_recursion_depth (), orig_val);
+
+%!error (max_recursion_depth (1, 2))
 */
 
 DEFUN (silent_functions, args, nargout,
@@ -1236,7 +1277,6 @@
 }
 
 /*
-%!error (silent_functions (1, 2));
 %!test
 %! orig_val = silent_functions ();
 %! old_val = silent_functions (! orig_val);
@@ -1244,4 +1284,6 @@
 %! assert (silent_functions (), ! orig_val);
 %! silent_functions (orig_val);
 %! assert (silent_functions (), orig_val);
+
+%!error (silent_functions (1, 2))
 */
rename from src/pt-eval.h
rename to libinterp/parse-tree/pt-eval.h
--- a/src/pt-eval.h
+++ b/libinterp/parse-tree/pt-eval.h
@@ -60,7 +60,7 @@
 
   void visit_global_command (tree_global_command&);
 
-  void visit_static_command (tree_static_command&);
+  void visit_persistent_command (tree_persistent_command&);
 
   void visit_decl_elt (tree_decl_elt&);
 
@@ -136,6 +136,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.
   //
rename from src/pt-except.cc
rename to libinterp/parse-tree/pt-except.cc
rename from src/pt-except.h
rename to libinterp/parse-tree/pt-except.h
--- a/src/pt-except.h
+++ b/libinterp/parse-tree/pt-except.h
@@ -137,13 +137,13 @@
   // body of code.
   tree_statement_list *cleanup_code;
 
-  // Comment preceding TRY token.
+  // Comment preceding UNWIND_PROTECT token.
   octave_comment_list *lead_comm;
 
-  // Comment preceding CATCH token.
+  // Comment preceding UNWIND_PROTECT_CLEANUP token.
   octave_comment_list *mid_comm;
 
-  // Comment preceding END_TRY_CATCH token.
+  // Comment preceding END_UNWIND_PROTECT token.
   octave_comment_list *trail_comm;
 
   // No copying!
rename from src/pt-exp.cc
rename to libinterp/parse-tree/pt-exp.cc
rename from src/pt-exp.h
rename to libinterp/parse-tree/pt-exp.h
--- a/src/pt-exp.h
+++ b/libinterp/parse-tree/pt-exp.h
@@ -52,7 +52,9 @@
 
   virtual bool is_constant (void) const { return false; }
 
-  virtual bool is_matrix_constant (void) const { return false; }
+  virtual bool is_matrix (void) const { return false; }
+
+  virtual bool is_cell (void) const { return false; }
 
   virtual bool is_identifier (void) const { return false; }
 
@@ -87,6 +89,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>"; }
rename from src/pt-fcn-handle.cc
rename to libinterp/parse-tree/pt-fcn-handle.cc
rename from src/pt-fcn-handle.h
rename to libinterp/parse-tree/pt-fcn-handle.h
rename from src/pt-id.cc
rename to libinterp/parse-tree/pt-id.cc
--- a/src/pt-id.cc
+++ b/libinterp/parse-tree/pt-id.cc
@@ -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"
@@ -49,21 +50,24 @@
     return;
 
   if (l == -1 && c == -1)
-    ::error ("'%s' undefined", name ().c_str ());
+    ::error_with_id ("Octave:undefined-function",
+                     "'%s' undefined", name ().c_str ());
   else
-    ::error ("'%s' undefined near line %d column %d",
-             name ().c_str (), l, c);
+    ::error_with_id ("Octave:undefined-function",
+                     "'%s' undefined near line %d column %d",
+                     name ().c_str (), l, c);
 }
 
 octave_value_list
-tree_identifier::rvalue (int nargout)
+tree_identifier::rvalue (int nargout,
+                         const std::list<octave_lvalue> *lvalue_list)
 {
   octave_value_list retval;
 
   if (error_state)
     return retval;
 
-  octave_value val = xsym ().find ();
+  octave_value val = sym->find ();
 
   if (val.is_defined ())
     {
@@ -82,16 +86,21 @@
         {
           octave_value_list tmp_args;
 
-          retval = val.do_multi_index_op (nargout, tmp_args);
+          retval = (lvalue_list
+                    ? val.do_multi_index_op (nargout, tmp_args, lvalue_list)
+                    : val.do_multi_index_op (nargout, tmp_args));
         }
       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;
         }
     }
+  else if (sym->is_added_static ())
+    static_workspace_error ();
   else
     eval_undefined_error ();
 
@@ -114,7 +123,10 @@
 octave_lvalue
 tree_identifier::lvalue (void)
 {
-  return octave_lvalue (&(xsym().varref ()));
+  if (sym->is_added_static ())
+    static_workspace_error ();
+
+  return octave_lvalue (sym);
 }
 
 tree_identifier *
rename from src/pt-id.h
rename to libinterp/parse-tree/pt-id.h
--- a/src/pt-id.h
+++ b/libinterp/parse-tree/pt-id.h
@@ -46,12 +46,12 @@
 public:
 
   tree_identifier (int l = -1, int c = -1)
-    : tree_expression (l, c), sym (), scope (-1) { }
+    : tree_expression (l, c) { }
 
   tree_identifier (const symbol_table::symbol_record& s,
                    int l = -1, int c = -1,
                    symbol_table::scope_id sc = symbol_table::current_scope ())
-    : tree_expression (l, c), sym (s), scope (sc) { }
+    : tree_expression (l, c), sym (s, sc) { }
 
   ~tree_identifier (void) { }
 
@@ -63,9 +63,9 @@
   // accessing it through sym so that this function may remain const.
   std::string name (void) const { return sym.name (); }
 
-  bool is_defined (void) { return xsym().is_defined (); }
+  bool is_defined (void) { return sym->is_defined (); }
 
-  virtual bool is_variable (void) { return xsym().is_variable (); }
+  virtual bool is_variable (void) { return sym->is_variable (); }
 
   virtual bool is_black_hole (void) { return false; }
 
@@ -87,14 +87,14 @@
   octave_value
   do_lookup (const octave_value_list& args = octave_value_list ())
   {
-    return xsym().find (args);
+    return sym->find (args);
   }
 
-  void mark_global (void) { xsym().mark_global (); }
+  void mark_global (void) { sym->mark_global (); }
 
-  void mark_as_static (void) { xsym().init_persistent (); }
+  void mark_as_static (void) { sym->init_persistent (); }
 
-  void mark_as_formal_parameter (void) { xsym().mark_formal (); }
+  void mark_as_formal_parameter (void) { sym->mark_formal (); }
 
   // We really need to know whether this symbol referst to a variable
   // or a function, but we may not know that yet.
@@ -103,39 +103,37 @@
 
   octave_value rvalue1 (int nargout = 1);
 
-  octave_value_list rvalue (int nargout);
+  octave_value_list rvalue (int nargout)
+  {
+    return rvalue (nargout, 0);
+  }
+
+  octave_value_list rvalue (int nargout,
+                            const std::list<octave_lvalue> *lvalue_list);
 
   octave_lvalue lvalue (void);
 
   void eval_undefined_error (void);
 
+  void static_workspace_error (void)
+  {
+    ::error ("can not add variable \"%s\" to a static workspace",
+             name ().c_str ());
+  }
+
   tree_identifier *dup (symbol_table::scope_id scope,
                         symbol_table::context_id context) const;
 
   void accept (tree_walker& tw);
 
+  symbol_table::symbol_reference symbol (void) const
+  {
+    return sym;
+  }
 private:
 
   // The symbol record that this identifier references.
-  symbol_table::symbol_record sym;
-
-  symbol_table::scope_id scope;
-
-  // A script may be executed in multiple scopes.  If the last one was
-  // different from the one we are in now, update sym to be from the
-  // new scope.
-  symbol_table::symbol_record& xsym (void)
-  {
-    symbol_table::scope_id curr_scope = symbol_table::current_scope ();
-
-    if (scope != curr_scope)
-      {
-        scope = curr_scope;
-        sym = symbol_table::insert (sym.name ());
-      }
-
-    return sym;
-  }
+  symbol_table::symbol_reference sym;
 
   // No copying!
 
@@ -162,7 +160,7 @@
 
   octave_lvalue lvalue (void)
     {
-      return octave_lvalue (0); // black hole lvalue
+      return octave_lvalue (); // black hole lvalue
     }
 };
 
rename from src/pt-idx.cc
rename to libinterp/parse-tree/pt-idx.cc
--- a/src/pt-idx.cc
+++ b/libinterp/parse-tree/pt-idx.cc
@@ -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 ();
@@ -448,12 +443,7 @@
 
   if (! error_state)
     {
-      const octave_value *tro = retval.object ();
-
-      octave_value tmp;
-
-      if (tro)
-        tmp = *tro;
+      octave_value tmp = retval.value ();
 
       octave_idx_type tmpi = 0;
       std::list<octave_value_list> tmpidx;
@@ -532,7 +522,7 @@
                                  && (tmp.is_matrix_type () || tmp.is_string ()
                                      || tmp.is_cell ()));
 
-                if (i > 0 && type [i-1] == '(')
+                if (i > 0 && type[i-1] == '(')
                   {
                     octave_value_list pidx = idx.back ();
 
@@ -601,13 +591,13 @@
 
 /*
 %!test
-%! clear x
-%! clear y
+%! clear x;
+%! clear y;
 %! y = 3;
 %! x(y(end)) = 1;
 %! assert (x, [0, 0, 1]);
-%! clear x
-%! clear y
+%! clear x;
+%! clear y;
 %! y = {3};
 %! x(y{end}) = 1;
 %! assert (x, [0, 0, 1]);
rename from src/pt-idx.h
rename to libinterp/parse-tree/pt-idx.h
rename from src/pt-jump.cc
rename to libinterp/parse-tree/pt-jump.cc
rename from src/pt-jump.h
rename to libinterp/parse-tree/pt-jump.h
rename from src/pt-loop.cc
rename to libinterp/parse-tree/pt-loop.cc
--- a/src/pt-loop.cc
+++ b/libinterp/parse-tree/pt-loop.cc
@@ -35,6 +35,7 @@
 #include "pt-bp.h"
 #include "pt-cmd.h"
 #include "pt-exp.h"
+#include "pt-jit.h"
 #include "pt-jump.h"
 #include "pt-loop.h"
 #include "pt-stmt.h"
@@ -49,6 +50,9 @@
   delete list;
   delete lead_comm;
   delete trail_comm;
+#ifdef HAVE_LLVM
+  delete compiled;
+#endif
 }
 
 tree_command *
@@ -97,6 +101,9 @@
   delete list;
   delete lead_comm;
   delete trail_comm;
+#ifdef HAVE_LLVM
+  delete compiled;
+#endif
 }
 
 tree_command *
rename from src/pt-loop.h
rename to libinterp/parse-tree/pt-loop.h
--- a/src/pt-loop.h
+++ b/libinterp/parse-tree/pt-loop.h
@@ -36,6 +36,8 @@
 #include "pt-cmd.h"
 #include "symtab.h"
 
+class jit_info;
+
 // While.
 
 class
@@ -45,21 +47,33 @@
 
   tree_while_command (int l = -1, int c = -1)
     : tree_command (l, c), expr (0), list (0), lead_comm (0),
-      trail_comm (0) { }
+      trail_comm (0)
+#ifdef HAVE_LLVM
+    , compiled (0)
+#endif
+  { }
 
   tree_while_command (tree_expression *e,
                       octave_comment_list *lc = 0,
                       octave_comment_list *tc = 0,
                       int l = -1, int c = -1)
     : tree_command (l, c), expr (e), list (0), lead_comm (lc),
-      trail_comm (tc) { }
+      trail_comm (tc)
+#ifdef HAVE_LLVM
+    , compiled (0)
+#endif
+  { }
 
   tree_while_command (tree_expression *e, tree_statement_list *lst,
                       octave_comment_list *lc = 0,
                       octave_comment_list *tc = 0,
                       int l = -1, int c = -1)
     : tree_command (l, c), expr (e), list (lst), lead_comm (lc),
-      trail_comm (tc) { }
+      trail_comm (tc)
+#ifdef HAVE_LLVM
+    , compiled (0)
+#endif
+  { }
 
   ~tree_while_command (void);
 
@@ -76,6 +90,19 @@
 
   void accept (tree_walker& tw);
 
+#ifdef HAVE_LLVM
+  // some functions use by tree_jit
+  jit_info *get_info (void) const
+  {
+    return compiled;
+  }
+
+  void stash_info (jit_info *jinfo)
+  {
+    compiled = jinfo;
+  }
+#endif
+
 protected:
 
   // Expression to test.
@@ -92,6 +119,11 @@
 
 private:
 
+#ifdef HAVE_LLVM
+  // compiled version of the loop
+  jit_info *compiled;
+#endif
+
   // No copying!
 
   tree_while_command (const tree_while_command&);
@@ -146,7 +178,11 @@
 
   tree_simple_for_command (int l = -1, int c = -1)
     : tree_command (l, c), parallel (false), lhs (0), expr (0),
-      maxproc (0), list (0), lead_comm (0), trail_comm (0) { }
+      maxproc (0), list (0), lead_comm (0), trail_comm (0)
+#ifdef HAVE_LLVM
+    , compiled (0)
+#endif
+  { }
 
   tree_simple_for_command (bool parallel_arg, tree_expression *le,
                            tree_expression *re,
@@ -157,7 +193,11 @@
                            int l = -1, int c = -1)
     : tree_command (l, c), parallel (parallel_arg), lhs (le),
       expr (re), maxproc (maxproc_arg), list (lst),
-      lead_comm (lc), trail_comm (tc) { }
+      lead_comm (lc), trail_comm (tc)
+#ifdef HAVE_LLVM
+    , compiled (0)
+#endif
+  { }
 
   ~tree_simple_for_command (void);
 
@@ -180,8 +220,20 @@
 
   void accept (tree_walker& tw);
 
+#ifdef HAVE_LLVM
+  // some functions use by tree_jit
+  jit_info *get_info (void) const
+  {
+    return compiled;
+  }
+
+  void stash_info (jit_info *jinfo)
+  {
+    compiled = jinfo;
+  }
+#endif
+
 private:
-
   // TRUE means operate in parallel (subject to the value of the
   // maxproc expression).
   bool parallel;
@@ -205,6 +257,9 @@
   // Comment preceding ENDFOR token.
   octave_comment_list *trail_comm;
 
+  // compiled version of the loop
+  jit_info *compiled;
+
   // No copying!
 
   tree_simple_for_command (const tree_simple_for_command&);
rename from src/pt-mat.cc
rename to libinterp/parse-tree/pt-mat.cc
--- a/src/pt-mat.cc
+++ b/libinterp/parse-tree/pt-mat.cc
@@ -402,7 +402,7 @@
               first_elem = false;
               dv = this_elt_dv;
             }
-          else if (! dv.hvcat (this_elt_dv, 1))
+          else if ((! any_class) && (! dv.hvcat (this_elt_dv, 1)))
             {
               eval_error ("horizontal dimensions mismatch", dv, this_elt_dv);
               break;
@@ -644,7 +644,7 @@
                 dv(1) = this_elt_nc;
               dv(0) += this_elt_nr;
             }
-          else if (! dv.hvcat (this_elt_dv, 0))
+          else if ((!any_class) && (!dv.hvcat (this_elt_dv, 0)))
             {
               eval_error ("vertical dimensions mismatch", dv, this_elt_dv);
               return;
@@ -655,48 +655,6 @@
   ok = ! error_state;
 }
 
-tree_matrix::~tree_matrix (void)
-{
-  while (! empty ())
-    {
-      iterator p = begin ();
-      delete *p;
-      erase (p);
-    }
-}
-
-bool
-tree_matrix::has_magic_end (void) const
-{
-  for (const_iterator p = begin (); p != end (); p++)
-    {
-      octave_quit ();
-
-      tree_argument_list *elt = *p;
-
-      if (elt && elt->has_magic_end ())
-        return true;
-    }
-
-  return false;
-}
-
-bool
-tree_matrix::all_elements_are_constant (void) const
-{
-  for (const_iterator p = begin (); p != end (); p++)
-    {
-      octave_quit ();
-
-      tree_argument_list *elt = *p;
-
-      if (! elt->all_elements_are_constant ())
-        return false;
-    }
-
-  return true;
-}
-
 octave_value_list
 tree_matrix::rvalue (int nargout)
 {
@@ -784,7 +742,7 @@
         {
           // Optimize all scalars case.
           result.clear (dv);
-          assert (result.numel () == row.length ());
+          assert (static_cast<size_t> (result.numel ()) == row.length ());
           octave_idx_type i = 0;
           for (tm_row_const::iterator q = row.begin ();
                q != row.end () && ! error_state; q++)
@@ -1110,7 +1068,7 @@
                     }
                 }
 
-              ctmp = (*(tmp.begin() -> begin()));
+              ctmp = (*(tmp.begin () -> begin ()));
 
             found_non_empty:
 
@@ -1174,14 +1132,7 @@
 {
   tree_matrix *new_matrix = new tree_matrix (0, line (), column ());
 
-  for (const_iterator p = begin (); p != end (); p++)
-    {
-      const tree_argument_list *elt = *p;
-
-      new_matrix->append (elt ? elt->dup (scope, context) : 0);
-    }
-
-  new_matrix->copy_base (*this);
+  new_matrix->copy_base (*this, scope, context);
 
   return new_matrix;
 }
@@ -1193,198 +1144,198 @@
 }
 
 /*
-%% test concatenation with all zero matrices
-%!assert([ '' 65*ones(1,10) ], 'AAAAAAAAAA');
-%!assert([ 65*ones(1,10) '' ], 'AAAAAAAAAA');
+## test concatenation with all zero matrices
+%!assert ([ "" 65*ones(1,10) ], "AAAAAAAAAA");
+%!assert ([ 65*ones(1,10) "" ], "AAAAAAAAAA");
 
 %!test
-%! c = {'foo'; 'bar'; 'bazoloa'};
-%! assert ([c; 'a'; 'bc'; 'def'], {'foo'; 'bar'; 'bazoloa'; 'a'; 'bc'; 'def'});
+%! c = {"foo"; "bar"; "bazoloa"};
+%! assert ([c; "a"; "bc"; "def"], {"foo"; "bar"; "bazoloa"; "a"; "bc"; "def"});
 
-%!assert (class ([int64(1), int64(1)]), 'int64')
-%!assert (class ([int64(1), int32(1)]), 'int64')
-%!assert (class ([int64(1), int16(1)]), 'int64')
-%!assert (class ([int64(1), int8(1)]), 'int64')
-%!assert (class ([int64(1), uint64(1)]), 'int64')
-%!assert (class ([int64(1), uint32(1)]), 'int64')
-%!assert (class ([int64(1), uint16(1)]), 'int64')
-%!assert (class ([int64(1), uint8(1)]), 'int64')
-%!assert (class ([int64(1), single(1)]), 'int64')
-%!assert (class ([int64(1), double(1)]), 'int64')
-%!assert (class ([int64(1), cell(1)]), 'cell')
-%!assert (class ([int64(1), true]), 'int64')
-%!assert (class ([int64(1), 'a']), 'char')
+%!assert (class ([int64(1), int64(1)]), "int64")
+%!assert (class ([int64(1), int32(1)]), "int64")
+%!assert (class ([int64(1), int16(1)]), "int64")
+%!assert (class ([int64(1), int8(1)]), "int64")
+%!assert (class ([int64(1), uint64(1)]), "int64")
+%!assert (class ([int64(1), uint32(1)]), "int64")
+%!assert (class ([int64(1), uint16(1)]), "int64")
+%!assert (class ([int64(1), uint8(1)]), "int64")
+%!assert (class ([int64(1), single(1)]), "int64")
+%!assert (class ([int64(1), double(1)]), "int64")
+%!assert (class ([int64(1), cell(1)]), "cell")
+%!assert (class ([int64(1), true]), "int64")
+%!assert (class ([int64(1), "a"]), "char")
 
-%!assert (class ([int32(1), int64(1)]), 'int32')
-%!assert (class ([int32(1), int32(1)]), 'int32')
-%!assert (class ([int32(1), int16(1)]), 'int32')
-%!assert (class ([int32(1), int8(1)]), 'int32')
-%!assert (class ([int32(1), uint64(1)]), 'int32')
-%!assert (class ([int32(1), uint32(1)]), 'int32')
-%!assert (class ([int32(1), uint16(1)]), 'int32')
-%!assert (class ([int32(1), uint8(1)]), 'int32')
-%!assert (class ([int32(1), single(1)]), 'int32')
-%!assert (class ([int32(1), double(1)]), 'int32')
-%!assert (class ([int32(1), cell(1)]), 'cell')
-%!assert (class ([int32(1), true]), 'int32')
-%!assert (class ([int32(1), 'a']), 'char')
+%!assert (class ([int32(1), int64(1)]), "int32")
+%!assert (class ([int32(1), int32(1)]), "int32")
+%!assert (class ([int32(1), int16(1)]), "int32")
+%!assert (class ([int32(1), int8(1)]), "int32")
+%!assert (class ([int32(1), uint64(1)]), "int32")
+%!assert (class ([int32(1), uint32(1)]), "int32")
+%!assert (class ([int32(1), uint16(1)]), "int32")
+%!assert (class ([int32(1), uint8(1)]), "int32")
+%!assert (class ([int32(1), single(1)]), "int32")
+%!assert (class ([int32(1), double(1)]), "int32")
+%!assert (class ([int32(1), cell(1)]), "cell")
+%!assert (class ([int32(1), true]), "int32")
+%!assert (class ([int32(1), "a"]), "char")
 
-%!assert (class ([int16(1), int64(1)]), 'int16')
-%!assert (class ([int16(1), int32(1)]), 'int16')
-%!assert (class ([int16(1), int16(1)]), 'int16')
-%!assert (class ([int16(1), int8(1)]), 'int16')
-%!assert (class ([int16(1), uint64(1)]), 'int16')
-%!assert (class ([int16(1), uint32(1)]), 'int16')
-%!assert (class ([int16(1), uint16(1)]), 'int16')
-%!assert (class ([int16(1), uint8(1)]), 'int16')
-%!assert (class ([int16(1), single(1)]), 'int16')
-%!assert (class ([int16(1), double(1)]), 'int16')
-%!assert (class ([int16(1), cell(1)]), 'cell')
-%!assert (class ([int16(1), true]), 'int16')
-%!assert (class ([int16(1), 'a']), 'char')
+%!assert (class ([int16(1), int64(1)]), "int16")
+%!assert (class ([int16(1), int32(1)]), "int16")
+%!assert (class ([int16(1), int16(1)]), "int16")
+%!assert (class ([int16(1), int8(1)]), "int16")
+%!assert (class ([int16(1), uint64(1)]), "int16")
+%!assert (class ([int16(1), uint32(1)]), "int16")
+%!assert (class ([int16(1), uint16(1)]), "int16")
+%!assert (class ([int16(1), uint8(1)]), "int16")
+%!assert (class ([int16(1), single(1)]), "int16")
+%!assert (class ([int16(1), double(1)]), "int16")
+%!assert (class ([int16(1), cell(1)]), "cell")
+%!assert (class ([int16(1), true]), "int16")
+%!assert (class ([int16(1), "a"]), "char")
 
-%!assert (class ([int8(1), int64(1)]), 'int8')
-%!assert (class ([int8(1), int32(1)]), 'int8')
-%!assert (class ([int8(1), int16(1)]), 'int8')
-%!assert (class ([int8(1), int8(1)]), 'int8')
-%!assert (class ([int8(1), uint64(1)]), 'int8')
-%!assert (class ([int8(1), uint32(1)]), 'int8')
-%!assert (class ([int8(1), uint16(1)]), 'int8')
-%!assert (class ([int8(1), uint8(1)]), 'int8')
-%!assert (class ([int8(1), single(1)]), 'int8')
-%!assert (class ([int8(1), double(1)]), 'int8')
-%!assert (class ([int8(1), cell(1)]), 'cell')
-%!assert (class ([int8(1), true]), 'int8')
-%!assert (class ([int8(1), 'a']), 'char')
+%!assert (class ([int8(1), int64(1)]), "int8")
+%!assert (class ([int8(1), int32(1)]), "int8")
+%!assert (class ([int8(1), int16(1)]), "int8")
+%!assert (class ([int8(1), int8(1)]), "int8")
+%!assert (class ([int8(1), uint64(1)]), "int8")
+%!assert (class ([int8(1), uint32(1)]), "int8")
+%!assert (class ([int8(1), uint16(1)]), "int8")
+%!assert (class ([int8(1), uint8(1)]), "int8")
+%!assert (class ([int8(1), single(1)]), "int8")
+%!assert (class ([int8(1), double(1)]), "int8")
+%!assert (class ([int8(1), cell(1)]), "cell")
+%!assert (class ([int8(1), true]), "int8")
+%!assert (class ([int8(1), "a"]), "char")
 
-%!assert (class ([uint64(1), int64(1)]), 'uint64')
-%!assert (class ([uint64(1), int32(1)]), 'uint64')
-%!assert (class ([uint64(1), int16(1)]), 'uint64')
-%!assert (class ([uint64(1), int8(1)]), 'uint64')
-%!assert (class ([uint64(1), uint64(1)]), 'uint64')
-%!assert (class ([uint64(1), uint32(1)]), 'uint64')
-%!assert (class ([uint64(1), uint16(1)]), 'uint64')
-%!assert (class ([uint64(1), uint8(1)]), 'uint64')
-%!assert (class ([uint64(1), single(1)]), 'uint64')
-%!assert (class ([uint64(1), double(1)]), 'uint64')
-%!assert (class ([uint64(1), cell(1)]), 'cell')
-%!assert (class ([uint64(1), true]), 'uint64')
-%!assert (class ([uint64(1), 'a']), 'char')
+%!assert (class ([uint64(1), int64(1)]), "uint64")
+%!assert (class ([uint64(1), int32(1)]), "uint64")
+%!assert (class ([uint64(1), int16(1)]), "uint64")
+%!assert (class ([uint64(1), int8(1)]), "uint64")
+%!assert (class ([uint64(1), uint64(1)]), "uint64")
+%!assert (class ([uint64(1), uint32(1)]), "uint64")
+%!assert (class ([uint64(1), uint16(1)]), "uint64")
+%!assert (class ([uint64(1), uint8(1)]), "uint64")
+%!assert (class ([uint64(1), single(1)]), "uint64")
+%!assert (class ([uint64(1), double(1)]), "uint64")
+%!assert (class ([uint64(1), cell(1)]), "cell")
+%!assert (class ([uint64(1), true]), "uint64")
+%!assert (class ([uint64(1), "a"]), "char")
 
-%!assert (class ([uint32(1), int64(1)]), 'uint32')
-%!assert (class ([uint32(1), int32(1)]), 'uint32')
-%!assert (class ([uint32(1), int16(1)]), 'uint32')
-%!assert (class ([uint32(1), int8(1)]), 'uint32')
-%!assert (class ([uint32(1), uint64(1)]), 'uint32')
-%!assert (class ([uint32(1), uint32(1)]), 'uint32')
-%!assert (class ([uint32(1), uint16(1)]), 'uint32')
-%!assert (class ([uint32(1), uint8(1)]), 'uint32')
-%!assert (class ([uint32(1), single(1)]), 'uint32')
-%!assert (class ([uint32(1), double(1)]), 'uint32')
-%!assert (class ([uint32(1), cell(1)]), 'cell')
-%!assert (class ([uint32(1), true]), 'uint32')
-%!assert (class ([uint32(1), 'a']), 'char')
+%!assert (class ([uint32(1), int64(1)]), "uint32")
+%!assert (class ([uint32(1), int32(1)]), "uint32")
+%!assert (class ([uint32(1), int16(1)]), "uint32")
+%!assert (class ([uint32(1), int8(1)]), "uint32")
+%!assert (class ([uint32(1), uint64(1)]), "uint32")
+%!assert (class ([uint32(1), uint32(1)]), "uint32")
+%!assert (class ([uint32(1), uint16(1)]), "uint32")
+%!assert (class ([uint32(1), uint8(1)]), "uint32")
+%!assert (class ([uint32(1), single(1)]), "uint32")
+%!assert (class ([uint32(1), double(1)]), "uint32")
+%!assert (class ([uint32(1), cell(1)]), "cell")
+%!assert (class ([uint32(1), true]), "uint32")
+%!assert (class ([uint32(1), "a"]), "char")
 
-%!assert (class ([uint16(1), int64(1)]), 'uint16')
-%!assert (class ([uint16(1), int32(1)]), 'uint16')
-%!assert (class ([uint16(1), int16(1)]), 'uint16')
-%!assert (class ([uint16(1), int8(1)]), 'uint16')
-%!assert (class ([uint16(1), uint64(1)]), 'uint16')
-%!assert (class ([uint16(1), uint32(1)]), 'uint16')
-%!assert (class ([uint16(1), uint16(1)]), 'uint16')
-%!assert (class ([uint16(1), uint8(1)]), 'uint16')
-%!assert (class ([uint16(1), single(1)]), 'uint16')
-%!assert (class ([uint16(1), double(1)]), 'uint16')
-%!assert (class ([uint16(1), cell(1)]), 'cell')
-%!assert (class ([uint16(1), true]), 'uint16')
-%!assert (class ([uint16(1), 'a']), 'char')
+%!assert (class ([uint16(1), int64(1)]), "uint16")
+%!assert (class ([uint16(1), int32(1)]), "uint16")
+%!assert (class ([uint16(1), int16(1)]), "uint16")
+%!assert (class ([uint16(1), int8(1)]), "uint16")
+%!assert (class ([uint16(1), uint64(1)]), "uint16")
+%!assert (class ([uint16(1), uint32(1)]), "uint16")
+%!assert (class ([uint16(1), uint16(1)]), "uint16")
+%!assert (class ([uint16(1), uint8(1)]), "uint16")
+%!assert (class ([uint16(1), single(1)]), "uint16")
+%!assert (class ([uint16(1), double(1)]), "uint16")
+%!assert (class ([uint16(1), cell(1)]), "cell")
+%!assert (class ([uint16(1), true]), "uint16")
+%!assert (class ([uint16(1), "a"]), "char")
 
-%!assert (class ([uint8(1), int64(1)]), 'uint8')
-%!assert (class ([uint8(1), int32(1)]), 'uint8')
-%!assert (class ([uint8(1), int16(1)]), 'uint8')
-%!assert (class ([uint8(1), int8(1)]), 'uint8')
-%!assert (class ([uint8(1), uint64(1)]), 'uint8')
-%!assert (class ([uint8(1), uint32(1)]), 'uint8')
-%!assert (class ([uint8(1), uint16(1)]), 'uint8')
-%!assert (class ([uint8(1), uint8(1)]), 'uint8')
-%!assert (class ([uint8(1), single(1)]), 'uint8')
-%!assert (class ([uint8(1), double(1)]), 'uint8')
-%!assert (class ([uint8(1), cell(1)]), 'cell')
-%!assert (class ([uint8(1), true]), 'uint8')
-%!assert (class ([uint8(1), 'a']), 'char')
+%!assert (class ([uint8(1), int64(1)]), "uint8")
+%!assert (class ([uint8(1), int32(1)]), "uint8")
+%!assert (class ([uint8(1), int16(1)]), "uint8")
+%!assert (class ([uint8(1), int8(1)]), "uint8")
+%!assert (class ([uint8(1), uint64(1)]), "uint8")
+%!assert (class ([uint8(1), uint32(1)]), "uint8")
+%!assert (class ([uint8(1), uint16(1)]), "uint8")
+%!assert (class ([uint8(1), uint8(1)]), "uint8")
+%!assert (class ([uint8(1), single(1)]), "uint8")
+%!assert (class ([uint8(1), double(1)]), "uint8")
+%!assert (class ([uint8(1), cell(1)]), "cell")
+%!assert (class ([uint8(1), true]), "uint8")
+%!assert (class ([uint8(1), "a"]), "char")
 
-%!assert (class ([single(1), int64(1)]), 'int64')
-%!assert (class ([single(1), int32(1)]), 'int32')
-%!assert (class ([single(1), int16(1)]), 'int16')
-%!assert (class ([single(1), int8(1)]), 'int8')
-%!assert (class ([single(1), uint64(1)]), 'uint64')
-%!assert (class ([single(1), uint32(1)]), 'uint32')
-%!assert (class ([single(1), uint16(1)]), 'uint16')
-%!assert (class ([single(1), uint8(1)]), 'uint8')
-%!assert (class ([single(1), single(1)]), 'single')
-%!assert (class ([single(1), double(1)]), 'single')
-%!assert (class ([single(1), cell(1)]), 'cell')
-%!assert (class ([single(1), true]), 'single')
-%!assert (class ([single(1), 'a']), 'char')
+%!assert (class ([single(1), int64(1)]), "int64")
+%!assert (class ([single(1), int32(1)]), "int32")
+%!assert (class ([single(1), int16(1)]), "int16")
+%!assert (class ([single(1), int8(1)]), "int8")
+%!assert (class ([single(1), uint64(1)]), "uint64")
+%!assert (class ([single(1), uint32(1)]), "uint32")
+%!assert (class ([single(1), uint16(1)]), "uint16")
+%!assert (class ([single(1), uint8(1)]), "uint8")
+%!assert (class ([single(1), single(1)]), "single")
+%!assert (class ([single(1), double(1)]), "single")
+%!assert (class ([single(1), cell(1)]), "cell")
+%!assert (class ([single(1), true]), "single")
+%!assert (class ([single(1), "a"]), "char")
 
-%!assert (class ([double(1), int64(1)]), 'int64')
-%!assert (class ([double(1), int32(1)]), 'int32')
-%!assert (class ([double(1), int16(1)]), 'int16')
-%!assert (class ([double(1), int8(1)]), 'int8')
-%!assert (class ([double(1), uint64(1)]), 'uint64')
-%!assert (class ([double(1), uint32(1)]), 'uint32')
-%!assert (class ([double(1), uint16(1)]), 'uint16')
-%!assert (class ([double(1), uint8(1)]), 'uint8')
-%!assert (class ([double(1), single(1)]), 'single')
-%!assert (class ([double(1), double(1)]), 'double')
-%!assert (class ([double(1), cell(1)]), 'cell')
-%!assert (class ([double(1), true]), 'double')
-%!assert (class ([double(1), 'a']), 'char')
+%!assert (class ([double(1), int64(1)]), "int64")
+%!assert (class ([double(1), int32(1)]), "int32")
+%!assert (class ([double(1), int16(1)]), "int16")
+%!assert (class ([double(1), int8(1)]), "int8")
+%!assert (class ([double(1), uint64(1)]), "uint64")
+%!assert (class ([double(1), uint32(1)]), "uint32")
+%!assert (class ([double(1), uint16(1)]), "uint16")
+%!assert (class ([double(1), uint8(1)]), "uint8")
+%!assert (class ([double(1), single(1)]), "single")
+%!assert (class ([double(1), double(1)]), "double")
+%!assert (class ([double(1), cell(1)]), "cell")
+%!assert (class ([double(1), true]), "double")
+%!assert (class ([double(1), "a"]), "char")
 
-%!assert (class ([cell(1), int64(1)]), 'cell')
-%!assert (class ([cell(1), int32(1)]), 'cell')
-%!assert (class ([cell(1), int16(1)]), 'cell')
-%!assert (class ([cell(1), int8(1)]), 'cell')
-%!assert (class ([cell(1), uint64(1)]), 'cell')
-%!assert (class ([cell(1), uint32(1)]), 'cell')
-%!assert (class ([cell(1), uint16(1)]), 'cell')
-%!assert (class ([cell(1), uint8(1)]), 'cell')
-%!assert (class ([cell(1), single(1)]), 'cell')
-%!assert (class ([cell(1), double(1)]), 'cell')
-%!assert (class ([cell(1), cell(1)]), 'cell')
-%!assert (class ([cell(1), true]), 'cell')
-%!assert (class ([cell(1), 'a']), 'cell')
+%!assert (class ([cell(1), int64(1)]), "cell")
+%!assert (class ([cell(1), int32(1)]), "cell")
+%!assert (class ([cell(1), int16(1)]), "cell")
+%!assert (class ([cell(1), int8(1)]), "cell")
+%!assert (class ([cell(1), uint64(1)]), "cell")
+%!assert (class ([cell(1), uint32(1)]), "cell")
+%!assert (class ([cell(1), uint16(1)]), "cell")
+%!assert (class ([cell(1), uint8(1)]), "cell")
+%!assert (class ([cell(1), single(1)]), "cell")
+%!assert (class ([cell(1), double(1)]), "cell")
+%!assert (class ([cell(1), cell(1)]), "cell")
+%!assert (class ([cell(1), true]), "cell")
+%!assert (class ([cell(1), "a"]), "cell")
 
-%!assert (class ([true, int64(1)]), 'int64')
-%!assert (class ([true, int32(1)]), 'int32')
-%!assert (class ([true, int16(1)]), 'int16')
-%!assert (class ([true, int8(1)]), 'int8')
-%!assert (class ([true, uint64(1)]), 'uint64')
-%!assert (class ([true, uint32(1)]), 'uint32')
-%!assert (class ([true, uint16(1)]), 'uint16')
-%!assert (class ([true, uint8(1)]), 'uint8')
-%!assert (class ([true, single(1)]), 'single')
-%!assert (class ([true, double(1)]), 'double')
-%!assert (class ([true, cell(1)]), 'cell')
-%!assert (class ([true, true]), 'logical')
-%!assert (class ([true, 'a']), 'char')
+%!assert (class ([true, int64(1)]), "int64")
+%!assert (class ([true, int32(1)]), "int32")
+%!assert (class ([true, int16(1)]), "int16")
+%!assert (class ([true, int8(1)]), "int8")
+%!assert (class ([true, uint64(1)]), "uint64")
+%!assert (class ([true, uint32(1)]), "uint32")
+%!assert (class ([true, uint16(1)]), "uint16")
+%!assert (class ([true, uint8(1)]), "uint8")
+%!assert (class ([true, single(1)]), "single")
+%!assert (class ([true, double(1)]), "double")
+%!assert (class ([true, cell(1)]), "cell")
+%!assert (class ([true, true]), "logical")
+%!assert (class ([true, "a"]), "char")
 
-%!assert (class (['a', int64(1)]), 'char')
-%!assert (class (['a', int32(1)]), 'char')
-%!assert (class (['a', int16(1)]), 'char')
-%!assert (class (['a', int8(1)]), 'char')
-%!assert (class (['a', int64(1)]), 'char')
-%!assert (class (['a', int32(1)]), 'char')
-%!assert (class (['a', int16(1)]), 'char')
-%!assert (class (['a', int8(1)]), 'char')
-%!assert (class (['a', single(1)]), 'char')
-%!assert (class (['a', double(1)]), 'char')
-%!assert (class (['a', cell(1)]), 'cell')
-%!assert (class (['a', true]), 'char')
-%!assert (class (['a', 'a']), 'char')
+%!assert (class (["a", int64(1)]), "char")
+%!assert (class (["a", int32(1)]), "char")
+%!assert (class (["a", int16(1)]), "char")
+%!assert (class (["a", int8(1)]), "char")
+%!assert (class (["a", int64(1)]), "char")
+%!assert (class (["a", int32(1)]), "char")
+%!assert (class (["a", int16(1)]), "char")
+%!assert (class (["a", int8(1)]), "char")
+%!assert (class (["a", single(1)]), "char")
+%!assert (class (["a", double(1)]), "char")
+%!assert (class (["a", cell(1)]), "cell")
+%!assert (class (["a", true]), "char")
+%!assert (class (["a", "a"]), "char")
 
-%!assert (class ([cell(1), struct('foo', 'bar')]), 'cell')
-%!error [struct('foo', 'bar'), cell(1)];
+%!assert (class ([cell(1), struct("foo", "bar")]), "cell")
+%!error [struct("foo", "bar"), cell(1)]
 */
 
 DEFUN (string_fill_char, args, nargout,
@@ -1400,9 +1351,9 @@
 @group\n\
 string_fill_char (\"X\");\n\
 [ \"these\"; \"are\"; \"strings\" ]\n\
-     @result{} \"theseXX\"\n\
-        \"areXXXX\"\n\
-        \"strings\"\n\
+      @result{}  \"theseXX\"\n\
+          \"areXXXX\"\n\
+          \"strings\"\n\
 @end group\n\
 @end example\n\
 \n\
@@ -1415,9 +1366,8 @@
 }
 
 /*
-%!error (string_fill_char (1, 2));
-%% string_fill_char() function call must be outside of %!test block
-%% due to the way a %!test block is wrapped inside a function
+## string_fill_char() function call must be outside of %!test block
+## due to the way a %!test block is wrapped inside a function
 %!shared orig_val, old_val
 %! orig_val = string_fill_char ();
 %! old_val  = string_fill_char ("X");
@@ -1427,4 +1377,6 @@
 %! assert (["these"; "are"; "strings"], ["theseXX"; "areXXXX"; "strings"]);
 %! string_fill_char (orig_val);
 %! assert (string_fill_char (), orig_val);
+
+%!error (string_fill_char (1, 2))
 */
rename from src/pt-mat.h
rename to libinterp/parse-tree/pt-mat.h
--- a/src/pt-mat.h
+++ b/libinterp/parse-tree/pt-mat.h
@@ -32,6 +32,7 @@
 class tree_walker;
 
 #include "base-list.h"
+#include "pt-array-list.h"
 #include "pt-exp.h"
 #include "symtab.h"
 
@@ -39,23 +40,17 @@
 // other matrices, variables, and functions.
 
 class
-tree_matrix : public tree_expression,
-              public octave_base_list<tree_argument_list *>
+tree_matrix : public tree_array_list
 {
 public:
 
   tree_matrix (tree_argument_list *row = 0, int l = -1, int c = -1)
-    : tree_expression (l, c)
-  {
-    if (row)
-      append (row);
-  }
+    : tree_array_list (row, l, c)
+  { }
 
-  ~tree_matrix (void);
+  ~tree_matrix (void) { }
 
-  bool has_magic_end (void) const;
-
-  bool all_elements_are_constant (void) const;
+  bool is_matrix (void) const { return true; }
 
   bool rvalue_ok (void) const { return true; }
 
rename from src/pt-misc.cc
rename to libinterp/parse-tree/pt-misc.cc
--- a/src/pt-misc.cc
+++ b/libinterp/parse-tree/pt-misc.cc
@@ -228,6 +228,21 @@
     }
 }
 
+std::list<std::string>
+tree_parameter_list::variable_names (void) const
+{
+  std::list<std::string> retval;
+
+  for (const_iterator p = begin (); p != end (); p++)
+    {
+      tree_decl_elt *elt = *p;
+      
+      retval.push_back (elt->name ());
+    }
+
+  return retval;
+}
+
 octave_value_list
 tree_parameter_list::convert_to_const_vector (int nargout,
                                               const Cell& varargout)
rename from src/pt-misc.h
rename to libinterp/parse-tree/pt-misc.h
--- a/src/pt-misc.h
+++ b/libinterp/parse-tree/pt-misc.h
@@ -78,6 +78,8 @@
 
   bool is_defined (void);
 
+  std::list<std::string> variable_names (void) const;
+
   octave_value_list convert_to_const_vector (int nargout, const Cell& varargout);
 
   tree_parameter_list *dup (symbol_table::scope_id scope,
rename from src/pt-pr-code.cc
rename to libinterp/parse-tree/pt-pr-code.cc
--- a/src/pt-pr-code.cc
+++ b/libinterp/parse-tree/pt-pr-code.cc
@@ -165,7 +165,7 @@
 }
 
 void
-tree_print_code::visit_static_command (tree_static_command& cmd)
+tree_print_code::visit_persistent_command (tree_persistent_command& cmd)
 {
   do_decl_command (cmd);
 }
rename from src/pt-pr-code.h
rename to libinterp/parse-tree/pt-pr-code.h
--- a/src/pt-pr-code.h
+++ b/libinterp/parse-tree/pt-pr-code.h
@@ -67,7 +67,7 @@
 
   void visit_global_command (tree_global_command&);
 
-  void visit_static_command (tree_static_command&);
+  void visit_persistent_command (tree_persistent_command&);
 
   void visit_decl_elt (tree_decl_elt&);
 
rename from src/pt-select.cc
rename to libinterp/parse-tree/pt-select.cc
--- a/src/pt-select.cc
+++ b/libinterp/parse-tree/pt-select.cc
@@ -123,7 +123,7 @@
 {
   octave_value label_value = label->rvalue1 ();
 
-  if (! error_state && label_value.is_defined() )
+  if (! error_state && label_value.is_defined () )
     {
       if (label_value.is_cell ())
         {
rename from src/pt-select.h
rename to libinterp/parse-tree/pt-select.h
rename from src/pt-stmt.cc
rename to libinterp/parse-tree/pt-stmt.cc
--- a/src/pt-stmt.cc
+++ b/libinterp/parse-tree/pt-stmt.cc
@@ -32,6 +32,7 @@
 #include "error.h"
 #include "gripes.h"
 #include "ov.h"
+#include "octave-link.h"
 #include "oct-lvalue.h"
 #include "input.h"
 #include "pager.h"
@@ -191,6 +192,55 @@
   return tbp.get_list ();
 }
 
+bp_table::intmap
+tree_statement_list::add_breakpoint (const std::string& file,
+                                     const bp_table::intmap& line)
+{
+  bp_table::intmap retval;
+
+  octave_idx_type len = line.size ();
+
+  for (int i = 0; i < len; i++)
+    {
+      bp_table::const_intmap_iterator p = line.find (i);
+
+      if (p != line.end ())
+        {
+          int lineno = p->second;
+
+          retval[i] = set_breakpoint (lineno);
+
+          if (retval[i] != 0 && ! file.empty ())
+            octave_link::update_breakpoint (true, file, retval[i]);
+        }
+    }
+
+  return retval;
+}
+
+bp_table::intmap
+tree_statement_list::remove_all_breakpoints (const std::string& file)
+{
+  bp_table::intmap retval;
+
+  octave_value_list bkpts = list_breakpoints ();
+
+  for (int i = 0; i < bkpts.length (); i++)
+    {
+      int lineno = static_cast<int> (bkpts(i).int_value ());
+
+      delete_breakpoint (lineno);
+
+      retval[i] = lineno;
+
+      if (! file.empty ())
+        octave_link::update_breakpoint (false, file, lineno);
+    }
+
+  return retval;
+}
+
+
 tree_statement_list *
 tree_statement_list::dup (symbol_table::scope_id scope,
                           symbol_table::context_id context) const
rename from src/pt-stmt.h
rename to libinterp/parse-tree/pt-stmt.h
--- a/src/pt-stmt.h
+++ b/libinterp/parse-tree/pt-stmt.h
@@ -34,13 +34,15 @@
 
 #include "base-list.h"
 #include "comment-list.h"
+#include "debug.h"
 #include "symtab.h"
+#include "pt.h"
 
 // A statement is either a command to execute or an expression to
 // evaluate.
 
 class
-tree_statement
+tree_statement : public tree
 {
 public:
 
@@ -159,6 +161,11 @@
 
   octave_value_list list_breakpoints (void);
 
+  bp_table::intmap add_breakpoint (const std::string& file,
+                                   const bp_table::intmap& line);
+
+  bp_table::intmap remove_all_breakpoints (const std::string& file);
+
   tree_statement_list *dup (symbol_table::scope_id scope,
                             symbol_table::context_id context) const;
 
rename from src/pt-unop.cc
rename to libinterp/parse-tree/pt-unop.cc
rename from src/pt-unop.h
rename to libinterp/parse-tree/pt-unop.h
rename from src/pt-walk.h
rename to libinterp/parse-tree/pt-walk.h
--- a/src/pt-walk.h
+++ b/libinterp/parse-tree/pt-walk.h
@@ -30,7 +30,7 @@
 class tree_colon_expression;
 class tree_continue_command;
 class tree_global_command;
-class tree_static_command;
+class tree_persistent_command;
 class tree_decl_elt;
 class tree_decl_init_list;
 class tree_simple_for_command;
@@ -92,7 +92,7 @@
   visit_global_command (tree_global_command&) = 0;
 
   virtual void
-  visit_static_command (tree_static_command&) = 0;
+  visit_persistent_command (tree_persistent_command&) = 0;
 
   virtual void
   visit_decl_elt (tree_decl_elt&) = 0;
rename from src/pt.cc
rename to libinterp/parse-tree/pt.cc
rename from src/pt.h
rename to libinterp/parse-tree/pt.h
rename from src/token.cc
rename to libinterp/parse-tree/token.cc
--- a/src/token.cc
+++ b/libinterp/parse-tree/token.cc
@@ -32,62 +32,93 @@
 #include "token.h"
 #include "utils.h"
 
-token::token (int l, int c)
+token::token (int tv, int l, int c)
 {
+  maybe_cmd = false;
+  tspc = false;
   line_num = l;
   column_num = c;
+  tok_val = tv;
   type_tag = generic_token;
 }
 
-token::token (const std::string& s, int l, int c)
+token::token (int tv, bool is_kw, int l, int c)
 {
+  maybe_cmd = false;
+  tspc = false;
   line_num = l;
   column_num = c;
+  tok_val = tv;
+  type_tag = is_kw ? keyword_token : generic_token;
+}
+
+token::token (int tv, const std::string& s, int l, int c)
+{
+  maybe_cmd = false;
+  tspc = false;
+  line_num = l;
+  column_num = c;
+  tok_val = tv;
   type_tag = string_token;
   str = new std::string (s);
 }
 
-token::token (double d, const std::string& s, int l, int c)
+token::token (int tv, double d, const std::string& s, int l, int c)
 {
+  maybe_cmd = false;
+  tspc = false;
   line_num = l;
   column_num = c;
+  tok_val = tv;
   type_tag = double_token;
   num = d;
   orig_text = s;
 }
 
-token::token (end_tok_type t, int l, int c)
+token::token (int tv, end_tok_type t, int l, int c)
 {
+  maybe_cmd = false;
+  tspc = false;
   line_num = l;
   column_num = c;
+  tok_val = tv;
   type_tag = ettype_token;
   et = t;
 }
 
-token::token (symbol_table::symbol_record *s, int l, int c)
+token::token (int tv, symbol_table::symbol_record *s, int l, int c)
 {
+  maybe_cmd = false;
+  tspc = false;
   line_num = l;
   column_num = c;
+  tok_val = tv;
   type_tag = sym_rec_token;
   sr = s;
 }
 
-token::token (symbol_table::symbol_record *cls,
+token::token (int tv, symbol_table::symbol_record *cls,
               symbol_table::symbol_record *pkg, int l, int c)
 {
+  maybe_cmd = false;
+  tspc = false;
   line_num = l;
   column_num = c;
+  tok_val = tv;
   type_tag = meta_rec_token;
   mc.cr = cls;
   mc.pr = pkg;
 }
 
-token::token (symbol_table::symbol_record *mth,
+token::token (int tv, symbol_table::symbol_record *mth,
               symbol_table::symbol_record *cls,
               symbol_table::symbol_record *pkg, int l, int c)
 {
+  maybe_cmd = false;
+  tspc = false;
   line_num = l;
   column_num = c;
+  tok_val = tv;
   type_tag = scls_rec_token;
   sc.mr = mth;
   sc.cr = cls;
@@ -101,21 +132,34 @@
 }
 
 std::string
-token::text (void)
+token::text (void) const
 {
   assert (type_tag == string_token);
   return *str;
 }
 
+std::string
+token::symbol_name (void) const
+{
+  assert (type_tag == sym_rec_token);
+  return sr->name ();
+}
+
 double
-token::number (void)
+token::number (void) const
 {
   assert (type_tag == double_token);
   return num;
 }
 
+token::token_type
+token::ttype (void) const
+{
+  return type_tag;
+}
+
 token::end_tok_type
-token::ettype (void)
+token::ettype (void) const
 {
   assert (type_tag == ettype_token);
   return et;
rename from src/token.h
rename to libinterp/parse-tree/token.h
--- a/src/token.h
+++ b/libinterp/parse-tree/token.h
@@ -25,6 +25,8 @@
 
 #include <string>
 
+#include "symtab.h"
+
 class
 token
 {
@@ -33,6 +35,7 @@
   enum token_type
     {
       generic_token,
+      keyword_token,
       string_token,
       double_token,
       ettype_token,
@@ -59,26 +62,48 @@
       unwind_protect_end
     };
 
-  token (int l = -1, int c = -1);
-  token (const std::string& s, int l = -1, int c = -1);
-  token (double d, const std::string& s = std::string (),
+  token (int tv, int l = -1, int c = -1);
+  token (int tv, bool is_keyword, int l = -1, int c = -1);
+  token (int tv, const std::string& s, int l = -1, int c = -1);
+  token (int tv, double d, const std::string& s = std::string (),
          int l = -1, int c = -1);
-  token (end_tok_type t, int l = -1, int c = -1);
-  token (symbol_table::symbol_record *s, int l = -1, int c = -1);
-  token (symbol_table::symbol_record *cls,
+  token (int tv, end_tok_type t, int l = -1, int c = -1);
+  token (int tv, symbol_table::symbol_record *s, int l = -1, int c = -1);
+  token (int tv, symbol_table::symbol_record *cls,
          symbol_table::symbol_record *pkg, int l = -1, int c = -1);
-  token (symbol_table::symbol_record *mth,
+  token (int tv, symbol_table::symbol_record *mth,
          symbol_table::symbol_record *cls,
          symbol_table::symbol_record *pkg, int l = -1, int c = -1);
 
   ~token (void);
 
-  int line (void) { return line_num; }
-  int column (void) { return column_num; }
+  void mark_may_be_command (void) { maybe_cmd = true; }
+  bool may_be_command (void) const { return maybe_cmd; }
+
+  void mark_trailing_space (void) { tspc = true; }
+  bool space_follows_token (void) const { return tspc; }
+
+  int token_value (void) const { return tok_val; }
+  bool token_value_is (int tv) const { return tv == tok_val; }
+
+  int line (void) const { return line_num; }
+  int column (void) const { return column_num; }
 
-  std::string text (void);
-  double number (void);
-  end_tok_type ettype (void);
+  bool is_keyword (void) const
+  {
+    return type_tag == keyword_token || type_tag == ettype_token;
+  }
+
+  bool is_symbol (void) const
+  {
+    return type_tag == sym_rec_token;
+  }
+
+  std::string text (void) const;
+  std::string symbol_name (void) const;
+  double number (void) const;
+  token_type ttype (void) const;
+  end_tok_type ettype (void) const;
   symbol_table::symbol_record *sym_rec (void);
 
   symbol_table::symbol_record *method_rec (void);
@@ -98,8 +123,11 @@
 
   token& operator = (const token& tok);
 
+  bool maybe_cmd;
+  bool tspc;
   int line_num;
   int column_num;
+  int tok_val;
   token_type type_tag;
   union
     {
new file mode 100644
--- /dev/null
+++ b/libinterp/template-inst/Array-jit.cc
@@ -0,0 +1,45 @@
+/*
+
+Copyright (C) 2012 Max Brister <max@2bass.com>
+
+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
+
+#ifdef HAVE_LLVM
+
+#include "Array.h"
+#include "Array.cc"
+
+extern template class OCTAVE_API Array<octave_idx_type>;
+
+#include "jit-ir.h"
+
+NO_INSTANTIATE_ARRAY_SORT (jit_function);
+
+INSTANTIATE_ARRAY (jit_function, OCTINTERP_API);
+
+#ifdef Cell_h
+#error Must not include Cell.h in Array-jit.h
+#error This causes problems on MSVC
+#endif
+
+#endif
rename from src/TEMPLATE-INST/Array-os.cc
rename to libinterp/template-inst/Array-os.cc
rename from src/TEMPLATE-INST/Array-sym.cc
rename to libinterp/template-inst/Array-sym.cc
rename from src/TEMPLATE-INST/Array-tc.cc
rename to libinterp/template-inst/Array-tc.cc
rename from src/TEMPLATE-INST/module.mk
rename to libinterp/template-inst/module.mk
--- a/src/TEMPLATE-INST/module.mk
+++ b/libinterp/template-inst/module.mk
@@ -1,5 +1,6 @@
-EXTRA_DIST += TEMPLATE-INST/module.mk
+EXTRA_DIST += template-inst/module.mk
 
 TEMPLATE_INST_SRC = \
-  TEMPLATE-INST/Array-os.cc \
-  TEMPLATE-INST/Array-tc.cc
+  template-inst/Array-os.cc \
+  template-inst/Array-tc.cc \
+  template-inst/Array-jit.cc
rename from src/version.h.in
rename to libinterp/version.in.h
--- a/src/version.h.in
+++ b/libinterp/version.in.h
@@ -1,3 +1,4 @@
+// %NO_EDIT_WARNING%
 /*
 
 Copyright (C) 1992-2012 John W. Eaton
@@ -86,6 +87,6 @@
 
 #define OCTAVE_STARTUP_MESSAGE \
   X_OCTAVE_NAME_VERSION_COPYRIGHT_COPYING_WARRANTY_AND_BUGS \
-    ("  For details, type `warranty'.") "\n\n" \
-  "For information about changes from previous versions, type `news'."
+    ("  For details, type 'warranty'.") "\n\n" \
+  "For information about changes from previous versions, type 'news'."
 #endif
--- a/liboctave/Makefile.am
+++ b/liboctave/Makefile.am
@@ -1,4 +1,4 @@
-# Makefile for octave's liboctave directory
+# Makefile for Octave's liboctave directory
 #
 # Copyright (C) 1993-2012 John W. Eaton
 #
@@ -20,266 +20,34 @@
 
 include $(top_srcdir)/build-aux/common.mk
 
+AUTOMAKE_OPTIONS = subdir-objects
+
+## Run cruft dir with stand-alone Makefile.
+## Eventually this will use module.mk syntax.
+SUBDIRS = cruft
+
 ## Search local directories before those specified by the user.
 AM_CPPFLAGS = \
-  -I../libgnu -I$(top_srcdir)/libgnu \
-  -I$(top_srcdir)/libcruft/misc \
-  @CPPFLAGS@
-
-EXTRA_DIST = \
-  config-ops.sh \
-  mk-ops.awk \
-  mx-op-inc.mk \
-  mx-op-src.mk \
-  mx-ops \
-  smx-op-inc.mk \
-  smx-op-src.mk \
-  sparse-mk-ops.awk \
-  sparse-mx-ops \
-  vx-op-inc.mk \
-  vx-op-src.mk \
-  vx-ops \
-  $(OPT_IN)
+  -I$(srcdir)/array \
+  -I$(srcdir)/cruft/misc \
+  -Inumeric -I$(srcdir)/numeric \
+  -Ioperators -I$(srcdir)/operators \
+  -I$(srcdir)/system \
+  -I$(srcdir)/util \
+  -I$(top_builddir)/libgnu -I$(top_srcdir)/libgnu
 
-MATRIX_INC = \
-  Array-util.h \
-  Array.h \
-  Array2.h \
-  Array3.h \
-  ArrayN.h \
-  CColVector.h \
-  CDiagMatrix.h \
-  CMatrix.h \
-  CNDArray.h \
-  CRowVector.h \
-  CSparse.h \
-  CmplxAEPBAL.h \
-  CmplxCHOL.h \
-  CmplxGEPBAL.h \
-  CmplxHESS.h \
-  CmplxLU.h \
-  CmplxQR.h \
-  CmplxQRP.h \
-  CmplxSCHUR.h \
-  CmplxSVD.h \
-  DET.h \
-  DiagArray2.h \
-  EIG.h \
-  MArray-decl.h \
-  MArray-defs.h \
-  MArray.h \
-  MArray2.h \
-  MArrayN.h \
-  MDiagArray2.h \
-  MSparse-defs.h \
-  MSparse.h \
-  Matrix.h \
-  MatrixType.h \
-  PermMatrix.h \
-  Sparse-diag-op-defs.h \
-  Sparse-op-defs.h \
-  Sparse-perm-op-defs.h \
-  Sparse.h \
-  SparseCmplxCHOL.h \
-  SparseCmplxLU.h \
-  SparseCmplxQR.h \
-  SparseQR.h \
-  SparsedbleCHOL.h \
-  SparsedbleLU.h \
-  base-aepbal.h \
-  base-lu.h \
-  base-qr.h \
-  boolMatrix.h \
-  boolNDArray.h \
-  boolSparse.h \
-  bsxfun-decl.h \
-  chMatrix.h \
-  chNDArray.h \
-  dColVector.h \
-  dDiagMatrix.h \
-  dMatrix.h \
-  dNDArray.h \
-  dRowVector.h \
-  dSparse.h \
-  dbleAEPBAL.h \
-  dbleCHOL.h \
-  dbleGEPBAL.h \
-  dbleHESS.h \
-  dbleLU.h \
-  dbleQR.h \
-  dbleQRP.h \
-  dbleSCHUR.h \
-  dbleSVD.h \
-  dim-vector.h \
-  fCColVector.h \
-  fCDiagMatrix.h \
-  fCMatrix.h \
-  fCNDArray.h \
-  fCRowVector.h \
-  fCmplxAEPBAL.h \
-  fCmplxCHOL.h \
-  fCmplxGEPBAL.h \
-  fCmplxHESS.h \
-  fCmplxLU.h \
-  fCmplxQR.h \
-  fCmplxQRP.h \
-  fCmplxSCHUR.h \
-  fCmplxSVD.h \
-  fColVector.h \
-  fDiagMatrix.h \
-  fEIG.h \
-  fMatrix.h \
-  fNDArray.h \
-  fRowVector.h \
-  floatAEPBAL.h \
-  floatCHOL.h \
-  floatGEPBAL.h \
-  floatHESS.h \
-  floatLU.h \
-  floatQR.h \
-  floatQRP.h \
-  floatSCHUR.h \
-  floatSVD.h \
-  int16NDArray.h \
-  int32NDArray.h \
-  int64NDArray.h \
-  int8NDArray.h \
-  intNDArray.h \
-  mx-base.h \
-  mx-defs.h \
-  mx-ext.h \
-  mx-op-decl.h \
-  mx-op-defs.h \
-  sparse-base-chol.h \
-  sparse-base-lu.h \
-  uint16NDArray.h \
-  uint32NDArray.h \
-  uint64NDArray.h \
-  uint8NDArray.h
+AM_CFLAGS += $(WARN_CFLAGS)
+
+AM_CXXFLAGS += $(WARN_CXXFLAGS)
 
-OPT_IN = \
-  DASPK-opts.in \
-  DASRT-opts.in \
-  DASSL-opts.in \
-  LSODE-opts.in \
-  Quad-opts.in
-
-OPT_INC = \
-  DASPK-opts.h \
-  DASRT-opts.h \
-  DASSL-opts.h \
-  LSODE-opts.h \
-  Quad-opts.h
+octlib_LTLIBRARIES = liboctave.la
 
-INCS = \
-  CollocWt.h \
-  DAE.h \
-  DAEFunc.h \
-  DAERT.h \
-  DAERTFunc.h \
-  DASPK.h \
-  DASRT.h \
-  DASSL.h \
-  LSODE.h \
-  ODE.h \
-  ODEFunc.h \
-  ODES.h \
-  ODESFunc.h \
-  Quad.h \
-  Range.h \
-  base-dae.h \
-  base-de.h \
-  base-list.h \
-  base-min.h \
-  bsxfun.h \
-  byte-swap.h \
-  caseless-str.h \
-  cmd-edit.h \
-  cmd-hist.h \
-  data-conv.h \
-  dir-ops.h \
-  file-ops.h \
-  file-stat.h \
-  functor.h \
-  glob-match.h \
-  idx-vector.h \
-  lo-array-gripes.h \
-  lo-cutils.h \
-  lo-ieee.h \
-  lo-macros.h \
-  lo-mappers.h \
-  lo-math.h \
-  lo-specfun.h \
-  lo-sysdep.h \
-  lo-traits.h \
-  lo-utils.h \
-  mach-info.h \
-  oct-alloc.h \
-  oct-binmap.h \
-  oct-cmplx.h \
-  oct-convn.h \
-  oct-env.h \
-  oct-fftw.h \
-  oct-glob.h \
-  oct-group.h \
-  oct-inttypes.h \
-  oct-locbuf.h \
-  oct-md5.h \
-  oct-mem.h \
-  oct-mutex.h \
-  oct-norm.h \
-  oct-openmp.h \
-  oct-passwd.h \
-  oct-rand.h \
-  oct-refcount.h \
-  oct-rl-edit.h \
-  oct-rl-hist.h \
-  oct-shlib.h \
-  oct-sort.h \
-  oct-sparse.h \
-  oct-spparms.h \
-  oct-syscalls.h \
-  oct-time.h \
-  oct-uname.h \
-  pathlen.h \
-  pathsearch.h \
-  randgamma.h \
-  randmtzig.h \
-  randpoisson.h \
-  regexp.h \
-  singleton-cleanup.h \
-  sparse-sort.h \
-  sparse-util.h \
-  statdefs.h \
-  str-vec.h \
-  sun-utils.h \
-  sysdir.h \
-  syswait.h \
-  $(MATRIX_INC)
+EXTRA_DIST =
 
-PRIVATE_INCS = \
-  oct-glob.h
-
-OTHER_INC = \
-  intNDArray.cc \
-  kpse.cc \
-  mx-inlines.cc
-
-include vx-op-inc.mk
-include mx-op-inc.mk
-include smx-op-inc.mk
-
-$(srcdir)/vx-op-inc.mk: $(srcdir)/config-ops.sh $(srcdir)/mk-ops.awk $(srcdir)/vx-ops
-	$(srcdir)/config-ops.sh $(top_srcdir) vx inc
-
-$(srcdir)/mx-op-inc.mk: $(srcdir)/config-ops.sh $(srcdir)/mk-ops.awk $(srcdir)/mx-ops
-	$(srcdir)/config-ops.sh $(top_srcdir) mx inc
-
-$(srcdir)/smx-op-inc.mk: $(srcdir)/config-ops.sh $(srcdir)/sparse-mk-ops.awk $(srcdir)/sparse-mx-ops
-	$(srcdir)/config-ops.sh $(top_srcdir) smx inc
+DISTCLEANFILES =
 
 BUILT_INCS = \
-  mx-ops.h \
+  operators/mx-ops.h \
   $(OPT_INC) \
   $(MX_OP_INC) \
   $(VX_OP_INC) \
@@ -287,279 +55,87 @@
 
 BUILT_SOURCES = $(BUILT_INCS)
 
-TEMPLATE_SRC = \
-  Array.cc \
-  DiagArray2.cc \
-  MArray.cc \
-  MDiagArray2.cc \
-  base-lu.cc \
-  base-qr.cc \
-  bsxfun-defs.cc \
-  eigs-base.cc \
-  oct-sort.cc \
-  sparse-base-chol.cc \
-  sparse-base-lu.cc \
-  sparse-dmsolve.cc
+octinclude_HEADERS = \
+  $(ARRAY_INC) \
+  $(NUMERIC_INC) \
+  $(OPERATORS_INC) \
+  $(SYSTEM_INC) \
+  $(UTIL_INC) \
+  $(OTHER_INC) \
+  $(TEMPLATE_SRC)
 
-TI_SRC = \
-  Array-C.cc \
-  Array-b.cc \
-  Array-ch.cc \
-  Array-d.cc \
-  Array-f.cc \
-  Array-fC.cc \
-  Array-i.cc \
-  Array-idx-vec.cc \
-  Array-s.cc \
-  Array-str.cc \
-  Array-voidp.cc \
-  MArray-C.cc \
-  MArray-d.cc \
-  MArray-f.cc \
-  MArray-fC.cc \
-  MArray-i.cc \
-  MArray-s.cc \
-  MSparse-C.cc \
-  MSparse-d.cc \
-  Sparse-C.cc \
-  Sparse-b.cc \
-  Sparse-d.cc \
-  oct-inttypes.cc
+nodist_octinclude_HEADERS = \
+  $(BUILT_INCS)
+
+noinst_LTLIBRARIES =
+
+## C++ files that are #included, not compiled
+OTHER_INC =
 
-MATRIX_SRC = \
-  Array-util.cc \
-  CColVector.cc \
-  CDiagMatrix.cc \
-  CMatrix.cc \
-  CNDArray.cc \
-  CRowVector.cc \
-  CSparse.cc \
-  CmplxAEPBAL.cc \
-  CmplxCHOL.cc \
-  CmplxGEPBAL.cc \
-  CmplxHESS.cc \
-  CmplxLU.cc \
-  CmplxQR.cc \
-  CmplxQRP.cc \
-  CmplxSCHUR.cc \
-  CmplxSVD.cc \
-  EIG.cc \
-  MSparse.cc \
-  MatrixType.cc \
-  PermMatrix.cc \
-  Sparse.cc \
-  SparseCmplxCHOL.cc \
-  SparseCmplxLU.cc \
-  SparseCmplxQR.cc \
-  SparseQR.cc \
-  SparsedbleCHOL.cc \
-  SparsedbleLU.cc \
-  boolMatrix.cc \
-  boolNDArray.cc \
-  boolSparse.cc \
-  chMatrix.cc \
-  chNDArray.cc \
-  dim-vector.cc \
-  dColVector.cc \
-  dDiagMatrix.cc \
-  dMatrix.cc \
-  dNDArray.cc \
-  dRowVector.cc \
-  dSparse.cc \
-  dbleAEPBAL.cc \
-  dbleCHOL.cc \
-  dbleGEPBAL.cc \
-  dbleHESS.cc \
-  dbleLU.cc \
-  dbleQR.cc \
-  dbleQRP.cc \
-  dbleSCHUR.cc \
-  dbleSVD.cc \
-  fCColVector.cc \
-  fCDiagMatrix.cc \
-  fCMatrix.cc \
-  fCNDArray.cc \
-  fCRowVector.cc \
-  fCmplxAEPBAL.cc \
-  fCmplxCHOL.cc \
-  fCmplxGEPBAL.cc \
-  fCmplxHESS.cc \
-  fCmplxLU.cc \
-  fCmplxQR.cc \
-  fCmplxQRP.cc \
-  fCmplxSCHUR.cc \
-  fCmplxSVD.cc \
-  fColVector.cc \
-  fDiagMatrix.cc \
-  fEIG.cc \
-  fMatrix.cc \
-  fNDArray.cc \
-  fRowVector.cc \
-  floatAEPBAL.cc \
-  floatCHOL.cc \
-  floatGEPBAL.cc \
-  floatHESS.cc \
-  floatLU.cc \
-  floatQR.cc \
-  floatQRP.cc \
-  floatSCHUR.cc \
-  floatSVD.cc \
-  int16NDArray.cc \
-  int32NDArray.cc \
-  int64NDArray.cc \
-  int8NDArray.cc \
-  uint16NDArray.cc \
-  uint32NDArray.cc \
-  uint64NDArray.cc \
-  uint8NDArray.cc
+## C++ files with templates that are #included, not compiled
+TEMPLATE_SRC =
 
-octlib_LTLIBRARIES = liboctave.la
+## A list of all files that could include tests
 
-LIBOCTAVE_CXX_SOURCES = \
-  CollocWt.cc \
-  DASPK.cc \
-  DASRT.cc \
-  DASSL.cc \
-  LSODE.cc \
-  ODES.cc \
-  Quad.cc \
-  Range.cc \
-  data-conv.cc \
-  dir-ops.cc \
-  file-ops.cc \
-  file-stat.cc \
-  glob-match.cc \
-  idx-vector.cc \
-  lo-array-gripes.cc \
-  lo-ieee.cc \
-  lo-mappers.cc \
-  lo-specfun.cc \
-  lo-sysdep.cc \
-  lo-utils.cc \
-  mach-info.cc \
-  oct-alloc.cc \
-  oct-convn.cc \
-  oct-env.cc \
-  oct-fftw.cc \
-  oct-glob.cc \
-  oct-group.cc \
-  oct-locbuf.cc \
-  oct-md5.cc \
-  oct-mutex.cc \
-  oct-norm.cc \
-  oct-passwd.cc \
-  oct-rand.cc \
-  oct-shlib.cc \
-  oct-spparms.cc \
-  oct-syscalls.cc \
-  oct-time.cc \
-  oct-uname.cc \
-  pathsearch.cc \
-  regexp.cc \
-  singleton-cleanup.cc \
-  sparse-sort.cc \
-  sparse-util.cc \
-  str-vec.cc \
-  $(TI_SRC) \
-  $(MATRIX_SRC)
+include array/module.mk
+include numeric/module.mk
+include operators/module.mk
+include system/module.mk
+include util/module.mk
 
-include vx-op-src.mk
-include mx-op-src.mk
-include smx-op-src.mk
-
-$(srcdir)/vx-op-src.mk: $(srcdir)/config-ops.sh $(srcdir)/mk-ops.awk $(srcdir)/vx-ops
-	$(srcdir)/config-ops.sh $(top_srcdir) vx src
-
-$(srcdir)/mx-op-src.mk: $(srcdir)/config-ops.sh $(srcdir)/mk-ops.awk $(srcdir)/mx-ops
-	$(srcdir)/config-ops.sh $(top_srcdir) mx src
-
-$(srcdir)/smx-op-src.mk: $(srcdir)/config-ops.sh $(srcdir)/sparse-mk-ops.awk $(srcdir)/sparse-mx-ops
-	$(srcdir)/config-ops.sh $(top_srcdir) smx src
-
-BUILT_LIBOCTAVE_CXX_SOURCES = \
-  $(MX_OP_SRC) \
-  $(VX_OP_SRC) \
-  $(SMX_OP_SRC)
+## liboctave merely collects a bunch of compiled convenience libraries.
+## It has no source code itself.
+liboctave_la_SOURCES = 
 
-LIBOCTAVE_C_SOURCES = \
-  f2c-main.c \
-  lo-cieee.c \
-  lo-cutils.c \
-  randgamma.c \
-  randmtzig.c \
-  randpoisson.c \
-  tempnam.c \
-  tempname.c
-
-LIBOCT_READLINE_CXX_SOURCES = cmd-edit.cc cmd-hist.cc
-
-LIBOCT_READLINE_C_SOURCES = oct-rl-edit.c oct-rl-hist.c
-
-LIBOCT_READLINE_SOURCES = $(LIBOCT_READLINE_CXX_SOURCES) $(LIBOCT_READLINE_C_SOURCES)
-
-liboctave_la_SOURCES = \
-  $(LIBOCTAVE_CXX_SOURCES) \
-  $(LIBOCTAVE_C_SOURCES) \
-  $(LIBOCTAVE_SOURCES) \
-  $(LIBOCT_READLINE_SOURCES) \
-  $(LIBOCT_PATHSEARCH_SOURCES)
-
-nodist_liboctave_la_SOURCES = \
-  $(BUILT_LIBOCTAVE_CXX_SOURCES)
+liboctave_la_CPPFLAGS = @OCTAVE_DLL_DEFS@ @CRUFT_DLL_DEFS@ $(AM_CPPFLAGS)
 
 include link-deps.mk
 
+# Dummy C++ source to force C++ linking.
+nodist_EXTRA_liboctave_la_SOURCES = dummy.cc
+
 liboctave_la_LIBADD = \
-  ../libcruft/libcruft.la \
+  array/libarray.la \
+  cruft/libcruft.la \
+  cruft/ranlib/libranlib.la \
+  numeric/libnumeric.la \
+  operators/liboperators.la \
+  system/libsystem.la \
+  util/libutil.la \
+  $(top_builddir)/libgnu/libgnu.la \
   $(LIBOCTAVE_LINK_DEPS)
 
-liboctave_la_CPPFLAGS = \
-  @OCTAVE_DLL_DEFS@ \
-  $(SPARSE_XCPPFLAGS) \
-  $(FFTW_XCPPFLAGS) \
-  $(ARPACK_CPPFLAGS) \
-  $(AM_CPPFLAGS)
-
-# Increment these as needed and according to the rules in the libtool
-# manual:
-liboctave_current = 2
-liboctave_revision = 0
-liboctave_age = 1
+# Increment these as needed and according to the rules in the libtool manual:
+liboctave_current = 1
+liboctave_revision = 1
+liboctave_age = 0
 
 liboctave_version_info = $(liboctave_current):$(liboctave_revision):$(liboctave_age)
 
 liboctave_la_LDFLAGS = \
   -version-info $(liboctave_version_info) \
   $(NO_UNDEFINED_LDFLAG) \
+  @XTRA_CRUFT_SH_LDFLAGS@ \
   -bindir $(bindir) \
   $(LIBOCTAVE_LINK_OPTS)
 
-octinclude_HEADERS = \
-  $(INCS) \
-  $(OTHER_INC) \
-  $(TEMPLATE_SRC) \
-  $(EXTRA_HEADERS)
+## Rules to build test files
 
-nodist_octinclude_HEADERS = \
-  $(BUILT_INCS)
+LIBOCTAVE_TST_SRC = \
+  $(array_libarray_la_SOURCES) \
+  $(numeric_libnumeric_la_SOURCES) \
+  $(system_libsystem_la_SOURCES) \
+  $(util_libutil_la_SOURCES)
 
-$(OPT_INC) : %.h : %.in $(top_srcdir)/build-aux/mk-opts.pl
-	@echo making $@ from $<
-	@$(PERL) $(top_srcdir)/build-aux/mk-opts.pl --opt-class-header $< > $@-t
-	mv $@-t $@
+TST_FILES_SRC := $(shell $(top_srcdir)/build-aux/find-files-with-tests.sh "$(srcdir)" $(LIBOCTAVE_TST_SRC))
 
-$(VX_OP_INC) $(VX_OP_SRC) : $(srcdir)/mk-ops.awk vx-ops
-	$(AWK) -f $(srcdir)/mk-ops.awk prefix=vx $(srcdir)/vx-ops
+TST_FILES := $(addsuffix -tst,$(TST_FILES_SRC))
 
-$(MX_OP_INC) $(MX_OP_SRC) : $(srcdir)/mk-ops.awk mx-ops
-	$(AWK) -f $(srcdir)/mk-ops.awk prefix=mx $(srcdir)/mx-ops
+liboctavetestsdir := $(octtestsdir)/liboctave
 
-$(SMX_OP_INC) $(SMX_OP_SRC) : $(srcdir)/sparse-mk-ops.awk sparse-mx-ops
-	$(AWK) -f $(srcdir)/sparse-mk-ops.awk prefix=smx $(srcdir)/sparse-mx-ops
+nobase_liboctavetests_DATA = $(TST_FILES)
 
-mx-ops.h : $(srcdir)/mk-ops.awk mx-ops
-	$(AWK) -f $(srcdir)/mk-ops.awk prefix=mx make_inclusive_header=mx-ops.h $(srcdir)/mx-ops > $@-t
-	mv $@-t $@
+DISTCLEANFILES += \
+  $(BUILT_INCS) \
+  $(TST_FILES)
 
-DISTCLEANFILES = $(BUILT_INCS) $(BUILT_LIBOCTAVE_CXX_SOURCES)
-
rename from liboctave/Array-C.cc
rename to liboctave/array/Array-C.cc
rename from liboctave/Array-b.cc
rename to liboctave/array/Array-b.cc
rename from liboctave/Array-ch.cc
rename to liboctave/array/Array-ch.cc
rename from liboctave/Array-d.cc
rename to liboctave/array/Array-d.cc
rename from liboctave/Array-f.cc
rename to liboctave/array/Array-f.cc
rename from liboctave/Array-fC.cc
rename to liboctave/array/Array-fC.cc
rename from liboctave/Array-i.cc
rename to liboctave/array/Array-i.cc
rename from liboctave/Array-idx-vec.cc
rename to liboctave/array/Array-idx-vec.cc
rename from liboctave/Array-s.cc
rename to liboctave/array/Array-s.cc
rename from liboctave/Array-str.cc
rename to liboctave/array/Array-str.cc
rename from liboctave/Array-util.cc
rename to liboctave/array/Array-util.cc
--- a/liboctave/Array-util.cc
+++ b/liboctave/array/Array-util.cc
@@ -236,7 +236,7 @@
   Array<octave_idx_type> retval (a.dims ());
 
   for (octave_idx_type i = 0; i < a.length (); i++)
-    retval (i) = a(i).elem (0);
+    retval(i) = a(i).elem (0);
 
   return retval;
 }
@@ -247,7 +247,7 @@
   Array<idx_vector> retval (dim_vector (len, 1));
 
   for (octave_idx_type i = 0; i < len; i++)
-      retval (i) = tmp[i];
+      retval(i) = tmp[i];
 
   return retval;
 }
@@ -426,7 +426,7 @@
 {
   int ial = ia.length (), rhdvl = rhdv.length ();
   dim_vector rdv = dim_vector::alloc (ial);
-  bool *scalar = new bool[ial], *colon = new bool[ial];
+  bool *scalar = new bool [ial], *colon = new bool [ial];
   // Mark scalars and colons, count non-scalar indices.
   int nonsc = 0;
   bool all_colons = true;
@@ -445,7 +445,7 @@
   if (all_colons)
     {
       rdv = rhdv;
-      rdv.resize(ial, 1);
+      rdv.resize (ial, 1);
     }
   else if (nonsc == rhdvl)
     {
@@ -466,7 +466,7 @@
         {
           if (scalar[i]) continue;
           if (colon[i])
-            rdv(i) =  (j < rhdv0l) ? rhdv0(j++) : 1;
+            rdv(i) = (j < rhdv0l) ? rhdv0(j++) : 1;
         }
     }
 
rename from liboctave/Array-util.h
rename to liboctave/array/Array-util.h
rename from liboctave/Array-voidp.cc
rename to liboctave/array/Array-voidp.cc
rename from liboctave/Array.cc
rename to liboctave/array/Array.cc
--- a/liboctave/Array.cc
+++ b/liboctave/array/Array.cc
@@ -28,7 +28,6 @@
 #endif
 
 #include <cassert>
-#include <climits>
 
 #include <iostream>
 #include <sstream>
@@ -649,7 +648,7 @@
       int i = 0;
       for (; i < l-1 && ndv(i) == odv(i); i++) ld *= ndv(i);
       n = l - i;
-      cext = new octave_idx_type[3*n];
+      cext = new octave_idx_type [3*n];
       // Trick to avoid three allocations
       sext = cext + n;
       dext = sext + n;
@@ -723,17 +722,17 @@
 
       // FIXME -- this is for Matlab compatibility.  Matlab 2007 given
       //
-      //   b = ones(3,1)
+      //   b = ones (3,1)
       //
       // yields the following:
       //
-      //   b(zeros(0,0)) gives []
-      //   b(zeros(1,0)) gives zeros(0,1)
-      //   b(zeros(0,1)) gives zeros(0,1)
-      //   b(zeros(0,m)) gives zeros(0,m)
-      //   b(zeros(m,0)) gives zeros(m,0)
-      //   b(1:2) gives ones(2,1)
-      //   b(ones(2)) gives ones(2) etc.
+      //   b(zeros (0,0)) gives []
+      //   b(zeros (1,0)) gives zeros (0,1)
+      //   b(zeros (0,1)) gives zeros (0,1)
+      //   b(zeros (0,m)) gives zeros (0,m)
+      //   b(zeros (m,0)) gives zeros (m,0)
+      //   b(1:2) gives ones (2,1)
+      //   b(ones (2)) gives ones (2) etc.
       //
       // As you can see, the behaviour is weird, but the tests end up pretty
       // simple.  Nah, I don't want to suggest that this is ad hoc :)
@@ -884,7 +883,8 @@
 // The default fill value.  Override if you want a different one.
 
 template <class T>
-const T& Array<T>::resize_fill_value ()
+T
+Array<T>::resize_fill_value (void) const
 {
   static T zero = T ();
   return zero;
@@ -1652,24 +1652,24 @@
 %! m9 = reshape (1 : 9*8, 8, 9);
 %! mt9 = [mt8; 65:72];
 
-%!assert(m7', mt7)
-%!assert((1i*m7).', 1i * mt7)
-%!assert((1i*m7)', conj (1i * mt7))
-%!assert(m8', mt8)
-%!assert((1i*m8).', 1i * mt8)
-%!assert((1i*m8)', conj (1i * mt8))
-%!assert(m9', mt9)
-%!assert((1i*m9).', 1i * mt9)
-%!assert((1i*m9)', conj (1i * mt9))
-%!assert([m7, m8; m7, m8]', [mt7, mt7; mt8, mt8])
-%!assert((1i*[m7, m8; m7, m8]).', 1i * [mt7, mt7; mt8, mt8])
-%!assert((1i*[m7, m8; m7, m8])', conj (1i * [mt7, mt7; mt8, mt8]))
-%!assert([m8, m8; m8, m8]', [mt8, mt8; mt8, mt8])
-%!assert((1i*[m8, m8; m8, m8]).', 1i * [mt8, mt8; mt8, mt8])
-%!assert((1i*[m8, m8; m8, m8])', conj (1i * [mt8, mt8; mt8, mt8]))
-%!assert([m9, m8; m9, m8]', [mt9, mt9; mt8, mt8])
-%!assert((1i*[m9, m8; m9, m8]).', 1i * [mt9, mt9; mt8, mt8])
-%!assert((1i*[m9, m8; m9, m8])', conj (1i * [mt9, mt9; mt8, mt8]))
+%!assert (m7', mt7)
+%!assert ((1i*m7).', 1i * mt7)
+%!assert ((1i*m7)', conj (1i * mt7))
+%!assert (m8', mt8)
+%!assert ((1i*m8).', 1i * mt8)
+%!assert ((1i*m8)', conj (1i * mt8))
+%!assert (m9', mt9)
+%!assert ((1i*m9).', 1i * mt9)
+%!assert ((1i*m9)', conj (1i * mt9))
+%!assert ([m7, m8; m7, m8]', [mt7, mt7; mt8, mt8])
+%!assert ((1i*[m7, m8; m7, m8]).', 1i * [mt7, mt7; mt8, mt8])
+%!assert ((1i*[m7, m8; m7, m8])', conj (1i * [mt7, mt7; mt8, mt8]))
+%!assert ([m8, m8; m8, m8]', [mt8, mt8; mt8, mt8])
+%!assert ((1i*[m8, m8; m8, m8]).', 1i * [mt8, mt8; mt8, mt8])
+%!assert ((1i*[m8, m8; m8, m8])', conj (1i * [mt8, mt8; mt8, mt8]))
+%!assert ([m9, m8; m9, m8]', [mt9, mt9; mt8, mt8])
+%!assert ((1i*[m9, m8; m9, m8]).', 1i * [mt9, mt9; mt8, mt8])
+%!assert ((1i*[m9, m8; m9, m8])', conj (1i * [mt9, mt9; mt8, mt8]))
 
 */
 
@@ -2222,13 +2222,13 @@
     }
 
   // Fixup return dimensions, for Matlab compatibility.
-  // find(zeros(0,0)) -> zeros(0,0)
-  // find(zeros(1,0)) -> zeros(1,0)
-  // find(zeros(0,1)) -> zeros(0,1)
-  // find(zeros(0,X)) -> zeros(0,1)
-  // find(zeros(1,1)) -> zeros(0,0) !!!! WHY?
-  // find(zeros(0,1,0)) -> zeros(0,0)
-  // find(zeros(0,1,0,1)) -> zeros(0,0) etc
+  // find (zeros (0,0)) -> zeros (0,0)
+  // find (zeros (1,0)) -> zeros (1,0)
+  // find (zeros (0,1)) -> zeros (0,1)
+  // find (zeros (0,X)) -> zeros (0,1)
+  // find (zeros (1,1)) -> zeros (0,0) !!!! WHY?
+  // find (zeros (0,1,0)) -> zeros (0,0)
+  // find (zeros (0,1,0,1)) -> zeros (0,0) etc
 
   if ((numel () == 1 && retval.is_empty ())
       || (rows () == 0 && dims ().numel (1) == 0))
@@ -2531,6 +2531,26 @@
 
 template <class T>
 Array<T>
+Array<T>::diag (octave_idx_type m, octave_idx_type n) const
+{
+  Array<T> retval;
+
+  if (ndims () == 2 && (rows () == 1 || cols () == 1))
+    {
+      retval.resize (dim_vector (m, n), resize_fill_value ());
+
+      for (octave_idx_type i = 0; i < numel (); i++)
+        retval.xelem (i, i) = xelem (i);
+    }
+  else
+    (*current_liboctave_error_handler)
+      ("cat: invalid dimension");
+
+  return retval;
+}
+
+template <class T>
+Array<T>
 Array<T>::cat (int dim, octave_idx_type n, const Array<T> *array_list)
 {
   // Default concatenation.
@@ -2667,7 +2687,7 @@
 {
   // This guards against accidental implicit instantiations.
   // Array<T> instances should always be explicit and use INSTANTIATE_ARRAY.
-  T::__xXxXx__();
+  T::__xXxXx__ ();
 }
 
 #define INSTANTIATE_ARRAY(T, API) \
@@ -2720,7 +2740,7 @@
                   for (octave_idx_type k = 0; k < cols; k++)
                     {
                       ra_idx(1) = k;
-                      os << " " << a.elem(ra_idx);
+                      os << " " << a.elem (ra_idx);
                     }
                   os << "\n";
                 }
@@ -2732,7 +2752,7 @@
               for (octave_idx_type k = 0; k < rows; k++)
                 {
                   ra_idx(0) = k;
-                  os << " " << a.elem(ra_idx);
+                  os << " " << a.elem (ra_idx);
                 }
               break;
             }
@@ -2760,7 +2780,7 @@
                   for (octave_idx_type k = 0; k < cols; k++)
                     {
                       ra_idx(1) = k;
-                      os << " " << a.elem(ra_idx);
+                      os << " " << a.elem (ra_idx);
                     }
 
                   os << "\n";
rename from liboctave/Array.h
rename to liboctave/array/Array.h
--- a/liboctave/Array.h
+++ b/liboctave/array/Array.h
@@ -164,6 +164,14 @@
       return &nr;
     }
 
+protected:
+
+  // For jit support
+  Array (T *sdata, octave_idx_type slen, octave_idx_type *adims, void *arep)
+    : dimensions (adims),
+      rep (reinterpret_cast<typename Array<T>::ArrayRep *> (arep)),
+      slice_data (sdata), slice_len (slen) {}
+
 public:
 
   // Empty ctor (0x0).
@@ -229,7 +237,7 @@
 
 public:
 
-  ~Array (void)
+  virtual ~Array (void)
     {
       if (--rep->count == 0)
         delete rep;
@@ -324,16 +332,16 @@
 
   // No checking, even for multiple references, ever.
 
-  T& xelem (octave_idx_type n) { return slice_data [n]; }
-  crefT xelem (octave_idx_type n) const { return slice_data [n]; }
+  T& xelem (octave_idx_type n) { return slice_data[n]; }
+  crefT xelem (octave_idx_type n) const { return slice_data[n]; }
 
-  T& xelem (octave_idx_type i, octave_idx_type j) { return xelem (dim1()*j+i); }
-  crefT xelem (octave_idx_type i, octave_idx_type j) const { return xelem (dim1()*j+i); }
+  T& xelem (octave_idx_type i, octave_idx_type j) { return xelem (dim1 ()*j+i); }
+  crefT xelem (octave_idx_type i, octave_idx_type j) const { return xelem (dim1 ()*j+i); }
 
   T& xelem (octave_idx_type i, octave_idx_type j, octave_idx_type k)
-    { return xelem (i, dim2()*k+j); }
+    { return xelem (i, dim2 ()*k+j); }
   crefT xelem (octave_idx_type i, octave_idx_type j, octave_idx_type k) const
-    { return xelem (i, dim2()*k+j); }
+    { return xelem (i, dim2 ()*k+j); }
 
   T& xelem (const Array<octave_idx_type>& ra_idx)
     { return xelem (compute_index_unchecked (ra_idx)); }
@@ -356,9 +364,9 @@
       return xelem (n);
     }
 
-  T& elem (octave_idx_type i, octave_idx_type j) { return elem (dim1()*j+i); }
+  T& elem (octave_idx_type i, octave_idx_type j) { return elem (dim1 ()*j+i); }
 
-  T& elem (octave_idx_type i, octave_idx_type j, octave_idx_type k) { return elem (i, dim2()*k+j); }
+  T& elem (octave_idx_type i, octave_idx_type j, octave_idx_type k) { return elem (i, dim2 ()*k+j); }
 
   T& elem (const Array<octave_idx_type>& ra_idx)
     { return Array<T>::elem (compute_index_unchecked (ra_idx)); }
@@ -450,46 +458,69 @@
 
   Array<T> index (const Array<idx_vector>& ia) const;
 
-  static const T& resize_fill_value ();
+  virtual T resize_fill_value (void) const;
 
   // Resizing (with fill).
 
-  void resize1 (octave_idx_type n, const T& rfv = resize_fill_value ());
+  void resize1 (octave_idx_type n, const T& rfv);
+  void resize1 (octave_idx_type n) { resize1 (n, resize_fill_value ()); }
 
-  void resize (octave_idx_type n) GCC_ATTR_DEPRECATED
-    { resize1 (n); }
+  void resize (octave_idx_type n) GCC_ATTR_DEPRECATED { resize1 (n); }
 
-  void resize (octave_idx_type nr, octave_idx_type nc,
-               const T& rfv = resize_fill_value ()) GCC_ATTR_DEPRECATED
+  void resize (octave_idx_type nr, octave_idx_type nc, const T& rfv) GCC_ATTR_DEPRECATED
   {
     resize2 (nr, nc, rfv);
   }
 
-  void resize (const dim_vector& dv, const T& rfv = resize_fill_value ());
+  void resize (octave_idx_type nr, octave_idx_type nc) GCC_ATTR_DEPRECATED
+  {
+    resize2 (nr, nc, resize_fill_value ());
+  }
+
+  void resize (const dim_vector& dv, const T& rfv);
+  void resize (const dim_vector& dv) { resize (dv, resize_fill_value ()); }
 
   // Indexing with possible resizing and fill
   // FIXME -- this is really a corner case, that should better be
   // handled directly in liboctinterp.
 
-  Array<T> index (const idx_vector& i, bool resize_ok,
-                  const T& rfv = resize_fill_value ()) const;
+  Array<T> index (const idx_vector& i, bool resize_ok, const T& rfv) const;
+  Array<T> index (const idx_vector& i, bool resize_ok) const
+  {
+    return index (i, resize_ok, resize_fill_value ());
+  }
 
-  Array<T> index (const idx_vector& i, const idx_vector& j,
-                  bool resize_ok, const T& rfv = resize_fill_value ()) const;
+  Array<T> index (const idx_vector& i, const idx_vector& j, bool resize_ok, const T& rfv) const;
+  Array<T> index (const idx_vector& i, const idx_vector& j, bool resize_ok) const
+  {
+    return index (i, j, resize_ok, resize_fill_value ());
+  }
 
-  Array<T> index (const Array<idx_vector>& ia,
-                  bool resize_ok, const T& rfv = resize_fill_value ()) const;
+  Array<T> index (const Array<idx_vector>& ia, bool resize_ok, const T& rfv) const;
+  Array<T> index (const Array<idx_vector>& ia, bool resize_ok) const
+  {
+    return index (ia, resize_ok, resize_fill_value ());
+  }
 
   // Indexed assignment (always with resize & fill).
 
-  void assign (const idx_vector& i, const Array<T>& rhs,
-               const T& rfv = resize_fill_value ());
+  void assign (const idx_vector& i, const Array<T>& rhs, const T& rfv);
+  void assign (const idx_vector& i, const Array<T>& rhs)
+  {
+    assign (i, rhs, resize_fill_value ());
+  }
 
-  void assign (const idx_vector& i, const idx_vector& j, const Array<T>& rhs,
-               const T& rfv = resize_fill_value ());
+  void assign (const idx_vector& i, const idx_vector& j, const Array<T>& rhs, const T& rfv);
+  void assign (const idx_vector& i, const idx_vector& j, const Array<T>& rhs)
+  {
+    assign (i, j, rhs, resize_fill_value ());
+  }
 
-  void assign (const Array<idx_vector>& ia, const Array<T>& rhs,
-               const T& rfv = resize_fill_value ());
+  void assign (const Array<idx_vector>& ia, const Array<T>& rhs, const T& rfv);
+  void assign (const Array<idx_vector>& ia, const Array<T>& rhs)
+  {
+    assign (ia, rhs, resize_fill_value ());
+  }
 
   // Deleting elements.
 
@@ -562,6 +593,8 @@
 
   Array<T> diag (octave_idx_type k = 0) const;
 
+  Array<T> diag (octave_idx_type m, octave_idx_type n) const;
+
   // Concatenation along a specified (0-based) dimension, equivalent to cat().
   // dim = -1 corresponds to dim = 0 and dim = -2 corresponds to dim = 1,
   // but apply the looser matching rules of vertcat/horzcat.
@@ -613,30 +646,7 @@
   template <class F, bool zero>
   bool test (F fcn) const
   {
-    octave_idx_type len = length ();
-
-    const T *m = data ();
-
-    octave_idx_type i;
-    for (i = 0; i < len - 3; i += 4)
-      {
-        octave_quit ();
-
-        if (fcn (m[i]) != zero
-            || fcn (m[i+1]) != zero
-            || fcn (m[i+2]) != zero
-            || fcn (m[i+3]) != zero)
-           return ! zero;
-
-      }
-
-    octave_quit ();
-
-    for (; i < len; i++)
-       if (fcn (m[i]) != zero)
-          return ! zero;
-
-    return zero;
+    return any_all_test<F, T, zero> (fcn, data (), length ());
   }
 
   // Simpler calls.
@@ -668,10 +678,23 @@
   // supposedly equal dimensions (e.g. structs in the interpreter).
   bool optimize_dimensions (const dim_vector& dv);
 
+  // WARNING: Only call these functions from jit
+
+  int *jit_ref_count (void) { return rep->count.get (); }
+
+  T *jit_slice_data (void) const { return slice_data; }
+
+  octave_idx_type *jit_dimensions (void) const { return dimensions.to_jit (); }
+
+  void *jit_array_rep (void) const { return rep; }
+
 private:
 
-  void resize2 (octave_idx_type nr, octave_idx_type nc,
-                const T& rfv = resize_fill_value ());
+  void resize2 (octave_idx_type nr, octave_idx_type nc, const T& rfv);
+  void resize2 (octave_idx_type nr, octave_idx_type nc)                
+  {
+    resize2 (nr, nc, resize_fill_value ());
+  }
 
   static void instantiation_guard ();
 };
rename from liboctave/Array2.h
rename to liboctave/array/Array2.h
rename from liboctave/Array3.h
rename to liboctave/array/Array3.h
rename from liboctave/ArrayN.h
rename to liboctave/array/ArrayN.h
rename from liboctave/CColVector.cc
rename to liboctave/array/CColVector.cc
--- a/liboctave/CColVector.cc
+++ b/liboctave/array/CColVector.cc
@@ -515,7 +515,7 @@
 std::istream&
 operator >> (std::istream& is, ComplexColumnVector& a)
 {
-  octave_idx_type len = a.length();
+  octave_idx_type len = a.length ();
 
   if (len > 0)
     {
rename from liboctave/CColVector.h
rename to liboctave/array/CColVector.h
--- a/liboctave/CColVector.h
+++ b/liboctave/array/CColVector.h
@@ -132,8 +132,7 @@
   friend OCTAVE_API std::ostream& operator << (std::ostream& os, const ComplexColumnVector& a);
   friend OCTAVE_API std::istream& operator >> (std::istream& is, ComplexColumnVector& a);
 
-  void resize (octave_idx_type n,
-               const Complex& rfv = Array<Complex>::resize_fill_value ())
+  void resize (octave_idx_type n, const Complex& rfv = Complex (0))
   {
     Array<Complex>::resize (dim_vector (n, 1), rfv);
   }
rename from liboctave/CDiagMatrix.cc
rename to liboctave/array/CDiagMatrix.cc
--- a/liboctave/CDiagMatrix.cc
+++ b/liboctave/array/CDiagMatrix.cc
@@ -236,13 +236,13 @@
 DiagMatrix
 ComplexDiagMatrix::abs (void) const
 {
-  return DiagMatrix (diag ().abs (), rows (), columns ());
+  return DiagMatrix (extract_diag ().abs (), rows (), columns ());
 }
 
 ComplexDiagMatrix
 conj (const ComplexDiagMatrix& a)
 {
-  return ComplexDiagMatrix (conj (a.diag ()), a.rows (), a.columns ());
+  return ComplexDiagMatrix (conj (a.extract_diag ()), a.rows (), a.columns ());
 }
 
 // resize is the destructive analog for this one
@@ -546,7 +546,7 @@
 double
 ComplexDiagMatrix::rcond (void) const
 {
-  ColumnVector av = diag (0).map<double> (std::abs);
+  ColumnVector av = extract_diag (0).map<double> (std::abs);
   double amx = av.max (), amn = av.min ();
   return amx == 0 ? 0.0 : amn / amx;
 }
rename from liboctave/CDiagMatrix.h
rename to liboctave/array/CDiagMatrix.h
--- a/liboctave/CDiagMatrix.h
+++ b/liboctave/array/CDiagMatrix.h
@@ -90,7 +90,7 @@
   ComplexDiagMatrix& fill (const ComplexRowVector& a, octave_idx_type beg);
 
   ComplexDiagMatrix hermitian (void) const { return MDiagArray2<Complex>::hermitian (std::conj); }
-  ComplexDiagMatrix transpose (void) const { return MDiagArray2<Complex>::transpose(); }
+  ComplexDiagMatrix transpose (void) const { return MDiagArray2<Complex>::transpose (); }
   DiagMatrix abs (void) const;
 
   friend OCTAVE_API ComplexDiagMatrix conj (const ComplexDiagMatrix& a);
@@ -120,8 +120,8 @@
 
   // other operations
 
-  ComplexColumnVector diag (octave_idx_type k = 0) const
-    { return MDiagArray2<Complex>::diag (k); }
+  ComplexColumnVector extract_diag (octave_idx_type k = 0) const
+    { return MDiagArray2<Complex>::extract_diag (k); }
 
   ComplexDET determinant (void) const;
   double rcond (void) const;
rename from liboctave/CMatrix.cc
rename to liboctave/array/CMatrix.cc
--- a/liboctave/CMatrix.cc
+++ b/liboctave/array/CMatrix.cc
@@ -1079,7 +1079,7 @@
       F77_XFCN (zgetri, ZGETRI, (nc, tmp_data, nr, pipvt,
                                  z.fortran_vec (), lwork, info));
 
-      lwork = static_cast<octave_idx_type> (std::real(z(0)));
+      lwork = static_cast<octave_idx_type> (std::real (z(0)));
       lwork = (lwork <  2 *nc ? 2*nc : lwork);
       z.resize (dim_vector (lwork, 1));
       Complex *pz = z.fortran_vec ();
@@ -1089,7 +1089,7 @@
       // Calculate the norm of the matrix, for later use.
       double anorm;
       if (calc_cond)
-        anorm  = retval.abs().sum().row(static_cast<octave_idx_type>(0)).max();
+        anorm = retval.abs ().sum ().row (static_cast<octave_idx_type>(0)).max ();
 
       F77_XFCN (zgetrf, ZGETRF, (nc, nc, tmp_data, nr, pipvt, info));
 
@@ -1127,7 +1127,7 @@
         }
 
       if (info != 0)
-        mattype.mark_as_rectangular();
+        mattype.mark_as_rectangular ();
     }
 
   return retval;
@@ -1153,7 +1153,7 @@
           if (info == 0)
             {
               if (calc_cond)
-                rcon = chol.rcond();
+                rcon = chol.rcond ();
               else
                 rcon = 1.0;
               ret = chol.inverse ();
@@ -1163,7 +1163,7 @@
         }
 
       if (!mattype.is_hermitian ())
-        ret = finverse(mattype, info, rcon, force, calc_cond);
+        ret = finverse (mattype, info, rcon, force, calc_cond);
 
       if ((mattype.is_hermitian () || calc_cond) && rcon == 0.)
         ret = ComplexMatrix (rows (), columns (), Complex (octave_Inf, 0.));
@@ -1183,7 +1183,7 @@
   ComplexMatrix U = result.left_singular_matrix ();
   ComplexMatrix V = result.right_singular_matrix ();
 
-  ColumnVector sigma = S.diag ();
+  ColumnVector sigma = S.extract_diag ();
 
   octave_idx_type r = sigma.length () - 1;
   octave_idx_type nr = rows ();
@@ -1192,9 +1192,9 @@
   if (tol <= 0.0)
     {
       if (nr > nc)
-        tol = nr * sigma.elem (0) * DBL_EPSILON;
+        tol = nr * sigma.elem (0) * std::numeric_limits<double>::epsilon ();
       else
-        tol = nc * sigma.elem (0) * DBL_EPSILON;
+        tol = nc * sigma.elem (0) * std::numeric_limits<double>::epsilon ();
     }
 
   while (r >= 0 && sigma.elem (r) < tol)
@@ -1721,7 +1721,7 @@
     rcon = octave_Inf;
   else
     {
-      int typ = mattype.type ();
+      volatile int typ = mattype.type ();
 
       if (typ == MatrixType::Unknown)
         typ = mattype.type (*this);
@@ -1837,9 +1837,9 @@
               Array<octave_idx_type> ipvt (dim_vector (nr, 1));
               octave_idx_type *pipvt = ipvt.fortran_vec ();
 
-              if(anorm < 0.)
-                anorm = atmp.abs().sum().
-                  row(static_cast<octave_idx_type>(0)).max();
+              if (anorm < 0.)
+                anorm = atmp.abs ().sum ().
+                  row(static_cast<octave_idx_type>(0)).max ();
 
               Array<Complex> z (dim_vector (2 * nc, 1));
               Complex *pz = z.fortran_vec ();
@@ -2163,7 +2163,7 @@
 
                   F77_XFCN (zpotrs, ZPOTRS, (F77_CONST_CHAR_ARG2 (&job, 1),
                                              nr, b_nc, tmp_data, nr,
-                                             result, b.rows(), info
+                                             result, b.rows (), info
                                              F77_CHAR_ARG_LEN (1)));
                 }
               else
@@ -2191,7 +2191,7 @@
 
           // Calculate the norm of the matrix, for later use.
           if (anorm < 0.)
-            anorm = atmp.abs().sum().row(static_cast<octave_idx_type>(0)).max();
+            anorm = atmp.abs ().sum ().row (static_cast<octave_idx_type>(0)).max ();
 
           F77_XFCN (zgetrf, ZGETRF, (nr, nr, tmp_data, nr, pipvt, info));
 
@@ -2249,7 +2249,7 @@
                   char job = 'N';
                   F77_XFCN (zgetrs, ZGETRS, (F77_CONST_CHAR_ARG2 (&job, 1),
                                              nr, b_nc, tmp_data, nr,
-                                             pipvt, result, b.rows(), info
+                                             pipvt, result, b.rows (), info
                                              F77_CHAR_ARG_LEN (1)));
                 }
               else
@@ -2417,7 +2417,7 @@
 
   ComplexMatrix tmp (b);
   tmp = solve (typ, tmp, info, rcon, sing_handler, true, transt);
-  return tmp.column(static_cast<octave_idx_type> (0));
+  return tmp.column (static_cast<octave_idx_type> (0));
 }
 
 ComplexMatrix
@@ -3169,25 +3169,7 @@
 bool
 ComplexMatrix::too_large_for_float (void) const
 {
-  octave_idx_type nr = rows ();
-  octave_idx_type nc = cols ();
-
-  for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = 0; i < nr; i++)
-      {
-        Complex val = elem (i, j);
-
-        double r_val = std::real (val);
-        double i_val = std::imag (val);
-
-        if ((! (xisnan (r_val) || xisinf (r_val))
-             && fabs (r_val) > FLT_MAX)
-            || (! (xisnan (i_val) || xisinf (i_val))
-                && fabs (i_val) > FLT_MAX))
-          return true;
-      }
-
-  return false;
+  return test_any (xtoo_large_for_float);
 }
 
 // FIXME Do these really belong here?  Maybe they should be
@@ -3246,6 +3228,23 @@
   return MArray<Complex>::diag (k);
 }
 
+ComplexDiagMatrix
+ComplexMatrix::diag (octave_idx_type m, octave_idx_type n) const
+{
+  ComplexDiagMatrix retval;
+
+  octave_idx_type nr = rows ();
+  octave_idx_type nc = cols ();
+
+  if (nr == 1 || nc == 1)
+    retval = ComplexDiagMatrix (*this, m, n);
+  else
+    (*current_liboctave_error_handler)
+      ("diag: expecting vector argument");
+
+  return retval;
+}
+
 bool
 ComplexMatrix::row_is_real_only (octave_idx_type i) const
 {
@@ -3709,25 +3708,27 @@
     return ComplexMatrix (m) * a;
 }
 
-/* Simple Dot Product, Matrix-Vector and Matrix-Matrix Unit tests
-%!assert([1+i 2+i 3+i] * [ 4+i ; 5+i ; 6+i], 29+21i, 1e-14)
-%!assert([1+i 2+i ; 3+i 4+i ] * [5+i ; 6+i], [15 + 14i ; 37 + 18i], 1e-14)
-%!assert([1+i 2+i ; 3+i 4+i ] * [5+i 6+i ; 7+i 8+i], [17 + 15i 20 + 17i; 41 + 19i 48 + 21i], 1e-14)
-%!assert([1 i]*[i 0]', -i);
-*/
-
-/* Test some simple identities
+/*
+
+## Simple Dot Product, Matrix-Vector, and Matrix-Matrix Unit tests
+%!assert ([1+i 2+i 3+i] * [ 4+i ; 5+i ; 6+i], 29+21i, 1e-14)
+%!assert ([1+i 2+i ; 3+i 4+i ] * [5+i ; 6+i], [15 + 14i ; 37 + 18i], 1e-14)
+%!assert ([1+i 2+i ; 3+i 4+i ] * [5+i 6+i ; 7+i 8+i], [17 + 15i 20 + 17i; 41 + 19i 48 + 21i], 1e-14)
+%!assert ([1 i]*[i 0]', -i);
+
+## Test some simple identities
 %!shared M, cv, rv
-%! M = randn(10,10)+i*rand(10,10);
-%! cv = randn(10,1)+i*rand(10,1);
-%! rv = randn(1,10)+i*rand(1,10);
-%!assert([M*cv,M*cv],M*[cv,cv],1e-14)
-%!assert([M.'*cv,M.'*cv],M.'*[cv,cv],1e-14)
-%!assert([M'*cv,M'*cv],M'*[cv,cv],1e-14)
-%!assert([rv*M;rv*M],[rv;rv]*M,1e-14)
-%!assert([rv*M.';rv*M.'],[rv;rv]*M.',1e-14)
-%!assert([rv*M';rv*M'],[rv;rv]*M',1e-14)
-%!assert(2*rv*cv,[rv,rv]*[cv;cv],1e-14)
+%! M = randn (10,10) + i*rand (10,10);
+%! cv = randn (10,1) + i*rand (10,1);
+%! rv = randn (1,10) + i*rand (1,10);
+%!assert ([M*cv,M*cv], M*[cv,cv], 1e-14)
+%!assert ([M.'*cv,M.'*cv], M.'*[cv,cv], 1e-14)
+%!assert ([M'*cv,M'*cv], M'*[cv,cv], 1e-14)
+%!assert ([rv*M;rv*M], [rv;rv]*M, 1e-14)
+%!assert ([rv*M.';rv*M.'], [rv;rv]*M.', 1e-14)
+%!assert ([rv*M';rv*M'], [rv;rv]*M', 1e-14)
+%!assert (2*rv*cv, [rv,rv]*[cv;cv], 1e-14)
+
 */
 
 static inline char
rename from liboctave/CMatrix.h
rename to liboctave/array/CMatrix.h
--- a/liboctave/CMatrix.h
+++ b/liboctave/array/CMatrix.h
@@ -152,7 +152,7 @@
   ComplexColumnVector column (octave_idx_type i) const;
 
   void resize (octave_idx_type nr, octave_idx_type nc,
-               const Complex& rfv = resize_fill_value ())
+               const Complex& rfv = Complex (0))
   {
     MArray<Complex>::resize (dim_vector (nr, nc), rfv);
   }
@@ -357,6 +357,8 @@
 
   ComplexMatrix diag (octave_idx_type k = 0) const;
 
+  ComplexDiagMatrix diag (octave_idx_type m, octave_idx_type n) const;
+
   bool row_is_real_only (octave_idx_type) const;
   bool column_is_real_only (octave_idx_type) const;
 
@@ -376,9 +378,6 @@
 
   friend OCTAVE_API std::ostream& operator << (std::ostream& os, const ComplexMatrix& a);
   friend OCTAVE_API std::istream& operator >> (std::istream& is, ComplexMatrix& a);
-
-  static Complex resize_fill_value (void) { return Complex (0.0, 0.0); }
-
 };
 
 extern OCTAVE_API ComplexMatrix conj (const ComplexMatrix& a);
rename from liboctave/CNDArray.cc
rename to liboctave/array/CNDArray.cc
--- a/liboctave/CNDArray.cc
+++ b/liboctave/array/CNDArray.cc
@@ -119,7 +119,7 @@
 ComplexNDArray
 ComplexNDArray::fourier2d (void) const
 {
-  dim_vector dv = dims();
+  dim_vector dv = dims ();
   if (dv.length () < 2)
     return ComplexNDArray ();
 
@@ -127,7 +127,7 @@
   const Complex *in = fortran_vec ();
   ComplexNDArray retval (dv);
   Complex *out = retval.fortran_vec ();
-  octave_idx_type howmany = numel() / dv(0) / dv(1);
+  octave_idx_type howmany = numel () / dv(0) / dv(1);
   octave_idx_type dist = dv(0) * dv(1);
 
   for (octave_idx_type i=0; i < howmany; i++)
@@ -139,7 +139,7 @@
 ComplexNDArray
 ComplexNDArray::ifourier2d (void) const
 {
-  dim_vector dv = dims();
+  dim_vector dv = dims ();
   if (dv.length () < 2)
     return ComplexNDArray ();
 
@@ -147,7 +147,7 @@
   const Complex *in = fortran_vec ();
   ComplexNDArray retval (dv);
   Complex *out = retval.fortran_vec ();
-  octave_idx_type howmany = numel() / dv(0) / dv(1);
+  octave_idx_type howmany = numel () / dv(0) / dv(1);
   octave_idx_type dist = dv(0) * dv(1);
 
   for (octave_idx_type i=0; i < howmany; i++)
@@ -240,12 +240,12 @@
           octave_quit ();
 
           for (octave_idx_type i = 0; i < npts; i++)
-            tmp[i] = elem((i + k*npts)*stride + j*dist);
+            tmp[i] = elem ((i + k*npts)*stride + j*dist);
 
           F77_FUNC (zfftf, ZFFTF) (npts, tmp, pwsave);
 
           for (octave_idx_type i = 0; i < npts; i++)
-            retval ((i + k*npts)*stride + j*dist) = tmp[i];
+            retval((i + k*npts)*stride + j*dist) = tmp[i];
         }
     }
 
@@ -287,12 +287,12 @@
           octave_quit ();
 
           for (octave_idx_type i = 0; i < npts; i++)
-            tmp[i] = elem((i + k*npts)*stride + j*dist);
+            tmp[i] = elem ((i + k*npts)*stride + j*dist);
 
           F77_FUNC (zfftb, ZFFTB) (npts, tmp, pwsave);
 
           for (octave_idx_type i = 0; i < npts; i++)
-            retval ((i + k*npts)*stride + j*dist) = tmp[i] /
+            retval((i + k*npts)*stride + j*dist) = tmp[i] /
               static_cast<double> (npts);
         }
     }
@@ -333,12 +333,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (zfftf, ZFFTF) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l];
+                retval((l + k*npts)*stride + j*dist) = prow[l];
             }
         }
 
@@ -351,7 +351,7 @@
 ComplexNDArray
 ComplexNDArray::ifourier2d (void) const
 {
-  dim_vector dv = dims();
+  dim_vector dv = dims ();
   dim_vector dv2 (dv(0), dv(1));
   int rank = 2;
   ComplexNDArray retval (*this);
@@ -381,12 +381,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (zfftb, ZFFTB) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l] /
+                retval((l + k*npts)*stride + j*dist) = prow[l] /
                   static_cast<double> (npts);
             }
         }
@@ -429,12 +429,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (zfftf, ZFFTF) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l];
+                retval((l + k*npts)*stride + j*dist) = prow[l];
             }
         }
 
@@ -476,12 +476,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (zfftb, ZFFTB) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l] /
+                retval((l + k*npts)*stride + j*dist) = prow[l] /
                   static_cast<double> (npts);
             }
         }
@@ -584,23 +584,7 @@
 bool
 ComplexNDArray::too_large_for_float (void) const
 {
-  octave_idx_type nel = nelem ();
-
-  for (octave_idx_type i = 0; i < nel; i++)
-    {
-      Complex val = elem (i);
-
-      double r_val = std::real (val);
-      double i_val = std::imag (val);
-
-      if ((! (xisnan (r_val) || xisinf (r_val))
-           && fabs (r_val) > FLT_MAX)
-          || (! (xisnan (i_val) || xisinf (i_val))
-              && fabs (i_val) > FLT_MAX))
-        return true;
-    }
-
-  return false;
+  return test_any (xtoo_large_for_float);
 }
 
 boolNDArray
@@ -862,6 +846,12 @@
   return MArray<Complex>::diag (k);
 }
 
+ComplexNDArray
+ComplexNDArray::diag (octave_idx_type m, octave_idx_type n) const
+{
+  return MArray<Complex>::diag (m, n);
+}
+
 // This contains no information on the array structure !!!
 std::ostream&
 operator << (std::ostream& os, const ComplexNDArray& a)
rename from liboctave/CNDArray.h
rename to liboctave/array/CNDArray.h
--- a/liboctave/CNDArray.h
+++ b/liboctave/array/CNDArray.h
@@ -135,13 +135,13 @@
   friend OCTAVE_API std::ostream& operator << (std::ostream& os, const ComplexNDArray& a);
   friend OCTAVE_API std::istream& operator >> (std::istream& is, ComplexNDArray& a);
 
-  static Complex resize_fill_value (void) { return Complex (0.0, 0.0); }
-
   //  bool all_elements_are_real (void) const;
   //  bool all_integers (double& max_val, double& min_val) const;
 
   ComplexNDArray diag (octave_idx_type k = 0) const;
 
+  ComplexNDArray diag (octave_idx_type m, octave_idx_type n) const;
+
   ComplexNDArray& changesign (void)
     {
       MArray<Complex>::changesign ();
rename from liboctave/CRowVector.cc
rename to liboctave/array/CRowVector.cc
--- a/liboctave/CRowVector.cc
+++ b/liboctave/array/CRowVector.cc
@@ -411,7 +411,7 @@
 std::istream&
 operator >> (std::istream& is, ComplexRowVector& a)
 {
-  octave_idx_type len = a.length();
+  octave_idx_type len = a.length ();
 
   if (len > 0)
     {
rename from liboctave/CRowVector.h
rename to liboctave/array/CRowVector.h
--- a/liboctave/CRowVector.h
+++ b/liboctave/array/CRowVector.h
@@ -112,8 +112,7 @@
   friend std::ostream& operator << (std::ostream& os, const ComplexRowVector& a);
   friend std::istream& operator >> (std::istream& is, ComplexRowVector& a);
 
-  void resize (octave_idx_type n,
-               const Complex& rfv = Array<Complex>::resize_fill_value ())
+  void resize (octave_idx_type n, const Complex& rfv = Complex (0))
   {
     Array<Complex>::resize (dim_vector (1, n), rfv);
   }
rename from liboctave/CSparse.cc
rename to liboctave/array/CSparse.cc
--- a/liboctave/CSparse.cc
+++ b/liboctave/array/CSparse.cc
@@ -172,7 +172,7 @@
         }
     }
   for (octave_idx_type i = l; i <= a.cols (); i++)
-    cidx(i) = j;
+    cidx (i) = j;
 }
 bool
 SparseComplexMatrix::operator == (const SparseComplexMatrix& a) const
@@ -188,11 +188,11 @@
     return false;
 
   for (octave_idx_type i = 0; i < nc + 1; i++)
-    if (cidx(i) != a.cidx(i))
+    if (cidx (i) != a.cidx (i))
         return false;
 
   for (octave_idx_type i = 0; i < nz; i++)
-    if (data(i) != a.data(i) || ridx(i) != a.ridx(i))
+    if (data (i) != a.data (i) || ridx (i) != a.ridx (i))
       return false;
 
   return true;
@@ -214,19 +214,19 @@
     {
       for (octave_idx_type j = 0; j < nc; j++)
         {
-          for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-            {
-              octave_idx_type ri = ridx(i);
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+            {
+              octave_idx_type ri = ridx (i);
 
               if (ri != j)
                 {
                   bool found = false;
 
-                  for (octave_idx_type k = cidx(ri); k < cidx(ri+1); k++)
+                  for (octave_idx_type k = cidx (ri); k < cidx (ri+1); k++)
                     {
-                      if (ridx(k) == j)
+                      if (ridx (k) == j)
                         {
-                          if (data(i) == conj(data(k)))
+                          if (data (i) == conj (data (k)))
                             found = true;
                           break;
                         }
@@ -277,9 +277,9 @@
           Complex tmp_max;
           double abs_max = octave_NaN;
           octave_idx_type idx_j = 0;
-          for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-            {
-              if (ridx(i) != idx_j)
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+            {
+              if (ridx (i) != idx_j)
                 break;
               else
                 idx_j++;
@@ -291,7 +291,7 @@
               abs_max = 0.;
             }
 
-          for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
             {
               Complex tmp = data (i);
 
@@ -332,30 +332,30 @@
     {
       idx_arg.resize (dim_vector (nr, 1), 0);
 
-      for (octave_idx_type i = cidx(0); i < cidx(1); i++)
-        idx_arg.elem(ridx(i)) = -1;
+      for (octave_idx_type i = cidx (0); i < cidx (1); i++)
+        idx_arg.elem (ridx (i)) = -1;
 
       for (octave_idx_type j = 0; j < nc; j++)
         for (octave_idx_type i = 0; i < nr; i++)
           {
-            if (idx_arg.elem(i) != -1)
+            if (idx_arg.elem (i) != -1)
               continue;
             bool found = false;
-            for (octave_idx_type k = cidx(j); k < cidx(j+1); k++)
-              if (ridx(k) == i)
+            for (octave_idx_type k = cidx (j); k < cidx (j+1); k++)
+              if (ridx (k) == i)
                 {
                   found = true;
                   break;
                 }
 
             if (!found)
-              idx_arg.elem(i) = j;
+              idx_arg.elem (i) = j;
 
           }
 
       for (octave_idx_type j = 0; j < nc; j++)
         {
-          for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
             {
               octave_idx_type ir = ridx (i);
               octave_idx_type ix = idx_arg.elem (ir);
@@ -363,14 +363,14 @@
 
               if (xisnan (tmp))
                 continue;
-              else if (ix == -1 || std::abs(tmp) > std::abs(elem (ir, ix)))
+              else if (ix == -1 || std::abs (tmp) > std::abs (elem (ir, ix)))
                 idx_arg.elem (ir) = j;
             }
         }
 
       octave_idx_type nel = 0;
       for (octave_idx_type j = 0; j < nr; j++)
-        if (idx_arg.elem(j) == -1 || elem (j, idx_arg.elem (j)) != 0.)
+        if (idx_arg.elem (j) == -1 || elem (j, idx_arg.elem (j)) != 0.)
           nel++;
 
       result = SparseComplexMatrix (nr, 1, nel);
@@ -432,9 +432,9 @@
           Complex tmp_min;
           double abs_min = octave_NaN;
           octave_idx_type idx_j = 0;
-          for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-            {
-              if (ridx(i) != idx_j)
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+            {
+              if (ridx (i) != idx_j)
                 break;
               else
                 idx_j++;
@@ -446,7 +446,7 @@
               abs_min = 0.;
             }
 
-          for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
             {
               Complex tmp = data (i);
 
@@ -487,30 +487,30 @@
     {
       idx_arg.resize (dim_vector (nr, 1), 0);
 
-      for (octave_idx_type i = cidx(0); i < cidx(1); i++)
-        idx_arg.elem(ridx(i)) = -1;
+      for (octave_idx_type i = cidx (0); i < cidx (1); i++)
+        idx_arg.elem (ridx (i)) = -1;
 
       for (octave_idx_type j = 0; j < nc; j++)
         for (octave_idx_type i = 0; i < nr; i++)
           {
-            if (idx_arg.elem(i) != -1)
+            if (idx_arg.elem (i) != -1)
               continue;
             bool found = false;
-            for (octave_idx_type k = cidx(j); k < cidx(j+1); k++)
-              if (ridx(k) == i)
+            for (octave_idx_type k = cidx (j); k < cidx (j+1); k++)
+              if (ridx (k) == i)
                 {
                   found = true;
                   break;
                 }
 
             if (!found)
-              idx_arg.elem(i) = j;
+              idx_arg.elem (i) = j;
 
           }
 
       for (octave_idx_type j = 0; j < nc; j++)
         {
-          for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
             {
               octave_idx_type ir = ridx (i);
               octave_idx_type ix = idx_arg.elem (ir);
@@ -518,14 +518,14 @@
 
               if (xisnan (tmp))
                 continue;
-              else if (ix == -1 || std::abs(tmp) < std::abs(elem (ir, ix)))
+              else if (ix == -1 || std::abs (tmp) < std::abs (elem (ir, ix)))
                 idx_arg.elem (ir) = j;
             }
         }
 
       octave_idx_type nel = 0;
       for (octave_idx_type j = 0; j < nr; j++)
-        if (idx_arg.elem(j) == -1 || elem (j, idx_arg.elem (j)) != 0.)
+        if (idx_arg.elem (j) == -1 || elem (j, idx_arg.elem (j)) != 0.)
           nel++;
 
       result = SparseComplexMatrix (nr, 1, nel);
@@ -663,7 +663,7 @@
   // retval.xcidx[1:nr] holds row entry *start* offsets for rows 0:(nr-1)
 
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type k = cidx(j); k < cidx(j+1); k++)
+    for (octave_idx_type k = cidx (j); k < cidx (j+1); k++)
       {
         octave_idx_type q = retval.xcidx (ridx (k) + 1)++;
         retval.xridx (q) = j;
@@ -743,19 +743,19 @@
           typ == MatrixType::Permuted_Diagonal)
         {
           if (typ == MatrixType::Permuted_Diagonal)
-            retval = transpose();
+            retval = transpose ();
           else
             retval = *this;
 
           // Force make_unique to be called
-          Complex *v = retval.data();
+          Complex *v = retval.data ();
 
           if (calccond)
             {
               double dmax = 0., dmin = octave_Inf;
               for (octave_idx_type i = 0; i < nr; i++)
                 {
-                  double tmp = std::abs(v[i]);
+                  double tmp = std::abs (v[i]);
                   if (tmp > dmax)
                     dmax = tmp;
                   if (tmp < dmin)
@@ -805,8 +805,8 @@
               for (octave_idx_type j = 0; j < nr; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += std::abs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += std::abs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -831,9 +831,9 @@
                       retval.change_capacity (nz2);
                     }
 
-                  retval.xcidx(i) = cx;
-                  retval.xridx(cx) = i;
-                  retval.xdata(cx) = 1.0;
+                  retval.xcidx (i) = cx;
+                  retval.xridx (cx) = i;
+                  retval.xdata (cx) = 1.0;
                   cx++;
 
                   // iterate accross columns of input matrix
@@ -841,11 +841,11 @@
                     {
                       Complex v = 0.;
                       // iterate to calculate sum
-                      octave_idx_type colXp = retval.xcidx(i);
-                      octave_idx_type colUp = cidx(j);
+                      octave_idx_type colXp = retval.xcidx (i);
+                      octave_idx_type colUp = cidx (j);
                       octave_idx_type rpX, rpU;
 
-                      if (cidx(j) == cidx(j+1))
+                      if (cidx (j) == cidx (j+1))
                         {
                           (*current_liboctave_error_handler)
                             ("division by zero");
@@ -855,8 +855,8 @@
                       do
                         {
                           octave_quit ();
-                          rpX = retval.xridx(colXp);
-                          rpU = ridx(colUp);
+                          rpX = retval.xridx (colXp);
+                          rpU = ridx (colUp);
 
                           if (rpX < rpU)
                             colXp++;
@@ -864,7 +864,7 @@
                             colUp++;
                           else
                             {
-                              v -= retval.xdata(colXp) * data(colUp);
+                              v -= retval.xdata (colXp) * data (colUp);
                               colXp++;
                               colUp++;
                             }
@@ -874,11 +874,11 @@
 
                       // get A(m,m)
                       if (typ == MatrixType::Upper)
-                        colUp = cidx(j+1) - 1;
+                        colUp = cidx (j+1) - 1;
                       else
-                        colUp = cidx(j);
-                      Complex pivot = data(colUp);
-                      if (pivot == 0. || ridx(colUp) != j)
+                        colUp = cidx (j);
+                      Complex pivot = data (colUp);
+                      if (pivot == 0. || ridx (colUp) != j)
                         {
                           (*current_liboctave_error_handler)
                             ("division by zero");
@@ -893,8 +893,8 @@
                               retval.change_capacity (nz2);
                             }
 
-                          retval.xridx(cx) = j;
-                          retval.xdata(cx) = v / pivot;
+                          retval.xridx (cx) = j;
+                          retval.xdata (cx) = v / pivot;
                           cx++;
                         }
                     }
@@ -902,11 +902,11 @@
                   // get A(m,m)
                   octave_idx_type colUp;
                   if (typ == MatrixType::Upper)
-                    colUp = cidx(i+1) - 1;
+                    colUp = cidx (i+1) - 1;
                   else
-                    colUp = cidx(i);
-                  Complex pivot = data(colUp);
-                  if (pivot == 0. || ridx(colUp) != i)
+                    colUp = cidx (i);
+                  Complex pivot = data (colUp);
+                  if (pivot == 0. || ridx (colUp) != i)
                     {
                       (*current_liboctave_error_handler) ("division by zero");
                       goto inverse_singular;
@@ -914,9 +914,9 @@
 
                   if (pivot != 1.0)
                     for (octave_idx_type j = cx_colstart; j < cx; j++)
-                      retval.xdata(j) /= pivot;
-                }
-              retval.xcidx(nr) = cx;
+                      retval.xdata (j) /= pivot;
+                }
+              retval.xcidx (nr) = cx;
               retval.maybe_compress ();
             }
           else
@@ -929,7 +929,7 @@
               OCTAVE_LOCAL_BUFFER (Complex, work, nr);
               OCTAVE_LOCAL_BUFFER (octave_idx_type, rperm, nr);
 
-              octave_idx_type *perm = mattyp.triangular_perm();
+              octave_idx_type *perm = mattyp.triangular_perm ();
               if (typ == MatrixType::Permuted_Upper)
                 {
                   for (octave_idx_type i = 0; i < nr; i++)
@@ -960,19 +960,19 @@
                       Complex v = 0.;
                       octave_idx_type jidx = perm[j];
                       // iterate to calculate sum
-                      for (octave_idx_type k = cidx(jidx);
-                           k < cidx(jidx+1); k++)
+                      for (octave_idx_type k = cidx (jidx);
+                           k < cidx (jidx+1); k++)
                         {
                           octave_quit ();
-                          v -= work[ridx(k)] * data(k);
+                          v -= work[ridx (k)] * data (k);
                         }
 
                       // get A(m,m)
                       Complex pivot;
                       if (typ == MatrixType::Permuted_Upper)
-                        pivot = data(cidx(jidx+1) - 1);
+                        pivot = data (cidx (jidx+1) - 1);
                       else
-                        pivot = data(cidx(jidx));
+                        pivot = data (cidx (jidx));
                       if (pivot == 0.)
                         {
                           (*current_liboctave_error_handler)
@@ -986,11 +986,11 @@
                   // get A(m,m)
                   octave_idx_type colUp;
                   if (typ == MatrixType::Permuted_Upper)
-                    colUp = cidx(perm[iidx]+1) - 1;
+                    colUp = cidx (perm[iidx]+1) - 1;
                   else
-                    colUp = cidx(perm[iidx]);
-
-                  Complex pivot = data(colUp);
+                    colUp = cidx (perm[iidx]);
+
+                  Complex pivot = data (colUp);
                   if (pivot == 0.)
                     {
                       (*current_liboctave_error_handler)
@@ -1013,16 +1013,16 @@
                       retval.change_capacity (nz2);
                     }
 
-                  retval.xcidx(i) = cx;
+                  retval.xcidx (i) = cx;
                   for (octave_idx_type j = iidx; j < nr; j++)
                     if (work[j] != 0.)
                       {
-                        retval.xridx(cx) = j;
-                        retval.xdata(cx++) = work[j];
+                        retval.xridx (cx) = j;
+                        retval.xdata (cx++) = work[j];
                       }
                 }
 
-              retval.xcidx(nr) = cx;
+              retval.xcidx (nr) = cx;
               retval.maybe_compress ();
             }
 
@@ -1032,9 +1032,9 @@
               for (octave_idx_type j = 0; j < nr; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = retval.cidx(j);
-                       i < retval.cidx(j+1); i++)
-                    atmp += std::abs(retval.data(i));
+                  for (octave_idx_type i = retval.cidx (j);
+                       i < retval.cidx (j+1); i++)
+                    atmp += std::abs (retval.data (i));
                   if (atmp > ainvnorm)
                     ainvnorm = atmp;
                 }
@@ -1049,7 +1049,7 @@
   return retval;
 
  inverse_singular:
-  return SparseComplexMatrix();
+  return SparseComplexMatrix ();
 }
 
 SparseComplexMatrix
@@ -1065,26 +1065,26 @@
   if (typ == MatrixType::Diagonal || typ == MatrixType::Permuted_Diagonal)
     ret = dinverse (mattype, info, rcond, true, calc_cond);
   else if (typ == MatrixType::Upper || typ == MatrixType::Permuted_Upper)
-    ret = tinverse (mattype, info, rcond, true, calc_cond).transpose();
+    ret = tinverse (mattype, info, rcond, true, calc_cond).transpose ();
   else if (typ == MatrixType::Lower || typ == MatrixType::Permuted_Lower)
     {
-      MatrixType newtype = mattype.transpose();
-      ret = transpose().tinverse (newtype, info, rcond, true, calc_cond);
+      MatrixType newtype = mattype.transpose ();
+      ret = transpose ().tinverse (newtype, info, rcond, true, calc_cond);
     }
   else
     {
-      if (mattype.is_hermitian())
+      if (mattype.is_hermitian ())
         {
           MatrixType tmp_typ (MatrixType::Upper);
           SparseComplexCHOL fact (*this, info, false);
-          rcond = fact.rcond();
+          rcond = fact.rcond ();
           if (info == 0)
             {
               double rcond2;
-              SparseMatrix Q = fact.Q();
-              SparseComplexMatrix InvL = fact.L().transpose().
-                tinverse(tmp_typ, info, rcond2, true, false);
-              ret = Q * InvL.hermitian() * InvL * Q.transpose();
+              SparseMatrix Q = fact.Q ();
+              SparseComplexMatrix InvL = fact.L ().transpose ().
+                tinverse (tmp_typ, info, rcond2, true, false);
+              ret = Q * InvL.hermitian () * InvL * Q.transpose ();
             }
           else
             {
@@ -1094,22 +1094,22 @@
             }
         }
 
-      if (!mattype.is_hermitian())
+      if (!mattype.is_hermitian ())
         {
-          octave_idx_type n = rows();
+          octave_idx_type n = rows ();
           ColumnVector Qinit(n);
           for (octave_idx_type i = 0; i < n; i++)
             Qinit(i) = i;
 
           MatrixType tmp_typ (MatrixType::Upper);
           SparseComplexLU fact (*this, Qinit, Matrix (), false, false);
-          rcond = fact.rcond();
+          rcond = fact.rcond ();
           double rcond2;
-          SparseComplexMatrix InvL = fact.L().transpose().
-            tinverse(tmp_typ, info, rcond2, true, false);
-          SparseComplexMatrix InvU = fact.U().
-            tinverse(tmp_typ, info, rcond2, true, false).transpose();
-          ret = fact.Pc().transpose() * InvU * InvL * fact.Pr();
+          SparseComplexMatrix InvL = fact.L ().transpose ().
+            tinverse (tmp_typ, info, rcond2, true, false);
+          SparseComplexMatrix InvU = fact.U ().
+            tinverse (tmp_typ, info, rcond2, true, false).transpose ();
+          ret = fact.Pc ().transpose () * InvU * InvL * fact.Pr ();
         }
     }
 
@@ -1279,23 +1279,23 @@
       if (typ == MatrixType::Diagonal ||
           typ == MatrixType::Permuted_Diagonal)
         {
-          retval.resize (nc, b.cols(), Complex(0.,0.));
+          retval.resize (nc, b.cols (), Complex (0.,0.));
           if (typ == MatrixType::Diagonal)
-            for (octave_idx_type j = 0; j < b.cols(); j++)
+            for (octave_idx_type j = 0; j < b.cols (); j++)
                 for (octave_idx_type i = 0; i < nm; i++)
                   retval(i,j) = b(i,j) / data (i);
           else
-            for (octave_idx_type j = 0; j < b.cols(); j++)
+            for (octave_idx_type j = 0; j < b.cols (); j++)
               for (octave_idx_type k = 0; k < nc; k++)
-                for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
-                  retval(k,j) = b(ridx(i),j) / data (i);
+                for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
+                  retval(k,j) = b(ridx (i),j) / data (i);
 
           if (calc_cond)
             {
               double dmax = 0., dmin = octave_Inf;
               for (octave_idx_type i = 0; i < nm; i++)
                 {
-                  double tmp = std::abs(data(i));
+                  double tmp = std::abs (data (i));
                   if (tmp > dmax)
                     dmax = tmp;
                   if (tmp < dmin)
@@ -1344,30 +1344,30 @@
           octave_idx_type b_nz = b.nnz ();
           retval = SparseComplexMatrix (nc, b_nc, b_nz);
 
-          retval.xcidx(0) = 0;
+          retval.xcidx (0) = 0;
           octave_idx_type ii = 0;
           if (typ == MatrixType::Diagonal)
-            for (octave_idx_type j = 0; j < b.cols(); j++)
+            for (octave_idx_type j = 0; j < b.cols (); j++)
               {
-                for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
+                for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
                   {
-                    if (b.ridx(i) >= nm)
+                    if (b.ridx (i) >= nm)
                       break;
-                    retval.xridx (ii) = b.ridx(i);
-                    retval.xdata (ii++) = b.data(i) / data (b.ridx (i));
+                    retval.xridx (ii) = b.ridx (i);
+                    retval.xdata (ii++) = b.data (i) / data (b.ridx (i));
                   }
-                retval.xcidx(j+1) = ii;
+                retval.xcidx (j+1) = ii;
               }
           else
-            for (octave_idx_type j = 0; j < b.cols(); j++)
+            for (octave_idx_type j = 0; j < b.cols (); j++)
               {
                 for (octave_idx_type l = 0; l < nc; l++)
-                  for (octave_idx_type i = cidx(l); i < cidx(l+1); i++)
+                  for (octave_idx_type i = cidx (l); i < cidx (l+1); i++)
                     {
                       bool found = false;
                       octave_idx_type k;
-                      for (k = b.cidx(j); k < b.cidx(j+1); k++)
-                        if (ridx(i) == b.ridx(k))
+                      for (k = b.cidx (j); k < b.cidx (j+1); k++)
+                        if (ridx (i) == b.ridx (k))
                           {
                             found = true;
                             break;
@@ -1375,10 +1375,10 @@
                       if (found)
                         {
                           retval.xridx (ii) = l;
-                          retval.xdata (ii++) = b.data(k) / data (i);
+                          retval.xdata (ii++) = b.data (k) / data (i);
                         }
                     }
-                retval.xcidx(j+1) = ii;
+                retval.xcidx (j+1) = ii;
               }
 
           if (calc_cond)
@@ -1386,7 +1386,7 @@
               double dmax = 0., dmin = octave_Inf;
               for (octave_idx_type i = 0; i < nm; i++)
                 {
-                  double tmp = std::abs(data(i));
+                  double tmp = std::abs (data (i));
                   if (tmp > dmax)
                     dmax = tmp;
                   if (tmp < dmin)
@@ -1431,23 +1431,23 @@
       if (typ == MatrixType::Diagonal ||
           typ == MatrixType::Permuted_Diagonal)
         {
-          retval.resize (nc, b.cols(), Complex(0.,0.));
+          retval.resize (nc, b.cols (), Complex (0.,0.));
           if (typ == MatrixType::Diagonal)
-            for (octave_idx_type j = 0; j < b.cols(); j++)
+            for (octave_idx_type j = 0; j < b.cols (); j++)
               for (octave_idx_type i = 0; i < nm; i++)
                 retval(i,j) = b(i,j) / data (i);
           else
-            for (octave_idx_type j = 0; j < b.cols(); j++)
+            for (octave_idx_type j = 0; j < b.cols (); j++)
               for (octave_idx_type k = 0; k < nc; k++)
-                for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
-                  retval(k,j) = b(ridx(i),j) / data (i);
+                for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
+                  retval(k,j) = b(ridx (i),j) / data (i);
 
           if (calc_cond)
             {
               double dmax = 0., dmin = octave_Inf;
               for (octave_idx_type i = 0; i < nr; i++)
                 {
-                  double tmp = std::abs(data(i));
+                  double tmp = std::abs (data (i));
                   if (tmp > dmax)
                     dmax = tmp;
                   if (tmp < dmin)
@@ -1496,30 +1496,30 @@
           octave_idx_type b_nz = b.nnz ();
           retval = SparseComplexMatrix (nc, b_nc, b_nz);
 
-          retval.xcidx(0) = 0;
+          retval.xcidx (0) = 0;
           octave_idx_type ii = 0;
           if (typ == MatrixType::Diagonal)
-            for (octave_idx_type j = 0; j < b.cols(); j++)
+            for (octave_idx_type j = 0; j < b.cols (); j++)
               {
-                for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
+                for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
                   {
-                    if (b.ridx(i) >= nm)
+                    if (b.ridx (i) >= nm)
                       break;
-                    retval.xridx (ii) = b.ridx(i);
-                    retval.xdata (ii++) = b.data(i) / data (b.ridx (i));
+                    retval.xridx (ii) = b.ridx (i);
+                    retval.xdata (ii++) = b.data (i) / data (b.ridx (i));
                   }
-                retval.xcidx(j+1) = ii;
+                retval.xcidx (j+1) = ii;
               }
           else
-            for (octave_idx_type j = 0; j < b.cols(); j++)
+            for (octave_idx_type j = 0; j < b.cols (); j++)
               {
                 for (octave_idx_type l = 0; l < nc; l++)
-                  for (octave_idx_type i = cidx(l); i < cidx(l+1); i++)
+                  for (octave_idx_type i = cidx (l); i < cidx (l+1); i++)
                     {
                       bool found = false;
                       octave_idx_type k;
-                      for (k = b.cidx(j); k < b.cidx(j+1); k++)
-                        if (ridx(i) == b.ridx(k))
+                      for (k = b.cidx (j); k < b.cidx (j+1); k++)
+                        if (ridx (i) == b.ridx (k))
                           {
                             found = true;
                             break;
@@ -1527,10 +1527,10 @@
                       if (found)
                         {
                           retval.xridx (ii) = l;
-                          retval.xdata (ii++) = b.data(k) / data (i);
+                          retval.xdata (ii++) = b.data (k) / data (i);
                         }
                     }
-                retval.xcidx(j+1) = ii;
+                retval.xcidx (j+1) = ii;
               }
 
           if (calc_cond)
@@ -1538,7 +1538,7 @@
               double dmax = 0., dmin = octave_Inf;
               for (octave_idx_type i = 0; i < nm; i++)
                 {
-                  double tmp = std::abs(data(i));
+                  double tmp = std::abs (data (i));
                   if (tmp > dmax)
                     dmax = tmp;
                   if (tmp < dmin)
@@ -1594,8 +1594,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += std::abs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += std::abs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -1620,26 +1620,26 @@
 
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(kidx+1)-1) != k ||
-                              data(cidx(kidx+1)-1) == 0.)
+                          if (ridx (cidx (kidx+1)-1) != k ||
+                              data (cidx (kidx+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(cidx(kidx+1)-1);
+                          Complex tmp = work[k] / data (cidx (kidx+1)-1);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(kidx);
-                               i < cidx(kidx+1)-1; i++)
+                          for (octave_idx_type i = cidx (kidx);
+                               i < cidx (kidx+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
 
                   for (octave_idx_type i = 0; i < nc; i++)
-                    retval (perm[i], j) = work[i];
+                    retval(perm[i], j) = work[i];
                 }
 
               if (calc_cond)
@@ -1658,20 +1658,20 @@
 
                           if (work[k] != 0.)
                             {
-                              Complex tmp = work[k] / data(cidx(iidx+1)-1);
+                              Complex tmp = work[k] / data (cidx (iidx+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(iidx);
-                                   i < cidx(iidx+1)-1; i++)
+                              for (octave_idx_type i = cidx (iidx);
+                                   i < cidx (iidx+1)-1; i++)
                                 {
-                                  octave_idx_type idx2 = ridx(i);
-                                  work[idx2] = work[idx2] - tmp * data(i);
+                                  octave_idx_type idx2 = ridx (i);
+                                  work[idx2] = work[idx2] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -1696,19 +1696,19 @@
                     {
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(k+1)-1) != k ||
-                              data(cidx(k+1)-1) == 0.)
+                          if (ridx (cidx (k+1)-1) != k ||
+                              data (cidx (k+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(cidx(k+1)-1);
+                          Complex tmp = work[k] / data (cidx (k+1)-1);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1)-1; i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -1731,20 +1731,20 @@
                         {
                           if (work[k] != 0.)
                             {
-                              Complex tmp = work[k] / data(cidx(k+1)-1);
+                              Complex tmp = work[k] / data (cidx (k+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1)-1; i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1)-1; i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -1829,8 +1829,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += std::abs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += std::abs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -1839,7 +1839,7 @@
           octave_idx_type b_nc = b.cols ();
           octave_idx_type b_nz = b.nnz ();
           retval = SparseComplexMatrix (nc, b_nc, b_nz);
-          retval.xcidx(0) = 0;
+          retval.xcidx (0) = 0;
           octave_idx_type ii = 0;
           octave_idx_type x_nz = b_nz;
 
@@ -1856,8 +1856,8 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     work[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    work[b.ridx(i)] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    work[b.ridx (i)] = b.data (i);
 
                   for (octave_idx_type k = nc-1; k >= 0; k--)
                     {
@@ -1865,20 +1865,20 @@
 
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(kidx+1)-1) != k ||
-                              data(cidx(kidx+1)-1) == 0.)
+                          if (ridx (cidx (kidx+1)-1) != k ||
+                              data (cidx (kidx+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(cidx(kidx+1)-1);
+                          Complex tmp = work[k] / data (cidx (kidx+1)-1);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(kidx);
-                               i < cidx(kidx+1)-1; i++)
+                          for (octave_idx_type i = cidx (kidx);
+                               i < cidx (kidx+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -1901,10 +1901,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (work[rperm[i]] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = work[rperm[i]];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = work[rperm[i]];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -1925,20 +1925,20 @@
 
                           if (work[k] != 0.)
                             {
-                              Complex tmp = work[k] / data(cidx(iidx+1)-1);
+                              Complex tmp = work[k] / data (cidx (iidx+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(iidx);
-                                   i < cidx(iidx+1)-1; i++)
+                              for (octave_idx_type i = cidx (iidx);
+                                   i < cidx (iidx+1)-1; i++)
                                 {
-                                  octave_idx_type idx2 = ridx(i);
-                                  work[idx2] = work[idx2] - tmp * data(i);
+                                  octave_idx_type idx2 = ridx (i);
+                                  work[idx2] = work[idx2] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -1955,26 +1955,26 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     work[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    work[b.ridx(i)] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    work[b.ridx (i)] = b.data (i);
 
                   for (octave_idx_type k = nc-1; k >= 0; k--)
                     {
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(k+1)-1) != k ||
-                              data(cidx(k+1)-1) == 0.)
+                          if (ridx (cidx (k+1)-1) != k ||
+                              data (cidx (k+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(cidx(k+1)-1);
+                          Complex tmp = work[k] / data (cidx (k+1)-1);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1)-1; i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -1997,10 +1997,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (work[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = work[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = work[i];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -2019,20 +2019,20 @@
                         {
                           if (work[k] != 0.)
                             {
-                              Complex tmp = work[k] / data(cidx(k+1)-1);
+                              Complex tmp = work[k] / data (cidx (k+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1)-1; i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1)-1; i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2117,8 +2117,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += std::abs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += std::abs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -2143,26 +2143,26 @@
 
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(kidx+1)-1) != k ||
-                              data(cidx(kidx+1)-1) == 0.)
+                          if (ridx (cidx (kidx+1)-1) != k ||
+                              data (cidx (kidx+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(cidx(kidx+1)-1);
+                          Complex tmp = work[k] / data (cidx (kidx+1)-1);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(kidx);
-                               i < cidx(kidx+1)-1; i++)
+                          for (octave_idx_type i = cidx (kidx);
+                               i < cidx (kidx+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
 
                   for (octave_idx_type i = 0; i < nc; i++)
-                    retval (perm[i], j) = work[i];
+                    retval(perm[i], j) = work[i];
                 }
 
               if (calc_cond)
@@ -2181,20 +2181,20 @@
 
                           if (work[k] != 0.)
                             {
-                              Complex tmp = work[k] / data(cidx(iidx+1)-1);
+                              Complex tmp = work[k] / data (cidx (iidx+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(iidx);
-                                   i < cidx(iidx+1)-1; i++)
+                              for (octave_idx_type i = cidx (iidx);
+                                   i < cidx (iidx+1)-1; i++)
                                 {
-                                  octave_idx_type idx2 = ridx(i);
-                                  work[idx2] = work[idx2] - tmp * data(i);
+                                  octave_idx_type idx2 = ridx (i);
+                                  work[idx2] = work[idx2] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2219,19 +2219,19 @@
                     {
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(k+1)-1) != k ||
-                              data(cidx(k+1)-1) == 0.)
+                          if (ridx (cidx (k+1)-1) != k ||
+                              data (cidx (k+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(cidx(k+1)-1);
+                          Complex tmp = work[k] / data (cidx (k+1)-1);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1)-1; i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -2254,20 +2254,20 @@
                         {
                           if (work[k] != 0.)
                             {
-                              Complex tmp = work[k] / data(cidx(k+1)-1);
+                              Complex tmp = work[k] / data (cidx (k+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1)-1; i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1)-1; i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2352,8 +2352,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += std::abs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += std::abs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -2362,7 +2362,7 @@
           octave_idx_type b_nc = b.cols ();
           octave_idx_type b_nz = b.nnz ();
           retval = SparseComplexMatrix (nc, b_nc, b_nz);
-          retval.xcidx(0) = 0;
+          retval.xcidx (0) = 0;
           octave_idx_type ii = 0;
           octave_idx_type x_nz = b_nz;
 
@@ -2379,8 +2379,8 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     work[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    work[b.ridx(i)] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    work[b.ridx (i)] = b.data (i);
 
                   for (octave_idx_type k = nc-1; k >= 0; k--)
                     {
@@ -2388,20 +2388,20 @@
 
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(kidx+1)-1) != k ||
-                              data(cidx(kidx+1)-1) == 0.)
+                          if (ridx (cidx (kidx+1)-1) != k ||
+                              data (cidx (kidx+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(cidx(kidx+1)-1);
+                          Complex tmp = work[k] / data (cidx (kidx+1)-1);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(kidx);
-                               i < cidx(kidx+1)-1; i++)
+                          for (octave_idx_type i = cidx (kidx);
+                               i < cidx (kidx+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -2424,10 +2424,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (work[rperm[i]] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = work[rperm[i]];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = work[rperm[i]];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -2448,20 +2448,20 @@
 
                           if (work[k] != 0.)
                             {
-                              Complex tmp = work[k] / data(cidx(iidx+1)-1);
+                              Complex tmp = work[k] / data (cidx (iidx+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(iidx);
-                                   i < cidx(iidx+1)-1; i++)
+                              for (octave_idx_type i = cidx (iidx);
+                                   i < cidx (iidx+1)-1; i++)
                                 {
-                                  octave_idx_type idx2 = ridx(i);
-                                  work[idx2] = work[idx2] - tmp * data(i);
+                                  octave_idx_type idx2 = ridx (i);
+                                  work[idx2] = work[idx2] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2478,26 +2478,26 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     work[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    work[b.ridx(i)] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    work[b.ridx (i)] = b.data (i);
 
                   for (octave_idx_type k = nr-1; k >= 0; k--)
                     {
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(k+1)-1) != k ||
-                              data(cidx(k+1)-1) == 0.)
+                          if (ridx (cidx (k+1)-1) != k ||
+                              data (cidx (k+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(cidx(k+1)-1);
+                          Complex tmp = work[k] / data (cidx (k+1)-1);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1)-1; i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -2520,10 +2520,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (work[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = work[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = work[i];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -2542,20 +2542,20 @@
                         {
                           if (work[k] != 0.)
                             {
-                              Complex tmp = work[k] / data(cidx(k+1)-1);
+                              Complex tmp = work[k] / data (cidx (k+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1)-1; i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1)-1; i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2641,8 +2641,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += std::abs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += std::abs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -2668,10 +2668,10 @@
                           octave_idx_type minr = nr;
                           octave_idx_type mini = 0;
 
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
-                            if (perm[ridx(i)] < minr)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
+                            if (perm[ridx (i)] < minr)
                               {
-                                minr = perm[ridx(i)];
+                                minr = perm[ridx (i)];
                                 mini = i;
                               }
 
@@ -2681,21 +2681,21 @@
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(mini);
+                          Complex tmp = work[k] / data (mini);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
                             {
                               if (i == mini)
                                 continue;
 
-                              octave_idx_type iidx = perm[ridx(i)];
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = perm[ridx (i)];
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
 
                   for (octave_idx_type i = 0; i < nc; i++)
-                    retval (i, j) = work[i];
+                    retval(i, j) = work[i];
                 }
 
               if (calc_cond)
@@ -2715,24 +2715,24 @@
                               octave_idx_type minr = nr;
                               octave_idx_type mini = 0;
 
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
-                                if (perm[ridx(i)] < minr)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
+                                if (perm[ridx (i)] < minr)
                                   {
-                                    minr = perm[ridx(i)];
+                                    minr = perm[ridx (i)];
                                     mini = i;
                                   }
 
-                              Complex tmp = work[k] / data(mini);
+                              Complex tmp = work[k] / data (mini);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
                                 {
                                   if (i == mini)
                                     continue;
 
-                                  octave_idx_type iidx = perm[ridx(i)];
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = perm[ridx (i)];
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
@@ -2740,7 +2740,7 @@
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2764,19 +2764,19 @@
                     {
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(k)) != k ||
-                              data(cidx(k)) == 0.)
+                          if (ridx (cidx (k)) != k ||
+                              data (cidx (k)) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(cidx(k));
+                          Complex tmp = work[k] / data (cidx (k));
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k)+1; i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k)+1; i < cidx (k+1); i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -2799,20 +2799,20 @@
 
                           if (work[k] != 0.)
                             {
-                              Complex tmp = work[k] / data(cidx(k));
+                              Complex tmp = work[k] / data (cidx (k));
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k)+1;
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k)+1;
+                                   i < cidx (k+1); i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2897,8 +2897,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += std::abs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += std::abs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -2907,7 +2907,7 @@
           octave_idx_type b_nc = b.cols ();
           octave_idx_type b_nz = b.nnz ();
           retval = SparseComplexMatrix (nc, b_nc, b_nz);
-          retval.xcidx(0) = 0;
+          retval.xcidx (0) = 0;
           octave_idx_type ii = 0;
           octave_idx_type x_nz = b_nz;
 
@@ -2920,8 +2920,8 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     work[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    work[perm[b.ridx(i)]] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    work[perm[b.ridx (i)]] = b.data (i);
 
                   for (octave_idx_type k = 0; k < nc; k++)
                     {
@@ -2930,10 +2930,10 @@
                           octave_idx_type minr = nr;
                           octave_idx_type mini = 0;
 
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
-                            if (perm[ridx(i)] < minr)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
+                            if (perm[ridx (i)] < minr)
                               {
-                                minr = perm[ridx(i)];
+                                minr = perm[ridx (i)];
                                 mini = i;
                               }
 
@@ -2943,15 +2943,15 @@
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(mini);
+                          Complex tmp = work[k] / data (mini);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
                             {
                               if (i == mini)
                                 continue;
 
-                              octave_idx_type iidx = perm[ridx(i)];
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = perm[ridx (i)];
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -2974,10 +2974,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (work[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = work[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = work[i];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -2999,24 +2999,24 @@
                               octave_idx_type minr = nr;
                               octave_idx_type mini = 0;
 
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
-                                if (perm[ridx(i)] < minr)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
+                                if (perm[ridx (i)] < minr)
                                   {
-                                    minr = perm[ridx(i)];
+                                    minr = perm[ridx (i)];
                                     mini = i;
                                   }
 
-                              Complex tmp = work[k] / data(mini);
+                              Complex tmp = work[k] / data (mini);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
                                 {
                                   if (i == mini)
                                     continue;
 
-                                  octave_idx_type iidx = perm[ridx(i)];
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = perm[ridx (i)];
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
@@ -3024,7 +3024,7 @@
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -3041,26 +3041,26 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     work[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    work[b.ridx(i)] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    work[b.ridx (i)] = b.data (i);
 
                   for (octave_idx_type k = 0; k < nc; k++)
                     {
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(k)) != k ||
-                              data(cidx(k)) == 0.)
+                          if (ridx (cidx (k)) != k ||
+                              data (cidx (k)) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(cidx(k));
+                          Complex tmp = work[k] / data (cidx (k));
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k)+1; i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k)+1; i < cidx (k+1); i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -3083,10 +3083,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (work[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = work[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = work[i];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -3106,20 +3106,20 @@
 
                           if (work[k] != 0.)
                             {
-                              Complex tmp = work[k] / data(cidx(k));
+                              Complex tmp = work[k] / data (cidx (k));
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k)+1;
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k)+1;
+                                   i < cidx (k+1); i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -3205,8 +3205,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += std::abs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += std::abs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -3232,10 +3232,10 @@
                           octave_idx_type minr = nr;
                           octave_idx_type mini = 0;
 
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
-                            if (perm[ridx(i)] < minr)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
+                            if (perm[ridx (i)] < minr)
                               {
-                                minr = perm[ridx(i)];
+                                minr = perm[ridx (i)];
                                 mini = i;
                               }
 
@@ -3245,21 +3245,21 @@
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(mini);
+                          Complex tmp = work[k] / data (mini);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
                             {
                               if (i == mini)
                                 continue;
 
-                              octave_idx_type iidx = perm[ridx(i)];
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = perm[ridx (i)];
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
 
                   for (octave_idx_type i = 0; i < nc; i++)
-                    retval (i, j) = work[i];
+                    retval(i, j) = work[i];
                 }
 
               if (calc_cond)
@@ -3279,24 +3279,24 @@
                               octave_idx_type minr = nr;
                               octave_idx_type mini = 0;
 
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
-                                if (perm[ridx(i)] < minr)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
+                                if (perm[ridx (i)] < minr)
                                   {
-                                    minr = perm[ridx(i)];
+                                    minr = perm[ridx (i)];
                                     mini = i;
                                   }
 
-                              Complex tmp = work[k] / data(mini);
+                              Complex tmp = work[k] / data (mini);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
                                 {
                                   if (i == mini)
                                     continue;
 
-                                  octave_idx_type iidx = perm[ridx(i)];
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = perm[ridx (i)];
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
@@ -3304,7 +3304,7 @@
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -3330,19 +3330,19 @@
                     {
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(k)) != k ||
-                              data(cidx(k)) == 0.)
+                          if (ridx (cidx (k)) != k ||
+                              data (cidx (k)) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(cidx(k));
+                          Complex tmp = work[k] / data (cidx (k));
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k)+1; i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k)+1; i < cidx (k+1); i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -3366,20 +3366,20 @@
 
                           if (work[k] != 0.)
                             {
-                              Complex tmp = work[k] / data(cidx(k));
+                              Complex tmp = work[k] / data (cidx (k));
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k)+1;
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k)+1;
+                                   i < cidx (k+1); i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -3464,8 +3464,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += std::abs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += std::abs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -3474,7 +3474,7 @@
           octave_idx_type b_nc = b.cols ();
           octave_idx_type b_nz = b.nnz ();
           retval = SparseComplexMatrix (nc, b_nc, b_nz);
-          retval.xcidx(0) = 0;
+          retval.xcidx (0) = 0;
           octave_idx_type ii = 0;
           octave_idx_type x_nz = b_nz;
 
@@ -3487,8 +3487,8 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     work[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    work[perm[b.ridx(i)]] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    work[perm[b.ridx (i)]] = b.data (i);
 
                   for (octave_idx_type k = 0; k < nc; k++)
                     {
@@ -3497,10 +3497,10 @@
                           octave_idx_type minr = nr;
                           octave_idx_type mini = 0;
 
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
-                            if (perm[ridx(i)] < minr)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
+                            if (perm[ridx (i)] < minr)
                               {
-                                minr = perm[ridx(i)];
+                                minr = perm[ridx (i)];
                                 mini = i;
                               }
 
@@ -3510,15 +3510,15 @@
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(mini);
+                          Complex tmp = work[k] / data (mini);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
                             {
                               if (i == mini)
                                 continue;
 
-                              octave_idx_type iidx = perm[ridx(i)];
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = perm[ridx (i)];
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -3541,10 +3541,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (work[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = work[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = work[i];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -3566,24 +3566,24 @@
                               octave_idx_type minr = nr;
                               octave_idx_type mini = 0;
 
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
-                                if (perm[ridx(i)] < minr)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
+                                if (perm[ridx (i)] < minr)
                                   {
-                                    minr = perm[ridx(i)];
+                                    minr = perm[ridx (i)];
                                     mini = i;
                                   }
 
-                              Complex tmp = work[k] / data(mini);
+                              Complex tmp = work[k] / data (mini);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
                                 {
                                   if (i == mini)
                                     continue;
 
-                                  octave_idx_type iidx = perm[ridx(i)];
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = perm[ridx (i)];
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
@@ -3591,7 +3591,7 @@
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -3608,26 +3608,26 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     work[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    work[b.ridx(i)] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    work[b.ridx (i)] = b.data (i);
 
                   for (octave_idx_type k = 0; k < nc; k++)
                     {
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(k)) != k ||
-                              data(cidx(k)) == 0.)
+                          if (ridx (cidx (k)) != k ||
+                              data (cidx (k)) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = work[k] / data(cidx(k));
+                          Complex tmp = work[k] / data (cidx (k));
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k)+1; i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k)+1; i < cidx (k+1); i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -3650,10 +3650,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (work[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = work[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = work[i];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -3673,20 +3673,20 @@
 
                           if (work[k] != 0.)
                             {
-                              Complex tmp = work[k] / data(cidx(k));
+                              Complex tmp = work[k] / data (cidx (k));
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k)+1;
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k)+1;
+                                   i < cidx (k+1); i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += std::abs(work[i]);
+                          atmp += std::abs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -3771,11 +3771,11 @@
 
               for (octave_idx_type j = 0; j < nc-1; j++)
                 {
-                  D[j] = std::real(data(ii++));
-                  DL[j] = data(ii);
+                  D[j] = std::real (data (ii++));
+                  DL[j] = data (ii);
                   ii += 2;
                 }
-              D[nc-1] = std::real(data(ii));
+              D[nc-1] = std::real (data (ii));
             }
           else
             {
@@ -3787,21 +3787,21 @@
                 }
 
               for (octave_idx_type j = 0; j < nc; j++)
-                for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+                for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
                   {
-                    if (ridx(i) == j)
-                      D[j] = std::real(data(i));
-                    else if (ridx(i) == j + 1)
-                      DL[j] = data(i);
+                    if (ridx (i) == j)
+                      D[j] = std::real (data (i));
+                    else if (ridx (i) == j + 1)
+                      DL[j] = data (i);
                   }
             }
 
-          octave_idx_type b_nc = b.cols();
+          octave_idx_type b_nc = b.cols ();
           retval = ComplexMatrix (b);
           Complex *result = retval.fortran_vec ();
 
           F77_XFCN (zptsv, ZPTSV, (nr, b_nc, D, DL, result,
-                                   b.rows(), err));
+                                   b.rows (), err));
 
           if (err != 0)
             {
@@ -3825,11 +3825,11 @@
 
               for (octave_idx_type j = 0; j < nc-1; j++)
                 {
-                  D[j] = data(ii++);
-                  DL[j] = data(ii++);
-                  DU[j] = data(ii++);
-                }
-              D[nc-1] = data(ii);
+                  D[j] = data (ii++);
+                  DL[j] = data (ii++);
+                  DU[j] = data (ii++);
+                }
+              D[nc-1] = data (ii);
             }
           else
             {
@@ -3842,23 +3842,23 @@
                 }
 
               for (octave_idx_type j = 0; j < nc; j++)
-                for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+                for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
                   {
-                    if (ridx(i) == j)
-                      D[j] = data(i);
-                    else if (ridx(i) == j + 1)
-                      DL[j] = data(i);
-                    else if (ridx(i) == j - 1)
-                      DU[j-1] = data(i);
+                    if (ridx (i) == j)
+                      D[j] = data (i);
+                    else if (ridx (i) == j + 1)
+                      DL[j] = data (i);
+                    else if (ridx (i) == j - 1)
+                      DU[j-1] = data (i);
                   }
             }
 
-          octave_idx_type b_nc = b.cols();
+          octave_idx_type b_nc = b.cols ();
           retval = ComplexMatrix (b);
           Complex *result = retval.fortran_vec ();
 
           F77_XFCN (zgtsv, ZGTSV, (nr, b_nc, DL, D, DU, result,
-                                   b.rows(), err));
+                                   b.rows (), err));
 
           if (err != 0)
             {
@@ -3928,11 +3928,11 @@
 
               for (octave_idx_type j = 0; j < nc-1; j++)
                 {
-                  D[j] = data(ii++);
-                  DL[j] = data(ii++);
-                  DU[j] = data(ii++);
-                }
-              D[nc-1] = data(ii);
+                  D[j] = data (ii++);
+                  DL[j] = data (ii++);
+                  DU[j] = data (ii++);
+                }
+              D[nc-1] = data (ii);
             }
           else
             {
@@ -3945,14 +3945,14 @@
                 }
 
               for (octave_idx_type j = 0; j < nc; j++)
-                for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+                for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
                   {
-                    if (ridx(i) == j)
-                      D[j] = data(i);
-                    else if (ridx(i) == j + 1)
-                      DL[j] = data(i);
-                    else if (ridx(i) == j - 1)
-                      DU[j-1] = data(i);
+                    if (ridx (i) == j)
+                      D[j] = data (i);
+                    else if (ridx (i) == j + 1)
+                      DL[j] = data (i);
+                    else if (ridx (i) == j - 1)
+                      DU[j-1] = data (i);
                   }
             }
 
@@ -3979,7 +3979,7 @@
               volatile octave_idx_type x_nz = b.nnz ();
               octave_idx_type b_nc = b.cols ();
               retval = SparseComplexMatrix (nr, b_nc, x_nz);
-              retval.xcidx(0) = 0;
+              retval.xcidx (0) = 0;
               volatile octave_idx_type ii = 0;
               rcond = 1.0;
 
@@ -3989,8 +3989,8 @@
                 {
                   for (octave_idx_type i = 0; i < nr; i++)
                     work[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    work[b.ridx(i)] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    work[b.ridx (i)] = b.data (i);
 
                   F77_XFCN (zgttrs, ZGTTRS,
                             (F77_CONST_CHAR_ARG2 (&job, 1),
@@ -4016,10 +4016,10 @@
                   for (octave_idx_type i = 0; i < nr; i++)
                     if (work[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = work[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = work[i];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -4069,11 +4069,11 @@
 
               for (octave_idx_type j = 0; j < nc-1; j++)
                 {
-                  D[j] = std::real(data(ii++));
-                  DL[j] = data(ii);
+                  D[j] = std::real (data (ii++));
+                  DL[j] = data (ii);
                   ii += 2;
                 }
-              D[nc-1] = std::real(data(ii));
+              D[nc-1] = std::real (data (ii));
             }
           else
             {
@@ -4085,17 +4085,17 @@
                 }
 
               for (octave_idx_type j = 0; j < nc; j++)
-                for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+                for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
                   {
-                    if (ridx(i) == j)
-                      D[j] = std::real (data(i));
-                    else if (ridx(i) == j + 1)
-                      DL[j] = data(i);
+                    if (ridx (i) == j)
+                      D[j] = std::real (data (i));
+                    else if (ridx (i) == j + 1)
+                      DL[j] = data (i);
                   }
             }
 
           octave_idx_type b_nr = b.rows ();
-          octave_idx_type b_nc = b.cols();
+          octave_idx_type b_nc = b.cols ();
           rcond = 1.;
 
           retval = ComplexMatrix (b);
@@ -4124,11 +4124,11 @@
 
               for (octave_idx_type j = 0; j < nc-1; j++)
                 {
-                  D[j] = data(ii++);
-                  DL[j] = data(ii++);
-                  DU[j] = data(ii++);
-                }
-              D[nc-1] = data(ii);
+                  D[j] = data (ii++);
+                  DL[j] = data (ii++);
+                  DU[j] = data (ii++);
+                }
+              D[nc-1] = data (ii);
             }
           else
             {
@@ -4141,19 +4141,19 @@
                 }
 
               for (octave_idx_type j = 0; j < nc; j++)
-                for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+                for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
                   {
-                    if (ridx(i) == j)
-                      D[j] = data(i);
-                    else if (ridx(i) == j + 1)
-                      DL[j] = data(i);
-                    else if (ridx(i) == j - 1)
-                      DU[j-1] = data(i);
+                    if (ridx (i) == j)
+                      D[j] = data (i);
+                    else if (ridx (i) == j + 1)
+                      DL[j] = data (i);
+                    else if (ridx (i) == j - 1)
+                      DU[j-1] = data (i);
                   }
             }
 
-          octave_idx_type b_nr = b.rows();
-          octave_idx_type b_nc = b.cols();
+          octave_idx_type b_nr = b.rows ();
+          octave_idx_type b_nc = b.cols ();
           rcond = 1.;
 
           retval = ComplexMatrix (b);
@@ -4228,11 +4228,11 @@
 
               for (octave_idx_type j = 0; j < nc-1; j++)
                 {
-                  D[j] = data(ii++);
-                  DL[j] = data(ii++);
-                  DU[j] = data(ii++);
-                }
-              D[nc-1] = data(ii);
+                  D[j] = data (ii++);
+                  DL[j] = data (ii++);
+                  DU[j] = data (ii++);
+                }
+              D[nc-1] = data (ii);
             }
           else
             {
@@ -4245,14 +4245,14 @@
                 }
 
               for (octave_idx_type j = 0; j < nc; j++)
-                for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+                for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
                   {
-                    if (ridx(i) == j)
-                      D[j] = data(i);
-                    else if (ridx(i) == j + 1)
-                      DL[j] = data(i);
-                    else if (ridx(i) == j - 1)
-                      DU[j-1] = data(i);
+                    if (ridx (i) == j)
+                      D[j] = data (i);
+                    else if (ridx (i) == j + 1)
+                      DL[j] = data (i);
+                    else if (ridx (i) == j - 1)
+                      DU[j-1] = data (i);
                   }
             }
 
@@ -4286,7 +4286,7 @@
               volatile octave_idx_type ii = 0;
               retval = SparseComplexMatrix (b_nr, b_nc, x_nz);
 
-              retval.xcidx(0) = 0;
+              retval.xcidx (0) = 0;
               for (volatile octave_idx_type j = 0; j < b_nc; j++)
                 {
 
@@ -4326,11 +4326,11 @@
                   for (octave_idx_type i = 0; i < nr; i++)
                     if (Bx[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = Bx[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = Bx[i];
                       }
 
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -4383,17 +4383,17 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
               {
                 octave_idx_type ri = ridx (i);
                 if (ri >= j)
-                  m_band(ri - j, j) = data(i);
+                  m_band(ri - j, j) = data (i);
               }
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
           if (calc_cond)
-            anorm = m_band.abs().sum().row(0).max();
+            anorm = m_band.abs ().sum ().row (0).max ();
 
           char job = 'L';
           F77_XFCN (zpbtrf, ZPBTRF, (F77_CONST_CHAR_ARG2 (&job, 1),
@@ -4457,7 +4457,7 @@
                   F77_XFCN (zpbtrs, ZPBTRS,
                             (F77_CONST_CHAR_ARG2 (&job, 1),
                              nr, n_lower, b_nc, tmp_data,
-                             ldm, result, b.rows(), err
+                             ldm, result, b.rows (), err
                              F77_CHAR_ARG_LEN (1)));
 
                   if (err != 0)
@@ -4490,8 +4490,8 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-              m_band(ridx(i) - j + n_lower + n_upper, j) = data(i);
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+              m_band(ridx (i) - j + n_lower + n_upper, j) = data (i);
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
@@ -4500,8 +4500,8 @@
               for (octave_idx_type j = 0; j < nr; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += std::abs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += std::abs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -4579,7 +4579,7 @@
                   F77_XFCN (zgbtrs, ZGBTRS,
                             (F77_CONST_CHAR_ARG2 (&job, 1),
                              nr, n_lower, n_upper, b_nc, tmp_data,
-                             ldm, pipvt, result, b.rows(), err
+                             ldm, pipvt, result, b.rows (), err
                              F77_CHAR_ARG_LEN (1)));
                 }
             }
@@ -4632,17 +4632,17 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
               {
                 octave_idx_type ri = ridx (i);
                 if (ri >= j)
-                  m_band(ri - j, j) = data(i);
+                  m_band(ri - j, j) = data (i);
               }
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
           if (calc_cond)
-            anorm = m_band.abs().sum().row(0).max();
+            anorm = m_band.abs ().sum ().row (0).max ();
 
           char job = 'L';
           F77_XFCN (zpbtrf, ZPBTRF, (F77_CONST_CHAR_ARG2 (&job, 1),
@@ -4706,7 +4706,7 @@
                   volatile octave_idx_type ii = 0;
                   retval = SparseComplexMatrix (b_nr, b_nc, x_nz);
 
-                  retval.xcidx(0) = 0;
+                  retval.xcidx (0) = 0;
                   for (volatile octave_idx_type j = 0; j < b_nc; j++)
                     {
                       for (octave_idx_type i = 0; i < b_nr; i++)
@@ -4740,11 +4740,11 @@
                                   retval.change_capacity (sz);
                                   x_nz = sz;
                                 }
-                              retval.xdata(ii) = tmp;
-                              retval.xridx(ii++) = i;
+                              retval.xdata (ii) = tmp;
+                              retval.xridx (ii++) = i;
                             }
                         }
-                      retval.xcidx(j+1) = ii;
+                      retval.xcidx (j+1) = ii;
                     }
 
                   retval.maybe_compress ();
@@ -4772,8 +4772,8 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-              m_band(ridx(i) - j + n_lower + n_upper, j) = data(i);
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+              m_band(ridx (i) - j + n_lower + n_upper, j) = data (i);
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
@@ -4782,8 +4782,8 @@
               for (octave_idx_type j = 0; j < nr; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += std::abs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += std::abs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -4855,7 +4855,7 @@
                   volatile octave_idx_type x_nz = b.nnz ();
                   octave_idx_type b_nc = b.cols ();
                   retval = SparseComplexMatrix (nr, b_nc, x_nz);
-                  retval.xcidx(0) = 0;
+                  retval.xcidx (0) = 0;
                   volatile octave_idx_type ii = 0;
 
                   OCTAVE_LOCAL_BUFFER (Complex, work, nr);
@@ -4864,9 +4864,9 @@
                     {
                       for (octave_idx_type i = 0; i < nr; i++)
                         work[i] = 0.;
-                      for (octave_idx_type i = b.cidx(j);
-                           i < b.cidx(j+1); i++)
-                        work[b.ridx(i)] = b.data(i);
+                      for (octave_idx_type i = b.cidx (j);
+                           i < b.cidx (j+1); i++)
+                        work[b.ridx (i)] = b.data (i);
 
                       F77_XFCN (zgbtrs, ZGBTRS,
                                 (F77_CONST_CHAR_ARG2 (&job, 1),
@@ -4892,10 +4892,10 @@
                       for (octave_idx_type i = 0; i < nr; i++)
                         if (work[i] != 0.)
                           {
-                            retval.xridx(ii) = i;
-                            retval.xdata(ii++) = work[i];
+                            retval.xridx (ii) = i;
+                            retval.xdata (ii++) = work[i];
                           }
-                      retval.xcidx(j+1) = ii;
+                      retval.xcidx (j+1) = ii;
                     }
 
                   retval.maybe_compress ();
@@ -4950,17 +4950,17 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
               {
                 octave_idx_type ri = ridx (i);
                 if (ri >= j)
-                  m_band(ri - j, j) = data(i);
+                  m_band(ri - j, j) = data (i);
               }
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
           if (calc_cond)
-            anorm = m_band.abs().sum().row(0).max();
+            anorm = m_band.abs ().sum ().row (0).max ();
 
           char job = 'L';
           F77_XFCN (zpbtrf, ZPBTRF, (F77_CONST_CHAR_ARG2 (&job, 1),
@@ -5057,8 +5057,8 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-              m_band(ridx(i) - j + n_lower + n_upper, j) = data(i);
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+              m_band(ridx (i) - j + n_lower + n_upper, j) = data (i);
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
@@ -5067,8 +5067,8 @@
               for (octave_idx_type j = 0; j < nr; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += std::abs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += std::abs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -5196,17 +5196,17 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
               {
                 octave_idx_type ri = ridx (i);
                 if (ri >= j)
-                  m_band(ri - j, j) = data(i);
+                  m_band(ri - j, j) = data (i);
               }
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
           if (calc_cond)
-            anorm = m_band.abs().sum().row(0).max();
+            anorm = m_band.abs ().sum ().row (0).max ();
 
           char job = 'L';
           F77_XFCN (zpbtrf, ZPBTRF, (F77_CONST_CHAR_ARG2 (&job, 1),
@@ -5273,7 +5273,7 @@
                   volatile octave_idx_type ii = 0;
                   retval = SparseComplexMatrix (b_nr, b_nc, x_nz);
 
-                  retval.xcidx(0) = 0;
+                  retval.xcidx (0) = 0;
                   for (volatile octave_idx_type j = 0; j < b_nc; j++)
                     {
 
@@ -5312,11 +5312,11 @@
                       for (octave_idx_type i = 0; i < nr; i++)
                         if (Bx[i] != 0.)
                           {
-                            retval.xridx(ii) = i;
-                            retval.xdata(ii++) = Bx[i];
+                            retval.xridx (ii) = i;
+                            retval.xdata (ii++) = Bx[i];
                           }
 
-                      retval.xcidx(j+1) = ii;
+                      retval.xcidx (j+1) = ii;
                     }
 
                   retval.maybe_compress ();
@@ -5344,8 +5344,8 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-              m_band(ridx(i) - j + n_lower + n_upper, j) = data(i);
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+              m_band(ridx (i) - j + n_lower + n_upper, j) = data (i);
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
@@ -5354,8 +5354,8 @@
               for (octave_idx_type j = 0; j < nr; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += std::abs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += std::abs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -5427,7 +5427,7 @@
                   volatile octave_idx_type x_nz = b.nnz ();
                   octave_idx_type b_nc = b.cols ();
                   retval = SparseComplexMatrix (nr, b_nc, x_nz);
-                  retval.xcidx(0) = 0;
+                  retval.xcidx (0) = 0;
                   volatile octave_idx_type ii = 0;
 
                   OCTAVE_LOCAL_BUFFER (Complex, Bx, nr);
@@ -5437,9 +5437,9 @@
                       for (octave_idx_type i = 0; i < nr; i++)
                         Bx[i] = 0.;
 
-                      for (octave_idx_type i = b.cidx(j);
-                           i < b.cidx(j+1); i++)
-                        Bx[b.ridx(i)] = b.data(i);
+                      for (octave_idx_type i = b.cidx (j);
+                           i < b.cidx (j+1); i++)
+                        Bx[b.ridx (i)] = b.data (i);
 
                       F77_XFCN (zgbtrs, ZGBTRS,
                                 (F77_CONST_CHAR_ARG2 (&job, 1),
@@ -5465,10 +5465,10 @@
                       for (octave_idx_type i = 0; i < nr; i++)
                         if (Bx[i] != 0.)
                           {
-                            retval.xridx(ii) = i;
-                            retval.xdata(ii++) = Bx[i];
+                            retval.xridx (ii) = i;
+                            retval.xdata (ii++) = Bx[i];
                           }
-                      retval.xcidx(j+1) = ii;
+                      retval.xcidx (j+1) = ii;
                     }
 
                   retval.maybe_compress ();
@@ -5655,13 +5655,13 @@
           A->nrow = nr;
           A->ncol = nc;
 
-          A->p = cidx();
-          A->i = ridx();
-          A->nzmax = nnz();
+          A->p = cidx ();
+          A->i = ridx ();
+          A->nzmax = nnz ();
           A->packed = true;
           A->sorted = true;
           A->nz = 0;
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
           A->itype = CHOLMOD_LONG;
 #else
           A->itype = CHOLMOD_INT;
@@ -5673,21 +5673,21 @@
           if (nr < 1)
             A->x = &dummy;
           else
-            A->x = data();
+            A->x = data ();
 
           cholmod_dense Bstore;
           cholmod_dense *B = &Bstore;
-          B->nrow = b.rows();
-          B->ncol = b.cols();
+          B->nrow = b.rows ();
+          B->ncol = b.cols ();
           B->d = B->nrow;
           B->nzmax = B->nrow * B->ncol;
           B->dtype = CHOLMOD_DOUBLE;
           B->xtype = CHOLMOD_REAL;
-          if (nc < 1 || b.cols() < 1)
+          if (nc < 1 || b.cols () < 1)
             B->x = &dummy;
           else
             // We won't alter it, honest :-)
-            B->x = const_cast<double *>(b.fortran_vec());
+            B->x = const_cast<double *>(b.fortran_vec ());
 
           cholmod_factor *L;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -5731,12 +5731,12 @@
               X = CHOLMOD_NAME(solve) (CHOLMOD_A, L, B, cm);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
 
-              retval.resize (b.rows (), b.cols());
-              for (octave_idx_type j = 0; j < b.cols(); j++)
-                {
-                  octave_idx_type jr = j * b.rows();
-                  for (octave_idx_type i = 0; i < b.rows(); i++)
-                    retval.xelem(i,j) = static_cast<Complex *>(X->x)[jr + i];
+              retval.resize (b.rows (), b.cols ());
+              for (octave_idx_type j = 0; j < b.cols (); j++)
+                {
+                  octave_idx_type jr = j * b.rows ();
+                  for (octave_idx_type i = 0; i < b.rows (); i++)
+                    retval.xelem (i,j) = static_cast<Complex *>(X->x)[jr + i];
                 }
 
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -5898,13 +5898,13 @@
           A->nrow = nr;
           A->ncol = nc;
 
-          A->p = cidx();
-          A->i = ridx();
-          A->nzmax = nnz();
+          A->p = cidx ();
+          A->i = ridx ();
+          A->nzmax = nnz ();
           A->packed = true;
           A->sorted = true;
           A->nz = 0;
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
           A->itype = CHOLMOD_LONG;
 #else
           A->itype = CHOLMOD_INT;
@@ -5916,19 +5916,19 @@
           if (nr < 1)
             A->x = &dummy;
           else
-            A->x = data();
+            A->x = data ();
 
           cholmod_sparse Bstore;
           cholmod_sparse *B = &Bstore;
-          B->nrow = b.rows();
-          B->ncol = b.cols();
-          B->p = b.cidx();
-          B->i = b.ridx();
-          B->nzmax = b.nnz();
+          B->nrow = b.rows ();
+          B->ncol = b.cols ();
+          B->p = b.cidx ();
+          B->i = b.ridx ();
+          B->nzmax = b.nnz ();
           B->packed = true;
           B->sorted = true;
           B->nz = 0;
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
           B->itype = CHOLMOD_LONG;
 #else
           B->itype = CHOLMOD_INT;
@@ -5937,10 +5937,10 @@
           B->stype = 0;
           B->xtype = CHOLMOD_REAL;
 
-          if (b.rows() < 1 || b.cols() < 1)
+          if (b.rows () < 1 || b.cols () < 1)
             B->x = &dummy;
           else
-            B->x = b.data();
+            B->x = b.data ();
 
           cholmod_factor *L;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -5990,12 +5990,12 @@
                  static_cast<octave_idx_type>(X->nzmax));
               for (octave_idx_type j = 0;
                    j <= static_cast<octave_idx_type>(X->ncol); j++)
-                retval.xcidx(j) = static_cast<octave_idx_type *>(X->p)[j];
+                retval.xcidx (j) = static_cast<octave_idx_type *>(X->p)[j];
               for (octave_idx_type j = 0;
                    j < static_cast<octave_idx_type>(X->nzmax); j++)
                 {
-                  retval.xridx(j) = static_cast<octave_idx_type *>(X->i)[j];
-                  retval.xdata(j) = static_cast<Complex *>(X->x)[j];
+                  retval.xridx (j) = static_cast<octave_idx_type *>(X->i)[j];
+                  retval.xdata (j) = static_cast<Complex *>(X->x)[j];
                 }
 
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -6050,7 +6050,7 @@
 
               OCTAVE_LOCAL_BUFFER (Complex, Xx, b_nr);
 
-              retval.xcidx(0) = 0;
+              retval.xcidx (0) = 0;
               for (octave_idx_type j = 0; j < b_nc; j++)
                 {
 
@@ -6105,11 +6105,11 @@
                               retval.change_capacity (sz);
                               x_nz = sz;
                             }
-                          retval.xdata(ii) = tmp;
-                          retval.xridx(ii++) = i;
+                          retval.xdata (ii) = tmp;
+                          retval.xridx (ii++) = i;
                         }
                     }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -6189,13 +6189,13 @@
           A->nrow = nr;
           A->ncol = nc;
 
-          A->p = cidx();
-          A->i = ridx();
-          A->nzmax = nnz();
+          A->p = cidx ();
+          A->i = ridx ();
+          A->nzmax = nnz ();
           A->packed = true;
           A->sorted = true;
           A->nz = 0;
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
           A->itype = CHOLMOD_LONG;
 #else
           A->itype = CHOLMOD_INT;
@@ -6207,21 +6207,21 @@
           if (nr < 1)
             A->x = &dummy;
           else
-            A->x = data();
+            A->x = data ();
 
           cholmod_dense Bstore;
           cholmod_dense *B = &Bstore;
-          B->nrow = b.rows();
-          B->ncol = b.cols();
+          B->nrow = b.rows ();
+          B->ncol = b.cols ();
           B->d = B->nrow;
           B->nzmax = B->nrow * B->ncol;
           B->dtype = CHOLMOD_DOUBLE;
           B->xtype = CHOLMOD_COMPLEX;
-          if (nc < 1 || b.cols() < 1)
+          if (nc < 1 || b.cols () < 1)
             B->x = &dummy;
           else
             // We won't alter it, honest :-)
-            B->x = const_cast<Complex *>(b.fortran_vec());
+            B->x = const_cast<Complex *>(b.fortran_vec ());
 
           cholmod_factor *L;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -6265,12 +6265,12 @@
               X = CHOLMOD_NAME(solve) (CHOLMOD_A, L, B, cm);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
 
-              retval.resize (b.rows (), b.cols());
-              for (octave_idx_type j = 0; j < b.cols(); j++)
-                {
-                  octave_idx_type jr = j * b.rows();
-                  for (octave_idx_type i = 0; i < b.rows(); i++)
-                    retval.xelem(i,j) = static_cast<Complex *>(X->x)[jr + i];
+              retval.resize (b.rows (), b.cols ());
+              for (octave_idx_type j = 0; j < b.cols (); j++)
+                {
+                  octave_idx_type jr = j * b.rows ();
+                  for (octave_idx_type i = 0; i < b.rows (); i++)
+                    retval.xelem (i,j) = static_cast<Complex *>(X->x)[jr + i];
                 }
 
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -6411,13 +6411,13 @@
           A->nrow = nr;
           A->ncol = nc;
 
-          A->p = cidx();
-          A->i = ridx();
-          A->nzmax = nnz();
+          A->p = cidx ();
+          A->i = ridx ();
+          A->nzmax = nnz ();
           A->packed = true;
           A->sorted = true;
           A->nz = 0;
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
           A->itype = CHOLMOD_LONG;
 #else
           A->itype = CHOLMOD_INT;
@@ -6429,19 +6429,19 @@
           if (nr < 1)
             A->x = &dummy;
           else
-            A->x = data();
+            A->x = data ();
 
           cholmod_sparse Bstore;
           cholmod_sparse *B = &Bstore;
-          B->nrow = b.rows();
-          B->ncol = b.cols();
-          B->p = b.cidx();
-          B->i = b.ridx();
-          B->nzmax = b.nnz();
+          B->nrow = b.rows ();
+          B->ncol = b.cols ();
+          B->p = b.cidx ();
+          B->i = b.ridx ();
+          B->nzmax = b.nnz ();
           B->packed = true;
           B->sorted = true;
           B->nz = 0;
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
           B->itype = CHOLMOD_LONG;
 #else
           B->itype = CHOLMOD_INT;
@@ -6450,10 +6450,10 @@
           B->stype = 0;
           B->xtype = CHOLMOD_COMPLEX;
 
-          if (b.rows() < 1 || b.cols() < 1)
+          if (b.rows () < 1 || b.cols () < 1)
             B->x = &dummy;
           else
-            B->x = b.data();
+            B->x = b.data ();
 
           cholmod_factor *L;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -6503,12 +6503,12 @@
                  static_cast<octave_idx_type>(X->nzmax));
               for (octave_idx_type j = 0;
                    j <= static_cast<octave_idx_type>(X->ncol); j++)
-                retval.xcidx(j) = static_cast<octave_idx_type *>(X->p)[j];
+                retval.xcidx (j) = static_cast<octave_idx_type *>(X->p)[j];
               for (octave_idx_type j = 0;
                    j < static_cast<octave_idx_type>(X->nzmax); j++)
                 {
-                  retval.xridx(j) = static_cast<octave_idx_type *>(X->i)[j];
-                  retval.xdata(j) = static_cast<Complex *>(X->x)[j];
+                  retval.xridx (j) = static_cast<octave_idx_type *>(X->i)[j];
+                  retval.xdata (j) = static_cast<Complex *>(X->x)[j];
                 }
 
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -6556,7 +6556,7 @@
 
               OCTAVE_LOCAL_BUFFER (Complex, Xx, b_nr);
 
-              retval.xcidx(0) = 0;
+              retval.xcidx (0) = 0;
               for (octave_idx_type j = 0; j < b_nc; j++)
                 {
                   for (octave_idx_type i = 0; i < b_nr; i++)
@@ -6596,11 +6596,11 @@
                               retval.change_capacity (sz);
                               x_nz = sz;
                             }
-                          retval.xdata(ii) = tmp;
-                          retval.xridx(ii++) = i;
+                          retval.xdata (ii) = tmp;
+                          retval.xridx (ii++) = i;
                         }
                     }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -6694,7 +6694,7 @@
       return ComplexMatrix ();
     }
 
-  if (singular_fallback && mattype.type(false) == MatrixType::Rectangular)
+  if (singular_fallback && mattype.type (false) == MatrixType::Rectangular)
     {
       rcond = 1.;
 #ifdef USE_QRSOLVE
@@ -6762,7 +6762,7 @@
       return SparseComplexMatrix ();
     }
 
-  if (singular_fallback && mattype.type(false) == MatrixType::Rectangular)
+  if (singular_fallback && mattype.type (false) == MatrixType::Rectangular)
     {
       rcond = 1.;
 #ifdef USE_QRSOLVE
@@ -6830,7 +6830,7 @@
       return ComplexMatrix ();
     }
 
-  if (singular_fallback && mattype.type(false) == MatrixType::Rectangular)
+  if (singular_fallback && mattype.type (false) == MatrixType::Rectangular)
     {
       rcond = 1.;
 #ifdef USE_QRSOLVE
@@ -6899,7 +6899,7 @@
       return SparseComplexMatrix ();
     }
 
-  if (singular_fallback && mattype.type(false) == MatrixType::Rectangular)
+  if (singular_fallback && mattype.type (false) == MatrixType::Rectangular)
     {
       rcond = 1.;
 #ifdef USE_QRSOLVE
@@ -7177,12 +7177,12 @@
     {
       for (octave_idx_type j = 0; j < nr; j++)
         {
-          if (jj < cidx(i+1) && ridx(jj) == j)
+          if (jj < cidx (i+1) && ridx (jj) == j)
             jj++;
           else
             {
-              r.data(ii) = true;
-              r.ridx(ii++) = j;
+              r.data (ii) = true;
+              r.ridx (ii++) = j;
             }
         }
       r.cidx (i+1) = ii;
@@ -7267,8 +7267,8 @@
   if (nel == 0)
     return false;
 
-  max_val = std::real(data (0));
-  min_val = std::real(data (0));
+  max_val = std::real (data (0));
+  min_val = std::real (data (0));
 
   for (octave_idx_type i = 0; i < nel; i++)
     {
@@ -7299,23 +7299,7 @@
 bool
 SparseComplexMatrix::too_large_for_float (void) const
 {
-  octave_idx_type nel = nnz ();
-
-  for (octave_idx_type i = 0; i < nel; i++)
-    {
-        Complex val = data (i);
-
-        double r_val = std::real (val);
-        double i_val = std::imag (val);
-
-        if (r_val > FLT_MAX
-            || i_val > FLT_MAX
-            || r_val < FLT_MIN
-            || i_val < FLT_MIN)
-          return true;
-    }
-
-  return false;
+  return test_any (xtoo_large_for_float);
 }
 
 // FIXME Do these really belong here?  Maybe they should be
@@ -7348,12 +7332,12 @@
 SparseComplexMatrix
 SparseComplexMatrix::prod (int dim) const
 {
-  if ((rows() == 1 && dim == -1) || dim == 1)
-    return transpose (). prod (0). transpose();
+  if ((rows () == 1 && dim == -1) || dim == 1)
+    return transpose (). prod (0). transpose ();
   else
     {
       SPARSE_REDUCTION_OP (SparseComplexMatrix, Complex, *=,
-                           (cidx(j+1) - cidx(j) < nr ? 0.0 : 1.0), 1.0);
+                           (cidx (j+1) - cidx (j) < nr ? 0.0 : 1.0), 1.0);
     }
 }
 
@@ -7368,11 +7352,11 @@
 {
 #define ROW_EXPR \
   Complex d = data (i); \
-  tmp [ridx(i)] += d * conj (d)
+  tmp[ridx (i)] += d * conj (d)
 
 #define COL_EXPR \
   Complex d = data (i); \
-  tmp [j] += d * conj (d)
+  tmp[j] += d * conj (d)
 
   SPARSE_BASE_REDUCTION_OP (SparseComplexMatrix, Complex, ROW_EXPR,
                             COL_EXPR, 0.0, 0.0);
@@ -7386,7 +7370,7 @@
   octave_idx_type nz = nnz ();
   octave_idx_type nc = cols ();
 
-  SparseMatrix retval (rows(), nc, nz);
+  SparseMatrix retval (rows (), nc, nz);
 
   for (octave_idx_type i = 0; i < nc + 1; i++)
     retval.cidx (i) = cidx (i);
@@ -7416,10 +7400,10 @@
    for (octave_idx_type j = 0; j < nc; j++)
      {
        octave_quit ();
-       for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+       for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
          {
-           os << a.ridx(i) + 1 << " "  << j + 1 << " ";
-           octave_write_complex (os, a.data(i));
+           os << a.ridx (i) + 1 << " "  << j + 1 << " ";
+           octave_write_complex (os, a.data (i));
            os << "\n";
          }
      }
@@ -7640,15 +7624,15 @@
 
   EMPTY_RETURN_CHECK (SparseComplexMatrix);
 
-  if (abs(c) == 0.)
+  if (abs (c) == 0.)
     return SparseComplexMatrix (nr, nc);
   else
     {
       result = SparseComplexMatrix (m);
 
       for (octave_idx_type j = 0; j < nc; j++)
-        for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++)
-          result.data(i) = xmin(c, m.data(i));
+        for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++)
+          result.data (i) = xmin (c, m.data (i));
     }
 
   return result;
@@ -7665,7 +7649,7 @@
 {
   SparseComplexMatrix r;
 
-  if ((a.rows() == b.rows()) && (a.cols() == b.cols()))
+  if ((a.rows () == b.rows ()) && (a.cols () == b.cols ()))
     {
       octave_idx_type a_nr = a.rows ();
       octave_idx_type a_nc = a.cols ();
@@ -7686,38 +7670,38 @@
           r.cidx (0) = 0;
           for (octave_idx_type i = 0 ; i < a_nc ; i++)
             {
-              octave_idx_type  ja = a.cidx(i);
-              octave_idx_type  ja_max = a.cidx(i+1);
+              octave_idx_type  ja = a.cidx (i);
+              octave_idx_type  ja_max = a.cidx (i+1);
               bool ja_lt_max= ja < ja_max;
 
-              octave_idx_type  jb = b.cidx(i);
-              octave_idx_type  jb_max = b.cidx(i+1);
+              octave_idx_type  jb = b.cidx (i);
+              octave_idx_type  jb_max = b.cidx (i+1);
               bool jb_lt_max = jb < jb_max;
 
               while (ja_lt_max || jb_lt_max )
                 {
                   octave_quit ();
                   if ((! jb_lt_max) ||
-                      (ja_lt_max && (a.ridx(ja) < b.ridx(jb))))
+                      (ja_lt_max && (a.ridx (ja) < b.ridx (jb))))
                     {
-                      Complex tmp = xmin (a.data(ja), 0.);
+                      Complex tmp = xmin (a.data (ja), 0.);
                       if (tmp != 0.)
                         {
-                          r.ridx(jx) = a.ridx(ja);
-                          r.data(jx) = tmp;
+                          r.ridx (jx) = a.ridx (ja);
+                          r.data (jx) = tmp;
                           jx++;
                         }
                       ja++;
                       ja_lt_max= ja < ja_max;
                     }
                   else if (( !ja_lt_max ) ||
-                           (jb_lt_max && (b.ridx(jb) < a.ridx(ja)) ) )
+                           (jb_lt_max && (b.ridx (jb) < a.ridx (ja)) ) )
                     {
-                      Complex tmp = xmin (0., b.data(jb));
+                      Complex tmp = xmin (0., b.data (jb));
                       if (tmp != 0.)
                         {
-                          r.ridx(jx) = b.ridx(jb);
-                          r.data(jx) = tmp;
+                          r.ridx (jx) = b.ridx (jb);
+                          r.data (jx) = tmp;
                           jx++;
                         }
                       jb++;
@@ -7725,11 +7709,11 @@
                     }
                   else
                     {
-                      Complex tmp = xmin (a.data(ja), b.data(jb));
+                      Complex tmp = xmin (a.data (ja), b.data (jb));
                       if (tmp != 0.)
                         {
-                          r.data(jx) = tmp;
-                          r.ridx(jx) = a.ridx(ja);
+                          r.data (jx) = tmp;
+                          r.ridx (jx) = a.ridx (ja);
                           jx++;
                         }
                       ja++;
@@ -7738,7 +7722,7 @@
                       jb_lt_max= jb < jb_max;
                     }
                 }
-              r.cidx(i+1) = jx;
+              r.cidx (i+1) = jx;
             }
 
           r.maybe_compress ();
@@ -7761,12 +7745,12 @@
   EMPTY_RETURN_CHECK (SparseComplexMatrix);
 
   // Count the number of non-zero elements
-  if (xmax(c, 0.) != 0.)
+  if (xmax (c, 0.) != 0.)
     {
       result = SparseComplexMatrix (nr, nc, c);
       for (octave_idx_type j = 0; j < nc; j++)
-        for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++)
-          result.xdata(m.ridx(i) + j * nr) = xmax (c, m.data(i));
+        for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++)
+          result.xdata (m.ridx (i) + j * nr) = xmax (c, m.data (i));
     }
   else
     result = SparseComplexMatrix (m);
@@ -7785,7 +7769,7 @@
 {
   SparseComplexMatrix r;
 
-  if ((a.rows() == b.rows()) && (a.cols() == b.cols()))
+  if ((a.rows () == b.rows ()) && (a.cols () == b.cols ()))
     {
       octave_idx_type a_nr = a.rows ();
       octave_idx_type a_nc = a.cols ();
@@ -7810,38 +7794,38 @@
           r.cidx (0) = 0;
           for (octave_idx_type i = 0 ; i < a_nc ; i++)
             {
-              octave_idx_type  ja = a.cidx(i);
-              octave_idx_type  ja_max = a.cidx(i+1);
+              octave_idx_type  ja = a.cidx (i);
+              octave_idx_type  ja_max = a.cidx (i+1);
               bool ja_lt_max= ja < ja_max;
 
-              octave_idx_type  jb = b.cidx(i);
-              octave_idx_type  jb_max = b.cidx(i+1);
+              octave_idx_type  jb = b.cidx (i);
+              octave_idx_type  jb_max = b.cidx (i+1);
               bool jb_lt_max = jb < jb_max;
 
               while (ja_lt_max || jb_lt_max )
                 {
                   octave_quit ();
                   if ((! jb_lt_max) ||
-                      (ja_lt_max && (a.ridx(ja) < b.ridx(jb))))
+                      (ja_lt_max && (a.ridx (ja) < b.ridx (jb))))
                     {
-                      Complex tmp = xmax (a.data(ja), 0.);
+                      Complex tmp = xmax (a.data (ja), 0.);
                       if (tmp != 0.)
                         {
-                          r.ridx(jx) = a.ridx(ja);
-                          r.data(jx) = tmp;
+                          r.ridx (jx) = a.ridx (ja);
+                          r.data (jx) = tmp;
                           jx++;
                         }
                       ja++;
                       ja_lt_max= ja < ja_max;
                     }
                   else if (( !ja_lt_max ) ||
-                           (jb_lt_max && (b.ridx(jb) < a.ridx(ja)) ) )
+                           (jb_lt_max && (b.ridx (jb) < a.ridx (ja)) ) )
                     {
-                      Complex tmp = xmax (0., b.data(jb));
+                      Complex tmp = xmax (0., b.data (jb));
                       if (tmp != 0.)
                         {
-                          r.ridx(jx) = b.ridx(jb);
-                          r.data(jx) = tmp;
+                          r.ridx (jx) = b.ridx (jb);
+                          r.data (jx) = tmp;
                           jx++;
                         }
                       jb++;
@@ -7849,11 +7833,11 @@
                     }
                   else
                     {
-                      Complex tmp = xmax (a.data(ja), b.data(jb));
+                      Complex tmp = xmax (a.data (ja), b.data (jb));
                       if (tmp != 0.)
                         {
-                          r.data(jx) = tmp;
-                          r.ridx(jx) = a.ridx(ja);
+                          r.data (jx) = tmp;
+                          r.ridx (jx) = a.ridx (ja);
                           jx++;
                         }
                       ja++;
@@ -7862,7 +7846,7 @@
                       jb_lt_max= jb < jb_max;
                     }
                 }
-              r.cidx(i+1) = jx;
+              r.cidx (i+1) = jx;
             }
 
           r.maybe_compress ();
rename from liboctave/CSparse.h
rename to liboctave/array/CSparse.h
--- a/liboctave/CSparse.h
+++ b/liboctave/array/CSparse.h
@@ -513,7 +513,7 @@
 
 SPARSE_FORWARD_DEFS (MSparse, SparseComplexMatrix, ComplexMatrix, Complex)
 
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
 #define UMFPACK_ZNAME(name) umfpack_zl_ ## name
 #else
 #define UMFPACK_ZNAME(name) umfpack_zi_ ## name
rename from liboctave/DiagArray2.cc
rename to liboctave/array/DiagArray2.cc
--- a/liboctave/DiagArray2.cc
+++ b/liboctave/array/DiagArray2.cc
@@ -48,14 +48,14 @@
 
 template <class T>
 Array<T>
-DiagArray2<T>::extract_diag (octave_idx_type k) const
+DiagArray2<T>::diag (octave_idx_type k) const
 {
-  return diag (k);
+  return extract_diag (k);
 }
 
 template <class T>
 Array<T>
-DiagArray2<T>::diag (octave_idx_type k) const
+DiagArray2<T>::extract_diag (octave_idx_type k) const
 {
   Array<T> d;
 
rename from liboctave/DiagArray2.h
rename to liboctave/array/DiagArray2.h
--- a/liboctave/DiagArray2.h
+++ b/liboctave/array/DiagArray2.h
@@ -97,7 +97,7 @@
 
   dim_vector dims (void) const { return dim_vector (d1, d2); }
 
-  Array<T> diag (octave_idx_type k = 0) const;
+  Array<T> diag (octave_idx_type k = 0) const GCC_ATTR_DEPRECATED;
   Array<T> extract_diag (octave_idx_type k = 0) const;
   DiagArray2<T> build_diag_matrix () const
   {
@@ -132,7 +132,7 @@
   T operator () (octave_idx_type r, octave_idx_type c) const
     {
 #if defined (BOUNDS_CHECKING)
-      checkelem (r, c);
+      return checkelem (r, c);
 #else
       return elem (r, c);
 #endif
@@ -166,8 +166,11 @@
   T dgxelem (octave_idx_type i) const
     { return Array<T>::xelem (i); }
 
-  void resize (octave_idx_type n, octave_idx_type m,
-               const T& rfv = Array<T>::resize_fill_value ());
+  void resize (octave_idx_type n, octave_idx_type m, const T& rfv);
+  void resize (octave_idx_type n, octave_idx_type m)
+  {
+    resize (n, m, Array<T>::resize_fill_value ());
+  }
 
   DiagArray2<T> transpose (void) const;
   DiagArray2<T> hermitian (T (*fcn) (const T&) = 0) const;
rename from liboctave/MArray-C.cc
rename to liboctave/array/MArray-C.cc
rename from liboctave/MArray-d.cc
rename to liboctave/array/MArray-d.cc
rename from liboctave/MArray-decl.h
rename to liboctave/array/MArray-decl.h
rename from liboctave/MArray-defs.h
rename to liboctave/array/MArray-defs.h
rename from liboctave/MArray-f.cc
rename to liboctave/array/MArray-f.cc
rename from liboctave/MArray-fC.cc
rename to liboctave/array/MArray-fC.cc
rename from liboctave/MArray-i.cc
rename to liboctave/array/MArray-i.cc
--- a/liboctave/MArray-i.cc
+++ b/liboctave/array/MArray-i.cc
@@ -32,7 +32,9 @@
 #include "MArray.cc"
 
 template class OCTAVE_API MArray<int>;
-template class OCTAVE_API MArray<long>;
+#ifdef USE_64_BIT_IDX_T
+template class OCTAVE_API MArray<int64_t>;
+#endif
 
 // Explicit instantiation, as this seems to be required by weird compilers
 // like MSVC. This should be harmless on other compilers.
@@ -42,7 +44,9 @@
 template long xmax<long> (long, long);
 
 INSTANTIATE_MARRAY_FRIENDS (int, OCTAVE_API)
-INSTANTIATE_MARRAY_FRIENDS (long, OCTAVE_API)
+#ifdef USE_64_BIT_IDX_T
+INSTANTIATE_MARRAY_FRIENDS (int64_t, OCTAVE_API)
+#endif
 
 template class OCTAVE_API MArray<octave_int8>;
 template class OCTAVE_API MArray<octave_int16>;
rename from liboctave/MArray-s.cc
rename to liboctave/array/MArray-s.cc
rename from liboctave/MArray.cc
rename to liboctave/array/MArray.cc
rename from liboctave/MArray.h
rename to liboctave/array/MArray.h
--- a/liboctave/MArray.h
+++ b/liboctave/array/MArray.h
@@ -39,6 +39,12 @@
 class
 MArray : public Array<T>
 {
+protected:
+
+  // For jit support
+  MArray (T *sdata, octave_idx_type slen, octave_idx_type *adims, void *arep)
+    : Array<T> (sdata, slen, adims, arep) { }
+
 public:
 
   MArray (void) : Array<T> () {}
rename from liboctave/MArray2.h
rename to liboctave/array/MArray2.h
rename from liboctave/MArrayN.h
rename to liboctave/array/MArrayN.h
rename from liboctave/MDiagArray2.cc
rename to liboctave/array/MDiagArray2.cc
rename from liboctave/MDiagArray2.h
rename to liboctave/array/MDiagArray2.h
--- a/liboctave/MDiagArray2.h
+++ b/liboctave/array/MDiagArray2.h
@@ -91,7 +91,7 @@
     }
 
   MArray<T> diag (octave_idx_type k = 0) const
-    { return DiagArray2<T>::diag (k); }
+    { return DiagArray2<T>::extract_diag (k); }
 
   MDiagArray2<T> transpose (void) const { return DiagArray2<T>::transpose (); }
   MDiagArray2<T> hermitian (T (*fcn) (const T&) = 0) const { return DiagArray2<T>::hermitian (fcn); }
rename from liboctave/MSparse-C.cc
rename to liboctave/array/MSparse-C.cc
rename from liboctave/MSparse-d.cc
rename to liboctave/array/MSparse-d.cc
rename from liboctave/MSparse-defs.h
rename to liboctave/array/MSparse-defs.h
rename from liboctave/MSparse.cc
rename to liboctave/array/MSparse.cc
--- a/liboctave/MSparse.cc
+++ b/liboctave/array/MSparse.cc
@@ -60,41 +60,41 @@
         octave_idx_type jx = 0;
         for (octave_idx_type i = 0 ; i < a_nc ; i++)
           {
-            octave_idx_type  ja = a.cidx(i);
-            octave_idx_type  ja_max = a.cidx(i+1);
+            octave_idx_type  ja = a.cidx (i);
+            octave_idx_type  ja_max = a.cidx (i+1);
             bool ja_lt_max= ja < ja_max;
 
-            octave_idx_type  jb = b.cidx(i);
-            octave_idx_type  jb_max = b.cidx(i+1);
+            octave_idx_type  jb = b.cidx (i);
+            octave_idx_type  jb_max = b.cidx (i+1);
             bool jb_lt_max = jb < jb_max;
 
             while (ja_lt_max || jb_lt_max )
               {
                 octave_quit ();
                 if ((! jb_lt_max) ||
-                      (ja_lt_max && (a.ridx(ja) < b.ridx(jb))))
+                      (ja_lt_max && (a.ridx (ja) < b.ridx (jb))))
                   {
-                    r.ridx(jx) = a.ridx(ja);
-                    r.data(jx) = op (a.data(ja), 0.);
+                    r.ridx (jx) = a.ridx (ja);
+                    r.data (jx) = op (a.data (ja), 0.);
                     jx++;
                     ja++;
                     ja_lt_max= ja < ja_max;
                   }
                 else if (( !ja_lt_max ) ||
-                     (jb_lt_max && (b.ridx(jb) < a.ridx(ja)) ) )
+                     (jb_lt_max && (b.ridx (jb) < a.ridx (ja)) ) )
                   {
-                    r.ridx(jx) = b.ridx(jb);
-                    r.data(jx) = op (0., b.data(jb));
+                    r.ridx (jx) = b.ridx (jb);
+                    r.data (jx) = op (0., b.data (jb));
                     jx++;
                     jb++;
                     jb_lt_max= jb < jb_max;
                   }
                 else
                   {
-                     if (op (a.data(ja), b.data(jb)) != 0.)
+                     if (op (a.data (ja), b.data (jb)) != 0.)
                        {
-                          r.data(jx) = op (a.data(ja), b.data(jb));
-                          r.ridx(jx) = a.ridx(ja);
+                          r.data (jx) = op (a.data (ja), b.data (jb));
+                          r.ridx (jx) = a.ridx (ja);
                           jx++;
                        }
                      ja++;
@@ -103,7 +103,7 @@
                      jb_lt_max= jb < jb_max;
                   }
               }
-            r.cidx(i+1) = jx;
+            r.cidx (i+1) = jx;
           }
 
         a = r.maybe_compress ();
@@ -139,7 +139,7 @@
   MArray<T> r (dim_vector (nr, nc), op (0.0, s));
 
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+    for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
       r.elem (a.ridx (i), j) = op (a.data (i), s);
   return r;
 }
@@ -171,11 +171,11 @@
 
   for (octave_idx_type i = 0; i < nz; i++)
     {
-      r.data(i) = op (a.data(i), s);
-      r.ridx(i) = a.ridx(i);
+      r.data (i) = op (a.data (i), s);
+      r.ridx (i) = a.ridx (i);
     }
   for (octave_idx_type i = 0; i < nc + 1; i++)
-    r.cidx(i) = a.cidx(i);
+    r.cidx (i) = a.cidx (i);
   r.maybe_compress (true);
   return r;
 }
@@ -207,7 +207,7 @@
   MArray<T> r (dim_vector (nr, nc), op (s, 0.0));
 
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+    for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
       r.elem (a.ridx (i), j) = op (s, a.data (i));
   return r;
 }
@@ -238,11 +238,11 @@
 
   for (octave_idx_type i = 0; i < nz; i++)
     {
-      r.data(i) = op (s, a.data(i));
-      r.ridx(i) = a.ridx(i);
+      r.data (i) = op (s, a.data (i));
+      r.ridx (i) = a.ridx (i);
     }
   for (octave_idx_type i = 0; i < nc + 1; i++)
-    r.cidx(i) = a.cidx(i);
+    r.cidx (i) = a.cidx (i);
   r.maybe_compress (true);
   return r;
 }
@@ -279,23 +279,23 @@
 
   if (a_nr == 1 && a_nc == 1)
     {
-      if (a.elem(0,0) == 0.)
+      if (a.elem (0,0) == 0.)
         if (negate)
           r = -MSparse<T> (b);
         else
           r = MSparse<T> (b);
       else
         {
-          r = MSparse<T> (b_nr, b_nc, op (a.data(0), 0.));
+          r = MSparse<T> (b_nr, b_nc, op (a.data (0), 0.));
 
           for (octave_idx_type j = 0 ; j < b_nc ; j++)
             {
               octave_quit ();
               octave_idx_type idxj = j * b_nr;
-              for (octave_idx_type i = b.cidx(j) ; i < b.cidx(j+1) ; i++)
+              for (octave_idx_type i = b.cidx (j) ; i < b.cidx (j+1) ; i++)
                 {
                   octave_quit ();
-                  r.data(idxj + b.ridx(i)) = op (a.data(0), b.data(i));
+                  r.data (idxj + b.ridx (i)) = op (a.data (0), b.data (i));
                 }
             }
           r.maybe_compress ();
@@ -303,20 +303,20 @@
     }
   else if (b_nr == 1 && b_nc == 1)
     {
-      if (b.elem(0,0) == 0.)
+      if (b.elem (0,0) == 0.)
         r = MSparse<T> (a);
       else
         {
-          r = MSparse<T> (a_nr, a_nc, op (0.0, b.data(0)));
+          r = MSparse<T> (a_nr, a_nc, op (0.0, b.data (0)));
 
           for (octave_idx_type j = 0 ; j < a_nc ; j++)
             {
               octave_quit ();
               octave_idx_type idxj = j * a_nr;
-              for (octave_idx_type i = a.cidx(j) ; i < a.cidx(j+1) ; i++)
+              for (octave_idx_type i = a.cidx (j) ; i < a.cidx (j+1) ; i++)
                 {
                   octave_quit ();
-                  r.data(idxj + a.ridx(i)) = op (a.data(i), b.data(0));
+                  r.data (idxj + a.ridx (i)) = op (a.data (i), b.data (0));
                 }
             }
           r.maybe_compress ();
@@ -332,41 +332,41 @@
       r.cidx (0) = 0;
       for (octave_idx_type i = 0 ; i < a_nc ; i++)
         {
-          octave_idx_type  ja = a.cidx(i);
-          octave_idx_type  ja_max = a.cidx(i+1);
+          octave_idx_type  ja = a.cidx (i);
+          octave_idx_type  ja_max = a.cidx (i+1);
           bool ja_lt_max= ja < ja_max;
 
-          octave_idx_type  jb = b.cidx(i);
-          octave_idx_type  jb_max = b.cidx(i+1);
+          octave_idx_type  jb = b.cidx (i);
+          octave_idx_type  jb_max = b.cidx (i+1);
           bool jb_lt_max = jb < jb_max;
 
           while (ja_lt_max || jb_lt_max )
             {
               octave_quit ();
               if ((! jb_lt_max) ||
-                  (ja_lt_max && (a.ridx(ja) < b.ridx(jb))))
+                  (ja_lt_max && (a.ridx (ja) < b.ridx (jb))))
                 {
-                  r.ridx(jx) = a.ridx(ja);
-                  r.data(jx) = op (a.data(ja), 0.);
+                  r.ridx (jx) = a.ridx (ja);
+                  r.data (jx) = op (a.data (ja), 0.);
                   jx++;
                   ja++;
                   ja_lt_max= ja < ja_max;
                 }
               else if (( !ja_lt_max ) ||
-                       (jb_lt_max && (b.ridx(jb) < a.ridx(ja)) ) )
+                       (jb_lt_max && (b.ridx (jb) < a.ridx (ja)) ) )
                 {
-                  r.ridx(jx) = b.ridx(jb);
-                  r.data(jx) = op (0.,  b.data(jb));
+                  r.ridx (jx) = b.ridx (jb);
+                  r.data (jx) = op (0.,  b.data (jb));
                   jx++;
                   jb++;
                   jb_lt_max= jb < jb_max;
                 }
               else
                 {
-                  if (op (a.data(ja), b.data(jb)) != 0.)
+                  if (op (a.data (ja), b.data (jb)) != 0.)
                     {
-                      r.data(jx) = op (a.data(ja), b.data(jb));
-                      r.ridx(jx) = a.ridx(ja);
+                      r.data (jx) = op (a.data (ja), b.data (jb));
+                      r.ridx (jx) = a.ridx (ja);
                       jx++;
                     }
                   ja++;
@@ -375,7 +375,7 @@
                   jb_lt_max= jb < jb_max;
                 }
             }
-          r.cidx(i+1) = jx;
+          r.cidx (i+1) = jx;
         }
 
       r.maybe_compress ();
@@ -412,34 +412,34 @@
 
   if (a_nr == 1 && a_nc == 1)
     {
-      if (a.elem(0,0) == 0.)
+      if (a.elem (0,0) == 0.)
         r = MSparse<T> (b_nr, b_nc);
       else
         {
           r = MSparse<T> (b);
-          octave_idx_type b_nnz = b.nnz();
+          octave_idx_type b_nnz = b.nnz ();
 
           for (octave_idx_type i = 0 ; i < b_nnz ; i++)
             {
               octave_quit ();
-              r.data (i) = a.data(0) * r.data(i);
+              r.data (i) = a.data (0) * r.data (i);
             }
           r.maybe_compress ();
         }
     }
   else if (b_nr == 1 && b_nc == 1)
     {
-      if (b.elem(0,0) == 0.)
+      if (b.elem (0,0) == 0.)
         r = MSparse<T> (a_nr, a_nc);
       else
         {
           r = MSparse<T> (a);
-          octave_idx_type a_nnz = a.nnz();
+          octave_idx_type a_nnz = a.nnz ();
 
           for (octave_idx_type i = 0 ; i < a_nnz ; i++)
             {
               octave_quit ();
-              r.data (i) = r.data(i) * b.data(0);
+              r.data (i) = r.data (i) * b.data (0);
             }
           r.maybe_compress ();
         }
@@ -454,40 +454,40 @@
       r.cidx (0) = 0;
       for (octave_idx_type i = 0 ; i < a_nc ; i++)
         {
-          octave_idx_type  ja = a.cidx(i);
-          octave_idx_type  ja_max = a.cidx(i+1);
+          octave_idx_type  ja = a.cidx (i);
+          octave_idx_type  ja_max = a.cidx (i+1);
           bool ja_lt_max= ja < ja_max;
 
-          octave_idx_type  jb = b.cidx(i);
-          octave_idx_type  jb_max = b.cidx(i+1);
+          octave_idx_type  jb = b.cidx (i);
+          octave_idx_type  jb_max = b.cidx (i+1);
           bool jb_lt_max = jb < jb_max;
 
           while (ja_lt_max || jb_lt_max )
             {
               octave_quit ();
               if ((! jb_lt_max) ||
-                  (ja_lt_max && (a.ridx(ja) < b.ridx(jb))))
+                  (ja_lt_max && (a.ridx (ja) < b.ridx (jb))))
                 {
                   ja++; ja_lt_max= ja < ja_max;
                 }
               else if (( !ja_lt_max ) ||
-                       (jb_lt_max && (b.ridx(jb) < a.ridx(ja)) ) )
+                       (jb_lt_max && (b.ridx (jb) < a.ridx (ja)) ) )
                 {
                   jb++; jb_lt_max= jb < jb_max;
                 }
               else
                 {
-                  if ((a.data(ja) * b.data(jb)) != 0.)
+                  if ((a.data (ja) * b.data (jb)) != 0.)
                     {
-                      r.data(jx) = a.data(ja) * b.data(jb);
-                      r.ridx(jx) = a.ridx(ja);
+                      r.data (jx) = a.data (ja) * b.data (jb);
+                      r.ridx (jx) = a.ridx (ja);
                       jx++;
                     }
                   ja++; ja_lt_max= ja < ja_max;
                   jb++; jb_lt_max= jb < jb_max;
                 }
             }
-          r.cidx(i+1) = jx;
+          r.cidx (i+1) = jx;
         }
 
       r.maybe_compress ();
@@ -512,13 +512,13 @@
   if (a_nr == 1 && a_nc == 1)
     {
       T val = a.elem (0,0);
-      T fill = val / T();
-      if (fill == T())
+      T fill = val / T ();
+      if (fill == T ())
         {
-          octave_idx_type b_nnz = b.nnz();
+          octave_idx_type b_nnz = b.nnz ();
           r = MSparse<T> (b);
           for (octave_idx_type i = 0 ; i < b_nnz ; i++)
-            r.data (i) = val / r.data(i);
+            r.data (i) = val / r.data (i);
           r.maybe_compress ();
         }
       else
@@ -528,10 +528,10 @@
             {
               octave_quit ();
               octave_idx_type idxj = j * b_nr;
-              for (octave_idx_type i = b.cidx(j) ; i < b.cidx(j+1) ; i++)
+              for (octave_idx_type i = b.cidx (j) ; i < b.cidx (j+1) ; i++)
                 {
                   octave_quit ();
-                  r.data(idxj + b.ridx(i)) = val / b.data(i);
+                  r.data (idxj + b.ridx (i)) = val / b.data (i);
                 }
             }
           r.maybe_compress ();
@@ -540,13 +540,13 @@
   else if (b_nr == 1 && b_nc == 1)
     {
       T val = b.elem (0,0);
-      T fill = T() / val;
-      if (fill == T())
+      T fill = T () / val;
+      if (fill == T ())
         {
-          octave_idx_type a_nnz = a.nnz();
+          octave_idx_type a_nnz = a.nnz ();
           r = MSparse<T> (a);
           for (octave_idx_type i = 0 ; i < a_nnz ; i++)
-            r.data (i) = r.data(i) / val;
+            r.data (i) = r.data (i) / val;
           r.maybe_compress ();
         }
       else
@@ -556,10 +556,10 @@
             {
               octave_quit ();
               octave_idx_type idxj = j * a_nr;
-              for (octave_idx_type i = a.cidx(j) ; i < a.cidx(j+1) ; i++)
+              for (octave_idx_type i = a.cidx (j) ; i < a.cidx (j+1) ; i++)
                 {
                   octave_quit ();
-                  r.data(idxj + a.ridx(i)) = a.data(i) / val;
+                  r.data (idxj + a.ridx (i)) = a.data (i) / val;
                 }
             }
           r.maybe_compress ();
@@ -573,32 +573,32 @@
 
       for (octave_idx_type i = 0 ; i < a_nc ; i++)
         {
-          octave_idx_type  ja = a.cidx(i);
-          octave_idx_type  ja_max = a.cidx(i+1);
+          octave_idx_type  ja = a.cidx (i);
+          octave_idx_type  ja_max = a.cidx (i+1);
           bool ja_lt_max= ja < ja_max;
 
-          octave_idx_type  jb = b.cidx(i);
-          octave_idx_type  jb_max = b.cidx(i+1);
+          octave_idx_type  jb = b.cidx (i);
+          octave_idx_type  jb_max = b.cidx (i+1);
           bool jb_lt_max = jb < jb_max;
 
           while (ja_lt_max || jb_lt_max )
             {
               octave_quit ();
               if ((! jb_lt_max) ||
-                  (ja_lt_max && (a.ridx(ja) < b.ridx(jb))))
+                  (ja_lt_max && (a.ridx (ja) < b.ridx (jb))))
                 {
-                  r.elem (a.ridx(ja),i) = a.data(ja) / Zero;
+                  r.elem (a.ridx (ja),i) = a.data (ja) / Zero;
                   ja++; ja_lt_max= ja < ja_max;
                 }
               else if (( !ja_lt_max ) ||
-                       (jb_lt_max && (b.ridx(jb) < a.ridx(ja)) ) )
+                       (jb_lt_max && (b.ridx (jb) < a.ridx (ja)) ) )
                 {
-                  r.elem (b.ridx(jb),i) = Zero / b.data(jb);
+                  r.elem (b.ridx (jb),i) = Zero / b.data (jb);
                   jb++; jb_lt_max= jb < jb_max;
                 }
               else
                 {
-                  r.elem (a.ridx(ja),i) = a.data(ja) / b.data(jb);
+                  r.elem (a.ridx (ja),i) = a.data (ja) / b.data (jb);
                   ja++; ja_lt_max= ja < ja_max;
                   jb++; jb_lt_max= jb < jb_max;
                 }
@@ -629,6 +629,6 @@
   MSparse<T> retval (a);
   octave_idx_type nz = a.nnz ();
   for (octave_idx_type i = 0; i < nz; i++)
-    retval.data(i) = - retval.data(i);
+    retval.data (i) = - retval.data (i);
   return retval;
 }
rename from liboctave/MSparse.h
rename to liboctave/array/MSparse.h
rename from liboctave/Matrix.h
rename to liboctave/array/Matrix.h
rename from liboctave/MatrixType.cc
rename to liboctave/array/MatrixType.cc
--- a/liboctave/MatrixType.cc
+++ b/liboctave/array/MatrixType.cc
@@ -40,7 +40,7 @@
 
 MatrixType::MatrixType (void)
   : typ (MatrixType::Unknown),
-    sp_bandden (octave_sparse_params::get_bandden()),
+    sp_bandden (octave_sparse_params::get_bandden ()),
     bandden (0), upper_band (0),
     lower_band (0), dense (false), full (false), nperm (0), perm (0) { }
 
@@ -74,7 +74,7 @@
       bool hermitian = true;
 
       // do the checks for lower/upper/hermitian all in one pass.
-      OCTAVE_LOCAL_BUFFER(T, diag, ncols);
+      OCTAVE_LOCAL_BUFFER (T, diag, ncols);
 
       for (octave_idx_type j = 0;
            j < ncols && upper; j++)
@@ -132,7 +132,7 @@
       bool hermitian = true;
 
       // do the checks for lower/upper/hermitian all in one pass.
-      OCTAVE_LOCAL_BUFFER(T, diag, ncols);
+      OCTAVE_LOCAL_BUFFER (T, diag, ncols);
 
       for (octave_idx_type j = 0;
            j < ncols && upper; j++)
@@ -140,8 +140,8 @@
           std::complex<T> d = a.elem (j,j);
           upper = upper && (d != zero);
           lower = lower && (d != zero);
-          hermitian = hermitian && (d.real() > zero && d.imag() == zero);
-          diag[j] = d.real();
+          hermitian = hermitian && (d.real () > zero && d.imag () == zero);
+          diag[j] = d.real ();
         }
 
       for (octave_idx_type j = 0;
@@ -220,7 +220,7 @@
     (*current_liboctave_warning_handler)
       ("Calculating Sparse Matrix Type");
 
-  sp_bandden = octave_sparse_params::get_bandden();
+  sp_bandden = octave_sparse_params::get_bandden ();
   bool maybe_hermitian = false;
   typ = MatrixType::Full;
 
@@ -231,12 +231,12 @@
       // Maybe the matrix is diagonal
       for (i = 0; i < nm; i++)
         {
-          if (a.cidx(i+1) != a.cidx(i) + 1)
+          if (a.cidx (i+1) != a.cidx (i) + 1)
             {
               tmp_typ = MatrixType::Full;
               break;
             }
-          if (a.ridx(i) != i)
+          if (a.ridx (i) != i)
             {
               tmp_typ = MatrixType::Permuted_Diagonal;
               break;
@@ -248,19 +248,19 @@
           std::vector<bool> found (nrows);
 
           for (octave_idx_type j = 0; j < i; j++)
-            found [j] = true;
+            found[j] = true;
           for (octave_idx_type j = i; j < nrows; j++)
-            found [j] = false;
+            found[j] = false;
 
           for (octave_idx_type j = i; j < nm; j++)
             {
-              if ((a.cidx(j+1) > a.cidx(j) + 1)  ||
-                  ((a.cidx(j+1) == a.cidx(j) + 1) && found [a.ridx(j)]))
+              if ((a.cidx (j+1) > a.cidx (j) + 1)  ||
+                  ((a.cidx (j+1) == a.cidx (j) + 1) && found[a.ridx (j)]))
                 {
                   tmp_typ = MatrixType::Full;
                   break;
                 }
-              found [a.ridx(j)] = true;
+              found[a.ridx (j)] = true;
             }
         }
       typ = tmp_typ;
@@ -278,8 +278,8 @@
           if (j < nrows)
             {
               zero_on_diagonal = true;
-              for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
-                if (a.ridx(i) == j)
+              for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
+                if (a.ridx (i) == j)
                   {
                     zero_on_diagonal = false;
                     break;
@@ -292,10 +292,10 @@
               break;
             }
 
-          if (a.cidx(j+1) != a.cidx(j))
+          if (a.cidx (j+1) != a.cidx (j))
             {
-              octave_idx_type ru = a.ridx(a.cidx(j));
-              octave_idx_type rl = a.ridx(a.cidx(j+1)-1);
+              octave_idx_type ru = a.ridx (a.cidx (j));
+              octave_idx_type rl = a.ridx (a.cidx (j+1)-1);
 
               if (j - ru > upper_band)
                 upper_band = j - ru;
@@ -351,7 +351,7 @@
           perm = new octave_idx_type [ncols];
 
           for (octave_idx_type i = 0; i < ncols; i++)
-            perm [i] = -1;
+            perm[i] = -1;
 
           for (octave_idx_type i = 0; i < nm; i++)
             {
@@ -359,10 +359,10 @@
 
               for (octave_idx_type j = 0; j < ncols; j++)
                 {
-                  if ((a.cidx(j+1) - a.cidx(j)) > 0 &&
-                      (a.ridx(a.cidx(j+1)-1) == i))
+                  if ((a.cidx (j+1) - a.cidx (j)) > 0 &&
+                      (a.ridx (a.cidx (j+1)-1) == i))
                     {
-                      perm [i] = j;
+                      perm[i] = j;
                       found = true;
                       break;
                     }
@@ -379,11 +379,11 @@
                 {
                   octave_idx_type k = nrows;
                   for (octave_idx_type i = 0; i < ncols; i++)
-                    if (perm [i] == -1)
+                    if (perm[i] == -1)
                       perm[i] = k++;
                 }
             }
-          else if (a.cidx(nm) == a.cidx(ncols))
+          else if (a.cidx (nm) == a.cidx (ncols))
             {
               nperm = nrows;
               delete [] perm;
@@ -392,13 +392,13 @@
 
               for (octave_idx_type i = 0; i < nrows; i++)
                 {
-                  perm [i] = -1;
-                  tmp [i] = -1;
+                  perm[i] = -1;
+                  tmp[i] = -1;
                 }
 
               for (octave_idx_type j = 0; j < ncols; j++)
-                for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
-                    perm [a.ridx(i)] = j;
+                for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
+                    perm[a.ridx (i)] = j;
 
               found = true;
               for (octave_idx_type i = 0; i < nm; i++)
@@ -478,11 +478,11 @@
           for (octave_idx_type j = 0; is_herm && j < ncols; j++)
             {
               is_herm = false;
-              for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+              for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
                 {
-                  if (a.ridx(i) == j)
+                  if (a.ridx (i) == j)
                     {
-                      double d = a.data(i);
+                      double d = a.data (i);
                       is_herm = d > 0.;
                       diag(j) = d;
                       break;
@@ -494,20 +494,20 @@
           // next, check symmetry and 2x2 positiveness
 
           for (octave_idx_type j = 0; is_herm && j < ncols; j++)
-            for (octave_idx_type i = a.cidx(j); is_herm && i < a.cidx(j+1); i++)
+            for (octave_idx_type i = a.cidx (j); is_herm && i < a.cidx (j+1); i++)
               {
-                octave_idx_type k = a.ridx(i);
+                octave_idx_type k = a.ridx (i);
                 is_herm = k == j;
                 if (is_herm)
                   continue;
-                double d = a.data(i);
+                double d = a.data (i);
                 if (d*d < diag(j)*diag(k))
                   {
-                    for (octave_idx_type l = a.cidx(k); l < a.cidx(k+1); l++)
+                    for (octave_idx_type l = a.cidx (k); l < a.cidx (k+1); l++)
                       {
-                        if (a.ridx(l) == j)
+                        if (a.ridx (l) == j)
                           {
-                            is_herm = a.data(l) == d;
+                            is_herm = a.data (l) == d;
                             break;
                           }
                       }
@@ -541,7 +541,7 @@
     (*current_liboctave_warning_handler)
       ("Calculating Sparse Matrix Type");
 
-  sp_bandden = octave_sparse_params::get_bandden();
+  sp_bandden = octave_sparse_params::get_bandden ();
   bool maybe_hermitian = false;
   typ = MatrixType::Full;
 
@@ -552,12 +552,12 @@
       // Maybe the matrix is diagonal
       for (i = 0; i < nm; i++)
         {
-          if (a.cidx(i+1) != a.cidx(i) + 1)
+          if (a.cidx (i+1) != a.cidx (i) + 1)
             {
               tmp_typ = MatrixType::Full;
               break;
             }
-          if (a.ridx(i) != i)
+          if (a.ridx (i) != i)
             {
               tmp_typ = MatrixType::Permuted_Diagonal;
               break;
@@ -569,19 +569,19 @@
           std::vector<bool> found (nrows);
 
           for (octave_idx_type j = 0; j < i; j++)
-            found [j] = true;
+            found[j] = true;
           for (octave_idx_type j = i; j < nrows; j++)
-            found [j] = false;
+            found[j] = false;
 
           for (octave_idx_type j = i; j < nm; j++)
             {
-              if ((a.cidx(j+1) > a.cidx(j) + 1)  ||
-                  ((a.cidx(j+1) == a.cidx(j) + 1) && found [a.ridx(j)]))
+              if ((a.cidx (j+1) > a.cidx (j) + 1)  ||
+                  ((a.cidx (j+1) == a.cidx (j) + 1) && found[a.ridx (j)]))
                 {
                   tmp_typ = MatrixType::Full;
                   break;
                 }
-              found [a.ridx(j)] = true;
+              found[a.ridx (j)] = true;
             }
         }
       typ = tmp_typ;
@@ -599,8 +599,8 @@
           if (j < nrows)
             {
               zero_on_diagonal = true;
-              for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
-                if (a.ridx(i) == j)
+              for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
+                if (a.ridx (i) == j)
                   {
                     zero_on_diagonal = false;
                     break;
@@ -613,10 +613,10 @@
               break;
             }
 
-          if (a.cidx(j+1) != a.cidx(j))
+          if (a.cidx (j+1) != a.cidx (j))
             {
-              octave_idx_type ru = a.ridx(a.cidx(j));
-              octave_idx_type rl = a.ridx(a.cidx(j+1)-1);
+              octave_idx_type ru = a.ridx (a.cidx (j));
+              octave_idx_type rl = a.ridx (a.cidx (j+1)-1);
 
               if (j - ru > upper_band)
                 upper_band = j - ru;
@@ -672,7 +672,7 @@
           perm = new octave_idx_type [ncols];
 
           for (octave_idx_type i = 0; i < ncols; i++)
-            perm [i] = -1;
+            perm[i] = -1;
 
           for (octave_idx_type i = 0; i < nm; i++)
             {
@@ -680,10 +680,10 @@
 
               for (octave_idx_type j = 0; j < ncols; j++)
                 {
-                  if ((a.cidx(j+1) - a.cidx(j)) > 0 &&
-                      (a.ridx(a.cidx(j+1)-1) == i))
+                  if ((a.cidx (j+1) - a.cidx (j)) > 0 &&
+                      (a.ridx (a.cidx (j+1)-1) == i))
                     {
-                      perm [i] = j;
+                      perm[i] = j;
                       found = true;
                       break;
                     }
@@ -700,11 +700,11 @@
                 {
                   octave_idx_type k = nrows;
                   for (octave_idx_type i = 0; i < ncols; i++)
-                    if (perm [i] == -1)
+                    if (perm[i] == -1)
                       perm[i] = k++;
                 }
             }
-          else if (a.cidx(nm) == a.cidx(ncols))
+          else if (a.cidx (nm) == a.cidx (ncols))
             {
               nperm = nrows;
               delete [] perm;
@@ -713,13 +713,13 @@
 
               for (octave_idx_type i = 0; i < nrows; i++)
                 {
-                  perm [i] = -1;
-                  tmp [i] = -1;
+                  perm[i] = -1;
+                  tmp[i] = -1;
                 }
 
               for (octave_idx_type j = 0; j < ncols; j++)
-                for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
-                    perm [a.ridx(i)] = j;
+                for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
+                    perm[a.ridx (i)] = j;
 
               found = true;
               for (octave_idx_type i = 0; i < nm; i++)
@@ -799,13 +799,13 @@
           for (octave_idx_type j = 0; is_herm && j < ncols; j++)
             {
               is_herm = false;
-              for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+              for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
                 {
-                  if (a.ridx(i) == j)
+                  if (a.ridx (i) == j)
                     {
-                      Complex d = a.data(i);
-                      is_herm = d.real() > 0. && d.imag() == 0.;
-                      diag(j) = d.real();
+                      Complex d = a.data (i);
+                      is_herm = d.real () > 0. && d.imag () == 0.;
+                      diag(j) = d.real ();
                       break;
                     }
                 }
@@ -814,21 +814,21 @@
           // next, check symmetry and 2x2 positiveness
 
           for (octave_idx_type j = 0; is_herm && j < ncols; j++)
-            for (octave_idx_type i = a.cidx(j); is_herm && i < a.cidx(j+1); i++)
+            for (octave_idx_type i = a.cidx (j); is_herm && i < a.cidx (j+1); i++)
               {
-                octave_idx_type k = a.ridx(i);
+                octave_idx_type k = a.ridx (i);
                 is_herm = k == j;
                 if (is_herm)
                   continue;
-                Complex d = a.data(i);
+                Complex d = a.data (i);
                 if (std::norm (d) < diag(j)*diag(k))
                   {
                     d = std::conj (d);
-                    for (octave_idx_type l = a.cidx(k); l < a.cidx(k+1); l++)
+                    for (octave_idx_type l = a.cidx (k); l < a.cidx (k+1); l++)
                       {
-                        if (a.ridx(l) == j)
+                        if (a.ridx (l) == j)
                           {
-                            is_herm = a.data(l) == d;
+                            is_herm = a.data (l) == d;
                             break;
                           }
                       }
@@ -850,7 +850,7 @@
 }
 MatrixType::MatrixType (const matrix_type t, bool _full)
   : typ (MatrixType::Unknown),
-    sp_bandden (octave_sparse_params::get_bandden()),
+    sp_bandden (octave_sparse_params::get_bandden ()),
     bandden (0), upper_band (0), lower_band (0),
     dense (false), full (_full), nperm (0), perm (0)
 {
@@ -867,7 +867,7 @@
 MatrixType::MatrixType (const matrix_type t, const octave_idx_type np,
                         const octave_idx_type *p, bool _full)
   : typ (MatrixType::Unknown),
-    sp_bandden (octave_sparse_params::get_bandden()),
+    sp_bandden (octave_sparse_params::get_bandden ()),
     bandden (0), upper_band (0), lower_band (0),
     dense (false), full (_full), nperm (0), perm (0)
 {
@@ -887,7 +887,7 @@
 MatrixType::MatrixType (const matrix_type t, const octave_idx_type ku,
                         const octave_idx_type kl, bool _full)
   : typ (MatrixType::Unknown),
-    sp_bandden (octave_sparse_params::get_bandden()),
+    sp_bandden (octave_sparse_params::get_bandden ()),
     bandden (0), upper_band (0), lower_band (0),
     dense (false), full (_full), nperm (0), perm (0)
 {
@@ -944,7 +944,7 @@
 MatrixType::type (bool quiet)
 {
   if (typ != MatrixType::Unknown && (full ||
-      sp_bandden == octave_sparse_params::get_bandden()))
+      sp_bandden == octave_sparse_params::get_bandden ()))
     {
       if (!quiet &&
           octave_sparse_params::get_key ("spumoni") != 0.)
@@ -968,7 +968,7 @@
 MatrixType::type (const SparseMatrix &a)
 {
   if (typ != MatrixType::Unknown && (full ||
-      sp_bandden == octave_sparse_params::get_bandden()))
+      sp_bandden == octave_sparse_params::get_bandden ()))
     {
       if (octave_sparse_params::get_key ("spumoni") != 0.)
         (*current_liboctave_warning_handler)
@@ -1001,7 +1001,7 @@
 MatrixType::type (const SparseComplexMatrix &a)
 {
   if (typ != MatrixType::Unknown && (full ||
-      sp_bandden == octave_sparse_params::get_bandden()))
+      sp_bandden == octave_sparse_params::get_bandden ()))
     {
       if (octave_sparse_params::get_key ("spumoni") != 0.)
         (*current_liboctave_warning_handler)
rename from liboctave/MatrixType.h
rename to liboctave/array/MatrixType.h
rename from liboctave/PermMatrix.cc
rename to liboctave/array/PermMatrix.cc
rename from liboctave/PermMatrix.h
rename to liboctave/array/PermMatrix.h
rename from liboctave/Range.cc
rename to liboctave/array/Range.cc
--- a/liboctave/Range.cc
+++ b/liboctave/array/Range.cc
@@ -36,14 +36,6 @@
 #include "lo-utils.h"
 #include "Array-util.h"
 
-Range::Range (double b, double i, octave_idx_type n)
-  : rng_base (b), rng_limit (b + (n-1) * i), rng_inc (i),
-    rng_nelem (n), cache ()
-{
-  if (! xfinite (b) || ! xfinite (i))
-    rng_nelem = -2;
-}
-
 bool
 Range::all_elements_are_ints (void) const
 {
@@ -64,17 +56,24 @@
       cache.resize (1, rng_nelem);
       double b = rng_base;
       double increment = rng_inc;
-      for (octave_idx_type i = 0; i < rng_nelem; i++)
-        cache(i) = b + i * increment;
+      if (rng_nelem > 0)
+        {
+          // The first element must always be *exactly* the base.
+          // E.g, -0 would otherwise become +0 in the loop (-0 + 0*increment).
+          cache(0) = b; 
+          for (octave_idx_type i = 1; i < rng_nelem; i++)
+            cache(i) = b + i * increment;
+        }
 
       // On some machines (x86 with extended precision floating point
       // arithmetic, for example) it is possible that we can overshoot
       // the limit by approximately the machine precision even though
       // we were very careful in our calculation of the number of
-      // elements.
+      // elements.  The tests need equality (>= rng_limit or <= rng_limit)
+      // to have expressions like -5:1:-0 result in a -0 endpoint.
 
-      if ((rng_inc > 0 && cache(rng_nelem-1) > rng_limit)
-          || (rng_inc < 0 && cache(rng_nelem-1) < rng_limit))
+      if ((rng_inc > 0 && cache(rng_nelem-1) >= rng_limit)
+          || (rng_inc < 0 && cache(rng_nelem-1) <= rng_limit))
         cache(rng_nelem-1) = rng_limit;
     }
 
@@ -87,16 +86,71 @@
   if (i < 0 || i >= rng_nelem)
     gripe_index_out_of_range (1, 1, i+1, rng_nelem);
 
-  return rng_base + rng_inc * i;
+  if (i == 0)
+    return rng_base;
+  else if (i < rng_nelem - 1) 
+    return rng_base + i * rng_inc;
+  else
+    {
+      double end = rng_base + i * rng_inc;
+      if ((rng_inc > 0 && end >= rng_limit)
+          || (rng_inc < 0 && end <= rng_limit))
+        return rng_limit;
+      else
+        return end;
+    }
 }
 
-struct _rangeidx_helper
+double
+Range::elem (octave_idx_type i) const
+{
+#if defined (BOUNDS_CHECKING)
+  return checkelem (i);
+#else
+  if (i == 0)
+    return rng_base;
+  else if (i < rng_nelem - 1) 
+    return rng_base + i * rng_inc;
+  else
+    {
+      double end = rng_base + i * rng_inc;
+      if ((rng_inc > 0 && end >= rng_limit)
+          || (rng_inc < 0 && end <= rng_limit))
+        return rng_limit;
+      else
+        return end;
+    }
+#endif
+}
+
+// Helper class used solely for idx_vector.loop () function call
+class __rangeidx_helper
 {
-  double *array, base, inc;
-  _rangeidx_helper (double *a, double b, double i)
-    : array (a), base (b), inc (i) { }
+ public:
+  __rangeidx_helper (double *a, double b, double i, double l, octave_idx_type n)
+    : array (a), base (b), inc (i), limit (l), nmax (n-1) { }
+
   void operator () (octave_idx_type i)
-    { *array++ = base + i * inc; }
+    {
+      if (i == 0)
+        *array++ = base;
+      else if (i < nmax) 
+        *array++ = base + i * inc;
+      else
+        {
+          double end = base + i * inc;
+          if ((inc > 0 && end >= limit) || (inc < 0 && end <= limit))
+            *array++ = limit;
+          else
+            *array++ = end;
+        }
+    }
+
+ private:
+
+  double *array, base, inc, limit;
+  octave_idx_type nmax;
+
 };
 
 Array<double>
@@ -119,19 +173,22 @@
       octave_idx_type il = i.length (n);
 
       // taken from Array.cc.
-
       if (n != 1 && rd.is_vector ())
         rd = dim_vector (1, il);
 
       retval.clear (rd);
 
-      i.loop (n, _rangeidx_helper (retval.fortran_vec (), rng_base, rng_inc));
+      // idx_vector loop across all values in i,
+      // executing __rangeidx_helper (i) for each i
+      i.loop (n, __rangeidx_helper (retval.fortran_vec (),
+                                    rng_base, rng_inc, rng_limit, rng_nelem));
     }
 
   return retval;
 }
 
 // NOTE: max and min only return useful values if nelem > 0.
+//       do_minmax_body() in max.cc avoids calling Range::min/max if nelem == 0.
 
 double
 Range::min (void) const
@@ -146,8 +203,7 @@
           retval = rng_base + (rng_nelem - 1) * rng_inc;
 
           // See the note in the matrix_value method above.
-
-          if (retval < rng_limit)
+          if (retval <= rng_limit)
             retval = rng_limit;
         }
 
@@ -166,8 +222,7 @@
           retval = rng_base + (rng_nelem - 1) * rng_inc;
 
           // See the note in the matrix_value method above.
-
-          if (retval > rng_limit)
+          if (retval >= rng_limit)
             retval = rng_limit;
         }
       else
@@ -268,7 +323,7 @@
   if (dim == 1)
     {
       if (mode == ASCENDING)
-          retval.sort_internal (sidx, true);
+        retval.sort_internal (sidx, true);
       else if (mode == DESCENDING)
         retval.sort_internal (sidx, false);
     }
@@ -281,10 +336,10 @@
 sortmode
 Range::is_sorted (sortmode mode) const
 {
-  if (rng_nelem > 1 && rng_inc < 0)
+  if (rng_nelem > 1 && rng_inc > 0)
+    mode = (mode == DESCENDING) ? UNSORTED : ASCENDING;
+  else if (rng_nelem > 1 && rng_inc < 0)
     mode = (mode == ASCENDING) ? UNSORTED : DESCENDING;
-  else if (rng_nelem > 1 && rng_inc > 0)
-    mode = (mode == DESCENDING) ? UNSORTED : ASCENDING;
   else
     mode = mode ? mode : ASCENDING;
 
@@ -298,12 +353,15 @@
   double increment = a.inc ();
   octave_idx_type num_elem = a.nelem ();
 
-  for (octave_idx_type i = 0; i < num_elem-1; i++)
-    os << b + i * increment << " ";
+  if (num_elem > 1)
+    {
+      // First element must be the base *exactly* (-0).
+      os << b << " ";
+      for (octave_idx_type i = 1; i < num_elem-1; i++)
+        os << b + i * increment << " ";
+    }
 
-  // Prevent overshoot.  See comment in the matrix_value method
-  // above.
-
+  // Prevent overshoot.  See comment in the matrix_value method above.
   os << (increment > 0 ? a.max () : a.min ()) << "\n";
 
   return os;
@@ -456,7 +514,7 @@
 }
 
 static inline bool
-teq (double u, double v, double ct = 3.0 * DBL_EPSILON)
+teq (double u, double v, double ct = 3.0 * std::numeric_limits<double>::epsilon ())
 {
   double tu = fabs (u);
   double tv = fabs (v);
@@ -477,7 +535,7 @@
     }
   else
     {
-      double ct = 3.0 * DBL_EPSILON;
+      double ct = 3.0 * std::numeric_limits<double>::epsilon ();
 
       double tmp = tfloor ((rng_limit - rng_base + rng_inc) / rng_inc, ct);
 
@@ -502,7 +560,7 @@
             n_elt++;
         }
 
-      retval = (n_elt >= std::numeric_limits<octave_idx_type>::max () - 1) ? -1 : n_elt;
+      retval = (n_elt < std::numeric_limits<octave_idx_type>::max () - 1) ? n_elt : -1;
     }
 
   return retval;
rename from liboctave/Range.h
rename to liboctave/array/Range.h
--- a/liboctave/Range.h
+++ b/liboctave/array/Range.h
@@ -50,7 +50,13 @@
       rng_nelem (nelem_internal ()), cache () { }
 
   // For operators' usage (to preserve element count).
-  Range (double b, double i, octave_idx_type n);
+  Range (double b, double i, octave_idx_type n)
+    : rng_base (b), rng_limit (b + (n-1) * i), rng_inc (i),
+      rng_nelem (n), cache ()
+    {
+      if (! xfinite (b) || ! xfinite (i))
+        rng_nelem = -2;
+    }
 
   double base (void) const { return rng_base; }
   double limit (void) const { return rng_limit; }
@@ -80,14 +86,7 @@
 
   double checkelem (octave_idx_type i) const;
 
-  double elem (octave_idx_type i) const
-    {
-#if defined (BOUNDS_CHECKING)
-      return checkelem (i);
-#else
-      return rng_base + rng_inc * i;
-#endif
-    }
+  double elem (octave_idx_type i) const;
 
   Array<double> index (const idx_vector& i) const;
 
rename from liboctave/Sparse-C.cc
rename to liboctave/array/Sparse-C.cc
rename from liboctave/Sparse-b.cc
rename to liboctave/array/Sparse-b.cc
rename from liboctave/Sparse-d.cc
rename to liboctave/array/Sparse-d.cc
rename from liboctave/Sparse.cc
rename to liboctave/array/Sparse.cc
--- a/liboctave/Sparse.cc
+++ b/liboctave/array/Sparse.cc
@@ -28,10 +28,10 @@
 #endif
 
 #include <cassert>
-#include <climits>
 
 #include <algorithm>
 #include <iostream>
+#include <limits>
 #include <sstream>
 #include <vector>
 
@@ -55,7 +55,7 @@
 template <class T>
 Sparse<T>::Sparse (const PermMatrix& a)
   : rep (new typename Sparse<T>::SparseRep (a.rows (), a.cols (), a.rows ())),
-         dimensions (dim_vector (a.rows (), a.cols()))
+         dimensions (dim_vector (a.rows (), a.cols ()))
 {
   octave_idx_type n = a.rows ();
   for (octave_idx_type i = 0; i <= n; i++)
@@ -66,12 +66,12 @@
   if (a.is_row_perm ())
     {
       for (octave_idx_type i = 0; i < n; i++)
-        ridx (pv (i)) = i;
+        ridx (pv(i)) = i;
     }
   else
     {
       for (octave_idx_type i = 0; i < n; i++)
-        ridx (i) = pv (i);
+        ridx (i) = pv(i);
     }
 
   for (octave_idx_type i = 0; i < n; i++)
@@ -149,7 +149,7 @@
         {
           octave_idx_type u = c[j];
           for (i = i; i < u; i++)
-            if (d[i] != T())
+            if (d[i] != T ())
               {
                 d[k] = d[i];
                 r[k++] = r[i];
@@ -223,7 +223,7 @@
     {
       rep = new typename Sparse<T>::SparseRep (nr, nc, 0);
       for (octave_idx_type j = 0; j < nc+1; j++)
-        xcidx(j) = 0;
+        xcidx (j) = 0;
     }
 }
 
@@ -231,7 +231,7 @@
 Sparse<T>::Sparse (const dim_vector& dv)
   : rep (0), dimensions (dv)
 {
-  if (dv.length() != 2)
+  if (dv.length () != 2)
     (*current_liboctave_error_handler)
       ("Sparse::Sparse (const dim_vector&): dimension mismatch");
   else
@@ -254,7 +254,7 @@
       ("Sparse::Sparse (const Sparse&, const dim_vector&): dimension mismatch");
   else
     {
-      dim_vector old_dims = a.dims();
+      dim_vector old_dims = a.dims ();
       octave_idx_type new_nzmx = a.nnz ();
       octave_idx_type new_nr = dv (0);
       octave_idx_type new_nc = dv (1);
@@ -264,21 +264,21 @@
       rep = new typename Sparse<T>::SparseRep (new_nr, new_nc, new_nzmx);
 
       octave_idx_type kk = 0;
-      xcidx(0) = 0;
+      xcidx (0) = 0;
       for (octave_idx_type i = 0; i < old_nc; i++)
-        for (octave_idx_type j = a.cidx(i); j < a.cidx(i+1); j++)
+        for (octave_idx_type j = a.cidx (i); j < a.cidx (i+1); j++)
           {
-            octave_idx_type tmp = i * old_nr + a.ridx(j);
+            octave_idx_type tmp = i * old_nr + a.ridx (j);
             octave_idx_type ii = tmp % new_nr;
             octave_idx_type jj = (tmp - ii) / new_nr;
             for (octave_idx_type k = kk; k < jj; k++)
-              xcidx(k+1) = j;
+              xcidx (k+1) = j;
             kk = jj;
-            xdata(j) = a.data(j);
-            xridx(j) = ii;
+            xdata (j) = a.data (j);
+            xridx (j) = ii;
           }
       for (octave_idx_type k = kk; k < new_nc; k++)
-        xcidx(k+1) = new_nzmx;
+        xcidx (k+1) = new_nzmx;
     }
 }
 
@@ -326,15 +326,16 @@
           xcidx(0) = 0;
           xridx(0) = r(0);
           xdata(0) = a(0);
+
           for (octave_idx_type j = 0; j < nc; j++)
-            xcidx(j+1) = j >= c(0);
+            xcidx (j+1) = j >= c(0);
         }
     }
   else if (a_scalar)
     {
       // This is completely specialized, because the sorts can be simplified.
       T a0 = a(0);
-      if (a0 == T())
+      if (a0 == T ())
         {
           // Do nothing, it's an empty matrix.
         }
@@ -419,7 +420,7 @@
               sidx[ci[cd[i]+1]++] = rd[i];
 
           // Subsorts. We don't need a stable sort, all values are equal.
-          xcidx(0) = 0;
+          xcidx (0) = 0;
           for (octave_idx_type j = 0; j < nc; j++)
             {
               std::sort (sidx + ci[j], sidx + ci[j+1]);
@@ -435,7 +436,7 @@
                     }
                 }
               // Set column pointer.
-              xcidx(j+1) = xcidx(j) + nzj;
+              xcidx (j+1) = xcidx (j) + nzj;
             }
 
           change_capacity (nzm > xcidx (nc) ? nzm : xcidx (nc));
@@ -566,7 +567,7 @@
         }
 
       // Subsorts. We don't need a stable sort, the second index stabilizes it.
-      xcidx(0) = 0;
+      xcidx (0) = 0;
       for (octave_idx_type j = 0; j < nc; j++)
         {
           std::sort (spairs + ci[j], spairs + ci[j+1]);
@@ -582,7 +583,7 @@
                 }
             }
           // Set column pointer.
-          xcidx(j+1) = xcidx(j) + nzj;
+          xcidx (j+1) = xcidx (j) + nzj;
         }
 
       change_capacity (nzm > xcidx (nc) ? nzm : xcidx (nc));
@@ -652,16 +653,16 @@
       rep = new typename Sparse<T>::SparseRep (nr, nc, new_nzmx);
 
       octave_idx_type ii = 0;
-      xcidx(0) = 0;
+      xcidx (0) = 0;
       for (octave_idx_type j = 0; j < nc; j++)
         {
           for (octave_idx_type i = 0; i < nr; i++)
             if (a.elem (i,j) != T ())
               {
-                xdata(ii) = a.elem (i,j);
-                xridx(ii++) = i;
+                xdata (ii) = a.elem (i,j);
+                xridx (ii++) = i;
               }
-          xcidx(j+1) = ii;
+          xcidx (j+1) = ii;
         }
     }
 }
@@ -815,7 +816,7 @@
       (*current_liboctave_warning_handler)
         ("reshape: sparse reshape to N-d array smashes dims");
 
-      for (octave_idx_type i = 2; i < dims2.length(); i++)
+      for (octave_idx_type i = 2; i < dims2.length (); i++)
         dims2(1) *= dims2(i);
 
       dims2.resize (2);
@@ -833,21 +834,21 @@
           retval = Sparse<T> (new_nr, new_nc, new_nnz);
 
           octave_idx_type kk = 0;
-          retval.xcidx(0) = 0;
+          retval.xcidx (0) = 0;
           for (octave_idx_type i = 0; i < old_nc; i++)
-            for (octave_idx_type j = cidx(i); j < cidx(i+1); j++)
+            for (octave_idx_type j = cidx (i); j < cidx (i+1); j++)
               {
-                octave_idx_type tmp = i * old_nr + ridx(j);
+                octave_idx_type tmp = i * old_nr + ridx (j);
                 octave_idx_type ii = tmp % new_nr;
                 octave_idx_type jj = (tmp - ii) / new_nr;
                 for (octave_idx_type k = kk; k < jj; k++)
-                  retval.xcidx(k+1) = j;
+                  retval.xcidx (k+1) = j;
                 kk = jj;
-                retval.xdata(j) = data(j);
-                retval.xridx(j) = ii;
+                retval.xdata (j) = data (j);
+                retval.xridx (j) = ii;
               }
           for (octave_idx_type k = kk; k < new_nc; k++)
-            retval.xcidx(k+1) = new_nnz;
+            retval.xcidx (k+1) = new_nnz;
         }
       else
         {
@@ -949,14 +950,14 @@
       octave_idx_type i = 0, k = 0;
       for (octave_idx_type j = 1; j <= rep->ncols; j++)
         {
-          octave_idx_type u = xcidx(j);
+          octave_idx_type u = xcidx (j);
           for (i = i; i < u; i++)
-            if (xridx(i) < r)
+            if (xridx (i) < r)
               {
-                xdata(k) = xdata(i);
-                xridx(k++) = xridx(i);
+                xdata (k) = xdata (i);
+                xridx (k++) = xridx (i);
               }
-          xcidx(j) = k;
+          xcidx (j) = k;
         }
     }
 
@@ -994,69 +995,69 @@
     }
 
   // First count the number of elements in the final array
-  octave_idx_type nel = cidx(c) + a.nnz ();
+  octave_idx_type nel = cidx (c) + a.nnz ();
 
   if (c + a_cols < nc)
-    nel += cidx(nc) - cidx(c + a_cols);
+    nel += cidx (nc) - cidx (c + a_cols);
 
   for (octave_idx_type i = c; i < c + a_cols; i++)
-    for (octave_idx_type j = cidx(i); j < cidx(i+1); j++)
-      if (ridx(j) < r || ridx(j) >= r + a_rows)
+    for (octave_idx_type j = cidx (i); j < cidx (i+1); j++)
+      if (ridx (j) < r || ridx (j) >= r + a_rows)
         nel++;
 
   Sparse<T> tmp (*this);
   --rep->count;
   rep = new typename Sparse<T>::SparseRep (nr, nc, nel);
 
-  for (octave_idx_type i = 0; i < tmp.cidx(c); i++)
+  for (octave_idx_type i = 0; i < tmp.cidx (c); i++)
     {
-      data(i) = tmp.data(i);
-      ridx(i) = tmp.ridx(i);
+      data (i) = tmp.data (i);
+      ridx (i) = tmp.ridx (i);
     }
   for (octave_idx_type i = 0; i < c + 1; i++)
-    cidx(i) = tmp.cidx(i);
+    cidx (i) = tmp.cidx (i);
 
-  octave_idx_type ii = cidx(c);
+  octave_idx_type ii = cidx (c);
 
   for (octave_idx_type i = c; i < c + a_cols; i++)
     {
       octave_quit ();
 
-      for (octave_idx_type j = tmp.cidx(i); j < tmp.cidx(i+1); j++)
-        if (tmp.ridx(j) < r)
+      for (octave_idx_type j = tmp.cidx (i); j < tmp.cidx (i+1); j++)
+        if (tmp.ridx (j) < r)
           {
-            data(ii) = tmp.data(j);
-            ridx(ii++) = tmp.ridx(j);
+            data (ii) = tmp.data (j);
+            ridx (ii++) = tmp.ridx (j);
           }
 
       octave_quit ();
 
-      for (octave_idx_type j = a.cidx(i-c); j < a.cidx(i-c+1); j++)
+      for (octave_idx_type j = a.cidx (i-c); j < a.cidx (i-c+1); j++)
         {
-          data(ii) = a.data(j);
-          ridx(ii++) = r + a.ridx(j);
+          data (ii) = a.data (j);
+          ridx (ii++) = r + a.ridx (j);
         }
 
       octave_quit ();
 
-      for (octave_idx_type j = tmp.cidx(i); j < tmp.cidx(i+1); j++)
-        if (tmp.ridx(j) >= r + a_rows)
+      for (octave_idx_type j = tmp.cidx (i); j < tmp.cidx (i+1); j++)
+        if (tmp.ridx (j) >= r + a_rows)
           {
-            data(ii) = tmp.data(j);
-            ridx(ii++) = tmp.ridx(j);
+            data (ii) = tmp.data (j);
+            ridx (ii++) = tmp.ridx (j);
           }
 
-      cidx(i+1) = ii;
+      cidx (i+1) = ii;
     }
 
   for (octave_idx_type i = c + a_cols; i < nc; i++)
     {
-      for (octave_idx_type j = tmp.cidx(i); j < tmp.cidx(i+1); j++)
+      for (octave_idx_type j = tmp.cidx (i); j < tmp.cidx (i+1); j++)
         {
-          data(ii) = tmp.data(j);
-          ridx(ii++) = tmp.ridx(j);
+          data (ii) = tmp.data (j);
+          ridx (ii++) = tmp.ridx (j);
         }
-      cidx(i+1) = ii;
+      cidx (i+1) = ii;
     }
 
   return *this;
@@ -1100,7 +1101,7 @@
   // retval.xcidx[1:nr] holds row entry *start* offsets for rows 0:(nr-1)
 
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type k = cidx(j); k < cidx(j+1); k++)
+    for (octave_idx_type k = cidx (j); k < cidx (j+1); k++)
       {
         octave_idx_type q = retval.xcidx (ridx (k) + 1)++;
         retval.xridx (q) = j;
@@ -1170,7 +1171,7 @@
           copy_or_memcpy (li, tmp.ridx (), xridx ());
           copy_or_memcpy (nz - ui, tmp.data () + ui, xdata () + li);
           mx_inline_sub (nz - ui, xridx () + li, tmp.ridx () + ui, ub - lb);
-          xcidx(1) = nz_new;
+          xcidx (1) = nz_new;
         }
       else
         {
@@ -1181,11 +1182,11 @@
           octave_idx_type sl = sidx.length (nel), nz_new = 0, j = 0;
           for (octave_idx_type i = 0; i < nz; i++)
             {
-              octave_idx_type r = tmp.ridx(i);
+              octave_idx_type r = tmp.ridx (i);
               for (;j < sl && sj[j] < r; j++) ;
               if (j == sl || sj[j] > r)
                 {
-                  data_new[nz_new] = tmp.data(i);
+                  data_new[nz_new] = tmp.data (i);
                   ridx_new[nz_new++] = r - j;
                 }
             }
@@ -1193,7 +1194,7 @@
           *this = Sparse<T> (nr - sl, 1, nz_new);
           copy_or_memcpy (nz_new, ridx_new, ridx ());
           copy_or_memcpy (nz_new, data_new, xdata ());
-          xcidx(1) = nz_new;
+          xcidx (1) = nz_new;
         }
     }
   else if (nr == 1)
@@ -1203,7 +1204,7 @@
       if (idx.is_cont_range (nc, lb, ub))
         {
           const Sparse<T> tmp = *this;
-          octave_idx_type lbi = tmp.cidx(lb), ubi = tmp.cidx(ub), new_nz = nz - (ubi - lbi);
+          octave_idx_type lbi = tmp.cidx (lb), ubi = tmp.cidx (ub), new_nz = nz - (ubi - lbi);
           *this = Sparse<T> (1, nc - (ub - lb), new_nz);
           copy_or_memcpy (lbi, tmp.data (), data ());
           copy_or_memcpy (nz - ubi, tmp.data () + ubi, xdata () + lbi);
@@ -1373,15 +1374,15 @@
 
           for (octave_idx_type i = 0; i < nc; i++)
             {
-              for (octave_idx_type j = cidx(i); j < cidx(i+1); j++)
+              for (octave_idx_type j = cidx (i); j < cidx (i+1); j++)
                 {
-                  retval.xdata(j) = data(j);
-                  retval.xridx(j) = ridx(j) + i * nr;
+                  retval.xdata (j) = data (j);
+                  retval.xridx (j) = ridx (j) + i * nr;
                 }
             }
 
-          retval.xcidx(0) = 0;
-          retval.xcidx(1) = nz;
+          retval.xcidx (0) = 0;
+          retval.xcidx (1) = nz;
         }
     }
   else if (idx.extent (nel) > nel)
@@ -1404,7 +1405,7 @@
       // then want to make a dense matrix with sparse
       // representation. Ok, we'll do it, but you deserve what
       // you get!!
-      retval = Sparse<T> (idx_dims(0), idx_dims(1), nz ? data(0) : T ());
+      retval = Sparse<T> (idx_dims(0), idx_dims(1), nz ? data (0) : T ());
     }
   else if (nc == 1)
     {
@@ -1415,8 +1416,8 @@
         {
           // Scalar index - just a binary lookup.
           octave_idx_type i = lblookup (ridx (), nz, idx(0));
-          if (i < nz && ridx(i) == idx(0))
-            retval = Sparse (1, 1, data(i));
+          if (i < nz && ridx (i) == idx(0))
+            retval = Sparse (1, 1, data (i));
           else
             retval = Sparse (1, 1);
         }
@@ -1431,7 +1432,7 @@
           retval = Sparse<T> (ub - lb, 1, nz_new);
           copy_or_memcpy (nz_new, data () + li, retval.data ());
           mx_inline_sub (nz_new, retval.xridx (), ridx () + li, lb);
-          retval.xcidx(1) = nz_new;
+          retval.xcidx (1) = nz_new;
         }
       else if (idx.is_permutation (nel) && idx.is_vector ())
         {
@@ -1477,15 +1478,15 @@
               for (octave_idx_type i = 0; i < new_nr; i++)
                 {
                   octave_idx_type l = lidx(i, j);
-                  if (l < nz && ridx(l) == idxa(i, j))
+                  if (l < nz && ridx (l) == idxa(i, j))
                     nzj++;
                   else
                     lidx(i, j) = nz;
                 }
-              retval.xcidx(j+1) = retval.xcidx(j) + nzj;
+              retval.xcidx (j+1) = retval.xcidx (j) + nzj;
             }
 
-          retval.change_capacity (retval.xcidx(new_nc));
+          retval.change_capacity (retval.xcidx (new_nc));
 
           // Copy data and set row indices.
           octave_idx_type k = 0;
@@ -1495,8 +1496,8 @@
                 octave_idx_type l = lidx(i, j);
                 if (l < nz)
                   {
-                    retval.data(k) = data(l);
-                    retval.xridx(k++) = i;
+                    retval.data (k) = data (l);
+                    retval.xridx (k++) = i;
                   }
               }
         }
@@ -1505,11 +1506,11 @@
     {
       octave_idx_type lb, ub;
       if (idx.is_scalar ())
-        retval = Sparse<T> (1, 1, elem(0, idx(0)));
+        retval = Sparse<T> (1, 1, elem (0, idx(0)));
       else if (idx.is_cont_range (nel, lb, ub))
         {
           // Special-case a contiguous range.
-          octave_idx_type lbi = cidx(lb), ubi = cidx(ub), new_nz = ubi - lbi;
+          octave_idx_type lbi = cidx (lb), ubi = cidx (ub), new_nz = ubi - lbi;
           retval = Sparse<T> (1, ub - lb, new_nz);
           copy_or_memcpy (new_nz, data () + lbi, retval.data ());
           fill_or_memset (new_nz, static_cast<octave_idx_type> (0), retval.ridx ());
@@ -1583,7 +1584,7 @@
       else if (idx_j.is_cont_range (nc, lb, ub))
         {
           // Special-case a contiguous range.
-          octave_idx_type lbi = cidx(lb), ubi = cidx(ub), new_nz = ubi - lbi;
+          octave_idx_type lbi = cidx (lb), ubi = cidx (ub), new_nz = ubi - lbi;
           retval = Sparse<T> (nr, ub - lb, new_nz);
           copy_or_memcpy (new_nz, data () + lbi, retval.data ());
           copy_or_memcpy (new_nz, ridx () + lbi, retval.ridx ());
@@ -1596,7 +1597,7 @@
           for (octave_idx_type j = 0; j < m; j++)
             {
               octave_idx_type jj = idx_j(j);
-              retval.xcidx(j+1) = retval.xcidx(j) + (cidx(jj+1) - cidx(jj));
+              retval.xcidx (j+1) = retval.xcidx (j) + (cidx (jj+1) - cidx (jj));
             }
 
           retval.change_capacity (retval.xcidx (m));
@@ -1604,8 +1605,8 @@
           // Copy data & indices.
           for (octave_idx_type j = 0; j < m; j++)
             {
-              octave_idx_type ljj = cidx(idx_j(j));
-              octave_idx_type lj = retval.xcidx(j), nzj = retval.xcidx(j+1) - lj;
+              octave_idx_type ljj = cidx (idx_j(j));
+              octave_idx_type lj = retval.xcidx (j), nzj = retval.xcidx (j+1) - lj;
               copy_or_memcpy (nzj, data () + ljj, retval.data () + lj);
               copy_or_memcpy (nzj, ridx () + ljj, retval.ridx () + lj);
             }
@@ -1618,7 +1619,7 @@
 
       // If nr == 1 then the vector indexing will return a column vector!!
       if (nr == 1)
-        retval.transpose();
+        retval.transpose ();
     }
   else if (idx_i.is_scalar ())
     {
@@ -1628,28 +1629,28 @@
       for (octave_idx_type j = 0; j < m; j++)
         {
           octave_quit ();
-          octave_idx_type jj = idx_j(j), lj = cidx(jj), nzj = cidx(jj+1) - cidx(jj);
+          octave_idx_type jj = idx_j(j), lj = cidx (jj), nzj = cidx (jj+1) - cidx (jj);
           // Scalar index - just a binary lookup.
           octave_idx_type i = lblookup (ridx () + lj, nzj, ii);
-          if (i < nzj && ridx(i+lj) == ii)
+          if (i < nzj && ridx (i+lj) == ii)
             {
               ij[j] = i + lj;
-              retval.xcidx(j+1) = retval.xcidx(j) + 1;
+              retval.xcidx (j+1) = retval.xcidx (j) + 1;
             }
           else
-            retval.xcidx(j+1) = retval.xcidx(j);
+            retval.xcidx (j+1) = retval.xcidx (j);
         }
 
-      retval.change_capacity (retval.xcidx(m));
+      retval.change_capacity (retval.xcidx (m));
 
       // Copy data, adjust row indices.
       for (octave_idx_type j = 0; j < m; j++)
         {
-          octave_idx_type i = retval.xcidx(j);
-          if (retval.xcidx(j+1) > i)
+          octave_idx_type i = retval.xcidx (j);
+          if (retval.xcidx (j+1) > i)
             {
-              retval.xridx(i) = 0;
-              retval.xdata(i) = data(ij[j]);
+              retval.xridx (i) = 0;
+              retval.xdata (i) = data (ij[j]);
             }
         }
     }
@@ -1661,15 +1662,15 @@
       for (octave_idx_type j = 0; j < m; j++)
         {
           octave_quit ();
-          octave_idx_type jj = idx_j(j), lj = cidx(jj), nzj = cidx(jj+1) - cidx(jj);
+          octave_idx_type jj = idx_j(j), lj = cidx (jj), nzj = cidx (jj+1) - cidx (jj);
           octave_idx_type lij, uij;
           // Lookup indices.
           li[j] = lij = lblookup (ridx () + lj, nzj, lb) + lj;
           ui[j] = uij = lblookup (ridx () + lj, nzj, ub) + lj;
-          retval.xcidx(j+1) = retval.xcidx(j) + ui[j] - li[j];
+          retval.xcidx (j+1) = retval.xcidx (j) + ui[j] - li[j];
         }
 
-      retval.change_capacity (retval.xcidx(m));
+      retval.change_capacity (retval.xcidx (m));
 
       // Copy data, adjust row indices.
       for (octave_idx_type j = 0, k = 0; j < m; j++)
@@ -1677,8 +1678,8 @@
           octave_quit ();
           for (octave_idx_type i = li[j]; i < ui[j]; i++)
             {
-              retval.xdata(k) = data(i);
-              retval.xridx(k++) = ridx(i) - lb;
+              retval.xdata (k) = data (i);
+              retval.xridx (k++) = ridx (i) - lb;
             }
         }
     }
@@ -1690,7 +1691,7 @@
       for (octave_idx_type j = 0; j < m; j++)
         {
           octave_idx_type jj = idx_j(j);
-          retval.xcidx(j+1) = retval.xcidx(j) + (cidx(jj+1) - cidx(jj));
+          retval.xcidx (j+1) = retval.xcidx (j) + (cidx (jj+1) - cidx (jj));
         }
 
       retval.change_capacity (retval.xcidx (m));
@@ -1703,12 +1704,12 @@
           for (octave_idx_type j = 0; j < m; j++)
             {
               octave_quit ();
-              octave_idx_type jj = idx_j(j), lj = cidx(jj), nzj = cidx(jj+1) - cidx(jj);
-              octave_idx_type li = retval.xcidx(j), uj = lj + nzj - 1;
+              octave_idx_type jj = idx_j(j), lj = cidx (jj), nzj = cidx (jj+1) - cidx (jj);
+              octave_idx_type li = retval.xcidx (j), uj = lj + nzj - 1;
               for (octave_idx_type i = 0; i < nzj; i++)
                 {
-                  retval.xdata(li + i) = data(uj - i); // Copy in reverse order.
-                  retval.xridx(li + i) = nr - 1 - ridx(uj - i); // Ditto with transform.
+                  retval.xdata (li + i) = data (uj - i); // Copy in reverse order.
+                  retval.xridx (li + i) = nr - 1 - ridx (uj - i); // Ditto with transform.
                 }
             }
         }
@@ -1725,11 +1726,11 @@
           for (octave_idx_type j = 0; j < m; j++)
             {
               octave_quit ();
-              octave_idx_type jj = idx_j(j), lj = cidx(jj), nzj = cidx(jj+1) - cidx(jj);
-              octave_idx_type li = retval.xcidx(j);
+              octave_idx_type jj = idx_j(j), lj = cidx (jj), nzj = cidx (jj+1) - cidx (jj);
+              octave_idx_type li = retval.xcidx (j);
               // Scatter the column, transform indices.
               for (octave_idx_type i = 0; i < nzj; i++)
-                scb[rri[li + i] = iinv[ridx(lj + i)]] = data(lj + i);
+                scb[rri[li + i] = iinv[ridx (lj + i)]] = data (lj + i);
 
               octave_quit ();
 
@@ -1738,7 +1739,7 @@
 
               // Gather.
               for (octave_idx_type i = 0; i < nzj; i++)
-                retval.xdata(li + i) = scb[rri[li + i]];
+                retval.xdata (li + i) = scb[rri[li + i]];
             }
         }
 
@@ -1846,7 +1847,7 @@
                   copy_or_memcpy (nz - ui, tmp.ridx () + ui, ridx () + li + rnz);
                 }
 
-              cidx(1) = new_nz;
+              cidx (1) = new_nz;
             }
           else if (idx.is_range () && idx.increment () == -1)
             {
@@ -1866,7 +1867,7 @@
                   octave_idx_type iidx = idx(i);
                   octave_idx_type li = lblookup (ri, nz, iidx);
                   if (li != nz && ri[li] == iidx)
-                    xdata(li) = T();
+                    xdata (li) = T ();
                 }
 
               maybe_compress (true);
@@ -1985,7 +1986,7 @@
           else if (idx_j.is_cont_range (nc, lb, ub))
             {
               // Special-case a contiguous range.
-              octave_idx_type li = cidx(lb), ui = cidx(ub);
+              octave_idx_type li = cidx (lb), ui = cidx (ub);
               octave_idx_type rnz = rhs.nnz (), new_nz = nz - (ui - li) + rnz;
 
               if (new_nz >= nz && new_nz <= capacity ())
@@ -2051,36 +2052,36 @@
 
               // Assemble column lengths.
               for (octave_idx_type i = 0; i < nc; i++)
-                xcidx(i+1) = tmp.cidx(i+1) - tmp.cidx(i);
+                xcidx (i+1) = tmp.cidx (i+1) - tmp.cidx (i);
 
               for (octave_idx_type i = 0; i < m; i++)
                 {
                   octave_idx_type j =idx_j(i);
                   jsav[j] = i;
-                  xcidx(j+1) = rhs.cidx(i+1) - rhs.cidx(i);
+                  xcidx (j+1) = rhs.cidx (i+1) - rhs.cidx (i);
                 }
 
               // Make cumulative.
               for (octave_idx_type i = 0; i < nc; i++)
-                xcidx(i+1) += xcidx(i);
+                xcidx (i+1) += xcidx (i);
 
               change_capacity (nnz ());
 
               // Merge columns.
               for (octave_idx_type i = 0; i < nc; i++)
                 {
-                  octave_idx_type l = xcidx(i), u = xcidx(i+1), j = jsav[i];
+                  octave_idx_type l = xcidx (i), u = xcidx (i+1), j = jsav[i];
                   if (j >= 0)
                     {
                       // from rhs
-                      octave_idx_type k = rhs.cidx(j);
+                      octave_idx_type k = rhs.cidx (j);
                       copy_or_memcpy (u - l, rhs.data () + k, xdata () + l);
                       copy_or_memcpy (u - l, rhs.ridx () + k, xridx () + l);
                     }
                   else
                     {
                       // original
-                      octave_idx_type k = tmp.cidx(i);
+                      octave_idx_type k = tmp.cidx (i);
                       copy_or_memcpy (u - l, tmp.data () + k, xdata () + l);
                       copy_or_memcpy (u - l, tmp.ridx () + k, xridx () + l);
                     }
@@ -2183,26 +2184,26 @@
 
   for (octave_idx_type j = 0; j < nc; j++)
     {
-      octave_idx_type ns = mcidx [j + 1] - mcidx [j];
+      octave_idx_type ns = mcidx[j + 1] - mcidx[j];
       lsort.sort (v, ns);
 
       octave_idx_type i;
       if (mode == ASCENDING)
         {
           for (i = 0; i < ns; i++)
-            if (sparse_ascending_compare<T> (static_cast<T> (0), v [i]))
+            if (sparse_ascending_compare<T> (static_cast<T> (0), v[i]))
               break;
         }
       else
         {
           for (i = 0; i < ns; i++)
-            if (sparse_descending_compare<T> (static_cast<T> (0), v [i]))
+            if (sparse_descending_compare<T> (static_cast<T> (0), v[i]))
               break;
         }
       for (octave_idx_type k = 0; k < i; k++)
-        mridx [k] = k;
+        mridx[k] = k;
       for (octave_idx_type k = i; k < ns; k++)
-        mridx [k] = k - ns + nr;
+        mridx[k] = k - ns + nr;
 
       v += ns;
       mridx += ns;
@@ -2255,7 +2256,7 @@
 
   for (octave_idx_type j = 0; j < nc; j++)
     {
-      octave_idx_type ns = mcidx [j + 1] - mcidx [j];
+      octave_idx_type ns = mcidx[j + 1] - mcidx[j];
       octave_idx_type offset = j * nr;
 
       if (ns == 0)
@@ -2296,14 +2297,14 @@
 
           for (octave_idx_type k = 0; k < i; k++)
             {
-              sidx (k + offset) = vi [k];
-              mridx [k] = k;
+              sidx (k + offset) = vi[k];
+              mridx[k] = k;
             }
 
           for (octave_idx_type k = i; k < ns; k++)
             {
-              sidx (k - ns + nr + offset) = vi [k];
-              mridx [k] = k - ns + nr;
+              sidx (k - ns + nr + offset) = vi[k];
+              mridx[k] = k - ns + nr;
             }
 
           v += ns;
@@ -2437,12 +2438,12 @@
 
               for (octave_idx_type j = 0; j < nnc; j++)
                 {
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
                     {
                       d.xdata (i) = data (i);
                       d.xridx (i) = j + roff;
                     }
-                  d.xcidx (j + coff + 1) = cidx(j+1);
+                  d.xcidx (j + coff + 1) = cidx (j+1);
                 }
 
               for (octave_idx_type i = nnc + coff + 1; i < n + 1; i++)
@@ -2459,7 +2460,7 @@
           if (nnz () > 0)
             {
               octave_idx_type ii = 0;
-              octave_idx_type ir = ridx(0);
+              octave_idx_type ir = ridx (0);
 
               for (octave_idx_type i = 0; i < coff+1; i++)
                 d.xcidx (i) = 0;
@@ -2545,17 +2546,17 @@
                 if (spi.is_empty ())
                   continue;
 
-                octave_idx_type kl = spi.cidx(j), ku = spi.cidx(j+1);
+                octave_idx_type kl = spi.cidx (j), ku = spi.cidx (j+1);
                 for (octave_idx_type k = kl; k < ku; k++, l++)
                   {
-                    retval.xridx(l) = spi.ridx(k) + rcum;
-                    retval.xdata(l) = spi.data(k);
+                    retval.xridx (l) = spi.ridx (k) + rcum;
+                    retval.xdata (l) = spi.data (k);
                   }
 
                 rcum += spi.rows ();
               }
 
-            retval.xcidx(j+1) = l;
+            retval.xcidx (j+1) = l;
           }
 
         break;
@@ -2589,21 +2590,21 @@
 Array<T>
 Sparse<T>::array_value () const
 {
-  NoAlias< Array<T> > retval (dims (), T());
+  NoAlias< Array<T> > retval (dims (), T ());
   if (rows () == 1)
     {
       octave_idx_type i = 0;
       for (octave_idx_type j = 0, nc = cols (); j < nc; j++)
         {
-          if (cidx(j+1) > i)
+          if (cidx (j+1) > i)
             retval(j) = data (i++);
         }
     }
   else
     {
       for (octave_idx_type j = 0, nc = cols (); j < nc; j++)
-        for (octave_idx_type i = cidx(j), iu = cidx(j+1); i < iu; i++)
-          retval (ridx(i), j) = data (i);
+        for (octave_idx_type i = cidx (j), iu = cidx (j+1); i < iu; i++)
+          retval(ridx (i), j) = data (i);
     }
 
   return retval;
@@ -2613,7 +2614,7 @@
  * Tests
  *
 
-%!function x = set_slice(x, dim, slice, arg)
+%!function x = set_slice (x, dim, slice, arg)
 %!  switch dim
 %!    case 11
 %!      x(slice) = 2;
@@ -2622,151 +2623,151 @@
 %!    case 22
 %!      x(:, slice) = 2;
 %!    otherwise
-%!      error("invalid dim, '%d'", dim);
+%!      error ("invalid dim, '%d'", dim);
 %!  endswitch
-%! endfunction
+%!endfunction
 
-%!function x = set_slice2(x, dim, slice)
+%!function x = set_slice2 (x, dim, slice)
 %!  switch dim
 %!    case 11
-%!      x(slice) = 2 * ones (size(slice));
+%!      x(slice) = 2 * ones (size (slice));
 %!    case 21
-%!      x(slice, :) = 2 * ones (length(slice), columns (x));
+%!      x(slice, :) = 2 * ones (length (slice), columns (x));
 %!    case 22
-%!      x(:, slice) = 2 * ones (rows (x), length(slice));
+%!      x(:, slice) = 2 * ones (rows (x), length (slice));
 %!    otherwise
-%!      error("invalid dim, '%d'", dim);
+%!      error ("invalid dim, '%d'", dim);
 %!  endswitch
-%! endfunction
+%!endfunction
 
-%!function test_sparse_slice(size, dim, slice)
-%!  x = ones(size);
-%!  s = set_slice(sparse(x), dim, slice);
-%!  f = set_slice(x, dim, slice);
-%!  assert (nnz(s), nnz(f));
-%!  assert(full(s), f);
-%!  s = set_slice2(sparse(x), dim, slice);
-%!  f = set_slice2(x, dim, slice);
-%!  assert (nnz(s), nnz(f));
-%!  assert(full(s), f);
-%! endfunction
+%!function test_sparse_slice (size, dim, slice)
+%!  x = ones (size);
+%!  s = set_slice (sparse (x), dim, slice);
+%!  f = set_slice (x, dim, slice);
+%!  assert (nnz (s), nnz (f));
+%!  assert (full (s), f);
+%!  s = set_slice2 (sparse (x), dim, slice);
+%!  f = set_slice2 (x, dim, slice);
+%!  assert (nnz (s), nnz (f));
+%!  assert (full (s), f);
+%!endfunction
 
 #### 1d indexing
 
 ## size = [2 0]
-%!test test_sparse_slice([2 0], 11, []);
-%!assert(set_slice(sparse(ones([2 0])), 11, 1), sparse([2 0]'));  # sparse different from full
-%!assert(set_slice(sparse(ones([2 0])), 11, 2), sparse([0 2]'));  # sparse different from full
-%!assert(set_slice(sparse(ones([2 0])), 11, 3), sparse([0 0; 2 0]'));  # sparse different from full
-%!assert(set_slice(sparse(ones([2 0])), 11, 4), sparse([0 0; 0 2]'));  # sparse different from full
+%!test test_sparse_slice ([2 0], 11, []);
+%!assert (set_slice (sparse (ones ([2 0])), 11, 1), sparse ([2 0]'))  # sparse different from full
+%!assert (set_slice (sparse (ones ([2 0])), 11, 2), sparse ([0 2]'))  # sparse different from full
+%!assert (set_slice (sparse (ones ([2 0])), 11, 3), sparse ([0 0; 2 0]'))  # sparse different from full
+%!assert (set_slice (sparse (ones ([2 0])), 11, 4), sparse ([0 0; 0 2]'))  # sparse different from full
 
 ## size = [0 2]
-%!test test_sparse_slice([0 2], 11, []);
-%!assert(set_slice(sparse(ones([0 2])), 11, 1), sparse([2 0]));  # sparse different from full
-%!test test_sparse_slice([0 2], 11, 2);
-%!test test_sparse_slice([0 2], 11, 3);
-%!test test_sparse_slice([0 2], 11, 4);
-%!test test_sparse_slice([0 2], 11, [4, 4]);
+%!test test_sparse_slice ([0 2], 11, []);
+%!assert (set_slice (sparse (ones ([0 2])), 11, 1), sparse ([2 0]))  # sparse different from full
+%!test test_sparse_slice ([0 2], 11, 2);
+%!test test_sparse_slice ([0 2], 11, 3);
+%!test test_sparse_slice ([0 2], 11, 4);
+%!test test_sparse_slice ([0 2], 11, [4, 4]);
 
 ## size = [2 1]
-%!test test_sparse_slice([2 1], 11, []);
-%!test test_sparse_slice([2 1], 11, 1);
-%!test test_sparse_slice([2 1], 11, 2);
-%!test test_sparse_slice([2 1], 11, 3);
-%!test test_sparse_slice([2 1], 11, 4);
-%!test test_sparse_slice([2 1], 11, [4, 4]);
+%!test test_sparse_slice ([2 1], 11, []);
+%!test test_sparse_slice ([2 1], 11, 1);
+%!test test_sparse_slice ([2 1], 11, 2);
+%!test test_sparse_slice ([2 1], 11, 3);
+%!test test_sparse_slice ([2 1], 11, 4);
+%!test test_sparse_slice ([2 1], 11, [4, 4]);
 
 ## size = [1 2]
-%!test test_sparse_slice([1 2], 11, []);
-%!test test_sparse_slice([1 2], 11, 1);
-%!test test_sparse_slice([1 2], 11, 2);
-%!test test_sparse_slice([1 2], 11, 3);
-%!test test_sparse_slice([1 2], 11, 4);
-%!test test_sparse_slice([1 2], 11, [4, 4]);
+%!test test_sparse_slice ([1 2], 11, []);
+%!test test_sparse_slice ([1 2], 11, 1);
+%!test test_sparse_slice ([1 2], 11, 2);
+%!test test_sparse_slice ([1 2], 11, 3);
+%!test test_sparse_slice ([1 2], 11, 4);
+%!test test_sparse_slice ([1 2], 11, [4, 4]);
 
 ## size = [2 2]
-%!test test_sparse_slice([2 2], 11, []);
-%!test test_sparse_slice([2 2], 11, 1);
-%!test test_sparse_slice([2 2], 11, 2);
-%!test test_sparse_slice([2 2], 11, 3);
-%!test test_sparse_slice([2 2], 11, 4);
-%!test test_sparse_slice([2 2], 11, [4, 4]);
+%!test test_sparse_slice ([2 2], 11, []);
+%!test test_sparse_slice ([2 2], 11, 1);
+%!test test_sparse_slice ([2 2], 11, 2);
+%!test test_sparse_slice ([2 2], 11, 3);
+%!test test_sparse_slice ([2 2], 11, 4);
+%!test test_sparse_slice ([2 2], 11, [4, 4]);
 # These 2 errors are the same as in the full case
-%!error id=Octave:invalid-resize set_slice(sparse(ones([2 2])), 11, 5);
-%!error id=Octave:invalid-resize set_slice(sparse(ones([2 2])), 11, 6);
+%!error id=Octave:invalid-resize set_slice (sparse (ones ([2 2])), 11, 5)
+%!error id=Octave:invalid-resize set_slice (sparse (ones ([2 2])), 11, 6)
 
 
 #### 2d indexing
 
 ## size = [2 0]
-%!test test_sparse_slice([2 0], 21, []);
-%!test test_sparse_slice([2 0], 21, 1);
-%!test test_sparse_slice([2 0], 21, 2);
-%!test test_sparse_slice([2 0], 21, [2,2]);
-%!assert(set_slice(sparse(ones([2 0])), 21, 3), sparse(3,0));
-%!assert(set_slice(sparse(ones([2 0])), 21, 4), sparse(4,0));
-%!test test_sparse_slice([2 0], 22, []);
-%!test test_sparse_slice([2 0], 22, 1);
-%!test test_sparse_slice([2 0], 22, 2);
-%!test test_sparse_slice([2 0], 22, [2,2]);
-%!assert(set_slice(sparse(ones([2 0])), 22, 3), sparse([0 0 2;0 0 2]));  # sparse different from full
-%!assert(set_slice(sparse(ones([2 0])), 22, 4), sparse([0 0 0 2;0 0 0 2]));  # sparse different from full
+%!test test_sparse_slice ([2 0], 21, []);
+%!test test_sparse_slice ([2 0], 21, 1);
+%!test test_sparse_slice ([2 0], 21, 2);
+%!test test_sparse_slice ([2 0], 21, [2,2]);
+%!assert (set_slice (sparse (ones ([2 0])), 21, 3), sparse (3,0))
+%!assert (set_slice (sparse (ones ([2 0])), 21, 4), sparse (4,0))
+%!test test_sparse_slice ([2 0], 22, []);
+%!test test_sparse_slice ([2 0], 22, 1);
+%!test test_sparse_slice ([2 0], 22, 2);
+%!test test_sparse_slice ([2 0], 22, [2,2]);
+%!assert (set_slice (sparse (ones ([2 0])), 22, 3), sparse ([0 0 2;0 0 2]))  # sparse different from full
+%!assert (set_slice (sparse (ones ([2 0])), 22, 4), sparse ([0 0 0 2;0 0 0 2]))  # sparse different from full
 
 ## size = [0 2]
-%!test test_sparse_slice([0 2], 21, []);
-%!test test_sparse_slice([0 2], 21, 1);
-%!test test_sparse_slice([0 2], 21, 2);
-%!test test_sparse_slice([0 2], 21, [2,2]);
-%!assert(set_slice(sparse(ones([0 2])), 21, 3), sparse([0 0;0 0;2 2]));  # sparse different from full
-%!assert(set_slice(sparse(ones([0 2])), 21, 4), sparse([0 0;0 0;0 0;2 2]));  # sparse different from full
-%!test test_sparse_slice([0 2], 22, []);
-%!test test_sparse_slice([0 2], 22, 1);
-%!test test_sparse_slice([0 2], 22, 2);
-%!test test_sparse_slice([0 2], 22, [2,2]);
-%!assert(set_slice(sparse(ones([0 2])), 22, 3), sparse(0,3));
-%!assert(set_slice(sparse(ones([0 2])), 22, 4), sparse(0,4));
+%!test test_sparse_slice ([0 2], 21, []);
+%!test test_sparse_slice ([0 2], 21, 1);
+%!test test_sparse_slice ([0 2], 21, 2);
+%!test test_sparse_slice ([0 2], 21, [2,2]);
+%!assert (set_slice (sparse (ones ([0 2])), 21, 3), sparse ([0 0;0 0;2 2]))  # sparse different from full
+%!assert (set_slice (sparse (ones ([0 2])), 21, 4), sparse ([0 0;0 0;0 0;2 2]))  # sparse different from full
+%!test test_sparse_slice ([0 2], 22, []);
+%!test test_sparse_slice ([0 2], 22, 1);
+%!test test_sparse_slice ([0 2], 22, 2);
+%!test test_sparse_slice ([0 2], 22, [2,2]);
+%!assert (set_slice (sparse (ones ([0 2])), 22, 3), sparse (0,3))
+%!assert (set_slice (sparse (ones ([0 2])), 22, 4), sparse (0,4))
 
 ## size = [2 1]
-%!test test_sparse_slice([2 1], 21, []);
-%!test test_sparse_slice([2 1], 21, 1);
-%!test test_sparse_slice([2 1], 21, 2);
-%!test test_sparse_slice([2 1], 21, [2,2]);
-%!test test_sparse_slice([2 1], 21, 3);
-%!test test_sparse_slice([2 1], 21, 4);
-%!test test_sparse_slice([2 1], 22, []);
-%!test test_sparse_slice([2 1], 22, 1);
-%!test test_sparse_slice([2 1], 22, 2);
-%!test test_sparse_slice([2 1], 22, [2,2]);
-%!test test_sparse_slice([2 1], 22, 3);
-%!test test_sparse_slice([2 1], 22, 4);
+%!test test_sparse_slice ([2 1], 21, []);
+%!test test_sparse_slice ([2 1], 21, 1);
+%!test test_sparse_slice ([2 1], 21, 2);
+%!test test_sparse_slice ([2 1], 21, [2,2]);
+%!test test_sparse_slice ([2 1], 21, 3);
+%!test test_sparse_slice ([2 1], 21, 4);
+%!test test_sparse_slice ([2 1], 22, []);
+%!test test_sparse_slice ([2 1], 22, 1);
+%!test test_sparse_slice ([2 1], 22, 2);
+%!test test_sparse_slice ([2 1], 22, [2,2]);
+%!test test_sparse_slice ([2 1], 22, 3);
+%!test test_sparse_slice ([2 1], 22, 4);
 
 ## size = [1 2]
-%!test test_sparse_slice([1 2], 21, []);
-%!test test_sparse_slice([1 2], 21, 1);
-%!test test_sparse_slice([1 2], 21, 2);
-%!test test_sparse_slice([1 2], 21, [2,2]);
-%!test test_sparse_slice([1 2], 21, 3);
-%!test test_sparse_slice([1 2], 21, 4);
-%!test test_sparse_slice([1 2], 22, []);
-%!test test_sparse_slice([1 2], 22, 1);
-%!test test_sparse_slice([1 2], 22, 2);
-%!test test_sparse_slice([1 2], 22, [2,2]);
-%!test test_sparse_slice([1 2], 22, 3);
-%!test test_sparse_slice([1 2], 22, 4);
+%!test test_sparse_slice ([1 2], 21, []);
+%!test test_sparse_slice ([1 2], 21, 1);
+%!test test_sparse_slice ([1 2], 21, 2);
+%!test test_sparse_slice ([1 2], 21, [2,2]);
+%!test test_sparse_slice ([1 2], 21, 3);
+%!test test_sparse_slice ([1 2], 21, 4);
+%!test test_sparse_slice ([1 2], 22, []);
+%!test test_sparse_slice ([1 2], 22, 1);
+%!test test_sparse_slice ([1 2], 22, 2);
+%!test test_sparse_slice ([1 2], 22, [2,2]);
+%!test test_sparse_slice ([1 2], 22, 3);
+%!test test_sparse_slice ([1 2], 22, 4);
 
 ## size = [2 2]
-%!test test_sparse_slice([2 2], 21, []);
-%!test test_sparse_slice([2 2], 21, 1);
-%!test test_sparse_slice([2 2], 21, 2);
-%!test test_sparse_slice([2 2], 21, [2,2]);
-%!test test_sparse_slice([2 2], 21, 3);
-%!test test_sparse_slice([2 2], 21, 4);
-%!test test_sparse_slice([2 2], 22, []);
-%!test test_sparse_slice([2 2], 22, 1);
-%!test test_sparse_slice([2 2], 22, 2);
-%!test test_sparse_slice([2 2], 22, [2,2]);
-%!test test_sparse_slice([2 2], 22, 3);
-%!test test_sparse_slice([2 2], 22, 4);
+%!test test_sparse_slice ([2 2], 21, []);
+%!test test_sparse_slice ([2 2], 21, 1);
+%!test test_sparse_slice ([2 2], 21, 2);
+%!test test_sparse_slice ([2 2], 21, [2,2]);
+%!test test_sparse_slice ([2 2], 21, 3);
+%!test test_sparse_slice ([2 2], 21, 4);
+%!test test_sparse_slice ([2 2], 22, []);
+%!test test_sparse_slice ([2 2], 22, 1);
+%!test test_sparse_slice ([2 2], 22, 2);
+%!test test_sparse_slice ([2 2], 22, [2,2]);
+%!test test_sparse_slice ([2 2], 22, 3);
+%!test test_sparse_slice ([2 2], 22, 4);
 
 bug #35570:
 
@@ -2780,7 +2781,7 @@
 %! assert (s, sparse (magic (5)(:, [1,5])));
 
 %!test
-%! s = sparse([], [], [], 1, 1);
+%! s = sparse ([], [], [], 1, 1);
 %! s(1,:) = [];
 %! assert (s, sparse ([], [], [], 0, 1));
 
rename from liboctave/Sparse.h
rename to liboctave/array/Sparse.h
--- a/liboctave/Sparse.h
+++ b/liboctave/array/Sparse.h
@@ -71,25 +71,25 @@
     octave_idx_type ncols;
     octave_refcount<int> count;
 
-    SparseRep (void) : d (0), r (0), c (new octave_idx_type [1]), nzmx (0), nrows (0),
-                       ncols (0), count (1) { c[0] = 0; }
+    SparseRep (void)
+      : d (0), r (0), c (new octave_idx_type [1]), nzmx (0), nrows (0),
+      ncols (0), count (1)
+      {
+        c[0] = 0;
+      }
 
-    SparseRep (octave_idx_type n) : d (0), r (0), c (new octave_idx_type [n+1]), nzmx (0), nrows (n),
+    SparseRep (octave_idx_type n)
+      : d (0), r (0), c (new octave_idx_type [n+1]), nzmx (0), nrows (n),
       ncols (n), count (1)
       {
         for (octave_idx_type i = 0; i < n + 1; i++)
           c[i] = 0;
       }
 
-    SparseRep (octave_idx_type nr, octave_idx_type nc) : d (0), r (0), c (new octave_idx_type [nc+1]), nzmx (0),
-      nrows (nr), ncols (nc), count (1)
-      {
-        for (octave_idx_type i = 0; i < nc + 1; i++)
-          c[i] = 0;
-      }
-
-    SparseRep (octave_idx_type nr, octave_idx_type nc, octave_idx_type nz) : d (new T [nz]),
-      r (new octave_idx_type [nz]), c (new octave_idx_type [nc+1]), nzmx (nz), nrows (nr),
+    SparseRep (octave_idx_type nr, octave_idx_type nc, octave_idx_type nz = 0)
+      : 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)
       {
         for (octave_idx_type i = 0; i < nc + 1; i++)
@@ -97,7 +97,8 @@
       }
 
     SparseRep (const SparseRep& a)
-      : d (new T [a.nzmx]), r (new octave_idx_type [a.nzmx]), c (new octave_idx_type [a.ncols + 1]),
+      : d (new T [a.nzmx]), r (new octave_idx_type [a.nzmx]),
+      c (new octave_idx_type [a.ncols + 1]),
       nzmx (a.nzmx), nrows (a.nrows), ncols (a.ncols), count (1)
       {
         octave_idx_type nz = a.nnz ();
@@ -110,7 +111,7 @@
 
     octave_idx_type length (void) const { return nzmx; }
 
-    octave_idx_type nnz (void) const { return c [ncols]; }
+    octave_idx_type nnz (void) const { return c[ncols]; }
 
     T& elem (octave_idx_type _r, octave_idx_type _c);
 
@@ -144,17 +145,17 @@
   //--------------------------------------------------------------------
 
   void make_unique (void)
-    {
-      if (rep->count > 1)
-        {
-          SparseRep *r = new SparseRep (*rep);
+  {
+    if (rep->count > 1)
+      {
+        SparseRep *r = new SparseRep (*rep);
 
-          if (--rep->count == 0)
-            delete rep;
+        if (--rep->count == 0)
+          delete rep;
 
-          rep = r;
-        }
-    }
+        rep = r;
+      }
+  }
 
 public:
 
@@ -168,18 +169,18 @@
 private:
 
   typename Sparse<T>::SparseRep *nil_rep (void) const
-    {
-      static typename Sparse<T>::SparseRep nr;
-      return &nr;
-    }
+  {
+    static typename Sparse<T>::SparseRep nr;
+    return &nr;
+  }
 
 public:
 
   Sparse (void)
     : rep (nil_rep ()), dimensions (dim_vector(0,0))
-    {
-      rep->count++;
-    }
+  {
+    rep->count++;
+  }
 
   explicit Sparse (octave_idx_type n)
     : rep (new typename Sparse<T>::SparseRep (n)),
@@ -193,7 +194,7 @@
 
   Sparse (const dim_vector& dv, octave_idx_type nz)
     : rep (new typename Sparse<T>::SparseRep (dv(0), dv(1), nz)),
-    dimensions (dv) { }
+      dimensions (dv) { }
 
   Sparse (octave_idx_type nr, octave_idx_type nc, octave_idx_type nz)
     : rep (new typename Sparse<T>::SparseRep (nr, nc, nz)),
@@ -207,20 +208,20 @@
   template <class U>
   Sparse (const Sparse<U>& a)
     : rep (new typename Sparse<T>::SparseRep (a.rep->nrows, a.rep->ncols, a.rep->nzmx)),
-    dimensions (a.dimensions)
-    {
-      octave_idx_type nz = a.nnz ();
-      std::copy (a.rep->d, a.rep->d + nz, rep->d);
-      copy_or_memcpy (nz, a.rep->r, rep->r);
-      copy_or_memcpy (rep->ncols + 1, a.rep->c, rep->c);
-    }
+      dimensions (a.dimensions)
+  {
+    octave_idx_type nz = a.nnz ();
+    std::copy (a.rep->d, a.rep->d + nz, rep->d);
+    copy_or_memcpy (nz, a.rep->r, rep->r);
+    copy_or_memcpy (rep->ncols + 1, a.rep->c, rep->c);
+  }
 
   // No type conversion case.
   Sparse (const Sparse<T>& a)
     : rep (a.rep), dimensions (a.dimensions)
-    {
-      rep->count++;
-    }
+  {
+    rep->count++;
+  }
 
 public:
 
@@ -249,9 +250,9 @@
   // Querying the number of elements (incl. zeros) may overflow the index type,
   // so don't do it unless you really need it.
   octave_idx_type numel (void) const
-    {
-      return dimensions.safe_numel ();
-    }
+  {
+    return dimensions.safe_numel ();
+  }
 
   octave_idx_type nelem (void) const { return capacity (); }
   octave_idx_type length (void) const { return numel (); }
@@ -265,18 +266,19 @@
 
   octave_idx_type get_row_index (octave_idx_type k) { return ridx (k); }
   octave_idx_type get_col_index (octave_idx_type k)
-    {
-      octave_idx_type ret = 0;
-      while (cidx(ret+1) < k)
-        ret++;
-      return ret;
-    }
+  {
+    octave_idx_type ret = 0;
+    while (cidx (ret+1) < k)
+      ret++;
+    return ret;
+  }
 
   size_t byte_size (void) const
-    {
-      return (static_cast<size_t>(cols () + 1) * sizeof (octave_idx_type)
-              + static_cast<size_t> (capacity ()) * (sizeof (T) + sizeof (octave_idx_type)));
-    }
+  {
+    return (static_cast<size_t>(cols () + 1) * sizeof (octave_idx_type)
+            + static_cast<size_t> (capacity ())
+            * (sizeof (T) + sizeof (octave_idx_type)));
+  }
 
   dim_vector dims (void) const { return dimensions; }
 
@@ -296,145 +298,189 @@
   // No checking, even for multiple references, ever.
 
   T& xelem (octave_idx_type n)
-    {
-      octave_idx_type i = n % rows (), j = n / rows();
-      return xelem (i, j);
-    }
+  {
+    octave_idx_type i = n % rows (), j = n / rows ();
+    return xelem (i, j);
+  }
 
   T xelem (octave_idx_type n) const
-    {
-      octave_idx_type i = n % rows (), j = n / rows();
-      return xelem (i, j);
-    }
+  {
+    octave_idx_type i = n % rows (), j = n / rows ();
+    return xelem (i, j);
+  }
 
   T& xelem (octave_idx_type i, octave_idx_type j) { return rep->elem (i, j); }
-  T xelem (octave_idx_type i, octave_idx_type j) const { return rep->celem (i, j); }
+  T xelem (octave_idx_type i, octave_idx_type j) const
+  {
+    return rep->celem (i, j);
+  }
 
   T& xelem (const Array<octave_idx_type>& ra_idx)
-    { return xelem (compute_index (ra_idx)); }
+  { return xelem (compute_index (ra_idx)); }
 
   T xelem (const Array<octave_idx_type>& ra_idx) const
-    { return xelem (compute_index (ra_idx)); }
+  { return xelem (compute_index (ra_idx)); }
 
   // FIXME -- would be nice to fix this so that we don't
   // unnecessarily force a copy, but that is not so easy, and I see no
   // clean way to do it.
 
   T& checkelem (octave_idx_type n)
-    {
-      if (n < 0 || n >= numel ())
-        return range_error ("T& Sparse<T>::checkelem", n);
-      else
-        {
-          make_unique ();
-          return xelem (n);
-        }
-    }
+  {
+    if (n < 0 || n >= numel ())
+      return range_error ("T& Sparse<T>::checkelem", n);
+    else
+      {
+        make_unique ();
+        return xelem (n);
+      }
+  }
 
   T& checkelem (octave_idx_type i, octave_idx_type j)
-    {
-      if (i < 0 || j < 0 || i >= dim1 () || j >= dim2 ())
-        return range_error ("T& Sparse<T>::checkelem", i, j);
-      else
-        {
-          make_unique ();
-          return xelem (i, j);
-        }
-    }
+  {
+    if (i < 0 || j < 0 || i >= dim1 () || j >= dim2 ())
+      return range_error ("T& Sparse<T>::checkelem", i, j);
+    else
+      {
+        make_unique ();
+        return xelem (i, j);
+      }
+  }
 
   T& checkelem (const Array<octave_idx_type>& ra_idx)
-    {
-      octave_idx_type i = compute_index (ra_idx);
+  {
+    octave_idx_type i = compute_index (ra_idx);
 
-      if (i < 0)
-        return range_error ("T& Sparse<T>::checkelem", ra_idx);
-      else
-        return elem (i);
-    }
+    if (i < 0)
+      return range_error ("T& Sparse<T>::checkelem", ra_idx);
+    else
+      return elem (i);
+  }
 
   T& elem (octave_idx_type n)
-    {
-      make_unique ();
-      return xelem (n);
-    }
+  {
+    make_unique ();
+    return xelem (n);
+  }
 
   T& elem (octave_idx_type i, octave_idx_type j)
-    {
-      make_unique ();
-      return xelem (i, j);
-    }
+  {
+    make_unique ();
+    return xelem (i, j);
+  }
 
   T& elem (const Array<octave_idx_type>& ra_idx)
-    { return Sparse<T>::elem (compute_index (ra_idx)); }
+  { return Sparse<T>::elem (compute_index (ra_idx)); }
 
 #if defined (BOUNDS_CHECKING)
-  T& operator () (octave_idx_type n) { return checkelem (n); }
-  T& operator () (octave_idx_type i, octave_idx_type j) { return checkelem (i, j); }
-  T& operator () (const Array<octave_idx_type>& ra_idx) { return checkelem (ra_idx); }
+  T& operator () (octave_idx_type n)
+  {
+    return checkelem (n);
+  }
+
+  T& operator () (octave_idx_type i, octave_idx_type j)
+  {
+    return checkelem (i, j);
+  }
+
+  T& operator () (const Array<octave_idx_type>& ra_idx)
+  {
+    return checkelem (ra_idx);
+  }
+
 #else
-  T& operator () (octave_idx_type n) { return elem (n); }
-  T& operator () (octave_idx_type i, octave_idx_type j) { return elem (i, j); }
-  T& operator () (const Array<octave_idx_type>& ra_idx) { return elem (ra_idx); }
+  T& operator () (octave_idx_type n)
+  {
+    return elem (n);
+  }
+
+  T& operator () (octave_idx_type i, octave_idx_type j)
+  {
+    return elem (i, j);
+  }
+
+  T& operator () (const Array<octave_idx_type>& ra_idx)
+  {
+    return elem (ra_idx);
+  }
+
 #endif
 
   T checkelem (octave_idx_type n) const
-    {
-      if (n < 0 || n >= numel ())
-        return range_error ("T Sparse<T>::checkelem", n);
-      else
-        return xelem (n);
-    }
+  {
+    if (n < 0 || n >= numel ())
+      return range_error ("T Sparse<T>::checkelem", n);
+    else
+      return xelem (n);
+  }
 
   T checkelem (octave_idx_type i, octave_idx_type j) const
-    {
-      if (i < 0 || j < 0 || i >= dim1 () || j >= dim2 ())
-        return range_error ("T Sparse<T>::checkelem", i, j);
-      else
-        return xelem (i, j);
-    }
+  {
+    if (i < 0 || j < 0 || i >= dim1 () || j >= dim2 ())
+      return range_error ("T Sparse<T>::checkelem", i, j);
+    else
+      return xelem (i, j);
+  }
 
   T checkelem (const Array<octave_idx_type>& ra_idx) const
-    {
-      octave_idx_type i = compute_index (ra_idx);
+  {
+    octave_idx_type i = compute_index (ra_idx);
 
-      if (i < 0)
-        return range_error ("T Sparse<T>::checkelem", ra_idx);
-      else
-        return Sparse<T>::elem (i);
-    }
+    if (i < 0)
+      return range_error ("T Sparse<T>::checkelem", ra_idx);
+    else
+      return Sparse<T>::elem (i);
+  }
 
   T elem (octave_idx_type n) const { return xelem (n); }
 
   T elem (octave_idx_type i, octave_idx_type j) const { return xelem (i, j); }
 
   T elem (const Array<octave_idx_type>& ra_idx) const
-    { return Sparse<T>::elem (compute_index (ra_idx)); }
+  { return Sparse<T>::elem (compute_index (ra_idx)); }
 
 #if defined (BOUNDS_CHECKING)
   T operator () (octave_idx_type n) const { return checkelem (n); }
-  T operator () (octave_idx_type i, octave_idx_type j) const { return checkelem (i, j); }
-  T operator () (const Array<octave_idx_type>& ra_idx) const { return checkelem (ra_idx); }
+  T operator () (octave_idx_type i, octave_idx_type j) const
+  {
+    return checkelem (i, j);
+  }
+
+  T operator () (const Array<octave_idx_type>& ra_idx) const
+  {
+    return checkelem (ra_idx);
+  }
+
 #else
   T operator () (octave_idx_type n) const { return elem (n); }
-  T operator () (octave_idx_type i, octave_idx_type j) const { return elem (i, j); }
-  T operator () (const Array<octave_idx_type>& ra_idx) const { return elem (ra_idx); }
+  T operator () (octave_idx_type i, octave_idx_type j) const
+  {
+    return elem (i, j);
+  }
+
+  T operator () (const Array<octave_idx_type>& ra_idx) const
+  {
+    return elem (ra_idx);
+  }
 #endif
 
   Sparse<T> maybe_compress (bool remove_zeros = false)
-    {
-      if (remove_zeros)
-        make_unique (); // Needs to unshare because elements are removed.
+  {
+    if (remove_zeros)
+      make_unique (); // Needs to unshare because elements are removed.
 
-      rep->maybe_compress (remove_zeros);
-      return (*this);
-    }
+    rep->maybe_compress (remove_zeros);
+    return (*this);
+  }
 
   Sparse<T> reshape (const dim_vector& new_dims) const;
 
   Sparse<T> permute (const Array<octave_idx_type>& vec, bool inv = false) const;
 
   Sparse<T> ipermute (const Array<octave_idx_type>& vec) const
-    { return permute (vec, true); }
+  {
+    return permute (vec, true);
+  }
 
   void resize1 (octave_idx_type n);
 
@@ -443,11 +489,11 @@
   void resize (const dim_vector& dv);
 
   void change_capacity (octave_idx_type nz)
-    {
-      if (nz < nnz ())
-        make_unique (); // Unshare now because elements will be truncated.
-      rep->change_length (nz);
-    }
+  {
+    if (nz < nnz ())
+      make_unique (); // Unshare now because elements will be truncated.
+    rep->change_length (nz);
+  }
 
   Sparse<T>& insert (const Sparse<T>& a, octave_idx_type r, octave_idx_type c);
   Sparse<T>& insert (const Sparse<T>& a, const Array<octave_idx_type>& idx);
@@ -468,7 +514,11 @@
   T* data (void) const { return rep->d; }
 
   octave_idx_type* ridx (void) { make_unique (); return rep->r; }
-  octave_idx_type& ridx (octave_idx_type i) { make_unique (); return rep->ridx (i); }
+  octave_idx_type& ridx (octave_idx_type i)
+  {
+    make_unique (); return rep->ridx (i);
+  }
+
   octave_idx_type* xridx (void) { return rep->r; }
   octave_idx_type& xridx (octave_idx_type i) { return rep->ridx (i); }
 
@@ -477,7 +527,11 @@
   octave_idx_type* ridx (void) const { return rep->r; }
 
   octave_idx_type* cidx (void) { make_unique (); return rep->c; }
-  octave_idx_type& cidx (octave_idx_type i) { make_unique (); return rep->cidx (i); }
+  octave_idx_type& cidx (octave_idx_type i)
+  {
+    make_unique (); return rep->cidx (i);
+  }
+
   octave_idx_type* xcidx (void) { return rep->c; }
   octave_idx_type& xcidx (octave_idx_type i) { return rep->cidx (i); }
 
@@ -495,7 +549,8 @@
 
   Sparse<T> index (const idx_vector& i, bool resize_ok = false) const;
 
-  Sparse<T> index (const idx_vector& i, const idx_vector& j, bool resize_ok = false) const;
+  Sparse<T> index (const idx_vector& i, const idx_vector& j,
+                   bool resize_ok = false) const;
 
   void assign (const idx_vector& i, const Sparse<T>& rhs);
 
@@ -507,13 +562,19 @@
   // You should not use them anywhere else.
   void *mex_get_data (void) const { return const_cast<T *> (data ()); }
 
-  octave_idx_type *mex_get_ir (void) const { return const_cast<octave_idx_type *> (ridx ()); }
+  octave_idx_type *mex_get_ir (void) const
+  {
+    return const_cast<octave_idx_type *> (ridx ());
+  }
 
-  octave_idx_type *mex_get_jc (void) const { return const_cast<octave_idx_type *> (cidx ()); }
+  octave_idx_type *mex_get_jc (void) const
+  {
+    return const_cast<octave_idx_type *> (cidx ());
+  }
 
   Sparse<T> sort (octave_idx_type dim = 0, sortmode mode = ASCENDING) const;
   Sparse<T> sort (Array<octave_idx_type> &sidx, octave_idx_type dim = 0,
-                 sortmode mode = ASCENDING) const;
+                  sortmode mode = ASCENDING) const;
 
   Sparse<T> diag (octave_idx_type k = 0) const;
 
@@ -523,6 +584,35 @@
 
   Array<T> array_value (void) const;
 
+  // Generic any/all test functionality with arbitrary predicate.
+  template <class F, bool zero>
+  bool test (F fcn) const
+  {
+    return any_all_test<F, T, zero> (fcn, data (), nnz ());
+  }
+
+  // Simpler calls.
+  template <class F>
+  bool test_any (F fcn) const
+  { return test<F, false> (fcn); }
+
+  template <class F>
+  bool test_all (F fcn) const
+  { return test<F, true> (fcn); }
+
+  // Overloads for function references.
+  bool test_any (bool (&fcn) (T)) const
+  { return test<bool (&) (T), false> (fcn); }
+
+  bool test_any (bool (&fcn) (const T&)) const
+  { return test<bool (&) (const T&), false> (fcn); }
+
+  bool test_all (bool (&fcn) (T)) const
+  { return test<bool (&) (T), true> (fcn); }
+
+  bool test_all (bool (&fcn) (const T&)) const
+  { return test<bool (&) (const T&), true> (fcn); }
+
   template <class U, class F>
   Sparse<U>
   map (F fcn) const
@@ -538,11 +628,11 @@
         result = Sparse<U> (nr, nc, f_zero);
 
         for (octave_idx_type j = 0; j < nc; j++)
-          for (octave_idx_type i = cidx(j); i < cidx (j+1); i++)
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
             {
               octave_quit ();
               /* Use data instead of elem for better performance.  */
-              result.data (ridx (i) + j * nr) = fcn (data(i));
+              result.data (ridx (i) + j * nr) = fcn (data (i));
             }
 
         result.maybe_compress (true);
@@ -559,7 +649,7 @@
 
         for (octave_idx_type j = 0; j < nc; j++)
           {
-            for (octave_idx_type i = cidx(j); i < cidx (j+1); i++)
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
               {
                 U val = fcn (data (i));
                 if (val != 0.0)
@@ -648,7 +738,7 @@
           else if (jtmp > jold)
             {
               for (octave_idx_type j = jold; j < jtmp; j++)
-                a.cidx(j+1) = ii;
+                a.cidx (j+1) = ii;
             }
           else if (itmp < iold)
             {
@@ -673,7 +763,7 @@
         }
 
       for (octave_idx_type j = jold; j < nc; j++)
-        a.cidx(j+1) = ii;
+        a.cidx (j+1) = ii;
     }
 
  done:
rename from liboctave/boolMatrix.cc
rename to liboctave/array/boolMatrix.cc
rename from liboctave/boolMatrix.h
rename to liboctave/array/boolMatrix.h
--- a/liboctave/boolMatrix.h
+++ b/liboctave/array/boolMatrix.h
@@ -84,14 +84,10 @@
   friend std::istream& operator >> (std::istream& is, Matrix& a);
 #endif
 
-  void resize (octave_idx_type nr, octave_idx_type nc,
-               bool rfv = resize_fill_value ())
+  void resize (octave_idx_type nr, octave_idx_type nc, bool rfv = false)
   {
     Array<bool>::resize (dim_vector (nr, nc), rfv);
   }
-
-  static bool resize_fill_value (void) { return false; }
-
 };
 
 MM_BOOL_OP_DECLS (boolMatrix, boolMatrix, OCTAVE_API)
rename from liboctave/boolNDArray.cc
rename to liboctave/array/boolNDArray.cc
--- a/liboctave/boolNDArray.cc
+++ b/liboctave/array/boolNDArray.cc
@@ -134,6 +134,12 @@
   return Array<bool>::diag (k);
 }
 
+boolNDArray
+boolNDArray::diag (octave_idx_type m, octave_idx_type n) const
+{
+  return Array<bool>::diag (m, n);
+}
+
 NDND_BOOL_OPS (boolNDArray, boolNDArray)
 NDND_CMP_OPS (boolNDArray, boolNDArray)
 
rename from liboctave/boolNDArray.h
rename to liboctave/array/boolNDArray.h
--- a/liboctave/boolNDArray.h
+++ b/liboctave/array/boolNDArray.h
@@ -96,13 +96,12 @@
   // friend std::ostream& operator << (std::ostream& os, const NDArray& a);
   // friend std::istream& operator >> (std::istream& is, NDArray& a);
 
-  static bool resize_fill_value (void) { return false; }
-
   //  bool all_elements_are_real (void) const;
   //  bool all_integers (double& max_val, double& min_val) const;
 
   boolNDArray diag (octave_idx_type k = 0) const;
 
+  boolNDArray diag (octave_idx_type m, octave_idx_type n) const;
 };
 
 NDND_BOOL_OP_DECLS (boolNDArray, boolNDArray, OCTAVE_API)
rename from liboctave/boolSparse.cc
rename to liboctave/array/boolSparse.cc
--- a/liboctave/boolSparse.cc
+++ b/liboctave/array/boolSparse.cc
@@ -29,7 +29,6 @@
 #include <iostream>
 #include <vector>
 
-#include "config.h"
 #include "quit.h"
 #include "lo-ieee.h"
 #include "lo-mappers.h"
@@ -55,11 +54,11 @@
     return false;
 
   for (octave_idx_type i = 0; i < nc + 1; i++)
-    if (cidx(i) != a.cidx(i))
+    if (cidx (i) != a.cidx (i))
         return false;
 
   for (octave_idx_type i = 0; i < nz; i++)
-    if (data(i) != a.data(i) || ridx(i) != a.ridx(i))
+    if (data (i) != a.data (i) || ridx (i) != a.ridx (i))
       return false;
 
   return true;
@@ -113,12 +112,12 @@
     {
       for (octave_idx_type j = 0; j < nr; j++)
         {
-          if (jj < cidx(i+1) && ridx(jj) == j)
+          if (jj < cidx (i+1) && ridx (jj) == j)
             jj++;
           else
             {
-              r.data(ii) = true;
-              r.ridx(ii++) = j;
+              r.data (ii) = true;
+              r.ridx (ii++) = j;
             }
         }
       r.cidx (i+1) = ii;
@@ -150,10 +149,10 @@
     {
       // Result is a row vector.
       retval = Sparse<bool> (1, nc);
-      retval.xcidx(0) = 0;
+      retval.xcidx (0) = 0;
       for (octave_idx_type i = 0; i < nc; i++)
-        retval.xcidx(i+1) = retval.xcidx(i) + (cidx(i+1) > cidx(i));
-      octave_idx_type new_nz = retval.xcidx(nc);
+        retval.xcidx (i+1) = retval.xcidx (i) + (cidx (i+1) > cidx (i));
+      octave_idx_type new_nz = retval.xcidx (nc);
       retval.change_capacity (new_nz);
       fill_or_memset (new_nz, static_cast<octave_idx_type> (0), retval.ridx ());
       fill_or_memset (new_nz, true, retval.data ());
@@ -166,7 +165,7 @@
           // We can use O(nr) memory.
           Array<bool> tmp (dim_vector (nr, 1), false);
           for (octave_idx_type i = 0; i < nz; i++)
-            tmp.xelem(ridx(i)) = true;
+            tmp.xelem (ridx (i)) = true;
           retval = tmp;
         }
       else
@@ -195,16 +194,16 @@
     {
       // Result is a row vector.
       retval = Sparse<double> (1, nc);
-      for(octave_idx_type i = 0; i < nc; i++)
-        retval.xcidx(i+1) = retval.xcidx(i) + (cidx(i+1) > cidx(i));
-      octave_idx_type new_nz = retval.xcidx(nc);
+      for (octave_idx_type i = 0; i < nc; i++)
+        retval.xcidx (i+1) = retval.xcidx (i) + (cidx (i+1) > cidx (i));
+      octave_idx_type new_nz = retval.xcidx (nc);
       retval.change_capacity (new_nz);
       fill_or_memset (new_nz, static_cast<octave_idx_type> (0), retval.ridx ());
-      for(octave_idx_type i = 0, k = 0; i < nc; i++)
+      for (octave_idx_type i = 0, k = 0; i < nc; i++)
         {
-          octave_idx_type c = cidx(i+1) - cidx(i);
+          octave_idx_type c = cidx (i+1) - cidx (i);
           if (c > 0)
-            retval.xdata(k++) = c;
+            retval.xdata (k++) = c;
         }
     }
   else if (dim == 1)
@@ -215,7 +214,7 @@
           // We can use O(nr) memory.
           Array<double> tmp (dim_vector (nr, 1), 0);
           for (octave_idx_type i = 0; i < nz; i++)
-            tmp.xelem(ridx(i)) += 1.0;
+            tmp.xelem (ridx (i)) += 1.0;
           retval = tmp;
         }
       else
@@ -246,8 +245,8 @@
 
   boolMatrix retval (nr, nc, false);
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-      retval.elem (ridx(i), j) = data (i);
+    for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+      retval.elem (ridx (i), j) = data (i);
 
   return retval;
 }
@@ -262,8 +261,8 @@
    for (octave_idx_type j = 0; j < nc; j++)
      {
        octave_quit ();
-       for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
-         os << a.ridx(i) + 1 << " "  << j + 1 << " " << a.data(i) << "\n";
+       for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
+         os << a.ridx (i) + 1 << " "  << j + 1 << " " << a.data (i) << "\n";
      }
 
   return os;
rename from liboctave/boolSparse.h
rename to liboctave/array/boolSparse.h
rename from liboctave/chMatrix.cc
rename to liboctave/array/chMatrix.cc
rename from liboctave/chMatrix.h
rename to liboctave/array/chMatrix.h
--- a/liboctave/chMatrix.h
+++ b/liboctave/array/chMatrix.h
@@ -86,8 +86,7 @@
 
   charMatrix extract (octave_idx_type r1, octave_idx_type c1, octave_idx_type r2, octave_idx_type c2) const;
 
-  void resize (octave_idx_type nr, octave_idx_type nc,
-               char rfv = resize_fill_value ())
+  void resize (octave_idx_type nr, octave_idx_type nc, char rfv = 0)
   {
     Array<char>::resize (dim_vector (nr, nc), rfv);
   }
@@ -103,9 +102,6 @@
   friend std::ostream& operator << (std::ostream& os, const Matrix& a);
   friend std::istream& operator >> (std::istream& is, Matrix& a);
 #endif
-
-  static char resize_fill_value (void) { return '\0'; }
-
 };
 
 MS_CMP_OP_DECLS (charMatrix, char, OCTAVE_API)
rename from liboctave/chNDArray.cc
rename to liboctave/array/chNDArray.cc
--- a/liboctave/chNDArray.cc
+++ b/liboctave/array/chNDArray.cc
@@ -79,7 +79,7 @@
         {
           octave_idx_type ival = NINTbig (d);
 
-          if (ival < 0 || ival > UCHAR_MAX)
+          if (ival < 0 || ival > std::numeric_limits<unsigned char>::max ())
             // FIXME -- is there something
             // better we could do? Should we warn the user?
             ival = 0;
@@ -92,6 +92,30 @@
   return *this;
 }
 
+charNDArray
+charNDArray::max (int dim) const
+{
+  return do_mx_minmax_op<char> (*this, dim, mx_inline_max);
+}
+
+charNDArray
+charNDArray::max (Array<octave_idx_type>& idx_arg, int dim) const
+{
+  return do_mx_minmax_op<char> (*this, idx_arg, dim, mx_inline_max);
+}
+
+charNDArray
+charNDArray::min (int dim) const
+{
+  return do_mx_minmax_op<char> (*this, dim, mx_inline_min);
+}
+
+charNDArray
+charNDArray::min (Array<octave_idx_type>& idx_arg, int dim) const
+{
+  return do_mx_minmax_op<char> (*this, idx_arg, dim, mx_inline_min);
+}
+
 charNDArray&
 charNDArray::insert (const charNDArray& a, octave_idx_type r, octave_idx_type c)
 {
@@ -133,6 +157,54 @@
   return Array<char>::diag (k);
 }
 
+charNDArray
+charNDArray::diag (octave_idx_type m, octave_idx_type n) const
+{
+  return Array<char>::diag (m, n);
+}
+
+charNDArray
+min (char d, const charNDArray& m)
+{
+  return do_sm_binary_op<charNDArray::element_type, char, charNDArray::element_type>
+           (d, m, mx_inline_xmin);
+}
+
+charNDArray
+min (const charNDArray& m, char d)
+{
+  return do_ms_binary_op<charNDArray::element_type, charNDArray::element_type, char>
+           (m, d, mx_inline_xmin);
+}
+
+charNDArray
+min (const charNDArray& a, const charNDArray& b)
+{
+  return do_mm_binary_op<charNDArray::element_type, charNDArray::element_type, charNDArray::element_type>
+           (a, b, mx_inline_xmin, mx_inline_xmin, mx_inline_xmin, "min");
+}
+
+charNDArray
+max (char d, const charNDArray& m)
+{
+  return do_sm_binary_op<charNDArray::element_type, char, charNDArray::element_type>
+           (d, m, mx_inline_xmax);
+}
+
+charNDArray
+max (const charNDArray& m, char d)
+{
+  return do_ms_binary_op<charNDArray::element_type, charNDArray::element_type, char>
+           (m, d, mx_inline_xmax);
+}
+
+charNDArray
+max (const charNDArray& a, const charNDArray& b)
+{
+  return do_mm_binary_op<charNDArray::element_type, charNDArray::element_type, charNDArray::element_type>
+           (a, b, mx_inline_xmax, mx_inline_xmax, mx_inline_xmax, "max");
+}
+
 NDS_CMP_OPS (charNDArray, char)
 NDS_BOOL_OPS (charNDArray, char)
 
rename from liboctave/chNDArray.h
rename to liboctave/array/chNDArray.h
--- a/liboctave/chNDArray.h
+++ b/liboctave/array/chNDArray.h
@@ -73,6 +73,11 @@
   charNDArray concat (const charNDArray& rb, const Array<octave_idx_type>& ra_idx);
   charNDArray concat (const NDArray& rb, const Array<octave_idx_type>& ra_idx);
 
+  charNDArray max (int dim = -1) const;
+  charNDArray max (Array<octave_idx_type>& index, int dim = -1) const;
+  charNDArray min (int dim = -1) const;
+  charNDArray min (Array<octave_idx_type>& index, int dim = -1) const;
+
   charNDArray& insert (const charNDArray& a, octave_idx_type r, octave_idx_type c);
   charNDArray& insert (const charNDArray& a, const Array<octave_idx_type>& ra_idx);
 
@@ -92,12 +97,18 @@
   // friend std::ostream& operator << (std::ostream& os, const charNDArray& a);
   // friend std::istream& operator >> (std::istream& is, charNDArray& a);
 
-  static char resize_fill_value (void) { return '\0'; }
-
   charNDArray diag (octave_idx_type k = 0) const;
 
+  charNDArray diag (octave_idx_type m, octave_idx_type n) const;
 };
 
+extern OCTAVE_API charNDArray min (char d, const charNDArray& m);
+extern OCTAVE_API charNDArray min (const charNDArray& m, char d);
+extern OCTAVE_API charNDArray min (const charNDArray& a, const charNDArray& b);
+extern OCTAVE_API charNDArray max (char d, const charNDArray& m);
+extern OCTAVE_API charNDArray max (const charNDArray& m, char d);
+extern OCTAVE_API charNDArray max (const charNDArray& a, const charNDArray& b);
+
 NDS_CMP_OP_DECLS (charNDArray, char, OCTAVE_API)
 NDS_BOOL_OP_DECLS (charNDArray, char, OCTAVE_API)
 
rename from liboctave/dColVector.cc
rename to liboctave/array/dColVector.cc
--- a/liboctave/dColVector.cc
+++ b/liboctave/array/dColVector.cc
@@ -143,7 +143,7 @@
 RowVector
 ColumnVector::transpose (void) const
 {
-  return MArray<double>::transpose();
+  return MArray<double>::transpose ();
 }
 
 ColumnVector
@@ -308,7 +308,7 @@
 std::istream&
 operator >> (std::istream& is, ColumnVector& a)
 {
-  octave_idx_type len = a.length();
+  octave_idx_type len = a.length ();
 
   if (len > 0)
     {
rename from liboctave/dColVector.h
rename to liboctave/array/dColVector.h
--- a/liboctave/dColVector.h
+++ b/liboctave/array/dColVector.h
@@ -99,8 +99,7 @@
   friend OCTAVE_API std::ostream& operator << (std::ostream& os, const ColumnVector& a);
   friend OCTAVE_API std::istream& operator >> (std::istream& is, ColumnVector& a);
 
-  void resize (octave_idx_type n,
-               const double& rfv = Array<double>::resize_fill_value ())
+  void resize (octave_idx_type n, const double& rfv = 0)
   {
     Array<double>::resize (dim_vector (n, 1), rfv);
   }
rename from liboctave/dDiagMatrix.cc
rename to liboctave/array/dDiagMatrix.cc
--- a/liboctave/dDiagMatrix.cc
+++ b/liboctave/array/dDiagMatrix.cc
@@ -141,19 +141,19 @@
 DiagMatrix
 DiagMatrix::abs (void) const
 {
-  return DiagMatrix (diag ().abs (), rows (), columns ());
+  return DiagMatrix (extract_diag ().abs (), rows (), columns ());
 }
 
 DiagMatrix
 real (const ComplexDiagMatrix& a)
 {
-  return DiagMatrix (real (a.diag ()), a.rows (), a.cols ());
+  return DiagMatrix (real (a.extract_diag ()), a.rows (), a.cols ());
 }
 
 DiagMatrix
 imag (const ComplexDiagMatrix& a)
 {
-  return DiagMatrix (imag (a.diag ()), a.rows (), a.cols ());
+  return DiagMatrix (imag (a.extract_diag ()), a.rows (), a.cols ());
 }
 
 Matrix
@@ -362,7 +362,7 @@
 double
 DiagMatrix::rcond (void) const
 {
-  ColumnVector av  = diag (0).map<double> (fabs);
+  ColumnVector av = extract_diag (0).map<double> (fabs);
   double amx = av.max (), amn = av.min ();
   return amx == 0 ? 0.0 : amn / amx;
 }
rename from liboctave/dDiagMatrix.h
rename to liboctave/array/dDiagMatrix.h
--- a/liboctave/dDiagMatrix.h
+++ b/liboctave/array/dDiagMatrix.h
@@ -74,7 +74,7 @@
   DiagMatrix& fill (const ColumnVector& a, octave_idx_type beg);
   DiagMatrix& fill (const RowVector& a, octave_idx_type beg);
 
-  DiagMatrix transpose (void) const { return MDiagArray2<double>::transpose(); }
+  DiagMatrix transpose (void) const { return MDiagArray2<double>::transpose (); }
   DiagMatrix abs (void) const;
 
   friend OCTAVE_API DiagMatrix real (const ComplexDiagMatrix& a);
@@ -98,8 +98,8 @@
 
   // other operations
 
-  ColumnVector diag (octave_idx_type k = 0) const
-    { return MDiagArray2<double>::diag (k); }
+  ColumnVector extract_diag (octave_idx_type k = 0) const
+    { return MDiagArray2<double>::extract_diag (k); }
 
   DET determinant (void) const;
   double rcond (void) const;
rename from liboctave/dMatrix.cc
rename to liboctave/array/dMatrix.cc
--- a/liboctave/dMatrix.cc
+++ b/liboctave/array/dMatrix.cc
@@ -763,7 +763,7 @@
       // Calculate the norm of the matrix, for later use.
       double anorm = 0;
       if (calc_cond)
-        anorm = retval.abs().sum().row(static_cast<octave_idx_type>(0)).max();
+        anorm = retval.abs ().sum ().row (static_cast<octave_idx_type>(0)).max ();
 
       F77_XFCN (dgetrf, DGETRF, (nc, nc, tmp_data, nr, pipvt, info));
 
@@ -802,7 +802,7 @@
         }
 
       if (info != 0)
-        mattype.mark_as_rectangular();
+        mattype.mark_as_rectangular ();
     }
 
   return retval;
@@ -838,7 +838,7 @@
         }
 
       if (!mattype.is_hermitian ())
-        ret = finverse(mattype, info, rcon, force, calc_cond);
+        ret = finverse (mattype, info, rcon, force, calc_cond);
 
       if ((mattype.is_hermitian () || calc_cond) && rcon == 0.)
         ret = Matrix (rows (), columns (), octave_Inf);
@@ -856,7 +856,7 @@
   Matrix U = result.left_singular_matrix ();
   Matrix V = result.right_singular_matrix ();
 
-  ColumnVector sigma = S.diag ();
+  ColumnVector sigma = S.extract_diag ();
 
   octave_idx_type r = sigma.length () - 1;
   octave_idx_type nr = rows ();
@@ -865,9 +865,9 @@
   if (tol <= 0.0)
     {
       if (nr > nc)
-        tol = nr * sigma.elem (0) * DBL_EPSILON;
+        tol = nr * sigma.elem (0) * std::numeric_limits<double>::epsilon ();
       else
-        tol = nc * sigma.elem (0) * DBL_EPSILON;
+        tol = nc * sigma.elem (0) * std::numeric_limits<double>::epsilon ();
     }
 
   while (r >= 0 && sigma.elem (r) < tol)
@@ -1389,7 +1389,7 @@
     rcon = octave_Inf;
   else
     {
-      int typ = mattype.type ();
+      volatile int typ = mattype.type ();
 
       if (typ == MatrixType::Unknown)
         typ = mattype.type (*this);
@@ -1503,9 +1503,9 @@
               Array<octave_idx_type> ipvt (dim_vector (nr, 1));
               octave_idx_type *pipvt = ipvt.fortran_vec ();
 
-              if(anorm < 0.)
-                anorm = atmp.abs().sum().
-                  row(static_cast<octave_idx_type>(0)).max();
+              if (anorm < 0.)
+                anorm = atmp.abs ().sum ().
+                  row(static_cast<octave_idx_type>(0)).max ();
 
               Array<double> z (dim_vector (4 * nc, 1));
               double *pz = z.fortran_vec ();
@@ -1825,7 +1825,7 @@
 
                   F77_XFCN (dpotrs, DPOTRS, (F77_CONST_CHAR_ARG2 (&job, 1),
                                              nr, b_nc, tmp_data, nr,
-                                             result, b.rows(), info
+                                             result, b.rows (), info
                                              F77_CHAR_ARG_LEN (1)));
                 }
               else
@@ -1910,7 +1910,7 @@
                   char job = 'N';
                   F77_XFCN (dgetrs, DGETRS, (F77_CONST_CHAR_ARG2 (&job, 1),
                                              nr, b_nc, tmp_data, nr,
-                                             pipvt, result, b.rows(), info
+                                             pipvt, result, b.rows (), info
                                              F77_CHAR_ARG_LEN (1)));
                 }
               else
@@ -2070,7 +2070,7 @@
 {
   Matrix tmp (b);
   tmp = solve (typ, tmp, info, rcon, sing_handler, true, transt);
-  return tmp.column(static_cast<octave_idx_type> (0));
+  return tmp.column (static_cast<octave_idx_type> (0));
 }
 
 ComplexColumnVector
@@ -2102,7 +2102,7 @@
                solve_singularity_handler sing_handler, blas_trans_type transt) const
 {
   ComplexMatrix tmp (*this);
-  return tmp.solve(typ, b, info, rcon, sing_handler, transt);
+  return tmp.solve (typ, b, info, rcon, sing_handler, transt);
 }
 
 Matrix
@@ -2731,7 +2731,7 @@
 bool
 Matrix::too_large_for_float (void) const
 {
-  return test_all (xtoo_large_for_float);
+  return test_any (xtoo_large_for_float);
 }
 
 // FIXME Do these really belong here?  Maybe they should be
@@ -2791,6 +2791,23 @@
   return MArray<double>::diag (k);
 }
 
+DiagMatrix
+Matrix::diag (octave_idx_type m, octave_idx_type n) const
+{
+  DiagMatrix retval;
+
+  octave_idx_type nr = rows ();
+  octave_idx_type nc = cols ();
+
+  if (nr == 1 || nc == 1)
+    retval = DiagMatrix (*this, m, n);
+  else
+    (*current_liboctave_error_handler)
+      ("diag: expecting vector argument");
+
+  return retval;
+}
+
 ColumnVector
 Matrix::row_min (void) const
 {
@@ -3121,26 +3138,28 @@
 
 // matrix by matrix -> matrix operations
 
-/* Simple Dot Product, Matrix-Vector and Matrix-Matrix Unit tests
-%!assert([1 2 3] * [ 4 ; 5 ; 6], 32, 1e-14)
-%!assert([1 2 ; 3 4 ] * [5 ; 6], [17 ; 39 ], 1e-14)
-%!assert([1 2 ; 3 4 ] * [5 6 ; 7 8], [19 22; 43 50], 1e-14)
-*/
-
-/* Test some simple identities
+/*
+
+## Simple Dot Product, Matrix-Vector and Matrix-Matrix Unit tests
+%!assert ([1 2 3] * [ 4 ; 5 ; 6], 32, 1e-14)
+%!assert ([1 2 ; 3 4 ] * [5 ; 6], [17 ; 39 ], 1e-14)
+%!assert ([1 2 ; 3 4 ] * [5 6 ; 7 8], [19 22; 43 50], 1e-14)
+
+## Test some simple identities
 %!shared M, cv, rv, Mt, rvt
-%! M = randn(10,10)+100*eye(10,10);
+%! M = randn (10,10) + 100*eye (10,10);
 %! Mt = M';
-%! cv = randn(10,1);
-%! rv = randn(1,10);
+%! cv = randn (10,1);
+%! rv = randn (1,10);
 %! rvt = rv';
-%!assert([M*cv,M*cv],M*[cv,cv],1e-13)
-%!assert([M'*cv,M'*cv],M'*[cv,cv],1e-13)
-%!assert([rv*M;rv*M],[rv;rv]*M,1e-13)
-%!assert([rv*M';rv*M'],[rv;rv]*M',1e-13)
-%!assert(2*rv*cv,[rv,rv]*[cv;cv],1e-13)
-%!assert(M'\cv,Mt\cv,1e-14)
-%!assert(M'\rv',Mt\rvt,1e-14)
+%!assert ([M*cv,M*cv], M*[cv,cv], 1e-13)
+%!assert ([M'*cv,M'*cv], M'*[cv,cv], 1e-13)
+%!assert ([rv*M;rv*M], [rv;rv]*M, 1e-13)
+%!assert ([rv*M';rv*M'], [rv;rv]*M', 1e-13)
+%!assert (2*rv*cv, [rv,rv]*[cv;cv], 1e-13)
+%!assert (M'\cv, Mt\cv, 1e-14)
+%!assert (M'\rv', Mt\rvt, 1e-14)
+
 */
 
 static inline char
rename from liboctave/dMatrix.h
rename to liboctave/array/dMatrix.h
--- a/liboctave/dMatrix.h
+++ b/liboctave/array/dMatrix.h
@@ -125,8 +125,7 @@
 
   ColumnVector column (octave_idx_type i) const;
 
-  void resize (octave_idx_type nr, octave_idx_type nc,
-               double rfv = resize_fill_value ())
+  void resize (octave_idx_type nr, octave_idx_type nc, double rfv = 0)
   {
     MArray<double>::resize (dim_vector (nr, nc), rfv);
   }
@@ -316,6 +315,8 @@
 
   Matrix diag (octave_idx_type k = 0) const;
 
+  DiagMatrix diag (octave_idx_type m, octave_idx_type n) const;
+
   ColumnVector row_min (void) const;
   ColumnVector row_max (void) const;
 
@@ -332,8 +333,6 @@
 
   friend OCTAVE_API std::ostream& operator << (std::ostream& os, const Matrix& a);
   friend OCTAVE_API std::istream& operator >> (std::istream& is, Matrix& a);
-
-  static double resize_fill_value (void) { return 0; }
 };
 
 // Publish externally used friend functions.
rename from liboctave/dNDArray.cc
rename to liboctave/array/dNDArray.cc
--- a/liboctave/dNDArray.cc
+++ b/liboctave/array/dNDArray.cc
@@ -160,7 +160,7 @@
 ComplexNDArray
 NDArray::fourier2d (void) const
 {
-  dim_vector dv = dims();
+  dim_vector dv = dims ();
   if (dv.length () < 2)
     return ComplexNDArray ();
 
@@ -168,7 +168,7 @@
   const double *in = fortran_vec ();
   ComplexNDArray retval (dv);
   Complex *out = retval.fortran_vec ();
-  octave_idx_type howmany = numel() / dv(0) / dv(1);
+  octave_idx_type howmany = numel () / dv(0) / dv(1);
   octave_idx_type dist = dv(0) * dv(1);
 
   for (octave_idx_type i=0; i < howmany; i++)
@@ -180,14 +180,14 @@
 ComplexNDArray
 NDArray::ifourier2d (void) const
 {
-  dim_vector dv = dims();
+  dim_vector dv = dims ();
   if (dv.length () < 2)
     return ComplexNDArray ();
 
   dim_vector dv2(dv(0), dv(1));
   ComplexNDArray retval (*this);
   Complex *out = retval.fortran_vec ();
-  octave_idx_type howmany = numel() / dv(0) / dv(1);
+  octave_idx_type howmany = numel () / dv(0) / dv(1);
   octave_idx_type dist = dv(0) * dv(1);
 
   for (octave_idx_type i=0; i < howmany; i++)
@@ -281,12 +281,12 @@
           octave_quit ();
 
           for (octave_idx_type i = 0; i < npts; i++)
-            tmp[i] = elem((i + k*npts)*stride + j*dist);
+            tmp[i] = elem ((i + k*npts)*stride + j*dist);
 
           F77_FUNC (zfftf, ZFFTF) (npts, tmp, pwsave);
 
           for (octave_idx_type i = 0; i < npts; i++)
-            retval ((i + k*npts)*stride + j*dist) = tmp[i];
+            retval((i + k*npts)*stride + j*dist) = tmp[i];
         }
     }
 
@@ -328,12 +328,12 @@
           octave_quit ();
 
           for (octave_idx_type i = 0; i < npts; i++)
-            tmp[i] = elem((i + k*npts)*stride + j*dist);
+            tmp[i] = elem ((i + k*npts)*stride + j*dist);
 
           F77_FUNC (zfftb, ZFFTB) (npts, tmp, pwsave);
 
           for (octave_idx_type i = 0; i < npts; i++)
-            retval ((i + k*npts)*stride + j*dist) = tmp[i] /
+            retval((i + k*npts)*stride + j*dist) = tmp[i] /
               static_cast<double> (npts);
         }
     }
@@ -344,7 +344,7 @@
 ComplexNDArray
 NDArray::fourier2d (void) const
 {
-  dim_vector dv = dims();
+  dim_vector dv = dims ();
   dim_vector dv2 (dv(0), dv(1));
   int rank = 2;
   ComplexNDArray retval (*this);
@@ -374,12 +374,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (zfftf, ZFFTF) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l];
+                retval((l + k*npts)*stride + j*dist) = prow[l];
             }
         }
 
@@ -392,7 +392,7 @@
 ComplexNDArray
 NDArray::ifourier2d (void) const
 {
-  dim_vector dv = dims();
+  dim_vector dv = dims ();
   dim_vector dv2 (dv(0), dv(1));
   int rank = 2;
   ComplexNDArray retval (*this);
@@ -422,12 +422,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (zfftb, ZFFTB) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l] /
+                retval((l + k*npts)*stride + j*dist) = prow[l] /
                   static_cast<double> (npts);
             }
         }
@@ -470,12 +470,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (zfftf, ZFFTF) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l];
+                retval((l + k*npts)*stride + j*dist) = prow[l];
             }
         }
 
@@ -517,12 +517,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (zfftb, ZFFTB) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l] /
+                retval((l + k*npts)*stride + j*dist) = prow[l] /
                   static_cast<double> (npts);
             }
         }
@@ -632,7 +632,7 @@
 bool
 NDArray::too_large_for_float (void) const
 {
-  return test_all (xtoo_large_for_float);
+  return test_any (xtoo_large_for_float);
 }
 
 // FIXME -- this is not quite the right thing.
@@ -776,7 +776,7 @@
         {
           octave_idx_type ival = NINTbig (d);
 
-          if (ival < 0 || ival > UCHAR_MAX)
+          if (ival < 0 || ival > std::numeric_limits<unsigned char>::max ())
             // FIXME -- is there something
             // better we could do? Should we warn the user?
             ival = 0;
@@ -877,6 +877,12 @@
   return MArray<double>::diag (k);
 }
 
+NDArray
+NDArray::diag (octave_idx_type m, octave_idx_type n) const
+{
+  return MArray<double>::diag (m, n);
+}
+
 // This contains no information on the array structure !!!
 std::ostream&
 operator << (std::ostream& os, const NDArray& a)
rename from liboctave/dNDArray.h
rename to liboctave/array/dNDArray.h
--- a/liboctave/dNDArray.h
+++ b/liboctave/array/dNDArray.h
@@ -64,6 +64,10 @@
 
   NDArray (const charNDArray&);
 
+  // For jit support only
+  NDArray (double *sdata, octave_idx_type slen, octave_idx_type *adims, void *arep)
+    : MArray<double> (sdata, slen, adims, arep) { }
+
   NDArray& operator = (const NDArray& a)
     {
       MArray<double>::operator = (a);
@@ -150,9 +154,9 @@
   friend OCTAVE_API std::ostream& operator << (std::ostream& os, const NDArray& a);
   friend OCTAVE_API std::istream& operator >> (std::istream& is, NDArray& a);
 
-  static double resize_fill_value (void) { return 0; }
+  NDArray diag (octave_idx_type k = 0) const;
 
-  NDArray diag (octave_idx_type k = 0) const;
+  NDArray diag (octave_idx_type m, octave_idx_type n) const;
 
   NDArray& changesign (void)
     {
rename from liboctave/dRowVector.cc
rename to liboctave/array/dRowVector.cc
--- a/liboctave/dRowVector.cc
+++ b/liboctave/array/dRowVector.cc
@@ -146,7 +146,7 @@
 ColumnVector
 RowVector::transpose (void) const
 {
-  return MArray<double>::transpose();
+  return MArray<double>::transpose ();
 }
 
 RowVector
@@ -271,7 +271,7 @@
 std::istream&
 operator >> (std::istream& is, RowVector& a)
 {
-  octave_idx_type len = a.length();
+  octave_idx_type len = a.length ();
 
   if (len > 0)
     {
rename from liboctave/dRowVector.h
rename to liboctave/array/dRowVector.h
--- a/liboctave/dRowVector.h
+++ b/liboctave/array/dRowVector.h
@@ -92,8 +92,7 @@
   friend OCTAVE_API std::ostream& operator << (std::ostream& os, const RowVector& a);
   friend OCTAVE_API std::istream& operator >> (std::istream& is, RowVector& a);
 
-  void resize (octave_idx_type n,
-               const double& rfv = Array<double>::resize_fill_value ())
+  void resize (octave_idx_type n, const double& rfv = 0)
   {
     Array<double>::resize (dim_vector (1, n), rfv);
   }
rename from liboctave/dSparse.cc
rename to liboctave/array/dSparse.cc
--- a/liboctave/dSparse.cc
+++ b/liboctave/array/dSparse.cc
@@ -177,7 +177,7 @@
         }
     }
   for (octave_idx_type i = l; i <= a.cols (); i++)
-    cidx(i) = j;
+    cidx (i) = j;
 }
 
 bool
@@ -194,11 +194,11 @@
     return false;
 
   for (octave_idx_type i = 0; i < nc + 1; i++)
-    if (cidx(i) != a.cidx(i))
+    if (cidx (i) != a.cidx (i))
         return false;
 
   for (octave_idx_type i = 0; i < nz; i++)
-    if (data(i) != a.data(i) || ridx(i) != a.ridx(i))
+    if (data (i) != a.data (i) || ridx (i) != a.ridx (i))
       return false;
 
   return true;
@@ -220,19 +220,19 @@
     {
       for (octave_idx_type j = 0; j < nc; j++)
         {
-          for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-            {
-              octave_idx_type ri = ridx(i);
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+            {
+              octave_idx_type ri = ridx (i);
 
               if (ri != j)
                 {
                   bool found = false;
 
-                  for (octave_idx_type k = cidx(ri); k < cidx(ri+1); k++)
+                  for (octave_idx_type k = cidx (ri); k < cidx (ri+1); k++)
                     {
-                      if (ridx(k) == j)
+                      if (ridx (k) == j)
                         {
-                          if (data(i) == data(k))
+                          if (data (i) == data (k))
                             found = true;
                           break;
                         }
@@ -294,9 +294,9 @@
         {
           double tmp_max = octave_NaN;
           octave_idx_type idx_j = 0;
-          for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-            {
-              if (ridx(i) != idx_j)
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+            {
+              if (ridx (i) != idx_j)
                 break;
               else
                 idx_j++;
@@ -305,7 +305,7 @@
           if (idx_j != nr)
             tmp_max = 0.;
 
-          for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
             {
               double tmp = data (i);
 
@@ -344,30 +344,30 @@
     {
       idx_arg.resize (dim_vector  (nr, 1), 0);
 
-      for (octave_idx_type i = cidx(0); i < cidx(1); i++)
-        idx_arg.elem(ridx(i)) = -1;
+      for (octave_idx_type i = cidx (0); i < cidx (1); i++)
+        idx_arg.elem (ridx (i)) = -1;
 
       for (octave_idx_type j = 0; j < nc; j++)
         for (octave_idx_type i = 0; i < nr; i++)
           {
-            if (idx_arg.elem(i) != -1)
+            if (idx_arg.elem (i) != -1)
               continue;
             bool found = false;
-            for (octave_idx_type k = cidx(j); k < cidx(j+1); k++)
-              if (ridx(k) == i)
+            for (octave_idx_type k = cidx (j); k < cidx (j+1); k++)
+              if (ridx (k) == i)
                 {
                   found = true;
                   break;
                 }
 
             if (!found)
-              idx_arg.elem(i) = j;
+              idx_arg.elem (i) = j;
 
           }
 
       for (octave_idx_type j = 0; j < nc; j++)
         {
-          for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
             {
               octave_idx_type ir = ridx (i);
               octave_idx_type ix = idx_arg.elem (ir);
@@ -382,7 +382,7 @@
 
       octave_idx_type nel = 0;
       for (octave_idx_type j = 0; j < nr; j++)
-        if (idx_arg.elem(j) == -1 || elem (j, idx_arg.elem (j)) != 0.)
+        if (idx_arg.elem (j) == -1 || elem (j, idx_arg.elem (j)) != 0.)
           nel++;
 
       result = SparseMatrix (nr, 1, nel);
@@ -443,9 +443,9 @@
         {
           double tmp_min = octave_NaN;
           octave_idx_type idx_j = 0;
-          for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-            {
-              if (ridx(i) != idx_j)
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+            {
+              if (ridx (i) != idx_j)
                 break;
               else
                 idx_j++;
@@ -454,7 +454,7 @@
           if (idx_j != nr)
             tmp_min = 0.;
 
-          for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
             {
               double tmp = data (i);
 
@@ -493,30 +493,30 @@
     {
       idx_arg.resize (dim_vector (nr, 1), 0);
 
-      for (octave_idx_type i = cidx(0); i < cidx(1); i++)
-        idx_arg.elem(ridx(i)) = -1;
+      for (octave_idx_type i = cidx (0); i < cidx (1); i++)
+        idx_arg.elem (ridx (i)) = -1;
 
       for (octave_idx_type j = 0; j < nc; j++)
         for (octave_idx_type i = 0; i < nr; i++)
           {
-            if (idx_arg.elem(i) != -1)
+            if (idx_arg.elem (i) != -1)
               continue;
             bool found = false;
-            for (octave_idx_type k = cidx(j); k < cidx(j+1); k++)
-              if (ridx(k) == i)
+            for (octave_idx_type k = cidx (j); k < cidx (j+1); k++)
+              if (ridx (k) == i)
                 {
                   found = true;
                   break;
                 }
 
             if (!found)
-              idx_arg.elem(i) = j;
+              idx_arg.elem (i) = j;
 
           }
 
       for (octave_idx_type j = 0; j < nc; j++)
         {
-          for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+          for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
             {
               octave_idx_type ir = ridx (i);
               octave_idx_type ix = idx_arg.elem (ir);
@@ -531,7 +531,7 @@
 
       octave_idx_type nel = 0;
       for (octave_idx_type j = 0; j < nr; j++)
-        if (idx_arg.elem(j) == -1 || elem (j, idx_arg.elem (j)) != 0.)
+        if (idx_arg.elem (j) == -1 || elem (j, idx_arg.elem (j)) != 0.)
           nel++;
 
       result = SparseMatrix (nr, 1, nel);
@@ -620,12 +620,12 @@
   SparseMatrix r (nr, nc, nz);
 
   for (octave_idx_type i = 0; i < nc +1; i++)
-    r.cidx(i) = a.cidx(i);
+    r.cidx (i) = a.cidx (i);
 
   for (octave_idx_type i = 0; i < nz; i++)
     {
-      r.data(i) = std::real (a.data(i));
-      r.ridx(i) = a.ridx(i);
+      r.data (i) = std::real (a.data (i));
+      r.ridx (i) = a.ridx (i);
     }
 
   return r;
@@ -640,12 +640,12 @@
   SparseMatrix r (nr, nc, nz);
 
   for (octave_idx_type i = 0; i < nc +1; i++)
-    r.cidx(i) = a.cidx(i);
+    r.cidx (i) = a.cidx (i);
 
   for (octave_idx_type i = 0; i < nz; i++)
     {
-      r.data(i) = std::imag (a.data(i));
-      r.ridx(i) = a.ridx(i);
+      r.data (i) = std::imag (a.data (i));
+      r.ridx (i) = a.ridx (i);
     }
 
   return r;
@@ -667,7 +667,7 @@
 
       for (octave_idx_type j = 0; j < nc; j++)
         for (octave_idx_type i = y.cidx (j); i < y.cidx (j+1); i++)
-          tmp.elem (y.ridx(i), j) = atan2 (x, y.data(i));
+          tmp.elem (y.ridx (i), j) = atan2 (x, y.data (i));
 
       return SparseMatrix (tmp);
     }
@@ -683,12 +683,12 @@
   SparseMatrix retval (nr, nc, nz);
 
   octave_idx_type ii = 0;
-  retval.xcidx(0) = 0;
+  retval.xcidx (0) = 0;
   for (octave_idx_type i = 0; i < nc; i++)
     {
-      for (octave_idx_type j = x.cidx(i); j < x.cidx(i+1); j++)
+      for (octave_idx_type j = x.cidx (i); j < x.cidx (i+1); j++)
         {
-          double tmp = atan2 (x.data(j), y);
+          double tmp = atan2 (x.data (j), y);
           if (tmp != 0.)
             {
               retval.xdata (ii) = tmp;
@@ -719,7 +719,7 @@
 {
   SparseMatrix r;
 
-  if ((x.rows() == y.rows()) && (x.cols() == y.cols()))
+  if ((x.rows () == y.rows ()) && (x.cols () == y.cols ()))
     {
       octave_idx_type x_nr = x.rows ();
       octave_idx_type x_nc = x.cols ();
@@ -737,39 +737,39 @@
           r.cidx (0) = 0;
           for (octave_idx_type i = 0 ; i < x_nc ; i++)
             {
-              octave_idx_type  ja = x.cidx(i);
-              octave_idx_type  ja_max = x.cidx(i+1);
+              octave_idx_type  ja = x.cidx (i);
+              octave_idx_type  ja_max = x.cidx (i+1);
               bool ja_lt_max= ja < ja_max;
 
-              octave_idx_type  jb = y.cidx(i);
-              octave_idx_type  jb_max = y.cidx(i+1);
+              octave_idx_type  jb = y.cidx (i);
+              octave_idx_type  jb_max = y.cidx (i+1);
               bool jb_lt_max = jb < jb_max;
 
               while (ja_lt_max || jb_lt_max )
                 {
                   octave_quit ();
                   if ((! jb_lt_max) ||
-                      (ja_lt_max && (x.ridx(ja) < y.ridx(jb))))
+                      (ja_lt_max && (x.ridx (ja) < y.ridx (jb))))
                     {
-                      r.ridx(jx) = x.ridx(ja);
-                      r.data(jx) = atan2 (x.data(ja), 0.);
+                      r.ridx (jx) = x.ridx (ja);
+                      r.data (jx) = atan2 (x.data (ja), 0.);
                       jx++;
                       ja++;
                       ja_lt_max= ja < ja_max;
                     }
                   else if (( !ja_lt_max ) ||
-                           (jb_lt_max && (y.ridx(jb) < x.ridx(ja)) ) )
+                           (jb_lt_max && (y.ridx (jb) < x.ridx (ja)) ) )
                     {
                       jb++;
                       jb_lt_max= jb < jb_max;
                     }
                   else
                     {
-                      double tmp = atan2 (x.data(ja), y.data(jb));
+                      double tmp = atan2 (x.data (ja), y.data (jb));
                       if (tmp != 0.)
                         {
-                          r.data(jx) = tmp;
-                          r.ridx(jx) = x.ridx(ja);
+                          r.data (jx) = tmp;
+                          r.ridx (jx) = x.ridx (ja);
                           jx++;
                         }
                       ja++;
@@ -778,7 +778,7 @@
                       jb_lt_max= jb < jb_max;
                     }
                 }
-              r.cidx(i+1) = jx;
+              r.cidx (i+1) = jx;
             }
 
           r.maybe_compress ();
@@ -837,19 +837,19 @@
           typ == MatrixType::Permuted_Diagonal)
         {
           if (typ == MatrixType::Permuted_Diagonal)
-            retval = transpose();
+            retval = transpose ();
           else
             retval = *this;
 
           // Force make_unique to be called
-          double *v = retval.data();
+          double *v = retval.data ();
 
           if (calccond)
             {
               double dmax = 0., dmin = octave_Inf;
               for (octave_idx_type i = 0; i < nr; i++)
                 {
-                  double tmp = fabs(v[i]);
+                  double tmp = fabs (v[i]);
                   if (tmp > dmax)
                     dmax = tmp;
                   if (tmp < dmin)
@@ -899,8 +899,8 @@
               for (octave_idx_type j = 0; j < nr; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += fabs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += fabs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -925,9 +925,9 @@
                       retval.change_capacity (nz2);
                     }
 
-                  retval.xcidx(i) = cx;
-                  retval.xridx(cx) = i;
-                  retval.xdata(cx) = 1.0;
+                  retval.xcidx (i) = cx;
+                  retval.xridx (cx) = i;
+                  retval.xdata (cx) = 1.0;
                   cx++;
 
                   // iterate accross columns of input matrix
@@ -935,11 +935,11 @@
                     {
                       double v = 0.;
                       // iterate to calculate sum
-                      octave_idx_type colXp = retval.xcidx(i);
-                      octave_idx_type colUp = cidx(j);
+                      octave_idx_type colXp = retval.xcidx (i);
+                      octave_idx_type colUp = cidx (j);
                       octave_idx_type rpX, rpU;
 
-                      if (cidx(j) == cidx(j+1))
+                      if (cidx (j) == cidx (j+1))
                         {
                           (*current_liboctave_error_handler)
                             ("division by zero");
@@ -949,8 +949,8 @@
                       do
                         {
                           octave_quit ();
-                          rpX = retval.xridx(colXp);
-                          rpU = ridx(colUp);
+                          rpX = retval.xridx (colXp);
+                          rpU = ridx (colUp);
 
                           if (rpX < rpU)
                             colXp++;
@@ -958,7 +958,7 @@
                             colUp++;
                           else
                             {
-                              v -= retval.xdata(colXp) * data(colUp);
+                              v -= retval.xdata (colXp) * data (colUp);
                               colXp++;
                               colUp++;
                             }
@@ -967,11 +967,11 @@
 
                       // get A(m,m)
                       if (typ == MatrixType::Upper)
-                        colUp = cidx(j+1) - 1;
+                        colUp = cidx (j+1) - 1;
                       else
-                        colUp = cidx(j);
-                      double pivot = data(colUp);
-                      if (pivot == 0. || ridx(colUp) != j)
+                        colUp = cidx (j);
+                      double pivot = data (colUp);
+                      if (pivot == 0. || ridx (colUp) != j)
                         {
                           (*current_liboctave_error_handler)
                             ("division by zero");
@@ -986,8 +986,8 @@
                               retval.change_capacity (nz2);
                             }
 
-                          retval.xridx(cx) = j;
-                          retval.xdata(cx) = v / pivot;
+                          retval.xridx (cx) = j;
+                          retval.xdata (cx) = v / pivot;
                           cx++;
                         }
                     }
@@ -995,11 +995,11 @@
                   // get A(m,m)
                   octave_idx_type colUp;
                   if (typ == MatrixType::Upper)
-                    colUp = cidx(i+1) - 1;
+                    colUp = cidx (i+1) - 1;
                   else
-                    colUp = cidx(i);
-                  double pivot = data(colUp);
-                  if (pivot == 0. || ridx(colUp) != i)
+                    colUp = cidx (i);
+                  double pivot = data (colUp);
+                  if (pivot == 0. || ridx (colUp) != i)
                     {
                       (*current_liboctave_error_handler) ("division by zero");
                       goto inverse_singular;
@@ -1007,9 +1007,9 @@
 
                   if (pivot != 1.0)
                     for (octave_idx_type j = cx_colstart; j < cx; j++)
-                      retval.xdata(j) /= pivot;
-                }
-              retval.xcidx(nr) = cx;
+                      retval.xdata (j) /= pivot;
+                }
+              retval.xcidx (nr) = cx;
               retval.maybe_compress ();
             }
           else
@@ -1022,7 +1022,7 @@
               OCTAVE_LOCAL_BUFFER (double, work, nr);
               OCTAVE_LOCAL_BUFFER (octave_idx_type, rperm, nr);
 
-              octave_idx_type *perm = mattyp.triangular_perm();
+              octave_idx_type *perm = mattyp.triangular_perm ();
               if (typ == MatrixType::Permuted_Upper)
                 {
                   for (octave_idx_type i = 0; i < nr; i++)
@@ -1053,19 +1053,19 @@
                       double v = 0.;
                       octave_idx_type jidx = perm[j];
                       // iterate to calculate sum
-                      for (octave_idx_type k = cidx(jidx);
-                           k < cidx(jidx+1); k++)
+                      for (octave_idx_type k = cidx (jidx);
+                           k < cidx (jidx+1); k++)
                         {
                           octave_quit ();
-                          v -= work[ridx(k)] * data(k);
+                          v -= work[ridx (k)] * data (k);
                         }
 
                       // get A(m,m)
                       double pivot;
                       if (typ == MatrixType::Permuted_Upper)
-                        pivot = data(cidx(jidx+1) - 1);
+                        pivot = data (cidx (jidx+1) - 1);
                       else
-                        pivot = data(cidx(jidx));
+                        pivot = data (cidx (jidx));
                       if (pivot == 0.)
                         {
                           (*current_liboctave_error_handler)
@@ -1079,11 +1079,11 @@
                   // get A(m,m)
                   octave_idx_type colUp;
                   if (typ == MatrixType::Permuted_Upper)
-                    colUp = cidx(perm[iidx]+1) - 1;
+                    colUp = cidx (perm[iidx]+1) - 1;
                   else
-                    colUp = cidx(perm[iidx]);
-
-                  double pivot = data(colUp);
+                    colUp = cidx (perm[iidx]);
+
+                  double pivot = data (colUp);
                   if (pivot == 0.)
                     {
                       (*current_liboctave_error_handler)
@@ -1106,16 +1106,16 @@
                       retval.change_capacity (nz2);
                     }
 
-                  retval.xcidx(i) = cx;
+                  retval.xcidx (i) = cx;
                   for (octave_idx_type j = iidx; j < nr; j++)
                     if (work[j] != 0.)
                       {
-                        retval.xridx(cx) = j;
-                        retval.xdata(cx++) = work[j];
+                        retval.xridx (cx) = j;
+                        retval.xdata (cx++) = work[j];
                       }
                 }
 
-              retval.xcidx(nr) = cx;
+              retval.xcidx (nr) = cx;
               retval.maybe_compress ();
             }
 
@@ -1125,9 +1125,9 @@
               for (octave_idx_type j = 0; j < nr; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = retval.cidx(j);
-                       i < retval.cidx(j+1); i++)
-                    atmp += fabs(retval.data(i));
+                  for (octave_idx_type i = retval.cidx (j);
+                       i < retval.cidx (j+1); i++)
+                    atmp += fabs (retval.data (i));
                   if (atmp > ainvnorm)
                     ainvnorm = atmp;
                 }
@@ -1142,7 +1142,7 @@
   return retval;
 
  inverse_singular:
-  return SparseMatrix();
+  return SparseMatrix ();
 }
 
 SparseMatrix
@@ -1158,26 +1158,26 @@
   if (typ == MatrixType::Diagonal || typ == MatrixType::Permuted_Diagonal)
     ret = dinverse (mattype, info, rcond, true, calc_cond);
   else if (typ == MatrixType::Upper || typ == MatrixType::Permuted_Upper)
-    ret = tinverse (mattype, info, rcond, true, calc_cond).transpose();
+    ret = tinverse (mattype, info, rcond, true, calc_cond).transpose ();
   else if (typ == MatrixType::Lower || typ == MatrixType::Permuted_Lower)
     {
-      MatrixType newtype = mattype.transpose();
-      ret = transpose().tinverse (newtype, info, rcond, true, calc_cond);
+      MatrixType newtype = mattype.transpose ();
+      ret = transpose ().tinverse (newtype, info, rcond, true, calc_cond);
     }
   else
     {
-      if (mattype.is_hermitian())
+      if (mattype.is_hermitian ())
         {
           MatrixType tmp_typ (MatrixType::Upper);
           SparseCHOL fact (*this, info, false);
-          rcond = fact.rcond();
+          rcond = fact.rcond ();
           if (info == 0)
             {
               double rcond2;
-              SparseMatrix Q = fact.Q();
-              SparseMatrix InvL = fact.L().transpose().tinverse(tmp_typ,
+              SparseMatrix Q = fact.Q ();
+              SparseMatrix InvL = fact.L ().transpose ().tinverse (tmp_typ,
                                            info, rcond2, true, false);
-              ret = Q * InvL.transpose() * InvL * Q.transpose();
+              ret = Q * InvL.transpose () * InvL * Q.transpose ();
             }
           else
             {
@@ -1187,22 +1187,22 @@
             }
         }
 
-      if (!mattype.is_hermitian())
+      if (!mattype.is_hermitian ())
         {
-          octave_idx_type n = rows();
+          octave_idx_type n = rows ();
           ColumnVector Qinit(n);
           for (octave_idx_type i = 0; i < n; i++)
             Qinit(i) = i;
 
           MatrixType tmp_typ (MatrixType::Upper);
-          SparseLU fact (*this, Qinit, Matrix(), false, false);
-          rcond = fact.rcond();
+          SparseLU fact (*this, Qinit, Matrix (), false, false);
+          rcond = fact.rcond ();
           double rcond2;
-          SparseMatrix InvL = fact.L().transpose().tinverse(tmp_typ,
+          SparseMatrix InvL = fact.L ().transpose ().tinverse (tmp_typ,
                                            info, rcond2, true, false);
-          SparseMatrix InvU = fact.U().tinverse(tmp_typ, info, rcond2,
-                                           true, false).transpose();
-          ret = fact.Pc().transpose() * InvU * InvL * fact.Pr();
+          SparseMatrix InvU = fact.U ().tinverse (tmp_typ, info, rcond2,
+                                           true, false).transpose ();
+          ret = fact.Pc ().transpose () * InvU * InvL * fact.Pr ();
         }
     }
 
@@ -1366,23 +1366,23 @@
       if (typ == MatrixType::Diagonal ||
           typ == MatrixType::Permuted_Diagonal)
         {
-          retval.resize (nc, b.cols(), 0.);
+          retval.resize (nc, b.cols (), 0.);
           if (typ == MatrixType::Diagonal)
-            for (octave_idx_type j = 0; j < b.cols(); j++)
+            for (octave_idx_type j = 0; j < b.cols (); j++)
               for (octave_idx_type i = 0; i < nm; i++)
                 retval(i,j) = b(i,j) / data (i);
           else
-            for (octave_idx_type j = 0; j < b.cols(); j++)
+            for (octave_idx_type j = 0; j < b.cols (); j++)
               for (octave_idx_type k = 0; k < nc; k++)
-                for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
-                  retval(k,j) = b(ridx(i),j) / data (i);
+                for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
+                  retval(k,j) = b(ridx (i),j) / data (i);
 
           if (calc_cond)
             {
               double dmax = 0., dmin = octave_Inf;
               for (octave_idx_type i = 0; i < nm; i++)
                 {
-                  double tmp = fabs(data(i));
+                  double tmp = fabs (data (i));
                   if (tmp > dmax)
                     dmax = tmp;
                   if (tmp < dmin)
@@ -1430,30 +1430,30 @@
           octave_idx_type b_nz = b.nnz ();
           retval = SparseMatrix (nc, b_nc, b_nz);
 
-          retval.xcidx(0) = 0;
+          retval.xcidx (0) = 0;
           octave_idx_type ii = 0;
           if (typ == MatrixType::Diagonal)
             for (octave_idx_type j = 0; j < b_nc; j++)
               {
-                for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
+                for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
                   {
-                    if (b.ridx(i) >= nm)
+                    if (b.ridx (i) >= nm)
                       break;
-                    retval.xridx (ii) = b.ridx(i);
-                    retval.xdata (ii++) = b.data(i) / data (b.ridx (i));
+                    retval.xridx (ii) = b.ridx (i);
+                    retval.xdata (ii++) = b.data (i) / data (b.ridx (i));
                   }
-                retval.xcidx(j+1) = ii;
+                retval.xcidx (j+1) = ii;
               }
           else
             for (octave_idx_type j = 0; j < b_nc; j++)
               {
                 for (octave_idx_type l = 0; l < nc; l++)
-                  for (octave_idx_type i = cidx(l); i < cidx(l+1); i++)
+                  for (octave_idx_type i = cidx (l); i < cidx (l+1); i++)
                     {
                       bool found = false;
                       octave_idx_type k;
-                      for (k = b.cidx(j); k < b.cidx(j+1); k++)
-                        if (ridx(i) == b.ridx(k))
+                      for (k = b.cidx (j); k < b.cidx (j+1); k++)
+                        if (ridx (i) == b.ridx (k))
                           {
                             found = true;
                             break;
@@ -1461,10 +1461,10 @@
                       if (found)
                         {
                           retval.xridx (ii) = l;
-                          retval.xdata (ii++) = b.data(k) / data (i);
+                          retval.xdata (ii++) = b.data (k) / data (i);
                         }
                     }
-                retval.xcidx(j+1) = ii;
+                retval.xcidx (j+1) = ii;
               }
 
           if (calc_cond)
@@ -1472,7 +1472,7 @@
               double dmax = 0., dmin = octave_Inf;
               for (octave_idx_type i = 0; i < nm; i++)
                 {
-                  double tmp = fabs(data(i));
+                  double tmp = fabs (data (i));
                   if (tmp > dmax)
                     dmax = tmp;
                   if (tmp < dmin)
@@ -1516,23 +1516,23 @@
       if (typ == MatrixType::Diagonal ||
           typ == MatrixType::Permuted_Diagonal)
         {
-          retval.resize (nc, b.cols(), 0);
+          retval.resize (nc, b.cols (), 0);
           if (typ == MatrixType::Diagonal)
-            for (octave_idx_type j = 0; j < b.cols(); j++)
+            for (octave_idx_type j = 0; j < b.cols (); j++)
                 for (octave_idx_type i = 0; i < nm; i++)
                   retval(i,j) = b(i,j) / data (i);
           else
-            for (octave_idx_type j = 0; j < b.cols(); j++)
+            for (octave_idx_type j = 0; j < b.cols (); j++)
               for (octave_idx_type k = 0; k < nc; k++)
-                for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
-                  retval(k,j) = b(ridx(i),j) / data (i);
+                for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
+                  retval(k,j) = b(ridx (i),j) / data (i);
 
           if (calc_cond)
             {
               double dmax = 0., dmin = octave_Inf;
               for (octave_idx_type i = 0; i < nm; i++)
                 {
-                  double tmp = fabs(data(i));
+                  double tmp = fabs (data (i));
                   if (tmp > dmax)
                     dmax = tmp;
                   if (tmp < dmin)
@@ -1580,30 +1580,30 @@
           octave_idx_type b_nz = b.nnz ();
           retval = SparseComplexMatrix (nc, b_nc, b_nz);
 
-          retval.xcidx(0) = 0;
+          retval.xcidx (0) = 0;
           octave_idx_type ii = 0;
           if (typ == MatrixType::Diagonal)
-            for (octave_idx_type j = 0; j < b.cols(); j++)
+            for (octave_idx_type j = 0; j < b.cols (); j++)
               {
-                for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
+                for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
                   {
-                    if (b.ridx(i) >= nm)
+                    if (b.ridx (i) >= nm)
                       break;
-                    retval.xridx (ii) = b.ridx(i);
-                    retval.xdata (ii++) = b.data(i) / data (b.ridx (i));
+                    retval.xridx (ii) = b.ridx (i);
+                    retval.xdata (ii++) = b.data (i) / data (b.ridx (i));
                   }
-                retval.xcidx(j+1) = ii;
+                retval.xcidx (j+1) = ii;
               }
           else
-            for (octave_idx_type j = 0; j < b.cols(); j++)
+            for (octave_idx_type j = 0; j < b.cols (); j++)
               {
                 for (octave_idx_type l = 0; l < nc; l++)
-                  for (octave_idx_type i = cidx(l); i < cidx(l+1); i++)
+                  for (octave_idx_type i = cidx (l); i < cidx (l+1); i++)
                     {
                       bool found = false;
                       octave_idx_type k;
-                      for (k = b.cidx(j); k < b.cidx(j+1); k++)
-                        if (ridx(i) == b.ridx(k))
+                      for (k = b.cidx (j); k < b.cidx (j+1); k++)
+                        if (ridx (i) == b.ridx (k))
                           {
                             found = true;
                             break;
@@ -1611,10 +1611,10 @@
                       if (found)
                         {
                           retval.xridx (ii) = l;
-                          retval.xdata (ii++) = b.data(k) / data (i);
+                          retval.xdata (ii++) = b.data (k) / data (i);
                         }
                     }
-                retval.xcidx(j+1) = ii;
+                retval.xcidx (j+1) = ii;
               }
 
           if (calc_cond)
@@ -1622,7 +1622,7 @@
               double dmax = 0., dmin = octave_Inf;
               for (octave_idx_type i = 0; i < nm; i++)
                 {
-                  double tmp = fabs(data(i));
+                  double tmp = fabs (data (i));
                   if (tmp > dmax)
                     dmax = tmp;
                   if (tmp < dmin)
@@ -1678,8 +1678,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += fabs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += fabs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -1704,20 +1704,20 @@
 
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(kidx+1)-1) != k ||
-                              data(cidx(kidx+1)-1) == 0.)
+                          if (ridx (cidx (kidx+1)-1) != k ||
+                              data (cidx (kidx+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          double tmp = work[k] / data(cidx(kidx+1)-1);
+                          double tmp = work[k] / data (cidx (kidx+1)-1);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(kidx);
-                               i < cidx(kidx+1)-1; i++)
+                          for (octave_idx_type i = cidx (kidx);
+                               i < cidx (kidx+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -1742,20 +1742,20 @@
 
                           if (work[k] != 0.)
                             {
-                              double tmp = work[k] / data(cidx(iidx+1)-1);
+                              double tmp = work[k] / data (cidx (iidx+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(iidx);
-                                   i < cidx(iidx+1)-1; i++)
+                              for (octave_idx_type i = cidx (iidx);
+                                   i < cidx (iidx+1)-1; i++)
                                 {
-                                  octave_idx_type idx2 = ridx(i);
-                                  work[idx2] = work[idx2] - tmp * data(i);
+                                  octave_idx_type idx2 = ridx (i);
+                                  work[idx2] = work[idx2] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -1780,19 +1780,19 @@
                     {
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(k+1)-1) != k ||
-                              data(cidx(k+1)-1) == 0.)
+                          if (ridx (cidx (k+1)-1) != k ||
+                              data (cidx (k+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          double tmp = work[k] / data(cidx(k+1)-1);
+                          double tmp = work[k] / data (cidx (k+1)-1);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1)-1; i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -1815,19 +1815,19 @@
                         {
                           if (work[k] != 0.)
                             {
-                              double tmp = work[k] / data(cidx(k+1)-1);
+                              double tmp = work[k] / data (cidx (k+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k); i < cidx(k+1)-1; i++)
+                              for (octave_idx_type i = cidx (k); i < cidx (k+1)-1; i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -1912,8 +1912,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += fabs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += fabs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -1922,7 +1922,7 @@
           octave_idx_type b_nc = b.cols ();
           octave_idx_type b_nz = b.nnz ();
           retval = SparseMatrix (nc, b_nc, b_nz);
-          retval.xcidx(0) = 0;
+          retval.xcidx (0) = 0;
           octave_idx_type ii = 0;
           octave_idx_type x_nz = b_nz;
 
@@ -1939,8 +1939,8 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     work[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    work[b.ridx(i)] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    work[b.ridx (i)] = b.data (i);
 
                   for (octave_idx_type k = nc-1; k >= 0; k--)
                     {
@@ -1948,20 +1948,20 @@
 
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(kidx+1)-1) != k ||
-                              data(cidx(kidx+1)-1) == 0.)
+                          if (ridx (cidx (kidx+1)-1) != k ||
+                              data (cidx (kidx+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          double tmp = work[k] / data(cidx(kidx+1)-1);
+                          double tmp = work[k] / data (cidx (kidx+1)-1);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(kidx);
-                               i < cidx(kidx+1)-1; i++)
+                          for (octave_idx_type i = cidx (kidx);
+                               i < cidx (kidx+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -1984,10 +1984,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (work[rperm[i]] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = work[rperm[i]];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = work[rperm[i]];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -2008,20 +2008,20 @@
 
                           if (work[k] != 0.)
                             {
-                              double tmp = work[k] / data(cidx(iidx+1)-1);
+                              double tmp = work[k] / data (cidx (iidx+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(iidx);
-                                   i < cidx(iidx+1)-1; i++)
+                              for (octave_idx_type i = cidx (iidx);
+                                   i < cidx (iidx+1)-1; i++)
                                 {
-                                  octave_idx_type idx2 = ridx(i);
-                                  work[idx2] = work[idx2] - tmp * data(i);
+                                  octave_idx_type idx2 = ridx (i);
+                                  work[idx2] = work[idx2] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2038,26 +2038,26 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     work[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    work[b.ridx(i)] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    work[b.ridx (i)] = b.data (i);
 
                   for (octave_idx_type k = nc-1; k >= 0; k--)
                     {
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(k+1)-1) != k ||
-                              data(cidx(k+1)-1) == 0.)
+                          if (ridx (cidx (k+1)-1) != k ||
+                              data (cidx (k+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          double tmp = work[k] / data(cidx(k+1)-1);
+                          double tmp = work[k] / data (cidx (k+1)-1);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1)-1; i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -2080,10 +2080,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (work[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = work[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = work[i];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -2102,20 +2102,20 @@
                         {
                           if (work[k] != 0.)
                             {
-                              double tmp = work[k] / data(cidx(k+1)-1);
+                              double tmp = work[k] / data (cidx (k+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1)-1; i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1)-1; i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2200,8 +2200,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += fabs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += fabs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -2226,20 +2226,20 @@
 
                       if (cwork[k] != 0.)
                         {
-                          if (ridx(cidx(kidx+1)-1) != k ||
-                              data(cidx(kidx+1)-1) == 0.)
+                          if (ridx (cidx (kidx+1)-1) != k ||
+                              data (cidx (kidx+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = cwork[k] / data(cidx(kidx+1)-1);
+                          Complex tmp = cwork[k] / data (cidx (kidx+1)-1);
                           cwork[k] = tmp;
-                          for (octave_idx_type i = cidx(kidx);
-                               i < cidx(kidx+1)-1; i++)
+                          for (octave_idx_type i = cidx (kidx);
+                               i < cidx (kidx+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              cwork[iidx] = cwork[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              cwork[iidx] = cwork[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -2265,20 +2265,20 @@
 
                           if (work[k] != 0.)
                             {
-                              double tmp = work[k] / data(cidx(iidx+1)-1);
+                              double tmp = work[k] / data (cidx (iidx+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(iidx);
-                                   i < cidx(iidx+1)-1; i++)
+                              for (octave_idx_type i = cidx (iidx);
+                                   i < cidx (iidx+1)-1; i++)
                                 {
-                                  octave_idx_type idx2 = ridx(i);
-                                  work[idx2] = work[idx2] - tmp * data(i);
+                                  octave_idx_type idx2 = ridx (i);
+                                  work[idx2] = work[idx2] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2303,19 +2303,19 @@
                     {
                       if (cwork[k] != 0.)
                         {
-                          if (ridx(cidx(k+1)-1) != k ||
-                              data(cidx(k+1)-1) == 0.)
+                          if (ridx (cidx (k+1)-1) != k ||
+                              data (cidx (k+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = cwork[k] / data(cidx(k+1)-1);
+                          Complex tmp = cwork[k] / data (cidx (k+1)-1);
                           cwork[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1)-1; i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              cwork[iidx] = cwork[iidx] - tmp  * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              cwork[iidx] = cwork[iidx] - tmp  * data (i);
                             }
                         }
                     }
@@ -2339,20 +2339,20 @@
                         {
                           if (work[k] != 0.)
                             {
-                              double tmp = work[k] / data(cidx(k+1)-1);
+                              double tmp = work[k] / data (cidx (k+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1)-1; i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1)-1; i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2437,8 +2437,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += fabs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += fabs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -2447,7 +2447,7 @@
           octave_idx_type b_nc = b.cols ();
           octave_idx_type b_nz = b.nnz ();
           retval = SparseComplexMatrix (nc, b_nc, b_nz);
-          retval.xcidx(0) = 0;
+          retval.xcidx (0) = 0;
           octave_idx_type ii = 0;
           octave_idx_type x_nz = b_nz;
 
@@ -2464,8 +2464,8 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     cwork[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    cwork[b.ridx(i)] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    cwork[b.ridx (i)] = b.data (i);
 
                   for (octave_idx_type k = nc-1; k >= 0; k--)
                     {
@@ -2473,20 +2473,20 @@
 
                       if (cwork[k] != 0.)
                         {
-                          if (ridx(cidx(kidx+1)-1) != k ||
-                              data(cidx(kidx+1)-1) == 0.)
+                          if (ridx (cidx (kidx+1)-1) != k ||
+                              data (cidx (kidx+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = cwork[k] / data(cidx(kidx+1)-1);
+                          Complex tmp = cwork[k] / data (cidx (kidx+1)-1);
                           cwork[k] = tmp;
-                          for (octave_idx_type i = cidx(kidx);
-                               i < cidx(kidx+1)-1; i++)
+                          for (octave_idx_type i = cidx (kidx);
+                               i < cidx (kidx+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              cwork[iidx] = cwork[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              cwork[iidx] = cwork[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -2509,10 +2509,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (cwork[rperm[i]] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = cwork[rperm[i]];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = cwork[rperm[i]];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -2534,20 +2534,20 @@
 
                           if (work[k] != 0.)
                             {
-                              double tmp = work[k] / data(cidx(iidx+1)-1);
+                              double tmp = work[k] / data (cidx (iidx+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(iidx);
-                                   i < cidx(iidx+1)-1; i++)
+                              for (octave_idx_type i = cidx (iidx);
+                                   i < cidx (iidx+1)-1; i++)
                                 {
-                                  octave_idx_type idx2 = ridx(i);
-                                  work[idx2] = work[idx2] - tmp * data(i);
+                                  octave_idx_type idx2 = ridx (i);
+                                  work[idx2] = work[idx2] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2564,26 +2564,26 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     cwork[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    cwork[b.ridx(i)] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    cwork[b.ridx (i)] = b.data (i);
 
                   for (octave_idx_type k = nc-1; k >= 0; k--)
                     {
                       if (cwork[k] != 0.)
                         {
-                          if (ridx(cidx(k+1)-1) != k ||
-                              data(cidx(k+1)-1) == 0.)
+                          if (ridx (cidx (k+1)-1) != k ||
+                              data (cidx (k+1)-1) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = cwork[k] / data(cidx(k+1)-1);
+                          Complex tmp = cwork[k] / data (cidx (k+1)-1);
                           cwork[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1)-1; i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1)-1; i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              cwork[iidx] = cwork[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              cwork[iidx] = cwork[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -2606,10 +2606,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (cwork[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = cwork[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = cwork[i];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -2629,20 +2629,20 @@
                         {
                           if (work[k] != 0.)
                             {
-                              double tmp = work[k] / data(cidx(k+1)-1);
+                              double tmp = work[k] / data (cidx (k+1)-1);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1)-1; i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1)-1; i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = 0; i < j+1; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2728,8 +2728,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += fabs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += fabs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -2756,34 +2756,34 @@
                           octave_idx_type minr = nr;
                           octave_idx_type mini = 0;
 
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
-                            if (perm[ridx(i)] < minr)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
+                            if (perm[ridx (i)] < minr)
                               {
-                                minr = perm[ridx(i)];
+                                minr = perm[ridx (i)];
                                 mini = i;
                               }
 
-                          if (minr != k || data(mini) == 0)
+                          if (minr != k || data (mini) == 0)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          double tmp = work[k] / data(mini);
+                          double tmp = work[k] / data (mini);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
                             {
                               if (i == mini)
                                 continue;
 
-                              octave_idx_type iidx = perm[ridx(i)];
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = perm[ridx (i)];
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
 
                   for (octave_idx_type i = 0; i < nc; i++)
-                    retval (i, j) = work[i];
+                    retval(i, j) = work[i];
                 }
 
               if (calc_cond)
@@ -2803,24 +2803,24 @@
                               octave_idx_type minr = nr;
                               octave_idx_type mini = 0;
 
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
-                                if (perm[ridx(i)] < minr)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
+                                if (perm[ridx (i)] < minr)
                                   {
-                                    minr = perm[ridx(i)];
+                                    minr = perm[ridx (i)];
                                     mini = i;
                                   }
 
-                              double tmp = work[k] / data(mini);
+                              double tmp = work[k] / data (mini);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
                                 {
                                   if (i == mini)
                                     continue;
 
-                                  octave_idx_type iidx = perm[ridx(i)];
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = perm[ridx (i)];
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
@@ -2828,7 +2828,7 @@
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2852,20 +2852,20 @@
                     {
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(k)) != k ||
-                              data(cidx(k)) == 0.)
+                          if (ridx (cidx (k)) != k ||
+                              data (cidx (k)) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          double tmp = work[k] / data(cidx(k));
+                          double tmp = work[k] / data (cidx (k));
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k)+1;
-                               i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k)+1;
+                               i < cidx (k+1); i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -2889,20 +2889,20 @@
 
                           if (work[k] != 0.)
                             {
-                              double tmp = work[k] / data(cidx(k));
+                              double tmp = work[k] / data (cidx (k));
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k)+1;
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k)+1;
+                                   i < cidx (k+1); i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -2987,8 +2987,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += fabs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += fabs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -2997,7 +2997,7 @@
           octave_idx_type b_nc = b.cols ();
           octave_idx_type b_nz = b.nnz ();
           retval = SparseMatrix (nc, b_nc, b_nz);
-          retval.xcidx(0) = 0;
+          retval.xcidx (0) = 0;
           octave_idx_type ii = 0;
           octave_idx_type x_nz = b_nz;
 
@@ -3010,8 +3010,8 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     work[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    work[perm[b.ridx(i)]] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    work[perm[b.ridx (i)]] = b.data (i);
 
                   for (octave_idx_type k = 0; k < nc; k++)
                     {
@@ -3020,28 +3020,28 @@
                           octave_idx_type minr = nr;
                           octave_idx_type mini = 0;
 
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
-                            if (perm[ridx(i)] < minr)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
+                            if (perm[ridx (i)] < minr)
                               {
-                                minr = perm[ridx(i)];
+                                minr = perm[ridx (i)];
                                 mini = i;
                               }
 
-                          if (minr != k || data(mini) == 0)
+                          if (minr != k || data (mini) == 0)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          double tmp = work[k] / data(mini);
+                          double tmp = work[k] / data (mini);
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
                             {
                               if (i == mini)
                                 continue;
 
-                              octave_idx_type iidx = perm[ridx(i)];
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = perm[ridx (i)];
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -3064,10 +3064,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (work[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = work[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = work[i];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -3089,24 +3089,24 @@
                               octave_idx_type minr = nr;
                               octave_idx_type mini = 0;
 
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
-                                if (perm[ridx(i)] < minr)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
+                                if (perm[ridx (i)] < minr)
                                   {
-                                    minr = perm[ridx(i)];
+                                    minr = perm[ridx (i)];
                                     mini = i;
                                   }
 
-                              double tmp = work[k] / data(mini);
+                              double tmp = work[k] / data (mini);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
                                 {
                                   if (i == mini)
                                     continue;
 
-                                  octave_idx_type iidx = perm[ridx(i)];
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = perm[ridx (i)];
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
@@ -3114,7 +3114,7 @@
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nr; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -3131,26 +3131,26 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     work[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    work[b.ridx(i)] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    work[b.ridx (i)] = b.data (i);
 
                   for (octave_idx_type k = 0; k < nc; k++)
                     {
                       if (work[k] != 0.)
                         {
-                          if (ridx(cidx(k)) != k ||
-                              data(cidx(k)) == 0.)
+                          if (ridx (cidx (k)) != k ||
+                              data (cidx (k)) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          double tmp = work[k] / data(cidx(k));
+                          double tmp = work[k] / data (cidx (k));
                           work[k] = tmp;
-                          for (octave_idx_type i = cidx(k)+1; i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k)+1; i < cidx (k+1); i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              work[iidx] = work[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              work[iidx] = work[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -3173,10 +3173,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (work[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = work[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = work[i];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -3196,20 +3196,20 @@
 
                           if (work[k] != 0.)
                             {
-                              double tmp = work[k] / data(cidx(k));
+                              double tmp = work[k] / data (cidx (k));
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k)+1;
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k)+1;
+                                   i < cidx (k+1); i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -3295,8 +3295,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += fabs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += fabs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -3322,34 +3322,34 @@
                           octave_idx_type minr = nr;
                           octave_idx_type mini = 0;
 
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
-                            if (perm[ridx(i)] < minr)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
+                            if (perm[ridx (i)] < minr)
                               {
-                                minr = perm[ridx(i)];
+                                minr = perm[ridx (i)];
                                 mini = i;
                               }
 
-                          if (minr != k || data(mini) == 0)
+                          if (minr != k || data (mini) == 0)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = cwork[k] / data(mini);
+                          Complex tmp = cwork[k] / data (mini);
                           cwork[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
                             {
                               if (i == mini)
                                 continue;
 
-                              octave_idx_type iidx = perm[ridx(i)];
-                              cwork[iidx] = cwork[iidx] - tmp * data(i);
+                              octave_idx_type iidx = perm[ridx (i)];
+                              cwork[iidx] = cwork[iidx] - tmp * data (i);
                             }
                         }
                     }
 
                   for (octave_idx_type i = 0; i < nc; i++)
-                    retval (i, j) = cwork[i];
+                    retval(i, j) = cwork[i];
                 }
 
               if (calc_cond)
@@ -3370,24 +3370,24 @@
                               octave_idx_type minr = nr;
                               octave_idx_type mini = 0;
 
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
-                                if (perm[ridx(i)] < minr)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
+                                if (perm[ridx (i)] < minr)
                                   {
-                                    minr = perm[ridx(i)];
+                                    minr = perm[ridx (i)];
                                     mini = i;
                                   }
 
-                              double tmp = work[k] / data(mini);
+                              double tmp = work[k] / data (mini);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
                                 {
                                   if (i == mini)
                                     continue;
 
-                                  octave_idx_type iidx = perm[ridx(i)];
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = perm[ridx (i)];
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
@@ -3395,7 +3395,7 @@
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -3420,19 +3420,19 @@
                     {
                       if (cwork[k] != 0.)
                         {
-                          if (ridx(cidx(k)) != k ||
-                              data(cidx(k)) == 0.)
+                          if (ridx (cidx (k)) != k ||
+                              data (cidx (k)) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = cwork[k] / data(cidx(k));
+                          Complex tmp = cwork[k] / data (cidx (k));
                           cwork[k] = tmp;
-                          for (octave_idx_type i = cidx(k)+1; i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k)+1; i < cidx (k+1); i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              cwork[iidx] = cwork[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              cwork[iidx] = cwork[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -3457,20 +3457,20 @@
 
                           if (work[k] != 0.)
                             {
-                              double tmp = work[k] / data(cidx(k));
+                              double tmp = work[k] / data (cidx (k));
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k)+1;
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k)+1;
+                                   i < cidx (k+1); i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -3555,8 +3555,8 @@
               for (octave_idx_type j = 0; j < nc; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += fabs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += fabs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -3565,7 +3565,7 @@
           octave_idx_type b_nc = b.cols ();
           octave_idx_type b_nz = b.nnz ();
           retval = SparseComplexMatrix (nc, b_nc, b_nz);
-          retval.xcidx(0) = 0;
+          retval.xcidx (0) = 0;
           octave_idx_type ii = 0;
           octave_idx_type x_nz = b_nz;
 
@@ -3578,8 +3578,8 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     cwork[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    cwork[perm[b.ridx(i)]] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    cwork[perm[b.ridx (i)]] = b.data (i);
 
                   for (octave_idx_type k = 0; k < nc; k++)
                     {
@@ -3588,28 +3588,28 @@
                           octave_idx_type minr = nr;
                           octave_idx_type mini = 0;
 
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
-                            if (perm[ridx(i)] < minr)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
+                            if (perm[ridx (i)] < minr)
                               {
-                                minr = perm[ridx(i)];
+                                minr = perm[ridx (i)];
                                 mini = i;
                               }
 
-                          if (minr != k || data(mini) == 0)
+                          if (minr != k || data (mini) == 0)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = cwork[k] / data(mini);
+                          Complex tmp = cwork[k] / data (mini);
                           cwork[k] = tmp;
-                          for (octave_idx_type i = cidx(k); i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k); i < cidx (k+1); i++)
                             {
                               if (i == mini)
                                 continue;
 
-                              octave_idx_type iidx = perm[ridx(i)];
-                              cwork[iidx] = cwork[iidx] - tmp * data(i);
+                              octave_idx_type iidx = perm[ridx (i)];
+                              cwork[iidx] = cwork[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -3632,10 +3632,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (cwork[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = cwork[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = cwork[i];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -3658,24 +3658,24 @@
                               octave_idx_type minr = nr;
                               octave_idx_type mini = 0;
 
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
-                                if (perm[ridx(i)] < minr)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
+                                if (perm[ridx (i)] < minr)
                                   {
-                                    minr = perm[ridx(i)];
+                                    minr = perm[ridx (i)];
                                     mini = i;
                                   }
 
-                              double tmp = work[k] / data(mini);
+                              double tmp = work[k] / data (mini);
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k);
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k);
+                                   i < cidx (k+1); i++)
                                 {
                                   if (i == mini)
                                     continue;
 
-                                  octave_idx_type iidx = perm[ridx(i)];
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = perm[ridx (i)];
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
@@ -3683,7 +3683,7 @@
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -3700,26 +3700,26 @@
                 {
                   for (octave_idx_type i = 0; i < nm; i++)
                     cwork[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    cwork[b.ridx(i)] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    cwork[b.ridx (i)] = b.data (i);
 
                   for (octave_idx_type k = 0; k < nc; k++)
                     {
                       if (cwork[k] != 0.)
                         {
-                          if (ridx(cidx(k)) != k ||
-                              data(cidx(k)) == 0.)
+                          if (ridx (cidx (k)) != k ||
+                              data (cidx (k)) == 0.)
                             {
                               err = -2;
                               goto triangular_error;
                             }
 
-                          Complex tmp = cwork[k] / data(cidx(k));
+                          Complex tmp = cwork[k] / data (cidx (k));
                           cwork[k] = tmp;
-                          for (octave_idx_type i = cidx(k)+1; i < cidx(k+1); i++)
+                          for (octave_idx_type i = cidx (k)+1; i < cidx (k+1); i++)
                             {
-                              octave_idx_type iidx = ridx(i);
-                              cwork[iidx] = cwork[iidx] - tmp * data(i);
+                              octave_idx_type iidx = ridx (i);
+                              cwork[iidx] = cwork[iidx] - tmp * data (i);
                             }
                         }
                     }
@@ -3742,10 +3742,10 @@
                   for (octave_idx_type i = 0; i < nc; i++)
                     if (cwork[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = cwork[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = cwork[i];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -3766,20 +3766,20 @@
 
                           if (work[k] != 0.)
                             {
-                              double tmp = work[k] / data(cidx(k));
+                              double tmp = work[k] / data (cidx (k));
                               work[k] = tmp;
-                              for (octave_idx_type i = cidx(k)+1;
-                                   i < cidx(k+1); i++)
+                              for (octave_idx_type i = cidx (k)+1;
+                                   i < cidx (k+1); i++)
                                 {
-                                  octave_idx_type iidx = ridx(i);
-                                  work[iidx] = work[iidx] - tmp * data(i);
+                                  octave_idx_type iidx = ridx (i);
+                                  work[iidx] = work[iidx] - tmp * data (i);
                                 }
                             }
                         }
                       double atmp = 0;
                       for (octave_idx_type i = j; i < nc; i++)
                         {
-                          atmp += fabs(work[i]);
+                          atmp += fabs (work[i]);
                           work[i] = 0.;
                         }
                       if (atmp > ainvnorm)
@@ -3864,11 +3864,11 @@
 
               for (octave_idx_type j = 0; j < nc-1; j++)
                 {
-                  D[j] = data(ii++);
-                  DL[j] = data(ii);
+                  D[j] = data (ii++);
+                  DL[j] = data (ii);
                   ii += 2;
                 }
-              D[nc-1] = data(ii);
+              D[nc-1] = data (ii);
             }
           else
             {
@@ -3880,21 +3880,21 @@
                 }
 
               for (octave_idx_type j = 0; j < nc; j++)
-                for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+                for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
                   {
-                    if (ridx(i) == j)
-                      D[j] = data(i);
-                    else if (ridx(i) == j + 1)
-                      DL[j] = data(i);
+                    if (ridx (i) == j)
+                      D[j] = data (i);
+                    else if (ridx (i) == j + 1)
+                      DL[j] = data (i);
                   }
             }
 
-          octave_idx_type b_nc = b.cols();
+          octave_idx_type b_nc = b.cols ();
           retval = b;
           double *result = retval.fortran_vec ();
 
           F77_XFCN (dptsv, DPTSV, (nr, b_nc, D, DL, result,
-                                   b.rows(), err));
+                                   b.rows (), err));
 
           if (err != 0)
             {
@@ -3918,11 +3918,11 @@
 
               for (octave_idx_type j = 0; j < nc-1; j++)
                 {
-                  D[j] = data(ii++);
-                  DL[j] = data(ii++);
-                  DU[j] = data(ii++);
-                }
-              D[nc-1] = data(ii);
+                  D[j] = data (ii++);
+                  DL[j] = data (ii++);
+                  DU[j] = data (ii++);
+                }
+              D[nc-1] = data (ii);
             }
           else
             {
@@ -3935,23 +3935,23 @@
                 }
 
               for (octave_idx_type j = 0; j < nc; j++)
-                for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+                for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
                   {
-                    if (ridx(i) == j)
-                      D[j] = data(i);
-                    else if (ridx(i) == j + 1)
-                      DL[j] = data(i);
-                    else if (ridx(i) == j - 1)
-                      DU[j-1] = data(i);
+                    if (ridx (i) == j)
+                      D[j] = data (i);
+                    else if (ridx (i) == j + 1)
+                      DL[j] = data (i);
+                    else if (ridx (i) == j - 1)
+                      DU[j-1] = data (i);
                   }
             }
 
-          octave_idx_type b_nc = b.cols();
+          octave_idx_type b_nc = b.cols ();
           retval = b;
           double *result = retval.fortran_vec ();
 
           F77_XFCN (dgtsv, DGTSV, (nr, b_nc, DL, D, DU, result,
-                                   b.rows(), err));
+                                   b.rows (), err));
 
           if (err != 0)
             {
@@ -4021,11 +4021,11 @@
 
               for (octave_idx_type j = 0; j < nc-1; j++)
                 {
-                  D[j] = data(ii++);
-                  DL[j] = data(ii++);
-                  DU[j] = data(ii++);
-                }
-              D[nc-1] = data(ii);
+                  D[j] = data (ii++);
+                  DL[j] = data (ii++);
+                  DU[j] = data (ii++);
+                }
+              D[nc-1] = data (ii);
             }
           else
             {
@@ -4038,14 +4038,14 @@
                 }
 
               for (octave_idx_type j = 0; j < nc; j++)
-                for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+                for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
                   {
-                    if (ridx(i) == j)
-                      D[j] = data(i);
-                    else if (ridx(i) == j + 1)
-                      DL[j] = data(i);
-                    else if (ridx(i) == j - 1)
-                      DU[j-1] = data(i);
+                    if (ridx (i) == j)
+                      D[j] = data (i);
+                    else if (ridx (i) == j + 1)
+                      DL[j] = data (i);
+                    else if (ridx (i) == j - 1)
+                      DU[j-1] = data (i);
                   }
             }
 
@@ -4073,7 +4073,7 @@
               volatile octave_idx_type x_nz = b.nnz ();
               octave_idx_type b_nc = b.cols ();
               retval = SparseMatrix (nr, b_nc, x_nz);
-              retval.xcidx(0) = 0;
+              retval.xcidx (0) = 0;
               volatile octave_idx_type ii = 0;
 
               OCTAVE_LOCAL_BUFFER (double, work, nr);
@@ -4082,8 +4082,8 @@
                 {
                   for (octave_idx_type i = 0; i < nr; i++)
                     work[i] = 0.;
-                  for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
-                    work[b.ridx(i)] = b.data(i);
+                  for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
+                    work[b.ridx (i)] = b.data (i);
 
                   F77_XFCN (dgttrs, DGTTRS,
                             (F77_CONST_CHAR_ARG2 (&job, 1),
@@ -4109,10 +4109,10 @@
                   for (octave_idx_type i = 0; i < nr; i++)
                     if (work[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) = work[i];
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) = work[i];
                       }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -4162,11 +4162,11 @@
 
               for (octave_idx_type j = 0; j < nc-1; j++)
                 {
-                  D[j] = data(ii++);
-                  DL[j] = data(ii);
+                  D[j] = data (ii++);
+                  DL[j] = data (ii);
                   ii += 2;
                 }
-              D[nc-1] = data(ii);
+              D[nc-1] = data (ii);
             }
           else
             {
@@ -4178,17 +4178,17 @@
                 }
 
               for (octave_idx_type j = 0; j < nc; j++)
-                for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+                for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
                   {
-                    if (ridx(i) == j)
-                      D[j] = data(i);
-                    else if (ridx(i) == j + 1)
-                      DL[j] = data(i);
+                    if (ridx (i) == j)
+                      D[j] = data (i);
+                    else if (ridx (i) == j + 1)
+                      DL[j] = data (i);
                   }
             }
 
           octave_idx_type b_nr = b.rows ();
-          octave_idx_type b_nc = b.cols();
+          octave_idx_type b_nc = b.cols ();
           rcond = 1.;
 
           retval = b;
@@ -4217,11 +4217,11 @@
 
               for (octave_idx_type j = 0; j < nc-1; j++)
                 {
-                  D[j] = data(ii++);
-                  DL[j] = data(ii++);
-                  DU[j] = data(ii++);
-                }
-              D[nc-1] = data(ii);
+                  D[j] = data (ii++);
+                  DL[j] = data (ii++);
+                  DU[j] = data (ii++);
+                }
+              D[nc-1] = data (ii);
             }
           else
             {
@@ -4234,19 +4234,19 @@
                 }
 
               for (octave_idx_type j = 0; j < nc; j++)
-                for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+                for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
                   {
-                    if (ridx(i) == j)
-                      D[j] = data(i);
-                    else if (ridx(i) == j + 1)
-                      DL[j] = data(i);
-                    else if (ridx(i) == j - 1)
-                      DU[j-1] = data(i);
+                    if (ridx (i) == j)
+                      D[j] = data (i);
+                    else if (ridx (i) == j + 1)
+                      DL[j] = data (i);
+                    else if (ridx (i) == j - 1)
+                      DU[j-1] = data (i);
                   }
             }
 
-          octave_idx_type b_nr = b.rows();
-          octave_idx_type b_nc = b.cols();
+          octave_idx_type b_nr = b.rows ();
+          octave_idx_type b_nc = b.cols ();
           rcond = 1.;
 
           retval = b;
@@ -4320,11 +4320,11 @@
 
               for (octave_idx_type j = 0; j < nc-1; j++)
                 {
-                  D[j] = data(ii++);
-                  DL[j] = data(ii++);
-                  DU[j] = data(ii++);
-                }
-              D[nc-1] = data(ii);
+                  D[j] = data (ii++);
+                  DL[j] = data (ii++);
+                  DU[j] = data (ii++);
+                }
+              D[nc-1] = data (ii);
             }
           else
             {
@@ -4337,14 +4337,14 @@
                 }
 
               for (octave_idx_type j = 0; j < nc; j++)
-                for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+                for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
                   {
-                    if (ridx(i) == j)
-                      D[j] = data(i);
-                    else if (ridx(i) == j + 1)
-                      DL[j] = data(i);
-                    else if (ridx(i) == j - 1)
-                      DU[j-1] = data(i);
+                    if (ridx (i) == j)
+                      D[j] = data (i);
+                    else if (ridx (i) == j + 1)
+                      DL[j] = data (i);
+                    else if (ridx (i) == j - 1)
+                      DU[j-1] = data (i);
                   }
             }
 
@@ -4379,7 +4379,7 @@
               volatile octave_idx_type ii = 0;
               retval = SparseComplexMatrix (b_nr, b_nc, x_nz);
 
-              retval.xcidx(0) = 0;
+              retval.xcidx (0) = 0;
               for (volatile octave_idx_type j = 0; j < b_nc; j++)
                 {
 
@@ -4438,12 +4438,12 @@
                   for (octave_idx_type i = 0; i < nr; i++)
                     if (Bx[i] != 0. || Bz[i] != 0.)
                       {
-                        retval.xridx(ii) = i;
-                        retval.xdata(ii++) =
+                        retval.xridx (ii) = i;
+                        retval.xdata (ii++) =
                           Complex (Bx[i], Bz[i]);
                       }
 
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -4496,17 +4496,17 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
               {
                 octave_idx_type ri = ridx (i);
                 if (ri >= j)
-                  m_band(ri - j, j) = data(i);
+                  m_band(ri - j, j) = data (i);
               }
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
           if (calc_cond)
-            anorm = m_band.abs().sum().row(0).max();
+            anorm = m_band.abs ().sum ().row (0).max ();
 
           char job = 'L';
           F77_XFCN (dpbtrf, DPBTRF, (F77_CONST_CHAR_ARG2 (&job, 1),
@@ -4570,7 +4570,7 @@
                   F77_XFCN (dpbtrs, DPBTRS,
                             (F77_CONST_CHAR_ARG2 (&job, 1),
                              nr, n_lower, b_nc, tmp_data,
-                             ldm, result, b.rows(), err
+                             ldm, result, b.rows (), err
                              F77_CHAR_ARG_LEN (1)));
 
                   if (err != 0)
@@ -4603,8 +4603,8 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-              m_band(ridx(i) - j + n_lower + n_upper, j) = data(i);
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+              m_band(ridx (i) - j + n_lower + n_upper, j) = data (i);
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
@@ -4613,8 +4613,8 @@
               for (octave_idx_type j = 0; j < nr; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += fabs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += fabs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -4693,7 +4693,7 @@
                   F77_XFCN (dgbtrs, DGBTRS,
                             (F77_CONST_CHAR_ARG2 (&job, 1),
                              nr, n_lower, n_upper, b_nc, tmp_data,
-                             ldm, pipvt, result, b.rows(), err
+                             ldm, pipvt, result, b.rows (), err
                              F77_CHAR_ARG_LEN (1)));
                 }
             }
@@ -4746,17 +4746,17 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
               {
                 octave_idx_type ri = ridx (i);
                 if (ri >= j)
-                  m_band(ri - j, j) = data(i);
+                  m_band(ri - j, j) = data (i);
               }
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
           if (calc_cond)
-            anorm = m_band.abs().sum().row(0).max();
+            anorm = m_band.abs ().sum ().row (0).max ();
 
           char job = 'L';
           F77_XFCN (dpbtrf, DPBTRF, (F77_CONST_CHAR_ARG2 (&job, 1),
@@ -4820,7 +4820,7 @@
                   volatile octave_idx_type ii = 0;
                   retval = SparseMatrix (b_nr, b_nc, x_nz);
 
-                  retval.xcidx(0) = 0;
+                  retval.xcidx (0) = 0;
                   for (volatile octave_idx_type j = 0; j < b_nc; j++)
                     {
                       for (octave_idx_type i = 0; i < b_nr; i++)
@@ -4854,11 +4854,11 @@
                                   retval.change_capacity (sz);
                                   x_nz = sz;
                                 }
-                              retval.xdata(ii) = tmp;
-                              retval.xridx(ii++) = i;
+                              retval.xdata (ii) = tmp;
+                              retval.xridx (ii++) = i;
                             }
                         }
-                      retval.xcidx(j+1) = ii;
+                      retval.xcidx (j+1) = ii;
                     }
 
                   retval.maybe_compress ();
@@ -4886,8 +4886,8 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-              m_band(ridx(i) - j + n_lower + n_upper, j) = data(i);
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+              m_band(ridx (i) - j + n_lower + n_upper, j) = data (i);
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
@@ -4896,8 +4896,8 @@
               for (octave_idx_type j = 0; j < nr; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += fabs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += fabs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -4969,7 +4969,7 @@
                   volatile octave_idx_type x_nz = b.nnz ();
                   octave_idx_type b_nc = b.cols ();
                   retval = SparseMatrix (nr, b_nc, x_nz);
-                  retval.xcidx(0) = 0;
+                  retval.xcidx (0) = 0;
                   volatile octave_idx_type ii = 0;
 
                   OCTAVE_LOCAL_BUFFER (double, work, nr);
@@ -4978,9 +4978,9 @@
                     {
                       for (octave_idx_type i = 0; i < nr; i++)
                         work[i] = 0.;
-                      for (octave_idx_type i = b.cidx(j);
-                           i < b.cidx(j+1); i++)
-                        work[b.ridx(i)] = b.data(i);
+                      for (octave_idx_type i = b.cidx (j);
+                           i < b.cidx (j+1); i++)
+                        work[b.ridx (i)] = b.data (i);
 
                       F77_XFCN (dgbtrs, DGBTRS,
                                 (F77_CONST_CHAR_ARG2 (&job, 1),
@@ -5006,10 +5006,10 @@
                       for (octave_idx_type i = 0; i < nr; i++)
                         if (work[i] != 0.)
                           {
-                            retval.xridx(ii) = i;
-                            retval.xdata(ii++) = work[i];
+                            retval.xridx (ii) = i;
+                            retval.xdata (ii++) = work[i];
                           }
-                      retval.xcidx(j+1) = ii;
+                      retval.xcidx (j+1) = ii;
                     }
 
                   retval.maybe_compress ();
@@ -5064,17 +5064,17 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
               {
                 octave_idx_type ri = ridx (i);
                 if (ri >= j)
-                  m_band(ri - j, j) = data(i);
+                  m_band(ri - j, j) = data (i);
               }
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
           if (calc_cond)
-            anorm = m_band.abs().sum().row(0).max();
+            anorm = m_band.abs ().sum ().row (0).max ();
 
           char job = 'L';
           F77_XFCN (dpbtrf, DPBTRF, (F77_CONST_CHAR_ARG2 (&job, 1),
@@ -5164,7 +5164,7 @@
                       F77_XFCN (dpbtrs, DPBTRS,
                                 (F77_CONST_CHAR_ARG2 (&job, 1),
                                  nr, n_lower, 1, tmp_data,
-                                 ldm, Bz, b.rows(), err
+                                 ldm, Bz, b.rows (), err
                                  F77_CHAR_ARG_LEN (1)));
 
                       if (err != 0)
@@ -5176,7 +5176,7 @@
                         }
 
                       for (octave_idx_type i = 0; i < b_nr; i++)
-                        retval (i, j) = Complex (Bx[i], Bz[i]);
+                        retval(i, j) = Complex (Bx[i], Bz[i]);
                     }
                 }
             }
@@ -5202,8 +5202,8 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-              m_band(ridx(i) - j + n_lower + n_upper, j) = data(i);
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+              m_band(ridx (i) - j + n_lower + n_upper, j) = data (i);
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
@@ -5212,8 +5212,8 @@
               for (octave_idx_type j = 0; j < nr; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += fabs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += fabs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -5310,7 +5310,7 @@
                                  F77_CHAR_ARG_LEN (1)));
 
                       for (octave_idx_type i = 0; i < nr; i++)
-                        retval (i, j) = Complex (Bx[i], Bz[i]);
+                        retval(i, j) = Complex (Bx[i], Bz[i]);
                     }
                 }
             }
@@ -5363,17 +5363,17 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
               {
                 octave_idx_type ri = ridx (i);
                 if (ri >= j)
-                  m_band(ri - j, j) = data(i);
+                  m_band(ri - j, j) = data (i);
               }
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
           if (calc_cond)
-            anorm = m_band.abs().sum().row(0).max();
+            anorm = m_band.abs ().sum ().row (0).max ();
 
           char job = 'L';
           F77_XFCN (dpbtrf, DPBTRF, (F77_CONST_CHAR_ARG2 (&job, 1),
@@ -5441,7 +5441,7 @@
                   volatile octave_idx_type ii = 0;
                   retval = SparseComplexMatrix (b_nr, b_nc, x_nz);
 
-                  retval.xcidx(0) = 0;
+                  retval.xcidx (0) = 0;
                   for (volatile octave_idx_type j = 0; j < b_nc; j++)
                     {
 
@@ -5499,12 +5499,12 @@
                       for (octave_idx_type i = 0; i < nr; i++)
                         if (Bx[i] != 0. || Bz[i] != 0.)
                           {
-                            retval.xridx(ii) = i;
-                            retval.xdata(ii++) =
+                            retval.xridx (ii) = i;
+                            retval.xdata (ii++) =
                               Complex (Bx[i], Bz[i]);
                           }
 
-                      retval.xcidx(j+1) = ii;
+                      retval.xcidx (j+1) = ii;
                     }
 
                   retval.maybe_compress ();
@@ -5532,8 +5532,8 @@
             }
 
           for (octave_idx_type j = 0; j < nc; j++)
-            for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-              m_band(ridx(i) - j + n_lower + n_upper, j) = data(i);
+            for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+              m_band(ridx (i) - j + n_lower + n_upper, j) = data (i);
 
           // Calculate the norm of the matrix, for later use.
           double anorm;
@@ -5542,8 +5542,8 @@
               for (octave_idx_type j = 0; j < nr; j++)
                 {
                   double atmp = 0.;
-                  for (octave_idx_type i = cidx(j); i < cidx(j+1); i++)
-                    atmp += fabs(data(i));
+                  for (octave_idx_type i = cidx (j); i < cidx (j+1); i++)
+                    atmp += fabs (data (i));
                   if (atmp > anorm)
                     anorm = atmp;
                 }
@@ -5615,7 +5615,7 @@
                   volatile octave_idx_type x_nz = b.nnz ();
                   octave_idx_type b_nc = b.cols ();
                   retval = SparseComplexMatrix (nr, b_nc, x_nz);
-                  retval.xcidx(0) = 0;
+                  retval.xcidx (0) = 0;
                   volatile octave_idx_type ii = 0;
 
                   OCTAVE_LOCAL_BUFFER (double, Bx, nr);
@@ -5628,12 +5628,12 @@
                           Bx[i] = 0.;
                           Bz[i] = 0.;
                         }
-                      for (octave_idx_type i = b.cidx(j);
-                           i < b.cidx(j+1); i++)
+                      for (octave_idx_type i = b.cidx (j);
+                           i < b.cidx (j+1); i++)
                         {
-                          Complex c = b.data(i);
-                          Bx[b.ridx(i)] = std::real (c);
-                          Bz[b.ridx(i)] = std::imag (c);
+                          Complex c = b.data (i);
+                          Bx[b.ridx (i)] = std::real (c);
+                          Bz[b.ridx (i)] = std::imag (c);
                         }
 
                       F77_XFCN (dgbtrs, DGBTRS,
@@ -5666,11 +5666,11 @@
                       for (octave_idx_type i = 0; i < nr; i++)
                         if (Bx[i] != 0. || Bz[i] != 0.)
                           {
-                            retval.xridx(ii) = i;
-                            retval.xdata(ii++) =
+                            retval.xridx (ii) = i;
+                            retval.xdata (ii++) =
                               Complex (Bx[i], Bz[i]);
                           }
-                      retval.xcidx(j+1) = ii;
+                      retval.xcidx (j+1) = ii;
                     }
 
                   retval.maybe_compress ();
@@ -5853,13 +5853,13 @@
           A->nrow = nr;
           A->ncol = nc;
 
-          A->p = cidx();
-          A->i = ridx();
-          A->nzmax = nnz();
+          A->p = cidx ();
+          A->i = ridx ();
+          A->nzmax = nnz ();
           A->packed = true;
           A->sorted = true;
           A->nz = 0;
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
           A->itype = CHOLMOD_LONG;
 #else
           A->itype = CHOLMOD_INT;
@@ -5871,21 +5871,21 @@
           if (nr < 1)
             A->x = &dummy;
           else
-            A->x = data();
+            A->x = data ();
 
           cholmod_dense Bstore;
           cholmod_dense *B = &Bstore;
-          B->nrow = b.rows();
-          B->ncol = b.cols();
+          B->nrow = b.rows ();
+          B->ncol = b.cols ();
           B->d = B->nrow;
           B->nzmax = B->nrow * B->ncol;
           B->dtype = CHOLMOD_DOUBLE;
           B->xtype = CHOLMOD_REAL;
-          if (nc < 1 || b.cols() < 1)
+          if (nc < 1 || b.cols () < 1)
             B->x = &dummy;
           else
             // We won't alter it, honest :-)
-            B->x = const_cast<double *>(b.fortran_vec());
+            B->x = const_cast<double *>(b.fortran_vec ());
 
           cholmod_factor *L;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -5930,12 +5930,12 @@
               X = CHOLMOD_NAME(solve) (CHOLMOD_A, L, B, cm);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
 
-              retval.resize (b.rows (), b.cols());
-              for (octave_idx_type j = 0; j < b.cols(); j++)
-                {
-                  octave_idx_type jr = j * b.rows();
-                  for (octave_idx_type i = 0; i < b.rows(); i++)
-                    retval.xelem(i,j) = static_cast<double *>(X->x)[jr + i];
+              retval.resize (b.rows (), b.cols ());
+              for (octave_idx_type j = 0; j < b.cols (); j++)
+                {
+                  octave_idx_type jr = j * b.rows ();
+                  for (octave_idx_type i = 0; i < b.rows (); i++)
+                    retval.xelem (i,j) = static_cast<double *>(X->x)[jr + i];
                 }
 
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -5965,7 +5965,7 @@
           if (err == 0)
             {
               const double *Bx = b.fortran_vec ();
-              retval.resize (b.rows (), b.cols());
+              retval.resize (b.rows (), b.cols ());
               double *result = retval.fortran_vec ();
               octave_idx_type b_nr = b.rows ();
               octave_idx_type b_nc = b.cols ();
@@ -6069,13 +6069,13 @@
           A->nrow = nr;
           A->ncol = nc;
 
-          A->p = cidx();
-          A->i = ridx();
-          A->nzmax = nnz();
+          A->p = cidx ();
+          A->i = ridx ();
+          A->nzmax = nnz ();
           A->packed = true;
           A->sorted = true;
           A->nz = 0;
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
           A->itype = CHOLMOD_LONG;
 #else
           A->itype = CHOLMOD_INT;
@@ -6087,19 +6087,19 @@
           if (nr < 1)
             A->x = &dummy;
           else
-            A->x = data();
+            A->x = data ();
 
           cholmod_sparse Bstore;
           cholmod_sparse *B = &Bstore;
-          B->nrow = b.rows();
-          B->ncol = b.cols();
-          B->p = b.cidx();
-          B->i = b.ridx();
-          B->nzmax = b.nnz();
+          B->nrow = b.rows ();
+          B->ncol = b.cols ();
+          B->p = b.cidx ();
+          B->i = b.ridx ();
+          B->nzmax = b.nnz ();
           B->packed = true;
           B->sorted = true;
           B->nz = 0;
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
           B->itype = CHOLMOD_LONG;
 #else
           B->itype = CHOLMOD_INT;
@@ -6108,10 +6108,10 @@
           B->stype = 0;
           B->xtype = CHOLMOD_REAL;
 
-          if (b.rows() < 1 || b.cols() < 1)
+          if (b.rows () < 1 || b.cols () < 1)
             B->x = &dummy;
           else
-            B->x = b.data();
+            B->x = b.data ();
 
           cholmod_factor *L;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -6160,12 +6160,12 @@
                                      static_cast<octave_idx_type>(X->nzmax));
               for (octave_idx_type j = 0;
                    j <= static_cast<octave_idx_type>(X->ncol); j++)
-                retval.xcidx(j) = static_cast<octave_idx_type *>(X->p)[j];
+                retval.xcidx (j) = static_cast<octave_idx_type *>(X->p)[j];
               for (octave_idx_type j = 0;
                    j < static_cast<octave_idx_type>(X->nzmax); j++)
                 {
-                  retval.xridx(j) = static_cast<octave_idx_type *>(X->i)[j];
-                  retval.xdata(j) = static_cast<double *>(X->x)[j];
+                  retval.xridx (j) = static_cast<octave_idx_type *>(X->i)[j];
+                  retval.xdata (j) = static_cast<double *>(X->x)[j];
                 }
 
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -6212,7 +6212,7 @@
               octave_idx_type ii = 0;
               retval = SparseMatrix (b_nr, b_nc, x_nz);
 
-              retval.xcidx(0) = 0;
+              retval.xcidx (0) = 0;
               for (octave_idx_type j = 0; j < b_nc; j++)
                 {
 
@@ -6247,11 +6247,11 @@
                               retval.change_capacity (sz);
                               x_nz = sz;
                             }
-                          retval.xdata(ii) = tmp;
-                          retval.xridx(ii++) = i;
+                          retval.xdata (ii) = tmp;
+                          retval.xridx (ii++) = i;
                         }
                     }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -6331,13 +6331,13 @@
           A->nrow = nr;
           A->ncol = nc;
 
-          A->p = cidx();
-          A->i = ridx();
-          A->nzmax = nnz();
+          A->p = cidx ();
+          A->i = ridx ();
+          A->nzmax = nnz ();
           A->packed = true;
           A->sorted = true;
           A->nz = 0;
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
           A->itype = CHOLMOD_LONG;
 #else
           A->itype = CHOLMOD_INT;
@@ -6349,21 +6349,21 @@
           if (nr < 1)
             A->x = &dummy;
           else
-            A->x = data();
+            A->x = data ();
 
           cholmod_dense Bstore;
           cholmod_dense *B = &Bstore;
-          B->nrow = b.rows();
-          B->ncol = b.cols();
+          B->nrow = b.rows ();
+          B->ncol = b.cols ();
           B->d = B->nrow;
           B->nzmax = B->nrow * B->ncol;
           B->dtype = CHOLMOD_DOUBLE;
           B->xtype = CHOLMOD_COMPLEX;
-          if (nc < 1 || b.cols() < 1)
+          if (nc < 1 || b.cols () < 1)
             B->x = &dummy;
           else
             // We won't alter it, honest :-)
-            B->x = const_cast<Complex *>(b.fortran_vec());
+            B->x = const_cast<Complex *>(b.fortran_vec ());
 
           cholmod_factor *L;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -6407,12 +6407,12 @@
               X = CHOLMOD_NAME(solve) (CHOLMOD_A, L, B, cm);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
 
-              retval.resize (b.rows (), b.cols());
-              for (octave_idx_type j = 0; j < b.cols(); j++)
-                {
-                  octave_idx_type jr = j * b.rows();
-                  for (octave_idx_type i = 0; i < b.rows(); i++)
-                    retval.xelem(i,j) = static_cast<Complex *>(X->x)[jr + i];
+              retval.resize (b.rows (), b.cols ());
+              for (octave_idx_type j = 0; j < b.cols (); j++)
+                {
+                  octave_idx_type jr = j * b.rows ();
+                  for (octave_idx_type i = 0; i < b.rows (); i++)
+                    retval.xelem (i,j) = static_cast<Complex *>(X->x)[jr + i];
                 }
 
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -6487,7 +6487,7 @@
                     }
 
                   for (octave_idx_type i = 0; i < b_nr; i++)
-                    retval (i, j) = Complex (Xx[i], Xz[i]);
+                    retval(i, j) = Complex (Xx[i], Xz[i]);
                 }
 
               UMFPACK_DNAME (report_info) (control, info);
@@ -6565,13 +6565,13 @@
           A->nrow = nr;
           A->ncol = nc;
 
-          A->p = cidx();
-          A->i = ridx();
-          A->nzmax = nnz();
+          A->p = cidx ();
+          A->i = ridx ();
+          A->nzmax = nnz ();
           A->packed = true;
           A->sorted = true;
           A->nz = 0;
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
           A->itype = CHOLMOD_LONG;
 #else
           A->itype = CHOLMOD_INT;
@@ -6583,19 +6583,19 @@
           if (nr < 1)
             A->x = &dummy;
           else
-            A->x = data();
+            A->x = data ();
 
           cholmod_sparse Bstore;
           cholmod_sparse *B = &Bstore;
-          B->nrow = b.rows();
-          B->ncol = b.cols();
-          B->p = b.cidx();
-          B->i = b.ridx();
-          B->nzmax = b.nnz();
+          B->nrow = b.rows ();
+          B->ncol = b.cols ();
+          B->p = b.cidx ();
+          B->i = b.ridx ();
+          B->nzmax = b.nnz ();
           B->packed = true;
           B->sorted = true;
           B->nz = 0;
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
           B->itype = CHOLMOD_LONG;
 #else
           B->itype = CHOLMOD_INT;
@@ -6604,10 +6604,10 @@
           B->stype = 0;
           B->xtype = CHOLMOD_COMPLEX;
 
-          if (b.rows() < 1 || b.cols() < 1)
+          if (b.rows () < 1 || b.cols () < 1)
             B->x = &dummy;
           else
-            B->x = b.data();
+            B->x = b.data ();
 
           cholmod_factor *L;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -6657,12 +6657,12 @@
                  static_cast<octave_idx_type>(X->nzmax));
               for (octave_idx_type j = 0;
                    j <= static_cast<octave_idx_type>(X->ncol); j++)
-                retval.xcidx(j) = static_cast<octave_idx_type *>(X->p)[j];
+                retval.xcidx (j) = static_cast<octave_idx_type *>(X->p)[j];
               for (octave_idx_type j = 0;
                    j < static_cast<octave_idx_type>(X->nzmax); j++)
                 {
-                  retval.xridx(j) = static_cast<octave_idx_type *>(X->i)[j];
-                  retval.xdata(j) = static_cast<Complex *>(X->x)[j];
+                  retval.xridx (j) = static_cast<octave_idx_type *>(X->i)[j];
+                  retval.xdata (j) = static_cast<Complex *>(X->x)[j];
                 }
 
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
@@ -6712,7 +6712,7 @@
               OCTAVE_LOCAL_BUFFER (double, Xx, b_nr);
               OCTAVE_LOCAL_BUFFER (double, Xz, b_nr);
 
-              retval.xcidx(0) = 0;
+              retval.xcidx (0) = 0;
               for (octave_idx_type j = 0; j < b_nc; j++)
                 {
                   for (octave_idx_type i = 0; i < b_nr; i++)
@@ -6754,11 +6754,11 @@
                               retval.change_capacity (sz);
                               x_nz = sz;
                             }
-                          retval.xdata(ii) = tmp;
-                          retval.xridx(ii++) = i;
+                          retval.xdata (ii) = tmp;
+                          retval.xridx (ii++) = i;
                         }
                     }
-                  retval.xcidx(j+1) = ii;
+                  retval.xcidx (j+1) = ii;
                 }
 
               retval.maybe_compress ();
@@ -6970,7 +6970,7 @@
       return ComplexMatrix ();
     }
 
-  if (singular_fallback && mattype.type(false) == MatrixType::Rectangular)
+  if (singular_fallback && mattype.type (false) == MatrixType::Rectangular)
     {
       rcond = 1.;
 #ifdef USE_QRSOLVE
@@ -7038,7 +7038,7 @@
       return SparseComplexMatrix ();
     }
 
-  if (singular_fallback && mattype.type(false) == MatrixType::Rectangular)
+  if (singular_fallback && mattype.type (false) == MatrixType::Rectangular)
     {
       rcond = 1.;
 #ifdef USE_QRSOLVE
@@ -7418,17 +7418,7 @@
 bool
 SparseMatrix::too_large_for_float (void) const
 {
-  octave_idx_type nel = nnz ();
-
-  for (octave_idx_type i = 0; i < nel; i++)
-    {
-      double val = data (i);
-
-      if (val > FLT_MAX || val < FLT_MIN)
-        return true;
-    }
-
-  return false;
+  return test_any (xtoo_large_for_float);
 }
 
 SparseBoolMatrix
@@ -7451,12 +7441,12 @@
     {
       for (octave_idx_type j = 0; j < nr; j++)
         {
-          if (jj < cidx(i+1) && ridx(jj) == j)
+          if (jj < cidx (i+1) && ridx (jj) == j)
             jj++;
           else
             {
-              r.data(ii) = true;
-              r.ridx(ii++) = j;
+              r.data (ii) = true;
+              r.ridx (ii++) = j;
             }
         }
       r.cidx (i+1) = ii;
@@ -7495,12 +7485,12 @@
 SparseMatrix
 SparseMatrix::prod (int dim) const
 {
-  if ((rows() == 1 && dim == -1) || dim == 1)
-    return transpose (). prod (0). transpose();
+  if ((rows () == 1 && dim == -1) || dim == 1)
+    return transpose (). prod (0). transpose ();
   else
     {
       SPARSE_REDUCTION_OP (SparseMatrix, double, *=,
-                           (cidx(j+1) - cidx(j) < nr ? 0.0 : 1.0), 1.0);
+                           (cidx (j+1) - cidx (j) < nr ? 0.0 : 1.0), 1.0);
     }
 }
 
@@ -7515,7 +7505,7 @@
 {
 #define ROW_EXPR \
   double d = data (i); \
-  tmp[ridx(i)] += d * d
+  tmp[ridx (i)] += d * d
 
 #define COL_EXPR \
   double d = data (i); \
@@ -7536,7 +7526,7 @@
   SparseMatrix retval (*this);
 
   for (octave_idx_type i = 0; i < nz; i++)
-    retval.data(i) = fabs(retval.data(i));
+    retval.data (i) = fabs (retval.data (i));
 
   return retval;
 }
@@ -7563,10 +7553,10 @@
    for (octave_idx_type j = 0; j < nc; j++)
      {
        octave_quit ();
-       for (octave_idx_type i = a.cidx(j); i < a.cidx(j+1); i++)
+       for (octave_idx_type i = a.cidx (j); i < a.cidx (j+1); i++)
          {
-           os << a.ridx(i) + 1 << " "  << j + 1 << " ";
-           octave_write_double (os, a.data(i));
+           os << a.ridx (i) + 1 << " "  << j + 1 << " ";
+           octave_write_double (os, a.data (i));
            os << "\n";
          }
      }
@@ -7712,14 +7702,14 @@
     {
       result = SparseMatrix (nr, nc, d);
       for (octave_idx_type j = 0; j < nc; j++)
-        for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++)
+        for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++)
           {
             double tmp = xmin (d, m.data (i));
             if (tmp != 0.)
               {
-                octave_idx_type idx = m.ridx(i) + j * nr;
-                result.xdata(idx) = tmp;
-                result.xridx(idx) = m.ridx(i);
+                octave_idx_type idx = m.ridx (i) + j * nr;
+                result.xdata (idx) = tmp;
+                result.xridx (idx) = m.ridx (i);
               }
           }
     }
@@ -7727,27 +7717,27 @@
     {
       octave_idx_type nel = 0;
       for (octave_idx_type j = 0; j < nc; j++)
-        for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++)
+        for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++)
           if (xmin (d, m.data (i)) != 0.)
             nel++;
 
       result = SparseMatrix (nr, nc, nel);
 
       octave_idx_type ii = 0;
-      result.xcidx(0) = 0;
+      result.xcidx (0) = 0;
       for (octave_idx_type j = 0; j < nc; j++)
         {
-          for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++)
+          for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++)
             {
               double tmp = xmin (d, m.data (i));
 
               if (tmp != 0.)
                 {
-                  result.xdata(ii) = tmp;
-                  result.xridx(ii++) = m.ridx(i);
-                }
-            }
-          result.xcidx(j+1) = ii;
+                  result.xdata (ii) = tmp;
+                  result.xridx (ii++) = m.ridx (i);
+                }
+            }
+          result.xcidx (j+1) = ii;
         }
     }
 
@@ -7765,7 +7755,7 @@
 {
   SparseMatrix r;
 
-  if ((a.rows() == b.rows()) && (a.cols() == b.cols()))
+  if ((a.rows () == b.rows ()) && (a.cols () == b.cols ()))
     {
       octave_idx_type a_nr = a.rows ();
       octave_idx_type a_nc = a.cols ();
@@ -7783,38 +7773,38 @@
           r.cidx (0) = 0;
           for (octave_idx_type i = 0 ; i < a_nc ; i++)
             {
-              octave_idx_type  ja = a.cidx(i);
-              octave_idx_type  ja_max = a.cidx(i+1);
+              octave_idx_type  ja = a.cidx (i);
+              octave_idx_type  ja_max = a.cidx (i+1);
               bool ja_lt_max= ja < ja_max;
 
-              octave_idx_type  jb = b.cidx(i);
-              octave_idx_type  jb_max = b.cidx(i+1);
+              octave_idx_type  jb = b.cidx (i);
+              octave_idx_type  jb_max = b.cidx (i+1);
               bool jb_lt_max = jb < jb_max;
 
               while (ja_lt_max || jb_lt_max )
                 {
                   octave_quit ();
                   if ((! jb_lt_max) ||
-                      (ja_lt_max && (a.ridx(ja) < b.ridx(jb))))
+                      (ja_lt_max && (a.ridx (ja) < b.ridx (jb))))
                     {
-                      double tmp = xmin (a.data(ja), 0.);
+                      double tmp = xmin (a.data (ja), 0.);
                       if (tmp != 0.)
                         {
-                          r.ridx(jx) = a.ridx(ja);
-                          r.data(jx) = tmp;
+                          r.ridx (jx) = a.ridx (ja);
+                          r.data (jx) = tmp;
                           jx++;
                         }
                       ja++;
                       ja_lt_max= ja < ja_max;
                     }
                   else if (( !ja_lt_max ) ||
-                           (jb_lt_max && (b.ridx(jb) < a.ridx(ja)) ) )
+                           (jb_lt_max && (b.ridx (jb) < a.ridx (ja)) ) )
                     {
-                      double tmp = xmin (0., b.data(jb));
+                      double tmp = xmin (0., b.data (jb));
                       if (tmp != 0.)
                         {
-                          r.ridx(jx) = b.ridx(jb);
-                          r.data(jx) = tmp;
+                          r.ridx (jx) = b.ridx (jb);
+                          r.data (jx) = tmp;
                           jx++;
                         }
                       jb++;
@@ -7822,11 +7812,11 @@
                     }
                   else
                     {
-                      double tmp = xmin (a.data(ja), b.data(jb));
+                      double tmp = xmin (a.data (ja), b.data (jb));
                       if (tmp != 0.)
                         {
-                          r.data(jx) = tmp;
-                          r.ridx(jx) = a.ridx(ja);
+                          r.data (jx) = tmp;
+                          r.ridx (jx) = a.ridx (ja);
                           jx++;
                         }
                       ja++;
@@ -7835,7 +7825,7 @@
                       jb_lt_max= jb < jb_max;
                     }
                 }
-              r.cidx(i+1) = jx;
+              r.cidx (i+1) = jx;
             }
 
           r.maybe_compress ();
@@ -7862,15 +7852,15 @@
     {
       result = SparseMatrix (nr, nc, d);
       for (octave_idx_type j = 0; j < nc; j++)
-        for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++)
+        for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++)
           {
             double tmp = xmax (d, m.data (i));
 
             if (tmp != 0.)
               {
-                octave_idx_type idx = m.ridx(i) + j * nr;
-                result.xdata(idx) = tmp;
-                result.xridx(idx) = m.ridx(i);
+                octave_idx_type idx = m.ridx (i) + j * nr;
+                result.xdata (idx) = tmp;
+                result.xridx (idx) = m.ridx (i);
               }
           }
     }
@@ -7878,26 +7868,26 @@
     {
       octave_idx_type nel = 0;
       for (octave_idx_type j = 0; j < nc; j++)
-        for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++)
+        for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++)
           if (xmax (d, m.data (i)) != 0.)
             nel++;
 
       result = SparseMatrix (nr, nc, nel);
 
       octave_idx_type ii = 0;
-      result.xcidx(0) = 0;
+      result.xcidx (0) = 0;
       for (octave_idx_type j = 0; j < nc; j++)
         {
-          for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++)
+          for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++)
             {
               double tmp = xmax (d, m.data (i));
               if (tmp != 0.)
                 {
-                  result.xdata(ii) = tmp;
-                  result.xridx(ii++) = m.ridx(i);
-                }
-            }
-          result.xcidx(j+1) = ii;
+                  result.xdata (ii) = tmp;
+                  result.xridx (ii++) = m.ridx (i);
+                }
+            }
+          result.xcidx (j+1) = ii;
         }
     }
 
@@ -7915,7 +7905,7 @@
 {
   SparseMatrix r;
 
-  if ((a.rows() == b.rows()) && (a.cols() == b.cols()))
+  if ((a.rows () == b.rows ()) && (a.cols () == b.cols ()))
     {
       octave_idx_type a_nr = a.rows ();
       octave_idx_type a_nc = a.cols ();
@@ -7933,38 +7923,38 @@
           r.cidx (0) = 0;
           for (octave_idx_type i = 0 ; i < a_nc ; i++)
             {
-              octave_idx_type  ja = a.cidx(i);
-              octave_idx_type  ja_max = a.cidx(i+1);
+              octave_idx_type  ja = a.cidx (i);
+              octave_idx_type  ja_max = a.cidx (i+1);
               bool ja_lt_max= ja < ja_max;
 
-              octave_idx_type  jb = b.cidx(i);
-              octave_idx_type  jb_max = b.cidx(i+1);
+              octave_idx_type  jb = b.cidx (i);
+              octave_idx_type  jb_max = b.cidx (i+1);
               bool jb_lt_max = jb < jb_max;
 
               while (ja_lt_max || jb_lt_max )
                 {
                   octave_quit ();
                   if ((! jb_lt_max) ||
-                      (ja_lt_max && (a.ridx(ja) < b.ridx(jb))))
+                      (ja_lt_max && (a.ridx (ja) < b.ridx (jb))))
                     {
-                      double tmp = xmax (a.data(ja), 0.);
+                      double tmp = xmax (a.data (ja), 0.);
                       if (tmp != 0.)
                         {
-                          r.ridx(jx) = a.ridx(ja);
-                          r.data(jx) = tmp;
+                          r.ridx (jx) = a.ridx (ja);
+                          r.data (jx) = tmp;
                           jx++;
                         }
                       ja++;
                       ja_lt_max= ja < ja_max;
                     }
                   else if (( !ja_lt_max ) ||
-                           (jb_lt_max && (b.ridx(jb) < a.ridx(ja)) ) )
+                           (jb_lt_max && (b.ridx (jb) < a.ridx (ja)) ) )
                     {
-                      double tmp = xmax (0., b.data(jb));
+                      double tmp = xmax (0., b.data (jb));
                       if (tmp != 0.)
                         {
-                          r.ridx(jx) = b.ridx(jb);
-                          r.data(jx) = tmp;
+                          r.ridx (jx) = b.ridx (jb);
+                          r.data (jx) = tmp;
                           jx++;
                         }
                       jb++;
@@ -7972,11 +7962,11 @@
                     }
                   else
                     {
-                      double tmp = xmax (a.data(ja), b.data(jb));
+                      double tmp = xmax (a.data (ja), b.data (jb));
                       if (tmp != 0.)
                         {
-                          r.data(jx) = tmp;
-                          r.ridx(jx) = a.ridx(ja);
+                          r.data (jx) = tmp;
+                          r.ridx (jx) = a.ridx (ja);
                           jx++;
                         }
                       ja++;
@@ -7985,7 +7975,7 @@
                       jb_lt_max= jb < jb_max;
                     }
                 }
-              r.cidx(i+1) = jx;
+              r.cidx (i+1) = jx;
             }
 
           r.maybe_compress ();
rename from liboctave/dSparse.h
rename to liboctave/array/dSparse.h
--- a/liboctave/dSparse.h
+++ b/liboctave/array/dSparse.h
@@ -469,7 +469,7 @@
 
 SPARSE_FORWARD_DEFS (MSparse, SparseMatrix, Matrix, double)
 
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
 #define UMFPACK_DNAME(name) umfpack_dl_ ## name
 #else
 #define UMFPACK_DNAME(name) umfpack_di_ ## name
rename from liboctave/dim-vector.cc
rename to liboctave/array/dim-vector.cc
--- a/liboctave/dim-vector.cc
+++ b/liboctave/array/dim-vector.cc
@@ -45,7 +45,7 @@
   make_unique ();
 
   int j = 0;
-  int l = ndims();
+  int l = ndims ();
 
   for (int i = 0; i < l; i++)
     {
@@ -157,16 +157,16 @@
             }
         }
       else
-        new_dims.resize(k);
+        new_dims.resize (k);
     }
 
   return new_dims;
 }
 
-// This is the rule for cat(). cat(dim, A, B) works if one
+// This is the rule for cat(). cat (dim, A, B) works if one
 // of the following holds, in this order:
 //
-// 1. size(A, k) == size(B, k) for all k != dim.
+// 1. size (A, k) == size (B, k) for all k != dim.
 // In this case, size (C, dim) = size (A, dim) + size (B, dim) and
 // other sizes remain intact.
 //
@@ -230,7 +230,7 @@
 // horizontally (dim = 2) or vertically (dim = 1) if one of the
 // following holds, in this order:
 //
-// 1. cat(dim, A, B) works
+// 1. cat (dim, A, B) works
 //
 // 2. A, B are 2D and one of them is an empty vector, in which
 // case the result is the other one except if both of them
rename from liboctave/dim-vector.h
rename to liboctave/array/dim-vector.h
--- a/liboctave/dim-vector.h
+++ b/liboctave/array/dim-vector.h
@@ -66,7 +66,7 @@
 
   static octave_idx_type *newrep (int ndims)
   {
-    octave_idx_type *r = new octave_idx_type[ndims + 2];
+    octave_idx_type *r = new octave_idx_type [ndims + 2];
 
     *r++ = 1;
     *r++ = ndims;
@@ -80,7 +80,7 @@
   {
     int l = ndims ();
 
-    octave_idx_type *r = new octave_idx_type[l + 2];
+    octave_idx_type *r = new octave_idx_type [l + 2];
 
     *r++ = 1;
     *r++ = l;
@@ -100,7 +100,7 @@
     if (n < 2)
       n = 2;
 
-    octave_idx_type *r = new octave_idx_type[n + 2];
+    octave_idx_type *r = new octave_idx_type [n + 2];
 
     *r++ = 1;
     *r++ = n;
@@ -129,10 +129,10 @@
   {
     if (count () > 1)
       {
-	octave_idx_type *new_rep = clonerep ();
+        octave_idx_type *new_rep = clonerep ();
 
-	if (OCTREFCOUNT_ATOMIC_DECREMENT(&(count())) == 0)
-	  freerep ();
+        if (OCTREFCOUNT_ATOMIC_DECREMENT(&(count())) == 0)
+          freerep ();
 
         rep = new_rep;
       }
@@ -212,6 +212,12 @@
 
   void chop_all_singletons (void);
 
+  // WARNING: Only call by jit
+  octave_idx_type *to_jit (void) const
+  {
+    return rep;
+  }
+
 private:
 
   static octave_idx_type *nil_rep (void)
@@ -220,9 +226,6 @@
       return zv.rep;
     }
 
-  explicit dim_vector (octave_idx_type *r)
-    : rep (r) { }
-
 public:
 
   static octave_idx_type dim_max (void);
@@ -233,6 +236,10 @@
   dim_vector (const dim_vector& dv) : rep (dv.rep)
   { OCTREFCOUNT_ATOMIC_INCREMENT (&(count())); }
 
+  // FIXME: Should be private, but required by array constructor for jit
+  explicit dim_vector (octave_idx_type *r)
+    : rep (r) { }
+
   static dim_vector alloc (int n)
   {
     return dim_vector (newrep (n < 2 ? 2 : n));
rename from liboctave/fCColVector.cc
rename to liboctave/array/fCColVector.cc
--- a/liboctave/fCColVector.cc
+++ b/liboctave/array/fCColVector.cc
@@ -514,7 +514,7 @@
 std::istream&
 operator >> (std::istream& is, FloatComplexColumnVector& a)
 {
-  octave_idx_type len = a.length();
+  octave_idx_type len = a.length ();
 
   if (len > 0)
     {
rename from liboctave/fCColVector.h
rename to liboctave/array/fCColVector.h
--- a/liboctave/fCColVector.h
+++ b/liboctave/array/fCColVector.h
@@ -134,8 +134,7 @@
   friend OCTAVE_API std::ostream& operator << (std::ostream& os, const FloatComplexColumnVector& a);
   friend OCTAVE_API std::istream& operator >> (std::istream& is, FloatComplexColumnVector& a);
 
-  void resize (octave_idx_type n,
-               const FloatComplex& rfv = Array<FloatComplex>::resize_fill_value ())
+  void resize (octave_idx_type n, const FloatComplex& rfv = FloatComplex (0))
   {
     Array<FloatComplex>::resize (dim_vector (n, 1), rfv);
   }
rename from liboctave/fCDiagMatrix.cc
rename to liboctave/array/fCDiagMatrix.cc
--- a/liboctave/fCDiagMatrix.cc
+++ b/liboctave/array/fCDiagMatrix.cc
@@ -236,13 +236,13 @@
 FloatDiagMatrix
 FloatComplexDiagMatrix::abs (void) const
 {
-  return FloatDiagMatrix (diag ().abs (), rows (), columns ());
+  return FloatDiagMatrix (extract_diag ().abs (), rows (), columns ());
 }
 
 FloatComplexDiagMatrix
 conj (const FloatComplexDiagMatrix& a)
 {
-  return FloatComplexDiagMatrix (conj (a.diag ()), a.rows (), a.columns ());
+  return FloatComplexDiagMatrix (conj (a.extract_diag ()), a.rows (), a.columns ());
 }
 
 // resize is the destructive analog for this one
@@ -546,7 +546,7 @@
 float
 FloatComplexDiagMatrix::rcond (void) const
 {
-  FloatColumnVector av = diag (0).map<float> (std::abs);
+  FloatColumnVector av = extract_diag (0).map<float> (std::abs);
   float amx = av.max (), amn = av.min ();
   return amx == 0 ? 0.0f : amn / amx;
 }
rename from liboctave/fCDiagMatrix.h
rename to liboctave/array/fCDiagMatrix.h
--- a/liboctave/fCDiagMatrix.h
+++ b/liboctave/array/fCDiagMatrix.h
@@ -90,7 +90,7 @@
   FloatComplexDiagMatrix& fill (const FloatComplexRowVector& a, octave_idx_type beg);
 
   FloatComplexDiagMatrix hermitian (void) const { return MDiagArray2<FloatComplex>::hermitian (std::conj); }
-  FloatComplexDiagMatrix transpose (void) const { return MDiagArray2<FloatComplex>::transpose(); }
+  FloatComplexDiagMatrix transpose (void) const { return MDiagArray2<FloatComplex>::transpose (); }
   FloatDiagMatrix abs (void) const;
 
   friend OCTAVE_API FloatComplexDiagMatrix conj (const FloatComplexDiagMatrix& a);
@@ -120,8 +120,8 @@
 
   // other operations
 
-  FloatComplexColumnVector diag (octave_idx_type k = 0) const
-    { return MDiagArray2<FloatComplex>::diag (k); }
+  FloatComplexColumnVector extract_diag (octave_idx_type k = 0) const
+    { return MDiagArray2<FloatComplex>::extract_diag (k); }
 
   FloatComplexDET determinant (void) const;
   float rcond (void) const;
rename from liboctave/fCMatrix.cc
rename to liboctave/array/fCMatrix.cc
--- a/liboctave/fCMatrix.cc
+++ b/liboctave/array/fCMatrix.cc
@@ -1081,7 +1081,7 @@
       F77_XFCN (cgetri, CGETRI, (nc, tmp_data, nr, pipvt,
                                  z.fortran_vec (), lwork, info));
 
-      lwork = static_cast<octave_idx_type> (std::real(z(0)));
+      lwork = static_cast<octave_idx_type> (std::real (z(0)));
       lwork = (lwork <  2 *nc ? 2*nc : lwork);
       z.resize (dim_vector (lwork, 1));
       FloatComplex *pz = z.fortran_vec ();
@@ -1091,7 +1091,7 @@
       // Calculate the norm of the matrix, for later use.
       float anorm;
       if (calc_cond)
-        anorm  = retval.abs().sum().row(static_cast<octave_idx_type>(0)).max();
+        anorm = retval.abs ().sum ().row (static_cast<octave_idx_type>(0)).max ();
 
       F77_XFCN (cgetrf, CGETRF, (nc, nc, tmp_data, nr, pipvt, info));
 
@@ -1129,7 +1129,7 @@
         }
 
       if (info != 0)
-        mattype.mark_as_rectangular();
+        mattype.mark_as_rectangular ();
     }
 
   return retval;
@@ -1155,7 +1155,7 @@
           if (info == 0)
             {
               if (calc_cond)
-                rcon = chol.rcond();
+                rcon = chol.rcond ();
               else
                 rcon = 1.0;
               ret = chol.inverse ();
@@ -1165,7 +1165,7 @@
         }
 
       if (!mattype.is_hermitian ())
-        ret = finverse(mattype, info, rcon, force, calc_cond);
+        ret = finverse (mattype, info, rcon, force, calc_cond);
 
       if ((mattype.is_hermitian () || calc_cond) && rcon == 0.)
         ret = FloatComplexMatrix (rows (), columns (), FloatComplex (octave_Float_Inf, 0.));
@@ -1185,7 +1185,7 @@
   FloatComplexMatrix U = result.left_singular_matrix ();
   FloatComplexMatrix V = result.right_singular_matrix ();
 
-  FloatColumnVector sigma = S.diag ();
+  FloatColumnVector sigma = S.extract_diag ();
 
   octave_idx_type r = sigma.length () - 1;
   octave_idx_type nr = rows ();
@@ -1194,9 +1194,9 @@
   if (tol <= 0.0)
     {
       if (nr > nc)
-        tol = nr * sigma.elem (0) * DBL_EPSILON;
+        tol = nr * sigma.elem (0) * std::numeric_limits<double>::epsilon ();
       else
-        tol = nc * sigma.elem (0) * DBL_EPSILON;
+        tol = nc * sigma.elem (0) * std::numeric_limits<double>::epsilon ();
     }
 
   while (r >= 0 && sigma.elem (r) < tol)
@@ -1717,7 +1717,7 @@
     rcon = octave_Inf;
   else
     {
-      int typ = mattype.type ();
+      volatile int typ = mattype.type ();
 
       if (typ == MatrixType::Unknown)
         typ = mattype.type (*this);
@@ -1833,9 +1833,9 @@
               Array<octave_idx_type> ipvt (dim_vector (nr, 1));
               octave_idx_type *pipvt = ipvt.fortran_vec ();
 
-              if(anorm < 0.)
-                anorm = atmp.abs().sum().
-                  row(static_cast<octave_idx_type>(0)).max();
+              if (anorm < 0.)
+                anorm = atmp.abs ().sum ().
+                  row(static_cast<octave_idx_type>(0)).max ();
 
               Array<FloatComplex> z (dim_vector (2 * nc, 1));
               FloatComplex *pz = z.fortran_vec ();
@@ -2159,7 +2159,7 @@
 
                   F77_XFCN (cpotrs, CPOTRS, (F77_CONST_CHAR_ARG2 (&job, 1),
                                              nr, b_nc, tmp_data, nr,
-                                             result, b.rows(), info
+                                             result, b.rows (), info
                                              F77_CHAR_ARG_LEN (1)));
                 }
               else
@@ -2187,7 +2187,7 @@
 
           // Calculate the norm of the matrix, for later use.
           if (anorm < 0.)
-            anorm = atmp.abs().sum().row(static_cast<octave_idx_type>(0)).max();
+            anorm = atmp.abs ().sum ().row (static_cast<octave_idx_type>(0)).max ();
 
           F77_XFCN (cgetrf, CGETRF, (nr, nr, tmp_data, nr, pipvt, info));
 
@@ -2245,7 +2245,7 @@
                   char job = 'N';
                   F77_XFCN (cgetrs, CGETRS, (F77_CONST_CHAR_ARG2 (&job, 1),
                                              nr, b_nc, tmp_data, nr,
-                                             pipvt, result, b.rows(), info
+                                             pipvt, result, b.rows (), info
                                              F77_CHAR_ARG_LEN (1)));
                 }
               else
@@ -2413,7 +2413,7 @@
 
   FloatComplexMatrix tmp (b);
   tmp = solve (typ, tmp, info, rcon, sing_handler, true, transt);
-  return tmp.column(static_cast<octave_idx_type> (0));
+  return tmp.column (static_cast<octave_idx_type> (0));
 }
 
 FloatComplexMatrix
@@ -3165,24 +3165,6 @@
 bool
 FloatComplexMatrix::too_large_for_float (void) const
 {
-  octave_idx_type nr = rows ();
-  octave_idx_type nc = cols ();
-
-  for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = 0; i < nr; i++)
-      {
-        FloatComplex val = elem (i, j);
-
-        float r_val = std::real (val);
-        float i_val = std::imag (val);
-
-        if ((! (xisnan (r_val) || xisinf (r_val))
-             && fabs (r_val) > FLT_MAX)
-            || (! (xisnan (i_val) || xisinf (i_val))
-                && fabs (i_val) > FLT_MAX))
-          return true;
-      }
-
   return false;
 }
 
@@ -3242,6 +3224,23 @@
   return MArray<FloatComplex>::diag (k);
 }
 
+FloatComplexDiagMatrix
+FloatComplexMatrix::diag (octave_idx_type m, octave_idx_type n) const
+{
+  FloatComplexDiagMatrix retval;
+
+  octave_idx_type nr = rows ();
+  octave_idx_type nc = cols ();
+
+  if (nr == 1 || nc == 1)
+    retval = FloatComplexDiagMatrix (*this, m, n);
+  else
+    (*current_liboctave_error_handler)
+      ("diag: expecting vector argument");
+
+  return retval;
+}
+
 bool
 FloatComplexMatrix::row_is_real_only (octave_idx_type i) const
 {
@@ -3705,25 +3704,27 @@
     return m * FloatComplexMatrix (a);
 }
 
-/* Simple Dot Product, Matrix-Vector and Matrix-Matrix Unit tests
-%!assert(single([1+i 2+i 3+i]) * single([ 4+i ; 5+i ; 6+i]), single(29+21i), 5e-7)
-%!assert(single([1+i 2+i ; 3+i 4+i ]) * single([5+i ; 6+i]), single([15 + 14i ; 37 + 18i]), 5e-7)
-%!assert(single([1+i 2+i ; 3+i 4+i ]) * single([5+i 6+i ; 7+i 8+i]), single([17 + 15i 20 + 17i; 41 + 19i 48 + 21i]), 5e-7)
-%!assert(single([1 i])*single([i 0])', single(-i));
-*/
-
-/* Test some simple identities
+/*
+
+## Simple Dot Product, Matrix-Vector, and Matrix-Matrix Unit tests
+%!assert (single ([1+i 2+i 3+i]) * single ([ 4+i ; 5+i ; 6+i]), single (29+21i), 5e-7)
+%!assert (single ([1+i 2+i ; 3+i 4+i]) * single ([5+i ; 6+i]), single ([15 + 14i ; 37 + 18i]), 5e-7)
+%!assert (single ([1+i 2+i ; 3+i 4+i ]) * single ([5+i 6+i ; 7+i 8+i]), single ([17 + 15i 20 + 17i; 41 + 19i 48 + 21i]), 5e-7)
+%!assert (single ([1 i])*single ([i 0])', single (-i))
+
+## Test some simple identities
 %!shared M, cv, rv
-%! M = single(randn(10,10))+i*single(rand(10,10));
-%! cv = single(randn(10,1))+i*single(rand(10,1));
-%! rv = single(randn(1,10))+i*single(rand(1,10));
-%!assert([M*cv,M*cv],M*[cv,cv],5e-6)
-%!assert([M.'*cv,M.'*cv],M.'*[cv,cv],5e-6)
-%!assert([M'*cv,M'*cv],M'*[cv,cv],5e-6)
-%!assert([rv*M;rv*M],[rv;rv]*M,5e-6)
-%!assert([rv*M.';rv*M.'],[rv;rv]*M.',5e-6)
-%!assert([rv*M';rv*M'],[rv;rv]*M',5e-6)
-%!assert(2*rv*cv,[rv,rv]*[cv;cv],5e-6)
+%! M = single (randn (10,10))+ i*single (rand (10,10));
+%! cv = single (randn (10,1))+ i*single (rand (10,1));
+%! rv = single (randn (1,10))+ i*single (rand (1,10));
+%!assert ([M*cv,M*cv], M*[cv,cv], 5e-6)
+%!assert ([M.'*cv,M.'*cv], M.'*[cv,cv], 5e-6)
+%!assert ([M'*cv,M'*cv], M'*[cv,cv], 5e-6)
+%!assert ([rv*M;rv*M], [rv;rv]*M, 5e-6)
+%!assert ([rv*M.';rv*M.'], [rv;rv]*M.', 5e-6)
+%!assert ([rv*M';rv*M'], [rv;rv]*M', 5e-6)
+%!assert (2*rv*cv, [rv,rv]*[cv;cv], 5e-6)
+
 */
 
 static char
rename from liboctave/fCMatrix.h
rename to liboctave/array/fCMatrix.h
--- a/liboctave/fCMatrix.h
+++ b/liboctave/array/fCMatrix.h
@@ -157,7 +157,7 @@
   FloatComplexColumnVector column (octave_idx_type i) const;
 
   void resize (octave_idx_type nr, octave_idx_type nc,
-               const FloatComplex& rfv = resize_fill_value ())
+               const FloatComplex& rfv = FloatComplex (0))
   {
     MArray<FloatComplex>::resize (dim_vector (nr, nc), rfv);
   }
@@ -362,6 +362,8 @@
 
   FloatComplexMatrix diag (octave_idx_type k = 0) const;
 
+  FloatComplexDiagMatrix diag (octave_idx_type m, octave_idx_type n) const;
+
   bool row_is_real_only (octave_idx_type) const;
   bool column_is_real_only (octave_idx_type) const;
 
@@ -381,9 +383,6 @@
 
   friend OCTAVE_API std::ostream& operator << (std::ostream& os, const FloatComplexMatrix& a);
   friend OCTAVE_API std::istream& operator >> (std::istream& is, FloatComplexMatrix& a);
-
-  static FloatComplex resize_fill_value (void) { return FloatComplex (0.0, 0.0); }
-
 };
 
 extern OCTAVE_API FloatComplexMatrix conj (const FloatComplexMatrix& a);
rename from liboctave/fCNDArray.cc
rename to liboctave/array/fCNDArray.cc
--- a/liboctave/fCNDArray.cc
+++ b/liboctave/array/fCNDArray.cc
@@ -119,7 +119,7 @@
 FloatComplexNDArray
 FloatComplexNDArray::fourier2d (void) const
 {
-  dim_vector dv = dims();
+  dim_vector dv = dims ();
   if (dv.length () < 2)
     return FloatComplexNDArray ();
 
@@ -127,7 +127,7 @@
   const FloatComplex *in = fortran_vec ();
   FloatComplexNDArray retval (dv);
   FloatComplex *out = retval.fortran_vec ();
-  octave_idx_type howmany = numel() / dv(0) / dv(1);
+  octave_idx_type howmany = numel () / dv(0) / dv(1);
   octave_idx_type dist = dv(0) * dv(1);
 
   for (octave_idx_type i=0; i < howmany; i++)
@@ -139,7 +139,7 @@
 FloatComplexNDArray
 FloatComplexNDArray::ifourier2d (void) const
 {
-  dim_vector dv = dims();
+  dim_vector dv = dims ();
   if (dv.length () < 2)
     return FloatComplexNDArray ();
 
@@ -147,7 +147,7 @@
   const FloatComplex *in = fortran_vec ();
   FloatComplexNDArray retval (dv);
   FloatComplex *out = retval.fortran_vec ();
-  octave_idx_type howmany = numel() / dv(0) / dv(1);
+  octave_idx_type howmany = numel () / dv(0) / dv(1);
   octave_idx_type dist = dv(0) * dv(1);
 
   for (octave_idx_type i=0; i < howmany; i++)
@@ -237,12 +237,12 @@
           octave_quit ();
 
           for (octave_idx_type i = 0; i < npts; i++)
-            tmp[i] = elem((i + k*npts)*stride + j*dist);
+            tmp[i] = elem ((i + k*npts)*stride + j*dist);
 
           F77_FUNC (cfftf, CFFTF) (npts, tmp, pwsave);
 
           for (octave_idx_type i = 0; i < npts; i++)
-            retval ((i + k*npts)*stride + j*dist) = tmp[i];
+            retval((i + k*npts)*stride + j*dist) = tmp[i];
         }
     }
 
@@ -284,12 +284,12 @@
           octave_quit ();
 
           for (octave_idx_type i = 0; i < npts; i++)
-            tmp[i] = elem((i + k*npts)*stride + j*dist);
+            tmp[i] = elem ((i + k*npts)*stride + j*dist);
 
           F77_FUNC (cfftb, CFFTB) (npts, tmp, pwsave);
 
           for (octave_idx_type i = 0; i < npts; i++)
-            retval ((i + k*npts)*stride + j*dist) = tmp[i] /
+            retval((i + k*npts)*stride + j*dist) = tmp[i] /
               static_cast<float> (npts);
         }
     }
@@ -330,12 +330,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (cfftf, CFFTF) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l];
+                retval((l + k*npts)*stride + j*dist) = prow[l];
             }
         }
 
@@ -348,7 +348,7 @@
 FloatComplexNDArray
 FloatComplexNDArray::ifourier2d (void) const
 {
-  dim_vector dv = dims();
+  dim_vector dv = dims ();
   dim_vector dv2 (dv(0), dv(1));
   int rank = 2;
   FloatComplexNDArray retval (*this);
@@ -378,12 +378,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (cfftb, CFFTB) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l] /
+                retval((l + k*npts)*stride + j*dist) = prow[l] /
                   static_cast<float> (npts);
             }
         }
@@ -426,12 +426,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (cfftf, CFFTF) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l];
+                retval((l + k*npts)*stride + j*dist) = prow[l];
             }
         }
 
@@ -473,12 +473,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (cfftb, CFFTB) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l] /
+                retval((l + k*npts)*stride + j*dist) = prow[l] /
                   static_cast<float> (npts);
             }
         }
@@ -581,22 +581,6 @@
 bool
 FloatComplexNDArray::too_large_for_float (void) const
 {
-  octave_idx_type nel = nelem ();
-
-  for (octave_idx_type i = 0; i < nel; i++)
-    {
-      FloatComplex val = elem (i);
-
-      float r_val = std::real (val);
-      float i_val = std::imag (val);
-
-      if ((! (xisnan (r_val) || xisinf (r_val))
-           && fabs (r_val) > FLT_MAX)
-          || (! (xisnan (i_val) || xisinf (i_val))
-              && fabs (i_val) > FLT_MAX))
-        return true;
-    }
-
   return false;
 }
 
@@ -859,6 +843,12 @@
   return MArray<FloatComplex>::diag (k);
 }
 
+FloatComplexNDArray
+FloatComplexNDArray::diag (octave_idx_type m, octave_idx_type n) const
+{
+  return MArray<FloatComplex>::diag (m, n);
+}
+
 // This contains no information on the array structure !!!
 std::ostream&
 operator << (std::ostream& os, const FloatComplexNDArray& a)
rename from liboctave/fCNDArray.h
rename to liboctave/array/fCNDArray.h
--- a/liboctave/fCNDArray.h
+++ b/liboctave/array/fCNDArray.h
@@ -135,13 +135,13 @@
   friend OCTAVE_API std::ostream& operator << (std::ostream& os, const FloatComplexNDArray& a);
   friend OCTAVE_API std::istream& operator >> (std::istream& is, FloatComplexNDArray& a);
 
-  static FloatComplex resize_fill_value (void) { return FloatComplex (0.0, 0.0); }
-
   //  bool all_elements_are_real (void) const;
   //  bool all_integers (float& max_val, float& min_val) const;
 
   FloatComplexNDArray diag (octave_idx_type k = 0) const;
 
+  FloatComplexNDArray diag (octave_idx_type m, octave_idx_type n) const;
+
   FloatComplexNDArray& changesign (void)
     {
       MArray<FloatComplex>::changesign ();
rename from liboctave/fCRowVector.cc
rename to liboctave/array/fCRowVector.cc
--- a/liboctave/fCRowVector.cc
+++ b/liboctave/array/fCRowVector.cc
@@ -411,7 +411,7 @@
 std::istream&
 operator >> (std::istream& is, FloatComplexRowVector& a)
 {
-  octave_idx_type len = a.length();
+  octave_idx_type len = a.length ();
 
   if (len > 0)
     {
rename from liboctave/fCRowVector.h
rename to liboctave/array/fCRowVector.h
--- a/liboctave/fCRowVector.h
+++ b/liboctave/array/fCRowVector.h
@@ -116,8 +116,7 @@
   friend std::ostream& operator << (std::ostream& os, const FloatComplexRowVector& a);
   friend std::istream& operator >> (std::istream& is, FloatComplexRowVector& a);
 
-  void resize (octave_idx_type n,
-               const FloatComplex& rfv = Array<FloatComplex>::resize_fill_value ())
+  void resize (octave_idx_type n, const FloatComplex& rfv = FloatComplex (0))
   {
     Array<FloatComplex>::resize (dim_vector (1, n), rfv);
   }
rename from liboctave/fColVector.cc
rename to liboctave/array/fColVector.cc
--- a/liboctave/fColVector.cc
+++ b/liboctave/array/fColVector.cc
@@ -142,7 +142,7 @@
 FloatRowVector
 FloatColumnVector::transpose (void) const
 {
-  return MArray<float>::transpose();
+  return MArray<float>::transpose ();
 }
 
 FloatColumnVector
@@ -307,7 +307,7 @@
 std::istream&
 operator >> (std::istream& is, FloatColumnVector& a)
 {
-  octave_idx_type len = a.length();
+  octave_idx_type len = a.length ();
 
   if (len > 0)
     {
rename from liboctave/fColVector.h
rename to liboctave/array/fColVector.h
--- a/liboctave/fColVector.h
+++ b/liboctave/array/fColVector.h
@@ -102,8 +102,7 @@
   friend OCTAVE_API std::ostream& operator << (std::ostream& os, const FloatColumnVector& a);
   friend OCTAVE_API std::istream& operator >> (std::istream& is, FloatColumnVector& a);
 
-  void resize (octave_idx_type n,
-               const float& rfv = Array<float>::resize_fill_value ())
+  void resize (octave_idx_type n, const float& rfv = 0)
   {
     Array<float>::resize (dim_vector (n, 1), rfv);
   }
rename from liboctave/fDiagMatrix.cc
rename to liboctave/array/fDiagMatrix.cc
--- a/liboctave/fDiagMatrix.cc
+++ b/liboctave/array/fDiagMatrix.cc
@@ -141,19 +141,19 @@
 FloatDiagMatrix
 FloatDiagMatrix::abs (void) const
 {
-  return FloatDiagMatrix (diag ().abs (), rows (), columns ());
+  return FloatDiagMatrix (extract_diag ().abs (), rows (), columns ());
 }
 
 FloatDiagMatrix
 real (const FloatComplexDiagMatrix& a)
 {
-  return FloatDiagMatrix (real (a.diag ()), a.rows (), a.columns ());
+  return FloatDiagMatrix (real (a.extract_diag ()), a.rows (), a.columns ());
 }
 
 FloatDiagMatrix
 imag (const FloatComplexDiagMatrix& a)
 {
-  return FloatDiagMatrix (imag (a.diag ()), a.rows (), a.columns ());
+  return FloatDiagMatrix (imag (a.extract_diag ()), a.rows (), a.columns ());
 }
 
 FloatMatrix
@@ -362,7 +362,7 @@
 float
 FloatDiagMatrix::rcond (void) const
 {
-  FloatColumnVector av = diag (0).map<float> (fabsf);
+  FloatColumnVector av = extract_diag (0).map<float> (fabsf);
   float amx = av.max (), amn = av.min ();
   return amx == 0 ? 0.0f : amn / amx;
 }
rename from liboctave/fDiagMatrix.h
rename to liboctave/array/fDiagMatrix.h
--- a/liboctave/fDiagMatrix.h
+++ b/liboctave/array/fDiagMatrix.h
@@ -74,7 +74,7 @@
   FloatDiagMatrix& fill (const FloatColumnVector& a, octave_idx_type beg);
   FloatDiagMatrix& fill (const FloatRowVector& a, octave_idx_type beg);
 
-  FloatDiagMatrix transpose (void) const { return MDiagArray2<float>::transpose(); }
+  FloatDiagMatrix transpose (void) const { return MDiagArray2<float>::transpose (); }
   FloatDiagMatrix abs (void) const;
 
   friend OCTAVE_API FloatDiagMatrix real (const FloatComplexDiagMatrix& a);
@@ -98,8 +98,8 @@
 
   // other operations
 
-  FloatColumnVector diag (octave_idx_type k = 0) const
-    { return MDiagArray2<float>::diag (k); }
+  FloatColumnVector extract_diag (octave_idx_type k = 0) const
+    { return MDiagArray2<float>::extract_diag (k); }
 
   FloatDET determinant (void) const;
   float rcond (void) const;
rename from liboctave/fMatrix.cc
rename to liboctave/array/fMatrix.cc
--- a/liboctave/fMatrix.cc
+++ b/liboctave/array/fMatrix.cc
@@ -763,7 +763,7 @@
       // Calculate the norm of the matrix, for later use.
       float anorm = 0;
       if (calc_cond)
-        anorm = retval.abs().sum().row(static_cast<octave_idx_type>(0)).max();
+        anorm = retval.abs ().sum ().row (static_cast<octave_idx_type>(0)).max ();
 
       F77_XFCN (sgetrf, SGETRF, (nc, nc, tmp_data, nr, pipvt, info));
 
@@ -802,7 +802,7 @@
         }
 
       if (info != 0)
-        mattype.mark_as_rectangular();
+        mattype.mark_as_rectangular ();
     }
 
   return retval;
@@ -838,7 +838,7 @@
         }
 
       if (!mattype.is_hermitian ())
-        ret = finverse(mattype, info, rcon, force, calc_cond);
+        ret = finverse (mattype, info, rcon, force, calc_cond);
 
       if ((mattype.is_hermitian () || calc_cond) && rcon == 0.)
         ret = FloatMatrix (rows (), columns (), octave_Float_Inf);
@@ -856,7 +856,7 @@
   FloatMatrix U = result.left_singular_matrix ();
   FloatMatrix V = result.right_singular_matrix ();
 
-  FloatColumnVector sigma = S.diag ();
+  FloatColumnVector sigma = S.extract_diag ();
 
   octave_idx_type r = sigma.length () - 1;
   octave_idx_type nr = rows ();
@@ -865,9 +865,9 @@
   if (tol <= 0.0)
     {
       if (nr > nc)
-        tol = nr * sigma.elem (0) * DBL_EPSILON;
+        tol = nr * sigma.elem (0) * std::numeric_limits<double>::epsilon ();
       else
-        tol = nc * sigma.elem (0) * DBL_EPSILON;
+        tol = nc * sigma.elem (0) * std::numeric_limits<double>::epsilon ();
     }
 
   while (r >= 0 && sigma.elem (r) < tol)
@@ -1389,7 +1389,7 @@
     rcon = octave_Inf;
   else
     {
-      int typ = mattype.type ();
+      volatile int typ = mattype.type ();
 
       if (typ == MatrixType::Unknown)
         typ = mattype.type (*this);
@@ -1503,9 +1503,9 @@
               Array<octave_idx_type> ipvt (dim_vector (nr, 1));
               octave_idx_type *pipvt = ipvt.fortran_vec ();
 
-              if(anorm < 0.)
-                anorm = atmp.abs().sum().
-                  row(static_cast<octave_idx_type>(0)).max();
+              if (anorm < 0.)
+                anorm = atmp.abs ().sum ().
+                  row(static_cast<octave_idx_type>(0)).max ();
 
               Array<float> z (dim_vector (4 * nc, 1));
               float *pz = z.fortran_vec ();
@@ -1825,7 +1825,7 @@
 
                   F77_XFCN (spotrs, SPOTRS, (F77_CONST_CHAR_ARG2 (&job, 1),
                                              nr, b_nc, tmp_data, nr,
-                                             result, b.rows(), info
+                                             result, b.rows (), info
                                              F77_CHAR_ARG_LEN (1)));
                 }
               else
@@ -1910,7 +1910,7 @@
                   char job = 'N';
                   F77_XFCN (sgetrs, SGETRS, (F77_CONST_CHAR_ARG2 (&job, 1),
                                              nr, b_nc, tmp_data, nr,
-                                             pipvt, result, b.rows(), info
+                                             pipvt, result, b.rows (), info
                                              F77_CHAR_ARG_LEN (1)));
                 }
               else
@@ -2070,7 +2070,7 @@
 {
   FloatMatrix tmp (b);
   tmp = solve (typ, tmp, info, rcon, sing_handler, true, transt);
-  return tmp.column(static_cast<octave_idx_type> (0));
+  return tmp.column (static_cast<octave_idx_type> (0));
 }
 
 FloatComplexColumnVector
@@ -2102,7 +2102,7 @@
                solve_singularity_handler sing_handler, blas_trans_type transt) const
 {
   FloatComplexMatrix tmp (*this);
-  return tmp.solve(typ, b, info, rcon, sing_handler, transt);
+  return tmp.solve (typ, b, info, rcon, sing_handler, transt);
 }
 
 FloatMatrix
@@ -2791,6 +2791,23 @@
   return MArray<float>::diag (k);
 }
 
+FloatDiagMatrix
+FloatMatrix::diag (octave_idx_type m, octave_idx_type n) const
+{
+  FloatDiagMatrix retval;
+
+  octave_idx_type nr = rows ();
+  octave_idx_type nc = cols ();
+
+  if (nr == 1 || nc == 1)
+    retval = FloatDiagMatrix (*this, m, n);
+  else
+    (*current_liboctave_error_handler)
+      ("diag: expecting vector argument");
+
+  return retval;
+}
+
 FloatColumnVector
 FloatMatrix::row_min (void) const
 {
@@ -3121,22 +3138,23 @@
 
 // matrix by matrix -> matrix operations
 
-/* Simple Dot Product, Matrix-Vector and Matrix-Matrix Unit tests
-%!assert(single([1 2 3]) * single([ 4 ; 5 ; 6]), single(32), 5e-7)
-%!assert(single([1 2 ; 3 4 ]) * single([5 ; 6]), single([17 ; 39 ]), 5e-7)
-%!assert(single([1 2 ; 3 4 ]) * single([5 6 ; 7 8]), single([19 22; 43 50]), 5e-7)
-*/
-
-/* Test some simple identities
+/*
+## Simple Dot Product, Matrix-Vector, and Matrix-Matrix Unit tests
+%!assert (single ([1 2 3]) * single ([ 4 ; 5 ; 6]), single (32), 5e-7)
+%!assert (single ([1 2 ; 3 4]) * single ([5 ; 6]), single ([17 ; 39]), 5e-7)
+%!assert (single ([1 2 ; 3 4]) * single ([5 6 ; 7 8]), single ([19 22; 43 50]), 5e-7)
+
+## Test some simple identities
 %!shared M, cv, rv
-%! M = single(randn(10,10));
-%! cv = single(randn(10,1));
-%! rv = single(randn(1,10));
-%!assert([M*cv,M*cv],M*[cv,cv],5e-6)
-%!assert([M'*cv,M'*cv],M'*[cv,cv],5e-6)
-%!assert([rv*M;rv*M],[rv;rv]*M,5e-6)
-%!assert([rv*M';rv*M'],[rv;rv]*M',5e-6)
-%!assert(2*rv*cv,[rv,rv]*[cv;cv],5e-6)
+%! M = single (randn (10,10));
+%! cv = single (randn (10,1));
+%! rv = single (randn (1,10));
+%!assert ([M*cv,M*cv], M*[cv,cv], 5e-6)
+%!assert ([M'*cv,M'*cv], M'*[cv,cv], 5e-6)
+%!assert ([rv*M;rv*M], [rv;rv]*M, 5e-6)
+%!assert ([rv*M';rv*M'], [rv;rv]*M', 5e-6)
+%!assert (2*rv*cv, [rv,rv]*[cv;cv], 5e-6)
+
 */
 
 static char
rename from liboctave/fMatrix.h
rename to liboctave/array/fMatrix.h
--- a/liboctave/fMatrix.h
+++ b/liboctave/array/fMatrix.h
@@ -126,8 +126,7 @@
 
   FloatColumnVector column (octave_idx_type i) const;
 
-  void resize (octave_idx_type nr, octave_idx_type nc,
-               float rfv = resize_fill_value ())
+  void resize (octave_idx_type nr, octave_idx_type nc, float rfv = 0)
   {
     MArray<float>::resize (dim_vector (nr, nc), rfv);
   }
@@ -316,6 +315,8 @@
 
   FloatMatrix diag (octave_idx_type k = 0) const;
 
+  FloatDiagMatrix diag (octave_idx_type m, octave_idx_type n) const;
+
   FloatColumnVector row_min (void) const;
   FloatColumnVector row_max (void) const;
 
@@ -332,9 +333,6 @@
 
   friend OCTAVE_API std::ostream& operator << (std::ostream& os, const FloatMatrix& a);
   friend OCTAVE_API std::istream& operator >> (std::istream& is, FloatMatrix& a);
-
-  static float resize_fill_value (void) { return 0; }
-
 };
 
 // Publish externally used friend functions.
rename from liboctave/fNDArray.cc
rename to liboctave/array/fNDArray.cc
--- a/liboctave/fNDArray.cc
+++ b/liboctave/array/fNDArray.cc
@@ -118,7 +118,7 @@
 FloatComplexNDArray
 FloatNDArray::fourier2d (void) const
 {
-  dim_vector dv = dims();
+  dim_vector dv = dims ();
   if (dv.length () < 2)
     return FloatComplexNDArray ();
 
@@ -126,7 +126,7 @@
   const float *in = fortran_vec ();
   FloatComplexNDArray retval (dv);
   FloatComplex *out = retval.fortran_vec ();
-  octave_idx_type howmany = numel() / dv(0) / dv(1);
+  octave_idx_type howmany = numel () / dv(0) / dv(1);
   octave_idx_type dist = dv(0) * dv(1);
 
   for (octave_idx_type i=0; i < howmany; i++)
@@ -138,14 +138,14 @@
 FloatComplexNDArray
 FloatNDArray::ifourier2d (void) const
 {
-  dim_vector dv = dims();
+  dim_vector dv = dims ();
   if (dv.length () < 2)
     return FloatComplexNDArray ();
 
   dim_vector dv2(dv(0), dv(1));
   FloatComplexNDArray retval (*this);
   FloatComplex *out = retval.fortran_vec ();
-  octave_idx_type howmany = numel() / dv(0) / dv(1);
+  octave_idx_type howmany = numel () / dv(0) / dv(1);
   octave_idx_type dist = dv(0) * dv(1);
 
   for (octave_idx_type i=0; i < howmany; i++)
@@ -241,12 +241,12 @@
           octave_quit ();
 
           for (octave_idx_type i = 0; i < npts; i++)
-            tmp[i] = elem((i + k*npts)*stride + j*dist);
+            tmp[i] = elem ((i + k*npts)*stride + j*dist);
 
           F77_FUNC (cfftf, CFFTF) (npts, tmp, pwsave);
 
           for (octave_idx_type i = 0; i < npts; i++)
-            retval ((i + k*npts)*stride + j*dist) = tmp[i];
+            retval((i + k*npts)*stride + j*dist) = tmp[i];
         }
     }
 
@@ -288,12 +288,12 @@
           octave_quit ();
 
           for (octave_idx_type i = 0; i < npts; i++)
-            tmp[i] = elem((i + k*npts)*stride + j*dist);
+            tmp[i] = elem ((i + k*npts)*stride + j*dist);
 
           F77_FUNC (cfftb, CFFTB) (npts, tmp, pwsave);
 
           for (octave_idx_type i = 0; i < npts; i++)
-            retval ((i + k*npts)*stride + j*dist) = tmp[i] /
+            retval((i + k*npts)*stride + j*dist) = tmp[i] /
               static_cast<float> (npts);
         }
     }
@@ -304,7 +304,7 @@
 FloatComplexNDArray
 FloatNDArray::fourier2d (void) const
 {
-  dim_vector dv = dims();
+  dim_vector dv = dims ();
   dim_vector dv2 (dv(0), dv(1));
   int rank = 2;
   FloatComplexNDArray retval (*this);
@@ -334,12 +334,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (cfftf, CFFTF) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l];
+                retval((l + k*npts)*stride + j*dist) = prow[l];
             }
         }
 
@@ -352,7 +352,7 @@
 FloatComplexNDArray
 FloatNDArray::ifourier2d (void) const
 {
-  dim_vector dv = dims();
+  dim_vector dv = dims ();
   dim_vector dv2 (dv(0), dv(1));
   int rank = 2;
   FloatComplexNDArray retval (*this);
@@ -382,12 +382,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (cfftb, CFFTB) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l] /
+                retval((l + k*npts)*stride + j*dist) = prow[l] /
                   static_cast<float> (npts);
             }
         }
@@ -430,12 +430,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (cfftf, CFFTF) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l];
+                retval((l + k*npts)*stride + j*dist) = prow[l];
             }
         }
 
@@ -477,12 +477,12 @@
               octave_quit ();
 
               for (octave_idx_type l = 0; l < npts; l++)
-                prow[l] = retval ((l + k*npts)*stride + j*dist);
+                prow[l] = retval((l + k*npts)*stride + j*dist);
 
               F77_FUNC (cfftb, CFFTB) (npts, prow, pwsave);
 
               for (octave_idx_type l = 0; l < npts; l++)
-                retval ((l + k*npts)*stride + j*dist) = prow[l] /
+                retval((l + k*npts)*stride + j*dist) = prow[l] /
                   static_cast<float> (npts);
             }
         }
@@ -736,7 +736,7 @@
         {
           octave_idx_type ival = NINTbig (d);
 
-          if (ival < 0 || ival > UCHAR_MAX)
+          if (ival < 0 || ival > std::numeric_limits<unsigned char>::max ())
             // FIXME -- is there something
             // better we could do? Should we warn the user?
             ival = 0;
@@ -837,6 +837,12 @@
   return MArray<float>::diag (k);
 }
 
+FloatNDArray
+FloatNDArray::diag (octave_idx_type m, octave_idx_type n) const
+{
+  return MArray<float>::diag (m, n);
+}
+
 // This contains no information on the array structure !!!
 std::ostream&
 operator << (std::ostream& os, const FloatNDArray& a)
rename from liboctave/fNDArray.h
rename to liboctave/array/fNDArray.h
--- a/liboctave/fNDArray.h
+++ b/liboctave/array/fNDArray.h
@@ -147,9 +147,9 @@
   friend OCTAVE_API std::ostream& operator << (std::ostream& os, const FloatNDArray& a);
   friend OCTAVE_API std::istream& operator >> (std::istream& is, FloatNDArray& a);
 
-  static float resize_fill_value (void) { return 0; }
+  FloatNDArray diag (octave_idx_type k = 0) const;
 
-  FloatNDArray diag (octave_idx_type k = 0) const;
+  FloatNDArray diag (octave_idx_type m, octave_idx_type n) const;
 
   FloatNDArray& changesign (void)
     {
rename from liboctave/fRowVector.cc
rename to liboctave/array/fRowVector.cc
--- a/liboctave/fRowVector.cc
+++ b/liboctave/array/fRowVector.cc
@@ -146,7 +146,7 @@
 FloatColumnVector
 FloatRowVector::transpose (void) const
 {
-  return MArray<float>::transpose();
+  return MArray<float>::transpose ();
 }
 
 FloatRowVector
@@ -271,7 +271,7 @@
 std::istream&
 operator >> (std::istream& is, FloatRowVector& a)
 {
-  octave_idx_type len = a.length();
+  octave_idx_type len = a.length ();
 
   if (len > 0)
     {
rename from liboctave/fRowVector.h
rename to liboctave/array/fRowVector.h
--- a/liboctave/fRowVector.h
+++ b/liboctave/array/fRowVector.h
@@ -93,8 +93,7 @@
   friend OCTAVE_API std::ostream& operator << (std::ostream& os, const FloatRowVector& a);
   friend OCTAVE_API std::istream& operator >> (std::istream& is, FloatRowVector& a);
 
-  void resize (octave_idx_type n,
-               const float& rfv = Array<float>::resize_fill_value ())
+  void resize (octave_idx_type n, const float& rfv = 0)
   {
     Array<float>::resize (dim_vector (1, n), rfv);
   }
rename from liboctave/idx-vector.cc
rename to liboctave/array/idx-vector.cc
--- a/liboctave/idx-vector.cc
+++ b/liboctave/array/idx-vector.cc
@@ -108,7 +108,7 @@
 idx_vector::idx_range_rep::idx_range_rep (octave_idx_type _start,
                                           octave_idx_type _limit,
                                           octave_idx_type _step)
-  : start(_start), len (_step ? std::max((_limit - _start) / _step, static_cast<octave_idx_type> (0)) : -1), step (_step)
+  : start(_start), len (_step ? std::max ((_limit - _start) / _step, static_cast<octave_idx_type> (0)) : -1), step (_step)
 {
   if (len < 0)
     {
@@ -325,7 +325,7 @@
 {
   if (len != 0)
     {
-      octave_idx_type *d = new octave_idx_type[len];
+      octave_idx_type *d = new octave_idx_type [len];
       for (octave_idx_type i = 0; i < len; i++)
         d[i] = convert_index (nda.xelem (i), err, ext);
       data = d;
@@ -489,7 +489,7 @@
   if (ext > len*xlog2 (1.0 + len))
     {
       // Use standard sort via octave_sort.
-      octave_idx_type *new_data = new octave_idx_type[len];
+      octave_idx_type *new_data = new octave_idx_type [len];
       new_rep->data = new_data;
 
       std::copy (data, data + len, new_data);
@@ -524,7 +524,7 @@
       else
         new_rep->orig_dims = dim_vector (new_len, 1);
 
-      octave_idx_type *new_data = new octave_idx_type[new_len];
+      octave_idx_type *new_data = new octave_idx_type [new_len];
       new_rep->data = new_data;
 
       for (octave_idx_type i = 0, j = 0; i < ext; i++)
@@ -538,7 +538,7 @@
       for (octave_idx_type i = 0; i < len; i++)
         cnt[data[i]]++;
 
-      octave_idx_type *new_data = new octave_idx_type[len];
+      octave_idx_type *new_data = new octave_idx_type [len];
       new_rep->data = new_data;
 
       for (octave_idx_type i = 0, j = 0; i < ext; i++)
@@ -1145,7 +1145,7 @@
 
   if (is_colon_equiv (n))
     retval = true;
-  else if (length (n) == n && extent(n) == n)
+  else if (length(n) == n && extent(n) == n)
     {
       OCTAVE_LOCAL_BUFFER_INIT (bool, left, n, true);
 
@@ -1190,7 +1190,7 @@
         const octave_idx_type *ri = r->get_data ();
         Array<octave_idx_type> idx (orig_dimensions ());
         for (octave_idx_type i = 0; i < n; i++)
-          idx.xelem(ri[i]) = i;
+          idx.xelem (ri[i]) = i;
         retval = new idx_vector_rep (idx, r->extent (0), DIRECT);
         break;
       }
@@ -1330,7 +1330,7 @@
 
 /*
 
-%!error id=Octave:index-out-of-bounds 1(find([1,1] != 0))
-%!assert ((1:3)(find([1,0,1] != 0)), [1,3])
+%!error id=Octave:index-out-of-bounds 1(find ([1,1] != 0))
+%!assert ((1:3)(find ([1,0,1] != 0)), [1,3])
 
 */
rename from liboctave/idx-vector.h
rename to liboctave/array/idx-vector.h
--- a/liboctave/idx-vector.h
+++ b/liboctave/array/idx-vector.h
@@ -604,7 +604,7 @@
     { return orig_dimensions () (1); }
 
   int orig_empty (void) const
-    { return (! is_colon () && orig_dimensions().any_zero ()); }
+    { return (! is_colon () && orig_dimensions ().any_zero ()); }
 
   // i/o
 
rename from liboctave/int16NDArray.cc
rename to liboctave/array/int16NDArray.cc
rename from liboctave/int16NDArray.h
rename to liboctave/array/int16NDArray.h
rename from liboctave/int32NDArray.cc
rename to liboctave/array/int32NDArray.cc
rename from liboctave/int32NDArray.h
rename to liboctave/array/int32NDArray.h
rename from liboctave/int64NDArray.cc
rename to liboctave/array/int64NDArray.cc
rename from liboctave/int64NDArray.h
rename to liboctave/array/int64NDArray.h
rename from liboctave/int8NDArray.cc
rename to liboctave/array/int8NDArray.cc
rename from liboctave/int8NDArray.h
rename to liboctave/array/int8NDArray.h
rename from liboctave/intNDArray.cc
rename to liboctave/array/intNDArray.cc
--- a/liboctave/intNDArray.cc
+++ b/liboctave/array/intNDArray.cc
@@ -69,6 +69,13 @@
   return MArray<T>::diag (k);
 }
 
+template <class T>
+intNDArray<T>
+intNDArray<T>::diag (octave_idx_type m, octave_idx_type n) const
+{
+  return MArray<T>::diag (m, n);
+}
+
 // FIXME -- this is not quite the right thing.
 
 template <class T>
rename from liboctave/intNDArray.h
rename to liboctave/array/intNDArray.h
--- a/liboctave/intNDArray.h
+++ b/liboctave/array/intNDArray.h
@@ -66,6 +66,8 @@
 
   intNDArray diag (octave_idx_type k = 0) const;
 
+  intNDArray diag (octave_idx_type m, octave_idx_type n) const;
+
   intNDArray& changesign (void)
     {
       MArray<T>::changesign ();
@@ -113,9 +115,6 @@
 
   static octave_idx_type compute_index (Array<octave_idx_type>& ra_idx,
                             const dim_vector& dimensions);
-
-  static T resize_fill_value (void) { return 0; }
-
 };
 
 // i/o
new file mode 100644
--- /dev/null
+++ b/liboctave/array/module.mk
@@ -0,0 +1,143 @@
+EXTRA_DIST += \
+  array/module.mk
+
+ARRAY_INC = \
+  array/Array2.h \
+  array/Array3.h \
+  array/Array.h \
+  array/ArrayN.h \
+  array/Array-util.h \
+  array/boolMatrix.h \
+  array/boolNDArray.h \
+  array/boolSparse.h \
+  array/CColVector.h \
+  array/CDiagMatrix.h \
+  array/chMatrix.h \
+  array/chNDArray.h \
+  array/CMatrix.h \
+  array/CNDArray.h \
+  array/CRowVector.h \
+  array/CSparse.h \
+  array/dColVector.h \
+  array/dDiagMatrix.h \
+  array/DiagArray2.h \
+  array/dim-vector.h \
+  array/dMatrix.h \
+  array/dNDArray.h \
+  array/dRowVector.h \
+  array/dSparse.h \
+  array/fCColVector.h \
+  array/fCDiagMatrix.h \
+  array/fCMatrix.h \
+  array/fCNDArray.h \
+  array/fColVector.h \
+  array/fCRowVector.h \
+  array/fDiagMatrix.h \
+  array/fMatrix.h \
+  array/fNDArray.h \
+  array/fRowVector.h \
+  array/idx-vector.h \
+  array/int16NDArray.h \
+  array/int32NDArray.h \
+  array/int64NDArray.h \
+  array/int8NDArray.h \
+  array/intNDArray.h \
+  array/MArray2.h \
+  array/MArray-decl.h \
+  array/MArray-defs.h \
+  array/MArray.h \
+  array/MArrayN.h \
+  array/Matrix.h \
+  array/MatrixType.h \
+  array/MDiagArray2.h \
+  array/MSparse-defs.h \
+  array/MSparse.h \
+  array/PermMatrix.h \
+  array/Range.h \
+  array/Sparse.h \
+  array/uint16NDArray.h \
+  array/uint32NDArray.h \
+  array/uint64NDArray.h \
+  array/uint8NDArray.h
+
+ARRAY_SRC = \
+  array/Array-b.cc \
+  array/Array-C.cc \
+  array/Array-ch.cc \
+  array/Array-d.cc \
+  array/Array-f.cc \
+  array/Array-fC.cc \
+  array/Array-i.cc \
+  array/Array-idx-vec.cc \
+  array/Array-s.cc \
+  array/Array-str.cc \
+  array/Array-util.cc \
+  array/Array-voidp.cc \
+  array/boolMatrix.cc \
+  array/boolNDArray.cc \
+  array/boolSparse.cc \
+  array/CColVector.cc \
+  array/CDiagMatrix.cc \
+  array/chMatrix.cc \
+  array/chNDArray.cc \
+  array/CMatrix.cc \
+  array/CNDArray.cc \
+  array/CRowVector.cc \
+  array/CSparse.cc \
+  array/dColVector.cc \
+  array/dDiagMatrix.cc \
+  array/dim-vector.cc \
+  array/dMatrix.cc \
+  array/dNDArray.cc \
+  array/dRowVector.cc \
+  array/dSparse.cc \
+  array/fCColVector.cc \
+  array/fCDiagMatrix.cc \
+  array/fCMatrix.cc \
+  array/fCNDArray.cc \
+  array/fColVector.cc \
+  array/fCRowVector.cc \
+  array/fDiagMatrix.cc \
+  array/fMatrix.cc \
+  array/fNDArray.cc \
+  array/fRowVector.cc \
+  array/idx-vector.cc \
+  array/int16NDArray.cc \
+  array/int32NDArray.cc \
+  array/int64NDArray.cc \
+  array/int8NDArray.cc \
+  array/MArray-C.cc \
+  array/MArray-d.cc \
+  array/MArray-f.cc \
+  array/MArray-fC.cc \
+  array/MArray-i.cc \
+  array/MArray-s.cc \
+  array/MatrixType.cc \
+  array/MSparse-C.cc \
+  array/MSparse-d.cc \
+  array/PermMatrix.cc \
+  array/Range.cc \
+  array/Sparse-b.cc \
+  array/Sparse-C.cc \
+  array/Sparse-d.cc \
+  array/uint16NDArray.cc \
+  array/uint32NDArray.cc \
+  array/uint64NDArray.cc \
+  array/uint8NDArray.cc 
+
+TEMPLATE_SRC += \
+  array/Array.cc \
+  array/DiagArray2.cc \
+  array/intNDArray.cc \
+  array/MArray.cc \
+  array/MDiagArray2.cc \
+  array/MSparse.cc \
+  array/Sparse.cc
+
+noinst_LTLIBRARIES += array/libarray.la
+
+array_libarray_la_SOURCES = $(ARRAY_SRC)
+array_libarray_la_CPPFLAGS = \
+  $(liboctave_la_CPPFLAGS) \
+  $(SPARSE_XCPPFLAGS)
+
rename from liboctave/uint16NDArray.cc
rename to liboctave/array/uint16NDArray.cc
rename from liboctave/uint16NDArray.h
rename to liboctave/array/uint16NDArray.h
rename from liboctave/uint32NDArray.cc
rename to liboctave/array/uint32NDArray.cc
rename from liboctave/uint32NDArray.h
rename to liboctave/array/uint32NDArray.h
rename from liboctave/uint64NDArray.cc
rename to liboctave/array/uint64NDArray.cc
rename from liboctave/uint64NDArray.h
rename to liboctave/array/uint64NDArray.h
rename from liboctave/uint8NDArray.cc
rename to liboctave/array/uint8NDArray.cc
rename from liboctave/uint8NDArray.h
rename to liboctave/array/uint8NDArray.h
new file mode 100644
--- /dev/null
+++ b/liboctave/cruft/Faddeeva/Faddeeva.cc
@@ -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
new file mode 100644
--- /dev/null
+++ b/liboctave/cruft/Faddeeva/Faddeeva.hh
@@ -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
new file mode 100644
--- /dev/null
+++ b/liboctave/cruft/Faddeeva/module.mk
@@ -0,0 +1,3 @@
+EXTRA_DIST += Faddeeva/module.mk
+
+libcruft_la_SOURCES += Faddeeva/Faddeeva.cc Faddeeva/Faddeeva.hh
rename from libcruft/Makefile.am
rename to liboctave/cruft/Makefile.am
--- a/libcruft/Makefile.am
+++ b/liboctave/cruft/Makefile.am
@@ -1,4 +1,4 @@
-# Makefile for octave's libcruft directory
+# Makefile for Octave's liboctave/cruft directory
 #
 # Copyright (C) 1993-2012 John W. Eaton
 #
@@ -20,62 +20,34 @@
 
 include $(top_srcdir)/build-aux/common.mk
 
+AUTOMAKE_OPTIONS = subdir-objects
+
 ## Search local directories before those specified by the user.
 AM_CPPFLAGS = \
-  -I../libgnu -I$(top_srcdir)/libgnu \
-  @CPPFLAGS@
+  -I$(top_builddir)/libgnu -I$(top_srcdir)/libgnu
 
-AUTOMAKE_OPTIONS = subdir-objects
+EXTRA_DIST = mkf77def.in
 
-octlib_LTLIBRARIES = libcruft.la
+noinst_LTLIBRARIES = libcruft.la
 
 libcruft_la_SOURCES =
 
+nodist_libcruft_la_SOURCES =
+
 libcruft_la_FFLAGS = $(F77_INTEGER_8_FLAG)
 
-libcruft_la_CPPFLAGS = \
-  @CRUFT_DLL_DEFS@ \
-  $(AM_CPPFLAGS)
-
-include link-deps.mk
-
-libcruft_la_LIBADD = \
-  libranlib.la \
-  ../libgnu/libgnu.la \
-  $(LIBCRUFT_LINK_DEPS)
-
-# Increment these as needed and according to the rules in the libtool
-# manual:
-libcruft_current = 1
-libcruft_revision = 1
-libcruft_age = 0
-
-libcruft_version_info = $(libcruft_current):$(libcruft_revision):$(libcruft_age)
-
-libcruft_la_LDFLAGS = \
-  -version-info $(libcruft_version_info) \
-  $(NO_UNDEFINED_LDFLAG) \
-  @XTRA_CRUFT_SH_LDFLAGS@ \
-  -bindir $(bindir) \
-  $(LIBCRUFT_LINK_OPTS)
+libcruft_la_CPPFLAGS = @CRUFT_DLL_DEFS@ $(AM_CPPFLAGS)
 
 libcruft_la_DEPENDENCIES = cruft.def
 
-noinst_LTLIBRARIES = libranlib.la
-
-libranlib_la_SOURCES =
-
-libranlib_la_DEPENDENCIES = ranlib.def
-
 octinclude_HEADERS =
 
-EXTRA_DIST =
-
 include amos/module.mk
 include blas-xtra/module.mk
 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
@@ -86,17 +58,14 @@
 include slatec-err/module.mk
 include slatec-fn/module.mk
 
+## Special rules for files which must be built before compilation
 cruft.def: $(libcruft_la_SOURCES) mkf77def
 	chmod a+rx mkf77def
 	./mkf77def $(srcdir) $(libcruft_la_SOURCES) > $@-t
 	mv $@-t $@
 
-ranlib.def: $(libranlib_la_SOURCES) mkf77def
-	chmod a+rx mkf77def
-	./mkf77def $(srcdir) $(libranlib_la_SOURCES) > $@-t
-	mv $@-t $@
+DISTCLEANFILES = \
+  cruft.def \
+  ranlib/ranlib.def \
+  $(nodist_libcruft_la_SOURCES)
 
-EXTRA_DIST += mkf77def.in
-
-DISTCLEANFILES = cruft.def ranlib.def
-
rename from libcruft/amos/README
rename to liboctave/cruft/amos/README
rename from libcruft/amos/cacai.f
rename to liboctave/cruft/amos/cacai.f
rename from libcruft/amos/cacon.f
rename to liboctave/cruft/amos/cacon.f
rename from libcruft/amos/cairy.f
rename to liboctave/cruft/amos/cairy.f
rename from libcruft/amos/casyi.f
rename to liboctave/cruft/amos/casyi.f
rename from libcruft/amos/cbesh.f
rename to liboctave/cruft/amos/cbesh.f
rename from libcruft/amos/cbesi.f
rename to liboctave/cruft/amos/cbesi.f
rename from libcruft/amos/cbesj.f
rename to liboctave/cruft/amos/cbesj.f
rename from libcruft/amos/cbesk.f
rename to liboctave/cruft/amos/cbesk.f
rename from libcruft/amos/cbesy.f
rename to liboctave/cruft/amos/cbesy.f
rename from libcruft/amos/cbinu.f
rename to liboctave/cruft/amos/cbinu.f
rename from libcruft/amos/cbiry.f
rename to liboctave/cruft/amos/cbiry.f
rename from libcruft/amos/cbknu.f
rename to liboctave/cruft/amos/cbknu.f
rename from libcruft/amos/cbuni.f
rename to liboctave/cruft/amos/cbuni.f
rename from libcruft/amos/cbunk.f
rename to liboctave/cruft/amos/cbunk.f
rename from libcruft/amos/ckscl.f
rename to liboctave/cruft/amos/ckscl.f
rename from libcruft/amos/cmlri.f
rename to liboctave/cruft/amos/cmlri.f
rename from libcruft/amos/crati.f
rename to liboctave/cruft/amos/crati.f
rename from libcruft/amos/cs1s2.f
rename to liboctave/cruft/amos/cs1s2.f
rename from libcruft/amos/cseri.f
rename to liboctave/cruft/amos/cseri.f
rename from libcruft/amos/cshch.f
rename to liboctave/cruft/amos/cshch.f
rename from libcruft/amos/cuchk.f
rename to liboctave/cruft/amos/cuchk.f
rename from libcruft/amos/cunhj.f
rename to liboctave/cruft/amos/cunhj.f
rename from libcruft/amos/cuni1.f
rename to liboctave/cruft/amos/cuni1.f
rename from libcruft/amos/cuni2.f
rename to liboctave/cruft/amos/cuni2.f
rename from libcruft/amos/cunik.f
rename to liboctave/cruft/amos/cunik.f
rename from libcruft/amos/cunk1.f
rename to liboctave/cruft/amos/cunk1.f
rename from libcruft/amos/cunk2.f
rename to liboctave/cruft/amos/cunk2.f
rename from libcruft/amos/cuoik.f
rename to liboctave/cruft/amos/cuoik.f
rename from libcruft/amos/cwrsk.f
rename to liboctave/cruft/amos/cwrsk.f
rename from libcruft/amos/dgamln.f
rename to liboctave/cruft/amos/dgamln.f
rename from libcruft/amos/gamln.f
rename to liboctave/cruft/amos/gamln.f
rename from libcruft/amos/module.mk
rename to liboctave/cruft/amos/module.mk
rename from libcruft/amos/xzabs.f
rename to liboctave/cruft/amos/xzabs.f
rename from libcruft/amos/xzexp.f
rename to liboctave/cruft/amos/xzexp.f
rename from libcruft/amos/xzlog.f
rename to liboctave/cruft/amos/xzlog.f
rename from libcruft/amos/xzsqrt.f
rename to liboctave/cruft/amos/xzsqrt.f
rename from libcruft/amos/zacai.f
rename to liboctave/cruft/amos/zacai.f
rename from libcruft/amos/zacon.f
rename to liboctave/cruft/amos/zacon.f
rename from libcruft/amos/zairy.f
rename to liboctave/cruft/amos/zairy.f
rename from libcruft/amos/zasyi.f
rename to liboctave/cruft/amos/zasyi.f
rename from libcruft/amos/zbesh.f
rename to liboctave/cruft/amos/zbesh.f
rename from libcruft/amos/zbesi.f
rename to liboctave/cruft/amos/zbesi.f
rename from libcruft/amos/zbesj.f
rename to liboctave/cruft/amos/zbesj.f
rename from libcruft/amos/zbesk.f
rename to liboctave/cruft/amos/zbesk.f
rename from libcruft/amos/zbesy.f
rename to liboctave/cruft/amos/zbesy.f
rename from libcruft/amos/zbinu.f
rename to liboctave/cruft/amos/zbinu.f
rename from libcruft/amos/zbiry.f
rename to liboctave/cruft/amos/zbiry.f
rename from libcruft/amos/zbknu.f
rename to liboctave/cruft/amos/zbknu.f
rename from libcruft/amos/zbuni.f
rename to liboctave/cruft/amos/zbuni.f
rename from libcruft/amos/zbunk.f
rename to liboctave/cruft/amos/zbunk.f
rename from libcruft/amos/zdiv.f
rename to liboctave/cruft/amos/zdiv.f
rename from libcruft/amos/zkscl.f
rename to liboctave/cruft/amos/zkscl.f
rename from libcruft/amos/zmlri.f
rename to liboctave/cruft/amos/zmlri.f
rename from libcruft/amos/zmlt.f
rename to liboctave/cruft/amos/zmlt.f
rename from libcruft/amos/zrati.f
rename to liboctave/cruft/amos/zrati.f
rename from libcruft/amos/zs1s2.f
rename to liboctave/cruft/amos/zs1s2.f
rename from libcruft/amos/zseri.f
rename to liboctave/cruft/amos/zseri.f
rename from libcruft/amos/zshch.f
rename to liboctave/cruft/amos/zshch.f
rename from libcruft/amos/zuchk.f
rename to liboctave/cruft/amos/zuchk.f
rename from libcruft/amos/zunhj.f
rename to liboctave/cruft/amos/zunhj.f
rename from libcruft/amos/zuni1.f
rename to liboctave/cruft/amos/zuni1.f
rename from libcruft/amos/zuni2.f
rename to liboctave/cruft/amos/zuni2.f
rename from libcruft/amos/zunik.f
rename to liboctave/cruft/amos/zunik.f
rename from libcruft/amos/zunk1.f
rename to liboctave/cruft/amos/zunk1.f
rename from libcruft/amos/zunk2.f
rename to liboctave/cruft/amos/zunk2.f
rename from libcruft/amos/zuoik.f
rename to liboctave/cruft/amos/zuoik.f
rename from libcruft/amos/zwrsk.f
rename to liboctave/cruft/amos/zwrsk.f
rename from libcruft/blas-xtra/cconv2.f
rename to liboctave/cruft/blas-xtra/cconv2.f
rename from libcruft/blas-xtra/cdotc3.f
rename to liboctave/cruft/blas-xtra/cdotc3.f
rename from libcruft/blas-xtra/cmatm3.f
rename to liboctave/cruft/blas-xtra/cmatm3.f
rename from libcruft/blas-xtra/csconv2.f
rename to liboctave/cruft/blas-xtra/csconv2.f
rename from libcruft/blas-xtra/dconv2.f
rename to liboctave/cruft/blas-xtra/dconv2.f
rename from libcruft/blas-xtra/ddot3.f
rename to liboctave/cruft/blas-xtra/ddot3.f
rename from libcruft/blas-xtra/dmatm3.f
rename to liboctave/cruft/blas-xtra/dmatm3.f
rename from libcruft/blas-xtra/module.mk
rename to liboctave/cruft/blas-xtra/module.mk
rename from libcruft/blas-xtra/sconv2.f
rename to liboctave/cruft/blas-xtra/sconv2.f
rename from libcruft/blas-xtra/sdot3.f
rename to liboctave/cruft/blas-xtra/sdot3.f
rename from libcruft/blas-xtra/smatm3.f
rename to liboctave/cruft/blas-xtra/smatm3.f
rename from libcruft/blas-xtra/xcdotc.f
rename to liboctave/cruft/blas-xtra/xcdotc.f
rename from libcruft/blas-xtra/xcdotu.f
rename to liboctave/cruft/blas-xtra/xcdotu.f
rename from libcruft/blas-xtra/xddot.f
rename to liboctave/cruft/blas-xtra/xddot.f
rename from libcruft/blas-xtra/xdnrm2.f
rename to liboctave/cruft/blas-xtra/xdnrm2.f
rename from libcruft/blas-xtra/xdznrm2.f
rename to liboctave/cruft/blas-xtra/xdznrm2.f
rename from libcruft/blas-xtra/xerbla.f
rename to liboctave/cruft/blas-xtra/xerbla.f
rename from libcruft/blas-xtra/xscnrm2.f
rename to liboctave/cruft/blas-xtra/xscnrm2.f
rename from libcruft/blas-xtra/xsdot.f
rename to liboctave/cruft/blas-xtra/xsdot.f
rename from libcruft/blas-xtra/xsnrm2.f
rename to liboctave/cruft/blas-xtra/xsnrm2.f
rename from libcruft/blas-xtra/xzdotc.f
rename to liboctave/cruft/blas-xtra/xzdotc.f
rename from libcruft/blas-xtra/xzdotu.f
rename to liboctave/cruft/blas-xtra/xzdotu.f
rename from libcruft/blas-xtra/zconv2.f
rename to liboctave/cruft/blas-xtra/zconv2.f
rename from libcruft/blas-xtra/zdconv2.f
rename to liboctave/cruft/blas-xtra/zdconv2.f
rename from libcruft/blas-xtra/zdotc3.f
rename to liboctave/cruft/blas-xtra/zdotc3.f
rename from libcruft/blas-xtra/zmatm3.f
rename to liboctave/cruft/blas-xtra/zmatm3.f
rename from libcruft/daspk/datv.f
rename to liboctave/cruft/daspk/datv.f
rename from libcruft/daspk/dcnst0.f
rename to liboctave/cruft/daspk/dcnst0.f
rename from libcruft/daspk/dcnstr.f
rename to liboctave/cruft/daspk/dcnstr.f
rename from libcruft/daspk/ddasic.f
rename to liboctave/cruft/daspk/ddasic.f
rename from libcruft/daspk/ddasid.f
rename to liboctave/cruft/daspk/ddasid.f
rename from libcruft/daspk/ddasik.f
rename to liboctave/cruft/daspk/ddasik.f
rename from libcruft/daspk/ddaspk.f
rename to liboctave/cruft/daspk/ddaspk.f
rename from libcruft/daspk/ddstp.f
rename to liboctave/cruft/daspk/ddstp.f
rename from libcruft/daspk/ddwnrm.f
rename to liboctave/cruft/daspk/ddwnrm.f
rename from libcruft/daspk/dfnrmd.f
rename to liboctave/cruft/daspk/dfnrmd.f
rename from libcruft/daspk/dfnrmk.f
rename to liboctave/cruft/daspk/dfnrmk.f
rename from libcruft/daspk/dhels.f
rename to liboctave/cruft/daspk/dhels.f
rename from libcruft/daspk/dheqr.f
rename to liboctave/cruft/daspk/dheqr.f
rename from libcruft/daspk/dinvwt.f
rename to liboctave/cruft/daspk/dinvwt.f
rename from libcruft/daspk/dlinsd.f
rename to liboctave/cruft/daspk/dlinsd.f
rename from libcruft/daspk/dlinsk.f
rename to liboctave/cruft/daspk/dlinsk.f
rename from libcruft/daspk/dmatd.f
rename to liboctave/cruft/daspk/dmatd.f
rename from libcruft/daspk/dnedd.f
rename to liboctave/cruft/daspk/dnedd.f
rename from libcruft/daspk/dnedk.f
rename to liboctave/cruft/daspk/dnedk.f
rename from libcruft/daspk/dnsd.f
rename to liboctave/cruft/daspk/dnsd.f
rename from libcruft/daspk/dnsid.f
rename to liboctave/cruft/daspk/dnsid.f
rename from libcruft/daspk/dnsik.f
rename to liboctave/cruft/daspk/dnsik.f
rename from libcruft/daspk/dnsk.f
rename to liboctave/cruft/daspk/dnsk.f
rename from libcruft/daspk/dorth.f
rename to liboctave/cruft/daspk/dorth.f
rename from libcruft/daspk/dslvd.f
rename to liboctave/cruft/daspk/dslvd.f
rename from libcruft/daspk/dslvk.f
rename to liboctave/cruft/daspk/dslvk.f
rename from libcruft/daspk/dspigm.f
rename to liboctave/cruft/daspk/dspigm.f
rename from libcruft/daspk/dyypnw.f
rename to liboctave/cruft/daspk/dyypnw.f
rename from libcruft/daspk/module.mk
rename to liboctave/cruft/daspk/module.mk
rename from libcruft/dasrt/ddasrt.f
rename to liboctave/cruft/dasrt/ddasrt.f
rename from libcruft/dasrt/drchek.f
rename to liboctave/cruft/dasrt/drchek.f
rename from libcruft/dasrt/droots.f
rename to liboctave/cruft/dasrt/droots.f
rename from libcruft/dasrt/module.mk
rename to liboctave/cruft/dasrt/module.mk
rename from libcruft/dassl/ddaini.f
rename to liboctave/cruft/dassl/ddaini.f
rename from libcruft/dassl/ddajac.f
rename to liboctave/cruft/dassl/ddajac.f
rename from libcruft/dassl/ddanrm.f
rename to liboctave/cruft/dassl/ddanrm.f
rename from libcruft/dassl/ddaslv.f
rename to liboctave/cruft/dassl/ddaslv.f
rename from libcruft/dassl/ddassl.f
rename to liboctave/cruft/dassl/ddassl.f
rename from libcruft/dassl/ddastp.f
rename to liboctave/cruft/dassl/ddastp.f
rename from libcruft/dassl/ddatrp.f
rename to liboctave/cruft/dassl/ddatrp.f
rename from libcruft/dassl/ddawts.f
rename to liboctave/cruft/dassl/ddawts.f
rename from libcruft/dassl/module.mk
rename to liboctave/cruft/dassl/module.mk
rename from libcruft/fftpack/cfftb.f
rename to liboctave/cruft/fftpack/cfftb.f
rename from libcruft/fftpack/cfftb1.f
rename to liboctave/cruft/fftpack/cfftb1.f
rename from libcruft/fftpack/cfftf.f
rename to liboctave/cruft/fftpack/cfftf.f
rename from libcruft/fftpack/cfftf1.f
rename to liboctave/cruft/fftpack/cfftf1.f
rename from libcruft/fftpack/cffti.f
rename to liboctave/cruft/fftpack/cffti.f
rename from libcruft/fftpack/cffti1.f
rename to liboctave/cruft/fftpack/cffti1.f
rename from libcruft/fftpack/fftpack.doc
rename to liboctave/cruft/fftpack/fftpack.doc
rename from libcruft/fftpack/module.mk
rename to liboctave/cruft/fftpack/module.mk
rename from libcruft/fftpack/passb.f
rename to liboctave/cruft/fftpack/passb.f
rename from libcruft/fftpack/passb2.f
rename to liboctave/cruft/fftpack/passb2.f
rename from libcruft/fftpack/passb3.f
rename to liboctave/cruft/fftpack/passb3.f
rename from libcruft/fftpack/passb4.f
rename to liboctave/cruft/fftpack/passb4.f
rename from libcruft/fftpack/passb5.f
rename to liboctave/cruft/fftpack/passb5.f
rename from libcruft/fftpack/passf.f
rename to liboctave/cruft/fftpack/passf.f
rename from libcruft/fftpack/passf2.f
rename to liboctave/cruft/fftpack/passf2.f
rename from libcruft/fftpack/passf3.f
rename to liboctave/cruft/fftpack/passf3.f
rename from libcruft/fftpack/passf4.f
rename to liboctave/cruft/fftpack/passf4.f
rename from libcruft/fftpack/passf5.f
rename to liboctave/cruft/fftpack/passf5.f
rename from libcruft/fftpack/zfftb.f
rename to liboctave/cruft/fftpack/zfftb.f
rename from libcruft/fftpack/zfftb1.f
rename to liboctave/cruft/fftpack/zfftb1.f
rename from libcruft/fftpack/zfftf.f
rename to liboctave/cruft/fftpack/zfftf.f
rename from libcruft/fftpack/zfftf1.f
rename to liboctave/cruft/fftpack/zfftf1.f
rename from libcruft/fftpack/zffti.f
rename to liboctave/cruft/fftpack/zffti.f
rename from libcruft/fftpack/zffti1.f
rename to liboctave/cruft/fftpack/zffti1.f
rename from libcruft/fftpack/zpassb.f
rename to liboctave/cruft/fftpack/zpassb.f
rename from libcruft/fftpack/zpassb2.f
rename to liboctave/cruft/fftpack/zpassb2.f
rename from libcruft/fftpack/zpassb3.f
rename to liboctave/cruft/fftpack/zpassb3.f
rename from libcruft/fftpack/zpassb4.f
rename to liboctave/cruft/fftpack/zpassb4.f
rename from libcruft/fftpack/zpassb5.f
rename to liboctave/cruft/fftpack/zpassb5.f
rename from libcruft/fftpack/zpassf.f
rename to liboctave/cruft/fftpack/zpassf.f
rename from libcruft/fftpack/zpassf2.f
rename to liboctave/cruft/fftpack/zpassf2.f
rename from libcruft/fftpack/zpassf3.f
rename to liboctave/cruft/fftpack/zpassf3.f
rename from libcruft/fftpack/zpassf4.f
rename to liboctave/cruft/fftpack/zpassf4.f
rename from libcruft/fftpack/zpassf5.f
rename to liboctave/cruft/fftpack/zpassf5.f
rename from libcruft/lapack-xtra/crsf2csf.f
rename to liboctave/cruft/lapack-xtra/crsf2csf.f
rename from libcruft/lapack-xtra/module.mk
rename to liboctave/cruft/lapack-xtra/module.mk
rename from libcruft/lapack-xtra/xclange.f
rename to liboctave/cruft/lapack-xtra/xclange.f
rename from libcruft/lapack-xtra/xdlamch.f
rename to liboctave/cruft/lapack-xtra/xdlamch.f
rename from libcruft/lapack-xtra/xdlange.f
rename to liboctave/cruft/lapack-xtra/xdlange.f
rename from libcruft/lapack-xtra/xilaenv.f
rename to liboctave/cruft/lapack-xtra/xilaenv.f
rename from libcruft/lapack-xtra/xslamch.f
rename to liboctave/cruft/lapack-xtra/xslamch.f
rename from libcruft/lapack-xtra/xslange.f
rename to liboctave/cruft/lapack-xtra/xslange.f
rename from libcruft/lapack-xtra/xzlange.f
rename to liboctave/cruft/lapack-xtra/xzlange.f
rename from libcruft/lapack-xtra/zrsf2csf.f
rename to liboctave/cruft/lapack-xtra/zrsf2csf.f
rename from libcruft/misc/blaswrap.c
rename to liboctave/cruft/misc/blaswrap.c
rename from libcruft/misc/cquit.c
rename to liboctave/cruft/misc/cquit.c
--- a/libcruft/misc/cquit.c
+++ b/liboctave/cruft/misc/cquit.c
@@ -43,176 +43,6 @@
   memcpy (current_context, save_buf, sizeof (octave_jmp_buf));
 }
 
-#if defined (__WIN32__) && ! defined (_POSIX_VERSION)
-
-/* FIXME -- eventually remove the debugging */
-#if defined (DEBUG)
-
-#define PRINT_CURRENT_THREAD() printf ("%lx: ", GetCurrentThreadId ())
-
-#define DEBUGs(s) \
-  do \
-    { \
-      PRINT_CURRENT_THREAD (); \
-      printf (s "\n"); \
-      fflush (stdout); \
-    } \
-  while (0)
-
-#define DEBUGd(s, d) \
-  do \
-    { \
-      PRINT_CURRENT_THREAD (); \
-      printf (s "\n", d); \
-      fflush (stdout); \
-    } \
-  while (0)
-
-#else
-#define DEBUGs(s)
-#define DEBUGd(s, d)
-#endif
-
-CRITICAL_SECTION w32_thread_setjmp_mutex;
-static CONTEXT w32_signal_context;
-static int w32_signal_to_raise = 0;
-static DWORD w32_main_thread_id;
-static HANDLE w32_main_thread;
-static HANDLE w32_restore_thread = NULL;
-
-int
-w32_in_main_thread(void)
-{
-  return (GetCurrentThreadId () == w32_main_thread_id);
-}
-
-static DWORD WINAPI
-w32_reset_context (LPVOID v)
-{
-  PCONTEXT context = (PCONTEXT)v;
-  int ret;
-
-  /* Mutex the setjmp/longjmp */
-  EnterCriticalSection (&w32_thread_setjmp_mutex);
-
-  DEBUGs ("enter w32_set_context");
-  SuspendThread (w32_main_thread);
-  DEBUGs ("main suspended");
-  if (! SetThreadContext (w32_main_thread, context))
-    {
-      fprintf (stderr, "%lx: context failed: ctrl-c won't work\n",
-               GetCurrentThreadId ());
-      fflush (stderr);
-    }
-  DEBUGs ("context captured (or not)");
-  ret = ResumeThread (w32_main_thread);
-  DEBUGd ("main resumed with %d", ret);
-
-  LeaveCriticalSection (&w32_thread_setjmp_mutex);
-  return 0;
-}
-
-static void
-w32_raise_in_main (void)
-{
-  DWORD threadid;
-
-  DEBUGd ("w32_raise_in_main with signal %d", w32_signal_to_raise);
-  raise (w32_signal_to_raise);
-  DEBUGd ("w32_raise_in_main signal %d returned a value",
-          w32_signal_to_raise);
-
-  DEBUGs ("attempting to restore main to pre-signal configuration");
-  if (w32_restore_thread != NULL) /* Catch leaky threads */
-    CloseHandle (w32_restore_thread);
-  w32_restore_thread = CreateThread (NULL, 10000, w32_reset_context,
-                                     &w32_signal_context, 0, &threadid);
-  if (w32_restore_thread == NULL)
-    {
-      fprintf (stderr, "w32_raise_in_main couldn't create thread\n");
-      fflush (stderr);
-    }
-  else
-    {
-      DEBUGs ("waiting to restore raise context");
-      WaitForSingleObject (w32_restore_thread, INFINITE);
-      fprintf (stderr, "w32_raise_in_main couldn't restore context\n");
-      fflush (stderr);
-    }
-}
-
-void
-w32_raise_final (void)
-{
-  CloseHandle (w32_main_thread);
-  if (w32_restore_thread != NULL) /* Catch leaky threads */
-    CloseHandle (w32_restore_thread);
-  w32_main_thread = w32_restore_thread = NULL;
-}
-
-/* Raise the given signal in the main thread.  w32_raise_init ()
-   must have been called from the main thread already.  */
-void
-w32_raise (int sig)
-{
-  int ret;
-
-  if (w32_in_main_thread ())
-    {
-      /* Called from main thread -- a simple raise () should work.  */
-      DEBUGd ("raising signal %d within main", signal);
-      raise (sig);
-      DEBUGd ("returning from signal %d within main", signal);
-    }
-  else
-    {
-      /* Called from alternate thread -- call w32_raise_in_main in the
-         main thread with w32_signal_to_raise set to the signal */
-      CONTEXT raise_context;
-      DEBUGd ("raising signal %d from separate thread", signal);
-
-      /* Suspend main and remember the context.  */
-      SuspendThread (w32_main_thread);
-      /* X86 code */
-      w32_signal_context.ContextFlags
-        = CONTEXT_FULL|CONTEXT_FLOATING_POINT|CONTEXT_DEBUG_REGISTERS;
-      GetThreadContext (w32_main_thread, &w32_signal_context);
-
-      /* Change the context to w32_raise_in_main.  The
-         context.Eip=&fn trick for setting the program counter is
-         courtesy of
-
-           http://fit.c2.com/files/LispPlatform/lisp/clisp-2.28/src/win32aux.d
-
-         Auxiliary functions for CLISP on Win32, Bruno Haible
-         1997-1999.  */
-
-      memcpy (&raise_context, &w32_signal_context, sizeof (CONTEXT));
-      raise_context.Eip = (DWORD)&w32_raise_in_main; /* X86 code */
-      w32_signal_to_raise = sig;
-      SetThreadContext (w32_main_thread, &raise_context);
-
-      /* Resume main at w32_raise_in_main */
-      ret = ResumeThread (w32_main_thread);
-      DEBUGd ("main resumed at w32_raise_in_main with suspend count %d",
-              ret);
-    }
-}
-
-void
-w32_sigint_init (void)
-{
-  /* Capture main context */
-  w32_main_thread_id = GetCurrentThreadId ();
-  DuplicateHandle (GetCurrentProcess (), GetCurrentThread (),
-                   GetCurrentProcess (), &w32_main_thread,
-                   0, FALSE, DUPLICATE_SAME_ACCESS);
-
-  InitializeCriticalSectionAndSpinCount (&w32_thread_setjmp_mutex, 0);
-}
-
-#endif /* #if defined (__WIN32__) && ! defined (_POSIX_VERSION) */
-
 void
 octave_jump_to_enclosing_context (void)
 {
rename from libcruft/misc/d1mach-tst.for
rename to liboctave/cruft/misc/d1mach-tst.for
rename from libcruft/misc/d1mach.f
rename to liboctave/cruft/misc/d1mach.f
rename from libcruft/misc/f77-extern.cc
rename to liboctave/cruft/misc/f77-extern.cc
rename from libcruft/misc/f77-fcn.c
rename to liboctave/cruft/misc/f77-fcn.c
--- a/libcruft/misc/f77-fcn.c
+++ b/liboctave/cruft/misc/f77-fcn.c
@@ -60,5 +60,5 @@
 
   octave_jump_to_enclosing_context ();
 
-  F77_RETURN (0)
+  F77_NORETURN (0)
 }
rename from libcruft/misc/f77-fcn.h
rename to liboctave/cruft/misc/f77-fcn.h
--- a/libcruft/misc/f77-fcn.h
+++ b/liboctave/cruft/misc/f77-fcn.h
@@ -81,6 +81,57 @@
 #define F77_FCN(f, F) F77_FUNC (f, F)
 #endif
 
+/*
+
+The following macros are used for handling Fortran <-> C calling
+conventions.  They are defined below for three different types of
+systems, Cray (possibly now obsolete), Visual Fortran, and any system
+that is compatible with the f2c calling conventions, including g77 and
+gfortran.  Note that gfortran is not completely compatible with the
+f2c calling conventions, but that we only use the parts that are
+compatible.  For example, f2c and gfortran differ in the way they
+handle Fortran functions that return complex values, but Octave does
+not call any Fortran functions like that directly from C or C++.
+
+Use these macros to pass character strings from C to Fortran:
+
+  F77_CHAR_ARG(x)
+  F77_CONST_CHAR_ARG(x)
+  F77_CXX_STRING_ARG(x)
+  F77_CHAR_ARG_LEN(l)
+  F77_CHAR_ARG_DECL
+  F77_CONST_CHAR_ARG_DECL
+  F77_CHAR_ARG_LEN_DECL
+
+Use these macros to write C-language functions that accept
+Fortran-style character strings:
+
+  F77_CHAR_ARG_DEF(s, len)
+  F77_CONST_CHAR_ARG_DEF(s, len)
+  F77_CHAR_ARG_LEN_DEF(len)
+  F77_CHAR_ARG_USE(s)
+  F77_CHAR_ARG_LEN_USE(s, len)
+
+Use this macro to declare the return type of a C-language function
+that is supposed to act like a Fortran subroutine:
+
+  F77_RET_T int
+
+Use these macros to return from C-language functions that are supposed
+to act like Fortran subroutines.  F77_NORETURN is intended to be used
+as the last statement of such a function that has been tagged with a
+"noreturn" attribute.  If the compiler supports the "noreturn"
+attribute or if F77_RET_T is void, then it should expand to nothing so
+that we avoid warnings about functions tagged as "noreturn"
+containing a return statement.  Otherwise, it should expand to a
+statement that returns the given value so that we avoid warnings about
+not returning a value from a function declared to return something.
+
+  F77_RETURN(retval)
+  F77_NORETURN(retval)
+
+*/
+
 #if defined (F77_USES_CRAY_CALLING_CONVENTION)
 
 #include <fortran.h>
@@ -106,8 +157,20 @@
 #define F77_CHAR_ARG_USE(s) s.ptr
 #define F77_CHAR_ARG_LEN_USE(s, len) (s.mask.len>>3)
 
+/* Use this macro to declare the return type of a C-language function
+   that is supposed to act like a Fortran subroutine.  */
 #define F77_RET_T int
+
+/* Use these macros to return from C-language functions that are
+   supposed to act like Fortran subroutines.  F77_NORETURN is intended
+   to be used as the last statement of such a function that has been
+   tagged with a "noreturn" attribute.  */
 #define F77_RETURN(retval) return retval;
+#if defined (HAVE_ATTR_NORETURN)
+#define F77_NORETURN(retval)
+#else
+#define F77_NORETURN(retval) return retval;
+#endif
 
 /* FIXME -- these should work for SV1 or Y-MP systems but will
    need to be changed for others.  */
@@ -167,8 +230,6 @@
 #define F77_CONST_CHAR_ARG_DECL const char *, int
 #define F77_CHAR_ARG_LEN_DECL
 
-/* Use these macros to write C-language functions that accept
-   Fortran-style character strings.  */
 #define F77_CHAR_ARG_DEF(s, len) char *s, int len
 #define F77_CONST_CHAR_ARG_DEF(s, len) const char *s, int len
 #define F77_CHAR_ARG_LEN_DEF(len)
@@ -176,13 +237,14 @@
 #define F77_CHAR_ARG_LEN_USE(s, len) len
 
 #define F77_RET_T void
-#define F77_RETURN(retval)
+
+#define F77_RETURN(retval) return;
+#define F77_NORETURN(retval)
 
 #else
 
 /* Assume f2c-compatible calling convention.  */
 
-/* Use these macros to pass character strings from C to Fortran.  */
 #define F77_CHAR_ARG(x) x
 #define F77_CONST_CHAR_ARG(x) F77_CHAR_ARG (x)
 #define F77_CHAR_ARG2(x, l) x
@@ -193,8 +255,6 @@
 #define F77_CONST_CHAR_ARG_DECL const char *
 #define F77_CHAR_ARG_LEN_DECL , long
 
-/* Use these macros to write C-language functions that accept
-   Fortran-style character strings.  */
 #define F77_CHAR_ARG_DEF(s, len) char *s
 #define F77_CONST_CHAR_ARG_DEF(s, len) const char *s
 #define F77_CHAR_ARG_LEN_DEF(len) , long len
@@ -202,7 +262,13 @@
 #define F77_CHAR_ARG_LEN_USE(s, len) len
 
 #define F77_RET_T int
+
 #define F77_RETURN(retval) return retval;
+#if defined (HAVE_ATTR_NORETURN)
+#define F77_NORETURN(retval)
+#else
+#define F77_NORETURN(retval) return retval;
+#endif
 
 #endif
 
rename from libcruft/misc/i1mach.f
rename to liboctave/cruft/misc/i1mach.f
rename from libcruft/misc/lo-error.c
rename to liboctave/cruft/misc/lo-error.c
--- a/libcruft/misc/lo-error.c
+++ b/liboctave/cruft/misc/lo-error.c
@@ -111,6 +111,7 @@
 liboctave_fatal_with_id (const char *id, const char *fmt, ...)
 {
   va_list args;
+  (void) id; /*unused*/
   va_start (args, fmt);
   verror ("fatal", fmt, args);
   va_end (args);
@@ -131,6 +132,7 @@
 liboctave_warning_with_id (const char *id, const char *fmt, ...)
 {
   va_list args;
+  (void) id; /*unused*/
   va_start (args, fmt);
   verror ("warning", fmt, args);
   va_end (args);
rename from libcruft/misc/lo-error.h
rename to liboctave/cruft/misc/lo-error.h
rename from libcruft/misc/module.mk
rename to liboctave/cruft/misc/module.mk
rename from libcruft/misc/quit.cc
rename to liboctave/cruft/misc/quit.cc
rename from libcruft/misc/quit.h
rename to liboctave/cruft/misc/quit.h
rename from libcruft/misc/r1mach.f
rename to liboctave/cruft/misc/r1mach.f
rename from libcruft/mkf77def.in
rename to liboctave/cruft/mkf77def.in
--- a/libcruft/mkf77def.in
+++ b/liboctave/cruft/mkf77def.in
@@ -25,19 +25,19 @@
 F77_APPEND_UNDERSCORE="@F77_APPEND_UNDERSCORE@"
 F77_APPEND_EXTRA_UNDERSCORE="@F77_APPEND_EXTRA_UNDERSCORE@"
 
-if $F77_TOLOWER; then
+if test x$F77_TOLOWER = xyes; then
   case_cmd="tolower";
 else
   case_cmd="toupper";
 fi
 
-if $F77_APPEND_UNDERSCORE; then
+if test x$F77_APPEND_UNDERSCORE = xyes; then
   uscore="_";
 else
   uscore="";
 fi
 
-if $F77_APPEND_EXTRA_UNDERSCORE; then
+if test x$F77_APPEND_EXTRA_UNDERSCORE = xyes; then
   awkcmd="$AWK '{ if (\$0 ~ /_/) extra = \"_\"; else extra = \"\"; printf (\"%s%s%s\n\", $case_cmd (\$0), \"$uscore\", extra); }'"
 else
   awkcmd="$AWK '{ printf (\"%s%s\n\", tolower (\$0), \"$uscore\"); }'"
rename from libcruft/odepack/cfode.f
rename to liboctave/cruft/odepack/cfode.f
rename from libcruft/odepack/dlsode.f
rename to liboctave/cruft/odepack/dlsode.f
rename from libcruft/odepack/ewset.f
rename to liboctave/cruft/odepack/ewset.f
rename from libcruft/odepack/intdy.f
rename to liboctave/cruft/odepack/intdy.f
rename from libcruft/odepack/module.mk
rename to liboctave/cruft/odepack/module.mk
rename from libcruft/odepack/prepj.f
rename to liboctave/cruft/odepack/prepj.f
rename from libcruft/odepack/scfode.f
rename to liboctave/cruft/odepack/scfode.f
rename from libcruft/odepack/sewset.f
rename to liboctave/cruft/odepack/sewset.f
rename from libcruft/odepack/sintdy.f
rename to liboctave/cruft/odepack/sintdy.f
rename from libcruft/odepack/slsode.f
rename to liboctave/cruft/odepack/slsode.f
rename from libcruft/odepack/solsy.f
rename to liboctave/cruft/odepack/solsy.f
rename from libcruft/odepack/sprepj.f
rename to liboctave/cruft/odepack/sprepj.f
rename from libcruft/odepack/ssolsy.f
rename to liboctave/cruft/odepack/ssolsy.f
rename from libcruft/odepack/sstode.f
rename to liboctave/cruft/odepack/sstode.f
rename from libcruft/odepack/stode.f
rename to liboctave/cruft/odepack/stode.f
rename from libcruft/odepack/svnorm.f
rename to liboctave/cruft/odepack/svnorm.f
rename from libcruft/odepack/vnorm.f
rename to liboctave/cruft/odepack/vnorm.f
rename from libcruft/ordered-qz/README
rename to liboctave/cruft/ordered-qz/README
rename from libcruft/ordered-qz/dsubsp.f
rename to liboctave/cruft/ordered-qz/dsubsp.f
rename from libcruft/ordered-qz/exchqz.f
rename to liboctave/cruft/ordered-qz/exchqz.f
rename from libcruft/ordered-qz/module.mk
rename to liboctave/cruft/ordered-qz/module.mk
rename from libcruft/ordered-qz/sexchqz.f
rename to liboctave/cruft/ordered-qz/sexchqz.f
rename from libcruft/ordered-qz/ssubsp.f
rename to liboctave/cruft/ordered-qz/ssubsp.f
rename from libcruft/quadpack/dqagi.f
rename to liboctave/cruft/quadpack/dqagi.f
rename from libcruft/quadpack/dqagie.f
rename to liboctave/cruft/quadpack/dqagie.f
rename from libcruft/quadpack/dqagp.f
rename to liboctave/cruft/quadpack/dqagp.f
rename from libcruft/quadpack/dqagpe.f
rename to liboctave/cruft/quadpack/dqagpe.f
rename from libcruft/quadpack/dqelg.f
rename to liboctave/cruft/quadpack/dqelg.f
rename from libcruft/quadpack/dqk15i.f
rename to liboctave/cruft/quadpack/dqk15i.f
rename from libcruft/quadpack/dqk21.f
rename to liboctave/cruft/quadpack/dqk21.f
rename from libcruft/quadpack/dqpsrt.f
rename to liboctave/cruft/quadpack/dqpsrt.f
rename from libcruft/quadpack/module.mk
rename to liboctave/cruft/quadpack/module.mk
rename from libcruft/quadpack/qagi.f
rename to liboctave/cruft/quadpack/qagi.f
rename from libcruft/quadpack/qagie.f
rename to liboctave/cruft/quadpack/qagie.f
rename from libcruft/quadpack/qagp.f
rename to liboctave/cruft/quadpack/qagp.f
rename from libcruft/quadpack/qagpe.f
rename to liboctave/cruft/quadpack/qagpe.f
rename from libcruft/quadpack/qelg.f
rename to liboctave/cruft/quadpack/qelg.f
rename from libcruft/quadpack/qk15i.f
rename to liboctave/cruft/quadpack/qk15i.f
rename from libcruft/quadpack/qk21.f
rename to liboctave/cruft/quadpack/qk21.f
rename from libcruft/quadpack/qpsrt.f
rename to liboctave/cruft/quadpack/qpsrt.f
rename from libcruft/quadpack/xerror.f
rename to liboctave/cruft/quadpack/xerror.f
rename from libcruft/ranlib/Basegen.doc
rename to liboctave/cruft/ranlib/Basegen.doc
rename from libcruft/ranlib/HOWTOGET
rename to liboctave/cruft/ranlib/HOWTOGET
rename from libcruft/ranlib/README
rename to liboctave/cruft/ranlib/README
rename from libcruft/ranlib/advnst.f
rename to liboctave/cruft/ranlib/advnst.f
rename from libcruft/ranlib/genbet.f
rename to liboctave/cruft/ranlib/genbet.f
rename from libcruft/ranlib/genchi.f
rename to liboctave/cruft/ranlib/genchi.f
rename from libcruft/ranlib/genexp.f
rename to liboctave/cruft/ranlib/genexp.f
rename from libcruft/ranlib/genf.f
rename to liboctave/cruft/ranlib/genf.f
rename from libcruft/ranlib/gengam.f
rename to liboctave/cruft/ranlib/gengam.f
rename from libcruft/ranlib/genmn.f
rename to liboctave/cruft/ranlib/genmn.f
rename from libcruft/ranlib/genmul.f
rename to liboctave/cruft/ranlib/genmul.f
rename from libcruft/ranlib/gennch.f
rename to liboctave/cruft/ranlib/gennch.f
rename from libcruft/ranlib/gennf.f
rename to liboctave/cruft/ranlib/gennf.f
rename from libcruft/ranlib/gennor.f
rename to liboctave/cruft/ranlib/gennor.f
rename from libcruft/ranlib/genprm.f
rename to liboctave/cruft/ranlib/genprm.f
rename from libcruft/ranlib/genunf.f
rename to liboctave/cruft/ranlib/genunf.f
rename from libcruft/ranlib/getcgn.f
rename to liboctave/cruft/ranlib/getcgn.f
rename from libcruft/ranlib/getsd.f
rename to liboctave/cruft/ranlib/getsd.f
rename from libcruft/ranlib/ignbin.f
rename to liboctave/cruft/ranlib/ignbin.f
rename from libcruft/ranlib/ignlgi.f
rename to liboctave/cruft/ranlib/ignlgi.f
rename from libcruft/ranlib/ignnbn.f
rename to liboctave/cruft/ranlib/ignnbn.f
rename from libcruft/ranlib/ignpoi.f
rename to liboctave/cruft/ranlib/ignpoi.f
rename from libcruft/ranlib/ignuin.f
rename to liboctave/cruft/ranlib/ignuin.f
rename from libcruft/ranlib/initgn.f
rename to liboctave/cruft/ranlib/initgn.f
rename from libcruft/ranlib/inrgcm.f
rename to liboctave/cruft/ranlib/inrgcm.f
rename from libcruft/ranlib/lennob.f
rename to liboctave/cruft/ranlib/lennob.f
rename from libcruft/ranlib/mltmod.f
rename to liboctave/cruft/ranlib/mltmod.f
rename from libcruft/ranlib/module.mk
rename to liboctave/cruft/ranlib/module.mk
--- a/libcruft/ranlib/module.mk
+++ b/liboctave/cruft/ranlib/module.mk
@@ -9,7 +9,7 @@
   ranlib/tstgmn.for \
   ranlib/tstmid.for
 
-libranlib_la_SOURCES += \
+RANLIB_SRC = \
   ranlib/advnst.f \
   ranlib/genbet.f \
   ranlib/genchi.f \
@@ -45,3 +45,16 @@
   ranlib/sgamma.f \
   ranlib/snorm.f \
   ranlib/wrap.f
+
+noinst_LTLIBRARIES += ranlib/libranlib.la
+
+ranlib_libranlib_la_SOURCES = $(RANLIB_SRC)
+
+ranlib_libranlib_la_DEPENDENCIES = ranlib/ranlib.def
+
+## Special rules for files which must be built before compilation
+ranlib/ranlib.def: $(RANLIB_SRC) mkf77def
+	chmod a+rx mkf77def
+	./mkf77def $(srcdir) $(RANLIB_SRC) > $@-t
+	mv $@-t $@
+
rename from libcruft/ranlib/phrtsd.f
rename to liboctave/cruft/ranlib/phrtsd.f
rename from libcruft/ranlib/qrgnin.f
rename to liboctave/cruft/ranlib/qrgnin.f
rename from libcruft/ranlib/randlib.chs
rename to liboctave/cruft/ranlib/randlib.chs
rename from libcruft/ranlib/randlib.fdoc
rename to liboctave/cruft/ranlib/randlib.fdoc
rename from libcruft/ranlib/ranf.f
rename to liboctave/cruft/ranlib/ranf.f
rename from libcruft/ranlib/setall.f
rename to liboctave/cruft/ranlib/setall.f
rename from libcruft/ranlib/setant.f
rename to liboctave/cruft/ranlib/setant.f
rename from libcruft/ranlib/setgmn.f
rename to liboctave/cruft/ranlib/setgmn.f
rename from libcruft/ranlib/setsd.f
rename to liboctave/cruft/ranlib/setsd.f
rename from libcruft/ranlib/sexpo.f
rename to liboctave/cruft/ranlib/sexpo.f
rename from libcruft/ranlib/sgamma.f
rename to liboctave/cruft/ranlib/sgamma.f
rename from libcruft/ranlib/snorm.f
rename to liboctave/cruft/ranlib/snorm.f
rename from libcruft/ranlib/tstbot.for
rename to liboctave/cruft/ranlib/tstbot.for
rename from libcruft/ranlib/tstgmn.for
rename to liboctave/cruft/ranlib/tstgmn.for
rename from libcruft/ranlib/tstmid.for
rename to liboctave/cruft/ranlib/tstmid.for
rename from libcruft/ranlib/wrap.f
rename to liboctave/cruft/ranlib/wrap.f
rename from libcruft/slatec-err/fdump.f
rename to liboctave/cruft/slatec-err/fdump.f
rename from libcruft/slatec-err/ixsav.f
rename to liboctave/cruft/slatec-err/ixsav.f
rename from libcruft/slatec-err/j4save.f
rename to liboctave/cruft/slatec-err/j4save.f
rename from libcruft/slatec-err/module.mk
rename to liboctave/cruft/slatec-err/module.mk
rename from libcruft/slatec-err/xerclr.f
rename to liboctave/cruft/slatec-err/xerclr.f
rename from libcruft/slatec-err/xercnt.f
rename to liboctave/cruft/slatec-err/xercnt.f
rename from libcruft/slatec-err/xerhlt.f
rename to liboctave/cruft/slatec-err/xerhlt.f
rename from libcruft/slatec-err/xermsg.f
rename to liboctave/cruft/slatec-err/xermsg.f
rename from libcruft/slatec-err/xerprn.f
rename to liboctave/cruft/slatec-err/xerprn.f
rename from libcruft/slatec-err/xerrwd.f
rename to liboctave/cruft/slatec-err/xerrwd.f
rename from libcruft/slatec-err/xersve.f
rename to liboctave/cruft/slatec-err/xersve.f
rename from libcruft/slatec-err/xgetf.f
rename to liboctave/cruft/slatec-err/xgetf.f
rename from libcruft/slatec-err/xgetua.f
rename to liboctave/cruft/slatec-err/xgetua.f
rename from libcruft/slatec-err/xsetf.f
rename to liboctave/cruft/slatec-err/xsetf.f
rename from libcruft/slatec-err/xsetua.f
rename to liboctave/cruft/slatec-err/xsetua.f
rename from libcruft/slatec-fn/acosh.f
rename to liboctave/cruft/slatec-fn/acosh.f
rename from libcruft/slatec-fn/albeta.f
rename to liboctave/cruft/slatec-fn/albeta.f
rename from libcruft/slatec-fn/algams.f
rename to liboctave/cruft/slatec-fn/algams.f
rename from libcruft/slatec-fn/alngam.f
rename to liboctave/cruft/slatec-fn/alngam.f
rename from libcruft/slatec-fn/alnrel.f
rename to liboctave/cruft/slatec-fn/alnrel.f
rename from libcruft/slatec-fn/asinh.f
rename to liboctave/cruft/slatec-fn/asinh.f
rename from libcruft/slatec-fn/atanh.f
rename to liboctave/cruft/slatec-fn/atanh.f
--- a/libcruft/slatec-fn/atanh.f
+++ b/liboctave/cruft/slatec-fn/atanh.f
@@ -57,8 +57,14 @@
       FIRST = .FALSE.
 C
       Y = ABS(X)
-      IF (Y .GE. 1.0) CALL XERMSG ('SLATEC', 'ATANH', 'ABS(X) GE 1', 2,
-     +   2)
+      IF (Y .GE. 1.0) THEN
+         IF (Y .GT. 1.0) THEN 
+            ATANH = (X - X) / (X - X)
+         ELSE
+            ATANH = X / 0.0
+         ENDIF
+         RETURN
+      ENDIF
 C
       IF (1.0-Y .LT. DXREL) CALL XERMSG ('SLATEC', 'ATANH',
      +   'ANSWER LT HALF PRECISION BECAUSE ABS(X) TOO NEAR 1', 1, 1)
rename from libcruft/slatec-fn/betai.f
rename to liboctave/cruft/slatec-fn/betai.f
rename from libcruft/slatec-fn/csevl.f
rename to liboctave/cruft/slatec-fn/csevl.f
rename from libcruft/slatec-fn/d9gmit.f
rename to liboctave/cruft/slatec-fn/d9gmit.f
rename from libcruft/slatec-fn/d9lgic.f
rename to liboctave/cruft/slatec-fn/d9lgic.f
rename from libcruft/slatec-fn/d9lgit.f
rename to liboctave/cruft/slatec-fn/d9lgit.f
rename from libcruft/slatec-fn/d9lgmc.f
rename to liboctave/cruft/slatec-fn/d9lgmc.f
rename from libcruft/slatec-fn/dacosh.f
rename to liboctave/cruft/slatec-fn/dacosh.f
rename from libcruft/slatec-fn/dasinh.f
rename to liboctave/cruft/slatec-fn/dasinh.f
rename from libcruft/slatec-fn/datanh.f
rename to liboctave/cruft/slatec-fn/datanh.f
--- a/libcruft/slatec-fn/datanh.f
+++ b/liboctave/cruft/slatec-fn/datanh.f
@@ -68,8 +68,14 @@
       FIRST = .FALSE.
 C
       Y = ABS(X)
-      IF (Y .GE. 1.D0) CALL XERMSG ('SLATEC', 'DATANH', 'ABS(X) GE 1',
-     +   2, 2)
+      IF (Y .GE. 1.D0) THEN
+         IF (Y .GT. 1.D0) THEN 
+            DATANH = (X - X) / (X - X)
+         ELSE
+            DATANH = X / 0.D0
+         ENDIF
+         RETURN
+      ENDIF
 C
       IF (1.D0-Y .LT. DXREL) CALL XERMSG ('SLATEC', 'DATANH',
      +   'ANSWER LT HALF PRECISION BECAUSE ABS(X) TOO NEAR 1', 1, 1)
rename from libcruft/slatec-fn/dbetai.f
rename to liboctave/cruft/slatec-fn/dbetai.f
rename from libcruft/slatec-fn/dcsevl.f
rename to liboctave/cruft/slatec-fn/dcsevl.f
rename from libcruft/slatec-fn/derf.f
rename to liboctave/cruft/slatec-fn/derf.f
--- a/libcruft/slatec-fn/derf.f
+++ b/liboctave/cruft/slatec-fn/derf.f
@@ -69,7 +69,7 @@
 C
 C ERF(X) = 1.0 - ERFC(X)  FOR  -1.0 .LE. X .LE. 1.0
 C
-      IF (Y.LE.SQEPS) DERF = 2.0D0*X*X/SQRTPI
+      IF (Y.LE.SQEPS) DERF = 2.0D0*X/SQRTPI
       IF (Y.GT.SQEPS) DERF = X*(1.0D0 + DCSEVL (2.D0*X*X-1.D0,
      1  ERFCS, NTERF))
       RETURN
rename from libcruft/slatec-fn/derfc.f
rename to liboctave/cruft/slatec-fn/derfc.in.f
--- a/libcruft/slatec-fn/derfc.f
+++ b/liboctave/cruft/slatec-fn/derfc.in.f
@@ -191,6 +191,11 @@
       ENDIF
       FIRST = .FALSE.
 C
+      IF (ISNAN(X)) THEN
+         DERFC = X
+         RETURN
+      ENDIF
+C
       IF (X.GT.XSML) GO TO 20
 C
 C ERFC(X) = 1.0 - ERF(X)  FOR  X .LT. XSML
@@ -219,8 +224,7 @@
       IF (X.LT.0.D0) DERFC = 2.0D0 - DERFC
       RETURN
 C
- 40   CALL XERMSG ('SLATEC', 'DERFC', 'X SO BIG ERFC UNDERFLOWS', 1, 1)
-      DERFC = 0.D0
+ 40   DERFC = 0.D0
       RETURN
 C
       END
rename from libcruft/slatec-fn/dgami.f
rename to liboctave/cruft/slatec-fn/dgami.f
rename from libcruft/slatec-fn/dgamit.f
rename to liboctave/cruft/slatec-fn/dgamit.f
rename from libcruft/slatec-fn/dgamlm.f
rename to liboctave/cruft/slatec-fn/dgamlm.f
rename from libcruft/slatec-fn/dgamma.f
rename to liboctave/cruft/slatec-fn/dgamma.f
rename from libcruft/slatec-fn/dgamr.f
rename to liboctave/cruft/slatec-fn/dgamr.f
rename from libcruft/slatec-fn/dlbeta.f
rename to liboctave/cruft/slatec-fn/dlbeta.f
rename from libcruft/slatec-fn/dlgams.f
rename to liboctave/cruft/slatec-fn/dlgams.f
rename from libcruft/slatec-fn/dlngam.f
rename to liboctave/cruft/slatec-fn/dlngam.f
rename from libcruft/slatec-fn/dlnrel.f
rename to liboctave/cruft/slatec-fn/dlnrel.f
rename from libcruft/slatec-fn/dpchim.f
rename to liboctave/cruft/slatec-fn/dpchim.f
rename from libcruft/slatec-fn/dpchst.f
rename to liboctave/cruft/slatec-fn/dpchst.f
rename from libcruft/slatec-fn/erf.f
rename to liboctave/cruft/slatec-fn/erf.f
rename from libcruft/slatec-fn/erfc.f
rename to liboctave/cruft/slatec-fn/erfc.in.f
--- a/libcruft/slatec-fn/erfc.f
+++ b/liboctave/cruft/slatec-fn/erfc.in.f
@@ -121,6 +121,11 @@
       ENDIF
       FIRST = .FALSE.
 C
+      IF (ISNAN(X)) THEN
+         ERFC = X
+         RETURN
+      ENDIF
+C
       IF (X.GT.XSML) GO TO 20
 C
 C ERFC(X) = 1.0 - ERF(X) FOR X .LT. XSML
@@ -149,8 +154,7 @@
       IF (X.LT.0.) ERFC = 2.0 - ERFC
       RETURN
 C
- 40   CALL XERMSG ('SLATEC', 'ERFC', 'X SO BIG ERFC UNDERFLOWS', 1, 1)
-      ERFC = 0.
+ 40   ERFC = 0.
       RETURN
 C
       END
rename from libcruft/slatec-fn/gami.f
rename to liboctave/cruft/slatec-fn/gami.f
rename from libcruft/slatec-fn/gamit.f
rename to liboctave/cruft/slatec-fn/gamit.f
rename from libcruft/slatec-fn/gamlim.f
rename to liboctave/cruft/slatec-fn/gamlim.f
rename from libcruft/slatec-fn/gamma.f
rename to liboctave/cruft/slatec-fn/gamma.f
rename from libcruft/slatec-fn/gamr.f
rename to liboctave/cruft/slatec-fn/gamr.f
rename from libcruft/slatec-fn/initds.f
rename to liboctave/cruft/slatec-fn/initds.f
rename from libcruft/slatec-fn/inits.f
rename to liboctave/cruft/slatec-fn/inits.f
rename from libcruft/slatec-fn/module.mk
rename to liboctave/cruft/slatec-fn/module.mk
--- a/libcruft/slatec-fn/module.mk
+++ b/liboctave/cruft/slatec-fn/module.mk
@@ -1,4 +1,7 @@
-EXTRA_DIST += slatec-fn/module.mk
+EXTRA_DIST += \
+  slatec-fn/module.mk \
+  slatec-fn/derfc.in.f \
+  slatec-fn/erfc.in.f
 
 libcruft_la_SOURCES += \
   slatec-fn/albeta.f \
@@ -20,7 +23,6 @@
   slatec-fn/dbetai.f \
   slatec-fn/dcsevl.f \
   slatec-fn/derf.f \
-  slatec-fn/derfc.f \
   slatec-fn/dgami.f \
   slatec-fn/dgamit.f \
   slatec-fn/dgamlm.f \
@@ -33,7 +35,6 @@
   slatec-fn/dpchim.f \
   slatec-fn/dpchst.f \
   slatec-fn/erf.f \
-  slatec-fn/erfc.f \
   slatec-fn/gami.f \
   slatec-fn/gamit.f \
   slatec-fn/gamlim.f \
@@ -65,3 +66,16 @@
   slatec-fn/xsgmainc.f \
   slatec-fn/xgamma.f \
   slatec-fn/xbetai.f
+
+nodist_libcruft_la_SOURCES += \
+  slatec-fn/derfc.f \
+  slatec-fn/erfc.f
+
+slatec-fn/erfc.f: slatec-fn/erfc.in.f Makefile
+	$(SED) -e "${F77_ISNAN_MACRO}" < $< > $@-t
+	mv $@-t $@
+
+slatec-fn/derfc.f: slatec-fn/derfc.in.f Makefile
+	$(SED) -e "${F77_ISNAN_MACRO}" < $< > $@-t
+	mv $@-t $@
+
rename from libcruft/slatec-fn/pchim.f
rename to liboctave/cruft/slatec-fn/pchim.f
rename from libcruft/slatec-fn/pchst.f
rename to liboctave/cruft/slatec-fn/pchst.f
rename from libcruft/slatec-fn/r9gmit.f
rename to liboctave/cruft/slatec-fn/r9gmit.f
rename from libcruft/slatec-fn/r9lgic.f
rename to liboctave/cruft/slatec-fn/r9lgic.f
rename from libcruft/slatec-fn/r9lgit.f
rename to liboctave/cruft/slatec-fn/r9lgit.f
rename from libcruft/slatec-fn/r9lgmc.f
rename to liboctave/cruft/slatec-fn/r9lgmc.f
rename from libcruft/slatec-fn/xacosh.f
rename to liboctave/cruft/slatec-fn/xacosh.f
rename from libcruft/slatec-fn/xasinh.f
rename to liboctave/cruft/slatec-fn/xasinh.f
rename from libcruft/slatec-fn/xatanh.f
rename to liboctave/cruft/slatec-fn/xatanh.f
rename from libcruft/slatec-fn/xbetai.f
rename to liboctave/cruft/slatec-fn/xbetai.f
rename from libcruft/slatec-fn/xdacosh.f
rename to liboctave/cruft/slatec-fn/xdacosh.f
rename from libcruft/slatec-fn/xdasinh.f
rename to liboctave/cruft/slatec-fn/xdasinh.f
rename from libcruft/slatec-fn/xdatanh.f
rename to liboctave/cruft/slatec-fn/xdatanh.f
rename from libcruft/slatec-fn/xdbetai.f
rename to liboctave/cruft/slatec-fn/xdbetai.f
rename from libcruft/slatec-fn/xderf.f
rename to liboctave/cruft/slatec-fn/xderf.f
rename from libcruft/slatec-fn/xderfc.f
rename to liboctave/cruft/slatec-fn/xderfc.f
rename from libcruft/slatec-fn/xdgami.f
rename to liboctave/cruft/slatec-fn/xdgami.f
rename from libcruft/slatec-fn/xdgamit.f
rename to liboctave/cruft/slatec-fn/xdgamit.f
rename from libcruft/slatec-fn/xdgamma.f
rename to liboctave/cruft/slatec-fn/xdgamma.f
rename from libcruft/slatec-fn/xerf.f
rename to liboctave/cruft/slatec-fn/xerf.f
rename from libcruft/slatec-fn/xerfc.f
rename to liboctave/cruft/slatec-fn/xerfc.f
rename from libcruft/slatec-fn/xgamma.f
rename to liboctave/cruft/slatec-fn/xgamma.f
rename from libcruft/slatec-fn/xgmainc.f
rename to liboctave/cruft/slatec-fn/xgmainc.f
rename from libcruft/slatec-fn/xsgmainc.f
rename to liboctave/cruft/slatec-fn/xsgmainc.f
--- a/liboctave/link-deps.mk
+++ b/liboctave/link-deps.mk
@@ -1,6 +1,20 @@
-include ../libcruft/link-deps.mk
+GNULIB_LINK_DEPS = \
+  $(COPYSIGNF_LIBM)\
+  $(COPYSIGN_LIBM)\
+  $(FLOORF_LIBM)\
+  $(FLOOR_LIBM)\
+  $(GETHOSTNAME_LIB)\
+  $(LIBSOCKET)\
+  $(LIB_NANOSLEEP)\
+  $(LIB_SELECT)\
+  $(LTLIBINTL)\
+  $(ROUNDF_LIBM)\
+  $(ROUND_LIBM)\
+  $(TRUNCF_LIBM)\
+  $(TRUNC_LIBM)
 
 LIBOCTAVE_LINK_DEPS = \
+  $(GNULIB_LINK_DEPS) \
   $(SPARSE_XLIBS) \
   $(ARPACK_LIBS) \
   $(QRUPDATE_LIBS) \
@@ -13,6 +27,7 @@
   $(REGEX_LIBS) \
   $(DL_LIBS) \
   $(PTHREAD_LIBS) \
+  $(FLIBS) \
   $(LIBS)
 
 LIBOCTAVE_LINK_OPTS = \
@@ -20,8 +35,3 @@
   $(ARPACK_LDFLAGS) \
   $(QRUPDATE_LDFLAGS) \
   $(FFTW_XLDFLAGS)
-
-if AMCOND_LINK_ALL_DEPS
-  LIBOCTAVE_LINK_DEPS += $(LIBCRUFT_LINK_DEPS)
-  LIBOCTAVE_LINK_OPTS += $(LIBCRUFT_LINK_OPTS)
-endif
rename from liboctave/CmplxAEPBAL.cc
rename to liboctave/numeric/CmplxAEPBAL.cc
rename from liboctave/CmplxAEPBAL.h
rename to liboctave/numeric/CmplxAEPBAL.h
rename from liboctave/CmplxCHOL.cc
rename to liboctave/numeric/CmplxCHOL.cc
rename from liboctave/CmplxCHOL.h
rename to liboctave/numeric/CmplxCHOL.h
rename from liboctave/CmplxGEPBAL.cc
rename to liboctave/numeric/CmplxGEPBAL.cc
--- a/liboctave/CmplxGEPBAL.cc
+++ b/liboctave/numeric/CmplxGEPBAL.cc
@@ -70,7 +70,7 @@
       return -1;
     }
 
-  if (a.dims() != b.dims ())
+  if (a.dims () != b.dims ())
     {
       gripe_nonconformant ("ComplexGEPBALANCE", n, n, b.rows(), b.cols());
       return -1;
rename from liboctave/CmplxGEPBAL.h
rename to liboctave/numeric/CmplxGEPBAL.h
rename from liboctave/CmplxHESS.cc
rename to liboctave/numeric/CmplxHESS.cc
rename from liboctave/CmplxHESS.h
rename to liboctave/numeric/CmplxHESS.h
rename from liboctave/CmplxLU.cc
rename to liboctave/numeric/CmplxLU.cc
--- a/liboctave/CmplxLU.cc
+++ b/liboctave/numeric/CmplxLU.cc
@@ -33,8 +33,8 @@
 
 // Instantiate the base LU class for the types we need.
 
-#include <base-lu.h>
-#include <base-lu.cc>
+#include "base-lu.h"
+#include "base-lu.cc"
 
 template class base_lu <ComplexMatrix>;
 
rename from liboctave/CmplxLU.h
rename to liboctave/numeric/CmplxLU.h
rename from liboctave/CmplxQR.cc
rename to liboctave/numeric/CmplxQR.cc
--- a/liboctave/CmplxQR.cc
+++ b/liboctave/numeric/CmplxQR.cc
@@ -469,7 +469,7 @@
 
   if (u.length () == m && v.length () == n)
     {
-      init(q*r + ComplexMatrix (u) * ComplexMatrix (v).hermitian (), get_type ());
+      init (q*r + ComplexMatrix (u) * ComplexMatrix (v).hermitian (), get_type ());
     }
   else
     (*current_liboctave_error_handler) ("qrupdate: dimensions mismatch");
@@ -485,7 +485,7 @@
 
   if (u.rows () == m && v.rows () == n && u.cols () == v.cols ())
     {
-      init(q*r + u * v.hermitian (), get_type ());
+      init (q*r + u * v.hermitian (), get_type ());
     }
   else
     (*current_liboctave_error_handler) ("qrupdate: dimensions mismatch");
rename from liboctave/CmplxQR.h
rename to liboctave/numeric/CmplxQR.h
rename from liboctave/CmplxQRP.cc
rename to liboctave/numeric/CmplxQRP.cc
rename from liboctave/CmplxQRP.h
rename to liboctave/numeric/CmplxQRP.h
rename from liboctave/CmplxSCHUR.cc
rename to liboctave/numeric/CmplxSCHUR.cc
rename from liboctave/CmplxSCHUR.h
rename to liboctave/numeric/CmplxSCHUR.h
rename from liboctave/CmplxSVD.cc
rename to liboctave/numeric/CmplxSVD.cc
rename from liboctave/CmplxSVD.h
rename to liboctave/numeric/CmplxSVD.h
rename from liboctave/CollocWt.cc
rename to liboctave/numeric/CollocWt.cc
--- a/liboctave/CollocWt.cc
+++ b/liboctave/numeric/CollocWt.cc
@@ -212,7 +212,7 @@
               xn1 = xp1;
             }
 
-          double zc  = 1.0;
+          double zc = 1.0;
           double z = xn / xn1;
 
           if (i != 0)
@@ -230,12 +230,12 @@
           if (++k > 100 || xisnan (z))
             return false;
 
-          if (std::abs (z) <= 100 * DBL_EPSILON)
+          if (std::abs (z) <= 100 * std::numeric_limits<double>::epsilon ())
             done = true;
         }
 
       root[i] = x;
-      x = x + sqrt (DBL_EPSILON);
+      x = x + sqrt (std::numeric_limits<double>::epsilon ());
     }
 
   // Add interpolation points at x = 0 and/or x = 1.
rename from liboctave/CollocWt.h
rename to liboctave/numeric/CollocWt.h
rename from liboctave/DAE.h
rename to liboctave/numeric/DAE.h
rename from liboctave/DAEFunc.h
rename to liboctave/numeric/DAEFunc.h
rename from liboctave/DAERT.h
rename to liboctave/numeric/DAERT.h
rename from liboctave/DAERTFunc.h
rename to liboctave/numeric/DAERTFunc.h
rename from liboctave/DASPK-opts.in
rename to liboctave/numeric/DASPK-opts.in
--- a/liboctave/DASPK-opts.in
+++ b/liboctave/numeric/DASPK-opts.in
@@ -32,13 +32,13 @@
   SET_ARG_TYPE = "const $TYPE&"
   INIT_BODY
     $OPTVAR.resize (dim_vector (1, 1));
-    $OPTVAR(0) = ::sqrt (DBL_EPSILON);
+    $OPTVAR(0) = ::sqrt (std::numeric_limits<double>::epsilon ());
   END_INIT_BODY
   SET_CODE
     void set_$OPT (double val)
       {
         $OPTVAR.resize (dim_vector (1, 1));
-        $OPTVAR(0) = (val > 0.0) ? val : ::sqrt (DBL_EPSILON);
+        $OPTVAR(0) = (val > 0.0) ? val : ::sqrt (std::numeric_limits<double>::epsilon ());
         reset = true;
       }
 
@@ -68,13 +68,13 @@
   SET_ARG_TYPE = "const $TYPE&"
   INIT_BODY
     $OPTVAR.resize (dim_vector (1, 1));
-    $OPTVAR(0) = ::sqrt (DBL_EPSILON);
+    $OPTVAR(0) = ::sqrt (std::numeric_limits<double>::epsilon ());
   END_INIT_BODY
   SET_CODE
     void set_$OPT (double val)
       {
         $OPTVAR.resize (dim_vector (1, 1));
-        $OPTVAR(0) = (val > 0.0) ? val : ::sqrt (DBL_EPSILON);
+        $OPTVAR(0) = (val > 0.0) ? val : ::sqrt (std::numeric_limits<double>::epsilon ());
         reset = true;
       }
 
@@ -172,7 +172,7 @@
     $OPTVAR(1) = 6.0;
     $OPTVAR(2) = 5.0;
     $OPTVAR(3) = 0.0;
-    $OPTVAR(4) = ::pow (DBL_EPSILON, 2.0/3.0);
+    $OPTVAR(4) = ::pow (std::numeric_limits<double>::epsilon (), 2.0/3.0);
     $OPTVAR(5) = 0.01;
   END_INIT_BODY
   SET_EXPR = "val"
rename from liboctave/DASPK.cc
rename to liboctave/numeric/DASPK.cc
--- a/liboctave/DASPK.cc
+++ b/liboctave/numeric/DASPK.cc
@@ -83,8 +83,8 @@
 
   for (octave_idx_type i = 0; i < nn; i++)
     {
-      tmp_deriv.elem (i) = deriv [i];
-      tmp_state.elem (i) = state [i];
+      tmp_deriv.elem (i) = deriv[i];
+      tmp_state.elem (i) = state[i];
     }
 
   tmp_delta = user_fun (tmp_state, tmp_deriv, time, ires);
@@ -96,7 +96,7 @@
       else
         {
           for (octave_idx_type i = 0; i < nn; i++)
-            delta [i] = tmp_delta.elem (i);
+            delta[i] = tmp_delta.elem (i);
         }
     }
 
@@ -137,15 +137,15 @@
 
   for (octave_idx_type i = 0; i < nn; i++)
     {
-      tmp_deriv.elem (i) = deriv [i];
-      tmp_state.elem (i) = state [i];
+      tmp_deriv.elem (i) = deriv[i];
+      tmp_state.elem (i) = state[i];
     }
 
   Matrix tmp_pd = user_jac (tmp_state, tmp_deriv, time, cj);
 
   for (octave_idx_type j = 0; j < nn; j++)
     for (octave_idx_type i = 0; i < nn; i++)
-      pd [nn * j + i] = tmp_pd.elem (i, j);
+      pd[nn * j + i] = tmp_pd.elem (i, j);
 
   END_INTERRUPT_WITH_EXCEPTIONS;
 
rename from liboctave/DASPK.h
rename to liboctave/numeric/DASPK.h
rename from liboctave/DASRT-opts.in
rename to liboctave/numeric/DASRT-opts.in
--- a/liboctave/DASRT-opts.in
+++ b/liboctave/numeric/DASRT-opts.in
@@ -32,13 +32,13 @@
   SET_ARG_TYPE = "const $TYPE&"
   INIT_BODY
     $OPTVAR.resize (dim_vector (1, 1));
-    $OPTVAR(0) = ::sqrt (DBL_EPSILON);
+    $OPTVAR(0) = ::sqrt (std::numeric_limits<double>::epsilon ());
   END_INIT_BODY
   SET_CODE
     void set_$OPT (double val)
       {
         $OPTVAR.resize (dim_vector (1, 1));
-        $OPTVAR(0) = (val > 0.0) ? val : ::sqrt (DBL_EPSILON);
+        $OPTVAR(0) = (val > 0.0) ? val : ::sqrt (std::numeric_limits<double>::epsilon ());
         reset = true;
       }
 
@@ -68,13 +68,13 @@
   SET_ARG_TYPE = "const $TYPE&"
   INIT_BODY
     $OPTVAR.resize (dim_vector (1, 1));
-    $OPTVAR(0) = ::sqrt (DBL_EPSILON);
+    $OPTVAR(0) = ::sqrt (std::numeric_limits<double>::epsilon ());
   END_INIT_BODY
   SET_CODE
     void set_$OPT (double val)
       {
         $OPTVAR.resize (dim_vector (1, 1));
-        $OPTVAR(0) = (val > 0.0) ? val : ::sqrt (DBL_EPSILON);
+        $OPTVAR(0) = (val > 0.0) ? val : ::sqrt (std::numeric_limits<double>::epsilon ());
         reset = true;
       }
 
rename from liboctave/DASRT.cc
rename to liboctave/numeric/DASRT.cc
--- a/liboctave/DASRT.cc
+++ b/liboctave/numeric/DASRT.cc
@@ -113,15 +113,15 @@
 
   for (octave_idx_type i = 0; i < nn; i++)
     {
-      tmp_deriv.elem (i) = deriv [i];
-      tmp_state.elem (i) = state [i];
+      tmp_deriv.elem (i) = deriv[i];
+      tmp_state.elem (i) = state[i];
     }
 
   Matrix tmp_pd = (*user_jsub) (tmp_state, tmp_deriv, time, cj);
 
   for (octave_idx_type j = 0; j < nn; j++)
     for (octave_idx_type i = 0; i < nn; i++)
-      pd [nn * j + i] = tmp_pd.elem (i, j);
+      pd[nn * j + i] = tmp_pd.elem (i, j);
 
   END_INTERRUPT_WITH_EXCEPTIONS;
 
rename from liboctave/DASRT.h
rename to liboctave/numeric/DASRT.h
rename from liboctave/DASSL-opts.in
rename to liboctave/numeric/DASSL-opts.in
--- a/liboctave/DASSL-opts.in
+++ b/liboctave/numeric/DASSL-opts.in
@@ -32,13 +32,13 @@
   SET_ARG_TYPE = "const $TYPE&"
   INIT_BODY
     $OPTVAR.resize (dim_vector (1, 1));
-    $OPTVAR(0) = ::sqrt (DBL_EPSILON);
+    $OPTVAR(0) = ::sqrt (std::numeric_limits<double>::epsilon ());
   END_INIT_BODY
   SET_CODE
     void set_$OPT (double val)
       {
         $OPTVAR.resize (dim_vector (1, 1));
-        $OPTVAR(0) = (val > 0.0) ? val : ::sqrt (DBL_EPSILON);
+        $OPTVAR(0) = (val > 0.0) ? val : ::sqrt (std::numeric_limits<double>::epsilon ());
         reset = true;
       }
 
@@ -68,13 +68,13 @@
   SET_ARG_TYPE = "const $TYPE&"
   INIT_BODY
     $OPTVAR.resize (dim_vector (1, 1));
-    $OPTVAR(0) = ::sqrt (DBL_EPSILON);
+    $OPTVAR(0) = ::sqrt (std::numeric_limits<double>::epsilon ());
   END_INIT_BODY
   SET_CODE
     void set_$OPT (double val)
       {
         $OPTVAR.resize (dim_vector (1, 1));
-        $OPTVAR(0) = (val > 0.0) ? val : ::sqrt (DBL_EPSILON);
+        $OPTVAR(0) = (val > 0.0) ? val : ::sqrt (std::numeric_limits<double>::epsilon ());
         reset = true;
       }
 
rename from liboctave/DASSL.cc
rename to liboctave/numeric/DASSL.cc
--- a/liboctave/DASSL.cc
+++ b/liboctave/numeric/DASSL.cc
@@ -76,8 +76,8 @@
 
   for (octave_idx_type i = 0; i < nn; i++)
     {
-      tmp_deriv.elem (i) = deriv [i];
-      tmp_state.elem (i) = state [i];
+      tmp_deriv.elem (i) = deriv[i];
+      tmp_state.elem (i) = state[i];
     }
 
   tmp_delta = user_fun (tmp_state, tmp_deriv, time, ires);
@@ -89,7 +89,7 @@
       else
         {
           for (octave_idx_type i = 0; i < nn; i++)
-            delta [i] = tmp_delta.elem (i);
+            delta[i] = tmp_delta.elem (i);
         }
     }
 
@@ -111,15 +111,15 @@
 
   for (octave_idx_type i = 0; i < nn; i++)
     {
-      tmp_deriv.elem (i) = deriv [i];
-      tmp_state.elem (i) = state [i];
+      tmp_deriv.elem (i) = deriv[i];
+      tmp_state.elem (i) = state[i];
     }
 
   Matrix tmp_pd = user_jac (tmp_state, tmp_deriv, time, cj);
 
   for (octave_idx_type j = 0; j < nn; j++)
     for (octave_idx_type i = 0; i < nn; i++)
-      pd [nn * j + i] = tmp_pd.elem (i, j);
+      pd[nn * j + i] = tmp_pd.elem (i, j);
 
   END_INTERRUPT_WITH_EXCEPTIONS;
 
rename from liboctave/DASSL.h
rename to liboctave/numeric/DASSL.h
rename from liboctave/DET.h
rename to liboctave/numeric/DET.h
rename from liboctave/EIG.cc
rename to liboctave/numeric/EIG.cc
--- a/liboctave/EIG.cc
+++ b/liboctave/numeric/EIG.cc
@@ -230,8 +230,8 @@
                   return -1;
                 }
 
-              lambda.elem(j) = Complex (wr.elem(j), wi.elem(j));
-              lambda.elem(j+1) = Complex (wr.elem(j+1), wi.elem(j+1));
+              lambda.elem (j) = Complex (wr.elem (j), wi.elem (j));
+              lambda.elem (j+1) = Complex (wr.elem (j+1), wi.elem (j+1));
 
               for (octave_idx_type i = 0; i < nvr; i++)
                 {
@@ -581,10 +581,10 @@
                   return -1;
                 }
 
-              lambda.elem(j) = Complex (ar.elem(j) / beta.elem (j),
-                                        ai.elem(j) / beta.elem (j));
-              lambda.elem(j+1) = Complex (ar.elem(j+1) / beta.elem (j+1),
-                                          ai.elem(j+1) / beta.elem (j+1));
+              lambda.elem (j) = Complex (ar.elem (j) / beta.elem (j),
+                                         ai.elem (j) / beta.elem (j));
+              lambda.elem (j+1) = Complex (ar.elem (j+1) / beta.elem (j+1),
+                                           ai.elem (j+1) / beta.elem (j+1));
 
               for (octave_idx_type i = 0; i < nvr; i++)
                 {
@@ -691,7 +691,7 @@
   octave_idx_type n = a.rows ();
   octave_idx_type nb = b.rows ();
 
-  if (n != a.cols () || nb != b.cols())
+  if (n != a.cols () || nb != b.cols ())
     {
       (*current_liboctave_error_handler) ("EIG requires square matrix");
       return -1;
@@ -780,7 +780,7 @@
       lambda.resize (n);
 
       for (octave_idx_type j = 0; j < n; j++)
-        lambda.elem (j) = alpha.elem (j) / beta.elem(j);
+        lambda.elem (j) = alpha.elem (j) / beta.elem (j);
 
       v = vtmp;
     }
rename from liboctave/EIG.h
rename to liboctave/numeric/EIG.h
rename from liboctave/LSODE-opts.in
rename to liboctave/numeric/LSODE-opts.in
--- a/liboctave/LSODE-opts.in
+++ b/liboctave/numeric/LSODE-opts.in
@@ -31,13 +31,13 @@
   SET_ARG_TYPE = "const $TYPE&"
   INIT_BODY
     $OPTVAR.resize (dim_vector (1, 1));
-    $OPTVAR(0) = ::sqrt (DBL_EPSILON);
+    $OPTVAR(0) = ::sqrt (std::numeric_limits<double>::epsilon ());
   END_INIT_BODY
   SET_CODE
     void set_$OPT (double val)
       {
         $OPTVAR.resize (dim_vector (1, 1));
-        $OPTVAR(0) = (val > 0.0) ? val : ::sqrt (DBL_EPSILON);
+        $OPTVAR(0) = (val > 0.0) ? val : ::sqrt (std::numeric_limits<double>::epsilon ());
         reset = true;
       }
 
@@ -63,8 +63,8 @@
 
   END_DOC_ITEM
   TYPE = "double"
-  INIT_VALUE = "::sqrt (DBL_EPSILON)"
-  SET_EXPR = "(val > 0.0) ? val : ::sqrt (DBL_EPSILON)"
+  INIT_VALUE = "::sqrt (std::numeric_limits<double>::epsilon ())"
+  SET_EXPR = "(val > 0.0) ? val : ::sqrt (std::numeric_limits<double>::epsilon ())"
 END_OPTION
 
 OPTION
rename from liboctave/LSODE.cc
rename to liboctave/numeric/LSODE.cc
--- a/liboctave/LSODE.cc
+++ b/liboctave/numeric/LSODE.cc
@@ -79,7 +79,7 @@
   else
     {
       for (octave_idx_type i = 0; i < neq; i++)
-        deriv [i] = tmp_deriv.elem (i);
+        deriv[i] = tmp_deriv.elem (i);
     }
 
   END_INTERRUPT_WITH_EXCEPTIONS;
@@ -103,7 +103,7 @@
 
   for (octave_idx_type j = 0; j < neq; j++)
     for (octave_idx_type i = 0; i < neq; i++)
-      pd [nrowpd * j + i] = tmp_jac (i, j);
+      pd[nrowpd * j + i] = tmp_jac (i, j);
 
   END_INTERRUPT_WITH_EXCEPTIONS;
 
rename from liboctave/LSODE.h
rename to liboctave/numeric/LSODE.h
rename from liboctave/ODE.h
rename to liboctave/numeric/ODE.h
rename from liboctave/ODEFunc.h
rename to liboctave/numeric/ODEFunc.h
rename from liboctave/ODES.cc
rename to liboctave/numeric/ODES.cc
rename from liboctave/ODES.h
rename to liboctave/numeric/ODES.h
rename from liboctave/ODESFunc.h
rename to liboctave/numeric/ODESFunc.h
rename from liboctave/Quad-opts.in
rename to liboctave/numeric/Quad-opts.in
--- a/liboctave/Quad-opts.in
+++ b/liboctave/numeric/Quad-opts.in
@@ -25,7 +25,7 @@
 
   END_DOC_ITEM
   TYPE = "double"
-  INIT_VALUE = "::sqrt (DBL_EPSILON)"
+  INIT_VALUE = "::sqrt (std::numeric_limits<double>::epsilon ())"
   SET_EXPR = "val"
 END_OPTION
 
@@ -38,7 +38,7 @@
 
   END_DOC_ITEM
   TYPE = "double"
-  INIT_VALUE = "::sqrt (DBL_EPSILON)"
+  INIT_VALUE = "::sqrt (std::numeric_limits<double>::epsilon ())"
   SET_EXPR = "val"
 END_OPTION
 
@@ -50,7 +50,7 @@
 
   END_DOC_ITEM
   TYPE = "float"
-  INIT_VALUE = "::sqrt (FLT_EPSILON)"
+  INIT_VALUE = "::sqrt (std::numeric_limits<float>::epsilon ())"
   SET_EXPR = "val"
 END_OPTION
 
@@ -62,6 +62,6 @@
 @w{@code{max (50*eps, 0.5e-28)}}.
   END_DOC_ITEM
   TYPE = "float"
-  INIT_VALUE = "::sqrt (FLT_EPSILON)"
+  INIT_VALUE = "::sqrt (std::numeric_limits<float>::epsilon ())"
   SET_EXPR = "val"
 END_OPTION
rename from liboctave/Quad.cc
rename to liboctave/numeric/Quad.cc
rename from liboctave/Quad.h
rename to liboctave/numeric/Quad.h
rename from liboctave/SparseCmplxCHOL.cc
rename to liboctave/numeric/SparseCmplxCHOL.cc
--- a/liboctave/SparseCmplxCHOL.cc
+++ b/liboctave/numeric/SparseCmplxCHOL.cc
@@ -51,13 +51,13 @@
 
       if (typ == MatrixType::Upper)
         {
-          rinv = r.inverse(mattype, info, rcond, true, false);
-          retval = rinv.transpose() * rinv;
+          rinv = r.inverse (mattype, info, rcond, true, false);
+          retval = rinv.transpose () * rinv;
         }
       else if (typ == MatrixType::Lower)
         {
-          rinv = r.transpose().inverse(mattype, info, rcond, true, false);
-          retval = rinv.transpose() * rinv;
+          rinv = r.transpose ().inverse (mattype, info, rcond, true, false);
+          retval = rinv.transpose () * rinv;
         }
       else
         (*current_liboctave_error_handler)
rename from liboctave/SparseCmplxCHOL.h
rename to liboctave/numeric/SparseCmplxCHOL.h
--- a/liboctave/SparseCmplxCHOL.h
+++ b/liboctave/numeric/SparseCmplxCHOL.h
@@ -38,14 +38,13 @@
   SparseComplexCHOL (void) :
     sparse_base_chol<SparseComplexMatrix, Complex, SparseMatrix> () { }
 
-  SparseComplexCHOL (const SparseComplexMatrix& a, bool natural = true) :
-    sparse_base_chol<SparseComplexMatrix, Complex, SparseMatrix>
-  (a, natural) { }
+  SparseComplexCHOL (const SparseComplexMatrix& a, bool natural = true,
+                     bool force = false) :
+    sparse_base_chol<SparseComplexMatrix, Complex, SparseMatrix> (a, natural, force) { }
 
   SparseComplexCHOL (const SparseComplexMatrix& a, octave_idx_type& info,
-                     bool natural = true) :
-    sparse_base_chol<SparseComplexMatrix, Complex, SparseMatrix>
-  (a, info, natural) { }
+                     bool natural = true, bool force = false) :
+    sparse_base_chol<SparseComplexMatrix, Complex, SparseMatrix> (a, info, natural, force) { }
 
   SparseComplexCHOL (const SparseComplexCHOL& a) :
     sparse_base_chol<SparseComplexMatrix, Complex, SparseMatrix> (a) { }
@@ -61,7 +60,7 @@
       return *this;
     }
 
-  SparseComplexMatrix chol_matrix (void) const { return R(); }
+  SparseComplexMatrix chol_matrix (void) const { return R (); }
 
   SparseComplexMatrix L (void) const
     { return sparse_base_chol<SparseComplexMatrix, Complex,
rename from liboctave/SparseCmplxLU.cc
rename to liboctave/numeric/SparseCmplxLU.cc
--- a/liboctave/SparseCmplxLU.cc
+++ b/liboctave/numeric/SparseCmplxLU.cc
@@ -57,7 +57,7 @@
   double tmp = octave_sparse_params::get_key ("spumoni");
   if (!xisnan (tmp))
     Control (UMFPACK_PRL) = tmp;
-  if (piv_thres.nelem() == 2)
+  if (piv_thres.nelem () == 2)
     {
       tmp = (piv_thres (0) > 1. ? 1. : piv_thres (0));
       if (!xisnan (tmp))
@@ -223,12 +223,12 @@
 
                   UMFPACK_ZNAME (report_matrix) (nr, n_inner,
                                             Lfact.cidx (), Lfact.ridx (),
-                                            reinterpret_cast<double *> (Lfact.data()),
+                                            reinterpret_cast<double *> (Lfact.data ()),
                                             0, 1, control);
 
                   UMFPACK_ZNAME (report_matrix) (n_inner, nc,
                                             Ufact.cidx (), Ufact.ridx (),
-                                            reinterpret_cast<double *> (Ufact.data()),
+                                            reinterpret_cast<double *> (Ufact.data ()),
                                             0, 1, control);
                   UMFPACK_ZNAME (report_perm) (nr, p, control);
                   UMFPACK_ZNAME (report_perm) (nc, q, control);
@@ -266,7 +266,7 @@
       double tmp = octave_sparse_params::get_key ("spumoni");
       if (!xisnan (tmp))
         Control (UMFPACK_PRL) = tmp;
-      if (piv_thres.nelem() == 2)
+      if (piv_thres.nelem () == 2)
         {
           tmp = (piv_thres (0) > 1. ? 1. : piv_thres (0));
           if (!xisnan (tmp))
@@ -326,7 +326,7 @@
         OCTAVE_LOCAL_BUFFER (octave_idx_type, qinit, nc);
 
         for (octave_idx_type i = 0; i < nc; i++)
-          qinit [i] = static_cast<octave_idx_type> (Qinit (i));
+          qinit[i] = static_cast<octave_idx_type> (Qinit (i));
 
         status = UMFPACK_ZNAME (qsymbolic) (nr, nc, Ap, Ai,
                                        reinterpret_cast<const double *> (Ax),
@@ -452,13 +452,13 @@
                       UMFPACK_ZNAME (report_matrix) (nr, n_inner,
                                                 Lfact.cidx (),
                                                 Lfact.ridx (),
-                                                reinterpret_cast<double *> (Lfact.data()),
+                                                reinterpret_cast<double *> (Lfact.data ()),
                                                 0, 1, control);
 
                       UMFPACK_ZNAME (report_matrix) (n_inner, nc,
                                                 Ufact.cidx (),
                                                 Ufact.ridx (),
-                                                reinterpret_cast<double *> (Ufact.data()),
+                                                reinterpret_cast<double *> (Ufact.data ()),
                                                 0, 1, control);
                       UMFPACK_ZNAME (report_perm) (nr, p, control);
                       UMFPACK_ZNAME (report_perm) (nc, q, control);
rename from liboctave/SparseCmplxLU.h
rename to liboctave/numeric/SparseCmplxLU.h
rename from liboctave/SparseCmplxQR.cc
rename to liboctave/numeric/SparseCmplxQR.cc
--- a/liboctave/SparseCmplxQR.cc
+++ b/liboctave/numeric/SparseCmplxQR.cc
@@ -69,7 +69,7 @@
                                       (a.data ()));
   A.nz = -1;
   BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
   S = CXSPARSE_ZNAME (_sqr) (order, &A, 1);
 #else
   S = CXSPARSE_ZNAME (_sqr) (&A, order - 1, 1);
@@ -130,10 +130,10 @@
 #ifdef HAVE_CXSPARSE
   ColumnVector ret(N->L->m);
   for (octave_idx_type i = 0; i < N->L->m; i++)
-#if defined(CS_VER) && (CS_VER >= 2)
-    ret.xelem(i) = S->pinv[i];
+#if defined (CS_VER) && (CS_VER >= 2)
+    ret.xelem (i) = S->pinv[i];
 #else
-    ret.xelem(i) = S->Pinv[i];
+    ret.xelem (i) = S->Pinv[i];
 #endif
   return ret;
 #else
@@ -147,10 +147,10 @@
 #ifdef HAVE_CXSPARSE
   ColumnVector ret(N->L->m);
   for (octave_idx_type i = 0; i < N->L->m; i++)
-#if defined(CS_VER) && (CS_VER >= 2)
-    ret.xelem(S->pinv[i]) = i;
+#if defined (CS_VER) && (CS_VER >= 2)
+    ret.xelem (S->pinv[i]) = i;
 #else
-    ret.xelem(S->Pinv[i]) = i;
+    ret.xelem (S->Pinv[i]) = i;
 #endif
   return ret;
 #else
@@ -192,14 +192,14 @@
 SparseComplexQR::SparseComplexQR_rep::C (const ComplexMatrix &b) const
 {
 #ifdef HAVE_CXSPARSE
-  octave_idx_type b_nr = b.rows();
-  octave_idx_type b_nc = b.cols();
+  octave_idx_type b_nr = b.rows ();
+  octave_idx_type b_nc = b.cols ();
   octave_idx_type nc = N->L->n;
   octave_idx_type nr = nrows;
   const cs_complex_t *bvec =
-    reinterpret_cast<const cs_complex_t *>(b.fortran_vec());
+    reinterpret_cast<const cs_complex_t *>(b.fortran_vec ());
   ComplexMatrix ret(b_nr, b_nc);
-  Complex *vec = ret.fortran_vec();
+  Complex *vec = ret.fortran_vec ();
   if (nr < 0 || nc < 0 || nr != b_nr)
     (*current_liboctave_error_handler) ("matrix dimension mismatch");
   else if (nr == 0 || nc == 0 || b_nc == 0)
@@ -212,7 +212,7 @@
           octave_quit ();
           volatile octave_idx_type nm = (nr < nc ? nr : nc);
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
           CXSPARSE_ZNAME (_ipvec)
             (S->pinv, bvec + idx, reinterpret_cast<cs_complex_t *>(buf), b_nr);
 #else
@@ -245,7 +245,7 @@
   octave_idx_type nc = N->L->n;
   octave_idx_type nr = nrows;
   ComplexMatrix ret(nr, nr);
-  Complex *vec = ret.fortran_vec();
+  Complex *vec = ret.fortran_vec ();
   if (nr < 0 || nc < 0)
     (*current_liboctave_error_handler) ("matrix dimension mismatch");
   else if (nr == 0 || nc == 0)
@@ -262,7 +262,7 @@
           bvec[j] = OCTAVE_C99_ONE;
           volatile octave_idx_type nm = (nr < nc ? nr : nc);
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
           CXSPARSE_ZNAME (_ipvec)
             (S->pinv, bvec, reinterpret_cast<cs_complex_t *>(buf), nr);
 #else
@@ -290,14 +290,14 @@
 }
 
 ComplexMatrix
-qrsolve(const SparseComplexMatrix&a, const Matrix &b, octave_idx_type &info)
+qrsolve (const SparseComplexMatrix&a, const Matrix &b, octave_idx_type &info)
 {
   info = -1;
 #ifdef HAVE_CXSPARSE
-  octave_idx_type nr = a.rows();
-  octave_idx_type nc = a.cols();
-  octave_idx_type b_nc = b.cols();
-  octave_idx_type b_nr = b.rows();
+  octave_idx_type nr = a.rows ();
+  octave_idx_type nc = a.cols ();
+  octave_idx_type b_nc = b.cols ();
+  octave_idx_type b_nr = b.rows ();
   ComplexMatrix x;
 
   if (nr < 0 || nc < 0 || nr != b_nr)
@@ -309,41 +309,41 @@
     {
       SparseComplexQR q (a, 2);
       if (! q.ok ())
-        return ComplexMatrix();
-      x.resize(nc, b_nc);
+        return ComplexMatrix ();
+      x.resize (nc, b_nc);
       cs_complex_t *vec = reinterpret_cast<cs_complex_t *>
-        (x.fortran_vec());
-      OCTAVE_C99_COMPLEX (buf, q.S()->m2);
+        (x.fortran_vec ());
+      OCTAVE_C99_COMPLEX (buf, q.S ()->m2);
       OCTAVE_LOCAL_BUFFER (Complex, Xx, b_nr);
       for (volatile octave_idx_type i = 0, idx = 0; i < b_nc; i++, idx+=nc)
         {
           octave_quit ();
           for (octave_idx_type j = 0; j < b_nr; j++)
-            Xx[j] = b.xelem(j,i);
-          for (octave_idx_type j = nr; j < q.S()->m2; j++)
+            Xx[j] = b.xelem (j,i);
+          for (octave_idx_type j = nr; j < q.S ()->m2; j++)
             buf[j] = OCTAVE_C99_ZERO;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
           CXSPARSE_ZNAME (_ipvec)
-            (q.S()->pinv, reinterpret_cast<cs_complex_t *>(Xx), buf, nr);
+            (q.S ()->pinv, reinterpret_cast<cs_complex_t *>(Xx), buf, nr);
 #else
           CXSPARSE_ZNAME (_ipvec)
-            (nr, q.S()->Pinv, reinterpret_cast<cs_complex_t *>(Xx), buf);
+            (nr, q.S ()->Pinv, reinterpret_cast<cs_complex_t *>(Xx), buf);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = 0; j < nc; j++)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_ZNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_ZNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-          CXSPARSE_ZNAME (_usolve) (q.N()->U, buf);
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_ZNAME (_ipvec) (q.S()->q, buf, vec + idx, nc);
+          CXSPARSE_ZNAME (_usolve) (q.N ()->U, buf);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_ZNAME (_ipvec) (q.S ()->q, buf, vec + idx, nc);
 #else
-          CXSPARSE_ZNAME (_ipvec) (nc, q.S()->Q, buf, vec + idx);
+          CXSPARSE_ZNAME (_ipvec) (nc, q.S ()->Q, buf, vec + idx);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
         }
@@ -351,60 +351,60 @@
     }
   else
     {
-      SparseComplexMatrix at = a.hermitian();
+      SparseComplexMatrix at = a.hermitian ();
       SparseComplexQR q (at, 2);
       if (! q.ok ())
-        return ComplexMatrix();
-      x.resize(nc, b_nc);
+        return ComplexMatrix ();
+      x.resize (nc, b_nc);
       cs_complex_t *vec = reinterpret_cast<cs_complex_t *>
-        (x.fortran_vec());
-      volatile octave_idx_type nbuf = (nc > q.S()->m2 ? nc : q.S()->m2);
+        (x.fortran_vec ());
+      volatile octave_idx_type nbuf = (nc > q.S ()->m2 ? nc : q.S ()->m2);
       OCTAVE_C99_COMPLEX (buf, nbuf);
       OCTAVE_LOCAL_BUFFER (Complex, Xx, b_nr);
-#if defined(CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
+#if defined (CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
       OCTAVE_LOCAL_BUFFER (double, B, nr);
       for (octave_idx_type i = 0; i < nr; i++)
-        B[i] = q.N()->B [i];
+        B[i] = q.N ()->B[i];
 #else
       OCTAVE_LOCAL_BUFFER (Complex, B, nr);
       for (octave_idx_type i = 0; i < nr; i++)
-        B[i] = conj (reinterpret_cast<Complex *>(q.N()->B) [i]);
+        B[i] = conj (reinterpret_cast<Complex *>(q.N ()->B)[i]);
 #endif
       for (volatile octave_idx_type i = 0, idx = 0; i < b_nc; i++, idx+=nc)
         {
           octave_quit ();
           for (octave_idx_type j = 0; j < b_nr; j++)
-            Xx[j] = b.xelem(j,i);
+            Xx[j] = b.xelem (j,i);
           for (octave_idx_type j = nr; j < nbuf; j++)
             buf[j] = OCTAVE_C99_ZERO;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
           CXSPARSE_ZNAME (_pvec)
-            (q.S()->q, reinterpret_cast<cs_complex_t *>(Xx), buf, nr);
+            (q.S ()->q, reinterpret_cast<cs_complex_t *>(Xx), buf, nr);
 #else
           CXSPARSE_ZNAME (_pvec)
-            (nr, q.S()->Q, reinterpret_cast<cs_complex_t *>(Xx), buf);
+            (nr, q.S ()->Q, reinterpret_cast<cs_complex_t *>(Xx), buf);
 #endif
-          CXSPARSE_ZNAME (_utsolve) (q.N()->U, buf);
+          CXSPARSE_ZNAME (_utsolve) (q.N ()->U, buf);
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = nr-1; j >= 0; j--)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
 
-#if defined(CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
-              CXSPARSE_ZNAME (_happly) (q.N()->L, j, B[j], buf);
+#if defined (CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
+              CXSPARSE_ZNAME (_happly) (q.N ()->L, j, B[j], buf);
 #else
               CXSPARSE_ZNAME (_happly)
-                (q.N()->L, j, reinterpret_cast<cs_complex_t *>(B)[j], buf);
+                (q.N ()->L, j, reinterpret_cast<cs_complex_t *>(B)[j], buf);
 #endif
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_ZNAME (_pvec) (q.S()->pinv, buf, vec + idx, nc);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_ZNAME (_pvec) (q.S ()->pinv, buf, vec + idx, nc);
 #else
-          CXSPARSE_ZNAME (_pvec) (nc, q.S()->Pinv, buf, vec + idx);
+          CXSPARSE_ZNAME (_pvec) (nc, q.S ()->Pinv, buf, vec + idx);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
         }
@@ -418,14 +418,14 @@
 }
 
 SparseComplexMatrix
-qrsolve(const SparseComplexMatrix&a, const SparseMatrix &b, octave_idx_type &info)
+qrsolve (const SparseComplexMatrix&a, const SparseMatrix &b, octave_idx_type &info)
 {
   info = -1;
 #ifdef HAVE_CXSPARSE
-  octave_idx_type nr = a.rows();
-  octave_idx_type nc = a.cols();
-  octave_idx_type b_nc = b.cols();
-  octave_idx_type b_nr = b.rows();
+  octave_idx_type nr = a.rows ();
+  octave_idx_type nc = a.cols ();
+  octave_idx_type b_nc = b.cols ();
+  octave_idx_type b_nr = b.rows ();
   SparseComplexMatrix x;
   volatile octave_idx_type ii, x_nz;
 
@@ -438,44 +438,44 @@
     {
       SparseComplexQR q (a, 2);
       if (! q.ok ())
-        return SparseComplexMatrix();
-      x = SparseComplexMatrix (nc, b_nc, b.nnz());
-      x.xcidx(0) = 0;
-      x_nz = b.nnz();
+        return SparseComplexMatrix ();
+      x = SparseComplexMatrix (nc, b_nc, b.nnz ());
+      x.xcidx (0) = 0;
+      x_nz = b.nnz ();
       ii = 0;
       OCTAVE_LOCAL_BUFFER (Complex, Xx, (b_nr > nc ? b_nr : nc));
-      OCTAVE_C99_COMPLEX (buf, q.S()->m2);
+      OCTAVE_C99_COMPLEX (buf, q.S ()->m2);
       for (volatile octave_idx_type i = 0, idx = 0; i < b_nc; i++, idx+=nc)
         {
           octave_quit ();
           for (octave_idx_type j = 0; j < b_nr; j++)
-            Xx[j] = b.xelem(j,i);
-          for (octave_idx_type j = nr; j < q.S()->m2; j++)
+            Xx[j] = b.xelem (j,i);
+          for (octave_idx_type j = nr; j < q.S ()->m2; j++)
             buf[j] = OCTAVE_C99_ZERO;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
           CXSPARSE_ZNAME (_ipvec)
-            (q.S()->pinv, reinterpret_cast<cs_complex_t *>(Xx), buf, nr);
+            (q.S ()->pinv, reinterpret_cast<cs_complex_t *>(Xx), buf, nr);
 #else
           CXSPARSE_ZNAME (_ipvec)
-            (nr, q.S()->Pinv, reinterpret_cast<cs_complex_t *>(Xx), buf);
+            (nr, q.S ()->Pinv, reinterpret_cast<cs_complex_t *>(Xx), buf);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = 0; j < nc; j++)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_ZNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_ZNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-          CXSPARSE_ZNAME (_usolve) (q.N()->U, buf);
-#if defined(CS_VER) && (CS_VER >= 2)
+          CXSPARSE_ZNAME (_usolve) (q.N ()->U, buf);
+#if defined (CS_VER) && (CS_VER >= 2)
           CXSPARSE_ZNAME (_ipvec)
-            (q.S()->q, buf, reinterpret_cast<cs_complex_t *>(Xx), nc);
+            (q.S ()->q, buf, reinterpret_cast<cs_complex_t *>(Xx), nc);
 #else
           CXSPARSE_ZNAME (_ipvec)
-            (nc, q.S()->Q, buf, reinterpret_cast<cs_complex_t *>(Xx));
+            (nc, q.S ()->Q, buf, reinterpret_cast<cs_complex_t *>(Xx));
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
 
@@ -492,73 +492,73 @@
                       x.change_capacity (sz);
                       x_nz = sz;
                     }
-                  x.xdata(ii) = tmp;
-                  x.xridx(ii++) = j;
+                  x.xdata (ii) = tmp;
+                  x.xridx (ii++) = j;
                 }
             }
-          x.xcidx(i+1) = ii;
+          x.xcidx (i+1) = ii;
         }
       info = 0;
     }
   else
     {
-      SparseComplexMatrix at = a.hermitian();
+      SparseComplexMatrix at = a.hermitian ();
       SparseComplexQR q (at, 2);
       if (! q.ok ())
-        return SparseComplexMatrix();
-      x = SparseComplexMatrix (nc, b_nc, b.nnz());
-      x.xcidx(0) = 0;
-      x_nz = b.nnz();
+        return SparseComplexMatrix ();
+      x = SparseComplexMatrix (nc, b_nc, b.nnz ());
+      x.xcidx (0) = 0;
+      x_nz = b.nnz ();
       ii = 0;
-      volatile octave_idx_type nbuf = (nc > q.S()->m2 ? nc : q.S()->m2);
+      volatile octave_idx_type nbuf = (nc > q.S ()->m2 ? nc : q.S ()->m2);
       OCTAVE_LOCAL_BUFFER (Complex, Xx, (b_nr > nc ? b_nr : nc));
       OCTAVE_C99_COMPLEX (buf, nbuf);
 
-#if defined(CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
+#if defined (CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
       OCTAVE_LOCAL_BUFFER (double, B, nr);
       for (octave_idx_type i = 0; i < nr; i++)
-        B[i] = q.N()->B [i];
+        B[i] = q.N ()->B[i];
 #else
       OCTAVE_LOCAL_BUFFER (Complex, B, nr);
       for (octave_idx_type i = 0; i < nr; i++)
-        B[i] = conj (reinterpret_cast<Complex *>(q.N()->B) [i]);
+        B[i] = conj (reinterpret_cast<Complex *>(q.N ()->B)[i]);
 #endif
       for (volatile octave_idx_type i = 0, idx = 0; i < b_nc; i++, idx+=nc)
         {
           octave_quit ();
           for (octave_idx_type j = 0; j < b_nr; j++)
-            Xx[j] = b.xelem(j,i);
+            Xx[j] = b.xelem (j,i);
           for (octave_idx_type j = nr; j < nbuf; j++)
             buf[j] = OCTAVE_C99_ZERO;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
           CXSPARSE_ZNAME (_pvec)
-            (q.S()->q, reinterpret_cast<cs_complex_t *>(Xx), buf, nr);
+            (q.S ()->q, reinterpret_cast<cs_complex_t *>(Xx), buf, nr);
 #else
           CXSPARSE_ZNAME (_pvec)
-            (nr, q.S()->Q, reinterpret_cast<cs_complex_t *>(Xx), buf);
+            (nr, q.S ()->Q, reinterpret_cast<cs_complex_t *>(Xx), buf);
 #endif
-          CXSPARSE_ZNAME (_utsolve) (q.N()->U, buf);
+          CXSPARSE_ZNAME (_utsolve) (q.N ()->U, buf);
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = nr-1; j >= 0; j--)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
-              CXSPARSE_ZNAME (_happly) (q.N()->L, j, B[j], buf);
+#if defined (CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
+              CXSPARSE_ZNAME (_happly) (q.N ()->L, j, B[j], buf);
 #else
               CXSPARSE_ZNAME (_happly)
-                (q.N()->L, j, reinterpret_cast<cs_complex_t *>(B)[j], buf);
+                (q.N ()->L, j, reinterpret_cast<cs_complex_t *>(B)[j], buf);
 #endif
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
           CXSPARSE_ZNAME (_pvec)
-            (q.S()->pinv, buf, reinterpret_cast<cs_complex_t *>(Xx), nc);
+            (q.S ()->pinv, buf, reinterpret_cast<cs_complex_t *>(Xx), nc);
 #else
           CXSPARSE_ZNAME (_pvec)
-            (nc, q.S()->Pinv, buf, reinterpret_cast<cs_complex_t *>(Xx));
+            (nc, q.S ()->Pinv, buf, reinterpret_cast<cs_complex_t *>(Xx));
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
 
@@ -575,11 +575,11 @@
                       x.change_capacity (sz);
                       x_nz = sz;
                     }
-                  x.xdata(ii) = tmp;
-                  x.xridx(ii++) = j;
+                  x.xdata (ii) = tmp;
+                  x.xridx (ii++) = j;
                 }
             }
-          x.xcidx(i+1) = ii;
+          x.xcidx (i+1) = ii;
         }
       info = 0;
     }
@@ -592,16 +592,16 @@
 }
 
 ComplexMatrix
-qrsolve(const SparseComplexMatrix&a, const ComplexMatrix &b, octave_idx_type &info)
+qrsolve (const SparseComplexMatrix&a, const ComplexMatrix &b, octave_idx_type &info)
 {
   info = -1;
 #ifdef HAVE_CXSPARSE
-  octave_idx_type nr = a.rows();
-  octave_idx_type nc = a.cols();
-  octave_idx_type b_nc = b.cols();
-  octave_idx_type b_nr = b.rows();
+  octave_idx_type nr = a.rows ();
+  octave_idx_type nc = a.cols ();
+  octave_idx_type b_nc = b.cols ();
+  octave_idx_type b_nr = b.rows ();
   const cs_complex_t *bvec =
-    reinterpret_cast<const cs_complex_t *>(b.fortran_vec());
+    reinterpret_cast<const cs_complex_t *>(b.fortran_vec ());
   ComplexMatrix x;
 
   if (nr < 0 || nc < 0 || nr != b_nr)
@@ -613,37 +613,37 @@
     {
       SparseComplexQR q (a, 2);
       if (! q.ok ())
-        return ComplexMatrix();
-      x.resize(nc, b_nc);
+        return ComplexMatrix ();
+      x.resize (nc, b_nc);
       cs_complex_t *vec = reinterpret_cast<cs_complex_t *>
-        (x.fortran_vec());
-      OCTAVE_C99_COMPLEX (buf, q.S()->m2);
+        (x.fortran_vec ());
+      OCTAVE_C99_COMPLEX (buf, q.S ()->m2);
       for (volatile octave_idx_type i = 0, idx = 0, bidx = 0; i < b_nc;
            i++, idx+=nc, bidx+=b_nr)
         {
           octave_quit ();
-          for (octave_idx_type j = nr; j < q.S()->m2; j++)
+          for (octave_idx_type j = nr; j < q.S ()->m2; j++)
             buf[j] = OCTAVE_C99_ZERO;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_ZNAME (_ipvec) (q.S()->pinv, bvec + bidx, buf, nr);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_ZNAME (_ipvec) (q.S ()->pinv, bvec + bidx, buf, nr);
 #else
-          CXSPARSE_ZNAME (_ipvec) (nr, q.S()->Pinv, bvec + bidx, buf);
+          CXSPARSE_ZNAME (_ipvec) (nr, q.S ()->Pinv, bvec + bidx, buf);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = 0; j < nc; j++)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_ZNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_ZNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-          CXSPARSE_ZNAME (_usolve) (q.N()->U, buf);
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_ZNAME (_ipvec) (q.S()->q, buf, vec + idx, nc);
+          CXSPARSE_ZNAME (_usolve) (q.N ()->U, buf);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_ZNAME (_ipvec) (q.S ()->q, buf, vec + idx, nc);
 #else
-          CXSPARSE_ZNAME (_ipvec) (nc, q.S()->Q, buf, vec + idx);
+          CXSPARSE_ZNAME (_ipvec) (nc, q.S ()->Q, buf, vec + idx);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
         }
@@ -651,23 +651,23 @@
     }
   else
     {
-      SparseComplexMatrix at = a.hermitian();
+      SparseComplexMatrix at = a.hermitian ();
       SparseComplexQR q (at, 2);
       if (! q.ok ())
-        return ComplexMatrix();
-      x.resize(nc, b_nc);
+        return ComplexMatrix ();
+      x.resize (nc, b_nc);
       cs_complex_t *vec = reinterpret_cast<cs_complex_t *>
-        (x.fortran_vec());
-      volatile octave_idx_type nbuf = (nc > q.S()->m2 ? nc : q.S()->m2);
+        (x.fortran_vec ());
+      volatile octave_idx_type nbuf = (nc > q.S ()->m2 ? nc : q.S ()->m2);
       OCTAVE_C99_COMPLEX (buf, nbuf);
-#if defined(CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
+#if defined (CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
       OCTAVE_LOCAL_BUFFER (double, B, nr);
       for (octave_idx_type i = 0; i < nr; i++)
-        B[i] = q.N()->B [i];
+        B[i] = q.N ()->B[i];
 #else
       OCTAVE_LOCAL_BUFFER (Complex, B, nr);
       for (octave_idx_type i = 0; i < nr; i++)
-        B[i] = conj (reinterpret_cast<Complex *>(q.N()->B) [i]);
+        B[i] = conj (reinterpret_cast<Complex *>(q.N ()->B)[i]);
 #endif
       for (volatile octave_idx_type i = 0, idx = 0, bidx = 0; i < b_nc;
            i++, idx+=nc, bidx+=b_nr)
@@ -676,30 +676,30 @@
           for (octave_idx_type j = nr; j < nbuf; j++)
             buf[j] = OCTAVE_C99_ZERO;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_ZNAME (_pvec) (q.S()->q, bvec + bidx, buf, nr);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_ZNAME (_pvec) (q.S ()->q, bvec + bidx, buf, nr);
 #else
-          CXSPARSE_ZNAME (_pvec) (nr, q.S()->Q, bvec + bidx, buf);
+          CXSPARSE_ZNAME (_pvec) (nr, q.S ()->Q, bvec + bidx, buf);
 #endif
-          CXSPARSE_ZNAME (_utsolve) (q.N()->U, buf);
+          CXSPARSE_ZNAME (_utsolve) (q.N ()->U, buf);
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = nr-1; j >= 0; j--)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
-              CXSPARSE_ZNAME (_happly) (q.N()->L, j, B[j], buf);
+#if defined (CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
+              CXSPARSE_ZNAME (_happly) (q.N ()->L, j, B[j], buf);
 #else
               CXSPARSE_ZNAME (_happly)
-                (q.N()->L, j, reinterpret_cast<cs_complex_t *>(B)[j], buf);
+                (q.N ()->L, j, reinterpret_cast<cs_complex_t *>(B)[j], buf);
 #endif
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_ZNAME (_pvec) (q.S()->pinv, buf, vec + idx, nc);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_ZNAME (_pvec) (q.S ()->pinv, buf, vec + idx, nc);
 #else
-          CXSPARSE_ZNAME (_pvec) (nc, q.S()->Pinv, buf, vec + idx);
+          CXSPARSE_ZNAME (_pvec) (nc, q.S ()->Pinv, buf, vec + idx);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
         }
@@ -713,14 +713,14 @@
 }
 
 SparseComplexMatrix
-qrsolve(const SparseComplexMatrix&a, const SparseComplexMatrix &b, octave_idx_type &info)
+qrsolve (const SparseComplexMatrix&a, const SparseComplexMatrix &b, octave_idx_type &info)
 {
   info = -1;
 #ifdef HAVE_CXSPARSE
-  octave_idx_type nr = a.rows();
-  octave_idx_type nc = a.cols();
-  octave_idx_type b_nc = b.cols();
-  octave_idx_type b_nr = b.rows();
+  octave_idx_type nr = a.rows ();
+  octave_idx_type nc = a.cols ();
+  octave_idx_type b_nc = b.cols ();
+  octave_idx_type b_nr = b.rows ();
   SparseComplexMatrix x;
   volatile octave_idx_type ii, x_nz;
 
@@ -733,44 +733,44 @@
     {
       SparseComplexQR q (a, 2);
       if (! q.ok ())
-        return SparseComplexMatrix();
-      x = SparseComplexMatrix (nc, b_nc, b.nnz());
-      x.xcidx(0) = 0;
-      x_nz = b.nnz();
+        return SparseComplexMatrix ();
+      x = SparseComplexMatrix (nc, b_nc, b.nnz ());
+      x.xcidx (0) = 0;
+      x_nz = b.nnz ();
       ii = 0;
       OCTAVE_LOCAL_BUFFER (Complex, Xx, (b_nr > nc ? b_nr : nc));
-      OCTAVE_C99_COMPLEX (buf, q.S()->m2);
+      OCTAVE_C99_COMPLEX (buf, q.S ()->m2);
       for (volatile octave_idx_type i = 0, idx = 0; i < b_nc; i++, idx+=nc)
         {
           octave_quit ();
           for (octave_idx_type j = 0; j < b_nr; j++)
-            Xx[j] = b.xelem(j,i);
-          for (octave_idx_type j = nr; j < q.S()->m2; j++)
+            Xx[j] = b.xelem (j,i);
+          for (octave_idx_type j = nr; j < q.S ()->m2; j++)
             buf[j] = OCTAVE_C99_ZERO;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
           CXSPARSE_ZNAME (_ipvec)
-            (q.S()->pinv, reinterpret_cast<cs_complex_t *>(Xx), buf, nr);
+            (q.S ()->pinv, reinterpret_cast<cs_complex_t *>(Xx), buf, nr);
 #else
           CXSPARSE_ZNAME (_ipvec)
-            (nr, q.S()->Pinv, reinterpret_cast<cs_complex_t *>(Xx), buf);
+            (nr, q.S ()->Pinv, reinterpret_cast<cs_complex_t *>(Xx), buf);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = 0; j < nc; j++)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_ZNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_ZNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-          CXSPARSE_ZNAME (_usolve) (q.N()->U, buf);
-#if defined(CS_VER) && (CS_VER >= 2)
+          CXSPARSE_ZNAME (_usolve) (q.N ()->U, buf);
+#if defined (CS_VER) && (CS_VER >= 2)
           CXSPARSE_ZNAME (_ipvec)
-            (q.S()->q, buf, reinterpret_cast<cs_complex_t *>(Xx), nc);
+            (q.S ()->q, buf, reinterpret_cast<cs_complex_t *>(Xx), nc);
 #else
           CXSPARSE_ZNAME (_ipvec)
-            (nc, q.S()->Q, buf, reinterpret_cast<cs_complex_t *>(Xx));
+            (nc, q.S ()->Q, buf, reinterpret_cast<cs_complex_t *>(Xx));
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
 
@@ -787,72 +787,72 @@
                       x.change_capacity (sz);
                       x_nz = sz;
                     }
-                  x.xdata(ii) = tmp;
-                  x.xridx(ii++) = j;
+                  x.xdata (ii) = tmp;
+                  x.xridx (ii++) = j;
                 }
             }
-          x.xcidx(i+1) = ii;
+          x.xcidx (i+1) = ii;
         }
       info = 0;
     }
   else
     {
-      SparseComplexMatrix at = a.hermitian();
+      SparseComplexMatrix at = a.hermitian ();
       SparseComplexQR q (at, 2);
       if (! q.ok ())
-        return SparseComplexMatrix();
-      x = SparseComplexMatrix (nc, b_nc, b.nnz());
-      x.xcidx(0) = 0;
-      x_nz = b.nnz();
+        return SparseComplexMatrix ();
+      x = SparseComplexMatrix (nc, b_nc, b.nnz ());
+      x.xcidx (0) = 0;
+      x_nz = b.nnz ();
       ii = 0;
-      volatile octave_idx_type nbuf = (nc > q.S()->m2 ? nc : q.S()->m2);
+      volatile octave_idx_type nbuf = (nc > q.S ()->m2 ? nc : q.S ()->m2);
       OCTAVE_LOCAL_BUFFER (Complex, Xx, (b_nr > nc ? b_nr : nc));
       OCTAVE_C99_COMPLEX (buf, nbuf);
-#if defined(CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
+#if defined (CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
       OCTAVE_LOCAL_BUFFER (double, B, nr);
       for (octave_idx_type i = 0; i < nr; i++)
-        B[i] = q.N()->B [i];
+        B[i] = q.N ()->B[i];
 #else
       OCTAVE_LOCAL_BUFFER (Complex, B, nr);
       for (octave_idx_type i = 0; i < nr; i++)
-        B[i] = conj (reinterpret_cast<Complex *>(q.N()->B) [i]);
+        B[i] = conj (reinterpret_cast<Complex *>(q.N ()->B)[i]);
 #endif
       for (volatile octave_idx_type i = 0, idx = 0; i < b_nc; i++, idx+=nc)
         {
           octave_quit ();
           for (octave_idx_type j = 0; j < b_nr; j++)
-            Xx[j] = b.xelem(j,i);
+            Xx[j] = b.xelem (j,i);
           for (octave_idx_type j = nr; j < nbuf; j++)
             buf[j] = OCTAVE_C99_ZERO;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
           CXSPARSE_ZNAME (_pvec)
-            (q.S()->q, reinterpret_cast<cs_complex_t *>(Xx), buf, nr);
+            (q.S ()->q, reinterpret_cast<cs_complex_t *>(Xx), buf, nr);
 #else
           CXSPARSE_ZNAME (_pvec)
-            (nr, q.S()->Q, reinterpret_cast<cs_complex_t *>(Xx), buf);
+            (nr, q.S ()->Q, reinterpret_cast<cs_complex_t *>(Xx), buf);
 #endif
-          CXSPARSE_ZNAME (_utsolve) (q.N()->U, buf);
+          CXSPARSE_ZNAME (_utsolve) (q.N ()->U, buf);
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = nr-1; j >= 0; j--)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
-              CXSPARSE_ZNAME (_happly) (q.N()->L, j, B[j], buf);
+#if defined (CS_VER) && (((CS_VER == 2) && (CS_SUBVER >= 2)) || (CS_VER > 2))
+              CXSPARSE_ZNAME (_happly) (q.N ()->L, j, B[j], buf);
 #else
               CXSPARSE_ZNAME (_happly)
-                (q.N()->L, j, reinterpret_cast<cs_complex_t *>(B)[j], buf);
+                (q.N ()->L, j, reinterpret_cast<cs_complex_t *>(B)[j], buf);
 #endif
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
           CXSPARSE_ZNAME (_pvec)
-            (q.S()->pinv, buf, reinterpret_cast<cs_complex_t *>(Xx), nc);
+            (q.S ()->pinv, buf, reinterpret_cast<cs_complex_t *>(Xx), nc);
 #else
           CXSPARSE_ZNAME (_pvec)
-            (nc, q.S()->Pinv, buf, reinterpret_cast<cs_complex_t *>(Xx));
+            (nc, q.S ()->Pinv, buf, reinterpret_cast<cs_complex_t *>(Xx));
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
 
@@ -869,11 +869,11 @@
                       x.change_capacity (sz);
                       x_nz = sz;
                     }
-                  x.xdata(ii) = tmp;
-                  x.xridx(ii++) = j;
+                  x.xdata (ii) = tmp;
+                  x.xridx (ii++) = j;
                 }
             }
-          x.xcidx(i+1) = ii;
+          x.xcidx (i+1) = ii;
         }
       info = 0;
     }
rename from liboctave/SparseCmplxQR.h
rename to liboctave/numeric/SparseCmplxQR.h
--- a/liboctave/SparseCmplxQR.h
+++ b/liboctave/numeric/SparseCmplxQR.h
@@ -31,7 +31,7 @@
 #include "CSparse.h"
 #include "oct-sparse.h"
 
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
 #define CXSPARSE_ZNAME(name) cs_cl ## name
 #else
 #define CXSPARSE_ZNAME(name) cs_ci ## name
@@ -87,7 +87,7 @@
 
 public:
   SparseComplexQR (void) :
-    rep (new SparseComplexQR_rep (SparseComplexMatrix(), 0)) { }
+    rep (new SparseComplexQR_rep (SparseComplexMatrix (), 0)) { }
 
   SparseComplexQR (const SparseComplexMatrix& a, int order = 0) :
     rep (new SparseComplexQR_rep (a, order)) { }
@@ -113,20 +113,20 @@
       return *this;
     }
 
-  bool ok (void) const { return rep->ok(); }
+  bool ok (void) const { return rep->ok (); }
 
-  SparseComplexMatrix V (void) const { return rep->V(); }
+  SparseComplexMatrix V (void) const { return rep->V (); }
 
-  ColumnVector Pinv (void) const { return rep->P(); }
+  ColumnVector Pinv (void) const { return rep->P (); }
 
-  ColumnVector P (void) const { return rep->P(); }
+  ColumnVector P (void) const { return rep->P (); }
 
   SparseComplexMatrix R (const bool econ = false) const
     { return rep->R(econ); }
 
   ComplexMatrix C (const ComplexMatrix &b) const { return rep->C(b); }
 
-  ComplexMatrix Q (void) const { return rep->Q(); }
+  ComplexMatrix Q (void) const { return rep->Q (); }
 
   friend ComplexMatrix qrsolve (const SparseComplexMatrix &a, const Matrix &b,
                                 octave_idx_type &info);
rename from liboctave/SparseQR.cc
rename to liboctave/numeric/SparseQR.cc
--- a/liboctave/SparseQR.cc
+++ b/liboctave/numeric/SparseQR.cc
@@ -48,7 +48,7 @@
   A.x = const_cast<double *>(a.data ());
   A.nz = -1;
   BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
   S = CXSPARSE_DNAME (_sqr) (order, &A, 1);
 #else
   S = CXSPARSE_DNAME (_sqr) (&A, order - 1, 1);
@@ -110,10 +110,10 @@
 #ifdef HAVE_CXSPARSE
   ColumnVector ret(N->L->m);
   for (octave_idx_type i = 0; i < N->L->m; i++)
-#if defined(CS_VER) && (CS_VER >= 2)
-    ret.xelem(i) = S->pinv[i];
+#if defined (CS_VER) && (CS_VER >= 2)
+    ret.xelem (i) = S->pinv[i];
 #else
-    ret.xelem(i) = S->Pinv[i];
+    ret.xelem (i) = S->Pinv[i];
 #endif
   return ret;
 #else
@@ -127,10 +127,10 @@
 #ifdef HAVE_CXSPARSE
   ColumnVector ret(N->L->m);
   for (octave_idx_type i = 0; i < N->L->m; i++)
-#if defined(CS_VER) && (CS_VER >= 2)
-    ret.xelem(S->pinv[i]) = i;
+#if defined (CS_VER) && (CS_VER >= 2)
+    ret.xelem (S->pinv[i]) = i;
 #else
-    ret.xelem(S->Pinv[i]) = i;
+    ret.xelem (S->Pinv[i]) = i;
 #endif
   return ret;
 #else
@@ -174,13 +174,13 @@
 SparseQR::SparseQR_rep::C (const Matrix &b) const
 {
 #ifdef HAVE_CXSPARSE
-  octave_idx_type b_nr = b.rows();
-  octave_idx_type b_nc = b.cols();
+  octave_idx_type b_nr = b.rows ();
+  octave_idx_type b_nc = b.cols ();
   octave_idx_type nc = N->L->n;
   octave_idx_type nr = nrows;
-  const double *bvec = b.fortran_vec();
+  const double *bvec = b.fortran_vec ();
   Matrix ret (b_nr, b_nc);
-  double *vec = ret.fortran_vec();
+  double *vec = ret.fortran_vec ();
   if (nr < 0 || nc < 0 || nr != b_nr)
     (*current_liboctave_error_handler) ("matrix dimension mismatch");
   else if (nr == 0 || nc == 0 || b_nc == 0)
@@ -195,7 +195,7 @@
             buf[i] = 0.;
           volatile octave_idx_type nm = (nr < nc ? nr : nc);
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
           CXSPARSE_DNAME (_ipvec) (S->pinv, bvec + idx, buf, b_nr);
 #else
           CXSPARSE_DNAME (_ipvec) (b_nr, S->Pinv, bvec + idx, buf);
@@ -226,7 +226,7 @@
   octave_idx_type nc = N->L->n;
   octave_idx_type nr = nrows;
   Matrix ret (nr, nr);
-  double *vec = ret.fortran_vec();
+  double *vec = ret.fortran_vec ();
   if (nr < 0 || nc < 0)
     (*current_liboctave_error_handler) ("matrix dimension mismatch");
   else if (nr == 0 || nc == 0)
@@ -245,7 +245,7 @@
             buf[i] = 0.;
           volatile octave_idx_type nm = (nr < nc ? nr : nc);
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
           CXSPARSE_DNAME (_ipvec) (S->pinv, bvec, buf, nr);
 #else
           CXSPARSE_DNAME (_ipvec) (nr, S->Pinv, bvec, buf);
@@ -271,15 +271,15 @@
 }
 
 Matrix
-qrsolve(const SparseMatrix&a, const Matrix &b, octave_idx_type& info)
+qrsolve (const SparseMatrix&a, const Matrix &b, octave_idx_type& info)
 {
   info = -1;
 #ifdef HAVE_CXSPARSE
-  octave_idx_type nr = a.rows();
-  octave_idx_type nc = a.cols();
-  octave_idx_type b_nc = b.cols();
-  octave_idx_type b_nr = b.rows();
-  const double *bvec = b.fortran_vec();
+  octave_idx_type nr = a.rows ();
+  octave_idx_type nc = a.cols ();
+  octave_idx_type b_nc = b.cols ();
+  octave_idx_type b_nr = b.rows ();
+  const double *bvec = b.fortran_vec ();
   Matrix x;
 
   if (nr < 0 || nc < 0 || nr != b_nr)
@@ -291,36 +291,36 @@
     {
       SparseQR q (a, 3);
       if (! q.ok ())
-        return Matrix();
-      x.resize(nc, b_nc);
-      double *vec = x.fortran_vec();
-      OCTAVE_LOCAL_BUFFER (double, buf, q.S()->m2);
+        return Matrix ();
+      x.resize (nc, b_nc);
+      double *vec = x.fortran_vec ();
+      OCTAVE_LOCAL_BUFFER (double, buf, q.S ()->m2);
       for (volatile octave_idx_type i = 0, idx = 0, bidx = 0; i < b_nc;
            i++, idx+=nc, bidx+=b_nr)
         {
           octave_quit ();
-          for (octave_idx_type j = nr; j < q.S()->m2; j++)
+          for (octave_idx_type j = nr; j < q.S ()->m2; j++)
             buf[j] = 0.;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_ipvec) (q.S()->pinv, bvec + bidx, buf, nr);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_ipvec) (q.S ()->pinv, bvec + bidx, buf, nr);
 #else
-          CXSPARSE_DNAME (_ipvec) (nr, q.S()->Pinv, bvec + bidx, buf);
+          CXSPARSE_DNAME (_ipvec) (nr, q.S ()->Pinv, bvec + bidx, buf);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = 0; j < nc; j++)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_DNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_DNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-          CXSPARSE_DNAME (_usolve) (q.N()->U, buf);
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_ipvec) (q.S()->q, buf, vec + idx, nc);
+          CXSPARSE_DNAME (_usolve) (q.N ()->U, buf);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_ipvec) (q.S ()->q, buf, vec + idx, nc);
 #else
-          CXSPARSE_DNAME (_ipvec) (nc, q.S()->Q, buf, vec + idx);
+          CXSPARSE_DNAME (_ipvec) (nc, q.S ()->Q, buf, vec + idx);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
         }
@@ -328,13 +328,13 @@
     }
   else
     {
-      SparseMatrix at = a.hermitian();
+      SparseMatrix at = a.hermitian ();
       SparseQR q (at, 3);
       if (! q.ok ())
-        return Matrix();
-      x.resize(nc, b_nc);
-      double *vec = x.fortran_vec();
-      volatile octave_idx_type nbuf = (nc > q.S()->m2 ? nc : q.S()->m2);
+        return Matrix ();
+      x.resize (nc, b_nc);
+      double *vec = x.fortran_vec ();
+      volatile octave_idx_type nbuf = (nc > q.S ()->m2 ? nc : q.S ()->m2);
       OCTAVE_LOCAL_BUFFER (double, buf, nbuf);
       for (volatile octave_idx_type i = 0, idx = 0, bidx = 0; i < b_nc;
            i++, idx+=nc, bidx+=b_nr)
@@ -343,25 +343,25 @@
           for (octave_idx_type j = nr; j < nbuf; j++)
             buf[j] = 0.;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_pvec) (q.S()->q, bvec + bidx, buf, nr);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_pvec) (q.S ()->q, bvec + bidx, buf, nr);
 #else
-          CXSPARSE_DNAME (_pvec) (nr, q.S()->Q, bvec + bidx, buf);
+          CXSPARSE_DNAME (_pvec) (nr, q.S ()->Q, bvec + bidx, buf);
 #endif
-          CXSPARSE_DNAME (_utsolve) (q.N()->U, buf);
+          CXSPARSE_DNAME (_utsolve) (q.N ()->U, buf);
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = nr-1; j >= 0; j--)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_DNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_DNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_pvec) (q.S()->pinv, buf, vec + idx, nc);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_pvec) (q.S ()->pinv, buf, vec + idx, nc);
 #else
-          CXSPARSE_DNAME (_pvec) (nc, q.S()->Pinv, buf, vec + idx);
+          CXSPARSE_DNAME (_pvec) (nc, q.S ()->Pinv, buf, vec + idx);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
         }
@@ -375,14 +375,14 @@
 }
 
 SparseMatrix
-qrsolve(const SparseMatrix&a, const SparseMatrix &b, octave_idx_type &info)
+qrsolve (const SparseMatrix&a, const SparseMatrix &b, octave_idx_type &info)
 {
   info = -1;
 #ifdef HAVE_CXSPARSE
-  octave_idx_type nr = a.rows();
-  octave_idx_type nc = a.cols();
-  octave_idx_type b_nr = b.rows();
-  octave_idx_type b_nc = b.cols();
+  octave_idx_type nr = a.rows ();
+  octave_idx_type nc = a.cols ();
+  octave_idx_type b_nr = b.rows ();
+  octave_idx_type b_nc = b.cols ();
   SparseMatrix x;
   volatile octave_idx_type ii, x_nz;
 
@@ -395,40 +395,40 @@
     {
       SparseQR q (a, 3);
       if (! q.ok ())
-        return SparseMatrix();
-      x = SparseMatrix (nc, b_nc, b.nnz());
-      x.xcidx(0) = 0;
-      x_nz = b.nnz();
+        return SparseMatrix ();
+      x = SparseMatrix (nc, b_nc, b.nnz ());
+      x.xcidx (0) = 0;
+      x_nz = b.nnz ();
       ii = 0;
       OCTAVE_LOCAL_BUFFER (double, Xx, (b_nr > nc ? b_nr : nc));
-      OCTAVE_LOCAL_BUFFER (double, buf, q.S()->m2);
+      OCTAVE_LOCAL_BUFFER (double, buf, q.S ()->m2);
       for (volatile octave_idx_type i = 0, idx = 0; i < b_nc; i++, idx+=nc)
         {
           octave_quit ();
           for (octave_idx_type j = 0; j < b_nr; j++)
-            Xx[j] = b.xelem(j,i);
-          for (octave_idx_type j = nr; j < q.S()->m2; j++)
+            Xx[j] = b.xelem (j,i);
+          for (octave_idx_type j = nr; j < q.S ()->m2; j++)
             buf[j] = 0.;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_ipvec) (q.S()->pinv, Xx, buf, nr);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_ipvec) (q.S ()->pinv, Xx, buf, nr);
 #else
-          CXSPARSE_DNAME (_ipvec) (nr, q.S()->Pinv, Xx, buf);
+          CXSPARSE_DNAME (_ipvec) (nr, q.S ()->Pinv, Xx, buf);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = 0; j < nc; j++)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_DNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_DNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-          CXSPARSE_DNAME (_usolve) (q.N()->U, buf);
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_ipvec) (q.S()->q, buf, Xx, nc);
+          CXSPARSE_DNAME (_usolve) (q.N ()->U, buf);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_ipvec) (q.S ()->q, buf, Xx, nc);
 #else
-          CXSPARSE_DNAME (_ipvec) (nc, q.S()->Q, buf, Xx);
+          CXSPARSE_DNAME (_ipvec) (nc, q.S ()->Q, buf, Xx);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
 
@@ -445,54 +445,54 @@
                       x.change_capacity (sz);
                       x_nz = sz;
                     }
-                  x.xdata(ii) = tmp;
-                  x.xridx(ii++) = j;
+                  x.xdata (ii) = tmp;
+                  x.xridx (ii++) = j;
                 }
             }
-          x.xcidx(i+1) = ii;
+          x.xcidx (i+1) = ii;
         }
       info = 0;
     }
   else
     {
-      SparseMatrix at = a.hermitian();
+      SparseMatrix at = a.hermitian ();
       SparseQR q (at, 3);
       if (! q.ok ())
-        return SparseMatrix();
-      x = SparseMatrix (nc, b_nc, b.nnz());
-      x.xcidx(0) = 0;
-      x_nz = b.nnz();
+        return SparseMatrix ();
+      x = SparseMatrix (nc, b_nc, b.nnz ());
+      x.xcidx (0) = 0;
+      x_nz = b.nnz ();
       ii = 0;
-      volatile octave_idx_type nbuf = (nc > q.S()->m2 ? nc : q.S()->m2);
+      volatile octave_idx_type nbuf = (nc > q.S ()->m2 ? nc : q.S ()->m2);
       OCTAVE_LOCAL_BUFFER (double, Xx, (b_nr > nc ? b_nr : nc));
       OCTAVE_LOCAL_BUFFER (double, buf, nbuf);
       for (volatile octave_idx_type i = 0, idx = 0; i < b_nc; i++, idx+=nc)
         {
           octave_quit ();
           for (octave_idx_type j = 0; j < b_nr; j++)
-            Xx[j] = b.xelem(j,i);
+            Xx[j] = b.xelem (j,i);
           for (octave_idx_type j = nr; j < nbuf; j++)
             buf[j] = 0.;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_pvec) (q.S()->q, Xx, buf, nr);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_pvec) (q.S ()->q, Xx, buf, nr);
 #else
-          CXSPARSE_DNAME (_pvec) (nr, q.S()->Q, Xx, buf);
+          CXSPARSE_DNAME (_pvec) (nr, q.S ()->Q, Xx, buf);
 #endif
-          CXSPARSE_DNAME (_utsolve) (q.N()->U, buf);
+          CXSPARSE_DNAME (_utsolve) (q.N ()->U, buf);
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = nr-1; j >= 0; j--)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_DNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_DNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_pvec) (q.S()->pinv, buf, Xx, nc);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_pvec) (q.S ()->pinv, buf, Xx, nc);
 #else
-          CXSPARSE_DNAME (_pvec) (nc, q.S()->Pinv, buf, Xx);
+          CXSPARSE_DNAME (_pvec) (nc, q.S ()->Pinv, buf, Xx);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
 
@@ -509,11 +509,11 @@
                       x.change_capacity (sz);
                       x_nz = sz;
                     }
-                  x.xdata(ii) = tmp;
-                  x.xridx(ii++) = j;
+                  x.xdata (ii) = tmp;
+                  x.xridx (ii++) = j;
                 }
             }
-          x.xcidx(i+1) = ii;
+          x.xcidx (i+1) = ii;
         }
       info = 0;
     }
@@ -526,14 +526,14 @@
 }
 
 ComplexMatrix
-qrsolve(const SparseMatrix&a, const ComplexMatrix &b, octave_idx_type &info)
+qrsolve (const SparseMatrix&a, const ComplexMatrix &b, octave_idx_type &info)
 {
   info = -1;
 #ifdef HAVE_CXSPARSE
-  octave_idx_type nr = a.rows();
-  octave_idx_type nc = a.cols();
-  octave_idx_type b_nc = b.cols();
-  octave_idx_type b_nr = b.rows();
+  octave_idx_type nr = a.rows ();
+  octave_idx_type nc = a.cols ();
+  octave_idx_type b_nc = b.cols ();
+  octave_idx_type b_nr = b.rows ();
   ComplexMatrix x;
 
   if (nr < 0 || nc < 0 || nr != b_nr)
@@ -545,12 +545,12 @@
     {
       SparseQR q (a, 3);
       if (! q.ok ())
-        return ComplexMatrix();
-      x.resize(nc, b_nc);
-      Complex *vec = x.fortran_vec();
+        return ComplexMatrix ();
+      x.resize (nc, b_nc);
+      Complex *vec = x.fortran_vec ();
       OCTAVE_LOCAL_BUFFER (double, Xx, (b_nr > nc ? b_nr : nc));
       OCTAVE_LOCAL_BUFFER (double, Xz, (b_nr > nc ? b_nr : nc));
-      OCTAVE_LOCAL_BUFFER (double, buf, q.S()->m2);
+      OCTAVE_LOCAL_BUFFER (double, buf, q.S ()->m2);
       for (volatile octave_idx_type i = 0, idx = 0; i < b_nc; i++, idx+=nc)
         {
           octave_quit ();
@@ -560,50 +560,50 @@
               Xx[j] = std::real (c);
               Xz[j] = std::imag (c);
             }
-          for (octave_idx_type j = nr; j < q.S()->m2; j++)
+          for (octave_idx_type j = nr; j < q.S ()->m2; j++)
             buf[j] = 0.;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_ipvec) (q.S()->pinv, Xx, buf, nr);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_ipvec) (q.S ()->pinv, Xx, buf, nr);
 #else
-          CXSPARSE_DNAME (_ipvec) (nr, q.S()->Pinv, Xx, buf);
+          CXSPARSE_DNAME (_ipvec) (nr, q.S ()->Pinv, Xx, buf);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = 0; j < nc; j++)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_DNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_DNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-          CXSPARSE_DNAME (_usolve) (q.N()->U, buf);
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_ipvec) (q.S()->q, buf, Xx, nc);
+          CXSPARSE_DNAME (_usolve) (q.N ()->U, buf);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_ipvec) (q.S ()->q, buf, Xx, nc);
 #else
-          CXSPARSE_DNAME (_ipvec) (nc, q.S()->Q, buf, Xx);
+          CXSPARSE_DNAME (_ipvec) (nc, q.S ()->Q, buf, Xx);
 #endif
-          for (octave_idx_type j = nr; j < q.S()->m2; j++)
+          for (octave_idx_type j = nr; j < q.S ()->m2; j++)
             buf[j] = 0.;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_ipvec) (q.S()->pinv, Xz, buf, nr);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_ipvec) (q.S ()->pinv, Xz, buf, nr);
 #else
-          CXSPARSE_DNAME (_ipvec) (nr, q.S()->Pinv, Xz, buf);
+          CXSPARSE_DNAME (_ipvec) (nr, q.S ()->Pinv, Xz, buf);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = 0; j < nc; j++)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_DNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_DNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-          CXSPARSE_DNAME (_usolve) (q.N()->U, buf);
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_ipvec) (q.S()->q, buf, Xz, nc);
+          CXSPARSE_DNAME (_usolve) (q.N ()->U, buf);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_ipvec) (q.S ()->q, buf, Xz, nc);
 #else
-          CXSPARSE_DNAME (_ipvec) (nc, q.S()->Q, buf, Xz);
+          CXSPARSE_DNAME (_ipvec) (nc, q.S ()->Q, buf, Xz);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (octave_idx_type j = 0; j < nc; j++)
@@ -613,13 +613,13 @@
     }
   else
     {
-      SparseMatrix at = a.hermitian();
+      SparseMatrix at = a.hermitian ();
       SparseQR q (at, 3);
       if (! q.ok ())
-        return ComplexMatrix();
-      x.resize(nc, b_nc);
-      Complex *vec = x.fortran_vec();
-      volatile octave_idx_type nbuf = (nc > q.S()->m2 ? nc : q.S()->m2);
+        return ComplexMatrix ();
+      x.resize (nc, b_nc);
+      Complex *vec = x.fortran_vec ();
+      volatile octave_idx_type nbuf = (nc > q.S ()->m2 ? nc : q.S ()->m2);
       OCTAVE_LOCAL_BUFFER (double, Xx, (b_nr > nc ? b_nr : nc));
       OCTAVE_LOCAL_BUFFER (double, Xz, (b_nr > nc ? b_nr : nc));
       OCTAVE_LOCAL_BUFFER (double, buf, nbuf);
@@ -635,49 +635,49 @@
           for (octave_idx_type j = nr; j < nbuf; j++)
             buf[j] = 0.;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_pvec) (q.S()->q, Xx, buf, nr);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_pvec) (q.S ()->q, Xx, buf, nr);
 #else
-          CXSPARSE_DNAME (_pvec) (nr, q.S()->Q, Xx, buf);
+          CXSPARSE_DNAME (_pvec) (nr, q.S ()->Q, Xx, buf);
 #endif
-          CXSPARSE_DNAME (_utsolve) (q.N()->U, buf);
+          CXSPARSE_DNAME (_utsolve) (q.N ()->U, buf);
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = nr-1; j >= 0; j--)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_DNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_DNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_pvec) (q.S()->pinv, buf, Xx, nc);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_pvec) (q.S ()->pinv, buf, Xx, nc);
 #else
-          CXSPARSE_DNAME (_pvec) (nc, q.S()->Pinv, buf, Xx);
+          CXSPARSE_DNAME (_pvec) (nc, q.S ()->Pinv, buf, Xx);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (octave_idx_type j = nr; j < nbuf; j++)
             buf[j] = 0.;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_pvec) (q.S()->q, Xz, buf, nr);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_pvec) (q.S ()->q, Xz, buf, nr);
 #else
-          CXSPARSE_DNAME (_pvec) (nr, q.S()->Q, Xz, buf);
+          CXSPARSE_DNAME (_pvec) (nr, q.S ()->Q, Xz, buf);
 #endif
-          CXSPARSE_DNAME (_utsolve) (q.N()->U, buf);
+          CXSPARSE_DNAME (_utsolve) (q.N ()->U, buf);
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = nr-1; j >= 0; j--)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_DNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_DNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_pvec) (q.S()->pinv, buf, Xz, nc);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_pvec) (q.S ()->pinv, buf, Xz, nc);
 #else
-          CXSPARSE_DNAME (_pvec) (nc, q.S()->Pinv, buf, Xz);
+          CXSPARSE_DNAME (_pvec) (nc, q.S ()->Pinv, buf, Xz);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (octave_idx_type j = 0; j < nc; j++)
@@ -693,14 +693,14 @@
 }
 
 SparseComplexMatrix
-qrsolve(const SparseMatrix&a, const SparseComplexMatrix &b, octave_idx_type &info)
+qrsolve (const SparseMatrix&a, const SparseComplexMatrix &b, octave_idx_type &info)
 {
   info = -1;
 #ifdef HAVE_CXSPARSE
-  octave_idx_type nr = a.rows();
-  octave_idx_type nc = a.cols();
-  octave_idx_type b_nr = b.rows();
-  octave_idx_type b_nc = b.cols();
+  octave_idx_type nr = a.rows ();
+  octave_idx_type nc = a.cols ();
+  octave_idx_type b_nr = b.rows ();
+  octave_idx_type b_nc = b.cols ();
   SparseComplexMatrix x;
   volatile octave_idx_type ii, x_nz;
 
@@ -713,14 +713,14 @@
     {
       SparseQR q (a, 3);
       if (! q.ok ())
-        return SparseComplexMatrix();
-      x = SparseComplexMatrix (nc, b_nc, b.nnz());
-      x.xcidx(0) = 0;
-      x_nz = b.nnz();
+        return SparseComplexMatrix ();
+      x = SparseComplexMatrix (nc, b_nc, b.nnz ());
+      x.xcidx (0) = 0;
+      x_nz = b.nnz ();
       ii = 0;
       OCTAVE_LOCAL_BUFFER (double, Xx, (b_nr > nc ? b_nr : nc));
       OCTAVE_LOCAL_BUFFER (double, Xz, (b_nr > nc ? b_nr : nc));
-      OCTAVE_LOCAL_BUFFER (double, buf, q.S()->m2);
+      OCTAVE_LOCAL_BUFFER (double, buf, q.S ()->m2);
       for (volatile octave_idx_type i = 0, idx = 0; i < b_nc; i++, idx+=nc)
         {
           octave_quit ();
@@ -730,52 +730,52 @@
               Xx[j] = std::real (c);
               Xz[j] = std::imag (c);
             }
-          for (octave_idx_type j = nr; j < q.S()->m2; j++)
+          for (octave_idx_type j = nr; j < q.S ()->m2; j++)
             buf[j] = 0.;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_ipvec) (q.S()->pinv, Xx, buf, nr);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_ipvec) (q.S ()->pinv, Xx, buf, nr);
 #else
-          CXSPARSE_DNAME (_ipvec) (nr, q.S()->Pinv, Xx, buf);
+          CXSPARSE_DNAME (_ipvec) (nr, q.S ()->Pinv, Xx, buf);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = 0; j < nc; j++)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_DNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_DNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-          CXSPARSE_DNAME (_usolve) (q.N()->U, buf);
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_ipvec) (q.S()->q, buf, Xx, nc);
+          CXSPARSE_DNAME (_usolve) (q.N ()->U, buf);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_ipvec) (q.S ()->q, buf, Xx, nc);
 #else
-          CXSPARSE_DNAME (_ipvec) (nc, q.S()->Q, buf, Xx);
+          CXSPARSE_DNAME (_ipvec) (nc, q.S ()->Q, buf, Xx);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-          for (octave_idx_type j = nr; j < q.S()->m2; j++)
+          for (octave_idx_type j = nr; j < q.S ()->m2; j++)
             buf[j] = 0.;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_ipvec) (q.S()->pinv, Xz, buf, nr);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_ipvec) (q.S ()->pinv, Xz, buf, nr);
 #else
-          CXSPARSE_DNAME (_ipvec) (nr, q.S()->Pinv, Xz, buf);
+          CXSPARSE_DNAME (_ipvec) (nr, q.S ()->Pinv, Xz, buf);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = 0; j < nc; j++)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_DNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_DNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-          CXSPARSE_DNAME (_usolve) (q.N()->U, buf);
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_ipvec) (q.S()->q, buf, Xz, nc);
+          CXSPARSE_DNAME (_usolve) (q.N ()->U, buf);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_ipvec) (q.S ()->q, buf, Xz, nc);
 #else
-          CXSPARSE_DNAME (_ipvec) (nc, q.S()->Q, buf, Xz);
+          CXSPARSE_DNAME (_ipvec) (nc, q.S ()->Q, buf, Xz);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
 
@@ -792,25 +792,25 @@
                       x.change_capacity (sz);
                       x_nz = sz;
                     }
-                  x.xdata(ii) = tmp;
-                  x.xridx(ii++) = j;
+                  x.xdata (ii) = tmp;
+                  x.xridx (ii++) = j;
                 }
             }
-          x.xcidx(i+1) = ii;
+          x.xcidx (i+1) = ii;
         }
       info = 0;
     }
   else
     {
-      SparseMatrix at = a.hermitian();
+      SparseMatrix at = a.hermitian ();
       SparseQR q (at, 3);
       if (! q.ok ())
-        return SparseComplexMatrix();
-      x = SparseComplexMatrix (nc, b_nc, b.nnz());
-      x.xcidx(0) = 0;
-      x_nz = b.nnz();
+        return SparseComplexMatrix ();
+      x = SparseComplexMatrix (nc, b_nc, b.nnz ());
+      x.xcidx (0) = 0;
+      x_nz = b.nnz ();
       ii = 0;
-      volatile octave_idx_type nbuf = (nc > q.S()->m2 ? nc : q.S()->m2);
+      volatile octave_idx_type nbuf = (nc > q.S ()->m2 ? nc : q.S ()->m2);
       OCTAVE_LOCAL_BUFFER (double, Xx, (b_nr > nc ? b_nr : nc));
       OCTAVE_LOCAL_BUFFER (double, Xz, (b_nr > nc ? b_nr : nc));
       OCTAVE_LOCAL_BUFFER (double, buf, nbuf);
@@ -826,49 +826,49 @@
           for (octave_idx_type j = nr; j < nbuf; j++)
             buf[j] = 0.;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_pvec) (q.S()->q, Xx, buf, nr);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_pvec) (q.S ()->q, Xx, buf, nr);
 #else
-          CXSPARSE_DNAME (_pvec) (nr, q.S()->Q, Xx, buf);
+          CXSPARSE_DNAME (_pvec) (nr, q.S ()->Q, Xx, buf);
 #endif
-          CXSPARSE_DNAME (_utsolve) (q.N()->U, buf);
+          CXSPARSE_DNAME (_utsolve) (q.N ()->U, buf);
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = nr-1; j >= 0; j--)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_DNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_DNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_pvec) (q.S()->pinv, buf, Xx, nc);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_pvec) (q.S ()->pinv, buf, Xx, nc);
 #else
-          CXSPARSE_DNAME (_pvec) (nc, q.S()->Pinv, buf, Xx);
+          CXSPARSE_DNAME (_pvec) (nc, q.S ()->Pinv, buf, Xx);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (octave_idx_type j = nr; j < nbuf; j++)
             buf[j] = 0.;
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_pvec) (q.S()->q, Xz, buf, nr);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_pvec) (q.S ()->q, Xz, buf, nr);
 #else
-          CXSPARSE_DNAME (_pvec) (nr, q.S()->Q, Xz, buf);
+          CXSPARSE_DNAME (_pvec) (nr, q.S ()->Q, Xz, buf);
 #endif
-          CXSPARSE_DNAME (_utsolve) (q.N()->U, buf);
+          CXSPARSE_DNAME (_utsolve) (q.N ()->U, buf);
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
           for (volatile octave_idx_type j = nr-1; j >= 0; j--)
             {
               octave_quit ();
               BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-              CXSPARSE_DNAME (_happly) (q.N()->L, j, q.N()->B[j], buf);
+              CXSPARSE_DNAME (_happly) (q.N ()->L, j, q.N ()->B[j], buf);
               END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
             }
           BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
-#if defined(CS_VER) && (CS_VER >= 2)
-          CXSPARSE_DNAME (_pvec) (q.S()->pinv, buf, Xz, nc);
+#if defined (CS_VER) && (CS_VER >= 2)
+          CXSPARSE_DNAME (_pvec) (q.S ()->pinv, buf, Xz, nc);
 #else
-          CXSPARSE_DNAME (_pvec) (nc, q.S()->Pinv, buf, Xz);
+          CXSPARSE_DNAME (_pvec) (nc, q.S ()->Pinv, buf, Xz);
 #endif
           END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
 
@@ -885,11 +885,11 @@
                       x.change_capacity (sz);
                       x_nz = sz;
                     }
-                  x.xdata(ii) = tmp;
-                  x.xridx(ii++) = j;
+                  x.xdata (ii) = tmp;
+                  x.xridx (ii++) = j;
                 }
             }
-          x.xcidx(i+1) = ii;
+          x.xcidx (i+1) = ii;
         }
       info = 0;
     }
@@ -902,15 +902,15 @@
 }
 
 Matrix
-qrsolve(const SparseMatrix &a, const MArray<double> &b,
-        octave_idx_type &info)
+qrsolve (const SparseMatrix &a, const MArray<double> &b,
+         octave_idx_type &info)
 {
   return qrsolve (a, Matrix (b), info);
 }
 
 ComplexMatrix
-qrsolve(const SparseMatrix &a, const MArray<Complex> &b,
-        octave_idx_type &info)
+qrsolve (const SparseMatrix &a, const MArray<Complex> &b,
+         octave_idx_type &info)
 {
   return qrsolve (a, ComplexMatrix (b), info);
 }
rename from liboctave/SparseQR.h
rename to liboctave/numeric/SparseQR.h
--- a/liboctave/SparseQR.h
+++ b/liboctave/numeric/SparseQR.h
@@ -31,7 +31,7 @@
 #include "CSparse.h"
 #include "oct-sparse.h"
 
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
 #define CXSPARSE_DNAME(name) cs_dl ## name
 #else
 #define CXSPARSE_DNAME(name) cs_di ## name
@@ -89,7 +89,7 @@
 
 public:
 
-  SparseQR (void) : rep (new SparseQR_rep (SparseMatrix(), 0)) { }
+  SparseQR (void) : rep (new SparseQR_rep (SparseMatrix (), 0)) { }
 
   SparseQR (const SparseMatrix& a, int order = 0) :
     rep (new SparseQR_rep (a, order)) { }
@@ -115,19 +115,19 @@
       return *this;
     }
 
-  bool ok (void) const { return rep->ok(); }
+  bool ok (void) const { return rep->ok (); }
 
-  SparseMatrix V (void) const { return rep->V(); }
+  SparseMatrix V (void) const { return rep->V (); }
 
-  ColumnVector Pinv (void) const { return rep->P(); }
+  ColumnVector Pinv (void) const { return rep->P (); }
 
-  ColumnVector P (void) const { return rep->P(); }
+  ColumnVector P (void) const { return rep->P (); }
 
   SparseMatrix R (const bool econ = false) const { return rep->R(econ); }
 
   Matrix C (const Matrix &b) const { return rep->C(b); }
 
-  Matrix Q (void) const { return rep->Q(); }
+  Matrix Q (void) const { return rep->Q (); }
 
   friend Matrix qrsolve (const SparseMatrix &a, const Matrix &b,
                          octave_idx_type &info);
rename from liboctave/SparsedbleCHOL.cc
rename to liboctave/numeric/SparsedbleCHOL.cc
--- a/liboctave/SparsedbleCHOL.cc
+++ b/liboctave/numeric/SparsedbleCHOL.cc
@@ -51,13 +51,13 @@
 
       if (typ == MatrixType::Upper)
         {
-          rinv = r.inverse(mattype, info, rcond, true, false);
-          retval = rinv.transpose() * rinv;
+          rinv = r.inverse (mattype, info, rcond, true, false);
+          retval = rinv.transpose () * rinv;
         }
       else if (typ == MatrixType::Lower)
         {
-          rinv = r.transpose().inverse(mattype, info, rcond, true, false);
-          retval = rinv.transpose() * rinv;
+          rinv = r.transpose ().inverse (mattype, info, rcond, true, false);
+          retval = rinv.transpose () * rinv;
         }
       else
         (*current_liboctave_error_handler)
rename from liboctave/SparsedbleCHOL.h
rename to liboctave/numeric/SparsedbleCHOL.h
--- a/liboctave/SparsedbleCHOL.h
+++ b/liboctave/numeric/SparsedbleCHOL.h
@@ -35,12 +35,12 @@
 
   SparseCHOL (void) : sparse_base_chol<SparseMatrix, double, SparseMatrix> () { }
 
-  SparseCHOL (const SparseMatrix& a, bool natural = true) :
-    sparse_base_chol<SparseMatrix, double, SparseMatrix> (a, natural) { }
+  SparseCHOL (const SparseMatrix& a, bool natural = true, bool force = false) :
+    sparse_base_chol<SparseMatrix, double, SparseMatrix> (a, natural, force) { }
 
   SparseCHOL (const SparseMatrix& a, octave_idx_type& info,
-              bool natural = true) :
-    sparse_base_chol<SparseMatrix, double, SparseMatrix> (a, info, natural) { }
+              bool natural = false, bool force = false) :
+    sparse_base_chol<SparseMatrix, double, SparseMatrix> (a, info, natural, force) { }
 
   SparseCHOL (const SparseCHOL& a) :
     sparse_base_chol<SparseMatrix, double, SparseMatrix> (a) { }
@@ -55,7 +55,7 @@
       return *this;
     }
 
-  SparseMatrix chol_matrix (void) const { return R(); }
+  SparseMatrix chol_matrix (void) const { return R (); }
 
   SparseMatrix L (void) const
   { return sparse_base_chol<SparseMatrix, double, SparseMatrix>:: L (); }
rename from liboctave/SparsedbleLU.cc
rename to liboctave/numeric/SparsedbleLU.cc
--- a/liboctave/SparsedbleLU.cc
+++ b/liboctave/numeric/SparsedbleLU.cc
@@ -57,7 +57,7 @@
   if (!xisnan (tmp))
     Control (UMFPACK_PRL) = tmp;
 
-  if (piv_thres.nelem() == 2)
+  if (piv_thres.nelem () == 2)
     {
       tmp = (piv_thres (0) > 1. ? 1. : piv_thres (0));
       if (!xisnan (tmp))
@@ -253,7 +253,7 @@
       if (!xisnan (tmp))
         Control (UMFPACK_PRL) = tmp;
 
-      if (piv_thres.nelem() == 2)
+      if (piv_thres.nelem () == 2)
         {
           tmp = (piv_thres (0) > 1. ? 1. : piv_thres (0));
           if (!xisnan (tmp))
@@ -311,7 +311,7 @@
         OCTAVE_LOCAL_BUFFER (octave_idx_type, qinit, nc);
 
         for (octave_idx_type i = 0; i < nc; i++)
-          qinit [i] = static_cast<octave_idx_type> (Qinit (i));
+          qinit[i] = static_cast<octave_idx_type> (Qinit (i));
 
         status = UMFPACK_DNAME (qsymbolic) (nr, nc, Ap, Ai, Ax,
                                        qinit, &Symbolic, control, info);
rename from liboctave/SparsedbleLU.h
rename to liboctave/numeric/SparsedbleLU.h
--- a/liboctave/SparsedbleLU.h
+++ b/liboctave/numeric/SparsedbleLU.h
@@ -36,11 +36,11 @@
   SparseLU (void)
     : sparse_base_lu <SparseMatrix, double, SparseMatrix, double> () { }
 
-  SparseLU (const SparseMatrix& a, const Matrix& piv_thres = Matrix(),
+  SparseLU (const SparseMatrix& a, const Matrix& piv_thres = Matrix (),
             bool scale = false);
 
   SparseLU (const SparseMatrix& a, const ColumnVector& Qinit,
-            const Matrix& piv_thres = Matrix(), bool scale = false,
+            const Matrix& piv_thres = Matrix (), bool scale = false,
             bool FixedQ = false, double droptol = -1.,
             bool milu = false, bool udiag = false);
 
rename from liboctave/base-aepbal.h
rename to liboctave/numeric/base-aepbal.h
rename from liboctave/base-dae.h
rename to liboctave/numeric/base-dae.h
rename from liboctave/base-de.h
rename to liboctave/numeric/base-de.h
rename from liboctave/base-lu.cc
rename to liboctave/numeric/base-lu.cc
--- a/liboctave/base-lu.cc
+++ b/liboctave/numeric/base-lu.cc
@@ -111,7 +111,7 @@
 base_lu <lu_type> :: Y (void) const
 {
   if (! packed ())
-    (*current_liboctave_error_handler) ("lu: Y() not implemented for unpacked form");
+    (*current_liboctave_error_handler) ("lu: Y () not implemented for unpacked form");
   return a_fact;
 }
 
@@ -128,7 +128,7 @@
       for (octave_idx_type i = 0; i < a_nr; i++)
         pvt.xelem (i) = i;
 
-      for (octave_idx_type i = 0; i < ipvt.length(); i++)
+      for (octave_idx_type i = 0; i < ipvt.length (); i++)
         {
           octave_idx_type k = ipvt.xelem (i);
 
rename from liboctave/base-lu.h
rename to liboctave/numeric/base-lu.h
rename from liboctave/base-min.h
rename to liboctave/numeric/base-min.h
rename from liboctave/base-qr.cc
rename to liboctave/numeric/base-qr.cc
rename from liboctave/base-qr.h
rename to liboctave/numeric/base-qr.h
rename from liboctave/bsxfun-decl.h
rename to liboctave/numeric/bsxfun-decl.h
rename from liboctave/bsxfun-defs.cc
rename to liboctave/numeric/bsxfun-defs.cc
rename from liboctave/bsxfun.h
rename to liboctave/numeric/bsxfun.h
rename from liboctave/dbleAEPBAL.cc
rename to liboctave/numeric/dbleAEPBAL.cc
rename from liboctave/dbleAEPBAL.h
rename to liboctave/numeric/dbleAEPBAL.h
rename from liboctave/dbleCHOL.cc
rename to liboctave/numeric/dbleCHOL.cc
--- a/liboctave/dbleCHOL.cc
+++ b/liboctave/numeric/dbleCHOL.cc
@@ -157,7 +157,7 @@
       octave_idx_type info = 0;
 
       Matrix tmp = r;
-      double *v = tmp.fortran_vec();
+      double *v = tmp.fortran_vec ();
 
       if (info == 0)
         {
rename from liboctave/dbleCHOL.h
rename to liboctave/numeric/dbleCHOL.h
rename from liboctave/dbleGEPBAL.cc
rename to liboctave/numeric/dbleGEPBAL.cc
--- a/liboctave/dbleGEPBAL.cc
+++ b/liboctave/numeric/dbleGEPBAL.cc
@@ -70,7 +70,7 @@
       return -1;
     }
 
-  if (a.dims() != b.dims ())
+  if (a.dims () != b.dims ())
     {
       gripe_nonconformant ("GEPBALANCE", n, n, b.rows(), b.cols());
       return -1;
rename from liboctave/dbleGEPBAL.h
rename to liboctave/numeric/dbleGEPBAL.h
rename from liboctave/dbleHESS.cc
rename to liboctave/numeric/dbleHESS.cc
rename from liboctave/dbleHESS.h
rename to liboctave/numeric/dbleHESS.h
rename from liboctave/dbleLU.cc
rename to liboctave/numeric/dbleLU.cc
--- a/liboctave/dbleLU.cc
+++ b/liboctave/numeric/dbleLU.cc
@@ -33,8 +33,8 @@
 
 // Instantiate the base LU class for the types we need.
 
-#include <base-lu.h>
-#include <base-lu.cc>
+#include "base-lu.h"
+#include "base-lu.cc"
 
 template class base_lu <Matrix>;
 
rename from liboctave/dbleLU.h
rename to liboctave/numeric/dbleLU.h
rename from liboctave/dbleQR.cc
rename to liboctave/numeric/dbleQR.cc
--- a/liboctave/dbleQR.cc
+++ b/liboctave/numeric/dbleQR.cc
@@ -466,7 +466,7 @@
 
   if (u.length () == m && v.length () == n)
     {
-      init(q*r + Matrix (u) * Matrix (v).transpose (), get_type ());
+      init (q*r + Matrix (u) * Matrix (v).transpose (), get_type ());
     }
   else
     (*current_liboctave_error_handler) ("qrupdate: dimensions mismatch");
@@ -482,7 +482,7 @@
 
   if (u.rows () == m && v.rows () == n && u.cols () == v.cols ())
     {
-      init(q*r + u * v.transpose (), get_type ());
+      init (q*r + u * v.transpose (), get_type ());
     }
   else
     (*current_liboctave_error_handler) ("qrupdate: dimensions mismatch");
rename from liboctave/dbleQR.h
rename to liboctave/numeric/dbleQR.h
rename from liboctave/dbleQRP.cc
rename to liboctave/numeric/dbleQRP.cc
rename from liboctave/dbleQRP.h
rename to liboctave/numeric/dbleQRP.h
rename from liboctave/dbleSCHUR.cc
rename to liboctave/numeric/dbleSCHUR.cc
rename from liboctave/dbleSCHUR.h
rename to liboctave/numeric/dbleSCHUR.h
rename from liboctave/dbleSVD.cc
rename to liboctave/numeric/dbleSVD.cc
--- a/liboctave/dbleSVD.cc
+++ b/liboctave/numeric/dbleSVD.cc
@@ -134,7 +134,7 @@
   double *u = left_sm.fortran_vec ();
 
   sigma.resize (nrow_s, ncol_s);
-  double *s_vec  = sigma.fortran_vec ();
+  double *s_vec = sigma.fortran_vec ();
 
   if (! (jobv == 'N' || jobv == 'O'))
     right_sm.resize (nrow_vt, n);
rename from liboctave/dbleSVD.h
rename to liboctave/numeric/dbleSVD.h
rename from liboctave/eigs-base.cc
rename to liboctave/numeric/eigs-base.cc
--- a/liboctave/eigs-base.cc
+++ b/liboctave/numeric/eigs-base.cc
@@ -226,14 +226,14 @@
 static M
 ltsolve (const SM& L, const ColumnVector& Q, const M& m)
 {
-  octave_idx_type n = L.cols();
-  octave_idx_type b_nc = m.cols();
+  octave_idx_type n = L.cols ();
+  octave_idx_type b_nc = m.cols ();
   octave_idx_type err = 0;
   double rcond;
   MatrixType ltyp (MatrixType::Lower);
   M tmp = L.solve (ltyp, m, err, rcond, 0);
   M retval;
-  const double* qv = Q.fortran_vec();
+  const double* qv = Q.fortran_vec ();
 
   if (!err)
     {
@@ -241,8 +241,8 @@
       for (octave_idx_type j = 0; j < b_nc; j++)
         {
           for (octave_idx_type i = 0; i < n; i++)
-            retval.elem(static_cast<octave_idx_type>(qv[i]), j)  =
-              tmp.elem(i,j);
+            retval.elem (static_cast<octave_idx_type>(qv[i]), j) =
+              tmp.elem (i,j);
         }
     }
 
@@ -253,18 +253,18 @@
 static M
 utsolve (const SM& U, const ColumnVector& Q, const M& m)
 {
-  octave_idx_type n = U.cols();
-  octave_idx_type b_nc = m.cols();
+  octave_idx_type n = U.cols ();
+  octave_idx_type b_nc = m.cols ();
   octave_idx_type err = 0;
   double rcond;
   MatrixType utyp (MatrixType::Upper);
 
   M retval (n, b_nc);
-  const double* qv = Q.fortran_vec();
+  const double* qv = Q.fortran_vec ();
   for (octave_idx_type j = 0; j < b_nc; j++)
     {
       for (octave_idx_type i = 0; i < n; i++)
-        retval.elem(i,j) = m.elem(static_cast<octave_idx_type>(qv[i]), j);
+        retval.elem (i,j) = m.elem (static_cast<octave_idx_type>(qv[i]), j);
     }
   return U.solve (utyp, retval, err, rcond, 0);
 }
@@ -278,8 +278,8 @@
     y[j] = 0.;
 
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++)
-      y[m.ridx(i)] += m.data(i) * x[j];
+    for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++)
+      y[m.ridx (i)] += m.data (i) * x[j];
 
   return true;
 }
@@ -315,8 +315,8 @@
     y[j] = 0.;
 
   for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++)
-      y[m.ridx(i)] += m.data(i) * x[j];
+    for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++)
+      y[m.ridx (i)] += m.data (i) * x[j];
 
   return true;
 }
@@ -347,15 +347,15 @@
 {
   octave_idx_type info;
   CHOL fact (b, info);
-  octave_idx_type n = b.cols();
+  octave_idx_type n = b.cols ();
 
   if (info != 0)
     return false;
   else
     {
       bt = fact.chol_matrix ();
-      b =  bt.transpose();
-      permB = ColumnVector(n);
+      b = bt.transpose ();
+      permB = ColumnVector (n);
       for (octave_idx_type i = 0; i < n; i++)
         permB(i) = i;
       return true;
@@ -368,13 +368,13 @@
   octave_idx_type info;
   SparseCHOL fact (b, info, false);
 
-  if (fact.P() != 0)
+  if (fact.P () != 0)
     return false;
   else
     {
-      b = fact.L();
-      bt = b.transpose();
-      permB = fact.perm() - 1.0;
+      b = fact.L ();
+      bt = b.transpose ();
+      permB = fact.perm () - 1.0;
       return true;
     }
 }
@@ -384,15 +384,15 @@
 {
   octave_idx_type info;
   ComplexCHOL fact (b, info);
-  octave_idx_type n = b.cols();
+  octave_idx_type n = b.cols ();
 
   if (info != 0)
     return false;
   else
     {
       bt = fact.chol_matrix ();
-      b =  bt.hermitian();
-      permB = ColumnVector(n);
+      b = bt.hermitian ();
+      permB = ColumnVector (n);
       for (octave_idx_type i = 0; i < n; i++)
         permB(i) = i;
       return true;
@@ -406,13 +406,13 @@
   octave_idx_type info;
   SparseComplexCHOL fact (b, info, false);
 
-  if (fact.P() != 0)
+  if (fact.P () != 0)
     return false;
   else
     {
-      b = fact.L();
-      bt = b.hermitian();
-      permB = fact.perm() - 1.0;
+      b = fact.L ();
+      bt = b.hermitian ();
+      permB = fact.perm () - 1.0;
       return true;
     }
 }
@@ -424,7 +424,7 @@
                 octave_idx_type *Q)
 {
   bool have_b = ! b.is_empty ();
-  octave_idx_type n = m.rows();
+  octave_idx_type n = m.rows ();
 
   // Caclulate LU decomposition of 'A - sigma * B'
   SparseMatrix AminusSigmaB (m);
@@ -433,24 +433,24 @@
     {
       if (cholB)
         {
-          if (permB.length())
+          if (permB.length ())
             {
               SparseMatrix tmp(n,n,n);
               for (octave_idx_type i = 0; i < n; i++)
                 {
-                  tmp.xcidx(i) = i;
-                  tmp.xridx(i) =
+                  tmp.xcidx (i) = i;
+                  tmp.xridx (i) =
                     static_cast<octave_idx_type>(permB(i));
-                  tmp.xdata(i) = 1;
+                  tmp.xdata (i) = 1;
                 }
-              tmp.xcidx(n) = n;
+              tmp.xcidx (n) = n;
 
               AminusSigmaB = AminusSigmaB - sigma * tmp *
-                b.transpose() * b * tmp.transpose();
+                b.transpose () * b * tmp.transpose ();
             }
           else
             AminusSigmaB = AminusSigmaB - sigma *
-              b.transpose() * b;
+              b.transpose () * b;
         }
       else
         AminusSigmaB = AminusSigmaB - sigma * b;
@@ -459,13 +459,13 @@
     {
       SparseMatrix sigmat (n, n, n);
 
-          // Create sigma * speye(n,n)
+          // Create sigma * speye (n,n)
           sigmat.xcidx (0) = 0;
           for (octave_idx_type i = 0; i < n; i++)
             {
-              sigmat.xdata(i) = sigma;
-              sigmat.xridx(i) = i;
-              sigmat.xcidx(i+1) = i + 1;
+              sigmat.xdata (i) = sigma;
+              sigmat.xridx (i) = i;
+              sigmat.xcidx (i+1) = i + 1;
             }
 
           AminusSigmaB = AminusSigmaB - sigmat;
@@ -490,9 +490,9 @@
   for (octave_idx_type j = 0; j < n; j++)
     {
       double d = 0.;
-      if (U.xcidx(j+1) > U.xcidx(j) &&
-          U.xridx (U.xcidx(j+1)-1) == j)
-        d = std::abs (U.xdata (U.xcidx(j+1)-1));
+      if (U.xcidx (j+1) > U.xcidx (j) &&
+          U.xridx (U.xcidx (j+1)-1) == j)
+        d = std::abs (U.xdata (U.xcidx (j+1)-1));
 
       if (xisnan (minU) || d < minU)
         minU = d;
@@ -522,7 +522,7 @@
                 octave_idx_type *Q)
 {
   bool have_b = ! b.is_empty ();
-  octave_idx_type n = m.cols();
+  octave_idx_type n = m.cols ();
 
   // Caclulate LU decomposition of 'A - sigma * B'
   Matrix AminusSigmaB (m);
@@ -531,18 +531,18 @@
     {
       if (cholB)
         {
-          Matrix tmp = sigma * b.transpose() * b;
-          const double *pB = permB.fortran_vec();
-          double *p = AminusSigmaB.fortran_vec();
-
-          if (permB.length())
+          Matrix tmp = sigma * b.transpose () * b;
+          const double *pB = permB.fortran_vec ();
+          double *p = AminusSigmaB.fortran_vec ();
+
+          if (permB.length ())
             {
               for (octave_idx_type j = 0;
-                   j < b.cols(); j++)
+                   j < b.cols (); j++)
                 for (octave_idx_type i = 0;
-                     i < b.rows(); i++)
-                  *p++ -=  tmp.xelem (static_cast<octave_idx_type>(pB[i]),
-                                      static_cast<octave_idx_type>(pB[j]));
+                     i < b.rows (); i++)
+                  *p++ -= tmp.xelem (static_cast<octave_idx_type>(pB[i]),
+                                     static_cast<octave_idx_type>(pB[j]));
             }
           else
             AminusSigmaB = AminusSigmaB - tmp;
@@ -552,7 +552,7 @@
     }
   else
     {
-      double *p = AminusSigmaB.fortran_vec();
+      double *p = AminusSigmaB.fortran_vec ();
 
       for (octave_idx_type i = 0; i < n; i++)
         p[i*(n+1)] -= sigma;
@@ -560,7 +560,7 @@
 
   LU fact (AminusSigmaB);
 
-  L = fact.P().transpose() * fact.L ();
+  L = fact.P ().transpose () * fact.L ();
   U = fact.U ();
   for (octave_idx_type j = 0; j < n; j++)
     P[j] = Q[j] = j;
@@ -570,7 +570,7 @@
   double maxU = octave_NaN;
   for (octave_idx_type j = 0; j < n; j++)
     {
-      double d = std::abs (U.xelem(j,j));
+      double d = std::abs (U.xelem (j,j));
       if (xisnan (minU) || d < minU)
         minU = d;
 
@@ -599,7 +599,7 @@
                 octave_idx_type *P, octave_idx_type *Q)
 {
   bool have_b = ! b.is_empty ();
-  octave_idx_type n = m.rows();
+  octave_idx_type n = m.rows ();
 
   // Caclulate LU decomposition of 'A - sigma * B'
   SparseComplexMatrix AminusSigmaB (m);
@@ -608,23 +608,23 @@
     {
       if (cholB)
         {
-          if (permB.length())
+          if (permB.length ())
             {
               SparseMatrix tmp(n,n,n);
               for (octave_idx_type i = 0; i < n; i++)
                 {
-                  tmp.xcidx(i) = i;
-                  tmp.xridx(i) =
+                  tmp.xcidx (i) = i;
+                  tmp.xridx (i) =
                     static_cast<octave_idx_type>(permB(i));
-                  tmp.xdata(i) = 1;
+                  tmp.xdata (i) = 1;
                 }
-              tmp.xcidx(n) = n;
-
-              AminusSigmaB = AminusSigmaB - tmp * b.hermitian() * b *
-                tmp.transpose() * sigma;
+              tmp.xcidx (n) = n;
+
+              AminusSigmaB = AminusSigmaB - tmp * b.hermitian () * b *
+                tmp.transpose () * sigma;
             }
           else
-            AminusSigmaB = AminusSigmaB - sigma * b.hermitian() * b;
+            AminusSigmaB = AminusSigmaB - sigma * b.hermitian () * b;
         }
       else
         AminusSigmaB = AminusSigmaB - sigma * b;
@@ -633,13 +633,13 @@
     {
       SparseComplexMatrix sigmat (n, n, n);
 
-      // Create sigma * speye(n,n)
+      // Create sigma * speye (n,n)
       sigmat.xcidx (0) = 0;
       for (octave_idx_type i = 0; i < n; i++)
         {
-          sigmat.xdata(i) = sigma;
-          sigmat.xridx(i) = i;
-          sigmat.xcidx(i+1) = i + 1;
+          sigmat.xdata (i) = sigma;
+          sigmat.xridx (i) = i;
+          sigmat.xcidx (i+1) = i + 1;
         }
 
       AminusSigmaB = AminusSigmaB - sigmat;
@@ -664,9 +664,9 @@
   for (octave_idx_type j = 0; j < n; j++)
     {
       double d = 0.;
-      if (U.xcidx(j+1) > U.xcidx(j) &&
-          U.xridx (U.xcidx(j+1)-1) == j)
-        d = std::abs (U.xdata (U.xcidx(j+1)-1));
+      if (U.xcidx (j+1) > U.xcidx (j) &&
+          U.xridx (U.xcidx (j+1)-1) == j)
+        d = std::abs (U.xdata (U.xcidx (j+1)-1));
 
       if (xisnan (minU) || d < minU)
         minU = d;
@@ -696,7 +696,7 @@
                 octave_idx_type *Q)
 {
   bool have_b = ! b.is_empty ();
-  octave_idx_type n = m.cols();
+  octave_idx_type n = m.cols ();
 
   // Caclulate LU decomposition of 'A - sigma * B'
   ComplexMatrix AminusSigmaB (m);
@@ -705,18 +705,18 @@
     {
       if (cholB)
         {
-          ComplexMatrix tmp = sigma * b.hermitian() * b;
-          const double *pB = permB.fortran_vec();
-          Complex *p = AminusSigmaB.fortran_vec();
-
-          if (permB.length())
+          ComplexMatrix tmp = sigma * b.hermitian () * b;
+          const double *pB = permB.fortran_vec ();
+          Complex *p = AminusSigmaB.fortran_vec ();
+
+          if (permB.length ())
             {
               for (octave_idx_type j = 0;
-                   j < b.cols(); j++)
+                   j < b.cols (); j++)
                 for (octave_idx_type i = 0;
-                     i < b.rows(); i++)
-                  *p++ -=  tmp.xelem (static_cast<octave_idx_type>(pB[i]),
-                                      static_cast<octave_idx_type>(pB[j]));
+                     i < b.rows (); i++)
+                  *p++ -= tmp.xelem (static_cast<octave_idx_type>(pB[i]),
+                                     static_cast<octave_idx_type>(pB[j]));
             }
           else
             AminusSigmaB = AminusSigmaB - tmp;
@@ -726,7 +726,7 @@
     }
   else
     {
-      Complex *p = AminusSigmaB.fortran_vec();
+      Complex *p = AminusSigmaB.fortran_vec ();
 
       for (octave_idx_type i = 0; i < n; i++)
         p[i*(n+1)] -= sigma;
@@ -734,7 +734,7 @@
 
   ComplexLU fact (AminusSigmaB);
 
-  L = fact.P().transpose() * fact.L ();
+  L = fact.P ().transpose () * fact.L ();
   U = fact.U ();
   for (octave_idx_type j = 0; j < n; j++)
     P[j] = Q[j] = j;
@@ -744,7 +744,7 @@
   double maxU = octave_NaN;
   for (octave_idx_type j = 0; j < n; j++)
     {
-      double d = std::abs (U.xelem(j,j));
+      double d = std::abs (U.xelem (j,j));
       if (xisnan (minU) || d < minU)
         minU = d;
 
@@ -779,30 +779,30 @@
   M b(_b);
   octave_idx_type n = m.cols ();
   octave_idx_type mode = 1;
-  bool have_b = ! b.is_empty();
+  bool have_b = ! b.is_empty ();
   bool note3 = false;
   char bmat = 'I';
   double sigma = 0.;
   M bt;
 
-  if (m.rows() != m.cols())
+  if (m.rows () != m.cols ())
     {
       (*current_liboctave_error_handler) ("eigs: A must be square");
       return -1;
     }
-  if (have_b && (m.rows() != b.rows() || m.rows() != b.cols()))
+  if (have_b && (m.rows () != b.rows () || m.rows () != b.cols ()))
     {
       (*current_liboctave_error_handler)
         ("eigs: B must be square and the same size as A");
       return -1;
     }
 
-  if (resid.is_empty())
+  if (resid.is_empty ())
     {
-      std::string rand_dist = octave_rand::distribution();
-      octave_rand::distribution("uniform");
-      resid = ColumnVector (octave_rand::vector(n));
-      octave_rand::distribution(rand_dist);
+      std::string rand_dist = octave_rand::distribution ();
+      octave_rand::distribution ("uniform");
+      resid = ColumnVector (octave_rand::vector (n));
+      octave_rand::distribution (rand_dist);
     }
 
   if (n < 3)
@@ -827,7 +827,7 @@
     {
       (*current_liboctave_error_handler)
         ("eigs: Invalid number of eigenvalues to extract (must be 0 < k < n-1-1).\n"
-         "      Use 'eig(full(A))' instead");
+         "      Use 'eig (full (A))' instead");
       return -1;
     }
 
@@ -838,10 +838,10 @@
       return -1;
     }
 
-  if (have_b && cholB && permB.length() != 0)
+  if (have_b && cholB && permB.length () != 0)
     {
       // Check the we really have a permutation vector
-      if (permB.length() != n)
+      if (permB.length () != n)
         {
           (*current_liboctave_error_handler)
             ("eigs: permB vector invalid");
@@ -888,17 +888,17 @@
       if (cholB)
         {
           bt = b;
-          b = b.transpose();
-          if (permB.length() == 0)
+          b = b.transpose ();
+          if (permB.length () == 0)
             {
-              permB = ColumnVector(n);
+              permB = ColumnVector (n);
               for (octave_idx_type i = 0; i < n; i++)
                 permB(i) = i;
             }
         }
       else
         {
-          if (! make_cholb(b, bt, permB))
+          if (! make_cholb (b, bt, permB))
             {
               (*current_liboctave_error_handler)
                 ("eigs: The matrix B is not positive definite");
@@ -939,7 +939,7 @@
     {
       F77_FUNC (dsaupd, DSAUPD)
         (ido, F77_CONST_CHAR_ARG2 (&bmat, 1), n,
-         F77_CONST_CHAR_ARG2 ((typ.c_str()), 2),
+         F77_CONST_CHAR_ARG2 ((typ.c_str ()), 2),
          k, tol, presid, p, v, n, iparam,
          ipntr, workd, workl, lwork, info
          F77_CHAR_ARG_LEN(1) F77_CHAR_ARG_LEN(2));
@@ -951,7 +951,7 @@
           return -1;
         }
 
-      if (disp > 0 && !xisnan(workl[iptr(5)-1]))
+      if (disp > 0 && !xisnan (workl[iptr (5)-1]))
         {
           if (iter++)
             {
@@ -979,7 +979,7 @@
               for (octave_idx_type i = 0; i < n; i++)
                 mtmp(i,0) = workd[i + iptr(0) - 1];
 
-              mtmp = utsolve(bt, permB, m * ltsolve(b, permB, mtmp));
+              mtmp = utsolve (bt, permB, m * ltsolve (b, permB, mtmp));
 
               for (octave_idx_type i = 0; i < n; i++)
                 workd[i+iptr(1)-1] = mtmp(i,0);
@@ -1073,7 +1073,7 @@
                 }
 
               if (note3)
-                eig_vec = ltsolve(b, permB, eig_vec);
+                eig_vec = ltsolve (b, permB, eig_vec);
             }
         }
       else
@@ -1100,15 +1100,15 @@
   M b(_b);
   octave_idx_type n = m.cols ();
   octave_idx_type mode = 3;
-  bool have_b = ! b.is_empty();
+  bool have_b = ! b.is_empty ();
   std::string typ = "LM";
 
-  if (m.rows() != m.cols())
+  if (m.rows () != m.cols ())
     {
       (*current_liboctave_error_handler) ("eigs: A must be square");
       return -1;
     }
-  if (have_b && (m.rows() != b.rows() || m.rows() != b.cols()))
+  if (have_b && (m.rows () != b.rows () || m.rows () != b.cols ()))
     {
       (*current_liboctave_error_handler)
         ("eigs: B must be square and the same size as A");
@@ -1121,12 +1121,12 @@
   //                                _b, permB, resid, os, tol, rvec, cholB,
   //                                disp, maxit);
 
-  if (resid.is_empty())
+  if (resid.is_empty ())
     {
-      std::string rand_dist = octave_rand::distribution();
-      octave_rand::distribution("uniform");
-      resid = ColumnVector (octave_rand::vector(n));
-      octave_rand::distribution(rand_dist);
+      std::string rand_dist = octave_rand::distribution ();
+      octave_rand::distribution ("uniform");
+      resid = ColumnVector (octave_rand::vector (n));
+      octave_rand::distribution (rand_dist);
     }
 
   if (n < 3)
@@ -1140,7 +1140,7 @@
     {
       (*current_liboctave_error_handler)
         ("eigs: Invalid number of eigenvalues to extract (must be 0 < k < n-1-1).\n"
-             "      Use 'eig(full(A))' instead");
+             "      Use 'eig (full (A))' instead");
       return -1;
     }
 
@@ -1162,10 +1162,10 @@
       return -1;
     }
 
-  if (have_b && cholB && permB.length() != 0)
+  if (have_b && cholB && permB.length () != 0)
     {
       // Check the we really have a permutation vector
-      if (permB.length() != n)
+      if (permB.length () != n)
         {
           (*current_liboctave_error_handler) ("eigs: permB vector invalid");
           return -1;
@@ -1215,10 +1215,10 @@
   int iter = 0;
   M L, U;
 
-  OCTAVE_LOCAL_BUFFER (octave_idx_type, P, (have_b ? b.rows() : m.rows()));
-  OCTAVE_LOCAL_BUFFER (octave_idx_type, Q, (have_b ? b.cols() : m.cols()));
-
-  if (! LuAminusSigmaB(m, b, cholB, permB, sigma, L, U, P, Q))
+  OCTAVE_LOCAL_BUFFER (octave_idx_type, P, (have_b ? b.rows () : m.rows ()));
+  OCTAVE_LOCAL_BUFFER (octave_idx_type, Q, (have_b ? b.cols () : m.cols ()));
+
+  if (! LuAminusSigmaB (m, b, cholB, permB, sigma, L, U, P, Q))
     return -1;
 
   octave_idx_type lwork = p * (p + 8);
@@ -1232,7 +1232,7 @@
     {
       F77_FUNC (dsaupd, DSAUPD)
         (ido, F77_CONST_CHAR_ARG2 (&bmat, 1), n,
-         F77_CONST_CHAR_ARG2 ((typ.c_str()), 2),
+         F77_CONST_CHAR_ARG2 ((typ.c_str ()), 2),
          k, tol, presid, p, v, n, iparam,
          ipntr, workd, workl, lwork, info
          F77_CHAR_ARG_LEN(1) F77_CHAR_ARG_LEN(2));
@@ -1244,7 +1244,7 @@
           return -1;
         }
 
-      if (disp > 0 && !xisnan(workl[iptr(5)-1]))
+      if (disp > 0 && !xisnan (workl[iptr (5)-1]))
         {
           if (iter++)
             {
@@ -1430,12 +1430,12 @@
   octave_idx_type mode = 1;
   int err = 0;
 
-  if (resid.is_empty())
+  if (resid.is_empty ())
     {
-      std::string rand_dist = octave_rand::distribution();
-      octave_rand::distribution("uniform");
-      resid = ColumnVector (octave_rand::vector(n));
-      octave_rand::distribution(rand_dist);
+      std::string rand_dist = octave_rand::distribution ();
+      octave_rand::distribution ("uniform");
+      resid = ColumnVector (octave_rand::vector (n));
+      octave_rand::distribution (rand_dist);
     }
 
   if (n < 3)
@@ -1460,7 +1460,7 @@
     {
       (*current_liboctave_error_handler)
         ("eigs: Invalid number of eigenvalues to extract (must be 0 < k < n-1).\n"
-             "      Use 'eig(full(A))' instead");
+             "      Use 'eig (full (A))' instead");
       return -1;
     }
 
@@ -1533,7 +1533,7 @@
     {
       F77_FUNC (dsaupd, DSAUPD)
         (ido, F77_CONST_CHAR_ARG2 (&bmat, 1), n,
-         F77_CONST_CHAR_ARG2 ((typ.c_str()), 2),
+         F77_CONST_CHAR_ARG2 ((typ.c_str ()), 2),
          k, tol, presid, p, v, n, iparam,
          ipntr, workd, workl, lwork, info
          F77_CHAR_ARG_LEN(1) F77_CHAR_ARG_LEN(2));
@@ -1545,7 +1545,7 @@
           return -1;
         }
 
-      if (disp > 0 && !xisnan(workl[iptr(5)-1]))
+      if (disp > 0 && !xisnan (workl[iptr (5)-1]))
         {
           if (iter++)
             {
@@ -1692,31 +1692,31 @@
   M b(_b);
   octave_idx_type n = m.cols ();
   octave_idx_type mode = 1;
-  bool have_b = ! b.is_empty();
+  bool have_b = ! b.is_empty ();
   bool note3 = false;
   char bmat = 'I';
   double sigmar = 0.;
   double sigmai = 0.;
   M bt;
 
-  if (m.rows() != m.cols())
+  if (m.rows () != m.cols ())
     {
       (*current_liboctave_error_handler) ("eigs: A must be square");
       return -1;
     }
-  if (have_b && (m.rows() != b.rows() || m.rows() != b.cols()))
+  if (have_b && (m.rows () != b.rows () || m.rows () != b.cols ()))
     {
       (*current_liboctave_error_handler)
         ("eigs: B must be square and the same size as A");
       return -1;
     }
 
-  if (resid.is_empty())
+  if (resid.is_empty ())
     {
-      std::string rand_dist = octave_rand::distribution();
-      octave_rand::distribution("uniform");
-      resid = ColumnVector (octave_rand::vector(n));
-      octave_rand::distribution(rand_dist);
+      std::string rand_dist = octave_rand::distribution ();
+      octave_rand::distribution ("uniform");
+      resid = ColumnVector (octave_rand::vector (n));
+      octave_rand::distribution (rand_dist);
     }
 
   if (n < 3)
@@ -1741,7 +1741,7 @@
     {
       (*current_liboctave_error_handler)
         ("eigs: Invalid number of eigenvalues to extract (must be 0 < k < n-1).\n"
-         "      Use 'eig(full(A))' instead");
+         "      Use 'eig (full (A))' instead");
       return -1;
     }
 
@@ -1752,10 +1752,10 @@
       return -1;
     }
 
-  if (have_b && cholB && permB.length() != 0)
+  if (have_b && cholB && permB.length () != 0)
     {
       // Check the we really have a permutation vector
-      if (permB.length() != n)
+      if (permB.length () != n)
         {
           (*current_liboctave_error_handler)
             ("eigs: permB vector invalid");
@@ -1802,17 +1802,17 @@
       if (cholB)
         {
           bt = b;
-          b = b.transpose();
-          if (permB.length() == 0)
+          b = b.transpose ();
+          if (permB.length () == 0)
             {
-              permB = ColumnVector(n);
+              permB = ColumnVector (n);
               for (octave_idx_type i = 0; i < n; i++)
                 permB(i) = i;
             }
         }
       else
         {
-          if (! make_cholb(b, bt, permB))
+          if (! make_cholb (b, bt, permB))
             {
               (*current_liboctave_error_handler)
                 ("eigs: The matrix B is not positive definite");
@@ -1853,7 +1853,7 @@
     {
       F77_FUNC (dnaupd, DNAUPD)
         (ido, F77_CONST_CHAR_ARG2 (&bmat, 1), n,
-         F77_CONST_CHAR_ARG2 ((typ.c_str()), 2),
+         F77_CONST_CHAR_ARG2 ((typ.c_str ()), 2),
          k, tol, presid, p, v, n, iparam,
          ipntr, workd, workl, lwork, info
          F77_CHAR_ARG_LEN(1) F77_CHAR_ARG_LEN(2));
@@ -1893,7 +1893,7 @@
               for (octave_idx_type i = 0; i < n; i++)
                 mtmp(i,0) = workd[i + iptr(0) - 1];
 
-              mtmp = utsolve(bt, permB, m * ltsolve(b, permB, mtmp));
+              mtmp = utsolve (bt, permB, m * ltsolve (b, permB, mtmp));
 
               for (octave_idx_type i = 0; i < n; i++)
                 workd[i+iptr(1)-1] = mtmp(i,0);
@@ -1969,7 +1969,7 @@
               if (dr[i] == 0.0 && di[i] == 0.0 && jj == 0)
                 jj++;
               else
-                d [i-jj] = Complex (dr[i], di[i]);
+                d[i-jj] = Complex (dr[i], di[i]);
             }
           if (jj == 0 && !rvec)
             for (octave_idx_type i = 0; i < k; i++)
@@ -1982,7 +1982,7 @@
               d[i] = d[k - i - 1];
               d[k - i - 1] = dtmp;
             }
-          eig_val.resize(k);
+          eig_val.resize (k);
 
           if (rvec)
             {
@@ -2012,11 +2012,11 @@
                 {
                   octave_idx_type off1 = i * n;
                   octave_idx_type off2 = (i+1) * n;
-                  if (std::imag(eig_val(i)) == 0)
+                  if (std::imag (eig_val(i)) == 0)
                     {
                       for (octave_idx_type j = 0; j < n; j++)
                         eig_vec(j,i) =
-                          Complex(z[j+off1],0.);
+                          Complex (z[j+off1],0.);
                       i++;
                     }
                   else
@@ -2024,17 +2024,17 @@
                       for (octave_idx_type j = 0; j < n; j++)
                         {
                           eig_vec(j,i) =
-                            Complex(z[j+off1],z[j+off2]);
+                            Complex (z[j+off1],z[j+off2]);
                           if (i < k - 1)
                             eig_vec(j,i+1) =
-                              Complex(z[j+off1],-z[j+off2]);
+                              Complex (z[j+off1],-z[j+off2]);
                         }
                       i+=2;
                     }
                 }
 
               if (note3)
-                eig_vec = ltsolve(M (b), permB, eig_vec);
+                eig_vec = ltsolve (M(b), permB, eig_vec);
             }
         }
       else
@@ -2062,16 +2062,16 @@
   M b(_b);
   octave_idx_type n = m.cols ();
   octave_idx_type mode = 3;
-  bool have_b = ! b.is_empty();
+  bool have_b = ! b.is_empty ();
   std::string typ = "LM";
   double sigmai = 0.;
 
-  if (m.rows() != m.cols())
+  if (m.rows () != m.cols ())
     {
       (*current_liboctave_error_handler) ("eigs: A must be square");
       return -1;
     }
-  if (have_b && (m.rows() != b.rows() || m.rows() != b.cols()))
+  if (have_b && (m.rows () != b.rows () || m.rows () != b.cols ()))
     {
       (*current_liboctave_error_handler)
         ("eigs: B must be square and the same size as A");
@@ -2084,12 +2084,12 @@
   //                                   _b, permB, resid, os, tol, rvec, cholB,
   //                                   disp, maxit);
 
-  if (resid.is_empty())
+  if (resid.is_empty ())
     {
-      std::string rand_dist = octave_rand::distribution();
-      octave_rand::distribution("uniform");
-      resid = ColumnVector (octave_rand::vector(n));
-      octave_rand::distribution(rand_dist);
+      std::string rand_dist = octave_rand::distribution ();
+      octave_rand::distribution ("uniform");
+      resid = ColumnVector (octave_rand::vector (n));
+      octave_rand::distribution (rand_dist);
     }
 
   if (n < 3)
@@ -2114,7 +2114,7 @@
     {
       (*current_liboctave_error_handler)
         ("eigs: Invalid number of eigenvalues to extract (must be 0 < k < n-1).\n"
-             "      Use 'eig(full(A))' instead");
+             "      Use 'eig (full (A))' instead");
       return -1;
     }
 
@@ -2125,10 +2125,10 @@
       return -1;
     }
 
-  if (have_b && cholB && permB.length() != 0)
+  if (have_b && cholB && permB.length () != 0)
     {
       // Check that we really have a permutation vector
-      if (permB.length() != n)
+      if (permB.length () != n)
         {
           (*current_liboctave_error_handler) ("eigs: permB vector invalid");
           return -1;
@@ -2178,10 +2178,10 @@
   int iter = 0;
   M L, U;
 
-  OCTAVE_LOCAL_BUFFER (octave_idx_type, P, (have_b ? b.rows() : m.rows()));
-  OCTAVE_LOCAL_BUFFER (octave_idx_type, Q, (have_b ? b.cols() : m.cols()));
-
-  if (! LuAminusSigmaB(m, b, cholB, permB, sigmar, L, U, P, Q))
+  OCTAVE_LOCAL_BUFFER (octave_idx_type, P, (have_b ? b.rows () : m.rows ()));
+  OCTAVE_LOCAL_BUFFER (octave_idx_type, Q, (have_b ? b.cols () : m.cols ()));
+
+  if (! LuAminusSigmaB (m, b, cholB, permB, sigmar, L, U, P, Q))
     return -1;
 
   octave_idx_type lwork = 3 * p * (p + 2);
@@ -2195,7 +2195,7 @@
     {
       F77_FUNC (dnaupd, DNAUPD)
         (ido, F77_CONST_CHAR_ARG2 (&bmat, 1), n,
-         F77_CONST_CHAR_ARG2 ((typ.c_str()), 2),
+         F77_CONST_CHAR_ARG2 ((typ.c_str ()), 2),
          k, tol, presid, p, v, n, iparam,
          ipntr, workd, workl, lwork, info
          F77_CHAR_ARG_LEN(1) F77_CHAR_ARG_LEN(2));
@@ -2207,7 +2207,7 @@
           return -1;
         }
 
-      if (disp > 0 && !xisnan(workl[iptr(5)-1]))
+      if (disp > 0 && !xisnan (workl[iptr (5)-1]))
         {
           if (iter++)
             {
@@ -2355,7 +2355,7 @@
               if (dr[i] == 0.0 && di[i] == 0.0 && jj == 0)
                 jj++;
               else
-                d [i-jj] = Complex (dr[i], di[i]);
+                d[i-jj] = Complex (dr[i], di[i]);
             }
           if (jj == 0 && !rvec)
             for (octave_idx_type i = 0; i < k; i++)
@@ -2368,7 +2368,7 @@
               d[i] = d[k - i - 1];
               d[k - i - 1] = dtmp;
             }
-          eig_val.resize(k);
+          eig_val.resize (k);
 
           if (rvec)
             {
@@ -2398,11 +2398,11 @@
                 {
                   octave_idx_type off1 = i * n;
                   octave_idx_type off2 = (i+1) * n;
-                  if (std::imag(eig_val(i)) == 0)
+                  if (std::imag (eig_val(i)) == 0)
                     {
                       for (octave_idx_type j = 0; j < n; j++)
                         eig_vec(j,i) =
-                          Complex(z[j+off1],0.);
+                          Complex (z[j+off1],0.);
                       i++;
                     }
                   else
@@ -2410,10 +2410,10 @@
                       for (octave_idx_type j = 0; j < n; j++)
                         {
                           eig_vec(j,i) =
-                            Complex(z[j+off1],z[j+off2]);
+                            Complex (z[j+off1],z[j+off2]);
                           if (i < k - 1)
                             eig_vec(j,i+1) =
-                              Complex(z[j+off1],-z[j+off2]);
+                              Complex (z[j+off1],-z[j+off2]);
                         }
                       i+=2;
                     }
@@ -2447,12 +2447,12 @@
   octave_idx_type mode = 1;
   int err = 0;
 
-  if (resid.is_empty())
+  if (resid.is_empty ())
     {
-      std::string rand_dist = octave_rand::distribution();
-      octave_rand::distribution("uniform");
-      resid = ColumnVector (octave_rand::vector(n));
-      octave_rand::distribution(rand_dist);
+      std::string rand_dist = octave_rand::distribution ();
+      octave_rand::distribution ("uniform");
+      resid = ColumnVector (octave_rand::vector (n));
+      octave_rand::distribution (rand_dist);
     }
 
   if (n < 3)
@@ -2477,7 +2477,7 @@
     {
       (*current_liboctave_error_handler)
         ("eigs: Invalid number of eigenvalues to extract (must be 0 < k < n-1).\n"
-             "      Use 'eig(full(A))' instead");
+             "      Use 'eig (full (A))' instead");
       return -1;
     }
 
@@ -2551,7 +2551,7 @@
     {
       F77_FUNC (dnaupd, DNAUPD)
         (ido, F77_CONST_CHAR_ARG2 (&bmat, 1), n,
-         F77_CONST_CHAR_ARG2 ((typ.c_str()), 2),
+         F77_CONST_CHAR_ARG2 ((typ.c_str ()), 2),
          k, tol, presid, p, v, n, iparam,
          ipntr, workd, workl, lwork, info
          F77_CHAR_ARG_LEN(1) F77_CHAR_ARG_LEN(2));
@@ -2667,7 +2667,7 @@
               if (dr[i] == 0.0 && di[i] == 0.0 && jj == 0)
                 jj++;
               else
-                d [i-jj] = Complex (dr[i], di[i]);
+                d[i-jj] = Complex (dr[i], di[i]);
             }
           if (jj == 0 && !rvec)
             for (octave_idx_type i = 0; i < k; i++)
@@ -2680,7 +2680,7 @@
               d[i] = d[k - i - 1];
               d[k - i - 1] = dtmp;
             }
-          eig_val.resize(k);
+          eig_val.resize (k);
 
           if (rvec)
             {
@@ -2710,11 +2710,11 @@
                 {
                   octave_idx_type off1 = i * n;
                   octave_idx_type off2 = (i+1) * n;
-                  if (std::imag(eig_val(i)) == 0)
+                  if (std::imag (eig_val(i)) == 0)
                     {
                       for (octave_idx_type j = 0; j < n; j++)
                         eig_vec(j,i) =
-                          Complex(z[j+off1],0.);
+                          Complex (z[j+off1],0.);
                       i++;
                     }
                   else
@@ -2722,10 +2722,10 @@
                       for (octave_idx_type j = 0; j < n; j++)
                         {
                           eig_vec(j,i) =
-                            Complex(z[j+off1],z[j+off2]);
+                            Complex (z[j+off1],z[j+off2]);
                           if (i < k - 1)
                             eig_vec(j,i+1) =
-                              Complex(z[j+off1],-z[j+off2]);
+                              Complex (z[j+off1],-z[j+off2]);
                         }
                       i+=2;
                     }
@@ -2757,34 +2757,34 @@
   M b(_b);
   octave_idx_type n = m.cols ();
   octave_idx_type mode = 1;
-  bool have_b = ! b.is_empty();
+  bool have_b = ! b.is_empty ();
   bool note3 = false;
   char bmat = 'I';
   Complex sigma = 0.;
   M bt;
 
-  if (m.rows() != m.cols())
+  if (m.rows () != m.cols ())
     {
       (*current_liboctave_error_handler) ("eigs: A must be square");
       return -1;
     }
-  if (have_b && (m.rows() != b.rows() || m.rows() != b.cols()))
+  if (have_b && (m.rows () != b.rows () || m.rows () != b.cols ()))
     {
       (*current_liboctave_error_handler)
         ("eigs: B must be square and the same size as A");
       return -1;
     }
 
-  if (cresid.is_empty())
+  if (cresid.is_empty ())
     {
-      std::string rand_dist = octave_rand::distribution();
-      octave_rand::distribution("uniform");
-      Array<double> rr (octave_rand::vector(n));
-      Array<double> ri (octave_rand::vector(n));
+      std::string rand_dist = octave_rand::distribution ();
+      octave_rand::distribution ("uniform");
+      Array<double> rr (octave_rand::vector (n));
+      Array<double> ri (octave_rand::vector (n));
       cresid = ComplexColumnVector (n);
       for (octave_idx_type i = 0; i < n; i++)
-        cresid(i) = Complex(rr(i),ri(i));
-      octave_rand::distribution(rand_dist);
+        cresid(i) = Complex (rr(i),ri(i));
+      octave_rand::distribution (rand_dist);
     }
 
   if (n < 3)
@@ -2809,7 +2809,7 @@
     {
       (*current_liboctave_error_handler)
         ("eigs: Invalid number of eigenvalues to extract (must be 0 < k < n-1).\n"
-         "      Use 'eig(full(A))' instead");
+         "      Use 'eig (full (A))' instead");
       return -1;
     }
 
@@ -2820,10 +2820,10 @@
       return -1;
     }
 
-  if (have_b && cholB && permB.length() != 0)
+  if (have_b && cholB && permB.length () != 0)
     {
       // Check the we really have a permutation vector
-      if (permB.length() != n)
+      if (permB.length () != n)
         {
           (*current_liboctave_error_handler)
             ("eigs: permB vector invalid");
@@ -2870,17 +2870,17 @@
       if (cholB)
         {
           bt = b;
-          b = b.hermitian();
-          if (permB.length() == 0)
+          b = b.hermitian ();
+          if (permB.length () == 0)
             {
-              permB = ColumnVector(n);
+              permB = ColumnVector (n);
               for (octave_idx_type i = 0; i < n; i++)
                 permB(i) = i;
             }
         }
       else
         {
-          if (! make_cholb(b, bt, permB))
+          if (! make_cholb (b, bt, permB))
             {
               (*current_liboctave_error_handler)
                 ("eigs: The matrix B is not positive definite");
@@ -2922,7 +2922,7 @@
     {
       F77_FUNC (znaupd, ZNAUPD)
         (ido, F77_CONST_CHAR_ARG2 (&bmat, 1), n,
-         F77_CONST_CHAR_ARG2 ((typ.c_str()), 2),
+         F77_CONST_CHAR_ARG2 ((typ.c_str ()), 2),
          k, tol, presid, p, v, n, iparam,
          ipntr, workd, workl, lwork, rwork, info
          F77_CHAR_ARG_LEN(1) F77_CHAR_ARG_LEN(2));
@@ -2934,7 +2934,7 @@
           return -1;
         }
 
-      if (disp > 0 && !xisnan(workl[iptr(5)-1]))
+      if (disp > 0 && !xisnan (workl[iptr (5)-1]))
         {
           if (iter++)
             {
@@ -2961,7 +2961,7 @@
               ComplexMatrix mtmp (n,1);
               for (octave_idx_type i = 0; i < n; i++)
                 mtmp(i,0) = workd[i + iptr(0) - 1];
-              mtmp = utsolve(bt, permB, m * ltsolve(b, permB, mtmp));
+              mtmp = utsolve (bt, permB, m * ltsolve (b, permB, mtmp));
               for (octave_idx_type i = 0; i < n; i++)
                 workd[i+iptr(1)-1] = mtmp(i,0);
 
@@ -3026,7 +3026,7 @@
           d[i] = d[k - i - 1];
           d[k - i - 1] = ctmp;
         }
-      eig_val.resize(k);
+      eig_val.resize (k);
 
       if (rvec)
         {
@@ -3051,7 +3051,7 @@
             }
 
           if (note3)
-            eig_vec = ltsolve(b, permB, eig_vec);
+            eig_vec = ltsolve (b, permB, eig_vec);
         }
     }
   else
@@ -3079,15 +3079,15 @@
   M b(_b);
   octave_idx_type n = m.cols ();
   octave_idx_type mode = 3;
-  bool have_b = ! b.is_empty();
+  bool have_b = ! b.is_empty ();
   std::string typ = "LM";
 
-  if (m.rows() != m.cols())
+  if (m.rows () != m.cols ())
     {
       (*current_liboctave_error_handler) ("eigs: A must be square");
       return -1;
     }
-  if (have_b && (m.rows() != b.rows() || m.rows() != b.cols()))
+  if (have_b && (m.rows () != b.rows () || m.rows () != b.cols ()))
     {
       (*current_liboctave_error_handler)
         ("eigs: B must be square and the same size as A");
@@ -3100,16 +3100,16 @@
   //                                      eig_val, _b, permB, cresid, os, tol,
   //                                      rvec, cholB, disp, maxit);
 
-  if (cresid.is_empty())
+  if (cresid.is_empty ())
     {
-      std::string rand_dist = octave_rand::distribution();
-      octave_rand::distribution("uniform");
-      Array<double> rr (octave_rand::vector(n));
-      Array<double> ri (octave_rand::vector(n));
+      std::string rand_dist = octave_rand::distribution ();
+      octave_rand::distribution ("uniform");
+      Array<double> rr (octave_rand::vector (n));
+      Array<double> ri (octave_rand::vector (n));
       cresid = ComplexColumnVector (n);
       for (octave_idx_type i = 0; i < n; i++)
-        cresid(i) = Complex(rr(i),ri(i));
-      octave_rand::distribution(rand_dist);
+        cresid(i) = Complex (rr(i),ri(i));
+      octave_rand::distribution (rand_dist);
     }
 
   if (n < 3)
@@ -3134,7 +3134,7 @@
     {
       (*current_liboctave_error_handler)
         ("eigs: Invalid number of eigenvalues to extract (must be 0 < k < n-1).\n"
-             "      Use 'eig(full(A))' instead");
+             "      Use 'eig (full (A))' instead");
       return -1;
     }
 
@@ -3145,10 +3145,10 @@
       return -1;
     }
 
-  if (have_b && cholB && permB.length() != 0)
+  if (have_b && cholB && permB.length () != 0)
     {
       // Check that we really have a permutation vector
-      if (permB.length() != n)
+      if (permB.length () != n)
         {
           (*current_liboctave_error_handler) ("eigs: permB vector invalid");
           return -1;
@@ -3198,10 +3198,10 @@
   int iter = 0;
   M L, U;
 
-  OCTAVE_LOCAL_BUFFER (octave_idx_type, P, (have_b ? b.rows() : m.rows()));
-  OCTAVE_LOCAL_BUFFER (octave_idx_type, Q, (have_b ? b.cols() : m.cols()));
-
-  if (! LuAminusSigmaB(m, b, cholB, permB, sigma, L, U, P, Q))
+  OCTAVE_LOCAL_BUFFER (octave_idx_type, P, (have_b ? b.rows () : m.rows ()));
+  OCTAVE_LOCAL_BUFFER (octave_idx_type, Q, (have_b ? b.cols () : m.cols ()));
+
+  if (! LuAminusSigmaB (m, b, cholB, permB, sigma, L, U, P, Q))
     return -1;
 
   octave_idx_type lwork = p * (3 * p + 5);
@@ -3216,7 +3216,7 @@
     {
       F77_FUNC (znaupd, ZNAUPD)
         (ido, F77_CONST_CHAR_ARG2 (&bmat, 1), n,
-         F77_CONST_CHAR_ARG2 ((typ.c_str()), 2),
+         F77_CONST_CHAR_ARG2 ((typ.c_str ()), 2),
          k, tol, presid, p, v, n, iparam,
          ipntr, workd, workl, lwork, rwork, info
          F77_CHAR_ARG_LEN(1) F77_CHAR_ARG_LEN(2));
@@ -3366,7 +3366,7 @@
           d[i] = d[k - i - 1];
           d[k - i - 1] = ctmp;
         }
-      eig_val.resize(k);
+      eig_val.resize (k);
 
       if (rvec)
         {
@@ -3412,21 +3412,21 @@
                              int disp, int maxit)
 {
   std::string typ (_typ);
-  bool have_sigma = (std::abs(sigma) ? true : false);
+  bool have_sigma = (std::abs (sigma) ? true : false);
   char bmat = 'I';
   octave_idx_type mode = 1;
   int err = 0;
 
-  if (cresid.is_empty())
+  if (cresid.is_empty ())
     {
-      std::string rand_dist = octave_rand::distribution();
-      octave_rand::distribution("uniform");
-      Array<double> rr (octave_rand::vector(n));
-      Array<double> ri (octave_rand::vector(n));
+      std::string rand_dist = octave_rand::distribution ();
+      octave_rand::distribution ("uniform");
+      Array<double> rr (octave_rand::vector (n));
+      Array<double> ri (octave_rand::vector (n));
       cresid = ComplexColumnVector (n);
       for (octave_idx_type i = 0; i < n; i++)
-        cresid(i) = Complex(rr(i),ri(i));
-      octave_rand::distribution(rand_dist);
+        cresid(i) = Complex (rr(i),ri(i));
+      octave_rand::distribution (rand_dist);
     }
 
   if (n < 3)
@@ -3451,7 +3451,7 @@
     {
       (*current_liboctave_error_handler)
         ("eigs: Invalid number of eigenvalues to extract (must be 0 < k < n-1).\n"
-             "      Use 'eig(full(A))' instead");
+             "      Use 'eig (full (A))' instead");
       return -1;
     }
 
@@ -3525,7 +3525,7 @@
     {
       F77_FUNC (znaupd, ZNAUPD)
         (ido, F77_CONST_CHAR_ARG2 (&bmat, 1), n,
-         F77_CONST_CHAR_ARG2 ((typ.c_str()), 2),
+         F77_CONST_CHAR_ARG2 ((typ.c_str ()), 2),
          k, tol, presid, p, v, n, iparam,
          ipntr, workd, workl, lwork, rwork, info
          F77_CHAR_ARG_LEN(1) F77_CHAR_ARG_LEN(2));
@@ -3630,7 +3630,7 @@
           d[i] = d[k - i - 1];
           d[k - i - 1] = ctmp;
         }
-      eig_val.resize(k);
+      eig_val.resize (k);
 
       if (rvec)
         {
@@ -3672,7 +3672,8 @@
                          octave_idx_type &info, Matrix &eig_vec,
                          ColumnVector &eig_val, const Matrix& b,
                          ColumnVector &permB, ColumnVector &resid,
-                         std::ostream &os, double tol = DBL_EPSILON,
+                         std::ostream &os,
+                         double tol = std::numeric_limits<double>::epsilon (),
                          bool rvec = false, bool cholB = 0, int disp = 0,
                          int maxit = 300);
 
@@ -3682,7 +3683,8 @@
                          octave_idx_type &info, Matrix &eig_vec,
                          ColumnVector &eig_val, const SparseMatrix& b,
                          ColumnVector &permB, ColumnVector &resid,
-                         std::ostream& os, double tol = DBL_EPSILON,
+                         std::ostream& os,
+                         double tol = std::numeric_limits<double>::epsilon (),
                          bool rvec = false, bool cholB = 0, int disp = 0,
                          int maxit = 300);
 
@@ -3692,7 +3694,8 @@
                               octave_idx_type &info, Matrix &eig_vec,
                               ColumnVector &eig_val, const Matrix& b,
                               ColumnVector &permB, ColumnVector &resid,
-                              std::ostream &os, double tol = DBL_EPSILON,
+                              std::ostream &os,
+                              double tol = std::numeric_limits<double>::epsilon (),
                               bool rvec = false, bool cholB = 0, int disp = 0,
                               int maxit = 300);
 
@@ -3702,7 +3705,8 @@
                               octave_idx_type &info, Matrix &eig_vec,
                               ColumnVector &eig_val, const SparseMatrix& b,
                               ColumnVector &permB, ColumnVector &resid,
-                              std::ostream &os, double tol = DBL_EPSILON,
+                              std::ostream &os,
+                              double tol = std::numeric_limits<double>::epsilon (),
                               bool rvec = false, bool cholB = 0, int disp = 0,
                               int maxit = 300);
 
@@ -3713,8 +3717,9 @@
                        octave_idx_type &info,
                        Matrix &eig_vec, ColumnVector &eig_val,
                        ColumnVector &resid, std::ostream &os,
-                       double tol = DBL_EPSILON, bool rvec = false,
-                       bool cholB = 0, int disp = 0, int maxit = 300);
+                       double tol = std::numeric_limits<double>::epsilon (),
+                       bool rvec = false, bool cholB = 0, int disp = 0,
+                       int maxit = 300);
 
 extern octave_idx_type
 EigsRealNonSymmetricMatrix (const Matrix& m, const std::string typ,
@@ -3722,7 +3727,8 @@
                             octave_idx_type &info, ComplexMatrix &eig_vec,
                             ComplexColumnVector &eig_val, const Matrix& b,
                             ColumnVector &permB, ColumnVector &resid,
-                            std::ostream &os, double tol = DBL_EPSILON,
+                            std::ostream &os,
+                            double tol = std::numeric_limits<double>::epsilon (),
                             bool rvec = false, bool cholB = 0, int disp = 0,
                             int maxit = 300);
 
@@ -3733,7 +3739,8 @@
                             ComplexColumnVector &eig_val,
                             const SparseMatrix& b,
                             ColumnVector &permB, ColumnVector &resid,
-                            std::ostream &os, double tol = DBL_EPSILON,
+                            std::ostream &os,
+                            double tol = std::numeric_limits<double>::epsilon (),
                             bool rvec = false, bool cholB = 0, int disp = 0,
                             int maxit = 300);
 
@@ -3744,7 +3751,8 @@
                                  ComplexMatrix &eig_vec,
                                  ComplexColumnVector &eig_val, const Matrix& b,
                                  ColumnVector &permB, ColumnVector &resid,
-                                 std::ostream &os, double tol = DBL_EPSILON,
+                                 std::ostream &os,
+                                 double tol = std::numeric_limits<double>::epsilon (),
                                  bool rvec = false, bool cholB = 0,
                                  int disp = 0, int maxit = 300);
 
@@ -3756,7 +3764,8 @@
                                  ComplexColumnVector &eig_val,
                                  const SparseMatrix& b,
                                  ColumnVector &permB, ColumnVector &resid,
-                                 std::ostream &os, double tol = DBL_EPSILON,
+                                 std::ostream &os,
+                                 double tol = std::numeric_limits<double>::epsilon (),
                                  bool rvec = false, bool cholB = 0,
                                  int disp = 0, int maxit = 300);
 
@@ -3767,8 +3776,9 @@
                           octave_idx_type &info, ComplexMatrix &eig_vec,
                           ComplexColumnVector &eig_val,
                           ColumnVector &resid, std::ostream& os,
-                          double tol = DBL_EPSILON, bool rvec = false,
-                          bool cholB = 0, int disp = 0, int maxit = 300);
+                          double tol = std::numeric_limits<double>::epsilon (),
+                          bool rvec = false, bool cholB = 0, int disp = 0,
+                          int maxit = 300);
 
 extern octave_idx_type
 EigsComplexNonSymmetricMatrix (const ComplexMatrix& m, const std::string typ,
@@ -3777,7 +3787,8 @@
                                ComplexColumnVector &eig_val,
                                const ComplexMatrix& b, ColumnVector &permB,
                                ComplexColumnVector &resid,
-                               std::ostream &os, double tol = DBL_EPSILON,
+                               std::ostream &os,
+                               double tol = std::numeric_limits<double>::epsilon (),
                                bool rvec = false, bool cholB = 0, int disp = 0,
                                int maxit = 300);
 
@@ -3790,7 +3801,8 @@
                                const SparseComplexMatrix& b,
                                ColumnVector &permB,
                                ComplexColumnVector &resid,
-                               std::ostream &os, double tol = DBL_EPSILON,
+                               std::ostream &os,
+                               double tol = std::numeric_limits<double>::epsilon (),
                                bool rvec = false, bool cholB = 0, int disp = 0,
                                int maxit = 300);
 
@@ -3803,7 +3815,8 @@
                                     const ComplexMatrix& b,
                                     ColumnVector &permB,
                                     ComplexColumnVector &resid,
-                                    std::ostream &os, double tol = DBL_EPSILON,
+                                    std::ostream &os,
+                                    double tol = std::numeric_limits<double>::epsilon (),
                                     bool rvec = false, bool cholB = 0,
                                     int disp = 0, int maxit = 300);
 
@@ -3817,7 +3830,8 @@
                                     const SparseComplexMatrix& b,
                                     ColumnVector &permB,
                                     ComplexColumnVector &resid,
-                                    std::ostream &os, double tol = DBL_EPSILON,
+                                    std::ostream &os,
+                                    double tol = std::numeric_limits<double>::epsilon (),
                                     bool rvec = false, bool cholB = 0,
                                     int disp = 0, int maxit = 300);
 
@@ -3828,48 +3842,49 @@
                              octave_idx_type &info, ComplexMatrix &eig_vec,
                              ComplexColumnVector &eig_val,
                              ComplexColumnVector &resid, std::ostream& os,
-                             double tol = DBL_EPSILON, bool rvec = false,
-                             bool cholB = 0, int disp = 0, int maxit = 300);
+                             double tol = std::numeric_limits<double>::epsilon (),
+                             bool rvec = false, bool cholB = 0,
+                             int disp = 0, int maxit = 300);
 #endif
 
 #ifndef _MSC_VER
-template static octave_idx_type
+template octave_idx_type
 lusolve (const SparseMatrix&, const SparseMatrix&, Matrix&);
 
-template static octave_idx_type
+template octave_idx_type
 lusolve (const SparseComplexMatrix&, const SparseComplexMatrix&,
          ComplexMatrix&);
 
-template static octave_idx_type
+template octave_idx_type
 lusolve (const Matrix&, const Matrix&, Matrix&);
 
-template static octave_idx_type
+template octave_idx_type
 lusolve (const ComplexMatrix&, const ComplexMatrix&, ComplexMatrix&);
 
-template static ComplexMatrix
+template ComplexMatrix
 ltsolve (const SparseComplexMatrix&, const ColumnVector&,
          const ComplexMatrix&);
 
-template static Matrix
+template Matrix
 ltsolve (const SparseMatrix&, const ColumnVector&, const Matrix&);
 
-template static ComplexMatrix
+template ComplexMatrix
 ltsolve (const ComplexMatrix&, const ColumnVector&, const ComplexMatrix&);
 
-template static Matrix
+template Matrix
 ltsolve (const Matrix&, const ColumnVector&, const Matrix&);
 
-template static ComplexMatrix
+template ComplexMatrix
 utsolve (const SparseComplexMatrix&, const ColumnVector&,
          const ComplexMatrix&);
 
-template static Matrix
+template Matrix
 utsolve (const SparseMatrix&, const ColumnVector&, const Matrix&);
 
-template static ComplexMatrix
+template ComplexMatrix
 utsolve (const ComplexMatrix&, const ColumnVector&, const ComplexMatrix&);
 
-template static Matrix
+template Matrix
 utsolve (const Matrix&, const ColumnVector&, const Matrix&);
 #endif
 
rename from liboctave/fCmplxAEPBAL.cc
rename to liboctave/numeric/fCmplxAEPBAL.cc
rename from liboctave/fCmplxAEPBAL.h
rename to liboctave/numeric/fCmplxAEPBAL.h
rename from liboctave/fCmplxCHOL.cc
rename to liboctave/numeric/fCmplxCHOL.cc
rename from liboctave/fCmplxCHOL.h
rename to liboctave/numeric/fCmplxCHOL.h
rename from liboctave/fCmplxGEPBAL.cc
rename to liboctave/numeric/fCmplxGEPBAL.cc
--- a/liboctave/fCmplxGEPBAL.cc
+++ b/liboctave/numeric/fCmplxGEPBAL.cc
@@ -69,7 +69,7 @@
       return -1;
     }
 
-  if (a.dims() != b.dims ())
+  if (a.dims () != b.dims ())
     {
       gripe_nonconformant ("FloatComplexGEPBALANCE", n, n, b.rows(), b.cols());
       return -1;
rename from liboctave/fCmplxGEPBAL.h
rename to liboctave/numeric/fCmplxGEPBAL.h
rename from liboctave/fCmplxHESS.cc
rename to liboctave/numeric/fCmplxHESS.cc
rename from liboctave/fCmplxHESS.h
rename to liboctave/numeric/fCmplxHESS.h
rename from liboctave/fCmplxLU.cc
rename to liboctave/numeric/fCmplxLU.cc
--- a/liboctave/fCmplxLU.cc
+++ b/liboctave/numeric/fCmplxLU.cc
@@ -33,8 +33,8 @@
 
 // Instantiate the base LU class for the types we need.
 
-#include <base-lu.h>
-#include <base-lu.cc>
+#include "base-lu.h"
+#include "base-lu.cc"
 
 template class base_lu <FloatComplexMatrix>;
 
rename from liboctave/fCmplxLU.h
rename to liboctave/numeric/fCmplxLU.h
rename from liboctave/fCmplxQR.cc
rename to liboctave/numeric/fCmplxQR.cc
--- a/liboctave/fCmplxQR.cc
+++ b/liboctave/numeric/fCmplxQR.cc
@@ -471,7 +471,7 @@
 
   if (u.length () == m && v.length () == n)
     {
-      init(q*r + FloatComplexMatrix (u) * FloatComplexMatrix (v).hermitian (), get_type ());
+      init (q*r + FloatComplexMatrix (u) * FloatComplexMatrix (v).hermitian (), get_type ());
     }
   else
     (*current_liboctave_error_handler) ("qrupdate: dimensions mismatch");
@@ -487,7 +487,7 @@
 
   if (u.rows () == m && v.rows () == n && u.cols () == v.cols ())
     {
-      init(q*r + u * v.hermitian (), get_type ());
+      init (q*r + u * v.hermitian (), get_type ());
     }
   else
     (*current_liboctave_error_handler) ("qrupdate: dimensions mismatch");
rename from liboctave/fCmplxQR.h
rename to liboctave/numeric/fCmplxQR.h
rename from liboctave/fCmplxQRP.cc
rename to liboctave/numeric/fCmplxQRP.cc
rename from liboctave/fCmplxQRP.h
rename to liboctave/numeric/fCmplxQRP.h
rename from liboctave/fCmplxSCHUR.cc
rename to liboctave/numeric/fCmplxSCHUR.cc
rename from liboctave/fCmplxSCHUR.h
rename to liboctave/numeric/fCmplxSCHUR.h
rename from liboctave/fCmplxSVD.cc
rename to liboctave/numeric/fCmplxSVD.cc
rename from liboctave/fCmplxSVD.h
rename to liboctave/numeric/fCmplxSVD.h
rename from liboctave/fEIG.cc
rename to liboctave/numeric/fEIG.cc
--- a/liboctave/fEIG.cc
+++ b/liboctave/numeric/fEIG.cc
@@ -226,8 +226,8 @@
                   return -1;
                 }
 
-              lambda.elem(j) = FloatComplex (wr.elem(j), wi.elem(j));
-              lambda.elem(j+1) = FloatComplex (wr.elem(j+1), wi.elem(j+1));
+              lambda.elem (j) = FloatComplex (wr.elem (j), wi.elem (j));
+              lambda.elem (j+1) = FloatComplex (wr.elem (j+1), wi.elem (j+1));
 
               for (octave_idx_type i = 0; i < nvr; i++)
                 {
@@ -576,10 +576,10 @@
                   return -1;
                 }
 
-              lambda.elem(j) = FloatComplex (ar.elem(j) / beta.elem (j),
-                                             ai.elem(j) / beta.elem (j));
-              lambda.elem(j+1) = FloatComplex (ar.elem(j+1) / beta.elem (j+1),
-                                               ai.elem(j+1) / beta.elem (j+1));
+              lambda.elem (j) = FloatComplex (ar.elem (j) / beta.elem (j),
+                                              ai.elem (j) / beta.elem (j));
+              lambda.elem (j+1) = FloatComplex (ar.elem (j+1) / beta.elem (j+1),
+                                                ai.elem (j+1) / beta.elem (j+1));
 
               for (octave_idx_type i = 0; i < nvr; i++)
                 {
@@ -686,7 +686,7 @@
   octave_idx_type n = a.rows ();
   octave_idx_type nb = b.rows ();
 
-  if (n != a.cols () || nb != b.cols())
+  if (n != a.cols () || nb != b.cols ())
     {
       (*current_liboctave_error_handler) ("EIG requires square matrix");
       return -1;
@@ -775,7 +775,7 @@
       lambda.resize (n);
 
       for (octave_idx_type j = 0; j < n; j++)
-        lambda.elem (j) = alpha.elem (j) / beta.elem(j);
+        lambda.elem (j) = alpha.elem (j) / beta.elem (j);
 
       v = vtmp;
     }
rename from liboctave/fEIG.h
rename to liboctave/numeric/fEIG.h
rename from liboctave/floatAEPBAL.cc
rename to liboctave/numeric/floatAEPBAL.cc
rename from liboctave/floatAEPBAL.h
rename to liboctave/numeric/floatAEPBAL.h
rename from liboctave/floatCHOL.cc
rename to liboctave/numeric/floatCHOL.cc
--- a/liboctave/floatCHOL.cc
+++ b/liboctave/numeric/floatCHOL.cc
@@ -157,7 +157,7 @@
       octave_idx_type info = 0;
 
       FloatMatrix tmp = r;
-      float *v = tmp.fortran_vec();
+      float *v = tmp.fortran_vec ();
 
       if (info == 0)
         {
rename from liboctave/floatCHOL.h
rename to liboctave/numeric/floatCHOL.h
rename from liboctave/floatGEPBAL.cc
rename to liboctave/numeric/floatGEPBAL.cc
--- a/liboctave/floatGEPBAL.cc
+++ b/liboctave/numeric/floatGEPBAL.cc
@@ -70,7 +70,7 @@
       return -1;
     }
 
-  if (a.dims() != b.dims ())
+  if (a.dims () != b.dims ())
     {
       gripe_nonconformant ("FloatGEPBALANCE", n, n, b.rows(), b.cols());
       return -1;
rename from liboctave/floatGEPBAL.h
rename to liboctave/numeric/floatGEPBAL.h
rename from liboctave/floatHESS.cc
rename to liboctave/numeric/floatHESS.cc
rename from liboctave/floatHESS.h
rename to liboctave/numeric/floatHESS.h
rename from liboctave/floatLU.cc
rename to liboctave/numeric/floatLU.cc
--- a/liboctave/floatLU.cc
+++ b/liboctave/numeric/floatLU.cc
@@ -33,8 +33,8 @@
 
 // Instantiate the base LU class for the types we need.
 
-#include <base-lu.h>
-#include <base-lu.cc>
+#include "base-lu.h"
+#include "base-lu.cc"
 
 template class base_lu <FloatMatrix>;
 
rename from liboctave/floatLU.h
rename to liboctave/numeric/floatLU.h
rename from liboctave/floatQR.cc
rename to liboctave/numeric/floatQR.cc
--- a/liboctave/floatQR.cc
+++ b/liboctave/numeric/floatQR.cc
@@ -464,7 +464,7 @@
 
   if (u.length () == m && v.length () == n)
     {
-      init(q*r + FloatMatrix (u) * FloatMatrix (v).transpose (), get_type ());
+      init (q*r + FloatMatrix (u) * FloatMatrix (v).transpose (), get_type ());
     }
   else
     (*current_liboctave_error_handler) ("qrupdate: dimensions mismatch");
@@ -480,7 +480,7 @@
 
   if (u.rows () == m && v.rows () == n && u.cols () == v.cols ())
     {
-      init(q*r + u * v.transpose (), get_type ());
+      init (q*r + u * v.transpose (), get_type ());
     }
   else
     (*current_liboctave_error_handler) ("qrupdate: dimensions mismatch");
rename from liboctave/floatQR.h
rename to liboctave/numeric/floatQR.h
rename from liboctave/floatQRP.cc
rename to liboctave/numeric/floatQRP.cc
rename from liboctave/floatQRP.h
rename to liboctave/numeric/floatQRP.h
rename from liboctave/floatSCHUR.cc
rename to liboctave/numeric/floatSCHUR.cc
rename from liboctave/floatSCHUR.h
rename to liboctave/numeric/floatSCHUR.h
rename from liboctave/floatSVD.cc
rename to liboctave/numeric/floatSVD.cc
--- a/liboctave/floatSVD.cc
+++ b/liboctave/numeric/floatSVD.cc
@@ -134,7 +134,7 @@
   float *u = left_sm.fortran_vec ();
 
   sigma.resize (nrow_s, ncol_s);
-  float *s_vec  = sigma.fortran_vec ();
+  float *s_vec = sigma.fortran_vec ();
 
   if (! (jobv == 'N' || jobv == 'O'))
     right_sm.resize (nrow_vt, n);
rename from liboctave/floatSVD.h
rename to liboctave/numeric/floatSVD.h
rename from liboctave/lo-mappers.cc
rename to liboctave/numeric/lo-mappers.cc
--- a/liboctave/lo-mappers.cc
+++ b/liboctave/numeric/lo-mappers.cc
@@ -279,10 +279,15 @@
   return gnulib::copysignf (x, y);
 }
 
+float xfloor (float x)
+{
+  return gnulib::floorf (x);
+}
+
 float
 xround (float x)
 {
-  return gnulib::round (x);
+  return gnulib::roundf (x);
 }
 
 float
@@ -312,7 +317,9 @@
 float
 xlog2 (float x)
 {
-#if defined (HAVE_LOG2)
+#if defined (HAVE_LOG2F)
+  return log2f (x);
+#elif defined (HAVE_LOG2)
   return log2 (x);
 #else
 #if defined (M_LN2)
@@ -340,7 +347,9 @@
 float
 xexp2 (float x)
 {
-#if defined (HAVE_EXP2)
+#if defined (HAVE_EXP2F)
+  return exp2f (x);
+#elif defined (HAVE_EXP2)
   return exp2 (x);
 #else
 #if defined (M_LN2)
rename from liboctave/lo-mappers.h
rename to liboctave/numeric/lo-mappers.h
--- a/liboctave/lo-mappers.h
+++ b/liboctave/numeric/lo-mappers.h
@@ -119,7 +119,7 @@
 extern OCTAVE_API float xtrunc (float x);
 extern OCTAVE_API float xcopysign (float x, float y);
 inline float xceil (float x) { return ceilf (x); }
-inline float xfloor (float x) { return floorf (x); }
+extern OCTAVE_API float xfloor (float x);
 inline float arg (float x) { return atan2f (0.0f, x); }
 inline float conj (float x) { return x; }
 inline float fix (float x) { return xtrunc (x); }
@@ -401,4 +401,11 @@
   return retval;
 }
 
+template <typename T>
+T
+xsignbit (T x)
+{
+  return signbit (x);
+}
+
 #endif
rename from liboctave/lo-specfun.cc
rename to liboctave/numeric/lo-specfun.cc
--- a/liboctave/lo-specfun.cc
+++ b/liboctave/numeric/lo-specfun.cc
@@ -46,9 +46,7 @@
 #include "mx-inlines.cc"
 #include "lo-mappers.h"
 
-#ifndef M_PI
-#define M_PI 3.14159265358979323846
-#endif
+#include "Faddeeva.hh"
 
 extern "C"
 {
@@ -287,6 +285,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)
 {
@@ -454,13 +528,13 @@
 #endif
 
 Complex
-expm1(const Complex& x)
+expm1 (const Complex& x)
 {
   Complex retval;
 
   if (std:: abs (x) < 1)
     {
-      double im = x.imag();
+      double im = x.imag ();
       double u = expm1 (x.real ());
       double v = sin (im/2);
       v = -2*v*v;
@@ -509,13 +583,13 @@
 #endif
 
 FloatComplex
-expm1(const FloatComplex& x)
+expm1 (const FloatComplex& x)
 {
   FloatComplex retval;
 
   if (std:: abs (x) < 1)
     {
-      float im = x.imag();
+      float im = x.imag ();
       float u = expm1 (x.real ());
       float v = sin (im/2);
       v = -2*v*v;
@@ -556,7 +630,7 @@
 {
   Complex retval;
 
-  double r = x.real (), i = x.imag();
+  double r = x.real (), i = x.imag ();
 
   if (fabs (r) < 0.5 && fabs (i) < 0.5)
     {
@@ -565,7 +639,7 @@
                         atan2 (1 + r, i));
     }
   else
-    retval = std::log (Complex(1) + x);
+    retval = std::log (Complex (1) + x);
 
   return retval;
 }
@@ -615,7 +689,7 @@
 {
   FloatComplex retval;
 
-  float r = x.real (), i = x.imag();
+  float r = x.real (), i = x.imag ();
 
   if (fabs (r) < 0.5 && fabs (i) < 0.5)
     {
@@ -624,7 +698,7 @@
                         atan2 (1 + r, i));
     }
   else
-    retval = std::log (FloatComplex(1) + x);
+    retval = std::log (FloatComplex (1) + x);
 
   return retval;
 }
@@ -873,7 +947,7 @@
           if (kode == 2)
             {
               // Compensate for different scaling factor of besk.
-              tmp2 *= exp(-z - std::abs(z.real()));
+              tmp2 *= exp (-z - std::abs (z.real ()));
             }
 
           tmp += tmp2;
@@ -1483,7 +1557,7 @@
           if (kode == 2)
             {
               // Compensate for different scaling factor of besk.
-              tmp2 *= exp(-z - std::abs(z.real()));
+              tmp2 *= exp (-z - std::abs (z.real ()));
             }
 
           tmp += tmp2;
@@ -1893,7 +1967,7 @@
 
   if (! scaled)
     {
-      Complex expz = exp (- 2.0 / 3.0 * z * sqrt(z));
+      Complex expz = exp (- 2.0 / 3.0 * z * sqrt (z));
 
       double rexpz = real (expz);
       double iexpz = imag (expz);
@@ -1986,7 +2060,7 @@
   ierr.resize (dv);
 
   for (octave_idx_type i = 0; i < nel; i++)
-    retval (i) = airy (z(i), deriv, scaled, ierr(i));
+    retval(i) = airy (z(i), deriv, scaled, ierr(i));
 
   return retval;
 }
@@ -2001,7 +2075,7 @@
   ierr.resize (dv);
 
   for (octave_idx_type i = 0; i < nel; i++)
-    retval (i) = biry (z(i), deriv, scaled, ierr(i));
+    retval(i) = biry (z(i), deriv, scaled, ierr(i));
 
   return retval;
 }
@@ -2023,7 +2097,7 @@
 
   if (! scaled)
     {
-      FloatComplex expz = exp (- static_cast<float> (2.0 / 3.0) * z * sqrt(z));
+      FloatComplex expz = exp (- static_cast<float> (2.0 / 3.0) * z * sqrt (z));
 
       float rexpz = real (expz);
       float iexpz = imag (expz);
@@ -2116,7 +2190,7 @@
   ierr.resize (dv);
 
   for (octave_idx_type i = 0; i < nel; i++)
-    retval (i) = airy (z(i), deriv, scaled, ierr(i));
+    retval(i) = airy (z(i), deriv, scaled, ierr(i));
 
   return retval;
 }
@@ -2131,21 +2205,12 @@
   ierr.resize (dv);
 
   for (octave_idx_type i = 0; i < nel; i++)
-    retval (i) = biry (z(i), deriv, scaled, ierr(i));
+    retval(i) = biry (z(i), deriv, scaled, ierr(i));
 
   return retval;
 }
 
 static void
-gripe_betainc_nonconformant (octave_idx_type r1, octave_idx_type c1, octave_idx_type r2, octave_idx_type c2, octave_idx_type r3,
-                             octave_idx_type c3)
-{
-  (*current_liboctave_error_handler)
-   ("betainc: nonconformant arguments (x is %dx%d, a is %dx%d, b is %dx%d)",
-     r1, c1, r2, c2, r3, c3);
-}
-
-static void
 gripe_betainc_nonconformant (const dim_vector& d1, const dim_vector& d2,
                              const dim_vector& d3)
 {
@@ -2158,6 +2223,19 @@
    d1_str.c_str (), d2_str.c_str (), d3_str.c_str ());
 }
 
+static void
+gripe_betaincinv_nonconformant (const dim_vector& d1, const dim_vector& d2,
+                                const dim_vector& d3)
+{
+  std::string d1_str = d1.str ();
+  std::string d2_str = d2.str ();
+  std::string d3_str = d3.str ();
+
+  (*current_liboctave_error_handler)
+  ("betaincinv: nonconformant arguments (x is %s, a is %s, b is %s)",
+   d1_str.c_str (), d2_str.c_str (), d3_str.c_str ());
+}
+
 double
 betainc (double x, double a, double b)
 {
@@ -2166,93 +2244,42 @@
   return retval;
 }
 
-Matrix
-betainc (double x, double a, const Matrix& b)
+Array<double>
+betainc (double x, double a, const Array<double>& b)
 {
-  octave_idx_type nr = b.rows ();
-  octave_idx_type nc = b.cols ();
-
-  Matrix retval (nr, nc);
-
-  for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = 0; i < nr; i++)
-      retval(i,j) = betainc (x, a, b(i,j));
-
-  return retval;
-}
-
-Matrix
-betainc (double x, const Matrix& a, double b)
-{
-  octave_idx_type nr = a.rows ();
-  octave_idx_type nc = a.cols ();
-
-  Matrix retval (nr, nc);
-
-  for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = 0; i < nr; i++)
-      retval(i,j) = betainc (x, a(i,j), b);
+  dim_vector dv = b.dims ();
+  octave_idx_type nel = dv.numel ();
+
+  Array<double> retval (dv);
+
+  double *pretval = retval.fortran_vec ();
+
+  for (octave_idx_type i = 0; i < nel; i++)
+    *pretval++ = betainc (x, a, b(i));
 
   return retval;
 }
 
-Matrix
-betainc (double x, const Matrix& a, const Matrix& b)
+Array<double>
+betainc (double x, const Array<double>& a, double b)
 {
-  Matrix retval;
-
-  octave_idx_type a_nr = a.rows ();
-  octave_idx_type a_nc = a.cols ();
-
-  octave_idx_type b_nr = b.rows ();
-  octave_idx_type b_nc = b.cols ();
-
-  if (a_nr == b_nr && a_nc == b_nc)
-    {
-      retval.resize (a_nr, a_nc);
-
-      for (octave_idx_type j = 0; j < a_nc; j++)
-        for (octave_idx_type i = 0; i < a_nr; i++)
-          retval(i,j) = betainc (x, a(i,j), b(i,j));
-    }
-  else
-    gripe_betainc_nonconformant (1, 1, a_nr, a_nc, b_nr, b_nc);
+  dim_vector dv = a.dims ();
+  octave_idx_type nel = dv.numel ();
+
+  Array<double> retval (dv);
+
+  double *pretval = retval.fortran_vec ();
+
+  for (octave_idx_type i = 0; i < nel; i++)
+    *pretval++ = betainc (x, a(i), b);
 
   return retval;
 }
 
-NDArray
-betainc (double x, double a, const NDArray& b)
+Array<double>
+betainc (double x, const Array<double>& a, const Array<double>& b)
 {
-  dim_vector dv = b.dims ();
-  octave_idx_type nel = dv.numel ();
-
-  NDArray retval (dv);
-
-  for (octave_idx_type i = 0; i < nel; i++)
-    retval (i) = betainc (x, a, b(i));
-
-  return retval;
-}
-
-NDArray
-betainc (double x, const NDArray& a, double b)
-{
-  dim_vector dv = a.dims ();
-  octave_idx_type nel = dv.numel ();
-
-  NDArray retval (dv);
-
-  for (octave_idx_type i = 0; i < nel; i++)
-    retval (i) = betainc (x, a(i), b);
-
-  return retval;
-}
-
-NDArray
-betainc (double x, const NDArray& a, const NDArray& b)
-{
-  NDArray retval;
+  Array<double> retval;
   dim_vector dv = a.dims ();
 
   if (dv == b.dims ())
@@ -2261,8 +2288,10 @@
 
       retval.resize (dv);
 
+      double *pretval = retval.fortran_vec ();
+
       for (octave_idx_type i = 0; i < nel; i++)
-        retval (i) = betainc (x, a(i), b(i));
+        *pretval++ = betainc (x, a(i), b(i));
     }
   else
     gripe_betainc_nonconformant (dim_vector (0, 0), dv, b.dims ());
@@ -2270,118 +2299,26 @@
   return retval;
 }
 
-
-Matrix
-betainc (const Matrix& x, double a, double b)
-{
-  octave_idx_type nr = x.rows ();
-  octave_idx_type nc = x.cols ();
-
-  Matrix retval (nr, nc);
-
-  for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = 0; i < nr; i++)
-      retval(i,j) = betainc (x(i,j), a, b);
-
-  return retval;
-}
-
-Matrix
-betainc (const Matrix& x, double a, const Matrix& b)
+Array<double>
+betainc (const Array<double>& x, double a, double b)
 {
-  Matrix retval;
-
-  octave_idx_type nr = x.rows ();
-  octave_idx_type nc = x.cols ();
-
-  octave_idx_type b_nr = b.rows ();
-  octave_idx_type b_nc = b.cols ();
-
-  if (nr == b_nr && nc == b_nc)
-    {
-      retval.resize (nr, nc);
-
-      for (octave_idx_type j = 0; j < nc; j++)
-        for (octave_idx_type i = 0; i < nr; i++)
-          retval(i,j) = betainc (x(i,j), a, b(i,j));
-    }
-  else
-    gripe_betainc_nonconformant (nr, nc, 1, 1, b_nr, b_nc);
+  dim_vector dv = x.dims ();
+  octave_idx_type nel = dv.numel ();
+
+  Array<double> retval (dv);
+
+  double *pretval = retval.fortran_vec ();
+
+  for (octave_idx_type i = 0; i < nel; i++)
+    *pretval++ = betainc (x(i), a, b);
 
   return retval;
 }
 
-Matrix
-betainc (const Matrix& x, const Matrix& a, double b)
-{
-  Matrix retval;
-
-  octave_idx_type nr = x.rows ();
-  octave_idx_type nc = x.cols ();
-
-  octave_idx_type a_nr = a.rows ();
-  octave_idx_type a_nc = a.cols ();
-
-  if (nr == a_nr && nc == a_nc)
-    {
-      retval.resize (nr, nc);
-
-      for (octave_idx_type j = 0; j < nc; j++)
-        for (octave_idx_type i = 0; i < nr; i++)
-          retval(i,j) = betainc (x(i,j), a(i,j), b);
-    }
-  else
-    gripe_betainc_nonconformant (nr, nc, a_nr, a_nc, 1, 1);
-
-  return retval;
-}
-
-Matrix
-betainc (const Matrix& x, const Matrix& a, const Matrix& b)
+Array<double>
+betainc (const Array<double>& x, double a, const Array<double>& b)
 {
-  Matrix retval;
-
-  octave_idx_type nr = x.rows ();
-  octave_idx_type nc = x.cols ();
-
-  octave_idx_type a_nr = a.rows ();
-  octave_idx_type a_nc = a.cols ();
-
-  octave_idx_type b_nr = b.rows ();
-  octave_idx_type b_nc = b.cols ();
-
-  if (nr == a_nr && nr == b_nr && nc == a_nc && nc == b_nc)
-    {
-      retval.resize (nr, nc);
-
-      for (octave_idx_type j = 0; j < nc; j++)
-        for (octave_idx_type i = 0; i < nr; i++)
-          retval(i,j) = betainc (x(i,j), a(i,j), b(i,j));
-    }
-  else
-    gripe_betainc_nonconformant (nr, nc, a_nr, a_nc, b_nr, b_nc);
-
-  return retval;
-}
-
-NDArray
-betainc (const NDArray& x, double a, double b)
-{
-  dim_vector dv = x.dims ();
-  octave_idx_type nel = dv.numel ();
-
-  NDArray retval (dv);
-
-  for (octave_idx_type i = 0; i < nel; i++)
-    retval (i) = betainc (x(i), a, b);
-
-  return retval;
-}
-
-NDArray
-betainc (const NDArray& x, double a, const NDArray& b)
-{
-  NDArray retval;
+  Array<double> retval;
   dim_vector dv = x.dims ();
 
   if (dv == b.dims ())
@@ -2390,8 +2327,10 @@
 
       retval.resize (dv);
 
+      double *pretval = retval.fortran_vec ();
+
       for (octave_idx_type i = 0; i < nel; i++)
-        retval (i) = betainc (x(i), a, b(i));
+        *pretval++ = betainc (x(i), a, b(i));
     }
   else
     gripe_betainc_nonconformant (dv, dim_vector (0, 0), b.dims ());
@@ -2399,10 +2338,10 @@
   return retval;
 }
 
-NDArray
-betainc (const NDArray& x, const NDArray& a, double b)
+Array<double>
+betainc (const Array<double>& x, const Array<double>& a, double b)
 {
-  NDArray retval;
+  Array<double> retval;
   dim_vector dv = x.dims ();
 
   if (dv == a.dims ())
@@ -2411,8 +2350,10 @@
 
       retval.resize (dv);
 
+      double *pretval = retval.fortran_vec ();
+
       for (octave_idx_type i = 0; i < nel; i++)
-        retval (i) = betainc (x(i), a(i), b);
+        *pretval++ = betainc (x(i), a(i), b);
     }
   else
     gripe_betainc_nonconformant (dv, a.dims (), dim_vector (0, 0));
@@ -2420,10 +2361,10 @@
   return retval;
 }
 
-NDArray
-betainc (const NDArray& x, const NDArray& a, const NDArray& b)
+Array<double>
+betainc (const Array<double>& x, const Array<double>& a, const Array<double>& b)
 {
-  NDArray retval;
+  Array<double> retval;
   dim_vector dv = x.dims ();
 
   if (dv == a.dims () && dv == b.dims ())
@@ -2432,8 +2373,10 @@
 
       retval.resize (dv);
 
+      double *pretval = retval.fortran_vec ();
+
       for (octave_idx_type i = 0; i < nel; i++)
-        retval (i) = betainc (x(i), a(i), b(i));
+        *pretval++ = betainc (x(i), a(i), b(i));
     }
   else
     gripe_betainc_nonconformant (dv, a.dims (), b.dims ());
@@ -2449,93 +2392,42 @@
   return retval;
 }
 
-FloatMatrix
-betainc (float x, float a, const FloatMatrix& b)
+Array<float>
+betainc (float x, float a, const Array<float>& b)
 {
-  octave_idx_type nr = b.rows ();
-  octave_idx_type nc = b.cols ();
-
-  FloatMatrix retval (nr, nc);
-
-  for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = 0; i < nr; i++)
-      retval(i,j) = betainc (x, a, b(i,j));
-
-  return retval;
-}
-
-FloatMatrix
-betainc (float x, const FloatMatrix& a, float b)
-{
-  octave_idx_type nr = a.rows ();
-  octave_idx_type nc = a.cols ();
-
-  FloatMatrix retval (nr, nc);
-
-  for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = 0; i < nr; i++)
-      retval(i,j) = betainc (x, a(i,j), b);
+  dim_vector dv = b.dims ();
+  octave_idx_type nel = dv.numel ();
+
+  Array<float> retval (dv);
+
+  float *pretval = retval.fortran_vec ();
+
+  for (octave_idx_type i = 0; i < nel; i++)
+    *pretval++ = betainc (x, a, b(i));
 
   return retval;
 }
 
-FloatMatrix
-betainc (float x, const FloatMatrix& a, const FloatMatrix& b)
+Array<float>
+betainc (float x, const Array<float>& a, float b)
 {
-  FloatMatrix retval;
-
-  octave_idx_type a_nr = a.rows ();
-  octave_idx_type a_nc = a.cols ();
-
-  octave_idx_type b_nr = b.rows ();
-  octave_idx_type b_nc = b.cols ();
-
-  if (a_nr == b_nr && a_nc == b_nc)
-    {
-      retval.resize (a_nr, a_nc);
-
-      for (octave_idx_type j = 0; j < a_nc; j++)
-        for (octave_idx_type i = 0; i < a_nr; i++)
-          retval(i,j) = betainc (x, a(i,j), b(i,j));
-    }
-  else
-    gripe_betainc_nonconformant (1, 1, a_nr, a_nc, b_nr, b_nc);
+  dim_vector dv = a.dims ();
+  octave_idx_type nel = dv.numel ();
+
+  Array<float> retval (dv);
+
+  float *pretval = retval.fortran_vec ();
+
+  for (octave_idx_type i = 0; i < nel; i++)
+    *pretval++ = betainc (x, a(i), b);
 
   return retval;
 }
 
-FloatNDArray
-betainc (float x, float a, const FloatNDArray& b)
+Array<float>
+betainc (float x, const Array<float>& a, const Array<float>& b)
 {
-  dim_vector dv = b.dims ();
-  octave_idx_type nel = dv.numel ();
-
-  FloatNDArray retval (dv);
-
-  for (octave_idx_type i = 0; i < nel; i++)
-    retval (i) = betainc (x, a, b(i));
-
-  return retval;
-}
-
-FloatNDArray
-betainc (float x, const FloatNDArray& a, float b)
-{
-  dim_vector dv = a.dims ();
-  octave_idx_type nel = dv.numel ();
-
-  FloatNDArray retval (dv);
-
-  for (octave_idx_type i = 0; i < nel; i++)
-    retval (i) = betainc (x, a(i), b);
-
-  return retval;
-}
-
-FloatNDArray
-betainc (float x, const FloatNDArray& a, const FloatNDArray& b)
-{
-  FloatNDArray retval;
+  Array<float> retval;
   dim_vector dv = a.dims ();
 
   if (dv == b.dims ())
@@ -2544,8 +2436,10 @@
 
       retval.resize (dv);
 
+      float *pretval = retval.fortran_vec ();
+
       for (octave_idx_type i = 0; i < nel; i++)
-        retval (i) = betainc (x, a(i), b(i));
+        *pretval++ = betainc (x, a(i), b(i));
     }
   else
     gripe_betainc_nonconformant (dim_vector (0, 0), dv, b.dims ());
@@ -2553,118 +2447,26 @@
   return retval;
 }
 
-
-FloatMatrix
-betainc (const FloatMatrix& x, float a, float b)
-{
-  octave_idx_type nr = x.rows ();
-  octave_idx_type nc = x.cols ();
-
-  FloatMatrix retval (nr, nc);
-
-  for (octave_idx_type j = 0; j < nc; j++)
-    for (octave_idx_type i = 0; i < nr; i++)
-      retval(i,j) = betainc (x(i,j), a, b);
-
-  return retval;
-}
-
-FloatMatrix
-betainc (const FloatMatrix& x, float a, const FloatMatrix& b)
+Array<float>
+betainc (const Array<float>& x, float a, float b)
 {
-  FloatMatrix retval;
-
-  octave_idx_type nr = x.rows ();
-  octave_idx_type nc = x.cols ();
-
-  octave_idx_type b_nr = b.rows ();
-  octave_idx_type b_nc = b.cols ();
-
-  if (nr == b_nr && nc == b_nc)
-    {
-      retval.resize (nr, nc);
-
-      for (octave_idx_type j = 0; j < nc; j++)
-        for (octave_idx_type i = 0; i < nr; i++)
-          retval(i,j) = betainc (x(i,j), a, b(i,j));
-    }
-  else
-    gripe_betainc_nonconformant (nr, nc, 1, 1, b_nr, b_nc);
+  dim_vector dv = x.dims ();
+  octave_idx_type nel = dv.numel ();
+
+  Array<float> retval (dv);
+
+  float *pretval = retval.fortran_vec ();
+
+  for (octave_idx_type i = 0; i < nel; i++)
+    *pretval++ = betainc (x(i), a, b);
 
   return retval;
 }
 
-FloatMatrix
-betainc (const FloatMatrix& x, const FloatMatrix& a, float b)
-{
-  FloatMatrix retval;
-
-  octave_idx_type nr = x.rows ();
-  octave_idx_type nc = x.cols ();
-
-  octave_idx_type a_nr = a.rows ();
-  octave_idx_type a_nc = a.cols ();
-
-  if (nr == a_nr && nc == a_nc)
-    {
-      retval.resize (nr, nc);
-
-      for (octave_idx_type j = 0; j < nc; j++)
-        for (octave_idx_type i = 0; i < nr; i++)
-          retval(i,j) = betainc (x(i,j), a(i,j), b);
-    }
-  else
-    gripe_betainc_nonconformant (nr, nc, a_nr, a_nc, 1, 1);
-
-  return retval;
-}
-
-FloatMatrix
-betainc (const FloatMatrix& x, const FloatMatrix& a, const FloatMatrix& b)
+Array<float>
+betainc (const Array<float>& x, float a, const Array<float>& b)
 {
-  FloatMatrix retval;
-
-  octave_idx_type nr = x.rows ();
-  octave_idx_type nc = x.cols ();
-
-  octave_idx_type a_nr = a.rows ();
-  octave_idx_type a_nc = a.cols ();
-
-  octave_idx_type b_nr = b.rows ();
-  octave_idx_type b_nc = b.cols ();
-
-  if (nr == a_nr && nr == b_nr && nc == a_nc && nc == b_nc)
-    {
-      retval.resize (nr, nc);
-
-      for (octave_idx_type j = 0; j < nc; j++)
-        for (octave_idx_type i = 0; i < nr; i++)
-          retval(i,j) = betainc (x(i,j), a(i,j), b(i,j));
-    }
-  else
-    gripe_betainc_nonconformant (nr, nc, a_nr, a_nc, b_nr, b_nc);
-
-  return retval;
-}
-
-FloatNDArray
-betainc (const FloatNDArray& x, float a, float b)
-{
-  dim_vector dv = x.dims ();
-  octave_idx_type nel = dv.numel ();
-
-  FloatNDArray retval (dv);
-
-  for (octave_idx_type i = 0; i < nel; i++)
-    retval (i) = betainc (x(i), a, b);
-
-  return retval;
-}
-
-FloatNDArray
-betainc (const FloatNDArray& x, float a, const FloatNDArray& b)
-{
-  FloatNDArray retval;
+  Array<float> retval;
   dim_vector dv = x.dims ();
 
   if (dv == b.dims ())
@@ -2673,8 +2475,10 @@
 
       retval.resize (dv);
 
+      float *pretval = retval.fortran_vec ();
+
       for (octave_idx_type i = 0; i < nel; i++)
-        retval (i) = betainc (x(i), a, b(i));
+        *pretval++ = betainc (x(i), a, b(i));
     }
   else
     gripe_betainc_nonconformant (dv, dim_vector (0, 0), b.dims ());
@@ -2682,10 +2486,10 @@
   return retval;
 }
 
-FloatNDArray
-betainc (const FloatNDArray& x, const FloatNDArray& a, float b)
+Array<float>
+betainc (const Array<float>& x, const Array<float>& a, float b)
 {
-  FloatNDArray retval;
+  Array<float> retval;
   dim_vector dv = x.dims ();
 
   if (dv == a.dims ())
@@ -2694,8 +2498,10 @@
 
       retval.resize (dv);
 
+      float *pretval = retval.fortran_vec ();
+
       for (octave_idx_type i = 0; i < nel; i++)
-        retval (i) = betainc (x(i), a(i), b);
+        *pretval++ = betainc (x(i), a(i), b);
     }
   else
     gripe_betainc_nonconformant (dv, a.dims (), dim_vector (0, 0));
@@ -2703,10 +2509,10 @@
   return retval;
 }
 
-FloatNDArray
-betainc (const FloatNDArray& x, const FloatNDArray& a, const FloatNDArray& b)
+Array<float>
+betainc (const Array<float>& x, const Array<float>& a, const Array<float>& b)
 {
-  FloatNDArray retval;
+  Array<float> retval;
   dim_vector dv = x.dims ();
 
   if (dv == a.dims () && dv == b.dims ())
@@ -2715,8 +2521,10 @@
 
       retval.resize (dv);
 
+      float *pretval = retval.fortran_vec ();
+
       for (octave_idx_type i = 0; i < nel; i++)
-        retval (i) = betainc (x(i), a(i), b(i));
+        *pretval++ = betainc (x(i), a(i), b(i));
     }
   else
     gripe_betainc_nonconformant (dv, a.dims (), b.dims ());
@@ -3128,7 +2936,7 @@
 
       (*current_liboctave_error_handler)
         ("gammainc: nonconformant arguments (arg 1 is %s, arg 2 is %s)",
-         x_str.c_str (), a_str. c_str ());
+         x_str.c_str (), a_str.c_str ());
     }
 
  done:
@@ -3152,7 +2960,7 @@
 // This algorithm is due to P. J. Acklam.
 // See http://home.online.no/~pjacklam/notes/invnorm/
 // The rational approximation has relative accuracy 1.15e-9 in the whole region.
-// For doubles, it is refined by a single step of Higham's 3rd order method.
+// For doubles, it is refined by a single step of Halley's 3rd order method.
 // For single precision, the accuracy is already OK, so we skip it to get
 // faster evaluation.
 
@@ -3175,7 +2983,7 @@
     {  7.784695709041462e-03,  3.224671290700398e-01,
        2.445134137142996e+00,  3.754408661907416e+00 };
 
-  static const double spi2 =  8.862269254527579e-01; // sqrt(pi)/2.
+  static const double spi2 = 8.862269254527579e-01; // sqrt(pi)/2.
   static const double pbreak = 0.95150;
   double ax = fabs (x), y;
 
@@ -3204,7 +3012,7 @@
   if (refine)
     {
       // One iteration of Halley's method gives full precision.
-      double u = (erf(y) - x) * spi2 * exp (y*y);
+      double u = (erf (y) - x) * spi2 * exp (y*y);
       y -= u / (1 + y*u);
     }
 
@@ -3221,102 +3029,542 @@
   return do_erfinv (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)
+// The algorthim for erfcinv is an adaptation of the erfinv algorithm above
+// from P. J. Acklam.  It has been modified to run over the different input
+// domain of erfcinv.  See the notes for erfinv for an explanation.
+
+static double do_erfcinv (double x, bool refine)
 {
-  static const T c[] =
+  // Coefficients of rational approximation.
+  static const double a[] =
+    { -2.806989788730439e+01,  1.562324844726888e+02,
+      -1.951109208597547e+02,  9.783370457507161e+01,
+      -2.168328665628878e+01,  1.772453852905383e+00 };
+  static const double b[] =
+    { -5.447609879822406e+01,  1.615858368580409e+02,
+      -1.556989798598866e+02,  6.680131188771972e+01,
+      -1.328068155288572e+01 };
+  static const double c[] =
+    { -5.504751339936943e-03, -2.279687217114118e-01,
+      -1.697592457770869e+00, -1.802933168781950e+00,
+       3.093354679843505e+00,  2.077595676404383e+00 };
+  static const double d[] =
+    {  7.784695709041462e-03,  3.224671290700398e-01,
+       2.445134137142996e+00,  3.754408661907416e+00 };
+
+  static const double spi2 = 8.862269254527579e-01; // sqrt(pi)/2.
+  static const double pbreak_lo = 0.04850;  // 1-pbreak
+  static const double pbreak_hi = 1.95150;  // 1+pbreak
+  double y;
+
+  // Select case.
+  if (x >= pbreak_lo && x <= pbreak_hi)
+    {
+      // Middle region.
+      const double q = 0.5*(1-x), r = q*q;
+      const double yn = (((((a[0]*r + a[1])*r + a[2])*r + a[3])*r + a[4])*r + a[5])*q;
+      const double yd = ((((b[0]*r + b[1])*r + b[2])*r + b[3])*r + b[4])*r + 1.0;
+      y = yn / yd;
+    }
+  else if (x > 0.0 && x < 2.0)
+    {
+      // Tail region.
+      const double q = x < 1 ? sqrt (-2*log (0.5*x)) : sqrt (-2*log (0.5*(2-x)));
+      const double yn = ((((c[0]*q + c[1])*q + c[2])*q + c[3])*q + c[4])*q + c[5];
+      const double yd = (((d[0]*q + d[1])*q + d[2])*q + d[3])*q + 1.0;
+      y = yn / yd;
+      if (x < pbreak_lo)
+        y = -y;
+    }
+  else if (x == 0.0)
+    return octave_Inf;
+  else if (x == 2.0)
+    return -octave_Inf;
+  else
+    return octave_NaN;
+
+  if (refine)
     {
-      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[] =
+      // One iteration of Halley's method gives full precision.
+      double u = (erf (y) - (1-x)) * spi2 * exp (y*y);
+      y -= u / (1 + y*u);
+    }
+
+  return y;
+}
+
+double erfcinv (double x)
+{
+  return do_erfcinv (x, true);
+}
+
+float erfcinv (float x)
+{
+  return do_erfcinv (x, false);
+}
+
+//
+//  Incomplete Beta function ratio
+//
+//  Algorithm based on the one by John Burkardt.
+//  See http://people.sc.fsu.edu/~jburkardt/cpp_src/asa109/asa109.html
+//
+//  The original code is distributed under the GNU LGPL v3 license.
+//
+//  Reference:
+//
+//    KL Majumder, GP Bhattacharjee,
+//    Algorithm AS 63:
+//    The incomplete Beta Integral,
+//    Applied Statistics,
+//    Volume 22, Number 3, 1973, pages 409-411.
+//
+double
+betain (double x, double p, double q, double beta, bool& err)
+{
+  double acu = 0.1E-14, ai, cx;
+  bool indx;
+  int ns;
+  double pp, psq, qq, rx, temp, term, value, xx;
+
+  value = x;
+  err = false;
+
+  //  Check the input arguments.
+
+  if ((p <= 0.0 || q <= 0.0) || (x < 0.0 || 1.0 < x))
+    {
+      err = true;
+      return value;
+    }
+
+  //  Special cases.
+
+  if (x == 0.0 || x == 1.0)
+    {
+      return value;
+    }
+
+  //  Change tail if necessary and determine S.
+
+  psq = p + q;
+  cx = 1.0 - x;
+
+  if (p < psq * x)
     {
-      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[] =
+      xx = cx;
+      cx = x;
+      pp = q;
+      qq = p;
+      indx = true;
+    }
+  else
     {
-      3.05326634961232344e-1,3.60344899949804439e-1,
-      1.25781726111229246e-1,1.60837851487422766e-2,
-      6.58749161529837803e-4,1.63153871373020978e-2
-    };
-
-  static const T q[] =
+      xx = x;
+      pp = p;
+      qq = q;
+      indx = false;
+    }
+
+  term = 1.0;
+  ai = 1.0;
+  value = 1.0;
+  ns = static_cast<int> (qq + cx * psq);
+
+  //  Use the Soper reduction formula.
+
+  rx = xx / cx;
+  temp = qq - ai;
+  if (ns == 0)
+    {
+      rx = xx;
+    }
+
+  for ( ; ; )
     {
-      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);
+      term = term * temp * rx / (pp + ai);
+      value = value + term;
+      temp = fabs (term);
+
+      if (temp <= acu && temp <= acu * value)
+        {
+          value = value * exp (pp * log (xx)
+          + (qq - 1.0) * log (cx) - beta) / pp;
+
+          if (indx)
+            {
+              value = 1.0 - value;
+            }
+          break;
+        }
+
+      ai = ai + 1.0;
+      ns = ns - 1;
+
+      if (0 <= ns)
+        {
+          temp = qq - ai;
+          if (ns == 0)
+            {
+              rx = xx;
+            }
+        }
+      else
+        {
+          temp = psq;
+          psq = psq + 1.0;
+        }
+    }
+
+  return value;
+}
+
+//
+//  Inverse of the incomplete Beta function
+//
+//  Algorithm based on the one by John Burkardt.
+//  See http://people.sc.fsu.edu/~jburkardt/cpp_src/asa109/asa109.html
+//
+//  The original code is distributed under the GNU LGPL v3 license.
+//
+//  Reference:
+//
+//    GW Cran, KJ Martin, GE Thomas,
+//    Remark AS R19 and Algorithm AS 109:
+//    A Remark on Algorithms AS 63: The Incomplete Beta Integral
+//    and AS 64: Inverse of the Incomplete Beta Integeral,
+//    Applied Statistics,
+//    Volume 26, Number 1, 1977, pages 111-114.
+//
+double
+betaincinv (double y, double p, double q)
+{
+  double a, acu, adj, fpu, g, h;
+  int iex;
+  bool indx;
+  double pp, prev, qq, r, s, sae = -37.0, sq, t, tx, value, w, xin, ycur, yprev;
+
+  double beta = xlgamma (p) + xlgamma (q) - xlgamma (p + q);
+  bool err = false;
+  fpu = pow (10.0, sae);
+  value = y;
+
+  //  Test for admissibility of parameters.
+
+  if (p <= 0.0 || q <= 0.0)
+    {
+      (*current_liboctave_error_handler)
+        ("betaincinv: wrong parameters");
+    }
+
+  if (y < 0.0 || 1.0 < y)
+    {
+      (*current_liboctave_error_handler)
+        ("betaincinv: wrong parameter Y");
+    }
+
+  if (y == 0.0 || y == 1.0)
+    {
+      return value;
+    }
+
+  //  Change tail if necessary.
+
+  if (0.5 < y)
+    {
+      a = 1.0 - y;
+      pp = q;
+      qq = p;
+      indx = true;
+    }
   else
     {
-      if (y <= 4.0)
+      a = y;
+      pp = p;
+      qq = q;
+      indx = false;
+    }
+
+  //  Calculate the initial approximation.
+
+  r = sqrt (- log (a * a));
+
+  ycur = r - (2.30753 + 0.27061 * r) / (1.0 + (0.99229 + 0.04481 * r) * r);
+
+  if (1.0 < pp && 1.0 < qq)
+    {
+      r = (ycur * ycur - 3.0) / 6.0;
+      s = 1.0 / (pp + pp - 1.0);
+      t = 1.0 / (qq + qq - 1.0);
+      h = 2.0 / (s + t);
+      w = ycur * sqrt (h + r) / h - (t - s) * (r + 5.0 / 6.0 - 2.0 / (3.0 * h));
+      value = pp / (pp + qq * exp (w + w));
+    }
+  else
+    {
+      r = qq + qq;
+      t = 1.0 / (9.0 * qq);
+      t = r * pow (1.0 - t + ycur * sqrt (t), 3);
+
+      if (t <= 0.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;
+          value = 1.0 - exp ((log ((1.0 - a) * qq) + beta) / qq);
         }
       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;
+          t = (4.0 * pp + r - 2.0) / t;
+
+          if (t <= 1.0)
+            {
+              value = exp ((log (a * pp) + beta) / pp);
+            }
+          else
+            {
+              value = 1.0 - 2.0 / (t + 1.0);
+            }
         }
     }
 
-  return result;
+  //  Solve for X by a modified Newton-Raphson method,
+  //  using the function BETAIN.
+
+  r = 1.0 - pp;
+  t = 1.0 - qq;
+  yprev = 0.0;
+  sq = 1.0;
+  prev = 1.0;
+
+  if (value < 0.0001)
+    {
+      value = 0.0001;
+    }
+
+  if (0.9999 < value)
+    {
+      value = 0.9999;
+    }
+
+  iex = std::max (- 5.0 / pp / pp - 1.0 / pow (a, 0.2) - 13.0, sae);
+
+  acu = pow (10.0, iex);
+
+  for ( ; ; )
+    {
+      ycur = betain (value, pp, qq, beta, err);
+
+      if (err)
+        {
+          return value;
+        }
+
+      xin = value;
+      ycur = (ycur - a) * exp (beta + r * log (xin) + t * log (1.0 - xin));
+
+      if (ycur * yprev <= 0.0)
+        {
+          prev = std::max (sq, fpu);
+        }
+
+      g = 1.0;
+
+      for ( ; ; )
+        {
+          for ( ; ; )
+            {
+              adj = g * ycur;
+              sq = adj * adj;
+
+              if (sq < prev)
+                {
+                  tx = value - adj;
+
+                  if (0.0 <= tx && tx <= 1.0)
+                    {
+                      break;
+                    }
+                }
+              g = g / 3.0;
+            }
+
+          if (prev <= acu)
+            {
+              if (indx)
+                {
+                  value = 1.0 - value;
+                }
+              return value;
+            }
+
+          if (ycur * ycur <= acu)
+            {
+              if (indx)
+                {
+                  value = 1.0 - value;
+                }
+              return value;
+            }
+
+          if (tx != 0.0 && tx != 1.0)
+            {
+              break;
+            }
+
+          g = g / 3.0;
+        }
+
+      if (tx == value)
+        {
+          break;
+        }
+
+      value = tx;
+      yprev = ycur;
+    }
+
+  if (indx)
+    {
+      value = 1.0 - value;
+    }
+
+  return value;
 }
 
-double erfcx (double x)
+Array<double>
+betaincinv (double x, double a, const Array<double>& b)
 {
-  return erfcx_impl (x);
+  dim_vector dv = b.dims ();
+  octave_idx_type nel = dv.numel ();
+
+  Array<double> retval (dv);
+
+  double *pretval = retval.fortran_vec ();
+
+  for (octave_idx_type i = 0; i < nel; i++)
+    *pretval++ = betaincinv (x, a, b(i));
+
+  return retval;
+}
+
+Array<double>
+betaincinv (double x, const Array<double>& a, double b)
+{
+  dim_vector dv = a.dims ();
+  octave_idx_type nel = dv.numel ();
+
+  Array<double> retval (dv);
+
+  double *pretval = retval.fortran_vec ();
+
+  for (octave_idx_type i = 0; i < nel; i++)
+    *pretval++ = betaincinv (x, a(i), b);
+
+  return retval;
+}
+
+Array<double>
+betaincinv (double x, const Array<double>& a, const Array<double>& b)
+{
+  Array<double> retval;
+  dim_vector dv = a.dims ();
+
+  if (dv == b.dims ())
+    {
+      octave_idx_type nel = dv.numel ();
+
+      retval.resize (dv);
+
+      double *pretval = retval.fortran_vec ();
+
+      for (octave_idx_type i = 0; i < nel; i++)
+        *pretval++ = betaincinv (x, a(i), b(i));
+    }
+  else
+    gripe_betaincinv_nonconformant (dim_vector (0, 0), dv, b.dims ());
+
+  return retval;
+}
+
+Array<double>
+betaincinv (const Array<double>& x, double a, double b)
+{
+  dim_vector dv = x.dims ();
+  octave_idx_type nel = dv.numel ();
+
+  Array<double> retval (dv);
+
+  double *pretval = retval.fortran_vec ();
+
+  for (octave_idx_type i = 0; i < nel; i++)
+    *pretval++ = betaincinv (x(i), a, b);
+
+  return retval;
 }
 
-float erfcx (float x)
+Array<double>
+betaincinv (const Array<double>& x, double a, const Array<double>& b)
+{
+  Array<double> retval;
+  dim_vector dv = x.dims ();
+
+  if (dv == b.dims ())
+    {
+      octave_idx_type nel = dv.numel ();
+
+      retval.resize (dv);
+
+      double *pretval = retval.fortran_vec ();
+
+      for (octave_idx_type i = 0; i < nel; i++)
+        *pretval++ = betaincinv (x(i), a, b(i));
+    }
+  else
+    gripe_betaincinv_nonconformant (dv, dim_vector (0, 0), b.dims ());
+
+  return retval;
+}
+
+Array<double>
+betaincinv (const Array<double>& x, const Array<double>& a, double b)
 {
-  return erfcx_impl (x);
+  Array<double> retval;
+  dim_vector dv = x.dims ();
+
+  if (dv == a.dims ())
+    {
+      octave_idx_type nel = dv.numel ();
+
+      retval.resize (dv);
+
+      double *pretval = retval.fortran_vec ();
+
+      for (octave_idx_type i = 0; i < nel; i++)
+        *pretval++ = betaincinv (x(i), a(i), b);
+    }
+  else
+    gripe_betaincinv_nonconformant (dv, a.dims (), dim_vector (0, 0));
+
+  return retval;
 }
+
+Array<double>
+betaincinv (const Array<double>& x, const Array<double>& a, const Array<double>& b)
+{
+  Array<double> retval;
+  dim_vector dv = x.dims ();
+
+  if (dv == a.dims () && dv == b.dims ())
+    {
+      octave_idx_type nel = dv.numel ();
+
+      retval.resize (dv);
+
+      double *pretval = retval.fortran_vec ();
+
+      for (octave_idx_type i = 0; i < nel; i++)
+        *pretval++ = betaincinv (x(i), a(i), b(i));
+    }
+  else
+    gripe_betaincinv_nonconformant (dv, a.dims (), b.dims ());
+
+  return retval;
+}
rename from liboctave/lo-specfun.h
rename to liboctave/numeric/lo-specfun.h
--- a/liboctave/lo-specfun.h
+++ b/liboctave/numeric/lo-specfun.h
@@ -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);
@@ -520,42 +524,24 @@
 biry (const FloatComplexNDArray& z, bool deriv, bool scaled, Array<octave_idx_type>& ierr);
 
 extern OCTAVE_API double betainc (double x, double a, double b);
-extern OCTAVE_API Matrix betainc (double x, double a, const Matrix& b);
-extern OCTAVE_API Matrix betainc (double x, const Matrix& a, double b);
-extern OCTAVE_API Matrix betainc (double x, const Matrix& a, const Matrix& b);
-
-extern OCTAVE_API NDArray betainc (double x, double a, const NDArray& b);
-extern OCTAVE_API NDArray betainc (double x, const NDArray& a, double b);
-extern OCTAVE_API NDArray betainc (double x, const NDArray& a, const NDArray& b);
-
-extern OCTAVE_API Matrix betainc (const Matrix& x, double a, double b);
-extern OCTAVE_API Matrix betainc (const Matrix& x, double a, const Matrix& b);
-extern OCTAVE_API Matrix betainc (const Matrix& x, const Matrix& a, double b);
-extern OCTAVE_API Matrix betainc (const Matrix& x, const Matrix& a, const Matrix& b);
-
-extern OCTAVE_API NDArray betainc (const NDArray& x, double a, double b);
-extern OCTAVE_API NDArray betainc (const NDArray& x, double a, const NDArray& b);
-extern OCTAVE_API NDArray betainc (const NDArray& x, const NDArray& a, double b);
-extern OCTAVE_API NDArray betainc (const NDArray& x, const NDArray& a, const NDArray& b);
+extern OCTAVE_API Array<double> betainc (double x, double a, const Array<double>& b);
+extern OCTAVE_API Array<double> betainc (double x, const Array<double>& a, double b);
+extern OCTAVE_API Array<double> betainc (double x, const Array<double>& a, const Array<double>& b);
+extern OCTAVE_API Array<double> betainc (const Array<double>& x, double a, double b);
+extern OCTAVE_API Array<double> betainc (const Array<double>& x, double a, double b);
+extern OCTAVE_API Array<double> betainc (const Array<double>& x, double a, const Array<double>& b);
+extern OCTAVE_API Array<double> betainc (const Array<double>& x, const Array<double>& a, double b);
+extern OCTAVE_API Array<double> betainc (const Array<double>& x, const Array<double>& a, const Array<double>& b);
 
 extern OCTAVE_API float betainc (float x, float a, float b);
-extern OCTAVE_API FloatMatrix betainc (float x, float a, const FloatMatrix& b);
-extern OCTAVE_API FloatMatrix betainc (float x, const FloatMatrix& a, float b);
-extern OCTAVE_API FloatMatrix betainc (float x, const FloatMatrix& a, const FloatMatrix& b);
-
-extern OCTAVE_API FloatNDArray betainc (float x, float a, const FloatNDArray& b);
-extern OCTAVE_API FloatNDArray betainc (float x, const FloatNDArray& a, float b);
-extern OCTAVE_API FloatNDArray betainc (float x, const FloatNDArray& a, const FloatNDArray& b);
-
-extern OCTAVE_API FloatMatrix betainc (const FloatMatrix& x, float a, float b);
-extern OCTAVE_API FloatMatrix betainc (const FloatMatrix& x, float a, const FloatMatrix& b);
-extern OCTAVE_API FloatMatrix betainc (const FloatMatrix& x, const FloatMatrix& a, float b);
-extern OCTAVE_API FloatMatrix betainc (const FloatMatrix& x, const FloatMatrix& a, const FloatMatrix& b);
-
-extern OCTAVE_API FloatNDArray betainc (const FloatNDArray& x, float a, float b);
-extern OCTAVE_API FloatNDArray betainc (const FloatNDArray& x, float a, const FloatNDArray& b);
-extern OCTAVE_API FloatNDArray betainc (const FloatNDArray& x, const FloatNDArray& a, float b);
-extern OCTAVE_API FloatNDArray betainc (const FloatNDArray& x, const FloatNDArray& a, const FloatNDArray& b);
+extern OCTAVE_API Array<float> betainc (float x, float a, const Array<float>& b);
+extern OCTAVE_API Array<float> betainc (float x, const Array<float>& a, float b);
+extern OCTAVE_API Array<float> betainc (float x, const Array<float>& a, const Array<float>& b);
+extern OCTAVE_API Array<float> betainc (const Array<float>& x, float a, float b);
+extern OCTAVE_API Array<float> betainc (const Array<float>& x, float a, float b);
+extern OCTAVE_API Array<float> betainc (const Array<float>& x, float a, const Array<float>& b);
+extern OCTAVE_API Array<float> betainc (const Array<float>& x, const Array<float>& a, float b);
+extern OCTAVE_API Array<float> betainc (const Array<float>& x, const Array<float>& a, const Array<float>& b);
 
 extern OCTAVE_API double gammainc (double x, double a, bool& err);
 extern OCTAVE_API Matrix gammainc (double x, const Matrix& a);
@@ -593,7 +579,32 @@
 extern OCTAVE_API double erfinv (double x);
 extern OCTAVE_API float erfinv (float x);
 
+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);
+extern OCTAVE_API Array<double> betaincinv (double x, const Array<double>& a, double b);
+extern OCTAVE_API Array<double> betaincinv (double x, const Array<double>& a, const Array<double>& b);
+extern OCTAVE_API Array<double> betaincinv (const Array<double>& x, double a, double b);
+extern OCTAVE_API Array<double> betaincinv (const Array<double>& x, double a, double b);
+extern OCTAVE_API Array<double> betaincinv (const Array<double>& x, double a, const Array<double>& b);
+extern OCTAVE_API Array<double> betaincinv (const Array<double>& x, const Array<double>& a, double b);
+extern OCTAVE_API Array<double> betaincinv (const Array<double>& x, const Array<double>& a, const Array<double>& b);
 
 #endif
new file mode 100644
--- /dev/null
+++ b/liboctave/numeric/module.mk
@@ -0,0 +1,185 @@
+EXTRA_DIST += \
+  numeric/module.mk \
+  $(OPT_IN)
+
+OPT_INC = \
+  numeric/DASPK-opts.h \
+  numeric/DASRT-opts.h \
+  numeric/DASSL-opts.h \
+  numeric/LSODE-opts.h \
+  numeric/Quad-opts.h
+
+OPT_IN = $(OPT_INC:.h=.in)
+
+NUMERIC_INC = \
+  numeric/base-aepbal.h \
+  numeric/base-dae.h \
+  numeric/base-de.h \
+  numeric/base-lu.h \
+  numeric/base-min.h \
+  numeric/base-qr.h \
+  numeric/bsxfun-decl.h \
+  numeric/bsxfun.h \
+  numeric/CmplxAEPBAL.h \
+  numeric/CmplxCHOL.h \
+  numeric/CmplxGEPBAL.h \
+  numeric/CmplxHESS.h \
+  numeric/CmplxLU.h \
+  numeric/CmplxQR.h \
+  numeric/CmplxQRP.h \
+  numeric/CmplxSCHUR.h \
+  numeric/CmplxSVD.h \
+  numeric/CollocWt.h \
+  numeric/DAEFunc.h \
+  numeric/DAE.h \
+  numeric/DAERTFunc.h \
+  numeric/DAERT.h \
+  numeric/DASPK.h \
+  numeric/DASRT.h \
+  numeric/DASSL.h \
+  numeric/dbleAEPBAL.h \
+  numeric/dbleCHOL.h \
+  numeric/dbleGEPBAL.h \
+  numeric/dbleHESS.h \
+  numeric/dbleLU.h \
+  numeric/dbleQR.h \
+  numeric/dbleQRP.h \
+  numeric/dbleSCHUR.h \
+  numeric/dbleSVD.h \
+  numeric/DET.h \
+  numeric/EIG.h \
+  numeric/fCmplxAEPBAL.h \
+  numeric/fCmplxCHOL.h \
+  numeric/fCmplxGEPBAL.h \
+  numeric/fCmplxHESS.h \
+  numeric/fCmplxLU.h \
+  numeric/fCmplxQR.h \
+  numeric/fCmplxQRP.h \
+  numeric/fCmplxSCHUR.h \
+  numeric/fCmplxSVD.h \
+  numeric/fEIG.h \
+  numeric/floatAEPBAL.h \
+  numeric/floatCHOL.h \
+  numeric/floatGEPBAL.h \
+  numeric/floatHESS.h \
+  numeric/floatLU.h \
+  numeric/floatQR.h \
+  numeric/floatQRP.h \
+  numeric/floatSCHUR.h \
+  numeric/floatSVD.h \
+  numeric/lo-mappers.h \
+  numeric/lo-specfun.h \
+  numeric/LSODE.h \
+  numeric/oct-convn.h \
+  numeric/oct-fftw.h \
+  numeric/oct-norm.h \
+  numeric/oct-rand.h \
+  numeric/oct-spparms.h \
+  numeric/ODEFunc.h \
+  numeric/ODE.h \
+  numeric/ODESFunc.h \
+  numeric/ODES.h \
+  numeric/Quad.h \
+  numeric/randgamma.h \
+  numeric/randmtzig.h \
+  numeric/randpoisson.h \
+  numeric/sparse-base-chol.h \
+  numeric/sparse-base-lu.h \
+  numeric/SparseCmplxCHOL.h \
+  numeric/SparseCmplxLU.h \
+  numeric/SparseCmplxQR.h \
+  numeric/SparsedbleCHOL.h \
+  numeric/SparsedbleLU.h \
+  numeric/SparseQR.h 
+
+NUMERIC_C_SRC = \
+  numeric/randgamma.c \
+  numeric/randmtzig.c \
+  numeric/randpoisson.c
+
+NUMERIC_SRC = \
+  numeric/CmplxAEPBAL.cc \
+  numeric/CmplxCHOL.cc \
+  numeric/CmplxGEPBAL.cc \
+  numeric/CmplxHESS.cc \
+  numeric/CmplxLU.cc \
+  numeric/CmplxQR.cc \
+  numeric/CmplxQRP.cc \
+  numeric/CmplxSCHUR.cc \
+  numeric/CmplxSVD.cc \
+  numeric/CollocWt.cc \
+  numeric/DASPK.cc \
+  numeric/DASRT.cc \
+  numeric/DASSL.cc \
+  numeric/dbleAEPBAL.cc \
+  numeric/dbleCHOL.cc \
+  numeric/dbleGEPBAL.cc \
+  numeric/dbleHESS.cc \
+  numeric/dbleLU.cc \
+  numeric/dbleQR.cc \
+  numeric/dbleQRP.cc \
+  numeric/dbleSCHUR.cc \
+  numeric/dbleSVD.cc \
+  numeric/EIG.cc \
+  numeric/fCmplxAEPBAL.cc \
+  numeric/fCmplxCHOL.cc \
+  numeric/fCmplxGEPBAL.cc \
+  numeric/fCmplxHESS.cc \
+  numeric/fCmplxLU.cc \
+  numeric/fCmplxQR.cc \
+  numeric/fCmplxQRP.cc \
+  numeric/fCmplxSCHUR.cc \
+  numeric/fCmplxSVD.cc \
+  numeric/fEIG.cc \
+  numeric/floatAEPBAL.cc \
+  numeric/floatCHOL.cc \
+  numeric/floatGEPBAL.cc \
+  numeric/floatHESS.cc \
+  numeric/floatLU.cc \
+  numeric/floatQR.cc \
+  numeric/floatQRP.cc \
+  numeric/floatSCHUR.cc \
+  numeric/floatSVD.cc \
+  numeric/lo-mappers.cc \
+  numeric/lo-specfun.cc \
+  numeric/LSODE.cc \
+  numeric/oct-convn.cc \
+  numeric/oct-fftw.cc \
+  numeric/oct-norm.cc \
+  numeric/oct-rand.cc \
+  numeric/oct-spparms.cc \
+  numeric/ODES.cc \
+  numeric/Quad.cc \
+  numeric/SparseCmplxCHOL.cc \
+  numeric/SparseCmplxLU.cc \
+  numeric/SparseCmplxQR.cc \
+  numeric/SparsedbleCHOL.cc \
+  numeric/SparsedbleLU.cc \
+  numeric/SparseQR.cc \
+  $(NUMERIC_C_SRC)
+
+TEMPLATE_SRC += \
+  numeric/base-lu.cc \
+  numeric/base-qr.cc \
+  numeric/bsxfun-defs.cc \
+  numeric/eigs-base.cc \
+  numeric/sparse-base-chol.cc \
+  numeric/sparse-base-lu.cc \
+  numeric/sparse-dmsolve.cc
+
+## Special rules for sources which must be built before rest of compilation.
+$(OPT_INC) : %.h : %.in $(top_srcdir)/build-aux/mk-opts.pl
+	@echo making $@ from $<
+	@$(PERL) $(top_srcdir)/build-aux/mk-opts.pl --opt-class-header $< > $@-t
+	mv $@-t $@
+
+noinst_LTLIBRARIES += numeric/libnumeric.la
+
+numeric_libnumeric_la_SOURCES = $(NUMERIC_SRC)
+numeric_libnumeric_la_CPPFLAGS = \
+  $(liboctave_la_CPPFLAGS) \
+  $(ARPACK_CPPFLAGS) \
+  -I$(srcdir)/cruft/Faddeeva \
+  $(FFTW_XCPPFLAGS) \
+  $(SPARSE_XCPPFLAGS)
+
rename from liboctave/oct-convn.cc
rename to liboctave/numeric/oct-convn.cc
--- a/liboctave/oct-convn.cc
+++ b/liboctave/numeric/oct-convn.cc
@@ -125,7 +125,7 @@
                              static_cast<octave_idx_type> (0));
     }
 
-  MArray<T> c (cdims, T());
+  MArray<T> c (cdims, T ());
 
   convolve_nd<T, R> (a.fortran_vec (), adims, adims.cumulative (),
                      b.fortran_vec (), bdims, bdims.cumulative (),
rename from liboctave/oct-convn.h
rename to liboctave/numeric/oct-convn.h
rename from liboctave/oct-fftw.cc
rename to liboctave/numeric/oct-fftw.cc
--- a/liboctave/oct-fftw.cc
+++ b/liboctave/numeric/oct-fftw.cc
@@ -35,6 +35,10 @@
 #include "oct-locbuf.h"
 #include "singleton-cleanup.h"
 
+#if defined (HAVE_FFTW3_THREADS)
+#include "nproc.h"
+#endif
+
 octave_fftw_planner *octave_fftw_planner::instance = 0;
 
 // Helper class to create and cache FFTW plans for both 1D and
@@ -65,6 +69,16 @@
   inplace[0] = inplace[1] = false;
   n[0] = n[1] = dim_vector ();
 
+#if defined (HAVE_FFTW3_THREADS)
+  int init_ret = fftw_init_threads ();
+  if (!init_ret)
+    (*current_liboctave_error_handler) ("Error initializing FFTW threads");
+  //Use number of processors available to the current process
+  //This can be later changed with fftw ("threads", nthreads)
+  nthreads = num_processors (NPROC_CURRENT);
+  fftw_plan_with_nthreads (nthreads);
+#endif
+
   // If we have a system wide wisdom file, import it.
   fftw_import_system_wisdom ();
 }
@@ -395,6 +409,16 @@
   inplace[0] = inplace[1] = false;
   n[0] = n[1] = dim_vector ();
 
+#if defined (HAVE_FFTW3F_THREADS)
+  int init_ret = fftwf_init_threads ();
+  if (!init_ret)
+    (*current_liboctave_error_handler) ("Error initializing FFTW3F threads");
+  //Use number of processors available to the current process
+  //This can be later changed with fftw ("threads", nthreads)
+  nthreads = num_processors (NPROC_CURRENT);
+  fftwf_plan_with_nthreads (nthreads);
+#endif
+
   // If we have a system wide wisdom file, import it.
   fftwf_import_system_wisdom ();
 }
@@ -723,7 +747,7 @@
 
   for (size_t i = 0; i < nr; i++)
     for (size_t j = nc/2+1; j < nc; j++)
-      out[j*stride + i*dist] = conj(out[(nc - j)*stride + i*dist]);
+      out[j*stride + i*dist] = conj (out[(nc - j)*stride + i*dist]);
 
   octave_quit ();
 }
@@ -758,10 +782,10 @@
     {
       for (size_t j = 1; j < nr; j++)
         for (size_t k = nc/2+1; k < nc; k++)
-          out[k + (j + i*nr)*nc] = conj(out[nc - k + ((i+1)*nr - j)*nc]);
+          out[k + (j + i*nr)*nc] = conj (out[nc - k + ((i+1)*nr - j)*nc]);
 
       for (size_t j = nc/2+1; j < nc; j++)
-        out[j + i*nr*nc] = conj(out[(i*nr+1)*nc - j]);
+        out[j + i*nr*nc] = conj (out[(i*nr+1)*nc - j]);
     }
 
   octave_quit ();
@@ -782,7 +806,7 @@
             for (size_t l = nc/2+1; l < nc; l++)
               {
                 T tmp = out[i+ j + k + l];
-                out[i + j + k + l] =  out[i + jj + k + l];
+                out[i + j + k + l] = out[i + jj + k + l];
                 out[i + jj + k + l] = tmp;
               }
       jstart = jmax;
rename from liboctave/oct-fftw.h
rename to liboctave/numeric/oct-fftw.h
--- a/liboctave/oct-fftw.h
+++ b/liboctave/numeric/oct-fftw.h
@@ -98,6 +98,24 @@
     return instance_ok () ? instance->do_method (_meth) : dummy;
   }
 
+#if defined (HAVE_FFTW3F_THREADS)
+  static void threads (int _nthreads)
+  {
+    if (instance_ok () && _nthreads != threads ())
+      {
+        instance->nthreads = _nthreads;
+        fftw_plan_with_nthreads (_nthreads);
+        //Clear the current plans
+        instance->rplan = instance->plan[0] = instance->plan[1] = 0;
+      }
+  }
+
+  static int threads ()
+  {
+    return instance_ok () ? instance->nthreads : 0;
+  }
+#endif
+
 private:
 
   // No copying!
@@ -169,6 +187,11 @@
   dim_vector rn;
 
   bool rsimd_align;
+
+#if defined (HAVE_FFTW3_THREADS)
+  //number of threads when compiled with Multi-threading support
+  int nthreads;
+#endif
 };
 
 class
@@ -235,6 +258,24 @@
     return instance_ok () ? instance->do_method (_meth) : dummy;
   }
 
+#if defined (HAVE_FFTW3F_THREADS)
+  static void threads (int _nthreads)
+  {
+    if (instance_ok () && _nthreads != threads ())
+      {
+        instance->nthreads = _nthreads;
+        fftwf_plan_with_nthreads (_nthreads);
+        //Clear the current plans
+        instance->rplan = instance->plan[0] = instance->plan[1] = 0;
+      }
+  }
+
+  static int threads ()
+  {
+    return instance_ok () ? instance->nthreads : 0;
+  }
+#endif
+
 private:
 
   // No copying!
@@ -306,6 +347,11 @@
   dim_vector rn;
 
   bool rsimd_align;
+
+#if defined (HAVE_FFTW3F_THREADS)
+  //number of threads when compiled with Multi-threading support
+  int nthreads;
+#endif
 };
 
 class
rename from liboctave/oct-norm.cc
rename to liboctave/numeric/oct-norm.cc
--- a/liboctave/oct-norm.cc
+++ b/liboctave/numeric/oct-norm.cc
@@ -415,7 +415,7 @@
   // the OSE part
   VectorT y(m.rows (), 1, 0), z(m.rows (), 1);
   typedef typename VectorT::element_type RR;
-  RR lambda = 0, mu = 0;
+  RR lambda = 0, mu = 1;
   for (octave_idx_type k = 0; k < m.columns (); k++)
     {
       octave_quit ();
rename from liboctave/oct-norm.h
rename to liboctave/numeric/oct-norm.h
rename from liboctave/oct-rand.cc
rename to liboctave/numeric/oct-rand.cc
--- a/liboctave/oct-rand.cc
+++ b/liboctave/numeric/oct-rand.cc
@@ -360,7 +360,7 @@
           break;
 
         case poisson_dist:
-          if (a < 0.0 || xisnan(a) || xisinf(a))
+          if (a < 0.0 || xisnan (a) || xisinf (a))
             retval = octave_NaN;
           else
             {
@@ -371,7 +371,7 @@
           break;
 
         case gamma_dist:
-          if (a <= 0.0 || xisnan(a) || xisinf(a))
+          if (a <= 0.0 || xisnan (a) || xisinf (a))
             retval = octave_NaN;
           else
             F77_FUNC (dgengam, DGENGAM) (1.0, a, retval);
@@ -419,34 +419,86 @@
   return retval;
 }
 
-Matrix
-octave_rand::do_matrix (octave_idx_type n, octave_idx_type m, double a)
+float
+octave_rand::do_float_scalar (float a)
 {
-  Matrix retval;
+  float retval = 0.0;
+
+  if (use_old_generators)
+    {
+      double da = a;
+      double dretval = 0.0;
+      switch (current_distribution)
+        {
+        case uniform_dist:
+          F77_FUNC (dgenunf, DGENUNF) (0.0, 1.0, dretval);
+          break;
+
+        case normal_dist:
+          F77_FUNC (dgennor, DGENNOR) (0.0, 1.0, dretval);
+          break;
+
+        case expon_dist:
+          F77_FUNC (dgenexp, DGENEXP) (1.0, dretval);
+          break;
 
-  if (n >= 0 && m >= 0)
-    {
-      retval.clear (n, m);
+        case poisson_dist:
+          if (da < 0.0 || xisnan (da) || xisinf (da))
+            dretval = octave_NaN;
+          else
+            {
+              // workaround bug in ignpoi, by calling with different Mu
+              F77_FUNC (dignpoi, DIGNPOI) (da + 1, dretval);
+              F77_FUNC (dignpoi, DIGNPOI) (da, dretval);
+            }
+          break;
 
-      if (n > 0 && m > 0)
-        fill (retval.capacity(), retval.fortran_vec(), a);
+        case gamma_dist:
+          if (da <= 0.0 || xisnan (da) || xisinf (da))
+            retval = octave_NaN;
+          else
+            F77_FUNC (dgengam, DGENGAM) (1.0, da, dretval);
+          break;
+
+        default:
+          (*current_liboctave_error_handler)
+            ("rand: invalid distribution ID = %d", current_distribution);
+          break;
+        }
+      retval = dretval;
     }
   else
-    (*current_liboctave_error_handler) ("rand: invalid negative argument");
+    {
+      switch (current_distribution)
+        {
+        case uniform_dist:
+          retval = oct_float_randu ();
+          break;
 
-  return retval;
-}
+        case normal_dist:
+          retval = oct_float_randn ();
+          break;
+
+        case expon_dist:
+          retval = oct_float_rande ();
+          break;
 
-NDArray
-octave_rand::do_nd_array (const dim_vector& dims, double a)
-{
-  NDArray retval;
+        case poisson_dist:
+          // Keep poisson distribution in double precision for accuracy
+          retval = oct_randp (a);
+          break;
 
-  if (! dims.all_zero ())
-    {
-      retval.clear (dims);
+        case gamma_dist:
+          retval = oct_float_randg (a);
+          break;
 
-      fill (retval.capacity(), retval.fortran_vec(), a);
+        default:
+          (*current_liboctave_error_handler)
+            ("rand: invalid distribution ID = %d", current_distribution);
+          break;
+        }
+
+      save_state ();
     }
 
   return retval;
@@ -469,6 +521,53 @@
   return retval;
 }
 
+Array<float>
+octave_rand::do_float_vector (octave_idx_type n, float a)
+{
+  Array<float> retval;
+
+  if (n > 0)
+    {
+      retval.clear (n, 1);
+
+      fill (retval.capacity (), retval.fortran_vec (), a);
+    }
+  else if (n < 0)
+    (*current_liboctave_error_handler) ("rand: invalid negative argument");
+
+  return retval;
+}
+
+NDArray
+octave_rand::do_nd_array (const dim_vector& dims, double a)
+{
+  NDArray retval;
+
+  if (! dims.all_zero ())
+    {
+      retval.clear (dims);
+
+      fill (retval.capacity (), retval.fortran_vec (), a);
+    }
+
+  return retval;
+}
+
+FloatNDArray
+octave_rand::do_float_nd_array (const dim_vector& dims, float a)
+{
+  FloatNDArray retval;
+
+  if (! dims.all_zero ())
+    {
+      retval.clear (dims);
+
+      fill (retval.capacity (), retval.fortran_vec (), a);
+    }
+
+  return retval;
+}
+
 // Make the random number generator give us a different sequence every
 // time we start octave unless we specifically set the seed.  The
 // technique used below will cycle monthly, but it it does seem to
@@ -481,11 +580,11 @@
   int stored_distribution = current_distribution;
   F77_FUNC (setcgn, SETCGN) (uniform_dist);
 
-  int hour = tm.hour() + 1;
-  int minute = tm.min() + 1;
-  int second = tm.sec() + 1;
+  int hour = tm.hour () + 1;
+  int minute = tm.min () + 1;
+  int second = tm.sec () + 1;
 
-  int32_t s0 = tm.mday() * hour * minute * second;
+  int32_t s0 = tm.mday () * hour * minute * second;
   int32_t s1 = hour * minute * second;
 
   s0 = force_to_fit_range (s0, 1, 2147483563);
@@ -531,7 +630,7 @@
   oct_get_state (tmp);
 
   for (octave_idx_type i = 0; i <= MT_N; i++)
-    s.elem (i) = static_cast<double> (tmp [i]);
+    s.elem (i) = static_cast<double> (tmp[i]);
 
   return s;
 }
@@ -573,7 +672,7 @@
   OCTAVE_LOCAL_BUFFER (uint32_t, tmp, MT_N + 1);
 
   for (octave_idx_type i = 0; i < n; i++)
-    tmp[i] = static_cast<uint32_t> (s.elem(i));
+    tmp[i] = static_cast<uint32_t> (s.elem (i));
 
   if (len == MT_N + 1 && tmp[MT_N] <= MT_N && tmp[MT_N] > 0)
     oct_set_state (tmp);
@@ -649,7 +748,7 @@
     case poisson_dist:
       if (use_old_generators)
         {
-          if (a < 0.0 || xisnan(a) || xisinf(a))
+          if (a < 0.0 || xisnan (a) || xisinf (a))
 #define RAND_FUNC(x) x = octave_NaN;
             MAKE_RAND (len);
 #undef RAND_FUNC
@@ -670,7 +769,7 @@
     case gamma_dist:
       if (use_old_generators)
         {
-          if (a <= 0.0 || xisnan(a) || xisinf(a))
+          if (a <= 0.0 || xisnan (a) || xisinf (a))
 #define RAND_FUNC(x) x = octave_NaN;
             MAKE_RAND (len);
 #undef RAND_FUNC
@@ -693,3 +792,94 @@
 
   return;
 }
+
+void
+octave_rand::fill (octave_idx_type len, float *v, float a)
+{
+  if (len < 1)
+    return;
+
+  switch (current_distribution)
+    {
+    case uniform_dist:
+      if (use_old_generators)
+        {
+#define RAND_FUNC(x) F77_FUNC (dgenunf, DGENUNF) (0.0, 1.0, x)
+          MAKE_RAND (len);
+#undef RAND_FUNC
+        }
+      else
+        oct_fill_float_randu (len, v);
+      break;
+
+    case normal_dist:
+      if (use_old_generators)
+        {
+#define RAND_FUNC(x) F77_FUNC (dgennor, DGENNOR) (0.0, 1.0, x)
+          MAKE_RAND (len);
+#undef RAND_FUNC
+        }
+      else
+        oct_fill_float_randn (len, v);
+      break;
+
+    case expon_dist:
+      if (use_old_generators)
+        {
+#define RAND_FUNC(x) F77_FUNC (dgenexp, DGENEXP) (1.0, x)
+          MAKE_RAND (len);
+#undef RAND_FUNC
+        }
+      else
+        oct_fill_float_rande (len, v);
+      break;
+
+    case poisson_dist:
+      if (use_old_generators)
+        {
+          double da = a;
+          if (da < 0.0 || xisnan (da) || xisinf (da))
+#define RAND_FUNC(x) x = octave_NaN;
+            MAKE_RAND (len);
+#undef RAND_FUNC
+          else
+            {
+              // workaround bug in ignpoi, by calling with different Mu
+              double tmp;
+              F77_FUNC (dignpoi, DIGNPOI) (da + 1, tmp);
+#define RAND_FUNC(x) F77_FUNC (dignpoi, DIGNPOI) (da, x)
+                MAKE_RAND (len);
+#undef RAND_FUNC
+            }
+        }
+      else
+        oct_fill_float_randp (a, len, v);
+      break;
+
+    case gamma_dist:
+      if (use_old_generators)
+        {
+          double da = a;
+          if (da <= 0.0 || xisnan (da) || xisinf (da))
+#define RAND_FUNC(x) x = octave_NaN;
+            MAKE_RAND (len);
+#undef RAND_FUNC
+          else
+#define RAND_FUNC(x) F77_FUNC (dgengam, DGENGAM) (1.0, da, x)
+            MAKE_RAND (len);
+#undef RAND_FUNC
+        }
+      else
+        oct_fill_float_randg (a, len, v);
+      break;
+
+    default:
+      (*current_liboctave_error_handler)
+        ("rand: invalid distribution ID = %d", current_distribution);
+      break;
+    }
+
+  save_state ();
+
+  return;
+}
rename from liboctave/oct-rand.h
rename to liboctave/numeric/oct-rand.h
--- a/liboctave/oct-rand.h
+++ b/liboctave/numeric/oct-rand.h
@@ -27,8 +27,8 @@
 #include <string>
 
 #include "dColVector.h"
-#include "dMatrix.h"
 #include "dNDArray.h"
+#include "fNDArray.h"
 #include "lo-ieee.h"
 
 class
@@ -136,13 +136,24 @@
     return instance_ok () ? instance->do_scalar (a) : octave_NaN;
   }
 
-  // Return a matrix of numbers from the sequence, filled in column
-  // major order.
-  static Matrix matrix (octave_idx_type r, octave_idx_type c, double a = 1.0)
+  // Return the next number from the sequence.
+  static float float_scalar (float a = 1.0)
   {
-    return instance_ok () ? instance->do_matrix (r, c, a) : Matrix ();
+    return instance_ok () ? instance->do_float_scalar (a) : octave_Float_NaN;
   }
 
+  // Return an array of numbers from the sequence.
+  static Array<double> vector (octave_idx_type n, double a = 1.0)
+   {
+     return instance_ok () ? instance->do_vector (n, a) : Array<double> ();
+   }
+
+  // Return an array of numbers from the sequence.
+  static Array<float> float_vector (octave_idx_type n, float a = 1.0)
+   {
+     return instance_ok () ? instance->do_float_vector (n, a) : Array<float> ();
+   }
+
   // Return an N-dimensional array of numbers from the sequence,
   // filled in column major order.
   static NDArray nd_array (const dim_vector& dims, double a = 1.0)
@@ -150,10 +161,12 @@
     return instance_ok () ? instance->do_nd_array (dims, a) : NDArray ();
   }
 
-  // Return an array of numbers from the sequence.
-  static Array<double> vector (octave_idx_type n, double a = 1.0)
+
+  // Return an N-dimensional array of numbers from the sequence,
+  // filled in column major order.
+  static FloatNDArray float_nd_array (const dim_vector& dims, float a = 1.0)
   {
-    return instance_ok () ? instance->do_vector (n, a) : Array<double> ();
+    return instance_ok () ? instance->do_float_nd_array (dims, a) : FloatNDArray ();
   }
 
 private:
@@ -220,16 +233,22 @@
   // Return the next number from the sequence.
   double do_scalar (double a = 1.);
 
-  // Return a matrix of numbers from the sequence, filled in column
-  // major order.
-  Matrix do_matrix (octave_idx_type r, octave_idx_type c, double a = 1.);
+  // Return the next number from the sequence.
+  float do_float_scalar (float a = 1.);
+
+  // Return an array of numbers from the sequence.
+  Array<double> do_vector (octave_idx_type n, double a = 1.);
+
+  // Return an array of numbers from the sequence.
+  Array<float> do_float_vector (octave_idx_type n, float a = 1.);
 
   // Return an N-dimensional array of numbers from the sequence,
   // filled in column major order.
   NDArray do_nd_array (const dim_vector& dims, double a = 1.);
 
-  // Return an array of numbers from the sequence.
-  Array<double> do_vector (octave_idx_type n, double a = 1.);
+  // Return an N-dimensional array of numbers from the sequence,
+  // filled in column major order.
+  FloatNDArray do_float_nd_array (const dim_vector& dims, float a = 1.);
 
   // Some helper functions.
 
@@ -248,6 +267,8 @@
   void switch_to_generator (int dist);
 
   void fill (octave_idx_type len, double *v, double a);
+
+  void fill (octave_idx_type len, float *v, float a);
 };
 
 #endif
rename from liboctave/oct-spparms.cc
rename to liboctave/numeric/oct-spparms.cc
rename from liboctave/oct-spparms.h
rename to liboctave/numeric/oct-spparms.h
rename from liboctave/randgamma.c
rename to liboctave/numeric/randgamma.c
--- a/liboctave/randgamma.c
+++ b/liboctave/numeric/randgamma.c
@@ -25,8 +25,8 @@
 
 /*
 
-double randg(a)
-void fill_randg(a,n,x)
+double randg (a)
+void fill_randg (a,n,x)
 
 Generate a series of standard gamma distributions.
 
@@ -58,7 +58,7 @@
 chisq(df) for df>0
   r = 2*randg(df/2)
 t(df) for 0<df<inf (use randn if df is infinite)
-  r = randn() / sqrt(2*randg(df/2)/df)
+  r = randn () / sqrt(2*randg(df/2)/df)
 F(n1,n2) for 0<n1, 0<n2
   r1 = 2*randg(n1/2)/n1 or 1 if n1 is infinite
   r2 = 2*randg(n2/2)/n2 or 1 if n2 is infinite
@@ -99,9 +99,9 @@
 oct_fill_randg (double a, octave_idx_type n, double *r)
 {
   octave_idx_type i;
-  /* If a < 1, start by generating gamma(1+a) */
+  /* If a < 1, start by generating gamma (1+a) */
   const double d =  (a < 1. ? 1.+a : a) - 1./3.;
-  const double c = 1./sqrt(9.*d);
+  const double c = 1./sqrt (9.*d);
 
   /* Handle invalid cases */
   if (a <= 0 || INFINITE(a))
@@ -122,7 +122,7 @@
         goto restart; /* rare, so don't bother moving up */
       u = RUNI;
       xsq = x*x;
-      if (u >= 1.-0.0331*xsq*xsq && log(u) >= 0.5*xsq + d*(1-v+log(v)))
+      if (u >= 1.-0.0331*xsq*xsq && log (u) >= 0.5*xsq + d*(1-v+log (v)))
         goto restart;
       r[i] = d*v;
     }
@@ -130,7 +130,7 @@
     { /* Use gamma(a) = gamma(1+a)*U^(1/a) */
       /* Given REXP = -log(U) then U^(1/a) = exp(-REXP/a) */
       for (i = 0; i < n; i++)
-        r[i] *= exp(-REXP/a);
+        r[i] *= exp (-REXP/a);
     }
 }
 
@@ -138,6 +138,62 @@
 oct_randg (double a)
 {
   double ret;
-  oct_fill_randg(a,1,&ret);
+  oct_fill_randg (a,1,&ret);
   return ret;
 }
+
+#undef NAN
+#undef RUNI
+#undef RNOR
+#undef REXP
+#define NAN octave_Float_NaN
+#define RUNI oct_float_randu()
+#define RNOR oct_float_randn()
+#define REXP oct_float_rande()
+
+void
+oct_fill_float_randg (float a, octave_idx_type n, float *r)
+{
+  octave_idx_type i;
+  /* If a < 1, start by generating gamma(1+a) */
+  const float d =  (a < 1. ? 1.+a : a) - 1./3.;
+  const float c = 1./sqrt (9.*d);
+
+  /* Handle invalid cases */
+  if (a <= 0 || INFINITE(a))
+    {
+      for (i=0; i < n; i++)
+        r[i] = NAN;
+      return;
+    }
+
+  for (i=0; i < n; i++)
+    {
+      float x, xsq, v, u;
+    frestart:
+      x = RNOR;
+      v = (1+c*x);
+      v *= v*v;
+      if (v <= 0)
+        goto frestart; /* rare, so don't bother moving up */
+      u = RUNI;
+      xsq = x*x;
+      if (u >= 1.-0.0331*xsq*xsq && log (u) >= 0.5*xsq + d*(1-v+log (v)))
+        goto frestart;
+      r[i] = d*v;
+    }
+  if (a < 1)
+    { /* Use gamma(a) = gamma(1+a)*U^(1/a) */
+      /* Given REXP = -log(U) then U^(1/a) = exp(-REXP/a) */
+      for (i = 0; i < n; i++)
+        r[i] *= exp (-REXP/a);
+    }
+}
+
+float
+oct_float_randg (float a)
+{
+  float ret;
+  oct_fill_float_randg (a,1,&ret);
+  return ret;
+}
rename from liboctave/randgamma.h
rename to liboctave/numeric/randgamma.h
--- a/liboctave/randgamma.h
+++ b/liboctave/numeric/randgamma.h
@@ -32,6 +32,9 @@
 extern OCTAVE_API double oct_randg (double a);
 extern OCTAVE_API void oct_fill_randg (double a, octave_idx_type n, double *p);
 
+extern OCTAVE_API float oct_float_randg (float a);
+extern OCTAVE_API void oct_fill_float_randg (float a, octave_idx_type n, float *p);
+
 #ifdef  __cplusplus
 }
 #endif
rename from liboctave/randmtzig.c
rename to liboctave/numeric/randmtzig.c
--- a/liboctave/randmtzig.c
+++ b/liboctave/numeric/randmtzig.c
@@ -64,10 +64,6 @@
    http://www.math.keio.ac.jp/matumoto/emt.html
    email: matumoto@math.keio.ac.jp
 
-   * 2006-04-01 David Bateman
-   * * convert for use in octave, declaring static functions only used
-   *   here and adding oct_ to functions visible externally
-   * * inverse sense of ALLBITS
    * 2004-01-19 Paul Kienzle
    * * comment out main
    * add init_by_entropy, get_state, set_state
@@ -87,6 +83,15 @@
    *
    * 2005-02-23 Paul Kienzle
    * * fix -DHAVE_X86_32 flag and add -DUSE_X86_32=0|1 for explicit control
+   *
+   * 2006-04-01 David Bateman
+   * * convert for use in octave, declaring static functions only used
+   *   here and adding oct_ to functions visible externally
+   * * inverse sense of ALLBITS
+   *
+   * 2012-05-18 David Bateman
+   * * Remove randu64 and ALLBIT option
+   * * Add the single precision generators
    */
 
 /*
@@ -96,9 +101,6 @@
    available.  This is not necessary if your architecture has
    /dev/urandom defined.
 
-   Compile with -DALLBITS to disable 53-bit random numbers. This is about
-   50% slower than using 32-bit random numbers.
-
    Uses implicit -Di386 or explicit -DHAVE_X86_32 to determine if CPU=x86.
    You can force X86 behaviour with -DUSE_X86_32=1, or suppress it with
    -DUSE_X86_32=0. You should also consider -march=i686 or similar for
@@ -115,32 +117,39 @@
    All generators share the same state vector.
 
    === Mersenne Twister ===
-   void oct_init_by_int(uint32_t s)           32-bit initial state
-   void oct_init_by_array(uint32_t k[],int m) m*32-bit initial state
-   void oct_init_by_entropy(void)             random initial state
-   void oct_get_state(uint32_t save[MT_N+1])  saves state in array
-   void oct_set_state(uint32_t save[MT_N+1])  restores state from array
-   static uint32_t randmt(void)               returns 32-bit unsigned int
+   void oct_init_by_int (uint32_t s)           32-bit initial state
+   void oct_init_by_array (uint32_t k[],int m) m*32-bit initial state
+   void oct_init_by_entropy (void)             random initial state
+   void oct_get_state (uint32_t save[MT_N+1])  saves state in array
+   void oct_set_state (uint32_t save[MT_N+1])  restores state from array
+   static uint32_t randmt (void)               returns 32-bit unsigned int
 
    === inline generators ===
-   static uint32_t randi32(void)   returns 32-bit unsigned int
-   static uint64_t randi53(void)   returns 53-bit unsigned int
-   static uint64_t randi54(void)   returns 54-bit unsigned int
-   static uint64_t randi64(void)   returns 64-bit unsigned int
-   static double randu32(void)     returns 32-bit uniform in (0,1)
-   static double randu53(void)     returns 53-bit uniform in (0,1)
+   static uint32_t randi32 (void)   returns 32-bit unsigned int
+   static uint64_t randi53 (void)   returns 53-bit unsigned int
+   static uint64_t randi54 (void)   returns 54-bit unsigned int
+   static float randu32 (void)      returns 32-bit uniform in (0,1)
+   static double randu53 (void)     returns 53-bit uniform in (0,1)
 
-   double oct_randu(void)       returns M-bit uniform in (0,1)
-   double oct_randn(void)       returns M-bit standard normal
-   double oct_rande(void)       returns N-bit standard exponential
+   double oct_randu (void)       returns M-bit uniform in (0,1)
+   double oct_randn (void)       returns M-bit standard normal
+   double oct_rande (void)       returns N-bit standard exponential
+
+   float oct_float_randu (void)       returns M-bit uniform in (0,1)
+   float oct_float_randn (void)       returns M-bit standard normal
+   float oct_float_rande (void)       returns N-bit standard exponential
 
    === Array generators ===
-   void oct_fill_randi32(octave_idx_type, uint32_t [])
-   void oct_fill_randi64(octave_idx_type, uint64_t [])
-   void oct_fill_randu(octave_idx_type, double [])
-   void oct_fill_randn(octave_idx_type, double [])
-   void oct_fill_rande(octave_idx_type, double [])
+   void oct_fill_randi32 (octave_idx_type, uint32_t [])
+   void oct_fill_randi64 (octave_idx_type, uint64_t [])
 
+   void oct_fill_randu (octave_idx_type, double [])
+   void oct_fill_randn (octave_idx_type, double [])
+   void oct_fill_rande (octave_idx_type, double [])
+
+   void oct_fill_float_randu (octave_idx_type, float [])
+   void oct_fill_float_randn (octave_idx_type, float [])
+   void oct_fill_float_rande (octave_idx_type, float [])
 */
 
 #if defined (HAVE_CONFIG_H)
@@ -157,9 +166,9 @@
 #include "lo-math.h"
 #include "randmtzig.h"
 
-/* FIXME may want to suppress X86 if sizeof(long)>4 */
-#if !defined(USE_X86_32)
-# if defined(i386) || defined(HAVE_X86_32)
+/* FIXME may want to suppress X86 if sizeof(long) > 4 */
+#if !defined (USE_X86_32)
+# if defined (i386) || defined (HAVE_X86_32)
 #  define USE_X86_32 1
 # else
 #  define USE_X86_32 0
@@ -180,6 +189,7 @@
 static int left = 1;
 static int initf = 0;
 static int initt = 1;
+static int inittf = 1;
 
 /* initializes state[MT_N] with a seed */
 void
@@ -250,34 +260,34 @@
     int n = 0;
 
     /* Look for entropy in /dev/urandom */
-    FILE* urandom =fopen("/dev/urandom", "rb");
+    FILE* urandom = fopen ("/dev/urandom", "rb");
     if (urandom)
       {
         while (n < MT_N)
           {
             unsigned char word[4];
-            if (fread(word, 4, 1, urandom) != 1)
+            if (fread (word, 4, 1, urandom) != 1)
               break;
             entropy[n++] = word[0]+(word[1]<<8)+(word[2]<<16)+(word[3]<<24);
           }
-        fclose(urandom);
+        fclose (urandom);
       }
 
     /* If there isn't enough entropy, gather some from various sources */
     if (n < MT_N)
-      entropy[n++] = time(NULL); /* Current time in seconds */
+      entropy[n++] = time (NULL); /* Current time in seconds */
     if (n < MT_N)
-      entropy[n++] = clock();    /* CPU time used (usec) */
+      entropy[n++] = clock ();    /* CPU time used (usec) */
 #ifdef HAVE_GETTIMEOFDAY
     if (n < MT_N)
       {
         struct timeval tv;
-        if (gettimeofday(&tv, NULL) != -1)
+        if (gettimeofday (&tv, NULL) != -1)
           entropy[n++] = tv.tv_usec;   /* Fractional part of current time */
       }
 #endif
     /* Send all the entropy into the initial state vector */
-    oct_init_by_array(entropy,n);
+    oct_init_by_array (entropy,n);
 }
 
 void
@@ -310,7 +320,7 @@
   /* if (initf==0) init_by_int(5489UL); */
   /* Or better yet, a random seed! */
   if (initf == 0)
-    oct_init_by_entropy();
+    oct_init_by_entropy ();
 
   left = MT_N;
   next = state;
@@ -331,7 +341,7 @@
   register uint32_t y;
 
   if (--left == 0)
-    next_state();
+    next_state ();
   y = *next++;
 
   /* Tempering */
@@ -349,8 +359,8 @@
 static uint64_t
 randi53 (void)
 {
-  const uint32_t lo = randi32();
-  const uint32_t hi = randi32()&0x1FFFFF;
+  const uint32_t lo = randi32 ();
+  const uint32_t hi = randi32 ()&0x1FFFFF;
 #if HAVE_X86_32
   uint64_t u;
   uint32_t *p = (uint32_t *)&u;
@@ -365,8 +375,8 @@
 static uint64_t
 randi54 (void)
 {
-  const uint32_t lo = randi32();
-  const uint32_t hi = randi32()&0x3FFFFF;
+  const uint32_t lo = randi32 ();
+  const uint32_t hi = randi32 ()&0x3FFFFF;
 #if HAVE_X86_32
   uint64_t u;
   uint32_t *p = (uint32_t *)&u;
@@ -378,71 +388,38 @@
 #endif
 }
 
-#if 0
-// FIXME -- this doesn't seem to be used anywhere; should it be removed?
-static uint64_t
-randi64 (void)
-{
-  const uint32_t lo = randi32();
-  const uint32_t hi = randi32();
-#if HAVE_X86_32
-  uint64_t u;
-  uint32_t *p = (uint32_t *)&u;
-  p[0] = lo;
-  p[1] = hi;
-  return u;
-#else
-  return (((uint64_t)hi<<32)|lo);
-#endif
-}
-#endif
-
-#ifdef ALLBITS
 /* generates a random number on (0,1)-real-interval */
-static double
+static float
 randu32 (void)
 {
-  return ((double)randi32() + 0.5) * (1.0/4294967296.0);
+  return ((float)randi32 () + 0.5) * (1.0/4294967296.0);
   /* divided by 2^32 */
 }
-#else
+
 /* generates a random number on (0,1) with 53-bit resolution */
 static double
 randu53 (void)
 {
-  const uint32_t a=randi32()>>5;
-  const uint32_t b=randi32()>>6;
+  const uint32_t a = randi32 ()>>5;
+  const uint32_t b = randi32 ()>>6;
   return (a*67108864.0+b+0.4) * (1.0/9007199254740992.0);
 }
-#endif
 
 /* Determine mantissa for uniform doubles */
 double
 oct_randu (void)
 {
-#ifdef ALLBITS
+  return randu53 ();
+}
+
+/* Determine mantissa for uniform floats */
+float
+oct_float_randu (void)
+{
   return randu32 ();
-#else
-  return randu53 ();
-#endif
 }
 
 /* ===== Ziggurat normal and exponential generators ===== */
-#ifdef ALLBITS
-# define ZIGINT uint32_t
-# define EMANTISSA 4294967296.0 /* 32 bit mantissa */
-# define ERANDI randi32() /* 32 bits for mantissa */
-# define NMANTISSA 2147483648.0 /* 31 bit mantissa */
-# define NRANDI randi32() /* 31 bits for mantissa + 1 bit sign */
-# define RANDU randu32()
-#else
-# define ZIGINT uint64_t
-# define EMANTISSA 9007199254740992.0  /* 53 bit mantissa */
-# define ERANDI randi53() /* 53 bits for mantissa */
-# define NMANTISSA EMANTISSA
-# define NRANDI randi54() /* 53 bits for mantissa + 1 bit sign */
-# define RANDU randu53()
-#endif
 
 #define ZIGGURAT_TABLE_SIZE 256
 
@@ -454,6 +431,13 @@
 #define ZIGGURAT_EXP_INV_R 0.129918765548341586
 #define EXP_SECTION_AREA 0.0039496598225815571993
 
+#define ZIGINT uint64_t
+#define EMANTISSA 9007199254740992.0  /* 53 bit mantissa */
+#define ERANDI randi53() /* 53 bits for mantissa */
+#define NMANTISSA EMANTISSA
+#define NRANDI randi54() /* 53 bits for mantissa + 1 bit sign */
+#define RANDU randu53()
+
 static ZIGINT ki[ZIGGURAT_TABLE_SIZE];
 static double wi[ZIGGURAT_TABLE_SIZE], fi[ZIGGURAT_TABLE_SIZE];
 static ZIGINT ke[ZIGGURAT_TABLE_SIZE];
@@ -522,7 +506,7 @@
       /* New x is given by x = f^{-1}(v/x_{i+1} + f(x_{i+1})), thus
        * need inverse operator of y = exp(-0.5*x*x) -> x = sqrt(-2*ln(y))
        */
-      x = sqrt(-2. * log(NOR_SECTION_AREA / x1 + fi[i+1]));
+      x = sqrt (-2. * log (NOR_SECTION_AREA / x1 + fi[i+1]));
       ki[i+1] = (ZIGINT)(x / x1 * NMANTISSA);
       wi[i] = x / NMANTISSA;
       fi[i] = exp (-0.5 * x * x);
@@ -550,7 +534,7 @@
       /* New x is given by x = f^{-1}(v/x_{i+1} + f(x_{i+1})), thus
        * need inverse operator of y = exp(-x) -> x = -ln(y)
        */
-      x = - log(EXP_SECTION_AREA / x1 + fe[i+1]);
+      x = - log (EXP_SECTION_AREA / x1 + fe[i+1]);
       ke[i+1] = (ZIGINT)(x / x1 * EMANTISSA);
       we[i] = x / EMANTISSA;
       fe[i] = exp (-x);
@@ -580,7 +564,7 @@
 oct_randn (void)
 {
   if (initt)
-    create_ziggurat_tables();
+    create_ziggurat_tables ();
 
   while (1)
     {
@@ -592,7 +576,6 @@
        * Of course, different compilers and operating systems may
        * have something to do with this.
        */
-#if !defined(ALLBITS)
 # if HAVE_X86_32
       /* 53-bit mantissa, 1-bit sign, x86 32-bit architecture */
       double x;
@@ -600,9 +583,9 @@
       register uint32_t lo, hi;
       int64_t rabs;
       uint32_t *p = (uint32_t *)&rabs;
-      lo = randi32();
+      lo = randi32 ();
       idx = lo&0xFF;
-      hi = randi32();
+      hi = randi32 ();
       si = hi&UMASK;
       p[0] = lo;
       p[1] = hi&0x1FFFFF;
@@ -610,19 +593,11 @@
 # else /* !HAVE_X86_32 */
       /* arbitrary mantissa (selected by NRANDI, with 1 bit for sign) */
       const uint64_t r = NRANDI;
-      const int64_t rabs=r>>1;
+      const int64_t rabs = r>>1;
       const int idx = (int)(rabs&0xFF);
       const double x = ( r&1 ? -rabs : rabs) * wi[idx];
 # endif /* !HAVE_X86_32 */
       if (rabs < (int64_t)ki[idx])
-#else /* ALLBITS */
-      /* 32-bit mantissa */
-      const uint32_t r = randi32();
-      const uint32_t rabs = r&LMASK;
-      const int idx = (int)(r&0xFF);
-      const double x = ((int32_t)r) * wi[idx];
-      if (rabs < ki[idx])
-#endif /* ALLBITS */
         return x;        /* 99.3% of the time we return here 1st try */
       else if (idx == 0)
         {
@@ -645,7 +620,7 @@
           while ( yy+yy <= xx*xx);
           return (rabs&0x100 ? -ZIGGURAT_NOR_R-xx : ZIGGURAT_NOR_R+xx);
         }
-      else if ((fi[idx-1] - fi[idx]) * RANDU + fi[idx] < exp(-0.5*x*x))
+      else if ((fi[idx-1] - fi[idx]) * RANDU + fi[idx] < exp (-0.5*x*x))
         return x;
     }
 }
@@ -654,7 +629,7 @@
 oct_rande (void)
 {
   if (initt)
-    create_ziggurat_tables();
+    create_ziggurat_tables ();
 
   while (1)
     {
@@ -662,7 +637,7 @@
       const int idx = (int)(ri & 0xFF);
       const double x = ri * we[idx];
       if (ri < ke[idx])
-        return x;               // 98.9% of the time we return here 1st try
+        return x;               /* 98.9% of the time we return here 1st try */
       else if (idx == 0)
         {
           /* As stated in Marsaglia and Tsang
@@ -670,9 +645,176 @@
            * For the exponential tail, the method of Marsaglia[5] provides:
            * x = r - ln(U);
            */
-          return ZIGGURAT_EXP_R - log(RANDU);
+          return ZIGGURAT_EXP_R - log (RANDU);
         }
-      else if ((fe[idx-1] - fe[idx]) * RANDU + fe[idx] < exp(-x))
+      else if ((fe[idx-1] - fe[idx]) * RANDU + fe[idx] < exp (-x))
+        return x;
+    }
+}
+
+#undef ZIGINT
+#undef EMANTISSA
+#undef ERANDI
+#undef NMANTISSA
+#undef NRANDI
+#undef RANDU
+
+#define ZIGINT uint32_t
+#define EMANTISSA 4294967296.0 /* 32 bit mantissa */
+#define ERANDI randi32() /* 32 bits for mantissa */
+#define NMANTISSA 2147483648.0 /* 31 bit mantissa */
+#define NRANDI randi32() /* 31 bits for mantissa + 1 bit sign */
+#define RANDU randu32()
+
+static ZIGINT fki[ZIGGURAT_TABLE_SIZE];
+static float fwi[ZIGGURAT_TABLE_SIZE], ffi[ZIGGURAT_TABLE_SIZE];
+static ZIGINT fke[ZIGGURAT_TABLE_SIZE];
+static float fwe[ZIGGURAT_TABLE_SIZE], ffe[ZIGGURAT_TABLE_SIZE];
+
+
+static void
+create_ziggurat_float_tables (void)
+{
+  int i;
+  float x, x1;
+
+  /* Ziggurat tables for the normal distribution */
+  x1 = ZIGGURAT_NOR_R;
+  fwi[255] = x1 / NMANTISSA;
+  ffi[255] = exp (-0.5 * x1 * x1);
+
+  /* Index zero is special for tail strip, where Marsaglia and Tsang
+   * defines this as
+   * k_0 = 2^31 * r * f(r) / v, w_0 = 0.5^31 * v / f(r), f_0 = 1,
+   * where v is the area of each strip of the ziggurat.
+   */
+  fki[0] = (ZIGINT) (x1 * ffi[255] / NOR_SECTION_AREA * NMANTISSA);
+  fwi[0] = NOR_SECTION_AREA / ffi[255] / NMANTISSA;
+  ffi[0] = 1.;
+
+  for (i = 254; i > 0; i--)
+    {
+      /* New x is given by x = f^{-1}(v/x_{i+1} + f(x_{i+1})), thus
+       * need inverse operator of y = exp(-0.5*x*x) -> x = sqrt(-2*ln(y))
+       */
+      x = sqrt (-2. * log (NOR_SECTION_AREA / x1 + ffi[i+1]));
+      fki[i+1] = (ZIGINT)(x / x1 * NMANTISSA);
+      fwi[i] = x / NMANTISSA;
+      ffi[i] = exp (-0.5 * x * x);
+      x1 = x;
+    }
+
+  fki[1] = 0;
+
+  /* Zigurrat tables for the exponential distribution */
+  x1 = ZIGGURAT_EXP_R;
+  fwe[255] = x1 / EMANTISSA;
+  ffe[255] = exp (-x1);
+
+  /* Index zero is special for tail strip, where Marsaglia and Tsang
+   * defines this as
+   * k_0 = 2^32 * r * f(r) / v, w_0 = 0.5^32 * v / f(r), f_0 = 1,
+   * where v is the area of each strip of the ziggurat.
+   */
+  fke[0] = (ZIGINT) (x1 * ffe[255] / EXP_SECTION_AREA * EMANTISSA);
+  fwe[0] = EXP_SECTION_AREA / ffe[255] / EMANTISSA;
+  ffe[0] = 1.;
+
+  for (i = 254; i > 0; i--)
+    {
+      /* New x is given by x = f^{-1}(v/x_{i+1} + f(x_{i+1})), thus
+       * need inverse operator of y = exp(-x) -> x = -ln(y)
+       */
+      x = - log (EXP_SECTION_AREA / x1 + ffe[i+1]);
+      fke[i+1] = (ZIGINT)(x / x1 * EMANTISSA);
+      fwe[i] = x / EMANTISSA;
+      ffe[i] = exp (-x);
+      x1 = x;
+    }
+  fke[1] = 0;
+
+  inittf = 0;
+}
+
+/*
+ * Here is the guts of the algorithm. As Marsaglia and Tsang state the
+ * algorithm in their paper
+ *
+ * 1) Calculate a random signed integer j and let i be the index
+ *     provided by the rightmost 8-bits of j
+ * 2) Set x = j * w_i. If j < k_i return x
+ * 3) If i = 0, then return x from the tail
+ * 4) If [f(x_{i-1}) - f(x_i)] * U < f(x) - f(x_i), return x
+ * 5) goto step 1
+ *
+ * Where f is the functional form of the distribution, which for a normal
+ * distribution is exp(-0.5*x*x)
+ */
+
+float
+oct_float_randn (void)
+{
+  if (inittf)
+    create_ziggurat_float_tables ();
+
+  while (1)
+    {
+      /* 32-bit mantissa */
+      const uint32_t r = randi32 ();
+      const uint32_t rabs = r&LMASK;
+      const int idx = (int)(r&0xFF);
+      const float x = ((int32_t)r) * fwi[idx];
+      if (rabs < fki[idx])
+        return x;        /* 99.3% of the time we return here 1st try */
+      else if (idx == 0)
+        {
+          /* As stated in Marsaglia and Tsang
+           *
+           * For the normal tail, the method of Marsaglia[5] provides:
+           * generate x = -ln(U_1)/r, y = -ln(U_2), until y+y > x*x,
+           * then return r+x. Except that r+x is always in the positive
+           * tail!!!! Any thing random might be used to determine the
+           * sign, but as we already have r we might as well use it
+           *
+           * [PAK] but not the bottom 8 bits, since they are all 0 here!
+           */
+          float xx, yy;
+          do
+            {
+              xx = - ZIGGURAT_NOR_INV_R * log (RANDU);
+              yy = - log (RANDU);
+            }
+          while ( yy+yy <= xx*xx);
+          return (rabs&0x100 ? -ZIGGURAT_NOR_R-xx : ZIGGURAT_NOR_R+xx);
+        }
+      else if ((ffi[idx-1] - ffi[idx]) * RANDU + ffi[idx] < exp (-0.5*x*x))
+        return x;
+    }
+}
+
+float
+oct_float_rande (void)
+{
+  if (inittf)
+    create_ziggurat_float_tables ();
+
+  while (1)
+    {
+      ZIGINT ri = ERANDI;
+      const int idx = (int)(ri & 0xFF);
+      const float x = ri * fwe[idx];
+      if (ri < fke[idx])
+        return x;               /* 98.9% of the time we return here 1st try */
+      else if (idx == 0)
+        {
+          /* As stated in Marsaglia and Tsang
+           *
+           * For the exponential tail, the method of Marsaglia[5] provides:
+           * x = r - ln(U);
+           */
+          return ZIGGURAT_EXP_R - log (RANDU);
+        }
+      else if ((ffe[idx-1] - ffe[idx]) * RANDU + ffe[idx] < exp (-x))
         return x;
     }
 }
@@ -683,7 +825,7 @@
 {
   octave_idx_type i;
   for (i = 0; i < n; i++)
-    p[i] = oct_randu();
+    p[i] = oct_randu ();
 }
 
 void
@@ -691,7 +833,7 @@
 {
   octave_idx_type i;
   for (i = 0; i < n; i++)
-    p[i] = oct_randn();
+    p[i] = oct_randn ();
 }
 
 void
@@ -699,5 +841,29 @@
 {
   octave_idx_type i;
   for (i = 0; i < n; i++)
-    p[i] = oct_rande();
+    p[i] = oct_rande ();
+}
+
+void
+oct_fill_float_randu (octave_idx_type n, float *p)
+{
+  octave_idx_type i;
+  for (i = 0; i < n; i++)
+    p[i] = oct_float_randu ();
 }
+
+void
+oct_fill_float_randn (octave_idx_type n, float *p)
+{
+  octave_idx_type i;
+  for (i = 0; i < n; i++)
+    p[i] = oct_float_randn ();
+}
+
+void
+oct_fill_float_rande (octave_idx_type n, float *p)
+{
+  octave_idx_type i;
+  for (i = 0; i < n; i++)
+    p[i] = oct_float_rande ();
+}
rename from liboctave/randmtzig.h
rename to liboctave/numeric/randmtzig.h
--- a/liboctave/randmtzig.h
+++ b/liboctave/numeric/randmtzig.h
@@ -82,11 +82,19 @@
 extern OCTAVE_API double oct_randn (void);
 extern OCTAVE_API double oct_rande (void);
 
+extern OCTAVE_API float oct_float_randu (void);
+extern OCTAVE_API float oct_float_randn (void);
+extern OCTAVE_API float oct_float_rande (void);
+
 /* === Array generators === */
 extern OCTAVE_API void oct_fill_randu (octave_idx_type n, double *p);
 extern OCTAVE_API void oct_fill_randn (octave_idx_type n, double *p);
 extern OCTAVE_API void oct_fill_rande (octave_idx_type n, double *p);
 
+extern OCTAVE_API void oct_fill_float_randu (octave_idx_type n, float *p);
+extern OCTAVE_API void oct_fill_float_randn (octave_idx_type n, float *p);
+extern OCTAVE_API void oct_fill_float_rande (octave_idx_type n, float *p);
+
 #ifdef  __cplusplus
 }
 #endif
rename from liboctave/randpoisson.c
rename to liboctave/numeric/randpoisson.c
--- a/liboctave/randpoisson.c
+++ b/liboctave/numeric/randpoisson.c
@@ -105,7 +105,7 @@
     {
       r  = 1.0 / k;
       rr = r * r;
-      return ((k + 0.5)*log(k) - k + C0 + r*(C1 + rr*(C3 + rr*(C5 + rr*C7))));
+      return ((k + 0.5)*log (k) - k + C0 + r*(C1 + rr*(C3 + rr*(C5 + rr*C7))));
     }
   else
     return (logfak[(int)k]);
@@ -146,7 +146,7 @@
 static double
 f (double k, double l_nu, double c_pm)
 {
-  return exp(k * l_nu - flogfak(k) - c_pm);
+  return exp (k * l_nu - flogfak (k) - c_pm);
 }
 
 static double
@@ -163,13 +163,13 @@
     {                               /* set-up           */
       my_last = my;
       /* approximate deviation of reflection points k2, k4 from my - 1/2 */
-      Ds = sqrt(my + 0.25);
+      Ds = sqrt (my + 0.25);
 
       /* mode m, reflection points k2 and k4, and points k1 and k5,      */
       /* which delimit the centre region of h(x)                         */
-      m  = floor(my);
-      k2 = ceil(my - 0.5 - Ds);
-      k4 = floor(my - 0.5 + Ds);
+      m  = floor (my);
+      k2 = ceil (my - 0.5 - Ds);
+      k4 = floor (my - 0.5 + Ds);
       k1 = k2 + k2 - m + 1L;
       k5 = k4 + k4 - m;
 
@@ -184,18 +184,18 @@
       r5 = my / (k5 + 1.0);
 
       /* reciprocal values of the scale parameters of exp. tail envelope */
-      ll =  log(r1);                                 /* expon. tail left */
-      lr = -log(r5);                                 /* expon. tail right*/
+      ll =  log (r1);                                /* expon. tail left */
+      lr = -log (r5);                                /* expon. tail right*/
 
       /* Poisson constants, necessary for computing function values f(k) */
-      l_my = log(my);
-      c_pm = m * l_my - flogfak(m);
+      l_my = log (my);
+      c_pm = m * l_my - flogfak (m);
 
       /* function values f(k) = p(k)/p(m) at k = k2, k4, k1, k5          */
-      f2 = f(k2, l_my, c_pm);
-      f4 = f(k4, l_my, c_pm);
-      f1 = f(k1, l_my, c_pm);
-      f5 = f(k5, l_my, c_pm);
+      f2 = f (k2, l_my, c_pm);
+      f4 = f (k4, l_my, c_pm);
+      f1 = f (k1, l_my, c_pm);
+      f5 = f (k5, l_my, c_pm);
 
       /* area of the two centre and the two exponential tail regions     */
       /* area of the two immediate acceptance regions between k2, k4     */
@@ -216,26 +216,26 @@
 
           /* immediate acceptance region
              R2 = [k2, m) *[0, f2),  X = k2, ... m -1 */
-          if ((V = U - p1) < 0.0)  return(k2 + floor(U/f2));
+          if ((V = U - p1) < 0.0)  return (k2 + floor (U/f2));
           /* immediate acceptance region
              R1 = [k1, k2)*[0, f1),  X = k1, ... k2-1 */
-          if ((W = V / dl) < f1 )  return(k1 + floor(V/f1));
+          if ((W = V / dl) < f1 )  return (k1 + floor (V/f1));
 
           /* computation of candidate X < k2, and its counterpart Y > k2 */
           /* either squeeze-acceptance of X or acceptance-rejection of Y */
-          Dk = floor(dl * RUNI) + 1.0;
+          Dk = floor (dl * RUNI) + 1.0;
           if (W <= f2 - Dk * (f2 - f2/r2))
             {                                        /* quick accept of  */
-              return(k2 - Dk);                       /* X = k2 - Dk      */
+              return (k2 - Dk);                      /* X = k2 - Dk      */
             }
           if ((V = f2 + f2 - W) < 1.0)
             {                                        /* quick reject of Y*/
               Y = k2 + Dk;
               if (V <= f2 + Dk * (1.0 - f2)/(dl + 1.0))
                 {                                    /* quick accept of  */
-                  return(Y);                         /* Y = k2 + Dk      */
+                  return (Y);                        /* Y = k2 + Dk      */
                 }
-              if (V <= f(Y, l_my, c_pm))  return(Y); /* final accept of Y*/
+              if (V <= f (Y, l_my, c_pm))  return (Y); /* final accept of Y*/
             }
           X = k2 - Dk;
         }
@@ -243,26 +243,26 @@
         {                                            /* centre right     */
           /*  immediate acceptance region
               R3 = [m, k4+1)*[0, f4), X = m, ... k4    */
-          if ((V = U - p3) < 0.0)  return(k4 - floor((U - p2)/f4));
+          if ((V = U - p3) < 0.0)  return (k4 - floor ((U - p2)/f4));
           /* immediate acceptance region
              R4 = [k4+1, k5+1)*[0, f5)                */
-          if ((W = V / dr) < f5 )  return(k5 - floor(V/f5));
+          if ((W = V / dr) < f5 )  return (k5 - floor (V/f5));
 
           /* computation of candidate X > k4, and its counterpart Y < k4 */
           /* either squeeze-acceptance of X or acceptance-rejection of Y */
-          Dk = floor(dr * RUNI) + 1.0;
+          Dk = floor (dr * RUNI) + 1.0;
           if (W <= f4 - Dk * (f4 - f4*r4))
             {                                        /* quick accept of  */
-              return(k4 + Dk);                       /* X = k4 + Dk      */
+              return (k4 + Dk);                      /* X = k4 + Dk      */
             }
           if ((V = f4 + f4 - W) < 1.0)
             {                                        /* quick reject of Y*/
               Y = k4 - Dk;
               if (V <= f4 + Dk * (1.0 - f4)/ dr)
                 {                                    /* quick accept of  */
-                  return(Y);                         /* Y = k4 - Dk      */
+                  return (Y);                        /* Y = k4 - Dk      */
                 }
-              if (V <= f(Y, l_my, c_pm))  return(Y); /* final accept of Y*/
+              if (V <= f (Y, l_my, c_pm))  return (Y); /* final accept of Y*/
             }
           X = k4 + Dk;
         }
@@ -271,26 +271,26 @@
           W = RUNI;
           if (U < p5)
             {                                        /* expon. tail left */
-              Dk = floor(1.0 - log(W)/ll);
+              Dk = floor (1.0 - log (W)/ll);
               if ((X = k1 - Dk) < 0L)  continue;     /* 0 <= X <= k1 - 1 */
               W *= (U - p4) * ll;                    /* W -- U(0, h(x))  */
               if (W <= f1 - Dk * (f1 - f1/r1))
-                return(X);                           /* quick accept of X*/
+                return (X);                          /* quick accept of X*/
             }
           else
             {                                        /* expon. tail right*/
-              Dk = floor(1.0 - log(W)/lr);
+              Dk = floor (1.0 - log (W)/lr);
               X  = k5 + Dk;                          /* X >= k5 + 1      */
               W *= (U - p5) * lr;                    /* W -- U(0, h(x))  */
               if (W <= f5 - Dk * (f5 - f5*r5))
-                return(X);                           /* quick accept of X*/
+                return (X);                          /* quick accept of X*/
             }
         }
 
       /* acceptance-rejection test of candidate X from the original area */
       /* test, whether  W <= f(k),    with  W = U*h(x)  and  U -- U(0, 1)*/
       /* log f(X) = (X - m)*log(my) - log X! + log m!                    */
-      if (log(W) <= X * l_my - flogfak(X) - c_pm)  return(X);
+      if (log (W) <= X * l_my - flogfak (X) - c_pm)  return (X);
     }
 }
 /* ---- pprsc.c end ------ */
@@ -300,7 +300,7 @@
 
 /* Given uniform u, find x such that CDF(L,x)==u.  Return x. */
 static void
-poisson_cdf_lookup(double lambda, double *p, size_t n)
+poisson_cdf_lookup (double lambda, double *p, size_t n)
 {
   /* Table size is predicated on the maximum value of lambda
    * we want to store in the table, and the maximum value of
@@ -316,12 +316,12 @@
 
   /* Precompute the table for the u up to and including 0.458.
    * We will almost certainly need it. */
-  int intlambda = (int)floor(lambda);
+  int intlambda = (int)floor (lambda);
   double P;
   int tableidx;
   size_t i = n;
 
-  t[0] = P = exp(-lambda);
+  t[0] = P = exp (-lambda);
   for (tableidx = 1; tableidx <= intlambda; tableidx++) {
     P = P*lambda/(double)tableidx;
     t[tableidx] = t[tableidx-1] + P;
@@ -368,12 +368,52 @@
   }
 }
 
+static void
+poisson_cdf_lookup_float (double lambda, float *p, size_t n)
+{
+  double t[TABLESIZE];
+
+  /* Precompute the table for the u up to and including 0.458.
+   * We will almost certainly need it. */
+  int intlambda = (int)floor (lambda);
+  double P;
+  int tableidx;
+  size_t i = n;
+
+  t[0] = P = exp (-lambda);
+  for (tableidx = 1; tableidx <= intlambda; tableidx++) {
+    P = P*lambda/(double)tableidx;
+    t[tableidx] = t[tableidx-1] + P;
+  }
+
+  while (i-- > 0) {
+    double u = RUNI;
+    int k = (u > 0.458 ? intlambda : 0);
+  nextk:
+    if ( u <= t[k] ) {
+      p[i] = (float) k;
+      continue;
+    }
+    if (++k < tableidx) goto nextk;
+
+    while (tableidx < TABLESIZE) {
+      P = P*lambda/(double)tableidx;
+      t[tableidx] = t[tableidx-1] + P;
+      if (t[tableidx] == t[tableidx-1]) t[tableidx] = 1.0;
+      tableidx++;
+      if (u <= t[tableidx-1]) break;
+    }
+
+    p[i] = (float)(tableidx-1);
+  }
+}
+
 /* From Press, et al., Numerical Recipes */
 static void
 poisson_rejection (double lambda, double *p, size_t n)
 {
-  double sq = sqrt(2.0*lambda);
-  double alxm = log(lambda);
+  double sq = sqrt (2.0*lambda);
+  double alxm = log (lambda);
   double g = lambda*alxm - LGAMMA(lambda+1.0);
   size_t i;
 
@@ -382,11 +422,35 @@
       double y, em, t;
       do {
         do {
-          y = tan(M_PI*RUNI);
+          y = tan (M_PI*RUNI);
           em = sq * y + lambda;
         } while (em < 0.0);
-        em = floor(em);
-        t = 0.9*(1.0+y*y)*exp(em*alxm-flogfak(em)-g);
+        em = floor (em);
+        t = 0.9*(1.0+y*y)*exp (em*alxm-flogfak (em)-g);
+      } while (RUNI > t);
+      p[i] = em;
+    }
+}
+
+/* From Press, et al., Numerical Recipes */
+static void
+poisson_rejection_float (double lambda, float *p, size_t n)
+{
+  double sq = sqrt (2.0*lambda);
+  double alxm = log (lambda);
+  double g = lambda*alxm - LGAMMA(lambda+1.0);
+  size_t i;
+
+  for (i = 0; i < n; i++)
+    {
+      double y, em, t;
+      do {
+        do {
+          y = tan (M_PI*RUNI);
+          em = sq * y + lambda;
+        } while (em < 0.0);
+        em = floor (em);
+        t = 0.9*(1.0+y*y)*exp (em*alxm-flogfak (em)-g);
       } while (RUNI > t);
       p[i] = em;
     }
@@ -413,20 +477,20 @@
     }
   else if (L <= 10.0)
     {
-      poisson_cdf_lookup(L, p, n);
+      poisson_cdf_lookup (L, p, n);
     }
   else if (L <= 1e8)
     {
       for (i=0; i<n; i++)
-        p[i] = pprsc(L);
+        p[i] = pprsc (L);
     }
   else
     {
       /* normal approximation: from Phys. Rev. D (1994) v50 p1284 */
-      const double sqrtL = sqrt(L);
+      const double sqrtL = sqrt (L);
       for (i = 0; i < n; i++)
         {
-          p[i] = floor(RNOR*sqrtL + L + 0.5);
+          p[i] = floor (RNOR*sqrtL + L + 0.5);
           if (p[i] < 0.0)
             p[i] = 0.0; /* will probably never happen */
         }
@@ -441,7 +505,7 @@
   if (L < 0.0) ret = NAN;
   else if (L <= 12.0) {
     /* From Press, et al. Numerical recipes */
-    double g = exp(-L);
+    double g = exp (-L);
     int em = -1;
     double t = 1.0;
     do {
@@ -451,15 +515,80 @@
     ret = em;
   } else if (L <= 1e8) {
     /* numerical recipes */
-    poisson_rejection(L, &ret, 1);
+    poisson_rejection (L, &ret, 1);
   } else if (INFINITE(L)) {
     /* FIXME R uses NaN, but the normal approx. suggests that as
      * limit should be inf. Which is correct? */
     ret = NAN;
   } else {
     /* normal approximation: from Phys. Rev. D (1994) v50 p1284 */
-    ret = floor(RNOR*sqrt(L) + L + 0.5);
+    ret = floor (RNOR*sqrt (L) + L + 0.5);
     if (ret < 0.0) ret = 0.0; /* will probably never happen */
   }
   return ret;
 }
+
+/* Generate a set of poisson numbers with the same distribution */
+void
+oct_fill_float_randp (float FL, octave_idx_type n, float *p)
+{
+  double L = FL;
+  octave_idx_type i;
+  if (L < 0.0 || INFINITE(L))
+    {
+      for (i=0; i<n; i++)
+        p[i] = NAN;
+    }
+  else if (L <= 10.0)
+    {
+      poisson_cdf_lookup_float (L, p, n);
+    }
+  else if (L <= 1e8)
+    {
+      for (i=0; i<n; i++)
+        p[i] = pprsc (L);
+    }
+  else
+    {
+      /* normal approximation: from Phys. Rev. D (1994) v50 p1284 */
+      const double sqrtL = sqrt (L);
+      for (i = 0; i < n; i++)
+        {
+          p[i] = floor (RNOR*sqrtL + L + 0.5);
+          if (p[i] < 0.0)
+            p[i] = 0.0; /* will probably never happen */
+        }
+    }
+}
+
+/* Generate one poisson variate */
+float
+oct_float_randp (float FL)
+{
+  double L = FL;
+  float ret;
+  if (L < 0.0) ret = NAN;
+  else if (L <= 12.0) {
+    /* From Press, et al. Numerical recipes */
+    double g = exp (-L);
+    int em = -1;
+    double t = 1.0;
+    do {
+      ++em;
+      t *= RUNI;
+    } while (t > g);
+    ret = em;
+  } else if (L <= 1e8) {
+    /* numerical recipes */
+    poisson_rejection_float (L, &ret, 1);
+  } else if (INFINITE(L)) {
+    /* FIXME R uses NaN, but the normal approx. suggests that as
+     * limit should be inf. Which is correct? */
+    ret = NAN;
+  } else {
+    /* normal approximation: from Phys. Rev. D (1994) v50 p1284 */
+    ret = floor (RNOR*sqrt (L) + L + 0.5);
+    if (ret < 0.0) ret = 0.0; /* will probably never happen */
+  }
+  return ret;
+}
rename from liboctave/randpoisson.h
rename to liboctave/numeric/randpoisson.h
--- a/liboctave/randpoisson.h
+++ b/liboctave/numeric/randpoisson.h
@@ -32,6 +32,9 @@
 extern OCTAVE_API double oct_randp (double L);
 extern OCTAVE_API void oct_fill_randp (double L, octave_idx_type n, double *p);
 
+extern OCTAVE_API float oct_float_randp (float L);
+extern OCTAVE_API void oct_fill_float_randp (float L, octave_idx_type n, float *p);
+
 #ifdef  __cplusplus
 }
 #endif
rename from liboctave/sparse-base-chol.cc
rename to liboctave/numeric/sparse-base-chol.cc
--- a/liboctave/sparse-base-chol.cc
+++ b/liboctave/numeric/sparse-base-chol.cc
@@ -56,33 +56,34 @@
 
   for (k = 0; k < ncol; k++)
     {
-      p = Sp [k];
-      pend = Sp [k+1];
-      Sp [k] = pdest;
+      p = Sp[k];
+      pend = Sp[k+1];
+      Sp[k] = pdest;
       for (; p < pend; p++)
         {
-          sik = Sx [p];
+          sik = Sx[p];
           if (CHOLMOD_IS_NONZERO (sik))
             {
               if (p != pdest)
                 {
-                  Si [pdest] = Si [p];
-                  Sx [pdest] = sik;
+                  Si[pdest] = Si[p];
+                  Sx[pdest] = sik;
                 }
               pdest++;
             }
         }
     }
-  Sp [ncol] = pdest;
+  Sp[ncol] = pdest;
 }
 #endif
 
 template <class chol_type, class chol_elt, class p_type>
 octave_idx_type
 sparse_base_chol<chol_type, chol_elt, p_type>::sparse_base_chol_rep::init
-  (const chol_type& a, bool natural)
+  (const chol_type& a, bool natural, bool force)
 {
   volatile octave_idx_type info = 0;
+
 #ifdef HAVE_CHOLMOD
   octave_idx_type a_nr = a.rows ();
   octave_idx_type a_nc = a.cols ();
@@ -129,13 +130,13 @@
   ac->nrow = a_nr;
   ac->ncol = a_nc;
 
-  ac->p = a.cidx();
-  ac->i = a.ridx();
-  ac->nzmax = a.nnz();
+  ac->p = a.cidx ();
+  ac->i = a.ridx ();
+  ac->nzmax = a.nnz ();
   ac->packed = true;
   ac->sorted = true;
   ac->nz = 0;
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
   ac->itype = CHOLMOD_LONG;
 #else
   ac->itype = CHOLMOD_INT;
@@ -151,13 +152,13 @@
   if (a_nr < 1)
     ac->x = &dummy;
   else
-    ac->x = a.data();
+    ac->x = a.data ();
 
   // use natural ordering if no q output parameter
   if (natural)
     {
       cm->nmethods = 1 ;
-      cm->method [0].ordering = CHOLMOD_NATURAL ;
+      cm->method[0].ordering = CHOLMOD_NATURAL ;
       cm->postorder = false ;
     }
 
@@ -170,7 +171,7 @@
   is_pd = cm->status == CHOLMOD_OK;
   info = (is_pd ? 0 : cm->status);
 
-  if (is_pd)
+  if (is_pd || force)
     {
       BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
       cond = CHOLMOD_NAME(rcond) (Lfactor, cm);
@@ -224,20 +225,20 @@
 sparse_base_chol<chol_type, chol_elt, p_type>::L (void) const
 {
 #ifdef HAVE_CHOLMOD
-  cholmod_sparse *m = rep->L();
+  cholmod_sparse *m = rep->L ();
   octave_idx_type nc = m->ncol;
   octave_idx_type nnz = m->nzmax;
   chol_type ret (m->nrow, nc, nnz);
   for (octave_idx_type j = 0; j < nc+1; j++)
-    ret.xcidx(j) = static_cast<octave_idx_type *>(m->p)[j];
+    ret.xcidx (j) = static_cast<octave_idx_type *>(m->p)[j];
   for (octave_idx_type i = 0; i < nnz; i++)
     {
-      ret.xridx(i) = static_cast<octave_idx_type *>(m->i)[i];
-      ret.xdata(i) = static_cast<chol_elt *>(m->x)[i];
+      ret.xridx (i) = static_cast<octave_idx_type *>(m->i)[i];
+      ret.xdata (i) = static_cast<chol_elt *>(m->x)[i];
     }
   return ret;
 #else
-  return chol_type();
+  return chol_type ();
 #endif
 }
 
@@ -252,15 +253,15 @@
 
   for (octave_idx_type i = 0; i < n; i++)
     {
-      p.xcidx(i) = i;
-      p.xridx(i) = static_cast<octave_idx_type>(perms(i));
-      p.xdata(i) = 1;
+      p.xcidx (i) = i;
+      p.xridx (i) = static_cast<octave_idx_type>(perms (i));
+      p.xdata (i) = 1;
     }
-  p.xcidx(n) = n;
+  p.xcidx (n) = n;
 
   return p;
 #else
-  return p_type();
+  return p_type ();
 #endif
 }
 
@@ -270,19 +271,19 @@
 {
   chol_type retval;
 #ifdef HAVE_CHOLMOD
-  cholmod_sparse *m = rep->L();
+  cholmod_sparse *m = rep->L ();
   octave_idx_type n = m->ncol;
-  ColumnVector perms = rep->perm();
+  ColumnVector perms = rep->perm ();
   chol_type ret;
   double rcond2;
   octave_idx_type info;
   MatrixType mattype (MatrixType::Upper);
-  chol_type linv = L().hermitian().inverse(mattype, info, rcond2, 1, 0);
+  chol_type linv = L ().hermitian ().inverse (mattype, info, rcond2, 1, 0);
 
-  if (perms.length() == n)
+  if (perms.length () == n)
     {
-      p_type Qc = Q();
-      retval = Qc * linv * linv.hermitian() * Qc.transpose();
+      p_type Qc = Q ();
+      retval = Qc * linv * linv.hermitian () * Qc.transpose ();
     }
   else
     retval = linv * linv.hermitian ();
rename from liboctave/sparse-base-chol.h
rename to liboctave/numeric/sparse-base-chol.h
--- a/liboctave/sparse-base-chol.h
+++ b/liboctave/numeric/sparse-base-chol.h
@@ -41,19 +41,19 @@
         perms (), cond (0)
       { }
 
-    sparse_base_chol_rep (const chol_type& a, const bool natural)
+    sparse_base_chol_rep (const chol_type& a, bool natural, bool force)
       : count (1), Lsparse (0), Common (), is_pd (false), minor_p (0),
         perms (), cond (0)
       {
-        init (a, natural);
+        init (a, natural, force);
       }
 
     sparse_base_chol_rep (const chol_type& a, octave_idx_type& info,
-                          const bool natural)
+                          bool natural, bool force)
       : count (1), Lsparse (0), Common (), is_pd (false), minor_p (0),
         perms (), cond (0)
       {
-        info = init (a, natural);
+        info = init (a, natural, force);
       }
 
     ~sparse_base_chol_rep (void)
@@ -93,7 +93,7 @@
 
     double cond;
 
-    octave_idx_type init (const chol_type& a, bool natural = true);
+    octave_idx_type init (const chol_type& a, bool natural, bool force);
 
     void drop_zeros (const cholmod_sparse* S);
 
@@ -110,15 +110,18 @@
     sparse_base_chol_rep (void)
       : count (1), is_pd (false), minor_p (0), perms (), cond (0) { }
 
-    sparse_base_chol_rep (const chol_type& a,
-                          const bool natural)
+    sparse_base_chol_rep (const chol_type& a, bool natural, bool force)
       : count (1), is_pd (false), minor_p (0), perms (), cond (0)
-      { init (a, natural); }
+      {
+        init (a, natural, force);
+      }
 
     sparse_base_chol_rep (const chol_type& a, octave_idx_type& info,
-                          const bool natural)
+                          bool natural, bool force)
       : count (1), is_pd (false), minor_p (0), perms (), cond (0)
-      { info = init (a, natural); }
+      {
+        info = init (a, natural, force);
+      }
 
     ~sparse_base_chol_rep (void) { }
 
@@ -143,7 +146,7 @@
 
     double cond;
 
-    octave_idx_type init (const chol_type& a, bool natural = true);
+    octave_idx_type init (const chol_type& a, bool natural, bool force);
 
     // No copying!
 
@@ -163,13 +166,14 @@
            sparse_base_chol<chol_type, chol_elt, p_type>::sparse_base_chol_rep ())
     { }
 
-  sparse_base_chol (const chol_type& a, const bool n)
+  sparse_base_chol (const chol_type& a, bool natural, bool force)
     : rep (new typename
-           sparse_base_chol<chol_type, chol_elt, p_type>::sparse_base_chol_rep (a, n))
+           sparse_base_chol<chol_type, chol_elt, p_type>::sparse_base_chol_rep (a, natural, force))
     { }
 
-  sparse_base_chol (const chol_type& a, octave_idx_type& info, const bool n)
-    : rep (new typename sparse_base_chol<chol_type, chol_elt, p_type>::sparse_base_chol_rep (a, info, n))
+  sparse_base_chol (const chol_type& a, octave_idx_type& info,
+                    bool natural, bool force)
+    : rep (new typename sparse_base_chol<chol_type, chol_elt, p_type>::sparse_base_chol_rep (a, info, natural, force))
     { }
 
   sparse_base_chol (const sparse_base_chol<chol_type, chol_elt, p_type>& a)
@@ -198,18 +202,18 @@
 
   chol_type L (void) const;
 
-  chol_type R (void) const { return L().hermitian (); }
+  chol_type R (void) const { return L ().hermitian (); }
 
-  octave_idx_type P (void) const { return rep->P(); }
+  octave_idx_type P (void) const { return rep->P (); }
 
-  ColumnVector perm (void) const { return rep->perm(); }
+  ColumnVector perm (void) const { return rep->perm (); }
 
-  p_type Q (void) const { return rep->Q(); }
+  p_type Q (void) const { return rep->Q (); }
 
   bool is_positive_definite (void) const
-    { return rep->is_positive_definite(); }
+    { return rep->is_positive_definite (); }
 
-  double rcond (void) const { return rep->rcond(); }
+  double rcond (void) const { return rep->rcond (); }
 
   chol_type inverse (void) const;
 };
rename from liboctave/sparse-base-lu.cc
rename to liboctave/numeric/sparse-base-lu.cc
--- a/liboctave/sparse-base-lu.cc
+++ b/liboctave/numeric/sparse-base-lu.cc
@@ -35,28 +35,28 @@
   octave_idx_type nc = Ufact.rows ();
   octave_idx_type rcmin = (nr > nc ? nr : nc);
 
-  lu_type Yout (nr, nc, Lfact.nnz() + Ufact.nnz());
+  lu_type Yout (nr, nc, Lfact.nnz () + Ufact.nnz ());
   octave_idx_type ii = 0;
-  Yout.xcidx(0) = 0;
+  Yout.xcidx (0) = 0;
 
   for (octave_idx_type j = 0; j < nc; j++)
     {
-      for (octave_idx_type i = Ufact.cidx (j); i < Ufact.cidx(j + 1); i++)
+      for (octave_idx_type i = Ufact.cidx (j); i < Ufact.cidx (j + 1); i++)
         {
-          Yout.xridx (ii) = Ufact.ridx(i);
-          Yout.xdata (ii++) = Ufact.data(i);
+          Yout.xridx (ii) = Ufact.ridx (i);
+          Yout.xdata (ii++) = Ufact.data (i);
         }
       if (j < rcmin)
         {
           // Note the +1 skips the 1.0 on the diagonal
           for (octave_idx_type i = Lfact.cidx (j) + 1;
-               i < Lfact.cidx(j +1); i++)
+               i < Lfact.cidx (j +1); i++)
             {
-              Yout.xridx (ii) = Lfact.ridx(i);
-              Yout.xdata (ii++) = Lfact.data(i);
+              Yout.xridx (ii) = Lfact.ridx (i);
+              Yout.xdata (ii++) = Lfact.data (i);
             }
         }
-      Yout.xcidx(j + 1) = ii;
+      Yout.xcidx (j + 1) = ii;
     }
 
   return Yout;
rename from liboctave/sparse-base-lu.h
rename to liboctave/numeric/sparse-base-lu.h
rename from liboctave/sparse-dmsolve.cc
rename to liboctave/numeric/sparse-dmsolve.cc
--- a/liboctave/sparse-dmsolve.cc
+++ b/liboctave/numeric/sparse-dmsolve.cc
@@ -63,16 +63,16 @@
       nz = 0;
       for (octave_idx_type j = cst ; j < cend ; j++)
         {
-          octave_idx_type qq = (Q ? Q [j] : j);
+          octave_idx_type qq = (Q ? Q[j] : j);
           B.xcidx (j - cst) = nz;
-          for (octave_idx_type p = A.cidx(qq) ; p < A.cidx (qq+1) ; p++)
+          for (octave_idx_type p = A.cidx (qq) ; p < A.cidx (qq+1) ; p++)
             {
               octave_quit ();
-              octave_idx_type r = (Pinv ? Pinv [A.ridx (p)] : A.ridx (p));
+              octave_idx_type r = (Pinv ? Pinv[A.ridx (p)] : A.ridx (p));
               if (r >= rst && r < rend)
                 {
                   B.xdata (nz) = A.data (p);
-                  B.xridx (nz++) =  r - rst ;
+                  B.xridx (nz++) = r - rst ;
                 }
             }
         }
@@ -82,25 +82,25 @@
     {
       OCTAVE_LOCAL_BUFFER (T, X, rend - rst);
       octave_sort<octave_idx_type> sort;
-      octave_idx_type *ri = B.xridx();
+      octave_idx_type *ri = B.xridx ();
       nz = 0;
       for (octave_idx_type j = cst ; j < cend ; j++)
         {
-          octave_idx_type qq = (Q ? Q [j] : j);
+          octave_idx_type qq = (Q ? Q[j] : j);
           B.xcidx (j - cst) = nz;
-          for (octave_idx_type p = A.cidx(qq) ; p < A.cidx (qq+1) ; p++)
+          for (octave_idx_type p = A.cidx (qq) ; p < A.cidx (qq+1) ; p++)
             {
               octave_quit ();
-              octave_idx_type r = (Pinv ? Pinv [A.ridx (p)] : A.ridx (p));
+              octave_idx_type r = (Pinv ? Pinv[A.ridx (p)] : A.ridx (p));
               if (r >= rst && r < rend)
                 {
-                  X [r-rst] = A.data (p);
-                  B.xridx (nz++) =  r - rst ;
+                  X[r-rst] = A.data (p);
+                  B.xridx (nz++) = r - rst ;
                 }
             }
           sort.sort (ri + B.xcidx (j - cst), nz - B.xcidx (j - cst));
           for (octave_idx_type p = B.cidx (j - cst); p < nz; p++)
-            B.xdata (p) = X [B.xridx (p)];
+            B.xdata (p) = X[B.xridx (p)];
         }
       B.xcidx (cend - cst) = nz ;
     }
@@ -167,11 +167,11 @@
 dmsolve_insert (MArray<T> &a, const MArray<T> &b, const octave_idx_type *Q,
                octave_idx_type r, octave_idx_type c)
 {
-  T *ax = a.fortran_vec();
-  const T *bx = b.fortran_vec();
-  octave_idx_type anr = a.rows();
-  octave_idx_type nr = b.rows();
-  octave_idx_type nc = b.cols();
+  T *ax = a.fortran_vec ();
+  const T *bx = b.fortran_vec ();
+  octave_idx_type anr = a.rows ();
+  octave_idx_type nr = b.rows ();
+  octave_idx_type nc = b.cols ();
   for (octave_idx_type j = 0; j < nc; j++)
     {
       octave_idx_type aoff = (c + j) * anr;
@@ -179,7 +179,7 @@
       for (octave_idx_type i = 0; i < nr; i++)
         {
           octave_quit ();
-          ax [Q [r + i] + aoff] = bx [i + boff];
+          ax[Q[r + i] + aoff] = bx[i + boff];
         }
     }
 }
@@ -206,68 +206,68 @@
 
   OCTAVE_LOCAL_BUFFER (octave_idx_type, Qinv, nr);
   for (octave_idx_type i = 0; i < nr; i++)
-    Qinv [Q [i]] = i;
+    Qinv[Q[i]] = i;
 
   // First count the number of elements in the final array
-  octave_idx_type nel = a.xcidx(c) + b.nnz ();
+  octave_idx_type nel = a.xcidx (c) + b.nnz ();
 
   if (c + b_cols < nc)
-    nel += a.xcidx(nc) - a.xcidx(c + b_cols);
+    nel += a.xcidx (nc) - a.xcidx (c + b_cols);
 
   for (octave_idx_type i = c; i < c + b_cols; i++)
-    for (octave_idx_type j = a.xcidx(i); j < a.xcidx(i+1); j++)
-      if (Qinv [a.xridx(j)] < r || Qinv [a.xridx(j)] >= r + b_rows)
+    for (octave_idx_type j = a.xcidx (i); j < a.xcidx (i+1); j++)
+      if (Qinv[a.xridx (j)] < r || Qinv[a.xridx (j)] >= r + b_rows)
         nel++;
 
   OCTAVE_LOCAL_BUFFER (T, X, nr);
   octave_sort<octave_idx_type> sort;
   MSparse<T> tmp (a);
   a = MSparse<T> (nr, nc, nel);
-  octave_idx_type *ri = a.xridx();
+  octave_idx_type *ri = a.xridx ();
 
-  for (octave_idx_type i = 0; i < tmp.cidx(c); i++)
+  for (octave_idx_type i = 0; i < tmp.cidx (c); i++)
     {
-      a.xdata(i) = tmp.xdata(i);
-      a.xridx(i) = tmp.xridx(i);
+      a.xdata (i) = tmp.xdata (i);
+      a.xridx (i) = tmp.xridx (i);
     }
   for (octave_idx_type i = 0; i < c + 1; i++)
-    a.xcidx(i) = tmp.xcidx(i);
+    a.xcidx (i) = tmp.xcidx (i);
 
-  octave_idx_type ii = a.xcidx(c);
+  octave_idx_type ii = a.xcidx (c);
 
   for (octave_idx_type i = c; i < c + b_cols; i++)
     {
       octave_quit ();
 
-      for (octave_idx_type j = tmp.xcidx(i); j < tmp.xcidx(i+1); j++)
-        if (Qinv [tmp.xridx(j)] < r ||  Qinv [tmp.xridx(j)] >= r + b_rows)
+      for (octave_idx_type j = tmp.xcidx (i); j < tmp.xcidx (i+1); j++)
+        if (Qinv[tmp.xridx (j)] < r ||  Qinv[tmp.xridx (j)] >= r + b_rows)
           {
-            X [tmp.xridx(j)] = tmp.xdata(j);
-            a.xridx(ii++) = tmp.xridx(j);
+            X[tmp.xridx (j)] = tmp.xdata (j);
+            a.xridx (ii++) = tmp.xridx (j);
           }
 
       octave_quit ();
 
-      for (octave_idx_type j = b.cidx(i-c); j < b.cidx(i-c+1); j++)
+      for (octave_idx_type j = b.cidx (i-c); j < b.cidx (i-c+1); j++)
         {
-          X [Q [r + b.ridx(j)]] = b.data(j);
-          a.xridx(ii++) = Q [r + b.ridx(j)];
+          X[Q[r + b.ridx (j)]] = b.data (j);
+          a.xridx (ii++) = Q[r + b.ridx (j)];
         }
 
       sort.sort (ri + a.xcidx (i), ii - a.xcidx (i));
       for (octave_idx_type p = a.xcidx (i); p < ii; p++)
-        a.xdata (p) = X [a.xridx (p)];
-      a.xcidx(i+1) = ii;
+        a.xdata (p) = X[a.xridx (p)];
+      a.xcidx (i+1) = ii;
     }
 
   for (octave_idx_type i = c + b_cols; i < nc; i++)
     {
-      for (octave_idx_type j = tmp.xcidx(i); j < tmp.cidx(i+1); j++)
+      for (octave_idx_type j = tmp.xcidx (i); j < tmp.cidx (i+1); j++)
         {
-          a.xdata(ii) = tmp.xdata(j);
-          a.xridx(ii++) = tmp.xridx(j);
+          a.xdata (ii) = tmp.xdata (j);
+          a.xridx (ii++) = tmp.xridx (j);
         }
-      a.xcidx(i+1) = ii;
+      a.xcidx (i+1) = ii;
     }
 }
 
@@ -287,16 +287,16 @@
 {
   octave_idx_type b_nr = b.rows ();
   octave_idx_type b_nc = b.cols ();
-  const T *Bx = b.fortran_vec();
+  const T *Bx = b.fortran_vec ();
   a.resize (dim_vector (b_nr, b_nc));
-  RT *Btx = a.fortran_vec();
+  RT *Btx = a.fortran_vec ();
   for (octave_idx_type j = 0; j < b_nc; j++)
     {
       octave_idx_type off = j * b_nr;
       for (octave_idx_type i = 0; i < b_nr; i++)
         {
           octave_quit ();
-          Btx [p [i] + off] = Bx [ i + off];
+          Btx[p[i] + off] = Bx[ i + off];
         }
     }
 }
@@ -325,25 +325,25 @@
   octave_idx_type nz = 0;
   a = MSparse<RT> (b_nr, b_nc, b_nz);
   octave_sort<octave_idx_type> sort;
-  octave_idx_type *ri = a.xridx();
+  octave_idx_type *ri = a.xridx ();
   OCTAVE_LOCAL_BUFFER (RT, X, b_nr);
-  a.xcidx(0) = 0;
+  a.xcidx (0) = 0;
   for (octave_idx_type j = 0; j < b_nc; j++)
     {
-      for (octave_idx_type i = b.cidx(j); i < b.cidx(j+1); i++)
+      for (octave_idx_type i = b.cidx (j); i < b.cidx (j+1); i++)
         {
           octave_quit ();
-          octave_idx_type r = p [b.ridx (i)];
-          X [r] = b.data (i);
-          a.xridx(nz++) = p [b.ridx (i)];
+          octave_idx_type r = p[b.ridx (i)];
+          X[r] = b.data (i);
+          a.xridx (nz++) = p[b.ridx (i)];
         }
       sort.sort (ri + a.xcidx (j), nz - a.xcidx (j));
       for (octave_idx_type i = a.cidx (j); i < nz; i++)
         {
           octave_quit ();
-          a.xdata (i) = X [a.xridx (i)];
+          a.xdata (i) = X[a.xridx (i)];
         }
-      a.xcidx(j+1) = nz;
+      a.xcidx (j+1) = nz;
     }
 }
 
@@ -398,7 +398,7 @@
       csm.p = const_cast<octave_idx_type *>(a.cidx ());
       csm.i = const_cast<octave_idx_type *>(a.ridx ());
 
-#if defined(CS_VER) && (CS_VER >= 2)
+#if defined (CS_VER) && (CS_VER >= 2)
       CXSPARSE_DNAME (d) *dm = CXSPARSE_DNAME(_dmperm) (&csm, 0);
       octave_idx_type *p = dm->p;
       octave_idx_type *q = dm->q;
@@ -409,27 +409,27 @@
 #endif
       OCTAVE_LOCAL_BUFFER (octave_idx_type, pinv, nr);
       for (octave_idx_type i = 0; i < nr; i++)
-        pinv [p [i]] = i;
+        pinv[p[i]] = i;
       RT btmp;
       dmsolve_permute (btmp, b, pinv);
       info = 0;
       retval.resize (nc, b_nc);
 
       // Leading over-determined block
-      if (dm->rr [2] < nr && dm->cc [3] < nc)
+      if (dm->rr[2] < nr && dm->cc[3] < nc)
         {
-          ST m = dmsolve_extract (a, pinv, q, dm->rr [2], nr, dm->cc [3], nc,
+          ST m = dmsolve_extract (a, pinv, q, dm->rr[2], nr, dm->cc[3], nc,
                                   nnz_remaining, true);
-          nnz_remaining -= m.nnz();
+          nnz_remaining -= m.nnz ();
           RT mtmp =
             qrsolve (m, dmsolve_extract (btmp, 0, 0, dm->rr[2], b_nr, 0,
                                          b_nc), info);
-          dmsolve_insert (retval, mtmp, q, dm->cc [3], 0);
-          if (dm->rr [2] > 0 && !info)
+          dmsolve_insert (retval, mtmp, q, dm->cc[3], 0);
+          if (dm->rr[2] > 0 && !info)
             {
-              m = dmsolve_extract (a, pinv, q, 0, dm->rr [2],
-                                   dm->cc [3], nc, nnz_remaining, true);
-              nnz_remaining -= m.nnz();
+              m = dmsolve_extract (a, pinv, q, 0, dm->rr[2],
+                                   dm->cc[3], nc, nnz_remaining, true);
+              nnz_remaining -= m.nnz ();
               RT ctmp = dmsolve_extract (btmp, 0, 0, 0,
                                          dm->rr[2], 0, b_nc);
               btmp.insert (ctmp - m * mtmp, 0, 0);
@@ -438,12 +438,12 @@
 
       // Structurally non-singular blocks
       // FIXME Should use fine Dulmange-Mendelsohn decomposition here.
-      if (dm->rr [1] < dm->rr [2] && dm->cc [2] < dm->cc [3] && !info)
+      if (dm->rr[1] < dm->rr[2] && dm->cc[2] < dm->cc[3] && !info)
         {
-          ST m = dmsolve_extract (a, pinv, q, dm->rr [1], dm->rr [2],
-                                  dm->cc [2], dm->cc [3], nnz_remaining, false);
-          nnz_remaining -= m.nnz();
-          RT btmp2 = dmsolve_extract (btmp, 0, 0, dm->rr [1], dm->rr [2],
+          ST m = dmsolve_extract (a, pinv, q, dm->rr[1], dm->rr[2],
+                                  dm->cc[2], dm->cc[3], nnz_remaining, false);
+          nnz_remaining -= m.nnz ();
+          RT btmp2 = dmsolve_extract (btmp, 0, 0, dm->rr[1], dm->rr[2],
                                       0, b_nc);
           double rcond = 0.0;
           MatrixType mtyp (MatrixType::Full);
@@ -455,12 +455,12 @@
               mtmp = qrsolve (m, btmp2, info);
             }
 
-          dmsolve_insert (retval, mtmp, q, dm->cc [2], 0);
-          if (dm->rr [1] > 0 && !info)
+          dmsolve_insert (retval, mtmp, q, dm->cc[2], 0);
+          if (dm->rr[1] > 0 && !info)
             {
-              m = dmsolve_extract (a, pinv, q, 0, dm->rr [1], dm->cc [2],
-                                   dm->cc [3], nnz_remaining, true);
-              nnz_remaining -= m.nnz();
+              m = dmsolve_extract (a, pinv, q, 0, dm->rr[1], dm->cc[2],
+                                   dm->cc[3], nnz_remaining, true);
+              nnz_remaining -= m.nnz ();
               RT ctmp = dmsolve_extract (btmp, 0, 0, 0,
                                          dm->rr[1], 0, b_nc);
               btmp.insert (ctmp - m * mtmp, 0, 0);
@@ -468,13 +468,13 @@
         }
 
       // Trailing under-determined block
-      if (dm->rr [1] > 0 && dm->cc [2] > 0 && !info)
+      if (dm->rr[1] > 0 && dm->cc[2] > 0 && !info)
         {
-          ST m = dmsolve_extract (a, pinv, q, 0, dm->rr [1], 0,
-                                  dm->cc [2], nnz_remaining, true);
+          ST m = dmsolve_extract (a, pinv, q, 0, dm->rr[1], 0,
+                                  dm->cc[2], nnz_remaining, true);
           RT mtmp =
-            qrsolve (m, dmsolve_extract(btmp, 0, 0, 0, dm->rr [1] , 0,
-                                        b_nc), info);
+            qrsolve (m, dmsolve_extract (btmp, 0, 0, 0, dm->rr[1] , 0,
+                                         b_nc), info);
           dmsolve_insert (retval, mtmp, q, 0, 0);
         }
 
@@ -482,6 +482,8 @@
     }
   return retval;
 #else
+  (*current_liboctave_error_handler)
+    ("CXSPARSE unavailable; cannot solve minimum norm problem");
   return RT ();
 #endif
 }
rename from liboctave/Sparse-diag-op-defs.h
rename to liboctave/operators/Sparse-diag-op-defs.h
rename from liboctave/Sparse-op-defs.h
rename to liboctave/operators/Sparse-op-defs.h
--- a/liboctave/Sparse-op-defs.h
+++ b/liboctave/operators/Sparse-op-defs.h
@@ -74,11 +74,11 @@
  \
     for (octave_idx_type i = 0; i < nz; i++) \
       { \
-        r.xdata(i) = m.data(i) OP s; \
-        r.xridx(i) = m.ridx(i); \
+        r.xdata (i) = m.data (i) OP s; \
+        r.xridx (i) = m.ridx (i); \
       } \
     for (octave_idx_type i = 0; i < nc + 1; i++) \
-      r.xcidx(i) = m.cidx(i); \
+      r.xcidx (i) = m.cidx (i); \
     \
     r.maybe_compress (true); \
     return r; \
@@ -114,7 +114,7 @@
       { \
         r = SparseBoolMatrix (nr, nc, true); \
         for (octave_idx_type j = 0; j < nc; j++) \
-          for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++) \
+          for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++) \
             if (! (MC (m.data (i)) OP SC (s))) \
               r.data (m.ridx (i) + j * nr) = false; \
         r.maybe_compress (true); \
@@ -126,7 +126,7 @@
         octave_idx_type nel = 0; \
         for (octave_idx_type j = 0; j < nc; j++) \
           { \
-            for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++) \
+            for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++) \
               if (MC (m.data (i)) OP SC (s)) \
                 { \
                   r.ridx (nel) = m.ridx (i); \
@@ -169,8 +169,8 @@
           { \
             r = SparseBoolMatrix (nr, nc, true); \
             for (octave_idx_type j = 0; j < nc; j++) \
-              for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++) \
-                if (! ((m.data(i) != LHS_ZERO) OP (s != RHS_ZERO))) \
+              for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++) \
+                if (! ((m.data (i) != LHS_ZERO) OP (s != RHS_ZERO))) \
                   r.data (m.ridx (i) + j * nr) = false; \
             r.maybe_compress (true); \
           } \
@@ -181,8 +181,8 @@
             octave_idx_type nel = 0; \
             for (octave_idx_type j = 0; j < nc; j++) \
               { \
-                for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++) \
-                  if ((m.data(i) != LHS_ZERO) OP (s != RHS_ZERO)) \
+                for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++) \
+                  if ((m.data (i) != LHS_ZERO) OP (s != RHS_ZERO)) \
                     { \
                       r.ridx (nel) = m.ridx (i); \
                       r.data (nel++) = true; \
@@ -243,11 +243,11 @@
  \
     for (octave_idx_type i = 0; i < nz; i++) \
       { \
-        r.xdata(i) = s OP m.data(i); \
-        r.xridx(i) = m.ridx(i); \
+        r.xdata (i) = s OP m.data (i); \
+        r.xridx (i) = m.ridx (i); \
       } \
     for (octave_idx_type i = 0; i < nc + 1; i++) \
-      r.xcidx(i) = m.cidx(i); \
+      r.xcidx (i) = m.cidx (i); \
  \
     r.maybe_compress(true); \
     return r; \
@@ -283,7 +283,7 @@
       { \
         r = SparseBoolMatrix (nr, nc, true); \
         for (octave_idx_type j = 0; j < nc; j++) \
-          for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++) \
+          for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++) \
             if (! (SC (s) OP MC (m.data (i)))) \
               r.data (m.ridx (i) + j * nr) = false; \
         r.maybe_compress (true); \
@@ -295,7 +295,7 @@
         octave_idx_type nel = 0; \
         for (octave_idx_type j = 0; j < nc; j++) \
           { \
-            for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++) \
+            for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++) \
               if (SC (s) OP MC (m.data (i))) \
                 { \
                   r.ridx (nel) = m.ridx (i); \
@@ -338,8 +338,8 @@
           { \
             r = SparseBoolMatrix (nr, nc, true); \
             for (octave_idx_type j = 0; j < nc; j++) \
-              for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++) \
-                if (! ((s != LHS_ZERO) OP (m.data(i) != RHS_ZERO))) \
+              for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++) \
+                if (! ((s != LHS_ZERO) OP (m.data (i) != RHS_ZERO))) \
                   r.data (m.ridx (i) + j * nr) = false; \
             r.maybe_compress (true); \
           } \
@@ -350,8 +350,8 @@
             octave_idx_type nel = 0; \
             for (octave_idx_type j = 0; j < nc; j++) \
               { \
-                for (octave_idx_type i = m.cidx(j); i < m.cidx(j+1); i++) \
-                  if ((s != LHS_ZERO) OP (m.data(i) != RHS_ZERO)) \
+                for (octave_idx_type i = m.cidx (j); i < m.cidx (j+1); i++) \
+                  if ((s != LHS_ZERO) OP (m.data (i) != RHS_ZERO)) \
                     { \
                       r.ridx (nel) = m.ridx (i); \
                       r.data (nel++) = true; \
@@ -398,20 +398,20 @@
  \
     if (m1_nr == 1 && m1_nc == 1) \
       { \
-        if (m1.elem(0,0) == 0.) \
+        if (m1.elem (0,0) == 0.) \
           r = OP R (m2); \
         else \
           { \
-            r = R (m2_nr, m2_nc, m1.data(0) OP 0.); \
+            r = R (m2_nr, m2_nc, m1.data (0) OP 0.); \
             \
             for (octave_idx_type j = 0 ; j < m2_nc ; j++) \
               { \
                 octave_quit (); \
                 octave_idx_type idxj = j * m2_nr; \
-                for (octave_idx_type i = m2.cidx(j) ; i < m2.cidx(j+1) ; i++) \
+                for (octave_idx_type i = m2.cidx (j) ; i < m2.cidx (j+1) ; i++) \
                   { \
                     octave_quit (); \
-                    r.data(idxj + m2.ridx(i)) = m1.data(0) OP m2.data(i); \
+                    r.data (idxj + m2.ridx (i)) = m1.data (0) OP m2.data (i); \
                   } \
               } \
             r.maybe_compress (); \
@@ -419,20 +419,20 @@
       } \
     else if (m2_nr == 1 && m2_nc == 1) \
       { \
-        if (m2.elem(0,0) == 0.) \
+        if (m2.elem (0,0) == 0.) \
           r = R (m1); \
         else \
           { \
-            r = R (m1_nr, m1_nc, 0. OP m2.data(0)); \
+            r = R (m1_nr, m1_nc, 0. OP m2.data (0)); \
             \
             for (octave_idx_type j = 0 ; j < m1_nc ; j++) \
               { \
                 octave_quit (); \
                 octave_idx_type idxj = j * m1_nr; \
-                for (octave_idx_type i = m1.cidx(j) ; i < m1.cidx(j+1) ; i++) \
+                for (octave_idx_type i = m1.cidx (j) ; i < m1.cidx (j+1) ; i++) \
                   { \
                     octave_quit (); \
-                    r.data(idxj + m1.ridx(i)) = m1.data(i) OP m2.data(0); \
+                    r.data (idxj + m1.ridx (i)) = m1.data (i) OP m2.data (0); \
                   } \
               } \
             r.maybe_compress (); \
@@ -448,41 +448,41 @@
         r.cidx (0) = 0; \
         for (octave_idx_type i = 0 ; i < m1_nc ; i++) \
           { \
-            octave_idx_type  ja = m1.cidx(i); \
-            octave_idx_type  ja_max = m1.cidx(i+1); \
+            octave_idx_type  ja = m1.cidx (i); \
+            octave_idx_type  ja_max = m1.cidx (i+1); \
             bool ja_lt_max= ja < ja_max; \
             \
-            octave_idx_type  jb = m2.cidx(i); \
-            octave_idx_type  jb_max = m2.cidx(i+1); \
+            octave_idx_type  jb = m2.cidx (i); \
+            octave_idx_type  jb_max = m2.cidx (i+1); \
             bool jb_lt_max = jb < jb_max; \
             \
             while (ja_lt_max || jb_lt_max ) \
               { \
                 octave_quit (); \
                 if ((! jb_lt_max) || \
-                      (ja_lt_max && (m1.ridx(ja) < m2.ridx(jb)))) \
+                      (ja_lt_max && (m1.ridx (ja) < m2.ridx (jb)))) \
                   { \
-                    r.ridx(jx) = m1.ridx(ja); \
-                    r.data(jx) = m1.data(ja) OP 0.; \
+                    r.ridx (jx) = m1.ridx (ja); \
+                    r.data (jx) = m1.data (ja) OP 0.; \
                     jx++; \
                     ja++; \
                     ja_lt_max= ja < ja_max; \
                   } \
                 else if (( !ja_lt_max ) || \
-                     (jb_lt_max && (m2.ridx(jb) < m1.ridx(ja)) ) ) \
+                     (jb_lt_max && (m2.ridx (jb) < m1.ridx (ja)) ) ) \
                   { \
-                    r.ridx(jx) = m2.ridx(jb); \
-                    r.data(jx) = 0. OP m2.data(jb); \
+                    r.ridx (jx) = m2.ridx (jb); \
+                    r.data (jx) = 0. OP m2.data (jb); \
                     jx++; \
                     jb++; \
                     jb_lt_max= jb < jb_max; \
                   } \
                 else \
                   { \
-                     if ((m1.data(ja) OP m2.data(jb)) != 0.) \
+                     if ((m1.data (ja) OP m2.data (jb)) != 0.) \
                        { \
-                          r.data(jx) = m1.data(ja) OP m2.data(jb); \
-                          r.ridx(jx) = m1.ridx(ja); \
+                          r.data (jx) = m1.data (ja) OP m2.data (jb); \
+                          r.ridx (jx) = m1.ridx (ja); \
                           jx++; \
                        } \
                      ja++; \
@@ -491,7 +491,7 @@
                      jb_lt_max= jb < jb_max; \
                   } \
               } \
-            r.cidx(i+1) = jx; \
+            r.cidx (i+1) = jx; \
           } \
         \
         r.maybe_compress (); \
@@ -514,34 +514,34 @@
  \
     if (m1_nr == 1 && m1_nc == 1) \
       { \
-        if (m1.elem(0,0) == 0.) \
+        if (m1.elem (0,0) == 0.) \
           r = R (m2_nr, m2_nc); \
         else \
           { \
             r = R (m2); \
-            octave_idx_type m2_nnz = m2.nnz(); \
+            octave_idx_type m2_nnz = m2.nnz (); \
             \
             for (octave_idx_type i = 0 ; i < m2_nnz ; i++) \
               { \
                 octave_quit (); \
-                r.data (i) = m1.data(0) OP r.data(i); \
+                r.data (i) = m1.data (0) OP r.data (i); \
               } \
             r.maybe_compress (); \
           } \
       } \
     else if (m2_nr == 1 && m2_nc == 1) \
       { \
-        if (m2.elem(0,0) == 0.) \
+        if (m2.elem (0,0) == 0.) \
           r = R (m1_nr, m1_nc); \
         else \
           { \
             r = R (m1); \
-            octave_idx_type m1_nnz = m1.nnz(); \
+            octave_idx_type m1_nnz = m1.nnz (); \
             \
             for (octave_idx_type i = 0 ; i < m1_nnz ; i++) \
               { \
                 octave_quit (); \
-                r.data (i) = r.data(i) OP m2.data(0); \
+                r.data (i) = r.data (i) OP m2.data (0); \
               } \
             r.maybe_compress (); \
           } \
@@ -556,40 +556,40 @@
         r.cidx (0) = 0; \
         for (octave_idx_type i = 0 ; i < m1_nc ; i++) \
           { \
-            octave_idx_type  ja = m1.cidx(i); \
-            octave_idx_type  ja_max = m1.cidx(i+1); \
+            octave_idx_type  ja = m1.cidx (i); \
+            octave_idx_type  ja_max = m1.cidx (i+1); \
             bool ja_lt_max= ja < ja_max; \
             \
-            octave_idx_type  jb = m2.cidx(i); \
-            octave_idx_type  jb_max = m2.cidx(i+1); \
+            octave_idx_type  jb = m2.cidx (i); \
+            octave_idx_type  jb_max = m2.cidx (i+1); \
             bool jb_lt_max = jb < jb_max; \
             \
             while (ja_lt_max || jb_lt_max ) \
               { \
                 octave_quit (); \
                 if ((! jb_lt_max) || \
-                      (ja_lt_max && (m1.ridx(ja) < m2.ridx(jb)))) \
+                      (ja_lt_max && (m1.ridx (ja) < m2.ridx (jb)))) \
                   { \
                      ja++; ja_lt_max= ja < ja_max; \
                   } \
                 else if (( !ja_lt_max ) || \
-                     (jb_lt_max && (m2.ridx(jb) < m1.ridx(ja)) ) ) \
+                     (jb_lt_max && (m2.ridx (jb) < m1.ridx (ja)) ) ) \
                   { \
                      jb++; jb_lt_max= jb < jb_max; \
                   } \
                 else \
                   { \
-                     if ((m1.data(ja) OP m2.data(jb)) != 0.) \
+                     if ((m1.data (ja) OP m2.data (jb)) != 0.) \
                        { \
-                          r.data(jx) = m1.data(ja) OP m2.data(jb); \
-                          r.ridx(jx) = m1.ridx(ja); \
+                          r.data (jx) = m1.data (ja) OP m2.data (jb); \
+                          r.ridx (jx) = m1.ridx (ja); \
                           jx++; \
                        } \
                      ja++; ja_lt_max= ja < ja_max; \
                      jb++; jb_lt_max= jb < jb_max; \
                   } \
               } \
-            r.cidx(i+1) = jx; \
+            r.cidx (i+1) = jx; \
           } \
         \
         r.maybe_compress (); \
@@ -612,25 +612,25 @@
  \
     if (m1_nr == 1 && m1_nc == 1) \
       { \
-        if ((m1.elem (0,0) OP Complex()) == Complex()) \
+        if ((m1.elem (0,0) OP Complex ()) == Complex ()) \
           { \
-            octave_idx_type m2_nnz = m2.nnz(); \
+            octave_idx_type m2_nnz = m2.nnz (); \
             r = R (m2); \
             for (octave_idx_type i = 0 ; i < m2_nnz ; i++) \
-              r.data (i) = m1.elem(0,0) OP r.data(i); \
+              r.data (i) = m1.elem (0,0) OP r.data (i); \
             r.maybe_compress (); \
           } \
         else \
           { \
-            r = R (m2_nr, m2_nc, m1.elem(0,0) OP Complex ()); \
+            r = R (m2_nr, m2_nc, m1.elem (0,0) OP Complex ()); \
             for (octave_idx_type j = 0 ; j < m2_nc ; j++) \
               { \
                 octave_quit (); \
                 octave_idx_type idxj = j * m2_nr; \
-                for (octave_idx_type i = m2.cidx(j) ; i < m2.cidx(j+1) ; i++) \
+                for (octave_idx_type i = m2.cidx (j) ; i < m2.cidx (j+1) ; i++) \
                   { \
                     octave_quit (); \
-                    r.data(idxj + m2.ridx(i)) = m1.elem(0,0) OP m2.data(i); \
+                    r.data (idxj + m2.ridx (i)) = m1.elem (0,0) OP m2.data (i); \
                   } \
               } \
             r.maybe_compress (); \
@@ -638,25 +638,25 @@
       } \
     else if (m2_nr == 1 && m2_nc == 1) \
       { \
-        if ((Complex() OP m1.elem (0,0)) == Complex()) \
+        if ((Complex () OP m1.elem (0,0)) == Complex ()) \
           { \
-            octave_idx_type m1_nnz = m1.nnz(); \
+            octave_idx_type m1_nnz = m1.nnz (); \
             r = R (m1); \
             for (octave_idx_type i = 0 ; i < m1_nnz ; i++) \
-              r.data (i) = r.data(i) OP m2.elem(0,0); \
+              r.data (i) = r.data (i) OP m2.elem (0,0); \
             r.maybe_compress (); \
           } \
         else \
           { \
-            r = R (m1_nr, m1_nc, Complex() OP m2.elem(0,0)); \
+            r = R (m1_nr, m1_nc, Complex () OP m2.elem (0,0)); \
             for (octave_idx_type j = 0 ; j < m1_nc ; j++) \
               { \
                 octave_quit (); \
                 octave_idx_type idxj = j * m1_nr; \
-                for (octave_idx_type i = m1.cidx(j) ; i < m1.cidx(j+1) ; i++) \
+                for (octave_idx_type i = m1.cidx (j) ; i < m1.cidx (j+1) ; i++) \
                   { \
                     octave_quit (); \
-                    r.data(idxj + m1.ridx(i)) = m1.data(i) OP m2.elem(0,0); \
+                    r.data (idxj + m1.ridx (i)) = m1.data (i) OP m2.elem (0,0); \
                   } \
               } \
             r.maybe_compress (); \
@@ -672,36 +672,36 @@
         \
         for (octave_idx_type i = 0 ; i < m1_nc ; i++) \
           { \
-            octave_idx_type  ja = m1.cidx(i); \
-            octave_idx_type  ja_max = m1.cidx(i+1); \
+            octave_idx_type  ja = m1.cidx (i); \
+            octave_idx_type  ja_max = m1.cidx (i+1); \
             bool ja_lt_max= ja < ja_max; \
             \
-            octave_idx_type  jb = m2.cidx(i); \
-            octave_idx_type  jb_max = m2.cidx(i+1); \
+            octave_idx_type  jb = m2.cidx (i); \
+            octave_idx_type  jb_max = m2.cidx (i+1); \
             bool jb_lt_max = jb < jb_max; \
             \
             while (ja_lt_max || jb_lt_max ) \
               { \
                 octave_quit (); \
                 if ((! jb_lt_max) || \
-                      (ja_lt_max && (m1.ridx(ja) < m2.ridx(jb)))) \
+                      (ja_lt_max && (m1.ridx (ja) < m2.ridx (jb)))) \
                   { \
                     /* keep those kludges coming */ \
-                    r.elem(m1.ridx(ja),i) = m1.data(ja) OP Complex (); \
+                    r.elem (m1.ridx (ja),i) = m1.data (ja) OP Complex (); \
                     ja++; \
                     ja_lt_max= ja < ja_max; \
                   } \
                 else if (( !ja_lt_max ) || \
-                     (jb_lt_max && (m2.ridx(jb) < m1.ridx(ja)) ) ) \
+                     (jb_lt_max && (m2.ridx (jb) < m1.ridx (ja)) ) ) \
                   { \
                     /* keep those kludges coming */ \
-                    r.elem(m2.ridx(jb),i) = Complex () OP m2.data(jb);  \
+                    r.elem (m2.ridx (jb),i) = Complex () OP m2.data (jb);  \
                     jb++; \
                     jb_lt_max= jb < jb_max; \
                   } \
                 else \
                   { \
-                    r.elem(m1.ridx(ja),i) = m1.data(ja) OP m2.data(jb); \
+                    r.elem (m1.ridx (ja),i) = m1.data (ja) OP m2.data (jb); \
                     ja++; \
                     ja_lt_max= ja < ja_max; \
                     jb++; \
@@ -755,12 +755,12 @@
     \
     if (m1_nr == 1 && m1_nc == 1) \
       { \
-    if (C1 (m1.elem(0,0)) OP C2 (Z2)) \
+    if (C1 (m1.elem (0,0)) OP C2 (Z2)) \
           { \
             r = SparseBoolMatrix (m2_nr, m2_nc, true); \
             for (octave_idx_type j = 0; j < m2_nc; j++) \
-              for (octave_idx_type i = m2.cidx(j); i < m2.cidx(j+1); i++) \
-                if (! (C1 (m1.elem (0,0)) OP C2 (m2.data(i)))) \
+              for (octave_idx_type i = m2.cidx (j); i < m2.cidx (j+1); i++) \
+                if (! (C1 (m1.elem (0,0)) OP C2 (m2.data (i)))) \
                   r.data (m2.ridx (i) + j * m2_nr) = false; \
             r.maybe_compress (true); \
           } \
@@ -771,8 +771,8 @@
             octave_idx_type nel = 0; \
             for (octave_idx_type j = 0; j < m2_nc; j++) \
               { \
-                for (octave_idx_type i = m2.cidx(j); i < m2.cidx(j+1); i++) \
-                  if (C1 (m1.elem (0,0)) OP C2 (m2.data(i))) \
+                for (octave_idx_type i = m2.cidx (j); i < m2.cidx (j+1); i++) \
+                  if (C1 (m1.elem (0,0)) OP C2 (m2.data (i))) \
                     { \
                       r.ridx (nel) = m2.ridx (i); \
                       r.data (nel++) = true; \
@@ -788,8 +788,8 @@
           { \
             r = SparseBoolMatrix (m1_nr, m1_nc, true); \
             for (octave_idx_type j = 0; j < m1_nc; j++) \
-              for (octave_idx_type i = m1.cidx(j); i < m1.cidx(j+1); i++) \
-                if (! (C1 (m1.data (i)) OP C2 (m2.elem(0,0)))) \
+              for (octave_idx_type i = m1.cidx (j); i < m1.cidx (j+1); i++) \
+                if (! (C1 (m1.data (i)) OP C2 (m2.elem (0,0)))) \
                   r.data (m1.ridx (i) + j * m1_nr) = false; \
             r.maybe_compress (true); \
           } \
@@ -800,8 +800,8 @@
             octave_idx_type nel = 0; \
             for (octave_idx_type j = 0; j < m1_nc; j++) \
               { \
-                for (octave_idx_type i = m1.cidx(j); i < m1.cidx(j+1); i++) \
-                  if (C1 (m1.data (i)) OP C2 (m2.elem(0,0))) \
+                for (octave_idx_type i = m1.cidx (j); i < m1.cidx (j+1); i++) \
+                  if (C1 (m1.data (i)) OP C2 (m2.elem (0,0))) \
                     { \
                       r.ridx (nel) = m1.ridx (i); \
                       r.data (nel++) = true; \
@@ -826,13 +826,13 @@
                      octave_idx_type e2 = m2.cidx (j+1); \
                      while (i1 < e1 || i2 < e2) \
                        { \
-                         if (i1 == e1 || (i2 < e2 && m1.ridx(i1) > m2.ridx(i2))) \
+                         if (i1 == e1 || (i2 < e2 && m1.ridx (i1) > m2.ridx (i2))) \
                            { \
                              if (! (C1 (Z1) OP C2 (m2.data (i2)))) \
                                r.data (m2.ridx (i2) + j * m1_nr) = false; \
                              i2++; \
                            } \
-                         else if (i2 == e2 || m1.ridx(i1) < m2.ridx(i2)) \
+                         else if (i2 == e2 || m1.ridx (i1) < m2.ridx (i2)) \
                            { \
                              if (! (C1 (m1.data (i1)) OP C2 (Z2))) \
                                r.data (m1.ridx (i1) + j * m1_nr) = false; \
@@ -862,7 +862,7 @@
                      octave_idx_type e2 = m2.cidx (j+1); \
                      while (i1 < e1 || i2 < e2) \
                        { \
-                         if (i1 == e1 || (i2 < e2 && m1.ridx(i1) > m2.ridx(i2))) \
+                         if (i1 == e1 || (i2 < e2 && m1.ridx (i1) > m2.ridx (i2))) \
                            { \
                              if (C1 (Z1) OP C2 (m2.data (i2))) \
                                { \
@@ -871,7 +871,7 @@
                                } \
                              i2++; \
                            } \
-                         else if (i2 == e2 || m1.ridx(i1) < m2.ridx(i2)) \
+                         else if (i2 == e2 || m1.ridx (i1) < m2.ridx (i2)) \
                            { \
                              if (C1 (m1.data (i1)) OP C2 (Z2)) \
                                { \
@@ -941,12 +941,12 @@
       { \
         if (m2_nr > 0 && m2_nc > 0) \
           { \
-            if ((m1.elem(0,0) != LHS_ZERO) OP RHS_ZERO) \
+            if ((m1.elem (0,0) != LHS_ZERO) OP RHS_ZERO) \
               { \
                 r = SparseBoolMatrix (m2_nr, m2_nc, true); \
                 for (octave_idx_type j = 0; j < m2_nc; j++) \
-                  for (octave_idx_type i = m2.cidx(j); i < m2.cidx(j+1); i++) \
-                    if (! ((m1.elem(0,0) != LHS_ZERO) OP (m2.data(i) != RHS_ZERO))) \
+                  for (octave_idx_type i = m2.cidx (j); i < m2.cidx (j+1); i++) \
+                    if (! ((m1.elem (0,0) != LHS_ZERO) OP (m2.data (i) != RHS_ZERO))) \
                       r.data (m2.ridx (i) + j * m2_nr) = false; \
                 r.maybe_compress (true); \
               } \
@@ -957,8 +957,8 @@
                 octave_idx_type nel = 0; \
                 for (octave_idx_type j = 0; j < m2_nc; j++) \
                   { \
-                    for (octave_idx_type i = m2.cidx(j); i < m2.cidx(j+1); i++) \
-                      if ((m1.elem(0,0) != LHS_ZERO) OP (m2.data(i) != RHS_ZERO)) \
+                    for (octave_idx_type i = m2.cidx (j); i < m2.cidx (j+1); i++) \
+                      if ((m1.elem (0,0) != LHS_ZERO) OP (m2.data (i) != RHS_ZERO)) \
                         { \
                           r.ridx (nel) = m2.ridx (i); \
                           r.data (nel++) = true; \
@@ -973,12 +973,12 @@
       { \
         if (m1_nr > 0 && m1_nc > 0) \
           { \
-            if (LHS_ZERO OP (m2.elem(0,0) != RHS_ZERO)) \
+            if (LHS_ZERO OP (m2.elem (0,0) != RHS_ZERO)) \
               { \
                 r = SparseBoolMatrix (m1_nr, m1_nc, true); \
                 for (octave_idx_type j = 0; j < m1_nc; j++) \
-                  for (octave_idx_type i = m1.cidx(j); i < m1.cidx(j+1); i++) \
-                    if (! ((m1.data(i) != LHS_ZERO) OP (m2.elem(0,0) != RHS_ZERO))) \
+                  for (octave_idx_type i = m1.cidx (j); i < m1.cidx (j+1); i++) \
+                    if (! ((m1.data (i) != LHS_ZERO) OP (m2.elem (0,0) != RHS_ZERO))) \
                       r.data (m1.ridx (i) + j * m1_nr) = false; \
                 r.maybe_compress (true); \
               } \
@@ -989,8 +989,8 @@
                 octave_idx_type nel = 0; \
                 for (octave_idx_type j = 0; j < m1_nc; j++) \
                   { \
-                    for (octave_idx_type i = m1.cidx(j); i < m1.cidx(j+1); i++) \
-                      if ((m1.data(i) != LHS_ZERO) OP (m2.elem(0,0) != RHS_ZERO)) \
+                    for (octave_idx_type i = m1.cidx (j); i < m1.cidx (j+1); i++) \
+                      if ((m1.data (i) != LHS_ZERO) OP (m2.elem (0,0) != RHS_ZERO)) \
                         { \
                           r.ridx (nel) = m1.ridx (i); \
                           r.data (nel++) = true; \
@@ -1016,7 +1016,7 @@
                 octave_idx_type e2 = m2.cidx (j+1); \
                 while (i1 < e1 || i2 < e2) \
                   { \
-                    if (i1 == e1 || (i2 < e2 && m1.ridx(i1) > m2.ridx(i2))) \
+                    if (i1 == e1 || (i2 < e2 && m1.ridx (i1) > m2.ridx (i2))) \
                       { \
                         if (LHS_ZERO OP m2.data (i2) != RHS_ZERO) \
                           { \
@@ -1025,7 +1025,7 @@
                           } \
                         i2++; \
                       } \
-                    else if (i2 == e2 || m1.ridx(i1) < m2.ridx(i2)) \
+                    else if (i2 == e2 || m1.ridx (i1) < m2.ridx (i2)) \
                       { \
                         if (m1.data (i1) != LHS_ZERO OP RHS_ZERO) \
                           { \
@@ -1036,7 +1036,7 @@
                       } \
                     else \
                       { \
-                        if (m1.data (i1) != LHS_ZERO OP m2.data(i2) != RHS_ZERO) \
+                        if (m1.data (i1) != LHS_ZERO OP m2.data (i2) != RHS_ZERO) \
                           { \
                             r.ridx (nel) = m1.ridx (i1); \
                             r.data (nel++) = true; \
@@ -1091,7 +1091,7 @@
     octave_idx_type m2_nc = m2.cols (); \
  \
     if (m2_nr == 1 && m2_nc == 1) \
-      r = R (m1 OP m2.elem(0,0)); \
+      r = R (m1 OP m2.elem (0,0)); \
     else if (m1_nr != m2_nr || m1_nc != m2_nc) \
       gripe_nonconformant (#F, m1_nr, m1_nc, m2_nr, m2_nc); \
     else \
@@ -1114,7 +1114,7 @@
     octave_idx_type m2_nc = m2.cols (); \
  \
     if (m2_nr == 1 && m2_nc == 1) \
-      r = R (m1 OP m2.elem(0,0)); \
+      r = R (m1 OP m2.elem (0,0)); \
     else if (m1_nr != m2_nr || m1_nc != m2_nc) \
       gripe_nonconformant (#F, m1_nr, m1_nc, m2_nr, m2_nc); \
     else \
@@ -1127,18 +1127,18 @@
             for (octave_idx_type j = 0, k = 0; j < m2_nc; j++) \
               { \
                 octave_quit (); \
-                for (octave_idx_type i = m2.cidx(j); i < m2.cidx(j+1); i++) \
+                for (octave_idx_type i = m2.cidx (j); i < m2.cidx (j+1); i++) \
                   { \
-                    octave_idx_type mri = m2.ridx(i); \
-                    R::element_type x = m1(mri, j) OP m2.data(i); \
+                    octave_idx_type mri = m2.ridx (i); \
+                    R::element_type x = m1(mri, j) OP m2.data (i); \
                     if (x != 0.0) \
                       { \
-                        r.xdata(k) = x; \
-                        r.xridx(k) = m2.ridx(i); \
+                        r.xdata (k) = x; \
+                        r.xridx (k) = m2.ridx (i); \
                         k++; \
                       } \
                   } \
-                r.xcidx(j+1) = k; \
+                r.xcidx (j+1) = k; \
               } \
             r.maybe_compress (false); \
             return r; \
@@ -1182,7 +1182,7 @@
     octave_idx_type m2_nc = m2.cols (); \
     \
     if (m2_nr == 1 && m2_nc == 1) \
-      r = SparseBoolMatrix (F (m1, m2.elem(0,0))); \
+      r = SparseBoolMatrix (F (m1, m2.elem (0,0))); \
     else if (m1_nr == m2_nr && m1_nc == m2_nc) \
       { \
         if (m1_nr != 0 || m1_nc != 0) \
@@ -1191,7 +1191,7 @@
             octave_idx_type nel = 0; \
             for (octave_idx_type j = 0; j < m1_nc; j++) \
               for (octave_idx_type i = 0; i < m1_nr; i++) \
-                if (C1 (m1.elem(i, j)) OP C2 (m2.elem(i, j))) \
+                if (C1 (m1.elem (i, j)) OP C2 (m2.elem (i, j))) \
                   nel++; \
             \
             r = SparseBoolMatrix (m1_nr, m1_nc, nel); \
@@ -1202,14 +1202,14 @@
               { \
                 for (octave_idx_type i = 0; i < m1_nr; i++) \
                   { \
-                    bool el = C1 (m1.elem(i, j)) OP C2 (m2.elem(i, j)); \
+                    bool el = C1 (m1.elem (i, j)) OP C2 (m2.elem (i, j)); \
                     if (el) \
                       { \
-                        r.data(ii) = el; \
-                        r.ridx(ii++) = i; \
+                        r.data (ii) = el; \
+                        r.ridx (ii++) = i; \
                       } \
                   } \
-                r.cidx(j+1) = ii; \
+                r.cidx (j+1) = ii; \
               } \
           } \
       }       \
@@ -1250,7 +1250,7 @@
     octave_idx_type m2_nc = m2.cols (); \
     \
     if (m2_nr == 1 && m2_nc == 1) \
-      r = SparseBoolMatrix  (F (m1, m2.elem(0,0))); \
+      r = SparseBoolMatrix (F (m1, m2.elem (0,0))); \
     else if (m1_nr == m2_nr && m1_nc == m2_nc) \
       { \
         if (m1_nr != 0 || m1_nc != 0) \
@@ -1259,8 +1259,8 @@
             octave_idx_type nel = 0; \
             for (octave_idx_type j = 0; j < m1_nc; j++) \
               for (octave_idx_type i = 0; i < m1_nr; i++) \
-                if ((m1.elem(i, j) != LHS_ZERO) \
-                    OP (m2.elem(i, j) != RHS_ZERO)) \
+                if ((m1.elem (i, j) != LHS_ZERO) \
+                    OP (m2.elem (i, j) != RHS_ZERO)) \
                   nel++; \
             \
             r = SparseBoolMatrix (m1_nr, m1_nc, nel); \
@@ -1271,15 +1271,15 @@
               { \
                 for (octave_idx_type i = 0; i < m1_nr; i++) \
                   { \
-                    bool el = (m1.elem(i, j) != LHS_ZERO) \
-                      OP (m2.elem(i, j) != RHS_ZERO);     \
+                    bool el = (m1.elem (i, j) != LHS_ZERO) \
+                      OP (m2.elem (i, j) != RHS_ZERO);     \
                     if (el) \
                       { \
-                        r.data(ii) = el; \
-                        r.ridx(ii++) = i; \
+                        r.data (ii) = el; \
+                        r.ridx (ii++) = i; \
                       } \
                   } \
-                r.cidx(j+1) = ii; \
+                r.cidx (j+1) = ii; \
               } \
           } \
       }       \
@@ -1324,7 +1324,7 @@
     octave_idx_type m2_nc = m2.cols (); \
  \
     if (m1_nr == 1 && m1_nc == 1) \
-      r = R (m1.elem(0,0) OP m2); \
+      r = R (m1.elem (0,0) OP m2); \
     else if (m1_nr != m2_nr || m1_nc != m2_nc) \
       gripe_nonconformant (#F, m1_nr, m1_nc, m2_nr, m2_nc); \
     else \
@@ -1355,7 +1355,7 @@
     octave_idx_type m2_nc = m2.cols (); \
  \
     if (m1_nr == 1 && m1_nc == 1) \
-      r = R (m1.elem(0,0) OP m2); \
+      r = R (m1.elem (0,0) OP m2); \
     else if (m1_nr != m2_nr || m1_nc != m2_nc) \
       gripe_nonconformant (#F, m1_nr, m1_nc, m2_nr, m2_nc); \
     else \
@@ -1368,18 +1368,18 @@
             for (octave_idx_type j = 0, k = 0; j < m1_nc; j++) \
               { \
                 octave_quit (); \
-                for (octave_idx_type i = m1.cidx(j); i < m1.cidx(j+1); i++) \
+                for (octave_idx_type i = m1.cidx (j); i < m1.cidx (j+1); i++) \
                   { \
-                    octave_idx_type mri = m1.ridx(i); \
-                    R::element_type x = m1.data(i) OP m2(mri, j); \
+                    octave_idx_type mri = m1.ridx (i); \
+                    R::element_type x = m1.data (i) OP m2 (mri, j); \
                     if (x != 0.0) \
                       { \
-                        r.xdata(k) = x; \
-                        r.xridx(k) = m1.ridx(i); \
+                        r.xdata (k) = x; \
+                        r.xridx (k) = m1.ridx (i); \
                         k++; \
                       } \
                   } \
-                r.xcidx(j+1) = k; \
+                r.xcidx (j+1) = k; \
               } \
             r.maybe_compress (false); \
             return r; \
@@ -1422,7 +1422,7 @@
     octave_idx_type m2_nc = m2.cols (); \
     \
     if (m1_nr == 1 && m1_nc == 1) \
-      r = SparseBoolMatrix (F (m1.elem(0,0), m2)); \
+      r = SparseBoolMatrix (F (m1.elem (0,0), m2)); \
     else if (m1_nr == m2_nr && m1_nc == m2_nc) \
       { \
         if (m1_nr != 0 || m1_nc != 0) \
@@ -1431,7 +1431,7 @@
             octave_idx_type nel = 0; \
             for (octave_idx_type j = 0; j < m1_nc; j++) \
               for (octave_idx_type i = 0; i < m1_nr; i++) \
-                if (C1 (m1.elem(i, j)) OP C2 (m2.elem(i, j))) \
+                if (C1 (m1.elem (i, j)) OP C2 (m2.elem (i, j))) \
                   nel++; \
             \
             r = SparseBoolMatrix (m1_nr, m1_nc, nel); \
@@ -1442,14 +1442,14 @@
               { \
                 for (octave_idx_type i = 0; i < m1_nr; i++) \
                   { \
-                    bool el = C1 (m1.elem(i, j)) OP C2 (m2.elem(i, j)); \
+                    bool el = C1 (m1.elem (i, j)) OP C2 (m2.elem (i, j)); \
                     if (el) \
                       { \
-                        r.data(ii) = el; \
-                        r.ridx(ii++) = i; \
+                        r.data (ii) = el; \
+                        r.ridx (ii++) = i; \
                       } \
                   } \
-                r.cidx(j+1) = ii; \
+                r.cidx (j+1) = ii; \
               } \
           } \
       }       \
@@ -1490,7 +1490,7 @@
     octave_idx_type m2_nc = m2.cols (); \
     \
     if (m1_nr == 1 && m1_nc == 1) \
-      r = SparseBoolMatrix (F (m1.elem(0,0), m2)); \
+      r = SparseBoolMatrix (F (m1.elem (0,0), m2)); \
     else if (m1_nr == m2_nr && m1_nc == m2_nc) \
       { \
         if (m1_nr != 0 || m1_nc != 0) \
@@ -1499,8 +1499,8 @@
             octave_idx_type nel = 0; \
             for (octave_idx_type j = 0; j < m1_nc; j++) \
               for (octave_idx_type i = 0; i < m1_nr; i++) \
-                if ((m1.elem(i, j) != LHS_ZERO) \
-                    OP (m2.elem(i, j) != RHS_ZERO)) \
+                if ((m1.elem (i, j) != LHS_ZERO) \
+                    OP (m2.elem (i, j) != RHS_ZERO)) \
                   nel++; \
             \
             r = SparseBoolMatrix (m1_nr, m1_nc, nel); \
@@ -1511,15 +1511,15 @@
               { \
                 for (octave_idx_type i = 0; i < m1_nr; i++) \
                   { \
-                    bool el = (m1.elem(i, j) != LHS_ZERO) \
-                      OP (m2.elem(i, j) != RHS_ZERO);     \
+                    bool el = (m1.elem (i, j) != LHS_ZERO) \
+                      OP (m2.elem (i, j) != RHS_ZERO);     \
                     if (el) \
                       { \
-                        r.data(ii) = el; \
-                        r.ridx(ii++) = i; \
+                        r.data (ii) = el; \
+                        r.ridx (ii++) = i; \
                       } \
                   } \
-                r.cidx(j+1) = ii; \
+                r.cidx (j+1) = ii; \
               } \
           } \
       }       \
@@ -1565,30 +1565,30 @@
               ELT_TYPE t = ELT_TYPE (); \
               for (octave_idx_type j = cidx (i); j < cidx (i+1); j++)   \
                 { \
-                  t += data(j); \
+                  t += data (j); \
                   if (t != ELT_TYPE ()) \
                     { \
-                      if (j == cidx(i+1) - 1) \
-                        nel += nr - ridx(j);  \
+                      if (j == cidx (i+1) - 1) \
+                        nel += nr - ridx (j);  \
                       else \
-                        nel += ridx(j+1) - ridx(j); \
+                        nel += ridx (j+1) - ridx (j); \
                     } \
                 } \
             } \
           retval = RET_TYPE (nr, nc, nel); \
-          retval.cidx(0) = 0; \
+          retval.cidx (0) = 0; \
           octave_idx_type ii = 0; \
           for (octave_idx_type i = 0; i < nc; i++) \
             { \
               ELT_TYPE t = ELT_TYPE (); \
               for (octave_idx_type j = cidx (i); j < cidx (i+1); j++)   \
                 { \
-                  t += data(j); \
+                  t += data (j); \
                   if (t != ELT_TYPE ()) \
                     { \
-                      if (j == cidx(i+1) - 1) \
+                      if (j == cidx (i+1) - 1) \
                         { \
-                          for (octave_idx_type k = ridx(j); k < nr; k++) \
+                          for (octave_idx_type k = ridx (j); k < nr; k++) \
                             { \
                                retval.data (ii) = t; \
                                retval.ridx (ii++) = k; \
@@ -1596,7 +1596,7 @@
                         } \
                       else \
                         { \
-                          for (octave_idx_type k = ridx(j); k < ridx(j+1); k++) \
+                          for (octave_idx_type k = ridx (j); k < ridx (j+1); k++) \
                             { \
                                retval.data (ii) = t; \
                                retval.ridx (ii++) = k; \
@@ -1604,7 +1604,7 @@
                         } \
                     } \
                 } \
-              retval.cidx(i+1) = ii; \
+              retval.cidx (i+1) = ii; \
             } \
         } \
     } \
@@ -1634,7 +1634,7 @@
               octave_idx_type jj = 0; \
               for (octave_idx_type j = cidx (i); j < cidx (i+1); j++) \
                 { \
-                  if (jj == ridx(j)) \
+                  if (jj == ridx (j)) \
                     { \
                       nel++; \
                       jj++; \
@@ -1644,7 +1644,7 @@
                 } \
             } \
           retval = RET_TYPE (nr, nc, nel); \
-          retval.cidx(0) = 0; \
+          retval.cidx (0) = 0; \
           octave_idx_type ii = 0; \
           for (octave_idx_type i = 0; i < nc; i++) \
             { \
@@ -1652,16 +1652,16 @@
               octave_idx_type jj = 0; \
               for (octave_idx_type j = cidx (i); j < cidx (i+1); j++) \
                 { \
-                  if (jj == ridx(j)) \
+                  if (jj == ridx (j)) \
                     { \
-                      t *= data(j); \
-                      retval.data(ii) = t; \
-                      retval.ridx(ii++) = jj++; \
+                      t *= data (j); \
+                      retval.data (ii) = t; \
+                      retval.ridx (ii++) = jj++; \
                     } \
                   else \
                     break; \
                 } \
-              retval.cidx(i+1) = ii; \
+              retval.cidx (i+1) = ii; \
             } \
         } \
     } \
@@ -1690,7 +1690,7 @@
             tmp[i] = INIT_VAL; \
           for (j = 0; j < nc; j++) \
             { \
-              for (octave_idx_type i = cidx(j); i < cidx(j + 1); i++) \
+              for (octave_idx_type i = cidx (j); i < cidx (j + 1); i++) \
                 { \
                   ROW_EXPR; \
                 } \
@@ -1700,14 +1700,14 @@
             if (tmp[i] != EL_TYPE ())  \
               nel++ ; \
           retval = RET_TYPE (nr, static_cast<octave_idx_type> (1), nel); \
-          retval.cidx(0) = 0; \
-          retval.cidx(1) = nel; \
+          retval.cidx (0) = 0; \
+          retval.cidx (1) = nel; \
           nel = 0; \
           for (octave_idx_type i = 0; i < nr; i++) \
             if (tmp[i] != EL_TYPE ())  \
               { \
-                retval.data(nel) = tmp[i]; \
-                retval.ridx(nel++) = i; \
+                retval.data (nel) = tmp[i]; \
+                retval.ridx (nel++) = i; \
               } \
         } \
       else \
@@ -1717,7 +1717,7 @@
           for (octave_idx_type j = 0; j < nc; j++) \
             { \
               tmp[j] = INIT_VAL; \
-              for (octave_idx_type i = cidx(j); i < cidx(j + 1); i++) \
+              for (octave_idx_type i = cidx (j); i < cidx (j + 1); i++) \
                 { \
                   COL_EXPR; \
                 } \
@@ -1727,17 +1727,17 @@
             if (tmp[i] != EL_TYPE ())  \
               nel++ ; \
           retval = RET_TYPE (static_cast<octave_idx_type> (1), nc, nel); \
-          retval.cidx(0) = 0; \
+          retval.cidx (0) = 0; \
           nel = 0; \
           for (octave_idx_type i = 0; i < nc; i++) \
             if (tmp[i] != EL_TYPE ())  \
               { \
-                retval.data(nel) = tmp[i]; \
-                retval.ridx(nel++) = 0; \
-                retval.cidx(i+1) = retval.cidx(i) + 1; \
+                retval.data (nel) = tmp[i]; \
+                retval.ridx (nel++) = 0; \
+                retval.cidx (i+1) = retval.cidx (i) + 1; \
               } \
             else \
-              retval.cidx(i+1) = retval.cidx(i); \
+              retval.cidx (i+1) = retval.cidx (i); \
         } \
     } \
   else if (nc == 0 && (nr == 0 || (nr == 1 && dim == -1))) \
@@ -1747,10 +1747,10 @@
           retval = RET_TYPE (static_cast<octave_idx_type> (1), \
                              static_cast<octave_idx_type> (1), \
                              static_cast<octave_idx_type> (1)); \
-          retval.cidx(0) = 0; \
-          retval.cidx(1) = 1; \
-          retval.ridx(0) = 0; \
-          retval.data(0) = MT_RESULT; \
+          retval.cidx (0) = 0; \
+          retval.cidx (1) = 1; \
+          retval.ridx (0) = 0; \
+          retval.data (0) = MT_RESULT; \
         } \
       else \
           retval = RET_TYPE (static_cast<octave_idx_type> (1), \
@@ -1779,12 +1779,12 @@
       if (MT_RESULT) \
         { \
           retval = RET_TYPE (nr, static_cast<octave_idx_type> (1), nr); \
-          retval.cidx(0) = 0; \
-          retval.cidx(1) = nr; \
+          retval.cidx (0) = 0; \
+          retval.cidx (1) = nr; \
           for (octave_idx_type i = 0; i < nr; i++) \
             { \
-              retval.ridx(i) = i; \
-              retval.data(i) = MT_RESULT; \
+              retval.ridx (i) = i; \
+              retval.data (i) = MT_RESULT; \
             } \
         } \
       else \
@@ -1797,7 +1797,7 @@
   return retval
 
 #define SPARSE_REDUCTION_OP_ROW_EXPR(OP) \
-  tmp[ridx(i)] OP data (i)
+  tmp[ridx (i)] OP data (i)
 
 #define SPARSE_REDUCTION_OP_COL_EXPR(OP) \
   tmp[j] OP data (i)
@@ -1814,7 +1814,7 @@
 // loop.
 #define SPARSE_ANY_ALL_OP_ROW_CODE(TEST_OP, TEST_TRUE_VAL) \
   if (data (i) TEST_OP 0.0) \
-    tmp[ridx(i)] = TEST_TRUE_VAL; \
+    tmp[ridx (i)] = TEST_TRUE_VAL; \
 
 #define SPARSE_ANY_ALL_OP_COL_CODE(TEST_OP, TEST_TRUE_VAL) \
   if (data (i) TEST_OP 0.0) \
@@ -1830,11 +1830,11 @@
                         INIT_VAL, MT_RESULT)
 
 #define SPARSE_ALL_OP(DIM) \
-  if ((rows() == 1 && dim == -1) || dim == 1) \
-    return transpose (). all (0). transpose(); \
+  if ((rows () == 1 && dim == -1) || dim == 1) \
+    return transpose (). all (0). transpose (); \
   else \
     { \
-      SPARSE_ANY_ALL_OP (DIM, (cidx(j+1) - cidx(j) < nr ? false : true), \
+      SPARSE_ANY_ALL_OP (DIM, (cidx (j+1) - cidx (j) < nr ? false : true), \
                          true, ==, false); \
     }
 
@@ -1849,20 +1849,20 @@
   \
   if (nr == 1 && nc == 1) \
    { \
-     RET_EL_TYPE s = m.elem(0,0); \
-     octave_idx_type nz = a.nnz(); \
+     RET_EL_TYPE s = m.elem (0,0); \
+     octave_idx_type nz = a.nnz (); \
      RET_TYPE r (a_nr, a_nc, nz); \
      \
      for (octave_idx_type i = 0; i < nz; i++) \
        { \
          octave_quit (); \
-         r.data(i) = s * a.data(i); \
-         r.ridx(i) = a.ridx(i); \
+         r.data (i) = s * a.data (i); \
+         r.ridx (i) = a.ridx (i); \
        } \
      for (octave_idx_type i = 0; i < a_nc + 1; i++) \
        { \
          octave_quit (); \
-         r.cidx(i) = a.cidx(i); \
+         r.cidx (i) = a.cidx (i); \
        } \
      \
      r.maybe_compress (true); \
@@ -1870,20 +1870,20 @@
    } \
   else if (a_nr == 1 && a_nc == 1) \
    { \
-     RET_EL_TYPE s = a.elem(0,0); \
-     octave_idx_type nz = m.nnz(); \
+     RET_EL_TYPE s = a.elem (0,0); \
+     octave_idx_type nz = m.nnz (); \
      RET_TYPE r (nr, nc, nz); \
      \
      for (octave_idx_type i = 0; i < nz; i++) \
        { \
          octave_quit (); \
-         r.data(i) = m.data(i) * s; \
-         r.ridx(i) = m.ridx(i); \
+         r.data (i) = m.data (i) * s; \
+         r.ridx (i) = m.ridx (i); \
        } \
      for (octave_idx_type i = 0; i < nc + 1; i++) \
        { \
          octave_quit (); \
-         r.cidx(i) = m.cidx(i); \
+         r.cidx (i) = m.cidx (i); \
        } \
      \
      r.maybe_compress (true); \
@@ -1900,26 +1900,26 @@
       RET_TYPE retval (nr, a_nc, static_cast<octave_idx_type> (0)); \
       for (octave_idx_type i = 0; i < nr; i++) \
         w[i] = 0; \
-      retval.xcidx(0) = 0; \
+      retval.xcidx (0) = 0; \
       \
       octave_idx_type nel = 0; \
       \
       for (octave_idx_type i = 0; i < a_nc; i++) \
         { \
-          for (octave_idx_type j = a.cidx(i); j < a.cidx(i+1); j++) \
+          for (octave_idx_type j = a.cidx (i); j < a.cidx (i+1); j++) \
             { \
-              octave_idx_type  col = a.ridx(j); \
-              for (octave_idx_type k = m.cidx(col) ; k < m.cidx(col+1); k++) \
+              octave_idx_type  col = a.ridx (j); \
+              for (octave_idx_type k = m.cidx (col) ; k < m.cidx (col+1); k++) \
                 { \
-                  if (w[m.ridx(k)] < i + 1) \
+                  if (w[m.ridx (k)] < i + 1) \
                     { \
-                      w[m.ridx(k)] = i + 1; \
+                      w[m.ridx (k)] = i + 1; \
                       nel++; \
                     } \
                   octave_quit (); \
                 } \
             } \
-          retval.xcidx(i+1) = nel; \
+          retval.xcidx (i+1) = nel; \
         } \
       \
       if (nel == 0) \
@@ -1946,62 +1946,62 @@
           octave_idx_type n_per_col = (a_nc > 43000 ? 43000 : \
                                         (a_nc * a_nc) / 43000); \
           octave_idx_type ii = 0; \
-          octave_idx_type *ri = retval.xridx(); \
+          octave_idx_type *ri = retval.xridx (); \
           octave_sort<octave_idx_type> sort; \
           \
           for (octave_idx_type i = 0; i < a_nc ; i++) \
             { \
-              if (retval.xcidx(i+1) - retval.xcidx(i) > n_per_col) \
+              if (retval.xcidx (i+1) - retval.xcidx (i) > n_per_col) \
                 { \
-                  for (octave_idx_type j = a.cidx(i); j < a.cidx(i+1); j++) \
+                  for (octave_idx_type j = a.cidx (i); j < a.cidx (i+1); j++) \
                     { \
-                      octave_idx_type col = a.ridx(j); \
-                      EL_TYPE tmpval = a.data(j); \
-                      for (octave_idx_type k = m.cidx(col) ; \
-                           k < m.cidx(col+1); k++) \
+                      octave_idx_type col = a.ridx (j); \
+                      EL_TYPE tmpval = a.data (j); \
+                      for (octave_idx_type k = m.cidx (col) ; \
+                           k < m.cidx (col+1); k++) \
                         { \
                           octave_quit (); \
-                          octave_idx_type row = m.ridx(k); \
+                          octave_idx_type row = m.ridx (k); \
                           if (w[row] < i + 1) \
                             { \
                               w[row] = i + 1; \
-                              Xcol[row] = tmpval * m.data(k); \
+                              Xcol[row] = tmpval * m.data (k); \
                             } \
                           else \
-                            Xcol[row] += tmpval * m.data(k); \
+                            Xcol[row] += tmpval * m.data (k); \
                         } \
                     } \
                   for (octave_idx_type k = 0; k < nr; k++) \
                     if (w[k] == i + 1) \
                       { \
-                        retval.xdata(ii) = Xcol[k]; \
-                        retval.xridx(ii++) = k; \
+                        retval.xdata (ii) = Xcol[k]; \
+                        retval.xridx (ii++) = k; \
                       } \
                 } \
               else \
                 { \
-                  for (octave_idx_type j = a.cidx(i); j < a.cidx(i+1); j++) \
+                  for (octave_idx_type j = a.cidx (i); j < a.cidx (i+1); j++) \
                     { \
-                      octave_idx_type col = a.ridx(j); \
-                      EL_TYPE tmpval = a.data(j); \
-                      for (octave_idx_type k = m.cidx(col) ; \
-                          k < m.cidx(col+1); k++) \
+                      octave_idx_type col = a.ridx (j); \
+                      EL_TYPE tmpval = a.data (j); \
+                      for (octave_idx_type k = m.cidx (col) ; \
+                          k < m.cidx (col+1); k++) \
                         { \
                           octave_quit (); \
-                          octave_idx_type row = m.ridx(k); \
+                          octave_idx_type row = m.ridx (k); \
                           if (w[row] < i + 1) \
                             { \
                               w[row] = i + 1; \
-                              retval.xridx(ii++) = row;\
-                              Xcol[row] = tmpval * m.data(k); \
+                              retval.xridx (ii++) = row;\
+                              Xcol[row] = tmpval * m.data (k); \
                             } \
                           else \
-                            Xcol[row] += tmpval * m.data(k); \
+                            Xcol[row] += tmpval * m.data (k); \
                         } \
                     } \
-                  sort.sort (ri + retval.xcidx(i), ii - retval.xcidx(i)); \
-                  for (octave_idx_type k = retval.xcidx(i); k < ii; k++) \
-                    retval.xdata(k) = Xcol[retval.xridx(k)]; \
+                  sort.sort (ri + retval.xcidx (i), ii - retval.xcidx (i)); \
+                  for (octave_idx_type k = retval.xcidx (i); k < ii; k++) \
+                    retval.xdata (k) = Xcol[retval.xridx (k)]; \
                 }  \
             } \
           retval.maybe_compress (true);\
@@ -2036,9 +2036,9 @@
             { \
               octave_quit (); \
               \
-              EL_TYPE tmpval = a.elem(j,i); \
-              for (octave_idx_type k = m.cidx(j) ; k < m.cidx(j+1); k++) \
-                retval.elem (m.ridx(k),i) += tmpval * m.data(k); \
+              EL_TYPE tmpval = a.elem (j,i); \
+              for (octave_idx_type k = m.cidx (j) ; k < m.cidx (j+1); k++) \
+                retval.elem (m.ridx (k),i) += tmpval * m.data (k); \
             } \
         } \
       return retval; \
@@ -2053,7 +2053,7 @@
   \
   if (nr == 1 && nc == 1) \
     { \
-      RET_TYPE retval = CONJ_OP (m.elem(0,0)) * a; \
+      RET_TYPE retval = CONJ_OP (m.elem (0,0)) * a; \
       return retval; \
     } \
   else if (nr != a_nr) \
@@ -2072,8 +2072,8 @@
               octave_quit (); \
               \
               EL_TYPE acc = ZERO; \
-              for (octave_idx_type k = m.cidx(j) ; k < m.cidx(j+1); k++) \
-                acc += a.elem (m.ridx(k),i) * CONJ_OP (m.data(k)); \
+              for (octave_idx_type k = m.cidx (j) ; k < m.cidx (j+1); k++) \
+                acc += a.elem (m.ridx (k),i) * CONJ_OP (m.data (k)); \
               retval.xelem (j,i) = acc; \
             } \
         } \
@@ -2104,13 +2104,13 @@
       for (octave_idx_type i = 0; i < a_nc ; i++) \
         { \
           octave_quit (); \
-          for (octave_idx_type j = a.cidx(i); j < a.cidx(i+1); j++) \
+          for (octave_idx_type j = a.cidx (i); j < a.cidx (i+1); j++) \
             { \
-              octave_idx_type col = a.ridx(j); \
-              EL_TYPE tmpval = a.data(j); \
+              octave_idx_type col = a.ridx (j); \
+              EL_TYPE tmpval = a.data (j); \
               \
               for (octave_idx_type k = 0 ; k < nr; k++) \
-                retval.xelem (k,i) += tmpval * m.elem(k,col); \
+                retval.xelem (k,i) += tmpval * m.elem (k,col); \
             } \
         } \
       return retval; \
@@ -2125,7 +2125,7 @@
   \
   if (a_nr == 1 && a_nc == 1) \
     { \
-      RET_TYPE retval = m * CONJ_OP (a.elem(0,0)); \
+      RET_TYPE retval = m * CONJ_OP (a.elem (0,0)); \
       return retval; \
     } \
   else if (nc != a_nc) \
@@ -2140,12 +2140,12 @@
       for (octave_idx_type i = 0; i < a_nc ; i++) \
         { \
           octave_quit (); \
-          for (octave_idx_type j = a.cidx(i); j < a.cidx(i+1); j++) \
+          for (octave_idx_type j = a.cidx (i); j < a.cidx (i+1); j++) \
             { \
-              octave_idx_type col = a.ridx(j); \
-              EL_TYPE tmpval = CONJ_OP (a.data(j)); \
+              octave_idx_type col = a.ridx (j); \
+              EL_TYPE tmpval = CONJ_OP (a.data (j)); \
               for (octave_idx_type k = 0 ; k < nr; k++) \
-                retval.xelem (k,col) += tmpval * m.elem(k,i); \
+                retval.xelem (k,col) += tmpval * m.elem (k,i); \
             } \
         } \
       return retval; \
rename from liboctave/Sparse-perm-op-defs.h
rename to liboctave/operators/Sparse-perm-op-defs.h
--- a/liboctave/Sparse-perm-op-defs.h
+++ b/liboctave/operators/Sparse-perm-op-defs.h
@@ -43,15 +43,15 @@
     {
       octave_quit ();
 
-      OCTAVE_LOCAL_BUFFER (octave_idx_type, sidx, r.xcidx(j+1) - r.xcidx(j));
-      for (octave_idx_type i = r.xcidx(j), ii = 0; i < r.xcidx(j+1); i++)
+      OCTAVE_LOCAL_BUFFER (octave_idx_type, sidx, r.xcidx (j+1) - r.xcidx (j));
+      for (octave_idx_type i = r.xcidx (j), ii = 0; i < r.xcidx (j+1); i++)
         {
           sidx[ii++]=i;
           r.xridx (i) = pcol[a.ridx (i)];
         }
-      sort.sort (r.xridx() + r.xcidx(j), sidx, r.xcidx(j+1) - r.xcidx(j));
-      for (octave_idx_type i = r.xcidx(j), ii = 0; i < r.xcidx(j+1); i++)
-        r.xdata(i) = a.data (sidx[ii++]);
+      sort.sort (r.xridx () + r.xcidx (j), sidx, r.xcidx (j+1) - r.xcidx (j));
+      for (octave_idx_type i = r.xcidx (j), ii = 0; i < r.xcidx (j+1); i++)
+        r.xdata (i) = a.data (sidx[ii++]);
     }
 
   return r;
@@ -71,7 +71,7 @@
     {
       // Form the column permutation and then call the colpm_sm routine.
       const octave_idx_type *prow = p.pvec ().data ();
-      OCTAVE_LOCAL_BUFFER(octave_idx_type, pcol, nr);
+      OCTAVE_LOCAL_BUFFER (octave_idx_type, pcol, nr);
       for (octave_idx_type i = 0; i < nr; ++i)
         pcol[prow[i]] = i;
       return octinternal_do_mul_colpm_sm (pcol, a);
rename from liboctave/config-ops.sh
rename to liboctave/operators/config-ops.sh
--- a/liboctave/config-ops.sh
+++ b/liboctave/operators/config-ops.sh
@@ -17,14 +17,14 @@
 fi
 
 if [ $# -lt 1 ]; then
-  top_srcdir=".."
+  top_srcdir="../.."
 else
   top_srcdir="$1"
 fi
 
 move_if_change="$top_srcdir/build-aux/move-if-change"
 
-liboctave_dir="$top_srcdir/liboctave"
+liboctave_dir="$top_srcdir/liboctave/operators"
 
 mk_ops="$liboctave_dir/mk-ops.awk"
 sparse_mk_ops="$liboctave_dir/sparse-mk-ops.awk"
rename from liboctave/mk-ops.awk
rename to liboctave/operators/mk-ops.awk
--- a/liboctave/mk-ops.awk
+++ b/liboctave/operators/mk-ops.awk
@@ -93,13 +93,13 @@
 
           if (list_cc_files)
             {
-              printf (" %s", cc_file);
+              printf (" operators/%s", cc_file);
               next;
             }
 
           if (list_h_files)
             {
-              printf (" %s", h_file);
+              printf (" operators/%s", h_file);
               next;
             }
 
new file mode 100644
--- /dev/null
+++ b/liboctave/operators/module.mk
@@ -0,0 +1,69 @@
+EXTRA_DIST += \
+  operators/module.mk \
+  operators/config-ops.sh \
+  operators/mk-ops.awk \
+  operators/mx-op-inc.mk \
+  operators/mx-op-src.mk \
+  operators/mx-ops \
+  operators/smx-op-inc.mk \
+  operators/smx-op-src.mk \
+  operators/sparse-mk-ops.awk \
+  operators/sparse-mx-ops \
+  operators/vx-op-inc.mk \
+  operators/vx-op-src.mk \
+  operators/vx-ops
+
+include operators/vx-op-inc.mk
+include operators/mx-op-inc.mk
+include operators/smx-op-inc.mk
+
+include operators/vx-op-src.mk
+include operators/mx-op-src.mk
+include operators/smx-op-src.mk
+
+BUILT_LIBOPERATORS_SOURCES = \
+  $(MX_OP_SRC) \
+  $(VX_OP_SRC) \
+  $(SMX_OP_SRC)
+
+OPERATORS_INC = \
+  operators/mx-base.h \
+  operators/mx-defs.h \
+  operators/mx-ext.h \
+  operators/mx-op-decl.h \
+  operators/mx-op-defs.h \
+  operators/Sparse-diag-op-defs.h \
+  operators/Sparse-op-defs.h \
+  operators/Sparse-perm-op-defs.h
+
+## There are no distributed source files in this directory
+OPERATORS_SRC =
+
+TEMPLATE_SRC += \
+  operators/mx-inlines.cc
+
+OP_SRCDIR = $(abs_top_srcdir)/liboctave/operators
+
+## Special rules for sources which must be built before rest of compilation.
+$(VX_OP_INC) $(VX_OP_SRC) : operators/mk-ops.awk operators/vx-ops
+	(cd operators; $(AWK) -f $(OP_SRCDIR)/mk-ops.awk prefix=vx $(OP_SRCDIR)/vx-ops)
+
+$(MX_OP_INC) $(MX_OP_SRC) : operators/mk-ops.awk operators/mx-ops
+	(cd operators; $(AWK) -f $(OP_SRCDIR)/mk-ops.awk prefix=mx $(OP_SRCDIR)/mx-ops)
+
+$(SMX_OP_INC) $(SMX_OP_SRC) : operators/sparse-mk-ops.awk operators/sparse-mx-ops
+	(cd operators; $(AWK) -f $(OP_SRCDIR)/sparse-mk-ops.awk prefix=smx $(OP_SRCDIR)/sparse-mx-ops)
+
+operators/mx-ops.h : operators/mk-ops.awk operators/mx-ops
+	$(AWK) -f $(OP_SRCDIR)/mk-ops.awk prefix=mx make_inclusive_header=mx-ops.h $(OP_SRCDIR)/mx-ops > $@-t
+	mv $@-t $@
+
+noinst_LTLIBRARIES += operators/liboperators.la
+
+operators_liboperators_la_SOURCES = $(OPERATORS_SRC)
+nodist_operators_liboperators_la_SOURCES = $(BUILT_LIBOPERATORS_SOURCES)
+
+operators_liboperators_la_CPPFLAGS = $(liboctave_la_CPPFLAGS)
+
+DISTCLEANFILES += $(BUILT_LIBOPERATORS_SOURCES)
+
rename from liboctave/mx-base.h
rename to liboctave/operators/mx-base.h
rename from liboctave/mx-defs.h
rename to liboctave/operators/mx-defs.h
rename from liboctave/mx-ext.h
rename to liboctave/operators/mx-ext.h
rename from liboctave/mx-inlines.cc
rename to liboctave/operators/mx-inlines.cc
--- a/liboctave/mx-inlines.cc
+++ b/liboctave/operators/mx-inlines.cc
@@ -62,7 +62,7 @@
 #define DEFMXUNBOOLOP(F, OP) \
 template <class X> \
 inline void F (size_t n, bool *r, const X *x) throw () \
-{ const X zero = X(); for (size_t i = 0; i < n; i++) r[i] = x[i] OP zero; }
+{ const X zero = X (); for (size_t i = 0; i < n; i++) r[i] = x[i] OP zero; }
 
 DEFMXUNBOOLOP (mx_inline_iszero, ==)
 DEFMXUNBOOLOP (mx_inline_notzero, !=)
@@ -483,12 +483,12 @@
 #define OP_RED_SUMSQ(ac, el) ac += el*el
 #define OP_RED_SUMSQC(ac, el) ac += cabsq (el)
 
-inline void op_dble_sum(double& ac, float el)
+inline void op_dble_sum (double& ac, float el)
 { ac += el; }
-inline void op_dble_sum(Complex& ac, const FloatComplex& el)
+inline void op_dble_sum (Complex& ac, const FloatComplex& el)
 { ac += el; } // FIXME: guaranteed?
 template <class T>
-inline void op_dble_sum(double& ac, const octave_int<T>& el)
+inline void op_dble_sum (double& ac, const octave_int<T>& el)
 { ac += el.double_value (); }
 
 // The following two implement a simple short-circuiting.
@@ -1177,7 +1177,7 @@
 {
   octave_idx_type l, n, u;
   dim_vector dims = src.dims ();
-  // M*b inconsistency: sum([]) = 0 etc.
+  // M*b inconsistency: sum ([]) = 0 etc.
   if (dims.length () == 2 && dims(0) == 0 && dims(1) == 0)
     dims (1) = 1;
 
rename from liboctave/mx-op-decl.h
rename to liboctave/operators/mx-op-decl.h
rename from liboctave/mx-op-defs.h
rename to liboctave/operators/mx-op-defs.h
--- a/liboctave/mx-op-defs.h
+++ b/liboctave/operators/mx-op-defs.h
@@ -413,7 +413,7 @@
           octave_idx_type len = dm.length (); \
  \
           for (octave_idx_type i = 0; i < len; i++) \
-            r.elem(i, i) OPEQ dm.elem(i, i); \
+            r.elem (i, i) OPEQ dm.elem (i, i); \
         } \
     } \
  \
@@ -483,7 +483,7 @@
           octave_idx_type len = dm.length (); \
  \
           for (octave_idx_type i = 0; i < len; i++) \
-            r.elem(i, i) OPEQ dm.elem(i, i); \
+            r.elem (i, i) OPEQ dm.elem (i, i); \
         } \
       else \
         r.resize (m_nr, m_nc); \
rename from liboctave/mx-ops
rename to liboctave/operators/mx-ops
--- a/liboctave/mx-ops
+++ b/liboctave/operators/mx-ops
@@ -16,7 +16,7 @@
 # along with Octave; see the file COPYING.  If not, see
 # <http://www.gnu.org/licenses/>.
 
-# NOTE: if this file changes, you must run autogen.sh and configure to
+# NOTE: if this file changes, you must run bootstrap and configure to
 # rebuild the source file lists for Make.
 
 # types
rename from liboctave/sparse-mk-ops.awk
rename to liboctave/operators/sparse-mk-ops.awk
--- a/liboctave/sparse-mk-ops.awk
+++ b/liboctave/operators/sparse-mk-ops.awk
@@ -92,13 +92,13 @@
 
           if (list_cc_files)
             {
-              printf (" %s", cc_file);
+              printf (" operators/%s", cc_file);
               next;
             }
 
           if (list_h_files)
             {
-              printf (" %s", h_file);
+              printf (" operators/%s", h_file);
               next;
             }
 
rename from liboctave/sparse-mx-ops
rename to liboctave/operators/sparse-mx-ops
--- a/liboctave/sparse-mx-ops
+++ b/liboctave/operators/sparse-mx-ops
@@ -16,7 +16,7 @@
 # along with Octave; see the file COPYING.  If not, see
 # <http://www.gnu.org/licenses/>.
 
-# NOTE: if this file changes, you must run autogen.sh and configure to
+# NOTE: if this file changes, you must run bootstrap and configure to
 # rebuild the source file lists for Make.
 
 # types
rename from liboctave/vx-ops
rename to liboctave/operators/vx-ops
--- a/liboctave/vx-ops
+++ b/liboctave/operators/vx-ops
@@ -16,7 +16,7 @@
 # along with Octave; see the file COPYING.  If not, see
 # <http://www.gnu.org/licenses/>.
 
-# NOTE: if this file changes, you must run autogen.sh and configure to
+# NOTE: if this file changes, you must run bootstrap and configure to
 # rebuild the source file lists for Make.
 
 # types
rename from liboctave/dir-ops.cc
rename to liboctave/system/dir-ops.cc
rename from liboctave/dir-ops.h
rename to liboctave/system/dir-ops.h
rename from liboctave/file-ops.cc
rename to liboctave/system/file-ops.cc
--- a/liboctave/file-ops.cc
+++ b/liboctave/system/file-ops.cc
@@ -37,6 +37,7 @@
 #include <unistd.h>
 
 #include "pathmax.h"
+#include "canonicalize.h"
 
 #include "dir-ops.h"
 #include "file-ops.h"
@@ -356,7 +357,7 @@
 {
   return dir.empty ()
     ? file
-    : (is_dir_sep (dir[dir.length()-1])
+    : (is_dir_sep (dir[dir.length ()-1])
        ? dir + file
        : dir + dir_sep_char () + file);
 }
rename from liboctave/file-ops.h
rename to liboctave/system/file-ops.h
rename from liboctave/file-stat.cc
rename to liboctave/system/file-stat.cc
--- a/liboctave/file-stat.cc
+++ b/liboctave/system/file-stat.cc
@@ -189,7 +189,7 @@
       // Remove trailing slash.
       if (file_ops::is_dir_sep (full_file_name[full_file_name.length () - 1])
           && full_file_name.length () != 1
-          && ! (full_file_name.length() == 3 && full_file_name[1] == ':'))
+          && ! (full_file_name.length () == 3 && full_file_name[1] == ':'))
         full_file_name.resize (full_file_name.length () - 1);
 #endif
 
rename from liboctave/file-stat.h
rename to liboctave/system/file-stat.h
rename from liboctave/lo-sysdep.cc
rename to liboctave/system/lo-sysdep.cc
--- a/liboctave/lo-sysdep.cc
+++ b/liboctave/system/lo-sysdep.cc
@@ -73,7 +73,7 @@
   std::string path = file_ops::tilde_expand (path_arg);
 
 #if defined (__WIN32__) && ! defined (__CYGWIN__)
-  if (path.length() == 2 && path[1] == ':')
+  if (path.length () == 2 && path[1] == ':')
     path += "\\";
 #endif
 
@@ -90,7 +90,7 @@
   PROCESS_INFORMATION pi;
   STARTUPINFO si;
   std::string command = "\"" + cmd + "\"";
-  HANDLE hProcess = GetCurrentProcess(), childRead, childWrite, parentRead, parentWrite;
+  HANDLE hProcess = GetCurrentProcess (), childRead, childWrite, parentRead, parentWrite;
   DWORD pipeMode;
 
   ZeroMemory (&pi, sizeof (pi));
@@ -114,14 +114,14 @@
       pipeMode = PIPE_NOWAIT;
       SetNamedPipeHandleState (parentRead, &pipeMode, 0, 0);
     }
-  fildes[1] = _open_osfhandle (reinterpret_cast<long> (parentRead), _O_RDONLY | _O_BINARY);
-  fildes[0] = _open_osfhandle (reinterpret_cast<long> (parentWrite), _O_WRONLY | _O_BINARY);
+  fildes[1] = _open_osfhandle (reinterpret_cast<intptr_t> (parentRead), _O_RDONLY | _O_BINARY);
+  fildes[0] = _open_osfhandle (reinterpret_cast<intptr_t> (parentWrite), _O_WRONLY | _O_BINARY);
   si.dwFlags |= STARTF_USESTDHANDLES;
   si.hStdInput = childRead;
   si.hStdOutput = childWrite;
 
   // Ignore first arg as it is the command
-  for (int k=1; k<args.length(); k++)
+  for (int k=1; k<args.length (); k++)
     command += " \"" + args[k] + "\"";
   OCTAVE_LOCAL_BUFFER (char, c_command, command.length () + 1);
   strcpy (c_command, command.c_str ());
rename from liboctave/lo-sysdep.h
rename to liboctave/system/lo-sysdep.h
rename from liboctave/mach-info.cc
rename to liboctave/system/mach-info.cc
--- a/liboctave/mach-info.cc
+++ b/liboctave/system/mach-info.cc
@@ -237,19 +237,19 @@
   switch (flt_fmt)
     {
     case flt_fmt_ieee_big_endian:
-      retval = "ieee_big_endian";
+      retval = "ieee-be";
       break;
 
     case flt_fmt_ieee_little_endian:
-      retval = "ieee_little_endian";
+      retval = "ieee-le";
       break;
 
     case flt_fmt_vax_d:
-      retval = "vax_d_float";
+      retval = "vaxd";
       break;
 
     case flt_fmt_vax_g:
-      retval = "vax_g_float";
+      retval = "vaxg";
       break;
 
     case flt_fmt_cray:
rename from liboctave/mach-info.h
rename to liboctave/system/mach-info.h
new file mode 100644
--- /dev/null
+++ b/liboctave/system/module.mk
@@ -0,0 +1,43 @@
+EXTRA_DIST += \
+  system/module.mk
+
+SYSTEM_INC = \
+  system/dir-ops.h \
+  system/file-ops.h \
+  system/file-stat.h \
+  system/lo-sysdep.h \
+  system/mach-info.h \
+  system/oct-env.h \
+  system/oct-group.h \
+  system/oct-openmp.h \
+  system/oct-passwd.h \
+  system/oct-syscalls.h \
+  system/oct-time.h \
+  system/oct-uname.h \
+  system/pathlen.h \
+  system/sysdir.h \
+  system/syswait.h
+
+SYSTEM_C_SRC = \
+  system/tempnam.c \
+  system/tempname.c
+
+SYSTEM_SRC = \
+  system/dir-ops.cc \
+  system/file-ops.cc \
+  system/file-stat.cc \
+  system/lo-sysdep.cc \
+  system/mach-info.cc \
+  system/oct-env.cc \
+  system/oct-group.cc \
+  system/oct-passwd.cc \
+  system/oct-syscalls.cc \
+  system/oct-time.cc \
+  system/oct-uname.cc \
+  $(SYSTEM_C_SRC)
+
+noinst_LTLIBRARIES += system/libsystem.la
+
+system_libsystem_la_SOURCES = $(SYSTEM_SRC)
+system_libsystem_la_CPPFLAGS = $(liboctave_la_CPPFLAGS)
+
rename from liboctave/oct-env.cc
rename to liboctave/system/oct-env.cc
rename from liboctave/oct-env.h
rename to liboctave/system/oct-env.h
rename from liboctave/oct-group.cc
rename to liboctave/system/oct-group.cc
rename from liboctave/oct-group.h
rename to liboctave/system/oct-group.h
--- a/liboctave/oct-group.h
+++ b/liboctave/system/oct-group.h
@@ -48,7 +48,7 @@
   {
     if (this != &gr)
       {
-        gr_name  = gr.gr_name;
+        gr_name = gr.gr_name;
         gr_passwd = gr.gr_passwd;
         gr_gid = gr.gr_gid;
         gr_mem = gr.gr_mem;
rename from liboctave/oct-openmp.h
rename to liboctave/system/oct-openmp.h
rename from liboctave/oct-passwd.cc
rename to liboctave/system/oct-passwd.cc
rename from liboctave/oct-passwd.h
rename to liboctave/system/oct-passwd.h
rename from liboctave/oct-syscalls.cc
rename to liboctave/system/oct-syscalls.cc
--- a/liboctave/oct-syscalls.cc
+++ b/liboctave/system/oct-syscalls.cc
@@ -356,9 +356,9 @@
               else
                 child_msg = "popen2 (child): file handle duplication failed -- " + child_msg;
 
-              (*current_liboctave_error_handler)(child_msg.c_str());
+              (*current_liboctave_error_handler)(child_msg.c_str ());
 
-              exit(0);
+              exit (0);
             }
           else
             {
@@ -372,8 +372,8 @@
               else
 #endif
                 {
-                  fildes[0] = child_stdin [1];
-                  fildes[1] = child_stdout [0];
+                  fildes[0] = child_stdin[1];
+                  fildes[1] = child_stdout[0];
                   return pid;
                 }
             }
rename from liboctave/oct-syscalls.h
rename to liboctave/system/oct-syscalls.h
rename from liboctave/oct-time.cc
rename to liboctave/system/oct-time.cc
--- a/liboctave/oct-time.cc
+++ b/liboctave/system/oct-time.cc
@@ -24,7 +24,8 @@
 #include <config.h>
 #endif
 
-#include <climits>
+#include <limits>
+
 #include <ctime>
 
 #include <sys/time.h>
@@ -121,7 +122,8 @@
 DEFINE_SET_INT_FIELD_FCN (hour, 0, 23)
 DEFINE_SET_INT_FIELD_FCN (mday, 1, 31)
 DEFINE_SET_INT_FIELD_FCN (mon, 0, 11)
-DEFINE_SET_INT_FIELD_FCN (year, INT_MIN, INT_MAX)
+DEFINE_SET_INT_FIELD_FCN (year, std::numeric_limits<int>::min (),
+                          std::numeric_limitd<int>::max ())
 DEFINE_SET_INT_FIELD_FCN (wday, 0, 6)
 DEFINE_SET_INT_FIELD_FCN (yday, 0, 365)
 DEFINE_SET_INT_FIELD_FCN (isdst, 0, 1)
@@ -175,7 +177,7 @@
       while (chars_written == 0)
         {
           delete [] buf;
-          buf = new char[bufsize];
+          buf = new char [bufsize];
           buf[0] = '\0';
 
           chars_written = nstrftime (buf, bufsize, fmt_str, &t, 0, 0);
@@ -256,7 +258,7 @@
   t.tm_hour = 0;
   t.tm_mday = 0;
   t.tm_mon = -1;
-  t.tm_year = INT_MIN;
+  t.tm_year = std::numeric_limits<int>::min ();
   t.tm_wday = 0;
   t.tm_yday = 0;
   t.tm_isdst = 0;
@@ -276,7 +278,8 @@
 
   // Fill in wday and yday, but only if mday is valid and the mon and year
   // are filled in, avoiding issues with mktime and invalid dates.
-  if (t.tm_mday != 0 && t.tm_mon >= 0 && t.tm_year != INT_MIN)
+  if (t.tm_mday != 0 && t.tm_mon >= 0
+      && t.tm_year != std::numeric_limits<int>::min ())
     {
       t.tm_isdst = -1;
       gnulib::mktime (&t);
@@ -285,7 +288,7 @@
   if (t.tm_mon < 0)
     t.tm_mon = 0;
 
-  if (t.tm_year == INT_MIN)
+  if (t.tm_year == std::numeric_limits<int>::min ())
     t.tm_year = 0;
 
   if (q)
rename from liboctave/oct-time.h
rename to liboctave/system/oct-time.h
rename from liboctave/oct-uname.cc
rename to liboctave/system/oct-uname.cc
rename from liboctave/oct-uname.h
rename to liboctave/system/oct-uname.h
rename from liboctave/pathlen.h
rename to liboctave/system/pathlen.h
rename from liboctave/sysdir.h
rename to liboctave/system/sysdir.h
rename from liboctave/syswait.h
rename to liboctave/system/syswait.h
rename from liboctave/tempnam.c
rename to liboctave/system/tempnam.c
--- a/liboctave/tempnam.c
+++ b/liboctave/system/tempnam.c
@@ -43,16 +43,16 @@
 {
   size_t len;
   register char *s;
-  register char *t = __stdio_gen_tempname(dir, pfx, 1, &len, (FILE **) NULL);
+  register char *t = __stdio_gen_tempname (dir, pfx, 1, &len, (FILE **) NULL);
 
   if (t == NULL)
     return NULL;
 
-  s = (char *) malloc(len);
+  s = (char *) malloc (len);
   if (s == NULL)
     return NULL;
 
-  (void) memcpy(s, t, len);
+  (void) memcpy (s, t, len);
   return s;
 }
 
rename from liboctave/tempname.c
rename to liboctave/system/tempname.c
--- a/liboctave/tempname.c
+++ b/liboctave/system/tempname.c
@@ -107,19 +107,19 @@
   size_t *idx;
   static char buf[FILENAME_MAX];
   static pid_t oldpid = (pid_t) 0;
-  pid_t pid = getpid();
+  pid_t pid = getpid ();
   register size_t len, plen, dlen;
 
   if (dir_search)
     {
-      register const char *d = getenv("TMPDIR");
-      if (d != NULL && !diraccess(d))
+      register const char *d = getenv ("TMPDIR");
+      if (d != NULL && !diraccess (d))
         d = NULL;
-      if (d == NULL && dir != NULL && diraccess(dir))
+      if (d == NULL && dir != NULL && diraccess (dir))
         d = dir;
-      if (d == NULL && diraccess(tmpdir))
+      if (d == NULL && diraccess (tmpdir))
         d = tmpdir;
-      if (d == NULL && diraccess("/tmp"))
+      if (d == NULL && diraccess ("/tmp"))
         d = "/tmp";
       if (d == NULL)
         {
@@ -139,14 +139,14 @@
 
   if (pfx != NULL && *pfx != '\0')
     {
-      plen = strlen(pfx);
+      plen = strlen (pfx);
       if (plen > 5)
         plen = 5;
     }
   else
     plen = 0;
 
-  if (dir != tmpdir && !strcmp(dir, tmpdir))
+  if (dir != tmpdir && !strcmp (dir, tmpdir))
     dir = tmpdir;
   idx = &indices[(plen == 0 && dir == tmpdir) ? 1 : 0];
 
rename from liboctave/base-list.h
rename to liboctave/util/base-list.h
--- a/liboctave/base-list.h
+++ b/liboctave/util/base-list.h
@@ -23,6 +23,8 @@
 #if !defined (octave_base_list_h)
 #define octave_base_list_h 1
 
+#include <cstdlib>
+
 #include <list>
 
 template <typename elt_type>
rename from liboctave/byte-swap.h
rename to liboctave/util/byte-swap.h
rename from liboctave/caseless-str.h
rename to liboctave/util/caseless-str.h
--- a/liboctave/caseless-str.h
+++ b/liboctave/util/caseless-str.h
@@ -23,6 +23,7 @@
 #if !defined (octave_caseless_str_h)
 #define octave_caseless_str_h 1
 
+#include <cctype>
 #include <string>
 
 class caseless_str : public std::string
rename from liboctave/cmd-edit.cc
rename to liboctave/util/cmd-edit.cc
--- a/liboctave/cmd-edit.cc
+++ b/liboctave/util/cmd-edit.cc
@@ -48,6 +48,8 @@
 
 std::set<command_editor::startup_hook_fcn> command_editor::startup_hook_set;
 
+std::set<command_editor::pre_input_hook_fcn> command_editor::pre_input_hook_set;
+
 std::set<command_editor::event_hook_fcn> command_editor::event_hook_set;
 
 static octave_mutex event_hook_lock;
@@ -66,6 +68,8 @@
 
   typedef command_editor::startup_hook_fcn startup_hook_fcn;
 
+  typedef command_editor::pre_input_hook_fcn pre_input_hook_fcn;
+
   typedef command_editor::event_hook_fcn event_hook_fcn;
 
   typedef command_editor::completion_fcn completion_fcn;
@@ -86,11 +90,13 @@
 
   FILE *do_get_output_stream (void);
 
+  void do_redisplay (void);
+
   int do_terminal_rows (void);
 
   int do_terminal_cols (void);
 
-  void do_clear_screen (void);
+  void do_clear_screen (bool skip_redisplay);
 
   void do_resize_terminal (void);
 
@@ -137,18 +143,28 @@
 
   std::string do_get_line_buffer (void) const;
 
+  std::string do_get_current_line (void) const;
+
+  void do_replace_line (const std::string& text, bool clear_undo);
+
   void do_insert_text (const std::string& text);
 
   void do_newline (void);
 
   void do_accept_line (void);
 
+  bool do_undo (void);
+
   void do_clear_undo_list (void);
 
   void set_startup_hook (startup_hook_fcn f);
 
   void restore_startup_hook (void);
 
+  void set_pre_input_hook (pre_input_hook_fcn f);
+
+  void restore_pre_input_hook (void);
+
   void set_event_hook (event_hook_fcn f);
 
   void restore_event_hook (void);
@@ -163,6 +179,8 @@
 
   bool do_filename_quoting_desired (bool);
 
+  void do_interrupt (bool);
+
   static int operate_and_get_next (int, int);
 
   static int history_search_backward (int, int);
@@ -173,6 +191,8 @@
 
   startup_hook_fcn previous_startup_hook;
 
+  pre_input_hook_fcn previous_pre_input_hook;
+
   event_hook_fcn previous_event_hook;
 
   completion_fcn completion_function;
@@ -199,6 +219,7 @@
 
 gnu_readline::gnu_readline ()
   : command_editor (), previous_startup_hook (0),
+    previous_pre_input_hook (0),
     previous_event_hook (0), completion_function (0),
     quoting_function (0), dequoting_function (0),
     char_is_quoted_function (0), user_accept_line_function (0)
@@ -290,6 +311,12 @@
   return ::octave_rl_get_output_stream ();
 }
 
+void
+gnu_readline::do_redisplay (void)
+{
+  ::octave_rl_redisplay ();
+}
+
 // GNU readline handles SIGWINCH, so these values have a good chance
 // of being correct even if the window changes size (they may be
 // wrong if, for example, the luser changes the window size while the
@@ -313,9 +340,9 @@
 }
 
 void
-gnu_readline::do_clear_screen (void)
+gnu_readline::do_clear_screen (bool skip_redisplay)
 {
-  ::octave_rl_clear_screen ();
+  ::octave_rl_clear_screen (skip_redisplay);
 }
 
 void
@@ -510,6 +537,22 @@
   return ::octave_rl_line_buffer ();
 }
 
+std::string
+gnu_readline::do_get_current_line (void) const
+{
+  std::string retval;
+  char *buf = ::octave_rl_copy_line ();
+  retval = buf;
+  free (buf);
+  return retval;
+}
+
+void
+gnu_readline::do_replace_line (const std::string& text, bool clear_undo)
+{
+  ::octave_rl_replace_line (text.c_str (), clear_undo);
+}
+
 void
 gnu_readline::do_insert_text (const std::string& text)
 {
@@ -528,6 +571,12 @@
   command_accept_line (1, '\n');
 }
 
+bool
+gnu_readline::do_undo (void)
+{
+  return ::octave_rl_do_undo ();
+}
+
 void
 gnu_readline::do_clear_undo_list ()
 {
@@ -550,6 +599,21 @@
 }
 
 void
+gnu_readline::set_pre_input_hook (pre_input_hook_fcn f)
+{
+  previous_pre_input_hook = ::octave_rl_get_pre_input_hook ();
+
+  if (f != previous_pre_input_hook)
+    ::octave_rl_set_pre_input_hook (f);
+}
+
+void
+gnu_readline::restore_pre_input_hook (void)
+{
+  ::octave_rl_set_pre_input_hook (previous_pre_input_hook);
+}
+
+void
 gnu_readline::set_event_hook (event_hook_fcn f)
 {
   previous_event_hook = octave_rl_get_event_hook ();
@@ -587,6 +651,12 @@
   return ::octave_rl_filename_quoting_desired (arg);
 }
 
+void
+gnu_readline::do_interrupt (bool arg)
+{
+  ::octave_rl_done (arg);
+}
+
 int
 gnu_readline::operate_and_get_next (int /* count */, int /* c */)
 {
@@ -743,7 +813,11 @@
 
   std::string do_get_line_buffer (void) const;
 
-  void do_insert_text (const std::string&);
+  std::string do_get_current_line (void) const;
+
+  void do_replace_line (const std::string& text, bool clear_undo);
+
+  void do_insert_text (const std::string& text);
 
   void do_newline (void);
 
@@ -808,6 +882,19 @@
   return "";
 }
 
+std::string
+default_command_editor::do_get_current_line (void) const
+{
+  // FIXME
+  return std::string ();
+}
+
+void
+default_command_editor::do_replace_line (const std::string&, bool)
+{
+  // FIXME
+}
+
 void
 default_command_editor::do_insert_text (const std::string&)
 {
@@ -867,6 +954,19 @@
   instance = new default_command_editor ();
 }
 
+void
+command_editor::set_initial_input (const std::string& text)
+{
+  if (instance_ok ())
+    instance->initial_input = text;
+}
+
+int
+command_editor::insert_initial_input (void)
+{
+  return instance_ok () ? instance->do_insert_initial_input () : 0;
+}
+
 int
 command_editor::startup_handler (void)
 {
@@ -883,6 +983,21 @@
 }
 
 int
+command_editor::pre_input_handler (void)
+{
+  for (pre_input_hook_set_iterator p = pre_input_hook_set.begin ();
+       p != pre_input_hook_set.end (); p++)
+    {
+      pre_input_hook_fcn f = *p;
+
+      if (f)
+        f ();
+    }
+
+  return 0;
+}
+
+int
 command_editor::event_handler (void)
 {
   event_hook_lock.lock ();
@@ -921,8 +1036,17 @@
 std::string
 command_editor::readline (const std::string& prompt, bool& eof)
 {
-  return (instance_ok ())
-    ? instance->do_readline (prompt, eof) : std::string ();
+  std::string retval;
+
+  if (instance_ok ())
+    {
+      if (! instance->initial_input.empty ())
+        add_pre_input_hook (command_editor::insert_initial_input);
+
+      retval = instance->do_readline (prompt, eof);
+    }
+
+  return retval;
 }
 
 void
@@ -953,6 +1077,13 @@
     ? instance->do_get_output_stream () : 0;
 }
 
+void
+command_editor::redisplay (void)
+{
+  if (instance_ok ())
+    instance->do_redisplay ();
+}
+
 int
 command_editor::terminal_rows (void)
 {
@@ -968,10 +1099,10 @@
 }
 
 void
-command_editor::clear_screen (void)
+command_editor::clear_screen (bool skip_redisplay)
 {
   if (instance_ok ())
-    instance->do_clear_screen ();
+    instance->do_clear_screen (skip_redisplay);
 }
 
 void
@@ -1148,6 +1279,19 @@
   return (instance_ok ()) ? instance->do_get_line_buffer () : "";
 }
 
+std::string
+command_editor::get_current_line (void)
+{
+  return (instance_ok ()) ? instance->do_get_current_line () : "";
+}
+
+void
+command_editor::replace_line (const std::string& text, bool clear_undo)
+{
+  if (instance_ok ())
+    instance->do_replace_line (text, clear_undo);
+}
+
 void
 command_editor::insert_text (const std::string& text)
 {
@@ -1169,6 +1313,12 @@
     instance->do_accept_line ();
 }
 
+bool
+command_editor::undo (void)
+{
+  return instance_ok () ? instance->do_undo () : false;
+}
+
 void
 command_editor::clear_undo_list (void)
 {
@@ -1203,6 +1353,32 @@
 }
 
 void
+command_editor::add_pre_input_hook (pre_input_hook_fcn f)
+{
+  if (instance_ok ())
+    {
+      pre_input_hook_set.insert (f);
+
+      instance->set_pre_input_hook (pre_input_handler);
+    }
+}
+
+void
+command_editor::remove_pre_input_hook (pre_input_hook_fcn f)
+{
+  if (instance_ok ())
+    {
+      pre_input_hook_set_iterator p = pre_input_hook_set.find (f);
+
+      if (p != pre_input_hook_set.end ())
+        pre_input_hook_set.erase (p);
+
+      if (pre_input_hook_set.empty ())
+        instance->restore_pre_input_hook ();
+    }
+}
+
+void
 command_editor::add_event_hook (event_hook_fcn f)
 {
   octave_autolock guard (event_hook_lock);
@@ -1270,6 +1446,26 @@
     ? instance->do_filename_quoting_desired (arg) : false;
 }
 
+bool
+command_editor::interrupt (bool arg)
+{
+  bool retval;
+
+  if (instance_ok ())
+    {
+      // Return the current interrupt state.
+      retval = instance->interrupted;
+
+      instance->do_interrupt (arg);
+
+      instance->interrupted = arg;
+    }
+  else
+    retval = false;
+
+  return retval;
+}
+
 // Return a string which will be printed as a prompt.  The string may
 // contain special characters which are decoded as follows:
 //
@@ -1529,6 +1725,21 @@
   return result;
 }
 
+int
+command_editor::do_insert_initial_input (void)
+{
+  std::string input = initial_input;
+
+  initial_input = "";
+
+  do_insert_text (input);
+
+  // Is it really right to redisplay here?
+  do_redisplay ();
+
+  return 0;
+}
+
 // Return the octal number parsed from STRING, or -1 to indicate that
 // the string contained a bad number.
 
rename from liboctave/cmd-edit.h
rename to liboctave/util/cmd-edit.h
--- a/liboctave/cmd-edit.h
+++ b/liboctave/util/cmd-edit.h
@@ -37,12 +37,14 @@
 protected:
 
   command_editor (void)
-    : command_number (0) { }
+    : command_number (0), interrupted (false), initial_input () { }
 
 public:
 
   typedef int (*startup_hook_fcn) (void);
 
+  typedef int (*pre_input_hook_fcn) (void);
+
   typedef int (*event_hook_fcn) (void);
 
   typedef std::string (*completion_fcn) (const std::string&, int);
@@ -71,11 +73,13 @@
 
   static FILE *get_output_stream (void);
 
+  static void redisplay (void);
+
   static int terminal_rows (void);
 
   static int terminal_cols (void);
 
-  static void clear_screen (void);
+  static void clear_screen (bool skip_redisplay = false);
 
   static void resize_terminal (void);
 
@@ -121,18 +125,28 @@
 
   static std::string get_line_buffer (void);
 
+  static std::string get_current_line (void);
+
+  static void replace_line (const std::string& text, bool clear_undo = true);
+
   static void insert_text (const std::string& text);
 
   static void newline (void);
 
   static void accept_line (void);
 
+  static bool undo (void);
+
   static void clear_undo_list (void);
 
   static void add_startup_hook (startup_hook_fcn f);
 
   static void remove_startup_hook (startup_hook_fcn f);
 
+  static void add_pre_input_hook (pre_input_hook_fcn f);
+
+  static void remove_pre_input_hook (pre_input_hook_fcn f);
+
   static void add_event_hook (event_hook_fcn f);
 
   static void remove_event_hook (event_hook_fcn f);
@@ -147,6 +161,8 @@
 
   static bool filename_quoting_desired (bool);
 
+  static bool interrupt (bool = true);
+
   static int current_command_number (void);
 
   static void reset_current_command_number (int n);
@@ -155,6 +171,10 @@
 
   static void force_default_editor (void);
 
+  static void set_initial_input (const std::string& text);
+
+  static int insert_initial_input (void);
+
 private:
 
   // No copying!
@@ -169,15 +189,22 @@
 
   static int startup_handler (void);
 
+  static int pre_input_handler (void);
+
   static int event_handler (void);
 
   static std::set<startup_hook_fcn> startup_hook_set;
 
+  static std::set<pre_input_hook_fcn> pre_input_hook_set;
+
   static std::set<event_hook_fcn> event_hook_set;
 
   typedef std::set<startup_hook_fcn>::iterator startup_hook_set_iterator;
   typedef std::set<startup_hook_fcn>::const_iterator startup_hook_set_const_iterator;
 
+  typedef std::set<pre_input_hook_fcn>::iterator pre_input_hook_set_iterator;
+  typedef std::set<pre_input_hook_fcn>::const_iterator pre_input_hook_set_const_iterator;
+
   typedef std::set<event_hook_fcn>::iterator event_hook_set_iterator;
   typedef std::set<event_hook_fcn>::const_iterator event_hook_set_const_iterator;
 
@@ -211,11 +238,13 @@
 
   virtual FILE *do_get_output_stream (void) = 0;
 
+  virtual void do_redisplay (void) { }
+
   virtual int do_terminal_rows (void) { return 24; }
 
   virtual int do_terminal_cols (void) { return 80; }
 
-  virtual void do_clear_screen (void) { }
+  virtual void do_clear_screen (bool) { }
 
   virtual void do_resize_terminal (void) { }
 
@@ -263,19 +292,29 @@
 
   virtual std::string do_get_line_buffer (void) const = 0;
 
-  virtual void do_insert_text (const std::string&) = 0;
+  virtual std::string do_get_current_line (void) const = 0;
+
+  virtual void do_replace_line (const std::string& text, bool clear_undo) = 0;
+
+  virtual void do_insert_text (const std::string& text) = 0;
 
   virtual void do_newline (void) = 0;
 
   virtual void do_accept_line (void) = 0;
 
+  virtual bool do_undo (void) { return false; }
+
   virtual void do_clear_undo_list (void) { }
 
   virtual void set_startup_hook (startup_hook_fcn) { }
 
   virtual void restore_startup_hook (void) { }
 
-  virtual void set_event_hook (startup_hook_fcn) { }
+  virtual void set_pre_input_hook (pre_input_hook_fcn) { }
+
+  virtual void restore_pre_input_hook (void) { }
+
+  virtual void set_event_hook (event_hook_fcn) { }
 
   virtual void restore_event_hook (void) { }
 
@@ -287,6 +326,10 @@
 
   virtual bool do_filename_quoting_desired (bool) { return false; }
 
+  virtual void do_interrupt (bool) { }
+
+  int do_insert_initial_input (void);
+
   int read_octal (const std::string& s);
 
   void error (int);
@@ -295,6 +338,10 @@
 
   // The current command number.
   int command_number;
+
+  bool interrupted;
+
+  std::string initial_input;
 };
 
 #endif
rename from liboctave/cmd-hist.cc
rename to liboctave/util/cmd-hist.cc
--- a/liboctave/cmd-hist.cc
+++ b/liboctave/util/cmd-hist.cc
@@ -69,6 +69,8 @@
 
   void do_remove (int);
 
+  void do_clear (void);
+
   int do_where (void) const;
 
   int do_length (void) const;
@@ -165,7 +167,7 @@
 
   if (history_control & HC_IGNDUPS)
     {
-      if (retval.length() > 0)
+      if (retval.length () > 0)
         retval.append (":");
 
       retval.append ("ignoredups");
@@ -173,7 +175,7 @@
 
   if (history_control & HC_ERASEDUPS)
     {
-      if (retval.length() > 0)
+      if (retval.length () > 0)
         retval.append (":");
 
       retval.append ("erasedups");
@@ -190,8 +192,14 @@
       if (s.empty ()
           || (s.length () == 1 && (s[0] == '\r' || s[0] == '\n')))
         return;
+     
+      // Strip newline before adding to list
+      std::string stmp = s;
+      int stmp_len = stmp.length ();
+      if (stmp[stmp_len - 1] == '\n')
+        stmp.resize (stmp_len - 1);
 
-      lines_this_session += ::octave_add_history (s.c_str (), history_control);
+      lines_this_session += ::octave_add_history (stmp.c_str (), history_control);
     }
 }
 
@@ -201,6 +209,12 @@
   ::octave_remove_history (n);
 }
 
+void
+gnu_history::do_clear (void)
+{
+  ::octave_clear_history ();
+}
+
 int
 gnu_history::do_where (void) const
 {
@@ -535,7 +549,7 @@
 command_history::process_histcontrol (const std::string& control_arg)
 {
   if (instance_ok ())
-    instance->do_process_histcontrol(control_arg);
+    instance->do_process_histcontrol (control_arg);
 }
 
 std::string
@@ -587,6 +601,13 @@
     instance->do_remove (n);
 }
 
+void
+command_history::clear (void)
+{
+  if (instance_ok ())
+    instance->do_clear ();
+}
+
 int
 command_history::where (void)
 {
@@ -807,6 +828,11 @@
 {
 }
 
+void
+command_history::do_clear (void)
+{
+}
+
 int
 command_history::do_where (void) const
 {
rename from liboctave/cmd-hist.h
rename to liboctave/util/cmd-hist.h
--- a/liboctave/cmd-hist.h
+++ b/liboctave/util/cmd-hist.h
@@ -65,6 +65,8 @@
 
   static void remove (int);
 
+  static void clear (void);
+
   static int where (void);
 
   static int length (void);
@@ -158,6 +160,8 @@
 
   virtual void do_remove (int);
 
+  virtual void do_clear (void);
+
   virtual int do_where (void) const;
 
   virtual int do_length (void) const;
rename from liboctave/data-conv.cc
rename to liboctave/util/data-conv.cc
--- a/liboctave/data-conv.cc
+++ b/liboctave/util/data-conv.cc
@@ -25,6 +25,7 @@
 #endif
 
 #include <cctype>
+#include <climits>
 #include <cstdlib>
 
 #include <iostream>
@@ -486,7 +487,8 @@
       if (len > 0) \
         { \
           OCTAVE_LOCAL_BUFFER (TYPE, ptr, len); \
-          stream.read (reinterpret_cast<char *>  (ptr), size * len); \
+          std::streamsize n_bytes = size * len; \
+          stream.read (reinterpret_cast<char *> (ptr), n_bytes); \
           if (swap) \
             swap_bytes< size > (ptr, len); \
           for (octave_idx_type i = 0; i < len; i++) \
@@ -496,7 +498,7 @@
   while (0)
 
 // Have to use copy here to avoid writing over data accessed via
-// Matrix::data().
+// Matrix::data ().
 
 #define LS_DO_WRITE(TYPE, data, size, len, stream) \
   do \
@@ -508,7 +510,8 @@
           OCTAVE_LOCAL_BUFFER (TYPE, ptr, len); \
           for (octave_idx_type i = 0; i < len; i++) \
             ptr[i] = static_cast <TYPE> (data[i]);         \
-          stream.write (reinterpret_cast<char *> (ptr), size * len); \
+          std::streamsize n_bytes = size * len; \
+          stream.write (reinterpret_cast<char *> (ptr), n_bytes); \
         } \
     } \
   while (0)
@@ -1007,7 +1010,6 @@
     }
 }
 
-
 void
 read_doubles (std::istream& is, double *data, save_type type,
               octave_idx_type len, bool swap,
@@ -1042,7 +1044,8 @@
     case LS_FLOAT:
       {
         OCTAVE_LOCAL_BUFFER (float, ptr, len);
-        is.read (reinterpret_cast<char *> (ptr), 4 * len);
+        std::streamsize n_bytes = 4 * len;
+        is.read (reinterpret_cast<char *> (ptr), n_bytes);
         do_float_format_conversion (ptr, len, fmt);
         for (octave_idx_type i = 0; i < len; i++)
           data[i] = ptr[i];
@@ -1051,7 +1054,8 @@
 
     case LS_DOUBLE: // No conversion necessary.
       {
-        is.read (reinterpret_cast<char *> (data), 8 * len);
+        std::streamsize n_bytes = 8 * static_cast<std::streamsize> (len);
+        is.read (reinterpret_cast<char *> (data), n_bytes);
         do_double_format_conversion (data, len, fmt);
 
         for (int i = 0; i < len; i++)
@@ -1097,14 +1101,18 @@
       break;
 
     case LS_FLOAT: // No conversion necessary.
-      is.read (reinterpret_cast<char *> (data), 4 * len);
-      do_float_format_conversion (data, len, fmt);
+      {
+        std::streamsize n_bytes = 4 * len;
+        is.read (reinterpret_cast<char *> (data), n_bytes);
+        do_float_format_conversion (data, len, fmt);
+      }
       break;
 
     case LS_DOUBLE:
       {
         OCTAVE_LOCAL_BUFFER (double, ptr, len);
-        is.read (reinterpret_cast<char *> (ptr), 8 * len);
+        std::streamsize n_bytes = 8 * len;
+        is.read (reinterpret_cast<char *> (ptr), n_bytes);
         do_double_format_conversion (ptr, len, fmt);
         for (octave_idx_type i = 0; i < len; i++)
           data[i] = ptr[i];
@@ -1155,7 +1163,8 @@
       {
         char tmp_type = static_cast<char> (type);
         os.write (&tmp_type, 1);
-        os.write (reinterpret_cast <const char *> (data), 8 * len);
+        std::streamsize n_bytes = 8 * static_cast<std::streamsize> (len);
+        os.write (reinterpret_cast <const char *> (data), n_bytes);
       }
       break;
 
@@ -1200,7 +1209,8 @@
       {
         char tmp_type = static_cast<char> (type);
         os.write (&tmp_type, 1);
-        os.write (reinterpret_cast <const char *> (data), 4 * len);
+        std::streamsize n_bytes = 4 * len;
+        os.write (reinterpret_cast <const char *> (data), n_bytes);
       }
       break;
 
rename from liboctave/data-conv.h
rename to liboctave/util/data-conv.h
--- a/liboctave/data-conv.h
+++ b/liboctave/util/data-conv.h
@@ -23,7 +23,7 @@
 #if !defined (octave_data_conv_h)
 #define octave_data_conv_h 1
 
-#include <climits>
+#include <limits>
 
 #include "mach-info.h"
 
rename from liboctave/f2c-main.c
rename to liboctave/util/f2c-main.c
--- a/liboctave/f2c-main.c
+++ b/liboctave/util/f2c-main.c
@@ -31,5 +31,5 @@
 #  ifdef __cplusplus
 extern "C"
 #  endif
-int F77_DUMMY_MAIN() { assert(0); return 1; }
+int F77_DUMMY_MAIN () { assert (0); return 1; }
 #endif
rename from liboctave/functor.h
rename to liboctave/util/functor.h
rename from liboctave/glob-match.cc
rename to liboctave/util/glob-match.cc
rename from liboctave/glob-match.h
rename to liboctave/util/glob-match.h
rename from liboctave/kpse.cc
rename to liboctave/util/kpse.cc
--- a/liboctave/kpse.cc
+++ b/liboctave/util/kpse.cc
@@ -35,7 +35,7 @@
    myself; if you do, I'd be grateful for any changes. --kb@mail.tug.org */
 
 /* If we have either DOS or OS2, we are DOSISH.  */
-#if defined (DOS) || defined (OS2) || defined (WIN32) || defined(__MSDOS__)
+#if defined (DOS) || defined (OS2) || defined (WIN32) || defined (__MSDOS__)
 #define DOSISH
 #endif
 
@@ -44,11 +44,11 @@
 #endif
 
 extern "C" {
-#if defined(__MINGW32__)
+#if defined (__MINGW32__)
 #include <windows.h>
 #include <fcntl.h>
 #include <dirent.h>
-#elif defined(WIN32)
+#elif defined (WIN32)
 #ifndef _MSC_VER
 #define __STDC__ 1
 #include "win32lib.h"
@@ -76,7 +76,7 @@
 /* If you want to find subdirectories in a directory with non-Unix
    semantics (specifically, if a directory with no subdirectories does
    not have exactly two links), define this.  */
-#if defined(__DJGPP__) || ! defined (DOSISH)
+#if defined (__DJGPP__) || ! defined (DOSISH)
 /* Surprise!  DJGPP returns st_nlink exactly like on Unix.  */
 #define ST_NLINK_TRICK
 #endif /* either not DOSISH or __DJGPP__ */
@@ -99,7 +99,7 @@
 #define DIR_SEP '/'
 #define DIR_SEP_STRING "/"
 #define IS_DEVICE_SEP(ch) ((ch) == ':')
-#define NAME_BEGINS_WITH_DEVICE(name) ((name.length()>0) && IS_DEVICE_SEP((name)[1]))
+#define NAME_BEGINS_WITH_DEVICE(name) ((name.length ()>0) && IS_DEVICE_SEP((name)[1]))
 /* On DOS, it's good to allow both \ and / between directories.  */
 #define IS_DIR_SEP(ch) ((ch) == '/' || (ch) == '\\')
 #else
@@ -129,7 +129,6 @@
 #include <cstdio>
 #include <cstdarg>
 #include <cstdlib>
-#include <climits>
 #include <cerrno>
 #include <cassert>
 
@@ -365,7 +364,7 @@
 
   if (KPSE_DEBUG_P (KPSE_DEBUG_FOPEN))
     DEBUGF3 ("fopen (%s, %s) => 0x%lx\n", filename.c_str (), mode,
-             reinterpret_cast<unsigned long> (f));
+             reinterpret_cast<intptr_t> (f));
 
   return f;
 }
rename from liboctave/lo-array-gripes.cc
rename to liboctave/util/lo-array-gripes.cc
rename from liboctave/lo-array-gripes.h
rename to liboctave/util/lo-array-gripes.h
rename from liboctave/lo-cieee.c
rename to liboctave/util/lo-cieee.c
rename from liboctave/lo-cutils.c
rename to liboctave/util/lo-cutils.c
--- a/liboctave/lo-cutils.c
+++ b/liboctave/util/lo-cutils.c
@@ -24,6 +24,8 @@
 #include <config.h>
 #endif
 
+#include "lo-error.h"
+
 /* This gives us a better chance of finding a prototype for strptime
    on some systems.  */
 
@@ -76,3 +78,123 @@
 {
   return WAITPID (pid, status, options);
 }
+
+static inline void
+gripe_missing_wait_macro (const char *id, int status)
+{
+  (*current_liboctave_warning_handler)
+    ("%s always returns false in this version of Octave; status = %d",
+     id, status);
+}
+
+OCTAVE_API int
+octave_wifexited (int status)
+{
+  int retval = 0;
+
+#if defined (WIFEXITED)
+  retval = WIFEXITED (status);
+#else
+  gripe_missing_wait_macro ("WIFEXITED", status);
+#endif
+
+  return retval;
+}
+
+OCTAVE_API int
+octave_wexitstatus (int status)
+{
+  int retval = 0;
+
+#if defined (WEXITSTATUS)
+  retval = WEXITSTATUS (status);
+#else
+  gripe_missing_wait_macro ("WEXITSTATUS", status);
+#endif
+
+  return retval;
+}
+
+OCTAVE_API int
+octave_wifsignaled (int status)
+{
+  int retval = 0;
+
+#if defined (WIFSIGNALED)
+  retval = WIFSIGNALED (status);
+#else
+  gripe_missing_wait_macro ("WIFSIGNALED", status);
+#endif
+
+  return retval;
+}
+
+OCTAVE_API int
+octave_wtermsig (int status)
+{
+  int retval = 0;
+
+#if defined (WTERMSIG)
+  retval = WTERMSIG (status);
+#else
+  gripe_missing_wait_macro ("WTERMSIG", status);
+#endif
+
+  return retval;
+}
+
+OCTAVE_API int
+octave_wcoredump (int status)
+{
+  int retval = 0;
+
+#if defined (WCOREDUMP)
+  retval = WCOREDUMP (status);
+#else
+  gripe_missing_wait_macro ("WCOREDUMP", status);
+#endif
+
+  return retval;
+}
+
+OCTAVE_API int
+octave_wifstopped (int status)
+{
+  int retval = 0;
+
+#if defined (WIFSTOPPED)
+  retval = WIFSTOPPED (status);
+#else
+  gripe_missing_wait_macro ("WIFSTOPPED", status);
+#endif
+
+  return retval;
+}
+
+OCTAVE_API int
+octave_wstopsig (int status)
+{
+  int retval = 0;
+
+#if defined (WSTOPSIG)
+  retval = WSTOPSIG (status);
+#else
+  gripe_missing_wait_macro ("WSTOPSIG", status);
+#endif
+
+  return retval;
+}
+
+OCTAVE_API int
+octave_wifcontinued (int status)
+{
+  int retval = 0;
+
+#if defined (WIFCONTINUED)
+  retval = WIFCONTINUED (status);
+#else
+  gripe_missing_wait_macro ("WIFCONTINUED", status);
+#endif
+
+  return retval;
+}
rename from liboctave/lo-cutils.h
rename to liboctave/util/lo-cutils.h
--- a/liboctave/lo-cutils.h
+++ b/liboctave/util/lo-cutils.h
@@ -23,7 +23,7 @@
 #if !defined (octave_liboctave_cutils_h)
 #define octave_liboctave_cutils_h 1
 
-#include "sys/types.h"
+#include <sys/types.h>
 
 #ifdef HAVE_LOADLIBRARY_API
 #define WIN32_LEAN_AND_MEAN
@@ -52,6 +52,15 @@
 OCTAVE_API pid_t
 octave_waitpid (pid_t pid, int *status, int options);
 
+OCTAVE_API int octave_wifexited (int status);
+OCTAVE_API int octave_wexitstatus (int status);
+OCTAVE_API int octave_wifsignaled (int status);
+OCTAVE_API int octave_wtermsig (int status);
+OCTAVE_API int octave_wcoredump (int status);
+OCTAVE_API int octave_wifstopped (int status);
+OCTAVE_API int octave_wstopsig (int status);
+OCTAVE_API int octave_wifcontinued (int status);
+
 #ifdef __cplusplus
 }
 #endif
rename from liboctave/lo-ieee.cc
rename to liboctave/util/lo-ieee.cc
rename from liboctave/lo-ieee.h
rename to liboctave/util/lo-ieee.h
--- a/liboctave/lo-ieee.h
+++ b/liboctave/util/lo-ieee.h
@@ -118,4 +118,26 @@
 #define lo_ieee_signbit(x) (sizeof (x) == sizeof (float) ? \
                           __lo_ieee_float_signbit (x) : __lo_ieee_signbit (x))
 
+#ifdef __cplusplus
+
+template <typename T>
+struct octave_numeric_limits
+{
+  static T NA (void) { return static_cast<T> (0); }
+};
+
+template <>
+struct octave_numeric_limits<double>
+{
+  static double NA (void) { return octave_NA; }
+};
+
+template <>
+struct octave_numeric_limits<float>
+{
+  static float NA (void) { return octave_Float_NA; }
+};
+
 #endif
+
+#endif
rename from liboctave/lo-macros.h
rename to liboctave/util/lo-macros.h
--- a/liboctave/lo-macros.h
+++ b/liboctave/util/lo-macros.h
@@ -92,4 +92,8 @@
 #define OCT_MAKE_DECL_LIST(TYPE, PREFIX, NUM) \
   OCT_ITERATE_PARAM_MACRO(OCT_MAKE_DECL_LIST_HELPER, TYPE PREFIX, NUM)
 
+// expands to PREFIX0, PREFIX1, ..., PREFIX ## (NUM-1)
+#define OCT_MAKE_ARG_LIST(PREFIX, NUM)          \
+  OCT_ITERATE_PARAM_MACRO(OCT_MAKE_DECL_LIST_HELPER, PREFIX, NUM)
+
 #endif
rename from liboctave/lo-math.h
rename to liboctave/util/lo-math.h
rename from liboctave/lo-traits.h
rename to liboctave/util/lo-traits.h
rename from liboctave/lo-utils.cc
rename to liboctave/util/lo-utils.cc
--- a/liboctave/lo-utils.cc
+++ b/liboctave/util/lo-utils.cc
@@ -54,7 +54,16 @@
 { return x == 0; }
 
 bool xtoo_large_for_float (double x)
-{ return (! (xisnan (x) || xisinf (x)) && fabs (x) > FLT_MAX); }
+{
+  return (! (xisnan (x) || xisinf (x))
+          && fabs (x) > std::numeric_limits<float>::max ());
+}
+
+bool xtoo_large_for_float (const Complex& x)
+{
+  return (xtoo_large_for_float (x.real ())
+          || xtoo_large_for_float (x.imag ()));
+}
 
 bool xis_int_or_inf_or_nan (float x)
 { return xisnan (x) || D_NINT (x) == x; }
@@ -97,7 +106,7 @@
   // As far as I can see there's no way to distinguish between the
   // various errors; putenv doesn't have errno values.
 
-  if (putenv (new_item) < 0)
+  if (gnulib::putenv (new_item) < 0)
     (*current_liboctave_error_handler) ("putenv (%s) failed", new_item);
 }
 
@@ -198,10 +207,11 @@
 // Note that the caller is responsible for repositioning the stream on
 // failure.
 
-static inline double
+template <typename T>
+T
 read_inf_nan_na (std::istream& is, char c0)
 {
-  double d = 0.0;
+  T val = 0.0;
 
   switch (c0)
     {
@@ -212,7 +222,7 @@
           {
             char c2 = is.get ();
             if (c2 == 'f' || c2 == 'F')
-              d = octave_Inf;
+              val = std::numeric_limits<T>::infinity ();
             else
               is.setstate (std::ios::failbit);
           }
@@ -228,9 +238,9 @@
           {
             char c2 = is.get ();
             if (c2 == 'n' || c2 == 'N')
-              d = octave_NaN;
+              val = std::numeric_limits<T>::quiet_NaN ();
             else
-              d = octave_NA;
+              val = octave_numeric_limits<T>::NA ();
           }
         else
           is.setstate (std::ios::failbit);
@@ -241,16 +251,16 @@
       abort ();
     }
 
-  return d;
+  return val;
 }
 
 // Read a double value.  Discard any sign on NaN and NA.
 
-template <>
+template <typename T>
 double
-octave_read_value (std::istream& is)
+octave_read_fp_value (std::istream& is)
 {
-  double d = 0.0;
+  T val = 0.0;
 
   // FIXME -- resetting stream position is likely to fail unless we are
   // reading from a file.
@@ -274,26 +284,26 @@
         char c2 = 0;
         c2 = is.get ();
         if (c2 == 'i' || c2 == 'I' || c2 == 'n' || c2 == 'N')
-          d = read_inf_nan_na (is, c2);
+          val = read_inf_nan_na<T> (is, c2);
         else
           {
             is.putback (c2);
-            is >> d;
+            is >> val;
           }
 
         if (neg && ! is.fail ())
-          d = -d;
+          val = -val;
       }
       break;
 
     case 'i': case 'I':
     case 'n': case 'N':
-      d = read_inf_nan_na (is, c1);
+      val = read_inf_nan_na<T> (is, c1);
       break;
 
     default:
       is.putback (c1);
-      is >> d;
+      is >> val;
       break;
     }
 
@@ -305,16 +315,16 @@
       is.setstate (status);
     }
 
-  return d;
+  return val;
 }
 
-template <>
-Complex
-octave_read_value (std::istream& is)
+template <typename T>
+std::complex<T>
+octave_read_cx_fp_value (std::istream& is)
 {
-  double re = 0.0, im = 0.0;
+  T re = 0.0, im = 0.0;
 
-  Complex cx = 0.0;
+  std::complex<T> cx = 0.0;
 
   char ch = ' ';
 
@@ -323,16 +333,16 @@
 
   if (ch == '(')
     {
-      re = octave_read_value<double> (is);
+      re = octave_read_value<T> (is);
       ch = is.get ();
 
       if (ch == ',')
         {
-          im = octave_read_value<double> (is);
+          im = octave_read_value<T> (is);
           ch = is.get ();
 
           if (ch == ')')
-            cx = Complex (re, im);
+            cx = std::complex<T> (re, im);
           else
             is.setstate (std::ios::failbit);
         }
@@ -348,163 +358,26 @@
     }
 
   return cx;
-
 }
 
-// Note that the caller is responsible for repositioning the stream on
-// failure.
-
-static inline float
-read_float_inf_nan_na (std::istream& is, char c0, char sign = '+')
+template <> OCTAVE_API double octave_read_value (std::istream& is)
 {
-  float d = 0.0;
-
-  switch (c0)
-    {
-    case 'i': case 'I':
-      {
-        char c1 = is.get ();
-        if (c1 == 'n' || c1 == 'N')
-          {
-            char c2 = is.get ();
-            if (c2 == 'f' || c2 == 'F')
-              d = octave_Float_Inf;
-            else
-              is.setstate (std::ios::failbit);
-          }
-        else
-          is.setstate (std::ios::failbit);
-      }
-      break;
-
-    case 'n': case 'N':
-      {
-        char c1 = is.get ();
-        if (c1 == 'a' || c1 == 'A')
-          {
-            char c2 = is.get ();
-            if (c2 == 'n' || c2 == 'N')
-              d = octave_Float_NaN;
-            else
-              d = octave_Float_NA;
-          }
-        else
-          is.setstate (std::ios::failbit);
-      }
-      break;
-
-    default:
-      abort ();
-    }
-
-  return d;
+  return octave_read_fp_value<double> (is);
 }
 
-// Read a float value.  Discard any sign on NaN and NA.
-
-template <>
-float
-octave_read_value (std::istream& is)
+template <> OCTAVE_API Complex octave_read_value (std::istream& is)
 {
-  float d = 0.0;
-
-  // FIXME -- resetting stream position is likely to fail unless we are
-  // reading from a file.
-  std::ios::streampos pos = is.tellg ();
-
-  char c1 = ' ';
-
-  while (isspace (c1))
-    c1 = is.get ();
-
-  bool neg = false;
-
-  switch (c1)
-    {
-    case '-':
-      neg = true;
-      // fall through...
-
-    case '+':
-      {
-        char c2 = 0;
-        c2 = is.get ();
-        if (c2 == 'i' || c2 == 'I' || c2 == 'n' || c2 == 'N')
-          d = read_float_inf_nan_na (is, c2);
-        else
-          {
-            is.putback (c2);
-            is >> d;
-          }
-
-        if (neg && ! is.fail ())
-          d = -d;
-      }
-      break;
-
-    case 'i': case 'I':
-    case 'n': case 'N':
-      d = read_float_inf_nan_na (is, c1);
-      break;
-
-    default:
-      is.putback (c1);
-      is >> d;
-      break;
-    }
-
-  std::ios::iostate status = is.rdstate ();
-  if (status & std::ios::failbit)
-    {
-      is.clear ();
-      is.seekg (pos);
-      is.setstate (status);
-    }
-
-  return d;
+  return octave_read_cx_fp_value<double> (is);
 }
 
-template <>
-FloatComplex
-octave_read_value (std::istream& is)
+template <> OCTAVE_API float octave_read_value (std::istream& is)
 {
-  float re = 0.0, im = 0.0;
-
-  FloatComplex cx = 0.0;
-
-  char ch = ' ';
-
-  while (isspace (ch))
-    ch = is.get ();
-
-  if (ch == '(')
-    {
-      re = octave_read_value<float> (is);
-      ch = is.get ();
+  return octave_read_fp_value<float> (is);
+}
 
-      if (ch == ',')
-        {
-          im = octave_read_value<float> (is);
-          ch = is.get ();
-
-          if (ch == ')')
-            cx = FloatComplex (re, im);
-          else
-            is.setstate (std::ios::failbit);
-        }
-      else if (ch == ')')
-        cx = re;
-      else
-        is.setstate (std::ios::failbit);
-    }
-  else
-    {
-      is.putback (ch);
-      cx = octave_read_value<float> (is);
-    }
-
-  return cx;
-
+template <> OCTAVE_API FloatComplex octave_read_value (std::istream& is)
+{
+  return octave_read_cx_fp_value<float> (is);
 }
 
 void
rename from liboctave/lo-utils.h
rename to liboctave/util/lo-utils.h
--- a/liboctave/lo-utils.h
+++ b/liboctave/util/lo-utils.h
@@ -28,14 +28,46 @@
 #include <iostream>
 #include <string>
 
+#include "quit.h"
+
 #include "lo-cutils.h"
 #include "oct-cmplx.h"
 
+// Generic any/all test functionality with arbitrary predicate.
+
+template <class F, class T, bool zero>
+bool
+any_all_test (F fcn, const T *m, octave_idx_type len)
+{
+  octave_idx_type i;
+
+  for (i = 0; i < len - 3; i += 4)
+    {
+      octave_quit ();
+
+      if (fcn (m[i]) != zero
+          || fcn (m[i+1]) != zero
+          || fcn (m[i+2]) != zero
+          || fcn (m[i+3]) != zero)
+        return ! zero;
+    }
+
+  octave_quit ();
+
+  for (; i < len; i++)
+    if (fcn (m[i]) != zero)
+      return ! zero;
+
+  return zero;
+}
+
 extern OCTAVE_API bool xis_int_or_inf_or_nan (double x);
 extern OCTAVE_API bool xis_one_or_zero (double x);
 extern OCTAVE_API bool xis_zero (double x);
 extern OCTAVE_API bool xtoo_large_for_float (double x);
 
+extern OCTAVE_API bool xtoo_large_for_float (const Complex&  x);
+
 extern OCTAVE_API bool xis_int_or_inf_or_nan (float x);
 extern OCTAVE_API bool xis_one_or_zero (float x);
 extern OCTAVE_API bool xis_zero (float x);
@@ -103,4 +135,52 @@
 extern OCTAVE_API void
 octave_write_float_complex (std::ostream& os, const FloatComplex& cval);
 
+// Maybe this is overkill, but it allos
+
+class
+octave_wait
+{
+public:
+
+  static bool ifexited (int status)
+  {
+    return octave_wifexited (status);
+  }
+
+  static int exitstatus (int status)
+  {
+    return octave_wexitstatus (status);
+  }
+
+  static bool ifsignaled (int status)
+  {
+    return octave_wifsignaled (status);
+  }
+
+  static int termsig (int status)
+  {
+    return octave_wtermsig (status);
+  }
+
+  static bool coredump (int status)
+  {
+    return octave_wcoredump (status);
+  }
+
+  static bool ifstopped (int status)
+  {
+    return octave_wifstopped (status);
+  }
+
+  static int stopsig (int status)
+  {
+    return octave_wstopsig (status);
+  }
+
+  static bool ifcontinued (int status)
+  {
+    return octave_wifcontinued (status);
+  }
+};
+
 #endif
new file mode 100644
--- /dev/null
+++ b/liboctave/util/module.mk
@@ -0,0 +1,88 @@
+EXTRA_DIST += \
+  util/module.mk
+
+UTIL_INC = \
+  util/base-list.h \
+  util/byte-swap.h \
+  util/caseless-str.h \
+  util/cmd-edit.h \
+  util/cmd-hist.h \
+  util/data-conv.h \
+  util/functor.h \
+  util/glob-match.h \
+  util/lo-array-gripes.h \
+  util/lo-cutils.h \
+  util/lo-ieee.h \
+  util/lo-macros.h \
+  util/lo-math.h \
+  util/lo-traits.h \
+  util/lo-utils.h \
+  util/oct-alloc.h \
+  util/oct-base64.h \
+  util/oct-binmap.h \
+  util/oct-cmplx.h \
+  util/oct-glob.h \
+  util/oct-inttypes.h \
+  util/oct-locbuf.h \
+  util/oct-md5.h \
+  util/oct-mem.h \
+  util/oct-mutex.h \
+  util/oct-refcount.h \
+  util/oct-rl-edit.h \
+  util/oct-rl-hist.h \
+  util/oct-shlib.h \
+  util/oct-sort.h \
+  util/oct-sparse.h \
+  util/pathsearch.h \
+  util/regexp.h \
+  util/singleton-cleanup.h \
+  util/sparse-sort.h \
+  util/sparse-util.h \
+  util/statdefs.h \
+  util/str-vec.h \
+  util/sun-utils.h 
+
+UTIL_C_SRC = \
+  util/f2c-main.c \
+  util/lo-cieee.c \
+  util/lo-cutils.c \
+  util/oct-rl-edit.c \
+  util/oct-rl-hist.c 
+
+UTIL_SRC = \
+  util/cmd-edit.cc \
+  util/cmd-hist.cc \
+  util/data-conv.cc \
+  util/glob-match.cc \
+  util/lo-array-gripes.cc \
+  util/lo-ieee.cc \
+  util/lo-utils.cc \
+  util/oct-alloc.cc \
+  util/oct-base64.cc \
+  util/oct-glob.cc \
+  util/oct-inttypes.cc \
+  util/oct-locbuf.cc \
+  util/oct-md5.cc \
+  util/oct-mutex.cc \
+  util/oct-shlib.cc \
+  util/pathsearch.cc \
+  util/regexp.cc \
+  util/singleton-cleanup.cc \
+  util/sparse-sort.cc \
+  util/sparse-util.cc \
+  util/str-vec.cc \
+  $(UTIL_C_SRC)
+
+TEMPLATE_SRC += \
+  util/oct-sort.cc
+
+OTHER_INC += \
+  util/kpse.cc
+
+noinst_LTLIBRARIES += util/libutil.la
+
+util_libutil_la_SOURCES = $(UTIL_SRC)
+util_libutil_la_CPPFLAGS = \
+  $(liboctave_la_CPPFLAGS) \
+  $(SPARSE_XCPPFLAGS)
+
rename from liboctave/oct-alloc.cc
rename to liboctave/util/oct-alloc.cc
rename from liboctave/oct-alloc.h
rename to liboctave/util/oct-alloc.h
new file mode 100644
--- /dev/null
+++ b/liboctave/util/oct-base64.cc
@@ -0,0 +1,90 @@
+/*
+
+Copyright (C) 2012 John W. Eaton
+
+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 <algorithm>
+
+#include <base64.h>
+
+#include "Array.h"
+#include "oct-base64.h"
+
+bool
+octave_base64_encode (const char *inc, const size_t inlen, char **out)
+{  
+  bool ret = false;
+
+  size_t outlen = base64_encode_alloc (inc, inlen, out);
+  
+  if (! *out)
+    {
+      if (outlen == 0 && inlen != 0)
+        (*current_liboctave_error_handler)
+          ("base64_encode: input array too large");
+      else
+        (*current_liboctave_error_handler)
+          ("base64_encode: memory allocation error");
+    }
+  else
+    ret = true;
+
+  return ret;
+}
+
+Array<double>
+octave_base64_decode (const std::string& str)
+{
+  Array<double> retval;
+
+  const char *inc = &(str[0]);
+
+  char *out;
+  size_t outlen;
+
+  bool ok = base64_decode_alloc (inc, str.length (), &out, &outlen);
+
+  if (! ok)
+    (*current_liboctave_error_handler)
+      ("base64_decode: input was not valid base64");
+  else if (! out)
+    (*current_liboctave_error_handler)
+      ("base64_decode: memory allocation error");
+  else
+    {
+      if ((outlen % (sizeof (double) / sizeof (char))) != 0)
+        (*current_liboctave_error_handler)
+          ("base64_decode: incorrect input size");
+      else
+        {
+          octave_idx_type len = (outlen * sizeof (char)) / sizeof (double);
+          retval.resize (dim_vector (1, len));
+          double *dout = reinterpret_cast<double*> (out);
+          std::copy (dout, dout + len, retval.fortran_vec ());
+        }
+    }
+
+  return retval;
+}
+
new file mode 100644
--- /dev/null
+++ b/liboctave/util/oct-base64.h
@@ -0,0 +1,37 @@
+/*
+
+Copyright (C) 2012 John W. Eaton
+
+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_base64_h)
+#define octave_base64_h 1
+
+#include <string>
+
+template<class T> class Array;
+
+extern OCTAVE_API bool
+octave_base64_encode (const char *inc, const size_t inlen, char **out);
+
+extern OCTAVE_API Array<double>
+octave_base64_decode (const std::string& str);
+
+#endif
+
rename from liboctave/oct-binmap.h
rename to liboctave/util/oct-binmap.h
--- a/liboctave/oct-binmap.h
+++ b/liboctave/util/oct-binmap.h
@@ -30,7 +30,7 @@
 #include "bsxfun.h"
 
 // This source file implements a general binary maping function for
-// arrays. The syntax is binmap<type> (a, b, f, [name]). type denotes
+// arrays. The syntax is binmap<type> (a, b, f,[name]). type denotes
 // the expected return type of the operation. a, b, should be one of
 // the 6 combinations:
 //
@@ -223,7 +223,7 @@
   for (octave_idx_type i = 0; i < nz; i++)
     {
       octave_quit ();
-      retval.xdata(i) = fcn (x, ys.data(i));
+      retval.xdata (i) = fcn (x, ys.data (i));
     }
 
   octave_quit ();
@@ -241,7 +241,7 @@
   for (octave_idx_type i = 0; i < nz; i++)
     {
       octave_quit ();
-      retval.xdata(i) = fcn (xs.data(i), y);
+      retval.xdata (i) = fcn (xs.data (i), y);
     }
 
   octave_quit ();
@@ -265,7 +265,7 @@
   R yzero = R ();
 
   U fz = fcn (xzero, yzero);
-  if (fz == U())
+  if (fz == U ())
     {
       // Sparsity-preserving function. Do it efficiently.
       octave_idx_type nr = xs.rows (), nc = xs.cols ();
@@ -276,49 +276,49 @@
       for (octave_idx_type j = 0; j < nc; j++)
         {
           octave_quit ();
-          octave_idx_type ix = xs.cidx(j), iy = ys.cidx(j);
-          octave_idx_type ux = xs.cidx(j+1), uy = ys.cidx(j+1);
+          octave_idx_type ix = xs.cidx (j), iy = ys.cidx (j);
+          octave_idx_type ux = xs.cidx (j+1), uy = ys.cidx (j+1);
           while (ix != ux || iy != uy)
             {
-              octave_idx_type rx = xs.ridx(ix), ry = ys.ridx(ix);
+              octave_idx_type rx = xs.ridx (ix), ry = ys.ridx (ix);
               ix += rx <= ry;
               iy += ry <= rx;
               nz++;
             }
 
-          retval.xcidx(j+1) = nz;
+          retval.xcidx (j+1) = nz;
         }
 
       // Allocate space.
-      retval.change_capacity (retval.xcidx(nc));
+      retval.change_capacity (retval.xcidx (nc));
 
       // Fill.
       nz = 0;
       for (octave_idx_type j = 0; j < nc; j++)
         {
           octave_quit ();
-          octave_idx_type ix = xs.cidx(j), iy = ys.cidx(j);
-          octave_idx_type ux = xs.cidx(j+1), uy = ys.cidx(j+1);
+          octave_idx_type ix = xs.cidx (j), iy = ys.cidx (j);
+          octave_idx_type ux = xs.cidx (j+1), uy = ys.cidx (j+1);
           while (ix != ux || iy != uy)
             {
-              octave_idx_type rx = xs.ridx(ix), ry = ys.ridx(ix);
+              octave_idx_type rx = xs.ridx (ix), ry = ys.ridx (ix);
               if (rx == ry)
                 {
-                  retval.xridx(nz) = rx;
-                  retval.xdata(nz) = fcn (xs.data(ix), ys.data(iy));
+                  retval.xridx (nz) = rx;
+                  retval.xdata (nz) = fcn (xs.data (ix), ys.data (iy));
                   ix++;
                   iy++;
                 }
               else if (rx < ry)
                 {
-                  retval.xridx(nz) = rx;
-                  retval.xdata(nz) = fcn (xs.data(ix), yzero);
+                  retval.xridx (nz) = rx;
+                  retval.xdata (nz) = fcn (xs.data (ix), yzero);
                   ix++;
                 }
               else if (ry < rx)
                 {
-                  retval.xridx(nz) = ry;
-                  retval.xdata(nz) = fcn (xzero, ys.data(iy));
+                  retval.xridx (nz) = ry;
+                  retval.xdata (nz) = fcn (xzero, ys.data (iy));
                   iy++;
                 }
 
rename from liboctave/oct-cmplx.h
rename to liboctave/util/oct-cmplx.h
rename from liboctave/oct-glob.cc
rename to liboctave/util/oct-glob.cc
rename from liboctave/oct-glob.h
rename to liboctave/util/oct-glob.h
rename from liboctave/oct-inttypes.cc
rename to liboctave/util/oct-inttypes.cc
--- a/liboctave/oct-inttypes.cc
+++ b/liboctave/util/oct-inttypes.cc
@@ -272,7 +272,7 @@
 
 INT_DOUBLE_BINOP_DECL (+, uint64)
 {
-  return (y < 0) ? x - octave_uint64(-y) : x + octave_uint64(y);
+  return (y < 0) ? x - octave_uint64 (-y) : x + octave_uint64 (y);
 }
 
 DOUBLE_INT_BINOP_DECL (+, uint64)
@@ -288,7 +288,7 @@
       // probably), the above will work as expected. If not, it's more
       // complicated - as long as y is within _twice_ the signed range, the
       // result may still be an integer. An instance of such an operation is
-      // 3*2**62 + (1+intmin('int64')) that should yield int64(2**62) + 1.  So
+      // 3*2**62 + (1+intmin ('int64')) that should yield int64 (2**62) + 1.  So
       // what we do is to try to convert y/2 and add it twice. Note that if y/2
       // overflows, the result must overflow as well, and that y/2 cannot be a
       // fractional number.
@@ -310,12 +310,12 @@
 DOUBLE_INT_BINOP_DECL (-, uint64)
 {
   if (x <= static_cast<double> (octave_uint64::max ()))
-    return octave_uint64(x) - y;
+    return octave_uint64 (x) - y;
   else
     {
       // Again a trick to get the corner cases right. Things like
-      // 3**2**63 - intmax('uint64') should produce the correct result, i.e.
-      // int64(2**63) + 1.
+      // 3**2**63 - intmax ('uint64') should produce the correct result, i.e.
+      // int64 (2**63) + 1.
       const double p2_64 = std::pow (2.0, 64);
       if (y.bool_value ())
         {
@@ -340,7 +340,7 @@
   // be eliminated at compile time.
   if (twosc && y.value () == std::numeric_limits<int64_t>::min ())
     {
-      return octave_int64 (x + std::pow(2.0, 63));
+      return octave_int64 (x + std::pow (2.0, 63));
     }
   else
     return x + (-y);
@@ -630,24 +630,23 @@
 INSTANTIATE_INTTYPE (uint64_t);
 
 
-// Tests follow.
-
 /*
 
-%!assert(intmax("int64")/intmin("int64"),int64(-1))
-%!assert(intmin("int64")/int64(-1),intmax("int64"))
-%!assert(int64(2**63),intmax("int64"))
-%!assert(uint64(2**64),intmax("uint64"))
+%!assert (intmax ("int64") / intmin ("int64"), int64 (-1))
+%!assert (intmin ("int64") / int64 (-1), intmax ("int64"))
+%!assert (int64 (2**63), intmax ("int64"))
+%!assert (uint64 (2**64), intmax ("uint64"))
 %!test
-%! a = 1.9*2^61; b = uint64(a); b++; assert(b > a)
+%! a = 1.9*2^61; b = uint64 (a); b++; assert (b > a);
 %!test
-%! a = -1.9*2^61; b = int64(a); b++; assert(b > a)
+%! a = -1.9*2^61; b = int64 (a); b++; assert (b > a);
 %!test
-%! a = int64(-2**60) + 2; assert(1.25*a == (5*a)/4)
+%! a = int64 (-2**60) + 2; assert (1.25*a == (5*a)/4);
 %!test
-%! a = uint64(2**61) + 2; assert(1.25*a == (5*a)/4)
-%!assert(int32(2**31+0.5),intmax('int32'))
-%!assert(int32(-2**31-0.5),intmin('int32'))
-%!assert((int64(2**62)+1)**1, int64(2**62)+1)
-%!assert((int64(2**30)+1)**2, int64(2**60+2**31) + 1)
+%! a = uint64 (2**61) + 2; assert (1.25*a == (5*a)/4);
+%!assert (int32 (2**31+0.5), intmax ("int32"))
+%!assert (int32 (-2**31-0.5), intmin ("int32"))
+%!assert ((int64 (2**62)+1)**1, int64 (2**62)+1)
+%!assert ((int64 (2**30)+1)**2, int64 (2**60+2**31) + 1)
+
 */
rename from liboctave/oct-inttypes.h
rename to liboctave/util/oct-inttypes.h
--- a/liboctave/oct-inttypes.h
+++ b/liboctave/util/oct-inttypes.h
@@ -24,7 +24,6 @@
 #if !defined (octave_inttypes_h)
 #define octave_inttypes_h 1
 
-#include <climits>
 #include <cstdlib>
 
 #include <limits>
@@ -825,7 +824,7 @@
 
   static int nbits (void) { return std::numeric_limits<T>::digits; }
 
-  static int byte_size (void) { return sizeof(T); }
+  static int byte_size (void) { return sizeof (T); }
 
   static const char *type_name ();
 
rename from liboctave/oct-locbuf.cc
rename to liboctave/util/oct-locbuf.cc
rename from liboctave/oct-locbuf.h
rename to liboctave/util/oct-locbuf.h
--- a/liboctave/oct-locbuf.h
+++ b/liboctave/util/oct-locbuf.h
@@ -38,7 +38,7 @@
     : data (0)
     {
       if (size)
-        data = new T[size];
+        data = new T [size];
     }
   ~octave_local_buffer (void) { delete [] data; }
   operator T *() const { return data; }
@@ -204,7 +204,7 @@
 // about shadowed parameters.
 
 #define OCTAVE_LOCAL_BUFFER_INIT(T, buf, size, value) \
-  OCTAVE_LOCAL_BUFFER(T, buf, size); \
+  OCTAVE_LOCAL_BUFFER (T, buf, size); \
   for (size_t _buf_iter = 0, _buf_size = size; \
         _buf_iter < _buf_size; _buf_iter++) \
     buf[_buf_iter] = value
rename from liboctave/oct-md5.cc
rename to liboctave/util/oct-md5.cc
--- a/liboctave/oct-md5.cc
+++ b/liboctave/util/oct-md5.cc
@@ -21,7 +21,7 @@
 */
 
 #ifdef HAVE_CONFIG_H
-#include "config.h"
+#include <config.h>
 #endif
 
 #include <cstdio>
@@ -36,7 +36,7 @@
 static std::string
 oct_md5_result_to_str (const unsigned char *buf)
 {
-  char tmp [33];
+  char tmp[33];
 
   sprintf (tmp,
            "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
@@ -79,7 +79,7 @@
     }
   else
     (*current_liboctave_error_handler) ("unable to open file '%s' for reading",
-                                        file.c_str());
+                                        file.c_str ());
 
   return retval;
 }
rename from liboctave/oct-md5.h
rename to liboctave/util/oct-md5.h
rename from liboctave/oct-mem.h
rename to liboctave/util/oct-mem.h
--- a/liboctave/oct-mem.h
+++ b/liboctave/util/oct-mem.h
@@ -92,7 +92,7 @@
 
 template <class T>
 inline bool helper_is_zero_mem (const octave_int<T>& value)
-{ return value.value () == T(); }
+{ return value.value () == T (); }
 
 #define DEFINE_POD_FILL(T) \
 inline void fill_or_memset (size_t n, const T& value, T *dest) \
@@ -128,7 +128,7 @@
   // Some systems let us allocate > 2GB memory even though size_t, which is either
   // buggy or completely cuckoo, so let's check here to stay safe.
   safe_size_comp (n, sizeof (T));
-  return new T[n];
+  return new T [n];
 }
 template <class T>
 inline void no_ctor_delete (T *ptr)
@@ -137,7 +137,7 @@
 #define DEFINE_POD_NEW_DELETE(T) \
 template <> \
 inline T *no_ctor_new<T > (size_t n) \
-{ return reinterpret_cast<T *> (new char[safe_size_comp (n, sizeof (T))]); } \
+{ return reinterpret_cast<T *> (new char [safe_size_comp (n, sizeof (T))]); } \
 template <> \
 inline void no_ctor_delete<T > (T *ptr) \
 { delete [] reinterpret_cast<char *> (ptr); }
rename from liboctave/oct-mutex.cc
rename to liboctave/util/oct-mutex.cc
rename from liboctave/oct-mutex.h
rename to liboctave/util/oct-mutex.h
rename from liboctave/oct-refcount.h
rename to liboctave/util/oct-refcount.h
--- a/liboctave/oct-refcount.h
+++ b/liboctave/util/oct-refcount.h
@@ -82,6 +82,11 @@
       return static_cast<count_type const volatile&> (count);
     }
 
+  count_type *get (void)
+    {
+      return &count;
+    }
+
 private:
   count_type count;
 };
rename from liboctave/oct-rl-edit.c
rename to liboctave/util/oct-rl-edit.c
--- a/liboctave/oct-rl-edit.c
+++ b/liboctave/util/oct-rl-edit.c
@@ -91,17 +91,23 @@
 }
 
 void
-octave_rl_clear_screen (void)
+octave_rl_clear_screen (int skip_redisplay)
 {
   int ignore1 = 0;
   int ignore2 = 0;
 
-  rl_voidfunc_t *saved_redisplay_function = rl_redisplay_function;
-  rl_redisplay_function = flush_stdout;
+  if (skip_redisplay)
+    {
+      rl_voidfunc_t *saved_redisplay_function = rl_redisplay_function;
+
+      rl_redisplay_function = flush_stdout;
 
-  rl_clear_screen (ignore1, ignore2);
+      rl_clear_screen (ignore1, ignore2);
 
-  rl_redisplay_function = saved_redisplay_function;
+      rl_redisplay_function = saved_redisplay_function;
+    }
+  else
+    rl_clear_screen (ignore1, ignore2);
 }
 
 void
@@ -117,6 +123,18 @@
     rl_deprep_term_function ();
 }
 
+char *
+octave_rl_copy_line (void)
+{
+  return rl_copy_text (0, rl_end);
+}
+
+void
+octave_rl_replace_line (const char *s, int clear_undo)
+{
+  rl_replace_line (s, clear_undo);
+}
+
 void
 octave_rl_insert_text (const char *s)
 {
@@ -135,6 +153,12 @@
   return rl_line_buffer;
 }
 
+int
+octave_rl_do_undo (void)
+{
+  return rl_do_undo ();
+}
+
 void
 octave_rl_clear_undo_list (void)
 {
@@ -218,6 +242,12 @@
   return retval;
 }
 
+void
+octave_rl_done (int arg)
+{
+  rl_done = arg;
+}
+
 char *
 octave_rl_filename_completion_function (const char *text, int state)
 {
@@ -307,6 +337,18 @@
 }
 
 void
+octave_rl_set_pre_input_hook (rl_pre_input_hook_fcn_ptr f)
+{
+  rl_pre_input_hook = f;
+}
+
+rl_pre_input_hook_fcn_ptr
+octave_rl_get_pre_input_hook (void)
+{
+  return rl_pre_input_hook;
+}
+
+void
 octave_rl_set_event_hook (rl_event_hook_fcn_ptr f)
 {
   rl_event_hook = f;
rename from liboctave/oct-rl-edit.h
rename to liboctave/util/oct-rl-edit.h
--- a/liboctave/oct-rl-edit.h
+++ b/liboctave/util/oct-rl-edit.h
@@ -25,6 +25,8 @@
 
 typedef int (*rl_startup_hook_fcn_ptr) (void);
 
+typedef int (*rl_pre_input_hook_fcn_ptr) (void);
+
 typedef int (*rl_event_hook_fcn_ptr) (void);
 
 typedef int (*rl_fcn_ptr) (int, int);
@@ -46,7 +48,7 @@
 {
 #endif
 
-  extern void octave_rl_redisplay (void);
+extern void octave_rl_redisplay (void);
 
 extern int octave_rl_screen_height (void);
 
@@ -56,18 +58,24 @@
 
 extern void octave_rl_init (void);
 
-extern void octave_rl_clear_screen (void);
+extern void octave_rl_clear_screen (int skip_redisplay);
 
 extern void octave_rl_resize_terminal (void);
 
 extern void octave_rl_restore_terminal_state (void);
 
+extern char *octave_rl_copy_line (void);
+
+extern void octave_rl_replace_line (const char *s, int clear_undo);
+
 extern void octave_rl_insert_text (const char *);
 
 extern int octave_rl_newline (int, int);
 
 extern const char *octave_rl_line_buffer (void);
 
+extern int octave_rl_do_undo (void);
+
 extern void octave_rl_clear_undo_list (void);
 
 extern void octave_rl_set_name (const char *);
@@ -90,6 +98,8 @@
 
 extern int octave_rl_filename_quoting_desired (int);
 
+extern void octave_rl_done (int);
+
 extern char *octave_rl_filename_completion_function (const char *, int);
 
 extern void octave_rl_set_basic_word_break_characters (const char *);
@@ -119,6 +129,10 @@
 
 extern rl_startup_hook_fcn_ptr octave_rl_get_startup_hook (void);
 
+extern void octave_rl_set_pre_input_hook (rl_startup_hook_fcn_ptr);
+
+extern rl_pre_input_hook_fcn_ptr octave_rl_get_pre_input_hook (void);
+
 extern void octave_rl_set_event_hook (rl_event_hook_fcn_ptr f);
 
 extern rl_event_hook_fcn_ptr octave_rl_get_event_hook (void);
rename from liboctave/oct-rl-hist.c
rename to liboctave/util/oct-rl-hist.c
--- a/liboctave/oct-rl-hist.c
+++ b/liboctave/util/oct-rl-hist.c
@@ -210,6 +210,12 @@
     }
 }
 
+void
+octave_clear_history (void)
+{
+  clear_history ();
+}
+
 char *
 octave_history_goto_mark (int n)
 {
rename from liboctave/oct-rl-hist.h
rename to liboctave/util/oct-rl-hist.h
--- a/liboctave/oct-rl-hist.h
+++ b/liboctave/util/oct-rl-hist.h
@@ -66,6 +66,8 @@
 
 extern void octave_remove_history (int);
 
+extern void octave_clear_history (void);
+
 extern char *octave_history_goto_mark (int n);
 
 extern char *octave_history_get (int n);
rename from liboctave/oct-shlib.cc
rename to liboctave/util/oct-shlib.cc
--- a/liboctave/oct-shlib.cc
+++ b/liboctave/util/oct-shlib.cc
@@ -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 ();
 
@@ -272,7 +272,7 @@
   if (! library)
     {
       using namespace std;
-      (*current_liboctave_error_handler) ("%s", strerror (errno));
+      (*current_liboctave_error_handler) ("%s", gnulib::strerror (errno));
     }
 }
 
rename from liboctave/oct-shlib.h
rename to liboctave/util/oct-shlib.h
rename from liboctave/oct-sort.cc
rename to liboctave/util/oct-sort.cc
--- a/liboctave/oct-sort.cc
+++ b/liboctave/util/oct-sort.cc
@@ -542,7 +542,7 @@
    */
   delete [] a;
   delete [] ia; // Must do this or fool possible next getmemi.
-  a = new T[need];
+  a = new T [need];
   alloced = need;
 
 }
@@ -561,8 +561,8 @@
   delete [] a;
   delete [] ia;
 
-  a = new T[need];
-  ia = new octave_idx_type[need];
+  a = new T [need];
+  ia = new octave_idx_type [need];
   alloced = need;
 }
 
@@ -1184,7 +1184,7 @@
     return nb;
 
   /* Merge what remains of the runs, using a temp array with
-   * min(na, nb) elements.
+   * min (na, nb) elements.
    */
   if (na <= nb)
     return merge_lo (pa, na, pb, nb, comp);
@@ -1238,7 +1238,7 @@
     return nb;
 
   /* Merge what remains of the runs, using a temp array with
-   * min(na, nb) elements.
+   * min (na, nb) elements.
    */
   if (na <= nb)
     return merge_lo (pa, ipa, na, pb, ipb, nb, comp);
@@ -1413,7 +1413,7 @@
             goto fail;
           if (descending)
             std::reverse (data + lo, data + lo + n);
-          /* If short, extend to min(minrun, nremaining). */
+          /* If short, extend to min (minrun, nremaining). */
           if (n < minrun)
             {
               const octave_idx_type force = nremaining <= minrun ? nremaining : minrun;
@@ -1475,7 +1475,7 @@
               std::reverse (data + lo, data + lo + n);
               std::reverse (idx + lo, idx + lo + n);
             }
-          /* If short, extend to min(minrun, nremaining). */
+          /* If short, extend to min (minrun, nremaining). */
           if (n < minrun)
             {
               const octave_idx_type force = nremaining <= minrun ? nremaining : minrun;
@@ -1610,9 +1610,9 @@
 
   while (! runs.empty ())
     {
-      octave_idx_type col  = runs.top ().col;
-      octave_idx_type ofs  = runs.top ().ofs;
-      octave_idx_type nel  = runs.top ().nel;
+      octave_idx_type col = runs.top ().col;
+      octave_idx_type ofs = runs.top ().ofs;
+      octave_idx_type nel = runs.top ().nel;
       runs.pop ();
       assert (nel > 1);
 
rename from liboctave/oct-sort.h
rename to liboctave/util/oct-sort.h
rename from liboctave/oct-sparse.h
rename to liboctave/util/oct-sparse.h
--- a/liboctave/oct-sparse.h
+++ b/liboctave/util/oct-sparse.h
@@ -87,7 +87,7 @@
      || defined (HAVE_UFSPARSE_CHOLMOD_H) \
      || defined (HAVE_CHOLMOD_CHOLMOD_H) \
      || defined (HAVE_CHOLMOD_H))
-#ifdef IDX_TYPE_LONG
+#ifdef USE_64_BIT_IDX_T
 #define CHOLMOD_NAME(name) cholmod_l_ ## name
 #else
 #define CHOLMOD_NAME(name) cholmod_ ## name
rename from liboctave/pathsearch.cc
rename to liboctave/util/pathsearch.cc
rename from liboctave/pathsearch.h
rename to liboctave/util/pathsearch.h
rename from liboctave/regexp.cc
rename to liboctave/util/regexp.cc
--- a/liboctave/regexp.cc
+++ b/liboctave/util/regexp.cc
@@ -315,9 +315,9 @@
         }
       else if (matches == PCRE_ERROR_NOMATCH)
         break;
-      else if (ovector[1] <= ovector[0])
+      else if (ovector[1] <= ovector[0] && ! options.emptymatch ())
         {
-          // Zero sized match.  Skip to next char.
+          // Zero length match.  Skip to next char.
           idx = ovector[0] + 1;
           if (idx < buffer.length ())
             continue;
@@ -333,8 +333,7 @@
             {
               if (ovector[2*i] >= 0 && ovector[2*i+1] > 0
                   && (i == 1 || ovector[2*i] != ovector[2*i-2]
-                      || ovector[2*i-1] != ovector[2*i+1])
-                  && ovector[2*i] >= 0 && ovector[2*i+1] > 0)
+                      || ovector[2*i-1] != ovector[2*i+1]))
                 {
                   token_extents(pos_match,0) = double (ovector[2*i]+1);
                   token_extents(pos_match++,1) = double (ovector[2*i+1]);
@@ -401,7 +400,16 @@
           regexp::match_element new_elem (named_tokens, tokens, match_string,
                                           token_extents, start, end);
           lst.push_back (new_elem);
-          idx = ovector[1];
+
+          if (ovector[1] <= ovector[0])
+          {
+            // Zero length match.  Skip to next char.
+            idx = ovector[0] + 1;
+            if (idx <= buffer.length ())
+              continue;
+          }
+          else 
+            idx = ovector[1];
 
           if (options.once () || idx >= buffer.length ())
             break;
@@ -418,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>
@@ -438,55 +442,80 @@
   return retval;
 }
 
+// Declare rep_token_t used in processing replacement string
+typedef struct
+  {
+    size_t pos;
+    int num;
+  } rep_token_t;
+
+
 std::string
 regexp::replace (const std::string& buffer, const std::string& replacement)
 {
   std::string retval;
 
+  regexp::match_data rx_lst = match (buffer);
+
+  size_t num_matches = rx_lst.size ();
+
+  if (num_matches == 0)
+    {
+      retval = buffer;
+      return retval;
+    }
+
   // Identify replacement tokens; build a vector of group numbers in
   // the replacement string so that we can quickly calculate the size
   // of the replacement.
 
-  int tokens = 0;
-  for (size_t i=1; i < replacement.size (); i++)
+  // FIXME: All code assumes that only 10 tokens ($0-$9) exist.
+  //        $11 represents $1 followed by the character '1' rather than
+  //        the eleventh capture buffer.
+
+  std::string repstr = replacement;
+  std::vector<rep_token_t> tokens;
+  tokens.reserve (5);  // Reserve memory for 5 pattern replacements
+
+  for (size_t i=0; i < repstr.size (); i++)
     {
-      if (replacement[i-1]=='$' && isdigit (replacement[i]))
+      if (repstr[i] == '\\')
         {
-          tokens++;
-          i++;
+          if (i < repstr.size () - 1 && repstr[i+1] == '$')
+            {
+              repstr.erase (i,1);  // erase backslash
+              i++;                 // skip over '$'
+              continue;
+            }
+          if (i < repstr.size () - 1 && repstr[i+1] == '\\')
+            {
+              repstr.erase (i,1);  // erase 1st backslash
+              continue;
+            }
         }
-    }
-  std::vector<int> token (tokens);
+      else if (repstr[i] == '$')
+        {
+          if (i < repstr.size () - 1 && isdigit (repstr[i+1]))
+            {
+              rep_token_t tmp_token;
 
-  int kk = 0;
-  for (size_t i = 1; i < replacement.size (); i++)
-    {
-      if (replacement[i-1]=='$' && isdigit (replacement[i]))
-        {
-          token[kk++] = replacement[i]-'0';
-          i++;
+              tmp_token.pos = i;
+              tmp_token.num = repstr[i+1]-'0';
+              tokens.push_back (tmp_token);
+            }
         }
     }
 
-  regexp::match_data rx_lst = match (buffer);
-
-  size_t sz = rx_lst.size ();
+  std::string rep;
+  int num_tokens = tokens.size ();
 
-  if (sz == 0)
-    {
-      retval = buffer;
-      return retval;
-    }
-
-  std::string rep;
-
-  if (tokens > 0)
+  if (num_tokens > 0)
     {
       // Determine replacement length
-      const size_t replen = replacement.size () - 2*tokens;
+      const size_t replen = repstr.size () - 2*num_tokens;
       int delta = 0;
       regexp::match_data::const_iterator p = rx_lst.begin ();
-      for (size_t i = 0; i < sz; i++)
+      for (size_t i = 0; i < num_matches; i++)
         {
           OCTAVE_QUIT;
 
@@ -495,13 +524,13 @@
 
           const Matrix pairs (p->token_extents ());
           size_t pairlen = 0;
-          for (int j = 0; j < tokens; j++)
+          for (int j = 0; j < num_tokens; j++)
             {
-              if (token[j] == 0)
+              if (tokens[j].num == 0)
                 pairlen += static_cast<size_t> (end - start) + 1;
-              else if (token[j] <= pairs.rows ())
-                pairlen += static_cast<size_t> (pairs(token[j]-1,1)
-                                                - pairs(token[j]-1,0)) + 1;
+              else if (tokens[j].num <= pairs.rows ())
+                pairlen += static_cast<size_t> (pairs(tokens[j].num-1,1)
+                                                - pairs(tokens[j].num-1,0)) + 1;
             }
           delta += (static_cast<int> (replen + pairlen)
                     - static_cast<int> (end - start + 1));
@@ -512,7 +541,7 @@
       rep.reserve (buffer.size () + delta);
       size_t from = 0;
       p = rx_lst.begin ();
-      for (size_t i = 0; i < sz; i++)
+      for (size_t i = 0; i < num_matches; i++)
         {
           OCTAVE_QUIT;
 
@@ -523,51 +552,50 @@
           rep.append (&buffer[from], static_cast<size_t> (start - 1) - from);
           from = static_cast<size_t> (end - 1) + 1;
 
-          for (size_t j = 1; j < replacement.size (); j++)
+          size_t cur_pos = 0;
+
+          for (int j = 0; j < num_tokens; j++)
             {
-              if (replacement[j-1]=='$' && isdigit (replacement[j]))
+              rep.append (&repstr[cur_pos], (tokens[j].pos) - cur_pos);
+              cur_pos = tokens[j].pos+2;
+
+              int k = tokens[j].num;
+              if (k == 0)
                 {
-                  int k = replacement[j]-'0';
-                  if (k == 0)
-                    {
-                      // replace with entire match
-                      rep.append (&buffer[static_cast<size_t> (end - 1)],
-                                  static_cast<size_t> (end - start) + 1);
-                    }
-                  else if (k <= pairs.rows ())
-                    {
-                      // replace with group capture
-                      rep.append (&buffer[static_cast<size_t> (pairs(k-1,0)-1)],
-                                  static_cast<size_t> (pairs(k-1,1)
-                                                       - pairs(k-1,0)) + 1);
-                    }
-                  else
-                    {
-                      // replace with nothing
-                    }
-                  j++;
+                  // replace with entire match
+                  rep.append (&buffer[static_cast<size_t> (end - 1)],
+                              static_cast<size_t> (end - start) + 1);
+                }
+              else if (k <= pairs.rows ())
+                {
+                  // replace with group capture
+                  rep.append (&buffer[static_cast<size_t> (pairs(k-1,0)-1)],
+                              static_cast<size_t> (pairs(k-1,1)
+                                                   - pairs(k-1,0)) + 1);
                 }
               else
-                rep.append (1, replacement[j-1]);
+                {
+                  // replace with nothing
+                }
+            }
+          if (cur_pos < repstr.size ())
+            rep.append (&repstr[cur_pos], repstr.size () - cur_pos);
 
-              if (j+1 == replacement.size ())
-                rep.append (1, replacement[j]);
-            }
           p++;
         }
       rep.append (&buffer[from], buffer.size () - from);
     }
   else
     {
-      // Determine replacement length
-      const size_t replen = replacement.size ();
+      // Determine repstr length
+      const size_t replen = repstr.size ();
       int delta = 0;
       regexp::match_data::const_iterator p = rx_lst.begin ();
-      for (size_t i = 0; i < sz; i++)
+      for (size_t i = 0; i < num_matches; i++)
         {
           OCTAVE_QUIT;
           delta += static_cast<int> (replen)
-            - static_cast<int> (p->end () - p->start () + 1);
+                   - static_cast<int> (p->end () - p->start () + 1);
           p++;
         }
 
@@ -575,13 +603,13 @@
       rep.reserve (buffer.size () + delta);
       size_t from = 0;
       p = rx_lst.begin ();
-      for (size_t i = 0; i < sz; i++)
+      for (size_t i = 0; i < num_matches; i++)
         {
           OCTAVE_QUIT;
           rep.append (&buffer[from],
                       static_cast<size_t> (p->start () - 1) - from);
           from = static_cast<size_t> (p->end () - 1) + 1;
-          rep.append (replacement);
+          rep.append (repstr);
           p++;
         }
       rep.append (&buffer[from], buffer.size () - from);
rename from liboctave/regexp.h
rename to liboctave/util/regexp.h
--- a/liboctave/regexp.h
+++ b/liboctave/util/regexp.h
@@ -33,7 +33,9 @@
 #include "base-list.h"
 #include "str-vec.h"
 
-class regexp
+class
+OCTAVE_API
+regexp
 {
 public:
 
@@ -87,17 +89,19 @@
   std::string replace (const std::string& buffer,
                        const std::string& replacement);
 
-  struct opts
+  class opts
   {
   public:
 
     opts (void)
       : x_case_insensitive (false), x_dotexceptnewline (false),
-        x_freespacing (false), x_lineanchors (false), x_once (false) { }
+        x_emptymatch (false), x_freespacing (false), x_lineanchors (false),
+        x_once (false) { }
 
     opts (const opts& o)
       : x_case_insensitive (o.x_case_insensitive),
         x_dotexceptnewline (o.x_dotexceptnewline),
+        x_emptymatch (o.x_emptymatch),
         x_freespacing (o.x_freespacing),
         x_lineanchors (o.x_lineanchors),
         x_once (o.x_once)
@@ -109,6 +113,7 @@
         {
           x_case_insensitive = o.x_case_insensitive;
           x_dotexceptnewline = o.x_dotexceptnewline;
+          x_emptymatch = o.x_emptymatch;
           x_freespacing = o.x_freespacing;
           x_lineanchors = o.x_lineanchors;
           x_once = o.x_once;
@@ -121,12 +126,14 @@
 
     void case_insensitive (bool val) { x_case_insensitive = val; }
     void dotexceptnewline (bool val) { x_dotexceptnewline = val; }
+    void emptymatch (bool val) { x_emptymatch = val; }
     void freespacing (bool val) { x_freespacing = val; }
     void lineanchors (bool val) { x_lineanchors = val; }
     void once (bool val) { x_once = val; }
 
     bool case_insensitive (void) const { return x_case_insensitive; }
     bool dotexceptnewline (void) const { return x_dotexceptnewline; }
+    bool emptymatch (void) const { return x_emptymatch; }
     bool freespacing (void) const { return x_freespacing; }
     bool lineanchors (void) const { return x_lineanchors; }
     bool once (void) const { return x_once; }
@@ -135,6 +142,7 @@
 
     bool x_case_insensitive;
     bool x_dotexceptnewline;
+    bool x_emptymatch;
     bool x_freespacing;
     bool x_lineanchors;
     bool x_once;
rename from liboctave/singleton-cleanup.cc
rename to liboctave/util/singleton-cleanup.cc
rename from liboctave/singleton-cleanup.h
rename to liboctave/util/singleton-cleanup.h
rename from liboctave/sparse-sort.cc
rename to liboctave/util/sparse-sort.cc
rename from liboctave/sparse-sort.h
rename to liboctave/util/sparse-sort.h
rename from liboctave/sparse-util.cc
rename to liboctave/util/sparse-util.cc
--- a/liboctave/sparse-util.cc
+++ b/liboctave/util/sparse-util.cc
@@ -28,9 +28,13 @@
 #include <stdio.h>
 #include <stdarg.h>
 #include "lo-error.h"
+#include "oct-sparse.h"
 #include "sparse-util.h"
 
 // FIXME this overload is here due to API change in SuiteSparse (3.1 -> 3.2)
+
+#ifdef HAVE_CHOLMOD
+
 void
 SparseCholError (int status, char *file, int line, char *message)
 {
@@ -40,10 +44,16 @@
 void
 SparseCholError (int status, const char *file, int line, const char *message)
 {
-  (*current_liboctave_warning_handler)("warning %i, at line %i in file %s",
-                                     status, line, file);
 
-  (*current_liboctave_warning_handler)(message);
+  // Ignore CHOLMOD_NOT_POSDEF, since we handle that in Fchol as an
+  // error or exit status.
+  if (status != CHOLMOD_NOT_POSDEF)
+    {
+      (*current_liboctave_warning_handler)("warning %i, at line %i in file %s",
+                                           status, line, file);
+
+      (*current_liboctave_warning_handler)(message);
+    }
 }
 
 int
@@ -57,6 +67,7 @@
   return ret;
 }
 
+#endif //HAVE_CHOLMOD
 
 bool
 sparse_indices_ok (octave_idx_type *r, octave_idx_type *c,
rename from liboctave/sparse-util.h
rename to liboctave/util/sparse-util.h
--- a/liboctave/sparse-util.h
+++ b/liboctave/util/sparse-util.h
@@ -24,6 +24,8 @@
 #if !defined (octave_sparse_util_h)
 #define octave_sparse_util_h 1
 
+#ifdef HAVE_CHOLMOD
+
 // FIXME this overload is here due to API change in SuiteSparse (3.1 -> 3.2)
 extern OCTAVE_API void SparseCholError (int status, char *file,
                                         int line, char *message);
@@ -31,6 +33,8 @@
                                         int line, const char *message);
 extern OCTAVE_API int SparseCholPrint (const char *fmt, ...);
 
+#endif //HAVE_CHOLMOD
+
 extern OCTAVE_API bool
 sparse_indices_ok (octave_idx_type *r, octave_idx_type *c,
                    octave_idx_type nrows, octave_idx_type ncols,
rename from liboctave/statdefs.h
rename to liboctave/util/statdefs.h
rename from liboctave/str-vec.cc
rename to liboctave/util/str-vec.cc
--- a/liboctave/str-vec.cc
+++ b/liboctave/util/str-vec.cc
@@ -54,7 +54,7 @@
   for (std::list<std::string>::const_iterator p = lst.begin ();
        p != lst.end ();
        p++)
-    elem(i++) = *p;
+    elem (i++) = *p;
 }
 
 string_vector::string_vector (const std::set<std::string>& lst)
@@ -69,7 +69,7 @@
   for (std::set<std::string>::const_iterator p = lst.begin ();
        p != lst.end ();
        p++)
-    elem(i++) = *p;
+    elem (i++) = *p;
 }
 
 // Create a string vector from a NULL terminated list of C strings.
@@ -125,9 +125,9 @@
       octave_idx_type k = 0;
 
       for (octave_idx_type i = 1; i < len; i++)
-        if (elem(i) != elem(k))
+        if (elem (i) != elem (k))
           if (++k != i)
-            elem(k) = elem(i);
+            elem (k) = elem (i);
 
       if (len != ++k)
         resize (k);
@@ -143,7 +143,7 @@
 
   resize (len + 1);
 
-  elem(len) = s;
+  elem (len) = s;
 
   return *this;
 }
@@ -158,7 +158,7 @@
   resize (new_len);
 
   for (octave_idx_type i = 0; i < sv_len; i++)
-    elem(len + i) = sv[i];
+    elem (len + i) = sv[i];
 
   return *this;
 }
@@ -175,9 +175,9 @@
       octave_idx_type i;
 
       for (i = 0; i < len - 1; i++)
-        retval += elem(i) + sep;
+        retval += elem (i) + sep;
 
-      retval += elem(i);
+      retval += elem (i);
     }
 
   return retval;
@@ -190,10 +190,10 @@
 
   char **retval = new char * [len + 1];
 
-  retval [len] = 0;
+  retval[len] = 0;
 
   for (octave_idx_type i = 0; i < len; i++)
-    retval[i] = strsave (elem(i).c_str ());
+    retval[i] = strsave (elem (i).c_str ());
 
   return retval;
 }
@@ -212,7 +212,8 @@
 // Format a list in neat columns.
 
 std::ostream&
-string_vector::list_in_columns (std::ostream& os, int width) const
+string_vector::list_in_columns (std::ostream& os, int width,
+                                const std::string& prefix) const
 {
   // Compute the maximum name length.
 
@@ -241,7 +242,8 @@
   // Calculate the maximum number of columns that will fit.
 
   octave_idx_type line_length
-    = (width <= 0) ? command_editor::terminal_cols () : width;
+    = ((width <= 0 ? command_editor::terminal_cols () : width)
+       - prefix.length ());
 
   octave_idx_type nc = line_length / max_name_length;
   if (nc == 0)
@@ -264,6 +266,8 @@
 
       // Print the next row.
 
+      os << prefix;
+
       while (1)
         {
           std::string nm = elem (count);
rename from liboctave/str-vec.h
rename to liboctave/util/str-vec.h
--- a/liboctave/str-vec.h
+++ b/liboctave/util/str-vec.h
@@ -79,7 +79,7 @@
 
     for (octave_idx_type i = 0; i < n; i++)
       {
-        octave_idx_type tmp = elem(i).length ();
+        octave_idx_type tmp = elem (i).length ();
 
         if (tmp > longest)
           longest = tmp;
@@ -88,7 +88,7 @@
     return longest;
   }
 
-  void resize (octave_idx_type n, const std::string& rfv = resize_fill_value ())
+  void resize (octave_idx_type n, const std::string& rfv = std::string ())
   {
     Array<std::string>::resize (dim_vector (n, 1), rfv);
   }
@@ -111,7 +111,9 @@
 
   static void delete_c_str_vec (const char * const*);
 
-  std::ostream& list_in_columns (std::ostream&, int width = 0) const;
+  std::ostream&
+  list_in_columns (std::ostream&, int width = 0,
+                   const std::string& prefix = std::string ()) const;
 };
 
 #endif
rename from liboctave/sun-utils.h
rename to liboctave/util/sun-utils.h
--- a/m4/acinclude.m4
+++ b/m4/acinclude.m4
@@ -37,357 +37,293 @@
 dnl
 dnl ----------------------------------------------------------------------
 dnl
-dnl Figure out the hardware-vendor-os info.
-dnl
-dnl OCTAVE_HOST_TYPE
-AC_DEFUN([OCTAVE_HOST_TYPE],
-[AC_CANONICAL_HOST
-if test -z "$host"; then
-  host=unknown
-fi
-canonical_host_type=$host
-if test "$host" = unknown; then
-  AC_MSG_WARN([configuring Octave for unknown system type
-])
-fi
-AC_SUBST(canonical_host_type)])
-dnl
-dnl Set default value for a variable and substitute it.
+
 dnl
-dnl OCTAVE_SET_DEFAULT
-AC_DEFUN([OCTAVE_SET_DEFAULT],
-[ifelse($#, 2, [: ${$1=$2}
-])dnl
-AC_MSG_RESULT([defining $1 to be $$1])
-AC_SUBST($1)])
-dnl
-dnl Check for ar.
-dnl
-AC_DEFUN([OCTAVE_PROG_AR],
-[if test -z "$AR"; then
-  AR=ar
-fi
-AC_SUBST(AR)
-
-if test -z "$ARFLAGS"; then
-  ARFLAGS="rc"
-fi
-AC_SUBST(ARFLAGS)
-])
-dnl
-dnl See if the compiler supports placement delete
+dnl Alphabetical list of macros in the OCTAVE_ namespace
 dnl
-AC_DEFUN([OCTAVE_PLACEMENT_DELETE],
-[AC_CACHE_CHECK([whether <new> defines placement delete operator],
-octave_cv_placement_delete,
-[AC_LANG_PUSH(C++)
-AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <new>]],
-[[operator delete((void *)0, (void *)0);]])],
-octave_cv_placement_delete=yes, octave_cv_placement_delete=no)])
-if test $octave_cv_placement_delete = yes; then
-AC_DEFINE(HAVE_PLACEMENT_DELETE,1,[Define if C++ supports operator delete(void *, void *)])
-fi
-AC_LANG_POP(C++)
-])
-dnl
-dnl See if the compiler dynamic auto arrays
+
 dnl
-AC_DEFUN([OCTAVE_DYNAMIC_AUTO_ARRAYS],
-[AC_CACHE_CHECK([whether C++ supports dynamic auto arrays],
-octave_cv_dynamic_auto_arrays,
-[AC_LANG_PUSH(C++)
-AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]],
-[[void test(char *); int length(); char x[length()]; test(x);]])],
-octave_cv_dynamic_auto_arrays=yes, octave_cv_dynamic_auto_arrays=no)])
-if test $octave_cv_dynamic_auto_arrays = yes; then
-AC_DEFINE(HAVE_DYNAMIC_AUTO_ARRAYS,1,[Define if C++ supports dynamic auto arrays])
-fi
-AC_LANG_POP(C++)
-])
-dnl
-dnl See if the C++ library has functions to set real and imaginary
-dnl parts of complex numbers independently.
-dnl
-AC_DEFUN([OCTAVE_CXX_COMPLEX_SETTERS],
-[AC_CACHE_CHECK([whether complex class can set components independently],
-octave_cv_cxx_complex_setters,
-[AC_LANG_PUSH(C++)
-AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <complex>]],
-[[std::complex<double> x; x.real (1.0); x.imag (2.0);]])],
-octave_cv_cxx_complex_setters=yes, octave_cv_cxx_complex_setters=no)])
-if test $octave_cv_cxx_complex_setters = yes; then
-AC_DEFINE(HAVE_CXX_COMPLEX_SETTERS,1,[Define if C++ complex class has void real (T) and void imag (T) methods])
-fi
-AC_LANG_POP(C++)
-])
-dnl
-dnl See if the C++ library has functions to access real and imaginary
-dnl parts of complex numbers independently via references.
+dnl Check if the Carbon Framework defines CGDisplayBitsPerPixel.
 dnl
-AC_DEFUN([OCTAVE_CXX_COMPLEX_REFERENCE_ACCESSORS],
-[AC_CACHE_CHECK([whether complex class can reference components independently],
-octave_cv_cxx_complex_reference_accessors,
-[AC_LANG_PUSH(C++)
-AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <complex>]],
-[[std::complex<double> x; x.real () = 1.0; x.imag () = 1.0;]])],
-octave_cv_cxx_complex_reference_accessors=yes, octave_cv_cxx_complex_reference_accessors=no)])
-if test $octave_cv_cxx_complex_reference_accessors = yes; then
-AC_DEFINE(HAVE_CXX_COMPLEX_REFERENCE_ACCESSORS,1,[Define if C++ complex class has T& real (void) and T& imag (void) methods])
-fi
-AC_LANG_POP(C++)
-])
-dnl
-dnl The following test is from Karl Berry's Kpathseach library.  I'm
-dnl including it here in case we someday want to make the use of
-dnl kpathsea optional.
-dnl
-dnl Some BSD putenv's, e.g., FreeBSD, do malloc/free's on the environment.
-dnl This test program is due to Mike Hibler <mike@cs.utah.edu>.
-dnl We don't actually need to run this if we don't have putenv, but it
-dnl doesn't hurt.
-AC_DEFUN([OCTAVE_SMART_PUTENV],
-[AC_MSG_CHECKING([whether putenv uses malloc])
-AC_CACHE_VAL(octave_cv_func_putenv_malloc,
-[AC_RUN_IFELSE([AC_LANG_SOURCE([[
-#define VAR	"YOW_VAR"
-#define STRING1 "GabbaGabbaHey"
-#define STRING2 "Yow!!"		/* should be shorter than STRING1 */
-extern char *getenv (); /* in case char* and int don't mix gracefully */
-main ()
-{
-  char *str1, *rstr1, *str2, *rstr2;
-  str1 = getenv (VAR);
-  if (str1)
-    exit (1);
-  str1 = malloc (strlen (VAR) + 1 + strlen (STRING1) + 1);
-  if (str1 == 0)
-    exit (2);
-  strcpy (str1, VAR);
-  strcat (str1, "=");
-  strcat (str1, STRING1);
-  if (putenv (str1) < 0)
-    exit (3);
-  rstr1 = getenv (VAR);
-  if (rstr1 == 0)
-    exit (4);
-  rstr1 -= strlen (VAR) + 1;
-  if (strncmp (rstr1, VAR, strlen (VAR)))
-    exit (5);
-  str2 = malloc (strlen (VAR) + 1 + strlen (STRING2) + 1);
-  if (str2 == 0 || str1 == str2)
-    exit (6);
-  strcpy (str2, VAR);
-  strcat (str2, "=");
-  strcat (str2, STRING2);
-  if (putenv (str2) < 0)
-    exit (7);
-  rstr2 = getenv (VAR);
-  if (rstr2 == 0)
-    exit (8);
-  rstr2 -= strlen (VAR) + 1;
-#if 0
-  printf ("rstr1=0x%x, rstr2=0x%x\n", rstr1, rstr2);
-  /*
-   * If string from first call was reused for the second call,
-   * you had better not do a free on the first string!
-   */
-  if (rstr1 == rstr2)
-          printf ("#define SMART_PUTENV\n");
-  else
-          printf ("#undef SMART_PUTENV\n");
-#endif
-  exit (rstr1 == rstr2 ? 0 : 1);
-}]])], octave_cv_func_putenv_malloc=yes, octave_cv_func_putenv_malloc=no,
-    octave_cv_func_putenv_malloc=no)])dnl
-AC_MSG_RESULT([$octave_cv_func_putenv_malloc])
-if test $octave_cv_func_putenv_malloc = yes; then
-  AC_DEFINE(SMART_PUTENV,1,[To quiet autoheader.])
-fi])
-dnl
-dnl Check to see if C++ compiler needs the new friend template declaration 
-dnl syntax. 
-dnl
-dnl OCTAVE_CXX_NEW_FRIEND_TEMPLATE_DECL
-AC_DEFUN([OCTAVE_CXX_NEW_FRIEND_TEMPLATE_DECL], [
-  AC_REQUIRE([AC_PROG_CXX])
-  AC_MSG_CHECKING([for C++ support for new friend template declaration])
-  AC_CACHE_VAL(octave_cv_cxx_new_friend_template_decl, [
-    AC_LANG_PUSH(C++)
-    rm -f conftest.h
-    cat > conftest.h <<EOB
-       struct A {
-	 friend int operator== (const A&, const A&);
-	 A (int) { }
-       };
-
-       template <class T> int
-       operator== (const T&, const T&)
-       {
-	 return 0;
-       }
-EOB
-    AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include "conftest.h"]],
-      [[A a (1);
-        return a == A(1);]])],
-      [octave_cv_cxx_new_friend_template_decl=no],
-      [octave_cv_cxx_new_friend_template_decl=yes])
+AC_DEFUN([OCTAVE_CARBON_CGDISPLAYBITSPERPIXEL], [
+  AC_CACHE_CHECK([whether CGDisplayBitsPerPixel is defined in the Carbon Framework],
+    [octave_cv_func_carbon_cgdisplaybitsperpixel],
+    [AC_LANG_PUSH(C++)
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+        #include <Carbon/Carbon.h>
+        ]], [[
+        CGDirectDisplayID display = CGMainDisplayID ();
+        size_t depth = CGDisplayBitsPerPixel (display);
+      ]])],
+      octave_cv_func_carbon_cgdisplaybitsperpixel=yes,
+      octave_cv_func_carbon_cgdisplaybitsperpixel=no)
     AC_LANG_POP(C++)
   ])
-  AC_MSG_RESULT([$octave_cv_cxx_new_friend_template_decl])
-  if test $octave_cv_cxx_new_friend_template_decl = yes; then
-    AC_DEFINE(CXX_NEW_FRIEND_TEMPLATE_DECL,1,[Define if your compiler supports `<>' stuff for template friends.])
+  if test $octave_cv_func_carbon_cgdisplaybitsperpixel = yes; then
+    AC_DEFINE(HAVE_CARBON_CGDISPLAYBITSPERPIXEL, 1,
+      [Define to 1 if Carbon Framework has CGDisplayBitsPerPixel.])
   fi
 ])
 dnl
-dnl Check to see if C compiler handles FLAG command line option.  If
-dnl two arguments are specified, execute the second arg as shell
-dnl commands.  Otherwise, add FLAG to CFLAGS if the compiler accepts
-dnl the flag.
+dnl Check if C compiler handles FLAG command line option.  If two
+dnl arguments are specified, execute the second arg as shell commands.
+dnl Otherwise, add FLAG to CFLAGS if the compiler accepts the flag.
 dnl
-dnl OCTAVE_CC_FLAG
 AC_DEFUN([OCTAVE_CC_FLAG], [
-  ac_safe=`echo "$1" | sed 'y%./+-:=%__p___%'`
+  ac_safe=`echo "$1" | sed 'y% ./+-:=%___p___%'`
   AC_MSG_CHECKING([whether ${CC-cc} accepts $1])
-  AC_CACHE_VAL(octave_cv_cc_flag_$ac_safe, [
-    AC_LANG_PUSH(C)
-    XCFLAGS="$CFLAGS"
+  AC_CACHE_VAL([octave_cv_cc_flag_$ac_safe],
+    [AC_LANG_PUSH(C)
+    ac_octave_save_CFLAGS="$CFLAGS"
     CFLAGS="$CFLAGS $1"
     AC_LINK_IFELSE([AC_LANG_PROGRAM([], [])],
-      eval "octave_cv_cc_flag_$ac_safe=yes",
-      eval "octave_cv_cc_flag_$ac_safe=no")
-    CFLAGS="$XCFLAGS"
+      [eval "octave_cv_cc_flag_$ac_safe=yes"],
+      [eval "octave_cv_cc_flag_$ac_safe=no"])
+    CFLAGS="$ac_octave_save_CFLAGS"
     AC_LANG_POP(C)
   ])
   if eval "test \"`echo '$octave_cv_cc_flag_'$ac_safe`\" = yes"; then
-    AC_MSG_RESULT(yes)
-    ifelse([$2], , [
-      CFLAGS="$CFLAGS $1"
+    AC_MSG_RESULT([yes])
+    ifelse([$2], , 
+      [CFLAGS="$CFLAGS $1"
       AC_MSG_RESULT([adding $1 to CFLAGS])], [$2])
   else
-    AC_MSG_RESULT(no)
+    AC_MSG_RESULT([no])
     ifelse([$3], , , [$3])
   fi
 ])
 dnl
-dnl Check to see if C++ compiler handles FLAG command line option.  If
-dnl two arguments are specified, execute the second arg as shell
-dnl commands.  Otherwise, add FLAG to CXXFLAGS if the compiler accepts
-dnl the flag.
+dnl Check whether the FFTW library supports multi-threading. This macro
+dnl should be called once per FFTW precision passing in the library
+dnl variant (e.g. "fftw3") and a function in the thread support API
+dnl (e.g. "fftw_plan_with_nthreads"). Depending on how FFTW was built,
+dnl the thread functions could be compiled into the main FFTW library or
+dnl could be a separate add-on library that is passed to the linker
+dnl ahead of the main FFTW library.
 dnl
-dnl OCTAVE_CXX_FLAG
-AC_DEFUN([OCTAVE_CXX_FLAG], [
-  ac_safe=`echo "$1" | sed 'y%./+-:=%__p___%'`
-  AC_MSG_CHECKING([whether ${CXX-g++} accepts $1])
-  AC_CACHE_VAL(octave_cv_cxx_flag_$ac_safe, [
-    AC_LANG_PUSH(C++)
-    XCXXFLAGS="$CXXFLAGS"
-    CXXFLAGS="$CXXFLAGS $1"
-    AC_LINK_IFELSE([AC_LANG_PROGRAM([], [])],
-      eval "octave_cv_cxx_flag_$ac_safe=yes",
-      eval "octave_cv_cxx_flag_$ac_safe=no")
-    CXXFLAGS="$XCXXFLAGS"
+AC_DEFUN([OCTAVE_CHECK_FFTW_THREADS], [
+  ac_octave_save_CPPFLAGS="$CPPFLAGS"
+  ac_octave_save_LDFLAGS="$LDFLAGS"
+  ac_octave_save_LIBS="$LIBS"
+  CPPFLAGS="$m4_toupper([$1])_CPPFLAGS $CPPFLAGS"
+  LDFLAGS="$m4_toupper([$1])_LDFLAGS $LDFLAGS"
+  LIBS="$m4_toupper([$1])_LIBS $LIBS"
+  AC_CACHE_CHECK([for $1 multi-threading support],
+    [octave_cv_[$1]_threads_lib],
+    [AC_LINK_IFELSE([AC_LANG_PROGRAM([[
+      #include <fftw3.h>
+      ]], [[
+      $2 (2);
+      ]])],
+      [octave_cv_[$1]_threads_lib=yes],
+      [LIBS="-l[$1]_threads $LIBS"
+      AC_LINK_IFELSE([AC_LANG_PROGRAM([[
+        #include <fftw3.h>
+        ]], [[
+        $2 (2);
+        ]])],
+        [octave_cv_[$1]_threads_lib="-l[$1]_threads"],
+        [octave_cv_[$1]_threads_lib=no])
+    ])
+  ])
+  case $octave_cv_[$1]_threads_lib in
+    -l*)
+      m4_toupper([$1])_LIBS="$octave_cv_[$1]_threads_lib $m4_toupper([$1])_LIBS"
+      ;;
+    no)
+      AC_MSG_WARN([No $1 multi-threading support found.])
+      AC_MSG_WARN([The single-threaded library will be used instead.])
+      ;;
+  esac
+  if test $octave_cv_[$1]_threads_lib != no; then
+    AC_DEFINE([HAVE_]m4_toupper([$1])[_THREADS], 1,
+      [Define to 1 if ]m4_toupper([$1])[ has multi-threading support.])
+  fi
+  CPPFLAGS="$ac_octave_save_CPPFLAGS"
+  LDFLAGS="$ac_octave_save_LDFLAGS"
+  LIBS="$ac_octave_save_LIBS"
+])
+dnl
+dnl Check whether a math mapper function is available in <cmath>.
+dnl Will define HAVE_CMATH_FUNC if there is a double variant and
+dnl HAVE_CMATH_FUNCF if there is a float variant.
+dnl Currently capable of checking for functions with single 
+dnl argument and returning bool/int/real.
+dnl
+AC_DEFUN([OCTAVE_CHECK_FUNC_CMATH], [
+  ac_safe=`echo "$1" | sed 'y% ./+-:=%___p___%'`
+
+  AC_CACHE_CHECK([for std::$1 in <cmath>],
+    [octave_cv_func_cmath_$ac_safe],
+    [AC_LANG_PUSH(C++)
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+        #include <cmath>
+        void take_func (bool (*func) (double x));
+        void take_func (int (*func) (double x));
+        void take_func (double (*func) (double x));
+        ]], [[
+        take_func(std::$1);
+        ]])],
+      [eval "octave_cv_func_cmath_$ac_safe=yes"],
+      [eval "octave_cv_func_cmath_$ac_safe=no"])
     AC_LANG_POP(C++)
   ])
-  if eval "test \"`echo '$octave_cv_cxx_flag_'$ac_safe`\" = yes"; then
-    AC_MSG_RESULT(yes)
-    ifelse([$2], , [
-      CXXFLAGS="$CXXFLAGS $1"
-      AC_MSG_RESULT([adding $1 to CXXFLAGS])], [$2])
-  else
-    AC_MSG_RESULT(no)
-    ifelse([$3], , , [$3])
+  if eval "test \"`echo '$octave_cv_func_cmath_'$ac_safe`\" = yes"; then
+    AC_DEFINE(AS_TR_CPP([[HAVE_CMATH_][$1]]), 1,
+      [Define to 1 if <cmath> provides $1.])
   fi
-])
-dnl
-dnl Check to see if Fortran compiler handles FLAG command line option.  If
-dnl two arguments are specified, execute the second arg as shell
-dnl commands.  Otherwise, add FLAG to FFLAGS if the compiler accepts
-dnl the flag.
-dnl
-dnl OCTAVE_F77_FLAG
-AC_DEFUN([OCTAVE_F77_FLAG], [
-  ac_safe=`echo "$1" | sed 'y%./+-:=%__p___%'`
-  AC_MSG_CHECKING([whether ${F77-g77} accepts $1])
-  AC_CACHE_VAL(octave_cv_f77_flag_$ac_safe, [
-    AC_LANG_PUSH(Fortran 77)
-    XFFLAGS="$FFLAGS"
-    FFLAGS="$FFLAGS $1"
-    AC_LINK_IFELSE([AC_LANG_PROGRAM([], [])],
-      eval "octave_cv_f77_flag_$ac_safe=yes",
-      eval "octave_cv_f77_flag_$ac_safe=no")
-    FFLAGS="$XFFLAGS"
-    AC_LANG_POP(Fortran 77)
+
+  AC_CACHE_CHECK([for std::$1 (float variant) in <cmath>],
+    [octave_cv_func_cmath_f$ac_safe],
+    [AC_LANG_PUSH(C++)
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+        #include <cmath>
+        void take_func (bool (*func) (float x));
+        void take_func (int (*func) (float x));
+        void take_func (float (*func) (float x));
+        ]], [[
+        take_func(std::$1);
+        ]])],
+      [eval "octave_cv_func_cmath_f$ac_safe=yes"],
+      [eval "octave_cv_func_cmath_f$ac_safe=no"])
+    AC_LANG_POP(C++)
   ])
-  if eval "test \"`echo '$octave_cv_f77_flag_'$ac_safe`\" = yes"; then
-    AC_MSG_RESULT(yes)
-    ifelse([$2], , [
-      FFLAGS="$FFLAGS $1"
-      AC_MSG_RESULT([adding $1 to FFLAGS])], [$2])
-  else
-    AC_MSG_RESULT(no)
-    ifelse([$3], , , [$3])
+  if eval "test \"`echo '$octave_cv_func_cmath_f'$ac_safe`\" = yes"; then
+    AC_DEFINE(AS_TR_CPP([[HAVE_CMATH_][$1][F]]), 1,
+      [Define to 1 if <cmath> provides float variant of $1.])
   fi
 ])
 dnl
-dnl Check to see whether the default Fortran INTEGER is 64 bits wide.
+dnl Check whether Qscintilla FindFirst function is old (16 inputs) or
+dnl new (17 inputs).
+dnl FIXME: This test uses a version number.  It potentially could
+dnl        be re-written to actually call the function, but is it worth it?
 dnl
-AC_DEFUN([OCTAVE_CHECK_FORTRAN_INTEGER_SIZE], [
-  octave_fintsize_save_FFLAGS="$FFLAGS"
-  FFLAGS="$FFLAGS $F77_INTEGER_8_FLAG"
-  AC_LANG_PUSH(Fortran 77)
-  AC_CACHE_CHECK([whether $F77 generates correct size integers],
-                 [octave_cv_fortran_integer_size],
-[AC_COMPILE_IFELSE(
-[      subroutine foo(n, in, out)
-      integer n, in(n), out(n)
-      integer i
-      do 10 i = 1, n
-        out(i) = in(i)
-   10 continue
-      return
-      end],
-[mv conftest.$ac_objext fintsize.$ac_objext
-
-  octave_fintsize_save_LIBS="$LIBS"
-  LIBS="fintsize.$ac_objext $[]_AC_LANG_PREFIX[]LIBS"
-  AC_LANG_PUSH(C)dnl
-  AC_RUN_IFELSE([AC_LANG_PROGRAM([[#include <assert.h>]], [[
-#ifdef USE_64_BIT_IDX_T
-#if IDX_TYPE_LONG
-  typedef long octave_idx_type;
-#else
-  typedef int octave_idx_type;
-#endif
-#else
-  typedef int octave_idx_type;
-#endif
-  octave_idx_type n = 2;
-  octave_idx_type in[2];
-  octave_idx_type out[2];
-  in[0] = 13;
-  in[0] = 42;
-  F77_FUNC(foo,FOO) (&n, &in, &out);
-  assert (in[0] == out[0] && in[1] == out[1]);
-]])],
-  [octave_cv_fortran_integer_size=yes],
-  [octave_cv_fortran_integer_size=no],
-  [octave_cv_fortran_integer_size=yes])
-  AC_LANG_POP(C)dnl
-  LIBS="$octave_fintsize_save_LIBS"
-rm -f conftest.$ac_objext fintsize.$ac_objext
-], [
-  rm -f conftest.$ac_objext
-  AC_MSG_FAILURE([cannot compile a simple Fortran program])
-  octave_cv_fortran_integer_size=no])])
-  AC_LANG_POP(Fortran 77)
-  FFLAGS="$octave_fintsize_save_FFLAGS"
+AC_DEFUN([OCTAVE_CHECK_FUNC_FINDFIRST_MODERN], [
+  AC_CACHE_CHECK([whether Qscintilla FindFirst uses 17 input arguments],
+    [octave_cv_func_findfirst_modern],
+    [AC_LANG_PUSH(C++)
+    ac_octave_save_CPPFLAGS="$CPPFLAGS"
+    CPPFLAGS="$QT_CPPFLAGS $CPPFLAGS"
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+        #include <Qsci/qsciglobal.h>
+        ]], [[
+        #if QSCINTILLA_VERSION < 0x020600
+        #error Old FindFirst function found.
+        #endif
+        ]])],
+      octave_cv_func_findfirst_modern=yes,
+      octave_cv_func_findfirst_modern=no)
+    CPPFLAGS="$ac_octave_save_CPPFLAGS"
+    AC_LANG_POP(C++)
+  ])
+  if test $octave_cv_func_findfirst_modern = yes; then
+    AC_DEFINE(HAVE_FINDFIRST_MODERN, 1, 
+      [Define to 1 if Qscintilla FindFirst uses modern form with 17 inputs.])
+  fi
+])
+dnl
+dnl Check if Fortran compiler has the intrinsic function ISNAN.
+dnl
+AC_DEFUN([OCTAVE_CHECK_FUNC_FORTRAN_ISNAN], [
+  AC_CACHE_CHECK([whether $F77 has the intrinsic function ISNAN],
+    [octave_cv_func_fortran_isnan],
+    [AC_LANG_PUSH(Fortran 77)
+    AC_COMPILE_IFELSE(
+[[      program foo
+      implicit none
+      real x
+      double precision y
+      if (isnan(x)) then
+        print *, 'x is NaN'
+      end if
+      if (isnan(y)) then
+        print *, 'y is NaN'
+      end if
+      end program
+]],
+      octave_cv_func_fortran_isnan=yes, octave_cv_func_fortran_isnan=no)
+    AC_LANG_POP(Fortran 77)      
+  ])
 ])
 dnl
+dnl Check if function gluTessCallback is called with "(...)".
 dnl
+AC_DEFUN([OCTAVE_CHECK_FUNC_GLUTESSCALLBACK_THREEDOTS], [
+  AC_CACHE_CHECK([whether gluTessCallback is called with "(...)"],
+    [octave_cv_func_glutesscallback_threedots],
+    [AC_LANG_PUSH(C++)
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+        #ifdef HAVE_GL_GLU_H
+        # include <GL/glu.h>
+        #elif defined HAVE_OPENGL_GLU_H || defined HAVE_FRAMEWORK_OPENGL
+        # include <OpenGL/glu.h>
+        #endif
+        ]], [[
+        GLvoid (*func)(...);
+        gluTessCallback(0, 0, func);
+        ]])],
+      octave_cv_func_glutesscallback_threedots=yes,
+      octave_cv_func_glutesscallback_threedots=no)
+    AC_LANG_POP(C++)
+  ])
+  if test $octave_cv_func_glutesscallback_threedots = yes; then
+    AC_DEFINE(HAVE_GLUTESSCALLBACK_THREEDOTS, 1, 
+      [Define to 1 if gluTessCallback is called with (...).])
+  fi
+])
+dnl
+dnl Check whether Qscintilla SetPlaceholderText function exists.
+dnl FIXME: This test uses a version number.  It potentially could
+dnl        be re-written to actually call the function, but is it worth it?
 dnl
-dnl OCTAVE_CHECK_LIBRARY(LIBRARY, DOC-NAME, WARN-MSG, HEADER, FUNC,
-dnl                      LANG, DOC-STRING, EXTRA-CHECK)
-AC_DEFUN([OCTAVE_CHECK_LIBRARY], [
+AC_DEFUN([OCTAVE_CHECK_FUNC_SETPLACEHOLDERTEXT], [
+  AC_CACHE_CHECK([whether Qt has SetPlaceholderText function],
+    [octave_cv_func_setplaceholdertext],
+    [AC_LANG_PUSH(C++)
+    ac_octave_save_CPPFLAGS="$CPPFLAGS"
+    CPPFLAGS="$QT_CPPFLAGS $CPPFLAGS"
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+        #include <Qt/qglobal.h>
+        ]], [[
+        #if QT_VERSION < 0x040700
+        #error No SetPlacholderText function available.
+        #endif
+        ]])],
+      octave_cv_func_setplaceholdertext=yes,
+      octave_cv_func_setplaceholdertext=no)
+    CPPFLAGS="$ac_octave_save_CPPFLAGS"
+    AC_LANG_POP(C++)
+  ])
+  if test $octave_cv_func_setplaceholdertext = yes; then
+    AC_DEFINE(HAVE_SETPLACEHOLDERTEXT, 1, 
+      [Define to 1 if you have the Qt SetPlaceholderText function.])
+  fi
+])
+dnl
+dnl Check whether HDF5 library has version 1.6 API functions.
+dnl
+AC_DEFUN([OCTAVE_CHECK_HDF5_HAS_VER_16_API], [
+  AC_CACHE_CHECK([whether HDF5 library has enforced version 1.6 API],
+    [octave_cv_hdf5_has_ver_16_api],
+    [AC_LINK_IFELSE([AC_LANG_PROGRAM([[
+      #include <hdf5.h>
+      ]], [[
+      H5Eset_auto (0, 0);
+      ]])],
+      octave_cv_hdf5_has_ver_16_api=yes,
+      octave_cv_hdf5_has_ver_16_api=no)
+  ])
+  if test $octave_cv_hdf5_has_ver_16_api != yes; then
+    AC_DEFINE(HAVE_HDF5_18, 1, [Define to 1 if >=HDF5-1.8 is available.])
+  fi
+])
+dnl
+dnl Usage:
+dnl OCTAVE_CHECK_LIB(LIBRARY, DOC-NAME, WARN-MSG, HEADER, FUNC,
+dnl                  LANG, DOC-STRING, EXTRA-CHECK)
+dnl
+AC_DEFUN([OCTAVE_CHECK_LIB], [
   AC_ARG_WITH([$1-includedir],
     [AS_HELP_STRING([--with-$1-includedir=DIR],
       [look for $2 include files in DIR])],
@@ -424,36 +360,39 @@
 
   [TEXINFO_]m4_toupper([$1])=
   warn_$1="$3"
+  m4_set_add([summary_warning_list], [warn_$1])
+
   if test -n "$m4_toupper([$1])_LIBS"; then
-    octave_check_library_save_CPPFLAGS="$CPPFLAGS"
+    ac_octave_save_CPPFLAGS="$CPPFLAGS"
+    ac_octave_save_LDFLAGS="$LDFLAGS"
+    ac_octave_save_LIBS="$LIBS"
     CPPFLAGS="$m4_toupper([$1])_CPPFLAGS $CPPFLAGS"
+    LDFLAGS="$m4_toupper([$1])_LDFLAGS $LDFLAGS"
+    LIBS="$m4_toupper([$1])_LIBS $LIBS"
     m4_ifnblank([$6], [AC_LANG_PUSH($6)])
-    octave_$1_check_for_lib=false
-    m4_ifblank([$4], [octave_$1_check_for_lib=true],
-               [AC_CHECK_HEADERS($4, [octave_$1_check_for_lib=true; break])])
-    if $octave_$1_check_for_lib; then
-      octave_check_library_save_LDFLAGS="$LDFLAGS"
-      LDFLAGS="$m4_toupper([$1])_LDFLAGS $LDFLAGS"
-      octave_check_library_save_LIBS="$LIBS"
-      LIBS="$m4_toupper([$1])_LIBS $LIBS"
-      octave_$1_ok=no
-      AC_MSG_CHECKING([for $5 in $m4_toupper([$1])_LIBS])
-      AC_LINK_IFELSE([AC_LANG_CALL([], [$5])],
-	[octave_$1_ok=yes])
-      AC_MSG_RESULT([$octave_$1_ok])
-      if test $octave_$1_ok = yes; then
-	m4_ifblank([$8], [
-	  warn_$1=
-	  AC_DEFINE([HAVE_]m4_toupper([$1]), 1,
-            [Define if $2 is available.])
-	  [TEXINFO_]m4_toupper([$1])="@set [HAVE_]m4_toupper([$1])"], [$8])
+    ac_octave_$1_check_for_lib=no
+    m4_ifblank([$4], [ac_octave_$1_check_for_lib=yes],
+               [AC_CHECK_HEADERS([$4], [ac_octave_$1_check_for_lib=yes; break])])
+    if test $ac_octave_$1_check_for_lib = yes; then
+      AC_CACHE_CHECK([for $5 in $m4_toupper([$1])_LIBS],
+        [octave_cv_lib_$1],
+        [AC_LINK_IFELSE([AC_LANG_CALL([], [$5])],
+          [octave_cv_lib_$1=yes], [octave_cv_lib_$1=no])
+      ])
+      if test "$octave_cv_lib_$1" = yes; then
+        m4_ifblank([$8], [
+          warn_$1=
+          AC_DEFINE([HAVE_]m4_toupper([$1]), 1,
+            [Define to 1 if $2 is available.])
+          [TEXINFO_]m4_toupper([$1])="@set [HAVE_]m4_toupper([$1])"], [$8])
       fi
-      LIBS="$octave_check_library_save_LIBS"
-      LDFLAGS="$octave_check_library_save_LDFLAGS"
     fi
     m4_ifnblank([$6], [AC_LANG_POP($6)])
-    CPPFLAGS="$octave_check_library_save_CPPFLAGS"
+    CPPFLAGS="$ac_octave_save_CPPFLAGS"
+    LDFLAGS="$ac_octave_save_LDFLAGS"
+    LIBS="$ac_octave_save_LIBS"
   fi
+
   AC_SUBST(m4_toupper([$1])_LIBS)
   AC_SUBST([TEXINFO_]m4_toupper([$1]))
   if test -n "$warn_$1"; then
@@ -462,583 +401,18 @@
   fi
 ])
 dnl
-dnl Check for flex
-dnl
-AC_DEFUN([OCTAVE_PROG_FLEX], [
-### For now, don't define LEXLIB to be -lfl -- we don't use anything in
-### it, and it might not be installed.
-###
-### Also make sure that we generate an interactive scanner if we are
-### using flex.
-  AC_PROG_LEX
-  case "$LEX" in
-    flex*)
-      LFLAGS="-I"
-      AC_MSG_RESULT([defining LFLAGS to be $LFLAGS])
-      LEXLIB=
-    ;;
-    *)
-      LEX='$(top_srcdir)/missing flex'
-      warn_flex="I didn't find flex, but it's only a problem if you need to reconstruct lex.cc"
-      AC_MSG_WARN([$warn_flex])
-    ;;
-  esac
-  AC_SUBST(LFLAGS)
-])
-dnl
-dnl Check for bison
-dnl
-AC_DEFUN([OCTAVE_PROG_BISON], [
-  AC_PROG_YACC
-  case "$YACC" in
-    bison*)
-    ;;
-    *)
-      YACC='$(top_srcdir)/missing bison'
-      warn_bison="I didn't find bison, but it's only a problem if you need to reconstruct parse.cc"
-      AC_MSG_WARN([$warn_bison])
-    ;;
-  esac
-])
-dnl
-dnl What pager should we use?
-dnl
-AC_DEFUN([OCTAVE_PROG_PAGER],
-[if test "$cross_compiling" = yes; then
-  DEFAULT_PAGER=less
-  AC_MSG_RESULT([assuming $DEFAULT_PAGER exists on $canonical_host_type host])
-  AC_SUBST(DEFAULT_PAGER)
-else
-  octave_possible_pagers="less more page pg"
-  case "$canonical_host_type" in
-    *-*-cygwin* | *-*-mingw32* | *-*-msdosmsvc)
-      octave_possible_pagers="$octave_possible_pagers more.com"
-    ;;
-  esac
-
-  AC_CHECK_PROGS(DEFAULT_PAGER, $octave_possible_pagers, [])
-  if test -z "$DEFAULT_PAGER"; then
-    warn_less="I couldn't find \`less', \`more', \`page', or \`pg'"
-    AC_MSG_WARN([$warn_less])
-  fi
-fi
-])
-dnl
-dnl Does gnuplot exist?
-dnl
-AC_DEFUN([OCTAVE_PROG_GNUPLOT], [
-gp_names="gnuplot"
-gp_default="gnuplot"
-if test "$cross_compiling" = yes; then
-  GNUPLOT="$gp_default"
-  AC_MSG_RESULT([assuming $GNUPLOT exists on $canonical_host_type host])
-else
-  AC_CHECK_PROGS(GNUPLOT, [$gp_names])
-  if test -z "$GNUPLOT"; then
-    warn_gnuplot=yes
-
-    GNUPLOT="$gp_default"
-
-    AC_MSG_WARN([gnuplot not found.  It isn't necessary to have gnuplot])
-    AC_MSG_WARN([installed, but without native graphics or gnuplot])
-	 AC_MSG_WARN([you won't be able to use any of Octave's plotting commands.])
-  fi
-fi
-AC_SUBST(GNUPLOT)
-])
-dnl
-dnl Is gperf installed?
-dnl
-dnl OCTAVE_PROG_GPERF
-AC_DEFUN([OCTAVE_PROG_GPERF], [
-  AC_CHECK_PROG(GPERF, gperf, gperf, [])
-  if test -z "$GPERF"; then
-    GPERF='$(top_srcdir)/missing gperf'
-    warn_gperf="I didn't find gperf, but it's only a problem if you need to reconstruct oct-gperf.h"
-    AC_MSG_WARN([$warn_gperf])
-  fi
-  AC_SUBST(GPERF)
-])
-dnl
-dnl Is ghostscript installed?
-dnl
-dnl OCTAVE_PROG_GHOSTSCRIPT
-AC_DEFUN([OCTAVE_PROG_GHOSTSCRIPT], [
-  case "$canonical_host_type" in
-    *-*-mingw* | *-*-msdosmsvc)
-      gs_names="gswin32c gs mgs"
-    ;;
-    *)
-      gs_names="gs"
-    ;;
-  esac
-  AC_CHECK_PROGS(GHOSTSCRIPT, [$gs_names])
-  if test -z "$GHOSTSCRIPT"; then
-    GHOSTSCRIPT='$(top_srcdir)/missing gs'
-    warn_ghostscript="I didn't find ghostscript, so reconstructing figures for the manual will fail, and saving graphics in some output formats will fail when using Octave"
-    AC_MSG_WARN([$warn_ghostscript])
-  fi
-  AC_SUBST(GHOSTSCRIPT)
-])
-dnl
-dnl Is texi2dvi installed?
-dnl
-dnl OCTAVE_PROG_TEXI2DVI
-AC_DEFUN([OCTAVE_PROG_TEXI2DVI], [
-  AC_CHECK_PROG(TEXI2DVI, texi2dvi, texi2dvi, [])
-  if test -z "$TEXI2DVI"; then
-    TEXI2DVI='$(top_srcdir)/missing texi2dvi'
-    warn_texi2dvi="I didn't find texi2dvi, but it's only a problem if you need to reconstruct the DVI version of the manual"
-    AC_MSG_WARN([$warn_texi2dvi])
-  fi
-  AC_SUBST(TEXI2DVI)
-])
-dnl
-dnl Is texi2pdf installed?
-dnl
-dnl OCTAVE_PROG_TEXI2PDF
-AC_DEFUN([OCTAVE_PROG_TEXI2PDF], [
-  AC_REQUIRE([OCTAVE_PROG_TEXI2DVI])
-  AC_CHECK_PROG(TEXI2PDF, texi2pdf, texi2pdf, [])
-  if test -z "$TEXI2PDF"; then
-    missing=true;
-    if test -n "$TEXI2DVI"; then
-      TEXI2PDF="$TEXI2DVI --pdf"
-      missing=false;
-    fi
-  else
-    missing=false;
-  fi
-  if $missing; then
-    TEXI2PDF='$(top_srcdir)/missing texi2pdf'
-    warn_texi2pdf="I didn't find texi2pdf, but it's only a problem if you need to reconstruct the PDF version of the manual"
-    AC_MSG_WARN([$warn_texi2pdf])
-  fi
-  AC_SUBST(TEXI2PDF)
-])
-dnl
-dnl See if the C++ library is ISO compliant.
-dnl FIXME: This is obviously very simplistic, and trivially fooled.
-dnl
-dnl OCTAVE_CXX_ISO_COMPLIANT_LIBRARY
-AC_DEFUN([OCTAVE_CXX_ISO_COMPLIANT_LIBRARY], [
-  AC_REQUIRE([AC_PROG_CXX])
-  AC_MSG_CHECKING([if C++ library is ISO compliant])
-  AC_CACHE_VAL(octave_cv_cxx_iso_compliant_library, [
-    AC_LANG_PUSH(C++)
-    rm -f conftest.h
-### Omitting cwctype for now, since it is broken with gcc-3.0.x and
-### possibly other versions...
-    for inc in algorithm bitset cassert cctype cerrno cfloat ciso646 \
-	climits clocale cmath complex csetjmp csignal cstdarg cstddef \
-	cstdio cstdlib cstring ctime cwchar deque exception \
-	fstream functional iomanip ios iosfwd iostream istream iterator \
-	limits list locale map memory new numeric ostream queue set \
-	sstream stack stdexcept streambuf string strstream typeinfo \
-	utility valarray vector; do
-      echo "#include <$inc>" >> conftest.h
-    done
-    AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include "conftest.h"]],
-      [[std::bitset<50> flags;
-        flags.set();
-        int digits = std::numeric_limits<unsigned long>::digits;
-        digits = 0;]])],
-      [octave_cv_cxx_iso_compliant_library=yes],
-      [octave_cv_cxx_iso_compliant_library=no])
-    AC_LANG_POP(C++)
-  ])
-  AC_MSG_RESULT([$octave_cv_cxx_iso_compliant_library])
-  if test $octave_cv_cxx_iso_compliant_library = yes; then
-    AC_DEFINE(CXX_ISO_COMPLIANT_LIBRARY, 1, [Define if your C++ runtime library is ISO compliant.])
-  fi
-])
-dnl
-dnl Allow the user disable support for command line editing using GNU
-dnl readline.
-dnl
-dnl OCTAVE_ENABLE_READLINE
-AC_DEFUN([OCTAVE_ENABLE_READLINE], [
-  USE_READLINE=true
-  READLINE_LIBS=
-  AC_ARG_ENABLE(readline,
-    [  --enable-readline       use readline library (default is yes)],
-    [if test "$enableval" = no; then
-       USE_READLINE=false
-       warn_readline="command editing and history features require GNU Readline"
-     fi])
-  if $USE_READLINE; then
-    save_LIBS="$LIBS"
-    LIBS="$TERM_LIBS"
-    AC_CHECK_LIB(readline, rl_set_keyboard_input_timeout, [
-      READLINE_LIBS="-lreadline"
-      AC_DEFINE(USE_READLINE, 1, [Define to use the readline library.])
-    ], [
-      AC_MSG_WARN([I need GNU Readline 4.2 or later])
-      AC_MSG_ERROR([this is fatal unless you specify --disable-readline])
-    ])
-    LIBS="$save_LIBS"
-  fi
-  AC_SUBST(READLINE_LIBS)
-])
-dnl
-dnl Check to see if C++ reintrepret cast works for function pointers.
-dnl
-dnl OCTAVE_CXX_BROKEN_REINTERPRET_CAST
-dnl
-AC_DEFUN([OCTAVE_CXX_BROKEN_REINTERPRET_CAST], [
-  AC_REQUIRE([AC_PROG_CXX])
-  AC_LANG_PUSH(C++)
-  AC_CACHE_CHECK([for broken C++ reinterpret_cast],
-    octave_cv_cxx_broken_reinterpret_cast, [
-    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include <cmath>]], [[
-      typedef double (*fptr) (double);
-      fptr psin = sin;
-      void *vptr = reinterpret_cast<void *> (psin);
-      psin = reinterpret_cast<fptr> (vptr);]])],
-      octave_cv_cxx_broken_reinterpret_cast=no,
-      octave_cv_cxx_broken_reinterpret_cast=yes)])
-  if test $octave_cv_cxx_broken_reinterpret_cast = yes ; then
-    AC_DEFINE(CXX_BROKEN_REINTERPRET_CAST, 1, [Define if C++ reinterpret_cast fails for function pointers.])
-fi
-  AC_LANG_POP(C++)])
-dnl
-dnl Find find.
-dnl
-# Prefer GNU find if found.
-AN_MAKEVAR([FIND],  [OCTAVE_PROG_FIND])
-AN_PROGRAM([gfind], [OCTAVE_PROG_FIND])
-AN_PROGRAM([find],  [OCTAVE_PROG_FIND])
-AC_DEFUN([OCTAVE_PROG_FIND],
-[AC_CHECK_PROGS(FIND, gfind find, )])
-dnl
-dnl Find sed.
-dnl
-# Check for a fully-functional sed program, that truncates
-# as few characters as possible and that supports "\(X\|Y\)"
-# style regular expression alternation.  Prefer GNU sed if found.
-AC_DEFUN([OCTAVE_PROG_SED],
-[AC_MSG_CHECKING([for a usable sed])
-if test -z "$SED"; then
-  AC_CACHE_VAL(ac_cv_path_sed, [
-  # Loop through the user's path and test for sed and gsed.
-  # Then use that list of sed's as ones to test for truncation.
-  _AS_PATH_WALK([$PATH],
-    [for ac_prog in sed gsed; do
-      for ac_exec_ext in '' $ac_executable_extensions; do
-	if AS_EXECUTABLE_P(["$as_dir/$ac_prog$ac_exec_ext"]); then
-	  _sed_list="$_sed_list $as_dir/$ac_prog$ac_exec_ext"
-	fi
-      done
-    done
-    ])
-    AS_TMPDIR(sed)
-    _max=0
-    _count=0
-    # Add /usr/xpg4/bin/sed as it is typically found on Solaris
-    # along with /bin/sed that truncates output.
-    for _sed in $_sed_list /usr/xpg4/bin/sed; do
-      test ! -f ${_sed} && break
-      cat /dev/null > "$tmp/sed.in"
-      _count=0
-      echo $ECHO_N "0123456789$ECHO_C" >"$tmp/sed.in"
-      # Check for GNU sed and select it if it is found.
-      if "${_sed}" --version 2>&1 < /dev/null | egrep '(GNU)' > /dev/null; then
-	octave_cv_path_sed=${_sed}
-	break;
-      fi
-      # Reject if RE alternation is not handled.
-      if test "`echo 'this and that' | ${_sed} -n 's/\(this\|that\).*$/\1/p'`" != "this"; then
-        continue;
-      fi
-      while true; do
-	cat "$tmp/sed.in" "$tmp/sed.in" >"$tmp/sed.tmp"
-	mv "$tmp/sed.tmp" "$tmp/sed.in"
-	cp "$tmp/sed.in" "$tmp/sed.nl"
-	echo >>"$tmp/sed.nl"
-	${_sed} -e 's/a$//' < "$tmp/sed.nl" >"$tmp/sed.out" || break
-	cmp -s "$tmp/sed.out" "$tmp/sed.nl" || break
-	# 10000 chars as input seems more than enough
-	test $_count -gt 10 && break
-	_count=`expr $_count + 1`
-	if test $_count -gt $_max; then
-	  _max=$_count
-	  octave_cv_path_sed=$_sed
-	fi
-      done
-    done
-    rm -rf "$tmp"
-  ])
-  SED=$octave_cv_path_sed
-  if test -z "$SED"; then
-    AC_MSG_ERROR([no usable version of sed found])
-  fi
-fi
-AC_SUBST(SED)
-AC_MSG_RESULT([$SED])
-])
-dnl
-dnl Find Perl.
-dnl
-dnl OCTAVE_PROG_PERL
-AC_DEFUN([OCTAVE_PROG_PERL],
-[AC_CHECK_PROG(PERL, perl, perl, [])
-  AC_SUBST(PERL)
-])
-dnl
-dnl Find Python.
-dnl
-dnl OCTAVE_PROG_PYTHON
-AC_DEFUN([OCTAVE_PROG_PYTHON],
-[AC_CHECK_PROG(PYTHON, python, python, [])
-  AC_SUBST(PYTHON)
-])
-dnl
-dnl Find desktop-file-install.
-dnl
-dnl OCTAVE_PROG_DESKTOP_FILE_INSTALL
-AC_DEFUN([OCTAVE_PROG_DESKTOP_FILE_INSTALL],
-[AC_CHECK_PROG(DESKTOP_FILE_INSTALL, desktop-file-install, desktop-file-install, [])
-  AC_SUBST(DESKTOP_FILE_INSTALL)
-])
-dnl
-dnl Check for IEEE 754 data format.
-dnl
-AC_DEFUN([OCTAVE_IEEE754_DATA_FORMAT],
-[AC_MSG_CHECKING([for IEEE 754 data format])
-AC_CACHE_VAL(octave_cv_ieee754_data_format,
-[AC_RUN_IFELSE([AC_LANG_SOURCE([[
-int
-main (void) 
-{
-  typedef union { unsigned char c[8]; double d; } ieeebytes;
-   
-  ieeebytes l = {0x1c, 0xbc, 0x6e, 0xf2, 0x54, 0x8b, 0x11, 0x43};
-  ieeebytes b = {0x43, 0x11, 0x8b, 0x54, 0xf2, 0x6e, 0xbc, 0x1c};
-
-  return l.d != 1234567891234567.0 && b.d != 1234567891234567.0;
-}]])],
-  octave_cv_ieee754_data_format=yes,
-  octave_cv_ieee754_data_format=no,
-  octave_cv_ieee754_data_format=yes)])
-if test "$cross_compiling" = yes; then
-  AC_MSG_RESULT([$octave_cv_ieee754_data_format assumed for cross compilation])
-else
-  AC_MSG_RESULT([$octave_cv_ieee754_data_format])
-fi
-if test "$octave_cv_ieee754_data_format" = yes; then
-  AC_DEFINE(HAVE_IEEE754_DATA_FORMAT, 1, [Define if your system uses IEEE 754 data format.])
-else
-  ## If the format is unknown, then you will probably not have a
-  ## useful system, so we will abort here.  Anyone wishing to
-  ## experiment with building Octave on a system without IEEE
-  ## floating point should be capable of removing this check and
-  ## the one in the octave_ieee_init function in liboctave/lo-ieee.cc.
-  AC_MSG_ERROR([IEEE 754 data format required for building Octave])
-fi
-])
-dnl
-dnl Check for UMFPACK seperately split complex matrix and RHS. Note
-dnl that as umfpack.h can be in three different places, rather than
-dnl include it, just declare the functions needed.
-dnl
-dnl Assumes that the check for umfpack has already been performed.
-dnl
-AC_DEFUN([OCTAVE_UMFPACK_SEPERATE_SPLIT],
-[AC_MSG_CHECKING([for UMFPACK seperate complex matrix and rhs split])
-AC_CACHE_VAL(octave_cv_umfpack_seperate_split,
-[AC_RUN_IFELSE([AC_LANG_SOURCE([[
-#include <stdlib.h>
-#if defined (HAVE_UFSPARSE_UMFPACK_h)
-#include <ufsparse/umfpack.h>
-#elif defined (HAVE_UMFPACK_UMFPACK_H)
-#include <umfpack/umfpack.h>
-#elif defined (HAVE_UMFPACK_H)
-#include <umfpack.h>
-#endif
-int n = 5;
-int Ap[] = {0, 2, 5, 9, 10, 12};
-int Ai[]  = {0, 1, 0, 2, 4, 1, 2, 3, 4, 2, 1, 4};
-double Ax[] = {2., 0., 3., 0., 3., 0., -1., 0., 4., 0., 4., 0., 
-	      -3., 0., 1., 0., 2., 0., 2., 0., 6., 0., 1., 0.};
-double br[] = {8., 45., -3., 3., 19.};
-double bi[] = {0., 0., 0., 0., 0.};
-int main (void)
-{
-  double *null = (double *) NULL ;
-  double *x = (double *)malloc (2 * n * sizeof(double));
-  int i ;
-  void *Symbolic, *Numeric ;
-  (void) umfpack_zi_symbolic (n, n, Ap, Ai, Ax, null, &Symbolic, null, null) ;
-  (void) umfpack_zi_numeric (Ap, Ai, Ax, null, Symbolic, &Numeric, null, null) ;
-  umfpack_zi_free_symbolic (&Symbolic) ;
-  (void) umfpack_zi_solve (0, Ap, Ai, Ax, null, x, null, br, bi, 
-		Numeric, null, null) ;
-  umfpack_zi_free_numeric (&Numeric) ;
-  for (i = 0; i < n; i++, x+=2) 
-    if (fabs(*x - i - 1.) > 1.e-13)
-      return (1);
-  return (0) ;
-}
-]])],
-  octave_cv_umfpack_seperate_split=yes,
-  octave_cv_umfpack_seperate_split=no,
-  octave_cv_umfpack_seperate_split=yes)])
-if test "$cross_compiling" = yes; then
-  AC_MSG_RESULT([$octave_cv_umfpack_seperate_split assumed for cross compilation])
-else
-  AC_MSG_RESULT([$octave_cv_umfpack_seperate_split])
-fi
-if test "$octave_cv_umfpack_seperate_split" = yes; then
-  AC_DEFINE(UMFPACK_SEPARATE_SPLIT, 1, [Define if the UMFPACK Complex solver allow matrix and RHS to be split independently])
-fi
-])
-dnl
-dnl Check whether using HDF5 DLL under Windows. This is done by
-dnl testing for a data symbol in the HDF5 library, which would
-dnl requires the definition of _HDF5USEDL_ under MSVC compiler.
-dnl
-AC_DEFUN([OCTAVE_HDF5_DLL], [
-  AC_CACHE_CHECK([if _HDF5USEDLL_ needs to be defined],octave_cv_hdf5_dll, [
-    AC_TRY_LINK([#include <hdf5.h>], [hid_t x = H5T_NATIVE_DOUBLE; return x],
-      octave_cv_hdf5_dll=no, [
-      save_CFLAGS="$CFLAGS"
-      CFLAGS="$CFLAGS -DWIN32 -D_HDF5USEDLL_"
-      save_LIBS="$LIBS"
-      LIBS="$HDF5_LIBS $LIBS"
-      AC_TRY_LINK([#include <hdf5.h>], [hid_t x = H5T_NATIVE_DOUBLE; return x],
-        octave_cv_hdf5_dll=yes,
-	octave_cv_hdf5_dll=no)
-      CFLAGS="$save_CFLAGS"
-      LIBS="$save_LIBS"])])
-  if test "$octave_cv_hdf5_dll" = yes; then
-    AC_DEFINE(_HDF5USEDLL_, 1, [Define if using HDF5 dll (Win32)])
-  fi])
-dnl
-dnl Check whether HDF5 library has version 1.6 API functions.
-dnl
-AC_DEFUN([OCTAVE_HDF5_HAS_ENFORCED_16_API], [
-  AC_CACHE_CHECK([whether HDF5 library has enforced version 1.6 API],
-    octave_cv_hdf5_has_enforced_16_api, [
-    AC_TRY_LINK([
-#include <hdf5.h>
-], [
-  H5Eset_auto (0, 0);], [
-      octave_cv_hdf5_has_enforced_16_api=yes], [
-      octave_cv_hdf5_has_enforced_16_api=no])])
-  if test "$octave_cv_hdf5_has_enforced_16_api" != "yes"; then
-    AC_DEFINE(HAVE_HDF5_18, 1, [Define if >=HDF5-1.8 is available.])
-  fi
-])
-dnl
-dnl Check for the QHull version.
-dnl
-AC_DEFUN([OCTAVE_CHECK_QHULL_VERSION],
-  [AC_CACHE_CHECK([for qh_version in $QHULL_LIBS],
-    octave_cv_lib_qhull_version,  [
-      AC_LINK_IFELSE([AC_LANG_PROGRAM([[
-#include <stdio.h>
-#if defined (HAVE_LIBQHULL_LIBQHULL_H)
-# include <libqhull/libqhull.h>
-# include <libqhull/qset.h>
-# include <libqhull/geom.h>
-# include <libqhull/poly.h>
-# include <libqhull/io.h>
-#elif defined (HAVE_QHULL_LIBQHULL_H) || defined (HAVE_QHULL_QHULL_H)
-# if defined (HAVE_QHULL_LIBQHULL_H)
-#  include <qhull/libqhull.h>
-# else
-#  include <qhull/qhull.h>
-# endif
-# include <qhull/qset.h>
-# include <qhull/geom.h>
-# include <qhull/poly.h>
-# include <qhull/io.h>
-#elif defined (HAVE_LIBQHULL_H) || defined (HAVE_QHULL_H)
-# if defined (HAVE_LIBQHULL_H)
-#  include <libqhull.h>
-# else
-#  include <qhull.h>
-# endif
-# include <qset.h>
-# include <geom.h>
-# include <poly.h>
-# include <io.h>
-#endif
-]], [[
-const char *tmp = qh_version;
-]])], [octave_cv_lib_qhull_version=yes], [octave_cv_lib_qhull_version=no])])
-  if test "$octave_cv_lib_qhull_version" = no; then
-    AC_DEFINE(NEED_QHULL_VERSION, 1,
-      [Define if the QHull library needs a qh_version variable defined.])
-  fi
-])
-dnl
-dnl Check whether QHull works (does not crash)
-dnl
-AC_DEFUN([OCTAVE_CHECK_QHULL_OK],
-  [AC_CACHE_CHECK([whether the qhull library works],
-    octave_cv_lib_qhull_ok, [
-      AC_RUN_IFELSE([AC_LANG_PROGRAM([[
-#include <stdio.h>
-#if defined (HAVE_LIBQHULL_LIBQHULL_H)
-# include <libqhull/libqhull.h>
-# include <libqhull/qset.h>
-# include <libqhull/geom.h>
-# include <libqhull/poly.h>
-# include <libqhull/io.h>
-#elif defined (HAVE_QHULL_LIBQHULL_H) || defined (HAVE_QHULL_QHULL_H)
-# if defined (HAVE_QHULL_LIBQHULL_H)
-#  include <qhull/libqhull.h>
-# else
-#  include <qhull/qhull.h>
-# endif
-# include <qhull/qset.h>
-# include <qhull/geom.h>
-# include <qhull/poly.h>
-# include <qhull/io.h>
-#elif defined (HAVE_LIBQHULL_H) || defined (HAVE_QHULL_H)
-# if defined (HAVE_LIBQHULL_H)
-#  include <libqhull.h>
-# else
-#  include <qhull.h>
-# endif
-# include <qset.h>
-# include <geom.h>
-# include <poly.h>
-# include <io.h>
-#endif
-#ifdef NEED_QHULL_VERSION
-char *qh_version = "version";
-#endif
-]], [[
-int dim = 2;
-int n = 4;
-coordT points[8] = { -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5 };
-boolT ismalloc = 0;
-return qh_new_qhull (dim, n, points, ismalloc, "qhull ", 0, stderr); 
-]])],
-  [octave_cv_lib_qhull_ok=yes],
-  [octave_cv_lib_qhull_ok=no],
-  [octave_cv_lib_qhull_ok=yes])])
-  if test "$octave_cv_lib_qhull_ok" = "yes"; then
-    $1
-  else
-    $2
-  fi
-])
-dnl
-dnl Check whether ARPACK works (does not crash)
+dnl Check whether ARPACK works (does not crash).
 dnl
 dnl Using a pure Fortran program doesn't seem to crash when linked
-dnl with the buggy ARPACK library but the C++ program does.  Maybe
-dnl it is the memory allocation that exposes the bug and using statically
+dnl with the buggy ARPACK library but the C++ program does.  Maybe it
+dnl is the memory allocation that exposes the bug and using statically
 dnl allocated arrays in Fortran does not?
 dnl
-AC_DEFUN([OCTAVE_CHECK_ARPACK_OK], [
-  AC_LANG_PUSH(C++)
+AC_DEFUN([OCTAVE_CHECK_LIB_ARPACK_OK], [
   AC_CACHE_CHECK([whether the arpack library works],
-    [octave_cv_lib_arpack_ok], [
-      AC_RUN_IFELSE([AC_LANG_PROGRAM([[
+    [octave_cv_lib_arpack_ok],
+    [AC_LANG_PUSH(C++)
+    AC_RUN_IFELSE([AC_LANG_PROGRAM([[
 // External functions from ARPACK library
 extern "C" int
 F77_FUNC (dnaupd, DNAUPD) (int&, const char *, const int&, const char *,
@@ -1154,7 +528,7 @@
   double sigmar = 0.0;
   double sigmai = 0.0;
 
-  // In Octave, this is n*(k+1), but k+2 avoids segfault
+  // In Octave, this is n*(k+1), but n*(k+2) avoids segfault
   double *z = new double [n * (k + 1)];
 
   F77_FUNC (dneupd, DNEUPD) (rvec, "A", sel, dr, di, z, n, sigmar,
@@ -1162,185 +536,683 @@
                              resid, p, v, n, ip, ipntr, workd,
                              workl, lwork, info, 1L, 1L, 2L);
 }
+
 ]], [[
+
   for (int i = 0; i < 10; i++)
     doit ();
-]])],
-  [octave_cv_lib_arpack_ok=yes],
-  [octave_cv_lib_arpack_ok=no],
-  [octave_cv_lib_arpack_ok=yes])])
-  AC_LANG_POP(C++)
-  if test "$octave_cv_lib_arpack_ok" = "yes"; then
+    ]])],
+    octave_cv_lib_arpack_ok=yes,
+    octave_cv_lib_arpack_ok=no,
+    octave_cv_lib_arpack_ok=yes)
+    AC_LANG_POP(C++)
+  ])
+  if test $octave_cv_lib_arpack_ok = yes; then
     $1
+    :
   else
     $2
+    :
   fi
 ])
 dnl
-dnl Check for OpenGL.  If found, define OPENGL_LIBS
+dnl Check whether using HDF5 DLL under Windows.  This is done by
+dnl testing for a data symbol in the HDF5 library, which would
+dnl require the definition of _HDF5USEDL_ under MSVC compiler.
 dnl
-dnl FIXME -- the following tests should probably check for the
+AC_DEFUN([OCTAVE_CHECK_LIB_HDF5_DLL], [
+  AC_CACHE_CHECK([if _HDF5USEDLL_ needs to be defined],
+    [octave_cv_lib_hdf5_dll],
+    [AC_LINK_IFELSE([AC_LANG_PROGRAM([[
+        #include <hdf5.h>
+        ]], [[
+        hid_t x = H5T_NATIVE_DOUBLE;
+        return x
+      ]])],
+      [octave_cv_lib_hdf5_dll=no],
+      [save_CFLAGS="$CFLAGS"
+      CFLAGS="$CFLAGS -DWIN32 -D_HDF5USEDLL_"
+      save_LIBS="$LIBS"
+      LIBS="$HDF5_LIBS $LIBS"
+      AC_LINK_IFELSE([AC_LANG_PROGRAM([[
+          #include <hdf5.h>
+          ]], [[
+          hid_t x = H5T_NATIVE_DOUBLE;
+          return x
+        ]])],
+        octave_cv_lib_hdf5_dll=yes,
+        octave_cv_lib_hdf5_dll=no)
+      CFLAGS="$save_CFLAGS"
+      LIBS="$save_LIBS"
+    ])
+  ])
+  if test $octave_cv_lib_hdf5_dll = yes; then
+    AC_DEFINE(_HDF5USEDLL_, 1, [Define to 1 if using HDF5 dll (Win32).])
+  fi
+])
+dnl
+dnl Check for OpenGL.  If found, define OPENGL_LIBS.
+dnl
+dnl FIXME: The following tests should probably check for the
 dnl libraries separately.
 dnl
-dnl FIXME -- should we allow a way to specify a directory for OpenGL
+dnl FIXME: Should we allow a way to specify a directory for OpenGL
 dnl libraries and header files?
 dnl
-AC_DEFUN([OCTAVE_OPENGL], [
-OPENGL_LIBS=
+AC_DEFUN([OCTAVE_CHECK_LIB_OPENGL], [
+  OPENGL_LIBS=
 
-### On MacOSX systems the OpenGL framework can be used
-OCTAVE_HAVE_FRAMEWORK(OpenGL, [
-#include <OpenGL/gl.h>
-#include <OpenGL/glu.h> ], [GLint par; glGetIntegerv (GL_VIEWPORT, &par);],
-  [have_framework_opengl="yes"], [have_framework_opengl="no"])
+  ## On MacOSX systems the OpenGL framework can be used
+  OCTAVE_HAVE_FRAMEWORK(OpenGL, [[
+    #include <OpenGL/gl.h>
+    #include <OpenGL/glu.h>
+    ]], [[
+    GLint par; glGetIntegerv (GL_VIEWPORT, &par);
+    ]],
+    have_framework_opengl=yes, have_framework_opengl=no)
 
-if test $have_framework_opengl = "yes"; then
-  AC_DEFINE(HAVE_FRAMEWORK_OPENGL, 1, [Define if framework OPENGL is available.])
-  OPENGL_LIBS="-Wl,-framework -Wl,OpenGL"
-  AC_MSG_NOTICE([adding -Wl,-framework -Wl,OpenGL to OPENGL_LIBS])
-  OCTAVE_GLUTESSCALLBACK_THREEDOTS
-else
-  case $canonical_host_type in
-    *-*-mingw32* | *-*-msdosmsvc)
-      AC_CHECK_HEADERS(windows.h)
-    ;;
-  esac
-  have_opengl_incs=no
-  AC_CHECK_HEADERS([GL/gl.h OpenGL/gl.h], [
-    AC_CHECK_HEADERS([GL/glu.h OpenGL/glu.h], [
-      have_opengl_incs=yes; break], [], [
+  if test $have_framework_opengl = yes; then
+    AC_DEFINE(HAVE_FRAMEWORK_OPENGL, 1,
+      [Define to 1 if framework OPENGL is available.])
+    OPENGL_LIBS="-Wl,-framework -Wl,OpenGL"
+    AC_MSG_NOTICE([adding -Wl,-framework -Wl,OpenGL to OPENGL_LIBS])
+    OCTAVE_CHECK_FUNC_GLUTESSCALLBACK_THREEDOTS
+  else
+    case $canonical_host_type in
+      *-*-mingw32* | *-*-msdosmsvc)
+        AC_CHECK_HEADERS([windows.h])
+      ;;
+    esac
+    have_opengl_incs=no
+    AC_CHECK_HEADERS([GL/gl.h OpenGL/gl.h],
+      [AC_CHECK_HEADERS([GL/glu.h OpenGL/glu.h],
+        [have_opengl_incs=yes; break], [], [
 #ifdef HAVE_WINDOWS_H
 #include <windows.h>
 #endif
-    ])
-    break
-    ], [], [
+      ])
+      break
+      ], [], [
 #ifdef HAVE_WINDOWS_H
-#include <windows.h>
+# include <windows.h>
 #endif
     ])
 
-  if test "$have_opengl_incs" = "yes"; then
-    case $canonical_host_type in
-      *-*-mingw32* | *-*-msdosmsvc)
-        save_LIBS="$LIBS"
-        LIBS="$LIBS -lopengl32"
-        AC_MSG_CHECKING([for glEnable in -lopengl32])
-        AC_TRY_LINK([
-#if HAVE_WINDOWS_H
-#include <windows.h>
-#endif
-#if defined (HAVE_GL_GL_H)
-#include <GL/gl.h>
-#elif defined (HAVE_OPENGL_GL_H)
-#include <OpenGL/gl.h>
-#endif
-], [glEnable(GL_SMOOTH);], OPENGL_LIBS="-lopengl32 -lglu32")
-        LIBS="$save_LIBS"
-        if test "x$OPENGL_LIBS" != "x"; then
-          AC_MSG_RESULT(yes)
-        else
-          AC_MSG_RESULT(no)
-        fi
-        ;;
-      *)
-        AC_CHECK_LIB(GL, glEnable, OPENGL_LIBS="-lGL -lGLU")
-        ;;
-    esac
+    if test "$have_opengl_incs" = yes; then
+      case $canonical_host_type in
+        *-*-mingw32* | *-*-msdosmsvc)
+          save_LIBS="$LIBS"
+          LIBS="$LIBS -lopengl32"
+          AC_MSG_CHECKING([for glEnable in -lopengl32])
+          AC_LINK_IFELSE([AC_LANG_PROGRAM([[
+            #if HAVE_WINDOWS_H
+            # include <windows.h>
+            #endif
+            #if defined (HAVE_GL_GL_H)
+            # include <GL/gl.h>
+            #elif defined (HAVE_OPENGL_GL_H)
+            # include <OpenGL/gl.h>
+            #endif
+            ]], [[ 
+            glEnable(GL_SMOOTH);
+            ]])], [OPENGL_LIBS="-lopengl32 -lglu32"])
+
+          LIBS="$save_LIBS"
+          if test "x$OPENGL_LIBS" != "x"; then
+            AC_MSG_RESULT([yes])
+          else
+            AC_MSG_RESULT([no])
+          fi
+          ;;
+        *)
+          ## Non-Mac, Non-Windows systems use this check
+          AC_CHECK_LIB([GL], [glEnable], [OPENGL_LIBS="-lGL -lGLU"])
+          ;;
+      esac
+    fi
   fi
-fi
-AC_SUBST(OPENGL_LIBS)
+  AC_SUBST(OPENGL_LIBS)
+])
+dnl
+dnl Check whether Qhull works (does not crash).
+dnl
+AC_DEFUN([OCTAVE_CHECK_LIB_QHULL_OK], [
+  AC_CACHE_CHECK([whether the qhull library works],
+    [octave_cv_lib_qhull_ok],
+    [AC_RUN_IFELSE([AC_LANG_PROGRAM([[
+        #include <stdio.h>
+        #if defined (HAVE_LIBQHULL_LIBQHULL_H)
+        # include <libqhull/libqhull.h>
+        # include <libqhull/qset.h>
+        # include <libqhull/geom.h>
+        # include <libqhull/poly.h>
+        # include <libqhull/io.h>
+        #elif defined (HAVE_QHULL_LIBQHULL_H) || defined (HAVE_QHULL_QHULL_H)
+        # if defined (HAVE_QHULL_LIBQHULL_H)
+        #  include <qhull/libqhull.h>
+        # else
+        #  include <qhull/qhull.h>
+        # endif
+        # include <qhull/qset.h>
+        # include <qhull/geom.h>
+        # include <qhull/poly.h>
+        # include <qhull/io.h>
+        #elif defined (HAVE_LIBQHULL_H) || defined (HAVE_QHULL_H)
+        # if defined (HAVE_LIBQHULL_H)
+        #  include <libqhull.h>
+        # else
+        #  include <qhull.h>
+        # endif
+        # include <qset.h>
+        # include <geom.h>
+        # include <poly.h>
+        # include <io.h>
+        #endif
+        #ifdef NEED_QHULL_VERSION
+          char *qh_version = "version";
+        #endif
+        ]], [[
+        int dim = 2;
+        int n = 4;
+        coordT points[8] = { -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5 };
+        boolT ismalloc = 0;
+        return qh_new_qhull (dim, n, points, ismalloc, "qhull ", 0, stderr); 
+      ]])],
+      octave_cv_lib_qhull_ok=yes,
+      octave_cv_lib_qhull_ok=no,
+      octave_cv_lib_qhull_ok=yes)
+  ])
+  if test $octave_cv_lib_qhull_ok = yes; then
+    $1
+    :
+  else
+    $2
+    :
+  fi
+])
+dnl
+dnl Find a suitable termlib to use.
+dnl
+AC_DEFUN([OCTAVE_CHECK_LIB_TERMLIB], [
+  TERM_LIBS=
+  ac_octave_save_LIBS="$LIBS"
+  AC_SEARCH_LIBS([tputs],
+                 [ncurses curses termcap terminfo termlib],
+                 [], [])
+  LIBS="$ac_octave_save_LIBS"
+  case "$ac_cv_search_tputs" in
+    -l*)  
+      TERM_LIBS="$ac_cv_search_tputs"
+    ;;
+    no)
+      warn_termlibs="I couldn't find -ltermcap, -lterminfo, -lncurses, -lcurses, or -ltermlib!"
+      AC_MSG_WARN([$warn_termlibs])
+    ;;
+  esac
+
+dnl  Old code (9/9/2012).  Delete when new code is definitely proven.
+dnl
+dnl  for _termlib in ncurses curses termcap terminfo termlib; do
+dnl    AC_CHECK_LIB([${_termlib}], [tputs], [
+dnl      TERM_LIBS="-l${termlib}"
+dnl      octave_cv_lib_found_termlib=yes
+dnl      break])
+dnl  done
+
+  AC_SUBST(TERM_LIBS)
 ])
 dnl
-dnl See if function gluTessCallback is called with "(...)"
+dnl Check for support of OpenMP with a given compiler flag.
+dnl If found define HAVE_OPENMP and add the compile flag
+dnl to CFLAGS and CXXFLAGS.
+dnl
+AC_DEFUN([OCTAVE_CHECK_OPENMP], [
+  AC_MSG_CHECKING([for support of OpenMP])
+  ac_octave_save_CFLAGS="$CFLAGS"
+  CFLAGS="$CFLAGS $1"
+  AC_CACHE_VAL([octave_cv_check_openmp],
+    [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+        #include <omp.h>
+        #include <stdio.h>
+        ]], [[
+        int main(int argc, char* argv[])
+        {
+          _Pragma("omp parallel")  
+          printf("Hello, world.\n");
+          return 0;
+        }
+      ]])],
+      octave_cv_openmp=yes, octave_cv_openmmp=no, octave_cv_openmp=no)
+  ])
+  AC_MSG_RESULT([$octave_cv_openmp])
+  if test $octave_cv_openmp = yes; then
+    AC_DEFINE(HAVE_OPENMP, 1, [Define to 1 if compiler supports OpenMP.])
+    CXXFLAGS="$CXXFLAGS $1"
+  else
+    CFLAGS="$ac_octave_save_CFLAGS"
+  fi
+])
+dnl
+dnl Check for the Qhull version.
 dnl
-dnl OCTAVE_GLUTESSCALLBACK_THREEDOTS
-AC_DEFUN([OCTAVE_GLUTESSCALLBACK_THREEDOTS],
-[AC_CACHE_CHECK([whether gluTessCallback is called with "(...)"],
-octave_cv_glutesscallback_threedots,
-[AC_LANG_PUSH(C++)
-AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
-#ifdef HAVE_GL_GLU_H
-#include <GL/glu.h>
-#elif defined HAVE_OPENGL_GLU_H || defined HAVE_FRAMEWORK_OPENGL
-#include <OpenGL/glu.h>
-#endif]],
-[[GLvoid (*func)(...); gluTessCallback(0, 0, func);]])],
-octave_cv_glutesscallback_threedots="yes", octave_cv_glutesscallback_threedots="no")])
-AC_LANG_POP(C++)
-if test $octave_cv_glutesscallback_threedots = "yes"; then
-  AC_DEFINE(HAVE_GLUTESSCALLBACK_THREEDOTS, 1, 
-    [Define if gluTessCallback is called with (...)])
-fi
+AC_DEFUN([OCTAVE_CHECK_QHULL_VERSION], [
+  AC_CACHE_CHECK([for qh_version in $QHULL_LIBS],
+    [octave_cv_lib_qhull_version],
+    [AC_LINK_IFELSE([AC_LANG_PROGRAM([[
+        #include <stdio.h>
+        #if defined (HAVE_LIBQHULL_LIBQHULL_H)
+        # include <libqhull/libqhull.h>
+        # include <libqhull/qset.h>
+        # include <libqhull/geom.h>
+        # include <libqhull/poly.h>
+        # include <libqhull/io.h>
+        #elif defined (HAVE_QHULL_LIBQHULL_H) || defined (HAVE_QHULL_QHULL_H)
+        # if defined (HAVE_QHULL_LIBQHULL_H)
+        #  include <qhull/libqhull.h>
+        # else
+        #  include <qhull/qhull.h>
+        # endif
+        # include <qhull/qset.h>
+        # include <qhull/geom.h>
+        # include <qhull/poly.h>
+        # include <qhull/io.h>
+        #elif defined (HAVE_LIBQHULL_H) || defined (HAVE_QHULL_H)
+        # if defined (HAVE_LIBQHULL_H)
+        #  include <libqhull.h>
+        # else
+        #  include <qhull.h>
+        # endif
+        # include <qset.h>
+        # include <geom.h>
+        # include <poly.h>
+        # include <io.h>
+        #endif
+        ]], [[
+        const char *tmp = qh_version;
+      ]])], 
+      octave_cv_lib_qhull_version=yes, octave_cv_lib_qhull_version=no)
+  ])
+  if test $octave_cv_lib_qhull_version = no; then
+    AC_DEFINE(NEED_QHULL_VERSION, 1,
+      [Define to 1 if the Qhull library needs a qh_version variable defined.])
+  fi
+])
+dnl
+dnl Check if the default Fortran INTEGER is 64 bits wide.
+dnl
+AC_DEFUN([OCTAVE_CHECK_SIZEOF_FORTRAN_INTEGER], [
+  AC_CACHE_CHECK([whether $F77 generates correct size integers],
+    [octave_cv_sizeof_fortran_integer],
+    [ac_octave_save_FFLAGS="$FFLAGS"
+    FFLAGS="$FFLAGS $F77_INTEGER_8_FLAG"
+    AC_LANG_PUSH(Fortran 77)
+    AC_COMPILE_IFELSE(
+[[      subroutine foo(n, in, out)
+      integer n, in(n), out(n)
+      integer i
+      do 10 i = 1, n
+        out(i) = in(i)
+   10 continue
+      return
+      end
+]],
+      [mv conftest.$ac_objext fintsize.$ac_objext
+      ac_octave_save_LIBS="$LIBS"
+      LIBS="fintsize.$ac_objext $[]_AC_LANG_PREFIX[]LIBS"
+      AC_LANG_PUSH(C)
+      AC_RUN_IFELSE([AC_LANG_PROGRAM([[
+          #include <assert.h>
+          #include <stdint.h> ]], [[
+          #ifdef USE_64_BIT_IDX_T
+            typedef int64_t octave_idx_type;
+          #else
+            typedef int octave_idx_type;
+          #endif
+          octave_idx_type n = 2;
+          octave_idx_type in[2];
+          octave_idx_type out[2];
+          in[0] = 13;
+          in[0] = 42;
+          F77_FUNC(foo,FOO) (&n, &in, &out);
+          assert (in[0] == out[0] && in[1] == out[1]);
+        ]])],
+        octave_cv_sizeof_fortran_integer=yes,
+        octave_cv_sizeof_fortran_integer=no,
+        octave_cv_sizeof_fortran_integer=yes)
+      AC_LANG_POP(C)
+      LIBS="$ac_octave_save_LIBS"
+      rm -f conftest.$ac_objext fintsize.$ac_objext],
+      [rm -f conftest.$ac_objext
+      AC_MSG_FAILURE([cannot compile a simple Fortran program])
+      octave_cv_sizeof_fortran_integer=no])
+    AC_LANG_POP(Fortran 77)
+    FFLAGS="$ac_octave_save_FFLAGS"
+  ])
+])
+dnl
+dnl Add warning to final summary.
+dnl
+AC_DEFUN([OCTAVE_CONFIGURE_WARNING], [
+  AC_MSG_WARN([$][$1])
+  m4_set_add([summary_warning_list], [$1])
+])
+dnl
+dnl Print final summary.
+dnl
+AC_DEFUN([OCTAVE_CONFIGURE_WARNING_SUMMARY], [
+  m4_set_foreach([summary_warning_list], [elt], [
+    if test -n "[$]elt"; then
+      AC_MSG_WARN([$]elt)
+      warn_msg_printed=true
+    fi])
 ])
 dnl
-dnl Check for support of OpenMP with a given compiler flag. If
-dnl found define HAVE_OPENMP and add the compile flag to CFLAGS
-dnl and CXXFLAGS.
+dnl Check if the C++ library has the bit_and, bit_or, and bit_xor
+dnl templates defined.
+dnl
+AC_DEFUN([OCTAVE_CXX_BITWISE_OP_TEMPLATES], [
+  AC_CACHE_CHECK([whether bit_and, bit_or, bit_xor are defined in the C++ library],
+    [octave_cv_cxx_bitwise_op_templates],
+    [AC_LANG_PUSH(C++)
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+        #include <functional>
+        ]], [[
+        int x = 0;
+        int y = 1;
+        int z1 = std::bit_and<int>() (x, y);
+        int z2 = std::bit_or<int>() (x, y);
+        int z3 = std::bit_xor<int>() (x, y);
+      ]])],
+      octave_cv_cxx_bitwise_op_templates=yes,
+      octave_cv_cxx_bitwise_op_templates=no)
+    AC_LANG_POP(C++)
+  ])
+  if test $octave_cv_cxx_bitwise_op_templates = yes; then
+    AC_DEFINE(HAVE_CXX_BITWISE_OP_TEMPLATES, 1,
+      [Define to 1 if C++ library has templated bitwise operators.])
+  fi
+])
+dnl
+dnl Check if C++ reinterpret cast works for function pointers.
+dnl
+AC_DEFUN([OCTAVE_CXX_BROKEN_REINTERPRET_CAST],
+  [AC_REQUIRE([AC_PROG_CXX])
+  AC_CACHE_CHECK([for broken C++ reinterpret_cast],
+    [octave_cv_cxx_broken_reinterpret_cast],
+    [AC_LANG_PUSH(C++)
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+        #include <cmath> ]], [[
+        typedef double (*fptr) (double);
+        fptr psin = sin;
+        void *vptr = reinterpret_cast<void *> (psin);
+        psin = reinterpret_cast<fptr> (vptr);
+      ]])],
+      octave_cv_cxx_broken_reinterpret_cast=no,
+      octave_cv_cxx_broken_reinterpret_cast=yes)
+    AC_LANG_POP(C++)
+  ])
+  if test $octave_cv_cxx_broken_reinterpret_cast = yes; then
+    AC_DEFINE(CXX_BROKEN_REINTERPRET_CAST, 1,
+      [Define to 1 if C++ reinterpret_cast fails for function pointers.])
+  fi
+])
+dnl
+dnl Check if the C++ library has functions to access real and imaginary
+dnl parts of complex numbers independently via references.
+dnl
+AC_DEFUN([OCTAVE_CXX_COMPLEX_REFERENCE_ACCESSORS], [
+  AC_CACHE_CHECK([whether complex class can reference components independently],
+    [octave_cv_cxx_complex_reference_accessors],
+    [AC_LANG_PUSH(C++)
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+        #include <complex>
+        ]], [[
+        std::complex<double> x;
+        x.real () = 1.0;
+        x.imag () = 1.0;
+      ]])],
+      octave_cv_cxx_complex_reference_accessors=yes,
+      octave_cv_cxx_complex_reference_accessors=no)
+    AC_LANG_POP(C++)
+  ])
+  if test $octave_cv_cxx_complex_reference_accessors = yes; then
+    AC_DEFINE(HAVE_CXX_COMPLEX_REFERENCE_ACCESSORS, 1,
+      [Define to 1 if C++ complex class has T& real (void) and T& imag (void) methods.])
+  fi
+])
+dnl
+dnl Check if the C++ library has functions to set real and imaginary
+dnl parts of complex numbers independently.
+dnl
+AC_DEFUN([OCTAVE_CXX_COMPLEX_SETTERS], [
+  AC_CACHE_CHECK([whether complex class can set components independently],
+    [octave_cv_cxx_complex_setters],
+    [AC_LANG_PUSH(C++)
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+        #include <complex>
+        ]], [[
+        std::complex<double> x;
+        x.real (1.0);
+        x.imag (2.0);
+      ]])],
+      octave_cv_cxx_complex_setters=yes, octave_cv_cxx_complex_setters=no)
+    AC_LANG_POP(C++)
+  ])
+  if test $octave_cv_cxx_complex_setters = yes; then
+    AC_DEFINE(HAVE_CXX_COMPLEX_SETTERS, 1, 
+      [Define to 1 if C++ complex class has void real (T) and void imag (T) methods.])
+  fi
+])
+dnl
+dnl Check if the compiler supports dynamic auto arrays.
 dnl
-AC_DEFUN([OCTAVE_CHECK_OPENMP],
-[AC_MSG_CHECKING([for support of OpenMP])
-XCFLAGS="$CFLAGS"
-CFLAGS="$CFLAGS $1"
-AC_CACHE_VAL(octave_cv_check_openmp,[
-AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
-#include <omp.h>
-#include <stdio.h>
-]], [[
-int main(int argc, char* argv[])
-{
-  _Pragma("omp parallel")  
-  printf("Hello, world.\n");
-  return 0;
-}
-]])],octave_cv_openmp=yes, octave_cv_openmmp=no, octave_cv_openmp=no)])
-AC_MSG_RESULT($octave_cv_openmp)
-if test "$octave_cv_openmp" = yes; then
-  AC_DEFINE(HAVE_OPENMP,1,[Define if compiler supports OpenMP])
-  CXXFLAGS="$CXXFLAGS $1"
-else
-  CFLAGS="$XCFLAGS"
-fi
+AC_DEFUN([OCTAVE_CXX_DYNAMIC_AUTO_ARRAYS], [
+  AC_CACHE_CHECK([whether C++ supports dynamic auto arrays],
+    [octave_cv_cxx_dynamic_auto_arrays],
+    [AC_LANG_PUSH(C++)
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [[
+        void test(char *);
+        int length();
+        char x[length()];
+        test(x);
+      ]])],
+      octave_cv_cxx_dynamic_auto_arrays=yes, 
+      octave_cv_cxx_dynamic_auto_arrays=no)
+    AC_LANG_POP(C++)
+  ])
+  if test $octave_cv_cxx_dynamic_auto_arrays = yes; then
+    AC_DEFINE(HAVE_DYNAMIC_AUTO_ARRAYS, 1,
+      [Define to 1 if C++ supports dynamic auto arrays.])
+  fi
+])
+dnl
+dnl Check if C++ compiler handles FLAG command line option.  If two
+dnl arguments are specified, execute the second arg as shell commands.
+dnl Otherwise, add FLAG to CXXFLAGS if the compiler accepts the flag.
+dnl
+AC_DEFUN([OCTAVE_CXX_FLAG], [
+  ac_safe=`echo "$1" | sed 'y%./+-:=%__p___%'`
+  AC_MSG_CHECKING([whether ${CXX-g++} accepts $1])
+  AC_CACHE_VAL([octave_cv_cxx_flag_$ac_safe],
+    [AC_LANG_PUSH(C++)
+    ac_octave_save_CXXFLAGS="$CXXFLAGS"
+    CXXFLAGS="$CXXFLAGS $1"
+    AC_LINK_IFELSE([AC_LANG_PROGRAM([], [])],
+      eval "octave_cv_cxx_flag_$ac_safe=yes",
+      eval "octave_cv_cxx_flag_$ac_safe=no")
+    CXXFLAGS="$ac_octave_save_CXXFLAGS"
+    AC_LANG_POP(C++)
+  ])
+  if eval "test \"`echo '$octave_cv_cxx_flag_'$ac_safe`\" = yes"; then
+    AC_MSG_RESULT([yes])
+    ifelse([$2], ,
+      [CXXFLAGS="$CXXFLAGS $1"
+      AC_MSG_RESULT([adding $1 to CXXFLAGS])], [$2])
+  else
+    AC_MSG_RESULT([no])
+    ifelse([$3], , , [$3])
+  fi
 ])
+dnl
+dnl Check if the C++ library is ISO compliant.
+dnl FIXME: This is obviously very simplistic, and trivially fooled.
+dnl
+AC_DEFUN([OCTAVE_CXX_ISO_COMPLIANT_LIBRARY], [
+  AC_REQUIRE([AC_PROG_CXX])
+  AC_MSG_CHECKING([if C++ library is ISO compliant])
+  AC_CACHE_VAL([octave_cv_cxx_iso_compliant_library],
+    [AC_LANG_PUSH(C++)
+    rm -f conftest.h
+    ## Omitting cwctype for now, since it is broken with gcc-3.0.x and
+    ## possibly other versions...
+    for inc in algorithm bitset cassert cctype cerrno cfloat ciso646 \
+        climits clocale cmath complex csetjmp csignal cstdarg cstddef \
+        cstdio cstdlib cstring ctime cwchar deque exception \
+        fstream functional iomanip ios iosfwd iostream istream iterator \
+        limits list locale map memory new numeric ostream queue set \
+        sstream stack stdexcept streambuf string strstream typeinfo \
+        utility valarray vector; do
+      echo "#include <$inc>" >> conftest.h
+    done
+    AC_LINK_IFELSE([AC_LANG_PROGRAM([[
+        #include "conftest.h"
+        ]], [[
+        std::bitset<50> flags;
+        flags.set();
+        int digits = std::numeric_limits<unsigned long>::digits;
+        digits = 0;
+      ]])],
+      octave_cv_cxx_iso_compliant_library=yes,
+      octave_cv_cxx_iso_compliant_library=no)
+    AC_LANG_POP(C++)
+  ])
+  AC_MSG_RESULT([$octave_cv_cxx_iso_compliant_library])
+  if test $octave_cv_cxx_iso_compliant_library = yes; then
+    AC_DEFINE(CXX_ISO_COMPLIANT_LIBRARY, 1, 
+      [Define to 1 if your C++ runtime library is ISO compliant.])
+  fi
+])
+dnl
+dnl Check if C++ compiler needs the new friend template declaration
+dnl syntax. 
+dnl
+AC_DEFUN([OCTAVE_CXX_NEW_FRIEND_TEMPLATE_DECL], [
+  AC_REQUIRE([AC_PROG_CXX])
+  AC_MSG_CHECKING([for C++ support for new friend template declaration])
+  AC_CACHE_VAL([octave_cv_cxx_new_friend_template_decl],
+    [AC_LANG_PUSH(C++)
+    rm -f conftest.h
+    cat > conftest.h <<EOB
+       struct A {
+         friend int operator== (const A&, const A&);
+         A (int) { }
+       };
 
-dnl Check whether a math mapper function is available in <cmath>.
-dnl Will define HAVE_CMATH_FUNC if there is a double variant and
-dnl HAVE_CMATH_FUNCF if there is a float variant.
-dnl Currently capable of checking for functions with single 
-dnl argument and returning bool/int/real.
-AC_DEFUN([OCTAVE_CMATH_FUNC],[
-AC_MSG_CHECKING([for std::$1 in <cmath>])
-AC_LANG_PUSH(C++)
-AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
-#include <cmath>
-void take_func (bool (*func) (double x));
-void take_func (int (*func) (double x));
-void take_func (double (*func) (double x));
-]],
-[[
-take_func(std::$1);
-]])],
-[AC_MSG_RESULT([yes])
- AC_DEFINE(HAVE_CMATH_[]AS_TR_CPP($1),1,[Define if <cmath> provides $1])],
-[AC_MSG_RESULT([no])])
-AC_MSG_CHECKING([for std::$1 (float variant) in <cmath>])
-AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
-#include <cmath>
-void take_func (bool (*func) (float x));
-void take_func (int (*func) (float x));
-void take_func (float (*func) (float x));
-]],
-[[
-take_func(std::$1);
-]])],
-[AC_MSG_RESULT([yes])
- AC_DEFINE(HAVE_CMATH_[]AS_TR_CPP($1)F,1,[Define if <cmath> provides float variant of $1])],
-[AC_MSG_RESULT([no])])
-AC_LANG_POP(C++)
+       template <class T> int
+       operator== (const T&, const T&)
+       {
+         return 0;
+       }
+EOB
+    AC_LINK_IFELSE([AC_LANG_PROGRAM([[
+        #include "conftest.h"
+        ]], [[
+        A a (1);
+        return a == A(1);
+      ]])],
+      octave_cv_cxx_new_friend_template_decl=no,
+      octave_cv_cxx_new_friend_template_decl=yes)
+    AC_LANG_POP(C++)
+  ])
+  AC_MSG_RESULT([$octave_cv_cxx_new_friend_template_decl])
+  if test $octave_cv_cxx_new_friend_template_decl = yes; then
+    AC_DEFINE(CXX_NEW_FRIEND_TEMPLATE_DECL, 1,
+      [Define to 1 if your compiler supports `<>' stuff for template friends.])
+  fi
+])
+dnl
+dnl Check if the compiler supports placement delete.
+dnl
+AC_DEFUN([OCTAVE_CXX_PLACEMENT_DELETE], [
+  AC_CACHE_CHECK([whether <new> defines placement delete operator],
+    [octave_cv_cxx_placement_delete],
+    [AC_LANG_PUSH(C++)
+    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
+        #include <new>
+        ]], [[
+        operator delete((void *)0, (void *)0);
+      ]])],
+      octave_cv_cxx_placement_delete=yes, 
+      octave_cv_cxx_placement_delete=no)
+    AC_LANG_POP(C++)
+  ])
+  if test $octave_cv_cxx_placement_delete = yes; then
+    AC_DEFINE(HAVE_PLACEMENT_DELETE, 1,
+      [Define to 1 if C++ supports operator delete(void *, void *).])
+  fi
 ])
-
+dnl
+dnl Allow the user disable support for command line editing using GNU
+dnl readline.
+dnl
+AC_DEFUN([OCTAVE_ENABLE_READLINE], [
+  USE_READLINE=yes
+  READLINE_LIBS=
+  AC_ARG_ENABLE([readline],
+    [AS_HELP_STRING([--disable-readline],
+      [use readline library])],
+    [if test "$enableval" = no; then
+       USE_READLINE=no
+       warn_readline="command editing and history features require GNU Readline"
+     fi])
+  if test $USE_READLINE = yes; then
+    dnl RHEL 5 and older systems require termlib set before enabling readline
+    AC_REQUIRE([OCTAVE_CHECK_LIB_TERMLIB])
+    ac_octave_save_LIBS="$LIBS"
+    LIBS="$TERM_LIBS"
+    AC_CHECK_LIB([readline], [rl_set_keyboard_input_timeout],
+      [READLINE_LIBS="-lreadline"
+      AC_DEFINE(USE_READLINE, 1, [Define to 1 to use the readline library.])
+      ],
+      [AC_MSG_WARN([I need GNU Readline 4.2 or later])
+      AC_MSG_ERROR([this is fatal unless you specify --disable-readline])
+    ])
+    LIBS="$ac_octave_save_LIBS"
+  fi
+  AC_SUBST(READLINE_LIBS)
+])
+dnl
+dnl Check if Fortran compiler handles FLAG command line option.  If
+dnl two arguments are specified, execute the second arg as shell
+dnl commands.  Otherwise, add FLAG to FFLAGS if the compiler accepts
+dnl the flag.
+dnl
+AC_DEFUN([OCTAVE_F77_FLAG], [
+  ac_safe=`echo "$1" | sed 'y%./+-:=%__p___%'`
+  AC_MSG_CHECKING([whether ${F77-g77} accepts $1])
+  AC_CACHE_VAL([octave_cv_f77_flag_$ac_safe], [
+    AC_LANG_PUSH(Fortran 77)
+    ac_octave_save_FFLAGS="$FFLAGS"
+    FFLAGS="$FFLAGS $1"
+    AC_LINK_IFELSE([AC_LANG_PROGRAM([], [])],
+      eval "octave_cv_f77_flag_$ac_safe=yes",
+      eval "octave_cv_f77_flag_$ac_safe=no")
+    FFLAGS="$ac_octave_save_FFLAGS"
+    AC_LANG_POP(Fortran 77)
+  ])
+  if eval "test \"`echo '$octave_cv_f77_flag_'$ac_safe`\" = yes"; then
+    AC_MSG_RESULT([yes])
+    ifelse([$2], ,
+      [FFLAGS="$FFLAGS $1"
+      AC_MSG_RESULT([adding $1 to FFLAGS])], [$2])
+  else
+    AC_MSG_RESULT([no])
+    ifelse([$3], , , [$3])
+  fi
+])
+dnl
 dnl Check whether fast signed integer arithmetics using bit tricks
-dnl can be used in oct-inttypes.h. Defines HAVE_FAST_INT_OPS if
+dnl can be used in oct-inttypes.h.  Defines HAVE_FAST_INT_OPS if
 dnl the following conditions hold:
 dnl 1. Signed numbers are represented by twos complement
 dnl    (see <http://en.wikipedia.org/wiki/Two%27s_complement>)
@@ -1350,269 +1222,669 @@
 dnl    (We use casts to prevent optimization interference, so there is no
 dnl     need for things like -ftrapv).
 dnl 4. Bit operations on signed integers work like on unsigned integers,
-dnl    except for the shifts. Shifts are arithmetic.
+dnl    except for the shifts.  Shifts are arithmetic.
 dnl
-AC_DEFUN([OCTAVE_FAST_INT_OPS],
-[AC_CACHE_CHECK([whether fast integer arithmetics is usable],
-octave_cv_fast_int_ops,
-[AC_LANG_PUSH(C++)
-AC_RUN_IFELSE([AC_LANG_PROGRAM([[
-#include <limits>
-template<class UT, class ST>
-static bool 
-do_test (UT, ST)
-{
-  volatile ST s = std::numeric_limits<ST>::min () / 3;
-  volatile UT u = static_cast<UT> (s);
-  if (*(reinterpret_cast<volatile ST *> (&u)) != s) return true;
-  
-  u = 0; u = ~u;
-  if (*(reinterpret_cast<volatile ST *> (&u)) != -1) return true;
-  
-  ST sx, sy;
-  sx = std::numeric_limits<ST>::max () / 2 + 1;
-  sy = std::numeric_limits<ST>::max () / 2 + 2;
-  if (static_cast<ST> (static_cast<UT> (sx) + static_cast<UT> (sy))
-      != std::numeric_limits<ST>::min () + 1) return true;
-  if (static_cast<ST> (static_cast<UT> (sx) - static_cast<UT> (sy))
-      != -1) return true;
-  
-  if ((sx & sy) != (static_cast<UT> (sx) & static_cast<UT> (sy)))
-    return true;
-  if ((sx | sy) != (static_cast<UT> (sx) | static_cast<UT> (sy)))
-    return true;
-  if ((sx ^ sy) != (static_cast<UT> (sx) ^ static_cast<UT> (sy)))
-    return true;
-  if ((-1 >> 1) != -1) return true;
-  return false;
-}
+AC_DEFUN([OCTAVE_FAST_INT_OPS], [
+  AC_CACHE_CHECK([whether fast integer arithmetics is usable],
+    [octave_cv_fast_int_ops],
+    [AC_LANG_PUSH(C++)
+    AC_RUN_IFELSE([AC_LANG_PROGRAM([[
+        #include <limits>
+        template<class UT, class ST>
+        static bool 
+        do_test (UT, ST)
+        {
+          volatile ST s = std::numeric_limits<ST>::min () / 3;
+          volatile UT u = static_cast<UT> (s);
+          if (*(reinterpret_cast<volatile ST *> (&u)) != s) return true;
+          
+          u = 0; u = ~u;
+          if (*(reinterpret_cast<volatile ST *> (&u)) != -1) return true;
+          
+          ST sx, sy;
+          sx = std::numeric_limits<ST>::max () / 2 + 1;
+          sy = std::numeric_limits<ST>::max () / 2 + 2;
+          if (static_cast<ST> (static_cast<UT> (sx) + static_cast<UT> (sy))
+              != std::numeric_limits<ST>::min () + 1) return true;
+          if (static_cast<ST> (static_cast<UT> (sx) - static_cast<UT> (sy))
+              != -1) return true;
+          
+          if ((sx & sy) != (static_cast<UT> (sx) & static_cast<UT> (sy)))
+            return true;
+          if ((sx | sy) != (static_cast<UT> (sx) | static_cast<UT> (sy)))
+            return true;
+          if ((sx ^ sy) != (static_cast<UT> (sx) ^ static_cast<UT> (sy)))
+            return true;
+          if ((-1 >> 1) != -1) return true;
+          return false;
+        }
+      
+        #define DO_TEST(T) \
+          if (do_test (static_cast<unsigned T> (0), static_cast<signed T> (0)))\
+            return sizeof (T);
 
-#define DO_TEST(T) \
-if (do_test (static_cast<unsigned T> (0), static_cast<signed T> (0))) \
-  return sizeof (T);
-]],[[
-  DO_TEST(char)
-  DO_TEST(short)
-  DO_TEST(int)
-  DO_TEST(long)
-#if (defined(HAVE_LONG_LONG_INT) && defined(HAVE_UNSIGNED_LONG_LONG_INT))
-  DO_TEST(long long)
-#endif
-]])],
-   [octave_cv_fast_int_ops=yes],
-   [octave_cv_fast_int_ops=no],
-   [octave_cv_fast_int_ops=yes])
-AC_LANG_POP(C++)])
-if test $octave_cv_fast_int_ops = yes; then
-  AC_DEFINE(HAVE_FAST_INT_OPS, 1,
-    [Define if signed integers use two's complement])
-fi
+        ]],[[
+
+        DO_TEST(char)
+        DO_TEST(short)
+        DO_TEST(int)
+        DO_TEST(long)
+        #if (defined(HAVE_LONG_LONG_INT) && defined(HAVE_UNSIGNED_LONG_LONG_INT))
+          DO_TEST(long long)
+        #endif
+      ]])],
+      octave_cv_fast_int_ops=yes,
+      octave_cv_fast_int_ops=no,
+      octave_cv_fast_int_ops=yes)
+    AC_LANG_POP(C++)
+  ])
+  if test $octave_cv_fast_int_ops = yes; then
+    AC_DEFINE(HAVE_FAST_INT_OPS, 1,
+      [Define to 1 if signed integers use two's complement.])
+  fi
 ])
 dnl
 dnl Check to see if the compiler and the linker can handle the flags
 dnl "-framework $1" for the given prologue $2 and the given body $3 of
 dnl a source file.  Arguments 2 and 3 optionally can also be empty.
 dnl Add options (lower case letters $1) "--with-framework-$1" and
-dnl "--without-framework-$1". If this test is successful then perform
+dnl "--without-framework-$1".  If this test is successful then perform
 dnl $4, otherwise do $5.
 dnl
-dnl OCTAVE_HAVE_FRAMEWORK
 AC_DEFUN([OCTAVE_HAVE_FRAMEWORK], [
   AC_MSG_CHECKING([whether ${LD-ld} accepts -framework $1])
-  AC_CACHE_VAL(octave_cv_framework_$1, [
-    XLDFLAGS="$LDFLAGS"
+  AC_CACHE_VAL([octave_cv_framework_$1],
+    [ac_octave_save_LDFLAGS="$LDFLAGS"
     LDFLAGS="$LDFLAGS -framework $1"
     AC_LANG_PUSH(C++)
     AC_LINK_IFELSE([AC_LANG_PROGRAM([$2], [$3])],
       eval "octave_cv_framework_$1=yes",
       eval "octave_cv_framework_$1=no")
     AC_LANG_POP(C++)
-    LDFLAGS="$XLDFLAGS"
+    LDFLAGS="$ac_octave_save_LDFLAGS"
   ])
-  if test "$octave_cv_framework_$1" = "yes"; then
-    AC_MSG_RESULT(yes)
+  if test "$octave_cv_framework_$1" = yes; then
+    AC_MSG_RESULT([yes])
     AC_ARG_WITH(framework-m4_tolower($1),
       [AS_HELP_STRING([--without-framework-m4_tolower($1)], 
         [don't use framework $1])],
-         with_have_framework=$withval, with_have_framework="yes")
-    if test "$with_have_framework" = "yes"; then
+         with_have_framework=$withval, with_have_framework=yes)
+    if test "$with_have_framework" = yes; then
       [$4]
+      :
     else
       AC_MSG_NOTICE([framework rejected by --without-framework-m4_tolower($1)])
       [$5]
     fi
   else
-    AC_MSG_RESULT(no)
+    AC_MSG_RESULT([no])
     [$5]
   fi
 ])
+dnl
+dnl Figure out the hardware-vendor-os info.
+dnl
+AC_DEFUN([OCTAVE_CANONICAL_HOST], [
+  AC_CANONICAL_HOST
+  if test -z "$host"; then
+    host=unknown-unknown-unknown
+    AC_MSG_WARN([configuring Octave for unknown system type])
+  fi
+  canonical_host_type=$host
+  AC_SUBST(canonical_host_type)
+  if test -z "$host_cpu"; then
+    host_cpu=unknown
+  fi
+  if test -z "$host_vendor"; then
+    host_vendor=unknown
+  fi
+  if test -z "$host_os"; then
+    host_os=unknown
+  fi
+])
+dnl
+dnl Check for IEEE 754 data format.
+dnl
+AC_DEFUN([OCTAVE_IEEE754_DATA_FORMAT], [
+  AC_MSG_CHECKING([for IEEE 754 data format])
+  AC_CACHE_VAL([octave_cv_ieee754_data_format],
+    [AC_RUN_IFELSE([AC_LANG_SOURCE([[
+        int
+        main (void) 
+        {
+          typedef union { unsigned char c[8]; double d; } ieeebytes;
+           
+          ieeebytes l = {0x1c, 0xbc, 0x6e, 0xf2, 0x54, 0x8b, 0x11, 0x43};
+          ieeebytes b = {0x43, 0x11, 0x8b, 0x54, 0xf2, 0x6e, 0xbc, 0x1c};
+
+          return l.d != 1234567891234567.0 && b.d != 1234567891234567.0;
+        }
+      ]])],
+      octave_cv_ieee754_data_format=yes,
+      octave_cv_ieee754_data_format=no,
+      octave_cv_ieee754_data_format=yes)
+  ])
+  if test "$cross_compiling" = yes; then
+    AC_MSG_RESULT([$octave_cv_ieee754_data_format assumed for cross compilation])
+  else
+    AC_MSG_RESULT([$octave_cv_ieee754_data_format])
+  fi
+  if test $octave_cv_ieee754_data_format = yes; then
+    AC_DEFINE(HAVE_IEEE754_DATA_FORMAT, 1,
+      [Define to 1 if your system uses IEEE 754 data format.])
+  else
+    ## If the format is unknown, then you will probably not have a
+    ## useful system, so we will abort here.  Anyone wishing to
+    ## experiment with building Octave on a system without IEEE
+    ## floating point should be capable of removing this check and
+    ## the one in the octave_ieee_init function in liboctave/lo-ieee.cc.
+    AC_MSG_ERROR([IEEE 754 data format required for building Octave])
+  fi
+])
+dnl
+dnl Check for ar.
+dnl
+AC_DEFUN([OCTAVE_PROG_AR], [
+  if test -z "$AR"; then
+    AR=ar
+  fi
+  AC_SUBST(AR)
+
+  if test -z "$ARFLAGS"; then
+    ARFLAGS="rc"
+  fi
+  AC_SUBST(ARFLAGS)
+])
+dnl
+dnl Check for bison.
+dnl
+AC_DEFUN([OCTAVE_PROG_BISON], [
+  AC_PROG_YACC
+  case "$YACC" in
+    bison*)
+    AC_CACHE_CHECK([syntax of bison push/pull declaration],
+                   [octave_cv_bison_push_pull_decl_style], [
+      style="dash underscore"
+      quote="noquote quote"
+      for s in $style; do
+        for q in $quote; do
+          if test $s = "dash"; then
+            def="%define api.push-pull"
+          else
+            def="%define api.push_pull"
+          fi
+          if test $q = "quote"; then
+            def="$def \"both\""
+          else
+            def="$def both"
+          fi
+          cat << EOF > conftest.yy
+$def
+%start input
+%%
+input:;
+%%
+EOF
+          $YACC conftest.yy > /dev/null 2>&1
+          ac_status=$?
+          if test $ac_status -eq 0; then
+            if test $q = noquote; then
+              q=
+            fi
+            octave_cv_bison_push_pull_decl_style="$s $q"
+            break
+          fi
+        done
+        if test $ac_status -eq 0; then
+          break
+        fi
+      done
+      rm -f conftest.yy y.tab.h y.tab.c
+      ])
+    ;;
+  esac
+
+  AC_SUBST(BISON_PUSH_PULL_DECL_STYLE, $octave_cv_bison_push_pull_decl_style)
+
+  if test -z "$octave_cv_bison_push_pull_decl_style"; then
+    YACC=
+    warn_bison_push_pull_decl_style="
+
+I wasn't able to find a suitable style for declaring a push-pull
+parser in a bison input file so I'm disabling bison.
+"
+    OCTAVE_CONFIGURE_WARNING([warn_bison_push_pull_decl_style])
+  fi
+
+  case "$YACC" in
+    bison*)
+    ;;
+    *)
+      YACC='$(top_srcdir)/build-aux/missing bison'
+      warn_bison="
+
+I didn't find bison, but it's only a problem if you need to
+reconstruct parse.cc, which is the case if you're building from VCS
+sources.
+"
+      OCTAVE_CONFIGURE_WARNING([warn_bison])
+    ;;
+  esac
+])
+dnl
+dnl Find desktop-file-install program.
+dnl
+AC_DEFUN([OCTAVE_PROG_DESKTOP_FILE_INSTALL], [
+  AC_CHECK_PROG(DESKTOP_FILE_INSTALL, desktop-file-install, desktop-file-install, [])
+  AC_SUBST(DESKTOP_FILE_INSTALL)
+])
+dnl
+dnl Find find program.
+dnl
+## Prefer GNU find if found.
+AN_MAKEVAR([FIND],  [OCTAVE_PROG_FIND])
+AN_PROGRAM([gfind], [OCTAVE_PROG_FIND])
+AN_PROGRAM([find],  [OCTAVE_PROG_FIND])
+AC_DEFUN([OCTAVE_PROG_FIND], [
+  AC_CHECK_PROGS(FIND, [gfind find])
+])
+dnl
+dnl Check for flex.
+dnl
+AC_DEFUN([OCTAVE_PROG_FLEX], [
+  ## For now, don't define LEXLIB to be -lfl -- we don't use anything in
+  ## it, and it might not be installed.
+  ##
+  ## Also make sure that we generate an interactive scanner if we are
+  ## using flex.
+  AC_PROG_LEX
+  case "$LEX" in
+    flex*)
+      LFLAGS="-I"
+      AC_MSG_RESULT([defining LFLAGS to be $LFLAGS])
+      LEXLIB=
+    ;;
+    *)
+      LEX='$(top_srcdir)/build-aux/missing flex'
+      warn_flex="
+
+I didn't find flex, but it's only a problem if you need to reconstruct
+lex.cc, which is the case if you're building from VCS sources.
+"
+      OCTAVE_CONFIGURE_WARNING([warn_flex])
+    ;;
+  esac
+  AC_SUBST(LFLAGS)
+])
+dnl
+dnl Check for ghostscript.
+dnl
+AC_DEFUN([OCTAVE_PROG_GHOSTSCRIPT], [
+  case "$canonical_host_type" in
+    *-*-mingw* | *-*-msdosmsvc)
+      ac_octave_gs_names="gswin32c gs mgs"
+    ;;
+    *)
+      ac_octave_gs_names="gs"
+    ;;
+  esac
+  AC_CHECK_PROGS(GHOSTSCRIPT, [$ac_octave_gs_names])
+  if test -z "$GHOSTSCRIPT"; then
+    GHOSTSCRIPT='$(top_srcdir)/build-aux/missing gs'
+    warn_ghostscript="
+
+I didn't find ghostscript, so reconstructing figures for the manual
+will fail, and saving graphics in some output formats will fail when
+using Octave
+"
+    OCTAVE_CONFIGURE_WARNING([warn_ghostscript])
+  fi
+  AC_SUBST(GHOSTSCRIPT)
+])
+dnl
+dnl Check for gnuplot.
+dnl
+AC_DEFUN([OCTAVE_PROG_GNUPLOT], [
+  ac_octave_gp_names="gnuplot"
+  ac_octave_gp_default="gnuplot"
+  if test "$cross_compiling" = yes; then
+    GNUPLOT="$ac_octave_gp_default"
+    AC_MSG_RESULT([assuming $GNUPLOT exists on $canonical_host_type host])
+  else
+    AC_CHECK_PROGS(GNUPLOT, [$ac_octave_gp_names])
+    if test -z "$GNUPLOT"; then
+      GNUPLOT="$gp_default"
+      warn_gnuplot="
+
+gnuplot not found.  It isn't necessary to have gnuplot installed, but
+without native graphics or gnuplot you won't be able to use any of
+Octave's plotting commands.
+"
+      OCTAVE_CONFIGURE_WARNING([warn_gnuplot])
+    fi
+  fi
+  AC_SUBST(GNUPLOT)
+])
+dnl
+dnl Check for gperf.
+dnl
+AC_DEFUN([OCTAVE_PROG_GPERF], [
+  AC_CHECK_PROG(GPERF, gperf, gperf, [])
+  if test -z "$GPERF"; then
+    GPERF='$(top_srcdir)/build-aux/missing gperf'
+    warn_gperf="
+
+I didn't find gperf, but it's only a problem if you need to
+reconstruct oct-gperf.h 
+"
+    OCTAVE_CONFIGURE_WARNING([warn_gperf])
+  fi
+  AC_SUBST(GPERF)
+])
+dnl
+dnl Check for makeinfo.
+dnl
+AC_DEFUN([OCTAVE_PROG_MAKEINFO], [
+  dnl use MKINFO, not MAKEINFO, for variable name because Automake
+  dnl automatically defines a value for MAKEINFO even when it does not
+  dnl exist which will then fool the 'test -z' line.
+  AC_CHECK_PROG(MKINFO, makeinfo, makeinfo, [])
+  if test -z "$MKINFO"; then
+    warn_makeinfo="
+
+I didn't find makeinfo, which is required for reading documentation.
+You may install a copy later for Octave to use.
+"
+    OCTAVE_CONFIGURE_WARNING([warn_makeinfo])
+  fi
+])
+dnl
+dnl What pager should we use?
+dnl
+AC_DEFUN([OCTAVE_PROG_PAGER], [
+  if test "$cross_compiling" = yes; then
+    DEFAULT_PAGER=less
+    AC_MSG_RESULT([assuming $DEFAULT_PAGER exists on $canonical_host_type host])
+    AC_SUBST(DEFAULT_PAGER)
+  else
+    ac_octave_possible_pagers="less more page pg"
+    case "$canonical_host_type" in
+      *-*-cygwin* | *-*-mingw32* | *-*-msdosmsvc)
+        ac_octave_possible_pagers="$ac_octave_possible_pagers more.com"
+      ;;
+    esac
+
+    AC_CHECK_PROGS(DEFAULT_PAGER, [$ac_octave_possible_pagers], [])
+    if test -z "$DEFAULT_PAGER"; then
+      warn_less="I couldn't find \`less', \`more', \`page', or \`pg'"
+      OCTAVE_CONFIGURE_WARNING([warn_less])
+    fi
+  fi
+])
+dnl
+dnl Find Perl program.
+dnl
+AC_DEFUN([OCTAVE_PROG_PERL], [
+  AC_CHECK_PROG(PERL, perl, perl, [])
+  AC_SUBST(PERL)
+])
+dnl
+dnl Find Python program.
+dnl
+AC_DEFUN([OCTAVE_PROG_PYTHON], [
+  AC_CHECK_PROG(PYTHON, python, python, [])
+  AC_SUBST(PYTHON)
+])
+dnl
+dnl Find sed program.
+dnl
+# Check for a fully-functional sed program, that truncates
+# as few characters as possible and that supports "\(X\|Y\)"
+# style regular expression alternation.  Prefer GNU sed if found.
+AC_DEFUN([OCTAVE_PROG_SED], [
+  AC_MSG_CHECKING([for a usable sed])
+  if test -z "$SED"; then
+    AC_CACHE_VAL([octave_cv_prog_sed],
+      [# Loop through the user's path and search for sed and gsed.
+      # Next, test potential sed programs in list for truncation.
+      _AS_PATH_WALK([$PATH],
+        [for ac_prog in sed gsed; do
+          for ac_exec_ext in '' $ac_executable_extensions; do
+            if AS_EXECUTABLE_P(["$as_dir/$ac_prog$ac_exec_ext"]); then
+              _sed_list="$_sed_list $as_dir/$ac_prog$ac_exec_ext"
+            fi
+          done
+        done
+      ])
+      AS_TMPDIR(sed)
+      _max=0
+      _count=0
+      # Add /usr/xpg4/bin/sed as it is typically found on Solaris
+      # along with /bin/sed that truncates output.
+      for _sed in $_sed_list /usr/xpg4/bin/sed; do
+        test ! -f ${_sed} && break
+        cat /dev/null > "$tmp/sed.in"
+        _count=0
+        echo $ECHO_N "0123456789$ECHO_C" >"$tmp/sed.in"
+        # Check for GNU sed and select it if it is found.
+        if "${_sed}" --version 2>&1 < /dev/null | egrep '(GNU)' > /dev/null; then
+          octave_cv_prog_sed=${_sed}
+          break;
+        fi
+        # Reject if RE alternation is not handled.
+        if test "`echo 'this and that' | ${_sed} -n 's/\(this\|that\).*$/\1/p'`" != "this"; then
+          continue;
+        fi
+        while true; do
+          cat "$tmp/sed.in" "$tmp/sed.in" >"$tmp/sed.tmp"
+          mv "$tmp/sed.tmp" "$tmp/sed.in"
+          cp "$tmp/sed.in" "$tmp/sed.nl"
+          echo >>"$tmp/sed.nl"
+          ${_sed} -e 's/a$//' < "$tmp/sed.nl" >"$tmp/sed.out" || break
+          cmp -s "$tmp/sed.out" "$tmp/sed.nl" || break
+          # 10000 chars as input seems more than enough
+          test $_count -gt 10 && break
+          _count=`expr $_count + 1`
+          if test $_count -gt $_max; then
+            _max=$_count
+            octave_cv_prog_sed=$_sed
+          fi
+        done
+      done
+      rm -rf "$tmp"
+    ])
+    SED=$octave_cv_prog_sed
+    if test -z "$SED"; then
+      AC_MSG_ERROR([no usable version of sed found])
+    fi
+  fi
+  AC_SUBST(SED)
+  AC_MSG_RESULT([$SED])
+])
+dnl
+dnl Check for texi2dvi.
+dnl
+AC_DEFUN([OCTAVE_PROG_TEXI2DVI], [
+  AC_CHECK_PROG(TEXI2DVI, texi2dvi, texi2dvi, [])
+  if test -z "$TEXI2DVI"; then
+    TEXI2DVI='$(top_srcdir)/build-aux/missing texi2dvi'
+    warn_texi2dvi="
+
+I didn't find texi2dvi, but it's only a problem if you need to
+reconstruct the DVI version of the manual
+"
+    OCTAVE_CONFIGURE_WARNING([warn_texi2dvi])
+  fi
+  TEXI2DVI="$TEXI2DVI"' --build-dir=t2d_cache'
+  AC_SUBST(TEXI2DVI)
+])
+dnl
+dnl Check for texi2pdf.
+dnl
+AC_DEFUN([OCTAVE_PROG_TEXI2PDF], [
+  AC_REQUIRE([OCTAVE_PROG_TEXI2DVI])
+  AC_CHECK_PROG(TEXI2PDF, texi2pdf, texi2pdf, [])
+  if test -z "$TEXI2PDF"; then
+    ac_octave_texi2pdf_missing=yes;
+    if test -n "$TEXI2DVI"; then
+      TEXI2PDF="$TEXI2DVI --pdf"
+      ac_octave_texi2pdf_missing=no;
+    fi
+  else
+    ac_octave_texi2pdf_missing=no;
+  fi
+  if test $ac_octave_texi2pdf_missing = yes; then
+    TEXI2PDF='$(top_srcdir)/build-aux/missing texi2pdf'
+    warn_texi2pdf="
+
+I didn't find texi2pdf, but it's only a problem if you need to
+reconstruct the PDF version of the manual
+"
+    OCTAVE_CONFIGURE_WARNING([warn_texi2pdf])
+  fi
+  TEXI2PDF="$TEXI2PDF"' --build-dir=t2d_cache'
+  AC_SUBST(TEXI2PDF)
+])
+dnl
+dnl Set default value for a variable and substitute it.
+dnl
+AC_DEFUN([OCTAVE_SET_DEFAULT], [
+  ifelse($#, 2, [: ${$1=$2}
+])dnl
+  AC_MSG_RESULT([defining $1 to be $$1])
+  AC_SUBST($1)
+])
+dnl
+dnl Check whether SuiteSparse_time is required by UMFPACK.
+dnl UMFPACK >= 4 requires linking in another library for SuiteSparse_time.
+dnl
+dnl Macro assumes that the check for umfpack has already been performed.
+dnl
+AC_DEFUN([OCTAVE_UMFPACK_NEED_SUITESPARSE_TIME], [
+  AC_CACHE_CHECK([whether UMFPACK needs SuiteSparse_time function], 
+    [octave_cv_umfpack_need_suitesparse_time],
+    [AC_LANG_PUSH(C)
+    AC_LINK_IFELSE([AC_LANG_PROGRAM([[
+        #if defined (HAVE_SUITESPARSE_UMFPACK_H)
+        # include <suitesparse/umfpack.h>
+        #elif defined (HAVE_UFSPARSE_UMFPACK_H)
+        # include <ufsparse/umfpack.h>
+        #elif defined (HAVE_UMFPACK_UMFPACK_H)
+        # include <umfpack/umfpack.h>
+        #elif defined (HAVE_UMFPACK_H)
+        # include <umfpack.h>
+        #endif
+        ]], [[
+        double stats [2];
+        umfpack_tic (stats);
+      ]])],
+      octave_cv_umfpack_need_suitesparse_time=no,
+      octave_cv_umfpack_need_suitesparse_time=yes)
+    AC_LANG_POP(C)
+  ])
+])
+dnl
+dnl Check for UMFPACK separately split complex matrix and RHS.
+dnl
+dnl Macro assumes that the check for umfpack has already been performed.
+dnl
+AC_DEFUN([OCTAVE_UMFPACK_SEPARATE_SPLIT], [
+  AC_MSG_CHECKING([for UMFPACK separate complex matrix and rhs split])
+  AC_CACHE_VAL([octave_cv_umfpack_separate_split],
+    [AC_RUN_IFELSE([AC_LANG_SOURCE([[
+        #include <stdint.h>
+        #include <stdlib.h>
+        #include <math.h>
+        #if defined (HAVE_SUITESPARSE_UMFPACK_H)
+        # include <suitesparse/umfpack.h>
+        #elif defined (HAVE_UFSPARSE_UMFPACK_H)
+        # include <ufsparse/umfpack.h>
+        #elif defined (HAVE_UMFPACK_UMFPACK_H)
+        # include <umfpack/umfpack.h>
+        #elif defined (HAVE_UMFPACK_H)
+        # include <umfpack.h>
+        #endif
+        #ifdef USE_64_BIT_IDX_T
+        typedef uint64_t idx_type;
+        #define UMFPACK_NAME(name) umfpack_zl_ ## name
+        #else
+        typedef int idx_type;
+        #define UMFPACK_NAME(name) umfpack_zi_ ## name
+        #endif
+        idx_type n = 5;
+        idx_type Ap[] = {0, 2, 5, 9, 10, 12};
+        idx_type Ai[]  = {0, 1, 0, 2, 4, 1, 2, 3, 4, 2, 1, 4};
+        double Ax[] = {2., 0., 3., 0., 3., 0., -1., 0., 4., 0., 4., 0., 
+                      -3., 0., 1., 0., 2., 0., 2., 0., 6., 0., 1., 0.};
+        double br[] = {8., 45., -3., 3., 19.};
+        double bi[] = {0., 0., 0., 0., 0.};
+        int main (void)
+        {
+          double *null = (double *) NULL ;
+          double *x = (double *)malloc (2 * n * sizeof(double));
+          idx_type i ;
+          void *Symbolic, *Numeric ;
+          (void) UMFPACK_NAME (symbolic) (n, n, Ap, Ai, Ax, null, &Symbolic, null, null) ;
+          (void) UMFPACK_NAME (numeric) (Ap, Ai, Ax, null, Symbolic, &Numeric, null, null) ;
+          UMFPACK_NAME (free_symbolic) (&Symbolic) ;
+          (void) UMFPACK_NAME (solve) (0, Ap, Ai, Ax, null, x, null, br, bi, 
+                                   Numeric, null, null) ;
+          UMFPACK_NAME (free_numeric) (&Numeric) ;
+          for (i = 0; i < n; i++, x+=2) 
+            if (fabs (*x - i - 1.) > 1.e-13)
+              return (1);
+          return (0) ;
+        }
+      ]])],
+      octave_cv_umfpack_separate_split=yes,
+      octave_cv_umfpack_separate_split=no,
+      octave_cv_umfpack_separate_split=yes)
+  ])
+  if test "$cross_compiling" = yes; then
+    AC_MSG_RESULT([$octave_cv_umfpack_separate_split assumed for cross compilation])
+  else
+    AC_MSG_RESULT([$octave_cv_umfpack_separate_split])
+  fi
+  if test $octave_cv_umfpack_separate_split = yes; then
+    AC_DEFINE(UMFPACK_SEPARATE_SPLIT, 1, 
+      [Define to 1 if the UMFPACK Complex solver allows matrix and RHS to be split independently.])
+  fi
+])
+dnl
+dnl Check for unordered map headers and whether tr1 namespace is
+dnl required.
+dnl
+AC_DEFUN([OCTAVE_UNORDERED_MAP_HEADERS], [
+  AC_CHECK_HEADERS([unordered_map], [],
+    [AC_CHECK_HEADERS([tr1/unordered_map])])
+  AC_CACHE_CHECK([whether unordered_map requires tr1 namespace], 
+    [octave_cv_header_require_tr1_namespace],
+    [AC_LANG_PUSH(C++)
+    octave_cv_header_require_tr1_namespace=no
+    if test $ac_cv_header_unordered_map = yes; then
+      ## Have <unordered_map>, but still have to check whether
+      ## tr1 namespace is required (like MSVC, for instance).
+      AC_COMPILE_IFELSE(
+        [AC_LANG_PROGRAM([[
+          #include <unordered_map>
+          ]], [[
+          std::unordered_map<int,int> m;
+        ]])],
+        octave_cv_header_require_tr1_namespace=no, 
+        octave_cv_header_require_tr1_namespace=yes)
+    elif test $ac_cv_header_tr1_unordered_map = yes; then
+      octave_cv_header_require_tr1_namespace=yes
+    fi
+    AC_LANG_POP(C++)
+  ])
+  if test $octave_cv_header_require_tr1_namespace = yes; then
+    AC_DEFINE(USE_UNORDERED_MAP_WITH_TR1, 1, 
+      [Define to 1 if unordered_map requires the use of tr1 namespace.])
+  fi
+])
 
-##############################################################################
-##############################################################################
-
-# pkg.m4 - Macros to locate and utilise pkg-config.            -*- Autoconf -*-
-# 
-# Copyright © 2004 Scott James Remnant <scott@netsplit.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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-# PKG_PROG_PKG_CONFIG([MIN-VERSION])
-# ----------------------------------
-AC_DEFUN([PKG_PROG_PKG_CONFIG],
-[m4_pattern_forbid([^_?PKG_[A-Z_]+$])
-m4_pattern_allow([^PKG_CONFIG(_PATH)?$])
-AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])dnl
-if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
-	AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
-fi
-if test -n "$PKG_CONFIG"; then
-	_pkg_min_version=m4_default([$1], [0.9.0])
-	AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version])
-	if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
-		AC_MSG_RESULT([yes])
-	else
-		AC_MSG_RESULT([no])
-		PKG_CONFIG=""
-	fi
-		
-fi[]dnl
-])# PKG_PROG_PKG_CONFIG
-
-# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
-#
-# Check to see whether a particular set of modules exists.  Similar
-# to PKG_CHECK_MODULES(), but does not set variables or print errors.
-#
-#
-# Similar to PKG_CHECK_MODULES, make sure that the first instance of
-# this or PKG_CHECK_MODULES is called, or make sure to call
-# PKG_CHECK_EXISTS manually
-# --------------------------------------------------------------
-AC_DEFUN([PKG_CHECK_EXISTS],
-[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
-if test -n "$PKG_CONFIG" && \
-    AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
-  m4_ifval([$2], [$2], [:])
-m4_ifvaln([$3], [else
-  $3])dnl
-fi])
-
-
-# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
-# ---------------------------------------------
-m4_define([_PKG_CONFIG],
-[if test -n "$PKG_CONFIG"; then
-    if test -n "$$1"; then
-        pkg_cv_[]$1="$$1"
-    else
-        PKG_CHECK_EXISTS([$3],
-                         [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`],
-			 [pkg_failed=yes])
-    fi
-else
-	pkg_failed=untried
-fi[]dnl
-])# _PKG_CONFIG
-
-# _PKG_SHORT_ERRORS_SUPPORTED
-# -----------------------------
-AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
-[AC_REQUIRE([PKG_PROG_PKG_CONFIG])
-if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
-        _pkg_short_errors_supported=yes
-else
-        _pkg_short_errors_supported=no
-fi[]dnl
-])# _PKG_SHORT_ERRORS_SUPPORTED
-
-
-# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
-# [ACTION-IF-NOT-FOUND])
-#
-#
-# Note that if there is a possibility the first call to
-# PKG_CHECK_MODULES might not happen, you should be sure to include an
-# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
-#
-#
-# --------------------------------------------------------------
-AC_DEFUN([PKG_CHECK_MODULES],
-[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
-AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
-AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl
-
-pkg_failed=no
-AC_MSG_CHECKING([for $1])
-
-_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2])
-_PKG_CONFIG([$1][_LIBS], [libs], [$2])
-
-m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS
-and $1[]_LIBS to avoid the need to call pkg-config.
-See the pkg-config man page for more details.])
-
-if test $pkg_failed = yes; then
-        _PKG_SHORT_ERRORS_SUPPORTED
-        if test $_pkg_short_errors_supported = yes; then
-	        $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --errors-to-stdout --print-errors "$2"`
-        else 
-	        $1[]_PKG_ERRORS=`$PKG_CONFIG --errors-to-stdout --print-errors "$2"`
-        fi
-	# Put the nasty error message in config.log where it belongs
-	echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD
-
-	ifelse([$4], , [AC_MSG_ERROR(dnl
-[Package requirements ($2) were not met:
-
-$$1_PKG_ERRORS
-
-Consider adjusting the PKG_CONFIG_PATH environment variable if you
-installed software in a non-standard prefix.
-
-_PKG_TEXT
-])],
-		[AC_MSG_RESULT([no])
-                $4])
-elif test $pkg_failed = untried; then
-	ifelse([$4], , [AC_MSG_FAILURE(dnl
-[The pkg-config script could not be found or is too old.  Make sure it
-is in your PATH or set the PKG_CONFIG environment variable to the full
-path to pkg-config.
-
-_PKG_TEXT
-
-To get pkg-config, see <http://pkg-config.freedesktop.org/>.])],
-		[$4])
-else
-	$1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
-	$1[]_LIBS=$pkg_cv_[]$1[]_LIBS
-        AC_MSG_RESULT([yes])
-	ifelse([$3], , :, [$3])
-fi[]dnl
-])# PKG_CHECK_MODULES
-
-dnl
-dnl External macros.
+dnl         End of macros written by Octave developers
+dnl ------------------------------------------------------------
 dnl
 
-m4_include([m4/ax_pthread.m4])
-m4_include([m4/ax_blas.m4])
-m4_include([m4/ax_blas_f77_func.m4])
-m4_include([m4/ax_lapack.m4])
+##############################################################################
--- a/m4/ax_blas.m4
+++ b/m4/ax_blas.m4
@@ -63,7 +63,7 @@
 #   modified version of the Autoconf Macro, you may extend this special
 #   exception to the GPL to apply to your modified version as well.
 
-#serial 11
+#serial 12
 
 AU_ALIAS([ACX_BLAS], [AX_BLAS])
 AC_DEFUN([AX_BLAS], [
@@ -130,7 +130,7 @@
 
 # BLAS in Intel MKL library?
 if test $ax_blas_ok = no; then
-	AC_CHECK_LIB(mkl, $sgemm, [ax_blas_ok=yes;BLAS_LIBS="-lmkl"])
+	AC_CHECK_LIB(mkl, $sgemm, [ax_blas_ok=yes;BLAS_LIBS="-lmkl -lguide -lpthread"],,[-lguide -lpthread])
 fi
 
 # BLAS in Apple vecLib library?
--- a/m4/ax_blas_f77_func.m4
+++ b/m4/ax_blas_f77_func.m4
@@ -52,7 +52,7 @@
 #   modified version of the Autoconf Macro, you may extend this special
 #   exception to the GPL to apply to your modified version as well.
 
-#serial 5
+#serial 8
 
 AU_ALIAS([ACX_BLAS_F77_FUNC], [AX_BLAS_F77_FUNC])
 AC_DEFUN([AX_BLAS_F77_FUNC], [
@@ -150,9 +150,9 @@
       real s,a(1),b(1),sdot
       a(1) = 1.0
       b(1) = 1.0
-c Generate -2**33 + 1, if possible
+c Generate -2**32 + 1, if possible
       n = 2
-      n = -4 * (n ** 30)
+      n = -4 ** (n ** 30)
       n = n + 1
       if (n >= 0) goto 1
 c This means we're on 64-bit integers. Check whether the BLAS is, too.
new file mode 100644
--- /dev/null
+++ b/m4/ax_compare_version.m4
@@ -0,0 +1,177 @@
+# ===========================================================================
+#    http://www.gnu.org/software/autoconf-archive/ax_compare_version.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+#   AX_COMPARE_VERSION(VERSION_A, OP, VERSION_B, [ACTION-IF-TRUE], [ACTION-IF-FALSE])
+#
+# DESCRIPTION
+#
+#   This macro compares two version strings. Due to the various number of
+#   minor-version numbers that can exist, and the fact that string
+#   comparisons are not compatible with numeric comparisons, this is not
+#   necessarily trivial to do in a autoconf script. This macro makes doing
+#   these comparisons easy.
+#
+#   The six basic comparisons are available, as well as checking equality
+#   limited to a certain number of minor-version levels.
+#
+#   The operator OP determines what type of comparison to do, and can be one
+#   of:
+#
+#    eq  - equal (test A == B)
+#    ne  - not equal (test A != B)
+#    le  - less than or equal (test A <= B)
+#    ge  - greater than or equal (test A >= B)
+#    lt  - less than (test A < B)
+#    gt  - greater than (test A > B)
+#
+#   Additionally, the eq and ne operator can have a number after it to limit
+#   the test to that number of minor versions.
+#
+#    eq0 - equal up to the length of the shorter version
+#    ne0 - not equal up to the length of the shorter version
+#    eqN - equal up to N sub-version levels
+#    neN - not equal up to N sub-version levels
+#
+#   When the condition is true, shell commands ACTION-IF-TRUE are run,
+#   otherwise shell commands ACTION-IF-FALSE are run. The environment
+#   variable 'ax_compare_version' is always set to either 'true' or 'false'
+#   as well.
+#
+#   Examples:
+#
+#     AX_COMPARE_VERSION([3.15.7],[lt],[3.15.8])
+#     AX_COMPARE_VERSION([3.15],[lt],[3.15.8])
+#
+#   would both be true.
+#
+#     AX_COMPARE_VERSION([3.15.7],[eq],[3.15.8])
+#     AX_COMPARE_VERSION([3.15],[gt],[3.15.8])
+#
+#   would both be false.
+#
+#     AX_COMPARE_VERSION([3.15.7],[eq2],[3.15.8])
+#
+#   would be true because it is only comparing two minor versions.
+#
+#     AX_COMPARE_VERSION([3.15.7],[eq0],[3.15])
+#
+#   would be true because it is only comparing the lesser number of minor
+#   versions of the two values.
+#
+#   Note: The characters that separate the version numbers do not matter. An
+#   empty string is the same as version 0. OP is evaluated by autoconf, not
+#   configure, so must be a string, not a variable.
+#
+#   The author would like to acknowledge Guido Draheim whose advice about
+#   the m4_case and m4_ifvaln functions make this macro only include the
+#   portions necessary to perform the specific comparison specified by the
+#   OP argument in the final configure script.
+#
+# LICENSE
+#
+#   Copyright (c) 2008 Tim Toolan <toolan@ele.uri.edu>
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved. This file is offered as-is, without any
+#   warranty.
+
+#serial 11
+
+dnl #########################################################################
+AC_DEFUN([AX_COMPARE_VERSION], [
+  AC_REQUIRE([AC_PROG_AWK])
+
+  # Used to indicate true or false condition
+  ax_compare_version=false
+
+  # Convert the two version strings to be compared into a format that
+  # allows a simple string comparison.  The end result is that a version
+  # string of the form 1.12.5-r617 will be converted to the form
+  # 0001001200050617.  In other words, each number is zero padded to four
+  # digits, and non digits are removed.
+  AS_VAR_PUSHDEF([A],[ax_compare_version_A])
+  A=`echo "$1" | sed -e 's/\([[0-9]]*\)/Z\1Z/g' \
+                     -e 's/Z\([[0-9]]\)Z/Z0\1Z/g' \
+                     -e 's/Z\([[0-9]][[0-9]]\)Z/Z0\1Z/g' \
+                     -e 's/Z\([[0-9]][[0-9]][[0-9]]\)Z/Z0\1Z/g' \
+                     -e 's/[[^0-9]]//g'`
+
+  AS_VAR_PUSHDEF([B],[ax_compare_version_B])
+  B=`echo "$3" | sed -e 's/\([[0-9]]*\)/Z\1Z/g' \
+                     -e 's/Z\([[0-9]]\)Z/Z0\1Z/g' \
+                     -e 's/Z\([[0-9]][[0-9]]\)Z/Z0\1Z/g' \
+                     -e 's/Z\([[0-9]][[0-9]][[0-9]]\)Z/Z0\1Z/g' \
+                     -e 's/[[^0-9]]//g'`
+
+  dnl # In the case of le, ge, lt, and gt, the strings are sorted as necessary
+  dnl # then the first line is used to determine if the condition is true.
+  dnl # The sed right after the echo is to remove any indented white space.
+  m4_case(m4_tolower($2),
+  [lt],[
+    ax_compare_version=`echo "x$A
+x$B" | sed 's/^ *//' | sort -r | sed "s/x${A}/false/;s/x${B}/true/;1q"`
+  ],
+  [gt],[
+    ax_compare_version=`echo "x$A
+x$B" | sed 's/^ *//' | sort | sed "s/x${A}/false/;s/x${B}/true/;1q"`
+  ],
+  [le],[
+    ax_compare_version=`echo "x$A
+x$B" | sed 's/^ *//' | sort | sed "s/x${A}/true/;s/x${B}/false/;1q"`
+  ],
+  [ge],[
+    ax_compare_version=`echo "x$A
+x$B" | sed 's/^ *//' | sort -r | sed "s/x${A}/true/;s/x${B}/false/;1q"`
+  ],[
+    dnl Split the operator from the subversion count if present.
+    m4_bmatch(m4_substr($2,2),
+    [0],[
+      # A count of zero means use the length of the shorter version.
+      # Determine the number of characters in A and B.
+      ax_compare_version_len_A=`echo "$A" | $AWK '{print(length)}'`
+      ax_compare_version_len_B=`echo "$B" | $AWK '{print(length)}'`
+
+      # Set A to no more than B's length and B to no more than A's length.
+      A=`echo "$A" | sed "s/\(.\{$ax_compare_version_len_B\}\).*/\1/"`
+      B=`echo "$B" | sed "s/\(.\{$ax_compare_version_len_A\}\).*/\1/"`
+    ],
+    [[0-9]+],[
+      # A count greater than zero means use only that many subversions
+      A=`echo "$A" | sed "s/\(\([[0-9]]\{4\}\)\{m4_substr($2,2)\}\).*/\1/"`
+      B=`echo "$B" | sed "s/\(\([[0-9]]\{4\}\)\{m4_substr($2,2)\}\).*/\1/"`
+    ],
+    [.+],[
+      AC_WARNING(
+        [illegal OP numeric parameter: $2])
+    ],[])
+
+    # Pad zeros at end of numbers to make same length.
+    ax_compare_version_tmp_A="$A`echo $B | sed 's/./0/g'`"
+    B="$B`echo $A | sed 's/./0/g'`"
+    A="$ax_compare_version_tmp_A"
+
+    # Check for equality or inequality as necessary.
+    m4_case(m4_tolower(m4_substr($2,0,2)),
+    [eq],[
+      test "x$A" = "x$B" && ax_compare_version=true
+    ],
+    [ne],[
+      test "x$A" != "x$B" && ax_compare_version=true
+    ],[
+      AC_WARNING([illegal OP parameter: $2])
+    ])
+  ])
+
+  AS_VAR_POPDEF([A])dnl
+  AS_VAR_POPDEF([B])dnl
+
+  dnl # Execute ACTION-IF-TRUE / ACTION-IF-FALSE.
+  if test "$ax_compare_version" = "true" ; then
+    m4_ifvaln([$4],[$4],[:])dnl
+    m4_ifvaln([$5],[else $5])dnl
+  fi
+]) dnl AX_COMPARE_VERSION
--- a/m4/ax_pthread.m4
+++ b/m4/ax_pthread.m4
@@ -33,6 +33,10 @@
 #   has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to that name
 #   (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
 #
+#   Also HAVE_PTHREAD_PRIO_INHERIT is defined if pthread is found and the
+#   PTHREAD_PRIO_INHERIT symbol is defined when compiling with
+#   PTHREAD_CFLAGS.
+#
 #   ACTION-IF-FOUND is a list of shell commands to run if a threads library
 #   is found, and ACTION-IF-NOT-FOUND is a list of commands to run it if it
 #   is not found. If ACTION-IF-FOUND is not specified, the default action
@@ -45,9 +49,12 @@
 #   Alejandro Forero Cuervo to the autoconf macro repository. We are also
 #   grateful for the helpful feedback of numerous users.
 #
+#   Updated for Autoconf 2.68 by Daniel Richard G.
+#
 # LICENSE
 #
 #   Copyright (c) 2008 Steven G. Johnson <stevenj@alum.mit.edu>
+#   Copyright (c) 2011 Daniel Richard G. <skunk@iSKUNK.ORG>
 #
 #   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
@@ -75,13 +82,12 @@
 #   modified version of the Autoconf Macro, you may extend this special
 #   exception to the GPL to apply to your modified version as well.
 
-#serial 9
+#serial 18
 
 AU_ALIAS([ACX_PTHREAD], [AX_PTHREAD])
 AC_DEFUN([AX_PTHREAD], [
 AC_REQUIRE([AC_CANONICAL_HOST])
-AC_LANG_SAVE
-AC_LANG_C
+AC_LANG_PUSH([C])
 ax_pthread_ok=no
 
 # We used to check for pthread.h first, but this fails if pthread.h
@@ -139,8 +145,8 @@
 # --thread-safe: KAI C++
 # pthread-config: use pthread-config program (for GNU Pth library)
 
-case "${host_cpu}-${host_os}" in
-        *solaris*)
+case ${host_os} in
+        solaris*)
 
         # On Solaris (at least, for some versions), libc contains stubbed
         # (non-functional) versions of the pthreads routines, so link-based
@@ -153,9 +159,9 @@
         ax_pthread_flags="-pthreads pthread -mt -pthread $ax_pthread_flags"
         ;;
 
-	*-darwin*)
-	ax_pthread_flags="-pthread $ax_pthread_flags"
-	;;
+        darwin*)
+        ax_pthread_flags="-pthread $ax_pthread_flags"
+        ;;
 esac
 
 if test x"$ax_pthread_ok" = xno; then
@@ -171,12 +177,12 @@
                 PTHREAD_CFLAGS="$flag"
                 ;;
 
-		pthread-config)
-		AC_CHECK_PROG(ax_pthread_config, pthread-config, yes, no)
-		if test x"$ax_pthread_config" = xno; then continue; fi
-		PTHREAD_CFLAGS="`pthread-config --cflags`"
-		PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
-		;;
+                pthread-config)
+                AC_CHECK_PROG(ax_pthread_config, pthread-config, yes, no)
+                if test x"$ax_pthread_config" = xno; then continue; fi
+                PTHREAD_CFLAGS="`pthread-config --cflags`"
+                PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
+                ;;
 
                 *)
                 AC_MSG_CHECKING([for the pthreads library -l$flag])
@@ -198,16 +204,17 @@
         # pthread_cleanup_push because it is one of the few pthread
         # functions on Solaris that doesn't have a non-functional libc stub.
         # We try pthread_create on general principles.
-        AC_TRY_LINK([#include <pthread.h>
-	             static void routine(void* a) {a=0;}
-	             static void* start_routine(void* a) {return a;}],
-                    [pthread_t th; pthread_attr_t attr;
-                     pthread_create(&th,0,start_routine,0);
-                     pthread_join(th, 0);
-                     pthread_attr_init(&attr);
-                     pthread_cleanup_push(routine, 0);
-                     pthread_cleanup_pop(0); ],
-                    [ax_pthread_ok=yes])
+        AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>
+                        static void routine(void *a) { a = 0; }
+                        static void *start_routine(void *a) { return a; }],
+                       [pthread_t th; pthread_attr_t attr;
+                        pthread_create(&th, 0, start_routine, 0);
+                        pthread_join(th, 0);
+                        pthread_attr_init(&attr);
+                        pthread_cleanup_push(routine, 0);
+                        pthread_cleanup_pop(0) /* ; */])],
+                [ax_pthread_ok=yes],
+                [])
 
         LIBS="$save_LIBS"
         CFLAGS="$save_CFLAGS"
@@ -230,12 +237,14 @@
         CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
 
         # Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
-	AC_MSG_CHECKING([for joinable pthread attribute])
-	attr_name=unknown
-	for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
-	    AC_TRY_LINK([#include <pthread.h>], [int attr=$attr; return attr;],
-                        [attr_name=$attr; break])
-	done
+        AC_MSG_CHECKING([for joinable pthread attribute])
+        attr_name=unknown
+        for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
+            AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>],
+                           [int attr = $attr; return attr /* ; */])],
+                [attr_name=$attr; break],
+                [])
+        done
         AC_MSG_RESULT($attr_name)
         if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then
             AC_DEFINE_UNQUOTED(PTHREAD_CREATE_JOINABLE, $attr_name,
@@ -245,24 +254,41 @@
 
         AC_MSG_CHECKING([if more special flags are required for pthreads])
         flag=no
-        case "${host_cpu}-${host_os}" in
-            *-aix* | *-freebsd* | *-darwin*) flag="-D_THREAD_SAFE";;
-            *solaris* | *-osf* | *-hpux*) flag="-D_REENTRANT";;
+        case ${host_os} in
+            aix* | freebsd* | darwin*) flag="-D_THREAD_SAFE";;
+            osf* | hpux*) flag="-D_REENTRANT";;
+            solaris*)
+            if test "$GCC" = "yes"; then
+                flag="-D_REENTRANT"
+            else
+                flag="-mt -D_REENTRANT"
+            fi
+            ;;
         esac
         AC_MSG_RESULT(${flag})
         if test "x$flag" != xno; then
             PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS"
         fi
 
+        AC_CACHE_CHECK([for PTHREAD_PRIO_INHERIT],
+            ax_cv_PTHREAD_PRIO_INHERIT, [
+                AC_LINK_IFELSE([
+                    AC_LANG_PROGRAM([[#include <pthread.h>]], [[int i = PTHREAD_PRIO_INHERIT;]])],
+                    [ax_cv_PTHREAD_PRIO_INHERIT=yes],
+                    [ax_cv_PTHREAD_PRIO_INHERIT=no])
+            ])
+        AS_IF([test "x$ax_cv_PTHREAD_PRIO_INHERIT" = "xyes"],
+            AC_DEFINE([HAVE_PTHREAD_PRIO_INHERIT], 1, [Have PTHREAD_PRIO_INHERIT.]))
+
         LIBS="$save_LIBS"
         CFLAGS="$save_CFLAGS"
 
         # More AIX lossage: must compile with xlc_r or cc_r
-	if test x"$GCC" != xyes; then
+        if test x"$GCC" != xyes; then
           AC_CHECK_PROGS(PTHREAD_CC, xlc_r cc_r, ${CC})
         else
           PTHREAD_CC=$CC
-	fi
+        fi
 else
         PTHREAD_CC="$CC"
 fi
@@ -279,5 +305,5 @@
         ax_pthread_ok=no
         $2
 fi
-AC_LANG_RESTORE
+AC_LANG_POP
 ])dnl AX_PTHREAD
--- a/m4/module.mk
+++ b/m4/module.mk
@@ -2,6 +2,7 @@
   m4/module.mk \
   m4/ax_blas.m4 \
   m4/ax_blas_f77_func.m4 \
+  m4/ax_compare_version.m4 \
   m4/ax_lapack.m4	\
   m4/ax_pthread.m4 \
   m4/gnulib-cache.m4 \
@@ -9,4 +10,5 @@
   m4/ltoptions.m4 \
   m4/ltsugar.m4 \
   m4/ltversion.m4 \
-  m4/lt~obsolete.m4
+  m4/lt~obsolete.m4 \
+  m4/pkg.m4
new file mode 100644
--- /dev/null
+++ b/m4/pkg.m4
@@ -0,0 +1,157 @@
+# pkg.m4 - Macros to locate and utilise pkg-config.            -*- Autoconf -*-
+# 
+# Copyright © 2004 Scott James Remnant <scott@netsplit.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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# PKG_PROG_PKG_CONFIG([MIN-VERSION])
+# ----------------------------------
+AC_DEFUN([PKG_PROG_PKG_CONFIG],
+[m4_pattern_forbid([^_?PKG_[A-Z_]+$])
+m4_pattern_allow([^PKG_CONFIG(_PATH)?$])
+AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])dnl
+if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
+	AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
+fi
+if test -n "$PKG_CONFIG"; then
+	_pkg_min_version=m4_default([$1], [0.9.0])
+	AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version])
+	if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
+		AC_MSG_RESULT([yes])
+	else
+		AC_MSG_RESULT([no])
+		PKG_CONFIG=""
+	fi
+		
+fi[]dnl
+])# PKG_PROG_PKG_CONFIG
+
+# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
+#
+# Check to see whether a particular set of modules exists.  Similar
+# to PKG_CHECK_MODULES(), but does not set variables or print errors.
+#
+#
+# Similar to PKG_CHECK_MODULES, make sure that the first instance of
+# this or PKG_CHECK_MODULES is called, or make sure to call
+# PKG_CHECK_EXISTS manually
+# --------------------------------------------------------------
+AC_DEFUN([PKG_CHECK_EXISTS],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
+if test -n "$PKG_CONFIG" && \
+    AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
+  m4_ifval([$2], [$2], [:])
+m4_ifvaln([$3], [else
+  $3])dnl
+fi])
+
+
+# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
+# ---------------------------------------------
+m4_define([_PKG_CONFIG],
+[if test -n "$PKG_CONFIG"; then
+    if test -n "$$1"; then
+        pkg_cv_[]$1="$$1"
+    else
+        PKG_CHECK_EXISTS([$3],
+                         [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`],
+			 [pkg_failed=yes])
+    fi
+else
+	pkg_failed=untried
+fi[]dnl
+])# _PKG_CONFIG
+
+# _PKG_SHORT_ERRORS_SUPPORTED
+# -----------------------------
+AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])
+if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
+        _pkg_short_errors_supported=yes
+else
+        _pkg_short_errors_supported=no
+fi[]dnl
+])# _PKG_SHORT_ERRORS_SUPPORTED
+
+
+# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
+# [ACTION-IF-NOT-FOUND])
+#
+#
+# Note that if there is a possibility the first call to
+# PKG_CHECK_MODULES might not happen, you should be sure to include an
+# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
+#
+#
+# --------------------------------------------------------------
+AC_DEFUN([PKG_CHECK_MODULES],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
+AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
+AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl
+
+pkg_failed=no
+AC_MSG_CHECKING([for $1])
+
+_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2])
+_PKG_CONFIG([$1][_LIBS], [libs], [$2])
+
+m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS
+and $1[]_LIBS to avoid the need to call pkg-config.
+See the pkg-config man page for more details.])
+
+if test $pkg_failed = yes; then
+        _PKG_SHORT_ERRORS_SUPPORTED
+        if test $_pkg_short_errors_supported = yes; then
+	        $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --errors-to-stdout --print-errors "$2"`
+        else 
+	        $1[]_PKG_ERRORS=`$PKG_CONFIG --errors-to-stdout --print-errors "$2"`
+        fi
+	# Put the nasty error message in config.log where it belongs
+	echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD
+
+	ifelse([$4], , [AC_MSG_ERROR(dnl
+[Package requirements ($2) were not met:
+
+$$1_PKG_ERRORS
+
+Consider adjusting the PKG_CONFIG_PATH environment variable if you
+installed software in a non-standard prefix.
+
+_PKG_TEXT
+])],
+		[AC_MSG_RESULT([no])
+                $4])
+elif test $pkg_failed = untried; then
+	ifelse([$4], , [AC_MSG_FAILURE(dnl
+[The pkg-config script could not be found or is too old.  Make sure it
+is in your PATH or set the PKG_CONFIG environment variable to the full
+path to pkg-config.
+
+_PKG_TEXT
+
+To get pkg-config, see <http://pkg-config.freedesktop.org/>.])],
+		[$4])
+else
+	$1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
+	$1[]_LIBS=$pkg_cv_[]$1[]_LIBS
+        AC_MSG_RESULT([yes])
+	ifelse([$3], , :, [$3])
+fi[]dnl
+])# PKG_CHECK_MODULES
new file mode 100644
--- /dev/null
+++ b/oct-conf-post.in.h
@@ -0,0 +1,168 @@
+/*
+
+Copyright (C) 1993-2012 John W. Eaton
+
+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 (GNULIB_NAMESPACE)
+#define GNULIB_NAMESPACE gnulib
+#endif
+
+#if defined (__GNUC__)
+#define GCC_ATTR_DEPRECATED __attribute__ ((__deprecated__))
+#define HAVE_ATTR_DEPRECATED
+
+#define GCC_ATTR_NORETURN __attribute__ ((__noreturn__))
+#define HAVE_ATTR_NORETURN
+
+#define GCC_ATTR_UNUSED __attribute__ ((__unused__))
+#define HAVE_ATTR_UNUSED
+#else
+#define GCC_ATTR_DEPRECATED
+#define GCC_ATTR_NORETURN
+#define GCC_ATTR_UNUSED
+#endif
+
+#define X_CAST(T, E) (T) (E)
+
+#if defined (CXX_BROKEN_REINTERPRET_CAST)
+#define FCN_PTR_CAST(T, E) (T) (E)
+#else
+#define FCN_PTR_CAST(T, E) reinterpret_cast<T> (E)
+#endif
+
+#if ! defined (HAVE_DEV_T)
+typedef short dev_t;
+#endif
+
+#if ! defined (HAVE_INO_T)
+typedef unsigned long ino_t;
+#endif
+
+#if defined (_MSC_VER)
+#define __WIN32__
+#define WIN32
+/* missing parameters in macros */
+#pragma warning (disable: 4003)
+/* missing implementations in template instantiation */
+#pragma warning (disable: 4996)
+/* deprecated function names (FIXME?) */
+#pragma warning (disable: 4661)
+#endif
+
+#if defined (__WIN32__) && ! defined (__CYGWIN__)
+#define OCTAVE_HAVE_WINDOWS_FILESYSTEM 1
+#elif defined (__CYGWIN__)
+#define OCTAVE_HAVE_WINDOWS_FILESYSTEM 1
+#define OCTAVE_HAVE_POSIX_FILESYSTEM 1
+#else
+#define OCTAVE_HAVE_POSIX_FILESYSTEM 1
+#endif
+
+/* Define to 1 if we expect to have <windows.h>, Sleep, etc. */
+#if defined (__WIN32__) && ! defined (__CYGWIN__)
+#define OCTAVE_USE_WINDOWS_API 1
+#endif
+
+#if defined (__APPLE__) && defined (__MACH__)
+#define OCTAVE_USE_OS_X_API 1
+#endif
+
+/* sigsetjmp is a macro, not a function. */
+#if defined (sigsetjmp) && defined (HAVE_SIGLONGJMP)
+#define OCTAVE_HAVE_SIG_JUMP
+#endif
+
+#if defined (_UNICOS)
+#define F77_USES_CRAY_CALLING_CONVENTION
+#endif
+
+#if 0
+#define F77_USES_VISUAL_FORTRAN_CALLING_CONVENTION
+#endif
+
+#ifdef USE_64_BIT_IDX_T
+#define SIZEOF_OCTAVE_IDX_TYPE SIZEOF_INT64_T
+#else
+#define SIZEOF_OCTAVE_IDX_TYPE SIZEOF_INT
+#endif
+
+/* To be able to use long doubles for 64-bit mixed arithmetics, we need
+   them at least 80 bits wide and we need roundl declared in math.h.
+   FIXME: Maybe substitute this by a more precise check in the future?  */
+#if (SIZEOF_LONG_DOUBLE >= 10) && defined (HAVE_ROUNDL)
+#define OCTAVE_INT_USE_LONG_DOUBLE
+#endif
+
+#define OCTAVE_EMPTY_CPP_ARG
+
+/* oct-dlldefs.h */
+
+#if defined (_MSC_VER)
+#define OCTAVE_EXPORT __declspec(dllexport)
+#define OCTAVE_IMPORT __declspec(dllimport)
+#else
+/* All other compilers, at least for now. */
+#define OCTAVE_EXPORT
+#define OCTAVE_IMPORT
+#endif
+
+/* API macro for libcruft */
+#ifdef CRUFT_DLL
+#define CRUFT_API OCTAVE_EXPORT
+#else
+#define CRUFT_API OCTAVE_IMPORT
+#endif
+
+/* API macro for liboctave */
+#ifdef OCTAVE_DLL
+#define OCTAVE_API OCTAVE_EXPORT
+#else
+#define OCTAVE_API OCTAVE_IMPORT
+#endif
+
+/* API macro for libinterp */
+#ifdef OCTINTERP_DLL
+#define OCTINTERP_API OCTAVE_EXPORT
+#else
+#define OCTINTERP_API OCTAVE_IMPORT
+#endif
+
+/* API macro for libinterp/graphics */
+#ifdef OCTGRAPHICS_DLL
+#define OCTGRAPHICS_API OCTAVE_EXPORT
+#else
+#define OCTGRAPHICS_API OCTAVE_IMPORT
+#endif
+
+/* API macro for libgui */
+#ifdef OCTGUI_DLL
+#define OCTGUI_API OCTAVE_EXPORT
+#else
+#define OCTGUI_API OCTAVE_IMPORT
+#endif
+
+/* oct-types.h */
+
+#include <stdint.h>
+
+typedef OCTAVE_IDX_TYPE octave_idx_type;
+
+/* Tag indicating Octave config.h has been included */
+#define OCTAVE_CONFIG_INCLUDED 1
--- a/run-octave.in
+++ b/run-octave.in
@@ -32,7 +32,7 @@
 
 d1="$top_srcdir/scripts"
 d2="$builddir/scripts"
-d3="$builddir/src"
+d3="$builddir/libinterp"
 
 d1_list=`$FIND "$d1" -type d -a ! \( \( -name private -o -name '@*' \) -a -prune \) -exec echo '{}' ';' | $SED 's/$/:/'`
 d2_list=`$FIND "$d2" -type d -a ! \( \( -name private -o -name '@*' \) -a -prune \) -exec echo '{}' ';' | $SED 's/$/:/'`
@@ -42,9 +42,13 @@
 d2_path=`echo "$d2_list" | $AWK '{ t = (s $0); s = t; } END { sub (/:$/, "", s); print s; }'`
 d3_path=`echo "$d3_list" | $AWK '{ t = (s $0); s = t; } END { sub (/:$/, "", s); print s; }'`
 
+octave_executable="$builddir/src/octave"
+
 LOADPATH="$d1_path:$d2_path:$d3_path"
 IMAGEPATH="$top_srcdir/scripts/image"
 DOCFILE="$builddir/doc/interpreter/doc-cache"
+BUILT_IN_DOCSTRINGS_FILE="$builddir/libinterp/DOCSTRINGS"
+TEXIMACROSFILE="$top_srcdir/doc/interpreter/macros.texi"
 INFOFILE="$top_srcdir/doc/interpreter/octave.info"
 
 ## Checking for string equality below with prepended x's in order to
@@ -57,17 +61,29 @@
     ## Frontends for gdb (e.g. Emacs's GUD mode) need --annotate=3
     driver="gdb --annotate=3 --args"
     shift
+  elif [ "x$1" = "x-gud2" ]; then
+    ## The latest version of gud needs -i=mi. There isn't a good way to check
+    ## this at configure time, so we just add a gud2 flag
+    driver="gdb -i=mi --args"
+    shift
   elif [ "x$1" = "x-valgrind" ]; then
     driver="valgrind --tool=memcheck"
     shift
   elif [ "x$1" = "x-strace" ]; then
     driver="strace -o octave.trace"
     shift
+  elif [ "x$1" = "x-cli" ]; then
+    octave_executable="$builddir/src/octave-cli"
+    shift
   fi
 fi
 
 OCTAVE_SITE_INITFILE="$top_srcdir/scripts/startup/main-rcfile" \
+OCTAVE_DEFAULT_QT_SETTINGS="$builddir/libgui/default-qt-settings" \
+OCTAVE_LOCALE_DIR="$builddir/libgui/languages" \
+OCTAVE_JAVA_DIR="$builddir/scripts/java" \
   exec $builddir/libtool --mode=execute $driver \
-    "$builddir/src/octave" --no-init-path --path="$LOADPATH" \
+    "$octave_executable" --no-init-path --path="$LOADPATH" \
     --image-path="$IMAGEPATH" --doc-cache-file="$DOCFILE" \
-    --info-file="$INFOFILE" "$@"
+    --built-in-docstrings-file="$BUILT_IN_DOCSTRINGS_FILE" \
+    --texi-macros-file="$TEXIMACROSFILE" --info-file="$INFOFILE" "$@"
--- a/scripts/@ftp/ascii.m
+++ b/scripts/@ftp/ascii.m
@@ -18,7 +18,11 @@
 
 ## -*- texinfo -*-
 ## @deftypefn {Function File} {} ascii (@var{f})
-## Put the FTP connection @var{f} into ascii mode.
+## Set the FTP connection @var{f} to use ASCII mode for transfers.
+## ASCII mode is only appropriate for text files as it will convert
+## the remote host's newline representation to the local host's newline
+## representation.
+##
 ## @var{f} is an FTP object returned by the @code{ftp} function.
 ## @end deftypefn
 
--- a/scripts/@ftp/binary.m
+++ b/scripts/@ftp/binary.m
@@ -18,7 +18,10 @@
 
 ## -*- texinfo -*-
 ## @deftypefn {Function File} {} binary (@var{f})
-## Put the FTP connection @var{f} into binary mode.
+## Set the FTP connection @var{f} to use binary mode for transfers.
+## In binary mode there is no conversion of newlines from the remote
+## representation to the local representation.
+##
 ## @var{f} is an FTP object returned by the @code{ftp} function.
 ## @end deftypefn
 
--- a/scripts/@ftp/cd.m
+++ b/scripts/@ftp/cd.m
@@ -19,6 +19,7 @@
 ## -*- texinfo -*-
 ## @deftypefn {Function File} {} cd (@var{f}, @var{path})
 ## Set the remote directory to @var{path} on the FTP connection @var{f}.
+##
 ## @var{f} is an FTP object returned by the @code{ftp} function.
 ## @end deftypefn
 
--- a/scripts/@ftp/close.m
+++ b/scripts/@ftp/close.m
@@ -18,7 +18,8 @@
 
 ## -*- texinfo -*-
 ## @deftypefn {Function File} {} close (@var{f})
-## Close the FTP connection represented by the given FTP object @var{f}.
+## Close the FTP connection represented by the FTP object @var{f}.
+##
 ## @var{f} is an FTP object returned by the @code{ftp} function.
 ## @end deftypefn
 
--- a/scripts/@ftp/delete.m
+++ b/scripts/@ftp/delete.m
@@ -18,7 +18,8 @@
 
 ## -*- texinfo -*-
 ## @deftypefn {Function File} {} delete (@var{f}, @var{file})
-## Delete the remote file @var{file}, over the FTP connection @var{f}.
+## Delete the remote file @var{file} over the FTP connection @var{f}.
+##
 ## @var{f} is an FTP object returned by the @code{ftp} function.
 ## @end deftypefn
 
--- a/scripts/@ftp/dir.m
+++ b/scripts/@ftp/dir.m
@@ -19,7 +19,9 @@
 ## -*- texinfo -*-
 ## @deftypefn {Function File} {@var{lst} =} dir (@var{f})
 ## List the current directory in verbose form for the FTP connection
-## @var{f}.  @var{f} is an FTP object returned by the @code{ftp} function.
+## @var{f}.
+##
+## @var{f} is an FTP object returned by the @code{ftp} function.
 ## @end deftypefn
 
 function lst = dir (f)
--- a/scripts/@ftp/ftp.m
+++ b/scripts/@ftp/ftp.m
@@ -23,23 +23,38 @@
 ## If @var{username} and @var{password} are not specified, user "anonymous"
 ## with no password is used.  The returned FTP object @var{f} represents the
 ## established FTP connection.
+##
+## The list of actions for an FTP object are shown below.  All functions
+## require an FTP object as the first argument.
+##
+## @multitable @columnfractions 0.15 0.8
+## @headitem Method @tab Description
+## @item ascii @tab Set transfer type to ascii
+## @item binary @tab Set transfer type to binary
+## @item cd @tab Change remote working directory 
+## @item close @tab Close FTP connection
+## @item delete @tab Delete remote file 
+## @item dir @tab List remote directory contents 
+## @item mget @tab Download remote files
+## @item mkdir @tab Create remote directory
+## @item mput @tab Upload local files
+## @item rename @tab Rename remote file or directory
+## @item rmdir @tab Remove remote directory
+## @end multitable
+## 
 ## @end deftypefn
 
-function obj = ftp (host, username = "anonymous", password = "")
-  if (nargin == 0)
-    p.host = "";
-    p.username = username;
-    p.password = password;
-    p.curlhandle = tmpnam ("ftp-");
-    obj = class (p, "ftp");
-  elseif (nargin == 1 && strcmp (class (host), "ftp"))
-    obj = host;
+function obj = ftp (host = "", username = "anonymous", password = "")
+  if (nargin == 1 && isa (host, "ftp"))
+    obj = host;   # Copy constructor
   else
     p.host = host;
     p.username = username;
     p.password = password;
     p.curlhandle = tmpnam ("ftp-");
-    __ftp__ (p.curlhandle, host, username, password);
+    if (nargin > 0)
+      __ftp__ (p.curlhandle, host, username, password);
+    endif
     obj = class (p, "ftp");
   endif
 endfunction
--- a/scripts/@ftp/loadobj.m
+++ b/scripts/@ftp/loadobj.m
@@ -30,7 +30,7 @@
     b = rmfield (b, "dir");
   elseif (isfield (b, "remotePwd"))
     ## FIXME: Can we read matlab java stringBuffer objects?
-    warning ("can not change remote directory in loqded FTP object");
+    warning ("can not change remote directory in loaded FTP object");
     b = rmfield (b, "remotePwd");
   endif
 endfunction
--- a/scripts/@ftp/mget.m
+++ b/scripts/@ftp/mget.m
@@ -19,7 +19,7 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {} mget (@var{f}, @var{file})
 ## @deftypefnx {Function File} {} mget (@var{f}, @var{dir})
-## @deftypefnx {Function File} {} mget (@dots{}, @var{target})
+## @deftypefnx {Function File} {} mget (@var{f}, @var{remote_name}, @var{target})
 ## Download a remote file @var{file} or directory @var{dir} to the local
 ## directory on the FTP connection @var{f}.  @var{f} is an FTP object
 ## returned by the @code{ftp} function.
@@ -28,8 +28,8 @@
 ## files or directories on the remote server that match will be downloaded.
 ##
 ## If a third argument @var{target} is given, then a single file or
-## directory will be downloaded with the name @var{target} to the local
-## directory.
+## directory will be downloaded to the local directory and the local name
+## will be changed to @var{target}.
 ## @end deftypefn
 
 function mget (f, file)
--- a/scripts/@ftp/mkdir.m
+++ b/scripts/@ftp/mkdir.m
@@ -19,6 +19,7 @@
 ## -*- texinfo -*-
 ## @deftypefn {Function File} {} mkdir (@var{f}, @var{path})
 ## Create the remote directory @var{path}, over the FTP connection @var{f}.
+##
 ## @var{f} is an FTP object returned by the @code{ftp} function.
 ## @end deftypefn
 
--- a/scripts/@ftp/mput.m
+++ b/scripts/@ftp/mput.m
@@ -22,7 +22,7 @@
 ## the FTP connection @var{f}.  @var{f} is an FTP object returned by the
 ## ftp function.
 ##
-## The argument @var{file} is passed by the @dfn{glob} function and any
+## The argument @var{file} is passed through the @code{glob} function and any
 ## files that match the wildcards in @var{file} will be uploaded.
 ## @end deftypefn
 
--- a/scripts/@ftp/rename.m
+++ b/scripts/@ftp/rename.m
@@ -19,8 +19,9 @@
 ## -*- texinfo -*-
 ## @deftypefn {Function File} {} rename (@var{f}, @var{oldname}, @var{newname})
 ## Rename or move the remote file or directory @var{oldname} to @var{newname},
-##  over the FTP connection @var{f}.  @var{f} is an FTP object returned by the
-## ftp function.
+## over the FTP connection @var{f}.
+##
+## @var{f} is an FTP object returned by the ftp function.
 ## @end deftypefn
 
 function rename (f, oldname, newname)
--- a/scripts/@ftp/rmdir.m
+++ b/scripts/@ftp/rmdir.m
@@ -19,6 +19,7 @@
 ## -*- texinfo -*-
 ## @deftypefn {Function File} {} rmdir (@var{f}, @var{path})
 ## Remove the remote directory @var{path}, over the FTP connection @var{f}.
+##
 ## @var{f} is an FTP object returned by the @code{ftp} function.
 ## @end deftypefn
 
--- a/scripts/Makefile.am
+++ b/scripts/Makefile.am
@@ -1,4 +1,4 @@
-# Makefile for octave's scripts directory
+# Makefile for Octave's scripts directory
 #
 # Copyright (C) 1993-2012 John W. Eaton
 #
@@ -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
@@ -67,17 +74,18 @@
 include strings/module.mk
 include testfun/module.mk
 include time/module.mk
+include ui/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 +126,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 $@
@@ -202,6 +214,10 @@
 	$(srcdir)/mk-pkg-add $(srcdir) $(time_FCN_FILES) -- $(time_GEN_FCN_FILES) > $@-t
 	mv $@-t $@
 
+ui/PKG_ADD: $(ui_FCN_FILES) $(ui_GEN_FCN_FILES) ui/$(octave_dirstamp) mk-pkg-add
+	$(srcdir)/mk-pkg-add $(srcdir) $(ui_FCN_FILES) -- $(ui_GEN_FCN_FILES) > $@-t
+	mv $@-t $@
+
 $(@ftp_GEN_FCN_FILES): @ftp/$(octave_dirstamp)
 $(audio_GEN_FCN_FILES): audio/$(octave_dirstamp)
 $(deprecated_GEN_FCN_FILES): deprecated/$(octave_dirstamp)
@@ -211,6 +227,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)
@@ -232,6 +249,7 @@
 $(strings_GEN_FCN_FILES): strings/$(octave_dirstamp)
 $(testfun_GEN_FCN_FILES): testfun/$(octave_dirstamp)
 $(time_GEN_FCN_FILES): time/$(octave_dirstamp)
+$(ui_GEN_FCN_FILES): ui/$(octave_dirstamp)
 
 @ftp/$(octave_dirstamp):
 	$(MKDIR_P) @ftp
@@ -260,6 +278,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)
@@ -323,6 +344,9 @@
 time/$(octave_dirstamp):
 	$(MKDIR_P) time
 	: > time/$(octave_dirstamp)
+ui/$(octave_dirstamp):
+	$(MKDIR_P) ui
+	: > ui/$(octave_dirstamp)
 
 if AMCOND_BUILD_DOCS
 
@@ -371,6 +395,12 @@
 	  done ) | ../run-octave -qf
 .PHONY: check-missing-semicolon
 
+## Add rule to generate ctags.
+## Automake would normally generate such a rule, but only if there is a
+## xxx_SOURCES target
+ctags:
+	ctags $(addprefix $(srcdir)/, $(FCN_FILES)) $(GEN_FCN_FILES)
+
 install-data-local: install-startup-files install-pkg-add
 
 uninstall-local: uninstall-startup-files uninstall-pkg-add
@@ -417,6 +447,12 @@
 	done
 .PHONY: uninstall-pkg-add
 
+if AMCOND_HAVE_JAVA
+else
+dist-hook:
+	@echo "Packaging distribution requires Java." ; exit 1;
+endif
+
 EXTRA_DIST += \
   $(IMAGES) \
   $(FCN_FILES) \
@@ -426,10 +462,14 @@
   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
--- a/scripts/audio/lin2mu.m
+++ b/scripts/audio/lin2mu.m
@@ -62,7 +62,7 @@
   endif
 
   ## Determine sign of x, set sign(0) = 1.
-  sig = sign(x) + (x == 0);
+  sig = sign (x) + (x == 0);
 
   ## Take absolute value of x, but force it to be smaller than 32636;
   ## add bias.
--- a/scripts/audio/loadaudio.m
+++ b/scripts/audio/loadaudio.m
@@ -63,7 +63,7 @@
       [X, c] = fread (num, inf, "short");
     endif
   elseif (strcmp (ext, "mu") || strcmp (ext, "au")
-          || strcmp (ext, "snd") || strcmp(ext, "ul"))
+          || strcmp (ext, "snd") || strcmp (ext, "ul"))
     [Y, c] = fread (num, inf, "uchar");
     ## remove file header
     m = find (Y(1:64) == 0, 1, "last");
--- a/scripts/audio/mu2lin.m
+++ b/scripts/audio/mu2lin.m
@@ -41,21 +41,21 @@
     print_usage ();
   endif
 
-  ulaw = [32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956, \
-          23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, \
-          15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412, \
-          11900, 11388, 10876, 10364,  9852,  9340,  8828,  8316, \
-           7932,  7676,  7420,  7164,  6908,  6652,  6396,  6140, \
-           5884,  5628,  5372,  5116,  4860,  4604,  4348,  4092, \
-           3900,  3772,  3644,  3516,  3388,  3260,  3132,  3004, \
-           2876,  2748,  2620,  2492,  2364,  2236,  2108,  1980, \
-           1884,  1820,  1756,  1692,  1628,  1564,  1500,  1436, \
-           1372,  1308,  1244,  1180,  1116,  1052,   988,   924, \
-            876,   844,   812,   780,   748,   716,   684,   652, \
-            620,   588,   556,   524,   492,   460,   428,   396, \
-            372,   356,   340,   324,   308,   292,   276,   260, \
-            244,   228,   212,   196,   180,   164,   148,   132, \
-            120,   112,   104,    96,    88,    80,    72,    64, \
+  ulaw = [32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956, ...
+          23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, ...
+          15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412, ...
+          11900, 11388, 10876, 10364,  9852,  9340,  8828,  8316, ...
+           7932,  7676,  7420,  7164,  6908,  6652,  6396,  6140, ...
+           5884,  5628,  5372,  5116,  4860,  4604,  4348,  4092, ...
+           3900,  3772,  3644,  3516,  3388,  3260,  3132,  3004, ...
+           2876,  2748,  2620,  2492,  2364,  2236,  2108,  1980, ...
+           1884,  1820,  1756,  1692,  1628,  1564,  1500,  1436, ...
+           1372,  1308,  1244,  1180,  1116,  1052,   988,   924, ...
+            876,   844,   812,   780,   748,   716,   684,   652, ...
+            620,   588,   556,   524,   492,   460,   428,   396, ...
+            372,   356,   340,   324,   308,   292,   276,   260, ...
+            244,   228,   212,   196,   180,   164,   148,   132, ...
+            120,   112,   104,    96,    88,    80,    72,    64, ...
              56,    48,    40,    32,    24,    16,     8,     0 ];
 
   ulaw = [ -ulaw, ulaw ];
--- a/scripts/audio/playaudio.m
+++ b/scripts/audio/playaudio.m
@@ -47,7 +47,7 @@
       fclose (fid);
       [status, out] = system (sprintf ('cat "%s" > /dev/dsp', file));
       if (status != 0)
-        system (sprintf ("paplay --raw \"%s\"", file))
+        system (sprintf ("paplay --raw \"%s\"", file));
       endif
     unwind_protect_cleanup
       unlink (file);
@@ -62,12 +62,12 @@
     if (any (strcmp (ext, {"lin", "raw"})))
       [status, out] = system (sprintf ('cat "%s" > /dev/dsp', name));
       if (status != 0)
-        system (sprintf ('paplay --raw "%s"', name))
+        system (sprintf ('paplay --raw "%s"', name));
       endif
     elseif (any (strcmp (ext, {"mu", "au" "snd", "ul"})))
       [status, out] = system (sprintf ('cat "%s" > /dev/audio', name));
       if (status != 0)
-        system (sprintf ('paplay "%s"', name))
+        system (sprintf ('paplay "%s"', name));
       endif
     else
       error ("playaudio: unsupported extension '%s'", ext);
--- a/scripts/audio/wavread.m
+++ b/scripts/audio/wavread.m
@@ -17,23 +17,32 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {@var{y} =} wavread (@var{filename})
+## @deftypefn  {Function File} {@var{y} =} wavread (@var{filename})
+## @deftypefnx {Function File} {[@var{y}, @var{Fs}, @var{bps}] =} wavread (@var{filename})
+## @deftypefnx {Function File} {[@dots{}] =} wavread (@var{filename}, @var{n})
+## @deftypefnx {Function File} {[@dots{}] =} wavread (@var{filename}, [@var{n1} @var{n2}])
+## @deftypefnx {Function File} {[@var{samples}, @var{channels}] =} wavread (@var{filename}, "size")
+## 
 ## Load the RIFF/WAVE sound file @var{filename}, and return the samples
 ## in vector @var{y}.  If the file contains multichannel data, then
 ## @var{y} is a matrix with the channels represented as columns.
 ##
-## @deftypefnx {Function File} {[@var{y}, @var{Fs}, @var{bps}] =} wavread (@var{filename})
+## @code{[@var{y}, @var{Fs}, @var{bps}] = wavread (@var{filename})}
+##
 ## Additionally return the sample rate (@var{fs}) in Hz and the number of bits
 ## per sample (@var{bps}).
 ##
-## @deftypefnx {Function File} {[@dots{}] =} wavread (@var{filename}, @var{n})
+## @code{[@dots{}] = wavread (@var{filename}, @var{n})}
+##
 ## Read only the first @var{n} samples from each channel.
 ##
-## @deftypefnx {Function File} {[@dots{}] =} wavread (@var{filename}, @var{n1} @var{n2})
+## @code{wavread (@var{filename}, [@var{n1} @var{n2}])}
+##
 ## Read only samples @var{n1} through @var{n2} from each channel.
 ##
-## @deftypefnx {Function File} {[@var{samples}, @var{channels}] =} wavread (@var{filename}, "size")
-## Return the number of samples (@var{n}) and channels (@var{ch})
+## @code{[@var{samples}, @var{channels}] = wavread (@var{filename}, "size")}
+##
+## Return the number of samples (@var{n}) and number of channels (@var{ch})
 ## instead of the audio data.
 ## @seealso{wavwrite}
 ## @end deftypefn
@@ -76,6 +85,7 @@
     if (riff_size == -1)
       error ("wavread: file contains no RIFF chunk");
     endif
+    riff_size = min (riff_size, file_size - riff_pos);
 
     riff_type = char (fread (fid, 4))';
     if (! strcmp (riff_type, "WAVE"))
@@ -87,7 +97,7 @@
     ## Find format chunk inside the RIFF chunk.
     fseek (fid, riff_pos, "bof");
     fmt_size = find_chunk (fid, "fmt ", riff_size);
-    fmt_pos = ftell(fid);
+    fmt_pos = ftell (fid);
     if (fmt_size == -1)
       error ("wavread: file contains no format chunk");
     endif
@@ -100,6 +110,7 @@
     if (data_size == -1)
       error ("wavread: file contains no data chunk");
     endif
+    data_size = min (data_size, file_size - data_pos);
 
     ### Read format chunk.
     fseek (fid, fmt_pos, "bof");
@@ -196,7 +207,7 @@
   endif
 
   if (bits_per_sample == 24)
-    yi = reshape (yi, 3, rows(yi)/3)';
+    yi = reshape (yi, 3, rows (yi) / 3)';
     yi(yi(:,3) >= 128, 3) -= 256;
     yi = yi * [1; 256; 65536];
   endif
@@ -244,6 +255,7 @@
   endif
 endfunction
 
-## Mark file as being tested.  Tests for wavread/wavwrite pair are in
-## wavwrite.m
-%!assert(1)
+
+## Mark file as tested.  Tests for wavread/wavwrite pair are in wavwrite.m.
+%!assert (1)
+
--- a/scripts/audio/wavwrite.m
+++ b/scripts/audio/wavwrite.m
@@ -23,7 +23,8 @@
 ## Write @var{y} to the canonical RIFF/WAVE sound file @var{filename}
 ## with sample rate @var{Fs} and bits per sample @var{bps}.  The
 ## default sample rate is 8000 Hz with 16-bits per sample.  Each column
-## of the data represents a separate channel.
+## of the data represents a separate channel.  If @var{y} is either a
+## row vector or a column vector, it is written as a single channel.
 ## @seealso{wavread}
 ## @end deftypefn
 
@@ -50,11 +51,20 @@
     endif
   endif
 
+  ## calculate filesize
+  [n, channels] = size (y);
+
+  ## allow y to be a row vector
+  if (n == 1)
+    n = channels;
+    channels = 1;
+  endif
+
   ## test arguments
-  if (columns (y) < 1)
+  if (channels < 1)
     error ("wavwrite: Y must have at least one column");
   endif
-  if (columns (y) > 0x7FFF)
+  if (channels > 0x7FFF)
     error ("wavwrite: Y has more than 32767 columns (too many for a WAV-file)");
   endif
 
@@ -70,9 +80,6 @@
       error ("wavwrite: sample resolution not supported");
   endswitch
 
-  ## calculate filesize
-  [n, channels] = size (y);
-
   ## size of data chunk
   ck_size = n*channels*(bits_per_sample/8);
 
@@ -174,10 +181,19 @@
 %! unlink (fname);
 %
 %!test
-%! A = [-2:2];
+%! A = [-2:2]';
 %! wavwrite (A, fname);
 %! B = wavread (fname);
 %! B *= 32768;
-%! assert (B, [-32768 -32768 0 32767 32767]);
+%! assert (B, [-32768 -32768 0 32767 32767]');
+%! unlink (fname);
+%
+%!test
+%! A = [-1:0.1:1];
+%! wavwrite (A, fname);
+%! [B, samples_per_sec, bits_per_sample] = wavread (fname);
+%! assert (A', B, 1/2^15);
+%! assert (samples_per_sec, 8000);
+%! assert (bits_per_sample, 16);
 %! unlink (fname);
 
deleted file mode 100644
--- a/scripts/deprecated/autocor.m
+++ /dev/null
@@ -1,59 +0,0 @@
-## Copyright (C) 1995-2012 Friedrich Leisch
-##
-## 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} {} autocor (@var{x}, @var{h})
-## Return the autocorrelations from lag 0 to @var{h} of vector @var{x}.
-## If @var{h} is omitted, all autocorrelations are computed.
-## If @var{x} is a matrix, the autocorrelations of each column are
-## computed.
-## The particular algorithm used is from the field of statistics and
-## differs from the definition used in signal processing.
-## @end deftypefn
-
-## Author: FL <Friedrich.Leisch@ci.tuwien.ac.at>
-## Description: Compute autocorrelations
-
-## Deprecated in version 3.4
-
-function retval = autocor (X, h)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "autocor is obsolete and will be removed from a future version of Octave; See the Octave-Forge signal package and the function xcor for a replacement");
-  endif
-
-
-  if (nargin == 1)
-    retval = autocov (X);
-  elseif (nargin == 2)
-    retval = autocov (X, h);
-  else
-    print_usage ();
-  endif
-
-  if (min (retval (1,:)) != 0)
-    retval = retval ./ (ones (rows (retval), 1) * retval(1,:));
-  endif
-
-endfunction
-
-
-
deleted file mode 100644
--- a/scripts/deprecated/autocov.m
+++ /dev/null
@@ -1,62 +0,0 @@
-## Copyright (C) 1995-2012 Friedrich Leisch
-##
-## 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} {} autocov (@var{x}, @var{h})
-## Return the autocovariances from lag 0 to @var{h} of vector @var{x}.
-## If @var{h} is omitted, all autocovariances are computed.
-## If @var{x} is a matrix, the autocovariances of each column are
-## computed.
-## The particular algorithm used is from the field of statistics and
-## differs from the definition used in signal processing.
-## @end deftypefn
-
-## Author: FL <Friedrich.Leisch@ci.tuwien.ac.at>
-## Description: Compute autocovariances
-
-## Deprecated in version 3.4
-
-function retval = autocov (X, h)
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "autocov is obsolete and will be removed from a future version of Octave; See the Octave-Forge signal package and the function xcov for a replacement");
-  endif
-
-  [n, c] = size (X);
-
-  if (isvector (X))
-    n = length (X);
-    c = 1;
-    X = reshape (X, n, 1);
-  endif
-
-  X = center (X);
-
-  if (nargin == 1)
-    h = n - 1;
-  endif
-
-  retval = zeros (h + 1, c);
-
-  for i = 0 : h
-    retval(i+1, :) = diag (X(i+1:n, :).' * conj (X(1:n-i, :))).' / n;
-  endfor
-
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/betai.m
+++ /dev/null
@@ -1,47 +0,0 @@
-## Copyright (C) 1994-2012 John W. Eaton
-##
-## 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} {} betai (@var{a}, @var{b}, @var{x})
-## This function is provided for compatibility with older versions of
-## Octave.  New programs should use betainc instead.
-##
-## @code{betai (@var{a}, @var{b}, @var{x})} is the same as
-## @code{betainc (@var{x}, @var{a}, @var{b})}.
-## @end deftypefn
-
-## Author: jwe
-## Created: 30 Jan 1998
-
-## Deprecated in version 3.4
-
-function retval = betai (a, b, x)
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "betai is obsolete and will be removed from a future version of Octave; please use betainc instead");
-  endif
-
-  if (nargin == 3)
-    retval = betainc (x, a, b);
-  else
-    print_usage ();
-  endif
-
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/cellidx.m
+++ /dev/null
@@ -1,108 +0,0 @@
-## Copyright (C) 2000-2012 Auburn University.  All rights reserved.
-##
-## This file is part of Octave.
-##
-## Octave 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.
-##
-## Octave program is distributed in the hope that it will be useful, but
-## WITHOUT ANY WARRANTY; without even the implied warranty of
-## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-## General Public License for more details.
-##
-## You should have received a copy of the GNU General Public License
-## along with Octave; see the file COPYING.  If not, see
-## <http://www.gnu.org/licenses/>.
-
-## -*- texinfo -*-
-## @deftypefn {Function File} {[@var{idxvec}, @var{errmsg}] =} cellidx (@var{listvar}, @var{strlist})
-## Return indices of string entries in @var{listvar} that match strings
-## in @var{strlist}.
-##
-## Both @var{listvar} and @var{strlist} may be passed as strings or
-## string matrices.  If they are passed as string matrices, each entry
-## is processed by @code{deblank} prior to searching for the entries.
-##
-## The first output is the vector of indices in @var{listvar}.
-##
-## If @var{strlist} contains a string not in @var{listvar}, then
-## an error message is returned in @var{errmsg}.  If only one output
-## argument is requested, then @var{cellidx} prints @var{errmsg} to the
-## screen and exits with an error.
-## @end deftypefn
-
-## deprecated in version 3.4
-
-function [idxvec,errmsg]  = cellidx (listvar, strlist)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "cellidx is obsolete and will be removed from a future version of Octave; use ismember instead");
-  endif
-
-  if (nargin != 2)
-    print_usage ();
-  endif
-
-  if (ischar (strlist))
-    tmp = strlist;
-    strlist = {};
-    for kk = 1:rows(tmp)
-      strlist{kk} = deblank (tmp(kk,:));
-    endfor
-  endif
-
-  if (ischar (listvar))
-    tmp = listvar;
-    listvar = {};
-    for kk = 1:rows(tmp)
-      listvar{kk} = deblank (tmp(kk,:));
-    endfor
-  endif
-
-  ## initialize size of idxvec (for premature return)
-  idxvec = zeros (length(strlist), 1);
-
-  errmsg = "";
-  if (! iscellstr (listvar))
-    errmsg = "listvar must be a list of strings";
-  elseif (! iscellstr (strlist))
-    errmsg = "strlist must be a list of strings";
-  endif
-
-  if (length (errmsg))
-    if (nargout < 2)
-      error (errmsg);
-    else
-      return;
-    endif
-  endif
-
-  nsigs = length(listvar);
-  for idx = 1:length(strlist)
-    signame = strlist{idx};
-    for jdx = 1:nsigs
-      if (strcmp (signame, listvar{jdx}))
-        if (idxvec(idx) != 0)
-          warning ("Duplicate signal name %s (%d,%d)\n",
-                   listvar{jdx}, jdx, idxvec(idx));
-        else
-          idxvec(idx) = jdx;
-        endif
-      endif
-    endfor
-    if (idxvec(idx) == 0)
-      errmsg = sprintf ("Did not find %s", signame);
-      if (nargout == 1)
-        error (errmsg);
-      else
-        break;
-      endif
-    endif
-  endfor
-
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/clg.m
+++ /dev/null
@@ -1,40 +0,0 @@
-## Copyright (C) 2006-2012 John W. Eaton
-##
-## 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} {} clg ()
-## This function has been deprecated.  Use clf instead.
-## @end deftypefn
-
-## Author: jwe
-
-## Deprecated in version 3.0
-## Matlab still has this function, so don't remove just yet.
-
-function clg ()
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "clg is obsolete and will be removed from a future version of Octave, please use clf instead");
-  endif
-
-  clf ();
-
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/cquad.m
+++ /dev/null
@@ -1,39 +0,0 @@
-## Copyright (C) 2012 John W. Eaton
-##
-## 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{int}, @var{err}, @var{nr_points}] =} cquad (@var{f}, @var{a}, @var{b}, @var{tol})
-## @deftypefnx {Function File} {[@var{int}, @var{err}, @var{nr_points}] =} cquad (@var{f}, @var{a}, @var{b}, @var{tol}, @var{sing})
-## This function is an alias for compatibility with older versions of
-## Octave.  New programs should use @code{quadcc} instead.
-## @seealso{quadcc}
-## @end deftypefn
-
-## Deprecated in version 3.4
-
-function retval = cquad (varargin)
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "cquad has been renamed to quadcc and this alias will be removed from a future version of Octave; please use quadcc instead");
-  endif
-
-  retval = quadcc (varargin{:});
-
-endfunction
--- a/scripts/deprecated/cut.m
+++ b/scripts/deprecated/cut.m
@@ -51,10 +51,10 @@
   if (!isvector (x))
     error ("cut: X must be a vector");
   endif
-  if isscalar (breaks)
+  if (isscalar (breaks))
     breaks = linspace (min (x), max (x), breaks + 1);
     breaks(1) = breaks(1) - 1;
-  elseif isvector (breaks)
+  elseif (isvector (breaks))
     breaks = sort (breaks);
   else
     error ("cut: BREAKS must be a scalar or vector");
@@ -62,7 +62,7 @@
 
   group = NaN (size (x));
   m = length (breaks);
-  if any (k = find ((x >= min (breaks)) & (x < max (breaks))))
+  if (any (k = find ((x >= min (breaks)) & (x < max (breaks)))))
     n = length (k);
     group(k) = sum ((ones (m, 1) * reshape (x(k), 1, n))
                     >= (reshape (breaks, m, 1) * ones (1, n)));
deleted file mode 100644
--- a/scripts/deprecated/dispatch.m
+++ /dev/null
@@ -1,103 +0,0 @@
-## Copyright (C) 2010-2012 John W. Eaton
-##
-## 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} {} dispatch (@var{f}, @var{r}, @var{type})
-##
-## Replace the function @var{f} with a dispatch so that function @var{r}
-## is called when @var{f} is called with the first argument of the named
-## @var{type}.  If the type is @var{any} then call @var{r} if no other type
-## matches.  The original function @var{f} is accessible using
-## @code{builtin (@var{f}, @dots{})}.
-##
-## If @var{r} is omitted, clear dispatch function associated with @var{type}.
-##
-## If both @var{r} and @var{type} are omitted, list dispatch functions
-## for @var{f}.
-## @seealso{builtin}
-## @end deftypefn
-
-## Deprecated in version 3.4
-
-function varargout = dispatch (varargin)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "dispatch is obsolete and will be removed from a future version of Octave; please use classes instead");
-  endif
-
-  varargout = cell (nargout, 1);
-  [ varargout{:} ] = __dispatch__ (varargin{:});
-
-endfunction
-
-
-%!test # builtin function replacement
-%! dispatch('sin','length','string')
-%! assert(sin("abc"),3)
-%! assert(sin(0),0,10*eps);
-
-%!test # 'any' function
-%! dispatch('sin','exp','any')
-%! assert(sin(0),1,eps);
-%! assert(sin("abc"),3);
-
-%!test # 'builtin' function
-%! assert(builtin('sin',0),0,eps);
-%! builtin('eval','x=1;');
-%! assert(x,1);
-
-%!test # clear function mapping
-%! dispatch('sin','string')
-%! dispatch('sin','any')
-%! assert(sin(0),0,10*eps);
-
-%!test # oct-file replacement
-%! dispatch('fft','length','string')
-%! assert(fft([1,1]),[2,0]);
-%! assert(fft("abc"),3)
-%! dispatch('fft','string');
-
-%!test # m-file replacement
-%! dispatch('hamming','length','string')
-%! assert(hamming(1),1)
-%! assert(hamming("abc"),3)
-%! dispatch('hamming','string')
-
-%!test # override preloaded builtin
-%! evalin('base','cos(1);');
-%! dispatch('cos','length','string')
-%! evalin('base','assert(cos("abc"),3)');
-%! evalin('base','assert(cos(0),1,eps)');
-%! dispatch('cos','string')
-
-%!test # override pre-loaded oct-file
-%! evalin('base','qr(1);');
-%! dispatch('qr','length','string')
-%! evalin('base','assert(qr("abc"),3)');
-%! evalin('base','assert(qr(1),1)');
-%! dispatch('qr','string');
-
-%!test # override pre-loaded m-file
-%! evalin('base','hanning(1);');
-%! dispatch('hanning','length','string')
-%! evalin('base','assert(hanning("abc"),3)');
-%! evalin('base','assert(hanning(1),1)');
-%! dispatch('hanning','string');
deleted file mode 100644
--- a/scripts/deprecated/fstat.m
+++ /dev/null
@@ -1,35 +0,0 @@
-## Copyright (C) 2010-2012 VZLU Prague
-##
-## 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{info}, @var{err}, @var{msg}] =} fstat (fid)
-## This function has been deprecated.  Use stat instead.
-## @end deftypefn
-
-## Deprecated in version 3.4
-
-function [info, err, msg] = fstat (fid)
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "fstat is obsolete and will be removed from a future version of Octave, please use stat instead");
-  endif
-
-  [info, err, msg] = stat (fid);
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/gammai.m
+++ /dev/null
@@ -1,47 +0,0 @@
-## Copyright (C) 1994-2012 John W. Eaton
-##
-## 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} {} gammai (@var{a}, @var{x})
-## This function is provided for compatibility with older versions of
-## Octave.  New programs should use @code{gammainc} instead.
-##
-## @code{gammai (@var{a}, @var{x})} is the same as
-## @code{gammainc (@var{x}, @var{a})}.
-## @end deftypefn
-
-## Author: jwe
-## Created: 30 Jan 1998
-
-## Deprecated in version 3.4
-
-function retval = gammai (a, x)
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "gammai is obsolete and will be removed from a future version of Octave; please use gammainc instead");
-  endif
-
-  if (nargin == 2)
-    retval = gammainc (x, a);
-  else
-    print_usage ();
-  endif
-
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/glpkmex.m
+++ /dev/null
@@ -1,117 +0,0 @@
-## Copyright (C) 2005-2012 Nicolo' Giorgetti
-##
-## 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{xopt}, @var{fmin}, @var{status}, @var{extra}] =} glpkmex (@var{sense}, @var{c}, @var{A}, @var{b}, @var{ctype}, @var{lb}, @var{ub}, @var{vartype}, @var{param}, @var{lpsolver}, @var{save_pb})
-## This function is provided for compatibility with the old @sc{matlab}
-## interface to the GNU @sc{glpk} library.  For Octave code, you should use
-## the @code{glpk} function instead.
-## @seealso{glpk}
-## @end deftypefn
-
-function [xopt, fopt, status, extra] = glpkmex (varargin)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "glpkmex is obsolete and will be removed from a future version of Octave; please use glpk instead");
-  endif
-
-  ## If there is no input output the version and syntax
-  if (nargin < 4 || nargin > 11)
-    print_usage ();
-    return;
-  endif
-
-  ## reorder args:
-  ##
-  ##     glpkmex    glpk
-  ##
-  ##  1   sense      c
-  ##  2   c          a
-  ##  3   a          b
-  ##  4   b          lb
-  ##  5   ctype      ub
-  ##  6   lb         ctype
-  ##  7   ub         vartype
-  ##  8   vartype    sense
-  ##  9   param      param
-  ## 10   lpsolver
-  ## 11   savepb
-
-  sense = varargin{1};
-  c = varargin{2};
-  a = varargin{3};
-  b = varargin{4};
-
-  nx = length  (c);
-
-  if (nargin > 4)
-    ctype = varargin{5};
-  else
-    ctype = repmat ("U", nx, 1);
-  endif
-
-  if (nargin > 5)
-    lb = varargin{6};
-  else
-    lb = repmat (-Inf, nx, 1);
-  endif
-
-  if (nargin > 6)
-    ub = varargin{7};
-  else
-    ub = repmat (Inf, nx, 1);
-  endif
-
-  if (nargin > 7)
-    vartype = varargin{8};
-  else
-    vartype = repmat ("C", nx, 1);
-  endif
-
-  if (nargin > 8)
-    param = varargin{9};
-  else
-    param = struct ();
-  endif
-
-  if (nargin > 9 && ! isfield (param, "lpsolver"))
-    param.lpsolver = varargin{10};
-  endif
-
-  if (nargin > 10 && ! isfield (param, "save"))
-    param.save = varargin{11};
-  endif
-
-  if (nargout == 0)
-    glpk (c, a, b, lb, ub, ctype, vartype, sense, param);
-  elseif (nargout == 1)
-    xopt = glpk (c, a, b, lb, ub, ctype, vartype, sense, param);
-  elseif (nargout == 2)
-    [xopt, fopt] = glpk (c, a, b, lb, ub, ctype, vartype, sense, param);
-  elseif (nargout == 3)
-    [xopt, fopt, status] = ...
-      glpk (c, a, b, lb, ub, ctype, vartype, sense, param);
-  else
-    [xopt, fopt, status, extra] = ...
-      glpk (c, a, b, lb, ub, ctype, vartype, sense, param);
-  endif
-
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/intwarning.m
+++ /dev/null
@@ -1,133 +0,0 @@
-## Copyright (C) 2008-2012 David Bateman
-##
-## 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} {} intwarning (@var{action})
-## @deftypefnx {Function File} {} intwarning (@var{s})
-## @deftypefnx {Function File} {@var{s} =} intwarning (@dots{})
-## Control the state of the warning for integer conversions and math
-## operations.
-##
-## @table @asis
-## @item "query"
-## With an output argument, return the current state of the integer
-## conversion and math warnings.  With no output arguments, print the
-## current state.
-## @c Set example in small font to prevent overfull line
-##
-## @smallexample
-## @group
-## intwarning ("query")
-## The state of warning "Octave:int-convert-nan" is "off"
-## The state of warning "Octave:int-convert-non-int-val" is "off"
-## The state of warning "Octave:int-convert-overflow" is "off"
-## The state of warning "Octave:int-math-overflow" is "off"
-## @end group
-## @end smallexample
-##
-## @item "on"
-## @itemx "off"
-## Turn integer conversion and math warnings on (or off).  If there is
-## no output argument, then nothing is printed.  Otherwise the original
-## state of the state of the integer conversion and math warnings is
-## returned in a structure array.
-## @end table
-##
-## The original state of the integer warnings can be restored by passing
-## the structure array returned by @code{intwarning} to a later call to
-## @code{intwarning}.  For example:
-##
-## @example
-## @group
-## s = intwarning ("off");
-## @dots{}
-## intwarning (s);
-## @end group
-## @end example
-## @seealso{warning}
-## @end deftypefn
-
-## Deprecated in v. 3.4
-
-function y = intwarning (x)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "intwarning is obsolete and will be removed from a future version of Octave; integer math no longer produces warnings -- supply your own checks if you need those");
-  endif
-
-  return;
-
-  if (nargin != 1)
-    print_usage ();
-  else
-    if (nargout > 0)
-      y = warning("query", "Octave:int-convert-nan");
-      y = [y; warning("query", "Octave:int-convert-non-int-val")];
-      y = [y; warning("query", "Octave:int-convert-overflow")];
-      y = [y; warning("query", "Octave:int-math-overflow")];
-    endif
-    if (ischar (x))
-      if (strcmpi (x, "query"))
-        if (nargout == 0)
-          __print_int_warn_state__ ("Octave:int-convert-nan");
-          __print_int_warn_state__ ("Octave:int-convert-non-int-val");
-          __print_int_warn_state__ ("Octave:int-convert-overflow");
-          __print_int_warn_state__ ("Octave:int-math-overflow");
-          printf("\n");
-        endif
-      elseif (strcmpi (x, "on"))
-        warning ("on", "Octave:int-convert-nan");
-        warning ("on", "Octave:int-convert-non-int-val");
-        warning ("on", "Octave:int-convert-overflow");
-        warning ("on", "Octave:int-math-overflow");
-      elseif (strcmpi (x, "off"))
-        warning ("off", "Octave:int-convert-nan");
-        warning ("off", "Octave:int-convert-non-int-val");
-        warning ("off", "Octave:int-convert-overflow");
-        warning ("off", "Octave:int-math-overflow");
-      else
-        error ("intwarning: unrecognized argument");
-      endif
-    elseif (isstruct(x))
-      for fld = fieldnames (x)
-        if (strcmp ("Octave:int-convert-nan")
-            || strcmp ("Octave:int-convert-non-int-val")
-            || strcmp ("Octave:int-convert-overflow")
-            || strcmp ("Octave:int-cmath-overflow"))
-          s = getfield (x, fld);
-          if (! ischar (s) || !(strcmpi("s","on") || strcmpi("s","off")))
-            error ("intwarning: unexpected warning state");
-          endif
-          warning (s, fld);
-        else
-          error ("intwarning: unrecognized integer warning %s", fld);
-        endif
-      endfor
-    else
-      error ("intwarning: unexpected input");
-    endif
-  endif
-endfunction
-
-function __print_int_warn_state__ (s)
-  fprintf ("The state of warning \"%s\" is \"%s\"\n",
-           s, warning ("query", s).state);
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/is_duplicate_entry.m
+++ /dev/null
@@ -1,53 +0,0 @@
-## Copyright (C) 1996-2012 A. S. Hodel
-##
-## 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} {} is_duplicate_entry (@var{x})
-## Return non-zero if any entries in @var{x} are duplicates of one
-## another.
-## @seealso{unique}
-## @end deftypefn
-
-## Author: A. S. Hodel <scotte@eng.auburn.edu>
-
-function retval = is_duplicate_entry (x)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "is_duplicate_entry is obsolete and will be removed from a future version of Octave; see the function unique for equivalent functionality");
-  endif
-
-
-  if (nargin == 1)
-    if (ismatrix (x))
-      lx = numel (x);
-      lx1 = lx-1;
-      x = sort (reshape (x, 1, lx));
-      dx = x(1:lx1) - x(2:lx);
-      retval = sum (dx == 0);
-    else
-      error ("is_duplicate_entry: expecting matrix argument");
-    endif
-  else
-    print_usage ();
-  endif
-
-endfunction
-
deleted file mode 100644
--- a/scripts/deprecated/is_global.m
+++ /dev/null
@@ -1,37 +0,0 @@
-## Copyright (C) 1994-2012 John W. Eaton
-##
-## 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} {} is_global (@var{name})
-## This function is provided for compatibility with older versions of
-## Octave.  New programs should use isglobal instead.
-## @end deftypefn
-
-## Deprecated in version 3.4
-
-function retval = is_global (name)
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "is_global is obsolete and will be removed from a future version of Octave; please use isglobal instead");
-  endif
-
-  retval = isglobal(name);
-
-endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/deprecated/java_convert_matrix.m
@@ -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
+
new file mode 100644
--- /dev/null
+++ b/scripts/deprecated/java_debug.m
@@ -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
+
new file mode 100644
--- /dev/null
+++ b/scripts/deprecated/java_get.m
@@ -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
+
new file mode 100644
--- /dev/null
+++ b/scripts/deprecated/java_invoke.m
@@ -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
+
new file mode 100644
--- /dev/null
+++ b/scripts/deprecated/java_new.m
@@ -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
+
new file mode 100644
--- /dev/null
+++ b/scripts/deprecated/java_set.m
@@ -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
+
new file mode 100644
--- /dev/null
+++ b/scripts/deprecated/java_unsigned_conversion.m
@@ -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
+
new file mode 100644
--- /dev/null
+++ b/scripts/deprecated/javafields.m
@@ -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, ';', false);
+
+  if (nargout == 0)
+    if (! isempty (method_list))
+      disp (method_list);
+    endif
+  else
+    fld_names = cellstr (method_list);
+  endif
+
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/deprecated/javamethods.m
@@ -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, ';', false);
+
+  if (nargout == 0)
+    if (! isempty (method_list))
+      disp (method_list);
+    endif
+  else
+    mtd_names = cellstr (method_list);
+  endif
+
+endfunction
+
deleted file mode 100644
--- a/scripts/deprecated/krylovb.m
+++ /dev/null
@@ -1,46 +0,0 @@
-## Copyright (C) 1993-2012 A. Scottedward Hodel
-##
-## 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{u}, @var{ucols}] =} krylovb (@var{A}, @var{V}, @var{k}, @var{eps1}, @var{pflg})
-## See @code{krylov}.
-## @end deftypefn
-
-## Deprecated in version 3.4
-
-function [Uret, Ucols] = krylovb (A, V, k, eps1, pflg)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "krylovb is obsolete and will be removed from a future version of Octave; please use [Uret, ~, Ucols] = krylov (...) instead");
-  endif
-
-  switch (nargin)
-    case (3)
-      [Uret, H, Ucols] = krylov (A, V, k);
-    case (4)
-      [Uret, H, Ucols] = krylov (A, V, k, eps1);
-    case (5)
-      [Uret, H, Ucols] = krylov (A, V, k, eps1, pflg);
-    otherwise
-      print_usage ();
-  endswitch
-
-endfunction
--- a/scripts/deprecated/module.mk
+++ b/scripts/deprecated/module.mk
@@ -2,39 +2,25 @@
 
 deprecated_FCN_FILES = \
   deprecated/__error_text__.m \
-  deprecated/autocor.m \
-  deprecated/autocov.m \
-  deprecated/betai.m \
-  deprecated/cellidx.m \
-  deprecated/clg.m \
   deprecated/cor.m \
   deprecated/corrcoef.m \
-  deprecated/cquad.m \
   deprecated/cut.m \
-  deprecated/dispatch.m \
+  deprecated/java_debug.m \
   deprecated/error_text.m \
-  deprecated/fstat.m \
-  deprecated/gammai.m \
-  deprecated/glpkmex.m \
-  deprecated/intwarning.m \
-  deprecated/is_duplicate_entry.m \
-  deprecated/is_global.m \
   deprecated/isstr.m \
-  deprecated/krylovb.m \
-  deprecated/perror.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/replot.m \
-  deprecated/saveimage.m \
   deprecated/setstr.m \
   deprecated/shell_cmd.m \
-  deprecated/strerror.m \
   deprecated/studentize.m \
-  deprecated/sylvester_matrix.m \
-  deprecated/values.m \
-  deprecated/weibcdf.m \
-  deprecated/weibinv.m \
-  deprecated/weibpdf.m \
-  deprecated/weibrnd.m
+  deprecated/sylvester_matrix.m
 
 FCN_FILES += $(deprecated_FCN_FILES)
 
deleted file mode 100644
--- a/scripts/deprecated/perror.m
+++ /dev/null
@@ -1,45 +0,0 @@
-## Copyright (C) 1993-2012 John W. Eaton
-##
-## 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} {} perror (@var{funcname}, @var{num})
-## Print the error message for function @var{funcname} corresponding to the
-## error number @var{num}.  This function is intended to be used to print
-## useful error messages for those functions that return numeric error
-## codes.
-## @seealso{strerror}
-## @end deftypefn
-
-## Author: jwe
-
-function perror (funcname, num)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "perror is obsolete and will be removed from a future version of Octave.");
-  endif
-
-  if (nargin != 2)
-    print_usage ();
-  else
-    printf (strerror (funcname, num));
-  endif
-
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/replot.m
+++ /dev/null
@@ -1,43 +0,0 @@
-## Copyright (C) 2005-2012 John W. Eaton
-##
-## 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} {} replot ()
-## Refresh the plot window.
-## @end deftypefn
-
-## Author: jwe
-
-## Deprecated in version 3.4
-
-function replot ()
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "replot is obsolete and will be removed from a future version of Octave; please use refresh instead");
-  endif
-
-  if (nargin == 0)
-    drawnow ();
-  else
-    print_usage ();
-  endif
-
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/saveimage.m
+++ /dev/null
@@ -1,314 +0,0 @@
-## Copyright (C) 1994-2012 John W. Eaton
-##
-## 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} {} saveimage (@var{fname}, @var{img}, @var{fmt})
-## @deftypefnx {Function File} {} saveimage (@var{fname}, @var{img}, @var{fmt}, @var{map})
-## Save the matrix @var{img} to file @var{fname} in image format @var{fmt}.
-## Valid values for @var{fmt} are
-##
-## @table @asis
-## @item "img"
-## Octave's image format.  The current colormap is also saved in the file.
-##
-## @item "ppm"
-## Portable pixmap format.
-##
-## @item "ps"
-## PostScript format.
-## @end table
-##
-## If the fourth argument is supplied, the specified colormap will also be
-## saved along with the image.
-##
-## Note: if the colormap contains only two entries and these entries are
-## black and white, the bitmap ppm and PostScript formats are used.  If the
-## image is a gray scale image (the entries within each row of the colormap
-## are equal) the gray scale ppm and PostScript image formats are used,
-## otherwise the full color formats are used.
-## @seealso{imread, save, load, colormap}
-## @end deftypefn
-
-## The conversion to PostScript is based on pbmtolps.c, which was
-## written by
-##
-##   George Phillips <phillips@cs.ubc.ca>
-##   Department of Computer Science
-##   University of British Columbia
-##
-## and is part of the portable bitmap utilities,
-
-## Author: Tony Richardson <arichard@stark.cc.oh.us>
-## Created: July 1994
-## Adapted-By: jwe
-
-## Rewritten by jwe to avoid using octoppm and pbm routines so that
-## people who don't have the pbm stuff installed can still use this
-## function.
-##
-## The conversion to PostScript is based on pnmtops.c, which is part of
-## the portable bitmap utilties and bears this copyright notice:
-##
-## Copyright (C) 1989 by Jef Poskanzer.
-##
-## Permission to use, copy, modify, and distribute this software and its
-## documentation for any purpose and without fee is hereby granted, provided
-## that the above copyright notice appear in all copies and that both that
-## copyright notice and this permission notice appear in supporting
-## documentation.  This software is provided "as is" without express or
-## implied warranty.
-
-function saveimage (fname, img, fmt, map)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "saveimage is obsolete and will be removed from a future version of Octave; please use imwrite instead");
-  endif
-
-  if (nargin < 2 || nargin > 4)
-    print_usage ();
-  endif
-
-  if (nargin < 4)
-    if (size(img, 3) == 3)
-      [img, map] = rgb2ind(img);
-    else
-      map = colormap ();
-    endif
-  endif
-
-  [map_nr, map_nc] = size (map);
-
-  if (map_nc != 3)
-    error ("saveimage: MAP must be an N x 3 matrix");
-  endif
-
-  if (nargin < 3)
-    fmt = "img";
-  elseif (! ischar (fmt))
-    error ("saveimage: FMT specification must be a string");
-  elseif (! (strcmp (fmt, "img")
-             || strcmp (fmt, "ppm")
-             || strcmp (fmt, "ps")))
-    error ("saveimage: unsupported image format specification");
-  endif
-
-  if (! ismatrix (img))
-    warning ("IMG variable is not a matrix");
-  endif
-
-  if (! ischar (fname))
-    error ("saveimage: FNAME must be a string");
-  endif
-
-  ## If we just want Octave image format, save and return.
-
-  if (strcmp (fmt, "img"))
-    save ("-text", fname, "map", "img");
-    return;
-  endif
-
-  ## Convert to another format if requested.
-
-  grey = all (map(:,1) == map(:,2) && map(:,1) == map (:,3));
-
-  pbm = pgm = ppm = 0;
-
-  map_sz = map_nr * map_nc;
-
-  map = reshape (map, map_sz, 1);
-
-  map (map > 1) = 1;
-  map (map < 0) = 0;
-
-  map = round (255 * map);
-
-  bw = (map_nr == 2
-        && ((map(1,1) == 0 && map(2,1) == 255)
-            || (map(1,1) == 255 && map(2,1) == 0)));
-
-  img = round (img');
-  [img_nr, img_nc] = size (img);
-
-  img_sz = img_nr * img_nc;
-  img = reshape (img, img_sz, 1);
-
-  img (img > map_nr) = map_nr;
-  img (img <= 0) = 1;
-
-  if (strcmp (fmt, "ppm"))
-
-    ## Would be nice to make this consistent with the line used by the
-    ## load/save functions, but we need a good way to get username and
-    ## hostname information.
-
-    time_string = ctime (time ());
-    time_string = time_string (1:length (time_string)-1);
-    tagline = sprintf ("# Created by Octave %s, %s",
-                       OCTAVE_VERSION, time_string);
-
-    if (grey && bw)
-
-      if (map(1) != 0)
-        map = [0; 1];
-      else
-        map = [1; 0];
-      endif
-
-      n_long = rem (img_nc, 8);
-      tmp = zeros (ceil (img_nc/8), img_nr);
-
-      k = ceil (img_nr/8);
-      tmp = zeros (k, img_nc);
-
-      ## Append columns with zeros to original image so that
-      ## mod (cols, 8) = 0.
-
-      bwimg = postpad (reshape (map(img), img_nr, img_nc), k * 8, 0);
-
-      b = kron (pow2 (7:-1:0)', ones (1, img_nc));
-
-      for i = 1:k
-        tmp(i,:) = sum (bwimg(8*(i-1)+1:8*i,:) .* b);
-      endfor
-
-      fid = fopen (fname, "wb");
-      fprintf (fid, "P4\n%s\n%d %d\n", tagline, img_nr, img_nc);
-      fwrite (fid, tmp, "uchar");
-      fprintf (fid, "\n");
-      fclose (fid);
-
-    elseif (grey)
-
-      fid = fopen (fname, "wb");
-      fprintf (fid, "P5\n%s\n%d %d\n255\n", tagline, img_nr, img_nc);
-      fwrite (fid, map(img), "uchar");
-      fprintf (fid, "\n");
-      fclose (fid);
-
-    else
-
-      img_idx = ((1:3:3*img_sz)+2)';
-      map_idx = ((2*map_nr+1):map_sz)';
-
-      tmap = map(map_idx);
-      tmp(img_idx--) = tmap(img);
-
-      map_idx = map_idx - map_nr;
-      tmap = map(map_idx);
-      tmp(img_idx--) = tmap(img);
-
-      map_idx = map_idx - map_nr;
-      tmap = map(map_idx);
-      tmp(img_idx--) = tmap(img);
-
-      fid = fopen (fname, "wb");
-      fprintf (fid, "P6\n%s\n%d %d\n255\n", tagline, img_nr, img_nc);
-      fwrite (fid, tmp, "uchar");
-      fprintf (fid, "\n");
-      fclose (fid);
-
-    endif
-
-  elseif (strcmp (fmt, "ps") == 1)
-
-    if (! grey)
-      error ("saveimage: must have a greyscale colormap for conversion to PostScript");
-    endif
-
-    bps = 8;
-    dpi = 300;
-    pagewid = 612;
-    pagehgt = 762;
-    MARGIN = 0.95;
-    devpix = dpi / 72.0 + 0.5;
-    pixfac = 72.0 / dpi * devpix;
-
-    ## Compute padding to round cols * bps up to the nearest multiple of 8
-    ## (nr and nc are switched because we transposed the image above).
-
-    padright = (((img_nr * bps + 7) / 8) * 8 - img_nr * bps) / bps;
-
-    scols = img_nr * pixfac;
-    srows = img_nc * pixfac;
-    scale = 1;
-
-    if (scols > pagewid * MARGIN || srows > pagehgt * MARGIN)
-      if (scols > pagewid * MARGIN)
-        scale = scale * (pagewid / scols * MARGIN);
-        scols = scale * img_nr * pixfac;
-        srows = scale * img_nc * pixfac;
-      endif
-      if (srows > pagehgt * MARGIN)
-        scale = scale * (pagehgt / srows * MARGIN);
-        scols = scale * img_nr * pixfac;
-        srows = scale * img_nc * pixfac;
-      endif
-      warning ("image too large for page, rescaling to %g", scale);
-    endif
-
-    llx = (pagewid - scols) / 2;
-    lly = (pagehgt - srows) / 2;
-    urx = llx + fix (scols + 0.5);
-    ury = lly + fix (srows + 0.5);
-
-    fid = fopen (fname, "wb");
-
-    fprintf (fid, "%%!PS-Adobe-2.0 EPSF-2.0\n");
-    fprintf (fid, "%%%%Creator: Octave %s (saveimage.m)\n", OCTAVE_VERSION);
-    fprintf (fid, "%%%%Title: %s\n", fname);
-    fprintf (fid, "%%%%Pages: 1\n");
-    fprintf (fid, "%%%%BoundingBox: %d %d %d %d\n",
-             fix (llx), fix (lly), fix (urx), fix (ury));
-    fprintf (fid, "%%%%EndComments\n");
-    fprintf (fid, "/readstring {\n");
-    fprintf (fid, "  currentfile exch readhexstring pop\n");
-    fprintf (fid, "} bind def\n");
-    fprintf (fid, "/picstr %d string def\n",
-             fix ((img_nr + padright) * bps / 8));
-    fprintf (fid, "%%%%EndProlog\n");
-    fprintf (fid, "%%%%Page: 1 1\n");
-    fprintf (fid, "gsave\n");
-    fprintf (fid, "%g %g translate\n", llx, lly);
-    fprintf (fid, "%g %g scale\n", scols, srows);
-    fprintf (fid, "%d %d %d\n", img_nr, img_nc, bps);
-    fprintf (fid, "[ %d 0 0 -%d 0 %d ]\n", img_nr, img_nc, img_nc);
-    fprintf (fid, "{ picstr readstring }\n");
-    fprintf (fid, "image\n");
-
-    img = map(img);
-
-    fmt = "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n";
-    fprintf (fid, fmt, img);
-
-    if (rem (img_sz, 30) != 0)
-      fprintf (fid, "\n");
-    endif
-
-    fprintf (fid, "grestore\n");
-    fprintf (fid, "showpage\n");
-    fprintf (fid, "%%%%Trailer\n");
-    fclose (fid);
-
-  else
-    error ("saveimage: what happened to the image type?");
-  endif
-
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/strerror.m
+++ /dev/null
@@ -1,72 +0,0 @@
-## Copyright (C) 1995-2012 John W. Eaton
-##
-## 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} {} strerror (@var{name}, @var{num})
-## Return the text of an error message for function @var{name}
-## corresponding to the error number @var{num}.  This function is intended
-## to be used to print useful error messages for those functions that
-## return numeric error codes.
-## @end deftypefn
-
-## Author: jwe
-
-function msg = strerror (name, num)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "strerror is obsolete and will be removed from a future version of Octave.");
-  endif
-
-  if (nargin != 2)
-    print_usage ();
-  endif
-
-  if (! ischar (name))
-    error ("strerror: first argument must be a string");
-  endif
-
-  if (! isscalar (num))
-    error ("strerror: second argument must be a scalar");
-  endif
-
-  if (strcmp (name, "fsolve"))
-
-    if (num == -2)
-      msg = "input error\n";
-    elseif (num == -1)
-      msg = "error encountered in user-supplied function\n";
-    elseif (num == 1)
-      msg = "solution converged to requested tolerance\n";
-    elseif (num == 3)
-      msg = "iteration is not making good progress\n";
-    elseif (num == 4)
-      msg = "iteration limit exceeded\n";
-    else
-      error ("strerror: unrecognized error code for fsolve");
-    endif
-
-  else
-
-    error ("strerror: unrecognized function NAME");
-
-  endif
-
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/values.m
+++ /dev/null
@@ -1,61 +0,0 @@
-## Copyright (C) 1995-2012 Kurt Hornik
-##
-## 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} {} values (@var{x})
-## Return the different values in a column vector, arranged in ascending
-## order.
-##
-## As an example, @code{values([1, 2, 3, 1])} returns the vector
-## @code{[1, 2, 3]}.
-## @end deftypefn
-
-## Author: KH <Kurt.Hornik@wu-wien.ac.at>
-## Description: Extract unique elements
-
-## Deprecated in version 3.4
-
-function v = values (x)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "values is obsolete and will be removed from a future version of Octave; please use unique instead");
-  endif
-
-  if (nargin != 1)
-    print_usage ();
-  endif
-
-  if (! (isvector (x)))
-    error ("values: X must be a vector");
-  endif
-
-  i = any (isnan (x));
-  ## HACK!
-  x = x(find(!isnan (x)));
-  n = length (x);
-  x = reshape (x, n, 1);
-  s = sort (x);
-  v = s([1; (find (s(2:n) > s(1:n-1)) + 1)]);
-  if (i)
-    v = [v; NaN];
-  endif
-
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/weibcdf.m
+++ /dev/null
@@ -1,47 +0,0 @@
-## Copyright (C) 2006-2012 John W. Eaton
-##
-## 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} {} weibcdf (@var{x}, @var{scale}, @var{shape})
-## Compute the cumulative distribution function (CDF) at @var{x} of the
-## Weibull distribution with shape parameter @var{scale} and scale
-## parameter @var{shape}, which is
-##
-## @example
-## 1 - exp(-(x/shape)^scale)
-## @end example
-##
-## @noindent
-## for @var{x} @geq{} 0.
-## @end deftypefn
-
-## Deprecated in version 3.0
-## Matlab still has this function, so don't remove just yet.
-
-function cdf = weibcdf (varargin)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "weibcdf is obsolete and will be removed from a future version of Octave; please use wblcdf instead");
-  endif
-
-  cdf = wblcdf (varargin{:});
-
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/weibinv.m
+++ /dev/null
@@ -1,40 +0,0 @@
-## Copyright (C) 2006-2012 John W. Eaton
-##
-## 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} {} weibinv (@var{x}, @var{scale}, @var{shape})
-## Compute the quantile (the inverse of the CDF) at @var{x} of the
-## Weibull distribution with shape parameter @var{scale} and scale
-## parameter @var{shape}.
-## @end deftypefn
-
-## Deprecated in version 3.0
-## Matlab still has this function, so don't remove just yet.
-
-function inv = weibinv (varargin)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "weibinv is obsolete and will be removed from a future version of Octave; please use wblinv instead");
-  endif
-
-  inv = wblinv (varargin{:});
-
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/weibpdf.m
+++ /dev/null
@@ -1,47 +0,0 @@
-## Copyright (C) 2006-2012 John W. Eaton
-##
-## 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} {} weibpdf (@var{x}, @var{scale}, @var{shape})
-## Compute the probability density function (PDF) at @var{x} of the
-## Weibull distribution with shape parameter @var{scale} and scale
-## parameter @var{shape} which is given by
-##
-## @example
-##    scale * shape^(-scale) * x^(scale-1) * exp(-(x/shape)^scale)
-## @end example
-##
-## @noindent
-## for @var{x} > 0.
-## @end deftypefn
-
-## Deprecated in version 3.0
-## Matlab still has this function, so don't remove just yet.
-
-function pdf = weibpdf (varargin)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "weibpdf is obsolete and will be removed from a future version of Octave; please use wblpdf instead");
-  endif
-
-  pdf = wblpdf (varargin{:});
-
-endfunction
deleted file mode 100644
--- a/scripts/deprecated/weibrnd.m
+++ /dev/null
@@ -1,46 +0,0 @@
-## Copyright (C) 2006-2012 John W. Eaton
-##
-## 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} {} weibrnd (@var{scale}, @var{shape}, @var{r}, @var{c})
-## @deftypefnx {Function File} {} weibrnd (@var{scale}, @var{shape}, @var{sz})
-## Return an @var{r} by @var{c} matrix of random samples from the
-## Weibull distribution with parameters @var{scale} and @var{shape}
-## which must be scalar or of size @var{r} by @var{c}.  Or if @var{sz}
-## is a vector return a matrix of size @var{sz}.
-##
-## If @var{r} and @var{c} are omitted, the size of the result matrix is
-## the common size of @var{alpha} and @var{sigma}.
-## @end deftypefn
-
-## Deprecated in version 3.0
-## Matlab still has this function, so don't remove just yet.
-
-function rnd = weibrnd (varargin)
-
-  persistent warned = false;
-  if (! warned)
-    warned = true;
-    warning ("Octave:deprecated-function",
-             "weibrnd is obsolete and will be removed from a future version of Octave; please use wblrnd instead");
-  endif
-
-  rnd = wblrnd (varargin{:});
-
-endfunction
-
--- a/scripts/elfun/acosd.m
+++ b/scripts/elfun/acosd.m
@@ -25,12 +25,18 @@
 ## Author: David Bateman <dbateman@free.fr>
 
 function y = acosd (x)
+
   if (nargin != 1)
     print_usage ();
   endif
-  y = acos(x) .* 180 ./ pi;
+
+  y = acos (x) .* 180 ./ pi;
+
 endfunction
 
-%!error(acosd())
-%!error(acosd(1,2))
-%!assert(acosd(0:0.1:1),180/pi*acos(0:0.1:1),-10*eps)
+
+%!assert (acosd (0:0.1:1), 180/pi * acos (0:0.1:1), -10*eps)
+
+%!error acosd ()
+%!error acosd (1, 2)
+
--- a/scripts/elfun/acot.m
+++ b/scripts/elfun/acot.m
@@ -30,18 +30,18 @@
     print_usage ();
   endif
 
-  y = atan (1./x);
+  y = atan (1 ./ x);
 
 endfunction
 
+
 %!test
 %! rt2 = sqrt (2);
 %! rt3 = sqrt (3);
 %! x = [rt3, 1, rt3/3, 0, -rt3/3, -1, -rt3];
 %! v = [pi/6, pi/4, pi/3, pi/2, -pi/3, -pi/4, -pi/6];
-%! assert(all (abs (acot (x) - v) < sqrt (eps)));
+%! assert (acot (x), v, sqrt (eps));
 
-%!error acot ();
+%!error acot ()
+%!error acot (1, 2)
 
-%!error acot (1, 2);
-
--- a/scripts/elfun/acotd.m
+++ b/scripts/elfun/acotd.m
@@ -25,12 +25,18 @@
 ## Author: David Bateman <dbateman@free.fr>
 
 function y = acotd (x)
+
   if (nargin != 1)
     print_usage ();
   endif
+
   y = atand (1 ./ x);
+
 endfunction
 
-%!error(acotd())
-%!error(acotd(1,2))
-%!assert(acotd(0:10:90),180./pi.*acot(0:10:90),-10*eps)
+
+%!assert (acotd (0:10:90), 180/pi * acot (0:10:90), -10*eps)
+
+%!error acotd ()
+%!error acotd (1, 2)
+
--- a/scripts/elfun/acoth.m
+++ b/scripts/elfun/acoth.m
@@ -34,14 +34,14 @@
 
 endfunction
 
+
 %!test
 %! rt2 = sqrt (2);
 %! rt3 = sqrt (3);
 %! v = -i*[pi/6, pi/4, pi/3, -pi/3, -pi/4, -pi/6];
 %! x = i*[rt3, 1, rt3/3, -rt3/3, -1, -rt3];
-%! assert(all (abs (acoth (x) - v) < sqrt (eps)));
+%! assert (acoth (x), v, sqrt (eps));
 
-%!error acoth ();
+%!error acoth ()
+%!error acoth (1, 2)
 
-%!error acoth (1, 2);
-
--- a/scripts/elfun/acsc.m
+++ b/scripts/elfun/acsc.m
@@ -34,14 +34,14 @@
 
 endfunction
 
+
 %!test
 %! rt2 = sqrt (2);
 %! rt3 = sqrt (3);
 %! v = [pi/6, pi/4, pi/3, pi/2, pi/3, pi/4, pi/6];
 %! x = [2, rt2, 2*rt3/3, 1, 2*rt3/3, rt2, 2];
-%! assert(all (abs (acsc (x) - v) < sqrt (eps)));
+%! assert (acsc (x), v, sqrt (eps));
 
-%!error acsc ();
+%!error acsc ()
+%!error acsc (1, 2)
 
-%!error acsc (1, 2);
-
--- a/scripts/elfun/acscd.m
+++ b/scripts/elfun/acscd.m
@@ -25,12 +25,18 @@
 ## Author: David Bateman <dbateman@free.fr>
 
 function y = acscd (x)
+
   if (nargin != 1)
     print_usage ();
   endif
-  y = acsc(x) .* 180 ./ pi;
+
+  y = acsc (x) .* 180 ./ pi;
+
 endfunction
 
-%!error(acscd())
-%!error(acscd(1,2))
-%!assert(acscd(0:10:90),180/pi*acsc(0:10:90),-10*eps)
+
+%!assert (acscd (0:10:90), 180/pi * acsc (0:10:90), -10*eps)
+
+%!error acscd ()
+%!error acscd (1, 2)
+
--- a/scripts/elfun/acsch.m
+++ b/scripts/elfun/acsch.m
@@ -34,12 +34,12 @@
 
 endfunction
 
+
 %!test
 %! v = [pi/2*i, -pi/2*i];
 %! x = [-i, i];
-%! assert(all (abs (acsch (x) - v) < sqrt (eps)));
+%! assert (acsch (x), v, sqrt (eps));
 
-%!error acsch ();
+%!error acsch ()
+%!error acsch (1, 2)
 
-%!error acsch (1, 2);
-
--- a/scripts/elfun/asec.m
+++ b/scripts/elfun/asec.m
@@ -34,13 +34,14 @@
 
 endfunction
 
+
 %!test
 %! rt2 = sqrt (2);
 %! rt3 = sqrt (3);
 %! v = [0, pi/6, pi/4, pi/3, 2*pi/3, 3*pi/4, 5*pi/6, pi];
 %! x = [1, 2*rt3/3, rt2, 2, -2, -rt2, -2*rt3/3, -1];
-%! assert(all (abs (asec (x) - v) < sqrt (eps)));
+%! assert (asec (x), v, sqrt (eps));
 
-%!error asec ();
+%!error asec ()
+%!error asec (1, 2)
 
-%!error asec (1, 2);
--- a/scripts/elfun/asecd.m
+++ b/scripts/elfun/asecd.m
@@ -25,12 +25,18 @@
 ## Author: David Bateman <dbateman@free.fr>
 
 function y = asecd (x)
+
   if (nargin != 1)
     print_usage ();
   endif
+
   y = asec (x) .* 180 ./ pi;
-endfunction;
+
+endfunction
+
 
-%!error(asecd())
-%!error(asecd(1,2))
-%!assert(asecd(0:10:90),180./pi.*asec(0:10:90),-10*eps)
+%!assert (asecd (0:10:90), 180/pi * asec (0:10:90), -10*eps)
+
+%!error asecd ()
+%!error asecd (1, 2)
+
--- a/scripts/elfun/asech.m
+++ b/scripts/elfun/asech.m
@@ -34,12 +34,12 @@
 
 endfunction
 
+
 %!test
 %! v = [0, pi*i];
 %! x = [1, -1];
-%! assert(all (abs (asech (x) - v) < sqrt (eps)));
+%! assert (asech (x), v, sqrt (eps));
 
-%!error asech ();
+%!error asech ()
+%!error asech (1, 2)
 
-%!error asech (1, 2);
-
--- a/scripts/elfun/asind.m
+++ b/scripts/elfun/asind.m
@@ -25,12 +25,18 @@
 ## Author: David Bateman <dbateman@free.fr>
 
 function y = asind (x)
+
   if (nargin != 1)
     print_usage ();
   endif
-  y = asin(x) .* 180 ./ pi;
+
+  y = asin (x) .* 180 ./ pi;
+
 endfunction
 
-%!error(asind())
-%!error(asind(1,2))
-%!assert(asind(0:0.1:1),180/pi*asin(0:0.1:1),-10*eps)
+
+%!assert (asind (0:0.1:1), 180/pi * asin (0:0.1:1), -10*eps)
+
+%!error asind ()
+%!error asind (1, 2)
+
--- a/scripts/elfun/atand.m
+++ b/scripts/elfun/atand.m
@@ -25,12 +25,18 @@
 ## Author: David Bateman <dbateman@free.fr>
 
 function y = atand (x)
+
   if (nargin != 1)
     print_usage ();
   endif
+
   y = 180 ./ pi .* atan (x);
+
 endfunction
 
-%!error(atand())
-%!error(atand(1,2))
-%!assert(atand(0:10:90),180./pi.*atan(0:10:90),-10*eps)
+
+%!assert (atand (0:10:90), 180/pi * atan (0:10:90), -10*eps)
+
+%!error atand ()
+%!error atand (1, 2)
+
--- a/scripts/elfun/cosd.m
+++ b/scripts/elfun/cosd.m
@@ -26,17 +26,23 @@
 ## Author: David Bateman <dbateman@free.fr>
 
 function y = cosd (x)
+
   if (nargin != 1)
     print_usage ();
   endif
+
   I = x / 180;
   y = cos (I .* pi);
   I = I + 0.5;
   y(I == fix (I) & finite (I)) = 0;
+
 endfunction
 
-%!error(cosd())
-%!error(cosd(1,2))
-%!assert(cosd(0:10:80),cos(pi*[0:10:80]/180),-10*eps)
-%!assert(cosd([0,180,360]) != 0)
-%!assert(cosd([90,270]) == 0)
+
+%!assert (cosd (0:10:80), cos (pi*[0:10:80]/180), -10*eps)
+%!assert (cosd ([0, 180, 360]) != 0)
+%!assert (cosd ([90, 270]) == 0)
+
+%!error cosd ()
+%!error cosd (1, 2)
+
--- a/scripts/elfun/cot.m
+++ b/scripts/elfun/cot.m
@@ -30,18 +30,18 @@
     print_usage ();
   endif
 
-  y = 1 ./ tan(x);
+  y = 1 ./ tan (x);
 
 endfunction
 
+
 %!test
 %! rt2 = sqrt (2);
 %! rt3 = sqrt (3);
 %! x = [pi/6, pi/4, pi/3, pi/2, 2*pi/3, 3*pi/4, 5*pi/6];
 %! v = [rt3, 1, rt3/3, 0, -rt3/3, -1, -rt3];
-%! assert(all (abs (cot (x) - v) < sqrt (eps)));
+%! assert (cot (x), v, sqrt (eps));
 
-%!error cot ();
+%!error cot ()
+%!error cot (1, 2)
 
-%!error cot (1, 2);
-
--- a/scripts/elfun/cotd.m
+++ b/scripts/elfun/cotd.m
@@ -25,14 +25,20 @@
 ## Author: David Bateman <dbateman@free.fr>
 
 function y = cotd (x)
+
   if (nargin != 1)
     print_usage ();
   endif
+
   y = 1 ./ tand (x);
+
 endfunction
 
-%!error(cotd())
-%!error(cotd(1,2))
-%!assert(cotd(10:10:80),cot(pi*[10:10:80]/180),-10*eps)
-%!assert(cotd([0,180,360]) == Inf)
-%!assert(cotd([90,270]) == 0)
+
+%!assert (cotd (10:10:80), cot (pi*[10:10:80]/180), -10*eps)
+%!assert (cotd ([0, 180, 360]) == Inf)
+%!assert (cotd ([90, 270]) == 0)
+
+%!error cotd ()
+%!error cotd (1, 2)
+
--- a/scripts/elfun/coth.m
+++ b/scripts/elfun/coth.m
@@ -34,12 +34,12 @@
 
 endfunction
 
+
 %!test
 %! x = [pi/2*i, 3*pi/2*i];
 %! v = [0, 0];
-%! assert(all (abs (coth (x) - v) < sqrt (eps)));
+%! assert (coth (x), v, sqrt (eps));
 
-%!error coth ();
+%!error coth ()
+%!error coth (1, 2)
 
-%!error coth (1, 2);
-
--- a/scripts/elfun/csc.m
+++ b/scripts/elfun/csc.m
@@ -30,18 +30,18 @@
     print_usage ();
   endif
 
-  y = 1 ./ sin(x);
+  y = 1 ./ sin (x);
 
 endfunction
 
+
 %!test
 %! rt2 = sqrt (2);
 %! rt3 = sqrt (3);
 %! x = [pi/6, pi/4, pi/3, pi/2, 2*pi/3, 3*pi/4, 5*pi/6];
 %! v = [2, rt2, 2*rt3/3, 1, 2*rt3/3, rt2, 2];
-%! assert(all (abs (csc (x) - v) < sqrt (eps)));
+%! assert (csc (x), v, sqrt (eps));
 
-%!error csc ();
+%!error csc ()
+%!error csc (1, 2)
 
-%!error csc (1, 2);
-
--- a/scripts/elfun/cscd.m
+++ b/scripts/elfun/cscd.m
@@ -25,15 +25,20 @@
 ## Author: David Bateman <dbateman@free.fr>
 
 function y = cscd (x)
+
   if (nargin != 1)
     print_usage ();
   endif
+
   y = 1 ./ sind (x);
+
 endfunction
 
-%!error(cscd())
-%!error(cscd(1,2))
-%!assert(cscd(10:10:90),csc(pi*[10:10:90]/180),-10*eps)
-%!assert(cscd([0,180,360]) == Inf)
-%!assert(cscd([90,270]) != Inf)
 
+%!assert (cscd (10:10:90), csc (pi*[10:10:90]/180), -10*eps)
+%!assert (cscd ([0, 180, 360]) == Inf)
+%!assert (cscd ([90, 270]) != Inf)
+
+%!error cscd ()
+%!error cscd (1, 2)
+
--- a/scripts/elfun/csch.m
+++ b/scripts/elfun/csch.m
@@ -30,16 +30,16 @@
     print_usage ();
   endif
 
-  y = 1 ./ sinh(x);
+  y = 1 ./ sinh (x);
 
 endfunction
 
+
 %!test
 %! x = [pi/2*i, 3*pi/2*i];
 %! v = [-i, i];
-%! assert(all (abs (csch (x) - v) < sqrt (eps)));
+%! assert (csch (x), v, sqrt (eps));
 
-%!error csch ();
+%!error csch ()
+%!error csch (1, 2)
 
-%!error csch (1, 2);
-
--- a/scripts/elfun/sec.m
+++ b/scripts/elfun/sec.m
@@ -30,18 +30,18 @@
     print_usage ();
   endif
 
-  y = 1 ./ cos(x);
+  y = 1 ./ cos (x);
 
 endfunction
 
+
 %!test
 %! rt2 = sqrt (2);
 %! rt3 = sqrt (3);
 %! x = [0, pi/6, pi/4, pi/3, 2*pi/3, 3*pi/4, 5*pi/6, pi];
 %! v = [1, 2*rt3/3, rt2, 2, -2, -rt2, -2*rt3/3, -1];
-%! assert(all (abs (sec (x) - v) < sqrt (eps)));
+%! assert (sec (x), v, sqrt (eps));
 
-%!error sec ();
+%!error sec ()
+%!error sec (1, 2)
 
-%!error sec (1, 2);
-
--- a/scripts/elfun/secd.m
+++ b/scripts/elfun/secd.m
@@ -25,14 +25,20 @@
 ## Author: David Bateman <dbateman@free.fr>
 
 function y = secd (x)
+
   if (nargin != 1)
     print_usage ();
   endif
+
   y = 1 ./ cosd (x);
+
 endfunction
 
-%!error(secd())
-%!error(secd(1,2))
-%!assert(secd(0:10:80),sec(pi*[0:10:80]/180),-10*eps)
-%!assert(secd([0,180,360]) != Inf)
-%!assert(secd([90,270]) == Inf)
+
+%!assert (secd (0:10:80), sec (pi*[0:10:80]/180), -10*eps)
+%!assert (secd ([0, 180, 360]) != Inf)
+%!assert (secd ([90, 270]) == Inf)
+
+%!error secd ()
+%!error secd (1, 2)
+
--- a/scripts/elfun/sech.m
+++ b/scripts/elfun/sech.m
@@ -30,16 +30,16 @@
     print_usage ();
   endif
 
-  y = 1 ./ cosh(x);
+  y = 1 ./ cosh (x);
 
 endfunction
 
+
 %!test
 %! x = [0, pi*i];
 %! v = [1, -1];
-%! assert(all (abs (sech (x) - v) < sqrt (eps)));
+%! assert (sech (x), v, sqrt (eps));
 
-%!error sech ();
+%!error sech ()
+%!error sech (1, 2)
 
-%!error sech (1, 2);
-
--- a/scripts/elfun/sind.m
+++ b/scripts/elfun/sind.m
@@ -26,16 +26,22 @@
 ## Author: David Bateman <dbateman@free.fr>
 
 function y = sind (x)
+
   if (nargin != 1)
     print_usage ();
   endif
+
   I = x / 180;
   y = sin (I .* pi);
   y(I == fix (I) & finite (I)) = 0;
+
 endfunction
 
-%!error(sind())
-%!error(sind(1,2))
-%!assert(sind(10:10:90),sin(pi*[10:10:90]/180),-10*eps)
-%!assert(sind([0,180,360]) == 0)
-%!assert(sind([90,270]) != 0)
+
+%!assert (sind (10:10:90), sin (pi*[10:10:90]/180), -10*eps)
+%!assert (sind ([0, 180, 360]) == 0)
+%!assert (sind ([90, 270]) != 0)
+
+%!error sind ()
+%!error sind (1, 2)
+
--- a/scripts/elfun/tand.m
+++ b/scripts/elfun/tand.m
@@ -27,18 +27,24 @@
 ## Author: David Bateman <dbateman@free.fr>
 
 function y = tand (x)
+
   if (nargin != 1)
     print_usage ();
   endif
+
   I0 = x / 180;
   I90 = (x-90) / 180;
   y = tan (I0 .* pi);
   y(I0 == fix (I0) & finite (I0)) = 0;
   y(I90 == fix (I90) & finite (I90)) = Inf;
-endfunction;
+
+endfunction
+
 
-%!error(tand())
-%!error(tand(1,2))
-%!assert(tand(10:10:80),tan(pi*[10:10:80]/180),-10*eps)
-%!assert(tand([0,180,360]) == 0)
-%!assert(tand([90,270]) == Inf)
+%!assert (tand (10:10:80), tan (pi*[10:10:80]/180), -10*eps)
+%!assert (tand ([0, 180, 360]) == 0)
+%!assert (tand ([90, 270]) == Inf)
+
+%!error tand ()
+%!error tand (1, 2)
+
--- a/scripts/general/accumarray.m
+++ b/scripts/general/accumarray.m
@@ -92,7 +92,7 @@
 ## @end example
 ##
 ## The sparse option can be used as an alternative to the @code{sparse}
-## constructor (@pxref{doc-sparse}). Thus
+## constructor (@pxref{doc-sparse}).  Thus
 ##
 ## @example
 ## sparse (@var{i}, @var{j}, @var{sv})
@@ -106,7 +106,7 @@
 ## @end example
 ##
 ## @noindent
-## For repeated indices, @code{sparse} adds the corresponding value. To
+## For repeated indices, @code{sparse} adds the corresponding value.  To
 ## take the minimum instead, use @code{min} as an accumulator function:
 ##
 ## @example
@@ -150,7 +150,7 @@
   else
     ndims = columns (subs);
     if (lenvals > 1 && lenvals != rows (subs))
-      error ("accumarray: dimension mismatch")
+      error ("accumarray: dimension mismatch");
     endif
   endif
 
@@ -368,24 +368,23 @@
   endif
 endfunction
 
-%!error (accumarray (1:5))
-%!error (accumarray ([1,2,3],1:2))
+
 %!assert (accumarray ([1;2;4;2;4],101:105), [101;206;0;208])
-%!assert (accumarray ([1,1,1;2,1,2;2,3,2;2,1,2;2,3,2],101:105),cat(3, [101,0,0;0,0,0],[0,0,0;206,0,208]))
-%!assert (accumarray ([1,1,1;2,1,2;2,3,2;2,1,2;2,3,2],101:105,[],@(x)sin(sum(x))),sin(cat(3, [101,0,0;0,0,0],[0,0,0;206,0,208])))
-%!assert (accumarray ({[1 3 3 2 3 1 2 2 3 3 1 2],[3 4 2 1 4 3 4 2 2 4 3 4],[1 1 2 2 1 1 2 1 1 1 2 2]},101:112),cat(3,[0,0,207,0;0,108,0,0;0,109,0,317],[0,0,111,0;104,0,0,219;0,103,0,0]))
-%!assert (accumarray ([1,1;2,1;2,3;2,1;2,3],101:105,[2,4],@max,NaN),[101,NaN,NaN,NaN;104,NaN,105,NaN])
+%!assert (accumarray ([1,1,1;2,1,2;2,3,2;2,1,2;2,3,2],101:105), cat (3, [101,0,0;0,0,0],[0,0,0;206,0,208]))
+%!assert (accumarray ([1,1,1;2,1,2;2,3,2;2,1,2;2,3,2],101:105,[],@(x)sin(sum(x))), sin (cat (3, [101,0,0;0,0,0],[0,0,0;206,0,208])))
+%!assert (accumarray ({[1 3 3 2 3 1 2 2 3 3 1 2],[3 4 2 1 4 3 4 2 2 4 3 4],[1 1 2 2 1 1 2 1 1 1 2 2]},101:112), cat (3, [0,0,207,0;0,108,0,0;0,109,0,317], [0,0,111,0;104,0,0,219;0,103,0,0]))
+%!assert (accumarray ([1,1;2,1;2,3;2,1;2,3],101:105,[2,4],@max,NaN), [101,NaN,NaN,NaN;104,NaN,105,NaN])
 %!assert (accumarray ([1 1; 2 1; 2 3; 2 1; 2 3],101:105, [], @prod), [101, 0, 0; 10608, 0, 10815])
-%!assert (accumarray ([1 1; 2 1; 2 3; 2 1; 2 3],101:105,[2 4],@prod,0,true),sparse([1,2,2],[1,1,3],[101,10608,10815],2,4))
+%!assert (accumarray ([1 1; 2 1; 2 3; 2 1; 2 3],101:105,[2 4],@prod,0,true), sparse ([1,2,2],[1,1,3],[101,10608,10815],2,4))
 %!assert (accumarray ([1 1; 2 1; 2 3; 2 1; 2 3],1,[2,4]), [1,0,0,0;2,0,2,0])
-%!assert (accumarray ([1 1; 2 1; 2 3; 2 1; 2 3],101:105,[2,4],@(x)length(x)>1),[false,false,false,false;true,false,true,false])
+%!assert (accumarray ([1 1; 2 1; 2 3; 2 1; 2 3],101:105,[2,4],@(x)length(x)>1), [false,false,false,false;true,false,true,false])
 %!assert (accumarray ([1; 2], [3; 4], [2, 1], @min, [], 0), [3; 4])
 %!assert (accumarray ([1; 2], [3; 4], [2, 1], @min, [], 1), sparse ([3; 4]))
 %!assert (accumarray ([1; 2], [3; 4], [1, 2], @min, [], 0), [3, 4])
 %!assert (accumarray ([1; 2], [3; 4], [1, 2], @min, [], 1), sparse ([3, 4]))
 %!test
-%! A = accumarray ([1 1; 2 1; 2 3; 2 1; 2 3],101:105,[2,4],@(x){x});
-%! assert (A{2},[102;104])
+%! A = accumarray ([1 1; 2 1; 2 3; 2 1; 2 3], 101:105, [2,4], @(x){x});
+%! assert (A{2},[102;104]);
 %!test
 %! subs = ceil (rand (2000, 3)*10);
 %! vals = rand (2000, 1);
@@ -405,4 +404,6 @@
 %! vals = rand (2000, 1);
 %! assert (accumarray (subsc, vals, [], @max), accumarray (subs, vals, [], @max));
 
+%!error (accumarray (1:5))
+%!error (accumarray ([1,2,3],1:2))
 
--- a/scripts/general/accumdim.m
+++ b/scripts/general/accumdim.m
@@ -83,7 +83,8 @@
   sz = size (vals);
 
   if (nargin < 3)
-    [~, dim] = max (sz != 1); # first non-singleton dim
+    ## Find the first non-singleton dimension.
+    (dim = find (sz > 1, 1)) || (dim = 1);
   elseif (! isindex (dim))
     error ("accumdim: DIM must be a valid dimension");
   elseif (dim > length (sz))
@@ -92,7 +93,7 @@
   sz(dim) = n;
 
   if (length (subs) != size (vals, dim))
-    error ("accumdim: dimension mismatch")
+    error ("accumdim: dimension mismatch");
   endif
 
   if (isempty (func) || func == @sum)
@@ -147,6 +148,7 @@
 
 endfunction
 
+
 %%test accumdim vs. accumarray
 
 %!shared a
@@ -156,3 +158,4 @@
 %!assert (accumdim ([2;3;2;2;2], a, 2, 4)(4,:,2), accumarray ([2;3;2;2;2], a(4,:,2), [1,4]))
 %!assert (accumdim ([2;3;2;1;2], a, 3, 3, @min)(1,5,:), accumarray ([2;3;2;1;2], a(1,5,:), [1,1,3], @min))
 %!assert (accumdim ([1;3;2;2;1], a, 2, 3, @median)(4,:,5), accumarray ([1;3;2;2;1], a(4,:,5), [1,3], @median))
+
--- a/scripts/general/bicubic.m
+++ b/scripts/general/bicubic.m
@@ -38,7 +38,7 @@
     print_usage ();
   endif
 
-  if (nargin == 7 && isscalar(spline_alpha))
+  if (nargin == 7 && isscalar (spline_alpha))
     a = spline_alpha;
   else
     a = 0.5;
@@ -50,9 +50,9 @@
 
   if (isa (x, "single") || isa (y, "single") || isa (z, "single")
       || isa (xi, "single") || isa (yi, "single"))
-    myeps = eps("single");
+    myeps = eps ("single");
   else
-    myeps = eps;
+    myeps = eps ();
   endif
 
   if (nargin <= 2)
@@ -65,8 +65,8 @@
     z = x;
     x = [];
     [rz, cz] = size (z);
-    s = linspace (1, cz, (cz-1)*pow2(n)+1);
-    t = linspace (1, rz, (rz-1)*pow2(n)+1);
+    s = linspace (1, cz, (cz-1) * pow2 (n) + 1);
+    t = linspace (1, rz, (rz-1) * pow2 (n) + 1);
   elseif (nargin == 3)
     if (! isvector (x) || ! isvector (y))
       error ("bicubic: XI and YI must be vector");
@@ -88,6 +88,23 @@
       error ("bicubic: X, Y and Z must be equal size matrices of same size");
     endif
 
+    if (all (diff (x) < 0))
+      flipx = true;
+      x = fliplr (x);
+    elseif (all (diff (x) > 0))
+      flipx = false;
+    else
+      error ("bicubic:nonmonotonic", "bicubic: X values must be monotonic");
+    endif
+    if (all (diff (y) < 0))
+      flipy = true;
+      y = flipud (y);
+    elseif (all (diff (y) > 0))
+      flipy = false;
+    else
+      error ("bicubic:nonmonotonic", "bicubic: Y values must be monotonic");
+    endif
+
     ## Mark values outside the lookup table.
     xfirst_ind = find (xi < x(1));
     xlast_ind  = find (xi > x(cz));
@@ -99,9 +116,8 @@
     yi(yfirst_ind) = y(1);
     yi(ylast_ind) = y(rz);
 
-
     x = reshape (x, 1, cz);
-    x(cz) *= 1 + sign (x(cz))*myeps;
+    x(cz) *= 1 + sign (x(cz)) * myeps;
     if (x(cz) == 0)
       x(cz) = myeps;
     endif;
@@ -111,7 +127,7 @@
     xidx = o(find (i > cz));
 
     y = reshape (y, rz, 1);
-    y(rz) *= 1 + sign (y(rz))*myeps;
+    y(rz) *= 1 + sign (y(rz)) * myeps;
     if (y(rz) == 0)
       y(rz) = myeps;
     endif;
@@ -121,8 +137,15 @@
     yidx = o([find(i > rz)]);
 
     ## Set s and t used follow codes.
-    s = xidx + ((xi .- x(xidx))./(x(xidx+1) .- x(xidx)));
-    t = yidx + ((yi - y(yidx))./(y(yidx+1) - y(yidx)));
+    s = xidx + ((xi .- x(xidx)) ./ (x(xidx+1) .- x(xidx)));
+    t = yidx + ((yi  - y(yidx)) ./ (y(yidx+1)  - y(yidx)));
+
+    if (flipx)
+      s = fliplr (s);
+    endif
+    if (flipy)
+      t = flipud (t);
+    endif
   else
     print_usage ();
   endif
@@ -199,10 +222,26 @@
 endfunction
 
 %!demo
-%! A=[13,-1,12;5,4,3;1,6,2];
-%! x=[0,1,4]+10; y=[-10,-9,-8];
-%! xi=linspace(min(x),max(x),17);
-%! yi=linspace(min(y),max(y),26)';
-%! mesh(xi,yi,bicubic(x,y,A,xi,yi));
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
+%! clf;
+%! colormap ("default");
+%! A = [13,-1,12;5,4,3;1,6,2];
+%! x = [0,1,4]+10;
+%! y = [-10,-9,-8];
+%! xi = linspace (min (x), max (x), 17);
+%! yi = linspace (min (y), max (y), 26)';
+%! mesh (xi, yi, bicubic (x,y,A,xi,yi));
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
+
+%!test
+%! x = linspace (1, -1, 10);
+%! [xx, yy] = meshgrid (x);
+%! z = cos (6 * xx) + sin (6 * yy);
+%! x = linspace (1, -1, 30);
+%! [xx2, yy2] = meshgrid (x);
+%! z1 = interp2 (xx, yy, z, xx2, yy2, "cubic");
+%! z2 = interp2 (fliplr (xx), flipud (yy), fliplr (flipud(z)),
+%!               fliplr (xx2), flipud (yy2), "cubic");
+%! z2 = fliplr (flipud (z2));
+%! assert (z1, z2, 100 * eps ())
+
--- a/scripts/general/bitcmp.m
+++ b/scripts/general/bitcmp.m
@@ -86,38 +86,38 @@
 
 
 %!test
-%! Amax=53;
+%! Amax = 53;
 %! Bmax = bitmax;
-%! A = bitshift(Bmax,-2);
-%! assert(bitcmp(A,Amax),bitor(bitshift(1,Amax-1),bitshift(1,Amax-2)));
-%! assert(bitcmp(A,Amax-1),bitshift(1,Amax-2));
-%! assert(bitcmp(A,Amax-2),0);
+%! A = bitshift (Bmax,-2);
+%! assert (bitcmp (A,Amax),bitor (bitshift (1,Amax-1), bitshift (1,Amax-2)));
+%! assert (bitcmp (A,Amax-1), bitshift (1,Amax-2));
+%! assert (bitcmp (A,Amax-2), 0);
 %!test
-%! Amax=8;
-%! Bmax = intmax('uint8');
-%! A = bitshift(Bmax,-2);
-%! assert(bitcmp(A,Amax),bitor(bitshift(uint8(1),Amax-1),bitshift(uint8(1),Amax-2)));
-%! assert(bitcmp(A,Amax-1),bitshift(uint8(1),Amax-2));
-%! assert(bitcmp(A,Amax-2),uint8(0));
+%! Amax = 8;
+%! Bmax = intmax ("uint8");
+%! A = bitshift (Bmax,-2);
+%! assert (bitcmp (A,Amax),bitor (bitshift (uint8 (1),Amax-1), bitshift (uint8 (1),Amax-2)));
+%! assert (bitcmp (A,Amax-1), bitshift (uint8 (1),Amax-2));
+%! assert (bitcmp (A,Amax-2), uint8 (0));
 %!test
-%! Amax=16;
-%! Bmax = intmax('uint16');
-%! A = bitshift(Bmax,-2);
-%! assert(bitcmp(A,Amax),bitor(bitshift(uint16(1),Amax-1),bitshift(uint16(1),Amax-2)));
-%! assert(bitcmp(A,Amax-1),bitshift(uint16(1),Amax-2));
-%! assert(bitcmp(A,Amax-2),uint16(0));
+%! Amax = 16;
+%! Bmax = intmax ("uint16");
+%! A = bitshift (Bmax,-2);
+%! assert (bitcmp (A,Amax),bitor (bitshift (uint16 (1),Amax-1), bitshift (uint16 (1),Amax-2)));
+%! assert (bitcmp (A,Amax-1), bitshift (uint16 (1),Amax-2));
+%! assert (bitcmp (A,Amax-2), uint16 (0));
 %!test
-%! Amax=32;
-%! Bmax = intmax('uint32');
-%! A = bitshift(Bmax,-2);
-%! assert(bitcmp(A,Amax),bitor(bitshift(uint32(1),Amax-1),bitshift(uint32(1),Amax-2)));
-%! assert(bitcmp(A,Amax-1),bitshift(uint32(1),Amax-2));
-%! assert(bitcmp(A,Amax-2),uint32(0));
+%! Amax = 32;
+%! Bmax = intmax ("uint32");
+%! A = bitshift (Bmax,-2);
+%! assert (bitcmp (A,Amax),bitor (bitshift (uint32 (1),Amax-1), bitshift (uint32 (1),Amax-2)));
+%! assert (bitcmp (A,Amax-1), bitshift (uint32 (1),Amax-2));
+%! assert (bitcmp (A,Amax-2), uint32 (0));
 %!test
-%! Amax=64;
-%! Bmax = intmax('uint64');
-%! A = bitshift(Bmax,-2);
-%! assert(bitcmp(A,Amax),bitor(bitshift(uint64(1),Amax-1),bitshift(uint64(1),Amax-2)));
-%! assert(bitcmp(A,Amax-1),bitshift(uint64(1),Amax-2));
-%! assert(bitcmp(A,Amax-2),uint64(0));
+%! Amax = 64;
+%! Bmax = intmax ("uint64");
+%! A = bitshift (Bmax,-2);
+%! assert (bitcmp (A,Amax),bitor (bitshift (uint64 (1),Amax-1), bitshift (uint64 (1),Amax-2)));
+%! assert (bitcmp (A,Amax-1), bitshift (uint64 (1),Amax-2));
+%! assert (bitcmp (A,Amax-2), uint64 (0));
 
--- a/scripts/general/bitget.m
+++ b/scripts/general/bitget.m
@@ -80,8 +80,6 @@
 
 endfunction
 
-%!error bitget (1);
-%!error bitget (1, 2, 3);
 
 %!test
 %! assert (bitget ([4, 14], [3, 3]), logical ([1, 1]));
@@ -93,17 +91,21 @@
 %!   endfor
 %! endfor
 
-%!error bitget (0, 0);
-%!error bitget (0, 55);
+%!error bitget (0, 0)
+%!error bitget (0, 55)
 
-%!error bitget (int8 (0), 9);
-%!error bitget (uint8 (0), 9);
+%!error bitget (int8 (0), 9)
+%!error bitget (uint8 (0), 9)
+
+%!error bitget (int16 (0), 17)
+%!error bitget (uint16 (0), 17)
 
-%!error bitget (int16 (0), 17);
-%!error bitget (uint16 (0), 17);
+%!error bitget (int32 (0), 33)
+%!error bitget (uint32 (0), 33)
 
-%!error bitget (int32 (0), 33);
-%!error bitget (uint32 (0), 33);
+%!error bitget (int64 (0), 65)
+%!error bitget (uint64 (0), 65)
 
-%!error bitget (int64 (0), 65);
-%!error bitget (uint64 (0), 65);
+%!error bitget (1)
+%!error bitget (1, 2, 3)
+
--- a/scripts/general/bitset.m
+++ b/scripts/general/bitset.m
@@ -1,4 +1,5 @@
 ## Copyright (C) 2004-2012 David Bateman
+## Copyright (C) 2012 Jordi Gutiérrez Hermoso
 ##
 ## This file is part of Octave.
 ##
@@ -21,7 +22,8 @@
 ## @deftypefnx {Function File} {@var{C} =} bitset (@var{A}, @var{n}, @var{val})
 ## Set or reset bit(s) @var{n} of unsigned integers in @var{A}.
 ## @var{val} = 0 resets and @var{val} = 1 sets the bits.
-## The lowest significant bit is: @var{n} = 1
+## The lowest significant bit is: @var{n} = 1.  All variables must be the
+## same size or scalars.
 ##
 ## @example
 ## @group
@@ -32,69 +34,60 @@
 ## @seealso{bitand, bitor, bitxor, bitget, bitcmp, bitshift, bitmax}
 ## @end deftypefn
 
-## Liberally based on the version by Kai Habel from octave-forge
-
 function C = bitset (A, n, val)
 
   if (nargin < 2 || nargin > 3)
     print_usage ();
   endif
 
+  if (any (A(:) < 0))
+    error ("bitset: A must be >= 0");
+  endif
+
+  sz = size (A);
+
   if (nargin == 2)
-    val = 1;
+    val = true (sz);
   endif
 
-  if (isa (A, "double"))
-    Bmax = bitmax;
-    Amax = log2 (Bmax) + 1;
-    _conv = @double;
+  cl = class (A);
+
+  if (isfloat (A) && isreal (A))
+    Bmax = bitmax (cl);
+    Amax = log2 (Bmax);
+  elseif (isinteger (A))
+    Bmax = intmax (cl);
+    Amax = round (log2 (Bmax));
   else
-    if (isa (A, "uint8"))
-      Amax = 8;
-      _conv = @uint8;
-    elseif (isa (A, "uint16"))
-      Amax = 16;
-      _conv = @uint16;
-    elseif (isa (A, "uint32"))
-      Amax = 32;
-      _conv = @uint32;
-    elseif (isa (A, "uint64"))
-      Amax = 64;
-      _conv = @uint64;
-    elseif (isa (A, "int8"))
-      Amax = 8;
-      _conv = @int8;
-    elseif (isa (A, "int16"))
-      Amax = 16;
-      _conv = @int16;
-    elseif (isa (A, "int32"))
-      Amax = 32;
-      _conv = @int32;
-    elseif (isa (A, "int64"))
-      Amax = 64;
-      _conv = @int64;
-    else
-      error ("bitset: invalid class %s", class (A));
-    endif
-    Bmax = intmax (class (A));
+    error ("bitset: invalid class %s", cl);
   endif
 
-  m = double (n(:));
-  if (any (m < 1) || any (m > Amax))
+  if (any ((n < 1)(:)) || any ((n > Amax)(:)))
     error ("bitset: N must be in the range [1,%d]", Amax);
   endif
 
-  mask = bitshift (_conv (1), uint8 (n) - uint8 (1));
-  C = bitxor (A, bitand (A, mask));
+  mask = bitshift (cast (1, cl), uint8 (n) - uint8 (1));
+
+  on = logical (val);
+  off = !on;
 
-  if (val)
-    C = bitor (A, mask);
+  if (isscalar (mask))
+    onmask = mask;
+    offmask = mask;
+  else
+    if (! size_equal (A, n))
+      error ("bitset: N must be scalar or the same size as A");
+    endif
+    onmask = mask(on);
+    offmask = mask(off);
   endif
 
+  C = zeros (sz, cl);
+  C(on) = bitor (A(on), onmask);
+  C(off) = bitand (A(off), bitcmp (offmask));
+
 endfunction
 
-%!error bitset (1);
-%!error bitset (1, 2, 3, 4);
 
 %!test
 %! assert (bitset ([0, 10], [3, 3]), [4, 14]);
@@ -106,17 +99,24 @@
 %!   endfor
 %! endfor
 
-%!error bitset (0, 0);
-%!error bitset (0, 55);
-
-%!error bitset (int8 (0), 9);
-%!error bitset (uint8 (0), 9);
+## Bug #36458
+%!assert (bitset (uint8 ([1, 2;3 4]), 1, [0 1; 0 1]), uint8 ([0, 3; 2 5]))
 
-%!error bitset (int16 (0), 17);
-%!error bitset (uint16 (0), 17);
+%!error bitset (1)
+%!error bitset (1, 2, 3, 4)
+%!error <A must be .= 0> bitset (-1, 2)
+%!error <invalid class char> bitset ("1", 2)
+%!error <N must be in the range \[1,53\]> bitset (0, 0)
+%!error <N must be in the range \[1,53\]> bitset (0, 55)
+%!error <N must be in the range \[1,8\]> bitset (uint8 (0), 0)
+%!error <N must be in the range \[1,8\]> bitset (uint8 (0), 9)
+%!error <N must be in the range \[1,7\]> bitset (int8 (0), 9)
+%!error <N must be in the range \[1,15\]> bitset (int16 (0), 17)
+%!error <N must be in the range \[1,16\]> bitset (uint16 (0), 17)
+%!error <N must be in the range \[1,31\]> bitset (int32 (0), 33)
+%!error <N must be in the range \[1,32\]> bitset (uint32 (0), 33)
+%!error <N must be in the range \[1,63\]> bitset (int64 (0), 65)
+%!error <N must be in the range \[1,64\]> bitset (uint64 (0), 65)
+%!error <N must be scalar or the same size as A> bitset (uint8 (1), [1 3])
+%!error <N must be scalar or the same size as A> bitset (uint8 (1:3), [1 3])
 
-%!error bitset (int32 (0), 33);
-%!error bitset (uint32 (0), 33);
-
-%!error bitset (int64 (0), 65);
-%!error bitset (uint64 (0), 65);
--- a/scripts/general/blkdiag.m
+++ b/scripts/general/blkdiag.m
@@ -63,19 +63,21 @@
 
 endfunction
 
+
 ## regular tests
-%!assert(blkdiag(1,ones(2),1),[1,0,0,0;0,1,1,0;0,1,1,0;0,0,0,1])
-%!assert(blkdiag([1,2],[3,4],[5,6]),[1,2,0,0,0,0;0,0,3,4,0,0;0,0,0,0,5,6])
-%!assert(blkdiag([1,2],[3;4],[5,6]),[1,2,0,0,0;0,0,3,0,0;0,0,4,0,0;0,0,0,5,6])
-%!assert(blkdiag([1,2;3,4],[5,6,7]),[1,2,0,0,0;3,4,0,0,0;0,0,5,6,7])
+%!assert (blkdiag (1,ones (2),1), [1,0,0,0;0,1,1,0;0,1,1,0;0,0,0,1])
+%!assert (blkdiag ([1,2],[3,4],[5,6]), [1,2,0,0,0,0;0,0,3,4,0,0;0,0,0,0,5,6])
+%!assert (blkdiag ([1,2],[3;4],[5,6]), [1,2,0,0,0;0,0,3,0,0;0,0,4,0,0;0,0,0,5,6])
+%!assert (blkdiag ([1,2;3,4],[5,6,7]), [1,2,0,0,0;3,4,0,0,0;0,0,5,6,7])
 ## tests involving empty matrices
-%!assert(blkdiag([],[],[]),[])
-%!assert(blkdiag([],[1,2;3,4],[],5,[]),[1,2,0;3,4,0;0,0,5])
-%!assert(blkdiag(zeros(1,0,1),[1,2,3],1,0,5,zeros(0,1,1)),[0,0,0,0,0,0,0;1,2,3,0,0,0,0;0,0,0,1,0,0,0;0,0,0,0,0,0,0;0,0,0,0,0,5,0]);
+%!assert (blkdiag ([],[],[]), [])
+%!assert (blkdiag ([],[1,2;3,4],[],5,[]), [1,2,0;3,4,0;0,0,5])
+%!assert (blkdiag (zeros (1,0,1),[1,2,3],1,0,5,zeros (0,1,1)), [0,0,0,0,0,0,0;1,2,3,0,0,0,0;0,0,0,1,0,0,0;0,0,0,0,0,0,0;0,0,0,0,0,5,0]);
 ## tests involving sparse matrices
-%!assert (blkdiag (sparse([1,2;3,4]),[5,6;7,8]), sparse([1,2,0,0;3,4,0,0;0,0,5,6;0,0,7,8]))
-%!assert (blkdiag (sparse([1,2;3,4]),[5,6]), sparse([1,2,0,0;3,4,0,0;0,0,5,6]))
+%!assert (blkdiag (sparse ([1,2;3,4]),[5,6;7,8]), sparse ([1,2,0,0;3,4,0,0;0,0,5,6;0,0,7,8]))
+%!assert (blkdiag (sparse ([1,2;3,4]),[5,6]), sparse ([1,2,0,0;3,4,0,0;0,0,5,6]))
 # sanity checks
 %!test
 %! A = rand (round (rand (1, 2) * 10));
 %! assert (blkdiag (A), A);
+
--- a/scripts/general/cart2pol.m
+++ b/scripts/general/cart2pol.m
@@ -81,6 +81,7 @@
 
 endfunction
 
+
 %!test
 %! x = [0, 1, 2];
 %! y = 0;
@@ -92,16 +93,16 @@
 %! x = [0, 1, 2];
 %! y = [0, 1, 2];
 %! [t, r] = cart2pol (x, y);
-%! assert (t, [0, pi/4, pi/4], sqrt(eps));
-%! assert (r, sqrt(2)*[0, 1, 2], sqrt(eps));
+%! assert (t, [0, pi/4, pi/4], sqrt (eps));
+%! assert (r, sqrt (2)*[0, 1, 2], sqrt (eps));
 
 %!test
 %! x = [0, 1, 2];
 %! y = [0, 1, 2];
 %! z = [0, 1, 2];
 %! [t, r, z2] = cart2pol (x, y, z);
-%! assert (t, [0, pi/4, pi/4], sqrt(eps));
-%! assert (r, sqrt(2)*[0, 1, 2], sqrt(eps));
+%! assert (t, [0, pi/4, pi/4], sqrt (eps));
+%! assert (r, sqrt (2)*[0, 1, 2], sqrt (eps));
 %! assert (z, z2);
 
 %!test
@@ -134,10 +135,10 @@
 %!test
 %! C = [0, 0; 1, 1; 2, 2];
 %! P = [0, 0; pi/4, sqrt(2); pi/4, 2*sqrt(2)];
-%! assert (cart2pol (C), P, sqrt(eps));
+%! assert (cart2pol (C), P, sqrt (eps));
 
 %!test
 %! C = [0, 0, 0; 1, 1, 1; 2, 2, 2];
 %! P = [0, 0, 0; pi/4, sqrt(2), 1; pi/4, 2*sqrt(2), 2];
-%! assert (cart2pol (C), P, sqrt(eps));
+%! assert (cart2pol (C), P, sqrt (eps));
 
--- a/scripts/general/cart2sph.m
+++ b/scripts/general/cart2sph.m
@@ -71,14 +71,15 @@
 
 endfunction
 
+
 %!test
 %! x = [0, 1, 2];
 %! y = [0, 1, 2];
 %! z = [0, 1, 2];
 %! [t, p, r] = cart2sph (x, y, z);
 %! assert (t, [0, pi/4, pi/4], eps);
-%! assert (p, [0, 1, 1]*atan(sqrt(0.5)), eps);
-%! assert (r, [0, 1, 2]*sqrt(3), eps);
+%! assert (p, [0, 1, 1]*atan (sqrt (0.5)), eps);
+%! assert (r, [0, 1, 2]*sqrt (3), eps);
 
 %!test
 %! x = 0;
@@ -87,7 +88,7 @@
 %! [t, p, r] = cart2sph (x, y, z);
 %! assert (t, [0, 1, 1] * pi/2, eps);
 %! assert (p, [0, 1, 1] * pi/4, eps);
-%! assert (r, [0, 1, 2] * sqrt(2), eps);
+%! assert (r, [0, 1, 2] * sqrt (2), eps);
 
 %!test
 %! x = [0, 1, 2];
@@ -96,7 +97,7 @@
 %! [t, p, r] = cart2sph (x, y, z);
 %! assert (t, [0, 0, 0]);
 %! assert (p, [0, 1, 1] * pi/4);
-%! assert (r, [0, 1, 2] * sqrt(2));
+%! assert (r, [0, 1, 2] * sqrt (2));
 
 %!test
 %! x = [0, 1, 2];
@@ -105,9 +106,10 @@
 %! [t, p, r] = cart2sph (x, y, z);
 %! assert (t, [0, 1, 1] * pi/4);
 %! assert (p, [0, 0, 0]);
-%! assert (r, [0, 1, 2] * sqrt(2));
+%! assert (r, [0, 1, 2] * sqrt (2));
 
 %!test
 %! C = [0, 0, 0; 1, 0, 1; 2, 0, 2];
 %! S = [0, 0, 0; 0, pi/4, sqrt(2); 0, pi/4, 2*sqrt(2)];
-%! assert (cart2sph(C), S, eps);
+%! assert (cart2sph (C), S, eps);
+
--- a/scripts/general/cell2mat.m
+++ b/scripts/general/cell2mat.m
@@ -78,27 +78,28 @@
 
 endfunction
 
-## Tests
-%!shared C, D, E, F
+
+%!demo
+%! C = {[1], [2 3 4]; [5; 9], [6 7 8; 10 11 12]};
+%! cell2mat (C)
+
+%!assert (cell2mat ({}), []);
+%!test
 %! C = {[1], [2 3 4]; [5; 9], [6 7 8; 10 11 12]};
 %! D = C; D(:,:,2) = C;
 %! E = [1 2 3 4; 5 6 7 8; 9 10 11 12];
 %! F = E; F(:,:,2) = E;
-%!assert (cell2mat (C), E);
-%!assert (cell2mat (D), F);
+%! assert (cell2mat (C), E);
+%! assert (cell2mat (D), F);
 %!test
 %! m = rand (10) + i * rand (10);
 %! c = mat2cell (m, [1 2 3 4], [4 3 2 1]);
-%! assert (cell2mat (c), m)
+%! assert (cell2mat (c), m);
 %!test
 %! m = int8 (256*rand (4, 5, 6, 7, 8));
 %! c = mat2cell (m, [1 2 1], [1 2 2], [3 1 1 1], [4 1 2], [3 1 4]);
-%! assert (cell2mat (c), m)
+%! assert (cell2mat (c), m);
 %!test
 %! m = {1, 2, 3};
 %! assert (cell2mat (mat2cell (m, 1, [1 1 1])), m);
-%!assert (cell2mat ({}), []);
-## Demos
-%!demo
-%! C = {[1], [2 3 4]; [5; 9], [6 7 8; 10 11 12]};
-%! cell2mat (C)
+
--- a/scripts/general/celldisp.m
+++ b/scripts/general/celldisp.m
@@ -17,7 +17,8 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} celldisp (@var{c}, @var{name})
+## @deftypefn  {Function File} {} celldisp (@var{c})
+## @deftypefnx {Function File} {} celldisp (@var{c}, @var{name})
 ## Recursively display the contents of a cell array.  By default the values
 ## are displayed with the name of the variable @var{c}.  However, this name
 ## can be replaced with the variable @var{name}.  For example:
@@ -44,12 +45,13 @@
 ## This is ugly, but seems to be what matlab does..
 
 function celldisp (c, name)
+
   if (nargin < 1 || nargin > 2)
     print_usage ();
   endif
 
   if (! iscell (c))
-    error ("celldisp: argument must be a cell array");
+    error ("celldisp: C must be a cell array");
   endif
 
   if (nargin == 1)
@@ -71,17 +73,19 @@
   if (sum (dv != 1) > 1)
     c = cell (size (dv));
     [c{:}] = ind2sub (dv, i);
-    s = sprintf("%i,", c{:});
+    s = sprintf ("%i,", c{:});
     s(end) = [];
   else
-    s = sprintf("%i", i);
+    s = sprintf ("%i", i);
   endif
 endfunction
 
+
 %!demo
 %! c = {1, 2, {31, 32}};
-%! celldisp(c, "b")
+%! celldisp (c, "b")
 
-%!error celldisp ();
-%!error celldisp ({}, "name", 1);
-%!error celldisp (1);
+## Test input validation
+%!error celldisp ()
+%!error celldisp ({}, "name", 1)
+%!error <C must be a cell array> celldisp (1)
--- a/scripts/general/chop.m
+++ b/scripts/general/chop.m
@@ -78,3 +78,4 @@
 %!assert (chop (-e, 4, 7), -2.716)
 %!assert (chop (hilb (3), 3), [1,.5,.333;.5,.333,.25;.333,.25,.2])
 %!assert (chop (hilb (3), 2, 7), [.7,.49,.35;.49,.35,.28;.35,.28,.21], 2*eps)
+
--- a/scripts/general/circshift.m
+++ b/scripts/general/circshift.m
@@ -98,7 +98,7 @@
 %!error circshift ()
 %!error circshift (1)
 %!error circshift (1,2,3)
-%!error circshift (1, ones(2,2))
+%!error circshift (1, ones (2,2))
 %!error circshift (1, [1 2 3])
 %!error circshift (1, 1.5)
 
--- a/scripts/general/colon.m
+++ b/scripts/general/colon.m
@@ -35,10 +35,11 @@
 
 function r = colon (varargin)
   if (nargin != 0)
-    error ("colon: not defined for class \"%s\"", class(varargin{1}));
+    error ('colon: not defined for class "%s"', class (varargin{1}));
   endif
 endfunction
 
+
 %!error colon (1)
 
 ## FIXME -- what does colon () mean since it doesn't set a return value?
--- a/scripts/general/common_size.m
+++ b/scripts/general/common_size.m
@@ -79,7 +79,6 @@
   endif
 endfunction
 
-%!error common_size ();
 
 %!test
 %! m = [1,2;3,4];
@@ -88,3 +87,6 @@
 %! assert (a, m);
 %! assert (b, [3,3;3,3]);
 %! assert (c, [5,5;5,5]);
+
+%!error common_size ()
+
--- a/scripts/general/cplxpair.m
+++ b/scripts/general/cplxpair.m
@@ -44,15 +44,15 @@
 ## @end deftypefn
 
 ## FIXME: subsort returned pairs by imaginary magnitude
-## FIXME: Why doesn't exp(2i*pi*[0:4]'/5) produce exact conjugates. Does
-## FIXME:    it in Matlab?  The reason is that complex pairs are supposed
-## FIXME:    to be exact conjugates, and not rely on a tolerance test.
+## FIXME: Why doesn't exp (2i*pi*[0:4]'/5) produce exact conjugates.  Does
+## FIXME: it in Matlab?  The reason is that complex pairs are supposed
+## FIXME: to be exact conjugates, and not rely on a tolerance test.
 
 ## 2006-05-12 David Bateman - Modified for NDArrays
 
 function y = cplxpair (z, tol, dim)
 
-  if nargin < 1 || nargin > 3
+  if (nargin < 1 || nargin > 3)
     print_usage ();
   endif
 
@@ -82,7 +82,7 @@
       dim = 1;
     endif
   else
-    dim = floor(dim);
+    dim = floor (dim);
     if (dim < 1 || dim > nd)
       error ("cplxpair: invalid dimension along which to sort");
     endif
@@ -105,7 +105,7 @@
   if (isa (z, "single"))
     cls = "single";
   endif
-  [idxi, idxj] = find (abs (imag (z)) ./ (abs (z) + realmin(cls)) < tol);
+  [idxi, idxj] = find (abs (imag (z)) ./ (abs (z) + realmin (cls)) < tol);
   q = sparse (idxi, idxj, 1, n, m);
   nr = sum (q, 1);
   [q, idx] = sort (q, 1);
@@ -139,26 +139,28 @@
 
 endfunction
 
+
 %!demo
 %! [ cplxpair(exp(2i*pi*[0:4]'/5)), exp(2i*pi*[3; 2; 4; 1; 0]/5) ]
 
-%!assert (isempty(cplxpair([])));
-%!assert (cplxpair(1), 1)
-%!assert (cplxpair([1+1i, 1-1i]), [1-1i, 1+1i])
-%!assert (cplxpair([1+1i, 1+1i, 1, 1-1i, 1-1i, 2]), \
-%!        [1-1i, 1+1i, 1-1i, 1+1i, 1, 2])
-%!assert (cplxpair([1+1i; 1+1i; 1; 1-1i; 1-1i; 2]), \
-%!        [1-1i; 1+1i; 1-1i; 1+1i; 1; 2])
-%!assert (cplxpair([0, 1, 2]), [0, 1, 2]);
+%!assert (isempty (cplxpair ([])))
+%!assert (cplxpair (1), 1)
+%!assert (cplxpair ([1+1i, 1-1i]), [1-1i, 1+1i])
+%!assert (cplxpair ([1+1i, 1+1i, 1, 1-1i, 1-1i, 2]), ...
+%!                  [1-1i, 1+1i, 1-1i, 1+1i, 1, 2])
+%!assert (cplxpair ([1+1i; 1+1i; 1; 1-1i; 1-1i; 2]), ...
+%!                  [1-1i; 1+1i; 1-1i; 1+1i; 1; 2])
+%!assert (cplxpair ([0, 1, 2]), [0, 1, 2])
 
 %!shared z
-%! z=exp(2i*pi*[4; 3; 5; 2; 6; 1; 0]/7);
-%!assert (cplxpair(z(randperm(7))), z);
-%!assert (cplxpair(z(randperm(7))), z);
-%!assert (cplxpair(z(randperm(7))), z);
-%!assert (cplxpair([z(randperm(7)),z(randperm(7))]),[z,z])
-%!assert (cplxpair([z(randperm(7)),z(randperm(7))],[],1),[z,z])
-%!assert (cplxpair([z(randperm(7)).';z(randperm(7)).'],[],2),[z.';z.'])
+%! z = exp (2i*pi*[4; 3; 5; 2; 6; 1; 0]/7);
+%!assert (cplxpair (z(randperm (7))), z)
+%!assert (cplxpair (z(randperm (7))), z)
+%!assert (cplxpair (z(randperm (7))), z)
+%!assert (cplxpair ([z(randperm(7)),z(randperm(7))]), [z,z])
+%!assert (cplxpair ([z(randperm(7)),z(randperm(7))],[],1), [z,z])
+%!assert (cplxpair ([z(randperm(7)).';z(randperm(7)).'],[],2), [z.';z.'])
 
 %!## tolerance test
-%!assert (cplxpair([1i, -1i, 1+(1i*eps)],2*eps), [-1i, 1i, 1+(1i*eps)]);
+%!assert (cplxpair ([1i, -1i, 1+(1i*eps)],2*eps), [-1i, 1i, 1+(1i*eps)])
+ 
--- a/scripts/general/cumtrapz.m
+++ b/scripts/general/cumtrapz.m
@@ -117,18 +117,18 @@
 %! x1 = [0,0,0;2,2,2];
 %! x2 = [0,2,4;0,2,4];
 %! y = [1,2,3;4,5,6];
-%!assert (cumtrapz(y), [0,0,0;2.5,3.5,4.5])
-%!assert (cumtrapz(x1,y), [0,0,0;5,7,9])
-%!assert (cumtrapz(y,1), [0,0,0;2.5,3.5,4.5])
-%!assert (cumtrapz(x1,y,1), [0,0,0;5,7,9])
-%!assert (cumtrapz(y,2), [0,1.5,4;0,4.5,10])
-%!assert (cumtrapz(x2,y,2), [0,3,8;0,9,20])
+%!assert (cumtrapz (y), [0,0,0;2.5,3.5,4.5])
+%!assert (cumtrapz (x1,y), [0,0,0;5,7,9])
+%!assert (cumtrapz (y,1), [0,0,0;2.5,3.5,4.5])
+%!assert (cumtrapz (x1,y,1), [0,0,0;5,7,9])
+%!assert (cumtrapz (y,2), [0,1.5,4;0,4.5,10])
+%!assert (cumtrapz (x2,y,2), [0,3,8;0,9,20])
 %% Test ND-array implementation
 %!shared x1,x2,y
 %! x1 = 1:3;
 %! x2 = reshape ([0,2,4;0,2,4], [1 2 3]);
 %! y = reshape ([1,2,3;4,5,6], [1 2 3]);
-%!assert (cumtrapz(y,3), reshape([0,1.5,4;0,4.5,10],[1 2 3]))
-%!assert (cumtrapz(x1,y,3), reshape([0,1.5,4;0,4.5,10],[1 2 3]))
-%!assert (cumtrapz(x2,y,3), reshape([0,3,8;0,9,20],[1 2 3]))
+%!assert (cumtrapz (y,3), reshape ([0,1.5,4;0,4.5,10],[1 2 3]))
+%!assert (cumtrapz (x1,y,3), reshape ([0,1.5,4;0,4.5,10],[1 2 3]))
+%!assert (cumtrapz (x2,y,3), reshape ([0,3,8;0,9,20],[1 2 3]))
 
--- a/scripts/general/curl.m
+++ b/scripts/general/curl.m
@@ -71,7 +71,7 @@
     dy = varargin{2}(:,1,1)(:);
     dz = varargin{3}(1,1,:)(:);
   else
-    print_usage();
+    print_usage ();
   endif
 
   if ((nargin == 4) || (nargin == 2))
@@ -129,14 +129,16 @@
 
 endfunction
 
+
 %!test
-%! [X,Y]=meshgrid(-20:20,-22:22);
-%! av = curl(2*(X-Y),Y);
-%! assert(all(av(:)==1));
-%! [cz,av] = curl(2*(X-Y),Y);
-%! assert(all(cz(:)==2));
-%! assert(all(av(:)==1));
-%! [cz,av] = curl(X/2,Y/2,2*(X-Y),Y);
-%! assert(all(cz(:)==4));
-%! assert(all(av(:)==2));
-%! assert(size_equal(X,Y,cz,av));
+%! [X,Y] = meshgrid (-20:20,-22:22);
+%! av = curl (2*(X-Y), Y);
+%! assert (all (av(:) == 1));
+%! [cz,av] = curl (2*(X-Y), Y);
+%! assert (all (cz(:) == 2));
+%! assert (all (av(:) == 1));
+%! [cz,av] = curl (X/2, Y/2, 2*(X-Y), Y);
+%! assert (all (cz(:) == 4));
+%! assert (all (av(:) == 2));
+%! assert (size_equal (X,Y,cz,av));
+
--- a/scripts/general/dblquad.m
+++ b/scripts/general/dblquad.m
@@ -67,16 +67,17 @@
 endfunction
 
 function q = __dblquad_inner__ (y, f, xa, xb, tol, quadf, varargin)
-  q = zeros (size(y));
+  q = zeros (size (y));
   for i = 1 : length (y)
     q(i) = feval (quadf, @(x) f(x, y(i), varargin{:}), xa, xb, tol);
   endfor
 endfunction
 
+
 %% Nasty integrand to show quadcc off
-%!assert (dblquad (@(x,y) 1 ./ (x+y), 0, 1, 0, 1), 2*log(2), 1e-6)
+%!assert (dblquad (@(x,y) 1 ./ (x+y), 0, 1, 0, 1), 2*log (2), 1e-6)
 
-%!assert (dblquad (@(x,y) exp(-x.^2 - y.^2) , -1, 1, -1, 1, 1e-6, @quadgk), pi * erf(1).^2, 1e-6)
-%!assert (dblquad (@(x,y) exp(-x.^2 - y.^2) , -1, 1, -1, 1, 1e-6, @quadl), pi * erf(1).^2, 1e-6)
-%!assert (dblquad (@(x,y) exp(-x.^2 - y.^2) , -1, 1, -1, 1, 1e-6, @quadv), pi * erf(1).^2, 1e-6)
+%!assert (dblquad (@(x,y) exp (-x.^2 - y.^2) , -1, 1, -1, 1, 1e-6, @quadgk), pi * erf (1).^2, 1e-6)
+%!assert (dblquad (@(x,y) exp (-x.^2 - y.^2) , -1, 1, -1, 1, 1e-6, @quadl), pi * erf (1).^2, 1e-6)
+%!assert (dblquad (@(x,y) exp (-x.^2 - y.^2) , -1, 1, -1, 1, 1e-6, @quadv), pi * erf (1).^2, 1e-6)
 
--- a/scripts/general/deal.m
+++ b/scripts/general/deal.m
@@ -73,11 +73,13 @@
 
 endfunction
 
+
 %!test
-%! [a,b]=deal(1,2);
-%! assert(a,1);
-%! assert(b,2);
+%! [a,b] = deal (1,2);
+%! assert (a, 1);
+%! assert (b, 2);
 %!test
-%! [a,b]=deal(1);
-%! assert(a,1);
-%! assert(b,1);
+%! [a,b] = deal (1);
+%! assert (a, 1);
+%! assert (b, 1);
+
--- a/scripts/general/divergence.m
+++ b/scripts/general/divergence.m
@@ -69,7 +69,7 @@
     dy = varargin{2}(:,1,1)(:);
     dz = varargin{3}(1,1,:)(:);
   else
-    print_usage();
+    print_usage ();
   endif
 
   if ((nargin == 4) || (nargin == 2))
@@ -81,8 +81,8 @@
       error ("divergence: size of dx and dy must match the respective dimension of X and Y");
     endif
 
-    retval = gradient(varargin{fidx}, dx, dy);
-    retval += gradient(varargin{fidx + 1}.', dy, dx).';
+    retval = gradient (varargin{fidx}, dx, dy);
+    retval += gradient (varargin{fidx + 1}.', dy, dx).';
 
   elseif ((nargin == 6) || (nargin == 3))
     if (!size_equal (varargin{fidx},varargin{fidx + 1},varargin{fidx + 2}))
@@ -105,8 +105,10 @@
 
 endfunction
 
+
 %!test
-%! [X,Y]=meshgrid(-20:20,-22:22);
-%! div = divergence(X-Y,Y);
-%! assert(all(div(:)==2));
-%! assert(size_equal(X,Y,div));
+%! [X,Y] = meshgrid (-20:20,-22:22);
+%! div = divergence (X-Y,Y);
+%! assert (all (div(:) == 2));
+%! assert (size_equal (X,Y,div));
+
new file mode 100644
--- /dev/null
+++ b/scripts/general/fieldnames.m
@@ -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, ';', false);
+  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/flipdim.m
+++ b/scripts/general/flipdim.m
@@ -57,11 +57,13 @@
 
 endfunction
 
-%!error flipdim ();
-%!error flipdim (1, 2, 3);
 
-%!assert (flipdim ([1,2;3,4]), flipdim ([1,2 ; 3,4], 1));
-%!assert (flipdim ([1,2;3,4], 2), [2,1;4,3]);
-%!assert (flipdim ([1,2;3,4], 3), [1,2;3,4]);
+%!assert (flipdim ([1,2;3,4]), flipdim ([1,2 ; 3,4], 1))
+%!assert (flipdim ([1,2;3,4], 2), [2,1;4,3])
+%!assert (flipdim ([1,2;3,4], 3), [1,2;3,4])
 
 ## FIXME -- we need tests for multidimensional arrays.
+
+%!error flipdim ()
+%!error flipdim (1, 2, 3)
+
--- a/scripts/general/fliplr.m
+++ b/scripts/general/fliplr.m
@@ -52,11 +52,11 @@
 
 endfunction
 
-%!assert((fliplr ([1, 2; 3, 4]) == [2, 1; 4, 3]
-%! && fliplr ([1, 2; 3, 4; 5, 6]) == [2, 1; 4, 3; 6, 5]
-%! && fliplr ([1, 2, 3; 4, 5, 6]) == [3, 2, 1; 6, 5, 4]));
 
-%!error fliplr();
+%!assert (fliplr ([1, 2; 3, 4]), [2, 1; 4, 3])
+%!assert (fliplr ([1, 2; 3, 4; 5, 6]), [2, 1; 4, 3; 6, 5])
+%!assert (fliplr ([1, 2, 3; 4, 5, 6]), [3, 2, 1; 6, 5, 4])
 
-%!error fliplr (1, 2);
+%!error fliplr()
+%!error fliplr (1, 2)
 
--- a/scripts/general/flipud.m
+++ b/scripts/general/flipud.m
@@ -52,11 +52,11 @@
 
 endfunction
 
-%!assert((flipud ([1, 2; 3, 4]) == [3, 4; 1, 2]
-%! && flipud ([1, 2; 3, 4; 5, 6]) == [5, 6; 3, 4; 1, 2]
-%! && flipud ([1, 2, 3; 4, 5, 6]) == [4, 5, 6; 1, 2, 3]));
 
-%!error flipud ();
+%!assert (flipud ([1, 2; 3, 4]), [3, 4; 1, 2])
+%!assert (flipud ([1, 2; 3, 4; 5, 6]), [5, 6; 3, 4; 1, 2])
+%!assert (flipud ([1, 2, 3; 4, 5, 6]), [4, 5, 6; 1, 2, 3])
 
-%!error flipud (1, 2);
+%!error flipud ()
+%!error flipud (1, 2)
 
--- a/scripts/general/genvarname.m
+++ b/scripts/general/genvarname.m
@@ -158,45 +158,45 @@
     endif
     varname(i) = str(i);
     idx = 0;
-    while excluded
+    while (excluded)
       idx++;
-      varname{i} = sprintf("%s%d", str{i}, idx);
+      varname{i} = sprintf ("%s%d", str{i}, idx);
       excluded = any (strcmp (varname{i}, exclusions));
     endwhile
     exclusions(end+1) = varname(i);
   endfor
 
-  if strinput
+  if (strinput)
     varname = varname{1};
   endif
 
 endfunction
 
-## Tests
+
 ## a single argument
-%!assert(genvarname("a"), "a")
+%!assert (genvarname ("a"), "a")
 ## a single argument with a non-conflicting exception
-%!assert(genvarname("a", "b"), "a")
+%!assert (genvarname ("a", "b"), "a")
 ## a single argument with a conflicting exception
-%!assert(genvarname("a", "a"), "a1")
+%!assert (genvarname ("a", "a"), "a1")
 ## a single argument as a cell
-%!assert(genvarname({"a"}), {"a"})
-%!assert(genvarname({"a"}, "b"), {"a"})
-%!assert(genvarname({"a"}, {"b"}), {"a"})
-%!assert(genvarname({"a"}, "a"), {"a1"})
-%!assert(genvarname({"a"}, {"a"}), {"a1"})
+%!assert (genvarname ({"a"}), {"a"})
+%!assert (genvarname ({"a"}, "b"), {"a"})
+%!assert (genvarname ({"a"}, {"b"}), {"a"})
+%!assert (genvarname ({"a"}, "a"), {"a1"})
+%!assert (genvarname ({"a"}, {"a"}), {"a1"})
 ## Test different arguments
 ## orientation
-%!assert(genvarname({"a" "b"}), {"a" "b"})
-%!assert(genvarname({"a";"b"}), {"a";"b"})
-%!assert(genvarname({"a" "a"}), {"a" "a1"})
-%!assert(genvarname({"a" "b";"c" "d"}), {"a" "b";"c" "d"})
-%!assert(genvarname({"a" "a" "a";"a" "a" "a"}), {"a" "a2" "a4";"a1" "a3" "a5"})
+%!assert (genvarname ({"a" "b"}), {"a" "b"})
+%!assert (genvarname ({"a";"b"}), {"a";"b"})
+%!assert (genvarname ({"a" "a"}), {"a" "a1"})
+%!assert (genvarname ({"a" "b";"c" "d"}), {"a" "b";"c" "d"})
+%!assert (genvarname ({"a" "a" "a";"a" "a" "a"}), {"a" "a2" "a4";"a1" "a3" "a5"})
 ## more than one repetition
-%!assert(genvarname({"a" "a" "a"}), {"a" "a1" "a2"})
-%!assert(genvarname({"a" "a" "a"}, {"a" "a1" "a2"}), {"a3" "a4" "a5"})
+%!assert (genvarname ({"a" "a" "a"}), {"a" "a1" "a2"})
+%!assert (genvarname ({"a" "a" "a"}, {"a" "a1" "a2"}), {"a3" "a4" "a5"})
 ## more than one repetition not in order
-%!assert(genvarname({"a" "b" "a" "b" "a"}), {"a" "b" "a1" "b1" "a2"})
+%!assert (genvarname ({"a" "b" "a" "b" "a"}), {"a" "b" "a1" "b1" "a2"})
 ## Variable name munging
 %!assert (genvarname ("__x__"), "_x_")
 %!assert (genvarname ("123456789"), "_123456789")
@@ -206,3 +206,4 @@
 %!assert (genvarname ({"", "", ""}), {"x", "x1", "x2"})
 %!assert (genvarname ("if"), "_if")
 %!assert (genvarname ({"if", "if", "if"}), {"_if", "_if1", "_if2"})
+
--- a/scripts/general/gradient.m
+++ b/scripts/general/gradient.m
@@ -70,12 +70,12 @@
     print_usage ();
   endif
 
-  nargout_with_ans = max(1,nargout);
+  nargout_with_ans = max (1,nargout);
   if (ismatrix (m))
     [varargout{1:nargout_with_ans}] = matrix_gradient (m, varargin{:});
   elseif (isa (m, "function_handle"))
     [varargout{1:nargout_with_ans}] = handle_gradient (m, varargin{:});
-  elseif (ischar(m))
+  elseif (ischar (m))
     [varargout{1:nargout_with_ans}] = handle_gradient (str2func (m), varargin{:});
   else
     error ("gradient: first input must be an array or a function");
@@ -87,13 +87,13 @@
   transposed = false;
   if (isvector (m))
     ## make a row vector.
-    transposed = (size (m, 2) == 1);
+    transposed = (columns (m) == 1);
     m = m(:).';
   endif
 
   nd = ndims (m);
   sz = size (m);
-  if (length(sz) > 1)
+  if (length (sz) > 1)
     tmp = sz(1); sz(1) = sz(2); sz(2) = tmp;
   endif
 
@@ -220,6 +220,7 @@
   endfor
 endfunction
 
+
 %!test
 %! data = [1, 2, 4, 2];
 %! dx = gradient (data);
@@ -228,63 +229,63 @@
 %! assert (dx, [1, 3/2, 0, -2]);
 %! assert (dx2, [4, 6, 0, -8]);
 %! assert (dx3, [4, 4, 0, -1]);
-%! assert (size_equal(data, dx));
+%! assert (size_equal (data, dx));
 
 %!test
 %! [Y,X,Z,U] = ndgrid (2:2:8,1:5,4:4:12,3:5:30);
 %! [dX,dY,dZ,dU] = gradient (X);
-%! assert (all(dX(:)==1));
-%! assert (all(dY(:)==0));
-%! assert (all(dZ(:)==0));
-%! assert (all(dU(:)==0));
+%! assert (all (dX(:) == 1));
+%! assert (all (dY(:) == 0));
+%! assert (all (dZ(:) == 0));
+%! assert (all (dU(:) == 0));
 %! [dX,dY,dZ,dU] = gradient (Y);
-%! assert (all(dX(:)==0));
-%! assert (all(dY(:)==2));
-%! assert (all(dZ(:)==0));
-%! assert (all(dU(:)==0));
+%! assert (all (dX(:) == 0));
+%! assert (all (dY(:) == 2));
+%! assert (all (dZ(:) == 0));
+%! assert (all (dU(:) == 0));
 %! [dX,dY,dZ,dU] = gradient (Z);
-%! assert (all(dX(:)==0));
-%! assert (all(dY(:)==0));
-%! assert (all(dZ(:)==4));
-%! assert (all(dU(:)==0));
+%! assert (all (dX(:) == 0));
+%! assert (all (dY(:) == 0));
+%! assert (all (dZ(:) == 4));
+%! assert (all (dU(:) == 0));
 %! [dX,dY,dZ,dU] = gradient (U);
-%! assert (all(dX(:)==0));
-%! assert (all(dY(:)==0));
-%! assert (all(dZ(:)==0));
-%! assert (all(dU(:)==5));
-%! assert (size_equal(dX, dY, dZ, dU, X, Y, Z, U));
+%! assert (all (dX(:) == 0));
+%! assert (all (dY(:) == 0));
+%! assert (all (dZ(:) == 0));
+%! assert (all (dU(:) == 5));
+%! assert (size_equal (dX, dY, dZ, dU, X, Y, Z, U));
 %! [dX,dY,dZ,dU] = gradient (U, 5.0);
-%! assert (all(dU(:)==1));
+%! assert (all (dU(:) == 1));
 %! [dX,dY,dZ,dU] = gradient (U, 1.0, 2.0, 3.0, 2.5);
-%! assert (all(dU(:)==2));
+%! assert (all (dU(:) == 2));
 
 %!test
 %! [Y,X,Z,U] = ndgrid (2:2:8,1:5,4:4:12,3:5:30);
 %! [dX,dY,dZ,dU] = gradient (X+j*X);
-%! assert (all(dX(:)==1+1j));
-%! assert (all(dY(:)==0));
-%! assert (all(dZ(:)==0));
-%! assert (all(dU(:)==0));
+%! assert (all (dX(:) == 1+1j));
+%! assert (all (dY(:) == 0));
+%! assert (all (dZ(:) == 0));
+%! assert (all (dU(:) == 0));
 %! [dX,dY,dZ,dU] = gradient (Y-j*Y);
-%! assert (all(dX(:)==0));
-%! assert (all(dY(:)==2-j*2));
-%! assert (all(dZ(:)==0));
-%! assert (all(dU(:)==0));
+%! assert (all (dX(:) == 0));
+%! assert (all (dY(:) == 2-j*2));
+%! assert (all (dZ(:) == 0));
+%! assert (all (dU(:) == 0));
 %! [dX,dY,dZ,dU] = gradient (Z+j*1);
-%! assert (all(dX(:)==0));
-%! assert (all(dY(:)==0));
-%! assert (all(dZ(:)==4));
-%! assert (all(dU(:)==0));
+%! assert (all (dX(:) == 0));
+%! assert (all (dY(:) == 0));
+%! assert (all (dZ(:) == 4));
+%! assert (all (dU(:) == 0));
 %! [dX,dY,dZ,dU] = gradient (U-j*1);
-%! assert (all(dX(:)==0));
-%! assert (all(dY(:)==0));
-%! assert (all(dZ(:)==0));
-%! assert (all(dU(:)==5));
-%! assert (size_equal(dX, dY, dZ, dU, X, Y, Z, U));
+%! assert (all (dX(:) == 0));
+%! assert (all (dY(:) == 0));
+%! assert (all (dZ(:) == 0));
+%! assert (all (dU(:) == 5));
+%! assert (size_equal (dX, dY, dZ, dU, X, Y, Z, U));
 %! [dX,dY,dZ,dU] = gradient (U, 5.0);
-%! assert (all(dU(:)==1));
+%! assert (all (dU(:) == 1));
 %! [dX,dY,dZ,dU] = gradient (U, 1.0, 2.0, 3.0, 2.5);
-%! assert (all(dU(:)==2));
+%! assert (all (dU(:) == 2));
 
 %!test
 %! x = 0:10;
--- a/scripts/general/idivide.m
+++ b/scripts/general/idivide.m
@@ -100,25 +100,27 @@
   endif
 endfunction
 
+
 %!shared a, af, b, bf
-%! a = int8(3);
+%! a = int8 (3);
 %! af = 3;
-%! b = int8([-4, 4]);
+%! b = int8 ([-4, 4]);
 %! bf = [-4, 4];
 
 %!assert (idivide (a, b), int8 ([0, 0]))
-%!assert (idivide (a, b, "floor"), int8([-1, 0]))
+%!assert (idivide (a, b, "floor"), int8 ([-1, 0]))
 %!assert (idivide (a, b, "ceil"), int8 ([0, 1]))
 %!assert (idivide (a, b, "round"), int8 ([-1, 1]))
 
 %!assert (idivide (af, b), int8 ([0, 0]))
-%!assert (idivide (af, b, "floor"), int8([-1, 0]))
+%!assert (idivide (af, b, "floor"), int8 ([-1, 0]))
 %!assert (idivide (af, b, "ceil"), int8 ([0, 1]))
 %!assert (idivide (af, b, "round"), int8 ([-1, 1]))
 
 %!assert (idivide (a, bf), int8 ([0, 0]))
-%!assert (idivide (a, bf, "floor"), int8([-1, 0]))
+%!assert (idivide (a, bf, "floor"), int8 ([-1, 0]))
 %!assert (idivide (a, bf, "ceil"), int8 ([0, 1]))
 %!assert (idivide (a, bf, "round"), int8 ([-1, 1]))
 
-%!error (idivide (uint8(1), int8(1)))
+%!error (idivide (uint8 (1), int8 (1)))
+
--- a/scripts/general/int2str.m
+++ b/scripts/general/int2str.m
@@ -32,7 +32,7 @@
 ##         4  5  6
 ##
 ## whos s
-##      @result{} s =
+##      @result{}
 ##       Attr Name        Size                     Bytes  Class
 ##       ==== ====        ====                     =====  =====
 ##            s           2x7                         14  char
@@ -57,8 +57,8 @@
     return;
   endif
 
-  n = round (real(n));
-  sz = size(n);
+  n = round (real (n));
+  sz = size (n);
   nd = ndims (n);
   nc = columns (n);
   if (nc > 1)
@@ -73,7 +73,7 @@
   endif
   tmp = sprintf (fmt, permute (n, [2, 1, 3 : nd]));
   tmp(end) = "";
-  retval = char (strsplit (tmp, "\n"));
+  retval = char (strsplit (tmp, "\n", false));
 
 endfunction
 
@@ -113,10 +113,12 @@
 
 endfunction
 
-%!assert (strcmp (int2str (-123), "-123") && strcmp (int2str (1.2), "1"));
-%!assert (all (int2str ([1, 2, 3; 4, 5, 6]) == ["1  2  3";"4  5  6"]));
-%!assert (int2str([]), "");
 
-%!error int2str ();
-%!error int2str (1, 2);
+%!assert (int2str (-123), "-123")
+%!assert (int2str (1.2), "1")
+%!assert (int2str ([1, 2, 3; 4, 5, 6]), ["1  2  3";"4  5  6"])
+%!assert (int2str ([]), "")
 
+%!error int2str ()
+%!error int2str (1, 2)
+
--- a/scripts/general/interp1.m
+++ b/scripts/general/interp1.m
@@ -22,56 +22,59 @@
 ## @deftypefnx {Function File} {@var{yi} =} interp1 (@var{y}, @var{xi})
 ## @deftypefnx {Function File} {@var{yi} =} interp1 (@dots{}, @var{method})
 ## @deftypefnx {Function File} {@var{yi} =} interp1 (@dots{}, @var{extrap})
-## @deftypefnx {Function File} {@var{pp} =} interp1 (@dots{}, 'pp')
+## @deftypefnx {Function File} {@var{pp} =} interp1 (@dots{}, "pp")
 ##
-## One-dimensional interpolation.  Interpolate @var{y}, defined at the
-## points @var{x}, at the points @var{xi}.  The sample points @var{x}
-## must be monotonic.  If not specified, @var{x} is taken to be the
-## indices of @var{y}.  If @var{y} is an array, treat the columns
+## One-dimensional interpolation.  Interpolates to determine the value of
+## @var{yi} at the points, @var{xi}.  If not specified, @var{x} is taken
+## to be the indices of @var{y}.  If @var{y} is an array, treat the columns
 ## of @var{y} separately.
 ##
 ## Method is one of:
 ##
 ## @table @asis
-## @item 'nearest'
+## @item "nearest"
 ## Return the nearest neighbor.
 ##
-## @item 'linear'
+## @item "linear"
 ## Linear interpolation from nearest neighbors
 ##
-## @item 'pchip'
+## @item "pchip"
 ## Piecewise cubic Hermite interpolating polynomial
 ##
-## @item 'cubic'
+## @item "cubic"
 ## Cubic interpolation (same as @code{pchip})
 ##
-## @item 'spline'
+## @item "spline"
 ## Cubic spline interpolation---smooth first and second derivatives
 ## throughout the curve
 ## @end table
 ##
 ## Appending '*' to the start of the above method forces @code{interp1}
-## to assume that @var{x} is uniformly spaced, and only @code{@var{x}
-## (1)} and @code{@var{x} (2)} are referenced.  This is usually faster,
-## and is never slower.  The default method is 'linear'.
+## to assume that @var{x} is uniformly spaced, and only @code{@var{x}(1)}
+## and @code{@var{x}(2)} are referenced.  This is usually faster,
+## and is never slower.  The default method is "linear".
 ##
-## If @var{extrap} is the string 'extrap', then extrapolate values beyond
+## If @var{extrap} is the string "extrap", then extrapolate values beyond
 ## the endpoints.  If @var{extrap} is a number, replace values beyond the
 ## endpoints with that number.  If @var{extrap} is missing, assume NA.
 ##
-## If the string argument 'pp' is specified, then @var{xi} should not be
+## If the string argument "pp" is specified, then @var{xi} should not be
 ## supplied and @code{interp1} returns the piecewise polynomial that
 ## can later be used with @code{ppval} to evaluate the interpolation.
 ## There is an equivalence, such that @code{ppval (interp1 (@var{x},
-## @var{y}, @var{method}, 'pp'), @var{xi}) == interp1 (@var{x}, @var{y},
-## @var{xi}, @var{method}, 'extrap')}.
+## @var{y}, @var{method}, "pp"), @var{xi}) == interp1 (@var{x}, @var{y},
+## @var{xi}, @var{method}, "extrap")}.
 ##
 ## Duplicate points in @var{x} specify a discontinuous interpolant.  There
-## should be at most 2 consecutive points with the same value.
-## The discontinuous interpolant is right-continuous if @var{x} is increasing,
-## left-continuous if it is decreasing.
-## Discontinuities are (currently) only allowed for "nearest" and "linear"
-## methods; in all other cases, @var{x} must be strictly monotonic.
+## may be at most 2 consecutive points with the same value.
+## If @var{x} is increasing, the default discontinuous interpolant is
+## right-continuous. If @var{x} is decreasing, the default discontinuous
+## interpolant is left-continuous.
+## The continuity condition of the interpolant may be specified by using
+## the options, "-left" or "-right", to select a left-continuous
+## or right-continuous interpolant, respectively.
+## Discontinuous interpolation is only allowed for "nearest" and "linear"
+## methods; in all other cases, the @var{x}-values must be unique.
 ##
 ## An example of the use of @code{interp1} is
 ##
@@ -114,6 +117,7 @@
   xi = [];
   ispp = false;
   firstnumeric = true;
+  rightcontinuous = [];
 
   if (nargin > 2)
     for i = 1:length (varargin)
@@ -124,6 +128,10 @@
           extrap = "extrap";
         elseif (strcmp ("pp", arg))
           ispp = true;
+        elseif (any (strcmp ({"right", "-right"}, arg)))
+          rightcontinuous = true;
+        elseif (any (strcmp ({"left", "-left"}, arg)))
+          rightcontinuous = false;
         else
           method = arg;
         endif
@@ -141,7 +149,7 @@
   if (isempty (xi) && firstnumeric && ! ispp)
     xi = y;
     y = x;
-    x = 1:numel(y);
+    x = 1:numel (y);
   endif
 
   ## reshape matrices for convenience
@@ -168,26 +176,41 @@
     y = y(p,:);
   endif
 
+  if (isempty (rightcontinuous))
+    ## If not specified, set the continuity condition
+    if (x(end) < x(1))
+      rightcontinuous = false;
+    else
+      rightcontinuous = true;
+    end
+  endif
+
+  if ((rightcontinuous && (x(end) < x(1)))
+      || (~ rightcontinuous && (x(end) > x(1))))
+    ## Switch between left-continuous and right-continuous
+    x = flipud (x);
+    y = flipud (y);
+  end
+
   starmethod = method(1) == "*";
 
   if (starmethod)
     dx = x(2) - x(1);
   else
-    jumps = x(1:nx-1) == x(2:nx);
+    jumps = x(1:end-1) == x(2:end);
     have_jumps = any (jumps);
     if (have_jumps)
       if (any (strcmp (method, {"nearest", "linear"})))
         if (any (jumps(1:nx-2) & jumps(2:nx-1)))
-          warning ("interp1: extra points in discontinuities");
+          error ("interp1: extra points in discontinuities");
         endif
       else
-        error ("interp1: discontinuities not supported for method %s", method);
+        error ("interp1: discontinuities not supported for method '%s'", method);
       endif
     endif
   endif
 
   ## Proceed with interpolating by all methods.
-
   switch (method)
   case "nearest"
     pp = mkpp ([x(1); (x(1:nx-1)+x(2:nx))/2; x(nx)], shiftdim (y, 1), szy(2:end));
@@ -204,7 +227,7 @@
     if (ispp)
       yi = pp;
     else
-      yi = ppval(pp, reshape (xi, szx));
+      yi = ppval (pp, reshape (xi, szx));
     endif
   case "linear"
     dy = diff (y);
@@ -225,7 +248,7 @@
     if (ispp)
       yi = pp;
     else
-      yi = ppval(pp, reshape (xi, szx));
+      yi = ppval (pp, reshape (xi, szx));
     endif
 
   case "*linear"
@@ -237,7 +260,7 @@
     if (ispp)
       yi = pp;
     else
-      yi = ppval(pp, reshape (xi, szx));
+      yi = ppval (pp, reshape (xi, szx));
     endif
 
   case {"pchip", "*pchip", "cubic", "*cubic"}
@@ -248,21 +271,29 @@
     if (ispp)
       y = shiftdim (reshape (y, szy), 1);
       yi = pchip (x, y);
+      yi.orient = "first";
     else
       y = shiftdim (y, 1);
       yi = pchip (x, y, reshape (xi, szx));
+      if (! isvector (y))
+        yi = shiftdim (yi, 1);
+      endif
     endif
   case {"spline", "*spline"}
     if (nx == 2 || starmethod)
-      x = linspace(x(1), x(nx), ny);
+      x = linspace (x(1), x(nx), ny);
     endif
 
     if (ispp)
       y = shiftdim (reshape (y, szy), 1);
       yi = spline (x, y);
+      yi.orient = "first";
     else
       y = shiftdim (y, 1);
       yi = spline (x, y, reshape (xi, szx));
+      if (! isvector (y))
+        yi = shiftdim (yi, 1);
+      endif
     endif
   otherwise
     error ("interp1: invalid method '%s'", method);
@@ -280,287 +311,307 @@
         yi(outliers) = extrap;
         yi = reshape (yi, szx);
       elseif (!isvector (yi))
-        if (strcmp (method, "pchip") || strcmp (method, "*pchip")
-          ||strcmp (method, "cubic") || strcmp (method, "*cubic")
-          ||strcmp (method, "spline") || strcmp (method, "*spline"))
-          yi(:, outliers) = extrap;
-          yi = shiftdim(yi, 1);
-        else
-          yi(outliers, :) = extrap;
-        endif
+        yi(outliers, :) = extrap;
       else
         yi(outliers.') = extrap;
       endif
     endif
-  else
-    yi.orient = "first";
   endif
 
 endfunction
 
+
 %!demo
-%! xf=0:0.05:10; yf = sin(2*pi*xf/5);
-%! xp=0:10;      yp = sin(2*pi*xp/5);
-%! lin=interp1(xp,yp,xf,"linear");
-%! spl=interp1(xp,yp,xf,"spline");
-%! cub=interp1(xp,yp,xf,"pchip");
-%! near=interp1(xp,yp,xf,"nearest");
-%! plot(xf,yf,"r",xf,near,"g",xf,lin,"b",xf,cub,"c",xf,spl,"m",xp,yp,"r*");
-%! legend ("original","nearest","linear","pchip","spline")
+%! clf;
+%! xf = 0:0.05:10;  yf = sin (2*pi*xf/5);
+%! xp = 0:10;       yp = sin (2*pi*xp/5);
+%! lin = interp1 (xp,yp,xf, "linear");
+%! spl = interp1 (xp,yp,xf, "spline");
+%! cub = interp1 (xp,yp,xf, "pchip");
+%! near= interp1 (xp,yp,xf, "nearest");
+%! plot (xf,yf,"r",xf,near,"g",xf,lin,"b",xf,cub,"c",xf,spl,"m",xp,yp,"r*");
+%! legend ("original", "nearest", "linear", "pchip", "spline");
+%! %--------------------------------------------------------
+%! % confirm that interpolated function matches the original
+
+%!demo
+%! clf;
+%! xf = 0:0.05:10;  yf = sin (2*pi*xf/5);
+%! xp = 0:10;       yp = sin (2*pi*xp/5);
+%! lin = interp1 (xp,yp,xf, "*linear");
+%! spl = interp1 (xp,yp,xf, "*spline");
+%! cub = interp1 (xp,yp,xf, "*cubic");
+%! near= interp1 (xp,yp,xf, "*nearest");
+%! plot (xf,yf,"r",xf,near,"g",xf,lin,"b",xf,cub,"c",xf,spl,"m",xp,yp,"r*");
+%! legend ("*original", "*nearest", "*linear", "*cubic", "*spline");
 %! %--------------------------------------------------------
 %! % confirm that interpolated function matches the original
 
 %!demo
-%! xf=0:0.05:10; yf = sin(2*pi*xf/5);
-%! xp=0:10;      yp = sin(2*pi*xp/5);
-%! lin=interp1(xp,yp,xf,"*linear");
-%! spl=interp1(xp,yp,xf,"*spline");
-%! cub=interp1(xp,yp,xf,"*cubic");
-%! near=interp1(xp,yp,xf,"*nearest");
-%! plot(xf,yf,"r",xf,near,"g",xf,lin,"b",xf,cub,"c",xf,spl,"m",xp,yp,"r*");
-%! legend ("*original","*nearest","*linear","*cubic","*spline")
-%! %--------------------------------------------------------
-%! % confirm that interpolated function matches the original
-
-%!demo
+%! clf;
 %! t = 0 : 0.3 : pi; dt = t(2)-t(1);
 %! n = length (t); k = 100; dti = dt*n/k;
 %! ti = t(1) + [0 : k-1]*dti;
 %! y = sin (4*t + 0.3) .* cos (3*t - 0.1);
-%! ddyc = diff(diff(interp1(t,y,ti,'cubic'))./dti)./dti;
-%! ddys = diff(diff(interp1(t,y,ti,'spline'))./dti)./dti;
-%! ddyp = diff(diff(interp1(t,y,ti,'pchip'))./dti)./dti;
-%! plot (ti(2:end-1), ddyc,'g+',ti(2:end-1),ddys,'b*', ...
-%!       ti(2:end-1),ddyp,'c^');
-%! legend('cubic','spline','pchip');
-%! title("Second derivative of interpolated 'sin (4*t + 0.3) .* cos (3*t - 0.1)'");
+%! ddyc = diff (diff (interp1 (t,y,ti, "cubic")) ./dti)./dti;
+%! ddys = diff (diff (interp1 (t,y,ti, "spline"))./dti)./dti;
+%! ddyp = diff (diff (interp1 (t,y,ti, "pchip")) ./dti)./dti;
+%! plot (ti(2:end-1),ddyc,'g+', ti(2:end-1),ddys,'b*', ti(2:end-1),ddyp,'c^');
+%! legend ("cubic", "spline", "pchip");
+%! title ("Second derivative of interpolated 'sin (4*t + 0.3) .* cos (3*t - 0.1)'");
 
 %!demo
-%! xf=0:0.05:10; yf = sin(2*pi*xf/5) - (xf >= 5);
-%! xp=[0:.5:4.5,4.99,5:.5:10];      yp = sin(2*pi*xp/5) - (xp >= 5);
-%! lin=interp1(xp,yp,xf,"linear");
-%! near=interp1(xp,yp,xf,"nearest");
-%! plot(xf,yf,"r",xf,near,"g",xf,lin,"b",xp,yp,"r*");
-%! legend ("original","nearest","linear")
+%! clf;
+%! xf = 0:0.05:10;                yf = sin (2*pi*xf/5) - (xf >= 5);
+%! xp = [0:.5:4.5,4.99,5:.5:10];  yp = sin (2*pi*xp/5) - (xp >= 5);
+%! lin = interp1 (xp,yp,xf, "linear");
+%! near= interp1 (xp,yp,xf, "nearest");
+%! plot (xf,yf,"r", xf,near,"g", xf,lin,"b", xp,yp,"r*");
+%! legend ("original", "nearest", "linear");
 %! %--------------------------------------------------------
 %! % confirm that interpolated function matches the original
 
+%!demo
+%! clf;
+%! x = 0:0.5:3;
+%! x1 = [3 2 2 1];
+%! x2 = [1 2 2 3];
+%! y1 = [1 1 0 0];
+%! y2 = [0 0 1 1];
+%! h = plot (x, interp1 (x1, y1, x), 'b', x1, y1, 'sb');
+%! hold on
+%! g = plot (x, interp1 (x2, y2, x), 'r', x2, y2, '*r');
+%! xlim ([1 3])
+%! legend ([h(1), g(1)], {'left-continous', 'right-continuous'}, ...
+%!         'location', 'east')
+%! legend boxoff
+%! %--------------------------------------------------------
+%! % red curve is left-continuos and blue is right-continuous at x = 2
+
 ##FIXME: add test for n-d arguments here
 
 ## For each type of interpolated test, confirm that the interpolated
 ## value at the knots match the values at the knots.  Points away
-## from the knots are requested, but only 'nearest' and 'linear'
+## from the knots are requested, but only "nearest" and "linear"
 ## confirm they are the correct values.
 
 %!shared xp, yp, xi, style
-%! xp=0:2:10;      yp = sin(2*pi*xp/5);
+%! xp = 0:2:10;
+%! yp = sin (2*pi*xp/5);
 %! xi = [-1, 0, 2.2, 4, 6.6, 10, 11];
 
-
 ## The following BLOCK/ENDBLOCK section is repeated for each style
 ##    nearest, linear, cubic, spline, pchip
 ## The test for ppval of cubic has looser tolerance, but otherwise
 ## the tests are identical.
 ## Note that the block checks style and *style; if you add more tests
-## before to add them to both sections of each block.  One test,
+## be sure to add them to both sections of each block.  One test,
 ## style vs. *style, occurs only in the first section.
 ## There is an ENDBLOCKTEST after the final block
+
 %!test style = "nearest";
 ## BLOCK
-%!assert (interp1(xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA]);
-%!assert (interp1(xp,yp,xp,style), yp, 100*eps);
-%!assert (interp1(xp,yp,xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp,style), yp, 100*eps);
-%!assert (isempty(interp1(xp',yp',[],style)));
-%!assert (isempty(interp1(xp,yp,[],style)));
-%!assert (interp1(xp,[yp',yp'],xi(:),style),...
-%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)]);
-%!assert (interp1(xp,yp,xi,style),...
-%!        interp1(fliplr(xp),fliplr(yp),xi,style),100*eps);
-%!assert (ppval(interp1(xp,yp,style,"pp"),xi),
-%!        interp1(xp,yp,xi,style,"extrap"),10*eps);
-%!error interp1(1,1,1, style);
-%!assert (interp1(xp,[yp',yp'],xi,style),
-%!        interp1(xp,[yp',yp'],xi,["*",style]),100*eps);
-%!test style=['*',style];
-%!assert (interp1(xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA]);
-%!assert (interp1(xp,yp,xp,style), yp, 100*eps);
-%!assert (interp1(xp,yp,xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp,style), yp, 100*eps);
-%!assert (isempty(interp1(xp',yp',[],style)));
-%!assert (isempty(interp1(xp,yp,[],style)));
-%!assert (interp1(xp,[yp',yp'],xi(:),style),...
-%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)]);
-%!assert (interp1(xp,yp,xi,style),...
-%!        interp1(fliplr(xp),fliplr(yp),xi,style),100*eps);
-%!assert (ppval(interp1(xp,yp,style,"pp"),xi),
-%!        interp1(xp,yp,xi,style,"extrap"),10*eps);
-%!error interp1(1,1,1, style);
+%!assert (interp1 (xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA])
+%!assert (interp1 (xp,yp,xp,style), yp, 100*eps)
+%!assert (interp1 (xp,yp,xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp,style), yp, 100*eps)
+%!assert (isempty (interp1 (xp',yp',[],style)))
+%!assert (isempty (interp1 (xp,yp,[],style)))
+%!assert (interp1 (xp,[yp',yp'],xi(:),style),...
+%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)])
+%!assert (interp1 (xp,yp,xi,style),...
+%!        interp1 (fliplr (xp),fliplr (yp),xi,style),100*eps)
+%!assert (ppval (interp1 (xp,yp,style,"pp"),xi),
+%!        interp1 (xp,yp,xi,style,"extrap"),10*eps)
+%!error interp1 (1,1,1, style)
+%!assert (interp1 (xp,[yp',yp'],xi,style),
+%!        interp1 (xp,[yp',yp'],xi,["*",style]),100*eps)
+%!test style = ["*",style];
+%!assert (interp1 (xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA])
+%!assert (interp1 (xp,yp,xp,style), yp, 100*eps)
+%!assert (interp1 (xp,yp,xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp,style), yp, 100*eps)
+%!assert (isempty (interp1 (xp',yp',[],style)))
+%!assert (isempty (interp1 (xp,yp,[],style)))
+%!assert (interp1 (xp,[yp',yp'],xi(:),style),...
+%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)])
+%!assert (interp1 (xp,yp,xi,style),...
+%!        interp1 (fliplr (xp),fliplr (yp),xi,style),100*eps)
+%!assert (ppval (interp1 (xp,yp,style,"pp"),xi),
+%!        interp1 (xp,yp,xi,style,"extrap"),10*eps)
+%!error interp1 (1,1,1, style)
 ## ENDBLOCK
-%!test style='linear';
+
+%!test style = "linear";
 ## BLOCK
-%!assert (interp1(xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA]);
-%!assert (interp1(xp,yp,xp,style), yp, 100*eps);
-%!assert (interp1(xp,yp,xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp,style), yp, 100*eps);
-%!assert (isempty(interp1(xp',yp',[],style)));
-%!assert (isempty(interp1(xp,yp,[],style)));
-%!assert (interp1(xp,[yp',yp'],xi(:),style),...
-%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)]);
-%!assert (interp1(xp,yp,xi,style),...
-%!        interp1(fliplr(xp),fliplr(yp),xi,style),100*eps);
-%!assert (ppval(interp1(xp,yp,style,"pp"),xi),
-%!        interp1(xp,yp,xi,style,"extrap"),10*eps);
-%!error interp1(1,1,1, style);
-%!assert (interp1(xp,[yp',yp'],xi,style),
-%!        interp1(xp,[yp',yp'],xi,["*",style]),100*eps);
-%!test style=['*',style];
-%!assert (interp1(xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA]);
-%!assert (interp1(xp,yp,xp,style), yp, 100*eps);
-%!assert (interp1(xp,yp,xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp,style), yp, 100*eps);
-%!assert (isempty(interp1(xp',yp',[],style)));
-%!assert (isempty(interp1(xp,yp,[],style)));
-%!assert (interp1(xp,[yp',yp'],xi(:),style),...
-%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)]);
-%!assert (interp1(xp,yp,xi,style),...
-%!        interp1(fliplr(xp),fliplr(yp),xi,style),100*eps);
-%!assert (ppval(interp1(xp,yp,style,"pp"),xi),
-%!        interp1(xp,yp,xi,style,"extrap"),10*eps);
-%!error interp1(1,1,1, style);
+%!assert (interp1 (xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA])
+%!assert (interp1 (xp,yp,xp,style), yp, 100*eps)
+%!assert (interp1 (xp,yp,xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp,style), yp, 100*eps)
+%!assert (isempty (interp1 (xp',yp',[],style)))
+%!assert (isempty (interp1 (xp,yp,[],style)))
+%!assert (interp1 (xp,[yp',yp'],xi(:),style),...
+%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)])
+%!assert (interp1 (xp,yp,xi,style),...
+%!        interp1 (fliplr (xp),fliplr (yp),xi,style),100*eps)
+%!assert (ppval (interp1 (xp,yp,style,"pp"),xi),
+%!        interp1 (xp,yp,xi,style,"extrap"),10*eps)
+%!error interp1 (1,1,1, style)
+%!assert (interp1 (xp,[yp',yp'],xi,style),
+%!        interp1 (xp,[yp',yp'],xi,["*",style]),100*eps)
+%!test style = ['*',style];
+%!assert (interp1 (xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA])
+%!assert (interp1 (xp,yp,xp,style), yp, 100*eps)
+%!assert (interp1 (xp,yp,xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp,style), yp, 100*eps)
+%!assert (isempty (interp1 (xp',yp',[],style)))
+%!assert (isempty (interp1 (xp,yp,[],style)))
+%!assert (interp1 (xp,[yp',yp'],xi(:),style),...
+%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)])
+%!assert (interp1 (xp,yp,xi,style),...
+%!        interp1 (fliplr (xp),fliplr (yp),xi,style),100*eps)
+%!assert (ppval (interp1 (xp,yp,style,"pp"),xi),
+%!        interp1 (xp,yp,xi,style,"extrap"),10*eps)
+%!assert (interp1 ([1 2 2 3], [1 2 3 4], 2), 3);
+%!assert (interp1 ([3 2 2 1], [4 3 2 1], 2), 2);
+%!error interp1 (1,1,1, style)
 ## ENDBLOCK
-%!test style='cubic';
+
+%!test style = "cubic";
 ## BLOCK
-%!assert (interp1(xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA]);
-%!assert (interp1(xp,yp,xp,style), yp, 100*eps);
-%!assert (interp1(xp,yp,xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp,style), yp, 100*eps);
-%!assert (isempty(interp1(xp',yp',[],style)));
-%!assert (isempty(interp1(xp,yp,[],style)));
-%!assert (interp1(xp,[yp',yp'],xi(:),style),...
-%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)]);
-%!assert (interp1(xp,yp,xi,style),...
-%!        interp1(fliplr(xp),fliplr(yp),xi,style),100*eps);
-%!assert (ppval(interp1(xp,yp,style,"pp"),xi),
-%!        interp1(xp,yp,xi,style,"extrap"),100*eps);
-%!error interp1(1,1,1, style);
-%!assert (interp1(xp,[yp',yp'],xi,style),
-%!        interp1(xp,[yp',yp'],xi,["*",style]),100*eps);
-%!test style=['*',style];
-%!assert (interp1(xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA]);
-%!assert (interp1(xp,yp,xp,style), yp, 100*eps);
-%!assert (interp1(xp,yp,xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp,style), yp, 100*eps);
-%!assert (isempty(interp1(xp',yp',[],style)));
-%!assert (isempty(interp1(xp,yp,[],style)));
-%!assert (interp1(xp,[yp',yp'],xi(:),style),...
-%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)]);
-%!assert (interp1(xp,yp,xi,style),...
-%!        interp1(fliplr(xp),fliplr(yp),xi,style),100*eps);
-%!assert (ppval(interp1(xp,yp,style,"pp"),xi),
-%!        interp1(xp,yp,xi,style,"extrap"),100*eps);
-%!error interp1(1,1,1, style);
+%!assert (interp1 (xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA])
+%!assert (interp1 (xp,yp,xp,style), yp, 100*eps)
+%!assert (interp1 (xp,yp,xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp,style), yp, 100*eps)
+%!assert (isempty (interp1 (xp',yp',[],style)))
+%!assert (isempty (interp1 (xp,yp,[],style)))
+%!assert (interp1 (xp,[yp',yp'],xi(:),style),...
+%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)])
+%!assert (interp1 (xp,yp,xi,style),...
+%!        interp1 (fliplr (xp),fliplr (yp),xi,style),100*eps)
+%!assert (ppval (interp1 (xp,yp,style,"pp"),xi),
+%!        interp1 (xp,yp,xi,style,"extrap"),100*eps)
+%!error interp1 (1,1,1, style)
+%!assert (interp1 (xp,[yp',yp'],xi,style),
+%!        interp1 (xp,[yp',yp'],xi,["*",style]),100*eps)
+%!test style = ["*",style];
+%!assert (interp1 (xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA])
+%!assert (interp1 (xp,yp,xp,style), yp, 100*eps)
+%!assert (interp1 (xp,yp,xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp,style), yp, 100*eps)
+%!assert (isempty (interp1 (xp',yp',[],style)))
+%!assert (isempty (interp1 (xp,yp,[],style)))
+%!assert (interp1 (xp,[yp',yp'],xi(:),style),...
+%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)])
+%!assert (interp1 (xp,yp,xi,style),...
+%!        interp1 (fliplr (xp),fliplr (yp),xi,style),100*eps)
+%!assert (ppval (interp1 (xp,yp,style,"pp"),xi),
+%!        interp1 (xp,yp,xi,style,"extrap"),100*eps)
+%!error interp1 (1,1,1, style)
 ## ENDBLOCK
-%!test style='pchip';
+
+%!test style = "pchip";
 ## BLOCK
-%!assert (interp1(xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA]);
-%!assert (interp1(xp,yp,xp,style), yp, 100*eps);
-%!assert (interp1(xp,yp,xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp,style), yp, 100*eps);
-%!assert (isempty(interp1(xp',yp',[],style)));
-%!assert (isempty(interp1(xp,yp,[],style)));
-%!assert (interp1(xp,[yp',yp'],xi(:),style),...
-%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)]);
-%!assert (interp1(xp,yp,xi,style),...
-%!        interp1(fliplr(xp),fliplr(yp),xi,style),100*eps);
-%!assert (ppval(interp1(xp,yp,style,"pp"),xi),
-%!        interp1(xp,yp,xi,style,"extrap"),10*eps);
-%!error interp1(1,1,1, style);
-%!assert (interp1(xp,[yp',yp'],xi,style),
-%!        interp1(xp,[yp',yp'],xi,["*",style]),100*eps);
-%!test style=['*',style];
-%!assert (interp1(xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA]);
-%!assert (interp1(xp,yp,xp,style), yp, 100*eps);
-%!assert (interp1(xp,yp,xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp,style), yp, 100*eps);
-%!assert (isempty(interp1(xp',yp',[],style)));
-%!assert (isempty(interp1(xp,yp,[],style)));
-%!assert (interp1(xp,[yp',yp'],xi(:),style),...
-%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)]);
-%!assert (interp1(xp,yp,xi,style),...
-%!        interp1(fliplr(xp),fliplr(yp),xi,style),100*eps);
-%!assert (ppval(interp1(xp,yp,style,"pp"),xi),
-%!        interp1(xp,yp,xi,style,"extrap"),10*eps);
-%!error interp1(1,1,1, style);
+%!assert (interp1 (xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA])
+%!assert (interp1 (xp,yp,xp,style), yp, 100*eps)
+%!assert (interp1 (xp,yp,xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp,style), yp, 100*eps)
+%!assert (isempty (interp1 (xp',yp',[],style)))
+%!assert (isempty (interp1 (xp,yp,[],style)))
+%!assert (interp1 (xp,[yp',yp'],xi(:),style),...
+%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)])
+%!assert (interp1 (xp,yp,xi,style),...
+%!        interp1 (fliplr (xp),fliplr (yp),xi,style),100*eps)
+%!assert (ppval (interp1 (xp,yp,style,"pp"),xi),
+%!        interp1 (xp,yp,xi,style,"extrap"),10*eps)
+%!error interp1 (1,1,1, style)
+%!assert (interp1 (xp,[yp',yp'],xi,style),
+%!        interp1 (xp,[yp',yp'],xi,["*",style]),100*eps)
+%!test style = ["*",style];
+%!assert (interp1 (xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA])
+%!assert (interp1 (xp,yp,xp,style), yp, 100*eps)
+%!assert (interp1 (xp,yp,xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp,style), yp, 100*eps)
+%!assert (isempty (interp1 (xp',yp',[],style)))
+%!assert (isempty (interp1 (xp,yp,[],style)))
+%!assert (interp1 (xp,[yp',yp'],xi(:),style),...
+%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)])
+%!assert (interp1 (xp,yp,xi,style),...
+%!        interp1 (fliplr (xp),fliplr (yp),xi,style),100*eps)
+%!assert (ppval (interp1 (xp,yp,style,"pp"),xi),
+%!        interp1 (xp,yp,xi,style,"extrap"),10*eps)
+%!error interp1 (1,1,1, style)
 ## ENDBLOCK
-%!test style='spline';
+
+%!test style = "spline";
 ## BLOCK
-%!assert (interp1(xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA]);
-%!assert (interp1(xp,yp,xp,style), yp, 100*eps);
-%!assert (interp1(xp,yp,xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp,style), yp, 100*eps);
-%!assert (isempty(interp1(xp',yp',[],style)));
-%!assert (isempty(interp1(xp,yp,[],style)));
-%!assert (interp1(xp,[yp',yp'],xi(:),style),...
-%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)]);
-%!assert (interp1(xp,yp,xi,style),...
-%!        interp1(fliplr(xp),fliplr(yp),xi,style),100*eps);
-%!assert (ppval(interp1(xp,yp,style,"pp"),xi),
-%!        interp1(xp,yp,xi,style,"extrap"),10*eps);
-%!error interp1(1,1,1, style);
-%!assert (interp1(xp,[yp',yp'],xi,style),
-%!        interp1(xp,[yp',yp'],xi,["*",style]),100*eps);
-%!test style=['*',style];
-%!assert (interp1(xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA]);
-%!assert (interp1(xp,yp,xp,style), yp, 100*eps);
-%!assert (interp1(xp,yp,xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp',style), yp', 100*eps);
-%!assert (interp1(xp',yp',xp,style), yp, 100*eps);
-%!assert (isempty(interp1(xp',yp',[],style)));
-%!assert (isempty(interp1(xp,yp,[],style)));
-%!assert (interp1(xp,[yp',yp'],xi(:),style),...
-%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)]);
-%!assert (interp1(xp,yp,xi,style),...
-%!        interp1(fliplr(xp),fliplr(yp),xi,style),100*eps);
-%!assert (ppval(interp1(xp,yp,style,"pp"),xi),
-%!        interp1(xp,yp,xi,style,"extrap"),10*eps);
-%!error interp1(1,1,1, style);
+%!assert (interp1 (xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA])
+%!assert (interp1 (xp,yp,xp,style), yp, 100*eps)
+%!assert (interp1 (xp,yp,xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp,style), yp, 100*eps)
+%!assert (isempty (interp1 (xp',yp',[],style)))
+%!assert (isempty (interp1 (xp,yp,[],style)))
+%!assert (interp1 (xp,[yp',yp'],xi(:),style),...
+%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)])
+%!assert (interp1 (xp,yp,xi,style),...
+%!        interp1 (fliplr (xp),fliplr (yp),xi,style),100*eps)
+%!assert (ppval (interp1 (xp,yp,style,"pp"),xi),
+%!        interp1 (xp,yp,xi,style,"extrap"),10*eps)
+%!error interp1 (1,1,1, style)
+%!assert (interp1 (xp,[yp',yp'],xi,style),
+%!        interp1 (xp,[yp',yp'],xi,["*",style]),100*eps)
+%!test style = ["*",style];
+%!assert (interp1 (xp, yp, [min(xp)-1, max(xp)+1],style), [NA, NA])
+%!assert (interp1 (xp,yp,xp,style), yp, 100*eps)
+%!assert (interp1 (xp,yp,xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp',style), yp', 100*eps)
+%!assert (interp1 (xp',yp',xp,style), yp, 100*eps)
+%!assert (isempty (interp1 (xp',yp',[],style)))
+%!assert (isempty (interp1 (xp,yp,[],style)))
+%!assert (interp1 (xp,[yp',yp'],xi(:),style),...
+%!        [interp1(xp,yp,xi(:),style),interp1(xp,yp,xi(:),style)])
+%!assert (interp1 (xp,yp,xi,style),...
+%!        interp1 (fliplr (xp),fliplr (yp),xi,style),100*eps)
+%!assert (ppval (interp1 (xp,yp,style,"pp"),xi),
+%!        interp1 (xp,yp,xi,style,"extrap"),10*eps)
+%!error interp1 (1,1,1, style)
 ## ENDBLOCK
 ## ENDBLOCKTEST
 
 %!# test linear extrapolation
-%!assert (interp1([1:5],[3:2:11],[0,6],"linear","extrap"), [1, 13], eps);
-%!assert (interp1(xp, yp, [-1, max(xp)+1],"linear",5), [5, 5]);
-
-%!error interp1
-%!error interp1(1:2,1:2,1,"bogus")
+%!assert (interp1 ([1:5],[3:2:11],[0,6],"linear","extrap"), [1, 13], eps)
+%!assert (interp1 (xp, yp, [-1, max(xp)+1],"linear",5), [5, 5])
 
-%!assert (interp1(1:2,1:2,1.4,"nearest"),1);
-%!error interp1(1,1,1, "linear");
-%!assert (interp1(1:2,1:2,1.4,"linear"),1.4);
-%!assert (interp1(1:4,1:4,1.4,"cubic"),1.4);
-%!assert (interp1(1:2,1:2,1.1, "spline"), 1.1);
-%!assert (interp1(1:3,1:3,1.4,"spline"),1.4);
+%!assert (interp1 (1:2,1:2,1.4,"nearest"), 1)
+%!assert (interp1 (1:2,1:2,1.4,"linear"), 1.4)
+%!assert (interp1 (1:4,1:4,1.4,"cubic"), 1.4)
+%!assert (interp1 (1:2,1:2,1.1, "spline"), 1.1)
+%!assert (interp1 (1:3,1:3,1.4,"spline"), 1.4)
 
-%!error interp1(1,1,1, "*nearest");
-%!assert (interp1(1:2:4,1:2:4,1.4,"*nearest"),1);
-%!error interp1(1,1,1, "*linear");
-%!assert (interp1(1:2:4,1:2:4,[0,1,1.4,3,4],"*linear"),[NA,1,1.4,3,NA]);
-%!assert (interp1(1:2:8,1:2:8,1.4,"*cubic"),1.4);
-%!assert (interp1(1:2,1:2,1.3, "*spline"), 1.3);
-%!assert (interp1(1:2:6,1:2:6,1.4,"*spline"),1.4);
+%!assert (interp1 (1:2:4,1:2:4,1.4,"*nearest"), 1)
+%!assert (interp1 (1:2:4,1:2:4,[0,1,1.4,3,4],"*linear"), [NA,1,1.4,3,NA])
+%!assert (interp1 (1:2:8,1:2:8,1.4,"*cubic"), 1.4)
+%!assert (interp1 (1:2,1:2,1.3, "*spline"), 1.3)
+%!assert (interp1 (1:2:6,1:2:6,1.4,"*spline"), 1.4)
 
-%!assert (interp1([3,2,1],[3,2,2],2.5),2.5)
+%!assert (interp1 ([3,2,1],[3,2,2],2.5), 2.5)
 
 %!assert (interp1 ([1,2,2,3,4],[0,1,4,2,1],[-1,1.5,2,2.5,3.5], "linear", "extrap"), [-2,0.5,4,3,1.5])
 %!assert (interp1 ([4,4,3,2,0],[0,1,4,2,1],[1.5,4,4.5], "linear"), [1.75,1,NA])
 %!assert (interp1 (0:4, 2.5), 1.5)
+
+%!error interp1 ()
+%!error interp1 (1,1,1, "linear")
+%!error interp1 (1,1,1, "*nearest")
+%!error interp1 (1,1,1, "*linear")
+%!error interp1 (1:2,1:2,1, "bogus")
+
--- a/scripts/general/interp1q.m
+++ b/scripts/general/interp1q.m
@@ -37,7 +37,7 @@
 
 function yi = interp1q (x, y, xi)
   x = x(:);
-  nx = size (x, 1);
+  nx = rows (x);
   szy = size (y);
   y = y(:,:);
   [ny, nc] = size (y);
@@ -57,14 +57,16 @@
   endif
 endfunction
 
+
 %!shared xp, yp, xi, yi
-%! xp=[0:2:10].';      yp = sin(2*pi*xp/5);
+%! xp = [0:2:10].';   yp = sin (2*pi*xp/5);
 %! xi = [-1; 0; 2.2; 4; 6.6; 10; 11];
 %! yi = interp1 (xp,yp,xi);
-%!assert (interp1q(xp, yp, [min(xp)-1; max(xp)+1]), [NA; NA]);
-%!assert (interp1q(xp,yp,xp), yp, 100*eps);
-%!assert (isempty(interp1q(xp,yp,[])));
-%!assert (interp1q(xp,yp,xi), yi);
-%!assert (interp1q(xp,[yp,yp],xi), [yi, yi]);
-%!assert (interp1q(xp,yp,[xi,xi]), [yi, yi]);
-%!assert (interp1q(xp,[yp,yp],[xi,xi]), cat (3, [yi, yi], [yi, yi]));
+%!assert (interp1q (xp,yp, [min(xp)-1; max(xp)+1]), [NA; NA]);
+%!assert (interp1q (xp,yp,xp), yp, 100*eps);
+%!assert (isempty (interp1q (xp,yp,[])));
+%!assert (interp1q (xp,yp,xi), yi);
+%!assert (interp1q (xp,[yp,yp],xi), [yi, yi]);
+%!assert (interp1q (xp,yp,[xi,xi]), [yi, yi]);
+%!assert (interp1q (xp,[yp,yp],[xi,xi]), cat (3, [yi, yi], [yi, yi]));
+
--- a/scripts/general/interp2.m
+++ b/scripts/general/interp2.m
@@ -36,8 +36,8 @@
 ## matrices @var{xi}, @var{yi}.
 ##
 ## If the last argument is a string, the interpolation method can
-## be specified.  The method can be 'linear', 'nearest' or 'cubic'.
-## If it is omitted 'linear' interpolation is assumed.
+## be specified.  The method can be "linear", "nearest" or "cubic".
+## If it is omitted "linear" interpolation is assumed.
 ##
 ## @item interp2 (@var{z}, @var{xi}, @var{yi})
 ## Assumes @code{@var{x} = 1:rows (@var{z})} and @code{@var{y} =
@@ -52,19 +52,19 @@
 ## interpolation.  It can take one of the following values
 ##
 ## @table @asis
-## @item 'nearest'
+## @item "nearest"
 ## Return the nearest neighbor.
 ##
-## @item 'linear'
+## @item "linear"
 ## Linear interpolation from nearest neighbors.
 ##
-## @item 'pchip'
+## @item "pchip"
 ## Piecewise cubic Hermite interpolating polynomial.
 ##
-## @item 'cubic'
+## @item "cubic"
 ## Cubic interpolation from four nearest neighbors.
 ##
-## @item 'spline'
+## @item "spline"
 ## Cubic spline interpolation---smooth first and second derivatives
 ## throughout the curve.
 ## @end table
@@ -377,7 +377,7 @@
         AX_2 = bc ((XI - K - 2));
 
         ## Perform interpolation
-        sz = size(Z);
+        sz = size (Z);
         ZI = AY_2 .* AX_2 .* Z (sym_sub2ind (sz, L+2, K+2)) ...
            + AY_2 .* AX_1 .* Z (sym_sub2ind (sz, L+2, K+1)) ...
            + AY_2 .* AX0  .* Z (sym_sub2ind (sz, L+2, K))   ...
@@ -420,9 +420,9 @@
 endfunction
 
 ## Compute the bicubic interpolation coefficients
-function o = bc(x)
-  x = abs(x);
-  o = zeros(size(x));
+function o = bc (x)
+  x = abs (x);
+  o = zeros (size (x));
   idx1 = (x < 1);
   idx2 = !idx1 & (x < 2);
   o(idx1) = 1 - 2.*x(idx1).^2 + x(idx1).^3;
@@ -430,7 +430,7 @@
 endfunction
 
 ## This version of sub2ind behaves as if the data was symmetrically padded
-function ind = sym_sub2ind(sz, Y, X)
+function ind = sym_sub2ind (sz, Y, X)
   Y (Y < 1) = 1 - Y (Y < 1);
   while (any (Y (:) > 2 * sz (1)))
     Y (Y > 2 * sz (1)) = round (Y (Y > 2 * sz (1)) / 2);
@@ -441,170 +441,191 @@
     X (X > 2 * sz (2)) = round (X (X > 2 * sz (2)) / 2);
   endwhile
   X (X > sz (2)) = 1 + 2 * sz (2) - X (X > sz (2));
-  ind = sub2ind(sz, Y, X);
+  ind = sub2ind (sz, Y, X);
 endfunction
 
 
 %!demo
-%! A=[13,-1,12;5,4,3;1,6,2];
-%! x=[0,1,4]; y=[10,11,12];
-%! xi=linspace(min(x),max(x),17);
-%! yi=linspace(min(y),max(y),26)';
-%! mesh(xi,yi,interp2(x,y,A,xi,yi,'linear'));
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
+%! clf;
+%! colormap ("default");
+%! A = [13,-1,12;5,4,3;1,6,2];
+%! x = [0,1,4];  y = [10,11,12];
+%! xi = linspace (min (x), max (x), 17);
+%! yi = linspace (min (y), max (y), 26)';
+%! mesh (xi,yi,interp2 (x,y,A,xi,yi, "linear"));
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
 
 %!demo
-%! [x,y,A] = peaks(10);
-%! x = x(1,:)'; y = y(:,1);
-%! xi=linspace(min(x),max(x),41);
-%! yi=linspace(min(y),max(y),41)';
-%! mesh(xi,yi,interp2(x,y,A,xi,yi,'linear'));
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
+%! clf;
+%! colormap ("default");
+%! [x,y,A] = peaks (10);
+%! x = x(1,:)';  y = y(:,1);
+%! xi = linspace (min (x), max (x), 41);
+%! yi = linspace (min (y), max (y), 41)';
+%! mesh (xi,yi,interp2 (x,y,A,xi,yi, "linear"));
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
 
 %!demo
-%! A=[13,-1,12;5,4,3;1,6,2];
-%! x=[0,1,4]; y=[10,11,12];
-%! xi=linspace(min(x),max(x),17);
-%! yi=linspace(min(y),max(y),26)';
-%! mesh(xi,yi,interp2(x,y,A,xi,yi,'nearest'));
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
+%! clf;
+%! colormap ("default");
+%! A = [13,-1,12;5,4,3;1,6,2];
+%! x = [0,1,4];  y = [10,11,12];
+%! xi = linspace (min (x), max (x), 17);
+%! yi = linspace (min (y), max (y), 26)';
+%! mesh (xi,yi,interp2 (x,y,A,xi,yi, "nearest"));
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
 
 %!demo
-%! [x,y,A] = peaks(10);
-%! x = x(1,:)'; y = y(:,1);
-%! xi=linspace(min(x),max(x),41);
-%! yi=linspace(min(y),max(y),41)';
-%! mesh(xi,yi,interp2(x,y,A,xi,yi,'nearest'));
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
+%! clf;
+%! colormap ("default");
+%! [x,y,A] = peaks (10);
+%! x = x(1,:)';  y = y(:,1);
+%! xi = linspace (min (x), max (x), 41);
+%! yi = linspace (min (y), max (y), 41)';
+%! mesh (xi,yi,interp2 (x,y,A,xi,yi, "nearest"));
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
 
 %!demo
-%! A=[13,-1,12;5,4,3;1,6,2];
-%! x=[0,1,2]; y=[10,11,12];
-%! xi=linspace(min(x),max(x),17);
-%! yi=linspace(min(y),max(y),26)';
-%! mesh(xi,yi,interp2(x,y,A,xi,yi,'pchip'));
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
+%! clf;
+%! colormap ("default");
+%! A = [13,-1,12;5,4,3;1,6,2];
+%! x = [0,1,2];  y = [10,11,12];
+%! xi = linspace (min (x), max (x), 17);
+%! yi = linspace (min (y), max (y), 26)';
+%! mesh (xi,yi,interp2 (x,y,A,xi,yi, "pchip"));
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
 
 %!demo
-%! [x,y,A] = peaks(10);
-%! x = x(1,:)'; y = y(:,1);
-%! xi=linspace(min(x),max(x),41);
-%! yi=linspace(min(y),max(y),41)';
-%! mesh(xi,yi,interp2(x,y,A,xi,yi,'pchip'));
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
+%! clf;
+%! colormap ("default");
+%! [x,y,A] = peaks (10);
+%! x = x(1,:)';  y = y(:,1);
+%! xi = linspace (min (x), max (x), 41);
+%! yi = linspace (min (y), max (y), 41)';
+%! mesh (xi,yi,interp2 (x,y,A,xi,yi, "pchip"));
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
 
 %!demo
-%! A=[13,-1,12;5,4,3;1,6,2];
-%! x=[0,1,2]; y=[10,11,12];
-%! xi=linspace(min(x),max(x),17);
-%! yi=linspace(min(y),max(y),26)';
-%! mesh(xi,yi,interp2(x,y,A,xi,yi,'cubic'));
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
+%! clf;
+%! colormap ("default");
+%! A = [13,-1,12;5,4,3;1,6,2];
+%! x = [0,1,2];  y = [10,11,12];
+%! xi = linspace (min (x), max (x), 17);
+%! yi = linspace (min (y), max (y), 26)';
+%! mesh (xi,yi,interp2 (x,y,A,xi,yi, "cubic"));
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
 
 %!demo
-%! [x,y,A] = peaks(10);
-%! x = x(1,:)'; y = y(:,1);
-%! xi=linspace(min(x),max(x),41);
-%! yi=linspace(min(y),max(y),41)';
-%! mesh(xi,yi,interp2(x,y,A,xi,yi,'cubic'));
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
+%! clf;
+%! colormap ("default");
+%! [x,y,A] = peaks (10);
+%! x = x(1,:)';  y = y(:,1);
+%! xi = linspace (min (x), max (x), 41);
+%! yi = linspace (min (y), max (y), 41)';
+%! mesh (xi,yi,interp2 (x,y,A,xi,yi, "cubic"));
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
 
 %!demo
-%! A=[13,-1,12;5,4,3;1,6,2];
-%! x=[0,1,2]; y=[10,11,12];
-%! xi=linspace(min(x),max(x),17);
-%! yi=linspace(min(y),max(y),26)';
-%! mesh(xi,yi,interp2(x,y,A,xi,yi,'spline'));
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
+%! clf;
+%! colormap ("default");
+%! A = [13,-1,12;5,4,3;1,6,2];
+%! x = [0,1,2];  y = [10,11,12];
+%! xi = linspace (min (x), max (x), 17);
+%! yi = linspace (min (y), max (y), 26)';
+%! mesh (xi,yi,interp2 (x,y,A,xi,yi, "spline"));
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
 
 %!demo
-%! [x,y,A] = peaks(10);
-%! x = x(1,:)'; y = y(:,1);
-%! xi=linspace(min(x),max(x),41);
-%! yi=linspace(min(y),max(y),41)';
-%! mesh(xi,yi,interp2(x,y,A,xi,yi,'spline'));
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
+%! clf;
+%! colormap ("default");
+%! [x,y,A] = peaks (10);
+%! x = x(1,:)';  y = y(:,1);
+%! xi = linspace (min (x), max (x), 41);
+%! yi = linspace (min (y), max (y), 41)';
+%! mesh (xi,yi,interp2 (x,y,A,xi,yi, "spline"));
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
 
 %!test % simple test
-%!  x = [1,2,3];
-%!  y = [4,5,6,7];
-%!  [X, Y] = meshgrid(x,y);
-%!  Orig = X.^2 + Y.^3;
-%!  xi = [1.2,2, 1.5];
-%!  yi = [6.2, 4.0, 5.0]';
+%! x = [1,2,3];
+%! y = [4,5,6,7];
+%! [X, Y] = meshgrid (x, y);
+%! Orig = X.^2 + Y.^3;
+%! xi = [1.2,2, 1.5];
+%! yi = [6.2, 4.0, 5.0]';
 %!
-%!  Expected = ...
-%!    [243,   245.4,  243.9;
-%!      65.6,  68,     66.5;
-%!     126.6, 129,    127.5];
-%!  Result = interp2(x,y,Orig, xi, yi);
+%! Expected = ...
+%!   [243,   245.4,  243.9;
+%!     65.6,  68,     66.5;
+%!    126.6, 129,    127.5];
+%! Result = interp2 (x,y,Orig, xi, yi);
 %!
-%!  assert(Result, Expected, 1000*eps);
+%! assert (Result, Expected, 1000*eps);
 
 %!test % 2^n form
-%!  x = [1,2,3];
-%!  y = [4,5,6,7];
-%!  [X, Y] = meshgrid(x,y);
-%!  Orig = X.^2 + Y.^3;
-%!  xi = [1:0.25:3]; yi = [4:0.25:7]';
-%!  Expected = interp2(x,y,Orig, xi, yi);
-%!  Result = interp2(Orig,2);
+%! x = [1,2,3];
+%! y = [4,5,6,7];
+%! [X, Y] = meshgrid (x, y);
+%! Orig = X.^2 + Y.^3;
+%! xi = [1:0.25:3];  yi = [4:0.25:7]';
+%! Expected = interp2 (x,y,Orig, xi, yi);
+%! Result = interp2 (Orig, 2);
 %!
-%!  assert(Result, Expected, 10*eps);
+%! assert (Result, Expected, 10*eps);
 
 %!test % matrix slice
-%!  A = eye(4);
-%!  assert(interp2(A,[1:4],[1:4]),[1,1,1,1]);
+%! A = eye (4);
+%! assert (interp2 (A,[1:4],[1:4]), [1,1,1,1]);
 
 %!test % non-gridded XI,YI
-%!  A = eye(4);
-%!  assert(interp2(A,[1,2;3,4],[1,3;2,4]),[1,0;0,1]);
+%! A = eye (4);
+%! assert (interp2 (A,[1,2;3,4],[1,3;2,4]), [1,0;0,1]);
 
 %!test % for values outside of boundaries
-%!  x = [1,2,3];
-%!  y = [4,5,6,7];
-%!  [X, Y] = meshgrid(x,y);
-%!  Orig = X.^2 + Y.^3;
-%!  xi = [0,4];
-%!  yi = [3,8]';
-%!  assert(interp2(x,y,Orig, xi, yi),[NA,NA;NA,NA]);
-%!  assert(interp2(x,y,Orig, xi, yi,'linear', 0),[0,0;0,0]);
+%! x = [1,2,3];
+%! y = [4,5,6,7];
+%! [X, Y] = meshgrid (x,y);
+%! Orig = X.^2 + Y.^3;
+%! xi = [0,4];
+%! yi = [3,8]';
+%! assert (interp2 (x,y,Orig, xi, yi), [NA,NA;NA,NA]);
+%! assert (interp2 (x,y,Orig, xi, yi,"linear", 0), [0,0;0,0]);
 
 %!test % for values at boundaries
-%!  A=[1,2;3,4];
-%!  x=[0,1];
-%!  y=[2,3]';
-%!  assert(interp2(x,y,A,x,y,'linear'), A);
-%!  assert(interp2(x,y,A,x,y,'nearest'), A);
+%! A=[1,2;3,4];
+%! x=[0,1];
+%! y=[2,3]';
+%! assert (interp2 (x,y,A,x,y,"linear"), A);
+%! assert (interp2 (x,y,A,x,y,"nearest"), A);
 
 %!test % for Matlab-compatible rounding for 'nearest'
 %! X = meshgrid (1:4);
-%! assert (interp2 (X, 2.5, 2.5, 'nearest'), 3);
+%! assert (interp2 (X, 2.5, 2.5, "nearest"), 3);
 
 %!shared z, zout, tol
-%!  z = [1 3 5; 3 5 7; 5 7 9];
-%!  zout = [1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8; 5 6 7 8 9];
-%!  tol = 2 * eps;
-%!assert (interp2 (z), zout, tol);
-%!assert (interp2 (z, "linear"), zout, tol);
-%!assert (interp2 (z, "pchip"), zout, tol);
-%!assert (interp2 (z, "cubic"), zout, 10 * tol);
-%!assert (interp2 (z, "spline"), zout, tol);
+%! z = [1 3 5; 3 5 7; 5 7 9];
+%! zout = [1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8; 5 6 7 8 9];
+%! tol = 2 * eps;
+%!assert (interp2 (z), zout, tol)
+%!assert (interp2 (z, "linear"), zout, tol)
+%!assert (interp2 (z, "pchip"), zout, tol)
+%!assert (interp2 (z, "cubic"), zout, 10 * tol)
+%!assert (interp2 (z, "spline"), zout, tol)
 %!assert (interp2 (z, [2 3 1], [2 2 2]', "linear"), repmat ([5, 7, 3], [3, 1]), tol) 
 %!assert (interp2 (z, [2 3 1], [2 2 2]', "pchip"), repmat ([5, 7, 3], [3, 1]), tol) 
 %!assert (interp2 (z, [2 3 1], [2 2 2]', "cubic"), repmat ([5, 7, 3], [3, 1]), 10 * tol) 
 %!assert (interp2 (z, [2 3 1], [2 2 2]', "spline"), repmat ([5, 7, 3], [3, 1]), tol) 
-%!assert (interp2 (z, [2 3 1], [2 2 2], "linear"), [5 7 3], tol);
-%!assert (interp2 (z, [2 3 1], [2 2 2], "pchip"), [5 7 3], tol);
-%!assert (interp2 (z, [2 3 1], [2 2 2], "cubic"), [5 7 3], 10 * tol);
-%!assert (interp2 (z, [2 3 1], [2 2 2], "spline"), [5 7 3], tol);
+%!assert (interp2 (z, [2 3 1], [2 2 2], "linear"), [5 7 3], tol)
+%!assert (interp2 (z, [2 3 1], [2 2 2], "pchip"), [5 7 3], tol)
+%!assert (interp2 (z, [2 3 1], [2 2 2], "cubic"), [5 7 3], 10 * tol)
+%!assert (interp2 (z, [2 3 1], [2 2 2], "spline"), [5 7 3], tol)
+
--- a/scripts/general/interp3.m
+++ b/scripts/general/interp3.m
@@ -28,7 +28,7 @@
 ## array @var{v} represents a value at a location given by the parameters
 ## @var{x}, @var{y}, and @var{z}.  The parameters @var{x}, @var{x}, and
 ## @var{z} are either 3-dimensional arrays of the same size as the array
-## @var{v} in the 'meshgrid' format or vectors.  The parameters @var{xi}, etc.
+## @var{v} in the "meshgrid" format or vectors.  The parameters @var{xi}, etc.
 ## respect a similar format to @var{x}, etc., and they represent the points
 ## at which the array @var{vi} is interpolated.
 ##
@@ -42,23 +42,23 @@
 ## Method is one of:
 ##
 ## @table @asis
-## @item 'nearest'
+## @item "nearest"
 ## Return the nearest neighbor.
 ##
-## @item 'linear'
+## @item "linear"
 ## Linear interpolation from nearest neighbors.
 ##
-## @item 'cubic'
+## @item "cubic"
 ## Cubic interpolation from four nearest neighbors (not implemented yet).
 ##
-## @item 'spline'
+## @item "spline"
 ## Cubic spline interpolation---smooth first and second derivatives
 ## throughout the curve.
 ## @end table
 ##
-## The default method is 'linear'.
+## The default method is "linear".
 ##
-## If @var{extrap} is the string 'extrap', then extrapolate values beyond
+## If @var{extrap} is the string "extrap", then extrapolate values beyond
 ## the endpoints.  If @var{extrap} is a number, replace values beyond the
 ## endpoints with that number.  If @var{extrap} is missing, assume NA.
 ## @seealso{interp1, interp2, spline, meshgrid}
@@ -91,7 +91,7 @@
     if (ndims (v) != 3)
       error ("interp3: expect 3-dimensional array of values");
     endif
-    x = varargin (2:end);
+    x = varargin (2:nargs);
     if (any (! cellfun (@isvector, x)))
       for i = 2 : 3
         if (! size_equal (x{1}, x{i}))
@@ -135,16 +135,50 @@
   endif
 endfunction
 
+
 %!test
-%! x = y = z = -1:1;
+%! x = y = z = -1:1; y = y + 2;
 %! f = @(x,y,z) x.^2 - y - z.^2;
 %! [xx, yy, zz] = meshgrid (x, y, z);
 %! v = f (xx,yy,zz);
-%! xi = yi = zi = -1:0.5:1;
+%! xi = yi = zi = -1:0.5:1; yi = yi + 2.1;
 %! [xxi, yyi, zzi] = meshgrid (xi, yi, zi);
-%! vi = interp3(x, y, z, v, xxi, yyi, zzi);
-%! [xxi, yyi, zzi] = ndgrid (xi, yi, zi);
-%! vi2 = interpn(x, y, z, v, xxi, yyi, zzi);
+%! vi = interp3 (x, y, z, v, xxi, yyi, zzi);
+%! [xxi, yyi, zzi] = ndgrid (yi, xi, zi);
+%! vi2 = interpn (y, x, z, v, xxi, yyi, zzi);
+%! tol = 10 * eps;
+%! assert (vi, vi2, tol);
+
+%!test
+%! x=z=1:2; y=1:3;xi=zi=.6:1.6; yi=1; v=ones([3,2,2]);  v(:,2,1)=[7 ;5;4];  v(:,1,2)=[2 ;3;5];
+%! [xxi3, yyi3, zzi3] = meshgrid (xi, yi, zi);
+%! [xxi, yyi, zzi] = ndgrid (yi, xi, zi);
+%! vi = interp3 (x, y, z, v, xxi3, yyi3, zzi3, "nearest");
+%! vi2 = interpn (y, x, z, v, xxi, yyi, zzi,"nearest");
+%! assert (vi, vi2);
+
+%!test
+%! x=z=1:2; y=1:3;xi=zi=.6:1.6; yi=1; v=ones([3,2,2]);  v(:,2,1)=[7 ;5;4];  v(:,1,2)=[2 ;3;5];
+%! vi = interp3 (x, y, z, v, xi+1, yi, zi, "nearest",3);
+%! vi2 = interpn (y, x, z, v, yi, xi+1, zi,"nearest", 3);
+%! assert (vi, vi2);
+
+%!test
+%! x=z=1:2; y=1:3;xi=zi=.6:1.6; yi=1; v=ones([3,2,2]);  v(:,2,1)=[7 ;5;4];  v(:,1,2)=[2 ;3;5];
+%! vi = interp3 (x, y, z, v, xi, yi, zi, "nearest");
+%! vi2 = interpn (y, x, z, v, yi, xi, zi,"nearest");
+%! assert (vi, vi2);
+
+%!test
+%! x=z=1:2; y=1:3;xi=zi=.6:1.6; yi=1; v=ones([3,2,2]);  v(:,2,1)=[7 ;5;4];  v(:,1,2)=[2 ;3;5];
+%! vi = interp3 (v, xi, yi, zi, "nearest",3);
+%! vi2 = interpn (v, yi, xi, zi,"nearest", 3);
+%! assert (vi, vi2);
+
+%!test
+%! xi=zi=.6:1.6; yi=1; v=ones([3,2,2]);  v(:,2,1)=[7 ;5;4];  v(:,1,2)=[2 ;3;5];
+%! vi = interp3 (v, xi, yi, zi, "nearest");
+%! vi2 = interpn (v, yi, xi, zi,"nearest");
 %! assert (vi, vi2);
 
 %!shared z, zout, tol
@@ -164,3 +198,4 @@
 %!assert (interp3 (z), zout, tol)
 %!assert (interp3 (z, "linear"), zout, tol)
 %!assert (interp3 (z, "spline"), zout, tol)
+
--- a/scripts/general/interpft.m
+++ b/scripts/general/interpft.m
@@ -92,25 +92,28 @@
 
 
 %!demo
-%! t = 0 : 0.3 : pi; dt = t(2)-t(1);
-%! n = length (t); k = 100;
+%! clf;
+%! t = 0 : 0.3 : pi;  dt = t(2)-t(1);
+%! n = length (t);  k = 100;
 %! ti = t(1) + [0 : k-1]*dt*n/k;
 %! y = sin (4*t + 0.3) .* cos (3*t - 0.1);
 %! yp = sin (4*ti + 0.3) .* cos (3*ti - 0.1);
-%! plot (ti, yp, 'g', ti, interp1(t, y, ti, 'spline'), 'b', ...
-%!       ti, interpft (y, k), 'c', t, y, 'r+');
-%! legend ('sin(4t+0.3)cos(3t-0.1','spline','interpft','data');
+%! plot (ti, yp, 'g', ti, interp1(t, y, ti, "spline"), 'b', ...
+%!       ti, interpft (y, k), 'c', t, y, "r+");
+%! legend ("sin(4t+0.3)cos(3t-0.1)", "spline", "interpft", "data");
 
 %!shared n,y
-%! x = [0:10]'; y = sin(x); n = length (x);
-%!assert (interpft(y, n), y, 20*eps);
-%!assert (interpft(y', n), y', 20*eps);
-%!assert (interpft([y,y],n), [y,y], 20*eps);
+%! x = [0:10]';  y = sin(x);  n = length (x);
+%!assert (interpft (y, n), y, 20*eps);
+%!assert (interpft (y', n), y', 20*eps);
+%!assert (interpft ([y,y],n), [y,y], 20*eps);
 
 %% Test input validation
 %!error interpft ()
 %!error interpft (1)
 %!error interpft (1,2,3)
-%!error (interpft(1,[n,n]))
-%!error (interpft(1,2,0))
-%!error (interpft(1,2,3))
+%!error <N must be a scalar integer> interpft (1,[2,2])
+%!error <N must be a scalar integer> interpft (1,2.1)
+%!error <invalid dimension DIM> interpft (1,2,0)
+%!error <invalid dimension DIM> interpft (1,2,3)
+
--- a/scripts/general/interpn.m
+++ b/scripts/general/interpn.m
@@ -29,7 +29,7 @@
 ## at a location given by the parameters @var{x1}, @var{x2}, @dots{}, @var{xn}.
 ## The parameters @var{x1}, @var{x2}, @dots{}, @var{xn} are either
 ## @var{n}-dimensional arrays of the same size as the array @var{v} in
-## the 'ndgrid' format or vectors.  The parameters @var{y1}, etc. respect a
+## the "ndgrid" format or vectors.  The parameters @var{y1}, etc. respect a
 ## similar format to @var{x1}, etc., and they represent the points at which
 ## the array @var{vi} is interpolated.
 ##
@@ -42,21 +42,21 @@
 ## Method is one of:
 ##
 ## @table @asis
-## @item 'nearest'
+## @item "nearest"
 ## Return the nearest neighbor.
 ##
-## @item 'linear'
+## @item "linear"
 ## Linear interpolation from nearest neighbors.
 ##
-## @item 'cubic'
+## @item "cubic"
 ## Cubic interpolation from four nearest neighbors (not implemented yet).
 ##
-## @item 'spline'
+## @item "spline"
 ## Cubic spline interpolation---smooth first and second derivatives
 ## throughout the curve.
 ## @end table
 ##
-## The default method is 'linear'.
+## The default method is "linear".
 ##
 ## If @var{extrapval} is the scalar value, use it to replace the values
 ## beyond the endpoints with that number.  If @var{extrapval} is missing,
@@ -198,8 +198,8 @@
         q(:) = i;
         idx {i} = q;
       endfor
-      vi = vi (cellfun (@(x) sub2ind (size(vi), x{:}), idx));
-      vi = reshape (vi, size(y{1}));
+      vi = vi (cellfun (@(x) sub2ind (size (vi), x{:}), idx));
+      vi = reshape (vi, size (y{1}));
     endif
   elseif (strcmp (method, "cubic"))
     error ("interpn: cubic interpolation not yet implemented");
@@ -209,93 +209,98 @@
 
 endfunction
 
+
 %!demo
-%! A=[13,-1,12;5,4,3;1,6,2];
-%! x=[0,1,4]; y=[10,11,12];
-%! xi=linspace(min(x),max(x),17);
-%! yi=linspace(min(y),max(y),26)';
-%! mesh(xi,yi,interpn(x,y,A.',xi,yi,"linear").');
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
+%! clf;
+%! colormap ("default");
+%! A = [13,-1,12;5,4,3;1,6,2];
+%! x = [0,1,4];  y = [10,11,12];
+%! xi = linspace (min (x), max (x), 17);
+%! yi = linspace (min (y), max (y), 26)';
+%! mesh (xi, yi, interpn (x,y,A.',xi,yi, "linear").');
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
 
 %!demo
-%! A=[13,-1,12;5,4,3;1,6,2];
-%! x=[0,1,4]; y=[10,11,12];
-%! xi=linspace(min(x),max(x),17);
-%! yi=linspace(min(y),max(y),26)';
-%! mesh(xi,yi,interpn(x,y,A.',xi,yi,"nearest").');
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
+%! clf;
+%! colormap ("default");
+%! A = [13,-1,12;5,4,3;1,6,2];
+%! x = [0,1,4];  y = [10,11,12];
+%! xi = linspace (min (x), max (x), 17);
+%! yi = linspace (min (y), max (y), 26)';
+%! mesh (xi, yi, interpn (x,y,A.',xi,yi, "nearest").');
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
 
-%!#demo
-%! A=[13,-1,12;5,4,3;1,6,2];
-%! x=[0,1,2]; y=[10,11,12];
-%! xi=linspace(min(x),max(x),17);
-%! yi=linspace(min(y),max(y),26)';
-%! mesh(xi,yi,interpn(x,y,A.',xi,yi,"cubic").');
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
+%!#demo  # FIXME: Uncomment when support for "cubic" has been added
+%! clf;
+%! colormap ("default");
+%! A = [13,-1,12;5,4,3;1,6,2];
+%! x = [0,1,2];  y = [10,11,12];
+%! xi = linspace (min (x), max (x), 17);
+%! yi = linspace (min (y), max (y), 26)';
+%! mesh (xi, yi, interpn (x,y,A.',xi,yi, "cubic").');
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
 
 %!demo
-%! A=[13,-1,12;5,4,3;1,6,2];
-%! x=[0,1,2]; y=[10,11,12];
-%! xi=linspace(min(x),max(x),17);
-%! yi=linspace(min(y),max(y),26)';
-%! mesh(xi,yi,interpn(x,y,A.',xi,yi,"spline").');
-%! [x,y] = meshgrid(x,y);
-%! hold on; plot3(x(:),y(:),A(:),"b*"); hold off;
-
+%! clf;
+%! colormap ("default");
+%! A = [13,-1,12;5,4,3;1,6,2];
+%! x = [0,1,2];  y = [10,11,12];
+%! xi = linspace (min (x), max (x), 17);
+%! yi = linspace (min (y), max (y), 26)';
+%! mesh (xi, yi, interpn (x,y,A.',xi,yi, "spline").');
+%! [x,y] = meshgrid (x,y);
+%! hold on; plot3 (x(:),y(:),A(:),"b*"); hold off;
 
 %!demo
+%! clf;
+%! colormap ("default");
 %! x = y = z = -1:1;
 %! f = @(x,y,z) x.^2 - y - z.^2;
 %! [xx, yy, zz] = meshgrid (x, y, z);
 %! v = f (xx,yy,zz);
 %! xi = yi = zi = -1:0.1:1;
 %! [xxi, yyi, zzi] = ndgrid (xi, yi, zi);
-%! vi = interpn(x, y, z, v, xxi, yyi, zzi, 'spline');
+%! vi = interpn (x, y, z, v, xxi, yyi, zzi, "spline");
 %! mesh (yi, zi, squeeze (vi(1,:,:)));
 
-
 %!test
-%! [x,y,z] = ndgrid(0:2);
-%! f = x+y+z;
-%! assert (interpn(x,y,z,f,[.5 1.5],[.5 1.5],[.5 1.5]), [1.5, 4.5])
-%! assert (interpn(x,y,z,f,[.51 1.51],[.51 1.51],[.51 1.51],'nearest'), [3, 6])
-%! assert (interpn(x,y,z,f,[.5 1.5],[.5 1.5],[.5 1.5],'spline'), [1.5, 4.5])
-%! assert (interpn(x,y,z,f,x,y,z), f)
-%! assert (interpn(x,y,z,f,x,y,z,'nearest'), f)
-%! assert (interpn(x,y,z,f,x,y,z,'spline'), f)
+%! [x,y,z] = ndgrid (0:2);
+%! f = x + y + z;
+%! assert (interpn (x,y,z,f,[.5 1.5],[.5 1.5],[.5 1.5]), [1.5, 4.5]);
+%! assert (interpn (x,y,z,f,[.51 1.51],[.51 1.51],[.51 1.51],"nearest"), [3, 6]);
+%! assert (interpn (x,y,z,f,[.5 1.5],[.5 1.5],[.5 1.5],"spline"), [1.5, 4.5]);
+%! assert (interpn (x,y,z,f,x,y,z), f);
+%! assert (interpn (x,y,z,f,x,y,z,"nearest"), f);
+%! assert (interpn (x,y,z,f,x,y,z,"spline"), f);
 
 %!test
 %! [x, y, z] = ndgrid (0:2, 1:4, 2:6);
 %! f = x + y + z;
-%! xi = [0.5 1.0 1.5];
-%! yi = [1.5 2.0 2.5 3.5];
-%! zi = [2.5 3.5 4.0 5.0 5.5];
+%! xi = [0.5 1.0 1.5];  yi = [1.5 2.0 2.5 3.5];  zi = [2.5 3.5 4.0 5.0 5.5];
 %! fi = interpn (x, y, z, f, xi, yi, zi);
 %! [xi, yi, zi] = ndgrid (xi, yi, zi);
-%! assert (fi, xi + yi + zi)
+%! assert (fi, xi + yi + zi);
 
 %!test
-%! xi = 0:2;
-%! yi = 1:4;
-%! zi = 2:6;
+%! xi = 0:2;  yi = 1:4;  zi = 2:6;
 %! [x, y, z] = ndgrid (xi, yi, zi);
 %! f = x + y + z;
 %! fi = interpn (x, y, z, f, xi, yi, zi, "nearest");
-%! assert (fi, x + y + z)
+%! assert (fi, x + y + z);
 
 %!test
-%! [x,y,z] = ndgrid(0:2);
-%! f = x.^2+y.^2+z.^2;
-%! assert (interpn(x,y,-z,f,1.5,1.5,-1.5), 7.5)
+%! [x,y,z] = ndgrid (0:2);
+%! f = x.^2 + y.^2 + z.^2;
+%! assert (interpn (x,y,-z,f,1.5,1.5,-1.5), 7.5);
 
-%!test % for Matlab-compatible rounding for 'nearest'
-%! X = meshgrid (1:4);
-%! assert (interpn (X, 2.5, 2.5, 'nearest'), 3);
+%!test  # for Matlab-compatible rounding for "nearest"
+%! x = meshgrid (1:4);
+%! assert (interpn (x, 2.5, 2.5, "nearest"), 3);
 
-%!shared z, zout, tol
+%!test
 %! z = zeros (3, 3, 3);
 %! zout = zeros (5, 5, 5);
 %! z(:,:,1) = [1 3 5; 3 5 7; 5 7 9];
@@ -303,12 +308,13 @@
 %! z(:,:,3) = z(:,:,2) + 2;
 %! for n = 1:5
 %!   zout(:,:,n) = [1 2 3 4 5;
-%!                  2 3 4 5 6; 
+%!                  2 3 4 5 6;
 %!                  3 4 5 6 7;
 %!                  4 5 6 7 8;
 %!                  5 6 7 8 9] + (n-1);
-%! end
-%! tol = 10 * eps;
-%!assert (interpn (z), zout, tol)
-%!assert (interpn (z, "linear"), zout, tol)
-%!assert (interpn (z, "spline"), zout, tol)
+%! endfor
+%! tol = 10*eps;
+%! assert (interpn (z), zout, tol);
+%! assert (interpn (z, "linear"), zout, tol);
+%! assert (interpn (z, "spline"), zout, tol);
+
--- a/scripts/general/isa.m
+++ b/scripts/general/isa.m
@@ -17,40 +17,50 @@
 ## <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
 
 endfunction
 
+
 %!assert (isa ("char", "float"), false)
 %!assert (isa (logical (1), "float"), false)
 %!assert (isa (double (13), "float"), true)
@@ -75,21 +85,24 @@
 %!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"));
-%!assert (isa (int8 (13), "int8"));
-%!assert (isa (int16 (13), "int16"));
-%!assert (isa (int32 (13), "int32"));
-%!assert (isa (int64 (13), "int64"));
-%!assert (isa (uint8 (13), "uint8"));
-%!assert (isa (uint16 (13), "uint16"));
-%!assert (isa (uint32 (13), "uint32"));
-%!assert (isa (uint64 (13), "uint64"));
-%!assert (isa ("string", "char"));
-%!assert (isa (true, "logical"));
-%!assert (isa (false, "logical"));
-%!assert (isa ({1, 2}, "cell"));
+%!assert (isa (double (13), "double"))
+%!assert (isa (single (13), "single"))
+%!assert (isa (int8 (13), "int8"))
+%!assert (isa (int16 (13), "int16"))
+%!assert (isa (int32 (13), "int32"))
+%!assert (isa (int64 (13), "int64"))
+%!assert (isa (uint8 (13), "uint8"))
+%!assert (isa (uint16 (13), "uint16"))
+%!assert (isa (uint32 (13), "uint32"))
+%!assert (isa (uint64 (13), "uint64"))
+%!assert (isa ("string", "char"))
+%!assert (isa (true, "logical"))
+%!assert (isa (false, "logical"))
+%!assert (isa ({1, 2}, "cell"))
 %!test
 %! a.b = 1;
 %! assert (isa (a, "struct"));
--- a/scripts/general/isdir.m
+++ b/scripts/general/isdir.m
@@ -32,8 +32,9 @@
 
 endfunction
 
-%!error isdir ();
-%!error isdir (1, 2);
+%!assert (isdir (pwd ()))
+%!assert (! isdir ("this is highly unlikely to be a directory name"))
 
-%!assert (isdir (pwd ()));
-%!assert (! isdir ("this is highly unlikely to be a directory name"));
+%!error isdir ()
+%!error isdir (1, 2)
+
--- a/scripts/general/isequal.m
+++ b/scripts/general/isequal.m
@@ -32,12 +32,13 @@
 
 endfunction
 
+
 ## test size and shape
-%!assert(isequal([1,2,3,4],[1,2,3,4]), true)
-%!assert(isequal([1;2;3;4],[1;2;3;4]), true)
-%!assert(isequal([1,2,3,4],[1;2;3;4]), false)
-%!assert(isequal([1,2,3,4],[1,2;3,4]), false)
-%!assert(isequal([1,2,3,4],[1,3;2,4]), false)
+%!assert (isequal ([1,2,3,4],[1,2,3,4]), true)
+%!assert (isequal ([1;2;3;4],[1;2;3;4]), true)
+%!assert (isequal ([1,2,3,4],[1;2;3;4]), false)
+%!assert (isequal ([1,2,3,4],[1,2;3,4]), false)
+%!assert (isequal ([1,2,3,4],[1,3;2,4]), false)
 
 %!test
 %! A = 1:8;
@@ -55,20 +56,21 @@
 %! assert (isequal (A, B), false);
 
 ## test for equality
-%!assert(isequal([1,2,3,4],[1,2,3,4]), true)
-%!assert(isequal(['a','b','c','d'],['a','b','c','d']), true)
+%!assert (isequal ([1,2,3,4],[1,2,3,4]), true)
+%!assert (isequal (['a','b','c','d'],['a','b','c','d']), true)
 ## Test multi-line strings
-%!assert(isequal(["test";"strings"],["test";"strings"],["test";"strings"]), true)
+%!assert (isequal (["test";"strings"],["test";"strings"],["test";"strings"]), true)
 ## test for inequality
-%!assert(isequal([1,2,3,4],[1;2;3;4]),false)
-%!assert(isequal({1,2,3,4},[1,2,3,4]),false)
-%!assert(isequal([1,2,3,4],{1,2,3,4}),false)
-%!assert(isequal([1,2,NaN,4],[1,2,NaN,4]),false)
-%!assert(isequal(['a','b','c','d'],['a';'b';'c';'d']),false)
-%!assert(isequal({'a','b','c','d'},{'a';'b';'c';'d'}),false)
+%!assert (isequal ([1,2,3,4],[1;2;3;4]), false)
+%!assert (isequal ({1,2,3,4},[1,2,3,4]), false)
+%!assert (isequal ([1,2,3,4],{1,2,3,4}), false)
+%!assert (isequal ([1,2,NaN,4],[1,2,NaN,4]), false)
+%!assert (isequal (['a','b','c','d'],['a';'b';'c';'d']), false)
+%!assert (isequal ({'a','b','c','d'},{'a';'b';'c';'d'}), false)
 ## test for equality (struct)
-%!assert(isequal(struct('a',1,'b',2),struct('a',1,'b',2)),true)
-%!assert(isequal(struct('a',1,'b',2),struct('a',1,'b',2),struct('a',1,'b',2)),true)
-%!assert(isequal(struct('a','abc','b',2),struct('a','abc','b',2)),true)
+%!assert (isequal (struct ('a',1,'b',2),struct ('a',1,'b',2)), true)
+%!assert (isequal (struct ('a',1,'b',2),struct ('a',1,'b',2),struct ('a',1,'b',2)), true)
+%!assert (isequal (struct ('a',"abc",'b',2),struct ('a',"abc",'b',2)), true)
 ## test for inequality (struct)
-%!assert(isequal(struct('a',NaN,'b',2),struct('a',NaN,'b',2),struct('a',NaN,'b',2)),false)
+%!assert (isequal (struct ('a',NaN,'b',2),struct ('a',NaN,'b',2),struct ('a',NaN,'b',2)), false)
+
--- a/scripts/general/isequalwithequalnans.m
+++ b/scripts/general/isequalwithequalnans.m
@@ -33,12 +33,14 @@
 
 endfunction
 
+
 ## test for equality
-%!assert(isequalwithequalnans({1,2,NaN,4},{1,2,NaN,4}), true)
-%!assert(isequalwithequalnans([1,2,NaN,4],[1,2,NaN,4]), true)
+%!assert (isequalwithequalnans ({1,2,NaN,4},{1,2,NaN,4}), true)
+%!assert (isequalwithequalnans ([1,2,NaN,4],[1,2,NaN,4]), true)
 ## test for inequality
-%!assert(isequalwithequalnans([1,2,NaN,4],[1,NaN,3,4]),false)
-%!assert(isequalwithequalnans([1,2,NaN,4],[1,2,3,4]),false)
+%!assert (isequalwithequalnans ([1,2,NaN,4],[1,NaN,3,4]), false)
+%!assert (isequalwithequalnans ([1,2,NaN,4],[1,2,3,4]), false)
 ## test for equality (struct)
-%!assert(isequalwithequalnans(struct('a',NaN,'b',2),struct('a',NaN,'b',2),struct('a',NaN,'b',2)),true)
-%!assert(isequalwithequalnans(1,2,1), false)
+%!assert (isequalwithequalnans (struct ('a',NaN,'b',2),struct ('a',NaN,'b',2),struct ('a',NaN,'b',2)), true)
+%!assert (isequalwithequalnans (1,2,1), false)
+
--- a/scripts/general/issquare.m
+++ b/scripts/general/issquare.m
@@ -41,22 +41,23 @@
 
 endfunction
 
-%!assert(issquare ([]));
-%!assert(issquare (1));
-%!assert(!(issquare ([1, 2])));
-%!assert(issquare ([1, 2; 3, 4]));
-%!assert(!(issquare ([1, 2; 3, 4; 5, 6])));
-%!assert(!(issquare (ones (3,3,3))));
-%!assert(issquare ("t"));
-%!assert(!(issquare ("test")));
-%!assert(issquare (["test"; "ing"; "1"; "2"]));
+
+%!assert (issquare ([]))
+%!assert (issquare (1))
+%!assert (! issquare ([1, 2]))
+%!assert (issquare ([1, 2; 3, 4]))
+%!assert (! issquare ([1, 2; 3, 4; 5, 6]))
+%!assert (! issquare (ones (3,3,3)))
+%!assert (issquare ("t"))
+%!assert (! issquare ("test"))
+%!assert (issquare (["test"; "ing"; "1"; "2"]))
 %!test
 %! s.a = 1;
-%! assert(issquare (s));
-%!assert(issquare ({1, 2; 3, 4}));
-%!assert(sparse (([1, 2; 3, 4])));
+%! assert (issquare (s));
+%!assert (issquare ({1, 2; 3, 4}))
+%!assert (sparse (([1, 2; 3, 4])))
 
 %% Test input validation
-%!error issquare ();
-%!error issquare ([1, 2; 3, 4], 2);
+%!error issquare ()
+%!error issquare ([1, 2; 3, 4], 2)
 
--- a/scripts/general/loadobj.m
+++ b/scripts/general/loadobj.m
@@ -37,5 +37,5 @@
 ## @end deftypefn
 
 function b = loadobj (a)
-  error ("loadobj: not defined for class \"%s\"", class(a));
+  error ('loadobj: not defined for class "%s"', class (a));
 endfunction
--- a/scripts/general/logspace.m
+++ b/scripts/general/logspace.m
@@ -85,15 +85,15 @@
 %! 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 ();
-%!error logspace (1, 2, 3, 4);
-%!error logspace ([1, 2; 3, 4], 5, 6);
-%!error logspace (1, [1, 2; 3, 4], 6);
-%!error logspace (1, 2, [1, 2; 3, 4]);
+%!error logspace ()
+%!error logspace (1, 2, 3, 4)
+%!error logspace ([1, 2; 3, 4], 5, 6)
+%!error logspace (1, [1, 2; 3, 4], 6)
+%!error logspace (1, 2, [1, 2; 3, 4])
 
new file mode 100644
--- /dev/null
+++ b/scripts/general/methods.m
@@ -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, ';', false);
+    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, ';', false);
+  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
+++ b/scripts/general/module.mk
@@ -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/nargchk.m
+++ b/scripts/general/nargchk.m
@@ -63,18 +63,19 @@
 
 ## Tests
 %!shared stnul, stmin, stmax
-%!  stnul = resize (struct ("message", "", "identifier", ""), 0, 1);
-%!  stmin = struct ("message", "not enough input arguments",
-%!                  "identifier", "Octave:nargchk:not-enough-inputs");
-%!  stmax = struct ("message", "too many input arguments",
-%!                  "identifier", "Octave:nargchk:too-many-inputs");
+%! stnul = resize (struct ("message", "", "identifier", ""), 0, 1);
+%! stmin = struct ("message", "not enough input arguments",
+%!                 "identifier", "Octave:nargchk:not-enough-inputs");
+%! stmax = struct ("message", "too many input arguments",
+%!                 "identifier", "Octave:nargchk:too-many-inputs");
 %!assert (nargchk (0, 1, 0), "")
 %!assert (nargchk (0, 1, 1), "")
 %!assert (nargchk (1, 1, 0), "not enough input arguments")
 %!assert (nargchk (0, 1, 2), "too many input arguments")
 %!assert (nargchk (0, 1, 2, "string"), "too many input arguments")
 ## Struct outputs
-%!assert (isequal (nargchk (0, 1, 0, "struct"), stnul))
-%!assert (isequal (nargchk (0, 1, 1, "struct"), stnul))
+%!assert (nargchk (0, 1, 0, "struct"), stnul)
+%!assert (nargchk (0, 1, 1, "struct"), stnul)
 %!assert (nargchk (1, 1, 0, "struct"), stmin)
 %!assert (nargchk (0, 1, 2, "struct"), stmax)
+
--- a/scripts/general/narginchk.m
+++ b/scripts/general/narginchk.m
@@ -42,7 +42,7 @@
   elseif (!isnumeric (maxargs) || !isscalar (maxargs))
     error ("maxargs must be a numeric scalar");
   elseif (minargs > maxargs)
-    error ("minargs cannot be larger than maxargs")
+    error ("minargs cannot be larger than maxargs");
   endif
 
   args = evalin ("caller", "nargin;");
@@ -55,6 +55,7 @@
 
 endfunction
 
+
 %!function f (nargs, varargin)
 %! narginchk (nargs(1), nargs(2));
 %!endfunction
@@ -64,6 +65,6 @@
 
 %!test
 %! f([1,1])
-
 %!test
 %! f([1,5], 2, 3, 4, 5)
+
--- a/scripts/general/nargoutchk.m
+++ b/scripts/general/nargoutchk.m
@@ -87,7 +87,7 @@
     elseif (!isnumeric (maxargs) || !isscalar (maxargs))
       error ("maxargs must be a numeric scalar");
     elseif (minargs > maxargs)
-      error ("minargs cannot be larger than maxargs")
+      error ("minargs cannot be larger than maxargs");
     endif
 
     args = evalin ("caller", "nargout;");
@@ -104,21 +104,21 @@
 
 endfunction
 
-## Tests
+
 %!shared stnul, stmin, stmax
-%!  stnul = resize (struct ("message", "", "identifier", ""), 0, 1);
-%!  stmin = struct ("message", "not enough output arguments",
-%!                  "identifier", "Octave:nargoutchk:not-enough-outputs");
-%!  stmax = struct ("message", "too many output arguments",
-%!                  "identifier", "Octave:nargoutchk:too-many-outputs");
+%! stnul = resize (struct ("message", "", "identifier", ""), 0, 1);
+%! stmin = struct ("message", "not enough output arguments",
+%!                 "identifier", "Octave:nargoutchk:not-enough-outputs");
+%! stmax = struct ("message", "too many output arguments",
+%!                 "identifier", "Octave:nargoutchk:too-many-outputs");
 %!assert (nargoutchk (0, 1, 0), "")
 %!assert (nargoutchk (0, 1, 1), "")
 %!assert (nargoutchk (1, 1, 0), "not enough output arguments")
 %!assert (nargoutchk (0, 1, 2), "too many output arguments")
 %!assert (nargoutchk (0, 1, 2, "string"), "too many output arguments")
 ## Struct outputs
-%!assert (isequal (nargoutchk (0, 1, 0, "struct"), stnul))
-%!assert (isequal (nargoutchk (0, 1, 1, "struct"), stnul))
+%!assert (nargoutchk (0, 1, 0, "struct"), stnul)
+%!assert (nargoutchk (0, 1, 1, "struct"), stnul)
 %!assert (nargoutchk (1, 1, 0, "struct"), stmin)
 %!assert (nargoutchk (0, 1, 2, "struct"), stmax)
 
--- a/scripts/general/nextpow2.m
+++ b/scripts/general/nextpow2.m
@@ -56,13 +56,15 @@
 
 endfunction
 
-%!error nexpow2 ();
-%!error nexpow2 (1, 2);
 
-%!assert (nextpow2 (16), 4);
-%!assert (nextpow2 (17), 5);
-%!assert (nextpow2 (31), 5);
-%!assert (nextpow2 (-16), 4);
-%!assert (nextpow2 (-17), 5);
-%!assert (nextpow2 (-31), 5);
-%!assert (nextpow2 (1:17), 5);
+%!assert (nextpow2 (16), 4)
+%!assert (nextpow2 (17), 5)
+%!assert (nextpow2 (31), 5)
+%!assert (nextpow2 (-16), 4)
+%!assert (nextpow2 (-17), 5)
+%!assert (nextpow2 (-31), 5)
+%!assert (nextpow2 (1:17), 5)
+
+%!error nexpow2 ()
+%!error nexpow2 (1, 2)
+
--- a/scripts/general/nthargout.m
+++ b/scripts/general/nthargout.m
@@ -34,7 +34,7 @@
 ## @example
 ## @group
 ## @var{m} = magic (5);
-## cell2mat (nthargout ([1, 2], @@ind2sub, size(@var{m}),
+## cell2mat (nthargout ([1, 2], @@ind2sub, size (@var{m}),
 ##                      nthargout (2, @@max, @var{m}(:))))
 ## @result{} 5   3
 ## @end group
@@ -45,7 +45,7 @@
 ##
 ## @example
 ## @group
-## @var{m} = magic(5);
+## @var{m} = magic (5);
 ## [~, idx] = max (@var{M}(:));
 ## [i, j] = ind2sub (size (@var{m}), idx);
 ## [i, j]
@@ -84,7 +84,7 @@
   endif
 
   if (any (n != fix (n))  || ntot != fix (ntot) || any (n <= 0) || ntot <= 0)
-    error ("nthargout: N and NTOT must consist of positive integers")
+    error ("nthargout: N and NTOT must consist of positive integers");
   endif
 
   outargs = cell (1, ntot);
@@ -107,7 +107,9 @@
 
 endfunction
 
+
 %!shared m
 %! m = magic (5);
-%!assert (nthargout ([1, 2], @ind2sub, size(m), nthargout (2, @max, m(:))), {5,3}) 
+%!assert (nthargout ([1,2], @ind2sub, size (m), nthargout (2, @max, m(:))), {5,3})
 %!assert (nthargout (3, @find, m(m>20)), [23, 24, 25, 21, 22]')
+
--- a/scripts/general/num2str.m
+++ b/scripts/general/num2str.m
@@ -24,8 +24,9 @@
 ## optional second argument may either give the number of significant
 ## digits (@var{precision}) to be used in the output or a format
 ## template string (@var{format}) as in @code{sprintf} (@pxref{Formatted
-## Output}).  @code{num2str} can also handle complex numbers.  For
-## example:
+## Output}).  @code{num2str} can also handle complex numbers.
+##
+## Examples:
 ##
 ## @example
 ## @group
@@ -50,11 +51,17 @@
 ## @end group
 ## @end example
 ##
+## Notes:
+##
+## For Matlab compatibility, leading spaces are stripped before returning
+## the string.
+##
 ## The @code{num2str} function is not very flexible.  For better control
 ## over the results, use @code{sprintf} (@pxref{Formatted Output}).
-## Note that for complex @var{x}, the format string may only contain one
-## output conversion specification and nothing else.  Otherwise, you
-## will get unpredictable results.
+##
+## For complex @var{x}, the format string may only contain one
+## output conversion specification and nothing else.  Otherwise, results
+## will be unpredictable.
 ## @seealso{sprintf, int2str, mat2str}
 ## @end deftypefn
 
@@ -64,54 +71,88 @@
 
   if (nargin != 1 && nargin != 2)
     print_usage ();
+  elseif (! ismatrix (x))
+    error ("num2str: X must be a numeric, logical, or character array");
   endif
 
   if (ischar (x))
     retval = x;
   elseif (isempty (x))
     retval = "";
-  elseif (iscomplex (x))
+  elseif (isreal (x))
+    if (nargin == 2)
+      if (ischar (arg))
+        fmt = arg;
+      elseif (isnumeric (arg) && isscalar (arg) && arg >= 0)
+        fmt = sprintf ("%%%d.%dg", arg+7, arg);
+      else
+        error ("num2str: PRECISION must be a scalar integer >= 0");
+      endif
+    else
+      if (isnumeric (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
+          dgt = min (dgt, 16);      # Cap significant digits at 16
+          fmt = sprintf ("%%%d.%dg", dgt+7+any (x(:) < 0), dgt);
+        else
+          ## Integer input
+          dgt = max (dgt + 1, 1);
+          ## FIXME: Integers should be masked to show only 16 significant digits
+          ##        See %!xtest below
+          fmt = sprintf ("%%%d.%dg", dgt+2+any (x(:) < 0), dgt);
+        endif
+      else
+        ## Logical input
+        fmt = "%3d";
+      endif
+    endif
+    fmt = cstrcat (deblank (repmat (fmt, 1, columns (x))), "\n");
+    nd = ndims (x);
+    tmp = sprintf (fmt, permute (x, [2, 1, 3:nd]));
+    retval = strtrim (char (strsplit (tmp(1:end-1), "\n", false)));
+  else   # Complex matrix input
     if (nargin == 2)
       if (ischar (arg))
         fmt = cstrcat (arg, "%-+", arg(2:end), "i");
+      elseif (isnumeric (arg) && isscalar (arg) && arg >= 0)
+        fmt = sprintf ("%%%d.%dg%%-+%d.%dgi", arg+7, arg, arg+7, arg);
       else
-        if (isnumeric (x) && x == fix (x) && abs (x) < (10 .^ arg))
-          fmt = sprintf ("%%%dd%%-+%ddi  ", arg, arg);
-        else
-          fmt = sprintf ("%%%d.%dg%%-+%d.%dgi", arg+7, arg, arg+7, arg);
-        endif
+        error ("num2str: PRECISION must be a scalar integer >= 0");
       endif
     else
       ## Setup a suitable format string
-      if (isnumeric (x) && x == fix (x) && abs (x) < 1e10)
-        if (max (abs (real (x(:)))) == 0)
-          dgt1 = 2;
-        else
-          dgt1 = ceil (log10 (max (max (abs (real (x(:)))),
-                                   max (abs (imag (x(:))))))) + 2;
-        endif
-        dgt2 = dgt1 - (min (real (x(:))) >= 0);
-
-        if (length (abs (x) == x) > 0)
-          fmt = sprintf("%%%dg%%+-%dgi  ", dgt2, dgt1);
-        else
-          fmt = sprintf("%%%dd%%+-%ddi  ", dgt2, dgt1);
-        endif
-      elseif (isscalar (x))
-        fmt = "%.6g%-+.6gi";
+      dgt = floor (log10 (max (max (abs (real (x(:)))),
+                               max (abs (imag (x(:)))))));
+      if (any (x(:) != fix (x(:))))
+        ## Floating point input
+          dgt = max (dgt + 4, 5);   # Keep 4 sig. figures after decimal point
+          dgt = min (dgt, 16);      # Cap significant digits at 16
+          fmt = sprintf ("%%%d.%dg%%-+%d.%dgi", dgt+7, dgt, dgt+7, dgt);
       else
-        fmt = "%11.6g%-+11.6gi";
+        ## Integer input
+        dgt = max (1 + dgt, 1);
+        ## FIXME: Integers should be masked to show only 16 significant digits
+        ##        See %!xtest below
+        fmt = sprintf ("%%%d.%dg%%-+%d.%dgi", dgt+2, dgt, dgt+2, dgt);
       endif
     endif
 
     ## Manipulate the complex value to have real values in the odd
     ## columns and imaginary values in the even columns.
-    sz = size (x);
-    nc = sz(2);
+    nc = columns (x);
     nd = ndims (x);
-    perm = fix ([1:0.5:nc+0.5]);
-    perm(2:2:2*nc) = perm(2:2:2*nc) + nc;
     idx = repmat ({':'}, nd, 1);
+    perm(1:2:2*nc) = 1:nc;
+    perm(2:2:2*nc) = nc + (1:nc);
     idx{2} = perm;
     x = horzcat (real (x), imag (x));
     x = x(idx{:});
@@ -120,67 +161,42 @@
     tmp = sprintf (fmt, permute (x, [2, 1, 3:nd]));
 
     ## Put the "i"'s where they are supposed to be.
-    while (true)
-      tmp2 = strrep (tmp, " i\n", "i\n");
-      if (length (tmp) == length (tmp2))
-        break;
-      else
-        tmp = tmp2;
-      endif
-    endwhile
-    while (true)
-      tmp2 = strrep (tmp, " i", "i ");
-      if (tmp == tmp2)
-        break;
-      else
-        tmp = tmp2;
-      endif
-    endwhile
+    tmp = regexprep (tmp, " +i\n", "i\n");
+    tmp = regexprep (tmp, "( +)i", "i$1");
 
-    tmp(length (tmp)) = "";
-    retval = char (strtrim (strsplit (tmp, "\n")));
-  else
-    if (nargin == 2)
-      if (ischar (arg))
-        fmt = arg;
-      else
-        if (isnumeric (x) && x == fix (x) && abs (x) < (10 .^ arg))
-          fmt = sprintf ("%%%dd  ", arg);
-        else
-          fmt = sprintf ("%%%d.%dg", arg+7, arg);
-        endif
-      endif
-    else
-      if (isnumeric (x) && x == fix (x) && abs (x) < 1e10)
-        if (max (abs (x(:))) == 0)
-          dgt = 2;
-        else
-          dgt = floor (log10 (max (abs(x(:))))) + (min (real (x(:))) < 0) + 2;
-        endif
-        if (length (abs (x) == x) > 0)
-          fmt = sprintf ("%%%dg  ", dgt);
-        else
-          fmt = sprintf ("%%%dd  ", dgt);
-        endif
-      elseif (isscalar (x))
-        fmt = "%11.5g";
-      else
-        fmt = "%11.5g";
-      endif
-    endif
-    fmt = cstrcat (deblank (repmat (fmt, 1, columns (x))), "\n");
-    nd = ndims (x);
-    tmp = sprintf (fmt, permute (x, [2, 1, 3:nd]));
-    tmp(length (tmp)) = "";
-    retval = strtrim (char (strsplit (tmp, "\n")));
+    retval = strtrim (char (strsplit (tmp(1:end-1), "\n", false)));
   endif
 
 endfunction
 
-%!assert ((strcmp (num2str (123), "123") && strcmp (num2str (1.23), "1.23")));
-%!assert (num2str (123.456, 4), "123.5");
-%!assert (all (num2str ([1, 1.34; 3, 3.56], "%5.1f") == ["1.0  1.3"; "3.0  3.6"]));
-%!assert (num2str (1.234 + 27.3i), "1.234+27.3i");
-%!error num2str ();
-%!error num2str (1, 2, 3);
+
+%!assert (num2str (123), "123")
+%!assert (num2str (1.23), "1.23")
+%!assert (num2str (123.456, 4), "123.5")
+%!assert (num2str ([1, 1.34; 3, 3.56], "%5.1f"),  ["1.0  1.3"; "3.0  3.6"])
+%!assert (num2str (1.234 + 27.3i), "1.234+27.3i")
+%!assert (num2str ([true false true]), "1  0  1");
+
+%!assert (num2str (19440606), "19440606")
+%!assert (num2str (2^33), "8589934592")
+%!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.
+%!xtest
+%! assert (num2str (1e23), "100000000000000000000000");
+
+%!error num2str ()
+%!error num2str (1, 2, 3)
+%!error <X must be a numeric> num2str ({1})
+%!error <PRECISION must be a scalar integer> num2str (1, {1})
+%!error <PRECISION must be a scalar integer> num2str (1, ones (2))
+%!error <PRECISION must be a scalar integer> num2str (1, -1)
+%!error <PRECISION must be a scalar integer> num2str (1+1i, {1})
+%!error <PRECISION must be a scalar integer> num2str (1+1i, ones (2))
+%!error <PRECISION must be a scalar integer> num2str (1+1i, -1)
+
--- a/scripts/general/pol2cart.m
+++ b/scripts/general/pol2cart.m
@@ -80,27 +80,28 @@
 
 endfunction
 
+
 %!test
 %! t = [0, 0.5, 1] * pi;
 %! r = 1;
 %! [x, y] = pol2cart (t, r);
-%! assert (x, [1, 0, -1], sqrt(eps));
-%! assert (y, [0, 1,  0], sqrt(eps));
+%! assert (x, [1, 0, -1], sqrt (eps));
+%! assert (y, [0, 1,  0], sqrt (eps));
 
 %!test
 %! t = [0, 1, 1] * pi/4;
-%! r = sqrt(2) * [0, 1, 2];
+%! r = sqrt (2) * [0, 1, 2];
 %! [x, y] = pol2cart (t, r);
-%! assert (x, [0, 1, 2], sqrt(eps));
-%! assert (y, [0, 1, 2], sqrt(eps));
+%! assert (x, [0, 1, 2], sqrt (eps));
+%! assert (y, [0, 1, 2], sqrt (eps));
 
 %!test
 %! t = [0, 1, 1] * pi/4;
-%! r = sqrt(2) * [0, 1, 2];
+%! r = sqrt (2) * [0, 1, 2];
 %! z = [0, 1, 2];
 %! [x, y, z2] = pol2cart (t, r, z);
-%! assert (x, [0, 1, 2], sqrt(eps));
-%! assert (y, [0, 1, 2], sqrt(eps));
+%! assert (x, [0, 1, 2], sqrt (eps));
+%! assert (y, [0, 1, 2], sqrt (eps));
 %! assert (z, z2);
 
 %!test
@@ -108,8 +109,8 @@
 %! r = [0, 1, 2];
 %! z = [0, 1, 2];
 %! [x, y, z2] = pol2cart (t, r, z);
-%! assert (x, [0, 1, 2], sqrt(eps));
-%! assert (y, [0, 0, 0], sqrt(eps));
+%! assert (x, [0, 1, 2], sqrt (eps));
+%! assert (y, [0, 0, 0], sqrt (eps));
 %! assert (z, z2);
 
 %!test
@@ -117,8 +118,8 @@
 %! r = 1;
 %! z = [0, 1, 2];
 %! [x, y, z2] = pol2cart (t, r, z);
-%! assert (x, [1, 1, 1] / sqrt(2), eps);
-%! assert (y, [1, 1, 1] / sqrt(2), eps);
+%! assert (x, [1, 1, 1] / sqrt (2), eps);
+%! assert (y, [1, 1, 1] / sqrt (2), eps);
 %! assert (z, z2);
 
 %!test
@@ -127,16 +128,16 @@
 %! z = 1;
 %! [x, y, z2] = pol2cart (t, r, z);
 %! assert (x, [1, 2, 3], eps);
-%! assert (y, [0, 0, 0] / sqrt(2), eps);
+%! assert (y, [0, 0, 0] / sqrt (2), eps);
 %! assert (z, z2);
 
 %!test
 %! P = [0, 0; pi/4, sqrt(2); pi/4, 2*sqrt(2)];
 %! C = [0, 0; 1, 1; 2, 2];
-%! assert (pol2cart(P), C, sqrt(eps));
+%! assert (pol2cart (P), C, sqrt (eps));
 
 %!test
 %! P = [0, 0, 0; pi/4, sqrt(2), 1; pi/4, 2*sqrt(2), 2];
 %! C = [0, 0, 0; 1, 1, 1; 2, 2, 2];
-%! assert (pol2cart(P), C, sqrt(eps));
+%! assert (pol2cart (P), C, sqrt (eps));
 
--- a/scripts/general/polyarea.m
+++ b/scripts/general/polyarea.m
@@ -61,10 +61,12 @@
   endif
 endfunction
 
+
 %!shared x, y
 %! x = [1;1;3;3;1];
 %! y = [1;3;3;1;1];
-%!assert (polyarea(x,y), 4, eps)
-%!assert (polyarea([x,x],[y,y]), [4,4], eps)
-%!assert (polyarea([x,x],[y,y],1), [4,4], eps)
-%!assert (polyarea([x,x]',[y,y]',2), [4;4], eps)
+%!assert (polyarea (x,y), 4, eps)
+%!assert (polyarea ([x,x],[y,y]), [4,4], eps)
+%!assert (polyarea ([x,x],[y,y],1), [4,4], eps)
+%!assert (polyarea ([x,x]',[y,y]',2), [4;4], eps)
+
--- a/scripts/general/postpad.m
+++ b/scripts/general/postpad.m
@@ -78,20 +78,20 @@
     y = x(idx{:});
   else
     sz (dim) = l - d;
-    y = cat (dim, x, c * ones (sz));
+    y = cat (dim, x, c(ones (sz)));
   endif
 
 endfunction
 
-%!error postpad ();
-%!error postpad (1);
-%!error postpad (1,2,3,4,5);
-%!error postpad ([1,2], 2, 2,3);
 
-%!assert (postpad ([1,2], 4), [1,2,0,0]);
-%!assert (postpad ([1;2], 4), [1;2;0;0]);
+%!assert (postpad ([1,2], 4), [1,2,0,0])
+%!assert (postpad ([1;2], 4), [1;2;0;0])
+%!assert (postpad ([1,2], 4, 2), [1,2,2,2])
+%!assert (postpad ([1;2], 4, 2), [1;2;2;2])
+%!assert (postpad ([1,2], 2, 2, 1), [1,2;2,2])
 
-%!assert (postpad ([1,2], 4, 2), [1,2,2,2]);
-%!assert (postpad ([1;2], 4, 2), [1;2;2;2]);
+%!error postpad ()
+%!error postpad (1)
+%!error postpad (1,2,3,4,5)
+%!error postpad ([1,2], 2, 2,3)
 
-%!assert (postpad ([1,2], 2, 2, 1), [1,2;2,2]);
--- a/scripts/general/prepad.m
+++ b/scripts/general/prepad.m
@@ -46,7 +46,7 @@
     c = 0;
   else
     if (! isscalar (c))
-      error ("prepad: third argument must be empty or a scalar");
+      error ("prepad: pad value C must be empty or a scalar");
     endif
   endif
 
@@ -63,7 +63,7 @@
   endif
 
   if (! isscalar (l) || l < 0)
-    error ("prepad: second argument must be a positive scaler");
+    error ("prepad: length L must be a positive scalar");
   endif
 
   if (dim > nd)
@@ -83,17 +83,24 @@
 
 endfunction
 
-%!error prepad ();
-%!error prepad (1);
-%!error prepad (1,2,3,4,5);
-%!error prepad ([1,2], 2, 2,3);
+
+%!assert (prepad ([1,2], 4), [0,0,1,2])
+%!assert (prepad ([1;2], 4), [0;0;1;2])
 
-%!assert (prepad ([1,2], 4), [0,0,1,2]);
-%!assert (prepad ([1;2], 4), [0;0;1;2]);
+%!assert (prepad ([1,2], 4, 2), [2,2,1,2])
+%!assert (prepad ([1;2], 4, 2), [2;2;1;2])
 
-%!assert (prepad ([1,2], 4, 2), [2,2,1,2]);
-%!assert (prepad ([1;2], 4, 2), [2;2;1;2]);
-
-%!assert (prepad ([1,2], 2, 2, 1), [2,2;1,2]);
+%!assert (prepad ([1,2], 2, 2, 1), [2,2;1,2])
 
 ## FIXME -- we need tests for multidimensional arrays.
+
+%!error prepad ()
+%!error prepad (1)
+%!error prepad (1,2,3,4,5)
+%!error <C must be empty or a scalar> prepad ([1,2], 2, ones (2))
+%!error <DIM must be an integer> prepad ([1,2], 2, 2, ones (3))
+%!error <DIM must be an integer> prepad ([1,2], 2, 2, 1.1)
+%!error <DIM must be an integer> prepad ([1,2], 2, 2, 3)
+%!error <L must be a positive scalar> prepad ([1,2], ones (2))
+%!error <L must be a positive scalar> prepad ([1,2], -1)
+
--- a/scripts/general/private/__isequal__.m
+++ b/scripts/general/private/__isequal__.m
@@ -58,7 +58,7 @@
 
   ## All arguments must either be of the same class or they must be
   ## numeric values.
-  t = (all (strcmp (class(x),
+  t = (all (strcmp (class (x),
                     cellfun ("class", varargin, "uniformoutput", false)))
        || ((isnumeric (x) || islogical (x))
            && all (cellfun ("isnumeric", varargin)
--- a/scripts/general/private/__splinen__.m
+++ b/scripts/general/private/__splinen__.m
@@ -31,18 +31,18 @@
   endif
   ## ND isvector function.
   isvec = @(x) numel (x) == length (x);
-  if (!iscell (x) || length(x) < ndims(y) || any (! cellfun (isvec, x))
-      || !iscell (xi) || length(xi) < ndims(y) || any (! cellfun (isvec, xi)))
+  if (!iscell (x) || length (x) < ndims (y) || any (! cellfun (isvec, x))
+      || !iscell (xi) || length (xi) < ndims (y) || any (! cellfun (isvec, xi)))
     error ("__splinen__: %s: non gridded data or dimensions inconsistent", f);
   endif
   yi = y;
-  for i = length(x):-1:1
+  for i = length (x):-1:1
     yi = permute (spline (x{i}, yi, xi{i}(:)), [length(x),1:length(x)-1]);
   endfor
 
   [xi{:}] = ndgrid (cellfun (@(x) x(:), xi, "uniformoutput", false){:});
-  idx = zeros (size(xi{1}));
-  for i = 1 : length(x)
+  idx = zeros (size (xi{1}));
+  for i = 1 : length (x)
     idx |= xi{i} < min (x{i}(:)) | xi{i} > max (x{i}(:));
   endfor
   yi(idx) = extrapval;
--- a/scripts/general/profexplore.m
+++ b/scripts/general/profexplore.m
@@ -21,7 +21,7 @@
 ## Interactively explore hierarchical profiler output.
 ##
 ## Assuming @var{data} is the structure with profile data returned by
-## @code{profile ('info')}, this command opens an interactive prompt
+## @code{profile ("info")}, this command opens an interactive prompt
 ## that can be used to explore the call-tree.  Type @kbd{help} to get a list
 ## of possible commands.
 ## @seealso{profile, profshow}
@@ -32,7 +32,7 @@
 
 function profexplore (data)
 
-  if (nargin ~= 1)
+  if (nargin != 1)
     print_usage ();
   endif
 
@@ -45,7 +45,7 @@
 endfunction
 
 ## This is the worker function.  tree is the current subtree we want to
-## display / explore.  parents is a string containing the already 'rendered'
+## display / explore.  parents is a string containing the already "rendered"
 ## data for the parents which is displayed on top of the list of current
 ## children.  prefix is the prefix to add to each line rendered; this
 ## is just a string of spaces to get indentation right.
@@ -87,7 +87,7 @@
       printf ("help   Display this help message.\n");
       printf ("up [N] Go up N levels, where N is an integer.  Default is 1.\n");
       printf ("N      Go down a level into option N.\n");
-    elseif (~isnan (option))
+    elseif (! isnan (option))
       if (option < 1 || option > length (tree))
         printf ("The chosen option is out of range!\n");
       else
@@ -115,7 +115,7 @@
 
       if (length (cmd) > 3 && cmd(3) == ' ')
         opt = fix (str2double (substr (cmd, 3)));
-        if (~isnan (opt) && opt > 0)
+        if (! isnan (opt) && opt > 0)
           rv = opt;
           return;
         endif
--- a/scripts/general/profile.m
+++ b/scripts/general/profile.m
@@ -21,8 +21,8 @@
 ## @deftypefnx {Command} {} profile off
 ## @deftypefnx {Command} {} profile resume
 ## @deftypefnx {Command} {} profile clear
-## @deftypefnx {Function File} {@var{S} =} profile ('status')
-## @deftypefnx {Function File} {@var{T} =} profile ('info')
+## @deftypefnx {Function File} {@var{S} =} profile ("status")
+## @deftypefnx {Function File} {@var{T} =} profile ("info")
 ## Control the built-in profiler.
 ##
 ## @table @code
@@ -32,7 +32,7 @@
 ##
 ## @item profile off
 ## Stop profiling.  The collected data can later be retrieved and examined
-## with calls like @code{S = profile ('info')}.
+## with calls like @code{S = profile ("info")}.
 ##
 ## @item profile clear
 ## Clear all collected profiler data.
@@ -41,12 +41,12 @@
 ## Restart profiling without cleaning up the old data and instead
 ## all newly collected statistics are added to the already existing ones.
 ##
-## @item @var{S} = profile ('status')
+## @item @var{S} = profile ("status")
 ## Return a structure filled with certain information about the current status
 ## of the profiler.  At the moment, the only field is @code{ProfilerStatus}
-## which is either 'on' or 'off'.
+## which is either "on" or "off".
 ##
-## @item @var{T} = profile ('info')
+## @item @var{T} = profile ("info")
 ## Return the collected profiling statistics in the structure @var{T}.
 ## The flat profile is returned in the field @code{FunctionTable} which is an
 ## array of structures, each entry corresponding to a function which was called
@@ -69,31 +69,31 @@
   endif
 
   switch (option)
-    case 'on'
+    case "on"
       __profiler_reset__ ();
       __profiler_enable__ (true);
 
-    case 'off'
+    case "off"
       __profiler_enable__ (false);
 
-    case 'clear'
+    case "clear"
       __profiler_reset__ ();
 
-    case 'resume'
+    case "resume"
       __profiler_enable__ (true);
 
-    case 'status'
+    case "status"
       enabled = __profiler_enable__ ();
       if (enabled)
-        enabled = 'on';
+        enabled = "on";
       else
-        enabled = 'off';
+        enabled = "off";
       endif
-      retval = struct ('ProfilerStatus', enabled);
+      retval = struct ("ProfilerStatus", enabled);
 
-    case 'info'
+    case "info"
       [flat, tree] = __profiler_data__ ();
-      retval = struct ('FunctionTable', flat, 'Hierarchical', tree);
+      retval = struct ("FunctionTable", flat, "Hierarchical", tree);
 
     otherwise
       warning ("profile: Unrecognized option '%s'", option);
@@ -105,47 +105,50 @@
 
 
 %!demo
-%! profile ('on');
+%! profile on;
 %! A = rand (100);
 %! B = expm (A);
-%! profile ('off');
-%! profile ('resume');
+%! profile off;
+%! profile resume;
 %! C = sqrtm (A);
-%! profile ('off');
-%! T = profile ('info');
+%! profile off;
+%! T = profile ("info");
 %! profshow (T);
 
-%!error profile ();
-%!error profile ('on', 2);
-
 %!test
 %! on_struct.ProfilerStatus = "on";
 %! off_struct.ProfilerStatus = "off";
-%! profile ('on');
+%! profile ("on");
 %! result = logm (rand (200) + 10 * eye (200));
-%! assert (profile ('status'), on_struct);
-%! profile ('off');
-%! assert (profile ('status'), off_struct);
-%! profile ('resume');
+%! assert (profile ("status"), on_struct);
+%! profile ("off");
+%! assert (profile ("status"), off_struct);
+%! profile ("resume");
 %! result = logm (rand (200) + 10 * eye (200));
-%! profile ('off');
-%! assert (profile ('status'), off_struct);
-%! info = profile ('info');
+%! profile ("off");
+%! assert (profile ("status"), off_struct);
+%! info = profile ("info");
 %! assert (isstruct (info));
 %! assert (size (info), [1, 1]);
-%! assert (fieldnames (info), {'FunctionTable'; 'Hierarchical'});
+%! assert (fieldnames (info), {"FunctionTable"; "Hierarchical"});
 %! ftbl = info.FunctionTable;
-%! assert (fieldnames (ftbl), {'FunctionName'; 'TotalTime'; 'NumCalls'; 'IsRecursive'; 'Parents'; 'Children'});
+%! assert (fieldnames (ftbl), {"FunctionName"; "TotalTime"; "NumCalls"; "IsRecursive"; "Parents"; "Children"});
 %! hier = info.Hierarchical;
-%! assert (fieldnames (hier), {'Index'; 'SelfTime'; 'TotalTime'; 'NumCalls'; 'Children'});
-%! profile ('clear');
-%! info = profile ('info');
+%! assert (fieldnames (hier), {"Index"; "SelfTime"; "TotalTime"; "NumCalls"; "Children"});
+%! profile ("clear");
+%! info = profile ("info");
 %! assert (isstruct (info));
 %! assert (size (info), [1, 1]);
-%! assert (fieldnames (info), {'FunctionTable'; 'Hierarchical'});
+%! assert (fieldnames (info), {"FunctionTable"; "Hierarchical"});
 %! ftbl = info.FunctionTable;
 %! assert (size (ftbl), [0, 1]);
-%! assert (fieldnames (ftbl), {'FunctionName'; 'TotalTime'; 'NumCalls'; 'IsRecursive'; 'Parents'; 'Children'});
+%! assert (fieldnames (ftbl), {"FunctionName"; "TotalTime"; "NumCalls"; "IsRecursive"; "Parents"; "Children"});
 %! hier = info.Hierarchical;
 %! assert (size (hier), [0, 1]);
-%! assert (fieldnames (hier), {'Index'; 'SelfTime'; 'NumCalls'; 'Children'});
+%! assert (fieldnames (hier), {"Index"; "SelfTime"; "NumCalls"; "Children"});
+
+%% Test input validation
+%!error profile ()
+%!error profile ("on", 2)
+%!error profile ("INVALID_OPTION")
+
--- a/scripts/general/profshow.m
+++ b/scripts/general/profshow.m
@@ -22,7 +22,7 @@
 ## Show flat profiler results.
 ##
 ## This command prints out profiler data as a flat profile.  @var{data} is the
-## structure returned by @code{profile ('info')}.  If @var{n} is given, it
+## structure returned by @code{profile ("info")}.  If @var{n} is given, it
 ## specifies the number of functions to show in the profile; functions are
 ## sorted in descending order by total time spent in them.  If there are more
 ## than @var{n} included in the profile, those will not be shown.  @var{n}
@@ -81,20 +81,24 @@
 
 endfunction
 
+
 %!demo
-%! profile ("on");
+%! profile on;
 %! A = rand (100);
 %! B = expm (A);
-%! profile ("off");
+%! profile off;
 %! T = profile ("info");
 %! profshow (T, 10);
 
 %!demo
-%! profile ("on");
+%! profile on;
 %! expm (rand (500) + eye (500));
-%! profile ("off");
+%! profile off;
 %! profshow (profile ("info"), 5);
 
-%!error profshow ();
-%!error profshow (1, 2, 3);
-%!error profshow (struct (), 1.2);
+%!error profshow ()
+%!error profshow (1, 2, 3)
+%!error <N must be a positive integer> profshow (struct (), ones (2))
+%!error <N must be a positive integer> profshow (struct (), 1+i)
+%!error <N must be a positive integer> profshow (struct (), -1)
+
--- a/scripts/general/quadgk.m
+++ b/scripts/general/quadgk.m
@@ -78,7 +78,7 @@
 ## unacceptable error are subdivided and re-evaluated.  If the number of
 ## subintervals exceeds 650 subintervals at any point then a poor
 ## convergence is signaled and the current estimate of the integral is
-## returned.  The property 'MaxIntervalCount' can be used to alter the
+## returned.  The property "MaxIntervalCount" can be used to alter the
 ## number of subintervals that can exist before exiting.
 ##
 ## @item WayPoints
@@ -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
@@ -162,7 +162,7 @@
               abstol = varargin{idx++};
             elseif (strcmpi (str, "waypoints"))
               waypoints = varargin{idx++} (:);
-              if (isreal(waypoints))
+              if (isreal (waypoints))
                 waypoints (waypoints < a | waypoints > b) = [];
               endif
             elseif (strcmpi (str, "maxintervalcount"))
@@ -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,24 +188,24 @@
     endif
 
     ## Use variable subsitution to weaken endpoint singularities and to
-    ## perform integration with endpoints at infinity. No transform for
-    ## contour integrals
-    if (iscomplex (a) || iscomplex (b) || iscomplex(waypoints))
+    ## 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];
       h = sum (abs (diff (subs)));
       h0 = h;
       trans = @(t) t;
-    elseif (isinf (a) && isinf(b))
-      ## Standard Infinite to finite integral transformation.
+    elseif (isinf (a) && isinf (b))
+      ## 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))
-        trans = @(x) (2 * x) ./ (1 + sqrt(1 + 4 * x .^ 2));
+      if (! isempty (waypoints))
+        trans = @(x) (2 * x) ./ (1 + sqrt (1 + 4 * x .^ 2));
         subs = [-1; trans(waypoints); 1];
       else
         subs = linspace (-1, 1, 11)';
@@ -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];
@@ -240,7 +240,7 @@
       h0 = b - a;
       trans = @(t) b - (t ./ (1 + t)).^2;
       f = @(s) - 2 * s .* f (b -  (s ./ (1 + s)) .^ 2) ./ ((1 + s) .^ 3);
-    elseif (isinf(b))
+    elseif (isinf (b))
       ## 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
@@ -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];
@@ -281,7 +281,7 @@
         trans = @__quadgk_finite_waypoint__;
         subs = [-1; trans(waypoints, a, b); 1];
       else
-        subs = linspace(-1, 1, 11)';
+        subs = linspace (-1, 1, 11)';
       endif
       h = 2;
       h0 = b - a;
@@ -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
 
@@ -425,7 +422,7 @@
   halfwidth = diff (subs, [], 2) ./ 2;
   center = sum (subs, 2) ./ 2;;
   x = bsxfun (@plus, halfwidth * abscissa, center);
-  y = reshape (f (x(:)), size(x));
+  y = reshape (f (x(:)), size (x));
 
   ## This is faster than using bsxfun as the * operator can use a
   ## single BLAS call, rather than rows(sub) calls to the @times
@@ -436,26 +433,27 @@
 
 function t = __quadgk_finite_waypoint__ (x, a, b)
   c = (-4 .* x + 2.* (b + a)) ./ (b - a);
-  k = ((sqrt(c .^ 2 - 4) + c) ./ 2) .^ (1/3);
+  k = ((sqrt (c .^ 2 - 4) + c) ./ 2) .^ (1/3);
   t = real ((sqrt(3) .* 1i * (1 - k .^ 2) - (1 + k .^ 2)) ./ 2 ./ k);
 endfunction
 
+
+%!assert (quadgk (@sin,-pi,pi), 0, 1e-6)
+%!assert (quadgk (inline ("sin"),-pi,pi), 0, 1e-6)
+%!assert (quadgk ("sin",-pi,pi), 0, 1e-6)
+%!assert (quadgk (@sin,-pi,pi, "waypoints", 0, "MaxIntervalCount", 100, "reltol", 1e-3, "abstol", 1e-6, "trace", false), 0, 1e-6)
+%!assert (quadgk (@sin,-pi,pi, 1e-6,false), 0, 1e-6)
+
+%!assert (quadgk (@sin,-pi,0), -2, 1e-6)
+%!assert (quadgk (@sin,0,pi), 2, 1e-6)
+%!assert (quadgk (@(x) 1./sqrt (x),0,1), 2, 1e-6)
+%!assert (quadgk (@(x) abs (1 - x.^2),0,2, "Waypoints", 1), 2, 1e-6)
+%!assert (quadgk (@(x) 1./(sqrt (x) .* (x+1)),0,Inf), pi, 1e-6)
+%!assert (quadgk (@(z) log (z),1+1i,1+1i, "WayPoints", [1-1i, -1,-1i, -1+1i]), -pi * 1i, 1e-6)
+
+%!assert (quadgk (@(x) exp (-x .^ 2),-Inf,Inf), sqrt (pi), 1e-6)
+%!assert (quadgk (@(x) exp (-x .^ 2),-Inf,0), sqrt (pi)/2, 1e-6)
+
 %error (quadgk (@sin))
 %error (quadgk (@sin, -pi))
-%error (quadgk (@sin, -pi, pi, 'DummyArg'))
-
-%!assert (quadgk(@sin,-pi,pi), 0, 1e-6)
-%!assert (quadgk(inline('sin'),-pi,pi), 0, 1e-6)
-%!assert (quadgk('sin',-pi,pi), 0, 1e-6)
-%!assert (quadgk(@sin,-pi,pi,'waypoints', 0, 'MaxIntervalCount', 100, 'reltol', 1e-3, 'abstol', 1e-6, 'trace', false), 0, 1e-6)
-%!assert (quadgk(@sin,-pi,pi,1e-6,false), 0, 1e-6)
-
-%!assert (quadgk(@sin,-pi,0), -2, 1e-6)
-%!assert (quadgk(@sin,0,pi), 2, 1e-6)
-%!assert (quadgk(@(x) 1./sqrt(x), 0, 1), 2, 1e-6)
-%!assert (quadgk (@(x) abs (1 - x.^2), 0, 2, 'Waypoints', 1), 2, 1e-6)
-%!assert (quadgk(@(x) 1./(sqrt(x).*(x+1)), 0, Inf), pi, 1e-6)
-%!assert (quadgk (@(z) log (z), 1+1i, 1+1i, 'WayPoints', [1-1i, -1,-1i, -1+1i]), -pi * 1i, 1e-6)
-
-%!assert (quadgk (@(x) exp(-x .^ 2), -Inf, Inf), sqrt(pi), 1e-6)
-%!assert (quadgk (@(x) exp(-x .^ 2), -Inf, 0), sqrt(pi)/2, 1e-6)
+%error (quadgk (@sin, -pi, pi, "DummyArg"))
--- a/scripts/general/quadl.m
+++ b/scripts/general/quadl.m
@@ -136,7 +136,7 @@
   if (R > 0 && R < 1)
     tol = tol/R;
   endif
-  is = s * abs(is) * tol/myeps;
+  is = s * abs (is) * tol/myeps;
   if (is == 0)
     is = b-a;
   endif
@@ -162,7 +162,7 @@
   h = (b-a)/2;
   m = (a+b)/2;
   alpha = sqrt (2/3);
-  beta = 1 / sqrt(5);
+  beta = 1 / sqrt (5);
   mll = m-alpha*h;
   ml  = m-beta*h;
   mr  = m+beta*h;
--- a/scripts/general/quadv.m
+++ b/scripts/general/quadv.m
@@ -148,14 +148,16 @@
   endif
 endfunction
 
+
 %!assert (quadv (@sin, 0, 2 * pi), 0, 1e-5)
 %!assert (quadv (@sin, 0, pi), 2, 1e-5)
 
 %% Handles weak singularities at the edge
-%!assert (quadv (@(x) 1 ./ sqrt(x), 0, 1), 2, 1e-5)
+%!assert (quadv (@(x) 1 ./ sqrt (x), 0, 1), 2, 1e-5)
 
 %% Handles vector-valued functions
 %!assert (quadv (@(x) [(sin (x)), (sin (2 * x))], 0, pi), [2, 0], 1e-5)
 
 %% Handles matrix-valued functions
 %!assert (quadv (@(x) [ x, x, x; x, 1./sqrt(x), x; x, x, x ], 0, 1 ), [0.5, 0.5, 0.5; 0.5, 2, 0.5; 0.5, 0.5, 0.5], 1e-5)
+
--- a/scripts/general/randi.m
+++ b/scripts/general/randi.m
@@ -57,7 +57,7 @@
 function ri = randi (bounds, varargin)
 
   if (nargin < 1)
-    print_usage();
+    print_usage ();
   endif
 
   if (! (isnumeric (bounds) && isreal (bounds)))
@@ -113,29 +113,29 @@
 
 %!test
 %! ri = randi (10, 1000, 1);
-%! assert(isequal(ri, fix (ri)));
-%! assert(min(ri) == 1);
-%! assert(max(ri) == 10);
-%! assert(rows(ri) == 1000);
-%! assert(columns(ri) == 1);
-%! assert(strcmp (class (ri), "double"));
+%! assert (ri, fix (ri));
+%! assert (min (ri), 1);
+%! assert (max (ri), 10);
+%! assert (rows (ri), 1000);
+%! assert (columns (ri), 1);
+%! assert (class (ri), "double");
 %!test
 %! ri = randi ([-5, 10], 1000, 1, "int8");
-%! assert(isequal(ri, fix (ri)));
-%! assert(min(ri) == -5);
-%! assert(max(ri) == 10);
-%! assert(strcmp (class (ri), "int8"));
+%! assert (ri, fix (ri));
+%! assert (min (ri), int8 (-5));
+%! assert (max (ri), int8 (10));
+%! assert (class (ri), "int8");
 %!
-%!assert(size (randi(10, 3,1,2)) == [3, 1, 2])
+%!assert (size (randi (10, 3,1,2)), [3, 1, 2])
 
 %% Test input validation
-%!error(randi())
-%!error(randi("test"))
-%!error(randi(10+2i))
-%!error(randi(0))
-%!error(randi([10, 1]))
-%!error(randi(256, "uint8"))
-%!error(randi(2^25, "single"))
-%!error(randi(bitmax() + 1))
-%!error(randi([-1, bitmax()]))
+%!error (randi ())
+%!error (randi ("test"))
+%!error (randi (10+2i))
+%!error (randi (0))
+%!error (randi ([10, 1]))
+%!error (randi (256, "uint8"))
+%!error (randi (2^25, "single"))
+%!error (randi (bitmax () + 1))
+%!error (randi ([-1, bitmax()]))
 
--- a/scripts/general/rat.m
+++ b/scripts/general/rat.m
@@ -36,7 +36,7 @@
 ## @seealso{rats}
 ## @end deftypefn
 
-function [n,d] = rat(x,tol)
+function [n,d] = rat (x,tol)
 
   if (nargin != [1,2] || nargout > 2)
     print_usage ();
@@ -49,27 +49,27 @@
 
   ## default norm
   if (nargin < 2)
-    tol = 1e-6 * norm(y,1);
+    tol = 1e-6 * norm (y,1);
   endif
 
   ## First step in the approximation is the integer portion
 
   ## First element in the continued fraction.
-  n = round(y);
-  d = ones(size(y));
+  n = round (y);
+  d = ones (size (y));
   frac = y-n;
-  lastn = ones(size(y));
-  lastd = zeros(size(y));
+  lastn = ones (size (y));
+  lastd = zeros (size (y));
 
-  nd = ndims(y);
+  nd = ndims (y);
   nsz = numel (y);
-  steps = zeros([nsz, 0]);
+  steps = zeros ([nsz, 0]);
 
   ## Grab new factors until all continued fractions converge.
   while (1)
     ## Determine which fractions have not yet converged.
-    idx = find(abs (y-n./d) >= tol);
-    if (isempty(idx))
+    idx = find (abs (y-n./d) >= tol);
+    if (isempty (idx))
       if (isempty (steps))
         steps = NaN (nsz, 1);
       endif
@@ -79,7 +79,7 @@
     ## Grab the next step in the continued fraction.
     flip = 1./frac(idx);
     ## Next element in the continued fraction.
-    step = round(flip);
+    step = round (flip);
 
     if (nargout < 2)
       tsteps = NaN (nsz, 1);
@@ -100,23 +100,23 @@
 
   if (nargout == 2)
     ## Move the minus sign to the top.
-    n = n.*sign(d);
-    d = abs(d);
+    n = n .* sign (d);
+    d = abs (d);
 
     ## Return the same shape as you receive.
-    n = reshape(n, size(x));
-    d = reshape(d, size(x));
+    n = reshape (n, size (x));
+    d = reshape (d, size (x));
 
     ## Use 1/0 for Inf.
-    n(isinf(x)) = sign(x(isinf(x)));
-    d(isinf(x)) = 0;
+    n(isinf (x)) = sign (x(isinf (x)));
+    d(isinf (x)) = 0;
 
     ## Reshape the output.
     n = reshape (n, size (x));
     d = reshape (d, size (x));
   else
     n = "";
-    nsteps = size(steps, 2);
+    nsteps = columns (steps);
     for i = 1: nsz
       s = [int2str(y(i))," "];
       j = 1;
@@ -151,10 +151,12 @@
 
 endfunction
 
-%!error rat ();
-%!error rat (1, 2, 3);
 
 %!test
 %! [n, d] = rat ([0.5, 0.3, 1/3]);
 %! assert (n, [1, 3, 1]);
 %! assert (d, [2, 10, 3]);
+
+%!error rat ();
+%!error rat (1, 2, 3);
+
--- a/scripts/general/repmat.m
+++ b/scripts/general/repmat.m
@@ -20,12 +20,13 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {} repmat (@var{A}, @var{m})
 ## @deftypefnx {Function File} {} repmat (@var{A}, @var{m}, @var{n})
-## @deftypefnx {Function File} {} repmat (@var{A}, @var{m}, @var{n}, @var{p}, @dots{})
 ## @deftypefnx {Function File} {} repmat (@var{A}, [@var{m} @var{n}])
 ## @deftypefnx {Function File} {} repmat (@var{A}, [@var{m} @var{n} @var{p} @dots{}])
 ## Form a block matrix of size @var{m} by @var{n}, with a copy of matrix
 ## @var{A} as each element.  If @var{n} is not specified, form an
-## @var{m} by @var{m} block matrix.
+## @var{m} by @var{m} block matrix.  For copying along more than two
+## dimensions, specify the number of times to copy across each dimension
+## @var{m}, @var{n}, @var{p}, @dots{}, in a vector in the second argument.
 ## @seealso{repelems}
 ## @end deftypefn
 
@@ -39,24 +40,48 @@
   endif
 
   if (nargin == 3)
-    if (! (isscalar (m) && isscalar (n)))
-      error ("repmat: with 3 arguments M and N must be scalar");
+    if (! isempty (m) && isempty (n))
+      m = m(:).';
+      n = 1;
+    elseif (isempty (m) && ! isempty (n))
+      m = n(:).';
+      n = 1;
+    elseif (isempty (m) && isempty (n))
+      m = n = 1;
+    else
+      if (all (size (m) > 1))
+        m = m(:,1);
+        if (numel (m) < 3)
+          n = n(end);
+        else
+          n = [];
+        endif
+      endif
+      if (all (size (n) > 1))
+        n = n(:,1);
+      endif
+      m = m(:).';
+      n = n(:).';
     endif
-    idx = [m, n];
   else
-    if (isscalar (m))
-      idx = [m, m];
+    if (isempty (m))
+      m = n = 1;
+    elseif (isscalar (m))
       n = m;
-    elseif (isvector (m) && length (m) > 1)
-      ## Ensure that we have a row vector
-      idx = m(:).';
+    elseif (ndims (m) > 2)
+      error ("repmat: M has more than 2 dimensions")
+    elseif (all (size (m) > 1))
+      m = m(:,1).';
+      n = [];
     else
-      error ("repmat: invalid dimensional argument");
+      m = m(:).';
+      n = [];
     endif
   endif
+  idx = [m, n];
 
   if (all (idx < 0))
-    error ("repmat: invalid dimensions");
+    error ("repmat: invalid dimensions")
   else
     idx = max (idx, 0);
   endif
@@ -100,63 +125,78 @@
 
 endfunction
 
+# Tests for ML compatibility
+%!shared x
+%! x = [1 2 3];
+%!assert (repmat (x, [3, 1]), repmat (x, 3, []))
+%!assert (repmat (x, [3, 1]), repmat (x, [], 3))
+%!assert (repmat (x, [1, 3]), repmat (x, [], [1, 3]))
+%!assert (repmat (x, [1, 3]), repmat (x, [1, 3], []))
+%!assert (repmat (x, [1 3]), repmat (x, [1 3; 3 3]))
+%!assert (repmat (x, [1 1 2]), repmat (x, [1 1; 1 3; 2 1]))
+%!assert (repmat (x, [1 3; 1 3], [1; 3]), repmat (x, [1 1 3]))
+%!assert (repmat (x, [1 1], 4), repmat (x, [1 3; 1 3], [1; 4]))
+%!assert (repmat (x, [1 1], 4), repmat (x, [1 3; 1 3], [1 2; 3 4]))
+%!assert (repmat (x, [1 1], 4), repmat (x, [1 1 4]));
+%!assert (repmat (x, [1 1], 4), repmat (x, 1, [1 4]));
+
 # Test various methods of providing size parameters
 %!shared x
 %! x = [1 2;3 4];
-%!assert(repmat(x, [1 1]), repmat(x, 1));
-%!assert(repmat(x, [3 3]), repmat(x, 3));
-%!assert(repmat(x, [1 1]), repmat(x, 1, 1));
-%!assert(repmat(x, [1 3]), repmat(x, 1, 3));
-%!assert(repmat(x, [3 1]), repmat(x, 3, 1));
-%!assert(repmat(x, [3 3]), repmat(x, 3, 3));
+%!assert (repmat (x, [1 1]), repmat (x, 1))
+%!assert (repmat (x, [3 3]), repmat (x, 3))
+%!assert (repmat (x, [1 1]), repmat (x, 1, 1))
+%!assert (repmat (x, [1 3]), repmat (x, 1, 3))
+%!assert (repmat (x, [3 1]), repmat (x, 3, 1))
+%!assert (repmat (x, [3 3]), repmat (x, 3, 3))
 
 # Tests for numel==1 case:
 %!shared x, r
 %! x = [ 65 ];
-%! r = kron(ones(2,2), x);
-%!assert(r, repmat(x, [2 2]));
-%!assert(char(r), repmat(char(x), [2 2]));
-%!assert(int8(r), repmat(int8(x), [2 2]));
+%! r = kron (ones (2,2), x);
+%!assert (r, repmat (x, [2 2]))
+%!assert (char (r), repmat (char (x), [2 2]))
+%!assert (int8 (r), repmat (int8 (x), [2 2]))
 
 # Tests for ndims==2 case:
 %!shared x, r
 %! x = [ 65 66 67 ];
-%! r = kron(ones(2,2), x);
-%!assert(r, repmat(x, [2 2]));
-%!assert(char(r), repmat(char(x), [2 2]));
-%!assert(int8(r), repmat(int8(x), [2 2]));
+%! r = kron (ones (2,2), x);
+%!assert (r, repmat (x, [2 2]))
+%!assert (char (r), repmat (char (x), [2 2]))
+%!assert (int8 (r), repmat (int8 (x), [2 2]))
 
 # Tests for dim>2 case:
 %!shared x, r
 %! x = [ 65 66 67 ];
-%! r = kron(ones(2,2), x);
+%! r = kron (ones (2,2), x);
 %! r(:,:,2) = r(:,:,1);
-%!assert(r, repmat(x, [2 2 2]));
-%!assert(char(r), repmat(char(x), [2 2 2]));
-%!assert(int8(r), repmat(int8(x), [2 2 2]));
+%!assert (r, repmat (x, [2 2 2]))
+%!assert (char (r), repmat (char (x), [2 2 2]))
+%!assert (int8 (r), repmat (int8 (x), [2 2 2]))
 
 # Test that sparsity is kept
-%!assert(sparse(4,4), repmat(sparse(2,2),[2 2]));
+%!assert (sparse (4,4), repmat (sparse (2,2),[2 2]))
 
+%!assert (size (repmat (".", -1, 1)), [0, 1])
+%!assert (size (repmat (".", 1, -1)), [1, 0])
 
-%!assert (size (repmat (".", -1, 1)), [0, 1]);
-%!assert (size (repmat (".", 1, -1)), [1, 0]);
-%!error (size (repmat (".", -1, -1)));
-
-%!assert (size (repmat (1, [1, 0])), [1, 0]);
-%!assert (size (repmat (1, [5, 0])), [5, 0]);
-%!assert (size (repmat (1, [0, 1])), [0, 1]);
-%!assert (size (repmat (1, [0, 5])), [0, 5]);
+%!assert (size (repmat (1, [1, 0])), [1, 0])
+%!assert (size (repmat (1, [5, 0])), [5, 0])
+%!assert (size (repmat (1, [0, 1])), [0, 1])
+%!assert (size (repmat (1, [0, 5])), [0, 5])
 
 %!shared x
 %! x = struct ("a", [], "b", []);
-%!assert (size (repmat (x, [1, 0])), [1, 0]);
-%!assert (size (repmat (x, [5, 0])), [5, 0]);
-%!assert (size (repmat (x, [0, 1])), [0, 1]);
-%!assert (size (repmat (x, [0, 5])), [0, 5]);
+%!assert (size (repmat (x, [1, 0])), [1, 0])
+%!assert (size (repmat (x, [5, 0])), [5, 0])
+%!assert (size (repmat (x, [0, 1])), [0, 1])
+%!assert (size (repmat (x, [0, 5])), [0, 5])
 
-%!assert (size (repmat ({1}, [1, 0])), [1, 0]);
-%!assert (size (repmat ({1}, [5, 0])), [5, 0]);
-%!assert (size (repmat ({1}, [0, 1])), [0, 1]);
-%!assert (size (repmat ({1}, [0, 5])), [0, 5]);
+%!assert (size (repmat ({1}, [1, 0])), [1, 0])
+%!assert (size (repmat ({1}, [5, 0])), [5, 0])
+%!assert (size (repmat ({1}, [0, 1])), [0, 1])
+%!assert (size (repmat ({1}, [0, 5])), [0, 5])
 
+%!error (size (repmat (".", -1, -1)))
+
--- a/scripts/general/rot90.m
+++ b/scripts/general/rot90.m
@@ -87,16 +87,17 @@
 %! x3 = [4, 3; 2, 1];
 %! x4 = [3, 1; 4, 2];
 %!
-%! assert(rot90 (x1), x2);
-%! assert(rot90 (x1, 2), x3);
-%! assert(rot90 (x1, 3), x4);
-%! assert(rot90 (x1, 4), x1);
-%! assert(rot90 (x1, 5), x2);
-%! assert(rot90 (x1, -1), x4);
+%! assert (rot90 (x1), x2);
+%! assert (rot90 (x1, 2), x3);
+%! assert (rot90 (x1, 3), x4);
+%! assert (rot90 (x1, 4), x1);
+%! assert (rot90 (x1, 5), x2);
+%! assert (rot90 (x1, -1), x4);
 
 %% Test input validation
-%!error rot90 ();
-%!error rot90 (1, 2, 3);
-%!error rot90 (1, ones(2));
-%!error rot90 (1, 1.5);
-%!error rot90 (1, 1+i);
+%!error rot90 ()
+%!error rot90 (1, 2, 3)
+%!error rot90 (1, ones (2))
+%!error rot90 (1, 1.5)
+%!error rot90 (1, 1+i)
+
--- a/scripts/general/rotdim.m
+++ b/scripts/general/rotdim.m
@@ -60,8 +60,8 @@
     print_usage ();
   endif
 
-  if (nargin > 1 && ! isempty(n))
-    if (!isscalar (n) || !isreal(n) || fix (n) != n)
+  if (nargin > 1 && ! isempty (n))
+    if (!isscalar (n) || !isreal (n) || fix (n) != n)
       error ("rotdim: N must be a scalar integer");
     endif
   else
@@ -124,35 +124,37 @@
 
 endfunction
 
-%!error rotdim ();
-%!error rotdim (1, 2, 3, 4);
 
 %!shared r, rr
-%! r = [1,2,3]; rr = [3,2,1];
-%!assert (rotdim (r, 0), r);
-%!assert (rotdim (r, 1), rr');
-%!assert (rotdim (r, 2), rr);
-%!assert (rotdim (r, 3), r');
-%!assert (rotdim (r, 3), rotdim (r, -1));
-%!assert (rotdim (r, 1), rotdim (r));
+%! r = [1,2,3];  rr = [3,2,1];
+%!assert (rotdim (r, 0), r)
+%!assert (rotdim (r, 1), rr')
+%!assert (rotdim (r, 2), rr)
+%!assert (rotdim (r, 3), r')
+%!assert (rotdim (r, 3), rotdim (r, -1))
+%!assert (rotdim (r, 1), rotdim (r))
 
 %!shared c, cr
-%! c = [1;2;3]; cr = [3;2;1];
-%!assert (rotdim (c, 0), c);
-%!assert (rotdim (c, 1), c');
-%!assert (rotdim (c, 2), cr);
-%!assert (rotdim (c, 3), cr');
-%!assert (rotdim (c, 3), rotdim (c, -1));
-%!assert (rotdim (c, 1), rotdim (c));
+%! c = [1;2;3];  cr = [3;2;1];
+%!assert (rotdim (c, 0), c)
+%!assert (rotdim (c, 1), c')
+%!assert (rotdim (c, 2), cr)
+%!assert (rotdim (c, 3), cr')
+%!assert (rotdim (c, 3), rotdim (c, -1))
+%!assert (rotdim (c, 1), rotdim (c))
 
 %!shared m
 %! m = [1,2;3,4];
-%!assert (rotdim (m, 0), m);
-%!assert (rotdim (m, 1), [2,4;1,3]);
-%!assert (rotdim (m, 2), [4,3;2,1]);
-%!assert (rotdim (m, 3), [3,1;4,2]);
-%!assert (rotdim (m, 3), rotdim (m, -1));
-%!assert (rotdim (m, 1), rotdim (m));
+%!assert (rotdim (m, 0), m)
+%!assert (rotdim (m, 1), [2,4;1,3])
+%!assert (rotdim (m, 2), [4,3;2,1])
+%!assert (rotdim (m, 3), [3,1;4,2])
+%!assert (rotdim (m, 3), rotdim (m, -1))
+%!assert (rotdim (m, 1), rotdim (m))
 
 ## FIXME -- we need tests for multidimensional arrays and different
 ## values of PLANE.
+
+%!error rotdim ()
+%!error rotdim (1, 2, 3, 4)
+
--- a/scripts/general/saveobj.m
+++ b/scripts/general/saveobj.m
@@ -40,5 +40,5 @@
 ## @end deftypefn
 
 function b = saveobj (a)
-  error ("saveobj: not defined for class \"%s\"", class(a));
+  error ('saveobj: not defined for class "%s"', class (a));
 endfunction
--- a/scripts/general/shift.m
+++ b/scripts/general/shift.m
@@ -80,19 +80,19 @@
 %! r = [a, b, c];
 %! m = [a; b; c];
 %!
-%! assert(shift (r, 0), r);
-%! assert(shift (r, 3), [c, a, b]);
-%! assert(shift (r, -6), [c, a, b]);
-%! assert(shift (r, -3), [b, c, a]);
-%! assert(shift (m, 1), [c; a; b]);
-%! assert(shift (m, -2), [c; a; b]);
+%! assert (shift (r, 0), r);
+%! assert (shift (r, 3), [c, a, b]);
+%! assert (shift (r, -6), [c, a, b]);
+%! assert (shift (r, -3), [b, c, a]);
+%! assert (shift (m, 1), [c; a; b]);
+%! assert (shift (m, -2), [c; a; b]);
 
 %% Test input validation
 %!error shift ()
 %!error shift (1, 2, 3, 4)
 %!error shift ([], 1)
-%!error shift (ones(2), ones(2))
-%!error shift (ones(2), 1.5)
+%!error shift (ones (2), ones (2))
+%!error shift (ones (2), 1.5)
 %!error shift (1, 1, 1.5)
 %!error shift (1, 1, 0)
 %!error shift (1, 1, 3)
--- a/scripts/general/shiftdim.m
+++ b/scripts/general/shiftdim.m
@@ -90,11 +90,12 @@
 %! assert (ns, 2);
 %! assert (shiftdim (y, -2), x);
 %! assert (size (shiftdim (x, 2)), [4 2]);
-%!assert (size (shiftdim (rand (0, 1, 2))), [0 1 2]);
+
+%!assert (size (shiftdim (rand (0, 1, 2))), [0 1 2])
 
 %% Test input validation
-%!error(shiftdim ());
-%!error(shiftdim (1,2,3));
-%!error(shiftdim (1, ones (2)));
-%!error(shiftdim (1, 1.5));
+%!error (shiftdim ())
+%!error (shiftdim (1,2,3))
+%!error (shiftdim (1, ones (2)))
+%!error (shiftdim (1, 1.5))
 
--- a/scripts/general/sph2cart.m
+++ b/scripts/general/sph2cart.m
@@ -71,6 +71,7 @@
 
 endfunction
 
+
 %!test
 %! t = [0, 0, 0];
 %! p = [0, 0, 0];
@@ -110,5 +111,5 @@
 %!test
 %! S = [ 0, 0, 1; 0.5*pi, 0, 1; pi, 0, 1];
 %! C = [ 1, 0, 0; 0, 1, 0; -1, 0, 0];
-%! assert (sph2cart(S), C, eps);
+%! assert (sph2cart (S), C, eps);
 
--- a/scripts/general/structfun.m
+++ b/scripts/general/structfun.m
@@ -133,14 +133,15 @@
 %! d(1:2, 1, 1) = [1; 16];
 %! d(1:2, 1, 2) = [4; 25];
 %! d(1:2, 1, 3) = [9; 36];
-%! [aa, bb] = structfun(@__twoouts, s);
-%! assert(aa, c);
-%! assert(bb, d);
+%! [aa, bb] = structfun (@__twoouts, s);
+%! assert (aa, c);
+%! assert (bb, d);
 
 %!test
 %! s = struct ("a", {1, 2, 3}, "b", {4, 5, 6});
 %! c = struct ("a", {2, 4, 6}, "b", {8, 10, 12});
 %! d = struct ("a", {1, 4, 9}, "b", {16, 25, 36});
-%! [aa, bb] = structfun(@__twoouts, s, "UniformOutput", false);
-%! assert(aa, c);
-%! assert(bb, d);
+%! [aa, bb] = structfun (@__twoouts, s, "UniformOutput", false);
+%! assert (aa, c);
+%! assert (bb, d);
+
--- a/scripts/general/subsindex.m
+++ b/scripts/general/subsindex.m
@@ -60,6 +60,6 @@
 ## @end deftypefn
 
 function idx = subsindex (a)
-  error ("subsindex: not defined for class \"%s\"", class(a));
+  error ("subsindex: not defined for class \"%s\"", class (a));
 endfunction
 
--- a/scripts/general/trapz.m
+++ b/scripts/general/trapz.m
@@ -123,16 +123,16 @@
 endfunction
 
 
-%!assert (trapz(1:5), 12)
-%!assert (trapz(0:0.5:2,1:5), 6)
-%!assert (trapz([1:5;1:5].',1), [12,12])
-%!assert (trapz([1:5;1:5],2), [12;12])
-%!assert (trapz(repmat(reshape(1:5,1,1,5),2,2), 3), [12 12; 12 12])
-%!assert (trapz([0:0.5:2;0:0.5:2].',[1:5;1:5].',1), [6, 6])
-%!assert (trapz([0:0.5:2;0:0.5:2],[1:5;1:5],2), [6; 6])
-%!assert (trapz(repmat(reshape([0:0.5:2],1,1,5),2,2), ...
-%!              repmat(reshape(1:5,1,1,5),2,2), 3), [6 6; 6 6])
-%!assert (trapz(0:0.5:2,[(1:5)',(1:5)']), [6, 6])
-%!assert (trapz(0:0.5:2,[(1:5);(1:5)],2), [6; 6])
-%!assert (trapz(0:0.5:2,repmat(reshape(1:5,1,1,5),2,2),3), [6 6; 6 6])
+%!assert (trapz (1:5), 12)
+%!assert (trapz (0:0.5:2,1:5), 6)
+%!assert (trapz ([1:5;1:5].',1), [12,12])
+%!assert (trapz ([1:5;1:5],2), [12;12])
+%!assert (trapz (repmat (reshape (1:5,1,1,5),2,2), 3), [12 12; 12 12])
+%!assert (trapz ([0:0.5:2;0:0.5:2].',[1:5;1:5].',1), [6, 6])
+%!assert (trapz ([0:0.5:2;0:0.5:2],[1:5;1:5],2), [6; 6])
+%!assert (trapz (repmat (reshape ([0:0.5:2],1,1,5),2,2), ...
+%!               repmat (reshape (1:5,1,1,5),2,2), 3), [6 6; 6 6])
+%!assert (trapz (0:0.5:2,[(1:5)',(1:5)']), [6, 6])
+%!assert (trapz (0:0.5:2,[(1:5);(1:5)],2), [6; 6])
+%!assert (trapz (0:0.5:2,repmat (reshape (1:5,1,1,5),2,2),3), [6 6; 6 6])
 
--- a/scripts/general/triplequad.m
+++ b/scripts/general/triplequad.m
@@ -69,17 +69,17 @@
 endfunction
 
 function q = __triplequad_inner__ (y, z, f, xa, xb, tol, quadf, varargin)
-  q = zeros (size(y));
+  q = zeros (size (y));
   for i = 1 : length (y)
     q(i) = feval (quadf, @(x) f (x, y(i), z, varargin{:}), xa, xb, tol);
   endfor
 endfunction
 
 
-%!assert (triplequad (@(x,y,z) exp(-x.^2 - y.^2 - z.^2) , -1, 1, -1, 1, -1, 1, [],  @quadcc), pi ^ (3/2) * erf(1).^3, 1e-6)
+%!assert (triplequad (@(x,y,z) exp (-x.^2 - y.^2 - z.^2) , -1, 1, -1, 1, -1, 1, [], @quadcc), pi^(3/2) * erf (1).^3, 1e-6)
 
 %% These tests are too expensive to run normally (~30 sec each).  Disable them
-#%!assert (triplequad (@(x,y,z) exp(-x.^2 - y.^2 - z.^2) , -1, 1, -1, 1, -1, 1, [],  @quadgk), pi ^ (3/2) * erf(1).^3, 1e-6)
-#%!#assert (triplequad (@(x,y,z) exp(-x.^2 - y.^2 - z.^2) , -1, 1, -1, 1, -1, 1, [],  @quadl), pi ^ (3/2) * erf(1).^3, 1e-6)
-#%!#assert (triplequad (@(x,y,z) exp(-x.^2 - y.^2 - z.^2) , -1, 1, -1, 1, -1, 1, [],  @quadv), pi ^ (3/2) * erf(1).^3, 1e-6)
+#%!assert (triplequad (@(x,y,z) exp (-x.^2 - y.^2 - z.^2) , -1, 1, -1, 1, -1, 1, [], @quadgk), pi^(3/2) * erf (1).^3, 1e-6)
+#%!#assert (triplequad (@(x,y,z) exp (-x.^2 - y.^2 - z.^2) , -1, 1, -1, 1, -1, 1, [], @quadl), pi^(3/2) * erf (1).^3, 1e-6)
+#%!#assert (triplequad (@(x,y,z) exp (-x.^2 - y.^2 - z.^2) , -1, 1, -1, 1, -1, 1, [], @quadv), pi^(3/2) * erf (1).^3, 1e-6)
 
--- a/scripts/geometry/convhull.m
+++ b/scripts/geometry/convhull.m
@@ -20,7 +20,7 @@
 ## @deftypefn  {Function File} {@var{H} =} convhull (@var{x}, @var{y})
 ## @deftypefnx {Function File} {@var{H} =} convhull (@var{x}, @var{y}, @var{options})
 ## Compute the convex hull of the set of points defined by the
-## vectors @var{x} and @var{y}.  The hull @var{H} is an index vector into
+## arrays @var{x} and @var{y}.  The hull @var{H} is an index vector into
 ## the set of points and specifies which points form the enclosing hull.
 ##
 ## An optional third argument, which must be a string or cell array of strings,
@@ -45,17 +45,20 @@
     print_usage ();
   endif
 
-  if (! (isvector (x) && isvector (y) && length (x) == length (y))
-      && ! size_equal (x, y))
-    error ("convhull: X and Y must be the same size");
+  ## convhulln expects column vectors
+  x = x(:);
+  y = y(:);
+
+  if (length (x) != length (y))
+    error ("convhull: X and Y must have the same size");
   elseif (nargin == 3 && ! (ischar (options) || iscellstr (options)))
     error ("convhull: OPTIONS must be a string or cell array of strings");
   endif
 
   if (nargin == 2)
-    i = convhulln ([x(:), y(:)]);
+    i = convhulln ([x, y]);
   else
-    i = convhulln ([x(:), y(:)], options);
+    i = convhulln ([x, y], options);
   endif
 
   n = rows (i);
@@ -85,6 +88,7 @@
 
 
 %!demo
+%! clf;
 %! x = -3:0.05:3;
 %! y = abs (sin (x));
 %! k = convhull (x, y);
@@ -94,7 +98,7 @@
 %!testif HAVE_QHULL
 %! x = -3:0.5:3;
 %! y = abs (sin (x));
-%! assert (convhull (x, y), [1;7;13;12;11;10;4;3;2;1])
+%! assert (convhull (x, y), [1;7;13;12;11;10;4;3;2;1]);
 
 %% FIXME: Need input validation tests
 
--- a/scripts/geometry/delaunay.m
+++ b/scripts/geometry/delaunay.m
@@ -56,7 +56,7 @@
 ## plot (VX, VY, "b", x, y, "r*");
 ## @end group
 ## @end example
-## @seealso{delaunay3, delaunayn, convhull, voronoi}
+## @seealso{delaunay3, delaunayn, convhull, voronoi, triplot, trimesh, trisurf}
 ## @end deftypefn
 
 ## Author: Kai Habel <kai.habel@gmx.de>
@@ -102,8 +102,9 @@
 %! T = delaunay (x,y);
 %! VX = [ x(T(:,1)); x(T(:,2)); x(T(:,3)); x(T(:,1)) ];
 %! VY = [ y(T(:,1)); y(T(:,2)); y(T(:,3)); y(T(:,1)) ];
+%! clf;
+%! plot (VX,VY,"b", x,y,"r*");
 %! axis ([0,1,0,1]);
-%! plot (VX,VY,"b", x,y,"r*");
 
 %!testif HAVE_QHULL
 %! x = [-1, 0, 1, 0];
--- a/scripts/geometry/delaunay3.m
+++ b/scripts/geometry/delaunay3.m
@@ -42,7 +42,7 @@
 ## To append user options to the defaults it is necessary to repeat the 
 ## default arguments in @var{options}.  Use a null string to pass no arguments.
 ##
-## @seealso{delaunay, delaunayn, convhull, voronoi}
+## @seealso{delaunay, delaunayn, convhull, voronoi, tetramesh}
 ## @end deftypefn
 
 ## Author: Kai Habel <kai.habel@gmx.de>
@@ -54,7 +54,7 @@
   endif
 
   if (! (isvector (x) && isvector (y) && isvector (z)
-         && length (x) == length (y) && length(x) == length (z)))
+         && length (x) == length (y) && length (x) == length (z)))
     error ("delaunay: X, Y, and Z must be the same size");
   elseif (nargin == 4 && ! (ischar (options) || iscellstr (options)))
     error ("delaunay3: OPTIONS must be a string or cell array of strings");
--- a/scripts/geometry/delaunayn.m
+++ b/scripts/geometry/delaunayn.m
@@ -47,7 +47,7 @@
 ## To append user options to the defaults it is necessary to repeat the 
 ## default arguments in @var{options}.  Use a null string to pass no arguments.
 ##
-## @seealso{delaunay, delaunay3, convhulln, voronoin}
+## @seealso{delaunay, delaunay3, convhulln, voronoin, trimesh, tetramesh}
 ## @end deftypefn
 
 function T = delaunayn (pts, varargin)
--- a/scripts/geometry/dsearch.m
+++ b/scripts/geometry/dsearch.m
@@ -32,9 +32,11 @@
   idx = __dsearchn__ ([x(:), y(:)], [xi(:), yi(:)]);
 endfunction
 
+
 %!shared x, y, tri
 %! x = [-1;-1;1];
 %! y = [-1;1;-1];
 %! tri = [1,2,3];
-%!assert (dsearch(x,y,tri,1,1/3), 3);
-%!assert (dsearch(x,y,tri,1/3,1), 2);
+%!assert (dsearch (x,y,tri,1,1/3), 3)
+%!assert (dsearch (x,y,tri,1/3,1), 2)
+
--- a/scripts/geometry/dsearchn.m
+++ b/scripts/geometry/dsearchn.m
@@ -46,12 +46,14 @@
   endif
 endfunction
 
+
 %!shared x, tri
 %! x = [-1,-1;-1,1;1,-1];
 %! tri = [1,2,3];
-%!assert (dsearchn(x,tri,[1,1/3]), 3);
-%!assert (dsearchn(x,tri,[1,1/3],NaN), NaN);
-%!assert (dsearchn(x,tri,[1,1/3],NA), NA);
-%!assert (dsearchn(x,tri,[1/3,1]), 2);
-%!assert (dsearchn(x,tri,[1/3,1],NaN), NaN);
-%!assert (dsearchn(x,tri,[1/3,1],NA), NA);
+%!assert (dsearchn (x,tri,[1,1/3]), 3)
+%!assert (dsearchn (x,tri,[1,1/3],NaN), NaN)
+%!assert (dsearchn (x,tri,[1,1/3],NA), NA)
+%!assert (dsearchn (x,tri,[1/3,1]), 2)
+%!assert (dsearchn (x,tri,[1/3,1],NaN), NaN)
+%!assert (dsearchn (x,tri,[1/3,1],NA), NA)
+
--- a/scripts/geometry/griddata.m
+++ b/scripts/geometry/griddata.m
@@ -17,8 +17,9 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {@var{zi} =} griddata (@var{x}, @var{y}, @var{z}, @var{xi}, @var{yi}, @var{method})
-## @deftypefnx {Function File} {[@var{xi}, @var{yi}, @var{zi}] =} griddata (@var{x}, @var{y}, @var{z}, @var{xi}, @var{yi}, @var{method})
+## @deftypefn  {Function File} {@var{zi} =} griddata (@var{x}, @var{y}, @var{z}, @var{xi}, @var{yi})
+## @deftypefnx {Function File} {@var{zi} =} griddata (@var{x}, @var{y}, @var{z}, @var{xi}, @var{yi}, @var{method})
+## @deftypefnx {Function File} {[@var{xi}, @var{yi}, @var{zi}] =} griddata (@dots{})
 ##
 ## Generate a regular mesh from irregular data using interpolation.
 ## The function is defined by @code{@var{z} = f (@var{x}, @var{y})}.
@@ -30,7 +31,7 @@
 ##
 ## The interpolation method can be @code{"nearest"}, @code{"cubic"} or
 ## @code{"linear"}.  If method is omitted it defaults to @code{"linear"}.
-## @seealso{delaunay}
+## @seealso{griddata3, griddatan, delaunay}
 ## @end deftypefn
 
 ## Author:      Kai Habel <kai.habel@gmx.de>
@@ -38,11 +39,8 @@
 ##              xi and yi are not "meshgridded" if both are vectors
 ##              of the same size (for compatibility)
 
-function [rx, ry, rz] = griddata (x, y, z, xi, yi, method)
+function [rx, ry, rz] = griddata (x, y, z, xi, yi, method = "linear")
 
-  if (nargin == 5)
-    method = "linear";
-  endif
   if (nargin < 5 || nargin > 7)
     print_usage ();
   endif
@@ -51,27 +49,32 @@
     method = tolower (method);
   endif
 
+  ## Meshgrid if x and y are vectors but z is matrix
   if (isvector (x) && isvector (y) && all ([numel(y), numel(x)] == size (z)))
     [x, y] = meshgrid (x, y);
-  elseif (! all (size (x) == size (y) & size (x) == size (z)))
-    if (isvector (z))
-      error ("griddata: X, Y, and Z, be vectors of same length");
-    else
-      error ("griddata: lengths of X, Y must match the columns and rows of Z");
+  endif
+    
+  if (isvector (x) && isvector (y) && isvector (z))
+    if (! isequal (length (x), length (y), length (z)))
+      error ("griddata: X, Y, and Z must be vectors of the same length");
     endif
+  elseif (! size_equal (x, y, z))
+    error ("griddata: lengths of X, Y must match the columns and rows of Z");
   endif
 
   ## Meshgrid xi and yi if they are a row and column vector.
   if (rows (xi) == 1 && columns (yi) == 1)
     [xi, yi] = meshgrid (xi, yi);
+  elseif (isvector (xi) && isvector (yi))
+    ## Otherwise, convert to column vectors
+    xi = xi(:);
+    yi = yi(:);
   endif
 
   if (! size_equal (xi, yi))
     error ("griddata: XI and YI must be vectors or matrices of same size");
   endif
 
-  [nr, nc] = size (xi);
-
   x = x(:);
   y = y(:);
   z = z(:);
@@ -138,40 +141,64 @@
   elseif (nargout == 0)
     mesh (xi, yi, zi);
   endif
+
 endfunction
 
-%!testif HAVE_QHULL
-%! [xx,yy]=meshgrid(linspace(-1,1,32));
-%! x = xx(:);
-%! x = x + 10 * (2 * round(rand(size(x))) - 1) * eps;
-%! y = yy(:);
-%! y = y + 10 * (2 * round(rand(size(y))) - 1) * eps;
-%! z = sin(2*(x.^2+y.^2));
-%! zz = griddata(x,y,z,xx,yy,'linear');
-%! zz2 = sin(2*(xx.^2+yy.^2));
-%! zz2(isnan(zz)) = NaN;
-%! assert (zz, zz2, 100 * eps)
+
+%!demo
+%! clf;
+%! colormap ("default");
+%! x = 2*rand (100,1) - 1;
+%! y = 2*rand (size (x)) - 1;
+%! z = sin (2*(x.^2 + y.^2));
+%! [xx,yy] = meshgrid (linspace (-1,1,32));
+%! griddata (x,y,z,xx,yy);
+%! title ("nonuniform grid sampled at 100 points");
+
+%!demo
+%! clf;
+%! colormap ("default");
+%! x = 2*rand (1000,1) - 1;
+%! y = 2*rand (size (x)) - 1;
+%! z = sin (2*(x.^2 + y.^2));
+%! [xx,yy] = meshgrid (linspace (-1,1,32));
+%! griddata (x,y,z,xx,yy);
+%! title ("nonuniform grid sampled at 1000 points");
 
 %!demo
-%! x=2*rand(100,1)-1;
-%! y=2*rand(size(x))-1;
-%! z=sin(2*(x.^2+y.^2));
-%! [xx,yy]=meshgrid(linspace(-1,1,32));
-%! griddata(x,y,z,xx,yy);
-%! title('nonuniform grid sampled at 100 points');
+%! clf;
+%! colormap ("default");
+%! x = 2*rand (1000,1) - 1;
+%! y = 2*rand (size (x)) - 1;
+%! z = sin (2*(x.^2 + y.^2));
+%! [xx,yy] = meshgrid (linspace (-1,1,32));
+%! griddata (x,y,z,xx,yy,"nearest");
+%! title ("nonuniform grid sampled at 1000 points with nearest neighbor");
 
-%!demo
-%! x=2*rand(1000,1)-1;
-%! y=2*rand(size(x))-1;
-%! z=sin(2*(x.^2+y.^2));
-%! [xx,yy]=meshgrid(linspace(-1,1,32));
-%! griddata(x,y,z,xx,yy);
-%! title('nonuniform grid sampled at 1000 points');
+%!testif HAVE_QHULL
+%! [xx,yy] = meshgrid (linspace (-1,1,32));
+%! x = xx(:);
+%! x = x + 10*(2*round (rand (size (x))) - 1) * eps;
+%! y = yy(:);
+%! y = y + 10*(2*round (rand (size (y))) - 1) * eps;
+%! z = sin (2*(x.^2 + y.^2));
+%! zz = griddata (x,y,z,xx,yy,"linear");
+%! zz2 = sin (2*(xx.^2 + yy.^2));
+%! zz2(isnan (zz)) = NaN;
+%! assert (zz, zz2, 100*eps);
 
-%!demo
-%! x=2*rand(1000,1)-1;
-%! y=2*rand(size(x))-1;
-%! z=sin(2*(x.^2+y.^2));
-%! [xx,yy]=meshgrid(linspace(-1,1,32));
-%! griddata(x,y,z,xx,yy,'nearest');
-%! title('nonuniform grid sampled at 1000 points with nearest neighbor');
+%% Test input validation
+%!error griddata ()
+%!error griddata (1)
+%!error griddata (1,2)
+%!error griddata (1,2,3)
+%!error griddata (1,2,3,4)
+%!error griddata (1,2,3,4,5,6,7)
+%!error <vectors of the same length> griddata (1:3, 1:3, 1:4, 1:3, 1:3)
+%!error <vectors of the same length> griddata (1:3, 1:4, 1:3, 1:3, 1:3)
+%!error <vectors of the same length> griddata (1:4, 1:3, 1:3, 1:3, 1:3)
+%!error <the columns and rows of Z> griddata (1:4, 1:3, ones (4,4), 1:3, 1:3)
+%!error <the columns and rows of Z> griddata (1:4, 1:3, ones (3,5), 1:3, 1:3)
+%!error <matrices of same size> griddata (1:3, 1:3, 1:3, 1:4, 1:3)
+%!error <matrices of same size> griddata (1:3, 1:3, 1:3, 1:3, 1:4)
+
--- a/scripts/geometry/griddata3.m
+++ b/scripts/geometry/griddata3.m
@@ -17,7 +17,9 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {@var{vi} =} griddata3 (@var{x}, @var{y}, @var{z}, @var{v}, @var{xi}, @var{yi}, @var{zi}, @var{method}, @var{options})
+## @deftypefn  {Function File} {@var{vi} =} griddata3 (@var{x}, @var{y}, @var{z}, @var{v}, @var{xi}, @var{yi}, @var{zi})
+## @deftypefnx {Function File} {@var{vi} =} griddata3 (@var{x}, @var{y}, @var{z}, @var{v}, @var{xi}, @var{yi}, @var{zi}, @var{method})
+## @deftypefnx {Function File} {@var{vi} =} griddata3 (@var{x}, @var{y}, @var{z}, @var{v}, @var{xi}, @var{yi}, @var{zi}, @var{method}, @var{options})
 ##
 ## Generate a regular mesh from irregular data using interpolation.
 ## The function is defined by @code{@var{v} = f (@var{x}, @var{y}, @var{z})}.
@@ -25,6 +27,11 @@
 ##
 ## The interpolation method can be @code{"nearest"} or @code{"linear"}.
 ## If method is omitted it defaults to @code{"linear"}.
+##
+## The optional argument @var{options} is passed directly to Qhull when
+## computing the Delaunay triangulation used for interpolation.  See
+## @code{delaunayn} for information on the defaults and how to pass different
+## values.
 ## @seealso{griddata, griddatan, delaunayn}
 ## @end deftypefn
 
@@ -36,19 +43,29 @@
     print_usage ();
   endif
 
-  if (!all (size (x) == size (y) & size (x) == size(z) & size(x) == size (v)))
-    error ("griddata3: X, Y, Z, and V must be vectors of same length");
+  if (isvector (x) && isvector (y) && isvector (z) && isvector (v))
+    if (! isequal (length (x), length (y), length (z), length (v)))
+      error ("griddata: X, Y, Z, and V must be vectors of the same length");
+    endif
+  elseif (! size_equal (x, y, z, v))
+    error ("griddata: X, Y, Z, and V must have equal sizes");
   endif
 
-  ## meshgrid xi, yi and zi if they are vectors unless they
-  ## are vectors of the same length
-  if (isvector (xi) && isvector (yi) && isvector (zi)
-      && (numel (xi) != numel (yi) || numel (xi) != numel (zi)))
-    [xi, yi, zi] = meshgrid (xi, yi, zi);
+  ## meshgrid xi, yi and zi if they are vectors unless
+  ## they are vectors of the same length.
+  if (isvector (xi) && isvector (yi) && isvector (zi))
+    if (! isequal (length (xi), length (yi), length (zi)))
+      [xi, yi, zi] = meshgrid (xi, yi, zi);
+    else
+      ## Otherwise, convert to column vectors
+      xi = xi(:);
+      yi = yi(:);
+      zi = zi(:);
+    endif
   endif
 
-  if (any (size(xi) != size(yi)) || any (size(xi) != size(zi)))
-    error ("griddata3: XI, YI and ZI must be vectors or matrices of same size");
+  if (! size_equal (xi, yi, zi))
+    error ("griddata3: XI, YI, and ZI must be vectors or matrices of the same size");
   endif
 
   vi = griddatan ([x(:), y(:), z(:)], v(:), [xi(:), yi(:), zi(:)], varargin{:});
@@ -66,7 +83,7 @@
 %! z = 2 * rand (1000, 1) - 1;
 %! v = x.^2 + y.^2 + z.^2;
 %! [xi, yi, zi] = meshgrid (-0.8:0.2:0.8);
-%! vi = griddata3 (x, y, z, v, xi, yi, zi, 'linear');
+%! vi = griddata3 (x, y, z, v, xi, yi, zi, "linear");
 %! vv = vi - xi.^2 - yi.^2 - zi.^2;
 %! assert (max (abs (vv(:))), 0, 0.1);
 
@@ -79,6 +96,7 @@
 %! z = 2 * rand (1000, 1) - 1;
 %! v = x.^2 + y.^2 + z.^2;
 %! [xi, yi, zi] = meshgrid (-0.8:0.2:0.8);
-%! vi = griddata3 (x, y, z, v, xi, yi, zi, 'nearest');
+%! vi = griddata3 (x, y, z, v, xi, yi, zi, "nearest");
 %! vv = vi - xi.^2 - yi.^2 - zi.^2;
 %! assert (max (abs (vv(:))), 0, 0.1)
+
--- a/scripts/geometry/griddatan.m
+++ b/scripts/geometry/griddatan.m
@@ -17,7 +17,9 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {@var{yi} =} griddatan (@var{x}, @var{y}, @var{xi}, @var{method}, @var{options})
+## @deftypefn  {Function File} {@var{yi} =} griddatan (@var{x}, @var{y}, @var{xi})
+## @deftypefnx {Function File} {@var{yi} =} griddatan (@var{x}, @var{y}, @var{xi}, @var{method})
+## @deftypefnx {Function File} {@var{yi} =} griddatan (@var{x}, @var{y}, @var{xi}, @var{method}, @var{options})
 ##
 ## Generate a regular mesh from irregular data using interpolation.
 ## The function is defined by @code{@var{y} = f (@var{x})}.
@@ -25,16 +27,18 @@
 ##
 ## The interpolation method can be @code{"nearest"} or @code{"linear"}.
 ## If method is omitted it defaults to @code{"linear"}.
-## @seealso{griddata, delaunayn}
+## 
+## The optional argument @var{options} is passed directly to Qhull when
+## computing the Delaunay triangulation used for interpolation.  See
+## @code{delaunayn} for information on the defaults and how to pass different
+## values.
+## @seealso{griddata, griddata3, delaunayn}
 ## @end deftypefn
 
 ## Author: David Bateman <dbateman@free.fr>
 
-function yi = griddatan (x, y, xi, method, varargin)
+function yi = griddatan (x, y, xi, method = "linear", varargin)
 
-  if (nargin == 3)
-    method = "linear";
-  endif
   if (nargin < 3)
     print_usage ();
   endif
@@ -46,13 +50,12 @@
   [m, n] = size (x);
   [mi, ni] = size (xi);
 
-  if (n != ni || size (y, 1) != m || size (y, 2) != 1)
+  if (n != ni || rows (y) != m || columns (y) != 1)
     error ("griddatan: dimensional mismatch");
   endif
 
   ## triangulate data
-  ## tri = delaunayn(x, varargin{:});
-  tri = delaunayn (x);
+  tri = delaunayn (x, varargin{:});
 
   yi = NaN (mi, 1);
 
@@ -85,22 +88,24 @@
 
 endfunction
 
-%!testif HAVE_QHULL
-%! [xx,yy] = meshgrid(linspace(-1,1,32));
-%! xi = [xx(:), yy(:)];
-%! x = (2 * rand(100,2) - 1);
-%! x = [x;1,1;1,-1;-1,-1;-1,1];
-%! y = sin(2*(sum(x.^2,2)));
-%! zz = griddatan(x,y,xi,'linear');
-%! zz2 = griddata(x(:,1),x(:,2),y,xi(:,1),xi(:,2),'linear');
-%! assert (zz, zz2, 1e-10)
 
 %!testif HAVE_QHULL
-%! [xx,yy] = meshgrid(linspace(-1,1,32));
+%! [xx,yy] = meshgrid (linspace (-1,1,32));
 %! xi = [xx(:), yy(:)];
-%! x = (2 * rand(100,2) - 1);
+%! x = 2*rand (100,2) - 1;
 %! x = [x;1,1;1,-1;-1,-1;-1,1];
-%! y = sin(2*(sum(x.^2,2)));
-%! zz = griddatan(x,y,xi,'nearest');
-%! zz2 = griddata(x(:,1),x(:,2),y,xi(:,1),xi(:,2),'nearest');
-%! assert (zz, zz2, 1e-10)
+%! y = sin (2 * sum (x.^2,2));
+%! zz = griddatan (x,y,xi,"linear");
+%! zz2 = griddata (x(:,1),x(:,2),y,xi(:,1),xi(:,2),"linear");
+%! assert (zz, zz2, 1e-10);
+
+%!testif HAVE_QHULL
+%! [xx,yy] = meshgrid (linspace (-1,1,32));
+%! xi = [xx(:), yy(:)];
+%! x = 2*rand (100,2) - 1;
+%! x = [x;1,1;1,-1;-1,-1;-1,1];
+%! y = sin (2*sum (x.^2,2));
+%! zz = griddatan (x,y,xi,"nearest");
+%! zz2 = griddata (x(:,1),x(:,2),y,xi(:,1),xi(:,2),"nearest");
+%! assert (zz, zz2, 1e-10);
+
--- a/scripts/geometry/inpolygon.m
+++ b/scripts/geometry/inpolygon.m
@@ -54,9 +54,9 @@
   npol = length (xv);
   do_boundary = (nargout >= 2);
 
-  in = zeros (size(x), "logical");
+  in = zeros (size (x), "logical");
   if (do_boundary)
-    on = zeros (size(x), "logical");
+    on = zeros (size (x), "logical");
   endif
 
   j = npol;
@@ -84,60 +84,64 @@
 
 endfunction
 
-%!demo
-%!  xv=[ 0.05840, 0.48375, 0.69356, 1.47478, 1.32158, \
-%!       1.94545, 2.16477, 1.87639, 1.18218, 0.27615, \
-%!       0.05840 ];
-%!  yv=[ 0.60628, 0.04728, 0.50000, 0.50000, 0.02015, \
-%!       0.18161, 0.78850, 1.13589, 1.33781, 1.04650, \
-%!       0.60628 ];
-%! xa=[0:0.1:2.3];
-%! ya=[0:0.1:1.4];
-%! [x,y]=meshgrid(xa,ya);
-%! [in,on]=inpolygon(x,y,xv,yv);
-%!
-%! inside=in & !on;
-%! plot(xv,yv)
-%! hold on
-%! plot(x(inside),y(inside),"@g")
-%! plot(x(~in),y(~in),"@m")
-%! plot(x(on),y(on),"@b")
-%! hold off
-%! disp("Green points are inside polygon, magenta are outside,");
-%! disp("and blue are on boundary.");
 
 %!demo
-%!  xv=[ 0.05840, 0.48375, 0.69356, 1.47478, 1.32158, \
-%!       1.94545, 2.16477, 1.87639, 1.18218, 0.27615, \
-%!       0.05840, 0.73295, 1.28913, 1.74221, 1.16023, \
-%!       0.73295, 0.05840 ];
-%!  yv=[ 0.60628, 0.04728, 0.50000, 0.50000, 0.02015, \
-%!       0.18161, 0.78850, 1.13589, 1.33781, 1.04650, \
-%!       0.60628, 0.82096, 0.67155, 0.96114, 1.14833, \
-%!       0.82096, 0.60628];
-%! xa=[0:0.1:2.3];
-%! ya=[0:0.1:1.4];
-%! [x,y]=meshgrid(xa,ya);
-%! [in,on]=inpolygon(x,y,xv,yv);
+%! xv = [ 0.05840, 0.48375, 0.69356, 1.47478, 1.32158, ...
+%!        1.94545, 2.16477, 1.87639, 1.18218, 0.27615, ...
+%!        0.05840 ];
+%! yv = [ 0.60628, 0.04728, 0.50000, 0.50000, 0.02015, ...
+%!        0.18161, 0.78850, 1.13589, 1.33781, 1.04650, ...
+%!        0.60628 ];
+%! xa = [0:0.1:2.3];
+%! ya = [0:0.1:1.4];
+%! [x,y] = meshgrid (xa, ya);
+%! [in,on] = inpolygon (x, y, xv, yv);
+%! inside = in & !on;
 %!
-%! inside=in & ~ on;
-%! plot(xv,yv)
-%! hold on
-%! plot(x(inside),y(inside),"@g")
-%! plot(x(~in),y(~in),"@m")
-%! plot(x(on),y(on),"@b")
-%! hold off
-%! disp("Green points are inside polygon, magenta are outside,");
-%! disp("and blue are on boundary.");
+%! clf;
+%! plot (xv, yv);
+%! hold on;
+%! plot (x(inside), y(inside), "@g")
+%! plot (x(!in), y(!in), "@m");
+%! plot (x(on), y(on), "@b");
+%! hold off;
+%! disp ("Green points are inside polygon, magenta are outside,");
+%! disp ("and blue are on boundary.");
 
-%!error inpolygon ();
-%!error inpolygon (1, 2);
-%!error inpolygon (1, 2, 3);
-
-%!error inpolygon (1, [1,2], [3, 4], [5, 6]);
-%!error inpolygon ([1,2], [3, 4], [5, 6], 1);
+%!demo
+%!  xv = [ 0.05840, 0.48375, 0.69356, 1.47478, 1.32158, ...
+%!         1.94545, 2.16477, 1.87639, 1.18218, 0.27615, ...
+%!         0.05840, 0.73295, 1.28913, 1.74221, 1.16023, ...
+%!         0.73295, 0.05840 ];
+%!  yv = [ 0.60628, 0.04728, 0.50000, 0.50000, 0.02015, ...
+%!         0.18161, 0.78850, 1.13589, 1.33781, 1.04650, ...
+%!         0.60628, 0.82096, 0.67155, 0.96114, 1.14833, ...
+%!         0.82096, 0.60628];
+%! xa = [0:0.1:2.3];
+%! ya = [0:0.1:1.4];
+%! [x,y] = meshgrid (xa, ya);
+%! [in,on] = inpolygon (x, y, xv, yv);
+%! inside = in & !on;
+%!
+%! clf;
+%! plot (xv, yv);
+%! hold on;
+%! plot (x(inside), y(inside), "@g");
+%! plot (x(!in), y(!in), "@m");
+%! plot (x(on), y(on), "@b");
+%! hold off;
+%! disp ("Green points are inside polygon, magenta are outside,");
+%! disp ("and blue are on boundary.");
 
 %!test
 %! [in, on] = inpolygon ([1, 0], [1, 0], [-1, -1, 1, 1], [-1, 1, 1, -1]);
 %! assert (in, [false, true]);
 %! assert (on, [true, false]);
+
+%% Test input validation
+%!error inpolygon ()
+%!error inpolygon (1, 2)
+%!error inpolygon (1, 2, 3)
+%!error inpolygon (1, [1,2], [3, 4], [5, 6])
+%!error inpolygon ([1,2], [3, 4], [5, 6], 1)
+
--- a/scripts/geometry/rectint.m
+++ b/scripts/geometry/rectint.m
@@ -43,7 +43,7 @@
     error ("rectint: A must have 4 columns");
   elseif (columns (b) != 4)
     error ("rectint: B must have 4 columns");
-  elseif any ([a(:,3:4);b(:,3:4)](:) < 0)
+  elseif (any ([a(:,3:4);b(:,3:4)](:) < 0))
     error ("rectint: all widths and heights must be > 0");
   endif
 
@@ -105,27 +105,28 @@
 
   endfor
 
-  if swapinputs
+  if (swapinputs)
     area = area';
   endif
 
 endfunction
 
-## Tests
+
 ## Exactly overlapping
-%!assert(rectint([0 0 1 1], [0 0 1 1]), 1)
+%!assert (rectint ([0 0 1 1], [0 0 1 1]), 1)
 ## rect2 completely enclosed by rect1
-%!assert(rectint([-1 -1 3 3], [0 0 1 1]), 1)
+%!assert (rectint ([-1 -1 3 3], [0 0 1 1]), 1)
 ## rect1 completely enclosed by rect2
-%!assert(rectint([0 0 1 1], [-1 -1 3 3]), 1)
+%!assert (rectint ([0 0 1 1], [-1 -1 3 3]), 1)
 ## rect1 right and top in rect2
-%!assert(rectint([-1 -1 1.5 1.5], [0 0 1 1]), 0.25)
+%!assert (rectint ([-1 -1 1.5 1.5], [0 0 1 1]), 0.25)
 ## rect2 right and top in rect1
-%!assert(rectint([0 0 1 1], [-1 -1 1.5 1.5]), 0.25)
+%!assert (rectint ([0 0 1 1], [-1 -1 1.5 1.5]), 0.25)
 ## no overlap - shared corner
-%!assert(rectint([0 0 1 1], [1 1 2 2]), 0)
+%!assert (rectint ([0 0 1 1], [1 1 2 2]), 0)
 ## no overlap - shared edge
-%!assert(rectint([0 0 1 1], [0 1 2 2]), 0)
+%!assert (rectint ([0 0 1 1], [0 1 2 2]), 0)
 ## Correct orientation of output
-%!assert(rectint([0 0 1 1;0.5 0.5 1 1;-1 -1 2 2], [1 1 2 2]), [0;0.25;0])
-%!assert(rectint([1 1 2 2], [0 0 1 1;0.5 0.5 1 1;-1 -1 2 2]), [0 0.25 0])
+%!assert (rectint ([0 0 1 1;0.5 0.5 1 1;-1 -1 2 2], [1 1 2 2]), [0;0.25;0])
+%!assert (rectint ([1 1 2 2], [0 0 1 1;0.5 0.5 1 1;-1 -1 2 2]), [0 0.25 0])
+
--- a/scripts/geometry/tsearchn.m
+++ b/scripts/geometry/tsearchn.m
@@ -31,9 +31,9 @@
     print_usage ();
   endif
 
-  nt = size (t, 1);
+  nt = rows (t);
   [m, n] = size (x);
-  mi = size (xi, 1);
+  mi = rows (xi);
   idx = NaN (mi, 1);
   p = NaN (mi, n + 1);
 
@@ -44,8 +44,8 @@
     b = cart2bary (x (t (i, :), :), xi(ni,:));
 
     ## Our points xi are in the current triangle if
-    ## (all(b >= 0) && all (b <= 1)). However as we impose that
-    ## sum(b,2) == 1 we only need to test all(b>=0). Note need to add
+    ## (all (b >= 0) && all (b <= 1)). However as we impose that
+    ## sum (b,2) == 1 we only need to test all(b>=0). Note need to add
     ## a small margin for rounding errors
     intri = all (b >= -1e-12, 2);
     idx(ni(intri)) = i;
@@ -69,39 +69,41 @@
   ##
   ## and therefore we can write the above as
   ##
-  ## P - T(end, :) = Beta(1:end-1) * (T(1:end-1,:) - ones(N,1) * T(end,:))
+  ## P - T(end, :) = Beta(1:end-1) * (T(1:end-1,:) - ones (N,1) * T(end,:))
   ##
   ## and then we can solve for Beta as
   ##
-  ## Beta(1:end-1) = (P - T(end,:)) / (T(1:end-1,:) - ones(N,1) * T(end,:))
-  ## Beta(end) = sum(Beta)
+  ## Beta(1:end-1) = (P - T(end,:)) / (T(1:end-1,:) - ones (N,1) * T(end,:))
+  ## Beta(end) = sum (Beta)
   ##
   ## Note below is generalize for multiple values of P, one per row.
   [M, N] = size (P);
-  Beta = (P - ones (M,1) * T(end,:)) / (T(1:end-1,:) - ones(N,1) * T(end,:));
-  Beta (:,end+1) = 1 - sum(Beta, 2);
+  Beta = (P - ones (M,1) * T(end,:)) / (T(1:end-1,:) - ones (N,1) * T(end,:));
+  Beta (:,end+1) = 1 - sum (Beta, 2);
 endfunction
 
+
 %!shared x, tri
 %! x = [-1,-1;-1,1;1,-1];
 %! tri = [1, 2, 3];
 %!test
 %! [idx, p] = tsearchn (x,tri,[-1,-1]);
-%! assert (idx, 1)
-%! assert (p, [1,0,0], 1e-12)
+%! assert (idx, 1);
+%! assert (p, [1,0,0], 1e-12);
 %!test
 %! [idx, p] = tsearchn (x,tri,[-1,1]);
-%! assert (idx, 1)
-%! assert (p, [0,1,0], 1e-12)
+%! assert (idx, 1);
+%! assert (p, [0,1,0], 1e-12);
 %!test
 %! [idx, p] = tsearchn (x,tri,[1,-1]);
-%! assert (idx, 1)
-%! assert (p, [0,0,1], 1e-12)
+%! assert (idx, 1);
+%! assert (p, [0,0,1], 1e-12);
 %!test
 %! [idx, p] = tsearchn (x,tri,[-1/3,-1/3]);
-%! assert (idx, 1)
-%! assert (p, [1/3,1/3,1/3], 1e-12)
+%! assert (idx, 1);
+%! assert (p, [1/3,1/3,1/3], 1e-12);
 %!test
 %! [idx, p] = tsearchn (x,tri,[1,1]);
-%! assert (idx, NaN)
-%! assert (p, [NaN, NaN, NaN])
+%! assert (idx, NaN);
+%! assert (p, [NaN, NaN, NaN]);
+
--- a/scripts/geometry/voronoi.m
+++ b/scripts/geometry/voronoi.m
@@ -37,7 +37,7 @@
 ##
 ## If a single output argument is requested then the Voronoi diagram will be
 ## plotted and a graphics handle @var{h} to the plot is returned.
-## [@var{vx}, @var{vy}] = voronoi(@dots{}) returns the Voronoi vertices
+## [@var{vx}, @var{vy}] = voronoi (@dots{}) returns the Voronoi vertices
 ## instead of plotting the diagram.
 ##
 ## @example
@@ -105,10 +105,7 @@
     linespec = varargin(narg);
   endif
 
-  lx = length (x);
-  ly = length (y);
-
-  if (lx != ly)
+  if (length (x) != length (y))
     error ("voronoi: X and Y must be vectors of the same length");
   endif
 
@@ -133,35 +130,33 @@
                               [[x(:) ; xbox(:)], [y(:); ybox(:)]],
                               opts{:});
 
-  idx = find (! infi);
-  ll = length (idx);
-  c = c(idx).';
-  k = sum (cellfun ("length", c));
+  c = c(! infi).';
+  ## Delete null entries which cause problems in next cellfun function
+  c(cellfun ("isempty", c)) = [];
   edges = cell2mat (cellfun (@(x) [x ; [x(end), x(1:end-1)]], c,
                              "uniformoutput", false));
 
   ## Identify the unique edges of the Voronoi diagram
   edges = sortrows (sort (edges).').';
-  edges = edges (:, [(edges(1, 1: end - 1) != edges(1, 2 : end) | ...
-                      edges(2, 1 :end - 1) != edges(2, 2 : end)), true]);
+  edges = edges(:, [(edges(1, 1 :end - 1) != edges(1, 2 : end) | ...
+                     edges(2, 1 :end - 1) != edges(2, 2 : end)), true]);
 
   ## Eliminate the edges of the diagram representing the box
-  poutside = (1 : rows(p)) ...
-      (p (:, 1) < xmin - xdelta | p (:, 1) > xmax + xdelta | ...
-       p (:, 2) < ymin - ydelta | p (:, 2) > ymax + ydelta);
-  edgeoutside = ismember (edges (1, :), poutside) & ...
-      ismember (edges (2, :), poutside);
-  edges (:, edgeoutside) = [];
+  poutside = (1:rows (p)) ...
+      (p(:, 1) < xmin - xdelta | p(:, 1) > xmax + xdelta | ...
+       p(:, 2) < ymin - ydelta | p(:, 2) > ymax + ydelta);
+  edgeoutside = ismember (edges(1, :), poutside) & ...
+                ismember (edges(2, :), poutside);
+  edges(:, edgeoutside) = [];
 
   ## Get points of the diagram
   Vvx = reshape (p(edges, 1), size (edges));
   Vvy = reshape (p(edges, 2), size (edges));
 
   if (nargout < 2)
+    h = plot (handl, Vvx, Vvy, linespec{:}, x, y, '+');
     lim = [xmin, xmax, ymin, ymax];
-    h = plot (handl, Vvx, Vvy, linespec{:}, x, y, '+');
-    axis (lim + 0.1 * [[-1, 1] * (lim (2) - lim (1)), ...
-                       [-1, 1] * (lim (4) - lim (3))]);
+    axis (lim + 0.1 * [[-1, 1] * xdelta, [-1, 1] * ydelta]);
     if (nargout == 1)
       vx = h;
     endif
@@ -174,14 +169,14 @@
 
 
 %!demo
-%! voronoi (rand(10,1), rand(10,1));
+%! voronoi (rand (10,1), rand (10,1));
 
 %!testif HAVE_QHULL
 %! phi = linspace (-pi, 3/4*pi, 8);
 %! [x,y] = pol2cart (phi, 1);
 %! [vx,vy] = voronoi (x,y);
-%! assert(vx(2,:), zeros (1, columns (vx)), eps);
-%! assert(vy(2,:), zeros (1, columns (vy)), eps);
+%! assert (vx(2,:), zeros (1, columns (vx)), eps);
+%! assert (vy(2,:), zeros (1, columns (vy)), eps);
 
 %% FIXME: Need input validation tests
 
--- a/scripts/geometry/voronoin.m
+++ b/scripts/geometry/voronoin.m
@@ -28,6 +28,20 @@
 ## contains options passed to the underlying qhull command.
 ## See the documentation for the Qhull library for details
 ## @url{http://www.qhull.org/html/qh-quick.htm#options}.
+##
+## The default options depend on the dimension of the input:
+##
+## @itemize
+## @item 2-D and 3-D: @var{options} = @code{@{"Qbb"@}}
+##
+## @item 4-D and higher: @var{options} = @code{@{"Qbb", "Qx"@}}
+## @end itemize
+##
+## If @var{options} is not present or @code{[]} then the default arguments are
+## used.  Otherwise, @var{options} replaces the default argument list. 
+## To append user options to the defaults it is necessary to repeat the 
+## default arguments in @var{options}.  Use a null string to pass no arguments.
+##
 ## @seealso{voronoi, convhulln, delaunayn}
 ## @end deftypefn
 
@@ -63,5 +77,7 @@
 
 %% FIXME: Need functional tests
 
-%% FIXME: Need input validation tests
+%!error voronoin ()
+%!error voronoin (1,2,3)
+%!error <number of points must be greater than their dimension> voronoin ([1 2])
 
--- a/scripts/help/__makeinfo__.m
+++ b/scripts/help/__makeinfo__.m
@@ -86,23 +86,23 @@
     error ("__makeinfo__: third input argument must be a function handle");
   endif
 
-
-  ## It seems like makeinfo sometimes gets angry if the first character
-  ## on a line is a space, so we remove these.
-  text = strrep (text, "\n ", "\n");
+  ## Formatting in m-files has an extra space at the beginning of every line.
+  ## Remove these unwanted spaces if present.  First text char is "\n" delim.
+  if (text(2) == " ")
+    text = strrep (text, "\n ", "\n");
+  endif
+  ## Texinfo crashes if @end tex does not appear first on the line.
+  text = regexprep (text, '^ +@end tex', '@end tex', 'lineanchors');
 
-  ## Handle @seealso macro
-  see_also_pat = '@seealso *\{(.*)\}';
-  args = regexp (text, see_also_pat, 'tokens');
-  for ii = 1:numel (args)
-    expanded = fsee_also (strtrim (strsplit (args{ii}{:}, ',', true)));
-    text = regexprep (text, see_also_pat, expanded, 'once');
-  endfor
-
-  ## Handle @nospell macro
-  text = regexprep (text, '@nospell *\{([^}]*)\}', "$1");
-  ## Handle @xcode macro
-  text = regexprep (text, '@xcode *\{([^}]*)\}', "$1");
+  file = texi_macros_file ();
+  fid = fopen (file, "r");
+  if (fid < 0)
+    error ("unable to open %s for reading", file);
+  else
+    macros_text = fread (fid, Inf, "*char")';
+    text = cstrcat (macros_text, text);
+  endif
+  fclose (fid);
 
   if (strcmpi (output_type, "texinfo"))
     status = 0;
@@ -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
@@ -145,6 +145,7 @@
   end_unwind_protect
 endfunction
 
+
 ## No test needed for internal helper function.
 %!assert (1)
 
rename from scripts/help/unimplemented.m
rename to scripts/help/__unimplemented__.m
--- a/scripts/help/unimplemented.m
+++ b/scripts/help/__unimplemented__.m
@@ -18,22 +18,29 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} unimplemented ()
-## Undocumented internal function.
+## @deftypefn {Function File} {@var{txt} =} unimplemented (@var{fcn})
+## Return specific help text for the unimplemented function @var{fcn}.
+## This is usually a suggestion for an existing compatible function to use in
+## place of @var{fcn}.
+##
+## This function is not called by users, but by the Octave interpreter when
+## it fails to recognize an input string as a valid function name.  See
+## @code{missing_function_hook} for using a different handler for this event.
+## @seealso{missing_function_hook}
 ## @end deftypefn
 
-function txt = unimplemented (fcn)
+
+function txt = __unimplemented__ (fcn)
+
+  if (nargin != 1)
+    print_usage ();
+  endif
 
   is_matlab_function = true;
 
   ## Some smarter cases, add more as needed.
   switch (fcn)
 
-  case "importdata"
-    txt = ["importdata is not implemented.  Similar functionality is ",...
-    "available through @code{load}, @code{dlmread}, @code{csvread}, ",...
-    "or @code{textscan}."];  
-
   case "quad2d"
     txt = ["quad2d is not implemented.  Consider using dblquad."];
 
@@ -42,6 +49,10 @@
     "linear-algebra package at ",...
     "@url{http://octave.sourceforge.net/linear-algebra/}."];
 
+  case "funm"
+    txt = ["funm is not currently part of core Octave.  See the ",...
+    "linear-algebra package at @url{http://octave.sf.net/linear-algebra/}."];
+
   case "linprog"
     txt = ["Octave does not currently provide linprog.  ",...
     "Linear programming problems may be solved using @code{glpk}.  ",...
@@ -53,6 +64,23 @@
     "Matlab-compatible ODE functions are provided by the odepkg package.  ",...
     "See @url{http://octave.sourceforge.net/odepkg/}."];
 
+  case {"javaArray", "javaMethod", "javaMethodEDT", "javaObject", "javaObjectEDT", "javaaddpath", "javaclasspath", "javarmpath"}
+    txt = ["Java objects and methods can be used with the java package. ",...
+    "See @url{http://octave.sf.net/java/}."];
+
+  case {"errordlg", "helpdlg", "inputdlg", "listdlg", "questdlg", "warndlg"}
+    txt = ["Several dialog functions are provided in the java package. ",...
+    "See @url{http://octave.sf.net/java/}."];
+
+  case {"xlsread", "xlsfinfo", "xlswrite", "wk1read", "wk1finfo", "wk1write"}
+    txt = ["Functions for spreadsheet style I/O (.xls .xlsx .sxc .ods .dbf .wk1 etc.) " , ...
+    "are provided in the io package. ",...
+    "See @url{http://octave.sf.net/io/}."];
+
+  case {"avifile", "aviinfo", "aviread"}
+    txt = ["Basic video file support is provided in the video package. ",...
+    "See @url{http://octave.sf.net/video/}."];
+
   otherwise
     if (ismember (fcn, missing_functions ()))
       txt = sprintf ("the '%s' function is not yet implemented in Octave", fcn);
@@ -93,13 +121,9 @@
   "aufinfo",
   "auread",
   "auwrite",
-  "avifile",
-  "aviinfo",
-  "aviread",
   "bar3",
   "bar3h",
   "bench",
-  "betaincinv",
   "bicgstabl",
   "brush",
   "builddocsearchdb",
@@ -145,7 +169,6 @@
   "condeig",
   "coneplot",
   "contourslice",
-  "copyobj",
   "createClassFromWsdl",
   "createSoapMessage",
   "customverctrl",
@@ -168,31 +191,22 @@
   "dragrect",
   "dynamicprops",
   "echodemo",
-  "ellipj",
-  "ellipke",
-  "erfcinv",
-  "errordlg",
   "evalc",
   "exifread",
-  "expint",
   "export2wsdlg",
   "figurepalette",
   "filebrowser",
   "fill3",
-  "findfigs",
   "fitsinfo",
   "fitsread",
   "flow",
-  "fminsearch",
   "frame2im",
   "freqspace",
   "funm",
   "gallery",
   "gammaincinv",
-  "gco",
   "getframe",
   "getpixelposition",
-  "gmres",
   "grabcode",
   "graymon",
   "gsvd",
@@ -210,7 +224,6 @@
   "hdftool",
   "helpbrowser",
   "helpdesk",
-  "helpdlg",
   "helpwin",
   "hgexport",
   "hgload",
@@ -224,10 +237,8 @@
   "imapprox",
   "imformats",
   "import",
-  "importdata",
   "inmem",
   "inputParser",
-  "inputdlg",
   "inspect",
   "instrfind",
   "instrfindall",
@@ -237,15 +248,7 @@
   "isjava",
   "isocaps",
   "isstudent",
-  "javaArray",
-  "javaMethod",
-  "javaMethodEDT",
-  "javaObject",
-  "javaObjectEDT",
-  "javaaddpath",
   "javachk",
-  "javaclasspath",
-  "javarmpath",
   "ldl",
   "libfunctions",
   "libfunctionsview",
@@ -258,7 +261,6 @@
   "linkaxes",
   "linkdata",
   "linsolve",
-  "listdlg",
   "listfonts",
   "loadlibrary",
   "lscov",
@@ -316,25 +318,20 @@
   "plotbrowser",
   "plotedit",
   "plottools",
-  "polyeig",
   "prefdir",
   "preferences",
   "printdlg",
   "printopt",
   "printpreview",
-  "profile",
   "profsave",
   "propedit",
   "propertyeditor",
   "publish",
   "qmr",
   "quad2d",
-  "questdlg",
   "rbbox",
   "reducepatch",
   "reducevolume",
-  "resample",
-  "rgbplot",
   "root",
   "rotate",
   "rotate3d",
@@ -343,7 +340,6 @@
   "serial",
   "setpixelposition",
   "showplottool",
-  "shrinkfaces",
   "smooth3",
   "snapnow",
   "sound",
@@ -363,7 +359,6 @@
   "surf2patch",
   "symmlq",
   "syntax",
-  "tetramesh",
   "texlabel",
   "textwrap",
   "tfqmr",
@@ -403,8 +398,6 @@
   "visdiff",
   "volumebounds",
   "waitfor",
-  "warndlg",
-  "waterfall",
   "wavfinfo",
   "wavplay",
   "wavrecord",
@@ -414,9 +407,6 @@
   "wk1read",
   "wk1write",
   "workspace",
-  "xlsfinfo",
-  "xlsread",
-  "xlswrite",
   "xmlread",
   "xmlwrite",
   "xslt",
@@ -426,11 +416,9 @@
 
 
 %!test
-%! str = unimplemented ("no_name_function");
+%! str = __unimplemented__ ("no_name_function");
 %! assert (isempty (str));
-%! str = unimplemented ("quad2d");
+%! str = __unimplemented__ ("quad2d");
 %! assert (str(1:51), "quad2d is not implemented.  Consider using dblquad.");
-%! str = unimplemented ("MException");
+%! str = __unimplemented__ ("MException");
 %! assert (str(1:58), "the 'MException' function is not yet implemented in Octave");
-
-
--- a/scripts/help/doc.m
+++ b/scripts/help/doc.m
@@ -86,7 +86,7 @@
     have_fname = ! isempty (fname);
 
     if (have_fname)
-      status = system (sprintf ("%s --index-search %s", cmd, fname));
+      status = system (sprintf ("%s --index-search \"%s\"", cmd, fname));
     endif
 
     if (! (have_fname && status == 0))
@@ -106,6 +106,10 @@
 
 endfunction
 
-%!test if exist( info_file ()) != 2 && exist (sprintf ("%s.gz", info_file ())) != 2
-%!       error ("Info file %s or %s.gz does not exist!", info_file (), info_file ());
-%!     endif
+
+%!test
+%! ifile = info_file ();
+%! if (exist (ifile) != 2 && exist (sprintf ("%s.gz", ifile)) != 2)
+%!   error ("Info file %s or %s.gz does not exist!", ifile, ifile);
+%! endif
+
--- a/scripts/help/gen_doc_cache.m
+++ b/scripts/help/gen_doc_cache.m
@@ -34,23 +34,30 @@
 function gen_doc_cache (out_file = "doc-cache", directory = [])
 
   ## Check input
-  if (!ischar (out_file))
+  if (! ischar (out_file))
     print_usage ();
   endif
 
   ## Generate cache
   if (isempty (directory))
     cache = gen_builtin_cache ();
+  elseif (iscell (directory))
+    if (all (cellfun (@ischar, directory)))
+      cache = gen_doc_cache_in_dir (directory);
+    else
+      error ("gen_doc_cache: cell must contain only strings");
+    endif
   elseif (ischar (directory))
-    cache = gen_doc_cache_in_dir (directory);
+     cache = gen_doc_cache_in_dir (directory);
   else
-    error ("gen_doc_cache: second input argument must be a string");
+     error ("gen_doc_cache: second input argument must be a string or a cell of strings");
   endif
 
   ## Save cache
   if (! isempty (cache))
-    save ("-text", out_file, "cache");
+     save ("-text", out_file, "cache");
   endif
+
 endfunction
 
 function [text, first_sentence, status] = handle_function (f, text, format)
@@ -108,31 +115,33 @@
 endfunction
 
 function cache = gen_doc_cache_in_dir (directory)
+
   ## If 'directory' is not in the current path, add it so we search it
-  dir_in_path = false;
-  p = path ();
-  idx = find (p == pathsep ());
-  prev_idx = 1;
-  for n = 1:length (idx)
-    f = p (prev_idx:idx (n)-1);
-    if (strcmp (f, directory))
-      dir_in_path = true;
-      break;
-    endif
-    prev_idx = idx (n) + 1;
-  endfor
+  dir_in_path = ismember (directory, strsplit (path (), pathsep (), false));
 
-  if (!dir_in_path)
-    addpath (directory);
+  # dirs not in path
+  if (! iscell (directory))
+    directory = {directory};
+  endif
+  dirs_notpath = {directory{!dir_in_path}};
+
+  # add them
+  if (! isempty (dirs_notpath))
+    cellfun (@addpath, dirs_notpath);
   endif
 
-  ## Get list of functions in directory and create cache
-  list = __list_functions__ (directory);
-  cache = create_cache (list);
+  # create cache
+  func = @(s_) create_cache (__list_functions__ (s_));
+  cache = cellfun (func, directory, 'UniformOutput', false);
 
-  if (!dir_in_path)
-    rmpath (directory);
+  # concatenate results
+  cache = [cache{:}];
+
+  #remove dirs form path
+  if (! isempty (dirs_notpath))
+    cellfun (@rmpath, dirs_notpath);
   endif
+
 endfunction
 
 function cache = gen_builtin_cache ()
@@ -148,4 +157,3 @@
 %% No true tests desirable for this function.
 %% Test input validation
 %!error gen_doc_cache (1)
-
--- a/scripts/help/get_first_help_sentence.m
+++ b/scripts/help/get_first_help_sentence.m
@@ -50,7 +50,7 @@
     error ("get_first_help_sentence: NAME must be a string");
   endif
 
-  if (!isnumeric (max_len) || max_len <= 0 || max_len != fix (max_len))
+  if (! isnumeric (max_len) || max_len <= 0 || max_len != fix (max_len))
     error ("get_first_help_sentence: MAX_LEN must be positive integer");
   endif
 
@@ -80,10 +80,13 @@
 
 ## This function extracts the first sentence from a plain text help text
 function [text, status] = first_sentence_plain_text (help_text, max_len)
-  ## Extract first line by searching for a period or a double line-end.
-  period_idx = find (help_text == '.', 1);
-  line_end_idx = strfind (help_text, "\n\n");
-  text = help_text (1:min ([period_idx(:); line_end_idx(:); max_len; length(help_text)]));
+  ## Extract first line by searching for a period followed by a space class
+  ## character (to support periods in numbers or words) ...
+  period_idx = regexp (help_text, '\.\s', "once");
+  ## ... or a double end-of-line (we subtract 1 because we are not interested
+  ## in capturing the first newline).
+  line_end_idx = regexp (help_text, "\n\n", "once") - 1;
+  text = help_text (1:min ([period_idx; line_end_idx; max_len; length(help_text)]));
   status = 0;
 endfunction
 
@@ -91,27 +94,27 @@
 ## The function works by removing @def* from the texinfo text. After this, we
 ## render the text to plain text using makeinfo, and then extract the first line.
 function [text, status] = first_sentence_texinfo (help_text, max_len)
-  ## Lines ending with "@\n" are continuation lines, so they should be concatenated
-  ## with the following line.
+  ## Lines ending with "@\n" are continuation lines, so they should be
+  ## concatenated with the following line.
   help_text = strrep (help_text, "@\n", " ");
 
   ## Find, and remove, lines that start with @def. This should remove things
   ## such as @deftypefn, @deftypefnx, @defvar, etc.
   keep = true (size (help_text));
   def_idx = strfind (help_text, "@def");
-  if (!isempty (def_idx))
+  if (! isempty (def_idx))
     endl_idx = find (help_text == "\n");
     for k = 1:length (def_idx)
-      endl = endl_idx (find (endl_idx > def_idx (k), 1));
+      endl = endl_idx(find (endl_idx > def_idx(k), 1));
       if (isempty (endl))
-        keep (def_idx (k):end) = false;
+        keep(def_idx(k):end) = false;
       else
-        keep (def_idx (k):endl) = false;
+        keep(def_idx(k):endl) = false;
       endif
     endfor
 
     ## Remove the @end ... that corresponds to the @def we removed above
-    def1 = def_idx (1);
+    def1 = def_idx(1);
     space_idx = find (help_text == " ");
     space_idx = space_idx (find (space_idx > def1, 1));
     bracket_idx = find (help_text == "{" | help_text == "}");
@@ -120,20 +123,20 @@
       error ("get_first_help_sentence: couldn't parse texinfo");
     endif
     sep_idx = min (space_idx, bracket_idx);
-    def_type = help_text (def1+1:sep_idx-1);
+    def_type = help_text(def1+1:sep_idx-1);
 
     end_idx = strfind (help_text, sprintf ("@end %s", def_type));
     if (isempty (end_idx))
       error ("get_first_help_sentence: couldn't parse texinfo");
     endif
-    endl = endl_idx (find (endl_idx > end_idx, 1));
+    endl = endl_idx(find (endl_idx > end_idx, 1));
     if (isempty (endl))
-      keep (end_idx:end) = false;
+      keep(end_idx:end) = false;
     else
-      keep (end_idx:endl) = false;
+      keep(end_idx:endl) = false;
     endif
 
-    help_text = help_text (keep);
+    help_text = help_text(keep);
   endif
 
   ## Run makeinfo to generate plain text
@@ -153,13 +156,14 @@
   text = first_sentence_plain_text (help_text, max_len);
 endfunction
 
-%!assert (strcmp (get_first_help_sentence('get_first_help_sentence'), "Return the first sentence of a function's help text."));
+
+%!assert (get_first_help_sentence ('get_first_help_sentence'), "Return the first sentence of a function's help text.")
 
 %% Test input validation
 %!error get_first_help_sentence ()
 %!error get_first_help_sentence (1, 2, 3)
-%!error get_first_help_sentence (1)
-%!error get_first_help_sentence ('ls', 'a')
-%!error get_first_help_sentence ('ls', 0)
-%!error get_first_help_sentence ('ls', 80.1)
+%!error <NAME must be a string> get_first_help_sentence (1)
+%!error <MAX_LEN must be positive integer> get_first_help_sentence ("ls", "a")
+%!error <MAX_LEN must be positive integer> get_first_help_sentence ("ls", 0)
+%!error <MAX_LEN must be positive integer> get_first_help_sentence ("ls", 80.1)
 
--- a/scripts/help/help.m
+++ b/scripts/help/help.m
@@ -19,6 +19,7 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Command} {} help @var{name}
 ## @deftypefnx {Command} {} help @code{--list}
+## @deftypefnx {Command} {} help @code{.}
 ## Display the help text for @var{name}.   For example, the command
 ## @kbd{help help} prints a short message describing the @code{help}
 ## command.
@@ -27,6 +28,9 @@
 ## keywords, built-in functions, and loadable functions available
 ## in the current session of Octave.
 ##
+## Given the single argument @code{.}, list all operators available
+## in the current session of Octave.
+##
 ## If invoked without any arguments, @code{help} display instructions
 ## on how to access help from the command line.
 ##
@@ -40,7 +44,7 @@
 
   if (nargin == 0)
 
-    puts ("\n\
+    text = "\n\
   For help with individual commands and functions type\n\
 \n\
     help NAME\n\
@@ -54,7 +58,13 @@
     doc\n\
 \n\
   GNU Octave is supported and developed by its user community.\n\
-  For more information visit http://www.octave.org.\n\n");
+  For more information visit http://www.octave.org.\n\n";
+
+    if (nargout == 0)
+      puts (text);
+    else
+      retval = text;
+    endif
 
   elseif (nargin == 1 && ischar (name))
 
@@ -68,6 +78,16 @@
       return;
     endif
 
+    if (strcmp (name, "."))
+      tmp = do_list_operators ();
+      if (nargout == 0)
+        printf ("%s", tmp);
+      else
+        retval = tmp;
+      endif
+      return;
+    endif
+
     ## Get help text
     [text, format] = get_help_text (name);
 
@@ -106,10 +126,15 @@
 
 endfunction
 
+function retval = do_list_operators ()
+  
+  retval = sprintf ("*** operators:\n\n%s\n\n",
+                       list_in_columns (__operators__ ()));
+endfunction
+
 function retval = do_list_functions ()
 
-  operators = sprintf ("*** operators:\n\n%s\n\n",
-                       list_in_columns (__operators__ ()));
+  operators = do_list_operators ();
 
   keywords = sprintf ("*** keywords:\n\n%s\n\n",
                       list_in_columns (__keywords__ ()));
@@ -117,7 +142,7 @@
   builtins = sprintf ("*** builtins:\n\n%s\n\n",
                       list_in_columns (__builtins__ ()));
 
-  dirs = strsplit (path, pathsep);
+  dirs = strsplit (path, pathsep, false);
   flist = "";
   for i = 2:numel (dirs)
     files = sort ({dir(fullfile (dirs{i}, "*.m")).name, ...
@@ -181,5 +206,7 @@
 endfunction
 
 
-%!assert (! isempty (findstr (help ("ls"), "List directory contents")))
+%!assert (! isempty (strfind (help ("ls"), "List directory contents")))
 %!error <invalid input> help (42)
+
+
--- a/scripts/help/lookfor.m
+++ b/scripts/help/lookfor.m
@@ -20,11 +20,11 @@
 ## @deftypefn  {Command} {} lookfor @var{str}
 ## @deftypefnx {Command} {} lookfor -all @var{str}
 ## @deftypefnx {Function File} {[@var{func}, @var{helpstring}] =} lookfor (@var{str})
-## @deftypefnx {Function File} {[@var{func}, @var{helpstring}] =} lookfor ('-all', @var{str})
+## @deftypefnx {Function File} {[@var{func}, @var{helpstring}] =} lookfor ("-all", @var{str})
 ## Search for the string @var{str} in all functions found in the current
 ## function search path.  By default, @code{lookfor} searches for @var{str}
 ## in the first sentence of the help string of each function found.  The entire
-## help text of each function can be searched if the '-all' argument is
+## help text of each function can be searched if the "-all" argument is
 ## supplied.  All searches are case insensitive.
 ##
 ## Called with no output arguments, @code{lookfor} prints the list of
@@ -36,7 +36,7 @@
 ## sentence of the help text is dependent on the format of the
 ## function's help.  All Octave core functions are correctly
 ## formatted, but the same can not be guaranteed for external packages and
-## user-supplied functions.  Therefore, the use of the '-all' argument may
+## user-supplied functions.  Therefore, the use of the "-all" argument may
 ## be necessary to find related functions that are not a part of Octave.
 ## @seealso{help, doc, which}
 ## @end deftypefn
@@ -66,10 +66,10 @@
   endif
 
   ## Search functions in new path dirs.
-  orig_path = strsplit (__pathorig__ (), pathsep ());
+  orig_path = strsplit (__pathorig__ (), pathsep (), false);
 
   ## ditto for path.
-  new_path = strsplit (path (), pathsep ());
+  new_path = strsplit (path (), pathsep (), false);
 
   ## scratch out directories already covered by orig_path.
   if (had_core_cache)
--- a/scripts/help/module.mk
+++ b/scripts/help/module.mk
@@ -6,6 +6,7 @@
 
 help_FCN_FILES = \
   help/__makeinfo__.m \
+  help/__unimplemented__.m \
   help/doc.m \
   help/gen_doc_cache.m \
   help/get_first_help_sentence.m \
@@ -13,7 +14,6 @@
   help/lookfor.m \
   help/print_usage.m \
   help/type.m \
-  help/unimplemented.m \
   help/which.m \
   $(help_PRIVATE_FCN_FILES)
 
--- a/scripts/help/print_usage.m
+++ b/scripts/help/print_usage.m
@@ -33,14 +33,15 @@
     if (numel (x) > 1)
       name = x (2).name;
     else
-      error ("print_usage: invalid function\n");
+      error ("Octave:invalid-context", "print_usage: invalid function\n");
     endif
     fullpath = evalin ("caller", "mfilename (""fullpath"")");
     if (strcmp (fullpath(end-length(name)+1:end), name))
       fullname = [fullpath, ".m"];
     endif
   elseif (!ischar (name))
-    error ("print_usage: input argument must be a string");
+    error ("Octave:invalid-input-arg",
+                                "print_usage: input argument must be a string");
   else
     fullname = name;
   endif
@@ -73,7 +74,7 @@
   endif
 
   if (at_toplev)
-    error ("Invalid call to %s.  Correct usage is:\n\n%s\n%s",
+    error ("Octave:invalid-fun-call", "Invalid call to %s.  Correct usage is:\n\n%s\n%s",
            name, usage_string, __additional_help_message__ ());
   else
     msg = sprintf ("Invalid call to %s.  Correct usage is:\n\n%s",
@@ -84,7 +85,7 @@
       msg(end) = " ";
     endif
 
-    error (msg);
+    error ("Octave:invalid-fun-call", msg);
   endif
 
 endfunction
@@ -139,4 +140,3 @@
 
 ## Stop reporting function as missing tests.  No good tests possible.
 %!assert (1)
-
--- a/scripts/help/type.m
+++ b/scripts/help/type.m
@@ -111,14 +111,16 @@
   endfor
 endfunction
 
+
 %!test
 %! var = 1;
 %! typestr = type ("var");
 %! typestr = typestr{1}(1:17);
 %! assert (typestr, "var is a variable");
 
-%!assert (type ('dot'){1}, "dot is a dynamically-linked function")
-%!assert (type ('cat'){1}, "cat is a built-in function")
-%!assert (type ('+'){1}, "+ is an operator")
-%!assert (type ('end'){1}, "end is a keyword")
+%!assert (type ("amd"){1}, "amd is a dynamically-linked function")
+%!assert (type ("cat"){1}, "cat is a built-in function")
+%!assert (type ("+"){1}, "+ is an operator")
+%!assert (type ("end"){1}, "end is a keyword")
 %!error (type ('NO_NAME'))
+ 
--- a/scripts/help/which.m
+++ b/scripts/help/which.m
@@ -57,9 +57,10 @@
 
 %!test
 %! str = which ("ls");
-%! assert (str(end-17:end), strcat ("miscellaneous", filesep(), "ls.m"));
+%! assert (str(end-17:end), strcat ("miscellaneous", filesep (), "ls.m"));
 %!test
-%! str = which ("dot");
-%! assert (str(end-6:end), "dot.oct");
+%! str = which ("amd");
+%! assert (str(end-6:end), "amd.oct");
 
-%!assert (which ("NO_NAME"), "");
+%!assert (which ("_NO_SUCH_NAME_"), "")
+
--- a/scripts/image/autumn.m
+++ b/scripts/image/autumn.m
@@ -28,13 +28,16 @@
 
 ## Author:  Kai Habel <kai.habel@gmx.de>
 
+## PKG_ADD: colormap ("register", "autumn");
+## PKG_DEL: colormap ("unregister", "autumn");
+
 function map = autumn (n)
 
   if (nargin == 0)
     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 ();
@@ -44,18 +47,19 @@
     map = [1, 0, 0];
   elseif (n > 1)
     r = ones (n, 1);
-    g = (0:n - 1)' ./ (n - 1);
+    g = [0:(n-1)]' / (n - 1);
     b = zeros (n, 1);
     map = [r, g, b];
   else
-    map = [];
+    map = zeros (0, 3);
   endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'autumn' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (autumn (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (autumn (64));
 
--- a/scripts/image/bone.m
+++ b/scripts/image/bone.m
@@ -28,37 +28,65 @@
 
 ## Author:  Kai Habel <kai.habel@gmx.de>
 
+## PKG_ADD: colormap ("register", "bone");
+## PKG_DEL: colormap ("unregister", "bone");
+
 function map = bone (n)
 
   if (nargin == 0)
     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 ();
   endif
 
   if (n == 1)
-    map = [0, 0, 0];
-  elseif (n > 1)
-    x = linspace (0, 1, n)';
+    map = [1/8 1/8 1/8];
+  elseif (n == 2)
+    map = [1/16 1/8 1/8
+            1    1   1 ];
+  elseif (n > 2)
+    x = [0:n-1]' / (n-1);
 
-    r = (x < 3/4) .* (7/8 * x) + (x >= 3/4) .* (11/8 * x - 3/8);
-    g = (x < 3/8) .* (7/8 * x)\
-      + (x >= 3/8 & x < 3/4) .* (29/24 * x - 1/8)\
-      + (x >= 3/4) .* (7/8 * x + 1/8);
-    b = (x < 3/8) .* (29/24 * x) + (x >= 3/8) .* (7/8 * x + 1/8);
+    idx = floor (3/4*n);
+    nel = n - idx + 1;    # number of elements
+    rem = mod (n, 8);
+    switch (rem)
+      case {2, 4}
+        base = 1 / (16 + 2*(n-rem));
+      case {5, 7}
+        base = 1 / (24 + 2*(n-rem));
+      otherwise
+        base = 0;
+    endswitch
+    r(1:idx,1) = 7/8 * x(1:idx);
+    r(idx:n,1) = linspace (7/8 * x(idx) + base, 1, nel);
+
+    idx = floor (3/8 * n);
+    nel = idx + 1;
+    g(1:idx,1) = 7/8 * x(1:idx);
+    g(idx:2*idx,1) = linspace (7/8 * x(idx), 7/8 * x(2*idx) + 1/8, nel);
+    g(2*idx+1:n,1) = 7/8 * x(2*idx+1:n) + 1/8;
+    
+    base = 1 / (8*idx);
+    nel = idx;
+    b(1:idx,1) = linspace (base, 7/8 * x(idx) + 1/8, nel);
+    b(idx:n,1) = 7/8 * x(idx:n) + 1/8;
+
     map = [r, g, b];
   else
-    map = [];
+    map = zeros (0, 3);
   endif
+
 endfunction
 
+
 %!demo
 %! ## Show the 'bone' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (bone (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (bone (64));
 
--- a/scripts/image/brighten.m
+++ b/scripts/image/brighten.m
@@ -18,39 +18,40 @@
 
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {@var{map_out} =} brighten (@var{map}, @var{beta})
+## @deftypefnx {Function File} {@var{map_out} =} brighten (@var{beta})
 ## @deftypefnx {Function File} {@var{map_out} =} brighten (@var{h}, @var{beta})
-## @deftypefnx {Function File} {@var{map_out} =} brighten (@var{beta})
-## Darken or brighten the given colormap.  If the @var{map} argument
-## is omitted, the function is applied to the current colormap.  The first
-## argument can also be a valid graphics handle @var{h}, in which case
-## @code{brighten} is applied to the colormap associated with this handle.
+## Brighten or darken a colormap.  If the @var{map} argument is omitted, the
+## function is applied to the current colormap.  The first argument can also be
+## a valid graphics handle @var{h}, in which case @code{brighten} is applied to
+## the colormap associated with this handle.
 ##
-## Should the resulting colormap @var{map_out} not be assigned, it will be
-## written to the current colormap.
+## The argument @var{beta} must be a scalar between -1 and 1, where a
+## negative value darkens and a positive value brightens the colormap.
 ##
-## The argument @var{beta} should be a scalar between -1 and 1,
-## where a negative value darkens and a positive value brightens
-## the colormap.
-## @seealso{colormap}
+## If no output is specified then the result is written to the current colormap.
+## @seealso{colormap, contrast}
 ## @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)
@@ -74,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");
+
new file mode 100644
--- /dev/null
+++ b/scripts/image/cmpermute.m
@@ -0,0 +1,145 @@
+## Copyright (C) 2004 Josep Mones i Teixidor
+## 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{Y}, @var{newmap}] =} cmpermute (@var{X}, @var{map})
+## @deftypefnx {Function File} {[@var{Y}, @var{newmap}] =} cmpermute (@var{X}, @var{map}, @var{index})
+## Reorder colors in a colormap.
+##
+## 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}.  
+##
+## When called with an optional third argument the order of colors in the
+## new colormap is defined by @var{index}.
+##
+## @strong{Caution:} @code{index} should not have repeated elements or the
+## function will fail.
+##
+## @end deftypefn
+
+## Author:  Josep Mones i Teixidor <jmones@puntbarra.com>
+
+function [Y, newmap] = cmpermute (X, map, index)
+
+  if (nargin < 2 || nargin > 3)
+    print_usage ();
+  endif
+
+  cls = class (X);
+  if (! any (strcmp (cls, {"uint8", "uint16", "single", "double"})))
+    error ("cmpermute: invalid data type '%s'", cls);
+  endif
+
+  if (! isreal (X) || issparse (X)
+      || (isfloat (X) && (any (X(:) < 1 || any (X(:) != fix (X(:)))))))
+    error ("cmpermute: X must be an indexed image");
+  endif
+
+  if (! iscolormap (map))
+    error ("cmpermute: MAP must be a valid colormap");
+  endif
+
+  if (nargin < 3)
+    index = randperm (rows (map));
+  elseif (! isvector (index) || length (index) != rows (map))
+    error ("cmpermute: invalid parameter INDEX");
+  endif
+
+  ## new colormap
+  newmap = map(index,:);
+
+  ## build reverse index
+  rindex = zeros (size (index));
+  rindex(index) = 1:length (index);
+ 
+  ## 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(single (X) + 1);
+  endif
+
+endfunction
+
+
+%!demo
+%! [Y, newmap] = cmpermute ([1:4], hot (4), 4:-1:1)
+%! ## colormap will be arranged in reverse order (so will image)
+
+%!shared X, map
+%! X = uint8 (magic (16));
+%! [X, map] = cmunique (X);
+
+%!test # random permutation, 0-based index
+%! [Y, newmap] = cmpermute (X, map);
+%! ## test we didn't lose colors
+%! assert (sort (map), sortrows (newmap)); 
+%! ## test if images are equal
+%! assert (map(double (X)+1), newmap(double (Y)+1));
+
+%!test # reverse map, 0-based index
+%! [Y, newmap] = cmpermute (X, map, rows (map):-1:1);
+%! ## we expect a reversed colormap
+%! assert (flipud (newmap), map);
+%! ## we expect reversed indices in image
+%! assert (X, max (Y(:)) - Y);
+
+%!shared X,map
+%! X = uint16 (magic (20));
+%! [X, map] = cmunique (X);
+
+%!test # random permutation, 1-based index
+%! [Y, newmap] = cmpermute (X, map);
+%! ## test we didn't lose colors
+%! assert (sort (map), sortrows (newmap)); 
+%! ## test if images are equal
+%! assert (map(X), newmap(Y));
+
+%!test # reverse map, 1-based index
+%! [Y, newmap] = cmpermute (X, map, rows (map):-1:1);
+%! ## we expect a reversed colormap
+%! assert (newmap (rows (newmap):-1:1,:), map);
+%! ## we expect reversed indices in image
+%! assert (X, max (Y(:)) + 1 - Y);
+
+## Test input validation
+%!error cmpermute ()
+%!error cmpermute (1,2,3,4)
+%!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))
+%!error <X must be an indexed image> cmpermute (1.5, jet (256))
+%!error <MAP must be a valid colormap> cmpermute (1, "a")
+%!error <MAP must be a valid colormap> cmpermute (1, i)
+%!error <MAP must be a valid colormap> cmpermute (1, ones (3,3,3))
+%!error <MAP must be a valid colormap> cmpermute (1, ones (3,2))
+%!error <MAP must be a valid colormap> cmpermute (1, [-1 1 1])
+%!error <MAP must be a valid colormap> cmpermute (1, [2 1 1])
+%!error <invalid parameter INDEX> cmpermute (1, [0 1 0;1 0 1], ones (3))
+%!error <invalid parameter INDEX> cmpermute (1, [0 1 0;1 0 1], 1:3)
+
new file mode 100644
--- /dev/null
+++ b/scripts/image/cmunique.m
@@ -0,0 +1,201 @@
+## Copyright (C) 2004 Josep Mones i Teixidor
+## 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{Y}, @var{newmap}] =} cmunique (@var{X}, @var{map})
+## @deftypefnx {Function File} {[@var{Y}, @var{newmap}] =} cmunique (@var{RGB})
+## @deftypefnx {Function File} {[@var{Y}, @var{newmap}] =} cmunique (@var{I})
+## Convert an input image @var{X} to an ouput indexed image @var{Y} which uses
+## the smallest colormap possible @var{newmap}.
+##
+## When the input is an indexed image (@var{X} with colormap @var{map}) the 
+## output is a colormap @var{newmap} from which any repeated rows have been
+## eliminated.  The output image, @var{Y}, is the original input image with
+## the indices adjusted to match the new, possibly smaller, colormap.
+##
+## When the input is an RGB image (an @nospell{MxNx3} array), the output
+## colormap will contain one entry for every unique color in the original image.
+## In the worst case the new map could have as many rows as the number of
+## pixels in the original image.
+##
+## When the input is a grayscale image @var{I}, the output colormap will
+## contain one entry for every unique intensity value in the original image.
+## In the worst case the new map could have as many rows as the number of
+## pixels in the original image.
+##
+## Implementation Details:
+##
+## @var{newmap} is always an Mx3 matrix, even if the input image is
+## an intensity grayscale image @var{I} (all three RGB planes are
+## assigned the same value).
+##
+## The output image is of class uint8 if the size of the new colormap is
+## less than or equal to 256.  Otherwise, the output image is of class double.
+##
+## @seealso{rgb2ind, gray2ind}
+## @end deftypefn
+
+
+## Author:  Josep Mones i Teixidor <jmones@puntbarra.com>
+
+function [Y, newmap] = cmunique (X, map)
+
+  if (nargin < 1 || nargin > 2)
+    print_usage ();
+  endif
+
+  cls = class (X);
+  if (! any (strcmp (cls, {"uint8", "uint16", "single", "double"})))
+    error ("cmunique: X is of invalid data type '%s'", cls);
+  endif
+
+  if (nargin == 2)
+    ## (X, map) case
+    if (! iscolormap (map))
+      error ("cmunique: MAP must be a valid colormap");
+    endif
+    [newmap,i,j] = unique (map, "rows");  # calculate unique colormap
+    if (isfloat (X))
+      Y = j(X);               # find new indices
+    else
+      Y = j(double (X) + 1);  # find new indices, switch to 1-based index
+    endif
+  else
+    switch (size (X,3))
+      case (1)
+        ## I case
+        [newmap,i,j] = unique (X);               # calculate unique colormap
+        newmap = repmat (newmap,1,3);            # get a RGB colormap
+        Y = reshape (j, rows (X), columns (X));  # Y is j reshaped
+      case (3)
+        ## RGB case
+        ## build a map with all values
+        map = [X(:,:,1)(:), X(:,:,2)(:), X(:,:,3)(:)];
+        [newmap,i,j] = unique (map, "rows");     # calculate unique colormap
+        Y = reshape (j, rows (X), columns (X));  # Y is j reshaped
+      otherwise
+        error ("cmunique: X is not a valid image");
+    endswitch
+    
+    ## if image was uint8 or uint16 we have to convert newmap to [0,1] range
+    if (isinteger (X))
+      newmap = double (newmap) / double (intmax (cls));
+    endif
+  endif
+
+  if (rows (newmap) <= 256)
+    ## convert Y to uint8 and 0-based indexing
+    Y = uint8 (Y-1);
+  endif
+
+endfunction
+
+
+%!demo
+%! [Y, newmap] = cmunique ([1:4;5:8], [hot(4);hot(4)])
+%! ## Both rows are equal since map maps colors to the same value
+%! ## cmunique will give the same indices to both
+
+## Check that output is uint8 in short colormaps
+%!test
+%! [Y, newmap] = cmunique ([1:4;5:8], [hot(4);hot(4)]);
+%! assert (Y, uint8 ([0:3;0:3]));
+%! assert (newmap, hot (4));
+
+## Check that output is double in bigger
+%!test
+%! [Y, newmap] = cmunique ([1:300;301:600], [hot(300);hot(300)]);
+%! assert (Y, [1:300;1:300]);
+%! assert (newmap, hot (300));
+
+## Check boundary case 256
+%!test
+%! [Y, newmap] = cmunique ([1:256;257:512], [hot(256);hot(256)]);
+%! assert (Y, uint8 ([0:255;0:255]));
+%! assert (newmap, hot (256));
+
+## Check boundary case 257
+%!test
+%! [Y, newmap] = cmunique ([1:257;258:514], [hot(257);hot(257)]);
+%! assert (Y, [1:257;1:257]);
+%! assert (newmap, hot (257));
+
+## Random RGB image
+%!test
+%! RGB = rand (10,10,3);
+%! [Y, newmap] = cmunique (RGB);
+%! assert (RGB(:,:,1), newmap(:,1)(Y+1));
+%! assert (RGB(:,:,2), newmap(:,2)(Y+1));
+%! assert (RGB(:,:,3), newmap(:,3)(Y+1));
+
+## Random uint8 RGB image
+%!test
+%! RGB = uint8 (rand (10,10,3)*255);
+%! RGBd = double (RGB) / 255;
+%! [Y, newmap] = cmunique (RGB);
+%! assert (RGBd(:,:,1), newmap(:,1)(Y+1));
+%! assert (RGBd(:,:,2), newmap(:,2)(Y+1));
+%! assert (RGBd(:,:,3), newmap(:,3)(Y+1));
+
+## Random uint16 RGB image
+%!test
+%! RGB = uint16 (rand (10,10,3)*65535);
+%! RGBd = double (RGB) / 65535;
+%! [Y, newmap] = cmunique (RGB);
+%! assert (RGBd(:,:,1), newmap(:,1)(Y+1));
+%! assert (RGBd(:,:,2), newmap(:,2)(Y+1));
+%! assert (RGBd(:,:,3), newmap(:,3)(Y+1));
+
+## Random I image
+%!test
+%! I = rand (10,10);
+%! [Y, newmap] = cmunique (I);
+%! assert (I, newmap(:,1)(Y+1));
+%! assert (I, newmap(:,2)(Y+1));
+%! assert (I, newmap(:,3)(Y+1));
+
+## Random uint8 I image
+%!test
+%! I = uint8 (rand (10,10)*256);
+%! Id = double (I) / 255;
+%! [Y, newmap] = cmunique (I);
+%! assert (Id, newmap(:,1)(Y+1));
+%! assert (Id, newmap(:,2)(Y+1));
+%! assert (Id, newmap(:,3)(Y+1));
+
+## Random uint16 I image
+%!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));
+
+## Test input validation
+%!error cmpermute ()
+%!error cmpermute (1,2,3)
+%!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))
+%!error <MAP must be a valid colormap> cmunique (1, ones (3,2))
+%!error <MAP must be a valid colormap> cmunique (1, [-1 1 1])
+%!error <MAP must be a valid colormap> cmunique (1, [2 1 1])
+
new file mode 100644
--- /dev/null
+++ b/scripts/image/colorcube.m
@@ -0,0 +1,96 @@
+## 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{map} =} colorcube ()
+## @deftypefnx {Function File} {@var{map} =} colorcube (@var{n})
+## Create color colormap.  This colormap is composed of as many equally
+## spaced colors (not grays) in the RGB color space as possible.  If there
+## are not a perfect number @var{n} of regularly spaced colors then the
+## remaining entries in the colormap are gradients of pure red, green, blue,
+## and gray.
+## The argument @var{n} must be a scalar.
+## If unspecified, the length of the current colormap, or 64, is used.
+## @seealso{colormap}
+## @end deftypefn
+
+function map = colorcube (n)
+
+  if (nargin == 0)
+    n = rows (colormap);
+  elseif (nargin == 1)
+    if (! isscalar (n))
+      error ("colorcube: N must be a scalar");
+    endif
+  else
+    print_usage ();
+  endif
+
+  if (n < 9)
+    map = gray (n);
+    return;
+  endif
+
+  # Create colorcube of evenly spaced points with side length of n^1/3
+  cubelen = fix (cbrt (n));
+  reserve = n - cubelen^3; 
+
+  if (reserve == 0)
+    # Steal space from blue to put the gray gradient
+    [r, g, b] = meshgrid (linspace (0,1,cubelen),
+                          linspace (0,1,cubelen),
+                          linspace (0,1,cubelen-1));
+  else
+    [r, g, b] = meshgrid (linspace (0,1,cubelen),
+                          linspace (0,1,cubelen),
+                          linspace (0,1,cubelen));
+  endif
+
+  # Create map and weed out grays
+  map = [r(:), g(:), b(:)];
+  idx = any (bsxfun (@ne, map(:, 1), map(:, 2:3)), 2);
+  map = map(idx, :);
+
+  # Weed out pure colors
+  idx = sum (map == 0, 2);
+  map = map(idx != 2, :);
+
+  # Put in remaining gradients of pure red, green, blue, and gray
+  reserve = n - rows (map) - 1;
+  csteps = fix (reserve/4);
+  cstepsz = 1 / csteps;
+  cgrad = (cstepsz:cstepsz:1)';
+  gsteps = reserve - 3*csteps;
+  gstepsz = 1 / gsteps;
+  ggrad = (gstepsz:gstepsz:1)';
+  map = [map
+         cgrad, zeros(csteps, 1), zeros(csteps, 1)
+         zeros(csteps, 1), cgrad, zeros(csteps, 1)
+         zeros(csteps, 1), zeros(csteps, 1), cgrad 
+         0, 0, 0
+         ggrad, ggrad, ggrad];
+
+endfunction
+
+
+%!demo
+%! ## Show the 'colorcube' colormap as an image
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (colorcube (64));
+
--- a/scripts/image/colormap.m
+++ b/scripts/image/colormap.m
@@ -1,4 +1,5 @@
 ## Copyright (C) 1994-2012 John W. Eaton
+## Copyright (C) 2012 Carnë Draug
 ##
 ## This file is part of Octave.
 ##
@@ -17,18 +18,26 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {} colormap (@var{map})
-## @deftypefnx {Function File} {} colormap ("default")
-## Set the current colormap.
+## @deftypefn  {Function File} {@var{cmap} =} colormap ()
+## @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", "@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
-## color map should be an @var{n} row by 3 column matrix.  The columns
+## colormap should be an @var{n} row by 3 column matrix.  The columns
 ## contain red, green, and blue intensities respectively.  All entries
-## should be between 0 and 1 inclusive.  The new colormap is returned.
+## must be between 0 and 1 inclusive.  The new colormap is returned.
 ##
 ## @code{colormap ("default")} restores the default colormap (the
 ## @code{jet} map with 64 entries).  The default colormap is returned.
 ##
+## @code{colormap ("list")} returns a cell array with all the available
+## colormaps.  The options `register' and `unregister' will add or remove the
+## colormap @var{name} to it.
+##
 ## With no arguments, @code{colormap} returns the current color map.
 ## @seealso{jet}
 ## @end deftypefn
@@ -37,33 +46,49 @@
 ## Created: July 1994
 ## Adapted-By: jwe
 
-function cmap = colormap (map)
+function cmap = colormap (map, name)
 
-  if (nargin > 1)
+  if (nargin > 2)
     print_usage ();
   endif
 
+  persistent map_list = cell ();
+
   if (nargin == 1)
 
     if (ischar (map))
       if (strcmp (map, "default"))
         map = jet (64);
+      elseif (strcmp (map, "list"))
+        cmap = map_list;
+        return;
       else
         map = feval (map);
       endif
     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);
     endif
 
+  elseif (nargin == 2)
+    if (! ischar (map) || all (! strcmp (map, {"register", "unregister"})))
+      print_usage ();
+    elseif (! ischar (name))
+      error ("colormap: to register/unregister a colormap, NAME must be a string");
+    elseif (strcmp (map, "register"))
+      map_list{end+1} = name;
+    elseif (strcmp (map, "unregister"))
+      map_list(strcmp (name, map_list)) = [];
+    endif
   endif
 
   ## Return current color map.
@@ -72,3 +97,6 @@
   endif
 
 endfunction
+
+
+%% FIXME: Need some demos/tests
--- a/scripts/image/contrast.m
+++ b/scripts/image/contrast.m
@@ -17,17 +17,18 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} 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 instead.
-## @seealso{colormap}
+## 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");
@@ -38,13 +39,26 @@
 
   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
 
-%!assert (contrast(1:100,10),[([0:9]/9)',([0:9]/9)',([0:9]/9)'],1e-10)
+
 %!demo
-%! image (reshape (1:100, 10, 10))
-%! colormap (contrast (1:100,10))
+%! 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) + 25;
+%! figure ("position", pos); 
+%! colormap (contrast (img, 10));
+%! imagesc (img);
+%! title ("Image with contrast enhanced");
+
+%!assert (contrast (1:100,10), [([0:9]/9)',([0:9]/9)',([0:9]/9)'], 1e-10)
+
--- a/scripts/image/cool.m
+++ b/scripts/image/cool.m
@@ -27,13 +27,16 @@
 
 ## Author:  Kai Habel <kai.habel@gmx.de>
 
+## PKG_ADD: colormap ("register", "cool");
+## PKG_DEL: colormap ("unregister", "cool");
+
 function map = cool (n)
 
   if (nargin == 0)
     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 ();
@@ -42,19 +45,20 @@
   if (n == 1)
     map = [0, 1, 1];
   elseif (n > 1)
-    r = (0:n - 1)' ./ (n - 1);
+    r = [0:(n-1)]' / (n - 1);
     g = 1 - r;
     b = ones (n, 1);
     map = [r, g, b];
   else
-    map = [];
+    map = zeros (0, 3);
   endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'cool' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (cool (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (cool (64));
 
--- a/scripts/image/copper.m
+++ b/scripts/image/copper.m
@@ -28,13 +28,16 @@
 
 ## Author:  Kai Habel <kai.habel@gmx.de>
 
+## PKG_ADD: colormap ("register", "copper");
+## PKG_DEL: colormap ("unregister", "copper");
+
 function map = copper (n)
 
   if (nargin == 0)
     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 ();
@@ -43,20 +46,22 @@
   if (n == 1)
     map = [0, 0, 0];
   elseif (n > 1)
-    x = linspace (0, 1, n)';
-    r = (x < 4/5) .* (5/4 * x) + (x >= 4/5);
-    g = 4/5 * x;
-    b = 1/2 * x;
+    x = [0:(n-1)]' / (n - 1);
+    r = (x < 4/5) .* (5/4 * x) ...
+      + (x >= 4/5);
+    g = 0.7812 * x;
+    b = 0.4975 * x;
     map = [r, g, b];
   else
-    map = [];
+    map = zeros (0, 3);
   endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'copper' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (copper (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (copper (64));
 
--- a/scripts/image/flag.m
+++ b/scripts/image/flag.m
@@ -19,7 +19,7 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {@var{map} =} flag ()
 ## @deftypefnx {Function File} {@var{map} =} flag (@var{n})
-## Create color colormap.  This colormap cycles through red, white, blue
+## Create color colormap.  This colormap cycles through red, white, blue,
 ## and black with each index change.
 ## The argument @var{n} must be a scalar.
 ## If unspecified, the length of the current colormap, or 64, is used.
@@ -28,32 +28,36 @@
 
 ## Author:  Kai Habel <kai.habel@gmx.de>
 
+## PKG_ADD: colormap ("register", "flag");
+## PKG_DEL: colormap ("unregister", "flag");
+
 function map = flag (n)
 
   if (nargin == 0)
     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 ();
   endif
 
-  p = [1, 0, 0; 1, 1, 1; 0, 0, 1; 0, 0, 0];
-  if (rem(n,4) == 0)
-    map = kron (ones (n / 4, 1), p);
+  if (n == 1)
+    map = [1, 0, 0];
+  elseif (n > 1)
+    C = [1, 0, 0; 1, 1, 1; 0, 0, 1; 0, 0, 0];
+    map = C(rem (0:(n-1), 4) + 1, :);
   else
-    m1 = kron (ones (fix (n / 4), 1), p);
-    m2 = p(1:rem (n, 4), :);
-    map = [m1; m2];
+    map = zeros (0, 3);
   endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'flag' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (flag (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (flag (64));
 
--- a/scripts/image/gmap40.m
+++ b/scripts/image/gmap40.m
@@ -23,35 +23,39 @@
 ## magenta and cyan.  This colormap is specifically designed for users of
 ## gnuplot 4.0 where these 6 colors are the allowable ones for patch objects.
 ## The argument @var{n} must be a scalar.
-## If unspecified, a length of 6 is assumed.  Larger values
-## of @var{n} result in a repetition of the above colors.
+## If unspecified, a length of 6 is assumed.  Larger values of @var{n} result
+## in a repetition of the above colors.
 ## @seealso{colormap}
 ## @end deftypefn
 
+## PKG_ADD: colormap ("register", "gmap40");
+## PKG_DEL: colormap ("unregister", "gmap40");
+
 function map = gmap40 (n)
 
   if (nargin == 0)
     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 ();
   endif
 
-  if (n >= 1)
-    map = repmat ([1, 0, 0; 0, 1, 0; 0, 0, 1; 1, 1, 0; 1, 0, 1; 0, 1, 1],
-          ceil (n / 6), 1) (1:n, :);
+  if (n > 1)
+    C = [1, 0, 0; 0, 1, 0; 0, 0, 1; 1, 1, 0; 1, 0, 1; 0, 1, 1];
+    map = C(rem (0:(n-1), 6) + 1, :);
   else
-    map = [];
+    map = zeros (0, 3);
   endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'gmap40' colormap as an image
-%! image (1:6, linspace (0, 1, 6), repmat (1:6, 6, 1)')
-%! axis ([1, 6, 0, 1], "ticy", "xy")
-%! colormap (gmap40 (6))
+%! image (1:6, linspace (0, 1, 6), repmat ((1:6)', 1, 6));
+%! axis ([1, 6, 0, 1], "ticy", "xy");
+%! colormap (gmap40 (6));
 
--- a/scripts/image/gray.m
+++ b/scripts/image/gray.m
@@ -23,33 +23,43 @@
 ## shades of gray.
 ## The argument @var{n} must be a scalar.
 ## If unspecified, the length of the current colormap, or 64, is used.
+## @seealso{colormap}
 ## @end deftypefn
 
 ## Author: Tony Richardson <arichard@stark.cc.oh.us>
 ## Created: July 1994
 ## Adapted-By: jwe
 
+## PKG_ADD: colormap ("register", "gray");
+## PKG_DEL: colormap ("unregister", "gray");
+
 function map = gray (n)
 
   if (nargin == 0)
     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 ();
   endif
 
-  gr = [0:(n-1)]';
-
-  map = [ gr, gr, gr ] / (n - 1);
+  if (n == 1)
+    map = [0, 0, 0];
+  elseif (n > 1)
+    gr = [0:(n-1)]' / (n - 1);
+    map = [gr, gr, gr];
+  else
+    map = zeros (0, 3);
+  endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'gray' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (gray (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (gray (64));
 
--- a/scripts/image/gray2ind.m
+++ b/scripts/image/gray2ind.m
@@ -17,45 +17,93 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {[@var{img}, @var{map}] =} gray2ind (@var{I}, @var{n})
-## Convert a gray scale intensity image to an Octave indexed image.
-## The indexed image will consist of @var{n} different intensity values.  If not
-## given @var{n} will default to 64.
+## @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 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
+++ b/scripts/image/hot.m
@@ -28,35 +28,54 @@
 
 ## Author:  Kai Habel <kai.habel@gmx.de>
 
+## PKG_ADD: colormap ("register", "hot");
+## PKG_DEL: colormap ("unregister", "hot");
+
 function map = hot (n)
 
   if (nargin == 0)
     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 ();
   endif
 
   if (n == 1)
-    map = [0, 0, 0];
-  elseif (n > 1)
-    x = linspace (0, 1, n)';
-    r = (x < 2/5) .* (5/2 * x) + (x >= 2/5);
-    g = (x >= 2/5 & x < 4/5) .* (5/2 * x - 1) + (x >= 4/5);
-    b = (x >= 4/5) .* (5*x - 4);
+    map = [1, 1, 1];
+  elseif (n == 2)
+    map = [1, 1, 1/2
+           1, 1,  1 ];
+  elseif (n > 2)
+    idx = floor (3/8 * n);
+    nel = idx;
+
+    r = ones (n, 1);
+    r(1:idx, 1) = [1:nel]' / nel;
+
+    g = zeros (n, 1);
+    g(idx+1:2*idx, 1) = r(1:idx);
+    g(2*idx+1:end, 1) = 1;
+
+    idx = 2*idx + 1;   # approximately 3/4 *n
+    nel = n - idx + 1;
+
+    b = zeros (n, 1);
+    b(idx:end, 1) = [1:nel]' / nel;
+
     map = [r, g, b];
   else
-    map = [];
+    map = zeros (0, 3);
   endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'hot' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (hot (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (hot (64));
 
--- a/scripts/image/hsv.m
+++ b/scripts/image/hsv.m
@@ -20,10 +20,10 @@
 ## @deftypefn {Function File} {} hsv (@var{n})
 ## Create color colormap.  This colormap begins with red, changes through
 ## yellow, green, cyan, blue, and magenta, before returning to red.
-## It is useful for displaying periodic functions.  It is obtained by linearly
-## varying the hue through all possible values while keeping constant maximum
-## saturation and value and is equivalent to
-## @code{hsv2rgb ([linspace(0,1,N)', ones(N,2)])}.
+## It is useful for displaying periodic functions.  The map is obtained by
+## linearly varying the hue through all possible values while keeping constant
+## maximum saturation and value.  The equivalent code is
+## @code{hsv2rgb ([(0:N-1)'/N, ones(N,2)])}.
 ##
 ## The argument @var{n} must be a scalar.
 ## If unspecified, the length of the current colormap, or 64, is used.
@@ -32,13 +32,16 @@
 
 ## Author:  Kai Habel <kai.habel@gmx.de>
 
+## PKG_ADD: colormap ("register", "hsv");
+## PKG_DEL: colormap ("unregister", "hsv");
+
 function map = hsv (n)
 
   if (nargin == 0)
     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 ();
@@ -47,17 +50,18 @@
   if (n == 1)
     map = [1, 0, 0];
   elseif (n > 1)
-    h = linspace (0, 1, n)';
-    map = hsv2rgb ([h, ones(n, 1), ones(n, 1)]);
+    hue = [0:n-1]' / n;
+    map = hsv2rgb ([hue, ones(n,1), ones(n,1)]);
   else
-    map = [];
+    map = zeros (0, 3);
   endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'hsv' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (hsv (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (hsv (64));
 
--- a/scripts/image/hsv2rgb.m
+++ b/scripts/image/hsv2rgb.m
@@ -17,9 +17,18 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {@var{rgb_map} =} hsv2rgb (@var{hsv_map})
-## Transform a colormap or image from the HSV space to the RGB space.
-## @seealso{rgb2hsv}
+## @deftypefn  {Function File} {@var{rgb_map} =} hsv2rgb (@var{hsv_map})
+## @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
 
 ## Author: Kai Habel <kai.habel@gmx.de>
@@ -27,61 +36,94 @@
 
 function rgb_map = hsv2rgb (hsv_map)
 
-## Each color value x = (r,g,b) is calculated with
-## x = (1-sat)*val+sat*val*f_x(hue)
-## where f_x(hue) is a piecewise defined function for
-## each color with f_r(hue-2/3) = f_g(hue) = f_b(hue-1/3).
+  ## Each color value x = (r,g,b) is calculated with
+  ## x = (1-sat)*val+sat*val*f_x(hue)
+  ## where f_x(hue) is a piecewise defined function for
+  ## each color with f_r(hue-2/3) = f_g(hue) = f_b(hue-1/3).
 
   if (nargin != 1)
     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
+++ b/scripts/image/image.m
@@ -19,25 +19,31 @@
 ## -*- 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.  The elements of @var{img} are indices
-## into the current colormap, and the colormap will be scaled so that the
-## extremes of @var{img} are mapped to the extremes of the colormap.
+## Display a matrix as an indexed color image.
 ##
-## The axis values corresponding to the matrix elements are specified in
-## @var{x} and @var{y}.  If you're not using gnuplot 4.2 or later, these
-## variables are ignored.
+## The elements of @var{img} are indices into the current colormap.
+## @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.
 ##
 ## Implementation Note: The origin (0, 0) for images is located in the
 ## upper left.  For ordinary plots, the origin is located in the lower
 ## left.  Octave handles this inversion by plotting the data normally,
 ## and then reversing the direction of the y-axis by setting the
-## @code{ydir} property to @code{"reverse"}.  This has implications whenever
+## @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)}.
 ##
-## The optional return value @var{h} is a graphics handle to the image.
 ## @seealso{imshow, imagesc, colormap}
 ## @end deftypefn
 
@@ -45,44 +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;
+    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
@@ -90,7 +90,7 @@
 ## Generic image creation.
 ##
 ## The axis values corresponding to the matrix elements are specified in
-## @var{x} and @var{y}. If you're not using gnuplot 4.2 or later, these
+## @var{x} and @var{y}.  If you're not using gnuplot 4.2 or later, these
 ## variables are ignored.
 
 ## Author: Tony Richardson <arichard@stark.cc.oh.us>
@@ -105,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
@@ -113,34 +120,38 @@
     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, size(img,2)-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, size(img,1)-1];
+    ydata = ydata(1) + [0, rows(img)-1];
   endif
   xlim = xdata + [-px(1), px(1)];
   ylim = ydata + [-px(2), px(2)];
@@ -155,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
@@ -170,69 +181,29 @@
   endif
 
   if (nargout > 0)
-    h = tmp;
+    h = htmp;
   endif
 
 endfunction
 
-%!demo
-%! clf
-%! img = 1 ./ hilb (11);
-%! x = -5:5;
-%! y = x;
-%! 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)')
-%! 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
-%! 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")
+%! clf;
+%! colormap (jet (21));
+%! img = 1 ./ hilb (11);
+%! x = y = -5:5;
+%! subplot (2,2,1);
+%!  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);
+%!  title ("image (-x, y, img)");
+%! subplot (2,2,3);
+%!  h = image (x, -y, img);
+%!  title ("image (x, -y, img)");
+%!  ylabel ("limits = [-5.5, 5.5]");
+%! subplot (2,2,4);
+%!  h = image (-x, -y, img);
+%!  title ("image (-x, -y, img)");
 
-%!demo
-%! clf
-%! 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
-%! 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
+++ b/scripts/image/imagesc.m
@@ -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
-## range is set to the 'clim' of the current axes.
+## 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
+++ b/scripts/image/imfinfo.m
@@ -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/imread.m
+++ b/scripts/image/imread.m
@@ -89,6 +89,7 @@
 
 endfunction
 
+
 %!testif HAVE_MAGICK
 %! vpng = [ ...
 %!  137,  80,  78,  71,  13,  10,  26,  10,   0,   0, ...
@@ -107,11 +108,12 @@
 %!   16,  28, 160,  16,   0, 197, 214,  13,  34,  74, ...
 %!  117, 213,  17,   0,   0,   0,   0,  73,  69,  78, ...
 %!   68, 174,  66,  96, 130];
-%! fid = fopen('test.png', 'wb');
-%! fwrite(fid, vpng);
-%! fclose(fid);
-%! A = imread('test.png');
-%! delete('test.png');
-%! assert(A(:,:,1), uint8 ([0, 255, 0; 255, 237, 255; 0, 255, 0]));
-%! assert(A(:,:,2), uint8 ([0, 255, 0; 255,  28, 255; 0, 255, 0]));
-%! assert(A(:,:,3), uint8 ([0, 255, 0; 255,  36, 255; 0, 255, 0]));
+%! fid = fopen ("test.png", "wb");
+%! fwrite (fid, vpng);
+%! fclose (fid);
+%! A = imread ("test.png");
+%! delete ("test.png");
+%! assert (A(:,:,1), uint8 ([0, 255, 0; 255, 237, 255; 0, 255, 0]));
+%! assert (A(:,:,2), uint8 ([0, 255, 0; 255,  28, 255; 0, 255, 0]));
+%! assert (A(:,:,3), uint8 ([0, 255, 0; 255,  36, 255; 0, 255, 0]));
+
--- a/scripts/image/imshow.m
+++ b/scripts/image/imshow.m
@@ -25,7 +25,7 @@
 ## @deftypefnx {Function File} {} imshow (@dots{}, @var{string_param1}, @var{value1}, @dots{})
 ## @deftypefnx {Function File} {@var{h} =} imshow (@dots{})
 ## Display the image @var{im}, where @var{im} can be a 2-dimensional
-## (gray-scale image) or a 3-dimensional (RGB image) matrix.
+## (grayscale image) or a 3-dimensional (RGB image) matrix.
 ##
 ## If @var{limits} is a 2-element vector @code{[@var{low}, @var{high}]},
 ## the image is shown using a display range between @var{low} and
@@ -41,6 +41,7 @@
 ##
 ## If given, the parameter @var{string_param1} has value
 ## @var{value1}.  @var{string_param1} can be any of the following:
+##
 ## @table @asis
 ## @item "displayrange"
 ## @var{value1} is the display range as described above.
@@ -176,35 +177,46 @@
 
 endfunction
 
-%!error imshow ()                           # no arguments
-%!error imshow ({"cell"})                   # No image or filename given
-%!error imshow (ones(4,4,4))                # Too many dimensions in image
+
+%!demo
+%! clf;
+%! imshow ("default.img");
 
 %!demo
-%!  imshow ("default.img");
+%! clf;
+%! imshow ("default.img");
+%! colormap (autumn (64));
 
 %!demo
-%!  imshow ("default.img");
-%!  colormap ("autumn");
+%! clf;
+%! [I, M] = imread ("default.img");
+%! imshow (I, M);
 
 %!demo
-%!  [I, M] = imread ("default.img");
-%!  imshow (I, M);
+%! clf;
+%! [I, M] = imread ("default.img");
+%! [R, G, B] = ind2rgb (I, M);
+%! imshow (cat (3, R, G*0.5, B*0.8));
 
 %!demo
-%!  [I, M] = imread ("default.img");
-%!  [R, G, B] = ind2rgb (I, M);
-%!  imshow (cat(3, R, G*0.5, B*0.8));
+%! clf;
+%! imshow (rand (100, 100));
 
 %!demo
-%!  imshow (rand (100, 100));
+%! clf;
+%! imshow (rand (100, 100, 3));
 
 %!demo
-%!  imshow (rand (100, 100, 3));
+%! clf;
+%! imshow (100*rand (100, 100, 3));
 
 %!demo
-%!  imshow (100*rand (100, 100, 3));
+%! clf;
+%! imshow (rand (100, 100));
+%! colormap (jet (64));
 
-%!demo
-%!  imshow (rand (100, 100));
-%!  colormap (jet);
+%% Test input validation
+%!error imshow ()
+%!error <IM must be an image> imshow ({"cell"})
+%!error <expecting MxN or MxNx3 matrix> imshow (ones (4,4,4))
+
--- a/scripts/image/imwrite.m
+++ b/scripts/image/imwrite.m
@@ -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
@@ -161,17 +161,12 @@
     else
       error ("imwrite: %s: invalid class for indexed image data", img_class);
     endif
-    if (isa (map, "double"))
-      if (ndims (map) != 2 || size (map, 2) != 3)
-        error ("imwrite: invalid size for colormap");
-      endif
-    else
-      error ("imwrite: %s invalid class for indexed image colormap",
-             class (map));
+    if (! iscolormap (map))
+      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);
@@ -187,14 +182,15 @@
 
 endfunction
 
+
 %% Test input validation
-%!error imwrite ()                           # Wrong # of args
-%!error imwrite (1)                          # Wrong # of args
-%!error imwrite ({"cell"}, "filename.jpg")   # Wrong class for img
-%!error imwrite (1, [], "filename.jpg")      # Empty image map
-%!error imwrite (1, 2, 3)                    # No filename specified
-%!error imwrite (1, "filename")              # No fmt specified
-%!error imwrite (1, "filename", "junk")      # Invalid fmt specified
-%!error imwrite ([], "filename.jpg")         # Empty img matrix
-%!error imwrite (spones(2), "filename.jpg")  # Invalid sparse img
+%!error imwrite ()                            # Wrong # of args
+%!error imwrite (1)                           # Wrong # of args
+%!error imwrite ({"cell"}, "filename.jpg")    # Wrong class for img
+%!error imwrite (1, [], "filename.jpg")       # Empty image map
+%!error imwrite (1, 2, 3)                     # No filename specified
+%!error imwrite (1, "filename")               # No fmt specified
+%!error imwrite (1, "filename", "junk")       # Invalid fmt specified
+%!error imwrite ([], "filename.jpg")          # Empty img matrix
+%!error imwrite (spones (2), "filename.jpg")  # Invalid sparse img
 
--- a/scripts/image/ind2gray.m
+++ b/scripts/image/ind2gray.m
@@ -17,33 +17,74 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} ind2gray (@var{x}, @var{map})
-## Convert an Octave indexed image to a gray scale intensity image.
-## If @var{map} is omitted, the current colormap is used to determine the
-## intensities.
-## @seealso{gray2ind, rgb2ntsc, image, colormap}
+## @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
 
 ## Author: Tony Richardson <arichard@stark.cc.oh.us>
 ## 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
+++ b/scripts/image/ind2rgb.m
@@ -18,12 +18,20 @@
 
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {@var{rgb} =} ind2rgb (@var{x}, @var{map})
-## @deftypefnx {Function File} {[@var{R}, @var{R}, @var{R}] =} 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.
-## @seealso{rgb2ind, image, imshow, ind2gray, gray2ind}
+##
+## 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
 
 ## Author: Tony Richardson <arichard@stark.cc.oh.us>
@@ -32,41 +40,59 @@
 
 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
+  [x, map] = ind2x ("ind2rgb", x, map);
 
-  ## 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
+  ## Compute result
+  sz = size (x);
+  R = reshape (map(x(:), 1), sz);
+  G = reshape (map(x(:), 2), sz);
+  B = reshape (map(x(:), 3), sz);
 
-  ## Check the color map.
-  if (ndims (map) != 2 || columns (map) != 3)
-    error ("ind2rgb: MAP must be a valid colormap");
+  ## Use ND array if only one output is requested.
+  if (nargout <= 1)
+    R = reshape ([R(:); G(:); B(:)], [sz, 3]);
   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
+endfunction
+
 
-  ## 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);
+%!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)")
 
-  ## Use 3D array if only one output is requested.
-  if (nargout <= 1)
-    R(:,:,3) = B;
-    R(:,:,2) = G;
-  endif
-endfunction
+%% 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])
+
new file mode 100644
--- /dev/null
+++ b/scripts/image/iscolormap.m
@@ -0,0 +1,53 @@
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {} iscolormap (@var{cmap})
+## Return true if @var{cmap} is a colormap.
+##
+## 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
+
+## Author: Carnë Draug <carandraug+dev@gmail.com>
+
+function retval = iscolormap (cmap)
+
+  if (nargin != 1)
+    print_usage;
+  endif
+
+  retval = (isnumeric (cmap) && isreal (cmap) &&
+            ndims (cmap) == 2 && columns (cmap) == 3 && isa (cmap, "double") &&
+            min (cmap(:)) >= 0 && max (cmap(:)) <= 1);
+
+endfunction
+
+
+%!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 (single (jet (64))), false)
+%!assert (iscolormap ([0 0 -2]), false)
+%!assert (iscolormap ([0 0 2]), false)
+
--- a/scripts/image/jet.m
+++ b/scripts/image/jet.m
@@ -28,38 +28,73 @@
 
 ## Author:  Kai Habel <kai.habel@gmx.de>
 
+## PKG_ADD: colormap ("register", "jet");
+## PKG_DEL: colormap ("unregister", "jet");
+
 function map = jet (n)
 
   if (nargin == 0)
     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 ();
   endif
 
   if (n == 1)
-    map = [0, 0, 0.5];
-  elseif (n > 1)
-    x = linspace(0, 1, n)';
-    r = (x >= 3/8 & x < 5/8) .* (4 * x - 3/2)\
-      + (x >= 5/8 & x < 7/8) + (x >= 7/8) .* (-4 * x + 9/2);
-    g = (x >= 1/8 & x < 3/8) .* (4 * x - 1/2)\
-      + (x >= 3/8 & x < 5/8) + (x >= 5/8 & x < 7/8) .* (-4 * x + 7/2);
-    b = (x < 1/8) .* (4 * x + 1/2) + (x >= 1/8 & x < 3/8)\
-      + (x >= 3/8 & x < 5/8) .* (-4 * x + 5/2);
+    map = [0, 1, 1];
+  elseif (n == 2)
+    map = [0, 0, 1
+           0, 1, 1];
+  elseif (n > 2)
+    nel = ceil (n/4);           # number of elements
+    idx1 = ceil (3/8 * n) + 1;  # ~3/8*n for large n
+    if (mod (n, 8) == 2)
+      idx1++;
+    endif
+    idx2 = idx1 + nel - 1;      # ~5/8*n for large n
+    idx3 = min (idx2 + nel, n); # ~7/8*n for large n
+
+    r = zeros (n, 1);
+    r(idx1:idx2, 1) = [1:nel] / nel;
+    r(idx2:idx3, 1) = 1;
+    nel2 = n - idx3; 
+    r(idx3:(idx3+nel2), 1) = [nel:-1:(nel - nel2)] / nel;
+
+    idx1 = idx1 - nel;          # ~1/8*n for large n
+    idx2 = idx1 + nel - 1;      # ~3/8*n for large n
+    idx3 = min (idx2 + nel, n); # ~5/8*n for large n
+
+    g = zeros (n, 1);
+    g(idx1:idx2, 1) = [1:nel] / nel;
+    g(idx2:idx3, 1) = 1;
+    nel2 = min (nel, n - idx3); 
+    g(idx3:(idx3+nel2), 1) = [nel:-1:(nel - nel2)] / nel;
+
+    idx1 = max (idx2 - nel, 1); # ~1/8*n for large n
+    idx2 = idx2;                # ~3/8*n for large n
+    idx3 = idx3;                # ~5/8*n for large n
+
+    b = zeros (n, 1);
+    nel2 = min (nel, idx1-1); 
+    b(1:idx1, 1) = [(nel - nel2):nel] / nel;
+    b(idx1:idx2, 1) = 1;
+    nel2 = min (nel, n - idx3); 
+    b(idx2:(idx2+nel2), 1) = [nel:-1:(nel - nel2)] / nel;
+
     map = [r, g, b];
   else
-    map = [];
+    map = zeros (0, 3);
   endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'jet' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (jet (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (jet (64));
 
new file mode 100644
--- /dev/null
+++ b/scripts/image/lines.m
@@ -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  {Function File} {@var{map} =} lines ()
+## @deftypefnx {Function File} {@var{map} =} lines (@var{n})
+## Create color colormap.  This colormap is composed of the list of colors
+## in the current axes "ColorOrder" property.  The default is blue,
+## green, red, cyan, pink, yellow, and gray.
+## The argument @var{n} must be a scalar.
+## If unspecified, the length of the current colormap, or 64, is used.
+## @seealso{colormap}
+## @end deftypefn
+
+## PKG_ADD: colormap ("register", "lines");
+## PKG_DEL: colormap ("unregister", "lines");
+
+function map = lines (n)
+
+  if (nargin == 0)
+    n = rows (colormap);
+  elseif (nargin == 1)
+    if (! isscalar (n))
+      error ("lines: N must be a scalar");
+    endif
+  else
+    print_usage ();
+  endif
+
+  if (n == 1)
+    map = [0, 0, 1];
+  elseif (n > 1)
+    C = get (gca, "colororder");
+    nr = rows (C);
+    map = C(rem (0:(n-1), nr) + 1, :);
+  else
+    map = zeros (0, 3);
+  endif
+
+endfunction
+
+
+%!demo
+%! ## Show the 'lines' colormap as an image
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (lines (64));
+
--- a/scripts/image/module.mk
+++ b/scripts/image/module.mk
@@ -1,9 +1,15 @@
 FCN_FILE_DIRS += image
 
+image_PRIVATE_FCN_FILES = \
+  image/private/ind2x.m
+
 image_FCN_FILES = \
   image/autumn.m \
   image/bone.m \
   image/brighten.m \
+  image/cmpermute.m \
+  image/cmunique.m \
+  image/colorcube.m \
   image/colormap.m \
   image/contrast.m \
   image/cool.m \
@@ -15,6 +21,7 @@
   image/hot.m \
   image/hsv.m \
   image/hsv2rgb.m \
+  image/iscolormap.m \
   image/image.m \
   image/imagesc.m \
   image/imfinfo.m \
@@ -24,6 +31,7 @@
   image/ind2gray.m \
   image/ind2rgb.m \
   image/jet.m \
+  image/lines.m \
   image/ntsc2rgb.m \
   image/ocean.m \
   image/pink.m \
@@ -32,10 +40,13 @@
   image/rgb2hsv.m \
   image/rgb2ind.m \
   image/rgb2ntsc.m \
+  image/rgbplot.m \
+  image/spinmap.m \
   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
+++ b/scripts/image/ntsc2rgb.m
@@ -17,9 +17,22 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} ntsc2rgb (@var{yiq})
-## Transform a colormap or image from NTSC to RGB.
-## @seealso{rgb2ntsc}
+## @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) 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
 
 ## Author: Tony Richardson <arichard@stark.cc.oh.us>
@@ -32,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
+++ b/scripts/image/ocean.m
@@ -23,43 +23,52 @@
 ## of blue.
 ## The argument @var{n} must be a scalar.
 ## If unspecified, the length of the current colormap, or 64, is used.
+## @seealso{colormap}
 ## @end deftypefn
 
 ## Author: Tony Richardson <arichard@stark.cc.oh.us>
 ## Created: July 1994
 ## Adapted-By: jwe
 
+## PKG_ADD: colormap ("register", "ocean");
+## PKG_DEL: colormap ("unregister", "ocean");
+
 function map = ocean (n)
 
   if (nargin == 0)
     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 ();
   endif
 
-  cutin = fix (n/3);
+  if (n == 1)
+    map = [0, 0, 0];
+  elseif (n > 1)
+    cutin = fix (n/3);
 
-  dr = (n - 1) / cutin;
-
-  r = prepad ([0:dr:(n-1)], n)';
+    dr = (n - 1) / cutin;
+    r = prepad ([0:dr:(n-1)], n)';
 
-  dg = (n - 1) / (2 * cutin);
+    dg = (n - 1) / (2 * cutin);
+    g = prepad ([0:dg:(n-1)], n)';
 
-  g = prepad([0:dg:(n-1)], n)';
+    b = [0:(n-1)]';
 
-  b = [0:(n-1)]';
-
-  map = [ r, g, b ] / (n - 1);
+    map = [r, g, b] / (n - 1);
+  else
+    map = zeros (0, 3);
+  endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'ocean' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (ocean (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (ocean (64));
 
--- a/scripts/image/pink.m
+++ b/scripts/image/pink.m
@@ -28,38 +28,54 @@
 
 ## Author:  Kai Habel <kai.habel@gmx.de>
 
+## PKG_ADD: colormap ("register", "pink");
+## PKG_DEL: colormap ("unregister", "pink");
+
 function map = pink (n)
 
   if (nargin == 0)
     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 ();
   endif
 
   if (n == 1)
-    map = [0, 0, 0];
-  elseif (n > 1)
-    x = linspace (0, 1, n)';
-    r = (x < 3/8) .* (14/9 * x) + (x >= 3/8) .* (2/3 * x + 1/3);
-    g = (x < 3/8) .* (2/3 * x)\
-      + (x >= 3/8 & x < 3/4) .* (14/9 * x - 1/3)\
-      + (x >= 3/4) .* (2/3 * x + 1/3);
-    b = (x < 3/4) .* (2/3 * x) + (x >= 3/4) .* (2 * x - 1);
+    map = sqrt ([1/3, 1/3, 1/3]);
+  elseif (n == 2)
+    map = sqrt ([1/3, 1/3, 1/6
+                  1    1    1 ]);
+  elseif (n > 2)
+    x = [0:(n-1)]' / (n-1);
+    idx = floor (3/8 * n);
+    base = 1 / (3 * idx);
+
+    nel = idx;   # number of elements
+    r(1:idx,1) = linspace (base, 2/3*x(idx) + 1/3, nel);
+    r(idx+1:n,1) = 2/3*x(idx+1:n) + 1/3;
+
+    g(1:idx,1) = 2/3*x(1:idx);
+    g(idx:2*idx,1) = linspace (2/3*x(idx), 2/3*x(2*idx) + 1/3, nel+1);
+    g(2*idx+1:n,1) = 2/3*x(2*idx+1:n) + 1/3;
+
+    nel = n - 2*idx + 1;
+    b(1:2*idx,1) = 2/3*x(1:2*idx);
+    b(2*idx:n,1) = linspace (2/3*x(2*idx), 1, nel);
 
     map = sqrt ([r, g, b]);
   else
-    map = [];
+    map = zeros (0, 3);
   endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'pink' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (pink (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (pink (64));
 
--- a/scripts/image/prism.m
+++ b/scripts/image/prism.m
@@ -28,31 +28,36 @@
 
 ## Author:  Kai Habel <kai.habel@gmx.de>
 
+## PKG_ADD: colormap ("register", "prism");
+## PKG_DEL: colormap ("unregister", "prism");
+
 function map = prism (n)
 
   if (nargin == 0)
     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 ();
   endif
 
-  p = [1, 0, 0; 1, 1/2, 0; 1, 1, 0; 0, 1, 0; 0, 0, 1; 2/3, 0, 1];
-
-  if (rem (n, 6) == 0)
-    map = kron(ones (fix (n / 6), 1), p);
+  if (n == 1)
+    map = [1 0 0];
+  elseif (n > 1)
+    C = [1, 0, 0; 1, 1/2, 0; 1, 1, 0; 0, 1, 0; 0, 0, 1; 2/3, 0, 1];
+    map = C(rem (0:(n-1), 6) + 1, :);
   else
-    map = [kron(ones (fix (n / 6), 1), p); p(1:rem (n, 6), :)];
+    map = zeros (0, 3);
   endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'prism' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (prism (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (prism (64));
 
new file mode 100644
--- /dev/null
+++ b/scripts/image/private/ind2x.m
@@ -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
+++ b/scripts/image/rainbow.m
@@ -31,13 +31,16 @@
 ## this colormap is not part of matlab, it is like the prism
 ## colormap map but with a continuous map
 
+## PKG_ADD: colormap ("register", "rainbow");
+## PKG_DEL: colormap ("unregister", "rainbow");
+
 function map = rainbow (n)
 
   if (nargin == 0)
     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 ();
@@ -46,22 +49,30 @@
   if (n == 1)
     map = [1, 0, 0];
   elseif (n > 1)
-    x = linspace (0, 1, n)';
-    r = (x < 2/5) + (x >= 2/5 & x < 3/5) .* (-5 * x + 3)\
-      + (x >= 4/5) .* (10/3 * x - 8/3);
-    g = (x < 2/5) .* (5/2 * x) + (x >= 2/5 & x < 3/5)\
-      + (x >= 3/5 & x < 4/5) .* (-5 * x + 4);
-    b = (x >= 3/5 & x < 4/5) .* (5 * x - 3) + (x >= 4/5);
+    x = [0:(n-1)]' / (n - 1);
+
+    r = (  (x < 2/5)
+         + (x >= 2/5 & x < 3/5) .* (-5 * x + 3)
+         + (x >= 4/5) .* (10/3 * x - 8/3));
+
+    g = (  (x < 2/5) .* (5/2 * x)
+         + (x >= 2/5 & x < 3/5)
+         + (x >= 3/5 & x < 4/5) .* (-5 * x + 4));
+
+    b = (  (x >= 3/5 & x < 4/5) .* (5 * x - 3)
+         + (x >= 4/5));
+
     map = [r, g, b];
   else
-    map = [];
+    map = zeros (0, 3);
   endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'rainbow' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (rainbow (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (rainbow (64));
 
--- a/scripts/image/rgb2hsv.m
+++ b/scripts/image/rgb2hsv.m
@@ -17,16 +17,18 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {@var{hsv_map} =} rgb2hsv (@var{rgb})
-## Transform a colormap or image from the RGB space to the HSV space.
-##
-## A color in the RGB space consists of the red, green and blue intensities.
+## @deftypefn  {Function File} {@var{hsv_map} =} rgb2hsv (@var{rgb})
+## @deftypefnx {Function File} {@var{hsv_map} =} rgb2hsv (@var{rgb})
+## Transform a colormap or image from red-green-blue (RGB) space to
+## hue-saturation-value (HSV) space.
 ##
-## In the HSV space each color is represented by their hue, saturation
-## and value (brightness).  Value gives the amount of light in the color.
-## Hue describes the dominant wavelength.
-## Saturation is the amount of hue mixed into the color.
-## @seealso{hsv2rgb}
+## 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
+## (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.
+## @seealso{hsv2rgb, rgb2ind, rgb2ntsc}
 ## @end deftypefn
 
 ## Author: Kai Habel <kai.habel@gmx.de>
@@ -38,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
@@ -83,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;
@@ -94,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
+++ b/scripts/image/rgb2ind.m
@@ -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 RGB image to an Octave indexed image.
-## @seealso{ind2rgb, rgb2ntsc}
+## 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
+++ b/scripts/image/rgb2ntsc.m
@@ -17,9 +17,28 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} rgb2ntsc (@var{rgb})
-## Transform a colormap or image from RGB to NTSC.
-## @seealso{ntsc2rgb}
+## @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) 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
 
 ## Author: Tony Richardson <arichard@stark.cc.oh.us>
@@ -32,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))
+
new file mode 100644
--- /dev/null
+++ b/scripts/image/rgbplot.m
@@ -0,0 +1,92 @@
+## Copyright (C) 2012 Rik Wehbring
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn  {Function File} {} rgbplot (@var{cmap})
+## @deftypefnx {Function File} {} rgbplot (@var{cmap}, @var{style})
+## @deftypefnx {Function File} {@var{h} =} rgbplot (@dots{})
+## Plot the components of a colormap.
+##
+## 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 h = rgbplot (cmap, style = "profile")
+
+  if (nargin < 1 || nargin > 2)
+    print_usage ();
+  endif
+
+  if (! iscolormap (cmap))
+    error ("rgbplot: CMAP must be a valid colormap");
+  elseif (! ischar (style))
+    error ("rgbplot: STYLE must be a string");
+  endif
+
+  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)
+    h = htmp;
+  endif
+
+endfunction
+
+
+%!demo
+%! clf;
+%! subplot (1, 2, 1);
+%! rgbplot (ocean, "profile");
+%! subplot (1, 2, 2);
+%! rgbplot (ocean, "composite");
+
+%% Test input validation
+%!error rgbplot ()
+%!error rgbplot (1,2)
+%!error <CMAP must be a valid colormap> rgbplot ({0 1 0})
+%!error <STYLE must be a string> rgbplot ([0 1 0], 2)
+%!error <unknown style `nostyle'> rgbplot ([0 1 0], "nostyle")
+
rename from scripts/plot/spinmap.m
rename to scripts/image/spinmap.m
--- a/scripts/plot/spinmap.m
+++ b/scripts/image/spinmap.m
@@ -17,41 +17,56 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} spinmap (@var{t}, @var{inc})
-## Cycle the colormap for @var{t} seconds with an increment
-## of @var{inc}.  Both parameters are optional.  The default cycle time
-## is 5 seconds and the default increment is 2.
+## @deftypefn  {Function File} {} spinmap ()
+## @deftypefnx {Function File} {} spinmap (@var{t})
+## @deftypefnx {Function File} {} spinmap (@var{t}, @var{inc})
+## @deftypefnx {Function File} {} spinmap ("inf")
+## Cycle the colormap for @var{t} seconds with a color increment of @var{inc}.
+## Both parameters are optional.  The default cycle time is 5 seconds and the
+## default increment is 2.  If the option "inf" is given then cycle
+## continuously until @kbd{Control-C} is pressed.
 ##
-## A higher value of @var{inc} causes a faster cycle through the
-## colormap.
-## @seealso{gca, colorbar}
+## When rotating the original color 1 becomes color 2, color 2 becomes
+## color 3, etc.  A positive or negative increment is allowed and a higher
+## value of @var{inc} will cause faster cycling through the colormap.
+## @seealso{colormap}
 ## @end deftypefn
 
 ## Author: Kai Habel <kai.habel at gmx.de>
 
-function spinmap (t, inc)
+function spinmap (t = 5, inc = 2)
 
-  if (nargin == 0)
-    inc = 2;
-    t = 5;
-  elseif (nargin == 1)
-    inc = 2;
+  if (nargin > 2)
+    print_usage ();
+  elseif (ischar (t))
+    if (strcmpi (t, "inf")) 
+      t = Inf;
+    else
+      error ('spinmap: time T must be a real scalar or "inf"');
+    endif
+  elseif (! isscalar (t) || ! isreal (t))
+    error ("spinmap: time T must be a real scalar");
   endif
 
-  cmap = get (gcf (), "colormap");
-  clen = rows (cmap);
+  cmap = cmap_orig = get (gcf (), "colormap");
 
   t0 = clock;
-
   while (etime (clock, t0) < t)
-    for n = 1:inc:clen
-      newmap = shift (cmap, n, 1);
-      set (gcf (), "colormap", newmap);
-      drawnow ();
-    endfor
+    cmap = shift (cmap, inc, 1);
+    set (gcf (), "colormap", cmap);
+    drawnow ();
   endwhile
 
-  set (gcf (), "colormap", cmap);
+  set (gcf (), "colormap", cmap_orig);
 
 endfunction
 
+
+%!demo
+%! clf;
+%! colormap (rainbow (128));
+%! imagesc (1:8);
+%! axis off;
+%! title ("Rotate color bars to the right");
+%! spinmap (3, 1);
+
--- a/scripts/image/spring.m
+++ b/scripts/image/spring.m
@@ -27,13 +27,16 @@
 
 ## Author:  Kai Habel <kai.habel@gmx.de>
 
+## PKG_ADD: colormap ("register", "spring");
+## PKG_DEL: colormap ("unregister", "spring");
+
 function map = spring (n)
 
   if (nargin == 0)
     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 ();
@@ -43,18 +46,19 @@
     map = [1, 0, 1];
   elseif (n > 1)
     r = ones (n, 1);
-    g = (0:n - 1)' ./ (n - 1);
+    g = [0:(n-1)]' / (n - 1);
     b = 1 - g;
     map = [r, g, b];
   else
-    map = [];
+    map = zeros (0, 3);
   endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'spring' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (spring (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (spring (64));
 
--- a/scripts/image/summer.m
+++ b/scripts/image/summer.m
@@ -27,13 +27,17 @@
 
 ## Author:  Kai Habel <kai.habel@gmx.de>
 ## Date:  06/03/2000
+
+## PKG_ADD: colormap ("register", "summer");
+## PKG_DEL: colormap ("unregister", "summer");
+
 function map = summer (n)
 
   if (nargin == 0)
     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 ();
@@ -42,20 +46,20 @@
   if (n == 1)
     map = [0, 0.5, 0.4];
   elseif (n > 1)
-    r = (0:n - 1)' ./ (n - 1);
-    g = 0.5 + r ./ 2;
+    r = [0:(n-1)]' / (n - 1);
+    g = 0.5 + r / 2;
     b = 0.4 * ones (n, 1);
-
     map = [r, g, b];
   else
-    map = [];
+    map = zeros (0, 3);
   endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'summer' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (summer (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (summer (64));
 
--- a/scripts/image/white.m
+++ b/scripts/image/white.m
@@ -27,29 +27,29 @@
 
 ## Author:  Kai Habel <kai.habel@gmx.de>
 
+## PKG_ADD: colormap ("register", "white");
+## PKG_DEL: colormap ("unregister", "white");
+
 function map = white (n)
 
   if (nargin == 0)
     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 ();
   endif
 
-  if (n > 0)
-    map = ones (n, 3);
-  else
-    map = [];
-  endif
+  map = ones (n, 3);
 
 endfunction
 
+
 %!demo
 %! ## Show the 'white' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (white (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (white (64));
 
--- a/scripts/image/winter.m
+++ b/scripts/image/winter.m
@@ -27,13 +27,16 @@
 
 ## Author:  Kai Habel <kai.habel@gmx.de>
 
+## PKG_ADD: colormap ("register", "winter");
+## PKG_DEL: colormap ("unregister", "winter");
+
 function map = winter (n)
 
   if (nargin == 0)
     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 ();
@@ -43,19 +46,19 @@
     map = [0, 0, 1];
   elseif (n > 1)
     r = zeros (n, 1);
-    g = (0:n - 1)' ./ (n - 1);
-    b = 1 - g ./ 2;
-
+    g = [0:(n-1)]' / (n - 1);
+    b = 1 - g / 2;
     map = [r, g, b];
   else
-    map = [];
+    map = zeros (0, 3);
   endif
 
 endfunction
 
+
 %!demo
 %! ## Show the 'winter' colormap as an image
-%! image (1:64, linspace (0, 1, 64), repmat (1:64, 64, 1)')
-%! axis ([1, 64, 0, 1], "ticy", "xy")
-%! colormap (winter (64))
+%! image (1:64, linspace (0, 1, 64), repmat ((1:64)', 1, 64));
+%! axis ([1, 64, 0, 1], "ticy", "xy");
+%! colormap (winter (64));
 
--- a/scripts/io/dlmwrite.m
+++ b/scripts/io/dlmwrite.m
@@ -146,7 +146,7 @@
       elseif (i == 3)
         c = varargin{i};
       else
-        print_usage();
+        print_usage ();
       endif
     endif
   endwhile
@@ -180,7 +180,7 @@
     endif
     if (iscomplex (M))
       M = M.';
-      b = zeros (2*rows(M), columns (M));
+      b = zeros (2*rows (M), columns (M));
       b(1: 2 : end, :) = real (M);
       b(2: 2 : end, :) = imag (M);
       fprintf (fid, template, b);
@@ -197,13 +197,13 @@
 
 %!test
 %! f = tmpnam ();
-%! dlmwrite (f,[1,2;3,4],'precision','%5.2f','newline','unix','roffset',1,'coffset',1);
+%! dlmwrite (f,[1,2;3,4],"precision","%5.2f","newline","unix","roffset",1,"coffset",1);
 %! fid = fopen (f,"rt");
-%! f1 = char (fread (fid,Inf,'char')');
+%! f1 = char (fread (fid,Inf,"char")');
 %! fclose (fid);
-%! dlmwrite (f,[5,6],'precision','%5.2f','newline','unix','coffset',1,'delimiter',',','-append');
+%! dlmwrite (f,[5,6],"precision","%5.2f","newline","unix","coffset",1,"delimiter",",","-append");
 %! fid = fopen (f,"rt");
-%! f2 = char (fread (fid,Inf,'char')');
+%! f2 = char (fread (fid,Inf,"char")');
 %! fclose (fid);
 %! unlink (f);
 %!
--- a/scripts/io/fileread.m
+++ b/scripts/io/fileread.m
@@ -38,7 +38,7 @@
   endif
 
   unwind_protect
-    str = fread (fid, "*char");
+    str = (fread (fid, "*char")).';
   unwind_protect_cleanup
     fclose (fid);
   end_unwind_protect
@@ -50,10 +50,10 @@
 %! cstr = {"Hello World", "The answer is 42", "Goodbye World"};
 %! fname = tmpnam ();
 %! fid = fopen (fname, "w");
-%! fprintf (fid, "%s\n", cstr{:})
+%! fprintf (fid, "%s\n", cstr{:});
 %! fclose (fid);
 %! str = fileread (fname);
-%! assert (str', [cstr{1} "\n" cstr{2} "\n" cstr{3} "\n"]);
+%! assert (str, [cstr{1} "\n" cstr{2} "\n" cstr{3} "\n"]);
 %! unlink (fname);
 
 %% Test input validation
new file mode 100644
--- /dev/null
+++ b/scripts/io/importdata.m
@@ -0,0 +1,436 @@
+## Copyright (C) 2012 Erik Kjellson
+##
+## 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{A} =} importdata (@var{fname})
+## @deftypefnx {Function File} {@var{A} =} importdata (@var{fname}, @var{delimiter})
+## @deftypefnx {Function File} {@var{A} =} importdata (@var{fname}, @var{delimiter}, @var{header_rows})
+## @deftypefnx {Function File} {[@var{A}, @var{delimiter}] =} importdata (@dots{})
+## @deftypefnx {Function File} {[@var{A}, @var{delimiter}, @var{header_rows}] =} importdata (@dots{})
+## Importing data from file.
+##
+## Importing the contents of file @var{fname} into workspace.
+##
+## Input parameters:
+## @itemize
+## @item @var{fname}
+## The file name for the file to import.
+## 
+## @item @var{delimiter}
+## The character separating columns of data. Use @code{\t} for tab.
+## (Only valid for ascii files)
+##
+## @item @var{header_rows}
+## Number of header rows before the data begins. (Only valid for ascii files)
+## @end itemize
+##
+## Different file types are supported:
+## @itemize
+## @item Ascii table
+##
+## Importing ascii table using the specified number of header rows and
+## the specified delimiter.
+##
+## @item Image file
+##
+## @item @sc{Matlab} file
+##
+## @item Spreadsheet files (depending on external software)
+##
+## @item Wav file
+##
+## @end itemize
+##
+## @seealso{textscan, dlmread, csvread, load}
+## @end deftypefn
+
+## Author: Erik Kjellson <erikiiofph7@users.sourceforge.net>
+
+function [output, delimiter, header_rows] = importdata (varargin)
+
+  ## Default values
+  fname   = "";
+  delimiter  = "";
+  header_rows = -1;
+
+  ##########
+
+  ## Check input arguments
+
+  if (nargin < 1)
+    print_usage ();
+  endif
+
+  fname = varargin{1};
+  ## Check that the file name really is a string
+  if (! ischar (fname))
+    error ("importdata: file name needs to be a string");
+  endif
+  if ( strcmpi (fname, "-pastespecial"))
+    error ("importdata: option -pastespecial not implemented");
+  endif
+
+  if (nargin > 1)
+    delimiter = varargin{2};
+    ## Check that the delimiter really is a string
+    if (!ischar (delimiter))
+      error("importdata: delimiter needs to be a character");
+    endif
+    if (length (delimiter) > 1 && !strcmpi (delimiter, "\\t"))
+      error("importdata: delimiter cannot be longer than 1 character");
+    endif
+    if (strcmpi (delimiter, "\\"))
+      delimiter = "\\\\";
+    endif
+  endif
+
+  if (nargin > 2)
+    header_rows = varargin{3};
+    if (!isnumeric (header_rows) || header_rows < 0)
+      error ("importdata: number of header rows needs to be an integer number >= 0");
+    endif
+  endif
+
+  if (nargin > 3)
+    error ("importdata: too many input arguments");
+  endif
+
+  ##########
+
+  ## Check file format
+  ## Get the extension from the file name.
+  [d n fileExt v] = fileparts (fname);
+  ## Make sure file extension is in lower case.
+  fileExt = lower (fileExt);
+
+  switch fileExt
+    case {".au", ".snd"}
+      error (sprintf ("importdata: not implemented for file format %s", 
+                      fileExt));
+    case ".avi"
+      error (sprintf ("importdata: not implemented for file format %s", 
+                      fileExt));
+    case {".bmp", ".cur", ".gif", ".hdf", ".ico", ".jpe", ".jpeg", ".jpg", \
+          ".pbm", ".pcx", ".pgm", ".png", ".pnm", ".ppm", ".ras", \
+          ".tif", ".tiff", ".xwd"}
+      delimiter  = NaN;
+      header_rows = 0;
+      [output.cdata, output.colormap, output.alpha] = imread (fname);
+    case ".mat"
+      delimiter  = NaN;
+      header_rows = 0;
+      output = load (fname);
+    case {".wk1", ".xls", ".xlsx", ".dbf", ".pxl"}
+      ## If there's no Excel file support simply fall back to unimplemented.m
+      output = xlsread (fname);
+    case {".ods", ".sxc", ".fods", ".uos", ".xml"}
+      ## unimplemented.m only knows ML functions; odsread isn't one but is in OF
+      try
+        output = odsread (fname);
+      catch
+        ## Fall back to unimplemented.m.
+        output = xlsread (fname);
+      end_try_catch
+    case {".wav", ".wave"}
+      delimiter  = NaN;
+      header_rows = 0;
+      [output.data, output.fs] = wavread (fname);
+    otherwise
+      ## Assume the file is in ascii format.
+      [output, delimiter, header_rows]  = \
+          importdata_ascii (fname, delimiter, header_rows);
+  endswitch
+
+  ## If there are any empty fields in the output structure, then remove them
+  if (isstruct (output) && length (output) == 1)
+    fields = fieldnames (output);
+    for i=1:length (fields)
+      if (isempty (getfield (output, fields{i})))
+        output = rmfield (output, fields{i});
+      endif
+    endfor
+
+    ## If only one field is left, replace the structure with the field,
+    ## i.e. output = output.onlyFieldLeft
+
+    ## Update the list of fields
+    fields = fieldnames (output);
+    if (length (fields) == 1)
+      output = getfield (output, fields{1});
+    endif
+  endif
+endfunction
+
+
+########################################
+
+function [output, delimiter, header_rows] = \
+      importdata_ascii (fname, delimiter, header_rows)
+
+  ## Define the fields in the output structure so that the order will be
+  ## correct.
+
+  output.data       = [];
+  output.textdata   = [];
+  output.rowheaders = [];
+  output.colheaders = [];
+
+  ## Read file into string and count the number of header rows
+  file_content = fileread (fname);
+
+  ## Split the file into rows (using \r\n or \n as delimiters between rows).
+  file_content_rows = regexp (file_content, "\r?\n", "split");
+
+  ## FIXME: guess delimiter, if it isn't defined
+  if (isempty (delimiter))
+    error ("importdata: Guessing delimiter is not implemented yet, you have to specify it.");
+  endif
+
+  ## FIXME: A more intelligent way to count number of header rows. This
+  ## is needed e.g. when delimiter=' ' and the header contains spaces...
+
+  ## If number of header rows is undefined, then count the number of
+  ## header rows by step through row by row and look for the delimiter.
+  ## Assume that the header can't contain any delimiter.
+  if (header_rows < 0)
+    header_rows = 0;
+    for i=1:length (file_content_rows)
+      if (isempty (regexp(file_content_rows{i}, delimiter, "once")))
+        header_rows++;
+      else
+        ## Data part has begun and therefore no more header rows can be
+        ## found
+        break;
+      endif
+    endfor
+  endif
+
+  ## Put the header rows in output.textdata.
+  if (header_rows > 0)
+    output.textdata   = file_content_rows (1:header_rows)';
+  endif
+
+  ## If space is the delimiter, then remove spaces in the beginning of
+  ## each data row.
+  if (strcmpi (delimiter, " "))
+    for i=(header_rows+1):length (file_content_rows)
+      ## strtrim does not only remove the leading spaces but also the
+      ## tailing spaces, but that doesn't really matter.
+      file_content_rows{i} = strtrim (file_content_rows{i});
+    endfor
+  endif
+
+  ## Remove empty data rows. Go through them backwards so that you wont
+  ## get out of bounds.
+  for i=length (file_content_rows):-1:(header_rows + 1)
+    if (length (file_content_rows{i}) < 1)
+      file_content_rows = [file_content_rows(1:i-1), \
+                           file_content_rows(i+1:length(file_content_rows))];
+    endif
+  endfor
+
+  ## Count the number of data columns. If there are different number of
+  ## columns, use the greatest value.
+  data_columns = 0;
+  delimiter_pattern = delimiter;
+  ## If space is the delimiter, then multiple spaces should count as ONE
+  ## delimiter. Also ignore leading spaces.
+  if (strcmpi (delimiter, " "))
+    delimiter_pattern = ' +';
+  endif
+  for i=(header_rows+1):length(file_content_rows)
+    data_columns = max (data_columns,
+                        length (regexp (file_content_rows{i},
+                                        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);
+  for i=(header_rows+1):length(file_content_rows)
+    ## Only use the row if it contains anything other than white-space
+    ## characters.
+    if (any (file_content_rows{i} != " "))
+      row_data = regexp (file_content_rows{i}, delimiter_pattern, "split");
+
+      for j=1:length(row_data)
+        ## Try to convert the column to a number, if it works put it in
+        ## output.data, otherwise in output.textdata
+        if (!isempty (row_data{j}))
+          data_numeric = str2double (row_data{j});
+          if (!isnan (data_numeric))
+            output.data(i-header_rows, j) = data_numeric;
+          else
+            output.textdata{i,j} = row_data{j};
+          endif
+        endif
+      endfor
+
+    endif
+  endfor
+
+  ## Check wether rowheaders or colheaders should be used
+  if ((header_rows == data_columns) && (size (output.textdata, 2) == 1))
+    output.rowheaders = output.textdata;
+  elseif (size (output.textdata, 2) == data_columns)
+    output.colheaders = output.textdata(end,:);
+  endif
+
+  ## When delimiter = "\\t" convert it to a tab, done for Matlab compatibility.
+  if (strcmp (delimiter, '\t'))
+    delimiter = "\t";
+  endif
+
+endfunction
+
+
+########################################
+
+%!test
+%! # Comma separated values
+%! A = [3.1 -7.2 0; 0.012 6.5 128];
+%! fn  = tmpnam ();
+%! fid = fopen (fn, "w");
+%! fputs (fid, "3.1,-7.2,0\n0.012,6.5,128");
+%! fclose (fid);
+%! [a,d,h] = importdata (fn, ",");
+%! unlink (fn);
+%! assert (a, A);
+%! assert (d, ",");
+%! assert (h, 0);
+
+%!test
+%! # Tab separated values
+%! A = [3.1 -7.2 0; 0.012 6.5 128];
+%! fn  = tmpnam ();
+%! fid = fopen (fn, "w");
+%! fputs (fid, "3.1\t-7.2\t0\n0.012\t6.5\t128");
+%! fclose (fid);
+%! [a,d,h] = importdata (fn, "\\t");
+%! unlink (fn);
+%! assert (a, A);
+%! assert (d, "\t");
+%! assert (h, 0);
+
+%!test
+%! # Space separated values, using multiple spaces to align in columns.
+%! A = [3.1 -7.2 0; 0.012 6.5 128];
+%! fn  = tmpnam ();
+%! fid = fopen (fn, "w");
+%! fprintf (fid, "%10.3f %10.3f %10.3f\n", A(1,:));
+%! fprintf (fid, "%10.3f %10.3f %10.3f\n", A(2,:));
+%! fclose (fid);
+%! [a,d,h] = importdata (fn, " ");
+%! unlink (fn);
+%! assert (a, A);
+%! assert (d, " ");
+%! assert (h, 0);
+
+%!test
+%! # Header
+%! A.data = [3.1 -7.2 0; 0.012 6.5 128];
+%! A.textdata = {"This is a header row."; \
+%!               "this row does not contain any data, but the next one does."};
+%! fn  = tmpnam ();
+%! fid = fopen (fn, "w");
+%! fputs (fid, [A.textdata{1} "\n"]);
+%! fputs (fid, [A.textdata{2} "\n"]);
+%! fputs (fid, "3.1\t-7.2\t0\n0.012\t6.5\t128");
+%! fclose (fid);
+%! [a,d,h] = importdata (fn, "\\t");
+%! unlink (fn);
+%! assert (a, A);
+%! assert (d, "\t");
+%! assert (h, 2);
+
+%!test
+%! # Ignore empty rows containing only spaces
+%! A = [3.1 -7.2 0; 0.012 6.5 128];
+%! fn  = tmpnam ();
+%! fid = fopen (fn, "w");
+%! fprintf (fid, "%10.3f %10.3f %10.3f\n", A(1,:));
+%! fputs (fid, "      ");
+%! fprintf (fid, "%10.3f %10.3f %10.3f\n", A(2,:));
+%! fclose (fid);
+%! [a,d,h] = importdata (fn, " ");
+%! unlink (fn);
+%! assert (a, A);
+%! assert (d, " ");
+%! assert (h, 0);
+
+%!test
+%! # Exponentials
+%! A = [3.1 -7.2 0; 0.012 6.5 128];
+%! fn  = tmpnam ();
+%! fid = fopen (fn, "w");
+%! fputs (fid, "+3.1e0\t-72E-1\t0\n12e-3\t6.5\t128");
+%! fclose (fid);
+%! [a,d,h] = importdata (fn, "\\t");
+%! unlink (fn);
+%! assert (a, A);
+%! assert (d, "\t");
+%! 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 ();
+%! fid = fopen (fn, "w");
+%! fputs (fid, "3.1\t\t0\n0.012\t6.5\t128");
+%! fclose (fid);
+%! [a,d,h] = importdata (fn, "\\t");
+%! unlink (fn);
+%! assert (a, A);
+%! assert (d, "\t");
+%! assert (h, 0);
+
+%!test
+%! # CRLF for line breaks
+%! A = [3.1 -7.2 0; 0.012 6.5 128];
+%! fn  = tmpnam ();
+%! fid = fopen (fn, "w");
+%! fputs (fid, "3.1\t-7.2\t0\r\n0.012\t6.5\t128");
+%! fclose (fid);
+%! [a,d,h] = importdata (fn, "\\t");
+%! unlink (fn);
+%! assert (a, A);
+%! assert (d, "\t");
+%! assert (h, 0);
+
--- a/scripts/io/is_valid_file_id.m
+++ b/scripts/io/is_valid_file_id.m
@@ -39,8 +39,10 @@
 
 endfunction
 
+
 %!assert (is_valid_file_id (stdout))
 %!assert (! is_valid_file_id ([1,2;3,4]))
 %!assert (! is_valid_file_id ("not_a_file_id"))
 %!assert (! is_valid_file_id (-1))
 %!assert (! is_valid_file_id (pi))
+
--- a/scripts/io/module.mk
+++ b/scripts/io/module.mk
@@ -6,6 +6,7 @@
   io/csvwrite.m \
   io/dlmwrite.m \
   io/fileread.m \
+  io/importdata.m \
   io/is_valid_file_id.m \
   io/strread.m \
   io/textscan.m \
--- a/scripts/io/strread.m
+++ b/scripts/io/strread.m
@@ -1,5 +1,5 @@
 ## Copyright (C) 2009-2012 Eric Chassande-Mottin, CNRS (France)
-## Copyright (C) 2012 Philip Nienhuis
+## Parts Copyright (C) 2012 Philip Nienhuis
 ##
 ## This file is part of Octave.
 ##
@@ -39,7 +39,7 @@
 ## @item %s
 ## The word is parsed as a string.
 ##
-## @itemx %f
+## @item  %f
 ## @itemx %n
 ## The word is parsed as a number and converted to double.
 ##
@@ -102,6 +102,7 @@
 ## @item "commentstyle"
 ## Parts of @var{str} are considered comments and will be skipped.
 ## @var{value} is the comment style and can be any of the following.
+##
 ## @itemize
 ## @item "shell"
 ## Everything from @code{#} characters to the nearest end-of-line is skipped.
@@ -153,6 +154,20 @@
 ##
 ## @end table
 ##
+## When the number of words in @var{str} doesn't match an exact multiple
+## of the number of format conversion specifiers, strread's behavior
+## depends on the last character of @var{str}:
+##
+## @table @asis
+## @item last character = "\n"
+## Data columns are padded with empty fields or Nan so that all columns
+## have equal length 
+##
+## @item last character is not "\n"
+## Data columns are not padded; strread returns columns of unequal length
+##
+## @end table
+##
 ## @seealso{textscan, textread, load, dlmread, fscanf}
 ## @end deftypefn
 
@@ -162,6 +177,12 @@
   if (nargin < 1)
     print_usage ();
   endif
+  
+  if (isempty (str))
+    ## Return empty args (no match), rather than raising an error
+    varargout = cell (1, nargout);
+    return;
+  endif
 
   if (isempty (format))
     format = "%f";
@@ -205,7 +226,7 @@
     switch (lower (varargin{n}))
       case "bufsize"
         ## We could synthesize this, but that just seems weird...
-        warning ('strread: property "bufsize" is not implemented');
+        warning ("strread: property 'bufsize' is not implemented");
       case "commentstyle"
         comment_flag = true;
         switch (lower (varargin{n+1}))
@@ -238,7 +259,7 @@
       case "emptyvalue"
         numeric_fill_value = varargin{n+1};
       case "expchars"
-        warning ('strread: property "expchars" is not implemented');
+        warning ("strread: property 'expchars' is not implemented");
       case "whitespace"
         white_spaces = varargin{n+1};
         if (strcmp (typeinfo (white_spaces), "sq_string"))
@@ -260,32 +281,47 @@
         elseif (ischar (varargin{n+1}))
           empty_str = varargin(n+1);
         else
-          error ('strread: "treatasempty" value must be string or cellstr');
+          error ("strread: 'treatasempty' value must be string or cellstr");
         endif
       otherwise
-        warning ('strread: unknown property "%s"', varargin{n});
+        warning ("strread: unknown property '%s'", varargin{n});
     endswitch
   endfor
 
   ## First parse of FORMAT
   if (strcmpi (strtrim (format), "%f"))
     ## Default format specified.  Expand it (to desired nargout)
-    fmt_words = cell (nargout, 1);
-    fmt_words (1:nargout) = format;
+    fmt_words = cell (max (nargout, 1), 1);
+    fmt_words (1:max (nargout, 1)) = format;
   else
     ## Determine the number of words per line as a first guess.  Forms
     ## like %f<literal>) (w/o delimiter in between) are fixed further on
     format = strrep (format, "%", " %");
-    fmt_words = regexp (format, '[^ ]+', 'match');
+    fmt_words = regexp (format, '[^ ]+', "match");
+    
+    ## Find position of conversion specifiers (they start with %)
+    idy2 = find (! cellfun ("isempty", regexp (fmt_words, '^%')));
+
+    ## Check for unsupported format specifiers
+    errpat = '(\[.*\]|[cq]|[nfdu]8|[nfdu]16|[nfdu]32|[nfdu]64)';
+    if (! all (cellfun ("isempty", regexp (fmt_words(idy2), errpat))))
+      error ("strread: %q, %c, %[] or bit width format specifiers are not supported yet.");
+    endif
+
     ## Format conversion specifiers following literals w/o space/delim
     ## in between are separate now.  Separate those w trailing literals
-    idy2 = find (! cellfun ("isempty", strfind (fmt_words, "%")));
     a = strfind (fmt_words(idy2), "%");
-    b = regexp (fmt_words(idy2), '[nfdus]', 'end');
+    b = regexp (fmt_words(idy2), '[nfdus]', "end");
     for jj = 1:numel (a)
+      ## From right to left to avoid losing track
       ii = numel (a) - jj + 1;
+      ## Check for illegal format specifiers
+      if (isempty (b{ii}))
+        error ("strread: unknown format specifier #%d ('%s')\n",
+              ii, fmt_words{idy2(ii)});
+      endif
       if (! (length (fmt_words{idy2(ii)}) == b{ii}(1)))
-        ## Fix format_words
+        ## Split fmt_words(ii) into % conv specifier and trailing literal
         fmt_words(idy2(ii)+1 : end+1) = fmt_words(idy2(ii) : end);
         fmt_words{idy2(ii)} = fmt_words{idy2(ii)}(a{ii} : b{ii}(1));
         fmt_words{idy2(ii)+1} = fmt_words{idy2(ii)+1}(b{ii}+1:end);
@@ -305,7 +341,7 @@
   ## Remove comments in str
   if (comment_flag)
     ## Expand 'eol_char' here, after option processing which may have set value
-    comment_end = regexprep (comment_end, 'eol_char', eol_char);
+    comment_end = regexprep (comment_end, "eol_char", eol_char);
     cstart = strfind (str, comment_start);
     cstop  = strfind (str, comment_end);
     ## Treat end of string as additional comment stop
@@ -335,7 +371,8 @@
   endif
 
   if (! isempty (white_spaces))
-    ## For numeric fields, whitespace is always a delimiter, but not for text fields
+    ## For numeric fields, whitespace is always a delimiter, but not for text
+    ## fields
     if (isempty (strfind (format, "%s")))
       ## Add whitespace to delimiter set
       delimiter_str = unique ([white_spaces delimiter_str]);
@@ -371,16 +408,17 @@
        str = str(2:end);
     endif
     ## Check for single delimiter followed/preceded by whitespace
-    ## FIXME: Double strrep on str is enormously expensive of CPU time.
-    ## Can this be eliminated
     if (! isempty (delimiter_str))
       dlmstr = setdiff (delimiter_str, " ");
-      rxp_dlmwsp = sprintf ("( [%s]|[%s] )", dlmstr, dlmstr);
-      str = regexprep (str, rxp_dlmwsp, delimiter_str(1));
+      if (! isempty (dlmstr))
+        rxp_dlmwsp = sprintf ('( [%s] | [%s]|[%s] )', dlmstr, dlmstr, dlmstr);
+        str = regexprep (str, rxp_dlmwsp, delimiter_str(1));
+      endif
     endif
+    ## Wipe leading and trailing whitespace on each line (it may be
+    ## delimiter too)
     ## FIXME: Double strrep on str is enormously expensive of CPU time.
     ## Can this be eliminated
-    ## Wipe leading and trailing whitespace on each line (it may be delimiter too)
     if (! isempty (eol_char))
       str = strrep (str, [eol_char " "], eol_char);
       str = strrep (str, [" " eol_char], eol_char);
@@ -390,27 +428,25 @@
   ## Split 'str' into words
   words = split_by (str, delimiter_str, mult_dlms_s1, eol_char);
   if (! isempty (white_spaces))
-    ## Trim leading and trailing white_spaces
-    ## FIXME: Is this correct?  strtrim clears what matches isspace(), not
-    ## necessarily what is in white_spaces.
+    ## Trim leading and trailing 'white_spaces'. All whitespace has
+    ## been converted to space above
     words = strtrim (words);
   endif
   num_words = numel (words);
-  ## First guess at number of lines in file (ignoring leading/trailing literals)
+  ## First guess at nr. of lines in file (ignoring leading/trailing literals)
   num_lines = ceil (num_words / num_words_per_line);
 
   ## Replace TreatAsEmpty char sequences by empty strings
   if (! isempty (empty_str))
     for ii = 1:numel (empty_str)
-      idz = strmatch (empty_str{ii}, words, "exact");
+      idz = strncmp (empty_str{ii}, words, length (empty_str{ii}));
       words(idz) = {""};
     endfor
   endif
 
   ## fmt_words has been split properly now, but words{} has only been split on
-  ## delimiter positions. 
-  ## As numeric fields can also be separated by whitespace, more splits may be
-  ## needed.
+  ## delimiter positions. As numeric fields can also be separated by
+  ## whitespace, more splits may be needed.
   ## We also don't know the number of lines (as EndOfLine may have been set to
   ## "" (empty) by the caller).
   ##
@@ -419,6 +455,8 @@
   ## B: Leading literals (<literal>%f) w/o delimiter in between.
   ## C. Skipping leftover parts of specified skip fields (%*N )
   ## Some words columns may have to be split further to fix these.
+  ## To find out, we'll match fmt_words to the words array to see what
+  ## needs to be done. fwptr tracks which {fmt_words}# starts in what {words}#
 
   ## Find indices and pointers to possible literals in fmt_words
   idf = cellfun ("isempty", strfind (fmt_words, "%"));
@@ -426,7 +464,7 @@
   idg = ! cellfun ("isempty", regexp (fmt_words, '%\*?\d'));
   idy = find (idf | idg);
   ## Find indices to numeric conversion specifiers
-  idn = ! cellfun ("isempty", regexp (fmt_words, "%[dnfu]"));
+  idn = ! cellfun ("isempty", regexp (fmt_words, '%[dnfu]'));
 
   ## If needed, split up columns in three steps:
   if (! isempty (idy))
@@ -436,11 +474,16 @@
       ## 1. Assess "period" in the split-up words array ( < num_words_per_line).
       ## Could be done using EndOfLine but that prohibits EndOfLine = "" option.
       ## Alternative below goes by simply parsing a first grab of words
-      ## and counting words until the fmt_words array is exhausted:
-      iwrd = 1; iwrdp = 0; iwrdl = length (words{iwrd});
-      for ii = 1:numel (fmt_words)
+      ## and matching fmt_words to words until the fmt_words array is exhausted.
+      ## iwrd: ptr to current analyzed word; iwrdp: ptr to pos before analyzed char
+      iwrd = 1; iwrdp = 0; iwrdl = length (words{1});
+      fwptr = zeros (1, numel (fmt_words));
+      ii = 1;
+      while ii <= numel (fmt_words)
 
         nxt_wrd = 0;
+        ## Keep track of which words nr. every fmt_words{} is (starts) in.
+        fwptr(ii) = iwrd;
 
         if (idf(ii))
           ## Literal expected
@@ -464,8 +507,9 @@
 
         elseif (idg(ii))
           ## Fixed width specifier (%N or %*N): read just a part of word
-          iwrdp += floor ...
-           (str2double (fmt_words{ii}(regexp(fmt_words{ii}, '\d') : end-1)));
+          sw = regexp (fmt_words{ii}, '\d', "once");
+          ew = regexp (fmt_words{ii}, '[nfuds]') - 1;
+          iwrdp += floor (str2double (fmt_words{ii}(sw:ew)));
           if (iwrdp > iwrdl)
             ## Match error. Field extends beyond word boundary.
             warning  ...
@@ -491,7 +535,7 @@
               ## ..or it IS found.  Add inferred width of current conversion field
               iwrdp += index (words{iwrd}(iwrdp+1:end), fmt_words{ii+1}) - 1;
             endif
-          elseif (iwrdp < iwrdl)
+          elseif (iwrdp <= iwrdl)
             ## No bordering literal to the right => field occupies (rest of) word
             nxt_wrd = 1;
           endif
@@ -500,30 +544,34 @@
 
         if (nxt_wrd)
           ++iwrd; iwrdp = 0;
-          if (ii < numel (fmt_words))
+          if (iwrd > numel (words))
+            ## Apparently EOF; assume incomplete row already at L.1 of data
+            ii = numel (fmt_words);
+          elseif (ii < numel (fmt_words) && iwrd <= numel (words))
             iwrdl = length (words{iwrd});
           endif
         endif
 
-      endfor
+        ++ii;
+
+      endwhile
       ## Done
       words_period = max (iwrd - 1, 1);
       num_lines = ceil (num_words / words_period);
 
       ## 2. Pad words array so that it can be reshaped
-      tmp_lines = ceil (num_words / words_period);
-      num_words_padded = tmp_lines * words_period - num_words;
+      num_words_padded = num_lines * words_period - num_words;
       if (num_words_padded)
         words = [words'; cell(num_words_padded, 1)];
       endif
-      words = reshape (words, words_period, tmp_lines);
+      words = reshape (words, words_period, num_lines);
 
       ## 3. Do the column splitting on rectangular words array
       icol = 1; ii = 1;    # icol = current column, ii = current fmt_word
       while (ii <= num_words_per_line)
 
         ## Check if fmt_words(ii) contains a literal or fixed-width
-        if ((idf(ii) || idg(ii)) && (rows(words) < num_words_per_line))
+        if ((idf(ii) || idg(ii)) && (rows (words) < num_words_per_line))
           if (idf(ii))
             s = strfind (words(icol, 1), fmt_words{ii});
             if (isempty (s{:}))
@@ -542,41 +590,52 @@
             if (! idg(ii) && ! isempty (s) && s(1) == 1)
               ## Leading literal.  Assign literal to icol, paste rest in icol + 1
               ## Apply only to those cells that do have something beyond literal
-              jptr = find (cellfun("length", words(icol+1, jptr), ...
-                            "UniformOutput", false) > e(1));
+              jptr = find (cellfun ("length", words(icol+1, jptr), ...
+                                    "UniformOutput", false) > e(1));
               words(icol+1, :) = {""};
               words(icol+1, jptr) = cellfun ...
-                (@(x) substr(x, e(1)+1, length(x)-e(1)), words(icol, jptr), ...
+                (@(x) substr (x, e(1)+1, length (x) - e(1)), words(icol, jptr), ...
                 "UniformOutput", false);
               words(icol, jptr) = fmt_words{ii};
+              fwptr = [fwptr(1:ii) (++fwptr(ii+1:end))];
 
             else
               if (! idg(ii) && ! isempty (strfind (fmt_words{ii-1}, "%s")))
                 ## Trailing literal.  If preceding format == '%s' this is an error
-                warning ("Ambiguous '%s' specifier next to literal in column %d", icol);
+                warning ...
+                 ("strread: ambiguous '%s' specifier next to literal in column %d", icol);
               elseif (idg(ii))
                 ## Current field = fixed width. Strip into icol, rest in icol+1
-                wdth = floor (str2double (fmt_words{ii}(regexp(fmt_words{ii}, ...
-                              '\d') : end-1)));
+                sw = regexp (fmt_words{ii}, '\d', "once");
+                ew = regexp (fmt_words{ii}, '[nfuds]') - 1;
+                wdth = floor (str2double (fmt_words{ii}(sw:ew)));
                 words(icol+1, jptr) = cellfun (@(x) x(wdth+1:end),
                      words(icol,jptr), "UniformOutput", false);
-                words(icol, jptr) = strtrunc (words(icol, jptr), wdth);
+                if (isempty ([words(icol+1, :){:}]))
+                  ## Apparently split wasn't needed as turns out to cover
+                  ## entire column. So delete column again
+                  words(icol+1, :) = [];
+                else
+                  words(icol, jptr) = strtrunc (words(icol, jptr), wdth);
+                  fwptr = [fwptr(1:ii) (++fwptr(ii+1:end))];
+                endif
               else
                 ## FIXME: this assumes char(254)/char(255) won't occur in input!
                 clear wrds;
                 wrds(1:2:2*numel (words(icol, jptr))) = ...
                      strrep (words(icol, jptr), fmt_words{ii}, ...
                      [char(255) char(254)]);
-                wrds(2:2:2*numel (words(icol, jptr))-1) = char(255);
-                wrds = strsplit ([wrds{:}], char(255));
+                wrds(2:2:2*numel (words(icol, jptr))-1) = char (255);
+                wrds = strsplit ([wrds{:}], char (255), false);
                 words(icol, jptr) = ...
-                  wrds(find (cellfun ("isempty", strfind (wrds, char(254)))));
-                wrds(find (cellfun ("isempty", strfind (wrds, char(254))))) ...
-                   = char(255);
+                  wrds(find (cellfun ("isempty", strfind (wrds, char (254)))));
+                wrds(find (cellfun ("isempty", strfind (wrds, char (254))))) ...
+                   = char (255);
                 words(icol+1, jptr) = strsplit (strrep ([wrds{2:end}], ...
-                   char(254), fmt_words{ii}), char(255));
+                   char (254), fmt_words{ii}), char (255), false);
                 ## Former trailing literal may now be leading for next specifier
                 --ii;
+                fwptr = [fwptr(1:ii) (++fwptr(ii+1:end))];
               endif
             endif
           endif
@@ -584,9 +643,7 @@
         else
           ## Conv. specifier.  Peek if next fmt_word needs split from current column
           if (ii < num_words_per_line)
-            if (idf(ii+1) && (! isempty (strfind (words{icol, 1}, fmt_words{ii+1}))))
-              --icol;
-            elseif (idg(ii+1))
+            if (fwptr(ii) == fwptr(ii+1))
               --icol;
             endif
           endif
@@ -645,10 +702,12 @@
           varargout{k} = data.';
           k++;
         case {"%0", "%1", "%2", "%3", "%4", "%5", "%6", "%7", "%8", "%9"}
-          nfmt = strsplit (fmt_words{m}(2:end-1), '.');
+          sw = regexp (fmt_words{m}, '\d', "once");
+          ew = regexp (fmt_words{m}, '[nfudsq]') - 1;
+          nfmt = strsplit (fmt_words{m}(2:ew), ".", false);
           swidth = str2double (nfmt{1});
-          switch fmt_words{m}(end)
-            case {"d", "u", "f", "n%"}
+          switch fmt_words{m}(ew+1)
+            case {"d", "u", "f", "n"}
               n = cellfun ("isempty", data);
               ### FIXME - erroneously formatted data lead to NaN, not an error
               ###         => ReturnOnError can't be implemented for numeric data
@@ -711,15 +770,15 @@
     ## to avoid it being included in consecutive delim series
     enchr = ' ';
     ## However watch out if eol_char is also in delimiters
-    if (index (sep, eol_char)); enchr = char(255); endif
+    if (index (sep, eol_char)); enchr = char (255); endif
     text = strrep (text, eol_char, [enchr eol_char enchr]);
   else
     mult_dlms_s1 = false;
   endif
 
   ## Split text string along delimiters
-  out = strsplit (text, sep, mult_dlms_s1);
-  if (index (sep, eol_char)); out = strrep (out, char(255), ''); endif
+  out = strsplit (text, sep, mult_dlms_s1, "delimitertype", "legacy");
+  if (index (sep, eol_char)); out = strrep (out, char (255), ''); endif
   ## In case of trailing delimiter, strip stray last empty word
   if (!isempty (out) && any (sep == text(end)))
     out(end) = [];
@@ -737,34 +796,34 @@
 %! assert (b, 2);
 
 %!test
-%! str = '';
+%! str = "";
 %! a = rand (10, 1);
 %! b = char (randi ([65, 85], 10, 1));
 %! for k = 1:10
-%!   str = sprintf ('%s %.6f %s\n', str, a(k), b(k));
+%!   str = sprintf ("%s %.6f %s\n", str, a(k), b(k));
 %! endfor
-%! [aa, bb] = strread (str, '%f %s');
-%! assert (a, aa, 1e-6);
-%! assert (cellstr (b), bb);
+%! [aa, bb] = strread (str, "%f %s");
+%! assert (aa, a, 1e-6);
+%! assert (bb, cellstr (b));
 
 %!test
-%! str = '';
+%! str = "";
 %! a = rand (10, 1);
 %! b = char (randi ([65, 85], 10, 1));
 %! for k = 1:10
-%!   str = sprintf ('%s %.6f %s\n', str, a(k), b(k));
+%!   str = sprintf ("%s %.6f %s\n", str, a(k), b(k));
 %! endfor
-%! aa = strread (str, '%f %*s');
-%! assert (a, aa, 1e-6);
+%! aa = strread (str, "%f %*s");
+%! assert (aa, a, 1e-6);
 
 %!test
-%! str = sprintf ('/* this is\nacomment*/ 1 2 3');
-%! a = strread (str, '%f', 'commentstyle', 'c');
+%! str = sprintf ("/* this is\nacomment*/ 1 2 3");
+%! a = strread (str, "%f", "commentstyle", "c");
 %! assert (a, [1; 2; 3]);
 
 %!test
 %! str = "# comment\n# comment\n1 2 3";
-%! [a, b] = strread (str, '%n %s', 'commentstyle', 'shell', 'endofline', "\n");
+%! [a, b] = strread (str, "%n %s", "commentstyle", "shell", "endofline", "\n");
 %! assert (a, [1; 3]);
 %! assert (b, {"2"});
 
@@ -783,9 +842,9 @@
 %!test
 %! # Bug #33536
 %! [a, b, c] = strread ("1,,2", "%s%s%s", "delimiter", ",");
-%! assert (a{1}, '1');
-%! assert (b{1}, '');
-%! assert (c{1}, '2');
+%! assert (a{1}, "1");
+%! assert (b{1}, "");
+%! assert (c{1}, "2");
 
 %!test
 %! # Bug #33536
@@ -794,17 +853,17 @@
 
 %!test
 %! dat = "Data file.\r\n=  =  =  =  =\r\nCOMPANY    : <Company name>\r\n";
-%! a = strread (dat, "%s", 'delimiter', "\n", 'whitespace', '', 'endofline', "\r\n");
+%! a = strread (dat, "%s", "delimiter", "\n", "whitespace", "", "endofline", "\r\n");
 %! assert (a{2}, "=  =  =  =  =");
 %! assert (double (a{3}(end-5:end)), [32 110 97 109 101 62]);
 
 %!test
-%! [a, b, c, d] = strread ("1,2,3,,5,6", "%d%f%d%f", 'delimiter', ',');
+%! [a, b, c, d] = strread ("1,2,3,,5,6", "%d%f%d%f", "delimiter", ",");
 %! assert (c, int32 (3));
 %! assert (d, NaN);
 
 %!test
-%! [a, b, c, d] = strread ("1,2,3,,5,6\n", "%d%d%f%d", 'delimiter', ',');
+%! [a, b, c, d] = strread ("1,2,3,,5,6\n", "%d%d%f%d", "delimiter", ",");
 %! assert (c, [3; NaN]);
 %! assert (d, int32 ([0; 0]));
 
@@ -816,12 +875,12 @@
 %1 assert (c, 0.3567);
 
 %!test
-%! [a, b] = strread('0.41 8.24 3.57 6.24 9.27', "%f%f", 2, 'delimiter', ' ');
+%! [a, b] = strread ("0.41 8.24 3.57 6.24 9.27", "%f%f", 2, "delimiter", " ");
 %1 assert (a, [0.41; 3.57]);
 
 %!test
 %! # TreatAsEmpty
-%! [a, b, c, d] = strread ("1,2,3,NN,5,6\n", "%d%d%d%f", 'delimiter', ',', 'TreatAsEmpty', 'NN');
+%! [a, b, c, d] = strread ("1,2,3,NN,5,6\n", "%d%d%d%f", "delimiter", ",", "TreatAsEmpty", "NN");
 %! assert (c, int32 ([3; 0]));
 %! assert (d, [NaN; NaN]);
 
@@ -830,13 +889,13 @@
 %! str = "Text1Text2Text\nText398Text4Text\nText57Text";
 %! [a, b] = strread (str, "Text%dText%1sText");
 %! assert (a, int32 ([1; 398; 57]));
-%! assert (b(1:2), {'2'; '4'});
+%! assert (b(1:2), {"2"; "4"});
 %! assert (isempty (b{3}), true);
 
 %% MultipleDelimsAsOne
 %!test
 %! str = "11, 12, 13,, 15\n21,, 23, 24, 25\n,, 33, 34, 35";
-%! [a b c d] = strread (str, "%f %f %f %f", 'delimiter', ',', 'multipledelimsasone', 1, 'endofline', "\n");
+%! [a b c d] = strread (str, "%f %f %f %f", "delimiter", ",", "multipledelimsasone", 1, "endofline", "\n");
 %! assert (a', [11, 21, NaN]);
 %! assert (b', [12, 23, 33]);
 %! assert (c', [13, 24, 34]);
@@ -887,3 +946,51 @@
 %! assert (a, [0.31; 0.60], 0.01)
 %! assert (b, [0.86; 0.72], 0.01)
 %! assert (c, [0.94; 0.87], 0.01)
+
+%!test
+%! [a, b] = strread (["Empty 1" char(10)], "Empty%s %f");
+%! assert (a{1}, '1');
+%! assert (b, NaN);
+
+%!test
+%! [a, b] = strread (["Empty" char(10)], "Empty%f %f");
+%! assert (a, NaN);
+%! assert (b, NaN);
+
+%!test
+%! # Bug #35999
+%! [a, b, c] = strread ("", "%f");
+%! assert (isempty (a));
+%! assert (isempty (b));
+%! assert (isempty (c));
+
+%% bug #37023
+%!test
+%! [a, b] = strread (" 1. 1 \n  2 3 \n", "%f %f", "endofline", "\n");
+%! assert (a, [1; 2], 1e-15);
+%! assert (b, [1; 3], 1e-15);
+
+%% Test for no output arg (interactive use)
+%!test
+%! assert (strread (",2,,4\n5,,7,", "", "delimiter", ","), [NaN; 2; NaN; 4; 5; NaN; 7]);
+
+%% Unsupported format specifiers
+%!test
+%!error <format specifiers are not supported> strread ("a", "%c")
+%!error <format specifiers are not supported> strread ("a", "%*c %d")
+%!error <format specifiers are not supported> strread ("a", "%q")
+%!error <format specifiers are not supported> strread ("a", "%*q %d")
+%!error <format specifiers are not supported> strread ("a", "%[a]")
+%!error <format specifiers are not supported> strread ("a", "%*[a] %d")
+%!error <format specifiers are not supported> strread ("a", "%[^a]")
+%!error <format specifiers are not supported> strread ("a", "%*[^a] %d")
+%!error <format specifiers are not supported> strread ("a", "%d8")
+%!error <format specifiers are not supported> strread ("a", "%*d8 %s")
+%!error <format specifiers are not supported> strread ("a", "%f64")
+%!error <format specifiers are not supported> strread ("a", "%*f64 %s")
+%!error <format specifiers are not supported> strread ("a", "%u32")
+%!error <format specifiers are not supported> strread ("a", "%*u32 %d")
+
+%% Illegal format specifiers
+%!test
+%!error <unknown format specifier> strread ("1.0", "%z")
--- a/scripts/io/textread.m
+++ b/scripts/io/textread.m
@@ -1,4 +1,4 @@
-## Copyright (C) 2009-2012 Eric Chassande-Mottin, CNRS (France)
+## Copyright (C) 2009-2013 Eric Chassande-Mottin, CNRS (France)
 ##
 ## This file is part of Octave.
 ##
@@ -41,14 +41,21 @@
 ## delimiters.
 ## @end itemize
 ##
-## The optional input @var{n} specifes the number of times to use
-## @var{format} when parsing, i.e., the format repeat count.
+## The optional input @var{n} specifies the number of data lines to read; in
+## this sense it differs slightly from the format repeat count in strread.
+##
+## If the format string is empty (not: omitted) and the file contains only
+## numeric data (excluding headerlines), textread will return a rectangular
+## matrix with the number of columns matching the number of numeric fields on
+## the first data line of the file. Empty fields are returned as zero values.
 ##
 ## @seealso{strread, load, dlmread, fscanf, textscan}
 ## @end deftypefn
 
 function varargout = textread (filename, format = "%f", varargin)
 
+  BUFLENGTH = 4096;       # Read buffer to speed up processing @var{n}
+
   ## Check input
   if (nargin < 1)
     print_usage ();
@@ -58,6 +65,17 @@
     error ("textread: FILENAME and FORMAT arguments must be strings");
   endif
 
+  if (! isempty (varargin) && isnumeric (varargin{1}))
+    nlines = varargin{1};
+  else
+    nlines = Inf;
+  endif
+  if (nlines < 1)
+    printf ("textread: N = 0, no data read\n");
+    varargout = cell (1, nargout);
+    return
+  endif
+
   ## Read file
   fid = fopen (filename, "r");
   if (fid == -1)
@@ -66,33 +84,30 @@
 
   ## Skip header lines if requested
   headerlines = find (strcmpi (varargin, "headerlines"), 1);
-  ## Beware of zero valued headerline, fskipl would skip to EOF
-  if (! isempty (headerlines) && (varargin{headerlines + 1} > 0))
-    fskipl (fid, varargin{headerlines + 1});
-    varargin(headerlines:headerlines+1) = [];
+  if (! isempty (headerlines))
+    ## Beware of missing or wrong headerline value
+    if (headerlines  == numel (varargin)
+       || ! isnumeric (varargin{headerlines + 1}))
+      error ("missing or illegal value for 'headerlines'" );
+    endif
+    ## Avoid conveying floats to fskipl
+    varargin{headerlines + 1} = round (varargin{headerlines + 1});
+    ## Beware of zero valued headerline, fskipl would skip to EOF
+    if (varargin{headerlines + 1} > 0)
+      fskipl (fid, varargin{headerlines + 1});
+      varargin(headerlines:headerlines+1) = [];
+      nargin = nargin - 2;
+    elseif (varargin{headerlines + 1} < 0)
+      warning ("textread: negative headerline value ignored");
+    endif
   endif
-
-  if (nargin > 2 && isnumeric (varargin{1}))
-    nlines = varargin{1};
-  else
-    nlines = Inf;
-  endif
+  st_pos = ftell (fid);
 
-  if (isfinite (nlines) && (nlines >= 0))
-    str = tmp_str = "";
-    n = 0;
-    ## FIXME: Can this be done without slow loop?
-    while (ischar (tmp_str) && n++ <= nlines)
-      str = strcat (str, tmp_str);
-      tmp_str = fgets (fid);
-    endwhile
-  else
-    str = fread (fid, "char=>char").';
-  endif
-  fclose (fid);
-
-  if (isempty (str))
+  ## Read a first file chunk. Rest follows after endofline processing
+  [str, count] = fscanf (fid, "%c", BUFLENGTH);
+  if (isempty (str) || count < 1)
     warning ("textread: empty file");
+    varargout = cell (1, nargout);
     return;
   endif
 
@@ -100,49 +115,203 @@
   if (! isempty (endofline))
     ## 'endofline' option set by user.
     if (! ischar (varargin{endofline + 1}));
-      error ("textread: character value required for EndOfLine");
+      error ("character value required for EndOfLine");
     endif
   else
-    ## Determine EOL from file.  Search for EOL candidates in first 3000 chars
-    eol_srch_len = min (length (str), 3000);
+    ## Determine EOL from file.  Search for EOL candidates in first BUFLENGTH chars
+    eol_srch_len = min (length (str), BUFLENGTH);
     ## First try DOS (CRLF)
-    if (! isempty (findstr ("\r\n", str(1 : eol_srch_len))))
+    if (! isempty (strfind (str(1 : eol_srch_len), "\r\n")))
       eol_char = "\r\n";
     ## Perhaps old Macintosh? (CR)
-    elseif (! isempty (findstr ("\r", str(1 : eol_srch_len))))
+    elseif (! isempty (strfind (str(1 : eol_srch_len), "\r")))
       eol_char = "\r";
-    ## Otherwise, use plain UNIX (LF)
+    ## Otherwise, use plain *nix (LF)
     else
       eol_char = "\n";
     endif
     ## Set up default endofline param value
-    varargin(end+1:end+2) = {'endofline', eol_char};
+    varargin(end+1:end+2) = {"endofline", eol_char};
   endif
-
+ 
+  ## Now that we know what EOL looks like, we can process format_repeat_count.
+  ## FIXME The below isn't ML-compatible: counts lines, not format string uses
+  if (isfinite (nlines) && (nlines > 0))
+    l_eol_char = length (eol_char);
+    eoi = findstr (str, eol_char);
+    n_eoi = length (eoi);
+    nblks = 0;
+    ## Avoid slow repeated str concatenation, first seek requested end of data
+    while (n_eoi < nlines && count == BUFLENGTH)
+      [nstr, count] = fscanf (fid, "%c", BUFLENGTH);
+      if (count > 0)
+        ## Watch out for multichar EOL being missed across buffer boundaries
+        if (l_eol_char > 1)
+          str = [str(end - length (eol_char) + 2 : end) nstr];
+        else
+          str = nstr;
+        endif
+        eoi = findstr (str, eol_char);
+        n_eoi += numel (eoi);
+        ++nblks;
+      endif
+    endwhile
+    ## Found EOL delimiting last requested line. Compute ptr (incl. EOL)
+    if (isempty (eoi))
+      printf ("textread: format repeat count specified but no endofline found\n");
+      eoi_pos = nblks * BUFLENGTH + count;
+    else
+      eoi_pos = (nblks * BUFLENGTH) + eoi(end + min (nlines, n_eoi) - n_eoi);
+    endif
+    fseek (fid, st_pos, "bof");
+    str = fscanf (fid, "%c", eoi_pos);
+  else
+    fseek (fid, st_pos, "bof");
+    str = fread (fid, "char=>char").';
+  endif
+  fclose (fid);
+ 
   ## Set up default whitespace param value if needed
-  if (isempty (find (strcmpi ('whitespace', varargin))))
-    varargin(end+1:end+2) = {'whitespace', " \b\t"};
+  if (isempty (find (strcmpi ("whitespace", varargin))))
+    varargin(end+1:end+2) = {"whitespace", " \b\t"};
   endif
 
   ## Call strread to make it do the real work
   [varargout{1:max (nargout, 1)}] = strread (str, format, varargin {:});
 
+  ## Hack to concatenate/reshape numeric output into 2D array (undocumented ML)
+  ## In ML this only works in case of an empty format string
+  if (isempty (format))
+    ## Get number of fields per line. 
+    ## 1. Get eol_char position
+    iwhsp = find (strcmpi ("whitespace", varargin));
+    whsp = varargin{iwhsp + 1};
+    idx = regexp (str, eol_char, "once");
+    ## 2. Get first data line til EOL. Avoid corner case of just one line
+    if (! isempty (idx))
+      str = str(1:idx-1);
+    endif
+    idelimiter = find (strcmpi (varargin, "delimiter"), 1);
+    if (isempty (idelimiter))
+      ## Assume delimiter = whitespace
+      ## 3A. whitespace incl. consecutive whitespace => single space
+      str = regexprep (str, sprintf ("[%s]+", whsp), ' ');
+      ## 4A. Remove possible leading & trailing spaces
+      str = strtrim (str);
+      ## 5A. Count spaces, add one to get nr of data fields per line
+      ncols = numel (strfind (str, " ")) + 1;
+    else
+      ## 3B. Just count delimiters. FIXME: delimiters could occur in literals
+      delimiter = varargin {idelimiter+1};
+      ncols = numel (regexp (str, sprintf ("[%s]", delimiter))) + 1;
+    endif
+    ## 6. Reshape; watch out, we need a transpose
+    nrows = ceil (numel (varargout{1}) / ncols);
+    pad = mod (numel (varargout{1}), ncols);
+    if (pad > 0)
+      pad = ncols - pad;
+      varargout{1}(end+1 : end+pad) = NaN;
+    endif
+    varargout{1} = reshape (varargout{1}, ncols, nrows)';
+    ## ML replaces empty values with NaNs
+    varargout{1}(find (isnan (varargout{1}))) = 0;
+  endif
+
 endfunction
 
-
 %!test
-%! f = tmpnam();
+%! f = tmpnam ();
 %! d = rand (5, 3);
-%! dlmwrite (f, d, 'precision', '%5.2f');
+%! dlmwrite (f, d, "precision", "%5.2f");
 %! [a, b, c] = textread (f, "%f %f %f", "delimiter", ",", "headerlines", 3);
-%! unlink(f);
+%! unlink (f);
 %! assert (a, d(4:5, 1), 1e-2);
 %! assert (b, d(4:5, 2), 1e-2);
 %! assert (c, d(4:5, 3), 1e-2);
 
+%!test
+%! f = tmpnam ();
+%! d = rand (7, 2);
+%! dlmwrite (f, d, "precision", "%5.2f");
+%! [a, b] = textread (f, "%f, %f", "headerlines", 1);
+%! unlink (f);
+%! assert (a, d(2:7, 1), 1e-2);
+
+%% Test reading 2D matrix with empty format
+%!test
+%! f = tmpnam ();
+%! d = rand (5, 2);
+%! dlmwrite (f, d, "precision", "%5.2f");
+%! A = textread (f, "", "headerlines", 3);
+%! unlink (f);
+%! assert (A, d(4:5, :), 1e-2);
+
+%% Read multiple lines using empty format string
+%!test
+%! f = tmpnam ();
+%! unlink (f);
+%! fid = fopen (f, "w");
+%! d = rand (1, 4);
+%! fprintf (fid, "  %f %f   %f  %f ", d);
+%! fclose (fid);
+%! A = textread (f, "");
+%! unlink (f);
+%! assert (A, d, 1e-6);
+
+%% Empty format, corner case = one line w/o EOL
+%!test
+%! f = tmpnam ();
+%! unlink (f);
+%! fid = fopen (f, "w");
+%! d = rand (1, 4);
+%! fprintf (fid, "  %f %f   %f  %f ", d);
+%! fclose (fid);
+%! A = textread (f, "");
+%! unlink (f);
+%! assert (A, d, 1e-6);
+
+%% Read multiple lines using empty format string, missing data (should be 0)
+%!test
+%! f = tmpnam ();
+%! unlink (f);
+%! fid = fopen (f, "w");
+%! d = rand (1, 4);
+%! fprintf (fid, "%f, %f, ,  %f,  %f ", d);
+%! fclose (fid);
+%! A = textread (f, "");
+%! unlink (f);
+%! assert (A, [ d(1:2) 0 d(3:4)], 1e-6);
+
+%% Test with empty positions - ML returns 0 for empty fields
+%!test
+%! f = tmpnam ();
+%! unlink (f);
+%! fid = fopen (f, "w");
+%! d = rand (1, 4);
+%! fprintf (fid, ",2,,4\n5,,7,\n");
+%! fclose (fid);
+%! A = textread (f, "", "delimiter", ",");
+%! unlink (f);
+%! assert (A, [0 2 0 4; 5 0 7 0], 1e-6);
+
+%% Another test with empty format + positions, now with more incomplete lower
+%% row (must be appended with zeros to get rectangular matrix)
+%!test
+%! f = tmpnam ();
+%! unlink (f);
+%! fid = fopen (f, "w");
+%! d = rand (1, 4);
+%! fprintf (fid, ",2,,4\n5,\n");
+%! fclose (fid);
+%! A = textread (f, "", "delimiter", ",");
+%! unlink (f);
+%! assert (A, [0 2 0 4; 5 0 0 0], 1e-6);
+
 %% Test input validation
 %!error textread ()
 %!error textread (1)
-%!error <arguments must be strings> textread (1, '%f')
+%!error <arguments must be strings> textread (1, "%f")
 %!error <arguments must be strings> textread ("fname", 1)
-
+%!error <missing or illegal value for> textread (file_in_loadpath ("textread.m"), "", "headerlines")
+%!error <missing or illegal value for> textread (file_in_loadpath ("textread.m"), "", "headerlines", 'hh')
+%!error <character value required for> textread (file_in_loadpath ("textread.m"), "%s", "endofline", true)
--- a/scripts/io/textscan.m
+++ b/scripts/io/textscan.m
@@ -1,4 +1,4 @@
-## Copyright (C) 2010-2012 Ben Abbott <bpabbott@mac.com>
+## Copyright (C) 2010-2013 Ben Abbott <bpabbott@mac.com>
 ##
 ## This file is part of Octave.
 ##
@@ -25,13 +25,13 @@
 ## @deftypefnx {Function File} {[@var{C}, @var{position}] =} textscan (@var{fid}, @dots{})
 ## Read data from a text file or string.
 ##
-## The file associated with @var{fid} is read and parsed according to
-## @var{format}.  The function behaves like @code{strread} except it works by
-## parsing a file instead of a string.  See the documentation of
-## @code{strread} for details.
+## The string @var{str} or file associated with @var{fid} is read from and
+## parsed according to @var{format}.  The function behaves like @code{strread}
+## except it can also read from file instead of a string.  See the documentation
+## of @code{strread} for details.
 ##
-## In addition to the options supported by
-## @code{strread}, this function supports a few more:
+## In addition to the options supported by @code{strread}, this function
+## supports a few more:
 ##
 ## @itemize
 ## @item "collectoutput":
@@ -50,45 +50,68 @@
 ## @item "returnonerror":
 ## If set to numerical 1 or true (default), return normally when read errors
 ## have been encountered.  If set to 0 or false, return an error and no data.
+## As the string or file is read by columns rather than by rows, and because
+## textscan is fairly forgiving as regards read errors, setting this option
+## may have little or no actual effect.
 ## @end itemize
 ##
-## The optional input @var{n} specifes the number of times to use
-## @var{format} when parsing, i.e., the format repeat count.
+## When reading from a character string, optional input argument @var{n}
+## specifies the number of times @var{format} should be used (i.e., to limit
+## the amount of data read).
+## When reading from file, @var{n} specifies the number of data lines to read;
+## in this sense it differs slightly from the format repeat count in strread.
 ##
-## The output @var{C} is a cell array whose length is given by the number
-## of format specifiers.
+## The output @var{C} is a cell array whose second dimension is determined
+## by the number of format specifiers.
 ##
 ## The second output, @var{position}, provides the position, in characters,
 ## from the beginning of the file.
 ##
+## If the format string is empty (not: omitted) and the file contains only
+## numeric data (excluding headerlines), textscan will return data in a number
+## of columns matching the number of numeric fields on the first data line of
+## the file.
+##
 ## @seealso{dlmread, fscanf, load, strread, textread}
 ## @end deftypefn
 
 function [C, position] = textscan (fid, format = "%f", varargin)
 
+  BUFLENGTH = 4096;               ## Read buffer
+  emptfmt = 0;                    ## Signals deliberately empty format string
+
   ## Check input
   if (nargin < 1)
     print_usage ();
   endif
 
   if (isempty (format))
+    emptfmt = 1;
     format = "%f";
   endif
 
-  if (! (isa (fid, "double") && fid > 0) && ! ischar (fid))
-    error ("textscan: first argument must be a file id or character string");
-  endif
-
   if (! ischar (format))
     error ("textscan: FORMAT must be a string");
   endif
 
+  ## Determine the number of data fields & initialize output array
+  num_fields = numel (strfind (format, "%")) - numel (strfind (format, "%*"));
+  C = cell (1, num_fields);
+
+  if (! (isa (fid, "double") && fid > 0) && ! ischar (fid))
+    error ("textscan: first argument must be a file id or character string");
+  endif
+
   args = varargin;
   if (nargin > 2 && isnumeric (args{1}))
     nlines = args{1};
   else
     nlines = Inf;
   endif
+  if (nlines < 1)
+    printf ("textscan: N = 0, no data read\n");
+    return
+  endif
 
   if (! any (strcmpi (args, "emptyvalue")))
     ## Matlab returns NaNs for missing values
@@ -104,13 +127,10 @@
     whitespace = " \b\t";
   else
     ## Check if there's at least one string format specifier
-    fmt = strrep (format, "%", " %");
-    fmt = regexp (fmt, '[^ ]+', 'match');
-    fmt = strtrim (fmt(strmatch ("%", fmt)));
-    has_str_fmt = all (cellfun ("isempty", strfind (strtrim (fmt(strmatch ("%", fmt))), 's')));
-    ## If there is a format, AND whitespace value = empty,
+    has_str_fmt = regexp (format, '%[*]?\d*s', "once");
+    ## If there is a string format AND whitespace value = empty,
     ## don't add a space (char(32)) to whitespace
-    if (! (isempty (args{ipos+1}) &&  has_str_fmt))
+    if (! (isempty (args{ipos+1}) && has_str_fmt))
       args{ipos+1} = unique ([" ", args{ipos+1}]);
     endif
   endif
@@ -119,6 +139,9 @@
     ## Matlab says default delimiter = whitespace.
     ## strread() will pick this up further
     args(end+1:end+2) = {'delimiter', ""};
+    delimiter = "";
+  else
+    delimiter = args{find (strcmpi (args, "delimiter")) + 1};
   endif
 
   collop = false;
@@ -144,6 +167,15 @@
     args(end+1:end+2) = {"returnonerror", 1};
   endif
 
+  ## Check if a headerlines argument is specified
+  headerlines = find (strcmpi (args, "headerlines"), 1);
+  if (! isempty (headerlines))
+    ## Yep. But it is stray when reading from strings...
+    if (ischar (fid))
+      warning ("textscan: 'headerlines' ignored when reading from strings");
+    endif
+  endif
+
   if (ischar (fid))
     ## Read from a text string
     if (nargout == 2)
@@ -151,32 +183,33 @@
     endif
     str = fid;
   else
+    st_pos = ftell (fid);
     ## Skip header lines if requested
-    headerlines = find (strcmpi (args, "headerlines"), 1);
-    ## Beware of zero valued headerline, fskipl would skip to EOF
-    if (! isempty (headerlines) && (args{headerlines + 1} > 0))
-      fskipl (fid, varargin{headerlines + 1});
-      args(headerlines:headerlines+1) = [];
-    endif
-    if (isfinite (nlines) && (nlines >= 0))
-      str = tmp_str = "";
-      n = 0;
-      ## FIXME: Can this be done without slow loop?
-      while (ischar (tmp_str) && n++ < nlines)
-        tmp_str = fgets (fid);
-        if (ischar (tmp_str))
-          str = strcat (str, tmp_str);
-        endif
-      endwhile
-    else
-      str = fread (fid, "char=>char").';
-    endif
+    if (! isempty (headerlines))
+      ## Beware of missing or wrong headerline value
+      if (headerlines  == numel (args)
+         || ! isnumeric (args{headerlines + 1}))
+        error ("Missing or illegal value for 'headerlines'" );
+      endif
+      ## Avoid conveying floats to fskipl
+      args{headerlines + 1} = round (args{headerlines + 1});
+      if (args{headerlines + 1} > 0)
+        ## Beware of zero valued headerline, fskipl would skip to EOF
+        fskipl (fid, args{headerlines + 1});
+        args(headerlines:headerlines+1) = [];
+        st_pos = ftell (fid);
+      elseif (args{headerlines + 1} < 0)
+        warning ("textscan.m: negative headerline value ignored");
+      endif
+    endif    
+    ## Read a first file chunk. Rest follows after endofline processing
+    [str, count] = fscanf (fid, "%c", BUFLENGTH);
+
   endif
 
   ## Check for empty result
   if (isempty (str))
     warning ("textscan: no data read");
-    C = [];
     return;
   endif
 
@@ -185,62 +218,158 @@
   if (! isempty (endofline))
     if (ischar (args{endofline + 1}))
       eol_char = args{endofline + 1};
-      if (isempty (strmatch (eol_char, {"", "\n", "\r", "\r\n"}, 'exact')))
+      if (! any (strcmp (eol_char, {"", "\n", "\r", "\r\n"})))
         error ("textscan: illegal EndOfLine character value specified");
       endif
     else
       error ("textscan: character value required for EndOfLine");
     endif
   else
-    ## Determine EOL from file.  Search for EOL candidates in first 3000 chars
-    eol_srch_len = min (length (str), 3000);
+    if (! ischar (fid))
+    ## Determine EOL from file.  Search for EOL candidates in first BUFLENGTH chars
+    eol_srch_len = min (length (str), BUFLENGTH);
     ## First try DOS (CRLF)
-    if (! isempty (findstr ("\r\n", str(1 : eol_srch_len))))
+    if (! isempty (strfind (str(1 : eol_srch_len), "\r\n")))
       eol_char = "\r\n";
     ## Perhaps old Macintosh? (CR)
-    elseif (! isempty (findstr ("\r", str(1 : eol_srch_len))))
+    elseif (! isempty (strfind (str(1 : eol_srch_len), "\r")))
       eol_char = "\r";
     ## Otherwise, use plain UNIX (LF)
     else
       eol_char = "\n";
     endif
+    else
+      eol_char = "\n";
+    endif
     ## Set up the default endofline param value
-    args(end+1:end+2) = {'endofline', eol_char};
+    args(end+1:end+2) = {"endofline", eol_char};
   endif
 
-  ## Determine the number of data fields
-  num_fields = numel (strfind (format, "%")) - numel (strfind (format, "%*"));
+  if (!ischar (fid))
+    ## Now that we know what EOL looks like, we can process format_repeat_count.
+    ## FIXME The below isn't ML-compatible: counts lines, not format string uses
+    if (isfinite (nlines) && (nlines >= 0))
+      l_eol_char = length (eol_char);
+      eoi = findstr (str, eol_char);
+      n_eoi = length (eoi);
+      nblks = 0;
+      ## Avoid slow repeated str concatenation, first seek requested end of data
+      while (n_eoi < nlines && count == BUFLENGTH)
+        [nstr, count] = fscanf (fid, "%c", BUFLENGTH);
+        if (count > 0)
+          ## Watch out for multichar EOL being missed across buffer boundaries
+          if (l_eol_char > 1)
+            str = [str(end - length (eol_char) + 2 : end) nstr];
+          else
+            str = nstr;
+          endif
+          eoi = findstr (str, eol_char);
+          n_eoi += numel (eoi);
+          ++nblks;
+        endif
+      endwhile
+      ## OK, found EOL delimiting last requested line. Compute ptr (incl. EOL)
+      if (isempty (eoi))
+        printf ("textscan: format repeat count specified but no endofline found\n");
+        data_size = nblks * BUFLENGTH + count;
+      else
+        ## Compute data size to read incl complete EOL
+        data_size = (nblks * BUFLENGTH) + eoi(end + min (nlines, n_eoi) - n_eoi) \
+                    + l_eol_char - 1;
+      endif
+      fseek (fid, st_pos, "bof");
+      str = fscanf (fid, "%c", data_size);
+    else
+      fseek (fid, st_pos, "bof");
+      str = fread (fid, "char=>char").';
+    endif
+  endif
 
-  ## Strip trailing EOL to avoid returning stray missing values (f. strread)
-  if (strcmp (str(end-length (eol_char) + 1 : end), eol_char));
-    str(end-length (eol_char) + 1 : end) = "";
-  endif
+  ## Strip trailing EOL to avoid returning stray missing values (f. strread).
+  ## However, in case of CollectOutput request, presence of EOL is required;
+  ## also in case of deliberately entered empty format string
+  eol_at_end = strcmp (str(end-length (eol_char) + 1 : end), eol_char);
+  if (collop || emptfmt)
+    if (! eol_at_end)
+      str(end+1 : end+length (eol_char)) = eol_char;
+    endif
+  elseif (eol_at_end)
+     str(end-length (eol_char) + 1 : end) = "";
+    ## A corner case: str may now be empty....
+    if (isempty (str)); return; endif
+   endif
 
   ## Call strread to make it do the real work
   C = cell (1, num_fields);
   [C{:}] = strread (str, format, args{:});
 
+  ## I.c.o. empty format, match nr. of cols to nr. of fields on first read line
+  if (emptfmt)
+    ## Find end of first line
+    eoi = index (str, eol_char);
+    if (eoi)
+      ## str contains an EOL, proceed with assessing nr. of columns
+      ncols = countcols (C, str(1 : eoi-1), delimiter, whitespace);
+      ## See if lowermost data row must be completed
+      pad = mod (numel (C{1}), ncols);
+      if (pad)
+        ## Textscan returns NaNs for empty fields
+        C(1) = [C{1}; NaN(ncols - pad, 1)]; 
+      endif
+      ## Replace NaNs with EmptyValue, if any
+      ipos = find (strcmpi (args, "emptyvalue"));
+      if (ipos)
+        C{1}(find (isnan (C{1}))) = args{ipos+1};
+      endif
+      ## Compute nr. of rows
+      nrows = floor (numel (C{1}) / ncols);
+      ## Reshape C; watch out, transpose needed
+      C(1) = reshape (C{1}, ncols, numel (C{1}) / ncols)';
+      ## Distribute columns over C and wipe cols 2:end of C{1}
+      for ii=2:ncols
+        C(ii) = C{1}(:, ii);
+      endfor
+      C{1} = C{1}(:, 1);
+    endif 
+  endif
+
   ## If requested, collect output columns of same class
   if (collop)
     C = colloutp (C);
   endif
 
   if (nargout == 2)
+    ## Remember file position (persistent var)
     position = ftell (fid);
   endif
 
 endfunction
 
 
+## Assess nr of data fields on first line of data
+function ncols = countcols (C, str, dlm, wsp)
+
+  if (isempty (dlm))
+    ## Field separator = whitespace. Fold multiple whitespace into one
+    str = regexprep (str, sprintf ("[%s]", wsp), " ");
+    str = strtrim (str);
+    ncols = numel (strfind (str, " ")) + 1;
+  else
+    ncols = numel (regexp (str, sprintf ("[%s]", dlm))) + 1;
+  endif
+
+endfunction
+
+
 ## Collect consecutive columns of same class into one cell column
 function C = colloutp (C)
 
   ## Start at rightmost column and work backwards to avoid ptr mixup
   ii = numel (C);
-  while ii > 1
+  while (ii > 1)
     clss1 = class (C{ii});
     jj = ii;
-    while  (jj > 1 && strcmp (clss1, class (C{jj - 1})))
+    while (jj > 1 && strcmp (clss1, class (C{jj - 1})))
       ## Column to the left is still same class; check next column to the left
       --jj;
     endwhile
@@ -258,6 +387,7 @@
 
 endfunction
 
+
 %!test
 %! str = "1,  2,  3,  4\n 5,  ,  ,  8\n 9, 10, 11, 12";
 %! fmtstr = "%f %d %f %s";
@@ -276,14 +406,14 @@
 %! assert (b(1,:)', c{1}, 1e-5);
 %! assert (b(2,:)', c{2}, 1e-5);
 
-#%!test
-#%! str = "13, 72, NA, str1, 25\r\n// Middle line\r\n36, na, 05, str3, 6";
-#%! a = textscan(str, '%d %n %f %s %n', 'delimiter', ',','treatAsEmpty', {'NA', 'na'},'commentStyle', '//');
-#%! assert (a{1}, int32([13; 36]));
-#%! assert (a{2}, [72; NaN]);
-#%! assert (a{3}, [NaN; 5]);
-#%! assert (a{4}, {"str1"; "str3"});
-#%! assert (a{5}, [25; 6]);
+%!test
+%! str = "13, 72, NA, str1, 25\r\n// Middle line\r\n36, na, 05, str3, 6";
+%! a = textscan (str, "%d %n %f %s %n", "delimiter", ",","treatAsEmpty", {"NA", "na"},"commentStyle", "//");
+%! assert (a{1}, int32 ([13; 36]));
+%! assert (a{2}, [72; NaN]);
+%! assert (a{3}, [NaN; 5]);
+%! assert (a{4}, {"str1"; "str3"});
+%! assert (a{5}, [25; 6]);
 
 %!test
 %! str = "Km:10 = hhhBjjj miles16hour\r\n";
@@ -291,20 +421,20 @@
 %! str = [str "Km:2 = hhhRjjj miles3hour\r\n"];
 %! str = [str "Km:25 = hhhZ\r\n"];
 %! fmt = "Km:%d = hhh%1sjjj miles%dhour";
-%! a = textscan (str, fmt, 'delimiter', ' ');
-%! assert (a{1}', int32([10 15 2 25]));
+%! a = textscan (str, fmt, "delimiter", " ");
+%! assert (a{1}', int32 ([10 15 2 25]));
 %! assert (a{2}', {'B' 'J' 'R' 'Z'});
-%! assert (a{3}', int32([16 241 3 0]));
+%! assert (a{3}', int32 ([16 241 3 0]));
 
 %% Test with default endofline parameter
 %!test
 %! c = textscan ("L1\nL2", "%s");
 %! assert (c{:}, {"L1"; "L2"});
 
-%% Test with endofline parameter set to '' (empty) - newline should be in word
+%% Test with endofline parameter set to "" (empty) - newline should be in word
 %!test
-%! c = textscan ("L1\nL2", "%s", 'endofline', '');
-%! assert (int8(c{:}{:}), int8([ 76,  49,  10,  76,  50 ]));
+%! c = textscan ("L1\nL2", "%s", "endofline", "");
+%! assert (int8 (c{:}{:}), int8 ([ 76,  49,  10,  76,  50 ]));
 
 %!test
 %! # No delimiters at all besides EOL.  Skip fields, even empty fields
@@ -318,9 +448,24 @@
 %! b = [b; 8*b/5; 8*b*1000/5];
 %! str = sprintf ("%g miles/hr = %g (%g) kilometers (meters)/hr\n", b);
 %! fmt = "%f miles%s %s %f (%f) kilometers %*s";
-%! c = textscan (str, fmt, 'collectoutput', 1);
-%! assert (size(c{3}), [10, 2]);
-%! assert (size(c{2}), [10, 2]);
+%! c = textscan (str, fmt, "collectoutput", 1);
+%! assert (size (c{3}), [10, 2]);
+%! assert (size (c{2}), [10, 2]);
+
+%!test
+%% CollectOutput test with uneven column length files
+%! b = [10:10:100];
+%! b = [b; 8*b/5; 8*b*1000/5];
+%! str = sprintf ("%g miles/hr = %g (%g) kilometers (meters)/hr\n", b);
+%! str = [str "110 miles/hr"];
+%! fmt = "%f miles%s %s %f (%f) kilometers %*s";
+%! c = textscan (str, fmt, "collectoutput", 1);
+%! assert (size (c{1}), [11, 1]);
+%! assert (size (c{3}), [11, 2]);
+%! assert (size (c{2}), [11, 2]);
+%! assert (c{3}(end), NaN);
+%! assert (c{2}{11, 1}, "/hr");
+%! assert (isempty (c{2}{11, 2}), true);
 
 %% Test input validation
 %!error textscan ()
@@ -330,3 +475,186 @@
 %!error <cannot provide position information> [C, pos] = textscan ("Hello World")
 %!error <character value required> textscan ("Hello World", '%s', 'EndOfLine', 3)
 
+%! Test incomplete first data line
+%! R = textscan (['Empty1' char(10)], 'Empty%d %f');
+%! assert (R{1}, int32 (1));
+%! assert (isempty (R{2}), true);
+
+%% bug #37023 (actually a strread test)
+%!test
+%! data = textscan("   1. 1 \n 2 3\n", '%f %f');
+%! assert (data{1}, [1; 2], 1e-15);
+%! assert (data{2}, [1; 3], 1e-15);
+
+%%  Whitespace test (bug #37333) using delimiter ";"
+%!test
+%! tc = [];
+%! tc{1, 1} = "C:/code;";
+%! tc{1, end+1} = "C:/code/meas;";
+%! tc{1, end+1} = " C:/code/sim;";
+%! tc{1, end+1} = "C:/code/utils;";
+%! string = [tc{:}];
+%! c = textscan (string, "%s", "delimiter", ";");
+%! for k = 1:numel (c{1})
+%!   lh = c{1}{k};
+%!   rh = tc{k};
+%!   rh(rh == ";") = "";
+%!   rh = strtrim (rh);
+%!   assert (strcmp (lh, rh));
+%! end
+
+%%  Whitespace test (bug #37333), adding multipleDelimsAsOne true arg
+%!test
+%! tc = [];
+%! tc{1, 1} = "C:/code;";
+%! tc{1, end+1} = " C:/code/meas;";
+%! tc{1, end+1} = "C:/code/sim;;";
+%! tc{1, end+1} = "C:/code/utils;";
+%! string = [tc{:}];
+%! c = textscan (string, "%s", "delimiter", ";", "multipleDelimsAsOne", 1);
+%! for k = 1:numel (c{1})
+%!   lh = c{1}{k};
+%!   rh = tc{k};
+%!   rh(rh == ";") = "";
+%!   rh = strtrim (rh);
+%!   assert (strcmp (lh, rh));
+%! end
+
+%%  Whitespace test (bug #37333), adding multipleDelimsAsOne false arg
+%!test
+%! tc = [];
+%! tc{1, 1} = "C:/code;";
+%! tc{1, end+1} = " C:/code/meas;";
+%! tc{1, end+1} = "C:/code/sim;;";
+%! tc{1, end+1} = "";
+%! tc{1, end+1} = "C:/code/utils;";
+%! string = [tc{:}];
+%! c = textscan (string, "%s", "delimiter", ";", "multipleDelimsAsOne", 0);
+%! for k = 1:numel (c{1})
+%!   lh = c{1}{k};
+%!   rh = tc{k};
+%!   rh(rh == ";") = "";
+%!   rh = strtrim (rh);
+%!   assert (strcmp (lh, rh));
+%! end
+
+%%  Whitespace test (bug #37333) whitespace "" arg
+%!test
+%! tc = [];
+%! tc{1, 1} = "C:/code;";
+%! tc{1, end+1} = " C:/code/meas;";
+%! tc{1, end+1} = "C:/code/sim;";
+%! tc{1, end+1} = "C:/code/utils;";
+%! string = [tc{:}];
+%! c = textscan (string, "%s", "delimiter", ";", "whitespace", "");
+%! for k = 1:numel (c{1})
+%!   lh = c{1}{k};
+%!   rh = tc{k};
+%!   rh(rh == ";") = "";
+%!   assert (strcmp (lh, rh));
+%! end
+
+%%  Whitespace test (bug #37333), whitespace " " arg
+%!test
+%! tc = [];
+%! tc{1, 1} = "C:/code;";
+%! tc{1, end+1} = " C:/code/meas;";
+%! tc{1, end+1} = "C:/code/sim;";
+%! tc{1, end+1} = "C:/code/utils;";
+%! string = [tc{:}];
+%! c = textscan (string, "%s", "delimiter", ";", "whitespace", " ");
+%! for k = 1:numel (c{1})
+%!   lh = c{1}{k};
+%!   rh = tc{k};
+%!   rh(rh == ";") = "";
+%!   rh = strtrim (rh);
+%!   assert (strcmp (lh, rh));
+%! end
+
+%% Test reading from a real file
+%!test
+%! f = tmpnam ();
+%! fid = fopen (f, "w+");
+%! d = rand (1, 4);
+%! fprintf (fid, "  %f %f   %f  %f ", d);
+%! fseek (fid, 0, "bof");
+%! A = textscan (fid, "%f %f");
+%! fclose (fid);
+%! unlink (f);
+%! assert (A{1}, [d(1); d(3)], 1e-6);
+%! assert (A{2}, [d(2); d(4)], 1e-6);
+
+%% Tests reading with empty format, should return proper nr of columns
+%!test
+%! f = tmpnam ();
+%! fid = fopen (f, "w+");
+%! fprintf (fid, " 1 2 3 4\n5 6 7 8");
+%! fseek (fid, 0, "bof");
+%! A = textscan (fid, "");
+%! fclose (fid);
+%! unlink (f);
+%! assert (A{1}, [1 ; 5], 1e-6);
+%! assert (A{2}, [2 ; 6], 1e-6);
+%! assert (A{3}, [3 ; 7], 1e-6);
+%! assert (A{4}, [4 ; 8], 1e-6);
+
+%% Tests reading with empty format; empty fields & incomplete lower row
+%!test
+%! f = tmpnam ();
+%! fid = fopen (f, "w+");
+%! fprintf (fid, " ,2,,4\n5,6");
+%! fseek (fid, 0, "bof");
+%! A = textscan (fid, "", "delimiter", ",", "EmptyValue", 999, "CollectOutput" , 1);
+%! fclose (fid);
+%! unlink (f);
+%! assert (A{1}, [999, 2, 999, 4; 5, 6, 999, 999], 1e-6);
+
+%% Error message tests
+
+%!test
+%! f = tmpnam ();
+%! fid = fopen (f, "w+");
+%! msg1 = "Missing or illegal value for 'headerlines'";
+%! try
+%! A = textscan (fid, "", "headerlines");
+%! end_try_catch;
+%! fclose (fid);
+%! unlink (f);
+%! assert (msg1, lasterr);
+
+%!test
+%! f = tmpnam ();
+%! fid = fopen (f, "w+");
+%! msg1 = "Missing or illegal value for 'headerlines'";
+%! try
+%! A = textscan (fid, "", "headerlines", "hh");
+%! end_try_catch;
+%! fclose (fid);
+%! unlink (f);
+%! assert (msg1, lasterr);
+
+%!test
+%! f = tmpnam ();
+%! fid = fopen (f, "w+");
+%! fprintf (fid,"some_string");
+%! fseek (fid, 0, "bof");
+%! msg1 = "textscan: illegal EndOfLine character value specified";
+%! try
+%! A = textscan (fid, "%f", "EndOfLine", "\n\r");
+%! end_try_catch;
+%! fclose (fid);
+%! unlink (f);
+%! assert (msg1, lasterr);
+
+%!test
+%! f = tmpnam ();
+%! fid = fopen (f, "w+");
+%! fprintf (fid,"some_string");
+%! fseek (fid, 0, "bof");
+%! msg1 = "textscan: character value required for EndOfLine";
+%! try
+%! A = textscan (fid, "%f", "EndOfLine", 33);
+%! end_try_catch;
+%! fclose (fid);
+%! unlink (f);
+%! assert (msg1, lasterr);
new file mode 100644
--- /dev/null
+++ b/scripts/java/javaArray.m
@@ -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
+
new file mode 100644
--- /dev/null
+++ b/scripts/java/javaaddpath.m
@@ -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
+
new file mode 100644
--- /dev/null
+++ b/scripts/java/javaclasspath.m
@@ -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 (), false);
+
+  ## static classpath
+  static_path = javaMethod ("getProperty", "java.lang.System", "java.class.path");
+  static_path_list = strsplit (static_path, pathsep (), false);
+  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
+
new file mode 100644
--- /dev/null
+++ b/scripts/java/javamem.m
@@ -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 configured using the file
+## @file{java.opts}.  The directory where this file resides is
+## determined by the environment variable @w{@env{OCTAVE_JAVA_DIR}}.
+## If unset, the directory where @file{javaaddpath.m} resides is used instead
+## (typically @file{@env{OCTAVE_HOME}/share/octave/@env{OCTAVE_VERSION}/m/java/}
+##
+## @file{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
+
new file mode 100644
--- /dev/null
+++ b/scripts/java/javarmpath.m
@@ -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
+
new file mode 100644
--- /dev/null
+++ b/scripts/java/module.mk
@@ -0,0 +1,75 @@
+FCN_FILE_DIRS += java
+
+java_FCN_FILES = \
+  java/javaArray.m \
+  java/javaaddpath.m \
+  java/javaclasspath.m \
+  java/javamem.m \
+  java/javarmpath.m \
+  java/usejava.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
+
new file mode 100644
--- /dev/null
+++ b/scripts/java/org/octave/ClassHelper.java
@@ -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});
+  }
+}
new file mode 100644
--- /dev/null
+++ b/scripts/java/org/octave/DlgListener.java
@@ -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)
+  {
+  }
+}
new file mode 100644
--- /dev/null
+++ b/scripts/java/org/octave/JDialogBox.java
@@ -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]);
+          }
+      }
+  }
+}
new file mode 100644
--- /dev/null
+++ b/scripts/java/org/octave/Matrix.java
@@ -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;
+  }
+}
new file mode 100644
--- /dev/null
+++ b/scripts/java/org/octave/OctClassLoader.java
@@ -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);
+  }
+}
new file mode 100644
--- /dev/null
+++ b/scripts/java/org/octave/Octave.java
@@ -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");
+  }
+}
new file mode 100644
--- /dev/null
+++ b/scripts/java/org/octave/OctaveReference.java
@@ -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;
+  }
+}
new file mode 100644
--- /dev/null
+++ b/scripts/java/org/octave/TeXcode.java
@@ -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;
+  }
+}
new file mode 100644
--- /dev/null
+++ b/scripts/java/org/octave/TeXtranslator.java
@@ -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 ());
+  }
+}
new file mode 100644
index 0000000000000000000000000000000000000000..75fe9106973d938e3b7849f7dd1916dd674d72ba
GIT binary patch
literal 1205
zc$~#ji%(Nm82@hHrEP3Qy0)-!A#513AZ3sdWbwA;O=Zxs&^SP7s2~Oq#EDwrQen_y
zT`_B*KwQUbz)%@knA;%UATKA$B%{jIMbw!v#~gE8(j|kl<Mv1F<ecC4``%y9Irg0F
zG)aIe001Nz>B$BxDSSu)8>3ryei92#nP$HR;L75gT*psXSJtJN>WtNg>Q0o@T0m1;
zZMKjZl_g~sgQcYOWX%mr5&%Kx=<`xm0SpGi69A!5h}digz~=ywk&!<GTmUEn$O6y<
zAiNO<Km_3jz`eEs&S6z1o5h%zh)$nI(a}jsNlvE|1qLE6_b#@}<?8^yU=kjV#A3wf
zqxkqQ0Y1R#+uL|hR8-X8-#-oD_xsV=v&dv}VWUJch%q#DWMpK0eSHCQp>PTy4U@RI
zGXP#py1P+G2x@6THrqJB7ue!<F9XzIa`2!LBSj4k4x-M^Va%n{j*bpKpZ_c798OnP
zm&fCwF)t`Uxw*(-xC8JuRyCRyfO`N-05nZ|z23&gMpRaYIy#U@gzD>2VWCc^TLEx5
z90<Dx22fSi7EZL=QB)MNT9L;ilgW@)iz+HAD=W*(%aPZMdU{Z7EXvPEt*uC@JOc0o
zP6-P`sj2urr_D<jv7qY=*+%sLE=b^Jl>xB!WF%|y>hGF|7r1`U_k&*2{aJ*(GnNK3
zGqNv{x{(>eO47D(uxp0d0<wU&xz{(o`Xp0Joh-?`cr4_-79g6hLqoNCXd@z5DR5m0
zI&p0A&iv?3k{%Ccst2xnckf;jaamE%M-QBuH0=ig$qWDEaXdlNiniq)Z+yHIXjD^B
zqNX44bo*ACzcB=geYoafxJCpIHM9wZc8}sU;7H#m{`U1Aa(tz-TBoeV%*}T4uZXD_
z8?F;0S$m}a&Ic81+{3n=#g938et)g)mXFPm4iV3K#VYI3GwHm|fX&}5{=QH70#eVe
z7yrnp)CJHNF|hn!-2JDu)||jLHQ>2bj3~ZI!3LJ#Yhr3P7^GB!ggM70Z!N@O_fZ9N
zv-MSZy?b1NJzYH0M6BR<vom#!2QLa~Z>w#p1o3csc3S=pDP<C`)yDaP=DS@V&P+V|
zx0#&XY@5>`k6&vNd@Ev2WF8NjTYpNh1X)$PCU(h;%!QXNZs(<N<+2+GPd=yG`0YY!
ztM8rp4aF!9J7RC1<G31fKVs?U@I_7QXJd%52QFp%0UBm<qxwDcyNz#A@No2{96i&2
z?G-%nZN2vXn7mfsO)?MnESjsHwHAiqh|9q(S1(nru29U(>%BTxXlvq&S1;TvO1YY9
tr|Bk1k0^TUPu$}keX609HU?2N0Ws;HWLGTB1><iF87bMxm$k*Ve*if99-ROH
new file mode 100644
index 0000000000000000000000000000000000000000..4246920a6171aaa8d30190391e4403789217012c
GIT binary patch
literal 963
zc%17D@N?(olHy`uVBq!ia0vp^4nVBH!3-p)I`?e@QY`6?zK#qG>ra@ocD)4hB}-f*
zN`mv#O3D+9QW+dm@{>{(JaZG%Q-e|yQz{EjrrIztFop&Agt+opuugf?>V4mM=G$)h
zDLi5soEm!t=DzE1dsQkJ!0vKSyWwTNNFqnVV{i5C{Jb`-7I$R3URCMe5^j1~l>aok
z|8>LC_cKjyODas`(LODxb6zm@Nr2o0p2=@oA|5(!{J7lho^I`nZ1o-dQq^4U_w<*&
zpVjfI!sxcR`#rtbNA60CdA;r%l{`ya`(e?vHyxo5?JJ+BmpxD6b72d5U@hRsrm~i=
z^<`=BLz|LkN$R`!B?>reUS#QB6H=JLE8V~y_sE0CidAVoZ^5$|y<0*B&tkRD3T8hI
zce<zP_rT2co{m&4m*yb>$Ghsv%lP<R*$i%ph{SOS$8aoqKW*ZhrlyyLYFqh5;yDC^
z*!kVr)_hpF=-pK9bAr*2TxD9h`JCA#iaDL{X*t|g(>g9N|J@|18ZO-{LUMgPigS21
zj|vn%i<6(sll~+)@{yD32L8~8cI!VbvAwGd4FA8I&3*%^qLLuL;Q#an3^mtJzW~N>
zsi%u$NX4xrjU@sMECS3+*?^=Svx?D<q>5OVqaUOg1RQ?wa7+-mbloIn`tfXFs(NVL
z(0J7-@OH1I(0WD&#+K_0!tT<AmIoE~fb_;OE9ESm(`z~DBS>onZ%1;WsF8UxM5k$k
zz3(M^{~3}{jcqqnKFTE8f;HZ2IWpmq?t#+>JFYV{FdWKvu!(lurtohH2hah$2~R%@
z3Leb|nPIMAF#WWW#D0(o_Zj@+{h1^Gfb`cf|G6Y8^07Tp5u~VLzH96328bFq{Zc_w
zu$q5Nt%^ERG=)K$T@EnF=`u2@3OO(Y#w=lE5jYBQe##=-CC-aVpw3Tt>b>E)*lDQq
z4`^tI9`1}31v}qfHe#liQRHKPPoQB6`Wl-z7`}X9%AnBjLHdEfx#Z<f`am98WFf`K
h)RDx@fJE>xG$lk{-#7cq7hv==c)I$ztaD0e0su9Tqz(W8
new file mode 100644
index 0000000000000000000000000000000000000000..030f44d2584ef9f0cfaec03d68ebd16642fe1302
GIT binary patch
literal 1463
zc$^(m2~<-@6n+0gAcUlXEV5Wl5fDL95ELrq{78t2Y+(zF6ax}A2`IAb@gPWLvn(Ql
zwU%(iMoIxwR6xW)0izXK(c)56h=@wvSZkwX`stiA^UlnBGxxsx<`waMcQ9yXGyq`m
zxa<JZGM6S*gIw9?iU&xe8OQQr0kkN#Qi@-Zd($+}(6qpm*tE>3R1vUZQldpno;WH_
z6d;O<$=-ic<OYD{^1XvRv3tlk3_<L3NVvc57!uSXZUJ&hN9NTCI10>54Pp1e<L;JY
z2ws20rq#f|2~JYj(hdm0wm#Dm1a9{rZ30F=!o1op9^pfaSm`3LrCwDC!Y84B3UU_d
zClUOs2GJsx_-V}^1a?J?KqQnP{A)GtuQpFd@Y_6f1c5{L%4h_v8d?&9qc0$R)?0#>
zry}rpvsa2Bc+Tt~33_q^dBRZzmY@|65N#B}@Vwn&1T!-bG0TWRz#g~AL0JALd<=nC
z2W1+8Z9K5&4U!RY2x-hA*pLQ$rosLM%&XSMB5N@+mLSa!B;o?}%^F4_;LYe3AaFVY
zum8~*N8tN3t{&n07hz*PbUoJbLvZk2YBQo|ASj(Pi$|bR!SqM)o1#V|YAMnt$vB9!
zWe98{A>@kvUi5_oxmF-(c@I~|p&KzH5x75vhaU{GP~3C3JpdZlcx+Zs)}v^J!p456
zl{*}BG9Ls2fsfDNIZK~9E~O;cngEATc*twYNK(Hh#@_utFc7PaB_*lX3pkB{^$8^j
zDJi!GB8?l*8z(-S=+niM)P#KKt^Ht~LQ{{RpKe-MFxui=nqbx(Tc7iUSr;;-46-(A
zoLsv>+)F0|nlie4qs$_@t68h)Sg)R*<c8!|Ma}s)7C+bk=}uLPv=X{66)8JE5vJuB
zQ*_p`G2-%MvYSODi7q!EP>3S!<W0KE1+w8g7s^E7Xl0Rqdv8DcXbgrI_S|F+c2yf#
z>>i5~%B7M9YJh*-ZAR6KDhidUl^OC^xC2Hhw>DkF;cyuCySxl`Fz;8?8c5}O%v_VS
zw!wav+Ghm?9<m@OVkW{Nxk%YTbYBE6Mru-%@ZD@KL%R7+hO^`F$Y+&)6XPQkb1Z=5
zEToJIHQL%}rj5aQwx9P?vIx#Z@d5lX>0(lflmw-t!nS~Z*0DNU`E9xqA3fCDTglu;
z(xpn7oK-P(N249{WtEM(23OjDS#zb!NfBV}s~?sN(SO_-qv5t83yQ7EW#zo;jF{+*
z&!ToZ`5PNg`e|z!lB`~~=NWNrJ8>gJ%h?y399)kTzMxF!8(Pj}VVZjR2iv}(aamDq
zwVAmAl5?#^S%os*SsM4qj#XtqUUs?QV1~Kgq8$D*M}K^$ey?Mg>n-c*V!{r0n;F#v
zQq6U@<;x~4{QNWhuNCG}c|4vd;Y18Sew$%<rw(Z9X|x;<&%id}8ZJpm?D@GWnu$qF
z(4|V2zxms^zpcsi2}(es;0d!iu=e;>-^)K07h9bYtPk~a;x8%sUUrK2>LteT7GA8N
zISaj?DP_+caUGY!PSyXfb6N2<Hhd3uM_@d|#!)Qp(PCF!{jqj-DYXYQ=R$pXnpVX|
zO>=p)JlM`cmqgnw{c}_7jl5tR(}V;4eW7^<bbj{fj+*lIBwD-1-EvO&;ifdOv9i{t
zP#QK9mEzMaHRW~AOV#a2Jn&GZ3UAEf&gy#2V65g=%lv>?_Z9r>!hI{r0BJaGkSP}b
zysN&e-F~&nOEc}T0XWfA-V}AlopftDc)m(4q3Y-q74D-E*xE7^mmWcbnekE;+%l`S
zUl7tvsI<J+Iws$>ydnAfMq%huvy7gJl#TREQT6E9)YK7omFkE)`N^43Ri+^$h}F1K
iN#O48R#sN-o`7k=qr&T7xzciAY4ALK+0EO9dH(_6kXd;E
new file mode 100644
index 0000000000000000000000000000000000000000..3098763a86700200907fe01a2adb0b8820ee6451
GIT binary patch
literal 1778
zc$~#ljX%{_7=NyN>Ed2)ADdLG?q*Fj(_N+6+Sb(zw~>#~(#xdVDy^v-p;hYVEu>JA
zmn7vS8;Q|XRIay$66$J9tD8cM66Gc7yWibEvGaM(dCupY=lP!R`JR_ZXD551!4v}`
z60VRfb78%dtztfxZR3|lD_O_eX1mgss37{l*s3_~<Yt-6N}_!;iI@<gQLz3Qk)MR9
z$CK!*1fog15`Ilm6LHDe(QWx!fGn5JV_W)$DANkCz<69Z<W8W;pSgYu%FL$hobA9t
zZA?>G0H$Mvk3J5%Lf8?hyBUV4;if+NreJsv;0@RTy6B<Hh2$4X%hr*1-~qrA_!w_Z
zFet(RwX11w7~QIz1Iz{NS)6;dq-mmE%npEu?hi2XA;!pcs{=3tZ<YW8yr5HOC?<h=
zT4?Mkp-XGy9rUh)M%#&Eh*U%xA`hZIq5z^HT^iJ3V+dO7Z2rU$6KOEe8`E^)wHkba
z4!W)0gE3(S4~xvT9Xl(0FU5kXhzW-69K-+<sK=Bri6GG0Yw`)2HyNj6vC9LI`@!~C
zvgE}Jx32*mI_d~G*}zv0LzcsX23p`S+ZdE|)(9`@VxAF8W8-d*@8G>2zj%S=!ycGo
zW5I6E0-sHVzVf0yo0WcBt^{nox_4X2FJ7hlwqM`B<HmuXRe|2+2X|H++EvLYs)KxP
z2K&~8_|=B`*M$Y#4&PfJv9BR=f5VXjO;Le&j~-MXJJcK<bU!AzB{rn>cxc;+u(r7H
zzvCkwo{H2Y9C@4=)t+?pX>v@*>DaE6<6UP?bf?Dkq@C<NcdGAv!t?aR7a2(}Gm{6h
zQU))ad7Yg)^jq3+&bg7?^KUL@jOAs%y_7Yce*p#ADEt*gIk=n)<wX=<!j*hnEkH>j
zt`*_>W!zArtQe}RC@(?9HB?<k^$q+{hMVQ6sX%Qd>Z)+N8ufqRPAwYh(0B_?w{f=~
z>IO77;(inUyoVMwTAR`KCmyum?^Zng3y<2Md4Tpuc%s46$LMHB=M!{2MRzB9p5dQv
z^!A|dA3X0v|8u;2fq{Mu4&c=whF)WM2qVK79l@JXjE!M@9Pi$NEivvrhuLFb_P98?
z;{PpVqwBDZNT*}PGF!L3De`Q4?x~W)!F9QcG@-7e*z=BfW^mqgF=N)K>sY5=-P%$l
zlCE7lS#D$!C%7d0x?~?i6%w)iDyRE3G7<l_SY^g@b8};|k~e=&Vn!m+ymxuveI1Uz
zzW&*|{=110*<OZGKGxROt5<tldJtdi$ThRB@|LPnA5~gdKA0=?BKwt0!nxes*tN<9
zGya2@GhbJc>A^3~=4WI`%NlL+(wG)entt$Tq8{-?PLpg3=m*V{zRvc}X{PI(%}yIF
zD6dgdC9$bHne_CWMNv`3#S<1snbc%RtvLQ^`Yi%>;SG9{(qMtY*WYK$R{ww@e*OEN
z!}Cs7$=UC2leOyM;mH~G)%Dd6%gck3S|b-9|I}P{%fV&BJuRv?lM^@Jy)0x}VVv)e
zyh-7bM)DAFNr!)$Q!*r8EGaGQUn)@ewa4T-L{;u&0Us-Z($mc)Go`Oe7kybe(?ahr
z1H-6IT7eW(=&tcRCM+!MQT4s~tw!M-;)J$Q#JHv99V`9isj2?{N~M^4vay-V6Geye
zd`MPi;#^jC$iR7VBQIAgK;9k=f1zrcS!}A5+pCyLBIy+&B~zqBF>ieYNBQ4oQ}k>q
zg#AU;+q7hAj)^QtNS(E^Yufzhy#gb<2)hXV79ktSLb_4~t$(YXvf}pIzB!Zf&D-C0
z%zrtBMYa)A=F&B$UzCYC{)rs-^oe37Kb)hctriIib}bv%k688QOHF>HS+lw3<rZ^h
zsZ0&>wVCb$Su-z-GgY?4r^`4x@^JUfpR`JUF5PHylK-=+n@OrRw=v9`k)su0yVNOu
zL&0<&W4N%`b0a@rX)2e;+O07bNfY%HM>=<#ld+DQ+p~3&P1zIpVoN<q@~n?Ifo8J!
zgkp8P=Mrt8yFg>P%Gp`8oMRwz-jX>xl)c0%QoSm6Irclo*~dpKmOCxWTjCk~FUDV`
AV*mgE
new file mode 100644
index 0000000000000000000000000000000000000000..3c7edfb31faf7dba138ec6d3014dfa4bd91dbb8d
GIT binary patch
literal 1508
zc$~$Qi&Ila6o>cTn*<UPNdl$`qLZpT1VmmUttgieP*i9DEl?Qckq4n;5lRI+T7mM2
zf(}AZ5L6zKLJ>+MYQbuGh=@`}Ml_;r6|F_9)u93*xw*H?U(ub}bLPyM^V{#t+1*33
z$W0uU0}BAa3EwP@h8~AoY>h!%6>{_<bTn0PL@)q9+*n6H{1V2Z?9jOEm<(lhPI8t4
z1j{p06yosR$tp#(B3ZsKb661w0Fo!$wmsC(k3tYKcOQ+QmQK%LBvqM~MiHcMY#fw7
z1VB4MZXwA10Nf$S(Ajy+LaB>NPz#y$>;+~fS6C>yL_(2NAwhZo5CTBD*%JNg4NRdi
zF;s3YHBT@}>LfuSZSClsiDo7_WA`wEVgv@#Cmz$v%Bb$k=<W=RAQMa$%w$;{A5Re!
zIz7WKETs5+s<DwWlk~UKSY{@aqSe;Ivl_NVU@u-ml7RjDsiw1#x%6ruYN3K|-A2u%
z)wlsmNkz0;>h@jOLi~5FC_%9aie<9Uj#Z)qgP76G17NE56xwwWn<rpMGnyeVVl>ln
z9N8Fznk)!G+5P?m^4Q+`)%xjkj!KQbdAmlXwmDr7;f2SmQKM;t(X=!~$~0MmDk`C6
z9Qej|o?y%x6R-SYKWkj8Yi7-vJg*Pi&&(-*Jin;5&HnyF>r36JVM1UuGoqrgwst0*
z)Yv_BHFSB|(UCFK|GPi{eX9xpY-hMMczf<dO3M&dQCaF^)Y;s8*NRw+8FfD6Vfi)7
zonAkDJl2Cs0t2cL8rKtJxhs}qGu^qOK|@))F0|-crU-EH0JiI#y|Oh*RzAr}DWCJI
z+H-#~Up3gl7w2^@kvVcz9ejuMRl~zJKKR;*f&@H~*A|@z`qS}9O)cBT0M>Zg`KQ|Y
z#_r&$kWJ^D0gdaAO*<yajROPyk`O1Sk3^i;7e?}&y&f?;KTC~bbMZL#X5Kx4l4(mv
zS`fWbsl2MbEiu%Ah0G}PQ;ZI{Q~8|o2Nm>__5a-RSbcPm36MfHzB)$Zbugfxo+Y@>
z)9Z_iUv1<Y0+EF(Znk$Uv!oh$_ikJ+Vag>A>jW+kq#1GSJ4rmn?IaEPu0u+mon3=Y
zo;Ee$Sy&?ksPzEg<R}srdx5ZTbvpY|I*%vDwCwSkue_UJ^ImMt-Ut4+R<9T$;1|pi
zYV<rD_<VSLiSGt<K{`Cr!>v~e5F9g<DHIJ1W5B;jLfC_lA$6j67KX4jW$eoLET7I2
zQN8X9m*<*}Wl)r}C#OKjW%=V3C-Nf%a?}9!B4vq8E?&L!NsEt_s2<JCUwPtC-Lg>-
zAMX@WjtJ=(4w4;`nmn*M3B<esHk2d1+9#<lhm+y|k{p(*J?QAl=rgSdekr2ijOx~*
zk4sq%ZC2LekwW{y=ly)vm&hn>YdNA9V~I8MQg1D`fPeQwua?#&k^`4cseV*nP@UB5
z*4JLz;J5%es^Pz<{q>?#wl(b-W47pA&BpbY{ED;S*egyoeSYOxTzw5QS{ILAd8%r5
zOBpI@b%2*eSkF6)xkcg5o4-bUD}NS@f}kM!0p4B@Ity~TkNGuL*NGJsD_dmtspq@8
zMs{daf>nKuLRc#J{%%x3WTpq46_$6}i+8?jBvy9h!JTW(0+{{aZ+x9=+e7_3j8i^2
zxfbaGLRMH@6`aD+!=Wo~{<bS2BCfdTOi<mKGlPlO@B8yEZ-JycE~urCri||EyIa)h
z={?=8`<%6tGHWjWlY8uusfm@&eebthWhnmaVb$FPs0P_Jeo8TLOgC^%Tk;79&qF{`
W>LQS{6Z-?cdJrBODeaIX75oP~Ex-c+
rename from scripts/miscellaneous/usejava.m
rename to scripts/java/usejava.m
--- a/scripts/miscellaneous/usejava.m
+++ b/scripts/java/usejava.m
@@ -1,4 +1,5 @@
 ## Copyright (C) 2012 Rik Wehbring
+## Parts Copyright (C) 2012 Philip Nienhuis <prnienhuis@users.sf.net>
 ##
 ## This file is part of Octave.
 ##
@@ -18,7 +19,7 @@
 
 ## -*- texinfo -*-
 ## @deftypefn {Function File} {} usejava (@var{feature})
-## Return true if the specific Sun Java element @var{feature} is available.
+## Return true if the Java element @var{feature} is available.
 ##
 ## Possible features are:
 ##
@@ -36,10 +37,12 @@
 ## Swing components for lightweight GUIs.
 ## @end table
 ##
-## This function is provided for compatibility with @sc{matlab} scripts which
-## may alter their behavior based on the availability of Java.  Octave does
-## not implement an interface to Java and this function always returns
-## @code{false}.
+## @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)
@@ -48,16 +51,38 @@
     print_usage ();
   endif
 
-  if (! any (strcmp (feature, {"awt", "desktop", "jvm", "swing"})))
-    error ("usejava: unrecognized feature '%s'", feature);
-  endif
+  retval = false;
 
-  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 ("awt"), false)
+%!assert (usejava ("desktop"), false)
+
+%!testif HAVE_JAVA
+%! assert (usejava ("jvm"), true);
 
 %% Test input validation
 %!error usejava ()
--- a/scripts/linear-algebra/commutation_matrix.m
+++ b/scripts/linear-algebra/commutation_matrix.m
@@ -96,24 +96,26 @@
 
 endfunction
 
+
 %!test
-%! c = commutation_matrix(1,1);
-%! assert(c,1);
+%! c = commutation_matrix (1,1);
+%! assert (c,1);
 
 %!test
-%! A = rand(3,5);
-%! vc = vec(A);
-%! vr = vec(A');
-%! c = commutation_matrix(3,5);
-%! assert(c*vc,vr);
+%! A = rand (3,5);
+%! vc = vec (A);
+%! vr = vec (A');
+%! c = commutation_matrix (3,5);
+%! assert (c*vc, vr);
 
 %!test
-%! A = rand(4,6);
-%! vc = vec(A);
-%! vr = vec(A');
-%! c = commutation_matrix(4,6);
-%! assert(c*vc,vr);
+%! A = rand (4,6);
+%! vc = vec (A);
+%! vr = vec (A');
+%! c = commutation_matrix (4,6);
+%! assert (c*vc, vr);
 
-%!error commutation_matrix(0,0);
-%!error commutation_matrix(1,0);
-%!error commutation_matrix(0,1);
+%!error <M must be a positive integer> commutation_matrix (0,0)
+%!error <N must be a positive integer> commutation_matrix (1,0)
+%!error <M must be a positive integer> commutation_matrix (0,1)
+
--- a/scripts/linear-algebra/cond.m
+++ b/scripts/linear-algebra/cond.m
@@ -74,20 +74,19 @@
 
 endfunction
 
+
 %!test
-%! y= [7, 2, 3; 1, 3, 4; 6, 4, 5];
+%! y = [7, 2, 3; 1, 3, 4; 6, 4, 5];
 %! tol = 1e-6;
-%! type = {1, 2, 'fro', 'inf', inf};
-%! for n = 1:numel(type)
+%! type = {1, 2, "fro", "inf", inf};
+%! for n = 1:numel (type)
 %!   rcondition(n) = 1 / cond (y, type{n});
 %! endfor
 %! assert (rcondition, [0.017460, 0.019597, 0.018714, 0.012022, 0.012022], tol);
 
-%!assert (abs (cond ([1, 2; 2, 1]) - 3) < sqrt (eps));
-
-%!assert (cond ([1, 2, 3; 4, 5, 6; 7, 8, 9]) > 1.0e+16);
+%!assert (cond ([1, 2; 2, 1]), 3, sqrt (eps))
+%!assert (cond ([1, 2, 3; 4, 5, 6; 7, 8, 9]) > 1.0e+16)
 
-%!error cond ();
+%!error cond ()
+%!error cond (1, 2, 3)
 
-%!error cond (1, 2, 3);
-
--- a/scripts/linear-algebra/condest.m
+++ b/scripts/linear-algebra/condest.m
@@ -132,7 +132,7 @@
     have_A = true;
 
     if (nargin > 1)
-      if (isscalar (varargin{2}))
+      if (! is_function_handle (varargin{2}))
         t = varargin{2};
         have_t = true;
       elseif (nargin > 2)
@@ -194,45 +194,47 @@
 
 endfunction
 
+
 %!demo
-%!  N = 100;
-%!  A = randn (N) + eye (N);
-%!  condest (A)
-%!  [L,U,P] = lu (A);
-%!  condest (A, @(x) U\ (L\ (P*x)), @(x) P'*(L'\ (U'\x)))
-%!  condest (@(x) A*x, @(x) A'*x, @(x) U\ (L\ (P*x)), @(x) P'*(L'\ (U'\x)), N)
-%!  norm (inv (A), 1) * norm (A, 1)
+%! N = 100;
+%! A = randn (N) + eye (N);
+%! condest (A)
+%! [L,U,P] = lu (A);
+%! condest (A, @(x) U \ (L \ (P*x)), @(x) P'*(L' \ (U'\x)))
+%! condest (@(x) A*x, @(x) A'*x, @(x) U \ (L \ (P*x)), @(x) P'*(L' \ (U'\x)), N)
+%! norm (inv (A), 1) * norm (A, 1)
 
 ## Yes, these test bounds are really loose.  There's
 ## enough randomization to trigger odd cases with hilb().
 
 %!test
-%!  N = 6;
-%!  A = hilb (N);
-%!  cA = condest (A);
-%!  cA_test = norm (inv (A), 1) * norm (A, 1);
-%!  assert (cA, cA_test, -2^-8);
+%! N = 6;
+%! A = hilb (N);
+%! cA = condest (A);
+%! cA_test = norm (inv (A), 1) * norm (A, 1);
+%! assert (cA, cA_test, -2^-8);
 
 %!test
-%!  N = 6;
-%!  A = hilb (N);
-%!  solve = @(x) A\x; solve_t = @(x) A'\x;
-%!  cA = condest (A, solve, solve_t);
-%!  cA_test = norm (inv (A), 1) * norm (A, 1);
-%!  assert (cA, cA_test, -2^-8);
+%! N = 6;
+%! A = hilb (N);
+%! solve = @(x) A\x; solve_t = @(x) A'\x;
+%! cA = condest (A, solve, solve_t);
+%! cA_test = norm (inv (A), 1) * norm (A, 1);
+%! assert (cA, cA_test, -2^-8);
 
 %!test
-%!  N = 6;
-%!  A = hilb (N);
-%!  apply = @(x) A*x; apply_t = @(x) A'*x;
-%!  solve = @(x) A\x; solve_t = @(x) A'\x;
-%!  cA = condest (apply, apply_t, solve, solve_t, N);
-%!  cA_test = norm (inv (A), 1) * norm (A, 1);
-%!  assert (cA, cA_test, -2^-6);
+%! N = 6;
+%! A = hilb (N);
+%! apply = @(x) A*x; apply_t = @(x) A'*x;
+%! solve = @(x) A\x; solve_t = @(x) A'\x;
+%! cA = condest (apply, apply_t, solve, solve_t, N);
+%! cA_test = norm (inv (A), 1) * norm (A, 1);
+%! assert (cA, cA_test, -2^-6);
 
 %!test
-%!  N = 12;
-%!  A = hilb (N);
-%!  [rcondA, v] = condest (A);
-%!  x = A*v;
-%!  assert (norm(x, inf), 0, eps);
+%! N = 12;
+%! A = hilb (N);
+%! [rcondA, v] = condest (A);
+%! x = A*v;
+%! assert (norm (x, inf), 0, eps);
+
--- a/scripts/linear-algebra/cross.m
+++ b/scripts/linear-algebra/cross.m
@@ -91,25 +91,26 @@
 
 endfunction
 
+
 %!test
 %! x = [1 0 0];
 %! y = [0 1 0];
 %! r = [0 0 1];
-%! assert(cross(x, y), r, 2e-8);
+%! assert (cross (x, y), r, 2e-8);
 
 %!test
 %! x = [1 2 3];
 %! y = [4 5 6];
 %! r = [(2*6-3*5) (3*4-1*6) (1*5-2*4)];
-%! assert(cross(x, y), r, 2e-8);
+%! assert (cross (x, y), r, 2e-8);
 
 %!test
 %! x = [1 0 0; 0 1 0; 0 0 1];
 %! y = [0 1 0; 0 0 1; 1 0 0];
 %! r = [0 0 1; 1 0 0; 0 1 0];
-%! assert(cross(x, y, 2), r, 2e-8);
-%! assert(cross(x, y, 1), -r, 2e-8);
+%! assert (cross (x, y, 2), r, 2e-8);
+%! assert (cross (x, y, 1), -r, 2e-8);
 
-%!error cross(0,0);
-%!error cross();
+%!error cross (0,0)
+%!error cross ()
 
--- a/scripts/linear-algebra/duplication_matrix.m
+++ b/scripts/linear-algebra/duplication_matrix.m
@@ -87,9 +87,10 @@
 
 endfunction
 
+
 %!test
 %! N = 2;
-%! A = rand(N);
+%! A = rand (N);
 %! B = A * A';
 %! C = A + A';
 %! D = duplication_matrix (N);
@@ -98,7 +99,7 @@
 
 %!test
 %! N = 3;
-%! A = rand(N);
+%! A = rand (N);
 %! B = A * A';
 %! C = A + A';
 %! D = duplication_matrix (N);
@@ -107,14 +108,15 @@
 
 %!test
 %! N = 4;
-%! A = rand(N);
+%! A = rand (N);
 %! B = A * A';
 %! C = A + A';
 %! D = duplication_matrix (N);
 %! assert (D * vech (B), vec (B), 1e-6);
 %! assert (D * vech (C), vec (C), 1e-6);
 
-%!error duplication_matrix ();
-%!error duplication_matrix (0.5);
-%!error duplication_matrix (-1);
-%!error duplication_matrix (ones(1,4));
+%!error duplication_matrix ()
+%!error duplication_matrix (0.5)
+%!error duplication_matrix (-1)
+%!error duplication_matrix (ones (1,4))
+
--- a/scripts/linear-algebra/expm.m
+++ b/scripts/linear-algebra/expm.m
@@ -141,14 +141,16 @@
 
 endfunction
 
-%!assert(norm(expm([1 -1;0 1]) - [e -e; 0 e]) < 1e-5);
-%!assert(expm([1 -1 -1;0 1 -1; 0 0 1]), [e -e -e/2; 0 e -e; 0 0 e], 1e-5);
 
-%% Test input validation
-%!error expm ();
-%!error expm (1, 2);
-%!error <expm: A must be a square matrix> expm([1 0;0 1; 2 2]);
+%!assert (norm (expm ([1 -1;0 1]) - [e -e; 0 e]) < 1e-5);
+%!assert (expm ([1 -1 -1;0 1 -1; 0 0 1]), [e -e -e/2; 0 e -e; 0 0 e], 1e-5);
 
 %!assert (expm (10), expm (10))
 %!assert (full (expm (eye (3))), expm (full (eye (3))))
 %!assert (full (expm (10*eye (3))), expm (full (10*eye (3))), 8*eps)
+
+%% Test input validation
+%!error expm ()
+%!error expm (1, 2)
+%!error <expm: A must be a square matrix> expm ([1 0;0 1; 2 2])
+
--- a/scripts/linear-algebra/housh.m
+++ b/scripts/linear-algebra/housh.m
@@ -23,8 +23,8 @@
 ##
 ## @example
 ## @group
-## (I - beta*housv*housv')x =  norm(x)*e(j) if x(j) < 0,
-## (I - beta*housv*housv')x = -norm(x)*e(j) if x(j) >= 0
+## (I - beta*housv*housv')x =  norm (x)*e(j) if x(j) < 0,
+## (I - beta*housv*housv')x = -norm (x)*e(j) if x(j) >= 0
 ## @end group
 ## @end example
 ##
@@ -66,7 +66,7 @@
   ## Check for valid inputs.
   if (! isvector (x) && ! isscalar (x))
     error ("housh: first input must be a vector");
-  elseif (! isscalar(j))
+  elseif (! isscalar (j))
     error ("housh: second argment must be an integer scalar");
   else
     housv = x;
@@ -92,42 +92,43 @@
 
 endfunction
 
+
 %!test
 %! x = [1 2 3]';
 %! j = 3;
-%! [hv, b, z] = housh(x, j, 0);
-%! r = (eye(3) - b*hv*hv') * x;
-%! d = - norm(x) * [0 0 1]';
-%! assert(r, d, 2e-8);
-%! assert(z, 0, 2e-8);
+%! [hv, b, z] = housh (x, j, 0);
+%! r = (eye (3) - b*hv*hv') * x;
+%! d = - norm (x) * [0 0 1]';
+%! assert (r, d, 2e-8);
+%! assert (z, 0, 2e-8);
 
 %!test
 %! x = [7 -3 1]';
 %! j = 2;
-%! [hv, b, z] = housh(x, j, 0);
-%! r = (eye(3) - b*hv*hv') * x;
-%! d = norm(x) * [0 1 0]';
-%! assert(r, d, 2e-8);
-%! assert(z, 0, 2e-8);
+%! [hv, b, z] = housh (x, j, 0);
+%! r = (eye (3) - b*hv*hv') * x;
+%! d = norm (x) * [0 1 0]';
+%! assert (r, d, 2e-8);
+%! assert (z, 0, 2e-8);
 
 %!test
 %! x = [1 0 0]';
 %! j = 1;
-%! [hv, b, z] = housh(x, j, 10);
-%! r = (eye(3) - b*hv*hv') * x;
-%! d = norm(x) * [1 0 0]';
-%! assert(r, d, 2e-8);
-%! assert(z, 1, 2e-8);
+%! [hv, b, z] = housh (x, j, 10);
+%! r = (eye (3) - b*hv*hv') * x;
+%! d = norm (x) * [1 0 0]';
+%! assert (r, d, 2e-8);
+%! assert (z, 1, 2e-8);
 
 %!test
 %! x = [5 0 4 1]';
 %! j = 2;
-%! [hv, b, z] = housh(x, j, 0);
-%! r = (eye(4) - b*hv*hv') * x;
-%! d = - norm(x) * [0 1 0 0]';
-%! assert(r, d, 2e-8);
-%! assert(z, 0, 2e-8);
+%! [hv, b, z] = housh (x, j, 0);
+%! r = (eye (4) - b*hv*hv') * x;
+%! d = - norm (x) * [0 1 0 0]';
+%! assert (r, d, 2e-8);
+%! assert (z, 0, 2e-8);
 
-%!error housh([0]);
-%!error housh();
+%!error housh ([0])
+%!error housh ()
 
--- a/scripts/linear-algebra/isdefinite.m
+++ b/scripts/linear-algebra/isdefinite.m
@@ -67,19 +67,19 @@
 
 %!test
 %! A = [-1 0; 0 -1];
-%! assert (isdefinite (A), -1)
+%! assert (isdefinite (A), -1);
 
 %!test
 %! A = [1 0; 0 1];
-%! assert (isdefinite (A), 1)
+%! assert (isdefinite (A), 1);
 
 %!test
 %! A = [2 -1 0; -1 2 -1; 0 -1 2];
-%! assert (isdefinite (A), 1)
+%! assert (isdefinite (A), 1);
 
 %!test
 %! A = [1 0; 0 0];
-%! assert (isdefinite (A), 0)
+%! assert (isdefinite (A), 0);
 
 %!error isdefinite ()
 %!error isdefinite (1,2,3)
--- a/scripts/linear-algebra/ishermitian.m
+++ b/scripts/linear-algebra/ishermitian.m
@@ -50,18 +50,21 @@
 
 endfunction
 
-%!assert(ishermitian (1));
-%!assert(!(ishermitian ([1, 2])));
-%!assert(ishermitian ([]));
-%!assert(ishermitian ([1, 2; 2, 1]));
-%!assert(!(ishermitian ("test")));
-%!assert(ishermitian ([1, 2.1; 2, 1.1], 0.2));
-%!assert(ishermitian ([1, -2i; 2i, 1]));
-%!assert(!(ishermitian ("t")));
-%!assert(!(ishermitian (["te"; "et"])));
-%!error ishermitian ([1, 2; 2, 1], 0, 0);
-%!error ishermitian ();
+
+%!assert (ishermitian (1))
+%!assert (! ishermitian ([1, 2]))
+%!assert (ishermitian ([]))
+%!assert (ishermitian ([1, 2; 2, 1]))
+%!assert (! ishermitian ("test"))
+%!assert (ishermitian ([1, 2.1; 2, 1.1], 0.2))
+%!assert (ishermitian ([1, -2i; 2i, 1]))
+%!assert (! ishermitian ("t"))
+%!assert (! ishermitian (["te"; "et"]))
 
 %!test
 %! s.a = 1;
-%! assert(!(ishermitian (s)));
+%! assert (! ishermitian (s));
+
+%!error ishermitian ([1, 2; 2, 1], 0, 0)
+%!error ishermitian ()
+
--- a/scripts/linear-algebra/issymmetric.m
+++ b/scripts/linear-algebra/issymmetric.m
@@ -49,18 +49,21 @@
 
 endfunction
 
-%!assert(issymmetric (1));
-%!assert(!(issymmetric ([1, 2])));
-%!assert(issymmetric ([]));
-%!assert(issymmetric ([1, 2; 2, 1]));
-%!assert(!(issymmetric ("test")));
-%!assert(issymmetric ([1, 2.1; 2, 1.1], 0.2));
-%!assert(issymmetric ([1, 2i; 2i, 1]));
-%!assert(!(issymmetric ("t")));
-%!assert(!(issymmetric (["te"; "et"])));
-%!error issymmetric ([1, 2; 2, 1], 0, 0);
-%!error issymmetric ();
+
+%!assert (issymmetric (1))
+%!assert (! issymmetric ([1, 2]))
+%!assert (issymmetric ([]))
+%!assert (issymmetric ([1, 2; 2, 1]))
+%!assert (! (issymmetric ("test")))
+%!assert (issymmetric ([1, 2.1; 2, 1.1], 0.2))
+%!assert (issymmetric ([1, 2i; 2i, 1]))
+%!assert (! (issymmetric ("t")))
+%!assert (! (issymmetric (["te"; "et"])))
 
 %!test
 %! s.a = 1;
-%! assert(!(issymmetric (s)));
+%! assert (! issymmetric (s));
+
+%!error issymmetric ([1, 2; 2, 1], 0, 0)
+%!error issymmetric ()
+
--- a/scripts/linear-algebra/krylov.m
+++ b/scripts/linear-algebra/krylov.m
@@ -34,7 +34,7 @@
 ## meaningless.
 ##
 ## If @var{V} is a vector and @var{k} is greater than
-## @code{length(A)-1}, then @var{h} contains the Hessenberg matrix such
+## @code{length (A) - 1}, then @var{h} contains the Hessenberg matrix such
 ## that @code{a*u == u*h}.
 ##
 ## The value of @var{nu} is the dimension of the span of the Krylov
@@ -71,7 +71,7 @@
     pflg = 0;
   endif
 
-  if(nargin < 4)
+  if (nargin < 4)
     ## Default tolerance parameter.
     eps1 = defeps;
   endif
@@ -115,14 +115,14 @@
   iter = 0;
   alpha = [];
   nh = 0;
-  while (length(alpha) < na) && (columns(V) > 0) && (iter < k)
+  while (length (alpha) < na) && (columns (V) > 0) && (iter < k)
     iter++;
 
     ## Get orthogonal basis of V.
     jj = 1;
     while (jj <= columns (V) && length (alpha) < na)
       ## Index of next Householder reflection.
-      nu = length(alpha)+1;
+      nu = length (alpha)+1;
 
       short_pv = pivot_vec(nu:na);
       q = V(:,jj);
--- a/scripts/linear-algebra/logm.m
+++ b/scripts/linear-algebra/logm.m
@@ -104,7 +104,7 @@
   s = 2^k * u * s * u';
 
   ## Remove small complex values (O(eps)) which may have entered calculation
-  if (real_eig && isreal(A))
+  if (real_eig && isreal (A))
     s = real (s);
   endif
 
@@ -156,16 +156,16 @@
 endfunction
 
 
-%!assert(norm(logm([1 -1;0 1]) - [0 -1; 0 0]) < 1e-5);
-%!assert(norm(expm(logm([-1 2 ; 4 -1])) - [-1 2 ; 4 -1]) < 1e-5);
-%!assert(logm([1 -1 -1;0 1 -1; 0 0 1]), [0 -1 -1.5; 0 0 -1; 0 0 0], 1e-5);
+%!assert (norm (logm ([1 -1;0 1]) - [0 -1; 0 0]) < 1e-5)
+%!assert (norm (expm (logm ([-1 2 ; 4 -1])) - [-1 2 ; 4 -1]) < 1e-5)
+%!assert (logm ([1 -1 -1;0 1 -1; 0 0 1]), [0 -1 -1.5; 0 0 -1; 0 0 0], 1e-5)
+%!assert (logm (10), log (10))
+%!assert (full (logm (eye (3))), logm (full (eye (3))))
+%!assert (full (logm (10*eye (3))), logm (full (10*eye (3))), 8*eps)
 %!assert (logm (expm ([0 1i; -1i 0])), [0 1i; -1i 0], 10 * eps)
 
 %% Test input validation
-%!error logm ();
-%!error logm (1, 2, 3);
-%!error <logm: A must be a square matrix> logm([1 0;0 1; 2 2]);
+%!error logm ()
+%!error logm (1, 2, 3)
+%!error <logm: A must be a square matrix> logm ([1 0;0 1; 2 2])
 
-%!assert (logm (10), log (10))
-%!assert (full (logm (eye (3))), logm (full (eye (3))))
-%!assert (full (logm (10*eye (3))), logm (full (10*eye (3))), 8*eps)
--- a/scripts/linear-algebra/normest.m
+++ b/scripts/linear-algebra/normest.m
@@ -75,13 +75,14 @@
   rand ("state", v);    # restore state of random number generator
 endfunction
 
+
 %!test
 %! A = toeplitz ([-2,1,0,0]);
-%! assert (normest(A), norm(A), 1e-6);
+%! assert (normest (A), norm (A), 1e-6);
 
 %!test
 %! A = rand (10);
-%! assert (normest(A), norm(A), 1e-6);
+%! assert (normest (A), norm (A), 1e-6);
 
 %% Test input validation
 %!error normest ()
--- a/scripts/linear-algebra/null.m
+++ b/scripts/linear-algebra/null.m
@@ -67,9 +67,9 @@
     if (rank < cols)
       retval = V (:, rank+1:cols);
       if (isa (A, "single"))
-        retval(abs (retval) < eps ("single")) = 0;
+        retval (abs (retval) < eps ("single")) = 0;
       else
-        retval(abs (retval) < eps) = 0;
+        retval (abs (retval) < eps) = 0;
       endif
     else
       retval = zeros (cols, 0);
@@ -78,34 +78,38 @@
 
 endfunction
 
+
+%% FIXME: Need some tests for 'single' variables as well
+
 %!test
 %! A = 0;
-%! assert(null(A), 1);
+%! assert (null (A), 1);
 
 %!test
 %! A = 1;
-%! assert(null(A), zeros(1,0))
+%! assert (null (A), zeros (1,0));
 
 %!test
 %! A = [1 0; 0 1];
-%! assert(null(A), zeros(2,0));
+%! assert (null (A), zeros (2,0));
 
 %!test
 %! A = [1 0; 1 0];
-%! assert(null(A), [0 1]')
+%! assert (null (A), [0 1]');
 
 %!test
 %! A = [1 1; 0 0];
-%! assert(null(A), [-1/sqrt(2) 1/sqrt(2)]', eps)
+%! assert (null (A), [-1/sqrt(2) 1/sqrt(2)]', eps);
 
 %!test
 %! tol = 1e-4;
 %! A = [1 0; 0 tol-eps];
-%! assert(null(A,tol), [0 1]')
+%! assert (null (A,tol), [0; 1]);
 
 %!test
 %! tol = 1e-4;
 %! A = [1 0; 0 tol+eps];
-%! assert(null(A,tol), zeros(2,0));
+%! assert (null (A,tol), zeros (2,0));
 
-%!error null()
+%!error null ()
+
--- a/scripts/linear-algebra/onenormest.m
+++ b/scripts/linear-algebra/onenormest.m
@@ -95,7 +95,7 @@
 
 function [est, v, w, iter] = onenormest (varargin)
 
-  if (size (varargin, 2) < 1 || size (varargin, 2) > 4)
+  if (nargin < 1 || nargin > 4)
     print_usage ();
   endif
 
@@ -103,31 +103,31 @@
   itmax = 10;
 
   if (ismatrix (varargin{1}))
-    n = size (varargin{1}, 1);
-    if n != size (varargin{1}, 2),
+    [n, nc] = size (varargin{1});
+    if (n != nc)
       error ("onenormest: matrix must be square");
     endif
     apply = @(x) varargin{1} * x;
     apply_t = @(x) varargin{1}' * x;
-    if (size (varargin) > 1)
+    if (nargin > 1)
       t = varargin{2};
     else
       t = min (n, default_t);
     endif
-    issing = isa (varargin {1}, "single");
+    issing = isa (varargin{1}, "single");
   else
-    if (size (varargin, 2) < 3)
-      print_usage();
+    if (nargin < 3)
+      print_usage ();
     endif
-    n = varargin{3};
     apply = varargin{1};
     apply_t = varargin{2};
-    if (size (varargin) > 3)
+    n = varargin{3};
+    if (nargin > 3)
       t = varargin{4};
     else
       t = default_t;
     endif
-    issing = isa (varargin {3}, "single");
+    issing = isa (n, "single");
   endif
 
   ## Initial test vectors X.
@@ -175,7 +175,7 @@
 
     ## Test if any of S are approximately parallel to previous S
     ## vectors or current S vectors.  If everything is parallel,
-    ## stop. Otherwise, replace any parallel vectors with
+    ## stop.  Otherwise, replace any parallel vectors with
     ## rand{-1,+1}.
     partest = any (abs (S_old' * S - n) < 4*eps*n);
     if (all (partest))
@@ -201,8 +201,7 @@
 
     Z = feval (apply_t, S);
 
-    ## Now find the largest non-previously-visted index per
-    ## vector.
+    ## Now find the largest non-previously-visted index per vector.
     h = max (abs (Z),2);
     [mh, mhi] = max (h);
     if (iter >= 2 && mhi == ind_best)
@@ -216,10 +215,10 @@
         ## Visited all these before, so stop.
         break;
       endif
-      ind = ind (!been_there (ind));
+      ind = ind(! been_there(ind));
       if (length (ind) < t)
         ## There aren't enough new vectors, so we're practically
-        ## in a cycle. Stop.
+        ## in a cycle.  Stop.
         break;
       endif
     endif
@@ -229,62 +228,65 @@
     for zz = 1 : t
       X(ind(zz),zz) = 1;
     endfor
-    been_there (ind (1 : t)) = 1;
+    been_there(ind(1 : t)) = 1;
   endfor
 
-  ## The estimate est and vector w are set in the loop above. The
-  ## vector v selects the ind_best column of A.
+  ## The estimate est and vector w are set in the loop above.
+  ## The vector v selects the ind_best column of A.
   v = zeros (n, 1);
   v(ind_best) = 1;
+
 endfunction
 
+
 %!demo
-%!  N = 100;
-%!  A = randn(N) + eye(N);
-%!  [L,U,P] = lu(A);
-%!  nm1inv = onenormest(@(x) U\(L\(P*x)), @(x) P'*(L'\(U'\x)), N, 30)
-%!  norm(inv(A), 1)
+%! N = 100;
+%! A = randn (N) + eye (N);
+%! [L,U,P] = lu (A);
+%! nm1inv = onenormest (@(x) U\(L\(P*x)), @(x) P'*(L'\(U'\x)), N, 30)
+%! norm (inv (A), 1)
 
 %!test
-%!  N = 10;
-%!  A = ones (N);
-%!  [nm1, v1, w1] = onenormest (A);
-%!  [nminf, vinf, winf] = onenormest (A', 6);
-%!  assert (nm1, N, -2*eps);
-%!  assert (nminf, N, -2*eps);
-%!  assert (norm (w1, 1), nm1 * norm (v1, 1), -2*eps)
-%!  assert (norm (winf, 1), nminf * norm (vinf, 1), -2*eps)
+%! N = 10;
+%! A = ones (N);
+%! [nm1, v1, w1] = onenormest (A);
+%! [nminf, vinf, winf] = onenormest (A', 6);
+%! assert (nm1, N, -2*eps);
+%! assert (nminf, N, -2*eps);
+%! assert (norm (w1, 1), nm1 * norm (v1, 1), -2*eps);
+%! assert (norm (winf, 1), nminf * norm (vinf, 1), -2*eps);
 
 %!test
-%!  N = 10;
-%!  A = ones (N);
-%!  [nm1, v1, w1] = onenormest (@(x) A*x, @(x) A'*x, N, 3);
-%!  [nminf, vinf, winf] = onenormest (@(x) A'*x, @(x) A*x, N, 3);
-%!  assert (nm1, N, -2*eps);
-%!  assert (nminf, N, -2*eps);
-%!  assert (norm (w1, 1), nm1 * norm (v1, 1), -2*eps)
-%!  assert (norm (winf, 1), nminf * norm (vinf, 1), -2*eps)
+%! N = 10;
+%! A = ones (N);
+%! [nm1, v1, w1] = onenormest (@(x) A*x, @(x) A'*x, N, 3);
+%! [nminf, vinf, winf] = onenormest (@(x) A'*x, @(x) A*x, N, 3);
+%! assert (nm1, N, -2*eps);
+%! assert (nminf, N, -2*eps);
+%! assert (norm (w1, 1), nm1 * norm (v1, 1), -2*eps);
+%! assert (norm (winf, 1), nminf * norm (vinf, 1), -2*eps);
 
 %!test
-%!  N = 5;
-%!  A = hilb (N);
-%!  [nm1, v1, w1] = onenormest (A);
-%!  [nminf, vinf, winf] = onenormest (A', 6);
-%!  assert (nm1, norm (A, 1), -2*eps);
-%!  assert (nminf, norm (A, inf), -2*eps);
-%!  assert (norm (w1, 1), nm1 * norm (v1, 1), -2*eps)
-%!  assert (norm (winf, 1), nminf * norm (vinf, 1), -2*eps)
+%! N = 5;
+%! A = hilb (N);
+%! [nm1, v1, w1] = onenormest (A);
+%! [nminf, vinf, winf] = onenormest (A', 6);
+%! assert (nm1, norm (A, 1), -2*eps);
+%! assert (nminf, norm (A, inf), -2*eps);
+%! assert (norm (w1, 1), nm1 * norm (v1, 1), -2*eps);
+%! assert (norm (winf, 1), nminf * norm (vinf, 1), -2*eps);
 
 ## Only likely to be within a factor of 10.
 %!test
-%!  old_state = rand ("state");
-%!  restore_state = onCleanup (@() rand ("state", old_state));
-%!  rand ('state', 42);  % Initialize to guarantee reproducible results
-%!  N = 100;
-%!  A = rand (N);
-%!  [nm1, v1, w1] = onenormest (A);
-%!  [nminf, vinf, winf] = onenormest (A', 6);
-%!  assert (nm1, norm (A, 1), -.1);
-%!  assert (nminf, norm (A, inf), -.1);
-%!  assert (norm (w1, 1), nm1 * norm (v1, 1), -2*eps)
-%!  assert (norm (winf, 1), nminf * norm (vinf, 1), -2*eps)
+%! old_state = rand ("state");
+%! restore_state = onCleanup (@() rand ("state", old_state));
+%! rand ('state', 42);  % Initialize to guarantee reproducible results
+%! N = 100;
+%! A = rand (N);
+%! [nm1, v1, w1] = onenormest (A);
+%! [nminf, vinf, winf] = onenormest (A', 6);
+%! assert (nm1, norm (A, 1), -.1);
+%! assert (nminf, norm (A, inf), -.1);
+%! assert (norm (w1, 1), nm1 * norm (v1, 1), -2*eps);
+%! assert (norm (winf, 1), nminf * norm (vinf, 1), -2*eps);
+
--- a/scripts/linear-algebra/orth.m
+++ b/scripts/linear-algebra/orth.m
@@ -80,11 +80,13 @@
 
 endfunction
 
+
 %!test
-%! for ii=1:20
+%! for i = 1:20
 %!   A = rand (10, 10);
 %!   V = orth (A);
 %!   if (det (A) != 0)
-%!     assert (V'*V, eye (10), 100*eps)
+%!     assert (V'*V, eye (10), 100*eps);
 %!   endif
 %! endfor
+
--- a/scripts/linear-algebra/planerot.m
+++ b/scripts/linear-algebra/planerot.m
@@ -35,13 +35,14 @@
   y = G * x(:);
 endfunction
 
+
 %!test
 %! x = [3 4];
-%! [g y] = planerot(x);
-%! assert(g - [x(1) x(2); -x(2) x(1)] / sqrt(x(1)^2 + x(2)^2), zeros(2), 2e-8);
-%! assert(y(2), 0, 2e-8);
+%! [g y] = planerot (x);
+%! assert (g, [x(1) x(2); -x(2) x(1)] / sqrt (x(1)^2 + x(2)^2), 2e-8);
+%! assert (y(2), 0, 2e-8);
 
-%!error planerot([0]);
-%!error planerot([0 0 0]);
-%!error planerot();
+%!error planerot ([0])
+%!error planerot ([0 0 0])
+%!error planerot ()
 
--- a/scripts/linear-algebra/qzhess.m
+++ b/scripts/linear-algebra/qzhess.m
@@ -91,6 +91,7 @@
 
 endfunction
 
+
 %!test
 %! a = [1 2 1 3;
 %!      2 5 3 2;
@@ -104,13 +105,13 @@
 %!         0 0 0 0;
 %!         1 0 0 0;
 %!         1 1 0 0];
-%! [aa, bb, q, z] = qzhess(a, b);
-%! assert(inv(q) - q', zeros(4), 2e-8);
-%! assert(inv(z) - z', zeros(4), 2e-8);
-%! assert(q * a * z, aa, 2e-8);
-%! assert(aa .* mask, zeros(4), 2e-8);
-%! assert(q * b * z, bb, 2e-8);
-%! assert(bb .* mask, zeros(4), 2e-8);
+%! [aa, bb, q, z] = qzhess (a, b);
+%! assert (inv (q) - q', zeros (4), 2e-8);
+%! assert (inv (z) - z', zeros (4), 2e-8);
+%! assert (q * a * z, aa, 2e-8);
+%! assert (aa .* mask, zeros (4), 2e-8);
+%! assert (q * b * z, bb, 2e-8);
+%! assert (bb .* mask, zeros (4), 2e-8);
 
 %!test
 %! a = [1 2 3 4 5;
@@ -128,14 +129,14 @@
 %!         1 0 0 0 0;
 %!         1 1 0 0 0;
 %!         1 1 1 0 0];
-%! [aa, bb, q, z] = qzhess(a, b);
-%! assert(inv(q) - q', zeros(5), 2e-8);
-%! assert(inv(z) - z', zeros(5), 2e-8);
-%! assert(q * a * z, aa, 2e-8);
-%! assert(aa .* mask, zeros(5), 2e-8);
-%! assert(q * b * z, bb, 2e-8);
-%! assert(bb .* mask, zeros(5), 2e-8);
+%! [aa, bb, q, z] = qzhess (a, b);
+%! assert (inv (q) - q', zeros (5), 2e-8);
+%! assert (inv (z) - z', zeros (5), 2e-8);
+%! assert (q * a * z, aa, 2e-8);
+%! assert (aa .* mask, zeros (5), 2e-8);
+%! assert (q * b * z, bb, 2e-8);
+%! assert (bb .* mask, zeros (5), 2e-8);
 
-%!error qzhess([0]);
-%!error qzhess();
+%!error qzhess ([0])
+%!error qzhess ()
 
--- a/scripts/linear-algebra/rank.m
+++ b/scripts/linear-algebra/rank.m
@@ -59,6 +59,7 @@
 
 endfunction
 
+
 %!test
 %! A = [1 2 3 4 5 6 7;
 %!      4 5 6 7 8 9 12;
@@ -67,7 +68,7 @@
 %!      3 4 5 6 7 8 9;
 %!      4 5 6 7 8 9 10;
 %!      5 6 7 8 9 10 11];
-%! assert(rank(A),4);
+%! assert (rank (A), 4);
 
 %!test
 %! A = [1 2 3 4 5 6 7;
@@ -77,7 +78,7 @@
 %!      3 4 5 6 7 8 9;
 %!      4 5 6 7 8 9 10;
 %!      5 6 7 8 9 10 11];
-%! assert(rank(A),4);
+%! assert (rank (A), 4);
 
 %!test
 %! A = [1 2 3 4 5 6 7;
@@ -87,7 +88,7 @@
 %!      3 4 5 6 7 8 9;
 %!      4 5 6 7 8 9 10;
 %!      5 6 7 8 9 10 11];
-%! assert(rank(A),3);
+%! assert (rank (A), 3);
 
 %!test
 %! A = [1 2 3 4 5 6 7;
@@ -97,15 +98,16 @@
 %!      3 4 5 6 7 8 9;
 %!      4 5 6 7 8 9 10;
 %!      5 6 7 8 9 10 11];
-%! assert(rank(A),3);
+%! assert (rank (A), 3);
 
 %!test
-%! A = eye(100);
-%! assert(rank(A),100);
+%! A = eye (100);
+%! assert (rank (A), 100);
 
 %!test
 %! A = [1, 2, 3; 1, 2.001, 3; 1, 2, 3.0000001];
-%! assert(rank(A),3)
-%! assert(rank(A,0.0009),1)
-%! assert(rank(A,0.0006),2)
-%! assert(rank(A,0.00000002),3)
\ No newline at end of file
+%! assert (rank (A), 3);
+%! assert (rank (A,0.0009), 1);
+%! assert (rank (A,0.0006), 2);
+%! assert (rank (A,0.00000002), 3);
+
--- a/scripts/linear-algebra/rref.m
+++ b/scripts/linear-algebra/rref.m
@@ -62,20 +62,20 @@
     if (m <= tol)
       ## Skip column c, making sure the approximately zero terms are
       ## actually zero.
-      A (r:rows, c) = zeros (rows-r+1, 1);
+      A(r:rows, c) = zeros (rows-r+1, 1);
     else
       ## keep track of bound variables
       used (1, c) = 1;
 
       ## Swap current row and pivot row
-      A ([pivot, r], c:cols) = A ([r, pivot], c:cols);
+      A([pivot, r], c:cols) = A([r, pivot], c:cols);
 
       ## Normalize pivot row
-      A (r, c:cols) = A (r, c:cols) / A (r, c);
+      A(r, c:cols) = A(r, c:cols) / A(r, c);
 
       ## Eliminate the current column
       ridx = [1:r-1, r+1:rows];
-      A (ridx, c:cols) = A (ridx, c:cols) - A (ridx, c) * A(r, c:cols);
+      A(ridx, c:cols) = A(ridx, c:cols) - A(ridx, c) * A(r, c:cols);
 
       ## Check if done
       if (r++ == rows)
@@ -87,42 +87,42 @@
 
 endfunction
 
+
 %!test
 %! a = [1];
-%! [r k] = rref(a);
-%! assert(r, [1], 2e-8);
-%! assert(k, [1], 2e-8);
+%! [r k] = rref (a);
+%! assert (r, [1], 2e-8);
+%! assert (k, [1], 2e-8);
 
 %!test
 %! a = [1 3; 4 5];
-%! [r k] = rref(a);
-%! assert(rank(a), rank(r), 2e-8);
-%! assert(r, eye(2), 2e-8);
-%! assert(k == [1, 2] || k == [2, 1]);
-
+%! [r k] = rref (a);
+%! assert (rank (a), rank (r), 2e-8);
+%! assert (r, eye (2), 2e-8);
+%! assert (k == [1, 2] || k == [2, 1]);
 
 %!test
 %! a = [1 3; 4 5; 7 9];
-%! [r k] = rref(a);
-%! assert(rank(a), rank(r), 2e-8);
-%! assert(r, eye(3)(:,1:2), 2e-8);
-%! assert(k, [1 2], 2e-8);
+%! [r k] = rref (a);
+%! assert (rank (a), rank (r), 2e-8);
+%! assert (r, eye(3)(:,1:2), 2e-8);
+%! assert (k, [1 2], 2e-8);
 
 %!test
 %! a = [1 2 3; 2 4 6; 7 2 0];
-%! [r k] = rref(a);
-%! assert(rank(a), rank(r), 2e-8);
-%! assert(r, [1 0 (3-7/2); 0 1 (7/4); 0 0 0], 2e-8);
-%! assert(k, [1 2], 2e-8);
+%! [r k] = rref (a);
+%! assert (rank (a), rank (r), 2e-8);
+%! assert (r, [1 0 (3-7/2); 0 1 (7/4); 0 0 0], 2e-8);
+%! assert (k, [1 2], 2e-8);
 
 %!test
 %! a = [1 2 1; 2 4 2.01; 2 4 2.1];
 %! tol = 0.02;
-%! [r k] = rref(a, tol);
-%! assert(rank(a, tol), rank(r, tol), 2e-8);
+%! [r k] = rref (a, tol);
+%! assert (rank (a, tol), rank (r, tol), 2e-8);
 %! tol = 0.2;
-%! [r k] = rref(a, tol);
-%! assert(rank(a, tol), rank(r, tol), 2e-8);
+%! [r k] = rref (a, tol);
+%! assert (rank (a, tol), rank (r, tol), 2e-8);
 
-%!error rref();
+%!error rref ();
 
--- a/scripts/linear-algebra/trace.m
+++ b/scripts/linear-algebra/trace.m
@@ -41,12 +41,14 @@
 
 endfunction
 
-%!assert(trace ([1, 2; 3, 4]) == 5);
-%!assert(trace ([1, 2; 3, 4; 5, 6]) == 5);
-%!assert(trace ([1, 3, 5; 2, 4, 6]) == 5);
-%!assert(trace ([]), 0);
-%!assert(trace (randn(1,0)), 0);
-%!
-%!error trace ();
-%!error trace (1, 2);
-%!error <only valid on 2-D objects> trace(reshape(1:9,[1,3,3]));
+
+%!assert (trace ([1, 2; 3, 4]), 5)
+%!assert (trace ([1, 2; 3, 4; 5, 6]), 5)
+%!assert (trace ([1, 3, 5; 2, 4, 6]), 5)
+%!assert (trace ([]), 0)
+%!assert (trace (randn (1,0)), 0)
+
+%!error trace ()
+%!error trace (1, 2)
+%!error <only valid on 2-D objects> trace (reshape (1:9,[1,3,3]))
+
--- a/scripts/linear-algebra/vech.m
+++ b/scripts/linear-algebra/vech.m
@@ -50,9 +50,9 @@
 
 endfunction
 
-%!assert(all (vech ([1, 2, 3; 4, 5, 6; 7, 8, 9]) == [1; 4; 7; 5; 8; 9]));
+
+%!assert (vech ([1, 2, 3; 4, 5, 6; 7, 8, 9]), [1; 4; 7; 5; 8; 9])
 
-%!error vech ();
+%!error vech ()
+%!error vech (1, 2)
 
-%!error vech (1, 2);
-
--- a/scripts/miscellaneous/ans.m
+++ b/scripts/miscellaneous/ans.m
@@ -29,6 +29,7 @@
 ## is evaluated, the value returned by @code{ans} is 25.
 ## @end defvr
 
+
 ## Mark file as being tested.  No real test needed for a documentation .m file
 %!assert (1)
 
--- a/scripts/miscellaneous/bincoeff.m
+++ b/scripts/miscellaneous/bincoeff.m
@@ -103,18 +103,18 @@
 endfunction
 
 
-%!assert(bincoeff (4, 2), 6)
-%!assert(bincoeff (2, 4), 0)
-%!assert(bincoeff (-4, 2), 10)
-%!assert(bincoeff (5, 2), 10)
-%!assert(bincoeff (50, 6), 15890700)
-%!assert(bincoeff (0.4, 2), -.12, 8*eps)
+%!assert (bincoeff (4, 2), 6)
+%!assert (bincoeff (2, 4), 0)
+%!assert (bincoeff (-4, 2), 10)
+%!assert (bincoeff (5, 2), 10)
+%!assert (bincoeff (50, 6), 15890700)
+%!assert (bincoeff (0.4, 2), -.12, 8*eps)
 
-%!assert(bincoeff ([4 NaN 4], [-1, 2, 2.5]), NaN (1, 3))
+%!assert (bincoeff ([4 NaN 4], [-1, 2, 2.5]), NaN (1, 3))
 
 %% Test input validation
-%!error bincoeff ();
-%!error bincoeff (1, 2, 3);
-%!error bincoeff (ones(3),ones(2))
-%!error bincoeff (ones(2),ones(3))
+%!error bincoeff ()
+%!error bincoeff (1, 2, 3)
+%!error bincoeff (ones (3),ones (2))
+%!error bincoeff (ones (2),ones (3))
 
--- a/scripts/miscellaneous/bug_report.m
+++ b/scripts/miscellaneous/bug_report.m
@@ -44,5 +44,6 @@
 
 endfunction
 
+
 ## Mark file as being tested.  No real test needed for this function.
 %!assert (1)
--- a/scripts/miscellaneous/bzip2.m
+++ b/scripts/miscellaneous/bzip2.m
@@ -21,7 +21,7 @@
 ## @deftypefn  {Function File} {@var{entries} =} bzip2 (@var{files})
 ## @deftypefnx {Function File} {@var{entries} =} bzip2 (@var{files}, @var{outdir})
 ## Compress the list of files specified in @var{files}.
-## Each file is compressed separately and a new file with a '.bz2' extension
+## Each file is compressed separately and a new file with a ".bz2" extension
 ## is created.  The original files are not modified.  Existing compressed files
 ## are silently overwritten.  If @var{outdir} is defined the compressed
 ## files are placed in this directory.
@@ -31,7 +31,7 @@
 function entries = bzip2 (varargin)
 
   if (nargin == 1 || nargin == 2)
-    if nargout == 0
+    if (nargout == 0)
       __xzip__ ("bzip2", "bz2", "bzip2 %s", varargin{:});
     else
       entries = __xzip__ ("bzip2", "bz2", "bzip2 %s", varargin{:});
@@ -42,20 +42,22 @@
 
 endfunction
 
+
 %!xtest
-%!  # test for correct cleanup of temporary files
-%!  unwind_protect
-%!    filename = tmpnam;
-%!    dummy    = 1;
-%!    save(filename, "dummy");
-%!    n_tmpfiles_before = length(find(strncmp("oct-", cellstr(ls(P_tmpdir)), 4)));
-%!    entry = bzip2(filename);
-%!    n_tmpfiles_after = length(find(strncmp("oct-", cellstr(ls(P_tmpdir)), 4)));
-%!    if (n_tmpfiles_before != n_tmpfiles_after)
-%!      error("bzip2 has not cleaned up temporary files correctly!");
-%!    endif
-%!  unwind_protect_cleanup
-%!    delete(filename);
-%!    [path, basename, extension] = fileparts(filename);
-%!    delete([basename, extension, ".bz2"]);
-%!  end_unwind_protect
+%! # test for correct cleanup of temporary files
+%! unwind_protect
+%!   filename = tmpnam;
+%!   dummy    = 1;
+%!   save (filename, "dummy");
+%!   n_tmpfiles_before = length (find (strncmp ("oct-", cellstr (ls (tempdir)), 4)));
+%!   entry = bzip2 (filename);
+%!   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
+%! unwind_protect_cleanup
+%!   delete (filename);
+%!   [path, basename, extension] = fileparts (filename);
+%!   delete ([basename, extension, ".bz2"]);
+%! end_unwind_protect
+
new file mode 100644
--- /dev/null
+++ b/scripts/miscellaneous/citation.m
@@ -0,0 +1,51 @@
+## Copyright (C) 2013 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/>.
+
+## -*- texinfo -*-
+## @deftypefn  {Command} {} citation
+## @deftypefnx {Command} {} citation @var{package}
+## Display instructions to cite GNU Octave and packages in publications.
+##
+## When called without an argument, displays information on how to cite the core
+## GNU Octave system in publications.  When given a package name @var{package},
+## display information on to cite it.  However, note that some packages may not
+## have instructions on how to cite them.
+##
+## The GNU Octave developers and its active community of package authors have
+## invested a lot of time and effort in creating GNU Octave as it is today.
+## Please give credit where credit is due and cite GNU Octave and its packages
+## when you use them.
+##
+## @end deftypefn
+
+## Author: Carnë Draug <carandraug+dev@gmail.com>
+## Idea and documentation from R's citation() (also under GPL)
+
+function citation (package = "octave")
+
+  if (nargin > 1)
+    print_usage ();
+  else
+    display_info_file ("citation", package, "CITATION");
+  endif
+
+endfunction
+
+%!error citation (1, 2)
+%!error <citation: PACKAGE must be a string> citation (1)
+%!error <citation: package .* is not installed> citation ("__NOT_A_VALID_PKG_NAME__")
--- a/scripts/miscellaneous/comma.m
+++ b/scripts/miscellaneous/comma.m
@@ -22,6 +22,7 @@
 ## @seealso{semicolon}
 ## @end deftypefn
 
+
 ## Mark file as being tested.  No real test needed for a documentation .m file
 %!assert (1)
 
--- a/scripts/miscellaneous/compare_versions.m
+++ b/scripts/miscellaneous/compare_versions.m
@@ -66,8 +66,8 @@
 ## Note that version "1.1-test2" will compare as greater than
 ## "1.1-test10".  Also, since the numeric part is compared first, "a"
 ## compares less than "1a" because the second string starts with a
-## numeric part even though @code{double("a")} is greater than
-## @code{double("1").}
+## numeric part even though @code{double ("a")} is greater than
+## @code{double ("1").}
 ## @end deftypefn
 
 ## Author: Bill Denney <denney@seas.upenn.edu>
@@ -89,7 +89,7 @@
   if (! ischar (operator))
     error ("compare_versions: OPERATOR must be a character string");
   elseif (numel (operator) > 2)
-    error("compare_versions: OPERATOR must be 1 or 2 characters long");
+    error ("compare_versions: OPERATOR must be 1 or 2 characters long");
   endif
 
   ## trim off any character data that is not part of a normal version
@@ -99,23 +99,23 @@
   v1firstchar = find (! ismember (v1, numbers), 1);
   v2firstchar = find (! ismember (v2, numbers), 1);
   if (! isempty (v1firstchar))
-    v1c = v1(v1firstchar:length(v1));
+    v1c = v1(v1firstchar:length (v1));
     v1nochar = v1(1:v1firstchar-1);
   else
     v1c = "";
     v1nochar = v1;
   endif
   if (! isempty (v2firstchar))
-    v2c = v2(v2firstchar:length(v2));
+    v2c = v2(v2firstchar:length (v2));
     v2nochar = v2(1:v2firstchar-1);
   else
     v2c = "";
     v2nochar = v2;
   endif
 
-  v1n = str2num (char (strsplit (v1nochar, ".")));
-  v2n = str2num (char (strsplit (v2nochar, ".")));
-  if ((isempty (v1n) && isempty (v1c)) || (isempty (v2n) && isempty(v2c)))
+  v1n = str2num (char (strsplit (v1nochar, ".", false)));
+  v2n = str2num (char (strsplit (v2nochar, ".", false)));
+  if ((isempty (v1n) && isempty (v1c)) || (isempty (v2n) && isempty (v2c)))
     error ("compare_versions: given version strings are not valid: %s %s",
            v1, v2);
   endif
@@ -141,22 +141,22 @@
   endif
 
   ## Determine the operator.
-  if any (ismember (operator, "="))
+  if (any (ismember (operator, "=")))
     equal_op = true;
   else
     equal_op = false;
   endif
-  if any (ismember (operator, "~!"))
+  if (any (ismember (operator, "~!")))
     not_op = true;
   else
     not_op = false;
   endif
-  if any (ismember (operator, "<"))
+  if (any (ismember (operator, "<")))
     lt_op = true;
   else
     lt_op = false;
   endif
-  if any (ismember (operator, ">"))
+  if (any (ismember (operator, ">")))
     gt_op = true;
   else
     gt_op = false;
@@ -200,54 +200,54 @@
 
 endfunction
 
+
 ## tests
 ## test both equality symbols
 ## test arbitrarily long equality
-%!assert(compare_versions("1.1.0.0.0", "1.1", "=="), true)
-%!assert(compare_versions("1", "1.1", "<"), true)
-%!assert(compare_versions("1.1", "1.1", "<="), true)
-%!assert(compare_versions("1.1", "1.1.1", "<="), true)
-%!assert(compare_versions("1.23", "1.24", "=<"), true)
+%!assert (compare_versions ("1.1.0.0.0", "1.1", "=="), true)
+%!assert (compare_versions ("1", "1.1", "<"), true)
+%!assert (compare_versions ("1.1", "1.1", "<="), true)
+%!assert (compare_versions ("1.1", "1.1.1", "<="), true)
+%!assert (compare_versions ("1.23", "1.24", "=<"), true)
 ## test different length numbers
-%!assert(compare_versions("23.2000", "23.1", ">"), true)
-%!assert(compare_versions("0.0.2", "0.0.1", ">="), true)
-%!assert(compare_versions("0.2", "0.0.100", "=>"), true)
-%!assert(compare_versions("0.1", "0.2", "!="), true)
-%!assert(compare_versions("0.1", "0.2", "~="), true)
+%!assert (compare_versions ("23.2000", "23.1", ">"), true)
+%!assert (compare_versions ("0.0.2", "0.0.1", ">="), true)
+%!assert (compare_versions ("0.2", "0.0.100", "=>"), true)
+%!assert (compare_versions ("0.1", "0.2", "!="), true)
+%!assert (compare_versions ("0.1", "0.2", "~="), true)
 
 ## test alphanumeric strings
-%!assert(compare_versions("1a", "1b", "<"), true)
-%!assert(compare_versions("a", "1", "<"), true)
-%!assert(compare_versions("1a", "1b", ">"), false)
-%!assert(compare_versions("a", "1", ">"), false)
-%!assert(compare_versions("1.1.0a", "1.1.0b", "=="), false)
-%!assert(compare_versions("1.1.0a", "1.1.0b", "!="), true)
-%!assert(compare_versions("1.1.0test", "1.1.0b", "=="), false)
-%!assert(compare_versions("1.1.0test", "1.1.0test", "=="), true)
+%!assert (compare_versions ("1a", "1b", "<"), true)
+%!assert (compare_versions ("a", "1", "<"), true)
+%!assert (compare_versions ("1a", "1b", ">"), false)
+%!assert (compare_versions ("a", "1", ">"), false)
+%!assert (compare_versions ("1.1.0a", "1.1.0b", "=="), false)
+%!assert (compare_versions ("1.1.0a", "1.1.0b", "!="), true)
+%!assert (compare_versions ("1.1.0test", "1.1.0b", "=="), false)
+%!assert (compare_versions ("1.1.0test", "1.1.0test", "=="), true)
 
 ## make sure that it won't just give true output
-%!assert(compare_versions("1", "0", "=="), false)
+%!assert (compare_versions ("1", "0", "=="), false)
 ## test arbitrarily long equality
-%!assert(compare_versions("1.1.1.0.0", "1.1", "=="), false)
-%!assert(compare_versions("1.1", "1", "<"), false)
-%!assert(compare_versions("2", "1.1", "<="), false)
-%!assert(compare_versions("1.1.1", "1.1", "<="), false)
-%!assert(compare_versions("1.25", "1.24", "=<"), false)
+%!assert (compare_versions ("1.1.1.0.0", "1.1", "=="), false)
+%!assert (compare_versions ("1.1", "1", "<"), false)
+%!assert (compare_versions ("2", "1.1", "<="), false)
+%!assert (compare_versions ("1.1.1", "1.1", "<="), false)
+%!assert (compare_versions ("1.25", "1.24", "=<"), false)
 ## test different length numbers
-%!assert(compare_versions("23.2", "23.100", ">"), false)
-%!assert(compare_versions("0.0.0.2", "0.0.1", ">="), false)
-%!assert(compare_versions("0.0.20", "0.10.2", "=>"), false)
-%!assert(compare_versions("0.1", "0.1", "!="), false)
-%!assert(compare_versions("0.1", "0.1", "~="), false)
+%!assert (compare_versions ("23.2", "23.100", ">"), false)
+%!assert (compare_versions ("0.0.0.2", "0.0.1", ">="), false)
+%!assert (compare_versions ("0.0.20", "0.10.2", "=>"), false)
+%!assert (compare_versions ("0.1", "0.1", "!="), false)
+%!assert (compare_versions ("0.1", "0.1", "~="), false)
 
 %% Test input validation
-%!error(compare_versions(0.1, "0.1", "=="))
-%!error(compare_versions("0.1", 0.1, "=="))
-%!error(compare_versions(["0";".";"1"], "0.1", "=="))
-%!error(compare_versions("0.1", ["0";".";"1"], "=="))
-%!error(compare_versions("0.1", "0.1", "<>"))
-%!error(compare_versions("0.1", "0.1", "!>"))
-%!error(compare_versions("0.1", "0.1", "="))
-%!error(compare_versions("0.1", "0.1", "aa"))
+%!error (compare_versions (0.1, "0.1", "=="))
+%!error (compare_versions ("0.1", 0.1, "=="))
+%!error (compare_versions (["0";".";"1"], "0.1", "=="))
+%!error (compare_versions ("0.1", ["0";".";"1"], "=="))
+%!error (compare_versions ("0.1", "0.1", "<>"))
+%!error (compare_versions ("0.1", "0.1", "!>"))
+%!error (compare_versions ("0.1", "0.1", "="))
+%!error (compare_versions ("0.1", "0.1", "aa"))
 
-
--- a/scripts/miscellaneous/computer.m
+++ b/scripts/miscellaneous/computer.m
@@ -49,7 +49,7 @@
 function [c, maxsize, endian] = computer (a)
 
   if (nargin == 1 && ischar (a) && strcmpi (a, "arch"))
-    tmp = strsplit (octave_config_info ("canonical_host_type"), "-");
+    tmp = strsplit (octave_config_info ("canonical_host_type"), "-", false);
     if (numel (tmp) == 4)
       c = sprintf ("%s-%s-%s", tmp{4}, tmp{3}, tmp{1});
     else
@@ -85,7 +85,10 @@
 
 endfunction
 
-%!assert((ischar (computer ())
-%! && computer () == octave_config_info ("canonical_host_type")));
-%!assert(ischar (computer ("arch")));
-%!error computer (2);
+
+%!assert (ischar (computer ()))
+%!assert (computer (), octave_config_info ("canonical_host_type"))
+%!assert (ischar (computer ("arch")))
+
+%!error computer (2)
+
--- a/scripts/miscellaneous/copyfile.m
+++ b/scripts/miscellaneous/copyfile.m
@@ -72,7 +72,7 @@
 
     ## If f1 has more than 1 element f2 must be a directory
     isdir = (exist (f2, "dir") != 0);
-    if (length(f1) > 1 && ! isdir)
+    if (length (f1) > 1 && ! isdir)
       error ("copyfile: when copying multiple files, second argument must be a directory");
     endif
 
@@ -84,12 +84,12 @@
     p1 = sprintf ("\"%s\" ", f1{:});
     p2 = tilde_expand (f2);
 
-    if (isdir && length(p1) > max_cmd_line)
-      l2 = length(p2) + length (cmd) + 6;
-      while (! isempty(f1))
+    if (isdir && length (p1) > max_cmd_line)
+      l2 = length (p2) + length (cmd) + 6;
+      while (! isempty (f1))
         p1 = sprintf ("\"%s\" ", f1{1});
         f1(1) = [];
-        while (!isempty (f1) && (length(p1) + length(f1{1}) + l2 <
+        while (!isempty (f1) && (length (p1) + length (f1{1}) + l2 <
                                  max_cmd_line))
           p1 = sprintf ("%s\"%s\" ", p1, f1{1});
           f1(1) = [];
--- a/scripts/miscellaneous/dump_prefs.m
+++ b/scripts/miscellaneous/dump_prefs.m
@@ -82,7 +82,7 @@
               "struct_levels_to_print";
               "suppress_verbose_help_message"];
 
-  for i = 1:rows(sym_list)
+  for i = 1:rows (sym_list)
     sym = deblank (sym_list(i,:));
     try
       val = feval (sym);
--- a/scripts/miscellaneous/edit.m
+++ b/scripts/miscellaneous/edit.m
@@ -72,8 +72,9 @@
 ## @item editor
 ## This is the editor to use to modify the functions.  By default it uses
 ## Octave's @env{EDITOR} built-in function, which comes from
-## @code{getenv("EDITOR")} and defaults to @code{emacs}.  Use @code{%s}
+## @code{getenv ("EDITOR")} and defaults to @code{emacs}.  Use @code{%s}
 ## In place of the function name.  For example,
+##
 ## @table @samp
 ## @item [EDITOR, " %s"]
 ## Use the editor which Octave uses for @code{edit_history}.
@@ -110,6 +111,7 @@
 ## Be sure to use @code{<user@@host>} as your format.
 ##
 ## @item license
+##
 ## @table @samp
 ## @item gpl
 ## GNU General Public License (default).
@@ -144,7 +146,7 @@
 ## Original version by Paul Kienzle distributed as free software in the
 ## public domain.
 
-function ret = edit (file, state)
+function ret = edit (varargin)
 
   ## Pick up globals or default them.
 
@@ -155,317 +157,364 @@
                                 "LICENSE",  "GPL",
                                 "MODE", "async",
                                 "EDITINPLACE", false);
-  ## Make sure the state variables survive "clear functions".
+  ## Make sure the stateval variables survive "clear functions".
   mlock;
 
-  if (nargin == 2)
-    switch (toupper (file))
+  if (nargin == 1)
+    ## User has supplied one arg, this can be a single file name
+    ## or a cell array of strings containing multiple files to be
+    ## opened
+    if (iscellstr(varargin{1}))
+      ## If first arg is a cell array of strings, it becomes the
+      ## list of files to be edited
+      editfilelist = varargin{1};
+    elseif (ischar(varargin{1}))
+      ## If first arg is a string, create a cell array of strings
+      ## of length one (by copying the input cell array)
+      editfilelist = varargin(1);
+    else
+      error('edit: expected file to be a string or cell array of strings');
+    endif
+  elseif (nargin == 2)
+    ## User has supplied two arguments, these could be two file
+    ## names, or a combination of editor state name and new value
+    ## for that state, so first check for the various states
+    statevar = varargin{1};
+    stateval = varargin{2};
+    switch (toupper (statevar))
     case "EDITOR"
-      FUNCTION.EDITOR = state;
+      FUNCTION.EDITOR = stateval;
+      return
     case "HOME"
-      if (! isempty (state) && state(1) == "~")
-        state = [ default_home, state(2:end) ];
+      if (! isempty (stateval) && stateval(1) == "~")
+        stateval = [ default_home, stateval(2:end) ];
       endif
-      FUNCTION.HOME = state;
+      FUNCTION.HOME = stateval;
+      return
     case "AUTHOR"
-      FUNCTION.AUTHOR = state;
+      FUNCTION.AUTHOR = stateval;
+      return
     case "EMAIL"
-      FUNCTION.EMAIL = state;
+      FUNCTION.EMAIL = stateval;
+      return
     case "LICENSE"
-      FUNCTION.LICENSE = state;
+      FUNCTION.LICENSE = stateval;
+      return
     case "MODE"
-      if (strcmp (state, "sync") || strcmp (state, "async"))
-        FUNCTION.MODE = state;
+      if (strcmp (stateval, "sync") || strcmp (stateval, "async"))
+        FUNCTION.MODE = stateval;
       else
-        error('edit: expected "edit MODE sync|async"');
+        error ('edit: expected "edit MODE sync|async"');
       endif
+      return
     case "EDITINPLACE"
-      if (ischar (state))
-        if (strcmpi (state, "true"))
-          state = true;
-        elseif (strcmpi (state, "false"))
-          state = false;
+      if (ischar (stateval))
+        if (strcmpi (stateval, "true"))
+          stateval = true;
+        elseif (strcmpi (stateval, "false"))
+          stateval = false;
         else
-          state = eval (state);
+          stateval = eval (stateval);
         endif
       endif
-      FUNCTION.EDITINPLACE = state;
+      FUNCTION.EDITINPLACE = stateval;
+      return
     case "GET"
-      if (isfield (FUNCTION, toupper(state)))
-        ret = FUNCTION.(toupper (state));
+      if (isfield (FUNCTION, toupper (stateval)))
+        ret = FUNCTION.(toupper (stateval));
       else
         ret = FUNCTION;
       endif
+      return
     otherwise
-      error ('edit: expected "edit EDITOR|HOME|AUTHOR|EMAIL|LICENSE|MODE val"');
+      ## If none of the states match, assume both inputs are
+      ## actually both file names to be opened
+      editfilelist = varargin;
     endswitch
-    return
+  elseif (nargin > 2)
+    if (iscellstr(varargin))
+      editfilelist = varargin;
+    else
+      error('edit: if supplying more than one input all inputs must be strings containing fiel names to open.');
+    endif
   endif
 
   ## Start the editor without a file if no file is given.
   if (nargin < 1)
-    if (exist (FUNCTION.HOME, "dir") == 7 && (isunix () || ! ispc ()))
-      system (cstrcat ("cd \"", FUNCTION.HOME, "\" ; ",
-                      sprintf (undo_string_escapes (FUNCTION.EDITOR), "")),
-              [], FUNCTION.MODE);
+    if (exist (FUNCTION.HOME, "dir") == 7)
+      curr_dir = pwd ();
+      unwind_protect
+        chdir (FUNCTION.HOME);
+        do_edit (FUNCTION.EDITOR, "", FUNCTION.MODE);
+      unwind_protect_cleanup
+        chdir (curr_dir);
+      end_unwind_protect
     else
-      system (sprintf (undo_string_escapes (FUNCTION.EDITOR), ""),
-              [], FUNCTION.MODE);
+      do_edit (FUNCTION.EDITOR, "", FUNCTION.MODE);
     endif
     return;
   endif
 
-  ## Check whether the user is trying to edit a builtin of compiled function.
-  switch (exist (file))
-    case {3, 5}
-      error ("edit: unable to edit a built-in or compiled function");
-  endswitch
+  if (numel(editfilelist) > 1)
+
+    ## Call edit on each of the files in the list if there are more than 1
+    for i = 1:numel(editfilelist)
+      edit(editfilelist{i});
+    endfor
 
-  ## Checks for whether the file is
-  ## absolute or relative should be handled inside file_in_loadpath.
-  ## That way, it will be possible to look up files correctly given
-  ## partial path information.  For example, you should be able to
-  ## edit a particular overloaded function by doing any one of
-  ##
-  ##   edit classname/foo
-  ##   edit classname/foo.m
-  ##   edit @classname/foo
-  ##   edit @classname/foo.m
-  ##
-  ## This functionality is needed for other functions as well (at least
-  ## help and type; there may be more).  So the place to fix that is in
-  ## file_in_loadpath, possibly with some help from the load_path class.
+  else
+  
+    ## Only one file name was supplied, get it from the cell array
+    file = editfilelist{1};
 
-  ## The code below includes a portion that serves as a place-holder for
-  ## the changes suggested above.
+    ## Check whether the user is trying to edit a builtin or compiled function.
+    switch (exist (file))
+      case {3, 5}
+        error ("edit: unable to edit a built-in or compiled function");
+    endswitch
 
-  ## Create list of explicit and implicit file names.
-  filelist = {file};
-  ## If file has no extension, add file.m and file.cc to the list.
-  idx = rindex (file, ".");
-  if (idx == 0)
-    ## Create the list of files to look for
-    filelist = {file};
-    if (isempty (regexp (file, '\.m$')))
-      ## No ".m" at the end of the file, add to the list.
-      filelist{end+1} = cat (2, file, ".m");
-    endif
-    if (isempty (regexp (file, '\.cc$')))
-      ## No ".cc" at the end of the file, add to the list.
-      filelist{end+1} = cat (2, file, ".cc");
-    endif
-  endif
+    ## Checks for whether the file is
+    ## absolute or relative should be handled inside file_in_loadpath.
+    ## That way, it will be possible to look up files correctly given
+    ## partial path information.  For example, you should be able to
+    ## edit a particular overloaded function by doing any one of
+    ##
+    ##   edit classname/foo
+    ##   edit classname/foo.m
+    ##   edit @classname/foo
+    ##   edit @classname/foo.m
+    ##
+    ## This functionality is needed for other functions as well (at least
+    ## help and type; there may be more).  So the place to fix that is in
+    ## file_in_loadpath, possibly with some help from the load_path class.
 
-  ## If the file includes a path, it may be an overloaded function.
-  if (! strcmp (file, "@") && index (file, filesep))
-    ## No "@" at the beginning of the file, add to the list.
-    numfiles = numel(filelist);
-    for n = 1:numfiles
-      filelist{n+numfiles} = cat (2, "@", filelist{n});
-    endfor
-  endif
+    ## The code below includes a portion that serves as a place-holder for
+    ## the changes suggested above.
 
-  ## Search the entire path for the 1st instance of a file in the list.
-  fileandpath = "";
-  for n = 1:numel(filelist)
-    filetoedit = file_in_path (path, filelist{n});
-    if (! isempty (filetoedit))
-      ## The path is explicitly included.
-      fileandpath = filetoedit;
-      break;
+    ## Create list of explicit and implicit file names.
+    filelist = {file};
+    ## If file has no extension, add file.m and file.cc to the list.
+    idx = rindex (file, ".");
+    if (idx == 0)
+      ## Create the list of files to look for
+      filelist = {file};
+      if (isempty (regexp (file, '\.m$')))
+        ## No ".m" at the end of the file, add to the list.
+        filelist{end+1} = cat (2, file, ".m");
+      endif
+      if (isempty (regexp (file, '\.cc$')))
+        ## No ".cc" at the end of the file, add to the list.
+        filelist{end+1} = cat (2, file, ".cc");
+      endif
     endif
-  endfor
+
+    ## If the file includes a path, it may be an overloaded function.
+    if (! strcmp (file, "@") && index (file, filesep))
+      ## No "@" at the beginning of the file, add to the list.
+      numfiles = numel (filelist);
+      for n = 1:numfiles
+        filelist{n+numfiles} = cat (2, "@", filelist{n});
+      endfor
+    endif
 
-  if (! isempty (fileandpath))
-    ## If the file exists, then edit it.
-    if (FUNCTION.EDITINPLACE)
-      ## Edit in place even if it is protected.
-      system (sprintf (undo_string_escapes (FUNCTION.EDITOR),
-                       cstrcat ("\"", fileandpath, "\"")),
-              [], FUNCTION.MODE);
-      return;
-    else
-      ## If the file is modifiable in place then edit it, otherwise make
-      ## a copy in HOME and then edit it.
-      fid = fopen (fileandpath, "r+t");
-      if (fid < 0)
-        from = fileandpath;
-        fileandpath = cstrcat (FUNCTION.HOME, from (rindex (from, filesep):end));
-        [status, msg] = copyfile (from, fileandpath, 1);
-        if (status == 0)
-          error (msg);
-        endif
-      else
-        fclose (fid);
+    ## Search the entire path for the 1st instance of a file in the list.
+    fileandpath = "";
+    for n = 1:numel (filelist)
+      filetoedit = file_in_path (path, filelist{n});
+      if (! isempty (filetoedit))
+        ## The path is explicitly included.
+        fileandpath = filetoedit;
+        break;
       endif
-      system (sprintf (undo_string_escapes (FUNCTION.EDITOR),
-                       cstrcat ("\"", fileandpath, "\"")),
-              [], FUNCTION.MODE);
-      return;
-    endif
-  endif
+    endfor
 
-  ## If editing a new file that is neither a m-file or an oct-file,
-  ## just edit it.
-  fileandpath = file;
-  idx = rindex (file, ".");
-  name = file(1:idx-1);
-  ext = file(idx+1:end);
-  switch (ext)
-    case {"cc", "m"}
-      0;
-    otherwise
-      system (sprintf (undo_string_escapes (FUNCTION.EDITOR),
-                       cstrcat ("\"", fileandpath, "\"")),
-              [], FUNCTION.MODE);
-      return;
-  endswitch
-
-  ## The file doesn't exist in path so create it, put in the function
-  ## template and edit it.
-
-  ## Guess the email name if it was not given.
-  if (isempty (FUNCTION.EMAIL))
-    host = getenv("HOSTNAME");
-    if (isempty (host) && ispc ())
-      host = getenv ("COMPUTERNAME");
-    endif
-    if (isempty (host))
-      [status, host] = system ("uname -n");
-      ## trim newline from end of hostname
-      if (! isempty (host))
-        host = host(1:end-1);
+    if (! isempty (fileandpath))
+      ## If the file exists, then edit it.
+      if (FUNCTION.EDITINPLACE)
+        ## Edit in place even if it is protected.
+        do_edit (FUNCTION.EDITOR, fileandpath, FUNCTION.MODE);
+        return;
+      else
+        ## If the file is modifiable in place then edit it, otherwise make
+        ## a copy in HOME and then edit it.
+        fid = fopen (fileandpath, "r+t");
+        if (fid < 0)
+          from = fileandpath;
+          fileandpath = cstrcat (FUNCTION.HOME, from (rindex (from, filesep):end));
+          [status, msg] = copyfile (from, fileandpath, 1);
+          if (status == 0)
+            error (msg);
+          endif
+        else
+          fclose (fid);
+        endif
+        do_edit (FUNCTION.EDITOR, fileandpath, FUNCTION.MODE);
+        return;
       endif
     endif
-    if (isempty (host))
-      FUNCTION.EMAIL = " ";
-    else
-      FUNCTION.EMAIL = cstrcat ("<", default_user(0), "@", host, ">");
-    endif
-  endif
 
-  ## Fill in the revision string.
-  now = localtime (time);
-  revs = cstrcat ("Created: ", strftime ("%Y-%m-%d", now));
+    ## If editing a new file that is neither a m-file or an oct-file,
+    ## just edit it.
+    fileandpath = file;
+    idx = rindex (file, ".");
+    name = file(1:idx-1);
+    ext = file(idx+1:end);
+    switch (ext)
+      case {"cc", "m"}
+        0;
+      otherwise
+        do_edit (FUNCTION.EDITOR, fileandpath, FUNCTION.MODE);
+        return;
+    endswitch
 
-  ## Fill in the copyright string.
-  copyright = cstrcat (strftime ("Copyright (C) %Y ", now), FUNCTION.AUTHOR);
-
-  ## Fill in the author tag field.
-  author = cstrcat ("Author: ", FUNCTION.AUTHOR, " ", FUNCTION.EMAIL);
+    ## The file doesn't exist in path so create it, put in the function
+    ## template and edit it.
 
-  ## Fill in the header.
-  uclicense = toupper (FUNCTION.LICENSE);
-  switch (uclicense)
-    case "GPL"
-      head = cstrcat (copyright, "\n\n", "\
-This program is free software; you can redistribute it and/or modify\n\
-it under the terms of the GNU General Public License as published by\n\
-the Free Software Foundation; either version 3 of the License, or\n\
-(at your option) any later version.\n\
-\n\
-This program is distributed in the hope that it will be useful,\n\
-but WITHOUT ANY WARRANTY; without even the implied warranty of\n\
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\
-GNU General Public License for more details.\n\
-\n\
-You should have received a copy of the GNU General Public License\n\
-along with Octave; see the file COPYING.  If not, see\n\
-<http://www.gnu.org/licenses/>.\
-");
-      tail = cstrcat (author, "\n", revs);
+    ## Guess the email name if it was not given.
+    if (isempty (FUNCTION.EMAIL))
+      host = getenv ("HOSTNAME");
+      if (isempty (host) && ispc ())
+        host = getenv ("COMPUTERNAME");
+      endif
+      if (isempty (host))
+        [status, host] = system ("uname -n");
+        ## trim newline from end of hostname
+        if (! isempty (host))
+          host = host(1:end-1);
+        endif
+      endif
+      if (isempty (host))
+        FUNCTION.EMAIL = " ";
+      else
+        FUNCTION.EMAIL = cstrcat ("<", default_user(0), "@", host, ">");
+      endif
+    endif
+
+    ## Fill in the revision string.
+    now = localtime (time);
+    revs = cstrcat ("Created: ", strftime ("%Y-%m-%d", now));
 
-    case "BSD"
-      head = cstrcat (copyright, "\n\n", "\
-This program is free software; redistribution and use in source and\n\
-binary forms, with or without modification, are permitted provided that\n\
-the following conditions are met:\n\
-\n\
-   1.Redistributions of source code must retain the above copyright\n\
-     notice, this list of conditions and the following disclaimer.\n\
-   2.Redistributions in binary form must reproduce the above copyright\n\
-     notice, this list of conditions and the following disclaimer in the\n\
-     documentation and/or other materials provided with the distribution.\n\
-\n\
-THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\
-ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\
-OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\
-HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\
-LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\
-OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\
-SUCH DAMAGE.\
-");
-      tail = cstrcat (author, "\n", revs);
+    ## Fill in the copyright string.
+    copyright = cstrcat (strftime ("Copyright (C) %Y ", now), FUNCTION.AUTHOR);
+
+    ## Fill in the author tag field.
+    author = cstrcat ("Author: ", FUNCTION.AUTHOR, " ", FUNCTION.EMAIL);
+
+    ## Fill in the header.
+    uclicense = toupper (FUNCTION.LICENSE);
+    switch (uclicense)
+      case "GPL"
+        head = cstrcat (copyright, "\n\n", "\
+  This program is free software; you can redistribute it and/or modify\n\
+  it under the terms of the GNU General Public License as published by\n\
+  the Free Software Foundation; either version 3 of the License, or\n\
+  (at your option) any later version.\n\
+  \n\
+  This program is distributed in the hope that it will be useful,\n\
+  but WITHOUT ANY WARRANTY; without even the implied warranty of\n\
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\
+  GNU General Public License for more details.\n\
+  \n\
+  You should have received a copy of the GNU General Public License\n\
+  along with Octave; see the file COPYING.  If not, see\n\
+  <http://www.gnu.org/licenses/>.\
+  ");
+        tail = cstrcat (author, "\n", revs);
 
-    case "PD"
-      head = "";
-      tail = cstrcat (author, "\n", revs, "\n\n",
-                     "This program is granted to the public domain.");
-
-    otherwise
-      head = "";
-      tail = cstrcat (copyright, "\n\n", FUNCTION.LICENSE, "\n",
-                     author, "\n", revs);
-  endswitch
+      case "BSD"
+        head = cstrcat (copyright, "\n\n", "\
+  This program is free software; redistribution and use in source and\n\
+  binary forms, with or without modification, are permitted provided that\n\
+  the following conditions are met:\n\
+  \n\
+     1.Redistributions of source code must retain the above copyright\n\
+       notice, this list of conditions and the following disclaimer.\n\
+     2.Redistributions in binary form must reproduce the above copyright\n\
+       notice, this list of conditions and the following disclaimer in the\n\
+       documentation and/or other materials provided with the distribution.\n\
+  \n\
+  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n\
+  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\
+  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\
+  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n\
+  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\
+  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\
+  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\
+  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\
+  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\
+  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\
+  SUCH DAMAGE.\
+  ");
+        tail = cstrcat (author, "\n", revs);
 
-  ## Generate the function template.
-  exists = exist (name);
-  switch (ext)
-    case {"cc", "C", "cpp"}
-      if (isempty (head))
-        comment = cstrcat ("/*\n", tail, "\n\n*/\n\n");
-      else
-        comment = cstrcat ("/*\n", head, "\n\n", tail, "\n\n*/\n\n");
-      endif
-      ## If we are shadowing an m-file, paste the code for the m-file.
-      if (any (exists == [2, 103]))
-        code = cstrcat ("\\ ", strrep (type (name), "\n", "\n// "));
-      else
-        code = " ";
-      endif
-      body = cstrcat ("#include <octave/oct.h>\n\n",
-                     "DEFUN_DLD(", name, ",args,nargout,\"\\\n",
-                     name, "\\n\\\n\")\n{\n",
-                     "  octave_value_list retval;\n",
-                     "  int nargin = args.length();\n\n",
-                     code, "\n  return retval;\n}\n");
+      case "PD"
+        head = "";
+        tail = cstrcat (author, "\n", revs, "\n\n",
+                       "This program is granted to the public domain.");
+
+      otherwise
+        head = "";
+        tail = cstrcat (copyright, "\n\n", FUNCTION.LICENSE, "\n",
+                       author, "\n", revs);
+    endswitch
 
-      text = cstrcat (comment, body);
-    case "m"
-      ## If we are editing a function defined on the fly, paste the
-      ## code.
-      if (any (exists == [2, 103]))
-        body = type (name);
-      else
-        body = cstrcat ("function [ ret ] = ", name, " ()\n\nendfunction\n");
-      endif
-      if (isempty (head))
-        comment = cstrcat ("## ", name, "\n\n",
-                          "## ", strrep (tail, "\n", "\n## "), "\n\n");
-      else
-        comment = cstrcat ("## ", strrep(head,"\n","\n## "), "\n\n", ...
-                          "## ", name, "\n\n", ...
-                          "## ", strrep (tail, "\n", "\n## "), "\n\n");
-      endif
-      text = cstrcat (comment, body);
-  endswitch
+    ## Generate the function template.
+    exists = exist (name);
+    switch (ext)
+      case {"cc", "C", "cpp"}
+        if (isempty (head))
+          comment = cstrcat ("/*\n", tail, "\n\n*/\n\n");
+        else
+          comment = cstrcat ("/*\n", head, "\n\n", tail, "\n\n*/\n\n");
+        endif
+        ## If we are shadowing an m-file, paste the code for the m-file.
+        if (any (exists == [2, 103]))
+          code = cstrcat ("\\ ", strrep (type (name){1}, "\n", "\n// "));
+        else
+          code = " ";
+        endif
+        body = cstrcat ("#include <octave/oct.h>\n\n",
+                       "DEFUN_DLD(", name, ",args,nargout,\"\\\n",
+                       name, "\\n\\\n\")\n{\n",
+                       "  octave_value_list retval;\n",
+                       "  int nargin = args.length ();\n\n",
+                       code, "\n  return retval;\n}\n");
 
-  ## Write the initial file (if there is anything to write)
-  fid = fopen (fileandpath, "wt");
-  if (fid < 0)
-    error ("edit: could not create %s", fileandpath);
+        text = cstrcat (comment, body);
+      case "m"
+        ## If we are editing a function defined on the fly, paste the
+        ## code.
+        if (any (exists == [2, 103]))
+          body = type (name){1};
+        else
+          body = cstrcat ("function [ret] = ", name, " ()\n\nendfunction\n");
+        endif
+        if (isempty (head))
+          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", ...
+                             "## -*- 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);
+    endswitch
+
+    ## Write the initial file (if there is anything to write)
+    fid = fopen (fileandpath, "wt");
+    if (fid < 0)
+      error ("edit: could not create %s", fileandpath);
+    endif
+    fputs (fid, text);
+    fclose (fid);
+
+    do_edit (FUNCTION.EDITOR, fileandpath, FUNCTION.MODE);
+            
   endif
-  fputs (fid, text);
-  fclose (fid);
-
-  ## Finally we are ready to edit it!
-  system (sprintf (undo_string_escapes (FUNCTION.EDITOR),
-                   cstrcat ("\"", fileandpath, "\"")),
-          [], FUNCTION.MODE);
 
 endfunction
 
@@ -509,6 +558,22 @@
 
 endfunction
 
+function do_edit (editor, file, mode)
+
+  ## Give the hook function a chance.  If that fails, fall back
+  ## on running an editor with the system function.
+
+  status = __octave_link_edit_file__ (file);
+
+  if (! status)
+    system (sprintf (undo_string_escapes (editor),
+                     cstrcat ("\"", file, "\"")),
+            [], mode);
+  endif
+
+endfunction
+
+
 %!test
 %! s.editor = edit ("get", "editor");
 %! s.home = edit ("get", "home");
new file mode 100644
--- /dev/null
+++ b/scripts/miscellaneous/error_ids.m
@@ -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/fact.m
+++ b/scripts/miscellaneous/fact.m
@@ -24,14 +24,14 @@
 ## @end deftypefn
 
 
-function f = fact()
-  persistent wisdom = \
+function f = fact ()
+  persistent wisdom = ...
       {
        "Richard Stallman takes notes in binary.";
        "Richard Stallman doesn't need sudo. I will make him a sandwich anyway.";
        "Richard Stallman is my shephurd, and I am his GNU.";
        "Richard Stallman doesn't wget, Richard Stallman wdemands!";
-       "Richard Stallman can touch MC Hammer";
+       "Richard Stallman can touch MC Hammer.";
        "Richard Stallman doesn't read web pages. They write to him.";
        "Richard Stallman gets 9 bits to the byte.";
        "Richard Stallman doesn't really believe in open software, because it's not free enough.";
@@ -50,48 +50,48 @@
        "Richard Stallman eats ethernet cables. That's why they invented wireless.";
        "Richard Stallman has a katana. 'Nuff said.";
        "Richard Stallman wrote a program that divides by zero.";
-       "Ricahrd Stallman doesn't use zip drives, he just squeezes the hard drive.";
+       "Richard Stallman doesn't use zip drives; he just squeezes the hard drive.";
        "Richard Stallman's compiler is afraid to report errors.";
        "Richard Stallman wrote the compiler God used. The Big Bang was the Universe's first segfault.";
        "Richard Stallman successfully compiled a kernel of popcorn.";
-       "Richard Stallman doesn't write programs, they write themselves out of reverence.";
+       "Richard Stallman doesn't write programs; they write themselves out of reverence.";
        "Richard Stallman can make infinite loops end.";
        "Richard Stallman's anti-virus programs cures HIV.";
        "Richard Stallman's computer doesn't have a clock; it defines what time it is.";
        "Richard Stallman wrote a program to compute the last digit of pi.";
-       "Richard Stallman doesn't use web browsers. He sends a link to a demon that uses wget to fetch the page and sends it back to him.";
+       "Richard Stallman doesn't use web browsers. He sends a link to a daemon that uses wget to fetch the page and sends it back to him.";
        "Richard Stallman can solve the halting problem... in polynomial time.";
        "For Richard Stallman, polynomial time is O(1).";
        "Richard Stallman didn't \"write\" Emacs or created it in his own image. Richard Stallman made Emacs an instance of himself.";
        "Richard Stallman can coerce meaningful data from /dev/null.";
        "Some people wear Linus Torvalds pyjamas to bed, Linus Torvalds wears Richard Stallman pyjamas.";
-       "There is no software development process, only a bunch of programs Richard Stallman allows to exist. ";
-       "Richard Stallman spends his leisure time programming with Guile on GNU Hurd. ";
+       "There is no software development process, only a bunch of programs Richard Stallman allows to exist.";
+       "Richard Stallman spends his leisure time programming with Guile on GNU Hurd.";
        "Richard Stallman's left and right hands are named \"(\" and \")\" ";
-       "Richard Stallman first words were actually syscalls. ";
-       "Richard Stallman didn't create the singularity. He is the singularity. GNU/Linux is only the event horizon. ";
+       "Richard Stallman first words were actually syscalls.";
+       "Richard Stallman didn't create the singularity. He is the singularity. GNU/Linux is only the event horizon.";
        "When Richard Stallman pipes to more, he gets less ";
-       "Richard Stallman never showers: he runs 'make clean'. ";
-       "Richard Stallman needs neither mouse nor keyboard to operate his computer. He just stares it down until it does what he wants. ";
-       "Richard Stallman didn't write the GPL. He is the GPL. ";
-       "Richad Stallman's pinky finger is really a USB memory stick. ";
-       "Richard Stallman called his operating system GNU because he created it before computers existed, when actual gnus were used for calcuations. ";
-       "In Soviet Russia, Richard Stallman is still Richard Stallman! ";
-       "Richard Stallman's flute only plays free music. ";
+       "Richard Stallman never showers; he runs 'make clean'.";
+       "Richard Stallman needs neither mouse nor keyboard to operate his computer. He just stares it down until it does what he wants.";
+       "Richard Stallman didn't write the GPL. He is the GPL.";
+       "Richard Stallman's pinky finger is really a USB memory stick.";
+       "Richard Stallman called his operating system GNU because he created it before computers existed, when actual gnus were used for calcuations.";
+       "In Soviet Russia, Richard Stallman is still Richard Stallman!";
+       "Richard Stallman's flute only plays free music.";
        "When Richard Stallman uses floats, there are no rounding errors.";
-       "Richard Stallman wrote a program so powerful, it knows the question to 42.";
+       "Richard Stallman wrote a program so powerful it knows the question to 42.";
        "Richard Stallman released his own DNA under GNU FDL.";
        "Richard Stallman knows the entire wikipedia by heart, markup included.";
        "Richard Stallman wrote the HAL9000 OS.";
        "Richard Stallman's laser pointer is a lightsaber.";
-       "Richard Stallman never steps down; he shifts the universe up .";
+       "Richard Stallman never steps down; he shifts the universe up.";
        "Richard Stallman doesn't maintain code; he stares at it until it fixes itself out of reverence.";
        "Richard Stallman doesn't use an editor; he sets the fundamental constants of the universe so that a magnetic platter with his code on it evolves itself.";
        "Richard Stallman doesn’t code; he dares the computer to not do his bidding.";
-       "Global warming is caused by Richard Stallman’s rage toward non-free software.";
+       "Global warming is caused by Richard Stallman's rage towards non-free software.";
        "Rather than being birthed like a normal child, Richard Stallman instead instantiated himself polymorphically. Shortly thereafter he grew a beard.";
        "Richard Stallman discovered extra-terrestrial life but killed them because they used non-free software.";
-       "Richard Stallman doesn't evaluate expressions, expressions evaluate to Richard Stallman.";
+       "Richard Stallman doesn't evaluate expressions; expressions evaluate to Richard Stallman.";
        "Richard Stallman can see Russia from his house.";
        "Richard Stallman proved P=NP, twice!";
        "Richard Stallman knows of an unfixed bug in TeX.";
@@ -118,7 +118,7 @@
        "Richard Satallman can make any operating system free, free from drivers.";
        "Richard Stallman programmed Chuck Norris.";
        "Behind Richard Stallman's beard there is another fist, to code faster.";
-       "Richard Stallman won a Suduku that started with only one number in each line";
+       "Richard Stallman won a Sudoku that started with only one number in each line.";
        "Richard Stallman's brain compiles and runs C code.";
        "Richard Stallman wrote the first version of Emacs using Emacs.";
        "Richard Stallman never gonna give you up, never gonna let you down, never gonna run around and desert you, never gonna make you cry, never gonna say goodbye, never gonna tell a lie and hurt you.";
@@ -127,15 +127,15 @@
        "Richard Stallman will revert the big rip by adding parenthesis to the dark matter.";
        "When you make a Google search and it doesn't find the answer, Google gently consults Richard Stallman.";
        "Richard Stallman's uptime is over 53 years. And counting up.";
-       "Richard Stallman's portable music player plays ogg and WMA.";
+       "Richard Stallman's portable music player can play ogg and WMA, but is too afraid to invoke Richard Stallman's wrath by playing WMA. Ogg it is, then.";
        "Richard Stallman will never die, but may some day go to /dev/null.";
        "Richard Stallman once got swine flu, but it got cleansed by hereditay GPL and thus got assimilated.";
-       "Richard Stallman don't cut his hair because there are no GNU/Scissors";
+       "Richard Stallman don't cut his hair because there are no GNU/Scissors.";
        "Richard Stallman is the one who trims Chuck Norris beard. And he does it freely, of course.";
        "Richard Stallman does not take bath, for the hydroelectric company uses proprietary software.";
        "Agent Smith loves Richard Stallman's scent.";
        "Richard Stallman is the One.";
-       "\"They can take our lives, but they can never take our freedom.\" Willian Wallace after a litle talk with Richard Stallman.";
+       "\"They can take our lives, but they can never take our freedom.\" -- William Wallace after a little talk with Richard Stallman.";
        "Richard Stallman can connect to any brain using an Emacs ssh client.";
        "Richard Stallman ported Emacs to Intel 4004 chip.";
        "Richard Stallman did not write GNU Emacs, he simply read the source code from /dev/null.";
@@ -147,9 +147,8 @@
        "When Richard Stallman runs /bin/false, it returns \"true\".";
        "Richard Stallman doesn't like money, because banks don't run on free software.";
        "Richard Stallman user GNU tar to compress air.";
-       "Richard Stallman was installed in the world, it runs on a free program ..";
        "When Richard Stallman reports a bug, the bug prefers to squash itself instead of facing Richard Stallman's wrath.";
-       "There is no Windows in Richard Stallman's house... only Doors...";
+       "There are no Windows in Richard Stallman's house... only Doors...";
        "Richard Stallman doesn't like neither PCs-Intel nor Burger King... He prefers e-Macs...";
        "Richard Stallman can use grep to find Jimmy Hoffa.";
        "Richard Stallman made it possible to not absolutely abhor HPUX.";
@@ -161,8 +160,8 @@
        "Richard Stallman doesn't need a qwerty/dvorak keyboard only two buttons \"1\" and \"0\" and his erect penis.";
        "On the first day Richard Stallman said M-x create-light.";
        "Richard Stallman once went out of scope for a while. The garbage collector never dared to touch him.";
-       "Richard Stallman does not compile; he closes his eyes, and see energy lines created between bit blocks by the compiler optimizations...";
-       "intx80 first calls Richard Stallman before calling sys_call";
+       "Richard Stallman does not compile; he closes his eyes, and see energy lines created between bit blocks by the compiler optimizations.";
+       "intx80 first calls Richard Stallman before calling sys_call.";
        "Tron is actually a biographical story about Richard Stallman. The director decided to tone it down or audiences wouldn't find it believable.";
        "Richard Stallman always wears a red shirt to make sure that whatever attacks his away-team has to go through him first.";
        "kill -9 invokes Richard Stallman's rage against a process.";
@@ -176,12 +175,12 @@
        "If Richard Stallman's beard were ever trimmed, the clippings would re-marshal into an exact copy of Richard Stallman.";
        "Richard Stallman never sleeps because he altered his own source to gain background garbage collection.";
        "Richard Stallman's doctor can retrieve a blood sample via CVS.";
-       "Richard Stallman can touch this";
+       "Richard Stallman can touch this.";
        "Because Richard Stallman's DNA is licensed under the FDL, his doctor can't draw his blood without violating HIPAA.";
-       "Richard Stallman can remove his own appendix, using only gdb.";
+       "Richard Stallman can remove his own appendix, using only GDB.";
        "Richard Stallman's DNA includes debugging symbols. But he doesn't need them.";
        "Richard Stallman met Chuck Norris once. Chuck tried a roundhouse, but Richard bashed him in the skull.";
-       "Richard Stallman doesn't need to buy a bigger hard drive. He can compress data infinitely. ";
+       "Richard Stallman doesn't need to buy a bigger hard drive. He can compress data infinitely.";
        "When Richard Stallman cannot take your call, his beard answers the phone for you.";
        "The R in RMS stands for RMS.";
        "Richard Stallman can parse HTML with regular expressions.";
@@ -194,24 +193,24 @@
        "After being unable to satisfy my wife for years, Richard Stallman was able to single-handedly unlock her orgasm within seconds and managed to write a texinfo manual minutes later for other users.";
        "Richard Stallman's tabbed browser is a set to wget/telnet fg/bg processes.";
        "There is no chin under Richard Stallman' beard. There's only another beard. Recursively.";
-       "Stallman can chown anything! stallman@stallman~$ chown stallman:stallman Earth (for example)";
+       "Richard Stallman can chown anything! stallman@stallman~$ chown stallman:stallman Earth (for example)";
        "Richard Stallman freed his beard so he can always check what's in it.";
        "In the beginning was the Word, and the Word was with RMS, and the Word was GNU.";
        "RMS means \"RMS means Stallman\"";
        "Richard Stallman is the babelfish of his own speeches.";
        "Richard Stallman wrote his own library and lives in it.";
        "Richard Stallman found Waldo using grep in /dev/null";
-       "Richard Stallman doesn't sleep; he is compiling";
+       "Richard Stallman doesn't sleep; he is compiling.";
        "Richard Stallman will get Coca Cola to release their recipe under the GPL.";
        "Richard Stallman doesn't change clothes. He makes case mods.";
        "Richard Stallman compiled the first version of gcc with an hexadecimal editor.";
-       "Richard Stallman will be the last guest on Linux Outlaws";
+       "Richard Stallman will be the last guest on Linux Outlaws.";
        "Richard Stallman calculates the universe's entropy by exploiting forced stack overflows.";
        "Richard Stallman's consciousness will one day become the singularity, which will create Deep Thought, and answer the meaning of life, the universe and everything.";
        "C is actually written in RMS.";
        "Richard Stallman can write software that does not have a buffer overflow when counting money lost by Jerome Kerviel.";
        "There were no double rainbows before Richard Stallman.";
-       "Chuck Norris had to shorten his beard in the presence of Stallman because two beards that awsome, so close would segfault the universe (again).";
+       "Chuck Norris had to shorten his beard in the presence of Richard Stallman because two beards that awsome, so close would segfault the universe (again).";
        "RMS is Titanic.";
        "Richard Stallman is the answer to the Turing Test.";
        "Richard Stallman's beard makes ads for Gillette and Braun appear.";
@@ -225,24 +224,23 @@
        "Richard Stallman doesn't always run an OS kernel, but when he does he prefers GNU/Hurd. He is... the most interesting hacker in the world. Stay free, my friends.";
        "When Richard Stallman gets hungry, he just picks debris from his foot and eats it.";
        "Richard Stallman can GPL your code just by looking at it funny.";
-       "Richard Mathew Stallman loves birds. Birds make auricular love to Richard Mathew Stallman.";
+       "Richard Stallman loves birds. Birds make auricular love to Richard Stallman.";
        "Richard Stallman is so free that the primitive recursive function for computing his liberty causes a stack overflow.";
        "GNU Hurd is taking more than twenty years to develop because Richard Stallman is using a programming language comprised entirely of different lengths of time.";
        "Richard Stallman's beard contains Richard Stallman, whose beard contains Richard Stallman....";
-       "Richard Stallman had a Google Plus account in 2010.";
-       "sudo chown rms:gnu ~/base -R";
+       "Richard Stallman could have had a Google Plus account in 2010. Too bad he didn't want it.";
        "Richard Stallman pipes the Emacs binaries to /dev/dsp before he goes to sleep.";
        "When Richard Stallman counted his fingers as a kid, he always started with 0.";
        "When Richard Stallman's computer gets a virus, he simply applies a GPL license to it which converts the whole botnet to Linux. I mean, GNU/Linux.";
        "Richard Stallman's beard trimmings can cure cancer. Too bad he never shaves.";
-       "Richard Stallman's doesn't kill a process, he just dares it to stay running.";
-       "Richard Stallman exists because he compiled himself into being. ";
+       "Richard Stallman's doesn't kill a process; he just dares it to stay running.";
+       "Richard Stallman exists because he compiled himself into being.";
        "Richard Stallman's first words were in binary. When they couldn't understand him, he wrote a parser.";
        "Richard Stallman doesn't need any codecs, he just opens a multimedia file with Emacs, and reads the bytes of the file as plain text. He then performs all the necessary decoding in his mind. But he refuses to decode files encrypted with DRM, although his mind is able to.";
        };
 
   w = wisdom{randi([1, numel(wisdom)])};
-  if nargout > 0
+  if (nargout > 0)
     f = w;
   else
     w = wordwrap (w);
@@ -252,18 +250,19 @@
 
 function out = wordwrap (w)
   cols = terminal_size ()(2);
-  wc = strsplit (w, " ");
+  wc = strsplit (w, " ", false);
   out = "\n";
   i = 1;
   numwords = numel (wc);
-  while i <= numwords;
+  while (i <= numwords);
     line = wc{i};
-    while (i < numwords && length (newline = cstrcat (line, " ", wc{i+1})) < cols)
+    while (i < numwords
+           && length (newline = cstrcat (line, " ", wc{i+1})) < cols)
       line = newline;
       i++;
     endwhile
     out = cstrcat (out, line, "\n");
     i++;
   endwhile
-  out = cstrcat(out, "\n");
-endfunction
\ No newline at end of file
+  out = cstrcat (out, "\n");
+endfunction
--- a/scripts/miscellaneous/fileattrib.m
+++ b/scripts/miscellaneous/fileattrib.m
@@ -57,6 +57,7 @@
 ## True if the user (group; other users) has execute permission for
 ## @var{file}.
 ## @end table
+##
 ## If an attribute does not apply (i.e., archive on a Unix system) then
 ## the field is set to NaN.
 ##
--- a/scripts/miscellaneous/fileparts.m
+++ b/scripts/miscellaneous/fileparts.m
@@ -34,7 +34,7 @@
       es = rindex (filename, ".");
       ## These can be the same if they are both 0 (no dir or ext).
       if (es <= ds)
-        es = length(filename)+1;
+        es = length (filename)+1;
       endif
       if (ds == 0)
         directory = "";
@@ -59,6 +59,7 @@
 
 endfunction
 
+
 %!test
 %! [d, n, e] = fileparts ("file");
 %! assert (strcmp (d, "") && strcmp (n, "file") && strcmp (e, ""));
@@ -94,3 +95,4 @@
 %!test
 %! [d, n, e] = fileparts (".ext");
 %! assert (strcmp (d, "") && strcmp (n, char (zeros (1, 0))) && strcmp (e, ".ext"));
+
--- a/scripts/miscellaneous/fullfile.m
+++ b/scripts/miscellaneous/fullfile.m
@@ -53,6 +53,7 @@
 
 endfunction
 
+
 %!shared fs, fsx, xfs, fsxfs, xfsy
 %! fs = filesep ();
 %! fsx = cstrcat (fs, "x");
@@ -78,3 +79,4 @@
 %!assert (fullfile (fs, xfs), fsxfs)
 %!assert (fullfile (fsx, fs), fsxfs)
 %!assert (fullfile (fs, "x", fs), fsxfs)
+
--- a/scripts/miscellaneous/getappdata.m
+++ b/scripts/miscellaneous/getappdata.m
@@ -15,12 +15,14 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {@var{value} =} getappdata (@var{h}, @var{name})
+## @deftypefn  {Function File} {@var{value} =} getappdata (@var{h}, @var{name})
+## @deftypefnx {Function File} {@var{appdata} =} getappdata (@var{h})
+## 
 ## Return the @var{value} for named application data for the object(s) with
 ## handle(s) @var{h}.
-## @deftypefnx {Function File} {@var{appdata} =} getappdata (@var{h})
-## Return a structure, @var{appdata}, whose fields correspond to the appdata
-## properties.
+## 
+## @code{getappdata(@var{h})} returns a structure, @var{appdata}, whose fields
+## correspond to the appdata properties.
 ## @end deftypefn
 
 ## Author: Ben Abbott <bpabbott@mac.com>
@@ -32,8 +34,8 @@
     ## FIXME - Is there a better way to handle non-existent appdata
     ## and missing fields?
     val = cell (numel (h), 1);
-    appdata = struct();
-    for nh = 1:numel(h)
+    appdata = struct ();
+    for nh = 1:numel (h)
       try
         appdata = get (h(nh), "__appdata__");
       end_try_catch
--- a/scripts/miscellaneous/getfield.m
+++ b/scripts/miscellaneous/getfield.m
@@ -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
 
@@ -60,9 +44,11 @@
   endif
 endfunction
 
+
 %!test
 %! x.a = "hello";
-%! assert(getfield(x,"a"),"hello");
+%! assert (getfield (x, "a"), "hello");
 %!test
 %! ss(1,2).fd(3).b = 5;
-%! assert(getfield(ss,{1,2},'fd',{3},'b'),5)
+%! assert (getfield (ss,{1,2},"fd",{3},"b"), 5);
+
--- a/scripts/miscellaneous/gzip.m
+++ b/scripts/miscellaneous/gzip.m
@@ -20,7 +20,7 @@
 ## @deftypefn  {Function File} {@var{entries} =} gzip (@var{files})
 ## @deftypefnx {Function File} {@var{entries} =} gzip (@var{files}, @var{outdir})
 ## Compress the list of files and/or directories specified in @var{files}.
-## Each file is compressed separately and a new file with a '.gz' extension
+## Each file is compressed separately and a new file with a ".gz" extension
 ## is created.  The original files are not modified.  Existing compressed
 ## files are silently overwritten.  If @var{outdir} is defined the compressed
 ## files are placed in this directory.
@@ -40,33 +40,36 @@
 
 endfunction
 
-%!error <Invalid call to gzip.  Correct usage is> gzip("1", "2", "3");
-%!error <Invalid call to gzip.  Correct usage is> gzip();
-%!error <output directory does not exist> gzip("1", tmpnam);
-%!error <FILES must be a character array or cellstr> gzip(1);
+
 %!xtest
-%!  # test gzip together with gunzip
-%!  unwind_protect
-%!    filename = tmpnam;
-%!    dummy    = 1;
-%!    save(filename, "dummy");
-%!    dirname  = tmpnam;
-%!    mkdir(dirname);
-%!    entry = gzip(filename, dirname);
-%!    [path, basename, extension] = fileparts(filename);
-%!    if ! strcmp(entry, [dirname, filesep, basename, extension, ".gz"])
-%!      error("gzipped file does not match expected name!");
-%!    endif
-%!    if ! exist(entry, "file")
-%!      error("gzipped file cannot be found!");
-%!    endif
-%!    gunzip(entry);
-%!    if (system(sprintf("diff %s %s%c%s%s", filename, dirname, filesep,
-%!                                          basename, extension)))
-%!      error("unzipped file not equal to original file!");
-%!    end
-%!  unwind_protect_cleanup
-%!    delete(filename);
-%!    delete([dirname, filesep, basename, extension]);
-%!    rmdir(dirname);
-%!  end_unwind_protect
+%! # test gzip together with gunzip
+%! unwind_protect
+%!   filename = tmpnam;
+%!   dummy    = 1;
+%!   save (filename, "dummy");
+%!   dirname  = tmpnam;
+%!   mkdir (dirname);
+%!   entry = gzip (filename, dirname);
+%!   [path, basename, extension] = fileparts (filename);
+%!   if (! strcmp (entry, [dirname, filesep, basename, extension, ".gz"]))
+%!     error ("gzipped file does not match expected name!");
+%!   endif
+%!   if (! exist (entry, "file"))
+%!     error ("gzipped file cannot be found!");
+%!   endif
+%!   gunzip (entry);
+%!   if (system (sprintf ("diff %s %s%c%s%s", filename, dirname, filesep,
+%!                                            basename, extension)))
+%!     error ("unzipped file not equal to original file!");
+%!   end
+%! unwind_protect_cleanup
+%!   delete (filename);
+%!   delete ([dirname, filesep, basename, extension]);
+%!   rmdir (dirname);
+%! end_unwind_protect
+
+%!error gzip ()
+%!error gzip ("1", "2", "3")
+%!error <output directory does not exist> gzip ("1", tmpnam)
+%!error <FILES must be a character array or cellstr> gzip (1)
+
--- a/scripts/miscellaneous/info.m
+++ b/scripts/miscellaneous/info.m
@@ -45,5 +45,7 @@
 
 endfunction
 
+
 ## Mark file as being tested.  No real test needed for this function.
 %! assert (1)
+
--- a/scripts/miscellaneous/inputname.m
+++ b/scripts/miscellaneous/inputname.m
@@ -40,6 +40,7 @@
 
 endfunction
 
+
 ## Warning: heap big magic in the following tests!!!
 ## The test function builds a private context for each
 ## test, with only the specified values shared between
@@ -51,6 +52,8 @@
 ## To test inputname, I need a function context invoked
 ## with known parameter names.  So define a couple of
 ## shared parameters, et voila!, the test is trivial.
-%!shared hello,worldly
-%!assert(inputname(1),'hello');
-%!assert(inputname(2),'worldly');
+  
+%!shared hello, worldly
+%!assert (inputname (1), "hello")
+%!assert (inputname (2), "worldly")
+
--- a/scripts/miscellaneous/isappdata.m
+++ b/scripts/miscellaneous/isappdata.m
@@ -30,7 +30,7 @@
     error ("isappdata: invalid input");
   endif
 
-  for nh = 1:numel(h)
+  for nh = 1:numel (h)
     data = get (h(nh));
     if (isfield (data, "__appdata__") && isfield (data.__appdata__, name))
       res(nh) = true;
@@ -41,8 +41,9 @@
 
 endfunction
 
+
 %!test
-%! setappdata (0, "hello", "world")
-%! assert (isappdata (0, "hello"), true)
-%!assert (isappdata (0, "foobar"), false)
+%! setappdata (0, "hello", "world");
+%! assert (isappdata (0, "hello"), true);
+%! assert (isappdata (0, "foobar"), false);
 
--- a/scripts/miscellaneous/isdeployed.m
+++ b/scripts/miscellaneous/isdeployed.m
@@ -28,4 +28,5 @@
   retval = false;
 endfunction
 
+
 %!assert (isdeployed (), false)
--- a/scripts/miscellaneous/ismac.m
+++ b/scripts/miscellaneous/ismac.m
@@ -32,5 +32,7 @@
 
 endfunction
 
-%!error ismac (1);
-%!assert (islogical (ismac ()));
+
+%!assert (islogical (ismac ()))
+
+%!error ismac (1)
--- a/scripts/miscellaneous/ispc.m
+++ b/scripts/miscellaneous/ispc.m
@@ -32,5 +32,8 @@
 
 endfunction
 
-%!error ispc (1);
-%!assert (islogical (ispc ()));
+
+%!assert (islogical (ispc ()))
+
+%!error ispc (1)
+
--- a/scripts/miscellaneous/isunix.m
+++ b/scripts/miscellaneous/isunix.m
@@ -32,5 +32,8 @@
 
 endfunction
 
-%!error isunix (1);
-%!assert (islogical (isunix ()));
+
+%!assert (islogical (isunix ()))
+
+%!error isunix (1)
+
--- a/scripts/miscellaneous/license.m
+++ b/scripts/miscellaneous/license.m
@@ -17,21 +17,31 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} license
+## @deftypefn  {Command} {} license
+## @deftypefnx {Function File} {} license ("inuse")
+## @deftypefnx {Function File} {@var{retval} =} license ("inuse")
+## @deftypefnx {Function File} {@var{retval} =} license ("test", @var{feature})
+## @deftypefnx {Function File} {} license ("test", @var{feature}, @var{toggle})
+## @deftypefnx {Function File} {@var{retval} =} license ("checkout", @var{feature})
+## 
 ## Display the license of Octave.
 ##
-## @deftypefnx {Function File} {} license ("inuse")
+## @code{license ("inuse")}
+##
 ## Display a list of packages currently being used.
 ##
-## @deftypefnx {Function File} {@var{retval} =} license ("inuse")
+## @code{@var{retval} = license ("inuse")}
+##
 ## Return a structure containing the fields @code{feature} and @code{user}.
 ##
-## @deftypefnx {Function File} {@var{retval} =} license ("test", @var{feature})
+## @code{@var{retval} = license ("test", @var{feature})}
+##
 ## Return 1 if a license exists for the product identified by the string
 ## @var{feature} and 0 otherwise.  The argument @var{feature} is case
 ## insensitive and only the first 27 characters are checked.
 ##
-## @deftypefnx {Function File} {} license ("test", @var{feature}, @var{toggle})
+## @code{license ("test", @var{feature}, @var{toggle})}
+##
 ## Enable or disable license testing for @var{feature}, depending on
 ## @var{toggle}, which may be one of:
 ##
@@ -44,7 +54,8 @@
 ## Future tests for the specified license of @var{feature} return 0.
 ## @end table
 ##
-## @deftypefnx {Function File} {@var{retval} =} license ("checkout", @var{feature})
+## @code{@var{retval} = license ("checkout", @var{feature})}
+##
 ## Check out a license for @var{feature}, returning 1 on success and 0
 ## on failure.
 ##
--- a/scripts/miscellaneous/list_primes.m
+++ b/scripts/miscellaneous/list_primes.m
@@ -51,8 +51,8 @@
   endif
 
   retval = zeros (1, n);
-  retval (1) = 2;
-  retval (2) = 3;
+  retval(1) = 2;
+  retval(2) = 3;
 
   n = n - 2;
   i = 3;
@@ -75,7 +75,7 @@
     endwhile
 
     if (is_prime)
-      retval (i++) = p;
+      retval(i++) = p;
       n--;
     endif
     p = p + 2;
@@ -84,8 +84,8 @@
 
 endfunction
 
-%!test
-%! assert (list_primes(), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,\
-%!                        43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]);
-%! assert (list_primes(5), [2, 3, 5, 7, 11]);
 
+%!assert (list_primes (), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, ...
+%!                         43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97])
+%!assert (list_primes (5), [2, 3, 5, 7, 11]);
+
--- a/scripts/miscellaneous/ls.m
+++ b/scripts/miscellaneous/ls.m
@@ -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
@@ -90,5 +90,5 @@
 %! assert (ischar (list));
 %! assert (! isempty (list));
 
-%!error ls (1);
+%!error ls (1)
 
--- a/scripts/miscellaneous/menu.m
+++ b/scripts/miscellaneous/menu.m
@@ -44,13 +44,41 @@
 
   page_screen_output (0, "local");
 
+  ## Process Supplied Options
+  if (nargin == 2)
+    ## List in a cell array
+    if (iscell (varargin{1}))
+      varargin = varargin{1};
+      nopt = length (varargin);
+      for i = 1:nopt
+        while (iscell (varargin{i}))
+          varargin{i} = varargin{i}{1};
+        endwhile
+      endfor
+    else
+      nopt = nargin - 1;
+    endif
+  else
+    ## List with random elements in it - pick the first always
+    for i = 1:nargin - 1
+      if (iscell (varargin{i}))
+        while (iscell (varargin{i}))
+          varargin{i} = varargin{i}{1};
+        endwhile
+      else
+        if (! ischar (varargin{i}))
+          varargin{i} = varargin{i}(1);
+        endif
+      endif
+    endfor
+    nopt = length (varargin);
+  endif
+
   if (! isempty (title))
     disp (title);
     printf ("\n");
   endif
 
-  nopt = nargin - 1;
-
   while (1)
     for i = 1:nopt
       printf ("  [%2d] ", i);
--- a/scripts/miscellaneous/mexext.m
+++ b/scripts/miscellaneous/mexext.m
@@ -26,4 +26,5 @@
   retval = "mex";
 endfunction
 
+
 %!assert (mexext (), "mex")
--- a/scripts/miscellaneous/mkoctfile.m
+++ b/scripts/miscellaneous/mkoctfile.m
@@ -17,7 +17,7 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Command} {} mkoctfile [-options] file @dots{}
+## @deftypefn  {Command} {} mkoctfile [-options] file @dots{}
 ## @deftypefnx {Function File} {[@var{output}, @var{status} =} mkoctfile (@dots{})
 ##
 ## The @code{mkoctfile} function compiles source code written in C,
@@ -87,18 +87,18 @@
 ##    CFLAGS                    LD_CXX
 ##    CPICFLAG                  LD_STATIC_FLAG
 ##    CPPFLAGS                  LFLAGS
-##    CXX                       LIBCRUFT
-##    CXXFLAGS                  LIBOCTAVE
-##    CXXPICFLAG                LIBOCTINTERP
-##    DEPEND_EXTRA_SED_PATTERN  LIBS
-##    DEPEND_FLAGS              OCTAVE_LIBS
-##    DL_LD                     OCTAVE_LINK_DEPS
-##    DL_LDFLAGS                OCT_LINK_DEPS
-##    EXEEXT                    RDYNAMIC_FLAG
-##    F77                       READLINE_LIBS
-##    F77_INTEGER_8_FLAG        SED
-##    FFLAGS                    XTRA_CFLAGS
-##    FFTW3_LDFLAGS             XTRA_CXXFLAGS
+##    CXX                       LIBOCTAVE       
+##    CXXFLAGS                  LIBOCTINTERP    
+##    CXXPICFLAG                LIBS            
+##    DEPEND_EXTRA_SED_PATTERN  OCTAVE_LIBS     
+##    DEPEND_FLAGS              OCTAVE_LINK_DEPS
+##    DL_LD                     OCT_LINK_DEPS   
+##    DL_LDFLAGS                RDYNAMIC_FLAG   
+##    EXEEXT                    READLINE_LIBS   
+##    F77                       SED             
+##    F77_INTEGER_8_FLAG        XTRA_CFLAGS     
+##    FFLAGS                    XTRA_CXXFLAGS   
+##    FFTW3_LDFLAGS             
 ##    FFTW3_LIBS
 ##    FFTW3F_LDFLAGS
 ##
--- a/scripts/miscellaneous/module.mk
+++ b/scripts/miscellaneous/module.mk
@@ -1,6 +1,7 @@
 FCN_FILE_DIRS += miscellaneous
 
 miscellaneous_PRIVATE_FCN_FILES = \
+  miscellaneous/private/display_info_file.m \
   miscellaneous/private/__xzip__.m
 
 miscellaneous_FCN_FILES = \
@@ -10,6 +11,7 @@
   miscellaneous/bunzip2.m \
   miscellaneous/bzip2.m \
   miscellaneous/cast.m \
+  miscellaneous/citation.m \
   miscellaneous/comma.m \
   miscellaneous/compare_versions.m \
   miscellaneous/computer.m \
@@ -20,6 +22,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 +71,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/movefile.m
+++ b/scripts/miscellaneous/movefile.m
@@ -72,7 +72,7 @@
 
     ## If f1 has more than 1 element f2 must be a directory
     isdir = (exist (f2, "dir") != 0);
-    if (length(f1) > 1 && ! isdir)
+    if (length (f1) > 1 && ! isdir)
       error ("movefile: when moving multiple files, second argument must be a directory");
     endif
 
@@ -84,12 +84,12 @@
     p1 = sprintf ("\"%s\" ", f1{:});
     p2 = tilde_expand (f2);
 
-    if (isdir && length(p1) > max_cmd_line)
-      l2 = length(p2) + length (cmd) + 6;
-      while (! isempty(f1))
+    if (isdir && length (p1) > max_cmd_line)
+      l2 = length (p2) + length (cmd) + 6;
+      while (! isempty (f1))
         p1 = sprintf ("\"%s\" ", f1{1});
         f1(1) = [];
-        while (!isempty (f1) && (length(p1) + length(f1{1}) + l2 <
+        while (!isempty (f1) && (length (p1) + length (f1{1}) + l2 <
                                  max_cmd_line))
           p1 = sprintf ("%s\"%s\" ", p1, f1{1});
           f1(1) = [];
--- a/scripts/miscellaneous/namelengthmax.m
+++ b/scripts/miscellaneous/namelengthmax.m
@@ -31,4 +31,4 @@
 endfunction
 
 
-%!assert (namelengthmax, 63)
+%!assert (namelengthmax (), 63)
--- a/scripts/miscellaneous/news.m
+++ b/scripts/miscellaneous/news.m
@@ -17,47 +17,26 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} news (@var{package})
-## Display the current NEWS file for Octave or installed package.
+## @deftypefn  {Command} {} news
+## @deftypefnx {Command} {} news @var{package}
+## Display the current NEWS file for Octave or an installed package.
 ##
-## If @var{package} is the name of an installed package, display the current
-## NEWS file for that package.
+## When called without an argument, display the NEWS file for Octave.
+## When given a package name @var{package}, display the current NEWS file for
+## that package.
 ## @end deftypefn
 
 function news (package = "octave")
 
-  if (ischar (package) && strcmpi (package, "octave"))
-    octetcdir = octave_config_info ("octetcdir");
-    newsfile  = fullfile (octetcdir, "NEWS");
-
-  elseif (nargin == 1 && ischar (package))
-    installed = pkg ("list");
-    names     = cellfun (@(x) x.name, installed, "UniformOutput", false);
-    ## we are nice and let the user use any case on the package name
-    pos = strcmpi (names, package);
-    if (!any (pos))
-      error ("Package '%s' is not installed.", package);
-    endif
-    newsfile = fullfile (installed{pos}.dir, "packinfo", "NEWS");
-
+  if (nargin > 1)
+    print_usage ();
   else
-    print_usage;
-  endif
-
-  if (exist (newsfile, "file"))
-    f = fopen (newsfile, "r");
-    while (ischar (line = fgets (f)))
-      puts (line);
-    endwhile
-  else
-    if (strcmpi (package, "octave"))
-      error ("news: unable to locate NEWS file");
-    else
-      error ("news: unable to locate NEWS file of %s package", package);
-    endif
+    display_info_file ("news", package, "NEWS");
   endif
 
 endfunction
 
-## Remove from test statistics.  No real tests possible
-%!assert (1)
+
+%!error news (1, 2)
+%!error <news: PACKAGE must be a string> news (1)
+%!error <news: package .* is not installed> news ("__NOT_A_VALID_PKG_NAME__")
--- a/scripts/miscellaneous/orderfields.m
+++ b/scripts/miscellaneous/orderfields.m
@@ -37,7 +37,7 @@
 ##
 ## @example
 ## @group
-## s = struct("d", 4, "b", 2, "a", 1, "c", 3);
+## s = struct ("d", 4, "b", 2, "a", 1, "c", 3);
 ## t1 = orderfields (s)
 ##      @result{} t1 =
 ##         @{
@@ -48,7 +48,7 @@
 ##         @}
 ## @end group
 ## @group
-## t = struct("d", @{@}, "c", @{@}, "b", "a", @{@});
+## t = struct ("d", @{@}, "c", @{@}, "b", @{@}, "a", @{@});
 ## t2 = orderfields (s, t)
 ##      @result{} t2 =
 ##         @{
@@ -59,7 +59,7 @@
 ##         @}
 ## @end group
 ## @group
-## t3 = orderfields (s, [3, 2, 4, 1]);
+## t3 = orderfields (s, [3, 2, 4, 1])
 ##      @result{} t3 =
 ##         @{
 ##           a =  1
@@ -162,27 +162,28 @@
 
 endfunction
 
+
 %!shared a, b, c
 %! a = struct ("foo", {1, 2}, "bar", {3, 4});
 %! b = struct ("bar", 6, "foo", 5);
 %! c = struct ("bar", {7, 8}, "foo", 9);
 %!test
 %! a(2) = orderfields (b, a);
-%! assert (a(2).foo, 5)
-%! assert (a(2).bar, 6)
+%! assert (a(2).foo, 5);
+%! assert (a(2).bar, 6);
 %!test
 %! [a(2), p] = orderfields (b, [2 1]);
-%! assert (a(2).foo, 5)
-%! assert (a(2).bar, 6)
+%! assert (a(2).foo, 5);
+%! assert (a(2).bar, 6);
 %! assert (p, [2; 1]);
 %!test
 %! a(2) = orderfields (b, fieldnames (a));
-%! assert (a(2).foo, 5)
-%! assert (a(2).bar, 6)
+%! assert (a(2).foo, 5);
+%! assert (a(2).bar, 6);
 %!test
 %! a(1:2) = orderfields (c, fieldnames (a));
-%! assert (a(2).foo, 9)
-%! assert (a(2).bar, 8)
+%! assert (a(2).foo, 9);
+%! assert (a(2).bar, 8);
 
 %!test
 %! aa.x = {1, 2};
@@ -193,3 +194,4 @@
 %! aa(2) = orderfields (bb, aa);
 %! assert (aa(2).x, 8);
 %! assert (aa(2).y{1}, 6);
+
--- a/scripts/miscellaneous/paren.m
+++ b/scripts/miscellaneous/paren.m
@@ -22,6 +22,7 @@
 ## Array index or function argument delimeter.
 ## @end deftypefn
 
+
 ## Mark file as being tested.  No real test needed for a documentation .m file
 %!assert (1)
 
--- a/scripts/miscellaneous/parseparams.m
+++ b/scripts/miscellaneous/parseparams.m
@@ -40,7 +40,7 @@
 ## @end group
 ## @end example
 ##
-## The parseparams function may be used to separate 'regular'
+## The parseparams function may be used to separate "regular"
 ## arguments and additional arguments given as property/value pairs of
 ## the @var{varargin} cell array.
 ##
@@ -88,7 +88,7 @@
       if (! size_equal (pnames, values) || ! all (strs(i:2:end)))
         error_as_caller ("options must be given as name-value pairs");
       endif
-      idx = lookup (toupper(names), toupper(pnames), "m");
+      idx = lookup (toupper (names), toupper (pnames), "m");
       if (! all (idx))
         error_as_caller ("unrecognized option: %s", pnames{find (idx == 0, 1)});
       else
--- a/scripts/miscellaneous/perl.m
+++ b/scripts/miscellaneous/perl.m
@@ -17,13 +17,14 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {[@var{output}, @var{status}] =} perl (@var{scriptfile})
-## @deftypefnx {Function File} {[@var{output}, @var{status}] =} perl (@var{scriptfile}, @var{argument1}, @var{argument2}, @dots{})
-## Invoke Perl script @var{scriptfile} with possibly a list of
-## command line arguments.
-## Returns output in @var{output} and status
-## in @var{status}.
-## @seealso{system}
+## @deftypefn  {Function File} {@var{output} =} perl (@var{scriptfile})
+## @deftypefnx {Function File} {@var{output} =} perl (@var{scriptfile}, @var{argument1}, @var{argument2}, @dots{})
+## @deftypefnx {Function File} {[@var{output}, @var{status}] =} perl (@dots{})
+## Invoke Perl script @var{scriptfile}, possibly with a list of command line
+## arguments.  Return output in @var{output} and optional status in
+## @var{status}.  If @var{scriptfile} is not an absolute file name it is
+## is searched for in the current directory and then in the Octave loadpath.
+## @seealso{system, python}
 ## @end deftypefn
 
 function [output, status] = perl (scriptfile = "-e ''", varargin)
@@ -33,8 +34,13 @@
   ## initial value in the argument list of the function definition.
 
   if (ischar (scriptfile)
-      && ((nargin != 1 && iscellstr (varargin))
-          || (nargin == 1 && ! isempty (scriptfile))))
+      && (   (nargin == 1 && ! isempty (scriptfile))
+          || (nargin != 1 && iscellstr (varargin))))
+    if (! strcmp (scriptfile(1:2), "-e"))
+      ## Attempt to find file in loadpath.  No effect for absolute filenames.
+      scriptfile = file_in_loadpath (scriptfile);
+    endif
+
     [status, output] = system (cstrcat ("perl ", scriptfile,
                                         sprintf (" %s", varargin{:})));
   else
--- a/scripts/miscellaneous/private/__xzip__.m
+++ b/scripts/miscellaneous/private/__xzip__.m
@@ -62,13 +62,14 @@
     files = glob (files);
 
     ## Ignore any file with the compress extension
-    files(cellfun (@(x) length(x) > length(extension)
-      && strcmp (x((end - length(extension) + 1):end), extension),
-      files)) = [];
+    files(cellfun (@(x) (length (x) > length (extension)
+                         && strcmp (x((end - length (extension) + 1):end),
+                                    extension)),
+                   files)) = [];
 
     copyfile (files, outdir);
 
-    [d, f] = myfileparts(files);
+    [d, f] = myfileparts (files);
 
     cd (outdir);
 
@@ -87,12 +88,12 @@
             f, "uniformoutput", false);
       endif
     else
-      movefile (cellfun(@(x) sprintf ("%s.%s", x, extension), f,
+      movefile (cellfun (@(x) sprintf ("%s.%s", x, extension), f,
                         "uniformoutput", false), cwd);
       if (nargout > 0)
         ## FIXME this does not work when you try to compress directories
-        entries  = cellfun(@(x) sprintf ("%s.%s", x, extension),
-                           files, "uniformoutput", false);
+        entries  = cellfun (@(x) sprintf ("%s.%s", x, extension),
+                            files, "uniformoutput", false);
       endif
     endif
 
@@ -119,20 +120,20 @@
 ## functions directly.
 ##
 ## %!error <extension has to be a string with finite length>
-## %!  __xzip__("gzip", "", "gzip -r %s", "bla");
+## %!  __xzip__ ("gzip", "", "gzip -r %s", "bla");
 ## %!error <no files to move>
-## %!  __xzip__("gzip", ".gz", "gzip -r %s", tmpnam);
+## %!  __xzip__ ("gzip", ".gz", "gzip -r %s", tmpnam);
 ## %!error <command failed with exit status>
 ## %!  # test __xzip__ with invalid compression command
 ## %!  unwind_protect
 ## %!    filename = tmpnam;
 ## %!    dummy    = 1;
-## %!    save(filename, "dummy");
+## %!    save (filename, "dummy");
 ## %!    dirname  = tmpnam;
-## %!    mkdir(dirname);
-## %!    entry = __xzip__("gzip", ".gz", "xxxzipxxx -r %s 2>/dev/null",
+## %!    mkdir (dirname);
+## %!    entry = __xzip__ ("gzip", ".gz", "xxxzipxxx -r %s 2>/dev/null",
 ## %!                     filename, dirname);
 ## %!  unwind_protect_cleanup
-## %!    delete(filename);
-## %!    rmdir(dirname);
+## %!    delete (filename);
+## %!    rmdir (dirname);
 ## %!  end_unwind_protect
new file mode 100644
--- /dev/null
+++ b/scripts/miscellaneous/private/display_info_file.m
@@ -0,0 +1,59 @@
+## Copyright (C) 2013 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/>.
+
+## news() and citation() are very much alike. They both do the same thing, just
+## for different files. This function does all the work.
+
+function display_info_file (func, package, file)
+
+  if (nargin != 3)
+    print_usage ();
+  endif
+
+  if (! ischar (package))
+    error ("%s: PACKAGE must be a string", func);
+  endif
+
+  if (strcmpi (package, "octave"))
+    octetcdir = octave_config_info ("octetcdir");
+    filepath  = fullfile (octetcdir, file);
+  else
+    installed = pkg ("list");
+    names     = cellfun (@(x) x.name, installed, "UniformOutput", false);
+    pos       = strcmpi (names, package);
+    if (! any (pos))
+      error ("%s: package '%s' is not installed.", func, package);
+    endif
+    filepath = fullfile (installed{pos}.dir, "packinfo", file);
+  endif
+
+  if (! exist (filepath, "file"))
+    if (strcmpi (package, "octave"))
+      error ("%s: broken installation -- unable to locate %s file", func, file);
+    else
+      error ("%s: unable to locate %s file for package %s", func, file, package);
+    endif
+  endif
+
+  fid = fopen (filepath, "r");
+  while (ischar (line = fgets (fid)))
+    puts (line);
+  endwhile
+  fclose (fid);
+
+endfunction
--- a/scripts/miscellaneous/python.m
+++ b/scripts/miscellaneous/python.m
@@ -18,26 +18,28 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {[@var{output}, @var{status}] =} python (@var{scriptfile})
-## @deftypefnx {Function File} {[@var{output}, @var{status}] =} python (@var{scriptfile}, @var{argument1}, @var{argument2}, @dots{})
-## Invoke python script @var{scriptfile} with possibly a list of
-## command line arguments.
-## Returns output in @var{output} and status
-## in @var{status}.
-## @seealso{system}
+## @deftypefn  {Function File} {@var{output} =} python (@var{scriptfile})
+## @deftypefnx {Function File} {@var{output} =} python (@var{scriptfile}, @var{argument1}, @var{argument2}, @dots{})
+## @deftypefnx {Function File} {[@var{output}, @var{status}] =} python (@dots{})
+## Invoke Python script @var{scriptfile}, possibly with a list of command line
+## arguments.  Return output in @var{output} and optional status in
+## @var{status}.  If @var{scriptfile} is not an absolute file name it is
+## is searched for in the current directory and then in the Octave loadpath.
+## @seealso{system, perl}
 ## @end deftypefn
 
 ## Author: Carnë Draug <carandraug+dev@gmail.com>
 
 function [output, status] = python (scriptfile = "-c ''", varargin)
 
-  ## VARARGIN is intialized to {}(1x0) if no additional arguments are
-  ## supplied, so there is no need to check for it, or provide an
-  ## initial value in the argument list of the function definition.
+  if (ischar (scriptfile)
+      && (   (nargin == 1 && ! isempty (scriptfile))
+          || (nargin != 1 && iscellstr (varargin))))
+    if (! strcmp (scriptfile(1:2), "-c"))
+      ## Attempt to find file in loadpath.  No effect for absolute filenames.
+      scriptfile = file_in_loadpath (scriptfile);
+    endif
 
-  if (ischar (scriptfile)
-      && ((nargin != 1 && iscellstr (varargin))
-          || (nargin == 1 && ! isempty (scriptfile))))
     [status, output] = system (cstrcat ("python ", scriptfile,
                                         sprintf (" %s", varargin{:})));
   else
--- a/scripts/miscellaneous/recycle.m
+++ b/scripts/miscellaneous/recycle.m
@@ -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
 
@@ -51,16 +51,18 @@
         error ("recycle: invalid value of STATE = '%s'", state);
       endif
     else
-      error ("recycle: expecting STATE to be a character string");
+      error ("recycle: STATE must be a character string");
     endif
   endif
 
 endfunction
 
-%!error recycle ("on");
-%!error recycle ("on", "and I mean it");
-%!error recycle (1);
 
 %!test
 %! recycle ("off");
 %! assert (recycle ("off"), "off");
+
+%!error <recycling files is not implemented> recycle ("on")
+%!error recycle ("on", "and I mean it")
+%!error <STATE must be a character string> recycle (1)
+
--- a/scripts/miscellaneous/rmappdata.m
+++ b/scripts/miscellaneous/rmappdata.m
@@ -29,16 +29,31 @@
     error ("rmappdata: invalid input");
   endif
 
-  for nh = 1:numel(h)
-    appdata = get (h(nh), "__appdata__");
-    appdata = rmfield (appdata, varargin);
-    set (h(nh), "__appdata__", appdata);
+  for nh = 1:numel (h)
+    if (isprop (h(nh), "__appdata__"))
+      appdata = get (h(nh), "__appdata__");
+      for v = 1:numel(varargin)
+        if (isfield (appdata, varargin{v}))
+          appdata = rmfield (appdata, varargin{v});
+        else
+          error ("rmappdata: appdata '%s' is not present")
+        endif
+      endfor
+      set (h(nh), "__appdata__", appdata);
+    endif
   endfor
 
 endfunction
 
 %!test
-%! setappdata (0, "hello", "world")
-%! rmappdata (0, "hello")
-%! assert (isappdata (0, "hello"), false)
+%! setappdata (0, "hello", "world");
+%! rmappdata (0, "hello");
+%! assert (isappdata (0, "hello"), false);
 
+%!test
+%! setappdata (0, "data1", rand (3));
+%! setappdata (0, "data2", {"hello", "world"});
+%! rmappdata (0, "data1", "data2");
+%! assert (isappdata (0, "data1"), false);
+%! assert (isappdata (0, "data2"), false);
+
--- a/scripts/miscellaneous/semicolon.m
+++ b/scripts/miscellaneous/semicolon.m
@@ -22,6 +22,7 @@
 ## @seealso{comma}
 ## @end deftypefn
 
+
 ## Mark file as being tested.  No real test needed for a documentation .m file
 %!assert (1)
 
--- a/scripts/miscellaneous/setappdata.m
+++ b/scripts/miscellaneous/setappdata.m
@@ -30,12 +30,12 @@
     error ("setappdata: invalid input");
   endif
 
-  for nh = 1:numel(h)
+  for nh = 1:numel (h)
     if (! isfield (get (h(nh)), "__appdata__"))
       addproperty ("__appdata__", h(nh), "any", struct ());
     endif
     appdata = get (h(nh), "__appdata__");
-    for narg = 1:2:numel(varargin)
+    for narg = 1:2:numel (varargin)
       if (iscellstr (varargin{narg}))
         ## Handle cell arrays like set() does.
         set (h(nh), "__appdata__", appdata);
@@ -52,8 +52,9 @@
 
 endfunction
 
+
 %!test
-%! setappdata (0, "hello", "world")
-%! assert (isappdata (0, "hello"), true)
-%!assert (getappdata (0, "hello"), "world")
+%! setappdata (0, "hello", "world");
+%! assert (isappdata (0, "hello"), true);
+%! assert (getappdata (0, "hello"), "world");
 
--- a/scripts/miscellaneous/setfield.m
+++ b/scripts/miscellaneous/setfield.m
@@ -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}
@@ -60,12 +115,14 @@
   endif
 endfunction
 
+
 %!test
 %! x.a = "hello";
-%! x = setfield(x,"b","world");
-%! y = struct("a","hello","b","world");
-%! assert(x,y);
+%! x = setfield (x, "b", "world");
+%! y = struct ("a", "hello", "b", "world");
+%! assert (x,y);
 %!test
-%! oo(1,1).f0= 1;
-%! oo = setfield(oo,{1,2},"fd",{3},"b", 6);
-%! assert (oo(1,2).fd(3).b, 6)
+%! oo(1,1).f0 = 1;
+%! oo = setfield (oo,{1,2},"fd",{3},"b", 6);
+%! assert (oo(1,2).fd(3).b, 6);
+
--- a/scripts/miscellaneous/substruct.m
+++ b/scripts/miscellaneous/substruct.m
@@ -73,6 +73,7 @@
 
 endfunction
 
+
 %!test
 %! x(1,1).type = "()";
 %! x(1,2).type = "{}";
@@ -81,9 +82,11 @@
 %! x(1,2).subs = {":"};
 %! x(1,3).subs = "foo";
 %! y = substruct ("()", {1,2,3}, "{}", {":"}, ".", "foo");
-%! assert(x,y);
-%!error assert(substruct);
-%!error assert(substruct (1, 2, 3));
-%!error assert(substruct ("x", 1));
-%!error assert(substruct ("()", [1,2,3]));
-%!error assert(substruct (".", {1,2,3}));
+%! assert (x,y);
+
+%!error substruct ()
+%!error substruct (1, 2, 3)
+%!error substruct ("x", 1)
+%!error substruct ("()", [1,2,3])
+%!error substruct (".", {1,2,3})
+
--- a/scripts/miscellaneous/swapbytes.m
+++ b/scripts/miscellaneous/swapbytes.m
@@ -52,7 +52,7 @@
       error ("swapbytes: invalid class of object");
     endif
     y = reshape (typecast (reshape (typecast (x(:), "uint8"), nb, numel (x))
-                           ([nb : -1 : 1], :) (:), clx), size(x));
+                           ([nb : -1 : 1], :) (:), clx), size (x));
   endif
 
 endfunction
--- a/scripts/miscellaneous/symvar.m
+++ b/scripts/miscellaneous/symvar.m
@@ -29,5 +29,7 @@
   args = argnames (inline (s));
 endfunction
 
+
 ## This function is tested by the tests for argnames().
 %!assert (1)
+
--- a/scripts/miscellaneous/tar.m
+++ b/scripts/miscellaneous/tar.m
@@ -59,7 +59,7 @@
     if (output(end) == "\n")
       output(end) = [];
     endif
-    entries = strsplit (output, "\n");
+    entries = strsplit (output, "\n", false);
     entries = entries';
   endif
 
--- a/scripts/miscellaneous/unpack.m
+++ b/scripts/miscellaneous/unpack.m
@@ -39,7 +39,7 @@
   endif
 
   if (! ischar (file) && ! iscellstr (file))
-    error ("unpack: invalid input file class, %s", class(file));
+    error ("unpack: invalid input file class, %s", class (file));
   endif
 
   ## character arrays of more than one string must be treated as cell strings
@@ -194,7 +194,7 @@
     if (output(length (output)) == "\n")
       output(length (output)) = [];
     endif
-    files = parser (strsplit (output, "\n"))';
+    files = parser (strsplit (output, "\n", false))';
 
     ## Move files if necessary
     if (needmove)
@@ -224,7 +224,7 @@
   ## Skip first line which is Archive header
   output(1) = [];
   for i = 1:length (output)
-    files{i} = output{i}(14:length(output{i}));
+    files{i} = output{i}(14:length (output{i}));
   endfor
 endfunction
 
@@ -246,7 +246,7 @@
                "Unable to parse line (gzip missing colon):\n%s", output{i});
     else
       midcolon = colons(ceil (length (colons)/2));
-      thisstr = output{i}(midcolon+2:length(output{i}));
+      thisstr = output{i}(midcolon+2:length (output{i}));
       idx = index (thisstr, "with") + 5;
       if (isempty (idx))
         warning ("unpack:parsing",
--- a/scripts/miscellaneous/ver.m
+++ b/scripts/miscellaneous/ver.m
@@ -17,13 +17,18 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} ver ()
+## @deftypefn  {Function File} {} ver ()
+## @deftypefnx {Function File} {v =} ver ()
+## @deftypefnx {Function File} {v =} ver ("Octave")
+## @deftypefnx {Function File} {v =} ver (@var{package})
+## 
 ## Display a header containing the current Octave version number, license
-## string and operating system, followed by the installed package names,
+## string, and operating system followed by a list of installed packages,
 ## versions, and installation directories.
 ##
-## @deftypefnx {Function File} {v =} ver ()
-## Return a vector of structures, respecting Octave and each installed package.
+## @code{v = ver ()}
+##
+## Return a vector of structures describing Octave and each installed package.
 ## The structure includes the following fields.
 ##
 ## @table @code
@@ -37,13 +42,15 @@
 ## Revision of the package.
 ##
 ## @item Date
-## Date respecting the version/revision.
+## Date of the version/revision.
 ## @end table
 ##
-## @deftypefnx {Function File} {v =} ver ("Octave")
+## @code{v = ver ("Octave")}
+##
 ## Return version information for Octave only.
 ##
-## @deftypefnx {Function File} {v =} ver (@var{package})
+## @code{v = ver (@var{package})}
+##
 ## Return version information for @var{package}.
 ##
 ## @seealso{version, octave_config_info}
@@ -94,7 +101,7 @@
   else
     if (! isempty (package))
       n = [];
-      for r = 1:numel(ret)
+      for r = 1:numel (ret)
         if (strcmpi (ret(r).Name, package))
           n = r;
           break;
@@ -107,17 +114,18 @@
 
 endfunction
 
+
 %!test
 %! result = ver;
-%! assert (result(1).Name, "Octave")
-%! assert (result(1).Version, version)
+%! assert (result(1).Name, "Octave");
+%! assert (result(1).Version, version);
 %! result = ver ("octave");
-%! assert (result(1).Name, "Octave")
-%! assert (result(1).Version, version)
+%! assert (result(1).Name, "Octave");
+%! assert (result(1).Version, version);
 
 %!test
 %! lst = pkg ("list");
-%! for n=1:numel(lst)
+%! for n = 1:numel (lst)
 %!   expected = lst{n}.name;
 %!   result = ver (expected);
 %!   assert (result.Name, expected);
--- a/scripts/miscellaneous/version.m
+++ b/scripts/miscellaneous/version.m
@@ -37,7 +37,9 @@
 
 endfunction
 
-%!assert(ischar (version ()) && strcmp (version (), OCTAVE_VERSION));
+
+%!assert (ischar (version ()))
+%!assert (version (), OCTAVE_VERSION)
 
 %!warning version (1);
 
--- a/scripts/miscellaneous/warning_ids.m
+++ b/scripts/miscellaneous/warning_ids.m
@@ -18,6 +18,7 @@
 
 ## -*- texinfo -*-
 ## @cindex warning ids
+##
 ## @table @code
 ## @item Octave:abbreviated-property-match
 ## By default, the @code{Octave:abbreviated-property-match} warning is enabled.
@@ -130,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.
@@ -169,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.
@@ -239,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.
@@ -254,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
@@ -320,5 +338,7 @@
   help ("warning_ids");
 endfunction
 
+
 ## Remove from test statistics.  No real tests possible
 %!assert (1)
+
--- a/scripts/miscellaneous/what.m
+++ b/scripts/miscellaneous/what.m
@@ -32,7 +32,7 @@
     d = pwd ();
   elseif (isempty (strfind (d, filesep ())))
     ## Find the appropriate directory on the path.
-    p = strtrim (strsplit (path (), pathsep()));
+    p = strtrim (strsplit (path (), pathsep (), false));
     d = p{find (cellfun (@(x) ! isempty (strfind (x, d)), p))(end)};
   else
     [status, msg, msgid] = fileattrib (d);
@@ -91,7 +91,7 @@
     printf ("%s %s:\n\n", msg, p);
 
     maxlen = max (cellfun ("length", f));
-    ncols = max (1, floor (terminal_size()(2) / (maxlen + 3)));
+    ncols = max (1, floor (terminal_size ()(2) / (maxlen + 3)));
     fmt = "";
     for i = 1: ncols
       fmt = sprintf ("%s   %%-%ds", fmt, maxlen);
--- a/scripts/miscellaneous/xor.m
+++ b/scripts/miscellaneous/xor.m
@@ -60,12 +60,12 @@
 
 endfunction
 
-%!assert((xor ([1, 1, 0, 0], [0, 1, 0, 1]) == [1, 0, 0, 1]
-%! && xor ([i, i, 0, 0], [1, 0, 1, 0]) == [0, 1, 1, 0]));
 
-%!assert(all (all (xor (eye (2), fliplr (eye (2))) == ones (2))));
+%!assert (xor ([1, 1, 0, 0], [0, 1, 0, 1]), logical ([1, 0, 0, 1]))
+%!assert (xor ([i, i, 0, 0], [1, 0, 1, 0]), logical ([0, 1, 1, 0]))
 
-%!error xor ();
+%!assert (xor (eye (2), fliplr (eye (2))), logical (ones (2)))
 
-%!error xor (1, 2, 3);
+%!error xor ()
+%!error xor (1, 2, 3)
 
--- a/scripts/miscellaneous/zip.m
+++ b/scripts/miscellaneous/zip.m
@@ -62,7 +62,7 @@
     if (entries(end) == "\n")
       entries(end) = [];
     endif
-    entries = strsplit (entries, "\n");
+    entries = strsplit (entries, "\n", false);
   endif
 
 endfunction
--- a/scripts/optimization/fminbnd.m
+++ b/scripts/optimization/fminbnd.m
@@ -20,14 +20,13 @@
 
 ## -*- 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: @code{"FunValCheck"}, @code{"OutputFcn"},
-## @code{"TolX"}, @code{"MaxIter"}, @code{"MaxFunEvals"}.
-## For description of these options, see @ref{doc-optimset,,optimset}.
+## 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:
+## "FunValCheck", "OutputFcn", "TolX", "MaxIter", "MaxFunEvals".  For a
+## description of these options, see @ref{doc-optimset,,optimset}.
 ##
 ## On exit, the function returns @var{x}, the approximate minimum point
 ## and @var{fval}, the function value thereof.
@@ -43,7 +42,13 @@
 ## @item -1
 ## The algorithm has been terminated from user output function.
 ## @end itemize
-## @seealso{optimset, fzero, fminunc}
+##
+## Notes: The search for a minimum is restricted to be in the interval
+## bound by @var{a} and @var{b}.  If you only have an initial point
+## to begin searching from you will need to use an unconstrained
+## minimization algorithm such as @code{fminunc} or @code{fminsearch}.
+## @code{fminbnd} internally uses a Golden Section search strategy.
+## @seealso{fzero, fminunc, fminsearch, optimset}
 ## @end deftypefn
 
 ## This is patterned after opt/fmin.f from Netlib, which in turn is taken from
@@ -56,8 +61,8 @@
 
   ## Get default options if requested.
   if (nargin == 1 && ischar (fun) && strcmp (fun, 'defaults'))
-    x = optimset ("MaxIter", Inf, "MaxFunEvals", Inf, "TolX", 1e-8, \
-    "OutputFcn", [], "FunValCheck", "off");
+    x = optimset ("MaxIter", Inf, "MaxFunEvals", Inf, "TolX", 1e-8,
+                  "OutputFcn", [], "FunValCheck", "off");
     return;
   endif
 
@@ -69,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);
@@ -88,7 +92,7 @@
   nfev = 0;
   sqrteps = eps (class (xmin + xmax));
 
-  c = 0.5*(3-sqrt(5));
+  c = 0.5*(3 - sqrt (5));
   a = xmin; b = xmax;
   v = a + c*(b-a);
   w = x = v;
@@ -96,11 +100,16 @@
   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)...
-    ## sometimes. Sometimes not, it depends on the function. This is the strategy
-    ## from the Netlib code. Something yet smarter would be good.
+    ## FIXME: the golden section search can actually get closer than sqrt(eps)
+    ## sometimes.  Sometimes not, it depends on the function.  This is the
+    ## strategy from the Netlib code.  Something yet smarter would be good.
     tol = 2 * sqrteps * abs (x) + tolx / 3;
     if (abs (x - xm) <= (2*tol - 0.5*(b-a)))
       info = 1;
@@ -110,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;
@@ -136,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)
@@ -186,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];
@@ -205,9 +245,41 @@
   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);
-%!assert (fminbnd (@cos, pi/2, 3*pi/2, opt0), pi, 10*sqrt(eps))
-%!assert (fminbnd (@(x) (x - 1e-3)^4, -1, 1, opt0), 1e-3, 10e-3*sqrt(eps))
-%!assert (fminbnd (@(x) abs(x-1e7), 0, 1e10, opt0), 1e7, 10e7*sqrt(eps))
-%!assert (fminbnd (@(x) x^2 + sin(2*pi*x), 0.4, 1, opt0), fzero (@(x) 2*x + 2*pi*cos(2*pi*x), [0.4, 1], opt0), sqrt(eps))
+%!assert (fminbnd (@cos, pi/2, 3*pi/2, opt0), pi, 10*sqrt (eps))
+%!assert (fminbnd (@(x) (x - 1e-3)^4, -1, 1, opt0), 1e-3, 10e-3*sqrt (eps))
+%!assert (fminbnd (@(x) abs (x-1e7), 0, 1e10, opt0), 1e7, 10e7*sqrt (eps))
+%!assert (fminbnd (@(x) x^2 + sin (2*pi*x), 0.4, 1, opt0), fzero (@(x) 2*x + 2*pi*cos (2*pi*x), [0.4, 1], opt0), sqrt (eps))
+
new file mode 100644
--- /dev/null
+++ b/scripts/optimization/fminsearch.m
@@ -0,0 +1,352 @@
+## Copyright (C) 2003,2012 Andy Adler
+## Copyright (C) 2002 N.J.Higham
+##
+## 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{x} =} fminsearch (@var{fun}, @var{x0})
+## @deftypefnx {Function File} {@var{x} =} fminsearch (@var{fun}, @var{x0}, @var{options})
+## @deftypefnx {Function File} {[@var{x}, @var{fval}] =} fminsearch (@dots{})
+##
+## Find a value of @var{x} which minimizes the function @var{fun}.
+## The search begins at the point @var{x0} and iterates using the
+## Nelder & Mead Simplex algorithm (a derivative-free method).  This algorithm
+## is better-suited to functions which have discontinuities or for which
+## a gradient-based search such as @code{fminunc} fails.
+##
+## Options for the search are provided in the parameter @var{options} using 
+## the function @code{optimset}.  Currently, @code{fminsearch} accepts the
+## options: "TolX", "MaxFunEvals", "MaxIter", "Display".  For a description of
+## these options, see @code{optimset}.
+##
+## On exit, the function returns @var{x}, the minimum point,
+## and @var{fval}, the function value thereof.
+##
+## Example usages:
+##
+## @example
+## @group
+## fminsearch (@@(x) (x(1)-5).^2+(x(2)-8).^4, [0;0])
+##
+## fminsearch (inline ("(x(1)-5).^2+(x(2)-8).^4", "x"), [0;0])
+## @end group
+## @end example
+## @seealso{fminbnd, fminunc, optimset}
+## @end deftypefn
+
+## PKG_ADD: ## Discard result to avoid polluting workspace with ans at startup.
+## PKG_ADD: [~] = __all_opts__ ("fminsearch");
+
+## FIXME: Add support for "exitflag" output variable
+## FIXME: Add support for "output" output variable
+## FIXME: For Display option, add 'final' and 'notify' options.  Not too hard.
+## FIXME: Add support for OutputFcn.  See fminunc for a template
+## FIXME: Add support for exiting based on TolFun.  See fminunc for an idea.
+
+function [x, fval] = fminsearch (fun, x0, options = struct ())
+
+  ## Get default options if requested.
+  if (nargin == 1 && ischar (fun) && strcmp (fun, "defaults"))
+    x = optimset ("Display", "notify", "FunValCheck", "off",
+                  "MaxFunEvals", 400, "MaxIter", 400,
+                  "OutputFcn", [],
+                  "TolFun", 1e-7, "TolX", 1e-4);
+    return;
+  endif
+
+  if (nargin < 2 || nargin > 3)
+    print_usage ();
+  endif
+
+  x = nmsmax (fun, x0, options);
+
+  if (isargout (2))
+    fval = feval (fun, x);
+  endif
+
+endfunction
+
+##NMSMAX  Nelder-Mead simplex method for direct search optimization.
+##        [x, fmax, nf] = NMSMAX(FUN, x0, STOPIT, SAVIT) attempts to
+##        maximize the function FUN, using the starting vector x0.
+##        The Nelder-Mead direct search method is used.
+##        Output arguments:
+##               x    = vector yielding largest function value found,
+##               fmax = function value at x,
+##               nf   = number of function evaluations.
+##        The iteration is terminated when either
+##               - the relative size of the simplex is <= STOPIT(1)
+##                 (default 1e-3),
+##               - STOPIT(2) function evaluations have been performed
+##                 (default inf, i.e., no limit), or
+##               - a function value equals or exceeds STOPIT(3)
+##                 (default inf, i.e., no test on function values).
+##        The form of the initial simplex is determined by STOPIT(4):
+##           STOPIT(4) = 0: regular simplex (sides of equal length, the default)
+##           STOPIT(4) = 1: right-angled simplex.
+##        Progress of the iteration is not shown if STOPIT(5) = 0 (default 1).
+##           STOPIT(6) indicates the direction (ie. minimization or
+##                   maximization.) Default is 1, maximization.
+##                   set STOPIT(6)=-1 for minimization
+##        If a non-empty fourth parameter string SAVIT is present, then
+##        'SAVE SAVIT x fmax nf' is executed after each inner iteration.
+##        NB: x0 can be a matrix.  In the output argument, in SAVIT saves,
+##            and in function calls, x has the same shape as x0.
+##        NMSMAX(fun, x0, STOPIT, SAVIT, P1, P2,...) allows additional
+##        arguments to be passed to fun, via feval(fun,x,P1,P2,...).
+## References:
+## N. J. Higham, Optimization by direct search in matrix computations,
+##    SIAM J. Matrix Anal. Appl, 14(2): 317-333, 1993.
+## C. T. Kelley, Iterative Methods for Optimization, Society for Industrial
+##    and Applied Mathematics, Philadelphia, PA, 1999.
+
+## From Matrix Toolbox
+## Copyright (C) 2002 N.J.Higham
+## www.maths.man.ac.uk/~higham/mctoolbox
+##
+## Modifications for Octave by A.Adler 2003
+
+function [stopit, savit, dirn, trace, tol, maxiter] = parse_options (options, x );
+
+  ## Tolerance for cgce test based on relative size of simplex.
+  stopit(1) = tol = optimget (options, "TolX", 1e-4);
+
+  ## Max no. of f-evaluations.
+  stopit(2) = optimget (options, "MaxFunEvals", length (x) * 200);
+
+  ## Max no. of iterations
+  maxiter = optimget (options, "MaxIter", length (x) * 200);
+
+  ## Default target for f-values.
+  stopit(3) = Inf;  # FIXME: expose this parameter to the outside
+
+  ## Default initial simplex.
+  stopit(4) = 0;    # FIXME: expose this parameter to the outside
+
+  ## Default: show progress.
+  display = optimget (options, "Display", "notify");
+  if (strcmp (display, "iter"))
+    stopit(5) = 1;
+  else
+    stopit(5) = 0;
+  endif
+  trace = stopit(5);
+
+  ## Use function to minimize, not maximize
+  stopit(6) = dirn = -1;
+
+  ## File name for snapshots.
+  savit = [];  # FIXME: expose this parameter to the outside
+
+endfunction
+
+function [x, fmax, nf] = nmsmax (fun, x, options, savit, varargin)
+
+  [stopit, savit, dirn, trace, tol, maxiter] = parse_options (options, x);
+
+  if (strcmpi (optimget (options, "FunValCheck", "off"), "on"))
+    ## Replace fcn with a guarded version.
+    fun = @(x) guarded_eval (fun, x);
+  endif
+
+  x0 = x(:);  # Work with column vector internally.
+  n = length (x0);
+
+  V = [zeros(n,1) eye(n)];
+  f = zeros (n+1,1);
+  V(:,1) = x0;
+  f(1) = dirn * feval (fun,x,varargin{:});
+  fmax_old = f(1);
+
+  if (trace)
+    fprintf ("f(x0) = %9.4e\n", f(1));
+  endif
+
+  k = 0; m = 0;
+
+  ## Set up initial simplex.
+  scale = max (norm (x0,Inf), 1);
+  if (stopit(4) == 0)
+    ## Regular simplex - all edges have same length.
+    ## Generated from construction given in reference [18, pp. 80-81] of [1].
+    alpha = scale / (n*sqrt (2)) * [sqrt(n+1)-1+n, sqrt(n+1)-1];
+    V(:,2:n+1) = (x0 + alpha(2)*ones (n,1)) * ones (1,n);
+    for j = 2:n+1
+      V(j-1,j) = x0(j-1) + alpha(1);
+      x(:) = V(:,j);
+      f(j) = dirn * feval (fun,x,varargin{:});
+    endfor
+  else
+    ## Right-angled simplex based on co-ordinate axes.
+    alpha = scale * ones(n+1,1);
+    for j=2:n+1
+      V(:,j) = x0 + alpha(j)*V(:,j);
+      x(:) = V(:,j);
+      f(j) = dirn * feval (fun,x,varargin{:});
+    endfor
+  endif
+  nf = n+1;
+  how = "initial  ";
+
+  [~,j] = sort (f);
+  j = j(n+1:-1:1);
+  f = f(j);
+  V = V(:,j);
+
+  alpha = 1;  beta = 1/2;  gamma = 2;
+
+  while (1)   # Outer (and only) loop.
+    k++;
+
+    if (k > maxiter)
+      msg = "Exceeded maximum iterations...quitting\n";
+      break;
+    endif
+
+    fmax = f(1);
+    if (fmax > fmax_old)
+      if (! isempty (savit))
+        x(:) = V(:,1);
+        eval (["save " savit " x fmax nf"]);
+      endif
+    endif
+    if (trace)
+      fprintf ("Iter. %2.0f,", k);
+      fprintf (["  how = " how "  "]);
+      fprintf ("nf = %3.0f,  f = %9.4e  (%2.1f%%)\n", nf, fmax, ...
+               100*(fmax-fmax_old)/(abs(fmax_old)+eps));
+    endif
+    fmax_old = fmax;
+
+    ## Three stopping tests from MDSMAX.M
+
+    ## Stopping Test 1 - f reached target value?
+    if (fmax >= stopit(3))
+      msg = "Exceeded target...quitting\n";
+      break;
+    endif
+
+    ## Stopping Test 2 - too many f-evals?
+    if (nf >= stopit(2))
+      msg = "Max no. of function evaluations exceeded...quitting\n";
+      break;
+    endif
+
+    ## Stopping Test 3 - converged?   This is test (4.3) in [1].
+    v1 = V(:,1);
+    size_simplex = norm (V(:,2:n+1)-v1(:,ones (1,n)),1) / max (1, norm (v1,1));
+    if (size_simplex <= tol)
+      msg = sprintf ("Simplex size %9.4e <= %9.4e...quitting\n", ...
+                      size_simplex, tol);
+      break;
+    endif
+
+    ##  One step of the Nelder-Mead simplex algorithm
+    ##  NJH: Altered function calls and changed CNT to NF.
+    ##       Changed each 'fr < f(1)' type test to '>' for maximization
+    ##       and re-ordered function values after sort.
+
+    vbar = (sum (V(:,1:n)')/n)';  # Mean value
+    vr = (1 + alpha)*vbar - alpha*V(:,n+1);
+    x(:) = vr;
+    fr = dirn * feval (fun,x,varargin{:});
+    nf = nf + 1;
+    vk = vr;  fk = fr; how = "reflect, ";
+    if (fr > f(n))
+      if (fr > f(1))
+        ve = gamma*vr + (1-gamma)*vbar;
+        x(:) = ve;
+        fe = dirn * feval (fun,x,varargin{:});
+        nf = nf + 1;
+        if (fe > f(1))
+          vk = ve;
+          fk = fe;
+          how = "expand,  ";
+        endif
+      endif
+    else
+      vt = V(:,n+1);
+      ft = f(n+1);
+      if (fr > ft)
+        vt = vr;
+        ft = fr;
+      endif
+      vc = beta*vt + (1-beta)*vbar;
+      x(:) = vc;
+      fc = dirn * feval (fun,x,varargin{:});
+      nf = nf + 1;
+      if (fc > f(n))
+        vk = vc; fk = fc;
+        how = "contract,";
+      else
+        for j = 2:n
+          V(:,j) = (V(:,1) + V(:,j))/2;
+          x(:) = V(:,j);
+          f(j) = dirn * feval (fun,x,varargin{:});
+        endfor
+        nf = nf + n-1;
+        vk = (V(:,1) + V(:,n+1))/2;
+        x(:) = vk;
+        fk = dirn * feval (fun,x,varargin{:});
+        nf = nf + 1;
+        how = "shrink,  ";
+      endif
+    endif
+    V(:,n+1) = vk;
+    f(n+1) = fk;
+    [~,j] = sort(f);
+    j = j(n+1:-1:1);
+    f = f(j);
+    V = V(:,j);
+
+  endwhile   # End of outer (and only) loop.
+
+  ## Finished.
+  if (trace)
+    fprintf (msg);
+  endif
+  x(:) = V(:,1);
+
+endfunction
+
+## A helper function that evaluates a function and checks for bad results.
+function y = guarded_eval (fun, x)
+
+  y = fun (x);
+
+  if (! (isreal (f)))
+    error ("fminsearch:notreal", "fminsearch: non-real value encountered");
+  elseif (any (isnan (f(:))))
+    error ("fminsearch:isnan", "fminsearch: NaN value encountered");
+  elseif (any (isinf (f(:))))
+    error ("fminsearch:isinf", "fminsearch: Inf value encountered");
+  endif
+
+endfunction
+
+
+%!demo
+%! fcn = @(x) (x(1)-5).^2 + (x(2)-8).^4
+%! x0 = [0;0];
+%! [xmin, fval] = fminsearch (fcn, x0)
+
+%!assert (fminsearch (@sin, 3, optimset ("MaxIter", 3)), 4.8750, 1e-4)
+%!assert (fminsearch (@sin, 3, optimset ("MaxIter", 30)), 4.7124, 1e-4)
+%!shared c
+%! c = 1.5;
+%!assert (fminsearch (@(x) x(1).^2+c*x(2).^2,[1;1]), [0;0], 1e-4)
+
--- a/scripts/optimization/fminunc.m
+++ b/scripts/optimization/fminunc.m
@@ -24,6 +24,7 @@
 ## @deftypefnx {Function File} {[@var{x}, @var{fvec}, @var{info}, @var{output}, @var{grad}, @var{hess}] =} fminunc (@var{fcn}, @dots{})
 ## Solve an unconstrained optimization problem defined by the function
 ## @var{fcn}.
+##
 ## @var{fcn} should accepts a vector (array) defining the unknown variables,
 ## and return the objective function value, optionally with gradient.
 ## In other words, this function attempts to determine a vector @var{x} such
@@ -72,9 +73,12 @@
 ## (@var{output}), the output gradient (@var{grad}) and approximate Hessian
 ## (@var{hess}).
 ##
-## Note: If you only have a single nonlinear equation of one variable, using
-## @code{fminbnd} is usually a much better idea.
-## @seealso{fminbnd, optimset}
+## Notes: If you only have a single nonlinear equation of one variable then
+## using @code{fminbnd} is usually a much better idea.  The algorithm used is a
+## gradient search which depends on the objective function being differentiable.
+## If the function has discontinuities it may be better to use a derivative-free
+## algorithm such as @code{fminsearch}.
+## @seealso{fminbnd, fminsearch, optimset}
 ## @end deftypefn
 
 ## PKG_ADD: ## Discard result to avoid polluting workspace with ans at startup.
@@ -84,11 +88,11 @@
 
   ## Get default options if requested.
   if (nargin == 1 && ischar (fcn) && strcmp (fcn, 'defaults'))
-    x = optimset ("MaxIter", 400, "MaxFunEvals", Inf, \
-    "GradObj", "off", "TolX", 1e-7, "TolFun", 1e-7,
-    "OutputFcn", [], "FunValCheck", "off",
-    "FinDiffType", "central",
-    "TypicalX", [], "AutoScaling", "off");
+    x = optimset ("MaxIter", 400, "MaxFunEvals", Inf,
+                  "GradObj", "off", "TolX", 1e-7, "TolFun", 1e-7,
+                  "OutputFcn", [], "FunValCheck", "off",
+                  "FinDiffType", "central",
+                  "TypicalX", [], "AutoScaling", "off");
     return;
   endif
 
@@ -260,7 +264,7 @@
       endif
 
       ## Update delta.
-      if (ratio < min(max(0.1, 0.8*lastratio), 0.9))
+      if (ratio < min (max (0.1, 0.8*lastratio), 0.9))
         delta *= decfac;
         decfac ^= 1.4142;
         if (delta <= 1e1*macheps*xn)
@@ -354,9 +358,12 @@
     error ("fminunc:notreal", "fminunc: non-real value encountered");
   elseif (any (isnan (fx(:))))
     error ("fminunc:isnan", "fminunc: NaN value encountered");
+  elseif (any (isinf (fx(:))))
+    error ("fminunc:isinf", "fminunc: Inf value encountered");
   endif
 endfunction
 
+
 %!function f = __rosenb (x)
 %!  n = length (x);
 %!  f = sumsq (1 - x(1:n-1)) + 100 * sumsq (x(2:n) - x(1:n-1).^2);
@@ -373,6 +380,12 @@
 %! assert (info > 0);
 %! assert (x, ones (1, 4), tol);
 %! assert (fval, 0, tol);
+%% Test FunValCheck works correctly
+%!assert (fminunc (@(x) x^2, 1, optimset ("FunValCheck", "on")), 0, eps)
+%!error <non-real value> fminunc (@(x) x + i, 1, optimset ("FunValCheck", "on"))
+%!error <NaN value> fminunc (@(x) x + NaN, 1, optimset ("FunValCheck", "on"))
+%!error <Inf value> fminunc (@(x) x + Inf, 1, optimset ("FunValCheck", "on"))
+
 
 ## Solve the double dogleg trust-region minimization problem:
 ## Minimize 1/2*norm(r*x)^2  subject to the constraint norm(d.*x) <= delta,
--- a/scripts/optimization/fsolve.m
+++ b/scripts/optimization/fsolve.m
@@ -96,7 +96,7 @@
 ## employ OutputFcn: After a vector is evaluated for residuals, if OutputFcn is
 ## called with that vector, then the intermediate results should be saved for
 ## future Jacobian evaluation, and should be kept until a Jacobian evaluation
-## is requested or until outputfcn is called with a different vector, in which
+## is requested or until OutputFcn is called with a different vector, in which
 ## case they should be dropped in favor of this most recent vector.  A short
 ## example how this can be achieved follows:
 ##
@@ -327,7 +327,7 @@
       endif
 
       ## Update delta.
-      if (ratio < min(max(0.1, 0.8*lastratio), 0.9))
+      if (ratio < min (max (0.1, 0.8*lastratio), 0.9))
         nsuc = 0;
         nfail ++;
         delta *= decfac;
@@ -446,10 +446,12 @@
 
   if (! complexeqn && ! (isreal (fx) && isreal (jx)))
     error ("fsolve:notreal", "fsolve: non-real value encountered");
-  elseif (complexeqn && ! (isnumeric (fx) && isnumeric(jx)))
+  elseif (complexeqn && ! (isnumeric (fx) && isnumeric (jx)))
     error ("fsolve:notnum", "fsolve: non-numeric value encountered");
   elseif (any (isnan (fx(:))))
     error ("fsolve:isnan", "fsolve: NaN value encountered");
+  elseif (any (isinf (fx(:))))
+    error ("fsolve:isinf", "fsolve: Inf value encountered");
   endif
 endfunction
 
@@ -465,14 +467,14 @@
 %!  y = p(2);
 %!  z = p(3);
 %!  retval = zeros (3, 1);
-%!  retval(1) = sin(x) + y**2 + log(z) - 7;
-%!  retval(2) = 3*x + 2**y -z**3 + 1;
+%!  retval(1) = sin (x) + y^2 + log (z) - 7;
+%!  retval(2) = 3*x + 2^y -z^3 + 1;
 %!  retval(3) = x + y + z - 5;
 %!endfunction
 %!test
 %! x_opt = [ 0.599054;
-%! 2.395931;
-%! 2.005014 ];
+%!           2.395931;
+%!           2.005014 ];
 %! tol = 1.0e-5;
 %! [x, fval, info] = fsolve (@__f, [ 0.5; 2.0; 2.5 ]);
 %! assert (info > 0);
@@ -491,7 +493,8 @@
 %!  retval(4) = x^2 + 2*y^3 + z - w - 4;
 %!endfunction
 %!test
-%! x_opt = [ -0.767297326653401, 0.590671081117440, 1.47190018629642, -1.52719341133957 ];
+%! x_opt = [ -0.767297326653401, 0.590671081117440, ...
+%!            1.47190018629642, -1.52719341133957 ];
 %! tol = 1.0e-5;
 %! [x, fval, info] = fsolve (@__f, [-1, 1, 2, -1]);
 %! assert (info > 0);
@@ -503,15 +506,15 @@
 %!  y = p(2);
 %!  z = p(3);
 %!  retval = zeros (3, 1);
-%!  retval(1) = sin(x) + y**2 + log(z) - 7;
-%!  retval(2) = 3*x + 2**y -z**3 + 1;
+%!  retval(1) = sin (x) + y^2 + log (z) - 7;
+%!  retval(2) = 3*x + 2^y -z^3 + 1;
 %!  retval(3) = x + y + z - 5;
-%!  retval(4) = x*x + y - z*log(z) - 1.36;
+%!  retval(4) = x*x + y - z*log (z) - 1.36;
 %!endfunction
 %!test
 %! x_opt = [ 0.599054;
-%! 2.395931;
-%! 2.005014 ];
+%!           2.395931;
+%!           2.005014 ];
 %! tol = 1.0e-5;
 %! [x, fval, info] = fsolve (@__f, [ 0.5; 2.0; 2.5 ]);
 %! assert (info > 0);
@@ -523,14 +526,14 @@
 %!  y = p(2);
 %!  z = p(3);
 %!  retval = zeros (3, 1);
-%!  retval(1) = sin(x) + y**2 + log(z) - 7;
-%!  retval(2) = 3*x + 2**y -z**3 + 1;
+%!  retval(1) = sin (x) + y^2 + log (z) - 7;
+%!  retval(2) = 3*x + 2^y -z^3 + 1;
 %!  retval(3) = x + y + z - 5;
 %!endfunction
 %!test
 %! x_opt = [ 0.599054;
-%! 2.395931;
-%! 2.005014 ];
+%!           2.395931;
+%!           2.005014 ];
 %! tol = 1.0e-5;
 %! opt = optimset ("Updating", "qrp");
 %! [x, fval, info] = fsolve (@__f, [ 0.5; 2.0; 2.5 ], opt);
@@ -552,7 +555,6 @@
 %! assert (norm (c - c_opt, Inf) < tol);
 %! assert (norm (fval) < norm (noise));
 
-
 %!function y = cfun (x)
 %!  y(1) = (1+i)*x(1)^2 - (1-i)*x(2) - 2;
 %!  y(2) = sqrt (x(1)*x(2)) - (1-2i)*x(3) + (3-4i);
--- a/scripts/optimization/fzero.m
+++ b/scripts/optimization/fzero.m
@@ -100,8 +100,8 @@
 
   ## Get default options if requested.
   if (nargin == 1 && ischar (fun) && strcmp (fun, 'defaults'))
-    x = optimset ("MaxIter", Inf, "MaxFunEvals", Inf, "TolX", 1e-8, \
-    "OutputFcn", [], "FunValCheck", "off");
+    x = optimset ("MaxIter", Inf, "MaxFunEvals", Inf, "TolX", 1e-8,
+                  "OutputFcn", [], "FunValCheck", "off");
     return;
   endif
 
@@ -359,5 +359,6 @@
 
 %!shared opt0
 %! opt0 = optimset ("tolx", 0);
-%!assert(fzero(@cos, [0, 3], opt0), pi/2, 10*eps)
-%!assert(fzero(@(x) x^(1/3) - 1e-8, [0,1], opt0), 1e-24, 1e-22*eps)
+%!assert (fzero (@cos, [0, 3], opt0), pi/2, 10*eps)
+%!assert (fzero (@(x) x^(1/3) - 1e-8, [0,1], opt0), 1e-24, 1e-22*eps)
+
--- a/scripts/optimization/glpk.m
+++ b/scripts/optimization/glpk.m
@@ -106,6 +106,7 @@
 ## An array of characters containing the sense of each constraint in the
 ## constraint matrix.  Each element of the array may be one of the
 ## following values
+##
 ## @table @asis
 ## @item "F"
 ## A free (unbounded) constraint (the constraint is ignored).
@@ -126,6 +127,7 @@
 ##
 ## @item vartype
 ## A column array containing the types of the variables.
+##
 ## @table @asis
 ## @item "C"
 ## A continuous variable.
@@ -149,6 +151,7 @@
 ## @table @code
 ## @item msglev (@w{@code{LPX_K_MSGLEV}}, default: 1)
 ## Level of messages output by solver routines:
+##
 ## @table @asis
 ## @item 0
 ## No output.
@@ -165,6 +168,7 @@
 ##
 ## @item scale (@w{@code{LPX_K_SCALE}}, default: 1)
 ## Scaling option:
+##
 ## @table @asis
 ## @item 0
 ## No scaling.
@@ -178,6 +182,7 @@
 ##
 ## @item dual    (@w{@code{LPX_K_DUAL}}, default: 0)
 ## Dual simplex option:
+##
 ## @table @asis
 ## @item 0
 ## Do not use the dual simplex.
@@ -188,6 +193,7 @@
 ##
 ## @item price   (@w{@code{LPX_K_PRICE}}, default: 1)
 ## Pricing option (for both primal and dual simplex):
+##
 ## @table @asis
 ## @item 0
 ## Textbook pricing.
@@ -198,6 +204,7 @@
 ##
 ## @item round   (@w{@code{LPX_K_ROUND}}, default: 0)
 ## Solution rounding option:
+##
 ## @table @asis
 ## @item 0
 ## Report all primal and dual values "as is".
@@ -219,6 +226,7 @@
 ##
 ## @item branch (@w{@code{LPX_K_BRANCH}}, default: 2)
 ## Branching heuristic option (for MIP only):
+##
 ## @table @asis
 ## @item 0
 ## Branch on the first variable.
@@ -232,6 +240,7 @@
 ##
 ## @item btrack (@w{@code{LPX_K_BTRACK}}, default: 2)
 ## Backtracking heuristic option (for MIP only):
+##
 ## @table @asis
 ## @item 0
 ## Depth first search.
@@ -250,6 +259,7 @@
 ## @item lpsolver (default: 1)
 ## Select which solver to use.  If the problem is a MIP problem this flag
 ## will be ignored.
+##
 ## @table @asis
 ## @item 1
 ## Revised simplex method.
@@ -339,6 +349,7 @@
 ## Status of the optimization.
 ##
 ## Simplex Method:
+##
 ## @table @asis
 ## @item 180 (@w{@code{LPX_OPT}})
 ## Solution is optimal.
@@ -358,7 +369,9 @@
 ## @item 185 (@w{@code{LPX_UNDEF}})
 ## Solution status is undefined.
 ## @end table
+##
 ## Interior Point Method:
+##
 ## @table @asis
 ## @item 150 (@w{@code{LPX_T_UNDEF}})
 ## The interior point method is undefined.
@@ -366,7 +379,9 @@
 ## @item 151 (@w{@code{LPX_T_OPT}})
 ## The interior point method is optimal.
 ## @end table
+##
 ## Mixed Integer Method:
+##
 ## @table @asis
 ## @item 170 (@w{@code{LPX_I_UNDEF}})
 ## The status is undefined.
@@ -380,6 +395,7 @@
 ## @item 173 (@w{@code{LPX_I_NOFEAS}})
 ## No integer feasible solution.
 ## @end table
+##
 ## @noindent
 ## If an error occurs, @var{status} will contain one of the following
 ## codes:
@@ -421,6 +437,7 @@
 ##
 ## @item extra
 ## A data structure containing the following fields:
+##
 ## @table @code
 ## @item lambda
 ## Dual variables.
@@ -486,7 +503,7 @@
     error ("glpk: A cannot be an empty matrix");
     return;
   endif
-  [nc, nxa] = size(A);
+  [nc, nxa] = size (A);
   if (! isreal (A) || nxa != nx)
     error ("glpk: A must be a real valued %d by %d matrix", nc, nx);
     return;
--- a/scripts/optimization/lsqnonneg.m
+++ b/scripts/optimization/lsqnonneg.m
@@ -21,6 +21,7 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {@var{x} =} lsqnonneg (@var{c}, @var{d})
 ## @deftypefnx {Function File} {@var{x} =} lsqnonneg (@var{c}, @var{d}, @var{x0})
+## @deftypefnx {Function File} {@var{x} =} lsqnonneg (@var{c}, @var{d}, @var{x0}, @var{options})
 ## @deftypefnx {Function File} {[@var{x}, @var{resnorm}] =} lsqnonneg (@dots{})
 ## @deftypefnx {Function File} {[@var{x}, @var{resnorm}, @var{residual}] =} lsqnonneg (@dots{})
 ## @deftypefnx {Function File} {[@var{x}, @var{resnorm}, @var{residual}, @var{exitflag}] =} lsqnonneg (@dots{})
@@ -29,12 +30,16 @@
 ## Minimize @code{norm (@var{c}*@var{x} - d)} subject to
 ## @code{@var{x} >= 0}.  @var{c} and @var{d} must be real.  @var{x0} is an
 ## optional initial guess for @var{x}.
+## Currently, @code{lsqnonneg}
+## recognizes these options: @code{"MaxIter"}, @code{"TolX"}.
+## For a description of these options, see @ref{doc-optimset,,optimset}.
 ##
 ## Outputs:
+##
 ## @itemize @bullet
 ## @item resnorm
 ##
-## The squared 2-norm of the residual: norm(@var{c}*@var{x}-@var{d})^2
+## The squared 2-norm of the residual: norm (@var{c}*@var{x}-@var{d})^2
 ##
 ## @item residual
 ##
@@ -50,6 +55,7 @@
 ## @item output
 ##
 ## A structure with two fields:
+##
 ## @itemize @bullet
 ## @item "algorithm": The algorithm used ("nnls")
 ##
@@ -145,7 +151,8 @@
     ## compute the gradient.
     w = c'*(d - c*x);
     w(p) = [];
-    if (! any (w > 0))
+    tolx = optimget (options, "TolX", 10*eps*norm (c, 1)*length (c));
+    if (! any (w > tolx))
       if (useqr)
         ## verify the solution achieved using qr updating.
         ## in the best case, this should only take a single step.
@@ -198,14 +205,15 @@
 
 endfunction
 
-## Tests
+
 %!test
 %! C = [1 0;0 1;2 1];
 %! d = [1;3;-2];
-%! assert (lsqnonneg (C, d), [0;0.5], 100*eps)
+%! assert (lsqnonneg (C, d), [0;0.5], 100*eps);
 
 %!test
 %! C = [0.0372 0.2869;0.6861 0.7071;0.6233 0.6245;0.6344 0.6170];
 %! d = [0.8587;0.1781;0.0747;0.8405];
 %! xnew = [0;0.6929];
-%! assert (lsqnonneg (C, d), xnew, 0.0001)
+%! assert (lsqnonneg (C, d), xnew, 0.0001);
+
--- a/scripts/optimization/module.mk
+++ b/scripts/optimization/module.mk
@@ -6,6 +6,7 @@
 optimization_FCN_FILES = \
   optimization/__all_opts__.m \
   optimization/fminbnd.m \
+  optimization/fminsearch.m \
   optimization/fminunc.m \
   optimization/fsolve.m \
   optimization/fzero.m \
--- a/scripts/optimization/optimset.m
+++ b/scripts/optimization/optimset.m
@@ -25,16 +25,38 @@
 ## Create options struct for optimization functions.
 ##
 ## Valid parameters are:
-## @itemize @bullet
+##
+## @table @asis
 ## @item AutoScaling
 ##
 ## @item ComplexEqn
 ##
+## @item Display
+## Request verbose display of results from optimizations.  Values are:
+##
+## @table @asis
+## @item "off" [default]
+## No display.
+##
+## @item "iter"
+## Display intermediate results for every loop iteration.
+##
+## @item "final"
+## Display the result of the final loop iteration.
+##
+## @item "notify"
+## Display the result of the final loop iteration if the function has
+## failed to converge.
+## @end table
+##
 ## @item FinDiffType
 ##
 ## @item FunValCheck
-## When enabled, display an error if the objective function returns a complex
-## value or NaN@.  Must be set to "on" or "off" [default].
+## When enabled, display an error if the objective function returns an invalid
+## value (a complex number, NaN, or Inf).  Must be set to "on" or "off"
+## [default].  Note: the functions @code{fzero} and @code{fminbnd} correctly
+## handle Inf values and only complex values or NaN will cause an error in this
+## case. 
 ##
 ## @item GradObj
 ## When set to "on", the function to be minimized must return a second argument
@@ -73,7 +95,7 @@
 ## @item TypicalX
 ##
 ## @item Updating
-## @end itemize
+## @end table
 ## @end deftypefn
 
 function retval = optimset (varargin)
@@ -141,8 +163,8 @@
 endfunction
 
 
-%!assert (optimget (optimset ('tolx', 1e-2), 'tOLx'), 1e-2)
-%!assert (isfield (optimset ('tolFun', 1e-3), 'TolFun'))
+%!assert (optimget (optimset ("tolx", 1e-2), "tOLx"), 1e-2)
+%!assert (isfield (optimset ("tolFun", 1e-3), "TolFun"))
 
 %!error (optimset ("%NOT_A_REAL_FUNCTION_NAME%"))
 
--- a/scripts/optimization/pqpnonneg.m
+++ b/scripts/optimization/pqpnonneg.m
@@ -30,6 +30,7 @@
 ## definite.  @var{x0} is an optional initial guess for @var{x}.
 ##
 ## Outputs:
+##
 ## @itemize @bullet
 ## @item minval
 ##
@@ -45,6 +46,7 @@
 ## @item output
 ##
 ## A structure with two fields:
+##
 ## @itemize @bullet
 ## @item "algorithm": The algorithm used ("nnls")
 ##
@@ -198,14 +200,15 @@
 
 endfunction
 
-## Tests
+
 %!test
 %! C = [5 2;2 2];
 %! d = [3; -1];
-%! assert (pqpnonneg (C, d), [0;0.5], 100*eps)
+%! assert (pqpnonneg (C, d), [0;0.5], 100*eps);
 
 ## Test equivalence of lsq and pqp
 %!test
 %! C = rand (20, 10);
 %! d = rand (20, 1);
-%! assert (pqpnonneg (C'*C, -C'*d), lsqnonneg (C, d), 100*eps)
+%! assert (pqpnonneg (C'*C, -C'*d), lsqnonneg (C, d), 100*eps);
+
--- a/scripts/optimization/qp.m
+++ b/scripts/optimization/qp.m
@@ -228,15 +228,15 @@
       if (! isempty (lb) && ! isempty (ub))
         rtol = sqrt (eps);
         for i = 1:n
-          if (abs(lb (i) - ub(i)) < rtol*(1 + max (abs (lb(i) + ub(i)))))
+          if (abs (lb (i) - ub(i)) < rtol*(1 + max (abs (lb(i) + ub(i)))))
             ## These are actually an equality constraint
-            tmprow = zeros(1,n);
+            tmprow = zeros (1,n);
             tmprow(i) = 1;
             A = [A;tmprow];
             b = [b; 0.5*(lb(i) + ub(i))];
             n_eq = n_eq + 1;
           else
-            tmprow = zeros(1,n);
+            tmprow = zeros (1,n);
             tmprow(i) = 1;
             Ain = [Ain; tmprow; -tmprow];
             bin = [bin; lb(i); -ub(i)];
--- a/scripts/optimization/sqp.m
+++ b/scripts/optimization/sqp.m
@@ -122,7 +122,7 @@
 ## iterations.  The default value is 100.
 ##
 ## The eighth argument @var{tol} specifies the tolerance for the
-## stopping criteria.  The default value is @code{sqrt(eps)}.
+## stopping criteria.  The default value is @code{sqrt (eps)}.
 ##
 ## The value returned in @var{info} may be one of the following:
 ##
@@ -186,12 +186,8 @@
 
 function [x, obj, info, iter, nf, lambda] = sqp (x0, objf, cef, cif, lb, ub, maxiter, tolerance)
 
-  global __sqp_nfun__;
-  global __sqp_obj_fun__;
-  global __sqp_ce_fun__;
-  global __sqp_ci_fun__;
-  global __sqp_cif__;
-  global __sqp_cifcn__;
+  globals = struct (); # data and handles, needed and changed by
+                       # subfunctions
 
   if (nargin < 2 || nargin > 8 || nargin == 5)
     print_usage ();
@@ -204,12 +200,12 @@
     x0 = x0';
   endif
 
-  obj_grd = @fd_obj_grd;
   have_hess = 0;
   if (iscell (objf))
     switch (numel (objf))
      case 1
        obj_fun = objf{1};
+       obj_grd = @ (x) fd_obj_grd (x, obj_fun);
      case 2
        obj_fun = objf{1};
        obj_grd = objf{2};
@@ -223,17 +219,17 @@
     endswitch
   else
     obj_fun = objf;   # No cell array, only obj_fun set
+    obj_grd = @ (x) fd_obj_grd (x, obj_fun);
   endif
-  __sqp_obj_fun__ = obj_fun;
 
   ce_fun = @empty_cf;
   ce_grd = @empty_jac;
   if (nargin > 2)
-    ce_grd = @fd_ce_jac;
     if (iscell (cef))
       switch (numel (cef))
        case 1
          ce_fun = cef{1};
+         ce_grd = @ (x) fd_ce_jac (x, ce_fun);
        case 2
          ce_fun = cef{1};
          ce_grd = cef{2};
@@ -242,28 +238,28 @@
       endswitch
     elseif (! isempty (cef))
       ce_fun = cef;   # No cell array, only constraint equality function set
+      ce_grd = @ (x) fd_ce_jac (x, ce_fun);
     endif
   endif
-  __sqp_ce_fun__ = ce_fun;
 
   ci_fun = @empty_cf;
   ci_grd = @empty_jac;
   if (nargin > 3)
     ## constraint function given by user with possible gradient
-    __sqp_cif__ = cif;
+    globals.cif = cif;
     ## constraint function given by user without gradient
-    __sqp_cifcn__ = @empty_cf;
+    globals.cifcn = @empty_cf;
     if (iscell (cif))
       if (length (cif) > 0)
-        __sqp_cifcn__ = cif{1};
+        globals.cifcn = cif{1};
       endif
     elseif (! isempty (cif))
-      __sqp_cifcn__ = cif;
+      globals.cifcn = cif;
     endif
 
     if (nargin < 5 || (nargin > 5 && isempty (lb) && isempty (ub)))
       ## constraint inequality function only without any bounds
-      ci_grd = @fd_ci_jac;
+      ci_grd = @ (x) fd_ci_jac (x, globals.cifcn);
       if (iscell (cif))
         switch length (cif)
          case {1}
@@ -279,35 +275,33 @@
       endif
     else
       ## constraint inequality function with bounds present
-      global __sqp_lb__;
       lb_idx = ub_idx = true (size (x0));
       ub_grad = - (lb_grad = eye (rows (x0)));
       if (isvector (lb))
-        __sqp_lb__ = tmp_lb = lb(:);
+        globals.lb = tmp_lb = lb(:);
         lb_idx(:) = tmp_idx = (lb != -Inf);
-        __sqp_lb__ = __sqp_lb__(tmp_idx, 1);
+        globals.lb = globals.lb(tmp_idx, 1);
         lb_grad = lb_grad(lb_idx, :);
       elseif (isempty (lb))
         if (isa (x0, "single"))
-          __sqp_lb__ = tmp_lb = -realmax ("single");
+          globals.lb = tmp_lb = -realmax ("single");
         else
-          __sqp_lb__ = tmp_lb = -realmax;
+          globals.lb = tmp_lb = -realmax;
         endif
       else
         error ("sqp: invalid lower bound");
       endif
 
-      global __sqp_ub__;
       if (isvector (ub))
-        __sqp_ub__ = tmp_ub = ub(:);
+        globals.ub = tmp_ub = ub(:);
         ub_idx(:) = tmp_idx = (ub != Inf);
-        __sqp_ub__ = __sqp_ub__(tmp_idx, 1);
+        globals.ub = globals.ub(tmp_idx, 1);
         ub_grad = ub_grad(ub_idx, :);
       elseif (isempty (ub))
         if (isa (x0, "single"))
-          __sqp_ub__ = tmp_ub = realmax ("single");
+          globals.ub = tmp_ub = realmax ("single");
         else
-          __sqp_ub__ = tmp_ub = realmax;
+          globals.ub = tmp_ub = realmax;
         endif
       else
         error ("sqp: invalid upper bound");
@@ -317,11 +311,10 @@
         error ("sqp: upper bound smaller than lower bound");
       endif
       bounds_grad = [lb_grad; ub_grad];
-      ci_fun = @ (x) cf_ub_lb (x, lb_idx, ub_idx);
-      ci_grd = @ (x) cigrad_ub_lb (x, bounds_grad);
+      ci_fun = @ (x) cf_ub_lb (x, lb_idx, ub_idx, globals);
+      ci_grd = @ (x) cigrad_ub_lb (x, bounds_grad, globals);
     endif
 
-    __sqp_ci_fun__ = ci_fun;
   endif   # if (nargin > 3)
 
   iter_max = 100;
@@ -354,7 +347,7 @@
   x = x0;
 
   obj = feval (obj_fun, x0);
-  __sqp_nfun__ = 1;
+  globals.nfun = 1;
 
   c = feval (obj_grd, x0);
 
@@ -432,8 +425,9 @@
 
     ## Choose mu such that p is a descent direction for the chosen
     ## merit function phi.
-    [x_new, alpha, obj_new] = linesearch_L1 (x, p, obj_fun, obj_grd,
-                                             ce_fun, ci_fun, lambda, obj);
+    [x_new, alpha, obj_new, globals] = \
+        linesearch_L1 (x, p, obj_fun, obj_grd, ce_fun, ci_fun, lambda, \
+                       obj, globals);
 
     ## Evaluate objective function, constraints, and gradients at x_new.
     c_new = feval (obj_grd, x_new);
@@ -521,14 +515,13 @@
     info = 103;
   endif
 
-  nf = __sqp_nfun__;
+  nf = globals.nfun;
 
 endfunction
 
 
-function [merit, obj] = phi_L1 (obj, obj_fun, ce_fun, ci_fun, x, mu)
-
-  global __sqp_nfun__;
+function [merit, obj, globals] = phi_L1 (obj, obj_fun, ce_fun, ci_fun, \
+                                         x, mu, globals)
 
   ce = feval (ce_fun, x);
   ci = feval (ci_fun, x);
@@ -539,7 +532,7 @@
 
   if (isempty (obj))
     obj = feval (obj_fun, x);
-    __sqp_nfun__++;
+    globals.nfun++;
   endif
 
   merit = obj;
@@ -552,8 +545,9 @@
 endfunction
 
 
-function [x_new, alpha, obj] = linesearch_L1 (x, p, obj_fun, obj_grd,
-                                              ce_fun, ci_fun, lambda, obj)
+function [x_new, alpha, obj, globals] = \
+      linesearch_L1 (x, p, obj_fun, obj_grd, ce_fun, ci_fun, lambda, \
+                     obj, globals)
 
   ## Choose parameters
   ##
@@ -576,7 +570,8 @@
   c = feval (obj_grd, x);
   ce = feval (ce_fun, x);
 
-  [phi_x_mu, obj] = phi_L1 (obj, obj_fun, ce_fun, ci_fun, x, mu);
+  [phi_x_mu, obj, globals] = phi_L1 (obj, obj_fun, ce_fun, ci_fun, x, \
+                                     mu, globals);
 
   D_phi_x_mu = c' * p;
   d = feval (ci_fun, x);
@@ -589,7 +584,8 @@
   endif
 
   while (1)
-    [p1, obj] = phi_L1 ([], obj_fun, ce_fun, ci_fun, x+alpha*p, mu);
+    [p1, obj, globals] = phi_L1 ([], obj_fun, ce_fun, ci_fun, \
+                                 x+alpha*p, mu, globals);
     p2 = phi_x_mu+eta*alpha*D_phi_x_mu;
     if (p1 > p2)
       ## Reset alpha = tau_alpha * alpha for some tau_alpha in the
@@ -648,11 +644,9 @@
 endfunction
 
 
-function grd = fd_obj_grd (x)
+function grd = fd_obj_grd (x, obj_fun)
 
-  global __sqp_obj_fun__;
-
-  grd = fdgrd (__sqp_obj_fun__, x);
+  grd = fdgrd (obj_fun, x);
 
 endfunction
 
@@ -671,47 +665,40 @@
 endfunction
 
 
-function jac = fd_ce_jac (x)
+function jac = fd_ce_jac (x, ce_fun)
 
-  global __sqp_ce_fun__;
-
-  jac = fdjac (__sqp_ce_fun__, x);
+  jac = fdjac (ce_fun, x);
 
 endfunction
 
 
-function jac = fd_ci_jac (x)
+function jac = fd_ci_jac (x, cifcn)
 
-  global __sqp_cifcn__;
-  ## __sqp_cifcn__ = constraint function without gradients and lb or ub
-  jac = fdjac (__sqp_cifcn__, x);
+  ## cifcn = constraint function without gradients and lb or ub
+  jac = fdjac (cifcn, x);
 
 endfunction
 
 
-function res = cf_ub_lb (x, lbidx, ubidx)
+function res = cf_ub_lb (x, lbidx, ubidx, globals)
 
   ## combine constraint function with ub and lb
-  global __sqp_cifcn__ __sqp_lb__ __sqp_ub__
-
-  if (isempty (__sqp_cifcn__))
-    res = [x(lbidx,1)-__sqp_lb__; __sqp_ub__-x(ubidx,1)];
+  if (isempty (globals.cifcn))
+    res = [x(lbidx,1)-globals.lb; globals.ub-x(ubidx,1)];
   else
-    res = [feval(__sqp_cifcn__,x); \
-           x(lbidx,1)-__sqp_lb__; __sqp_ub__-x(ubidx,1)];
+    res = [feval(globals.cifcn,x); x(lbidx,1)-globals.lb;
+           globals.ub-x(ubidx,1)];
   endif
 
 endfunction
 
 
-function res = cigrad_ub_lb (x, bgrad)
-
-  global __sqp_cif__
+function res = cigrad_ub_lb (x, bgrad, globals)
 
-  cigradfcn = @fd_ci_jac;
+  cigradfcn = @ (x) fd_ci_jac (x, globals.cifcn);
 
-  if (iscell (__sqp_cif__) && length (__sqp_cif__) > 1)
-    cigradfcn = __sqp_cif__{2};
+  if (iscell (globals.cif) && length (globals.cif) > 1)
+    cigradfcn = globals.cif{2};
   endif
 
   if (isempty (cigradfcn))
@@ -733,6 +720,7 @@
 
 endfunction
 
+
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %% Test Code
 
@@ -743,7 +731,7 @@
 %!endfunction
 %!
 %!function obj = __phi (x)
-%!  obj = exp(prod(x)) - 0.5*(x(1)^3+x(2)^3+1)^2;
+%!  obj = exp (prod (x)) - 0.5*(x(1)^3 + x(2)^3 + 1)^2;
 %!endfunction
 %!
 %!test
@@ -760,22 +748,23 @@
 %!
 %! obj_opt = 0.0539498477702739;
 %!
-%! assert (all (abs (x-x_opt) < 8*sqrt (eps)) && abs (obj-obj_opt) < sqrt (eps));
+%! assert (x, x_opt, 8*sqrt (eps));
+%! assert (obj, obj_opt, sqrt (eps));
 
 %% Test input validation
 %!error sqp ()
 %!error sqp (1)
 %!error sqp (1,2,3,4,5,6,7,8,9)
 %!error sqp (1,2,3,4,5)
-%!error sqp (ones(2,2))
-%!error sqp (1,cell(4,1))
-%!error sqp (1,cell(3,1),cell(3,1))
-%!error sqp (1,cell(3,1),cell(2,1),cell(3,1))
-%!error sqp (1,cell(3,1),cell(2,1),cell(2,1),ones(2,2),[])
-%!error sqp (1,cell(3,1),cell(2,1),cell(2,1),[],ones(2,2))
-%!error sqp (1,cell(3,1),cell(2,1),cell(2,1),1,-1)
-%!error sqp (1,cell(3,1),cell(2,1),cell(2,1),[],[],ones(2,2))
-%!error sqp (1,cell(3,1),cell(2,1),cell(2,1),[],[],-1)
-%!error sqp (1,cell(3,1),cell(2,1),cell(2,1),[],[],1.5)
-%!error sqp (1,cell(3,1),cell(2,1),cell(2,1),[],[],[],ones(2,2))
-%!error sqp (1,cell(3,1),cell(2,1),cell(2,1),[],[],[],-1)
+%!error sqp (ones (2,2))
+%!error sqp (1, cell (4,1))
+%!error sqp (1, cell (3,1), cell (3,1))
+%!error sqp (1, cell (3,1), cell (2,1), cell (3,1))
+%!error sqp (1, cell (3,1), cell (2,1), cell (2,1), ones (2,2),[])
+%!error sqp (1, cell (3,1), cell (2,1), cell (2,1),[], ones (2,2))
+%!error sqp (1, cell (3,1), cell (2,1), cell (2,1),1,-1)
+%!error sqp (1, cell (3,1), cell (2,1), cell (2,1),[],[], ones (2,2))
+%!error sqp (1, cell (3,1), cell (2,1), cell (2,1),[],[],-1)
+%!error sqp (1, cell (3,1), cell (2,1), cell (2,1),[],[],1.5)
+%!error sqp (1, cell (3,1), cell (2,1), cell (2,1),[],[],[], ones (2,2))
+%!error sqp (1, cell (3,1), cell (2,1), cell (2,1),[],[],[],-1)
--- a/scripts/path/matlabroot.m
+++ b/scripts/path/matlabroot.m
@@ -25,11 +25,13 @@
 ## @seealso{OCTAVE_HOME}
 ## @end deftypefn
 
-function val = matlabroot ()
+function retval = matlabroot ()
 
-  val = OCTAVE_HOME;
+  retval = OCTAVE_HOME;
 
 endfunction
 
-%!assert (matlabroot(), OCTAVE_HOME())
+
 
+%!assert (matlabroot (), OCTAVE_HOME ())
+
--- a/scripts/path/pathdef.m
+++ b/scripts/path/pathdef.m
@@ -21,7 +21,7 @@
 ## @deftypefn {Function File} {@var{val} =} pathdef ()
 ## Return the default path for Octave.
 ## The path information is extracted from one of three sources.
-## In order of preference, those are;
+## The possible sources, in order of preference, are:
 ##
 ## @enumerate
 ## @item @file{~/.octaverc}
@@ -30,7 +30,7 @@
 ##
 ## @item Octave's path prior to changes by any octaverc.
 ## @end enumerate
-## @seealso{path, addpath, rmpath, genpath, savepath, pathsep}
+## @seealso{path, addpath, rmpath, genpath, savepath}
 ## @end deftypefn
 
 function val = pathdef ()
@@ -39,10 +39,10 @@
   pathdir = octave_config_info ("localstartupfiledir");
   site_octaverc = fullfile (pathdir, "octaverc");
 
-  ## Locate the user ~\.octaverc file.
+  ## Locate the user's ~/.octaverc file.
   user_octaverc = fullfile ("~", ".octaverc");
 
-  ## Extract the specified paths from the site and user octaverc"s.
+  ## Extract the specified paths from the site and user octavercs.
   site_path = __extractpath__ (site_octaverc);
   if (exist (user_octaverc, "file"))
     user_path = __extractpath__ (user_octaverc);
@@ -50,9 +50,7 @@
     user_path = "";
   endif
 
-  ## A path definition in the user octaverc has precedence over the
-  ## site.
-
+  ## A path definition in the user rcfile has precedence over the site rcfile.
   if (! isempty (user_path))
     val = user_path;
   elseif (! isempty (site_path))
@@ -73,9 +71,10 @@
 function specifiedpath = __extractpath__ (savefile)
 
   ## The majority of this code was borrowed from savepath.m.
-  ## FIXME -- is there some way to share the common parts instead of
-  ## duplicating?
-
+  ## FIXME: is there some way to share the common parts instead of duplicating?
+  ## ANSWER: Yes.  Create a private directory and extract this section of code
+  ##         and place it there in a new function only visible by pathdef() and
+  ##         savepath().
   beginstring = "## Begin savepath auto-created section, do not edit";
   endstring   = "## End savepath auto-created section";
 
@@ -85,31 +84,22 @@
 
   ## Parse the file if it exists to see if we should replace a section
   ## or create a section.
-  startline = 0;
-  endline = 0;
+  startline = endline = 0;
   filelines = {};
   if (exist (savefile) == 2)
-    ## read in all lines of the file
     [fid, msg] = fopen (savefile, "rt");
     if (fid < 0)
       error ("__extractpath__: could not open savefile, %s: %s", savefile, msg);
     endif
     unwind_protect
       linenum = 0;
-      while (linenum >= 0)
-        result = fgetl (fid);
-        if (isnumeric (result))
-          ## End at the end of file.
-          linenum = -1;
-        else
-          linenum++;
-          filelines{linenum} = result;
-          ## Find the first and last lines if they exist in the file.
-          if (strcmp (result, beginstring))
-            startline = linenum + 1;
-          elseif (strcmp (result, endstring))
-            endline = linenum - 1;
-          endif
+      while (ischar (line = fgetl (fid)))
+        filelines{++linenum} = line;
+        ## find the first and last lines if they exist in the file
+        if (strcmp (line, beginstring))
+          startline = linenum;
+        elseif (strcmp (line, endstring))
+          endline = linenum;
         endif
       endwhile
     unwind_protect_cleanup
--- a/scripts/path/savepath.m
+++ b/scripts/path/savepath.m
@@ -17,19 +17,21 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} savepath (@var{file})
-## Save the portion of the current function search path, that is
-## not set during Octave's initialization process, to @var{file}.
+## @deftypefn  {Function File} {} savepath ()
+## @deftypefnx {Function File} {} savepath (@var{file})
+## @deftypefnx {Function File} {@var{status} =} savepath (@dots{})
+## Save the unique portion of the current function search path that is
+## not set during Octave's initialization process to @var{file}.
 ## If @var{file} is omitted, @file{~/.octaverc} is used.  If successful,
 ## @code{savepath} returns 0.
-## @seealso{path, addpath, rmpath, genpath, pathdef, pathsep}
+## @seealso{path, addpath, rmpath, genpath, pathdef}
 ## @end deftypefn
 
 ## Author: Bill Denney <bill@givebillmoney.com>
 
-function varargout = savepath (file)
+function retval = savepath (file)
 
-  retval = 1;
+  ret = 1;
 
   beginstring = "## Begin savepath auto-created section, do not edit";
   endstring   = "## End savepath auto-created section";
@@ -38,40 +40,30 @@
     file = fullfile ("~", ".octaverc");
   endif
 
-  ## parse the file if it exists to see if we should replace a section
-  ## or create a section
-  startline = 0;
-  endline = 0;
+  ## parse the file if it exists to see if we should replace an
+  ## existing section or create a new section
+  startline = endline = 0;
   filelines = {};
   if (exist (file) == 2)
-    ## read in all lines of the file
     [fid, msg] = fopen (file, "rt");
     if (fid < 0)
       error ("savepath: could not open file, %s: %s", file, msg);
     endif
     unwind_protect
       linenum = 0;
-      while (linenum >= 0)
-        result = fgetl (fid);
-        if (isnumeric (result))
-          ## end at the end of file
-          linenum = -1;
-        else
-          linenum = linenum + 1;
-          filelines{linenum} = result;
-          ## find the first and last lines if they exist in the file
-          if (strcmp (result, beginstring))
-            startline = linenum;
-          elseif (strcmp (result, endstring))
-            endline = linenum;
-          endif
+      while (ischar (line = fgetl (fid)))
+        filelines{++linenum} = line;
+        ## find the first and last lines if they exist in the file
+        if (strcmp (line, beginstring))
+          startline = linenum;
+        elseif (strcmp (line, endstring))
+          endline = linenum;
         endif
       endwhile
     unwind_protect_cleanup
       closeread = fclose (fid);
       if (closeread < 0)
-        error ("savepath: could not close file after reading, %s",
-               file);
+        error ("savepath: could not close file after reading, %s", file);
       endif
     end_unwind_protect
   endif
@@ -116,15 +108,16 @@
     workingpath = parsepath (path);
     command_line_path = parsepath (command_line_path ());
     octave_path = parsepath (getenv ("OCTAVE_PATH"));
-    if (isempty (pathdef ()))
+    pathdef = pathdef ();
+    if (isempty (pathdef))
       ## This occurs when running octave via run-octave. In this instance
       ## the entire path is specified via the command line and pathdef()
       ## is empty.
-      [tmp, n] = setdiff (workingpath, octave_path);
+      [~, n] = setdiff (workingpath, octave_path);
       default_path = command_line_path;
     else
-      [tmp, n] = setdiff (workingpath, union (command_line_path, octave_path));
-      default_path = parsepath (pathdef ());
+      [~, n] = setdiff (workingpath, union (command_line_path, octave_path));
+      default_path = parsepath (pathdef);
     endif
     ## This is the path we'd like to preserve when octave is run.
     path_to_preserve = workingpath (sort (n));
@@ -133,34 +126,33 @@
     [pkg_user, pkg_system] = pkg ("list");
     pkg_user_path = cell (1, numel (pkg_user));
     pkg_system_path = cell (1, numel (pkg_system));
-    for n = 1:numel(pkg_user)
+    for n = 1:numel (pkg_user)
       pkg_user_path{n} = pkg_user{n}.archprefix;
     endfor
-    for n = 1:numel(pkg_system)
+    for n = 1:numel (pkg_system)
       pkg_system_path{n} = pkg_system{n}.archprefix;
     endfor
     pkg_path = union (pkg_user_path, pkg_system_path);
 
     ## Rely on Octave's initialization to include the pkg path elements.
     if (! isempty (pkg_path))
-      [tmp, n] = setdiff (path_to_preserve, strcat (pkg_path, ":"));
-      path_to_preserve = path_to_preserve (sort (n));
+      [~, n] = setdiff (path_to_preserve, strcat (pkg_path, ":"));
+      path_to_preserve = path_to_preserve(sort (n));
     endif
 
     ## Split the path to be saved into two groups. Those path elements that
     ## belong at the beginning and those at the end.
     if (! isempty (default_path))
-      n1 = strmatch (default_path{1}, path_to_preserve, "exact");
-      n2 = strmatch (default_path{end}, path_to_preserve, "exact");
+      n1 = find (strcmp (default_path{1}, path_to_preserve));
+      n2 = find (strcmp (default_path{end}, path_to_preserve));
       n_middle = round (0.5*(n1+n2));
-      [tmp, n] = setdiff (path_to_preserve, default_path);
-      path_to_save = path_to_preserve (sort (n));
+      [~, n] = setdiff (path_to_preserve, default_path);
+      path_to_save = path_to_preserve(sort (n));
       ## Remove pwd
-      path_to_save = path_to_save (! strcmpi (path_to_save,
-                                              strcat (".", pathsep)));
+      path_to_save = path_to_save(! strcmp (path_to_save, ["." pathsep]));
       n = ones (size (path_to_save));
-      for m = 1:numel(path_to_save)
-        n(m) = strmatch (path_to_save{m}, path_to_preserve);
+      for m = 1:numel (path_to_save)
+        n(m) = find (strcmp (path_to_save{m}, path_to_preserve));
       endfor
       path_to_save_begin = path_to_save(n <= n_middle);
       path_to_save_end   = path_to_save(n > n_middle);
@@ -199,16 +191,16 @@
     endif
   end_unwind_protect
 
-  retval = 0;
+  ret = 0;
 
-  if (nargout == 1)
-    varargout{1} = retval;
+  if (nargout > 0)
+    retval = ret;
   endif
 
 endfunction
 
 function path_elements = parsepath (p)
   pat = sprintf ('([^%s]+[%s$])', pathsep, pathsep);
-  [~, ~, ~, path_elements] = regexpi (strcat (p, pathsep), pat);
+  path_elements = regexpi (strcat (p, pathsep), pat, "match");
 endfunction
 
--- a/scripts/pkg/module.mk
+++ b/scripts/pkg/module.mk
@@ -1,7 +1,44 @@
 FCN_FILE_DIRS += pkg
 
 pkg_PRIVATE_FCN_FILES = \
-  pkg/private/get_forge_pkg.m
+  pkg/private/build.m \
+  pkg/private/configure_make.m \
+  pkg/private/copy_files.m \
+  pkg/private/create_pkgadddel.m \
+  pkg/private/describe.m \
+  pkg/private/dirempty.m \
+  pkg/private/extract_pkg.m \
+  pkg/private/finish_installation.m \
+  pkg/private/fix_depends.m \
+  pkg/private/fix_version.m \
+  pkg/private/generate_lookfor_cache.m \
+  pkg/private/get_description.m \
+  pkg/private/get_forge_download.m \
+  pkg/private/get_forge_pkg.m \
+  pkg/private/getarch.m \
+  pkg/private/getarchdir.m \
+  pkg/private/getarchprefix.m \
+  pkg/private/get_unsatisfied_deps.m \
+  pkg/private/install.m \
+  pkg/private/installed_packages.m \
+  pkg/private/is_architecture_dependent.m \
+  pkg/private/list_forge_packages.m \
+  pkg/private/load_package_dirs.m \
+  pkg/private/load_packages.m \
+  pkg/private/load_packages_and_dependencies.m \
+  pkg/private/packinfo_copy_file.m \
+  pkg/private/parse_pkg_idx.m \
+  pkg/private/prepare_installation.m \
+  pkg/private/print_package_description.m \
+  pkg/private/rebuild.m \
+  pkg/private/repackage.m \
+  pkg/private/save_order.m \
+  pkg/private/shell.m \
+  pkg/private/uninstall.m \
+  pkg/private/unload_packages.m \
+  pkg/private/verify_directory.m \
+  pkg/private/write_index.m
+
 
 pkg_FCN_FILES = \
   pkg/pkg.m \
--- a/scripts/pkg/pkg.m
+++ b/scripts/pkg/pkg.m
@@ -1,5 +1,6 @@
 ## Copyright (C) 2005-2012 S�ren Hauberg
 ## Copyright (C) 2010 VZLU Prague, a.s.
+## Copyright (C) 2012 Carlo de Falco
 ##
 ## This file is part of Octave.
 ##
@@ -136,7 +137,7 @@
 ## [user_packages, system_packages] = pkg ("list")
 ## @end example
 ##
-## The option '-forge' lists packages available at the Octave-Forge repository.
+## The option "-forge" lists packages available at the Octave-Forge repository.
 ## This requires an internet connection and the cURL library.  For example:
 ##
 ## @example
@@ -145,7 +146,7 @@
 ##
 ## @item describe
 ## Show a short description of the named installed packages, with the option
-## '-verbose' also list functions provided by the package.  For example,
+## "-verbose" also list functions provided by the package.  For example,
 ##
 ## @example
 ## pkg describe -verbose all
@@ -262,16 +263,21 @@
 function [local_packages, global_packages] = pkg (varargin)
   ## Installation prefix (FIXME: what should these be on windows?)
   persistent user_prefix = false;
-  persistent prefix = -1;
+  persistent prefix = false;
   persistent archprefix = -1;
   persistent local_list = tilde_expand (fullfile ("~", ".octave_packages"));
   persistent global_list = fullfile (OCTAVE_HOME (), "share", "octave",
                                      "octave_packages");
+
+  confirm_recursive_rmdir (false, "local");
+
   mlock ();
 
-  global_install = issuperuser ();
+  ## If user is superuser set global_istall to true
+  ## FIXME: is it OK to set this always true on windows?
+  global_install = ((ispc () && ! isunix ()) || (geteuid () == 0));
 
-  if (prefix == -1)
+  if (isbool (prefix))
     if (global_install)
       prefix = fullfile (OCTAVE_HOME (), "share", "octave", "packages");
       archprefix = fullfile (octave_config_info ("libdir"),
@@ -311,6 +317,9 @@
         ## Send verbose output to pager immediately.  Change setting locally.
         page_output_immediately (true, "local");
       case "-forge"
+        if (! octave_config_info ("CURL_LIBS"))
+          error ("pkg: can't download from forge without the cURL library");
+        endif
         octave_forge = true;
       case "-local"
         global_install = false;
@@ -414,38 +423,47 @@
         local_packages = prefix;
         global_packages = archprefix;
       elseif (length (files) >= 1 && nargout <= 2 && ischar (files{1}))
-        prefix = files{1};
-        prefix = absolute_pathname (prefix);
-        local_packages = prefix;
+        prefix = tilde_expand (files{1});
+        if (! exist (prefix, "dir"))
+          [status, msg, msgid] = mkdir (prefix);
+          if (status == 0)
+            error("cannot create prefix %s: %s", prefix, msg);
+          endif
+          warning ("creating the directory %s\n", prefix);
+        endif
+        local_packages = prefix = canonicalize_file_name (prefix);
         user_prefix = true;
         if (length (files) >= 2 && ischar (files{2}))
-          archprefix = files{2};
-          try
-            archprefix = absolute_pathname (archprefix);
-          catch
-            mkdir (archprefix);
+          archprefix = tilde_expand (files{2});
+          if (! exist (archprefix, "dir"))
+            [status, msg, msgid] = mkdir (archprefix);
+            if (status == 0)
+              error("cannot create archprefix %s: %s", archprefix, msg);
+            endif
             warning ("creating the directory %s\n", archprefix);
-            archprefix = absolute_pathname (archprefix);
-          end_try_catch
-          global_packages = archprefix;
+            global_packages = archprefix = canonicalize_file_name (archprefix);
+          endif
         endif
       else
         error ("you must specify a prefix directory, or request an output argument");
       endif
-
+      
     case "local_list"
       if (length (files) == 0 && nargout == 0)
         disp (local_list);
       elseif (length (files) == 0 && nargout == 1)
         local_packages = local_list;
       elseif (length (files) == 1 && nargout == 0 && ischar (files{1}))
-        try
-          local_list = absolute_pathname (files{1});
-        catch
-          ## Force file to be created
-          fclose (fopen (files{1}, "wt"));
-          local_list = absolute_pathname (files{1});
-        end_try_catch
+        local_list = files{1};
+        if (! exist (local_list, "file"))          
+          try
+            ## Force file to be created
+            fclose (fopen (local_list, "wt"));
+          catch
+            error ("cannot create file %s", local_list);
+          end_try_catch
+        endif
+        local_list = canonicalize_file_name (local_list);
       else
         error ("you must specify a local_list file, or request an output argument");
       endif
@@ -456,13 +474,16 @@
       elseif (length (files) == 0 && nargout == 1)
         local_packages = global_list;
       elseif (length (files) == 1 && nargout == 0 && ischar (files{1}))
-        try
-          global_list = absolute_pathname (files{1});
-        catch
-          ## Force file to be created
-          fclose (fopen (files{1}, "wt"));
-          global_list = absolute_pathname (files{1});
-        end_try_catch
+        global_list = files{1};
+        if (! exist (global_list, "file"))  
+          try
+            ## Force file to be created
+            fclose (fopen (files{1}, "wt"));
+          catch
+            error ("cannot create file %s", global_list);
+          end_try_catch
+        endif
+        global_list = canonicalize_file_name (global_list);
       else
         error ("you must specify a global_list file, or request an output argument");
       endif
@@ -533,1905 +554,3 @@
       error ("you must specify a valid action for 'pkg'. See 'help pkg' for details");
   endswitch
 endfunction
-
-function descriptions = rebuild (prefix, archprefix, list, files, auto, verbose)
-  if (isempty (files))
-    [dirlist, err, msg] = readdir (prefix);
-    if (err)
-      error ("couldn't read directory %s: %s", prefix, msg);
-    endif
-    ## the two first entries of dirlist are "." and ".."
-    dirlist([1,2]) = [];
-  else
-    old_descriptions = installed_packages (list, list);
-    wd = pwd ();
-    unwind_protect
-      cd (prefix);
-      dirlist = glob (cellfun(@(x) cstrcat(x, '-*'), files, 'uniformoutput', 0));
-    unwind_protect_cleanup
-      cd (wd);
-    end_unwind_protect
-  endif
-  descriptions = {};
-  for k = 1:length (dirlist)
-    descfile = fullfile (prefix, dirlist{k}, "packinfo", "DESCRIPTION");
-    if (verbose)
-      printf ("recreating package description from %s\n", dirlist{k});
-    endif
-    if (exist (descfile, "file"))
-      desc = get_description (descfile);
-      desc.dir = fullfile (prefix, dirlist{k});
-      desc.archprefix = fullfile (archprefix, cstrcat (desc.name, "-",
-                                  desc.version));
-      if (auto != 0)
-        if (exist (fullfile (desc.dir, "packinfo", ".autoload"), "file"))
-          unlink (fullfile (desc.dir, "packinfo", ".autoload"));
-        endif
-        if (auto < 0)
-          desc.autoload = 0;
-        elseif (auto > 0)
-          desc.autoload = 1;
-          fclose (fopen (fullfile (desc.dir, "packinfo", ".autoload"), "wt"));
-        endif
-      else
-        if (exist (fullfile (desc.dir, "packinfo", ".autoload"), "file"))
-          desc.autoload = 1;
-        else
-          desc.autoload = 0;
-        endif
-      endif
-      descriptions{end + 1} = desc;
-    elseif (verbose)
-      warning ("directory %s is not a valid package", dirlist{k});
-    endif
-  endfor
-
-  if (! isempty (files))
-    ## We are rebuilding for a particular package(s) so we should take
-    ## care to keep the other untouched packages in the descriptions
-    descriptions = {descriptions{:}, old_descriptions{:}};
-
-    dup = [];
-    for i = 1:length (descriptions)
-      if (find (dup, i))
-        continue;
-      endif
-      for j = (i+1):length (descriptions)
-        if (find (dup, j))
-          continue;
-        endif
-        if (strcmp (descriptions{i}.name, descriptions{j}.name))
-          dup = [dup, j];
-        endif
-      endfor
-    endfor
-    if (! isempty (dup))
-      descriptions (dup) = [];
-    endif
-  endif
-endfunction
-
-function build (files, handle_deps, autoload, verbose)
-  if (length (files) < 1)
-    error ("insufficient number of files");
-  endif
-  builddir = files{1};
-  if (! exist (builddir, "dir"))
-    warning ("creating build directory %s", builddir);
-    [status, msg] = mkdir (builddir);
-    if (status != 1)
-      error ("could not create installation directory: %s", msg);
-    endif
-  endif
-  builddir = absolute_pathname (builddir);
-  installdir = fullfile (builddir, "install");
-  if (! exist (installdir, "dir"))
-    [status, msg] = mkdir (installdir);
-    if (status != 1)
-      error ("could not create installation directory: %s", msg);
-    endif
-  endif
-  files(1) = [];
-  buildlist = fullfile (builddir, "octave_packages");
-  install (files, handle_deps, autoload, installdir, installdir, verbose,
-           buildlist, "", false);
-  unwind_protect
-    repackage (builddir, buildlist);
-  unwind_protect_cleanup
-    unload_packages ({"all"}, handle_deps, buildlist, "");
-    if (exist (installdir, "dir"))
-      rm_rf (installdir);
-    endif
-    if (exist (buildlist, "file"))
-      unlink (buildlist);
-    endif
-  end_unwind_protect
-endfunction
-
-function install (files, handle_deps, autoload, prefix, archprefix, verbose,
-                  local_list, global_list, global_install)
-
-  ## Check that the directory in prefix exist. If it doesn't: create it!
-  if (! exist (prefix, "dir"))
-    warning ("creating installation directory %s", prefix);
-    [status, msg] = mkdir (prefix);
-    if (status != 1)
-      error ("could not create installation directory: %s", msg);
-    endif
-  endif
-
-  ## Get the list of installed packages.
-  [local_packages, global_packages] = installed_packages (local_list,
-                                                          global_list);
-
-  installed_pkgs_lst = {local_packages{:}, global_packages{:}};
-
-  if (global_install)
-    packages = global_packages;
-  else
-    packages = local_packages;
-  endif
-
-  ## Uncompress the packages and read the DESCRIPTION files.
-  tmpdirs = packdirs = descriptions = {};
-  try
-    ## Warn about non existent files.
-    for i = 1:length (files)
-      if (isempty (glob(files{i})))
-        warning ("file %s does not exist", files{i});
-      endif
-    endfor
-
-    ## Unpack the package files and read the DESCRIPTION files.
-    files = glob (files);
-    packages_to_uninstall = [];
-    for i = 1:length (files)
-      tgz = files{i};
-
-      if (exist (tgz, "file"))
-        ## Create a temporary directory.
-        tmpdir = tmpnam ();
-        tmpdirs{end+1} = tmpdir;
-        if (verbose)
-          printf ("mkdir (%s)\n", tmpdir);
-        endif
-        [status, msg] = mkdir (tmpdir);
-        if (status != 1)
-          error ("couldn't create temporary directory: %s", msg);
-        endif
-
-        ## Uncompress the package.
-        if (verbose)
-          printf ("untar (%s, %s)\n", tgz, tmpdir);
-        endif
-        untar (tgz, tmpdir);
-
-        ## Get the name of the directories produced by tar.
-        [dirlist, err, msg] = readdir (tmpdir);
-        if (err)
-          error ("couldn't read directory produced by tar: %s", msg);
-        endif
-
-        if (length (dirlist) > 3)
-          error ("bundles of packages are not allowed");
-        endif
-      endif
-
-      ## The filename pointed to an uncompressed package to begin with.
-      if (exist (tgz, "dir"))
-        dirlist = {".", "..", tgz};
-      endif
-
-      if (exist (tgz, "file") || exist (tgz, "dir"))
-        ## The two first entries of dirlist are "." and "..".
-        if (exist (tgz, "file"))
-          packdir = fullfile (tmpdir, dirlist{3});
-        else
-          packdir = fullfile (pwd(), dirlist{3});
-        endif
-        packdirs{end+1} = packdir;
-
-        ## Make sure the package contains necessary files.
-        verify_directory (packdir);
-
-        ## Read the DESCRIPTION file.
-        filename = fullfile (packdir, "DESCRIPTION");
-        desc = get_description (filename);
-
-        ## Verify that package name corresponds with filename.
-        [dummy, nm] = fileparts (tgz);
-        if ((length (nm) >= length (desc.name))
-            && ! strcmp (desc.name, nm(1:length(desc.name))))
-          error ("package name '%s' doesn't correspond to its filename '%s'",
-                 desc.name, nm);
-        endif
-
-        ## Set default installation directory.
-        desc.dir = fullfile (prefix, cstrcat (desc.name, "-", desc.version));
-
-        ## Set default architectire dependent installation directory.
-        desc.archprefix = fullfile (archprefix, cstrcat (desc.name, "-",
-                                                         desc.version));
-
-        ## Save desc.
-        descriptions{end+1} = desc;
-
-        ## Are any of the new packages already installed?
-        ## If so we'll remove the old version.
-        for j = 1:length (packages)
-          if (strcmp (packages{j}.name, desc.name))
-            packages_to_uninstall(end+1) = j;
-          endif
-        endfor
-      endif
-    endfor
-  catch
-    ## Something went wrong, delete tmpdirs.
-    for i = 1:length (tmpdirs)
-      rm_rf (tmpdirs{i});
-    endfor
-    rethrow (lasterror ());
-  end_try_catch
-
-  ## Check dependencies.
-  if (handle_deps)
-    ok = true;
-    error_text = "";
-    for i = 1:length (descriptions)
-      desc = descriptions{i};
-      idx2 = setdiff (1:length(descriptions), i);
-      if (global_install)
-        ## Global installation is not allowed to have dependencies on locally
-        ## installed packages.
-        idx1 = setdiff (1:length(global_packages), packages_to_uninstall);
-        pseudo_installed_packages = {global_packages{idx1}, ...
-                                     descriptions{idx2}};
-      else
-        idx1 = setdiff (1:length(local_packages), packages_to_uninstall);
-        pseudo_installed_packages = {local_packages{idx1}, ...
-                                     global_packages{:}, ...
-                                     descriptions{idx2}};
-      endif
-      bad_deps = get_unsatisfied_deps (desc, pseudo_installed_packages);
-      ## Are there any unsatisfied dependencies?
-      if (! isempty (bad_deps))
-        ok = false;
-        for i = 1:length (bad_deps)
-          dep = bad_deps{i};
-          error_text = cstrcat (error_text, " ", desc.name, " needs ",
-                               dep.package, " ", dep.operator, " ",
-                               dep.version, "\n");
-        endfor
-      endif
-    endfor
-
-    ## Did we find any unsatisfied dependencies?
-    if (! ok)
-      error ("the following dependencies where unsatisfied:\n  %s", error_text);
-    endif
-  endif
-
-  ## Prepare each package for installation.
-  try
-    for i = 1:length (descriptions)
-      desc = descriptions{i};
-      pdir = packdirs{i};
-      prepare_installation (desc, pdir);
-      configure_make (desc, pdir, verbose);
-    endfor
-  catch
-    ## Something went wrong, delete tmpdirs.
-    for i = 1:length (tmpdirs)
-      rm_rf (tmpdirs{i});
-    endfor
-    rethrow (lasterror ());
-  end_try_catch
-
-  ## Uninstall the packages that will be replaced.
-  try
-    for i = packages_to_uninstall
-      if (global_install)
-        uninstall ({global_packages{i}.name}, false, verbose, local_list,
-                   global_list, global_install);
-      else
-        uninstall ({local_packages{i}.name}, false, verbose, local_list,
-                   global_list, global_install);
-      endif
-    endfor
-  catch
-    ## Something went wrong, delete tmpdirs.
-    for i = 1:length (tmpdirs)
-      rm_rf (tmpdirs{i});
-    endfor
-    rethrow (lasterror ());
-  end_try_catch
-
-  ## Install each package.
-  try
-    for i = 1:length (descriptions)
-      desc = descriptions{i};
-      pdir = packdirs{i};
-      copy_files (desc, pdir, global_install);
-      create_pkgadddel (desc, pdir, "PKG_ADD", global_install);
-      create_pkgadddel (desc, pdir, "PKG_DEL", global_install);
-      finish_installation (desc, pdir, global_install);
-      generate_lookfor_cache (desc);
-    endfor
-  catch
-    ## Something went wrong, delete tmpdirs.
-    for i = 1:length (tmpdirs)
-      rm_rf (tmpdirs{i});
-    endfor
-    for i = 1:length (descriptions)
-      rm_rf (descriptions{i}.dir);
-      rm_rf (getarchdir (descriptions{i}));
-    endfor
-    rethrow (lasterror ());
-  end_try_catch
-
-  ## Check if the installed directory is empty. If it is remove it
-  ## from the list.
-  for i = length (descriptions):-1:1
-    if (dirempty (descriptions{i}.dir, {"packinfo", "doc"})
-        && dirempty (getarchdir (descriptions{i})))
-      warning ("package %s is empty\n", descriptions{i}.name);
-      rm_rf (descriptions{i}.dir);
-      rm_rf (getarchdir (descriptions{i}));
-      descriptions(i) = [];
-    endif
-  endfor
-
-  ## If the package requested that it is autoloaded, or the installer
-  ## requested that it is, then mark the package as autoloaded.
-  for i = length (descriptions):-1:1
-    if (autoload > 0 || (autoload == 0 && isautoload (descriptions(i))))
-      fclose (fopen (fullfile (descriptions{i}.dir, "packinfo",
-                               ".autoload"), "wt"));
-      descriptions{i}.autoload = 1;
-    endif
-  endfor
-
-  ## Add the packages to the package list.
-  try
-    if (global_install)
-      idx = setdiff (1:length(global_packages), packages_to_uninstall);
-      global_packages = save_order ({global_packages{idx}, descriptions{:}});
-      save (global_list, "global_packages");
-      installed_pkgs_lst = {local_packages{:}, global_packages{:}};
-    else
-      idx = setdiff (1:length(local_packages), packages_to_uninstall);
-      local_packages = save_order ({local_packages{idx}, descriptions{:}});
-      save (local_list, "local_packages");
-      installed_pkgs_lst = {local_packages{:}, global_packages{:}};
-    endif
-  catch
-    ## Something went wrong, delete tmpdirs.
-    for i = 1:length (tmpdirs)
-      rm_rf (tmpdirs{i});
-    endfor
-    for i = 1:length (descriptions)
-      rm_rf (descriptions{i}.dir);
-    endfor
-    if (global_install)
-      printf ("error: couldn't append to %s\n", global_list);
-    else
-      printf ("error: couldn't append to %s\n", local_list);
-    endif
-    rethrow (lasterror ());
-  end_try_catch
-
-  ## All is well, let's clean up.
-  for i = 1:length (tmpdirs)
-    [status, msg] = rm_rf (tmpdirs{i});
-    if (status != 1)
-      warning ("couldn't clean up after my self: %s\n", msg);
-    endif
-  endfor
-
-  ## Add the newly installed packages to the path, so the user
-  ## can begin using them. Only load them if they are marked autoload.
-  if (length (descriptions) > 0)
-    idx = [];
-    for i = 1:length (descriptions)
-      if (isautoload (descriptions(i)))
-        nm = descriptions{i}.name;
-        for j = 1:length (installed_pkgs_lst)
-          if (strcmp (nm, installed_pkgs_lst{j}.name))
-            idx (end + 1) = j;
-            break;
-          endif
-        endfor
-      endif
-    endfor
-    load_packages_and_dependencies (idx, handle_deps, installed_pkgs_lst,
-                                    global_install);
-  endif
-
-  ## If there's a NEWS file, mention it
-  ## we are checking if desc exists too because it's possible to ge to this point
-  ## without creating it such as giving an invalid filename for the package
-  if (exist ("desc", "var") && exist (fullfile (desc.dir, "packinfo", "NEWS"), "file"))
-    printf ("For information about changes from previous versions of the %s package, run 'news (\"%s\")'.\n",
-            desc.name, desc.name);
-  endif
-
-endfunction
-
-function uninstall (pkgnames, handle_deps, verbose, local_list,
-                    global_list, global_install)
-  ## Get the list of installed packages.
-  [local_packages, global_packages] = installed_packages(local_list,
-                                                         global_list);
-  if (global_install)
-    installed_pkgs_lst = {local_packages{:}, global_packages{:}};
-  else
-    installed_pkgs_lst = local_packages;
-  endif
-
-  num_packages = length (installed_pkgs_lst);
-  delete_idx = [];
-  for i = 1:num_packages
-    cur_name = installed_pkgs_lst{i}.name;
-    if (any (strcmp (cur_name, pkgnames)))
-      delete_idx(end+1) = i;
-    endif
-  endfor
-
-  ## Are all the packages that should be uninstalled already installed?
-  if (length (delete_idx) != length (pkgnames))
-    if (global_install)
-      ## Try again for a locally installed package.
-      installed_pkgs_lst = local_packages;
-
-      num_packages = length (installed_pkgs_lst);
-      delete_idx = [];
-      for i = 1:num_packages
-        cur_name = installed_pkgs_lst{i}.name;
-        if (any (strcmp (cur_name, pkgnames)))
-          delete_idx(end+1) = i;
-        endif
-      endfor
-      if (length (delete_idx) != length (pkgnames))
-        ## FIXME: We should have a better error message.
-        warning ("some of the packages you want to uninstall are not installed");
-      endif
-    else
-      ## FIXME: We should have a better error message.
-      warning ("some of the packages you want to uninstall are not installed");
-    endif
-  endif
-
-  ## Compute the packages that will remain installed.
-  idx = setdiff (1:num_packages, delete_idx);
-  remaining_packages = {installed_pkgs_lst{idx}};
-
-  ## Check dependencies.
-  if (handle_deps)
-    error_text = "";
-    for i = 1:length (remaining_packages)
-      desc = remaining_packages{i};
-      bad_deps = get_unsatisfied_deps (desc, remaining_packages);
-
-      ## Will the uninstallation break any dependencies?
-      if (! isempty (bad_deps))
-        for i = 1:length (bad_deps)
-          dep = bad_deps{i};
-          error_text = cstrcat (error_text, " ", desc.name, " needs ",
-                               dep.package, " ", dep.operator, " ",
-                               dep.version, "\n");
-        endfor
-      endif
-    endfor
-
-    if (! isempty (error_text))
-      error ("the following dependencies where unsatisfied:\n  %s", error_text);
-    endif
-  endif
-
-  ## Delete the directories containing the packages.
-  for i = delete_idx
-    desc = installed_pkgs_lst{i};
-    ## If an 'on_uninstall.m' exist, call it!
-    if (exist (fullfile (desc.dir, "packinfo", "on_uninstall.m"), "file"))
-      wd = pwd ();
-      cd (fullfile (desc.dir, "packinfo"));
-      on_uninstall (desc);
-      cd (wd);
-    endif
-    ## Do the actual deletion.
-    if (desc.loaded)
-      rmpath (desc.dir);
-      if (exist (getarchdir (desc)))
-        rmpath (getarchdir (desc));
-      endif
-    endif
-    if (exist (desc.dir, "dir"))
-      [status, msg] = rm_rf (desc.dir);
-      if (status != 1)
-        error ("couldn't delete directory %s: %s", desc.dir, msg);
-      endif
-      [status, msg] = rm_rf (getarchdir (desc));
-      if (status != 1)
-        error ("couldn't delete directory %s: %s", getarchdir (desc), msg);
-      endif
-      if (dirempty (desc.archprefix))
-        rm_rf (desc.archprefix);
-      endif
-    else
-      warning ("directory %s previously lost", desc.dir);
-    endif
-  endfor
-
-  ## Write a new ~/.octave_packages.
-  if (global_install)
-    if (length (remaining_packages) == 0)
-      unlink (global_list);
-    else
-      global_packages = save_order (remaining_packages);
-      save (global_list, "global_packages");
-    endif
-  else
-    if (length (remaining_packages) == 0)
-      unlink (local_list);
-    else
-      local_packages = save_order (remaining_packages);
-      save (local_list, "local_packages");
-    endif
-  endif
-
-endfunction
-
-function [pkg_desc_list, flag] = describe (pkgnames, verbose,
-                                           local_list, global_list)
-
-  ## Get the list of installed packages.
-  installed_pkgs_lst = installed_packages(local_list, global_list);
-  num_packages = length (installed_pkgs_lst);
-
-
-  describe_all = false;
-  if (any (strcmp ("all", pkgnames)))
-    describe_all = true;
-    flag(1:num_packages) = {"Not Loaded"};
-    num_pkgnames = num_packages;
-  else
-    num_pkgnames = length (pkgnames);
-    flag(1:num_pkgnames) = {"Not installed"};
-  endif
-
-  for i = 1:num_packages
-    curr_name = installed_pkgs_lst{i}.name;
-    if (describe_all)
-      name_pos = i;
-    else
-      name_pos = find(strcmp (curr_name, pkgnames));
-    endif
-
-    if (! isempty (name_pos))
-      if (installed_pkgs_lst{i}.loaded)
-        flag{name_pos} = "Loaded";
-      else
-        flag{name_pos} = "Not loaded";
-      endif
-
-      pkg_desc_list{name_pos}.name = installed_pkgs_lst{i}.name;
-      pkg_desc_list{name_pos}.version = installed_pkgs_lst{i}.version;
-      pkg_desc_list{name_pos}.description = installed_pkgs_lst{i}.description;
-      pkg_desc_list{name_pos}.provides = parse_pkg_idx (installed_pkgs_lst{i}.dir);
-
-    endif
-  endfor
-
-  non_inst = find (strcmp (flag, "Not installed"));
-  if (! isempty (non_inst))
-    if (nargout < 2)
-      non_inst_str = sprintf (" %s ", pkgnames{non_inst});
-      error ("some packages are not installed: %s", non_inst_str);
-    else
-      pkg_desc_list{non_inst} = struct ("name", {}, "description",
-                                        {}, "provides", {});
-    endif
-  endif
-
-  if (nargout == 0)
-    for i = 1:num_pkgnames
-      print_package_description (pkg_desc_list{i}.name,
-                                 pkg_desc_list{i}.version,
-                                 pkg_desc_list{i}.provides,
-                                 pkg_desc_list{i}.description,
-                                 flag{i}, verbose);
-    endfor
-  endif
-
-endfunction
-
-## AUXILIARY FUNCTIONS
-
-## Read an INDEX file.
-function [pkg_idx_struct] = parse_pkg_idx (packdir)
-
-  index_file = fullfile (packdir, "packinfo", "INDEX");
-
-  if (! exist (index_file, "file"))
-    error ("could not find any INDEX file in directory %s, try 'pkg rebuild all' to generate missing INDEX files", packdir);
-  endif
-
-
-  [fid, msg] = fopen (index_file, "r");
-  if (fid == -1)
-    error ("the INDEX file %s could not be read: %s",
-           index_file, msg);
-  endif
-
-  cat_num = 1;
-  pkg_idx_struct{1}.category = "Uncategorized";
-  pkg_idx_struct{1}.functions = {};
-
-  line = fgetl (fid);
-  while (isempty (strfind (line, ">>")) && ! feof (fid))
-    line = fgetl (fid);
-  endwhile
-
-  while (! feof (fid) || line != -1)
-    if (! any (! isspace (line)) || line(1) == "#" || any (line == "="))
-      ## Comments,  blank lines or comments about unimplemented
-      ## functions: do nothing
-      ## FIXME: probably comments and pointers to external functions
-      ## could be treated better when printing to screen?
-    elseif (! isempty (strfind (line, ">>")))
-      ## Skip package name and description as they are in DESCRIPTION
-      ## already.
-    elseif (! isspace (line(1)))
-      ## Category.
-      if (! isempty (pkg_idx_struct{cat_num}.functions))
-        pkg_idx_struct{++cat_num}.functions = {};
-      endif
-      pkg_idx_struct{cat_num}.category = deblank (line);
-    else
-      ## Function names.
-      while (any (! isspace (line)))
-        [fun_name, line] = strtok (line);
-        pkg_idx_struct{cat_num}.functions{end+1} = deblank (fun_name);
-      endwhile
-    endif
-    line = fgetl (fid);
-  endwhile
-  fclose (fid);
-endfunction
-
-function print_package_description (pkg_name, pkg_ver, pkg_idx_struct,
-                                    pkg_desc, status, verbose)
-
-  printf ("---\nPackage name:\n\t%s\n", pkg_name);
-  printf ("Version:\n\t%s\n", pkg_ver);
-  printf ("Short description:\n\t%s\n", pkg_desc);
-  printf ("Status:\n\t%s\n", status);
-  if (verbose)
-    printf ("---\nProvides:\n");
-    for i = 1:length(pkg_idx_struct)
-      if (! isempty (pkg_idx_struct{i}.functions))
-        printf ("%s\n", pkg_idx_struct{i}.category);
-        for j = 1:length(pkg_idx_struct{i}.functions)
-          printf ("\t%s\n", pkg_idx_struct{i}.functions{j});
-        endfor
-      endif
-    endfor
-  endif
-
-endfunction
-
-
-function pth = absolute_pathname (pth)
-  [status, msg, msgid] = fileattrib (pth);
-  if (status != 1)
-    error ("could not find the file or path %s", pth);
-  else
-    pth = msg.Name;
-  endif
-endfunction
-
-function repackage (builddir, buildlist)
-  packages = installed_packages (buildlist, buildlist);
-
-  wd = pwd();
-  for i = 1 : length(packages)
-    pack = packages{i};
-    unwind_protect
-      cd (builddir);
-      mkdir (pack.name);
-      mkdir (fullfile (pack.name, "inst"));
-      copyfile (fullfile (pack.dir, "*"), fullfile (pack.name, "inst"));
-      movefile (fullfile (pack.name, "inst","packinfo", "*"), pack.name);
-      if (exist (fullfile (pack.name, "inst","packinfo", ".autoload"), "file"))
-        unlink (fullfile (pack.name, "inst","packinfo", ".autoload"));
-      endif
-      rmdir (fullfile (pack.name, "inst", "packinfo"));
-      if (exist (fullfile (pack.name, "inst", "doc"), "dir"))
-        movefile (fullfile (pack.name, "inst", "doc"), pack.name);
-      endif
-      if (exist (fullfile (pack.name, "inst", "bin"), "dir"))
-        movefile (fullfile (pack.name, "inst", "bin"), pack.name);
-      endif
-      archdir = fullfile (pack.archprefix, cstrcat (pack.name, "-",
-                          pack.version), getarch ());
-      if (exist (archdir, "dir"))
-        if (exist (fullfile (pack.name, "inst", "PKG_ADD"), "file"))
-          unlink (fullfile (pack.name, "inst", "PKG_ADD"));
-        endif
-        if (exist (fullfile (pack.name, "inst", "PKG_DEL"), "file"))
-          unlink (fullfile (pack.name, "inst", "PKG_DEL"));
-        endif
-        if (exist (fullfile (archdir, "PKG_ADD"), "file"))
-          movefile (fullfile (archdir, "PKG_ADD"),
-                    fullfile (pack.name, "PKG_ADD"));
-        endif
-        if (exist (fullfile (archdir, "PKG_DEL"), "file"))
-          movefile (fullfile (archdir, "PKG_DEL"),
-                    fullfile (pack.name, "PKG_DEL"));
-        endif
-      else
-        if (exist (fullfile (pack.name, "inst", "PKG_ADD"), "file"))
-          movefile (fullfile (pack.name, "inst", "PKG_ADD"),
-                    fullfile (pack.name, "PKG_ADD"));
-        endif
-        if (exist (fullfile (pack.name, "inst", "PKG_DEL"), "file"))
-          movefile (fullfile (pack.name, "inst", "PKG_DEL"),
-                    fullfile (pack.name, "PKG_DEL"));
-        endif
-      endif
-      tfile = cstrcat (pack.name, "-", pack.version, ".tar");
-      tar (tfile, pack.name);
-      try
-        gzip (tfile);
-        unlink (tfile);
-      catch
-        warning ("failed to compress %s", tfile);
-      end_try_catch
-    unwind_protect_cleanup
-      if (exist (pack.name, "dir"))
-        rm_rf (pack.name);
-      endif
-      cd (wd);
-    end_unwind_protect
-  endfor
-endfunction
-
-function auto = isautoload (desc)
-  auto = false;
-  if (isfield (desc{1}, "autoload"))
-    a = desc{1}.autoload;
-    if ((isnumeric (a) && a > 0)
-        || (ischar (a) && (strcmpi (a, "true")
-                         || strcmpi (a, "on")
-                         || strcmpi (a, "yes")
-                         || strcmpi (a, "1"))))
-      auto = true;
-    endif
-  endif
-endfunction
-
-function prepare_installation (desc, packdir)
-  ## Is there a pre_install to call?
-  if (exist (fullfile (packdir, "pre_install.m"), "file"))
-    wd = pwd ();
-    try
-      cd (packdir);
-      pre_install (desc);
-      cd (wd);
-    catch
-      cd (wd);
-      rethrow (lasterror ());
-    end_try_catch
-  endif
-
-  ## If the directory "inst" doesn't exist, we create it.
-  inst_dir = fullfile (packdir, "inst");
-  if (! exist (inst_dir, "dir"))
-    [status, msg] = mkdir (inst_dir);
-    if (status != 1)
-      rm_rf (desc.dir);
-      error ("the 'inst' directory did not exist and could not be created: %s",
-             msg);
-    endif
-  endif
-endfunction
-
-function configure_make (desc, packdir, verbose)
-  ## Perform ./configure, make, make install in "src".
-  if (exist (fullfile (packdir, "src"), "dir"))
-    src = fullfile (packdir, "src");
-    octave_bindir = octave_config_info ("bindir");
-    ver = version ();
-    mkoctfile_program = fullfile (octave_bindir, sprintf ("mkoctfile-%s", ver));
-    octave_config_program = fullfile (octave_bindir, sprintf ("octave-config-%s", ver));
-    octave_binary = fullfile (octave_bindir, sprintf ("octave-%s", ver));
-    cenv = {"MKOCTFILE"; mkoctfile_program;
-            "OCTAVE_CONFIG"; octave_config_program;
-            "OCTAVE"; octave_binary;
-            "INSTALLDIR"; desc.dir};
-    scenv = sprintf ("%s=\"%s\" ", cenv{:});
-    ## Configure.
-    if (exist (fullfile (src, "configure"), "file"))
-      flags = "";
-      if (isempty (getenv ("CC")))
-        flags = cstrcat (flags, " CC=\"", mkoctfile ("-p", "CC"), "\"");
-      endif
-      if (isempty (getenv ("CXX")))
-        flags = cstrcat (flags, " CXX=\"", mkoctfile ("-p", "CXX"), "\"");
-      endif
-      if (isempty (getenv ("AR")))
-        flags = cstrcat (flags, " AR=\"", mkoctfile ("-p", "AR"), "\"");
-      endif
-      if (isempty (getenv ("RANLIB")))
-        flags = cstrcat (flags, " RANLIB=\"", mkoctfile ("-p", "RANLIB"), "\"");
-      endif
-      [status, output] = shell (cstrcat ("cd '", src, "'; ", scenv,
-                                         "./configure --prefix=\"",
-                                         desc.dir, "\"", flags));
-      if (status != 0)
-        rm_rf (desc.dir);
-        error ("the configure script returned the following error: %s", output);
-      elseif (verbose)
-        printf("%s", output);
-      endif
-
-    endif
-
-    ## Make.
-    if (exist (fullfile (src, "Makefile"), "file"))
-      [status, output] = shell (cstrcat (scenv, "make -C '", src, "'"));
-      if (status != 0)
-        rm_rf (desc.dir);
-        error ("'make' returned the following error: %s", output);
-      elseif (verbose)
-        printf("%s", output);
-      endif
-    endif
-
-    ## Copy files to "inst" and "inst/arch" (this is instead of 'make
-    ## install').
-    files = fullfile (src, "FILES");
-    instdir = fullfile (packdir, "inst");
-    archdir = fullfile (packdir, "inst", getarch ());
-
-    ## Get file names.
-    if (exist (files, "file"))
-      [fid, msg] = fopen (files, "r");
-      if (fid < 0)
-        error ("couldn't open %s: %s", files, msg);
-      endif
-      filenames = char (fread (fid))';
-      fclose (fid);
-      if (filenames(end) == "\n")
-        filenames(end) = [];
-      endif
-      filenames = split_by (filenames, "\n");
-      delete_idx =  [];
-      for i = 1:length (filenames)
-        if (! all (isspace (filenames{i})))
-          filenames{i} = fullfile (src, filenames{i});
-        else
-          delete_idx(end+1) = i;
-        endif
-      endfor
-      filenames(delete_idx) = [];
-    else
-      m = dir (fullfile (src, "*.m"));
-      oct = dir (fullfile (src, "*.oct"));
-      mex = dir (fullfile (src, "*.mex"));
-
-      filenames = cellfun (@(x) fullfile (src, x),
-                           {m.name, oct.name, mex.name},
-                           "uniformoutput", false);
-    endif
-
-    ## Split into architecture dependent and independent files.
-    if (isempty (filenames))
-      idx = [];
-    else
-      idx = cellfun ("is_architecture_dependent", filenames);
-    endif
-    archdependent = filenames (idx);
-    archindependent = filenames (!idx);
-
-    ## Copy the files.
-    if (! all (isspace ([filenames{:}])))
-        if (! exist (instdir, "dir"))
-          mkdir (instdir);
-        endif
-        if (! all (isspace ([archindependent{:}])))
-          if (verbose)
-            printf ("copyfile");
-            printf (" %s", archindependent{:});
-            printf ("%s\n", instdir);
-          endif
-          [status, output] = copyfile (archindependent, instdir);
-          if (status != 1)
-            rm_rf (desc.dir);
-            error ("Couldn't copy files from 'src' to 'inst': %s", output);
-          endif
-        endif
-        if (! all (isspace ([archdependent{:}])))
-          if (verbose)
-            printf ("copyfile");
-            printf (" %s", archdependent{:});
-            printf (" %s\n", archdir);
-          endif
-          if (! exist (archdir, "dir"))
-            mkdir (archdir);
-          endif
-          [status, output] = copyfile (archdependent, archdir);
-          if (status != 1)
-            rm_rf (desc.dir);
-            error ("Couldn't copy files from 'src' to 'inst': %s", output);
-          endif
-        endif
-    endif
-  endif
-endfunction
-
-function pkg = extract_pkg (nm, pat)
-  fid = fopen (nm, "rt");
-  pkg = "";
-  if (fid >= 0)
-    while (! feof (fid))
-      ln = fgetl (fid);
-      if (ln > 0)
-        t = regexp (ln, pat, "tokens");
-        if (! isempty (t))
-          pkg = cstrcat (pkg, "\n", t{1}{1});
-        endif
-      endif
-    endwhile
-    if (! isempty (pkg))
-      pkg = cstrcat (pkg, "\n");
-    endif
-    fclose (fid);
-  endif
-endfunction
-
-function create_pkgadddel (desc, packdir, nm, global_install)
-  instpkg = fullfile (desc.dir, nm);
-  instfid = fopen (instpkg, "wt");
-  ## If it is exists, most of the  PKG_* file should go into the
-  ## architecture dependent directory so that the autoload/mfilename
-  ## commands work as expected. The only part that doesn't is the
-  ## part in the main directory.
-  archdir = fullfile (getarchprefix (desc), cstrcat (desc.name, "-",
-                      desc.version), getarch ());
-  if (exist (getarchdir (desc, global_install), "dir"))
-    archpkg = fullfile (getarchdir (desc, global_install), nm);
-    archfid = fopen (archpkg, "at");
-  else
-    archpkg = instpkg;
-    archfid = instfid;
-  endif
-
-  if (archfid >= 0 && instfid >= 0)
-    ## Search all dot-m files for PKG commands.
-    lst = dir (fullfile (packdir, "inst", "*.m"));
-    for i = 1:length (lst)
-      nam = fullfile (packdir, "inst", lst(i).name);
-      fwrite (instfid, extract_pkg (nam, ['^[#%][#%]* *' nm ': *(.*)$']));
-    endfor
-
-    ## Search all C++ source files for PKG commands.
-    lst = dir (fullfile (packdir, "src", "*.cc"));
-    for i = 1:length (lst)
-      nam = fullfile (packdir, "src", lst(i).name);
-      fwrite (archfid, extract_pkg (nam, ['^//* *' nm ': *(.*)$']));
-      fwrite (archfid, extract_pkg (nam, ['^/\** *' nm ': *(.*) *\*/$']));
-    endfor
-
-    ## Add developer included PKG commands.
-    packdirnm = fullfile (packdir, nm);
-    if (exist (packdirnm, "file"))
-      fid = fopen (packdirnm, "rt");
-      if (fid >= 0)
-        while (! feof (fid))
-          ln = fgets (fid);
-          if (ln > 0)
-            fwrite (archfid, ln);
-          endif
-        endwhile
-        fclose (fid);
-      endif
-    endif
-
-    ## If the files is empty remove it.
-    fclose (instfid);
-    t = dir (instpkg);
-    if (t.bytes <= 0)
-      unlink (instpkg);
-    endif
-
-    if (instfid != archfid)
-      fclose (archfid);
-      t = dir (archpkg);
-      if (t.bytes <= 0)
-        unlink (archpkg);
-      endif
-    endif
-  endif
-endfunction
-
-function copy_files (desc, packdir, global_install)
-  ## Create the installation directory.
-  if (! exist (desc.dir, "dir"))
-    [status, output] = mkdir (desc.dir);
-    if (status != 1)
-      error ("couldn't create installation directory %s : %s",
-      desc.dir, output);
-    endif
-  endif
-
-  octfiledir = getarchdir (desc);
-
-  ## Copy the files from "inst" to installdir.
-  instdir = fullfile (packdir, "inst");
-  if (! dirempty (instdir))
-    [status, output] = copyfile (fullfile (instdir, "*"), desc.dir);
-    if (status != 1)
-      rm_rf (desc.dir);
-      error ("couldn't copy files to the installation directory");
-    endif
-    if (exist (fullfile (desc.dir, getarch ()), "dir")
-        && ! strcmp (fullfile (desc.dir, getarch ()), octfiledir))
-      if (! exist (octfiledir, "dir"))
-        ## Can be required to create upto three levels of dirs.
-        octm1 = fileparts (octfiledir);
-        if (! exist (octm1, "dir"))
-          octm2 = fileparts (octm1);
-          if (! exist (octm2, "dir"))
-            octm3 = fileparts (octm2);
-            if (! exist (octm3, "dir"))
-              [status, output] = mkdir (octm3);
-              if (status != 1)
-                rm_rf (desc.dir);
-                error ("couldn't create installation directory %s : %s",
-                       octm3, output);
-              endif
-            endif
-            [status, output] = mkdir (octm2);
-            if (status != 1)
-              rm_rf (desc.dir);
-              error ("couldn't create installation directory %s : %s",
-                     octm2, output);
-            endif
-          endif
-          [status, output] = mkdir (octm1);
-          if (status != 1)
-            rm_rf (desc.dir);
-            error ("couldn't create installation directory %s : %s",
-                   octm1, output);
-          endif
-        endif
-        [status, output] = mkdir (octfiledir);
-        if (status != 1)
-          rm_rf (desc.dir);
-          error ("couldn't create installation directory %s : %s",
-          octfiledir, output);
-        endif
-      endif
-      [status, output] = movefile (fullfile (desc.dir, getarch (), "*"),
-                                   octfiledir);
-      rm_rf (fullfile (desc.dir, getarch ()));
-
-      if (status != 1)
-        rm_rf (desc.dir);
-        rm_rf (octfiledir);
-        error ("couldn't copy files to the installation directory");
-      endif
-    endif
-
-  endif
-
-  ## Create the "packinfo" directory.
-  packinfo = fullfile (desc.dir, "packinfo");
-  [status, msg] = mkdir (packinfo);
-  if (status != 1)
-    rm_rf (desc.dir);
-    rm_rf (octfiledir);
-    error ("couldn't create packinfo directory: %s", msg);
-  endif
-
-  packinfo_copy_file ("DESCRIPTION", "required", packdir, packinfo, desc, octfiledir);
-  packinfo_copy_file ("COPYING", "required", packdir, packinfo, desc, octfiledir);
-
-  packinfo_copy_file ("NEWS", "optional", packdir, packinfo, desc, octfiledir);
-  packinfo_copy_file ("ONEWS", "optional", packdir, packinfo, desc, octfiledir);
-  packinfo_copy_file ("ChangeLog", "optional", packdir, packinfo, desc, octfiledir);
-
-  ## Is there an INDEX file to copy or should we generate one?
-  index_file = fullfile (packdir, "INDEX");
-  if (exist(index_file, "file"))
-    packinfo_copy_file ("INDEX", "required", packdir, packinfo, desc, octfiledir);
-  else
-    try
-      write_index (desc, fullfile (packdir, "inst"),
-                   fullfile (packinfo, "INDEX"), global_install);
-    catch
-      rm_rf (desc.dir);
-      rm_rf (octfiledir);
-      rethrow (lasterror ());
-    end_try_catch
-  endif
-
-  ## Is there an 'on_uninstall.m' to install?
-  packinfo_copy_file ("on_uninstall.m", "optional", packdir, packinfo, desc, octfiledir);
-
-  ## Is there a doc/ directory that needs to be installed?
-  docdir = fullfile (packdir, "doc");
-  if (exist (docdir, "dir") && ! dirempty (docdir))
-    [status, output] = copyfile (docdir, desc.dir);
-  endif
-
-  ## Is there a bin/ directory that needs to be installed?
-  ## FIXME: Need to treat architecture dependent files in bin/
-  bindir = fullfile (packdir, "bin");
-  if (exist (bindir, "dir") && ! dirempty (bindir))
-    [status, output] = copyfile (bindir, desc.dir);
-  endif
-endfunction
-
-function packinfo_copy_file (filename, requirement, packdir, packinfo, desc, octfiledir)
-  filepath = fullfile (packdir, filename);
-  if (!exist (filepath, "file") && strcmpi (requirement, "optional"))
-    ## do nothing, it's still OK
-  else
-    [status, output] = copyfile (filepath, packinfo);
-    if (status != 1)
-      rm_rf (desc.dir);
-      rm_rf (octfiledir);
-      error ("Couldn't copy %s file: %s", filename, output);
-    endif
-  endif
-endfunction
-
-function finish_installation (desc, packdir, global_install)
-  ## Is there a post-install to call?
-  if (exist (fullfile (packdir, "post_install.m"), "file"))
-    wd = pwd ();
-    try
-      cd (packdir);
-      post_install (desc);
-      cd (wd);
-    catch
-      cd (wd);
-      rm_rf (desc.dir);
-      rm_rf (getarchdir (desc), global_install);
-      rethrow (lasterror ());
-    end_try_catch
-  endif
-endfunction
-
-function generate_lookfor_cache (desc)
-  dirs = split_by (genpath (desc.dir), pathsep ());
-  for i = 1 : length (dirs)
-    gen_doc_cache (fullfile (dirs{i}, "doc-cache"), dirs{i});
-  endfor
-endfunction
-
-## Make sure the package contains the essential files.
-function verify_directory (dir)
-  needed_files = {"COPYING", "DESCRIPTION"};
-  for f = needed_files
-    if (! exist (fullfile (dir, f{1}), "file"))
-      error ("package is missing file: %s", f{1});
-    endif
-  endfor
-endfunction
-
-## Parse the DESCRIPTION file.
-function desc = get_description (filename)
-  [fid, msg] = fopen (filename, "r");
-  if (fid == -1)
-    error ("the DESCRIPTION file %s could not be read: %s", filename, msg);
-  endif
-
-  desc = struct ();
-
-  line = fgetl (fid);
-  while (line != -1)
-    if (line(1) == "#")
-      ## Comments, do nothing.
-    elseif (isspace(line(1)))
-      ## Continuation lines
-      if (exist ("keyword", "var") && isfield (desc, keyword))
-        desc.(keyword) = cstrcat (desc.(keyword), " ", rstrip(line));
-      endif
-    else
-      ## Keyword/value pair
-      colon = find (line == ":");
-      if (length (colon) == 0)
-        disp ("skipping line");
-      else
-        colon = colon(1);
-        keyword = tolower (strip (line(1:colon-1)));
-        value = strip (line (colon+1:end));
-        if (length (value) == 0)
-            fclose (fid);
-            error ("The keyword '%s' of the package '%s' has an empty value",
-                    keyword, desc.name);
-        endif
-        desc.(keyword) = value;
-      endif
-    endif
-    line = fgetl (fid);
-  endwhile
-  fclose (fid);
-
-  ## Make sure all is okay.
-  needed_fields = {"name", "version", "date", "title", ...
-                   "author", "maintainer", "description"};
-  for f = needed_fields
-    if (! isfield (desc, f{1}))
-      error ("description is missing needed field %s", f{1});
-    endif
-  endfor
-  desc.version = fix_version (desc.version);
-  if (isfield (desc, "depends"))
-    desc.depends = fix_depends (desc.depends);
-  else
-    desc.depends = "";
-  endif
-  desc.name = tolower (desc.name);
-endfunction
-
-## Make sure the version string v is a valid x.y.z version string
-## Examples: "0.1" => "0.1.0", "monkey" => error(...).
-function out = fix_version (v)
-  dots = find (v == ".");
-  if (length (dots) == 1)
-    major = str2num (v(1:dots-1));
-    minor = str2num (v(dots+1:end));
-    if (length (major) != 0 && length (minor) != 0)
-      out = sprintf ("%d.%d.0", major, minor);
-      return;
-    endif
-  elseif (length (dots) == 2)
-    major = str2num (v(1:dots(1)-1));
-    minor = str2num (v(dots(1)+1:dots(2)-1));
-    rev = str2num (v(dots(2)+1:end));
-    if (length (major) != 0 && length (minor) != 0 && length (rev) != 0)
-      out = sprintf ("%d.%d.%d", major, minor, rev);
-      return;
-    endif
-  endif
-  error ("bad version string: %s", v);
-endfunction
-
-## Make sure the depends field is of the right format.
-## This function returns a cell of structures with the following fields:
-##   package, version, operator
-function deps_cell = fix_depends (depends)
-  deps = split_by (tolower (depends), ",");
-  deps_cell = cell (1, length (deps));
-
-  ## For each dependency.
-  for i = 1:length (deps)
-    dep = deps{i};
-    lpar = find (dep == "(");
-    rpar = find (dep == ")");
-    ## Does the dependency specify a version
-    ## Example: package(>= version).
-    if (length (lpar) == 1 && length (rpar) == 1)
-      package = tolower (strip (dep(1:lpar-1)));
-      sub = dep(lpar(1)+1:rpar(1)-1);
-      parts = strsplit (sub, " ", true);
-      if (length (parts) != 2)
-        error ("incorrect syntax for dependency '%s' in the DESCRIPTION file\n",
-               dep);
-      endif
-      operator = parts{1};
-      if (! any (strcmp (operator, {">", ">=", "<=", "<", "=="})))
-        error ("unsupported operator: %s", operator);
-      endif
-      version  = fix_version (parts{2});
-
-  ## If no version is specified for the dependency
-  ## we say that the version should be greater than
-  ## or equal to "0.0.0".
-  else
-    package = tolower (strip (dep));
-    operator = ">=";
-    version  = "0.0.0";
-  endif
-  deps_cell{i} = struct ("package", package, "operator", operator,
-                         "version", version);
-  endfor
-endfunction
-
-## Strip the text of spaces from the right
-## Example: "  hello world  " => "  hello world"
-## FIXME -- is this the same as deblank?
-function text = rstrip (text)
-  chars = find (! isspace (text));
-  if (length (chars) > 0)
-    ## FIXME: shouldn't it be text = text(1:chars(end));
-    text = text (chars(1):end);
-  else
-    text = "";
-  endif
-endfunction
-
-## Strip the text of spaces from the left and the right.
-## Example: "  hello world  " => "hello world"
-function text = strip (text)
-  chars = find (! isspace (text));
-  if (length (chars) > 0)
-    text = text(chars(1):chars(end));
-  else
-    text = "";
-  endif
-endfunction
-
-## Split the text into a cell array of strings by sep.
-## Example: "A, B" => {"A", "B"} (with sep = ",")
-function out = split_by (text, sep)
-  out = strtrim (strsplit (text, sep));
-endfunction
-
-## Create an INDEX file for a package that doesn't provide one.
-##   'desc'  describes the package.
-##   'dir'   is the 'inst' directory in temporary directory.
-##   'index_file' is the name (including path) of resulting INDEX file.
-function write_index (desc, dir, index_file, global_install)
-  ## Get names of functions in dir
-  [files, err, msg] = readdir (dir);
-  if (err)
-    error ("couldn't read directory %s: %s", dir, msg);
-  endif
-
-  ## Get classes in dir
-  class_idx = strmatch ("@", files);
-  for k = 1:length (class_idx)
-    class_name = files {class_idx (k)};
-    class_dir = fullfile (dir, class_name);
-    if (exist (class_dir, "dir"))
-      [files2, err, msg] = readdir (class_dir);
-      if (err)
-        error ("couldn't read directory %s: %s", class_dir, msg);
-      endif
-      files2 = strcat (class_name, filesep (), files2);
-      files = [files; files2];
-    endif
-  endfor
-
-  ## Check for architecture dependent files.
-  tmpdir = getarchdir (desc);
-  if (exist (tmpdir, "dir"))
-    [files2, err, msg] = readdir (tmpdir);
-    if (err)
-      error ("couldn't read directory %s: %s", tmpdir, msg);
-    endif
-    files = [files; files2];
-  endif
-
-  functions = {};
-  for i = 1:length (files)
-    file = files{i};
-    lf = length (file);
-    if (lf > 2 && strcmp (file(end-1:end), ".m"))
-      functions{end+1} = file(1:end-2);
-    elseif (lf > 4 && strcmp (file(end-3:end), ".oct"))
-      functions{end+1} = file(1:end-4);
-    endif
-  endfor
-
-  ## Does desc have a categories field?
-  if (! isfield (desc, "categories"))
-    error ("the DESCRIPTION file must have a Categories field, when no INDEX file is given");
-  endif
-  categories = split_by (desc.categories, ",");
-  if (length (categories) < 1)
-      error ("the Category field is empty");
-  endif
-
-  ## Write INDEX.
-  fid = fopen (index_file, "w");
-  if (fid == -1)
-    error ("couldn't open %s for writing", index_file);
-  endif
-  fprintf (fid, "%s >> %s\n", desc.name, desc.title);
-  fprintf (fid, "%s\n", categories{1});
-  fprintf (fid, "  %s\n", functions{:});
-  fclose (fid);
-endfunction
-
-function bad_deps = get_unsatisfied_deps (desc, installed_pkgs_lst)
-  bad_deps = {};
-
-  ## For each dependency.
-  for i = 1:length (desc.depends)
-    dep = desc.depends{i};
-
-    ## Is the current dependency Octave?
-    if (strcmp (dep.package, "octave"))
-      if (! compare_versions (OCTAVE_VERSION, dep.version, dep.operator))
-        bad_deps{end+1} = dep;
-      endif
-      ## Is the current dependency not Octave?
-    else
-      ok = false;
-      for i = 1:length (installed_pkgs_lst)
-        cur_name = installed_pkgs_lst{i}.name;
-        cur_version = installed_pkgs_lst{i}.version;
-        if (strcmp (dep.package, cur_name)
-            && compare_versions (cur_version, dep.version, dep.operator))
-          ok = true;
-          break;
-        endif
-      endfor
-      if (! ok)
-        bad_deps{end+1} = dep;
-      endif
-    endif
-  endfor
-endfunction
-
-function [out1, out2] = installed_packages (local_list, global_list)
-  ## Get the list of installed packages.
-  try
-    local_packages = load (local_list).local_packages;
-  catch
-    local_packages = {};
-  end_try_catch
-  try
-    global_packages = load (global_list).global_packages;
-  catch
-    global_packages = {};
-  end_try_catch
-  installed_pkgs_lst = {local_packages{:}, global_packages{:}};
-
-  ## Eliminate duplicates in the installed package list.
-  ## Locally installed packages take precedence.
-  dup = [];
-  for i = 1:length (installed_pkgs_lst)
-    if (find (dup, i))
-      continue;
-    endif
-    for j = (i+1):length (installed_pkgs_lst)
-      if (find (dup, j))
-        continue;
-      endif
-      if (strcmp (installed_pkgs_lst{i}.name, installed_pkgs_lst{j}.name))
-        dup = [dup, j];
-      endif
-    endfor
-  endfor
-  if (! isempty(dup))
-    installed_pkgs_lst(dup) = [];
-  endif
-
-  ## Now check if the package is loaded.
-  tmppath = strrep (path(), "\\", "/");
-  for i = 1:length (installed_pkgs_lst)
-    if (findstr (tmppath, strrep (installed_pkgs_lst{i}.dir, "\\", "/")))
-      installed_pkgs_lst{i}.loaded = true;
-    else
-      installed_pkgs_lst{i}.loaded = false;
-    endif
-  endfor
-  for i = 1:length (local_packages)
-    if (findstr (tmppath, strrep (local_packages{i}.dir, "\\", "/")))
-      local_packages{i}.loaded = true;
-    else
-      local_packages{i}.loaded = false;
-    endif
-  endfor
-  for i = 1:length (global_packages)
-    if (findstr (tmppath, strrep (global_packages{i}.dir, "\\", "/")))
-      global_packages{i}.loaded = true;
-    else
-      global_packages{i}.loaded = false;
-    endif
-  endfor
-
-  ## Should we return something?
-  if (nargout == 2)
-    out1 = local_packages;
-    out2 = global_packages;
-    return;
-  elseif (nargout == 1)
-    out1 = installed_pkgs_lst;
-    return;
-  endif
-
-  ## We shouldn't return something, so we'll print something.
-  num_packages = length (installed_pkgs_lst);
-  if (num_packages == 0)
-    printf ("no packages installed.\n");
-    return;
-  endif
-
-  ## Compute the maximal lengths of name, version, and dir.
-  h1 = "Package Name";
-  h2 = "Version";
-  h3 = "Installation directory";
-  max_name_length = length (h1);
-  max_version_length = length (h2);
-  names = cell (num_packages, 1);
-  for i = 1:num_packages
-    max_name_length = max (max_name_length,
-                           length (installed_pkgs_lst{i}.name));
-    max_version_length = max (max_version_length,
-                              length (installed_pkgs_lst{i}.version));
-    names{i} = installed_pkgs_lst{i}.name;
-  endfor
-  max_dir_length = terminal_size()(2) - max_name_length - ...
-                                             max_version_length - 7;
-  if (max_dir_length < 20)
-     max_dir_length = Inf;
-  endif
-
-  h1 = postpad (h1, max_name_length + 1, " ");
-  h2 = postpad (h2, max_version_length, " ");;
-
-  ## Print a header.
-  header = sprintf("%s | %s | %s\n", h1, h2, h3);
-  printf (header);
-  tmp = sprintf (repmat ("-", 1, length(header)-1));
-  tmp(length(h1)+2) = "+";
-  tmp(length(h1)+length(h2)+5) = "+";
-  printf ("%s\n", tmp);
-
-  ## Print the packages.
-  format = sprintf ("%%%ds %%1s| %%%ds | %%s\n", max_name_length,
-                    max_version_length);
-  [dummy, idx] = sort (names);
-  for i = 1:num_packages
-    cur_name = installed_pkgs_lst{idx(i)}.name;
-    cur_version = installed_pkgs_lst{idx(i)}.version;
-    cur_dir = installed_pkgs_lst{idx(i)}.dir;
-    if (length (cur_dir) > max_dir_length)
-      first_char = length (cur_dir) - max_dir_length + 4;
-      first_filesep = strfind (cur_dir(first_char:end), filesep());
-      if (! isempty (first_filesep))
-        cur_dir = cstrcat ("...",
-                          cur_dir((first_char + first_filesep(1) - 1):end));
-      else
-        cur_dir = cstrcat ("...", cur_dir(first_char:end));
-      endif
-    endif
-    if (installed_pkgs_lst{idx(i)}.loaded)
-      cur_loaded = "*";
-    else
-      cur_loaded = " ";
-    endif
-    printf (format, cur_name, cur_loaded, cur_version, cur_dir);
-  endfor
-endfunction
-
-function load_packages (files, handle_deps, local_list, global_list)
-  installed_pkgs_lst = installed_packages (local_list, global_list);
-  num_packages = length (installed_pkgs_lst);
-
-  ## Read package names and installdirs into a more convenient format.
-  pnames = pdirs = cell (1, num_packages);
-  for i = 1:num_packages
-    pnames{i} = installed_pkgs_lst{i}.name;
-    pdirs{i} = installed_pkgs_lst{i}.dir;
-  endfor
-
-  ## Load all.
-  if (length (files) == 1 && strcmp (files{1}, "all"))
-    idx = [1:length(installed_pkgs_lst)];
-  ## Load auto.
-  elseif (length (files) == 1 && strcmp (files{1}, "auto"))
-    idx = [];
-    for i = 1:length (installed_pkgs_lst)
-      if (exist (fullfile (pdirs{i}, "packinfo", ".autoload"), "file"))
-        idx (end + 1) = i;
-      endif
-    endfor
-  ## Load package_name1 ...
-  else
-    idx = [];
-    for i = 1:length (files)
-      idx2 = find (strcmp (pnames, files{i}));
-      if (! any (idx2))
-          error ("package %s is not installed", files{i});
-      endif
-      idx (end + 1) = idx2;
-    endfor
-  endif
-
-  ## Load the packages, but take care of the ordering of dependencies.
-  load_packages_and_dependencies (idx, handle_deps, installed_pkgs_lst, true);
-endfunction
-
-function unload_packages (files, handle_deps, local_list, global_list)
-  installed_pkgs_lst = installed_packages (local_list, global_list);
-  num_packages = length (installed_pkgs_lst);
-
-  ## Read package names and installdirs into a more convenient format.
-  pnames = pdirs = cell (1, num_packages);
-  for i = 1:num_packages
-    pnames{i} = installed_pkgs_lst{i}.name;
-    pdirs{i} = installed_pkgs_lst{i}.dir;
-    pdeps{i} = installed_pkgs_lst{i}.depends;
-  endfor
-
-  ## Get the current octave path.
-  p = split_by (path(), pathsep ());
-
-  if (length (files) == 1 && strcmp (files{1}, "all"))
-    ## Unload all.
-    dirs = pdirs;
-    desc = installed_pkgs_lst;
-  else
-    ## Unload package_name1 ...
-    dirs = {};
-    desc = {};
-    for i = 1:length (files)
-      idx = strcmp (pnames, files{i});
-      if (! any (idx))
-        error ("package %s is not installed", files{i});
-      endif
-        dirs{end+1} = pdirs{idx};
-        desc{end+1} = installed_pkgs_lst{idx};
-      endfor
-  endif
-
-  ## Check for architecture dependent directories.
-  archdirs = {};
-  for i = 1:length (dirs)
-    tmpdir = getarchdir (desc{i});
-    if (exist (tmpdir, "dir"))
-      archdirs{end+1} = dirs{i};
-      archdirs{end+1} = tmpdir;
-    else
-      archdirs{end+1} = dirs{i};
-    endif
-  endfor
-
-  ## Unload the packages.
-  for i = 1:length (archdirs)
-    d = archdirs{i};
-    idx = strcmp (p, d);
-    if (any (idx))
-      rmpath (d);
-      ## FIXME: We should also check if we need to remove items from
-      ## EXEC_PATH.
-    endif
-  endfor
-endfunction
-
-function [status_out, msg_out] = rm_rf (dir)
-  if (exist (dir))
-    crr = confirm_recursive_rmdir (false, "local");
-    [status, msg] = rmdir (dir, "s");
-  else
-    status = 1;
-    msg = "";
-  endif
-  if (nargout > 0)
-    status_out = status;
-  endif
-  if (nargout > 1)
-    msg_out = msg;
-  endif
-endfunction
-
-function emp = dirempty (nm, ign)
-  if (exist (nm, "dir"))
-    if (nargin < 2)
-      ign = {".", ".."};
-    else
-      ign = [{".", ".."}, ign];
-    endif
-    l = dir (nm);
-    for i = 1:length (l)
-      found = false;
-      for j = 1:length (ign)
-        if (strcmp (l(i).name, ign{j}))
-          found = true;
-          break;
-        endif
-      endfor
-      if (! found)
-        emp = false;
-        return
-      endif
-    endfor
-    emp = true;
-  else
-    emp = true;
-  endif
-endfunction
-
-function arch = getarch ()
-  persistent _arch = cstrcat (octave_config_info ("canonical_host_type"),
-                              "-", octave_config_info ("api_version"));
-  arch = _arch;
-endfunction
-
-function archprefix = getarchprefix (desc, global_install)
-  if ((nargin == 2 && global_install) || (nargin < 2 && issuperuser ()))
-    archprefix = fullfile (octave_config_info ("libdir"), "octave",
-                           "packages", cstrcat(desc.name, "-", desc.version));
-  else
-    archprefix = desc.dir;
-  endif
-endfunction
-
-function archdir = getarchdir (desc)
-  archdir = fullfile (desc.archprefix, getarch());
-endfunction
-
-function s = issuperuser ()
-  if ((ispc () && ! isunix ()) || (geteuid() == 0))
-    s = true;
-  else
-    s = false;
-  endif
-endfunction
-
-function [status, output] = shell (cmd)
-  persistent have_sh;
-
-  cmd = strrep (cmd, "\\", "/");
-  if (ispc () && ! isunix ())
-    if (isempty(have_sh))
-      if (system("sh.exe -c \"exit\""))
-        have_sh = false;
-      else
-        have_sh = true;
-      endif
-    endif
-    if (have_sh)
-      [status, output] = system (cstrcat ("sh.exe -c \"", cmd, "\""));
-    else
-      error ("Can not find the command shell");
-    endif
-  else
-    [status, output] = system (cmd);
-  endif
-endfunction
-
-function newdesc = save_order (desc)
-  newdesc = {};
-  for i = 1 : length(desc)
-    deps = desc{i}.depends;
-    if (isempty (deps)
-        || (length (deps) == 1 && strcmp(deps{1}.package, "octave")))
-      newdesc {end + 1} = desc{i};
-    else
-      tmpdesc = {};
-      for k = 1 : length (deps)
-        for j = 1 : length (desc)
-          if (strcmp (desc{j}.name, deps{k}.package))
-            tmpdesc{end+1} = desc{j};
-            break;
-          endif
-        endfor
-      endfor
-      if (! isempty (tmpdesc))
-        newdesc = {newdesc{:}, save_order(tmpdesc){:}, desc{i}};
-      else
-        newdesc{end+1} = desc{i};
-      endif
-    endif
-  endfor
-  ## Eliminate the duplicates.
-  idx = [];
-  for i = 1 : length (newdesc)
-    for j = (i + 1) : length (newdesc)
-      if (strcmp (newdesc{i}.name, newdesc{j}.name))
-        idx (end + 1) = j;
-      endif
-    endfor
-  endfor
-  newdesc(idx) = [];
-endfunction
-
-function load_packages_and_dependencies (idx, handle_deps, installed_pkgs_lst,
-                                         global_install)
-  idx = load_package_dirs (idx, [], handle_deps, installed_pkgs_lst);
-  dirs = {};
-  execpath = EXEC_PATH ();
-  for i = idx;
-    ndir = installed_pkgs_lst{i}.dir;
-    dirs{end+1} = ndir;
-    if (exist (fullfile (dirs{end}, "bin"), "dir"))
-      execpath = cstrcat (execpath, pathsep (), fullfile (dirs{end}, "bin"));
-    endif
-    tmpdir = getarchdir (installed_pkgs_lst{i});
-    if (exist (tmpdir, "dir"))
-      dirs{end + 1} = tmpdir;
-      if (exist (fullfile (dirs{end}, "bin"), "dir"))
-        execpath = cstrcat (execpath, pathsep (), fullfile (dirs{end}, "bin"));
-      endif
-    endif
-  endfor
-
-  ## Load the packages.
-  if (length (dirs) > 0)
-    addpath (dirs{:});
-  endif
-
-  ## Add the binaries to exec_path.
-  if (! strcmp (EXEC_PATH, execpath))
-    EXEC_PATH (execpath);
-  endif
-endfunction
-
-function idx = load_package_dirs (lidx, idx, handle_deps, installed_pkgs_lst)
-  for i = lidx
-    if (isfield (installed_pkgs_lst{i}, "loaded")
-        && installed_pkgs_lst{i}.loaded)
-      continue;
-    else
-      if (handle_deps)
-        deps = installed_pkgs_lst{i}.depends;
-        if ((length (deps) > 1)
-            || (length (deps) == 1 && ! strcmp(deps{1}.package, "octave")))
-          tmplidx = [];
-          for k = 1 : length (deps)
-            for j = 1 : length (installed_pkgs_lst)
-              if (strcmp (installed_pkgs_lst{j}.name, deps{k}.package))
-                tmplidx (end + 1) = j;
-                break;
-              endif
-            endfor
-          endfor
-          idx = load_package_dirs (tmplidx, idx, handle_deps,
-                                 installed_pkgs_lst);
-        endif
-      endif
-      if (isempty (find(idx == i)))
-        idx (end + 1) = i;
-      endif
-    endif
-  endfor
-endfunction
-
-function dep = is_architecture_dependent (nm)
-  persistent archdepsuffix = {".oct",".mex",".a",".lib",".so",".so.*",".dll","dylib"};
-
-  dep = false;
-  for i = 1 : length (archdepsuffix)
-    ext = archdepsuffix{i};
-    if (ext(end) == "*")
-      isglob = true;
-      ext(end) = [];
-    else
-      isglob = false;
-    endif
-    pos = findstr (nm, ext);
-    if (pos)
-      if (! isglob && (length(nm) - pos(end) != length(ext) - 1))
-        continue;
-      endif
-      dep = true;
-      break;
-    endif
-  endfor
-endfunction
-
-function [url, local_file] = get_forge_download (name)
-  [ver, url] = get_forge_pkg (name);
-  local_file = [name, "-", ver, ".tar.gz"];
-endfunction
-
-function list = list_forge_packages ()
-  [list, succ] = urlread ("http://packages.octave.org/list_packages.php");
-  if (succ)
-    list = strsplit (list, " \n\t", true);
-  else
-    error ("pkg: could not read URL, please verify internet connection");
-  endif
-  if (nargout == 0)
-    page_screen_output (false, "local");
-    puts ("OctaveForge provides these packages:\n");
-    for i = 1:length (list)
-      try
-        ver = get_forge_pkg (list{i});
-      catch
-        ver = "unknown";
-      end_try_catch
-      printf ("  %s %s\n", list{i}, ver);
-    endfor
-  endif
-endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/build.m
@@ -0,0 +1,63 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} build (@var{files}, @var{handle_deps}, @var{autoload}, @var{verbose})
+## Undocumented internal function.
+## @end deftypefn
+
+function build (files, handle_deps, autoload, verbose)
+  if (length (files) < 1)
+    error ("insufficient number of files");
+  endif
+  builddir = files{1};
+  if (! exist (builddir, "dir"))
+    warning ("creating build directory %s", builddir);
+    [status, msg] = mkdir (builddir);
+    if (status != 1)
+      error ("could not create installation directory: %s", msg);
+    endif
+  endif
+  [builddir, status] = canonicalize_file_name (builddir);
+  if (status != 0)
+    error ("cannot find directory %s", builddir);
+  endif
+  installdir = fullfile (builddir, "install");
+  if (! exist (installdir, "dir"))
+    [status, msg] = mkdir (installdir);
+    if (status != 1)
+      error ("could not create installation directory: %s", msg);
+    endif
+  endif
+  files(1) = [];
+  buildlist = fullfile (builddir, "octave_packages");
+  install (files, handle_deps, autoload, installdir, installdir, verbose,
+           buildlist, "", false);
+  unwind_protect
+    repackage (builddir, buildlist);
+  unwind_protect_cleanup
+    unload_packages ({"all"}, handle_deps, buildlist, "");
+    if (exist (installdir, "dir"))
+      rmdir (installdir, "s");
+    endif
+    if (exist (buildlist, "file"))
+      unlink (buildlist);
+    endif
+  end_unwind_protect
+endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/configure_make.m
@@ -0,0 +1,158 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} configure_make (@var{desc}, @var{packdir}, @var{verbose})
+## Undocumented internal function.
+## @end deftypefn
+
+function configure_make (desc, packdir, verbose)
+  ## Perform ./configure, make, make install in "src".
+  if (exist (fullfile (packdir, "src"), "dir"))
+    src = fullfile (packdir, "src");
+    octave_bindir = octave_config_info ("bindir");
+    ver = version ();
+    mkoctfile_program = fullfile (octave_bindir, sprintf ("mkoctfile-%s", ver));
+    octave_config_program = fullfile (octave_bindir, sprintf ("octave-config-%s", ver));
+    octave_binary = fullfile (octave_bindir, sprintf ("octave-%s", ver));
+    cenv = {"MKOCTFILE"; mkoctfile_program;
+            "OCTAVE_CONFIG"; octave_config_program;
+            "OCTAVE"; octave_binary;
+            "INSTALLDIR"; desc.dir};
+    scenv = sprintf ("%s=\"%s\" ", cenv{:});
+    ## Configure.
+    if (exist (fullfile (src, "configure"), "file"))
+      flags = "";
+      if (isempty (getenv ("CC")))
+        flags = cstrcat (flags, " CC=\"", mkoctfile ("-p", "CC"), "\"");
+      endif
+      if (isempty (getenv ("CXX")))
+        flags = cstrcat (flags, " CXX=\"", mkoctfile ("-p", "CXX"), "\"");
+      endif
+      if (isempty (getenv ("AR")))
+        flags = cstrcat (flags, " AR=\"", mkoctfile ("-p", "AR"), "\"");
+      endif
+      if (isempty (getenv ("RANLIB")))
+        flags = cstrcat (flags, " RANLIB=\"", mkoctfile ("-p", "RANLIB"), "\"");
+      endif
+      [status, output] = shell (cstrcat ("cd '", src, "'; ", scenv,
+                                         "./configure --prefix=\"",
+                                         desc.dir, "\"", flags));
+      if (status != 0)
+        rmdir (desc.dir, "s");
+        error ("the configure script returned the following error: %s", output);
+      elseif (verbose)
+        printf ("%s", output);
+      endif
+
+    endif
+
+    ## Make.
+    if (exist (fullfile (src, "Makefile"), "file"))
+      [status, output] = shell (cstrcat (scenv, "make -C '", src, "'"));
+      if (status != 0)
+        rmdir (desc.dir, "s");
+        error ("'make' returned the following error: %s", output);
+      elseif (verbose)
+        printf ("%s", output);
+      endif
+    endif
+
+    ## Copy files to "inst" and "inst/arch" (this is instead of 'make
+    ## install').
+    files = fullfile (src, "FILES");
+    instdir = fullfile (packdir, "inst");
+    archdir = fullfile (packdir, "inst", getarch ());
+
+    ## Get file names.
+    if (exist (files, "file"))
+      [fid, msg] = fopen (files, "r");
+      if (fid < 0)
+        error ("couldn't open %s: %s", files, msg);
+      endif
+      filenames = char (fread (fid))';
+      fclose (fid);
+      if (filenames(end) == "\n")
+        filenames(end) = [];
+      endif
+      filenames = strtrim (strsplit (filenames, "\n", false));
+      delete_idx =  [];
+      for i = 1:length (filenames)
+        if (! all (isspace (filenames{i})))
+          filenames{i} = fullfile (src, filenames{i});
+        else
+          delete_idx(end+1) = i;
+        endif
+      endfor
+      filenames(delete_idx) = [];
+    else
+      m = dir (fullfile (src, "*.m"));
+      oct = dir (fullfile (src, "*.oct"));
+      mex = dir (fullfile (src, "*.mex"));
+
+      filenames = cellfun (@(x) fullfile (src, x),
+                           {m.name, oct.name, mex.name},
+                           "uniformoutput", false);
+    endif
+
+    ## Split into architecture dependent and independent files.
+    if (isempty (filenames))
+      idx = [];
+    else
+      idx = cellfun ("is_architecture_dependent", filenames);
+    endif
+    archdependent = filenames (idx);
+    archindependent = filenames (!idx);
+
+    ## Copy the files.
+    if (! all (isspace ([filenames{:}])))
+        if (! exist (instdir, "dir"))
+          mkdir (instdir);
+        endif
+        if (! all (isspace ([archindependent{:}])))
+          if (verbose)
+            printf ("copyfile");
+            printf (" %s", archindependent{:});
+            printf ("%s\n", instdir);
+          endif
+          [status, output] = copyfile (archindependent, instdir);
+          if (status != 1)
+            rmdir (desc.dir, "s");
+            error ("Couldn't copy files from 'src' to 'inst': %s", output);
+          endif
+        endif
+        if (! all (isspace ([archdependent{:}])))
+          if (verbose)
+            printf ("copyfile");
+            printf (" %s", archdependent{:});
+            printf (" %s\n", archdir);
+          endif
+          if (! exist (archdir, "dir"))
+            mkdir (archdir);
+          endif
+          [status, output] = copyfile (archdependent, archdir);
+          if (status != 1)
+            rmdir (desc.dir, "s");
+            error ("Couldn't copy files from 'src' to 'inst': %s", output);
+          endif
+        endif
+    endif
+  endif
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/copy_files.m
@@ -0,0 +1,144 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} copy_files (@var{desc}, @var{packdir}, @var{global_install})
+## Undocumented internal function.
+## @end deftypefn
+
+function copy_files (desc, packdir, global_install)
+  ## Create the installation directory.
+  if (! exist (desc.dir, "dir"))
+    [status, output] = mkdir (desc.dir);
+    if (status != 1)
+      error ("couldn't create installation directory %s : %s",
+      desc.dir, output);
+    endif
+  endif
+
+  octfiledir = getarchdir (desc);
+
+  ## Copy the files from "inst" to installdir.
+  instdir = fullfile (packdir, "inst");
+  if (! dirempty (instdir))
+    [status, output] = copyfile (fullfile (instdir, "*"), desc.dir);
+    if (status != 1)
+      rmdir (desc.dir, "s");
+      error ("couldn't copy files to the installation directory");
+    endif
+    if (exist (fullfile (desc.dir, getarch ()), "dir")
+        && ! strcmp (fullfile (desc.dir, getarch ()), octfiledir))
+      if (! exist (octfiledir, "dir"))
+        ## Can be required to create upto three levels of dirs.
+        octm1 = fileparts (octfiledir);
+        if (! exist (octm1, "dir"))
+          octm2 = fileparts (octm1);
+          if (! exist (octm2, "dir"))
+            octm3 = fileparts (octm2);
+            if (! exist (octm3, "dir"))
+              [status, output] = mkdir (octm3);
+              if (status != 1)
+                rmdir (desc.dir, "s");
+                error ("couldn't create installation directory %s : %s",
+                       octm3, output);
+              endif
+            endif
+            [status, output] = mkdir (octm2);
+            if (status != 1)
+              rmdir (desc.dir, "s");
+              error ("couldn't create installation directory %s : %s",
+                     octm2, output);
+            endif
+          endif
+          [status, output] = mkdir (octm1);
+          if (status != 1)
+            rmdir (desc.dir, "s");
+            error ("couldn't create installation directory %s : %s",
+                   octm1, output);
+          endif
+        endif
+        [status, output] = mkdir (octfiledir);
+        if (status != 1)
+          rmdir (desc.dir, "s");
+          error ("couldn't create installation directory %s : %s",
+          octfiledir, output);
+        endif
+      endif
+      [status, output] = movefile (fullfile (desc.dir, getarch (), "*"),
+                                   octfiledir);
+      rmdir (fullfile (desc.dir, getarch ()), "s");
+
+      if (status != 1)
+        rmdir (desc.dir, "s");
+        rmdir (octfiledir, "s");
+        error ("couldn't copy files to the installation directory");
+      endif
+    endif
+
+  endif
+
+  ## Create the "packinfo" directory.
+  packinfo = fullfile (desc.dir, "packinfo");
+  [status, msg] = mkdir (packinfo);
+  if (status != 1)
+    rmdir (desc.dir, "s");
+    rmdir (octfiledir, "s");
+    error ("couldn't create packinfo directory: %s", msg);
+  endif
+
+  packinfo_copy_file ("DESCRIPTION", "required", packdir, packinfo, desc, octfiledir);
+  packinfo_copy_file ("COPYING", "required", packdir, packinfo, desc, octfiledir);
+
+  packinfo_copy_file ("CITATION", "optional", packdir, packinfo, desc, octfiledir);
+  packinfo_copy_file ("NEWS", "optional", packdir, packinfo, desc, octfiledir);
+  packinfo_copy_file ("ONEWS", "optional", packdir, packinfo, desc, octfiledir);
+  packinfo_copy_file ("ChangeLog", "optional", packdir, packinfo, desc, octfiledir);
+
+  ## Is there an INDEX file to copy or should we generate one?
+  index_file = fullfile (packdir, "INDEX");
+  if (exist (index_file, "file"))
+    packinfo_copy_file ("INDEX", "required", packdir, packinfo, desc, octfiledir);
+  else
+    try
+      write_index (desc, fullfile (packdir, "inst"),
+                   fullfile (packinfo, "INDEX"), global_install);
+    catch
+      rmdir (desc.dir, "s");
+      rmdir (octfiledir, "s");
+      rethrow (lasterror ());
+    end_try_catch
+  endif
+
+  ## Is there an 'on_uninstall.m' to install?
+  packinfo_copy_file ("on_uninstall.m", "optional", packdir, packinfo, desc, octfiledir);
+
+  ## Is there a doc/ directory that needs to be installed?
+  docdir = fullfile (packdir, "doc");
+  if (exist (docdir, "dir") && ! dirempty (docdir))
+    [status, output] = copyfile (docdir, desc.dir);
+  endif
+
+  ## Is there a bin/ directory that needs to be installed?
+  ## FIXME: Need to treat architecture dependent files in bin/
+  bindir = fullfile (packdir, "bin");
+  if (exist (bindir, "dir") && ! dirempty (bindir))
+    [status, output] = copyfile (bindir, desc.dir);
+  endif
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/create_pkgadddel.m
@@ -0,0 +1,89 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} create_pkgadddel (@var{desc}, @var{packdir}, @var{nm}, @var{global_install})
+## Undocumented internal function.
+## @end deftypefn
+
+function create_pkgadddel (desc, packdir, nm, global_install)
+  instpkg = fullfile (desc.dir, nm);
+  instfid = fopen (instpkg, "wt");
+  ## If it is exists, most of the  PKG_* file should go into the
+  ## architecture dependent directory so that the autoload/mfilename
+  ## commands work as expected. The only part that doesn't is the
+  ## part in the main directory.
+  archdir = fullfile (getarchprefix (desc, global_install), cstrcat (desc.name,
+                      "-", desc.version), getarch ());
+  if (exist (getarchdir (desc, global_install), "dir"))
+    archpkg = fullfile (getarchdir (desc, global_install), nm);
+    archfid = fopen (archpkg, "at");
+  else
+    archpkg = instpkg;
+    archfid = instfid;
+  endif
+
+  if (archfid >= 0 && instfid >= 0)
+    ## Search all dot-m files for PKG commands.
+    lst = dir (fullfile (packdir, "inst", "*.m"));
+    for i = 1:length (lst)
+      nam = fullfile (packdir, "inst", lst(i).name);
+      fwrite (instfid, extract_pkg (nam, ['^[#%][#%]* *' nm ': *(.*)$']));
+    endfor
+
+    ## Search all C++ source files for PKG commands.
+    lst = dir (fullfile (packdir, "src", "*.cc"));
+    for i = 1:length (lst)
+      nam = fullfile (packdir, "src", lst(i).name);
+      fwrite (archfid, extract_pkg (nam, ['^//* *' nm ': *(.*)$']));
+      fwrite (archfid, extract_pkg (nam, ['^/\** *' nm ': *(.*) *\*/$']));
+    endfor
+
+    ## Add developer included PKG commands.
+    packdirnm = fullfile (packdir, nm);
+    if (exist (packdirnm, "file"))
+      fid = fopen (packdirnm, "rt");
+      if (fid >= 0)
+        while (! feof (fid))
+          ln = fgets (fid);
+          if (ln > 0)
+            fwrite (archfid, ln);
+          endif
+        endwhile
+        fclose (fid);
+      endif
+    endif
+
+    ## If the files is empty remove it.
+    fclose (instfid);
+    t = dir (instpkg);
+    if (t.bytes <= 0)
+      unlink (instpkg);
+    endif
+
+    if (instfid != archfid)
+      fclose (archfid);
+      t = dir (archpkg);
+      if (t.bytes <= 0)
+        unlink (archpkg);
+      endif
+    endif
+  endif
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/describe.m
@@ -0,0 +1,87 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{pkg_desc_list}, @var{flag}] =} describe (@var{pkgnames}, @var{verbose}, @var{local_list}, @var{global_list})
+## Undocumented internal function.
+## @end deftypefn
+
+function [pkg_desc_list, flag] = describe (pkgnames, verbose,
+                                           local_list, global_list)
+
+  ## Get the list of installed packages.
+  installed_pkgs_lst = installed_packages(local_list, global_list);
+  num_packages = length (installed_pkgs_lst);
+
+
+  describe_all = false;
+  if (any (strcmp ("all", pkgnames)))
+    describe_all = true;
+    flag(1:num_packages) = {"Not Loaded"};
+    num_pkgnames = num_packages;
+  else
+    num_pkgnames = length (pkgnames);
+    flag(1:num_pkgnames) = {"Not installed"};
+  endif
+
+  for i = 1:num_packages
+    curr_name = installed_pkgs_lst{i}.name;
+    if (describe_all)
+      name_pos = i;
+    else
+      name_pos = find (strcmp (curr_name, pkgnames));
+    endif
+
+    if (! isempty (name_pos))
+      if (installed_pkgs_lst{i}.loaded)
+        flag{name_pos} = "Loaded";
+      else
+        flag{name_pos} = "Not loaded";
+      endif
+
+      pkg_desc_list{name_pos}.name = installed_pkgs_lst{i}.name;
+      pkg_desc_list{name_pos}.version = installed_pkgs_lst{i}.version;
+      pkg_desc_list{name_pos}.description = installed_pkgs_lst{i}.description;
+      pkg_desc_list{name_pos}.provides = parse_pkg_idx (installed_pkgs_lst{i}.dir);
+
+    endif
+  endfor
+
+  non_inst = find (strcmp (flag, "Not installed"));
+  if (! isempty (non_inst))
+    if (nargout < 2)
+      non_inst_str = sprintf (" %s ", pkgnames{non_inst});
+      error ("some packages are not installed: %s", non_inst_str);
+    else
+      pkg_desc_list{non_inst} = struct ("name", {}, "description",
+                                        {}, "provides", {});
+    endif
+  endif
+
+  if (nargout == 0)
+    for i = 1:num_pkgnames
+      print_package_description (pkg_desc_list{i}.name,
+                                 pkg_desc_list{i}.version,
+                                 pkg_desc_list{i}.provides,
+                                 pkg_desc_list{i}.description,
+                                 flag{i}, verbose);
+    endfor
+  endif
+
+endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/dirempty.m
@@ -0,0 +1,50 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{emp} =} dirempty (@var{nm}, @var{ign})
+## Undocumented internal function.
+## @end deftypefn
+
+function emp = dirempty (nm, ign)
+  if (exist (nm, "dir"))
+    if (nargin < 2)
+      ign = {".", ".."};
+    else
+      ign = [{".", ".."}, ign];
+    endif
+    l = dir (nm);
+    for i = 1:length (l)
+      found = false;
+      for j = 1:length (ign)
+        if (strcmp (l(i).name, ign{j}))
+          found = true;
+          break;
+        endif
+      endfor
+      if (! found)
+        emp = false;
+        return
+      endif
+    endfor
+    emp = true;
+  else
+    emp = true;
+  endif
+endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/extract_pkg.m
@@ -0,0 +1,44 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{pkg} =} extract_pkg (@var{nm}, @var{pat})
+## Undocumented internal function.
+## @end deftypefn
+
+function pkg = extract_pkg (nm, pat)
+  fid = fopen (nm, "rt");
+  pkg = "";
+  if (fid >= 0)
+    while (! feof (fid))
+      ln = fgetl (fid);
+      if (ln > 0)
+        t = regexp (ln, pat, "tokens");
+        if (! isempty (t))
+          pkg = cstrcat (pkg, "\n", t{1}{1});
+        endif
+      endif
+    endwhile
+    if (! isempty (pkg))
+      pkg = cstrcat (pkg, "\n");
+    endif
+    fclose (fid);
+  endif
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/finish_installation.m
@@ -0,0 +1,41 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} finish_installation (@var{desc}, @var{packdir}, @var{global_install})
+## Undocumented internal function.
+## @end deftypefn
+
+function finish_installation (desc, packdir, global_install)
+  ## Is there a post-install to call?
+  if (exist (fullfile (packdir, "post_install.m"), "file"))
+    wd = pwd ();
+    try
+      cd (packdir);
+      post_install (desc);
+      cd (wd);
+    catch
+      cd (wd);
+      rmdir (desc.dir, "s");
+      rmdir (getarchdir (desc), "s");
+      rethrow (lasterror ());
+    end_try_catch
+  endif
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/fix_depends.m
@@ -0,0 +1,65 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{deps_cell} =} fix_depends (@var{depends})
+## Undocumented internal function.
+## @end deftypefn
+
+## Make sure the depends field is of the right format.
+## This function returns a cell of structures with the following fields:
+##   package, version, operator
+function deps_cell = fix_depends (depends)
+  deps = strtrim (strsplit (tolower (depends), ",", false));
+  deps_cell = cell (1, length (deps));
+
+  ## For each dependency.
+  for i = 1:length (deps)
+    dep = deps{i};
+    lpar = find (dep == "(");
+    rpar = find (dep == ")");
+    ## Does the dependency specify a version
+    ## Example: package(>= version).
+    if (length (lpar) == 1 && length (rpar) == 1)
+      package = tolower (strtrim (dep(1:lpar-1)));
+      sub = dep(lpar(1)+1:rpar(1)-1);
+      parts = strsplit (sub, " ", true);
+      if (length (parts) != 2)
+        error ("incorrect syntax for dependency '%s' in the DESCRIPTION file\n",
+               dep);
+      endif
+      operator = parts{1};
+      if (! any (strcmp (operator, {">", ">=", "<=", "<", "=="})))
+        error ("unsupported operator: %s", operator);
+      endif
+      version  = fix_version (parts{2});
+
+  ## If no version is specified for the dependency
+  ## we say that the version should be greater than
+  ## or equal to "0.0.0".
+  else
+    package = tolower (strtrim (dep));
+    operator = ">=";
+    version  = "0.0.0";
+  endif
+  deps_cell{i} = struct ("package", package, "operator", operator,
+                         "version", version);
+  endfor
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/fix_version.m
@@ -0,0 +1,47 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{out} =} fix_version (@var{v})
+## Undocumented internal function.
+## @end deftypefn
+
+## Make sure the version string v is a valid x.y.z version string
+## Examples: "0.1" => "0.1.0", "monkey" => error(...).
+function out = fix_version (v)
+  dots = find (v == ".");
+  if (length (dots) == 1)
+    major = str2num (v(1:dots-1));
+    minor = str2num (v(dots+1:end));
+    if (length (major) != 0 && length (minor) != 0)
+      out = sprintf ("%d.%d.0", major, minor);
+      return;
+    endif
+  elseif (length (dots) == 2)
+    major = str2num (v(1:dots(1)-1));
+    minor = str2num (v(dots(1)+1:dots(2)-1));
+    rev = str2num (v(dots(2)+1:end));
+    if (length (major) != 0 && length (minor) != 0 && length (rev) != 0)
+      out = sprintf ("%d.%d.%d", major, minor, rev);
+      return;
+    endif
+  endif
+  error ("bad version string: %s", v);
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/generate_lookfor_cache.m
@@ -0,0 +1,31 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} generate_lookfor_cache (@var{desc})
+## Undocumented internal function.
+## @end deftypefn
+
+function generate_lookfor_cache (desc)
+  dirs = strtrim (strsplit (genpath (desc.dir), pathsep (), false));
+  for i = 1 : length (dirs)
+    gen_doc_cache (fullfile (dirs{i}, "doc-cache"), dirs{i});
+  endfor
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/get_description.m
@@ -0,0 +1,80 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{desc} =} get_description (@var{filename})
+## Undocumented internal function.
+## @end deftypefn
+
+## Parse the DESCRIPTION file.
+function desc = get_description (filename)
+  [fid, msg] = fopen (filename, "r");
+  if (fid == -1)
+    error ("the DESCRIPTION file %s could not be read: %s", filename, msg);
+  endif
+
+  desc = struct ();
+
+  line = fgetl (fid);
+  while (line != -1)
+    if (line(1) == "#")
+      ## Comments, do nothing.
+    elseif (isspace (line(1)))
+      ## Continuation lines
+      if (exist ("keyword", "var") && isfield (desc, keyword))
+        desc.(keyword) = cstrcat (desc.(keyword), " ", deblank (line));
+      endif
+    else
+      ## Keyword/value pair
+      colon = find (line == ":");
+      if (length (colon) == 0)
+        disp ("skipping line");
+      else
+        colon = colon(1);
+        keyword = tolower (strtrim (line(1:colon-1)));
+        value = strtrim (line (colon+1:end));
+        if (length (value) == 0)
+            fclose (fid);
+            error ("The keyword '%s' of the package '%s' has an empty value",
+                    keyword, desc.name);
+        endif
+        desc.(keyword) = value;
+      endif
+    endif
+    line = fgetl (fid);
+  endwhile
+  fclose (fid);
+
+  ## Make sure all is okay.
+  needed_fields = {"name", "version", "date", "title", ...
+                   "author", "maintainer", "description"};
+  for f = needed_fields
+    if (! isfield (desc, f{1}))
+      error ("description is missing needed field %s", f{1});
+    endif
+  endfor
+  desc.version = fix_version (desc.version);
+  if (isfield (desc, "depends"))
+    desc.depends = fix_depends (desc.depends);
+  else
+    desc.depends = "";
+  endif
+  desc.name = tolower (desc.name);
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/get_forge_download.m
@@ -0,0 +1,28 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{url}, @var{local_file}] =} list_forge_packages ()
+## Undocumented internal function.
+## @end deftypefn
+
+function [url, local_file] = get_forge_download (name)
+  [ver, url] = get_forge_pkg (name);
+  local_file = [name, "-", ver, ".tar.gz"];
+endfunction
--- a/scripts/pkg/private/get_forge_pkg.m
+++ b/scripts/pkg/private/get_forge_pkg.m
@@ -1,3 +1,4 @@
+## Copyright (C) 2005-2012 Søren Hauberg
 ## Copyright (C) 2010-2012 VZLU Prague, a.s.
 ##
 ## This file is part of Octave.
@@ -45,7 +46,7 @@
     ## Good. Let's grep for the version.
     pat = "<tdclass=""package_table"">PackageVersion:</td><td>([\\d.]*)</td>";
     t = regexp (html, pat, "tokens");
-    if (isempty (t) || isempty(t{1}))
+    if (isempty (t) || isempty (t{1}))
       error ("get_forge_pkg: could not read version number from package's page");
     else
       ver = t{1}{1};
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/get_unsatisfied_deps.m
@@ -0,0 +1,54 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{bad_deps} =} get_unsatisfied_deps (@var{desc}, @var{installed_pkgs_lst})
+## Undocumented internal function.
+## @end deftypefn
+
+function bad_deps = get_unsatisfied_deps (desc, installed_pkgs_lst)
+  bad_deps = {};
+
+  ## For each dependency.
+  for i = 1:length (desc.depends)
+    dep = desc.depends{i};
+
+    ## Is the current dependency Octave?
+    if (strcmp (dep.package, "octave"))
+      if (! compare_versions (OCTAVE_VERSION, dep.version, dep.operator))
+        bad_deps{end+1} = dep;
+      endif
+      ## Is the current dependency not Octave?
+    else
+      ok = false;
+      for i = 1:length (installed_pkgs_lst)
+        cur_name = installed_pkgs_lst{i}.name;
+        cur_version = installed_pkgs_lst{i}.version;
+        if (strcmp (dep.package, cur_name)
+            && compare_versions (cur_version, dep.version, dep.operator))
+          ok = true;
+          break;
+        endif
+      endfor
+      if (! ok)
+        bad_deps{end+1} = dep;
+      endif
+    endif
+  endfor
+endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/getarch.m
@@ -0,0 +1,30 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{arch} =} getarch ()
+## Undocumented internal function.
+## @end deftypefn
+
+function arch = getarch ()
+  persistent _arch = cstrcat (octave_config_info ("canonical_host_type"),
+                              "-", octave_config_info ("api_version"));
+  arch = _arch;
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/getarchdir.m
@@ -0,0 +1,28 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{archdir} =} getarchdir (@var{desc})
+## Undocumented internal function.
+## @end deftypefn
+
+function archdir = getarchdir (desc)
+  archdir = fullfile (desc.archprefix, getarch ());
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/getarchprefix.m
@@ -0,0 +1,33 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{archprefix} =} getarchprefix (@var{desc}, @var{global_install})
+## Undocumented internal function.
+## @end deftypefn
+
+function archprefix = getarchprefix (desc, global_install)
+  if (global_install)
+    archprefix = fullfile (octave_config_info ("libdir"), "octave",
+                           "packages", cstrcat (desc.name, "-", desc.version));
+  else
+    archprefix = desc.dir;
+  endif
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/install.m
@@ -0,0 +1,345 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} install (@var{files}, @var{handle_deps}, @var{autoload}, @var{prefix}, @var{archprefix}, @var{verbose}, @var{local_list}, @var{global_list}, @var{global_install})
+## Undocumented internal function.
+## @end deftypefn
+
+function install (files, handle_deps, autoload, prefix, archprefix, verbose,
+                  local_list, global_list, global_install)
+
+  ## Check that the directory in prefix exist. If it doesn't: create it!
+  if (! exist (prefix, "dir"))
+    warning ("creating installation directory %s", prefix);
+    [status, msg] = mkdir (prefix);
+    if (status != 1)
+      error ("could not create installation directory: %s", msg);
+    endif
+  endif
+
+  ## Get the list of installed packages.
+  [local_packages, global_packages] = installed_packages (local_list,
+                                                          global_list);
+
+  installed_pkgs_lst = {local_packages{:}, global_packages{:}};
+
+  if (global_install)
+    packages = global_packages;
+  else
+    packages = local_packages;
+  endif
+
+  ## Uncompress the packages and read the DESCRIPTION files.
+  tmpdirs = packdirs = descriptions = {};
+  try
+    ## Warn about non existent files.
+    for i = 1:length (files)
+      if (isempty (glob (files{i})))
+        warning ("file %s does not exist", files{i});
+      endif
+    endfor
+
+    ## Unpack the package files and read the DESCRIPTION files.
+    files = glob (files);
+    packages_to_uninstall = [];
+    for i = 1:length (files)
+      tgz = files{i};
+
+      if (exist (tgz, "file"))
+        ## Create a temporary directory.
+        tmpdir = tmpnam ();
+        tmpdirs{end+1} = tmpdir;
+        if (verbose)
+          printf ("mkdir (%s)\n", tmpdir);
+        endif
+        [status, msg] = mkdir (tmpdir);
+        if (status != 1)
+          error ("couldn't create temporary directory: %s", msg);
+        endif
+
+        ## Uncompress the package.
+        if (verbose)
+          printf ("untar (%s, %s)\n", tgz, tmpdir);
+        endif
+        untar (tgz, tmpdir);
+
+        ## Get the name of the directories produced by tar.
+        [dirlist, err, msg] = readdir (tmpdir);
+        if (err)
+          error ("couldn't read directory produced by tar: %s", msg);
+        endif
+
+        if (length (dirlist) > 3)
+          error ("bundles of packages are not allowed");
+        endif
+      endif
+
+      ## The filename pointed to an uncompressed package to begin with.
+      if (exist (tgz, "dir"))
+        dirlist = {".", "..", tgz};
+      endif
+
+      if (exist (tgz, "file") || exist (tgz, "dir"))
+        ## The two first entries of dirlist are "." and "..".
+        if (exist (tgz, "file"))
+          packdir = fullfile (tmpdir, dirlist{3});
+        else
+          packdir = fullfile (pwd (), dirlist{3});
+        endif
+        packdirs{end+1} = packdir;
+
+        ## Make sure the package contains necessary files.
+        verify_directory (packdir);
+
+        ## Read the DESCRIPTION file.
+        filename = fullfile (packdir, "DESCRIPTION");
+        desc = get_description (filename);
+
+        ## Verify that package name corresponds with filename.
+        [dummy, nm] = fileparts (tgz);
+        if ((length (nm) >= length (desc.name))
+            && ! strcmp (desc.name, nm(1:length (desc.name))))
+          error ("package name '%s' doesn't correspond to its filename '%s'",
+                 desc.name, nm);
+        endif
+
+        ## Set default installation directory.
+        desc.dir = fullfile (prefix, cstrcat (desc.name, "-", desc.version));
+
+        ## Set default architectire dependent installation directory.
+        desc.archprefix = fullfile (archprefix, cstrcat (desc.name, "-",
+                                                         desc.version));
+
+        ## Save desc.
+        descriptions{end+1} = desc;
+
+        ## Are any of the new packages already installed?
+        ## If so we'll remove the old version.
+        for j = 1:length (packages)
+          if (strcmp (packages{j}.name, desc.name))
+            packages_to_uninstall(end+1) = j;
+          endif
+        endfor
+      endif
+    endfor
+  catch
+    ## Something went wrong, delete tmpdirs.
+    for i = 1:length (tmpdirs)
+      rmdir (tmpdirs{i}, "s");
+    endfor
+    rethrow (lasterror ());
+  end_try_catch
+
+  ## Check dependencies.
+  if (handle_deps)
+    ok = true;
+    error_text = "";
+    for i = 1:length (descriptions)
+      desc = descriptions{i};
+      idx2 = setdiff (1:length (descriptions), i);
+      if (global_install)
+        ## Global installation is not allowed to have dependencies on locally
+        ## installed packages.
+        idx1 = setdiff (1:length (global_packages), packages_to_uninstall);
+        pseudo_installed_packages = {global_packages{idx1}, ...
+                                     descriptions{idx2}};
+      else
+        idx1 = setdiff (1:length (local_packages), packages_to_uninstall);
+        pseudo_installed_packages = {local_packages{idx1}, ...
+                                     global_packages{:}, ...
+                                     descriptions{idx2}};
+      endif
+      bad_deps = get_unsatisfied_deps (desc, pseudo_installed_packages);
+      ## Are there any unsatisfied dependencies?
+      if (! isempty (bad_deps))
+        ok = false;
+        for i = 1:length (bad_deps)
+          dep = bad_deps{i};
+          error_text = cstrcat (error_text, " ", desc.name, " needs ",
+                               dep.package, " ", dep.operator, " ",
+                               dep.version, "\n");
+        endfor
+      endif
+    endfor
+
+    ## Did we find any unsatisfied dependencies?
+    if (! ok)
+      error ("the following dependencies were unsatisfied:\n  %s", error_text);
+    endif
+  endif
+
+  ## Prepare each package for installation.
+  try
+    for i = 1:length (descriptions)
+      desc = descriptions{i};
+      pdir = packdirs{i};
+      prepare_installation (desc, pdir);
+      configure_make (desc, pdir, verbose);
+    endfor
+  catch
+    ## Something went wrong, delete tmpdirs.
+    for i = 1:length (tmpdirs)
+      rmdir (tmpdirs{i}, "s");
+    endfor
+    rethrow (lasterror ());
+  end_try_catch
+
+  ## Uninstall the packages that will be replaced.
+  try
+    for i = packages_to_uninstall
+      if (global_install)
+        uninstall ({global_packages{i}.name}, false, verbose, local_list,
+                   global_list, global_install);
+      else
+        uninstall ({local_packages{i}.name}, false, verbose, local_list,
+                   global_list, global_install);
+      endif
+    endfor
+  catch
+    ## Something went wrong, delete tmpdirs.
+    for i = 1:length (tmpdirs)
+      rmdir (tmpdirs{i}, "s");
+    endfor
+    rethrow (lasterror ());
+  end_try_catch
+
+  ## Install each package.
+  try
+    for i = 1:length (descriptions)
+      desc = descriptions{i};
+      pdir = packdirs{i};
+      copy_files (desc, pdir, global_install);
+      create_pkgadddel (desc, pdir, "PKG_ADD", global_install);
+      create_pkgadddel (desc, pdir, "PKG_DEL", global_install);
+      finish_installation (desc, pdir, global_install);
+      generate_lookfor_cache (desc);
+    endfor
+  catch
+    ## Something went wrong, delete tmpdirs.
+    for i = 1:length (tmpdirs)
+      rmdir (tmpdirs{i}, "s");
+    endfor
+    for i = 1:length (descriptions)
+      rmdir (descriptions{i}.dir, "s");
+      rmdir (getarchdir (descriptions{i}), "s");
+    endfor
+    rethrow (lasterror ());
+  end_try_catch
+
+  ## Check if the installed directory is empty. If it is remove it
+  ## from the list.
+  for i = length (descriptions):-1:1
+    if (dirempty (descriptions{i}.dir, {"packinfo", "doc"})
+        && dirempty (getarchdir (descriptions{i})))
+      warning ("package %s is empty\n", descriptions{i}.name);
+      rmdir (descriptions{i}.dir, "s");
+      rmdir (getarchdir (descriptions{i}), "s");
+      descriptions(i) = [];
+    endif
+  endfor
+
+  ## If the package requested that it is autoloaded, or the installer
+  ## requested that it is, then mark the package as autoloaded.
+  str_true = {"true", "on", "yes", "1"};
+  for i = length (descriptions):-1:1
+
+    desc_autoload = false;
+    if (isfield (descriptions{i}, "autoload"))
+      a = descriptions{i}.autoload;
+      desc_autoload = ((isnumeric (a) && a > 0)
+                       || (ischar (a) 
+                           && any (strcmpi (a, str_true))));
+    endif
+
+    if (autoload > 0 || (autoload == 0 && desc_autoload))
+      fclose (fopen (fullfile (descriptions{i}.dir, "packinfo",
+                               ".autoload"), "wt"));
+      descriptions{i}.autoload = 1;
+    else
+      descriptions{i}.autoload = 0;
+    endif
+
+  endfor
+
+  ## Add the packages to the package list.
+  try
+    if (global_install)
+      idx = setdiff (1:length (global_packages), packages_to_uninstall);
+      global_packages = save_order ({global_packages{idx}, descriptions{:}});
+      save (global_list, "global_packages");
+      installed_pkgs_lst = {local_packages{:}, global_packages{:}};
+    else
+      idx = setdiff (1:length (local_packages), packages_to_uninstall);
+      local_packages = save_order ({local_packages{idx}, descriptions{:}});
+      save (local_list, "local_packages");
+      installed_pkgs_lst = {local_packages{:}, global_packages{:}};
+    endif
+  catch
+    ## Something went wrong, delete tmpdirs.
+    for i = 1:length (tmpdirs)
+      rmdir (tmpdirs{i}, "s");
+    endfor
+    for i = 1:length (descriptions)
+      rmdir (descriptions{i}.dir, "s");
+    endfor
+    if (global_install)
+      printf ("error: couldn't append to %s\n", global_list);
+    else
+      printf ("error: couldn't append to %s\n", local_list);
+    endif
+    rethrow (lasterror ());
+  end_try_catch
+
+  ## All is well, let's clean up.
+  for i = 1:length (tmpdirs)
+    [status, msg] = rmdir (tmpdirs{i}, "s");
+    if (status != 1 && exist (tmpdirs{i}, "dir"))
+      warning ("couldn't clean up after my self: %s\n", msg);
+    endif
+  endfor
+
+  ## Add the newly installed packages to the path, so the user
+  ## can begin using them. Only load them if they are marked autoload.
+  if (length (descriptions) > 0)
+    idx = [];
+    for i = 1:length (descriptions)
+      if (descriptions{i}.autoload > 0)
+        nm = descriptions{i}.name;
+        for j = 1:length (installed_pkgs_lst)
+          if (strcmp (nm, installed_pkgs_lst{j}.name))
+            idx (end + 1) = j;
+            break;
+          endif
+        endfor
+      endif
+    endfor
+    load_packages_and_dependencies (idx, handle_deps, installed_pkgs_lst,
+                                    global_install);
+  endif
+
+  ## If there's a NEWS file, mention it
+  ## we are checking if desc exists too because it's possible to ge to this point
+  ## without creating it such as giving an invalid filename for the package
+  if (exist ("desc", "var") && exist (fullfile (desc.dir, "packinfo", "NEWS"), "file"))
+    printf ("For information about changes from previous versions of the %s package, run 'news (\"%s\")'.\n",
+            desc.name, desc.name);
+  endif
+
+endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/installed_packages.m
@@ -0,0 +1,157 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{out1}, @var{out2}] =} installed_packages (@var{local_list}, @var{global_list})
+## Undocumented internal function.
+## @end deftypefn
+
+function [out1, out2] = installed_packages (local_list, global_list)
+  ## Get the list of installed packages.
+  try
+    local_packages = load (local_list).local_packages;
+  catch
+    local_packages = {};
+  end_try_catch
+  try
+    global_packages = load (global_list).global_packages;
+  catch
+    global_packages = {};
+  end_try_catch
+  installed_pkgs_lst = {local_packages{:}, global_packages{:}};
+
+  ## Eliminate duplicates in the installed package list.
+  ## Locally installed packages take precedence.
+  dup = [];
+  for i = 1:length (installed_pkgs_lst)
+    if (any (dup == i))
+      continue;
+    endif
+    for j = (i+1):length (installed_pkgs_lst)
+      if (any (dup == j))
+        continue;
+      endif
+      if (strcmp (installed_pkgs_lst{i}.name, installed_pkgs_lst{j}.name))
+        dup = [dup, j];
+      endif
+    endfor
+  endfor
+  if (! isempty (dup))
+    installed_pkgs_lst(dup) = [];
+  endif
+
+  ## Now check if the package is loaded.
+  tmppath = strrep (path (), "\\", "/");
+  for i = 1:length (installed_pkgs_lst)
+    if (strfind (tmppath, strrep (installed_pkgs_lst{i}.dir, '\', '/')))
+      installed_pkgs_lst{i}.loaded = true;
+    else
+      installed_pkgs_lst{i}.loaded = false;
+    endif
+  endfor
+  for i = 1:length (local_packages)
+    if (strfind (tmppath, strrep (local_packages{i}.dir, '\', '/')))
+      local_packages{i}.loaded = true;
+    else
+      local_packages{i}.loaded = false;
+    endif
+  endfor
+  for i = 1:length (global_packages)
+    if (strfind (tmppath, strrep (global_packages{i}.dir, '\', '/')))
+      global_packages{i}.loaded = true;
+    else
+      global_packages{i}.loaded = false;
+    endif
+  endfor
+
+  ## Should we return something?
+  if (nargout == 2)
+    out1 = local_packages;
+    out2 = global_packages;
+    return;
+  elseif (nargout == 1)
+    out1 = installed_pkgs_lst;
+    return;
+  endif
+
+  ## We shouldn't return something, so we'll print something.
+  num_packages = length (installed_pkgs_lst);
+  if (num_packages == 0)
+    printf ("no packages installed.\n");
+    return;
+  endif
+
+  ## Compute the maximal lengths of name, version, and dir.
+  h1 = "Package Name";
+  h2 = "Version";
+  h3 = "Installation directory";
+  max_name_length = length (h1);
+  max_version_length = length (h2);
+  names = cell (num_packages, 1);
+  for i = 1:num_packages
+    max_name_length = max (max_name_length,
+                           length (installed_pkgs_lst{i}.name));
+    max_version_length = max (max_version_length,
+                              length (installed_pkgs_lst{i}.version));
+    names{i} = installed_pkgs_lst{i}.name;
+  endfor
+  max_dir_length = terminal_size ()(2) - max_name_length - ...
+                                             max_version_length - 7;
+  if (max_dir_length < 20)
+     max_dir_length = Inf;
+  endif
+
+  h1 = postpad (h1, max_name_length + 1, " ");
+  h2 = postpad (h2, max_version_length, " ");;
+
+  ## Print a header.
+  header = sprintf ("%s | %s | %s\n", h1, h2, h3);
+  printf (header);
+  tmp = sprintf (repmat ("-", 1, length (header) - 1));
+  tmp(length(h1)+2) = "+";
+  tmp(length(h1)+length(h2)+5) = "+";
+  printf ("%s\n", tmp);
+
+  ## Print the packages.
+  format = sprintf ("%%%ds %%1s| %%%ds | %%s\n", max_name_length,
+                    max_version_length);
+  [dummy, idx] = sort (names);
+  for i = 1:num_packages
+    cur_name = installed_pkgs_lst{idx(i)}.name;
+    cur_version = installed_pkgs_lst{idx(i)}.version;
+    cur_dir = installed_pkgs_lst{idx(i)}.dir;
+    if (length (cur_dir) > max_dir_length)
+      first_char = length (cur_dir) - max_dir_length + 4;
+      first_filesep = strfind (cur_dir(first_char:end), filesep ());
+      if (! isempty (first_filesep))
+        cur_dir = cstrcat ("...",
+                          cur_dir((first_char + first_filesep(1) - 1):end));
+      else
+        cur_dir = cstrcat ("...", cur_dir(first_char:end));
+      endif
+    endif
+    if (installed_pkgs_lst{idx(i)}.loaded)
+      cur_loaded = "*";
+    else
+      cur_loaded = " ";
+    endif
+    printf (format, cur_name, cur_loaded, cur_version, cur_dir);
+  endfor
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/is_architecture_dependent.m
@@ -0,0 +1,46 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{dep} =} is_architecture_dependent (@var{nm})
+## Undocumented internal function.
+## @end deftypefn
+
+function dep = is_architecture_dependent (nm)
+  persistent archdepsuffix = {".oct",".mex",".a",".lib",".so",".so.*",".dll","dylib"};
+
+  dep = false;
+  for i = 1 : length (archdepsuffix)
+    ext = archdepsuffix{i};
+    if (ext(end) == "*")
+      isglob = true;
+      ext(end) = [];
+    else
+      isglob = false;
+    endif
+    pos = strfind (nm, ext);
+    if (pos)
+      if (! isglob && (length (nm) - pos(end) != length (ext) - 1))
+        continue;
+      endif
+      dep = true;
+      break;
+    endif
+  endfor
+endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/list_forge_packages.m
@@ -0,0 +1,44 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{list} =} list_forge_packages ()
+## Undocumented internal function.
+## @end deftypefn
+
+function list = list_forge_packages ()
+  [list, succ] = urlread ("http://packages.octave.org/list_packages.php");
+  if (succ)
+    list = strsplit (list, " \n\t", true, "delimitertype", "legacy");
+  else
+    error ("pkg: could not read URL, please verify internet connection");
+  endif
+  if (nargout == 0)
+    page_screen_output (false, "local");
+    puts ("OctaveForge provides these packages:\n");
+    for i = 1:length (list)
+      try
+        ver = get_forge_pkg (list{i});
+      catch
+        ver = "unknown";
+      end_try_catch
+      printf ("  %s %s\n", list{i}, ver);
+    endfor
+  endif
+endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/load_package_dirs.m
@@ -0,0 +1,58 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{idx} =} load_package_dirs (@var{lidx}, @var{idx}, @var{handle_deps}, @var{installed_pkgs_lst})
+## Undocumented internal function.
+## @end deftypefn
+
+function idx = load_package_dirs (lidx, idx, handle_deps, installed_pkgs_lst)
+  for i = lidx
+    if (isfield (installed_pkgs_lst{i}, "loaded")
+        && installed_pkgs_lst{i}.loaded)
+      continue;
+    else
+      ## Insert this package at the front before recursing over dependencies.
+      if (! any (idx == i))
+        idx = [i, idx];
+      endif
+
+      if (handle_deps)
+        deps = installed_pkgs_lst{i}.depends;
+        if ((length (deps) > 1)
+            || (length (deps) == 1 && ! strcmp (deps{1}.package, "octave")))
+          tmplidx = [];
+          for k = 1 : length (deps)
+            for j = 1 : length (installed_pkgs_lst)
+              if (strcmp (installed_pkgs_lst{j}.name, deps{k}.package))
+                if (! any (idx == j))
+                  tmplidx (end + 1) = j;
+                  break;
+                endif
+              endif
+            endfor
+          endfor
+          idx = load_package_dirs (tmplidx, idx, handle_deps,
+                                 installed_pkgs_lst);
+        endif
+      endif
+    endif
+  endfor
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/load_packages.m
@@ -0,0 +1,62 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} load_packages (@var{files}, @var{handle_deps}, @var{local_list}, @var{global_list})
+## Undocumented internal function.
+## @end deftypefn
+
+function load_packages (files, handle_deps, local_list, global_list)
+  installed_pkgs_lst = installed_packages (local_list, global_list);
+  num_packages = length (installed_pkgs_lst);
+
+  ## Read package names and installdirs into a more convenient format.
+  pnames = pdirs = cell (1, num_packages);
+  for i = 1:num_packages
+    pnames{i} = installed_pkgs_lst{i}.name;
+    pdirs{i} = installed_pkgs_lst{i}.dir;
+  endfor
+
+  ## Load all.
+  if (length (files) == 1 && strcmp (files{1}, "all"))
+    idx = [1:length(installed_pkgs_lst)];
+  ## Load auto.
+  elseif (length (files) == 1 && strcmp (files{1}, "auto"))
+    idx = [];
+    for i = 1:length (installed_pkgs_lst)
+      if (exist (fullfile (pdirs{i}, "packinfo", ".autoload"), "file"))
+        idx (end + 1) = i;
+      endif
+    endfor
+  ## Load package_name1 ...
+  else
+    idx = [];
+    for i = 1:length (files)
+      idx2 = find (strcmp (pnames, files{i}));
+      if (! any (idx2))
+          error ("package %s is not installed", files{i});
+      endif
+      idx (end + 1) = idx2;
+    endfor
+  endif
+
+  ## Load the packages, but take care of the ordering of dependencies.
+  load_packages_and_dependencies (idx, handle_deps, installed_pkgs_lst, true);
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/load_packages_and_dependencies.m
@@ -0,0 +1,55 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} load_packages_and_dependencies (@var{idx}, @var{handle_deps}, @var{installed_pkgs_lst}, @var{global_install})
+## Undocumented internal function.
+## @end deftypefn
+
+function load_packages_and_dependencies (idx, handle_deps, installed_pkgs_lst,
+                                         global_install)
+  idx = load_package_dirs (idx, [], handle_deps, installed_pkgs_lst);
+  dirs = {};
+  execpath = EXEC_PATH ();
+  for i = idx;
+    ndir = installed_pkgs_lst{i}.dir;
+    dirs{end+1} = ndir;
+    if (exist (fullfile (dirs{end}, "bin"), "dir"))
+      execpath = cstrcat (execpath, pathsep (), fullfile (dirs{end}, "bin"));
+    endif
+    tmpdir = getarchdir (installed_pkgs_lst{i});
+    if (exist (tmpdir, "dir"))
+      dirs{end + 1} = tmpdir;
+      if (exist (fullfile (dirs{end}, "bin"), "dir"))
+        execpath = cstrcat (execpath, pathsep (), fullfile (dirs{end}, "bin"));
+      endif
+    endif
+  endfor
+
+  ## Load the packages.
+  if (length (dirs) > 0)
+    addpath (dirs{:});
+  endif
+
+  ## Add the binaries to exec_path.
+  if (! strcmp (EXEC_PATH, execpath))
+    EXEC_PATH (execpath);
+  endif
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/packinfo_copy_file.m
@@ -0,0 +1,38 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} packinfo_copy_file (@var{filename}, @var{requirement}, @var{packdir}, @var{packinfo}, @var{desc}, @var{octfiledir})
+## Undocumented internal function.
+## @end deftypefn
+
+function packinfo_copy_file (filename, requirement, packdir, packinfo, desc, octfiledir)
+  filepath = fullfile (packdir, filename);
+  if (!exist (filepath, "file") && strcmpi (requirement, "optional"))
+    ## do nothing, it's still OK
+  else
+    [status, output] = copyfile (filepath, packinfo);
+    if (status != 1)
+      rmdir (desc.dir, "s");
+      rmdir (octfiledir, "s");
+      error ("Couldn't copy %s file: %s", filename, output);
+    endif
+  endif
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/parse_pkg_idx.m
@@ -0,0 +1,77 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{pkg_idx_struct} =} parse_pkg_idx (@var{packdir})
+## Undocumented internal function.
+## @end deftypefn
+
+
+## Read an INDEX file.
+function pkg_idx_struct = parse_pkg_idx (packdir)
+
+  index_file = fullfile (packdir, "packinfo", "INDEX");
+
+  if (! exist (index_file, "file"))
+    error ("could not find any INDEX file in directory %s, try 'pkg rebuild all' to generate missing INDEX files", packdir);
+  endif
+
+
+  [fid, msg] = fopen (index_file, "r");
+  if (fid == -1)
+    error ("the INDEX file %s could not be read: %s",
+           index_file, msg);
+  endif
+
+  cat_num = 1;
+  pkg_idx_struct{1}.category = "Uncategorized";
+  pkg_idx_struct{1}.functions = {};
+
+  line = fgetl (fid);
+  while (isempty (strfind (line, ">>")) && ! feof (fid))
+    line = fgetl (fid);
+  endwhile
+
+  while (! feof (fid) || line != -1)
+    if (! any (! isspace (line)) || line(1) == "#" || any (line == "="))
+      ## Comments,  blank lines or comments about unimplemented
+      ## functions: do nothing
+      ## FIXME: probably comments and pointers to external functions
+      ## could be treated better when printing to screen?
+    elseif (! isempty (strfind (line, ">>")))
+      ## Skip package name and description as they are in DESCRIPTION
+      ## already.
+    elseif (! isspace (line(1)))
+      ## Category.
+      if (! isempty (pkg_idx_struct{cat_num}.functions))
+        pkg_idx_struct{++cat_num}.functions = {};
+      endif
+      pkg_idx_struct{cat_num}.category = deblank (line);
+    else
+      ## Function names.
+      while (any (! isspace (line)))
+        [fun_name, line] = strtok (line);
+        pkg_idx_struct{cat_num}.functions{end+1} = deblank (fun_name);
+      endwhile
+    endif
+    line = fgetl (fid);
+  endwhile
+  fclose (fid);
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/prepare_installation.m
@@ -0,0 +1,50 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} prepare_installation (@var{desc}, @var{packdir})
+## Undocumented internal function.
+## @end deftypefn
+
+function prepare_installation (desc, packdir)
+  ## Is there a pre_install to call?
+  if (exist (fullfile (packdir, "pre_install.m"), "file"))
+    wd = pwd ();
+    try
+      cd (packdir);
+      pre_install (desc);
+      cd (wd);
+    catch
+      cd (wd);
+      rethrow (lasterror ());
+    end_try_catch
+  endif
+
+  ## If the directory "inst" doesn't exist, we create it.
+  inst_dir = fullfile (packdir, "inst");
+  if (! exist (inst_dir, "dir"))
+    [status, msg] = mkdir (inst_dir);
+    if (status != 1)
+      rmdir (desc.dir, "s");
+      error ("the 'inst' directory did not exist and could not be created: %s",
+             msg);
+    endif
+  endif
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/print_package_description.m
@@ -0,0 +1,46 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} print_package_description (@var{pkg_name}, @var{pkg_ver}, @var{pkg_idx_struct}, @var{pkg_desc}, @var{status}, @var{verbose})
+## Undocumented internal function.
+## @end deftypefn
+
+function print_package_description (pkg_name, pkg_ver, pkg_idx_struct,
+                                    pkg_desc, status, verbose)
+
+  printf ("---\nPackage name:\n\t%s\n", pkg_name);
+  printf ("Version:\n\t%s\n", pkg_ver);
+  printf ("Short description:\n\t%s\n", pkg_desc);
+  printf ("Status:\n\t%s\n", status);
+  if (verbose)
+    printf ("---\nProvides:\n");
+    for i = 1:length (pkg_idx_struct)
+      if (! isempty (pkg_idx_struct{i}.functions))
+        printf ("%s\n", pkg_idx_struct{i}.category);
+        for j = 1:length (pkg_idx_struct{i}.functions)
+          printf ("\t%s\n", pkg_idx_struct{i}.functions{j});
+        endfor
+      endif
+    endfor
+  endif
+
+endfunction
+
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/rebuild.m
@@ -0,0 +1,100 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{descriptions} =} rebuild (@var{prefix}, @var{archprefix}, @var{list}, @var{files}, @var{auto}, @var{verbose})
+## Undocumented internal function.
+## @end deftypefn
+
+function descriptions = rebuild (prefix, archprefix, list, files, auto, verbose)
+  if (isempty (files))
+    [dirlist, err, msg] = readdir (prefix);
+    if (err)
+      error ("couldn't read directory %s: %s", prefix, msg);
+    endif
+    ## the two first entries of dirlist are "." and ".."
+    dirlist([1,2]) = [];
+  else
+    old_descriptions = installed_packages (list, list);
+    wd = pwd ();
+    unwind_protect
+      cd (prefix);
+      dirlist = glob (cellfun(@(x) cstrcat (x, '-*'), files, 'uniformoutput', 0));
+    unwind_protect_cleanup
+      cd (wd);
+    end_unwind_protect
+  endif
+  descriptions = {};
+  for k = 1:length (dirlist)
+    descfile = fullfile (prefix, dirlist{k}, "packinfo", "DESCRIPTION");
+    if (verbose)
+      printf ("recreating package description from %s\n", dirlist{k});
+    endif
+    if (exist (descfile, "file"))
+      desc = get_description (descfile);
+      desc.dir = fullfile (prefix, dirlist{k});
+      desc.archprefix = fullfile (archprefix, cstrcat (desc.name, "-",
+                                  desc.version));
+      if (auto != 0)
+        if (exist (fullfile (desc.dir, "packinfo", ".autoload"), "file"))
+          unlink (fullfile (desc.dir, "packinfo", ".autoload"));
+        endif
+        if (auto < 0)
+          desc.autoload = 0;
+        elseif (auto > 0)
+          desc.autoload = 1;
+          fclose (fopen (fullfile (desc.dir, "packinfo", ".autoload"), "wt"));
+        endif
+      else
+        if (exist (fullfile (desc.dir, "packinfo", ".autoload"), "file"))
+          desc.autoload = 1;
+        else
+          desc.autoload = 0;
+        endif
+      endif
+      descriptions{end + 1} = desc;
+    elseif (verbose)
+      warning ("directory %s is not a valid package", dirlist{k});
+    endif
+  endfor
+
+  if (! isempty (files))
+    ## We are rebuilding for a particular package(s) so we should take
+    ## care to keep the other untouched packages in the descriptions
+    descriptions = {descriptions{:}, old_descriptions{:}};
+
+    dup = [];
+    for i = 1:length (descriptions)
+      if (any (dup == i))
+        continue;
+      endif
+      for j = (i+1):length (descriptions)
+        if (any (dup == j))
+          continue;
+        endif
+        if (strcmp (descriptions{i}.name, descriptions{j}.name))
+          dup = [dup, j];
+        endif
+      endfor
+    endfor
+    if (! isempty (dup))
+      descriptions (dup) = [];
+    endif
+  endif
+endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/repackage.m
@@ -0,0 +1,90 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} repackage (@var{builddir}, @var{buildlist})
+## Undocumented internal function.
+## @end deftypefn
+
+function repackage (builddir, buildlist)
+  packages = installed_packages (buildlist, buildlist);
+
+  wd = pwd ();
+  for i = 1 : length (packages)
+    pack = packages{i};
+    unwind_protect
+      cd (builddir);
+      mkdir (pack.name);
+      mkdir (fullfile (pack.name, "inst"));
+      copyfile (fullfile (pack.dir, "*"), fullfile (pack.name, "inst"));
+      movefile (fullfile (pack.name, "inst","packinfo", "*"), pack.name);
+      if (exist (fullfile (pack.name, "inst","packinfo", ".autoload"), "file"))
+        unlink (fullfile (pack.name, "inst","packinfo", ".autoload"));
+      endif
+      rmdir (fullfile (pack.name, "inst", "packinfo"));
+      if (exist (fullfile (pack.name, "inst", "doc"), "dir"))
+        movefile (fullfile (pack.name, "inst", "doc"), pack.name);
+      endif
+      if (exist (fullfile (pack.name, "inst", "bin"), "dir"))
+        movefile (fullfile (pack.name, "inst", "bin"), pack.name);
+      endif
+      archdir = fullfile (pack.archprefix, cstrcat (pack.name, "-",
+                          pack.version), getarch ());
+      if (exist (archdir, "dir"))
+        if (exist (fullfile (pack.name, "inst", "PKG_ADD"), "file"))
+          unlink (fullfile (pack.name, "inst", "PKG_ADD"));
+        endif
+        if (exist (fullfile (pack.name, "inst", "PKG_DEL"), "file"))
+          unlink (fullfile (pack.name, "inst", "PKG_DEL"));
+        endif
+        if (exist (fullfile (archdir, "PKG_ADD"), "file"))
+          movefile (fullfile (archdir, "PKG_ADD"),
+                    fullfile (pack.name, "PKG_ADD"));
+        endif
+        if (exist (fullfile (archdir, "PKG_DEL"), "file"))
+          movefile (fullfile (archdir, "PKG_DEL"),
+                    fullfile (pack.name, "PKG_DEL"));
+        endif
+      else
+        if (exist (fullfile (pack.name, "inst", "PKG_ADD"), "file"))
+          movefile (fullfile (pack.name, "inst", "PKG_ADD"),
+                    fullfile (pack.name, "PKG_ADD"));
+        endif
+        if (exist (fullfile (pack.name, "inst", "PKG_DEL"), "file"))
+          movefile (fullfile (pack.name, "inst", "PKG_DEL"),
+                    fullfile (pack.name, "PKG_DEL"));
+        endif
+      endif
+      tfile = cstrcat (pack.name, "-", pack.version, ".tar");
+      tar (tfile, pack.name);
+      try
+        gzip (tfile);
+        unlink (tfile);
+      catch
+        warning ("failed to compress %s", tfile);
+      end_try_catch
+    unwind_protect_cleanup
+      if (exist (pack.name, "dir"))
+        rmdir (pack.name, "s");
+      endif
+      cd (wd);
+    end_unwind_protect
+  endfor
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/save_order.m
@@ -0,0 +1,60 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{newdesc} =} save_order (@var{desc})
+## Undocumented internal function.
+## @end deftypefn
+
+function newdesc = save_order (desc)
+  newdesc = {};
+  for i = 1 : length (desc)
+    deps = desc{i}.depends;
+    if (isempty (deps)
+        || (length (deps) == 1 && strcmp (deps{1}.package, "octave")))
+      newdesc {end + 1} = desc{i};
+    else
+      tmpdesc = {};
+      for k = 1 : length (deps)
+        for j = 1 : length (desc)
+          if (strcmp (desc{j}.name, deps{k}.package))
+            tmpdesc{end+1} = desc{j};
+            break;
+          endif
+        endfor
+      endfor
+      if (! isempty (tmpdesc))
+        newdesc = {newdesc{:}, save_order(tmpdesc){:}, desc{i}};
+      else
+        newdesc{end+1} = desc{i};
+      endif
+    endif
+  endfor
+  ## Eliminate the duplicates.
+  idx = [];
+  for i = 1 : length (newdesc)
+    for j = (i + 1) : length (newdesc)
+      if (strcmp (newdesc{i}.name, newdesc{j}.name))
+        idx (end + 1) = j;
+      endif
+    endfor
+  endfor
+  newdesc(idx) = [];
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/shell.m
@@ -0,0 +1,46 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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{status}, @var{output}] =} shell (@var{cmd})
+## Undocumented internal function.
+## @end deftypefn
+
+function [status, output] = shell (cmd)
+  persistent have_sh;
+
+  cmd = strrep (cmd, "\\", "/");
+  if (ispc () && ! isunix ())
+    if (isempty (have_sh))
+      if (system ("sh.exe -c \"exit\""))
+        have_sh = false;
+      else
+        have_sh = true;
+      endif
+    endif
+    if (have_sh)
+      [status, output] = system (cstrcat ("sh.exe -c \"", cmd, "\""));
+    else
+      error ("Can not find the command shell");
+    endif
+  else
+    [status, output] = system (cmd);
+  endif
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/uninstall.m
@@ -0,0 +1,147 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} uninstall (@var{pkgnames}, @var{handle_deps}, @var{verbose}, @var{local_list}, @var{global_list}, @var{global_install})
+## Undocumented internal function.
+## @end deftypefn
+
+function uninstall (pkgnames, handle_deps, verbose, local_list,
+                    global_list, global_install)
+  ## Get the list of installed packages.
+  [local_packages, global_packages] = installed_packages(local_list,
+                                                         global_list);
+  if (global_install)
+    installed_pkgs_lst = {local_packages{:}, global_packages{:}};
+  else
+    installed_pkgs_lst = local_packages;
+  endif
+
+  num_packages = length (installed_pkgs_lst);
+  delete_idx = [];
+  for i = 1:num_packages
+    cur_name = installed_pkgs_lst{i}.name;
+    if (any (strcmp (cur_name, pkgnames)))
+      delete_idx(end+1) = i;
+    endif
+  endfor
+
+  ## Are all the packages that should be uninstalled already installed?
+  if (length (delete_idx) != length (pkgnames))
+    if (global_install)
+      ## Try again for a locally installed package.
+      installed_pkgs_lst = local_packages;
+
+      num_packages = length (installed_pkgs_lst);
+      delete_idx = [];
+      for i = 1:num_packages
+        cur_name = installed_pkgs_lst{i}.name;
+        if (any (strcmp (cur_name, pkgnames)))
+          delete_idx(end+1) = i;
+        endif
+      endfor
+      if (length (delete_idx) != length (pkgnames))
+        ## FIXME: We should have a better error message.
+        warning ("some of the packages you want to uninstall are not installed");
+      endif
+    else
+      ## FIXME: We should have a better error message.
+      warning ("some of the packages you want to uninstall are not installed");
+    endif
+  endif
+
+  ## Compute the packages that will remain installed.
+  idx = setdiff (1:num_packages, delete_idx);
+  remaining_packages = {installed_pkgs_lst{idx}};
+
+  ## Check dependencies.
+  if (handle_deps)
+    error_text = "";
+    for i = 1:length (remaining_packages)
+      desc = remaining_packages{i};
+      bad_deps = get_unsatisfied_deps (desc, remaining_packages);
+
+      ## Will the uninstallation break any dependencies?
+      if (! isempty (bad_deps))
+        for i = 1:length (bad_deps)
+          dep = bad_deps{i};
+          error_text = cstrcat (error_text, " ", desc.name, " needs ",
+                               dep.package, " ", dep.operator, " ",
+                               dep.version, "\n");
+        endfor
+      endif
+    endfor
+
+    if (! isempty (error_text))
+      error ("the following dependencies where unsatisfied:\n  %s", error_text);
+    endif
+  endif
+
+  ## Delete the directories containing the packages.
+  for i = delete_idx
+    desc = installed_pkgs_lst{i};
+    ## If an 'on_uninstall.m' exist, call it!
+    if (exist (fullfile (desc.dir, "packinfo", "on_uninstall.m"), "file"))
+      wd = pwd ();
+      cd (fullfile (desc.dir, "packinfo"));
+      on_uninstall (desc);
+      cd (wd);
+    endif
+    ## Do the actual deletion.
+    if (desc.loaded)
+      rmpath (desc.dir);
+      if (exist (getarchdir (desc)))
+        rmpath (getarchdir (desc));
+      endif
+    endif
+    if (exist (desc.dir, "dir"))
+      [status, msg] = rmdir (desc.dir, "s");
+      if (status != 1 && exist (desc.dir, "dir"))
+        error ("couldn't delete directory %s: %s", desc.dir, msg);
+      endif
+      [status, msg] = rmdir (getarchdir (desc), "s");
+      if (status != 1 && exist (getarchdir (desc), "dir"))
+        error ("couldn't delete directory %s: %s", getarchdir (desc), msg);
+      endif
+      if (dirempty (desc.archprefix))
+        rmdir (desc.archprefix, "s");
+      endif
+    else
+      warning ("directory %s previously lost", desc.dir);
+    endif
+  endfor
+
+  ## Write a new ~/.octave_packages.
+  if (global_install)
+    if (length (remaining_packages) == 0)
+      unlink (global_list);
+    else
+      global_packages = save_order (remaining_packages);
+      save (global_list, "global_packages");
+    endif
+  else
+    if (length (remaining_packages) == 0)
+      unlink (local_list);
+    else
+      local_packages = save_order (remaining_packages);
+      save (local_list, "local_packages");
+    endif
+  endif
+
+endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/unload_packages.m
@@ -0,0 +1,81 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} unload_packages (@var{files}, @var{handle_deps}, @var{local_list}, @var{global_list})
+## Undocumented internal function.
+## @end deftypefn
+
+function unload_packages (files, handle_deps, local_list, global_list)
+  installed_pkgs_lst = installed_packages (local_list, global_list);
+  num_packages = length (installed_pkgs_lst);
+
+  ## Read package names and installdirs into a more convenient format.
+  pnames = pdirs = cell (1, num_packages);
+  for i = 1:num_packages
+    pnames{i} = installed_pkgs_lst{i}.name;
+    pdirs{i} = installed_pkgs_lst{i}.dir;
+    pdeps{i} = installed_pkgs_lst{i}.depends;
+  endfor
+
+  ## Get the current octave path.
+  p = strtrim (strsplit (path (), pathsep (), false));
+
+  if (length (files) == 1 && strcmp (files{1}, "all"))
+    ## Unload all.
+    dirs = pdirs;
+    desc = installed_pkgs_lst;
+  else
+    ## Unload package_name1 ...
+    dirs = {};
+    desc = {};
+    for i = 1:length (files)
+      idx = strcmp (pnames, files{i});
+      if (! any (idx))
+        error ("package %s is not installed", files{i});
+      endif
+        dirs{end+1} = pdirs{idx};
+        desc{end+1} = installed_pkgs_lst{idx};
+      endfor
+  endif
+
+  ## Check for architecture dependent directories.
+  archdirs = {};
+  for i = 1:length (dirs)
+    tmpdir = getarchdir (desc{i});
+    if (exist (tmpdir, "dir"))
+      archdirs{end+1} = dirs{i};
+      archdirs{end+1} = tmpdir;
+    else
+      archdirs{end+1} = dirs{i};
+    endif
+  endfor
+
+  ## Unload the packages.
+  for i = 1:length (archdirs)
+    d = archdirs{i};
+    idx = strcmp (p, d);
+    if (any (idx))
+      rmpath (d);
+      ## FIXME: We should also check if we need to remove items from
+      ## EXEC_PATH.
+    endif
+  endfor
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/verify_directory.m
@@ -0,0 +1,34 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} verify_directory (@var{dir})
+## Undocumented internal function.
+## @end deftypefn
+
+## Make sure the package contains the essential files.
+function verify_directory (dir)
+  needed_files = {"COPYING", "DESCRIPTION"};
+  for f = needed_files
+    if (! exist (fullfile (dir, f{1}), "file"))
+      error ("package is missing file: %s", f{1});
+    endif
+  endfor
+endfunction
+
new file mode 100644
--- /dev/null
+++ b/scripts/pkg/private/write_index.m
@@ -0,0 +1,92 @@
+## Copyright (C) 2005-2012 Søren Hauberg
+## Copyright (C) 2010 VZLU Prague, a.s.
+##
+## 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} {} write_index (@var{desc}, @var{dir}, @var{index_file}, @var{global_install})
+## Undocumented internal function.
+## @end deftypefn
+
+## Create an INDEX file for a package that doesn't provide one.
+##   'desc'  describes the package.
+##   'dir'   is the 'inst' directory in temporary directory.
+##   'index_file' is the name (including path) of resulting INDEX file.
+
+function write_index (desc, dir, index_file, global_install)
+  ## Get names of functions in dir
+  [files, err, msg] = readdir (dir);
+  if (err)
+    error ("couldn't read directory %s: %s", dir, msg);
+  endif
+
+  ## Get classes in dir
+  class_idx = find (strncmp (files, '@', 1));
+  for k = 1:length (class_idx)
+    class_name = files {class_idx (k)};
+    class_dir = fullfile (dir, class_name);
+    if (exist (class_dir, "dir"))
+      [files2, err, msg] = readdir (class_dir);
+      if (err)
+        error ("couldn't read directory %s: %s", class_dir, msg);
+      endif
+      files2 = strcat (class_name, filesep (), files2);
+      files = [files; files2];
+    endif
+  endfor
+
+  ## Check for architecture dependent files.
+  tmpdir = getarchdir (desc);
+  if (exist (tmpdir, "dir"))
+    [files2, err, msg] = readdir (tmpdir);
+    if (err)
+      error ("couldn't read directory %s: %s", tmpdir, msg);
+    endif
+    files = [files; files2];
+  endif
+
+  functions = {};
+  for i = 1:length (files)
+    file = files{i};
+    lf = length (file);
+    if (lf > 2 && strcmp (file(end-1:end), ".m"))
+      functions{end+1} = file(1:end-2);
+    elseif (lf > 4 && strcmp (file(end-3:end), ".oct"))
+      functions{end+1} = file(1:end-4);
+    endif
+  endfor
+
+  ## Does desc have a categories field?
+  if (! isfield (desc, "categories"))
+    error ("the DESCRIPTION file must have a Categories field, when no INDEX file is given");
+  endif
+  categories = strtrim (strsplit (desc.categories, ",", false));
+  if (length (categories) < 1)
+    error ("the Category field is empty");
+  endif
+
+  ## Write INDEX.
+  fid = fopen (index_file, "w");
+  if (fid == -1)
+    error ("couldn't open %s for writing", index_file);
+  endif
+  fprintf (fid, "%s >> %s\n", desc.name, desc.title);
+  fprintf (fid, "%s\n", categories{1});
+  fprintf (fid, "  %s\n", functions{:});
+  fclose (fid);
+endfunction
+
--- a/scripts/plot/__gnuplot_drawnow__.m
+++ b/scripts/plot/__gnuplot_drawnow__.m
@@ -23,10 +23,10 @@
 
 ## Author: jwe
 
-function __gnuplot_drawnow__ (h, term, file, mono, debug_file)
+function __gnuplot_drawnow__ (h, term, file, mono = false, debug_file)
 
-  if (nargin < 4)
-    mono = false;
+  if (nargin < 1 || nargin > 5 || nargin == 2)
+    print_usage ();
   endif
 
   if (nargin >= 3 && nargin <= 5)
@@ -39,7 +39,7 @@
       plot_stream = __gnuplot_open_stream__ (2, h);
       gnuplot_supports_term = __gnuplot_has_terminal__ (term, plot_stream);
       if (gnuplot_supports_term)
-        enhanced = gnuplot_set_term (plot_stream (1), true, h, term, file);
+        enhanced = gnuplot_set_term (plot_stream(1), true, h, term, file);
         __go_draw_figure__ (h, plot_stream(1), enhanced, mono);
         if (nargin == 5)
           fid = fopen (debug_file, "wb");
@@ -47,7 +47,7 @@
           __go_draw_figure__ (h, fid, enhanced, mono);
         endif
       else
-        error ("__gnuplot_drawnow__: the gnuplot terminal, \"%s\", is not available",
+        error ('__gnuplot_drawnow__: the gnuplot terminal, "%s", is not available',
                gnuplot_trim_term (term));
       endif
     unwind_protect_cleanup
@@ -65,7 +65,7 @@
         fclose (fid);
       endif
     end_unwind_protect
-  elseif (nargin == 1)
+  else  # nargin == 1
     ##  Graphics terminal for display.
     plot_stream = get (h, "__plot_stream__");
     if (isempty (plot_stream))
@@ -74,17 +74,17 @@
     else
       new_stream = false;
     endif
-    term = gnuplot_default_term ();
+    term = gnuplot_default_term (plot_stream);
     if (strcmp (term, "dumb"))
       ## popen2 eats stdout of gnuplot, use temporary file instead
       dumb_tmp_file = tmpnam ();
-      enhanced = gnuplot_set_term (plot_stream (1), new_stream, h, ...
+      enhanced = gnuplot_set_term (plot_stream(1), new_stream, h,
                                    term, dumb_tmp_file);
     else
-      enhanced = gnuplot_set_term (plot_stream (1), new_stream, h, term);
+      enhanced = gnuplot_set_term (plot_stream(1), new_stream, h, term);
     endif
-    __go_draw_figure__ (h, plot_stream (1), enhanced, mono);
-    fflush (plot_stream (1));
+    __go_draw_figure__ (h, plot_stream(1), enhanced, mono);
+    fflush (plot_stream(1));
     if (strcmp (term, "dumb"))
       fid = -1;
       while (fid < 0)
@@ -94,17 +94,14 @@
       ## reprint the plot on screen
       [a, count] = fscanf (fid, '%c', Inf);
       fclose (fid);
-      if (count>0)
-        if (a(1)==12)
-          ## avoid ^L at the beginning
-          a = a(2:end);
+      if (count > 0)
+        if (a(1) == 12)
+          a = a(2:end);  # avoid ^L at the beginning
         endif
         puts (a);
       endif
       unlink (dumb_tmp_file);
     endif
-  else
-    print_usage ();
   endif
 
 endfunction
@@ -114,16 +111,15 @@
   ## When "term" originates from print.m, it may include other options.
   if (nargin < 4)
     ## This supports the gnuplot graphics toolkit.
-    term = gnuplot_default_term ();
+    term = gnuplot_default_term (plot_stream);
     opts_str = "";
   else
-    ## Get the one word terminal id and save the remaining as options to
-    ## be passed on to gnuplot.  The terminal may respect the graphics
-    ## toolkit.
+    ## Get the one word terminal id and save the remaining as options to be
+    ## passed on to gnuplot.  The terminal may respect the graphics toolkit.
     [term, opts_str] = gnuplot_trim_term (term);
     term = lower (term);
-    if (strcmpi (term, "lua"))
-      ## Replace "lau tikz" with
+    if (strcmp (term, "lua"))
+      ## Replace "lua tikz" with just "tikz"
       term = "tikz";
       opts_str = strrep (opts_str, "tikz", "");
     endif
@@ -132,7 +128,7 @@
   if (strfind (opts_str, "noenhanced"))
     enhanced = false;
   else
-    enhanced = gnuplot_is_enhanced_term (term);
+    enhanced = gnuplot_is_enhanced_term (plot_stream, term);
   endif
 
   ## Set the terminal.
@@ -147,10 +143,10 @@
     if (! isempty (h) && isfigure (h))
 
       ## Generate gnuplot title string for plot windows.
-      if (output_to_screen (term) && ~strcmp (term, "dumb"))
+      if (output_to_screen (term) && ! strcmp (term, "dumb"))
         fig.numbertitle = get (h, "numbertitle");
-        fig.name = strrep (get (h, "name"), "\"", "\\\"");
-        if (strcmpi (get (h, "numbertitle"), "on"))
+        fig.name = strrep (get (h, "name"), '"', '\"');
+        if (strcmp (get (h, "numbertitle"), "on"))
           title_str = sprintf ("Figure %d", h);
         else
           title_str = "";
@@ -161,11 +157,11 @@
           title_str = fig.name;
         endif
         if (! isempty (title_str))
-          title_str = sprintf ("title \"%s\"", title_str);
+          title_str = sprintf ('title "%s"', title_str);
         endif
         if (strcmp (term, "aqua"))
           ## Adjust axes-label and tick-label spacing.
-          opts_str = sprintf ("%s font \"%s,%d\"", opts_str,
+          opts_str = sprintf ('%s font "%s,%d"', opts_str,
                               get (0, "defaultaxesfontname"),
                               get (0, "defaultaxesfontsize") / 1.5);
         endif
@@ -186,8 +182,8 @@
         gnuplot_pos = position_in_pixels(1:2);
         gnuplot_size = position_in_pixels(3:4);
         if (! (output_to_screen (term)
-               || any (strcmp (term, {"emf", "gif", "jpeg", "pbm", "png", ...
-                                      "pngcairo", "svg"}))))
+               || any (strcmp (term, {"canvas", "emf", "gif", "jpeg", ...
+                                      "pbm", "png", "pngcairo", "svg"}))))
           ## Convert to inches
           gnuplot_pos = gnuplot_pos / 72;
           gnuplot_size = gnuplot_size / 72;
@@ -195,8 +191,11 @@
         if (all (gnuplot_size > 0))
           terminals_with_size = {"canvas", "emf", "epslatex", "fig", ...
                                  "gif", "jpeg", "latex", "pbm", "pdf", ...
-                                 "pdfcairo", "postscript", "png", "pngcairo", ...
-                                 "pstex", "pslatex", "svg", "tikz"};
+                                 "pdfcairo", "postscript", "png", ...
+                                 "pngcairo", "pstex", "pslatex", "svg", "tikz"};
+          if (__gnuplot_has_feature__ ("windows_figure_position"))
+            terminals_with_size{end+1} = "windows";
+          endif
           if (__gnuplot_has_feature__ ("x11_figure_position"))
             terminals_with_size{end+1} = "x11";
           endif
@@ -204,31 +203,33 @@
             terminals_with_size{end+1} = "wxt";
           endif
           switch (term)
-          case terminals_with_size
-            size_str = sprintf ("size %g,%g", gnuplot_size);
-          case "tikz"
-            size_str = sprintf ("size %gin,%gin", gnuplot_size);
-          case "dumb"
-            new_stream = 1;
-            if (~isempty (getenv ("COLUMNS")) && ~isempty (getenv ("LINES")))
-              ## Let dumb use full text screen size (minus prompt lines).
-              n = sprintf ("%i", -2 - length (find (sprintf ("%s", PS1) == "\n")));
-              ## n = the number of times \n appears in PS1
-              size_str = ["size ", getenv("COLUMNS"), ",", getenv("LINES"), n];
-            else
-              ## Use the gnuplot default.
+            case terminals_with_size
+              size_str = sprintf ("size %.12g,%.12g", gnuplot_size);
+            case "tikz"
+              size_str = sprintf ("size %gin,%gin", gnuplot_size);
+            case "dumb"
+              new_stream = 1;
+              if (! isempty (getenv ("COLUMNS")) && ! isempty (getenv ("LINES")))
+                ## Let dumb use full text screen size (minus prompt lines).
+                n = sprintf ("%i", -2 - length (find (sprintf ("%s", PS1) == "\n")));
+                ## n = the number of times \n appears in PS1
+                size_str = ["size ", getenv("COLUMNS"), ",", getenv("LINES"), n];
+              else
+                ## Use the gnuplot default.
+                size_str = "";
+              endif
+            case {"aqua", "fig", "corel"}
+              size_str = sprintf ("size %g %g", gnuplot_size);
+            case "dxf"
               size_str = "";
-            endif
-          case {"aqua", "fig", "corel"}
-            size_str = sprintf ("size %g %g", gnuplot_size);
-          case "dxf"
-            size_str = "";
-          otherwise
-            size_str = "";
+            otherwise
+              size_str = "";
           endswitch
-          if (strncmpi (term, "x11", 3)
-              && __gnuplot_has_feature__ ("x11_figure_position"))
-            ## X11 allows the window to be positioned as well.
+          if ((strncmpi (term, "x11", 3)
+               && __gnuplot_has_feature__ ("x11_figure_position"))
+              || (strcmpi (term, "windows")
+                  && __gnuplot_has_feature__ ("windows_figure_position")))
+            ## X11/Windows allows the window to be positioned as well.
             units = get (0, "units");
             unwind_protect
               set (0, "units", "pixels");
@@ -237,7 +238,7 @@
               set (0, "units", units);
             end_unwind_protect
             if (all (screen_size > 0))
-              ## For X11, set the figure positon as well as the size
+              ## For X11/Windows, set the figure positon as well as the size
               ## gnuplot position is UL, Octave's is LL (same for screen/window)
               gnuplot_pos(2) = screen_size(2) - gnuplot_pos(2) - gnuplot_size(2);
               gnuplot_pos = max (gnuplot_pos, 1);
@@ -254,9 +255,9 @@
         size_str = "";
       endif
     else
-      if isempty (h)
+      if (isempty (h))
         disp ("gnuplot_set_term: figure handle is empty");
-      elseif !isfigure(h)
+      elseif (! isfigure (h))
         disp ("gnuplot_set_term: not a figure handle");
       endif
       title_str = "";
@@ -264,34 +265,49 @@
     endif
 
     ## Set the gnuplot terminal (type, enhanced, title, options & size).
-    term_str = sprintf ("set terminal %s", term);
+    term_str = ["set terminal " term];
     if (! isempty (enh_str))
-      term_str = sprintf ("%s %s", term_str, enh_str);
+      term_str = [term_str " " enh_str];
     endif
     if (! isempty (title_str))
-      term_str = sprintf ("%s %s", term_str, title_str);
+      term_str = [term_str " " title_str];
     endif
     if (isempty (strfind (term, "corel")))
       if (! isempty (size_str) && new_stream)
         ## size_str comes after other options to permit specification of
         ## the canvas size for terminals cdr/corel.
-        term_str = sprintf ("%s %s", term_str, size_str);
+        term_str = [term_str " " size_str];
       endif
       if (nargin > 3 && ischar (opts_str))
         ## Options must go last.
-        term_str = sprintf ("%s %s", term_str, opts_str);
+        term_str = [term_str " " opts_str];
       endif
     else
       if (nargin > 3 && ischar (opts_str))
         ## Options must go last.
-        term_str = sprintf ("%s %s", term_str, opts_str);
+        term_str = [term_str " " opts_str];
       endif
       if (! isempty (size_str) && new_stream)
         ## size_str comes after other options to permit specification of
         ## the canvas size for terminals cdr/corel.
-        term_str = sprintf ("%s %s", term_str, size_str);
+        term_str = [term_str " " size_str];
       endif
     endif
+    if (! __gnuplot_has_feature__ ("has_termoption_dashed"))
+      ## If "set termoption dashed" isn't available add "dashed" option
+      ## to the "set terminal ..." command, if it is supported.
+      if (any (strcmp (term, {"aqua", "cgm", "eepic", "emf", "epslatex", \
+                              "fig", "pcl5", "mp", "next", "openstep", "pdf", \
+                              "pdfcairo", "pngcairo", "postscript", \
+                              "pslatex", "pstext", "svg", "tgif", "x11"})))
+        term_str = [term_str " dashed"];
+      endif
+    end
+    if (any (strcmp (term, {"aqua", "wxt"})))
+      term_str = [term_str, " ", "dashlength 1"];
+    elseif (any (strcmp (term, {"epslatex", "postscript", "pslatex"})))
+      term_str = [term_str, " ", "dashlength 2"];
+    endif
 
     ## Work around the gnuplot feature of growing the x11 window and
     ## flickering window (x11, windows, & wxt) when the mouse and
@@ -316,6 +332,9 @@
         endif
       endif
     endif
+    if (__gnuplot_has_feature__ ("has_termoption_dashed"))
+      fprintf (plot_stream, "set termoption dashed\n")
+    endif
   else
     ## gnuplot will pick up the GNUTERM environment variable itself
     ## so no need to set the terminal type if not also setting the
@@ -324,11 +343,13 @@
 
 endfunction
 
-function term = gnuplot_default_term ()
-  term = getenv ("GNUTERM");
+function term = gnuplot_default_term (plot_stream)
+  term = lower (getenv ("GNUTERM"));
   ## If not specified, guess the terminal type.
-  if (isempty (term))
-    if (ismac ())
+  if (isempty (term) || ! __gnuplot_has_terminal__ (term, plot_stream))
+    if (isguirunning () && __gnuplot_has_terminal__ ("qt", plot_stream))
+      term = "qt";
+    elseif (ismac ())
       term = "aqua";
     elseif (! isunix ())
       term = "windows";
@@ -342,35 +363,31 @@
 
 function [term, opts] = gnuplot_trim_term (string)
   ## Extract the terminal type and terminal options (from print.m)
-  string = deblank (string);
-  n = strfind (string, ' ');
-  if (isempty (n))
-    term = string;
-    opts = "";
-  else
-    term = string(1:(n-1));
-    opts = string((n+1):end);
+  string = strtrim (string);
+  [term, opts] = strtok (string, ' ');
+  if (! isempty (opts))
+    opts(1) = "";  # trim extra space from strtok
   endif
 endfunction
 
-function have_enhanced = gnuplot_is_enhanced_term (term)
-  persistent enhanced_terminals;
-  if (isempty (enhanced_terminals))
-    ## Don't include pstex, pslatex or epslatex here as the TeX commands
-    ## should not be interpreted in that case.
-    enhanced_terminals = {"aqua", "canvas", "dumb", "emf", "gif", "jpeg", ...
-                          "pdf", "pdfcairo", "pm", "png", "pngcairo", ...
-                          "postscript", "svg", "windows", "wxt", "x11"};
+function have_enhanced = gnuplot_is_enhanced_term (plot_stream, term)
+  ## Don't include pstex, pslatex or epslatex here as the TeX commands
+  ## should not be interpreted in that case.
+  persistent enhanced_terminals = {"aqua", "canvas", "dumb", "emf", "gif", ...
+                                   "jpeg", "pdf", "pdfcairo", "pm", "png", ...
+                                   "pngcairo", "postscript", "qt", "svg",  ...
+                                   "windows", "wxt", "x11"};
+
+  if (nargin < 2)
+    ## Determine the default gnuplot terminal.
+    term = gnuplot_default_term (plot_stream);
   endif
-  if (nargin < 1)
-    ## Determine the default gnuplot terminal.
-    term = gnuplot_default_term ();
-  endif
-  have_enhanced = any (strncmp (enhanced_terminals, term, min (numel (term), 3)));
+  have_enhanced = any (strcmp (term, enhanced_terminals));
 endfunction
 
 function ret = output_to_screen (term)
-  ret = any (strcmpi ({"aqua", "dumb", "wxt", "x11", "windows", "pm"}, term));
+  ret = any (strcmpi (term, 
+                     {"aqua", "dumb", "pm", "qt", "windows", "wxt", "x11"}));
 endfunction
 
 function retval = have_non_legend_axes (h)
@@ -390,3 +407,4 @@
 
 ## No test needed for internal helper function.
 %!assert (1)
+
--- a/scripts/plot/__plt_get_axis_arg__.m
+++ b/scripts/plot/__plt_get_axis_arg__.m
@@ -80,3 +80,4 @@
 
 ## No test needed for internal helper function.
 %!assert (1)
+
--- a/scripts/plot/allchild.m
+++ b/scripts/plot/allchild.m
@@ -49,7 +49,7 @@
 %! hf = figure ("visible", "off");
 %! unwind_protect
 %!   l = line;
-%!   assert(get (allchild (hf),"type"),{"axes"; "uimenu"; "uimenu"; "uimenu"});
+%!   assert (get (allchild (hf),"type"),{"axes"; "uimenu"; "uimenu"; "uimenu"});
 %! unwind_protect_cleanup
 %!   close (hf);
 %!   graphics_toolkit (toolkit);
--- a/scripts/plot/ancestor.m
+++ b/scripts/plot/ancestor.m
@@ -18,7 +18,7 @@
 
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {@var{parent} =} ancestor (@var{h}, @var{type})
-## @deftypefnx {Function File} {@var{parent} =} ancestor (@var{h}, @var{type}, 'toplevel')
+## @deftypefnx {Function File} {@var{parent} =} ancestor (@var{h}, @var{type}, "toplevel")
 ## Return the first ancestor of handle object @var{h} whose type matches
 ## @var{type}, where @var{type} is a character string.  If @var{type} is a
 ## cell array of strings, return the first parent whose type matches
@@ -49,7 +49,7 @@
         endif
       endif
       h = num2cell (h);
-      for nh = 1:numel(h)
+      for nh = 1:numel (h)
         while (true)
           if (isempty (h{nh}) || ! ishandle (h{nh}))
             break;
@@ -75,6 +75,7 @@
 
 endfunction
 
+
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
@@ -84,3 +85,4 @@
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
--- a/scripts/plot/area.m
+++ b/scripts/plot/area.m
@@ -18,26 +18,37 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {} area (@var{x}, @var{y})
-## @deftypefnx {Function File} {} area (@var{x}, @var{y}, @var{lvl})
+## @deftypefn  {Function File} {} area (@var{y})
+## @deftypefnx {Function File} {} area (@var{x}, @var{y})
+## @deftypefnx {Function File} {} area (@dots{}, @var{lvl})
 ## @deftypefnx {Function File} {} area (@dots{}, @var{prop}, @var{val}, @dots{})
-## @deftypefnx {Function File} {} area (@var{y}, @dots{})
 ## @deftypefnx {Function File} {} area (@var{h}, @dots{})
 ## @deftypefnx {Function File} {@var{h} =} area (@dots{})
-## Area plot of cumulative sum of the columns of @var{y}.  This shows the
-## contributions of a value to a sum, and is functionally similar to
+## Area plot of the columns of @var{y}.  This shows the
+## contributions of each column value to the row sum.  It is functionally similar to
 ## @code{plot (@var{x}, cumsum (@var{y}, 2))}, except that the area under
 ## the curve is shaded.
 ##
-## If the @var{x} argument is omitted it is assumed to be given by
+## If the @var{x} argument is omitted it defaults to 
 ## @code{1 : rows (@var{y})}.  A value @var{lvl} can be defined that determines
-## where the base level of the shading under the curve should be defined.
+## where the base level of the shading under the curve should be defined.  The
+## default level is 0.
 ##
-## Additional arguments to the @code{area} function are passed to
-## @code{patch}.
+## Additional arguments to the @code{area} function are passed directly to
+## @code{patch}.  
 ##
 ## The optional return value @var{h} is a graphics handle to the hggroup
-## object representing the area patch objects.
+## object representing the area patch objects.  The "BaseValue" property
+## of the hggroup can be used to adjust the level where shading begins.
+##
+## Example: Verify identity sin^2 + cos^2 = 1
+##
+## @example
+## t = linspace (0, 2*pi, 100)';
+## y = [sin(t).^2, cos(t).^2)];
+## area (t, y);
+## legend ('sin^2', 'cos^2', 'location', 'NorthEastOutside');  
+## @end example
 ## @seealso{plot, patch}
 ## @end deftypefn
 
@@ -45,60 +56,60 @@
 
   [ax, varargin, nargin] = __plt_get_axis_arg__ ("area", varargin{:});
 
-  if (nargin > 0)
-    idx = 1;
-    x = y = [];
-    bv = 0;
-    args = {};
-    ## Check for (X) or (X,Y) arguments and possible base value.
-    if (nargin >= idx && ismatrix (varargin{idx}))
-      y = varargin{idx};
-      idx++;
-      if (nargin >= idx)
-        if (isscalar (varargin{idx}))
+  if (nargin == 0)
+    print_usage ();
+  endif
+
+  idx = 1;
+  x = y = [];
+  bv = 0;
+  args = {};
+  ## Check for (X) or (X,Y) arguments and possible base value.
+  if (nargin >= idx && ismatrix (varargin{idx}))
+    y = varargin{idx};
+    idx++;
+    if (nargin >= idx)
+      if (isscalar (varargin{idx}))
+        bv = varargin{idx};
+        idx++;
+      elseif (ismatrix (varargin{idx}))
+        x = y;
+        y = varargin{idx};
+        idx++;
+        if (nargin >= idx && isscalar (varargin{idx}))
           bv = varargin{idx};
           idx++;
-        elseif (ismatrix (varargin{idx}))
-          x = y;
-          y = varargin{idx};
-          idx++;
-          if (nargin >= idx && isscalar (varargin{idx}))
-            bv = varargin{idx};
-            idx++;
-          endif
         endif
       endif
-    else
-      print_usage ();
-    endif
-    ## Check for additional args.
-    if (nargin >= idx)
-      args = {varargin{idx:end}};
-    endif
-    newplot ();
-    if (isvector (y))
-      y = y(:);
-    endif
-    if (isempty (x))
-      x = repmat ([1:size(y, 1)]', 1, size (y, 2));
-    elseif (isvector (x))
-      x = repmat (x(:),  1, size (y, 2));
-    endif
-
-    oldax = gca ();
-    unwind_protect
-      axes (ax);
-      tmp = __area__ (ax, x, y, bv, args{:});
-    unwind_protect_cleanup
-      axes (oldax);
-    end_unwind_protect
-
-    if (nargout > 0)
-      h = tmp;
     endif
   else
     print_usage ();
   endif
+  ## Check for additional args.
+  if (nargin >= idx)
+    args = {varargin{idx:end}};
+  endif
+  newplot ();
+  if (isvector (y))
+    y = y(:);
+  endif
+  if (isempty (x))
+    x = repmat ([1:rows(y)]', 1, columns (y));
+  elseif (isvector (x))
+    x = repmat (x(:),  1, columns (y));
+  endif
+
+  oldax = gca ();
+  unwind_protect
+    axes (ax);
+    tmp = __area__ (ax, x, y, bv, args{:});
+  unwind_protect_cleanup
+    axes (oldax);
+  end_unwind_protect
+
+  if (nargout > 0)
+    h = tmp;
+  endif
 
 endfunction
 
@@ -107,7 +118,7 @@
   y0 = bv * ones (1, rows (y));
   y0 = zeros (1, rows (y));
   retval = [];
-  for i = 1: size (y, 2);
+  for i = 1: columns (y);
     hg = hggroup ();
     retval = [retval; hg];
     args = __add_datasource__ ("area", hg, {"x", "y"}, varargin{:});
@@ -157,9 +168,9 @@
 function update_props (h, d)
   kids = get (h, "children");
   set (kids, "edgecolor", get (h, "edgecolor"),
-       "linewidth", get (h, "linewidth"),
-       "linestyle", get (h, "linestyle"),
-       "facecolor", get (h, "facecolor"));
+             "linewidth", get (h, "linewidth"),
+             "linestyle", get (h, "linestyle"),
+             "facecolor", get (h, "facecolor"));
 endfunction
 
 function move_baseline (h, d)
@@ -206,3 +217,26 @@
     y0 = y1;
   endfor
 endfunction
+
+
+%!demo
+%! # Verify identity sin^2 + cos^2 = 1
+%! clf;
+%! t = linspace (0, 2*pi, 100)';
+%! y = [sin(t).^2, cos(t).^2];
+%! area (t, y);
+%! legend ('sin^2', 'cos^2', 'location', 'NorthEastOutside');  
+
+%!demo
+%! # Show effects of setting BaseValue
+%! clf;
+%! x = [-2:0.1:2]';
+%! y = x.^2 - 1;
+%! subplot (1, 2, 1)
+%! area (x, y);
+%! title ({'Parabola y = x^2 -1';'BaseValue = 0'});
+%! subplot (1, 2, 2)
+%! h = area (x, y);
+%! set (h, 'basevalue', -1);
+%! title ({'Parabola y = x^2 -1';'BaseValue = -1'});
+
--- a/scripts/plot/axes.m
+++ b/scripts/plot/axes.m
@@ -43,7 +43,7 @@
   else
     ## arg is axes handle.
     tmp = varargin{1};
-    if (length(tmp) == 1 && ishandle (tmp)
+    if (length (tmp) == 1 && ishandle (tmp)
         && strcmp (get (tmp, "type"), "axes"))
       if (__is_handle_visible__ (tmp))
         parent = ancestor (tmp, "figure");
--- a/scripts/plot/axis.m
+++ b/scripts/plot/axis.m
@@ -109,6 +109,7 @@
 ## @item "nolabel"
 ## Turn tic labels off for all axes.
 ## @end table
+##
 ## Note, if there are no tic marks for an axis, there can be no labels.
 ##
 ## @noindent
@@ -180,7 +181,7 @@
       __do_tight_option__ (ca);
     elseif (strcmpi (ax, "square"))
       set (ca, "plotboxaspectratio", [1, 1, 1]);
-    elseif  (strcmp (ax, "equal"))
+    elseif (strcmp (ax, "equal"))
       if (strcmp (get (get (ca, "parent"), "__graphics_toolkit__"), "gnuplot"))
         ## FIXME - gnuplot applies the aspect ratio activepostionproperty.
         set (ca, "activepositionproperty", "position");
@@ -321,14 +322,14 @@
     scale = get (ca, strcat (ax, "scale"));
     if (! iscell (data))
       data = {data};
-    end
+    endif
     if (strcmp (scale, "log"))
       tmp = data;
       data = cellfun (@(x) x(x>0), tmp, "uniformoutput", false);
       n = cellfun (@isempty, data);
       data(n) = cellfun (@(x) x(x<0), tmp(n), "uniformoutput", false);
     endif
-    data = cellfun (@(x) x(isfinite(x)), data, "uniformoutput", false);
+    data = cellfun (@(x) x(isfinite (x)), data, "uniformoutput", false);
     data = data(! cellfun ("isempty", data));
     if (! isempty (data))
       lims_min = min (cellfun (@(x) min (x(:)), data(:)));
@@ -346,214 +347,221 @@
   set (ca,
        "xlim", __get_tight_lims__ (ca, "x"),
        "ylim", __get_tight_lims__ (ca, "y"));
-  if __calc_dimensions__ (ca) > 2
+  if (__calc_dimensions__ (ca) > 2)
     set (ca, "zlim", __get_tight_lims__ (ca, "z"));
   endif
 
 endfunction
 
-%!demo
-%! clf
-%! t=0:0.01:2*pi; x=sin(t);
-%!
-%! subplot(221);
-%! plot(t, x);
-%! title("normal plot");
-%!
-%! subplot(222);
-%! plot(t, x);
-%! title("square plot");
-%! axis("square");
-%!
-%! subplot(223);
-%! plot(t, x);
-%! title("equal plot");
-%! axis("equal");
-%!
-%! subplot(224);
-%! plot(t, x);
-%! title("normal plot again");
-%! axis("normal");
 
 %!demo
-%! clf
-%! t=0:0.01:2*pi; x=sin(t);
+%! clf;
+%! t = 0:0.01:2*pi;
+%! x = sin (t);
+%!
+%! subplot (221);
+%!  plot (t, x);
+%!  title ('normal plot');
+%!
+%! subplot (222);
+%!  plot (t, x);
+%!  title ('square plot');
+%!  axis ('square');
+%!
+%! subplot (223);
+%!  plot (t, x);
+%!  title ('equal plot');
+%!  axis ('equal');
 %!
-%! subplot(121);
-%! plot(t, x);
-%! title("ij plot");
-%! axis("ij");
+%! subplot (224);
+%!  plot (t, x);
+%!  title ('normal plot again');
+%!  axis ('normal');
+
+%!demo
+%! clf;
+%! t = 0:0.01:2*pi;
+%! x = sin (t);
 %!
-%! subplot(122);
-%! plot(t, x);
-%! title("xy plot");
-%! axis("xy");
+%! subplot (121);
+%!  plot (t, x);
+%!  title ('ij plot');
+%!  axis ('ij');
+%!
+%! subplot (122);
+%!  plot (t, x);
+%!  title ('xy plot');
+%!  axis ('xy');
 
 %!demo
-%! clf
-%! t=0:0.01:2*pi; x=sin(t);
+%! clf;
+%! t = 0:0.01:2*pi;
+%! x = sin (t);
 %!
-%! subplot(331);
-%! plot(t, x);
-%! title("x tics and labels");
-%! axis("ticx");
+%! subplot (331);
+%!  plot (t, x);
+%!  title ('x tics and labels');
+%!  axis ('ticx');
 %!
-%! subplot(332);
-%! plot(t, x);
-%! title("y tics and labels");
-%! axis("ticy");
+%! subplot (332);
+%!  plot (t, x);
+%!  title ('y tics and labels');
+%!  axis ('ticy');
 %!
-%! subplot(333);
-%! plot(t, x);
-%! title("axis off");
-%! axis("off");
+%! subplot (333);
+%!  plot (t, x);
+%!  title ('axis off');
+%!  axis ('off');
 %!
-%! subplot(334);
-%! plot(t, x);
-%! title("x and y tics, x labels");
-%! axis("labelx","tic");
+%! subplot (334);
+%!  plot (t, x);
+%!  title ('x and y tics, x labels');
+%!  axis ('labelx','tic');
 %!
-%! subplot(335);
-%! plot(t, x);
-%! title("x and y tics, y labels");
-%! axis("labely","tic");
+%! subplot (335);
+%!  plot (t, x);
+%!  title ('x and y tics, y labels');
+%!  axis ('labely','tic');
 %!
-%! subplot(336);
-%! plot(t, x);
-%! title("all tics but no labels");
-%! axis("nolabel","tic");
+%! subplot (336);
+%!  plot (t, x);
+%!  title ('all tics but no labels');
+%!  axis ('nolabel','tic');
 %!
-%! subplot(337);
-%! plot(t, x);
-%! title("x tics, no labels");
-%! axis("nolabel","ticx");
+%! subplot (337);
+%!  plot (t, x);
+%!  title ('x tics, no labels');
+%!  axis ('nolabel','ticx');
 %!
-%! subplot(338);
-%! plot(t, x);
-%! title("y tics, no labels");
-%! axis("nolabel","ticy");
+%! subplot (338);
+%!  plot (t, x);
+%!  title ('y tics, no labels');
+%!  axis ('nolabel','ticy');
 %!
-%! subplot(339);
-%! plot(t, x);
-%! title("all tics and labels");
-%! axis("on");
+%! subplot (339);
+%!  plot (t, x);
+%!  title ('all tics and labels');
+%!  axis ('on');
 
 %!demo
-%! clf
-%! t=0:0.01:2*pi; x=sin(t);
+%! clf;
+%! t = 0:0.01:2*pi;
+%! x = sin (t);
 %!
-%! subplot(321);
-%! plot(t, x);
-%! title("axes at [0 3 0 1]")
-%! axis([0,3,0,1]);
+%! subplot (321);
+%!  plot (t, x);
+%!  title ('axes at [0 3 0 1]');
+%!  axis ([0,3,0,1]);
 %!
-%! subplot(322);
-%! plot(t, x);
-%! title("auto");
-%! axis("auto");
+%! subplot (322);
+%!  plot (t, x);
+%!  title ('auto');
+%!  axis ('auto');
 %!
-%! subplot(323);
-%! plot(t, x, ";sine [0:2pi];"); hold on;
-%! plot(-3:3,-3:3, ";line (-3,-3)->(3,3);"); hold off;
-%! title("manual");
-%! axis("manual");
+%! subplot (323);
+%!  plot (t, x, ';sine [0:2pi];'); hold on;
+%!  plot (-3:3,-3:3, ';line (-3,-3)->(3,3);'); hold off;
+%!  title ('manual');
+%!  axis ('manual');
 %!
-%! subplot(324);
-%! plot(t, x, ";sine [0:2pi];");
-%! title("axes at [0 3 0 1], then autox");
-%! axis([0,3,0,1]); axis("autox");
+%! subplot (324);
+%!  plot (t, x, ';sine [0:2pi];');
+%!  title ('axes at [0 3 0 1], then autox');
+%!  axis ([0,3,0,1]);
+%!  axis ('autox');
 %!
-%! subplot(325);
-%! plot(t, x, ";sine [0:2p];");
-%! axis([3,6,0,1]); axis("autoy");
-%! title("axes at [3 6 0 1], then autoy");
+%! subplot (325);
+%!  plot (t, x, ';sine [0:2p];');
+%!  title ('axes at [3 6 0 1], then autoy');
+%!  axis ([3,6,0,1]);
+%!  axis ('autoy');
 %!
-%! subplot(326);
-%! plot(t, sin(t), t, -2*sin(t/2))
-%! axis("tight");
-%! title("tight");
+%! subplot (326);
+%!  plot (t, sin(t), t, -2*sin(t/2));
+%!  axis ('tight');
+%!  title ('tight');
 
 %!demo
-%! clf
-%! axis image
-%! x=0:0.1:10;
-%! plot(x,sin(x))
-%! axis image
-%! title("image")
+%! clf;
+%! x = 0:0.1:10;
+%! plot (x, sin(x));
+%! axis image;
+%! title ('image');
 
 %!demo
-%! clf
-%! [x,y,z] = peaks(50);
-%! x1 = max(x(:));
-%! pcolor(x-x1,y-x1/2,z)
-%! hold on
-%! [x,y,z] = sombrero;
-%! s = x1/max(x(:));
-%! pcolor(s*x+x1,s*y+x1/2,5*z)
-%! axis tight
+%! clf;
+%! colormap ('default');
+%! [x,y,z] = peaks (50);
+%! x1 = max (x(:));
+%! pcolor (x-x1, y-x1/2, z);
+%! hold on;
+%! [x,y,z] = sombrero ();
+%! s = x1 / max (x(:));
+%! pcolor (s*x+x1, s*y+x1/2, 5*z);
+%! axis tight;
 
 %!demo
-%! clf
+%! clf;
 %! x = -10:10;
-%! plot (x, x, x, -x)
-%! set (gca, "yscale", "log")
-%! legend ({"x >= 1", "x <= 1"}, "location", "north")
-%! title ("ylim = [1, 10]")
+%! plot (x,x, x,-x);
+%! set (gca, 'yscale', 'log');
+%! legend ({'x >= 1', 'x <= 1'}, 'location', 'north');
+%! title ('ylim = [1, 10]');
 
 %!demo
-%! clf
-%! loglog (1:20, "-s")
-%! axis tight
+%! clf;
+%! loglog (1:20, '-s');
+%! axis tight;
 
 %!demo
-%! clf
+%! clf;
 %! x = -10:0.1:10;
-%! y = sin(x)./(1+abs(x)) + x*0.1 - .4;
-%! plot (x, y)
-%! title ("no plot box")
-%! set (gca, "xaxislocation", "zero")
-%! set (gca, "yaxislocation", "zero")
-%! box off
+%! y = sin (x)./(1 + abs (x)) + 0.1*x - 0.4;
+%! plot (x, y);
+%! title ('no plot box');
+%! set (gca, 'xaxislocation', 'zero');
+%! set (gca, 'yaxislocation', 'zero');
+%! box off;
 
 %!demo
-%! clf
+%! clf;
 %! x = -10:0.1:10;
-%! y = sin(x)./(1+abs(x)) + x*0.1 - .4;
-%! plot (x, y)
-%! title ("no plot box")
-%! set (gca, "xaxislocation", "zero")
-%! set (gca, "yaxislocation", "left")
-%! box off
+%! y = sin (x)./(1+abs (x)) + 0.1*x - 0.4;
+%! plot (x, y);
+%! title ('no plot box');
+%! set (gca, 'xaxislocation', 'zero');
+%! set (gca, 'yaxislocation', 'left');
+%! box off;
 
 %!demo
-%! clf
+%! clf;
 %! x = -10:0.1:10;
-%! y = sin(x)./(1+abs(x)) + x*0.1 - .4;
-%! plot (x, y)
-%! title ("no plot box")
-%! set (gca, "xaxislocation", "zero")
-%! set (gca, "yaxislocation", "right")
-%! box off
+%! y = sin (x)./(1+abs (x)) + 0.1*x - 0.4;
+%! plot (x, y);
+%! title ('no plot box');
+%! set (gca, 'xaxislocation', 'zero');
+%! set (gca, 'yaxislocation', 'right');
+%! box off;
 
 %!demo
-%! clf
+%! clf;
 %! x = -10:0.1:10;
-%! y = sin(x)./(1+abs(x)) + x*0.1 - .4;
-%! plot (x, y)
-%! title ("no plot box")
-%! set (gca, "xaxislocation", "bottom")
-%! set (gca, "yaxislocation", "zero")
-%! box off
+%! y = sin (x)./(1+abs (x)) + 0.1*x - 0.4;
+%! plot (x, y);
+%! title ('no plot box');
+%! set (gca, 'xaxislocation', 'bottom');
+%! set (gca, 'yaxislocation', 'zero');
+%! box off;
 
 %!demo
-%! clf
+%! clf;
 %! x = -10:0.1:10;
-%! y = sin(x)./(1+abs(x)) + x*0.1 - .4;
-%! plot (x, y)
-%! title ("no plot box")
-%! set (gca, "xaxislocation", "top")
-%! set (gca, "yaxislocation", "zero")
-%! box off
+%! y = sin (x)./(1+abs (x)) + 0.1*x - 0.4;
+%! plot (x, y);
+%! title ('no plot box');
+%! set (gca, 'xaxislocation', 'top');
+%! set (gca, 'yaxislocation', 'zero');
+%! box off;
 
 %!test
 %! hf = figure ("visible", "off");
@@ -571,9 +579,9 @@
 %! hf = figure ("visible", "off");
 %! unwind_protect
 %!   a = logspace (-5, 1, 10);
-%!   loglog (a, -a)
+%!   loglog (a, -a);
 %!   axis tight;
-%!   assert (axis (), [1e-5, 10, -10, -1e-5])
+%!   assert (axis (), [1e-5, 10, -10, -1e-5]);
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
--- a/scripts/plot/bar.m
+++ b/scripts/plot/bar.m
@@ -95,5 +95,15 @@
 endfunction
 
 
-%% FIXME: Need demo or test for function
+%!demo
+%! clf;
+%! y = rand (10, 1);
+%! bar (y);
 
+%!demo
+%! clf;
+%! h = bar (rand (5, 3));
+%! set (h(1), 'facecolor', 'r')
+%! set (h(2), 'facecolor', 'g')
+%! set (h(3), 'facecolor', 'b')
+
--- a/scripts/plot/barh.m
+++ b/scripts/plot/barh.m
@@ -54,5 +54,15 @@
 endfunction
 
 
-%% FIXME: Need demo or test for function
+%!demo
+%! clf;
+%! x = rand (10, 1);
+%! barh (x);
 
+%!demo
+%! clf;
+%! h = barh (rand (5, 3));
+%! set (h(1), 'facecolor', 'r')
+%! set (h(2), 'facecolor', 'g')
+%! set (h(3), 'facecolor', 'b')
+
--- a/scripts/plot/box.m
+++ b/scripts/plot/box.m
@@ -17,11 +17,16 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {} box (@var{arg})
-## @deftypefnx {Function File} {} box (@var{h}, @dots{})
+## @deftypefn  {Function File} {} box
+## @deftypefnx {Function File} {} box ("on")
+## @deftypefnx {Function File} {} box ("off")
+## @deftypefnx {Function File} {} box (@var{hax}, @dots{})
 ## Control the display of a border around the plot.
 ## The argument may be either @code{"on"} or @code{"off"}.  If it is
 ## omitted, the current box state is toggled.
+##
+## If the first argument is an axis handle, @var{hax}, operate on the
+## specified axis object.
 ## @seealso{grid}
 ## @end deftypefn
 
@@ -29,14 +34,11 @@
 
 function box (varargin)
 
-  h = gca ();
-
-  box_state = get (h, "box");
-
-  nargs = numel (varargin);
+  [ax, varargin, nargs] = __plt_get_axis_arg__ ("box", varargin{:});
 
   if (nargs == 0)
-    if (strcmpi (box_state, "on"))
+    box_state = get (ax, "box");
+    if (strcmp (box_state, "on"))
       box_state = "off";
     else
       box_state = "on";
@@ -49,13 +51,15 @@
       elseif (strcmpi (state, "on"))
         box_state = "on";
       else
-        print_usage ();
+        error ('box: argument must be "on" or "off"');
       endif
+    else
+      error ('box: argument must be "on" or "off"');
     endif
   else
     print_usage ();
   endif
 
-  set (h, "box", box_state);
+  set (ax, "box", box_state);
 
 endfunction
--- a/scripts/plot/caxis.m
+++ b/scripts/plot/caxis.m
@@ -26,8 +26,8 @@
 ## colormap.  Values outside this range are clamped to the first and last
 ## colormap entries.
 ##
-## If @var{limits} is 'auto', then automatic colormap scaling is applied,
-## whereas if @var{limits} is 'manual' the colormap scaling is set to manual.
+## If @var{limits} is "auto", then automatic colormap scaling is applied,
+## whereas if @var{limits} is "manual" the colormap scaling is set to manual.
 ##
 ## Called without any arguments to current color axis limits are returned.
 ##
--- a/scripts/plot/cla.m
+++ b/scripts/plot/cla.m
@@ -89,14 +89,16 @@
 
 endfunction
 
+
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
-%!   plot (1:10)
-%!   cla ()
+%!   plot (1:10);
+%!   cla ();
 %!   kids = get (gca, "children");
-%!   cla ()
+%!   cla ();
 %! unwind_protect_cleanup
-%!   close (hf)
+%!   close (hf);
 %! end_unwind_protect
-%! assert (numel (kids), 0)
+%! assert (numel (kids), 0);
+
--- a/scripts/plot/clabel.m
+++ b/scripts/plot/clabel.m
@@ -67,7 +67,7 @@
     hparent = gca ();
   else
     arg = varargin{1};
-    if (isscalar (arg) && ishandle(arg)
+    if (isscalar (arg) && ishandle (arg)
         && strcmp (get (arg, "type"), "hggroup"))
       obj = get (arg);
       if (! isfield (obj, "contourmatrix"))
@@ -81,7 +81,7 @@
     endif
   endif
 
-  if (length(varargin) > 0 && isnumeric (varargin{1}))
+  if (length (varargin) > 0 && isnumeric (varargin{1}))
     v = varargin{1}(:);
     varargin(1) = [];
   else
@@ -127,16 +127,19 @@
   else
     retval =  __clabel__ (c, v, hparent, label_spacing, [], varargin{:});
   endif
+
 endfunction
 
 
 %!demo
-%! clf
-%! [c, h] = contour (peaks(), -4:6);
-%! clabel (c, h, -4:2:6, "fontsize", 12);
+%! clf;
+%! colormap ('default');
+%! [c, h] = contour (peaks (), -4:6);
+%! clabel (c, h, -4:2:6, 'fontsize', 12);
 
 %!demo
-%! clf
-%! [c, h] = contourf (peaks(), -7:6);
-%! clabel (c, h, -6:2:6, "fontsize", 12);
+%! clf;
+%! colormap ('default');
+%! [c, h] = contourf (peaks (), -7:6);
+%! clabel (c, h, -6:2:6, 'fontsize', 12);
 
--- a/scripts/plot/clf.m
+++ b/scripts/plot/clf.m
@@ -89,7 +89,7 @@
 %! hf = figure ("visible", "off");
 %! unwind_protect
 %!   l = line;
-%!   assert (!isempty (get (gcf, "children")));
+%!   assert (! isempty (get (gcf, "children")));
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
--- a/scripts/plot/close.m
+++ b/scripts/plot/close.m
@@ -46,7 +46,7 @@
       close_all_figures (false);
     elseif (isfigure (arg1))
       figs = arg1;
-    elseif (isempty(arg1))
+    elseif (isempty (arg1))
       figs = [];
     else
       error ("close: expecting argument to be \"all\" or a figure handle");
@@ -80,6 +80,7 @@
 
 endfunction
 
+
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
@@ -91,3 +92,4 @@
 %!     close (hf);
 %!   endif
 %! end_unwind_protect
+
--- a/scripts/plot/colorbar.m
+++ b/scripts/plot/colorbar.m
@@ -63,7 +63,7 @@
   i = 1;
   while (i <= nargin)
     arg = varargin {i++};
-    if (ischar(arg))
+    if (ischar (arg))
       if (strcmpi (arg, "peer"))
         if (i > nargin)
           error ("colorbar: missing axes handle after \"peer\"");
@@ -162,7 +162,7 @@
                   "yliminclude", "off", "zliminclude", "off",
                   "deletefcn", {@deletecolorbar, cax, obj});
 
-    set (cax, "deletefcn", {@resetaxis, obj});
+    set (cax, "deletefcn", {@resetaxis, ax, obj});
 
     addlistener (ax, "clim", {@update_colorbar_clim, hi, vertical});
     addlistener (ax, "plotboxaspectratio", {@update_colorbar_axis, cax, obj});
@@ -182,7 +182,7 @@
   ## Don't delete the colorbar and reset the axis size if the
   ## parent figure is being deleted.
   if (ishandle (hc) && strcmp (get (hc, "type"), "axes")
-      && (isempty (gcbf()) || strcmp (get (gcbf(), "beingdeleted"),"off")))
+      && (isempty (gcbf ()) || strcmp (get (gcbf (), "beingdeleted"),"off")))
     if (strcmp (get (hc, "beingdeleted"), "off"))
       delete (hc);
     endif
@@ -195,19 +195,21 @@
   endif
 endfunction
 
-function resetaxis (h, d, orig_props)
-  if (ishandle (h) && strcmp (get (h, "type"), "axes")
-      && (isempty (gcbf()) || strcmp (get (gcbf(), "beingdeleted"),"off"))
-      && ishandle (get (h, "axes")))
-     set (get (h, "axes"), "position", orig_props.position, ...
-                           "outerposition", orig_props.outerposition, ...
-                   "activepositionproperty", orig_props.activepositionproperty);
+function resetaxis (cax, d, ax, orig_props)
+  if (ishandle (ax) && strcmp (get (ax, "type"), "axes"))
+    dellistener (ax, "position");
+    units = get (ax, "units");
+    set (ax, "units", orig_props.units);
+    set (ax, "position", orig_props.position, ...
+             "outerposition", orig_props.outerposition, ...
+             "activepositionproperty", orig_props.activepositionproperty);
+    set (ax, "units", units);
   endif
 endfunction
 
 function update_colorbar_clim (h, d, hi, vert)
   if (ishandle (h) && strcmp (get (h, "type"), "image")
-      && (isempty (gcbf()) || strcmp (get (gcbf(), "beingdeleted"),"off")))
+      && (isempty (gcbf ()) || strcmp (get (gcbf (), "beingdeleted"),"off")))
     clen = rows (get (get (h, "parent"), "colormap"));
     cext = get (h, "clim");
     cdiff = (cext(2) - cext(1)) / clen / 2;
@@ -227,7 +229,7 @@
 function update_colorbar_axis (h, d, cax, orig_props)
 
   if (ishandle (cax) && strcmp (get (cax, "type"), "axes")
-      && (isempty (gcbf()) || strcmp (get (gcbf(), "beingdeleted"),"off")))
+      && (isempty (gcbf ()) || strcmp (get (gcbf (), "beingdeleted"),"off")))
     loc = get (cax, "location");
     obj = get (h);
     obj.__my_handle__ = h;
@@ -362,252 +364,288 @@
 
 endfunction
 
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! imagesc(x)
-%! colorbar();
-
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! imagesc(x)
-%! colorbar("westoutside");
-
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! imagesc(x)
-%! colorbar("peer", gca (), "northoutside");
-
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! imagesc(x)
-%! colorbar("southoutside");
-
-%!demo
-%! clf
-%! contour(peaks())
-%! colorbar("west");
-
-%!demo
-%! clf
-%! subplot(2,2,1)
-%! contour(peaks())
-%! colorbar("east");
-%! subplot(2,2,2)
-%! contour(peaks())
-%! colorbar("west");
-%! subplot(2,2,3)
-%! contour(peaks())
-%! colorbar("north");
-%! subplot(2,2,4)
-%! contour(peaks())
-%! colorbar("south");
-
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! subplot(2,2,1)
-%! imagesc(x)
-%! colorbar();
-%! subplot(2,2,2)
-%! imagesc(x)
-%! colorbar("westoutside");
-%! subplot(2,2,3)
-%! imagesc(x)
-%! colorbar("northoutside");
-%! subplot(2,2,4)
-%! imagesc(x)
-%! colorbar("southoutside");
-
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! subplot(1,2,1)
-%! imagesc(x)
-%! axis square;
-%! colorbar();
-%! subplot(1,2,2)
-%! imagesc(x)
-%! axis square;
-%! colorbar("westoutside");
-
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! subplot(1,2,1)
-%! imagesc(x)
-%! axis square;
-%! colorbar("northoutside");
-%! subplot(1,2,2)
-%! imagesc(x)
-%! axis square;
-%! colorbar("southoutside");
 
 %!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! subplot(2,1,1)
-%! imagesc(x)
-%! axis square;
-%! colorbar();
-%! subplot(2,1,2)
-%! imagesc(x)
-%! axis square;
-%! colorbar("westoutside");
-
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! subplot(2,1,1)
-%! imagesc(x)
-%! axis square;
-%! colorbar("northoutside");
-%! subplot(2,1,2)
-%! imagesc(x)
-%! axis square;
-%! colorbar("southoutside");
-
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! subplot(1,2,1)
-%! imagesc(x)
-%! colorbar();
-%! subplot(1,2,2)
-%! imagesc(x)
-%! colorbar("westoutside");
-
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! subplot(1,2,1)
-%! imagesc(x)
-%! colorbar("northoutside");
-%! subplot(1,2,2)
-%! imagesc(x)
-%! colorbar("southoutside");
-
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! subplot(2,1,1)
-%! imagesc(x)
-%! colorbar();
-%! subplot(2,1,2)
-%! imagesc(x)
-%! colorbar("westoutside");
-
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! subplot(2,1,1)
-%! imagesc(x)
-%! colorbar("northoutside");
-%! subplot(2,1,2)
-%! imagesc(x)
-%! colorbar("southoutside");
-
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! subplot(1,2,1)
-%! contour(x)
-%! axis square;
-%! colorbar("east");
-%! xlim ([1, 64])
-%! ylim ([1, 64])
-%! subplot(1,2,2)
-%! contour(x)
-%! colorbar("west");
-%! xlim ([1, 64])
-%! ylim ([1, 64])
-
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! contour (x)
-%! xlim ([1, 64])
-%! ylim ([1, 64])
-%! colorbar ();
-%! colorbar off
-
-%!demo
-%! clf
-%! n = 64; x = kron (1:n,ones(n,1)); x = abs(x - x.');
-%! contour (x)
-%! xlim ([1, 64])
-%! ylim ([1, 64])
-%! colorbar ();
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! imagesc (x);
 %! colorbar ();
 
 %!demo
-%! clf
-%! imagesc (1./hilb(99));
-%! h = colorbar;
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! imagesc (x);
+%! colorbar ('westoutside');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! imagesc (x);
+%! colorbar ('peer', gca, 'northoutside');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! imagesc (x);
+%! colorbar ('southoutside');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! contour (peaks ());
+%! colorbar ('west');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! subplot (2,2,1);
+%!  contour (peaks ());
+%!  colorbar ('east');
+%! subplot (2,2,2);
+%!  contour (peaks ());
+%!  colorbar ('west');
+%! subplot (2,2,3);
+%!  contour (peaks ());
+%!  colorbar ('north');
+%! subplot (2,2,4);
+%!  contour (peaks ());
+%!  colorbar ('south');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! subplot (2,2,1);
+%!  imagesc (x);
+%!  colorbar ();
+%! subplot (2,2,2);
+%!  imagesc (x);
+%!  colorbar ('westoutside');
+%! subplot (2,2,3);
+%!  imagesc (x);
+%!  colorbar ('northoutside');
+%! subplot (2,2,4);
+%!  imagesc (x);
+%!  colorbar ('southoutside');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! subplot (1,2,1);
+%!  imagesc (x);
+%!  axis square;
+%!  colorbar ();
+%! subplot (1,2,2);
+%!  imagesc (x);
+%!  axis square;
+%!  colorbar ('westoutside');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! subplot (1,2,1);
+%!  imagesc (x);
+%!  axis square;
+%!  colorbar ('northoutside');
+%! subplot (1,2,2);
+%!  imagesc (x);
+%!  axis square;
+%!  colorbar ('southoutside');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! subplot (2,1,1);
+%!  imagesc (x);
+%!  axis square;
+%!  colorbar ();
+%! subplot (2,1,2);
+%!  imagesc (x);
+%!  axis square;
+%!  colorbar ('westoutside');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! subplot (2,1,1);
+%!  imagesc (x);
+%!  axis square;
+%!  colorbar ('northoutside');
+%! subplot (2,1,2);
+%!  imagesc (x);
+%!  axis square;
+%!  colorbar ('southoutside');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! subplot (1,2,1);
+%!  imagesc (x);
+%!  colorbar ();
+%! subplot (1,2,2);
+%!  imagesc (x);
+%!  colorbar ('westoutside');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! subplot (1,2,1);
+%!  imagesc (x);
+%!  colorbar ('northoutside');
+%! subplot (1,2,2);
+%!  imagesc (x);
+%!  colorbar ('southoutside');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! subplot (2,1,1);
+%!  imagesc (x);
+%!  colorbar ();
+%! subplot (2,1,2);
+%!  imagesc (x);
+%!  colorbar ('westoutside');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! subplot (2,1,1);
+%!  imagesc (x);
+%!  colorbar ('northoutside');
+%! subplot (2,1,2);
+%!  imagesc (x);
+%!  colorbar ('southoutside');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! subplot (1,2,1);
+%!  contour (x);
+%!  axis square;
+%!  colorbar ('east');
+%!  xlim ([1, 64]);
+%!  ylim ([1, 64]);
+%! subplot (1,2,2);
+%!  contour (x);
+%!  colorbar ('west');
+%!  xlim ([1, 64]);
+%!  ylim ([1, 64]);
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! contour (x);
+%! xlim ([1, 64]);
+%! ylim ([1, 64]);
+%! colorbar ();
+%! colorbar off;
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! n = 64; x = kron (1:n, ones (n,1)); x = abs (x - x.');
+%! contour (x);
+%! xlim ([1, 64]);
+%! ylim ([1, 64]);
+%! colorbar ();
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! imagesc (1 ./ hilb (99));
+%! h = colorbar ();
 %! set (h, 'yscale', 'log');
 
 %!demo
-%! clf
+%! clf;
+%! colormap ('default');
 %! imagesc (log10 (1 ./ hilb (99)));
-%! h = colorbar;
-%! ytick = get(h, "ytick");
-%! set (h, "yticklabel", sprintf ('10^{%g}|', ytick));
-
-%!demo
-%! clf
-%! n=5;x=linspace(0,5,n);y=linspace(0,1,n);
-%! imagesc(1./hilb(n)); axis equal; colorbar
+%! h = colorbar ();
+%! ytick = get (h, 'ytick');
+%! set (h, 'yticklabel', sprintf ('10^{%g}|', ytick));
 
 %!demo
-%! clf
-%! n=5;x=linspace(0,5,n);y=linspace(0,1,n);
-%! imagesc(x,y,1./hilb(n)); axis equal; colorbar
+%! clf;
+%! colormap ('default');
+%! n = 5; x = linspace (0,5,n); y = linspace (0,1,n);
+%! imagesc (1 ./ hilb (n));
+%! axis equal;
+%! colorbar ();
 
 %!demo
-%! clf
-%! n=5;x=linspace(0,5,n);y=linspace(0,1,n);
-%! imagesc(y,x,1./hilb(n)); axis equal; colorbar
-## This requires that the axes position be properly determined for "axes equal"
-
-%!demo
-%! clf
-%! axes
-%! colorbar
-%! hold on
-%! contour(peaks)
-%! hold off
+%! clf;
+%! colormap ('default');
+%! n = 5; x = linspace (0,5,n); y = linspace (0,1,n);
+%! imagesc (x, y, 1 ./ hilb (n));
+%! axis equal;
+%! colorbar ();
 
 %!demo
-%! clf
-%! plot([0, 2])
-%! colorbar ("east")
-%! axis square
+%! clf;
+%! colormap ('default');
+%! n = 5; x = linspace (0,5,n); y = linspace (0,1,n);
+%! imagesc (y, x, 1 ./ hilb (n));
+%! axis equal;
+%! colorbar ();
+
+## This requires that the axes position be properly determined for 'axis equal'
+%!demo
+%! clf;
+%! colormap ('default');
+%! axes;
+%! colorbar ();
+%! hold on;
+%! contour (peaks ());
+%! hold off;
 
 %!demo
-%! clf
-%! plot([0, 2])
-%! colorbar ("eastoutside")
-%! axis square
+%! clf;
+%! colormap ('default');
+%! plot ([0, 2]);
+%! colorbar ('east');
+%! axis square;
 
 %!demo
-%! clf
-%! pcolor (peaks (20))
-%! shading ("interp")
-%! axis ("tight", "square")
-%! colorbar ()
-#%! axes('color','none','box','on','activepositionproperty','position')
+%! clf;
+%! colormap ('default');
+%! plot ([0, 2]);
+%! colorbar ('eastoutside');
+%! axis square;
 
 %!demo
-%! clf
-%! plot([0, 2])
-%! colorbar ("east")
-%! axis equal
+%! clf;
+%! colormap ('default');
+%! pcolor (peaks (20));
+%! shading interp;
+%! axis ('tight', 'square');
+%! colorbar ();
+#%! axes ('color','none','box','on','activepositionproperty','position');
 
 %!demo
-%! clf
-%! plot([0, 2])
-%! colorbar ("eastoutside")
-%! axis equal
+%! clf;
+%! colormap ('default');
+%! plot ([0, 2]);
+%! colorbar ('east');
+%! axis equal;
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! plot ([0, 2]);
+%! colorbar ('eastoutside');
+%! axis equal;
+
--- a/scripts/plot/colstyle.m
+++ b/scripts/plot/colstyle.m
@@ -64,6 +64,7 @@
 
 endfunction
 
+
 %!test
 %! [l, c, m, msg] = colstyle ("r:x");
 %! assert (isempty (msg));
--- a/scripts/plot/comet.m
+++ b/scripts/plot/comet.m
@@ -44,7 +44,7 @@
     print_usage ();
   elseif (nargin == 1)
     y = varargin{1};
-    x = 1:numel(y);
+    x = 1:numel (y);
     p = 0.1;
   elseif (nargin == 2)
     x = varargin{1};
@@ -78,11 +78,11 @@
 
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
 %! t = 0:.1:2*pi;
-%! x = cos(2*t).*(cos(t).^2);
-%! y = sin(2*t).*(sin(t).^2);
-%! comet(x,y)
+%! x = cos (2*t) .* (cos (t).^2);
+%! y = sin (2*t) .* (sin (t).^2);
+%! comet (x, y);
 
-
--- a/scripts/plot/comet3.m
+++ b/scripts/plot/comet3.m
@@ -43,7 +43,7 @@
     print_usage ();
   elseif (nargin == 1)
     z = varargin{1};
-    x = y = 1:numel(z);
+    x = y = 1:numel (z);
     p = 0.1;
   elseif (nargin == 3)
     x = varargin{1};
@@ -80,7 +80,9 @@
 
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
 %! t = 0:pi/20:5*pi;
-%! comet3 (cos(t), sin(t), t, 0.01);
+%! comet3 (cos (t), sin (t), t, 0.01);
+
--- a/scripts/plot/compass.m
+++ b/scripts/plot/compass.m
@@ -112,7 +112,7 @@
 
 
 %!demo
-%! clf
+%! clf;
 %! randn_9x1_data = [-2.555884; 0.394974; -0.191871; -1.147024; 1.355425; -0.437335; -0.014370; -0.941312; 1.240300];
 %! randn_1x9_data = [1.42934, -1.10821, -1.70404, 0.63357, -0.68337, -1.19771, -0.96502, -1.12810, 0.22457];
 %! a = toeplitz ([1;randn_9x1_data], [1,randn_1x9_data]);
--- a/scripts/plot/contour.m
+++ b/scripts/plot/contour.m
@@ -70,23 +70,27 @@
 
 endfunction
 
+
 %!demo
-%! clf ()
+%! clf;
+%! colormap ('default');
 %! [x, y, z] = peaks ();
 %! contour (x, y, z);
 
 %!demo
-%! clf ()
-%! [theta, r] = meshgrid (linspace (0, 2*pi, 64), linspace(0,1,64));
+%! clf;
+%! colormap ('default');
+%! [theta, r] = meshgrid (linspace (0,2*pi,64), linspace (0,1,64));
 %! [X, Y] = pol2cart (theta, r);
-%! Z = sin(2*theta).*(1-r);
-%! contour(X, Y, abs(Z), 10)
+%! Z = sin (2*theta) .* (1-r);
+%! contour (X, Y, abs (Z), 10);
 
 %!demo
-%! clf ()
+%! clf;
+%! colormap ('default');
 %! x = linspace (-2, 2);
 %! [x, y] = meshgrid (x);
-%! z = sqrt (x.^2 + y.^2) ./ (x.^2 + y.^2+1);
-%! contourf (x, y, z, [0.4, 0.4])
-%! title ("The hole should be filled with the background color")
+%! z = sqrt (x.^2 + y.^2) ./ (x.^2 + y.^2 + 1);
+%! contourf (x, y, z, [0.4, 0.4]);
+%! title ('The hole should be filled with the background color');
 
--- a/scripts/plot/contour3.m
+++ b/scripts/plot/contour3.m
@@ -74,13 +74,15 @@
 
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
 %! contour3 (peaks (19));
-%! hold on
-%! surface (peaks (19), "facecolor", "none", "edgecolor", "black")
-%! colormap hot
-%! axis tight
-%! zlim auto
-%! hold off
-%! box off
+%! hold on;
+%! surface (peaks (19), 'facecolor', 'none', 'edgecolor', 'black');
+%! colormap (hot (64));
+%! axis tight;
+%! zlim auto;
+%! box off;
+%! hold off;
+
--- a/scripts/plot/contourc.m
+++ b/scripts/plot/contourc.m
@@ -101,8 +101,8 @@
     c = __contourc__ (x(:)', y(:)', z, vv);
   else
     ## Indexes x,y for the purpose of __contourc__.
-    ii = 1:size (z,2);
-    jj = 1:size (z,1);
+    ii = 1:columns (z);
+    jj = 1:rows (z);
 
     ## Now call __contourc__ for the real work...
     c = __contourc__ (ii, jj, z, vv);
@@ -111,7 +111,7 @@
     ## to the original grid (x,y)
     i = 1;
 
-    while (i < size (c,2))
+    while (i < columns (c))
       clen = c(2, i);
       ind = i + [1 : clen];
 
@@ -123,8 +123,8 @@
       ## return NA for those values.
       ## The permitted range is enforced here:
 
-      ci = max (ci, 1); ci = min (ci, size (z, 2));
-      cj = max (cj, 1); cj = min (cj, size (z, 1));
+      ci = max (ci, 1); ci = min (ci, columns (z));
+      cj = max (cj, 1); cj = min (cj, rows (z));
 
       c(1, ind) = interp2 (ii, jj, x, ci, cj);
       c(2, ind) = interp2 (ii, jj, y, ci, cj);
@@ -140,6 +140,7 @@
 
 endfunction
 
+
 %!test
 %! x = 0:2;
 %! y = x;
@@ -147,7 +148,6 @@
 %! [c_actual, lev_actual]= contourc (x, y, z, 2:3);
 %! c_expected = [2, 1, 1, 2, 2, 3, 1.5, 2; 4, 2, 2, 1, 1, 2, 2, 1.5];
 %! lev_expected = [2 3];
-%! assert (c_actual, c_expected, eps)
-%! assert (lev_actual, lev_expected, eps)
+%! assert (c_actual, c_expected, eps);
+%! assert (lev_actual, lev_expected, eps);
 
-
--- a/scripts/plot/contourf.m
+++ b/scripts/plot/contourf.m
@@ -78,16 +78,21 @@
     c = ctmp;
     h = htmp;
   endif
+
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
+%! colormap ('default');
 %! [x, y, z] = peaks (50);
-%! contourf (x, y, z, -7:9)
+%! contourf (x, y, z, -7:9);
 
 %!demo
-%! clf
-%! [theta, r] = meshgrid (linspace (0, 2*pi, 64), linspace(0,1,64));
+%! clf;
+%! colormap ('default');
+%! [theta, r] = meshgrid (linspace (0,2*pi,64), linspace (0,1,64));
 %! [X, Y] = pol2cart (theta, r);
-%! Z = sin(2*theta).*(1-r);
-%! contourf(X, Y, abs(Z), 10)
+%! Z = sin (2*theta) .* (1-r);
+%! contourf (X, Y, abs (Z), 10);
+
new file mode 100644
--- /dev/null
+++ b/scripts/plot/copyobj.m
@@ -0,0 +1,140 @@
+## Copyright (C) 2012 pdiribarne
+##
+## 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 Octave; see the file COPYING.  If not, see
+## <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn  {Function File} {@var{hnew} =} copyobj (@var{horig})
+## @deftypefnx {Function File} {@var{hnew} =} copyobj (@var{horig}, @var{hparent})
+## Construct a copy of the object associated with handle @var{horig}
+## and return a handle @var{hnew} to the new object.
+## If a parent handle @var{hparent} (root, figure, axes, or hggroup) is
+## specified, the copied object will be created as a child to @var{hparent}.
+## @seealso{findobj, get, set, struct2hdl, hdl2struct}
+## @end deftypefn
+
+## Author: pdiribarne <pdiribarne@new-host.home>
+## Created: 2012-04-01
+
+function hnew = copyobj (horig, hparent = 0)
+
+  partypes = {"root", "figure", "axes", "hggroup"};
+  othertypes = {"line", "patch", "surface", "image", "text"};
+  alltypes = [partypes othertypes];
+
+  if (! ishandle (horig) || nargin > 2)
+    print_usage ();
+  elseif (! ishandle (hparent))
+    hparent = figure (fix (hparent));
+  elseif (! any (strcmpi (get (hparent).type, partypes)))
+    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));
+
+  if (kididx <= paridx)
+    error ("copyobj: %s object can't be children to %s.",
+           alltypes{kididx}, alltypes{paridx});
+  elseif (nargin == 1)
+    str = hdl2struct (horig);
+    hnew = struct2hdl (str);
+  else
+    str = hdl2struct (horig);
+    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
+
+
+%!demo
+%! hdl = figure (1234);
+%! clf;
+%! hold on;
+%! x = 1:10;
+%! y = x.^2;
+%! dy = 2 * (.2 * x);
+%! y2 = (x - 3).^2;
+%! hg = errorbar (x, y, dy,'#~');
+%! set (hg, 'marker', '^', 'markerfacecolor', rand (1,3));
+%! plot (x, y2, 'ok-');
+%! legend ('errorbar', 'line');
+%! hnew = copyobj (hdl);
+
+%!demo
+%! ## FIXME: This demo fails occasionally for an obscure reason.
+%! ## It appears that there is something wrong with Octave code for patches.
+%! hdl = figure (1234);
+%! clf;
+%! subplot (2,2,1);
+%! hold on;
+%! contourf (rand (10, 10));
+%! colorbar;
+%! subplot (2,2,2);
+%! quiver (rand (10, 10), rand (10, 10));
+%! subplot (2,2,3);
+%! colormap (jet (64));
+%! hold on;
+%! sombrero;
+%! colorbar ('peer', gca, 'NorthOutside');
+%! subplot (2,2,4);
+%! imagesc (rand (30, 30));
+%! text (15, 15, 'Rotated text', ...
+%!      'HorizontAlalignment', 'Center', 'Rotation', 30);
+%! hnew = copyobj (hdl);
+
+%!testif HAVE_MAGICK
+%! h1 = figure ();
+%! set (h1, "visible", "off");
+%! x = 0:0.1:2*pi;
+%! y1 = sin (x);
+%! y2 = exp (x - 1);
+%! ax = plotyy (x,y1, x-1,y2, @plot, @semilogy);
+%! xlabel ("X");
+%! ylabel (ax(1), "Axis 1");
+%! ylabel (ax(2), "Axis 2");
+%! axes (ax(1));
+%! text (0.5, 0.5, "Left Axis", ...
+%!       "color", [0 0 1], "horizontalalignment", "center");
+%! axes (ax(2));
+%! text (4.5, 80, "Right Axis", ...
+%!       "color", [0 0.5 0], "horizontalalignment", "center");
+%! s1 = hdl2struct (h1);
+%! h2 = struct2hdl (s1);
+%! s2 = hdl2struct (h2);
+%! png1 = strcat (tmpnam (), ".png");
+%! png2 = strcat (tmpnam (), ".png");
+%! unwind_protect
+%!   print (h1, png1);
+%!   [img1, map1, alpha1] = imread (png1);
+%!   print (h2, png2);
+%!   [img2, map2, alpha2] = imread (png2);
+%! unwind_protect_cleanup
+%!   unlink (png1);
+%!   unlink (png2);
+%! end_unwind_protect
+%! assert (img1, img2);
+%! assert (map1, map2);
+%! assert (alpha1, alpha2);
--- a/scripts/plot/cylinder.m
+++ b/scripts/plot/cylinder.m
@@ -65,13 +65,13 @@
   endif
 
   if (length (r) < 2)
-    error ("cylinder: length(R) must be larger than 2");
+    error ("cylinder: length (R) must be larger than 2");
   endif
 
   phi = linspace (0, 2*pi, n+1);
-  idx = 1:length(r);
-  [phi, idx] = meshgrid(phi, idx);
-  z = (idx - 1) / (length(r) - 1);
+  idx = 1:length (r);
+  [phi, idx] = meshgrid (phi, idx);
+  z = (idx - 1) / (length (r) - 1);
   r = r(idx);
   [x, y] = pol2cart (phi, r);
 
@@ -85,8 +85,11 @@
 
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
+%! colormap ('default');
 %! [x, y, z] = cylinder (10:-1:0,50);
 %! surf (x, y, z);
-%! title ("a cone")
+%! title ('a cone');
+
--- a/scripts/plot/daspect.m
+++ b/scripts/plot/daspect.m
@@ -17,23 +17,28 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} daspect (@var{data_aspect_ratio})
-## Set the data aspect ratio of the current axes.  The aspect ratio is
-## a normalized 3-element vector representing the span of the x, y, and
-## z-axes limits.
-##
-## @deftypefnx {Function File} {@var{data_aspect_ratio} =} daspect ( )
-## Return the data aspect ratio of the current axes.
-##
+## @deftypefn  {Function File} {@var{data_aspect_ratio} =} daspect ()
+## @deftypefnx {Function File} {} daspect (@var{data_aspect_ratio})
 ## @deftypefnx {Function File} {} daspect (@var{mode})
-## Set the data aspect ratio mode of the current axes.
+## @deftypefnx {Function File} {@var{data_aspect_ratio_mode} =} daspect ("mode")
+## @deftypefnx {Function File} {} daspect (@var{hax}, @dots{})
+## Query or set the data aspect ratio of the current axes.  The aspect 
+## ratio is a normalized 3-element vector representing the span of the x, y,
+## and z-axis limits.
+## 
+## @code{(daspect (@var{mode}))}
 ##
-## @deftypefnx {Function File} {@var{data_aspect_ratio_mode} =} daspect ("mode")
+## Set the data aspect ratio mode of the current axes.  @var{mode} is
+## either "auto" or "manual".
+## 
+## @code{daspect ("mode")}
+##
 ## Return the data aspect ratio mode of the current axes.
+## 
+## @code{daspect (@var{hax}, @dots{})}
 ##
-## @deftypefnx {Function File} {} daspect (@var{hax}, @dots{})
-## Use the axes, with handle @var{hax}, instead of the current axes.
-##
+## Operate on the axes in handle @var{hax} instead of the current axes.
+## 
 ## @seealso{axis, pbaspect, xlim, ylim, zlim}
 ## @end deftypefn
 
@@ -89,45 +94,46 @@
 
 endfunction
 
-%!demo
-%! x = 0:0.01:4;
-%! clf
-%! plot (x, cos (x), x, sin (x))
-%! axis square
-%! daspect ([1 1 1])
-%! title ("square plot-box with axis limits [0, 4, -2, 2]")
 
 %!demo
+%! clf;
 %! x = 0:0.01:4;
-%! clf
-%! plot (x, cos (x), x, sin (x))
-%! axis ([0 4 -1 1])
-%! daspect ([2 1 1])
-%! title ("square plot-box with axis limits [0, 4, -1, 1]")
+%! plot (x,cos(x), x,sin(x));
+%! axis square;
+%! daspect ([1 1 1]);
+%! title ('square plot-box with axis limits [0, 4, -2, 2]');
+
+%!demo
+%! clf;
+%! x = 0:0.01:4;
+%! plot (x,cos (x), x,sin (x));
+%! axis ([0 4 -1 1]);
+%! daspect ([2 1 1]);
+%! title ('square plot-box with axis limits [0, 4, -1, 1]');
 
 %!demo
+%! clf;
 %! x = 0:0.01:4;
-%! clf
-%! plot (x, cos (x), x, sin (x))
-%! daspect ([1 2 1])
-%! pbaspect ([2 1 1])
-%! title ("2x1 plot box with axis limits [0, 4, -2, 2]")
+%! plot (x,cos(x), x,sin(x));
+%! daspect ([1 2 1]);
+%! pbaspect ([2 1 1]);
+%! title ('2x1 plot box with axis limits [0, 4, -2, 2]');
 
 %!demo
+%! clf;
 %! x = 0:0.01:4;
-%! clf
-%! plot (x, cos (x), x, sin (x))
-%! axis square
-%! set (gca, "activepositionproperty", "position")
-%! daspect ([1 1 1])
-%! title ("square plot-box with axis limits [0, 4, -2, 2]")
+%! plot (x,cos(x), x, sin(x));
+%! axis square;
+%! set (gca, 'activepositionproperty', 'position');
+%! daspect ([1 1 1]);
+%! title ('square plot-box with axis limits [0, 4, -2, 2]');
 
 %!demo
+%! clf;
 %! x = 0:0.01:4;
-%! clf
-%! plot (x, cos (x), x, sin (x))
-%! axis ([0 4 -1 1])
-%! set (gca, "activepositionproperty", "position")
-%! daspect ([2 1 1])
-%! title ("square plot-box with axis limits [0, 4, -1, 1]")
+%! plot (x,cos(x), x,sin(x));
+%! axis ([0 4 -1 1]);
+%! set (gca, 'activepositionproperty', 'position');
+%! daspect ([2 1 1]);
+%! title ('square plot-box with axis limits [0, 4, -1, 1]');
 
--- a/scripts/plot/ellipsoid.m
+++ b/scripts/plot/ellipsoid.m
@@ -69,6 +69,8 @@
 
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
 %! ellipsoid (0, 0, 1, 2, 3, 4, 20);
+
--- a/scripts/plot/errorbar.m
+++ b/scripts/plot/errorbar.m
@@ -138,39 +138,39 @@
 
 
 %!demo
-%! clf
+%! clf;
 %! rand_1x11_data1 = [0.82712, 0.50325, 0.35613, 0.77089, 0.20474, 0.69160, 0.30858, 0.88225, 0.35187, 0.14168, 0.54270];
 %! rand_1x11_data2 = [0.506375, 0.330106, 0.017982, 0.859270, 0.140641, 0.327839, 0.275886, 0.162453, 0.807592, 0.318509, 0.921112];
 %! errorbar (0:10, rand_1x11_data1, 0.25*rand_1x11_data2);
 
 %!demo
-%! clf
+%! clf;
 %! rand_1x11_data3 = [0.423650, 0.142331, 0.213195, 0.129301, 0.975891, 0.012872, 0.635327, 0.338829, 0.764997, 0.401798, 0.551850];
 %! rand_1x11_data4 = [0.682566, 0.456342, 0.132390, 0.341292, 0.108633, 0.601553, 0.040455, 0.146665, 0.309187, 0.586291, 0.540149];
-%! errorbar(0:10, rand_1x11_data3, rand_1x11_data4, ">");
+%! errorbar (0:10, rand_1x11_data3, rand_1x11_data4, '>');
 
 %!demo
-%! clf
+%! clf;
 %! x = 0:0.5:2*pi;
 %! err = x/100;
 %! y1 = sin (x);
 %! y2 = cos (x);
-%! hg = errorbar (x, y1, err, "~", x, y2, err, ">");
+%! hg = errorbar (x, y1, err, '~', x, y2, err, '>');
 
 %!demo
-%! clf
+%! clf;
 %! x = 0:0.5:2*pi;
 %! err = x/100;
 %! y1 = sin (x);
 %! y2 = cos (x);
-%! hg = errorbar (x, y1, err, err, "#r", x, y2, err, err, "#~");
+%! hg = errorbar (x, y1, err, err, '#r', x, y2, err, err, '#~');
 
 %!demo
-%! clf
+%! clf;
 %! x = 0:0.5:2*pi;
 %! err = x/100;
 %! y1 = sin (x);
 %! y2 = cos (x);
-%! hg = errorbar (x, y1, err, err, err, err, "~>", ...
-%!                x, y2, err, err, err, err, "#~>-*");
+%! hg = errorbar (x, y1, err, err, err, err, '~>', ...
+%!                x, y2, err, err, err, err, '#~>-*');
 
--- a/scripts/plot/ezcontour.m
+++ b/scripts/plot/ezcontour.m
@@ -58,11 +58,13 @@
   if (nargout > 0)
     retval = h;
   endif
+
 endfunction
 
 
 %!demo
-%! clf
-%! f = @(x,y) sqrt(abs(x .* y)) ./ (1 + x.^2 + y.^2);
+%! clf;
+%! colormap ('default');
+%! f = @(x,y) sqrt (abs (x .* y)) ./ (1 + x.^2 + y.^2);
 %! ezcontour (f, [-3, 3]);
 
--- a/scripts/plot/ezcontourf.m
+++ b/scripts/plot/ezcontourf.m
@@ -58,10 +58,13 @@
   if (nargout > 0)
     retval = h;
   endif
+
 endfunction
 
 
 %!demo
-%! clf
-%! f = @(x,y) sqrt(abs(x .* y)) ./ (1 + x.^2 + y.^2);
+%! clf;
+%! colormap ('default');
+%! f = @(x,y) sqrt (abs (x .* y)) ./ (1 + x.^2 + y.^2);
 %! ezcontourf (f, [-3, 3]);
+
--- a/scripts/plot/ezmesh.m
+++ b/scripts/plot/ezmesh.m
@@ -21,7 +21,7 @@
 ## @deftypefnx {Function File} {} ezmesh (@var{fx}, @var{fy}, @var{fz})
 ## @deftypefnx {Function File} {} ezmesh (@dots{}, @var{dom})
 ## @deftypefnx {Function File} {} ezmesh (@dots{}, @var{n})
-## @deftypefnx {Function File} {} ezmesh (@dots{}, 'circ')
+## @deftypefnx {Function File} {} ezmesh (@dots{}, "circ")
 ## @deftypefnx {Function File} {} ezmesh (@var{h}, @dots{})
 ## @deftypefnx {Function File} {@var{h} =} ezmesh (@dots{})
 ##
@@ -41,7 +41,7 @@
 ## function @code{[@var{fx} (@var{s}, @var{t}), @var{fy} (@var{s}, @var{t}),
 ## @var{fz} (@var{s}, @var{t})]}.
 ##
-## If the argument 'circ' is given, then the function is plotted over a disk
+## If the argument "circ" is given, then the function is plotted over a disk
 ## centered on the middle of the domain @var{dom}.
 ##
 ## The optional return value @var{h} is a graphics handle to the created 
@@ -58,9 +58,9 @@
 ##
 ## @example
 ## @group
-## fx = @@(s,t) cos (s) .* cos(t);
-## fy = @@(s,t) sin (s) .* cos(t);
-## fz = @@(s,t) sin(t);
+## fx = @@(s,t) cos (s) .* cos (t);
+## fy = @@(s,t) sin (s) .* cos (t);
+## fz = @@(s,t) sin (t);
 ## ezmesh (fx, fy, fz, [-pi, pi, -pi/2, pi/2], 20);
 ## @end group
 ## @end example
@@ -79,18 +79,21 @@
   if (nargout > 0)
     retval = h;
   endif
+
 endfunction
 
 
 %!demo
-%! clf
-%! f = @(x,y) sqrt(abs(x .* y)) ./ (1 + x.^2 + y.^2);
+%! clf;
+%! colormap ('default');
+%! f = @(x,y) sqrt (abs (x .* y)) ./ (1 + x.^2 + y.^2);
 %! ezmesh (f, [-3, 3]);
 
 %!demo
-%! clf
-%! fx = @(s,t) cos (s) .* cos(t);
-%! fy = @(s,t) sin (s) .* cos(t);
+%! clf;
+%! colormap ('default');
+%! fx = @(s,t) cos (s) .* cos (t);
+%! fy = @(s,t) sin (s) .* cos (t);
 %! fz = @(s,t) sin (t);
 %! ezmesh (fx, fy, fz, [-pi,pi,-pi/2,pi/2], 20);
 
--- a/scripts/plot/ezmeshc.m
+++ b/scripts/plot/ezmeshc.m
@@ -21,7 +21,7 @@
 ## @deftypefnx {Function File} {} ezmeshc (@var{fx}, @var{fy}, @var{fz})
 ## @deftypefnx {Function File} {} ezmeshc (@dots{}, @var{dom})
 ## @deftypefnx {Function File} {} ezmeshc (@dots{}, @var{n})
-## @deftypefnx {Function File} {} ezmeshc (@dots{}, 'circ')
+## @deftypefnx {Function File} {} ezmeshc (@dots{}, "circ")
 ## @deftypefnx {Function File} {} ezmeshc (@var{h}, @dots{})
 ## @deftypefnx {Function File} {@var{h} =} ezmeshc (@dots{})
 ##
@@ -41,7 +41,7 @@
 ## function @code{[@var{fx} (@var{s}, @var{t}), @var{fy} (@var{s}, @var{t}),
 ## @var{fz} (@var{s}, @var{t})]}.
 ##
-## If the argument 'circ' is given, then the function is plotted over a disk
+## If the argument "circ" is given, then the function is plotted over a disk
 ## centered on the middle of the domain @var{dom}.
 ##
 ## The optional return value @var{h} is a 2-element vector with a graphics
@@ -69,11 +69,13 @@
   if (nargout > 0)
     retval = h;
   endif
+
 endfunction
 
 
 %!demo
-%! clf
-%! f = @(x,y) sqrt(abs(x .* y)) ./ (1 + x.^2 + y.^2);
+%! clf;
+%! colormap ('default');
+%! f = @(x,y) sqrt (abs (x .* y)) ./ (1 + x.^2 + y.^2);
 %! ezmeshc (f, [-3, 3]);
 
--- a/scripts/plot/ezplot.m
+++ b/scripts/plot/ezplot.m
@@ -77,18 +77,19 @@
   if (nargout > 0)
     retval = h;
   endif
+
 endfunction
 
 
 %!demo
-%! clf
-%! ezplot (@cos, @sin)
+%! clf;
+%! ezplot (@cos, @sin);
 
 %!demo
-%! clf
-%! ezplot ("1/x")
+%! clf;
+%! ezplot ('1/x');
 
 %!demo
-%! clf
-%! ezplot (inline ("x^2 - y^2 = 1"))
+%! clf;
+%! ezplot (inline ('x^2 - y^2 = 1'));
 
--- a/scripts/plot/ezplot3.m
+++ b/scripts/plot/ezplot3.m
@@ -57,11 +57,12 @@
   if (nargout > 0)
     retval = h;
   endif
+
 endfunction
 
 
 %!demo
-%! clf
+%! clf;
 %! fx = @(t) cos (t);
 %! fy = @(t) sin (t);
 %! fz = @(t) t;
--- a/scripts/plot/ezpolar.m
+++ b/scripts/plot/ezpolar.m
@@ -20,20 +20,25 @@
 ## @deftypefn  {Function File} {} ezpolar (@var{f})
 ## @deftypefnx {Function File} {} ezpolar (@dots{}, @var{dom})
 ## @deftypefnx {Function File} {} ezpolar (@dots{}, @var{n})
-## @deftypefnx {Function File} {} ezpolar (@var{h}, @dots{})
+## @deftypefnx {Function File} {} ezpolar (@var{hax}, @dots{})
 ## @deftypefnx {Function File} {@var{h} =} ezpolar (@dots{})
 ##
-## Plot a function in polar coordinates.  The function @var{f} is either
-## a string, inline function or function handle with one arguments defining
-## the function.  By default the plot is over the domain @code{0 < @var{x} <
-## 2*pi} with 60 points.
+## Plot a function in polar coordinates.  The function @var{f} is
+## a string, inline function, or function handle with a single argument.
+## The expected form of the function is
+## @code{@var{rho} = @var{f}(@var{theta})}.
+## By default the plot is over the domain @code{0 < @var{theta} < 2*pi} with 60
+## points.
 ##
 ## If @var{dom} is a two element vector, it represents the minimum and maximum
-## value of both @var{t}.  @var{n} is a scalar defining the number of points to
-## use.
+## values of @var{theta}.  @var{n} is a scalar defining the number of points to
+## use.  If the optional input @var{hax} is given then the plot is placed into
+## the specified axes rather than the current axes.
 ##
 ## The optional return value @var{h} is a graphics handle to the created plot.
 ##
+## Example:
+##
 ## @example
 ## ezpolar (@@(t) 1 + sin (t));
 ## @end example
@@ -52,10 +57,11 @@
   if (nargout > 0)
     retval = h;
   endif
+
 endfunction
 
 
 %!demo
-%! clf
+%! clf;
 %! ezpolar (@(t) 1 + sin (t));
 
--- a/scripts/plot/ezsurf.m
+++ b/scripts/plot/ezsurf.m
@@ -21,7 +21,7 @@
 ## @deftypefnx {Function File} {} ezsurf (@var{fx}, @var{fy}, @var{fz})
 ## @deftypefnx {Function File} {} ezsurf (@dots{}, @var{dom})
 ## @deftypefnx {Function File} {} ezsurf (@dots{}, @var{n})
-## @deftypefnx {Function File} {} ezsurf (@dots{}, 'circ')
+## @deftypefnx {Function File} {} ezsurf (@dots{}, "circ")
 ## @deftypefnx {Function File} {} ezsurf (@var{h}, @dots{})
 ## @deftypefnx {Function File} {@var{h} =} ezsurf (@dots{})
 ##
@@ -41,7 +41,7 @@
 ## function @code{[@var{fx} (@var{s}, @var{t}), @var{fy} (@var{s}, @var{t}),
 ## @var{fz} (@var{s}, @var{t})]}.
 ##
-## If the argument 'circ' is given, then the function is plotted over a disk
+## If the argument "circ" is given, then the function is plotted over a disk
 ## centered on the middle of the domain @var{dom}.
 ##
 ## The optional return value @var{h} is a graphics handle to the created
@@ -79,18 +79,21 @@
   if (nargout > 0)
     retval = h;
   endif
+
 endfunction
 
 
 %!demo
-%! clf
-%! f = @(x,y) sqrt(abs(x .* y)) ./ (1 + x.^2 + y.^2);
+%! clf;
+%! colormap ('default');
+%! f = @(x,y) sqrt (abs (x .* y)) ./ (1 + x.^2 + y.^2);
 %! ezsurf (f, [-3, 3]);
 
 %!demo
-%! clf
-%! fx = @(s,t) cos (s) .* cos(t);
-%! fy = @(s,t) sin (s) .* cos(t);
+%! clf;
+%! colormap ('default');
+%! fx = @(s,t) cos (s) .* cos (t);
+%! fy = @(s,t) sin (s) .* cos (t);
 %! fz = @(s,t) sin (t);
 %! ezsurf (fx, fy, fz, [-pi,pi,-pi/2,pi/2], 20);
 
--- a/scripts/plot/ezsurfc.m
+++ b/scripts/plot/ezsurfc.m
@@ -21,7 +21,7 @@
 ## @deftypefnx {Function File} {} ezsurfc (@var{fx}, @var{fy}, @var{fz})
 ## @deftypefnx {Function File} {} ezsurfc (@dots{}, @var{dom})
 ## @deftypefnx {Function File} {} ezsurfc (@dots{}, @var{n})
-## @deftypefnx {Function File} {} ezsurfc (@dots{}, 'circ')
+## @deftypefnx {Function File} {} ezsurfc (@dots{}, "circ")
 ## @deftypefnx {Function File} {} ezsurfc (@var{h}, @dots{})
 ## @deftypefnx {Function File} {@var{h} =} ezsurfc (@dots{})
 ##
@@ -41,7 +41,7 @@
 ## function @code{[@var{fx} (@var{s}, @var{t}), @var{fy} (@var{s}, @var{t}),
 ## @var{fz} (@var{s}, @var{t})]}.
 ##
-## If the argument 'circ' is given, then the function is plotted over a disk
+## If the argument "circ" is given, then the function is plotted over a disk
 ## centered on the middle of the domain @var{dom}.
 ##
 ## The optional return value @var{h} is a 2-element vector with a graphics
@@ -69,11 +69,13 @@
   if (nargout > 0)
     retval = h;
   endif
+
 endfunction
 
 
 %!demo
-%! clf
-%! f = @(x,y) sqrt(abs(x .* y)) ./ (1 + x.^2 + y.^2);
+%! clf;
+%! colormap ('default');
+%! f = @(x,y) sqrt (abs (x .* y)) ./ (1 + x.^2 + y.^2);
 %! ezsurfc (f, [-3, 3]);
 
--- a/scripts/plot/feather.m
+++ b/scripts/plot/feather.m
@@ -111,7 +111,7 @@
 
 
 %!demo
-%! clf
-%! phi = [0 : 15 : 360] * pi / 180;
-%! feather (sin (phi), cos (phi))
+%! clf;
+%! phi = [0 : 15 : 360] * pi/180;
+%! feather (sin (phi), cos (phi));
 
--- a/scripts/plot/figure.m
+++ b/scripts/plot/figure.m
@@ -17,8 +17,10 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {} figure (@var{n})
-## @deftypefnx {Function File} {} figure (@var{n}, @var{property}, @var{value}, @dots{})
+## @deftypefn  {Command} {} figure
+## @deftypefnx {Command} {} figure @var{n}
+## @deftypefnx {Function File} {} figure (@var{n})
+## @deftypefnx {Function File} {} figure (@var{n}, "@var{property}", @var{value}, @dots{})
 ## Set the current plot window to plot window @var{n}.  If no arguments are
 ## specified, the next available window number is chosen.
 ##
@@ -37,7 +39,10 @@
   init_new_figure = false;
   if (mod (nargs, 2) == 1)
     tmp = varargin{1};
-    if (ishandle (tmp) && strcmp (get (tmp, "type"), "figure"))
+    if (ischar (tmp))
+      tmp = str2double (tmp);
+    endif
+    if (isfigure (tmp))
       f = tmp;
       varargin(1) = [];
       nargs--;
@@ -54,7 +59,7 @@
   ## Check to see if we already have a figure on the screen.  If we do,
   ## then update it if it is different from the figure we are creating
   ## or switching to.
-  cf = get (0, "currentfigure");
+  cf = get (0, "currentfigure");   # Can't use gcf () because it calls figure ()
   if (! isempty (cf) && cf != 0)
     if (isnan (f) || cf != f)
       drawnow ();
@@ -64,7 +69,7 @@
   if (rem (nargs, 2) == 0)
     if (isnan (f) || init_new_figure)
       if (ismac () && strcmp (graphics_toolkit (), "fltk"))
-        ## FIXME - Hack for fltk-aqua to work around bug # 31931
+        ## FIXME - Hack for fltk-aqua to work around bug #31931
         f = __go_figure__ (f);
         drawnow ();
         if (! isempty (varargin))
@@ -81,9 +86,8 @@
     print_usage ();
   endif
 
-  cf = get (0, "currentfigure");
-  if (strcmp (get (cf, "__graphics_toolkit__"), "fltk"))
-    __add_default_menu__ (cf);
+  if (strcmp (get (f, "__graphics_toolkit__"), "fltk"))
+    __add_default_menu__ (f);
   endif
 
   if (nargout > 0)
@@ -92,6 +96,7 @@
 
 endfunction
 
+
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
@@ -100,3 +105,4 @@
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
--- a/scripts/plot/fill.m
+++ b/scripts/plot/fill.m
@@ -46,16 +46,16 @@
         set (h, "nextplot", "add");
       endif
       if (i == length (iargs))
-        args = varargin (iargs(i):end);
+        args = varargin(iargs(i):end);
       else
-        args = varargin (iargs(i):iargs(i+1)-1);
+        args = varargin(iargs(i):iargs(i+1)-1);
       endif
       newplot ();
       [tmp, fail] = __patch__ (h, args{:});
       if (fail)
-        print_usage();
+        print_usage ();
       endif
-      htmp (end + 1) = tmp;
+      htmp(end + 1, 1) = tmp;
     endfor
     if (strncmp (nextplot, "replace", 7))
       set (h, "nextplot", nextplot);
@@ -74,7 +74,7 @@
   iargs = [];
   i = 1;
   while (i < nargin)
-    iargs (end + 1) = i;
+    iargs(end + 1) = i;
     if (ischar (varargin{i})
         && (strcmpi (varargin{i}, "faces")
             || strcmpi (varargin{i}, "vertices")))
@@ -96,17 +96,10 @@
         elseif (ischar (varargin{i}))
           colspec = tolower (varargin{i});
           collen = length (colspec);
-
-          if (strncmp (colspec, "blue", collen)
-              || strncmp (colspec, "black", collen)
-              || strncmp (colspec, "k", collen)
-              || strncmp (colspec, "black", collen)
-              || strncmp (colspec, "red", collen)
-              || strncmp (colspec, "green", collen)
-              || strncmp (colspec, "yellow", collen)
-              || strncmp (colspec, "magenta", collen)
-              || strncmp (colspec, "cyan", collen)
-              || strncmp (colspec, "white", collen))
+          if (any (strncmp (colspec, 
+                            {"blue", "black", "k", "red", "green", ...
+                             "yellow", "magenta", "cyan", "white"},
+                            collen)))
             i++;
             break;
           endif
@@ -116,13 +109,14 @@
       endwhile
     endif
   endwhile
+
 endfunction
 
 
 %!demo
-%! clf
-%! t1 = (1/16:1/8:1)*2*pi;
-%! t2 = ((1/16:1/8:1) + 1/32)*2*pi;
+%! clf;
+%! t1 = (1/16:1/8:1) * 2*pi;
+%! t2 = ((1/16:1/8:1) + 1/32) * 2*pi;
 %! x1 = sin (t1) - 0.8;
 %! y1 = cos (t1);
 %! x2 = sin (t2) + 0.8;
new file mode 100644
--- /dev/null
+++ b/scripts/plot/findfigs.m
@@ -0,0 +1,81 @@
+## Copyright (C) 2008 Bill Denney
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {} findfigs ()
+## Find all visible figures that are currently off the screen and move them
+## onto the screen.
+## @seealso{allchild, figure, get, set}
+## @end deftypefn
+
+## Author: Bill Denney <bill@denney.ws>
+## Modified by: Carnë Draug <carandraug+dev@gmail.com>
+
+function findfigs ()
+
+  figh  = allchild (0);
+  units = get (0, "units");
+  unwind_protect
+    if (!strcmp (units, "pixels"))
+      set (0, "units", "pixels");
+    endif
+    screensize = get (0, "screensize");
+  unwind_protect_cleanup
+    set (0, "units", units);
+  end_unwind_protect
+
+  ## give the monitor a margin so that the figure must not just
+  ## marginally be on the monitor.
+  margin = 30;
+  screensize(1:2) += margin;
+  screensize(3:4) -= margin;
+
+  for i = 1:numel (figh)
+    if (strcmp (get (figh(i), "visible"), "on"))
+
+      units = get (figh(i), "units");
+      unwind_protect
+        if (!strcmp (units, "pixels"))
+          set (figh(i), "units", "pixels");
+        endif
+        pos = get (figh(i), "position");
+        ## Test if (in order):
+        ## The left side is outside the right side of the screen
+        ## The bottom is above the top of the screen
+        ## The right side is outside the left of the screen
+        ## the top is below the bottom of the screen
+        if (pos(1) > screensize(3)
+            || pos(2) > screensize(4)
+            || pos(1)+pos(3) < screensize(1)
+            || pos(2)+pos(4) < screensize(2))
+
+          ## the new position will be at the top left of the screen
+          ## (all moved figures will overlap).  The bottom left is chosen
+          ## instead of the top left because that allows for the unknown
+          ## amount of space for the menu bar and the title bar.
+          pos(1) = screensize(1);
+          pos(2) = screensize(2);
+          set (figh(i), "position", pos);
+        endif
+      unwind_protect_cleanup
+        set (figh(i), "units", units);
+      end_unwind_protect
+    endif
+  endfor
+endfunction
--- a/scripts/plot/findobj.m
+++ b/scripts/plot/findobj.m
@@ -146,18 +146,18 @@
           na = na + 1;
           pvalue{np} = args{na};
           na = na + 1;
-          if (na <= numel(args))
+          if (na <= numel (args))
             if (ischar (args{na}))
-              if strcmpi(args{na}, "-and")
+              if (strcmpi (args{na}, "-and"))
                 logicaloperator{np} = "and";
                 na = na+1;
-              elseif strcmpi(args{na}, "-or")
+              elseif (strcmpi (args{na}, "-or"))
                 logicaloperator{np} = "or";
                 na = na+1;
-              elseif strcmpi(args{na}, "-xor")
+              elseif (strcmpi (args{na}, "-xor"))
                 logicaloperator{np} = "xor";
                 na = na+1;
-              elseif strcmpi(args{na}, "-not")
+              elseif (strcmpi (args{na}, "-not"))
                 logicaloperator{np} = "not";
                 na = na+1;
               endif
@@ -173,7 +173,7 @@
         endif
       else
         ## This is sloppy ... but works like Matlab.
-        if strcmpi(args{na}, "-not")
+        if (strcmpi (args{na}, "-not"))
           h = [];
           return
         endif
@@ -192,7 +192,7 @@
   while (numel (handles) && ! (idepth >= depth))
     children = [];
     for n = 1 : numel (handles)
-      children = union (children, get(handles(n), "children"));
+      children = union (children, get (handles(n), "children"));
     endfor
     handles = children;
     h = union (h, children);
@@ -201,7 +201,7 @@
 
   keepers = ones (size (h));
   if (numpairs > 0)
-    for nh = 1 : numel(h)
+    for nh = 1 : numel (h)
       p = get (h (nh));
       for np = 1 : numpairs
         fields = fieldnames (p);
@@ -213,7 +213,7 @@
           else
             if (regularexpression(np))
               match = regexp (p.(pname{np}), pvalue{np});
-              if isempty (match)
+              if (isempty (match))
                 match = 0;
               endif
             elseif (numel (p.(pname{np})) == numel (pvalue{np}))
--- a/scripts/plot/fplot.m
+++ b/scripts/plot/fplot.m
@@ -42,26 +42,17 @@
 
 ## Author: Paul Kienzle <pkienzle@users.sf.net>
 
-function fplot (fn, limits, n, fmt)
+function fplot (fn, limits, n = 0.002, fmt = "")
+
   if (nargin < 2 || nargin > 4)
     print_usage ();
   endif
 
-  if (!isreal (limits) || (numel (limits) != 2 && numel (limits) != 4))
-    error ("fplot: second input argument must be a real vector with 2 or 4 elements");
-  endif
-
-  if (nargin < 3)
-    n = 0.002;
-  endif
-
-  have_linespec = true;
-  if (nargin < 4)
-    have_linespec = false;
+  if (iscomplex (limits) || (numel (limits) != 2 && numel (limits) != 4))
+    error ("fplot: LIMITS must be a real vector with 2 or 4 elements");
   endif
 
   if (ischar (n))
-    have_linespec = true;
     fmt = n;
     n = 0.002;
   endif
@@ -74,13 +65,13 @@
   elseif (all (isalnum (fn)))
     nam = fn;
   elseif (ischar (fn))
-     fn = vectorize (inline (fn));
-     nam = formula (fn);
+    fn = vectorize (inline (fn));
+    nam = formula (fn);
   else
-    error ("fplot: first input argument must be a function handle, inline function or string");
+    error ("fplot: FN must be a function handle, inline function, or string");
   endif
 
-  if (floor(n) != n)
+  if (n != fix (n))
     tol = n;
     x0 = linspace (limits(1), limits(2), 5)';
     y0 = feval (fn, x0);
@@ -92,7 +83,7 @@
     while (n < 2 .^ 20)
       y00 = interp1 (x0, y0, x, "linear");
       err = 0.5 * max (abs ((y00 - y) ./ (y00 + y))(:));
-      if (err == err0 || 0.5 * max (abs ((y00 - y) ./ (y00 + y))(:)) < tol)
+      if (err == err0 || err < tol)
         break;
       endif
       x0 = x;
@@ -107,11 +98,7 @@
     y = feval (fn, x);
   endif
 
-  if (have_linespec)
-    plot (x, y, fmt);
-  else
-    plot (x, y);
-  endif
+  plot (x, y, fmt);
 
   if (length (limits) > 2)
     axis (limits);
@@ -125,12 +112,15 @@
     endfor
     legend (nams{:});
   endif
+
 endfunction
 
+
 %!demo
-%! clf
-%! fplot ("cos", [0, 2*pi])
+%! clf;
+%! fplot ('cos', [0, 2*pi]);
 
 %!demo
-%! clf
-%! fplot ("[cos(x), sin(x)]", [0, 2*pi])
+%! clf;
+%! fplot ('[cos(x), sin(x)]', [0, 2*pi]);
+
--- a/scripts/plot/gca.m
+++ b/scripts/plot/gca.m
@@ -50,6 +50,7 @@
 
 endfunction
 
+
 %!test
 %! hf = figure ("visible", "off");
 %! ax = axes;
@@ -58,3 +59,4 @@
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
--- a/scripts/plot/gcbf.m
+++ b/scripts/plot/gcbf.m
@@ -32,5 +32,6 @@
 
 endfunction
 
-%!test
-%! assert (isempty (gcbf ));
+
+%!assert (isempty (gcbf))
+
--- a/scripts/plot/gcbo.m
+++ b/scripts/plot/gcbo.m
@@ -42,5 +42,7 @@
 
 endfunction
 
+
 %!test
-%! assert (isempty (gcbo ));
+%! assert (isempty (gcbo));
+
--- a/scripts/plot/gcf.m
+++ b/scripts/plot/gcf.m
@@ -54,6 +54,7 @@
 
 endfunction
 
+
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
@@ -61,3 +62,4 @@
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
new file mode 100644
--- /dev/null
+++ b/scripts/plot/gco.m
@@ -0,0 +1,45 @@
+## Copyright (C) 2012 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{h} =} gco ()
+## @deftypefnx {Function File} {@var{h} =} gco (@var{fig})
+## Return a handle to the current object of the current figure, or a handle
+## to the current object of the figure with handle @var{fig}.  The current
+## object of a figure is the object that was last clicked on.  It is stored
+## in the CurrentObject property of the target figure.
+##
+## If the last mouse click didn't occur on any child object of the figure,
+## the current object is the figure itself.
+##
+## If no mouse click occured in the target figure, this function returns an
+## empty matrix.
+##
+## Note that the value returned by this function is not necessarily the same
+## as the one returned by gcbo during callback execution.  An executing
+## callback can be interrupted by another callback and the current object
+## can be modified.
+##
+##@seealso{gcbo, gcf}
+##@end deftypefn
+
+function h = gco ()
+
+  h = get (get (0, "currentfigure"), "currentobject");
+
+endfunction
--- a/scripts/plot/ginput.m
+++ b/scripts/plot/ginput.m
@@ -43,6 +43,8 @@
 
 endfunction
 
+
 ## Remove from test statistics.  No real tests possible.
 %!test
 %! assert (1);
+
--- a/scripts/plot/gnuplot_binary.in
+++ b/scripts/plot/gnuplot_binary.in
@@ -22,8 +22,9 @@
 ## Query or set the name of the program invoked by the plot command
 ## when the graphics toolkit is set to "gnuplot".  Additional arguments to
 ## pass to the external plotting program may also be given.
-## The default value is @code{"gnuplot"} without additional arguments.
+## The default value is @code{"gnuplot"} with no additional arguments.
 ## @xref{Installation}.
+## @seealso{graphics_toolkit}
 ## @end deftypefn
 
 ## Author: jwe
@@ -39,23 +40,26 @@
   endif
 
   if (nargin == 1)
-    if (ischar (new_prog))
-      if (! isempty (new_prog))
-	gp_binary = new_prog;
-      else
-	error ("gnuplot_binary: value must not be empty");
-      endif
-    else
-      error ("gnuplot_binary: expecting program to be a character string");
+    if (! ischar (new_prog) || isempty (new_prog))
+      error ("gnuplot_binary: NEW_PROG must be a non-empty string");
     endif
+    gp_binary = new_prog;
   endif
 
   if (nargin > 1)
-    if (iscellstr (varargin))
-      gp_args = varargin;
-    else
-      error ("gnuplot_binary: expecting arguments to be character strings");
+    if (! iscellstr (varargin))
+      error ("gnuplot_binary: arguments must be character strings");
     endif
+    gp_args = varargin;
   endif
 
 endfunction
+
+
+%!test
+%! orig_val = gnuplot_binary ();
+%! old_val = gnuplot_binary ("X");
+%! assert (orig_val, old_val);
+%! assert (gnuplot_binary (), "X");
+%! gnuplot_binary (orig_val);
+%! assert (gnuplot_binary (), orig_val);
--- a/scripts/plot/graphics_toolkit.m
+++ b/scripts/plot/graphics_toolkit.m
@@ -18,14 +18,27 @@
 
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {@var{name} =} graphics_toolkit ()
-## @deftypefnx {Function File} {@var{old_name} =} graphics_toolkit (@var{name})
+## @deftypefnx {Function File} {@var{name} =} graphics_toolkit (@var{hlist})
+## @deftypefnx {Function File} {} graphics_toolkit (@var{name})
 ## @deftypefnx {Function File} {} graphics_toolkit (@var{hlist}, @var{name})
-## Query or set the default graphics toolkit to @var{name}.  If the
-## toolkit is not already loaded, it is first initialized by calling the
-## function @code{__init_@var{name}__}.
+## Return the default graphics toolkit.  The default graphics toolkit value
+## is assigned to new figures.
+## 
+## @code{graphics_toolkit (@var{hlist})}
+## 
+## Return the graphics toolkits for the figures with handles @var{hlist}.
+## 
+## @code{graphics_toolkit (@var{name})}
+## 
+## Set the default graphics toolkit to @var{name}.  If the toolkit is not
+## already loaded, it is initialized by calling the function
+## @code{__init_@var{name}__}.
+## 
+## @code{graphics_toolkit (@var{hlist}, @var{name})}
 ##
-## When called with a list of figure handles, @var{hlist}, the graphics
-## toolkit is changed only for the listed figures.
+## Set the graphics toolkit for the figures with handles @var{hlist} to
+## @var{name}.
+## 
 ## @seealso{available_graphics_toolkits}
 ## @end deftypefn
 
@@ -42,7 +55,11 @@
   if (nargin == 0)
     return;
   elseif (nargin == 1)
-    if (! ischar (name))
+    if (all (isfigure (name)))
+      hlist = name;
+      retval = get (hlist, "__graphics_toolkit__");
+      return
+    elseif (! ischar (name))
       error ("graphics_toolkit: invalid graphics toolkit NAME");
     endif
   elseif (nargin == 2)
@@ -77,19 +94,19 @@
 %!   toolkit = graphics_toolkit ();
 %!   assert (get (0, "defaultfigure__graphics_toolkit__"), toolkit);
 %!   graphics_toolkit (hf, "fltk"); 
-%!   assert (get (hf, "__graphics_toolkit__"), "fltk");
+%!   assert (graphics_toolkit (hf), "fltk");
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
 
 %!testif HAVE_FLTK
-%!  old_toolkit = graphics_toolkit ();
-%!  switch old_toolkit
-%!    case {"gnuplot"}
-%!      new_toolkit = "fltk";
-%!    otherwise
-%!      new_toolkit = "gnuplot";
-%!  endswitch
-%!  assert (graphics_toolkit (new_toolkit), old_toolkit)
-%!  assert (graphics_toolkit (old_toolkit), new_toolkit)
+%! old_toolkit = graphics_toolkit ();
+%! switch old_toolkit
+%!   case {"gnuplot"}
+%!     new_toolkit = "fltk";
+%!   otherwise
+%!     new_toolkit = "gnuplot";
+%! endswitch
+%! assert (graphics_toolkit (new_toolkit), old_toolkit);
+%! assert (graphics_toolkit (old_toolkit), new_toolkit);
 
--- a/scripts/plot/grid.m
+++ b/scripts/plot/grid.m
@@ -98,24 +98,23 @@
 
 endfunction
 
+
 %!demo
-%! clf
-%! subplot (2,2,1)
-%! plot (1:100)
-%! grid minor
-%! grid minor
-%! grid
-%! title ("no grid")
-%! subplot (2,2,2)
-%! plot (1:100)
-%! grid
-%! title ("grid on")
-%! subplot (2,2,3)
-%! plot (1:100)
-%! grid minor
-%! title ("grid minor")
-%! subplot (2,2,4)
-%! semilogy (1:100)
-%! grid minor
-%! title ("grid minor")
+%! clf;
+%! subplot (2,2,1);
+%!  plot (1:100);
+%!  grid off;
+%!  title ('no grid');
+%! subplot (2,2,2);
+%!  plot (1:100);
+%!  grid on;
+%!  title ('grid on');
+%! subplot (2,2,3);
+%!  plot (1:100);
+%!  grid minor;
+%!  title ('grid minor');
+%! subplot (2,2,4);
+%!  semilogy (1:100);
+%!  grid minor;
+%!  title ('grid minor');
 
--- a/scripts/plot/gtext.m
+++ b/scripts/plot/gtext.m
@@ -18,16 +18,24 @@
 
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {} gtext (@var{s})
+## @deftypefnx {Function File} {} gtext (@{@var{s1}, @var{s2}, @dots{}@})
 ## @deftypefnx {Function File} {} gtext (@{@var{s1}; @var{s2}; @dots{}@})
 ## @deftypefnx {Function File} {} gtext (@dots{}, @var{prop}, @var{val})
+## @deftypefnx {Function File} {@var{h} =} gtext (@dots{})
 ## Place text on the current figure using the mouse.  The text is defined
-## by the string @var{s}.  If @var{s} is a cell array, each element of the cell
-## array is written to a separate line.  Additional arguments are passed to
-## the underlying text object as properties.
+## by the string @var{s}.  If @var{s} is a cell string organized as a row
+## vector then each string of the cell array is written to a separate line.
+## If @var{s} is organized as a column vector then one string element of the
+## cell array is placed for every mouse click.  Additional inputs besides a
+## string or cellstr are passed to the underlying text object as Property-value
+## pairs.
+##
+## The optional return value @var{h} is a graphics handle to the created
+## text object.
 ## @seealso{ginput, text}
 ## @end deftypefn
 
-function gtext (s, varargin)
+function h = gtext (s, varargin)
 
   if (nargin < 1)
     print_usage ();
@@ -37,13 +45,26 @@
     error ("gtext: S must be a string or cell array of strings");
   endif
 
+  htmp = -1;
   if (! isempty (s))
-    [x, y] = ginput (1);
-    text (x, y, s, varargin{:});
+    if (ischar (s) || isrow (s))
+      [x, y] = ginput (1);
+      htmp = text (x, y, s, varargin{:});
+    else
+      for i = 1:numel (s)
+        [x, y] = ginput (1);
+        htmp = text (x, y, s{i}, varargin{:});
+      endfor
+    endif
+  endif
+
+  if (nargout > 0)
+    h = htmp;
   endif
 
 endfunction
 
+
 ## Remove from test statistics.  No real tests possible.
-%!test
-%! assert (1);
+%!assert (1)
+
new file mode 100644
--- /dev/null
+++ b/scripts/plot/hdl2struct.m
@@ -0,0 +1,170 @@
+## Copyright (C) 2012 pdiribarne
+##
+## 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 Octave; see the file COPYING.  If not, see
+## <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{s} =} hdl2struct (@var{h})
+## Return a structure, @var{s}, whose fields describe the properties
+## of the object, and its children, associated with the handle, @var{h}.
+## The fields of the structure, @var{s}, are "type", "handle", "properties",
+## "children" and "special".
+## @seealso{findobj, get, set, struct2hdl}
+## @end deftypefn
+
+## Author: pdiribarne <pdiribarne@new-host.home>
+## Created: 2012-03-04
+
+function s = hdl2struct (h)
+
+  if (nargin != 1 || !ishandle (h))
+    print_usage ();
+  endif
+
+  hiddenh = get (0, "showhiddenhandles");
+  if (strcmp (hiddenh, "on"))
+    set (0, "showhiddenhandles", "off");
+  endif
+
+  ## main object
+  main = get (h);
+  s.handle = h;
+  s.type =  main.type;
+  s.properties  = getprops (h);
+  s.children = [];
+  s.special = [];
+
+  ## sweep all children but legends, colorbars, uimenu and hggroup children
+  ## in reverse order
+  kids = main.children;
+  lg = findobj (h, "-depth", 1, "tag", "legend");
+  cb = findobj (h, "-depth", 1, "tag", "colorbar");
+  ui = findobj (h, "-depth", 1, "type", "uimenu");
+  nkids = length (kids);
+  ii = 0;
+  while (nkids)
+    if (! any (kids (nkids) == lg) && ! any (kids (nkids) == cb)
+          && ! any (kids (nkids) == ui) && ! strcmp (main.type, "hggroup"))
+      ii++;
+      s.children(ii) = hdl2struct (kids(nkids));
+    endif
+    nkids--;
+  endwhile
+
+  ## add non "children" children objects (title, xlabel, ...) and
+  ## hggroup children and tag theim in "special"
+  special = [];
+  if (strcmp (main.type, "hggroup"))
+    special = main.children;
+  endif
+  special = [special getspecial(h)];
+  nsp = length (special);
+  while (nsp)
+    ii++;
+    s.children(ii) = hdl2struct (special(nsp));
+    s.special(nsp) = ii;
+    nsp--;
+  endwhile
+
+  ## look for legends and colorbars among "main"'s brothers and add them
+  ## to the children list
+  if (strcmp (main.type, "axes"))
+    par = main.parent;
+    lg = findobj (par, "-depth", 1, "tag", "legend");
+    if (! isempty (lg))
+      idx = arrayfun (@(x) get(x).userdata.handle(end) == h, lg);
+      lg = lg(find (idx));
+    endif
+    nlg = length (lg);
+    if (nlg == 1)
+      ii++;
+      s.children(ii) = hdl2struct (lg);
+    elseif (nlg > 1)
+      error ("hdl2struct: more than one legend found");
+    endif
+
+    cb = findobj (par, "-depth", 1, "tag", "colorbar");
+    if (! isempty (cb))
+      idx = arrayfun (@(x) get(x).axes == h, cb);
+      cb = cb(find (idx));
+    endif
+
+    ncb = length (cb);
+    if (ncb == 1)
+      ii++;
+      s.children(ii) = hdl2struct (cb);
+    elseif (nlg > 1)
+      error ("hdl2struct: more than one colorbar found");
+    endif
+  endif
+
+  set (0, "showhiddenhandles", hiddenh);
+
+endfunction
+
+function hdlist = getspecial (h)
+  obj = get (h);
+  ## return handles to special children
+  fields = fieldnames (obj);
+  hdlist = [];
+
+  regkids = get ( h, "children");
+  set (0, "showhiddenhandles", "on");
+  allkids = get ( h, "children");
+  set (0, "showhiddenhandles", "off");
+  speckids = arrayfun (@(x) ! any (x == regkids), allkids);
+  hdlist = allkids (find (speckids));
+  hdlist = reshape (hdlist, 1, numel (hdlist));
+
+endfunction
+
+function prpstr = getprops (h)
+  obj = get (h);
+  ## get usefull properties rejecting readonly, children, handles ...
+  fields = fieldnames (obj);
+  hdlist = [];
+
+  forbid = {"beingdeleted", "busyaction", "buttondownfcn", ...
+            "children", "clipping", "createfcn", ...
+            "deletefcn", "handlevisibility", "hittest", ...
+            "interruptible", "parent", "selected" ,...
+            "selectionhighlight", "type", "__modified__", ...
+            "uicontextmenu", "__graphics_toolkit__", "currentaxes", ...
+            "currentcharacter", "currentobject","tightinset", ...
+            "currentpoint", "extent"};
+
+  nflds = length (fields);
+  ii = 0;
+  while nflds
+    prop = fields{nflds};
+    val = obj.(fields{nflds});
+    ii++;
+    if (! any (strcmp (prop, forbid)))
+      prpstr.(prop) = val;
+    endif
+    nflds--;
+  endwhile
+
+  ## hidden properties
+  hidden = {"autopos_tag", "looseinset"};
+  for ii = 1:numel (hidden)
+    if (isprop (h, hidden{ii}))
+      prpstr.(hidden{ii}) = get (h, hidden{ii});
+    endif
+  endfor
+
+endfunction
+
+
+## FIXME: need validation tests
--- a/scripts/plot/hggroup.m
+++ b/scripts/plot/hggroup.m
@@ -42,6 +42,7 @@
 
 endfunction
 
+
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
@@ -51,3 +52,4 @@
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
--- a/scripts/plot/hidden.m
+++ b/scripts/plot/hidden.m
@@ -21,7 +21,7 @@
 ## @deftypefnx {Function File} {} hidden ()
 ## Manipulation the mesh hidden line removal.  Called with no argument
 ## the hidden line removal is toggled.  The argument @var{mode} can be either
-## 'on' or 'off' and the set of the hidden line removal is set accordingly.
+## "on" or "off" and the set of the hidden line removal is set accordingly.
 ## @seealso{mesh, meshc, surf}
 ## @end deftypefn
 
--- a/scripts/plot/hist.m
+++ b/scripts/plot/hist.m
@@ -93,7 +93,7 @@
   if (nargin == 1 || ischar (varargin{iarg}))
     n = 10;
     x = [0.5:n]'/n;
-    x = x * (max_val - min_val) + ones(size(x)) * min_val;
+    x = x * (max_val - min_val) + ones (size (x)) * min_val;
   else
     ## nargin is either 2 or 3
     x = varargin{iarg++};
@@ -149,7 +149,7 @@
   if (nargin > 2 && ! ischar (varargin{iarg}))
     ## Normalise the histogram.
     norm = varargin{iarg++};
-    freq = freq / rows (y) * norm;
+    freq = freq / sum(! isnan (y)) * norm;
   endif
 
   if (nargout > 0)
@@ -160,7 +160,7 @@
       nn = freq;
       xx = x;
     endif
-  elseif (size (freq, 2) != 1)
+  elseif (columns (freq) != 1)
     bar (x, freq, 0.8, varargin{iarg:end});
   else
     bar (x, freq, 1.0, varargin{iarg:end});
@@ -168,30 +168,35 @@
 
 endfunction
 
+
 %!test
-%!  [nn,xx]=hist([1:4],3);
-%!  assert(xx, [1.5,2.5,3.5]);
-%!  assert(nn, [2,1,1]);
+%! [nn,xx] = hist ([1:4], 3);
+%! assert (xx, [1.5,2.5,3.5]);
+%! assert (nn, [2,1,1]);
 %!test
-%!  [nn,xx]=hist([1:4]',3);
-%!  assert(xx, [1.5,2.5,3.5]);
-%!  assert(nn, [2,1,1]);
+%! [nn,xx] = hist ([1:4]', 3);
+%! assert (xx, [1.5,2.5,3.5]);
+%! assert (nn, [2,1,1]);
 %!test
-%!  [nn,xx]=hist([1 1 1 NaN NaN NaN 2 2 3],[1 2 3]);
-%!  assert(xx, [1,2,3]);
-%!  assert(nn, [3,2,1]);
+%! [nn,xx] = hist ([1 1 1 NaN NaN NaN 2 2 3],[1 2 3]);
+%! assert (xx, [1,2,3]);
+%! assert (nn, [3,2,1]);
 %!test
-%!  [nn,xx]=hist([[1:4]',[1:4]'],3);
-%!  assert(xx, [1.5;2.5;3.5]);
-%!  assert(nn, [[2,1,1]',[2,1,1]']);
-%!assert(hist(1,1),1);
+%! [nn,xx] = hist ([1 1 1 NaN NaN NaN 2 2 3],[1 2 3], 6);
+%! assert (xx, [1,2,3]);
+%! assert (nn, [3,2,1]);
+%!test
+%! [nn,xx] = hist ([[1:4]', [1:4]'], 3);
+%! assert (xx, [1.5;2.5;3.5]);
+%! assert (nn, [[2,1,1]',[2,1,1]']);
 %!test
-%!  for n = [10, 30, 100, 1000]
-%!    assert(sum(hist([1:n], n)), n);
-%!    assert(sum(hist([1:n], [2:n-1])), n);
-%!    assert(sum(hist([1:n], [1:n])), n);
-%!    assert(sum(hist([1:n], 29)), n);
-%!    assert(sum(hist([1:n], 30)), n);
-%!  endfor
-%!test
-%!  assert (size (hist(randn(750,240), 200)), [200,240]);
+%! for n = [10, 30, 100, 1000]
+%!   assert (sum (hist ([1:n], n)), n);
+%!   assert (sum (hist ([1:n], [2:n-1])), n);
+%!   assert (sum (hist ([1:n], [1:n])), n);
+%!   assert (sum (hist ([1:n], 29)), n);
+%!   assert (sum (hist ([1:n], 30)), n);
+%! endfor
+%!assert (hist (1,1), 1)
+%!assert (size (hist (randn (750,240), 200)), [200,240])
+
--- a/scripts/plot/hold.m
+++ b/scripts/plot/hold.m
@@ -20,7 +20,7 @@
 ## @deftypefn  {Command} {} hold
 ## @deftypefnx {Command} {} hold @var{state}
 ## @deftypefnx {Function File} {} hold (@var{hax}, @dots{})
-## Toggle or set the 'hold' state of the plotting engine which determines
+## Toggle or set the "hold" state of the plotting engine which determines
 ## whether new graphic objects are added to the plot or replace the existing
 ## objects.
 ##
@@ -39,13 +39,13 @@
 ## command.  (default).
 ##
 ## @item hold
-## Toggle the current 'hold' state.
+## Toggle the current hold state.
 ## @end table
 ##
 ## When given the additional argument @var{hax}, the hold state is modified
 ## only for the given axis handle.
 ##
-## To query the current 'hold' state use the @code{ishold} function.
+## To query the current hold state use the @code{ishold} function.
 ## @seealso{ishold, cla, newplot, clf}
 ## @end deftypefn
 
@@ -94,60 +94,64 @@
 
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
 %! A = rand (100);
 %! [X, Y] = find (A > 0.9);
-%! imshow (A)
-%! hold on
-%! plot (X, Y, 'o')
-%! hold off
+%! imshow (A);
+%! hold on;
+%! plot (X, Y, 'o');
+%! hold off;
 
 %!demo
-%! clf
-%! hold on
-%! imagesc(1./hilb(4));
-%! plot (1:4, "-s")
-%! hold off
+%! clf;
+%! colormap ('default');
+%! hold on;
+%! imagesc (1 ./ hilb (4));
+%! plot (1:4, '-s');
+%! hold off;
 
 %!demo
-%! clf
-%! hold on
-%! imagesc(1./hilb(2));
-%! imagesc(1./hilb(4));
-%! hold off
+%! clf;
+%! colormap ('default');
+%! hold on;
+%! imagesc (1 ./ hilb (2));
+%! imagesc (1 ./ hilb (4));
+%! hold off;
 
 %!demo
-%! clf
-%! hold on
-%! plot (1:4, "-s")
-%! imagesc(1./hilb(4));
-%! hold off
+%! clf;
+%! colormap ('default');
+%! hold on;
+%! plot (1:4, '-s');
+%! imagesc (1 ./ hilb (4));
+%! hold off;
 
 %!demo
-%! clf
-%! colormap (jet)
+%! clf;
+%! colormap ('default');
 %! t = linspace (-3, 3, 50);
 %! [x, y] = meshgrid (t, t);
 %! z = peaks (x, y);
 %! contourf (x, y, z, 10);
-%! hold ("on");
-%! plot (vec (x), vec (y), "^");
-%! patch ([-1.0 1.0 1.0 -1.0 -1.0], [-1.0 -1.0 1.0 1.0 -1.0], "red");
+%! hold on;
+%! plot (x(:), y(:), '^');
+%! patch ([-1.0 1.0 1.0 -1.0 -1.0], [-1.0 -1.0 1.0 1.0 -1.0], 'red');
 %! xlim ([-2.0 2.0]);
 %! ylim ([-2.0 2.0]);
-%! colorbar ("SouthOutside");
-%! title ("Test script for some plot functions");
+%! colorbar ('SouthOutside');
+%! title ('Test script for some plot functions');
 
 ##hold on
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
 %!   p = plot ([0 1]);
-%!   assert (!ishold);
+%!   assert (! ishold);
 %!   hold on;
 %!   assert (ishold);
-%!   p1 = fill ([0 1 1], [0 0 1],"black");
+%!   p1 = fill ([0 1 1], [0 0 1], "black");
 %!   p2 = fill ([0 1 0], [0 1 1], "red");
 %!   assert (length (get (hf, "children")), 1);
 %!   assert (length (get (gca, "children")), 3);
@@ -160,14 +164,15 @@
 %! hf = figure ("visible", "off");
 %! unwind_protect
 %!   p = plot ([0 1]);
-%!   assert (!ishold);
+%!   assert (! ishold);
 %!   hold on;
 %!   assert (ishold);
-%!   p1 = fill ([0 1 1], [0 0 1],"black");
-%!   hold off
+%!   p1 = fill ([0 1 1], [0 0 1], "black");
+%!   hold off;
 %!   p2 = fill ([0 1 0], [0 1 1], "red");
 %!   assert (length (get (hf, "children")), 1);
 %!   assert (length (get (gca, "children")), 1);
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
--- a/scripts/plot/isfigure.m
+++ b/scripts/plot/isfigure.m
@@ -35,11 +35,13 @@
 
 endfunction
 
+
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
 %!   assert (isfigure (hf));
-%!   assert (!isfigure (-hf));
+%!   assert (! isfigure (-hf));
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
--- a/scripts/plot/ishghandle.m
+++ b/scripts/plot/ishghandle.m
@@ -27,32 +27,33 @@
   retval = ishandle (h);
 endfunction
 
+
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
 %!   assert (ishghandle (hf));
-%!   assert (!ishghandle (-hf));
+%!   assert (! ishghandle (-hf));
 %!   l = line;
-%!   ax = gca();
+%!   ax = gca;
 %!   assert (ishghandle (ax));
-%!   assert (!ishghandle (-ax));
+%!   assert (! ishghandle (-ax));
 %!   assert (ishghandle (l));
-%!   assert (!ishghandle (-l));
+%!   assert (! ishghandle (-l));
 %!   p = patch;
 %!   assert (ishghandle (p));
-%!   assert (!ishghandle (-p));
+%!   assert (! ishghandle (-p));
 %!   s = surface;
 %!   assert (ishghandle (s));
-%!   assert (!ishghandle (-s));
+%!   assert (! ishghandle (-s));
 %!   t = text;
 %!   assert (ishghandle (t));
-%!   assert (!ishghandle (-t));
+%!   assert (! ishghandle (-t));
 %!   i = image;
 %!   assert (ishghandle (i));
-%!   assert (!ishghandle (-i));
+%!   assert (! ishghandle (-i));
 %!   hg = hggroup;
 %!   assert (ishghandle (hg));
-%!   assert (!ishghandle (-hg));
+%!   assert (! ishghandle (-hg));
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
--- a/scripts/plot/ishold.m
+++ b/scripts/plot/ishold.m
@@ -55,15 +55,16 @@
 
 endfunction
 
+
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
-%!   assert (!ishold);
+%!   assert (! ishold);
 %!   assert (isempty (get (hf, "currentaxes")));
 %!   assert (get (hf, "NextPlot"), "add");
 %!   l = plot ([0 1]);
-%!   assert (!ishold);
-%!   assert (!ishold (gca));
+%!   assert (! ishold);
+%!   assert (! ishold (gca));
 %!   assert (get (gca, "NextPlot"), "replace");
 %!   assert (get (hf, "NextPlot"), "add");
 %!   hold;
@@ -77,3 +78,4 @@
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
--- a/scripts/plot/isocolors.m
+++ b/scripts/plot/isocolors.m
@@ -98,7 +98,7 @@
 
 ## Author: Martin Helm <martin@mhelm.de>
 
-function varargout = isocolors(varargin)
+function varargout = isocolors (varargin)
   calc_rgb = false;
   switch (nargin)
     case 2
@@ -134,7 +134,7 @@
     otherwise
       print_usage ();
   endswitch
-  if (ismatrix (vp) && size (vp,2) == 3)
+  if (ismatrix (vp) && columns (vp) == 3)
     pa = [];
     v = vp;
   elseif ( ishandle (vp) )
@@ -144,7 +144,7 @@
     error ("isocolors: last argument is not a vertex list or patch handle");
   endif
   if (calc_rgb)
-    new_col = zeros (size (v, 1), 3);
+    new_col = zeros (rows (v), 3);
     new_col(:,1) = __interp_cube__ (x, y, z, R, v, "values" );
     new_col(:,2) = __interp_cube__ (x, y, z, G, v, "values" );
     new_col(:,3) = __interp_cube__ (x, y, z, B, v, "values" );
@@ -163,10 +163,12 @@
   endswitch
 endfunction
 
+
 %!test
-%!  [x, y, z] = meshgrid (0:.5:2, 0:.5:2, 0:.5:2);
-%!  c = (x-.5).^2 + (y-.5).^2 + (z-.5).^2;
-%!  [f, v] = isosurface (x, y, z, c, .4);
-%!  cdat = isocolors (x, y, z, c, v);
-%!  assert (size (cdat, 1) == size (v, 1));
+%! [x, y, z] = meshgrid (0:.5:2, 0:.5:2, 0:.5:2);
+%! c = (x-.5).^2 + (y-.5).^2 + (z-.5).^2;
+%! [f, v] = isosurface (x, y, z, c, .4);
+%! cdat = isocolors (x, y, z, c, v);
+%! assert (rows (cdat) == rows (v));
 ## Can't create a patch handle for tests without a figure
+
--- a/scripts/plot/isonormals.m
+++ b/scripts/plot/isonormals.m
@@ -95,7 +95,7 @@
 
 ## Author: Martin Helm <martin@mhelm.de>
 
-function varargout = isonormals(varargin)
+function varargout = isonormals (varargin)
   na = nargin;
   negate = false;
   if (ischar (varargin{nargin}))
@@ -122,7 +122,7 @@
     otherwise
       print_usage ();
   endswitch
-  if (ismatrix (vp) && size (vp,2) == 3)
+  if (ismatrix (vp) && columns (vp) == 3)
     pa = [];
     v = vp;
   elseif (ishandle (vp))
@@ -148,16 +148,18 @@
   endswitch
 endfunction
 
+
 %!test
-%!  [x, y, z] = meshgrid (0:.5:2, 0:.5:2, 0:.5:2);
-%!  c = abs ((x-.5).^2 + (y-.5).^2 + (z-.5).^2);
-%!  [f, v, cdat] = isosurface (x, y, z, c, .4, y);
-%!  n = isonormals (x, y, z, c, v);
-%!  assert (size (v), size (n));
+%! [x, y, z] = meshgrid (0:.5:2, 0:.5:2, 0:.5:2);
+%! c = abs ((x-.5).^2 + (y-.5).^2 + (z-.5).^2);
+%! [f, v, cdat] = isosurface (x, y, z, c, .4, y);
+%! n = isonormals (x, y, z, c, v);
+%! assert (size (v), size (n));
 %!test
-%!  [x, y, z] = meshgrid (0:.5:2, 0:.5:2, 0:.5:2);
-%!  c = abs ((x-.5).^2 + (y-.5).^2 + (z-.5).^2);
-%!  [f, v, cdat] = isosurface (x, y, z, c, .4, y);
-%!  np = isonormals (x, y, z, c, v);
-%!  nn = isonormals (x, y, z, c, v, "negate");
-%!  assert (all (np == -nn));
+%! [x, y, z] = meshgrid (0:.5:2, 0:.5:2, 0:.5:2);
+%! c = abs ((x-.5).^2 + (y-.5).^2 + (z-.5).^2);
+%! [f, v, cdat] = isosurface (x, y, z, c, .4, y);
+%! np = isonormals (x, y, z, c, v);
+%! nn = isonormals (x, y, z, c, v, "negate");
+%! assert (np, -nn);
+
--- a/scripts/plot/isosurface.m
+++ b/scripts/plot/isosurface.m
@@ -118,7 +118,7 @@
 
 ## Author: Martin Helm <martin@mhelm.de>
 
-function varargout = isosurface(varargin)
+function varargout = isosurface (varargin)
 
   if (nargin < 2 || nargin > 8 || nargout > 3)
     print_usage ();
@@ -174,7 +174,7 @@
                     "FaceColor", "g", "EdgeColor", "k");
       endif
       if (! ishold ())
-        set (gca(), "view", [-37.5, 30],
+        set (gca (), "view", [-37.5, 30],
              "xgrid", "on", "ygrid", "on", "zgrid", "on");
       endif
     case 1
@@ -190,36 +190,37 @@
 endfunction
 
 
+%!demo
+%! clf;
+%! [x,y,z] = meshgrid (-2:0.5:2, -2:0.5:2, -2:0.5:2);
+%! v = x.^2 + y.^2 + z.^2;
+%! isosurface (x, y, z, v, 1);
+
 %!shared x, y, z, val
-%!  [x, y, z]  = meshgrid (0:1, 0:1, 0:1); ## Points for single
-%!  val        = [0, 0; 0, 0];             ## cube and a 3--dim
-%!  val(:,:,2) = [0, 0; 1, 0];             ## array of values
+%! [x, y, z]  = meshgrid (0:1, 0:1, 0:1); %% Points for single
+%! val        = [0, 0; 0, 0];             %% cube and a 3-D
+%! val(:,:,2) = [0, 0; 1, 0];             %% array of values
 %!test
-%!  fv = isosurface (x, y, z, val, 0.3);
-%!  assert (isfield (fv, "vertices"), true);
-%!  assert (isfield (fv, "faces"), true);
-%!  assert (size (fv.vertices), [3 3]);
-%!  assert (size (fv.faces), [1 3]);
+%! fv = isosurface (x, y, z, val, 0.3);
+%! assert (isfield (fv, "vertices"), true);
+%! assert (isfield (fv, "faces"), true);
+%! assert (size (fv.vertices), [3 3]);
+%! assert (size (fv.faces), [1 3]);
 %!test
-%!  fvc = isosurface (x, y, z, val, .3, y);
-%!  assert (isfield (fvc, "vertices"), true);
-%!  assert (isfield (fvc, "faces"), true);
-%!  assert (isfield (fvc, "facevertexcdata"), true);
-%!  assert (size (fvc.vertices), [3 3]);
-%!  assert (size (fvc.faces), [1 3]);
-%!  assert (size (fvc.facevertexcdata), [3 1]);
+%! fvc = isosurface (x, y, z, val, .3, y);
+%! assert (isfield (fvc, "vertices"), true);
+%! assert (isfield (fvc, "faces"), true);
+%! assert (isfield (fvc, "facevertexcdata"), true);
+%! assert (size (fvc.vertices), [3 3]);
+%! assert (size (fvc.faces), [1 3]);
+%! assert (size (fvc.facevertexcdata), [3 1]);
 %!test
-%!  [f, v] = isosurface (x, y, z, val, .3);
-%!  assert (size (f), [1 3]);
-%!  assert (size (v), [3 3]);
+%! [f, v] = isosurface (x, y, z, val, .3);
+%! assert (size (f), [1 3]);
+%! assert (size (v), [3 3]);
 %!test
-%!  [f, v, c] = isosurface (x, y, z, val, .3, y);
-%!  assert (size (f), [1 3]);
-%!  assert (size (v), [3 3]);
-%!  assert (size (c), [3 1]);
+%! [f, v, c] = isosurface (x, y, z, val, .3, y);
+%! assert (size (f), [1 3]);
+%! assert (size (v), [3 3]);
+%! assert (size (c), [3 1]);
 
-%!demo
-%! clf
-%! [x,y,z] = meshgrid(-2:0.5:2, -2:0.5:2, -2:0.5:2);
-%! v = x.^2 + y.^2 + z.^2;
-%! isosurface (x, y, z, v, 1)
--- a/scripts/plot/isprop.m
+++ b/scripts/plot/isprop.m
@@ -37,7 +37,7 @@
   endif
 
   res = false (size (h));
-  for n = 1:numel(res)
+  for n = 1:numel (res)
     res(n) = true;
     try
       v = get (h(n), prop);
@@ -47,9 +47,8 @@
   endfor
 endfunction
 
+
 %!assert (isprop (0, "foobar"), false)
-
 %!assert (isprop (0, "screenpixelsperinch"), true)
-
 %!assert (isprop (zeros (2, 3), "visible"), true (2, 3))
 
--- a/scripts/plot/legend.m
+++ b/scripts/plot/legend.m
@@ -19,20 +19,21 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {} legend (@var{str1}, @var{str2}, @dots{})
 ## @deftypefnx {Function File} {} legend (@var{matstr})
-## @deftypefnx {Function File} {} legend (@var{cell})
+## @deftypefnx {Function File} {} legend (@var{cellstr})
 ## @deftypefnx {Function File} {} legend (@dots{}, "location", @var{pos})
 ## @deftypefnx {Function File} {} legend (@dots{}, "orientation", @var{orient})
 ## @deftypefnx {Function File} {} legend (@var{hax}, @dots{})
 ## @deftypefnx {Function File} {} legend (@var{hobjs}, @dots{})
 ## @deftypefnx {Function File} {} legend (@var{hax}, @var{hobjs}, @dots{})
 ## @deftypefnx {Function File} {} legend ("@var{option}")
+## @deftypefnx {Function File} {[@var{hleg}, @var{hleg_obj}, @var{hplot}, @var{labels}] =} legend (@dots{})
 ##
 ## Display a legend for the axes with handle @var{hax}, or the current axes,
 ## using the specified strings as labels.  Legend entries may be specified
 ## as individual character string arguments, a character array, or a cell
 ## array of character strings.  If the handles, @var{hobjs}, are not specified
 ## then the legend's strings will be associated with the axes' descendants.
-## Legend works on line graphs, bar graphs, etc.
+## @code{legend} works on line graphs, bar graphs, etc.
 ## A plot must exist before legend is called.
 ##
 ## The optional parameter @var{pos} specifies the location of the legend
@@ -74,8 +75,8 @@
 ## @end multitable
 ##
 ## The optional parameter @var{orient} determines if the key elements
-## are placed vertically or horizontally.  The allowed values are "vertical"
-## or "horizontal" with the default being "vertical".
+## are placed vertically or horizontally.  The allowed values are
+## "vertical" (default) or "horizontal".
 ##
 ## The following customizations are available using @var{option}:
 ##
@@ -86,7 +87,7 @@
 ## @item "hide"
 ##   Hide legend on the plot
 ##
-## @itemx "toggle"
+## @item "toggle"
 ##   Toggles between "hide" and "show"
 ##
 ## @item "boxon"
@@ -96,14 +97,35 @@
 ##   Hide the box around legend
 ##
 ## @item "left"
-##   Place text to the left of the keys
+##   Place label text to the left of the keys
 ##
 ## @item "right"
-##   Place text to the right of the keys
+##   Place label text to the right of the keys
 ##
-## @itemx "off"
+## @item  "off"
 ##   Delete the legend object
 ## @end table
+##
+## The optional output values are
+##
+## @table @var
+## @item hleg
+##   The graphics handle of the legend object.
+##
+## @item hleg_obj
+##   Graphics handles to the text and line objects which make up the legend.
+##
+## @item hplot
+##   Graphics handles to the plot objects which were used in making the legend.
+##
+## @item labels
+##   A cell array of strings of the labels in the legend.
+## @end table 
+##
+## The legend label text is either provided in the call to @code{legend} or
+## is taken from the DisplayName property of graphics objects.  If no
+## labels or DisplayNames are available, then the label text is simply
+## "data1", "data2", @dots{}, "dataN".
 ## @end deftypefn
 
 function [hlegend2, hobjects2, hplot2, text_strings2] = legend (varargin)
@@ -122,6 +144,7 @@
     ca = gca ();
   endif
 
+  ## Special handling for plotyy which has two axes objects
   if (ishandle (ca) && isprop (ca, "__plotyy_axes__"))
     plty = get (ca, "__plotyy_axes__");
     if (isscalar (plty) && ishandle (plty))
@@ -131,11 +154,11 @@
     elseif (all (ishandle (plty)))
       ca = [ca, plty(:).'];
     else
-      error ("legend.m: This should not happen. File a bug report.")
+      error ("legend.m: This should not happen. File a bug report.");
     endif
     ## Remove duplicates while preserving order
     [~, n] = unique (ca);
-    ca = ca (sort (n));
+    ca = ca(sort (n));
   endif
 
   if (nargin > 0 && all (ishandle (varargin{1})))
@@ -143,11 +166,11 @@
     varargin(1) = [];
   else
     kids = ca;
-    kids (strcmp (get (ca, "tag"), "legend")) = [];
+    kids(strcmp (get (ca, "tag"), "legend")) = [];
     if (isscalar (kids))
-      kids = get(kids, "children")(:);
+      kids = get (kids, "children")(:);
     else
-      kids = [get(kids, "children"){:}](:);
+      kids = flipud ([get(kids, "children"){:}](:));
     endif
   endif
   nargs = numel (varargin);
@@ -159,6 +182,7 @@
   textpos = "default";
   box = "default";
 
+  ## Process old way of specifying position with a number rather than a string.
   if (nargs > 0)
     pos = varargin{nargs};
     if (isnumeric (pos) && isscalar (pos) && pos == fix (pos))
@@ -172,13 +196,14 @@
     endif
   endif
 
+  ## Find position and orientation property/value pairs
   while (nargs > 1)
     pos = varargin{nargs-1};
     str = varargin{nargs};
-    if (strcmpi (pos, "location")  && ischar (str))
+    if (strcmpi (pos, "location") && ischar (str))
       position = lower (str);
       nargs -= 2;
-    elseif (strcmpi (pos, "orientation")  && ischar (str))
+    elseif (strcmpi (pos, "orientation") && ischar (str))
       orientation = lower (str);
       nargs -= 2;
     else
@@ -188,14 +213,14 @@
 
   ## Validate the orientation
   switch (orientation)
-    case {"vertical", "horizontal","default"}
+    case {"vertical", "horizontal", "default"}
     otherwise
       error ("legend: unrecognized legend orientation");
   endswitch
 
-  ## Validate the position type is valid
+  ## Validate the position type
   outside = false;
-  inout = findstr (position, "outside");
+  inout = strfind (position, "outside");
   if (! isempty (inout))
     outside = true;
     position = position(1:inout-1);
@@ -213,14 +238,15 @@
       error ("legend: unrecognized legend position");
   endswitch
 
+  ## Find any existing legend object on figure
   hlegend = [];
   fkids = get (fig, "children");
-  for i = 1 : numel(fkids)
-    if (ishandle (fkids (i)) && strcmp (get (fkids (i), "type"), "axes")
-        && (strcmp (get (fkids (i), "tag"), "legend")))
-      udata = get (fkids (i), "userdata");
+  for i = 1 : numel (fkids)
+    if (ishandle (fkids(i)) && strcmp (get (fkids(i), "type"), "axes")
+        && (strcmp (get (fkids(i), "tag"), "legend")))
+      udata = get (fkids(i), "userdata");
       if (! isempty (intersect (udata.handle, ca)))
-        hlegend = fkids (i);
+        hlegend = fkids(i);
         break;
       endif
     endif
@@ -230,19 +256,27 @@
     arg = varargin{1};
     if (ischar (arg))
       if (rows (arg) == 1)
-        str = tolower (deblank (arg));
+        str = tolower (strtrim (arg));
         switch (str)
-          case {"off"}
+          case "off"
             delete (hlegend);
-            return
-          case {"hide"}
+            return;
+          case "hide"
             show = "off";
             nargs--;
           case "show"
-            show = "on";
+            if (! isempty (hlegend))
+              show = "on";
+            else
+              show = "create";
+              textpos = "left";
+            endif
             nargs--;
           case "toggle"
-            if (isempty (hlegend) || strcmp (get (hlegend, "visible"), "off"))
+            if (isempty (hlegend))
+              show = "create";
+              textpos = "left";
+            elseif (strcmp (get (hlegend, "visible"), "off"))
               show = "on";
             else
               show = "off";
@@ -260,23 +294,30 @@
           case "right"
             textpos = "right";
             nargs--;
-          otherwise
         endswitch
       else
+        ## Character matrix of labels
         varargin = cellstr (arg);
         nargs = numel (varargin);
       endif
     elseif (iscellstr (arg))
+      ## Cell array of labels
       varargin = arg;
       nargs = numel (varargin);
     else
       error ("legend: expecting argument to be a character string");
     endif
+  elseif (nargs > 1 && iscellstr (varargin{1}))
+    ## Cell array of labels followed by property/value pairs
+    varargin = {varargin{1}{:}, varargin{2:end}};
+    nargs = numel (varargin);
   endif
 
+  have_labels = (nargs > 0);
+
   if (strcmp (show, "off"))
     if (! isempty (hlegend))
-      set (get (hlegend, "children"), "visible", "off");
+      set (findobj (hlegend), "visible", "off");
       hlegend = [];
     endif
     hobjects = [];
@@ -284,7 +325,9 @@
     text_strings = {};
   elseif (strcmp (show, "on"))
     if (! isempty (hlegend))
-      set (get (hlegend, "children"), "visible", "on");
+      set (findobj (hlegend), "visible", "on");
+      ## NOTE - Matlab sets both "visible", and "box" to "on"
+      set (hlegend, "visible", get (hlegend, "box"));
     else
       hobjects = [];
       hplots  = [];
@@ -292,19 +335,20 @@
     endif
   elseif (strcmp (box, "on"))
     if (! isempty (hlegend))
-      set (hlegend, "visible", "on", "box", "on");
+      set (hlegend, "box", "on", "visible", "on");
     endif
   elseif (strcmp (box, "off"))
     if (! isempty (hlegend))
       set (hlegend, "box", "off", "visible", "off");
     endif
-  elseif (nargs == 0 && !(strcmp (position, "default") &&
-                          strcmp (orientation, "default")))
+  elseif (! have_labels && !(strcmp (position, "default") &&
+                             strcmp (orientation, "default")))
+    ## Changing location or orientation of existing legend
     if (! isempty (hlegend))
       hax = getfield (get (hlegend, "userdata"), "handle");
       [hplots, text_strings] = __getlegenddata__ (hlegend);
 
-      if  (strcmp (position, "default"))
+      if (strcmp (position, "default"))
         h = legend (hax, hplots, text_strings, "orientation", orientation);
       elseif (strcmp (orientation, "default"))
         if (outside)
@@ -324,13 +368,16 @@
       endif
     endif
   else
+    ## Create new legend
     hobjects = [];
     hplots  = [];
     text_strings = {};
 
-    if (nargs > 0)
+    if (have_labels)
+      ## Check for valid data that can be labeled.
       have_data = false;
-      for k = 1:nkids
+      have_dname = false;
+      for k = 1 : nkids
         typ = get (kids(k), "type");
         if (strcmp (typ, "line") || strcmp (typ, "surface")
             || strcmp (typ, "patch") || strcmp (typ, "hggroup"))
@@ -342,11 +389,40 @@
       if (! have_data)
         warning ("legend: plot data is empty; setting key labels has no effect");
       endif
-    endif
+    else
+      ## No labels.  Search for DisplayName property.
+      have_dname = false;
+      for k = 1 : nkids
+        hkid = kids(k);
+        typ = get (hkid, "type");
+        if (strcmp (typ, "line") || strcmp (typ, "surface")
+            || strcmp (typ, "patch"))
+          if (! isempty (get (hkid, "displayname")))
+            have_dname = true;
+            break;
+          endif
+        elseif (strcmp (typ, "hggroup"))
+          hgkids = get (hkid, "children");
+          for j = 1 : length (hgkids)
+            hgobj = get (hgkids(j));
+            if (isfield (hgobj, "displayname") && ! isempty (hgobj.displayname))
+              have_dname = true;
+              break;  # break from j-loop over hgkids
+            endif
+          endfor
+          if (have_dname)
+            break;  # break from k loop over nkids
+          endif
+        endif  # elseif hggroup
+      endfor   # for loop k = 1 : nkids
+    endif      # else branch of if (have_labels)
 
-    if (strcmp (textpos, "default"))
-      warned = false;
+    if (have_labels || ! have_dname)
       k = nkids;
+      if (! have_labels)
+        varargin = arrayfun (@(x) sprintf ("data%d", x), [1:nkids]', "uniformoutput", false);
+        nargs = nkids;
+      endif
       for i = 1 : nargs
         arg = varargin{i};
         if (ischar (arg))
@@ -360,16 +436,20 @@
             if (strcmp (get (kids(k), "type"), "hggroup"))
               hgkids = get (kids(k), "children");
               for j = 1 : length (hgkids)
-                hgobj = get (hgkids (j));
+                hgobj = get (hgkids(j));
                 if (isfield (hgobj, "displayname"))
-                  set (hgkids(j), "displayname", arg);
+                  if (have_labels)
+                    set (hgkids(j), "displayname", arg);
+                  endif
                   hplots = [hplots, hgkids(j)];
                   text_strings = {text_strings{:}, arg};
                   break;
                 endif
               endfor
             else
-              set (kids(k), "displayname", arg);
+              if (have_labels)
+                set (kids(k), "displayname", arg);
+              endif
               hplots = [hplots, kids(k)];
               text_strings = {text_strings{:}, arg};
             endif
@@ -377,17 +457,18 @@
             if (--k == 0)
               break;
             endif
-          elseif (! warned)
-            break;
+          else
+            break;  # k = 0, no further handles to process
           endif
         else
           error ("legend: expecting argument to be a character string");
         endif
       endfor
-      if (i < nargs && ! warned)
+      if (have_labels && i < nargs)
         warning ("legend: ignoring extra labels");
       endif
     else
+      ## No labels specified but objects have DisplayName property set.
       k = nkids;
       while (k > 0)
         typ = get (kids(k), "type");
@@ -404,7 +485,7 @@
           if (strcmp (get (kids(k), "type"), "hggroup"))
             hgkids = get (kids(k), "children");
             for j = 1 : length (hgkids)
-              hgobj = get (hgkids (j));
+              hgobj = get (hgkids(j));
               if (isfield (hgobj, "displayname")
                   && ! isempty (hgobj.displayname))
                 hplots = [hplots, hgkids(j)];
@@ -413,9 +494,9 @@
               endif
             endfor
           else
-            if (! isempty (get (kids (k), "displayname")))
+            if (! isempty (get (kids(k), "displayname")))
               hplots = [hplots, kids(k)];
-              text_strings = {text_strings{:}, get(kids (k), "displayname")};
+              text_strings = {text_strings{:}, get(kids(k), "displayname")};
             endif
           endif
           if (--k == 0)
@@ -428,21 +509,21 @@
     if (isempty (hplots))
       if (! isempty (hlegend))
         fkids = get (fig, "children");
-        delete (fkids (fkids == hlegend));
+        delete (fkids(fkids == hlegend));
         hlegend = [];
         hobjects = [];
         hplots  = [];
         text_strings = {};
       endif
     else
-      ## Delete the old legend if it exists
+      ## Preserve the old legend if it exists
       if (! isempty (hlegend))
         if (strcmp (textpos, "default"))
           textpos = get (hlegend, "textposition");
         endif
         if (strcmp (position, "default"))
           position = get (hlegend, "location");
-          inout = findstr (position, "outside");
+          inout = strfind (position, "outside");
           if (! isempty (inout))
             outside = true;
             position = position(1:inout-1);
@@ -454,10 +535,6 @@
           orientation = get (hlegend, "orientation");
         endif
         box = get (hlegend, "box");
-        fkids = get (fig, "children");
-
-        delete (hlegend);
-        hlegend = [];
       else
         if (strcmp (textpos, "default"))
           textpos = "left";
@@ -468,7 +545,7 @@
         if (strcmp (orientation, "default"))
           orientation = "vertical";
         endif
-        box = "off";
+        box = "on";
       endif
 
       ## Get axis size and fontsize in points.
@@ -497,24 +574,25 @@
       ## FIXME hlegend should inherit properties from "ca"
       curaxes = get (fig, "currentaxes");
       unwind_protect
-        ud = ancestor(hplots, "axes");
-        if (!isscalar(ud))
+        ud = ancestor (hplots, "axes");
+        if (!isscalar (ud))
           ud = unique ([ud{:}]);
         endif
         if (isempty (hlegend))
           addprops = true;
           hlegend = axes ("tag", "legend", "userdata", struct ("handle", ud),
                           "box", box,
-                          "xtick", [], "ytick", [], "xticklabel", "",
-                          "yticklabel", "", "zticklabel", "",
-                          "xlim", [0, 1], "ylim", [0, 1], "visible", "off",
-                          "activepositionproperty", "position");
+                          "xtick", [], "ytick", [],
+                          "xticklabel", "", "yticklabel", "", "zticklabel", "",
+                          "xlim", [0, 1], "ylim", [0, 1],
+                          "visible", ifelse (strcmp (box, "on"), "on", "off"),
+                          "activepositionproperty", "position",
+                          "fontsize", ca_fontsize);
         else
           addprops = false;
           axes (hlegend);
           delete (get (hlegend, "children"));
         endif
-
         ## Add text label to the axis first, checking their extents
         nentries = numel (hplots);
         texthandle = [];
@@ -522,22 +600,24 @@
         maxheight = 0;
         for k = 1 : nentries
           if (strcmp (textpos, "right"))
-            texthandle = [texthandle, text(0, 0, text_strings {k},
+            texthandle = [texthandle, text(0, 0, text_strings{k},
                                            "horizontalalignment", "left",
-                                           "userdata", hplots(k))];
+                                           "userdata", hplots(k),
+                                           "fontsize", ca_fontsize)];
           else
-            texthandle = [texthandle, text(0, 0, text_strings {k},
+            texthandle = [texthandle, text(0, 0, text_strings{k},
                                            "horizontalalignment", "right",
-                                           "userdata", hplots(k))];
+                                           "userdata", hplots(k),
+                                           "fontsize", ca_fontsize)];
           endif
-          units = get (texthandle (end), "units");
+          units = get (texthandle(end), "units");
           unwind_protect
-            set (texthandle (end), "units", "points");
-            extents = get (texthandle (end), "extent");
-            maxwidth = max (maxwidth, extents (3));
-            maxheight = max (maxheight, extents (4));
+            set (texthandle(end), "units", "points");
+            extents = get (texthandle(end), "extent");
+            maxwidth = max (maxwidth, extents(3));
+            maxheight = max (maxheight, extents(4));
           unwind_protect_cleanup
-            set (texthandle (end), "units", units);
+            set (texthandle(end), "units", units);
           end_unwind_protect
         endfor
 
@@ -545,24 +625,24 @@
         if (strcmp (orientation, "vertical"))
           height = nentries * (ypad + maxheight);
           if (outside)
-            if (height > ca_pos (4))
+            if (height > ca_pos(4))
               ## Avoid shrinking the height of the axis to zero if outside
               num1 = ca_pos(4) / (maxheight + ypad) / 2;
             endif
           else
-            if (height > 0.9 * ca_pos (4))
+            if (height > 0.9 * ca_pos(4))
               num1 = 0.9 * ca_pos(4) / (maxheight + ypad);
             endif
           endif
         else
           width = nentries * (ypad + maxwidth);
           if (outside)
-            if (width > ca_pos (3))
+            if (width > ca_pos(3))
               ## Avoid shrinking the width of the axis to zero if outside
               num1 = ca_pos(3) / (maxwidth + ypad) / 2;
             endif
           else
-            if (width > 0.9 * ca_pos (3))
+            if (width > 0.9 * ca_pos(3))
               num1 = 0.9 * ca_pos(3) / (maxwidth + ypad);
             endif
           endif
@@ -679,7 +759,7 @@
         xk = 0;
         yk = 0;
         for k = 1 : numel (hplots)
-          hobjects = [hobjects, texthandle (k)];
+          hobjects = [hobjects, texthandle(k)];
           switch (get (hplots(k), "type"))
           case "line"
             color = get (hplots(k), "color");
@@ -703,14 +783,26 @@
               hobjects = [hobjects, l1];
             endif
 
-            addlistener(hplots(k), "color", {@updateline, hlegend, linelength});
-            addlistener(hplots(k), "linestyle", {@updateline, hlegend, linelength});
-            addlistener(hplots(k), "marker", {@updateline, hlegend, linelength});
-            addlistener(hplots(k), "markeredgecolor", {@updateline, hlegend, linelength});
-            addlistener(hplots(k), "markerfacecolor", {@updateline, hlegend, linelength});
-            addlistener(hplots(k), "markersize", {@updateline, hlegend, linelength});
-            addlistener(hplots(k), "displayname", {@updateline, hlegend, linelength});
+            addlistener (hplots(k), "color", {@updateline, hlegend, linelength});
+            addlistener (hplots(k), "linestyle", {@updateline, hlegend, linelength});
+            addlistener (hplots(k), "marker", {@updateline, hlegend, linelength});
+            addlistener (hplots(k), "markeredgecolor", {@updateline, hlegend, linelength});
+            addlistener (hplots(k), "markerfacecolor", {@updateline, hlegend, linelength});
+            addlistener (hplots(k), "markersize", {@updateline, hlegend, linelength});
+            addlistener (hplots(k), "displayname", {@updateline, hlegend, linelength});
           case "patch"
+            facecolor = get (hplots(k), "facecolor");
+            edgecolor = get (hplots(k), "edgecolor");
+            cdata = get (hplots(k), "cdata");
+            if (! strcmp (facecolor, "none") || ! strcmp (edgecolor, "none"))
+              p1 = patch ("xdata", ([0, linelength, linelength, 0] +
+                                   xoffset + xk * xstep) / lpos(3),
+                         "ydata", (lpos(4) - yoffset -
+                                   [yk-0.3, yk-0.3, yk+0.3, yk+0.3] .* ystep) / lpos(4),
+                         "facecolor", facecolor, "edgecolor", edgecolor, "cdata", cdata,
+                         "userdata", hplots(k));
+              hobjects = [hobjects, p1];
+            endif
           case "surface"
           endswitch
           set (texthandle (k), "position", [(txoffset + xk * xstep) / lpos(3), ...
@@ -737,16 +829,16 @@
                    "xliminclude", "off", "yliminclude", "off");
         set (t1, "deletefcn", {@deletelegend1, hlegend});
 
-        ## Resize the axis the legend is attached to if the
-        ## legend is "outside" the plot and create listener to
+        ## Resize the axis that the legend is attached to if the
+        ## legend is "outside" the plot and create a listener to
         ## resize axis to original size if the legend is deleted,
-        ## hidden or shown
+        ## hidden, or shown.
         if (outside)
           for i = 1 : numel (ca)
             units = get (ca(i), "units");
             unwind_protect
               set (ca(i), "units", "points");
-              set (ca (i), "position", new_pos);
+              set (ca(i), "position", new_pos);
             unwind_protect_cleanup
               set (ca(i), "units", units);
             end_unwind_protect
@@ -782,6 +874,7 @@
         if (addprops)
           addlistener (hlegend, "edgecolor", @updatelegendtext);
           addlistener (hlegend, "textcolor", @updatelegendtext);
+          addlistener (hlegend, "fontsize", @updatelegendtext);
           addlistener (hlegend, "interpreter", @updatelegendtext);
           addlistener (hlegend, "location", @updatelegend);
           addlistener (hlegend, "orientation", @updatelegend);
@@ -823,9 +916,10 @@
   text_kids = findobj (kids, "-property", "interpreter", "type", "text");
   interpreter = get (h, "interpreter");
   textcolor = get (h, "textcolor");
-  set (kids, "interpreter", interpreter, "color", textcolor);
-  hobj = cell2mat (get (kids, "userdata"));
-  set (hobj, "interpreter", interpreter);
+  fontsize = get (h, "fontsize");
+  set (text_kids, "interpreter", interpreter,
+                  "fontsize", fontsize,
+                  "color", textcolor);
 endfunction
 
 function hideshowlegend (h, d, ca, pos1, pos2)
@@ -842,7 +936,7 @@
 
   for i = 1 : numel (ca)
     if (ishandle (ca(i)) && strcmp (get (ca(i), "type"), "axes")
-        && (isempty (gcbf()) || strcmp (get (gcbf(), "beingdeleted"),"off"))
+        && (isempty (gcbf ()) || strcmp (get (gcbf (), "beingdeleted"),"off"))
         && strcmp (get (ca(i), "beingdeleted"), "off"))
       units = get (ca(i), "units");
       unwind_protect
@@ -861,7 +955,7 @@
 
 function deletelegend1 (h, d, ca)
   if (ishandle (ca) && strcmp (get (ca, "type"), "axes")
-      && (isempty (gcbf()) || strcmp (get (gcbf(), "beingdeleted"),"off"))
+      && (isempty (gcbf ()) || strcmp (get (gcbf (), "beingdeleted"), "off"))
       && strcmp (get (ca, "beingdeleted"), "off"))
     delete (ca);
   endif
@@ -870,7 +964,7 @@
 function deletelegend2 (h, d, ca, pos, outpos, t1, hplots)
   for i = 1 : numel (ca)
     if (ishandle (ca(i)) && strcmp (get (ca(i), "type"), "axes")
-        && (isempty (gcbf()) || strcmp (get (gcbf(), "beingdeleted"),"off"))
+        && (isempty (gcbf ()) || strcmp (get (gcbf (), "beingdeleted"), "off"))
         && strcmp (get (ca(i), "beingdeleted"), "off"))
       if (!isempty (pos) && !isempty(outpos))
         units = get (ca(i), "units");
@@ -887,13 +981,13 @@
   delete (t1);
   for i = 1 : numel (hplots)
     if (ishandle (hplots(i)) && strcmp (get (hplots (i), "type"), "line"))
-      dellistener (hplots (i), "color");
-      dellistener (hplots (i), "linestyle");
-      dellistener (hplots (i), "marker");
-      dellistener (hplots (i), "markeredgecolor");
-      dellistener (hplots (i), "markerfacecolor");
-      dellistener (hplots (i), "markersize");
-      dellistener (hplots (i), "displayname");
+      dellistener (hplots(i), "color");
+      dellistener (hplots(i), "linestyle");
+      dellistener (hplots(i), "marker");
+      dellistener (hplots(i), "markeredgecolor");
+      dellistener (hplots(i), "markerfacecolor");
+      dellistener (hplots(i), "markersize");
+      dellistener (hplots(i), "displayname");
     endif
   endfor
 endfunction
@@ -903,12 +997,12 @@
   ll = [];
   kids = get (hlegend, "children");
   for i = 1 : numel (kids)
-    if (get (kids (i), "userdata") == h
+    if (get (kids(i), "userdata") == h
         && strcmp (get (kids(i), "type"), "line"))
       if (strcmp (get (kids (i), "marker"), "none"))
-        ll = kids (i);
+        ll = kids(i);
       else
-        lm = kids (i);
+        lm = kids(i);
       endif
     endif
   endfor
@@ -924,7 +1018,7 @@
     ## legend function to recreate a new legend
     [hplots, text_strings] = __getlegenddata__ (hlegend);
     for i = 1 : numel (hplots)
-      if (hplots (i) == h)
+      if (hplots(i) == h)
         hplots(i) = [];
         text_strings(i) = [];
         break;
@@ -945,7 +1039,7 @@
       ypos1 = get (ll,"ydata");
       xpos1 = get (ll,"xdata");
       ypos2 = ypos1(1);
-      xpos2 = sum(xpos1) / 2;
+      xpos2 = sum (xpos1) / 2;
       delete (ll);
       if (! isempty (lm))
         delete (lm);
@@ -972,190 +1066,232 @@
   endif
 endfunction
 
+
 %!demo
-%! clf
+%! plot (rand (2));
+%! title ('legend called with cellstr and string inputs for labels');
+%! legend ({'foo'}, 'bar');
+
+%!demo
+%! plot (rand (3));
+%! title ('legend() without inputs creates default labels');
+%! legend ();
+
+%!demo
+%! clf;
 %! x = 0:1;
-%! plot (x, x, ";I am Blue;", x, 2*x, ";I am Green;", x, 3*x, ";I am Red;")
+%! plot (x,x,';I am Blue;', x,2*x, x,3*x,';I am Red;');
+%! title ('Blue and Red keys, with Green missing');
+
+%!demo
+%! clf;
+%! plot (1:10, 1:10, 1:10, fliplr (1:10));
+%! title ('incline is blue and decline is green');
+%! legend ({'I am blue', 'I am green'}, 'location', 'east');
+
+%!demo
+%! clf;
+%! plot (1:10, 1:10, 1:10, fliplr (1:10));
+%! title ('Legend with keys in horizontal orientation');
+%! legend ({'I am blue', 'I am green'}, 'location', 'east', 'orientation', 'horizontal');
+%! legend boxoff;
 
 %!demo
-%! clf
-%! x = 0:1;
-%! plot (x, x, ";I am Blue;", x, 2*x, x, 3*x, ";I am Red;")
-%! title ("Blue and Green keys, with Green mising")
+%! clf;
+%! plot (1:10, 1:10, 1:10, fliplr (1:10));
+%! title ('Legend with box off');
+%! legend ({'I am blue', 'I am green'}, 'location', 'east');
+%! legend boxoff;
+
+%!demo
+%! clf;
+%! plot (1:10, 1:10, 1:10, fliplr (1:10));
+%! title ('Legend with text to the right of key');
+%! legend ({'I am blue', 'I am green'}, 'location', 'east');
+%! legend right;
 
 %!demo
-%! clf
-%! plot(1:10, 1:10, 1:10, fliplr(1:10));
-%! title("incline is blue and decline is green");
-%! legend({"I am blue", "I am green"}, "location", "east");
-%! legend({"I am blue", "I am green"}, "location", "east");
+%! clf;
+%! plot (1:10, 1:10, 1:10, fliplr (1:10));
+%! title ('Using properties to have legend text shown to the right of key');
+%! h = legend ({'I am blue', 'I am green'}, 'location', 'east');
+%! legend ('left');
+%! set (h, 'textposition', 'right');
+%! set (h, 'textcolor', [1 0 1]);
+
+%!demo
+%! clf;
+%! plot (1:10, 1:10, 1:10, fliplr (1:10));
+%! title ('Legend is hidden')
+%! legend ({'I am blue', 'I am green'}, 'location', 'east');
+%! legend hide;
+
+%!demo
+%! clf;
+%! x = 0:1;
+%! plot (x,x,';I am Blue;', x,2*x,';I am Green;', x,3*x,';I am Red;');
+%! title ('labels embedded in call to plot');
+%! legend boxon
 %! legend hide
 %! legend show
 
 %!demo
-%! clf
-%! plot(1:10, 1:10, 1:10, fliplr(1:10));
-%! title("Legend is hidden")
-%! legend({"I am blue", "I am green"}, "location", "east");
-%! legend hide
-
-%!demo
-%! clf
-%! plot(1:10, 1:10, 1:10, fliplr(1:10));
-%! title("Legend with box on")
-%! legend({"I am blue", "I am green"}, "location", "east");
-%! legend boxon
+%! clf;
+%! x = 0:1;
+%! plot (x, x, ';\alpha;',  ...
+%!       x, 2*x, ';\beta=2\alpha;',  ...
+%!       x, 3*x, ';\gamma=3\alpha;');
+%! title ('labels with interpreted Greek text');
 
 %!demo
-%! clf
-%! plot(1:10, 1:10, 1:10, fliplr(1:10));
-%! title("Legend with text to the right")
-%! legend({"I am blue", "I am green"}, "location", "east");
-%! legend right
+%! clf;
+%! plot (rand (2));
+%! title ('Labels with TeX interpreter turned off');
+%! h = legend ('Hello_World', 'foo^bar');
+%! set (h, 'interpreter', 'none');
 
 %!demo
-%! clf
-%! plot(1:10, 1:10);
-%! title("a very long label can sometimes cause problems");
-%! legend({"hello world"}, "location", "northeastoutside");
-
-%!demo
-%! clf
-%! plot(1:10, 1:10);
-%! title("a very long label can sometimes cause problems");
-%! legend("hello world", "location", "northeastoutside");
+%! clf;
+%! plot (1:10, 1:10);
+%! title ('a very long label can sometimes cause problems');
+%! legend ('hello very big world', 'location', 'northeastoutside');
 
 %!demo
-%! clf
+%! clf;
 %! labels = {};
-%! colororder = get (gca, "colororder");
+%! colororder = get (gca, 'colororder');
 %! for i = 1:5
-%!   h = plot(1:100, i + rand(100,1)); hold on;
-%!   set (h, "color", colororder(i,:))
-%!   labels = {labels{:}, cstrcat("Signal ", num2str(i))};
-%! endfor
+%!   h = plot (1:100, i + rand (100,1)); hold on;
+%!   set (h, 'color', colororder(i,:));
+%!   labels = {labels{:}, ['Signal ', num2str(i)]};
+%! end
 %! hold off;
-%! title("Signals with random offset and uniform noise")
-%! xlabel("Sample Nr [k]"); ylabel("Amplitude [V]");
-%! legend(labels, "location", "southoutside");
-%! legend("boxon");
+%! title ({'Signals with random offset and uniform noise';
+%!         'Legend shown below and outside of plot'});
+%! xlabel ('Sample Nr [k]'); ylabel ('Amplitude [V]');
+%! legend (labels, 'location', 'southoutside');
 
 %!demo
-%! clf
-%! labels = {};
-%! colororder = get (gca, "colororder");
-%! for i = 1:5
-%!   h = plot(1:100, i + rand(100,1)); hold on;
-%!   set (h, "color", colororder(i,:))
-%!   labels = {labels{:}, cstrcat("Signal ", num2str(i))};
-%! endfor
-%! hold off;
-%! title("Signals with random offset and uniform noise")
-%! xlabel("Sample Nr [k]"); ylabel("Amplitude [V]");
-%! legend(labels{:}, "location", "southoutside")
-%! legend("boxon")
-
-%!demo
-%! clf
+%! clf;
 %! x = linspace (0, 10);
 %! plot (x, x);
-%! hold ("on");
-%! stem (x, x.^2, 'g')
-%! legend ("linear");
-%! hold ("off");
+%! hold on;
+%! stem (x, x.^2, 'g');
+%! title ('First created object gets first label');
+%! legend ('linear');
+%! hold off;
 
 %!demo
-%! clf
+%! clf;
 %! x = linspace (0, 10);
 %! plot (x, x, x, x.^2);
-%! legend ("linear");
+%! title ('First created object gets first label');
+%! legend ('linear');
 
 %!demo
-%! clf
+%! clf;
 %! x = linspace (0, 10);
 %! plot (x, x, x, x.^2);
-%! legend ("linear", "quadratic");
+%! title ('Labels are applied in order of object creation');
+%! legend ('linear', 'quadratic');
 
 %!demo
-%! clf
+%! clf;
 %! rand_2x3_data1 = [0.341447, 0.171220, 0.284370; 0.039773, 0.731725, 0.779382];
 %! bar (rand_2x3_data1);
 %! ylim ([0 1.0]);
-%! legend ({"1st Bar", "2nd Bar", "3rd Bar"});
+%! title ('legend() works for bar graphs (hgobjects)');
+%! legend ({'1st Bar', '2nd Bar', '3rd Bar'});
 
 %!demo
-%! clf
+%! clf;
 %! rand_2x3_data2 = [0.44804, 0.84368, 0.23012; 0.72311, 0.58335, 0.90531];
 %! bar (rand_2x3_data2);
 %! ylim ([0 1.2]);
-%! legend ("1st Bar", "2nd Bar", "3rd Bar");
-%! legend right
+%! title ('legend() works for bar graphs (hgobjects)');
+%! legend ('1st Bar', '2nd Bar', '3rd Bar');
+%! legend right;
 
 %!demo
-%! clf
+%! clf;
 %! x = 0:0.1:7;
-%! h = plot (x, sin(x), x, cos(x), x, sin(x.^2/10), x, cos(x.^2/10));
-%! title ("Only the sin() objects have keylabels");
-%! legend (h([1, 3]), {"sin(x)", "sin(x^2/10)"}, "location", "southwest");
+%! h = plot (x,sin(x), x,cos(x), x,sin(x.^2/10), x,cos(x.^2/10));
+%! title ('Only the sin() objects have keylabels');
+%! legend (h([1, 3]), {'sin (x)', 'sin (x^2/10)'}, 'location', 'southwest');
 
 %!demo
-%! clf
+%! clf;
 %! x = 0:0.1:10;
-%! plot (x, sin(x), ";sin(x);")
-%! hold all
-%! plot (x, cos(x), ";cos(x);")
-%! hold off
+%! plot (x, sin (x), ';sin (x);');
+%! hold all;
+%! plot (x, cos (x), ';cos (x);');
+%! hold off;
+%! title ('legend constructed from multiple plot calls');
 
 %!demo
-%! clf
+%! clf;
 %! x = 0:0.1:10;
-%! plot (x, sin(x), ";sin(x);")
-%! hold all
-%! plot (x, cos(x), ";cos(x);")
-%! hold off
-%! legend ({"sin(x)", "cos(x)"}, "location", "northeastoutside")
+%! plot (x, sin (x), ';sin (x);');
+%! hold all;
+%! plot (x, cos (x), ';cos (x);');
+%! hold off;
+%! title ('Specified label text overrides previous labels');
+%! legend ({'Sine', 'Cosine'}, 'location', 'northeastoutside');
 
 %!demo
-%! clf
+%! clf;
 %! x = 0:10;
 %! plot (x, rand (11));
-%! xlabel ("Indices")
-%! ylabel ("Random Values")
-%! title ("Legend ""off"" should delete the legend")
-%! legend (cellstr (num2str ((1:10)')), "location", "northeastoutside")
-%! legend off
-%! axis ([0, 10, 0 1])
+%! xlabel ('Indices');
+%! ylabel ('Random Values');
+%! title ('Legend ''off'' deletes the legend');
+%! legend (cellstr (num2str ((1:10)')), 'location', 'northeastoutside');
+%! legend off;
+%! axis ([0, 10, 0 1]);
+
+%!demo
+%! clf;
+%! x = (1:5)';
+%! subplot (2,2,1);
+%!  plot (x, rand (numel (x)));
+%!  legend (cellstr (num2str (x)), 'location', 'northwestoutside');
+%! subplot (2,2,2);
+%!  plot (x, rand (numel (x)));
+%!  legend (cellstr (num2str (x)), 'location', 'northeastoutside');
+%! subplot (2,2,3);
+%!  plot (x, rand (numel (x)));
+%!  legend (cellstr (num2str (x)), 'location', 'southwestoutside');
+%! subplot (2,2,4);
+%!  plot (x, rand (numel (x)));
+%!  legend (cellstr (num2str (x)), 'location', 'southeastoutside');
 
 %!demo
-%! clf
-%! x = 1:5;
-%! subplot (2, 2, 1)
-%! plot (x, rand (numel (x)));
-%! legend (cellstr (num2str (x')), "location", "northwestoutside")
-%! legend boxon
-%! subplot (2, 2, 2)
-%! plot (x, rand (numel (x)));
-%! legend (cellstr (num2str (x')), "location", "northeastoutside")
-%! legend boxon
-%! subplot (2, 2, 3);
-%! plot (x, rand (numel (x)));
-%! legend (cellstr (num2str (x')), "location", "southwestoutside")
-%! legend boxon
-%! subplot (2, 2, 4)
-%! plot (x, rand (numel (x)));
-%! legend (cellstr (num2str (x')), "location", "southeastoutside")
-%! legend boxon
+%! clf;
+%! plot (rand (2));
+%! title ('legend() will warn if extra labels are specified');
+%! legend ('Hello', 'World', 'interpreter', 'foobar');
+
+%!demo
+%! x = 0:10;
+%! y1 = rand (size (x));
+%! y2 = rand (size (x));
+%! [ax, h1, h2] = plotyy (x, y1, x, y2);
+%! title ('plotyy legend test #1: Blue and Green labels');
+%! legend ([h1, h2], {'Blue', 'Green'}, 'location', 'south');
 
 %!demo
-%! clf
-%! plot (rand (2))
-%! title ("Warn of extra labels")
-%! legend ("Hello", "World", "interpreter", "foobar")
+%! x = 0:10;
+%! y1 = rand (size (x));
+%! y2 = rand (size (x));
+%! [ax, h1, h2] = plotyy (x, y1, x, y2);
+%! title ('plotyy legend test #2: Blue and Green labels');
+%! legend ({'Blue', 'Green'}, 'location', 'south');
 
 %!demo
-%! clf
-%! plot (rand (2))
-%! title ("Turn off TeX interpreter")
-%! h = legend ("Hello_World", "foo^bar");
-%! set (h, "interpreter", "none")
+%! x = 0:10;
+%! y1 = rand (size (x));
+%! y2 = rand (size (x));
+%! [ax, h1, h2] = plotyy (x, y1, x, y2);
+%! title ('plotyy legend test #3: Blue and Green labels');
+%! legend ('Blue', 'Green', 'location', 'south');
 
--- a/scripts/plot/line.m
+++ b/scripts/plot/line.m
@@ -43,6 +43,21 @@
 
 endfunction
 
+%!demo
+%! clf
+%! x = 0:0.3:10;
+%! y1 = cos (x);
+%! y2 = sin (x);
+%! subplot (3,1,1);
+%! args = {"color", "b", "marker", "s"};
+%! line ([x(:), x(:)], [y1(:), y2(:)], args{:})
+%! title ("Test broadcasting for line()")
+%! subplot (3,1,2);
+%! line (x(:), [y1(:), y2(:)], args{:})
+%! subplot (3,1,3);
+%! line ([x(:), x(:)+pi/2], y1(:), args{:})
+%! xlim ([0 10])
+
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
@@ -57,3 +72,4 @@
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
--- a/scripts/plot/loglog.m
+++ b/scripts/plot/loglog.m
@@ -38,7 +38,7 @@
   [h, varargin, nargs] = __plt_get_axis_arg__ ("loglog", varargin{:});
 
   if (nargs < 1)
-    print_usage();
+    print_usage ();
   endif
 
   oldh = gca ();
@@ -62,37 +62,38 @@
 
 endfunction
 
+
 %!demo
-%! clf ();
+%! clf;
 %! t = 1:0.01:10;
 %! x = sort ((t .* (1 + rand (size (t)))) .^ 2);
-%! y = ((t .* (1 + rand (size (t)))) .^ 2);
+%! y = (t .* (1 + rand (size (t)))) .^ 2;
 %! loglog (x, y);
 
 %!demo
-%! clf ();
+%! clf;
 %! a = logspace (-5, 1, 10);
 %! b =-logspace (-5, 1, 10);
 %!
-%! subplot (1, 2, 1)
-%! loglog (a, b)
-%! xlabel ('loglog (a, b)')
+%! subplot (1,2,1);
+%!  loglog (a, b);
+%!  xlabel ('loglog (a, b)');
 %!
-%! subplot (1, 2, 2)
-%! loglog (a, abs (b))
-%! set (gca, 'ydir', 'reverse')
-%! xlabel ('loglog (a, abs (b))')
+%! subplot (1,2,2);
+%!  loglog (a, abs (b));
+%!  set (gca, 'ydir', 'reverse');
+%!  xlabel ('loglog (a, abs (b))');
 
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
 %!   a = logspace (-5, 1, 10);
 %!   b = logspace (-5, 1, 10);
-%!   loglog (a, b)
+%!   loglog (a, b);
 %!   assert (get (gca, "yscale"), "log");
 %!   assert (get (gca, "xscale"), "log");
 %! unwind_protect_cleanup
-%! close (hf);
+%!   close (hf);
 %! end_unwind_protect
 
 %!test
@@ -100,10 +101,10 @@
 %! unwind_protect
 %!   a = logspace (-5, 1, 10);
 %!   b =-logspace (-5, 1, 10);
-%!   loglog (a, b)
-%!   axis tight
+%!   loglog (a, b);
+%!   axis tight;
 %!   assert (all (get (gca, "ytick") < 0));
 %! unwind_protect_cleanup
-%! close (hf);
+%!   close (hf);
 %! end_unwind_protect
 
--- a/scripts/plot/loglogerr.m
+++ b/scripts/plot/loglogerr.m
@@ -60,12 +60,13 @@
 
 endfunction
 
+
 %!demo
-%! clf
-%! x = exp (log(0.01):0.2:log(10));
+%! clf;
+%! x = exp (log (0.01):0.2:log (10));
 %! y = wblpdf (x, 3, 2);
 %! eyu = 2*rand (size (y)) .* y;
 %! eyl = 0.5*rand (size (y)) .* y;
-%! loglogerr (x, y, eyl, eyu, "#~x-")
-%! xlim (x([1, end]))
+%! loglogerr (x, y, eyl, eyu, '#~x-');
+%! xlim (x([1, end]));
 
--- a/scripts/plot/mesh.m
+++ b/scripts/plot/mesh.m
@@ -63,5 +63,25 @@
 endfunction
 
 
-%% FIXME: Need demo or test for function
+%!demo
+%! clf ();
+%! x = logspace (0,1,11);
+%! z = x'*x;
+%! mesh (x, x, z, z.^2);
+%! xlabel xlabel
+%! ylabel ylabel
+%! zlabel "linear scale"
 
+%!demo
+%! clf ();
+%! x = logspace (0,1,11);
+%! z = x'*x;
+%! mesh (x, x, z, z.^2);
+%! set (gca, "zscale", "log")
+%! xlabel xlabel
+%! ylabel ylabel
+%! zlabel "log scale"
+%! if (strcmp (get (gcf, "__graphics_toolkit__"), "gnuplot"))
+%!   title ({"Gnuplot: mesh color is wrong", "This a Gnuplot bug"})
+%! endif
+
--- a/scripts/plot/meshgrid.m
+++ b/scripts/plot/meshgrid.m
@@ -71,6 +71,7 @@
 
 endfunction
 
+
 %!test
 %! x = 1:2;
 %! y = 1:3;
@@ -100,4 +101,5 @@
 %! assert (ndims (XX1), 2);
 %! assert (size (XX1), [3, 3]);
 %! assert (XX1, XX2);
-%! assert (YY1, YY2);
\ No newline at end of file
+%! assert (YY1, YY2);
+
--- a/scripts/plot/meshz.m
+++ b/scripts/plot/meshz.m
@@ -68,10 +68,10 @@
          y(end, 1), y(end, :), y(end, end)];
   endif
 
-  zref = min(z(isfinite(z)));
-  z = [zref .* ones(1, size(z, 2) + 2);
-       zref .* ones(size(z, 1), 1), z, zref .* ones(size(z, 1), 1);
-       zref.* ones(1, size(z, 2) + 2)];
+  zref = min (z(isfinite (z)));
+  z = [zref .* ones(1, columns(z) + 2);
+       zref .* ones(rows(z), 1), z, zref .* ones(rows(z), 1);
+       zref.* ones(1, columns(z) + 2)];
 
   oldh = gca ();
   unwind_protect
--- a/scripts/plot/module.mk
+++ b/scripts/plot/module.mk
@@ -80,6 +80,7 @@
   plot/contour3.m \
   plot/contourc.m \
   plot/contourf.m \
+  plot/copyobj.m \
   plot/cylinder.m \
   plot/daspect.m \
   plot/diffuse.m \
@@ -98,18 +99,21 @@
   plot/figure.m \
   plot/fill.m \
   plot/findall.m \
+  plot/findfigs.m \
   plot/findobj.m \
   plot/fplot.m \
   plot/gca.m \
   plot/gcbf.m \
   plot/gcbo.m \
   plot/gcf.m \
+  plot/gco.m \
   plot/ginput.m \
   plot/graphics_toolkit.m \
   plot/grid.m \
   plot/gtext.m \
   plot/guidata.m \
   plot/guihandles.m \
+  plot/hdl2struct.m \
   plot/hggroup.m \
   plot/hidden.m \
   plot/hist.m \
@@ -146,6 +150,7 @@
   plot/plotyy.m \
   plot/polar.m \
   plot/print.m \
+  plot/printd.m \
   plot/quiver.m \
   plot/quiver3.m \
   plot/rectangle.m \
@@ -162,20 +167,23 @@
   plot/semilogyerr.m \
   plot/shading.m \
   plot/shg.m \
+  plot/shrinkfaces.m \
   plot/slice.m \
   plot/sombrero.m \
   plot/specular.m \
   plot/sphere.m \
-  plot/spinmap.m \
   plot/stairs.m \
   plot/stem.m \
   plot/stem3.m \
+  plot/stemleaf.m \
+  plot/struct2hdl.m \
   plot/subplot.m \
   plot/surf.m \
   plot/surface.m \
   plot/surfc.m \
   plot/surfl.m \
   plot/surfnorm.m \
+  plot/tetramesh.m \
   plot/text.m \
   plot/title.m \
   plot/trimesh.m \
@@ -196,6 +204,7 @@
   plot/view.m \
   plot/waitbar.m \
   plot/waitforbuttonpress.m \
+  plot/waterfall.m \
   plot/whitebg.m \
   plot/xlabel.m \
   plot/xlim.m \
--- a/scripts/plot/ndgrid.m
+++ b/scripts/plot/ndgrid.m
@@ -20,13 +20,13 @@
 ## @deftypefn  {Function File} {[@var{y1}, @var{y2}, @dots{}, @var{y}n] =} ndgrid (@var{x1}, @var{x2}, @dots{}, @var{x}n)
 ## @deftypefnx {Function File} {[@var{y1}, @var{y2}, @dots{}, @var{y}n] =} ndgrid (@var{x})
 ## Given n vectors @var{x1}, @dots{} @var{x}n, @code{ndgrid} returns
-## n arrays of dimension n. The elements of the i-th output argument
+## n arrays of dimension n.  The elements of the i-th output argument
 ## contains the elements of the vector @var{x}i repeated over all
 ## dimensions different from the i-th dimension.  Calling ndgrid with
 ## only one input argument @var{x} is equivalent of calling ndgrid with
 ## all n input arguments equal to @var{x}:
 ##
-## [@var{y1}, @var{y2}, @dots{},  @var{y}n] = ndgrid (@var{x}, @dots{}, @var{x})
+## [@var{y1}, @var{y2}, @dots{}, @var{y}n] = ndgrid (@var{x}, @dots{}, @var{x})
 ## @seealso{meshgrid}
 ## @end deftypefn
 
@@ -70,6 +70,7 @@
 
 endfunction
 
+
 %!test
 %! x = 1:2;
 %! y = 1:3;
@@ -95,3 +96,4 @@
 %! assert (XX2(end) * YY2(end), x(end) * y(end));
 %! assert (XX1, XX2.');
 %! assert (YY1, YY2.');
+
--- a/scripts/plot/newplot.m
+++ b/scripts/plot/newplot.m
@@ -17,13 +17,17 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} newplot ()
+## @deftypefn  {Function File} {} newplot ()
+## @deftypefnx {Function File} {@var{h} =} newplot ()
 ## Prepare graphics engine to produce a new plot.  This function is
 ## called at the beginning of all high-level plotting functions.
 ## It is not normally required in user programs.
+##
+## The optional return value @var{h} is a graphics handle to the created
+## axes (not figure).
 ## @end deftypefn
 
-function newplot ()
+function h = newplot ()
 
   if (nargin == 0)
     cf = gcf ();
@@ -59,18 +63,24 @@
       otherwise
         error ("newplot: unrecognized nextplot property for current axes");
     endswitch
+    if (nargout > 0)
+      h = ca;
+    endif
   else
     print_usage ();
   endif
 
 endfunction
 
+
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
 %!   p = plot ([0, 1]);
-%!   newplot;
+%!   ha = newplot ();
+%!   assert (ha, gca);
 %!   assert (isempty (get (gca, "children")));
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
--- a/scripts/plot/orient.m
+++ b/scripts/plot/orient.m
@@ -70,40 +70,42 @@
 
 endfunction
 
+
 %!shared papersize, paperposition, tallpaperposition, hfig
-%!  papersize = [8.5, 11];
-%!  paperposition = [0.25, 2.5, 8, 6];
-%!  tallpaperposition = [0.25, 0.25, (papersize-0.5)];
-%!  hfig = figure ();
-%!  set (hfig, "visible", "off")
-%!  set (hfig, "paperorientation", "portrait")
-%!  set (hfig, "papersize", papersize)
-%!  set (hfig, "paperposition", paperposition)
+%! papersize = [8.5, 11];
+%! paperposition = [0.25, 2.5, 8, 6];
+%! tallpaperposition = [0.25, 0.25, (papersize-0.5)];
+%! hfig = figure ();
+%! set (hfig, "visible", "off");
+%! set (hfig, "paperorientation", "portrait");
+%! set (hfig, "papersize", papersize);
+%! set (hfig, "paperposition", paperposition);
 %!test
-%!  orient portrait
-%!  assert (orient, "portrait") # default
-%!  assert (get (hfig, "papersize"), papersize)
-%!  assert (get (hfig, "paperposition"), paperposition)
+%! orient portrait;
+%! assert (orient, "portrait")   # default
+%! assert (get (hfig, "papersize"), papersize);
+%! assert (get (hfig, "paperposition"), paperposition);
 %!test
-%!  orient landscape
-%!  assert (orient,"landscape") # change to landscape
-%!  assert (get (hfig, "papersize"), papersize([2, 1]))
-%!  assert (get (hfig, "paperposition"), paperposition([2, 1, 4, 3]))
+%! orient landscape;
+%! assert (orient,"landscape")   # change to landscape
+%! assert (get (hfig, "papersize"), papersize([2, 1]));
+%! assert (get (hfig, "paperposition"), paperposition([2, 1, 4, 3]));
 %!test
-%!  orient portrait # change back to portrait
-%!  assert (orient, "portrait")
-%!  assert (get (hfig, "papersize"), papersize)
-%!  assert (get (hfig, "paperposition"), paperposition)
+%! orient portrait   # change back to portrait
+%! assert (orient, "portrait");
+%! assert (get (hfig, "papersize"), papersize);
+%! assert (get (hfig, "paperposition"), paperposition);
 %!test
-%!  orient landscape
-%!  orient tall
-%!  assert (orient, "portrait")
-%!  assert (get (hfig, "papersize"), papersize)
-%!  assert (get (hfig, "paperposition"), tallpaperposition)
+%! orient landscape;
+%! orient tall;
+%! assert (orient, "portrait");
+%! assert (get (hfig, "papersize"), papersize);
+%! assert (get (hfig, "paperposition"), tallpaperposition);
 %!fail ("orient ('nobody')", "unknown ORIENTATION")
 %!test
-%!  orient portrait # errors don't change the state
-%!  assert (orient, "portrait")
-%!  assert (get (hfig, "papersize"), papersize)
-%!  assert (get (hfig, "paperposition"), tallpaperposition)
-%!  close (hfig)
+%! orient portrait   # errors don't change the state
+%! assert (orient, "portrait");
+%! assert (get (hfig, "papersize"), papersize);
+%! assert (get (hfig, "paperposition"), tallpaperposition);
+%! close (hfig);
+
--- a/scripts/plot/pareto.m
+++ b/scripts/plot/pareto.m
@@ -74,20 +74,20 @@
       endif
     endif
   else
-    y = cellfun ("int2str", num2cell (1 : numel(x)),
+    y = cellfun ("int2str", num2cell (1 : numel (x)),
                  "uniformoutput", false);
   endif
 
   [x, idx] = sort (x, "descend");
   y = y (idx);
   cdf = cumsum (x);
-  maxcdf = max(cdf);
+  maxcdf = max (cdf);
   cdf = cdf ./ maxcdf;
   cdf95 = cdf - 0.95;
-  idx95 = find(sign(cdf95(1:end-1)) != sign(cdf95(2:end)))(1);
+  idx95 = find (sign (cdf95(1:end-1)) != sign (cdf95(2:end)))(1);
 
   [ax, hbar, hline] = plotyy (1 : idx95, x (1 : idx95),
-                              1 : length(cdf), 100 .* cdf,
+                              1 : length (cdf), 100 .* cdf,
                               @bar, @plot);
 
   axis (ax(1), [1 - 0.6, idx95 + 0.6, 0, maxcdf]);
@@ -105,16 +105,16 @@
 
 
 %!demo
-%! clf
+%! clf;
 %! colormap (jet (64));
-%! Cheese = {"Cheddar", "Swiss", "Camembert", "Munster", "Stilton", "Blue"};
+%! Cheese = {'Cheddar', 'Swiss', 'Camembert', 'Munster', 'Stilton', 'Blue'};
 %! Sold = [105, 30, 70, 10, 15, 20];
 %! pareto (Sold, Cheese);
 
 %!demo
-%! clf
-%! % Suppose that we want establish which products makes 80 % of turnover.
-%! Codes = {"AB4","BD7","CF8","CC5","AD11","BB5","BB3","AD8","DF3","DE7"};
+%! clf;
+%! % Suppose that we want establish which products makes 80% of turnover.
+%! Codes = {'AB4','BD7','CF8','CC5','AD11','BB5','BB3','AD8','DF3','DE7'};
 %! Value = [2.35 7.9 2.45 1.1 0.15 13.45 5.4 2.05 0.85  1.65]';
 %! SoldUnits = [54723 41114 16939 1576091 168000 687197 120222 168195, ...
 %!              1084118 55576]';
--- a/scripts/plot/patch.m
+++ b/scripts/plot/patch.m
@@ -21,7 +21,7 @@
 ## @deftypefnx {Function File} {} patch (@var{x}, @var{y}, @var{c})
 ## @deftypefnx {Function File} {} patch (@var{x}, @var{y}, @var{z}, @var{c})
 ## @deftypefnx {Function File} {} patch (@var{fv})
-## @deftypefnx {Function File} {} patch ('Faces', @var{f}, 'Vertices', @var{v}, @dots{})
+## @deftypefnx {Function File} {} patch ("Faces", @var{f}, "Vertices", @var{v}, @dots{})
 ## @deftypefnx {Function File} {} patch (@dots{}, @var{prop}, @var{val})
 ## @deftypefnx {Function File} {} patch (@var{h}, @dots{})
 ## @deftypefnx {Function File} {@var{h} =} patch (@dots{})
@@ -59,69 +59,70 @@
 
 endfunction
 
+
 %!demo
-%! ## Patches with same number of vertices
-%! clf
-%! t1 = (1/16:1/8:1)'*2*pi;
-%! t2 = ((1/16:1/8:1)' + 1/32)*2*pi;
+%! %% Patches with same number of vertices
+%! clf;
+%! t1 = (1/16:1/8:1)' * 2*pi;
+%! t2 = ((1/16:1/8:1)' + 1/32) * 2*pi;
 %! x1 = sin (t1) - 0.8;
 %! y1 = cos (t1);
 %! x2 = sin (t2) + 0.8;
 %! y2 = cos (t2);
-%! patch([x1,x2],[y1,y2],'r');
+%! patch ([x1,x2], [y1,y2], 'r');
 
 %!demo
-%! ## Unclosed patch
-%! clf
-%! t1 = (1/16:1/8:1)'*2*pi;
-%! t2 = ((1/16:1/16:1)' + 1/32)*2*pi;
+%! %% Unclosed patch
+%! clf;
+%! t1 = (1/16:1/8:1)' * 2*pi;
+%! t2 = ((1/16:1/16:1)' + 1/32) * 2*pi;
 %! x1 = sin (t1) - 0.8;
 %! y1 = cos (t1);
 %! x2 = sin (t2) + 0.8;
 %! y2 = cos (t2);
-%! patch([[x1;NaN(8,1)],x2],[[y1;NaN(8,1)],y2],'r');
+%! patch ([[x1;NaN(8,1)],x2], [[y1;NaN(8,1)],y2], 'r');
 
 %!demo
-%! ## Specify vertices and faces separately
-%! clf
-%! t1 = (1/16:1/8:1)'*2*pi;
-%! t2 = ((1/16:1/16:1)' + 1/32)*2*pi;
+%! %% Specify vertices and faces separately
+%! clf;
+%! t1 = (1/16:1/8:1)' * 2*pi;
+%! t2 = ((1/16:1/16:1)' + 1/32) * 2*pi;
 %! x1 = sin (t1) - 0.8;
 %! y1 = cos (t1);
 %! x2 = sin (t2) + 0.8;
 %! y2 = cos (t2);
 %! vert = [x1, y1; x2, y2];
 %! fac = [1:8,NaN(1,8);9:24];
-%! patch('Faces',fac,'Vertices',vert,'FaceColor','r');
+%! patch ('Faces',fac, 'Vertices',vert, 'FaceColor','r');
 
 %!demo
-%! ## Specify vertices and faces separately
-%! clf
-%! t1 = (1/16:1/8:1)'*2*pi;
-%! t2 = ((1/16:1/16:1)' + 1/32)*2*pi;
+%! %% Specify vertices and faces separately
+%! clf;
+%! t1 = (1/16:1/8:1)' * 2*pi;
+%! t2 = ((1/16:1/16:1)' + 1/32) * 2*pi;
 %! x1 = sin (t1) - 0.8;
 %! y1 = cos (t1);
 %! x2 = sin (t2) + 0.8;
 %! y2 = cos (t2);
 %! vert = [x1, y1; x2, y2];
 %! fac = [1:8,NaN(1,8);9:24];
-%! patch('Faces',fac,'Vertices',vert,'FaceVertexCData', [0, 1, 0; 0, 0, 1]);
+%! patch ('Faces',fac, 'Vertices',vert, 'FaceVertexCData',[0, 1, 0; 0, 0, 1]);
 
 %!demo
-%! ## Property change on multiple patches
-%! clf
-%! t1 = (1/16:1/8:1)'*2*pi;
-%! t2 = ((1/16:1/8:1)' + 1/32)*2*pi;
+%! %% Property change on multiple patches
+%! clf;
+%! t1 = (1/16:1/8:1)' * 2*pi;
+%! t2 = ((1/16:1/8:1)' + 1/32) * 2*pi;
 %! x1 = sin (t1) - 0.8;
 %! y1 = cos (t1);
 %! x2 = sin (t2) + 0.8;
 %! y2 = cos (t2);
-%! h = patch([x1,x2],[y1,y2],cat (3,[0,0],[1,0],[0,1]));
+%! h = patch ([x1,x2], [y1,y2], cat (3, [0,0],[1,0],[0,1]));
 %! pause (1);
 %! set (h, 'FaceColor', 'r');
 
 %!demo
-%! clf
+%! clf;
 %! vertices = [0, 0, 0;
 %!             1, 0, 0;
 %!             1, 1, 0;
@@ -132,11 +133,11 @@
 %!          3, 4, 5;
 %!          4, 1, 5];
 %! patch ('Vertices', vertices, 'Faces', faces, ...
-%!        'FaceVertexCData', jet(4), 'FaceColor', 'flat');
+%!        'FaceVertexCData', jet (4), 'FaceColor', 'flat');
 %! view (-37.5, 30);
 
 %!demo
-%! clf
+%! clf;
 %! vertices = [0, 0, 0;
 %!             1, 0, 0;
 %!             1, 1, 0;
@@ -146,64 +147,64 @@
 %!          2, 3, 5;
 %!          3, 4, 5;
 %!          4, 1, 5];
-%! patch ('Vertices', vertices, 'Faces', faces, ...
-%!        'FaceVertexCData', jet(5), 'FaceColor', 'interp');
+%! patch  ('Vertices', vertices, 'Faces', faces, ...
+%!        'FaceVertexCData', jet (5), 'FaceColor', 'interp');
 %! view (-37.5, 30);
 
 %!demo
-%! clf
-%! colormap (jet);
+%! clf;
+%! colormap (jet (64));
 %! x = [0 1 1 0];
 %! y = [0 0 1 1];
-%! subplot (2, 1, 1);
-%! title ("Blue, Light-Green, and Red Horizontal Bars");
-%! patch (x, y + 0, 1);
-%! patch (x, y + 1, 2);
-%! patch (x, y + 2, 3);
-%! subplot (2, 1, 2);
-%! title ("Blue, Light-Green, and Red Vertical Bars");
-%! patch (x + 0, y, 1 * ones (size (x)));
-%! patch (x + 1, y, 2 * ones (size (x)));
-%! patch (x + 2, y, 3 * ones (size (x)));
-
-%!demo
-%! clf
-%! colormap (jet);
-%! x = [0 1 1 0];
-%! y = [0 0 1 1];
-%! subplot (2, 1, 1);
-%! title ("Blue horizontal bars: Dark to Light");
-%! patch (x, y + 0, 1, "cdatamapping", "direct");
-%! patch (x, y + 1, 9, "cdatamapping", "direct");
-%! patch (x, y + 2, 17, "cdatamapping", "direct");
-%! subplot (2, 1, 2);
-%! title ("Blue vertical bars: Dark to Light")
-%! patch (x + 0, y, 1 * ones (size (x)), "cdatamapping", "direct");
-%! patch (x + 1, y, 9 * ones (size (x)), "cdatamapping", "direct");
-%! patch (x + 2, y, 17 * ones (size (x)), "cdatamapping", "direct");
+%! subplot (2,1,1);
+%!  title ('Blue, Light-Green, and Red Horizontal Bars');
+%!  patch (x, y + 0, 1);
+%!  patch (x, y + 1, 2);
+%!  patch (x, y + 2, 3);
+%! subplot (2,1,2);
+%!  title ('Blue, Light-Green, and Red Vertical Bars');
+%!  patch (x + 0, y, 1 * ones (size (x)));
+%!  patch (x + 1, y, 2 * ones (size (x)));
+%!  patch (x + 2, y, 3 * ones (size (x)));
 
 %!demo
 %! clf;
-%! colormap (jet);
-%! x = [ 0 0; 1 1; 1 0 ];
-%! y = [ 0 0; 0 1; 1 1 ];
-%! p = patch (x, y, "facecolor", "b");
-%! title ("Two blue triangles");
-%! set (p, "cdatamapping", "direct", "facecolor", "flat", "cdata", [1 32]);
-%! title ("Direct mapping of colors: Light-Green UL and Blue LR triangles");
+%! colormap (jet (64));
+%! x = [0 1 1 0];
+%! y = [0 0 1 1];
+%! subplot (2,1,1);
+%!  title ('Blue horizontal bars: Dark to Light');
+%!  patch (x, y + 0, 1, 'cdatamapping', 'direct');
+%!  patch (x, y + 1, 9, 'cdatamapping', 'direct');
+%!  patch (x, y + 2, 17, 'cdatamapping', 'direct');
+%! subplot (2,1,2);
+%!  title ('Blue vertical bars: Dark to Light');
+%!  patch (x + 0, y, 1 * ones (size (x)), 'cdatamapping', 'direct');
+%!  patch (x + 1, y, 9 * ones (size (x)), 'cdatamapping', 'direct');
+%!  patch (x + 2, y, 17 * ones (size (x)), 'cdatamapping', 'direct');
 
 %!demo
 %! clf;
-%! colormap (jet);
+%! colormap (jet (64));
+%! x = [ 0 0; 1 1; 1 0 ];
+%! y = [ 0 0; 0 1; 1 1 ];
+%! p = patch (x, y, 'facecolor', 'b');
+%! title ('Two blue triangles');
+%! set (p, 'cdatamapping', 'direct', 'facecolor', 'flat', 'cdata', [1 32]);
+%! title ('Direct mapping of colors: Light-Green UL and Blue LR triangles');
+
+%!demo
+%! clf;
+%! colormap (jet (64));
 %! x = [ 0 0; 1 1; 1 0 ];
 %! y = [ 0 0; 0 1; 1 1 ];
 %! p = patch (x, y, [1 32]);
-%! title ("Autoscaling of colors: Red UL and Blue LR triangles");
+%! title ('Autoscaling of colors: Red UL and Blue LR triangles');
 
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
-%!   h = patch;
+%!   h = patch ();
 %!   assert (findobj (hf, "type", "patch"), h);
 %!   assert (get (h, "xdata"), [0; 1; 0], eps);
 %!   assert (get (h, "ydata"), [1; 1; 0], eps);
--- a/scripts/plot/pbaspect.m
+++ b/scripts/plot/pbaspect.m
@@ -17,22 +17,28 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} pbaspect (@var{plot_box_aspect_ratio})
-## Set the plot box aspect ratio of the current axes.  The aspect ratio
-## is a normalized 3-element vector representing the rendered lengths of
-## the x, y, and z-axes.
+## @deftypefn  {Function File} {@var{plot_box_aspect_ratio} =} pbaspect ( )
+## @deftypefnx {Function File} {} pbaspect (@var{plot_box_aspect_ratio})
+## @deftypefnx {Function File} {} pbaspect (@var{mode})
+## @deftypefnx {Function File} {@var{plot_box_aspect_ratio_mode} =} pbaspect ("mode")
+## @deftypefnx {Function File} {} pbaspect (@var{hax}, @dots{})
 ##
-## @deftypefnx {Function File} {@var{plot_box_aspect_ratio} =} pbaspect ( )
-## Return the plot box aspect ratio of the current axes.
+## Query or set the plot box aspect ratio of the current axes.  The aspect
+## ratio is a normalized 3-element vector representing the rendered lengths of
+## the x, y, and z axes.
+##
+## @code{pbaspect(@var{mode})}
 ##
-## @deftypefnx {Function File} {} pbaspect (@var{mode})
-## Set the plot box aspect ratio mode of the current axes.
+## Set the plot box aspect ratio mode of the current axes.  @var{mode} is
+## either "auto" or "manual".
 ##
-## @deftypefnx {Function File} {@var{plot_box_aspect_ratio_mode} =} pbaspect ("mode")
+## @code{pbaspect ("mode")}
+##
 ## Return the plot box aspect ratio mode of the current axes.
 ##
-## @deftypefnx {Function File} {} pbaspect (@var{hax}, @dots{})
-## Use the axes, with handle @var{hax}, instead of the current axes.
+## @code{pbaspect (@var{hax}, @dots{})}
+##
+## Operate on the axes in handle @var{hax} instead of the current axes.
 ##
 ## @seealso{axis, daspect, xlim, ylim, zlim}
 ## @end deftypefn
@@ -89,25 +95,26 @@
 
 endfunction
 
+
 %!demo
+%! clf;
 %! x = 0:0.01:4;
-%! clf
-%! plot (x, cos (x), x, sin (x))
-%! pbaspect ([1 1 1])
-%! title ("plot box should be square")
+%! plot (x,cos(x), x,sin(x));
+%! pbaspect ([1 1 1]);
+%! title ('plot box is square');
 
 %!demo
-%! x = 0:0.01:4;
-%! clf
-%! plot (x, cos (x), x, sin (x))
-%! pbaspect ([2 1 1])
-%! title ("plot box aspect ratio should be 2x1")
+%! clf;
+%! x = 0:0.01:4;;
+%! plot (x,cos(x), x,sin(x));
+%! pbaspect ([2 1 1]);
+%! title ('plot box aspect ratio is 2x1');
 
 %!demo
+%! clf;
 %! x = 0:0.01:4;
-%! clf
-%! plot (x, cos (x), x, sin (x))
-%! daspect ([1 1 1])
-%! pbaspect ([2 1 1])
-%! title ("plot box should be 2x1, and axes [0 4 -1 1]")
+%! plot (x,cos(x), x,sin(x));
+%! daspect ([1 1 1]);
+%! pbaspect ([2 1 1]);
+%! title ('plot box is 2x1, and axes [0 4 -1 1]');
 
--- a/scripts/plot/pcolor.m
+++ b/scripts/plot/pcolor.m
@@ -55,7 +55,7 @@
 
   if (nargin == 1)
     c = x;
-    [nr, nc] = size(c);
+    [nr, nc] = size (c);
     z = zeros (nr, nc);
     [x, y] = meshgrid (1:nc, 1:nr);
   elseif (nargin == 3)
@@ -81,14 +81,18 @@
 
 endfunction
 
+
 %!demo
-%! clf
-%! [~,~,Z]=peaks;
-%! pcolor(Z);
+%! clf;
+%! colormap ('default');
+%! [~,~,Z] = peaks ();
+%! pcolor (Z);
 
 %!demo
-%! clf
-%! [X,Y,Z]=sombrero;
-%! [Fx,Fy] = gradient(Z);
-%! pcolor(X,Y,Fx+Fy);
+%! clf;
+%! colormap ('default');
+%! [X,Y,Z] = sombrero ();
+%! [Fx,Fy] = gradient (Z);
+%! pcolor (X,Y,Fx+Fy);
 %! shading interp;
+
--- a/scripts/plot/peaks.m
+++ b/scripts/plot/peaks.m
@@ -55,7 +55,7 @@
   if (nargin == 0)
     x = y = linspace (-3, 3, 49);
   elseif (nargin == 1)
-    if length(x) > 1
+    if (length (x) > 1)
       y = x;
     else
       x = y = linspace (-3, 3, x);
@@ -69,9 +69,9 @@
     Y = y;
   endif
 
-  Z = 3 * (1 - X) .^ 2 .* exp(- X .^ 2 - (Y + 1) .^ 2) \
-      - 10 * (X / 5 - X .^ 3 - Y .^ 5) .* exp(- X .^ 2 - Y .^ 2) \
-      - 1 / 3 * exp(- (X + 1) .^ 2 - Y .^ 2);
+  Z = 3 * (1 - X) .^ 2 .* exp (- X .^ 2 - (Y + 1) .^ 2) ...
+      - 10 * (X / 5 - X .^ 3 - Y .^ 5) .* exp (- X .^ 2 - Y .^ 2) ...
+      - 1 / 3 * exp (- (X + 1) .^ 2 - Y .^ 2);
 
   if (nargout == 0)
     surf (x, y, Z);
--- a/scripts/plot/pie.m
+++ b/scripts/plot/pie.m
@@ -29,7 +29,7 @@
 ## size of the values of @var{x}.
 ##
 ## The variable @var{explode} is a vector of the same length as @var{x} that
-## if non zero 'explodes' the slice from the pie chart.
+## if non zero "explodes" the slice from the pie chart.
 ##
 ## If given @var{labels} is a cell array of strings of the same length as
 ## @var{x}, giving the labels of each of the slices of the pie chart.
@@ -68,20 +68,20 @@
 
 
 %!demo
-%! clf
+%! clf;
 %! pie ([3, 2, 1], [0, 0, 1]);
 %! colormap ([1,0,0;0,1,0;0,0,1;1,1,0;1,0,1;0,1,1]);
 
 %!demo
-%! clf
-%! pie ([3, 2, 1], [0, 0, 1], {"Cheddar", "Swiss", "Camembert"});
+%! clf;
+%! pie ([3, 2, 1], [0, 0, 1], {'Cheddar', 'Swiss', 'Camembert'});
 %! colormap ([1,0,0;0,1,0;0,0,1;1,1,0;1,0,1;0,1,1]);
 %! axis ([-2,2,-2,2]);
 
 %!demo
-%! clf
-%! pie ([0.17, 0.34, 0.41], {"Cheddar", "Swiss", "Camembert"});
+%! clf;
+%! pie ([0.17, 0.34, 0.41], {'Cheddar', 'Swiss', 'Camembert'});
 %! colormap ([1,0,0;0,1,0;0,0,1;1,1,0;1,0,1;0,1,1]);
 %! axis ([-2,2,-2,2]);
-%! title ("missing slice");
+%! title ('missing slice');
 
--- a/scripts/plot/pie3.m
+++ b/scripts/plot/pie3.m
@@ -30,7 +30,7 @@
 ## size of the values of @var{x}.
 ##
 ## The variable @var{explode} is a vector of the same length as @var{x} that
-## if non zero 'explodes' the slice from the pie chart.
+## if non zero "explodes" the slice from the pie chart.
 ##
 ## If given @var{labels} is a cell array of strings of the same length as
 ## @var{x}, giving the labels of each of the slices of the pie chart.
@@ -69,20 +69,20 @@
 
 
 %!demo
-%! clf
+%! clf;
 %! pie3 ([5:-1:1], [0, 0, 1, 0, 0]);
 %! colormap ([1,0,0;0,1,0;0,0,1;1,1,0;1,0,1;0,1,1]);
 
 %!demo
-%! clf
-%! pie3 ([3, 2, 1], [0, 0, 1], {"Cheddar", "Swiss", "Camembert"});
+%! clf;
+%! pie3 ([3, 2, 1], [0, 0, 1], {'Cheddar', 'Swiss', 'Camembert'});
 %! colormap ([1,0,0;0,1,0;0,0,1;1,1,0;1,0,1;0,1,1]);
 %! axis ([-2,2,-2,2]);
 
 %!demo
-%! clf
-%! pie3 ([0.17, 0.34, 0.41], {"Cheddar", "Swiss", "Camembert"});
+%! clf;
+%! pie3 ([0.17, 0.34, 0.41], {'Cheddar', 'Swiss', 'Camembert'});
 %! colormap ([1,0,0;0,1,0;0,0,1;1,1,0;1,0,1;0,1,1]);
 %! axis ([-2,2,-2,2]);
-%! title ("missing slice");
+%! title ('missing slice');
 
--- a/scripts/plot/plot.m
+++ b/scripts/plot/plot.m
@@ -186,7 +186,7 @@
   [h, varargin, nargs] = __plt_get_axis_arg__ ("plot", varargin{:});
 
   if (nargs < 1)
-    print_usage();
+    print_usage ();
   endif
 
   oldh = gca ();
@@ -205,5 +205,20 @@
 endfunction
 
 
-%% FIXME: Need demo or test for function
+%!demo
+%! x = 1:5;  y = 1:5;
+%! plot (x,y,'g');
+%! title ('plot of green line at 45 degrees');
 
+%!demo
+%! x = 1:5;  y = 1:5;
+%! plot (x,y,'g*');
+%! title ('plot of green stars along a line at 45 degrees');
+
+%!demo
+%! x1 = 1:5;  y1 = 1:5;
+%! x2 = 5:9; y2 = 5:-1:1;
+%! plot (x1,y1,'bo-', x2,y2,'rs-');
+%! axis ('tight');
+%! title ('plot of blue circles ascending and red squares descending with connecting lines drawn'); 
+
--- a/scripts/plot/plot3.m
+++ b/scripts/plot/plot3.m
@@ -121,10 +121,10 @@
             y = real (x);
             y_set = 1;
             z_set = 1;
-            if (rows(x) > 1)
-              x = repmat ((1:rows(x))', 1, columns(x));
+            if (rows (x) > 1)
+              x = repmat ((1:rows (x))', 1, columns (x));
             else
-              x = 1:columns(x);
+              x = 1:columns (x);
             endif
           endif
         else
@@ -164,7 +164,7 @@
         elseif (length (x) == rows (z) && length (y) == columns (z))
           [x, y] = meshgrid (x, y);
         else
-          error ("plot3: [length(x), length(y)] must match size(z)");
+          error ("plot3: [length(x), length(y)] must match size (z)");
         endif
       endif
 
@@ -218,7 +218,7 @@
         elseif (length (x) == rows (z) && length (y) == columns (z))
           [x, y] = meshgrid (x, y);
         else
-          error ("plot3: [length(x), length(y)] must match size(z)");
+          error ("plot3: [length(x), length(y)] must match size (z)");
         endif
       endif
 
@@ -278,9 +278,9 @@
       y_set = 1;
       z_set = 1;
       if (rows (x) > 1)
-        x = repmat ((1:rows (x))', 1, columns(x));
+        x = repmat ((1:rows (x))', 1, columns (x));
       else
-        x = 1:columns(x);
+        x = 1:columns (x);
       endif
     endif
 
@@ -292,7 +292,7 @@
       elseif (length (x) == rows (z) && length (y) == columns (z))
         [x, y] = meshgrid (x, y);
       else
-        error ("plot3: [length(x), length(y)] must match size(z)");
+        error ("plot3: [length(x), length(y)] must match size (z)");
       endif
     endif
 
@@ -327,7 +327,7 @@
   endif
 
   if (!isempty (hlgnd))
-    legend (gca(), hlgnd, tlgnd);
+    legend (gca (), hlgnd, tlgnd);
   endif
 
   set (gca (), "view", [-37.5, 30]);
@@ -338,8 +338,10 @@
 
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
 %! z = [0:0.05:5];
-%! plot3 (cos(2*pi*z), sin(2*pi*z), z, ";helix;");
-%! plot3 (z, exp(2i*pi*z), ";complex sinusoid;");
+%! plot3 (cos (2*pi*z), sin (2*pi*z), z, ';helix;');
+%! plot3 (z, exp (2i*pi*z), ';complex sinusoid;');
+
--- a/scripts/plot/plotmatrix.m
+++ b/scripts/plot/plotmatrix.m
@@ -94,8 +94,8 @@
 endfunction
 
 %!demo
-%! clf
-%! plotmatrix (randn (100, 3), 'g+')
+%! clf;
+%! plotmatrix (randn (100, 3), 'g+');
 
 function plotmatrixdelete (h, d, ax)
   for i = 1 : numel (ax)
@@ -145,7 +145,7 @@
     returm;
   endif
 
-  if (rows(X) != rows(Y))
+  if (rows (X) != rows (Y))
     error ("plotmatrix: dimension mismatch in the arguments");
   endif
 
@@ -164,9 +164,9 @@
   border = [0.130, 0.110, 0.225, 0.185] .* [xsize, ysize, xsize, ysize];
   border(3:4) = - border(3:4) - border(1:2);
 
-  for i = 1 : n
-    for j = 1 : m
-      pos = [xsize * (j - 1) + xoff, ysize * (n - i) + yoff, xsize, ysize];
+  for i = 1 : m
+    for j = 1 : n
+      pos = [xsize * (i - 1) + xoff, ysize * (n - j) + yoff, xsize, ysize];
       tmp = axes ("outerposition", pos, "position", pos + border,
                   "parent", parent);
       if (i == j && have_hist)
--- a/scripts/plot/plotyy.m
+++ b/scripts/plot/plotyy.m
@@ -56,8 +56,8 @@
 function [Ax, H1, H2] = plotyy (varargin)
 
   ## Don't use __plt_get_axis_arg__ here as ax is a two vector for plotyy
-  if (nargin > 1 && length (varargin{1}) == 2 && ishandle(varargin{1}(1))
-      && ishandle(varargin{1}(2))
+  if (nargin > 1 && length (varargin{1}) == 2 && ishandle (varargin{1}(1))
+      && ishandle (varargin{1}(2))
       && all (floor (varargin{1}) != varargin{1}))
     obj1 = get (varargin{1}(1));
     obj2 = get (varargin{1}(2));
@@ -91,6 +91,7 @@
       ax = ax(1:2);
     elseif (length (ax) == 1)
       ax(2) = axes ();
+      set (ax(2), "nextplot", get (ax(1), "nextplot"));
     elseif (isempty (ax))
       ax(1) = axes ();
       ax(2) = axes ();
@@ -110,7 +111,7 @@
     [ax, h1, h2] = __plotyy__ (ax, varargin{:});
   unwind_protect_cleanup
     ## Only change back to the old axis if we didn't delete it
-    if (ishandle(oldh) && strcmp (get (oldh, "type"), "axes"))
+    if (ishandle (oldh) && strcmp (get (oldh, "type"), "axes"))
       axes (oldh);
     endif
   end_unwind_protect
@@ -137,7 +138,7 @@
 
   xlim = [min([x1(:); x2(:)]), max([x1(:); x2(:)])];
 
-  if (ishandle(ax(1)) && strcmp (get (ax(1), "type"), "axes"))
+  if (ishandle (ax(1)) && strcmp (get (ax(1), "type"), "axes"))
     axes (ax(1));
   else
     ax(1) = axes ();
@@ -152,10 +153,11 @@
   cf = gcf ();
   set (cf, "nextplot", "add");
 
-  if (ishandle(ax(2)) && strcmp (get (ax(2), "type"), "axes"))
+  if (ishandle (ax(2)) && strcmp (get (ax(2), "type"), "axes"))
     axes (ax(2));
   else
     ax(2) = axes ();
+    set (ax(2), "nextplot", get (ax(1), "nextplot"));
   endif
   newplot ();
 
@@ -172,7 +174,6 @@
   set (ax(2), "yaxislocation", "right");
   set (ax(2), "ycolor", getcolor (h2(1)));
 
-
   if (strcmp (get(ax(1), "activepositionproperty"), "position"))
     set (ax(2), "position", get (ax(1), "position"));
   else
@@ -208,6 +209,8 @@
   addlistener (ax(2), "plotboxaspectratio", {@update_position, ax(1)});
   addlistener (ax(1), "plotboxaspectratiomode", {@update_position, ax(2)});
   addlistener (ax(2), "plotboxaspectratiomode", {@update_position, ax(1)});
+  addlistener (ax(1), "nextplot", {@update_nextplot, ax(2)});
+  addlistener (ax(2), "nextplot", {@update_nextplot, ax(1)});
 
   ## Store the axes handles for the sister axes.
   if (ishandle (ax(1)) && ! isprop (ax(1), "__plotyy_axes__"))
@@ -215,64 +218,92 @@
   elseif (ishandle (ax(1)))
     set (ax(1), "__plotyy_axes__", ax);
   else
-    error ("plotyy.m: This shouldn't happen. File a bug report.")
+    error ("plotyy.m: This shouldn't happen. File a bug report.");
   endif
   if (ishandle (ax(2)) && ! isprop (ax(2), "__plotyy_axes__"))
     addproperty ("__plotyy_axes__", ax(2), "data", ax);
   elseif (ishandle (ax(2)))
     set (ax(2), "__plotyy_axes__", ax);
   else
-    error ("plotyy.m: This shouldn't happen. File a bug report.")
+    error ("plotyy.m: This shouldn't happen. File a bug report.");
   endif
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
 %! x = 0:0.1:2*pi;
 %! y1 = sin (x);
 %! y2 = exp (x - 1);
-%! ax = plotyy (x, y1, x - 1, y2, @plot, @semilogy);
-%! xlabel ("X");
-%! ylabel (ax(1), "Axis 1");
-%! ylabel (ax(2), "Axis 2");
-%! axes (ax(1))
-%! text (0.5, 0.5, "Left Axis", ...
-%!       "color", [0 0 1], "horizontalalignment", "center")
-%! axes (ax(2))
-%! text (4.5, 80, "Right Axis", ...
-%!       "color", [0 0.5 0], "horizontalalignment", "center")
+%! ax = plotyy (x,y1, x-1,y2, @plot, @semilogy);
+%! xlabel ('X');
+%! ylabel (ax(1), 'Axis 1');
+%! ylabel (ax(2), 'Axis 2');
+%! axes (ax(1));
+%! text (0.5, 0.5, 'Left Axis', ...
+%!       'color', [0 0 1], 'horizontalalignment', 'center');
+%! axes (ax(2));
+%! text (4.5, 80, 'Right Axis', ...
+%!       'color', [0 0.5 0], 'horizontalalignment', 'center');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! x = linspace (-1, 1, 201);
+%! subplot (2,2,1);
+%!  plotyy (x,sin(pi*x), x,10*cos(pi*x));
+%! subplot (2,2,2);
+%!  surf (peaks (25));
+%! subplot (2,2,3);
+%!  contour (peaks (25));
+%! subplot (2,2,4);
+%!  plotyy (x,10*sin(2*pi*x), x,cos(2*pi*x));
+%! axis square;
+
+%!demo
+%! clf;
+%! x = linspace (-1, 1, 201);
+%! hax = plotyy (x, sin (pi*x), x, cos (pi*x));
+%! ylabel (hax(1), 'Blue on the Left');
+%! ylabel (hax(2), 'Green on the Right');
+%! xlabel ('xlabel');
 
 %!demo
 %! clf
-%! x = linspace (-1, 1, 201);
-%! subplot (2, 2, 1)
-%! plotyy (x, sin(pi*x), x, 10*cos(pi*x))
-%! subplot (2, 2, 2)
-%! surf (peaks (25))
-%! subplot (2, 2, 3)
-%! contour (peaks (25))
-%! subplot (2, 2, 4)
-%! plotyy (x, 10*sin(2*pi*x), x, cos(2*pi*x))
-%! axis square
-
-%!demo
-%! clf
-%! x = linspace (-1, 1, 201);
-%! subplot (1, 1, 1);
-%! hax = plotyy (x, sin(pi*x), x, cos(pi*x));
-%! ylabel ("Blue and on the Left")
-%! ylabel (hax(2), "Green and on the Right")
-%! xlabel ("xlabel")
+%! hold on
+%! t = (0:0.1:9);
+%! x = sin (t);
+%! y = 5 * cos (t);
+%! [hax, h1, h2] = plotyy (t, x, t, y);
+%! [~, h3, h4] = plotyy (t+1, x, t+1, y);
+%! set ([h3, h4], "linestyle", "--")
+%! xlabel (hax(1), 'xlabel')
+%! title (hax(2), 'title')
+%! ylabel (hax(1), 'Left axis is Blue')
+%! ylabel (hax(2), 'Right axis is Green')
 
 function deleteplotyy (h, d, ax2, t2)
   if (ishandle (ax2) && strcmp (get (ax2, "type"), "axes")
-      && (isempty (gcbf()) || strcmp (get (gcbf(), "beingdeleted"),"off"))
+      && (isempty (gcbf ()) || strcmp (get (gcbf (), "beingdeleted"),"off"))
       && strcmp (get (ax2, "beingdeleted"), "off"))
     set (t2, "deletefcn", []);
     delete (ax2);
   endif
 endfunction
 
+function update_nextplot (h, d, ax2)
+  persistent recursion = false;
+  prop = "nextplot";
+  if (! recursion)
+    unwind_protect
+      recursion = true;
+      set (ax2, prop, get (h, prop));
+    unwind_protect_cleanup
+      recursion = false;
+    end_unwind_protect
+  endif
+endfunction
+
 function update_position (h, d, ax2)
   persistent recursion = false;
 
--- a/scripts/plot/polar.m
+++ b/scripts/plot/polar.m
@@ -38,7 +38,7 @@
   [h, varargin, nargs] = __plt_get_axis_arg__ ("polar", varargin{:});
 
   if (nargs < 1)
-    print_usage();
+    print_usage ();
   endif
 
   oldh = gca ();
@@ -55,8 +55,8 @@
     elseif (nargs == 2)
       if (ischar (varargin{2}))
         tmp = __plr1__ (h, varargin{:});
-        if (iscomplex(varargin{1}))
-          maxr = max (imag(varargin{1})(:));
+        if (iscomplex (varargin{1}))
+          maxr = max (imag (varargin{1})(:));
         else
           maxr = max (varargin{1}(:));
         endif
@@ -68,8 +68,8 @@
     elseif (nargs == 1)
       fmt = "";
       tmp = __plr1__ (h, varargin{:}, fmt);
-      if (iscomplex(varargin{1}))
-        maxr = max (imag(varargin{1})(:));
+      if (iscomplex (varargin{1}))
+        maxr = max (imag (varargin{1})(:));
       else
         maxr = max (varargin{1}(:));
       endif
@@ -217,14 +217,14 @@
 
 
 %!demo
-%! clf
-%! theta = linspace (0, 2*pi, 1000);
+%! clf;
+%! theta = linspace (0,2*pi,1000);
 %! rho = sin (7*theta);
 %! polar (theta, rho);
 
 %!demo
-%! clf
-%! theta = linspace (0, 10*pi, 1000);
+%! clf;
+%! theta = linspace (0,10*pi,1000);
 %! rho = sin (5/4*theta);
 %! polar (theta, rho);
 
--- a/scripts/plot/print.m
+++ b/scripts/plot/print.m
@@ -21,29 +21,41 @@
 ## @deftypefnx {Function File} {} print (@var{options})
 ## @deftypefnx {Function File} {} print (@var{filename}, @var{options})
 ## @deftypefnx {Function File} {} print (@var{h}, @var{filename}, @var{options})
-## Print a graph, or save it to a file
+## Print a plot, or save it to a file.  Both output formatted for 
+## printing (PDF and PostScript), and many bitmapped and vector
+## image formats are supported.
 ##
-## @var{filename} defines the file name of the output file.  If the
+## @var{filename} defines the name of the output file.  If the
 ## file name has no suffix, one is inferred from the specified
-## device and appended to the file name.  If no
-## filename is specified, the output is sent to the printer.
+## device and appended to the file name.  If no filename is
+## specified, the output is sent to the printer.
 ##
 ## @var{h} specifies the figure handle.  If no handle is specified
 ## the handle for the current figure is used.
 ##
-## @var{options}:
+## For output to a printer, PostScript file, or PDF file,
+## the paper size is specified by the figure's @code{papersize}
+## property.  The location and size of the image on the page are
+## specified by the figure's @code{paperposition} property.  The
+## orientation of the page is specified by the figure's
+## @code{paperorientation} property.
+##
+## The width and height of images are specified by the figure's
+## @code{paperpositon(3:4)} property values.
+##
+## The @code{print} command supports many @var{options}:
 ##
 ## @table @code
 ## @item -f@var{h}
 ##   Specify the handle, @var{h}, of the figure to be printed.  The
-##   default is the current figure.
+## default is the current figure.
 ##
 ## @item -P@var{printer}
-##   Set the @var{printer} name to which the graph is sent if no
-##   @var{filename} is specified.
+##   Set the @var{printer} name to which the plot is sent if no
+## @var{filename} is specified.
 ##
 ## @item -G@var{ghostscript_command}
-##   Specify the command for calling Ghostscript.  For Unix and Windows,
+##   Specify the command for calling Ghostscript.  For Unix and Windows
 ## the defaults are 'gs' and 'gswin32c', respectively.
 ##
 ## @item -color
@@ -52,7 +64,7 @@
 ##
 ## @item -solid
 ## @itemx -dashed
-##   Forces all lines to be solid or dashed, respectively.
+##   Force all lines to be solid or dashed, respectively.
 ##
 ## @item -portrait
 ## @itemx -landscape
@@ -62,15 +74,26 @@
 ## orientation specified.  This options is equivalent to changing
 ## the figure's "paperorientation" property.
 ##
+## @item -TextAlphaBits=@var{n}
+## @itemx -GraphicsAlphaBits=@var{n}
+##   Octave is able to produce output for various printers, bitmaps, and
+## vector formats by using Ghostscript.
+## For bitmap and printer output anti-aliasing is applied using
+## Ghostscript's TextAlphaBits and GraphicsAlphaBits options.
+## The default number of bits for each is 4.
+## Allowed values for @var{N} are 1, 2, or 4.
+##
 ## @item -d@var{device}
-##   Output device, where @var{device} is one of:
+##   The available output format is specified by the option @var{device},
+## and is one of:
+##
 ##   @table @code
 ##   @item ps
 ##   @itemx ps2
 ##   @itemx psc
 ##   @itemx psc2
 ##     Postscript (level 1 and 2, mono and color).  The FLTK graphics
-##     toolkit generates Postscript level 3.0.
+## toolkit generates Postscript level 3.0.
 ##
 ##   @item eps
 ##   @itemx eps2
@@ -85,7 +108,7 @@
 ##   @itemx pstex
 ##   @itemx pslatex
 ##   @itemx pdflatex
-##     Generate a @LaTeX{} (or @TeX{}) file for labels, and eps/ps/pdf
+##     Generate a @LaTeX{} (or @TeX{}) file for labels and eps/ps/pdf
 ## for graphics.  The file produced by @code{epslatexstandalone} can be
 ## processed directly by @LaTeX{}.  The other formats are intended to
 ## be included in a @LaTeX{} (or @TeX{}) document.  The @code{tex} device
@@ -93,8 +116,8 @@
 ## is only available for the FLTK graphics toolkit.
 ##
 ##   @item tikz
-##     Generate a @LaTeX{} file using PGF/TikZ@.  For the FLTK the result is
-##   PGF.
+##     Generate a @LaTeX{} file using PGF/TikZ@.  For the FLTK toolkit
+## the result is PGF.
 ##
 ##   @item ill
 ##   @itemx aifm
@@ -113,9 +136,9 @@
 ##
 ##   @item fig
 ##     XFig.  For the Gnuplot graphics toolkit, the additional options
-##     @option{-textspecial} or @option{-textnormal} can be used to control
-##     whether the special flag should be set for the text in
-##     the figure (default is @option{-textnormal}).
+## @option{-textspecial} or @option{-textnormal} can be used to control
+## whether the special flag should be set for the text in
+## the figure.  (default is @option{-textnormal})
 ##
 ##   @item hpgl
 ##     HP plotter language
@@ -184,53 +207,52 @@
 ## is sent to a file the size is determined by the plot box defined by
 ## the figure's "paperposition" property.
 ##
-## @itemx -append
-##   Appends the PS, or PDF output to a pre-existing file of the
-## same type.
+## @item -append
+##   Append Postscript or PDF output to a pre-existing file of the same type.
 ##
-## @itemx -r@var{NUM}
+## @item -r@var{NUM}
 ##   Resolution of bitmaps in pixels per inch.  For both metafiles and
-## SVG the default is the screen resolution, for other it is 150 dpi.
+## SVG the default is the screen resolution; for other formats it is 150 dpi.
 ## To specify screen resolution, use "-r0".
 ##
 ## @item -tight
-##   Forces a tight bounding box for eps-files.
+##   Force a tight bounding box for eps files.
 ##
 ## @item -@var{preview}
-##   Adds a preview to eps-files.  Supported formats are;
+##   Add a preview to eps files.  Supported formats are:
 ##
 ##   @table @code
 ##   @item -interchange
-##     Provides an interchange preview.
+##     Provide an interchange preview.
 ##
 ##   @item -metalfile
-##     Provides a metafile preview.
+##     Provide a metafile preview.
 ##
 ##   @item -pict
-##     Provides pict preview.
+##     Provide pict preview.
 ##
 ##   @item -tiff
-##     Provides a tiff preview.
+##     Provide a tiff preview.
 ##   @end table
 ##
 ## @item -S@var{xsize},@var{ysize}
-##   Plot size in pixels for EMF, GIF, JPEG, PBM, PNG and SVG@.  For
+##   Plot size in pixels for EMF, GIF, JPEG, PBM, PNG, and SVG@.  For
 ## PS, EPS, PDF, and other vector formats the plot size is in points.
 ## This option is equivalent to changing the size of the plot box
-## associated with "paperposition" property.  Using the command form of
-## the print function, you must quote the @var{xsize},@var{ysize}
-## option.  For example, by writing @w{@code{"-S640,480"}}.
+## associated with the "paperposition" property.  When using the command form
+## of the print function you must quote the @var{xsize},@var{ysize}
+## option.  For example, by writing @w{"-S640,480"}.
 ##
 ## @item -F@var{fontname}
 ## @itemx -F@var{fontname}:@var{size}
 ## @itemx -F:@var{size}
-##   Associates all text with the @var{fontname} and/or @var{fontsize}.
-## @var{fontname} is ignored for some devices; dxf, fig, hpgl, etc.
+##   Use @var{fontname} and/or @var{fontsize} for all text.
+## @var{fontname} is ignored for some devices: dxf, fig, hpgl, etc.
 ## @end table
 ##
 ## The filename and options can be given in any order.
 ##
-## Example: Print to a file, using the svg device.
+## Example: Print to a file using the svg device.
 ##
 ## @example
 ## @group
@@ -283,26 +305,34 @@
     ## Modify properties as specified by options
     props = [];
 
+    drawnow ();
+
+    ## print() requires figure units to be "pixels"
+    props(1).h = opts.figure;
+    props(1).name = "units";
+    props(1).value = {get(opts.figure, "units")};
+    set (opts.figure, "units", "pixels");
+
     ## graphics toolkit tranlates figure position to eps bbox in points
     fpos = get (opts.figure, "position");
-    props(1).h = opts.figure;
-    props(1).name = "position";
-    props(1).value = {fpos};
+    props(2).h = opts.figure;
+    props(2).name = "position";
+    props(2).value = {fpos};
     fpos(3:4) = opts.canvas_size;
     set (opts.figure, "position", fpos);
 
     ## Set figure background to none. This is done both for
     ## consistency with Matlab and to elliminate the visible
     ## box along the figure's perimeter.
-    props(2).h = opts.figure;
-    props(2).name = "color";
-    props(2).value{1} = get (props(2).h, props(2).name);
-    set (props(2).h, props(2).name, "none");
+    props(3).h = opts.figure;
+    props(3).name = "color";
+    props(3).value{1} = get (props(3).h, props(3).name);
+    set (props(3).h, "color", "none");
 
     if (opts.force_solid != 0)
       h = findall (opts.figure, "-property", "linestyle");
       m = numel (props);
-      for n = 1:numel(h)
+      for n = 1:numel (h)
         props(m+n).h = h(n);
         props(m+n).name = "linestyle";
         props(m+n).value = {get(h(n), "linestyle")};
@@ -318,12 +348,12 @@
     if (opts.use_color < 0
         && ! strcmp (get (opts.figure, "__graphics_toolkit__"), "gnuplot"))
       color_props = {"color", "facecolor", "edgecolor", "colormap"};
-      for c = 1:numel(color_props)
+      for c = 1:numel (color_props)
         h = findall (opts.figure, "-property", color_props{c});
         hnone = findall (opts.figure, color_props{c}, "none");
         h = setdiff (h, hnone);
         m = numel (props);
-        for n = 1:numel(h)
+        for n = 1:numel (h)
           if (ishandle (h(n)))
             ## Need to verify objects exist since callbacks may delete objects
             ## as the colors for others are modified.
@@ -333,7 +363,7 @@
             props(end).value = {get(h(n), color_props{c})};
             if (isnumeric (rgb))
               ## convert RGB color to RGB gray scale
-              xfer = repmat ([0.30, 0.59, 0.11], size (rgb, 1), 1);
+              xfer = repmat ([0.30, 0.59, 0.11], rows (rgb), 1);
               ggg = repmat (sum (xfer .* rgb, 2), 1, 3);
               set (h(n), color_props{c}, ggg);
             endif
@@ -345,7 +375,7 @@
     if (! isempty (opts.font) || ! isempty (opts.fontsize))
       h = findall (opts.figure, "-property", "fontname");
       m = numel (props);
-      for n = 1:numel(h)
+      for n = 1:numel (h)
         if (ishandle (h(n)))
           if (! isempty (opts.font))
             props(end+1).h = h(n);
@@ -362,7 +392,7 @@
         endif
       endfor
       if (! isempty (opts.font))
-        set (h(ishandle(h)), "fontname", opts.font);
+        set (h(ishandle (h)), "fontname", opts.font);
       endif
       if (! isempty (opts.fontsize))
         if (ischar (opts.fontsize))
@@ -370,7 +400,11 @@
         else
           fontsize = opts.fontsize;
         endif
-        set (h(ishandle(h)), "fontsize", fontsize);
+        if (! isempty (opts.scalefontsize) && ! opts.scalefontsize != 1)
+          ## This is done to work around the bbox being whole numbers.
+          fontsize = fontsize * opts.scalefontsize;
+        endif
+        set (h(ishandle (h)), "fontsize", fontsize);
       endif
     endif
 
@@ -385,7 +419,7 @@
   unwind_protect_cleanup
     ## restore modified properties
     if (isstruct (props))
-      for n = 1:numel(props)
+      for n = numel (props):-1:1
         if (ishandle (props(n).h))
           set (props(n).h, props(n).name, props(n).value{1});
         endif
@@ -393,7 +427,7 @@
     endif
 
     ## Unlink temporary files
-    for n = 1:numel(opts.unlink)
+    for n = 1:numel (opts.unlink)
       [status, output] = unlink (opts.unlink{n});
       if (status != 0)
         warning ("print.m: %s, '%s'", output, opts.unlink{n});
new file mode 100644
--- /dev/null
+++ b/scripts/plot/printd.m
@@ -0,0 +1,115 @@
+## Copyright (C) 2013 Michael D. Godfrey
+##
+## 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} {} printd (@var{obj}, @var{filename})
+## @deftypefnx {Function File} {@var{out_file} =} printd (@dots{})
+##
+## Convert any object acceptable to @code{disp} into the format
+## selected by the suffix of @var{filename}.  If the return argument
+## @var{out_file} is given, the name of the created file is returned.
+##
+## This function is intended to facilitate manipulation of the output
+## of functions such as @code{stemleaf}.
+## @seealso{stemleaf}
+## @end deftypefn
+
+## Author: Michael D. Godfrey <michaeldgodfrey@gmail.com>
+## Description: Convert objects into other file formats.
+
+function pr_out = printd (obj, filename)
+  ## Convert any object acceptable to disp() into various display formats.
+  ## obj is the input object.
+  ## filename is the output file (with required suffix).
+
+  ## Extract .suffix from filename
+  if ((sufix = rindex (filename, ".")) <= 0)
+    error ("The output filename: %s requires a suffix.\nOptions are: pdf ps eps txt jpg jpeg", filename);
+  endif
+  opt = substr (filename, sufix+1);
+  [pf, tempf, mag] = mkstemp ("oct-XXXXXX", 1);  # Safe version of tmpnam()
+  fprintf (pf, "%s", disp (obj));
+  frewind (pf);
+
+  ## It seems best to only use convert for image output.  Its ps and pdf
+  ## are badly rendered.
+  opt = lower (opt);
+  switch opt
+    case {"pdf"}
+      enscr = sprintf (
+                       "enscript --no-header -o %s.ps %s ; ps2pdf %s.ps %s.pdf; mv %s.pdf %s;exit",...
+                       tempf, tempf, tempf, tempf, tempf, filename);
+      system (enscr);
+      delete ([tempf ".ps"]);
+    case {"ps"}
+      enscr = sprintf ("enscript --no-header -o %s %s ; exit", filename, tempf);
+      system (enscr);
+    case {"eps"}
+      enscr = sprintf (
+                       "enscript --no-header -o %s.ps %s ; ps2eps --ignoreBB %s.ps; mv %s.eps %s; exit",...
+                       tempf, tempf, tempf, tempf, filename);
+      system (enscr);
+      delete ([tempf ".ps"]);
+    case {"txt"}
+      enscr = sprintf ("cp %s %s", tempf, filename);
+      system (enscr);
+    case {"jpg" "jpeg"}
+      enscr = sprintf ("convert -trim txt:%s  jpg:%s", tempf, filename);
+      system (enscr);
+    otherwise
+      fclose (pf);
+      delete (tempf);
+      error ("Unknown conversion type: %s.\nOptions are: pdf ps eps txt jpg jpeg", opt);
+
+  endswitch
+  fclose (pf);
+  delete (tempf);
+  pr_out =  sprintf ("%s file %s written\n", opt, filename);
+endfunction
+
+%!demo
+%! r2 = char (
+%! "stem step: 10, data: unsorted.",
+%! "Hinges:    lo: 12, hi: 42"     ,
+%! "   1 | 22118"                  ,
+%! "   2 | 28"                     ,
+%! "   3 | 98"                     ,
+%! "   4 | 244"                    ,
+%! "   5 | 2"                      );
+%! printd (r2, "test_p.txt");
+%! system ("cat test_p.txt");
+%! delete ("test_p.txt");
+
+%!test
+%! r2 = char (
+%! "stem step: 10, data: unsorted.",
+%! "Hinges:    lo: 12, hi: 42"     ,
+%! "   1 | 22118"                  ,
+%! "   2 | 28"                     ,
+%! "   3 | 98"                     ,
+%! "   4 | 244"                    ,
+%! "   5 | 2"                      );
+%! printd (r2, "test_p.txt");
+%! r4 = fileread ("test_p.txt");
+%! delete ("test_p.txt");
+%! r2 = disp (r2);
+%! assert (r4, r2)
+
+
--- a/scripts/plot/private/__add_datasource__.m
+++ b/scripts/plot/private/__add_datasource__.m
@@ -39,7 +39,7 @@
   newargs = {};
   while (i < numel (varargin))
     arg = varargin{++i};
-    if (i != numel(varargin) && ischar (arg)
+    if (i != numel (varargin) && ischar (arg)
         && length (arg) > 9 && strcmpi (arg(end-9:end), "datasource"))
       arg = tolower (arg);
       val = varargin{++i};
--- a/scripts/plot/private/__add_default_menu__.m
+++ b/scripts/plot/private/__add_default_menu__.m
@@ -98,12 +98,12 @@
 endfunction
 
 function guimode_cb (h, e)
-  lbl = get(h, "label");
-  if (strncmp(lbl, "Pan+Zoom", 8))
-    gui_mode("2D");
-  elseif (strncmp(lbl, "Rotate+Zoom", 11))
-    gui_mode("3D");
-  elseif (strncmp(lbl, "None", 4))
-    gui_mode("None");
+  lbl = get (h, "label");
+  if (strncmp (lbl, "Pan+Zoom", 8))
+    gui_mode ("2D");
+  elseif (strncmp (lbl, "Rotate+Zoom", 11))
+    gui_mode ("3D");
+  elseif (strncmp (lbl, "None", 4))
+    gui_mode ("None");
   endif
 endfunction
--- a/scripts/plot/private/__axes_limits__.m
+++ b/scripts/plot/private/__axes_limits__.m
@@ -41,7 +41,7 @@
         set (h, fcnmode, arg);
       endif
     else
-      if (!isnumeric (arg) && any (size(arg(:)) != [2, 1]))
+      if (!isnumeric (arg) && any (size (arg(:)) != [2, 1]))
         error ("%s: argument must be a 2 element vector", fcn);
       else
         if (arg(1) >= arg(2))
--- a/scripts/plot/private/__bar__.m
+++ b/scripts/plot/private/__bar__.m
@@ -45,12 +45,12 @@
     if (isvector (y))
       y = y(:);
     endif
-    if (size (x, 1) != size (y, 1))
+    if (rows (x) != rows (y))
       y = varargin{1};
       if (isvector (y))
         y = y(:);
       endif
-      x = [1:size(y,1)]';
+      x = [1:rows(y)]';
       idx = 2;
     else
       if (! isvector (x))
@@ -63,7 +63,7 @@
     if (isvector (y))
       y = y(:);
     endif
-    x = [1:size(y,1)]';
+    x = [1:rows(y)]';
     idx = 2;
   endif
 
@@ -82,12 +82,14 @@
         [linespec, valid] = __pltopt__ (func, varargin{idx}, false);
         if (valid)
           have_line_spec = true;
-          newargs = [{"facecolor", linespec.color}, newargs]
+          ## FIXME: strange parse error requires semicolon to be spaced
+          ##        away from closing ']' on next line.
+          newargs = [{"facecolor", linespec.color}, newargs] ;
           idx++;
           continue;
         endif
       endif
-      if (isscalar(varargin{idx}))
+      if (isscalar (varargin{idx}))
         width = varargin{idx++};
       elseif (idx == nargin - 2)
         newargs = [newargs,varargin(idx++)];
@@ -103,8 +105,8 @@
     endif
   endwhile
 
-  xlen = size (x, 1);
-  ylen = size (y, 1);
+  xlen = rows (x);
+  ylen = rows (y);
 
   if (xlen != ylen)
     error ("%s: length of x and y must be equal", func);
@@ -113,9 +115,9 @@
     error ("%s: x vector values must be in ascending order", func);
   endif
 
-  ycols = size (y, 2);
+  ycols = columns (y);
   if (numel (x) > 1)
-    cutoff = min (diff (double(x))) / 2;
+    cutoff = min (diff (double (x))) / 2;
   else
     cutoff = 1;
   endif
@@ -137,7 +139,7 @@
     y0 = zeros (size (y)) + bv;
     y1 = y;
   else
-    y1 = cumsum(y,2);
+    y1 = cumsum (y,2);
     y0 = [zeros(ylen,1)+bv, y1(:,1:end-1)];
   endif
 
@@ -194,10 +196,10 @@
         else
           lev = (i - 1) * (clim(2) - clim(1)) / (ycols - 1) - clim(1);
         endif
-        h = patch(xb(:,:,i), yb(:,:,i), "FaceColor", "flat",
-                  "cdata", lev, "parent", hg);
+        h = patch (xb(:,:,i), yb(:,:,i), "FaceColor", "flat",
+                   "cdata", lev, "parent", hg);
       else
-        h = patch(xb(:,:,i), yb(:,:,i), "parent", hg);
+        h = patch (xb(:,:,i), yb(:,:,i), "parent", hg);
       endif
     else
       if (! have_color_spec)
@@ -206,16 +208,17 @@
         else
           lev = (i - 1) * (clim(2) - clim(1)) / (ycols - 1) - clim(1);
         endif
-        h = patch(yb(:,:,i), xb(:,:,i), "FaceColor", "flat",
-                  "cdata", lev, "parent", hg);
+        h = patch (yb(:,:,i), xb(:,:,i), "FaceColor", "flat",
+                   "cdata", lev, "parent", hg);
       else
-        h = patch(yb(:,:,i), xb(:,:,i), "parent", hg);
+        h = patch (yb(:,:,i), xb(:,:,i), "parent", hg);
       endif
     endif
 
     if (i == 1)
       x_axis_range = get (ax, "xlim");
-      h_baseline = line (x_axis_range, [0, 0], "color", [0, 0, 0]);
+      h_baseline = line (x_axis_range, [base_value, base_value],
+                         "color", [0, 0, 0]);
       set (h_baseline, "handlevisibility", "off");
       set (h_baseline, "xliminclude", "off");
       addlistener (ax, "xlim", @update_xlim);
@@ -228,7 +231,8 @@
     addproperty ("basevalue", hg, "data", base_value);
     addproperty ("baseline", hg, "data", h_baseline);
 
-    addlistener (hg, "showbaseline", @show_baseline);
+    addlistener (hg, "showbaseline", {@show_baseline, "showbl"});
+    addlistener (hg, "visible", {@show_baseline, "visib"});
     addlistener (hg, "basevalue", @move_baseline);
 
     addproperty ("barwidth", hg, "data", width);
@@ -314,20 +318,27 @@
   endfor
 endfunction
 
-function show_baseline (h, d)
+function show_baseline (h, d, prop = "")
   persistent recursion = false;
-
+  
   ## Don't allow recursion
   if (! recursion)
     unwind_protect
       recursion = true;
       hlist = get (h, "bargroup");
-      showbaseline = get (h, "showbaseline");
-      for hh = hlist(:)'
-        if (hh != h)
-          set (hh, "showbaseline", showbaseline);
+      if (strcmp (prop, "showbl"))
+        showbaseline = get (h, "showbaseline");
+        for hh = hlist(:)'
+          if (hh != h)
+            set (hh, "showbaseline", showbaseline);
+          endif
+        endfor
+      elseif (strcmp (prop, "visib"))
+        showbaseline = "on";
+        if (all (strcmp (get (hlist, "visible"), "off")))
+          showbaseline = "off";
         endif
-      endfor
+      endif
       set (get (h, "baseline"), "visible", showbaseline);
     unwind_protect_cleanup
       recursion = false;
@@ -401,7 +412,7 @@
     unwind_protect
       recursion = true;
       hlist = get (h, "bargroup");
-      barwidth = get(h, "barwidth");
+      barwidth = get (h, "barwidth");
       barlayout = get (h, "barlayout");
       horizontal = get (h, "horizontal");
 
--- a/scripts/plot/private/__clabel__.m
+++ b/scripts/plot/private/__clabel__.m
@@ -25,10 +25,10 @@
   ## FIXME
   ## Assume that the plot size is 4 by 3 inches.
   lims = axis ();
-  xspacing = 72 * 4 / abs(lims(1) - lims(2));
-  yspacing = 72 * 3 / abs(lims(3) - lims(4));
+  xspacing = 72 * 4 / abs (lims(1) - lims(2));
+  yspacing = 72 * 3 / abs (lims(3) - lims(4));
 
-  if (isscalar (hparent) && ishandle(hparent)
+  if (isscalar (hparent) && ishandle (hparent)
       && strcmp (get (hparent, "type"), "hggroup"))
     x = get (hparent, "xdata");
     xmin = min (x(:));
@@ -67,14 +67,14 @@
     p = c(:, i1+1:i1+clen) .* repmat ([xspacing; yspacing], 1, clen);
     d = sqrt (sumsq (diff (p, 1, 2)));
     cumd = cumsum (d);
-    td = sum(d);
+    td = sum (d);
     ntag = ceil (td / label_spacing);
 
     if (all (c(:,i1+1) == c(:,i1+clen)))
       Spacing = td / ntag;
       pos = Spacing / 2 + [0:ntag-1] * Spacing;
     else
-      pos = zeros(1, ntag);
+      pos = zeros (1, ntag);
       pos(1) = (td - label_spacing * (ntag - 1)) ./ 2;
       pos(2:ntag) = pos(1) + [1:ntag-1] * label_spacing;
     endif
@@ -87,7 +87,7 @@
       while (j1 < clen && cumd(j1) < tagpos)
         j1++;
       endwhile
-      tpos = sum(c(:,i1+j1-1:i1+j1), 2) ./ 2;
+      tpos = sum (c(:,i1+j1-1:i1+j1), 2) ./ 2;
 
       if (tpos(1) != xmin &&  tpos(1) != xmax
           && tpos(2) != ymin &&  tpos(2) != ymax)
@@ -112,4 +112,4 @@
     endfor
     i1 += clen+1;
   endwhile
-endfunction
\ No newline at end of file
+endfunction
--- a/scripts/plot/private/__contour__.m
+++ b/scripts/plot/private/__contour__.m
@@ -79,10 +79,10 @@
     endif
   endwhile
 
-  if (length(varargin) < 5)
+  if (length (varargin) < 5)
     z1 = varargin{3};
-    x1 = 1 : columns(z1);
-    y1 = 1 : rows(z1);
+    x1 = 1 : columns (z1);
+    y1 = 1 : rows (z1);
   else
     x1 = varargin{3};
     y1 = varargin{4};
@@ -100,7 +100,7 @@
   endif
 
   if (isscalar (vn))
-    lvl = linspace (min (z1(!isinf(z1))), max (z1(!isinf(z1))),
+    lvl = linspace (min (z1(!isinf (z1))), max (z1(!isinf (z1))),
                     vn + 2)(1:end-1);
   else
     lvl = vn;
@@ -111,13 +111,13 @@
       [x1, y1] = meshgrid (x1, y1);
     endif
     [nr, nc] = size (z1);
-    x0 = prepad(x1, nc+1, 2 * x1(1, 1) - x1(1, 2), 2);
-    x0 = postpad(x0, nc+2, 2 * x1(1, nc) - x1(1, nc - 1), 2);
+    x0 = prepad (x1, nc+1, 2 * x1(1, 1) - x1(1, 2), 2);
+    x0 = postpad (x0, nc+2, 2 * x1(1, nc) - x1(1, nc - 1), 2);
     x0 = [x0(1, :); x0; x0(1, :)];
-    y0 = prepad(y1, nr+1, 2 * y1(1, 1) - y1(2, 1), 1);
-    y0 = postpad(y0, nr+2, 2 * y1(nr, 1) - y1(nr - 1, 1));
+    y0 = prepad (y1, nr+1, 2 * y1(1, 1) - y1(2, 1), 1);
+    y0 = postpad (y0, nr+2, 2 * y1(nr, 1) - y1(nr - 1, 1));
     y0 = [y0(:, 1), y0, y0(:, 1)];
-    z0 = -Inf(nr+2, nc+2);
+    z0 = -Inf (nr+2, nc+2);
     z0(2:nr+1, 2:nc+1) = z1;
     [c, lev] = contourc (x0, y0, z0, lvl);
   else
@@ -211,7 +211,7 @@
 
   add_patch_children (hg);
 
-  axis("tight");
+  axis ("tight");
 
   if (!isempty (opts))
     set (hg, opts{:});
@@ -241,6 +241,8 @@
     ## Decode contourc output format.
     i1 = 1;
     ncont = 0;
+    cont_lev = [];
+    cont_area = [];
     while (i1 < columns (c))
       ncont++;
       cont_lev(ncont) = c(1, i1);
@@ -258,7 +260,7 @@
       lvl_idx = find (abs (cont_lev - lev(k)) < lvl_eps);
       len = numel (lvl_idx);
       if (len > 1)
-        ## mark = logical(zeros(size(lvl_idx)));
+        ## mark = logical (zeros (size (lvl_idx)));
         mark = false (size (lvl_idx));
         a = 1;
         while (a < len)
@@ -283,7 +285,7 @@
           ma_idx = lvl_idx(mark);
           if (k > 1)
             ## Find color of level below.
-            tmp = find(abs(cont_lev - lev(k - 1)) < lvl_eps);
+            tmp = find (abs (cont_lev - lev(k - 1)) < lvl_eps);
             lvl_bel_idx = tmp(1);
             ## Set color of patches found.
             cont_lev(ma_idx) = cont_lev(lvl_bel_idx);
@@ -319,7 +321,7 @@
       else
         ## Special case unclosed contours
       endif
-      if (isnan(cont_lev(idx)))
+      if (isnan (cont_lev (idx)))
         fc = get (ca, "color");
         if (strcmp (fc, "none"))
           fc = get (ancestor (ca, "figure"), "color");
@@ -458,13 +460,13 @@
         [X, Y] = meshgrid (X, Y);
       endif
       [nr, nc] = size (Z);
-      X0 = prepad(X, nc+1, 2 * X(1, 1) - X(1, 2), 2);
-      X0 = postpad(X0, nc+2, 2 * X(1, nc) - X(1, nc - 1), 2);
+      X0 = prepad (X, nc+1, 2 * X(1, 1) - X(1, 2), 2);
+      X0 = postpad (X0, nc+2, 2 * X(1, nc) - X(1, nc - 1), 2);
       X0 = [X0(1, :); X0; X0(1, :)];
-      Y0 = prepad(Y, nr+1, 2 * Y(1, 1) - Y(2, 1), 1);
-      Y0 = postpad(Y0, nr+2, 2 * Y(nr, 1) - Y(nr - 1, 1));
+      Y0 = prepad (Y, nr+1, 2 * Y(1, 1) - Y(2, 1), 1);
+      Y0 = postpad (Y0, nr+2, 2 * Y(nr, 1) - Y(nr - 1, 1));
       Y0 = [Y0(:, 1), Y0, Y0(:, 1)];
-      Z0 = -Inf(nr+2, nc+2);
+      Z0 = -Inf (nr+2, nc+2);
       Z0(2:nr+1, 2:nc+1) = Z;
       [c, lev] = contourc (X0, Y0, Z0, lvl);
     else
@@ -480,7 +482,7 @@
     else
       set (h, "levellist", lev);
       z = get (h, "zdata");
-      lvlstep = (max(z(:)) - min(z(:))) / 10;
+      lvlstep = (max (z(:)) - min (z(:))) / 10;
       set (h, "levelstep", lvlstep);
     endif
 
--- a/scripts/plot/private/__errcomm__.m
+++ b/scripts/plot/private/__errcomm__.m
@@ -34,7 +34,7 @@
   nargs = length (varargin);
   retval = [];
   k = 1;
-  data = cell(6,1);
+  data = cell (6,1);
   while (k <= nargs)
     a = varargin{k++};
     if (isvector (a))
--- a/scripts/plot/private/__errplot__.m
+++ b/scripts/plot/private/__errplot__.m
@@ -71,7 +71,7 @@
           (__line__ (hg, "linestyle", "-", "marker", "none",
                    "color", fmt.color))];
 
-    switch (numel(varargin))
+    switch (numel (varargin))
       case 2
         ydata = varargin{1}(:,i);
         xdata = 1:numel (ydata);
@@ -196,7 +196,7 @@
   ## Process legend key
   if (! isempty (fmt.key))    
     hlegend = [];
-    fkids = get (gcf(), "children");
+    fkids = get (gcf (), "children");
     for i = 1 : numel (fkids)
       if (ishandle (fkids(i)) && strcmp (get (fkids(i), "type"), "axes")
           && (strcmp (get (fkids(i), "tag"), "legend")))
@@ -218,8 +218,8 @@
     hlgnd(end+1) = hg;
     tlgnd(end+1) = fmt.key;
 
-    legend (gca(), hlgnd, tlgnd);
-  end 
+    legend (gca (), hlgnd, tlgnd);
+  endif
 
 endfunction
 
@@ -232,7 +232,7 @@
     xhi = xdata + dx;
   else
     n = xdata > 0;
-    rx = exp(0.01 * (max (log(xdata(n))) - min (log(xdata(n)))));
+    rx = exp (0.01 * (max (log (xdata(n))) - min (log (xdata(n)))));
     xlo = xdata/rx;
     xhi = xdata*rx;
   endif
@@ -242,7 +242,7 @@
     yhi = ydata + dy;
   else
     n = ydata > 0;
-    ry = exp(0.01 * (max (log(ydata(n))) - min (log(ydata(n)))));
+    ry = exp (0.01 * (max (log (ydata(n))) - min (log (ydata(n)))));
     ylo = ydata/ry;
     yhi = ydata*ry;
   endif
--- a/scripts/plot/private/__ezplot__.m
+++ b/scripts/plot/private/__ezplot__.m
@@ -74,9 +74,9 @@
     endif
     fstr = formula (fun);
     if (isplot)
-      xarg = argnames(fun){1};
+      xarg = (argnames (fun)){1};
       if (nargs == 2)
-        yarg = argnames(fun){2};
+        yarg = (argnames (fun)){2};
       else
         yarg = "";
       endif
@@ -87,8 +87,8 @@
       xarg = "";
       yarg = "";
     else
-      xarg = argnames(fun){1};
-      yarg = argnames(fun){2};
+      xarg = (argnames (fun)){1};
+      yarg = (argnames (fun)){2};
     endif
   elseif (strcmp (typeinfo (fun), "inline function"))
     if (isplot && length (argnames (fun)) == 2)
@@ -99,9 +99,9 @@
     fun = vectorize (fun);
     fstr = formula (fun);
     if (isplot)
-      xarg = argnames(fun){1};
+      xarg = (argnames (fun)){1};
       if (nargs == 2)
-        yarg = argnames(fun){2};
+        yarg = (argnames (fun)){2};
       else
         yarg = "";
       endif
@@ -112,15 +112,15 @@
       xarg = "";
       yarg = "";
     else
-      xarg = argnames(fun)(1);
-      yarg = argnames(fun)(2);
+      xarg = (argnames (fun))(1);
+      yarg = (argnames (fun))(2);
     endif
   elseif (isa (fun, "function_handle"))
     fstr = func2str (fun);
-    if (length (findstr (fstr, ")")) != 0)
-      args = regexp (substr (fstr, 3, findstr (fstr, ")")(1) - 3),
+    if (! isempty (strfind (fstr, ')')))
+      args = regexp (substr (fstr, 3, strfind (fstr, ')')(1) - 3),
                      '(\w+)', 'tokens');
-    fstr = substr (fstr, findstr (fstr, ")")(1) + 1);
+    fstr = substr (fstr, strfind (fstr, ')')(1) + 1);
     else
       args = {{"x"}};
     endif
@@ -175,10 +175,10 @@
     elseif (isa (funy, "function_handle"))
       parametric = true;
       fstry = func2str (funy);
-      if (length (findstr (fstry, ")")) != 0)
-        args = regexp (substr (fstry, 3, findstr (fstry, ")")(1) - 3),
+      if (! isempty (strfind (fstry, ')')))
+        args = regexp (substr (fstry, 3, strfind (fstry, ')')(1) - 3),
                        '(\w+)', 'tokens');
-        fstry = substr (fstry, findstr (fstry, ")")(1) + 1);
+        fstry = substr (fstry, strfind (fstry, ')')(1) + 1);
       else
         args = {{"y"}};
       endif
@@ -216,12 +216,12 @@
         fstrz = formula (funz);
       elseif (isa (funz, "function_handle"))
         fstrz = func2str (funz);
-        args = regexp (substr (fstrz, 3, findstr (fstrz, ")")(1) - 3),
+        args = regexp (substr (fstrz, 3, strfind (fstrz, ')')(1) - 3),
                        '(\w+)', 'tokens');
         if (length (args) != nargs)
           error ("%s: excepting a function of %d arguments", func, nargs);
         endif
-        fstrz = substr (fstrz, findstr (fstrz, ")")(1) + 1);
+        fstrz = substr (fstrz, strfind (fstrz, ')')(1) + 1);
       else
         error ("%s: parametric plots expect 3 functions", func);
       endif
@@ -392,10 +392,10 @@
           yrange = [XX(1), XX(end)];
         endif
 
-        idx = 2 : length(Z);
+        idx = 2 : length (Z);
         idx = find (((Z(idx) > yrange(2) / 2) & (Z(idx-1) < yrange(1) / 2)) |
                  ((Z(idx) < yrange(1) / 2) & (Z(idx-1) > yrange (2) / 2)));
-        if (any(idx))
+        if (any (idx))
           Z(idx) = NaN;
         endif
       else
@@ -441,5 +441,5 @@
 
 function x = __eliminate_sing__ (x)
   x (isinf (x)) = NaN;
-  x (abs (del2 (x)) > 0.2 * (max(x(:)) - min(x(:)))) = NaN;
+  x (abs (del2 (x)) > 0.2 * (max (x(:)) - min (x(:)))) = NaN;
 endfunction
--- a/scripts/plot/private/__file_filter__.m
+++ b/scripts/plot/private/__file_filter__.m
@@ -81,7 +81,7 @@
   endswitch
 
   if (isempty (name))
-    extlist = strsplit(filterext, ";");
+    extlist = strsplit (filterext, ";", false);
     extlist = strrep (extlist, "*.", "");
     extlist = toupper (extlist);
     extlist(end+1, :) = repmat ({","}, 1, length (extlist));
--- a/scripts/plot/private/__fltk_file_filter__.m
+++ b/scripts/plot/private/__fltk_file_filter__.m
@@ -34,7 +34,7 @@
   for idx = 1 : r
 
     curr_ext = file_filter{idx, 1};
-    curr_ext = strsplit (curr_ext, ";");
+    curr_ext = strsplit (curr_ext, ";", false);
 
     if (length (curr_ext) > 1)
       curr_ext = regexprep (curr_ext, '\*\.', ',');
--- a/scripts/plot/private/__fltk_print__.m
+++ b/scripts/plot/private/__fltk_print__.m
@@ -125,9 +125,9 @@
     [cmd_gs, cmd_cleanup] = __ghostscript__ (opts.ghostscript);
     if (opts.send_to_printer || isempty (opts.name))
       cmd_lpr = opts.lpr_cmd (opts);
-      cmd = sprintf("%s | %s", cmd_gs, cmd_lpr);
+      cmd = sprintf ("%s | %s", cmd_gs, cmd_lpr);
     else
-      cmd = sprintf("%s", cmd_gs);
+      cmd = sprintf ("%s", cmd_gs);
     endif
     if (! isempty (cmd_cleanup))
       gl2ps_device = {"eps"};
@@ -148,11 +148,22 @@
 
   opts.pipeline = pipeline;
 
-  for n = 1:numel(pipeline)
+  ## Tell gl2ps to use different rendering options for 2D plots
+  haxes = findall (opts.figure, "type", "axes");
+  vw = get (haxes, "view");
+  if (iscell (vw))
+    vw = vertcat (vw{:});
+  endif
+  is2D = all (abs (vw(:,2)) == 90);
+  if (is2D)
+    gl2ps_device{end} = [gl2ps_device{end}, "is2D"];
+  endif
+
+  for n = 1:numel (pipeline)
     if (opts.debug)
       fprintf ("fltk-pipeline: '%s'\n", pipeline{n});
     endif
-    drawnow (gl2ps_device{n}, strcat('|',pipeline{n}));
+    drawnow (gl2ps_device{n}, strcat ('|',pipeline{n}));
   endfor
 
   if (! isempty (strfind (opts.devopt, "standalone")))
--- a/scripts/plot/private/__ghostscript__.m
+++ b/scripts/plot/private/__ghostscript__.m
@@ -32,6 +32,8 @@
   opts.device = "";
   opts.epscrop = false;
   opts.antialiasing  = false;
+  opts.antialiasing_textalphabits = 4;,
+  opts.antialiasing_graphicsalphabits = 4;
   opts.resolution = 150;
   opts.papersize = "";
   opts.pageoffset = [0 0];
@@ -47,12 +49,12 @@
   n = find (cellfun ("isclass", args, "struct"));
   if (! isempty (n))
     f = fieldnames (args{n});
-    for m = 1:numel(f)
+    for m = 1:numel (f)
       opts.(f{m}) = args{n}.(f{m});
     endfor
     args(n) = [];
   endif
-  for n = 1:2:numel(args)
+  for n = 1:2:numel (args)
     opts.(args{n}) = args{n+1};
   endfor
 
@@ -70,7 +72,9 @@
 
   if (opts.antialiasing && isempty (strfind (opts.device, "write")))
     ## Apply anti-aliasing to all bitmap formats/devices
-    gs_opts = sprintf ("%s -dTextAlphaBits=4 -dGraphicsAlphaBits=4", gs_opts);
+    gs_opts = sprintf ("%s -dTextAlphaBits=%d -dGraphicsAlphaBits=%d",
+                       gs_opts, opts.antialiasing_textalphabits,
+                       opts.antialiasing_graphicsalphabits);
     gs_opts = sprintf ("%s -r%dx%d", gs_opts, [1, 1] * opts.resolution);
   elseif (any (strcmp (opts.device, {"pswrite", "ps2write", "pdfwrite"})))
     gs_opts = sprintf ("%s -dEmbedAllFonts=true", gs_opts);
@@ -114,13 +118,13 @@
     unwind_protect
       fid = fopen (offsetfile, "w");
       if (fid == -1)
-        error ("print:fopenfailed", "__ghostscript__.m: fopen() failed");
+        error ("print:fopenfailed", "__ghostscript__.m: fopen () failed");
       endif
       fprintf (fid, "%s\n", offset_ps{:});
     unwind_protect_cleanup
       status = fclose (fid);
       if (status == -1)
-        error ("print:fclosefailed", "__ghostscript__.m: fclose() failed");
+        error ("print:fclosefailed", "__ghostscript__.m: fclose () failed");
       endif
     end_unwind_protect
     if (opts.debug)
@@ -135,7 +139,7 @@
   elseif (isempty (opts.output))
     cmd = sprintf ("%s %s", opts.binary, gs_opts);
   else
-    cmd = sprintf ("%s %s -sOutputFile=%s", opts.binary, gs_opts, opts.output);
+    cmd = sprintf ("%s %s -sOutputFile=\"%s\"", opts.binary, gs_opts, opts.output);
   endif
   if (! isempty (opts.prepend)
       && any (strcmpi (opts.device, {"pswrite", "ps2write", "pdfwrite"})))
--- a/scripts/plot/private/__gnuplot_get_var__.m
+++ b/scripts/plot/private/__gnuplot_get_var__.m
@@ -24,17 +24,11 @@
 ## Author: Ben Abbott <bpabbott@mac.com>
 ## Created: 2009-02-07
 
-function gp_var_value = __gnuplot_get_var__ (h, gp_var_name, fmt)
+function gp_var_value = __gnuplot_get_var__ (h, gp_var_name, fmt = "")
 
-  if (nargin == 0)
-    h = gcf ();
-  endif
   if (nargin < 2)
     print_usage ();
   endif
-  if (nargin < 3)
-    fmt = '';
-  endif
 
   if (numel (h) == 1 && isfigure (h))
     if (isempty (get (gcf, "__plot_stream__")))
@@ -65,8 +59,8 @@
     ## Mode: 6*8*8 ==  0600
     [err, msg] = mkfifo (gpin_name, 6*8*8);
 
-    if (err != 0)
-      error ("__gnuplot_get_var__: Can not make fifo (%s)", msg);
+    if (err)
+      error ("__gnuplot_get_var__: Can not make FIFO (%s)", msg);
     endif
   endif
 
@@ -79,18 +73,18 @@
   unwind_protect
 
     ## Notes: Variables may be undefined if user closes gnuplot by "q"
-    ## or Alt-F4. Further, this abrupt close also requires the leading
+    ## or Alt-F4.  Further, this abrupt close also requires the leading
     ## "\n" on the next line.
     if (use_mkfifo)
       fprintf (ostream, "\nset print \"%s\";\n", gpin_name);
       fflush (ostream);
       [gpin, err] = fopen (gpin_name, "r");
-      if (err != 0)
+      if (err)
         ## Try a second time, and then give an error.
         [gpin, err] = fopen (gpin_name, "r");
       endif
-      if (err != 0)
-        error ("__gnuplot_get_var__: can not open fifo");
+      if (err)
+        error ("__gnuplot_get_var__: can not open FIFO");
       endif
       gp_cmd = sprintf ("\nif (exists(\"%s\")) print %s; else print NaN\n",
                         gp_var_name(1:n), gp_var_name);
@@ -126,7 +120,7 @@
 
       str = {};
       while (isempty (str))
-        str = char (fread (istream)');
+        str = fread (istream, "*char")';
         if (isempty (str))
           sleep (0.05);
         else
@@ -138,8 +132,7 @@
     endif
 
     ## Strip out EOLs and the continuation character "|"
-    str(str=="\n") = "";
-    str(str=="\r") = "";
+    str(str=="\n" | str=="\r") = "";
     n_continue = strfind (str, " \\ ");
     if (! isempty (n_continue))
       str(n_continue+1) = "";
--- a/scripts/plot/private/__gnuplot_ginput__.m
+++ b/scripts/plot/private/__gnuplot_ginput__.m
@@ -31,6 +31,10 @@
 
 function [x, y, button] = __gnuplot_ginput__ (f, n)
 
+  if (compare_versions (__gnuplot_version__ (), "4.0", "<="))
+    error ("ginput: version %s of gnuplot not supported", gnuplot_version ());
+  endif
+
   ostream = get (f, "__plot_stream__");
   if (numel (ostream) < 1)
     error ("ginput: stream to gnuplot not open");
@@ -46,10 +50,6 @@
     ostream = ostream(1);
   endif
 
-  if (compare_versions (__gnuplot_version__ (), "4.0", "<="))
-    error ("ginput: version %s of gnuplot not supported", gnuplot_version ());
-  endif
-
   if (nargin == 1)
     x = zeros (100, 1);
     y = zeros (100, 1);
@@ -66,7 +66,7 @@
     ##Mode: 6*8*8 ==  0600
     [err, msg] = mkfifo (gpin_name, 6*8*8);
 
-    if (err != 0)
+    if (err)
       error ("ginput: Can not open fifo (%s)", msg);
     endif
   endif
@@ -84,8 +84,8 @@
         fprintf (ostream, "set print \"%s\";\n", gpin_name);
         fflush (ostream);
         [gpin, err] = fopen (gpin_name, "r");
-        if (err != 0)
-          error ("ginput: Can not open fifo (%s)", msg);
+        if (err)
+          error ("ginput: Can not open FIFO (%s)", msg);
         endif
         fputs (ostream, "pause mouse any;\n\n");
         fputs (ostream, "\nif (exists(\"MOUSE_KEY\") && exists(\"MOUSE_X\")) print MOUSE_X, MOUSE_Y, MOUSE_KEY; else print \"0 0 -1\"\n");
@@ -98,7 +98,7 @@
         [x(k), y(k), button(k), count] = fscanf (gpin, "%f %f %d", "C");
         fclose (gpin);
       else
-        fprintf (ostream, "set print \"-\";\n");
+        fputs (ostream, "set print \"-\";\n");
         fflush (ostream);
         fputs (ostream, "pause mouse any;\n\n");
         fputs (ostream, "\nif (exists(\"MOUSE_KEY\") && exists(\"MOUSE_X\")) print \"OCTAVE: \", MOUSE_X, MOUSE_Y, MOUSE_KEY; else print \"0 0 -1\"\n");
@@ -109,7 +109,7 @@
 
         str = {};
         while (isempty (str))
-          str = char (fread (istream)');
+          str = fread (istream, "*char")';
           if (isempty (str))
             sleep (0.05);
           else
--- a/scripts/plot/private/__gnuplot_has_feature__.m
+++ b/scripts/plot/private/__gnuplot_has_feature__.m
@@ -25,16 +25,18 @@
 ## Created: 2009-01-27
 
 function res = __gnuplot_has_feature__ (feature)
-  persistent features has_features
-  features = {"x11_figure_position",
-              "wxt_figure_size",
-              "transparent_patches",
-              "transparent_surface",
-              "epslatex_implies_eps_filesuffix",
-              "epslatexstandalone_terminal",
-              "screen_coordinates_for_{lrtb}margin",
-              "variable_GPVAL_TERMINALS",
-              "key_has_font_properties"};
+  persistent features = {"x11_figure_position",
+                         "wxt_figure_size",
+                         "transparent_patches",
+                         "transparent_surface",
+                         "epslatex_implies_eps_filesuffix",
+                         "epslatexstandalone_terminal",
+                         "screen_coordinates_for_{lrtb}margin",
+                         "variable_GPVAL_TERMINALS",
+                         "key_has_font_properties",
+                         "windows_figure_position",
+                         "has_termoption_dashed"};
+  persistent has_features;
 
   if (isempty (has_features))
     try
@@ -43,9 +45,9 @@
       ## Don't throw an error if gnuplot isn't installed
       gnuplot_version = "0.0.0";
     end_try_catch
-    versions = {"4.2.5", "4.4", "4.4", "4.4", "4.2", "4.2", "4.4", "4.4", "4.4"};
-    operators = {">=", ">=", ">=", ">=", ">=", ">=", ">=", ">=", ">="};
-    have_features = logical (zeros (size (features)));
+    versions = {"4.2.5", "4.4", "4.4", "4.4", "4.2", "4.2", "4.4", "4.4", "4.4", "4.4", "4.3"};
+    operators = {">=", ">=", ">=", ">=", ">=", ">=", ">=", ">=", ">=", ">=", ">="};
+    have_features = false (size (features));
     for n = 1 : numel (have_features)
       has_features(n) = compare_versions (gnuplot_version, versions{n}, operators{n});
     endfor
@@ -57,5 +59,6 @@
   else
     res = has_features(n);
   endif
+
 endfunction
 
--- a/scripts/plot/private/__gnuplot_has_terminal__.m
+++ b/scripts/plot/private/__gnuplot_has_terminal__.m
@@ -25,11 +25,10 @@
 ## Created: 2010-09-13
 
 function gnuplot_supports_term = __gnuplot_has_terminal__ (term, plot_stream)
-  term = deblank (term);
-  n = find (term == " ", 1);
-  if (! isempty (n))
-    term = term(1:n-1);
-  endif
+
+  term = strtrim (term);
+  term = lower (strtok (term, " "));
+
   if (__gnuplot_has_feature__ ("variable_GPVAL_TERMINALS"))
     if (nargin < 2)
       plot_stream = __gnuplot_open_stream__ (2);
@@ -59,6 +58,8 @@
                            "svg", "texdraw", "tgif", "tkcanvas", ...
                            "tpic", "windows", "x11", "xlib", "xterm"};
   endif
-  gnuplot_supports_term = any (strcmpi (available_terminals, term));
+
+  gnuplot_supports_term = any (strcmp (term, available_terminals));
+
 endfunction
 
--- a/scripts/plot/private/__gnuplot_print__.m
+++ b/scripts/plot/private/__gnuplot_print__.m
@@ -51,15 +51,15 @@
   switch (lower (opts.devopt))
   case {"eps", "eps2", "epsc", "epsc2"}
     if (any (strcmp (opts.devopt, {"eps", "epsc"})))
-      gp_opts = sprintf ("%s level1", gp_opts);
+      gp_opts = [gp_opts " level1"];
     endif
     if (opts.tight_flag || ! isempty (opts.preview))
       tmp_file = strcat (tmpnam (), ".eps");
       eps_drawnow (opts, tmp_file, gp_opts);
       if (dos_shell)
-        cleanup = sprintf (" & del %s", strrep (tmp_file, '/', '\'));
+        cleanup = [" & del " strrep(tmp_file, '/', '\')];
       else
-        cleanup = sprintf (" ; rm %s", tmp_file);
+        cleanup = [" ; rm " tmp_file];
       endif
       pipeline = {sprintf("%s %s",
                           opts.epstool_cmd (opts, tmp_file, opts.name),
@@ -89,33 +89,33 @@
     if (__gnuplot_has_feature__ ("epslatex_implies_eps_filesuffix"))
       suffix = "tex";
     else
-      %% Gnuplot 4.0 wants a ".eps" suffix.
+      ## Gnuplot 4.0 wants a ".eps" suffix.
       suffix = "eps";
     endif
-    local_drawnow (sprintf ("%s %s", term, gp_opts),
+    local_drawnow ([term " " gp_opts],
                    strcat (name, ".", suffix), opts);
   case "tikz"
     if (__gnuplot_has_terminal__ ("tikz"))
-      local_drawnow (sprintf ("lua tikz %s", gp_opts), opts.name, opts);
+      local_drawnow (["lua tikz " gp_opts], opts.name, opts);
     else
       error (sprintf ("print:no%soutput", opts.devopt),
              "print.m: '%s' output is not available for gnuplot-%s",
              upper (opts.devopt), __gnuplot_version__ ());
     endif
   case "svg"
-    local_drawnow (sprintf ("svg dynamic %s", gp_opts), opts.name, opts);
+    local_drawnow (["svg dynamic " gp_opts], opts.name, opts);
   case {"aifm", "corel", "eepic", "emf", "fig"}
-    local_drawnow (sprintf ("%s %s", opts.devopt, gp_opts), opts.name, opts);
+    local_drawnow ([opts.devopt " " gp_opts], opts.name, opts);
   case {"pdfcairo", "pngcairo"}
     if (__gnuplot_has_terminal__ (opts.devopt))
-      local_drawnow (sprintf ("%s %s", opts.devopt, gp_opts), opts.name, opts);
+      local_drawnow ([opts.devopt " " gp_opts], opts.name, opts);
     else
       error (sprintf ("print:no%soutput", opts.devopt),
              "print.m: '%s' output is not available for gnuplot-%s",
              upper (opts.devopt), __gnuplot_version__ ());
     endif
   case {"canvas", "dxf", "hpgl", "mf", "gif", "pstricks", "texdraw"}
-    local_drawnow (sprintf ("%s %s", opts.devopt, gp_opts), opts.name, opts);
+    local_drawnow ([opts.devopt " " gp_opts], opts.name, opts);
   case opts.ghostscript.device
     gp_opts = font_spec (opts, "devopt", "eps");
     opts.ghostscript.output = opts.name;
@@ -124,9 +124,9 @@
     [cmd_gs, cmd_cleanup] = __ghostscript__ (opts.ghostscript);
     if (opts.send_to_printer || isempty (opts.name))
       cmd_lpr = opts.lpr_cmd (opts);
-      cmd = sprintf ("%s | %s", cmd_gs, cmd_lpr);
+      cmd = [cmd_gs " | " cmd_lpr];
     else
-      cmd = sprintf ("%s", cmd_gs);
+      cmd = cmd_gs;
     endif
     if (dos_shell)
       cmd = sprintf ("%s & del %s", cmd, strrep (opts.ghostscript.source, '/', '\'));
@@ -135,9 +135,9 @@
     endif
     if (! isempty (cmd_cleanup))
       if (dos_shell)
-        pipeline = {sprintf("%s & %s", cmd, cmd_cleanup)};
+        pipeline = {[cmd " & " cmd_cleanup]};
       else
-        pipeline = {sprintf("%s ; %s", cmd, cmd_cleanup)};
+        pipeline = {[cmd " ; " cmd_cleanup]};
       endif
     else
       pipeline = {cmd};
@@ -151,7 +151,7 @@
 
   opts.pipeline = pipeline;
 
-  for n = 1:numel(pipeline)
+  for n = 1:numel (pipeline)
     if (opts.debug)
       fprintf ("gnuplot-pipeline: '%s'\n", pipeline{n});
     endif
@@ -170,14 +170,11 @@
 function eps_drawnow (opts, epsfile, gp_opts)
   [h, fontsize] = get_figure_text_objs (opts);
   unwind_protect
-    for n = 1:numel(h)
-      set (h(n), "fontsize", 2 * fontsize{n});
-    endfor
-    local_drawnow (sprintf ("postscript eps %s", gp_opts), epsfile, opts);
+    fontsize_2x = cellfun (@(x) 2*x, fontsize, "uniformoutput", false);
+    set (h, {"fontsize"}, fontsize_2x);
+    local_drawnow (["postscript eps " gp_opts], epsfile, opts);
   unwind_protect_cleanup
-    for n = 1:numel(h)
-      set (h(n), "fontsize", fontsize{n});
-    endfor
+    set (h, {"fontsize"}, fontsize);
   end_unwind_protect
 endfunction
 
@@ -196,16 +193,16 @@
 endfunction
 
 function f = font_spec (opts, varargin)
-  for n = 1:2:numel(varargin)
+  for n = 1:2:numel (varargin)
     opts.(varargin{n}) = varargin{n+1};
   endfor
   f = "";
   switch (opts.devopt)
   case "cgm"
     if (! isempty (opts.font) && ! isempty (opts.fontsize))
-      f = sprintf ("font ""%s,%d""", opts.font, opts.fontsize);
+      f = sprintf ('font "%s,%d"', opts.font, opts.fontsize);
     elseif (! isempty (opts.font))
-      f = sprintf ("font ""%s""", opts.font);
+      f = sprintf ('font "%s"', opts.font);
     elseif (! isempty (opts.fontsize))
       f = sprintf ("%d", opts.fontsize);
     endif
@@ -215,39 +212,39 @@
     ## Compensate for the half scale. This will produce the proper
     ## spacing for the requested fontsize.
     if (! isempty (opts.font) && ! isempty (opts.fontsize))
-      f = sprintf ("font ""%s,%d""", opts.font, 2 * opts.fontsize);
+      f = sprintf ('font "%s,%d"', opts.font, 2 * opts.fontsize);
     elseif (! isempty (opts.font))
-      f = sprintf ("font ""%s""", opts.font);
+      f = sprintf ('font "%s"', opts.font);
     elseif (! isempty (opts.fontsize))
       f = sprintf ("%d", 2 * opts.fontsize);
     endif
   case "svg"
     if (! isempty (opts.font) && ! isempty (opts.fontsize))
       fontsize = round (opts.fontsize * 0.75);
-      f = sprintf ("fname ""%s"" fsize %d", opts.font, fontsize);
+      f = sprintf ('fname "%s" fsize %d', opts.font, fontsize);
     elseif (! isempty (opts.font))
-      f = sprintf ("fname ""%s""", opts.font);
+      f = sprintf ('fname "%s"', opts.font);
     elseif (! isempty (opts.fontsize))
       fontsize = round (opts.fontsize * 0.75);
       f = sprintf ("%s fsize %d", f, fontsize);
     endif
   case "pdf"
     if (! isempty (opts.font) && ! isempty (opts.fontsize))
-      f = sprintf ("font ""%s,%d""", opts.font, opts.fontsize);
+      f = sprintf ('font "%s,%d"', opts.font, opts.fontsize);
     elseif (! isempty (opts.font))
-      f = sprintf ("font ""%s""", opts.font);
+      f = sprintf ('font "%s"', opts.font);
     elseif (! isempty (opts.fontsize))
       f = sprintf ("fsize %d", f, opts.fontsize);
     endif
   case {"pdfcairo", "pngcairo"}
     if (! isempty (opts.font))
-      f = sprintf ("font ""%s""", opts.font);
+      f = sprintf ('font "%s"', opts.font);
     endif
   case {"epslatex", "epslatexstandalone"}
     if (! isempty (opts.font) && ! isempty (opts.fontsize))
-      f = sprintf ("font ""%s,%d""", opts.font, opts.fontsize);
+      f = sprintf ('font "%s,%d"', opts.font, opts.fontsize);
     elseif (! isempty (opts.font))
-      f = sprintf ("font ""%s""", opts.font);
+      f = sprintf ('font "%s"', opts.font);
     elseif (! isempty (opts.fontsize))
       f = sprintf ("%d", opts.fontsize);
     endif
@@ -257,17 +254,17 @@
     endif
   case {"gif", "jpeg", "png"}
     if (! isempty (opts.font) && ! isempty (opts.fontsize))
-      f = sprintf ("font ""%s ,%d""", opts.font, opts.fontsize);
+      f = sprintf ('font "%s ,%d"', opts.font, opts.fontsize);
     elseif (! isempty (opts.font))
-      f = sprintf ("font ""%s""", opts.font);
+      f = sprintf ('font "%s"', opts.font);
     elseif (! isempty (opts.fontsize))
-      f = sprintf ("font ""%d""", opts.fontsize);
+      f = sprintf ('font "%d"', opts.fontsize);
     endif
   case "emf"
     if (! isempty (opts.font) && ! isempty (opts.fontsize))
-      f = sprintf ("""%s"" %d", opts.font, opts.fontsize);
+      f = sprintf ('"%s" %d', opts.font, opts.fontsize);
     elseif (! isempty (opts.font))
-      f = sprintf ("""%s""", opts.font);
+      f = sprintf ('"%s"', opts.font);
     elseif (! isempty (opts.fontsize))
       f = sprintf ("%d", opts.fontsize);
     endif
--- a/scripts/plot/private/__gnuplot_version__.m
+++ b/scripts/plot/private/__gnuplot_version__.m
@@ -30,12 +30,12 @@
   persistent __version__ = "";
 
   if (isempty (__version__))
-    [status, output] = system (sprintf ("\"%s\" --version", gnuplot_binary ()));
+    [status, output] = system (sprintf ('"%s" --version', gnuplot_binary ()));
     if (status != 0)
       ## This message ends in a newline so that the traceback messages
       ## are skipped and people might actually see the message, read it,
-      ## comprehend it, actually take the advice it gives, and stop
-      ## asking us why plotting fails when gnuplot is not found.
+      ## comprehend it, take the advice it gives, and stop asking us
+      ## why plotting fails when gnuplot is not found.
       error ("you must have gnuplot installed to display graphics; if you have gnuplot installed in a non-standard location, see the 'gnuplot_binary' function\n");
     endif
     output = strrep (output, "gnuplot", "");
--- a/scripts/plot/private/__go_draw_axes__.m
+++ b/scripts/plot/private/__go_draw_axes__.m
@@ -47,8 +47,8 @@
       else
         h = axis_obj.__plotyy_axes__;
         h = h(ishandle (h));
-        h = h(isprop (h, "__ploty_axes__"));
-        rmappdata (h, "__plotyy_axes__")
+        h = h(isprop (h, "__plotyy_axes__"));
+        rmappdata (h, "__plotyy_axes__");
       endif
     endif
 
@@ -90,7 +90,7 @@
           x = [1, 1];
         else
           ## 3D plots need to be sized down to fit in the window.
-          x = 1.0 ./ sqrt([2, 2.5]);
+          x = 1.0 ./ sqrt ([2, 2.5]);
         endif
         fprintf (plot_stream, "set tmargin screen %.15g;\n",
                  pos(2)+pos(4)/2+x(2)*pos(4)/2);
@@ -442,6 +442,16 @@
 
       obj = get (kids(end));
 
+      if (isfield (obj, "xdata"))
+        obj.xdata = double (obj.xdata);
+      end
+      if (isfield (obj, "ydata"))
+        obj.ydata = double (obj.ydata);
+      end
+      if (isfield (obj, "zdata"))
+        obj.zdata = double (obj.zdata);
+      end
+
       if (isfield (obj, "units"))
         units = obj.units;
         unwind_protect
@@ -453,7 +463,7 @@
       endif
       kids = kids(1:(end-1));
 
-      if (strcmpi (obj.visible, "off"))
+      if (strcmp (obj.visible, "off"))
         continue;
       endif
 
@@ -495,13 +505,13 @@
             img_xdata = img_xdata(2:-1:1);
             img_data = img_data(:,end:-1:1,:);
           elseif (img_xdata(1) == img_xdata(2))
-            img_xdata = img_xdata(1) + [0, size(img_data,2)-1];
+            img_xdata = img_xdata(1) + [0, columns(img_data)-1];
           endif
           if (img_ydata(2) < img_ydata(1))
             img_ydata = img_ydata(2:-1:1);
             img_data = img_data(end:-1:1,:,:);
           elseif (img_ydata(1) == img_ydata(2))
-            img_ydata = img_ydata(1) + [0, size(img_data,1)-1];
+            img_ydata = img_ydata(1) + [0, rows(img_data)-1];
           endif
 
           [y_dim, x_dim] = size (img_data(:,:,1));
@@ -574,7 +584,7 @@
             ydat = obj.ydata(:);
             data{data_idx} = [xdat, ydat]';
             usingclause{data_idx} = sprintf ("record=%d using ($1):($2) axes %s%s",
-                                            rows(xdat), xaxisloc_using, yaxisloc_using);
+                                            rows (xdat), xaxisloc_using, yaxisloc_using);
           endif
 
           style = do_linestyle_command (obj, obj.color, data_idx, mono,
@@ -680,14 +690,14 @@
                      || strncmp (obj.facecolor, "interp", 6))
                      && isfield (obj, "cdata"))
                    if (ndims (obj.cdata) == 2
-                       && (size (obj.cdata, 2) == nc
-                           && (size (obj.cdata, 1) == 1
-                               || size (obj.cdata, 1) == 3)))
+                       && (columns (obj.cdata) == nc
+                           && (rows (obj.cdata) == 1
+                               || rows (obj.cdata) == 3)))
                      ccol = cdat (:, i);
                    elseif (ndims (obj.cdata) == 2
-                       && (size (obj.cdata, 1) == nc
-                           && (size (obj.cdata, 2) == 1
-                               || size (obj.cdata, 2) == 3)))
+                       && (rows (obj.cdata) == nc
+                           && (columns (obj.cdata) == 1
+                               || columns (obj.cdata) == 3)))
                      ccol = cdat (i, :);
                    elseif (ndims (obj.cdata) == 3)
                      ccol = permute (cdat (:, i, :), [1, 3, 2]);
@@ -704,17 +714,17 @@
                        if (cdatadirect)
                          r = round (ccol);
                        else
-                         r = 1 + round ((size (cmap, 1) - 1)
+                         r = 1 + round ((rows (cmap) - 1)
                                         * (ccol - clim(1))/(clim(2) - clim(1)));
                        endif
-                       r = max (1, min (r, size (cmap, 1)));
+                       r = max (1, min (r, rows (cmap)));
                        color = cmap(r, :);
                      endif
                    elseif (strncmp (obj.facecolor, "interp", 6))
                      if (nd == 3 && numel (xcol) == 3)
                        ccdat = ccol;
                        if (! isvector (ccdat))
-                         tmp = rows(cmap) + rows(addedcmap) + ...
+                         tmp = rows (cmap) + rows (addedcmap) + ...
                               [1 : rows(ccdat)];
                          addedcmap = [addedcmap; ccdat];
                          ccdat = tmp(:);
@@ -728,10 +738,10 @@
                        if (cdatadirect)
                          r = round (ccol);
                        else
-                         r = 1 + round ((size (cmap, 1) - 1)
+                         r = 1 + round ((rows (cmap) - 1)
                                         * (ccol - clim(1))/(clim(2) - clim(1)));
                        endif
-                       r = max (1, min (r, size (cmap, 1)));
+                       r = max (1, min (r, rows (cmap)));
                        color = cmap(r(1),:);
                      endif
                    endif
@@ -746,7 +756,7 @@
 
                if (nd == 3 && numel (xcol) == 3)
                  if (isnan (ccdat))
-                   ccdat = (rows (cmap) + rows(addedcmap) + 1) * ones(3, 1);
+                   ccdat = (rows (cmap) + rows (addedcmap) + 1) * ones(3, 1);
                    addedcmap = [addedcmap; reshape(color, 1, 3)];
                  endif
                  data{data_3d_idx} = [data{data_3d_idx}, ...
@@ -812,14 +822,14 @@
                     || strncmp (ec, "interp", 6))
                    && isfield (obj, "cdata"))
                  if (ndims (obj.cdata) == 2
-                     && (size (obj.cdata, 2) == nc
-                         && (size (obj.cdata, 1) == 1
-                             || size (obj.cdata, 1) == 3)))
+                     && (columns (obj.cdata) == nc
+                         && (rows (obj.cdata) == 1
+                             || rows (obj.cdata) == 3)))
                    ccol = cdat (:, i);
                  elseif (ndims (obj.cdata) == 2
-                         && (size (obj.cdata, 1) == nc
-                             && (size (obj.cdata, 2) == 1
-                                 || size (obj.cdata, 2) == 3)))
+                         && (rows (obj.cdata) == nc
+                             && (columns (obj.cdata) == 1
+                                 || columns (obj.cdata) == 3)))
                    ccol = cdat (i, :);
                  elseif (ndims (obj.cdata) == 3)
                    ccol = permute (cdat (:, i, :), [1, 3, 2]);
@@ -827,22 +837,22 @@
                    ccol = cdat;
                  endif
                  if (strncmp (ec, "flat", 4))
-                   if (numel(ccol) == 3)
+                   if (numel (ccol) == 3)
                      color = ccol;
                    else
                      if (isscalar (ccol))
-                       ccol = repmat(ccol, numel (xcol), 1);
+                       ccol = repmat (ccol, numel (xcol), 1);
                      endif
                      color = "flat";
                      have_cdata(data_idx) = true;
                    endif
                  elseif (strncmp (ec, "interp", 6))
-                   if (numel(ccol) == 3)
+                   if (numel (ccol) == 3)
                      warning ("\"interp\" not supported, using 1st entry of cdata");
                      color = ccol(1,:);
                    else
                      if (isscalar (ccol))
-                       ccol = repmat(ccol, numel (xcol), 1);
+                       ccol = repmat (ccol, numel (xcol), 1);
                      endif
                      color = "interp";
                      have_cdata(data_idx) = true;
@@ -877,7 +887,7 @@
              endif
 
              if (isfield (obj, "linewidth"))
-               lw = sprintf("linewidth %f", obj.linewidth);
+               lw = sprintf ("linewidth %f", obj.linewidth);
              else
                lw  = "";
              endif
@@ -923,7 +933,7 @@
                    else
                      m = mdat;
                    endif
-                   ps = sprintf("pointsize %f", m / 3);
+                   ps = sprintf ("pointsize %f", m / 3);
                  else
                    ps = "";
                  endif
@@ -950,7 +960,7 @@
                    else
                      m = mdat;
                    endif
-                   ps = sprintf("pointsize %f", m / 3);
+                   ps = sprintf ("pointsize %f", m / 3);
                  else
                    ps = "";
                  endif
@@ -977,7 +987,7 @@
                      else
                        m = mdat;
                      endif
-                     ps = sprintf("pointsize %f", m / 3);
+                     ps = sprintf ("pointsize %f", m / 3);
                    else
                      ps = "";
                    endif
@@ -987,7 +997,7 @@
                  endif
                else
                  if (!isempty (style))
-                   if (length(tmpwith) < sidx || isempty (tmpwith{sidx}))
+                   if (length (tmpwith) < sidx || isempty (tmpwith{sidx}))
                      tmpwith{sidx} = sprintf ("with %s %s %s %s",
                                               style, lw, lt,
                                               colorspec);
@@ -1012,7 +1022,7 @@
                      else
                        m = mdat;
                      endif
-                     ps = sprintf("pointsize %f", m / 3);
+                     ps = sprintf ("pointsize %f", m / 3);
                    else
                      ps = "";
                    endif
@@ -1122,7 +1132,7 @@
             cdat = obj.cdata;
 
             err = false;
-            if (! size_equal(zdat, cdat))
+            if (! size_equal (zdat, cdat))
               err = true;
             endif
             if (isvector (xdat) && isvector (ydat) && ismatrix (zdat))
@@ -1188,11 +1198,11 @@
               if (all (obj.facecolor == 1))
                 hidden_removal = true;
               endif
-              fputs(plot_stream,"unset pm3d;\n");
-              fputs(plot_stream,"set style increment user;\n");
+              fputs (plot_stream,"unset pm3d;\n");
+              fputs (plot_stream,"set style increment user;\n");
               withpm3d = false;
-              withclause{data_idx} = sprintf("with %s linestyle %d",
-                                             style{1}, data_idx);
+              withclause{data_idx} = sprintf ("with %s linestyle %d",
+                                              style{1}, data_idx);
               fputs (plot_stream, "unset pm3d\n");
             endif
 
@@ -1267,7 +1277,7 @@
                                               style{3}, data_idx);
             endif
             if (withpm3d && strncmp (style {1}, "linespoints", 11))
-              if (isempty(zz))
+              if (isempty (zz))
                 len = 3 * xlen;
                 zz = zeros (ylen, len);
                 k = 1;
@@ -1315,7 +1325,7 @@
           endif
 
           if (ischar (obj.string))
-            num_lines = size (obj.string, 1);
+            num_lines = rows (obj.string);
           else
             num_lines = numel (obj.string);
           endif
@@ -1335,7 +1345,7 @@
           ## Gnuplot's Character units are different for x/y and vary with fontsize. The aspect ratio
           ## of 1:1.7 was determined by experiment to work for eps/ps/etc. For the MacOS aqua terminal
           ## a value of 2.5 is needed. However, the difference is barely noticable.
-          dx_and_dy = [(-dy * sind (angle)), (dy * cosd(angle))] .* [1.7 1];
+          dx_and_dy = [(-dy * sind (angle)), (dy * cosd (angle))] .* [1.7 1];
 
           ## FIXME - Multiline text produced the gnuplot "warning: ft_render: skipping glyph"
           if (nd == 3)
@@ -1376,7 +1386,7 @@
       fputs (plot_stream, "set pm3d explicit;\n");
     endif
 
-    if (isnan(hidden_removal) || hidden_removal)
+    if (isnan (hidden_removal) || hidden_removal)
       fputs (plot_stream, "set hidden3d;\n");
     else
       fputs (plot_stream, "unset hidden3d;\n");
@@ -1425,19 +1435,19 @@
     endif
 
     cmap = parent_figure_obj.colormap;
-    cmap_sz = rows(cmap);
+    cmap_sz = rows (cmap);
     if (! any (isinf (clim)))
       if (truecolor || ! cdatadirect)
-        if (rows(addedcmap) > 0)
+        if (rows (addedcmap) > 0)
           for i = 1:data_idx
             if (have_3d_patch(i))
               data{i}(end,:) = clim(2) * (data{i}(end, :) - 0.5) / cmap_sz;
              endif
           endfor
-          fprintf (plot_stream, "set cbrange [%g:%g];\n", clim(1), clim(2) *
-                   (cmap_sz + rows(addedcmap)) / cmap_sz);
+          fprintf (plot_stream, "set cbrange [%.15e:%.15e];\n", clim(1), clim(2) *
+                   (cmap_sz + rows (addedcmap)) / cmap_sz);
         else
-          fprintf (plot_stream, "set cbrange [%g:%g];\n", clim);
+          fprintf (plot_stream, "set cbrange [%.15e:%.15e];\n", clim);
         endif
       else
         fprintf (plot_stream, "set cbrange [1:%d];\n", cmap_sz +
@@ -1544,7 +1554,7 @@
       keypos = hlgnd.location;
       if (ischar (keypos))
         keypos = lower (keypos);
-        keyout = findstr (keypos, "outside");
+        keyout = strfind (keypos, "outside");
         if (! isempty (keyout))
           inout = "outside";
           keypos = keypos(1:keyout-1);
@@ -1581,16 +1591,29 @@
       else
         fontspec = "";
       endif
-      fprintf (plot_stream, "set key %s %s;\nset key %s %s %s %s;\n",
-               inout, pos, box, reverse, horzvert, fontspec);
+      textcolors = get (findobj (hlgnd.children, "type", "text"), "color");
+      if (iscell (textcolors))
+        textcolors = cell2mat (textcolors);
+        textcolors = unique (textcolors, "rows");
+      endif
+      if (rows (textcolors) > 1)
+        ## Gnuplot is unable to assign arbitrary colors to each text entry
+        ## for the key/legend.  But, the text color can be set to match the
+        ## color of the plot object.
+        colorspec = "textcolor variable";
+      else
+        colorspec = get_text_colorspec (textcolors, mono);
+      endif
+      fprintf (plot_stream, "set key %s %s;\nset key %s %s %s %s %s;\n",
+               inout, pos, box, reverse, horzvert, fontspec, colorspec);
     else
       fputs (plot_stream, "unset key;\n");
     endif
     fputs (plot_stream, "set style data lines;\n");
 
     cmap = [cmap; addedcmap];
-    cmap_sz = cmap_sz + rows(addedcmap);
-    if (length(cmap) > 0)
+    cmap_sz = cmap_sz + rows (addedcmap);
+    if (length (cmap) > 0)
       fprintf (plot_stream,
                "set palette positive color model RGB maxcolors %i;\n",
                cmap_sz);
@@ -1628,7 +1651,7 @@
         if (numel (is_image_data) > 1 && is_image_data(2))
           ## Remove terminating semicolon
           n = max (strfind (withclause{1}, ";"));
-          if (! isempty(n))
+          if (! isempty (n))
             withclause{1} = withclause{1}(1:n-1);
           endif
         endif
@@ -1656,7 +1679,7 @@
             if (numel (is_image_data) > i && is_image_data(i+1))
               ## Remove terminating semicolon
               n = max (strfind (withclause{i}, ";"));
-              if (! isempty(n))
+              if (! isempty (n))
                 withclause{i} = withclause{i}(1:n-1);
               endif
             endif
@@ -1689,7 +1712,7 @@
           ## Can't write 3d patch data as binary as can't plot more than
           ## a single patch at a time and have to plot all patches together
           ## so that the gnuplot depth ordering is done correctly
-          for j = 1 : 4 : columns(data{i})
+          for j = 1 : 4 : columns (data{i})
             if (j != 1)
               fputs (plot_stream, "\n\n");
             endif
@@ -1729,9 +1752,9 @@
 endfunction
 
 function x = flip (x)
-  if (size (x, 1) == 1)
+  if (rows (x) == 1)
     x = fliplr (x);
-  elseif (size (x, 2) == 1 || ischar (x))
+  elseif (columns (x) == 1 || ischar (x))
     x = flipud (x);
   else
     x = flipud (fliplr (x));
@@ -2096,7 +2119,7 @@
                     fontname, fontspec, interpreter, scale, sgn, gnuplot_term)
   persistent warned_latex = false;
   if (strcmpi (interpreter, "tex"))
-    for n = 1 : numel(labels)
+    for n = 1 : numel (labels)
       labels{n} = __tex2enhanced__ (labels{n}, fontname, false, false);
     endfor
   elseif (strcmpi (interpreter, "latex"))
@@ -2137,16 +2160,16 @@
         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
 
-        labels = regexprep(labels, '%', "%%");
+        labels = regexprep (labels, '%', "%%");
         for i = 1:ntics
           fprintf (plot_stream, " \"%s\" %.15g", labels{k++}, tics(i));
           if (i < ntics)
@@ -2162,7 +2185,7 @@
         else
           fprintf (plot_stream, "unset m%stics;\n", ax);
         endif
-     else
+      else
         error ("__go_draw_axes__: unsupported type of ticklabel");
       endif
     else
@@ -2205,9 +2228,8 @@
     ticklabel = num2str (ticklabel(:), 5);
   endif
   if (ischar (ticklabel))
-    if (size (ticklabel, 1) == 1 && any (ticklabel == "|"))
-      n = setdiff (findstr (ticklabel, "|"), findstr (ticklabel, '\|'));
-      ticklabel = strsplit (ticklabel, "|");
+    if (rows (ticklabel) == 1 && any (ticklabel == "|"))
+      ticklabel = strsplit (ticklabel, "|", false);
     else
       ticklabel = cellstr (ticklabel);
     endif
@@ -2237,7 +2259,7 @@
   it = false;
   bld = false;
   if (! isempty (t.fontweight) && strcmpi (t.fontweight, "bold"))
-    if (! isempty(t.fontangle)
+    if (! isempty (t.fontangle)
         && (strcmpi (t.fontangle, "italic")
             || strcmpi (t.fontangle, "oblique")))
       f = cstrcat (f, "-bolditalic");
@@ -2247,7 +2269,7 @@
       f = cstrcat (f, "-bold");
       bld = true;
     endif
-  elseif (! isempty(t.fontangle)
+  elseif (! isempty (t.fontangle)
           && (strcmpi (t.fontangle, "italic")
               || strcmpi (t.fontangle, "oblique")))
     f = cstrcat (f, "-italic");
@@ -2276,13 +2298,13 @@
 
   ## The text object maybe multiline, and may be of any class
   str = getfield (obj, fld);
-  if (ischar (str) && size (str, 1) > 1)
+  if (ischar (str) && rows (str) > 1)
     str = cellstr (str);
   elseif (isnumeric (str))
     str = cellstr (num2str (str(:)));
   endif
   if (iscellstr (str))
-    for n = 1:numel(str)
+    for n = 1:numel (str)
       if (isnumeric (str{n}))
         str{n} = num2str (str{n});
       endif
@@ -2293,7 +2315,7 @@
   if (enhanced)
     if (strcmpi (obj.interpreter, "tex"))
       if (iscellstr (str))
-        for n = 1:numel(str)
+        for n = 1:numel (str)
           str{n} = __tex2enhanced__ (str{n}, fnt, it, bld);
         endfor
       else
@@ -2317,14 +2339,14 @@
     labels = cellstr (str);
   endif
   for marker = "_^" 
-    for m = 1 : numel(labels)
+    for m = 1 : numel (labels)
       n1 = strfind (labels{m}, sprintf ("\\%s", marker));
       n2 = strfind (labels{m}, marker);
       if (! isempty (n1))
         n1 = n1 + 1;
         n2 = setdiff (n2, n1);
-      end
-      for n = numel(n2):-1:1
+      endif
+      for n = numel (n2):-1:1
         labels{m} = [labels{m}(1:n2(n)-1), "\\", labels{m}(n2(n):end)];
       endfor
     endfor
@@ -2340,7 +2362,7 @@
   persistent sym = __setup_sym_table__ ();
   persistent flds = fieldnames (sym);
 
-  [s, e, m] = regexp(str,'\\([a-zA-Z]+|0)','start','end','matches');
+  [s, e, m] = regexp (str, "\\\\([a-zA-Z]+|0)", "start", "end", "matches");
 
   for i = length (s) : -1 : 1
     ## special case for "\0"  and replace with "{/Symbol \306}'
@@ -2349,7 +2371,7 @@
     else
       f = m{i}(2:end);
       if (isfield (sym, f))
-        g = getfield(sym, f);
+        g = getfield (sym, f);
         ## FIXME The symbol font doesn't seem to support bold or italic
         ##if (bld)
         ##  if (it)
@@ -2369,54 +2391,54 @@
         it = true;
         if (bld)
           str = cstrcat (str(1:s(i) - 1), '/', fnt, '-bolditalic ',
-                        str(s(i) + 3:end));
+                         str(s(i) + 3:end));
         else
           str = cstrcat (str(1:s(i) - 1), '/', fnt, '-italic ',
-                        str(s(i) + 3:end));
+                         str(s(i) + 3:end));
         endif
       elseif (strncmp (f, "bf", 2))
         bld = true;
         if (it)
           str = cstrcat (str(1:s(i) - 1), '/', fnt, '-bolditalic ',
-                        str(2(i) + 3:end));
+                         str(2(i) + 3:end));
         else
           str = cstrcat (str(1:s(i) - 1), '/', fnt, '-bold ',
-                        str(s(i) + 3:end));
+                         str(s(i) + 3:end));
         endif
       elseif (strcmpi (f, "color"))
         ## FIXME Ignore \color but remove trailing {} block as well
-        d = strfind(str(e(i) + 1:end),'}');
+        d = strfind (str(e(i) + 1:end),'}');
         if (isempty (d))
           warning ('syntax error in \color argument');
         else
           str = cstrcat (str(1:s(i) - 1), str(e(i) + d + 1:end));
         endif
-      elseif(strcmpi (f, "fontname"))
-        b1 = strfind(str(e(i) + 1:end),'{');
-        b2 = strfind(str(e(i) + 1:end),'}');
-        if (isempty(b1) || isempty(b2))
+      elseif (strcmpi (f, "fontname"))
+        b1 = strfind (str(e(i) + 1:end),'{');
+        b2 = strfind (str(e(i) + 1:end),'}');
+        if (isempty (b1) || isempty (b2))
           warning ('syntax error in \fontname argument');
         else
           str = cstrcat (str(1:s(i) - 1), '/',
-                        str(e(i)+b1(1) + 1:e(i)+b2(1)-1), '{}',
-                        str(e(i) + b2(1) + 1:end));
+                         str(e(i)+b1(1) + 1:e(i)+b2(1)-1), '{}',
+                         str(e(i) + b2(1) + 1:end));
         endif
-      elseif(strcmpi (f, "fontsize"))
-        b1 = strfind(str(e(i) + 1:end),'{');
-        b2 = strfind(str(e(i) + 1:end),'}');
-        if (isempty(b1) || isempty(b2))
+      elseif (strcmpi (f, "fontsize"))
+        b1 = strfind (str(e(i) + 1:end),'{');
+        b2 = strfind (str(e(i) + 1:end),'}');
+        if (isempty (b1) || isempty (b2))
           warning ('syntax error in \fontname argument');
         else
           str = cstrcat (str(1:s(i) - 1), '/=',
-                        str(e(i)+b1(1) + 1:e(i)+b2(1)-1), '{}',
-                        str(e(i) + b2(1) + 1:end));
+                         str(e(i)+b1(1) + 1:e(i)+b2(1)-1), '{}',
+                         str(e(i) + b2(1) + 1:end));
         endif
       else
         ## Last desperate attempt to treat the symbol. Look for things
         ## like \pix, that should be translated to the symbol Pi and x
         for j = 1 : length (flds)
           if (strncmp (flds{j}, f, length (flds{j})))
-            g = getfield(sym, flds{j});
+            g = getfield (sym, flds{j});
             ## FIXME The symbol font doesn't seem to support bold or italic
             ##if (bld)
             ##  if (it)
@@ -2428,7 +2450,7 @@
             ##  g = regexprep (g, '/Symbol', '/Symbol-italic');
             ##endif
             str = cstrcat (str(1:s(i) - 1), g,
-                          str(s(i) + length (flds{j}) + 1:end));
+                           str(s(i) + length (flds{j}) + 1:end));
             break;
           endif
         endfor
@@ -2444,15 +2466,15 @@
 
   ## FIXME -- This is a mess... Is it worth it just for a "@" character?
 
-  [s, m] = regexp(str,'[_\^]','start','matches');
+  [s, m] = regexp (str,'[_\^]','start','matches');
   i = 1;
   p = 0;
   while (i < length (s))
-    if (i < length(s))
+    if (i < length (s))
       if (str(s(i) + p + 1) == "{")
-        s1 = strfind(str(s(i) + p + 2:end),'{');
+        s1 = strfind (str(s(i) + p + 2:end),'{');
         si = 1;
-        l1 = strfind(str(s(i) + p + 1:end),'}');
+        l1 = strfind (str(s(i) + p + 1:end),'}');
         li = 1;
         while (li <= length (l1) && si <= length (s1))
           if (l1(li) < s1(si))
@@ -2464,12 +2486,12 @@
             si++;
           endif
         endwhile
-        l1 = l1 (min (length(l1), si));
+        l1 = l1 (min (length (l1), si));
         if (s(i) + l1 + 1 == s(i+1))
           if (str(s(i + 1) + p + 1) == "{")
-            s2 = strfind(str(s(i + 1) + p + 2:end),'{');
+            s2 = strfind (str(s(i + 1) + p + 2:end),'{');
             si = 1;
-            l2 = strfind(str(s(i + 1) + p + 1:end),'}');
+            l2 = strfind (str(s(i + 1) + p + 1:end),'}');
             li = 1;
             while (li <= length (l2) && si <= length (s2))
               if (l2(li) < s2(si))
@@ -2481,20 +2503,20 @@
                 si++;
               endif
             endwhile
-            l2 = l2 (min (length(l2), si));
+            l2 = l2 (min (length (l2), si));
             if (length_string (str(s(i)+p+2:s(i)+p+l1-1)) <=
-                length_string(str(s(i+1)+p+2:s(i+1)+p+l2-1)))
+                length_string (str(s(i+1)+p+2:s(i+1)+p+l2-1)))
               ## Shortest already first!
               str = cstrcat (str(1:s(i)+p-1), "@", str(s(i)+p:end));
             else
               ## Have to swap sub/super-script to get shortest first.
               str = cstrcat (str(1:s(i)+p-1), "@", str(s(i+1)+p:s(i+1)+p+l2),
-                            str(s(i)+p:s(i)+p+l1), str(s(i+1)+p+l2+1:end));
+                             str(s(i)+p:s(i)+p+l1), str(s(i+1)+p+l2+1:end));
             endif
           else
             ## Have to swap sub/super-script to get shortest first.
             str = cstrcat (str(1:s(i)+p-1), "@", str(s(i+1)+p:s(i+1)+p+1),
-                          str(s(i)+p:s(i)+p+l1), str(s(i+1)+p+2:end));
+                           str(s(i)+p:s(i)+p+l1), str(s(i+1)+p+2:end));
           endif
           i += 2;
           p ++;
@@ -2519,7 +2541,7 @@
 endfunction
 
 function l = length_string (s)
-  l = length (s) - length (strfind(s,'{')) - length (strfind(s,'}'));
+  l = length (s) - length (strfind (s,'{')) - length (strfind (s,'}'));
   m = regexp (s, '/([\w-]+|[\w-]+=\d+)', 'matches');
   if (!isempty (m))
     l = l - sum (cellfun ("length", m));
--- a/scripts/plot/private/__go_draw_figure__.m
+++ b/scripts/plot/private/__go_draw_figure__.m
@@ -44,6 +44,7 @@
         else
           bg_is_set = false;
         endif
+        fg_was_set = false;
 
         for i = nkids:-1:1
           type = get (kids(i), "type");
@@ -142,6 +143,11 @@
                   if (isnumeric (fg) && strcmp (get (kids(i), "visible"), "on"))
                     fprintf (plot_stream, "set obj 2 rectangle from graph 0,0 to graph 1,1 behind fc rgb \"#%02x%02x%02x\"\n", 255 * fg);
                     fg_is_set = true;
+                    fg_was_set = true;
+                  elseif (fg_was_set)
+                    fprintf (plot_stream, "unset obj 2\n");
+                    fg_is_set = false;
+                    fg_was_set = false;
                   else
                     fg_is_set = false;
                   endif
@@ -152,12 +158,12 @@
                   ## to __go_draw_axes__
                   hlegend = [];
                   fkids = get (h, "children");
-                  for j = 1 : numel(fkids)
+                  for j = 1 : numel (fkids)
                     if (ishandle (fkids (j))
                         && strcmp (get (fkids (j), "type"), "axes")
                         && (strcmp (get (fkids (j), "tag"), "legend")))
                       udata = get (fkids (j), "userdata");
-                      if (isscalar(udata.handle)
+                      if (isscalar (udata.handle)
                           && ! isempty (intersect (udata.handle, kids (i))))
                         hlegend = get (fkids (j));
                         break;
@@ -177,11 +183,17 @@
               endif
             case "uimenu"
               ## ignore uimenu objects
+              kids(i) = [];
             otherwise
               error ("__go_draw_figure__: unknown object class, %s", type);
           endswitch
         endfor
-        fputs (plot_stream, "\nunset multiplot;\n");
+        if (isempty (kids))
+          fputs (plot_stream, "\nreset; clear;\n");
+          fflush (plot_stream);
+        else
+          fputs (plot_stream, "\nunset multiplot;\n");
+        endif
       else
         fputs (plot_stream, "\nreset; clear;\n");
         fflush (plot_stream);
--- a/scripts/plot/private/__interp_cube__.m
+++ b/scripts/plot/private/__interp_cube__.m
@@ -23,7 +23,7 @@
 ## Undocumented internal function.
 ## @end deftypefn
 
-function [Vxyz, idx, frac] = __interp_cube__(x, y, z, val, v, req = "values" )
+function [Vxyz, idx, frac] = __interp_cube__ (x, y, z, val, v, req = "values" )
   if (ismatrix (x) && ndims (x) == 3 && ismatrix (y) && ndims (y) == 3 ...
        && ismatrix (z) && ndims (z) == 3 && size_equal (x, y, z, val))
     x = squeeze (x(1,:,1))(:);
@@ -34,12 +34,12 @@
     y = y(:);
     z = z(:);
   else
-    error("__interp_cube__: X, Y, Z have wrong dimensions");
+    error ("__interp_cube__: X, Y, Z have wrong dimensions");
   endif
   if (size (val) != [length(x), length(y), length(z)])
     error ("__interp_cube__: VAL has wrong dimensions");
   endif
-  if (size (v, 2) != 3)
+  if (columns (v) != 3)
     error ( "v has to be N*3 matrix");
   endif
   if (!ischar (req))
@@ -101,7 +101,7 @@
   endswitch
 endfunction
 
-function [Vxyz, idx, frac] = interp_cube_trilin(x, y, z, val, v)
+function [Vxyz, idx, frac] = interp_cube_trilin (x, y, z, val, v)
   [idx, frac] = cube_idx (x(:), y(:), z(:), v);
   sval = size (val);
   i000 = sub2ind (sval, idx(:, 1), idx(:, 2), idx(:, 3));
@@ -126,7 +126,7 @@
     val( i111 ) .* Bx .* By .* Bz;
 endfunction
 
-function [Dx, Dy, Dz, idx, frac] = interp_cube_trilin_grad(x, y, z, val, v)
+function [Dx, Dy, Dz, idx, frac] = interp_cube_trilin_grad (x, y, z, val, v)
   [idx, frac] = cube_idx (x(:), y(:), z(:), v);
   sval = size (val);
   i000 = sub2ind (sval, idx(:, 1), idx(:, 2), idx(:, 3));
@@ -169,7 +169,7 @@
     val( i111 ) .* Bx .* By;
 endfunction
 
-function [idx, frac] = cube_idx(x, y, z, v)
+function [idx, frac] = cube_idx (x, y, z, v)
   idx = zeros (size (v));
   frac = zeros (size (v));
   idx(:, 2) = lookup (x(2:end-1), v(:, 1)) + 1;
--- a/scripts/plot/private/__line__.m
+++ b/scripts/plot/private/__line__.m
@@ -35,8 +35,8 @@
 
   nvargs = numel (varargin);
 
-  if (nvargs > 1 && isnumeric (varargin{1}) && isnumeric (varargin{2}))
-    if (nvargs > 2 && isnumeric (varargin{3}))
+  if (nvargs > 1 && ! ischar (varargin{1}) && ! ischar (varargin{2}))
+    if (nvargs > 2 && ! ischar (varargin{3}))
       num_data_args = 3;
     else
       num_data_args = 2;
@@ -46,7 +46,15 @@
   endif
 
   if (num_data_args > 0 && ! size_equal (varargin{1:num_data_args}))
-    error ("line: number of X, Y, and Z points must be equal");
+    n = 1:num_data_args;
+    m = cellfun (@numel, varargin(1:num_data_args));
+    [~, m] = max (m);
+    b = ones (size (varargin{m(1)}));
+    try
+      varargin(n) = cellfun (@(x) bsxfun (@times, b, x), varargin(n), "uniformoutput", false);
+    catch
+      error ("line: number of X, Y, and Z points must be equal");
+    end_try_catch
   endif
 
   if (rem (nvargs - num_data_args, 2) != 0)
@@ -90,11 +98,14 @@
   data = cell (1, 3);
 
   if (num_data_args > 1)
-    data(1) = varargin{1};
-    data(2) = varargin{2};
-    if (num_data_args == 3)
-      data(3) = varargin{3};
-    endif
+    data(1:num_data_args) = varargin(1:num_data_args);
+    for i = 1:num_data_args
+      if (islogical (data{i}))
+        data(i) = double (data{i});
+      elseif (iscomplex (data{i}))
+        data(i) = real (data{i});
+      endif
+    endfor
   endif
 
   data_args = reshape ({"xdata", "ydata", "zdata"; data{:}}, [1, 6]);
--- a/scripts/plot/private/__marching_cube__.m
+++ b/scripts/plot/private/__marching_cube__.m
@@ -169,13 +169,13 @@
     if (calc_cols)
       pp(id__, 1:5, jj) = [vertex_interp(iso, xx(id1), yy(id1), zz(id1), ...
         xx(id2), yy(id2), zz(id2), c(id1), c(id2), colors(id1), colors(id2)), ...
-        (1:size (id_, 1))' + ix_offset ];
+        (1:rows (id_))' + ix_offset ];
     else
       pp(id__, 1:4, jj) = [vertex_interp(iso, xx(id1), yy(id1), zz(id1), ...
         xx(id2), yy(id2), zz(id2), c(id1), c(id2)), ...
-        (1:size (id_, 1))' + ix_offset ];
+        (1:rows (id_))' + ix_offset ];
     endif
-    ix_offset += size (id_, 1);
+    ix_offset += rows (id_);
   endfor
 
   ## phase III: calculate the triangulation from the point list
@@ -183,7 +183,7 @@
   tri = tri_table(cc(id)+1, :);
   for jj=1:3:15
     id_ = find (tri(:, jj)>0);
-    p = [id_, lindex*ones(size (id_, 1), 1),tri(id_, jj:jj+2)];
+    p = [id_, lindex*ones(rows (id_), 1),tri(id_, jj:jj+2)];
     if (!isempty (p))
       p1 = sub2ind (size (pp), p(:,1), p(:,2), p(:,3));
       p2 = sub2ind (size (pp), p(:,1), p(:,2), p(:,4));
@@ -205,7 +205,7 @@
   endfor
 endfunction
 
-function p = vertex_interp(isolevel,p1x, p1y, p1z,...
+function p = vertex_interp (isolevel,p1x, p1y, p1z,...
   p2x, p2y, p2z,valp1,valp2, col1, col2)
 
   if (nargin == 9)
@@ -235,7 +235,7 @@
   endif
 endfunction
 
-function [edge_table, tri_table] = init_mc()
+function [edge_table, tri_table] = init_mc ()
   edge_table = [
   0x0  , 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, ...
   0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, ...
--- a/scripts/plot/private/__next_line_style__.m
+++ b/scripts/plot/private/__next_line_style__.m
@@ -41,7 +41,7 @@
       elseif (reset || isempty (style_rotation))
         style_rotation = get (gca (), "linestyleorder");
         if (ischar (style_rotation))
-          style_rotation = strsplit (style_rotation, "|");
+          style_rotation = strsplit (style_rotation, "|", false);
         endif
         num_styles = length (style_rotation);
         style_index = 1;
--- a/scripts/plot/private/__patch__.m
+++ b/scripts/plot/private/__patch__.m
@@ -40,12 +40,12 @@
   elseif (isstruct (varargin{1}))
     if (isfield (varargin{1}, "vertices") && isfield (varargin{1}, "faces"))
       args{1} = "faces";
-      args{2} = getfield(varargin{1}, "faces");
+      args{2} = getfield (varargin{1}, "faces");
       args{3} = "vertices";
-      args{4} = getfield(varargin{1}, "vertices");
+      args{4} = getfield (varargin{1}, "vertices");
       args{5} = "facevertexcdata";
       if (isfield (varargin{1}, "facevertexcdata"))
-        args{6} = getfield(varargin{1}, "facevertexcdata");
+        args{6} = getfield (varargin{1}, "facevertexcdata");
       else
         args{6} = [];
       endif
@@ -97,7 +97,7 @@
         if (isnumeric (c))
           if (isvector (c) && numel (c) == numel (x))
             c = c(:);
-          elseif (size (c, 1) != numel (x) && size (c, 2) == numel (x))
+          elseif (rows (c) != numel (x) && columns (c) == numel (x))
             c = c.';
           endif
         endif
@@ -111,7 +111,7 @@
 
       if (isnumeric (c))
 
-        if (ndims (c) == 3 && size (c, 2) == 1)
+        if (ndims (c) == 3 && columns (c) == 1)
           c = permute (c, [1, 3, 2]);
         endif
 
@@ -136,14 +136,14 @@
           args{10} = [];
         elseif (ndims (c) == 3 && size (c, 3) == 3)
           ## CDATA is specified as RGB data
-          if ((size (c, 1) == 1 && size (c, 2) == 1) ...
-              || (size (c, 1) == 1 && size (c, 2) == columns (x)))
+          if ((rows (c) == 1 && columns (c) == 1) ...
+              || (rows (c) == 1 && columns (c) == columns (x)))
             ## Single patch color or per-face color
             args{7} = "facecolor";
             args{8} = "flat";
             args{9} = "cdata";
             args{10} = c;
-          elseif (size (c, 1) == rows (x) && size (c, 2) == columns (x))
+          elseif (rows (c) == rows (x) && columns (c) == columns (x))
             ## Per-vertex color
             args{7} = "facecolor";
             args{8} = "interp";
@@ -209,7 +209,7 @@
   endif
 endfunction
 
-function args = delfields(args, flds)
+function args = delfields (args, flds)
   idx = cellfun (@(x) any (strcmpi (x, flds)), args);
   if (rows (idx) == 1)
     idx = idx | [false, idx(1:end-1)];
@@ -237,13 +237,13 @@
     vert = args {idx};
   endif
   idx = find (strcmpi (args, "facevertexcdata"), 1, "last") + 1;
-  if (isempty(idx) || idx > nargs)
+  if (isempty (idx) || idx > nargs)
     fvc = [];
   else
     fvc = args {idx};
   endif
   idx = find (strcmpi (args, "facecolor"), 1, "last") + 1;
-  if (isempty(idx) || idx > nargs)
+  if (isempty (idx) || idx > nargs)
     if (!isempty (fvc))
       fc = "flat";
     else
@@ -252,7 +252,7 @@
     args = {"facecolor", fc, args{:}};
   endif
 
-  nc = size (faces, 1);
+  nc = rows (faces);
   idx = faces .';
   t1 = isnan (idx);
   for i = find (any (t1))
@@ -261,22 +261,22 @@
   endfor
   x = reshape (vert(:,1)(idx), size (idx));
   y = reshape (vert(:,2)(idx), size (idx));
-  if (size(vert,2) > 2)
+  if (columns (vert) > 2)
     z = reshape (vert(:,3)(idx), size (idx));
   else
     z = [];
   endif
 
-  if (size(fvc, 1) == nc || size (fvc, 1) == 1)
+  if (rows (fvc) == nc || rows (fvc) == 1)
     c = reshape (fvc, [1, size(fvc)]);
   else
-    if (size(fvc, 2) == 3)
-      c = cat(3, reshape (fvc(idx, 1), size(idx)),
-              reshape (fvc(idx, 2), size(idx)),
-              reshape (fvc(idx, 3), size(idx)));
+    if (columns (fvc) == 3)
+      c = cat (3, reshape (fvc(idx, 1), size (idx)),
+               reshape (fvc(idx, 2), size (idx)),
+               reshape (fvc(idx, 3), size (idx)));
     elseif (isempty (fvc))
       c = [];
-    else ## if (size (fvc, 2) == 1)
+    else ## if (columnns (fvc) == 1)
       c = permute (fvc(faces), [2, 1]);
     endif
   endif
@@ -301,19 +301,19 @@
     y = args {idx};
   endif
   idx = find (strcmpi (args, "zdata"), 1, "last") + 1;
-  if (isempty(idx) || idx > nargs)
+  if (isempty (idx) || idx > nargs)
     z = [];
   else
     z = args {idx};
   endif
   idx = find (strcmpi (args, "cdata"), 1, "last") + 1;
-  if (isempty(idx) || idx > nargs)
+  if (isempty (idx) || idx > nargs)
     c = [];
   else
     c = args {idx};
   endif
   idx = find (strcmpi (args, "facecolor"), 1, "last") + 1;
-  if (isempty(idx) || idx > nargs)
+  if (isempty (idx) || idx > nargs)
     if (!isempty (c))
       fc = "flat";
     else
@@ -326,17 +326,17 @@
   if (nr == 1 && nc > 1)
     nr = nc;
     nc = 1;
-  end
+  endif
   if (!isempty (z))
     vert = [x(:), y(:), z(:)];
   else
     vert = [x(:), y(:)];
   endif
-  faces = reshape (1:numel(x), nr, nc);
+  faces = reshape (1:numel (x), nr, nc);
   faces = faces';
 
   if (ndims (c) == 3)
-    fvc = reshape (c, size (c, 1) * size (c, 2), size(c, 3));
+    fvc = reshape (c, rows (c) * columns (c), size (c, 3));
   else
     fvc = c(:);
   endif
--- a/scripts/plot/private/__pie__.m
+++ b/scripts/plot/private/__pie__.m
@@ -117,15 +117,15 @@
     if (strncmp (caller, "pie3", 4))
       ln = length (xn);
       zlvl = 0.35;
-      sx = repmat (xoff + [0, - sind(xn), 0], [2 1]);
-      sy = repmat (yoff + [0, cosd(xn), 0], [2 1]);
+      sx = repmat (xoff + [0, -sind(xn), 0], [2, 1]);
+      sy = repmat (yoff + [0, cosd(xn), 0], [2, 1]);
       sz = [zeros(1, ln + 2); zlvl * ones(1, ln + 2)];
       sc = i * ones (size (sz));
 
       hlist = [hlist;
-        patch(xoff + [0, - sind(xn)], yoff + [0, cosd(xn)], zeros (1, ln + 1), i);
+        patch(xoff + [0, -sind(xn)], yoff + [0, cosd(xn)], zeros (1, ln + 1), i);
         surface(sx, sy, sz, sc);
-        patch(xoff + [0, - sind(xn)], yoff + [0, cosd(xn)], zlvl * ones (1, ln + 1), i);
+        patch(xoff + [0, -sind(xn)], yoff + [0, cosd(xn)], zlvl * ones (1, ln + 1), i);
         text(xt, yt, zlvl, labels{i})];
 
     elseif (strncmp (caller, "pie", 3))
@@ -135,7 +135,7 @@
         align = "right";
       endif
 
-      hlist = [hlist; patch(xoff + [0, - sind(xn)], yoff + [0, cosd(xn)], i);
+      hlist = [hlist; patch(xoff + [0, -sind(xn)], yoff + [0, cosd(xn)], i);
                text(xt, yt, labels{i}, "horizontalalignment", align)];
 
     else
@@ -143,7 +143,7 @@
     endif
   endfor
 
-  addlistener(gca, "view", {@update_text_pos, hlist});
+  addlistener (gca, "view", {@update_text_pos, hlist});
 
   if (strncmp (caller, "pie3", 4))
     axis ([-1.25, 1.25, -1.25, 1.25, -0.05, 0.4], "equal", "off");
--- a/scripts/plot/private/__plt__.m
+++ b/scripts/plot/private/__plt__.m
@@ -37,8 +37,8 @@
     properties = {};
 
     hlegend = [];
-    fkids = get (gcf(), "children");
-    for i = 1 : numel(fkids)
+    fkids = get (gcf (), "children");
+    for i = 1 : numel (fkids)
       if (ishandle (fkids (i)) && strcmp (get (fkids (i), "type"), "axes")
           && (strcmp (get (fkids (i), "tag"), "legend")))
         udata = get (fkids (i), "userdata");
@@ -132,7 +132,7 @@
     endwhile
 
     if (setlgnd)
-      legend (gca(), hlgnd, tlgnd);
+      legend (gca (), hlgnd, tlgnd);
     endif
   else
     error ("__plt__: invalid number of arguments");
@@ -177,14 +177,17 @@
   [nr, nc] = size (x1);
   if (nr == 1)
     x1 = x1.';
-    tmp = nr;
-    nr = nc;
-    nc = tmp;
+    [nr, nc] = deal (nc, nr);   # Swap rows and columns
   endif
-  x1_i = imag (x1);
-  if (any (any (x1_i)))
-    x2 = x1_i;
-    x1 = real (x1);
+  if (iscomplex (x1))
+    x1_i = imag (x1);
+    if (any ((x1_i(:))))
+      x2 = x1_i;
+      x1 = real (x1);
+    else
+      x2 = x1;
+      x1 = (1:nr)';
+    endif
   else
     x2 = x1;
     x1 = (1:nr)';
@@ -212,11 +215,15 @@
     error ("__plt1__: options must be a struct array");
   endif
 
-  if (any (any (imag (x1))))
+  if (islogical (x1))
+    x1 = int8 (x1);
+  elseif (iscomplex ((x1)))
     x1 = real (x1);
   endif
 
-  if (any (any (imag (x2))))
+  if (islogical (x2))
+    x2 = int8 (x2);
+  elseif (iscomplex (x2))
     x2 = real (x2);
   endif
 
--- a/scripts/plot/private/__pltopt__.m
+++ b/scripts/plot/private/__pltopt__.m
@@ -206,7 +206,7 @@
       elseif (topt == ";")
         t = index (opt(2:end), ";");
         if (t)
-          options.key = undo_string_escapes (opt(2:t));
+          options.key = opt(2:t);
           n = t+1;
         else
           if (err_on_invalid)
--- a/scripts/plot/private/__print_parse_opts__.m
+++ b/scripts/plot/private/__print_parse_opts__.m
@@ -17,7 +17,7 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {@var{args} =} __print_parse_opts__ (@var{propname}, @var{propvalue})
+## @deftypefn  {Function File} {@var{args} =} __print_parse_opts__ (@var{propname}, @var{propvalue})
 ## @deftypefnx {Function File} {@var{args} =} __print_parse_opts__ (@var{struct})
 ## Undocumented internal function.
 ## @end deftypefn
@@ -36,6 +36,7 @@
   arg_st.fig2dev_binary = __quote_path__ (__find_binary__ ("fig2dev"));
   arg_st.fontsize = "";
   arg_st.font = "";
+  arg_st.scalefontsize = 1;
   arg_st.force_solid = 0; # 0=default, -1=dashed, +1=solid
   arg_st.formatted_for_printing = false;
   arg_st.ghostscript.binary = __quote_path__ (__ghostscript_binary__ ());
@@ -48,6 +49,8 @@
   arg_st.ghostscript.pageoffset = [];
   arg_st.ghostscript.resolution = 150;
   arg_st.ghostscript.antialiasing = false;
+  arg_st.ghostscript.antialiasing_textalphabits = 4;
+  arg_st.ghostscript.antialiasing_graphicsalphabits = 4;
   arg_st.loose = false;
   arg_st.lpr_binary = __quote_path__ (__find_binary__ ("lpr"));
   arg_st.name = "";
@@ -74,7 +77,7 @@
     varargin(1) = [];
   endif
 
-  for i = 1:numel(varargin)
+  for i = 1:numel (varargin)
     arg = strtrim (varargin{i});
     if (ischar (arg))
       if (strcmp (arg, "-color"))
@@ -117,6 +120,20 @@
         arg_st.fig2dev_binary = arg{10:end};
       elseif (strncmp (arg, "-PSTOEDIT:", 9))
         arg_st.pstoedit_binary = arg{10:end};
+      elseif (strncmpi (arg, "-textalphabits=", 15))
+        n = find (arg == "=");
+        if (! isempty (n) && n == numel (arg) - 1 && ismember (arg(end), "124"))
+          arg_st.ghostscript.antialiasing_textalphabits = str2num (arg(end));
+        else
+          error ("print: improper syntax, or value, for TextAlphaBits");
+        endif
+      elseif (strncmpi (arg, "-graphicsalphabits=", 19))
+        n = find (arg == "=");
+        if (! isempty (n) && n == numel (arg) - 1 && ismember (arg(end), "124"))
+          arg_st.ghostscript.antialiasing_graphicsalphabits = str2num (arg(end));
+        else
+          error ("print: improper syntax, or value, for GraphicsAlphaBits");
+        endif
       elseif ((length (arg) > 2) && arg(1:2) == "-G")
         arg_st.ghostscript.binary = file_in_path (getenv ("PATH"), arg(3:end));
         if (isempty (arg_st.ghostscript.binary))
@@ -142,7 +159,7 @@
       elseif (length (arg) >= 1 && arg(1) == "-")
         error ("print: unknown option '%s'", arg);
       elseif (length (arg) > 0)
-        arg_st.name = arg;
+        arg_st.name = tilde_expand (arg);
       endif
     elseif (isfigure (arg))
       arg_st.figure = arg;
@@ -326,8 +343,12 @@
       arg_st.ghostscript.pageoffset = paperposition(1:2);
     endif
   else
-    ## Convert canvas size to points from pixles.
-    arg_st.canvas_size = arg_st.canvas_size * 72 / arg_st.ghostscript.resolution;
+    ## Convert canvas size to points from pixels.
+    if (! isempty (arg_st.fontsize))
+      ## Work around the eps bbox having whole numbers (both gnuplot & gl2ps).
+      arg_st.scalefontsize = arg_st.ghostscript.resolution / 72;
+    endif
+    arg_st.ghostscript.resolution = 72;
     arg_st.ghostscript.papersize = arg_st.canvas_size;
     arg_st.ghostscript.epscrop = true;
     arg_st.ghostscript.pageoffset = [0, 0];
@@ -366,7 +387,7 @@
 %! assert (opts.use_color, 1);
 %! assert (opts.send_to_printer, true);
 %! assert (opts.canvas_size, [576, 432]);
-%! assert (opts.ghostscript.device, "pswrite")
+%! assert (opts.ghostscript.device, "pswrite");
 
 #%!test
 %! opts = __print_parse_opts__ ("test.pdf", "-S640,480");
@@ -378,7 +399,7 @@
 %! assert (opts.send_to_printer, true);
 %! assert (opts.use_color, 1);
 %! assert (opts.append_to_file, false);
-%! assert (opts.ghostscript.device, "pswrite")
+%! assert (opts.ghostscript.device, "pswrite");
 %! assert (opts.ghostscript.epscrop, false);
 
 #%!test
@@ -386,13 +407,13 @@
 %! assert (opts.tight_flag, true);
 %! assert (opts.send_to_printer, true);
 %! assert (opts.use_color, -1);
-%! assert (opts.ghostscript.device, "")
+%! assert (opts.ghostscript.device, "");
 
 #%!test
 %! opts = __print_parse_opts__ ("-djpg", "foobar", "-mono", "-loose");
-%! assert (opts.devopt, "jpeg")
-%! assert (opts.name, "foobar.jpg")
-%! assert (opts.ghostscript.device, "jpeg")
+%! assert (opts.devopt, "jpeg");
+%! assert (opts.name, "foobar.jpg");
+%! assert (opts.ghostscript.device, "jpeg");
 %! assert (opts.ghostscript.epscrop, true);
 %! assert (opts.ghostscript.papersize, "");
 %! assert (opts.ghostscript.pageoffset, [0, 0]);
@@ -402,24 +423,33 @@
 
 #%!test
 %! opts = __print_parse_opts__ ("-ddeskjet", "foobar", "-mono", "-Pmyprinter");
-%! assert (opts.ghostscript.output, "foobar.deskjet")
-%! assert (opts.ghostscript.device, "deskjet")
-%! assert (opts.devopt, "deskjet")
+%! assert (opts.ghostscript.output, "foobar.deskjet");
+%! assert (opts.ghostscript.device, "deskjet");
+%! assert (opts.devopt, "deskjet");
 %! assert (opts.send_to_printer, true);
 %! assert (opts.printer, "-Pmyprinter");
 %! assert (opts.use_color, -1);
 
 #%!test
 %! opts = __print_parse_opts__ ("-f5", "-dljet3");
-%! assert (opts.ghostscript.device, "ljet3")
-%! assert (strfind (opts.ghostscript.output, ".ljet3"))
-%! assert (opts.devopt, "ljet3")
+%! assert (opts.ghostscript.device, "ljet3");
+%! assert (strfind (opts.ghostscript.output, ".ljet3"));
+%! assert (opts.devopt, "ljet3");
 %! assert (opts.send_to_printer, true);
-%! assert (opts.figure, 5)
+%! assert (opts.figure, 5);
 
 function cmd = __quote_path__ (cmd)
-  if (any (cmd == " ") && ! (cmd(1) == """" && cmd(end) == """"))
-    cmd = strcat ("""", strrep (cmd, """", """"""), """");
+  if (! isempty (cmd))
+    is_quoted = all (cmd([1, end]) == "'");
+    if (! is_quoted)
+      dos_shell = ! isunix () && ispc ();
+      if (dos_shell && any (cmd == "/"))
+        cmd = strrep (cmd, "/", "\\");
+      endif
+      if (any (cmd == " "))
+        cmd = strcat ('"', strrep (cmd, '"', '""') ,'"');
+      endif
+    endif
   endif
 endfunction
 
@@ -539,7 +569,7 @@
   ##         Papersize is tall when portrait,and wide when landscape.
   if ((papersize(1) > papersize(2) && strcmpi (paperorientation, "portrait"))
       || (papersize(1) < papersize(2) && strcmpi (paperorientation, "landscape")))
-    papersize = papersize ([2,1]);
+    papersize = papersize([2,1]);
     paperposition = paperposition([2,1,4,3]);
   endif
 
--- a/scripts/plot/private/__quiver__.m
+++ b/scripts/plot/private/__quiver__.m
@@ -43,9 +43,9 @@
     v = varargin{ioff++};
     if (is3d)
       w = varargin{ioff++};
-      [x, y, z] = meshgrid (1:size(u,2), 1:size(u,1), 1:max(size(w)));
+      [x, y, z] = meshgrid (1:columns (u), 1:rows (u), 1:max (size (w)));
     else
-      [x, y] = meshgrid (1:size(u,2), 1:size(u,1));
+      [x, y] = meshgrid (1:columns (u), 1:rows (u));
     endif
     if (nargin >= ioff && isnumeric (varargin{ioff})
         && isscalar (varargin{ioff}))
@@ -62,7 +62,7 @@
     if (is3d)
       w = varargin{ioff++};
       if (isvector (x) && isvector (y) && isvector (z)
-          && (! isvector (u) || ! isvector (v) || ! isvector(w)))
+          && (! isvector (u) || ! isvector (v) || ! isvector (w)))
         [x, y, z] = meshgrid (x, y, z);
       endif
     else
@@ -112,10 +112,10 @@
     else
       [nx, ny] = size (x);
     endif
-    dx = (max(x(:)) - min(x(:))) ./ nx;
-    dy = (max(y(:)) - min(y(:))) ./ ny;
+    dx = (max (x(:)) - min (x(:))) ./ nx;
+    dy = (max (y(:)) - min (y(:))) ./ ny;
     if (is3d)
-      dz = (max(z(:)) - min(z(:))) ./ max (size (z));
+      dz = (max (z(:)) - min (z(:))) ./ max (size (z));
       len = max (sqrt (u(:).^2 + v(:).^2 + w(:).^2));
     else
       dz = 0;
@@ -124,7 +124,7 @@
     if (len > 0)
       sd = sqrt (dx.^2 + dy.^2 + dz.^2) / len;
       if (sd != 0)
-        s = sqrt(2) * autoscale * sd;
+        s = sqrt (2) * autoscale * sd;
       else # special case of identical points with multiple vectors
         s = autoscale;
       endif
@@ -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)
@@ -349,10 +356,10 @@
     else
       [nx, ny] = size (x);
     endif
-    dx = (max(x(:)) - min(x(:))) ./ nx;
-    dy = (max(y(:)) - min(y(:))) ./ ny;
+    dx = (max (x(:)) - min (x(:))) ./ nx;
+    dy = (max (y(:)) - min (y(:))) ./ ny;
     if (is3d)
-      dz = (max(z(:)) - min(z(:))) ./ max (size (z));
+      dz = (max (z(:)) - min (z(:))) ./ max (size (z));
       len = max (sqrt (u(:).^2 + v(:).^2 + w(:).^2));
     else
       dz = 0;
@@ -361,7 +368,7 @@
     if (len > 0)
       sd = sqrt (dx.^2 + dy.^2 + dz.^2) / len;
       if (sd != 0)
-        s *= sqrt(2) * sd;
+        s *= sqrt (2) * sd;
       endif
       u = s * u;
       v = s * v;
--- a/scripts/plot/private/__scatter__.m
+++ b/scripts/plot/private/__scatter__.m
@@ -32,13 +32,13 @@
 
   if (nd == 3)
     z = varargin{6}(:);
-    idx = isnan(x) | isnan (y) | isnan (z);
+    idx = isnan (x) | isnan (y) | isnan (z);
     x (idx) = [];
     y (idx) = [];
     z (idx) = [];
     istart = 7;
   else
-    idx = isnan(x) | isnan (y);
+    idx = isnan (x) | isnan (y);
     x (idx) = [];
     y (idx) = [];
     z = zeros (length (x), 0);
@@ -111,7 +111,7 @@
   endwhile
 
   if (isempty (c))
-    c = __next_line_color__();
+    c = __next_line_color__ ();
   endif
 
   hg = hggroup ();
@@ -140,7 +140,7 @@
     ## For small number of points, we'll construct an object for each point.
 
     if (numel (s) == 1)
-      s = repmat (s, numel(x), 1);
+      s = repmat (s, numel (x), 1);
     endif
 
     if (one_explicit_color)
@@ -222,11 +222,11 @@
   if (! ischar (c) && rows (c) > 1)
     ax = get (hg, "parent");
     clim = get (ax, "clim");
-    if (min(c(:)) < clim(1))
-      clim(1) = min(c(:));
+    if (min (c(:)) < clim(1))
+      clim(1) = min (c(:));
       set (ax, "clim", clim);
     endif
-    if (max(c(:)) > clim(2))
+    if (max (c(:)) > clim(2))
       set (ax, "clim", [clim(1), max(c(:))]);
     endif
   endif
@@ -259,7 +259,7 @@
 
 endfunction
 
-function h = render_size_color(hg, vert, s, c, marker, filled, isflat)
+function h = render_size_color (hg, vert, s, c, marker, filled, isflat)
   if (isscalar (s))
     x = vert(:,1);
     y = vert(:,2);
@@ -273,7 +273,7 @@
     if (ischar (c) || ! isflat || gnuplot_hack)
       if (filled)
         h = __go_patch__ (hg, "xdata", x, "ydata", y, "zdata", z,
-                          "faces", 1:numel(x), "vertices", vert,
+                          "faces", 1:numel (x), "vertices", vert,
                           "facecolor", "none", "edgecolor", "none",
                           "marker", marker,
                           "markeredgecolor", "none",
@@ -281,7 +281,7 @@
                           "markersize", s, "linestyle", "none");
       else
         h = __go_patch__ (hg, "xdata", x, "ydata", y, "zdata", z,
-                          "faces", 1:numel(x), "vertices", vert,
+                          "faces", 1:numel (x), "vertices", vert,
                           "facecolor", "none", "edgecolor", "none",
                           "marker", marker,
                           "markeredgecolor", c(1,:),
@@ -291,7 +291,7 @@
     else
       if (filled)
         h = __go_patch__ (hg, "xdata", x, "ydata", y, "zdata", z,
-                          "faces", 1:numel(x), "vertices", vert,
+                          "faces", 1:numel (x), "vertices", vert,
                           "facecolor", "none", "edgecolor", "none",
                           "marker", marker, "markersize", s,
                           "markeredgecolor", "none",
@@ -300,7 +300,7 @@
                           "linestyle", "none");
       else
         h = __go_patch__ (hg, "xdata", x, "ydata", y, "zdata", z,
-                          "faces", 1:numel(x), "vertices", vert,
+                          "faces", 1:numel (x), "vertices", vert,
                           "facecolor", "none", "edgecolor", "none",
                           "marker", marker, "markersize", s,
                           "markeredgecolor", "flat",
@@ -362,14 +362,14 @@
     if (isempty (z1))
       for i = 1 : length (hlist)
         set (hlist(i), "vertices", [x1(i), y1(i)], "cdata",
-             reshape(c1(i,:),[1, size(c1)(2:end)]),
+             reshape (c1(i,:),[1, size(c1)(2:end)]),
              "facevertexcdata", c1(i,:),
              "markersize", size1(i));
       endfor
     else
       for i = 1 : length (hlist)
         set (hlist(i), "vertices", [x1(i), y1(i), z1(i)], "cdata",
-             reshape(c1(i,:),[1, size(c1)(2:end)]),
+             reshape (c1(i,:),[1, size(c1)(2:end)]),
              "facevertexcdata", c1(i,:),
              "markersize", size1(i));
       endfor
--- a/scripts/plot/private/__stem__.m
+++ b/scripts/plot/private/__stem__.m
@@ -147,7 +147,7 @@
       if (! isempty (args))
         set (hg, args{:});
       endif
-      if (i == 1 && !isempty(h_baseline))
+      if (i == 1 && ! isempty (h_baseline))
         set (h_baseline, "parent", get (hg, "parent"));
       endif
     endfor
@@ -296,7 +296,7 @@
           error ("stem: X and Y must be matrices");
         endif
       endif
-    endif # if ischar(varargin{2})
+    endif # if ischar (varargin{2})
     if (! have_z)
       ## varargin{3} must be char.
       ## Check for "fill.
@@ -436,7 +436,7 @@
   [lc, ls, mc, ms] = set_default_values ();
   ## Parse the line specifier string.
   cur_props = __pltopt__ ("stem", str, false);
-  for i = 1:length(cur_props)
+  for i = 1:length (cur_props)
     if (isfield (cur_props(i), "color") && ! isempty (cur_props(i).color)); # means line color
       mc = lc = cur_props(i).color;
     elseif (isfield (cur_props(i), "linestyle"))
@@ -508,7 +508,7 @@
   endif
 
   kids = get (h, "children");
-  yt = get(h, "ydata")(:)';
+  yt = get (h, "ydata")(:)';
   ny = length (yt);
   yt = [b0 * ones(1, ny); yt; NaN(1, ny)](:);
   set (kids(2), "ydata", yt);
@@ -532,7 +532,7 @@
 
   if (!isempty (z) && size_equal (x, y, z))
     error ("stem3: inconsistent size of x, y and z");
-  elseif (numel(x) != numel (y))
+  elseif (numel (x) != numel (y))
     error ("stem: inconsistent size of x and y");
   else
     bl = get (h, "basevalue");
--- a/scripts/plot/private/__tight_eps_bbox__.m
+++ b/scripts/plot/private/__tight_eps_bbox__.m
@@ -58,12 +58,12 @@
     looking_for_bbox = true;
     while (looking_for_bbox)
       current_line = fgetl (fid);
-      if (strncmpi (current_line, box_string, numel(box_string)))
+      if (strncmpi (current_line, box_string, numel (box_string)))
         line_length = numel (current_line);
         num_spaces = line_length - numel (tight_bbox_line);
         if (numel (current_line) >= numel (tight_bbox_line))
           new_line = tight_bbox_line;
-          new_line(end+1:numel(current_line)) = " ";
+          new_line(end+1:numel (current_line)) = " ";
           bbox_replaced = true;
           ## Back up to the beginning of the line (include EOL characters).
           if (ispc ())
@@ -113,12 +113,12 @@
 function bbox_line = get_bbox (lines)
   box_string = "%%BoundingBox:";
   pattern = strcat (box_string, "[^%]*");
-  pattern = pattern(1:find(double(pattern)>32, 1, "last"));
+  pattern = pattern(1:find (double (pattern) > 32, 1, "last"));
   bbox_line = regexp (lines, pattern, "match");
   if (iscell (bbox_line))
     bbox_line = bbox_line{1};
   endif
   ## Remove the EOL characters.
-  bbox_line(double(bbox_line)<32) = "";
+  bbox_line(double (bbox_line) < 32) = "";
 endfunction
 
--- a/scripts/plot/private/__uigetdir_fltk__.m
+++ b/scripts/plot/private/__uigetdir_fltk__.m
@@ -25,7 +25,7 @@
 
 function dirname = __uigetdir_fltk__ (start_path, dialog_title)
 
-  if (exist("__fltk_uigetfile__") != 3)
+  if (exist ("__fltk_uigetfile__") != 3)
     error ("uigetdir: fltk graphics toolkit required");
   endif
 
--- a/scripts/plot/private/__uigetfile_fltk__.m
+++ b/scripts/plot/private/__uigetfile_fltk__.m
@@ -25,7 +25,7 @@
 
 function [retval, retpath, retindex] = __uigetfile_fltk__ (filters, title, defval, position, multiselect, defdir)
 
-  if (exist("__fltk_uigetfile__") != 3)
+  if (exist ("__fltk_uigetfile__") != 3)
     error ("uigetfile: fltk graphics toolkit required");
   endif
 
--- a/scripts/plot/private/__uiputfile_fltk__.m
+++ b/scripts/plot/private/__uiputfile_fltk__.m
@@ -25,7 +25,7 @@
 
 function [retval, retpath, retindex] = __uiputfile_fltk__ (filters, title, defval, position, tag, defdir)
 
-  if (exist("__fltk_uigetfile__") != 3)
+  if (exist ("__fltk_uigetfile__") != 3)
     error ("uiputfile: fltk graphics toolkit required");
   endif
 
--- a/scripts/plot/quiver.m
+++ b/scripts/plot/quiver.m
@@ -21,7 +21,7 @@
 ## @deftypefnx {Function File} {} quiver (@var{x}, @var{y}, @var{u}, @var{v})
 ## @deftypefnx {Function File} {} quiver (@dots{}, @var{s})
 ## @deftypefnx {Function File} {} quiver (@dots{}, @var{style})
-## @deftypefnx {Function File} {} quiver (@dots{}, 'filled')
+## @deftypefnx {Function File} {} quiver (@dots{}, "filled")
 ## @deftypefnx {Function File} {} quiver (@var{h}, @dots{})
 ## @deftypefnx {Function File} {@var{h} =} quiver (@dots{})
 ##
@@ -31,7 +31,7 @@
 ##
 ## If @var{x} and @var{y} are undefined they are assumed to be
 ## @code{(1:@var{m}, 1:@var{n})} where @code{[@var{m}, @var{n}] =
-## size(@var{u})}.
+## size (@var{u})}.
 ##
 ## The variable @var{s} is a scalar defining a scaling factor to use for
 ## the arrows of the field relative to the mesh spacing.  A value of 0
@@ -40,7 +40,7 @@
 ## The style to use for the plot can be defined with a line style @var{style}
 ## in a similar manner to the line styles used with the @code{plot} command.
 ## If a marker is specified then markers at the grid points of the vectors are
-## printed rather than arrows.  If the argument 'filled' is given then the
+## printed rather than arrows.  If the argument "filled" is given then the
 ## markers as filled.
 ##
 ## The optional return value @var{h} is a graphics handle to a quiver object.
@@ -83,17 +83,17 @@
 
 
 %!demo
-%! clf
+%! clf;
 %! [x,y] = meshgrid (1:2:20);
 %! h = quiver (x,y, sin (2*pi*x/10), sin (2*pi*y/10));
-%! set (h, "maxheadsize", 0.33);
+%! set (h, 'maxheadsize', 0.33);
 
 %!demo
-%! clf
-%! axis ("equal");
-%! x = linspace (0,3,80);
+%! clf;
+%! axis ('equal');
+%! x = linspace (0, 3, 80);
 %! y = sin (2*pi*x);
 %! theta = 2*pi*x + pi/2;
 %! quiver (x, y, sin (theta)/10, cos (theta)/10);
-%! hold on; plot(x,y,"r"); hold off;
+%! hold on; plot (x,y,'r'); hold off;
 
--- a/scripts/plot/quiver3.m
+++ b/scripts/plot/quiver3.m
@@ -21,7 +21,7 @@
 ## @deftypefnx {Function File} {} quiver3 (@var{x}, @var{y}, @var{z}, @var{u}, @var{v}, @var{w})
 ## @deftypefnx {Function File} {} quiver3 (@dots{}, @var{s})
 ## @deftypefnx {Function File} {} quiver3 (@dots{}, @var{style})
-## @deftypefnx {Function File} {} quiver3 (@dots{}, 'filled')
+## @deftypefnx {Function File} {} quiver3 (@dots{}, "filled")
 ## @deftypefnx {Function File} {} quiver3 (@var{h}, @dots{})
 ## @deftypefnx {Function File} {@var{h} =} quiver3 (@dots{})
 ##
@@ -31,7 +31,7 @@
 ##
 ## If @var{x}, @var{y} and @var{z} are undefined they are assumed to be
 ## @code{(1:@var{m}, 1:@var{n}, 1:@var{p})} where @code{[@var{m}, @var{n}] =
-## size(@var{u})} and @code{@var{p} = max (size (@var{w}))}.
+## size (@var{u})} and @code{@var{p} = max (size (@var{w}))}.
 ##
 ## The variable @var{s} is a scalar defining a scaling factor to use for
 ##  the arrows of the field relative to the mesh spacing.  A value of 0
@@ -40,7 +40,7 @@
 ## The style to use for the plot can be defined with a line style @var{style}
 ## in a similar manner to the line styles used with the @code{plot} command.
 ## If a marker is specified then markers at the grid points of the vectors are
-## printed rather than arrows.  If the argument 'filled' is given then the
+## printed rather than arrows.  If the argument "filled" is given then the
 ## markers as filled.
 ##
 ## The optional return value @var{h} is a graphics handle to a quiver object.
@@ -84,35 +84,38 @@
 
 endfunction
 
+
 %!demo
-%! clf
-%! colormap (jet (64));
+%! clf;
+%! colormap ('default');
 %! [x,y] = meshgrid (-1:0.1:1);
-%! z = sin (2*pi * sqrt (x.^2+y.^2));
-%! theta = 2*pi * sqrt (x.^2+y.^2) + pi/2;
+%! z = sin (2*pi * sqrt (x.^2 + y.^2));
+%! theta = 2*pi * sqrt (x.^2 + y.^2) + pi/2;
 %! quiver3 (x, y, z, sin (theta), cos (theta), ones (size (z)));
 %! hold on;
-%! mesh (x,y,z);
+%! mesh (x, y, z);
 %! hold off;
 
 %!demo
-%! clf
+%! clf;
+%! colormap ('default');
 %! [x, y, z] = peaks (25);
 %! surf (x, y, z);
 %! hold on;
 %! [u, v, w] = surfnorm (x, y, z / 10);
 %! h = quiver3 (x, y, z, u, v, w);
-%! set (h, "maxheadsize", 0.33);
+%! set (h, 'maxheadsize', 0.33);
 %! hold off;
 
 %!demo
-%! clf
+%! clf;
+%! colormap ('default');
 %! [x, y, z] = peaks (25);
 %! surf (x, y, z);
 %! hold on;
 %! [u, v, w] = surfnorm (x, y, z / 10);
 %! h = quiver3 (x, y, z, u, v, w);
-%! set (h, "maxheadsize", 0.33);
+%! set (h, 'maxheadsize', 0.33);
 %! hold off;
-%! shading interp
+%! shading interp;
 
--- a/scripts/plot/rectangle.m
+++ b/scripts/plot/rectangle.m
@@ -72,7 +72,7 @@
 
   while (iarg < length (varargin))
     arg = varargin{iarg};
-    if (ischar(arg))
+    if (ischar (arg))
       if (strcmpi (arg, "position"))
         pos = varargin{iarg+1};
         varargin(iarg:iarg+1) = [];
@@ -205,18 +205,18 @@
 
 
 %!demo
-%! clf
-%! axis equal
-%! rectangle ("Position", [0.05, 0.05, 0.9, 0.9], "Curvature", [0.5, 0.5]);
+%! clf;
+%! axis equal;
+%! rectangle ('Position', [0.05, 0.05, 0.9, 0.9], 'Curvature', [0.5, 0.5]);
 
 %!demo
-%! clf
-%! axis equal
-%! rectangle ("Position", [0.05, 0.05, 0.9, 0.4], "Curvature", 1.0);
+%! clf;
+%! axis equal;
+%! rectangle ('Position', [0.05, 0.05, 0.9, 0.4], 'Curvature', 1.0);
 
 %!demo
-%! clf
-%! axis equal
-%! h = rectangle ("Position", [0.05, 0.05, 0.9, 0.4], "Curvature",  1.0);
-%! set (h, "FaceColor", [0, 1, 0]);
+%! clf;
+%! axis equal;
+%! h = rectangle ('Position', [0.05, 0.05, 0.9, 0.4], 'Curvature', 1.0);
+%! set (h, 'FaceColor', [0, 1, 0]);
 
--- a/scripts/plot/refresh.m
+++ b/scripts/plot/refresh.m
@@ -19,24 +19,25 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {} refresh ()
 ## @deftypefnx {Function File} {} refresh (@var{h})
-## Refresh a figure, forcing it to be redrawn.  Called without an
-## argument the current figure is redrawn, otherwise the figure pointed
+## Refresh a figure, forcing it to be redrawn.  When called without an
+## argument the current figure is redrawn.  Otherwise, the figure pointed
 ## to by @var{h} is redrawn.
 ## @seealso{drawnow}
 ## @end deftypefn
 
 function refresh (h)
 
-  if (nargin == 1)
-    if (!ishandle (h) || !strcmp (get (h, "type"), "figure"))
-      error ("refresh: expecting argument to be a valid figure handle");
+  if (nargin > 1)
+    print_usage ();
+  elseif (nargin == 1)
+    if (! isfigure (h))
+      error ("refresh: H must be a valid figure handle");
     endif
-  elseif (nargin > 1)
-    print_usage ();
   else
     h = gcf ();
   endif
 
-  set(h,"__modified__", "on");
+  set (h, "__modified__", "on");
   drawnow ();
+
 endfunction
--- a/scripts/plot/refreshdata.m
+++ b/scripts/plot/refreshdata.m
@@ -82,7 +82,7 @@
   for i = 1 : numel (h)
     obj = get (h (i));
     fldnames = fieldnames (obj);
-    m = regexpi (fieldnames(obj), '^.+datasource$', "match");
+    m = regexpi (fieldnames (obj), '^.+datasource$', "match");
     idx = ! cellfun ("isempty", m);
     if (any (idx))
       tmp = m(idx);
@@ -103,15 +103,18 @@
       endif
     endfor
   endfor
+
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
 %! x = 0:0.1:10;
 %! y = sin (x);
-%! plot (x, y, "ydatasource", "y");
+%! plot (x, y, 'ydatasource', 'y');
 %! for i = 1 : 100
-%!   pause(0.1)
+%!   pause (0.1);
 %!   y = sin (x + 0.1 * i);
-%!   refreshdata(gcf(), "caller");
-%! endfor
+%!   refreshdata (gcf, 'caller');
+%! end
+
--- a/scripts/plot/ribbon.m
+++ b/scripts/plot/ribbon.m
@@ -23,7 +23,7 @@
 ## Plot a ribbon plot for the columns of @var{y} vs.  @var{x}.  The
 ## optional parameter @var{width} specifies the width of a single ribbon
 ## (default is 0.75).  If @var{x} is omitted, a vector containing the
-## row numbers is assumed (1:rows(Y)).
+## row numbers is assumed (1:rows (Y)).
 ##
 ## The optional return value @var{h} is a vector of graphics handles to
 ## the surface objects representing each ribbon.
@@ -31,9 +31,11 @@
 
 ## Author: Kai Habel <kai.habel at gmx.de>
 
-function h = ribbon (x, y, width)
+function h = ribbon (x, y, width = 0.75)
 
-  newplot ();
+  if (nargin < 1 || nargin > 3)
+    print_usage ();
+  endif
 
   if (nargin == 1)
     y = x;
@@ -42,54 +44,53 @@
     endif
     [nr, nc] = size (y);
     x = repmat ((1:nr)', 1, nc);
-    width = 0.75;
-  elseif (nargin == 2)
-    width = 0.75;
-  elseif (nargin != 3)
-    print_usage ();
   endif
 
   if (isvector (x) && isvector (y))
     if (length (x) != length (y))
-      error ("ribbon: in case of vectors, X and Y must have same length");
+      error ("ribbon: vectors X and Y must have the same length");
     else
       [x, y] = meshgrid (x, y);
     endif
   else
-    if (! size_equal(x, y))
-      error ("ribbon: in case of matrices, X and Y must have same size");
+    if (! size_equal (x, y))
+      error ("ribbon: matrices X and Y must have the same size");
     endif
   endif
 
+  newplot ();
+
   [nr, nc] = size (y);
-  tmp = zeros (1, nc);
+  htmp = zeros (nc, 1);
 
   for c = nc:-1:1
     zz = [y(:,c), y(:,c)];
     yy = x(:,c);
     xx = [c - width / 2, c + width / 2];
     [xx, yy] = meshgrid (xx, yy);
-    cc = ones (size (zz)) * c;
-    tmp(c) = surface (xx, yy, zz, cc);
+    cc = repmat (c, size (zz));
+    htmp(c) = surface (xx, yy, zz, cc);
   endfor
 
-  ax = get (tmp(c), "parent");
-
   if (! ishold ())
-    set (ax, "view", [-37.5, 30], "box", "off", "xgrid", "on",
-         "ygrid", "on", "zgrid", "on");
+    ax = get (htmp(1), "parent");
+    set (ax, "view", [-37.5, 30], "box", "off", 
+             "xgrid", "on", "ygrid", "on", "zgrid", "on");
   endif
 
   if (nargout > 0)
-    h = tmp;
+    h = htmp;
   endif
 
 endfunction
 
 
 %!demo
-%! clf
+%! clf;
+%! colormap ('default');
 %! [x, y, z] = sombrero ();
 %! [x, y] = meshgrid (x, y);
 %! ribbon (y, z);
 
+%!FIXME: Could have some input validation tests here
+
--- a/scripts/plot/rose.m
+++ b/scripts/plot/rose.m
@@ -80,7 +80,7 @@
   x1 = xx(1:end-1) + diff (xx, 1) / 2;
   x1 = [x1 ; x1; x1; x1](:);
   th = [0; 0; x1; 2*pi ; 2*pi];
-  r = zeros (4 * size (nn, 1), size (nn, 2));
+  r = zeros (4 * rows (nn), columns (nn));
   r(2:4:end, :) = nn;
   r(3:4:end, :) = nn;
 
@@ -106,6 +106,6 @@
 
 
 %!demo
-%! clf
+%! clf;
 %! rose ([2*randn(1e5, 1), pi + 2*randn(1e5, 1)]);
 
--- a/scripts/plot/saveas.m
+++ b/scripts/plot/saveas.m
@@ -102,6 +102,6 @@
 
   prt_opt = strcat ("-d", tolower (fmt));
 
-  print (filename, prt_opt);
+  print (fig, filename, prt_opt);
 
 endfunction
--- a/scripts/plot/scatter.m
+++ b/scripts/plot/scatter.m
@@ -19,7 +19,6 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {} scatter (@var{x}, @var{y})
 ## @deftypefnx {Function File} {} scatter (@var{x}, @var{y}, @var{s})
-## @deftypefnx {Function File} {} scatter (@var{x}, @var{y}, @var{c})
 ## @deftypefnx {Function File} {} scatter (@var{x}, @var{y}, @var{s}, @var{c})
 ## @deftypefnx {Function File} {} scatter (@var{x}, @var{y}, @var{s}, @var{c}, @var{style})
 ## @deftypefnx {Function File} {} scatter (@var{x}, @var{y}, @var{s}, @var{c}, @var{prop}, @var{val})
@@ -50,7 +49,7 @@
 ## @group
 ## x = randn (100, 1);
 ## y = randn (100, 1);
-## scatter (x, y, [], sqrt(x.^2 + y.^2));
+## scatter (x, y, [], sqrt (x.^2 + y.^2));
 ## @end group
 ## @end example
 ##
@@ -82,13 +81,14 @@
 
 
 %!demo
-%! clf
+%! clf;
 %! x = randn (100, 1);
 %! y = randn (100, 1);
-%! scatter (x, y, "r");
+%! scatter (x, y, 'r');
+%! title ('Scatter plot with red bubbles');
 
 %!demo
-%! clf
+%! clf;
 %! x = randn (100, 1);
 %! y = randn (100, 1);
 %! c = x .* y;
@@ -100,92 +100,96 @@
 %! x = randn (100, 1);
 %! y = randn (100, 1);
 %! scatter (x, y, [], sqrt (x.^2 + y.^2));
+%! title ('Scatter plot with bubble color determined by distance from origin');
 
 %!demo
-%! clf
+%! clf;
 %! rand_10x1_data1 = [0.171577, 0.404796, 0.025469, 0.335309, 0.047814, 0.898480, 0.639599, 0.700247, 0.497798, 0.737940];
 %! rand_10x1_data2 = [0.75495, 0.83991, 0.80850, 0.73603, 0.19360, 0.72573, 0.69371, 0.74388, 0.13837, 0.54143];
 %! x = rand_10x1_data1;
 %! y = rand_10x1_data2;
 %! s = 10 - 10*log (x.^2 + y.^2);
-%! h = scatter (x, y, s, s, "s", "filled");
+%! h = scatter (x, y, s, s, 's', 'filled');
+%! title ({'Scatter plot with filled square markers', ...
+%!         'size and color of markers determined by algorithm'});
 
 %!demo
-%! clf
+%! clf;
 %! rand_10x1_data3 = [0.42262, 0.51623, 0.65992, 0.14999, 0.68385, 0.55929, 0.52251, 0.92204, 0.19762, 0.93726];
 %! rand_10x1_data4 = [0.020207, 0.527193, 0.443472, 0.061683, 0.370277, 0.947349, 0.249591, 0.666304, 0.134247, 0.920356];
 %! x = rand_10x1_data3;
 %! y = rand_10x1_data4;
 %! s = 10 - 10*log (x.^2 + y.^2);
-%! h = scatter (x, y, [], "r", "s", "filled");
+%! h = scatter (x, y, [], 'r', 's', 'filled');
 
 %!demo
-%! clf
+%! clf;
 %! rand_10x1_data5 = [0.777753, 0.093848, 0.183162, 0.399499, 0.337997, 0.686724, 0.073906, 0.651808, 0.869273, 0.137949];
 %! rand_10x1_data6 = [0.37460, 0.25027, 0.19510, 0.51182, 0.54704, 0.56087, 0.24853, 0.75443, 0.42712, 0.44273];
 %! x = rand_10x1_data5;
 %! y = rand_10x1_data6;
 %! s = 10 - 10*log (x.^2 + y.^2);
-%! h = scatter (x, y, [], "r", "s");
+%! h = scatter (x, y, [], 'r', 's');
 
 %!demo
+%! clf;
 %! k = 1;
-%! clf
 %! for m = [1, 3]
 %!   for n = [101, 50, 1]
 %!     x = rand (n, 1);
 %!     y = rand (n, 1);
 %!     if (m > 1)
-%!       str = "Three Colors";
+%!       str = 'Three Colors';
 %!       idx = ceil (rand (n, 1) * 3);
-%!       colors = eye(3);
+%!       colors = eye (3);
 %!       colors = colors(idx, :);
 %!     else
-%!       str = "Random Colors";
+%!       str = 'Random Colors';
 %!       colors = rand (n, m);
-%!     endif
+%!     end
 %!     if (n == 1)
-%!       str = sprintf ("%s: 1 point", str);
+%!       str = sprintf ('%s: 1 point', str);
 %!     elseif (n < 100)
-%!       str = sprintf ("%s: < 100 points", str);
+%!       str = sprintf ('%s: < 100 points', str);
 %!     else
-%!       str = sprintf ("%s: > 100 points", str);
-%!     endif
-%!     subplot (2, 3, k)
+%!       str = sprintf ('%s: > 100 points', str);
+%!     end
+%!     subplot (2,3,k);
 %!     k = k + 1;
-%!     scatter (x, y, 15, colors, "filled")
-%!     axis ([0 1 0 1])
-%!     title (str)
-%!   endfor
-%! endfor
+%!     scatter (x, y, 15, colors, 'filled');
+%!     axis ([0 1 0 1]);
+%!     title (str);
+%!   end
+%! end
 
 %!demo
+%! clf;
 %! k = 1;
-%! clf
 %! for m = [1, 3]
 %!   for n = [101, 50, 1]
 %!     x = rand (n, 1);
 %!     y = rand (n, 1);
 %!     if (m > 1)
-%!       str = "Three Colors";
+%!       str = 'Three Colors';
 %!       idx = ceil (rand (n, 1) * 3);
-%!       colors = eye(3);
+%!       colors = eye (3);
 %!       colors = colors(idx, :);
 %!     else
-%!       str = "Random Colors";
+%!       str = 'Random Colors';
 %!       colors = rand (n, m);
-%!     endif
+%!     end
 %!     if (n == 1)
-%!       str = sprintf ("%s: 1 point", str);
+%!       str = sprintf ('%s: 1 point', str);
 %!     elseif (n < 100)
-%!       str = sprintf ("%s: < 100 points", str);
+%!       str = sprintf ('%s: < 100 points', str);
 %!     else
-%!       str = sprintf ("%s: > 100 points", str);
-%!     endif
-%!     subplot (2, 3, k)
+%!       str = sprintf ('%s: > 100 points', str);
+%!     end
+%!     subplot (2,3,k);
 %!     k = k + 1;
-%!     scatter (x, y, 15, colors)
-%!     axis ([0 1 0 1])
-%!     title (str)
-%!   endfor
-%! endfor
+%!     scatter (x, y, 15, colors);
+%!     axis ([0 1 0 1]);
+%!     title (str);
+%!   end
+%! end
+
--- a/scripts/plot/scatter3.m
+++ b/scripts/plot/scatter3.m
@@ -18,7 +18,7 @@
 
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {} scatter3 (@var{x}, @var{y}, @var{z}, @var{s}, @var{c})
-## @deftypefnx {Function File} {} scatter3 (@dots{}, 'filled')
+## @deftypefnx {Function File} {} scatter3 (@dots{}, "filled")
 ## @deftypefnx {Function File} {} scatter3 (@dots{}, @var{style})
 ## @deftypefnx {Function File} {} scatter3 (@dots{}, @var{prop}, @var{val})
 ## @deftypefnx {Function File} {} scatter3 (@var{h}, @dots{})
@@ -38,7 +38,7 @@
 ##
 ## The marker to use can be changed with the @var{style} argument, that is a
 ## string defining a marker in the same manner as the @code{plot} command.
-## If the argument 'filled' is given then the markers as filled.  All
+## If the argument "filled" is given then the markers as filled.  All
 ## additional arguments are passed to the underlying patch command.
 ##
 ## The optional return value @var{h} is a graphics handle to the hggroup
@@ -84,28 +84,27 @@
 
 
 %!demo
-%! clf
+%! clf;
 %! [x, y, z] = peaks (20);
 %! scatter3 (x(:), y(:), z(:), [], z(:));
+%! %% Default scatter3 with constant size bubbles and color determined by Z
 
 %!demo
-%! clf
-%! x = rand (20,1);
-%! y = rand (20,1);
-%! z = rand (20,1);
-%! scatter3 (x(:), y(:), z(:), 10, z(:), "s");
+%! clf;
+%! x = rand (20,1);  y = rand (20,1);  z = rand (20,1);
+%! scatter3 (x(:), y(:), z(:), 10, z(:), 's');
+%! %% scatter3 using a square marker of size 10 and color determined by Z
 
 %!demo
-%! clf
-%! x = rand (20,1);
-%! y = rand (20,1);
-%! z = rand (20,1);
-%! scatter3 (x(:), y(:), z(:), 20*z(:), z(:), "s");
+%! clf;
+%! x = rand (20,1);  y = rand (20,1);  z = rand (20,1);
+%! scatter3 (x(:), y(:), z(:), 20*z(:), [], 's');
+%! %% scatter3 using a square marker whose size is determined by Z
 
 %!demo
-%! clf
-%! x = rand (20,1);
-%! y = rand (20,1);
-%! z = rand (20,1);
-%! scatter3 (x(:), y(:), z(:), 20*z(:), [], "s");
+%! clf;
+%! x = rand (20,1);  y = rand (20,1);  z = rand (20,1);
+%! scatter3 (x(:), y(:), z(:), 20*z(:), z(:), 's');
+%! %% scatter3 using a square marker.
+%! %% Size and color of marker are determined by Z
 
--- a/scripts/plot/semilogx.m
+++ b/scripts/plot/semilogx.m
@@ -38,7 +38,7 @@
   [h, varargin, nargs] = __plt_get_axis_arg__ ("semilogx", varargin{:});
 
   if (nargs < 1)
-    print_usage();
+    print_usage ();
   endif
 
   oldh = gca ();
@@ -64,45 +64,45 @@
 
 
 %!demo
-%! clf ();
+%! clf;
 %! x = 1:0.01:10;
 %! y = (x .* (1 + rand (size (x)))) .^ 2;
 %! semilogx (y, x);
 
 %!demo
-%! clf ();
+%! clf;
 %! x = logspace (-5, 1, 10);
 %! y = logspace (-5, 1, 10);
 %!
-%! subplot (1, 2, 1);
-%! semilogx (x, y);
-%! xlabel ("semilogx (x, y)");
+%! subplot (1,2,1);
+%!  semilogx (x, y);
+%!  xlabel ('semilogx (x, y)');
 %!
-%! subplot (1, 2, 2);
-%! semilogx (-x, y);
-%! xlabel ("semilogx (-x, y)");
+%! subplot (1,2,2);
+%!  semilogx (-x, y);
+%!  xlabel ('semilogx (-x, y)');
 
 %!demo
-%! clf ();
+%! clf;
 %! x = logspace (-5, 1, 10);
 %! y = logspace (-5, 1, 10);
 %!
-%! subplot (1, 2, 1);
-%! semilogx (x, y);
-%! set (gca, "xdir", "reverse", "activepositionproperty", "outerposition")
-%! xlabel ({"semilogx (x, y)", "xdir = reversed"})
+%! subplot (1,2,1);
+%!  semilogx (x, y);
+%!  set (gca, 'xdir', 'reverse', 'activepositionproperty', 'outerposition');
+%!  xlabel ({'semilogx (x, y)', 'xdir = reversed'});
 %!
-%! subplot (1, 2, 2);
-%! semilogx (-x, y);
-%! set (gca, "xdir", "reverse", "activepositionproperty", "outerposition");
-%! xlabel ({"semilogx (-x, y)", "xdir = reversed"});
+%! subplot (1,2,2);
+%!  semilogx (-x, y);
+%!  set (gca, 'xdir', 'reverse', 'activepositionproperty', 'outerposition');
+%!  xlabel ({'semilogx (-x, y)', 'xdir = reversed'});
 
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
 %!   a = logspace (-5, 1, 10);
 %!   b = logspace (-5, 1, 10);
-%!   semilogx (a, b)
+%!   semilogx (a, b);
 %!   assert (get (gca, "xscale"), "log");
 %!   assert (get (gca, "yscale"), "linear");
 %! unwind_protect_cleanup
--- a/scripts/plot/semilogxerr.m
+++ b/scripts/plot/semilogxerr.m
@@ -60,10 +60,12 @@
 
 endfunction
 
+
 %!demo
-%! clf
-%! x = exp (log(0.01):0.2:log(10));
+%! clf;
+%! x = exp (log (0.01):0.2:log (10));
 %! y = wblpdf (x, 2, 2);
 %! ey = 0.5*rand (size (y)) .* y;
-%! semilogxerr (x, y, ey, "#~x-")
-%! xlim (x([1, end]))
+%! semilogxerr (x, y, ey, '#~x-');
+%! xlim (x([1, end]));
+
--- a/scripts/plot/semilogy.m
+++ b/scripts/plot/semilogy.m
@@ -38,7 +38,7 @@
   [h, varargin, nargs] = __plt_get_axis_arg__ ("semilogy", varargin{:});
 
   if (nargs < 1)
-    print_usage();
+    print_usage ();
   endif
 
   oldh = gca ();
@@ -47,7 +47,7 @@
     newplot ();
 
     set (h, "yscale", "log");
-    if (any( strcmp (get (gca, "nextplot"), {"new", "replace"})))
+    if (any (strcmp (get (gca, "nextplot"), {"new", "replace"})))
       set (h, "yminortick", "on");
     endif
 
@@ -63,39 +63,40 @@
 
 endfunction
 
+
 %!demo
-%! clf ();
+%! clf;
 %! x = 1:0.01:10;
 %! y = (x .* (1 + rand (size (x)))) .^ 2;
 %! semilogy (x, y);
 
 %!demo
-%! clf ();
+%! clf;
 %! x = logspace (-5, 1, 10);
 %! y = logspace (-5, 1, 10);
 %!
-%! subplot (2, 1, 1);
+%! subplot (2,1,1);
 %! semilogy (x, y);
-%! ylabel ("semilogy (x, y)");
+%! ylabel ('semilogy (x, y)');
 %!
-%! subplot (2, 1, 2);
+%! subplot (2,1,2);
 %! semilogy (x, -y);
-%! ylabel ("semilogy (x, -y)");
+%! ylabel ('semilogy (x, -y)');
 
 %!demo
-%! clf ();
+%! clf;
 %! x = logspace (-5, 1, 10);
 %! y = logspace (-5, 1, 10);
 %!
-%! subplot (2, 1, 1);
+%! subplot (2,1,1);
 %! semilogy (x, y);
-%! set (gca, "ydir", "reverse", "activepositionproperty", "outerposition");
-%! ylabel ({"semilogy (x, y)", "ydir = reversed"});
+%! set (gca, 'ydir', 'reverse', 'activepositionproperty', 'outerposition');
+%! ylabel ({'semilogy (x, y)', 'ydir = reversed'});
 %!
-%! subplot (2, 1, 2);
+%! subplot (2,1,2);
 %! semilogy (x, -y);
-%! set (gca, "ydir", "reverse", "activepositionproperty", "outerposition");
-%! ylabel ({"semilogy (x, -y)", "ydir = reversed"});
+%! set (gca, 'ydir', 'reverse', 'activepositionproperty', 'outerposition');
+%! ylabel ({'semilogy (x, -y)', 'ydir = reversed'});
 
 %!test
 %! hf = figure ("visible", "off");
--- a/scripts/plot/semilogyerr.m
+++ b/scripts/plot/semilogyerr.m
@@ -60,12 +60,13 @@
 
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
 %! x = 0.25:0.25:10;
 %! y = wblpdf (x, 4, 2);
 %! eyu = rand (size (y));
 %! eyl = 1.0 - 1./(1+eyu);
-%! semilogyerr (x, y, eyl.*y, eyu.*y, "~-d")
-%! xlim ([0 10])
+%! semilogyerr (x, y, eyl.*y, eyu.*y, '~-d');
+%! xlim ([0 10]);
 
--- a/scripts/plot/shading.m
+++ b/scripts/plot/shading.m
@@ -55,7 +55,7 @@
 
   obj = [h1(:); h2(:)];
 
-  for n = 1:numel(obj)
+  for n = 1:numel (obj)
     h = obj(n);
     if (strcmpi (mode, "flat"))
       set (h, "facecolor", "flat");
@@ -75,39 +75,44 @@
 
 
 %!demo
-%! clf
-%! colormap (jet)
-%! sombrero
-%! shading faceted
-%! title ('shading "faceted"')
+%! clf;
+%! colormap ('default');
+%! sombrero ();
+%! shading faceted;
+%! title ('shading ''faceted''');
 
 %!demo
-%! clf
-%! sombrero
-%! shading flat
-%! title ('shading "flat"')
+%! clf;
+%! colormap ('default');
+%! sombrero ();
+%! shading flat;
+%! title ('shading ''flat''');
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! sombrero ();
+%! shading interp;
+%! title ('shading ''interp''');
 
 %!demo
-%! clf
-%! sombrero
-%! shading interp
-%! title ('shading "interp"')
-
-%!demo
-%! clf
-%! pcolor (peaks ())
-%! shading faceted
-%! title ('shading "faceted"')
+%! clf;
+%! colormap ('default');
+%! pcolor (peaks ());
+%! shading faceted;
+%! title ('shading ''faceted''');
 
 %!demo
-%! clf
-%! pcolor (peaks ())
-%! shading flat
-%! title ('shading "flat"')
+%! clf;
+%! colormap ('default');
+%! pcolor (peaks ());
+%! shading flat;
+%! title ('shading ''flat''');
 
 %!demo
-%! clf
-%! pcolor (peaks ())
-%! shading interp
-%! title ('shading "interp"')
+%! clf;
+%! colormap ('default');
+%! pcolor (peaks ());
+%! shading interp;
+%! title ('shading ''interp''');
 
new file mode 100644
--- /dev/null
+++ b/scripts/plot/shrinkfaces.m
@@ -0,0 +1,216 @@
+## Copyright (C) 2012 Martin Helm
+##
+## 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} {} shrinkfaces (@var{p}, @var{sf})
+## @deftypefnx {Function File} {@var{nfv} =} shrinkfaces (@var{p}, @var{sf})
+## @deftypefnx {Function File} {@var{nfv} =} shrinkfaces (@var{fv}, @var{sf})
+## @deftypefnx {Function File} {@var{nfv} =} shrinkfaces (@var{f}, @var{v}, @var{sf})
+## @deftypefnx {Function File} {[@var{nf}, @var{nv}] =} shrinkfaces (@dots{})
+##
+## Reduce the faces area for a given patch, structure or explicit faces
+## and points matrices by a scale factor @var{sf}.  The structure
+## @var{fv} must contain the fields 'faces' and 'vertices'.  If the
+## factor @var{sf} is omitted then a default of 0.3 is used.
+##
+## Given a patch handle as the first input argument and no output
+## parameters, perform the shrinking of the patch faces in place and
+## redraw the patch.
+##
+## If called with one output argument, return a structure with fields
+## 'faces', 'vertices', and 'facevertexcdata' containing the data after
+## shrinking which can then directly be used as an input argument for the
+## @command{patch} function.
+##
+## Performing the shrinking on faces which are not convex can lead to
+## undesired results.
+##
+## For example,
+##
+## @example
+## @group
+## [phi r] = meshgrid (linspace (0, 1.5*pi, 16), linspace (1, 2, 4));
+## tri = delaunay (phi(:), r(:));
+## v = [r(:).*sin(phi(:)) r(:).*cos(phi(:))];
+## clf ()
+## p = patch ("Faces", tri, "Vertices", v, "FaceColor", "none");
+## fv = shrinkfaces (p);
+## patch (fv)
+## axis equal
+## grid on
+## @end group
+## @end example
+##
+## @noindent
+## draws a triangulated 3/4 circle and the corresponding shrunken
+## version.
+## @seealso{patch}
+## @end deftypefn
+
+## Author: Martin Helm <martin@mhelm.de>
+
+function [nf, nv] = shrinkfaces (varargin)
+
+  if (nargin < 1 || nargin > 3 || nargout > 2)
+    print_usage ();
+  endif
+  
+  sf = 0.3;
+  p = varargin{1};
+  colors = [];
+
+  if (ishandle (p) && nargin < 3)
+    faces = get (p, "Faces");
+    vertices = get (p, "Vertices");
+    colors = get (p, "FaceVertexCData");
+    if (nargin == 2)
+      sf = varargin{2};
+    endif
+  elseif (isstruct (p) && nargin < 3)
+    faces = p.faces;
+    vertices = p.vertices;
+    if (isfield (p, "facevertexcdata"))
+      colors = p.facevertexcdata;
+    endif
+    if (nargin == 2)
+      sf = varargin{2};
+    endif
+  elseif (ismatrix (p) && nargin >= 2 && ismatrix (varargin{2}))
+    faces = p;
+    vertices = varargin{2};
+    if (nargin == 3)
+      sf = varargin{3};
+    endif
+  else
+    print_usage ();
+  endif
+  
+  if (! isscalar (sf) || sf <= 0)
+    error ("shrinkfaces: scale factor must be a positive scalar");
+  endif
+
+  n = columns (vertices);
+  if (n < 2 || n > 3)
+    error ("shrinkfaces: only 2D and 3D patches are supported");
+  endif
+
+  m = columns (faces);
+  if (m < 3)
+    error ("shrinkfaces: faces must consist of at least 3 vertices");
+  endif
+
+  v = vertices(faces'(:), :);
+  if (isempty (colors) || rows (colors) == rows (faces))
+    c = colors;
+  elseif (rows (colors) == rows (vertices))
+    c = colors(faces'(:), :);
+  else
+    ## Discard inconsistent color data.
+    c = [];
+  endif
+  sv = rows (v);
+  ## we have to deal with a probably very large number of vertices, so
+  ## use sparse we use as midpoint (1/m, ..., 1/m) in generalized
+  ## barycentric coordinates.
+  midpoints = full (kron ( speye (sv / m), ones (m, m) / m) * sparse (v));
+  v = sqrt (sf) * (v - midpoints) + midpoints;
+  f = reshape (1:sv, m, sv / m)';
+  
+  switch (nargout)
+    case 0
+      if (ishandle (p))
+        ## avoid exceptions
+        set (p, "FaceVertexCData", [], "CData", []);
+        set (p, "Vertices", v, "Faces", f, "FaceVertexCData", c);
+      else
+        nf = struct ("faces", f, "vertices", v, "facevertexcdata", c);
+      endif
+    case 1
+      nf = struct ("faces", f, "vertices", v, "facevertexcdata", c);
+    case 2
+      nf = f;
+      nv = v;
+  endswitch
+
+endfunction
+
+%!demo
+%! faces = [1 2 3; 1 3 4];
+%! vertices = [0 0; 1 0; 1 1; 0 1];
+%! clf ()
+%! patch ("Faces", faces, "Vertices", vertices, "FaceColor", "none")
+%! fv = shrinkfaces (faces, vertices, 0.25);
+%! patch (fv)
+%! axis equal
+
+%!demo
+%! faces = [1 2 3 4; 5 6 7 8];
+%! vertices = [0 0; 1 0; 2 1; 1 1; 2 0; 3 0; 4 1; 3.5 1];
+%! clf ()
+%! patch ("Faces", faces, "Vertices", vertices, "FaceColor", "none")
+%! fv = shrinkfaces (faces, vertices, 0.25);
+%! patch (fv)
+%! axis equal
+%! grid on
+
+%!demo
+%! faces = [1 2 3 4];
+%! vertices = [-1 2; 0 0; 1 2; 0 1];
+%! clf ()
+%! patch ("Faces", faces, "Vertices", vertices, "FaceColor", "none")
+%! fv = shrinkfaces (faces, vertices, 0.25);
+%! patch (fv)
+%! axis equal
+%! grid on
+%! title "faces which are not convex are clearly not allowed"
+
+%!demo
+%! [phi r] = meshgrid (linspace (0, 1.5*pi, 16), linspace (1, 2, 4));
+%! tri = delaunay (phi(:), r(:));
+%! v = [r(:).*sin(phi(:)) r(:).*cos(phi(:))];
+%! clf ()
+%! p = patch ("Faces", tri, "Vertices", v, "FaceColor", "none");
+%! fv = shrinkfaces (p);
+%! patch (fv)
+%! axis equal
+%! grid on
+
+%!demo
+%! N = 10; # N intervals per axis
+%! [x, y, z] = meshgrid (linspace (-4,4,N+1));
+%! val = x.^3 + y.^3 + z.^3;
+%! fv = isosurface (x, y, z, val, 3, z);
+%!
+%! clf ()
+%! p = patch ("Faces", fv.faces, "Vertices", fv.vertices, "FaceVertexCData", ...
+%!            fv.facevertexcdata, "FaceColor", "interp", "EdgeColor", "black");
+%! axis equal
+%! view (115, 30)
+%! drawnow
+%! shrinkfaces (p, 0.6);
+
+%!shared faces, vertices, nfv, nfv2
+%! faces = [1 2 3];
+%! vertices = [0 0 0; 1 0 0; 1 1 0];
+%! nfv = shrinkfaces (faces, vertices, 0.7);
+%! nfv2 = shrinkfaces (nfv, 1/0.7);
+%!assert (isfield (nfv, "faces"));
+%!assert (isfield (nfv, "vertices"));
+%!assert (size (nfv.faces), [1 3]);
+%!assert (size (nfv.vertices), [3 3]);
+%!assert (norm (nfv2.vertices - vertices), 0, 2*eps);
--- a/scripts/plot/slice.m
+++ b/scripts/plot/slice.m
@@ -104,7 +104,7 @@
     x = varargin{1};
     y = varargin{2};
     z = varargin{3};
-    if (all ([isvector(x), isvector(y), isvector(z)]))
+    if (isvector (x) && isvector (y) && isvector (z))
       [x, y, z] = meshgrid (x, y, z);
     elseif (ndims (x) == 3 && size_equal (x, y, z))
       ## Do nothing.
@@ -120,7 +120,7 @@
 
   if (any ([isvector(sx), isvector(sy), isvector(sz)]))
     have_sval = true;
-  elseif (ndims(sx) == 2 && size_equal (sx, sy, sz))
+  elseif (ndims (sx) == 2 && size_equal (sx, sy, sz))
     have_sval = false;
   else
     error ("slice: dimensional mismatch for (XI, YI, ZI) or (SX, SY, SZ)");
@@ -135,10 +135,10 @@
 
   if (have_sval)
     ns = length (sx) + length (sy) + length (sz);
-    hs = zeros(ns,1);
+    hs = zeros (ns,1);
     [ny, nx, nz] = size (v);
-    if (length(sz) > 0)
-      for i = 1:length(sz)
+    if (length (sz) > 0)
+      for i = 1:length (sz)
         [xi, yi, zi] = meshgrid (squeeze (x(1,:,1)),
                                  squeeze (y(:,1,1)), sz(i));
         vz = squeeze (interp3 (x, y, z, v, xi, yi, zi, method));
@@ -147,7 +147,7 @@
     endif
 
     if (length (sy) > 0)
-      for i = length(sy):-1:1
+      for i = length (sy):-1:1
         [xi, yi, zi] = meshgrid (squeeze (x(1,:,1)), sy(i), squeeze (z(1,1,:)));
         vy = squeeze (interp3 (x, y, z, v, xi, yi, zi, method));
         tmp(sidx++) = surface (squeeze (xi),
@@ -157,7 +157,7 @@
     endif
 
     if (length (sx) > 0)
-      for i = length(sx):-1:1
+      for i = length (sx):-1:1
         [xi, yi, zi] = meshgrid (sx(i), squeeze (y(:,1,1)), squeeze (z(1,1,:)));
         vx = squeeze (interp3 (x, y, z, v, xi, yi, zi, method));
         tmp(sidx++) = surface (squeeze (sx(i) * ones (size (zi))),
@@ -182,13 +182,15 @@
 
 
 %!demo
-%! clf
+%! clf;
+%! colormap ('default');
 %! [x, y, z] = meshgrid (linspace (-8, 8, 32));
 %! v = sin (sqrt (x.^2 + y.^2 + z.^2)) ./ (sqrt (x.^2 + y.^2 + z.^2));
 %! slice (x, y, z, v, [], 0, []);
 
 %!demo
-%! clf
+%! clf;
+%! colormap ('default');
 %! [x, y, z] = meshgrid (linspace (-8, 8, 32));
 %! v = sin (sqrt (x.^2 + y.^2 + z.^2)) ./ (sqrt (x.^2 + y.^2 + z.^2));
 %! [xi, yi] = meshgrid (linspace (-7, 7));
--- a/scripts/plot/sombrero.m
+++ b/scripts/plot/sombrero.m
@@ -31,36 +31,37 @@
 
 ## Author: jwe
 
-function [x, y, z] = sombrero (n)
+function [x, y, z] = sombrero (n = 41)
 
-  if (nargin == 0)
-    n = 41;
+  if (nargin > 2)
+    print_usage ();
+  elseif (n <= 1)
+    error ("sombrero: number of grid lines N must be greater than 1");
   endif
 
-  if (nargin < 2)
-    if (n > 1)
-      tx = linspace (-8, 8, n)';
-      ty = tx;
-      [xx, yy] = meshgrid (tx, ty);
-      r = sqrt (xx .^ 2 + yy .^ 2) + eps;
-      tz = sin (r) ./ r;
-      if (nargout == 0)
-        surf (tx, ty, tz);
-        box ("off");
-      else
-        x = tx;
-        y = ty;
-        z = tz;
-      endif
-    else
-      error ("sombrero: number of grid lines must be greater than 1");
-    endif
+  tx = linspace (-8, 8, n)';
+  ty = tx;
+  [xx, yy] = meshgrid (tx, ty);
+  r = sqrt (xx .^ 2 + yy .^ 2) + eps;
+  tz = sin (r) ./ r;
+  if (nargout == 0)
+    surf (tx, ty, tz);
+    box ("off");
   else
-    print_usage ();
+    x = tx;
+    y = ty;
+    z = tz;
   endif
 
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
+%! colormap ('default');
 %! sombrero ();
+
+## Test input validation
+%!error sombrero (1,2,3)
+%!error <N must be greater than 1> sombrero (1)
+
--- a/scripts/plot/stairs.m
+++ b/scripts/plot/stairs.m
@@ -156,7 +156,7 @@
     h = [];
     unwind_protect
       hold_state = get (gca (), "nextplot");
-      for i = 1 : size(y, 2)
+      for i = 1 : columns (y)
         hg = hggroup ();
         h = [h; hg];
         args = __add_datasource__ ("stairs", hg, {"x", "y"}, varargin{:});
@@ -210,14 +210,14 @@
 
 
 %!demo
-%! clf
+%! clf;
 %! x = 1:10;
 %! rand_1x10_data1 = [0.073, 0.455, 0.837, 0.124, 0.426, 0.781, 0.004, 0.024, 0.519, 0.698];
 %! y = rand_1x10_data1;
 %! stairs (x, y);
 
 %!demo
-%! clf
+%! clf;
 %! x = 1:10;
 %! rand_1x10_data2 = [0.014, 0.460, 0.622, 0.394, 0.531, 0.378, 0.466, 0.788, 0.342, 0.893];
 %! y = rand_1x10_data2;
@@ -225,11 +225,11 @@
 %! plot (xs, ys);
 
 %!demo
-%! clf
+%! clf;
 %! stairs (1:9);
 
 %!demo
-%! clf
+%! clf;
 %! [xs, ys] = stairs (9:-1:1);
 %! plot (xs, ys);
 
--- a/scripts/plot/stem.m
+++ b/scripts/plot/stem.m
@@ -88,45 +88,45 @@
 
 
 %!demo
-%! clf
+%! clf;
 %! x = 1:10;
 %! stem (x);
 
 %!demo
-%! clf
+%! clf;
 %! x = 1:10;
 %! y = 2*x;
 %! stem (x, y);
 
 %!demo
-%! clf
+%! clf;
 %! x = 1:10;
 %! y = 2*x;
-%! h = stem (x, y, "r");
+%! h = stem (x, y, 'r');
 
 %!demo
-%! clf
+%! clf;
 %! x = 1:10;
 %! y = 2*x;
-%! h = stem (x, y, "-.k");
+%! h = stem (x, y, '-.k');
 
 %!demo
-%! clf
+%! clf;
 %! x = 1:10;
 %! y = 2*x;
-%! h = stem (x, y, "-.k.");
+%! h = stem (x, y, '-.k.');
 
 %!demo
-%! clf
+%! clf;
 %! x = 1:10;
 %! y = 2*x;
-%! h = stem (x, y, "filled");
+%! h = stem (x, y, 'filled');
 
 %!demo
-%! clf
-%! x = [0 : 10]';
+%! clf;
+%! x = (0 : 10)';
 %! y = [sin(x), cos(x)];
 %! h = stem (x, y);
-%! set (h(2), "color", "g");
-%! set (h(1), "basevalue", -1)
+%! set (h(2), 'color', 'g');
+%! set (h(1), 'basevalue', -1);
 
--- a/scripts/plot/stem3.m
+++ b/scripts/plot/stem3.m
@@ -52,7 +52,9 @@
 
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
 %! theta = 0:0.2:6;
-%! stem3 (cos (theta), sin (theta), theta)
+%! stem3 (cos (theta), sin (theta), theta);
+
new file mode 100644
--- /dev/null
+++ b/scripts/plot/stemleaf.m
@@ -0,0 +1,594 @@
+## Copyright (C) 2013 Michael D. Godfrey
+##
+## 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} {} stemleaf (@var{x}, @var{caption})
+## @deftypefnx {Function File} {} stemleaf (@var{x}, @var{caption}, @var{stem_sz})
+## @deftypefnx {Function File} {@var{plotstr} =} stemleaf (@dots{})
+## Compute and display a stem and leaf plot of the vector @var{x}.
+##
+## The input @var{x} should be a vector of integers.  Any non-integer values
+## will be converted to integer by @code{@var{x} = fix (@var{x})}.  By default
+## each element of @var{x} will be plotted with the last digit of the element
+## as a leaf value and the remaining digits as the stem.  For example, 123
+## will be plotted with the stem @samp{12} and the leaf @samp{3}.  The second
+## argument, @var{caption}, should be a character array which provides a
+## description of the data.  It is included as a heading for the output.
+##
+## The optional input @var{stem_sz} sets the width of each stem.
+## The stem width is determined by @code{10^(@var{stem_sz} + 1)}.
+## The default stem width is 10.
+##
+## The output of @code{stemleaf} is composed of two parts: a
+## "Fenced Letter Display," followed by the stem-and-leaf plot itself.
+## The Fenced Letter Display is described in @cite{Exploratory Data Analysis}.
+## Briefly, the entries are as shown:
+##
+## @example
+## @group
+##
+##         Fenced Letter Display
+## #% nx|___________________     nx = numel (x)
+## M% mi|       md         |     mi median index, md median
+## H% hi|hl              hu| hs  hi lower hinge index, hl,hu hinges,
+## 1    |x(1)         x(nx)|     hs h_spreadx(1), x(nx) first 
+##            _______            and last data value.
+##      ______|step |_______     step 1.5*h_spread
+##     f|ifl            ifh|     inner fence, lower and higher
+##      |nfl            nfh|     no.\ of data points within fences
+##     F|ofl            ofh|     outer fence, lower and higher
+##      |nFl            nFh|     no.\ of data points outside outer
+##                               fences
+## @end group
+## @end example
+##
+## The stem-and-leaf plot shows on each line the stem value followed by the
+## string made up of the leaf digits.  If the @var{stem_sz} is not 1 the
+## successive leaf values are separated by ",".
+##
+## With no return argument, the plot is immediately displayed.  If an output
+## argument is provided, the plot is returned as an array of strings. 
+##
+## The leaf digits are not sorted.  If sorted leaf values are desired, use
+## @code{@var{xs} = sort (@var{x})} before calling @code{stemleaf (@var{xs})}.
+##
+## The stem and leaf plot and associated displays are described in: 
+## Ch. 3, @cite{Exploratory Data Analysis} by J. W. Tukey, Addison-Wesley, 1977.
+## @seealso{hist, printd}
+## @end deftypefn
+
+## Author: Michael D. Godfrey <michaeldgodfrey@gmail.com>
+## Description: Compute stem and leaf plot
+
+function plotstr = stemleaf (x, caption, stem_sz)
+  ## Compute and display a stem and leaf plot of the vector x.  The x
+  ## vector is converted to integer by x = fix(x).  If an output argument
+  ## is provided, the plot is returned as an array of strings.  The
+  ## first element is the heading followed by an element for each stem.
+  ##
+  ## The default stem step is 10.  If stem_sz is provided the stem
+  ## step is set to: 10^(stem_sz+1).  The x vector should be integers.
+  ## It will be treated so that the last digit is the leaf value and the
+  ## other digits are the stems.
+  ##
+  ## When we first implemented stem and leaf plots in the early 1960's
+  ## there was some discussion about sorting vs. leaving the leaf
+  ## entries in the original order in the data.  We decided in favor of
+  ## sorting the leaves for most purposes.  This is the choice
+  ## implemented in the SNAP/IEDA system that was written at that time.
+  ##
+  ## SNAP/IEDA, and particularly its stem and leaf plotting, were further
+  ## developed by Hale Trotter, David Hoagland (at Princeton and MIT),
+  ## and others.
+  ##
+  ## Tukey, in EDA, generally uses unsorted leaves.  In addition, he
+  ## described a wide range of additional display formats.  This
+  ## implementation does not sort the leaves, but if the x vector is
+  ## sorted then the leaves come out sorted.  A simple display format is
+  ## used.
+  ##
+  ## I doubt if providing other options is worthwhile.  The code can
+  ## quite easily be modified to provide specific display results.  Or,
+  ## the returned output string can be edited.  The returned output is an
+  ## array of strings with each row containing a line of the plot
+  ## preceded by the lines of header text as the first row.  This
+  ## facilitates annotation.
+  ##
+  ## Note that the code has some added complexity due to the need to
+  ## distinguish both + and - 0 stems.  The +- stem values are essential
+  ## for all plots which span 0. After dealing with +-0 stems, the added
+  ## complexity of putting +- data values in the correct stem is minor,
+  ## but the sign of 0 leaves must be checked.  And, the cases where the
+  ## stems start or end at +- 0 must also be considered.
+  ##
+  ## The fact that IEEE floating point defines +- 0 helps make this
+  ## easier.
+  ##
+  ## Michael D. Godfrey   January 2013
+
+  ## More could be implemented for better data scaling.  And, of course,
+  ## other options for the kinds of plots described by Tukey could be
+  ## provided.  This may best be left to users.
+
+  if (nargin < 2 || nargin > 3)
+    print_usage ();
+  endif
+
+  if (! isvector (x))
+    error ("stemleaf: X must be a vector");
+  endif
+
+  if (isinteger (x))
+    ## Avoid use of integers because rounding rules do not use fix():
+    ## Example: floor (int32 (-44)/10) == -4, floor (int32 (-46)/10) = -5 !!!
+    x = single (x);
+  elseif (isfloat (x))
+    xint = fix (x);
+    if (any (x != xint))
+      warning ("stemleaf: X truncated to integer values");
+      x = xint;
+    endif
+  else
+    error ("stemleaf: X must be a numeric vector");
+  endif
+
+  if (! ischar (caption))
+    error ("stemleaf: CAPTION must be a character array");
+  endif
+
+  if (nargin == 2)
+    stem_step = 10;
+  else
+    if (isscalar (stem_sz) && stem_sz >= 0 && isreal (stem_sz))
+      stem_sz = fix (stem_sz);
+      stem_step = 10^(stem_sz+1);
+    else
+      error ("stemleaf: STEM_SZ must be a real integer >= 0");
+    endif
+  endif
+
+  ## Note that IEEE 754 states that -+ 0 should compare equal. This has
+  ## led to C sort (and therefore Octave) treating them as equal.  Thus,
+  ## sort([-1 0 -0 1]) yields [-1 0 -0 1], and sort([-1 -0 0 1])
+  ## yields: [-1 -0 0 1].  This means that stem-and-leaf plotting cannot
+  ## rely on sort to order the data as needed for display.
+  ## This also applies to min()/max() so these routines can't be relied
+  ## upon if the max or min is -+ 0.
+
+  ## Compute hinges and fences based on ref: EDA pgs. 33 and 44.
+  ## Note that these outlier estimates are meant to be "distribution free".
+
+  nx = numel (x);
+  xs = sort (x);                # Note that sort preserves -0
+  mdidx = fix ((nx + 1)/2);     # median index
+  hlidx = fix ((mdidx + 1)/2);  # lower hinge index
+  huidx = fix (nx + 1 - hlidx); # upper hinge index
+  md = xs(mdidx);               # median
+  hl = xs(hlidx);               # lower hinge
+  hu = xs(huidx);               # upper hinge
+  h_spread = hu - hl;           # h_spread: difference between hinges
+  step = 1.5*h_spread;          # step: 1.5 * h_spread
+  i_fence_l = hl - step;        # inner fences: outside hinges + step
+  o_fence_l = hl - 2*step;      # outer fences: outside hinges + 2*step
+  i_fence_h = hu + step;
+  o_fence_h = hu + 2*step;
+  n_out_l   = sum (x<i_fence_l) - sum (x<o_fence_l);
+  n_out_h   = sum (x>i_fence_h) - sum (x>o_fence_h);
+  n_far_l   = sum (x<o_fence_l);
+  n_far_h   = sum (x>o_fence_h);
+
+  # display table similar to that on pg. 33
+  plot_out = sprintf ("       Data: %s", caption);
+  plot_out = [plot_out; sprintf(" ")];
+  plot_out = [plot_out; sprintf("         Fenced Letter Display")];
+  plot_out = [plot_out; sprintf(" ")];
+  plot_out = [plot_out; sprintf("     #%3d|___________________", nx)];
+  plot_out = [plot_out; sprintf("     M%3d|       %5d      |", mdidx, md)];
+  plot_out = [plot_out; sprintf("     H%3d|%5d        %5d|   %d", hlidx, hl, hu, h_spread)];
+  plot_out = [plot_out; sprintf("     1   |%5d        %5d|", xs(1), xs(nx))];
+  plot_out = [plot_out; sprintf("               _______")];   
+  plot_out = [plot_out; sprintf("         ______|%5d|_______",step)];
+  plot_out = [plot_out; sprintf("        f|%5d        %5d|", i_fence_l, i_fence_h)];
+  plot_out = [plot_out; sprintf("         |%5d        %5d|  out", n_out_l, n_out_h)];
+  plot_out = [plot_out; sprintf("        F|%5d        %5g|", o_fence_l, o_fence_h)];
+  plot_out = [plot_out; sprintf("         |%5d        %5d|  far",n_far_l,n_far_h)];
+  plot_out = [plot_out; " "];
+
+  ## Determine stem values
+  min_x = min (x);
+  max_x = max (x);
+  if (min_x > 0)      # all stems > 0
+    stems = [fix(min(x)/stem_step) : (fix(max(x)/stem_step)+1)];
+  elseif (max_x < 0)  # all stems < 0
+    stems = [(fix(min_x/stem_step)-1) : fix(max_x/stem_step)];
+  elseif (min_x < 0 && max_x > 0)  # range crosses 0
+    stems = [(fix(min_x/stem_step)-1) : -0, 0 : fix(max_x/stem_step)+1 ];
+  else   # one endpoint is a zero which may be +0 or -0
+    if (min_x == 0)
+      if (any (x == 0 & signbit (x)))
+        min_x = -0;
+      else
+        min_x = +0;
+      endif
+    endif
+    if (max_x == 0)
+      if (any (x == 0 & ! signbit (x)))
+        max_x = +0;
+      else
+        max_x = -0;
+      endif
+    endif
+    stems = [];
+    if (signbit (min_x))
+      stems = [(fix(min_x/stem_step)-1) : -0];
+    endif
+    if (! signbit (max_x))
+      stems = [stems, 0 : fix(max_x/stem_step)+1 ];
+    endif
+  endif
+
+  ## Vectorized version provided by Rik Wehbring (rik@octave.org)
+  ## Determine leaves for each stem:
+  new_line  = 1;
+  for kx = 2: numel (stems)
+
+    stem_sign = signbit (stems(kx));
+    if (stems(kx) <= 0)
+      idx = ((x <= stems(kx)*stem_step) & (x > (stems(kx-1)*stem_step))
+              & (signbit (x) == stem_sign));
+      xlf = abs (x(idx) - stems(kx)*stem_step);
+    else
+      idx = ((x < stems(kx)*stem_step) & (x >= (stems(kx-1)*stem_step))
+              & (signbit (x) == stem_sign));
+      xlf = abs (x(idx) - stems(kx-1)*stem_step);
+    endif
+    ## Convert leaves to a string
+    if (stem_step == 10)
+      lf_str = sprintf ("%d", xlf);
+    else
+      lf_str = "";
+      if (! isempty (xlf))
+        lf_str = sprintf ("%d", xlf(1));
+        if (numel (xlf) > 1)
+          lf_str = [lf_str sprintf(",%d", xlf(2:end))];
+        endif
+      endif
+    endif
+
+    ## Set correct -0
+    if (stems(kx) == 0 && signbit (stems(kx)))
+      line = sprintf ("  -0 | %s",  lf_str);  # -0 stem.
+    elseif (stems(kx) < 0)
+      line = sprintf ("%4d | %s", stems(kx), lf_str);
+    elseif (stems(kx) > 0)
+      line = sprintf ("%4d | %s", stems(kx-1), lf_str);
+    else
+      line = "";
+    endif
+
+    if (! isempty (lf_str) || stems(kx) == 0 || stems(kx-1) == 0)
+      plot_out = [plot_out; line];
+      new_line = 1;
+    else
+      if (new_line == 1) 
+        plot_out = [plot_out; "     :"];  # just print one : if no leaves
+        new_line = 0;
+      endif
+    endif
+
+  endfor    # kx = 2: numel (stems)
+
+  if (nargout == 0)
+    disp (plot_out);
+  else
+    plotstr = plot_out;
+  endif
+
+endfunction
+
+
+%!demo
+%! ## Unsorted plot:
+%! x = [-22 12 -28 52  39 -2 12 10 11 11 42 38 44 18 44];
+%! stemleaf (x, "Unsorted plot");
+
+%!demo
+%! ## Sorted leaves:
+%! x = [-22 12 -28 52  39 -2 12 10 11 11 42 38 44 18 44];
+%! y = sort (x);
+%! stemleaf (y, "Sorted leaves");
+
+%!demo
+%! ## Sorted leaves (large dataset):
+%! x = [-22 12 -28 52  39 -2 12 10 11 11 42 38 44 18 44 37 113 124 37 48 127  \
+%!      36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 \
+%!      23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58  \
+%!      114 126 53 114 96 25 109 7 31 141 46 -13 71 43 117 116 27 7 68 40 31  \
+%!      115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57\
+%!      122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 \
+%!      127 31 116 146 21 23 30 10 20 21 30 0 100 110 1 20 0];
+%! y = sort (x);
+%! stemleaf (y, "Sorted leaves (large dataset)");
+
+%!demo
+%! ## Gaussian leaves:
+%! x = fix (30 * randn (300,1));
+%! stemleaf (x);
+
+%!test
+%! ## test minus to plus
+%! x = [-22 12 -28 52  39 -2 12 10 11 11 42 38 44 18 44 37 113 124 37 48 127  \
+%!      36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 \
+%!      23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58  \
+%!      114 126 53 114 96 25 109 7 31 141 46 -13 71 43 117 116 27 7 68 40 31  \
+%!      115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57\
+%!      122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 \
+%!      127 31 116 146 21 23 30 10 20 21 30 0 100 110 1 20 0];
+%! x = sort (x);
+%! rexp = char (
+%! "       Data: test minus to plus"    ,
+%! " "                                  ,
+%! "         Fenced Letter Display"     ,
+%! " "                                  ,
+%! "     #138|___________________"      ,     
+%! "     M 69|          52      |"      ,     
+%! "     H 35|   30          116|   86" ,
+%! "     1   |  -28          146|"      ,
+%! "               _______"             ,
+%! "         ______|  129|_______"      ,
+%! "        f|  -99          245|"      ,     
+%! "         |    0            0|  out" ,
+%! "        F| -228          374|"      ,
+%! "         |    0            0|  far" ,
+%! " "                                  ,
+%! "  -2 | 82"                          ,
+%! "  -1 | 3"                           ,
+%! "  -0 | 2"                           ,
+%! "   0 | 00177"                       ,
+%! "   1 | 00112288"                    ,
+%! "   2 | 001133577777899"             ,
+%! "   3 | 000111123456777889"          ,
+%! "   4 | 00122233344456788"           ,
+%! "   5 | 223788"                      ,
+%! "   6 | 138"                         ,
+%! "   7 | 11"                          ,
+%! "     : "                            ,
+%! "   9 | 69"                          ,
+%! "  10 | 04555567999"                 ,
+%! "  11 | 0133344455566667777899"      ,
+%! "  12 | 0011223444555677788"         ,
+%! "  13 | 1239"                        ,
+%! "  14 | 16"                          );
+%! r = stemleaf (x, "test minus to plus", 0);
+%! assert (r, rexp);
+
+%!test
+%! ## positive values above 0
+%! x = [5 22 12 28 52 39 12 11 11 42 38 44 18 44];
+%! rexp = char (
+%! "       Data: positive values above 0",
+%! " "                                   ,
+%! "         Fenced Letter Display"      ,
+%! " "                                   ,
+%! "     # 14|___________________"       ,     
+%! "     M  7|          22      |"       ,     
+%! "     H  4|   12           42|   30"  ,
+%! "     1   |    5           52|"       ,
+%! "               _______"              ,
+%! "         ______|   45|_______"       ,
+%! "        f|  -33           87|"       ,     
+%! "         |    0            0|  out"  ,
+%! "        F|  -78          132|"       ,
+%! "         |    0            0|  far"  ,
+%! " "                                   ,
+%! "   0 | 5"                            ,
+%! "   1 | 22118"                        ,
+%! "   2 | 28"                           ,
+%! "   3 | 98"                           ,
+%! "   4 | 244"                          ,
+%! "   5 | 2"                            );
+%! r = stemleaf (x, "positive values above 0");
+%! assert (r, rexp);
+
+%!test
+%! ## negative values below 0
+%! x = [5 22 12 28 52 39 12 11 11 42 38 44 18 44];
+%! x = -x;
+%! rexp = char (
+%! "       Data: negative values below 0",
+%! " "                                   ,
+%! "         Fenced Letter Display"      ,
+%! " "                                   ,
+%! "     # 14|___________________"       ,     
+%! "     M  7|         -28      |"       ,     
+%! "     H  4|  -42          -12|   30"  ,
+%! "     1   |  -52           -5|"       ,
+%! "               _______"              ,
+%! "         ______|   45|_______"       ,
+%! "        f|  -87           33|"       ,     
+%! "         |    0            0|  out"  ,
+%! "        F| -132           78|"       ,
+%! "         |    0            0|  far"  ,
+%! " "                                   ,
+%! "  -5 | 2"                            ,
+%! "  -4 | 244"                          ,
+%! "  -3 | 98"                           ,
+%! "  -2 | 28"                           ,
+%! "  -1 | 22118"                        ,
+%! "  -0 | 5"                            );
+%! r = stemleaf (x, "negative values below 0");
+%! assert (r, rexp);
+
+%!test
+%! ## positive values from 0
+%! x = [22 12 28 52 39 2 12 0 11 11 42 38 44 18 44];
+%! rexp = char (
+%! "       Data: positive values from 0",
+%! " "                                  ,
+%! "         Fenced Letter Display"     ,
+%! " "                                  ,
+%! "     # 15|___________________"      ,     
+%! "     M  8|          22      |"      ,     
+%! "     H  4|   11           42|   31" ,
+%! "     1   |    0           52|"      ,
+%! "               _______"             ,
+%! "         ______|   46|_______"      ,
+%! "        f|  -35           88|"      ,     
+%! "         |    0            0|  out" ,
+%! "        F|  -82          135|"      ,
+%! "         |    0            0|  far" ,
+%! " "                                  ,
+%! "   0 | 20"                          ,
+%! "   1 | 22118"                       ,
+%! "   2 | 28"                          ,
+%! "   3 | 98"                          ,
+%! "   4 | 244"                         ,
+%! "   5 | 2"                           );
+%! r = stemleaf (x, "positive values from 0");
+%! assert (r, rexp);
+
+%!test
+%! ## negative values from 0
+%! x = [22 12 28 52 39 2 12 0 11 11 42 38 44 18 44];
+%! x = -x;
+%! rexp = char (
+%! "       Data: negative values from 0",
+%! " "                                  ,
+%! "         Fenced Letter Display"     ,
+%! " "                                  ,
+%! "     # 15|___________________"      ,     
+%! "     M  8|         -22      |"      ,     
+%! "     H  4|  -42          -11|   31" ,
+%! "     1   |  -52            0|"      ,
+%! "               _______"             ,
+%! "         ______|   46|_______"      ,
+%! "        f|  -88           35|"      ,     
+%! "         |    0            0|  out" ,
+%! "        F| -135           82|"      ,
+%! "         |    0            0|  far" ,
+%! " "                                  ,
+%! "  -5 | 2"                           ,
+%! "  -4 | 244"                         ,
+%! "  -3 | 98"                          ,
+%! "  -2 | 28"                          ,
+%! "  -1 | 22118"                       ,
+%! "  -0 | 20"                          );
+%! r = stemleaf (x, "negative values from 0");
+%! assert (r, rexp);
+
+%!test
+%! ## both +0 and -0 present
+%! x = [-9 -7 -0 0 -0];
+%! rexp = char (
+%! "       Data: both +0 and -0 present",
+%! " "                                  ,
+%! "         Fenced Letter Display"     ,
+%! " "                                  ,
+%! "     #  5|___________________"      ,     
+%! "     M  3|           0      |"      ,     
+%! "     H  2|   -7            0|   7"  ,
+%! "     1   |   -9            0|"      ,
+%! "               _______"             ,
+%! "         ______|   10|_______"      ,
+%! "        f|  -17           10|"      ,     
+%! "         |    0            0|  out" ,
+%! "        F|  -28           21|"      ,
+%! "         |    0            0|  far" ,
+%! " "                                  ,
+%! "  -0 | 9700"                        ,
+%! "   0 | 0"                           );
+%! r = stemleaf (x, "both +0 and -0 present");
+%! assert (r, rexp);
+
+%!test
+%! ## both <= 0 and -0 present
+%! x = [-9 -7 0 -0];
+%! rexp = char (
+%! "       Data: both <= 0 and -0 present",
+%! " "                                    ,
+%! "         Fenced Letter Display"       ,
+%! " "                                    ,
+%! "     #  4|___________________"        ,     
+%! "     M  2|          -7      |"        ,     
+%! "     H  1|   -9            0|   9"    ,
+%! "     1   |   -9            0|"        ,
+%! "               _______"               ,
+%! "         ______|   13|_______"        ,
+%! "        f|  -22           13|"        ,     
+%! "         |    0            0|  out"   ,
+%! "        F|  -36           27|"        ,
+%! "         |    0            0|  far"   ,
+%! " "                                    ,
+%! "  -0 | 970"                           ,
+%! "   0 | 0"                             );
+%! r = stemleaf (x, "both <= 0 and -0 present");
+%! assert (r, rexp);
+
+%!test
+%! ##   Example from EDA: Chevrolet Prices pg. 30
+%! x = [150 250 688 695 795 795 895 895 895 1099 1166 1333 1499 1693 1699 1775 1995];
+%! rexp = char (
+%! "       Data: Chevrolet Prices EDA pg.30",
+%! " "                                      ,
+%! "         Fenced Letter Display"         ,
+%! " "                                      ,
+%! "     # 17|___________________"          ,          
+%! "     M  9|         895      |"          ,
+%! "     H  5|  795         1499|   704"    ,
+%! "     1   |  150         1995|"          ,
+%! "               _______"                 ,
+%! "         ______| 1056|_______"          ,
+%! "        f| -261         2555|"          ,
+%! "         |    0            0|  out"     ,
+%! "        F|-1317         3611|"          ,
+%! "         |    0            0|  far"     ,
+%! " "                                      ,
+%! "   1 | 50"                              ,
+%! "   2 | 50"                              ,
+%! "     :"                                 ,
+%! "   6 | 88,95"                           ,
+%! "   7 | 95,95"                           ,
+%! "   8 | 95,95,95"                        ,
+%! "     :"                                 ,
+%! "  10 | 99"                              ,
+%! "  11 | 66"                              ,
+%! "     :"                                 ,
+%! "  13 | 33"                              ,
+%! "  14 | 99"                              ,
+%! "     :"                                 ,
+%! "  16 | 93,99"                           ,
+%! "  17 | 75"                              ,
+%! "     :"                                 ,
+%! "  19 | 95"                              );
+%! r = stemleaf (x, "Chevrolet Prices EDA pg.30", 1);
+%! assert (r, rexp);
+
+## Test input validation
+%!error stemleaf ()
+%!error stemleaf (1, 2, 3, 4)
+%!error <X must be a vector> stemleaf (ones (2,2), "")
+%!warning <X truncated to integer values> tmp = stemleaf ([0 0.5 1],"");
+%!error <X must be a numeric vector> stemleaf ("Hello World", "data")
+%!error <CAPTION must be a character array> stemleaf (1, 2)
+%!error <STEM_SZ must be a real integer> stemleaf (1, "", ones (2,2))
+%!error <STEM_SZ must be a real integer> stemleaf (1, "", -1)
+%!error <STEM_SZ must be a real integer> stemleaf (1, "", 1+i)
+
new file mode 100644
--- /dev/null
+++ b/scripts/plot/struct2hdl.m
@@ -0,0 +1,638 @@
+## Copyright (C) 2012 pdiribarne
+##
+## 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 Octave; see the file COPYING.  If not, see
+## <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn  {Function File} {@var{h} =} struct2hdl (@var{s})
+## @deftypefnx {Function File} {@var{h} =} struct2hdl (@var{s}, @var{p})
+## @deftypefnx {Function File} {@var{h} =} struct2hdl (@var{s}, @var{p}, @var{hilev})
+## Construct a handle object @var{h} from the structure @var{s}.  The structure
+## must contain the fields "handle", "type", "children", "properties", and
+## "special".  If the handle of an existing figure or axes is specified,
+## @var{p}, the new object will be created as a child of that object.
+## If no object handle is provided then a new figure and the necessary
+## children will be constructed using the default object values from
+## the root figure.
+##
+## A third boolean argument @var{hilev} can be passed to specify whether
+## the function should try to preserve listeners/callbacks, e.g., for
+## legends or hggroups.  The default is false.
+## @seealso{hdl2struct, findobj, get, set}
+## @end deftypefn
+
+## Author: pdiribarne <pdiribarne@new-host.home>
+## Created: 2012-03-04
+
+function [h, pout] = struct2hdl (s, p=[], hilev = false)
+
+  fields = {"handle", "type", "children", "properties", "special"};
+  partypes = {"root", "figure", "axes", "hggroup"};
+  othertypes = {"line", "patch", "surface", "image", "text"};
+  alltypes = [partypes othertypes];
+
+  if (nargin > 3 || ! isstruct (s))
+    print_usage ();
+  elseif (! all (isfield (s, fields)))
+    print_usage ();
+  elseif (isscalar (p))
+    if (! ishandle (p))
+      error ("struct2hdl: P is not a handle to a graphic object");
+    endif
+    if (any (strcmp (get (p).type, partypes)))
+      paridx = find (strcmp (get (p).type, alltypes));
+      kididx = find (strcmp (s.type, alltypes));
+      if (kididx <= paridx)
+        error ("struct2hdl: incompatible input handles");
+      endif
+    else
+      error ("struct2hdl: %s object can't be parent object", get (p).type);
+    endif
+    hpar = p;
+    p = [NaN; hpar];
+    ## create appropriate parent if needed
+    if (any (strcmp (s.type, othertypes)))
+      for ii = (paridx+1) : (numel (partypes)-1)
+        eval (["hpar = " partypes{ii} "(\"parent\", hpar);"]);
+        p = [p [NaN; hpar]];
+      endfor
+    elseif (any (strcmp (s.type, {"hggroup", "axes"})))
+      for ii = (paridx+1) : (kididx-1)
+        eval (["hpar = " partypes{ii} "(\"parent\", hpar);"]);
+        p = [p [NaN; hpar]];
+      endfor
+    else
+      par = NaN;
+    endif
+  elseif (isempty (p))
+    if (any (strcmp (s.type, othertypes)))
+      par = axes ();
+    elseif (any (strcmp (s.type, {"hggroup", "axes"})))
+      par = figure ();
+    else
+      par = NaN;
+    endif
+    p = [NaN; par];
+  endif
+  ## read parent (last column) in p and remove it if duplicate
+  par = p(2,end);
+  tst = find (p(2,:) == par);
+  if (numel (tst) > 1)
+    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;
+    s.properties = rmfield (s.properties, ...
+                              {"callbackobject", "commandwindowsize", ...
+                               "screendepth", "screenpixelsperinch", ...
+                               "screensize"});
+  elseif (strcmp (s.type, "figure"))
+    h = figure ();
+  elseif (strcmp (s.type, "axes"))
+    ## legends and colorbars are "transformed" in normal axes
+    ## if hilev is not requested
+    if (! hilev)
+      if (strcmp (s.properties.tag, "legend"))
+        s.properties.tag = "";
+        s.properties.userdata = [];
+        par = gcf;
+      elseif (strcmp (s.properties.tag, "colorbar"))
+        s.properties.tag = "";
+        s.properties.userdata = [];
+        par = gcf;
+      endif
+    endif
+
+    [h, s] = createaxes (s, p, par);
+  elseif (strcmp (s.type, "line"))
+    h = createline (s, par);
+  elseif (strcmp (s.type, "patch"))
+    [h, s] = createpatch (s, par);
+  elseif (strcmp (s.type, "text"))
+    h = createtext (s, par);
+  elseif (strcmp (s.type, "image"))
+    h = createimage (s, par);
+  elseif (strcmp (s.type, "surface"))
+    h = createsurface (s, par);
+  elseif (strcmp (s.type, "hggroup"))
+    [h, s, p] = createhg (s, p, par, hilev);
+  else
+    error ("struct2hdl: %s objects are not implemented yet", s.type)
+  endif
+
+  ## children
+  p = [p [s.handle; h]];  # [original; new]
+  kids = s.children;
+  nkids = length (kids);
+  ii = 0;
+  while (nkids)
+    ii++;
+    if (! any (ii == s.special))
+      [h2, p] = struct2hdl (s.children(ii), [p [s.handle; h]], hilev);
+    endif
+    nkids--;
+  endwhile
+
+  ## paste properties
+  setprops (s, h, p, hilev);
+
+  pout = p;
+
+endfunction
+
+function [h, sout] = createaxes (s, p, par)
+  ## regular axes
+  if (strcmp (s.properties.tag, ""))
+    propval = {"position", s.properties.position};
+    hid = {"autopos_tag", "looseinset"};
+    for ii = 1:numel (hid)
+      prop = hid{ii};
+      if (isfield (s.properties, prop))
+        val = s.properties.(prop);
+        propval = [propval, prop, val];
+      endif
+    endfor
+    h = axes (propval{:}, "parent", par);
+
+    if (isfield (s.properties, "__plotyy_axes__"))
+      plty = s.properties.__plotyy_axes__;
+      addproperty ("__plotyy_axes__", h, "any");
+      tmp = [p [s.handle; h]];
+      tst = arrayfun (@(x) any (plty == x), tmp(1:2:end));
+      if (sum (tst) == numel (plty))
+        for ii = 1:numel (plty)
+          plty(ii) = tmp(find (tmp == plty(ii)) + 1);
+        endfor
+        for ii = 1:numel (plty)
+          set (plty(ii), "__plotyy_axes__", plty);
+        endfor
+      endif
+      s.properties = rmfield (s.properties, "__plotyy_axes__");
+    endif
+
+    ## delete non-default and already set properties
+    fields = fieldnames (s.properties);
+    tst = cellfun (@(x) isprop (h, x), fields);
+    s.properties = rmfield (s.properties, fields(find (tst == 0)));
+
+  elseif (strcmp (s.properties.tag, "legend"))
+    ## legends
+    oldax = s.properties.userdata.handle;
+    idx = find (p == oldax);
+    newax = p(idx+1);
+    strings = {};
+    kids = s.children;
+    kids(s.special) = [];
+    oldh = unique (arrayfun (@(x) x.properties.userdata(end), kids));
+    for ii = 1:length (oldh)
+      idx = find (p(1:2:end) == oldh(ii)) * 2;
+      if (! isempty (idx))
+        newh(ii) = p(idx);
+        if (! strcmp (get (newh(ii), "type"), "hggroup"))
+          str = get (newh(ii), "displayname");
+          strings = [strings str];
+        else
+          str = get (get (newh(ii), "children")(1), "displayname");
+          strings = [strings str];
+        endif
+      else
+        error ("struct2hdl: didn't find a legend item");
+      endif
+    endfor
+    location = s.properties.location;
+    orientation = s.properties.orientation;
+    textpos = s.properties.textposition;
+    box = s.properties.box;
+
+    h = legend (newax, newh, strings, "location", location, ...
+                "orientation", orientation);
+    set (h, "textposition", textpos); # bug makes "textposition"
+                                      # redefine the legend
+    h = legend (newax, newh, strings, "location", location, ...
+                "orientation", orientation);
+    ## box
+    if (strcmp (box, "on"))
+      legend ("boxon");
+    endif
+
+    ## visibility
+    tst = arrayfun (@(x) strcmp (x.properties.visible, "on"), kids);
+    if (! any (tst))
+      legend ("hide");
+    endif
+
+    ## remove all properties such as "textposition" that redefines
+    ## the entire legend. Also remove chidren
+    s.properties = rmfield (s.properties, ...
+                              {"userdata", "xlabel",...
+                               "ylabel", "zlabel", "location", ...
+                               "title", "string","orientation", ...
+                               "visible", "textposition"});
+
+    s.children = [];
+
+  elseif (strcmp (s.properties.tag, "colorbar"))
+    ## colorbar
+    oldax = s.properties.axes;
+    if (! isempty (idx = find (oldax == p)))
+      ax = p(idx+1);
+      location = s.properties.location;
+      h = colorbar ("peer", ax, location);
+      s.properties = rmfield (s.properties, ...
+                                {"userdata", "xlabel" ...
+                                 "ylabel", "zlabel", ...
+                                 "title", "axes"});
+      s.children= [];
+    else
+      error ("hdl2struct: didn't find an object");
+    endif
+  endif
+  sout = s;
+endfunction
+
+function h = createline (s, par)
+  h = line ("parent", par);
+  addmissingprops (h, s.properties);
+endfunction
+
+function [h, sout] = createpatch (s, par)
+  prp.faces = s.properties.faces;
+  prp.vertices = s.properties.vertices;
+  prp.facevertexcdata = s.properties.facevertexcdata;
+  h = patch (prp);
+  set (h, "parent", par);
+  s.properties = rmfield (s.properties,
+                            {"faces", "vertices", "facevertexcdata"});
+  addmissingprops (h, s.properties);
+  sout = s;
+endfunction
+
+function h = createtext (s, par)
+  h = text ("parent", par);
+  addmissingprops (h, s.properties);
+endfunction
+
+function h = createimage (s, par)
+  h = image ("parent", par);
+  addmissingprops (h, s.properties);
+endfunction
+
+function h = createsurface (s, par)
+  h = surface ("parent", par);
+  addmissingprops (h, s.properties);
+endfunction
+
+function [h, sout, pout] = createhg (s, p, par, hilev)
+  ## Here we infer from properties the type of hggroup we should build
+  ## an call corresponding high level functions
+  ## We manually set "hold on" to avoid next hggroup be deleted
+  ## the proper value of axes "nextplot" will finally be recovered
+
+  hold on;
+  if (hilev)
+    [h, s, p] = createhg_hilev (s, p, par);
+    if (numel (s.children) != numel (get (h).children))
+      warning (["struct2hdl: could not infer the hggroup type. ", ...
+                "Will build objects but listener/callback functions ", ...
+                "will be lost"]);
+      if (isfield (h, "bargroup"))
+        delete (get (h).bargroup);
+      else
+        delete (h);
+      endif
+      h = hggroup ("parent", par);
+      addmissingprops (h, s.properties);
+      s.special = [];
+    else
+      oldkids = s.children;
+      newkids = get (h).children;
+      nkids = numel (oldkids);
+      ii = 1;
+      while (nkids)
+        p = [p [oldkids(ii++).handle; newkids(nkids--)]];
+      endwhile
+    endif
+  else
+    h = hggroup ("parent", par);
+    addmissingprops (h, s.properties);
+    s.special = [];
+  endif
+  sout = s;
+  pout = p;
+endfunction
+
+function [h, sout, pout] = createhg_hilev (s, p, par)
+  fields = s.properties;
+  if (isfield (fields, "contourmatrix"))
+    ## contours
+    xdata = s.properties.xdata;
+    ydata = s.properties.ydata;
+    zdata = s.properties.zdata;
+    levellist = s.properties.levellist;
+    textlist = s.properties.textlist;
+
+    ## contour creation
+    if (isempty (s.children(1).properties.zdata))
+      if (strcmpi (s.properties.fill, "on"))
+        [cm2, h] = contourf (xdata, ydata, zdata, levellist);
+      else
+        [cm2, h] = contour (xdata, ydata, zdata, levellist);
+      endif
+
+      ## labels
+      if (strcmpi (s.properties.showtext, "on"))
+        clabel (cm2, h, textlist);
+      endif
+    else
+      [cm2, h] = contour3 (xdata, ydata, zdata, levellist);
+    endif
+
+    ## delete already set properties and children
+    s.properties = rmfield (s.properties, ...
+                              {"xdata", "ydata", "zdata", ...
+                               "contourmatrix", "levellist", ...
+                               "fill", "labelspacing", ...
+                               "levellistmode", "levelstep", ...
+                               "levelstepmode", "textlist"...
+                               "textlistmode" , "textstep", ...
+                               "textstepmode", "zlevel", ...
+                               "zlevelmode"});
+
+  elseif (isfield (fields, "udata") && isfield (fields, "vdata"))
+    ## quiver
+    xdata = s.properties.xdata;
+    ydata = s.properties.ydata;
+
+    udata = s.properties.udata;
+    vdata = s.properties.vdata;
+
+    h = quiver (xdata, ydata, udata, vdata);
+
+    ## delete already set properties and children
+    s.properties = rmfield (s.properties, ...
+                              {"xdata", "ydata", "zdata", ...
+                               "xdatasource", "ydatasource", "zdatasource", ...
+                               "udata", "vdata", "wdata", ...
+                               "udatasource", "vdatasource", "wdatasource"});
+
+  elseif (isfield (fields, "format"))
+    ##errorbar
+    form = s.properties.format;
+    xdata = s.properties.xdata;
+    ydata = s.properties.ydata;
+    xldata = s.properties.xldata;
+    ldata = s.properties.ldata;
+    xudata = s.properties.xudata;
+    udata = s.properties.udata;
+
+    switch form
+      case "xerr"
+        h = errorbar (xdata, ydata, xldata, xudata, ">");
+      case "yerr"
+        h = errorbar (xdata, ydata, ldata, udata, "~");
+      case "xyerr"
+        h = errorbar (xdata, ydata, xldata, xudata, ldata, udata, "~>");
+      case "box"
+        h = errorbar (xdata, ydata, xldata, xudata, "#");
+      case "boxy"
+        h = errorbar (xdata, ydata, ldata, udata, "#~");
+      case "boxxy"
+        h = errorbar (xdata, ydata, xldata, xudata, ldata, udata, "#~>");
+      otherwise
+        error ("struct2hdl: couldn't guess the errorbar format");
+    endswitch
+    ## delete already set properties
+    s.properties = rmfield (s.properties, ...
+                              {"xdata", "ydata", ...
+                               "xldata", "ldata", ...
+                               "xudata", "udata", ...
+                               "xldatasource", "ldatasource", ...
+                               "xudatasource", "udatasource", ...
+                               "format"});
+
+  elseif (isfield (fields, "bargroup"))
+    ## bar plot
+    ## FIXME - here we don't have access to brothers so we first create all
+    ## the barseries of the bargroup (but the last), then retrieve information,
+    ## and rebuild the whole bargroup.
+    ## The duplicate are deleted after calling "setprops"
+
+    bargroup = s.properties.bargroup;
+    oldh = s.handle;
+
+    temp = arrayfun (@(x) any(x == bargroup), [p(1:2:end) oldh]);
+    tst = sum (temp) == length (bargroup);
+
+    if (isscalar (bargroup) || !tst)
+      xdata = s.properties.xdata;
+      ydata = s.properties.ydata;
+
+      h = bar (xdata, ydata);
+
+      ## delete already set properties,
+      s.properties = rmfield (s.properties, ...
+                                {"xdata", "ydata", ...
+                                 "xdatasource", "ydatasource", ...
+                                 "bargroup", ...
+                                 "barwidth", "baseline"});
+    else
+      xdata = [];
+      ydata = [];
+
+      ##build x/y matrix
+      nbar = length (bargroup);
+      tmp = struct ("handle", NaN, "type", "", "children", [], "special", []);
+      for ii = 1:(nbar - 1)
+        idx = find (p(1:2:end) == bargroup(ii)) * 2;
+        hdl = p (idx);
+        xdata = [xdata get(hdl).xdata];
+        ydata = [ydata get(hdl).ydata];
+        tmp.children(ii) = hdl2struct (hdl);
+      endfor
+
+      xdata = [xdata s.properties.xdata];
+      ydata = [ydata s.properties.ydata];
+      width = s.properties.barwidth;
+      h = bar (ydata, width);
+
+      ## replace previous handles in "match", copy props and delete redundant
+      for ii = 1:(nbar - 1)
+        props = tmp.children(ii).properties;
+        bl = props.baseline;
+        tmp.children(ii).properties = rmfield (props, {"baseline", "bargroup"});
+        setprops (tmp.children(ii), h(ii), p, 1);
+        delete (tmp.children(ii).handle);
+        delete (bl);
+        idxpar = find (p == tmp.children(ii).handle);
+        p(idxpar) = h(ii);
+        idxkid = idxpar - 2;
+        p(idxkid) = get (h(ii), "children");
+      endfor
+      p(2,((end-nbar+2):end)) = h(1:(end-1));
+      h = h(end);
+
+      ## delete already set properties ,
+      s.properties = rmfield (s.properties, ...
+                                {"xdata", "ydata", "bargroup"...
+                                 "barwidth", "baseline"});
+    endif
+  elseif (isfield (fields, "baseline"))
+    ## stem plot
+    xdata = s.properties.xdata;
+    ydata = s.properties.ydata;
+
+    h = stem (xdata, ydata);
+
+    ## delete already set properties,
+    s.properties = rmfield (s.properties, ...
+                              {"xdata", "ydata", ...
+                               "xdatasource", "ydatasource", ...
+                               "baseline"});
+  elseif (isfield (fields, "basevalue"))
+    ## area plot
+    xdata = s.properties.xdata;
+    ydata = s.properties.ydata;
+    level = s.properties.basevalue;
+
+    h = area (xdata, ydata, level);
+
+    ## delete already set properties,
+    s.properties = rmfield (s.properties, ...
+                              {"xdata", "ydata", ...
+                               "xdatasource", "ydatasource"});
+  else
+    warning ("struct2hdl: could not infer the hggroup type. Will build objects but listener/callback functions will be lost");
+    h = hggroup ("parent", par);
+    addmissingprops (h, s.properties);
+    s.special = [];           # children will be treated as normal children
+  endif
+  sout = s;
+  pout = p;
+endfunction
+
+function setprops (s, h, p, hilev)
+  more off;
+  if (strcmpi (s.properties.tag, ""))
+    specs = s.children(s.special);
+    hdls = arrayfun (@(x) x.handle, specs);
+    nh = length (hdls);
+    msg = "";
+    if (! nh)
+      set (h, s.properties);
+    else
+      ## Specials are objects that where automatically constructed with
+      ## current object. Among them are "x(yz)labels", "title", high
+      ## level hggroup children
+      fields = fieldnames (s.properties);
+      vals = struct2cell (s.properties);
+      idx = find (cellfun (@(x) valcomp(x, hdls) , vals));
+      s.properties = rmfield (s.properties, fields(idx));
+
+      ## set all properties but special handles
+      set (h, s.properties);
+
+      ## find  props with val == (one of special handles)
+      nf = length (idx);
+      fields = fields(idx);
+      vals = vals(idx);
+      while (nf)
+        field = fields{nf};
+        idx = find (hdls == vals{nf});
+        spec = specs(idx);
+        if (isprop (h, field))
+           h2 = get (h , field);
+           set (h2, spec.properties);
+        endif
+        nf--;
+      endwhile
+
+      ## If hggroup children  were created by high level functions,
+      ## copy only usefull properties.
+      if (hilev)
+        if (strcmp (s.type, "hggroup"))
+          nold = numel (s.children);
+          nnew = numel (get (h).children);
+
+          if (nold == nnew)
+            hnew = get (h).children;
+            ii = 1;
+            while (ii <= nnew)
+              try
+                set (hnew (ii), "displayname", ...
+                     s.children(ii).properties.displayname);
+              catch
+                sprintf ("struct2hdl: couldn't set hggroup children #%d props.", ii);
+              end_try_catch
+              ii ++;
+            endwhile
+
+          else
+            error ("struct2hdl: non-conformant number of children in hgggroup");
+          endif
+        endif
+      endif
+    endif
+
+  elseif (strcmpi (s.properties.tag, "legend")
+          || strcmpi (s.properties.tag, "colorbar"))
+    set (h, s.properties);
+  endif
+
+endfunction
+
+function out = valcomp (x, hdls)
+  if (isfloat (x) && isscalar (x))
+    out = any (x == hdls);
+  else
+    out = 0;
+  endif
+endfunction
+
+function addmissingprops (h, props)
+  hid = {"autopos_tag", "looseinset"};
+  oldfields = fieldnames (props);
+  curfields = fieldnames (get (h));
+  missing = cellfun (@(x) !any (strcmp (x, curfields)), oldfields);
+  idx = find (missing);
+  for ii = 1:length (idx)
+    prop = oldfields{idx(ii)};
+    if (! any (strcmp (prop, hid)))
+      addproperty (prop, h, "any");
+    endif
+  endfor
+endfunction
+
+
+## FIXME: Need validation tests
--- a/scripts/plot/subplot.m
+++ b/scripts/plot/subplot.m
@@ -313,7 +313,7 @@
   x0 = xi .* (width + margins.column) + margins.left;
   y0 = yi .* (height + margins.row) + margins.bottom;
 
-  if (numel(x0) > 1)
+  if (numel (x0) > 1)
     ## subplot (row, col, m:n)
     x1 = max (x0(:)) + width;
     y1 = max (y0(:)) + height;
@@ -327,39 +327,40 @@
 
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
 %! r = 3;
 %! c = 3;
 %! fmt = {'horizontalalignment', 'center', 'verticalalignment', 'middle'};
-%! for n = 1:(r*c)
-%!   subplot (r, c, n)
-%!   xlabel (sprintf ("xlabel #%d", n))
-%!   ylabel (sprintf ("ylabel #%d", n))
-%!   title (sprintf ("title #%d", n))
-%!   text (0.5, 0.5, sprintf('subplot(%d,%d,%d)', r, c, n), fmt{:})
-%!   axis ([0 1 0 1])
-%! endfor
-%! subplot (r, c, 1:3)
-%! xlabel (sprintf ("xlabel #%d:%d", 1, 3))
-%! ylabel (sprintf ("ylabel #%d:%d", 1, 3))
-%! title (sprintf ("title #%d:%d", 1, 3))
-%! text (0.5, 0.5, sprintf('subplot(%d,%d,%d:%d)', r, c, 1, 3), fmt{:})
-%! axis ([0 1 0 1])
+%! for n = 1 : r*c
+%!   subplot (r, c, n);
+%!   xlabel (sprintf ('xlabel #%d', n));
+%!   ylabel (sprintf ('ylabel #%d', n));
+%!   title (sprintf ('title #%d', n));
+%!   text (0.5, 0.5, sprintf ('subplot(%d,%d,%d)', r, c, n), fmt{:});
+%!   axis ([0 1 0 1]);
+%! end
+%! subplot (r, c, 1:3);
+%! xlabel (sprintf ('xlabel #%d:%d', 1, 3));
+%! ylabel (sprintf ('ylabel #%d:%d', 1, 3));
+%! title (sprintf ('title #%d:%d', 1, 3));
+%! text (0.5, 0.5, sprintf ('subplot(%d,%d,%d:%d)', r, c, 1, 3), fmt{:});
+%! axis ([0 1 0 1]);
 
 %!demo
-%! clf
+%! clf;
 %! x = 0:1;
 %! for n = 1:4
-%!   subplot (2, 2, n, "align")
-%!   plot (x, x)
-%!   xlabel (sprintf ("xlabel (2,2,%d)", n))
-%!   ylabel (sprintf ("ylabel (2,2,%d)", n))
-%!   title (sprintf ("title (2,2,%d)", n))
-%! endfor
-%! subplot (1, 2, 1, "align")
-%! plot (x, x)
-%! xlabel ("xlabel (1,2,1)")
-%! ylabel ("ylabel (1,2,1)")
-%! title ("title (1,2,1)")
+%!   subplot (2,2,n, 'align');
+%!   plot (x, x);
+%!   xlabel (sprintf ('xlabel (2,2,%d)', n));
+%!   ylabel (sprintf ('ylabel (2,2,%d)', n));
+%!   title (sprintf ('title (2,2,%d)', n));
+%! end
+%! subplot (1,2,1, 'align');
+%! plot (x, x);
+%! xlabel ('xlabel (1,2,1)');
+%! ylabel ('ylabel (1,2,1)');
+%! title ('title (1,2,1)');
 
--- a/scripts/plot/surf.m
+++ b/scripts/plot/surf.m
@@ -66,20 +66,23 @@
 
 
 %!demo
-%! clf
-%! [~,~,Z] = peaks;
+%! clf;
+%! colormap ('default');
+%! [~,~,Z] = peaks ();
 %! surf (Z);
 
 %!demo
-%! clf
-%! [~,~,Z] = sombrero;
+%! clf;
+%! colormap ('default');
+%! [~,~,Z] = sombrero ();
 %! [Fx,Fy] = gradient (Z);
 %! surf (Z, Fx+Fy);
 %! shading interp;
 
 %!demo
-%! clf
-%! [X,Y,Z] = sombrero;
+%! clf;
+%! colormap ('default');
+%! [X,Y,Z] = sombrero ();
 %! [~,Fy] = gradient (Z);
 %! surf (X, Y, Z, Fy);
 %! shading interp;
--- a/scripts/plot/surface.m
+++ b/scripts/plot/surface.m
@@ -145,7 +145,7 @@
   elseif (firststring == 1)
     x = 1:3;
     y = (x).';
-    c = z = eye(3);
+    c = z = eye (3);
   else
     bad_usage = true;
   endif
@@ -166,8 +166,8 @@
 
 endfunction
 
+
 ## Functional tests for surface() are in surf.m, surfc.m, surfl.m, and pcolor.m
-
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
@@ -175,8 +175,8 @@
 %!   assert (findobj (hf, "type", "surface"), h);
 %!   assert (get (h, "xdata"), 1:3, eps);
 %!   assert (get (h, "ydata"), (1:3)', eps);
-%!   assert (get (h, "zdata"), eye(3));
-%!   assert (get (h, "cdata"), eye(3));
+%!   assert (get (h, "zdata"), eye (3));
+%!   assert (get (h, "cdata"), eye (3));
 %!   assert (get (h, "type"), "surface");
 %!   assert (get (h, "linestyle"), get (0, "defaultsurfacelinestyle"));
 %!   assert (get (h, "linewidth"), get (0, "defaultsurfacelinewidth"), eps);
--- a/scripts/plot/surfc.m
+++ b/scripts/plot/surfc.m
@@ -74,21 +74,26 @@
 
 endfunction
 
-%!demo
-%! clf
-%! [~,~,Z]=peaks;
-%! surfc(Z);
 
 %!demo
-%! clf
-%! [~,~,Z]=sombrero;
-%! [Fx,Fy] = gradient(Z);
-%! surfc(Z,Fx+Fy);
+%! clf;
+%! colormap ('default');
+%! [~,~,Z] = peaks ();
+%! surfc (Z);
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! [~,~,Z] = sombrero ();
+%! [Fx,Fy] = gradient (Z);
+%! surfc (Z, Fx+Fy);
 %! shading interp;
 
 %!demo
-%! clf
-%! [X,Y,Z]=sombrero;
-%! [~,Fy] = gradient(Z);
-%! surfc(X,Y,Z,Fy);
+%! clf;
+%! colormap ('default');
+%! [X,Y,Z] = sombrero ();
+%! [~,Fy] = gradient (Z);
+%! surfc (X,Y,Z,Fy);
 %! shading interp;
+
--- a/scripts/plot/surfl.m
+++ b/scripts/plot/surfl.m
@@ -23,21 +23,21 @@
 ## @deftypefnx {Function File} {} surfl (@var{x}, @var{y}, @var{z}, @var{L}, @var{P})
 ## @deftypefnx {Function File} {} surfl (@dots{}, "light")
 ## Plot a lighted surface given matrices @var{x}, and @var{y} from
-## @code{meshgrid} and
-## a matrix @var{z} corresponding to the @var{x} and @var{y} coordinates of
-## the mesh.  If @var{x} and @var{y} are vectors, then a typical vertex
-## is (@var{x}(j), @var{y}(i), @var{z}(i,j)).  Thus, columns of @var{z}
-## correspond to different @var{x} values and rows of @var{z} correspond
-## to different @var{y} values.
+## @code{meshgrid} and a matrix @var{z} corresponding to the @var{x} and
+## @var{y} coordinates of the mesh.  If @var{x} and @var{y} are vectors, then
+## a typical vertex is (@var{x}(j), @var{y}(i), @var{z}(i,j)).  Thus, columns
+## of @var{z} correspond to different @var{x} values and rows of @var{z}
+## correspond to different @var{y} values.
 ##
-## The light direction can be specified using @var{L}.  It can be
-## given as 2-element vector [azimuth, elevation] in degrees or as 3-element
-## vector [lx, ly, lz].
-## The default value is rotated 45° counter-clockwise from the current view.
+## The light direction can be specified using @var{L}.  It can be given as a
+## 2-element vector [azimuth, elevation] in degrees or as a 3-element vector
+## [lx, ly, lz].  The default value is rotated 45 degrees counterclockwise
+## from the current view.
 ##
 ## The material properties of the surface can specified using a 4-element vector
 ## @var{P} = [@var{AM} @var{D} @var{SP} @var{exp}] which defaults to
 ## @var{p} = [0.55 0.6 0.4 10].
+##
 ## @table @asis
 ## @item "AM" strength of ambient light
 ##
@@ -49,10 +49,9 @@
 ## @end table
 ##
 ## The default lighting mode "cdata", changes the cdata property to give the
-## impression
-## of a lighted surface.  Please note: the alternative "light" mode, which
-## creates a light
-## object to illuminate the surface is not implemented (yet).
+## impression of a lighted surface.  Please note: the alternative "light"
+## mode, which creates a light object to illuminate the surface is not
+## implemented (yet).
 ##
 ## Example:
 ##
@@ -80,12 +79,12 @@
     ## Check for lighting type.
     use_cdata = true;
     if (ischar (varargin{end}))
-      lstr = varargin{end};
-      if (strncmp (tolower (lstr), "light", 5))
+      lstr = tolower (varargin{end});
+      if (strncmp (lstr, "light", 5))
         warning ("light method not supported (yet), using cdata method instead");
         ## This can be implemented when light objects are supported.
         use_cdata = false;
-      elseif (strncmp (tolower (lstr), "cdata", 5))
+      elseif (strncmp (lstr, "cdata", 5))
         use_cdata = true;
       else
         error ("surfl: unknown lighting method");
@@ -123,7 +122,7 @@
       endif
     endif
 
-    tmp = surface (varargin{:});
+    htmp = surface (varargin{:});
     if (! ishold ())
       set (h, "view", [-37.5, 30],
            "xgrid", "on", "ygrid", "on", "zgrid", "on", "clim", [0 1]);
@@ -144,7 +143,7 @@
       lv = (R * vv.').';
     endif
 
-    vn = get (tmp, "vertexnormals");
+    vn = get (htmp, "vertexnormals");
     dar = get (h, "plotboxaspectratio");
     vn(:,:,1) *= dar(1);
     vn(:,:,2) *= dar(2);
@@ -152,37 +151,38 @@
 
     ## Normalize vn.
     vn = vn ./ repmat (sqrt (sumsq (vn, 3)), [1, 1, 3]);
-    [nr, nc] = size(get(tmp, "zdata"));
+    [nr, nc] = size (get (htmp, "zdata"));
 
     ## Ambient, diffuse, and specular term.
     cdata = (r(1) * ones (nr, nc)
              + r(2) * diffuse  (vn(:,:,1), vn(:,:,2), vn(:,:,3), lv)
              + r(3) * specular (vn(:,:,1), vn(:,:,2), vn(:,:,3), lv, vv, r(4)));
 
-    set (tmp, "cdata", cdata ./ sum (r(1:3)));
+    set (htmp, "cdata", cdata ./ sum (r(1:3)));
 
   unwind_protect_cleanup
     axes (oldh);
   end_unwind_protect
 
   if (nargout > 0)
-    retval = tmp;
+    retval = htmp;
   endif
 
 endfunction
 
+
 %!demo
-%! clf
-%! [X,Y,Z]=sombrero;
-%! colormap(copper);
-%! surfl(X,Y,Z);
+%! clf;
+%! [X,Y,Z] = sombrero ();
+%! colormap (copper (64));
+%! surfl (X,Y,Z);
 %! shading interp;
 
 %!demo
-%! clf
-%! [X,Y,Z]=sombrero;
-%! colormap(copper);
-%! [az, el] = view;
-%! surfl(X,Y,Z,[az+225,el],[0.2 0.6 0.4 25]);
+%! clf;
+%! [X,Y,Z] = sombrero ();
+%! colormap (copper (64));
+%! [az, el] = view ();
+%! surfl (X,Y,Z, [az+225,el], [0.2 0.6 0.4 25]);
 %! shading interp;
 
--- a/scripts/plot/surfnorm.m
+++ b/scripts/plot/surfnorm.m
@@ -27,8 +27,8 @@
 ##
 ## @example
 ## @group
-## [@var{x}, @var{y}] = meshgrid (1:size (@var{z}, 1),
-##                    1:size (@var{z}, 2));
+## [@var{x}, @var{y}] = meshgrid (1:rows (@var{z}),
+##                    1:columns (@var{z}));
 ## @end group
 ## @end example
 ##
@@ -62,7 +62,7 @@
 
   if (nargin == 1)
     z = varargin{1};
-    [x, y] = meshgrid (1:size(z,1), 1:size(z,2));
+    [x, y] = meshgrid (1:rows (z), 1:columns (z));
     ioff = 2;
   else
     x = varargin{1};
@@ -96,9 +96,9 @@
   v.z = zz(1:end-1,2:end) - zz(2:end,1:end-1);
 
   c = cross ([u.x(:), u.y(:), u.z(:)], [v.x(:), v.y(:), v.z(:)]);
-  w.x = reshape (c(:,1), size(u.x));
-  w.y = reshape (c(:,2), size(u.y));
-  w.z = reshape (c(:,3), size(u.z));
+  w.x = reshape (c(:,1), size (u.x));
+  w.y = reshape (c(:,2), size (u.y));
+  w.z = reshape (c(:,3), size (u.z));
 
   ## Create normal vectors as mesh vectices from normals at mesh centers
   nx = (w.x(1:end-1,1:end-1) + w.x(1:end-1,2:end) +
@@ -141,17 +141,21 @@
 
 endfunction
 
+
 %!demo
-%! clf
-%! colormap (jet (64))
-%! [x, y, z] = peaks(10);
+%! clf;
+%! colormap ('default');
+%! [x, y, z] = peaks (10);
 %! surfnorm (x, y, z);
 
 %!demo
-%! clf
-%! surfnorm (peaks(10));
+%! clf;
+%! colormap ('default');
+%! surfnorm (peaks (10));
 
 %!demo
-%! clf
-%! surfnorm (peaks(32));
-%! shading interp
+%! clf;
+%! colormap ('default');
+%! surfnorm (peaks (32));
+%! shading interp;
+
new file mode 100644
--- /dev/null
+++ b/scripts/plot/tetramesh.m
@@ -0,0 +1,148 @@
+## Copyright (C) 2012 Martin Helm
+##
+## 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} {} tetramesh (@var{T}, @var{X})
+## @deftypefnx {Function File} {} tetramesh (@var{T}, @var{X}, @var{C})
+## @deftypefnx {Function File} {} tetramesh (@dots{}, @var{property}, @var{val}, @dots{})
+## @deftypefnx {Function File} {@var{h} =} tetramesh (@dots{})
+##
+## Display the tetrahedrons defined in the m-by-4 matrix @var{T}
+## as 3-D patches.  @var{T} is typically the output of a Delaunay triangulation
+## of a 3-D set of points.  Every row of @var{T} contains four indices into
+## the n-by-3 matrix @var{X} of the vertices of a tetrahedron.  Every row in
+## @var{X} represents one point in 3-D space. 
+##
+## The vector @var{C} specifies the color of each tetrahedron as an index
+## into the current colormap.  The default value is 1:m where m is the number
+## of tetrahedrons; the indices are scaled to map to the full range of the
+## colormap.  If there are more tetrahedrons than colors in the colormap then
+## the values in @var{C} are cyclically repeated.
+## 
+## Calling @code{tetramesh (@dots{}, "property", "value", @dots{})} passes all
+## property/value pairs directly to the patch function as additional arguments.
+##
+## The optional return value @var{h} is a vector of patch handles where each
+## handle represents one tetrahedron in the order given by @var{T}. 
+## A typical use case for @var{h} is to turn the respective patch "visible"
+## property "on" or "off".
+##
+## Type @code{demo tetramesh} to see examples on using @code{tetramesh}.
+## @seealso{delaunay3, delaunayn, trimesh, patch}
+## @end deftypefn
+
+## Author: Martin Helm <martin@mhelm.de>
+
+function h = tetramesh (varargin)
+
+  [reg, prop] = parseparams (varargin);
+
+  if (length (reg) < 2 || length (reg) > 3)
+    print_usage ();
+  endif
+
+  T = reg{1};
+  X = reg{2};
+
+  if (! ismatrix (T) || columns (T) != 4)
+    error ("tetramesh: T must be a n-by-4 matrix");
+  endif
+  if (! ismatrix (X) || columns (X) != 3)
+    error ("tetramesh: X must be a n-by-3 matrix");
+  endif
+
+  size_T = rows (T);
+  colmap = colormap ();
+  
+  if (length (reg) < 3)
+    size_colmap = rows (colmap);
+    C = mod ((1:size_T)' - 1, size_colmap) + 1;
+    if (size_T < size_colmap && size_T > 1) 
+      ## expand to the available range of colors
+      C = floor ((C - 1) * (size_colmap - 1) / (size_T - 1)) + 1;
+    endif
+  else
+    C = reg{3};
+    if (! isvector (C) || size_T != length (C))
+      error ("tetramesh: C must be a vector of the same length as T");
+    endif
+  endif
+
+  h = zeros (1, size_T);
+  if (strcmp (graphics_toolkit (), "gnuplot"))
+    ## tiny reduction of the tetrahedron size to help gnuplot by
+    ## avoiding identical faces with different colors
+    for i = 1:size_T
+      [th, p] = __shrink__ ([1 2 3 4], X(T(i, :), :), 1 - 1e-7);
+      hvec(i) = patch ("Faces", th, "Vertices", p, 
+                       "FaceColor", colmap(C(i), :), prop{:});
+    endfor
+  else
+    for i = 1:size_T
+      th = [1 2 3; 2 3 4; 3 4 1; 4 1 2];
+      hvec(i) = patch ("Faces", th, "Vertices", X(T(i, :), :), 
+                       "FaceColor", colmap(C(i), :), prop{:});
+    endfor
+  endif
+
+  if (nargout > 0)
+    h = hvec;
+  endif
+
+endfunction
+
+## shrink the tetrahedron relative to its center of gravity
+function [tri, p] = __shrink__ (T, X, sf)
+  midpoint = repmat (sum (X(T, :), 1) / 4, 12, 1);
+  p = [X([1 2 3], :); X([2 3 4], :); X([3 4 1], :); X([4 1 2], :)];
+  p = sf * (p - midpoint) + midpoint;
+  tri = reshape (1:12, 3, 4)';
+endfunction
+
+
+%!demo
+%! clf;
+%! d = [-1 1];
+%! [x,y,z] = meshgrid (d, d, d);
+%! x = [x(:); 0];
+%! y = [y(:); 0];
+%! z = [z(:); 0];
+%! tetra = delaunay3 (x, y, z);
+%! X = [x(:) y(:) z(:)];
+%! colormap (jet (64));
+%! h = tetramesh (tetra, X);
+%! set (h(1:2:end), "Visible", "off");
+%! axis equal;
+%! view (30, 20);
+%! title ("Using jet (64), every other tetrahedron invisible");
+
+%!demo
+%! clf;
+%! d = [-1 1];
+%! [x,y,z] = meshgrid (d, d, d);
+%! x = [x(:); 0];
+%! y = [y(:); 0];
+%! z = [z(:); 0];
+%! tetra = delaunay3 (x, y, z);
+%! X = [x(:) y(:) z(:)];
+%! colormap (gray (256));
+%! tetramesh (tetra, X, 21:20:241, "EdgeColor", "w");
+%! axis equal;
+%! view (30, 20);
+%! title ("Using gray (256) and white edges");
+
--- a/scripts/plot/text.m
+++ b/scripts/plot/text.m
@@ -32,6 +32,9 @@
 
 ## Author: jwe
 
+## Note: The following code is rigged for Matlab compatibility and is
+##       full of hidden assumptions.  Be very wary when modifying.
+
 function h = text (varargin)
 
   nargs = nargin;
@@ -40,7 +43,6 @@
   if (nargs > 2 && isnumeric (varargin{1}) && isnumeric (varargin{2}))
     x = varargin{1};
     y = varargin{2};
-    offset = 3;
 
     if (nargin > 3 && isnumeric (varargin{3}))
       z = varargin{3};
@@ -56,167 +58,188 @@
     nx = numel (x);
     ny = numel (y);
     nz = numel (z);
-    if (ischar (label) || isnumeric (label))
-      nt = size (label, 1);
-      if (nx > 1 && nt == 1)
-        ## Mutiple text objects with same string
-        label = repmat ({label}, [nx, 1]);
-        nt = nx;
+    if (ischar (label))
+
+      do_keyword_repl = true;
+      nt = rows (label);
+      if (nx == 1 && nt == 1)
+        ## Single text object with one line
+        label = {label};
+      elseif (nx == 1 && nt > 1)
+        ## Single text object with multiple lines
+        ## FIXME: "default" or "factory" as first row
+        ##        should be escaped to "\default" or "\factory"
+        ##        Other rows do not require escaping.
+        do_keyword_repl = false;
+        label = {label};
       elseif (nx > 1 && nt == nx)
         ## Mutiple text objects with different strings
         label = cellstr (label);
-      elseif (ischar (label))
-        ## Single text object with one or more lines
-        label = {label};
-      endif
-    elseif (iscell (label))
-      nt = numel (label);
-      if (nx > 1 && nt == 1)
+      else 
+        ## Mutiple text objects with same string
         label = repmat ({label}, [nx, 1]);
         nt = nx;
-      elseif (! (nx > 1 && nt == nx))
+      endif
+
+      ## Escape special keywords
+      if (do_keyword_repl)
+        label = regexprep (label, '^(default|factory)$', '\\$1');
+      endif
+
+    elseif (iscell (label))
+
+      nt = numel (label);
+      if (nx == 1)      
+        ## Single text object with one or more lines
         label = {label};
         nt = 1;
+      elseif (nx > 1 && nt == nx)
+        ## Mutiple text objects with different strings
+      else
+        ## Mutiple text objects with same string
+        label = repmat ({label}, [nx, 1]);
+        nt = nx;
       endif
+
     else
-      error ("text: expecting LABEL to be a character string or cell array of character strings");
+
+      error ("text: LABEL must be a character string or cell array of character strings");
+
     endif
-  else
+  else  # Only PROP/VALUE pairs
     x = y = z = 0;
     nx = ny = nz = 1;
     label = {""};
     nt = 1;
   endif
 
-  if (rem (numel (varargin), 2) == 0)
+  ## Any remaining inputs must occur as PROPERTY/VALUE pairs
+  if (rem (numel (varargin), 2) != 0)
+    print_usage ();
+  endif
 
-    if (nx == ny && nx == nz && (nt == nx || nt == 1 || nx == 1))
-      pos = [x(:), y(:), z(:)];
-      ca = gca ();
-      tmp = zeros (nt, 1);
-      if (nx == 1)
-        ## TODO - Modify __go_text__() to accept cell-strings
-        tmp = __go_text__ (ca, "string", "foobar",
-                           varargin{:},
-                           "position", pos);
-        set (tmp, "string", label{1});
-      elseif (nt == nx)
-        for n = 1:nt
-          tmp(n) = __go_text__ (ca, "string", label{n},
-                                varargin{:},
-                                "position", pos(n,:));
-        endfor
-        __request_drawnow__ ();
-      else
-        error ("text: dimension mismatch for coordinates and LABEL");
-      endif
-    elseif (nt == nx || nt == 1 || nx == 1)
-      error ("text: dimension mismatch for coordinates");
+  if (nx == ny && nx == nz && (nt == nx || nt == 1 || nx == 1))
+    pos = [x(:), y(:), z(:)];
+    ca = gca ();
+    htmp = zeros (nt, 1);
+    if (nx == 1)
+      htmp = __go_text__ (ca, "string", label{1},
+                          varargin{:},
+                          "position", pos);
+    elseif (nx == nt)
+      for n = 1:nt
+        htmp(n) = __go_text__ (ca, "string", label{n},
+                               varargin{:},
+                               "position", pos(n,:));
+      endfor
+      __request_drawnow__ ();
     else
-      error ("text: mismatch betwween coordinates and strings");
+      error ("text: dimension mismatch for coordinates and LABEL");
     endif
+  elseif (nt == nx || nt == 1 || nx == 1)
+    error ("text: dimension mismatch for coordinates");
+  else
+    error ("text: dimension mismatch between coordinates and strings");
+  endif
 
-    if (nargout > 0)
-      h = tmp;
-    endif
-
-  else
-    print_usage ();
+  if (nargout > 0)
+    h = htmp;
   endif
 
 endfunction
 
-%!demo
-%! clf
-%! ha = {"left", "center", "right"};
-%! va = {"bottom", "middle", "top"};
-%! x = [0.25 0.5 0.75];
-%! y = [0.25 0.5 0.75];
-%! for t = 0:30:359;
-%!   for nh = 1:numel(ha)
-%!     for nv = 1:numel(va)
-%!       text (x(nh), y(nv), "Hello World", ...
-%!             "rotation", t, ...
-%!             "horizontalalignment", ha{nh}, ...
-%!             "verticalalignment", va{nv});
-%!     endfor
-%!   endfor
-%! endfor
-%! set (gca, "xtick", [0.25, 0.5, 0.75], ...
-%!           "xticklabel", ha, ...
-%!           "ytick", [0.25, 0.5, 0.75], ...
-%!           "yticklabel", va);
-%! axis ([0 1 0 1]);
-%! xlabel ("horizontal alignment");
-%! ylabel ("vertical alignment");
-%! title ("text alignment and rotation (0:30:360 degrees)")
 
 %!demo
-%! clf
-%! h = mesh (peaks, "edgecolor", 0.7 * [1 1 1], ...
-%!                  "facecolor", "none", ...
-%!                  "facealpha", 0);
+%! clf;
+%! ha = {'left', 'center', 'right'};
+%! va = {'bottom', 'middle', 'top'};
+%! x = [0.25 0.5 0.75];
+%! y = x;
+%! for t = 0:30:359;
+%!   for nh = 1:numel (ha)
+%!     for nv = 1:numel (va)
+%!       text (x(nh), y(nv), 'Hello World', ...
+%!             'rotation', t, ...
+%!             'horizontalalignment', ha{nh}, ...
+%!             'verticalalignment', va{nv});
+%!     end
+%!   end
+%! end
+%! set (gca, 'xtick', [0.25, 0.5, 0.75], ...
+%!           'xticklabel', ha, ...
+%!           'ytick', [0.25, 0.5, 0.75], ...
+%!           'yticklabel', va);
+%! axis ([0 1 0 1]);
+%! xlabel ('horizontal alignment');
+%! ylabel ('vertical alignment');
+%! title ('text alignment and rotation (0:30:360 degrees)');
+
+%!demo
+%! clf;
+%! h = mesh (peaks, 'edgecolor', 0.7 * [1 1 1], ...
+%!                  'facecolor', 'none', ...
+%!                  'facealpha', 0);
 %! for t = 0:45:359;
-%!   text (25, 25, 0, "Vertical Alignment = Bottom", ...
-%!                    "rotation", t, ...
-%!                    "horizontalalignment", "left", ...
-%!                    "verticalalignment", "bottom");
-%! endfor
+%!   text (25, 25, 0, 'Vertical Alignment = Bottom', ...
+%!                    'rotation', t, ...
+%!                    'horizontalalignment', 'left', ...
+%!                    'verticalalignment', 'bottom');
+%! end
 %! caxis ([-100 100]);
-%! title ("Vertically Aligned at Bottom");
+%! title ('Vertically Aligned at Bottom');
 
 %!demo
-%! clf
+%! clf;
 %! axis ([0 8 0 8]);
-%! title (["1st title";"2nd title"]);
-%! xlabel (["1st xlabel";"2nd xlabel"]);
-%! ylabel (["1st ylabel";"2nd ylabel"]);
-%! text (4, 4, {"Hello", "World"}, ...
-%!       "horizontalalignment", "center", ...
-%!       "verticalalignment", "middle");
-%! grid on
+%! title (['1st title';'2nd title']);
+%! xlabel (['1st xlabel';'2nd xlabel']);
+%! ylabel (['1st ylabel';'2nd ylabel']);
+%! text (4, 4, {'Hello', 'World'}, ...
+%!       'horizontalalignment', 'center', ...
+%!       'verticalalignment', 'middle');
+%! grid on;
 
 %!demo
-%! clf
-%! h = mesh (peaks, "edgecolor", 0.7 * [1 1 1], ...
-%!                  "facecolor", "none", ...
-%!                  "facealpha", 0);
-%! title (["1st title";"2nd title"]);
-%! xlabel (["1st xlabel";"2nd xlabel"]);
-%! ylabel (["1st ylabel";"2nd ylabel"]);
-%! zlabel (["1st zlabel";"2nd zlabel"]);
-%! text (0, 0, 5, {"Hello", "World"}, ...
-%!       "horizontalalignment", "center", ...
-%!       "verticalalignment", "middle");
+%! clf;
+%! h = mesh (peaks (), 'edgecolor', 0.7 * [1 1 1], ...
+%!                     'facecolor', 'none', ...
+%!                     'facealpha', 0);
+%! title (['1st title';'2nd title']);
+%! xlabel (['1st xlabel';'2nd xlabel']);
+%! ylabel (['1st ylabel';'2nd ylabel']);
+%! zlabel (['1st zlabel';'2nd zlabel']);
+%! text (0, 0, 5, {'Hello', 'World'}, ...
+%!       'horizontalalignment', 'center', ...
+%!       'verticalalignment', 'middle');
 %! hold on;
-%! plot3 (0, 0, 5, "+k");
+%! plot3 (0, 0, 5, '+k');
 
 %!demo
-%! clf
-%! h = text (0.5, 0.3, "char");
-%! assert ("char", class (get (h, "string")));
-%! h = text (0.5, 0.4, ["char row 1"; "char row 2"]);
-%! assert ("char", class (get (h, "string")));
-%! h = text (0.5, 0.6, {"cell2str (1,1)", "cell2str (1,2)"; "cell2str (2,1)", "cell2str (2,2)"});
-%! assert ("cell", class (get (h, "string")));
-%! h = text (0.5, 0.8, "foobar");
-%! set (h, "string", 1:3);
-%! h = text ([0.1, 0.1], [0.3, 0.4], "one string & two objects");
-%! assert ("char", class (get (h(1), "string")));
-%! assert ("char", class (get (h(2), "string")));
-%! h = text ([0.1, 0.1], [0.5, 0.6], {"one cellstr & two objects"});
-%! assert ("cell", class (get (h(1), "string")));
-%! assert ("cell", class (get (h(2), "string")));
-%! h = text ([0.1, 0.1], [0.7, 0.8], {"cellstr 1 object 1", "cellstr 2 object 2"});
-%! assert ("char", class (get (h(1), "string")));
-%! assert ("char", class (get (h(2), "string")));
-%! h = text ([0.1, 0.1], [0.1, 0.2], ["1st string & 1st object"; "2nd string & 2nd object"]);
-%! assert ("char", class (get (h(1), "string")));
-%! assert ("char", class (get (h(2), "string")));
-%! h = text (0.7, 0.6, "single string");
-%! assert ("char", class (get (h, "string")));
-%! h = text (0.7, 0.5, {"single cell-string"});
-%! assert ("cell", class (get (h, "string")));
+%! clf;
+%! h = text (0.5, 0.3, 'char');
+%! assert ('char', class (get (h, 'string')));
+%! h = text (0.5, 0.4, ['char row 1'; 'char row 2']);
+%! assert ('char', class (get (h, 'string')));
+%! h = text (0.5, 0.6, {'cell2str (1,1)', 'cell2str (1,2)'; 'cell2str (2,1)', 'cell2str (2,2)'});
+%! assert ('cell', class (get (h, 'string')));
+%! h = text (0.5, 0.8, 'foobar');
+%! set (h, 'string', 1:3);
+%! h = text ([0.1, 0.1], [0.3, 0.4], 'one string & two objects');
+%! assert ('char', class (get (h(1), 'string')));
+%! assert ('char', class (get (h(2), 'string')));
+%! h = text ([0.1, 0.1], [0.5, 0.6], {'one cellstr & two objects'});
+%! assert ('cell', class (get (h(1), 'string')));
+%! assert ('cell', class (get (h(2), 'string')));
+%! h = text ([0.1, 0.1], [0.7, 0.8], {'cellstr 1 object 1', 'cellstr 2 object 2'});
+%! assert ('char', class (get (h(1), 'string')));
+%! assert ('char', class (get (h(2), 'string')));
+%! h = text ([0.1, 0.1], [0.1, 0.2], ['1st string & 1st object'; '2nd string & 2nd object']);
+%! assert ('char', class (get (h(1), 'string')));
+%! assert ('char', class (get (h(2), 'string')));
+%! h = text (0.7, 0.6, 'single string');
+%! assert ('char', class (get (h, 'string')));
+%! h = text (0.7, 0.5, {'single cell-string'});
+%! assert ('cell', class (get (h, 'string')));
 %! xlabel (1:2);
 %! ylabel (1:2);
 %! title (1:2);
@@ -224,30 +247,70 @@
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
-%!   h = text (0.5, 0.3, "char");
-%!   assert ("char", class (get (h, "string")));
+%!   ## Single object with one line
+%!   h = text (0.5, 0.3, "single object with one line");
+%!   obs = get (h, "string");
+%!   assert (class (obs), "char");
+%!   assert (obs, "single object with one line");
+%!
+%!   ## Single object with multiple lines
 %!   h = text (0.5, 0.4, ["char row 1"; "char row 2"]);
-%!   assert ("char", class (get (h, "string")));
-%!   h = text (0.5, 0.6, {"cell2str (1,1)", "cell2str (1,2)"; "cell2str (2,1)", "cell2str (2,2)"});
-%!   assert ("cell", class (get (h, "string")));
-%!   h = text (0.5, 0.8, "foobar");
-%!   set (h, "string", 1:3);
-%!   h = text ([0.1, 0.1], [0.3, 0.4], "one string & two objects");
-%!   assert ("char", class (get (h(1), "string")));
-%!   assert ("char", class (get (h(2), "string")));
-%!   h = text ([0.1, 0.1], [0.5, 0.6], {"one cellstr & two objects"});
-%!   assert ("cell", class (get (h(1), "string")));
-%!   assert ("cell", class (get (h(2), "string")));
-%!   h = text ([0.1, 0.1], [0.7, 0.8], {"cellstr 1 object 1", "cellstr 2 object 2"});
-%!   assert ("char", class (get (h(1), "string")));
-%!   assert ("char", class (get (h(2), "string")));
-%!   h = text ([0.1, 0.1], [0.1, 0.2], ["1st string & 1st object"; "2nd string & 2nd object"]);
-%!   assert ("char", class (get (h(1), "string")));
-%!   assert ("char", class (get (h(2), "string")));
-%!   h = text (0.7, 0.6, "single string");
-%!   assert ("char", class (get (h, "string")));
-%!   h = text (0.7, 0.5, {"single cell-string"});
-%!   assert ("cell", class (get (h, "string")));
+%!   obs = get (h, "string");
+%!   assert (class (obs), "char");
+%!   assert (obs, ["char row 1"; "char row 2"]);
+%!
+%!   ## Multiple objects with single line
+%!   h = text ([0.1, 0.1], [0.3, 0.4], "two objects with same string");
+%!   assert (class (get (h(1), "string")), "char");
+%!   assert (class (get (h(2), "string")), "char");
+%!   assert (get (h(1), "string"), "two objects with same string");
+%!   assert (get (h(2), "string"), "two objects with same string");
+%!
+%!   ## Multiple objects with multiple lines
+%!   h = text ([0.1, 0.1], [0.3, 0.4], ["string1"; "string2"]);
+%!   assert (class (get (h(1), "string")), "char");
+%!   assert (class (get (h(2), "string")), "char");
+%!   assert (get (h(1), "string"), "string1");
+%!   assert (get (h(2), "string"), "string2");
+%!
+%!   ### Tests repeated with cell input ###
+%!
+%!   ## Single object with one line
+%!   h = text (0.5, 0.3, {"single object with one line"});
+%!   obs = get (h, "string");
+%!   assert (class (obs), "cell");
+%!   assert (obs, {"single object with one line"});
+%!
+%!   ## Single object with multiple lines
+%!   h = text (0.5, 0.6, {"cell2str (1,1)", "cell2str (1,2)";
+%!                        "cell2str (2,1)", "cell2str (2,2)"});
+%!   obs = get (h, "string");
+%!   assert (class (obs), "cell");
+%!   assert (obs, {"cell2str (1,1)"; "cell2str (2,1)";
+%!                 "cell2str (1,2)"; "cell2str (2,2)"});
+%!
+%!   ## Multiple objects with single line
+%!   h = text ([0.1, 0.1], [0.5, 0.6], {"two objects with same cellstr"});
+%!   assert (class (get (h(1), "string")), "cell");
+%!   assert (class (get (h(2), "string")), "cell");
+%!   ## FIXME: is return value of cellstr, rather than string, Matlab-verified?
+%!   assert (get (h(1), "string"), {"two objects with same cellstr"});
+%!   assert (get (h(2), "string"), {"two objects with same cellstr"});
+%!
+%!   ## Multiple objects with multiple lines
+%!   h = text ([0.1, 0.1], [0.7, 0.8], {"cellstr1", "cellstr2"});
+%!   ## FIXME: is return value really char in Matlab?
+%!   assert (class (get (h(1), "string")), "char");
+%!   assert (class (get (h(2), "string")), "char");
+%!   assert (get (h(1), "string"), "cellstr1");
+%!   assert (get (h(2), "string"), "cellstr2");
+%!
+%!   ## Test special keyword processing
+%!   h = text (0.5, 0.5, "default");
+%!   assert (get (h, "string"), "default")
+%!   h = text (0.5, 0.5, "factory");
+%!   assert (get (h, "string"), "factory")
+%!
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
--- a/scripts/plot/title.m
+++ b/scripts/plot/title.m
@@ -46,26 +46,26 @@
 
 
 %!demo
-%! clf ();
-%! ax = axes();
-%! xl = get (ax,"title");
-%! title ("Testing title");
-%! assert (get (xl,"string"), "Testing title");
+%! clf;
+%! ax = axes ();
+%! xl = get (ax, 'title');
+%! title ('Testing title');
+%! assert (get (xl, 'string'), 'Testing title');
 
 %!demo
-%! clf ();
+%! clf;
 %! plot3 ([0,1], [0,1], [0,1]);
-%! xl = get(gca (), "title");
-%! title ("Testing title");
-%! assert (get (xl,"string"),"Testing title");
+%! xl = get (gca, 'title');
+%! title ('Testing title');
+%! assert (get (xl, 'string'), 'Testing title');
 
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
-%!   ax = axes();
-%!   xl = get (ax,"title");
+%!   ax = axes ();
+%!   xl = get (ax, "title");
 %!   title ("Testing title");
-%!   assert (get (xl,"string"), "Testing title");
+%!   assert (get (xl, "string"), "Testing title");
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
@@ -74,9 +74,9 @@
 %! hf = figure ("visible", "off");
 %! unwind_protect
 %!   plot3 ([0,1], [0,1], [0,1]);
-%!   xl = get (gca (), "title");
-%!   title("Testing title");
-%!   assert (get (xl,"string"), "Testing title");
+%!   xl = get (gca, "title");
+%!   title ("Testing title");
+%!   assert (get (xl, "string"), "Testing title");
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
--- a/scripts/plot/trimesh.m
+++ b/scripts/plot/trimesh.m
@@ -41,10 +41,10 @@
   else
     newplot ();
     handle = patch ("Vertices", [x(:), y(:), z(:)], "Faces", tri,
-                    "FaceColor", "none", "EdgeColor", __next_line_color__(),
+                    "FaceColor", "none", "EdgeColor", __next_line_color__ (),
                     varargin{:});
     if (! ishold ())
-      set (gca(), "view", [-37.5, 30],
+      set (gca (), "view", [-37.5, 30],
            "xgrid", "on", "ygrid", "on", "zgrid", "on");
     endif
     if (nargout > 0)
@@ -56,10 +56,10 @@
 
 
 %!demo
-%! clf
-%! old_state = rand ("state");
-%! restore_state = onCleanup (@() rand ("state", old_state));
-%! rand ("state", 10);
+%! clf;
+%! old_state = rand ('state');
+%! restore_state = onCleanup (@() rand ('state', old_state));
+%! rand ('state', 10);
 %! N = 10;
 %! x = 3 - 6 * rand (N, N);
 %! y = 3 - 6 * rand (N, N);
--- a/scripts/plot/triplot.m
+++ b/scripts/plot/triplot.m
@@ -48,10 +48,10 @@
 
 
 %!demo
-%! clf
-%! old_state = rand ("state");
-%! restore_state = onCleanup (@() rand ("state", old_state));
-%! rand ("state", 2);
+%! clf;
+%! old_state = rand ('state');
+%! restore_state = onCleanup (@() rand ('state', old_state));
+%! rand ('state', 2);
 %! N = 20;
 %! x = rand (N, 1);
 %! y = rand (N, 1);
--- a/scripts/plot/trisurf.m
+++ b/scripts/plot/trisurf.m
@@ -64,40 +64,44 @@
     endif
 
     if (! ishold ())
-      set (gca(), "view", [-37.5, 30],
+      set (gca (), "view", [-37.5, 30],
            "xgrid", "on", "ygrid", "on", "zgrid", "on");
     endif
   endif
 
 endfunction
 
+
 %!demo
-%! clf
+%! clf;
+%! colormap ('default');
 %! N = 31;
 %! [x, y] = meshgrid (1:N);
 %! tri = delaunay (x, y);
 %! z = peaks (N);
-%! h = trisurf (tri, x, y, z, "facecolor", "interp");
-%! axis tight
-%! zlim auto
-%! title (sprintf ("facecolor = %s", get (h, "facecolor")))
+%! h = trisurf (tri, x, y, z, 'facecolor', 'interp');
+%! axis tight;
+%! zlim auto;
+%! title (sprintf ('facecolor = %s', get (h, 'facecolor')));
 
 %!demo
-%! clf
+%! clf;
+%! colormap ('default');
 %! N = 31;
 %! [x, y] = meshgrid (1:N);
 %! tri = delaunay (x, y);
 %! z = peaks (N);
-%! h = trisurf (tri, x, y, z, "facecolor", "flat");
-%! axis tight
-%! zlim auto
-%! title (sprintf ("facecolor = %s", get (h, "facecolor")))
+%! h = trisurf (tri, x, y, z, 'facecolor', 'flat');
+%! axis tight;
+%! zlim auto;
+%! title (sprintf ('facecolor = %s', get (h, 'facecolor')));
 
 %!demo
-%! clf
-%! old_state = rand ("state");
-%! restore_state = onCleanup (@() rand ("state", old_state));
-%! rand ("state", 10);
+%! clf;
+%! colormap ('default');
+%! old_state = rand ('state');
+%! restore_state = onCleanup (@() rand ('state', old_state));
+%! rand ('state', 10);
 %! N = 10;
 %! x = 3 - 6 * rand (N, N);
 %! y = 3 - 6 * rand (N, N);
@@ -106,7 +110,8 @@
 %! trisurf (tri, x(:), y(:), z(:));
 
 %!demo
-%! clf
+%! clf;
+%! colormap ('default');
 %! x = rand (100, 1);
 %! y = rand (100, 1);
 %! z = x.^2 + y.^2;
@@ -114,18 +119,20 @@
 %! trisurf (tri, x, y, z);
 
 %!demo
-%! clf
+%! clf;
+%! colormap ('default');
 %! x = rand (100, 1);
 %! y = rand (100, 1);
 %! z = x.^2 + y.^2;
 %! tri = delaunay (x, y);
-%! trisurf (tri, x, y, z, "facecolor", "interp");
+%! trisurf (tri, x, y, z, 'facecolor', 'interp');
 
 %!demo
-%! clf
+%! clf;
+%! colormap ('default');
 %! x = rand (100, 1);
 %! y = rand (100, 1);
 %! z = x.^2 + y.^2;
 %! tri = delaunay (x, y);
-%! trisurf (tri, x, y, z, "facecolor", "interp", "edgecolor", "k");
+%! trisurf (tri, x, y, z, 'facecolor', 'interp', 'edgecolor', 'k');
 
--- a/scripts/plot/uicontextmenu.m
+++ b/scripts/plot/uicontextmenu.m
@@ -17,7 +17,7 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {@var{handle} =} uicontextmenu ('Name', value, @dots{})
+## @deftypefn {Function File} {@var{handle} =} uicontextmenu ("Name", value, @dots{})
 ## @end deftypefn
 
 ## Author: goffioul
--- a/scripts/plot/uicontrol.m
+++ b/scripts/plot/uicontrol.m
@@ -17,8 +17,8 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {@var{handle} =} uicontrol ('Name', value, @dots{})
-## @deftypefnx {Function File} {@var{handle} =} uicontrol (@var{parent}, 'Name', value, @dots{})
+## @deftypefn  {Function File} {@var{handle} =} uicontrol ("Name", value, @dots{})
+## @deftypefnx {Function File} {@var{handle} =} uicontrol (@var{parent}, "Name", value, @dots{})
 ## @deftypefnx {Function File} {} uicontrol (@var{handle})
 ## @end deftypefn
 
--- a/scripts/plot/uigetdir.m
+++ b/scripts/plot/uigetdir.m
@@ -23,7 +23,7 @@
 ## Open a GUI dialog for selecting a directory.  If @var{init_path} is not
 ## given the current working directory is used.  @var{dialog_name} may be
 ## used to customize the dialog title.
-## @seealso{uigetfile}
+## @seealso{uigetfile, uiputfile}
 ## @end deftypefn
 
 ## Author: Kai Habel
@@ -58,9 +58,10 @@
 
 endfunction
 
+
 %!demo
-%! uigetdir(pwd, "Select Directory")
+%! uigetdir (pwd, 'Select Directory');
 
 ## Remove from test statistics.  No real tests possible.
-%!test
-%! assert (1);
+%!assert (1)
+
--- a/scripts/plot/uigetfile.m
+++ b/scripts/plot/uigetfile.m
@@ -24,7 +24,7 @@
 ## @deftypefnx {Function File} {[@dots{}] =} uigetfile (@dots{}, "Position", [@var{px} @var{py}])
 ## @deftypefnx {Function File} {[@dots{}] =} uigetfile (@dots{}, "MultiSelect", @var{mode})
 ##
-## Open a GUI dialog for selecting a file.  It returns the filename @var{fname},
+## Open a GUI dialog for selecting a file and return the filename @var{fname},
 ## the path to this file @var{fpath}, and the filter index @var{fltidx}.
 ## @var{flt} contains a (list of) file filter string(s) in one of the following
 ## formats:
@@ -58,25 +58,28 @@
 ## and a 2-element vector containing the pixel coordinates.
 ## Two or more files can be selected when setting the "MultiSelect" key to "on".
 ## In that case @var{fname} is a cell array containing the files.
+## @seealso{uiputfile, uigetdir}
 ## @end deftypefn
 
 ## Author: Kai Habel
 
 function [retfile, retpath, retindex] = uigetfile (varargin)
 
-  defaulttoolkit = get (0, "defaultfigure__graphics_toolkit__");
-  funcname = ["__uigetfile_", defaulttoolkit, "__"];
-  functype = exist (funcname);
-  if (! __is_function__ (funcname))
-    funcname = "__uigetfile_fltk__";
+  if (! __octave_link_enabled__ ())
+    defaulttoolkit = get (0, "defaultfigure__graphics_toolkit__");
+    funcname = ["__uigetfile_", defaulttoolkit, "__"];
+    functype = exist (funcname);
     if (! __is_function__ (funcname))
-      error ("uigetfile: fltk graphics toolkit required");
-    elseif (! strcmp (defaulttoolkit, "gnuplot"))
-      warning ("uigetfile: no implementation for toolkit '%s', using 'fltk' instead",
+      funcname = "__uigetfile_fltk__";
+      if (! __is_function__ (funcname))
+        error ("uigetfile: fltk graphics toolkit required");
+      elseif (! strcmp (defaulttoolkit, "gnuplot"))
+        warning ("uigetfile: no implementation for toolkit '%s', using 'fltk' instead",
                defaulttoolkit);
+      endif
     endif
   endif
-
+  
   if (nargin > 7)
     error ("uigetfile: number of input arguments must be less than eight");
   endif
@@ -98,9 +101,10 @@
     for i = 1 : length (varargin)
       val = varargin{i};
       if (ischar (val))
-        if (strncmpi (val, "multiselect", 11))
+        val = tolower (val);
+        if (strncmp (val, "multiselect", 11))
           idx1 = i;
-        elseif (strncmpi (val, "position", 8))
+        elseif (strncmp (val, "position", 8))
           idx2 = i;
         endif
       endif
@@ -164,7 +168,7 @@
       prop = varargin{i};
       val = varargin{i + 1};
       if (strncmp (tolower (prop), "position", 8))
-        if (ismatrix (val) && length(val) == 2)
+        if (ismatrix (val) && length (val) == 2)
           outargs{4} = val;
         else
           error ("uigetfile: expecting 2-element vector for position argument");
@@ -181,13 +185,18 @@
     endfor
   endif
 
-  [retfile, retpath, retindex] = feval (funcname, outargs{:});
+  if (__octave_link_enabled__ ())
+    [retfile, retpath, retindex] = __octave_link_file_dialog__ (outargs{:});
+  else
+    [retfile, retpath, retindex] = feval (funcname, outargs{:});
+  endif
 
 endfunction
 
+
 %!demo
-%! uigetfile({"*.gif;*.png;*.jpg", "Supported Picture Formats"})
+%! uigetfile ({'*.gif;*.png;*.jpg', 'Supported Picture Formats'});
 
 ## Remove from test statistics.  No real tests possible.
-%!test
-%! assert (1);
+%!assert (1)
+
--- a/scripts/plot/uimenu.m
+++ b/scripts/plot/uimenu.m
@@ -91,14 +91,14 @@
 
 
 %!demo
-%! clf
+%! clf;
 %! surfl (peaks);
-%! colormap (copper);
-%! shading ("interp");
-%! f = uimenu ("label", "&File", "accelerator", "f");
-%! e = uimenu ("label", "&Edit", "accelerator", "e");
-%! uimenu (f, "label", "Close", "accelerator", "q", "callback", "close (gcf)");
-%! uimenu (e, "label", "Toggle &Grid", "accelerator", "g", "callback", "grid (gca)");
+%! colormap (copper (64));
+%! shading ('interp');
+%! f = uimenu ('label', '&File', 'accelerator', 'f');
+%! e = uimenu ('label', '&Edit', 'accelerator', 'e');
+%! uimenu (f, 'label', 'Close', 'accelerator', 'q', 'callback', 'close (gcf)');
+%! uimenu (e, 'label', 'Toggle &Grid', 'accelerator', 'g', 'callback', 'grid (gca)');
 
 %!testif HAVE_FLTK
 %! toolkit = graphics_toolkit ();
@@ -124,11 +124,11 @@
 %! hf = figure ("visible", "off");
 %! unwind_protect
 %!   uif = findall (hf, "label", "&file");
-%!   assert (ishghandle (uif))
+%!   assert (ishghandle (uif));
 %!   uie = findall (hf, "label", "&edit");
-%!   assert (ishghandle (uie))
+%!   assert (ishghandle (uie));
 %!   uih = findall (hf, "label", "&help");
-%!   assert (ishghandle (uih))
+%!   assert (ishghandle (uih));
 %! unwind_protect_cleanup
 %!   close (hf);
 %!   graphics_toolkit (toolkit);
@@ -141,7 +141,7 @@
 %! unwind_protect
 %!   uie = findall (hf, "label", "&edit");
 %!   myui = uimenu (uie, "label", "mylabel");
-%!   assert (ancestor (myui, "uimenu", "toplevel"), uie)
+%!   assert (ancestor (myui, "uimenu", "toplevel"), uie);
 %! unwind_protect_cleanup
 %!   close (hf);
 %!   graphics_toolkit (toolkit);
--- a/scripts/plot/uipanel.m
+++ b/scripts/plot/uipanel.m
@@ -17,8 +17,8 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {@var{handle} =} uipanel ('Name', value, @dots{})
-## @deftypefnx {Function File} {@var{handle} =} uipanel (@var{parent}, 'Name', value, @dots{})
+## @deftypefn  {Function File} {@var{handle} =} uipanel ("Name", value, @dots{})
+## @deftypefnx {Function File} {@var{handle} =} uipanel (@var{parent}, "Name", value, @dots{})
 ## @end deftypefn
 
 ## Author: goffioul
--- a/scripts/plot/uipushtool.m
+++ b/scripts/plot/uipushtool.m
@@ -17,8 +17,8 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {@var{handle} =} uipushtool ('Name', value, @dots{})
-## @deftypefnx {Function File} {@var{handle} =} uipushtool (@var{parent}, 'Name', value, @dots{})
+## @deftypefn  {Function File} {@var{handle} =} uipushtool ("Name", value, @dots{})
+## @deftypefnx {Function File} {@var{handle} =} uipushtool (@var{parent}, "Name", value, @dots{})
 ## @end deftypefn
 
 ## Author: goffioul
--- a/scripts/plot/uiputfile.m
+++ b/scripts/plot/uiputfile.m
@@ -30,41 +30,44 @@
 ## extracted and used as filter.
 ## In addition the path is selected as current path and the filename is selected
 ## as default file.
-## Example: uiputfile("myfun.m");
+## Example: uiputfile ("myfun.m");
 ##
 ## @item "*.ext"
 ## A single file extension.
-## Example: uiputfile("*.ext");
+## Example: uiputfile ("*.ext");
 ##
 ## @item @{"*.ext","My Description"@}
 ## A 2-column cell array containing the file extension in the 1st column and
 ## a brief description in the 2nd column.
-## Example: uiputfile(@{"*.ext","My Description";"*.xyz","XYZ-Format"@});
+## Example: uiputfile (@{"*.ext","My Description";"*.xyz","XYZ-Format"@});
 ## @end table
 ##
 ## The filter string can also contain a semicolon separated list of filter
 ## extensions.
-## Example: uiputfile(@{"*.gif;*.png;*.jpg", "Supported Picture Formats"@});
+## Example: uiputfile (@{"*.gif;*.png;*.jpg", "Supported Picture Formats"@});
 ##
 ## @var{dialog_name} can be used to customize the dialog title.
 ## If @var{default_file} is given it is preselected in the GUI dialog.
 ## If, in addition, a path is given it is also used as current path.
+## @seealso{uigetfile, uigetdir}
 ## @end deftypefn
 
 ## Author: Kai Habel
 
 function [retfile, retpath, retindex] = uiputfile (varargin)
 
-  defaulttoolkit = get (0, "defaultfigure__graphics_toolkit__");
-  funcname = ["__uiputfile_", defaulttoolkit, "__"];
-  functype = exist (funcname);
-  if (! __is_function__ (funcname))
-    funcname = "__uiputfile_fltk__";
+  if (! __octave_link_enabled__ ())
+    defaulttoolkit = get (0, "defaultfigure__graphics_toolkit__");
+    funcname = ["__uiputfile_", defaulttoolkit, "__"];
+    functype = exist (funcname);
     if (! __is_function__ (funcname))
-      error ("uiputfile: fltk graphics toolkit required");
-    elseif (! strcmp (defaulttoolkit, "gnuplot"))
-      warning ("uiputfile: no implementation for toolkit '%s', using 'fltk' instead",
+      funcname = "__uiputfile_fltk__";
+      if (! __is_function__ (funcname))
+        error ("uiputfile: fltk graphics toolkit required");
+      elseif (! strcmp (defaulttoolkit, "gnuplot"))
+        warning ("uiputfile: no implementation for toolkit '%s', using 'fltk' instead",
                defaulttoolkit);
+      endif
     endif
   endif
 
@@ -79,7 +82,7 @@
                  "create",
                  pwd};           # Default directory
 
-  outargs = cell(6, 1);
+  outargs = cell (6, 1);
   for i = 1 : 6
     outargs{i} = defaultvals{i};
   endfor
@@ -116,13 +119,18 @@
     endif
   endif
 
-  [retfile, retpath, retindex] = feval (funcname, outargs{:});
+  if (__octave_link_enabled__ ())
+    [retfile, retpath, retindex] = __octave_link_file_dialog__ (outargs{:});
+  else
+    [retfile, retpath, retindex] = feval (funcname, outargs{:});
+  endif
 
 endfunction
 
+
 %!demo
-%! uiputfile({"*.gif;*.png;*.jpg", "Supported Picture Formats"})
+%! uiputfile ({'*.gif;*.png;*.jpg', 'Supported Picture Formats'});
 
 ## Remove from test statistics.  No real tests possible.
-%!test
-%! assert (1);
+%!assert (1)
+
--- a/scripts/plot/uiresume.m
+++ b/scripts/plot/uiresume.m
@@ -29,8 +29,8 @@
 
 function uiresume (h)
 
-  if (! ishandle (h) || ! strcmp (get (h, "type"), "figure"))
-    error ("uiresume: invalid figure handle");
+  if (! isfigure (h))
+    error ("uiresume: invalid figure handle H");
   endif
 
   try
--- a/scripts/plot/uitoggletool.m
+++ b/scripts/plot/uitoggletool.m
@@ -17,8 +17,8 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {@var{handle} =} uitoggletool ('Name', value, @dots{})
-## @deftypefnx {Function File} {@var{handle} =} uitoggletool (@var{parent}, 'Name', value, @dots{})
+## @deftypefn  {Function File} {@var{handle} =} uitoggletool ("Name", value, @dots{})
+## @deftypefnx {Function File} {@var{handle} =} uitoggletool (@var{parent}, "Name", value, @dots{})
 ## @end deftypefn
 
 ## Author: goffioul
--- a/scripts/plot/uitoolbar.m
+++ b/scripts/plot/uitoolbar.m
@@ -17,8 +17,8 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {@var{handle} =} uitoolbar ('Name', value, @dots{})
-## @deftypefnx {Function File} {@var{handle} =} uitoolbar (@var{parent}, 'Name', value, @dots{})
+## @deftypefn  {Function File} {@var{handle} =} uitoolbar ("Name", value, @dots{})
+## @deftypefnx {Function File} {@var{handle} =} uitoolbar (@var{parent}, "Name", value, @dots{})
 ## @end deftypefn
 
 ## Author: goffioul
--- a/scripts/plot/uiwait.m
+++ b/scripts/plot/uiwait.m
@@ -29,9 +29,9 @@
 ##
 ## When specified, @var{timeout} defines the number of seconds to wait
 ## for the figure deletion or the @code{uiresume} call.  The timeout value
-## must be at least 1. If a smaller value is specified, a warning is issued
+## must be at least 1.  If a smaller value is specified, a warning is issued
 ## and a timeout value of 1 is used instead.  If a non-integer value is
-## specified, it is truncated towards 0. If @var{timeout} is not specified,
+## specified, it is truncated towards 0.  If @var{timeout} is not specified,
 ## the program execution is suspended indefinitely.
 ## @seealso{uiresume, waitfor}
 ## @end deftypefn
@@ -47,8 +47,8 @@
     h = get (0, "currentfigure");
   else
     h = varargin{1};
-    if (! ishandle (h) || ! strcmp (get (h, "type"), "figure"))
-      error ("uiwait: invalid figure handle");
+    if (! isfigure (h))
+      error ("uiwait: invalid figure handle H");
     endif
     if (nargin > 1)
       timeout = varargin{2};
@@ -63,7 +63,7 @@
         if (! strcmp (get (h, "__uiwait_state__"), "none"))
           error ("uiwait: an active uiwait call for this figure already exists");
         endif
-	set (h, "__uiwait_state__", "active");
+        set (h, "__uiwait_state__", "active");
       end_try_catch
       waitfor_args = {h, "__uiwait_state__", "triggered"};
       if (! isempty (timeout))
--- a/scripts/plot/view.m
+++ b/scripts/plot/view.m
@@ -21,7 +21,8 @@
 ## @deftypefnx {Function File} {} view (@var{azimuth}, @var{elevation})
 ## @deftypefnx {Function File} {} view ([@var{azimuth} @var{elevation}])
 ## @deftypefnx {Function File} {} view ([@var{x} @var{y} @var{z}])
-## @deftypefnx {Function File} {} view (@var{dims})
+## @deftypefnx {Function File} {} view (2)
+## @deftypefnx {Function File} {} view (3)
 ## @deftypefnx {Function File} {} view (@var{ax}, @dots{})
 ## Query or set the viewpoint for the current axes.  The parameters
 ## @var{azimuth} and @var{elevation} can be given as two arguments or as
@@ -94,6 +95,7 @@
 
 endfunction
 
+
 %!test
 %! hf = figure ("visible", "off");
 %! unwind_protect
@@ -122,3 +124,4 @@
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
--- a/scripts/plot/waitbar.m
+++ b/scripts/plot/waitbar.m
@@ -26,7 +26,7 @@
 ## Return a handle @var{h} to a new waitbar object.  The waitbar is
 ## filled to fraction @var{frac} which must be in the range [0, 1].  The
 ## optional message @var{msg} is centered and displayed above the waitbar.
-## The appearance of the waitbar figure window can be configured by passing 
+## The appearance of the waitbar figure window can be configured by passing
 ## property/value pairs to the function.
 ## 
 ## When called with a single input the current waitbar, if it exists, is
@@ -136,46 +136,46 @@
 
 
 %!demo
-%! h = waitbar (0, "0.00%");
+%! h = waitbar (0, '0.00%');
 %! for i = 0:0.01:1
-%!   waitbar (i, h, sprintf ("%.2f%%", 100*i));
-%! endfor
+%!   waitbar (i, h, sprintf ('%.2f%%', 100*i));
+%! end
 %! close (h);
 
 %!demo
-%! h = waitbar (0, "please wait...");
+%! h = waitbar (0, 'please wait...');
 %! for i = 0:0.01:0.6
 %!   waitbar (i);
-%! endfor
+%! end
 %! i = 0.3;
-%! waitbar (i, h, "don't you hate taking a step backward?")
+%! waitbar (i, h, 'don''t you hate taking a step backward?');
 %! pause (0.5);
 %! for i = i:0.005:0.7
 %!   waitbar (i, h);
-%! endfor
-%! waitbar (i, h, "or stalling?")
+%! end
+%! waitbar (i, h, 'or stalling?');
 %! pause (1);
 %! for i = i:0.003:0.8
-%!   waitbar (i, h, "just a little longer now")
-%! endfor
+%!   waitbar (i, h, 'just a little longer now');
+%! end
 %! for i = i:0.001:1
-%!   waitbar (i, h, "please don't be impatient")
-%! endfor
+%!   waitbar (i, h, 'please don''t be impatient');
+%! end
 %! close (h);
 
 %!demo
-%! h1 = waitbar (0, "Waitbar #1");
-%! h2 = waitbar (0, "Waitbar #2");
-%! h2pos = get (h2, "position");
-%! h2pos(1) += h2pos(3) + 50;
-%! set (h2, "position", h2pos);
+%! h1 = waitbar (0, 'Waitbar #1');
+%! h2 = waitbar (0, 'Waitbar #2');
+%! h2pos = get (h2, 'position');
+%! h2pos(1) = h2pos(1) + (h2pos(3) + 50);
+%! set (h2, 'position', h2pos);
 %! pause (0.5);
 %! for i = 1:4
 %!   waitbar (i/4, h1);
 %!   pause (0.5);
 %!   waitbar (i/4, h2);
 %!   pause (0.5);
-%! endfor
+%! end
 %! pause (0.5);
 %! close (h1);
 %! close (h2);
new file mode 100644
--- /dev/null
+++ b/scripts/plot/waterfall.m
@@ -0,0 +1,61 @@
+## Copyright (C) 2013 Mike Miller
+##
+## 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} {} waterfall (@var{x}, @var{y}, @var{z})
+## @deftypefnx {Function File} {} waterfall (@var{z})
+## @deftypefnx {Function File} {@var{h} =} waterfall (@dots{})
+## Plot a waterfall plot given matrices @var{x}, and @var{y} from
+## @code{meshgrid} and a matrix @var{z} corresponding to the @var{x} and
+## @var{y} coordinates of the mesh.  If @var{x} and @var{y} are vectors,
+## then a typical vertex is (@var{x}(j), @var{y}(i), @var{z}(i,j)).  Thus,
+## columns of @var{z} correspond to different @var{x} values and rows of
+## @var{z} correspond to different @var{y} values.
+##
+## The optional return value @var{h} is a graphics handle to the created
+## surface object.
+## @seealso{meshgrid, meshz, surf}
+## @end deftypefn
+
+## Author: Mike Miller <mtmiller@ieee.org>
+
+function h = waterfall (varargin)
+
+  tmp = meshz (varargin{:});
+
+  set (tmp, "meshstyle", "row");
+
+  ## The gnuplot toolkit does nothing with the meshstyle property currently.
+  toolkit = get (ancestor (tmp, "figure"), "__graphics_toolkit__");
+  if (strcmp (toolkit, "gnuplot"))
+    warning ("waterfall: may not render correctly using toolkit '%s'", toolkit);
+  endif
+
+  if (nargout > 0)
+    h = tmp;
+  endif
+
+endfunction
+
+
+%!demo
+%! clf;
+%! colormap ('default');
+%! [~,~,Z] = peaks ();
+%! waterfall (Z);
+
--- a/scripts/plot/whitebg.m
+++ b/scripts/plot/whitebg.m
@@ -74,7 +74,7 @@
     if (isroot)
       fac = get (0, "factory");
       fields = fieldnames (fac);
-      fieldindex = intersect (find (!cellfun ("isempty", regexp(fields, 'color'))), union (find (!cellfun ("isempty", regexp(fields, 'factoryaxes.*'))), find (!cellfun ("isempty", regexp(fields, 'factoryfigure.*')))));
+      fieldindex = intersect (find (!cellfun ("isempty", regexp (fields, 'color'))), union (find (!cellfun ("isempty", regexp (fields, 'factoryaxes.*'))), find (!cellfun ("isempty", regexp (fields, 'factoryfigure.*')))));
 
       ## Check whether the factory value has been replaced
       for nf = 1 : numel (fieldindex);
@@ -95,21 +95,21 @@
     while (numel (handles))
       children = [];
       for n = 1 : numel (handles)
-        children = union (children, get(handles(n), "children"));
+        children = union (children, get (handles(n), "children"));
       endfor
       handles = children;
       h = union (h, children);
     endwhile
 
-    for nh = 1 : numel(h)
+    for nh = 1 : numel (h)
       p = get (h (nh));
       fields = fieldnames (p);
-      fieldindex = find (!cellfun ("isempty", regexp(fields, 'color')));
+      fieldindex = find (!cellfun ("isempty", regexp (fields, 'color')));
       if (numel (fieldindex))
         for nf = 1 : numel (fieldindex);
           field = fields {fieldindex (nf)};
           c = subsref (p, struct ("type", ".", "subs", field));
-          if (! ischar(c) && columns(c) == 3)
+          if (! ischar (c) && columns (c) == 3)
             set (h (nh), field, 1 - c);
           endif
         endfor
@@ -121,7 +121,7 @@
         def = get (h (nh), "default");
         fields = fieldnames (def);
         if (! isempty (fields))
-          fieldindex = find (!cellfun ("isempty", regexp(fields, 'color')));
+          fieldindex = find (!cellfun ("isempty", regexp (fields, 'color')));
           for nf = 1 : numel (fieldindex)
             defaultfield = fields {fieldindex (nf)};
             defaultvalue = 1 - subsref (def, struct ("type", ".", "subs", defaultfield));
@@ -144,6 +144,7 @@
   endif
 endfunction
 
+
 %!test
 %! dac = get (0, "defaultaxescolor");
 %! dfc = get (0, "defaultfigurecolor");
@@ -162,3 +163,4 @@
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
--- a/scripts/plot/xlim.m
+++ b/scripts/plot/xlim.m
@@ -23,7 +23,7 @@
 ##
 ## @deftypefn  {Function File} {@var{xl} =} xlim ()
 ## @deftypefnx {Function File} {} xlim (@var{xl})
-## @deftypefnx {Function File} {@var{m} =} xlim ('mode')
+## @deftypefnx {Function File} {@var{m} =} xlim ("mode")
 ## @deftypefnx {Function File} {} xlim (@var{m})
 ## @deftypefnx {Function File} {} xlim (@var{h}, @dots{})
 ## Get or set the limits of the x-axis of the current plot.  Called without
@@ -32,8 +32,8 @@
 ## to this value.
 ##
 ## The current mode for calculation of the x-axis can be returned with a
-## call @code{xlim ('mode')}, and can be either 'auto' or 'manual'.  The
-## current plotting mode can be set by passing either 'auto' or 'manual'
+## call @code{xlim ("mode")}, and can be either "auto" or "manual".  The
+## current plotting mode can be set by passing either "auto" or "manual"
 ## as the argument.
 ##
 ## If passed a handle as the first argument, then operate on this handle
@@ -49,34 +49,34 @@
   endif
 endfunction
 
+
 %!demo
-%! clf ();
+%! clf;
 %! line ();
 %! xlim ([0.2, 0.8]);
-%! title ("xlim is [0.2, 0.8]");
+%! title ('xlim is [0.2, 0.8]');
 %! assert (xlim (), [0.2, 0.8]);
 
 %!demo
-%! clf ();
+%! clf;
 %! line ();
 %! xlim ('auto');
-%! title ("xlim is auto");
-%! assert (xlim ("mode"), "auto");
+%! title ('xlim is auto');
+%! assert (xlim ('mode'), 'auto');
 
 %!demo
-%! clf ();
+%! clf;
 %! plot3 ([0,1], [0,1], [0,1]);
 %! xlim ([0.2, 0.8]);
-%! title ("xlim is [0.2, 0.8]");
+%! title ('xlim is [0.2, 0.8]');
 %! assert (xlim (), [0.2, 0.8]);
 
 %!demo
-%! clf ();
+%! clf;
 %! plot3 ([0,1], [0,1], [0,1]);
 %! xlim ('auto');
-%! title ("xlim is auto");
-%! assert (xlim ("mode"), "auto");
-
+%! title ('xlim is auto');
+%! assert (xlim ('mode'), 'auto');
 
 %!test
 %! hf = figure ("visible", "off");
@@ -98,3 +98,4 @@
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
--- a/scripts/plot/ylim.m
+++ b/scripts/plot/ylim.m
@@ -19,7 +19,7 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {@var{yl} =} ylim ()
 ## @deftypefnx {Function File} {} ylim (@var{yl})
-## @deftypefnx {Function File} {@var{m} =} ylim ('mode')
+## @deftypefnx {Function File} {@var{m} =} ylim ("mode")
 ## @deftypefnx {Function File} {} ylim (@var{m})
 ## @deftypefnx {Function File} {} ylim (@var{h}, @dots{})
 ## Get or set the limits of the y-axis of the current plot.  Called without
@@ -28,8 +28,8 @@
 ## to this value.
 ##
 ## The current mode for calculation of the y-axis can be returned with a
-## call @code{ylim ('mode')}, and can be either 'auto' or 'manual'.  The
-## current plotting mode can be set by passing either 'auto' or 'manual'
+## call @code{ylim ("mode")}, and can be either "auto" or "manual".  The
+## current plotting mode can be set by passing either "auto" or "manual"
 ## as the argument.
 ##
 ## If passed a handle as the first argument, then operate on this handle
@@ -45,33 +45,34 @@
   endif
 endfunction
 
+
 %!demo
-%! clf ();
+%! clf;
 %! line ();
 %! ylim ([0.2, 0.8]);
-%! title ("ylim is [0.2, 0.8]");
+%! title ('ylim is [0.2, 0.8]');
 %! assert (ylim (), [0.2, 0.8]);
 
 %!demo
-%! clf ();
+%! clf;
 %! line ();
 %! ylim ('auto');
-%! title ("ylim is auto");
-%! assert (ylim ("mode"), "auto");
+%! title ('ylim is auto');
+%! assert (ylim ('mode'), 'auto');
 
 %!demo
-%! clf ();
+%! clf;
 %! plot3 ([0,1], [0,1], [0,1]);
 %! ylim ([0.2, 0.8]);
-%! title ("ylim is [0.2, 0.8]");
+%! title ('ylim is [0.2, 0.8]');
 %! assert (ylim (), [0.2, 0.8]);
 
 %!demo
-%! clf ();
+%! clf;
 %! plot3 ([0,1], [0,1], [0,1]);
 %! ylim ('auto');
-%! title ("ylim is auto");
-%! assert (ylim ("mode"), "auto");
+%! title ('ylim is auto');
+%! assert (ylim ('mode'), 'auto');
 
 %!test
 %! hf = figure ("visible", "off");
@@ -94,3 +95,4 @@
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
--- a/scripts/plot/zlim.m
+++ b/scripts/plot/zlim.m
@@ -19,7 +19,7 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {@var{zl} =} zlim ()
 ## @deftypefnx {Function File} {} zlim (@var{zl})
-## @deftypefnx {Function File} {@var{m} =} zlim ('mode')
+## @deftypefnx {Function File} {@var{m} =} zlim ("mode")
 ## @deftypefnx {Function File} {} zlim (@var{m})
 ## @deftypefnx {Function File} {} zlim (@var{h}, @dots{})
 ## Get or set the limits of the z-axis of the current plot.  Called without
@@ -28,8 +28,8 @@
 ## to this value.
 ##
 ## The current mode for calculation of the z-axis can be returned with a
-## call @code{zlim ('mode')}, and can be either 'auto' or 'manual'.  The
-## current plotting mode can be set by passing either 'auto' or 'manual'
+## call @code{zlim ("mode")}, and can be either "auto" or "manual".  The
+## current plotting mode can be set by passing either "auto" or "manual"
 ## as the argument.
 ##
 ## If passed a handle as the first argument, then operate on this handle
@@ -45,33 +45,34 @@
   endif
 endfunction
 
+
 %!demo
-%! clf ();
+%! clf;
 %! line ();
 %! zlim ([0.2, 0.8]);
-%! title ("zlim is [0.2, 0.8]");
+%! title ('zlim is [0.2, 0.8]');
 %! assert (zlim (), [0.2, 0.8]);
 
 %!demo
-%! clf ();
+%! clf;
 %! line ();
 %! zlim ('auto');
-%! title ("zlim is auto");
-%! assert (zlim ("mode"), "auto");
+%! title ('zlim is auto');
+%! assert (zlim ('mode'), 'auto');
 
 %!demo
-%! clf ();
+%! clf;
 %! plot3 ([0,1], [0,1], [0,1]);
 %! zlim ([0.2, 0.8]);
-%! title ("zlim is [0.2, 0.8]");
+%! title ('zlim is [0.2, 0.8]');
 %! assert (zlim (), [0.2, 0.8]);
 
 %!demo
-%! clf ();
+%! clf;
 %! plot3 ([0,1], [0,1], [0,1]);
 %! zlim ('auto');
-%! title ("zlim is auto");
-%! assert (zlim ("mode"), "auto");
+%! title ('zlim is auto');
+%! assert (zlim ('mode'), 'auto');
 
 %!test
 %! hf = figure ("visible", "off");
@@ -94,3 +95,4 @@
 %! unwind_protect_cleanup
 %!   close (hf);
 %! end_unwind_protect
+
--- a/scripts/polynomial/compan.m
+++ b/scripts/polynomial/compan.m
@@ -79,15 +79,12 @@
 
 endfunction
 
-%!assert(all (all (compan ([1, 2, 3]) == [-2, -3; 1, 0])));
-
-%!assert(all (all (compan ([1; 2; 3]) == [-2, -3; 1, 0])));
-
-%!assert(isempty (compan (4)));
 
-%!assert(all (all (compan ([3, 2, 1]) == [-2/3, -1/3; 1, 0])));
+%!assert (compan ([1, 2, 3]), [-2, -3; 1, 0])
+%!assert (compan ([1; 2; 3]), [-2, -3; 1, 0])
+%!assert (isempty (compan (4)))
+%!assert (compan ([3, 2, 1]), [-2/3, -1/3; 1, 0])
 
-%!error compan ([1,2;3,4]);
+%!error compan ([1,2;3,4])
+%!error compan ([])
 
-%!error compan ([]);
-
--- a/scripts/polynomial/conv.m
+++ b/scripts/polynomial/conv.m
@@ -51,12 +51,12 @@
 
   if (! (isvector (a) && isvector (b)))
     error ("conv: both arguments A and B must be vectors");
-  elseif (nargin == 3 && ! any (strcmpi (shape, {"full", "same"})))
-    error ('conv: SHAPE argument must be "full" or "same"');
+  elseif (nargin == 3 && ! any (strcmpi (shape, {"full", "same", "valid"})))
+    error ('conv: SHAPE argument must be "full", "same", or "valid"');
   endif
 
-  la = length (a);
-  lb = length (b);
+  la = la_orig = length (a);
+  lb = lb_orig = length (b);
 
   ly = la + lb - 1;
 
@@ -79,63 +79,68 @@
 
   y = filter (a, 1, x);
 
-  if (strcmp (shape, "same"))
+  if (strcmpi (shape, "same"))
     idx = ceil ((ly - la) / 2);
     y = y(idx+1:idx+la);
+  elseif (strcmpi (shape, "valid"))
+    len = la_orig - lb_orig;
+    y = y(lb_orig:lb_orig+len);
   endif
 
 endfunction
 
 
 %!test
-%!  x = ones(3,1);
-%!  y = ones(1,3);
-%!  b = 2;
-%!  c = 3;
-%!  assert (conv (x, x), [1; 2; 3; 2; 1]);
-%!  assert (conv (y, y), [1, 2, 3, 2, 1]);
-%!  assert (conv (x, y), [1, 2, 3, 2, 1]);
-%!  assert (conv (y, x), [1; 2; 3; 2; 1]);
-%!  assert (conv (c, x), [3; 3; 3]);
-%!  assert (conv (c, y), [3, 3, 3]);
-%!  assert (conv (x, c), [3; 3; 3]);
-%!  assert (conv (y, c), [3, 3, 3]);
-%!  assert (conv (b, c), 6);
+%! x = ones (3,1);
+%! y = ones (1,3);
+%! b = 2;
+%! c = 3;
+%! assert (conv (x, x), [1; 2; 3; 2; 1]);
+%! assert (conv (y, y), [1, 2, 3, 2, 1]);
+%! assert (conv (x, y), [1, 2, 3, 2, 1]);
+%! assert (conv (y, x), [1; 2; 3; 2; 1]);
+%! assert (conv (c, x), [3; 3; 3]);
+%! assert (conv (c, y), [3, 3, 3]);
+%! assert (conv (x, c), [3; 3; 3]);
+%! assert (conv (y, c), [3, 3, 3]);
+%! assert (conv (b, c), 6);
 
+%!shared a,b
 %!test
-%!  a = 1:10;
-%!  b = 1:3;
-%!  assert (size (conv(a,b)), [1, numel(a)+numel(b)-1]);
-%!  assert (size (conv(b,a)), [1, numel(a)+numel(b)-1]);
+%! a = 1:10;
+%! b = 1:3;
+%!assert (size (conv (a,b)), [1, numel(a)+numel(b)-1])
+%!assert (size (conv (b,a)), [1, numel(a)+numel(b)-1])
 
 %!test
-%!  a = (1:10).';
-%!  b = 1:3;
-%!  assert (size (conv(a,b)), [numel(a)+numel(b)-1, 1]);
-%!  assert (size (conv(b,a)), [numel(a)+numel(b)-1, 1]);
+%! a = (1:10).';
+%!assert (size (conv (a,b)), [numel(a)+numel(b)-1, 1])
+%!assert (size (conv (b,a)), [numel(a)+numel(b)-1, 1])
+
+%!test
+%! a = 1:10;
+%! b = (1:3).';
+%!assert (size (conv (a,b)), [1, numel(a)+numel(b)-1])
+%!assert (size (conv (b,a)), [1, numel(a)+numel(b)-1])
 
 %!test
-%!  a = 1:10;
-%!  b = (1:3).';
-%!  assert (size (conv(a,b)), [1, numel(a)+numel(b)-1]);
-%!  assert (size (conv(b,a)), [1, numel(a)+numel(b)-1]);
+%! a = 1:10;
+%! b = 1:3;
+
+%!assert (conv (a,b,"full"), conv (a,b))
+%!assert (conv (b,a,"full"), conv (b,a))
 
-%!test
-%!  a = 1:10;
-%!  b = 1:3;
-%!  assert (conv (a,b,"full"), conv (a,b));
-%!  assert (conv (b,a,"full"), conv (b,a));
+%!assert (conv (a,b,"same"), [4, 10, 16, 22, 28, 34, 40, 46, 52, 47])
+%!assert (conv (b,a,"same"), [28, 34, 40])
 
-%!test
-%!  a = 1:10;
-%!  b = 1:3;
-%!  assert (conv (a,b,"same"), [4, 10, 16, 22, 28, 34, 40, 46, 52, 47]);
-%!  assert (conv (b,a,"same"), [28, 34, 40]);
+%!assert (conv (a,b,"valid"), [10, 16, 22, 28, 34, 40, 46, 52])
+%!assert (conv (b,a,"valid"), zeros (1,0))
+
 
 %% Test input validation
 %!error conv (1)
 %!error conv (1,2,3,4)
-%!error conv ([1, 2; 3, 4], 3)
-%!error conv (3, [1, 2; 3, 4])
-%!error conv (2, 3, "XXXX")
+%!error <A and B must be vectors> conv ([1, 2; 3, 4], 3)
+%!error <A and B must be vectors> conv (3, [1, 2; 3, 4])
+%!error <SHAPE argument must be> conv (2, 3, "INVALID_SHAPE")
 
--- a/scripts/polynomial/deconv.m
+++ b/scripts/polynomial/deconv.m
@@ -40,7 +40,7 @@
   endif
 
   if (! (isvector (y) && isvector (a)))
-    error("deconv: both arguments must be vectors");
+    error ("deconv: both arguments must be vectors");
   endif
 
   la = length (a);
@@ -68,7 +68,7 @@
     r = y - conv (a, b);
   else
     ## Respect the orientation of Y"
-    if (size (y, 1) <= size (y, 2))
+    if (rows (y) <= columns (y))
       r = [(zeros (1, lc - ly)), y] - conv (a, b);
     else
       r = [(zeros (lc - ly, 1)); y] - conv (a, b);
@@ -81,30 +81,34 @@
 
 endfunction
 
+
 %!test
 %! [b, r] = deconv ([3, 6, 9, 9], [1, 2, 3]);
-%! assert(all (all (b == [3, 0])) && all (all (r == [0, 0, 0, 9])));
+%! assert (b, [3, 0]);
+%! assert (r, [0, 0, 0, 9]);
 
 %!test
 %! [b, r] = deconv ([3, 6], [1, 2, 3]);
-%! assert(b == 0 && all (all (r == [3, 6])));
+%! assert (b, 0);
+%! assert (r, [3, 6]);
 
 %!test
 %! [b, r] = deconv ([3, 6], [1; 2; 3]);
-%! assert(b == 0 && all (all (r == [3, 6])));
+%! assert (b, 0);
+%! assert (r, [3, 6]);
 
 %!test
 %! [b,r] = deconv ([3; 6], [1; 2; 3]);
-%! assert (b == 0 && all (all (r == [3; 6])))
+%! assert (b, 0);
+%! assert (r, [3; 6]);
 
 %!test
 %! [b, r] = deconv ([3; 6], [1, 2, 3]);
-%! assert (b == 0 && all (all (r == [3; 6])))
-
-%!test
-%! assert (deconv ((1:3)',[1, 1]), [1; 1])
+%! assert (b, 0);
+%! assert (r, [3; 6]);
 
-%!error [b, r] = deconv ([3, 6], [1, 2; 3, 4]);
+%!assert (deconv ((1:3)',[1, 1]), [1; 1])
 
-%!error [b, r] = deconv ([3, 6; 1, 2], [1, 2, 3]);
+%!error [b, r] = deconv ([3, 6], [1, 2; 3, 4])
+%!error [b, r] = deconv ([3, 6; 1, 2], [1, 2, 3])
 
--- a/scripts/polynomial/mkpp.m
+++ b/scripts/polynomial/mkpp.m
@@ -79,34 +79,36 @@
 
 endfunction
 
+
 %!demo # linear interpolation
-%! x=linspace(0,pi,5)';
-%! t=[sin(x),cos(x)];
-%! m=diff(t)./(x(2)-x(1));
-%! b=t(1:4,:);
-%! pp = mkpp(x, [m(:),b(:)]);
-%! xi=linspace(0,pi,50);
-%! plot(x,t,"x",xi,ppval(pp,xi));
-%! legend("control","interp");
+%! x = linspace (0,pi,5)';
+%! t = [sin(x), cos(x)];
+%! m = diff (t) ./ (x(2)-x(1));
+%! b = t(1:4,:);
+%! pp = mkpp (x, [m(:),b(:)]);
+%! xi = linspace (0,pi,50);
+%! plot (x,t,"x", xi,ppval (pp,xi));
+%! legend ("control", "interp");
 
 %!shared b,c,pp
-%! b = 1:3; c = 1:24; pp=mkpp(b,c);
-%!assert (pp.pieces,2);
-%!assert (pp.order,12);
-%!assert (pp.dim,1);
-%!assert (size(pp.coefs),[2,12]);
-%! pp=mkpp(b,c,2);
-%!assert (pp.pieces,2);
-%!assert (pp.order,6);
-%!assert (pp.dim,2);
-%!assert (size(pp.coefs),[4,6]);
-%! pp=mkpp(b,c,3);
-%!assert (pp.pieces,2);
-%!assert (pp.order,4);
-%!assert (pp.dim,3);
-%!assert (size(pp.coefs),[6,4]);
-%! pp=mkpp(b,c,[2,3]);
-%!assert (pp.pieces,2);
-%!assert (pp.order,2);
-%!assert (pp.dim,[2,3]);
-%!assert (size(pp.coefs),[12,2]);
+%! b = 1:3; c = 1:24; pp = mkpp (b,c);
+%!assert (pp.pieces, 2)
+%!assert (pp.order, 12)
+%!assert (pp.dim, 1)
+%!assert (size (pp.coefs), [2,12])
+%! pp = mkpp (b,c,2);
+%!assert (pp.pieces, 2)
+%!assert (pp.order, 6)
+%!assert (pp.dim, 2)
+%!assert (size (pp.coefs), [4,6])
+%! pp = mkpp (b,c,3);
+%!assert (pp.pieces, 2)
+%!assert (pp.order, 4)
+%!assert (pp.dim, 3)
+%!assert (size (pp.coefs), [6,4])
+%! pp = mkpp (b,c,[2,3]);
+%!assert (pp.pieces, 2)
+%!assert (pp.order, 2)
+%!assert (pp.dim, [2,3])
+%!assert (size (pp.coefs), [12,2])
+
--- a/scripts/polynomial/module.mk
+++ b/scripts/polynomial/module.mk
@@ -1,5 +1,8 @@
 FCN_FILE_DIRS += polynomial
 
+polynomial_PRIVATE_FCN_FILES = \
+  polynomial/private/__splinefit__.m
+
 polynomial_FCN_FILES = \
   polynomial/compan.m \
   polynomial/conv.m \
@@ -10,6 +13,7 @@
   polynomial/poly.m \
   polynomial/polyaffine.m \
   polynomial/polyder.m \
+  polynomial/polyeig.m \
   polynomial/polyfit.m \
   polynomial/polygcd.m \
   polynomial/polyint.m \
@@ -24,7 +28,9 @@
   polynomial/residue.m \
   polynomial/roots.m \
   polynomial/spline.m \
-  polynomial/unmkpp.m
+  polynomial/splinefit.m \
+  polynomial/unmkpp.m \
+  $(polynomial_PRIVATE_FCN_FILES)
 
 FCN_FILES += $(polynomial_FCN_FILES)
 
--- a/scripts/polynomial/mpoles.m
+++ b/scripts/polynomial/mpoles.m
@@ -116,7 +116,8 @@
 
 endfunction
 
+
 %!test
 %! [mp, n] = mpoles ([0 0], 0.01);
-%! assert (mp, [1; 2])
+%! assert (mp, [1; 2]);
 
--- a/scripts/polynomial/pchip.m
+++ b/scripts/polynomial/pchip.m
@@ -79,13 +79,13 @@
   if (isvector (y))
     y = y(:).'; ##row vector
     szy = size (y);
-    if !(size_equal (x, y))
-      error ("pchip: length of X and Y must match")
+    if (! size_equal (x, y))
+      error ("pchip: length of X and Y must match");
     endif
   else
     szy = size (y);
     if (n != szy(end))
-      error ("pchip: length of X and last dimension of Y must match")
+      error ("pchip: length of X and last dimension of Y must match");
     endif
     y = reshape (y, [prod(szy(1:end-1)), szy(end)]);
   endif
@@ -96,7 +96,7 @@
     h = diff (x);
     y = fliplr (y);
   elseif (any (h <= 0))
-    error("pchip: X must be strictly monotonic");
+    error ("pchip: X must be strictly monotonic");
   endif
 
   f1 = y(:, 1:n-1);
@@ -129,44 +129,44 @@
 %! x = 0:8;
 %! y = [1, 1, 1, 1, 0.5, 0, 0, 0, 0];
 %! xi = 0:0.01:8;
-%! yspline = spline(x,y,xi);
-%! ypchip = pchip(x,y,xi);
-%! title("pchip and spline fit to discontinuous function");
-%! plot(xi,yspline,xi,ypchip,"-",x,y,"+");
-%! legend ("spline","pchip","data");
+%! yspline = spline (x,y,xi);
+%! ypchip = pchip (x,y,xi);
+%! title ("pchip and spline fit to discontinuous function");
+%! plot (xi,yspline, xi,ypchip,"-", x,y,"+");
+%! legend ("spline", "pchip", "data");
 %! %-------------------------------------------------------------------
 %! % confirm that pchip agreed better to discontinuous data than spline
 
-%!shared x,y,y2,pp,yi1,yi2,yi3
+%!shared x, y, y2, pp, yi1, yi2, yi3
 %! x = 0:8;
 %! y = [1, 1, 1, 1, 0.5, 0, 0, 0, 0];
-%!assert (pchip(x,y,x), y);
-%!assert (pchip(x,y,x'), y');
-%!assert (pchip(x',y',x'), y');
-%!assert (pchip(x',y',x), y);
-%!assert (isempty(pchip(x',y',[])));
-%!assert (isempty(pchip(x,y,[])));
-%!assert (pchip(x,[y;y],x), [pchip(x,y,x);pchip(x,y,x)])
-%!assert (pchip(x,[y;y],x'), [pchip(x,y,x);pchip(x,y,x)])
-%!assert (pchip(x',[y;y],x), [pchip(x,y,x);pchip(x,y,x)])
-%!assert (pchip(x',[y;y],x'), [pchip(x,y,x);pchip(x,y,x)])
+%!assert (pchip (x,y,x), y)
+%!assert (pchip (x,y,x'), y')
+%!assert (pchip (x',y',x'), y')
+%!assert (pchip (x',y',x), y)
+%!assert (isempty (pchip (x',y',[])))
+%!assert (isempty (pchip (x,y,[])))
+%!assert (pchip (x,[y;y],x), [pchip(x,y,x);pchip(x,y,x)])
+%!assert (pchip (x,[y;y],x'), [pchip(x,y,x);pchip(x,y,x)])
+%!assert (pchip (x',[y;y],x), [pchip(x,y,x);pchip(x,y,x)])
+%!assert (pchip (x',[y;y],x'), [pchip(x,y,x);pchip(x,y,x)])
 %!test
-%! x=(0:8)*pi/4;y=[sin(x);cos(x)];
-%! y2(:,:,1)=y;y2(:,:,2)=y+1;y2(:,:,3)=y-1;
-%! pp=pchip(x,shiftdim(y2,2));
-%! yi1=ppval(pp,(1:4)*pi/4);
-%! yi2=ppval(pp,repmat((1:4)*pi/4,[5,1]));
-%! yi3=ppval(pp,[pi/2,pi]);
-%!assert(size(pp.coefs),[48,4]);
-%!assert(pp.pieces,8);
-%!assert(pp.order,4);
-%!assert(pp.dim,[3,2]);
-%!assert(ppval(pp,pi),[0,-1;1,0;-1,-2],1e-14);
-%!assert(yi3(:,:,2),ppval(pp,pi),1e-14);
-%!assert(yi3(:,:,1),[1,0;2,1;0,-1],1e-14);
-%!assert(squeeze(yi1(1,2,:)),[1/sqrt(2); 0; -1/sqrt(2);-1],1e-14);
-%!assert(size(yi2),[3,2,5,4]);
-%!assert(squeeze(yi2(1,2,3,:)),[1/sqrt(2); 0; -1/sqrt(2);-1],1e-14);
+%! x = (0:8)*pi/4; y = [sin(x); cos(x)];
+%! y2(:,:,1) = y; y2(:,:,2) = y+1; y2(:,:,3) = y-1;
+%! pp = pchip (x, shiftdim (y2,2));
+%! yi1 = ppval (pp, (1:4)*pi/4);
+%! yi2 = ppval (pp, repmat ((1:4)*pi/4, [5,1]));
+%! yi3 = ppval (pp, [pi/2,pi]);
+%!assert (size (pp.coefs), [48,4])
+%!assert (pp.pieces, 8)
+%!assert (pp.order, 4)
+%!assert (pp.dim, [3,2])
+%!assert (ppval (pp,pi), [0,-1;1,0;-1,-2], 1e-14)
+%!assert (yi3(:,:,2), ppval (pp,pi), 1e-14)
+%!assert (yi3(:,:,1), [1,0;2,1;0,-1], 1e-14)
+%!assert (squeeze (yi1(1,2,:)), [1/sqrt(2); 0; -1/sqrt(2);-1], 1e-14)
+%!assert (size (yi2), [3,2,5,4])
+%!assert (squeeze (yi2(1,2,3,:)), [1/sqrt(2); 0; -1/sqrt(2);-1], 1e-14)
 
 %!error (pchip (1,2));
 %!error (pchip (1,2,3));
--- a/scripts/polynomial/poly.m
+++ b/scripts/polynomial/poly.m
@@ -81,11 +81,10 @@
 
 endfunction
 
-%!assert(all (all (poly ([1, 2, 3]) == [1, -6, 11, -6])));
-
-%!assert(all (all (abs (poly ([1, 2; 3, 4]) - [1, -5, -2]) < sqrt (eps))));
 
-%!error poly ([1, 2, 3; 4, 5, 6]);
+%!assert (poly ([]), 1)
+%!assert (poly ([1, 2, 3]), [1, -6, 11, -6])
+%!assert (poly ([1, 2; 3, 4]), [1, -5, -2], sqrt (eps))
 
-%!assert(poly ([]),1);
+%!error poly ([1, 2, 3; 4, 5, 6])
 
--- a/scripts/polynomial/polyaffine.m
+++ b/scripts/polynomial/polyaffine.m
@@ -30,7 +30,6 @@
 ## @seealso{polyval, polyfit}
 ## @end deftypefn
 
-
 function g = polyaffine (f, mu)
 
    if (nargin != 2)
@@ -73,16 +72,16 @@
 %!demo
 %! f = [1/5 4/5 -7/5 -2];
 %! g = polyaffine (f, [1, 1.2]);
-%! x = linspace (-4, 4, 100);
-%! plot(x, polyval (f, x), x, polyval (g, x));
+%! x = linspace (-4,4,100);
+%! plot (x,polyval (f, x), x,polyval (g, x));
 %! legend ("original", "affine");
 %! axis ([-4 4 -3 5]);
-%! grid ("on");
+%! grid on;
 
 %!test
 %! f = [1/5 4/5 -7/5 -2];
 %! mu = [1, 1.2];
 %! g = polyaffine (f, mu);
-%! x = linspace (-4, 4, 100);
+%! x = linspace (-4,4,100);
 %! assert (polyval (f, x, [], mu), polyval (g, x), 1e-10);
 
--- a/scripts/polynomial/polyder.m
+++ b/scripts/polynomial/polyder.m
@@ -60,7 +60,7 @@
 
         ## remove common factors from numerator and denominator
         x = polygcd (q, d);
-        if (length(x) != 1)
+        if (length (x) != 1)
           q = deconv (q, x);
           d = deconv (d, x);
         endif
@@ -91,9 +91,10 @@
 endfunction
 
 
-%!assert(all (all (polyder ([1, 2, 3]) == [2, 2])));
-%!assert(polyder (13) == 0);
+%!assert (polyder ([1, 2, 3], [2, 2]))
+%!assert (polyder (13), 0)
 
-%!error polyder ([]);
-%!error polyder ([1, 2; 3, 4]);
+%!error polyder ([])
+%!error polyder (1,2,3)
+%!error <argument must be a vector> polyder ([1, 2; 3, 4])
 
new file mode 100644
--- /dev/null
+++ b/scripts/polynomial/polyeig.m
@@ -0,0 +1,91 @@
+## Copyright (C) 2012 Fotios Kasolis
+##
+## 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{z} =} polyeig (@var{C0}, @var{C1}, @dots{}, @var{Cl})
+## @deftypefnx {Function File} {[@var{v}, @var{z}] =} polyeig (@var{C0}, @var{C1}, @dots{}, @var{Cl})
+##
+## Solve the polynomial eigenvalue problem of degree @var{l}.
+##
+## Given an @var{n*n} matrix polynomial
+## @code{@var{C}(s) = @var{C0} + @var{C1} s + @dots{} + @var{Cl} s^l}
+## polyeig solves the eigenvalue problem
+## @code{(@var{C0} + @var{C1} + @dots{} + @var{Cl})v = 0}.
+## Note that the eigenvalues @var{z} are the zeros of the matrix polynomial.
+## @var{z} is an @var{lxn} vector and @var{v} is an (@var{n} x @var{n})l matrix
+## with columns that correspond to the eigenvectors.
+##
+## @seealso{eig, eigs, compan}
+## @end deftypefn
+
+## Author: Fotios Kasolis
+
+function [ z, varargout ] = polyeig (varargin)
+  
+  if ( nargout > 2 )
+    print_usage ();
+  endif
+
+  nin = numel (varargin);
+
+  n = zeros (1, nin);
+
+  for cnt = 1 : nin
+    if ! ( issquare (varargin{cnt}) )
+       error ("polyeig: coefficients must be square matrices");
+    endif
+    n(cnt) = size (varargin{cnt}, 1);
+  endfor
+
+  if numel (unique (n)) > 1
+       error ("polyeig: coefficients must have the same dimensions");
+  endif
+  n = unique (n);
+
+  ## matrix polynomial degree
+  l = nin - 1;
+
+  ## form needed matrices
+  C = [ zeros(n * (l - 1), n), eye(n * (l - 1));
+       -cell2mat(varargin(1 : end - 1)) ];
+
+  D = [ eye(n * (l - 1)), zeros(n * (l - 1), n);
+       zeros(n, n * (l - 1)), varargin{end} ];
+
+  ## solve generalized eigenvalue problem
+  if ( isequal (nargout, 1) )
+    z = eig (C, D);
+  else
+    [ z, v ] = eig (C, D);
+    varargout{1} = v;
+    ## return n-element eigenvectors normalized so
+    ## that the infinity-norm = 1
+    z = z(1:n,:);
+    ## max() takes the abs if complex:
+    t = max (z);
+    z /= diag (t);
+  endif
+
+endfunction
+
+%!test
+%! C0 = [8, 0; 0, 4]; C1 = [1, 0; 0, 1];
+%! [v,z] = polyeig (C0, C1);
+%! assert (isequal (z(1), -8), true);
+%! d = C0*v + C1*v*z;
+%! assert (isequal (norm(d), 0.0), true);
--- a/scripts/polynomial/polyfit.m
+++ b/scripts/polynomial/polyfit.m
@@ -22,7 +22,9 @@
 ## @deftypefnx {Function File} {[@var{p}, @var{s}, @var{mu}] =} polyfit (@var{x}, @var{y}, @var{n})
 ## Return the coefficients of a polynomial @var{p}(@var{x}) of degree
 ## @var{n} that minimizes the least-squares-error of the fit to the points
-## @code{[@var{x}, @var{y}]}.
+## @code{[@var{x}, @var{y}]}.  If @var{n} is a logical vector, it is used
+## as a mask to selectively force the corresponding polynomial
+## coefficients to be used or ignored.
 ##
 ## The polynomial coefficients are returned in a row vector.
 ##
@@ -35,6 +37,11 @@
 ## @item X
 ## The Vandermonde matrix used to compute the polynomial coefficients.
 ##
+## @item C
+## The unscaled covariance matrix, formally equal to the inverse of
+## @var{x'}*@var{x}, but computed in a way minimizing roundoff error
+## propagation.
+## 
 ## @item df
 ## The degrees of freedom.
 ##
@@ -46,7 +53,9 @@
 ## @end table
 ##
 ## The second output may be used by @code{polyval} to calculate the
-## statistical error limits of the predicted values.
+## statistical error limits of the predicted values.  In particular, the
+## standard deviation of @var{p} coefficients is given by @*
+## @code{sqrt (diag (s.C)/s.df)*s.normr}.
 ##
 ## When the third output, @var{mu}, is present the
 ## coefficients, @var{p}, are associated with a polynomial in
@@ -60,6 +69,8 @@
 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
 ## Created: 13 December 1994
 ## Adapted-By: jwe
+## Modified on 20120204 by P. Dupuis; added the ability to specify a
+## polynomial mask instead of a polynomial degree.
 
 function [p, s, mu] = polyfit (x, y, n)
 
@@ -77,8 +88,16 @@
     error ("polyfit: X and Y must be vectors of the same size");
   endif
 
-  if (! (isscalar (n) && n >= 0 && ! isinf (n) && n == fix (n)))
-    error ("polyfit: N must be a non-negative integer");
+  if (islogical (n))
+    polymask = n;
+    ## n is the polynomial degree as given the polymask size; m is the
+    ## effective number of used coefficients.
+    n = length (polymask) - 1; m = sum (polymask) - 1;
+  else
+    if (! (isscalar (n) && n >= 0 && ! isinf (n) && n == fix (n)))
+      error ("polyfit: N must be a non-negative integer");
+    endif
+    polymask = logical (ones (1, n+1)); m = n;
   endif
 
   y_is_row_vector = (rows (y) == 1);
@@ -92,10 +111,15 @@
   v = vander (x, n+1);
 
   ## Solve by QR decomposition.
-  [q, r, k] = qr (v, 0);
+  [q, r, k] = qr (v(:, polymask), 0);
   p = r \ (q' * y);
   p(k) = p;
-
+  
+  if (n ~= m)
+    q = p; p = zeros (n+1, 1); 
+    p(polymask) = q;
+  endif
+  
   if (nargout > 1)
     yf = v*p;
 
@@ -104,10 +128,28 @@
     else
       s.yf = yf;
     endif
+    s.X = v; 
 
-    s.R = r;
-    s.X = v;
-    s.df = l - n - 1;
+    ## r.'*r is positive definite if X(:, polymask) is of full rank.
+    ## Invert it by cholinv to avoid taking the square root of squared
+    ## quantities. If cholinv fails, then X(:, polymask) is rank
+    ## deficient and not invertible.
+    try
+      C = cholinv (r.'*r)(k, k);
+    catch
+      C = NaN * ones (m+1, m+1);
+    end_try_catch
+
+    if (n ~= m)
+      ## fill matrices if required
+      s.X(:, ~polymask) = 0;
+      s.R = zeros (n+1, n+1); s.R(polymask, polymask) = r;
+      s.C = zeros (n+1, n+1); s.C(polymask, polymask) = C;
+    else
+      s.R = r; 
+      s.C = C;
+    endif
+    s.df = l - m - 1;
     s.normr = norm (yf - y);
   endif
 
@@ -116,23 +158,13 @@
 
 endfunction
 
-%!test
-%! x = [-2, -1, 0, 1, 2];
-%! assert(all (all (abs (polyfit (x, x.^2+x+1, 2) - [1, 1, 1]) < sqrt (eps))));
 
-%!error(polyfit ([1, 2; 3, 4], [1, 2, 3, 4], 2))
-
-%!test
+%!shared x
 %! x = [-2, -1, 0, 1, 2];
-%! assert(all (all (abs (polyfit (x, x.^2+x+1, 3) - [0, 1, 1, 1]) < sqrt (eps))));
-
-%!test
-%! x = [-2, -1, 0, 1, 2];
-%! fail("polyfit (x, x.^2+x+1)");
-
-%!test
-%! x = [-2, -1, 0, 1, 2];
-%! fail("polyfit (x, x.^2+x+1, [])");
+%!assert (polyfit (x, x.^2+x+1, 2), [1, 1, 1], sqrt (eps))
+%!assert (polyfit (x, x.^2+x+1, 3), [0, 1, 1, 1], sqrt (eps))
+%!fail ("polyfit (x, x.^2+x+1)")
+%!fail ("polyfit (x, x.^2+x+1, [])")
 
 ## Test difficult case where scaling is really needed. This example
 ## demonstrates the rather poor result which occurs when the dependent
@@ -146,32 +178,33 @@
 %!       315600.7143, 315602.9508, 315605.1765 ];
 %! [p1, s1] = polyfit (x, y, 10);
 %! [p2, s2, mu] = polyfit (x, y, 10);
-%! assert (s2.normr < s1.normr)
+%! assert (s2.normr < s1.normr);
 
 %!test
 %! x = 1:4;
 %! p0 = [1i, 0, 2i, 4];
 %! y0 = polyval (p0, x);
-%! p = polyfit (x, y0, numel(p0)-1);
-%! assert (p, p0, 1000*eps)
+%! p = polyfit (x, y0, numel (p0) - 1);
+%! assert (p, p0, 1000*eps);
 
 %!test
 %! x = 1000 + (-5:5);
 %! xn = (x - mean (x)) / std (x);
 %! pn = ones (1,5);
 %! y = polyval (pn, xn);
-%! [p, s, mu] = polyfit (x, y, numel(pn)-1);
-%! [p2, s2] = polyfit (x, y, numel(pn)-1);
-%! assert (p, pn, s.normr)
-%! assert (s.yf, y, s.normr)
-%! assert (mu, [mean(x), std(x)])
-%! assert (s.normr/s2.normr < sqrt(eps))
+%! [p, s, mu] = polyfit (x, y, numel (pn) - 1);
+%! [p2, s2] = polyfit (x, y, numel (pn) - 1);
+%! assert (p, pn, s.normr);
+%! assert (s.yf, y, s.normr);
+%! assert (mu, [mean(x), std(x)]);
+%! assert (s.normr/s2.normr < sqrt (eps));
 
 %!test
 %! x = [1, 2, 3; 4, 5, 6];
 %! y = [0, 0, 1; 1, 0, 0];
 %! p = polyfit (x, y, 5);
-%! expected = [0, 1, -14, 65, -112, 60]/12;
-%! assert (p, expected, sqrt(eps))
+%! expected = [0, 1, -14, 65, -112, 60] / 12;
+%! assert (p, expected, sqrt (eps));
 
+%!error <vectors of the same size> polyfit ([1, 2; 3, 4], [1, 2, 3, 4], 2)
 
--- a/scripts/polynomial/polygcd.m
+++ b/scripts/polynomial/polygcd.m
@@ -23,7 +23,7 @@
 ## Find the greatest common divisor of two polynomials.  This is equivalent
 ## to the polynomial found by multiplying together all the common roots.
 ## Together with deconv, you can reduce a ratio of two polynomials.
-## The tolerance @var{tol} defaults to @code{sqrt(eps)}.
+## The tolerance @var{tol} defaults to @code{sqrt (eps)}.
 ##
 ## @strong{Caution:} This is a numerically unstable algorithm and should not
 ## be used on large polynomials.
@@ -34,7 +34,7 @@
 ## @group
 ## polygcd (poly (1:8), poly (3:12)) - poly (3:8)
 ## @result{} [ 0, 0, 0, 0, 0, 0, 0 ]
-## deconv (poly (1:8), polygcd (poly (1:8), poly (3:12))) - poly(1:2)
+## deconv (poly (1:8), polygcd (poly (1:8), poly (3:12))) - poly (1:2)
 ## @result{} [ 0, 0, 0 ]
 ## @end group
 ## @end example
@@ -82,21 +82,19 @@
 
 
 %!test
-%! poly1 = [1 6 11 6]; % (x+1)(x+2)(x+3)
-%! poly2 = [1 3 2]; % (x+1)(x+2)
+%! poly1 = [1 6 11 6]; # (x+1)(x+2)(x+3);
+%! poly2 = [1 3 2];    # (x+1)(x+2);
 %! poly3 = polygcd (poly1, poly2);
-%! assert (poly3, poly2, sqrt (eps))
+%! assert (poly3, poly2, sqrt (eps));
 
-%!test
-%! assert (polygcd (poly(1:8), poly(3:12)), poly(3:8), sqrt (eps))
-
-%!test
-%! assert (deconv (poly(1:8), polygcd (poly(1:8), poly(3:12))), poly(1:2), sqrt (eps))
+%!assert (polygcd (poly (1:8), poly (3:12)), poly (3:8), sqrt (eps))
+%!assert (deconv (poly (1:8), polygcd (poly (1:8), poly (3:12))), poly (1:2), sqrt (eps))
 
 %!test
 %! for ii=1:10
 %!   p  = (unique (randn (10, 1)) * 10).';
 %!   p1 = p(3:end);
 %!   p2 = p(1:end-2);
-%!   assert (polygcd (poly (-p1), poly (-p2)), poly (- intersect (p1, p2)), sqrt (eps))
+%!   assert (polygcd (poly (-p1), poly (-p2)), poly (- intersect (p1, p2)), sqrt (eps));
 %! endfor
+
--- a/scripts/polynomial/polyint.m
+++ b/scripts/polynomial/polyint.m
@@ -61,17 +61,19 @@
 
 endfunction
 
+
 %!test
 %! A = [3, 2, 1];
-%! assert (polyint(A),polyint(A,0));
-%! assert (polyint(A),polyint(A'));
-%! assert (polyint(A),[1, 1, 1, 0]);
-%! assert (polyint(A,1),ones(1,4));
+%! assert (polyint (A), polyint (A,0));
+%! assert (polyint (A), polyint (A'));
+%! assert (polyint (A), [1, 1, 1, 0]);
+%! assert (polyint (A,1), ones (1,4));
 
 %!test
-%! A = ones(1,8);
+%! A = ones (1,8);
 %! B = [length(A):-1:1];
-%! assert (polyint(A),[1./B, 0]);
+%! assert (polyint (A), [1./B, 0]);
 
-%!error polyint()
-%!error polyint(ones(2,2))
+%!error polyint ()
+%!error polyint (ones (2,2))
+
--- a/scripts/polynomial/polyout.m
+++ b/scripts/polynomial/polyout.m
@@ -76,7 +76,7 @@
     tmp = " ";
   endif
 
-  if(nargout == 0)
+  if (nargout == 0)
     disp (tmp);
   else
     y = tmp;
@@ -96,8 +96,11 @@
   endif
 endfunction
 
-%!assert (polyout ([3 2 1]), '3*s^2 + 2*s^1 + 1')
-%!assert (polyout ([3 2 1], 'x'), '3*x^2 + 2*x^1 + 1')
-%!assert (polyout ([3 2 1], 'wxyz'), '3*wxyz^2 + 2*wxyz^1 + 1')
-%!assert (polyout ([5 4 3 2 1], '1'),'5*1^4 + 4*1^3 + 3*1^2 + 2*1^1 + 1')
+
+%!assert (polyout ([3 2 1]), "3*s^2 + 2*s^1 + 1")
+%!assert (polyout ([3 2 1], "x"), "3*x^2 + 2*x^1 + 1")
+%!assert (polyout ([3 2 1], "wxyz"), "3*wxyz^2 + 2*wxyz^1 + 1")
+%!assert (polyout ([5 4 3 2 1], "1"),"5*1^4 + 4*1^3 + 3*1^2 + 2*1^1 + 1")
+
 %!error polyout ([])
+
--- a/scripts/polynomial/polyreduce.m
+++ b/scripts/polynomial/polyreduce.m
@@ -31,35 +31,28 @@
 
   if (nargin != 1)
     print_usage ();
-  endif
-
-  if (!isvector (c) || isempty (c))
+  elseif (! isvector (c) || isempty (c))
     error ("polyreduce: C must be a non-empty vector");
   endif
 
-  if (! isempty (c))
-
-    index = find (c != 0);
-
-    if (isempty (index))
+  idx = find (c != 0, 1);
 
-      p = 0;
-
-    else
-
-      p = c(index (1):length (c));
-
-    endif
-
+  if (isempty (idx))
+    p = 0;
+  else
+    p = c(idx:end);
   endif
 
 endfunction
 
-%!assert(all (all (polyreduce ([0, 0, 1, 2, 3]) == [1, 2, 3])));
 
-%!assert(all (all (polyreduce ([1, 2, 3, 0, 0]) == [1, 2, 3, 0, 0])));
+%!assert (polyreduce ([0, 0, 1, 2, 3]), [1, 2, 3])
+%!assert (polyreduce ([1, 2, 3, 0, 0]), [1, 2, 3, 0, 0])
+%!assert (polyreduce ([1, 0, 3]), [1, 0, 3])
+%!assert (polyreduce ([0, 0, 0]), 0)
 
-%!assert(all (all (polyreduce ([1, 0, 3]) == [1, 0, 3])));
+%!error polyreduce ()
+%!error polyreduce (1, 2)
+%!error <C must be a non-empty vector> polyreduce ([1, 2; 3, 4])
+%!error <C must be a non-empty vector> polyreduce ([])
 
-%!error polyreduce ([1, 2; 3, 4]);
-
--- a/scripts/polynomial/polyval.m
+++ b/scripts/polynomial/polyval.m
@@ -19,19 +19,21 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {@var{y} =} polyval (@var{p}, @var{x})
 ## @deftypefnx {Function File} {@var{y} =} polyval (@var{p}, @var{x}, [], @var{mu})
+## @deftypefnx {Function File} {[@var{y}, @var{dy}] =} polyval (@var{p}, @var{x}, @var{s})
+## @deftypefnx {Function File} {[@var{y}, @var{dy}] =} polyval (@var{p}, @var{x}, @var{s}, @var{mu})
+## 
 ## Evaluate the polynomial @var{p} at the specified values of @var{x}.  When
 ## @var{mu} is present, evaluate the polynomial for
 ## (@var{x}-@var{mu}(1))/@var{mu}(2).
 ## If @var{x} is a vector or matrix, the polynomial is evaluated for each of
 ## the elements of @var{x}.
 ## 
-## @deftypefnx {Function File} {[@var{y}, @var{dy}] =} polyval (@var{p}, @var{x}, @var{s})
-## @deftypefnx {Function File} {[@var{y}, @var{dy}] =} polyval (@var{p}, @var{x}, @var{s}, @var{mu})
 ## In addition to evaluating the polynomial, the second output
 ## represents the prediction interval, @var{y} +/- @var{dy}, which
 ## contains at least 50% of the future predictions.  To calculate the
 ## prediction interval, the structured variable @var{s}, originating
 ## from @code{polyfit}, must be supplied.
+## 
 ## @seealso{polyvalm, polyaffine, polyfit, roots, poly}
 ## @end deftypefn
 
@@ -79,10 +81,10 @@
       dy = reshape (dy, size (x));
     catch
       if (isempty (s))
-        error ("polyval: third input is required.")
+        error ("polyval: third input is required.");
       elseif (isstruct (s)
               && all (ismember ({"R", "normr", "df"}, fieldnames (s))))
-        error (lasterr ())
+        error (lasterr ());
       elseif (isstruct (s))
         error ("polyval: third input is missing the required fields.");
       else
@@ -93,20 +95,20 @@
 
 endfunction
 
-%!test
-%! fail("polyval([1,0;0,1],0:10)");
+
+%!fail ("polyval ([1,0;0,1],0:10)")
 
 %!test
 %! r = 0:10:50;
 %! p = poly (r);
-%! p = p / max(abs(p));
-%! x = linspace(0,50,11);
-%! y = polyval(p,x) + 0.25*sin(100*x);
-%! [pf, s] = polyfit (x, y, numel(r));
+%! p = p / max (abs (p));
+%! x = linspace (0,50,11);
+%! y = polyval (p,x) + 0.25*sin (100*x);
+%! [pf, s] = polyfit (x, y, numel (r));
 %! [y1, delta] = polyval (pf, x, s);
 %! expected = [0.37235, 0.35854, 0.32231, 0.32448, 0.31328, ...
 %!    0.32036, 0.31328, 0.32448, 0.32231, 0.35854, 0.37235];
-%! assert (delta, expected, 0.00001)
+%! assert (delta, expected, 0.00001);
 
 %!test
 %! x = 10 + (-2:2);
@@ -115,38 +117,39 @@
 %! [pn, s, mu] = polyfit (x, y, numel (x) - 1);
 %! y1 = polyval (p, x);
 %! yn = polyval (pn, x, [], mu);
-%! assert (y1, y, sqrt(eps))
-%! assert (yn, y, sqrt(eps))
+%! assert (y1, y, sqrt (eps));
+%! assert (yn, y, sqrt (eps));
 
 %!test
 %! p = [0, 1, 0];
 %! x = 1:10;
-%! assert (x, polyval(p,x), eps)
+%! assert (x, polyval (p,x), eps);
 %! x = x(:);
-%! assert (x, polyval(p,x), eps)
-%! x = reshape(x, [2, 5]);
-%! assert (x, polyval(p,x), eps)
-%! x = reshape(x, [5, 2]);
-%! assert (x, polyval(p,x), eps)
-%! x = reshape(x, [1, 1, 5, 2]);
-%! assert (x, polyval(p,x), eps)
+%! assert (x, polyval (p,x), eps);
+%! x = reshape (x, [2, 5]);
+%! assert (x, polyval (p,x), eps);
+%! x = reshape (x, [5, 2]);
+%! assert (x, polyval (p,x), eps);
+%! x = reshape (x, [1, 1, 5, 2]);
+%! assert (x, polyval (p,x), eps);
 
 %!test
 %! p = [1];
 %! x = 1:10;
-%! y = ones(size(x));
-%! assert (y, polyval(p,x), eps)
+%! y = ones (size (x));
+%! assert (y, polyval (p,x), eps);
 %! x = x(:);
-%! y = ones(size(x));
-%! assert (y, polyval(p,x), eps)
-%! x = reshape(x, [2, 5]);
-%! y = ones(size(x));
-%! assert (y, polyval(p,x), eps)
-%! x = reshape(x, [5, 2]);
-%! y = ones(size(x));
-%! assert (y, polyval(p,x), eps)
-%! x = reshape(x, [1, 1, 5, 2]);
+%! y = ones (size (x));
+%! assert (y, polyval (p,x), eps);
+%! x = reshape (x, [2, 5]);
+%! y = ones (size (x));
+%! assert (y, polyval (p,x), eps);
+%! x = reshape (x, [5, 2]);
+%! y = ones (size (x));
+%! assert (y, polyval (p,x), eps);
+%! x = reshape (x, [1, 1, 5, 2]);
 
 %!assert (zeros (1, 10), polyval ([], 1:10))
 %!assert ([], polyval (1, []))
 %!assert ([], polyval ([], []))
+
--- a/scripts/polynomial/polyvalm.m
+++ b/scripts/polynomial/polyvalm.m
@@ -61,8 +61,8 @@
 endfunction
 
 
-%!assert(! any (polyvalm ([], [1, 2; 3, 4]))(:));
-%!assert(polyvalm ([1, 2, 3, 4], [3, -4, 1; -2, 0, 2; -1, 4, -3]), [117, -124, 11; -70, 36, 38; -43, 92, -45])
+%!assert (! any (polyvalm ([], [1, 2; 3, 4]))(:));
+%!assert (polyvalm ([1, 2, 3, 4], [3, -4, 1; -2, 0, 2; -1, 4, -3]), [117, -124, 11; -70, 36, 38; -43, 92, -45])
 
-%!error polyvalm ([1, 1, 1], [1, 2; 3, 4; 5, 6]);
+%!error <must be a square matrix> polyvalm ([1, 1, 1], [1, 2; 3, 4; 5, 6])
 
--- a/scripts/polynomial/ppder.m
+++ b/scripts/polynomial/ppder.m
@@ -51,20 +51,24 @@
   ppd = mkpp (x, pd, d);
 endfunction
 
+
 %!shared x,y,pp,ppd
-%! x=0:8;y=[x.^2;x.^3+1];pp=spline(x,y);
-%! ppd=ppder(pp);
-%!assert(ppval(ppd,x),[2*x;3*x.^2],1e-14)
-%!assert(ppd.order,3)
-%! ppd=ppder(pp,2);
-%!assert(ppval(ppd,x),[2*ones(size(x));6*x],1e-14)
-%!assert(ppd.order,2)
-%! ppd=ppder(pp,3);
-%!assert(ppd.order,1)
-%!assert(ppd.pieces,8)
-%!assert(size(ppd.coefs),[16,1])
-%! ppd=ppder(pp,4);
-%!assert(ppd.order,1)
-%!assert(ppd.pieces,1)
-%!assert(size(ppd.coefs),[2,1])
-%!assert(ppval(ppd,x),zeros(size(y)),1e-14)
+%! x = 0:8;
+%! y = [x.^2; x.^3+1];
+%! pp = spline (x, y);
+%! ppd = ppder (pp);
+%!assert (ppval (ppd, x), [2*x; 3*x.^2], 1e-14)
+%!assert (ppd.order, 3)
+%! ppd = ppder (pp, 2);
+%!assert (ppval (ppd, x), [2*ones(size (x)); 6*x], 1e-14)
+%!assert (ppd.order, 2)
+%! ppd = ppder (pp, 3);
+%!assert (ppd.order, 1)
+%!assert (ppd.pieces, 8)
+%!assert (size (ppd.coefs), [16, 1])
+%! ppd = ppder (pp, 4);
+%!assert (ppd.order, 1)
+%!assert (ppd.pieces, 1)
+%!assert (size (ppd.coefs), [2, 1])
+%!assert (ppval (ppd,x), zeros (size (y)), 1e-14)
+
--- a/scripts/polynomial/ppint.m
+++ b/scripts/polynomial/ppint.m
@@ -47,12 +47,16 @@
   ppi = mkpp (x, pi, d);
 
   tmp = -cumsum (ppjumps (ppi), length (d) + 1);
-  ppi.coefs(prod(d)+1:end, k) = tmp(:);
+  ppi.coefs(prod (d)+1 : end, k) = tmp(:);
 
 endfunction
 
+
 %!shared x,y,pp,ppi
-%! x=0:8;y=[ones(size(x));x+1];pp=spline(x,y);
-%! ppi=ppint(pp);
-%!assert(ppval(ppi,x),[x;0.5*x.^2+x],1e-14)
-%!assert(ppi.order,5)
+%! x = 0:8;
+%! y = [ ones(size(x)); x+1 ];
+%! pp = spline (x, y);
+%! ppi = ppint (pp);
+%!assert (ppval (ppi, x), [x; 0.5*x.^2 + x], 1e-14)
+%!assert (ppi.order, 5)
+
--- a/scripts/polynomial/ppjumps.m
+++ b/scripts/polynomial/ppjumps.m
@@ -34,18 +34,18 @@
   endif
 
   ## Extract info.
-  [x, P, n, k, d] = unmkpp(pp);
+  [x, P, n, k, d] = unmkpp (pp);
   nd = length (d) + 1;
 
   ## Offsets.
-  dx = diff(x(1:n));
+  dx = diff (x(1:n));
   dx = repmat (dx, [prod(d), 1]);
   dx = reshape (dx, [d, n-1]);
   dx = shiftdim (dx, nd - 1);
 
   ## Use Horner scheme.
   if (k>1)
-    llim = shiftdim (reshape (P(1:(n-1) * prod(d), 1), [d, n-1]), nd - 1);
+    llim = shiftdim (reshape (P(1:(n-1) * prod (d), 1), [d, n-1]), nd - 1);
   endif
 
   for i = 2 : k;
@@ -64,21 +64,20 @@
 %! y = polyval (p, x);
 %! pp = spline (x, y);
 %! jj = ppjumps (pp);
-%! assert (jj, [0 0], eps)
+%! assert (jj, [0 0], eps);
 
 %!test
-%!
 %! breaks = [0 1 2];
 %! pp1 = poly (-[1 2 3]);
 %! pp2 = poly (-([1 2 3]+1));
 %! pp = mkpp (breaks, [pp1;pp2]);
-%! assert (ppjumps (pp), 0, eps)
+%! assert (ppjumps (pp), 0, eps);
 
 %!test
-%!
 %! breaks = [0 1 2];
 %! pp1 = poly (-[1 2 3]);
 %! pp2 = poly (([1 2 3]+1));
 %! pp = mkpp (breaks, [pp1;pp2]);
 %! j  = - 2 * polyval (pp1, 1);
-%! assert (ppjumps (pp), j, eps)
+%! assert (ppjumps (pp), j, eps);
+
--- a/scripts/polynomial/ppval.m
+++ b/scripts/polynomial/ppval.m
@@ -56,7 +56,7 @@
   P = reshape (P, [n, k, d]);
   Pidx = P(idx(:), :);#2d matrix size x: coefs*prod(d) y: prod(sxi)
 
-  if (isvector(xi))
+  if (isvector (xi))
     Pidx = reshape (Pidx, [xn, k, d]);
     Pidx = shiftdim (Pidx, 1);
     dimvec = [d, xn];
@@ -68,7 +68,7 @@
   ndv = length (dimvec);
 
   ## Offsets.
-  dx = (xi - x(idx));
+  dx = (xi - x(idx))(:)';
   dx = repmat (dx, [prod(d), 1]);
   dx = reshape (dx, dimvec);
   dx = shiftdim (dx, ndv - 1);
@@ -92,7 +92,7 @@
   if (isvector (xi) && (d == 1))
     yi = reshape (yi, sxi);
   elseif (isfield (pp, "orient") && strcmp (pp.orient, "first"))
-    yi = shiftdim(yi, nd);
+    yi = shiftdim (yi, nd);
   endif
 
   ##
@@ -102,15 +102,28 @@
 
 endfunction
 
-%!shared b,c,pp,pp2,xi,abserr
-%! b = 1:3; c = ones(2); pp=mkpp(b,c);abserr = 1e-14;pp2=mkpp(b,[c;c],2);
+
+%!shared b, c, pp, pp2, xi, abserr
+%! b = 1:3;
+%! c = ones (2);
+%! pp = mkpp (b, c);
+%! abserr = 1e-14;
+%! pp2 = mkpp (b, [c;c], 2);
 %! xi = [1.1 1.3 1.9 2.1];
-%!assert (ppval(pp,1.1), 1.1, abserr);
-%!assert (ppval(pp,2.1), 1.1, abserr);
-%!assert (ppval(pp,xi), [1.1 1.3 1.9 1.1], abserr);
-%!assert (ppval(pp,xi.'), [1.1 1.3 1.9 1.1].', abserr);
-%!assert (ppval(pp2,1.1), [1.1;1.1], abserr);
-%!assert (ppval(pp2,2.1), [1.1;1.1], abserr);
-%!assert (ppval(pp2,xi), [1.1 1.3 1.9 1.1;1.1 1.3 1.9 1.1], abserr);
-%!assert (ppval(pp2,xi'), [1.1 1.3 1.9 1.1;1.1 1.3 1.9 1.1], abserr);
-%!assert (size(ppval(pp2,[xi;xi])), [2 2 4]);
+%!assert (ppval (pp, 1.1), 1.1, abserr)
+%!assert (ppval (pp, 2.1), 1.1, abserr)
+%!assert (ppval (pp, xi), [1.1 1.3 1.9 1.1], abserr)
+%!assert (ppval (pp, xi.'), [1.1 1.3 1.9 1.1].', abserr)
+%!assert (ppval (pp2, 1.1), [1.1;1.1], abserr)
+%!assert (ppval (pp2, 2.1), [1.1;1.1], abserr)
+%!assert (ppval (pp2, xi), [1.1 1.3 1.9 1.1;1.1 1.3 1.9 1.1], abserr)
+%!assert (ppval (pp2, xi'), [1.1 1.3 1.9 1.1;1.1 1.3 1.9 1.1], abserr)
+%!assert (size (ppval (pp2, [xi;xi])), [2 2 4])
+%!test
+%! breaks = [0, 1, 2, 3];
+%! coefs = rand (6, 4);
+%! pp = mkpp (breaks, coefs, 2);
+%! ret = zeros (2, 4, 2);
+%! ret(:,:,1) = ppval (pp, breaks');
+%! ret(:,:,2) = ppval (pp, breaks');
+%! assert (ppval (pp, [breaks',breaks']), ret)
new file mode 100644
--- /dev/null
+++ b/scripts/polynomial/private/__splinefit__.m
@@ -0,0 +1,624 @@
+## This function is private because it is maintained by Jonas Lundgren
+## separtely from Octave.  Please do not reformat to match Octave coding
+## conventions as that would make it harder to integrate upstream
+## changes.
+
+% Copyright (c) 2010, Jonas Lundgren
+% All rights reserved.
+% 
+% Redistribution and use in source and binary forms, with or without 
+% modification, are permitted provided that the following conditions are 
+% met:
+% 
+%     * Redistributions of source code must retain the above copyright 
+%       notice, this list of conditions and the following disclaimer.
+%     * Redistributions in binary form must reproduce the above copyright 
+%       notice, this list of conditions and the following disclaimer in 
+%       the documentation and/or other materials provided with the distribution
+%       
+% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
+% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
+% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
+% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
+% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
+% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+% POSSIBILITY OF SUCH DAMAGE.
+function pp = __splinefit__(varargin)
+%SPLINEFIT Fit a spline to noisy data.
+%   PP = SPLINEFIT(X,Y,BREAKS) fits a piecewise cubic spline with breaks
+%   (knots) BREAKS to the noisy data (X,Y). X is a vector and Y is a vector
+%   or an ND array. If Y is an ND array, then X(j) and Y(:,...,:,j) are
+%   matched. Use PPVAL to evaluate PP.
+%
+%   PP = SPLINEFIT(X,Y,P) where P is a positive integer interpolates the
+%   breaks linearly from the sorted locations of X. P is the number of
+%   spline pieces and P+1 is the number of breaks.
+%
+%   OPTIONAL INPUT
+%   Argument places 4 to 8 are reserved for optional input.
+%   These optional arguments can be given in any order:
+%
+%   PP = SPLINEFIT(...,'p') applies periodic boundary conditions to
+%   the spline. The period length is MAX(BREAKS)-MIN(BREAKS).
+%
+%   PP = SPLINEFIT(...,'r') uses robust fitting to reduce the influence
+%   from outlying data points. Three iterations of weighted least squares
+%   are performed. Weights are computed from previous residuals.
+%
+%   PP = SPLINEFIT(...,BETA), where 0 < BETA < 1, sets the robust fitting
+%   parameter BETA and activates robust fitting ('r' can be omitted).
+%   Default is BETA = 1/2. BETA close to 0 gives all data equal weighting.
+%   Increase BETA to reduce the influence from outlying data. BETA close
+%   to 1 may cause instability or rank deficiency.
+%
+%   PP = SPLINEFIT(...,N) sets the spline order to N. Default is a cubic
+%   spline with order N = 4. A spline with P pieces has P+N-1 degrees of
+%   freedom. With periodic boundary conditions the degrees of freedom are
+%   reduced to P.
+%
+%   PP = SPLINEFIT(...,CON) applies linear constraints to the spline.
+%   CON is a structure with fields 'xc', 'yc' and 'cc':
+%       'xc', x-locations (vector)
+%       'yc', y-values (vector or ND array)
+%       'cc', coefficients (matrix).
+%
+%   Constraints are linear combinations of derivatives of order 0 to N-2
+%   according to
+%
+%     cc(1,j)*y(x) + cc(2,j)*y'(x) + ... = yc(:,...,:,j),  x = xc(j).
+%
+%   The maximum number of rows for 'cc' is N-1. If omitted or empty 'cc'
+%   defaults to a single row of ones. Default for 'yc' is a zero array.
+%
+%   EXAMPLES
+%
+%       % Noisy data
+%       x = linspace(0,2*pi,100);
+%       y = sin(x) + 0.1*randn(size(x));
+%       % Breaks
+%       breaks = [0:5,2*pi];
+%
+%       % Fit a spline of order 5
+%       pp = splinefit(x,y,breaks,5);
+%
+%       % Fit a spline of order 3 with periodic boundary conditions
+%       pp = splinefit(x,y,breaks,3,'p');
+%
+%       % Constraints: y(0) = 0, y'(0) = 1 and y(3) + y"(3) = 0
+%       xc = [0 0 3];
+%       yc = [0 1 0];
+%       cc = [1 0 1; 0 1 0; 0 0 1];
+%       con = struct('xc',xc,'yc',yc,'cc',cc);
+%
+%       % Fit a cubic spline with 8 pieces and constraints
+%       pp = splinefit(x,y,8,con);
+%
+%       % Fit a spline of order 6 with constraints and periodicity
+%       pp = splinefit(x,y,breaks,con,6,'p');
+%
+%   See also SPLINE, PPVAL, PPDIFF, PPINT
+
+%   Author: Jonas Lundgren <splinefit@gmail.com> 2010
+
+%   2009-05-06  Original SPLINEFIT.
+%   2010-06-23  New version of SPLINEFIT based on B-splines.
+%   2010-09-01  Robust fitting scheme added.
+%   2010-09-01  Support for data containing NaNs.
+%   2011-07-01  Robust fitting parameter added.
+
+% Check number of arguments
+error(nargchk(3,7,nargin));
+
+% Check arguments
+[x,y,dim,breaks,n,periodic,beta,constr] = arguments(varargin{:});
+
+% Evaluate B-splines
+base = splinebase(breaks,n);
+pieces = base.pieces;
+A = ppval(base,x);
+
+% Bin data
+[junk,ibin] = histc(x,[-inf,breaks(2:end-1),inf]); %#ok
+
+% Sparse system matrix
+mx = numel(x);
+ii = [ibin; ones(n-1,mx)];
+ii = cumsum(ii,1);
+jj = repmat(1:mx,n,1);
+if periodic
+    ii = mod(ii-1,pieces) + 1;
+    A = sparse(ii,jj,A,pieces,mx);
+else
+    A = sparse(ii,jj,A,pieces+n-1,mx);
+end
+
+% Don't use the sparse solver for small problems
+if pieces < 20*n/log(1.7*n)
+    A = full(A);
+end
+
+% Solve
+if isempty(constr)
+    % Solve Min norm(u*A-y)
+    u = lsqsolve(A,y,beta);
+else
+    % Evaluate constraints
+    B = evalcon(base,constr,periodic);
+    % Solve constraints
+    [Z,u0] = solvecon(B,constr);
+    % Solve Min norm(u*A-y), subject to u*B = yc
+    y = y - u0*A;
+    A = Z*A;
+    v = lsqsolve(A,y,beta);
+    u = u0 + v*Z;
+end
+
+% Periodic expansion of solution
+if periodic
+    jj = mod(0:pieces+n-2,pieces) + 1;
+    u = u(:,jj);
+end
+
+% Compute polynomial coefficients
+ii = [repmat(1:pieces,1,n); ones(n-1,n*pieces)];
+ii = cumsum(ii,1);
+jj = repmat(1:n*pieces,n,1);
+C = sparse(ii,jj,base.coefs,pieces+n-1,n*pieces);
+coefs = u*C;
+coefs = reshape(coefs,[],n);
+
+% Make piecewise polynomial
+pp = mkpp(breaks,coefs,dim);
+
+
+%--------------------------------------------------------------------------
+function [x,y,dim,breaks,n,periodic,beta,constr] = arguments(varargin)
+%ARGUMENTS Lengthy input checking
+%   x           Noisy data x-locations (1 x mx)
+%   y           Noisy data y-values (prod(dim) x mx)
+%   dim         Leading dimensions of y
+%   breaks      Breaks (1 x (pieces+1))
+%   n           Spline order
+%   periodic    True if periodic boundary conditions
+%   beta        Robust fitting parameter, no robust fitting if beta = 0
+%   constr      Constraint structure
+%   constr.xc   x-locations (1 x nx)
+%   constr.yc   y-values (prod(dim) x nx)
+%   constr.cc   Coefficients (?? x nx)
+
+% Reshape x-data
+x = varargin{1};
+mx = numel(x);
+x = reshape(x,1,mx);
+
+% Remove trailing singleton dimensions from y
+y = varargin{2};
+dim = size(y);
+while numel(dim) > 1 && dim(end) == 1
+    dim(end) = [];
+end
+my = dim(end);
+
+% Leading dimensions of y
+if numel(dim) > 1
+    dim(end) = [];
+else
+    dim = 1;
+end
+
+% Reshape y-data
+pdim = prod(dim);
+y = reshape(y,pdim,my);
+
+% Check data size
+if mx ~= my
+    mess = 'Last dimension of array y must equal length of vector x.';
+    error('arguments:datasize',mess)
+end
+
+% Treat NaNs in x-data
+inan = find(isnan(x));
+if ~isempty(inan)
+    x(inan) = [];
+    y(:,inan) = [];
+    mess = 'All data points with NaN as x-location will be ignored.';
+    warning('arguments:nanx',mess)
+end
+
+% Treat NaNs in y-data
+inan = find(any(isnan(y),1));
+if ~isempty(inan)
+    x(inan) = [];
+    y(:,inan) = [];
+    mess = 'All data points with NaN in their y-value will be ignored.';
+    warning('arguments:nany',mess)
+end
+
+% Check number of data points
+mx = numel(x);
+if mx == 0
+    error('arguments:nodata','There must be at least one data point.')
+end
+
+% Sort data
+if any(diff(x) < 0)
+    [x,isort] = sort(x);
+    y = y(:,isort);
+end
+
+% Breaks
+if isscalar(varargin{3})
+    % Number of pieces
+    p = varargin{3};
+    if ~isreal(p) || ~isfinite(p) || p < 1 || fix(p) < p
+        mess = 'Argument #3 must be a vector or a positive integer.';
+        error('arguments:breaks1',mess)
+    end
+    if x(1) < x(end)
+        % Interpolate breaks linearly from x-data
+        dx = diff(x);
+        ibreaks = linspace(1,mx,p+1);
+        [junk,ibin] = histc(ibreaks,[0,2:mx-1,mx+1]); %#ok
+        breaks = x(ibin) + dx(ibin).*(ibreaks-ibin);
+    else
+        breaks = x(1) + linspace(0,1,p+1);
+    end
+else
+    % Vector of breaks
+    breaks = reshape(varargin{3},1,[]);
+    if isempty(breaks) || min(breaks) == max(breaks)
+        mess = 'At least two unique breaks are required.';
+        error('arguments:breaks2',mess);
+    end
+end
+
+% Unique breaks
+if any(diff(breaks) <= 0)
+    breaks = unique(breaks);
+end
+
+% Optional input defaults
+n = 4;                      % Cubic splines
+periodic = false;           % No periodic boundaries
+robust = false;             % No robust fitting scheme
+beta = 0.5;                 % Robust fitting parameter
+constr = [];                % No constraints
+
+% Loop over optional arguments
+for k = 4:nargin
+    a = varargin{k};
+    if ischar(a) && isscalar(a) && lower(a) == 'p'
+        % Periodic conditions
+        periodic = true;
+    elseif ischar(a) && isscalar(a) && lower(a) == 'r'
+        % Robust fitting scheme
+        robust = true;
+    elseif isreal(a) && isscalar(a) && isfinite(a) && a > 0 && a < 1
+        % Robust fitting parameter
+        beta = a;
+        robust = true;
+    elseif isreal(a) && isscalar(a) && isfinite(a) && a > 0 && fix(a) == a
+        % Spline order
+        n = a;
+    elseif isstruct(a) && isscalar(a)
+        % Constraint structure
+        constr = a;
+    else
+        error('arguments:nonsense','Failed to interpret argument #%d.',k)
+    end
+end
+
+% No robust fitting
+if ~robust
+    beta = 0;
+end
+
+% Check exterior data
+h = diff(breaks);
+xlim1 = breaks(1) - 0.01*h(1);
+xlim2 = breaks(end) + 0.01*h(end);
+if x(1) < xlim1 || x(end) > xlim2
+    if periodic
+        % Move data inside domain
+        P = breaks(end) - breaks(1);
+        x = mod(x-breaks(1),P) + breaks(1);
+        % Sort
+        [x,isort] = sort(x);
+        y = y(:,isort);
+    else
+        mess = 'Some data points are outside the spline domain.';
+        warning('arguments:exteriordata',mess)
+    end
+end
+
+% Return
+if isempty(constr)
+    return
+end
+
+% Unpack constraints
+xc = [];
+yc = [];
+cc = [];
+names = fieldnames(constr);
+for k = 1:numel(names)
+    switch names{k}
+        case {'xc'}
+            xc = constr.xc;
+        case {'yc'}
+            yc = constr.yc;
+        case {'cc'}
+            cc = constr.cc;
+        otherwise
+            mess = 'Unknown field ''%s'' in constraint structure.';
+            warning('arguments:unknownfield',mess,names{k})
+    end
+end
+
+% Check xc
+if isempty(xc)
+    mess = 'Constraints contains no x-locations.';
+    error('arguments:emptyxc',mess)
+else
+    nx = numel(xc);
+    xc = reshape(xc,1,nx);
+end
+
+% Check yc
+if isempty(yc)
+    % Zero array
+    yc = zeros(pdim,nx);
+elseif numel(yc) == 1
+    % Constant array
+    yc = zeros(pdim,nx) + yc;
+elseif numel(yc) ~= pdim*nx
+    % Malformed array
+    error('arguments:ycsize','Cannot reshape yc to size %dx%d.',pdim,nx)
+else
+    % Reshape array
+    yc = reshape(yc,pdim,nx);
+end
+
+% Check cc
+if isempty(cc)
+    cc = ones(size(xc));
+elseif numel(size(cc)) ~= 2
+    error('arguments:ccsize1','Constraint coefficients cc must be 2D.')
+elseif size(cc,2) ~= nx
+    mess = 'Last dimension of cc must equal length of xc.';
+    error('arguments:ccsize2',mess)
+end
+
+% Check high order derivatives
+if size(cc,1) >= n
+    if any(any(cc(n:end,:)))
+        mess = 'Constraints involve derivatives of order %d or larger.';
+        error('arguments:difforder',mess,n-1)
+    end
+    cc = cc(1:n-1,:);
+end
+
+% Check exterior constraints
+if min(xc) < xlim1 || max(xc) > xlim2
+    if periodic
+        % Move constraints inside domain
+        P = breaks(end) - breaks(1);
+        xc = mod(xc-breaks(1),P) + breaks(1);
+    else
+        mess = 'Some constraints are outside the spline domain.';
+        warning('arguments:exteriorconstr',mess)
+    end
+end
+
+% Pack constraints
+constr = struct('xc',xc,'yc',yc,'cc',cc);
+
+
+%--------------------------------------------------------------------------
+function pp = splinebase(breaks,n)
+%SPLINEBASE Generate B-spline base PP of order N for breaks BREAKS
+
+breaks = breaks(:);     % Breaks
+breaks0 = breaks';      % Initial breaks
+h = diff(breaks);       % Spacing
+pieces = numel(h);      % Number of pieces
+deg = n - 1;            % Polynomial degree
+
+% Extend breaks periodically
+if deg > 0
+    if deg <= pieces
+        hcopy = h;
+    else
+        hcopy = repmat(h,ceil(deg/pieces),1);
+    end
+    % to the left
+    hl = hcopy(end:-1:end-deg+1);
+    bl = breaks(1) - cumsum(hl);
+    % and to the right
+    hr = hcopy(1:deg);
+    br = breaks(end) + cumsum(hr);
+    % Add breaks
+    breaks = [bl(deg:-1:1); breaks; br];
+    h = diff(breaks);
+    pieces = numel(h);
+end
+
+% Initiate polynomial coefficients
+coefs = zeros(n*pieces,n);
+coefs(1:n:end,1) = 1;
+
+% Expand h
+ii = [1:pieces; ones(deg,pieces)];
+ii = cumsum(ii,1);
+ii = min(ii,pieces);
+H = h(ii(:));
+
+% Recursive generation of B-splines
+for k = 2:n
+    % Antiderivatives of splines
+    for j = 1:k-1
+        coefs(:,j) = coefs(:,j).*H/(k-j);
+    end
+    Q = sum(coefs,2);
+    Q = reshape(Q,n,pieces);
+    Q = cumsum(Q,1);
+    c0 = [zeros(1,pieces); Q(1:deg,:)];
+    coefs(:,k) = c0(:);
+    % Normalize antiderivatives by max value
+    fmax = repmat(Q(n,:),n,1);
+    fmax = fmax(:);
+    for j = 1:k
+        coefs(:,j) = coefs(:,j)./fmax;
+    end
+    % Diff of adjacent antiderivatives
+    coefs(1:end-deg,1:k) = coefs(1:end-deg,1:k) - coefs(n:end,1:k);
+    coefs(1:n:end,k) = 0;
+end
+
+% Scale coefficients
+scale = ones(size(H));
+for k = 1:n-1
+    scale = scale./H;
+    coefs(:,n-k) = scale.*coefs(:,n-k);
+end
+
+% Reduce number of pieces
+pieces = pieces - 2*deg;
+
+% Sort coefficients by interval number
+ii = [n*(1:pieces); deg*ones(deg,pieces)];
+ii = cumsum(ii,1);
+coefs = coefs(ii(:),:);
+
+% Make piecewise polynomial
+pp = mkpp(breaks0,coefs,n);
+
+
+%--------------------------------------------------------------------------
+function B = evalcon(base,constr,periodic)
+%EVALCON Evaluate linear constraints
+
+% Unpack structures
+breaks = base.breaks;
+pieces = base.pieces;
+n = base.order;
+xc = constr.xc;
+cc = constr.cc;
+
+% Bin data
+[junk,ibin] = histc(xc,[-inf,breaks(2:end-1),inf]); %#ok
+
+% Evaluate constraints
+nx = numel(xc);
+B0 = zeros(n,nx);
+for k = 1:size(cc,1)
+    if any(cc(k,:))
+        B0 = B0 + repmat(cc(k,:),n,1).*ppval(base,xc);
+    end
+    % Differentiate base
+    coefs = base.coefs(:,1:n-k);
+    for j = 1:n-k-1
+        coefs(:,j) = (n-k-j+1)*coefs(:,j);
+    end
+    base.coefs = coefs;
+    base.order = n-k;
+end
+
+% Sparse output
+ii = [ibin; ones(n-1,nx)];
+ii = cumsum(ii,1);
+jj = repmat(1:nx,n,1);
+if periodic
+    ii = mod(ii-1,pieces) + 1;
+    B = sparse(ii,jj,B0,pieces,nx);
+else
+    B = sparse(ii,jj,B0,pieces+n-1,nx);
+end
+
+
+%--------------------------------------------------------------------------
+function [Z,u0] = solvecon(B,constr)
+%SOLVECON Find a particular solution u0 and null space Z (Z*B = 0)
+%         for constraint equation u*B = yc.
+
+yc = constr.yc;
+tol = 1000*eps;
+
+% Remove blank rows
+ii = any(B,2);
+B2 = full(B(ii,:));
+
+% Null space of B2
+if isempty(B2)
+    Z2 = [];
+else
+    % QR decomposition with column permutation
+    [Q,R,dummy] = qr(B2); %#ok
+    R = abs(R);
+    jj = all(R < R(1)*tol, 2);
+    Z2 = Q(:,jj)';
+end
+
+% Sizes
+[m,ncon] = size(B);
+m2 = size(B2,1);
+nz = size(Z2,1);
+
+% Sparse null space of B
+Z = sparse(nz+1:nz+m-m2,find(~ii),1,nz+m-m2,m);
+Z(1:nz,ii) = Z2;
+
+% Warning rank deficient
+if nz + ncon > m2
+	mess = 'Rank deficient constraints, rank = %d.';
+	warning('solvecon:deficient',mess,m2-nz);
+end
+
+% Particular solution
+u0 = zeros(size(yc,1),m);
+if any(yc(:))
+    % Non-homogeneous case
+	u0(:,ii) = yc/B2;
+    % Check solution
+	if norm(u0*B - yc,'fro') > norm(yc,'fro')*tol
+        mess = 'Inconsistent constraints. No solution within tolerance.';
+        error('solvecon:inconsistent',mess)
+	end
+end
+
+
+%--------------------------------------------------------------------------
+function u = lsqsolve(A,y,beta)
+%LSQSOLVE Solve Min norm(u*A-y)
+
+% Avoid sparse-complex limitations
+if issparse(A) && ~isreal(y)
+    A = full(A);
+end
+
+% Solution
+u = y/A;
+
+% Robust fitting
+if beta > 0
+    [m,n] = size(y);
+    alpha = 0.5*beta/(1-beta)/m;
+    for k = 1:3
+        % Residual
+        r = u*A - y;
+        rr = r.*conj(r);
+        rrmean = sum(rr,2)/n;
+        rrmean(~rrmean) = 1;
+        rrhat = (alpha./rrmean)'*rr;
+        % Weights
+        w = exp(-rrhat);
+        spw = spdiags(w',0,n,n);
+        % Solve weighted problem
+        u = (y*spw)/(A*spw);
+    end
+end
+
--- a/scripts/polynomial/residue.m
+++ b/scripts/polynomial/residue.m
@@ -252,7 +252,7 @@
 
   A = zeros (border+1, border+1);
   B = prepad (reshape (b, [numel(b), 1]), border+1, 0);
-  for ip = 1:numel(p)
+  for ip = 1:numel (p)
     ri = zeros (size (p));
     ri(ip) = 1;
     A(:,ip) = prepad (rresidue (ri, p, [], toler), border+1, 0).';
@@ -285,19 +285,19 @@
     k = [];
   endif
 
-  if numel (e)
-    indx = 1:numel(p);
+  if (numel (e))
+    indx = 1:numel (p);
   else
     [e, indx] = mpoles (p, toler, 0);
     p = p (indx);
     r = r (indx);
   endif
 
-  indx = 1:numel(p);
+  indx = 1:numel (p);
 
   for n = indx
     pn = [1, -p(n)];
-    if n == 1
+    if (n == 1)
       pden = pn;
     else
       pden = conv (pden, pn);
@@ -351,23 +351,24 @@
 
 endfunction
 
+
 %!test
 %! b = [1, 1, 1];
 %! a = [1, -5, 8, -4];
 %! [r, p, k, e] = residue (b, a);
-%! assert (abs (r - [-2; 7; 3]) < 1e-12
-%!   && abs (p - [2; 2; 1]) < 1e-12
-%!   && isempty (k)
-%!   && e == [1; 2; 1]);
+%! assert (r, [-2; 7; 3], 1e-12);
+%! assert (p, [2; 2; 1], 1e-12);
+%! assert (isempty (k));
+%! assert (e, [1; 2; 1]);
 %! k = [1 0];
 %! b = conv (k, a) + prepad (b, numel (k) + numel (a) - 1, 0);
 %! a = a;
 %! [br, ar] = residue (r, p, k);
-%! assert ((abs (br - b) < 1e-12
-%!   && abs (ar - a) < 1e-12));
+%! assert (br, b, 1e-12);
+%! assert (ar, a, 1e-12);
 %! [br, ar] = residue (r, p, k, e);
-%! assert ((abs (br - b) < 1e-12
-%!   && abs (ar - a) < 1e-12));
+%! assert (br, b, 1e-12);
+%! assert (ar, a, 1e-12);
 
 %!test
 %! b = [1, 0, 1];
@@ -375,12 +376,13 @@
 %! [r, p, k, e] = residue (b, a);
 %! r1 = [-5i; 12; +5i; 12]/54;
 %! p1 = [+3i; +3i; -3i; -3i];
-%! assert (abs (r - r1) < 1e-12 && abs (p - p1) < 1e-12
-%!   && isempty (k)
-%!   && e == [1; 2; 1; 2]);
+%! assert (r, r1, 1e-12);
+%! assert (p, p1, 1e-12);
+%! assert (isempty (k));
+%! assert (e, [1; 2; 1; 2]);
 %! [br, ar] = residue (r, p, k);
-%! assert ((abs (br - b) < 1e-12
-%!   && abs (ar - a) < 1e-12));
+%! assert (br, b, 1e-12);
+%! assert (ar, a, 1e-12);
 
 %!test
 %! r = [7; 3; -2];
@@ -388,14 +390,14 @@
 %! k = [1 0];
 %! e = [2; 1; 1];
 %! [b, a] = residue (r, p, k, e);
-%! assert ((abs (b - [1, -5, 9, -3, 1]) < 1e-12
-%!   && abs (a - [1, -5, 8, -4]) < 1e-12));
+%! assert (b, [1, -5, 9, -3, 1], 1e-12);
+%! assert (a, [1, -5, 8, -4], 1e-12);
 %! [rr, pr, kr, er] = residue (b, a);
-%! [jnk, n] = mpoles(p);
-%! assert ((abs (rr - r(n)) < 1e-12
-%!   && abs (pr - p(n)) < 1e-12
-%!   && abs (kr - k) < 1e-12
-%!   && abs (er - e(n)) < 1e-12));
+%! [jnk, n] = mpoles (p);
+%! assert (rr, r(n), 1e-12);
+%! assert (pr, p(n), 1e-12);
+%! assert (kr, k, 1e-12);
+%! assert (er, e(n), 1e-12);
 
 %!test
 %! b = [1];
@@ -403,12 +405,13 @@
 %! [r, p, k, e] = residue (b, a);
 %! r1 = [0; 1];
 %! p1 = [-5; -5];
-%! assert (abs (r - r1) < 1e-12 && abs (p - p1) < 1e-12
-%!   && isempty (k)
-%!   && e == [1; 2]);
+%! assert (r, r1, 1e-12);
+%! assert (p, p1, 1e-12);
+%! assert (isempty (k));
+%! assert (e, [1; 2]);
 %! [br, ar] = residue (r, p, k);
-%! assert ((abs (br - b) < 1e-12
-%!   && abs (ar - a) < 1e-12));
+%! assert (br, b, 1e-12);
+%! assert (ar, a, 1e-12);
 
 ## The following test is due to Bernard Grung (bug #34266)
 %!xtest
@@ -428,3 +431,4 @@
 %! [br, ar] = residue (r, p, k, e);
 %! assert (br, b, 1e-8);
 %! assert (ar, a, 1e-8);
+
--- a/scripts/polynomial/roots.m
+++ b/scripts/polynomial/roots.m
@@ -81,7 +81,7 @@
 
   if (nargin != 1 || min (size (v)) > 1)
     print_usage ();
-  elseif (any (isnan(v) | isinf(v)))
+  elseif (any (isnan (v) | isinf (v)))
     error ("roots: inputs must not contain Inf or NaN");
   endif
 
@@ -118,24 +118,22 @@
 
 endfunction
 
+
 %!test
 %! p = [poly([3 3 3 3]), 0 0 0 0];
 %! r = sort (roots (p));
-%! assert (r, [0; 0; 0; 0; 3; 3; 3; 3], 0.001)
-
-%!assert(all (all (abs (roots ([1, -6, 11, -6]) - [3; 2; 1]) < sqrt (eps))));
-
-%!assert(isempty (roots ([])));
-
-%!error roots ([1, 2; 3, 4]);
+%! assert (r, [0; 0; 0; 0; 3; 3; 3; 3], 0.001);
 
-%!assert(isempty (roots (1)));
-
-%!error roots ([1, 2; 3, 4]);
-
-%!error roots ([1 Inf 1]);
-
-%!error roots ([1 NaN 1]);
+%!assert (isempty (roots ([])))
+%!assert (isempty (roots (1)))
+%!assert (roots ([1, -6, 11, -6]), [3; 2; 1], sqrt (eps))
 
 %!assert(roots ([1e-200, -1e200, 1]), 1e-200)
 %!assert(roots ([1e-200, -1e200 * 1i, 1]), -1e-200 * 1i)
+
+%!error roots ()
+%!error roots (1,2)
+%!error roots ([1, 2; 3, 4])
+%!error <inputs must not contain Inf or NaN> roots ([1 Inf 1])
+%!error <inputs must not contain Inf or NaN> roots ([1 NaN 1])
+
--- a/scripts/polynomial/spline.m
+++ b/scripts/polynomial/spline.m
@@ -100,15 +100,15 @@
   endfor
 
   complete = false;
-  if (size (a, 1) == n + 2)
+  if (rows (a) == n + 2)
     complete = true;
     dfs = a(1,:);
     dfe = a(end,:);
     a = a(2:end-1,:);
   endif
 
-  if (~issorted (x))
-    [x, idx] = sort(x);
+  if (! issorted (x))
+    [x, idx] = sort (x);
     a = a(idx,:);
   endif
 
@@ -131,31 +131,12 @@
       b = b(1:n-1,:);
       a = a(1:n-1,:);
     else
-      if (n == 3)
-        dg = 1.5 * h(1) - 0.5 * h(2);
-        c(2:n-1,:) = 1/dg(1);
-      else
-        dg = 2 * (h(1:n-2) .+ h(2:n-1));
-        dg(1) = dg(1) - 0.5 * h(1);
-        dg(n-2) = dg(n-2) - 0.5 * h(n-1);
-
-        e = h(2:n-2);
-
-        g = 3 * diff (a(2:n,:)) ./ h(2:n-1,idx) ...
-          - 3 * diff (a(1:n-1,:)) ./ h(1:n-2,idx);
-        g(1,:) = 3 * (a(3,:) - a(2,:)) / h(2) ...
-          - 3 / 2 * (3 * (a(2,:) - a(1,:)) / h(1) - dfs);
-        g(n-2,:) = 3 / 2 * (3 * (a(n,:) - a(n-1,:)) / h(n-1) - dfe) ...
-          - 3 * (a(n-1,:) - a(n-2,:)) / h(n-2);
-
-        c(2:n-1,:) = spdiags ([[e(:); 0], dg, [0; e(:)]],
-                              [-1, 0, 1], n-2, n-2) \ g;
-      endif
-
-      c(1,:) = (3 / h(1) * (a(2,:) - a(1,:)) - 3 * dfs
-             - c(2,:) * h(1)) / (2 * h(1));
-      c(n,:) = - (3 / h(n-1) * (a(n,:) - a(n-1,:)) - 3 * dfe
-             + c(n-1,:) * h(n-1)) / (2 * h(n-1));
+      g(1,:) = (a(2,:) - a(1,:)) / h(1) - dfs;
+      g(2:n-1,:) = (a(3:n,:) - a(2:n-1,:)) ./ h(2:n-1) - ...
+                   (a(2:n-1,:) - a(1:n-2,:)) ./ h(1:n-2);
+      g(n,:) = dfe - (a(n,:) - a(n-1,:)) / h(n-1);
+      c = spdiags ([[h/6;0],[h(1)/3;(h(1:n-2)+h(2:n-1))/3;h(n-1)/3],[0;h/6]],...
+                   [-1,0,1],n,n) \ (g / 2);
       b(1:n-1,:) = diff (a) ./ h(1:n-1, idx) ...
         - h(1:n-1,idx) / 3 .* (c(2:n,:) + 2 * c(1:n-1,:));
       d = diff (c) ./ (3 * h(1:n-1, idx));
@@ -244,37 +225,38 @@
 
 endfunction
 
+
 %!demo
-%! x = 0:10; y = sin(x);
-%! xspline = 0:0.1:10; yspline = spline(x,y,xspline);
-%! title("spline fit to points from sin(x)");
-%! plot(xspline,sin(xspline),"r",xspline,yspline,"g-",x,y,"b+");
-%! legend("original","interpolation","interpolation points");
+%! x = 0:10; y = sin (x);
+%! xspline = 0:0.1:10;  yspline = spline (x,y,xspline);
+%! title ("spline fit to points from sin (x)");
+%! plot (xspline,sin(xspline),"r", xspline,yspline,"g-", x,y,"b+");
+%! legend ("original", "interpolation", "interpolation points");
 %! %--------------------------------------------------------
 %! % confirm that interpolated function matches the original
 
 %!shared x,y,abserr
-%! x = [0:10]; y = sin(x); abserr = 1e-14;
-%!assert (spline(x,y,x), y, abserr);
-%!assert (spline(x,y,x'), y', abserr);
-%!assert (spline(x',y',x'), y', abserr);
-%!assert (spline(x',y',x), y, abserr);
-%!assert (isempty(spline(x',y',[])));
-%!assert (isempty(spline(x,y,[])));
-%!assert (spline(x,[y;y],x), [spline(x,y,x);spline(x,y,x)],abserr)
-%!assert (spline(x,[y;y],x'), [spline(x,y,x);spline(x,y,x)],abserr)
-%!assert (spline(x',[y;y],x), [spline(x,y,x);spline(x,y,x)],abserr)
-%!assert (spline(x',[y;y],x'), [spline(x,y,x);spline(x,y,x)],abserr)
-%! y = cos(x) + i*sin(x);
-%!assert (spline(x,y,x), y, abserr)
-%!assert (real(spline(x,y,x)), real(y), abserr);
-%!assert (real(spline(x,y,x.')), real(y).', abserr);
-%!assert (real(spline(x.',y.',x.')), real(y).', abserr);
-%!assert (real(spline(x.',y,x)), real(y), abserr);
-%!assert (imag(spline(x,y,x)), imag(y), abserr);
-%!assert (imag(spline(x,y,x.')), imag(y).', abserr);
-%!assert (imag(spline(x.',y.',x.')), imag(y).', abserr);
-%!assert (imag(spline(x.',y,x)), imag(y), abserr);
+%! x = [0:10]; y = sin (x); abserr = 1e-14;
+%!assert (spline (x,y,x), y, abserr)
+%!assert (spline (x,y,x'), y', abserr)
+%!assert (spline (x',y',x'), y', abserr)
+%!assert (spline (x',y',x), y, abserr)
+%!assert (isempty (spline (x',y',[])))
+%!assert (isempty (spline (x,y,[])))
+%!assert (spline (x,[y;y],x), [spline(x,y,x);spline(x,y,x)], abserr)
+%!assert (spline (x,[y;y],x'), [spline(x,y,x);spline(x,y,x)], abserr)
+%!assert (spline (x',[y;y],x), [spline(x,y,x);spline(x,y,x)], abserr)
+%!assert (spline (x',[y;y],x'), [spline(x,y,x);spline(x,y,x)], abserr)
+%! y = cos (x) + i*sin (x);
+%!assert (spline (x,y,x), y, abserr)
+%!assert (real (spline (x,y,x)), real (y), abserr)
+%!assert (real (spline (x,y,x.')), real (y).', abserr)
+%!assert (real (spline (x.',y.',x.')), real (y).', abserr)
+%!assert (real (spline (x.',y,x)), real (y), abserr)
+%!assert (imag (spline (x,y,x)), imag (y), abserr)
+%!assert (imag (spline (x,y,x.')), imag (y).', abserr)
+%!assert (imag (spline (x.',y.',x.')), imag (y).', abserr)
+%!assert (imag (spline (x.',y,x)), imag (y), abserr)
 %!test
 %! xnan = 5;
 %! y(x==xnan) = NaN;
@@ -296,10 +278,23 @@
 %! y = [1,2,3,4];
 %! pp = spline (x,y);
 %! [x,P] = unmkpp (pp);
-%! assert (norm (P-[3,-3,1,2]), 0, abserr);
+%! assert (P, [3,-3,1,2], abserr);
 %!test
 %! x = [2,1];
 %! y = [1,2,3,4];
 %! pp = spline (x,y);
 %! [x,P] = unmkpp (pp);
-%! assert (norm (P-[7,-9,1,3]), 0, abserr);
+%! assert (P, [7,-9,1,3], abserr);
+%!test
+%! x = [0,1,2];
+%! y = [0,0,1,0,0];
+%! pp = spline (x,y);
+%! [x,P] = unmkpp (pp);
+%! assert (P, [-2,3,0,0;2,-3,0,1], abserr);
+%!test
+%! x = [0,1,2,3];
+%! y = [0,0,1,1,0,0];
+%! pp = spline (x,y);
+%! [x,P] = unmkpp (pp);
+%! assert (P, [-1,2,0,0;0,-1,1,1;1,-1,-1,1], abserr);
+
new file mode 100644
--- /dev/null
+++ b/scripts/polynomial/splinefit.m
@@ -0,0 +1,239 @@
+## Copyright (C) 2012 Ben Abbott, Jonas Lundgren
+##
+## 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{pp} =} splinefit (@var{x}, @var{y}, @var{breaks})
+## @deftypefnx {Function File} {@var{pp} =} splinefit (@var{x}, @var{y}, @var{p})
+## @deftypefnx {Function File} {@var{pp} =} splinefit (@dots{}, "periodic", @var{periodic})
+## @deftypefnx {Function File} {@var{pp} =} splinefit (@dots{}, "robust", @var{robust})
+## @deftypefnx {Function File} {@var{pp} =} splinefit (@dots{}, "beta", @var{beta})
+## @deftypefnx {Function File} {@var{pp} =} splinefit (@dots{}, "order", @var{order})
+## @deftypefnx {Function File} {@var{pp} =} splinefit (@dots{}, "constraints", @var{constraints})
+##
+## Fit a piecewise cubic spline with breaks (knots) @var{breaks} to the
+## noisy data, @var{x} and @var{y}.  @var{x} is a vector, and @var{y}
+## is a vector or N-D array.  If @var{y} is an N-D array, then @var{x}(j)
+## is matched to @var{y}(:,@dots{},:,j).
+##
+## The fitted spline is returned as a piecewise polynomial, @var{pp}, and
+## may be evaluated using @code{ppval}.
+##
+## @var{p} is a positive integer defining the number of intervals along @var{x},
+## and @var{p}+1 is the number of breaks.  The number of points in each interval
+## differ by no more than 1.
+##
+## The optional property @var{periodic} is a logical value which specifies
+## whether a periodic boundary condition is applied to the spline.  The
+## length of the period is @code{max (@var{breaks}) - min (@var{breaks})}.
+## The default value is @code{false}.
+##
+## The optional property @var{robust} is a logical value which specifies
+## if robust fitting is to be applied to reduce the influence of outlying
+## data points.  Three iterations of weighted least squares are performed.
+## Weights are computed from previous residuals.  The sensitivity of outlier
+## identification is controlled by the property @var{beta}.  The value of
+## @var{beta} is stricted to the range, 0 < @var{beta} < 1.  The default
+## value is @var{beta} = 1/2.  Values close to 0 give all data equal
+## weighting.  Increasing values of @var{beta} reduce the influence of
+## outlying data.  Values close to unity may cause instability or rank
+## deficiency.
+##
+## The splines are constructed of polynomials with degree @var{order}.
+## The default is a cubic, @var{order}=3.  A spline with P pieces has
+## P+@var{order} degrees of freedom.  With periodic boundary conditions
+## the degrees of freedom are reduced to P.
+##
+## The optional property, @var{constaints}, is a structure specifying
+## linear constraints on the fit.  The structure has three fields, "xc",
+## "yc", and "cc".
+##
+## @table @asis
+## @item "xc"
+## Vector of the x-locations of the constraints.
+##
+## @item "yc"
+## Constraining values at the locations @var{xc}.
+## The default is an array of zeros.
+##
+## @item "cc"
+## Coefficients (matrix).  The default is an array of ones.  The number of
+## rows is limited to the order of the piecewise polynomials, @var{order}.
+## @end table
+##
+## Constraints are linear combinations of derivatives of order 0 to
+## @var{order}-1 according to
+##
+## @example
+## @group
+## @tex
+## $cc(1,j) \cdot y(xc(j)) + cc(2,j) \cdot y\prime(xc(j)) + ... = yc(:,\dots,:,j)$.
+## @end tex
+## @ifnottex
+## cc(1,j) * y(xc(j)) + cc(2,j) * y'(xc(j)) + ... = yc(:,...,:,j).
+## @end ifnottex
+## @end group
+## @end example
+##
+## @seealso{interp1, unmkpp, ppval, spline, pchip, ppder, ppint, ppjumps}
+## @end deftypefn
+
+function pp = splinefit (x, y, breaks, varargin)
+  if (nargin > 3)
+    n = cellfun (@ischar, varargin, "uniformoutput", true);
+    varargin(n) = lower (varargin(n));
+    try
+      props = struct (varargin{:});
+    catch
+      print_usage ();
+    end_try_catch
+  else
+    props = struct ();
+  endif
+  fields = fieldnames (props);
+  for f = 1:numel (fields)
+    if (! any (strcmp (fields{f},
+                       {"periodic", "robust", "beta", "order", "constraints"})))
+      error ("splinefit:invalidproperty",
+             "unrecognized property '%s'", fields{f});
+    endif
+  endfor
+  args = {};
+  if (isfield (props, "periodic") && props.periodic)
+    args{end+1} = "p";
+  endif
+  if (isfield (props, "robust") && props.robust)
+    args{end+1} = "r";
+  endif
+  if (isfield (props, "beta"))
+    if (0 < props.beta && props.beta < 1)
+      args{end+1} = props.beta;
+    else
+      error ("splinefit:invalidbeta", "invalid beta parameter (0 < beta < 1)");
+    endif
+  endif
+  if (isfield (props, "order"))
+    if (props.order >= 0)
+      args{end+1} = props.order + 1;
+    else
+      error ("splinefit:invalidorder", "invalid order");
+    endif
+  endif
+  if (isfield (props, "constraints"))
+    args{end+1} = props.constraints;
+  endif
+  if (nargin < 3)
+    print_usage ();
+  elseif (! isnumeric (breaks) || ! isvector (breaks))
+    print_usage ();
+  endif
+  pp = __splinefit__ (x, y, breaks, args{:});
+endfunction
+
+
+%!demo
+%! % Noisy data
+%! x = linspace (0, 2*pi, 100);
+%! y = sin (x) + 0.1 * randn (size (x));
+%! % Breaks
+%! breaks = [0:5, 2*pi];
+%! % Fit a spline of order 5
+%! pp = splinefit (x, y, breaks, "order", 4);
+%! clf ()
+%! plot (x, y, "s", x, ppval (pp, x), "r", breaks, ppval (pp, breaks), "+r")
+%! xlabel ("Independent Variable")
+%! ylabel ("Dependent Variable")
+%! title ("Fit a piece-wise polynomial of order 4");
+%! legend ({"data", "fit", "breaks"})
+%! axis tight
+%! ylim auto
+
+%!demo
+%! % Noisy data
+%! x = linspace (0,2*pi, 100);
+%! y = sin (x) + 0.1 * randn (size (x));
+%! % Breaks
+%! breaks = [0:5, 2*pi];
+%! % Fit a spline of order 3 with periodic boundary conditions
+%! pp = splinefit (x, y, breaks, "order", 2, "periodic", true);
+%! clf ()
+%! plot (x, y, "s", x, ppval (pp, x), "r", breaks, ppval (pp, breaks), "+r")
+%! xlabel ("Independent Variable")
+%! ylabel ("Dependent Variable")
+%! title ("Fit a periodic piece-wise polynomial of order 2");
+%! legend ({"data", "fit", "breaks"})
+%! axis tight
+%! ylim auto
+
+%!demo
+%! % Noisy data
+%! x = linspace (0, 2*pi, 100);
+%! y = sin (x) + 0.1 * randn (size (x));
+%! % Breaks
+%! breaks = [0:5, 2*pi];
+%! % Constraints: y(0) = 0, y'(0) = 1 and y(3) + y"(3) = 0
+%! xc = [0 0 3];
+%! yc = [0 1 0];
+%! cc = [1 0 1; 0 1 0; 0 0 1];
+%! con = struct ("xc", xc, "yc", yc, "cc", cc);
+%! % Fit a cubic spline with 8 pieces and constraints
+%! pp = splinefit (x, y, 8, "constraints", con);
+%! clf ()
+%! plot (x, y, "s", x, ppval (pp, x), "r", breaks, ppval (pp, breaks), "+r")
+%! xlabel ("Independent Variable")
+%! ylabel ("Dependent Variable")
+%! title ("Fit a cubic spline with constraints")
+%! legend ({"data", "fit", "breaks"})
+%! axis tight
+%! ylim auto
+
+%!demo
+%! % Noisy data
+%! x = linspace (0, 2*pi, 100);
+%! y = sin (x) + 0.1 * randn (size (x));
+%! % Breaks
+%! breaks = [0:5, 2*pi];
+%! xc = [0 0 3];
+%! yc = [0 1 0];
+%! cc = [1 0 1; 0 1 0; 0 0 1];
+%! con = struct ("xc", xc, "yc", yc, "cc", cc);
+%! % Fit a spline of order 6 with constraints and periodicity
+%! pp = splinefit (x, y, breaks, "constraints", con, "order", 5, "periodic", true);
+%! clf ()
+%! plot (x, y, "s", x, ppval (pp, x), "r", breaks, ppval (pp, breaks), "+r")
+%! xlabel ("Independent Variable")
+%! ylabel ("Dependent Variable")
+%! title ("Fit a 5th order piece-wise periodic polynomial with constraints")
+%! legend ({"data", "fit", "breaks"})
+%! axis tight
+%! ylim auto
+
+%!shared xb, yb, x
+%! xb = 0:2:10;
+%! yb = 2*rand (size (xb)) - 1;
+%! x = 0:0.1:10;
+
+%!test
+%! y = interp1 (xb, yb, x, "linear");
+%! assert (ppval (splinefit (x, y, xb, "order", 1), x), y, 15 * eps ());
+%!test
+%! y = interp1 (xb, yb, x, "spline");
+%! assert (ppval (splinefit (x, y, xb, "order", 3), x), y, 15 * eps ());
+%!test
+%! y = interp1 (xb, yb, x, "spline");
+%! assert (ppval (splinefit (x, y, xb), x), y, 15 * eps ());
+
--- a/scripts/prefs/addpref.m
+++ b/scripts/prefs/addpref.m
@@ -45,7 +45,7 @@
         endif
       elseif (iscellstr (pref))
         if (size_equal (pref, val))
-          for i = 1:numel(pref)
+          for i = 1:numel (pref)
             if (isfield (group, pref{i}))
               error ("preference %s already exists in group %s",
                      pref{i}, group);
--- a/scripts/prefs/getpref.m
+++ b/scripts/prefs/getpref.m
@@ -69,7 +69,7 @@
       endif
     elseif (iscellstr (pref))
       if (nargin == 2 || size_equal (pref, default))
-        for i = 1:numel(pref)
+        for i = 1:numel (pref)
           if (isfield (grp, pref{i}))
             retval.(pref) = grp.(pref{i});
           elseif (nargin == 3)
--- a/scripts/prefs/private/prefsfile.m
+++ b/scripts/prefs/private/prefsfile.m
@@ -27,25 +27,6 @@
 
   retval = "~/.octave_prefs";
 
-  ## Transition users to new filename if necessary
-  ## FIXME: Delete before 3.6.0 release
-  oldname = tilde_expand ("~/.octave-prefs");
-  if (exist (oldname, "file"))
-    newname = tilde_expand (retval); 
-    if (exist (newname, "file"))
-      error (["Octave uses the file ~/.octave_prefs to store preferences.\n",...
-              "       The old file name was ~/.octave-prefs.\n",...
-              "       Both files exist."...
-              "  User must manually delete one of the files.\n"]);
-    endif
-    status = movefile (oldname, newname);
-    if (! status)
-      error (["Octave uses the file ~/.octave_prefs to store preferences.\n",
-             "        The old file name was ~/.octave-prefs.\n",
-             "        User must manually rename the old file to the new name.\n"]);
-    endif
-  endif
-
 endfunction
 
 %% Testing these functions will require some care to avoid wiping out
--- a/scripts/prefs/rmpref.m
+++ b/scripts/prefs/rmpref.m
@@ -17,14 +17,15 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {} rmpref (@var{group}, @var{pref})
+## @deftypefn  {Function File} {} rmpref (@var{group})
+## @deftypefnx {Function File} {} rmpref (@var{group}, @var{pref})
 ## Remove the named preference @var{pref} from the preference group
 ## @var{group}.
 ##
 ## The named preference group must be a character string.
 ##
-## The preference @var{pref} may be a character string or a cell array
-## of character strings.
+## The preference @var{pref} may be a character string or cell array
+## of strings.
 ##
 ## If @var{pref} is not specified, remove the preference group
 ## @var{group}.
@@ -37,25 +38,48 @@
 
 function retval = rmpref (group, pref)
 
-  prefs = loadprefs ();
+  if (nargin < 1 || nargin > 2)
+    print_usage ();
+  elseif (! ischar (group))
+    error ("rmpref: GROUP must be a string");
+  elseif (nargin == 2 && ! (ischar (pref) || iscellstr (pref)))
+    error ("rmpref: PREF must be a string or cell array of strings");
+  endif
 
   if (nargin == 1)
-    if (ischar (group))
-      retval = isfield (prefs, group);
+    if (ispref (group))
+      prefs = loadprefs ();
+      prefs = rmfield (prefs, group);
+      saveprefs (prefs);
     else
-      error ("expecting group to be a character array");
-    endif
-  elseif (nargin == 2)
-    grp = getpref (group, pref);
-    if (ischar (pref) || iscellstr (pref))
-      retval = isfield (grp, pref);
+      error ("rmpref: group <%s> does not exist", group);
     endif
   else
-    print_usage ();
+    valid = ispref (group, pref);
+    if (all (valid))
+      prefs = loadprefs ();
+      prefs.(group) = rmfield (prefs.(group), pref);
+      saveprefs (prefs);
+    else
+      if (! ispref (group))
+        error ("rmpref: group <%s> does not exist", group);
+      else
+        idx = find (! valid, 1); 
+        error ("rmpref: pref <%s> does not exist", (cellstr (pref)){idx} );
+      endif
+    endif
   endif
 
 endfunction
 
-%% Testing these functions will require some care to avoid wiping out
-%% existing (or creating unwanted) preferences for the user running the
-%% tests.
+
+## Testing these functions will require some care to avoid wiping out
+## existing (or creating unwanted) preferences for the user running the
+## tests.
+
+## Test input validation
+%!error rmpref ()
+%!error rmpref (1,2,3)
+%!error rmpref ({"__group1__"})
+%!error rmpref ("__group1__", 1)
+
--- a/scripts/prefs/setpref.m
+++ b/scripts/prefs/setpref.m
@@ -43,7 +43,7 @@
         prefs.(group).(pref) = val;
       elseif (iscellstr (pref))
         if (size_equal (pref, val))
-          for i = 1:numel(pref)
+          for i = 1:numel (pref)
             prefs.(group).(pref{i}) = val;
           endfor
         else
--- a/scripts/set/intersect.m
+++ b/scripts/set/intersect.m
@@ -75,7 +75,7 @@
       ib = jb(ic(ii+1) - len_a);        ## b(ib) == c
     endif
 
-    if (nargin == 2 && (size (b, 1) == 1 || size (a, 1) == 1))
+    if (nargin == 2 && (rows (b) == 1 || rows (a) == 1))
       c = c.';
     endif
   endif
@@ -87,29 +87,30 @@
 %!test
 %! a = [3 2 4 5 7 6 5 1 0 13 13];
 %! b = [3 5 12 1 1 7];
-%! [c,ia,ib] = intersect(a,b);
-%! assert(c,[1 3 5 7]);
-%! assert(ia,[8 1 7 5]);
-%! assert(ib,[5 1 2 6]);
-%! assert(a(ia),c);
-%! assert(b(ib),c);
+%! [c,ia,ib] = intersect (a, b);
+%! assert (c, [1 3 5 7]);
+%! assert (ia, [8 1 7 5]);
+%! assert (ib, [5 1 2 6]);
+%! assert (a(ia), c);
+%! assert (b(ib), c);
 %!test
 %! a = [1,1,2;1,4,5;2,1,7];
 %! b = [1,4,5;2,3,4;1,1,2;9,8,7];
-%! [c,ia,ib] = intersect(a,b,'rows');
-%! assert(c,[1,1,2;1,4,5]);
-%! assert(ia,[1;2]);
-%! assert(ib,[3;1]);
-%! assert(a(ia,:),c);
-%! assert(b(ib,:),c);
+%! [c,ia,ib] = intersect (a, b, "rows");
+%! assert (c, [1,1,2;1,4,5]);
+%! assert (ia, [1;2]);
+%! assert (ib, [3;1]);
+%! assert (a(ia,:), c);
+%! assert (b(ib,:), c);
 %!test
 %! a = [1 1 1 2 2 2];
 %! b = [1 2 3 4 5 6];
-%! c = intersect(a,b);
+%! c = intersect (a, b);
 %! assert(c, [1,2]);
 %!test
 %! a = [1 2 3 4; 5 6 7 8; 9 10 11 12];
-%! [b, ia, ib] = intersect(a, a, "rows");
-%! assert(b, a);
-%! assert(ia, [1:3]');
-%! assert(ib, [1:3]');
+%! [b, ia, ib] = intersect (a, a, "rows");
+%! assert (b, a);
+%! assert (ia, [1:3]');
+%! assert (ib, [1:3]');
+
--- a/scripts/set/ismember.m
+++ b/scripts/set/ismember.m
@@ -40,8 +40,8 @@
 ##
 ## @example
 ## @group
-## a = @{'abc'@};
-## s = @{'abc', 'def'@};
+## a = @{"abc"@};
+## s = @{"abc", "def"@};
 ## [tf, s_idx] = ismember (a, s)
 ##      @result{} tf = [1, 0]
 ##      @result{} s_idx = [1, 0]
@@ -56,7 +56,7 @@
 ## @group
 ## a = [1:3; 5:7; 4:6];
 ## s = [0:2; 1:3; 2:4; 3:5; 4:6];
-## [tf, s_idx] = ismember(a, s, "rows")
+## [tf, s_idx] = ismember (a, s, "rows")
 ##      @result{} tf = logical ([1; 0; 1])
 ##      @result{} s_idx = [2; 0; 5];
 ## @end group
@@ -133,29 +133,30 @@
 
 endfunction
 
-%!assert (ismember ({''}, {'abc', 'def'}), false);
-%!assert (ismember ('abc', {'abc', 'def'}), true);
-%!assert (isempty (ismember ([], [1, 2])), true);
-%!assert (isempty (ismember ({}, {'a', 'b'})), true);
-%!assert (ismember ('', {'abc', 'def'}), false);
-%!fail ('ismember ([], {1, 2})');
-%!fail ('ismember ({[]}, {1, 2})');
-%!fail ('ismember ({}, {1, 2})');
-%!fail ('ismember ({1}, {''1'', ''2''})');
-%!fail ('ismember (1, ''abc'')');
-%!fail ('ismember ({''1''}, {''1'', ''2''},''rows'')');
-%!fail ('ismember ([1 2 3], [5 4 3 1], ''rows'')');
-%!assert (ismember ({'foo', 'bar'}, {'foobar'}), logical ([0, 0]));
-%!assert (ismember ({'foo'}, {'foobar'}), false);
-%!assert (ismember ({'bar'}, {'foobar'}), false);
-%!assert (ismember ({'bar'}, {'foobar', 'bar'}), true);
-%!assert (ismember ({'foo', 'bar'}, {'foobar', 'bar'}), logical ([0, 1]));
-%!assert (ismember ({'xfb', 'f', 'b'}, {'fb', 'b'}), logical ([0, 0, 1]));
-%!assert (ismember ("1", "0123456789."), true);
+
+%!assert (ismember ({""}, {"abc", "def"}), false)
+%!assert (ismember ("abc", {"abc", "def"}), true)
+%!assert (isempty (ismember ([], [1, 2])), true)
+%!assert (isempty (ismember ({}, {'a', 'b'})), true)
+%!assert (ismember ("", {"abc", "def"}), false)
+%!fail ("ismember ([], {1, 2})")
+%!fail ("ismember ({[]}, {1, 2})")
+%!fail ("ismember ({}, {1, 2})")
+%!fail ("ismember ({1}, {'1', '2'})")
+%!fail ("ismember (1, 'abc')")
+%!fail ("ismember ({'1'}, {'1' '2'},'rows')")
+%!fail ("ismember ([1 2 3], [5 4 3 1], 'rows')")
+%!assert (ismember ({"foo", "bar"}, {"foobar"}), [false false])
+%!assert (ismember ({"foo"}, {"foobar"}), false)
+%!assert (ismember ({"bar"}, {"foobar"}), false)
+%!assert (ismember ({"bar"}, {"foobar", "bar"}), true)
+%!assert (ismember ({"foo", "bar"}, {"foobar", "bar"}), [false true])
+%!assert (ismember ({"xfb", "f", "b"}, {"fb", "b"}), [false false true])
+%!assert (ismember ("1", "0123456789."), true)
 
 %!test
 %! [result, a_idx] = ismember ([1, 2], []);
-%! assert (result, logical ([0, 0]))
+%! assert (result, [false false])
 %! assert (a_idx, [0, 0]);
 
 %!test
@@ -164,46 +165,52 @@
 %! assert (a_idx, []);
 
 %!test
-%! [result, a_idx] = ismember ({'a', 'b'}, '');
-%! assert (result, logical ([0, 0]))
+%! [result, a_idx] = ismember ({"a", "b"}, "");
+%! assert (result, [false false])
 %! assert (a_idx, [0, 0]);
 
 %!test
-%! [result, a_idx] = ismember ({'a', 'b'}, {});
-%! assert (result, logical ([0, 0]))
+%! [result, a_idx] = ismember ({"a", "b"}, {});
+%! assert (result, [false false])
 %! assert (a_idx, [0, 0]);
 
 %!test
-%! [result, a_idx] = ismember ('', {'a', 'b'});
+%! [result, a_idx] = ismember ("", {"a", "b"});
 %! assert (result, false)
 %! assert (a_idx, 0);
 
 %!test
-%! [result, a_idx] = ismember ({}, {'a', 'b'});
+%! [result, a_idx] = ismember ({}, {"a", "b"});
 %! assert (result, logical ([]))
 %! assert (a_idx, []);
 
 %!test
-%! [result, a_idx] = ismember([1 2 3 4 5], [3]);
-%! assert (all (result == logical ([0 0 1 0 0])) && all (a_idx == [0 0 1 0 0]));
+%! [result, a_idx] = ismember ([1 2 3 4 5], [3]);
+%! assert (result, logical ([0 0 1 0 0]))
+%! assert (a_idx , [0 0 1 0 0]);
 
 %!test
-%! [result, a_idx] = ismember([1 6], [1 2 3 4 5 1 6 1]);
-%! assert (all (result == logical ([1 1])) && a_idx(2) == 7);
+%! [result, a_idx] = ismember ([1 6], [1 2 3 4 5 1 6 1]);
+%! assert (result, [true true]);
+%! assert (a_idx(2), 7);
 
 %!test
 %! [result, a_idx] = ismember ([3,10,1], [0,1,2,3,4,5,6,7,8,9]);
-%! assert (all (result == logical ([1, 0, 1])) && all (a_idx == [4, 0, 2]));
+%! assert (result, [true false true]);
+%! assert (a_idx, [4, 0, 2]);
 
 %!test
 %! [result, a_idx] = ismember ("1.1", "0123456789.1");
-%! assert (all (result == logical ([1, 1, 1])) && all (a_idx == [12, 11, 12]));
+%! assert (result, [true true true]);
+%! assert (a_idx, [12, 11, 12]);
 
 %!test
-%! [result, a_idx] = ismember([1:3; 5:7; 4:6], [0:2; 1:3; 2:4; 3:5; 4:6], 'rows');
-%! assert (all (result == logical ([1; 0; 1])) && all (a_idx == [2; 0; 5]));
+%! [result, a_idx] = ismember ([1:3; 5:7; 4:6], [0:2; 1:3; 2:4; 3:5; 4:6], "rows");
+%! assert (result, [true; false; true]);
+%! assert (a_idx, [2; 0; 5]);
 
 %!test
-%! [result, a_idx] = ismember([1.1,1.2,1.3; 2.1,2.2,2.3; 10,11,12], [1.1,1.2,1.3; 10,11,12; 2.12,2.22,2.32], 'rows');
-%! assert (all (result == logical ([1; 0; 1])) && all (a_idx == [1; 0; 2]));
+%! [result, a_idx] = ismember ([1.1,1.2,1.3; 2.1,2.2,2.3; 10,11,12], [1.1,1.2,1.3; 10,11,12; 2.12,2.22,2.32], "rows");
+%! assert (result, [true; false; true]);
+%! assert (a_idx, [1; 0; 2]);
 
--- a/scripts/set/powerset.m
+++ b/scripts/set/powerset.m
@@ -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,7 +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/set/setdiff.m
+++ b/scripts/set/setdiff.m
@@ -82,7 +82,7 @@
         i(idx(dups)) = [];
       endif
       ## Reshape if necessary.
-      if (size (c, 1) != 1 && size (b, 1) == 1)
+      if (rows (c) != 1 && rows (b) == 1)
         c = c.';
       endif
     endif
@@ -90,16 +90,18 @@
 
 endfunction
 
-%!assert(setdiff(["bb";"zz";"bb";"zz"],["bb";"cc";"bb"],"rows"), "zz")
-%!assert(setdiff(["b";"z";"b";"z"],["b";"c";"b"],"rows"), "z")
-%!assert(setdiff(["b";"z";"b";"z"],["b";"c";"b"]), "z")
-%!assert(setdiff([1, 1; 2, 2; 3, 3; 4, 4], [1, 1; 2, 2; 4, 4], "rows"), [3 3])
-%!assert(setdiff([1; 2; 3; 4], [1; 2; 4], "rows"), 3)
-%!assert(setdiff([1, 2; 3, 4], [1, 2; 3, 6], "rows"), [3, 4])
-%!assert(setdiff({"one","two";"three","four"},{"one","two";"three","six"}), {"four"})
+
+%!assert (setdiff (["bb";"zz";"bb";"zz"], ["bb";"cc";"bb"], "rows"), "zz")
+%!assert (setdiff (["b";"z";"b";"z"], ["b";"c";"b"], "rows"), "z")
+%!assert (setdiff (["b";"z";"b";"z"], ["b";"c";"b"]), "z")
+%!assert (setdiff ([1, 1; 2, 2; 3, 3; 4, 4], [1, 1; 2, 2; 4, 4], "rows"), [3 3])
+%!assert (setdiff ([1; 2; 3; 4], [1; 2; 4], "rows"), 3)
+%!assert (setdiff ([1, 2; 3, 4], [1, 2; 3, 6], "rows"), [3, 4])
+%!assert (setdiff ({"one","two";"three","four"}, {"one","two";"three","six"}), {"four"})
 
 %!test
-%! a = [3, 1, 4, 1, 5]; b = [1, 2, 3, 4];
+%! a = [3, 1, 4, 1, 5];  b = [1, 2, 3, 4];
 %! [y, i] = setdiff (a, b.');
-%! assert(y, [5]);
-%! assert(y, a(i));
+%! assert (y, [5]);
+%! assert (y, a(i));
+
--- a/scripts/set/setxor.m
+++ b/scripts/set/setxor.m
@@ -19,7 +19,7 @@
 
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {} setxor (@var{a}, @var{b})
-## @deftypefnx {Function File} {} setxor (@var{a}, @var{b}, 'rows')
+## @deftypefnx {Function File} {} setxor (@var{a}, @var{b}, "rows")
 ## @deftypefnx {Function File} {[@var{c}, @var{ia}, @var{ib}] =} setxor (@var{a}, @var{b})
 ##
 ## Return the elements exclusive to @var{a} or @var{b}, sorted in ascending
@@ -79,7 +79,7 @@
         c([idx, idx+1]) = [];
         i([idx, idx+1]) = [];
       endif
-      if (size (a, 1) == 1 || size (b, 1) == 1)
+      if (rows (a) == 1 || rows (b) == 1)
         c = c.';
       endif
     endif
@@ -91,11 +91,12 @@
 
 endfunction
 
-%!assert(setxor([1,2,3],[2,3,4]),[1,4])
-%!assert(setxor({'a'}, {'a', 'b'}), {'b'});
+
+%!assert (setxor ([1,2,3],[2,3,4]),[1,4])
+%!assert (setxor ({'a'}, {'a', 'b'}), {'b'})
 %!test
-%! a = [3, 1, 4, 1, 5]; b = [1, 2, 3, 4];
+%! a = [3, 1, 4, 1, 5];  b = [1, 2, 3, 4];
 %! [y, ia, ib] = setxor (a, b.');
-%! assert(y, [2, 5]);
-%! assert(y, sort([a(ia), b(ib)]));
+%! assert (y, [2, 5]);
+%! assert (y, sort ([a(ia), b(ib)]));
 
--- a/scripts/set/union.m
+++ b/scripts/set/union.m
@@ -20,8 +20,10 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {} union (@var{a}, @var{b})
 ## @deftypefnx {Function File} {} union (@var{a}, @var{b}, "rows")
+## @deftypefnx {Function File} {[@var{c}, @var{ia}, @var{ib}] =} union (@var{a}, @var{b})
+##
 ## Return the set of elements that are in either of the sets @var{a} and
-## @var{b}.  @var{a}, @var{b} may be cell arrays of string(s).
+## @var{b}.  @var{a}, @var{b} may be cell arrays of strings.
 ## For example:
 ##
 ## @example
@@ -31,8 +33,8 @@
 ## @end group
 ## @end example
 ##
-## If the optional third input argument is the string "rows" each row of
-## the matrices @var{a} and @var{b} will be considered an element of sets.
+## If the optional third input argument is the string "rows" then each row of
+## the matrices @var{a} and @var{b} will be considered as a single set element.
 ## For example:
 ##
 ## @example
@@ -44,10 +46,8 @@
 ## @end group
 ## @end example
 ##
-## @deftypefnx {Function File} {[@var{c}, @var{ia}, @var{ib}] =} union (@var{a}, @var{b})
-##
-## Return index vectors @var{ia} and @var{ib} such that @code{a(ia)} and
-## @code{b(ib)} are disjoint sets whose union is @var{c}.
+## The optional outputs @var{ia} and @var{ib} are index vectors such that
+## @code{a(ia)} and @code{b(ib)} are disjoint sets whose union is @var{c}.
 ##
 ## @seealso{intersect, setdiff, unique}
 ## @end deftypefn
@@ -65,7 +65,7 @@
   if (nargin == 2)
     y = [a(:); b(:)];
     na = numel (a); nb = numel (b);
-    if (size (a, 1) == 1 || size (b, 1) == 1)
+    if (rows (a) == 1 || rows (b) == 1)
       y = y.';
     endif
   else
@@ -83,18 +83,17 @@
 
 endfunction
 
-%!assert(all (all (union ([1, 2, 4], [2, 3, 5]) == [1, 2, 3, 4, 5])));
 
-%!assert(all (all (union ([1; 2; 4], [2, 3, 5]) == [1, 2, 3, 4, 5])));
-
-%!assert(all (all (union ([1, 2, 3], [5; 7; 9]) == [1, 2, 3, 5, 7, 9])));
-
-%!error union (1);
-
-%!error union (1, 2, 3);
+%!assert (union ([1, 2, 4], [2, 3, 5]), [1, 2, 3, 4, 5]);
+%!assert (union ([1; 2; 4], [2, 3, 5]), [1, 2, 3, 4, 5]);
+%!assert (union ([1, 2, 3], [5; 7; 9]), [1, 2, 3, 5, 7, 9]);
 
 %!test
-%! a = [3, 1, 4, 1, 5]; b = [1, 2, 3, 4];
+%! a = [3, 1, 4, 1, 5];  b = [1, 2, 3, 4];
 %! [y, ia, ib] = union (a, b.');
-%! assert(y, [1, 2, 3, 4, 5]);
-%! assert(y, sort([a(ia), b(ib)]));
+%! assert (y, [1, 2, 3, 4, 5]);
+%! assert (y, sort ([a(ia), b(ib)]));
+
+%!error union (1)
+%!error union (1, 2, 3)
+
--- a/scripts/set/unique.m
+++ b/scripts/set/unique.m
@@ -51,14 +51,17 @@
   if (nargin > 1)
     ## parse options
     if (iscellstr (varargin))
-      varargin = unique (varargin);
-      optfirst = strmatch ("first", varargin, "exact") > 0;
-      optlast = strmatch ("last", varargin, "exact") > 0;
-      optrows = strmatch ("rows", varargin, "exact") > 0;
+      optfirst = strcmp ("first", varargin);
+      optlast  = strcmp ("last", varargin);
+      optrows  = strcmp ("rows", varargin);
+      if (! all (optfirst | optlast | optrows))
+        error ("unique: invalid option");
+      endif
+      optfirst = any (optfirst);
+      optlast  = any (optlast);
+      optrows  = any (optrows);
       if (optfirst && optlast)
         error ('unique: cannot specify both "last" and "first"');
-      elseif (optfirst + optlast + optrows != nargin-1)
-        error ("unique: invalid option");
       endif
     else
       error ("unique: options must be strings");
@@ -163,52 +166,58 @@
 
 endfunction
 
-%!assert(unique([1 1 2; 1 2 1; 1 1 2]),[1;2])
-%!assert(unique([1 1 2; 1 0 1; 1 1 2],'rows'),[1 0 1; 1 1 2])
-%!assert(unique([]),[])
-%!assert(unique([1]),[1])
-%!assert(unique([1 2]),[1 2])
-%!assert(unique([1;2]),[1;2])
-%!assert(unique([1,NaN,Inf,NaN,Inf]),[1,Inf,NaN,NaN])
-%!assert(unique({'Foo','Bar','Foo'}),{'Bar','Foo'})
-%!assert(unique({'Foo','Bar','FooBar'}'),{'Bar','Foo','FooBar'}')
-%!assert(unique(zeros(1,0)), zeros(0,1))
-%!assert(unique(zeros(1,0), 'rows'), zeros(1,0))
-%!assert(unique(cell(1,0)), cell(0,1))
-%!assert(unique({}), {})
-%!assert(unique([1,2,2,3,2,4], 'rows'), [1,2,2,3,2,4])
-%!assert(unique([1,2,2,3,2,4]), [1,2,3,4])
-%!assert(unique([1,2,2,3,2,4]', 'rows'), [1,2,3,4]')
-%!assert(unique(sparse([2,0;2,0])), [0,2]')
-%!assert(unique(sparse([1,2;2,3])), [1,2,3]')
-%!assert(unique([1,2,2,3,2,4]', 'rows'), [1,2,3,4]')
-%!assert(unique(single([1,2,2,3,2,4]), 'rows'), single([1,2,2,3,2,4]))
-%!assert(unique(single([1,2,2,3,2,4])), single([1,2,3,4]))
-%!assert(unique(single([1,2,2,3,2,4]'), 'rows'), single([1,2,3,4]'))
-%!assert(unique(uint8([1,2,2,3,2,4]), 'rows'), uint8([1,2,2,3,2,4]))
-%!assert(unique(uint8([1,2,2,3,2,4])), uint8([1,2,3,4]))
-%!assert(unique(uint8([1,2,2,3,2,4]'), 'rows'), uint8([1,2,3,4]'))
+
+%!assert (unique ([1 1 2; 1 2 1; 1 1 2]),[1;2])
+%!assert (unique ([1 1 2; 1 0 1; 1 1 2],"rows"),[1 0 1; 1 1 2])
+%!assert (unique ([]),[])
+%!assert (unique ([1]),[1])
+%!assert (unique ([1 2]),[1 2])
+%!assert (unique ([1;2]),[1;2])
+%!assert (unique ([1,NaN,Inf,NaN,Inf]),[1,Inf,NaN,NaN])
+%!assert (unique ({"Foo","Bar","Foo"}),{"Bar","Foo"})
+%!assert (unique ({"Foo","Bar","FooBar"}'),{"Bar","Foo","FooBar"}')
+%!assert (unique (zeros (1,0)), zeros (0,1))
+%!assert (unique (zeros (1,0), "rows"), zeros (1,0))
+%!assert (unique (cell (1,0)), cell (0,1))
+%!assert (unique ({}), {})
+%!assert (unique ([1,2,2,3,2,4], "rows"), [1,2,2,3,2,4])
+%!assert (unique ([1,2,2,3,2,4]), [1,2,3,4])
+%!assert (unique ([1,2,2,3,2,4]', "rows"), [1,2,3,4]')
+%!assert (unique (sparse ([2,0;2,0])), [0,2]')
+%!assert (unique (sparse ([1,2;2,3])), [1,2,3]')
+%!assert (unique ([1,2,2,3,2,4]', "rows"), [1,2,3,4]')
+%!assert (unique (single ([1,2,2,3,2,4]), "rows"), single ([1,2,2,3,2,4]))
+%!assert (unique (single ([1,2,2,3,2,4])), single ([1,2,3,4]))
+%!assert (unique (single ([1,2,2,3,2,4]'), "rows"), single ([1,2,3,4]'))
+%!assert (unique (uint8 ([1,2,2,3,2,4]), "rows"), uint8 ([1,2,2,3,2,4]))
+%!assert (unique (uint8 ([1,2,2,3,2,4])), uint8 ([1,2,3,4]))
+%!assert (unique (uint8 ([1,2,2,3,2,4]'), "rows"), uint8 ([1,2,3,4]'))
 %!test
-%! [a,i,j] = unique([1,1,2,3,3,3,4]);
-%! assert(a,[1,2,3,4])
-%! assert(i,[2,3,6,7])
-%! assert(j,[1,1,2,3,3,3,4])
+%! [a,i,j] = unique ([1,1,2,3,3,3,4]);
+%! assert (a, [1,2,3,4]);
+%! assert (i, [2,3,6,7]);
+%! assert (j, [1,1,2,3,3,3,4]);
 %!
 %!test
-%! [a,i,j] = unique([1,1,2,3,3,3,4]','first');
-%! assert(a,[1,2,3,4]')
-%! assert(i,[1,3,4,7]')
-%! assert(j,[1,1,2,3,3,3,4]')
+%! [a,i,j] = unique ([1,1,2,3,3,3,4]', "first");
+%! assert (a, [1,2,3,4]');
+%! assert (i, [1,3,4,7]');
+%! assert (j, [1,1,2,3,3,3,4]');
 %!
 %!test
-%! [a,i,j] = unique({'z'; 'z'; 'z'});
-%! assert(a,{'z'})
-%! assert(i,[3]')
-%! assert(j,[1,1,1]')
+%! [a,i,j] = unique ({"z"; "z"; "z"});
+%! assert (a, {"z"});
+%! assert (i, [3]');
+%! assert (j, [1;1;1]);
 %!
 %!test
-%! A=[1,2,3;1,2,3];
-%! [a,i,j] = unique(A,'rows');
-%! assert(a,[1,2,3])
-%! assert(A(i,:),a)
-%! assert(a(j,:),A)
+%! A = [1,2,3;1,2,3];
+%! [a,i,j] = unique (A, "rows");
+%! assert (a, [1,2,3]);
+%! assert (A(i,:), a);
+%! assert (a(j,:), A);
+
+%!error unique({"a", "b", "c"}, "UnknownOption")
+%!error unique({"a", "b", "c"}, "UnknownOption1", "UnknownOption2")
+%!error unique({"a", "b", "c"}, "rows", "UnknownOption2")
+%!error unique({"a", "b", "c"}, "UnknownOption1", "last")
--- a/scripts/signal/arch_fit.m
+++ b/scripts/signal/arch_fit.m
@@ -109,7 +109,7 @@
     esq = e .^ 2;
     Z   = autoreg_matrix (esq, p);
     h   = Z * a;
-    f   = esq ./ h - ones(T,1);
+    f   = esq ./ h - ones (T,1);
     Z_tilde = Z ./ (h * ones (1, p+1));
     delta_a = inv (Z_tilde' * Z_tilde) * Z_tilde' * f;
     a   = a + gamma * delta_a;
--- a/scripts/signal/arch_rnd.m
+++ b/scripts/signal/arch_rnd.m
@@ -71,7 +71,7 @@
     b  = [b, 0];
     lb = lb + 1;
   endif
-  m  = max([la, lb]);
+  m  = max ([la, lb]);
 
   e  = zeros (t, 1);
   h  = zeros (t, 1);
--- a/scripts/signal/arch_test.m
+++ b/scripts/signal/arch_test.m
@@ -80,9 +80,9 @@
   if ((rx == 1) && (cx == 1))
     x = autoreg_matrix (y, x);
   elseif (! (rx == T))
-    error ("arch_test: either rows(X) == length(Y), or X is a scalar");
+    error ("arch_test: either rows (X) == length (Y), or X is a scalar");
   endif
-  if (! (isscalar(p) && (rem(p, 1) == 0) && (p > 0)))
+  if (! (isscalar (p) && (rem (p, 1) == 0) && (p > 0)))
     error ("arch_test: P must be a positive integer");
   endif
 
--- a/scripts/signal/autoreg_matrix.m
+++ b/scripts/signal/autoreg_matrix.m
@@ -50,13 +50,14 @@
 
 
 %!test
-%! K=4;
-%! A = zeros(1,K+1);
+%! K = 4;
+%! A = zeros (1,K+1);
 %! A(1) = 1;
-%! B = eye(K+1);
+%! B = eye (K+1);
 %! B(:,1) = 1;
-%! assert (autoreg_matrix(A,K),B);
+%! assert (autoreg_matrix (A,K), B);
 
-%!error autoreg_matrix()
-%!error autoreg_matrix(1)
-%!error autoreg_matrix(ones(4,1),5)
+%!error autoreg_matrix ()
+%!error autoreg_matrix (1)
+%!error autoreg_matrix (ones (4,1), 5)
+
--- a/scripts/signal/bartlett.m
+++ b/scripts/signal/bartlett.m
@@ -48,16 +48,18 @@
 
 endfunction
 
-%!assert (bartlett (1), 1);
-%!assert (bartlett (2), zeros (2,1));
-%!assert (bartlett (16), fliplr (bartlett (16)));
-%!assert (bartlett (15), fliplr (bartlett (15)));
+
+%!assert (bartlett (1), 1)
+%!assert (bartlett (2), zeros (2,1))
+%!assert (bartlett (16), fliplr (bartlett (16)))
+%!assert (bartlett (15), fliplr (bartlett (15)))
 %!test
 %! N = 9;
 %! A = bartlett (N);
-%! assert (A (ceil (N/2)), 1);
+%! assert (A(ceil (N/2)), 1);
 
-%!error bartlett ();
-%!error bartlett (0.5);
-%!error bartlett (-1);
-%!error bartlett (ones(1,4));
+%!error bartlett ()
+%!error bartlett (0.5)
+%!error bartlett (-1)
+%!error bartlett (ones (1,4))
+
--- a/scripts/signal/blackman.m
+++ b/scripts/signal/blackman.m
@@ -47,17 +47,19 @@
 
 endfunction
 
-%!assert (blackman (1), 1);
-%!assert (blackman (2), zeros(2,1), 1e-6);
-%!assert (blackman (16), fliplr (blackman (16)));
-%!assert (blackman (15), fliplr (blackman (15)));
+
+%!assert (blackman (1), 1)
+%!assert (blackman (2), zeros (2,1), 1e-6)
+%!assert (blackman (16), fliplr (blackman (16)))
+%!assert (blackman (15), fliplr (blackman (15)))
 %!test
 %! N = 9;
 %! A = blackman (N);
 %! assert (A (ceil (N/2)), 1, 1e-6);
 %! assert ([A(1), A(length (A))], zeros (1, 2), 1e-6);
 
-%!error blackman ();
-%!error blackman (0.5);
-%!error blackman (-1);
-%!error blackman (ones(1,4));
+%!error blackman ()
+%!error blackman (0.5)
+%!error blackman (-1)
+%!error blackman (ones (1,4))
+
--- a/scripts/signal/detrend.m
+++ b/scripts/signal/detrend.m
@@ -67,23 +67,24 @@
 
 endfunction
 
-%!test
-%! N=32;
-%! x = (0:1:N-1)/N + 2;
-%! y = detrend(x);
-%! assert(all (all (abs (y) < 20*eps)));
 
 %!test
-%! N=32;
+%! N = 32;
+%! x = (0:1:N-1)/N + 2;
+%! y = detrend (x);
+%! assert (abs (y(:)) < 20*eps);
+
+%!test
+%! N = 32;
 %! t = (0:1:N-1)/N;
 %! x = t .* t + 2;
-%! y = detrend(x,2);
-%! assert(all (all (abs (y) < 30*eps)));
+%! y = detrend (x,2);
+%! assert (abs (y(:)) < 30*eps);
 
 %!test
-%! N=32;
+%! N = 32;
 %! t = (0:1:N-1)/N;
 %! x = [t;4*t-3]';
-%! y = detrend(x);
-%! assert(all (all (abs (y) < 20*eps)));
+%! y = detrend (x);
+%! assert (abs (y(:)) < 20*eps);
 
--- a/scripts/signal/diffpara.m
+++ b/scripts/signal/diffpara.m
@@ -49,7 +49,7 @@
       k = 1;
       x = reshape (x, n, 1);
     else
-      [n, k] = size(x);
+      [n, k] = size (x);
     endif
     if (nargin == 1)
       a = 0.5 * sqrt (n);
--- a/scripts/signal/fftconv.m
+++ b/scripts/signal/fftconv.m
@@ -67,8 +67,8 @@
 
 %% FIXME: Borrow tests from conv.m.  May need a tolerance on the assert comparison
 %!test
-%!  x = ones(3,1);
-%!  y = ones(1,3);
+%!  x = ones (3,1);
+%!  y = ones (1,3);
 %!  b = 2;
 %!  c = 3;
 %!  assert (fftconv (x, x), [1; 2; 3; 2; 1], 5*eps);
@@ -84,23 +84,24 @@
 %!test
 %!  a = 1:10;
 %!  b = 1:3;
-%!  assert (size(conv(a,b)), [1, numel(a)+numel(b)-1])
-%!  assert (size(conv(b,a)), [1, numel(a)+numel(b)-1])
+%!  assert (size (conv (a,b)), [1, numel(a)+numel(b)-1])
+%!  assert (size (conv (b,a)), [1, numel(a)+numel(b)-1])
 
 %!  a = (1:10).';
 %!  b = 1:3;
-%!  assert (size(conv(a,b)), [numel(a)+numel(b)-1, 1])
-%!  assert (size(conv(b,a)), [numel(a)+numel(b)-1, 1])
+%!  assert (size (conv (a,b)), [numel(a)+numel(b)-1, 1])
+%!  assert (size (conv (b,a)), [numel(a)+numel(b)-1, 1])
 
 %!test
 %!  a = 1:10;
 %!  b = (1:3).';
-%!  assert (size(conv(a,b)), [1, numel(a)+numel(b)-1])
-%!  assert (size(conv(b,a)), [1, numel(a)+numel(b)-1])
+%!  assert (size (conv (a,b)), [1, numel(a)+numel(b)-1])
+%!  assert (size (conv (b,a)), [1, numel(a)+numel(b)-1])
 
 %% Test input validation
-%!error fftconv (1);
-%!error fftconv (1,2,3,4);
-%!error fftconv ([1, 2; 3, 4], 3);
-%!error fftconv (2, []);
-%!error fftconv ([1,1], [2,2] , [3, 4]);
+%!error fftconv (1)
+%!error fftconv (1,2,3,4)
+%!error fftconv ([1, 2; 3, 4], 3)
+%!error fftconv (2, [])
+%!error fftconv ([1,1], [2,2] , [3, 4])
+
--- a/scripts/signal/fftfilt.m
+++ b/scripts/signal/fftfilt.m
@@ -94,53 +94,91 @@
   endif
 
   y = y(1:r_x, :);
-  if (transpose)
-    y = y.';
+
+  ## Final cleanups:
+
+  ## - If both b and x are real, y should be real.
+  ## - If b is real and x is imaginary, y should be imaginary.
+  ## - If b is imaginary and x is real, y should be imaginary.
+  ## - If both b and x are imaginary, y should be real.
+  xisreal = all (imag (x) == 0);
+  xisimag = all (real (x) == 0);
+
+  if (all (imag (b) == 0))
+    y (:,xisreal) = real (y (:,xisreal));
+    y (:,xisimag) = complex (real (y (:,xisimag)) * 0, imag (y (:,xisimag)));
+  elseif (all (real (b) == 0))
+    y (:,xisreal) = complex (real (y (:,xisreal)) * 0, imag (y (:,xisreal)));
+    y (:,xisimag) = real (y (:,xisimag));
   endif
 
-  ## Final cleanups: If both x and b are real, y should be real.
-  ## If both x and b are integer, y should be integer.
+  ## - If both x and b are integer in both real and imaginary
+  ##   components, y should be integer.
+  if (! any (b - fix (b)))
+    idx = find (! any (x - fix (x)));
+    y (:, idx) = round (y (:, idx));
+  endif
 
-  if (isreal (b) && isreal (x))
-    y = real (y);
-  endif
-  if (! any (b - fix (b)))
-    idx = !any (x - fix (x));
-    y(:, idx) = round (y(:, idx));
+  ## Transpose after cleanup, otherwise rounding fails.
+  if (transpose)
+    y = y.';
   endif
 
 endfunction
 
 
 %!shared b, x, r
+
 %!test
-%!  b = [1 1];
-%!  x = [1, zeros(1,9)];
-%!  assert(fftfilt(b,  x  ), [1 1 0 0 0 0 0 0 0 0]  , eps);
-%!  assert(fftfilt(b,  x.'), [1 1 0 0 0 0 0 0 0 0].', eps);
-%!  assert(fftfilt(b.',x  ), [1 1 0 0 0 0 0 0 0 0]  , eps);
-%!  assert(fftfilt(b.',x.'), [1 1 0 0 0 0 0 0 0 0].', eps);
+%! b = [1 1];
+%! x = [1, zeros(1,9)];
+%! assert (fftfilt (b,  x  ), [1 1 0 0 0 0 0 0 0 0]  );
+%! assert (fftfilt (b,  x.'), [1 1 0 0 0 0 0 0 0 0].');
+%! assert (fftfilt (b.',x  ), [1 1 0 0 0 0 0 0 0 0]  );
+%! assert (fftfilt (b.',x.'), [1 1 0 0 0 0 0 0 0 0].');
+%! assert (fftfilt (b,  [x.' x.']), [1 1 0 0 0 0 0 0 0 0].'*[1 1]);
+%! assert (fftfilt (b,  [x.'+eps x.']) == [1 1 0 0 0 0 0 0 0 0].'*[1 1], [false(10, 1) true(10, 1)]);
+
+%!test
+%! r = sqrt (1/2) * (1+i);
+%! b = b*r;
+%! assert (fftfilt (b, x  ), r*[1 1 0 0 0 0 0 0 0 0]  , eps  );
+%! assert (fftfilt (b, r*x), r*r*[1 1 0 0 0 0 0 0 0 0], 2*eps);
+%! assert (fftfilt (b, x.'), r*[1 1 0 0 0 0 0 0 0 0].', eps  );
 
 %!test
-%!  r = sqrt(1/2) * (1+i);
-%!  b = b*r;
-%!  assert(fftfilt(b, x  ), r*[1 1 0 0 0 0 0 0 0 0]  , eps);
-%!  assert(fftfilt(b, r*x), r*r*[1 1 0 0 0 0 0 0 0 0], eps);
-%!  assert(fftfilt(b, x.'), r*[1 1 0 0 0 0 0 0 0 0].', eps);
+%! b  = [1 1];
+%! x  = zeros (10,3); x(1,1)=-1; x(1,2)=1;
+%! y0 = zeros (10,3); y0(1:2,1)=-1; y0(1:2,2)=1;
+%! y  = fftfilt (b, x);
+%! assert (y0, y);
+%! y  = fftfilt (b*i, x);
+%! assert (y0*i, y);
+%! y  = fftfilt (b, x*i);
+%! assert (y0*i, y);
+%! y  = fftfilt (b*i, x*i);
+%! assert (-y0, y);
+%! x  = rand (10, 1);
+%! y  = fftfilt (b, [x x*i]);
+%! assert (true, isreal (y(:,1)));
+%! assert (false, any (real (y(:,2))));
 
 %!test
-%!  b = [1 1];
-%!  x = zeros (10,3); x(1,1)=-1; x(1,2)=1;
-%!  y0 = zeros (10,3); y0(1:2,1)=-1; y0(1:2,2)=1;
-%!  y = fftfilt (b, x);
-%!  assert (y,y0);
+%! b  = rand (10, 1);
+%! x  = rand (10, 1);
+%! y0 = filter (b, 1, x);
+%! y  = fftfilt (b, x);
+%! assert (y0, y, 16*eps);
+%! y0 = filter (b*i, 1, x*i);
+%! y  = fftfilt (b*i, x*i);
+%! assert (y0, y, 16*eps);
 
 %!test
-%!  b  = rand (10, 1);
-%!  x  = rand (10, 1);
-%!  y0 = filter (b, 1, x);
-%!  y  = filter (b, 1, x);
-%!  assert (y, y0);
+%! b  = rand (10, 1) + i*rand (10, 1);
+%! x  = rand (10, 1) + i*rand (10, 1);
+%! y0 = filter (b, 1, x);
+%! y  = fftfilt (b, x);
+%! assert (y0, y, 55*eps);
 
 %% Test input validation
 %!error fftfilt (1)
--- a/scripts/signal/fftshift.m
+++ b/scripts/signal/fftshift.m
@@ -87,45 +87,45 @@
 %!test
 %!  x = [0:7];
 %!  y = fftshift (x);
-%!  assert(y, [4 5 6 7 0 1 2 3]);
-%!  assert(fftshift (y), x);
+%!  assert (y, [4 5 6 7 0 1 2 3]);
+%!  assert (fftshift (y), x);
 
 %!test
 %!  x = [0:6];
 %!  y = fftshift (x);
-%!  assert(y, [4 5 6 0 1 2 3]);
-%!  assert(fftshift (y), [1 2 3 4 5 6 0]);
+%!  assert (y, [4 5 6 0 1 2 3]);
+%!  assert (fftshift (y), [1 2 3 4 5 6 0]);
 
 %!test
 %!  x = [0:7]';
 %!  y = fftshift (x);
-%!  assert(y, [4;5;6;7;0;1;2;3]);
-%!  assert(fftshift (y), x);
+%!  assert (y, [4;5;6;7;0;1;2;3]);
+%!  assert (fftshift (y), x);
 
 %!test
 %!  x = [0:6]';
 %!  y = fftshift (x);
-%!  assert(y, [4;5;6;0;1;2;3]);
-%!  assert(fftshift (y), [1;2;3;4;5;6;0]);
+%!  assert (y, [4;5;6;0;1;2;3]);
+%!  assert (fftshift (y), [1;2;3;4;5;6;0]);
 
 %!test
 %!  x = [0:3];
 %!  x = [x;2*x;3*x+1;4*x+1];
 %!  y = fftshift (x);
-%!  assert(y, [[7 10 1 4];[9 13 1 5];[2 3 0 1];[4 6 0 2]]);
-%!  assert(fftshift (y), x);
+%!  assert (y, [[7 10 1 4];[9 13 1 5];[2 3 0 1];[4 6 0 2]]);
+%!  assert (fftshift (y), x);
 
 %!test
 %!  x = [0:3];
 %!  x = [x;2*x;3*x+1;4*x+1];
 %!  y = fftshift (x,1);
-%!  assert(y, [[1 4 7 10];[1 5 9 13];[0 1 2 3];[0 2 4 6]]);
-%!  assert(fftshift (y,1), x);
+%!  assert (y, [[1 4 7 10];[1 5 9 13];[0 1 2 3];[0 2 4 6]]);
+%!  assert (fftshift (y,1), x);
 
 %!test
 %!  x = [0:3];
 %!  x = [x;2*x;3*x+1;4*x+1];
 %!  y = fftshift (x,2);
-%!  assert(y, [[2 3 0 1];[4 6 0 2];[7 10 1 4];[9 13 1 5]]);
-%!  assert(fftshift (y,2), x);
+%!  assert (y, [[2 3 0 1];[4 6 0 2];[7 10 1 4];[9 13 1 5]]);
+%!  assert (fftshift (y,2), x);
 
--- a/scripts/signal/filter2.m
+++ b/scripts/signal/filter2.m
@@ -24,13 +24,13 @@
 ## Possible values are:
 ##
 ## @table @asis
-## @item 'full'
+## @item "full"
 ## pad @var{x} with zeros on all sides before filtering.
 ##
-## @item 'same'
+## @item "same"
 ## unpadded @var{x} (default)
 ##
-## @item 'valid'
+## @item "valid"
 ## trim @var{x} after filtering so edge effects are no included.
 ## @end table
 ##
@@ -52,7 +52,7 @@
     shape = "same";
   endif
 
-  [nr, nc] = size(b);
+  [nr, nc] = size (b);
   y = conv2 (x, b(nr:-1:1, nc:-1:1), shape);
 endfunction
 
--- a/scripts/signal/freqz.m
+++ b/scripts/signal/freqz.m
@@ -17,7 +17,11 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn {Function File} {[@var{h}, @var{w}] =} freqz (@var{b}, @var{a}, @var{n}, "whole")
+## @deftypefn  {Function File} {[@var{h}, @var{w}] =} freqz (@var{b}, @var{a}, @var{n}, "whole")
+## @deftypefnx {Function File} {@var{h} =} freqz (@var{b}, @var{a}, @var{w})
+## @deftypefnx {Function File} {[@dots{}] =} freqz (@dots{}, @var{Fs})
+## @deftypefnx {Function File} {} freqz (@dots{})
+## 
 ## Return the complex frequency response @var{h} of the rational IIR filter
 ## whose numerator and denominator coefficients are @var{b} and @var{a},
 ## respectively.  The response is evaluated at @var{n} angular frequencies
@@ -32,7 +36,15 @@
 ## @noindent
 ## The output value @var{w} is a vector of the frequencies.
 ##
-## If the fourth argument is omitted, the response is evaluated at
+## If @var{a} is omitted, the denominator is assumed to be 1 (this
+## corresponds to a simple FIR filter).
+##
+## If @var{n} is omitted, a value of 512 is assumed.
+##
+## For fastest computation, @var{n} should factor into a small number of
+## small primes.
+##
+## If the fourth argument, "whole", is omitted the response is evaluated at
 ## frequencies between 0 and
 ## @ifnottex
 ##  pi.
@@ -41,24 +53,19 @@
 ##  $\pi$.
 ## @end tex
 ##
-## If @var{n} is omitted, a value of 512 is assumed.
-##
-## If @var{a} is omitted, the denominator is assumed to be 1 (this
-## corresponds to a simple FIR filter).
+## @code{freqz (@var{b}, @var{a}, @var{w})}
 ##
-## For fastest computation, @var{n} should factor into a small number of
-## small primes.
-##
-## @deftypefnx {Function File} {@var{h} =} freqz (@var{b}, @var{a}, @var{w})
 ## Evaluate the response at the specific frequencies in the vector @var{w}.
 ## The values for @var{w} are measured in radians.
 ##
-## @deftypefnx {Function File} {[@dots{}] =} freqz (@dots{}, @var{Fs})
+## @code{[@dots{}] = freqz (@dots{}, @var{Fs})}
+##
 ## Return frequencies in Hz instead of radians assuming a sampling rate
 ## @var{Fs}.  If you are evaluating the response at specific frequencies
 ## @var{w}, those frequencies should be requested in Hz rather than radians.
 ##
-## @deftypefnx {Function File} {} freqz (@dots{})
+## @code{freqz (@dots{})}
+##
 ## Plot the pass band, stop band and phase response of @var{h} rather
 ## than returning them.
 ## @end deftypefn
@@ -169,29 +176,30 @@
 
 endfunction
 
+
 %!test # correct values and fft-polyval consistency
 %! # butterworth filter, order 2, cutoff pi/2 radians
 %! b = [0.292893218813452  0.585786437626905  0.292893218813452];
 %! a = [1  0  0.171572875253810];
-%! [h,w] = freqz(b,a,32);
-%! assert(h(1),1,10*eps);
-%! assert(abs(h(17)).^2,0.5,10*eps);
-%! assert(h,freqz(b,a,w),10*eps); # fft should be consistent with polyval
+%! [h,w] = freqz (b,a,32);
+%! assert (h(1),1,10*eps);
+%! assert (abs (h(17)).^2,0.5,10*eps);
+%! assert (h,freqz (b,a,w),10*eps); # fft should be consistent with polyval
 
 %!test # whole-half consistency
 %! b = [1 1 1]/3; # 3-sample average
-%! [h,w] = freqz(b,1,32,'whole');
-%! assert(h(2:16),conj(h(32:-1:18)),20*eps);
-%! [h2,w2] = freqz(b,1,16,'half');
-%! assert(h(1:16),h2,20*eps);
-%! assert(w(1:16),w2,20*eps);
+%! [h,w] = freqz (b,1,32,"whole");
+%! assert (h(2:16),conj (h(32:-1:18)),20*eps);
+%! [h2,w2] = freqz (b,1,16,"half");
+%! assert (h(1:16),h2,20*eps);
+%! assert (w(1:16),w2,20*eps);
 
 %!test # Sampling frequency properly interpreted
 %! b = [1 1 1]/3; a = [1 0.2];
-%! [h,f] = freqz(b,a,16,320);
-%! assert(f,[0:15]'*10,10*eps);
-%! [h2,f2] = freqz(b,a,[0:15]*10,320);
-%! assert(f2,[0:15]*10,10*eps);
-%! assert(h,h2.',20*eps);
-%! [h3,f3] = freqz(b,a,32,'whole',320);
-%! assert(f3,[0:31]'*10,10*eps);
+%! [h,f] = freqz (b,a,16,320);
+%! assert (f,[0:15]'*10,10*eps);
+%! [h2,f2] = freqz (b,a,[0:15]*10,320);
+%! assert (f2,[0:15]*10,10*eps);
+%! assert (h,h2.',20*eps);
+%! [h3,f3] = freqz (b,a,32,"whole",320);
+%! assert (f3,[0:31]'*10,10*eps);
--- a/scripts/signal/hamming.m
+++ b/scripts/signal/hamming.m
@@ -46,16 +46,18 @@
 
 endfunction
 
-%!assert (hamming (1), 1);
-%!assert (hamming (2), (0.54 - 0.46)*ones(2,1));
-%!assert (hamming (16), fliplr (hamming (16)));
-%!assert (hamming (15), fliplr (hamming (15)));
+
+%!assert (hamming (1), 1)
+%!assert (hamming (2), (0.54 - 0.46)*ones (2,1))
+%!assert (hamming (16), fliplr (hamming (16)))
+%!assert (hamming (15), fliplr (hamming (15)))
 %!test
 %! N = 15;
 %! A = hamming (N);
 %! assert (A (ceil (N/2)), 1);
 
-%!error hamming ();
-%!error hamming (0.5);
-%!error hamming (-1);
-%!error hamming (ones(1,4));
+%!error hamming ()
+%!error hamming (0.5)
+%!error hamming (-1)
+%!error hamming (ones (1,4))
+
--- a/scripts/signal/hanning.m
+++ b/scripts/signal/hanning.m
@@ -46,16 +46,18 @@
 
 endfunction
 
+
 %!assert (hanning (1), 1);
-%!assert (hanning (2), zeros(2,1));
+%!assert (hanning (2), zeros (2,1));
 %!assert (hanning (16), fliplr (hanning (16)));
 %!assert (hanning (15), fliplr (hanning (15)));
 %!test
 %! N = 15;
 %! A = hanning (N);
-%! assert (A (ceil (N/2)), 1);
+%! assert (A(ceil (N/2)), 1);
 
-%!error hanning ();
-%!error hanning (0.5);
-%!error hanning (-1);
-%!error hanning (ones(1,4));
+%!error hanning ()
+%!error hanning (0.5)
+%!error hanning (-1)
+%!error hanning (ones (1,4))
+
--- a/scripts/signal/hurst.m
+++ b/scripts/signal/hurst.m
@@ -42,7 +42,7 @@
 
   s = std (x);
   w = cumsum (x - mean (x));
-  RS = (max(w) - min(w)) ./ s;
+  RS = (max (w) - min (w)) ./ s;
   H = log (RS) / log (xr);
 
 endfunction
--- a/scripts/signal/ifftshift.m
+++ b/scripts/signal/ifftshift.m
@@ -69,48 +69,49 @@
 
 endfunction
 
+
 %!test
-%!  x = [0:7];
-%!  y = ifftshift (x);
-%!  assert(y, [4 5 6 7 0 1 2 3]);
-%!  assert(ifftshift (y), x);
+%! x = [0:7];
+%! y = ifftshift (x);
+%! assert (y, [4 5 6 7 0 1 2 3]);
+%! assert (ifftshift (y), x);
 
 %!test
-%!  x = [0:6];
-%!  y = ifftshift (x);
-%!  assert(y, [3 4 5 6 0 1 2]);
-%!  assert(ifftshift (y), [6 0 1 2 3 4 5]);
+%! x = [0:6];
+%! y = ifftshift (x);
+%! assert (y, [3 4 5 6 0 1 2]);
+%! assert (ifftshift (y), [6 0 1 2 3 4 5]);
 
 %!test
-%!  x = [0:7]';
-%!  y = ifftshift (x);
-%!  assert(y, [4;5;6;7;0;1;2;3]);
-%!  assert(ifftshift (y), x);
+%! x = [0:7]';
+%! y = ifftshift (x);
+%! assert (y, [4;5;6;7;0;1;2;3]);
+%! assert (ifftshift (y), x);
 
 %!test
-%!  x = [0:6]';
-%!  y = ifftshift (x);
-%!  assert(y, [3;4;5;6;0;1;2]);
-%!  assert(ifftshift (y), [6;0;1;2;3;4;5]);
+%! x = [0:6]';
+%! y = ifftshift (x);
+%! assert (y, [3;4;5;6;0;1;2]);
+%! assert (ifftshift (y), [6;0;1;2;3;4;5]);
 
 %!test
-%!  x = [0:3];
-%!  x = [x;2*x;3*x+1;4*x+1];
-%!  y = ifftshift (x);
-%!  assert(y, [[7 10 1 4];[9 13 1 5];[2 3 0 1];[4 6 0 2]]);
-%!  assert(ifftshift (y), x);
+%! x = [0:3];
+%! x = [x;2*x;3*x+1;4*x+1];
+%! y = ifftshift (x);
+%! assert (y, [[7 10 1 4];[9 13 1 5];[2 3 0 1];[4 6 0 2]]);
+%! assert (ifftshift (y), x);
 
 %!test
-%!  x = [0:3];
-%!  x = [x;2*x;3*x+1;4*x+1];
-%!  y = ifftshift (x,1);
-%!  assert(y, [[1 4 7 10];[1 5 9 13];[0 1 2 3];[0 2 4 6]]);
-%!  assert(ifftshift (y,1), x);
+%! x = [0:3];
+%! x = [x;2*x;3*x+1;4*x+1];
+%! y = ifftshift (x,1);
+%! assert (y, [[1 4 7 10];[1 5 9 13];[0 1 2 3];[0 2 4 6]]);
+%! assert (ifftshift (y,1), x);
 
 %!test
-%!  x = [0:3];
-%!  x = [x;2*x;3*x+1;4*x+1];
-%!  y = ifftshift (x,2);
-%!  assert(y, [[2 3 0 1];[4 6 0 2];[7 10 1 4];[9 13 1 5]]);
-%!  assert(ifftshift (y,2), x);
+%! x = [0:3];
+%! x = [x;2*x;3*x+1;4*x+1];
+%! y = ifftshift (x,2);
+%! assert (y, [[2 3 0 1];[4 6 0 2];[7 10 1 4];[9 13 1 5]]);
+%! assert (ifftshift (y,2), x);
 
--- a/scripts/signal/periodogram.m
+++ b/scripts/signal/periodogram.m
@@ -40,7 +40,7 @@
 ## @item win: weight data with window, x.*win is used for further computation,
 ## if window is empty, a rectangular window is used.
 ##
-## @item nfft: number of frequency bins, default max(256, 2.^ceil(log2(length(x)))).
+## @item nfft: number of frequency bins, default max (256, 2.^ceil (log2 (length (x)))).
 ##
 ## @item Fs: sampling rate, default 1.
 ##
@@ -108,7 +108,7 @@
   if (!  isempty (window))
     if (all (size (x) == size (window)))
       x .*= window;
-    elseif (size (x, 1) == size (window, 1) && size (window, 2) == 1)
+    elseif (rows (x) == rows (window) && columns (window) == 1)
       x .*= window (:,ones (1,c));
     endif;
   endif
@@ -122,7 +122,7 @@
 
   if (strcmp (range, "onesided"))
     range = 1;
-  elseif strcmp (range, "twosided")
+  elseif (strcmp (range, "twosided"))
     range = 2;
   else
     range = 2-isreal (x);
--- a/scripts/signal/private/rectangle_lw.m
+++ b/scripts/signal/private/rectangle_lw.m
@@ -34,6 +34,6 @@
   retval = zeros (n, 1);
   t = floor (1 / b);
 
-  retval (1:t, 1) = ones (t, 1);
+  retval(1:t, 1) = ones (t, 1);
 
 endfunction
--- a/scripts/signal/private/triangle_sw.m
+++ b/scripts/signal/private/triangle_sw.m
@@ -31,7 +31,7 @@
     print_usage ();
   endif
 
-  retval = zeros(n,1);
+  retval = zeros (n,1);
   retval(1) = 1 / b;
 
   l = (2:n)' - 1;
--- a/scripts/signal/sinc.m
+++ b/scripts/signal/sinc.m
@@ -23,7 +23,7 @@
 ## $ \sin (\pi x)/(\pi x)$.
 ## @end tex
 ## @ifnottex
-##  sin(pi*x)/(pi*x).
+##  sin (pi*x) / (pi*x).
 ## @end ifnottex
 ## @end deftypefn
 
@@ -47,8 +47,9 @@
 endfunction
 
 
-%!assert (sinc (0), 1);
-%!assert (sinc (1), 0,1e-6);
+%!assert (sinc (0), 1)
+%!assert (sinc (1), 0,1e-6)
 %!assert (sinc (1/2), 2/pi, 1e-6)
 
 %!error sinc()
+
--- a/scripts/signal/sinetone.m
+++ b/scripts/signal/sinetone.m
@@ -58,10 +58,11 @@
   retval = zeros (ns, n);
 
   for k = 1:n
-    retval (:, k) = ampl(k) * sin (2 * pi * (1:ns) / rate * freq(k))';
+    retval(:, k) = ampl(k) * sin (2 * pi * (1:ns) / rate * freq(k))';
   endfor
 
 endfunction
 
 
-%!assert (size (sinetone (18e6, 150e6, 19550/150e6, 1)), [19550, 1]);
+%!assert (size (sinetone (18e6, 150e6, 19550/150e6, 1)), [19550, 1])
+
--- a/scripts/signal/sinewave.m
+++ b/scripts/signal/sinewave.m
@@ -44,12 +44,14 @@
 
 endfunction
 
-%!assert (sinewave (1), 0);
-%!assert (sinewave (1, 4, 1), 1);
-%!assert (sinewave (1, 12, 1), 1/2, 1e-6);
-%!assert (sinewave (1, 12, 2), sqrt (3)/2, 1e-6);
-%!assert (sinewave (1, 20, 1), (sqrt (5)-1)/4, 1e-6);
-%!assert (sinewave (1), sinewave (1, 1,0));
-%!assert (sinewave (3, 4), sinewave(3, 4, 0));
 
-%!error sinewave ();
+%!assert (sinewave (1), 0)
+%!assert (sinewave (1, 4, 1), 1)
+%!assert (sinewave (1, 12, 1), 1/2, 1e-6)
+%!assert (sinewave (1, 12, 2), sqrt (3)/2, 1e-6)
+%!assert (sinewave (1, 20, 1), (sqrt (5)-1)/4, 1e-6)
+%!assert (sinewave (1), sinewave (1, 1,0))
+%!assert (sinewave (3, 4), sinewave (3, 4, 0))
+
+%!error sinewave ()
+
--- a/scripts/signal/spectral_xdf.m
+++ b/scripts/signal/spectral_xdf.m
@@ -53,7 +53,7 @@
   x = x - sum (x) / xr;
 
   retval = (abs (fft (x)) / xr).^2;
-  retval = real (ifft (fft(retval) .* fft(w)));
+  retval = real (ifft (fft (retval) .* fft (w)));
 
   retval = [(zeros (xr, 1)), retval];
   retval(:, 1) = (0 : xr-1)' / xr;
--- a/scripts/signal/spencer.m
+++ b/scripts/signal/spencer.m
@@ -31,15 +31,15 @@
     print_usage ();
   endif
 
-  [xr, xc] = size(x);
+  [xr, xc] = size (x);
 
   n = xr;
   c = xc;
 
-  if (isvector(x))
-   n = length(x);
+  if (isvector (x))
+   n = length (x);
    c = 1;
-   x = reshape(x, n, 1);
+   x = reshape (x, n, 1);
   endif
 
   w = [-3, -6, -5, 3, 21, 46, 67, 74, 67, 46, 21, 3, -5, -6, -3] / 320;
@@ -47,7 +47,7 @@
   retval = fftfilt (w, x);
   retval = [zeros(7,c); retval(15:n,:); zeros(7,c);];
 
-  retval = reshape(retval, xr, xc);
+  retval = reshape (retval, xr, xc);
 
 endfunction
 
--- a/scripts/signal/stft.m
+++ b/scripts/signal/stft.m
@@ -55,7 +55,7 @@
 ## Author: AW <Andreas.Weingessel@ci.tuwien.ac.at>
 ## Description: Short-Time Fourier Transform
 
-function [y, c] = stft(x, win_size, inc, num_coef, win_type)
+function [y, c] = stft (x, win_size, inc, num_coef, win_type)
 
   ## Default values of unspecified arguments.
   if (nargin < 5)
--- a/scripts/signal/synthesis.m
+++ b/scripts/signal/synthesis.m
@@ -62,11 +62,11 @@
   z = z(st:st+inc-1, :);
   w_coeff = w_coeff(st:st+inc-1);
 
-  nc = columns(z);
+  nc = columns (z);
   for i = 1:nc
     z(:, i) = z(:, i) ./ w_coeff;
   endfor
 
-  x = reshape(z, inc * nc, 1);
+  x = reshape (z, inc * nc, 1);
 
 endfunction
--- a/scripts/signal/unwrap.m
+++ b/scripts/signal/unwrap.m
@@ -36,7 +36,7 @@
     print_usage ();
   endif
 
-  if (!isnumeric(x))
+  if (!isnumeric (x))
     error ("unwrap: X must be a numeric matrix or vector");
   endif
 
@@ -78,7 +78,7 @@
   ## Find only the peaks, and multiply them by the appropriate amount
   ## of ranges so that there are kronecker deltas at each wrap point
   ## multiplied by the appropriate amount of range values.
-  p =  ceil(abs(d)./rng) .* rng .* (((d > tol) > 0) - ((d < -tol) > 0));
+  p =  ceil (abs (d)./rng) .* rng .* (((d > tol) > 0) - ((d < -tol) > 0));
 
   ## Now need to "integrate" this so that the deltas become steps.
   r = cumsum (p, dim);
@@ -89,16 +89,17 @@
 
 endfunction
 
-%!function t = __xassert(a,b,tol)
+
+%!function t = __xassert (a,b,tol)
 %!  if (nargin == 1)
-%!    t = all(a(:));
+%!    t = all (a(:));
 %!  else
 %!    if (nargin == 2)
 %!      tol = 0;
 %!    endif
-%!    if (any (size(a) != size(b)))
+%!    if (any (size (a) != size (b)))
 %!      t = 0;
-%!    elseif (any (abs(a(:) - b(:)) > tol))
+%!    elseif (any (abs (a(:) - b(:)) > tol))
 %!      t = 0;
 %!    else
 %!      t = 1;
@@ -112,29 +113,29 @@
 %! t = [];
 %!
 %! r = [0:100];                        # original vector
-%! w = r - 2*pi*floor((r+pi)/(2*pi));  # wrapped into [-pi,pi]
+%! w = r - 2*pi*floor ((r+pi)/(2*pi)); # wrapped into [-pi,pi]
 %! tol = 1e3*eps;                      # maximum expected deviation
 %!
-%! t(++i) = __xassert(r, unwrap(w), tol);               #unwrap single row
-%! t(++i) = __xassert(r', unwrap(w'), tol);             #unwrap single column
-%! t(++i) = __xassert([r',r'], unwrap([w',w']), tol);   #unwrap 2 columns
-%! t(++i) = __xassert([r;r], unwrap([w;w],[],2), tol);  #check that dim works
-%! t(++i) = __xassert(r+10, unwrap(10+w), tol);         #check r(1)>pi works
+%! t(++i) = __xassert (r, unwrap (w), tol);              #unwrap single row
+%! t(++i) = __xassert (r', unwrap (w'), tol);            #unwrap single column
+%! t(++i) = __xassert ([r',r'], unwrap ([w',w']), tol);  #unwrap 2 columns
+%! t(++i) = __xassert ([r;r], unwrap ([w;w],[],2), tol); #check that dim works
+%! t(++i) = __xassert (r+10, unwrap (10+w), tol);        #check r(1)>pi works
 %!
-%! t(++i) = __xassert(w', unwrap(w',[],2));  #unwrap col by rows should not change it
-%! t(++i) = __xassert(w, unwrap(w,[],1));    #unwrap row by cols should not change it
-%! t(++i) = __xassert([w;w], unwrap([w;w])); #unwrap 2 rows by cols should not change them
+%! t(++i) = __xassert (w', unwrap (w',[],2));  #unwrap col by rows should not change it
+%! t(++i) = __xassert (w, unwrap (w,[],1));    #unwrap row by cols should not change it
+%! t(++i) = __xassert ([w;w], unwrap ([w;w])); #unwrap 2 rows by cols should not change them
 %!
 %! ## verify that setting tolerance too low will cause bad results.
-%! t(++i) = __xassert(any(abs(r - unwrap(w,0.8)) > 100));
+%! t(++i) = __xassert (any (abs (r - unwrap (w,0.8)) > 100));
 %!
-%! assert(all(t));
+%! assert (all (t));
 %!
 %!test
 %! A = [pi*(-4), pi*(-2+1/6), pi/4, pi*(2+1/3), pi*(4+1/2), pi*(8+2/3), pi*(16+1), pi*(32+3/2), pi*64];
-%! assert (unwrap(A), unwrap(A, pi));
-%! assert (unwrap(A, pi), unwrap(A, pi, 2));
-%! assert (unwrap(A', pi), unwrap(A', pi, 1));
+%! assert (unwrap (A), unwrap (A, pi));
+%! assert (unwrap (A, pi), unwrap (A, pi, 2));
+%! assert (unwrap (A', pi), unwrap (A', pi, 1));
 %!
 %!test
 %! A = [pi*(-4); pi*(2+1/3); pi*(16+1)];
@@ -145,12 +146,13 @@
 %! E(:, :, 2) = [A+B, B+C, C+D, D+A];
 %! F(:, :, 1) = [unwrap(A), unwrap(B), unwrap(C), unwrap(D)];
 %! F(:, :, 2) = [unwrap(A+B), unwrap(B+C), unwrap(C+D), unwrap(D+A)];
-%! assert (unwrap(E), F);
+%! assert (unwrap (E), F);
 %!
 %!test
 %! A = [0, 2*pi, 4*pi, 8*pi, 16*pi, 65536*pi];
 %! B = [pi*(-2+1/6), pi/4, pi*(2+1/3), pi*(4+1/2), pi*(8+2/3), pi*(16+1), pi*(32+3/2), pi*64];
-%! assert (unwrap(A), zeros(1, length(A)));
-%! assert (diff(unwrap(B), 1)<2*pi, true(1, length(B)-1));
-%!
+%! assert (unwrap (A), zeros (1, length (A)));
+%! assert (diff (unwrap (B), 1) < 2*pi, true (1, length (B)-1));
+
 %!error unwrap()
+
--- a/scripts/signal/yulewalker.m
+++ b/scripts/signal/yulewalker.m
@@ -41,7 +41,7 @@
   endif
 
   cp = c(2 : p+1);
-  CP = zeros(p, p);
+  CP = zeros (p, p);
 
   for i = 1:p
     for j = 1:p
--- a/scripts/sparse/bicg.m
+++ b/scripts/sparse/bicg.m
@@ -15,7 +15,6 @@
 ## along with this program; If not, see <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-##
 ## @deftypefn  {Function File} {@var{x} =} bicg (@var{A}, @var{b}, @var{rtol}, @var{maxit}, @var{M1}, @var{M2}, @var{x0})
 ## @deftypefnx {Function File} {@var{x} =} bicg (@var{A}, @var{b}, @var{rtol}, @var{maxit}, @var{P})
 ## @deftypefnx {Function File} {[@var{x}, @var{flag}, @var{relres}, @var{iter}, @var{resvec}] =} bicg (@var{A}, @var{b}, @dots{})
@@ -40,13 +39,14 @@
 ## The preconditioner @var{P} is given as @code{P = M1 * M2}.
 ## Both @var{M1} and @var{M2} can be passed as a matrix or as
 ## a function handle or inline function @code{g} such that
-## @code{g(x, 'notransp') = M1 \ x} or @code{g(x, 'notransp') = M2 \ x} and
-## @code{g(x, 'transp') = M1' \ x} or @code{g(x, 'transp') = M2' \ x}.
+## @code{g(x, "notransp") = M1 \ x} or @code{g(x, "notransp") = M2 \ x} and
+## @code{g(x, "transp") = M1' \ x} or @code{g(x, "transp") = M2' \ x}.
 ##
 ## If called with more than one output parameter
 ##
 ## @itemize @minus
 ## @item @var{flag} indicates the exit status:
+##
 ## @itemize @minus
 ## @item 0: iteration converged to the within the chosen tolerance
 ##
@@ -228,7 +228,6 @@
 %! M2 = spdiags ([4*ones(n,1) -ones(n,1)], 0:1, n, n);
 %! [x, flag, relres, iter, resvec] = bicg (A, b, tol, maxit, M1, M2);
 %! assert (x, ones (size (b)), 1e-7);
-%!
 
 %!function y = afun (x, t, a)
 %!  switch t
@@ -260,3 +259,4 @@
 %! b = sum (A, 2);
 %! [x, flag, relres, iter, resvec] = bicg (A, b, tol, [], diag (diag (A)));
 %! assert (x, ones (size (b)), 1e-7);
+
--- a/scripts/sparse/bicgstab.m
+++ b/scripts/sparse/bicgstab.m
@@ -18,7 +18,6 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-##
 ## @deftypefn  {Function File} {@var{x} =} bicgstab (@var{A}, @var{b}, @var{rtol}, @var{maxit}, @var{M1}, @var{M2}, @var{x0})
 ## @deftypefnx {Function File} {@var{x} =} bicgstab (@var{A}, @var{b}, @var{rtol}, @var{maxit}, @var{P})
 ## @deftypefnx {Function File} {[@var{x}, @var{flag}, @var{relres}, @var{iter}, @var{resvec}] =} bicgstab (@var{A}, @var{b}, @dots{})
@@ -49,6 +48,7 @@
 ##
 ## @itemize @minus
 ## @item @var{flag} indicates the exit status:
+##
 ## @itemize @minus
 ## @item 0: iteration converged to the within the chosen tolerance
 ##
@@ -138,7 +138,7 @@
     rr = res;
 
     ## Vector of the residual norms for each iteration.
-    resvec = norm(res) / norm_b;
+    resvec = norm (res) / norm_b;
 
     ## Default behaviour we don't reach tolerance tol within maxit iterations.
     flag = 1;
@@ -206,11 +206,12 @@
 
 endfunction
 
+
 %!demo
 %! % Solve system of A*x=b
-%! A = [5 -1 3;-1 2 -2;3 -2 3]
-%! b = [7;-1;4]
-%! [x, flag, relres, iter, resvec] = bicgstab(A, b)
+%! A = [5 -1 3;-1 2 -2;3 -2 3];
+%! b = [7;-1;4];
+%! [x, flag, relres, iter, resvec] = bicgstab (A, b)
 
 %!shared A, b, n, M1, M2
 %!
@@ -245,3 +246,4 @@
 %! b = sum (A, 2);
 %! [x, flag, relres, iter, resvec] = bicgstab (A, b, tol, [], diag (diag (A)));
 %! assert (x, ones (size (b)), 1e-7);
+
--- a/scripts/sparse/cgs.m
+++ b/scripts/sparse/cgs.m
@@ -18,7 +18,6 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-##
 ## @deftypefn  {Function File} {@var{x} =} cgs (@var{A}, @var{b}, @var{rtol}, @var{maxit}, @var{M1}, @var{M2}, @var{x0})
 ## @deftypefnx {Function File} {@var{x} =} cgs (@var{A}, @var{b}, @var{rtol}, @var{maxit}, @var{P})
 ## @deftypefnx {Function File} {[@var{x}, @var{flag}, @var{relres}, @var{iter}, @var{resvec}] =} cgs (@var{A}, @var{b}, @dots{})
@@ -49,6 +48,7 @@
 ##
 ## @itemize @minus
 ## @item @var{flag} indicates the exit status:
+##
 ## @itemize @minus
 ## @item 0: iteration converged to the within the chosen tolerance
 ##
@@ -189,12 +189,11 @@
 endfunction
 
 
-
 %!demo
 %! % Solve system of A*x=b
-%! A=[5 -1 3;-1 2 -2;3 -2 3]
-%! b=[7;-1;4]
-%! [a,b,c,d,e]=cgs(A,b)
+%! A = [5 -1 3;-1 2 -2;3 -2 3];
+%! b = [7;-1;4];
+%! [a,b,c,d,e] = cgs (A,b)
 
 %!shared A, b, n, M
 %!
@@ -223,3 +222,4 @@
 %! b = sum (A, 2);
 %! [x, flag, relres, iter, resvec] = cgs (A, b, tol, [], diag (diag (A)));
 %! assert (x, ones (size (b)), 1e-7);
+
--- a/scripts/sparse/gmres.m
+++ b/scripts/sparse/gmres.m
@@ -32,7 +32,7 @@
 ## @code{min (10, numel (b) / restart)} is used.
 ##
 ## @item @var{x0} is the initial guess,
-## if not given or set to [] the default value @code{zeros(size (b))} is used.
+## if not given or set to [] the default value @code{zeros (size (b))} is used.
 ##
 ## @item @var{m} is the restart parameter,
 ## if not given or set to [] the default value @code{numel (b)} is used.
@@ -49,6 +49,7 @@
 ##
 ## @itemize @minus
 ## @item @var{flag} indicates the exit status:
+##
 ## @table @asis
 ## @item 0 : iteration converged to within the specified tolerance
 ##
@@ -56,7 +57,7 @@
 ##
 ## @item 2 : unused, but skipped for compatibility
 ##
-## @item 3 : algorithm reached stagnation
+## @item 3 : algorithm reached stagnation (no change between iterations)
 ## @end table
 ##
 ## @item @var{relres} is the final value of the relative residual.
@@ -71,7 +72,7 @@
 ## @seealso{bicg, bicgstab, cgs, pcg}
 ## @end deftypefn
 
-function [x, flag, presn, it, resids] = gmres (A, b, restart, rtol, maxit, M1, M2, x0)
+function [x, flag, relres, it, resvec] = gmres (A, b, restart, rtol, maxit, M1, M2, x0)
 
   if (nargin < 2 || nargin > 8)
     print_usage ();
@@ -141,10 +142,10 @@
   ## begin loop
   iter = 1;
   restart_it  = restart + 1;
-  resids      = zeros (maxit, 1);
-  resids(1)   = presn;
+  resvec      = zeros (maxit, 1);
+  resvec(1)   = presn;
   prec_b_norm = norm (Pm1x (b), 2);
-  flag        = 1;
+  flag        = 1;  # Default flag is maximum # of iterations exceeded
 
   while (iter <= maxit * restart && presn > rtol * prec_b_norm)
 
@@ -173,46 +174,63 @@
 
     x = x_old + V(:, 1:restart_it) * Y(1:restart_it);
 
-    resids(iter) = presn;
+    resvec(iter+1) = presn;
     if (norm (x - x_old, inf) <= eps)
-      flag = 3;
-      break
+      flag = 3;  # Stagnation: no change between iterations
+      break;
     endif
 
     restart_it++ ;
     iter++;
   endwhile
 
-  if (presn > rtol * prec_b_norm)
-    flag = 0;
+  if (nargout > 1)
+    ## Calculate extra outputs as requested
+    relres = presn / prec_b_norm;
+    if (relres <= rtol)
+      flag = 0;  # Converged to solution within tolerance
+    endif
+
+    it = [floor(iter/restart), restart_it-1];
   endif
 
-  resids = resids(1:iter-1);
-  it = [ceil(iter / restart), rem(iter, restart)];
-
 endfunction
 
 
+%!demo
+%! dim = 20;
+%! A = spdiags ([-ones(dim,1) 2*ones(dim,1) ones(dim,1)], [-1:1], dim, dim);
+%! b = ones (dim, 1);
+%! [x, flag, relres, iter, resvec] = gmres (A, b, 10, 1e-10, dim, @(x) x ./ diag (A), [], b)
+
 %!shared A, b, dim
 %! dim = 100;
 %!test
 %! A = spdiags ([-ones(dim,1) 2*ones(dim,1) ones(dim,1)], [-1:1], dim, dim);
-%! b = ones(dim, 1);
-%! x = gmres (A, b, 10, 1e-10, dim, @(x) x./diag(A), [],  b);
-%! assert(x, A\b, 1e-9*norm(x,inf));
+%! b = ones (dim, 1);
+%! x = gmres (A, b, 10, 1e-10, dim, @(x) x ./ diag (A), [], b);
+%! assert (x, A\b, 1e-9*norm (x, Inf));
 %!
 %!test
-%! x = gmres (A, b, dim, 1e-10, 1e4, @(x) diag(diag(A))\x, [],  b);
-%! assert(x, A\b, 1e-7*norm(x,inf));
+%! x = gmres (A, b, dim, 1e-10, 1e4, @(x) diag (diag (A)) \ x, [], b);
+%! assert(x, A\b, 1e-7*norm (x, Inf));
 %!
 %!test
 %! A = spdiags ([[1./(2:2:2*(dim-1)) 0]; 1./(1:2:2*dim-1); [0 1./(2:2:2*(dim-1))]]', -1:1, dim, dim);
 %! A = A'*A;
 %! b = rand (dim, 1);
-%! [x, resids] = gmres (@(x) A*x, b, dim, 1e-10, dim, @(x) x./diag(A), [],  []);
-%! assert(x, A\b, 1e-9*norm(x,inf))
-%! x = gmres (@(x) A*x, b, dim, 1e-10, 1e6, @(x) diag(diag(A))\x, [],  []);
-%! assert(x, A\b, 1e-9*norm(x,inf));
+%! [x, resvec] = gmres (@(x) A*x, b, dim, 1e-10, dim, @(x) x./diag (A), [], []);
+%! assert (x, A\b, 1e-9*norm (x, Inf));
+%! x = gmres (@(x) A*x, b, dim, 1e-10, 1e6, @(x) diag (diag (A)) \ x, [], []);
+%! assert (x, A\b, 1e-9*norm (x, Inf));
 %!test
-%! x =  gmres (@(x) A*x, b, dim, 1e-10, 1e6, @(x) x./diag(A), [],  []);
-%! assert(x, A\b, 1e-7*norm(x,inf));
+%! x = gmres (@(x) A*x, b, dim, 1e-10, 1e6, @(x) x ./ diag (A), [], []);
+%! assert (x, A\b, 1e-7*norm (x, Inf));
+
+
+%!error gmres (1)
+%!error gmres (1,2,3,4,5,6,7,8,9)
+%!error <A must be> gmres ({1},2)
+%!error <A must be a function or matrix> gmres ({1},2)
+%!error <M1 must be a function or matrix> gmres (1,2,3,4,5,{6})
+%!error <M2 must be a function or matrix> gmres (1,2,3,4,5,6,{7})
--- a/scripts/sparse/gplot.m
+++ b/scripts/sparse/gplot.m
@@ -66,13 +66,13 @@
 %!      0 0 0 0 1 0 0
 %!      0 0 0 0 1 0 0];
 %!
-%! xy = [1, 0
+%! xy = [1  , 0
 %!       1.5, 1
-%!       2, 0
+%!       2  , 0
 %!       2.5, 2
 %!       3.5, 1
-%!       3, 0
-%!       4, 0];
+%!       3  , 0
+%!       4  , 0];
 %!
 %! clf;
 %! gplot (A, xy, "o-");
@@ -80,5 +80,5 @@
 %! title ("gplot() of Binary Tree Adjacency matrix");
 
 %% Mark graphical function as tested by demo block
-%!assert (1);
+%!assert (1)
 
--- a/scripts/sparse/nonzeros.m
+++ b/scripts/sparse/nonzeros.m
@@ -34,7 +34,8 @@
 endfunction
 
 
-%!assert(nonzeros([1,2;3,0]),[1;3;2])
-%!assert(nonzeros([1,2,3,0]),[1;2;3])
-%!assert(nonzeros(sparse([1,2;3,0])),[1;3;2])
-%!assert(nonzeros(sparse([1,2,3,0])),[1;2;3])
+%!assert (nonzeros ([1,2;3,0]), [1;3;2])
+%!assert (nonzeros ([1,2,3,0]), [1;2;3])
+%!assert (nonzeros (sparse ([1,2;3,0])), [1;3;2])
+%!assert (nonzeros (sparse ([1,2,3,0])), [1;2;3])
+
--- a/scripts/sparse/pcg.m
+++ b/scripts/sparse/pcg.m
@@ -241,7 +241,7 @@
   endif
 
   if (nargin < 4 || isempty (maxit))
-    maxit = min (size (b, 1), 20);
+    maxit = min (rows (b), 20);
   endif
 
   maxit += 2;
@@ -275,7 +275,7 @@
 
   while (resvec (iter-1,1) > tol * resvec (1,1) && iter < maxit)
     if (exist_m1)
-      if(isnumeric (m1))
+      if (isnumeric (m1))
         y = m1 \ r;
       else
         y = feval (m1, r, varargin{:});
@@ -316,8 +316,8 @@
     if (nargout > 5 && iter > 2)
       T(iter-1:iter, iter-1:iter) = T(iter-1:iter, iter-1:iter) + ...
           [1 sqrt(beta); sqrt(beta) beta]./oldalpha;
-      ## EVS = eig(T(2:iter-1,2:iter-1));
-      ## fprintf(stderr,"PCG condest: %g (iteration: %d)\n", max(EVS)/min(EVS),iter);
+      ## EVS = eig (T(2:iter-1,2:iter-1));
+      ## fprintf (stderr,"PCG condest: %g (iteration: %d)\n", max (EVS)/min (EVS),iter);
     endif
     resvec (iter,1) = norm (r);
     iter++;
@@ -388,145 +388,153 @@
   endif
 endfunction
 
+
 %!demo
-%!
-%!      # Simplest usage of pcg (see also 'help pcg')
-%!
-%!      N = 10;
-%!      A = diag ([1:N]); b = rand (N, 1); y =  A \ b; #y is the true solution
-%!      x = pcg (A, b);
-%!      printf('The solution relative error is %g\n', norm (x - y) / norm (y));
-%!
-%!      # You shouldn't be afraid if pcg issues some warning messages in this
-%!      # example: watch out in the second example, why it takes N iterations
-%!      # of pcg to converge to (a very accurate, by the way) solution
+%!  # Simplest usage of pcg (see also 'help pcg')
+%! 
+%!  N = 10;
+%!  A = diag ([1:N]); b = rand (N, 1);
+%!  y = A \ b;  # y is the true solution
+%!  x = pcg (A, b);
+%!  printf ("The solution relative error is %g\n", norm (x - y) / norm (y));
+%! 
+%!  # You shouldn't be afraid if pcg issues some warning messages in this
+%!  # example: watch out in the second example, why it takes N iterations
+%!  # of pcg to converge to (a very accurate, by the way) solution
+
 %!demo
-%!
-%!      # Full output from pcg, except for the eigenvalue estimates
-%!      # We use this output to plot the convergence history
-%!
-%!      N = 10;
-%!      A = diag ([1:N]); b = rand (N, 1); X =  A \ b; #X is the true solution
-%!      [x, flag, relres, iter, resvec] = pcg (A, b);
-%!      printf('The solution relative error is %g\n', norm (x - X) / norm (X));
-%!      title('Convergence history'); xlabel('Iteration'); ylabel('log(||b-Ax||/||b||)');
-%!      semilogy([0:iter], resvec / resvec(1),'o-g');
-%!      legend('relative residual');
+%!  # Full output from pcg, except for the eigenvalue estimates
+%!  # We use this output to plot the convergence history
+%! 
+%!  N = 10;
+%!  A = diag ([1:N]); b = rand (N, 1);
+%!  X = A \ b;  # X is the true solution
+%!  [x, flag, relres, iter, resvec] = pcg (A, b);
+%!  printf ("The solution relative error is %g\n", norm (x - X) / norm (X));
+%!  title ("Convergence history");
+%!  semilogy ([0:iter], resvec / resvec(1), "o-g");
+%!  xlabel ("Iteration"); ylabel ("log(||b-Ax||/||b||)");
+%!  legend ("relative residual");
+
 %!demo
-%!
-%!      # Full output from pcg, including the eigenvalue estimates
-%!      # Hilbert matrix is extremely ill conditioned, so pcg WILL have problems
+%!  # Full output from pcg, including the eigenvalue estimates
+%!  # Hilbert matrix is extremely ill-conditioned, so pcg WILL have problems
+%! 
+%!  N = 10;
+%!  A = hilb (N); b = rand (N, 1);
+%!  X = A \ b;  # X is the true solution
+%!  [x, flag, relres, iter, resvec, eigest] = pcg (A, b, [], 200);
+%!  printf ("The solution relative error is %g\n", norm (x - X) / norm (X));
+%!  printf ("Condition number estimate is %g\n", eigest(2) / eigest(1));
+%!  printf ("Actual condition number is   %g\n", cond (A));
+%!  title ("Convergence history");
+%!  semilogy ([0:iter], resvec, ["o-g";"+-r"]);
+%!  xlabel ("Iteration"); ylabel ("log(||b-Ax||)");
+%!  legend ("absolute residual", "absolute preconditioned residual");
+
+%!demo
+%!  # Full output from pcg, including the eigenvalue estimates
+%!  # We use the 1-D Laplacian matrix for A, and cond(A) = O(N^2)
+%!  # and that's the reason we need some preconditioner; here we take
+%!  # a very simple and not powerful Jacobi preconditioner,
+%!  # which is the diagonal of A
 %!
-%!      N = 10;
-%!      A = hilb (N); b = rand (N, 1); X = A \ b; #X is the true solution
-%!      [x, flag, relres, iter, resvec, eigest] = pcg (A, b, [], 200);
-%!      printf('The solution relative error is %g\n', norm (x - X) / norm (X));
-%!      printf('Condition number estimate is %g\n', eigest(2) / eigest (1));
-%!      printf('Actual condition number is   %g\n', cond (A));
-%!      title('Convergence history'); xlabel('Iteration'); ylabel('log(||b-Ax||)');
-%!      semilogy([0:iter], resvec,['o-g';'+-r']);
-%!      legend('absolute residual','absolute preconditioned residual');
-%!demo
-%!
-%!      # Full output from pcg, including the eigenvalue estimates
-%!      # We use the 1-D Laplacian matrix for A, and cond(A) = O(N^2)
-%!      # and that's the reasone we need some preconditioner; here we take
-%!      # a very simple and not powerful Jacobi preconditioner,
-%!      # which is the diagonal of A
+%!  N = 100;
+%!  A = zeros (N, N);
+%!  for i = 1 : N - 1 # form 1-D Laplacian matrix
+%!    A(i:i+1, i:i+1) = [2 -1; -1 2];
+%!  endfor
+%!  b = rand (N, 1);
+%!  X = A \ b;  # X is the true solution
+%!  maxit = 80;
+%!  printf ("System condition number is %g\n", cond (A));
+%!  # No preconditioner: the convergence is very slow!
 %!
-%!      N = 100;
-%!      A = zeros (N, N);
-%!      for i=1 : N - 1 # form 1-D Laplacian matrix
-%!              A (i:i+1, i:i+1) = [2 -1; -1 2];
-%!      endfor
-%!      b = rand (N, 1); X = A \ b; #X is the true solution
-%!      maxit = 80;
-%!      printf('System condition number is %g\n', cond (A));
-%!      # No preconditioner: the convergence is very slow!
+%!  [x, flag, relres, iter, resvec, eigest] = pcg (A, b, [], maxit);
+%!  printf ("System condition number estimate is %g\n", eigest(2) / eigest(1));
+%!  title ("Convergence history");
+%!  semilogy ([0:iter], resvec(:,1), "o-g");
+%!  xlabel ("Iteration"); ylabel ("log(||b-Ax||)");
+%!  legend ("NO preconditioning: absolute residual");
 %!
-%!      [x, flag, relres, iter, resvec, eigest] = pcg (A, b, [], maxit);
-%!      printf('System condition number estimate is %g\n', eigest(2) / eigest(1));
-%!      title('Convergence history'); xlabel('Iteration'); ylabel('log(||b-Ax||)');
-%!      semilogy([0:iter], resvec(:,1), 'o-g');
-%!      legend('NO preconditioning: absolute residual');
-%!
-%!      pause(1);
-%!      # Test Jacobi preconditioner: it will not help much!!!
+%!  pause (1);
+%!  # Test Jacobi preconditioner: it will not help much!!!
 %!
-%!      M = diag (diag (A)); # Jacobi preconditioner
-%!      [x, flag, relres, iter, resvec, eigest] = pcg (A, b, [], maxit, M);
-%!      printf('JACOBI preconditioned system condition number estimate is %g\n', eigest(2) / eigest(1));
-%!      hold on;
-%!      semilogy([0:iter], resvec(:,1), 'o-r');
-%!      legend('NO preconditioning: absolute residual', ...
-%!             'JACOBI preconditioner: absolute residual');
+%!  M = diag (diag (A)); # Jacobi preconditioner
+%!  [x, flag, relres, iter, resvec, eigest] = pcg (A, b, [], maxit, M);
+%!  printf ("JACOBI preconditioned system condition number estimate is %g\n", eigest(2) / eigest(1));
+%!  hold on;
+%!  semilogy ([0:iter], resvec(:,1), "o-r");
+%!  legend ("NO preconditioning: absolute residual", ...
+%!          "JACOBI preconditioner: absolute residual");
 %!
-%!      pause(1);
-%!      # Test nonoverlapping block Jacobi preconditioner: it will help much!
+%!  pause (1);
+%!  # Test nonoverlapping block Jacobi preconditioner: it will help much!
 %!
-%!      M = zeros (N, N); k = 4;
-%!      for i = 1 : k : N # form 1-D Laplacian matrix
-%!              M (i:i+k-1, i:i+k-1) = A (i:i+k-1, i:i+k-1);
-%!      endfor
-%!      [x, flag, relres, iter, resvec, eigest] = pcg (A, b, [], maxit, M);
-%!      printf('BLOCK JACOBI preconditioned system condition number estimate is %g\n', eigest(2) / eigest(1));
-%!      semilogy ([0:iter], resvec(:,1),'o-b');
-%!      legend('NO preconditioning: absolute residual', ...
-%!             'JACOBI preconditioner: absolute residual', ...
-%!             'BLOCK JACOBI preconditioner: absolute residual');
-%!      hold off;
+%!  M = zeros (N, N); k = 4;
+%!  for i = 1 : k : N # form 1-D Laplacian matrix
+%!    M(i:i+k-1, i:i+k-1) = A(i:i+k-1, i:i+k-1);
+%!  endfor
+%!  [x, flag, relres, iter, resvec, eigest] = pcg (A, b, [], maxit, M);
+%!  printf ("BLOCK JACOBI preconditioned system condition number estimate is %g\n", eigest(2) / eigest(1));
+%!  semilogy ([0:iter], resvec(:,1), "o-b");
+%!  legend ("NO preconditioning: absolute residual", ...
+%!          "JACOBI preconditioner: absolute residual", ...
+%!          "BLOCK JACOBI preconditioner: absolute residual");
+%!  hold off;
+
 %!test
+%! # solve small diagonal system
 %!
-%!      #solve small diagonal system
-%!
-%!      N = 10;
-%!      A = diag ([1:N]); b = rand (N, 1); X = A \ b; #X is the true solution
-%!      [x, flag] = pcg (A, b, [], N+1);
-%!      assert(norm (x - X) / norm (X), 0, 1e-10);
-%!      assert(flag, 0);
-%!
+%! N = 10;
+%! A = diag ([1:N]); b = rand (N, 1);
+%! X = A \ b;  # X is the true solution
+%! [x, flag] = pcg (A, b, [], N+1);
+%! assert (norm (x - X) / norm (X), 0, 1e-10);
+%! assert (flag, 0);
+
 %!test
-%!
-%!      #solve small indefinite diagonal system
-%!      #despite A is indefinite, the iteration continues and converges
-%!      #indefiniteness of A is detected
+%! # solve small indefinite diagonal system
+%! # despite A is indefinite, the iteration continues and converges
+%! # indefiniteness of A is detected
 %!
-%!      N = 10;
-%!      A = diag([1:N] .* (-ones(1, N) .^ 2)); b = rand (N, 1); X = A \ b; #X is the true solution
-%!      [x, flag] = pcg (A, b, [], N+1);
-%!      assert(norm (x - X) / norm (X), 0, 1e-10);
-%!      assert(flag, 3);
-%!
+%! N = 10;
+%! A = diag([1:N] .* (-ones(1, N) .^ 2)); b = rand (N, 1);
+%! X = A \ b;  # X is the true solution
+%! [x, flag] = pcg (A, b, [], N+1);
+%! assert (norm (x - X) / norm (X), 0, 1e-10);
+%! assert (flag, 3);
+
 %!test
-%!
-%!      #solve tridiagonal system, do not converge in default 20 iterations
+%! # solve tridiagonal system, do not converge in default 20 iterations
 %!
-%!      N = 100;
-%!      A = zeros (N, N);
-%!      for i = 1 : N - 1 # form 1-D Laplacian matrix
-%!              A (i:i+1, i:i+1) = [2 -1; -1 2];
-%!      endfor
-%!      b = ones (N, 1); X = A \ b; #X is the true solution
-%!      [x, flag, relres, iter, resvec, eigest] = pcg (A, b, 1e-12);
-%!      assert(flag);
-%!      assert(relres > 1.0);
-%!      assert(iter, 20); #should perform max allowable default number of iterations
-%!
+%! N = 100;
+%! A = zeros (N, N);
+%! for i = 1 : N - 1 # form 1-D Laplacian matrix
+%!   A(i:i+1, i:i+1) = [2 -1; -1 2];
+%! endfor
+%! b = ones (N, 1);
+%! X = A \ b;  # X is the true solution
+%! [x, flag, relres, iter, resvec, eigest] = pcg (A, b, 1e-12);
+%! assert (flag);
+%! assert (relres > 1.0);
+%! assert (iter, 20); # should perform max allowable default number of iterations
+
 %!test
+%! # solve tridiagonal system with 'perfect' preconditioner
+%! # which converges in one iteration, so the eigest does not
+%! # work and issues a warning
 %!
-%!      #solve tridiagonal system with 'prefect' preconditioner
-%!      #converges in one iteration, so the eigest does not work
-%!      #and issues a warning
-%!
-%!      N = 100;
-%!      A = zeros (N, N);
-%!      for i = 1 : N - 1 # form 1-D Laplacian matrix
-%!              A (i:i+1, i:i+1) = [2 -1; -1 2];
-%!      endfor
-%!      b = ones (N, 1); X = A \ b; #X is the true solution
-%!      [x, flag, relres, iter, resvec, eigest] = pcg (A, b, [], [], A, [], b);
-%!      assert(norm (x - X) / norm (X), 0, 1e-6);
-%!      assert(flag, 0);
-%!      assert(iter, 1); #should converge in one iteration
-%!      assert(isnan (eigest), isnan ([NaN, NaN]));
-%!
+%! N = 100;
+%! A = zeros (N, N);
+%! for i = 1 : N - 1 # form 1-D Laplacian matrix
+%!         A (i:i+1, i:i+1) = [2 -1; -1 2];
+%! endfor
+%! b = ones (N, 1);
+%! X = A \ b;  # X is the true solution
+%! [x, flag, relres, iter, resvec, eigest] = pcg (A, b, [], [], A, [], b);
+%! assert (norm (x - X) / norm (X), 0, 1e-6);
+%! assert (flag, 0);
+%! assert (iter, 1); # should converge in one iteration
+%! assert (isnan (eigest), isnan ([NaN, NaN]));
+
--- a/scripts/sparse/pcr.m
+++ b/scripts/sparse/pcr.m
@@ -252,7 +252,7 @@
     x += lambda*p;
     r -= lambda*q;
 
-    if (isnumeric(A))           # is A a matrix?
+    if (isnumeric (A))          # is A a matrix?
       t = A*s;
     else                        # then A should be a function!
       t = feval (A, s, varargin{:});
@@ -301,132 +301,143 @@
 
 endfunction
 
+
 %!demo
-%!
-%!      # Simplest usage of PCR (see also 'help pcr')
+%! # Simplest usage of PCR (see also 'help pcr')
 %!
-%!      N = 20;
-%!      A = diag(linspace(-3.1,3,N)); b = rand(N,1); y = A\b; #y is the true solution
-%!      x = pcr(A,b);
-%!      printf('The solution relative error is %g\n', norm(x-y)/norm(y));
-%!
-%!      # You shouldn't be afraid if PCR issues some warning messages in this
-%!      # example: watch out in the second example, why it takes N iterations
-%!      # of PCR to converge to (a very accurate, by the way) solution
-%!demo
+%! N = 20;
+%! A = diag (linspace (-3.1,3,N)); b = rand (N,1);
+%! y = A \ b;  # y is the true solution
+%! x = pcr (A,b);
+%! printf ("The solution relative error is %g\n", norm (x-y) / norm (y));
 %!
-%!      # Full output from PCR
-%!      # We use this output to plot the convergence history
+%! # You shouldn't be afraid if PCR issues some warning messages in this
+%! # example: watch out in the second example, why it takes N iterations
+%! # of PCR to converge to (a very accurate, by the way) solution
+
+%!demo
+%! # Full output from PCR
+%! # We use this output to plot the convergence history
 %!
-%!      N = 20;
-%!      A = diag(linspace(-3.1,30,N)); b = rand(N,1); X = A\b; #X is the true solution
-%!      [x, flag, relres, iter, resvec] = pcr(A,b);
-%!      printf('The solution relative error is %g\n', norm(x-X)/norm(X));
-%!      title('Convergence history'); xlabel('Iteration'); ylabel('log(||b-Ax||/||b||)');
-%!      semilogy([0:iter],resvec/resvec(1),'o-g;relative residual;');
+%! N = 20;
+%! A = diag (linspace (-3.1,30,N)); b = rand (N,1);
+%! X = A \ b;  # X is the true solution
+%! [x, flag, relres, iter, resvec] = pcr (A,b);
+%! printf ("The solution relative error is %g\n", norm (x-X) / norm (X));
+%! clf;
+%! title ("Convergence history");
+%! xlabel ("Iteration"); ylabel ("log(||b-Ax||/||b||)");
+%! semilogy ([0:iter], resvec/resvec(1), "o-g;relative residual;");
+
 %!demo
-%!
-%!      # Full output from PCR
-%!      # We use indefinite matrix based on the Hilbert matrix, with one
-%!      # strongly negative eigenvalue
-%!      # Hilbert matrix is extremely ill conditioned, so is ours,
-%!      # and that's why PCR WILL have problems
+%! # Full output from PCR
+%! # We use indefinite matrix based on the Hilbert matrix, with one
+%! # strongly negative eigenvalue
+%! # Hilbert matrix is extremely ill conditioned, so is ours,
+%! # and that's why PCR WILL have problems
 %!
-%!      N = 10;
-%!      A = hilb(N); A(1,1)=-A(1,1); b = rand(N,1); X = A\b; #X is the true solution
-%!      printf('Condition number of A is   %g\n', cond(A));
-%!      [x, flag, relres, iter, resvec] = pcr(A,b,[],200);
-%!      if (flag == 3)
-%!        printf('PCR breakdown. System matrix is [close to] singular\n');
-%!      end
-%!      title('Convergence history'); xlabel('Iteration'); ylabel('log(||b-Ax||)');
-%!      semilogy([0:iter],resvec,'o-g;absolute residual;');
+%! N = 10;
+%! A = hilb (N); A(1,1) = -A(1,1); b = rand (N,1);
+%! X = A \ b;  # X is the true solution
+%! printf ("Condition number of A is   %g\n", cond (A));
+%! [x, flag, relres, iter, resvec] = pcr (A,b,[],200);
+%! if (flag == 3)
+%!   printf ("PCR breakdown.  System matrix is [close to] singular\n");
+%! end
+%! clf;
+%! title ("Convergence history");
+%! xlabel ("Iteration"); ylabel ("log(||b-Ax||)");
+%! semilogy ([0:iter], resvec, "o-g;absolute residual;");
+
 %!demo
+%! # Full output from PCR
+%! # We use an indefinite matrix based on the 1-D Laplacian matrix for A,
+%! # and here we have cond(A) = O(N^2)
+%! # That's the reason we need some preconditioner; here we take
+%! # a very simple and not powerful Jacobi preconditioner,
+%! # which is the diagonal of A
 %!
-%!      # Full output from PCR
-%!      # We use an indefinite matrix based on the 1-D Laplacian matrix for A,
-%!      # and here we have cond(A) = O(N^2)
-%!      # That's the reason we need some preconditioner; here we take
-%!      # a very simple and not powerful Jacobi preconditioner,
-%!      # which is the diagonal of A
-%!
-%!      # Note that we use here indefinite preconditioners!
+%! # Note that we use here indefinite preconditioners!
 %!
-%!      N = 100;
-%!      A = zeros(N,N);
-%!      for i=1:N-1 # form 1-D Laplacian matrix
-%!              A(i:i+1,i:i+1) = [2 -1; -1 2];
-%!      endfor
-%!      A = [A, zeros(size(A)); zeros(size(A)), -A];
-%!      b = rand(2*N,1); X = A\b; #X is the true solution
-%!      maxit = 80;
-%!      printf('System condition number is %g\n',cond(A));
-%!      # No preconditioner: the convergence is very slow!
+%! N = 100;
+%! A = zeros (N,N);
+%! for i=1:N-1 # form 1-D Laplacian matrix
+%!   A(i:i+1,i:i+1) = [2 -1; -1 2];
+%! endfor
+%! A = [A, zeros(size(A)); zeros(size(A)), -A];
+%! b = rand (2*N,1);
+%! X = A \ b;  # X is the true solution
+%! maxit = 80;
+%! printf ("System condition number is %g\n", cond (A));
+%! # No preconditioner: the convergence is very slow!
 %!
-%!      [x, flag, relres, iter, resvec] = pcr(A,b,[],maxit);
-%!      title('Convergence history'); xlabel('Iteration'); ylabel('log(||b-Ax||)');
-%!      semilogy([0:iter],resvec,'o-g;NO preconditioning: absolute residual;');
-%!
-%!      pause(1);
-%!      # Test Jacobi preconditioner: it will not help much!!!
+%! [x, flag, relres, iter, resvec] = pcr (A,b,[],maxit);
+%! clf;
+%! title ("Convergence history");
+%! xlabel ("Iteration"); ylabel ("log(||b-Ax||)");
+%! semilogy ([0:iter], resvec, "o-g;NO preconditioning: absolute residual;");
 %!
-%!      M = diag(diag(A)); # Jacobi preconditioner
-%!      [x, flag, relres, iter, resvec] = pcr(A,b,[],maxit,M);
-%!      hold on;
-%!      semilogy([0:iter],resvec,'o-r;JACOBI preconditioner: absolute residual;');
+%! pause (1);
+%! # Test Jacobi preconditioner: it will not help much!!!
 %!
-%!      pause(1);
-%!      # Test nonoverlapping block Jacobi preconditioner: this one should give
-%!      # some convergence speedup!
+%! M = diag (diag (A)); # Jacobi preconditioner
+%! [x, flag, relres, iter, resvec] = pcr (A,b,[],maxit,M);
+%! hold on;
+%! semilogy ([0:iter],resvec,"o-r;JACOBI preconditioner: absolute residual;");
 %!
-%!      M = zeros(N,N);k=4;
-%!      for i=1:k:N # get k x k diagonal blocks of A
-%!              M(i:i+k-1,i:i+k-1) = A(i:i+k-1,i:i+k-1);
-%!      endfor
-%!      M = [M, zeros(size(M)); zeros(size(M)), -M];
-%!      [x, flag, relres, iter, resvec] = pcr(A,b,[],maxit,M);
-%!      semilogy([0:iter],resvec,'o-b;BLOCK JACOBI preconditioner: absolute residual;');
-%!      hold off;
+%! pause (1);
+%! # Test nonoverlapping block Jacobi preconditioner: this one should give
+%! # some convergence speedup!
+%!
+%! M = zeros (N,N); k = 4;
+%! for i=1:k:N # get k x k diagonal blocks of A
+%!   M(i:i+k-1,i:i+k-1) = A(i:i+k-1,i:i+k-1);
+%! endfor
+%! M = [M, zeros(size (M)); zeros(size(M)), -M];
+%! [x, flag, relres, iter, resvec] = pcr (A,b,[],maxit,M);
+%! semilogy ([0:iter], resvec, "o-b;BLOCK JACOBI preconditioner: absolute residual;");
+%! hold off;
+
 %!test
-%!
-%!      #solve small indefinite diagonal system
-%!
-%!      N = 10;
-%!      A = diag(linspace(-10.1,10,N)); b = ones(N,1); X = A\b; #X is the true solution
-%!      [x, flag] = pcr(A,b,[],N+1);
-%!      assert(norm(x-X)/norm(X)<1e-10);
-%!      assert(flag,0);
+%! # solve small indefinite diagonal system
 %!
-%!test
-%!
-%!      #solve tridiagonal system, do not converge in default 20 iterations
-%!      #should perform max allowable default number of iterations
-%!
-%!      N = 100;
-%!      A = zeros(N,N);
-%!      for i=1:N-1 # form 1-D Laplacian matrix
-%!              A(i:i+1,i:i+1) = [2 -1; -1 2];
-%!      endfor
-%!      b = ones(N,1); X = A\b; #X is the true solution
-%!      [x, flag, relres, iter, resvec] = pcr(A,b,1e-12);
-%!      assert(flag,1);
-%!      assert(relres>0.6);
-%!      assert(iter,20);
-%!
+%! N = 10;
+%! A = diag (linspace (-10.1,10,N)); b = ones (N,1);
+%! X = A \ b;  # X is the true solution
+%! [x, flag] = pcr (A,b,[],N+1);
+%! assert (norm (x-X) / norm (X) < 1e-10);
+%! assert (flag, 0);
+
 %!test
-%!
-%!      #solve tridiagonal system with 'prefect' preconditioner
-%!      #converges in one iteration
+%! # solve tridiagonal system, do not converge in default 20 iterations
+%! # should perform max allowable default number of iterations
 %!
-%!      N = 100;
-%!      A = zeros(N,N);
-%!      for i=1:N-1 # form 1-D Laplacian matrix
-%!              A(i:i+1,i:i+1) = [2 -1; -1 2];
-%!      endfor
-%!      b = ones(N,1); X = A\b; #X is the true solution
-%!      [x, flag, relres, iter] = pcr(A,b,[],[],A,b);
-%!      assert(norm(x-X)/norm(X)<1e-6);
-%!      assert(relres<1e-6);
-%!      assert(flag,0);
-%!      assert(iter,1); #should converge in one iteration
+%! N = 100;
+%! A = zeros (N,N);
+%! for i=1:N-1 # form 1-D Laplacian matrix
+%!   A(i:i+1,i:i+1) = [2 -1; -1 2];
+%! endfor
+%! b = ones (N,1);
+%! X = A \ b;  # X is the true solution
+%! [x, flag, relres, iter, resvec] = pcr (A,b,1e-12);
+%! assert (flag, 1);
+%! assert (relres > 0.6);
+%! assert (iter, 20);
+
+%!test
+%! # solve tridiagonal system with "perfect" preconditioner
+%! # converges in one iteration
 %!
+%! N = 100;
+%! A = zeros (N,N);
+%! for i=1:N-1 # form 1-D Laplacian matrix
+%!   A(i:i+1,i:i+1) = [2 -1; -1 2];
+%! endfor
+%! b = ones (N,1);
+%! X = A \ b;  # X is the true solution
+%! [x, flag, relres, iter] = pcr (A,b,[],[],A,b);
+%! assert (norm (x-X) / norm(X) < 1e-6);
+%! assert (relres < 1e-6);
+%! assert (flag, 0);
+%! assert (iter, 1); # should converge in one iteration
+
--- a/scripts/sparse/private/__sprand_impl__.m
+++ b/scripts/sparse/private/__sprand_impl__.m
@@ -39,7 +39,7 @@
     return;
   endif
 
-  [m, n, d, funname, randfun] = deal(varargin{:});
+  [m, n, d, funname, randfun] = deal (varargin{:});
 
   if (!(isscalar (m) && m == fix (m) && m > 0))
     error ("%s: M must be an integer greater than 0", funname);
@@ -60,4 +60,4 @@
   [i, j] = ind2sub ([m, n], idx);
   S = sparse (i, j, randfun (k, 1), m, n);
 
-endfunction
\ No newline at end of file
+endfunction
--- a/scripts/sparse/spaugment.m
+++ b/scripts/sparse/spaugment.m
@@ -90,12 +90,14 @@
   s = [ c * speye(m, m), A; A', sparse(n, n)];
 endfunction
 
+
 %!testif HAVE_UMFPACK
-%! m = 11; n = 10; mn = max(m ,n);
+%! m = 11; n = 10; mn = max (m ,n);
 %! A = spdiags ([ones(mn,1), 10*ones(mn,1), -ones(mn,1)],[-1,0,1], m, n);
 %! x0 = A \ ones (m,1);
 %! s = spaugment (A);
 %! [L, U, P, Q] = lu (s);
 %! x1 = Q * (U \ (L \ (P  * [ones(m,1); zeros(n,1)])));
 %! x1 = x1(end - n + 1 : end);
-%! assert (x1, x0, 1e-6)
+%! assert (x1, x0, 1e-6);
+
--- a/scripts/sparse/spconvert.m
+++ b/scripts/sparse/spconvert.m
@@ -65,3 +65,4 @@
 %!error spconvert ([1 2])
 %!error spconvert ([1 2 3i])
 %!error spconvert ([1 2 3 4 5])
+
--- a/scripts/sparse/spdiags.m
+++ b/scripts/sparse/spdiags.m
@@ -79,16 +79,15 @@
     ## Create new matrix of size mxn using v,c
     [j, i, v] = find (v);
     offset = max (min (c(:), n-m), 0);
-    j = j + offset(i);
-    i = j-c(:)(i);
+    j = j(:) + offset(i(:));
+    i = j - c(:)(i(:));
     idx = i > 0 & i <= m & j > 0 & j <= n;
     A = sparse (i(idx), j(idx), v(idx), m, n);
   endif
 
 endfunction
 
-%!test
-%assert(spdiags(zeros(1,0),1,1,1),0)
 
-%!test
-%assert(spdiags(zeros(0,1),1,1,1),0)
+%!assert (spdiags (zeros (1,0),1,1,1), sparse (0))
+%!assert (spdiags (zeros (0,1),1,1,1), sparse (0))
+%!assert (spdiags ([0.5 -1 0.5], 0:2, 1, 1), sparse(0.5))
--- a/scripts/sparse/speye.m
+++ b/scripts/sparse/speye.m
@@ -32,7 +32,7 @@
 
 function s = speye (m, n)
   if (nargin == 1)
-    if (isvector (m) && length(m) == 2)
+    if (isvector (m) && length (m) == 2)
       n = m(2);
       m = m(1);
     elseif (isscalar (m))
@@ -50,8 +50,10 @@
   s = sparse (1:lo, 1:lo, 1, m, n);
 endfunction
 
-%!assert(issparse(speye(4)))
-%!assert(speye(4),sparse(1:4,1:4,1))
-%!assert(speye(2,4),sparse(1:2,1:2,1,2,4))
-%!assert(speye(4,2),sparse(1:2,1:2,1,4,2))
-%!assert(speye([4,2]),sparse(1:2,1:2,1,4,2))
+
+%!assert (issparse (speye (4)))
+%!assert (speye (4), sparse (1:4,1:4,1))
+%!assert (speye (2,4), sparse (1:2,1:2,1,2,4))
+%!assert (speye (4,2), sparse (1:2,1:2,1,4,2))
+%!assert (speye ([4,2]), sparse (1:2,1:2,1,4,2))
+
--- a/scripts/sparse/spfun.m
+++ b/scripts/sparse/spfun.m
@@ -37,13 +37,14 @@
   if (isa (f, "function_handle") || isa (f, "inline function"))
     y = sparse (i, j, f(v), m, n);
   else
-    y = sparse(i, j, feval (f, v), m, n);
+    y = sparse (i, j, feval (f, v), m, n);
   endif
 
 endfunction
 
-%!assert(spfun('exp',[1,2;3,0]),sparse([exp(1),exp(2);exp(3),0]))
-%!assert(spfun('exp',sparse([1,2;3,0])),sparse([exp(1),exp(2);exp(3),0]))
-%!assert(spfun(@exp,[1,2;3,0]),sparse([exp(1),exp(2);exp(3),0]))
-%!assert(spfun(@exp,sparse([1,2;3,0])),sparse([exp(1),exp(2);exp(3),0]))
 
+%!assert (spfun ("exp", [1,2;3,0]), sparse ([exp(1),exp(2);exp(3),0]))
+%!assert (spfun ("exp", sparse ([1,2;3,0])), sparse ([exp(1),exp(2);exp(3),0]))
+%!assert (spfun (@exp, [1,2;3,0]), sparse ([exp(1),exp(2);exp(3),0]))
+%!assert (spfun (@exp, sparse ([1,2;3,0])), sparse ([exp(1),exp(2);exp(3),0]))
+
--- a/scripts/sparse/spones.m
+++ b/scripts/sparse/spones.m
@@ -35,6 +35,8 @@
 
 endfunction
 
-%!assert(issparse(spones([1,2;3,0])))
-%!assert(spones([1,2;3,0]),sparse([1,1;1,0]))
-%!assert(spones(sparse([1,2;3,0])),sparse([1,1;1,0]))
+
+%!assert (issparse (spones ([1,2;3,0])))
+%!assert (spones ([1,2;3,0]), sparse ([1,1;1,0]))
+%!assert (spones (sparse ([1,2;3,0])), sparse ([1,1;1,0]))
+
--- a/scripts/sparse/sprand.m
+++ b/scripts/sparse/sprand.m
@@ -54,6 +54,7 @@
 
 endfunction
 
+
 %!test
 %! s = sprand (4, 10, 0.1);
 %! assert (size (s), [4, 10]);
@@ -71,10 +72,10 @@
 %!error sprand ()
 %!error sprand (1, 2)
 %!error sprand (1, 2, 3, 4)
-%!error sprand (ones(3), 3, 0.5)
+%!error sprand (ones (3), 3, 0.5)
 %!error sprand (3.5, 3, 0.5)
 %!error sprand (0, 3, 0.5)
-%!error sprand (3, ones(3), 0.5)
+%!error sprand (3, ones (3), 0.5)
 %!error sprand (3, 3.5, 0.5)
 %!error sprand (3, 0, 0.5)
 %!error sprand (3, 3, -1)
--- a/scripts/sparse/sprandn.m
+++ b/scripts/sparse/sprandn.m
@@ -24,7 +24,7 @@
 ## @deftypefnx {Function File} {} sprandn (@var{s})
 ## Generate a random sparse matrix.  The size of the matrix will be
 ## @var{m} by @var{n}, with a density of values given by @var{d}.
-## @var{d} should be between 0 and 1. Values will be normally
+## @var{d} should be between 0 and 1.  Values will be normally
 ## distributed with mean of zero and variance 1.
 ##
 ## If called with a single matrix argument, a random sparse matrix is
@@ -63,10 +63,10 @@
 %!error sprandn ()
 %!error sprandn (1, 2)
 %!error sprandn (1, 2, 3, 4)
-%!error sprandn (ones(3), 3, 0.5)
+%!error sprandn (ones (3), 3, 0.5)
 %!error sprandn (3.5, 3, 0.5)
 %!error sprandn (0, 3, 0.5)
-%!error sprandn (3, ones(3), 0.5)
+%!error sprandn (3, ones (3), 0.5)
 %!error sprandn (3, 3.5, 0.5)
 %!error sprandn (3, 0, 0.5)
 %!error sprandn (3, 3, -1)
--- a/scripts/sparse/sprandsym.m
+++ b/scripts/sparse/sprandsym.m
@@ -22,7 +22,7 @@
 ## @deftypefnx {Function File} {} sprandsym (@var{s})
 ## Generate a symmetric random sparse matrix.  The size of the matrix will be
 ## @var{n} by @var{n}, with a density of values given by @var{d}.
-## @var{d} should be between 0 and 1. Values will be normally
+## @var{d} should be between 0 and 1.  Values will be normally
 ## distributed with mean of zero and variance 1.
 ##
 ## If called with a single matrix argument, a random sparse matrix is
@@ -119,7 +119,7 @@
   ## numerically to avoid overflow.
 
   ## Degenerate case
-  if k == 1
+  if (k == 1)
     r = 1;
     return
   endif
@@ -151,6 +151,7 @@
 
 endfunction
 
+
 %!test
 %! s = sprandsym (10, 0.1);
 %! assert (issparse (s));
@@ -168,7 +169,7 @@
 %% Test input validation
 %!error sprandsym ()
 %!error sprandsym (1, 2, 3)
-%!error sprandsym (ones(3), 0.5)
+%!error sprandsym (ones (3), 0.5)
 %!error sprandsym (3.5, 0.5)
 %!error sprandsym (0, 0.5)
 %!error sprandsym (3, -1)
--- a/scripts/sparse/spstats.m
+++ b/scripts/sparse/spstats.m
@@ -51,7 +51,7 @@
   endif
   if (nargout > 2)
     ## FIXME Variance with count = 0 or 1?
-    diff = S - sparse (i, j, mean(j), n, m);
+    diff = S - sparse (i, j, mean (j), n, m);
     var = sum (diff .* diff) ./ (count - 1);
   endif
 
@@ -59,7 +59,8 @@
 
 
 %!test
-%! [n,m,v] = spstats([1 2 1 2 3 4],[2 2 1 1 1 1]);
-%! assert(n,sparse([4,2]));
-%! assert(m,sparse([10/4,3/2]),10*eps);
-%! assert(v,sparse([5/3,1/2]),10*eps);
+%! [n,m,v] = spstats ([1 2 1 2 3 4],[2 2 1 1 1 1]);
+%! assert (n, sparse ([4,2]));
+%! assert (m, sparse ([10/4,3/2]), 10*eps);
+%! assert (v, sparse ([5/3,1/2]), 10*eps);
+
--- a/scripts/sparse/spy.m
+++ b/scripts/sparse/spy.m
@@ -72,4 +72,5 @@
 %! spy (sprand (10,10, 0.2));
 
 %% Mark graphical function as tested by demo block
-%!assert (1);
+%!assert (1)
+
--- a/scripts/sparse/svds.m
+++ b/scripts/sparse/svds.m
@@ -85,7 +85,7 @@
 ## @end example
 ##
 ## @code{svds} is best for finding only a few singular values from a large
-## sparse matrix.  Otherwise, @code{svd (full(@var{A}))} will likely be more
+## sparse matrix.  Otherwise, @code{svd (full (@var{A}))} will likely be more
 ## efficient.
 ## @end deftypefn
 ## @seealso{svd, eigs}
@@ -98,12 +98,12 @@
     print_usage ();
   endif
 
-  if (ndims(A) > 2)
+  if (ndims (A) > 2)
     error ("svds: A must be a 2D matrix");
   endif
 
   if (nargin < 4)
-    opts.tol = 1e-10 / root2;
+    opts.tol = 0;   ## use ARPACK default
     opts.disp = 0;
     opts.maxit = 300;
   else
@@ -111,7 +111,7 @@
       error ("svds: OPTS must be a structure");
     endif
     if (!isfield (opts, "tol"))
-      opts.tol = 1e-10 / root2;
+      opts.tol = 0;   ## use ARPACK default
     else
       opts.tol = opts.tol / root2;
     endif
@@ -152,7 +152,6 @@
     b_opts = opts;
     ## Call to eigs is always a symmetric matrix by construction
     b_opts.issym = true;
-    b_opts.tol = opts.tol / max_a;
     b_sigma = sigma;
     if (!ischar (b_sigma))
       b_sigma = b_sigma / max_a;
@@ -194,7 +193,7 @@
     ## norm since if we don't we might end up with too many singular
     ## values.
     tol = norma * opts.tol;
-    ind = find(s > tol);
+    ind = find (s > tol);
     if (length (ind) < k)
       ## Too few eigenvalues returned.  Add in any zero eigenvalues of B,
       ## including the nominally negative ones.
@@ -235,19 +234,20 @@
     endif
 
     if (nargout > 3)
-      flag = norm (A*v - u*s, 1) > root2 * opts.tol * norm (A, 1);
+      flag = (flag != 0);
     endif
   endif
 
 endfunction
 
-%!shared n, k, A, u, s, v, opts, rand_state, randn_state
+
+%!shared n, k, A, u, s, v, opts, rand_state, randn_state, tol
 %! n = 100;
 %! k = 7;
 %! A = sparse ([3:n,1:n,1:(n-2)],[1:(n-2),1:n,3:n],[ones(1,n-2),0.4*n*ones(1,n),ones(1,n-2)]);
 %! [u,s,v] = svd (full (A));
 %! s = diag (s);
-%! [~, idx] = sort (abs(s));
+%! [~, idx] = sort (abs (s));
 %! s = s(idx);
 %! u = u(:, idx);
 %! v = v(:, idx);
@@ -262,22 +262,25 @@
 %! [u2,s2,v2,flag] = svds (A,k);
 %! s2 = diag (s2);
 %! assert (flag, !1);
-%! assert (s2, s(end:-1:end-k+1), 1e-10);
+%! tol = 10 * eps() * norm(s2, 1);
+%! assert (s2, s(end:-1:end-k+1), tol);
 %!
 %!testif HAVE_ARPACK, HAVE_UMFPACK
 %! [u2,s2,v2,flag] = svds (A,k,0,opts);
 %! s2 = diag (s2);
 %! assert (flag, !1);
-%! assert (s2, s(k:-1:1), 1e-10);
+%! tol = 10 * eps() * norm(s2, 1);
+%! assert (s2, s(k:-1:1), tol);
 %!
 %!testif HAVE_ARPACK, HAVE_UMFPACK
-%! idx = floor(n/2);
+%! idx = floor (n/2);
 %! % Don't put sigma right on a singular value or there are convergence issues
 %! sigma = 0.99*s(idx) + 0.01*s(idx+1);
 %! [u2,s2,v2,flag] = svds (A,k,sigma,opts);
 %! s2 = diag (s2);
 %! assert (flag, !1);
-%! assert (s2, s((idx+floor(k/2)):-1:(idx-floor(k/2))), 1e-10);
+%! tol = 10 * eps() * norm(s2, 1);
+%! assert (s2, s((idx+floor(k/2)):-1:(idx-floor(k/2))), tol);
 %!
 %!testif HAVE_ARPACK
 %! [u2,s2,v2,flag] = svds (zeros (10), k);
--- a/scripts/sparse/treelayout.m
+++ b/scripts/sparse/treelayout.m
@@ -141,7 +141,7 @@
 
       ## We are in top level separator when we have one child and the
       ## flag is 1
-      if (columns(idx) == 1 && top_level == 1)
+      if (columns (idx) == 1 && top_level == 1)
         s++;
       else
         # We aren't in top level separator now.
@@ -152,7 +152,7 @@
        left_most++;
        x_coordinate_r(par_number) = left_most;
        max_ht = min (max_ht, level);
-       if (length(stk) > 1 && find ((shift(stk,1)-stk) == 0) > 1
+       if (length (stk) > 1 && find ((shift (stk,1) - stk) == 0) > 1
            && stk(end,2) != stk(end-1,2))
           ## Return to the nearest branching the position to return
           ## position is the position on the stack, where should be
@@ -202,6 +202,7 @@
   endif
 endfunction
 
+
 %!test
 %! % Compute a simple tree layout
 %! [x, y, h, s] = treelayout ([0, 1, 2, 2]);
@@ -225,3 +226,4 @@
 %! assert (y, [0, 0, 0, 3]);
 %! assert (h, 0);
 %! assert (s, 1);
+
--- a/scripts/sparse/treeplot.m
+++ b/scripts/sparse/treeplot.m
@@ -116,13 +116,13 @@
       left_most++;
       x_coordinate_r(par_number) = left_most;
       max_ht = min (max_ht, level);
-      if (length(stk) > 1 && find ((shift(stk,1)-stk) == 0) > 1
+      if (length (stk) > 1 && find ((shift (stk,1) - stk) == 0) > 1
           && stk(end,2) != stk(end-1,2))
         ## Return to the nearest branching the position to return
         ## position is the position on the stack, where should be
         ## started further search (there are two nodes which has the
         ## same parent node).
-        position = (find ((shift(stk(:,2),1)-stk(:,2)) == 0))(end) + 1;
+        position = (find ((shift (stk(:,2),1) - stk(:,2)) == 0))(end) + 1;
         par_number_vec = stk(position:end,2);
         ## The vector of removed nodes (the content of stack form
         ## position to end).
@@ -173,7 +173,7 @@
 
     hold ("on");
     ## Plot each tree component in one loop.
-    for i = 2:length(idx)
+    for i = 2:length (idx)
       ## Tree component start.
       istart = idx(i-1) + 1;
       ## Tree component end.
@@ -196,10 +196,14 @@
 
 endfunction
 
-%!demo
-%! % Plot a simple tree plot
-%! treeplot([2 4 2 0 6 4 6])
 
 %!demo
+%! clf;
+%! treeplot ([2 4 2 0 6 4 6]);
+%! % Plot a simple tree plot
+
+%!demo
+%! clf;
+%! treeplot ([2 4 2 0 6 4 6], "b+", "g");
 %! % Plot a simple tree plot defining the edge and node styles
-%! treeplot([2 4 2 0 6 4 6], "b+", "g")
+
--- a/scripts/specfun/bessel.m
+++ b/scripts/specfun/bessel.m
@@ -27,21 +27,21 @@
 ## @table @code
 ## @item besselj
 ## Bessel functions of the first kind.  If the argument @var{opt} is supplied,
-## the result is multiplied by @code{exp(-abs(imag(x)))}.
+## the result is multiplied by @code{exp (-abs (imag (x)))}.
 ##
 ## @item bessely
 ## Bessel functions of the second kind.  If the argument @var{opt} is supplied,
-## the result is multiplied by @code{exp(-abs(imag(x)))}.
+## the result is multiplied by @code{exp (-abs (imag (x)))}.
 ##
 ## @item besseli
 ## Modified Bessel functions of the first kind.  If the argument @var{opt} is
 ## supplied,
-## the result is multiplied by @code{exp(-abs(real(x)))}.
+## the result is multiplied by @code{exp (-abs (real (x)))}.
 ##
 ## @item besselk
 ## Modified Bessel functions of the second kind.  If the argument @var{opt} is
 ## supplied,
-## the result is multiplied by @code{exp(x)}.
+## the result is multiplied by @code{exp (x)}.
 ##
 ## @item besselh
 ## Compute Hankel functions of the first (@var{k} = 1) or second (@var{k}
@@ -91,4 +91,5 @@
   error ("bessel: you must use besselj, bessely, besseli, or besselk");
 endfunction
 
+
 %!error bessel ()
--- a/scripts/specfun/beta.m
+++ b/scripts/specfun/beta.m
@@ -31,6 +31,7 @@
 ## @end example
 ##
 ## @end ifnottex
+## @seealso{betaln, betainc}
 ## @end deftypefn
 
 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
@@ -55,28 +56,30 @@
 
 endfunction
 
+
 %!test
-%! a=[1, 1.5, 2, 3];
-%! b=[4, 3, 2, 1];
-%! v1=beta(a,b);
-%! v2=beta(b,a);
-%! v3=gamma(a).*gamma(b)./gamma(a+b);
-%! assert(all(abs(v1-v2)<sqrt(eps)) && all(abs(v2-v3)<sqrt(eps)));
+%! a = [1, 1.5, 2, 3];
+%! b = [4, 3, 2, 1];
+%! v1 = beta (a,b);
+%! v2 = beta (b,a);
+%! v3 = gamma (a).*gamma (b) ./ gamma (a+b);
+%! assert (v1, v2, sqrt (eps));
+%! assert (v2, v3, sqrt (eps));
 
-%!error beta();
-
-%!error beta(1);
-
-%!assert (1, beta (1, 1))
+%!assert (beta (1, 1), 1)
 
 %!test
 %! a = 2:10;
 %! tol = 10 * max (a) * eps;
-%! assert (-a, beta (-1./a, 1), tol)
-%! assert (-a, beta (1, -1./a), tol)
+%! assert (-a, beta (-1./a, 1), tol);
+%! assert (-a, beta (1, -1./a), tol);
 
 %!test
 %! a = 0.25 + (0:5) * 0.5;
 %! tol = 10 * max (a) * eps;
-%! assert (zeros (size (a)), beta (a, -a), tol)
-%! assert (zeros (size (a)), beta (-a, a), tol)
+%! assert (zeros (size (a)), beta (a, -a), tol);
+%! assert (zeros (size (a)), beta (-a, a), tol);
+
+%!error beta ()
+%!error beta (1)
+
--- a/scripts/specfun/betaln.m
+++ b/scripts/specfun/betaln.m
@@ -50,7 +50,7 @@
 endfunction
 
 
-%!assert (betaln (3,4), log (beta(3,4)),eps);
+%!assert (betaln (3,4), log (beta (3,4)), eps)
 
 %% Test input validation
 %!error (betaln (1))
new file mode 100644
--- /dev/null
+++ b/scripts/specfun/ellipke.m
@@ -0,0 +1,153 @@
+## Copyright (C) 2001 David Billinghurst <David.Billinghurst@riotinto.com>
+## Copyright (C) 2001 Paul Kienzle <pkienzle@users.sf.net>
+## Copyright (C) 2003 Jaakko Ruohio
+##
+## 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} {} ellipke (@var{m})
+## @deftypefnx {Function File} {} ellipke (@var{m}, @var{tol})
+## @deftypefnx {Function File} {[@var{k}, @var{e}] =} ellipke (@dots{})
+## Compute complete elliptic integral of the first K(@var{m}) and second
+## E(@var{m}) kind.
+##
+## @var{m} is either real array or scalar with 0 <= m <= 1.
+##
+## @var{tol} is currently ignored (@sc{Matlab} uses this to allow faster,
+## less accurate approximation).
+##
+## Ref: Abramowitz, Milton and Stegun, Irene A. Handbook of Mathematical
+## Functions, Dover, 1965, Chapter 17.
+## @seealso{ellipj}
+## @end deftypefn
+
+function [k, e] = ellipke (m)
+
+  if (nargin < 1 || nargin > 2)
+    print_usage ();
+  endif
+
+  k = e = zeros (size (m));
+  m = m(:);
+  if any (!isreal (m))
+    error ("ellipke must have real m");
+  endif
+  if any (m > 1)
+    error ("ellipke must have m <= 1");
+  endif
+
+  Nmax = 16;
+  idx = find (m == 1);
+  if (!isempty (idx))
+    k(idx) = Inf;
+    e(idx) = 1;
+  endif
+
+  idx = find (m == -Inf);
+  if (!isempty (idx))
+    k(idx) = 0;
+    e(idx) = Inf;
+  endif
+
+  ## Arithmetic-Geometric Mean (AGM) algorithm
+  ## ( Abramowitz and Stegun, Section 17.6 )
+  idx = find (m != 1 & m != -Inf);
+  if (!isempty (idx))
+    idx_neg = find (m < 0 & m != -Inf);
+    mult_k = 1./sqrt (1 - m(idx_neg));
+    mult_e = sqrt (1 - m(idx_neg));
+    m(idx_neg) = -m(idx_neg)./(1 - m(idx_neg));
+    a = ones (length (idx), 1);
+    b = sqrt (1 - m(idx));
+    c = sqrt (m(idx));
+    f = 0.5;
+    sum = f*c.*c;
+    for n = 2:Nmax
+      t = (a + b)/2;
+      c = (a - b)/2;
+      b = sqrt (a.*b);
+      a = t;
+      f = f * 2;
+      sum = sum + f*c.*c;
+      if (all (c./a < eps)) break; endif
+    endfor
+    if (n >= Nmax) error ("ellipke: not enough workspace"); endif
+    k(idx) = 0.5*pi./a;
+    e(idx) = 0.5*pi.*(1 - sum)./a;
+    k(idx_neg) = mult_k.*k(idx_neg);
+    e(idx_neg) = mult_e.*e(idx_neg);
+  endif
+
+endfunction
+
+%% Test complete elliptic functions of first and second kind
+%% against "exact" solution from Mathematica 3.0
+%!test
+%! m = [0.0; 0.01; 0.1; 0.5; 0.9; 0.99; 1.0 ];
+%! [k,e] = ellipke (m);
+%!
+%! # K(1.0) is really infinity - see below
+%! k_exp = [1.5707963267948966192;
+%!          1.5747455615173559527;
+%!          1.6124413487202193982;
+%!          1.8540746773013719184;
+%!          2.5780921133481731882;
+%!          3.6956373629898746778;
+%!          0.0 ];
+%! e_exp = [1.5707963267948966192;
+%!          1.5668619420216682912;
+%!          1.5307576368977632025;
+%!          1.3506438810476755025;
+%!          1.1047747327040733261;
+%!          1.0159935450252239356;
+%!          1.0 ];
+%! if k(7)==Inf, k(7)=0; endif;
+%! assert (k, k_exp, 8*eps);
+%! assert (e, e_exp, 8*eps);
+
+%% Test against A&S Table 17.1
+%!test
+%! m = [0:5:50]'/100;
+%! k_exp = [1.570796326794897;
+%!          1.591003453790792;
+%!          1.612441348720219;
+%!          1.635256732264580;
+%!          1.659623598610528;
+%!          1.685750354812596;
+%!          1.713889448178791;
+%!          1.744350597225613;
+%!          1.777519371491253;
+%!          1.813883936816983;
+%!          1.854074677301372 ];
+%! e_exp = [1.570796327;
+%!          1.550973352;
+%!          1.530757637;
+%!          1.510121831;
+%!          1.489035058;
+%!          1.467462209;
+%!          1.445363064;
+%!          1.422691133;
+%!          1.399392139;
+%!          1.375401972;
+%!          1.350643881 ];
+%! [k,e] = ellipke (m);
+%! assert (k, k_exp, 1e-15);
+%! assert (e, e_exp, 1e-8);
+
+%% Test input validation
+%!error ellipke ()
+%!error ellipke (1,2,3)
new file mode 100644
--- /dev/null
+++ b/scripts/specfun/expint.m
@@ -0,0 +1,201 @@
+## Copyright (C) 2006 Sylvain Pelissier <sylvain.pelissier@gmail.com>
+##
+## 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} {} expint (@var{x})
+## Compute the exponential integral,
+## @tex
+## $$
+##  E_1 (x) = \int_x^\infty {e^{-t} \over t} dt.
+## $$
+## @end tex
+## @ifnottex
+##
+## @example
+## @group
+##               infinity
+##              /
+## expint (x) = | exp (-t)/t dt
+##              /
+##             x
+## @end group
+## @end example
+##
+## @end ifnottex
+## @end deftypefn
+
+function y = expint (x)
+
+  if (nargin != 1)
+    print_usage ();
+  endif
+
+  y = expint_E1 (x);
+
+endfunction
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{y} =} expint_E1 (@var{x})
+## Compute the exponential integral,
+## @verbatim
+##                    infinity
+##                   /
+##       expint(x) = | exp(-t)/t dt
+##                   /
+##                  x
+## @end verbatim
+## @end deftypefn
+
+function y = expint_E1 (x)
+
+  if (nargin != 1)
+    print_usage ();
+  endif
+
+  y = x;
+
+  idx = (imag (x) > 0 & imag (x) != 0);
+  y(idx) = -expint_Ei (-y(idx)) - i.*pi;
+
+  idx = (imag (x) < 0 & imag (x) != 0);
+  y(idx) = -expint_Ei (-y(idx)) + i.*pi;
+
+  idx = (real (x) >= 0 & imag (x) == 0);
+  y(idx) = -expint_Ei (-y(idx));
+
+  idx = (real (x) < 0 & imag (x) == 0);
+  y(idx) = -expint_Ei (-y(idx)) - i.*pi;
+
+endfunction
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{y} =} expint_Ei (@var{x})
+## Compute the exponential integral,
+## @verbatim
+##                      infinity
+##                     /
+##    expint_Ei(x) = - | exp(t)/t dt
+##                     /
+##                     -x
+## @end verbatim
+## @end deftypefn
+
+function y = expint_Ei (x)
+
+  if (nargin != 1)
+    print_usage ();
+  endif
+
+  y = zeros (size (x));
+  F = @(x) exp (-x)./x;
+  s = prod (size (x));
+
+  for t = 1:s;
+    if (x(t) < 0 && imag (x(t)) == 0)
+      y(t) = -quad (F, -x(t), Inf);
+    else
+      if (abs (x(t)) > 2 && imag (x(t)) == 0)
+        y(t) = expint_Ei (2) - quad (F, -x(t), -2);
+      else
+        if (abs (x(t)) >= 10)
+          if (imag (x(t)) <= 0)
+            a1 = 4.03640;
+            a2 = 1.15198;
+            b1 = 5.03637;
+            b2 = 4.19160;
+            y(t) = -(x(t).^2 - a1.*x(t) + a2) ...
+                   ./ ((x(t).^2 - b1.*x(t) + b2) .* (-x(t)) .* exp (-x(t))) ...
+                   - i.*pi;
+          else
+            y(t) = conj (expint_Ei (conj (x(t))));
+          endif;
+        ## Serie Expansion
+        else
+          for k = 1:100;
+            y(t) = y(t) + x(t).^k ./ (k.*factorial (k));
+          endfor
+          y(t) = 0.577215664901532860606512090082402431 + log (x(t)) + y(t);
+        endif
+      endif
+    endif
+  endfor
+endfunction
+
+%% Test against A&S Table 5.1
+%!test
+%! x = [5:5:50]'/100;
+%! gamma = 0.5772156649;
+%! y_exp = [0.9876375971;
+%!          0.9755453033;
+%!          0.9637156702;
+%!          0.9521414833;
+%!          0.9408157528;
+%!          0.9297317075;
+%!          0.9188827858;
+%!          0.9082626297;
+%!          0.8978650778;
+%!          0.8876841584 ];
+%! y = (expint (x) + log(x) + gamma) ./ x;
+%! assert (y, y_exp, 1e-9);
+%!test
+%! x = [50:5:95]'/100;
+%! y_exp = [0.559773595;
+%!          0.503364081;
+%!          0.454379503;
+%!          0.411516976;
+%!          0.373768843;
+%!          0.340340813;
+%!          0.310596579;
+%!          0.284019269;
+%!          0.260183939;
+%!          0.238737524 ];
+%! y = expint (x);
+%! assert (y, y_exp, 1e-9);
+%!test
+%! x = [100:5:145]'/100;
+%! y_exp = [0.219383934;
+%!          0.201872813;
+%!          0.185990905;
+%!          0.171555354;
+%!          0.158408437;
+%!          0.146413373;
+%!          0.135450958;
+%!          0.125416844;
+%!          0.116219313;
+%!          0.107777440 ];
+%! y = expint (x);
+%! assert (y, y_exp, 1e-9);
+%!test
+%! x = [150:5:200]'/100;
+%! y_exp = [0.100019582;
+%!          0.092882108;
+%!          0.086308334;
+%!          0.080247627;
+%!          0.074654644;
+%!          0.069488685;
+%!          0.064713129;
+%!          0.060294967;
+%!          0.056204378;
+%!          0.052414380;
+%!          0.048900511 ];
+%! y = expint (x);
+%! assert (y, y_exp, 1e-9);
+
+%% Test input validation
+%!error expint ()
+%!error expint (1,2)
--- a/scripts/specfun/factor.m
+++ b/scripts/specfun/factor.m
@@ -76,20 +76,21 @@
   ## Determine muliplicity.
   if (nargout > 1)
     idx = find ([0, x] != [x, 0]);
-    x = x(idx(1:length(idx)-1));
+    x = x(idx(1:length (idx)-1));
     n = diff (idx);
   endif
 
 endfunction
 
+
+%!assert (factor (1), 1)
 %!test
-%!  assert(factor(1),1);
-%!  for i=2:20
-%!     p = factor(i);
-%!     assert(prod(p),i);
-%!     assert(all(isprime(p)));
-%!     [p,n] = factor(i);
-%!     assert(prod(p.^n),i);
-%!     assert(all([0,p]!=[p,0]));
-%!  endfor
+%! for i = 2:20
+%!   p = factor (i);
+%!   assert (prod (p), i);
+%!   assert (all (isprime (p)));
+%!   [p,n] = factor (i);
+%!   assert (prod (p.^n), i);
+%!   assert (all ([0,p] != [p,0]));
+%! endfor
 
--- a/scripts/specfun/factorial.m
+++ b/scripts/specfun/factorial.m
@@ -35,8 +35,11 @@
   x = round (gamma (n+1));
 endfunction
 
-%!assert (factorial(5), prod(1:5))
-%!assert (factorial([1,2;3,4]), [1,2;6,24])
-%!assert (factorial(70), exp(sum(log(1:70))), -128*eps)
-%!fail ('factorial(5.5)', "must all be non-negative integers")
-%!fail ('factorial(-3)', "must all be non-negative integers")
+
+%!assert (factorial (5), prod (1:5))
+%!assert (factorial ([1,2;3,4]), [1,2;6,24])
+%!assert (factorial (70), exp (sum (log (1:70))), -128*eps)
+
+%!fail ("factorial (5.5)", "must all be non-negative integers")
+%!fail ("factorial (-3)", "must all be non-negative integers")
+
--- a/scripts/specfun/isprime.m
+++ b/scripts/specfun/isprime.m
@@ -80,8 +80,10 @@
 endfunction
 
 
-%!assert (isprime (4), logical (0));
-%!assert (isprime (3), logical (1));
-%!assert (isprime (magic (3)), logical ([0, 0, 0; 1, 1, 1; 0, 0, 1]));
+%!assert (isprime (3), true)
+%!assert (isprime (4), false)
+%!assert (isprime (magic (3)), logical ([0, 0, 0; 1, 1, 1; 0, 0, 1]))
+
 %!error isprime ()
 %!error isprime (1, 2)
+
--- a/scripts/specfun/lcm.m
+++ b/scripts/specfun/lcm.m
@@ -51,11 +51,11 @@
 
 endfunction
 
-%!assert(lcm (3, 5, 7, 15) == 105);
+
+%!assert (lcm (3, 5, 7, 15), 105)
 
 %!error lcm ();
-
 %!test
 %! s.a = 1;
-%! fail("lcm (s)");
+%! fail ("lcm (s)");
 
--- a/scripts/specfun/legendre.m
+++ b/scripts/specfun/legendre.m
@@ -196,7 +196,7 @@
   ## http://en.wikipedia.org/wiki/Associated_Legendre_function
 
   overflow = false;
-  retval = zeros([n+1, size(x)]);
+  retval = zeros ([n+1, size(x)]);
   for m = 1:n
     lpm1 = scale;
     lpm2 = (2*m-1) .* x .* scale;
@@ -222,7 +222,7 @@
       ## normalization == "sch" or normalization == "norm"
       scale = scale / sqrt ((n-m+1)*(n+m))*(2*m-1);
     endif
-    scale = scale .* sqrt(1-x.^2);
+    scale = scale .* sqrt (1-x.^2);
   endfor
 
   retval(n+1,:) = scale(:);
@@ -286,7 +286,7 @@
 
 %!test
 %! result = legendre (0, 0:0.1:1);
-%! assert (result, full(ones(1,11)));
+%! assert (result, full (ones (1,11)));
 
 %!test
 %! result = legendre (3, [-1,0,1;1,0,-1]);
@@ -303,13 +303,14 @@
 %! assert (result, expected);
 
 %% Check correct invocation
-%!error legendre ();
-%!error legendre (1);
-%!error legendre (1,2,3,4);
-%!error legendre ([1, 2], [-1, 0, 1]);
-%!error legendre (-1, [-1, 0, 1]);
-%!error legendre (1.1, [-1, 0, 1]);
-%!error legendre (1, [-1+i, 0, 1]);
-%!error legendre (1, [-2, 0, 1]);
-%!error legendre (1, [-1, 0, 2]);
-%!error legendre (1, [-1, 0, 1], "badnorm");
+%!error legendre ()
+%!error legendre (1)
+%!error legendre (1,2,3,4)
+%!error legendre ([1, 2], [-1, 0, 1])
+%!error legendre (-1, [-1, 0, 1])
+%!error legendre (1.1, [-1, 0, 1])
+%!error legendre (1, [-1+i, 0, 1])
+%!error legendre (1, [-2, 0, 1])
+%!error legendre (1, [-1, 0, 2])
+%!error legendre (1, [-1, 0, 1], "badnorm")
+
--- a/scripts/specfun/module.mk
+++ b/scripts/specfun/module.mk
@@ -4,6 +4,8 @@
   specfun/bessel.m \
   specfun/beta.m \
   specfun/betaln.m \
+  specfun/ellipke.m \
+  specfun/expint.m \
   specfun/factor.m \
   specfun/factorial.m \
   specfun/isprime.m \
--- a/scripts/specfun/nchoosek.m
+++ b/scripts/specfun/nchoosek.m
@@ -141,7 +141,7 @@
 
 
 %!assert (nchoosek (80,10), bincoeff (80,10))
-%!assert (nchoosek(1:5,3), [1:3;1,2,4;1,2,5;1,3,4;1,3,5;1,4,5;2:4;2,3,5;2,4,5;3:5])
+%!assert (nchoosek (1:5,3), [1:3;1,2,4;1,2,5;1,3,4;1,3,5;1,4,5;2:4;2,3,5;2,4,5;3:5])
 
 %% Test input validation
 %!warning nchoosek (100,45);
--- a/scripts/specfun/nthroot.m
+++ b/scripts/specfun/nthroot.m
@@ -81,11 +81,12 @@
 
 endfunction
 
-%!assert (nthroot(-32,5), -2);
-%!assert (nthroot(81,4), 3);
-%!assert (nthroot(Inf,4), Inf);
-%!assert (nthroot(-Inf,7), -Inf);
-%!assert (nthroot(-Inf,-7), 0);
+
+%!assert (nthroot (-32,5), -2);
+%!assert (nthroot (81,4), 3);
+%!assert (nthroot (Inf,4), Inf);
+%!assert (nthroot (-Inf,7), -Inf);
+%!assert (nthroot (-Inf,-7), 0);
 
 %% Test input validation
 %!error (nthroot ())
--- a/scripts/specfun/perms.m
+++ b/scripts/specfun/perms.m
@@ -24,7 +24,7 @@
 ## result has size @code{factorial (@var{n}) * @var{n}}, where @var{n}
 ## is the length of @var{v}.
 ##
-## As an example, @code{perms([1, 2, 3])} returns the matrix
+## As an example, @code{perms ([1, 2, 3])} returns the matrix
 ##
 ## @example
 ## @group
@@ -42,32 +42,34 @@
   if (nargin != 1)
     print_usage ();
   endif
-  v = v(:);
-  n = length (v);
+  vidx = [1:length(v)]';
+  n = length (vidx);
 
   if (n == 0)
-    A = [];
+    p = [];
   else
-    A = v(1);
+    p = vidx(1);
     for j = 2:n
-      B = A;
-      A = zeros (prod (2:j), n, class (v));
-      k = size (B, 1);
+      B = p;
+      p = zeros (prod (2:j), n);
+      k = rows (B);
       idx = 1:k;
       for i = j:-1:1
-        A(idx,1:i-1) = B(:,1:i-1);
-        A(idx,i) = v(j);
-        A(idx,i+1:j) = B(:,i:j-1);
+        p(idx,1:i-1) = B(:,1:i-1);
+        p(idx,i) = vidx(j);
+        p(idx,i+1:j) = B(:,i:j-1);
         idx += k;
       endfor
     endfor
   endif
+  A = v(p);
 endfunction
 
-%!error perms ();
-%!error perms (1, 2);
 
-%!assert (perms ([1,2,3]), [1,2,3;2,1,3;1,3,2;2,3,1;3,1,2;3,2,1]);
-%!assert (perms (1:3), perms ([1,2,3]));
+%!assert (perms ([1,2,3]), [1,2,3;2,1,3;1,3,2;2,3,1;3,1,2;3,2,1])
+%!assert (perms ("abc"), ["abc"; "bac"; "acb"; "bca"; "cab"; "cba"])
+%!assert (perms (int8 ([1,2,3])), int8 ([1,2,3;2,1,3;1,3,2;2,3,1;3,1,2;3,2,1]))
 
-%!assert (perms (int8([1,2,3])), int8([1,2,3;2,1,3;1,3,2;2,3,1;3,1,2;3,2,1]));
+%!error perms ()
+%!error perms (1, 2)
+
--- a/scripts/specfun/pow2.m
+++ b/scripts/specfun/pow2.m
@@ -54,16 +54,17 @@
 
 endfunction
 
+
 %!test
 %! x = [3, 0, -3];
 %! v = [8, 1, .125];
-%! assert(all (abs (pow2 (x) - v) < sqrt (eps)));
+%! assert (pow2 (x), v, sqrt (eps));
 
 %!test
 %! x = [3, 0, -3, 4, 0, -4, 5, 0, -5];
 %! y = [-2, -2, -2, 1, 1, 1, 3, 3, 3];
 %! z = x .* (2 .^ y);
-%! assert(all (abs (pow2 (x,y) - z) < sqrt (eps)));
+%! assert (pow2 (x,y), z, sqrt (eps));
 
-%!error pow2();
+%!error pow2 ()
 
--- a/scripts/specfun/primes.m
+++ b/scripts/specfun/primes.m
@@ -31,7 +31,7 @@
 ## $k \log (5 k)$.
 ## @end tex
 ## @ifnottex
-## k*log(5*k).
+## k*log (5*k).
 ## @end ifnottex
 ## @seealso{list_primes, isprime}
 ## @end deftypefn
@@ -61,7 +61,7 @@
     sievem = true (1, lenm);      # assume every number of form 6n-1 is prime
     sievep = true (1, lenp);      # assume every number of form 6n+1 is prime
 
-    for i = 1:(sqrt(n)+1)/6       # check up to sqrt(n)
+    for i = 1:(sqrt (n)+1)/6      # check up to sqrt (n)
       if (sievem(i))              # if i is prime, eliminate multiples of i
         sievem(7*i-1:6*i-1:lenm) = false;
         sievep(5*i-1:6*i-1:lenp) = false;
@@ -71,11 +71,11 @@
         sievem(5*i+1:6*i+1:lenm) = false;
       endif
     endfor
-    x = sort([2, 3, 6*find(sievem)-1, 6*find(sievep)+1]);
+    x = sort ([2, 3, 6*find(sievem)-1, 6*find(sievep)+1]);
   elseif (n > 352)                # nothing magical about 352; must be >2
     len = floor ((n-1)/2);        # length of the sieve
     sieve = true (1, len);        # assume every odd number is prime
-    for i = 1:(sqrt(n)-1)/2       # check up to sqrt(n)
+    for i = 1:(sqrt (n)-1)/2      # check up to sqrt (n)
       if (sieve(i))               # if i is prime, eliminate multiples of i
         sieve(3*i+1:2*i+1:len) = false; # do it
       endif
@@ -93,10 +93,10 @@
 
 endfunction
 
-%!error primes ();
-%!error primes (1, 2);
+
+%!assert (size (primes (350)), [1, 70])
+%!assert (primes (357)(end), 353)
 
-%!assert (size (primes (350)), [1, 70]);
-%!assert (size (primes (350)), [1, 70]);
+%!error primes ()
+%!error primes (1, 2)
 
-%!assert (primes (357)(end), 353);
--- a/scripts/specfun/reallog.m
+++ b/scripts/specfun/reallog.m
@@ -33,8 +33,11 @@
   endif
 endfunction
 
-%!assert (log(1:5),reallog(1:5))
+
+%!assert (log (1:5), reallog (1:5))
 %!test
 %! x = rand (10,10);
-%! assert (log(x),reallog(x))
-%!error (reallog(-1))
+%! assert (log (x),reallog (x));
+
+%!error <produced complex result> reallog (-1)
+
--- a/scripts/specfun/realpow.m
+++ b/scripts/specfun/realpow.m
@@ -35,11 +35,14 @@
   endif
 endfunction
 
+
 %!assert (power (1:10, 0.5:0.5:5), realpow (1:10, 0.5:0.5:5))
 %!assert ([1:10] .^ [0.5:0.5:5], realpow (1:10, 0.5:0.5:5))
 %!test
 %! x = rand (10,10);
 %! y = randn (10,10);
-%! assert (x.^y,realpow(x,y))
-%!assert (realpow(1i,2),-1)
-%!error (realpow(-1, 1/2))
+%! assert (x.^y, realpow (x,y));
+%!assert (realpow (1i,2), -1)
+
+%!error <produced complex result> realpow (-1, 1/2)
+
--- a/scripts/specfun/realsqrt.m
+++ b/scripts/specfun/realsqrt.m
@@ -33,8 +33,11 @@
   endif
 endfunction
 
-%!assert (sqrt(1:5),realsqrt(1:5))
+
+%!assert (sqrt (1:5), realsqrt (1:5))
 %!test
 %! x = rand (10,10);
-%! assert (sqrt(x),realsqrt(x))
-%!error (realsqrt(-1))
+%! assert (sqrt (x), realsqrt (x));
+
+%!error <produced complex result> realsqrt (-1)
+
--- a/scripts/special-matrix/hadamard.m
+++ b/scripts/special-matrix/hadamard.m
@@ -165,7 +165,7 @@
 %!assert (hadamard (2), [1,1;1,-1])
 %!test
 %! for n = [1,2,4,8,12,24,48,20,28,2^9]
-%!   h = hadamard(n);
+%!   h = hadamard (n);
 %!   assert (norm (h*h' - n*eye (n)), 0);
 %! endfor
 
--- a/scripts/special-matrix/hankel.m
+++ b/scripts/special-matrix/hankel.m
@@ -91,8 +91,8 @@
 %!assert (hankel (1:3,3:4), [1,2;2,3;3,4])
 %!assert (hankel (1:3,4:6), [1,2,3;2,3,5;3,5,6])
 
-%!error hankel ();
-%!error hankel (1, 2, 3);
+%!error hankel ()
+%!error hankel (1, 2, 3)
 %!error <C must be a vector> hankel ([1, 2; 3, 4])
 %!error <C and R must be vectors> hankel (1:4, [1, 2; 3, 4])
 
--- a/scripts/special-matrix/hilb.m
+++ b/scripts/special-matrix/hilb.m
@@ -75,5 +75,5 @@
 
 %!error hilb ()
 %!error hilb (1, 2)
-%!error <N must be a scalar integer> hilb (ones(2))
+%!error <N must be a scalar integer> hilb (ones (2))
 
--- a/scripts/special-matrix/invhilb.m
+++ b/scripts/special-matrix/invhilb.m
@@ -120,7 +120,7 @@
 %!            240 , -2700, 6480 , -4200;
 %!            -140, 1680 , -4200, 2800];
 %! assert (invhilb (4), result4);
-%!assert (abs (invhilb (7) * hilb (7) - eye (7)) < sqrt (eps))
+%!assert (invhilb (7) * hilb (7), eye (7), sqrt (eps))
 
 %!error invhilb ()
 %!error invhilb (1, 2)
--- a/scripts/special-matrix/magic.m
+++ b/scripts/special-matrix/magic.m
@@ -26,7 +26,7 @@
 ## Note: @var{n} must be greater than 2 for the magic square to exist.
 ## @end deftypefn
 
-function A = magic(n)
+function A = magic (n)
 
   if (nargin != 1)
     print_usage ();
@@ -80,13 +80,13 @@
 
 
 %!test
-%! for i=3:30
+%! for i = 3:30
 %!   A = magic (i);
 %!   assert (norm(diff([sum(diag(A)),sum(diag(flipud(A))),sum(A),sum(A')])),0);
 %! endfor
 
 %!assert (isempty (magic (0)))
-%!assert (magic(1), 1)
+%!assert (magic (1), 1)
 
 %% Test input validation
 %!error magic ()
--- a/scripts/special-matrix/rosser.m
+++ b/scripts/special-matrix/rosser.m
@@ -44,5 +44,9 @@
 
 endfunction
 
-%!assert (size(rosser()), [8,8])
-%!error (rosser(1))
+
+%!assert (size (rosser ()), [8,8])
+%!assert (rosser ()([1, end]), [611, 99])
+
+%!error (rosser (1))
+
--- a/scripts/special-matrix/toeplitz.m
+++ b/scripts/special-matrix/toeplitz.m
@@ -105,8 +105,8 @@
     ridx = ridx(ridx > 1);
 
     ## Form matrix.
-    retval = spdiags(repmat (c(cidx),nr,1),1-cidx,nr,nc) + ...
-             spdiags(repmat (r(ridx),nr,1),ridx-1,nr,nc);
+    retval = spdiags (repmat (c(cidx),nr,1),1-cidx,nr,nc) + ...
+             spdiags (repmat (r(ridx),nr,1),ridx-1,nr,nc);
   else
     ## Concatenate data into a single column vector.
     data = [r(end:-1:2)(:); c(:)];
--- a/scripts/special-matrix/vander.m
+++ b/scripts/special-matrix/vander.m
@@ -79,17 +79,17 @@
 %!test
 %! c = [0,1,2,3];
 %! expect = [0,0,0,1; 1,1,1,1; 8,4,2,1; 27,9,3,1];
-%! assert(vander (c), expect);
+%! assert (vander (c), expect);
 
 %!assert (vander (1), 1)
 %!assert (vander ([1, 2, 3]), vander ([1; 2; 3]))
 %!assert (vander ([1, 2, 3]), [1, 1, 1; 4, 2, 1; 9, 3, 1])
 %!assert (vander ([1, 2, 3]*i), [-1, i, 1; -4, 2i, 1; -9, 3i, 1])
 
-%!assert(vander (2, 3), [4, 2, 1])
-%!assert(vander ([2, 3], 3), [4, 2, 1; 9, 3, 1])
+%!assert (vander (2, 3), [4, 2, 1])
+%!assert (vander ([2, 3], 3), [4, 2, 1; 9, 3, 1])
 
-%!error vander ();
-%!error vander (1, 2, 3);
-%!error <polynomial C must be a vector> vander ([1, 2; 3, 4]);
+%!error vander ()
+%!error vander (1, 2, 3)
+%!error <polynomial C must be a vector> vander ([1, 2; 3, 4])
 
--- a/scripts/startup/__finish__.m
+++ b/scripts/startup/__finish__.m
@@ -23,9 +23,9 @@
 
 ## Check for the existence of the function/script, @file{finish}, in the
 ## path or current working directory and execute it.  This function is
-## intended to be excecuted upon a clean exit form Octave.  This is
+## intended to be excecuted upon a clean exit from Octave.  This is
 ## accomplished in the system script @file{startup/octaverc} by use of
-## the built-in function @code{onexit}.
+## the built-in function @code{atexit}.
 
 function __finish__ ()
 
@@ -36,5 +36,7 @@
 
 endfunction
 
+
+
 ## No test needed for internal helper function.
 %!assert (1)
--- a/scripts/statistics/base/center.m
+++ b/scripts/statistics/base/center.m
@@ -65,19 +65,21 @@
 
 endfunction
 
-%!assert(center ([1,2,3]), [-1,0,1])
-%!assert(center (single([1,2,3])), single([-1,0,1]))
-%!assert(center (int8 ([1,2,3])), [-1,0,1])
-%!assert(center (logical ([1, 0, 0, 1])), [0.5, -0.5, -0.5, 0.5])
-%!assert(center (ones (3,2,0,2)), zeros (3,2,0,2))
-%!assert(center (ones (3,2,0,2, 'single')), zeros (3,2,0,2, 'single'))
-%!assert(center (magic (3)), [3,-4,1;-2,0,2;-1,4,-3])
-%!assert(center ([1 2 3; 6 5 4], 2), [-1 0 1; 1 0 -1])
+
+%!assert (center ([1,2,3]), [-1,0,1])
+%!assert (center (single ([1,2,3])), single ([-1,0,1]))
+%!assert (center (int8 ([1,2,3])), [-1,0,1])
+%!assert (center (logical ([1, 0, 0, 1])), [0.5, -0.5, -0.5, 0.5])
+%!assert (center (ones (3,2,0,2)), zeros (3,2,0,2))
+%!assert (center (ones (3,2,0,2, "single")), zeros (3,2,0,2, "single"))
+%!assert (center (magic (3)), [3,-4,1;-2,0,2;-1,4,-3])
+%!assert (center ([1 2 3; 6 5 4], 2), [-1 0 1; 1 0 -1])
 
 %% Test input validation
 %!error center ()
 %!error center (1, 2, 3)
-%!error center (1, ones(2,2))
+%!error center (1, ones (2,2))
 %!error center (1, 1.5)
 %!error center (1, 0)
 %!error center (1, 3)
+
--- a/scripts/statistics/base/cloglog.m
+++ b/scripts/statistics/base/cloglog.m
@@ -46,10 +46,12 @@
 
 endfunction
 
-%!assert(cloglog(0), -Inf)
-%!assert(cloglog(1), Inf)
-%!assert(cloglog(1/e), 0)
+
+%!assert (cloglog (0), -Inf)
+%!assert (cloglog (1), Inf)
+%!assert (cloglog (1/e), 0)
 
 %% Test input validation
 %!error cloglog ()
 %!error cloglog (1, 2)
+
--- a/scripts/statistics/base/corr.m
+++ b/scripts/statistics/base/corr.m
@@ -56,7 +56,7 @@
 
   ## Special case, scalar is always 100% correlated with itself
   if (isscalar (x))
-    if (isa (x, 'single'))
+    if (isa (x, "single"))
       retval = single (1);
     else
       retval = 1;
@@ -89,24 +89,24 @@
 %!test
 %! x = [1:3]';
 %! y = [3:-1:1]';
-%! assert (corr (x,y), -1, 5*eps)
-%! assert (corr (x,flipud (y)), 1, 5*eps)
-%! assert (corr ([x, y]), [1 -1; -1 1], 5*eps)
+%! assert (corr (x, y), -1, 5*eps);
+%! assert (corr (x, flipud (y)), 1, 5*eps);
+%! assert (corr ([x, y]), [1 -1; -1 1], 5*eps);
 
 %!test
 %! x = single ([1:3]');
 %! y = single ([3:-1:1]');
-%! assert (corr (x,y), single (-1), 5*eps)
-%! assert (corr (x,flipud (y)), single (1), 5*eps)
-%! assert (corr ([x, y]), single ([1 -1; -1 1]), 5*eps)
+%! assert (corr (x, y), single (-1), 5*eps);
+%! assert (corr (x, flipud (y)), single (1), 5*eps);
+%! assert (corr ([x, y]), single ([1 -1; -1 1]), 5*eps);
 
-%!assert (corr (5), 1);
-%!assert (corr (single(5)), single(1));
+%!assert (corr (5), 1)
+%!assert (corr (single (5)), single (1))
 
 %% Test input validation
-%!error corr ();
-%!error corr (1, 2, 3);
-%!error corr ([1; 2], ["A", "B"]);
-%!error corr (ones (2,2,2));
-%!error corr (ones (2,2), ones (2,2,2));
+%!error corr ()
+%!error corr (1, 2, 3)
+%!error corr ([1; 2], ["A", "B"])
+%!error corr (ones (2,2,2))
+%!error corr (ones (2,2), ones (2,2,2))
 
--- a/scripts/statistics/base/cov.m
+++ b/scripts/statistics/base/cov.m
@@ -86,7 +86,7 @@
 
   ## Special case, scalar has zero covariance
   if (isscalar (x))
-    if (isa (x, 'single'))
+    if (isa (x, "single"))
       c = single (0);
     else
       c = 0;
@@ -121,22 +121,22 @@
 %! x = rand (10);
 %! cx1 = cov (x);
 %! cx2 = cov (x, x);
-%! assert(size (cx1) == [10, 10] && size (cx2) == [10, 10]);
-%! assert(cx1, cx2, 1e1*eps);
+%! assert (size (cx1) == [10, 10] && size (cx2) == [10, 10]);
+%! assert (cx1, cx2, 1e1*eps);
 
 %!test
 %! x = [1:3]';
 %! y = [3:-1:1]';
-%! assert (cov (x,y), -1, 5*eps)
-%! assert (cov (x,flipud (y)), 1, 5*eps)
-%! assert (cov ([x, y]), [1 -1; -1 1], 5*eps)
+%! assert (cov (x, y), -1, 5*eps);
+%! assert (cov (x, flipud (y)), 1, 5*eps);
+%! assert (cov ([x, y]), [1 -1; -1 1], 5*eps);
 
 %!test
 %! x = single ([1:3]');
 %! y = single ([3:-1:1]');
-%! assert (cov (x,y), single (-1), 5*eps)
-%! assert (cov (x,flipud (y)), single (1), 5*eps)
-%! assert (cov ([x, y]), single ([1 -1; -1 1]), 5*eps)
+%! assert (cov (x, y), single (-1), 5*eps);
+%! assert (cov (x, flipud (y)), single (1), 5*eps);
+%! assert (cov ([x, y]), single ([1 -1; -1 1]), 5*eps);
 
 %!test
 %! x = [1:5];
@@ -144,22 +144,22 @@
 %! assert (isscalar (c));
 %! assert (c, 2.5);
 
-%!assert(cov (5), 0);
-%!assert(cov (single(5)), single(0));
+%!assert (cov (5), 0)
+%!assert (cov (single (5)), single (0))
 
 %!test
 %! x = [1:5];
 %! c = cov (x, 0);
-%! assert(c, 2.5);
+%! assert (c, 2.5);
 %! c = cov (x, 1);
-%! assert(c, 2);
+%! assert (c, 2);
 
 %% Test input validation
-%!error cov ();
-%!error cov (1, 2, 3, 4);
-%!error cov ([1; 2], ["A", "B"]);
-%!error cov (ones (2,2,2));
-%!error cov (ones (2,2), ones (2,2,2));
-%!error cov (1, 3);
-%!error cov (ones (2,2), ones (3,2));
+%!error cov ()
+%!error cov (1, 2, 3, 4)
+%!error cov ([1; 2], ["A", "B"])
+%!error cov (ones (2,2,2))
+%!error cov (ones (2,2), ones (2,2,2))
+%!error cov (1, 3)
+%!error cov (ones (2,2), ones (3,2))
 
--- a/scripts/statistics/base/gls.m
+++ b/scripts/statistics/base/gls.m
@@ -140,6 +140,6 @@
 %!error gls (ones (2,2,2), ones (2,2), ones (4,4))
 %!error gls (ones (2,2), ones (2,2,2), ones (4,4))
 %!error gls (ones (2,2), ones (2,2), ones (4,4,4))
-%!error gls (ones(1,2), ones(2,2), ones (2,2))
-%!error gls (ones(2,2), ones(2,2), ones (2,2))
+%!error gls (ones (1,2), ones (2,2), ones (2,2))
+%!error gls (ones (2,2), ones (2,2), ones (2,2))
 
--- a/scripts/statistics/base/histc.m
+++ b/scripts/statistics/base/histc.m
@@ -168,9 +168,10 @@
 %! n = histc (x, 0:10, 2);
 %! assert (n, repmat ([repmat(100, 1, 10), 1], [2, 1, 3]));
 
-%!error histc ();
-%!error histc (1);
-%!error histc (1, 2, 3, 4);
-%!error histc ([1:10 1+i], 2);
-%!error histc (1:10, []);
-%!error histc (1, 1, 3);
+%!error histc ()
+%!error histc (1)
+%!error histc (1, 2, 3, 4)
+%!error histc ([1:10 1+i], 2)
+%!error histc (1:10, [])
+%!error histc (1, 1, 3)
+
--- a/scripts/statistics/base/iqr.m
+++ b/scripts/statistics/base/iqr.m
@@ -60,8 +60,8 @@
   ## can take a matrix, rather than just a vector argument.
   n = sz(dim);
   sz(dim) = 1;
-  if (isa (x, 'single'))
-    y = zeros (sz, 'single');
+  if (isa (x, "single"))
+    y = zeros (sz, "single");
   else
     y = zeros (sz);
   endif
@@ -82,17 +82,17 @@
 endfunction
 
 
-%!assert (iqr (1:101), 50);
-%!assert (iqr (single(1:101)), single(50));
+%!assert (iqr (1:101), 50)
+%!assert (iqr (single (1:101)), single (50))
 
 %%!test
 %%! x = [1:100];
 %%! n = iqr (x, 0:10);
 %%! assert (n, [repmat(100, 1, 10), 1]);
 
-%!error iqr ();
-%!error iqr (1, 2, 3);
-%!error iqr (1);
-%!error iqr (['A'; 'B']);
-%!error iqr (1:10, 3);
+%!error iqr ()
+%!error iqr (1, 2, 3)
+%!error iqr (1)
+%!error iqr (['A'; 'B'])
+%!error iqr (1:10, 3)
 
--- a/scripts/statistics/base/kendall.m
+++ b/scripts/statistics/base/kendall.m
@@ -99,10 +99,10 @@
     endif
   endif
 
-  if (isa (x, 'single') || isa (y, 'single'))
-    cls = 'single';
+  if (isa (x, "single") || isa (y, "single"))
+    cls = "single";
   else
-    cls = 'double';
+    cls = "double";
   endif
   r   = ranks (x);
   m   = sign (kron (r, ones (n, 1, cls)) - kron (ones (n, 1, cls), r));
@@ -121,14 +121,15 @@
 %! assert (kendall (x,y), 1, 5*eps);
 %! assert (kendall (x,fliplr (y)), -1, 5*eps);
 
-%!assert (kendall (logical(1)), 1);
-%!assert (kendall (single(1)), single(1));
+%!assert (kendall (logical (1)), 1)
+%!assert (kendall (single (1)), single (1))
 
 %% Test input validation
-%!error kendall ();
-%!error kendall (1, 2, 3);
-%!error kendall (['A'; 'B']);
-%!error kendall (ones(2,1), ['A'; 'B']);
-%!error kendall (ones (2,2,2));
-%!error kendall (ones (2,2), ones (2,2,2));
-%!error kendall (ones (2,2), ones (3,2));
+%!error kendall ()
+%!error kendall (1, 2, 3)
+%!error kendall (['A'; 'B'])
+%!error kendall (ones (2,1), ['A'; 'B'])
+%!error kendall (ones (2,2,2))
+%!error kendall (ones (2,2), ones (2,2,2))
+%!error kendall (ones (2,2), ones (3,2))
+
--- a/scripts/statistics/base/kurtosis.m
+++ b/scripts/statistics/base/kurtosis.m
@@ -29,7 +29,11 @@
 ## @ifnottex
 ##
 ## @example
-## kurtosis (x) = 1/N std(x)^(-4) sum ((x - mean(x)).^4) - 3
+## @group
+##                 1    sum ((x - mean(x)).^4)
+## kurtosis (x) = --- * ----------------------  -  3
+##                 N           std(x)^4
+## @end group
 ## @end example
 ##
 ## @end ifnottex
@@ -87,13 +91,13 @@
 %! y = [x, 2*x];
 %! assert (kurtosis (y), [-1.4, -1.4], sqrt (eps));
 
-%!assert (kurtosis (single(1)), single(0));
+%!assert (kurtosis (single (1)), single (0))
 
 %% Test input validation
 %!error kurtosis ()
 %!error kurtosis (1, 2, 3)
 %!error kurtosis (['A'; 'B'])
-%!error kurtosis (1, ones(2,2))
+%!error kurtosis (1, ones (2,2))
 %!error kurtosis (1, 1.5)
 %!error kurtosis (1, 0)
 %!error kurtosis (1, 3)
--- a/scripts/statistics/base/logit.m
+++ b/scripts/statistics/base/logit.m
@@ -50,10 +50,11 @@
 
 %!test
 %! p = [0.01:0.01:0.99];
-%! assert(logit (p), log (p ./ (1-p)), 25*eps)
+%! assert (logit (p), log (p ./ (1-p)), 25*eps);
 
-%!assert(logit ([-1, 0, 0.5, 1, 2]), [NaN, -Inf, 0, +Inf, NaN])
+%!assert (logit ([-1, 0, 0.5, 1, 2]), [NaN, -Inf, 0, +Inf, NaN])
 
 %% Test input validation
 %!error logit ()
 %!error logit (1, 2)
+
--- a/scripts/statistics/base/mahalanobis.m
+++ b/scripts/statistics/base/mahalanobis.m
@@ -71,10 +71,11 @@
 
 
 %% Test input validation
-%!error mahalanobis ();
-%!error mahalanobis (1, 2, 3);
-%!error mahalanobis ('A', 'B');
-%!error mahalanobis ([1, 2], ['A', 'B']);
-%!error mahalanobis (ones (2,2,2));
-%!error mahalanobis (ones (2,2), ones (2,2,2));
-%!error mahalanobis (ones (2,2), ones (2,3));
+%!error mahalanobis ()
+%!error mahalanobis (1, 2, 3)
+%!error mahalanobis ('A', 'B')
+%!error mahalanobis ([1, 2], ['A', 'B'])
+%!error mahalanobis (ones (2,2,2))
+%!error mahalanobis (ones (2,2), ones (2,2,2))
+%!error mahalanobis (ones (2,2), ones (2,3))
+
--- a/scripts/statistics/base/mean.m
+++ b/scripts/statistics/base/mean.m
@@ -113,7 +113,11 @@
   if (strcmp (opt, "a"))
     y = sum (x, dim) / n;
   elseif (strcmp (opt, "g"))
-    y = prod (x, dim) .^ (1/n);
+    if (all (x(:) >= 0))
+      y = exp (sum (log (x), dim) ./ n);
+    else
+      error ("mean: X must not contain any negative values");
+    endif
   elseif (strcmp (opt, "h"))
     y = n ./ sum (1 ./ x, dim);
   else
@@ -127,25 +131,28 @@
 %! x = -10:10;
 %! y = x';
 %! z = [y, y+10];
-%! assert(mean (x) == 0);
-%! assert(mean (y) == 0);
-%! assert(mean (z) == [0, 10]);
+%! assert (mean (x), 0);
+%! assert (mean (y), 0);
+%! assert (mean (z), [0, 10]);
+
+## Test small numbers
+%!assert (mean (repmat (0.1,1,1000), "g"), 0.1, 20*eps)
 
-%!assert(mean (magic(3), 1), [5, 5, 5]);
-%!assert(mean (magic(3), 2), [5; 5; 5]);
-%!assert(mean ([2 8], 'g'), 4);
-%!assert(mean ([4 4 2], 'h'), 3);
-%!assert(mean (logical ([1 0 1 1])), 0.75);
-%!assert(mean (single ([1 0 1 1])), single (0.75));
+%!assert (mean (magic (3), 1), [5, 5, 5])
+%!assert (mean (magic (3), 2), [5; 5; 5])
+%!assert (mean ([2 8], "g"), 4)
+%!assert (mean ([4 4 2], "h"), 3)
+%!assert (mean (logical ([1 0 1 1])), 0.75)
+%!assert (mean (single ([1 0 1 1])), single (0.75))
 
 %% Test input validation
-%!error mean ();
-%!error mean (1, 2, 3, 4);
-%!error mean ({1:5});
-%!error mean (1, 2, 3);
-%!error mean (1, ones(2,2));
-%!error mean (1, 1.5);
-%!error mean (1, 0);
-%!error mean (1, 3);
-%!error mean (1, 'b');
+%!error mean ()
+%!error mean (1, 2, 3, 4)
+%!error mean ({1:5})
+%!error mean (1, 2, 3)
+%!error mean (1, ones (2,2))
+%!error mean (1, 1.5)
+%!error mean (1, 0)
+%!error mean (1, 3)
+%!error mean (1, "b")
 
--- a/scripts/statistics/base/meansq.m
+++ b/scripts/statistics/base/meansq.m
@@ -73,16 +73,16 @@
 endfunction
 
 
-%!assert(meansq (1:5), 11);
-%!assert(meansq (single(1:5)), single(11));
-%!assert(meansq (magic (4)), [94.5, 92.5, 92.5, 94.5]);
-%!assert(meansq (magic (4), 2), [109.5; 77.5; 77.5; 109.5]);
+%!assert (meansq (1:5), 11)
+%!assert (meansq (single (1:5)), single (11))
+%!assert (meansq (magic (4)), [94.5, 92.5, 92.5, 94.5])
+%!assert (meansq (magic (4), 2), [109.5; 77.5; 77.5; 109.5])
 
 %% Test input validation
 %!error meansq ()
 %!error meansq (1, 2, 3)
-%!error meansq (['A'; 'B']);
-%!error meansq (1, ones(2,2))
+%!error meansq (['A'; 'B'])
+%!error meansq (1, ones (2,2))
 %!error meansq (1, 1.5)
 %!error meansq (1, 0)
 %!error meansq (1, 3)
--- a/scripts/statistics/base/median.m
+++ b/scripts/statistics/base/median.m
@@ -94,10 +94,13 @@
 %! y = [1, 2, 3, 4, 5, 6, 7];
 %! y2 = y';
 %!
-%! assert(median (x) == median (x2) && median (x) == 3.5);
-%! assert(median (y) == median (y2) && median (y) == 4);
-%! assert(median ([x2, 2*x2]) == [3.5, 7]);
-%! assert(median ([y2, 3*y2]) == [4, 12]);
+%! assert (median (x) == median (x2) && median (x) == 3.5);
+%! assert (median (y) == median (y2) && median (y) == 4);
+%! assert (median ([x2, 2*x2]), [3.5, 7]);
+%! assert (median ([y2, 3*y2]), [4, 12]);
+
+%!assert (median (single ([1,2,3])), single (2))
+%!assert (median ([1,2,NaN;4,5,6;NaN,8,9]), [NaN, 5, NaN])
 
 %% Test multidimensional arrays (bug #35679)
 %!shared a, b, x, y
@@ -109,15 +112,12 @@
 %!assert (median (a, 4), x(:, :, :, 3));
 %!assert (median (b, 3), (y(:, :, 3, :) + y(:, :, 4, :))/2);
 
-%!assert(median (single([1,2,3])), single(2));
-%!assert(median ([1,2,NaN;4,5,6;NaN,8,9]), [NaN, 5, NaN]);
+%% Test input validation
+%!error median ()
+%!error median (1, 2, 3)
+%!error median ({1:5})
+%!error median (['A'; 'B'])
+%!error median (1, ones (2,2))
+%!error median (1, 1.5)
+%!error median (1, 0)
 
-%% Test input validation
-%!error median ();
-%!error median (1, 2, 3);
-%!error median ({1:5});
-%!error median (['A'; 'B']);
-%!error median (1, ones(2,2));
-%!error median (1, 1.5);
-%!error median (1, 0);
-
--- a/scripts/statistics/base/mode.m
+++ b/scripts/statistics/base/mode.m
@@ -112,19 +112,19 @@
 %! [m2, f2, c2] = mode (full (a));
 %! assert (m, sparse (m2));
 %! assert (f, sparse (f2));
-%! c_exp(1:length(a)) = { sparse (0) };
+%! c_exp(1:length (a)) = { sparse (0) };
 %! assert (c ,c_exp);
 %! assert (c2,c_exp );
 
-%!assert(mode ([2,3,1,2,3,4],1),[2,3,1,2,3,4]);
-%!assert(mode ([2,3,1,2,3,4],2),2);
-%!assert(mode ([2,3,1,2,3,4]),2);
-%!assert(mode (single([2,3,1,2,3,4])), single(2));
-%!assert(mode (int8([2,3,1,2,3,4])), int8(2));
+%!assert (mode ([2,3,1,2,3,4],1),[2,3,1,2,3,4])
+%!assert (mode ([2,3,1,2,3,4],2),2)
+%!assert (mode ([2,3,1,2,3,4]),2)
+%!assert (mode (single ([2,3,1,2,3,4])), single (2))
+%!assert (mode (int8 ([2,3,1,2,3,4])), int8 (2))
 
-%!assert(mode ([2;3;1;2;3;4],1),2);
-%!assert(mode ([2;3;1;2;3;4],2),[2;3;1;2;3;4]);
-%!assert(mode ([2;3;1;2;3;4]),2);
+%!assert (mode ([2;3;1;2;3;4],1),2)
+%!assert (mode ([2;3;1;2;3;4],2),[2;3;1;2;3;4])
+%!assert (mode ([2;3;1;2;3;4]),2)
 
 %!shared x
 %! x(:,:,1) = toeplitz (1:3);
@@ -160,7 +160,7 @@
 %!error mode (1, 2, 3)
 %!error mode ({1 2 3})
 %!error mode (['A'; 'B'])
-%!error mode (1, ones(2,2))
+%!error mode (1, ones (2,2))
 %!error mode (1, 1.5)
 %!error mode (1, 0)
 %!error mode (1, 3)
--- a/scripts/statistics/base/moment.m
+++ b/scripts/statistics/base/moment.m
@@ -165,7 +165,7 @@
   if (any (type == "c"))
     x = center (x, dim);
   endif
-  if any (type == "a")
+  if (any (type == "a"))
     x = abs (x);
   endif
 
@@ -179,21 +179,21 @@
 %! assert (moment (x,1), mean (x), 1e1*eps);
 %! assert (moment (x,2), meansq (x), 1e1*eps);
 %! assert (moment (x,1,2), mean (x,2), 1e1*eps);
-%! assert (moment (x,1,'c'), mean (center (x)), 1e1*eps);
-%! assert (moment (x,1,'a'), mean (abs (x)), 1e1*eps);
+%! assert (moment (x,1,"c"), mean (center (x)), 1e1*eps);
+%! assert (moment (x,1,"a"), mean (abs (x)), 1e1*eps);
 
-%!assert (moment (single([1 2 3]),1), single(2));
+%!assert (moment (single ([1 2 3]), 1), single (2))
 
 %% Test input validation
 %!error moment ()
 %!error moment (1)
 %!error moment (1, 2, 3, 4, 5)
 %!error moment (['A'; 'B'], 2)
-%!error moment (ones(2,0,3), 2)
+%!error moment (ones (2,0,3), 2)
 %!error moment (1, true)
-%!error moment (1, ones(2,2))
+%!error moment (1, ones (2,2))
 %!error moment (1, 2, 3, 4)
-%!error moment (1, 2, ones(2,2))
+%!error moment (1, 2, ones (2,2))
 %!error moment (1, 2, 1.5)
 %!error moment (1, 2, 4)
 
--- a/scripts/statistics/base/ols.m
+++ b/scripts/statistics/base/ols.m
@@ -139,7 +139,7 @@
 %! x = [1:5]';
 %! y = 3*x + 2;
 %! x = [x, ones(5,1)];
-%! assert (ols(y,x), [3; 2], 50*eps)
+%! assert (ols (y,x), [3; 2], 50*eps)
 
 %!test
 %! x = [1, 2; 3, 4];
@@ -163,11 +163,12 @@
 %! assert (b, [1.4, 2], 2*eps);
 
 %% Test input validation
-%!error ols ();
-%!error ols (1);
-%!error ols (1, 2, 3);
-%!error ols ([true, true], [1, 2]);
-%!error ols ([1, 2], [true, true]);
-%!error ols (ones (2,2,2), ones (2,2));
-%!error ols (ones (2,2), ones (2,2,2));
-%!error ols (ones(1,2), ones(2,2));
+%!error ols ()
+%!error ols (1)
+%!error ols (1, 2, 3)
+%!error ols ([true, true], [1, 2])
+%!error ols ([1, 2], [true, true])
+%!error ols (ones (2,2,2), ones (2,2))
+%!error ols (ones (2,2), ones (2,2,2))
+%!error ols (ones (1,2), ones (2,2))
+
--- a/scripts/statistics/base/ppplot.m
+++ b/scripts/statistics/base/ppplot.m
@@ -79,6 +79,6 @@
 
 
 %% Test input validation
-%!error ppplot ();
-%!error ppplot (ones(2,2));
+%!error ppplot ()
+%!error ppplot (ones (2,2))
 
--- a/scripts/statistics/base/prctile.m
+++ b/scripts/statistics/base/prctile.m
@@ -173,3 +173,4 @@
 %!error prctile (1, 1, 1.5)
 %!error prctile (1, 1, 0)
 %!error prctile (1, 1, 3)
+
--- a/scripts/statistics/base/probit.m
+++ b/scripts/statistics/base/probit.m
@@ -36,7 +36,8 @@
 
 endfunction
 
-%!assert(probit([-1, 0, 0.5, 1, 2]), [NaN, -Inf, 0, Inf, NaN]);
+
+%!assert (probit ([-1, 0, 0.5, 1, 2]), [NaN, -Inf, 0, Inf, NaN])
 
 %% Test input validation
 %!error probit ()
--- a/scripts/statistics/base/qqplot.m
+++ b/scripts/statistics/base/qqplot.m
@@ -58,7 +58,7 @@
     print_usage ();
   endif
 
-  if (!(isnumeric (x) && isvector(x)))
+  if (!(isnumeric (x) && isvector (x)))
     error ("qqplot: X must be a numeric vector");
   endif
 
--- a/scripts/statistics/base/quantile.m
+++ b/scripts/statistics/base/quantile.m
@@ -17,7 +17,8 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {@var{q} =} quantile (@var{x}, @var{p})
+## @deftypefn  {Function File} {@var{q} =} quantile (@var{x})
+## @deftypefnx {Function File} {@var{q} =} quantile (@var{x}, @var{p})
 ## @deftypefnx {Function File} {@var{q} =} quantile (@var{x}, @var{p}, @var{dim})
 ## @deftypefnx {Function File} {@var{q} =} quantile (@var{x}, @var{p}, @var{dim}, @var{method})
 ## For a sample, @var{x}, calculate the quantiles, @var{q}, corresponding to
@@ -28,6 +29,8 @@
 ## return them in a matrix, such that the i-th row of @var{q} contains
 ## the @var{p}(i)th quantiles of each column of @var{x}.
 ##
+## If @var{p} is unspecified, return the quantiles for
+## @code{[0.00 0.25 0.50 0.75 1.00]}.
 ## The optional argument @var{dim} determines the dimension along which
 ## the quantiles are calculated.  If @var{dim} is omitted, and @var{x} is
 ## a vector or matrix, it defaults to 1 (column-wise quantiles).  If
@@ -51,10 +54,10 @@
 ## interpolation function respecting each methods' representative cdf.
 ##
 ## @enumerate 4
-## @item Method 4: p(k) = k / n. That is, linear interpolation of the
+## @item Method 4: p(k) = k / n.  That is, linear interpolation of the
 ## empirical cdf.
 ##
-## @item Method 5: p(k) = (k - 0.5) / n. That is a piecewise linear function
+## @item Method 5: p(k) = (k - 0.5) / n.  That is a piecewise linear function
 ## where the knots are the values midway through the steps of the empirical
 ## cdf.
 ##
@@ -128,7 +131,7 @@
   endif
 
   ## Set the permutation vector.
-  perm = 1:ndims(x);
+  perm = 1:ndims (x);
   perm(1) = dim;
   perm(dim) = 1;
 
@@ -157,7 +160,7 @@
 %! p = 0.5;
 %! x = sort (rand (11));
 %! q = quantile (x, p);
-%! assert (q, x(6,:))
+%! assert (q, x(6,:));
 %! x = x.';
 %! q = quantile (x, p, 2);
 %! assert (q, x(:,6));
@@ -174,9 +177,9 @@
 %!      1.0000   1.7500   2.5000   3.2500   4.0000
 %!      1.0000   1.4167   2.5000   3.5833   4.0000
 %!      1.0000   1.4375   2.5000   3.5625   4.0000];
-%! for m = (1:9)
+%! for m = 1:9
 %!   q = quantile (x, p, 1, m).';
-%!   assert (q, a(m,:), 0.0001)
+%!   assert (q, a(m,:), 0.0001);
 %! endfor
 
 %!test
@@ -191,9 +194,9 @@
 %!      1.0000   2.0000   3.0000   4.0000   5.0000
 %!      1.0000   1.6667   3.0000   4.3333   5.0000
 %!      1.0000   1.6875   3.0000   4.3125   5.0000];
-%! for m = (1:9)
+%! for m = 1:9
 %!   q = quantile (x, p, 1, m).';
-%!   assert (q, a(m,:), 0.0001)
+%!   assert (q, a(m,:), 0.0001);
 %! endfor
 
 %!test
@@ -208,9 +211,9 @@
 %!      1.0000   1.7500   3.5000   6.0000   9.0000
 %!      1.0000   1.4167   3.5000   7.3333   9.0000
 %!      1.0000   1.4375   3.5000   7.2500   9.0000];
-%! for m = (1:9)
+%! for m = 1:9
 %!   q = quantile (x, p, 1, m).';
-%!   assert (q, a(m,:), 0.0001)
+%!   assert (q, a(m,:), 0.0001);
 %! endfor
 
 %!test
@@ -225,9 +228,9 @@
 %!      1.0000    2.0000    5.0000    9.0000   11.0000
 %!      1.0000    1.6667    5.0000    9.6667   11.0000
 %!      1.0000    1.6875    5.0000    9.6250   11.0000];
-%! for m = (1:9)
+%! for m = 1:9
 %!   q = quantile (x, p, 1, m).';
-%!   assert (q, a(m,:), 0.0001)
+%!   assert (q, a(m,:), 0.0001);
 %! endfor
 
 %!test
@@ -242,9 +245,9 @@
 %!      6.0000   10.2500   11.5000   14.2500   16.0000
 %!      6.0000    9.8333   11.5000   15.0000   16.0000
 %!      6.0000    9.8750   11.5000   15.0000   16.0000];
-%! for m = (1:9)
+%! for m = 1:9
 %!   q = quantile (x, p, 1, m).';
-%!   assert (q, a(m,:), 0.0001)
+%!   assert (q, a(m,:), 0.0001);
 %! endfor
 
 %!test
@@ -260,9 +263,9 @@
 %!      -2.551474  -0.571522  -0.067751   0.106855   0.495271
 %!      -2.551474  -0.591566  -0.067751   0.146459   0.495271
 %!      -2.551474  -0.590801  -0.067751   0.140686   0.495271];
-%! for m = (1:9)
+%! for m = 1:9
 %!   q = quantile (x, p, 1, m).';
-%!   assert (q, a(m,:), 0.0001)
+%!   assert (q, a(m,:), 0.0001);
 %! endfor
 
 %!test
@@ -274,11 +277,11 @@
 %!      0.933100, 0.931200, 0.963500, 0.779600, 0.846100];
 %! tol = 0.00001;
 %! x(5,5) = NaN;
-%! assert (quantile(x, p, 1), [0.27950, 0.79780, 0.32960, 0.55670, 0.44460], tol);
+%! assert (quantile (x, p, 1), [0.27950, 0.79780, 0.32960, 0.55670, 0.44460], tol);
 %! x(1,1) = NaN;
-%! assert (quantile(x, p, 1), [0.35415, 0.79780, 0.32960, 0.55670, 0.44460], tol);
+%! assert (quantile (x, p, 1), [0.35415, 0.79780, 0.32960, 0.55670, 0.44460], tol);
 %! x(3,3) = NaN;
-%! assert (quantile(x, p, 1), [0.35415, 0.79780, 0.42590, 0.55670, 0.44460], tol);
+%! assert (quantile (x, p, 1), [0.35415, 0.79780, 0.42590, 0.55670, 0.44460], tol);
 
 %!test
 %! sx = [2, 3, 4];
--- a/scripts/statistics/base/range.m
+++ b/scripts/statistics/base/range.m
@@ -50,12 +50,13 @@
 endfunction
 
 
-%!assert(range (1:10), 9);
-%!assert(range (single(1:10)), single(9));
-%!assert(range (magic (3)), [5, 8, 5]);
-%!assert(range (magic (3), 2), [7; 4; 7]);
-%!assert(range (2), 0);
+%!assert (range (1:10), 9)
+%!assert (range (single (1:10)), single (9))
+%!assert (range (magic (3)), [5, 8, 5])
+%!assert (range (magic (3), 2), [7; 4; 7])
+%!assert (range (2), 0)
 
 %% Test input validation
 %!error range ()
 %!error range (1, 2, 3)
+
--- a/scripts/statistics/base/ranks.m
+++ b/scripts/statistics/base/ranks.m
@@ -54,7 +54,7 @@
   endif
 
   if (sz(dim) == 1)
-    y = ones(sz);
+    y = ones (sz);
   else
     ## The algorithm works only on dim = 1, so permute if necesary.
     if (dim != 1)
@@ -73,7 +73,7 @@
       runs = setdiff (eq_el, eq_el+1);
       len = diff (find (diff ([Inf; eq_el; -Inf]) != 1)) + 1;
       [eq_el, y] = sort (xi);
-      for i = 1 : length(runs)
+      for i = 1 : length (runs)
         y (xi (runs (i) + [0:(len(i)-1)]) + floor (runs (i) ./ sz(1))
            * sz(1)) = eq_el(runs(i)) + (len(i) - 1) / 2;
       endfor
@@ -86,12 +86,12 @@
 endfunction
 
 
-%!assert(ranks (1:2:10), 1:5);
-%!assert(ranks (10:-2:1), 5:-1:1);
-%!assert(ranks ([2, 1, 2, 4]), [2.5, 1, 2.5, 4]);
-%!assert(ranks (ones(1, 5)), 3*ones(1, 5));
-%!assert(ranks (1e6*ones(1, 5)), 3*ones(1, 5));
-%!assert(ranks (rand (1, 5), 1), ones(1, 5));
+%!assert (ranks (1:2:10), 1:5)
+%!assert (ranks (10:-2:1), 5:-1:1)
+%!assert (ranks ([2, 1, 2, 4]), [2.5, 1, 2.5, 4])
+%!assert (ranks (ones (1, 5)), 3*ones (1, 5))
+%!assert (ranks (1e6*ones (1, 5)), 3*ones (1, 5))
+%!assert (ranks (rand (1, 5), 1), ones (1, 5))
 
 %% Test input validation
 %!error ranks ()
--- a/scripts/statistics/base/run_count.m
+++ b/scripts/statistics/base/run_count.m
@@ -93,10 +93,10 @@
 endfunction
 
 
-%!assert(run_count (magic(3), 4), [1,0,1;1,0,1;0,1,0;0,0,0])
-%!assert(run_count (magic(3), 4, 2), [1,0,1;1,0,1;0,1,0;0,0,0]')
-%!assert(run_count (5:-1:1, 5), [5, 0, 0, 0, 0])
-%!assert(run_count (ones(3), 4), [0,0,0;0,0,0;1,1,1;0,0,0])
+%!assert (run_count (magic (3), 4), [1,0,1;1,0,1;0,1,0;0,0,0])
+%!assert (run_count (magic (3), 4, 2), [1,0,1;1,0,1;0,1,0;0,0,0]')
+%!assert (run_count (5:-1:1, 5), [5, 0, 0, 0, 0])
+%!assert (run_count (ones (3), 4), [0,0,0;0,0,0;1,1,1;0,0,0])
 
 %% Test input validation
 %!error run_count ()
@@ -104,10 +104,10 @@
 %!error run_count (1, 2, 3, 4)
 %!error run_count ({1, 2}, 3)
 %!error run_count (['A'; 'A'; 'B'], 3)
-%!error run_count (1:5, ones(2,2))
+%!error run_count (1:5, ones (2,2))
 %!error run_count (1:5, 1.5)
 %!error run_count (1:5, -2)
-%!error run_count (1:5, 3, ones(2,2))
+%!error run_count (1:5, 3, ones (2,2))
 %!error run_count (1:5, 3, 1.5)
 %!error run_count (1:5, 3, 0)
 
--- a/scripts/statistics/base/runlength.m
+++ b/scripts/statistics/base/runlength.m
@@ -52,8 +52,8 @@
 endfunction
 
 
-%!assert (runlength([2 2 0 4 4 4 0 1 1 1 1]), [2 1 3 1 4]);
-%!assert (runlength([2 2 0 4 4 4 0 1 1 1 1]'), [2 1 3 1 4]);
+%!assert (runlength ([2 2 0 4 4 4 0 1 1 1 1]), [2 1 3 1 4])
+%!assert (runlength ([2 2 0 4 4 4 0 1 1 1 1]'), [2 1 3 1 4])
 %!test
 %! [c, v] = runlength ([2 2 0 4 4 4 0 1 1 1 1]);
 %! assert (c, [2 1 3 1 4]);
@@ -63,4 +63,5 @@
 %!error runlength ()
 %!error runlength (1, 2)
 %!error runlength (['A'; 'B'])
-%!error runlength (ones(2,2))
+%!error runlength (ones (2,2))
+
--- a/scripts/statistics/base/skewness.m
+++ b/scripts/statistics/base/skewness.m
@@ -79,22 +79,23 @@
 endfunction
 
 
-%!assert(skewness ([-1,0,1]), 0);
-%!assert(skewness ([-2,0,1]) < 0);
-%!assert(skewness ([-1,0,2]) > 0);
-%!assert(skewness ([-3,0,1]) == -1*skewness([-1,0,3]));
+%!assert (skewness ([-1,0,1]), 0)
+%!assert (skewness ([-2,0,1]) < 0)
+%!assert (skewness ([-1,0,2]) > 0)
+%!assert (skewness ([-3,0,1]) == -1*skewness ([-1,0,3]))
 %!test
 %! x = [0; 0; 0; 1];
 %! y = [x, 2*x];
 %! assert(all (abs (skewness (y) - [0.75, 0.75]) < sqrt (eps)));
 
-%!assert (skewness (single(1)), single(0));
+%!assert (skewness (single (1)), single (0))
 
 %% Test input validation
 %!error skewness ()
 %!error skewness (1, 2, 3)
 %!error skewness (['A'; 'B'])
-%!error skewness (1, ones(2,2))
+%!error skewness (1, ones (2,2))
 %!error skewness (1, 1.5)
 %!error skewness (1, 0)
 %!error skewness (1, 3)
+
--- a/scripts/statistics/base/spearman.m
+++ b/scripts/statistics/base/spearman.m
@@ -69,7 +69,7 @@
   endif
 
   ## Restore class cleared by ranks
-  if (isa (x, 'single') || isa (y, 'single'))
+  if (isa (x, "single") || isa (y, "single"))
     rho = single (rho);
   endif
 
@@ -82,13 +82,14 @@
 %! assert (spearman (x,y), 1, 5*eps);
 %! assert (spearman (x,-y), -1, 5*eps);
 
-%!assert(spearman ([1 2 3], [-1 1 -2]), -0.5, 5*eps)
+%!assert (spearman ([1 2 3], [-1 1 -2]), -0.5, 5*eps)
 
 %% Test input validation
-%!error spearman ();
-%!error spearman (1, 2, 3);
-%!error spearman (['A'; 'B']);
-%!error spearman (ones(1,2), {1, 2});
-%!error spearman (ones (2,2,2));
-%!error spearman (ones (2,2), ones (2,2,2));
-%!error spearman (ones (2,2), ones (3,2));
+%!error spearman ()
+%!error spearman (1, 2, 3)
+%!error spearman (['A'; 'B'])
+%!error spearman (ones (1,2), {1, 2})
+%!error spearman (ones (2,2,2))
+%!error spearman (ones (2,2), ones (2,2,2))
+%!error spearman (ones (2,2), ones (3,2))
+
--- a/scripts/statistics/base/statistics.m
+++ b/scripts/statistics/base/statistics.m
@@ -81,7 +81,7 @@
 %!error statistics ()
 %!error statistics (1, 2, 3)
 %!error statistics (['A'; 'B'])
-%!error statistics (1, ones(2,2))
+%!error statistics (1, ones (2,2))
 %!error statistics (1, 1.5)
 %!error statistics (1, 0)
 %!error statistics (1, 3)
--- a/scripts/statistics/base/std.m
+++ b/scripts/statistics/base/std.m
@@ -92,8 +92,8 @@
 
   n = sz(dim);
   if (n == 1 || isempty (x))
-    if (isa (x, 'single'))
-      retval = zeros (sz, 'single');
+    if (isa (x, "single"))
+      retval = zeros (sz, "single");
     else
       retval = zeros (sz);
     endif
@@ -107,21 +107,21 @@
 %!test
 %! x = ones (10, 2);
 %! y = [1, 3];
-%! assert(std (x) == [0, 0]);
-%! assert(std (y), sqrt (2), sqrt (eps));
-%! assert(std (x, 0, 2), zeros (10, 1));
+%! assert (std (x), [0, 0]);
+%! assert (std (y), sqrt (2), sqrt (eps));
+%! assert (std (x, 0, 2), zeros (10, 1));
 
-%!assert(std (ones (3, 1, 2), 0, 2), zeros (3, 1, 2));
-%!assert(std ([1 2], 0), sqrt(2)/2, 5*eps);
-%!assert(std ([1 2], 1), 0.5, 5*eps);
-%!assert(std(1), 0);
-%!assert(std(single(1)), single(0));
-%!assert(std([]), []);
-%!assert(std(ones (1,3,0,2)), ones (1,3,0,2));
+%!assert (std (ones (3, 1, 2), 0, 2), zeros (3, 1, 2));
+%!assert (std ([1 2], 0), sqrt (2)/2, 5*eps);
+%!assert (std ([1 2], 1), 0.5, 5*eps);
+%!assert (std (1), 0);
+%!assert (std (single (1)), single (0));
+%!assert (std ([]), []);
+%!assert (std (ones (1,3,0,2)), ones (1,3,0,2));
 
 %% Test input validation
-%!error std ();
-%!error std (1, 2, 3, 4);
+%!error std ()
+%!error std (1, 2, 3, 4)
 %!error std (['A'; 'B'])
-%!error std (1, -1);
+%!error std (1, -1)
 
--- a/scripts/statistics/base/table.m
+++ b/scripts/statistics/base/table.m
@@ -71,3 +71,4 @@
 %!error table (ones (2,2), ones (2,1))
 %!error table (ones (2,1), ones (2,2))
 %!error table (ones (2,1), ones (3,1))
+
--- a/scripts/statistics/base/var.m
+++ b/scripts/statistics/base/var.m
@@ -51,6 +51,9 @@
 ##   normalizes with @math{N}, this provides the second moment around the mean
 ## @end table
 ##
+## If @math{N==1} the value of @var{opt} is ignored and normalization 
+## by @math{N} is used.
+##
 ## If the optional argument @var{dim} is given, operate along this dimension.
 ## @seealso{cov, std, skewness, kurtosis, moment}
 ## @end deftypefn
@@ -89,8 +92,8 @@
 
   n = sz(dim);
   if (n == 1)
-    if (isa (x, 'single'))
-      retval = zeros (sz, 'single');
+    if (isa (x, "single"))
+      retval = zeros (sz, "single");
     else
       retval = zeros (sz);
     endif
@@ -103,16 +106,16 @@
 endfunction
 
 
-%!assert(var (13), 0);
-%!assert(var (single(13)), single(0));
-%!assert(var ([1,2,3]), 1);
-%!assert(var ([1,2,3], 1), 2/3, eps);
-%!assert(var ([1,2,3], [], 1), [0,0,0]);
+%!assert (var (13), 0)
+%!assert (var (single (13)), single (0))
+%!assert (var ([1,2,3]), 1)
+%!assert (var ([1,2,3], 1), 2/3, eps)
+%!assert (var ([1,2,3], [], 1), [0,0,0])
 
 %% Test input validation
 %!error var ()
 %!error var (1,2,3,4)
 %!error var (['A'; 'B'])
-%!error var (1, -1);
-%!error var ([],1)
+%!error var (1, -1)
+%!error var ([], 1)
 
--- a/scripts/statistics/base/zscore.m
+++ b/scripts/statistics/base/zscore.m
@@ -17,23 +17,31 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {} zscore (@var{x})
-## @deftypefnx {Function File} {} zscore (@var{x}, @var{dim})
+## @deftypefn  {Function File} {[@var{z}, @var{mu}, @var{sigma}] =} zscore (@var{x})
+## @deftypefnx {Function File} {[@var{z}, @var{mu}, @var{sigma}] =} zscore (@var{x}, @var{opt})
+## @deftypefnx {Function File} {[@var{z}, @var{mu}, @var{sigma}] =} zscore (@var{x}, @var{opt}, @var{dim})
 ## If @var{x} is a vector, subtract its mean and divide by its standard
-## deviation.
+## deviation.  If the standard deviation is zero, divide by 1 instead.
+## The optional parameter @var{opt} determines the normalization to use
+## when computing the standard deviation and is the same as the
+## corresponding parameter for @code{std}.
 ##
 ## If @var{x} is a matrix, do the above along the first non-singleton
-## dimension.
-## If the optional argument @var{dim} is given, operate along this dimension.
-## @seealso{center}
+## dimension.  If the third optional argument @var{dim} is given, operate
+## along this dimension.
+##
+## The mean and standard deviation along @var{dim} are given in @var{mu}
+## and @var{sigma} respectively.
+##
+## @seealso{mean, std, center}
 ## @end deftypefn
 
 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
 ## Description: Subtract mean and divide by standard deviation
 
-function z = zscore (x, dim)
+function [z, mu, sigma] = zscore (x, opt, dim)
 
-  if (nargin != 1 && nargin != 2)
+  if (nargin < 1 || nargin > 3 )
     print_usage ();
   endif
 
@@ -41,9 +49,17 @@
     error ("zscore: X must be a numeric vector or matrix");
   endif
 
+  if (nargin < 2)
+    opt = 0;
+  else
+    if (opt != 0 && opt != 1 || ! isscalar (opt))
+      error ("zscore: OPT must be empty, 0, or 1");
+    endif
+  endif
+
   nd = ndims (x);
   sz = size (x);
-  if (nargin != 2)
+  if (nargin < 3)
     ## Find the first non-singleton dimension.
     (dim = find (sz > 1, 1)) || (dim = 1);
   else
@@ -57,28 +73,34 @@
   if (n == 0)
     z = x;
   else
-    x = center (x, dim); # center also promotes integer to double for next line
-    z = zeros (sz, class (x));
-    s = std (x, [], dim);
+
+    if (isinteger (x))
+      x = double (x);
+    endif
+
+    mu = mean (x, dim);
+    sigma = std (x, opt, dim);
+    s = sigma;
     s(s==0) = 1;
-    z = bsxfun (@rdivide, x, s);
+    ## FIXME: Use normal broadcasting once we can disable that warning
+    z = bsxfun (@rdivide, bsxfun (@minus, x, mu), s);
   endif
 
 endfunction
 
 
-%!assert(zscore ([1,2,3]), [-1,0,1])
-%!assert(zscore (single([1,2,3])), single([-1,0,1]))
-%!assert(zscore (int8([1,2,3])), [-1,0,1])
-%!assert(zscore (ones (3,2,2,2)), zeros (3,2,2,2))
-%!assert(zscore ([2,0,-2;0,2,0;-2,-2,2]), [1,0,-1;0,1,0;-1,-1,1])
+%!assert (zscore ([1,2,3]), [-1,0,1])
+%!assert (zscore (single ([1,2,3])), single ([-1,0,1]))
+%!assert (zscore (int8 ([1,2,3])), [-1,0,1])
+%!assert (zscore (ones (3,2,2,2)), zeros (3,2,2,2))
+%!assert (zscore ([2,0,-2;0,2,0;-2,-2,2]), [1,0,-1;0,1,0;-1,-1,1])
 
 %% Test input validation
 %!error zscore ()
 %!error zscore (1, 2, 3)
 %!error zscore (['A'; 'B'])
-%!error zscore (1, ones(2,2))
+%!error zscore (1, ones (2,2))
 %!error zscore (1, 1.5)
-%!error zscore (1, 0)
+%!error zscore (1, 1, 0)
 %!error zscore (1, 3)
 
--- a/scripts/statistics/distributions/betacdf.m
+++ b/scripts/statistics/distributions/betacdf.m
@@ -69,25 +69,25 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 2];
 %! y = [0 0 0.75 1 1];
-%!assert(betacdf (x, ones(1,5), 2*ones(1,5)), y);
-%!assert(betacdf (x, 1, 2*ones(1,5)), y);
-%!assert(betacdf (x, ones(1,5), 2), y);
-%!assert(betacdf (x, [0 1 NaN 1 1], 2), [NaN 0 NaN 1 1]);
-%!assert(betacdf (x, 1, 2*[0 1 NaN 1 1]), [NaN 0 NaN 1 1]);
-%!assert(betacdf ([x(1:2) NaN x(4:5)], 1, 2), [y(1:2) NaN y(4:5)]);
+%!assert (betacdf (x, ones (1,5), 2*ones (1,5)), y)
+%!assert (betacdf (x, 1, 2*ones (1,5)), y)
+%!assert (betacdf (x, ones (1,5), 2), y)
+%!assert (betacdf (x, [0 1 NaN 1 1], 2), [NaN 0 NaN 1 1])
+%!assert (betacdf (x, 1, 2*[0 1 NaN 1 1]), [NaN 0 NaN 1 1])
+%!assert (betacdf ([x(1:2) NaN x(4:5)], 1, 2), [y(1:2) NaN y(4:5)])
 
 %% Test class of input preserved
-%!assert(betacdf ([x, NaN], 1, 2), [y, NaN]);
-%!assert(betacdf (single([x, NaN]), 1, 2), single([y, NaN]));
-%!assert(betacdf ([x, NaN], single(1), 2), single([y, NaN]));
-%!assert(betacdf ([x, NaN], 1, single(2)), single([y, NaN]));
+%!assert (betacdf ([x, NaN], 1, 2), [y, NaN])
+%!assert (betacdf (single ([x, NaN]), 1, 2), single ([y, NaN]))
+%!assert (betacdf ([x, NaN], single (1), 2), single ([y, NaN]))
+%!assert (betacdf ([x, NaN], 1, single (2)), single ([y, NaN]))
 
 %% Test input validation
 %!error betacdf ()
 %!error betacdf (1)
 %!error betacdf (1,2)
 %!error betacdf (1,2,3,4)
-%!error betacdf (ones(3),ones(2),ones(2))
-%!error betacdf (ones(2),ones(3),ones(2))
-%!error betacdf (ones(2),ones(2),ones(3))
+%!error betacdf (ones (3), ones (2), ones (2))
+%!error betacdf (ones (2), ones (3), ones (2))
+%!error betacdf (ones (2), ones (2), ones (3))
 
--- a/scripts/statistics/distributions/betainv.m
+++ b/scripts/statistics/distributions/betainv.m
@@ -109,27 +109,27 @@
 
 %!shared x
 %! x = [-1 0 0.75 1 2];
-%!assert(betainv (x, ones(1,5), 2*ones(1,5)), [NaN 0 0.5 1 NaN]);
-%!assert(betainv (x, 1, 2*ones(1,5)), [NaN 0 0.5 1 NaN]);
-%!assert(betainv (x, ones(1,5), 2), [NaN 0 0.5 1 NaN]);
-%!assert(betainv (x, [1 0 NaN 1 1], 2), [NaN NaN NaN 1 NaN]);
-%!assert(betainv (x, 1, 2*[1 0 NaN 1 1]), [NaN NaN NaN 1 NaN]);
-%!assert(betainv ([x(1:2) NaN x(4:5)], 1, 2), [NaN 0 NaN 1 NaN]);
+%!assert (betainv (x, ones (1,5), 2*ones (1,5)), [NaN 0 0.5 1 NaN])
+%!assert (betainv (x, 1, 2*ones (1,5)), [NaN 0 0.5 1 NaN])
+%!assert (betainv (x, ones (1,5), 2), [NaN 0 0.5 1 NaN])
+%!assert (betainv (x, [1 0 NaN 1 1], 2), [NaN NaN NaN 1 NaN])
+%!assert (betainv (x, 1, 2*[1 0 NaN 1 1]), [NaN NaN NaN 1 NaN])
+%!assert (betainv ([x(1:2) NaN x(4:5)], 1, 2), [NaN 0 NaN 1 NaN])
 
 %% Test class of input preserved
-%!assert(betainv ([x, NaN], 1, 2), [NaN 0 0.5 1 NaN NaN]);
-%!assert(betainv (single([x, NaN]), 1, 2), single([NaN 0 0.5 1 NaN NaN]));
-%!assert(betainv ([x, NaN], single(1), 2), single([NaN 0 0.5 1 NaN NaN]));
-%!assert(betainv ([x, NaN], 1, single(2)), single([NaN 0 0.5 1 NaN NaN]));
+%!assert (betainv ([x, NaN], 1, 2), [NaN 0 0.5 1 NaN NaN])
+%!assert (betainv (single ([x, NaN]), 1, 2), single ([NaN 0 0.5 1 NaN NaN]))
+%!assert (betainv ([x, NaN], single (1), 2), single ([NaN 0 0.5 1 NaN NaN]))
+%!assert (betainv ([x, NaN], 1, single (2)), single ([NaN 0 0.5 1 NaN NaN]))
 
 %% Test input validation
 %!error betainv ()
 %!error betainv (1)
 %!error betainv (1,2)
 %!error betainv (1,2,3,4)
-%!error betainv (ones(3),ones(2),ones(2))
-%!error betainv (ones(2),ones(3),ones(2))
-%!error betainv (ones(2),ones(2),ones(3))
+%!error betainv (ones (3), ones (2), ones (2))
+%!error betainv (ones (2), ones (3), ones (2))
+%!error betainv (ones (2), ones (2), ones (3))
 %!error betainv (i, 2, 2)
 %!error betainv (2, i, 2)
 %!error betainv (2, 2, i)
--- a/scripts/statistics/distributions/betapdf.m
+++ b/scripts/statistics/distributions/betapdf.m
@@ -95,35 +95,35 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 2];
 %! y = [0 2 1 0 0];
-%!assert(betapdf (x, ones(1,5), 2*ones(1,5)), y);
-%!assert(betapdf (x, 1, 2*ones(1,5)), y);
-%!assert(betapdf (x, ones(1,5), 2), y);
-%!assert(betapdf (x, [0 NaN 1 1 1], 2), [NaN NaN y(3:5)]);
-%!assert(betapdf (x, 1, 2*[0 NaN 1 1 1]), [NaN NaN y(3:5)]);
-%!assert(betapdf ([x, NaN], 1, 2), [y, NaN]);
+%!assert (betapdf (x, ones (1,5), 2*ones (1,5)), y)
+%!assert (betapdf (x, 1, 2*ones (1,5)), y)
+%!assert (betapdf (x, ones (1,5), 2), y)
+%!assert (betapdf (x, [0 NaN 1 1 1], 2), [NaN NaN y(3:5)])
+%!assert (betapdf (x, 1, 2*[0 NaN 1 1 1]), [NaN NaN y(3:5)])
+%!assert (betapdf ([x, NaN], 1, 2), [y, NaN])
 
 %% Test class of input preserved
-%!assert(betapdf (single([x, NaN]), 1, 2), single([y, NaN]));
-%!assert(betapdf ([x, NaN], single(1), 2), single([y, NaN]));
-%!assert(betapdf ([x, NaN], 1, single(2)), single([y, NaN]));
+%!assert (betapdf (single ([x, NaN]), 1, 2), single ([y, NaN]))
+%!assert (betapdf ([x, NaN], single (1), 2), single ([y, NaN]))
+%!assert (betapdf ([x, NaN], 1, single (2)), single ([y, NaN]))
 
 %% Beta (1/2,1/2) == arcsine distribution
 %!test
 %! x = rand (10,1);
 %! y = 1./(pi * sqrt (x.*(1-x)));
-%! assert(betapdf (x, 1/2, 1/2), y, 50*eps);
+%! assert (betapdf (x, 1/2, 1/2), y, 50*eps);
 
 %% Test large input values to betapdf
-%!assert (betapdf(0.5, 1000, 1000), 35.678, 1e-3)
+%!assert (betapdf (0.5, 1000, 1000), 35.678, 1e-3)
 
 %% Test input validation
 %!error betapdf ()
 %!error betapdf (1)
 %!error betapdf (1,2)
 %!error betapdf (1,2,3,4)
-%!error betapdf (ones(3),ones(2),ones(2))
-%!error betapdf (ones(2),ones(3),ones(2))
-%!error betapdf (ones(2),ones(2),ones(3))
+%!error betapdf (ones (3), ones (2), ones (2))
+%!error betapdf (ones (2), ones (3), ones (2))
+%!error betapdf (ones (2), ones (2), ones (3))
 %!error betapdf (i, 2, 2)
 %!error betapdf (2, i, 2)
 %!error betapdf (2, 2, i)
--- a/scripts/statistics/distributions/betarnd.m
+++ b/scripts/statistics/distributions/betarnd.m
@@ -84,11 +84,8 @@
 
   if (isscalar (a) && isscalar (b))
     if ((a > 0) && (a < Inf) && (b > 0) && (b < Inf))
-      r = randg (a, sz);
-      rnd = r ./ (r + randg (b, sz));
-      if (strcmp (cls, "single"))
-        rnd = single (rnd);
-      endif
+      r = randg (a, sz, cls);
+      rnd = r ./ (r + randg (b, sz, cls));
     else
       rnd = NaN (sz, cls);
     endif
@@ -96,42 +93,42 @@
     rnd = NaN (sz, cls);
 
     k = (a > 0) & (a < Inf) & (b > 0) & (b < Inf);
-    r = randg (a(k));
-    rnd(k) = r ./ (r + randg (b(k)));
+    r = randg (a(k), cls);
+    rnd(k) = r ./ (r + randg (b(k), cls));
   endif
 
 endfunction
 
 
-%!assert(size (betarnd (1,2)), [1, 1]);
-%!assert(size (betarnd (ones(2,1), 2)), [2, 1]);
-%!assert(size (betarnd (ones(2,2), 2)), [2, 2]);
-%!assert(size (betarnd (1, 2*ones(2,1))), [2, 1]);
-%!assert(size (betarnd (1, 2*ones(2,2))), [2, 2]);
-%!assert(size (betarnd (1, 2, 3)), [3, 3]);
-%!assert(size (betarnd (1, 2, [4 1])), [4, 1]);
-%!assert(size (betarnd (1, 2, 4, 1)), [4, 1]);
+%!assert (size (betarnd (1,2)), [1, 1])
+%!assert (size (betarnd (ones (2,1), 2)), [2, 1])
+%!assert (size (betarnd (ones (2,2), 2)), [2, 2])
+%!assert (size (betarnd (1, 2*ones (2,1))), [2, 1])
+%!assert (size (betarnd (1, 2*ones (2,2))), [2, 2])
+%!assert (size (betarnd (1, 2, 3)), [3, 3])
+%!assert (size (betarnd (1, 2, [4 1])), [4, 1])
+%!assert (size (betarnd (1, 2, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (betarnd (1, 2)), "double");
-%!assert(class (betarnd (single(1), 2)), "single");
-%!assert(class (betarnd (single([1 1]), 2)), "single");
-%!assert(class (betarnd (1, single(2))), "single");
-%!assert(class (betarnd (1, single([2 2]))), "single");
+%!assert (class (betarnd (1, 2)), "double")
+%!assert (class (betarnd (single (1), 2)), "single")
+%!assert (class (betarnd (single ([1 1]), 2)), "single")
+%!assert (class (betarnd (1, single (2))), "single")
+%!assert (class (betarnd (1, single ([2 2]))), "single")
 
 %% Test input validation
 %!error betarnd ()
 %!error betarnd (1)
-%!error betarnd (ones(3),ones(2))
-%!error betarnd (ones(2),ones(3))
+%!error betarnd (ones (3), ones (2))
+%!error betarnd (ones (2), ones (3))
 %!error betarnd (i, 2)
 %!error betarnd (2, i)
 %!error betarnd (1,2, -1)
-%!error betarnd (1,2, ones(2))
+%!error betarnd (1,2, ones (2))
 %!error binornd (1,2, [2 -1 2])
-%!error betarnd (1,2, 1, ones(2))
+%!error betarnd (1,2, 1, ones (2))
 %!error betarnd (1,2, 1, -1)
-%!error betarnd (ones(2,2), 2, 3)
-%!error betarnd (ones(2,2), 2, [3, 2])
-%!error betarnd (ones(2,2), 2, 2, 3)
+%!error betarnd (ones (2,2), 2, 3)
+%!error betarnd (ones (2,2), 2, [3, 2])
+%!error betarnd (ones (2,2), 2, 2, 3)
 
--- a/scripts/statistics/distributions/binocdf.m
+++ b/scripts/statistics/distributions/binocdf.m
@@ -71,27 +71,27 @@
 %!shared x,y
 %! x = [-1 0 1 2 3];
 %! y = [0 1/4 3/4 1 1];
-%!assert(binocdf (x, 2*ones(1,5), 0.5*ones(1,5)), y);
-%!assert(binocdf (x, 2, 0.5*ones(1,5)), y);
-%!assert(binocdf (x, 2*ones(1,5), 0.5), y);
-%!assert(binocdf (x, 2*[0 -1 NaN 1.1 1], 0.5), [0 NaN NaN NaN 1]);
-%!assert(binocdf (x, 2, 0.5*[0 -1 NaN 3 1]), [0 NaN NaN NaN 1]);
-%!assert(binocdf ([x(1:2) NaN x(4:5)], 2, 0.5), [y(1:2) NaN y(4:5)]);
+%!assert (binocdf (x, 2*ones (1,5), 0.5*ones (1,5)), y)
+%!assert (binocdf (x, 2, 0.5*ones (1,5)), y)
+%!assert (binocdf (x, 2*ones (1,5), 0.5), y)
+%!assert (binocdf (x, 2*[0 -1 NaN 1.1 1], 0.5), [0 NaN NaN NaN 1])
+%!assert (binocdf (x, 2, 0.5*[0 -1 NaN 3 1]), [0 NaN NaN NaN 1])
+%!assert (binocdf ([x(1:2) NaN x(4:5)], 2, 0.5), [y(1:2) NaN y(4:5)])
 
 %% Test class of input preserved
-%!assert(binocdf ([x, NaN], 2, 0.5), [y, NaN]);
-%!assert(binocdf (single([x, NaN]), 2, 0.5), single([y, NaN]));
-%!assert(binocdf ([x, NaN], single(2), 0.5), single([y, NaN]));
-%!assert(binocdf ([x, NaN], 2, single(0.5)), single([y, NaN]));
+%!assert (binocdf ([x, NaN], 2, 0.5), [y, NaN])
+%!assert (binocdf (single ([x, NaN]), 2, 0.5), single ([y, NaN]))
+%!assert (binocdf ([x, NaN], single (2), 0.5), single ([y, NaN]))
+%!assert (binocdf ([x, NaN], 2, single (0.5)), single ([y, NaN]))
 
 %% Test input validation
 %!error binocdf ()
 %!error binocdf (1)
 %!error binocdf (1,2)
 %!error binocdf (1,2,3,4)
-%!error binocdf (ones(3),ones(2),ones(2))
-%!error binocdf (ones(2),ones(3),ones(2))
-%!error binocdf (ones(2),ones(2),ones(3))
+%!error binocdf (ones (3), ones (2), ones (2))
+%!error binocdf (ones (2), ones (3), ones (2))
+%!error binocdf (ones (2), ones (2), ones (3))
 %!error binocdf (i, 2, 2)
 %!error binocdf (2, i, 2)
 %!error binocdf (2, 2, i)
--- a/scripts/statistics/distributions/binoinv.m
+++ b/scripts/statistics/distributions/binoinv.m
@@ -88,27 +88,27 @@
 
 %!shared x
 %! x = [-1 0 0.5 1 2];
-%!assert(binoinv (x, 2*ones(1,5), 0.5*ones(1,5)), [NaN 0 1 2 NaN]);
-%!assert(binoinv (x, 2, 0.5*ones(1,5)), [NaN 0 1 2 NaN]);
-%!assert(binoinv (x, 2*ones(1,5), 0.5), [NaN 0 1 2 NaN]);
-%!assert(binoinv (x, 2*[0 -1 NaN 1.1 1], 0.5), [NaN NaN NaN NaN NaN]);
-%!assert(binoinv (x, 2, 0.5*[0 -1 NaN 3 1]), [NaN NaN NaN NaN NaN]);
-%!assert(binoinv ([x(1:2) NaN x(4:5)], 2, 0.5), [NaN 0 NaN 2 NaN]);
+%!assert (binoinv (x, 2*ones (1,5), 0.5*ones (1,5)), [NaN 0 1 2 NaN])
+%!assert (binoinv (x, 2, 0.5*ones (1,5)), [NaN 0 1 2 NaN])
+%!assert (binoinv (x, 2*ones (1,5), 0.5), [NaN 0 1 2 NaN])
+%!assert (binoinv (x, 2*[0 -1 NaN 1.1 1], 0.5), [NaN NaN NaN NaN NaN])
+%!assert (binoinv (x, 2, 0.5*[0 -1 NaN 3 1]), [NaN NaN NaN NaN NaN])
+%!assert (binoinv ([x(1:2) NaN x(4:5)], 2, 0.5), [NaN 0 NaN 2 NaN])
 
 %% Test class of input preserved
-%!assert(binoinv ([x, NaN], 2, 0.5), [NaN 0 1 2 NaN NaN]);
-%!assert(binoinv (single([x, NaN]), 2, 0.5), single([NaN 0 1 2 NaN NaN]));
-%!assert(binoinv ([x, NaN], single(2), 0.5), single([NaN 0 1 2 NaN NaN]));
-%!assert(binoinv ([x, NaN], 2, single(0.5)), single([NaN 0 1 2 NaN NaN]));
+%!assert (binoinv ([x, NaN], 2, 0.5), [NaN 0 1 2 NaN NaN])
+%!assert (binoinv (single ([x, NaN]), 2, 0.5), single ([NaN 0 1 2 NaN NaN]))
+%!assert (binoinv ([x, NaN], single (2), 0.5), single ([NaN 0 1 2 NaN NaN]))
+%!assert (binoinv ([x, NaN], 2, single (0.5)), single ([NaN 0 1 2 NaN NaN]))
 
 %% Test input validation
 %!error binoinv ()
 %!error binoinv (1)
 %!error binoinv (1,2)
 %!error binoinv (1,2,3,4)
-%!error binoinv (ones(3),ones(2),ones(2))
-%!error binoinv (ones(2),ones(3),ones(2))
-%!error binoinv (ones(2),ones(2),ones(3))
+%!error binoinv (ones (3), ones (2), ones (2))
+%!error binoinv (ones (2), ones (3), ones (2))
+%!error binoinv (ones (2), ones (2), ones (3))
 %!error binoinv (i, 2, 2)
 %!error binoinv (2, i, 2)
 %!error binoinv (2, 2, i)
--- a/scripts/statistics/distributions/binopdf.m
+++ b/scripts/statistics/distributions/binopdf.m
@@ -64,6 +64,12 @@
                   + x(k).*log (p(k)) + (n(k)-x(k)).*log (1-p(k)));
   endif
 
+  ## Special case inputs
+  ksp = k & (p == 0) & (x == 0);
+  pdf(ksp) = 1; 
+  ksp = k & (p == 1) & (x == n);
+  pdf(ksp) = 1; 
+
 endfunction
 
 
@@ -75,26 +81,31 @@
 %! endif
 %! x = [-1 0 1 2 3];
 %! y = [0 1/4 1/2 1/4 0];
-%!assert(binopdf (x, 2*ones(1,5), 0.5*ones(1,5)), y, tol);
-%!assert(binopdf (x, 2, 0.5*ones(1,5)), y, tol);
-%!assert(binopdf (x, 2*ones(1,5), 0.5), y, tol);
-%!assert(binopdf (x, 2*[0 -1 NaN 1.1 1], 0.5), [0 NaN NaN NaN 0]);
-%!assert(binopdf (x, 2, 0.5*[0 -1 NaN 3 1]), [0 NaN NaN NaN 0]);
-%!assert(binopdf ([x, NaN], 2, 0.5), [y, NaN], tol);
+%!assert (binopdf (x, 2*ones (1,5), 0.5*ones (1,5)), y, tol)
+%!assert (binopdf (x, 2, 0.5*ones (1,5)), y, tol)
+%!assert (binopdf (x, 2*ones (1,5), 0.5), y, tol)
+%!assert (binopdf (x, 2*[0 -1 NaN 1.1 1], 0.5), [0 NaN NaN NaN 0])
+%!assert (binopdf (x, 2, 0.5*[0 -1 NaN 3 1]), [0 NaN NaN NaN 0])
+%!assert (binopdf ([x, NaN], 2, 0.5), [y, NaN], tol)
+
+## Test Special input values
+%!assert (binopdf (0, 3, 0), 1);
+%!assert (binopdf (2, 2, 1), 1);
+%!assert (binopdf (1, 2, 1), 0);
 
 %% Test class of input preserved
-%!assert(binopdf (single([x, NaN]), 2, 0.5), single([y, NaN]));
-%!assert(binopdf ([x, NaN], single(2), 0.5), single([y, NaN]));
-%!assert(binopdf ([x, NaN], 2, single(0.5)), single([y, NaN]));
+%!assert (binopdf (single ([x, NaN]), 2, 0.5), single ([y, NaN]))
+%!assert (binopdf ([x, NaN], single (2), 0.5), single ([y, NaN]))
+%!assert (binopdf ([x, NaN], 2, single (0.5)), single ([y, NaN]))
 
 %% Test input validation
 %!error binopdf ()
 %!error binopdf (1)
 %!error binopdf (1,2)
 %!error binopdf (1,2,3,4)
-%!error binopdf (ones(3),ones(2),ones(2))
-%!error binopdf (ones(2),ones(3),ones(2))
-%!error binopdf (ones(2),ones(2),ones(3))
+%!error binopdf (ones (3), ones (2), ones (2))
+%!error binopdf (ones (2), ones (3), ones (2))
+%!error binopdf (ones (2), ones (2), ones (3))
 %!error binopdf (i, 2, 2)
 %!error binopdf (2, i, 2)
 %!error binopdf (2, 2, i)
--- a/scripts/statistics/distributions/binornd.m
+++ b/scripts/statistics/distributions/binornd.m
@@ -120,35 +120,35 @@
 %!assert (binornd (0, 0, 1), 0)
 %!assert (binornd ([0, 0], [0, 0], 1, 2), [0, 0])
 
-%!assert(size (binornd (2, 1/2)), [1, 1]);
-%!assert(size (binornd (2*ones(2,1), 1/2)), [2, 1]);
-%!assert(size (binornd (2*ones(2,2), 1/2)), [2, 2]);
-%!assert(size (binornd (2, 1/2*ones(2,1))), [2, 1]);
-%!assert(size (binornd (2, 1/2*ones(2,2))), [2, 2]);
-%!assert(size (binornd (2, 1/2, 3)), [3, 3]);
-%!assert(size (binornd (2, 1/2, [4 1])), [4, 1]);
-%!assert(size (binornd (2, 1/2, 4, 1)), [4, 1]);
+%!assert (size (binornd (2, 1/2)), [1, 1])
+%!assert (size (binornd (2*ones (2,1), 1/2)), [2, 1])
+%!assert (size (binornd (2*ones (2,2), 1/2)), [2, 2])
+%!assert (size (binornd (2, 1/2*ones (2,1))), [2, 1])
+%!assert (size (binornd (2, 1/2*ones (2,2))), [2, 2])
+%!assert (size (binornd (2, 1/2, 3)), [3, 3])
+%!assert (size (binornd (2, 1/2, [4 1])), [4, 1])
+%!assert (size (binornd (2, 1/2, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (binornd (2, 0.5)), "double");
-%!assert(class (binornd (single(2), 0.5)), "single");
-%!assert(class (binornd (single([2 2]), 0.5)), "single");
-%!assert(class (binornd (2, single(0.5))), "single");
-%!assert(class (binornd (2, single([0.5 0.5]))), "single");
+%!assert (class (binornd (2, 0.5)), "double")
+%!assert (class (binornd (single (2), 0.5)), "single")
+%!assert (class (binornd (single ([2 2]), 0.5)), "single")
+%!assert (class (binornd (2, single (0.5))), "single")
+%!assert (class (binornd (2, single ([0.5 0.5]))), "single")
 
 %% Test input validation
 %!error binornd ()
 %!error binornd (1)
-%!error binornd (ones(3),ones(2))
-%!error binornd (ones(2),ones(3))
+%!error binornd (ones (3), ones (2))
+%!error binornd (ones (2), ones (3))
 %!error binornd (i, 2)
 %!error binornd (2, i)
 %!error binornd (1,2, -1)
-%!error binornd (1,2, ones(2))
+%!error binornd (1,2, ones (2))
 %!error binornd (1,2, [2 -1 2])
-%!error binornd (1,2, 1, ones(2))
+%!error binornd (1,2, 1, ones (2))
 %!error binornd (1,2, 1, -1)
-%!error binornd (ones(2,2), 2, 3)
-%!error binornd (ones(2,2), 2, [3, 2])
-%!error binornd (ones(2,2), 2, 2, 3)
+%!error binornd (ones (2,2), 2, 3)
+%!error binornd (ones (2,2), 2, [3, 2])
+%!error binornd (ones (2,2), 2, 2, 3)
 
--- a/scripts/statistics/distributions/cauchy_cdf.m
+++ b/scripts/statistics/distributions/cauchy_cdf.m
@@ -65,26 +65,26 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 2];
 %! y = 1/pi * atan ((x-1) / 2) + 1/2;
-%!assert(cauchy_cdf (x, ones(1,5), 2*ones(1,5)), y);
-%!assert(cauchy_cdf (x, 1, 2*ones(1,5)), y);
-%!assert(cauchy_cdf (x, ones(1,5), 2), y);
-%!assert(cauchy_cdf (x, [-Inf 1 NaN 1 Inf], 2), [NaN y(2) NaN y(4) NaN]);
-%!assert(cauchy_cdf (x, 1, 2*[0 1 NaN 1 Inf]), [NaN y(2) NaN y(4) NaN]);
-%!assert(cauchy_cdf ([x(1:2) NaN x(4:5)], 1, 2), [y(1:2) NaN y(4:5)]);
+%!assert (cauchy_cdf (x, ones (1,5), 2*ones (1,5)), y)
+%!assert (cauchy_cdf (x, 1, 2*ones (1,5)), y)
+%!assert (cauchy_cdf (x, ones (1,5), 2), y)
+%!assert (cauchy_cdf (x, [-Inf 1 NaN 1 Inf], 2), [NaN y(2) NaN y(4) NaN])
+%!assert (cauchy_cdf (x, 1, 2*[0 1 NaN 1 Inf]), [NaN y(2) NaN y(4) NaN])
+%!assert (cauchy_cdf ([x(1:2) NaN x(4:5)], 1, 2), [y(1:2) NaN y(4:5)])
 
 %% Test class of input preserved
-%!assert(cauchy_cdf ([x, NaN], 1, 2), [y, NaN]);
-%!assert(cauchy_cdf (single([x, NaN]), 1, 2), single([y, NaN]), eps("single"));
-%!assert(cauchy_cdf ([x, NaN], single(1), 2), single([y, NaN]), eps("single"));
-%!assert(cauchy_cdf ([x, NaN], 1, single(2)), single([y, NaN]), eps("single"));
+%!assert (cauchy_cdf ([x, NaN], 1, 2), [y, NaN])
+%!assert (cauchy_cdf (single ([x, NaN]), 1, 2), single ([y, NaN]), eps ("single"))
+%!assert (cauchy_cdf ([x, NaN], single (1), 2), single ([y, NaN]), eps ("single"))
+%!assert (cauchy_cdf ([x, NaN], 1, single (2)), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error cauchy_cdf ()
 %!error cauchy_cdf (1,2)
 %!error cauchy_cdf (1,2,3,4)
-%!error cauchy_cdf (ones(3),ones(2),ones(2))
-%!error cauchy_cdf (ones(2),ones(3),ones(2))
-%!error cauchy_cdf (ones(2),ones(2),ones(3))
+%!error cauchy_cdf (ones (3), ones (2), ones (2))
+%!error cauchy_cdf (ones (2), ones (3), ones (2))
+%!error cauchy_cdf (ones (2), ones (2), ones (3))
 %!error cauchy_cdf (i, 2, 2)
 %!error cauchy_cdf (2, i, 2)
 %!error cauchy_cdf (2, 2, i)
--- a/scripts/statistics/distributions/cauchy_inv.m
+++ b/scripts/statistics/distributions/cauchy_inv.m
@@ -72,26 +72,26 @@
 
 %!shared x
 %! x = [-1 0 0.5 1 2];
-%!assert(cauchy_inv (x, ones(1,5), 2*ones(1,5)), [NaN -Inf 1 Inf NaN], eps);
-%!assert(cauchy_inv (x, 1, 2*ones(1,5)), [NaN -Inf 1 Inf NaN], eps);
-%!assert(cauchy_inv (x, ones(1,5), 2), [NaN -Inf 1 Inf NaN], eps);
-%!assert(cauchy_inv (x, [1 -Inf NaN Inf 1], 2), [NaN NaN NaN NaN NaN]);
-%!assert(cauchy_inv (x, 1, 2*[1 0 NaN Inf 1]), [NaN NaN NaN NaN NaN]);
-%!assert(cauchy_inv ([x(1:2) NaN x(4:5)], 1, 2), [NaN -Inf NaN Inf NaN]);
+%!assert (cauchy_inv (x, ones (1,5), 2*ones (1,5)), [NaN -Inf 1 Inf NaN], eps)
+%!assert (cauchy_inv (x, 1, 2*ones (1,5)), [NaN -Inf 1 Inf NaN], eps)
+%!assert (cauchy_inv (x, ones (1,5), 2), [NaN -Inf 1 Inf NaN], eps)
+%!assert (cauchy_inv (x, [1 -Inf NaN Inf 1], 2), [NaN NaN NaN NaN NaN])
+%!assert (cauchy_inv (x, 1, 2*[1 0 NaN Inf 1]), [NaN NaN NaN NaN NaN])
+%!assert (cauchy_inv ([x(1:2) NaN x(4:5)], 1, 2), [NaN -Inf NaN Inf NaN])
 
 %% Test class of input preserved
-%!assert(cauchy_inv ([x, NaN], 1, 2), [NaN -Inf 1 Inf NaN NaN], eps);
-%!assert(cauchy_inv (single([x, NaN]), 1, 2), single([NaN -Inf 1 Inf NaN NaN]), eps("single"));
-%!assert(cauchy_inv ([x, NaN], single(1), 2), single([NaN -Inf 1 Inf NaN NaN]), eps("single"));
-%!assert(cauchy_inv ([x, NaN], 1, single(2)), single([NaN -Inf 1 Inf NaN NaN]), eps("single"));
+%!assert (cauchy_inv ([x, NaN], 1, 2), [NaN -Inf 1 Inf NaN NaN], eps)
+%!assert (cauchy_inv (single ([x, NaN]), 1, 2), single ([NaN -Inf 1 Inf NaN NaN]), eps ("single"))
+%!assert (cauchy_inv ([x, NaN], single (1), 2), single ([NaN -Inf 1 Inf NaN NaN]), eps ("single"))
+%!assert (cauchy_inv ([x, NaN], 1, single (2)), single ([NaN -Inf 1 Inf NaN NaN]), eps ("single"))
 
 %% Test input validation
 %!error cauchy_inv ()
 %!error cauchy_inv (1,2)
 %!error cauchy_inv (1,2,3,4)
-%!error cauchy_inv (ones(3),ones(2),ones(2))
-%!error cauchy_inv (ones(2),ones(3),ones(2))
-%!error cauchy_inv (ones(2),ones(2),ones(3))
+%!error cauchy_inv (ones (3), ones (2), ones (2))
+%!error cauchy_inv (ones (2), ones (3), ones (2))
+%!error cauchy_inv (ones (2), ones (2), ones (3))
 %!error cauchy_inv (i, 2, 2)
 %!error cauchy_inv (2, i, 2)
 %!error cauchy_inv (2, 2, i)
--- a/scripts/statistics/distributions/cauchy_pdf.m
+++ b/scripts/statistics/distributions/cauchy_pdf.m
@@ -67,30 +67,30 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 2];
 %! y = 1/pi * ( 2 ./ ((x-1).^2 + 2^2) );
-%!assert(cauchy_pdf (x, ones(1,5), 2*ones(1,5)), y);
-%!assert(cauchy_pdf (x, 1, 2*ones(1,5)), y);
-%!assert(cauchy_pdf (x, ones(1,5), 2), y);
-%!assert(cauchy_pdf (x, [-Inf 1 NaN 1 Inf], 2), [NaN y(2) NaN y(4) NaN]);
-%!assert(cauchy_pdf (x, 1, 2*[0 1 NaN 1 Inf]), [NaN y(2) NaN y(4) NaN]);
-%!assert(cauchy_pdf ([x, NaN], 1, 2), [y, NaN]);
+%!assert (cauchy_pdf (x, ones (1,5), 2*ones (1,5)), y)
+%!assert (cauchy_pdf (x, 1, 2*ones (1,5)), y)
+%!assert (cauchy_pdf (x, ones (1,5), 2), y)
+%!assert (cauchy_pdf (x, [-Inf 1 NaN 1 Inf], 2), [NaN y(2) NaN y(4) NaN])
+%!assert (cauchy_pdf (x, 1, 2*[0 1 NaN 1 Inf]), [NaN y(2) NaN y(4) NaN])
+%!assert (cauchy_pdf ([x, NaN], 1, 2), [y, NaN])
 
 %% Test class of input preserved
-%!assert(cauchy_pdf (single([x, NaN]), 1, 2), single([y, NaN]), eps("single"));
-%!assert(cauchy_pdf ([x, NaN], single(1), 2), single([y, NaN]), eps("single"));
-%!assert(cauchy_pdf ([x, NaN], 1, single(2)), single([y, NaN]), eps("single"));
+%!assert (cauchy_pdf (single ([x, NaN]), 1, 2), single ([y, NaN]), eps ("single"))
+%!assert (cauchy_pdf ([x, NaN], single (1), 2), single ([y, NaN]), eps ("single"))
+%!assert (cauchy_pdf ([x, NaN], 1, single (2)), single ([y, NaN]), eps ("single"))
 
 %% Cauchy (0,1) == Student's T distribution with 1 DOF
 %!test
 %! x = rand (10, 1);
-%! assert(cauchy_pdf (x, 0, 1), tpdf (x, 1), eps);
+%! assert (cauchy_pdf (x, 0, 1), tpdf (x, 1), eps);
 
 %% Test input validation
 %!error cauchy_pdf ()
 %!error cauchy_pdf (1,2)
 %!error cauchy_pdf (1,2,3,4)
-%!error cauchy_pdf (ones(3),ones(2),ones(2))
-%!error cauchy_pdf (ones(2),ones(3),ones(2))
-%!error cauchy_pdf (ones(2),ones(2),ones(3))
+%!error cauchy_pdf (ones (3), ones (2), ones (2))
+%!error cauchy_pdf (ones (2), ones (3), ones (2))
+%!error cauchy_pdf (ones (2), ones (2), ones (3))
 %!error cauchy_pdf (i, 2, 2)
 %!error cauchy_pdf (2, i, 2)
 %!error cauchy_pdf (2, 2, i)
--- a/scripts/statistics/distributions/cauchy_rnd.m
+++ b/scripts/statistics/distributions/cauchy_rnd.m
@@ -84,7 +84,7 @@
 
   if (isscalar (location) && isscalar (scale))
     if (!isinf (location) && (scale > 0) && (scale < Inf))
-      rnd = location - cot (pi * rand (sz)) * scale;
+      rnd = location - cot (pi * rand (sz, cls)) * scale;
     else
       rnd = NaN (sz, cls);
     endif
@@ -92,41 +92,41 @@
     rnd = NaN (sz, cls);
 
     k = !isinf (location) & (scale > 0) & (scale < Inf);
-    rnd(k) = location(k)(:) - cot (pi * rand (sum (k(:)), 1)) .* scale(k)(:);
+    rnd(k) = location(k)(:) - cot (pi * rand (sum (k(:)), 1, cls)) .* scale(k)(:);
   endif
 
 endfunction
 
 
-%!assert(size (cauchy_rnd (1,2)), [1, 1]);
-%!assert(size (cauchy_rnd (ones(2,1), 2)), [2, 1]);
-%!assert(size (cauchy_rnd (ones(2,2), 2)), [2, 2]);
-%!assert(size (cauchy_rnd (1, 2*ones(2,1))), [2, 1]);
-%!assert(size (cauchy_rnd (1, 2*ones(2,2))), [2, 2]);
-%!assert(size (cauchy_rnd (1, 2, 3)), [3, 3]);
-%!assert(size (cauchy_rnd (1, 2, [4 1])), [4, 1]);
-%!assert(size (cauchy_rnd (1, 2, 4, 1)), [4, 1]);
+%!assert (size (cauchy_rnd (1,2)), [1, 1])
+%!assert (size (cauchy_rnd (ones (2,1), 2)), [2, 1])
+%!assert (size (cauchy_rnd (ones (2,2), 2)), [2, 2])
+%!assert (size (cauchy_rnd (1, 2*ones (2,1))), [2, 1])
+%!assert (size (cauchy_rnd (1, 2*ones (2,2))), [2, 2])
+%!assert (size (cauchy_rnd (1, 2, 3)), [3, 3])
+%!assert (size (cauchy_rnd (1, 2, [4 1])), [4, 1])
+%!assert (size (cauchy_rnd (1, 2, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (cauchy_rnd (1, 2)), "double");
-%!assert(class (cauchy_rnd (single(1), 2)), "single");
-%!assert(class (cauchy_rnd (single([1 1]), 2)), "single");
-%!assert(class (cauchy_rnd (1, single(2))), "single");
-%!assert(class (cauchy_rnd (1, single([2 2]))), "single");
+%!assert (class (cauchy_rnd (1, 2)), "double")
+%!assert (class (cauchy_rnd (single (1), 2)), "single")
+%!assert (class (cauchy_rnd (single ([1 1]), 2)), "single")
+%!assert (class (cauchy_rnd (1, single (2))), "single")
+%!assert (class (cauchy_rnd (1, single ([2 2]))), "single")
 
 %% Test input validation
 %!error cauchy_rnd ()
 %!error cauchy_rnd (1)
-%!error cauchy_rnd (ones(3),ones(2))
-%!error cauchy_rnd (ones(2),ones(3))
+%!error cauchy_rnd (ones (3), ones (2))
+%!error cauchy_rnd (ones (2), ones (3))
 %!error cauchy_rnd (i, 2)
 %!error cauchy_rnd (2, i)
 %!error cauchy_rnd (1,2, -1)
-%!error cauchy_rnd (1,2, ones(2))
+%!error cauchy_rnd (1,2, ones (2))
 %!error cauchy_rnd (1,2, [2 -1 2])
-%!error cauchy_rnd (1,2, 1, ones(2))
+%!error cauchy_rnd (1,2, 1, ones (2))
 %!error cauchy_rnd (1,2, 1, -1)
-%!error cauchy_rnd (ones(2,2), 2, 3)
-%!error cauchy_rnd (ones(2,2), 2, [3, 2])
-%!error cauchy_rnd (ones(2,2), 2, 2, 3)
+%!error cauchy_rnd (ones (2,2), 2, 3)
+%!error cauchy_rnd (ones (2,2), 2, [3, 2])
+%!error cauchy_rnd (ones (2,2), 2, 2, 3)
 
--- a/scripts/statistics/distributions/chi2cdf.m
+++ b/scripts/statistics/distributions/chi2cdf.m
@@ -52,22 +52,22 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 2];
 %! y = [0, 1 - exp(-x(2:end)/2)];
-%!assert(chi2cdf (x, 2*ones(1,5)), y, eps);
-%!assert(chi2cdf (x, 2), y, eps);
-%!assert(chi2cdf (x, 2*[1 0 NaN 1 1]), [y(1) NaN NaN y(4:5)], eps);
-%!assert(chi2cdf ([x(1:2) NaN x(4:5)], 2), [y(1:2) NaN y(4:5)], eps);
+%!assert (chi2cdf (x, 2*ones (1,5)), y, eps)
+%!assert (chi2cdf (x, 2), y, eps)
+%!assert (chi2cdf (x, 2*[1 0 NaN 1 1]), [y(1) NaN NaN y(4:5)], eps)
+%!assert (chi2cdf ([x(1:2) NaN x(4:5)], 2), [y(1:2) NaN y(4:5)], eps)
 
 %% Test class of input preserved
-%!assert(chi2cdf ([x, NaN], 2), [y, NaN], eps);
-%!assert(chi2cdf (single([x, NaN]), 2), single([y, NaN]), eps("single"));
-%!assert(chi2cdf ([x, NaN], single(2)), single([y, NaN]), eps("single"));
+%!assert (chi2cdf ([x, NaN], 2), [y, NaN], eps)
+%!assert (chi2cdf (single ([x, NaN]), 2), single ([y, NaN]), eps ("single"))
+%!assert (chi2cdf ([x, NaN], single (2)), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error chi2cdf ()
 %!error chi2cdf (1)
 %!error chi2cdf (1,2,3)
-%!error chi2cdf (ones(3),ones(2))
-%!error chi2cdf (ones(2),ones(3))
+%!error chi2cdf (ones (3), ones (2))
+%!error chi2cdf (ones (2), ones (3))
 %!error chi2cdf (i, 2)
 %!error chi2cdf (2, i)
 
--- a/scripts/statistics/distributions/chi2inv.m
+++ b/scripts/statistics/distributions/chi2inv.m
@@ -51,22 +51,22 @@
 
 %!shared x
 %! x = [-1 0 0.3934693402873666 1 2];
-%!assert(chi2inv (x, 2*ones(1,5)), [NaN 0 1 Inf NaN], 5*eps);
-%!assert(chi2inv (x, 2), [NaN 0 1 Inf NaN], 5*eps);
-%!assert(chi2inv (x, 2*[0 1 NaN 1 1]), [NaN 0 NaN Inf NaN], 5*eps);
-%!assert(chi2inv ([x(1:2) NaN x(4:5)], 2), [NaN 0 NaN Inf NaN], 5*eps);
+%!assert (chi2inv (x, 2*ones (1,5)), [NaN 0 1 Inf NaN], 5*eps)
+%!assert (chi2inv (x, 2), [NaN 0 1 Inf NaN], 5*eps)
+%!assert (chi2inv (x, 2*[0 1 NaN 1 1]), [NaN 0 NaN Inf NaN], 5*eps)
+%!assert (chi2inv ([x(1:2) NaN x(4:5)], 2), [NaN 0 NaN Inf NaN], 5*eps)
 
 %% Test class of input preserved
-%!assert(chi2inv ([x, NaN], 2), [NaN 0 1 Inf NaN NaN], 5*eps);
-%!assert(chi2inv (single([x, NaN]), 2), single([NaN 0 1 Inf NaN NaN]), 5*eps("single"));
-%!assert(chi2inv ([x, NaN], single(2)), single([NaN 0 1 Inf NaN NaN]), 5*eps("single"));
+%!assert (chi2inv ([x, NaN], 2), [NaN 0 1 Inf NaN NaN], 5*eps)
+%!assert (chi2inv (single ([x, NaN]), 2), single ([NaN 0 1 Inf NaN NaN]), 5*eps ("single"))
+%!assert (chi2inv ([x, NaN], single (2)), single ([NaN 0 1 Inf NaN NaN]), 5*eps ("single"))
 
 %% Test input validation
 %!error chi2inv ()
 %!error chi2inv (1)
 %!error chi2inv (1,2,3)
-%!error chi2inv (ones(3),ones(2))
-%!error chi2inv (ones(2),ones(3))
+%!error chi2inv (ones (3), ones (2))
+%!error chi2inv (ones (2), ones (3))
 %!error chi2inv (i, 2)
 %!error chi2inv (2, i)
 
--- a/scripts/statistics/distributions/chi2pdf.m
+++ b/scripts/statistics/distributions/chi2pdf.m
@@ -52,21 +52,21 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 Inf];
 %! y = [0, 1/2 * exp(-x(2:5)/2)];
-%!assert(chi2pdf (x, 2*ones(1,5)), y);
-%!assert(chi2pdf (x, 2), y);
-%!assert(chi2pdf (x, 2*[1 0 NaN 1 1]), [y(1) NaN NaN y(4:5)]);
-%!assert(chi2pdf ([x, NaN], 2), [y, NaN]);
+%!assert (chi2pdf (x, 2*ones (1,5)), y)
+%!assert (chi2pdf (x, 2), y)
+%!assert (chi2pdf (x, 2*[1 0 NaN 1 1]), [y(1) NaN NaN y(4:5)])
+%!assert (chi2pdf ([x, NaN], 2), [y, NaN])
 
 %% Test class of input preserved
-%!assert(chi2pdf (single([x, NaN]), 2), single([y, NaN]));
-%!assert(chi2pdf ([x, NaN], single(2)), single([y, NaN]));
+%!assert (chi2pdf (single ([x, NaN]), 2), single ([y, NaN]))
+%!assert (chi2pdf ([x, NaN], single (2)), single ([y, NaN]))
 
 %% Test input validation
 %!error chi2pdf ()
 %!error chi2pdf (1)
 %!error chi2pdf (1,2,3)
-%!error chi2pdf (ones(3),ones(2))
-%!error chi2pdf (ones(2),ones(3))
+%!error chi2pdf (ones (3), ones (2))
+%!error chi2pdf (ones (2), ones (3))
 %!error chi2pdf (i, 2)
 %!error chi2pdf (2, i)
 
--- a/scripts/statistics/distributions/chi2rnd.m
+++ b/scripts/statistics/distributions/chi2rnd.m
@@ -77,10 +77,7 @@
 
   if (isscalar (n))
     if ((n > 0) && (n < Inf))
-      rnd = 2 * randg (n/2, sz);
-      if (strcmp (cls, "single"))
-        rnd = single (rnd);
-      endif
+      rnd = 2 * randg (n/2, sz, cls);
     else
       rnd = NaN (sz, cls);
     endif
@@ -88,33 +85,33 @@
     rnd = NaN (sz, cls);
 
     k = (n > 0) | (n < Inf);
-    rnd(k) = 2 * randg (n(k)/2);
+    rnd(k) = 2 * randg (n(k)/2, cls);
   endif
 
 endfunction
 
 
-%!assert(size (chi2rnd (2)), [1, 1]);
-%!assert(size (chi2rnd (ones(2,1))), [2, 1]);
-%!assert(size (chi2rnd (ones(2,2))), [2, 2]);
-%!assert(size (chi2rnd (1, 3)), [3, 3]);
-%!assert(size (chi2rnd (1, [4 1])), [4, 1]);
-%!assert(size (chi2rnd (1, 4, 1)), [4, 1]);
+%!assert (size (chi2rnd (2)), [1, 1])
+%!assert (size (chi2rnd (ones (2,1))), [2, 1])
+%!assert (size (chi2rnd (ones (2,2))), [2, 2])
+%!assert (size (chi2rnd (1, 3)), [3, 3])
+%!assert (size (chi2rnd (1, [4 1])), [4, 1])
+%!assert (size (chi2rnd (1, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (chi2rnd (2)), "double");
-%!assert(class (chi2rnd (single(2))), "single");
-%!assert(class (chi2rnd (single([2 2]))), "single");
+%!assert (class (chi2rnd (2)), "double")
+%!assert (class (chi2rnd (single (2))), "single")
+%!assert (class (chi2rnd (single ([2 2]))), "single")
 
 %% Test input validation
 %!error chi2rnd ()
-%!error chi2rnd (ones(3),ones(2))
-%!error chi2rnd (ones(2),ones(3))
+%!error chi2rnd (ones (3), ones (2))
+%!error chi2rnd (ones (2), ones (3))
 %!error chi2rnd (i)
 %!error chi2rnd (1, -1)
-%!error chi2rnd (1, ones(2))
+%!error chi2rnd (1, ones (2))
 %!error chi2rnd (1, [2 -1 2])
-%!error chi2rnd (ones(2,2), 3)
-%!error chi2rnd (ones(2,2), [3, 2])
-%!error chi2rnd (ones(2,2), 2, 3)
+%!error chi2rnd (ones (2,2), 3)
+%!error chi2rnd (ones (2,2), [3, 2])
+%!error chi2rnd (ones (2,2), 2, 3)
 
--- a/scripts/statistics/distributions/discrete_cdf.m
+++ b/scripts/statistics/distributions/discrete_cdf.m
@@ -58,24 +58,24 @@
 %!shared x,v,p,y
 %! x = [-1 0.1 1.1 1.9 3];
 %! v = 0.1:0.2:1.9;
-%! p = 1/length(v) * ones(1, length(v));
+%! p = 1/length(v) * ones (1, length(v));
 %! y = [0 0.1 0.6 1 1];
-%!assert(discrete_cdf ([x, NaN], v, p), [y, NaN], eps);
+%!assert (discrete_cdf ([x, NaN], v, p), [y, NaN], eps)
 
 %% Test class of input preserved
-%!assert(discrete_cdf (single([x, NaN]), v, p), single([y, NaN]), 2*eps("single"));
-%!assert(discrete_cdf ([x, NaN], single(v), p), single([y, NaN]), 2*eps("single"));
-%!assert(discrete_cdf ([x, NaN], v, single(p)), single([y, NaN]), 2*eps("single"));
+%!assert (discrete_cdf (single ([x, NaN]), v, p), single ([y, NaN]), 2*eps ("single"))
+%!assert (discrete_cdf ([x, NaN], single (v), p), single ([y, NaN]), 2*eps ("single"))
+%!assert (discrete_cdf ([x, NaN], v, single (p)), single ([y, NaN]), 2*eps ("single"))
 
 %% Test input validation
 %!error discrete_cdf ()
 %!error discrete_cdf (1)
 %!error discrete_cdf (1,2)
 %!error discrete_cdf (1,2,3,4)
-%!error discrete_cdf (1, ones(2), ones(2,1))
-%!error discrete_cdf (1, [1 ; NaN], ones(2,1))
-%!error discrete_cdf (1, ones(2,1), ones(1,1))
-%!error discrete_cdf (1, ones(2,1), [1 -1])
-%!error discrete_cdf (1, ones(2,1), [1 NaN])
-%!error discrete_cdf (1, ones(2,1), [0  0])
+%!error discrete_cdf (1, ones (2), ones (2,1))
+%!error discrete_cdf (1, [1 ; NaN], ones (2,1))
+%!error discrete_cdf (1, ones (2,1), ones (1,1))
+%!error discrete_cdf (1, ones (2,1), [1 -1])
+%!error discrete_cdf (1, ones (2,1), [1 NaN])
+%!error discrete_cdf (1, ones (2,1), [0  0])
 
--- a/scripts/statistics/distributions/discrete_inv.m
+++ b/scripts/statistics/distributions/discrete_inv.m
@@ -73,23 +73,23 @@
 %!shared x,v,p,y
 %! x = [-1 0 0.1 0.5 1 2];
 %! v = 0.1:0.2:1.9;
-%! p = 1/length(v) * ones(1, length(v));
+%! p = 1/length(v) * ones (1, length(v));
 %! y = [NaN v(1) v(1) v(end/2) v(end) NaN];
-%!assert(discrete_inv ([x, NaN], v, p), [y, NaN], eps);
+%!assert (discrete_inv ([x, NaN], v, p), [y, NaN], eps)
 
 %% Test class of input preserved
-%!assert(discrete_inv (single([x, NaN]), v, p), single([y, NaN]), eps("single"));
-%!assert(discrete_inv ([x, NaN], single(v), p), single([y, NaN]), eps("single"));
-%!assert(discrete_inv ([x, NaN], v, single(p)), single([y, NaN]), eps("single"));
+%!assert (discrete_inv (single ([x, NaN]), v, p), single ([y, NaN]), eps ("single"))
+%!assert (discrete_inv ([x, NaN], single (v), p), single ([y, NaN]), eps ("single"))
+%!assert (discrete_inv ([x, NaN], v, single (p)), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error discrete_inv ()
 %!error discrete_inv (1)
 %!error discrete_inv (1,2)
 %!error discrete_inv (1,2,3,4)
-%!error discrete_inv (1, ones(2), ones(2,1))
-%!error discrete_inv (1, ones(2,1), ones(1,1))
-%!error discrete_inv (1, ones(2,1), [1 NaN])
-%!error discrete_inv (1, ones(2,1), [1 -1])
-%!error discrete_inv (1, ones(2,1), [0  0])
+%!error discrete_inv (1, ones (2), ones (2,1))
+%!error discrete_inv (1, ones (2,1), ones (1,1))
+%!error discrete_inv (1, ones (2,1), [1 NaN])
+%!error discrete_inv (1, ones (2,1), [1 -1])
+%!error discrete_inv (1, ones (2,1), [0  0])
 
--- a/scripts/statistics/distributions/discrete_pdf.m
+++ b/scripts/statistics/distributions/discrete_pdf.m
@@ -62,24 +62,24 @@
 %!shared x,v,p,y
 %! x = [-1 0.1 1.1 1.9 3];
 %! v = 0.1:0.2:1.9;
-%! p = 1/length(v) * ones(1, length(v));
+%! p = 1/length (v) * ones (1, length (v));
 %! y = [0 0.1 0.1 0.1 0];
-%!assert(discrete_pdf ([x, NaN], v, p), [y, NaN], 5*eps);
+%!assert (discrete_pdf ([x, NaN], v, p), [y, NaN], 5*eps)
 
 %% Test class of input preserved
-%!assert(discrete_pdf (single([x, NaN]), v, p), single([y, NaN]), 5*eps("single"));
-%!assert(discrete_pdf ([x, NaN], single(v), p), single([y, NaN]), 5*eps("single"));
-%!assert(discrete_pdf ([x, NaN], v, single(p)), single([y, NaN]), 5*eps("single"));
+%!assert (discrete_pdf (single ([x, NaN]), v, p), single ([y, NaN]), 5*eps ("single"))
+%!assert (discrete_pdf ([x, NaN], single (v), p), single ([y, NaN]), 5*eps ("single"))
+%!assert (discrete_pdf ([x, NaN], v, single (p)), single ([y, NaN]), 5*eps ("single"))
 
 %% Test input validation
 %!error discrete_pdf ()
 %!error discrete_pdf (1)
 %!error discrete_pdf (1,2)
 %!error discrete_pdf (1,2,3,4)
-%!error discrete_pdf (1, ones(2), ones(2,1))
-%!error discrete_pdf (1, [1 ; NaN], ones(2,1))
-%!error discrete_pdf (1, ones(2,1), ones(1,1))
-%!error discrete_pdf (1, ones(2,1), [1 -1])
-%!error discrete_pdf (1, ones(2,1), [1 NaN])
-%!error discrete_pdf (1, ones(2,1), [0  0])
+%!error discrete_pdf (1, ones (2), ones (2,1))
+%!error discrete_pdf (1, [1 ; NaN], ones (2,1))
+%!error discrete_pdf (1, ones (2,1), ones (1,1))
+%!error discrete_pdf (1, ones (2,1), [1 -1])
+%!error discrete_pdf (1, ones (2,1), [1 NaN])
+%!error discrete_pdf (1, ones (2,1), [0  0])
 
--- a/scripts/statistics/distributions/discrete_rnd.m
+++ b/scripts/statistics/distributions/discrete_rnd.m
@@ -77,13 +77,13 @@
 endfunction
 
 
-%!assert(size (discrete_rnd (1:2, 1:2, 3)), [3, 3]);
-%!assert(size (discrete_rnd (1:2, 1:2, [4 1])), [4, 1]);
-%!assert(size (discrete_rnd (1:2, 1:2, 4, 1)), [4, 1]);
+%!assert (size (discrete_rnd (1:2, 1:2, 3)), [3, 3])
+%!assert (size (discrete_rnd (1:2, 1:2, [4 1])), [4, 1])
+%!assert (size (discrete_rnd (1:2, 1:2, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (discrete_rnd (1:2, 1:2)), "double");
-%!assert(class (discrete_rnd (single(1:2), 1:2)), "single");
+%!assert (class (discrete_rnd (1:2, 1:2)), "double")
+%!assert (class (discrete_rnd (single (1:2), 1:2)), "single")
 ## FIXME: Maybe this should work, maybe it shouldn't.
 #%!assert(class (discrete_rnd (1:2, single(1:2))), "single");
 
@@ -91,14 +91,14 @@
 %!error discrete_rnd ()
 %!error discrete_rnd (1)
 %!error discrete_rnd (1:2,1:2, -1)
-%!error discrete_rnd (1:2,1:2, ones(2))
+%!error discrete_rnd (1:2,1:2, ones (2))
 %!error discrete_rnd (1:2,1:2, [2 -1 2])
-%!error discrete_rnd (1:2,1:2, 1, ones(2))
+%!error discrete_rnd (1:2,1:2, 1, ones (2))
 %!error discrete_rnd (1:2,1:2, 1, -1)
 %% test v,p verification
-%!error discrete_rnd (1, ones(2), ones(2,1))
-%!error discrete_rnd (1, ones(2,1), ones(1,1))
-%!error discrete_rnd (1, ones(2,1), [1 -1])
-%!error discrete_rnd (1, ones(2,1), [1 NaN])
-%!error discrete_rnd (1, ones(2,1), [0  0])
+%!error discrete_rnd (1, ones (2), ones (2,1))
+%!error discrete_rnd (1, ones (2,1), ones (1,1))
+%!error discrete_rnd (1, ones (2,1), [1 -1])
+%!error discrete_rnd (1, ones (2,1), [1 NaN])
+%!error discrete_rnd (1, ones (2,1), [0  0])
 
--- a/scripts/statistics/distributions/empirical_cdf.m
+++ b/scripts/statistics/distributions/empirical_cdf.m
@@ -46,17 +46,17 @@
 %! x = [-1 0.1 1.1 1.9 3];
 %! v = 0.1:0.2:1.9;
 %! y = [0 0.1 0.6 1 1];
-%!assert(empirical_cdf (x, v), y, eps);
-%!assert(empirical_cdf ([x(1) NaN x(3:5)], v), [0 NaN 0.6 1 1], eps);
+%!assert (empirical_cdf (x, v), y, eps)
+%!assert (empirical_cdf ([x(1) NaN x(3:5)], v), [0 NaN 0.6 1 1], eps)
 
 %% Test class of input preserved
-%!assert(empirical_cdf ([x, NaN], v), [y, NaN], eps);
-%!assert(empirical_cdf (single([x, NaN]), v), single([y, NaN]), eps);
-%!assert(empirical_cdf ([x, NaN], single(v)), single([y, NaN]), eps);
+%!assert (empirical_cdf ([x, NaN], v), [y, NaN], eps)
+%!assert (empirical_cdf (single ([x, NaN]), v), single ([y, NaN]), eps)
+%!assert (empirical_cdf ([x, NaN], single (v)), single ([y, NaN]), eps)
 
 %% Test input validation
 %!error empirical_cdf ()
 %!error empirical_cdf (1)
 %!error empirical_cdf (1,2,3)
-%!error empirical_cdf (1, ones(2))
+%!error empirical_cdf (1, ones (2))
 
--- a/scripts/statistics/distributions/empirical_inv.m
+++ b/scripts/statistics/distributions/empirical_inv.m
@@ -46,16 +46,16 @@
 %! x = [-1 0 0.1 0.5 1 2];
 %! v = 0.1:0.2:1.9;
 %! y = [NaN v(1) v(1) v(end/2) v(end) NaN];
-%!assert(empirical_inv (x, v), y, eps);
+%!assert (empirical_inv (x, v), y, eps)
 
 %% Test class of input preserved
-%!assert(empirical_inv ([x, NaN], v), [y, NaN], eps);
-%!assert(empirical_inv (single([x, NaN]), v), single([y, NaN]), eps);
-%!assert(empirical_inv ([x, NaN], single(v)), single([y, NaN]), eps);
+%!assert (empirical_inv ([x, NaN], v), [y, NaN], eps)
+%!assert (empirical_inv (single ([x, NaN]), v), single ([y, NaN]), eps)
+%!assert (empirical_inv ([x, NaN], single (v)), single ([y, NaN]), eps)
 
 %% Test input validation
 %!error empirical_inv ()
 %!error empirical_inv (1)
 %!error empirical_inv (1,2,3)
-%!error empirical_inv (1, ones(2))
+%!error empirical_inv (1, ones (2))
 
--- a/scripts/statistics/distributions/empirical_pdf.m
+++ b/scripts/statistics/distributions/empirical_pdf.m
@@ -46,15 +46,15 @@
 %! x = [-1 0.1 1.1 1.9 3];
 %! v = 0.1:0.2:1.9;
 %! y = [0 0.1 0.1 0.1 0];
-%!assert(empirical_pdf (x, v), y);
+%!assert (empirical_pdf (x, v), y)
 
 %% Test class of input preserved
-%!assert(empirical_pdf (single(x), v), single (y));
-%!assert(empirical_pdf (x, single(v)), single (y));
+%!assert (empirical_pdf (single (x), v), single (y))
+%!assert (empirical_pdf (x, single (v)), single (y))
 
 %% Test input validation
 %!error empirical_pdf ()
 %!error empirical_pdf (1)
 %!error empirical_pdf (1,2,3)
-%!error empirical_inv (1, ones(2))
+%!error empirical_inv (1, ones (2))
 
--- a/scripts/statistics/distributions/empirical_rnd.m
+++ b/scripts/statistics/distributions/empirical_rnd.m
@@ -53,17 +53,17 @@
 endfunction
 
 
-%!assert(size (empirical_rnd (ones (3, 1))), [3, 1]);
-%!assert(size (empirical_rnd (1:2, [4 1])), [4, 1]);
-%!assert(size (empirical_rnd (1:2, 4, 1)), [4, 1]);
+%!assert (size (empirical_rnd (ones (3, 1))), [3, 1])
+%!assert (size (empirical_rnd (1:2, [4 1])), [4, 1])
+%!assert (size (empirical_rnd (1:2, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (empirical_rnd (1:2, 1)), "double");
-%!assert(class (empirical_rnd (single(1:2), 1)), "single");
+%!assert (class (empirical_rnd (1:2, 1)), "double")
+%!assert (class (empirical_rnd (single (1:2), 1)), "single")
 
 %% Test input validation
 %!error empirical_rnd ()
-%!error empirical_rnd (ones(2), 1)
+%!error empirical_rnd (ones (2), 1)
 %% test data verification
-%!error empirical_rnd (ones(2), 1, 1)
+%!error empirical_rnd (ones (2), 1, 1)
 
--- a/scripts/statistics/distributions/expcdf.m
+++ b/scripts/statistics/distributions/expcdf.m
@@ -59,10 +59,10 @@
   cdf(k) = 1;
 
   k = (x > 0) & (x < Inf) & (lambda > 0);
-  if isscalar (lambda)
-    cdf(k) = 1 - exp (- x(k) / lambda);
+  if (isscalar (lambda))
+    cdf(k) = 1 - exp (-x(k) / lambda);
   else
-    cdf(k) = 1 - exp (- x(k) ./ lambda(k));
+    cdf(k) = 1 - exp (-x(k) ./ lambda(k));
   endif
 
 endfunction
@@ -71,21 +71,21 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 Inf];
 %! y = [0, 1 - exp(-x(2:end)/2)];
-%!assert(expcdf (x, 2*ones(1,5)), y);
-%!assert(expcdf (x, 2), y);
-%!assert(expcdf (x, 2*[1 0 NaN 1 1]), [y(1) NaN NaN y(4:5)]);
+%!assert (expcdf (x, 2*ones (1,5)), y)
+%!assert (expcdf (x, 2), y)
+%!assert (expcdf (x, 2*[1 0 NaN 1 1]), [y(1) NaN NaN y(4:5)])
 
 %% Test class of input preserved
-%!assert(expcdf ([x, NaN], 2), [y, NaN]);
-%!assert(expcdf (single([x, NaN]), 2), single([y, NaN]));
-%!assert(expcdf ([x, NaN], single(2)), single([y, NaN]));
+%!assert (expcdf ([x, NaN], 2), [y, NaN])
+%!assert (expcdf (single ([x, NaN]), 2), single ([y, NaN]))
+%!assert (expcdf ([x, NaN], single (2)), single ([y, NaN]))
 
 %% Test input validation
 %!error expcdf ()
 %!error expcdf (1)
 %!error expcdf (1,2,3)
-%!error expcdf (ones(3),ones(2))
-%!error expcdf (ones(2),ones(3))
+%!error expcdf (ones (3), ones (2))
+%!error expcdf (ones (2), ones (3))
 %!error expcdf (i, 2)
 %!error expcdf (2, i)
 
--- a/scripts/statistics/distributions/expinv.m
+++ b/scripts/statistics/distributions/expinv.m
@@ -63,7 +63,7 @@
   inv(k) = Inf;
 
   k = (x >= 0) & (x < 1) & (lambda > 0);
-  if isscalar (lambda)
+  if (isscalar (lambda))
     inv(k) = - lambda * log (1 - x(k));
   else
     inv(k) = - lambda(k) .* log (1 - x(k));
@@ -74,22 +74,22 @@
 
 %!shared x
 %! x = [-1 0 0.3934693402873666 1 2];
-%!assert(expinv (x, 2*ones(1,5)), [NaN 0 1 Inf NaN], eps);
-%!assert(expinv (x, 2), [NaN 0 1 Inf NaN], eps);
-%!assert(expinv (x, 2*[1 0 NaN 1 1]), [NaN NaN NaN Inf NaN], eps);
-%!assert(expinv ([x(1:2) NaN x(4:5)], 2), [NaN 0 NaN Inf NaN], eps);
+%!assert (expinv (x, 2*ones (1,5)), [NaN 0 1 Inf NaN], eps)
+%!assert (expinv (x, 2), [NaN 0 1 Inf NaN], eps)
+%!assert (expinv (x, 2*[1 0 NaN 1 1]), [NaN NaN NaN Inf NaN], eps)
+%!assert (expinv ([x(1:2) NaN x(4:5)], 2), [NaN 0 NaN Inf NaN], eps)
 
 %% Test class of input preserved
-%!assert(expinv ([x, NaN], 2), [NaN 0 1 Inf NaN NaN], eps);
-%!assert(expinv (single([x, NaN]), 2), single([NaN 0 1 Inf NaN NaN]), eps);
-%!assert(expinv ([x, NaN], single(2)), single([NaN 0 1 Inf NaN NaN]), eps);
+%!assert (expinv ([x, NaN], 2), [NaN 0 1 Inf NaN NaN], eps)
+%!assert (expinv (single ([x, NaN]), 2), single ([NaN 0 1 Inf NaN NaN]), eps)
+%!assert (expinv ([x, NaN], single (2)), single ([NaN 0 1 Inf NaN NaN]), eps)
 
 %% Test input validation
 %!error expinv ()
 %!error expinv (1)
 %!error expinv (1,2,3)
-%!error expinv (ones(3),ones(2))
-%!error expinv (ones(2),ones(3))
+%!error expinv (ones (3), ones (2))
+%!error expinv (ones (2), ones (3))
 %!error expinv (i, 2)
 %!error expinv (2, i)
 
--- a/scripts/statistics/distributions/exppdf.m
+++ b/scripts/statistics/distributions/exppdf.m
@@ -53,10 +53,10 @@
   pdf(k) = NaN;
 
   k = (x >= 0) & (x < Inf) & (lambda > 0);
-  if isscalar (lambda)
-    pdf(k) = exp (- x(k) / lambda) / lambda;
+  if (isscalar (lambda))
+    pdf(k) = exp (-x(k) / lambda) / lambda;
   else
-    pdf(k) = exp (- x(k) ./ lambda(k)) ./ lambda(k);
+    pdf(k) = exp (-x(k) ./ lambda(k)) ./ lambda(k);
   endif
 
 endfunction
@@ -65,20 +65,20 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 Inf];
 %! y = gampdf (x, 1, 2);
-%!assert(exppdf (x, 2*ones(1,5)), y);
-%!assert(exppdf (x, 2*[1 0 NaN 1 1]), [y(1) NaN NaN y(4:5)]);
-%!assert(exppdf ([x, NaN], 2), [y, NaN]);
+%!assert (exppdf (x, 2*ones (1,5)), y)
+%!assert (exppdf (x, 2*[1 0 NaN 1 1]), [y(1) NaN NaN y(4:5)])
+%!assert (exppdf ([x, NaN], 2), [y, NaN])
 
 %% Test class of input preserved
-%!assert(exppdf (single([x, NaN]), 2), single([y, NaN]));
-%!assert(exppdf ([x, NaN], single(2)), single([y, NaN]));
+%!assert (exppdf (single ([x, NaN]), 2), single ([y, NaN]))
+%!assert (exppdf ([x, NaN], single (2)), single ([y, NaN]))
 
 %% Test input validation
 %!error exppdf ()
 %!error exppdf (1)
 %!error exppdf (1,2,3)
-%!error exppdf (ones(3),ones(2))
-%!error exppdf (ones(2),ones(3))
+%!error exppdf (ones (3), ones (2))
+%!error exppdf (ones (2), ones (3))
 %!error exppdf (i, 2)
 %!error exppdf (2, i)
 
--- a/scripts/statistics/distributions/exprnd.m
+++ b/scripts/statistics/distributions/exprnd.m
@@ -77,7 +77,7 @@
 
   if (isscalar (lambda))
     if ((lambda > 0) && (lambda < Inf))
-      rnd = rande (sz) * lambda;
+      rnd = rande (sz, cls) * lambda;
     else
       rnd = NaN (sz, cls);
     endif
@@ -85,33 +85,33 @@
     rnd = NaN (sz, cls);
 
     k = (lambda > 0) & (lambda < Inf);
-    rnd(k) = rande (sum (k(:)), 1) .* lambda(k)(:);
+    rnd(k) = rande (sum (k(:)), 1, cls) .* lambda(k)(:);
   endif
 
 endfunction
 
 
-%!assert(size (exprnd (2)), [1, 1]);
-%!assert(size (exprnd (ones(2,1))), [2, 1]);
-%!assert(size (exprnd (ones(2,2))), [2, 2]);
-%!assert(size (exprnd (1, 3)), [3, 3]);
-%!assert(size (exprnd (1, [4 1])), [4, 1]);
-%!assert(size (exprnd (1, 4, 1)), [4, 1]);
+%!assert (size (exprnd (2)), [1, 1])
+%!assert (size (exprnd (ones (2,1))), [2, 1])
+%!assert (size (exprnd (ones (2,2))), [2, 2])
+%!assert (size (exprnd (1, 3)), [3, 3])
+%!assert (size (exprnd (1, [4 1])), [4, 1])
+%!assert (size (exprnd (1, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (exprnd (1)), "double");
-%!assert(class (exprnd (single(1))), "single");
-%!assert(class (exprnd (single([1 1]))), "single");
+%!assert (class (exprnd (1)), "double")
+%!assert (class (exprnd (single (1))), "single")
+%!assert (class (exprnd (single ([1 1]))), "single")
 
 %% Test input validation
 %!error exprnd ()
 %!error exprnd (1, -1)
-%!error exprnd (1, ones(2))
+%!error exprnd (1, ones (2))
 %!error exprnd (i)
 %!error exprnd (1, [2 -1 2])
 %!error exprnd (1, 2, -1)
-%!error exprnd (1, 2, ones(2))
-%!error exprnd (ones(2,2), 3)
-%!error exprnd (ones(2,2), [3, 2])
-%!error exprnd (ones(2,2), 2, 3)
+%!error exprnd (1, 2, ones (2))
+%!error exprnd (ones (2,2), 3)
+%!error exprnd (ones (2,2), [3, 2])
+%!error exprnd (ones (2,2), 2, 3)
 
--- a/scripts/statistics/distributions/fcdf.m
+++ b/scripts/statistics/distributions/fcdf.m
@@ -69,27 +69,27 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 2 Inf];
 %! y = [0 0 1/3 1/2 2/3 1];
-%!assert(fcdf (x, 2*ones(1,6), 2*ones(1,6)), y, eps);
-%!assert(fcdf (x, 2, 2*ones(1,6)), y, eps);
-%!assert(fcdf (x, 2*ones(1,6), 2), y, eps);
-%!assert(fcdf (x, [0 NaN Inf 2 2 2], 2), [NaN NaN NaN y(4:6)], eps);
-%!assert(fcdf (x, 2, [0 NaN Inf 2 2 2]), [NaN NaN NaN y(4:6)], eps);
-%!assert(fcdf ([x(1:2) NaN x(4:6)], 2, 2), [y(1:2) NaN y(4:6)], eps);
+%!assert (fcdf (x, 2*ones (1,6), 2*ones (1,6)), y, eps)
+%!assert (fcdf (x, 2, 2*ones (1,6)), y, eps)
+%!assert (fcdf (x, 2*ones (1,6), 2), y, eps)
+%!assert (fcdf (x, [0 NaN Inf 2 2 2], 2), [NaN NaN NaN y(4:6)], eps)
+%!assert (fcdf (x, 2, [0 NaN Inf 2 2 2]), [NaN NaN NaN y(4:6)], eps)
+%!assert (fcdf ([x(1:2) NaN x(4:6)], 2, 2), [y(1:2) NaN y(4:6)], eps)
 
 %% Test class of input preserved
-%!assert(fcdf ([x, NaN], 2, 2), [y, NaN], eps);
-%!assert(fcdf (single([x, NaN]), 2, 2), single([y, NaN]), eps("single"));
-%!assert(fcdf ([x, NaN], single(2), 2), single([y, NaN]), eps("single"));
-%!assert(fcdf ([x, NaN], 2, single(2)), single([y, NaN]), eps("single"));
+%!assert (fcdf ([x, NaN], 2, 2), [y, NaN], eps)
+%!assert (fcdf (single ([x, NaN]), 2, 2), single ([y, NaN]), eps ("single"))
+%!assert (fcdf ([x, NaN], single (2), 2), single ([y, NaN]), eps ("single"))
+%!assert (fcdf ([x, NaN], 2, single (2)), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error fcdf ()
 %!error fcdf (1)
 %!error fcdf (1,2)
 %!error fcdf (1,2,3,4)
-%!error fcdf (ones(3),ones(2),ones(2))
-%!error fcdf (ones(2),ones(3),ones(2))
-%!error fcdf (ones(2),ones(2),ones(3))
+%!error fcdf (ones (3), ones (2), ones (2))
+%!error fcdf (ones (2), ones (3), ones (2))
+%!error fcdf (ones (2), ones (2), ones (3))
 %!error fcdf (i, 2, 2)
 %!error fcdf (2, i, 2)
 %!error fcdf (2, 2, i)
--- a/scripts/statistics/distributions/finv.m
+++ b/scripts/statistics/distributions/finv.m
@@ -66,27 +66,27 @@
 
 %!shared x
 %! x = [-1 0 0.5 1 2];
-%!assert(finv (x, 2*ones(1,5), 2*ones(1,5)), [NaN 0 1 Inf NaN]);
-%!assert(finv (x, 2, 2*ones(1,5)), [NaN 0 1 Inf NaN]);
-%!assert(finv (x, 2*ones(1,5), 2), [NaN 0 1 Inf NaN]);
-%!assert(finv (x, [2 -Inf NaN Inf 2], 2), [NaN NaN NaN NaN NaN]);
-%!assert(finv (x, 2, [2 -Inf NaN Inf 2]), [NaN NaN NaN NaN NaN]);
-%!assert(finv ([x(1:2) NaN x(4:5)], 2, 2), [NaN 0 NaN Inf NaN]);
+%!assert (finv (x, 2*ones (1,5), 2*ones (1,5)), [NaN 0 1 Inf NaN])
+%!assert (finv (x, 2, 2*ones (1,5)), [NaN 0 1 Inf NaN])
+%!assert (finv (x, 2*ones (1,5), 2), [NaN 0 1 Inf NaN])
+%!assert (finv (x, [2 -Inf NaN Inf 2], 2), [NaN NaN NaN NaN NaN])
+%!assert (finv (x, 2, [2 -Inf NaN Inf 2]), [NaN NaN NaN NaN NaN])
+%!assert (finv ([x(1:2) NaN x(4:5)], 2, 2), [NaN 0 NaN Inf NaN])
 
 %% Test class of input preserved
-%!assert(finv ([x, NaN], 2, 2), [NaN 0 1 Inf NaN NaN]);
-%!assert(finv (single([x, NaN]), 2, 2), single([NaN 0 1 Inf NaN NaN]));
-%!assert(finv ([x, NaN], single(2), 2), single([NaN 0 1 Inf NaN NaN]));
-%!assert(finv ([x, NaN], 2, single(2)), single([NaN 0 1 Inf NaN NaN]));
+%!assert (finv ([x, NaN], 2, 2), [NaN 0 1 Inf NaN NaN])
+%!assert (finv (single ([x, NaN]), 2, 2), single ([NaN 0 1 Inf NaN NaN]))
+%!assert (finv ([x, NaN], single (2), 2), single ([NaN 0 1 Inf NaN NaN]))
+%!assert (finv ([x, NaN], 2, single (2)), single ([NaN 0 1 Inf NaN NaN]))
 
 %% Test input validation
 %!error finv ()
 %!error finv (1)
 %!error finv (1,2)
 %!error finv (1,2,3,4)
-%!error finv (ones(3),ones(2),ones(2))
-%!error finv (ones(2),ones(3),ones(2))
-%!error finv (ones(2),ones(2),ones(3))
+%!error finv (ones (3), ones (2), ones (2))
+%!error finv (ones (2), ones (3), ones (2))
+%!error finv (ones (2), ones (2), ones (3))
 %!error finv (i, 2, 2)
 %!error finv (2, i, 2)
 %!error finv (2, 2, i)
--- a/scripts/statistics/distributions/fpdf.m
+++ b/scripts/statistics/distributions/fpdf.m
@@ -74,31 +74,31 @@
 %! x = rand (10,1);
 %! x = x(x > 0.1 & x < 0.9);
 %! y = tpdf (sqrt (x), 2) ./ sqrt (x);
-%! assert(fpdf (x, 1, 2), y, 5*eps);
+%! assert (fpdf (x, 1, 2), y, 5*eps);
 
 %!shared x,y
 %! x = [-1 0 0.5 1 2];
 %! y = [0 0 4/9 1/4 1/9];
-%!assert(fpdf (x, 2*ones(1,5), 2*ones(1,5)), y, eps);
-%!assert(fpdf (x, 2, 2*ones(1,5)), y, eps);
-%!assert(fpdf (x, 2*ones(1,5), 2), y, eps);
-%!assert(fpdf (x, [0 NaN Inf 2 2], 2), [NaN NaN NaN y(4:5)], eps);
-%!assert(fpdf (x, 2, [0 NaN Inf 2 2]), [NaN NaN NaN y(4:5)], eps);
-%!assert(fpdf ([x, NaN], 2, 2), [y, NaN], eps);
+%!assert (fpdf (x, 2*ones (1,5), 2*ones (1,5)), y, eps)
+%!assert (fpdf (x, 2, 2*ones (1,5)), y, eps)
+%!assert (fpdf (x, 2*ones (1,5), 2), y, eps)
+%!assert (fpdf (x, [0 NaN Inf 2 2], 2), [NaN NaN NaN y(4:5)], eps)
+%!assert (fpdf (x, 2, [0 NaN Inf 2 2]), [NaN NaN NaN y(4:5)], eps)
+%!assert (fpdf ([x, NaN], 2, 2), [y, NaN], eps)
 
 %% Test class of input preserved
-%!assert(fpdf (single([x, NaN]), 2, 2), single([y, NaN]), eps("single"));
-%!assert(fpdf ([x, NaN], single(2), 2), single([y, NaN]), eps("single"));
-%!assert(fpdf ([x, NaN], 2, single(2)), single([y, NaN]), eps("single"));
+%!assert (fpdf (single ([x, NaN]), 2, 2), single ([y, NaN]), eps ("single"))
+%!assert (fpdf ([x, NaN], single (2), 2), single ([y, NaN]), eps ("single"))
+%!assert (fpdf ([x, NaN], 2, single (2)), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error fpdf ()
 %!error fpdf (1)
 %!error fpdf (1,2)
 %!error fpdf (1,2,3,4)
-%!error fpdf (ones(3),ones(2),ones(2))
-%!error fpdf (ones(2),ones(3),ones(2))
-%!error fpdf (ones(2),ones(2),ones(3))
+%!error fpdf (ones (3), ones (2), ones (2))
+%!error fpdf (ones (2), ones (3), ones (2))
+%!error fpdf (ones (2), ones (2), ones (3))
 %!error fpdf (i, 2, 2)
 %!error fpdf (2, i, 2)
 %!error fpdf (2, 2, i)
--- a/scripts/statistics/distributions/frnd.m
+++ b/scripts/statistics/distributions/frnd.m
@@ -84,7 +84,7 @@
 
   if (isscalar (m) && isscalar (n))
     if ((m > 0) && (m < Inf) && (n > 0) && (n < Inf))
-      rnd = n/m * randg (m/2, sz) ./ randg (n/2, sz);
+      rnd = n/m * randg (m/2, sz, cls) ./ randg (n/2, sz, cls);
     else
       rnd = NaN (sz, cls);
     endif
@@ -92,41 +92,41 @@
     rnd = NaN (sz, cls);
 
     k = (m > 0) & (m < Inf) & (n > 0) & (n < Inf);
-    rnd(k) = n(k) ./ m(k) .* randg (m(k)/2) ./ randg (n(k)/2);
+    rnd(k) = n(k) ./ m(k) .* randg (m(k)/2, cls) ./ randg (n(k)/2, cls);
   endif
 
 endfunction
 
 
-%!assert(size (frnd (1,2)), [1, 1]);
-%!assert(size (frnd (ones(2,1), 2)), [2, 1]);
-%!assert(size (frnd (ones(2,2), 2)), [2, 2]);
-%!assert(size (frnd (1, 2*ones(2,1))), [2, 1]);
-%!assert(size (frnd (1, 2*ones(2,2))), [2, 2]);
-%!assert(size (frnd (1, 2, 3)), [3, 3]);
-%!assert(size (frnd (1, 2, [4 1])), [4, 1]);
-%!assert(size (frnd (1, 2, 4, 1)), [4, 1]);
+%!assert (size (frnd (1,2)), [1, 1])
+%!assert (size (frnd (ones (2,1), 2)), [2, 1])
+%!assert (size (frnd (ones (2,2), 2)), [2, 2])
+%!assert (size (frnd (1, 2*ones (2,1))), [2, 1])
+%!assert (size (frnd (1, 2*ones (2,2))), [2, 2])
+%!assert (size (frnd (1, 2, 3)), [3, 3])
+%!assert (size (frnd (1, 2, [4 1])), [4, 1])
+%!assert (size (frnd (1, 2, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (frnd (1, 2)), "double");
-%!assert(class (frnd (single(1), 2)), "single");
-%!assert(class (frnd (single([1 1]), 2)), "single");
-%!assert(class (frnd (1, single(2))), "single");
-%!assert(class (frnd (1, single([2 2]))), "single");
+%!assert (class (frnd (1, 2)), "double")
+%!assert (class (frnd (single (1), 2)), "single")
+%!assert (class (frnd (single ([1 1]), 2)), "single")
+%!assert (class (frnd (1, single (2))), "single")
+%!assert (class (frnd (1, single ([2 2]))), "single")
 
 %% Test input validation
 %!error frnd ()
 %!error frnd (1)
-%!error frnd (ones(3),ones(2))
-%!error frnd (ones(2),ones(3))
+%!error frnd (ones (3), ones (2))
+%!error frnd (ones (2), ones (3))
 %!error frnd (i, 2)
 %!error frnd (2, i)
 %!error frnd (1,2, -1)
-%!error frnd (1,2, ones(2))
+%!error frnd (1,2, ones (2))
 %!error frnd (1, 2, [2 -1 2])
-%!error frnd (1,2, 1, ones(2))
+%!error frnd (1,2, 1, ones (2))
 %!error frnd (1,2, 1, -1)
-%!error frnd (ones(2,2), 2, 3)
-%!error frnd (ones(2,2), 2, [3, 2])
-%!error frnd (ones(2,2), 2, 2, 3)
+%!error frnd (ones (2,2), 2, 3)
+%!error frnd (ones (2,2), 2, [3, 2])
+%!error frnd (ones (2,2), 2, 2, 3)
 
--- a/scripts/statistics/distributions/gamcdf.m
+++ b/scripts/statistics/distributions/gamcdf.m
@@ -66,25 +66,25 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 2 Inf];
 %! y = [0, gammainc(x(2:end), 1)];
-%!assert(gamcdf (x, ones(1,6), ones(1,6)), y);
-%!assert(gamcdf (x, 1, ones(1,6)), y);
-%!assert(gamcdf (x, ones(1,6), 1), y);
-%!assert(gamcdf (x, [0 -Inf NaN Inf 1 1], 1), [NaN NaN NaN NaN y(5:6)]);
-%!assert(gamcdf (x, 1, [0 -Inf NaN Inf 1 1]), [NaN NaN NaN NaN y(5:6)]);
-%!assert(gamcdf ([x(1:2) NaN x(4:6)], 1, 1), [y(1:2) NaN y(4:6)]);
+%!assert (gamcdf (x, ones (1,6), ones (1,6)), y)
+%!assert (gamcdf (x, 1, ones (1,6)), y)
+%!assert (gamcdf (x, ones (1,6), 1), y)
+%!assert (gamcdf (x, [0 -Inf NaN Inf 1 1], 1), [NaN NaN NaN NaN y(5:6)])
+%!assert (gamcdf (x, 1, [0 -Inf NaN Inf 1 1]), [NaN NaN NaN NaN y(5:6)])
+%!assert (gamcdf ([x(1:2) NaN x(4:6)], 1, 1), [y(1:2) NaN y(4:6)])
 
 %% Test class of input preserved
-%!assert(gamcdf ([x, NaN], 1, 1), [y, NaN]);
-%!assert(gamcdf (single([x, NaN]), 1, 1), single([y, NaN]), eps("single"));
+%!assert (gamcdf ([x, NaN], 1, 1), [y, NaN])
+%!assert (gamcdf (single ([x, NaN]), 1, 1), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error gamcdf ()
 %!error gamcdf (1)
 %!error gamcdf (1,2)
 %!error gamcdf (1,2,3,4)
-%!error gamcdf (ones(3),ones(2),ones(2))
-%!error gamcdf (ones(2),ones(3),ones(2))
-%!error gamcdf (ones(2),ones(2),ones(3))
+%!error gamcdf (ones (3), ones (2), ones (2))
+%!error gamcdf (ones (2), ones (3), ones (2))
+%!error gamcdf (ones (2), ones (2), ones (3))
 %!error gamcdf (i, 2, 2)
 %!error gamcdf (2, i, 2)
 %!error gamcdf (2, 2, i)
--- a/scripts/statistics/distributions/gaminv.m
+++ b/scripts/statistics/distributions/gaminv.m
@@ -102,27 +102,27 @@
 
 %!shared x
 %! x = [-1 0 0.63212055882855778 1 2];
-%!assert(gaminv (x, ones(1,5), ones(1,5)), [NaN 0 1 Inf NaN], eps);
-%!assert(gaminv (x, 1, ones(1,5)), [NaN 0 1 Inf NaN], eps);
-%!assert(gaminv (x, ones(1,5), 1), [NaN 0 1 Inf NaN], eps);
-%!assert(gaminv (x, [1 -Inf NaN Inf 1], 1), [NaN NaN NaN NaN NaN]);
-%!assert(gaminv (x, 1, [1 -Inf NaN Inf 1]), [NaN NaN NaN NaN NaN]);
-%!assert(gaminv ([x(1:2) NaN x(4:5)], 1, 1), [NaN 0 NaN Inf NaN]);
+%!assert (gaminv (x, ones (1,5), ones (1,5)), [NaN 0 1 Inf NaN], eps)
+%!assert (gaminv (x, 1, ones (1,5)), [NaN 0 1 Inf NaN], eps)
+%!assert (gaminv (x, ones (1,5), 1), [NaN 0 1 Inf NaN], eps)
+%!assert (gaminv (x, [1 -Inf NaN Inf 1], 1), [NaN NaN NaN NaN NaN])
+%!assert (gaminv (x, 1, [1 -Inf NaN Inf 1]), [NaN NaN NaN NaN NaN])
+%!assert (gaminv ([x(1:2) NaN x(4:5)], 1, 1), [NaN 0 NaN Inf NaN])
 
 %% Test class of input preserved
-%!assert(gaminv ([x, NaN], 1, 1), [NaN 0 1 Inf NaN NaN], eps);
-%!assert(gaminv (single([x, NaN]), 1, 1), single([NaN 0 1 Inf NaN NaN]), eps("single"));
-%!assert(gaminv ([x, NaN], single(1), 1), single([NaN 0 1 Inf NaN NaN]), eps("single"));
-%!assert(gaminv ([x, NaN], 1, single(1)), single([NaN 0 1 Inf NaN NaN]), eps("single"));
+%!assert (gaminv ([x, NaN], 1, 1), [NaN 0 1 Inf NaN NaN], eps)
+%!assert (gaminv (single ([x, NaN]), 1, 1), single ([NaN 0 1 Inf NaN NaN]), eps ("single"))
+%!assert (gaminv ([x, NaN], single (1), 1), single ([NaN 0 1 Inf NaN NaN]), eps ("single"))
+%!assert (gaminv ([x, NaN], 1, single (1)), single ([NaN 0 1 Inf NaN NaN]), eps ("single"))
 
 %% Test input validation
 %!error gaminv ()
 %!error gaminv (1)
 %!error gaminv (1,2)
 %!error gaminv (1,2,3,4)
-%!error gaminv (ones(3),ones(2),ones(2))
-%!error gaminv (ones(2),ones(3),ones(2))
-%!error gaminv (ones(2),ones(2),ones(3))
+%!error gaminv (ones (3), ones (2), ones (2))
+%!error gaminv (ones (2), ones (3), ones (2))
+%!error gaminv (ones (2), ones (2), ones (3))
 %!error gaminv (i, 2, 2)
 %!error gaminv (2, i, 2)
 %!error gaminv (2, 2, i)
--- a/scripts/statistics/distributions/gampdf.m
+++ b/scripts/statistics/distributions/gampdf.m
@@ -77,26 +77,26 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 Inf];
 %! y = [0 exp(-x(2:end))];
-%!assert(gampdf (x, ones(1,5), ones(1,5)), y);
-%!assert(gampdf (x, 1, ones(1,5)), y);
-%!assert(gampdf (x, ones(1,5), 1), y);
-%!assert(gampdf (x, [0 -Inf NaN Inf 1], 1), [NaN NaN NaN NaN y(5)]);
-%!assert(gampdf (x, 1, [0 -Inf NaN Inf 1]), [NaN NaN NaN 0 y(5)]);
-%!assert(gampdf ([x, NaN], 1, 1), [y, NaN]);
+%!assert (gampdf (x, ones (1,5), ones (1,5)), y)
+%!assert (gampdf (x, 1, ones (1,5)), y)
+%!assert (gampdf (x, ones (1,5), 1), y)
+%!assert (gampdf (x, [0 -Inf NaN Inf 1], 1), [NaN NaN NaN NaN y(5)])
+%!assert (gampdf (x, 1, [0 -Inf NaN Inf 1]), [NaN NaN NaN 0 y(5)])
+%!assert (gampdf ([x, NaN], 1, 1), [y, NaN])
 
 %% Test class of input preserved
-%!assert(gampdf (single([x, NaN]), 1, 1), single([y, NaN]));
-%!assert(gampdf ([x, NaN], single(1), 1), single([y, NaN]));
-%!assert(gampdf ([x, NaN], 1, single(1)), single([y, NaN]));
+%!assert (gampdf (single ([x, NaN]), 1, 1), single ([y, NaN]))
+%!assert (gampdf ([x, NaN], single (1), 1), single ([y, NaN]))
+%!assert (gampdf ([x, NaN], 1, single (1)), single ([y, NaN]))
 
 %% Test input validation
 %!error gampdf ()
 %!error gampdf (1)
 %!error gampdf (1,2)
 %!error gampdf (1,2,3,4)
-%!error gampdf (ones(3),ones(2),ones(2))
-%!error gampdf (ones(2),ones(3),ones(2))
-%!error gampdf (ones(2),ones(2),ones(3))
+%!error gampdf (ones (3), ones (2), ones (2))
+%!error gampdf (ones (2), ones (3), ones (2))
+%!error gampdf (ones (2), ones (2), ones (3))
 %!error gampdf (i, 2, 2)
 %!error gampdf (2, i, 2)
 %!error gampdf (2, 2, i)
--- a/scripts/statistics/distributions/gamrnd.m
+++ b/scripts/statistics/distributions/gamrnd.m
@@ -84,10 +84,7 @@
 
   if (isscalar (a) && isscalar (b))
     if ((a > 0) && (a < Inf) && (b > 0) && (b < Inf))
-      rnd = b * randg (a, sz);
-      if (strcmp (cls, "single"))
-        rnd = single (rnd);
-      endif
+      rnd = b * randg (a, sz, cls);
     else 
       rnd = NaN (sz, cls);
     endif
@@ -95,41 +92,41 @@
     rnd = NaN (sz, cls);
 
     k = (a > 0) & (a < Inf) & (b > 0) & (b < Inf);
-    rnd(k) = b(k) .* randg (a(k));
+    rnd(k) = b(k) .* randg (a(k), cls);
   endif
 
 endfunction
 
 
-%!assert(size (gamrnd (1,2)), [1, 1]);
-%!assert(size (gamrnd (ones(2,1), 2)), [2, 1]);
-%!assert(size (gamrnd (ones(2,2), 2)), [2, 2]);
-%!assert(size (gamrnd (1, 2*ones(2,1))), [2, 1]);
-%!assert(size (gamrnd (1, 2*ones(2,2))), [2, 2]);
-%!assert(size (gamrnd (1, 2, 3)), [3, 3]);
-%!assert(size (gamrnd (1, 2, [4 1])), [4, 1]);
-%!assert(size (gamrnd (1, 2, 4, 1)), [4, 1]);
+%!assert (size (gamrnd (1,2)), [1, 1])
+%!assert (size (gamrnd (ones (2,1), 2)), [2, 1])
+%!assert (size (gamrnd (ones (2,2), 2)), [2, 2])
+%!assert (size (gamrnd (1, 2*ones (2,1))), [2, 1])
+%!assert (size (gamrnd (1, 2*ones (2,2))), [2, 2])
+%!assert (size (gamrnd (1, 2, 3)), [3, 3])
+%!assert (size (gamrnd (1, 2, [4 1])), [4, 1])
+%!assert (size (gamrnd (1, 2, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (gamrnd (1, 2)), "double");
-%!assert(class (gamrnd (single(1), 2)), "single");
-%!assert(class (gamrnd (single([1 1]), 2)), "single");
-%!assert(class (gamrnd (1, single(2))), "single");
-%!assert(class (gamrnd (1, single([2 2]))), "single");
+%!assert (class (gamrnd (1, 2)), "double")
+%!assert (class (gamrnd (single (1), 2)), "single")
+%!assert (class (gamrnd (single ([1 1]), 2)), "single")
+%!assert (class (gamrnd (1, single (2))), "single")
+%!assert (class (gamrnd (1, single ([2 2]))), "single")
 
 %% Test input validation
 %!error gamrnd ()
 %!error gamrnd (1)
-%!error gamrnd (ones(3),ones(2))
-%!error gamrnd (ones(2),ones(3))
+%!error gamrnd (ones (3), ones (2))
+%!error gamrnd (ones (2), ones (3))
 %!error gamrnd (i, 2)
 %!error gamrnd (2, i)
 %!error gamrnd (1,2, -1)
-%!error gamrnd (1,2, ones(2))
+%!error gamrnd (1,2, ones (2))
 %!error gamrnd (1, 2, [2 -1 2])
-%!error gamrnd (1,2, 1, ones(2))
+%!error gamrnd (1,2, 1, ones (2))
 %!error gamrnd (1,2, 1, -1)
-%!error gamrnd (ones(2,2), 2, 3)
-%!error gamrnd (ones(2,2), 2, [3, 2])
-%!error gamrnd (ones(2,2), 2, 2, 3)
+%!error gamrnd (ones (2,2), 2, 3)
+%!error gamrnd (ones (2,2), 2, [3, 2])
+%!error gamrnd (ones (2,2), 2, 2, 3)
 
--- a/scripts/statistics/distributions/geocdf.m
+++ b/scripts/statistics/distributions/geocdf.m
@@ -68,22 +68,22 @@
 %!shared x,y
 %! x = [-1 0 1 Inf];
 %! y = [0 0.5 0.75 1];
-%!assert(geocdf (x, 0.5*ones(1,4)), y);
-%!assert(geocdf (x, 0.5), y);
-%!assert(geocdf (x, 0.5*[-1 NaN 4 1]), [NaN NaN NaN y(4)]);
-%!assert(geocdf ([x(1:2) NaN x(4)], 0.5), [y(1:2) NaN y(4)]);
+%!assert (geocdf (x, 0.5*ones (1,4)), y)
+%!assert (geocdf (x, 0.5), y)
+%!assert (geocdf (x, 0.5*[-1 NaN 4 1]), [NaN NaN NaN y(4)])
+%!assert (geocdf ([x(1:2) NaN x(4)], 0.5), [y(1:2) NaN y(4)])
 
 %% Test class of input preserved
-%!assert(geocdf ([x, NaN], 0.5), [y, NaN]);
-%!assert(geocdf (single([x, NaN]), 0.5), single([y, NaN]));
-%!assert(geocdf ([x, NaN], single(0.5)), single([y, NaN]));
+%!assert (geocdf ([x, NaN], 0.5), [y, NaN])
+%!assert (geocdf (single ([x, NaN]), 0.5), single ([y, NaN]))
+%!assert (geocdf ([x, NaN], single (0.5)), single ([y, NaN]))
 
 %% Test input validation
 %!error geocdf ()
 %!error geocdf (1)
 %!error geocdf (1,2,3)
-%!error geocdf (ones(3),ones(2))
-%!error geocdf (ones(2),ones(3))
+%!error geocdf (ones (3), ones (2))
+%!error geocdf (ones (2), ones (3))
 %!error geocdf (i, 2)
 %!error geocdf (2, i)
 
--- a/scripts/statistics/distributions/geoinv.m
+++ b/scripts/statistics/distributions/geoinv.m
@@ -64,22 +64,22 @@
 
 %!shared x
 %! x = [-1 0 0.75 1 2];
-%!assert(geoinv (x, 0.5*ones(1,5)), [NaN 0 1 Inf NaN]);
-%!assert(geoinv (x, 0.5), [NaN 0 1 Inf NaN]);
-%!assert(geoinv (x, 0.5*[1 -1 NaN 4 1]), [NaN NaN NaN NaN NaN]);
-%!assert(geoinv ([x(1:2) NaN x(4:5)], 0.5), [NaN 0 NaN Inf NaN]);
+%!assert (geoinv (x, 0.5*ones (1,5)), [NaN 0 1 Inf NaN])
+%!assert (geoinv (x, 0.5), [NaN 0 1 Inf NaN])
+%!assert (geoinv (x, 0.5*[1 -1 NaN 4 1]), [NaN NaN NaN NaN NaN])
+%!assert (geoinv ([x(1:2) NaN x(4:5)], 0.5), [NaN 0 NaN Inf NaN])
 
 %% Test class of input preserved
-%!assert(geoinv ([x, NaN], 0.5), [NaN 0 1 Inf NaN NaN]);
-%!assert(geoinv (single([x, NaN]), 0.5), single([NaN 0 1 Inf NaN NaN]));
-%!assert(geoinv ([x, NaN], single(0.5)), single([NaN 0 1 Inf NaN NaN]));
+%!assert (geoinv ([x, NaN], 0.5), [NaN 0 1 Inf NaN NaN])
+%!assert (geoinv (single ([x, NaN]), 0.5), single ([NaN 0 1 Inf NaN NaN]))
+%!assert (geoinv ([x, NaN], single (0.5)), single ([NaN 0 1 Inf NaN NaN]))
 
 %% Test input validation
 %!error geoinv ()
 %!error geoinv (1)
 %!error geoinv (1,2,3)
-%!error geoinv (ones(3),ones(2))
-%!error geoinv (ones(2),ones(3))
+%!error geoinv (ones (3), ones (2))
+%!error geoinv (ones (2), ones (3))
 %!error geoinv (i, 2)
 %!error geoinv (2, i)
 
--- a/scripts/statistics/distributions/geopdf.m
+++ b/scripts/statistics/distributions/geopdf.m
@@ -65,21 +65,21 @@
 %!shared x,y
 %! x = [-1 0 1 Inf];
 %! y = [0, 1/2, 1/4, NaN];
-%!assert(geopdf (x, 0.5*ones(1,4)), y);
-%!assert(geopdf (x, 0.5), y);
-%!assert(geopdf (x, 0.5*[-1 NaN 4 1]), [NaN NaN NaN y(4)]);
-%!assert(geopdf ([x, NaN], 0.5), [y, NaN]);
+%!assert (geopdf (x, 0.5*ones (1,4)), y)
+%!assert (geopdf (x, 0.5), y)
+%!assert (geopdf (x, 0.5*[-1 NaN 4 1]), [NaN NaN NaN y(4)])
+%!assert (geopdf ([x, NaN], 0.5), [y, NaN])
 
 %% Test class of input preserved
-%!assert(geopdf (single([x, NaN]), 0.5), single([y, NaN]), 5*eps("single"));
-%!assert(geopdf ([x, NaN], single(0.5)), single([y, NaN]), 5*eps("single"));
+%!assert (geopdf (single ([x, NaN]), 0.5), single ([y, NaN]), 5*eps ("single"))
+%!assert (geopdf ([x, NaN], single (0.5)), single ([y, NaN]), 5*eps ("single"))
 
 %% Test input validation
 %!error geopdf ()
 %!error geopdf (1)
 %!error geopdf (1,2,3)
-%!error geopdf (ones(3),ones(2))
-%!error geopdf (ones(2),ones(3))
+%!error geopdf (ones (3), ones (2))
+%!error geopdf (ones (2), ones (3))
 %!error geopdf (i, 2)
 %!error geopdf (2, i)
 
--- a/scripts/statistics/distributions/geornd.m
+++ b/scripts/statistics/distributions/geornd.m
@@ -77,7 +77,7 @@
 
   if (isscalar (p))
     if (p > 0 && p < 1);
-      rnd = floor (- rande (sz) ./ log (1 - p));
+      rnd = floor (- rande (sz, cls) ./ log (1 - p));
     elseif (p == 0)
       rnd = Inf (sz, cls);
     elseif (p == 1)
@@ -86,10 +86,10 @@
       rnd = NaN (sz, cls);
     endif
   else
-    rnd = floor (- rande (sz) ./ log (1 - p));
+    rnd = floor (- rande (sz, cls) ./ log (1 - p));
 
     k = !(p >= 0) | !(p <= 1);
-  rnd(k) = NaN;
+    rnd(k) = NaN;
 
     k = (p == 0);
     rnd(k) = Inf;
@@ -98,28 +98,28 @@
 endfunction
 
 
-%!assert(size (geornd (0.5)), [1, 1]);
-%!assert(size (geornd (0.5*ones(2,1))), [2, 1]);
-%!assert(size (geornd (0.5*ones(2,2))), [2, 2]);
-%!assert(size (geornd (0.5, 3)), [3, 3]);
-%!assert(size (geornd (0.5, [4 1])), [4, 1]);
-%!assert(size (geornd (0.5, 4, 1)), [4, 1]);
+%!assert (size (geornd (0.5)), [1, 1])
+%!assert (size (geornd (0.5*ones (2,1))), [2, 1])
+%!assert (size (geornd (0.5*ones (2,2))), [2, 2])
+%!assert (size (geornd (0.5, 3)), [3, 3])
+%!assert (size (geornd (0.5, [4 1])), [4, 1])
+%!assert (size (geornd (0.5, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (geornd (0.5)), "double");
-%!assert(class (geornd (single(0.5))), "single");
-%!assert(class (geornd (single([0.5 0.5]))), "single");
-%!assert(class (geornd (single(0))), "single");
-%!assert(class (geornd (single(1))), "single");
+%!assert (class (geornd (0.5)), "double")
+%!assert (class (geornd (single (0.5))), "single")
+%!assert (class (geornd (single ([0.5 0.5]))), "single")
+%!assert (class (geornd (single (0))), "single")
+%!assert (class (geornd (single (1))), "single")
 
 %% Test input validation
 %!error geornd ()
-%!error geornd (ones(3),ones(2))
-%!error geornd (ones(2),ones(3))
+%!error geornd (ones (3), ones (2))
+%!error geornd (ones (2), ones (3))
 %!error geornd (i)
 %!error geornd (1, -1)
-%!error geornd (1, ones(2))
+%!error geornd (1, ones (2))
 %!error geornd (1, [2 -1 2])
-%!error geornd (ones(2,2), 2, 3)
-%!error geornd (ones(2,2), 3, 2)
+%!error geornd (ones (2,2), 2, 3)
+%!error geornd (ones (2,2), 3, 2)
 
--- a/scripts/statistics/distributions/hygecdf.m
+++ b/scripts/statistics/distributions/hygecdf.m
@@ -76,22 +76,22 @@
 %!shared x,y
 %! x = [-1 0 1 2 3];
 %! y = [0 1/6 5/6 1 1];
-%!assert(hygecdf (x, 4*ones(1,5), 2, 2), y, eps);
-%!assert(hygecdf (x, 4, 2*ones(1,5), 2), y, eps);
-%!assert(hygecdf (x, 4, 2, 2*ones(1,5)), y, eps);
-%!assert(hygecdf (x, 4*[1 -1 NaN 1.1 1], 2, 2), [y(1) NaN NaN NaN y(5)], eps);
-%!assert(hygecdf (x, 4, 2*[1 -1 NaN 1.1 1], 2), [y(1) NaN NaN NaN y(5)], eps);
-%!assert(hygecdf (x, 4, 5, 2), [NaN NaN NaN NaN NaN]);
-%!assert(hygecdf (x, 4, 2, 2*[1 -1 NaN 1.1 1]), [y(1) NaN NaN NaN y(5)], eps);
-%!assert(hygecdf (x, 4, 2, 5), [NaN NaN NaN NaN NaN]);
-%!assert(hygecdf ([x(1:2) NaN x(4:5)], 4, 2, 2), [y(1:2) NaN y(4:5)], eps);
+%!assert (hygecdf (x, 4*ones (1,5), 2, 2), y, eps)
+%!assert (hygecdf (x, 4, 2*ones (1,5), 2), y, eps)
+%!assert (hygecdf (x, 4, 2, 2*ones (1,5)), y, eps)
+%!assert (hygecdf (x, 4*[1 -1 NaN 1.1 1], 2, 2), [y(1) NaN NaN NaN y(5)], eps)
+%!assert (hygecdf (x, 4, 2*[1 -1 NaN 1.1 1], 2), [y(1) NaN NaN NaN y(5)], eps)
+%!assert (hygecdf (x, 4, 5, 2), [NaN NaN NaN NaN NaN])
+%!assert (hygecdf (x, 4, 2, 2*[1 -1 NaN 1.1 1]), [y(1) NaN NaN NaN y(5)], eps)
+%!assert (hygecdf (x, 4, 2, 5), [NaN NaN NaN NaN NaN])
+%!assert (hygecdf ([x(1:2) NaN x(4:5)], 4, 2, 2), [y(1:2) NaN y(4:5)], eps)
 
 %% Test class of input preserved
-%!assert(hygecdf ([x, NaN], 4, 2, 2), [y, NaN], eps);
-%!assert(hygecdf (single([x, NaN]), 4, 2, 2), single([y, NaN]), eps("single"));
-%!assert(hygecdf ([x, NaN], single(4), 2, 2), single([y, NaN]), eps("single"));
-%!assert(hygecdf ([x, NaN], 4, single(2), 2), single([y, NaN]), eps("single"));
-%!assert(hygecdf ([x, NaN], 4, 2, single(2)), single([y, NaN]), eps("single"));
+%!assert (hygecdf ([x, NaN], 4, 2, 2), [y, NaN], eps)
+%!assert (hygecdf (single ([x, NaN]), 4, 2, 2), single ([y, NaN]), eps ("single"))
+%!assert (hygecdf ([x, NaN], single (4), 2, 2), single ([y, NaN]), eps ("single"))
+%!assert (hygecdf ([x, NaN], 4, single (2), 2), single ([y, NaN]), eps ("single"))
+%!assert (hygecdf ([x, NaN], 4, 2, single (2)), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error hygecdf ()
@@ -99,9 +99,9 @@
 %!error hygecdf (1,2)
 %!error hygecdf (1,2,3)
 %!error hygecdf (1,2,3,4,5)
-%!error hygecdf (ones(2), ones(3), 1, 1)
-%!error hygecdf (1, ones(2), ones(3), 1)
-%!error hygecdf (1, 1, ones(2), ones(3))
+%!error hygecdf (ones (2), ones (3), 1, 1)
+%!error hygecdf (1, ones (2), ones (3), 1)
+%!error hygecdf (1, 1, ones (2), ones (3))
 %!error hygecdf (i, 2, 2, 2)
 %!error hygecdf (2, i, 2, 2)
 %!error hygecdf (2, 2, i, 2)
--- a/scripts/statistics/distributions/hygeinv.m
+++ b/scripts/statistics/distributions/hygeinv.m
@@ -80,23 +80,23 @@
 
 %!shared x
 %! x = [-1 0 0.5 1 2];
-%!assert(hygeinv (x, 4*ones(1,5), 2*ones(1,5), 2*ones(1,5)), [NaN 0 1 2 NaN]);
-%!assert(hygeinv (x, 4*ones(1,5), 2, 2), [NaN 0 1 2 NaN]);
-%!assert(hygeinv (x, 4, 2*ones(1,5), 2), [NaN 0 1 2 NaN]);
-%!assert(hygeinv (x, 4, 2, 2*ones(1,5)), [NaN 0 1 2 NaN]);
-%!assert(hygeinv (x, 4*[1 -1 NaN 1.1 1], 2, 2), [NaN NaN NaN NaN NaN]);
-%!assert(hygeinv (x, 4, 2*[1 -1 NaN 1.1 1], 2), [NaN NaN NaN NaN NaN]);
-%!assert(hygeinv (x, 4, 5, 2), [NaN NaN NaN NaN NaN]);
-%!assert(hygeinv (x, 4, 2, 2*[1 -1 NaN 1.1 1]), [NaN NaN NaN NaN NaN]);
-%!assert(hygeinv (x, 4, 2, 5), [NaN NaN NaN NaN NaN]);
-%!assert(hygeinv ([x(1:2) NaN x(4:5)], 4, 2, 2), [NaN 0 NaN 2 NaN]);
+%!assert (hygeinv (x, 4*ones (1,5), 2*ones (1,5), 2*ones (1,5)), [NaN 0 1 2 NaN])
+%!assert (hygeinv (x, 4*ones (1,5), 2, 2), [NaN 0 1 2 NaN])
+%!assert (hygeinv (x, 4, 2*ones (1,5), 2), [NaN 0 1 2 NaN])
+%!assert (hygeinv (x, 4, 2, 2*ones (1,5)), [NaN 0 1 2 NaN])
+%!assert (hygeinv (x, 4*[1 -1 NaN 1.1 1], 2, 2), [NaN NaN NaN NaN NaN])
+%!assert (hygeinv (x, 4, 2*[1 -1 NaN 1.1 1], 2), [NaN NaN NaN NaN NaN])
+%!assert (hygeinv (x, 4, 5, 2), [NaN NaN NaN NaN NaN])
+%!assert (hygeinv (x, 4, 2, 2*[1 -1 NaN 1.1 1]), [NaN NaN NaN NaN NaN])
+%!assert (hygeinv (x, 4, 2, 5), [NaN NaN NaN NaN NaN])
+%!assert (hygeinv ([x(1:2) NaN x(4:5)], 4, 2, 2), [NaN 0 NaN 2 NaN])
 
 %% Test class of input preserved
-%!assert(hygeinv ([x, NaN], 4, 2, 2), [NaN 0 1 2 NaN NaN]);
-%!assert(hygeinv (single([x, NaN]), 4, 2, 2), single([NaN 0 1 2 NaN NaN]));
-%!assert(hygeinv ([x, NaN], single(4), 2, 2), single([NaN 0 1 2 NaN NaN]));
-%!assert(hygeinv ([x, NaN], 4, single(2), 2), single([NaN 0 1 2 NaN NaN]));
-%!assert(hygeinv ([x, NaN], 4, 2, single(2)), single([NaN 0 1 2 NaN NaN]));
+%!assert (hygeinv ([x, NaN], 4, 2, 2), [NaN 0 1 2 NaN NaN])
+%!assert (hygeinv (single ([x, NaN]), 4, 2, 2), single ([NaN 0 1 2 NaN NaN]))
+%!assert (hygeinv ([x, NaN], single (4), 2, 2), single ([NaN 0 1 2 NaN NaN]))
+%!assert (hygeinv ([x, NaN], 4, single (2), 2), single ([NaN 0 1 2 NaN NaN]))
+%!assert (hygeinv ([x, NaN], 4, 2, single (2)), single ([NaN 0 1 2 NaN NaN]))
 
 %% Test input validation
 %!error hygeinv ()
@@ -104,9 +104,9 @@
 %!error hygeinv (1,2)
 %!error hygeinv (1,2,3)
 %!error hygeinv (1,2,3,4,5)
-%!error hygeinv (ones(2), ones(3), 1, 1)
-%!error hygeinv (1, ones(2), ones(3), 1)
-%!error hygeinv (1, 1, ones(2), ones(3))
+%!error hygeinv (ones (2), ones (3), 1, 1)
+%!error hygeinv (1, ones (2), ones (3), 1)
+%!error hygeinv (1, 1, ones (2), ones (3))
 %!error hygeinv (i, 2, 2, 2)
 %!error hygeinv (2, i, 2, 2)
 %!error hygeinv (2, 2, i, 2)
--- a/scripts/statistics/distributions/hygepdf.m
+++ b/scripts/statistics/distributions/hygepdf.m
@@ -80,21 +80,21 @@
 %!shared x,y
 %! x = [-1 0 1 2 3];
 %! y = [0 1/6 4/6 1/6 0];
-%!assert(hygepdf (x, 4*ones(1,5), 2, 2), y);
-%!assert(hygepdf (x, 4, 2*ones(1,5), 2), y);
-%!assert(hygepdf (x, 4, 2, 2*ones(1,5)), y);
-%!assert(hygepdf (x, 4*[1 -1 NaN 1.1 1], 2, 2), [0 NaN NaN NaN 0]);
-%!assert(hygepdf (x, 4, 2*[1 -1 NaN 1.1 1], 2), [0 NaN NaN NaN 0]);
-%!assert(hygepdf (x, 4, 5, 2), [NaN NaN NaN NaN NaN]);
-%!assert(hygepdf (x, 4, 2, 2*[1 -1 NaN 1.1 1]), [0 NaN NaN NaN 0]);
-%!assert(hygepdf (x, 4, 2, 5), [NaN NaN NaN NaN NaN]);
-%!assert(hygepdf ([x, NaN], 4, 2, 2), [y, NaN], eps);
+%!assert (hygepdf (x, 4*ones (1,5), 2, 2), y)
+%!assert (hygepdf (x, 4, 2*ones (1,5), 2), y)
+%!assert (hygepdf (x, 4, 2, 2*ones (1,5)), y)
+%!assert (hygepdf (x, 4*[1 -1 NaN 1.1 1], 2, 2), [0 NaN NaN NaN 0])
+%!assert (hygepdf (x, 4, 2*[1 -1 NaN 1.1 1], 2), [0 NaN NaN NaN 0])
+%!assert (hygepdf (x, 4, 5, 2), [NaN NaN NaN NaN NaN])
+%!assert (hygepdf (x, 4, 2, 2*[1 -1 NaN 1.1 1]), [0 NaN NaN NaN 0])
+%!assert (hygepdf (x, 4, 2, 5), [NaN NaN NaN NaN NaN])
+%!assert (hygepdf ([x, NaN], 4, 2, 2), [y, NaN], eps)
 
 %% Test class of input preserved
-%!assert(hygepdf (single([x, NaN]), 4, 2, 2), single([y, NaN]));
-%!assert(hygepdf ([x, NaN], single(4), 2, 2), single([y, NaN]));
-%!assert(hygepdf ([x, NaN], 4, single(2), 2), single([y, NaN]));
-%!assert(hygepdf ([x, NaN], 4, 2, single(2)), single([y, NaN]));
+%!assert (hygepdf (single ([x, NaN]), 4, 2, 2), single ([y, NaN]))
+%!assert (hygepdf ([x, NaN], single (4), 2, 2), single ([y, NaN]))
+%!assert (hygepdf ([x, NaN], 4, single (2), 2), single ([y, NaN]))
+%!assert (hygepdf ([x, NaN], 4, 2, single (2)), single ([y, NaN]))
 
 %% Test input validation
 %!error hygepdf ()
@@ -102,9 +102,9 @@
 %!error hygepdf (1,2)
 %!error hygepdf (1,2,3)
 %!error hygepdf (1,2,3,4,5)
-%!error hygepdf (1, ones(3),ones(2),ones(2))
-%!error hygepdf (1, ones(2),ones(3),ones(2))
-%!error hygepdf (1, ones(2),ones(2),ones(3))
+%!error hygepdf (1, ones (3), ones (2), ones (2))
+%!error hygepdf (1, ones (2), ones (3), ones (2))
+%!error hygepdf (1, ones (2), ones (2), ones (3))
 %!error hygepdf (i, 2, 2, 2)
 %!error hygepdf (2, i, 2, 2)
 %!error hygepdf (2, 2, i, 2)
--- a/scripts/statistics/distributions/hygernd.m
+++ b/scripts/statistics/distributions/hygernd.m
@@ -110,39 +110,39 @@
 endfunction
 
 
-%!assert(size (hygernd (4,2,2)), [1, 1]);
-%!assert(size (hygernd (4*ones(2,1), 2,2)), [2, 1]);
-%!assert(size (hygernd (4*ones(2,2), 2,2)), [2, 2]);
-%!assert(size (hygernd (4, 2*ones(2,1), 2)), [2, 1]);
-%!assert(size (hygernd (4, 2*ones(2,2), 2)), [2, 2]);
-%!assert(size (hygernd (4, 2, 2*ones(2,1))), [2, 1]);
-%!assert(size (hygernd (4, 2, 2*ones(2,2))), [2, 2]);
-%!assert(size (hygernd (4, 2, 2, 3)), [3, 3]);
-%!assert(size (hygernd (4, 2, 2, [4 1])), [4, 1]);
-%!assert(size (hygernd (4, 2, 2, 4, 1)), [4, 1]);
+%!assert (size (hygernd (4,2,2)), [1, 1])
+%!assert (size (hygernd (4*ones (2,1), 2,2)), [2, 1])
+%!assert (size (hygernd (4*ones (2,2), 2,2)), [2, 2])
+%!assert (size (hygernd (4, 2*ones (2,1), 2)), [2, 1])
+%!assert (size (hygernd (4, 2*ones (2,2), 2)), [2, 2])
+%!assert (size (hygernd (4, 2, 2*ones (2,1))), [2, 1])
+%!assert (size (hygernd (4, 2, 2*ones (2,2))), [2, 2])
+%!assert (size (hygernd (4, 2, 2, 3)), [3, 3])
+%!assert (size (hygernd (4, 2, 2, [4 1])), [4, 1])
+%!assert (size (hygernd (4, 2, 2, 4, 1)), [4, 1])
 
-%!assert(class (hygernd (4,2,2)), "double");
-%!assert(class (hygernd (single(4),2,2)), "single");
-%!assert(class (hygernd (single([4 4]),2,2)), "single");
-%!assert(class (hygernd (4,single(2),2)), "single");
-%!assert(class (hygernd (4,single([2 2]),2)), "single");
-%!assert(class (hygernd (4,2,single(2))), "single");
-%!assert(class (hygernd (4,2,single([2 2]))), "single");
+%!assert (class (hygernd (4,2,2)), "double")
+%!assert (class (hygernd (single (4),2,2)), "single")
+%!assert (class (hygernd (single ([4 4]),2,2)), "single")
+%!assert (class (hygernd (4,single (2),2)), "single")
+%!assert (class (hygernd (4,single ([2 2]),2)), "single")
+%!assert (class (hygernd (4,2,single (2))), "single")
+%!assert (class (hygernd (4,2,single ([2 2]))), "single")
 
 %% Test input validation
 %!error hygernd ()
 %!error hygernd (1)
 %!error hygernd (1,2)
-%!error hygernd (ones(3),ones(2),ones(2), 2)
-%!error hygernd (ones(2),ones(3),ones(2), 2)
-%!error hygernd (ones(2),ones(2),ones(3), 2)
+%!error hygernd (ones (3), ones (2), ones (2), 2)
+%!error hygernd (ones (2), ones (3), ones (2), 2)
+%!error hygernd (ones (2), ones (2), ones (3), 2)
 %!error hygernd (i, 2, 2)
 %!error hygernd (2, i, 2)
 %!error hygernd (2, 2, i)
 %!error hygernd (4,2,2, -1)
-%!error hygernd (4,2,2, ones(2))
+%!error hygernd (4,2,2, ones (2))
 %!error hygernd (4,2,2, [2 -1 2])
-%!error hygernd (4*ones(2),2,2, 3)
-%!error hygernd (4*ones(2),2,2, [3, 2])
-%!error hygernd (4*ones(2),2,2, 3, 2)
+%!error hygernd (4*ones (2),2,2, 3)
+%!error hygernd (4*ones (2),2,2, [3, 2])
+%!error hygernd (4*ones (2),2,2, 3, 2)
 
--- a/scripts/statistics/distributions/kolmogorov_smirnov_cdf.m
+++ b/scripts/statistics/distributions/kolmogorov_smirnov_cdf.m
@@ -90,6 +90,6 @@
 %% Test input validation
 %!error kolmogorov_smirnov_cdf ()
 %!error kolmogorov_smirnov_cdf (1,2,3)
-%!error kolmogorov_smirnov_cdf (1, ones(2))
+%!error kolmogorov_smirnov_cdf (1, ones (2))
 %!error kolmogorov_smirnov_cdf ([], 1)
 
--- a/scripts/statistics/distributions/laplace_cdf.m
+++ b/scripts/statistics/distributions/laplace_cdf.m
@@ -44,10 +44,10 @@
 %!shared x,y
 %! x = [-Inf -log(2) 0 log(2) Inf];
 %! y = [0, 1/4, 1/2, 3/4, 1]; 
-%!assert(laplace_cdf ([x, NaN]), [y, NaN]);
+%!assert (laplace_cdf ([x, NaN]), [y, NaN])
 
 %% Test class of input preserved
-%!assert(laplace_cdf (single([x, NaN])), single([y, NaN]));
+%!assert (laplace_cdf (single ([x, NaN])), single ([y, NaN]))
 
 %% Test input validation
 %!error laplace_cdf ()
--- a/scripts/statistics/distributions/laplace_inv.m
+++ b/scripts/statistics/distributions/laplace_inv.m
@@ -51,11 +51,11 @@
 
 %!shared x
 %! x = [-1 0 0.5 1 2];
-%!assert(laplace_inv (x), [NaN -Inf 0 Inf NaN]);
+%!assert (laplace_inv (x), [NaN -Inf 0 Inf NaN])
 
 %% Test class of input preserved
-%!assert(laplace_inv ([x, NaN]), [NaN -Inf 0 Inf NaN NaN]);
-%!assert(laplace_inv (single([x, NaN])), single([NaN -Inf 0 Inf NaN NaN]));
+%!assert (laplace_inv ([x, NaN]), [NaN -Inf 0 Inf NaN NaN])
+%!assert (laplace_inv (single ([x, NaN])), single ([NaN -Inf 0 Inf NaN NaN]))
 
 %% Test input validation
 %!error laplace_inv ()
--- a/scripts/statistics/distributions/laplace_pdf.m
+++ b/scripts/statistics/distributions/laplace_pdf.m
@@ -44,10 +44,10 @@
 %!shared x,y
 %! x = [-Inf -log(2) 0 log(2) Inf];
 %! y = [0, 1/4, 1/2, 1/4, 0]; 
-%!assert(laplace_pdf ([x, NaN]), [y, NaN]);
+%!assert (laplace_pdf ([x, NaN]), [y, NaN])
 
 %% Test class of input preserved
-%!assert(laplace_pdf (single([x, NaN])), single([y, NaN]));
+%!assert (laplace_pdf (single ([x, NaN])), single ([y, NaN]))
 
 %% Test input validation
 %!error laplace_pdf ()
--- a/scripts/statistics/distributions/laplace_rnd.m
+++ b/scripts/statistics/distributions/laplace_rnd.m
@@ -60,15 +60,15 @@
 endfunction
 
 
-%!assert(size (laplace_rnd (3)), [3, 3]);
-%!assert(size (laplace_rnd ([4 1])), [4, 1]);
-%!assert(size (laplace_rnd (4,1)), [4, 1]);
+%!assert (size (laplace_rnd (3)), [3, 3])
+%!assert (size (laplace_rnd ([4 1])), [4, 1])
+%!assert (size (laplace_rnd (4,1)), [4, 1])
 
 %% Test input validation
 %!error laplace_rnd ()
 %!error laplace_rnd (-1)
-%!error laplace_rnd (ones(2))
+%!error laplace_rnd (ones (2))
 %!error laplace_rnd ([2 -1 2])
-%!error laplace_rnd (1, ones(2))
+%!error laplace_rnd (1, ones (2))
 %!error laplace_rnd (1, -1)
 
--- a/scripts/statistics/distributions/logistic_cdf.m
+++ b/scripts/statistics/distributions/logistic_cdf.m
@@ -44,10 +44,10 @@
 %!shared x,y
 %! x = [-Inf -log(3) 0 log(3) Inf];
 %! y = [0, 1/4, 1/2, 3/4, 1]; 
-%!assert(logistic_cdf ([x, NaN]), [y, NaN], eps);
+%!assert (logistic_cdf ([x, NaN]), [y, NaN], eps)
 
 %% Test class of input preserved
-%!assert(logistic_cdf (single([x, NaN])), single([y, NaN]), eps ("single"));
+%!assert (logistic_cdf (single ([x, NaN])), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error logistic_cdf ()
--- a/scripts/statistics/distributions/logistic_inv.m
+++ b/scripts/statistics/distributions/logistic_inv.m
@@ -56,11 +56,11 @@
 
 %!shared x
 %! x = [-1 0 0.5 1 2];
-%!assert(logistic_inv (x), [NaN -Inf 0 Inf NaN]);
+%!assert (logistic_inv (x), [NaN -Inf 0 Inf NaN])
 
 %% Test class of input preserved
-%!assert(logistic_inv ([x, NaN]), [NaN -Inf 0 Inf NaN NaN]);
-%!assert(logistic_inv (single([x, NaN])), single([NaN -Inf 0 Inf NaN NaN]));
+%!assert (logistic_inv ([x, NaN]), [NaN -Inf 0 Inf NaN NaN])
+%!assert (logistic_inv (single ([x, NaN])), single ([NaN -Inf 0 Inf NaN NaN]))
 
 %% Test input validation
 %!error logistic_inv ()
--- a/scripts/statistics/distributions/logistic_pdf.m
+++ b/scripts/statistics/distributions/logistic_pdf.m
@@ -44,10 +44,10 @@
 %!shared x,y
 %! x = [-Inf -log(4) 0 log(4) Inf];
 %! y = [0, 0.16, 1/4, 0.16, 0]; 
-%!assert(logistic_pdf ([x, NaN]), [y, NaN], eps);
+%!assert (logistic_pdf ([x, NaN]), [y, NaN], eps)
 
 %% Test class of input preserved
-%!assert(logistic_pdf (single([x, NaN])), single([y, NaN]), eps ("single"));
+%!assert (logistic_pdf (single ([x, NaN])), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error logistic_pdf ()
--- a/scripts/statistics/distributions/logistic_rnd.m
+++ b/scripts/statistics/distributions/logistic_rnd.m
@@ -59,15 +59,15 @@
 endfunction
 
 
-%!assert(size (logistic_rnd (3)), [3, 3]);
-%!assert(size (logistic_rnd ([4 1])), [4, 1]);
-%!assert(size (logistic_rnd (4,1)), [4, 1]);
+%!assert (size (logistic_rnd (3)), [3, 3])
+%!assert (size (logistic_rnd ([4 1])), [4, 1])
+%!assert (size (logistic_rnd (4,1)), [4, 1])
 
 %% Test input validation
 %!error logistic_rnd ()
 %!error logistic_rnd (-1)
-%!error logistic_rnd (ones(2))
+%!error logistic_rnd (ones (2))
 %!error logistic_rnd ([2 -1 2])
-%!error logistic_rnd (1, ones(2))
+%!error logistic_rnd (1, ones (2))
 %!error logistic_rnd (1, -1)
 
--- a/scripts/statistics/distributions/logncdf.m
+++ b/scripts/statistics/distributions/logncdf.m
@@ -74,26 +74,26 @@
 %!shared x,y
 %! x = [-1 0 1 e Inf];
 %! y = [0, 0, 0.5, 1/2+1/2*erf(1/2), 1];
-%!assert(logncdf (x, zeros(1,5), sqrt(2)*ones(1,5)), y);
-%!assert(logncdf (x, 0, sqrt(2)*ones(1,5)), y);
-%!assert(logncdf (x, zeros(1,5), sqrt(2)), y);
-%!assert(logncdf (x, [0 1 NaN 0 1], sqrt(2)), [0 0 NaN y(4:5)]);
-%!assert(logncdf (x, 0, sqrt(2)*[0 NaN Inf 1 1]), [NaN NaN NaN y(4:5)]);
-%!assert(logncdf ([x(1:3) NaN x(5)], 0, sqrt(2)), [y(1:3) NaN y(5)]);
+%!assert (logncdf (x, zeros (1,5), sqrt(2)*ones (1,5)), y, eps)
+%!assert (logncdf (x, 0, sqrt(2)*ones (1,5)), y, eps)
+%!assert (logncdf (x, zeros (1,5), sqrt(2)), y, eps)
+%!assert (logncdf (x, [0 1 NaN 0 1], sqrt(2)), [0 0 NaN y(4:5)], eps)
+%!assert (logncdf (x, 0, sqrt(2)*[0 NaN Inf 1 1]), [NaN NaN NaN y(4:5)], eps)
+%!assert (logncdf ([x(1:3) NaN x(5)], 0, sqrt(2)), [y(1:3) NaN y(5)], eps)
 
 %% Test class of input preserved
-%!assert(logncdf ([x, NaN], 0, sqrt(2)), [y, NaN]);
-%!assert(logncdf (single([x, NaN]), 0, sqrt(2)), single([y, NaN]), eps("single"));
-%!assert(logncdf ([x, NaN], single(0), sqrt(2)), single([y, NaN]), eps("single"));
-%!assert(logncdf ([x, NaN], 0, single(sqrt(2))), single([y, NaN]), eps("single"));
+%!assert (logncdf ([x, NaN], 0, sqrt(2)), [y, NaN], eps)
+%!assert (logncdf (single ([x, NaN]), 0, sqrt(2)), single ([y, NaN]), eps ("single"))
+%!assert (logncdf ([x, NaN], single (0), sqrt(2)), single ([y, NaN]), eps ("single"))
+%!assert (logncdf ([x, NaN], 0, single (sqrt(2))), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error logncdf ()
 %!error logncdf (1,2)
 %!error logncdf (1,2,3,4)
-%!error logncdf (ones(3),ones(2),ones(2))
-%!error logncdf (ones(2),ones(3),ones(2))
-%!error logncdf (ones(2),ones(2),ones(3))
+%!error logncdf (ones (3), ones (2), ones (2))
+%!error logncdf (ones (2), ones (3), ones (2))
+%!error logncdf (ones (2), ones (2), ones (3))
 %!error logncdf (i, 2, 2)
 %!error logncdf (2, i, 2)
 %!error logncdf (2, 2, i)
--- a/scripts/statistics/distributions/logninv.m
+++ b/scripts/statistics/distributions/logninv.m
@@ -73,26 +73,26 @@
 
 %!shared x
 %! x = [-1 0 0.5 1 2];
-%!assert(logninv (x, ones(1,5), ones(1,5)), [NaN 0 e Inf NaN]);
-%!assert(logninv (x, 1, ones(1,5)), [NaN 0 e Inf NaN]);
-%!assert(logninv (x, ones(1,5), 1), [NaN 0 e Inf NaN]);
-%!assert(logninv (x, [1 1 NaN 0 1], 1), [NaN 0 NaN Inf NaN]);
-%!assert(logninv (x, 1, [1 0 NaN Inf 1]), [NaN NaN NaN NaN NaN]);
-%!assert(logninv ([x(1:2) NaN x(4:5)], 1, 2), [NaN 0 NaN Inf NaN]);
+%!assert (logninv (x, ones (1,5), ones (1,5)), [NaN 0 e Inf NaN])
+%!assert (logninv (x, 1, ones (1,5)), [NaN 0 e Inf NaN])
+%!assert (logninv (x, ones (1,5), 1), [NaN 0 e Inf NaN])
+%!assert (logninv (x, [1 1 NaN 0 1], 1), [NaN 0 NaN Inf NaN])
+%!assert (logninv (x, 1, [1 0 NaN Inf 1]), [NaN NaN NaN NaN NaN])
+%!assert (logninv ([x(1:2) NaN x(4:5)], 1, 2), [NaN 0 NaN Inf NaN])
 
 %% Test class of input preserved
-%!assert(logninv ([x, NaN], 1, 1), [NaN 0 e Inf NaN NaN]);
-%!assert(logninv (single([x, NaN]), 1, 1), single([NaN 0 e Inf NaN NaN]));
-%!assert(logninv ([x, NaN], single(1), 1), single([NaN 0 e Inf NaN NaN]));
-%!assert(logninv ([x, NaN], 1, single(1)), single([NaN 0 e Inf NaN NaN]));
+%!assert (logninv ([x, NaN], 1, 1), [NaN 0 e Inf NaN NaN])
+%!assert (logninv (single ([x, NaN]), 1, 1), single ([NaN 0 e Inf NaN NaN]))
+%!assert (logninv ([x, NaN], single (1), 1), single ([NaN 0 e Inf NaN NaN]))
+%!assert (logninv ([x, NaN], 1, single (1)), single ([NaN 0 e Inf NaN NaN]))
 
 %% Test input validation
 %!error logninv ()
 %!error logninv (1,2)
 %!error logninv (1,2,3,4)
-%!error logninv (ones(3),ones(2),ones(2))
-%!error logninv (ones(2),ones(3),ones(2))
-%!error logninv (ones(2),ones(2),ones(3))
+%!error logninv (ones (3), ones (2), ones (2))
+%!error logninv (ones (2), ones (3), ones (2))
+%!error logninv (ones (2), ones (2), ones (3))
 %!error logninv (i, 2, 2)
 %!error logninv (2, i, 2)
 %!error logninv (2, 2, i)
--- a/scripts/statistics/distributions/lognpdf.m
+++ b/scripts/statistics/distributions/lognpdf.m
@@ -71,25 +71,25 @@
 %!shared x,y
 %! x = [-1 0 e Inf];
 %! y = [0, 0, 1/(e*sqrt(2*pi)) * exp(-1/2), 0];
-%!assert(lognpdf (x, zeros(1,4), ones(1,4)), y, eps);
-%!assert(lognpdf (x, 0, ones(1,4)), y, eps);
-%!assert(lognpdf (x, zeros(1,4), 1), y, eps);
-%!assert(lognpdf (x, [0 1 NaN 0], 1), [0 0 NaN y(4)], eps);
-%!assert(lognpdf (x, 0, [0 NaN Inf 1]), [NaN NaN NaN y(4)], eps);
-%!assert(lognpdf ([x, NaN], 0, 1), [y, NaN], eps);
+%!assert (lognpdf (x, zeros (1,4), ones (1,4)), y, eps)
+%!assert (lognpdf (x, 0, ones (1,4)), y, eps)
+%!assert (lognpdf (x, zeros (1,4), 1), y, eps)
+%!assert (lognpdf (x, [0 1 NaN 0], 1), [0 0 NaN y(4)], eps)
+%!assert (lognpdf (x, 0, [0 NaN Inf 1]), [NaN NaN NaN y(4)], eps)
+%!assert (lognpdf ([x, NaN], 0, 1), [y, NaN], eps)
 
 %% Test class of input preserved
-%!assert(lognpdf (single([x, NaN]), 0, 1), single([y, NaN]), eps("single"));
-%!assert(lognpdf ([x, NaN], single(0), 1), single([y, NaN]), eps("single"));
-%!assert(lognpdf ([x, NaN], 0, single(1)), single([y, NaN]), eps("single"));
+%!assert (lognpdf (single ([x, NaN]), 0, 1), single ([y, NaN]), eps ("single"))
+%!assert (lognpdf ([x, NaN], single (0), 1), single ([y, NaN]), eps ("single"))
+%!assert (lognpdf ([x, NaN], 0, single (1)), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error lognpdf ()
 %!error lognpdf (1,2)
 %!error lognpdf (1,2,3,4)
-%!error lognpdf (ones(3),ones(2),ones(2))
-%!error lognpdf (ones(2),ones(3),ones(2))
-%!error lognpdf (ones(2),ones(2),ones(3))
+%!error lognpdf (ones (3), ones (2), ones (2))
+%!error lognpdf (ones (2), ones (3), ones (2))
+%!error lognpdf (ones (2), ones (2), ones (3))
 %!error lognpdf (i, 2, 2)
 %!error lognpdf (2, i, 2)
 %!error lognpdf (2, 2, i)
--- a/scripts/statistics/distributions/lognrnd.m
+++ b/scripts/statistics/distributions/lognrnd.m
@@ -84,12 +84,12 @@
 
   if (isscalar (mu) && isscalar (sigma))
     if ((sigma > 0) && (sigma < Inf))
-      rnd = exp (mu + sigma * randn (sz));
+      rnd = exp (mu + sigma * randn (sz, cls));
     else
       rnd = NaN (sz, cls);
     endif
   else
-    rnd = exp (mu + sigma .* randn (sz));
+    rnd = exp (mu + sigma .* randn (sz, cls));
 
     k = (sigma < 0) | (sigma == Inf);
     rnd(k) = NaN;
@@ -98,35 +98,35 @@
 endfunction
 
 
-%!assert(size (lognrnd (1,2)), [1, 1]);
-%!assert(size (lognrnd (ones(2,1), 2)), [2, 1]);
-%!assert(size (lognrnd (ones(2,2), 2)), [2, 2]);
-%!assert(size (lognrnd (1, 2*ones(2,1))), [2, 1]);
-%!assert(size (lognrnd (1, 2*ones(2,2))), [2, 2]);
-%!assert(size (lognrnd (1, 2, 3)), [3, 3]);
-%!assert(size (lognrnd (1, 2, [4 1])), [4, 1]);
-%!assert(size (lognrnd (1, 2, 4, 1)), [4, 1]);
+%!assert (size (lognrnd (1,2)), [1, 1])
+%!assert (size (lognrnd (ones (2,1), 2)), [2, 1])
+%!assert (size (lognrnd (ones (2,2), 2)), [2, 2])
+%!assert (size (lognrnd (1, 2*ones (2,1))), [2, 1])
+%!assert (size (lognrnd (1, 2*ones (2,2))), [2, 2])
+%!assert (size (lognrnd (1, 2, 3)), [3, 3])
+%!assert (size (lognrnd (1, 2, [4 1])), [4, 1])
+%!assert (size (lognrnd (1, 2, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (lognrnd (1, 2)), "double");
-%!assert(class (lognrnd (single(1), 2)), "single");
-%!assert(class (lognrnd (single([1 1]), 2)), "single");
-%!assert(class (lognrnd (1, single(2))), "single");
-%!assert(class (lognrnd (1, single([2 2]))), "single");
+%!assert (class (lognrnd (1, 2)), "double")
+%!assert (class (lognrnd (single (1), 2)), "single")
+%!assert (class (lognrnd (single ([1 1]), 2)), "single")
+%!assert (class (lognrnd (1, single (2))), "single")
+%!assert (class (lognrnd (1, single ([2 2]))), "single")
 
 %% Test input validation
 %!error lognrnd ()
 %!error lognrnd (1)
-%!error lognrnd (ones(3),ones(2))
-%!error lognrnd (ones(2),ones(3))
+%!error lognrnd (ones (3), ones (2))
+%!error lognrnd (ones (2), ones (3))
 %!error lognrnd (i, 2)
 %!error lognrnd (2, i)
 %!error lognrnd (1,2, -1)
-%!error lognrnd (1,2, ones(2))
+%!error lognrnd (1,2, ones (2))
 %!error lognrnd (1, 2, [2 -1 2])
-%!error lognrnd (1,2, 1, ones(2))
+%!error lognrnd (1,2, 1, ones (2))
 %!error lognrnd (1,2, 1, -1)
-%!error lognrnd (ones(2,2), 2, 3)
-%!error lognrnd (ones(2,2), 2, [3, 2])
-%!error lognrnd (ones(2,2), 2, 2, 3)
+%!error lognrnd (ones (2,2), 2, 3)
+%!error lognrnd (ones (2,2), 2, [3, 2])
+%!error lognrnd (ones (2,2), 2, 2, 3)
 
--- a/scripts/statistics/distributions/nbincdf.m
+++ b/scripts/statistics/distributions/nbincdf.m
@@ -78,27 +78,27 @@
 %!shared x,y
 %! x = [-1 0 1 2 Inf];
 %! y = [0 1/2 3/4 7/8 1];
-%!assert(nbincdf (x, ones(1,5), 0.5*ones(1,5)), y);
-%!assert(nbincdf (x, 1, 0.5*ones(1,5)), y);
-%!assert(nbincdf (x, ones(1,5), 0.5), y);
-%!assert(nbincdf ([x(1:3) 0 x(5)], [0 1 NaN 1.5 Inf], 0.5), [NaN 1/2 NaN nbinpdf(0,1.5,0.5) NaN], eps);
-%!assert(nbincdf (x, 1, 0.5*[-1 NaN 4 1 1]), [NaN NaN NaN y(4:5)]);
-%!assert(nbincdf ([x(1:2) NaN x(4:5)], 1, 0.5), [y(1:2) NaN y(4:5)]);
+%!assert (nbincdf (x, ones (1,5), 0.5*ones (1,5)), y)
+%!assert (nbincdf (x, 1, 0.5*ones (1,5)), y)
+%!assert (nbincdf (x, ones (1,5), 0.5), y)
+%!assert (nbincdf ([x(1:3) 0 x(5)], [0 1 NaN 1.5 Inf], 0.5), [NaN 1/2 NaN nbinpdf(0,1.5,0.5) NaN], eps)
+%!assert (nbincdf (x, 1, 0.5*[-1 NaN 4 1 1]), [NaN NaN NaN y(4:5)])
+%!assert (nbincdf ([x(1:2) NaN x(4:5)], 1, 0.5), [y(1:2) NaN y(4:5)])
 
 %% Test class of input preserved
-%!assert(nbincdf ([x, NaN], 1, 0.5), [y, NaN]);
-%!assert(nbincdf (single([x, NaN]), 1, 0.5), single([y, NaN]));
-%!assert(nbincdf ([x, NaN], single(1), 0.5), single([y, NaN]));
-%!assert(nbincdf ([x, NaN], 1, single(0.5)), single([y, NaN]));
+%!assert (nbincdf ([x, NaN], 1, 0.5), [y, NaN])
+%!assert (nbincdf (single ([x, NaN]), 1, 0.5), single ([y, NaN]))
+%!assert (nbincdf ([x, NaN], single (1), 0.5), single ([y, NaN]))
+%!assert (nbincdf ([x, NaN], 1, single (0.5)), single ([y, NaN]))
 
 %% Test input validation
 %!error nbincdf ()
 %!error nbincdf (1)
 %!error nbincdf (1,2)
 %!error nbincdf (1,2,3,4)
-%!error nbincdf (ones(3),ones(2),ones(2))
-%!error nbincdf (ones(2),ones(3),ones(2))
-%!error nbincdf (ones(2),ones(2),ones(3))
+%!error nbincdf (ones (3), ones (2), ones (2))
+%!error nbincdf (ones (2), ones (3), ones (2))
+%!error nbincdf (ones (2), ones (2), ones (3))
 %!error nbincdf (i, 2, 2)
 %!error nbincdf (2, i, 2)
 %!error nbincdf (2, 2, i)
--- a/scripts/statistics/distributions/nbininv.m
+++ b/scripts/statistics/distributions/nbininv.m
@@ -100,28 +100,28 @@
 
 %!shared x
 %! x = [-1 0 3/4 1 2];
-%!assert(nbininv (x, ones(1,5), 0.5*ones(1,5)), [NaN 0 1 Inf NaN]);
-%!assert(nbininv (x, 1, 0.5*ones(1,5)), [NaN 0 1 Inf NaN]);
-%!assert(nbininv (x, ones(1,5), 0.5), [NaN 0 1 Inf NaN]);
-%!assert(nbininv (x, [1 0 NaN Inf 1], 0.5), [NaN NaN NaN NaN NaN]);
-%!assert(nbininv (x, [1 0 1.5 Inf 1], 0.5), [NaN NaN 2 NaN NaN]);
-%!assert(nbininv (x, 1, 0.5*[1 -Inf NaN Inf 1]), [NaN NaN NaN NaN NaN]);
-%!assert(nbininv ([x(1:2) NaN x(4:5)], 1, 0.5), [NaN 0 NaN Inf NaN]);
+%!assert (nbininv (x, ones (1,5), 0.5*ones (1,5)), [NaN 0 1 Inf NaN])
+%!assert (nbininv (x, 1, 0.5*ones (1,5)), [NaN 0 1 Inf NaN])
+%!assert (nbininv (x, ones (1,5), 0.5), [NaN 0 1 Inf NaN])
+%!assert (nbininv (x, [1 0 NaN Inf 1], 0.5), [NaN NaN NaN NaN NaN])
+%!assert (nbininv (x, [1 0 1.5 Inf 1], 0.5), [NaN NaN 2 NaN NaN])
+%!assert (nbininv (x, 1, 0.5*[1 -Inf NaN Inf 1]), [NaN NaN NaN NaN NaN])
+%!assert (nbininv ([x(1:2) NaN x(4:5)], 1, 0.5), [NaN 0 NaN Inf NaN])
 
 %% Test class of input preserved
-%!assert(nbininv ([x, NaN], 1, 0.5), [NaN 0 1 Inf NaN NaN]);
-%!assert(nbininv (single([x, NaN]), 1, 0.5), single([NaN 0 1 Inf NaN NaN]));
-%!assert(nbininv ([x, NaN], single(1), 0.5), single([NaN 0 1 Inf NaN NaN]));
-%!assert(nbininv ([x, NaN], 1, single(0.5)), single([NaN 0 1 Inf NaN NaN]));
+%!assert (nbininv ([x, NaN], 1, 0.5), [NaN 0 1 Inf NaN NaN])
+%!assert (nbininv (single ([x, NaN]), 1, 0.5), single ([NaN 0 1 Inf NaN NaN]))
+%!assert (nbininv ([x, NaN], single (1), 0.5), single ([NaN 0 1 Inf NaN NaN]))
+%!assert (nbininv ([x, NaN], 1, single (0.5)), single ([NaN 0 1 Inf NaN NaN]))
 
 %% Test input validation
 %!error nbininv ()
 %!error nbininv (1)
 %!error nbininv (1,2)
 %!error nbininv (1,2,3,4)
-%!error nbininv (ones(3),ones(2),ones(2))
-%!error nbininv (ones(2),ones(3),ones(2))
-%!error nbininv (ones(2),ones(2),ones(3))
+%!error nbininv (ones (3), ones (2), ones (2))
+%!error nbininv (ones (2), ones (3), ones (2))
+%!error nbininv (ones (2), ones (2), ones (3))
 %!error nbininv (i, 2, 2)
 %!error nbininv (2, i, 2)
 %!error nbininv (2, 2, i)
--- a/scripts/statistics/distributions/nbinpdf.m
+++ b/scripts/statistics/distributions/nbinpdf.m
@@ -76,26 +76,26 @@
 %!shared x,y
 %! x = [-1 0 1 2 Inf];
 %! y = [0 1/2 1/4 1/8 NaN];
-%!assert(nbinpdf (x, ones(1,5), 0.5*ones(1,5)), y);
-%!assert(nbinpdf (x, 1, 0.5*ones(1,5)), y);
-%!assert(nbinpdf (x, ones(1,5), 0.5), y);
-%!assert(nbinpdf (x, [0 1 NaN 1.5 Inf], 0.5), [NaN 1/2 NaN 1.875*0.5^1.5/4 NaN], eps);
-%!assert(nbinpdf (x, 1, 0.5*[-1 NaN 4 1 1]), [NaN NaN NaN y(4:5)]);
-%!assert(nbinpdf ([x, NaN], 1, 0.5), [y, NaN]);
+%!assert (nbinpdf (x, ones (1,5), 0.5*ones (1,5)), y)
+%!assert (nbinpdf (x, 1, 0.5*ones (1,5)), y)
+%!assert (nbinpdf (x, ones (1,5), 0.5), y)
+%!assert (nbinpdf (x, [0 1 NaN 1.5 Inf], 0.5), [NaN 1/2 NaN 1.875*0.5^1.5/4 NaN], eps)
+%!assert (nbinpdf (x, 1, 0.5*[-1 NaN 4 1 1]), [NaN NaN NaN y(4:5)])
+%!assert (nbinpdf ([x, NaN], 1, 0.5), [y, NaN])
 
 %% Test class of input preserved
-%!assert(nbinpdf (single([x, NaN]), 1, 0.5), single([y, NaN]));
-%!assert(nbinpdf ([x, NaN], single(1), 0.5), single([y, NaN]));
-%!assert(nbinpdf ([x, NaN], 1, single(0.5)), single([y, NaN]));
+%!assert (nbinpdf (single ([x, NaN]), 1, 0.5), single ([y, NaN]))
+%!assert (nbinpdf ([x, NaN], single (1), 0.5), single ([y, NaN]))
+%!assert (nbinpdf ([x, NaN], 1, single (0.5)), single ([y, NaN]))
 
 %% Test input validation
 %!error nbinpdf ()
 %!error nbinpdf (1)
 %!error nbinpdf (1,2)
 %!error nbinpdf (1,2,3,4)
-%!error nbinpdf (ones(3),ones(2),ones(2))
-%!error nbinpdf (ones(2),ones(3),ones(2))
-%!error nbinpdf (ones(2),ones(2),ones(3))
+%!error nbinpdf (ones (3), ones (2), ones (2))
+%!error nbinpdf (ones (2), ones (3), ones (2))
+%!error nbinpdf (ones (2), ones (2), ones (3))
 %!error nbinpdf (i, 2, 2)
 %!error nbinpdf (2, i, 2)
 %!error nbinpdf (2, 2, i)
--- a/scripts/statistics/distributions/nbinrnd.m
+++ b/scripts/statistics/distributions/nbinrnd.m
@@ -84,10 +84,7 @@
 
   if (isscalar (n) && isscalar (p))
     if ((n > 0) && (n < Inf) && (p > 0) && (p <= 1))
-      rnd = randp ((1 - p) ./ p .* randg (n, sz));
-      if (strcmp (cls, "single"))
-        rnd = single (rnd);
-      endif
+      rnd = randp ((1 - p) ./ p .* randg (n, sz, cls), cls);
     elseif ((n > 0) && (n < Inf) && (p == 0))
       rnd = zeros (sz, cls);
     else
@@ -100,41 +97,41 @@
     rnd(k) = 0;
 
     k = (n > 0) & (n < Inf) & (p > 0) & (p <= 1);
-    rnd(k) = randp ((1 - p(k)) ./ p(k) .* randg (n(k)));
+    rnd(k) = randp ((1 - p(k)) ./ p(k) .* randg (n(k), cls));
   endif
 
 endfunction
 
 
-%!assert(size (nbinrnd (2, 1/2)), [1, 1]);
-%!assert(size (nbinrnd (2*ones(2,1), 1/2)), [2, 1]);
-%!assert(size (nbinrnd (2*ones(2,2), 1/2)), [2, 2]);
-%!assert(size (nbinrnd (2, 1/2*ones(2,1))), [2, 1]);
-%!assert(size (nbinrnd (2, 1/2*ones(2,2))), [2, 2]);
-%!assert(size (nbinrnd (2, 1/2, 3)), [3, 3]);
-%!assert(size (nbinrnd (2, 1/2, [4 1])), [4, 1]);
-%!assert(size (nbinrnd (2, 1/2, 4, 1)), [4, 1]);
+%!assert (size (nbinrnd (2, 1/2)), [1, 1])
+%!assert (size (nbinrnd (2*ones (2,1), 1/2)), [2, 1])
+%!assert (size (nbinrnd (2*ones (2,2), 1/2)), [2, 2])
+%!assert (size (nbinrnd (2, 1/2*ones (2,1))), [2, 1])
+%!assert (size (nbinrnd (2, 1/2*ones (2,2))), [2, 2])
+%!assert (size (nbinrnd (2, 1/2, 3)), [3, 3])
+%!assert (size (nbinrnd (2, 1/2, [4 1])), [4, 1])
+%!assert (size (nbinrnd (2, 1/2, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (nbinrnd (2, 1/2)), "double");
-%!assert(class (nbinrnd (single(2), 1/2)), "single");
-%!assert(class (nbinrnd (single([2 2]), 1/2)), "single");
-%!assert(class (nbinrnd (2, single(1/2))), "single");
-%!assert(class (nbinrnd (2, single([1/2 1/2]))), "single");
+%!assert (class (nbinrnd (2, 1/2)), "double")
+%!assert (class (nbinrnd (single (2), 1/2)), "single")
+%!assert (class (nbinrnd (single ([2 2]), 1/2)), "single")
+%!assert (class (nbinrnd (2, single (1/2))), "single")
+%!assert (class (nbinrnd (2, single ([1/2 1/2]))), "single")
 
 %% Test input validation
 %!error nbinrnd ()
 %!error nbinrnd (1)
-%!error nbinrnd (ones(3),ones(2))
-%!error nbinrnd (ones(2),ones(3))
+%!error nbinrnd (ones (3), ones (2))
+%!error nbinrnd (ones (2), ones (3))
 %!error nbinrnd (i, 2)
 %!error nbinrnd (2, i)
 %!error nbinrnd (1,2, -1)
-%!error nbinrnd (1,2, ones(2))
+%!error nbinrnd (1,2, ones (2))
 %!error nbinrnd (1, 2, [2 -1 2])
-%!error nbinrnd (1,2, 1, ones(2))
+%!error nbinrnd (1,2, 1, ones (2))
 %!error nbinrnd (1,2, 1, -1)
-%!error nbinrnd (ones(2,2), 2, 3)
-%!error nbinrnd (ones(2,2), 2, [3, 2])
-%!error nbinrnd (ones(2,2), 2, 2, 3)
+%!error nbinrnd (ones (2,2), 2, 3)
+%!error nbinrnd (ones (2,2), 2, [3, 2])
+%!error nbinrnd (ones (2,2), 2, 2, 3)
 
--- a/scripts/statistics/distributions/normcdf.m
+++ b/scripts/statistics/distributions/normcdf.m
@@ -73,26 +73,26 @@
 %!shared x,y
 %! x = [-Inf 1 2 Inf];
 %! y = [0, 0.5, 1/2*(1+erf(1/sqrt(2))), 1];
-%!assert(normcdf (x, ones(1,4), ones(1,4)), y);
-%!assert(normcdf (x, 1, ones(1,4)), y);
-%!assert(normcdf (x, ones(1,4), 1), y);
-%!assert(normcdf (x, [0 -Inf NaN Inf], 1), [y(1) NaN NaN NaN]);
-%!assert(normcdf (x, 1, [Inf NaN -1 0]), [NaN NaN NaN NaN]);
-%!assert(normcdf ([x(1:2) NaN x(4)], 1, 1), [y(1:2) NaN y(4)]);
+%!assert (normcdf (x, ones (1,4), ones (1,4)), y)
+%!assert (normcdf (x, 1, ones (1,4)), y)
+%!assert (normcdf (x, ones (1,4), 1), y)
+%!assert (normcdf (x, [0 -Inf NaN Inf], 1), [y(1) NaN NaN NaN])
+%!assert (normcdf (x, 1, [Inf NaN -1 0]), [NaN NaN NaN NaN])
+%!assert (normcdf ([x(1:2) NaN x(4)], 1, 1), [y(1:2) NaN y(4)])
 
 %% Test class of input preserved
-%!assert(normcdf ([x, NaN], 1, 1), [y, NaN]);
-%!assert(normcdf (single([x, NaN]), 1, 1), single([y, NaN]), eps("single"));
-%!assert(normcdf ([x, NaN], single(1), 1), single([y, NaN]), eps("single"));
-%!assert(normcdf ([x, NaN], 1, single(1)), single([y, NaN]), eps("single"));
+%!assert (normcdf ([x, NaN], 1, 1), [y, NaN])
+%!assert (normcdf (single ([x, NaN]), 1, 1), single ([y, NaN]), eps ("single"))
+%!assert (normcdf ([x, NaN], single (1), 1), single ([y, NaN]), eps ("single"))
+%!assert (normcdf ([x, NaN], 1, single (1)), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error normcdf ()
 %!error normcdf (1,2)
 %!error normcdf (1,2,3,4)
-%!error normcdf (ones(3),ones(2),ones(2))
-%!error normcdf (ones(2),ones(3),ones(2))
-%!error normcdf (ones(2),ones(2),ones(3))
+%!error normcdf (ones (3), ones (2), ones (2))
+%!error normcdf (ones (2), ones (3), ones (2))
+%!error normcdf (ones (2), ones (2), ones (3))
 %!error normcdf (i, 2, 2)
 %!error normcdf (2, i, 2)
 %!error normcdf (2, 2, i)
--- a/scripts/statistics/distributions/norminv.m
+++ b/scripts/statistics/distributions/norminv.m
@@ -67,26 +67,26 @@
 
 %!shared x
 %! x = [-1 0 0.5 1 2];
-%!assert(norminv (x, ones(1,5), ones(1,5)), [NaN -Inf 1 Inf NaN]);
-%!assert(norminv (x, 1, ones(1,5)), [NaN -Inf 1 Inf NaN]);
-%!assert(norminv (x, ones(1,5), 1), [NaN -Inf 1 Inf NaN]);
-%!assert(norminv (x, [1 -Inf NaN Inf 1], 1), [NaN NaN NaN NaN NaN]);
-%!assert(norminv (x, 1, [1 0 NaN Inf 1]), [NaN NaN NaN NaN NaN]);
-%!assert(norminv ([x(1:2) NaN x(4:5)], 1, 1), [NaN -Inf NaN Inf NaN]);
+%!assert (norminv (x, ones (1,5), ones (1,5)), [NaN -Inf 1 Inf NaN])
+%!assert (norminv (x, 1, ones (1,5)), [NaN -Inf 1 Inf NaN])
+%!assert (norminv (x, ones (1,5), 1), [NaN -Inf 1 Inf NaN])
+%!assert (norminv (x, [1 -Inf NaN Inf 1], 1), [NaN NaN NaN NaN NaN])
+%!assert (norminv (x, 1, [1 0 NaN Inf 1]), [NaN NaN NaN NaN NaN])
+%!assert (norminv ([x(1:2) NaN x(4:5)], 1, 1), [NaN -Inf NaN Inf NaN])
 
 %% Test class of input preserved
-%!assert(norminv ([x, NaN], 1, 1), [NaN -Inf 1 Inf NaN NaN]);
-%!assert(norminv (single([x, NaN]), 1, 1), single([NaN -Inf 1 Inf NaN NaN]));
-%!assert(norminv ([x, NaN], single(1), 1), single([NaN -Inf 1 Inf NaN NaN]));
-%!assert(norminv ([x, NaN], 1, single(1)), single([NaN -Inf 1 Inf NaN NaN]));
+%!assert (norminv ([x, NaN], 1, 1), [NaN -Inf 1 Inf NaN NaN])
+%!assert (norminv (single ([x, NaN]), 1, 1), single ([NaN -Inf 1 Inf NaN NaN]))
+%!assert (norminv ([x, NaN], single (1), 1), single ([NaN -Inf 1 Inf NaN NaN]))
+%!assert (norminv ([x, NaN], 1, single (1)), single ([NaN -Inf 1 Inf NaN NaN]))
 
 %% Test input validation
 %!error norminv ()
 %!error norminv (1,2)
 %!error norminv (1,2,3,4)
-%!error norminv (ones(3),ones(2),ones(2))
-%!error norminv (ones(2),ones(3),ones(2))
-%!error norminv (ones(2),ones(2),ones(3))
+%!error norminv (ones (3), ones (2), ones (2))
+%!error norminv (ones (2), ones (3), ones (2))
+%!error norminv (ones (2), ones (2), ones (3))
 %!error norminv (i, 2, 2)
 %!error norminv (2, i, 2)
 %!error norminv (2, 2, i)
--- a/scripts/statistics/distributions/normpdf.m
+++ b/scripts/statistics/distributions/normpdf.m
@@ -73,25 +73,25 @@
 %!shared x,y
 %! x = [-Inf 1 2 Inf];
 %! y = 1/sqrt(2*pi)*exp (-(x-1).^2/2);
-%!assert(normpdf (x, ones(1,4), ones(1,4)), y);
-%!assert(normpdf (x, 1, ones(1,4)), y);
-%!assert(normpdf (x, ones(1,4), 1), y);
-%!assert(normpdf (x, [0 -Inf NaN Inf], 1), [y(1) NaN NaN NaN]);
-%!assert(normpdf (x, 1, [Inf NaN -1 0]), [NaN NaN NaN NaN]);
-%!assert(normpdf ([x, NaN], 1, 1), [y, NaN]);
+%!assert (normpdf (x, ones (1,4), ones (1,4)), y)
+%!assert (normpdf (x, 1, ones (1,4)), y)
+%!assert (normpdf (x, ones (1,4), 1), y)
+%!assert (normpdf (x, [0 -Inf NaN Inf], 1), [y(1) NaN NaN NaN])
+%!assert (normpdf (x, 1, [Inf NaN -1 0]), [NaN NaN NaN NaN])
+%!assert (normpdf ([x, NaN], 1, 1), [y, NaN])
 
 %% Test class of input preserved
-%!assert(normpdf (single([x, NaN]), 1, 1), single([y, NaN]), eps("single"));
-%!assert(normpdf ([x, NaN], single(1), 1), single([y, NaN]), eps("single"));
-%!assert(normpdf ([x, NaN], 1, single(1)), single([y, NaN]), eps("single"));
+%!assert (normpdf (single ([x, NaN]), 1, 1), single ([y, NaN]), eps ("single"))
+%!assert (normpdf ([x, NaN], single (1), 1), single ([y, NaN]), eps ("single"))
+%!assert (normpdf ([x, NaN], 1, single (1)), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error normpdf ()
 %!error normpdf (1,2)
 %!error normpdf (1,2,3,4)
-%!error normpdf (ones(3),ones(2),ones(2))
-%!error normpdf (ones(2),ones(3),ones(2))
-%!error normpdf (ones(2),ones(2),ones(3))
+%!error normpdf (ones (3), ones (2), ones (2))
+%!error normpdf (ones (2), ones (3), ones (2))
+%!error normpdf (ones (2), ones (2), ones (3))
 %!error normpdf (i, 2, 2)
 %!error normpdf (2, i, 2)
 %!error normpdf (2, 2, i)
--- a/scripts/statistics/distributions/normrnd.m
+++ b/scripts/statistics/distributions/normrnd.m
@@ -84,12 +84,12 @@
 
   if (isscalar (mu) && isscalar (sigma))
     if (!isnan (mu) && !isinf (mu) && (sigma > 0) && (sigma < Inf))
-      rnd =  mu + sigma * randn (sz);
+      rnd =  mu + sigma * randn (sz, cls);
     else
       rnd = NaN (sz, cls);
     endif
   else
-    rnd = mu + sigma .* randn (sz);
+    rnd = mu + sigma .* randn (sz, cls);
     k = isnan (mu) | isinf (mu) | !(sigma > 0) | !(sigma < Inf);
     rnd(k) = NaN;
   endif
@@ -97,35 +97,35 @@
 endfunction
 
 
-%!assert(size (normrnd (1,2)), [1, 1]);
-%!assert(size (normrnd (ones(2,1), 2)), [2, 1]);
-%!assert(size (normrnd (ones(2,2), 2)), [2, 2]);
-%!assert(size (normrnd (1, 2*ones(2,1))), [2, 1]);
-%!assert(size (normrnd (1, 2*ones(2,2))), [2, 2]);
-%!assert(size (normrnd (1, 2, 3)), [3, 3]);
-%!assert(size (normrnd (1, 2, [4 1])), [4, 1]);
-%!assert(size (normrnd (1, 2, 4, 1)), [4, 1]);
+%!assert (size (normrnd (1,2)), [1, 1])
+%!assert (size (normrnd (ones (2,1), 2)), [2, 1])
+%!assert (size (normrnd (ones (2,2), 2)), [2, 2])
+%!assert (size (normrnd (1, 2*ones (2,1))), [2, 1])
+%!assert (size (normrnd (1, 2*ones (2,2))), [2, 2])
+%!assert (size (normrnd (1, 2, 3)), [3, 3])
+%!assert (size (normrnd (1, 2, [4 1])), [4, 1])
+%!assert (size (normrnd (1, 2, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (normrnd (1, 2)), "double");
-%!assert(class (normrnd (single(1), 2)), "single");
-%!assert(class (normrnd (single([1 1]), 2)), "single");
-%!assert(class (normrnd (1, single(2))), "single");
-%!assert(class (normrnd (1, single([2 2]))), "single");
+%!assert (class (normrnd (1, 2)), "double")
+%!assert (class (normrnd (single (1), 2)), "single")
+%!assert (class (normrnd (single ([1 1]), 2)), "single")
+%!assert (class (normrnd (1, single (2))), "single")
+%!assert (class (normrnd (1, single ([2 2]))), "single")
 
 %% Test input validation
 %!error normrnd ()
 %!error normrnd (1)
-%!error normrnd (ones(3),ones(2))
-%!error normrnd (ones(2),ones(3))
+%!error normrnd (ones (3), ones (2))
+%!error normrnd (ones (2), ones (3))
 %!error normrnd (i, 2)
 %!error normrnd (2, i)
 %!error normrnd (1,2, -1)
-%!error normrnd (1,2, ones(2))
+%!error normrnd (1,2, ones (2))
 %!error normrnd (1, 2, [2 -1 2])
-%!error normrnd (1,2, 1, ones(2))
+%!error normrnd (1,2, 1, ones (2))
 %!error normrnd (1,2, 1, -1)
-%!error normrnd (ones(2,2), 2, 3)
-%!error normrnd (ones(2,2), 2, [3, 2])
-%!error normrnd (ones(2,2), 2, 2, 3)
+%!error normrnd (ones (2,2), 2, 3)
+%!error normrnd (ones (2,2), 2, [3, 2])
+%!error normrnd (ones (2,2), 2, 2, 3)
 
--- a/scripts/statistics/distributions/poisscdf.m
+++ b/scripts/statistics/distributions/poisscdf.m
@@ -68,23 +68,23 @@
 
 %!shared x,y
 %! x = [-1 0 1 2 Inf];
-%! y = [0, gammainc(1, (x(2:4) +1), 'upper'), 1];
-%!assert(poisscdf (x, ones(1,5)), y);
-%!assert(poisscdf (x, 1), y);
-%!assert(poisscdf (x, [1 0 NaN 1 1]), [y(1) NaN NaN y(4:5)]);
-%!assert(poisscdf ([x(1:2) NaN Inf x(5)], 1), [y(1:2) NaN 1 y(5)]);
+%! y = [0, gammainc(1, (x(2:4) +1), "upper"), 1];
+%!assert (poisscdf (x, ones (1,5)), y)
+%!assert (poisscdf (x, 1), y)
+%!assert (poisscdf (x, [1 0 NaN 1 1]), [y(1) NaN NaN y(4:5)])
+%!assert (poisscdf ([x(1:2) NaN Inf x(5)], 1), [y(1:2) NaN 1 y(5)])
 
 %% Test class of input preserved
-%!assert(poisscdf ([x, NaN], 1), [y, NaN]);
-%!assert(poisscdf (single([x, NaN]), 1), single([y, NaN]), eps("single"));
-%!assert(poisscdf ([x, NaN], single(1)), single([y, NaN]), eps("single"));
+%!assert (poisscdf ([x, NaN], 1), [y, NaN])
+%!assert (poisscdf (single ([x, NaN]), 1), single ([y, NaN]), eps ("single"))
+%!assert (poisscdf ([x, NaN], single (1)), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error poisscdf ()
 %!error poisscdf (1)
 %!error poisscdf (1,2,3)
-%!error poisscdf (ones(3),ones(2))
-%!error poisscdf (ones(2),ones(3))
+%!error poisscdf (ones (3), ones (2))
+%!error poisscdf (ones (2), ones (3))
 %!error poisscdf (i, 2)
 %!error poisscdf (2, i)
 
--- a/scripts/statistics/distributions/poissinv.m
+++ b/scripts/statistics/distributions/poissinv.m
@@ -82,22 +82,22 @@
 
 %!shared x
 %! x = [-1 0 0.5 1 2];
-%!assert(poissinv (x, ones(1,5)), [NaN 0 1 Inf NaN]);
-%!assert(poissinv (x, 1), [NaN 0 1 Inf NaN]);
-%!assert(poissinv (x, [1 0 NaN 1 1]), [NaN NaN NaN Inf NaN]);
-%!assert(poissinv ([x(1:2) NaN x(4:5)], 1), [NaN 0 NaN Inf NaN]);
+%!assert (poissinv (x, ones (1,5)), [NaN 0 1 Inf NaN])
+%!assert (poissinv (x, 1), [NaN 0 1 Inf NaN])
+%!assert (poissinv (x, [1 0 NaN 1 1]), [NaN NaN NaN Inf NaN])
+%!assert (poissinv ([x(1:2) NaN x(4:5)], 1), [NaN 0 NaN Inf NaN])
 
 %% Test class of input preserved
-%!assert(poissinv ([x, NaN], 1), [NaN 0 1 Inf NaN NaN]);
-%!assert(poissinv (single([x, NaN]), 1), single([NaN 0 1 Inf NaN NaN]));
-%!assert(poissinv ([x, NaN], single(1)), single([NaN 0 1 Inf NaN NaN]));
+%!assert (poissinv ([x, NaN], 1), [NaN 0 1 Inf NaN NaN])
+%!assert (poissinv (single ([x, NaN]), 1), single ([NaN 0 1 Inf NaN NaN]))
+%!assert (poissinv ([x, NaN], single (1)), single ([NaN 0 1 Inf NaN NaN]))
 
 %% Test input validation
 %!error poissinv ()
 %!error poissinv (1)
 %!error poissinv (1,2,3)
-%!error poissinv (ones(3),ones(2))
-%!error poissinv (ones(2),ones(3))
+%!error poissinv (ones (3), ones (2))
+%!error poissinv (ones (2), ones (3))
 %!error poissinv (i, 2)
 %!error poissinv (2, i)
 
--- a/scripts/statistics/distributions/poisspdf.m
+++ b/scripts/statistics/distributions/poisspdf.m
@@ -65,21 +65,21 @@
 %!shared x,y
 %! x = [-1 0 1 2 Inf];
 %! y = [0, exp(-1)*[1 1 0.5], 0];
-%!assert(poisspdf (x, ones(1,5)), y, eps);
-%!assert(poisspdf (x, 1), y, eps);
-%!assert(poisspdf (x, [1 0 NaN 1 1]), [y(1) NaN NaN y(4:5)], eps);
-%!assert(poisspdf ([x, NaN], 1), [y, NaN], eps);
+%!assert (poisspdf (x, ones (1,5)), y, eps)
+%!assert (poisspdf (x, 1), y, eps)
+%!assert (poisspdf (x, [1 0 NaN 1 1]), [y(1) NaN NaN y(4:5)], eps)
+%!assert (poisspdf ([x, NaN], 1), [y, NaN], eps)
 
 %% Test class of input preserved
-%!assert(poisspdf (single([x, NaN]), 1), single([y, NaN]), eps("single"));
-%!assert(poisspdf ([x, NaN], single(1)), single([y, NaN]), eps("single"));
+%!assert (poisspdf (single ([x, NaN]), 1), single ([y, NaN]), eps ("single"))
+%!assert (poisspdf ([x, NaN], single (1)), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error poisspdf ()
 %!error poisspdf (1)
 %!error poisspdf (1,2,3)
-%!error poisspdf (ones(3),ones(2))
-%!error poisspdf (ones(2),ones(3))
+%!error poisspdf (ones (3), ones (2))
+%!error poisspdf (ones (2), ones (3))
 %!error poisspdf (i, 2)
 %!error poisspdf (2, i)
 
--- a/scripts/statistics/distributions/poissrnd.m
+++ b/scripts/statistics/distributions/poissrnd.m
@@ -77,10 +77,7 @@
 
   if (isscalar (lambda))
     if (lambda >= 0 && lambda < Inf)
-      rnd = randp (lambda, sz);
-      if (strcmp (cls, "single"))
-        rnd = single (rnd);
-      endif
+      rnd = randp (lambda, sz, cls);
     else
       rnd = NaN (sz, cls);
     endif
@@ -88,34 +85,35 @@
     rnd = NaN (sz, cls);
 
     k = (lambda >= 0) & (lambda < Inf);
-    rnd(k) = randp (lambda(k));
+    rnd(k) = randp (lambda(k), cls);
   endif
 
 endfunction
 
-%!assert(size (poissrnd (2)), [1, 1]);
-%!assert(size (poissrnd (ones(2,1))), [2, 1]);
-%!assert(size (poissrnd (ones(2,2))), [2, 2]);
-%!assert(size (poissrnd (1, 3)), [3, 3]);
-%!assert(size (poissrnd (1, [4 1])), [4, 1]);
-%!assert(size (poissrnd (1, 4, 1)), [4, 1]);
+
+%!assert (size (poissrnd (2)), [1, 1])
+%!assert (size (poissrnd (ones (2,1))), [2, 1])
+%!assert (size (poissrnd (ones (2,2))), [2, 2])
+%!assert (size (poissrnd (1, 3)), [3, 3])
+%!assert (size (poissrnd (1, [4 1])), [4, 1])
+%!assert (size (poissrnd (1, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (poissrnd (2)), "double");
-%!assert(class (poissrnd (single(2))), "single");
-%!assert(class (poissrnd (single([2 2]))), "single");
+%!assert (class (poissrnd (2)), "double")
+%!assert (class (poissrnd (single (2))), "single")
+%!assert (class (poissrnd (single ([2 2]))), "single")
 
 %% Test input validation
 %!error poissrnd ()
 %!error poissrnd (1, -1)
-%!error poissrnd (1, ones(2))
-%!error poissrnd (1, 2, ones(2))
+%!error poissrnd (1, ones (2))
+%!error poissrnd (1, 2, ones (2))
 %!error poissrnd (i)
 %!error poissrnd (1, 2, -1)
 %!error poissrnd (1, [2 -1 2])
-%!error poissrnd (ones(2,2), 3)
-%!error poissrnd (ones(2,2), [3, 2])
-%!error poissrnd (ones(2,2), 2, 3)
+%!error poissrnd (ones (2,2), 3)
+%!error poissrnd (ones (2,2), [3, 2])
+%!error poissrnd (ones (2,2), 2, 3)
 
 %!assert (poissrnd (0, 1, 1), 0)
 %!assert (poissrnd ([0, 0, 0], [1, 3]), [0 0 0])
--- a/scripts/statistics/distributions/stdnormal_cdf.m
+++ b/scripts/statistics/distributions/stdnormal_cdf.m
@@ -45,10 +45,10 @@
 %!shared x,y
 %! x = [-Inf 0 1 Inf];
 %! y = [0, 0.5, 1/2*(1+erf(1/sqrt(2))), 1];
-%!assert(stdnormal_cdf ([x, NaN]), [y, NaN]);
+%!assert (stdnormal_cdf ([x, NaN]), [y, NaN])
 
 %% Test class of input preserved
-%!assert(stdnormal_cdf (single([x, NaN])), single([y, NaN]), eps("single"));
+%!assert (stdnormal_cdf (single ([x, NaN])), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error stdnormal_cdf ()
--- a/scripts/statistics/distributions/stdnormal_inv.m
+++ b/scripts/statistics/distributions/stdnormal_inv.m
@@ -37,18 +37,18 @@
     error ("stdnormal_inv: X must not be complex");
   endif
 
-  inv = sqrt (2) * erfinv (2 * x - 1);
+  inv = - sqrt (2) * erfcinv (2 * x);
 
 endfunction
 
 
 %!shared x
 %! x = [-1 0 0.5 1 2];
-%!assert(stdnormal_inv (x), [NaN -Inf 0 Inf NaN]);
+%!assert (stdnormal_inv (x), [NaN -Inf 0 Inf NaN])
 
 %% Test class of input preserved
-%!assert(stdnormal_inv ([x, NaN]), [NaN -Inf 0 Inf NaN NaN]);
-%!assert(stdnormal_inv (single([x, NaN])), single([NaN -Inf 0 Inf NaN NaN]));
+%!assert (stdnormal_inv ([x, NaN]), [NaN -Inf 0 Inf NaN NaN])
+%!assert (stdnormal_inv (single ([x, NaN])), single ([NaN -Inf 0 Inf NaN NaN]))
 
 %% Test input validation
 %!error stdnormal_inv ()
--- a/scripts/statistics/distributions/stdnormal_pdf.m
+++ b/scripts/statistics/distributions/stdnormal_pdf.m
@@ -45,10 +45,10 @@
 %!shared x,y
 %! x = [-Inf 0 1 Inf];
 %! y = 1/sqrt(2*pi)*exp (-x.^2/2);
-%!assert(stdnormal_pdf ([x, NaN]), [y, NaN], eps);
+%!assert (stdnormal_pdf ([x, NaN]), [y, NaN], eps)
 
 %% Test class of input preserved
-%!assert(stdnormal_pdf (single([x, NaN])), single([y, NaN]), eps("single"));
+%!assert (stdnormal_pdf (single ([x, NaN])), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error stdnormal_pdf ()
--- a/scripts/statistics/distributions/stdnormal_rnd.m
+++ b/scripts/statistics/distributions/stdnormal_rnd.m
@@ -60,15 +60,15 @@
 endfunction
 
 
-%!assert(size (stdnormal_rnd (3)), [3, 3]);
-%!assert(size (stdnormal_rnd ([4 1])), [4, 1]);
-%!assert(size (stdnormal_rnd (4,1)), [4, 1]);
+%!assert (size (stdnormal_rnd (3)), [3, 3])
+%!assert (size (stdnormal_rnd ([4 1])), [4, 1])
+%!assert (size (stdnormal_rnd (4,1)), [4, 1])
 
 %% Test input validation
 %!error stdnormal_rnd ()
 %!error stdnormal_rnd (-1)
-%!error stdnormal_rnd (ones(2))
+%!error stdnormal_rnd (ones (2))
 %!error stdnormal_rnd ([2 -1 2])
-%!error stdnormal_rnd (1, ones(2))
+%!error stdnormal_rnd (1, ones (2))
 %!error stdnormal_rnd (1, -1)
 
--- a/scripts/statistics/distributions/tcdf.m
+++ b/scripts/statistics/distributions/tcdf.m
@@ -73,22 +73,22 @@
 %!shared x,y
 %! x = [-Inf 0 1 Inf];
 %! y = [0 1/2 3/4 1];
-%!assert(tcdf (x, ones(1,4)), y, eps);
-%!assert(tcdf (x, 1), y, eps);
-%!assert(tcdf (x, [0 1 NaN 1]), [NaN 1/2 NaN 1], eps);
-%!assert(tcdf ([x(1:2) NaN x(4)], 1), [y(1:2) NaN y(4)], eps);
+%!assert (tcdf (x, ones (1,4)), y, eps)
+%!assert (tcdf (x, 1), y, eps)
+%!assert (tcdf (x, [0 1 NaN 1]), [NaN 1/2 NaN 1], eps)
+%!assert (tcdf ([x(1:2) NaN x(4)], 1), [y(1:2) NaN y(4)], eps)
 
 %% Test class of input preserved
-%!assert(tcdf ([x, NaN], 1), [y, NaN], eps);
-%!assert(tcdf (single([x, NaN]), 1), single([y, NaN]), eps("single"));
-%!assert(tcdf ([x, NaN], single(1)), single([y, NaN]), eps("single"));
+%!assert (tcdf ([x, NaN], 1), [y, NaN], eps)
+%!assert (tcdf (single ([x, NaN]), 1), single ([y, NaN]), eps ("single"))
+%!assert (tcdf ([x, NaN], single (1)), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error tcdf ()
 %!error tcdf (1)
 %!error tcdf (1,2,3)
-%!error tcdf (ones(3),ones(2))
-%!error tcdf (ones(2),ones(3))
+%!error tcdf (ones (3), ones (2))
+%!error tcdf (ones (2), ones (3))
 %!error tcdf (i, 2)
 %!error tcdf (2, i)
 
--- a/scripts/statistics/distributions/tinv.m
+++ b/scripts/statistics/distributions/tinv.m
@@ -87,22 +87,22 @@
 
 %!shared x
 %! x = [-1 0 0.5 1 2];
-%!assert(tinv (x, ones(1,5)), [NaN -Inf 0 Inf NaN]);
-%!assert(tinv (x, 1), [NaN -Inf 0 Inf NaN], eps);
-%!assert(tinv (x, [1 0 NaN 1 1]), [NaN NaN NaN Inf NaN], eps);
-%!assert(tinv ([x(1:2) NaN x(4:5)], 1), [NaN -Inf NaN Inf NaN]);
+%!assert (tinv (x, ones (1,5)), [NaN -Inf 0 Inf NaN])
+%!assert (tinv (x, 1), [NaN -Inf 0 Inf NaN], eps)
+%!assert (tinv (x, [1 0 NaN 1 1]), [NaN NaN NaN Inf NaN], eps)
+%!assert (tinv ([x(1:2) NaN x(4:5)], 1), [NaN -Inf NaN Inf NaN])
 
 %% Test class of input preserved
-%!assert(tinv ([x, NaN], 1), [NaN -Inf 0 Inf NaN NaN], eps);
-%!assert(tinv (single([x, NaN]), 1), single([NaN -Inf 0 Inf NaN NaN]), eps("single"));
-%!assert(tinv ([x, NaN], single(1)), single([NaN -Inf 0 Inf NaN NaN]), eps("single"));
+%!assert (tinv ([x, NaN], 1), [NaN -Inf 0 Inf NaN NaN], eps)
+%!assert (tinv (single ([x, NaN]), 1), single ([NaN -Inf 0 Inf NaN NaN]), eps ("single"))
+%!assert (tinv ([x, NaN], single (1)), single ([NaN -Inf 0 Inf NaN NaN]), eps ("single"))
 
 %% Test input validation
 %!error tinv ()
 %!error tinv (1)
 %!error tinv (1,2,3)
-%!error tinv (ones(3),ones(2))
-%!error tinv (ones(2),ones(3))
+%!error tinv (ones (3), ones (2))
+%!error tinv (ones (2), ones (3))
 %!error tinv (i, 2)
 %!error tinv (2, i)
 
--- a/scripts/statistics/distributions/tpdf.m
+++ b/scripts/statistics/distributions/tpdf.m
@@ -68,26 +68,26 @@
 %!test
 %! x = rand (10,1);
 %! y = 1./(pi * (1 + x.^2));
-%! assert(tpdf (x, 1), y, 5*eps);
+%! assert (tpdf (x, 1), y, 5*eps);
 
 %!shared x,y
 %! x = [-Inf 0 0.5 1 Inf];
 %! y = 1./(pi * (1 + x.^2));
-%!assert(tpdf (x, ones(1,5)), y, eps);
-%!assert(tpdf (x, 1), y, eps);
-%!assert(tpdf (x, [0 NaN 1 1 1]), [NaN NaN y(3:5)], eps);
+%!assert (tpdf (x, ones (1,5)), y, eps)
+%!assert (tpdf (x, 1), y, eps)
+%!assert (tpdf (x, [0 NaN 1 1 1]), [NaN NaN y(3:5)], eps)
 
 %% Test class of input preserved
-%!assert(tpdf ([x, NaN], 1), [y, NaN], eps);
-%!assert(tpdf (single([x, NaN]), 1), single([y, NaN]), eps("single"));
-%!assert(tpdf ([x, NaN], single(1)), single([y, NaN]), eps("single"));
+%!assert (tpdf ([x, NaN], 1), [y, NaN], eps)
+%!assert (tpdf (single ([x, NaN]), 1), single ([y, NaN]), eps ("single"))
+%!assert (tpdf ([x, NaN], single (1)), single ([y, NaN]), eps ("single"))
 
 %% Test input validation
 %!error tpdf ()
 %!error tpdf (1)
 %!error tpdf (1,2,3)
-%!error tpdf (ones(3),ones(2))
-%!error tpdf (ones(2),ones(3))
+%!error tpdf (ones (3), ones (2))
+%!error tpdf (ones (2), ones (3))
 %!error tpdf (i, 2)
 %!error tpdf (2, i)
 
--- a/scripts/statistics/distributions/trnd.m
+++ b/scripts/statistics/distributions/trnd.m
@@ -77,7 +77,7 @@
 
   if (isscalar (n))
     if ((n > 0) && (n < Inf))
-      rnd = randn (sz) ./ sqrt (2*randg (n/2, sz) / n);
+      rnd = randn (sz, cls) ./ sqrt (2*randg (n/2, sz, cls) / n);
     else
       rnd = NaN (sz, cls);
     endif
@@ -85,33 +85,33 @@
     rnd = NaN (sz, cls);
 
     k = (n > 0) & (n < Inf);
-    rnd(k) = randn (sum (k(:)), 1) ./ sqrt (2*randg (n(k)/2) ./ n(k))(:);
+    rnd(k) = randn (sum (k(:)), 1, cls) ./ sqrt (2*randg (n(k)/2, cls) ./ n(k))(:);
   endif
 
 endfunction
 
 
-%!assert(size (trnd (2)), [1, 1]);
-%!assert(size (trnd (ones(2,1))), [2, 1]);
-%!assert(size (trnd (ones(2,2))), [2, 2]);
-%!assert(size (trnd (1, 3)), [3, 3]);
-%!assert(size (trnd (1, [4 1])), [4, 1]);
-%!assert(size (trnd (1, 4, 1)), [4, 1]);
+%!assert (size (trnd (2)), [1, 1])
+%!assert (size (trnd (ones (2,1))), [2, 1])
+%!assert (size (trnd (ones (2,2))), [2, 2])
+%!assert (size (trnd (1, 3)), [3, 3])
+%!assert (size (trnd (1, [4 1])), [4, 1])
+%!assert (size (trnd (1, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (trnd (1)), "double");
-%!assert(class (trnd (single(1))), "single");
-%!assert(class (trnd (single([1 1]))), "single");
+%!assert (class (trnd (1)), "double")
+%!assert (class (trnd (single (1))), "single")
+%!assert (class (trnd (single ([1 1]))), "single")
 
 %% Test input validation
 %!error trnd ()
 %!error trnd (1, -1)
-%!error trnd (1, ones(2))
+%!error trnd (1, ones (2))
 %!error trnd (i)
 %!error trnd (1, [2 -1 2])
-%!error trnd (1, 2, ones(2))
+%!error trnd (1, 2, ones (2))
 %!error trnd (1, 2, -1)
-%!error trnd (ones(2,2), 3)
-%!error trnd (ones(2,2), [3, 2])
-%!error trnd (ones(2,2), 2, 3)
+%!error trnd (ones (2,2), 3)
+%!error trnd (ones (2,2), [3, 2])
+%!error trnd (ones (2,2), 2, 3)
 
--- a/scripts/statistics/distributions/unidcdf.m
+++ b/scripts/statistics/distributions/unidcdf.m
@@ -68,22 +68,22 @@
 %!shared x,y
 %! x = [0 1 2.5 10 11];
 %! y = [0, 0.1 0.2 1.0 1.0];
-%!assert(unidcdf (x, 10*ones(1,5)), y);
-%!assert(unidcdf (x, 10), y);
-%!assert(unidcdf (x, 10*[0 1 NaN 1 1]), [NaN 0.1 NaN y(4:5)]);
-%!assert(unidcdf ([x(1:2) NaN Inf x(5)], 10), [y(1:2) NaN 1 y(5)]);
+%!assert (unidcdf (x, 10*ones (1,5)), y)
+%!assert (unidcdf (x, 10), y)
+%!assert (unidcdf (x, 10*[0 1 NaN 1 1]), [NaN 0.1 NaN y(4:5)])
+%!assert (unidcdf ([x(1:2) NaN Inf x(5)], 10), [y(1:2) NaN 1 y(5)])
 
 %% Test class of input preserved
-%!assert(unidcdf ([x, NaN], 10), [y, NaN]);
-%!assert(unidcdf (single([x, NaN]), 10), single([y, NaN]));
-%!assert(unidcdf ([x, NaN], single(10)), single([y, NaN]));
+%!assert (unidcdf ([x, NaN], 10), [y, NaN])
+%!assert (unidcdf (single ([x, NaN]), 10), single ([y, NaN]))
+%!assert (unidcdf ([x, NaN], single (10)), single ([y, NaN]))
 
 %% Test input validation
 %!error unidcdf ()
 %!error unidcdf (1)
 %!error unidcdf (1,2,3)
-%!error unidcdf (ones(3),ones(2))
-%!error unidcdf (ones(2),ones(3))
+%!error unidcdf (ones (3), ones (2))
+%!error unidcdf (ones (2), ones (3))
 %!error unidcdf (i, 2)
 %!error unidcdf (2, i)
 
--- a/scripts/statistics/distributions/unidinv.m
+++ b/scripts/statistics/distributions/unidinv.m
@@ -60,22 +60,22 @@
 
 %!shared x
 %! x = [-1 0 0.5 1 2];
-%!assert(unidinv (x, 10*ones(1,5)), [NaN NaN 5 10 NaN], eps);
-%!assert(unidinv (x, 10), [NaN NaN 5 10 NaN], eps);
-%!assert(unidinv (x, 10*[0 1 NaN 1 1]), [NaN NaN NaN 10 NaN], eps);
-%!assert(unidinv ([x(1:2) NaN x(4:5)], 10), [NaN NaN NaN 10 NaN], eps);
+%!assert (unidinv (x, 10*ones (1,5)), [NaN NaN 5 10 NaN], eps)
+%!assert (unidinv (x, 10), [NaN NaN 5 10 NaN], eps)
+%!assert (unidinv (x, 10*[0 1 NaN 1 1]), [NaN NaN NaN 10 NaN], eps)
+%!assert (unidinv ([x(1:2) NaN x(4:5)], 10), [NaN NaN NaN 10 NaN], eps)
 
 %% Test class of input preserved
-%!assert(unidinv ([x, NaN], 10), [NaN NaN 5 10 NaN NaN], eps);
-%!assert(unidinv (single([x, NaN]), 10), single([NaN NaN 5 10 NaN NaN]), eps);
-%!assert(unidinv ([x, NaN], single(10)), single([NaN NaN 5 10 NaN NaN]), eps);
+%!assert (unidinv ([x, NaN], 10), [NaN NaN 5 10 NaN NaN], eps)
+%!assert (unidinv (single ([x, NaN]), 10), single ([NaN NaN 5 10 NaN NaN]), eps)
+%!assert (unidinv ([x, NaN], single (10)), single ([NaN NaN 5 10 NaN NaN]), eps)
 
 %% Test input validation
 %!error unidinv ()
 %!error unidinv (1)
 %!error unidinv (1,2,3)
-%!error unidinv (ones(3),ones(2))
-%!error unidinv (ones(2),ones(3))
+%!error unidinv (ones (3), ones (2))
+%!error unidinv (ones (2), ones (3))
 %!error unidinv (i, 2)
 %!error unidinv (2, i)
 
--- a/scripts/statistics/distributions/unidpdf.m
+++ b/scripts/statistics/distributions/unidpdf.m
@@ -67,21 +67,21 @@
 %!shared x,y
 %! x = [-1 0 1 2 10 11];
 %! y = [0 0 0.1 0.1 0.1 0];
-%!assert(unidpdf (x, 10*ones(1,6)), y);
-%!assert(unidpdf (x, 10), y);
-%!assert(unidpdf (x, 10*[0 NaN 1 1 1 1]), [NaN NaN y(3:6)]);
-%!assert(unidpdf ([x, NaN], 10), [y, NaN]);
+%!assert (unidpdf (x, 10*ones (1,6)), y)
+%!assert (unidpdf (x, 10), y)
+%!assert (unidpdf (x, 10*[0 NaN 1 1 1 1]), [NaN NaN y(3:6)])
+%!assert (unidpdf ([x, NaN], 10), [y, NaN])
 
 %% Test class of input preserved
-%!assert(unidpdf (single([x, NaN]), 10), single([y, NaN]));
-%!assert(unidpdf ([x, NaN], single(10)), single([y, NaN]));
+%!assert (unidpdf (single ([x, NaN]), 10), single ([y, NaN]))
+%!assert (unidpdf ([x, NaN], single (10)), single ([y, NaN]))
 
 %% Test input validation
 %!error unidpdf ()
 %!error unidpdf (1)
 %!error unidpdf (1,2,3)
-%!error unidpdf (ones(3),ones(2))
-%!error unidpdf (ones(2),ones(3))
+%!error unidpdf (ones (3), ones (2))
+%!error unidpdf (ones (2), ones (3))
 %!error unidpdf (i, 2)
 %!error unidpdf (2, i)
 
--- a/scripts/statistics/distributions/unidrnd.m
+++ b/scripts/statistics/distributions/unidrnd.m
@@ -77,12 +77,12 @@
 
   if (isscalar (n))
     if (n > 0 && n == fix (n))
-      rnd = ceil (rand (sz) * n);
+      rnd = ceil (rand (sz, cls) * n);
     else
       rnd = NaN (sz, cls);
     endif
   else
-    rnd = ceil (rand (sz) .* n);
+    rnd = ceil (rand (sz, cls) .* n);
 
     k = ! (n > 0 & n == fix (n));
     rnd(k) = NaN;
@@ -91,21 +91,21 @@
 endfunction
 
 
-%!assert(size (unidrnd (2)), [1, 1]);
-%!assert(size (unidrnd (ones(2,1))), [2, 1]);
-%!assert(size (unidrnd (ones(2,2))), [2, 2]);
-%!assert(size (unidrnd (10, [4 1])), [4, 1]);
-%!assert(size (unidrnd (10, 4, 1)), [4, 1]);
+%!assert (size (unidrnd (2)), [1, 1])
+%!assert (size (unidrnd (ones (2,1))), [2, 1])
+%!assert (size (unidrnd (ones (2,2))), [2, 2])
+%!assert (size (unidrnd (10, [4 1])), [4, 1])
+%!assert (size (unidrnd (10, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (unidrnd (2)), "double");
-%!assert(class (unidrnd (single(2))), "single");
-%!assert(class (unidrnd (single([2 2]))), "single");
+%!assert (class (unidrnd (2)), "double")
+%!assert (class (unidrnd (single (2))), "single")
+%!assert (class (unidrnd (single ([2 2]))), "single")
 
 %% Test input validation
 %!error unidrnd ()
 %!error unidrnd (10, [1;2;3])
-%!error unidrnd (10, 2, ones(2))
-%!error unidrnd (10*ones(2), 2, 1)
+%!error unidrnd (10, 2, ones (2))
+%!error unidrnd (10*ones (2), 2, 1)
 %!error unidrnd (i)
 
--- a/scripts/statistics/distributions/unifcdf.m
+++ b/scripts/statistics/distributions/unifcdf.m
@@ -72,26 +72,26 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 2] + 1;
 %! y = [0 0 0.5 1 1];
-%!assert(unifcdf (x, ones(1,5), 2*ones(1,5)), y);
-%!assert(unifcdf (x, 1, 2*ones(1,5)), y);
-%!assert(unifcdf (x, ones(1,5), 2), y);
-%!assert(unifcdf (x, [2 1 NaN 1 1], 2), [NaN 0 NaN 1 1]);
-%!assert(unifcdf (x, 1, 2*[0 1 NaN 1 1]), [NaN 0 NaN 1 1]);
-%!assert(unifcdf ([x(1:2) NaN x(4:5)], 1, 2), [y(1:2) NaN y(4:5)]);
+%!assert (unifcdf (x, ones (1,5), 2*ones (1,5)), y)
+%!assert (unifcdf (x, 1, 2*ones (1,5)), y)
+%!assert (unifcdf (x, ones (1,5), 2), y)
+%!assert (unifcdf (x, [2 1 NaN 1 1], 2), [NaN 0 NaN 1 1])
+%!assert (unifcdf (x, 1, 2*[0 1 NaN 1 1]), [NaN 0 NaN 1 1])
+%!assert (unifcdf ([x(1:2) NaN x(4:5)], 1, 2), [y(1:2) NaN y(4:5)])
 
 %% Test class of input preserved
-%!assert(unifcdf ([x, NaN], 1, 2), [y, NaN]);
-%!assert(unifcdf (single([x, NaN]), 1, 2), single([y, NaN]));
-%!assert(unifcdf ([x, NaN], single(1), 2), single([y, NaN]));
-%!assert(unifcdf ([x, NaN], 1, single(2)), single([y, NaN]));
+%!assert (unifcdf ([x, NaN], 1, 2), [y, NaN])
+%!assert (unifcdf (single ([x, NaN]), 1, 2), single ([y, NaN]))
+%!assert (unifcdf ([x, NaN], single (1), 2), single ([y, NaN]))
+%!assert (unifcdf ([x, NaN], 1, single (2)), single ([y, NaN]))
 
 %% Test input validation
 %!error unifcdf ()
 %!error unifcdf (1,2)
 %!error unifcdf (1,2,3,4)
-%!error unifcdf (ones(3),ones(2),ones(2))
-%!error unifcdf (ones(2),ones(3),ones(2))
-%!error unifcdf (ones(2),ones(2),ones(3))
+%!error unifcdf (ones (3), ones (2), ones (2))
+%!error unifcdf (ones (2), ones (3), ones (2))
+%!error unifcdf (ones (2), ones (2), ones (3))
 %!error unifcdf (i, 2, 2)
 %!error unifcdf (2, i, 2)
 %!error unifcdf (2, 2, i)
--- a/scripts/statistics/distributions/unifinv.m
+++ b/scripts/statistics/distributions/unifinv.m
@@ -65,26 +65,26 @@
 
 %!shared x
 %! x = [-1 0 0.5 1 2];
-%!assert(unifinv (x, ones(1,5), 2*ones(1,5)), [NaN 1 1.5 2 NaN]);
-%!assert(unifinv (x, 1, 2*ones(1,5)), [NaN 1 1.5 2 NaN]);
-%!assert(unifinv (x, ones(1,5), 2), [NaN 1 1.5 2 NaN]);
-%!assert(unifinv (x, [1 2 NaN 1 1], 2), [NaN NaN NaN 2 NaN]);
-%!assert(unifinv (x, 1, 2*[1 0 NaN 1 1]), [NaN NaN NaN 2 NaN]);
-%!assert(unifinv ([x(1:2) NaN x(4:5)], 1, 2), [NaN 1 NaN 2 NaN]);
+%!assert (unifinv (x, ones (1,5), 2*ones (1,5)), [NaN 1 1.5 2 NaN])
+%!assert (unifinv (x, 1, 2*ones (1,5)), [NaN 1 1.5 2 NaN])
+%!assert (unifinv (x, ones (1,5), 2), [NaN 1 1.5 2 NaN])
+%!assert (unifinv (x, [1 2 NaN 1 1], 2), [NaN NaN NaN 2 NaN])
+%!assert (unifinv (x, 1, 2*[1 0 NaN 1 1]), [NaN NaN NaN 2 NaN])
+%!assert (unifinv ([x(1:2) NaN x(4:5)], 1, 2), [NaN 1 NaN 2 NaN])
 
 %% Test class of input preserved
-%!assert(unifinv ([x, NaN], 1, 2), [NaN 1 1.5 2 NaN NaN]);
-%!assert(unifinv (single([x, NaN]), 1, 2), single([NaN 1 1.5 2 NaN NaN]));
-%!assert(unifinv ([x, NaN], single(1), 2), single([NaN 1 1.5 2 NaN NaN]));
-%!assert(unifinv ([x, NaN], 1, single(2)), single([NaN 1 1.5 2 NaN NaN]));
+%!assert (unifinv ([x, NaN], 1, 2), [NaN 1 1.5 2 NaN NaN])
+%!assert (unifinv (single ([x, NaN]), 1, 2), single ([NaN 1 1.5 2 NaN NaN]))
+%!assert (unifinv ([x, NaN], single (1), 2), single ([NaN 1 1.5 2 NaN NaN]))
+%!assert (unifinv ([x, NaN], 1, single (2)), single ([NaN 1 1.5 2 NaN NaN]))
 
 %% Test input validation
 %!error unifinv ()
 %!error unifinv (1,2)
 %!error unifinv (1,2,3,4)
-%!error unifinv (ones(3),ones(2),ones(2))
-%!error unifinv (ones(2),ones(3),ones(2))
-%!error unifinv (ones(2),ones(2),ones(3))
+%!error unifinv (ones (3), ones (2), ones (2))
+%!error unifinv (ones (2), ones (3), ones (2))
+%!error unifinv (ones (2), ones (2), ones (3))
 %!error unifinv (i, 2, 2)
 %!error unifinv (2, i, 2)
 %!error unifinv (2, 2, i)
--- a/scripts/statistics/distributions/unifpdf.m
+++ b/scripts/statistics/distributions/unifpdf.m
@@ -68,25 +68,25 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 2] + 1;
 %! y = [0 1 1 1 0];
-%!assert(unifpdf (x, ones(1,5), 2*ones(1,5)), y);
-%!assert(unifpdf (x, 1, 2*ones(1,5)), y);
-%!assert(unifpdf (x, ones(1,5), 2), y);
-%!assert(unifpdf (x, [2 NaN 1 1 1], 2), [NaN NaN y(3:5)]);
-%!assert(unifpdf (x, 1, 2*[0 NaN 1 1 1]), [NaN NaN y(3:5)]);
-%!assert(unifpdf ([x, NaN], 1, 2), [y, NaN]);
+%!assert (unifpdf (x, ones (1,5), 2*ones (1,5)), y)
+%!assert (unifpdf (x, 1, 2*ones (1,5)), y)
+%!assert (unifpdf (x, ones (1,5), 2), y)
+%!assert (unifpdf (x, [2 NaN 1 1 1], 2), [NaN NaN y(3:5)])
+%!assert (unifpdf (x, 1, 2*[0 NaN 1 1 1]), [NaN NaN y(3:5)])
+%!assert (unifpdf ([x, NaN], 1, 2), [y, NaN])
 
 %% Test class of input preserved
-%!assert(unifpdf (single([x, NaN]), 1, 2), single([y, NaN]));
-%!assert(unifpdf (single([x, NaN]), single(1), 2), single([y, NaN]));
-%!assert(unifpdf ([x, NaN], 1, single(2)), single([y, NaN]));
+%!assert (unifpdf (single ([x, NaN]), 1, 2), single ([y, NaN]))
+%!assert (unifpdf (single ([x, NaN]), single (1), 2), single ([y, NaN]))
+%!assert (unifpdf ([x, NaN], 1, single (2)), single ([y, NaN]))
 
 %% Test input validation
 %!error unifpdf ()
 %!error unifpdf (1,2)
 %!error unifpdf (1,2,3,4)
-%!error unifpdf (ones(3),ones(2),ones(2))
-%!error unifpdf (ones(2),ones(3),ones(2))
-%!error unifpdf (ones(2),ones(2),ones(3))
+%!error unifpdf (ones (3), ones (2), ones (2))
+%!error unifpdf (ones (2), ones (3), ones (2))
+%!error unifpdf (ones (2), ones (2), ones (3))
 %!error unifpdf (i, 2, 2)
 %!error unifpdf (2, i, 2)
 %!error unifpdf (2, 2, i)
--- a/scripts/statistics/distributions/unifrnd.m
+++ b/scripts/statistics/distributions/unifrnd.m
@@ -84,12 +84,12 @@
 
   if (isscalar (a) && isscalar (b))
     if ((-Inf < a) && (a < b) && (b < Inf))
-      rnd =  a + (b - a) * rand (sz);
+      rnd =  a + (b - a) * rand (sz, cls);
     else
       rnd = NaN (sz, cls);
     endif
   else
-    rnd =  a + (b - a) .* rand (sz);
+    rnd =  a + (b - a) .* rand (sz, cls);
 
     k = !(-Inf < a) | !(a < b) | !(b < Inf);
     rnd(k) = NaN;
@@ -98,35 +98,35 @@
 endfunction
 
 
-%!assert(size (unifrnd (1,2)), [1, 1]);
-%!assert(size (unifrnd (ones(2,1), 2)), [2, 1]);
-%!assert(size (unifrnd (ones(2,2), 2)), [2, 2]);
-%!assert(size (unifrnd (1, 2*ones(2,1))), [2, 1]);
-%!assert(size (unifrnd (1, 2*ones(2,2))), [2, 2]);
-%!assert(size (unifrnd (1, 2, 3)), [3, 3]);
-%!assert(size (unifrnd (1, 2, [4 1])), [4, 1]);
-%!assert(size (unifrnd (1, 2, 4, 1)), [4, 1]);
+%!assert (size (unifrnd (1,2)), [1, 1])
+%!assert (size (unifrnd (ones (2,1), 2)), [2, 1])
+%!assert (size (unifrnd (ones (2,2), 2)), [2, 2])
+%!assert (size (unifrnd (1, 2*ones (2,1))), [2, 1])
+%!assert (size (unifrnd (1, 2*ones (2,2))), [2, 2])
+%!assert (size (unifrnd (1, 2, 3)), [3, 3])
+%!assert (size (unifrnd (1, 2, [4 1])), [4, 1])
+%!assert (size (unifrnd (1, 2, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (unifrnd (1, 2)), "double");
-%!assert(class (unifrnd (single(1), 2)), "single");
-%!assert(class (unifrnd (single([1 1]), 2)), "single");
-%!assert(class (unifrnd (1, single(2))), "single");
-%!assert(class (unifrnd (1, single([2 2]))), "single");
+%!assert (class (unifrnd (1, 2)), "double")
+%!assert (class (unifrnd (single (1), 2)), "single")
+%!assert (class (unifrnd (single ([1 1]), 2)), "single")
+%!assert (class (unifrnd (1, single (2))), "single")
+%!assert (class (unifrnd (1, single ([2 2]))), "single")
 
 %% Test input validation
 %!error unifrnd ()
 %!error unifrnd (1)
-%!error unifrnd (ones(3),ones(2))
-%!error unifrnd (ones(2),ones(3))
+%!error unifrnd (ones (3), ones (2))
+%!error unifrnd (ones (2), ones (3))
 %!error unifrnd (i, 2)
 %!error unifrnd (2, i)
 %!error unifrnd (1,2, -1)
-%!error unifrnd (1,2, ones(2))
+%!error unifrnd (1,2, ones (2))
 %!error unifrnd (1, 2, [2 -1 2])
-%!error unifrnd (1,2, 1, ones(2))
+%!error unifrnd (1,2, 1, ones (2))
 %!error unifrnd (1,2, 1, -1)
-%!error unifrnd (ones(2,2), 2, 3)
-%!error unifrnd (ones(2,2), 2, [3, 2])
-%!error unifrnd (ones(2,2), 2, 2, 3)
+%!error unifrnd (ones (2,2), 2, 3)
+%!error unifrnd (ones (2,2), 2, [3, 2])
+%!error unifrnd (ones (2,2), 2, 2, 3)
 
--- a/scripts/statistics/distributions/wblcdf.m
+++ b/scripts/statistics/distributions/wblcdf.m
@@ -88,25 +88,25 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 Inf];
 %! y = [0, 1-exp(-x(2:4)), 1];
-%!assert(wblcdf (x, ones(1,5), ones(1,5)), y);
-%!assert(wblcdf (x, 1, ones(1,5)), y);
-%!assert(wblcdf (x, ones(1,5), 1), y);
-%!assert(wblcdf (x, [0 1 NaN Inf 1], 1), [NaN 0 NaN NaN 1]);
-%!assert(wblcdf (x, 1, [0 1 NaN Inf 1]), [NaN 0 NaN NaN 1]);
-%!assert(wblcdf ([x(1:2) NaN x(4:5)], 1, 1), [y(1:2) NaN y(4:5)]);
+%!assert (wblcdf (x, ones (1,5), ones (1,5)), y)
+%!assert (wblcdf (x, 1, ones (1,5)), y)
+%!assert (wblcdf (x, ones (1,5), 1), y)
+%!assert (wblcdf (x, [0 1 NaN Inf 1], 1), [NaN 0 NaN NaN 1])
+%!assert (wblcdf (x, 1, [0 1 NaN Inf 1]), [NaN 0 NaN NaN 1])
+%!assert (wblcdf ([x(1:2) NaN x(4:5)], 1, 1), [y(1:2) NaN y(4:5)])
 
 %% Test class of input preserved
-%!assert(wblcdf ([x, NaN], 1, 1), [y, NaN]);
-%!assert(wblcdf (single([x, NaN]), 1, 1), single([y, NaN]));
-%!assert(wblcdf ([x, NaN], single(1), 1), single([y, NaN]));
-%!assert(wblcdf ([x, NaN], 1, single(1)), single([y, NaN]));
+%!assert (wblcdf ([x, NaN], 1, 1), [y, NaN])
+%!assert (wblcdf (single ([x, NaN]), 1, 1), single ([y, NaN]))
+%!assert (wblcdf ([x, NaN], single (1), 1), single ([y, NaN]))
+%!assert (wblcdf ([x, NaN], 1, single (1)), single ([y, NaN]))
 
 %% Test input validation
 %!error wblcdf ()
 %!error wblcdf (1,2,3,4)
-%!error wblcdf (ones(3),ones(2),ones(2))
-%!error wblcdf (ones(2),ones(3),ones(2))
-%!error wblcdf (ones(2),ones(2),ones(3))
+%!error wblcdf (ones (3), ones (2), ones (2))
+%!error wblcdf (ones (2), ones (3), ones (2))
+%!error wblcdf (ones (2), ones (2), ones (3))
 %!error wblcdf (i, 2, 2)
 %!error wblcdf (2, i, 2)
 %!error wblcdf (2, 2, i)
--- a/scripts/statistics/distributions/wblinv.m
+++ b/scripts/statistics/distributions/wblinv.m
@@ -74,25 +74,25 @@
 
 %!shared x
 %! x = [-1 0 0.63212055882855778 1 2];
-%!assert(wblinv (x, ones(1,5), ones(1,5)), [NaN 0 1 Inf NaN], eps);
-%!assert(wblinv (x, 1, ones(1,5)), [NaN 0 1 Inf NaN], eps);
-%!assert(wblinv (x, ones(1,5), 1), [NaN 0 1 Inf NaN], eps);
-%!assert(wblinv (x, [1 -1 NaN Inf 1], 1), [NaN NaN NaN NaN NaN]);
-%!assert(wblinv (x, 1, [1 -1 NaN Inf 1]), [NaN NaN NaN NaN NaN]);
-%!assert(wblinv ([x(1:2) NaN x(4:5)], 1, 1), [NaN 0 NaN Inf NaN]);
+%!assert (wblinv (x, ones (1,5), ones (1,5)), [NaN 0 1 Inf NaN], eps)
+%!assert (wblinv (x, 1, ones (1,5)), [NaN 0 1 Inf NaN], eps)
+%!assert (wblinv (x, ones (1,5), 1), [NaN 0 1 Inf NaN], eps)
+%!assert (wblinv (x, [1 -1 NaN Inf 1], 1), [NaN NaN NaN NaN NaN])
+%!assert (wblinv (x, 1, [1 -1 NaN Inf 1]), [NaN NaN NaN NaN NaN])
+%!assert (wblinv ([x(1:2) NaN x(4:5)], 1, 1), [NaN 0 NaN Inf NaN])
 
 %% Test class of input preserved
-%!assert(wblinv ([x, NaN], 1, 1), [NaN 0 1 Inf NaN NaN], eps);
-%!assert(wblinv (single([x, NaN]), 1, 1), single([NaN 0 1 Inf NaN NaN]), eps("single"));
-%!assert(wblinv ([x, NaN], single(1), 1), single([NaN 0 1 Inf NaN NaN]), eps("single"));
-%!assert(wblinv ([x, NaN], 1, single(1)), single([NaN 0 1 Inf NaN NaN]), eps("single"));
+%!assert (wblinv ([x, NaN], 1, 1), [NaN 0 1 Inf NaN NaN], eps)
+%!assert (wblinv (single ([x, NaN]), 1, 1), single ([NaN 0 1 Inf NaN NaN]), eps ("single"))
+%!assert (wblinv ([x, NaN], single (1), 1), single ([NaN 0 1 Inf NaN NaN]), eps ("single"))
+%!assert (wblinv ([x, NaN], 1, single (1)), single ([NaN 0 1 Inf NaN NaN]), eps ("single"))
 
 %% Test input validation
 %!error wblinv ()
 %!error wblinv (1,2,3,4)
-%!error wblinv (ones(3),ones(2),ones(2))
-%!error wblinv (ones(2),ones(3),ones(2))
-%!error wblinv (ones(2),ones(2),ones(3))
+%!error wblinv (ones (3), ones (2), ones (2))
+%!error wblinv (ones (2), ones (3), ones (2))
+%!error wblinv (ones (2), ones (2), ones (3))
 %!error wblinv (i, 2, 2)
 %!error wblinv (2, i, 2)
 %!error wblinv (2, 2, i)
--- a/scripts/statistics/distributions/wblpdf.m
+++ b/scripts/statistics/distributions/wblpdf.m
@@ -88,24 +88,24 @@
 %!shared x,y
 %! x = [-1 0 0.5 1 Inf];
 %! y = [0, exp(-x(2:4)), NaN];
-%!assert(wblpdf (x, ones(1,5), ones(1,5)), y);
-%!assert(wblpdf (x, 1, ones(1,5)), y);
-%!assert(wblpdf (x, ones(1,5), 1), y);
-%!assert(wblpdf (x, [0 NaN Inf 1 1], 1), [NaN NaN NaN y(4:5)]);
-%!assert(wblpdf (x, 1, [0 NaN Inf 1 1]), [NaN NaN NaN y(4:5)]);
-%!assert(wblpdf ([x, NaN], 1, 1), [y, NaN]);
+%!assert (wblpdf (x, ones (1,5), ones (1,5)), y)
+%!assert (wblpdf (x, 1, ones (1,5)), y)
+%!assert (wblpdf (x, ones (1,5), 1), y)
+%!assert (wblpdf (x, [0 NaN Inf 1 1], 1), [NaN NaN NaN y(4:5)])
+%!assert (wblpdf (x, 1, [0 NaN Inf 1 1]), [NaN NaN NaN y(4:5)])
+%!assert (wblpdf ([x, NaN], 1, 1), [y, NaN])
 
 %% Test class of input preserved
-%!assert(wblpdf (single([x, NaN]), 1, 1), single([y, NaN]));
-%!assert(wblpdf ([x, NaN], single(1), 1), single([y, NaN]));
-%!assert(wblpdf ([x, NaN], 1, single(1)), single([y, NaN]));
+%!assert (wblpdf (single ([x, NaN]), 1, 1), single ([y, NaN]))
+%!assert (wblpdf ([x, NaN], single (1), 1), single ([y, NaN]))
+%!assert (wblpdf ([x, NaN], 1, single (1)), single ([y, NaN]))
 
 %% Test input validation
 %!error wblpdf ()
 %!error wblpdf (1,2,3,4)
-%!error wblpdf (ones(3),ones(2),ones(2))
-%!error wblpdf (ones(2),ones(3),ones(2))
-%!error wblpdf (ones(2),ones(2),ones(3))
+%!error wblpdf (ones (3), ones (2), ones (2))
+%!error wblpdf (ones (2), ones (3), ones (2))
+%!error wblpdf (ones (2), ones (2), ones (3))
 %!error wblpdf (i, 2, 2)
 %!error wblpdf (2, i, 2)
 %!error wblpdf (2, 2, i)
--- a/scripts/statistics/distributions/wblrnd.m
+++ b/scripts/statistics/distributions/wblrnd.m
@@ -84,12 +84,12 @@
 
   if (isscalar (scale) && isscalar (shape))
     if ((scale > 0) && (scale < Inf) && (shape > 0) && (shape < Inf))
-      rnd = scale * rande (sz) .^ (1/shape);
+      rnd = scale * rande (sz, cls) .^ (1/shape);
     else
       rnd = NaN (sz, cls);
     endif
   else
-    rnd = scale .* rande (sz) .^ (1./shape);
+    rnd = scale .* rande (sz, cls) .^ (1./shape);
 
     k = (scale <= 0) | (scale == Inf) | (shape <= 0) | (shape == Inf);
     rnd(k) = NaN;
@@ -98,35 +98,35 @@
 endfunction
 
 
-%!assert(size (wblrnd (1,2)), [1, 1]);
-%!assert(size (wblrnd (ones(2,1), 2)), [2, 1]);
-%!assert(size (wblrnd (ones(2,2), 2)), [2, 2]);
-%!assert(size (wblrnd (1, 2*ones(2,1))), [2, 1]);
-%!assert(size (wblrnd (1, 2*ones(2,2))), [2, 2]);
-%!assert(size (wblrnd (1, 2, 3)), [3, 3]);
-%!assert(size (wblrnd (1, 2, [4 1])), [4, 1]);
-%!assert(size (wblrnd (1, 2, 4, 1)), [4, 1]);
+%!assert (size (wblrnd (1,2)), [1, 1])
+%!assert (size (wblrnd (ones (2,1), 2)), [2, 1])
+%!assert (size (wblrnd (ones (2,2), 2)), [2, 2])
+%!assert (size (wblrnd (1, 2*ones (2,1))), [2, 1])
+%!assert (size (wblrnd (1, 2*ones (2,2))), [2, 2])
+%!assert (size (wblrnd (1, 2, 3)), [3, 3])
+%!assert (size (wblrnd (1, 2, [4 1])), [4, 1])
+%!assert (size (wblrnd (1, 2, 4, 1)), [4, 1])
 
 %% Test class of input preserved
-%!assert(class (wblrnd (1, 2)), "double");
-%!assert(class (wblrnd (single(1), 2)), "single");
-%!assert(class (wblrnd (single([1 1]), 2)), "single");
-%!assert(class (wblrnd (1, single(2))), "single");
-%!assert(class (wblrnd (1, single([2 2]))), "single");
+%!assert (class (wblrnd (1, 2)), "double")
+%!assert (class (wblrnd (single (1), 2)), "single")
+%!assert (class (wblrnd (single ([1 1]), 2)), "single")
+%!assert (class (wblrnd (1, single (2))), "single")
+%!assert (class (wblrnd (1, single ([2 2]))), "single")
 
 %% Test input validation
 %!error wblrnd ()
 %!error wblrnd (1)
-%!error wblrnd (ones(3),ones(2))
-%!error wblrnd (ones(2),ones(3))
+%!error wblrnd (ones (3), ones (2))
+%!error wblrnd (ones (2), ones (3))
 %!error wblrnd (i, 2)
 %!error wblrnd (2, i)
 %!error wblrnd (1,2, -1)
-%!error wblrnd (1,2, ones(2))
+%!error wblrnd (1,2, ones (2))
 %!error wblrnd (1, 2, [2 -1 2])
-%!error wblrnd (1,2, 1, ones(2))
+%!error wblrnd (1,2, 1, ones (2))
 %!error wblrnd (1,2, 1, -1)
-%!error wblrnd (ones(2,2), 2, 3)
-%!error wblrnd (ones(2,2), 2, [3, 2])
-%!error wblrnd (ones(2,2), 2, 2, 3)
+%!error wblrnd (ones (2,2), 2, 3)
+%!error wblrnd (ones (2,2), 2, [3, 2])
+%!error wblrnd (ones (2,2), 2, 2, 3)
 
--- a/scripts/statistics/models/private/logistic_regression_likelihood.m
+++ b/scripts/statistics/models/private/logistic_regression_likelihood.m
@@ -35,7 +35,7 @@
 
   e = exp ([z, x] * beta); e1 = exp ([z1, x] * beta);
   g = e ./ (1 + e); g1 = e1 ./ (1 + e1);
-  g = max (y == max (y), g); g1 = min (y > min(y), g1);
+  g = max (y == max (y), g); g1 = min (y > min (y), g1);
 
   p = g - g1;
   dev = -2 * sum (log (p));
--- a/scripts/statistics/tests/bartlett_test.m
+++ b/scripts/statistics/tests/bartlett_test.m
@@ -61,7 +61,7 @@
   pval  = 1 - chi2cdf (chisq, df);
 
   if (nargout == 0)
-    printf("  pval: %g\n", pval);
+    printf ("  pval: %g\n", pval);
   endif
 
 endfunction
--- a/scripts/statistics/tests/chisquare_test_homogeneity.m
+++ b/scripts/statistics/tests/chisquare_test_homogeneity.m
@@ -42,7 +42,7 @@
     print_usage ();
   endif
 
-  if (! (isvector(x) && isvector(y) && isvector(c)))
+  if (! (isvector (x) && isvector (y) && isvector (c)))
     error ("chisquare_test_homogeneity: X, Y and C must be vectors");
   endif
   ## Now test c for strictly increasing entries
@@ -57,12 +57,12 @@
   n_x   = sum (x * ones (1, df+1) < ones (l_x, 1) * c);
   l_y   = length (y);
   y     = reshape (y, l_y, 1);
-  n_y   = sum(y * ones (1, df+1) < ones (l_y, 1) * c);
+  n_y   = sum (y * ones (1, df+1) < ones (l_y, 1) * c);
   chisq = l_x * l_y * sum ((n_x/l_x - n_y/l_y).^2 ./ (n_x + n_y));
   pval  = 1 - chi2cdf (chisq, df);
 
   if (nargout == 0)
-    printf("  pval: %g\n", pval);
+    printf ("  pval: %g\n", pval);
   endif
 
 endfunction
--- a/scripts/statistics/tests/chisquare_test_independence.m
+++ b/scripts/statistics/tests/chisquare_test_independence.m
@@ -47,7 +47,7 @@
   pval  = 1 - chi2cdf (chisq, df);
 
   if (nargout == 0)
-    printf("  pval: %g\n", pval);
+    printf ("  pval: %g\n", pval);
   endif
 
 endfunction
--- a/scripts/statistics/tests/kolmogorov_smirnov_test.m
+++ b/scripts/statistics/tests/kolmogorov_smirnov_test.m
@@ -28,7 +28,7 @@
 ## a uniform distribution on [2,4], use
 ##
 ## @example
-## kolmogorov_smirnov_test(x, "unif", 2, 4)
+## kolmogorov_smirnov_test (x, "unif", 2, 4)
 ## @end example
 ##
 ## @noindent
@@ -110,17 +110,18 @@
 
 endfunction
 
-%!error <Invalid call to kolmogorov_smirnov_test>
-%!  kolmogorov_smirnov_test (1);
-%!error <kolmogorov_smirnov_test: X must be a vector>
-%!  kolmogorov_smirnov_test ({}, "unif", 2, 4);
-%!error <kolmogorov_smirnov_test: no not_a_distcdf or not_a_dist_cdf function found>
+
+## test for recognition of unifcdf function
+%!assert (kolmogorov_smirnov_test (0:100, "unif", 0, 100), 1.0, eps)
+## test for recognition of logistic_cdf function
+%!assert (kolmogorov_smirnov_test (0:100, "logistic"), 0)
+## test for  F < G
+%!assert (kolmogorov_smirnov_test (50:100, "unif", 0, 50, "<"))
+
+%!error kolmogorov_smirnov_test (1)
+%!error <X must be a vector> kolmogorov_smirnov_test ({}, "unif", 2, 4)
+%!error <no not_a_distcdf or not_a_dist_cdf function found>
 %!  kolmogorov_smirnov_test (1, "not_a_dist");
-%!error <kolmogorov_smirnov_test: alternative bla not recognized>
-%!  kolmogorov_smirnov_test (1, "unif", 2, 4, "bla");
-%!test # for recognition of unifcdf function
-%!  assert (kolmogorov_smirnov_test (0:100, "unif", 0, 100), 1.0, eps);
-%!test # for recognition of logistic_cdf function
-%!  assert (kolmogorov_smirnov_test (0:100, "logistic"), 0);
-%!test # F < G
-%!  assert (kolmogorov_smirnov_test (50:100, "unif", 0, 50, "<"));
+%!error <alternative foo not recognized>
+%!  kolmogorov_smirnov_test (1, "unif", 2, 4, "foo");
+
--- a/scripts/statistics/tests/kruskal_wallis_test.m
+++ b/scripts/statistics/tests/kruskal_wallis_test.m
@@ -94,5 +94,6 @@
 
 endfunction
 
+
 ## Test with ties
-%!assert (abs(kruskal_wallis_test([86 86], [74]) - 0.157299207050285) < 0.0000000000001)
+%!assert (abs (kruskal_wallis_test ([86 86], [74]) - 0.157299207050285) < 0.0000000000001)
--- a/scripts/statistics/tests/prop_test_2.m
+++ b/scripts/statistics/tests/prop_test_2.m
@@ -65,9 +65,9 @@
   endif
   if (strcmp (alt, "!=") || strcmp (alt, "<>"))
     pval = 2 * min (cdf, 1 - cdf);
-  elseif strcmp (alt, ">")
+  elseif (strcmp (alt, ">"))
     pval = 1 - cdf;
-  elseif strcmp (alt, "<")
+  elseif (strcmp (alt, "<"))
     pval = cdf;
   else
     error ("prop_test_2: option %s not recognized", alt);
--- a/scripts/statistics/tests/run_test.m
+++ b/scripts/statistics/tests/run_test.m
@@ -46,13 +46,13 @@
   b = [1/6; 5/24; 11/120; 19/720; 29/5040; 1/840];
 
   n = rows (x);
-  r = run_count (x, 6) - n * b * ones (1, columns(x));
+  r = run_count (x, 6) - n * b * ones (1, columns (x));
 
   chisq = diag (r' * A * r)' / n;
   pval  = chi2cdf (chisq, 6);
 
   if (nargout == 0)
-    printf("pval: %g\n", pval);
+    printf ("pval: %g\n", pval);
   endif
 
 endfunction
--- a/scripts/statistics/tests/sign_test.m
+++ b/scripts/statistics/tests/sign_test.m
@@ -68,9 +68,9 @@
   endif
   if (strcmp (alt, "!=") || strcmp (alt, "<>"))
     pval = 2 * min (cdf, 1 - cdf);
-  elseif strcmp (alt, ">")
+  elseif (strcmp (alt, ">"))
     pval = 1 - cdf;
-  elseif strcmp (alt, "<")
+  elseif (strcmp (alt, "<"))
     pval = cdf;
   else
     error ("sign_test: option %s not recognized", alt);
--- a/scripts/statistics/tests/t_test.m
+++ b/scripts/statistics/tests/t_test.m
@@ -68,9 +68,9 @@
   endif
   if (strcmp (alt, "!=") || strcmp (alt, "<>"))
     pval = 2 * min (cdf, 1 - cdf);
-  elseif strcmp (alt, ">")
+  elseif (strcmp (alt, ">"))
     pval = 1 - cdf;
-  elseif strcmp (alt, "<")
+  elseif (strcmp (alt, "<"))
     pval = cdf;
   else
     error ("t_test: option %s not recognized", alt);
--- a/scripts/statistics/tests/t_test_2.m
+++ b/scripts/statistics/tests/t_test_2.m
@@ -69,9 +69,9 @@
   endif
   if (strcmp (alt, "!=") || strcmp (alt, "<>"))
     pval = 2 * min (cdf, 1 - cdf);
-  elseif strcmp (alt, ">")
+  elseif (strcmp (alt, ">"))
     pval = 1 - cdf;
-  elseif strcmp (alt, "<")
+  elseif (strcmp (alt, "<"))
     pval = cdf;
   else
     error ("t_test_2: option %s not recognized", alt);
--- a/scripts/statistics/tests/t_test_regression.m
+++ b/scripts/statistics/tests/t_test_regression.m
@@ -81,9 +81,9 @@
 
   if (strcmp (alt, "!=") || strcmp (alt, "<>"))
     pval = 2 * min (cdf, 1 - cdf);
-  elseif strcmp (alt, ">")
+  elseif (strcmp (alt, ">"))
     pval = 1 - cdf;
-  elseif strcmp (alt, "<")
+  elseif (strcmp (alt, "<"))
     pval = cdf;
   else
     error ("t_test_regression: the value '%s' for alt is not possible", alt);
--- a/scripts/statistics/tests/u_test.m
+++ b/scripts/statistics/tests/u_test.m
@@ -66,7 +66,7 @@
   endif
 
   if (! ischar (alt))
-    error("u_test: ALT must be a string");
+    error ("u_test: ALT must be a string");
   endif
   if (strcmp (alt, "!=") || strcmp (alt, "<>"))
     pval = 2 * min (cdf, 1 - cdf);
--- a/scripts/statistics/tests/wilcoxon_test.m
+++ b/scripts/statistics/tests/wilcoxon_test.m
@@ -73,7 +73,7 @@
   endif
 
   if (! ischar (alt))
-    error("wilcoxon_test: ALT must be a string");
+    error ("wilcoxon_test: ALT must be a string");
   elseif (strcmp (alt, "!=") || strcmp (alt, "<>"))
     pval = 2 * min (cdf, 1 - cdf);
   elseif (strcmp (alt, ">"))
--- a/scripts/statistics/tests/z_test.m
+++ b/scripts/statistics/tests/z_test.m
@@ -79,8 +79,8 @@
 
   if (nargout == 0)
     s = cstrcat ("Z-test of mean(x) == %g against mean(x) %s %g,\n",
-                "with known var(x) == %g:\n",
-                "  pval = %g\n");
+                 "with known var(x) == %g:\n",
+                 "  pval = %g\n");
     printf (s, m, alt, m, v, pval);
   endif
 
--- a/scripts/statistics/tests/z_test_2.m
+++ b/scripts/statistics/tests/z_test_2.m
@@ -48,7 +48,7 @@
   endif
 
   if (! (isvector (x) && isvector (y)))
-    error("z_test_2: both X and Y must be vectors");
+    error ("z_test_2: both X and Y must be vectors");
   elseif (! (isscalar (v_x) && (v_x > 0)
              && isscalar (v_y) && (v_y > 0)))
     error ("z_test_2: both V_X and V_Y must be positive scalars");
@@ -79,9 +79,9 @@
 
   if (nargout == 0)
     s = cstrcat ("Two-sample Z-test of mean(x) == mean(y) against ",
-                "mean(x) %s mean(y),\n",
-                "with known var(x) == %g and var(y) == %g:\n",
-                "  pval = %g\n");
+                 "mean(x) %s mean(y),\n",
+                 "with known var(x) == %g and var(y) == %g:\n",
+                 "  pval = %g\n");
     printf (s, alt, v_x, v_y, pval);
   endif
 
--- a/scripts/strings/base2dec.m
+++ b/scripts/strings/base2dec.m
@@ -117,20 +117,20 @@
 endfunction
 
 
-%!assert(base2dec ("11120", 3), 123);
-%!assert(base2dec ("yyyzx", "xyz"), 123);
-%!assert(base2dec ("-1", 2), NaN);
-%!assert(base2dec ({"A1", "1A"}, 16), [161; 26]);
+%!assert (base2dec ("11120", 3), 123)
+%!assert (base2dec ("yyyzx", "xyz"), 123)
+%!assert (base2dec ("-1", 2), NaN)
+%!assert (base2dec ({"A1", "1A"}, 16), [161; 26])
 
 %% Bug #35621
 %!assert (base2dec (["0"; "1"], 2), [0; 1])
 
 %%Test input validation
-%!error base2dec ();
-%!error base2dec ("11120");
-%!error base2dec ("11120", 3, 4);
-%!error base2dec ("11120", "1231");
-%!error base2dec ("11120", "12 3");
-%!error base2dec ("11120", ones(2));
-%!error base2dec ("11120", 37);
+%!error base2dec ()
+%!error base2dec ("11120")
+%!error base2dec ("11120", 3, 4)
+%!error base2dec ("11120", "1231")
+%!error base2dec ("11120", "12 3")
+%!error base2dec ("11120", ones (2))
+%!error base2dec ("11120", 37)
 
--- a/scripts/strings/bin2dec.m
+++ b/scripts/strings/bin2dec.m
@@ -60,15 +60,15 @@
 endfunction
 
 
-%!assert(bin2dec ("0000"), 0);
-%!assert(bin2dec ("1110"), 14);
-%!assert(bin2dec ("11111111111111111111111111111111111111111111111111111"), 2^53-1);
-%!assert(bin2dec ({"1110", "1111"}), [14; 15]);
+%!assert (bin2dec ("0000"), 0)
+%!assert (bin2dec ("1110"), 14)
+%!assert (bin2dec ("11111111111111111111111111111111111111111111111111111"), 2^53-1)
+%!assert (bin2dec ({"1110", "1111"}), [14; 15])
 %!assert (bin2dec ("1 0 1"), 5)
-%!assert (bin2dec (char ("1 0 1", "   1111")), [5; 15]);
+%!assert (bin2dec (char ("1 0 1", "   1111")), [5; 15])
 
 %%Test input validation
-%!error bin2dec ();
-%!error bin2dec (1);
-%!error bin2dec ("1", 2);
+%!error bin2dec ()
+%!error bin2dec (1)
+%!error bin2dec ("1", 2)
 
--- a/scripts/strings/blanks.m
+++ b/scripts/strings/blanks.m
@@ -23,7 +23,7 @@
 ## @example
 ## @group
 ## blanks (10);
-## whos ans;
+## whos ans
 ##      @result{}
 ##       Attr Name        Size                     Bytes  Class
 ##       ==== ====        ====                     =====  =====
@@ -52,9 +52,9 @@
 
 
 ## There really isn't that much to test here
-%!assert(blanks (0), "")
-%!assert(blanks (5), "     ")
-%!assert(blanks (10), "          ")
+%!assert (blanks (0), "")
+%!assert (blanks (5), "     ")
+%!assert (blanks (10), "          ")
 
 %% Test input validation
 %!error blanks ()
--- a/scripts/strings/cstrcat.m
+++ b/scripts/strings/cstrcat.m
@@ -32,8 +32,8 @@
 ## @group
 ## s = [ "ab"; "cde" ];
 ## cstrcat (s, s, s)
-##      @result{} "ab ab ab "
-##         "cdecdecde"
+##       @result{} "ab ab ab "
+##          "cdecdecde"
 ## @end group
 ## @end example
 ## @seealso{strcat, char, strvcat}
@@ -64,6 +64,6 @@
 %!assert (cstrcat (["a"; "bb"], ["foo"; "bar"]), ["a foo"; "bbbar"])
 
 %% Test input validation
-%!error cstrcat ();
-%!error cstrcat (1, 2);
+%!error cstrcat ()
+%!error cstrcat (1, 2)
 
--- a/scripts/strings/deblank.m
+++ b/scripts/strings/deblank.m
@@ -75,15 +75,15 @@
 endfunction
 
 
-%!assert (deblank (" f o o \0"), " f o o");
-%!assert (deblank ('   '), '');
-%!assert (deblank ("   "), "");
-%!assert (deblank (""), "");
-%!assert (deblank ({}), {});
-%!assert (deblank ({" abc   ", {"   def   "}}), {" abc", {"   def"}});
+%!assert (deblank (" f o o \0"), " f o o")
+%!assert (deblank ('   '), '')
+%!assert (deblank ("   "), "")
+%!assert (deblank (""), "")
+%!assert (deblank ({}), {})
+%!assert (deblank ({" abc   ", {"   def   "}}), {" abc", {"   def"}})
 
-%!error <Invalid call to deblank> deblank ();
-%!error <Invalid call to deblank> deblank ("foo", "bar");
-%!error <argument must be a string> deblank (1);
-%!error <argument must be a string> deblank ({[]});
+%!error <Invalid call to deblank> deblank ()
+%!error <Invalid call to deblank> deblank ("foo", "bar")
+%!error <argument must be a string> deblank (1)
+%!error <argument must be a string> deblank ({[]})
 
--- a/scripts/strings/dec2base.m
+++ b/scripts/strings/dec2base.m
@@ -119,23 +119,23 @@
 
 
 %!test
-%! s0 = '';
+%! s0 = "";
 %! for n = 1:13
 %!   for b = 2:16
 %!     pp = dec2base (b^n+1, b);
-%!     assert (dec2base(b^n, b), ['1',s0,'0']);
-%!     assert (dec2base(b^n+1, b), ['1',s0,'1']);
+%!     assert (dec2base (b^n, b), ['1',s0,'0']);
+%!     assert (dec2base (b^n+1, b), ['1',s0,'1']);
 %!   endfor
 %!   s0 = [s0,'0'];
 %! endfor
 
 %!test
-%! digits='0123456789ABCDEF';
+%! digits = "0123456789ABCDEF";
 %! for n = 1:13
 %!   for b = 2:16
-%!     pm = dec2base(b^n-1, b);
+%!     pm = dec2base (b^n-1, b);
 %!     assert (length (pm), n);
-%!     assert (all (pm==digits(b)));
+%!     assert (all (pm == digits(b)));
 %!   endfor
 %! endfor
 
@@ -144,12 +144,12 @@
 %!   assert (dec2base (0, b), '0');
 %! endfor
 
-%!assert(dec2base (0, 2, 4), "0000");
-%!assert(dec2base (2^51-1, 2), ...
-%!       '111111111111111111111111111111111111111111111111111');
-%!assert(dec2base(uint64(2)^63-1, 16), '7FFFFFFFFFFFFFFF');
-%!assert(dec2base([1, 2; 3, 4], 2, 3), ["001"; "011"; "010"; "100"]);
-%!assert(dec2base({1, 2; 3, 4}, 2, 3), ["001"; "011"; "010"; "100"]);
+%!assert (dec2base (0, 2, 4), "0000")
+%!assert (dec2base (2^51-1, 2), ...
+%!        "111111111111111111111111111111111111111111111111111")
+%!assert (dec2base (uint64 (2)^63-1, 16), "7FFFFFFFFFFFFFFF")
+%!assert (dec2base ([1, 2; 3, 4], 2, 3), ["001"; "011"; "010"; "100"])
+%!assert (dec2base ({1, 2; 3, 4}, 2, 3), ["001"; "011"; "010"; "100"])
 
 %%Test input validation
 %!error dec2base ()
@@ -161,7 +161,7 @@
 %!error dec2base (1.1)
 %!error dec2base (1, "ABA")
 %!error dec2base (1, "A B")
-%!error dec2base (1, ones(2))
+%!error dec2base (1, ones (2))
 %!error dec2base (1, 1)
 %!error dec2base (1, 37)
 
--- a/scripts/strings/dec2bin.m
+++ b/scripts/strings/dec2bin.m
@@ -53,11 +53,11 @@
 endfunction
 
 
-%!assert(dec2bin (14), "1110");
-%!assert(dec2bin (14, 6), "001110");
-%!assert(dec2bin ({1, 2; 3, 4}), ["001"; "011"; "010"; "100"]);
+%!assert (dec2bin (14), "1110")
+%!assert (dec2bin (14, 6), "001110")
+%!assert (dec2bin ({1, 2; 3, 4}), ["001"; "011"; "010"; "100"])
 
 %%Test input validation
-%!error dec2bin ();
-%!error dec2bin (1, 2, 3);
+%!error dec2bin ()
+%!error dec2bin (1, 2, 3)
 
--- a/scripts/strings/dec2hex.m
+++ b/scripts/strings/dec2hex.m
@@ -53,11 +53,11 @@
 endfunction
 
 
-%!assert(dec2hex (2748), "ABC");
-%!assert(dec2hex (2748, 5), "00ABC");
-%!assert(dec2hex ({2748, 2746}), ["ABC"; "ABA"]);
+%!assert (dec2hex (2748), "ABC")
+%!assert (dec2hex (2748, 5), "00ABC")
+%!assert (dec2hex ({2748, 2746}), ["ABC"; "ABA"])
 
 %% Test input validation
-%!error dec2hex ();
-%!error dec2hex (1, 2, 3);
+%!error dec2hex ()
+%!error dec2hex (1, 2, 3)
 
--- a/scripts/strings/findstr.m
+++ b/scripts/strings/findstr.m
@@ -133,11 +133,11 @@
 
 
 %!assert (findstr ("abababa", "a"), [1, 3, 5, 7])
-%!assert (findstr ("abababa", "aba"), [1, 3, 5]);
-%!assert (findstr ("aba", "abababa", 0), [1, 5]);
+%!assert (findstr ("abababa", "aba"), [1, 3, 5])
+%!assert (findstr ("aba", "abababa", 0), [1, 5])
 
 %% Test input validation
 %!error findstr ()
-%!error findstr ("foo", "bar", 3, 4);
-%!error findstr (["AB" ; "CD"], "C");
+%!error findstr ("foo", "bar", 3, 4)
+%!error <must have only one non-singleton dimension> findstr (["AB" ; "CD"], "C")
 
--- a/scripts/strings/hex2dec.m
+++ b/scripts/strings/hex2dec.m
@@ -24,9 +24,9 @@
 ## @example
 ## @group
 ## hex2dec ("12B")
-##      @result{} 299
+##       @result{} 299
 ## hex2dec ("12b")
-##      @result{} 299
+##       @result{} 299
 ## @end group
 ## @end example
 ##
@@ -53,13 +53,13 @@
 endfunction
 
 
-%!assert(hex2dec ("0000"), 0);
-%!assert(hex2dec ("1FFFFFFFFFFFFF"), 2^53-1);
-%!assert(hex2dec (["12b"; "12B"]), [299; 299]);
-%!assert(hex2dec ({"A1", "1A"}), [161; 26]);
+%!assert (hex2dec ("0000"), 0)
+%!assert (hex2dec ("1FFFFFFFFFFFFF"), 2^53-1)
+%!assert (hex2dec (["12b"; "12B"]), [299; 299])
+%!assert (hex2dec ({"A1", "1A"}), [161; 26])
 
 %%Test input validation
-%!error hex2dec ();
-%!error hex2dec (1);
-%!error hex2dec ("1", 2);
+%!error hex2dec ()
+%!error hex2dec (1)
+%!error hex2dec ("1", 2)
 
--- a/scripts/strings/index.m
+++ b/scripts/strings/index.m
@@ -28,7 +28,7 @@
 ## @example
 ## @group
 ## index ("Teststring", "t")
-##    @result{} 4
+##     @result{} 4
 ## @end group
 ## @end example
 ##
@@ -84,20 +84,21 @@
 endfunction
 
 
-%!assert (index ("foobarbaz", "b") == 4 && index ("foobarbaz", "z") == 9);
+%!assert (index ("foobarbaz", "b"), 4)
+%!assert (index ("foobarbaz", "z"), 9)
 
-%!assert (index("astringbstringcstring", "s"), 2)
-%!assert (index("astringbstringcstring", "st"), 2)
-%!assert (index("astringbstringcstring", "str"), 2)
-%!assert (index("astringbstringcstring", "string"), 2)
-%!assert (index("abc---", "abc+++"), 0)
+%!assert (index ("astringbstringcstring", "s"), 2)
+%!assert (index ("astringbstringcstring", "st"), 2)
+%!assert (index ("astringbstringcstring", "str"), 2)
+%!assert (index ("astringbstringcstring", "string"), 2)
+%!assert (index ("abc---", "abc+++"), 0)
 
 ## test everything out in reverse
-%!assert (index("astringbstringcstring", "s", "last"), 16)
-%!assert (index("astringbstringcstring", "st", "last"), 16)
-%!assert (index("astringbstringcstring", "str", "last"), 16)
-%!assert (index("astringbstringcstring", "string", "last"), 16)
-%!assert (index("abc---", "abc+++", "last"), 0)
+%!assert (index ("astringbstringcstring", "s", "last"), 16)
+%!assert (index ("astringbstringcstring", "st", "last"), 16)
+%!assert (index ("astringbstringcstring", "str", "last"), 16)
+%!assert (index ("astringbstringcstring", "string", "last"), 16)
+%!assert (index ("abc---", "abc+++", "last"), 0)
 
 %!test
 %! str = char ("Hello", "World", "Goodbye", "World");
--- a/scripts/strings/isletter.m
+++ b/scripts/strings/isletter.m
@@ -36,5 +36,7 @@
 
 endfunction
 
-%!error isletter();
-%!error isletter("a", "b");
+
+%!error isletter ()
+%!error isletter ("a", "b")
+
--- a/scripts/strings/mat2str.m
+++ b/scripts/strings/mat2str.m
@@ -41,7 +41,7 @@
 ## mat2str ([ -1/3 +i/7; 1/3 -i/7 ], [4 2])
 ##      @result{} "[-0.3333+0i 0+0.14i;0.3333+0i -0-0.14i]"
 ##
-## mat2str (int16([1 -1]), "class")
+## mat2str (int16 ([1 -1]), "class")
 ##      @result{} "int16([1 -1])"
 ##
 ## mat2str (logical (eye (2)))
@@ -128,20 +128,20 @@
 endfunction
 
 
-%!assert (mat2str (0.7), "0.7");
-%!assert (mat2str (pi), "3.14159265358979");
-%!assert (mat2str (pi, 5), "3.1416");
-%!assert (mat2str (single (pi), 5, "class"), "single(3.1416)");
+%!assert (mat2str (0.7), "0.7")
+%!assert (mat2str (pi), "3.14159265358979")
+%!assert (mat2str (pi, 5), "3.1416")
+%!assert (mat2str (single (pi), 5, "class"), "single(3.1416)")
 %!assert (mat2str ([-1/3 + i/7; 1/3 - i/7], [4 2]), "[-0.3333+0.14i;0.3333-0.14i]")
 %!assert (mat2str ([-1/3 +i/7; 1/3 -i/7], [4 2]), "[-0.3333+0i 0+0.14i;0.3333+0i -0-0.14i]")
-%!assert (mat2str (int16 ([1 -1]), 'class'), "int16([1 -1])")
-%!assert (mat2str (true), "true");
-%!assert (mat2str (false), "false");
-%!assert (mat2str (logical (eye (2))), "[true false;false true]");
+%!assert (mat2str (int16 ([1 -1]), "class"), "int16([1 -1])")
+%!assert (mat2str (true), "true")
+%!assert (mat2str (false), "false")
+%!assert (mat2str (logical (eye (2))), "[true false;false true]")
 
 %% Test input validation
 %!error mat2str ()
 %!error mat2str (1,2,3,4)
 %!error mat2str (["Hello"])
-%!error mat2str (ones(3,3,2))
+%!error <X must be two dimensional> mat2str (ones (3,3,2))
 
--- a/scripts/strings/module.mk
+++ b/scripts/strings/module.mk
@@ -21,6 +21,7 @@
   strings/strcat.m \
   strings/cstrcat.m \
   strings/strchr.m \
+  strings/strjoin.m \
   strings/strjust.m \
   strings/strmatch.m \
   strings/strtok.m \
--- a/scripts/strings/regexptranslate.m
+++ b/scripts/strings/regexptranslate.m
@@ -53,7 +53,7 @@
 
 function y = regexptranslate (op, s)
 
-  if nargin != 2
+  if (nargin != 2)
     print_usage ();
   endif
 
@@ -67,7 +67,7 @@
                                             '\*', '.*'), 
                                             '\?', '.');
   elseif (strcmp ("escape", op))
-    y = regexprep (s, '([^\w])', '\$1');
+    y = regexprep (s, '([^\w])', '\\$1');
   else
     error ("regexptranslate: invalid operation OP");
   endif
--- a/scripts/strings/rindex.m
+++ b/scripts/strings/rindex.m
@@ -52,7 +52,8 @@
 endfunction
 
 
-%!assert(rindex ("foobarbaz", "b") == 7 && rindex ("foobarbaz", "o") == 3);
+%!assert (rindex ("foobarbaz", "b"), 7)
+%!assert (rindex ("foobarbaz", "o"), 3)
 
 %!test
 %! str = char ("Hello", "World", "Goodbye", "World");
--- a/scripts/strings/str2num.m
+++ b/scripts/strings/str2num.m
@@ -68,8 +68,8 @@
 endfunction
 
 
-%!assert(str2num ("-1.3e2"), -130);
-%!assert(str2num ("[1, 2; 3, 4]"), [1, 2; 3, 4]);
+%!assert (str2num ("-1.3e2"), -130)
+%!assert (str2num ("[1, 2; 3, 4]"), [1, 2; 3, 4])
 
 %!test
 %! [x, state] = str2num ("pi");
--- a/scripts/strings/strcat.m
+++ b/scripts/strings/strcat.m
@@ -23,11 +23,35 @@
 ## horizontally.  If the arguments are cells strings,  @code{strcat}
 ## returns a cell string with the individual cells concatenated.
 ## For numerical input, each element is converted to the
-## corresponding ASCII character.  Trailing white space is eliminated.
+## corresponding ASCII character.  Trailing white space for each of
+## the inputs (@var{s1}, @var{S2}, @dots{}) is eliminated before they
+## are concatenated.
+##
 ## For example:
 ##
 ## @example
 ## @group
+## strcat ("|", " leading space is preserved", "|")
+##     @result{} | leading space is perserved|
+## @end group
+## @end example
+##
+## @example
+## @group
+## strcat ("|", "trailing space is eliminated ", "|")
+##     @result{} |trailing space is eliminated|
+## @end group
+## @end example
+##
+## @example
+## @group
+## strcat ("homogeneous space |", "  ", "| is also eliminated")
+##     @result{} homogeneous space || is also eliminated
+## @end group
+## @end example
+##
+## @example
+## @group
 ## s = [ "ab"; "cde" ];
 ## strcat (s, s, s)
 ##     @result{}
@@ -96,32 +120,31 @@
 
 ## test the dimensionality
 ## 1d
-%!assert(strcat("ab ", "ab "), "abab")
-%!assert(strcat({"ab "}, "ab "), {"ab ab"})
-%!assert(strcat("ab ", {"ab "}), {"abab "})
-%!assert(strcat({"ab "}, {"ab "}), {"ab ab "})
-%!assert(strcat("", "ab"), "ab")
-%!assert(strcat("", {"ab"}, {""}), {"ab"})
+%!assert (strcat ("ab ", "ab "), "abab")
+%!assert (strcat ({"ab "}, "ab "), {"ab ab"})
+%!assert (strcat ("ab ", {"ab "}), {"abab "})
+%!assert (strcat ({"ab "}, {"ab "}), {"ab ab "})
+%!assert (strcat ("", "ab"), "ab")
+%!assert (strcat ("", {"ab"}, {""}), {"ab"})
 ## 2d
-%!assert(strcat(["ab ";"cde"], ["ab ";"cde"]), ["abab  ";"cdecde"])
+%!assert (strcat (["ab ";"cde"], ["ab ";"cde"]), ["abab  ";"cdecde"])
 
 ## test for deblanking implied trailing spaces of character input
-%!assert((strcmp (strcat ("foo", "bar"), "foobar")
-%!        && strcmp (strcat (["a"; "bb"], ["foo"; "bar"]), ["afoo "; "bbbar"])));
+%!assert (strcat ("foo", "bar"), "foobar")
+%!assert (strcat (["a"; "bb"], ["foo"; "bar"]), ["afoo "; "bbbar"])
 
 ## test for mixing character and cell inputs
-%!assert(all (strcmp (strcat ("a", {"bc", "de"}, "f"), {"abcf", "adef"})))
+%!assert (strcat ("a", {"bc", "de"}, "f"), {"abcf", "adef"})
 
 ## test for scalar strings with vector strings
-%!assert(all (strcmp (strcat (["a"; "b"], "c"), ["ac"; "bc"])))
+%!assert (strcat (["a"; "b"], "c"), ["ac"; "bc"])
 
 ## test with cells with strings of differing lengths
-%!assert(all (strcmp (strcat ({"a", "bb"}, "ccc"), {"accc", "bbccc"})))
-%!assert(all (strcmp (strcat ("a", {"bb", "ccc"}), {"abb", "accc"})))
-
-%!error strcat ();
+%!assert (all (strcmp (strcat ({"a", "bb"}, "ccc"), {"accc", "bbccc"})))
+%!assert (all (strcmp (strcat ("a", {"bb", "ccc"}), {"abb", "accc"})))
 
-%!assert (strcat (1, 2), strcat (char(1), char(2)))
+%!assert (strcat (1, 2), strcat (char (1), char (2)))
+%!assert (strcat ("", 2), strcat ([], char (2)))
 
-%!assert (strcat ('', 2), strcat ([], char(2)))
+%!error strcat ()
 
--- a/scripts/strings/strchr.m
+++ b/scripts/strings/strchr.m
@@ -53,7 +53,7 @@
     ## Index the str into a mask of valid values.
     ## This is slower than it could be because of the +1 issue.
     f = false (256, 1);
-    f(uint8(chars)+1) = true;
+    f(uint8 (chars) + 1) = true;
     ## Default goes via double -- unnecessarily long.
     si = uint32 (str);
     ## in-place is faster than str+1
new file mode 100644
--- /dev/null
+++ b/scripts/strings/strjoin.m
@@ -0,0 +1,84 @@
+## Copyright (C) 2007 Muthiah Annamalai <muthiah.annamalai@uta.edu>
+## Copyright (C) 2013 Ben Abbott <bpabbott@mac.com>
+##
+## 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{str} =} strjoin (@var{cstr})
+## @deftypefnx {Function File} {@var{str} =} strjoin (@var{cstr}, @var{delimiter})
+## Joins the elements of the cell-string array, @var{cstr}, into a single
+## string.
+##
+## If no @var{delimiter} is specified, the elements of @var{cstr}
+## seperated by a space.
+##
+## If @var{delimiter} is specified as a string, the cell-string array is
+## joined using the string.
+##
+## If @var{delimiter} is a cell-string array whose length is one less
+## than @var{cstr}, then the elemennts of @var{cstr} are joined by
+## interleaving the cell-string elements of @var{delimiter}.
+##
+## @example
+## @group
+## strjoin (@{'Octave','Scilab','Lush','Yorick'@}, '*')
+##       @result{} 'Octave*Scilab*Lush*Yorick'
+## @end group
+## @end example
+## @seealso {strsplit}
+## @end deftypefn
+
+function rval = strjoin (cstr, delimiter)
+
+  if (nargin == 1)
+    delimiter = " ";
+  elseif (nargin < 1 || nargin > 2)
+    print_usage ();
+  elseif (! (iscellstr (cstr) && (ischar (delimiter) || iscellstr (delimiter))))
+    print_usage ();
+  endif
+
+  if (numel (cstr) == 1)
+    rval = cstr{1};
+    return
+  endif
+
+  if (ischar (delimiter))
+    delimiter = {delimiter};
+  end
+ 
+  num = numel (cstr); 
+  if (numel (delimiter) == 1 && num > 1)
+    delimiter = repmat (delimiter, 1, num);
+    delimiter(end) = {""};
+  elseif (numel (delimiter) != num - 1)
+    error ("strjoin:cellstring_delimiter_mismatch",
+      "strjoin: the number of delimiters does not match the number of strings")
+  else
+    delimiter(end+1) = {""};
+  endif
+
+  rval = sprintf ("%s", [cstr(:).'; delimiter(:).']{:});
+
+endfunction
+
+%!assert (strjoin ({"hello"}, "-"), "hello")
+%!assert (strjoin ({"hello", "world"}), "hello world")
+%!assert (strjoin ({"Octave", "Scilab", "Lush", "Yorick"}, "*"),
+%!  "Octave*Scilab*Lush*Yorick")
+%!assert (strjoin ({"space", "comma", "dash", "semicolon", "done"},
+%!  {" ", ",", "-", ";"}), "space comma,dash-semicolon;done")
--- a/scripts/strings/strjust.m
+++ b/scripts/strings/strjust.m
@@ -87,7 +87,7 @@
   endif
 
   ## Adjust the column indices.
-  jdx += shift(idx);
+  jdx += shift (idx);
 
   ## Create a blank matrix and position the nonblank characters.
   y = repmat (" ", nr, nc);
@@ -97,16 +97,16 @@
 
 
 %!assert (strjust (["a"; "ab"; "abc"; "abcd"]),
-%!        ["   a";"  ab"; " abc"; "abcd"]);
+%!        ["   a";"  ab"; " abc"; "abcd"])
 %!assert (strjust ([" a"; "  ab"; "abc"; "abcd"], "left"),
-%!        ["a   "; "ab  "; "abc "; "abcd"]);
+%!        ["a   "; "ab  "; "abc "; "abcd"])
 %!assert (strjust (["a"; "ab"; "abc"; "abcd"], "CENTER"),
-%!        [" a  "; " ab"; "abc "; "abcd"]);
-%!assert (strjust (["";""]), "");
+%!        [" a  "; " ab"; "abc "; "abcd"])
+%!assert (strjust (["";""]), "")
 
 %% Test input validation
 %!error <Invalid call to strjust> strjust ()
 %!error <Invalid call to strjust> strjust (["a";"ab"], "center", 1)
-%!error <S must be a string> strjust (ones(3,3))
-%!error <S must be a string> strjust (char (ones(3,3,3)))
+%!error <S must be a string> strjust (ones (3,3))
+%!error <S must be a string> strjust (char (ones (3,3,3)))
 
--- a/scripts/strings/strmatch.m
+++ b/scripts/strings/strmatch.m
@@ -26,7 +26,6 @@
 ## array of strings.  If the third argument @code{"exact"} is not given, then
 ## @var{s} only needs to match @var{A} up to the length of @var{s}.
 ## Trailing spaces and nulls in @var{s} and @var{A} are ignored when matching.
-## option.
 ##
 ## For example:
 ##
@@ -44,7 +43,8 @@
 ## @end example
 ##
 ## @strong{Caution:} @code{strmatch} is scheduled for deprecation.  Use
-## @code{strcmpi} or @code{strncmpi} in all new code.
+## @code{strncmp} (normal case), or @code{strcmp} ("exact" case), or
+## @code{regexp} in all new code.
 ## @seealso{strfind, findstr, strcmp, strncmp, strcmpi, strncmpi, find}
 ## @end deftypefn
 
@@ -97,23 +97,23 @@
 endfunction
 
 
-%!assert (strmatch("a", {"aaa", "bab", "bbb"}), 1);
-%!assert (strmatch ("apple", "apple juice"), 1);
-%!assert (strmatch ("apple", ["apple pie"; "apple juice"; "an apple"]), [1; 2]);
-%!assert (strmatch ("apple", {"apple pie"; "apple juice"; "tomato"}), [1; 2]);
-%!assert (strmatch ("apple pie", "apple"), []);
-%!assert (strmatch ("a ", "a"), 1);
-%!assert (strmatch ("a", "a \0", "exact"), 1);
-%!assert (strmatch ("a b", {"a b", "a c", "c d"}), 1);
-%!assert (strmatch ("", {"", "foo", "bar", ""}), [1, 4]);
-%!assert (strmatch ('', { '', '% comment', 'var a = 5', ''}, 'exact'), [1,4]);
+%!assert (strmatch ("a", {"aaa", "bab", "bbb"}), 1)
+%!assert (strmatch ("apple", "apple juice"), 1)
+%!assert (strmatch ("apple", ["apple pie"; "apple juice"; "an apple"]), [1; 2])
+%!assert (strmatch ("apple", {"apple pie"; "apple juice"; "tomato"}), [1; 2])
+%!assert (strmatch ("apple pie", "apple"), [])
+%!assert (strmatch ("a ", "a"), 1)
+%!assert (strmatch ("a", "a \0", "exact"), 1)
+%!assert (strmatch ("a b", {"a b", "a c", "c d"}), 1)
+%!assert (strmatch ("", {"", "foo", "bar", ""}), [1, 4])
+%!assert (strmatch ('', { '', '% comment', 'var a = 5', ''}, 'exact'), [1,4])
 
 %% Test input validation
-%!error <Invalid call to strmatch> strmatch();
-%!error <Invalid call to strmatch> strmatch("a");
-%!error <Invalid call to strmatch> strmatch("a", "aaa", "exact", 1);
-%!error <S must be a string> strmatch(1, "aaa");
-%!error <S must be a string> strmatch(char ("a", "bb"), "aaa");
-%!error <A must be a string> strmatch("a", 1);
-%!error <A must be a string> strmatch("a", {"hello", [1]});
+%!error <Invalid call to strmatch> strmatch ()
+%!error <Invalid call to strmatch> strmatch ("a")
+%!error <Invalid call to strmatch> strmatch ("a", "aaa", "exact", 1)
+%!error <S must be a string> strmatch (1, "aaa")
+%!error <S must be a string> strmatch (char ("a", "bb"), "aaa")
+%!error <A must be a string> strmatch ("a", 1)
+%!error <A must be a string> strmatch ("a", {"hello", [1]})
 
--- a/scripts/strings/strsplit.m
+++ b/scripts/strings/strsplit.m
@@ -17,20 +17,33 @@
 ## <http://www.gnu.org/licenses/>.
 
 ## -*- texinfo -*-
-## @deftypefn  {Function File} {[@var{cstr}] =} strsplit (@var{s}, @var{sep})
-## @deftypefnx {Function File} {[@var{cstr}] =} strsplit (@var{s}, @var{sep}, @var{strip_empty})
-## Split the string @var{s} using one or more separators @var{sep} and return
-## a cell array of strings.  Consecutive separators and separators at
-## boundaries result in empty strings, unless @var{strip_empty} is true.
-## The default value of @var{strip_empty} is false.
+## @deftypefn  {Function File} {[@var{cstr}] =} strsplit (@var{s})
+## @deftypefnx {Function File} {[@var{cstr}] =} strsplit (@var{s}, @var{del})
+## @deftypefnx {Function File} {[@var{cstr}] =} strsplit (@var{s}, @var{del}, @var{collapsedelimiters})
+## @deftypefnx {Function File} {[@var{cstr}] =} strsplit (@dots{}, @var{name}, @var{value})
+## @deftypefnx {Function File} {[@var{cstr}, @var{matches}] =} strsplit (@dots{})
+## Split the string @var{s} using the delimiters specified by @var{del}
+## and return a cell array of strings.  For a single delimiter, @var{del}
+## may be a string, or a scalar cell-string.  For multible delimiters, 
+## @var{del} must be a cell-string array.  Unless @var{collapsedelimiters} is
+## specified to be @var{false}, consecutive delimiters are collapsed into one.
 ##
-## 2-D character arrays are split at separators and at the original column
-## boundaries.
+## The second output, @var{matches}, returns the delmiters which were matched
+## in the original string.  The matched delimiters are uneffected by the
+## @var{collapsedelimiters}.
 ##
 ## Example:
 ##
 ## @example
 ## @group
+## strsplit ("a b c")
+##       @result{}
+##           @{
+##             [1,1] = a
+##             [1,2] = b
+##             [1,3] = c
+##           @}
+##
 ## strsplit ("a,b,c", ",")
 ##       @result{}
 ##           @{
@@ -39,80 +52,332 @@
 ##             [1,3] = c
 ##           @}
 ##
-## strsplit (["a,b" ; "cde"], ",")
+## strsplit ("a foo b,bar c", @{"\s", "foo", "bar"@})
+##       @result{}
+##           @{
+##             [1,1] = a
+##             [1,2] = b
+##             [1,3] = c
+##           @}
+##
+## strsplit ("a,,b, c", @{",", " "@}, false)
+##       @result{}
+##           @{
+##             [1,1] = a
+##             [1,2] = 
+##             [1,3] = b
+##             [1,4] = 
+##             [1,5] = c
+##           @}
+##
+## @end group
+## @end example
+##
+## Supported @var{name}/@var{value} pair arguments are;
+##
+## @itemize
+## @item @var{collapsedelimiters} may take the value of @var{true} or @var{false}
+## with the default being @var{false}.
+## @item @var{delimitertype} may take the value of @code{legacy},
+## @code{simple} or @code{regularexpression}.
+## If @var{delimitertype} is equal to @code{legacy}, each individual
+## character of @var{del} is used to split the input.  For both @code{simple}
+## and @code{regularexpression}, the string is split at the boundaries of the
+## delimiter string.  If @var{delimiter} is a cell-string, then the string
+## is split at the boundaries of each of the cells' strings.  @var{simple}
+## delimiters may contain escaped characters, but are otherwise treated as
+## literal strings.
+##
+## If the specified delimiters are single characters, the default is
+## @var{delimitertype} is @code{legacy}.  Otherwise the default
+## @var{delimitertype} is @code{simple}.
+## @end itemize
+## 
+## Example:
+##
+## @example
+## @group
+## strsplit ("a foo b,bar c", ",|\\s|foo|bar", "delimitertype", "regularexpression")
+##       @result{}
+##           @{
+##             [1,1] = a
+##             [1,2] = b
+##             [1,3] = c
+##           @}
+## 
+## strsplit ("a,,b, c", "[, ]", false, "delimitertype", "regularexpression")
+##       @result{}
+##           @{
+##             [1,1] = a
+##             [1,2] = 
+##             [1,3] = b
+##             [1,4] = 
+##             [1,5] = c
+##           @}
+## 
+## strsplit ("a,,b, c", ", ", false, "delimitertype", "legacy")
+##       @result{}
+##           @{
+##             [1,1] = a
+##             [1,2] = 
+##             [1,3] = b
+##             [1,4] = 
+##             [1,5] = c
+##           @}
+## 
+## strsplit ("a,\t,b, c", @{',', '\s'@}, "delimitertype", "regularexpression")
 ##       @result{}
 ##           @{
 ##             [1,1] = a
 ##             [1,2] = b
-##             [1,3] = cde
+##             [1,3] = c
 ##           @}
 ## @end group
 ## @end example
-## @seealso{strtok}
+## 
+## @seealso{strjoin, strtok, regexp}
 ## @end deftypefn
 
-function cstr = strsplit (s, sep, strip_empty = false)
+function [result, matches] = strsplit (str, del, varargin)
 
-  if (nargin < 2 || nargin > 3)
+  args.collapsedelimiters = true;
+  args.delimitertype = "default";
+
+  [reg, params] = parseparams (varargin);
+
+  if (numel (reg) > 1)
     print_usage ();
-  elseif (! ischar (s) || ! ischar (sep))
-    error ("strsplit: S and SEP must be string values");
-  elseif (! isscalar (strip_empty))
-    error ("strsplit: STRIP_EMPTY must be a scalar value");
+  elseif (numel (reg) == 1)
+    if (islogical (reg{1}) || isnumeric (reg{1}))
+      args.collapsedelimiters = reg{1};
+    else
+      print_usage ();
+    endif
+  endif
+  fields = fieldnames (args);
+  for n = 1:2:numel(params)
+    if (any (strcmpi (params{n}, fields)))
+      args.(lower(params{n})) = params{n+1};
+    elseif (ischar (varargin{n}))
+      error ("strsplit:invalid_parameter_name",
+        sprintf ("strsplit: Invalid parameter name, `%s'", varargin{n}))
+    else
+      print_usage ();
+    endif
+  endfor
+
+  if (strcmpi (args.delimitertype, "default"))
+    if (nargin == 1 || numel (del) == 1
+      || (nargin > 1 && (islogical (del) || isnumeric (del)))
+      || iscell (del) && all (cellfun (@numel, del) < 2))
+      ## For single character delimiters, default to "legacy"
+      args.delimitertype = "legacy";
+    else
+      ## For multi-character delimiters, default to "simple"
+      args.delimitertype = "simple";
+    endif
   endif
 
-  if (isempty (s))
-    cstr = cell (size (s));
-  else
-    if (rows (s) > 1)
-      ## For 2-D arrays, add separator character at line boundaries
-      ## and transform to single string
-      s(:, end+1) = sep(1);
-      s = reshape (s.', 1, numel (s));
-      s(end) = []; 
+  # Save the length of the "delimitertype" parameter
+  length_deltype = numel (args.delimitertype);
+
+  if (nargin == 1 || (nargin > 1 && (islogical (del) || isnumeric (del))))
+    if (nargin > 1)
+      ## Second input is the "collapsedelimiters" parameter
+      args.collapsedelimiters = del;
+    endif
+    ## Set proper default for the delimiter type
+    if (strncmpi (args.delimitertype, "simple", numel (args.delimitertype)))
+      del = {" ","\f","\n","\r","\t","\v"};
+    elseif (strncmpi (args.delimitertype, "legacy", numel (args.delimitertype)))
+      del = " \f\n\r\t\v";
+    else
+      del = "\\s";
     endif
+  endif
 
-    ## Split s according to delimiter
-    if (isscalar (sep))
+  if (nargin < 1)
+    print_usage ();
+  elseif (! ischar (str) || (! ischar (del) && ! iscellstr (del)))
+    error ("strsplit: S and DEL must be string values");
+  elseif (! isscalar (args.collapsedelimiters))
+    error ("strsplit: COLLAPSEDELIMITERS must be a scalar value");
+  endif
+
+  if (strncmpi (args.delimitertype, "simple", length_deltype))
+    if (iscellstr (del))
+      del = cellfun (@do_string_escapes, del, "uniformoutput", false);
+    else
+      del = do_string_escapes (del);
+    endif
+    del = regexprep (del, '([^\w])', '\\$1');
+  endif
+
+  if (rows (str) > 1)
+    tmp = char (del(1));
+    str = [str, repmat(tmp,rows(str),1)];
+    str = reshape (str.', 1, numel (str));
+    str(end-numel(tmp)+1:end) = [];
+  endif
+
+  if (isempty (str))
+    result = {str};
+  elseif (strncmpi (args.delimitertype, "legacy", length_deltype))
+    ## Legacy splitting is fast
+    if (! ischar (del))
+      if (iscell (del) && all (cellfun (@numel, del) < 2))
+        del = [del{:}];
+      else
+        error ("strsplit:legacy_delimiter_must_be_char",
+          "%s %s", "strsplit: for DELIMITERTYPE = ""legacy"" ", 
+           "DEL must be a string, or a cell array scalar character elements.")
+      endif
+    endif
+    if (strcmp (typeinfo (del), "sq_string"))
+      del = do_string_escapes (del);
+    endif
+    ## Split str at each character contained in del
+    if (isscalar (del))
       ## Single separator
-      idx = find (s == sep);
+      idx = find (str == del);
     else
       ## Multiple separators
-      idx = strchr (s, sep);
+      idx = strchr (str, del);
     endif
 
     ## Get substring lengths.
     if (isempty (idx))
-      strlens = length (s);
+      strlens = length (str);
     else
-      strlens = [idx(1)-1, diff(idx)-1, numel(s)-idx(end)];
+      strlens = [idx(1)-1, diff(idx)-1, numel(str)-idx(end)];
+    endif
+    if (nargout > 1)
+      ## Grab the separators
+      matches = num2cell (str(idx)(:)).';
+      if (args.collapsedelimiters)
+        ## Collapse the consequtive delimiters
+        ## TODO - is there a vectorized way?
+        for m = numel(matches):-1:2
+          if (strlens(m) == 0)
+            matches{m-1} = [matches{m-1:m}];
+            matches(m) = [];
+          endif
+        end
+      endif
     endif
     ## Remove separators.
-    s(idx) = [];
-    if (strip_empty)
+    str(idx) = [];
+    if (args.collapsedelimiters)
       ## Omit zero lengths.
       strlens = strlens(strlens != 0);
     endif
 
     ## Convert!
-    cstr = mat2cell (s, 1, strlens);
+    result = mat2cell (str, 1, strlens);
+  elseif (strncmpi (args.delimitertype, "regularexpression", length_deltype)
+          || strncmpi (args.delimitertype, "simple", length_deltype))
+    if (iscellstr (del))
+      del = sprintf ('%s|', del{:});
+      del(end) = [];
+    endif
+    if (args.collapsedelimiters)
+      del = ["(", del, ")+"];
+    endif
+    [result, ~, ~, ~, matches] = regexp (str, del, "split");
+  else
+    error ("strsplit:invalid_delimitertype", 
+      sprintf ("strsplit: Invalid DELIMITERTYPE"))
   endif
-
 endfunction
 
+% Mimic the old strsplit()
+%!assert (cellfun (@numel, strsplit (["a,b,c";"1,2   "], ",")), [1 1 2 1 4])
 
+%!shared str
+%! str = "The rain in Spain stays mainly in the plain.";
+% Split on all whitespace.
+%!assert (strsplit (str), {"The", "rain", "in", "Spain", "stays", ...
+%! "mainly", "in", "the", "plain."})
+% Split on "ain".
+%!assert (strsplit (str, "ain"), {"The r", " in Sp", " stays m", ...
+%!  "ly in the pl", "."})
+% Split on " " and "ain" (treating multiple delimiters as one).
+%!test
+%! s = strsplit (str, '\s|ain', true, "delimitertype", "r");
+%! assert (s, {"The", "r", "in", "Sp", "stays", "m", "ly", "in", "the", "pl", "."})
+%!test
+%! s = strsplit (str, "\\s|ain", true, "delimitertype", "r");
+%! assert (s, {"The", "r", "in", "Sp", "stays", "m", "ly", "in", "the", "pl", "."})
+%!test
+%! [s, m] = strsplit (str, {"\\s", "ain"}, true, "delimitertype", "r");
+%! assert (s, {"The", "r", "in", "Sp", "stays", "m", "ly", "in", "the", "pl", "."})
+%! assert (m, {" ", "ain ", " ", "ain ", " ", "ain", " ", " ", " ", "ain"})
+% Split on " " and "ain", and treat multiple delimiters separately.
+%!test
+%! [s, m] = strsplit (str, {" ", "ain"}, "collapsedelimiters", false);
+%! assert (s, {"The", "r", "", "in", "Sp", "", "stays", "m", "ly", "in", "the", "pl", "."})
+%! assert (m, {" ", "ain", " ", " ", "ain", " ", " ", "ain", " ", " ", " ", "ain"})
+
+%!assert (strsplit ("road to hell"), {"road", "to", "hell"})
 %!assert (strsplit ("road to hell", " "), {"road", "to", "hell"})
-%!assert (strsplit ("road to^hell", " ^"), {"road", "to", "hell"})
-%!assert (strsplit ("road   to--hell", " -", true), {"road", "to", "hell"})
-%!assert (strsplit (["a,bc";",de"], ","), {"a", "bc", ones(1,0), "de "})
-%!assert (strsplit (["a,bc";",de"], ",", true), {"a", "bc", "de "})
-%!assert (strsplit (["a,bc";",de"], ", ", true), {"a", "bc", "de"})
+%!assert (strsplit ("road to^hell", {" ","^"}), {"road", "to", "hell"})
+%!assert (strsplit ("road   to--hell", {" ","-"}, true), {"road", "to", "hell"})
+%!assert (strsplit (["a,bc,,de"], ",", false, "delimitertype", "s"), {"a", "bc", "", "de"})
+%!assert (strsplit (["a,bc,,de"], ",", false), {"a", "bc", char(ones(1,0)), "de"})
+%!assert (strsplit (["a,bc,de"], ",", true), {"a", "bc", "de"})
+%!assert (strsplit (["a,bc,de"], {","," "}, true), {"a", "bc", "de"})
+
+%!assert (strsplit ("road to hell", " ", "delimitertype", "r"), {"road", "to", "hell"})
+%!assert (strsplit ("road to^hell", '\^| ', "delimitertype", "r"), {"road", "to", "hell"})
+%!assert (strsplit ("road to^hell", "[ ^]", "delimitertype", "r"), {"road", "to", "hell"})
+%!assert (strsplit ("road   to--hell", "[ -]", false, "delimitertype", "r"), {"road", "", "", "to", "", "hell"})
+%!assert (strsplit (["a,bc,de"], ",", "delimitertype", "r"), {"a", "bc", "de"})
+%!assert (strsplit (["a,bc,,de"], ",", false, "delimitertype", "r"), {"a", "bc", "", "de"})
+%!assert (strsplit (["a,bc,de"], ",", true, "delimitertype", "r"), {"a", "bc", "de"})
+%!assert (strsplit (["a,bc,de"], "[, ]", true, "delimitertype", "r"), {"a", "bc", "de"})
+%!assert (strsplit ("hello \t world", 1, "delimitertype", "r"), {"hello", "world"});
+
+%!assert (strsplit ("road to hell", " ", false, "delimitertype", "l"), {"road", "to", "hell"})
+%!assert (strsplit ("road to^hell", " ^", false, "delimitertype", "l"), {"road", "to", "hell"})
+%!assert (strsplit ("road   to--hell", " -", true, "delimitertype", "l"), {"road", "to", "hell"})
+%!assert (strsplit (["a,bc";",de"], ",", false, "delimitertype", "l"), {"a", "bc", char(ones(1,0)), "de "})
+%!assert (strsplit (["a,bc";",de"], ",", true, "delimitertype", "l"), {"a", "bc", "de "})
+%!assert (strsplit (["a,bc";",de"], ", ", true, "delimitertype", "l"), {"a", "bc", "de"})
+
+%!assert (strsplit ("foo\tbar", '\t', "delimitertype", "l"), {"foo", "bar"})
+%!assert (strsplit ("foo\tbar", '\t', "delimitertype", "r"), {"foo", "bar"})
+%!assert (strsplit ("foo\tbar", '\t', "delimitertype", "s"), {"foo", "bar"})
+
+## Test "match" for consecutive delmiters
+%!test
+%! [a, m] = strsplit ("a\t \nb", '\s', 'delimitertype', 'regularexpression',
+%!   'collapsedelimiters', false);
+%! assert (a, {"a", "", "", "b"})
+%! assert (m, {"\t", " ", "\n"})
+%!test
+%! [a, m] = strsplit ("a\t \nb", '\s', false, 'delimitertype', 'regularexpression');
+%! assert (a, {"a", "", "", "b"})
+%! assert (m, {"\t", " ", "\n"})
+%!test
+%! [a, m] = strsplit ("a\t \nb", '\s', "delimitertype", "regularexpression");
+%! assert (a, {"a", "b"})
+%! assert (m, {"\t \n"})
+%!test
+%! [a, m] = strsplit ("a\t \nb", {"\t", " ", "\n"}, "delimitertype", "simple");
+%! assert (a, {"a", "b"})
+%! assert (m, {"\t \n"})
+%!test
+%! [a, m] = strsplit ("a123b", "123", "delimitertype", "legacy");
+%! assert (a, {"a", "b"})
+%! assert (m, {"123"})
+%!test
+%! [s, m] = strsplit ("hello \t world", 1);
+%! assert (s, {"hello", "world"});
+%! assert (m, {" \t "});
 
 %% Test input validation
 %!error strsplit ()
-%!error strsplit ("abc")
 %!error strsplit ("abc", "b", true, 4)
-%!error <S and SEP must be string values> strsplit (123, "b")
-%!error <S and SEP must be string values> strsplit ("abc", 1)
-%!error <STRIP_EMPTY must be a scalar value> strsplit ("abc", "def", ones(3,3))
+%!error <S and DEL must be string values> strsplit (123, "b")
+%!error <COLLAPSEDELIMITERS must be a scalar value> strsplit ("abc", "def", ones (3,3))
 
--- a/scripts/strings/strtok.m
+++ b/scripts/strings/strtok.m
@@ -75,7 +75,7 @@
       ## Index the str into a mask of valid values.  Faster for large N.
       f = false (256, 1);
       ## This is slower than it could be because of the +1 issue.
-      f(uint8(delim)+1) = true;
+      f(uint8 (delim)+1) = true;
       ## Default goes via double -- unnecessarily long.
       si = uint32 (str);
       ## in-place is faster than str+1
@@ -133,7 +133,7 @@
 
 
 %!demo
-%! strtok("this is the life")
+%! strtok ("this is the life")
 %! % split at the first space, returning "this"
 
 %!demo
@@ -146,7 +146,7 @@
 %!   endif
 %!   printf ("<%s>", s(1));
 %! endwhile
-%! printf("\n");
+%! printf ("\n");
 %! % ----------------------------------------------------
 %! % Demonstrates processing of an entire string split on
 %! % a variety of delimiters.  Tokens and delimiters are
@@ -190,19 +190,19 @@
 %! assert (r{7}, "");
 
 %% Simple check for 2, 3, and 4 delimeters
-%!assert(strtok ("this is", "i "), "th");
-%!assert(strtok ("this is", "ij "), "th");
-%!assert(strtok ("this is", "ijk "), "th");
+%!assert (strtok ("this is", "i "), "th")
+%!assert (strtok ("this is", "ij "), "th")
+%!assert (strtok ("this is", "ijk "), "th")
 
 %% Test all cases for 8 delimiters since a different
 %!# algorithm is used when more than 7 delimiters
-%!assert (strtok ("","jklmnop "), "");
-%!assert (strtok ("this","jklmnop "), "this");
-%!assert (strtok ("this ","jklmnop "), "this");
-%!assert (strtok ("this is","jklmnop "), "this");
-%!assert (strtok (" this","jklmnop "), "this");
-%!assert (strtok (" this ","jklmnop "), "this");
-%!assert (strtok (" ","jklmnop "), ""(1:0));
+%!assert (strtok ("","jklmnop "), "")
+%!assert (strtok ("this","jklmnop "), "this")
+%!assert (strtok ("this ","jklmnop "), "this")
+%!assert (strtok ("this is","jklmnop "), "this")
+%!assert (strtok (" this","jklmnop "), "this")
+%!assert (strtok (" this ","jklmnop "), "this")
+%!assert (strtok (" ","jklmnop "), ""(1:0))
 
 %% Test 'bad' string orientations
 %!assert (strtok (" this ".'), "this".');   # delimiter at start and end
@@ -213,7 +213,7 @@
 %! for ch = "\t\n\v\f\r"
 %!   [t, r] = strtok (cstrcat ("beg", ch, "end"));
 %!   assert (t, "beg");
-%!   assert (r, cstrcat (ch, "end"))
+%!   assert (r, cstrcat (ch, "end"));
 %! endfor
 
 %% Test input validation
--- a/scripts/strings/strtrim.m
+++ b/scripts/strings/strtrim.m
@@ -74,15 +74,15 @@
 endfunction
 
 
-%!assert (strtrim ("    abc  "), "abc");
-%!assert (strtrim ("  "), "");
-%!assert (strtrim ("abc"), "abc");
-%!assert (strtrim ([" abc   "; "   def   "]), ["abc  "; "  def"]);
-%!assert (strtrim ({" abc   "; "   def   "}), {"abc"; "def"});
-%!assert (strtrim ({" abc   ", {"   def   "}}), {"abc", {"def"}});
+%!assert (strtrim ("    abc  "), "abc")
+%!assert (strtrim ("  "), "")
+%!assert (strtrim ("abc"), "abc")
+%!assert (strtrim ([" abc   "; "   def   "]), ["abc  "; "  def"])
+%!assert (strtrim ({" abc   "; "   def   "}), {"abc"; "def"})
+%!assert (strtrim ({" abc   ", {"   def   "}}), {"abc", {"def"}})
 
-%!error <Invalid call to strtrim> strtrim ();
-%!error <Invalid call to strtrim> strtrim ("abc", "def");
-%!error <argument must be a string> strtrim (1);
-%!error <argument must be a string> strtrim ({[]});
+%!error <Invalid call to strtrim> strtrim ()
+%!error <Invalid call to strtrim> strtrim ("abc", "def")
+%!error <argument must be a string> strtrim (1)
+%!error <argument must be a string> strtrim ({[]})
 
--- a/scripts/strings/strtrunc.m
+++ b/scripts/strings/strtrunc.m
@@ -55,12 +55,12 @@
 endfunction
 
 
-%!assert (strtrunc("abcdefg", 4), "abcd");
-%!assert (strtrunc("abcdefg", 10), "abcdefg");
-%!assert (strtrunc(char ("abcdef", "fedcba"), 3), ["abc"; "fed"]);
-%!assert (strtrunc({"abcdef", "fedcba"}, 3), {"abc", "fed"});
-%!assert (strtrunc({"", "1", "21", "321"}, 1), {"", "1", "2", "3"})
-%!assert (strtrunc({"1", "", "2"}, 1), {"1", "", "2"})
+%!assert (strtrunc ("abcdefg", 4), "abcd")
+%!assert (strtrunc ("abcdefg", 10), "abcdefg")
+%!assert (strtrunc (char ("abcdef", "fedcba"), 3), ["abc"; "fed"])
+%!assert (strtrunc ({"abcdef", "fedcba"}, 3), {"abc", "fed"})
+%!assert (strtrunc ({"", "1", "21", "321"}, 1), {"", "1", "2", "3"})
+%!assert (strtrunc ({"1", "", "2"}, 1), {"1", "", "2"})
 %!test
 %! cstr = {"line1"; ["line2"; "line3"]; "line4"};
 %! y = strtrunc (cstr, 4);
--- a/scripts/strings/substr.m
+++ b/scripts/strings/substr.m
@@ -92,19 +92,19 @@
 endfunction
 
 
-%!assert (substr ("This is a test string", 6, 9), "is a test");
-%!assert (substr ("This is a test string", -11), "test string");
-%!assert (substr ("This is a test string", -11, 4), "test");
-%!assert (substr ("This is a test string", -11, -7), "test");
-%!assert (substr ("This is a test string", 1, -7), "This is a test");
-%!assert (isempty (substr ("This is a test string", 1, 0)));
+%!assert (substr ("This is a test string", 6, 9), "is a test")
+%!assert (substr ("This is a test string", -11), "test string")
+%!assert (substr ("This is a test string", -11, 4), "test")
+%!assert (substr ("This is a test string", -11, -7), "test")
+%!assert (substr ("This is a test string", 1, -7), "This is a test")
+%!assert (isempty (substr ("This is a test string", 1, 0)))
 
 %% Test input validation
 %!error substr ()
 %!error substr ("foo", 2, 3, 4)
 %!error substr (ones (5, 1), 1, 1)
-%!error substr ("foo", ones(2,2))
-%!error substr ("foo", 1, ones(2,2))
+%!error substr ("foo", ones (2,2))
+%!error substr ("foo", 1, ones (2,2))
 %!error substr ("foo", 0)
 %!error substr ("foo", 5)
 %!error substr ("foo", 1, 5)
--- a/scripts/strings/untabify.m
+++ b/scripts/strings/untabify.m
@@ -82,10 +82,10 @@
     nr = rows (t);
     sc = cell (nr, 1);
     for j = 1:nr
-      n = 1:numel(t(j,:));
+      n = 1:numel (t(j,:));
       m = find (t(j,:) == "\t");
       t(j,m) = " ";
-      for i = 1:numel(m)
+      for i = 1:numel (m)
         k = tw * ceil (n(m(i)) / tw);
         dn = k - n(m(i));
         n(m(i):end) += dn;
--- a/scripts/strings/validatestring.m
+++ b/scripts/strings/validatestring.m
@@ -138,12 +138,13 @@
 
 
 %!shared strarray
-%!  strarray = {"octave" "Oct" "octopus" "octaves"};
+%! strarray = {"octave" "Oct" "octopus" "octaves"};
 %!assert (validatestring ("octave", strarray), "octave")
 %!assert (validatestring ("oct", strarray), "Oct")
 %!assert (validatestring ("octa", strarray), "octave")
-%!  strarray = {"abc1" "def" "abc2"};
+%! strarray = {"abc1" "def" "abc2"};
 %!assert (validatestring ("d", strarray), "def")
+
 %!error <'xyz' does not match any> validatestring ("xyz", strarray)
 %!error <Function: DUMMY_TEST> validatestring ("xyz", strarray, "DUMMY_TEST")
 %!error <Function: DUMMY_TEST Variable: DUMMY_VAR:> validatestring ("xyz", strarray, "DUMMY_TEST", "DUMMY_VAR")
new file mode 100644
--- /dev/null
+++ b/scripts/testfun/__have_feature__.m
@@ -0,0 +1,34 @@
+## Copyright (C) 2013 John W. Eaton
+##
+## 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} {} __have_feature__ (feature)
+## Undocumented internal function.
+## @end deftypefn
+
+function retval = __have_feature__ (feature)
+  features = octave_config_info ("features");
+  if (iscellstr (feature))
+    retval = (all (isfield (features, feature))
+              && cellfun (@(x) features.(x), feature));
+  elseif (ischar (feature))
+    retval = isfield (features, feature) && features.(feature);
+  else
+    retval = false;
+  endif
+endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/testfun/__printf_assert__.m
@@ -0,0 +1,27 @@
+## Copyright (C) 2005-2012 David Bateman
+##
+## 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} {} __printf_assert__ (@dots{})
+## Undocumented internal function.
+## @end deftypefn
+
+function __printf_assert__ (varargin)
+  global _assert_printf;
+  _assert_printf = cat (2, _assert_printf, sprintf (varargin{:}));
+endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/testfun/__prog_output_assert__.m
@@ -0,0 +1,34 @@
+## Copyright (C) 2005-2012 David Bateman
+##
+## 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} {} __prog_output_assert__ (@var{str})
+## Undocumented internal function.
+## @end deftypefn
+
+function ret = __prog_output_assert__ (str)
+  global _assert_printf;
+  if (isempty (_assert_printf))
+    ret = isempty (str);
+  elseif (_assert_printf(end) == "\n")
+    ret = strcmp (_assert_printf(1:(end-1)), str);
+  else
+    ret = strcmp (_assert_printf, str);
+  endif
+  _assert_printf = "";
+endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/testfun/__run_test_suite__.m
@@ -0,0 +1,285 @@
+## Copyright (C) 2005-2012 David Bateman
+##
+## 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} {} __run_test_suite__ (@var{fcndirs}, @var{fixedtestdirs})
+## Undocumented internal function.
+## @end deftypefn
+
+function __run_test_suite__ (fcndirs, fixedtestdirs)
+  testsdir = octave_config_info ("octtestsdir");
+  libinterptestdir = fullfile (testsdir, "libinterp");
+  liboctavetestdir = fullfile (testsdir, "liboctave");
+  fixedtestdir = fullfile (testsdir, "fixed");
+  fcnfiledir = octave_config_info ("fcnfiledir");
+  if (nargin == 0)
+    fcndirs = { libinterptestdir, liboctavetestdir, fcnfiledir };
+    fixedtestdirs = { fixedtestdir };
+  endif
+  global files_with_no_tests = {};
+  global files_with_tests = {};
+  ## FIXME -- these names don't really make sense if we are running
+  ## tests for an installed copy of Octave.
+  global topsrcdir = fcnfiledir;
+  global topbuilddir = testsdir;
+  pso = page_screen_output ();
+  warn_state = warning ("query", "quiet");
+  warning ("on", "quiet");
+  try
+    page_screen_output (0);
+    warning ("off", "Octave:deprecated-function");
+    fid = fopen ("fntests.log", "wt");
+    if (fid < 0)
+      error ("could not open fntests.log for writing");
+    endif
+    test ("", "explain", fid);
+    dp = dn = dxf = dsk = 0;
+    puts ("\nIntegrated test scripts:\n\n");
+    for i = 1:length (fcndirs)
+      [p, n, xf, sk] = run_test_script (fid, fcndirs{i});
+      dp += p;
+      dn += n;
+      dxf += xf;
+      dsk += sk;
+    endfor
+    puts ("\nFixed test scripts:\n\n");
+    for i = 1:length (fixedtestdirs)
+      [p, n, xf, sk] = run_test_dir (fid, fixedtestdirs{i});
+      dp += p;
+      dn += n;
+      dxf += xf;
+      dsk += sk;
+    endfor
+    puts ("\nSummary:\n\n");
+    nfail = dn - dp;
+    printf ("  PASS    %6d\n", dp);
+    printf ("  FAIL    %6d\n", nfail);
+    if (dxf > 0)
+      printf ("  XFAIL   %6d\n", dxf);
+    endif
+    if (dsk > 0)
+      printf ("  SKIPPED %6d\n", dsk);
+    endif
+    puts ("\n");
+    puts ("See the file test/fntests.log for additional details.\n");
+    if (dxf > 0)
+      puts ("\n");
+      puts ("Expected failures (listed as XFAIL above) are known bugs.\n");
+      puts ("Please help improve Octave by contributing fixes for them.\n");
+    endif
+    if (dsk > 0)
+      puts ("\n");
+      puts ("Tests are most often skipped because the features they require\n");
+      puts ("have been disabled.  Features are most often disabled because\n");
+      puts ("they require dependencies that were not present when Octave\n");
+      puts ("was built.  The configure script should have printed a summary\n");
+      puts ("at the end of its run indicating which dependencies were not found.\n");
+    endif
+
+    ## Weed out deprecated and private functions
+    weed_idx = cellfun (@isempty, regexp (files_with_tests, '\bdeprecated\b|\bprivate\b', 'once'));
+    files_with_tests = files_with_tests(weed_idx);
+    weed_idx = cellfun (@isempty, regexp (files_with_no_tests, '\bdeprecated\b|\bprivate\b', 'once'));
+    files_with_no_tests = files_with_no_tests(weed_idx);
+
+    report_files_with_no_tests (files_with_tests, files_with_no_tests, ".m");
+
+    puts ("\nPlease help improve Octave by contributing tests for\n");
+    puts ("these files (see the list in the file fntests.log).\n\n");
+
+    fprintf (fid, "\nFiles with no tests:\n\n%s",
+            list_in_columns (files_with_no_tests, 80));
+    fclose (fid);
+
+    page_screen_output (pso);
+    warning (warn_state.state, "quiet");
+  catch
+    page_screen_output (pso);
+    warning (warn_state.state, "quiet");
+    disp (lasterr ());
+  end_try_catch
+endfunction
+
+function print_test_file_name (nm)
+  filler = repmat (".", 1, 55-length (nm));
+  printf ("  %s %s", nm, filler);
+endfunction
+
+function print_pass_fail (n, p)
+  if (n > 0)
+    printf (" PASS %4d/%-4d", p, n);
+    nfail = n - p;
+    if (nfail > 0)
+      printf (" FAIL %d", nfail);
+    endif
+  endif
+  puts ("\n");
+endfunction
+
+function retval = has_functions (f)
+  n = length (f);
+  if (n > 3 && strcmp (f((end-2):end), ".cc"))
+    fid = fopen (f);
+    if (fid >= 0)
+      str = fread (fid, "*char")';
+      fclose (fid);
+      retval = ! isempty (regexp (str,'^(DEFUN|DEFUN_DLD)\b', 'lineanchors'));
+    else
+      error ("fopen failed: %s", f);
+    endif
+  elseif (n > 2 && strcmp (f((end-1):end), ".m"))
+    retval = true;
+  else
+    retval = false;
+  endif
+endfunction
+
+function retval = has_tests (f)
+  fid = fopen (f);
+  if (fid >= 0)
+    str = fread (fid, "*char")';
+    fclose (fid);
+    retval = ! isempty (regexp (str, '^%!(assert|error|fail|test|warning)', "lineanchors"));
+  else
+    error ("fopen failed: %s", f);
+  endif
+endfunction
+
+function retval = has_demos (f)
+  fid = fopen (f);
+  if (fid >= 0)
+    str = fread (fid, "*char")';
+    fclose (fid);
+    retval = ! isempty (regexp (str, '^%!demo', "lineanchors"));
+  else
+    error ("fopen failed: %s", f);
+  endif
+endfunction
+
+function [dp, dn, dxf, dsk] = run_test_dir (fid, d);
+  global files_with_tests;
+  global files_with_no_tests;
+  lst = dir (d);
+  dp = dn = dxf = dsk = 0;
+  for i = 1:length (lst)
+    nm = lst(i).name;
+    if (lst(i).isdir
+        && ! strcmp (nm, ".") && ! strcmp (nm, "..")
+        && ! strcmp (nm, "private") && nm(1) != "@"
+        && ! strcmp (nm, "CVS"))
+      [p, n, xf, sk] = run_test_dir (fid, [d, filesep, nm]);
+      dp += p;
+      dn += n;
+      dxf += xf;
+      dsk += sk;
+    endif
+  endfor
+  saved_dir = pwd ();
+  unwind_protect
+    chdir (d);
+    for i = 1:length (lst)
+      nm = lst(i).name;
+      if (length (nm) > 4 && strcmp (nm((end-3):end), ".tst"))
+        p = n = xf = sk = 0;
+        ffnm = fullfile (d, nm);
+        if (has_tests (ffnm))
+          print_test_file_name (nm);
+          [p, n, xf, sk] = test (nm, "quiet", fid);
+          print_pass_fail (n, p);
+          files_with_tests(end+1) = ffnm;
+        ##elseif (has_demos (ffnm))
+        ##  files_with_tests(end+1) = ffnm;
+        else
+          files_with_no_tests(end+1) = ffnm;
+        endif
+        dp += p;
+        dn += n;
+        dxf += xf;
+        dsk += sk;
+      endif
+    endfor
+  unwind_protect_cleanup
+    chdir (saved_dir);
+  end_unwind_protect
+endfunction
+
+function [dp, dn, dxf, dsk] = run_test_script (fid, d);
+  global files_with_tests;
+  global files_with_no_tests;
+  global topsrcdir;
+  global topbuilddir;
+  lst = dir (d);
+  dp = dn = dxf = dsk = 0;
+  for i = 1:length (lst)
+    nm = lst(i).name;
+    if (lst(i).isdir && ! strcmp (nm, ".") && ! strcmp (nm, "..")
+        && ! strcmp (nm, "CVS"))
+      [p, n, xf, sk] = run_test_script (fid, [d, filesep, nm]);
+      dp += p;
+      dn += n;
+      dxf += xf;
+      dsk += sk;
+    endif
+  endfor
+  for i = 1:length (lst)
+    nm = lst(i).name;
+    ## Ignore hidden files
+    if (nm(1) == '.')
+      continue
+    endif
+    f = fullfile (d, nm);
+    if ((length (nm) > 2 && strcmp (nm((end-1):end), ".m"))
+        || (length (nm) > 4
+            && (strcmp (nm((end-3):end), "-tst")
+                || strcmp (nm((end-3):end), ".tst"))))
+      p = n = xf = 0;
+      ## Only run if it contains %!test, %!assert %!error or %!warning
+      if (has_tests (f))
+        tmp = strrep (f, [topsrcdir, filesep], "");
+        tmp = strrep (tmp, [topbuilddir, filesep], "");
+        print_test_file_name (tmp);
+        [p, n, xf, sk] = test (f, "quiet", fid);
+        print_pass_fail (n, p);
+        dp += p;
+        dn += n;
+        dxf += xf;
+        dsk += sk;
+        files_with_tests(end+1) = f;
+      ##elseif (has_demos (f))
+      ##  files_with_tests(end+1) = f;
+      else
+        ## To reduce the list length, only mark .cc files that contain
+        ## DEFUN definitions.
+        files_with_no_tests(end+1) = f;
+      endif
+    endif
+  endfor 
+  ##  printf("%s%s -> passes %d of %d tests\n", ident, d, dp, dn);
+endfunction
+
+function n = num_elts_matching_pattern (lst, pat)
+  n = sum (cellfun (@(x) !isempty (x), regexp (lst, pat, 'once')));
+endfunction
+
+function report_files_with_no_tests (with, without, typ)
+  pat = cstrcat ('\', typ, "$");
+  n_with = num_elts_matching_pattern (with, pat);
+  n_without = num_elts_matching_pattern (without, pat);
+  n_tot = n_with + n_without;
+  printf ("\n%d (of %d) %s files have no tests.\n", n_without, n_tot, typ);
+endfunction
--- a/scripts/testfun/assert.m
+++ b/scripts/testfun/assert.m
@@ -43,10 +43,10 @@
 ## Produce an error if observed is not the same as expected but equality
 ## comparison for numeric data uses a tolerance @var{tol}.
 ## If @var{tol} is positive then it is an absolute tolerance which will produce
-## an error if @code{abs(@var{observed} - @var{expected}) > abs(@var{tol})}.
+## an error if @code{abs (@var{observed} - @var{expected}) > abs (@var{tol})}.
 ## If @var{tol} is negative then it is a relative tolerance which will produce
-## an error if @code{abs(@var{observed} - @var{expected}) >
-## abs(@var{tol} * @var{expected})}.  If @var{expected} is zero @var{tol} will
+## an error if @code{abs (@var{observed} - @var{expected}) >
+## abs (@var{tol} * @var{expected})}.  If @var{expected} is zero @var{tol} will
 ## always be interpreted as an absolute tolerance.
 ## @end table
 ## @seealso{test, fail, error}
@@ -249,9 +249,9 @@
 %!assert (isempty ([]))
 %!assert (1)
 %!error assert (0)
-%!assert (ones(3,1))
-%!assert (ones(1,3))
-%!assert (ones(3,4))
+%!assert (ones (3,1))
+%!assert (ones (1,3))
+%!assert (ones (3,4))
 %!error assert ([1,0,1])
 %!error assert ([1;1;0])
 %!error assert ([1,0;1,1])
--- a/scripts/testfun/demo.m
+++ b/scripts/testfun/demo.m
@@ -19,8 +19,8 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Command} {} demo @var{name}
 ## @deftypefnx {Command} {} demo @var{name} @var{n}
-## @deftypefnx {Function File} {} demo ('@var{name}')
-## @deftypefnx {Function File} {} demo ('@var{name}', @var{n})
+## @deftypefnx {Function File} {} demo ("@var{name}")
+## @deftypefnx {Function File} {} demo ("@var{name}", @var{n})
 ##
 ## Run example code block @var{n} associated with the function @var{name}.
 ## If @var{n} is not specified, all examples are run.
@@ -35,8 +35,9 @@
 ## @example
 ## @group
 ## %!demo
-## %! t=0:0.01:2*pi; x = sin (t);
-## %! plot (t,x)
+## %! t = 0:0.01:2*pi;
+## %! x = sin (t);
+## %! plot (t, x);
 ## %! %-------------------------------------------------
 ## %! % the figure window shows one cycle of a sine wave
 ## @end group
@@ -64,7 +65,7 @@
 ## Also, because demo evaluates within a function context, you cannot
 ## define new functions inside a demo.  If you must have function blocks,
 ## rather than just anonymous functions or inline functions, you will have to
-## use @code{eval(example('function',n))} to see them.  Because eval only
+## use @code{eval (example ("function",n))} to see them.  Because eval only
 ## evaluates one line, or one statement if the statement crosses
 ## multiple lines, you must wrap your demo in "if 1 <demo stuff> endif"
 ## with the 'if' on the same line as 'demo'.  For example:
@@ -100,7 +101,11 @@
   endif
 
   [code, idx] = test (name, "grabdemo");
-  if (isempty (idx))
+
+  if (idx == -1)
+    warning ("no function %s found", name);
+    return;
+  elseif (isempty (idx))
     warning ("no demo available for %s", name);
     return;
   elseif (n >= length (idx))
@@ -111,7 +116,7 @@
   if (n > 0)
     doidx = n;
   else
-    doidx = 1:length(idx)-1;
+    doidx = 1:(length (idx) - 1);
   endif
   for i = 1:length (doidx)
     ## Pause between demos
@@ -122,19 +127,11 @@
     ## Process each demo without failing
     try
       block = code(idx(doidx(i)):idx(doidx(i)+1)-1);
-      ## FIXME: need to check for embedded test functions, which cause
-      ## segfaults, until issues with subfunctions in functions are resolved.
-      embed_func = regexp (block, '^\s*function ', 'once', 'lineanchors');
-      if (isempty (embed_func))
-        ## Use an environment without variables
-        eval (cstrcat ("function __demo__()\n", block, "\nendfunction"));
-        ## Display the code that will be executed before executing it
-        printf ("%s example %d:%s\n\n", name, doidx(i), block);
-        __demo__;
-      else
-        error (["Functions embedded in %!demo blocks are not allowed.\n", ...
-                "Use the %!function/%!endfunction syntax instead to define shared functions for testing.\n"]);
-      endif
+      ## Use an environment without variables
+      eval (cstrcat ("function __demo__ ()\n", block, "\nendfunction"));
+      ## Display the code that will be executed before executing it
+      printf ("%s example %d:%s\n\n", name, doidx(i), block);
+      __demo__;
     catch
       ## Let the programmer know which demo failed.
       printf ("%s example %d: failed\n%s\n", name, doidx(i), lasterr ());
@@ -144,11 +141,14 @@
 
 endfunction
 
+
 %!demo
-%! t=0:0.01:2*pi; x = sin(t);
-%! plot (t,x)
+%! t = 0:0.01:2*pi;
+%! x = sin (t);
+%! plot (t, x);
 %! %-------------------------------------------------
 %! % the figure window shows one cycle of a sine wave
 
-%!error demo ();
-%!error demo (1, 2, 3);
+%!error demo ()
+%!error demo (1, 2, 3)
+
--- a/scripts/testfun/example.m
+++ b/scripts/testfun/example.m
@@ -19,12 +19,12 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Command} {} example @var{name}
 ## @deftypefnx {Command} {} example @var{name} @var{n}
-## @deftypefnx {Function File} {} example ('@var{name}')
-## @deftypefnx {Function File} {} example ('@var{name}', @var{n})
+## @deftypefnx {Function File} {} example ("@var{name}")
+## @deftypefnx {Function File} {} example ("@var{name}", @var{n})
 ## @deftypefnx {Function File} {[@var{s}, @var{idx}] =} example (@dots{})
 ##
 ## Display the code for example @var{n} associated with the function
-## '@var{name}', but do not run it.  If @var{n} is not specified, all examples
+## "@var{name}", but do not run it.  If @var{n} is not specified, all examples
 ## are displayed.
 ##
 ## When called with output arguments, the examples are returned in the form of
@@ -65,13 +65,13 @@
     if (n > 0)
       doidx = n;
     else
-      doidx = 1:length(idx)-1;
+      doidx = 1:length (idx) - 1;
     endif
     if (isempty (idx))
       warning ("no example available for %s", name);
       return;
-    elseif (n >= length(idx))
-      warning ("only %d examples available for %s", length(idx)-1, name);
+    elseif (n >= length (idx))
+      warning ("only %d examples available for %s", length (idx) - 1, name);
       return;
     endif
 
@@ -84,21 +84,23 @@
 endfunction
 
 
-%!## warning: don't modify the demos without modifying the tests!
+## WARNING: don't modify the demos without modifying the tests!
 %!demo
-%! example ('example');
+%! example ("example");
+
 %!demo
-%! t=0:0.01:2*pi; x = sin(t);
+%! clf;
+%! t = 0:0.01:2*pi;  x = sin (t);
 %! plot (t,x)
 
-%!assert (example('example',1), "\n example ('example');");
+%!assert (example ("example",1), "\n example (\"example\");");
 %!test
-%! [code, idx] = example ('example');
+%! [code, idx] = example ("example");
 %! assert (code, ...
-%!         "\n example ('example');\n t=0:0.01:2*pi; x = sin(t);\n plot (t,x)")
-%! assert (idx, [1, 23, 63]);
+%!         "\n example (\"example\");\n clf;\n t = 0:0.01:2*pi;  x = sin (t);\n plot (t,x)")
+%! assert (idx, [1, 23, 73]);
 
 %% Test input validation
 %!error example
-%!error example ('example', 3, 5)
+%!error example ("example", 3, 5)
 
--- a/scripts/testfun/fail.m
+++ b/scripts/testfun/fail.m
@@ -22,7 +22,7 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {} fail (@var{code})
 ## @deftypefnx {Function File} {} fail (@var{code}, @var{pattern})
-## @deftypefnx {Function File} {} fail (@var{code}, 'warning', @var{pattern})
+## @deftypefnx {Function File} {} fail (@var{code}, "warning", @var{pattern})
 ##
 ## Return true if @var{code} fails with an error message matching
 ## @var{pattern}, otherwise produce an error.  Note that @var{code}
@@ -53,7 +53,7 @@
 ## The angle brackets are not part of the output.
 ##
 ## Called with three arguments, the behavior is similar to
-## @code{fail(@var{code}, @var{pattern})}, but produces an error if no
+## @code{fail (@var{code}, @var{pattern})}, but produces an error if no
 ## warning is given during code execution or if the code fails.
 ## @seealso{assert}
 ## @end deftypefn
@@ -79,7 +79,7 @@
     pattern = ".";
   endif
 
-  ## allow assert(fail())
+  ## allow assert (fail ())
   if (nargout)
     ret = 1;
   endif
@@ -92,9 +92,9 @@
     state = warning ("query", "quiet");
     warning ("on", "quiet");
     try
-      ## printf("lastwarn before %s: %s\n",code,lastwarn);
+      ## printf ("lastwarn before %s: %s\n",code,lastwarn);
       evalin ("caller", sprintf ("%s;", code));
-      ## printf("lastwarn after %s: %s\n",code,lastwarn);
+      ## printf ("lastwarn after %s: %s\n",code,lastwarn);
       ## Retrieve new warnings.
       err = lastwarn ();
       warning (state.state, "quiet");
@@ -139,15 +139,16 @@
 endfunction
 
 
-%!fail ('[1,2]*[2,3]', 'nonconformant')
-%!fail ("fail('[1,2]*[2;3]', 'nonconformant')", "expected error <nonconformant> but got none")
-%!fail ("fail('[1,2]*[2,3]','usage:')", "expected error <usage:>\nbut got.*nonconformant")
-%!fail ("warning('test warning')", 'warning','test warning');
+%!fail ("[1,2]*[2,3]", "nonconformant")
+%!fail ("fail ('[1,2]*[2;3]', 'nonconformant')", "expected error <nonconformant> but got none")
+%!fail ("fail ('[1,2]*[2,3]', 'usage:')", "expected error <usage:>\nbut got.*nonconformant")
+%!fail ("warning ('test warning')", "warning", "test warning");
 
-##% !fail ("warning('next test')",'warning','next test');  ## only allowed one warning test?!?
+##% !fail ("warning ('next test')",'warning','next test');  ## only allowed one warning test?!?
 
 %% Test that fail() itself will generate an error
-%!error fail ("1");
-%!error <undefined> fail ('a*[2;3]', 'nonconformant')
-%!error <expected error>  fail ('a*[2,3]', 'usage:')
-%!error <warning failure> fail ("warning('warning failure')", 'warning', 'success')
+%!error fail ("1")
+%!error <undefined> fail ("a*[2;3]", "nonconformant")
+%!error <expected error>  fail ("a*[2,3]", "usage:")
+%!error <warning failure> fail ("warning ('warning failure')", "warning", "success")
+
--- a/scripts/testfun/module.mk
+++ b/scripts/testfun/module.mk
@@ -1,6 +1,10 @@
 FCN_FILE_DIRS += testfun
 
 testfun_FCN_FILES = \
+  testfun/__have_feature__.m \
+  testfun/__printf_assert__.m \
+  testfun/__prog_output_assert__.m \
+  testfun/__run_test_suite__.m \
   testfun/assert.m \
   testfun/demo.m \
   testfun/example.m \
--- a/scripts/testfun/rundemos.m
+++ b/scripts/testfun/rundemos.m
@@ -30,7 +30,7 @@
 function rundemos (directory)
 
   if (nargin == 0)
-    dirs = strsplit (path (), pathsep ());
+    dirs = strsplit (path (), pathsep (), false);
   elseif (nargin == 1)
     if (is_absolute_filename (directory))
       dirs = {directory};
@@ -65,7 +65,7 @@
         try
           demo (f);
         catch
-          printf ("error: %s\n\n", lasterror().message)
+          printf ("error: %s\n\n", lasterror().message);
         end_try_catch
         if (i != numel (flist))
           input ("Press <enter> to continue: ", "s");
@@ -82,8 +82,11 @@
   else
     str = fscanf (fid, "%s");
     fclose (fid);
-    retval = findstr (str, "%!demo");
+    retval = strfind (str, "%!demo");
   endif
 endfunction
 
-%!error rundemos ("foo", 1);
+
+%!error rundemos ("foo", 1)
+%!error <DIRECTORY argument> rundemos ("#_TOTALLY_/_INVALID_/_PATHNAME_#")
+
--- a/scripts/testfun/runtests.m
+++ b/scripts/testfun/runtests.m
@@ -30,7 +30,7 @@
 function runtests (directory)
 
   if (nargin == 0)
-    dirs = strsplit (path (), pathsep ());
+    dirs = strsplit (path (), pathsep (), false);
   elseif (nargin == 1)
     if (is_absolute_filename (directory))
       dirs = {directory};
--- a/scripts/testfun/speed.m
+++ b/scripts/testfun/speed.m
@@ -323,13 +323,13 @@
     endif
     v = polyval (p, log (__test_n(tailidx)));
 
-    loglog (__test_n(tailidx), exp(v)*1000, sprintf ("b;%s;", order));
+    loglog (__test_n(tailidx), exp (v) * 1000, sprintf ("b;%s;", order));
     title ({"Time Complexity", __f1});
     xlabel ("test length");
 
     ## Get base time to 1 digit of accuracy.
     dt = exp (p(2));
-    dt = floor (dt/10^floor(log10(dt)))*10^floor(log10(dt));
+    dt = floor (dt/10^floor (log10 (dt)))*10^floor (log10 (dt));
     if (log10 (dt) >= -0.5)
       time = sprintf ("%g s", dt);
     elseif (log10 (dt) >= -3.5)
@@ -356,62 +356,63 @@
 %%        Unfortunately, we can't remove them from the user's workspace
 %%        because of another bug (#34497).
 %!demo
-%!  fstr_build_orig = cstrcat (
-%!  "function x = build_orig (n)\n",
-%!  "  ## extend the target vector on the fly\n",
-%!  "  for i=0:n-1, x([1:100]+i*100) = 1:100; endfor\n",
-%!  "endfunction");
-%!  fstr_build = cstrcat (
-%!  "function x = build (n)\n",
-%!  "  ## preallocate the target vector\n",
-%!  "  x = zeros (1, n*100);\n",
-%!  "  for i=0:n-1, x([1:100]+i*100) = 1:100; endfor\n",
-%!  "endfunction");
+%! fstr_build_orig = cstrcat (
+%!   "function x = build_orig (n)\n",
+%!   "  ## extend the target vector on the fly\n",
+%!   "  for i=0:n-1, x([1:100]+i*100) = 1:100; endfor\n",
+%!   "endfunction");
+%! fstr_build = cstrcat (
+%!   "function x = build (n)\n",
+%!   "  ## preallocate the target vector\n",
+%!   "  x = zeros (1, n*100);\n",
+%!   "  for i=0:n-1, x([1:100]+i*100) = 1:100; endfor\n",
+%!   "endfunction");
 %!
-%!  disp ("-----------------------");
-%!  disp (fstr_build_orig);
-%!  disp ("-----------------------");
-%!  disp (fstr_build);
-%!  disp ("-----------------------");
+%! disp ("-----------------------");
+%! disp (fstr_build_orig);
+%! disp ("-----------------------");
+%! disp (fstr_build);
+%! disp ("-----------------------");
 %!
-%!  ## Eval functions strings to create them in the current context
-%!  eval (fstr_build_orig);
-%!  eval (fstr_build);
+%! ## Eval functions strings to create them in the current context
+%! eval (fstr_build_orig);
+%! eval (fstr_build);
 %!
-%!  disp ("Preallocated vector test.\nThis takes a little while...");
-%!  speed("build (n)", "", 1000, "build_orig (n)");
-%!  clear -f build build_orig
-%!  disp ("Note how much faster it is to pre-allocate a vector.");
-%!  disp ("Notice the peak speedup ratio.");
+%! disp ("Preallocated vector test.\nThis takes a little while...");
+%! speed ("build (n)", "", 1000, "build_orig (n)");
+%! clear -f build build_orig
+%! disp ("-----------------------");
+%! disp ("Note how much faster it is to pre-allocate a vector.");
+%! disp ("Notice the peak speedup ratio.");
 
 %!demo
-%!  fstr_build_orig = cstrcat (
-%!  "function x = build_orig (n)\n",
-%!  "  for i=0:n-1, x([1:100]+i*100) = 1:100; endfor\n",
-%!  "endfunction");
-%!  fstr_build = cstrcat (
-%!  "function x = build (n)\n",
-%!  "  idx = [1:100]';\n",
-%!  "  x = idx(:,ones(1,n));\n",
-%!  "  x = reshape (x, 1, n*100);\n",
-%!  "endfunction");
+%! fstr_build_orig = cstrcat (
+%!   "function x = build_orig (n)\n",
+%!   "  for i=0:n-1, x([1:100]+i*100) = 1:100; endfor\n",
+%!   "endfunction");
+%! fstr_build = cstrcat (
+%!   "function x = build (n)\n",
+%!   "  idx = [1:100]';\n",
+%!   "  x = idx(:,ones(1,n));\n",
+%!   "  x = reshape (x, 1, n*100);\n",
+%!   "endfunction");
 %!
-%!  disp ("-----------------------");
-%!  disp (fstr_build_orig);
-%!  disp ("-----------------------");
-%!  disp (fstr_build);
-%!  disp ("-----------------------");
+%! disp ("-----------------------");
+%! disp (fstr_build_orig);
+%! disp ("-----------------------");
+%! disp (fstr_build);
+%! disp ("-----------------------");
 %!
-%!  ## Eval functions strings to create them in the current context
-%!  eval (fstr_build_orig);
-%!  eval (fstr_build);
+%! ## Eval functions strings to create them in the current context
+%! eval (fstr_build_orig);
+%! eval (fstr_build);
 %!
-%!  disp ("Vectorized test.\nThis takes a little while...");
-%!  speed("build (n)", "", 1000, "build_orig (n)");
-%!  clear -f build build_orig
-%!  disp ("-----------------------");
-%!  disp ("This time, the for loop is done away with entirely.");
-%!  disp ("Notice how much bigger the speedup is than in example 1.");
+%! disp ("Vectorized test.\nThis takes a little while...");
+%! speed ("build (n)", "", 1000, "build_orig (n)");
+%! clear -f build build_orig
+%! disp ("-----------------------");
+%! disp ("This time, the for loop is done away with entirely.");
+%! disp ("Notice how much bigger the speedup is than in example 1.");
 
 %!test
 %! [order, n, T_f1, T_f2] = speed ("airy (x)", "x = rand (n, 10)", [100, 1000]);
@@ -425,7 +426,8 @@
 %! assert (isnumeric (T_f2));
 %! assert (length (T_f2) > 10);
 
-%% This test is known to fail on operating systems with low resolution timers such as MinGW
+%% This test is known to fail on operating systems with low resolution timers
+%% such as MinGW
 %!xtest
 %! [order, n, T_f1, T_f2] = speed ("sum (x)", "", [100, 1000], "v = 0; for i = 1:length (x), v += x(i); endfor");
 %! assert (isstruct (order));
@@ -439,6 +441,6 @@
 %! assert (length (T_f2) > 10);
 
 %% Test input validation
-%!error speed ();
-%!error speed (1, 2, 3, 4, 5, 6, 7);
+%!error speed ()
+%!error speed (1, 2, 3, 4, 5, 6, 7)
 
--- a/scripts/testfun/test.m
+++ b/scripts/testfun/test.m
@@ -19,11 +19,11 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Command} {} test @var{name}
 ## @deftypefnx {Command} {} test @var{name} quiet|normal|verbose
-## @deftypefnx {Function File} {} test ('@var{name}', 'quiet|normal|verbose', @var{fid})
-## @deftypefnx {Function File} {} test ([], 'explain', @var{fid})
+## @deftypefnx {Function File} {} test ("@var{name}", "quiet|normal|verbose", @var{fid})
+## @deftypefnx {Function File} {} test ([], "explain", @var{fid})
 ## @deftypefnx {Function File} {@var{success} =} test (@dots{})
 ## @deftypefnx {Function File} {[@var{n}, @var{max}] =} test (@dots{})
-## @deftypefnx {Function File} {[@var{code}, @var{idx}] =} test ('@var{name}', 'grabdemo')
+## @deftypefnx {Function File} {[@var{code}, @var{idx}] =} test ("@var{name}", "grabdemo")
 ##
 ## Perform tests from the first file in the loadpath matching @var{name}.
 ## @code{test} can be called as a command or as a function.  Called with
@@ -34,14 +34,14 @@
 ## output is selected.
 ##
 ## @table @asis
-## @item 'quiet'
+## @item "quiet"
 ##  Don't report all the tests as they happen, just the errors.
 ##
-## @item 'normal'
+## @item "normal"
 ## Report all tests as they happen, but don't do tests which require
 ## user interaction.
 ##
-## @item 'verbose'
+## @item "verbose"
 ## Do tests which require user interaction.
 ## @end table
 ##
@@ -58,12 +58,12 @@
 ## @var{n} and @var{max}, the number of successful tests and the total number
 ## of tests in the file @var{name} are returned.
 ##
-## If the second argument is the string 'grabdemo', the contents of the demo
+## If the second argument is the string "grabdemo", the contents of the demo
 ## blocks are extracted but not executed.  Code for all code blocks is
 ## concatenated and returned as @var{code} with @var{idx} being a vector of
 ## positions of the ends of the demo blocks.
 ##
-## If the second argument is 'explain', then @var{name} is ignored and an
+## If the second argument is "explain", then @var{name} is ignored and an
 ## explanation of the line markers used is written to the file @var{fid}.
 ## @seealso{assert, fail, error, demo, example}
 ## @end deftypefn
@@ -145,7 +145,7 @@
     fprintf (__fid, "# success (in which case no error will be reported).\n");
     fflush (__fid);
     if (__close_fid)
-      fclose(__fid);
+      fclose (__fid);
     endif
     return;
   else
@@ -171,10 +171,17 @@
   if (isempty (__file))
     if (__grabdemo)
       __ret1 = "";
-      __ret2 = [];
+      __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
@@ -184,7 +191,7 @@
       endif
     endif
     if (__close_fid)
-      fclose(__fid);
+      fclose (__fid);
     endif
     return;
   endif
@@ -204,12 +211,12 @@
       endif
     endif
     if (__close_fid)
-      fclose(__fid);
+      fclose (__fid);
     endif
     return;
   else
     ## Add a dummy comment block to the end for ease of indexing.
-    if (__body (length(__body)) == "\n")
+    if (__body (length (__body)) == "\n")
       __body = sprintf ("\n%s#", __body);
     else
       __body = sprintf ("\n%s\n#", __body);
@@ -233,7 +240,7 @@
   __shared = " ";
   __shared_r = " ";
   __clear = "";
-  for __i = 1:length(__blockidx)-1
+  for __i = 1:length (__blockidx)-1
 
     ## Extract the block.
     __block = __body(__blockidx(__i):__blockidx(__i+1)-2);
@@ -251,7 +258,7 @@
       __code = "";
     else
       __type = __block(1:__idx(1)-1);
-      __code = __block(__idx(1):length(__block));
+      __code = __block(__idx(1):length (__block));
     endif
 
     ## Assume the block will succeed.
@@ -270,18 +277,18 @@
       __istest = 0;
 
       if (__grabdemo && __isdemo)
-        if (isempty(__demo_code))
+        if (isempty (__demo_code))
           __demo_code = __code;
           __demo_idx = [1, length(__demo_code)+1];
         else
-          __demo_code = cstrcat(__demo_code, __code);
+          __demo_code = cstrcat (__demo_code, __code);
           __demo_idx = [__demo_idx, length(__demo_code)+1];
         endif
 
       elseif (__rundemo && __isdemo)
         try
           ## process the code in an environment without variables
-          eval (sprintf ("function __test__()\n%s\nendfunction", __code));
+          eval (sprintf ("function __test__ ()\n%s\nendfunction", __code));
           __test__;
           input ("Press <enter> to continue: ", "s");
         catch
@@ -306,7 +313,7 @@
         __code = "";
       else
         __vars = __code (1:__idx(1)-1);
-        __code = __code (__idx(1):length(__code));
+        __code = __code (__idx(1):length (__code));
       endif
 
       ## Strip comments off the variables.
@@ -334,10 +341,6 @@
                          __signal_fail);
       end_try_catch
 
-      ## Clear shared function definitions.
-      eval (__clear, "");
-      __clear = "";
-
       ## Initialization code will be evaluated below.
 
 ### FUNCTION
@@ -354,7 +357,7 @@
         __name = __block(__name_position(1):__name_position(2));
         __code = __block;
         try
-          eval(__code); ## Define the function
+          eval (__code); ## Define the function
           __clear = sprintf ("%sclear %s;\n", __clear, __name);
         catch
           __success = 0;
@@ -382,7 +385,7 @@
 
 ### ERROR/WARNING
 
-    elseif (strcmp (__type, "error") || strcmp(__type, "warning"))
+    elseif (strcmp (__type, "error") || strcmp (__type, "warning"))
       __istest = 1;
       __warning = strcmp (__type, "warning");
       [__pattern, __id, __code] = getpattern (__code);
@@ -460,15 +463,16 @@
       ## Strip comment any comment from testif line before looking for features
       __feat_line = strtok (__code(1:__e), '#%'); 
       __feat = regexp (__feat_line, '\w+', 'match');
-      __have_feat = strfind (octave_config_info ("DEFS"), __feat); 
-      if (any (cellfun ("isempty", __have_feat)))
+      __feat = strrep (__feat, "HAVE_", "");
+      __have_feat = __have_feature__ (__feat);
+      if (__have_feat)
+        __istest = 1;
+        __code = __code(__e + 1 : end);
+      else
         __xskip++;
         __istest = 0;
         __code = ""; # Skip the code.
         __msg = sprintf ("%sskipped test\n", __signal_skip);
-      else
-        __istest = 1;
-        __code = __code(__e + 1 : end);
       endif
 
 ### TEST
@@ -547,7 +551,7 @@
           __ret1 = __ret2 = 0;
         endif
         if (__close_fid)
-          fclose(__fid);
+          fclose (__fid);
         endif
         return;
       endif
@@ -555,6 +559,7 @@
     __tests += __istest;
     __successes += __success * __istest;
   endfor
+  ## Clear any test functions created
   eval (__clear, "");
 
   if (nargout == 0)
@@ -644,7 +649,7 @@
 ## Strip leading blanks from string.
 function str = trimleft (str)
   idx = find (isspace (str));
-  leading = find (idx == 1:length(idx));
+  leading = find (idx == 1:length (idx));
   if (! isempty (leading))
     str = str(leading(end)+1:end);
   endif
@@ -666,7 +671,7 @@
       ln = fgetl (fid);
       if (length (ln) >= 2 && strcmp (ln(1:2), "%!"))
         body = [body, "\n"];
-        if (length(ln) > 2)
+        if (length (ln) > 2)
           body = cstrcat (body, ln(3:end));
         endif
       endif
@@ -675,37 +680,24 @@
   endif
 endfunction
 
-### Test for test for missing features
-%!testif OCTAVE_SOURCE
-%! ## This test should be run
-%! assert (true);
-
-### Disable this test to avoid spurious skipped test for "make check"
-% !testif HAVE_FOOBAR
-% ! ## missing feature. Fail if this test is run
-% ! error("Failed missing feature test");
-
-### Test for a known failure
-%!xtest error("This test is known to fail")
-
 ### example from toeplitz
 %!shared msg1,msg2
 %! msg1="C must be a vector";
 %! msg2="C and R must be vectors";
-%!fail ('toeplitz([])', msg1);
-%!fail ('toeplitz([1,2;3,4])', msg1);
-%!fail ('toeplitz([1,2],[])', msg2);
-%!fail ('toeplitz([1,2],[1,2;3,4])', msg2);
+%!fail ('toeplitz ([])', msg1);
+%!fail ('toeplitz ([1,2;3,4])', msg1);
+%!fail ('toeplitz ([1,2],[])', msg2);
+%!fail ('toeplitz ([1,2],[1,2;3,4])', msg2);
 %!fail ('toeplitz ([1,2;3,4],[1,2])', msg2);
 % !fail ('toeplitz','usage: toeplitz'); # usage doesn't generate an error
-% !fail ('toeplitz(1, 2, 3)', 'usage: toeplitz');
+% !fail ('toeplitz (1, 2, 3)', 'usage: toeplitz');
 %!test  assert (toeplitz ([1,2,3], [1,4]), [1,4; 2,1; 3,2]);
 %!demo  toeplitz ([1,2,3,4],[1,5,6])
 
 ### example from kron
 %!#error kron  # FIXME suppress these until we can handle output
 %!#error kron(1,2,3)
-%!test assert (isempty (kron ([], rand(3, 4))))
+%!test assert (isempty (kron ([], rand (3, 4))))
 %!test assert (isempty (kron (rand (3, 4), [])))
 %!test assert (isempty (kron ([], [])))
 %!shared A, B
@@ -729,16 +721,16 @@
 ### an extended demo from specgram
 %!#demo
 %! ## Speech spectrogram
-%! [x, Fs] = auload(file_in_loadpath("sample.wav")); # audio file
-%! step = fix(5*Fs/1000);     # one spectral slice every 5 ms
-%! window = fix(40*Fs/1000);  # 40 ms data window
-%! fftn = 2^nextpow2(window); # next highest power of 2
-%! [S, f, t] = specgram(x, fftn, Fs, window, window-step);
-%! S = abs(S(2:fftn*4000/Fs,:)); # magnitude in range 0<f<=4000 Hz.
-%! S = S/max(max(S));         # normalize magnitude so that max is 0 dB.
-%! S = max(S, 10^(-40/10));   # clip below -40 dB.
-%! S = min(S, 10^(-3/10));    # clip above -3 dB.
-%! imagesc(flipud(20*log10(S)), 1);
+%! [x, Fs] = auload (file_in_loadpath ("sample.wav")); # audio file
+%! step = fix (5*Fs/1000);     # one spectral slice every 5 ms
+%! window = fix (40*Fs/1000);  # 40 ms data window
+%! fftn = 2^nextpow2 (window); # next highest power of 2
+%! [S, f, t] = specgram (x, fftn, Fs, window, window-step);
+%! S = abs (S (2:fftn*4000/Fs,:)); # magnitude in range 0<f<=4000 Hz.
+%! S = S/max(max(S));          # normalize magnitude so that max is 0 dB.
+%! S = max (S, 10^(-40/10));   # clip below -40 dB.
+%! S = min (S, 10^(-3/10));    # clip above -3 dB.
+%! imagesc (flipud (20*log10 (S)), 1);
 %! % you should now see a spectrogram in the image window
 
 
@@ -746,74 +738,74 @@
 
 %!## usage and error testing
 % !fail ('test','usage.*test')           # no args, generates usage()
-% !fail ('test(1,2,3,4)','usage.*test')  # too many args, generates usage()
-%!fail ('test("test", "bogus")','unknown flag')      # incorrect args
+% !fail ('test (1,2,3,4)','usage.*test') # too many args, generates usage()
+%!fail ('test ("test", "bogus")','unknown flag')  # incorrect args
 %!fail ('garbage','garbage.*undefined')  # usage on nonexistent function should be
 
 %!error test                     # no args, generates usage()
-%!error test(1,2,3,4)            # too many args, generates usage()
-%!error <unknown flag> test("test", 'bogus');  # incorrect args, generates error()
+%!error test (1,2,3,4)           # too many args, generates usage()
+%!error <unknown flag> test ("test", 'bogus'); # incorrect args, generates error()
 %!error <garbage' undefined> garbage           # usage on nonexistent function should be
 
-%!error test("test", 'bogus');           # test without pattern
+%!error test ("test", 'bogus');  # test without pattern
 
 %!test
 %! lastwarn();            # clear last warning just in case
 
-%!warning <warning message> warning('warning message');
+%!warning <warning message> warning ('warning message');
 
 %!## test of shared variables
 %!shared a                # create a shared variable
 %!test   a=3;             # assign to a shared variable
-%!test   assert(a,3)      # variable should equal 3
+%!test   assert (a,3)     # variable should equal 3
 %!shared b,c              # replace shared variables
-%!test assert (!exist("a"));   # a no longer exists
-%!test assert (isempty(b));    # variables start off empty
+%!test assert (!exist ("a", "var"));  # a no longer exists
+%!test assert (isempty (b));   # variables start off empty
 %!shared a,b,c            # recreate a shared variable
-%!test assert (isempty(a));    # value is empty even if it had a previous value
+%!test assert (isempty (a));   # value is empty even if it had a previous value
 %!test a=1; b=2; c=3;   # give values to all variables
 %!test assert ([a,b,c],[1,2,3]); # test all of them together
 %!test c=6;             # update a value
-%!test assert([a, b, c],[1, 2, 6]); # show that the update sticks
-%!shared                    # clear all shared variables
-%!test assert(!exist("a"))  # show that they are cleared
-%!shared a,b,c              # support for initializer shorthand
+%!test assert ([a, b, c],[1, 2, 6]); # show that the update sticks
+%!shared                     # clear all shared variables
+%!test assert (!exist ("a", "var")) # show that they are cleared
+%!shared a,b,c               # support for initializer shorthand
 %! a=1; b=2; c=4;
 
-%!function x = __test_a(y)
+%!function x = __test_a (y)
 %! x = 2*y;
 %!endfunction
-%!assert(__test_a(2),4);       # Test a test function
+%!assert (__test_a (2),4);       # Test a test function
 
 %!function __test_a (y)
 %! x = 2*y;
 %!endfunction
 %!test
-%! __test_a(2);                # Test a test function with no return value
+%! __test_a (2);                # Test a test function with no return value
 
 %!function [x,z] = __test_a (y)
 %! x = 2*y;
 %! z = 3*y;
 %!endfunction
 %!test                   # Test a test function with multiple returns
-%! [x,z] = __test_a(3);
-%! assert(x,6);
-%! assert(z,9);
+%! [x,z] = __test_a (3);
+%! assert (x,6);
+%! assert (z,9);
 
 %!## test of assert block
-%!assert (isempty([]))      # support for test assert shorthand
+%!assert (isempty ([]))      # support for test assert shorthand
 
 %!## demo blocks
 %!demo                   # multiline demo block
-%! t=[0:0.01:2*pi]; x=sin(t);
-%! plot(t,x);
+%! t = [0:0.01:2*pi]; x = sin (t);
+%! plot (t,x);
 %! % you should now see a sine wave in your figure window
 %!demo a=3               # single line demo blocks work too
 
 %!## this is a comment block. it can contain anything.
 %!##
 %! it is the "#" as the block type that makes it a comment
-%! and it  stays as a comment even through continuation lines
+%! and it stays as a comment even through continuation lines
 %! which means that it works well with commenting out whole tests
 
 % !# failure tests.  All the following should fail. These tests should
@@ -831,10 +823,11 @@
 % !demo   with syntax error  # syntax errors in demo fail properly
 % !shared a,b,c
 % !demo                      # shared variables not available in demo
-% ! assert(exist("a"))
+% ! assert(exist("a", "var"))
 % !error
 % ! test('/etc/passwd');
 % ! test("nonexistent file");
 % ! ## These don't signal an error, so the test for an error fails. Note
 % ! ## that the call doesn't reference the current fid (it is unavailable),
 % ! ## so of course the informational message is not printed in the log.
+
--- a/scripts/time/addtodate.m
+++ b/scripts/time/addtodate.m
@@ -77,7 +77,7 @@
 
 ## tests
 %!shared d
-%!  d = datenum (2008, 1, 1);
+%! d = datenum (2008, 1, 1);
 ## Identity
 %!assert (addtodate (d, 0, "year"), d)
 %!assert (addtodate (d, 0, "month"), d)
--- a/scripts/time/asctime.m
+++ b/scripts/time/asctime.m
@@ -47,8 +47,8 @@
 
 %!test
 %! t = time ();
-%! assert(strcmp (asctime (localtime (t)), ctime (t)));
+%! assert (strcmp (asctime (localtime (t)), ctime (t)));
 
-%!error asctime ();
-%!error asctime (1, 2);
+%!error asctime ()
+%!error asctime (1, 2)
 
--- a/scripts/time/calendar.m
+++ b/scripts/time/calendar.m
@@ -88,14 +88,14 @@
 endfunction
 
 
-## demos
 %!demo
 %! ## Calendar for current month
 %! calendar ()
+
 %!demo
+%! ## Calendar for October, 1957
 %! calendar (1957, 10)
 
-## tests
 %!assert ((calendar(2000,2))'(2:31), [0:29])
 %!assert ((calendar(1957,10))'(2:33), [0:31])
 
--- a/scripts/time/clock.m
+++ b/scripts/time/clock.m
@@ -57,5 +57,5 @@
 %!test
 %! t1 = clock;
 %! t2 = str2num (strftime ("[%Y, %m, %d, %H, %M, %S]", localtime (time ())));
-%! assert(etime (t1, t2) < 1);
+%! assert (etime (t1, t2) < 1);
 
--- a/scripts/time/ctime.m
+++ b/scripts/time/ctime.m
@@ -47,8 +47,8 @@
 
 %!test
 %! t = time ();
-%! assert(strcmp (asctime (localtime (t)), ctime (t)));
+%! assert (strcmp (asctime (localtime (t)), ctime (t)));
 
-%!error ctime ();
-%!error ctime (1, 2);
+%!error ctime ()
+%!error ctime (1, 2)
 
--- a/scripts/time/date.m
+++ b/scripts/time/date.m
@@ -39,5 +39,6 @@
 
 endfunction
 
-%!assert(strcmp (date (), strftime ("%d-%b-%Y", localtime (time ()))));
 
+%!assert (strcmp (date (), strftime ("%d-%b-%Y", localtime (time ()))))
+
--- a/scripts/time/datenum.m
+++ b/scripts/time/datenum.m
@@ -67,7 +67,7 @@
 ## @end itemize
 ##
 ## @strong{Caution:} this function does not attempt to handle Julian
-## calendars so dates before Octave 15, 1582 are wrong by as much
+## calendars so dates before October 15, 1582 are wrong by as much
 ## as eleven days.  Also, be aware that only Roman Catholic countries
 ## adopted the calendar in 1582.  It took until 1924 for it to be
 ## adopted everywhere.  See the Wikipedia entry on the Gregorian
@@ -85,6 +85,7 @@
 
   ## Days until start of month assuming year starts March 1.
   persistent monthstart = [306; 337; 0; 31; 61; 92; 122; 153; 184; 214; 245; 275];
+  persistent monthlength = [31; 28; 31; 30; 31; 30; 31; 31; 30; 31; 30; 31];
 
   if (nargin == 0 || nargin > 6 || 
      (nargin > 2 && (ischar (year) || iscellstr (year))))
@@ -108,7 +109,25 @@
     endif
   endif
 
-  month(month<1) = 1; ## For compatibility.  Otherwise allow negative months.
+  if (! (isa (year, "double") && isa (month, "double") && isa (day, "double") &&
+         isa (hour, "double") && isa (minute, "double") && isa (second, "double")))
+    error ("datenum: all inputs must be of class double");
+  endif
+
+  month(month<1) = 1;  # For compatibility.  Otherwise allow negative months.
+
+  ## Treat fractional months, by converting the fraction to days
+  if (floor (month) != month)
+    fracmonth = month - floor (month);
+    month = floor (month);
+    if ((mod (month-1,12) + 1) == 2 && 
+        (floor (year/4) - floor (year/100) + floor (year/400)) != 0)
+      ## leap year
+      day += fracmonth * 29;
+    else
+      day += fracmonth * monthlength ((mod (month-1,12) + 1));
+    endif
+  endif
 
   ## Set start of year to March by moving Jan. and Feb. to previous year.
   ## Correct for months > 12 by moving to subsequent years.
@@ -159,19 +178,19 @@
 %! assert (datenum (t(1,:), t(2,:), t(3,:), t(4,:), t(5,:), t(6,:)), n, 2*eps);
 
 ## Test mixed vectors and scalars
-%!assert (datenum([2008;2009], 1, 1), [datenum(2008, 1, 1);datenum(2009, 1, 1)]);
-%!assert (datenum(2008, [1;2], 1), [datenum(2008, 1, 1);datenum(2008, 2, 1)]);
-%!assert (datenum(2008, 1, [1;2]), [datenum(2008, 1, 1);datenum(2008, 1, 2)]);
-%!assert (datenum([2008;2009], [1;2], 1), [datenum(2008, 1, 1);datenum(2009, 2, 1)]);
-%!assert (datenum([2008;2009], 1, [1;2]), [datenum(2008, 1, 1);datenum(2009, 1, 2)]);
-%!assert (datenum(2008, [1;2], [1;2]), [datenum(2008, 1, 1);datenum(2008, 2, 2)]);
+%!assert (datenum ([2008;2009],1,1), [datenum(2008,1,1);datenum(2009,1,1)])
+%!assert (datenum (2008, [1;2], 1), [datenum(2008,1,1);datenum(2008,2,1)])
+%!assert (datenum (2008, 1, [1;2]), [datenum(2008,1,1);datenum(2008,1,2)])
+%!assert (datenum ([2008;2009], [1;2], 1), [datenum(2008,1,1);datenum(2009,2,1)])
+%!assert (datenum ([2008;2009], 1, [1;2]), [datenum(2008,1,1);datenum(2009,1,2)])
+%!assert (datenum (2008, [1;2], [1;2]), [datenum(2008,1,1);datenum(2008,2,2)])
 ## And the other orientation
-%!assert (datenum([2008 2009], 1, 1), [datenum(2008, 1, 1) datenum(2009, 1, 1)]);
-%!assert (datenum(2008, [1 2], 1), [datenum(2008, 1, 1) datenum(2008, 2, 1)]);
-%!assert (datenum(2008, 1, [1 2]), [datenum(2008, 1, 1) datenum(2008, 1, 2)]);
-%!assert (datenum([2008 2009], [1 2], 1), [datenum(2008, 1, 1) datenum(2009, 2, 1)]);
-%!assert (datenum([2008 2009], 1, [1 2]), [datenum(2008, 1, 1) datenum(2009, 1, 2)]);
-%!assert (datenum(2008, [1 2], [1 2]), [datenum(2008, 1, 1) datenum(2008, 2, 2)]);
+%!assert (datenum ([2008 2009], 1, 1), [datenum(2008,1,1) datenum(2009,1,1)])
+%!assert (datenum (2008, [1 2], 1), [datenum(2008,1,1) datenum(2008,2,1)])
+%!assert (datenum (2008, 1, [1 2]), [datenum(2008,1,1) datenum(2008,1,2)])
+%!assert (datenum ([2008 2009], [1 2], 1), [datenum(2008,1,1) datenum(2009,2,1)])
+%!assert (datenum ([2008 2009], 1, [1 2]), [datenum(2008,1,1) datenum(2009,1,2)])
+%!assert (datenum (2008, [1 2], [1 2]), [datenum(2008,1,1) datenum(2008,2,2)])
 ## Test string and cellstr inputs
 %!assert (datenum ("5/19/2001"), 730990)
 %!assert (datenum ({"5/19/2001"}), 730990)
@@ -181,5 +200,6 @@
 %% Test input validation
 %!error datenum ()
 %!error datenum (1,2,3,4,5,6,7)
-%!error datenum ([1, 2])
-%!error datenum ([1,2,3,4,5,6,7])
+%!error <expected date vector containing> datenum ([1, 2])
+%!error <expected date vector containing> datenum ([1,2,3,4,5,6,7])
+%!error <all inputs must be of class double> datenum (int32 (2000), int32 (1), int32 (1))
--- a/scripts/time/datestr.m
+++ b/scripts/time/datestr.m
@@ -56,19 +56,19 @@
 ## @item 16 @tab HH:MM PM               @tab 03:38 PM
 ## @item 17 @tab QQ-YY                  @tab Q3-00
 ## @item 18 @tab QQ                     @tab Q3
-## @item 19 @tab dd/mm                  @tab 13/03
-## @item 20 @tab dd/mm/yy               @tab 13/03/95
-## @item 21 @tab mmm.dd.yyyy HH:MM:SS   @tab Mar.03.1962 13:53:06
-## @item 22 @tab mmm.dd.yyyy            @tab Mar.03.1962
-## @item 23 @tab mm/dd/yyyy             @tab 03/13/1962
-## @item 24 @tab dd/mm/yyyy             @tab 12/03/1962
-## @item 25 @tab yy/mm/dd               @tab 95/03/13
-## @item 26 @tab yyyy/mm/dd             @tab 1995/03/13
-## @item 27 @tab QQ-YYYY                @tab Q4-2132
-## @item 28 @tab mmmyyyy                @tab Mar2047
-## @item 29 @tab yyyymmdd               @tab 20470313
-## @item 30 @tab yyyymmddTHHMMSS        @tab 20470313T132603
-## @item 31 @tab yyyy-mm-dd HH:MM:SS    @tab 1047-03-13 13:26:03
+## @item 19 @tab dd/mm                  @tab 07/09
+## @item 20 @tab dd/mm/yy               @tab 07/09/00
+## @item 21 @tab mmm.dd,yyyy HH:MM:SS   @tab Sep.07,2000 15:38:08
+## @item 22 @tab mmm.dd,yyyy            @tab Sep.07,2000
+## @item 23 @tab mm/dd/yyyy             @tab 09/07/2000
+## @item 24 @tab dd/mm/yyyy             @tab 07/09/2000
+## @item 25 @tab yy/mm/dd               @tab 00/09/07
+## @item 26 @tab yyyy/mm/dd             @tab 2000/09/07
+## @item 27 @tab QQ-YYYY                @tab Q3-2000
+## @item 28 @tab mmmyyyy                @tab Sep2000
+## @item 29 @tab yyyy-mm-dd             @tab 2000-09-07
+## @item 30 @tab yyyymmddTHHMMSS        @tab 20000907T153808
+## @item 31 @tab yyyy-mm-dd HH:MM:SS    @tab 2000-09-07 15:38:08
 ## @end multitable
 ##
 ## If @var{f} is a format string, the following symbols are recognized:
@@ -76,7 +76,7 @@
 ## @multitable @columnfractions 0.1 0.7 0.2
 ## @headitem Symbol @tab Meaning @tab Example
 ## @item yyyy @tab Full year                                    @tab 2005
-## @item yy   @tab Two-digit year                               @tab 2005
+## @item yy   @tab Two-digit year                               @tab 05
 ## @item mmmm @tab Full month name                              @tab December
 ## @item mmm  @tab Abbreviated month name                       @tab Dec
 ## @item mm   @tab Numeric month number (padded with zeros)     @tab 01, 08, 12
@@ -281,13 +281,14 @@
 endfunction
 
 
-## demos
 %!demo
 %! ## Current date and time in default format
 %! datestr (now ())
+
 %!demo
 %! ## Current date (integer portion of datenum)
 %! datestr (fix (now ()))
+
 %!demo
 %! ## Current time (fractional portion of datenum)
 %! datestr (rem (now (), 1))
@@ -335,3 +336,4 @@
 %% Test input validation
 %!error datestr ()
 %!error datestr (1, 2, 3, 4)
+
--- a/scripts/time/datetick.m
+++ b/scripts/time/datetick.m
@@ -22,13 +22,12 @@
 ## @deftypefnx {Function File} {} datetick (@var{axis}, @var{form})
 ## @deftypefnx {Function File} {} datetick (@dots{}, "keeplimits")
 ## @deftypefnx {Function File} {} datetick (@dots{}, "keepticks")
-## @deftypefnx {Function File} {} datetick (@dots{ax}, @dots{})
-## Add date formatted tick labels to an axis.  The axis the apply the
-## ticks to is determined by @var{axis} that can take the values "x",
-## "y" or "z".  The default value is "x".  The formatting of the labels is
-## determined by the variable @var{form}, that can either be a string in
-## the format needed by @code{dateform}, or a positive integer that can
-## be accepted by @code{datestr}.
+## @deftypefnx {Function File} {} datetick (@var{hax}, @dots{})
+## Add date formatted tick labels to an axis.  The axis to apply the
+## ticks to is determined by @var{axis} which can take the values "x",
+## "y", or "z".  The default value is "x".  The formatting of the labels is
+## determined by the variable @var{form}, which can either be a string or
+## positive integer that @code{datestr} accepts.
 ## @seealso{datenum, datestr}
 ## @end deftypefn
 
@@ -46,7 +45,9 @@
 
 endfunction
 
+
 %!demo
+%! clf;
 %! yr = 1900:10:2000;
 %! pop = [76.094, 92.407, 106.461, 123.077 131.954, 151.868, 179.979, ...
 %!        203.984, 227.225, 249.623, 282.224];
@@ -56,16 +57,17 @@
 %! datetick ("x", "YYYY");
 
 %!demo
-%! yr =1988:2:2002;
-%! yr =datenum(yr,1,1);
+%! clf;
+%! yr = 1988:2:2002;
+%! yr = datenum (yr,1,1);
 %! pr = [12.1 13.3 12.6 13.1 13.3 14.1 14.4 15.2];
-%! plot(yr,pr);
-%! xlabel('year')
-%! ylabel('average price')
-%! ax=gca;
-%! set(ax,'xtick',datenum(1990:5:2005,1,1))
-%! datetick(2,'keepticks')
-%! set(ax,'ytick',12:16)
+%! plot (yr, pr);
+%! xlabel ("year");
+%! ylabel ("average price");
+%! ax = gca;
+%! set (ax, "xtick", datenum (1990:5:2005,1,1));
+%! datetick (2, "keepticks");
+%! set (ax, "ytick", 12:16);
 
 ## Remove from test statistics.  No real tests possible.
 %!assert (1)
@@ -132,7 +134,7 @@
   else
     ## Need to do our own axis tick position calculation as
     ## year, etc, don't fallback on nice datenum values.
-    objs = findall (gca());
+    objs = findall (gca ());
     xmax = NaN;
     xmin = NaN;
     for i = 1 : length (objs)
@@ -156,7 +158,7 @@
       ## Day scale or less
       if (xmax - xmin < N / 24 / 60 / 60)
         scl = 1 / 24 / 60 / 60;
-      elseif (xmax - xmin < N / 24 / 6)
+      elseif (xmax - xmin < N / 24 / 60)
         scl = 1 / 24 / 60;
       else
         scl = 1 / 24;
@@ -183,7 +185,7 @@
       elseif (maxyear - minyear < N)
         sep = __calc_tick_sep__ (minmonth , maxmonth);
         xmin = datenum (ymin, sep * floor (minmonth / sep), 1);
-        xmax = datenum (ymin, sep * ceil (maxmonth / sep), 1);
+        xmax = datenum (ymax, sep * ceil (maxmonth / sep), 1);
         nticks = ceil (maxmonth / sep) - floor (minmonth / sep) + 1;
       else
         sep = __calc_tick_sep__ (minyear , maxyear);
@@ -196,22 +198,22 @@
   endif
 
   if (isempty (form))
-    r = max(ticks) - min(ticks);
-    if r < 10/60/24
+    r = max (ticks) - min (ticks);
+    if (r < 10/60/24)
       ## minutes and seconds
       form = 13;
-    elseif r < 2
+    elseif (r < 2)
       ## hours
       form = 15;
-    elseif r < 15
+    elseif (r < 15)
       ## days
       form = 8;
-    elseif r < 365
+    elseif (r < 365)
       ## FIXME -- FORM should be 19 for European users who use dd/mm
       ## instead of mm/dd.  How can that be determined automatically?
       ## months
       form = 6;
-    elseif r < 90*12
+    elseif (r < 90*12)
       ## quarters
       form = 27;
     else
@@ -241,16 +243,16 @@
 
   if (keepticks)
     if (keeplimits)
-      set (gca(), strcat (ax, "ticklabel"), sticks);
+      set (gca (), strcat (ax, "ticklabel"), sticks);
     else
-      set (gca(), strcat (ax, "ticklabel"), sticks, strcat (ax, "lim"),
+      set (gca (), strcat (ax, "ticklabel"), sticks, strcat (ax, "lim"),
       [min(ticks), max(ticks)]);
     endif
   else
     if (keeplimits)
-      set (gca(), strcat (ax, "tick"), ticks, strcat (ax, "ticklabel"), sticks);
+      set (gca (), strcat (ax, "tick"), ticks, strcat (ax, "ticklabel"), sticks);
     else
-      set (gca(), strcat (ax, "tick"), ticks, strcat (ax, "ticklabel"), sticks,
+      set (gca (), strcat (ax, "tick"), ticks, strcat (ax, "ticklabel"), sticks,
       strcat (ax, "lim"), [min(ticks), max(ticks)]);
     endif
   endif
--- a/scripts/time/datevec.m
+++ b/scripts/time/datevec.m
@@ -29,7 +29,12 @@
 ## month, day, hour, minute, and seconds respectively.
 ##
 ## @var{f} is the format string used to interpret date strings
-## (see @code{datestr}).
+## (see @code{datestr}).  If @var{date} is a string, but no format is
+## specified, then a relatively slow search is performed through various
+## formats.  It is always preferable to specify the format string @var{f}
+## if it is known.  Formats which do not specify a particular time component
+## will have the value set to zero.  Formats which do not specify a date will
+## default to January 1st of the current year.
 ##
 ## @var{p} is the year at the start of the century to which two-digit years
 ## will be referenced.  If not specified, it defaults to the current year
@@ -53,7 +58,7 @@
   if (isempty (std_formats))
     std_formats = cell ();
     nfmt = 0;
-    ## These formats are specified by Matlab to be parsed
+    ## These formats are specified by Matlab documentation to be parsed
     ## The '# XX' refers to the datestr numerical format code
     std_formats{++nfmt} = "dd-mmm-yyyy HH:MM:SS";   # 0
     std_formats{++nfmt} = "dd-mmm-yyyy";            # 1
@@ -65,6 +70,14 @@
     std_formats{++nfmt} = "HH:MM PM";               # 16
     std_formats{++nfmt} = "mm/dd/yyyy";             # 23
 
+    ## These formats are undocumented but parsed by Matlab
+    std_formats{++nfmt} = "mmmyy";                  # 12
+    std_formats{++nfmt} = "mmm.dd,yyyy HH:MM:SS";   # 21
+    std_formats{++nfmt} = "mmm.dd,yyyy";            # 22
+    std_formats{++nfmt} = "yyyy/mm/dd";             # 26
+    std_formats{++nfmt} = "yyyy-mm-dd";             # 29
+    std_formats{++nfmt} = "yyyy-mm-dd HH:MM:SS";    # 31
+
     ## These are other formats that Octave tries
     std_formats{++nfmt} = "mmm-dd-yyyy HH:MM:SS";
     std_formats{++nfmt} = "mmm-dd-yyyy";
@@ -76,7 +89,6 @@
     std_formats{++nfmt} = "dd.mmm.yyyy";
     std_formats{++nfmt} = "mmm.dd.yyyy HH:MM:SS";
     std_formats{++nfmt} = "mmm.dd.yyyy";
-    std_formats{++nfmt} = "mmmyy";                  # 12
     std_formats{++nfmt} = "mm/dd/yyyy HH:MM";
   endif
 
@@ -254,9 +266,10 @@
     endif
     if (! fy && ! fm && ! fd)
       tmp = localtime (time ());
+      ## default is January 1st of current year
       y = tmp.year + 1900;
-      m = tmp.mon + 1;
-      d = tmp.mday;
+      m = 1;
+      d = 1;
     elseif (! fy && fm && fd)
       tmp = localtime (time ());
       y = tmp.year + 1900;
@@ -280,24 +293,24 @@
 %! ## Current date and time
 %! datevec (now ())
 
-%!shared nowvec
-%! nowvec = datevec (now); # Some tests could fail around midnight!
-%!# tests for standard formats: 0, 1, 2, 6, 13, 14, 15, 16, 23
+%!shared yr
+%! yr = datevec (now)(1);  # Some tests could fail around midnight!
+## tests for standard formats: 0, 1, 2, 6, 13, 14, 15, 16, 23
 %!assert (datevec ("07-Sep-2000 15:38:09"), [2000,9,7,15,38,9])
 %!assert (datevec ("07-Sep-2000"), [2000,9,7,0,0,0])
 %!assert (datevec ("09/07/00"), [2000,9,7,0,0,0])
-%!assert (datevec ("09/13"), [nowvec(1),9,13,0,0,0])
-%!assert (datevec ("15:38:09"), [nowvec(1:3),15,38,9])
-%!assert (datevec ("3:38:09 PM"), [nowvec(1:3),15,38,9])
-%!assert (datevec ("15:38"), [nowvec(1:3),15,38,0])
-%!assert (datevec ("03:38 PM"), [nowvec(1:3),15,38,0])
+%!assert (datevec ("09/13"), [yr,9,13,0,0,0])
+%!assert (datevec ("15:38:09"), [yr,1,1,15,38,9])
+%!assert (datevec ("3:38:09 PM"), [yr,1,1,15,38,9])
+%!assert (datevec ("15:38"), [yr,1,1,15,38,0])
+%!assert (datevec ("03:38 PM"), [yr,1,1,15,38,0])
 %!assert (datevec ("03/13/1962"), [1962,3,13,0,0,0])
 
 %% Test millisecond format FFF
-%!assert (datevec ("15:38:21.25", "HH:MM:SS.FFF"), [nowvec(1:3),15,38,21.025])
+%!assert (datevec ("15:38:21.25", "HH:MM:SS.FFF"), [yr,1,1,15,38,21.025])
 
 # Other tests
-%!assert (datenum (datevec ([-1e4:1e4])), [-1e4:1e4]')
+%!assert (datenum (datevec ([-1e4:1e4])), [-1e4:1e4]');
 %!test
 %! t = linspace (-2e5, 2e5, 10993);
 %! assert (all (abs (datenum (datevec (t)) - t') < 1e-5));
--- a/scripts/time/eomday.m
+++ b/scripts/time/eomday.m
@@ -54,7 +54,7 @@
 %!assert (eomday ([-800,800],2), [29,29])
 %!assert (eomday (2001,1:12), [31,28,31,30,31,30,31,31,30,31,30,31])
 %!assert (eomday (1:3,1:3), [31,28,31])
-%!assert (eomday (1:2000,2)', datevec(datenum(1:2000,3,0))(:,3))
+%!assert (eomday (1:2000,2)', datevec (datenum (1:2000,3,0))(:,3))
 %!assert ([1900:1999](find(eomday(1900:1999,2*ones(1,100))==29)), [1904,1908,1912,1916,1920,1924,1928,1932,1936,1940,1944,1948,1952,1956,1960,1964,1968,1972,1976,1980,1984,1988,1992,1996])
 %!assert (eomday ([2004;2005], [2;2]), [29;28])
 
--- a/scripts/time/etime.m
+++ b/scripts/time/etime.m
@@ -51,14 +51,14 @@
 endfunction
 
 
-%!assert (etime ([1900,12,31,23,59,59],[1901,1,1,0,0,0]),-1)
-%!assert (etime ([1900,2,28,23,59,59],[1900,3,1,0,0,0]),-1)
-%!assert (etime ([2000,2,28,23,59,59],[2000,3,1,0,0,0]),-86401)
-%!assert (etime ([1996,2,28,23,59,59],[1996,3,1,0,0,0]),-86401)
+%!assert (etime ([1900,12,31,23,59,59], [1901,1,1,0,0,0]), -1)
+%!assert (etime ([1900,2,28,23,59,59], [1900,3,1,0,0,0]), -1)
+%!assert (etime ([2000,2,28,23,59,59], [2000,3,1,0,0,0]), -86401)
+%!assert (etime ([1996,2,28,23,59,59], [1996,3,1,0,0,0]), -86401)
 %!test
 %! t1 = [1900,12,31,23,59,59; 1900,2,28,23,59,59];
 %! t2 = [1901,1,1,0,0,0; 1900,3,1,0,0,0];
-%! assert(etime(t2, t1), [1;1]);
+%! assert (etime (t2, t1), [1;1]);
 
 %!test
 %! t1 = [1993, 8, 20, 4, 56, 1];
--- a/scripts/time/is_leap_year.m
+++ b/scripts/time/is_leap_year.m
@@ -56,5 +56,5 @@
 %!assert (is_leap_year (1800), false)
 %!assert (is_leap_year (1600), true)
 
-%!error is_leap_year (1, 2);
+%!error is_leap_year (1, 2)
 
--- a/scripts/time/now.m
+++ b/scripts/time/now.m
@@ -47,15 +47,16 @@
   ##   divided by 86400 sec/day plus day num for 1970-1-1
   ##   t = (time - mktime(gmtime(0)))/86400 + 719529;
   ##
-  ## mktime(gmtime(0)) does indeed return the offset from Greenwich to the
+  ## mktime (gmtime (0)) does indeed return the offset from Greenwich to the
   ## local time zone, but we need to account for daylight savings time
   ## changing by an hour the offset from CUT for part of the year.
 
 endfunction
 
 
-%!assert (isnumeric (now ()));
-%!assert (now () > 0);
-%!assert (now () <= now ());
+%!assert (isnumeric (now ()))
+%!assert (now () > 0)
+%!assert (now () <= now ())
 
-%!error now (1);
+%!error now (1)
+
--- a/scripts/time/weekday.m
+++ b/scripts/time/weekday.m
@@ -84,12 +84,14 @@
 %!demo
 %! ## Current weekday
 %! [n, s] = weekday (now ())
+
 %!demo
 %! ## Weekday from datenum input
 %! [n, s] = weekday (728647)
+
 %!demo
 %! ## Weekday of new millennium from datestr input
-%! [n, s] = weekday ('1-Jan-2000')
+%! [n, s] = weekday ("1-Jan-2000")
 
 # tests
 %!assert (weekday (728647), 2)
new file mode 100644
--- /dev/null
+++ b/scripts/ui/errordlg.m
@@ -0,0 +1,49 @@
+## 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 retval = errordlg (msg, title = "Error Dialog")
+
+  if (nargin < 1 || nargin > 2)
+    print_usage ();
+  endif
+
+  retval = message_dialog ("errdlg", msg, title, "error");
+
+endfunction
+
+%!demo
+%!  disp('- test errordlg with prompt only.');
+%!  errordlg('Oops, an expected error occured');
+
+%!demo
+%!  disp('- test errordlg with prompt and caption.');
+%!  errordlg('Oops another error','This is a very long and informative caption');
new file mode 100644
--- /dev/null
+++ b/scripts/ui/helpdlg.m
@@ -0,0 +1,49 @@
+## 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 retval = helpdlg (msg, title = "Help Dialog")
+
+  if (nargin < 1 || nargin > 2)
+    print_usage ();
+  endif
+
+  retval = message_dialog ("helpdlg", msg, title, "help");
+
+endfunction
+
+%!demo
+%!  disp('- test helpdlg with a help message only.');
+%!  helpdlg("Below, you should see 3 lines:\nline #1\nline #2, and\nline #3.");
+
+%!demo
+%!  disp('- test helpdlg with help message and caption.');
+%!  helpdlg('You should see a single line.','A help dialog');
new file mode 100644
--- /dev/null
+++ b/scripts/ui/inputdlg.m
@@ -0,0 +1,205 @@
+## 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
+  rowscols = ceil (rowscols);
+  
+  ## convert numeric values in defaults cell array to strings
+  defs = cellfun (@num2str, defaults, "UniformOutput", false);
+  rc = arrayfun (@num2str, rowscols, "UniformOutput", false);
+
+  if (__octave_link_enabled__ ())
+    cstr = __octave_link_input_dialog__ (prompt, title, rowscols, defs);
+  elseif (__have_feature__ ("JAVA"))
+    user_inputs = javaMethod ("inputdlg", "org.octave.JDialogBox",
+                              prompt, title, rc, defs);  
+    if (isempty (user_inputs))
+      cstr = {};
+    else
+      cstr = cellstr (user_inputs);
+    endif
+  else
+    error ("inputdlg is not available in this version of Octave");
+  endif
+
+endfunction
+
+%!demo
+%!  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
+
+%!demo
+%!  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
+
+%!demo
+%!  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
+
+%!demo
+%!  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
new file mode 100644
--- /dev/null
+++ b/scripts/ui/listdlg.m
@@ -0,0 +1,192 @@
+## 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 "ListString" argument pair must be specified.
+##
+## Valid @var{key} and @var{value} pairs are:
+##
+## @table @asis
+## @item "ListString"
+## a cell array of strings comprising the content of the list.
+##
+## @item "SelectionMode"
+## can be either "Single" or "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 [sel, ok] = 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
+
+  ## make sure valid selection mode
+  if (! strcmp (selmode, "Multiple") && ! strcmp (selmode, "Single"))
+    error ("invalid SelectionMode");
+  endif
+
+  if (__octave_link_enabled__ ())
+    [sel, ok] = __octave_link_list_dialog__ (listcell, selmode, listsize,
+                                            initialvalue, name, prompt,
+                                            okstring, cancelstring);
+  elseif (__have_feature__ ("JAVA"))
+    ## 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);
+    if isempty(prompt)
+      prompt = {""};
+    endif
+
+    ret = javaMethod ("listdlg", "org.octave.JDialogBox", listcell,
+                      selmode, listsize, initialvalue, name, prompt,
+                      okstring, cancelstring);
+
+    if (numel (ret) > 0)
+      sel = ret;
+      ok = 1;
+    else
+      sel = {};
+      ok = 0;
+    endif
+  else
+    error ("listdlg is not available in this version of Octave");
+  endif
+
+endfunction
+
+%!demo
+%!  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
+
+%!demo
+%!  disp('- test listdlg with selectionmode and preselection. Has caption and two lines prompt.');
+%!  itemlist = {'An item \\alpha', 'another', 'yet another'};
+%!  s = listdlg ( 'ListString',itemlist, ...
+%!                'SelectionMode','Multiple', ...
+%!                'Name','Selection Dialog', ...
+%!                'InitialValue',[1,2,3,4],
+%!                'PromptString',{'Select <b>an</b> item...', '...or <b>multiple</b> items'} );
+%!  imax = numel (s);
+%!  for i=1:1:imax
+%!     disp(['Selected: ',num2str(i),': ', itemlist{s(i)}]);
+%!  end
+
+%!demo
+%!  disp('- test listdlg with listsize.');
+%!  itemlist = {"Neutron","Electron","Quark","Proton","Neutrino"};
+%!  s = listdlg ( "ListString",itemlist,
+%!                "Name","Bits and Pieces",
+%!                "ListSize",[200 75] );
+%!  imax = numel (s);
+%!  for i=1:1:imax
+%!     disp(['Selected: ',num2str(i),': ', itemlist{s(i)}]);
+%!  end
new file mode 100644
--- /dev/null
+++ b/scripts/ui/module.mk
@@ -0,0 +1,20 @@
+FCN_FILE_DIRS += ui
+
+ui_PRIVATE_FCN_FILES = \
+  ui/private/message_dialog.m
+
+ui_FCN_FILES = \
+  ui/errordlg.m \
+  ui/helpdlg.m \
+  ui/inputdlg.m \
+  ui/listdlg.m \
+  ui/msgbox.m \
+  ui/questdlg.m \
+  ui/warndlg.m \
+  $(ui_PRIVATE_FCN_FILES)
+
+FCN_FILES += $(ui_FCN_FILES)
+
+PKG_ADD_FILES += ui/PKG_ADD
+
+DIRSTAMP_FILES += ui/$(octave_dirstamp)
new file mode 100644
--- /dev/null
+++ b/scripts/ui/msgbox.m
@@ -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} =} 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 retval = msgbox (msg, title = "", varargin)
+
+  if (nargin < 1 || nargin > 3)
+    print_usage ();
+  endif
+
+  retval = message_dialog ("msgbox", msg, title, varargin{:});
+
+endfunction
+
+%!demo
+%!  disp('- test msgbox message only.');
+%!  msgbox("Below, you should see 3 lines:\nline #1\nline #2, and\nline #3.");
+
+%!demo
+%!  disp('- test msgbox message and caption.');
+%!  msgbox('You should see a single line.','A msgbox');
new file mode 100644
--- /dev/null
+++ b/scripts/ui/private/message_dialog.m
@@ -0,0 +1,65 @@
+## 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} =} message_dialog (@var{caller}, @var{msg}, @var{title}, @var{icon})
+## Undocumented internal function.
+## @end deftypefn
+
+function retval = message_dialog (caller, msg, title = "", icon)
+
+  if (! ischar (msg))
+    if (iscell (msg))
+      msg = sprintf ("%s\n", msg{:});
+      msg(end) = "";
+    else
+      error ("%s: MSG must be a character string or cellstr array", caller);
+    endif
+  endif
+
+  if (! ischar (title))
+    error ("%s: TITLE must be a character string", caller);
+  endif
+
+  dlg = "emptydlg";
+  if (nargin == 4)
+    switch (icon)
+      case "error"
+        dlg = "errordlg";
+      case "help"
+        dlg = "helpdlg";
+      case "warn"
+        dlg = "warndlg";
+      case "none"
+        dlg = "emptydlg";
+      otherwise
+        error ("%s: ICON is not a valid type", caller);
+    endswitch
+  else
+    icon = "none";
+  endif
+
+  if (__octave_link_enabled__ ())
+    retval = __octave_link_message_dialog__ (icon, msg, title);
+  elseif (__have_feature__ ("JAVA"))
+    retval = javaMethod (dlg, "org.octave.JDialogBox", msg, title);
+  else
+    error ("%s is not available in this version of Octave", dlg);
+  endif
+
+endfunction
new file mode 100644
--- /dev/null
+++ b/scripts/ui/questdlg.m
@@ -0,0 +1,174 @@
+## 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
+## ("\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 @key{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
+
+  defbtn_error_msg = "questdlg: DEFAULT must match one of the button options";
+
+  switch (numel (varargin))
+    case 0
+      ## use default default
+
+    case 1
+      ## default button string
+      options{4} = varargin{1};  # default
+      if (! any (strcmp (options{4}, options(1:3))))
+        error (defbtn_error_msg);
+      end
+
+    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
+      if (! any (strcmp (options{4}, options([1 3]))))
+        error (defbtn_error_msg);
+      end
+
+    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
+      if (! any (strcmp (options{4}, options(1:3))))
+        error (defbtn_error_msg);
+      end
+
+    otherwise
+      print_usage ();
+
+  endswitch
+
+  if (__octave_link_enabled__ ())
+    btn = __octave_link_question_dialog__ (msg, title, options{1}, options{2},
+                                           options{3}, options{4});
+  elseif (__have_feature__ ("JAVA"))
+    btn = javaMethod ("questdlg", "org.octave.JDialogBox", msg,
+                      title, options);
+  else
+    error ("questdlg is not available in this version of Octave");
+  endif
+
+endfunction
+
+%!demo
+%!  disp('- test questdlg with two buttons');
+%!  a = questdlg('Would you like some free money?',...
+%!               '$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $',...
+%!               'No', 'Cancel', 'Cancel');
+%!  if strcmp (a, 'No')
+%!    msgbox('Suit yourself.', 'Message Box');
+%!  endif
+
+%!demo
+%!  disp('- test questdlg with message and title only.');
+%!  a = 'No';
+%!  c = 0;
+%!  while (strcmp(a, 'No') || !c)
+%!    a = questdlg('Close this Question Dialog?', 'Reductio Ad Absurdum');
+%!    if strcmp(a, 'Yes')
+%!      q = 'Are you sure?';
+%!      while (strcmp(a, 'Yes') && !c)
+%!        a = questdlg(q, 'Reductio Ad Absurdum');
+%!        word = ' really';
+%!        i = strfind(q, word);
+%!        if isempty( i )
+%!          i = strfind(q, ' sure');
+%!          q = [q '!'];
+%!        else
+%!          word = [word ','];
+%!        endif
+%!        q = [q(1:i-1) word q(i:end)];
+%!      endwhile
+%!    endif
+%!    if strcmp(a, 'Cancel')
+%!      warndlg('Answer "Yes" or "No".', 'Warning Dialog');
+%!      a = 'No';
+%!      c = 1;
+%!    endif
+%!  endwhile
+%!  msgbox('Whew!');
+
+%!demo
+%!  disp('- test questdlg with five inputs');
+%!  ans = questdlg('Are you ready Steve?', 'Brian', 'No', 'Uh huh', 'Uh huh');
+%!  if !strcmp (ans, 'No')
+%!    ans = questdlg ('Andy?', 'Brian', 'No', 'Yeah', 'Yeah');
+%!    if !strcmp (ans, 'No')
+%!      ans = questdlg ('Mick?', 'Brian', 'No', 'Okay', 'Okay');
+%!      if !strcmp (ans, 'No')
+%!        ans = msgbox ("Well all right, fellas.    \n\n     Let''s GO!!!!!",...
+%!                      'Ballroom Blitz', 'none');
+%!      endif
+%!    endif
+%!  endif
+
new file mode 100644
--- /dev/null
+++ b/scripts/ui/warndlg.m
@@ -0,0 +1,48 @@
+## 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
+
+  retval = message_dialog ("warndlg", msg, title, "warn");
+
+endfunction
+
+%!demo
+%!  disp('- test warndlg with prompt only.');
+%!  warndlg('Oh, a warning occured');
+
+%!demo
+%!  disp('- test warndlg with prompt and caption.');
+%!  warndlg('Oh, No...','This is the last Warning');
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -1,4 +1,4 @@
-# Makefile for octave's src directory
+# Makefile for Octave's src directory
 #
 # Copyright (C) 1993-2012 John W. Eaton
 #
@@ -22,685 +22,118 @@
 
 ## Search local directories before those specified by the user.
 AM_CPPFLAGS = \
-  -I../libgnu -I$(top_srcdir)/libgnu \
-  -I$(top_srcdir)/libcruft/misc \
-  -I../liboctave -I$(top_srcdir)/liboctave \
-  -I. -I$(srcdir) \
-  @CPPFLAGS@
+  -I$(top_srcdir)/liboctave/array \
+  -I$(top_srcdir)/liboctave/cruft/misc \
+  -I$(top_srcdir)/liboctave/numeric \
+  -I$(top_srcdir)/liboctave/system \
+  -I$(top_srcdir)/liboctave/util \
+  -I$(top_srcdir)/libinterp \
+  -I$(top_builddir)/libinterp/interpfcn -I$(top_srcdir)/libinterp/interpfcn \
+  -I$(top_builddir)/libgnu -I$(top_srcdir)/libgnu
+
+AM_CFLAGS += $(WARN_CFLAGS)
+
+AM_CXXFLAGS += $(WARN_CXXFLAGS)
+
+EXTRA_DIST = \
+  mkoctfile.in.cc \
+  mkoctfile.in.sh \
+  octave-config.in.cc \
+  octave-config.in.sh
+
+DISTCLEANFILES =
+
+OCTAVE_BINARIES = \
+  octave \
+  octave-cli
+
+OCTAVE_CORE_LIBS = \
+  $(top_builddir)/libinterp/liboctinterp.la \
+  $(top_builddir)/liboctave/liboctave.la
+
+include ../libgui/link-deps.mk
 
-AUTOMAKE_OPTIONS = subdir-objects
+octave_cli_SOURCES = main-cli.cc
+
+octave_cli_LDADD = \
+  $(OCTAVE_CORE_LIBS)
+  $(OCTAVE_LINK_DEPS)
+
+octave_cli_LDFLAGS = \
+  $(NO_UNDEFINED_LDFLAG) \
+  $(OCTAVE_LINK_OPTS)
 
-octlib_LTLIBRARIES = liboctinterp.la
+if AMCOND_BUILD_GUI
+  octave_SOURCES = main.cc
+  OCTAVE_GUI_LIBS = $(top_builddir)/libgui/liboctgui.la
+  OCTAVE_GUI_CPPFLAGS = -I$(top_srcdir)/libgui/src
+else
+  octave_SOURCES = main-cli.cc
+  OCTAVE_GUI_LIBS =
+  OCTAVE_GUI_CPPFLAGS =
+endif
+
+octave_CPPFLAGS = \
+  $(AM_CPPFLAGS) \
+  $(OCTAVE_GUI_CPPFLAGS)
+
+octave_LDADD = \
+  $(OCTAVE_GUI_LIBS) \
+  $(OCTAVE_CORE_LIBS) \
+  $(OCTAVE_GUI_LINK_DEPS)
+
+octave_LDFLAGS = \
+  $(NO_UNDEFINED_LDFLAG) \
+  $(OCTAVE_GUI_LINK_OPTS)
 
 if AMCOND_BUILD_COMPILED_AUX_PROGRAMS
 bin_PROGRAMS = \
+  $(OCTAVE_BINARIES) \
   mkoctfile \
-  octave \
   octave-config
 
 mkoctfile_SOURCES =
 nodist_mkoctfile_SOURCES = mkoctfile.cc
-mkoctfile_LDADD = ../libgnu/libgnu.la $(LIBS)
+mkoctfile_LDADD = $(top_builddir)/libgnu/libgnu.la $(LIBS)
 
 octave_config_SOURCES =
 nodist_octave_config_SOURCES = octave-config.cc
-octave_config_LDADD = ../libgnu/libgnu.la $(LIBS)
+octave_config_LDADD = \
+  $(top_builddir)/libinterp/corefcn/libcorefcn.la \
+  $(top_builddir)/libgnu/libgnu.la \
+  $(LIBS)
 
-BUILT_SOURCES_EXTRA = \
-  mkoctfile.cc \
-  octave-config.cc
+DISTCLEANFILES += mkoctfile.cc octave-config.cc
+
 else
 bin_PROGRAMS = \
-  octave
+  $(OCTAVE_BINARIES)
 
 bin_SCRIPTS = \
   mkoctfile \
   octave-config
 endif
 
-## Order matters here.  Leave builtins.cc last, because it depends on
-## $(DEF_FILES), and building those requires all the sources
-## (except builtins.cc) to be available.
-BUILT_SOURCES = \
-  $(BUILT_SOURCES_EXTRA) \
-  defaults.h \
-  graphics.h \
-  graphics-props.cc \
-  lex.cc \
-  mxarray.h \
-  oct-conf.h \
-  oct-errno.cc \
-  oct-gperf.h \
-  oct-parse.cc \
-  ops.cc \
-  version.h \
-  builtins.cc
-
-BUILT_DISTFILES = \
-  oct-gperf.h \
-  oct-parse.h
-
-## Files that are created during build process and installed,
-## BUT not distributed in tarball.
-BUILT_NODISTFILES = \
-  defaults.h \
-  graphics.h \
-  oct-conf.h \
-  oct-errno.cc \
-  ops.cc \
-  mxarray.h \
-  version.h \
-  $(OPT_HANDLERS) \
-  $(OPT_INC) \
-  $(ALL_DEF_FILES) \
-  builtins.cc
-
-EXTRA_DIST = \
-  Makefile.in \
-  defaults.h.in \
-  DOCSTRINGS \
-  find-defun-files.sh \
-  gendoc.pl \
-  genprops.awk \
-  gl2ps.c \
-  graphics.h.in \
-  mk-errno-list \
-  mk-pkg-add \
-  mkbuiltins \
-  mkdefs \
-  mkoctfile.cc.in \
-  mkoctfile.in \
-  mkops \
-  mxarray.h.in \
-  oct-conf.h.in \
-  oct-errno.cc.in \
-  octave-config.cc.in \
-  octave-config.in \
-  octave.gperf \
-  version.h.in \
-  $(BUILT_DISTFILES)
-
-OPT_HANDLERS = \
-  DASPK-opts.cc \
-  DASRT-opts.cc \
-  DASSL-opts.cc \
-  LSODE-opts.cc \
-  Quad-opts.cc
-
-OPT_INC = \
-  ../liboctave/DASPK-opts.h \
-  ../liboctave/DASRT-opts.h \
-  ../liboctave/DASSL-opts.h \
-  ../liboctave/LSODE-opts.h \
-  ../liboctave/Quad-opts.h
-
-OV_INTTYPE_INC = \
-  ov-base-int.h \
-  ov-base-int.cc \
-  ov-int-traits.h \
-  ov-int16.h \
-  ov-int32.h \
-  ov-int64.h \
-  ov-int8.h \
-  ov-intx.h \
-  ov-uint16.h \
-  ov-uint32.h \
-  ov-uint64.h \
-  ov-uint8.h
-
-OV_INCLUDES = \
-  ov-base-diag.h \
-  ov-base-diag.cc \
-  ov-base-mat.h \
-  ov-base-mat.cc \
-  ov-base-scalar.h \
-  ov-base-scalar.cc \
-  ov-base.h \
-  ov-bool-mat.h \
-  ov-bool-mat.cc \
-  ov-bool.h \
-  ov-builtin.h \
-  ov-cell.h \
-  ov-ch-mat.h \
-  ov-class.h \
-  ov-colon.h \
-  ov-complex.h \
-  ov-cs-list.h \
-  ov-cx-diag.h \
-  ov-cx-mat.h \
-  ov-dld-fcn.h \
-  ov-fcn-handle.h \
-  ov-fcn-inline.h \
-  ov-fcn.h \
-  ov-float.h \
-  ov-flt-complex.h \
-  ov-flt-cx-diag.h \
-  ov-flt-cx-mat.h \
-  ov-flt-re-diag.h \
-  ov-flt-re-mat.h \
-  ov-lazy-idx.h \
-  ov-mex-fcn.h \
-  ov-null-mat.h \
-  ov-oncleanup.h \
-  ov-perm.h \
-  ov-range.h \
-  ov-re-diag.h \
-  ov-re-mat.h \
-  ov-scalar.h \
-  ov-str-mat.h \
-  ov-struct.h \
-  ov-type-conv.h \
-  ov-typeinfo.h \
-  ov-usr-fcn.h \
-  ov.h \
-  $(OV_INTTYPE_INC)
-
-OV_SPARSE_INCLUDES = \
-  ov-base-sparse.h \
-  ov-bool-sparse.h \
-  ov-cx-sparse.h \
-  ov-re-sparse.h
-
-PT_INCLUDES = \
-  pt-all.h \
-  pt-arg-list.h \
-  pt-assign.h \
-  pt-binop.h \
-  pt-bp.h \
-  pt-cbinop.h \
-  pt-cell.h \
-  pt-check.h \
-  pt-cmd.h \
-  pt-colon.h \
-  pt-const.h \
-  pt-decl.h \
-  pt-eval.h \
-  pt-except.h \
-  pt-exp.h \
-  pt-fcn-handle.h \
-  pt-id.h \
-  pt-idx.h \
-  pt-jump.h \
-  pt-loop.h \
-  pt-mat.h \
-  pt-misc.h \
-  pt-pr-code.h \
-  pt-select.h \
-  pt-stmt.h \
-  pt-unop.h \
-  pt-walk.h \
-  pt.h
-
-octinclude_HEADERS = \
-  Cell.h \
-  builtins.h \
-  c-file-ptr-stream.h \
-  comment-list.h \
-  cutils.h \
-  data.h \
-  debug.h \
-  defun-dld.h \
-  defun-int.h \
-  defun.h \
-  dirfns.h \
-  display.h \
-  dynamic-ld.h \
-  error.h \
-  file-io.h \
-  gl-render.h \
-  gl2ps.h \
-  gl2ps-renderer.h \
-  graphics-props.cc \
-  gripes.h \
-  help.h \
-  input.h \
-  lex.h \
-  load-path.h \
-  load-save.h \
-  ls-ascii-helper.h \
-  ls-hdf5.h \
-  ls-mat-ascii.h \
-  ls-mat4.h \
-  ls-mat5.h \
-  ls-oct-ascii.h \
-  ls-oct-binary.h \
-  ls-utils.h \
-  mex.h \
-  mexproto.h \
-  oct-errno.h \
-  oct-fstrm.h \
-  oct-gperf.h \
-  oct-hdf5.h \
-  oct-hist.h \
-  oct-iostrm.h \
-  oct-lvalue.h \
-  oct-map.h \
-  oct-obj.h \
-  oct-prcstrm.h \
-  oct-procbuf.h \
-  oct-stdstrm.h \
-  oct-stream.h \
-  oct-strstrm.h \
-  oct.h \
-  octave.h \
-  ops.h \
-  pager.h \
-  parse.h \
-  pr-output.h \
-  procstream.h \
-  profiler.h \
-  sighandlers.h \
-  siglist.h \
-  sparse-xdiv.h \
-  sparse-xpow.h \
-  symtab.h \
-  sysdep.h \
-  token.h \
-  toplev.h \
-  txt-eng-ft.h \
-  txt-eng.h \
-  unwind-prot.h \
-  utils.h \
-  variables.h \
-  xdiv.h \
-  xnorm.h \
-  xpow.h \
-  zfstream.h \
-  $(OV_INCLUDES) \
-  $(OV_SPARSE_INCLUDES) \
-  $(PT_INCLUDES)
-
-nodist_octinclude_HEADERS = \
-  defaults.h \
-  graphics.h \
-  oct-conf.h \
-  mxarray.h \
-  version.h
-
-OV_INTTYPE_SRC = \
-  ov-int16.cc \
-  ov-int32.cc \
-  ov-int64.cc \
-  ov-int8.cc \
-  ov-uint16.cc \
-  ov-uint32.cc \
-  ov-uint64.cc \
-  ov-uint8.cc
-
-OV_SPARSE_SRC = \
-  ov-base-sparse.cc \
-  ov-bool-sparse.cc \
-  ov-cx-sparse.cc \
-  ov-re-sparse.cc
-
-OV_SRC = \
-  ov-base.cc \
-  ov-bool-mat.cc \
-  ov-bool.cc \
-  ov-builtin.cc \
-  ov-cell.cc \
-  ov-ch-mat.cc \
-  ov-class.cc \
-  ov-colon.cc \
-  ov-complex.cc \
-  ov-cs-list.cc \
-  ov-cx-diag.cc \
-  ov-cx-mat.cc \
-  ov-dld-fcn.cc \
-  ov-fcn-handle.cc \
-  ov-fcn-inline.cc \
-  ov-fcn.cc \
-  ov-float.cc \
-  ov-flt-complex.cc \
-  ov-flt-cx-diag.cc \
-  ov-flt-cx-mat.cc \
-  ov-flt-re-diag.cc \
-  ov-flt-re-mat.cc \
-  ov-lazy-idx.cc \
-  ov-mex-fcn.cc \
-  ov-null-mat.cc \
-  ov-oncleanup.cc \
-  ov-perm.cc \
-  ov-range.cc \
-  ov-re-diag.cc \
-  ov-re-mat.cc \
-  ov-scalar.cc \
-  ov-str-mat.cc \
-  ov-struct.cc \
-  ov-typeinfo.cc \
-  ov-usr-fcn.cc \
-  ov.cc \
-  $(OV_INTTYPE_SRC) \
-  $(OV_SPARSE_SRC)
-
-PT_SRC = \
-  pt-arg-list.cc \
-  pt-assign.cc \
-  pt-binop.cc \
-  pt-bp.cc \
-  pt-cbinop.cc \
-  pt-cell.cc \
-  pt-check.cc \
-  pt-cmd.cc \
-  pt-colon.cc \
-  pt-const.cc \
-  pt-decl.cc \
-  pt-eval.cc \
-  pt-except.cc \
-  pt-exp.cc \
-  pt-fcn-handle.cc \
-  pt-id.cc \
-  pt-idx.cc \
-  pt-jump.cc \
-  pt-loop.cc \
-  pt-mat.cc \
-  pt-misc.cc \
-  pt-pr-code.cc \
-  pt-select.cc \
-  pt-stmt.cc \
-  pt-unop.cc \
-  pt.cc
-
-DIST_SRC = \
-  Cell.cc \
-  bitfcns.cc \
-  c-file-ptr-stream.cc \
-  comment-list.cc \
-  cutils.c \
-  data.cc \
-  debug.cc \
-  defaults.cc \
-  defun.cc \
-  dirfns.cc \
-  display.cc \
-  dynamic-ld.cc \
-  error.cc \
-  file-io.cc \
-  gl-render.cc \
-  gl2ps-renderer.cc \
-  graphics.cc \
-  gripes.cc \
-  help.cc \
-  input.cc \
-  lex.ll \
-  load-path.cc \
-  load-save.cc \
-  ls-ascii-helper.cc \
-  ls-hdf5.cc \
-  ls-mat-ascii.cc \
-  ls-mat4.cc \
-  ls-mat5.cc \
-  ls-oct-ascii.cc \
-  ls-oct-binary.cc \
-  ls-utils.cc \
-  mappers.cc \
-  matherr.c \
-  mex.cc \
-  oct-fstrm.cc \
-  oct-hist.cc \
-  oct-iostrm.cc \
-  oct-lvalue.cc \
-  oct-map.cc \
-  oct-obj.cc \
-  oct-parse.yy \
-  oct-prcstrm.cc \
-  oct-procbuf.cc \
-  oct-stream.cc \
-  oct-strstrm.cc \
-  octave.cc \
-  pager.cc \
-  pr-output.cc \
-  procstream.cc \
-  profiler.cc \
-  sighandlers.cc \
-  siglist.c \
-  sparse.cc \
-  sparse-xdiv.cc \
-  sparse-xpow.cc \
-  strfns.cc \
-  symtab.cc \
-  syscalls.cc \
-  sysdep.cc \
-  token.cc \
-  toplev.cc \
-  txt-eng-ft.cc \
-  unwind-prot.cc \
-  utils.cc \
-  variables.cc \
-  xdiv.cc \
-  xgl2ps.c \
-  xnorm.cc \
-  xpow.cc \
-  zfstream.cc \
-  $(OV_SRC) \
-  $(PT_SRC)
-
-include DLD-FUNCTIONS/module.mk
-
-$(srcdir)/DLD-FUNCTIONS/module.mk: $(srcdir)/DLD-FUNCTIONS/config-module.sh $(srcdir)/DLD-FUNCTIONS/config-module.awk $(srcdir)/DLD-FUNCTIONS/module-files
-	$(srcdir)/DLD-FUNCTIONS/config-module.sh $(top_srcdir)
-
-include OPERATORS/module.mk
-include TEMPLATE-INST/module.mk
-
-if AMCOND_ENABLE_DYNAMIC_LINKING
-  OCT_FILES = $(DLD_FUNCTIONS_LIBS:.la=.oct)
-  OCT_STAMP_FILES = $(subst DLD-FUNCTIONS/,DLD-FUNCTIONS/$(am__leading_dot),$(DLD_FUNCTIONS_LIBS:.la=.oct-stamp))
-else
-  OCT_FILES =
-  OCT_STAMP_FILES =
-endif
-
-liboctinterp_la_SOURCES = \
-  $(DIST_SRC) \
-  $(OPERATORS_SRC) \
-  $(TEMPLATE_INST_SRC)
-
-nodist_liboctinterp_la_SOURCES = \
-  builtins.cc \
-  defaults.h \
-  graphics.h \
-  mxarray.h \
-  oct-conf.h \
-  oct-errno.cc \
-  ops.cc \
-  version.h \
-  $(OPT_INC)
-
-liboctinterp_la_CPPFLAGS = @OCTINTERP_DLL_DEFS@ $(AM_CPPFLAGS)
-
-include link-deps.mk
-
-liboctinterp_la_LIBADD = \
-  ../liboctave/liboctave.la \
-  ../libcruft/libcruft.la \
-  $(LIBOCTINTERP_LINK_DEPS)
-
-# Increment these as needed and according to the rules in the libtool manual:
-liboctinterp_current = 1
-liboctinterp_revision = 2
-liboctinterp_age = 0
-
-liboctinterp_version_info = $(liboctinterp_current):$(liboctinterp_revision):$(liboctinterp_age)
-
-liboctinterp_la_LDFLAGS = \
-  -version-info $(liboctinterp_version_info) \
-  $(NO_UNDEFINED_LDFLAG) \
-  -bindir $(bindir) \
-  $(LIBOCTINTERP_LINK_OPTS)
-
-display.df display.lo: CPPFLAGS += $(X11_FLAGS)
-
-octave_SOURCES = main.c
-
-octave_LDADD = \
-  liboctinterp.la \
-  ../liboctave/liboctave.la \
-  ../libcruft/libcruft.la \
-  $(OCTAVE_LINK_DEPS)
-
-octave_LDFLAGS = \
-  $(NO_UNDEFINED_LDFLAG) \
-  $(OCTAVE_LINK_OPTS)
-
-## Section for defining and creating DEF_FILES
-SRC_DEF_FILES := $(shell $(srcdir)/find-defun-files.sh "$(srcdir)" $(DIST_SRC))
-
-DLD_FUNCTIONS_DEF_FILES = $(DLD_FUNCTIONS_SRC:.cc=.df)
-
-## builtins.cc depends on $(DEF_FILES), so DEF_FILES should only include
-## .df files that correspond to sources included in liboctave.
-if AMCOND_ENABLE_DYNAMIC_LINKING
-  DEF_FILES = $(SRC_DEF_FILES)
-else
-  DEF_FILES = $(SRC_DEF_FILES) $(DLD_FUNCTIONS_DEF_FILES)
-endif
-
-ALL_DEF_FILES = $(SRC_DEF_FILES) $(DLD_FUNCTIONS_DEF_FILES)
-
-$(SRC_DEF_FILES): mkdefs Makefile
-
-$(DEF_FILES): $(OPT_HANDLERS) $(OPT_INC)
-
-DLL_CDEFS = @OCTINTERP_DLL_DEFS@
-DLL_CXXDEFS = @OCTINTERP_DLL_DEFS@
-
-## Rule to build a DEF file from a .cc file
-%.df: %.cc
-	$(CXXCPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
-	  $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) \
-	  -DMAKE_BUILTINS $< | $(srcdir)/mkdefs $(srcdir) $< > $@-t
-	mv $@-t $@
-
-## Override Automake's rule that forces a .hh extension on us even
-## though we don't want it.  It would be super awesome if automake
-## would allow users to choose the header file extension.
-.yy.cc:
-	$(am__skipyacc) $(SHELL) $(YLWRAP) $< y.tab.c $@ y.tab.h $*.h y.output $*.output -- $(YACCCOMPILE)
-
-## Special rules:
-## Mostly for sources which must be built before rest of compilation.
-
-## defaults.h and oct-conf.h must depend on Makefile.  Calling configure
-## may change default/config values.  However, calling configure will also
-## regenerate the Makefiles from Makefile.am and trigger the rules below.
-defaults.h: defaults.h.in Makefile
+if AMCOND_BUILD_COMPILED_AUX_PROGRAMS
+octave-config.cc: octave-config.in.cc Makefile
 	@$(do_subst_default_vals)
 
-graphics.h: graphics.h.in genprops.awk Makefile
-	$(AWK) -f $(srcdir)/genprops.awk $< > $@-t
-	mv $@-t $@
-
-oct-conf.h: oct-conf.h.in Makefile
+mkoctfile.cc: mkoctfile.in.cc Makefile
 	@$(do_subst_config_vals)
 
-## Don't use a pipeline to process gperf output since if gperf
-## is missing but sed is not, the exit status of the pipeline
-## will still be success and we will end up creating an empty
-## oct-gperf.h file.
-oct-gperf.h: octave.gperf
-	$(GPERF) -t -C -D -G -L C++ -Z octave_kw_hash $< > $@-t1
-	$(SED) 's,lookup\[,gperf_lookup[,' < $@-t1 > $@-t
-	mv $@-t $@
-	rm -f $@-t1
-
-mxarray.h: mxarray.h.in Makefile
-	$(SED) < $< \
-	  -e "s|%OCTAVE_IDX_TYPE%|${OCTAVE_IDX_TYPE}|" > $@-t
-	mv $@-t $@
-
-version.h: version.h.in Makefile
-	$(SED) < $< \
-	  -e "s|%OCTAVE_API_VERSION_NUMBER%|${OCTAVE_API_VERSION_NUMBER}|" \
-	  -e "s|%OCTAVE_API_VERSION%|\"${OCTAVE_API_VERSION}\"|" \
-	  -e "s|%OCTAVE_COPYRIGHT%|\"${OCTAVE_COPYRIGHT}\"|" \
-	  -e "s|%OCTAVE_RELEASE_DATE%|\"${OCTAVE_RELEASE_DATE}\"|" \
-	  -e "s|%OCTAVE_VERSION%|\"${OCTAVE_VERSION}\"|" > $@-t
-	mv $@-t $@
-
-builtins.cc: $(DEF_FILES) mkbuiltins
-	$(srcdir)/mkbuiltins $(DEF_FILES) > $@-t
-	mv $@-t $@
-
-graphics-props.cc: graphics.h.in genprops.awk Makefile
-	$(AWK) -v emit_graphics_props=1 -f $(srcdir)/genprops.awk $< > $@-t
-	mv $@-t $@
-
-ops.cc: $(OPERATORS_SRC) mkops
-	$(srcdir)/mkops $(OPERATORS_SRC) > $@-t
-	mv $@-t $@
-
-oct-errno.cc: oct-errno.cc.in Makefile
-	if test -n "$(PERL)"; then \
-	  $(srcdir)/mk-errno-list --perl "$(PERL)" < $< > $@-t; \
-	elif test -n "$(PYTHON)"; then \
-	  $(srcdir)/mk-errno-list --python "$(PYTHON)" < $< > $@-t; \
-	else \
-	  $(SED) '/@SYSDEP_ERRNO_LIST@/D' $< > $@-t; \
-	fi
-	mv $@-t $@
-
-$(OPT_HANDLERS) : %.cc : $(top_srcdir)/liboctave/%.in $(top_srcdir)/build-aux/mk-opts.pl
-	$(PERL) $(top_srcdir)/build-aux/mk-opts.pl --opt-handler-fcns $< > $@-t
-	mv $@-t $@
-
-$(OPT_INC) : %.h : %.in
-	$(MAKE) -C $(@D) $(@F)
-
-if AMCOND_ENABLE_DYNAMIC_LINKING
-DLD_FUNCTIONS_PKG_ADD_FILE = DLD-FUNCTIONS/PKG_ADD
-
-DLD-FUNCTIONS/PKG_ADD: $(DLD_FUNCTIONS_DEF_FILES) mk-pkg-add
-	$(srcdir)/mk-pkg-add $(DLD_FUNCTIONS_DEF_FILES) > $@-t
-	mv $@-t $@
-endif
-
-lex.lo lex.o oct-parse.lo oct-parse.o: \
-  AM_CXXFLAGS := $(filter-out -Wold-style-cast, $(AM_CXXFLAGS))
-
-__fltk_uigetfile__.lo __fltk_uigetfile__.o: \
-  AM_CXXFLAGS := $(filter-out $(DLL_CXXDEFS), $(AM_CXXFLAGS) $(GRAPHICS_CFLAGS))
-
-__init_fltk__.lo __init_fltk__.o: \
-  AM_CXXFLAGS := $(filter-out $(DLL_CXXDEFS), $(AM_CXXFLAGS) $(GRAPHICS_CFLAGS))
-
-if AMCOND_BUILD_DOCS
-.DOCSTRINGS: $(ALL_DEF_FILES) gendoc.pl
-	if [ "x$(srcdir)" != "x." ] && [ -f $(srcdir)/DOCSTRINGS ] && [ ! -f DOCSTRINGS ]; then \
-		cp $(srcdir)/DOCSTRINGS DOCSTRINGS; \
-		touch -r $(srcdir)/DOCSTRINGS DOCSTRINGS; \
-	fi
-	@echo "creating .DOCSTRINGS from .cc source files"
-	@$(PERL) $(srcdir)/gendoc.pl $(ALL_DEF_FILES) > $@
-	$(top_srcdir)/build-aux/move-if-change $@ DOCSTRINGS
-	touch $@
-
-all-local: $(OCT_STAMP_FILES) $(DLD_FUNCTIONS_PKG_ADD_FILE) .DOCSTRINGS
 else
-all-local: $(OCT_STAMP_FILES) $(DLD_FUNCTIONS_PKG_ADD_FILE)
-endif
-
-if AMCOND_BUILD_COMPILED_AUX_PROGRAMS
-octave-config.cc: octave-config.cc.in Makefile
-	@$(do_subst_default_vals)
-
-mkoctfile.cc: mkoctfile.cc.in Makefile
-	@$(do_subst_config_vals)
-else
-octave-config: octave-config.in Makefile
+octave-config: octave-config.in.sh Makefile
 	@$(do_subst_default_vals)
 	chmod a+rx $@
 
-mkoctfile: mkoctfile.in Makefile
+mkoctfile: mkoctfile.in.sh Makefile
 	@$(do_subst_config_vals)
 	chmod a+rx $@
 endif
 
 install-exec-hook: make-version-links
 
-install-data-hook: install-oct
-
-uninstall-local: remove-version-links uninstall-oct
+uninstall-local: remove-version-links
 
 make-version-links:
 	cd $(DESTDIR)$(bindir) && \
@@ -728,48 +161,5 @@
 
 .PHONY: make-version-links remove-version-links
 
-if AMCOND_ENABLE_DYNAMIC_LINKING
-install-oct:
-	$(top_srcdir)/build-aux/mkinstalldirs $(DESTDIR)$(octfiledir)
-	if [ -n "`cat $(DLD_FUNCTIONS_PKG_ADD_FILE)`" ]; then \
-	  $(INSTALL_DATA) $(DLD_FUNCTIONS_PKG_ADD_FILE) $(DESTDIR)$(octfiledir)/PKG_ADD; \
-	fi
-	cd $(DESTDIR)$(octlibdir) && \
-	for ltlib in $(DLD_FUNCTIONS_LIBS); do \
-	  f=`echo $$ltlib | $(SED) 's,.*/,,'`; \
-	  dl=`$(SED) -n -e "s/dlname='\([^']*\)'/\1/p" < $$f`; \
-	  if [ -n "$$dl" ]; then \
-	    $(INSTALL_PROGRAM) $$dl $(DESTDIR)$(octfiledir)/`echo $$f | $(SED) 's,^lib,,; s,\.la$$,.oct,'`; \
-	  else \
-	    echo "error: dlname is empty in $$ltlib!"; \
-	    exit 1; \
-	  fi; \
-	  lnames=`$(SED) -n -e "s/library_names='\([^']*\)'/\1/p" < $$f`; \
-	  if [ -n "$$lnames" ]; then \
-	    rm -f $$f $$lnames $$dl; \
-	  fi \
-	done
-
-uninstall-oct:
-	for f in $(notdir $(OCT_FILES)); do \
-	  rm -f $(DESTDIR)$(octfiledir)/$$f; \
-	done
-	rm -f $(DESTDIR)$(octfiledir)/PKG_ADD
-endif
-.PHONY: install-oct uninstall-oct
-
 CLEANFILES = \
-  $(bin_SCRIPTS) \
-  $(DLD_FUNCTIONS_PKG_ADD_FILE) \
-  graphics-props.cc \
-  oct-parse.output
-
-DISTCLEANFILES = \
-  .DOCSTRINGS \
-  DOCSTRINGS \
-  $(BUILT_NODISTFILES) \
-  $(OCT_FILES) \
-  $(OCT_STAMP_FILES)
-
-MAINTAINERCLEANFILES = \
-  $(BUILT_DISTFILES)
+  $(bin_SCRIPTS)
new file mode 100644
--- /dev/null
+++ b/src/main-cli.cc
@@ -0,0 +1,43 @@
+/*
+
+Copyright (C) 2012 John W. Eaton
+
+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 "defaults.h"
+#include "octave.h"
+#include "sysdep.h"
+
+int
+main (int argc, char **argv)
+{
+  octave_process_command_line (argc, argv);
+
+  sysdep_init ();
+
+  install_defaults ();
+
+  octave_initialize_interpreter (argc, argv, 0);
+
+  return octave_execute_interpreter ();
+}
deleted file mode 100644
--- a/src/main.c
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
-
-Copyright (C) 2002-2012 John W. Eaton
-
-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 "f77-fcn.h"
-#include "lo-ieee.h"
-
-#include "octave.h"
-
-int
-main (int argc, char **argv)
-{
-  return octave_main (argc, argv, 0);
-}
new file mode 100644
--- /dev/null
+++ b/src/main.cc
@@ -0,0 +1,53 @@
+/*
+
+Copyright (C) 2012 John W. Eaton
+
+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 "defaults.h"
+#include "octave.h"
+#include "octave-gui.h"
+#include "sysdep.h"
+
+int
+main (int argc, char **argv)
+{
+  int retval = 0;
+
+  octave_process_command_line (argc, argv);
+
+  sysdep_init ();
+
+  install_defaults ();
+
+  if (octave_starting_gui ())
+    retval = octave_start_gui (argc, argv);
+  else
+    {
+      octave_initialize_interpreter (argc, argv, 0);
+
+      retval = octave_execute_interpreter ();
+    }
+
+  return retval;
+}
rename from src/mkoctfile.cc.in
rename to src/mkoctfile.in.cc
--- a/src/mkoctfile.cc.in
+++ b/src/mkoctfile.in.cc
@@ -25,6 +25,7 @@
 #endif
 
 #include <string>
+#include <cstring>
 #include <map>
 #include <list>
 #include <algorithm>
@@ -48,11 +49,11 @@
 
 static string OCTAVE_VERSION = %OCTAVE_CONF_VERSION%;
 
-static std::string
-substitute_prefix (const std::string& s, const std::string& prefix,
-                   const std::string& new_prefix)
+static string
+substitute_prefix (const string& s, const string& prefix,
+                   const string& new_prefix)
 {
-  std::string retval = s;
+  string retval = s;
 
   if (!prefix.empty () && new_prefix != prefix)
     {
@@ -62,7 +63,7 @@
     }
 
 #if defined (__WIN32__) && ! defined (_POSIX_VERSION)
-  std::replace (retval.begin (), retval.end (), '/', '\\');
+  replace (retval.begin (), retval.end (), '/', '\\');
 #endif
 
   return retval;
@@ -72,7 +73,7 @@
 get_line (FILE *fp)
 {
   static vector<char> buf (100);
-  int idx = 0;
+  unsigned int idx = 0;
   char c;
 
   while (true)
@@ -123,7 +124,7 @@
 #if defined (__WIN32__) && ! defined (_POSIX_VERSION)
   int n = 1024;
 
-  std::string bin_dir (n, '\0');
+  string bin_dir (n, '\0');
 
   while (true)
     {
@@ -154,10 +155,10 @@
 
   vars["OCTAVE_PREFIX"] = %OCTAVE_CONF_PREFIX%;
 
-  std::string DEFAULT_OCTINCLUDEDIR = %OCTAVE_CONF_OCTINCLUDEDIR%;
-  std::string DEFAULT_INCLUDEDIR = %OCTAVE_CONF_INCLUDEDIR%;
-  std::string DEFAULT_LIBDIR = %OCTAVE_CONF_LIBDIR%;
-  std::string DEFAULT_OCTLIBDIR = %OCTAVE_CONF_OCTLIBDIR%;
+  string DEFAULT_OCTINCLUDEDIR = %OCTAVE_CONF_OCTINCLUDEDIR%;
+  string DEFAULT_INCLUDEDIR = %OCTAVE_CONF_INCLUDEDIR%;
+  string DEFAULT_LIBDIR = %OCTAVE_CONF_LIBDIR%;
+  string DEFAULT_OCTLIBDIR = %OCTAVE_CONF_OCTLIBDIR%;
 
   if (! vars["OCTAVE_HOME"].empty ())
     {
@@ -184,18 +185,18 @@
   vars["OCTLIBDIR"] = get_variable ("OCTLIBDIR", DEFAULT_OCTLIBDIR);
 
 #if defined (__WIN32__) && ! defined (_POSIX_VERSION)
-  std::string DEFAULT_INCFLAGS
+  string DEFAULT_INCFLAGS
     = "-I" + quote_path (vars["OCTINCLUDEDIR"] + "\\..")
     + " -I" + quote_path (vars["OCTINCLUDEDIR"]);
 #else
-  std::string DEFAULT_INCFLAGS
+  string DEFAULT_INCFLAGS
     = "-I" + quote_path (vars["OCTINCLUDEDIR"] + "/..")
     + " -I" + quote_path (vars["OCTINCLUDEDIR"]);
 #endif
   if (vars["INCLUDEDIR"] != "/usr/include")
     DEFAULT_INCFLAGS += " -I" + quote_path (vars["INCLUDEDIR"]);
 
-  std::string DEFAULT_LFLAGS = "-L" + quote_path (vars["OCTLIBDIR"]);
+  string DEFAULT_LFLAGS = "-L" + quote_path (vars["OCTLIBDIR"]);
   if (vars["LIBDIR"] != "/usr/lib")
     DEFAULT_LFLAGS += " -L" + quote_path (vars["LIBDIR"]);
 
@@ -226,7 +227,6 @@
   vars["LIBOCTAVE"] = "-loctave";
   vars["LIBOCTINTERP"] = "-loctinterp";
   vars["READLINE_LIBS"] = "-lreadline";
-  vars["LIBCRUFT"] = "-lcruft";
   vars["LAPACK_LIBS"] = get_variable ("LAPACK_LIBS", %OCTAVE_CONF_LAPACK_LIBS%);
   vars["BLAS_LIBS"] = get_variable ("BLAS_LIBS", %OCTAVE_CONF_BLAS_LIBS%);
   vars["FFTW3_LDFLAGS"] = get_variable ("FFTW3_LDFLAGS", %OCTAVE_CONF_FFTW3_LDFLAGS%);
@@ -257,7 +257,7 @@
     + " " + vars["LDFLAGS"];
 
   vars["OCTAVE_LIBS"] = vars["LIBOCTINTERP"] + " " + vars["LIBOCTAVE"]
-    + " " + vars["SPECIAL_MATH_LIB"] + " " + vars["LIBCRUFT"];
+    + " " + vars["SPECIAL_MATH_LIB"];
 
   vars["FFTW_LIBS"] = vars["FFTW3_LDFLAGS"] + " " + vars["FFTW3_LIBS"]
     + " " + vars["FFTW3F_LDFLAGS"] + " " + vars["FFTW3F_LIBS"];
@@ -355,21 +355,23 @@
 static string
 basename (const string& s, bool strip_path = false)
 {
+  string retval;
   size_t pos = s.rfind ('.');
-  string retval;
 
   if (pos == string::npos)
     retval = s;
   else
     retval = s.substr (0, pos);
+
   if (strip_path)
     {
       size_t p1 = retval.rfind ('/'), p2 = retval.rfind ('\\');
       pos = (p1 != string::npos && p2 != string::npos
              ? max (p1, p2) : (p2 != string::npos ? p2 : p1));
       if (pos != string::npos)
-        retval = retval.substr (0, pos);
+        retval = retval.substr (++pos, string::npos);
     }
+
   return retval;
 }
 
@@ -436,7 +438,6 @@
   for (int i = 1; i < argc; i++)
     {
       string arg = argv[i];
-      size_t len = arg.length ();
 
       if (ends_with (arg, ".c"))
         {
@@ -608,13 +609,13 @@
 
           FILE *fd = popen (cmd.c_str (), "r");
           ofstream fo (dfile.c_str ());
-          int pos;
+          size_t pos;
           while (!feof (fd))
             {
               line = get_line (fd);
               if ((pos = line.rfind (".o:")) != string::npos)
                 {
-                  int spos = line.rfind ('/', pos);
+                  size_t spos = line.rfind ('/', pos);
                   string ofile = (spos == string::npos ? line.substr (0, pos+2) : line.substr (spos+1, pos-spos+1));
                   fo << "pic/" << ofile << " " << ofile << " " << dfile << line.substr (pos) << endl;
                 }
@@ -636,13 +637,13 @@
 
           FILE *fd = popen (cmd.c_str (), "r");
           ofstream fo (dfile.c_str ());
-          int pos;
+          size_t pos;
           while (!feof (fd))
             {
               line = get_line (fd);
               if ((pos = line.rfind (".o:")) != string::npos)
                 {
-                  int spos = line.rfind ('/', pos);
+                  size_t spos = line.rfind ('/', pos);
                   string ofile = (spos == string::npos ? line.substr (0, pos+2) : line.substr (spos+1, pos-spos+1));
                   fo << "pic/" << ofile << " " << ofile << " " << dfile << line.substr (pos+2) << endl;
                 }
@@ -753,7 +754,7 @@
                 + " " + vars["ALL_LDFLAGS"] + " " +  pass_on_options
                 + " " + output_option + " " + objfiles + " " + libfiles
                 + " " + ldflags + " " + vars["LFLAGS"]
-                + " -loctinterp -loctave -lcruft "
+                + " -loctinterp -loctave "
                 + " " + vars["OCT_LINK_OPTS"]
                 + " " + vars["OCTAVE_LINK_DEPS"];
               result = run_command (cmd);
@@ -770,7 +771,7 @@
           string cmd = vars["DL_LD"] + " " + vars["DL_LDFLAGS"] + " "
             + pass_on_options + " -o " + octfile + " " + objfiles + " "
             + libfiles + " " + ldflags + " " + vars["LFLAGS"]
-            + " -loctinterp -loctave -lcruft "
+            + " -loctinterp -loctave "
             + vars["OCT_LINK_OPTS"] + " " + vars["OCT_LINK_DEPS"];
           result = run_command (cmd);
         }
rename from src/mkoctfile.in
rename to src/mkoctfile.in.sh
--- a/src/mkoctfile.in
+++ b/src/mkoctfile.in.sh
@@ -92,7 +92,6 @@
 : ${LIBOCTAVE=-loctave}
 : ${LIBOCTINTERP=-loctinterp}
 : ${READLINE_LIBS=-lreadline}
-: ${LIBCRUFT=-lcruft}
 : ${LAPACK_LIBS=%OCTAVE_CONF_LAPACK_LIBS%}
 : ${BLAS_LIBS=%OCTAVE_CONF_BLAS_LIBS%}
 : ${FFTW3_LDFLAGS=%OCTAVE_CONF_FFTW3_LDFLAGS%}
@@ -119,7 +118,7 @@
 
 : ${ALL_LDFLAGS="$LD_STATIC_FLAG $CPICFLAG $LDFLAGS"}
 
-: ${OCTAVE_LIBS="$LIBOCTINTERP $LIBOCTAVE $SPECIAL_MATH_LIB $LIBCRUFT"}
+: ${OCTAVE_LIBS="$LIBOCTINTERP $LIBOCTAVE $SPECIAL_MATH_LIB"}
 
 # Local variables.
 
@@ -260,7 +259,7 @@
                             FFLAGS                    XTRA_CFLAGS
                             FFTW3_LDFLAGS             XTRA_CXXFLAGS
                             FFTW3_LIBS
-
+                          
 
   -v, --verbose           Echo commands as they are executed.
 
@@ -537,7 +536,7 @@
 if $link && [ -n "$objfiles" ]; then
   if $link_stand_alone; then
     if [ -n "$LD_CXX" ]; then
-      cmd="$LD_CXX $CPPFLAGS $ALL_CXXFLAGS $RDYNAMIC_FLAG $ALL_LDFLAGS $pass_on_options $output_option $objfiles $libfiles $ldflags $LFLAGS -loctinterp -loctave -lcruft $OCTAVE_LINK_OPTS $OCTAVE_LINK_DEPS"
+      cmd="$LD_CXX $CPPFLAGS $ALL_CXXFLAGS $RDYNAMIC_FLAG $ALL_LDFLAGS $pass_on_options $output_option $objfiles $libfiles $ldflags $LFLAGS -loctinterp -loctave $OCTAVE_LINK_OPTS $OCTAVE_LINK_DEPS"
       $dbg $cmd
       eval $cmd
     else
@@ -545,7 +544,7 @@
       exit 1
     fi
   else
-    cmd="$DL_LD $DL_LDFLAGS $pass_on_options -o $octfile $objfiles $libfiles $ldflags $LFLAGS -loctinterp -loctave -lcruft $OCT_LINK_OPTS $OCT_LINK_DEPS"
+    cmd="$DL_LD $DL_LDFLAGS $pass_on_options -o $octfile $objfiles $libfiles $ldflags $LFLAGS -loctinterp -loctave $OCT_LINK_OPTS $OCT_LINK_DEPS"
     $dbg $cmd
     eval $cmd
   fi
rename from src/octave-config.cc.in
rename to src/octave-config.in.cc
--- a/src/octave-config.cc.in
+++ b/src/octave-config.in.cc
@@ -167,7 +167,7 @@
   vars["OCTFILEDIR"] =substitute_prefix (%OCTAVE_OCTFILEDIR%, PREFIX, OCTAVE_HOME);
   vars["OCTINCLUDEDIR"] =substitute_prefix (%OCTAVE_OCTINCLUDEDIR%, PREFIX, OCTAVE_HOME);
   vars["OCTLIBDIR"] =substitute_prefix (%OCTAVE_OCTLIBDIR%, PREFIX, OCTAVE_HOME);
-  vars["PREFIX"] = (OCTAVE_HOME.empty() ? PREFIX : OCTAVE_HOME);
+  vars["PREFIX"] = (OCTAVE_HOME.empty () ? PREFIX : OCTAVE_HOME);
   vars["STARTUPFILEDIR"] =substitute_prefix (%OCTAVE_STARTUPFILEDIR%, PREFIX, OCTAVE_HOME);
   vars["VERSION"] = %OCTAVE_VERSION%;
 }
rename from src/octave-config.in
rename to src/octave-config.in.sh
--- a/test/Makefile.am
+++ b/test/Makefile.am
@@ -1,4 +1,4 @@
-# Makefile for octave's test directory
+# Makefile for Octave's test directory
 #
 # Copyright (C) 1994-2012 John W. Eaton
 #
@@ -22,62 +22,83 @@
 
 FCN_FILES = \
   fntests.m \
-  test_args.m \
-  test_diag_perm.m \
-  test_error.m \
-  test_eval-catch.m \
-  test_for.m \
-  test_func.m \
-  test_global.m \
-  test_if.m \
-  test_index.m \
-  test_io.m \
-  test_line_continue.m \
-  test_logical_index.m \
-  test_null_assign.m \
-  test_parser.m \
-  test_prefer.m \
-  test_range.m \
-  test_recursion.m \
-  test_return.m \
-  test_slice.m \
-  test_struct.m \
-  test_switch.m \
-  test_system.m \
-  test_transpose.m \
-  test_try.m \
-  test_unwind.m \
-  test_while.m
+  args.tst \
+  bug-31371.tst \
+  bug-38576.tst \
+  diag-perm.tst \
+  error.tst \
+  eval-catch.tst \
+  for.tst \
+  func.tst \
+  global.tst \
+  if.tst \
+  index.tst \
+  io.tst \
+  line-continue.tst \
+  logical-index.tst \
+  null-assign.tst \
+  parser.tst \
+  prefer.tst \
+  range.tst \
+  recursion.tst \
+  return.tst \
+  slice.tst \
+  struct.tst \
+  switch.tst \
+  system.tst \
+  transpose.tst \
+  try.tst \
+  unwind.tst \
+  while.tst
 
+include bug-35448/module.mk
+include bug-36025/module.mk
+include bug-38236/module.mk
 include classes/module.mk
 include class-concat/module.mk
 include ctor-vs-method/module.mk
 include fcn-handle-derived-resolution/module.mk
+include nest/module.mk
 
-check: test_sparse.m test_bc_overloads.m
+check: sparse.tst bc-overload-tests.stamp
 	$(top_builddir)/run-octave --norc --silent --no-history $(srcdir)/fntests.m $(srcdir)
 
-test_sparse.m: build_sparse_tests.sh
-	$(srcdir)/build_sparse_tests.sh
+sparse.tst: build-sparse-tests.sh
+	$(srcdir)/build-sparse-tests.sh
+
+GENERATED_BC_OVERLOADS_DIRS := \
+  $(shell $(srcdir)/build-bc-overload-tests.sh --list-dirs)
 
-test_bc_overloads.m: build_bc_overload_tests.sh bc_overloads_expected
-	$(srcdir)/build_bc_overload_tests.sh $(srcdir)/bc_overloads_expected
+GENERATED_BC_OVERLOADS_FILES := \
+  $(shell $(srcdir)/build-bc-overload-tests.sh --list-files)
+
+bc-overload-tests.stamp: build-bc-overload-tests.sh bc-overloads-expected
+	$(srcdir)/build-bc-overload-tests.sh $(srcdir)/bc-overloads-expected
+	touch $@
+
+BUILT_SOURCES = bc-overload-tests.stamp
 
 EXTRA_DIST = \
-  build_sparse_tests.sh \
-  build_bc_overload_tests.sh \
-  bc_overloads_expected \
+  build-sparse-tests.sh \
+  build-bc-overload-tests.sh \
+  bc-overloads-expected \
   build_bc_overloads_expected.m \
   $(FCN_FILES)
 
 CLEANFILES = \
-  test_sparse.m \
-  test_bc_overloads.m \
-  tbcover.m
+  sparse.tst \
+  bc-overload-tests.stamp \
+  $(GENERATED_BC_OVERLOADS_FILES)
 
 DISTCLEANFILES = \
   fntests.log
-        
+
+fixedtestsdir := $(octtestsdir)/fixed
+
+nobase_fixedtests_DATA = \
+  sparse.tst \
+  $(GENERATED_BC_OVERLOADS_FILES) \
+  $(filter-out fntests.m, $(FCN_FILES))
+
 clean-local:
-	-rm -rf @double @logical @int8 @uint64 @int64 @cell @single @int32 \
-	@uint8 @uint16 @uint32 @struct @int16 @function_handle @char
+	-rm -rf $(GENERATED_BC_OVERLOADS_DIRS)
rename from test/test_args.m
rename to test/args.tst
rename from test/bc_overloads_expected
rename to test/bc-overloads-expected
new file mode 100644
--- /dev/null
+++ b/test/bug-31371.tst
@@ -0,0 +1,41 @@
+%!test
+%! % Work around MATLAB bug where f(x)(y) is invalid syntax
+%! % (This bug does not apply to Octave)
+%!
+%! C = @(fcn,x) fcn(x);
+%! C2 = @(fcn,x,y) fcn(x,y);
+%!
+%! % Church Booleans
+%! T = @(t,f) t;
+%! F = @(t,f) f;
+%!
+%! % Church Numerals
+%! Zero  = @(fcn,x) x;
+%! One   = @(fcn,x) fcn(x);
+%! Two   = @(fcn,x) fcn(fcn(x));
+%! Three = @(fcn,x) fcn(fcn(fcn(x)));
+%! Four  = @(fcn,x) fcn(fcn(fcn(fcn(x))));
+%!
+%! % Arithmetic Operations
+%! Inc = @(a) @(f,x) f(a(f,x)); % Increment
+%! Add = @(a,b) @(f,x) a(f,b(f,x));
+%! Mult = @(a,b) @(f,x) a(@(x) b(f,x),x);
+%! Dec = @(a) @(f,x) C(a(@(g) @(h) h(g(f)), @(u) x), @(u) u); % Decrement
+%! Sub = @(a,b) b(Dec, a);
+%!
+%! % Renderer - Convert church numeral to "real" number
+%! Render = @(n) n(@(n) n+1,0);
+%!
+%! % Predicates
+%! Iszero = @(n) n(@(x) F, T);
+%!
+%! % Y combinator implements recursion
+%! Ycomb = @(f) C(@(g) f(@(x) C(g(g), x)), ...
+%!                @(g) f(@(x) C(g(g), x)));
+%!
+%! Factorial = Ycomb(@(f) @(n) C(C2(Iszero(n), ...
+%!                   @(d) One, @(d) Mult(n, f(Dec(n)))),0));
+%!
+%! assert (Render (Factorial (Two)), 2)
+%! assert (Render (Factorial (Three)), 6)
+%! assert (Render (Factorial (Four)), 24)
new file mode 100644
--- /dev/null
+++ b/test/bug-35448/bug-35448.tst
@@ -0,0 +1,11 @@
+%!test
+%! global gfun
+%! gfun = @fB;
+%! y = fA (e);
+%! assert (y, e);
+
+%!test
+%! global gfun
+%! gfun = @fC;
+%! y = fA (e);
+%! assert (y, e);
new file mode 100644
--- /dev/null
+++ b/test/bug-35448/fA.m
@@ -0,0 +1,10 @@
+# fA.m
+function y = fA (x, f)
+  global gfun
+  if nargin < 2
+    y = fA (x, gfun);
+  else
+    w = feval (f, x);
+    y = feval (@fB, w);
+  endif
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/bug-35448/fB.m
@@ -0,0 +1,4 @@
+# fB.m
+function y = fB (x)
+  y = x;
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/bug-35448/fC.m
@@ -0,0 +1,4 @@
+# fC.m
+function y = fC (x)
+  y = x;
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/bug-35448/module.mk
@@ -0,0 +1,7 @@
+bug_35448_FCN_FILES = \
+  bug-35448/fA.m \
+  bug-35448/fB.m \
+  bug-35448/fC.m \
+  bug-35448/bug-35448.tst
+
+FCN_FILES += $(bug_35448_FCN_FILES)
new file mode 100644
--- /dev/null
+++ b/test/bug-36025/@testclass/one.m
@@ -0,0 +1,5 @@
+% function ONE return item "X"
+
+function a = one (m)
+  a = m.x;
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/bug-36025/@testclass/testclass.m
@@ -0,0 +1,4 @@
+function m = testclass (x,y)
+  m = struct ('x',x,'y',y);
+  m = class (m,"testclass");
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/bug-36025/@testclass/two.m
@@ -0,0 +1,5 @@
+% function TWO returns item "Y"
+
+function a = one (m)
+  a = m.y;
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/bug-36025/bug-36025.tst
@@ -0,0 +1,9 @@
+%!test
+%! warning off Octave:function-name-clash
+%! f = testclass (1, 2);
+%! assert (one (f), 1);
+%! assert (two (f), 2);
+%! rehash ();
+%! assert (one (f), 1);
+%! assert (two (f), 2);
+%! assert (two (f), 2);
new file mode 100644
--- /dev/null
+++ b/test/bug-36025/module.mk
@@ -0,0 +1,7 @@
+bug_36025_FCN_FILES = \
+  bug-36025/@testclass/one.m \
+  bug-36025/@testclass/testclass.m \
+  bug-36025/@testclass/two.m \
+  bug-36025/bug-36025.tst
+
+FCN_FILES += $(bug_36025_FCN_FILES)
new file mode 100644
--- /dev/null
+++ b/test/bug-38236/bug-38236.tst
@@ -0,0 +1,3 @@
+%!test
+%! u_vr
+
new file mode 100644
--- /dev/null
+++ b/test/bug-38236/df_vr.m
@@ -0,0 +1,2 @@
+# df_vr.m
+vr = 7;
new file mode 100644
--- /dev/null
+++ b/test/bug-38236/module.mk
@@ -0,0 +1,6 @@
+bug_38236_FCN_FILES = \
+  bug-38236/df_vr.m \
+  bug-38236/u_vr.m \
+  bug-38236/bug-38236.tst
+
+FCN_FILES += $(bug_38236_FCN_FILES)
new file mode 100644
--- /dev/null
+++ b/test/bug-38236/u_vr.m
@@ -0,0 +1,12 @@
+# u_vr.m
+
+## define and exectute "__demo__" once
+eval ("function __demo__ ();  df_vr;  v = vr * 2; endfunction");
+__demo__;
+
+## clear definition of "__demo__"
+clear __demo__
+
+## define and exectute "__demo__" once more
+eval ("function __demo__ ();  df_vr;  v = vr * 2; endfunction");
+__demo__;
new file mode 100644
--- /dev/null
+++ b/test/bug-38565.tst
@@ -0,0 +1,9 @@
+%!function r = f (x)
+%!  if (ischar (x))
+%!    r = x;
+%!  else
+%!    error ("expecting character string");
+%!  endif
+%!endfunction
+
+%!assert (eval ("f 10;"), "10");
new file mode 100644
--- /dev/null
+++ b/test/bug-38576.tst
@@ -0,0 +1,16 @@
+%!function r = f1 ()
+%!  ls = svd (1);
+%!  r = eval ("ls -1;");
+%!endfunction
+%!function r = f2 ()
+%!  [u,ls,v] = svd (1);
+%!  r = eval ("ls -1;");
+%!endfunction
+%!function r = f3 (ls)
+%!  r = eval ("ls -1;");
+%!endfunction
+
+%!assert (f1 (), 0);
+%!assert (f2 (), 0);
+%!assert (ischar (f3 ()), true);
+%!assert (f3 (1), 0);
rename from test/build_bc_overload_tests.sh
rename to test/build-bc-overload-tests.sh
--- a/test/build_bc_overload_tests.sh
+++ b/test/build-bc-overload-tests.sh
@@ -37,7 +37,29 @@
 "
 
 if [ $# -eq 1 ]; then
-  expected_results_file="$1"
+  case "$1" in
+    --list-files)
+      echo tbcover.m
+      echo bc-overloads.tst
+      for class in $CLASSES; do
+        echo @$class/tbcover.m
+      done
+      exit
+    ;;
+    --list-dirs)
+      for class in $CLASSES; do
+        echo @$class
+      done
+      exit
+    ;;
+    --list-classes)
+      echo $CLASSES
+      exit
+    ;;
+    *)
+      expected_results_file="$1"
+    ;;
+  esac
 else
   echo "usage: build_bc_overload_tests.sh expected-results-file" 1>&2
   exit 1
@@ -65,14 +87,14 @@
   exit
 fi
 
-cat > test_bc_overloads.m << EOF
+cat > bc-overloads.tst << EOF
 ## !!! DO NOT EDIT !!!
 ## THIS IS AN AUTOMATICALLY GENERATED FILE
 ## modify build_bc_overload_tests.sh to generate the tests you need.
 
 %!shared ex
 %! ex.double = 1;
-%! ex.single = single(1);
+%! ex.single = single (1);
 %! ex.logical = true;
 %! ex.char = 'char';
 %! ex.int8  = int8 (1);
@@ -91,7 +113,7 @@
 
 cat $expected_results_file | \
 while read cl1 cl2 clr ; do
-  cat >> test_bc_overloads.m << EOF
+  cat >> bc-overloads.tst << EOF
 %% Name call
 %!assert (tbcover (ex.$cl1, ex.$cl2), "$clr")
 %% Handle call
@@ -100,7 +122,7 @@
 EOF
 done
 
-cat >> test_bc_overloads.m << EOF
+cat >> bc-overloads.tst << EOF
 %%test handles through cellfun
 %!test
 %! f = fieldnames (ex);
rename from test/build_sparse_tests.sh
rename to test/build-sparse-tests.sh
--- a/test/build_sparse_tests.sh
+++ b/test/build-sparse-tests.sh
@@ -19,15 +19,15 @@
 # <http://www.gnu.org/licenses/>.
 
 # Some tests are commented out because they are known to be broken!
-# Search for "# fails"   
+# Search for "# fails"
 
 # ./build_sparse_tests.sh preset
-#    creates test_sparse.m with preset tests.
-#    Use "test test_sparse" from octave to run the tests.
+#    creates sparse.tst with preset tests.
+#    Use "test sparse.tst" from octave to run the tests.
 #
 # ./build_sparse_tests.sh random
-#    Creates test_sprandom.m with randomly generated matrices.
-#    Use "test test_sprandom" from octave to run the tests.
+#    Creates sprandom.tst with randomly generated matrices.
+#    Use "test sprandom.tst" from octave to run the tests.
 
 # build_sparse_tests.sh generates tests for real and complex sparse matrices.
 # Also, we want to run both fixed tests with known outputs (quick tests)
@@ -36,13 +36,13 @@
 # uses randomly generated matrices.
 #
 # The tests are mostly identical for each case but the code is different,
-# so it is important that the tests be run on all cases.  Because our test 
+# so it is important that the tests be run on all cases.  Because our test
 # harness doesn't have support for looping or macros (it is only needed
 # for new data types), but sh does, we use sh to generate inline versions of
 # the tests for each case.
 #
 # Our 'macros' use shared variables as parameters.  This allows us to
-# for example define A complex and include all the unary ops tests, 
+# for example define A complex and include all the unary ops tests,
 # then set A=real(A) and include all the unary ops tests.  Thus the
 # same tests work for real and complex.  For binary tests it is even
 # more complicated because we want full X sparse, sparse X full and
@@ -59,7 +59,7 @@
 #    helper gen_eat_zeros
 #        make sure sparse-scalar ops which generate 0 work
 #    gen_specific_tests
-#        specific and eat zeros tests 
+#        specific and eat zeros tests
 #    helper gen_ordering_tests
 #        ordered comparison operators for real valued tests
 #    helper gen_sparsesparse_ordering_tests
@@ -71,12 +71,12 @@
 #        element-wise matrix binary operators, for sparse-sparse ops.
 #        horizontal/vertical concatenation are here as well.
 #    helper gen_divop_tests
-#        left and right matrix division operators of rectangular matrices. 
+#        left and right matrix division operators of rectangular matrices.
 #        Needs QR solvers
 #    helper gen_square_divop_tests
-#        left and right matrix division operators of square matrices. 
+#        left and right matrix division operators of square matrices.
 #    helper gen_matrixop_tests
-#        rectangular matrix binary operators: * 
+#        rectangular matrix binary operators: *
 #    helper gen_matrixdiag_tests
 #        Tests extract of diag and creation of diagonal matrices using
 #        diag and spdiags functions
@@ -114,9 +114,9 @@
 esac
 
 if $preset; then
-    TESTS=test_sparse.m
+    TESTS=sparse.tst
 else
-    TESTS=test_sprandom.m
+    TESTS=sprandom.tst
 fi
 
 # create initial file
@@ -146,7 +146,7 @@
 # Specific preset tests
 
 # =======================================================
-# If a sparse operation yields zeros, then those elements 
+# If a sparse operation yields zeros, then those elements
 # of the returned sparse matrix should be eaten.
 gen_eat_zeros() {
 cat >>$TESTS <<EOF
@@ -175,14 +175,14 @@
 
 %!test # segfault test from edd@debian.org
 %! n = 510;
-%! sparse (kron ((1:n)', ones(n,1)), kron (ones(n,1), (1:n)'), ones (n)); 
+%! sparse (kron ((1:n)', ones (n,1)), kron (ones (n,1), (1:n)'), ones (n));
 
 %% segfault tests from Fabian@isas-berlin.de
 %% Note that the last four do not fail, but rather give a warning
 %% of a singular matrix, which is consistent with the full matrix
 %% behaviour.  They are therefore disabled.
 %!testif HAVE_UMFPACK
-%! assert (inv (sparse ([1,1;1,1+i])), sparse([1-1i,1i;1i,-1i]), 10*eps);
+%! assert (inv (sparse ([1,1;1,1+i])), sparse ([1-1i,1i;1i,-1i]), 10*eps);
 %#!error inv ( sparse ([1,1;1,1]  ) );
 %#!error inv ( sparse ([0,0;0,1]  ) );
 %#!error inv ( sparse ([0,0;0,1+i]) );
@@ -238,7 +238,7 @@
 ##    run preset sparse tests.  All should pass.
 function [passes, tests] = test_sparse
   disp ("writing test output to sptest.log");
-  test ("test_sparse", "normal", "sptest.log");
+  test ("sparse.tst", "normal", "sptest.log");
 endfunction
 
 EOF
@@ -258,14 +258,14 @@
   warning ("untested --- fix the source in build_sparse_tests.sh");
   disp ("appending test output to sprandomtest.log");
   fid = fopen ("sprandomtest.log", "at");
-  test ("test_sprandom", "normal", fid);
-  ##[passes, total] = test("sprandomtest","normal",fid);
+  test ("sprandom.tst", "normal", fid);
+  ##[passes, total] = test ("sprandomtest", "normal", fid);
   fclose (fid);
 endfunction
 
 EOF
     fi
-    
+
 }
 
 
@@ -405,7 +405,7 @@
 %!assert (diag (as(:)',-1), sparse (diag (af(:)',-1)))
 %!assert (spdiags (as,[0,1]), [diag(af,0), diag(af,1)])
 %!test
-%! [tb,tc]=spdiags(as); 
+%! [tb,tc] = spdiags (as);
 %! assert (spdiags (tb,tc,sparse (zeros (size (as)))), as);
 %! assert (spdiags (tb,tc,size (as,1),size (as,2)), as);
 
@@ -416,12 +416,12 @@
 gen_matrixreshape_tests() {
     cat >>$TESTS <<EOF
 %% Matrix diagonal tests (uses af,as,bf,bs)
-%!assert(reshape(as,1,prod(size(as))),sparse(reshape(af,1,prod(size(af)))))
-%!assert(reshape(as,prod(size(as)),1),sparse(reshape(af,prod(size(af)),1)))
-%!assert(reshape(as,fliplr(size(as))),sparse(reshape(af,fliplr(size(af)))))
-%!assert(reshape(bs,1,prod(size(as))),sparse(reshape(bf,1,prod(size(af)))))
-%!assert(reshape(bs,prod(size(as)),1),sparse(reshape(bf,prod(size(af)),1)))
-%!assert(reshape(bs,fliplr(size(as))),sparse(reshape(bf,fliplr(size(af)))))
+%!assert (reshape (as,1,prod(size(as))), sparse (reshape (af,1,prod(size(af)))))
+%!assert (reshape (as,prod(size(as)),1), sparse (reshape (af,prod(size(af)),1)))
+%!assert (reshape (as,fliplr(size(as))), sparse (reshape (af,fliplr(size(af)))))
+%!assert (reshape (bs,1,prod(size(as))), sparse (reshape (bf,1,prod(size(af)))))
+%!assert (reshape (bs,prod(size(as)),1), sparse (reshape (bf,prod(size(af)),1)))
+%!assert (reshape (bs,fliplr(size(as))), sparse (reshape (bf,fliplr(size(af)))))
 
 EOF
 }
@@ -552,7 +552,7 @@
 %!assert (cumprod (as,2), sparse (cumprod (af,2)))
 
 %!assert (min (as), sparse (min (af)))
-%!assert (full (min (as(:))),min (af(:)))
+%!assert (full (min (as(:))), min (af(:)))
 %!assert (min (as,[],1), sparse (min (af,[],1)))
 %!assert (min (as,[],2), sparse (min (af,[],2)))
 %!assert (min (as,[],1), sparse (min (af,[],1)))
@@ -582,8 +582,8 @@
 %!assert (as',  sparse (af'));
 %!assert (-as, sparse (-af));
 %!assert (~as, sparse (~af));
-%!error [i,j]=size (af);as(i-1,j+1);
-%!error [i,j]=size (af);as(i+1,j-1);
+%!error [i,j] = size (af);as(i-1,j+1);
+%!error [i,j] = size (af);as(i+1,j-1);
 %!test
 %! [Is,Js,Vs] = find (as);
 %! [If,Jf,Vf] = find (af);
@@ -635,9 +635,9 @@
 
     cat >>$TESTS <<EOF
 %!testif HAVE_UMFPACK
-%! assert(det(bs+speye(size(bs))),det(bf+eye(size(bf))),100*eps*abs(det(bf+eye(size(bf)))))
+%! assert(det(bs+speye(size(bs))), det(bf+eye(size(bf))), 100*eps*abs(det(bf+eye(size(bf)))))
 
-%!testif HAVE_UMFPACK 
+%!testif HAVE_UMFPACK
 %! [l,u] = lu (sparse ([1,1;1,1]));
 %! assert (l*u, [1,1;1,1], 10*eps);
 
@@ -701,7 +701,7 @@
     cat >>$TESTS <<EOF
 %!testif HAVE_CHOLMOD
 %! assert (chol (bs)'*chol (bs), bs, 1e-10);
-%!testif HAVE_CHOLMOD 
+%!testif HAVE_CHOLMOD
 %! assert (chol (bs,'lower')*chol (bs,'lower')', bs, 1e-10);
 %!testif HAVE_CHOLMOD
 %! assert (chol (bs,'lower'), chol (bs)', 1e-10);
@@ -727,19 +727,19 @@
 
 # test scalar operations: uses af and real scalar bf; modifies as,bf,bs
 gen_scalar_tests() {
-    echo '%!test as=sparse(af);' >> $TESTS
-    echo '%!test bs=bf;' >> $TESTS
+    echo '%!test as = sparse (af);' >> $TESTS
+    echo '%!test bs = bf;' >> $TESTS
     gen_elementop_tests
     gen_ordering_tests
-    echo '%!test bf=bf+1i;' >>$TESTS
-    echo '%!test bs=bf;' >> $TESTS
+    echo '%!test bf = bf+1i;' >>$TESTS
+    echo '%!test bs = bf;' >> $TESTS
     gen_elementop_tests
 }
 
 # test matrix operations: uses af and bf; modifies as,bs
 gen_rectangular_tests() {
-    echo '%!test as=sparse(af);' >> $TESTS
-    echo '%!test bs=sparse(bf);' >>$TESTS
+    echo '%!test as = sparse(af);' >> $TESTS
+    echo '%!test bs = sparse(bf);' >>$TESTS
     gen_mapper_tests
     gen_real_mapper_tests
     gen_unaryop_tests
@@ -806,7 +806,7 @@
 %! funiq = fsum = zeros (m,n);
 %! funiq(r(:) + m*(c(:)-1) ) = ones (size (r(:)));
 %! funiq = sparse (funiq);
-%! for k=1:length(r)
+%! for k=1:length (r)
 %!   fsum(r(k),c(k)) += 1;
 %! endfor
 %! fsum = sparse (fsum);
@@ -847,7 +847,7 @@
 
 gen_select_tests() {
     cat >>$TESTS <<EOF
-%!test as=sparse(af);
+%!test as = sparse (af);
 
 %% Point tests
 %!test idx = ridx(:) + rows (as) * (cidx (:)-1);
@@ -875,16 +875,16 @@
 
 %% Assignment test
 %!test
-%! ts=as; ts(:,:) = ts(fliplr (1:size (as,1)),:);
-%! tf=af; tf(:,:) = tf(fliplr (1:size (af,1)),:);
+%! ts = as; ts(:,:) = ts(fliplr (1:size (as,1)),:);
+%! tf = af; tf(:,:) = tf(fliplr (1:size (af,1)),:);
 %! assert (ts, sparse (tf));
 %!test
-%! ts=as; ts(fliplr (1:size (as,1)),:) = ts;
-%! tf=af; tf(fliplr (1:size (af,1)),:) = tf;
+%! ts = as; ts(fliplr (1:size (as,1)),:) = ts;
+%! tf = af; tf(fliplr (1:size (af,1)),:) = tf;
 %! assert (ts, sparse (tf));
 %!test
-%! ts=as; ts(:,fliplr (1:size (as,2))) = ts;
-%! tf=af; tf(:,fliplr (1:size (af,2))) = tf;
+%! ts = as; ts(:,fliplr (1:size (as,2))) = ts;
+%! tf = af; tf(:,fliplr (1:size (af,2))) = tf;
 %! assert (ts, sparse (tf));
 %!test
 %! ts(fliplr (1:size (as,1))) = as(:,1);
@@ -893,10 +893,10 @@
 
 %% Deletion tests
 %!test
-%! ts=as; ts(1,:)=[]; tf=af; tf(1,:)=[];
+%! ts = as; ts(1,:) = []; tf = af; tf(1,:) = [];
 %! assert (ts, sparse (tf));
 %!test
-%! ts=as; ts(:,1)=[]; tf=af; tf(:,1)=[];
+%! ts = as; ts(:,1) = []; tf = af; tf(:,1) = [];
 %! assert (ts, sparse (tf));
 
 %% Test "end" keyword
@@ -921,7 +921,7 @@
 %! clear as_save;
 %! load (savefile, "as_save");
 %! unlink (savefile);
-%! assert (as_save, sparse(af));
+%! assert (as_save, sparse (af));
 %!test # save binary
 %! savefile = tmpnam ();
 %! as_save = as;
@@ -929,7 +929,7 @@
 %! clear as_save;
 %! load (savefile, "as_save");
 %! unlink (savefile);
-%! assert (as_save, sparse(af));
+%! assert (as_save, sparse (af));
 %!testif HAVE_HDF5   # save hdf5
 %! savefile = tmpnam ();
 %! as_save = as;
@@ -937,7 +937,7 @@
 %! clear as_save;
 %! load (savefile, "as_save");
 %! unlink (savefile);
-%! assert (as_save, sparse(af));
+%! assert (as_save, sparse (af));
 ## FIXME: We should skip (or mark as an expected failure) the test for
 ## saving sparse matrices to MAT files when using 64-bit indexing since
 ## that is not implemented yet.
@@ -948,7 +948,7 @@
 %! clear as_save;
 %! load (savefile, "as_save");
 %! unlink (savefile);
-%! assert (as_save, sparse(af));
+%! assert (as_save, sparse (af));
 EOF
 }
 
@@ -975,11 +975,11 @@
 
 cat >>$TESTS <<EOF
 %! df = diag (1:n).* alpha; ds = sparse (df);
-%! pdf = df(randperm (n),randperm (n));
+%! pdf = df(randperm (n), randperm (n));
 %! pds = sparse (pdf);
-%! plf = lf(randperm (n),randperm (n));
+%! plf = lf(randperm (n), randperm (n));
 %! pls = sparse (plf);
-%! puf = uf(randperm (n),randperm (n));
+%! puf = uf(randperm (n), randperm (n));
 %! pus = sparse (puf);
 %! bs = spdiags (repmat ([1:n]',1,4),-2:1,n,n).*alpha;
 %! bf = full (bs);
@@ -1024,28 +1024,28 @@
 cat >>$TESTS <<EOF
 %% QR solver tests
 
-%!function f(a, sz, feps)
+%!function f (a, sz, feps)
 %! b = randn (sz);
-%! x = a \ b; 
+%! x = a \ b;
 %! assert (a * x, b, feps);
 %! b = randn (sz) + 1i*randn (sz);
-%! x = a \ b;  
+%! x = a \ b;
 %! assert (a * x, b, feps);
 %! b = sprandn (sz(1),sz(2),0.2);
 %! x = a \ b;
 %! assert (sparse (a * x), b, feps);
 %! b = sprandn (sz(1),sz(2),0.2) + 1i*sprandn (sz(1),sz(2),0.2);
-%! x = a \ b; 
+%! x = a \ b;
 %! assert (sparse (a * x), b, feps);
 %!endfunction
 %!testif HAVE_UMFPACK
 %! a = alpha*sprandn (10,11,0.2) + speye (10,11);
-%! f(a,[10,2],1e-10);
-%! ## Test this by forcing matrix_type, as can't get a certain 
+%! f (a,[10,2],1e-10);
+%! ## Test this by forcing matrix_type, as can't get a certain
 %! ## result for over-determined systems.
-%! a = alpha*sprandn(10,10,0.2) + speye(10,10);
+%! a = alpha*sprandn (10,10,0.2) + speye (10,10);
 %! matrix_type (a, "Singular");
-%! f(a,[10,2],1e-10);
+%! f (a,[10,2],1e-10);
 
 %% Rectanguar solver tests that don't use QR
 
@@ -1149,7 +1149,7 @@
 gen_section
 
 # specific tests
-if $preset; then 
+if $preset; then
     gen_specific_tests
     gen_section
 fi
@@ -1194,25 +1194,25 @@
 gen_section
 gen_save_tests
 gen_section
-echo '%!test bf=real(bf);' >> $TESTS
+echo '%!test bf = real (bf);' >> $TESTS
 gen_rectangular_tests
 gen_section
 gen_sparsesparse_ordering_tests
 gen_section
-echo '%!test af=real(af);' >> $TESTS
+echo '%!test af = real (af);' >> $TESTS
 gen_rectangular_tests
 gen_section
 gen_save_tests
 gen_section
-echo '%!test bf=bf+1i*(bf~=0);' >> $TESTS
+echo '%!test bf = bf+1i*(bf~=0);' >> $TESTS
 gen_rectangular_tests
 gen_section
 
 # square operations
 if $preset; then
-    echo '%!test af=[1+1i,2-1i,0,0;0,0,0,3+2i;0,0,0,4];' >> $TESTS
-    echo '%! as=sparse(af);' >> $TESTS
-    echo '%!test bf=[0,1-1i,0,0;2+1i,0,0,0;3-1i,2+3i,0,0];' >> $TESTS
+    echo '%!test af = [1+1i,2-1i,0,0;0,0,0,3+2i;0,0,0,4];' >> $TESTS
+    echo '%! as = sparse (af);' >> $TESTS
+    echo '%!test bf = [0,1-1i,0,0;2+1i,0,0,0;3-1i,2+3i,0,0];' >> $TESTS
 else
     cat >>$TESTS <<EOF
 %!test
@@ -1234,34 +1234,34 @@
 
 gen_square_tests
 gen_section
-echo '%!test bf=real(bf);' >> $TESTS
-echo '%! bs=sparse(bf);' >> $TESTS
+echo '%!test bf = real (bf);' >> $TESTS
+echo '%! bs = sparse (bf);' >> $TESTS
 gen_square_tests
 gen_section
-echo '%!test af=real(af);' >> $TESTS
-echo '%! as=sparse(af);' >> $TESTS
+echo '%!test af = real (af);' >> $TESTS
+echo '%! as = sparse (af);' >> $TESTS
 gen_square_tests
 gen_section
-echo '%!test bf=bf+1i*(bf~=0);' >> $TESTS
-echo '%! bs=sparse(bf);' >> $TESTS
+echo '%!test bf = bf+1i*(bf~=0);' >> $TESTS
+echo '%! bs = sparse (bf);' >> $TESTS
 gen_square_tests
 gen_section
 
 # cholesky tests
 if $preset; then
-  echo '%!test bf=[5,0,1+1i,0;0,5,0,1-2i;1-1i,0,5,0;0,1+2i,0,5];' >> $TESTS
-  echo '%! bs=sparse(bf);' >> $TESTS
+  echo '%!test bf = [5,0,1+1i,0;0,5,0,1-2i;1-1i,0,5,0;0,1+2i,0,5];' >> $TESTS
+  echo '%! bs = sparse (bf);' >> $TESTS
 else
   echo '# This has a small chance of failing to create a positive definite matrix' >> $TESTS
-  echo '%!test n=floor (lognrnd (8,2)+1)' >> $TESTS
+  echo '%!test n = floor (lognrnd (8,2)+1)' >> $TESTS
   echo '%! bs = n*speye (n,n) + sprandn (n,n,0.3);' >> $TESTS
   echo '%! bf = full (bs);' >> $TESTS
 fi
 
 gen_cholesky_tests
 gen_section
-echo '%!test bf=real(bf);' >> $TESTS
-echo '%! bs=sparse(bf);' >> $TESTS
+echo '%!test bf = real (bf);' >> $TESTS
+echo '%! bs = sparse (bf);' >> $TESTS
 gen_cholesky_tests
 gen_section
 
@@ -1311,16 +1311,16 @@
 fi
 gen_scalar_select_tests
 gen_select_tests
-echo '%!test af=real(af);' >> $TESTS
+echo '%!test af = real (af);' >> $TESTS
 gen_select_tests
 gen_section
 echo '%!shared alpha,beta,df,pdf,lf,plf,uf,puf,bf,cf,bcf,tf,tcf,xf,ds,pds,ls,pls,us,pus,bs,cs,bcs,ts,tcs,xs' >>$TESTS
-echo '%!test alpha=1;beta=1;' >> $TESTS
+echo '%!test alpha=1; beta=1;' >> $TESTS
 gen_solver_tests
-echo '%!test alpha=1;beta=1i;' >> $TESTS
+echo '%!test alpha=1; beta=1i;' >> $TESTS
 gen_solver_tests
-echo '%!test alpha=1i;beta=1;' >> $TESTS
+echo '%!test alpha=1i; beta=1;' >> $TESTS
 gen_solver_tests
-echo '%!test alpha=1i;beta=1i;' >> $TESTS
+echo '%!test alpha=1i; beta=1i;' >> $TESTS
 gen_solver_tests
 gen_section
--- a/test/build_bc_overloads_expected.m
+++ b/test/build_bc_overloads_expected.m
@@ -6,7 +6,7 @@
 % to generate the overloaded functions.
 %
 ex.double = 1;
-ex.single = single(1);
+ex.single = single (1);
 ex.logical = true;
 ex.char = 'char';
 ex.int8  = int8 (1);
rename from test/class-concat/test_class_concat.m
rename to test/class-concat/class-concat.tst
--- a/test/class-concat/module.mk
+++ b/test/class-concat/module.mk
@@ -1,5 +1,5 @@
 class_concat_FCN_FILES = \
   class-concat/@foo/foo.m \
-  class-concat/test_class_concat.m
+  class-concat/class-concat.tst
 
 FCN_FILES += $(class_concat_FCN_FILES)
--- a/test/classes/@Blork/Blork.m
+++ b/test/classes/@Blork/Blork.m
@@ -1,16 +1,15 @@
-function [ s ] = Blork( bleek )
+function s = Blork (bleek)
 % Test class.
 
-    if (nargin==1) && isa(bleek, 'Blork')
-        s = bleek;
+  if (nargin == 1 && isa (bleek, 'Blork'))
+    s = bleek;
+  else
+    if (nargin == 0)
+      s.bleek = 1;
     else
-      if nargin==0
-        s.bleek = 1;
-      else
-        s.bleek = bleek;
-      end
-      s = class(s, 'Blork');
+      s.bleek = bleek;
+    end
+    s = class (s, 'Blork');
+  end
 
-    end
-        
 end
--- a/test/classes/@Blork/bleek.m
+++ b/test/classes/@Blork/bleek.m
@@ -1,10 +1,10 @@
-function [ out ] = bleek( in, val )
+function out = bleek (in, val)
 
-  if (nargin==1) 
+  if (nargin == 1)
     out = in.bleek;
   else
     in.bleek = val;
     out = in;
   end
-        
+
 end
--- a/test/classes/@Blork/display.m
+++ b/test/classes/@Blork/display.m
@@ -1,7 +1,7 @@
-function display( s )
+function display (s)
 
-  disp([inputname(1),'.bleek = '])
-  disp(' ');
-  disp(s.bleek);
+  disp ([inputname(1),'.bleek = ']);
+  disp (' ');
+  disp (s.bleek);
 
-end
\ No newline at end of file
+end
--- a/test/classes/@Blork/get.m
+++ b/test/classes/@Blork/get.m
@@ -1,10 +1,10 @@
-function [ v ] = get( s, propName )
+function v = get (s, propName)
 
-    switch propName
-        case 'bleek'
-            v = s.bleek;
-        otherwise
-            error([propName, ' is not a valid Blork property']);
-    end
+  switch propName
+    case 'bleek'
+      v = s.bleek;
+    otherwise
+      error ([propName, ' is not a valid Blork property']);
+  end
 
 end
--- a/test/classes/@Blork/set.m
+++ b/test/classes/@Blork/set.m
@@ -1,7 +1,7 @@
-function [ s ] = set( s, varargin )
+function s = set (s, varargin)
 
   propArgs = varargin;
-  while (length(propArgs) >= 2)
+  while (length (propArgs) >= 2)
     propName  = propArgs{1};
     propValue = propArgs{2};
     propArgs  = propArgs(3:end);
@@ -9,7 +9,7 @@
       case 'bleek'
         s.bleek = propValue;
       otherwise
-        error([propName, ' is not a valid Blork property']);
+        error ([propName, ' is not a valid Blork property']);
     end
   end
 
new file mode 100644
--- /dev/null
+++ b/test/classes/@CPrecedenceTester1/CPrecedenceTester1.m
@@ -0,0 +1,8 @@
+function x = CPrecedenceTester1 ()
+
+  x = struct ('useless_data', pi);
+  x = class (x, 'CPrecedenceTester1');
+
+  % don't change anything as far as precedence is concerned
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@CPrecedenceTester1/tattack.m
@@ -0,0 +1,5 @@
+function s = tattack (x, y)
+
+  s = 'CPrecedenceTester1';
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@CPrecedenceTester2/CPrecedenceTester2.m
@@ -0,0 +1,15 @@
+function x = CPrecedenceTester2 (flag)
+
+  x = struct ('useless_data', pi^2);
+  x = class (x, 'CPrecedenceTester2');
+
+  switch flag
+    case 1  % CPrecedencetester2 > Snork
+      superiorto ('Snork');
+    case 2  % CPrecedencetester2 < Snork
+      inferiorto ('Snork');
+    otherwise
+      error ('Incorrect value for argument flag: %d', flag);
+  end
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@CPrecedenceTester2/tattack.m
@@ -0,0 +1,5 @@
+function s = tattack (x, y)
+
+  s = 'CPrecedenceTester2';
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@CPrecedenceTester3/CPrecedenceTester3.m
@@ -0,0 +1,15 @@
+function x = CPrecedenceTester3 (flag)
+
+  x = struct ('useless_data', pi^3);
+  x = class (x, 'CPrecedenceTester3');
+
+  switch flag
+    case 1  % CPrecedencetester3 > Snork
+      superiorto ('Snork');
+    case 2  % CPrecedencetester3 < Snork
+      inferiorto ('Snork');
+    otherwise
+      error ('Incorrect value for argument flag: %d', flag);
+  end
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@CPrecedenceTester3/tattack.m
@@ -0,0 +1,5 @@
+function s = tattack (x, y)
+
+  s = 'CPrecedenceTester3';
+
+end
--- a/test/classes/@Cork/Cork.m
+++ b/test/classes/@Cork/Cork.m
@@ -1,16 +1,16 @@
-function [ s ] = Cork( click )
+function s = Cork (click)
 % Test class.
 
-  if ( (nargin==1) && (isa(click, 'Cork')) )
+  if (nargin == 1 && isa (click, 'Cork'))
     s = click;
     return;
   end
 
-  if( nargin<1 )
+  if (nargin < 1)
     s.click = 1;
   else
     s.click = click;
   end
-  s = class(s, 'Cork');
+  s = class (s, 'Cork');
 
 end
--- a/test/classes/@Cork/click.m
+++ b/test/classes/@Cork/click.m
@@ -1,10 +1,10 @@
-function [ out ] = click( in, val )
+function out = click (in, val)
 
-  if (nargin==1) 
+  if (nargin == 1)
     out = in.click;
   else
     in.click = val;
     out = in;
   end
-        
+
 end
--- a/test/classes/@Cork/display.m
+++ b/test/classes/@Cork/display.m
@@ -1,7 +1,7 @@
-function display( s )
+function display (s)
 
-  disp([inputname(1),'.click = ']);
-  disp(' ');
-  disp(s.click);
+  disp ([inputname(1),'.click = ']);
+  disp (' ');
+  disp (s.click);
 
-end
\ No newline at end of file
+end
--- a/test/classes/@Cork/get.m
+++ b/test/classes/@Cork/get.m
@@ -1,10 +1,10 @@
-function [ v ] = get( s, propName )
+function v = get (s, propName)
 
-    switch propName
-        case 'click'
-            v = s.click;
-        otherwise
-            error([propName, ' is not a valid Cork property']);
-    end
+  switch propName
+    case 'click'
+      v = s.click;
+    otherwise
+      error ([propName, ' is not a valid Cork property']);
+  end
 
 end
--- a/test/classes/@Cork/set.m
+++ b/test/classes/@Cork/set.m
@@ -1,7 +1,7 @@
-function [ s ] = set( s, varargin )
+function s = set (s, varargin)
 
   propArgs = varargin;
-  while (length(propArgs) >= 2)
+  while (length (propArgs) >= 2)
     propName  = propArgs{1};
     propValue = propArgs{2};
     propArgs  = propArgs(3:end);
@@ -9,7 +9,7 @@
       case 'click'
         s.click = propValue;
       otherwise
-        error([propName, ' is not a valid Cork property']);
+        error ([propName, ' is not a valid Cork property']);
     end
   end
 
--- a/test/classes/@Dork/Dork.m
+++ b/test/classes/@Dork/Dork.m
@@ -1,18 +1,18 @@
-function [ s ] = Dork( gick, gack )
+function s = Dork (gick, gack)
 
-  if (nargin==1) && isa(gick,'Dork')
+  if (nargin == 1 && isa (gick, 'Dork'))
     s = gick;
   else
     s.gack = 0;
-    if nargin == 0
-      s0 = Snork();
-    elseif nargin==1
-      s0 = Snork(gick);
+    if (nargin == 0)
+      s0 = Snork ();
+    elseif (nargin == 1)
+      s0 = Snork (gick);
     else
-      s0 = Snork(gick);
+      s0 = Snork (gick);
       s.gack = gack;
     end
-    s = class(s,'Dork',s0);
-   end 
-   
+    s = class (s, 'Dork', s0);
+   end
+
 end
--- a/test/classes/@Dork/bling.m
+++ b/test/classes/@Dork/bling.m
@@ -1,5 +1,5 @@
-function [ out ] = bling( m1, m2 )
+function out = bling (m1, m2)
 
   out = 1;
-        
+
 end
--- a/test/classes/@Dork/display.m
+++ b/test/classes/@Dork/display.m
@@ -1,13 +1,13 @@
-function display( s )
+function display (s)
 %  Display the critical info for an amplifier
 
-   gick = get(s,'gick');
-   disp([inputname(1),'.gick = '])
-   disp(' ');
-   disp(gick);
-   disp(' ');
-   disp([inputname(1),'.gack = '])
-   disp(' ');
-   disp(s.gack);
+   gick = get (s, 'gick');
+   disp ([inputname(1),'.gick = ']);
+   disp (' ');
+   disp (gick);
+   disp (' ');
+   disp ([inputname(1),'.gack = ']);
+   disp (' ');
+   disp (s.gack);
 
 end
--- a/test/classes/@Dork/gack.m
+++ b/test/classes/@Dork/gack.m
@@ -1,10 +1,10 @@
-function [ out ] = gack( in, val )
+function out = gack (in, val)
 
-  if (nargin==1) 
+  if (nargin == 1)
     out = in.gack;
   else
     in.gack = val;
     out = in;
   end
-        
+
 end
--- a/test/classes/@Dork/get.m
+++ b/test/classes/@Dork/get.m
@@ -1,10 +1,10 @@
-function [ v ] = get( s, propName )
+function v = get (s, propName)
 
   switch propName
     case 'gack'
       v = s.gack;
     otherwise
-      v = get(s.Snork,propName);
+      v = get (s.Snork,propName);
   end
 
 end
--- a/test/classes/@Dork/getStash.m
+++ b/test/classes/@Dork/getStash.m
@@ -1,5 +1,5 @@
-function [ out ] = getStash(cls)
+function out = getStash (cls)
 
-  out = myStash();
-        
+  out = myStash ();
+
 end
--- a/test/classes/@Dork/private/myStash.m
+++ b/test/classes/@Dork/private/myStash.m
@@ -1,4 +1,4 @@
-function [ out ] = myStash()
+function out = myStash ()
 
   out = 2;
 
--- a/test/classes/@Dork/set.m
+++ b/test/classes/@Dork/set.m
@@ -1,7 +1,7 @@
-function [ s ] = set( s, varargin )
+function s = set (s, varargin)
 
   propArgs = varargin;
-  while (length(propArgs) >= 2)
+  while (length (propArgs) >= 2)
     propName  = propArgs{1};
     propValue = propArgs{2};
     propArgs  = propArgs(3:end);
@@ -9,7 +9,7 @@
       case 'gack'
         s.gack = propValue;
       otherwise
-        s.Snork = set(s.Snork, propName, propValue);
+        s.Snork = set (s.Snork, propName, propValue);
     end
   end
 
--- a/test/classes/@Gork/Gork.m
+++ b/test/classes/@Gork/Gork.m
@@ -1,15 +1,16 @@
-function [ s ] = Gork( g )
-  if (nargin==1) && isa(g,'Gork')
+function s = Gork (g)
+
+  if (nargin == 1 && isa (g, 'Gork'))
     s = sprk;
     return;
   end
 
-  drk  = Dork();
-  prk  = Pork();
-  blrk = Blork();
-  s.Cork = Cork(17);  % Aggregation.
+  drk  = Dork ();
+  prk  = Pork ();
+  blrk = Blork ();
+  s.Cork = Cork (17);  % Aggregation.
   s.gark = -2;
   s.gyrk = -3;
-  s = class(s,'Gork',drk,prk,blrk);
-   
+  s = class (s,'Gork',drk,prk,blrk);
+
 end
--- a/test/classes/@Gork/cork.m
+++ b/test/classes/@Gork/cork.m
@@ -1,10 +1,10 @@
-function [ out ] = cork( in, val )
+function out = cork (in, val)
 
-  if (nargin==1) 
+  if (nargin == 1)
     out = in.Cork;
   else
     in.Cork = val;
     out = in;
   end
-        
+
 end
--- a/test/classes/@Gork/display.m
+++ b/test/classes/@Gork/display.m
@@ -1,16 +1,15 @@
-function display( s )
+function display (s)
 %  Display the critical info for a Gork.
 
    dork_base = s.Dork
    %pork_base = s.Pork
    %sprk = s.sprk;
-   gark = get(s,'gark');
-   disp([inputname(1),'.gark = '])
-   disp(' ');
-   disp(gark);
-   disp([inputname(1),'.Cork= '])
-   disp(' ');
-   disp(click(s.Cork));
-
+   gark = get (s, 'gark');
+   disp ([inputname(1),'.gark = ']);
+   disp (' ');
+   disp (gark);
+   disp ([inputname(1),'.Cork= ']);
+   disp (' ');
+   disp (click(s.Cork));
 
 end
--- a/test/classes/@Gork/gark.m
+++ b/test/classes/@Gork/gark.m
@@ -1,10 +1,10 @@
-function [ out ] = gark( in, val )
+function out = gark (in, val)
 
-  if (nargin==1) 
+  if (nargin == 1)
     out = in.gark;
   else
     in.gark = val;
     out = in;
   end
-        
+
 end
--- a/test/classes/@Gork/get.m
+++ b/test/classes/@Gork/get.m
@@ -1,4 +1,4 @@
-function [ v ] = get( s, propName )
+function v = get (s, propName)
 
   switch propName
     case 'cork'
@@ -8,7 +8,7 @@
     otherwise
       % Note that get/set for multiple parents is hard.  We only do one
       % branch of the parent tree just to test this stuff out.
-      v = get(s.Dork,propName);
+      v = get (s.Dork,propName);
   end
 
 end
--- a/test/classes/@Gork/set.m
+++ b/test/classes/@Gork/set.m
@@ -1,23 +1,23 @@
-function [ s ] = set( s, varargin )
+function s = set (s, varargin)
 
   propArgs = varargin;
-  while (length(propArgs) >= 2)
+  while (length (propArgs) >= 2)
     propName  = propArgs{1};
     propValue = propArgs{2};
     propArgs  = propArgs(3:end);
     switch propName
       case 'cork'
-        if(isa(propValue,'Cork'))
+        if (isa (propValue, 'Cork'))
           s.Cork = propValue;
         else
-          s.Cork = set(s.Cork, 'click',propValue);
+          s.Cork = set (s.Cork, 'click', propValue);
         end
       case 'gark'
         s.gark = propValue;
       otherwise
         % Note that get/set for multiple parents is hard.  We only do one
         % branch of the parent tree just to test this stuff out.
-        s.Dork = set(s.Dork, propName, propValue);
+        s.Dork = set (s.Dork, propName, propValue);
     end
   end
 
--- a/test/classes/@Gork/subsasgn.m
+++ b/test/classes/@Gork/subsasgn.m
@@ -1,9 +1,10 @@
-function g = subsasgn(g, s, x)
+function g = subsasgn (g, s, x)
 
   switch s.type
   case '.'
     switch s.subs
     case 'gyrk'
-      g.gyrk = x; 
+      g.gyrk = x;
   end
+
 end
--- a/test/classes/@Gork/subsref.m
+++ b/test/classes/@Gork/subsref.m
@@ -1,4 +1,4 @@
-function x = subsref(g, s)
+function x = subsref (g, s)
 
   switch s.type
   case '.'
@@ -6,4 +6,5 @@
     case 'gyrk'
       x = g.gyrk;
   end
+
 end
--- a/test/classes/@Pork/Pork.m
+++ b/test/classes/@Pork/Pork.m
@@ -1,19 +1,19 @@
-function [ s ] = Pork( geek, gurk )
+function s = Pork (geek, gurk)
 
-  if (nargin==1) && isa(geek,'Pork')
+  if (nargin == 1 && isa (geek, 'Pork'))
     s = geek;
   else
     s.gurk = 0;
-    if nargin == 0
-      s0 = Spork();
-    elseif nargin==1
-      s0 = Spork(geek);
+    if (nargin == 0)
+      s0 = Spork ();
+    elseif (nargin == 1)
+      s0 = Spork (geek);
     else
-      s0 = Spork(geek);
+      s0 = Spork (geek);
       s.gurk = gurk;
     end
-    s = class(s,'Pork',s0);
-   end 
-   superiorto('Dork');
+    s = class (s, 'Pork', s0);
+   end
+   superiorto ('Dork');
 
 end
--- a/test/classes/@Pork/bling.m
+++ b/test/classes/@Pork/bling.m
@@ -1,5 +1,5 @@
-function [ out ] = bling( m1, m2 )
+function out = bling (m1, m2)
 
   out = 2;
-        
+
 end
--- a/test/classes/@Pork/display.m
+++ b/test/classes/@Pork/display.m
@@ -1,13 +1,13 @@
-function display( s )
+function display (s)
 %  Display the critical info for an amplifier
 
-   geek = get(s,'geek');
-   disp([inputname(1),'.geek = '])
-   disp(' ');
-   disp(geek);
-   disp(' ');
-   disp([inputname(1),'.gurk = '])
-   disp(' ');
-   disp(s.gurk);
+   geek = get (s, 'geek');
+   disp ([inputname(1),'.geek = ']);
+   disp (' ');
+   disp (geek);
+   disp (' ');
+   disp ([inputname(1),'.gurk = ']);
+   disp (' ');
+   disp (s.gurk);
 
 end
--- a/test/classes/@Pork/get.m
+++ b/test/classes/@Pork/get.m
@@ -1,10 +1,10 @@
-function [ v ] = get( s, propName )
+function v = get (s, propName)
 
   switch propName
     case 'gurk'
       v = s.gurk;
     otherwise
-      v = get(s.Spork,propName);
+      v = get (s.Spork, propName);
   end
 
 end
--- a/test/classes/@Pork/gurk.m
+++ b/test/classes/@Pork/gurk.m
@@ -1,10 +1,10 @@
-function [ out ] = gurk( in, val )
+function out = gurk (in, val)
 
-  if (nargin==1) 
+  if (nargin == 1)
     out = in.gurk;
   else
     in.gurk = val;
     out = in;
   end
-        
+
 end
--- a/test/classes/@Pork/private/myStash.m
+++ b/test/classes/@Pork/private/myStash.m
@@ -1,4 +1,4 @@
-function [ out ] = myStash()
+function out = myStash ()
 
   out = 4;
 
--- a/test/classes/@Pork/set.m
+++ b/test/classes/@Pork/set.m
@@ -1,7 +1,7 @@
-function [ s ] = set( s, varargin )
+function s = set (s, varargin)
 
   propArgs = varargin;
-  while (length(propArgs) >= 2)
+  while (length (propArgs) >= 2)
     propName  = propArgs{1};
     propValue = propArgs{2};
     propArgs  = propArgs(3:end);
@@ -9,7 +9,7 @@
       case 'gurk'
         s.gurk = propValue;
       otherwise
-        s.Spork = set(s.Spork, propName, propValue);
+        s.Spork = set (s.Spork, propName, propValue);
     end
   end
 
--- a/test/classes/@Sneetch/Sneetch.m
+++ b/test/classes/@Sneetch/Sneetch.m
@@ -1,16 +1,16 @@
-function [ s ] = Sneetch( mcbean )
+function s = Sneetch (mcbean)
 % Test class: should produce error.
 
-  if (nargin==1) && isa(mcbean, 'Sneetch')
+  if (nargin == 1 && isa (mcbean, 'Sneetch'))
     s = mcbean;
   else
-    if nargin==0
+    if (nargin == 0)
       s.mcbean = 1;
     else
       s.mcbean = mcbean;
     end
-    s = class(s, 'Sneetch');
+    s = class (s, 'Sneetch');
     s.sylvester = 1;
   end
-        
+
 end
--- a/test/classes/@Sneetch/display.m
+++ b/test/classes/@Sneetch/display.m
@@ -1,10 +1,10 @@
-function display( s )
+function display ( s )
 
-  disp([inputname(1),'.mcbean = '])
-  disp(' ');
-  disp(s.mcbean);
-  disp([inputname(1),'.sylvester = '])
-  disp(' ');
-  disp(s.sylvester);
+  disp ([inputname(1),'.mcbean = ']);
+  disp (' ');
+  disp (s.mcbean);
+  disp ([inputname(1),'.sylvester = ']);
+  disp (' ');
+  disp (s.sylvester);
 
-end
\ No newline at end of file
+end
--- a/test/classes/@Snork/Snork.m
+++ b/test/classes/@Snork/Snork.m
@@ -1,17 +1,16 @@
-function [ s ] = Snork( gick )
+function s = Snork (gick)
 % Test class.
 
-  if ( (nargin==1) && (isa(gick, 'Snork')) )
+  if (nargin == 1 && isa (gick, 'Snork'))
     s = gick;
   else
     s.cack = [0 1 2 3];
-    if nargin==0
+    if (nargin == 0)
       s.gick = 1;
     else
       s.gick = gick;
     end
-    s = class(s, 'Snork');
-
+    s = class (s, 'Snork');
   end
-        
+
 end
--- a/test/classes/@Snork/cack.m
+++ b/test/classes/@Snork/cack.m
@@ -1,5 +1,5 @@
-function [ out ] = cack( in )
+function out = cack (in)
 
   out = in.cack;
-        
+
 end
--- a/test/classes/@Snork/display.m
+++ b/test/classes/@Snork/display.m
@@ -1,7 +1,7 @@
-function display( s )
+function display (s)
 
-  disp([inputname(1),'.gick = ']);
-  disp(' ');
-  disp(s.gick);
+  disp ([inputname(1),'.gick = ']);
+  disp (' ');
+  disp (s.gick);
 
-end
\ No newline at end of file
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/double.m
@@ -0,0 +1,6 @@
+function x = double (snk)
+
+  x = snk.gick;
+
+end
+
--- a/test/classes/@Snork/end.m
+++ b/test/classes/@Snork/end.m
@@ -3,7 +3,7 @@
   if (num_indices ~= 1)
     error ('Snork object may only have one index')
   end
-  
+
   r = length (snk.cack);
 
 end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/eq.m
@@ -0,0 +1,8 @@
+function b = eq (s1, s2)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  b = isequal (x1, x2);
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/ge.m
@@ -0,0 +1,8 @@
+function b = ge (s1, s2)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  b = (x1(1) >= x2(1));
+
+end
--- a/test/classes/@Snork/get.m
+++ b/test/classes/@Snork/get.m
@@ -1,10 +1,10 @@
-function [ v ] = get( s, propName )
+function v = get (s, propName)
 
-    switch propName
-        case 'gick'
-            v = s.gick;
-        otherwise
-            error([propName, ' is not a valid Snork property']);
-    end
+  switch propName
+    case 'gick'
+      v = s.gick;
+    otherwise
+      error ([propName, ' is not a valid Snork property']);
+  end
 
 end
--- a/test/classes/@Snork/getStash.m
+++ b/test/classes/@Snork/getStash.m
@@ -1,5 +1,5 @@
-function [ out ] = getStash(cls)
+function out = getStash (l)
 
-  out = myStash();
-        
+  out = myStash ();
+
 end
--- a/test/classes/@Snork/gick.m
+++ b/test/classes/@Snork/gick.m
@@ -1,10 +1,10 @@
-function [ out ] = gick( in, val )
+function out = gick (in, val)
 
-  if (nargin==1) 
+  if (nargin == 1)
     out = in.gick;
   else
     in.gick = val;
     out = in;
   end
-        
+
 end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/gt.m
@@ -0,0 +1,8 @@
+function b = gt (s1, s2)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  b = (x1(1) > x2(1));
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/horzcat.m
@@ -0,0 +1,8 @@
+function s = horzcat (s1, s2)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  s = Snork ([x1 x2]);
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/ldivide.m
@@ -0,0 +1,8 @@
+function s = ldivide (s1, s2)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  s = Snork(x1 .\ x2);
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/le.m
@@ -0,0 +1,8 @@
+function b = le (s1, s2)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  b = (x1(1) <= x2(1));
+
+end
--- a/test/classes/@Snork/loadobj.m
+++ b/test/classes/@Snork/loadobj.m
@@ -1,6 +1,6 @@
-function [ out ] = loadobj( in )
+function out = loadobj (in)
 
   out = in;
   out.cack = [-1 -2 -3 -4];
-        
+
 end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/lt.m
@@ -0,0 +1,8 @@
+function b = lt (s1, s2)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  b = (x1(1) < x2(1));
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/minus.m
@@ -0,0 +1,8 @@
+function s = minus (s1, s2)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  s = Snork (x1 - x2);
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/mldivide.m
@@ -0,0 +1,8 @@
+function s = mldivide (s1, s2)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  s = Snork (x1 \ x2);
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/mpower.m
@@ -0,0 +1,10 @@
+function s = mpower (s1, x)
+
+  if (~isa (s1, 'Snork') || isa (x, 'Snork'))
+    error ('mpower Snork!!!');
+  end
+
+  s = s1;
+  s.gick = s.gick ^ x;
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/mrdivide.m
@@ -0,0 +1,8 @@
+function s = mrdivide (s1, s2)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  s = Snork (x1 / x2);
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/mtimes.m
@@ -0,0 +1,8 @@
+function s = mtimes (s1, s2)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  s = Snork (x1 * x2);
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/ne.m
@@ -0,0 +1,5 @@
+function b = ne (s1, s2)
+
+  b = ~(s1 == s2);
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/plus.m
@@ -0,0 +1,8 @@
+function s = plus (s1, s2)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  s = Snork (x1 + x2);
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/power.m
@@ -0,0 +1,10 @@
+function s = power (s1, x)
+
+  if (~isa (s1, 'Snork') || isa (x, 'Snork'))
+    error ('power Snork!!!');
+  end
+
+  s = s1;
+  s.gick = s.gick .^ x;
+
+end
--- a/test/classes/@Snork/private/myStash.m
+++ b/test/classes/@Snork/private/myStash.m
@@ -1,5 +1,5 @@
-function [ out ] = myStash()
+function out = myStash ()
 
   out = 1;
-        
+
 end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/rdivide.m
@@ -0,0 +1,8 @@
+function s = rdivide (s1, s2)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  s = Snork(x1 ./ x2);
+
+end
--- a/test/classes/@Snork/saveobj.m
+++ b/test/classes/@Snork/saveobj.m
@@ -1,6 +1,6 @@
-function [ out ] = saveobj( in )
+function out = saveobj (in)
 
   out = in;
   out.cack = [];
-        
+
 end
--- a/test/classes/@Snork/set.m
+++ b/test/classes/@Snork/set.m
@@ -1,7 +1,7 @@
-function [ s ] = set( s, varargin )
+function s = set (s, varargin)
 
   propArgs = varargin;
-  while (length(propArgs) >= 2)
+  while (length (propArgs) >= 2)
     propName  = propArgs{1};
     propValue = propArgs{2};
     propArgs  = propArgs(3:end);
@@ -9,7 +9,7 @@
       case 'gick'
         s.gick = propValue;
       otherwise
-        error([propName, ' is not a valid Snork property']);
+        error ([propName, ' is not a valid Snork property']);
     end
   end
 
--- a/test/classes/@Snork/subsasgn.m
+++ b/test/classes/@Snork/subsasgn.m
@@ -1,4 +1,5 @@
 function snk = subsasgn (snk, s, val)
+
   if (length (s) < 1)
     error ('Snork: needs index');
   end
@@ -35,4 +36,5 @@
     otherwise
       error ('invalid subscript type');
   end
+
 end
--- a/test/classes/@Snork/subsindex.m
+++ b/test/classes/@Snork/subsindex.m
@@ -1,5 +1,5 @@
-function [ out ] = subsindex( obj )
+function out = subsindex (obj)
 
   out = 0;
-        
+
 end
--- a/test/classes/@Snork/subsref.m
+++ b/test/classes/@Snork/subsref.m
@@ -1,4 +1,5 @@
 function b = subsref (snk, s)
+
   if (isempty (s))
     error ('Snork: missing index');
   end
@@ -27,4 +28,5 @@
     otherwise
       error ('invalid subscript type');
   end
+
 end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/tattack.m
@@ -0,0 +1,5 @@
+function s = tattack (x, y)
+
+  s = 'Snork';
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/times.m
@@ -0,0 +1,8 @@
+function s = times (s1, s2, s3)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  s = Snork (x1 .* x2);
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/uminus.m
@@ -0,0 +1,6 @@
+function s = uminus (s1)
+
+  s = s1;
+  s.gick = - s.gick;
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/uplus.m
@@ -0,0 +1,5 @@
+function s = uplus (s1)
+
+  s = s1;
+
+end
new file mode 100644
--- /dev/null
+++ b/test/classes/@Snork/vertcat.m
@@ -0,0 +1,8 @@
+function s = vertcat (s1, s2)
+
+  x1 = double (s1);
+  x2 = double (s2);
+
+  s = Snork ([x1; x2]);
+
+end
--- a/test/classes/@Spork/Spork.m
+++ b/test/classes/@Spork/Spork.m
@@ -1,17 +1,16 @@
-function [ s ] = Spork( geek )
+function s = Spork (geek)
 % Test class.
 
-    if (nargin==1) && isa(geek, 'Spork')
-        s = geek;
+    if (nargin == 1 && isa (geek, 'Spork'))
+      s = geek;
     else
       s.cack = [-1 -2 -3 -4];
-      if nargin==0
+      if (nargin == 0)
         s.geek = 1;
       else
         s.geek = geek;
       end
-      s = class(s, 'Spork');
-
+      s = class (s, 'Spork');
     end
-        
+
 end
--- a/test/classes/@Spork/cack.m
+++ b/test/classes/@Spork/cack.m
@@ -1,5 +1,5 @@
-function [ out ] = cack( in )
+function out = cack (in)
 
   out = in.cack;
-        
+
 end
--- a/test/classes/@Spork/display.m
+++ b/test/classes/@Spork/display.m
@@ -1,7 +1,7 @@
-function display( s )
+function display (s)
 
-  disp([inputname(1),'.geek = '])
-  disp(' ');
-  disp(s.geek);
+  disp ([inputname(1),'.geek = ']);
+  disp (' ');
+  disp (s.geek);
 
-end
\ No newline at end of file
+end
--- a/test/classes/@Spork/geek.m
+++ b/test/classes/@Spork/geek.m
@@ -1,10 +1,10 @@
-function [ out ] = geek( in, val )
+function out = geek (in, val)
 
-  if (nargin==1) 
+  if (nargin == 1)
     out = in.geek;
   else
     in.geek = val;
     out = in;
   end
-        
+
 end
--- a/test/classes/@Spork/get.m
+++ b/test/classes/@Spork/get.m
@@ -1,10 +1,10 @@
-function [ v ] = get( s, propName )
+function v = get (s, propName)
 
-    switch propName
-        case 'geek'
-            v = s.geek;
-        otherwise
-            error([propName, ' is not a valid Spork property']);
-    end
+  switch propName
+    case 'geek'
+      v = s.geek;
+    otherwise
+      error ([propName, ' is not a valid Spork property']);
+  end
 
 end
--- a/test/classes/@Spork/getStash.m
+++ b/test/classes/@Spork/getStash.m
@@ -1,5 +1,5 @@
-function [ out ] = getStash(cls)
+function out = getStash (cls)
 
-  out = myStash();
-        
+  out = myStash ();
+
 end
--- a/test/classes/@Spork/loadobj.m
+++ b/test/classes/@Spork/loadobj.m
@@ -1,8 +1,8 @@
-function [ out ] = loadobj( in )
+function out = loadobj (in)
 
   out = in;
-  if (~isa(in,'Spork'))
-    out.cack=[];
+  if (~isa (in, 'Spork'))
+    out.cack = [];
   end
-        
+
 end
--- a/test/classes/@Spork/private/myStash.m
+++ b/test/classes/@Spork/private/myStash.m
@@ -1,5 +1,5 @@
-function [ out ] = myStash()
+function out = myStash ()
 
   out = 3;
-        
+
 end
--- a/test/classes/@Spork/saveobj.m
+++ b/test/classes/@Spork/saveobj.m
@@ -1,6 +1,6 @@
-function [ out ] = saveobj( in )
+function out = saveobj (in)
 
   out = in;
-  %rmfield(out,'cack');
-        
+  %rmfield (out,'cack');
+
 end
--- a/test/classes/@Spork/set.m
+++ b/test/classes/@Spork/set.m
@@ -1,7 +1,7 @@
-function [ s ] = set( s, varargin )
+function s = set (s, varargin)
 
   propArgs = varargin;
-  while (length(propArgs) >= 2)
+  while (length (propArgs) >= 2)
     propName  = propArgs{1};
     propValue = propArgs{2};
     propArgs  = propArgs(3:end);
@@ -9,7 +9,7 @@
       case 'geek'
         s.geek = propValue;
       otherwise
-        error([propName, ' is not a valid Spork property']);
+        error ([propName, ' is not a valid Spork property']);
     end
   end
 
rename from test/classes/test_classes.m
rename to test/classes/classes.tst
--- a/test/classes/test_classes.m
+++ b/test/classes/classes.tst
@@ -1,3 +1,4 @@
+## Copyright (C) 2013 Julien Bect
 ## Copyright (C) 2009-2012 Robert T. Short
 ##
 ## This file is part of Octave.
@@ -16,186 +17,347 @@
 ## along with Octave; see the file COPYING.  If not, see
 ## <http://www.gnu.org/licenses/>.
 
-%%  Test script for legacy OOP.
-%%  Requires the path to contain the test classes.
+%% Test script for legacy OOP.
+%% Requires the path to contain the test classes.
 %%
-%%  Note: This script and all classes are also intended to run
-%%        in MATLAB to test compatibility.  Don't break that!
+%% Note: This script and all classes are also intended to run
+%%       in MATLAB to test compatibility.  Don't break that!
 %%
-%%  To Do:  This script tests to ensure that things done correctly work
-%%          corrrectly.  It should also check that things done incorrectly
-%%          error properly.
+%%       Note(JBect, 2013/01/27) : in order to ease to process of testing
+%%       Matlab compatibility, the syntax assert(observed, expected) should
+%%       be avoided. I use assert(isequal(observed, expected) instead.
 %%
-%%  The classes used for the tests reside in the test directory.
+%% To Do:  This script tests to ensure that things done correctly work
+%%         corrrectly.  It should also check that things done incorrectly
+%%         error properly.
+%%
+%% The classes used for the tests reside in the test directory.
 %%
-%%  The classes provide the ability to test most of the major features
-%%  of the legacy OOP facilities.  There are a number of classes, mostly
-%%  kind of the same, that create a hierarchy.
+%% The classes provide the ability to test most of the major features
+%% of the legacy OOP facilities.  There are a number of classes, mostly
+%% kind of the same, that create a hierarchy.
 
-%%  Test the Snork class.  The Snork class has a number of the standard
-%%  methods that the others don't so we can test indexing and other
-%%  features.
+%% Test the Snork class.  The Snork class has a number of the standard
+%% methods that the others don't so we can test indexing and other
+%% features.
 %!shared snk, snk1, snk2
-%!test snk = Snork();
-%!  assert(gick(snk),1)
-%!  assert(snk.gick,1)
-%!  assert(snk(2),1);
-%!  assert(snk{end},3);
-%!test snk = gick(snk,2);
-%!  assert(gick(snk),2)
-%!test snk = set(snk,'gick',7);
-%!  assert(get(snk, 'gick'), 7)
+%!test snk = Snork ();
+%! assert (isequal (gick (snk), 1));
+%! assert (isequal (snk.gick, 1));
+%! assert (isequal (snk(2), 1));
+%! assert (isequal (snk{end}, 3));
+%!test snk = gick (snk, 2);
+%! assert (isequal (gick (snk), 2));
+%!test snk = set (snk, 'gick', 7);
+%! assert (isequal (get (snk, 'gick'), 7));
 %!test snk.gick = 4;
-%! assert(gick(snk),4)
-%!   snk(1) = 3;
+%! assert (isequal (gick (snk),4));
+%!  snk(1) = 3;
 %!test snk{end} = 9;
-%!  assert(cack(snk),[3 1 2 9])
-%!  assert(getStash(snk),1)             % Check private functions.
-%!  assert(isobject(snk))
-%!  assert(class(snk),'Snork')
-%!  assert(isa(snk,'Snork'))
-%!  assert(~isa(snk,'Sneetch'))
-%!  assert(ismethod(snk,'gick'))
-%!  assert(~ismethod(snk,'bletch'))
-%!  assert(exist('snk'))
-%!  assert(~exist('blink'))
-%!test snk1 = Snork(snk);
-%!  assert(class(snk1),'Snork')
-%!  assert(gick(snk1),4)
-%!test snk2 = Snork(-3);
-%!  assert(class(snk2),'Snork')
-%!  assert(gick(snk2),-3)
-%!test x=[1 2 3 4];
-%!  assert(x(snk),1);
-%% x=methods('Snork');                   % Need to test the methods function.
+%! assert (isequal (cack (snk), [3 1 2 9]));
+%! assert (isequal (getStash (snk), 1));             % Check private functions.
+%! assert (isobject (snk));
+%! assert (isequal (class (snk), 'Snork'));
+%! assert (isa (snk, 'Snork'));
+%! assert (~isa (snk, 'Sneetch'));
+%! assert (ismethod (snk, 'gick'));
+%! assert (~ismethod (snk, 'bletch'));
+%! assert (exist ('snk') == 1);
+%! assert (exist ('blink') == 0);
+%!test snk1 = Snork (snk);
+%! assert (isequal (class (snk1), 'Snork'));
+%! assert (isequal (gick (snk1), 4));
+%!test snk2 = Snork (-3);
+%! assert (isequal (class (snk2), 'Snork'));
+%! assert (isequal (gick (snk2), -3));
+%!test x = [1 2 3 4];
+%! assert (isequal (x(snk), 1));
+
+%% x = methods ('Snork');                % Need to test the methods function.
 %% save temp snk;
-%% load temp                             % This load causes a segment fault.
-%% assert(cack(snk),[-1 -2 -3 -4]);      % This is a major bug!
+%% load temp                             % This load causes a segfault.
+%% assert (isequal (cack(snk), [-1 -2 -3 -4]));      % This is a major bug!
 
 %% The Spork class is a near clone of Snork but without as many standard
 %% methods.  We are testing no new octave features, but this is makes
 %% sure that we haven't bollixed up the Spork class if we should make
 %% changes.  We use Spork in the class hierarchy.
 %!shared sprk
-%!test sprk = Spork();
-%!  assert(geek(sprk),1)
-%!test sprk = geek(sprk,3);
-%!  assert(geek(sprk),3)
-%!test sprk = set(sprk,'geek',7);
-%!  assert(get(sprk, 'geek'), 7)
-%!  assert(class(sprk),'Spork');
-%!  assert(isa(sprk,'Spork'))
+%!test sprk = Spork ();
+%! assert (isequal (geek (sprk), 1));
+%!test sprk = geek (sprk, 3);
+%! assert (isequal (geek (sprk), 3));
+%!test sprk = set (sprk,'geek',7);
+%! assert (isequal (get (sprk, 'geek'), 7));
+%! assert (isequal (class (sprk), 'Spork'));
+%! assert (isa (sprk, 'Spork'));
 
 %%  The Blork class is a near clone of Snork but without as many standard
 %%  methods.  We are testing no new octave features, but this is makes
 %%  sure that we haven't bollixed up the Blork class if we should make
 %%  changes.  We use Blork in the class hierarchy.
 %!shared blrk
-%!test blrk = Blork();
-%!  assert(bleek(blrk),1)
-%!test blrk = bleek(blrk,3);
-%!  assert(bleek(blrk),3)
-%!test blrk = set(blrk,'bleek',13);
-%!  assert(get(blrk, 'bleek'), 13)
-%!  assert(class(blrk),'Blork');
-%!  assert(isa(blrk,'Blork'))
+%!test blrk = Blork ();
+%! assert (isequal (bleek(blrk), 1));
+%!test blrk = bleek (blrk, 3);
+%! assert (isequal (bleek (blrk), 3));
+%!test blrk = set (blrk, 'bleek', 13);
+%! assert (isequal (get (blrk, 'bleek'), 13));
+%! assert (isequal (class (blrk), 'Blork'));
+%! assert (isa (blrk, 'Blork'));
 
 %%  The Cork class is a near clone of Snork but without as many standard
 %%  methods.  We are testing no new octave features, but this is makes
 %%  sure that we haven't bollixed up the Cork class if we should make
 %%  changes.  We use Cork in the class hierarchy.
 %!shared crk
-%!test crk = Cork(23);
-%!  assert(click(crk),23)
+%!test crk = Cork (23);
+%! assert (isequal (click(crk), 23));
 %!test crk = click(crk,3);
-%!  assert(click(crk),3)
-%!test crk = set(crk,'click',13);
-%!  assert(get(crk, 'click'), 13)
-%!  assert(class(crk),'Cork');
-%!  assert(isa(crk,'Cork'))
+%! assert (isequal (click(crk), 3));
+%!test crk = set (crk, 'click', 13);
+%! assert (isequal (get (crk, 'click'), 13));
+%! assert (isequal (class (crk), 'Cork'));
+%! assert (isa (crk, 'Cork'));
 
 %%  The Dork class tests single inheritance.
 %!shared drk
-%!test drk = Dork();
-%!  assert(gack(drk),0)
-%!test drk = gack(drk,-2);
-%!  assert(gack(drk),-2)
-%!test drk = gick(drk,2);
-%!  assert(gick(drk),2);
-%!test drk = set(drk, 'gick',3, 'gack',-3);
-%!  assert(get(drk, 'gick'), 3)
-%!  assert(get(drk, 'gack'), -3)
-%!  assert(class(drk),'Dork')
-%!  assert(isa(drk,'Dork'))
-%!  assert(isa(drk,'Snork'))
-%!  assert(getStash(drk),2)
-%!test drk1 = Dork(drk);
-%!  assert(class(drk1),'Dork')
-%!  assert(isa(drk1,'Snork'))
-%!  assert(gick(drk1),3)
-%!  assert(gack(drk1),-3)
-%!test drk2 = Dork(-4,4);
-%!  assert(class(drk2),'Dork')
-%!  assert(isa(drk2,'Snork'))
-%!  assert(gick(drk2),-4)
-%!  assert(gack(drk2),4)
+%!test drk = Dork ();
+%! assert (isequal (gack (drk),0));
+%!test drk = gack (drk,-2);
+%! assert (isequal (gack (drk),-2));
+%!test drk = gick (drk,2);
+%! assert (isequal (gick (drk),2));
+%!test drk = set (drk, 'gick',3, 'gack',-3);
+%! assert (isequal (get (drk, 'gick'), 3));
+%! assert (isequal (get (drk, 'gack'), -3));
+%! assert (isequal (class (drk), 'Dork'));
+%! assert (isa (drk, 'Dork'));
+%! assert (isa (drk, 'Snork'));
+%! assert (isequal (getStash (drk), 2));
+%!test drk1 = Dork (drk);
+%! assert (isequal (class (drk1), 'Dork'));
+%! assert (isa (drk1, 'Snork'));
+%! assert (isequal (gick (drk1), 3));
+%! assert (isequal (gack (drk1), -3));
+%!test drk2 = Dork (-4, 4);
+%! assert (isequal (class (drk2), 'Dork'));
+%! assert (isa (drk2, 'Snork'));
+%! assert (isequal (gick (drk2), -4));
+%! assert (isequal (gack (drk2), 4));
 
 %%  The Pork class is essentially a clone of Dork.  It is used as part
 %%  of the multiple inheritance test.
 %!shared prk, drk
-%!test prk = Pork();
-%!  assert(geek(prk),1)
-%!  assert(gurk(prk),0)
-%!test prk = gurk(prk,-3);
-%!  assert(gurk(prk),-3)
-%!test prk = geek(prk,9);
-%!  assert(geek(prk),9)
-%!  assert(class(prk),'Pork')
-%!  assert(isa(prk,'Pork'))
-%!  assert(isa(prk,'Spork'))
-%!test drk = Dork();                   % Precedence.
-%!  assert(bling(drk,prk),2)
-%!  assert(bling(prk,drk),2)
-  
+%!test prk = Pork ();
+%! assert (isequal (geek (prk), 1));
+%! assert (isequal (gurk (prk), 0));
+%!test prk = gurk (prk,-3);
+%! assert (isequal (gurk (prk), -3));
+%!test prk = geek (prk,9);
+%! assert (isequal (geek (prk), 9));
+%! assert (isequal (class (prk), 'Pork'));
+%! assert (isa (prk, 'Pork'));
+%! assert (isa (prk, 'Spork'));
+%!test drk = Dork ();                   % Precedence.
+%! assert (isequal (bling (drk, prk), 2));
+%! assert (isequal (bling (prk, drk), 2));
+
 %%  The Gork class tests aggregation and multiple inheritance.
 %!shared grk
-%!test grk = Gork();
-%!  assert(gick(grk),1)
-%!  assert(geek(grk),1)
-%!  assert(gack(grk),0)
-%!  assert(gurk(grk),0)
-%!  assert(bleek(grk),1)
-%!  assert(gark(grk),-2)
-%!  assert(click(cork(grk)),17)
-%!  assert(class(cork(grk)),'Cork')
-%!test grk = gick(grk,3);
-%!test grk = geek(grk,4);
-%!test grk = gack(grk,-9);
-%!test grk = gurk(grk,-8);
-%!test grk = bleek(grk,-7);
-%!test grk = gark(grk,-6);
-%!test grk = cork(grk,click(cork(grk),23));
-%!  assert(gick(grk),3)
-%!  assert(geek(grk),4)
-%!  assert(gack(grk),-9)
-%!  assert(gurk(grk),-8)
-%!  assert(bleek(grk),-7)
-%!  assert(gark(grk),-6)
-%!  assert(click(cork(grk)),23)
+%!test grk = Gork ();
+%! assert (isequal (gick (grk), 1));
+%! assert (isequal (geek (grk), 1));
+%! assert (isequal (gack (grk), 0));
+%! assert (isequal (gurk (grk), 0));
+%! assert (isequal (bleek (grk), 1));
+%! assert (isequal (gark(grk), -2));
+%! assert (isequal (click (cork (grk)), 17));
+%! assert (isequal (class (cork (grk)), 'Cork'));
+%!test grk = gick (grk, 3);
+%!test grk = geek (grk, 4);
+%!test grk = gack (grk, -9);
+%!test grk = gurk (grk, -8);
+%!test grk = bleek (grk, -7);
+%!test grk = gark (grk, -6);
+%!test grk = cork (grk, click (cork (grk), 23));
+%! assert (isequal (gick (grk), 3));
+%! assert (isequal (geek (grk), 4));
+%! assert (isequal (gack (grk), -9));
+%! assert (isequal (gurk (grk), -8));
+%! assert (isequal (bleek (grk), -7));
+%! assert (isequal (gark (grk), -6));
+%! assert (isequal (click (cork (grk)), 23));
 %!test
-%!    cork1 = Cork(13);
-%!    grk = set(grk, 'gick',-5, 'gack',-6, 'gark',-7, 'cork',cork1);
-%!  assert(get(grk,'gick'),-5)
-%!  assert(get(grk,'gack'),-6)
-%!  assert(get(grk,'gark'),-7)
-%!  assert(click(get(grk, 'cork')),13);
-%!test grk = set(grk, 'cork',12);
-%!  assert(click(get(grk, 'cork')),12);
-%!  assert(class(cork(grk)),'Cork')
-%!  assert(class(grk),'Gork')
-%!  assert(isa(grk,'Gork'))
-%!  assert(isa(grk,'Dork'))
-%!  assert(isa(grk,'Pork'))
-%!  assert(isa(grk,'Blork'))
-%!  assert(isa(grk,'Snork'))
-%!  assert(isa(grk,'Spork'))
+%! cork1 = Cork (13);
+%! grk = set (grk, 'gick', -5, 'gack', -6, 'gark', -7, 'cork', cork1);
+%! assert (isequal (get (grk, 'gick'), -5));
+%! assert (isequal (get (grk, 'gack'), -6));
+%! assert (isequal (get (grk, 'gark'), -7));
+%! assert (isequal (click(get (grk, 'cork')), 13));
+%!test grk = set (grk, 'cork', 12);
+%! assert (isequal (click(get (grk, 'cork')),12));
+%! assert (isequal (class (cork(grk)), 'Cork'));
+%! assert (isequal (class (grk), 'Gork'));
+%! assert (isa (grk, 'Gork'));
+%! assert (isa (grk, 'Dork'));
+%! assert (isa (grk, 'Pork'));
+%! assert (isa (grk, 'Blork'));
+%! assert (isa (grk, 'Snork'));
+%! assert (isa (grk, 'Spork'));
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Testing (some) overloaded operators %%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%% Common variables for testing overloaded operators
+%!shared x1, x2, x3, s1, s2, s3
+%!  x1 = 1 + rand (3);    s1 = Snork (x1);
+%!  x2 = 1 + rand (3);    s2 = Snork (x2);
+%!  x3 = diag ([1 2 3]);  s3 = Snork (x3);
+
+%% Test overloaded plus (+) and uplus (unitary +) for the Snork class
+%!test  s = s1 + s2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 + x2));
+%!test  s = s1 + x2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 + x2));
+%!test  s = x1 + s2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 + x2));
+%!test  s = +s1;      assert (isequal (s, s1));
+
+%% Test overloaded minus (-) for the Snork class
+%!test  s = s1 - s2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 - x2));
+%!test  s = s1 - x2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 - x2));
+%!test  s = x1 - s2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 - x2));
+%!test  s = -s1;      assert (isequal (s, Snork (-x1)));
+
+%% Test overloaded mtimes (*) for the Snork class
+%!test  s = s1 * s2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 * x2));
+%!test  s = s1 * x2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 * x2));
+%!test  s = x1 * s2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 * x2));
+
+%% Test overloaded times (.*) for the Snork class
+%!test  s = s1 .* s2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 .* x2));
+%!test  s = s1 .* x2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 .* x2));
+%!test  s = x1 .* s2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 .* x2));
+
+%% Test overloaded mpower (^) for the Snork class
+%!test  s = s1 ^ 3;   assert (isa (s, 'Snork') && isequal (s.gick, x1 ^ 3));
+%!error <mpower Snork!!!>  s = s1 ^ s1;
+%!error <mpower Snork!!!>  s = 20 ^ s1;
+
+%% Test overloaded power (.^) for the Snork class
+%!test  s = s1 .^ 2;   assert (isa (s, 'Snork') && isequal (s.gick, x1 .^ 2));
+%!error <power Snork!!!>  s = s1 .^ s1;
+%!error <power Snork!!!>  s = 20 .^ s1;
+
+%% Test overloaded rdivide (./) for the Snork class
+%!test  s = s1 ./ s2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 ./ x2));
+%!test  s = s1 ./ x2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 ./ x2));
+%!test  s = x1 ./ s2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 ./ x2));
+
+%% Test overloaded ldivide (.\) for the Snork class
+%!test  s = s1 .\ s2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 .\ x2));
+%!test  s = s1 .\ x2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 .\ x2));
+%!test  s = x1 .\ s2;  assert (isa (s, 'Snork') && isequal (s.gick, x1 .\ x2));
+
+%% Test overloaded mrdivide (/) for the Snork class
+%!test  s = s1 / s3;  assert (isa (s, 'Snork') && isequal (s.gick, x1 / x3));
+%!test  s = s1 / x3;  assert (isa (s, 'Snork') && isequal (s.gick, x1 / x3));
+%!test  s = x1 / s3;  assert (isa (s, 'Snork') && isequal (s.gick, x1 / x3));
+
+%% Test overloaded mldivide (\) for the Snork class
+%!test  s = s3 \ s2;  assert (isa (s, 'Snork') && isequal (s.gick, x3 \ x2));
+%!test  s = s3 \ x2;  assert (isa (s, 'Snork') && isequal (s.gick, x3 \ x2));
+%!test  s = x3 \ s2;  assert (isa (s, 'Snork') && isequal (s.gick, x3 \ x2));
+
+%% Test overloaded eq (==) for the Snork class
+%!assert (s1 == s1)
+%!assert (s1 == x1)
+%!assert (x1 == s1)
+%!assert (~(s1 == (s1 + 1)))
+%!assert (~(s1 == (x1 + 1)))
+%!assert (~(x1 == (s1 + 1)))
+
+%% Test overloaded ne (~=) for the Snork class
+%!assert (~(s1 ~= s1))
+%!assert (~(s1 ~= x1))
+%!assert (~(x1 ~= s1))
+%!assert (s1 ~= (s1 + 1))
+%!assert (x1 ~= (s1 + 1))
+%!assert (s1 ~= (x1 + 1))
+
+%% Test overloaded lt (<) for the Snork class
+%!assert (s1 < (s1 + 1))
+%!assert (s1 < (x1 + 1))
+%!assert (x1 < (s1 + 1))
+
+%% Test overloaded gt (>) for the Snork class
+%!assert (s1 > (s1 - 1))
+%!assert (s1 > (x1 - 1))
+%!assert (x1 > (s1 - 1))
+
+%% Test overloaded lt (<=) for the Snork class
+%!assert (s1 <= (s1 + 1))
+%!assert (s1 <= (x1 + 1))
+%!assert (x1 <= (s1 + 1))
+
+%% Test overloaded gt (>=) for the Snork class
+%!assert (s1 >= (s1 - 1))
+%!assert (s1 >= (x1 - 1))
+%!assert (x1 >= (s1 - 1))
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%% Testing horizontal & vertical concatenation %%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+%% Test overloaded vertcat() for the Snork class
+%% See bug #38128 (http://savannah.gnu.org/bugs/?38128)
+%!test   s = [s1; s2];  assert (isa (s, 'Snork') && isequal (s.gick, [x1; x2]));
+%!xtest  s = [s1; x2];  assert (isa (s, 'Snork') && isequal (s.gick, [x1; x2]));
+%!xtest  s = [x1; s2];  assert (isa (s, 'Snork') && isequal (s.gick, [x1; x2]));
+
+%% Test overloaded horzcat() for the Snork class
+%% See bug #38128 (http://savannah.gnu.org/bugs/?38128)
+%!test   s = [s1 s2];  assert (isa (s, 'Snork') && isequal (s.gick, [x1 x2]));
+%!xtest  s = [s1 x2];  assert (isa (s, 'Snork') && isequal (s.gick, [x1 x2]));
+%!xtest  s = [x1 s2];  assert (isa (s, 'Snork') && isequal (s.gick, [x1 x2]));
+
+%% Test with the Blork class, where neither vertcat() nor horzcat() is overloaded
+%!shared x1, x2, x3
+%!test x1 = Blork ();
+%!test x2 = [x1 x1];
+%!assert (isa (x2, 'Blork') && isequal (size (x2), [1 2]));
+%!test x2 = [x1 51];
+%!assert (isa (x2, 'Blork') && isequal (size (x2), [1 2]));
+%!test x3 = [x2; x2];
+%!assert (isa (x3, 'Blork') && isequal (size (x3), [2 2]));
+%!test x3 = [x2; [51 x1]];
+%!assert (isa (x3, 'Blork') && isequal (size (x3), [2 2]));
+%!error <dimension mismatch> x4 = [x1  x3];
+%!error <dimension mismatch> x4 = [x1; x3];
+
+%%%%%%%%%%%%%%%%%%%%%%%%
+%% Testing precedence %%
+%%%%%%%%%%%%%%%%%%%%%%%%
+
+%% default: leftmost object wins
+%!shared A, B
+%!test A = Snork (rand (2));
+%!test B = CPrecedenceTester1 ();  % no call to inferiorto/superiorto
+%!assert (isequal (tattack (A, B), 'Snork'))
+%!assert (isequal (tattack (B, A), 'CPrecedenceTester1'))  % idem
+
+%!shared A, B
+%!test A = Snork (rand (2));
+%!test B = CPrecedenceTester2 (1);  % CPrecedenceTester2 > Snork
+%!assert (isequal (tattack (A, B), 'CPrecedenceTester2'))
+%!assert (isequal (tattack (B, A), 'CPrecedenceTester2'))
+%% Trying to change to CPrecendenceTester < Snork
+%!error D = CPrecedenceTester2 (2);
+
+%!shared A, B
+%!test A = Snork (rand (2));
+%!test B = CPrecedenceTester3 (2);  % CPrecedenceTester3 < Snork
+%!assert (isequal (tattack (A, B), 'Snork'))
+%!assert (isequal (tattack (B, A), 'Snork'))
+%% Trying to change to CPrecendenceTester3 > Snork
+%!error D = CPrecedenceTester3 (1);
+
--- a/test/classes/module.mk
+++ b/test/classes/module.mk
@@ -1,14 +1,18 @@
-classes_FCN_FILES = \
+class_Blork_FCN_FILES = \
   classes/@Blork/Blork.m \
   classes/@Blork/bleek.m \
   classes/@Blork/display.m \
   classes/@Blork/get.m \
-  classes/@Blork/set.m \
+  classes/@Blork/set.m
+
+class_Cork_FCN_FILES = \
   classes/@Cork/Cork.m \
   classes/@Cork/click.m \
   classes/@Cork/display.m \
   classes/@Cork/get.m \
-  classes/@Cork/set.m \
+  classes/@Cork/set.m
+
+class_Dork_FCN_FILES = \
   classes/@Dork/Dork.m \
   classes/@Dork/bling.m \
   classes/@Dork/display.m \
@@ -16,7 +20,9 @@
   classes/@Dork/get.m \
   classes/@Dork/getStash.m \
   classes/@Dork/private/myStash.m \
-  classes/@Dork/set.m \
+  classes/@Dork/set.m
+
+class_Gork_FCN_FILES = \
   classes/@Gork/Gork.m \
   classes/@Gork/cork.m \
   classes/@Gork/display.m \
@@ -24,30 +30,60 @@
   classes/@Gork/get.m \
   classes/@Gork/set.m \
   classes/@Gork/subsasgn.m \
-  classes/@Gork/subsref.m \
+  classes/@Gork/subsref.m
+
+class_Pork_FCN_FILES = \
   classes/@Pork/Pork.m \
   classes/@Pork/bling.m \
   classes/@Pork/display.m \
   classes/@Pork/get.m \
   classes/@Pork/gurk.m \
   classes/@Pork/private/myStash.m \
-  classes/@Pork/set.m \
+  classes/@Pork/set.m
+
+class_Sneetch_FCN_FILES = \
   classes/@Sneetch/Sneetch.m \
-  classes/@Sneetch/display.m \
+  classes/@Sneetch/display.m
+
+class_Snork_FCN_FILES = \
   classes/@Snork/Snork.m \
   classes/@Snork/cack.m \
   classes/@Snork/display.m \
+  classes/@Snork/double.m \
   classes/@Snork/end.m \
+  classes/@Snork/eq.m \
+  classes/@Snork/ge.m \
   classes/@Snork/get.m \
   classes/@Snork/getStash.m \
   classes/@Snork/gick.m \
+  classes/@Snork/gt.m \
+  classes/@Snork/horzcat.m \
+  classes/@Snork/ldivide.m \
+  classes/@Snork/le.m \
   classes/@Snork/loadobj.m \
+  classes/@Snork/lt.m \
+  classes/@Snork/minus.m \
+  classes/@Snork/mldivide.m \
+  classes/@Snork/mpower.m \
+  classes/@Snork/mrdivide.m \
+  classes/@Snork/mtimes.m \
+  classes/@Snork/ne.m \
+  classes/@Snork/plus.m \
+  classes/@Snork/power.m \
   classes/@Snork/private/myStash.m \
+  classes/@Snork/rdivide.m \
   classes/@Snork/saveobj.m \
   classes/@Snork/set.m \
   classes/@Snork/subsasgn.m \
   classes/@Snork/subsindex.m \
   classes/@Snork/subsref.m \
+  classes/@Snork/tattack.m \
+  classes/@Snork/times.m \
+  classes/@Snork/uminus.m \
+  classes/@Snork/uplus.m \
+  classes/@Snork/vertcat.m
+
+class_Spork_FCN_FILES = \
   classes/@Spork/Spork.m \
   classes/@Spork/cack.m \
   classes/@Spork/display.m \
@@ -57,7 +93,32 @@
   classes/@Spork/loadobj.m \
   classes/@Spork/private/myStash.m \
   classes/@Spork/saveobj.m \
-  classes/@Spork/set.m \
-  classes/test_classes.m
+  classes/@Spork/set.m
+
+class_CPrecedenceTester1_FCN_FILES = \
+  classes/@CPrecedenceTester1/CPrecedenceTester1.m \
+  classes/@CPrecedenceTester1/tattack.m
+
+class_CPrecedenceTester2_FCN_FILES = \
+  classes/@CPrecedenceTester2/CPrecedenceTester2.m \
+  classes/@CPrecedenceTester2/tattack.m
+
+class_CPrecedenceTester3_FCN_FILES = \
+  classes/@CPrecedenceTester3/CPrecedenceTester3.m \
+  classes/@CPrecedenceTester3/tattack.m
+
+classes_FCN_FILES = \
+  $(class_Blork_FCN_FILES) \
+  $(class_Cork_FCN_FILES) \
+  $(class_Dork_FCN_FILES) \
+  $(class_Gork_FCN_FILES) \
+  $(class_Pork_FCN_FILES) \
+  $(class_Sneetch_FCN_FILES) \
+  $(class_Snork_FCN_FILES) \
+  $(class_Spork_FCN_FILES) \
+  $(class_CPrecedenceTester1_FCN_FILES) \
+  $(class_CPrecedenceTester2_FCN_FILES) \
+  $(class_CPrecedenceTester3_FCN_FILES) \
+  classes/classes.tst
 
 FCN_FILES += $(classes_FCN_FILES)
--- a/test/ctor-vs-method/__trace__.m
+++ b/test/ctor-vs-method/__trace__.m
@@ -1,5 +1,6 @@
 function r = __trace__ (t)
   persistent history
+
   if (isempty (history))
     history = {};
   end
@@ -14,5 +15,5 @@
   else
     error ('incorrect call to __trace__');
   end
+
 end
-    
\ No newline at end of file
rename from test/ctor-vs-method/test_ctor_vs_method.m
rename to test/ctor-vs-method/ctor-vs-method.tst
--- a/test/ctor-vs-method/module.mk
+++ b/test/ctor-vs-method/module.mk
@@ -6,6 +6,6 @@
   ctor-vs-method/@parent/method.m \
   ctor-vs-method/@parent/parent.m \
   ctor-vs-method/__trace__.m \
-  ctor-vs-method/test_ctor_vs_method.m
+  ctor-vs-method/ctor-vs-method.tst
 
 FCN_FILES += $(ctor_vs_method_FCN_FILES)
rename from test/test_diag_perm.m
rename to test/diag-perm.tst
rename from test/test_error.m
rename to test/error.tst
--- a/test/test_error.m
+++ b/test/error.tst
@@ -19,20 +19,20 @@
 ## Test %!error usage
 
 %% test/octave.test/error/error-1.m
-%!function g () 
+%!function g ()
 %!  error ("foo");
 %!endfunction
-%!function f () 
-%!  g (); 
+%!function f ()
+%!  g ();
 %!endfunction
 %!error <foo> f ()
 
 %% test/octave.test/error/error-2.m
-%!function g () 
+%!function g ()
 %!  error ("foo\n");
 %!endfunction
-%!function f () 
-%!  g 
+%!function f ()
+%!  g
 %!endfunction
 %!error <foo> f ()
 
@@ -59,29 +59,29 @@
 %! ws = warning ("query", "backtrace");
 %! warning ("on", "backtrace");
 %! st.state = "on";
-%! assert(warning ("query", "backtrace"), st);
+%! assert (warning ("query", "backtrace"), st);
 %! warning ("off", "backtrace");
 %! st.state = "off";
-%! assert(warning ("query", "backtrace"), st);
+%! assert (warning ("query", "backtrace"), st);
 %! warning (ws.state, "backtrace");
 
 ## Test usage() function
 
 %% test/octave.test/error/usage-1.m
-%!function g () 
+%!function g ()
 %!  usage ("foo");
 %!endfunction
-%!function f () 
-%!  g (); 
+%!function f ()
+%!  g ();
 %!endfunction
 %!error <foo> f ()
 
 %% test/octave.test/error/usage-2.m
-%!function g () 
+%!function g ()
 %!  usage ("foo");
 %!endfunction
-%!function f () 
-%!  g 
+%!function f ()
+%!  g
 %!endfunction
 %!error <foo> f ()
 
rename from test/test_eval-catch.m
rename to test/eval-catch.tst
--- a/test/test_eval-catch.m
+++ b/test/eval-catch.tst
@@ -48,7 +48,7 @@
 %!endfunction
 %!test
 %! eval ("clear a; a; str='';", "str = mangle (lasterr);");
-%! assert (mangle(lasterr)(1:14), "<'a' undefined");
+%! assert (mangle (lasterr)(1:14), "<'a' undefined");
 %! assert (str(1:14), "<'a' undefined");
 
 %% test/octave.test/eval-catch/eval-catch-8.m
--- a/test/fcn-handle-derived-resolution/@other/getsize_arrayfun.m
+++ b/test/fcn-handle-derived-resolution/@other/getsize_arrayfun.m
@@ -1,3 +1,3 @@
 function r = getsize_arrayfun (x)
-  r = arrayfun (@(i) numel (x(i).d), 1:numel(x), 'uniformoutput', true);
+  r = arrayfun (@(i) numel (x(i).d), 1:numel (x), 'uniformoutput', true);
 end
rename from test/fcn-handle-derived-resolution/test_fcn_handle_derived_resolution.m
rename to test/fcn-handle-derived-resolution/fcn-handle-derived-resolution.tst
--- a/test/fcn-handle-derived-resolution/module.mk
+++ b/test/fcn-handle-derived-resolution/module.mk
@@ -6,6 +6,6 @@
   fcn-handle-derived-resolution/@other/other.m \
   fcn-handle-derived-resolution/@parent/numel.m \
   fcn-handle-derived-resolution/@parent/parent.m \
-  fcn-handle-derived-resolution/test_fcn_handle_derived_resolution.m
+  fcn-handle-derived-resolution/fcn-handle-derived-resolution.tst
 
 FCN_FILES += $(fcn_handle_derived_resolution_FCN_FILES)
--- a/test/fntests.m
+++ b/test/fntests.m
@@ -25,8 +25,10 @@
 
 currdir = canonicalize_file_name (".");
 
+debug_on_error (true);
+
 if (nargin == 1)
-  xdir = argv(){1};
+  xdir = argv (){1};
 else
   xdir = ".";
 endif
@@ -41,8 +43,8 @@
   testdirs = {currdir, srcdir};
 endif
 
-src_tree = canonicalize_file_name (fullfile (topsrcdir, "src"));
-liboctave_tree = canonicalize_file_name (fullfile (topsrcdir, "liboctave"));
+src_tree = canonicalize_file_name (fullfile (topbuilddir, "libinterp"));
+liboctave_tree = canonicalize_file_name (fullfile (topbuilddir, "liboctave"));
 script_tree = canonicalize_file_name (fullfile (topsrcdir, "scripts"));
 local_script_tree = canonicalize_file_name (fullfile (currdir, "../scripts"));
 
@@ -52,261 +54,4 @@
   fundirs{end+1} = local_script_tree;
 endif
 
-function print_test_file_name (nm)
-  filler = repmat (".", 1, 55-length (nm));
-  printf ("  %s %s", nm, filler);
-endfunction
-
-function print_pass_fail (n, p)
-  if (n > 0)
-    printf (" PASS %4d/%-4d", p, n);
-    nfail = n - p;
-    if (nfail > 0)
-      printf (" FAIL %d", nfail);
-    endif
-  endif
-  puts ("\n");
-endfunction
-
-function retval = has_functions (f)
-  n = length (f);
-  if (n > 3 && strcmp (f((end-2):end), ".cc"))
-    fid = fopen (f);
-    if (fid >= 0)
-      str = fread (fid, "*char")';
-      fclose (fid);
-      retval = ! isempty (regexp (str,'^(DEFUN|DEFUN_DLD)\b', 'lineanchors'));
-    else
-      error ("fopen failed: %s", f);
-    endif
-  elseif (n > 2 && strcmp (f((end-1):end), ".m"))
-    retval = true;
-  else
-    retval = false;
-  endif
-endfunction
-
-function retval = has_tests (f)
-  fid = fopen (f);
-  if (fid >= 0)
-    str = fread (fid, "*char")';
-    fclose (fid);
-    retval = ! isempty (regexp (str, '^%!(assert|error|fail|test|warning)', "lineanchors"));
-  else
-    error ("fopen failed: %s", f);
-  endif
-endfunction
-
-function retval = has_demos (f)
-  fid = fopen (f);
-  if (fid >= 0)
-    str = fread (fid, "*char")';
-    fclose (fid);
-    retval = ! isempty (regexp (str, '^%!demo', "lineanchors"));
-  else
-    error ("fopen failed: %s", f);
-  endif
-endfunction
-
-function [dp, dn, dxf, dsk] = run_test_dir (fid, d);
-  global files_with_tests;
-  global files_with_no_tests;
-  lst = dir (d);
-  dp = dn = dxf = dsk = 0;
-  for i = 1:length (lst)
-    nm = lst(i).name;
-    if (lst(i).isdir
-        && ! strcmp (nm, ".") && ! strcmp (nm, "..")
-        && ! strcmp (nm, "private") && nm(1) != "@"
-        && ! strcmp (nm, "CVS"))
-      [p, n, xf, sk] = run_test_dir (fid, [d, filesep, nm]);
-      dp += p;
-      dn += n;
-      dxf += xf;
-      dsk += sk;
-    endif
-  endfor
-  saved_dir = pwd ();
-  unwind_protect
-    chdir (d);
-    for i = 1:length (lst)
-      nm = lst(i).name;
-      if (length (nm) > 5 && strcmp (nm(1:5), "test_")
-          && strcmp (nm((end-1):end), ".m"))
-        p = n = xf = sk = 0;
-        ffnm = fullfile (d, nm);
-        if (has_tests (ffnm))
-          print_test_file_name (nm);
-          [p, n, xf, sk] = test (nm(1:(end-2)), "quiet", fid);
-          print_pass_fail (n, p);
-          files_with_tests(end+1) = ffnm;
-        ##elseif (has_demos (ffnm))
-        ##  files_with_tests(end+1) = ffnm;
-        else
-          files_with_no_tests(end+1) = ffnm;
-        endif
-        dp += p;
-        dn += n;
-        dxf += xf;
-        dsk += sk;
-      endif
-    endfor
-  unwind_protect_cleanup
-    chdir (saved_dir);
-  end_unwind_protect
-endfunction
-
-function [dp, dn, dxf, dsk] = run_test_script (fid, d);
-  global files_with_tests;
-  global files_with_no_tests;
-  global topsrcdir;
-  global topbuilddir;
-  lst = dir (d);
-  dp = dn = dxf = dsk = 0;
-  for i = 1:length (lst)
-    nm = lst(i).name;
-    if (lst(i).isdir && ! strcmp (nm, ".") && ! strcmp (nm, "..")
-        && ! strcmp (nm, "CVS"))
-      [p, n, xf, sk] = run_test_script (fid, [d, filesep, nm]);
-      dp += p;
-      dn += n;
-      dxf += xf;
-      dsk += sk;
-    endif
-  endfor
-  for i = 1:length (lst)
-    nm = lst(i).name;
-    ## Ignore hidden files
-    if (nm(1) == '.')
-      continue
-    endif
-    f = fullfile (d, nm);
-    if ((length (nm) > 2 && strcmp (nm((end-1):end), ".m")) || 
-        (length (nm) > 3 && strcmp (nm((end-2):end), ".cc")))
-      p = n = xf = 0;
-      ## Only run if it contains %!test, %!assert %!error or %!warning
-      if (has_tests (f))
-        tmp = strrep (f, [topsrcdir, filesep], "");
-        tmp = strrep (tmp, [topbuilddir, filesep], ["..", filesep]);
-        print_test_file_name (tmp);
-        [p, n, xf, sk] = test (f, "quiet", fid);
-        print_pass_fail (n, p);
-        dp += p;
-        dn += n;
-        dxf += xf;
-        dsk += sk;
-        files_with_tests(end+1) = f;
-      ##elseif (has_demos (f))
-      ##  files_with_tests(end+1) = f;
-      elseif (has_functions (f))
-        ## To reduce the list length, only mark .cc files that contain
-        ## DEFUN definitions.
-        files_with_no_tests(end+1) = f;
-      endif
-    endif
-  endfor 
-  ##  printf("%s%s -> passes %d of %d tests\n", ident, d, dp, dn);
-endfunction
-
-function printf_assert (varargin)
-  global _assert_printf;
-  _assert_printf = cat (2, _assert_printf, sprintf (varargin{:}));
-endfunction
-
-function ret = prog_output_assert (str)
-  global _assert_printf;
-  if (isempty (_assert_printf))
-    ret = isempty (str);
-  elseif (_assert_printf(end) == "\n")
-    ret = strcmp (_assert_printf(1:(end-1)), str);
-  else
-    ret = strcmp (_assert_printf, str);
-  endif
-  _assert_printf = "";
-endfunction
-
-function n = num_elts_matching_pattern (lst, pat)
-  n = sum (cellfun (@(x) !isempty (x), regexp (lst, pat, 'once')));
-endfunction
-
-function report_files_with_no_tests (with, without, typ)
-  pat = cstrcat ('\', typ, "$");
-  n_with = num_elts_matching_pattern (with, pat);
-  n_without = num_elts_matching_pattern (without, pat);
-  n_tot = n_with + n_without;
-  printf ("\n%d (of %d) %s files have no tests.\n", n_without, n_tot, typ);
-endfunction
-
-pso = page_screen_output ();
-warn_state = warning ("query", "quiet");
-warning ("on", "quiet");
-try
-  page_screen_output (0);
-  warning ("off", "Octave:deprecated-functions");
-  fid = fopen ("fntests.log", "wt");
-  if (fid < 0)
-    error ("could not open fntests.log for writing");
-  endif
-  test ("", "explain", fid);
-  dp = dn = dxf = dsk = 0;
-  puts ("\nIntegrated test scripts:\n\n");
-  for i = 1:length (fundirs)
-    [p, n, xf, sk] = run_test_script (fid, fundirs{i});
-    dp += p;
-    dn += n;
-    dxf += xf;
-    dsk += sk;
-  endfor
-  puts ("\nFixed test scripts:\n\n");
-  for i = 1:length (testdirs)
-    [p, n, xf, sk] = run_test_dir (fid, testdirs{i});
-    dp += p;
-    dn += n;
-    dxf += xf;
-    dsk += sk;
-  endfor
-  printf ("\nSummary:\n\n  PASS %6d\n", dp);
-  nfail = dn - dp;
-  printf ("  FAIL %6d\n", nfail);
-  if (dxf > 0)
-    if (dxf > 1)
-      t1 = "were";
-      t2 = "failures";
-    else
-      t1 = "was";
-      t2 = "failure";
-    endif
-    printf ("\nThere %s %d expected %s (see fntests.log for details).\n",
-            t1, dxf, t2);
-    puts ("\nExpected failures are known bugs.  Please help improve Octave\n");
-    puts ("by contributing fixes for them.\n");
-  endif
-  if (dsk > 0)
-    printf ("\nThere were %d skipped tests (see fntests.log for details).\n", dsk);
-    puts ("Skipped tests are features that are disabled in this version of Octave\n");
-    puts ("because the needed libraries were not present when Octave was built.\n");
-  endif
-
-  ## Weed out deprecated and private functions
-  weed_idx = cellfun (@isempty, regexp (files_with_tests, '\bdeprecated\b|\bprivate\b', 'once'));
-  files_with_tests = files_with_tests(weed_idx);
-  weed_idx = cellfun (@isempty, regexp (files_with_no_tests, '\bdeprecated\b|\bprivate\b', 'once'));
-  files_with_no_tests = files_with_no_tests(weed_idx);
-
-  report_files_with_no_tests (files_with_tests, files_with_no_tests, ".m");
-  report_files_with_no_tests (files_with_tests, files_with_no_tests, ".cc");
-
-  puts ("\nPlease help improve Octave by contributing tests for\n");
-  puts ("these files (see the list in the file fntests.log).\n\n");
-
-  fprintf (fid, "\nFiles with no tests:\n\n%s",
-          list_in_columns (files_with_no_tests, 80));
-  fclose (fid);
-
-  page_screen_output (pso);
-  warning (warn_state.state, "quiet");
-catch
-  page_screen_output (pso);
-  warning (warn_state.state, "quiet");
-  disp (lasterr ());
-end_try_catch
+__run_test_suite__ (fundirs, testdirs);
rename from test/test_for.m
rename to test/for.tst
--- a/test/test_for.m
+++ b/test/for.tst
@@ -19,60 +19,60 @@
 %% test/octave.test/for/for-1.m
 %!test
 %! for i = 1
-%!   printf_assert ("%d", i);
+%!   __printf_assert__ ("%d", i);
 %! end
-%! printf_assert ("\n");
-%! assert (prog_output_assert ("1"));
+%! __printf_assert__ ("\n");
+%! assert (__prog_output_assert__ ("1"));
 
 %% test/octave.test/for/for-2.m
 %!test
 %! for i = 1:4
-%!   printf_assert ("%d", i);
+%!   __printf_assert__ ("%d", i);
 %! endfor
-%! printf_assert ("\n");
-%! assert (prog_output_assert ("1234"));
+%! __printf_assert__ ("\n");
+%! assert (__prog_output_assert__ ("1234"));
 
 %% test/octave.test/for/for-3.m
 %!test
 %! for i = [1,2,3,4]
-%!   printf_assert ("%d", i);
+%!   __printf_assert__ ("%d", i);
 %! endfor
-%! printf_assert ("\n");
-%! assert (prog_output_assert ("1234"));
+%! __printf_assert__ ("\n");
+%! assert (__prog_output_assert__ ("1234"));
 
 %% test/octave.test/for/for-4.m
 %!test
 %! for i = [1,2;3,4]
-%!   printf_assert ("%d", i(1,1));
-%!   printf_assert ("%d", i(2,1));
+%!   __printf_assert__ ("%d", i(1,1));
+%!   __printf_assert__ ("%d", i(2,1));
 %! endfor
-%! printf_assert ("\n");
-%! assert (prog_output_assert ("1324"));
+%! __printf_assert__ ("\n");
+%! assert (__prog_output_assert__ ("1324"));
 
 %% test/octave.test/for/for-5.m
 %!test
 %! for i = I
-%!   printf_assert ("%d", imag (i));
+%!   __printf_assert__ ("%d", imag (i));
 %! endfor
-%! printf_assert ("\n");
-%! assert (prog_output_assert ("1"));
+%! __printf_assert__ ("\n");
+%! assert (__prog_output_assert__ ("1"));
 
 %% test/octave.test/for/for-6.m
 %!test
 %! for i = [1,2,3,4]*I
-%!   printf_assert ("%d", imag (i));
+%!   __printf_assert__ ("%d", imag (i));
 %! endfor
-%! printf_assert ("\n");
-%! assert (prog_output_assert ("1234"));
+%! __printf_assert__ ("\n");
+%! assert (__prog_output_assert__ ("1234"));
 
 %% test/octave.test/for/for-7.m
 %!test
 %! for i = [1,2;3,4]*I
-%!   printf_assert ("%d", imag (i(1,1)));
-%!   printf_assert ("%d", imag (i(2,1)));
+%!   __printf_assert__ ("%d", imag (i(1,1)));
+%!   __printf_assert__ ("%d", imag (i(2,1)));
 %! endfor
-%! printf_assert ("\n");
-%! assert (prog_output_assert ("1324"));
+%! __printf_assert__ ("\n");
+%! assert (__prog_output_assert__ ("1324"));
 
 %% test/octave.test/for/for-8.m
 %!test
@@ -80,10 +80,10 @@
 %!   if (i > 2)
 %!     break;
 %!   endif
-%!   printf_assert ("%d", i);
+%!   __printf_assert__ ("%d", i);
 %! endfor
-%! printf_assert ("\n");
-%! assert (prog_output_assert ("12"));
+%! __printf_assert__ ("\n");
+%! assert (__prog_output_assert__ ("12"));
 
 %% test/octave.test/for/for-9.m
 %!test
@@ -91,10 +91,10 @@
 %!   if (i < 3)
 %!     continue;
 %!   endif
-%!   printf_assert ("%d", i);
+%!   __printf_assert__ ("%d", i);
 %! endfor
-%! printf_assert ("\n");
-%! assert (prog_output_assert ("34"));
+%! __printf_assert__ ("\n");
+%! assert (__prog_output_assert__ ("34"));
 
 %!test
 %! a = [1,3;2,4];
@@ -106,6 +106,6 @@
 %!test
 %! a = {1,3;2,4};
 %! j = 0;
-%! for i = cat (3, a, cellfun(@(x) 4 + x, a, "UniformOutput", 0))
+%! for i = cat (3, a, cellfun (@(x) 4 + x, a, "UniformOutput", 0))
 %!   assert (i, {1 + 2*j; 2 + 2*j++})
 %! endfor
rename from test/test_func.m
rename to test/func.tst
--- a/test/test_func.m
+++ b/test/func.tst
@@ -16,8 +16,8 @@
 ## along with Octave; see the file COPYING.  If not, see
 ## <http://www.gnu.org/licenses/>.
 
-## This piece of test code ensures that all operations which work on 
-## dimensions alone (squeeze, triu, etc.) work for all objects and 
+## This piece of test code ensures that all operations which work on
+## dimensions alone (squeeze, triu, etc.) work for all objects and
 ## preserve type. Even if the object is an empty matrix. This code is
 ## not to check that the function itself returns teh correct result,
 ## just that the results are consistent for all types.
@@ -93,13 +93,13 @@
 %! m3 = [];
 
 %!test
-%! __fntestfunc__("triu", m1, {"struct"});
+%! __fntestfunc__ ("triu", m1, {"struct"});
 %!test
 %! __fntestfunc__ ("triu", m1, {"struct"}, -1);
 %!test
 %! __fntestfunc__ ("triu", m1, {"struct"}, 1);
 %!test
-%! __fntestfunc__("triu", m3, {"struct"});
+%! __fntestfunc__ ("triu", m3, {"struct"});
 %!test
 %! __fntestfunc__ ("tril", m1, {"struct"});
 %!test
@@ -107,7 +107,7 @@
 %!test
 %! __fntestfunc__ ("tril", m1, {"struct"}, 1);
 %!test
-%! __fntestfunc__("tril", m3, {"struct"});
+%! __fntestfunc__ ("tril", m3, {"struct"});
 %!test
 %! __fntestfunc__ ("squeeze", m2);
 %!test
rename from test/test_global.m
rename to test/global.tst
--- a/test/test_global.m
+++ b/test/global.tst
@@ -36,7 +36,7 @@
 %!endfunction
 %!test
 %! global G = 1;
-%! f();
+%! f ();
 
 %% test/octave.test/global/global-4.m
 %!function f ()
@@ -54,7 +54,7 @@
 %!function g ()
 %!  fail ("H");
 %!test
-%! g();
+%! g ();
 
 %% test/octave.test/global/global-6.m
 %!function f ()
@@ -65,8 +65,8 @@
 %!  assert (H,1);
 %!endfunction
 %!test
-%! f();
-%! g();
+%! f ();
+%! g ();
 
 %% test/octave.test/global/global-7.m
 %!test
rename from test/test_if.m
rename to test/if.tst
--- a/test/test_if.m
+++ b/test/if.tst
@@ -21,67 +21,67 @@
 %! i = 0;
 %! if (i == 0)
 %!   i++;
-%!   printf_assert ("%d\n", i);
+%!   __printf_assert__ ("%d\n", i);
 %! endif
-%! assert (prog_output_assert ("1"));
+%! assert (__prog_output_assert__ ("1"));
 
 %% test/octave.test/if/if-2.m
 %!test
 %! if (eye (2))
-%!   printf_assert ("fail\n");
+%!   __printf_assert__ ("fail\n");
 %! else
-%!   printf_assert ("pass\n");
+%!   __printf_assert__ ("pass\n");
 %! end
-%! assert (prog_output_assert ("pass"));
+%! assert (__prog_output_assert__ ("pass"));
 
 %% test/octave.test/if/if-3.m
 %!test
 %! x = 2;
 %! if (eye (2))
-%!   printf_assert ("fail\n");
+%!   __printf_assert__ ("fail\n");
 %! elseif (x)
-%!   printf_assert ("pass\n");
+%!   __printf_assert__ ("pass\n");
 %! endif
-%! assert (prog_output_assert ("pass"));
+%! assert (__prog_output_assert__ ("pass"));
 
 %% test/octave.test/if/if-4.m
 %!test
 %! x = 0;
 %! y = -2;
 %! if (eye (2))
-%!   printf_assert ("fail\n");
+%!   __printf_assert__ ("fail\n");
 %! elseif (x)
-%!   printf_assert ("fail\n");
+%!   __printf_assert__ ("fail\n");
 %! elseif (y)
-%!   printf_assert ("pass\n");
+%!   __printf_assert__ ("pass\n");
 %! end
-%! assert (prog_output_assert ("pass"));
+%! assert (__prog_output_assert__ ("pass"));
 
 %% test/octave.test/if/if-5.m
 %!test
 %! x = 0;
 %! y = -2;
 %! if (eye (2))
-%!   printf_assert ("fail\n");
+%!   __printf_assert__ ("fail\n");
 %! elseif (x)
-%!   printf_assert ("fail\n");
+%!   __printf_assert__ ("fail\n");
 %! elseif (x)
-%!   printf_assert ("fail\n");
+%!   __printf_assert__ ("fail\n");
 %! else
-%!   printf_assert ("pass\n");
+%!   __printf_assert__ ("pass\n");
 %! endif
-%! assert (prog_output_assert ("pass"));
+%! assert (__prog_output_assert__ ("pass"));
 
 %% test/octave.test/if/if-6.m
 %!test
 %! x = 0;
 %! y = -2;
 %! if (y)
-%!   printf_assert ("pass\n");
+%!   __printf_assert__ ("pass\n");
 %! elseif (x)
-%!   printf_assert ("fail\n");
+%!   __printf_assert__ ("fail\n");
 %! elseif (x)
-%!   printf_assert ("fail\n");
+%!   __printf_assert__ ("fail\n");
 %! end
-%! assert (prog_output_assert ("pass"));
+%! assert (__prog_output_assert__ ("pass"));
 
rename from test/test_index.m
rename to test/index.tst
--- a/test/test_index.m
+++ b/test/index.tst
@@ -26,7 +26,7 @@
 %!assert (a(:), 1)
 %!assert (a(:,:), 1)
 %!assert (a(1,:), 1)
-%!assert (a(:,1),1)
+%!assert (a(:,1), 1)
 %!assert (isempty (a(logical (0))))
 %!error a(-1)
 %!error a(2)
@@ -119,19 +119,19 @@
 %!assert (b(:), [1; 3; 2; 4; 5; 7; 6; 8])
 %!assert (b(:,:), [1, 2, 5, 6; 3, 4, 7, 8])
 %!assert (b(:,1), [1;3])
-%!assert (b(:,:,:), reshape ([1,3,2,4,5,7,6,8],[2,2,2]))
+%!assert (b(:,:,:), reshape ([1,3,2,4,5,7,6,8], [2,2,2]))
 %!assert (b(:,1,1), [1;3])
-%!assert (b(:,1,1,[1,1]),reshape ([1,3,1,3],[2,1,1,2]))
+%!assert (b(:,1,1,[1,1]),reshape ([1,3,1,3], [2,1,1,2]))
 %!assert (b(1,3), 5)
 %!assert (b(1,[3,4]), [5,6])
 %!assert (b(1,1:4), [1,2,5,6])
 %!assert (b(1,[],:), zeros (1,0,2))
-%!assert (b(1,[]), zeros(1,0))
+%!assert (b(1,[]), zeros (1,0))
 %!assert (b(:,3), [5;7])
 %!assert (b([1,2],3), [5;7])
-%!assert (b(true(2,1),3), [5;7])
-%!assert (b(false(2,1),3), zeros(0,1))
-%!assert (b([],3), zeros(0,1))
+%!assert (b(true (2,1), 3), [5;7])
+%!assert (b(false (2,1), 3), zeros (0,1))
+%!assert (b([],3), zeros (0,1))
 
 %!shared x
 %! # Dummy shared block to clear any previous definitions
@@ -160,7 +160,7 @@
 %! assert (a, b);
 
 %!test
-%! a(:,:,:) = 1:4; 
+%! a(:,:,:) = 1:4;
 %! assert (a, [1:4]);
 
 %!test
@@ -210,3 +210,20 @@
 %!error <attempted to use a complex scalar as an index> x(i)
 %!error <attempted to use a complex scalar as an index> x(j)
 %!error <attempted to use a complex scalar as an index> x(1+i)
+
+## bug #38357
+%!shared d, dd
+%! d = diag ([1, 2, 3]);
+%! dd = diag ([1, 2, 3], 6, 3);
+%!assert (d(1), 1);
+%!assert (dd(1), 1);
+%!assert (d(3, 3), 3);
+%!assert (dd(3, 3), 3);
+%!assert (d(2), 0);
+%!assert (dd(2), 0);
+%!assert (dd(6,1), 0);
+%!error d(6,6);
+%!error dd(6,6);
+%!error d(3,6);
+%!error dd(3,6);
+
rename from test/test_io.m
rename to test/io.tst
--- a/test/test_io.m
+++ b/test/io.tst
@@ -16,7 +16,7 @@
 ## along with Octave; see the file COPYING.  If not, see
 ## <http://www.gnu.org/licenses/>.
 
-## FIXME -- we should skip (or mark as an expected failure) the test for
+## FIXME: we should skip (or mark as an expected failure) the test for
 ## saving sparse matrices to MAT files when using 64-bit indexing since
 ## that is not implemented yet.
 
@@ -35,11 +35,11 @@
 %!  ## scalar
 %!  a1 = 1;
 %!  ## matrix
-%!  persistent a2 = hilb(3);
+%!  persistent a2 = hilb (3);
 %!  ## complex scalar
 %!  persistent a3 = 1 + 1i;
 %!  ## complex matrix
-%!  persistent a4 = hilb(3) + 1i*hilb(3);
+%!  persistent a4 = hilb (3) + 1i*hilb (3);
 %!  ## bool
 %!  persistent a5 = (1 == 1);
 %!  ## bool matrix
@@ -119,11 +119,11 @@
 %!      if (! isequal (a8, b8))
 %!        error ("failed: %s struct", file);
 %!      endif
-%!      
+%!
 %!      if (! isequal (a9, b9))
 %!        error ("failed: %s cell", file);
 %!      endif
-%!      
+%!
 %!      if (! isequal (a10, b10))
 %!        error ("failed: %s string", file);
 %!      endif
@@ -171,7 +171,7 @@
 %!          || isglobal ("a13") || isglobal ("a14") || isglobal ("a15")
 %!          || isglobal ("a16") || isglobal ("a17") || isglobal ("a18")
 %!          || isglobal ("a19") || isglobal ("a20"))
-%!        error ("failed: %s global test", file); 
+%!        error ("failed: %s global test", file);
 %!      endif
 %!    endfor
 %!  endif
@@ -180,24 +180,24 @@
 %!endfunction
 
 %!test
-%! 
+%!
 %! [save_status, save_files] = testls (0);
 %! [load_status, load_files] = testls (1);
-%! 
+%!
 %! for f = [save_files, load_files]
 %!   unlink (f{1});
 %! endfor
-%! 
+%!
 %! assert (save_status && load_status);
 
 %!test
-%! 
+%!
 %! STR.scalar_fld = 1;
 %! STR.matrix_fld = [1.1,2;3,4];
 %! STR.string_fld = "Octave";
 %! STR.struct_fld.x = 0;
 %! STR.struct_fld.y = 1;
-%! 
+%!
 %! save struct.dat -struct STR;
 %! STR = load ("struct.dat");
 %!
@@ -211,7 +211,7 @@
 %! save -binary struct.dat -struct STR matrix_fld str*_fld;
 %! STR = load ("struct.dat");
 %!
-%! assert (!isfield(STR,"scalar_fld") && ...
+%! assert (!isfield (STR,"scalar_fld") && ...
 %!         STR.matrix_fld == [1.1,2;3,4] && ...
 %!         STR.string_fld == "Octave" && ...
 %!         STR.struct_fld.x == 0 && ...
@@ -250,6 +250,12 @@
 
 %!assert (sscanf (['ab'; 'cd'], '%s'), 'acbd')
 
+%!assert (sscanf ('02:08:30', '%i:%i:%i'), [2; 0]);
+%!assert (sscanf ('02:08:30', '%d:%d:%d'), [2; 8; 30]);
+
+%!assert (sscanf ('0177 08', '%i'), [127; 0; 8]);
+%!assert (sscanf ('0177 08', '%d'), [177; 8]);
+
 %!test
 %! [val, count, msg, pos] = sscanf ("3I2", "%f");
 %! assert (val, 3);
@@ -276,7 +282,7 @@
 %! [a, b, c] = sscanf ("1.2 3 foo", "%f%d%s", "C");
 %! [v1, c1, m1] = sscanf ("1 2 3 4 5 6", "%d");
 %! [v2, c2, m2] = sscanf ("1 2 bar 3 4 5 6", "%d");
-%! 
+%!
 %! assert ((a == 1.2 && b == 3 && c == "foo"
 %! && v1 == [1; 2; 3; 4; 5; 6] && c1 == 6 && ischar (m1)
 %! && v2 == [1; 2] && c2 == 2 && ischar (m2)));
@@ -299,13 +305,13 @@
 %% test/octave.test/io/printf-1.m
 %!test
 %! nm = tmpnam ();
-%! fid1 = fopen(nm,"w");
+%! fid1 = fopen (nm,"w");
 %! x = fprintf (fid1, "%s: %d\n", "test", 1);
-%! fclose(fid1);
-%! fid2 = fopen(nm,"r");
-%! str = fscanf(fid2,"%s");
-%! fclose(fid2);
-%! unlink(nm);
+%! fclose (fid1);
+%! fid2 = fopen (nm,"r");
+%! str = fscanf (fid2,"%s");
+%! fclose (fid2);
+%! unlink (nm);
 %! assert (x, 8);
 %! assert (str, "test:1");
 
@@ -318,7 +324,7 @@
 %% test/octave.test/io/sprintf-1.m
 %!test
 %! [s, msg, status] = sprintf ("%s: %d\n", "test", 1);
-%! 
+%!
 %! assert (s == "test: 1\n" && ischar (msg) && status == 8);
 
 %% test/octave.test/io/sprintf-2.m
@@ -329,24 +335,28 @@
 
 %% test/octave.test/io/fopen-1.m
 %!test
-%! arch_list = ["native"; "ieee-le"; "ieee-be"; "vaxd"; "vaxg"; "cray"];
-%! 
+%! arch_list = {"native"; "ieee-le"; "ieee-be"; "vaxd"; "vaxg"; "cray"};
+%! warning ("off", "Octave:fopen-mode")
 %! status = 1;
-%! 
+%!
 %! for i = 1:6
-%!   arch = deblank (arch_list (i,:));
-%!   for j = 1:6
+%!   arch = arch_list{i};
+%!   for j = 1:4
 %!     if (j == 1)
-%!       mode_list = ["w"; "r"; "a"];
+%!       mode_list = {"w"; "r"; "a"};
 %!     elseif (j == 2)
-%!       mode_list = ["w+"; "r+"; "a+"];
+%!       mode_list = {"w+"; "r+"; "a+"};
+%!     elseif (j == 3)
+%!       mode_list = {"W"; "R"; "A"};
+%!     elseif (j == 4)
+%!       mode_list = {"W+"; "R+"; "A+"};
 %!     endif
 %!     nm = tmpnam ();
 %!     for k = 1:3
-%!       mode = deblank (mode_list (k,:));
+%!       mode = mode_list{k};
 %!       [id, err] = fopen (nm, mode, arch);
 %!       if (id < 0)
-%!         printf_assert ("open failed: %s (%s, %s): %s\n", nm, mode, arch, err);
+%!         __printf_assert__ ("open failed: %s (%s, %s): %s\n", nm, mode, arch, err);
 %!         status = 0;
 %!         break;
 %!       else
@@ -355,7 +365,7 @@
 %!       tmp_mode = cstrcat (mode, "b");
 %!       [id, err] = fopen (nm, tmp_mode, arch);
 %!       if (id < 0)
-%!         printf_assert ("open failed: %s (%s, %s): %s\n", nm, tmp_mode, arch, err);
+%!         __printf_assert__ ("open failed: %s (%s, %s): %s\n", nm, tmp_mode, arch, err);
 %!         status = 0;
 %!         break;
 %!       else
@@ -364,7 +374,7 @@
 %!       tmp_mode = cstrcat (mode, "t");
 %!       [id, err] = fopen (nm, tmp_mode, arch);
 %!       if (id < 0)
-%!         printf_assert ("open failed: %s (%s, %s): %s\n", nm, tmp_mode, arch, err);
+%!         __printf_assert__ ("open failed: %s (%s, %s): %s\n", nm, tmp_mode, arch, err);
 %!         status = 0;
 %!         break;
 %!       else
@@ -380,7 +390,7 @@
 %!     break;
 %!   endif
 %! endfor
-%! 
+%!
 %! assert (status == 1);
 
 %% test/octave.test/io/fopen-2.m
@@ -393,7 +403,7 @@
 
 %% test/octave.test/io/fopen-4.m
 %! fopen ("foo", "wb", "noodle");
-%! assert (prog_output_assert ("error:"));
+%! assert (__prog_output_assert__ ("error:"));
 
 %% test/octave.test/io/fopen-5.m
 %!error <Invalid call to fopen> fopen ()
@@ -427,7 +437,7 @@
 %! "uint"; "unsigned int"; "long"; "ulong"; "unsigned long";
 %! "float"; "float32"; "real*4"; "double"; "float64";
 %! "real*8"; "int16"; "integer*2"; "int32"; "integer*4"];
-%! 
+%!
 %! n = rows (type_list);
 %! nm = tmpnam ();
 %! id = fopen (nm, "wb");
@@ -437,22 +447,22 @@
 %!   endfor
 %!
 %!   fclose (id);
-%!   
+%!
 %!   id = fopen (nm, "rb");
 %!   if (id > 0)
 %!     x = zeros (1, n);
 %!     for i = 1:n
 %!       x(i) = fread (id, [1, 1], deblank (type_list(i,:)));
 %!     endfor
-%!     
+%!
 %!     if (x == 1:n)
-%!       printf_assert ("ok\n");
+%!       __printf_assert__ ("ok\n");
 %!     endif
 %!   endif
 %! endif
-%! 
+%!
 %! unlink (nm);
-%! assert (prog_output_assert ("ok"));
+%! assert (__prog_output_assert__ ("ok"));
 
 %% test/octave.test/io/file-pos-1.m
 %!test
rename from test/test_line_continue.m
rename to test/line-continue.tst
--- a/test/test_line_continue.m
+++ b/test/line-continue.tst
@@ -30,7 +30,7 @@
 %! x = [1;2];
 %! y = [a... # comments here ok
 %! ;\
-%! 
+%!
 %! b];
 %! assert (y, x);
 
@@ -58,9 +58,9 @@
 
 %!test
 %! x = [1, ...
-%! 
+%!
 %! ...
-%! 
+%!
 %! 2];
 %! y = [1;2];
 %! assert (y, x);
rename from test/test_logical_index.m
rename to test/logical-index.tst
new file mode 100644
--- /dev/null
+++ b/test/nest/arg_nest.m
@@ -0,0 +1,8 @@
+# arg_nest.m
+function x = arg_nest
+  x = 1;
+  A (x);
+  function A (x)
+    x = 2;
+  endfunction
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/nest/arg_ret.m
@@ -0,0 +1,7 @@
+function a = arg_ret
+  a = 10;
+  f;
+  function a = f
+    a = 5;
+  endfunction
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/nest/module.mk
@@ -0,0 +1,21 @@
+nest_fcn_files = \
+  nest/arg_nest.m \
+  nest/arg_ret.m \
+  nest/nest_eval.m \
+  nest/no_closure.m \
+  nest/persistent_nest.m \
+  nest/recursive_nest.m \
+  nest/recursive_nest2.m \
+  nest/recursive_nest3.m \
+  nest/scope0.m \
+  nest/scope1.m \
+  nest/scope2.m \
+  nest/scope3.m \
+  nest/script_nest.m \
+  nest/script_nest_script.m \
+  nest/nest.tst \
+  nest/varg_nest.m \
+  nest/varg_nest2.m
+
+FCN_FILES += $(nest_FCN_FILES)
+
new file mode 100644
--- /dev/null
+++ b/test/nest/nest.tst
@@ -0,0 +1,58 @@
+## Copyright (C) 2006-2012 John W. Eaton
+##
+## 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/>.
+
+################################################################################
+## This file actually executes the tests on nested functions.
+##
+## It relies on the function files defined in the nest/ directory.
+################################################################################
+
+%!assert (recursive_nest (), 25)
+
+%!assert (recursive_nest2 (), 20)
+
+%!assert (recursive_nest3 (), 5)
+
+%!assert (script_nest (), 5)
+
+%!assert (arg_ret (), 10)
+
+%!assert (arg_nest, 1)
+
+%!assert (varg_nest (-1), 6)
+
+%!assert (varg_nest2, 5)
+
+%!test
+%! scope0;
+
+%!test
+%! scope1 (1);
+
+%!test
+%! scope3;
+
+%!assert (nest_eval ("x = 5;", "x = 6;"), 6);
+%!assert (nest_eval ("x = 5;", "y = 6;"), 5);
+%!assert (nest_eval ("x = -5; x = abs (x);", "y = 6;"), 5);
+
+%!error <D' undefined near line 7> scope2
+%!error <handles to nested functions are not yet supported> no_closure (0)
+%!error <handles to nested functions are not yet supported> no_closure (1)
+%!error <can not add variable "y" to a static workspace> nest_eval ("y = 5;", "")
+%!error <can not add variable "y" to a static workspace> nest_eval ("y;", "")
new file mode 100644
--- /dev/null
+++ b/test/nest/nest_eval.m
@@ -0,0 +1,8 @@
+function x = nest_eval (a, b)
+  eval (a);
+  nested ();
+
+  function nested ()
+    eval (b);
+  endfunction
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/nest/no_closure.m
@@ -0,0 +1,11 @@
+# no_closure.m
+function no_closure (n)
+  if n == 0
+    x = @no_closure;
+  else
+    f = @no_closure;
+  endif
+
+  function f
+  endfunction
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/nest/persistent_nest.m
@@ -0,0 +1,10 @@
+# persistent_nest
+function y = persistent_nest ()
+  persistent x = 0;
+  g;
+  y = x;
+
+  function g
+    x = x + 1;
+  end
+end
new file mode 100644
--- /dev/null
+++ b/test/nest/recursive_nest.m
@@ -0,0 +1,13 @@
+# recursive_nest.m
+function x = recursive_nest ()
+  global recursive_nest_inc = 1
+  x = 5;
+  f (20);
+
+  function f (n)
+    if n > 0
+      x = x + recursive_nest_inc;
+      f (n - 1);
+    end
+  endfunction
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/nest/recursive_nest2.m
@@ -0,0 +1,21 @@
+# recursive_nest2.m
+function x = recursive_nest2 ()
+  x = B (20);
+  function v = B (n)
+    Y = 0;
+    BB (n);
+    C;
+    v = Y;
+    function BB (m)
+      if m > 0
+	Y = Y + 1;
+	BB(m - 1);
+	C;
+      end
+    endfunction
+  endfunction
+
+  function C
+    Y = 0;
+  endfunction
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/nest/recursive_nest3.m
@@ -0,0 +1,13 @@
+function x = recursive_nest3 ()
+  y = 5;
+  f (y);
+  x = y;
+  g (x);
+  function f (y)
+    y = 10;
+  endfunction
+
+  function g (x)
+    x = 10;
+  endfunction
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/nest/scope0.m
@@ -0,0 +1,16 @@
+# scope0.m
+function scope0
+  C;
+  function A
+    B;
+    function B
+    endfunction
+  endfunction
+
+  function C
+    D;
+    function D
+      A;
+    endfunction
+  endfunction
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/nest/scope1.m
@@ -0,0 +1,20 @@
+# scope1.m
+function scope1 (n)
+  value = n;
+  if value
+    C;
+  end
+  function A
+    B;
+    function B
+      scope1 (0);
+    endfunction
+  endfunction
+
+  function C
+    D;
+    function D
+      A;
+    endfunction
+  endfunction
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/nest/scope2.m
@@ -0,0 +1,17 @@
+# scope2.m
+function scope2
+  C;
+  function A
+    B;
+    function B
+      D;
+    endfunction
+  endfunction
+
+  function C
+    D;
+    function D
+      A;
+    endfunction
+  endfunction
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/nest/scope3.m
@@ -0,0 +1,19 @@
+# scope3.m
+function scope3
+  C;
+  function A
+    B;
+    function B
+      E;
+    endfunction
+    function E
+    endfunction
+  endfunction
+
+  function C
+    D;
+    function D
+      A;
+    endfunction
+  endfunction
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/nest/script_nest.m
@@ -0,0 +1,11 @@
+# script_nest.m
+function x = script_nest
+  A (5)
+  function A (n)
+    if n <= 0
+      script_nest_script;
+    else
+      A (n - 1);
+    endif
+  endfunction
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/nest/script_nest_script.m
@@ -0,0 +1,2 @@
+# script_nest_script.m
+x = 5;
new file mode 100644
--- /dev/null
+++ b/test/nest/varg_nest.m
@@ -0,0 +1,11 @@
+function x = varg_nest (varargin)
+  x = abs (f (-5)) + g;
+
+  function x = f (varargin)
+    x = abs (varargin{1});
+  endfunction
+
+  function x = g
+    x = abs (varargin{1});
+  endfunction
+endfunction
new file mode 100644
--- /dev/null
+++ b/test/nest/varg_nest2.m
@@ -0,0 +1,14 @@
+function x = varg_nest2
+  [a, b] = f;
+  x = a;
+
+  if nargout == 1
+    x = a;
+  endif
+
+  function a, b = f
+    if nargout == 2
+      a = b = 5;
+    endif
+  endfunction
+endfunction
rename from test/test_null_assign.m
rename to test/null-assign.tst
rename from test/test_parser.m
rename to test/parser.tst
rename from test/test_prefer.m
rename to test/prefer.tst
--- a/test/test_prefer.m
+++ b/test/prefer.tst
@@ -95,14 +95,14 @@
 %!test
 %! wrre = warning ("query", "Octave:resize-on-range-error");
 %! warning ("off", "Octave:resize-on-range-error");
-%! clear a; 
-%! a(2) = 1; a(3) = 2; 
+%! clear a;
+%! a(2) = 1; a(3) = 2;
 %! assert (all (a == [0,1,2]));
 %! warning (wrre.state, "Octave:resize-on-range-error");
 
 %% test/octave.test/prefer/prefer-18.m
 %!test
-%! clear a; 
+%! clear a;
 %! a(1) = 1; a(2) = 2;
 %! assert (all (a == [1,2]));
 
@@ -137,7 +137,7 @@
 %! save_precision (1);
 %! x = pi;
 %! nm = tmpnam ();
-%! save("-text", nm, "x");
+%! save ("-text", nm, "x");
 %! clear x;
 %! load (nm);
 %! unlink (nm);
@@ -150,14 +150,14 @@
 %! save_precision (5);
 %! x = pi;
 %! nm = tmpnam ();
-%! save("-text", nm, "x");
+%! save ("-text", nm, "x");
 %! clear x;
 %! load (nm);
 %! unlink (nm);
 %! assert (x, 3.1416);
 %! save_precision (sp);
 
-%% FIXME: How to capture standard output for comparison? 
+%% FIXME: How to capture standard output for comparison?
 %% test/octave.test/prefer/prefer-29.m
 %!function f ()
 %! 1
@@ -169,7 +169,7 @@
 %! assert (??);
 %! silent_functions (sf);
 
-%% FIXME Same problem as above!!!
+%% FIXME: Same problem as above!!!
 %% test/octave.test/prefer/prefer-30.m
 %!function f ()
 %! 1
rename from test/test_range.m
rename to test/range.tst
--- a/test/test_range.m
+++ b/test/range.tst
@@ -40,14 +40,14 @@
 %!assert ([ r ; sparse(z)          ], sparse (expect))
 %!assert ([ r ; sparse(logical(z)) ], sparse (expect))
 
-%!assert ([ r ; int8(z)            ], int8(expect))
-%!assert ([ r ; int16(z)           ], int16(expect))
-%!assert ([ r ; int32(z)           ], int32(expect))
-%!assert ([ r ; int64(z)           ], int64(expect))
-%!assert ([ r ; uint8(z)           ], uint8(expect))
-%!assert ([ r ; uint16(z)          ], uint16(expect))
-%!assert ([ r ; uint32(z)          ], uint32(expect))
-%!assert ([ r ; uint64(z)          ], uint64(expect))
+%!assert ([ r ; int8(z)            ], int8 (expect))
+%!assert ([ r ; int16(z)           ], int16 (expect))
+%!assert ([ r ; int32(z)           ], int32 (expect))
+%!assert ([ r ; int64(z)           ], int64 (expect))
+%!assert ([ r ; uint8(z)           ], uint8 (expect))
+%!assert ([ r ; uint16(z)          ], uint16 (expect))
+%!assert ([ r ; uint32(z)          ], uint32 (expect))
+%!assert ([ r ; uint64(z)          ], uint64 (expect))
 
 ## Test mixing non-integer range with other types
 
@@ -63,12 +63,47 @@
 %!assert ([ r ; sparse(z)          ], sparse (expect))
 %!assert ([ r ; sparse(logical(z)) ], sparse (expect))
 
-%!assert ([ r ; int8(z)            ], int8(expect))
-%!assert ([ r ; int16(z)           ], int16(expect))
-%!assert ([ r ; int32(z)           ], int32(expect))
-%!assert ([ r ; int64(z)           ], int64(expect))
-%!assert ([ r ; uint8(z)           ], uint8(expect))
-%!assert ([ r ; uint16(z)          ], uint16(expect))
-%!assert ([ r ; uint32(z)          ], uint32(expect))
-%!assert ([ r ; uint64(z)          ], uint64(expect))
+%!assert ([ r ; int8(z)            ], int8 (expect))
+%!assert ([ r ; int16(z)           ], int16 (expect))
+%!assert ([ r ; int32(z)           ], int32 (expect))
+%!assert ([ r ; int64(z)           ], int64 (expect))
+%!assert ([ r ; uint8(z)           ], uint8 (expect))
+%!assert ([ r ; uint16(z)          ], uint16 (expect))
+%!assert ([ r ; uint32(z)          ], uint32 (expect))
+%!assert ([ r ; uint64(z)          ], uint64 (expect))
+
+## Test corner cases of ranges (base and limit)
+
+%!shared r, rrev, rneg
+%! r = -0:3;
+%! rrev = 3:-1:-0;
+%! rneg = -3:-0;
 
+%!assert (full (r), [-0 1 2 3])
+%!assert (signbit (full (r)), logical ([1 0 0 0]))
+%!assert (r(1), -0)
+%!assert (signbit (r(1)), true)
+%!assert (signbit (r(1:2)), logical ([1 0]))
+%!assert (signbit (r(2:-1:1)), logical ([0 1]))
+%!assert (signbit (r([2 1 1 3])), logical ([0 1 1 0]))
+
+%!assert (full (rrev), [3 2 1 -0])
+%!assert (signbit (full (rrev)), logical ([0 0 0 1]))
+%!assert (rrev(4), -0)
+%!assert (signbit (rrev(4)), true)
+%!assert (signbit (rrev(3:4)), logical ([0 1]))
+%!assert (signbit (rrev(4:-1:3)), logical ([1 0]))
+%!assert (signbit (rrev([1 4 4 2])), logical ([0 1 1 0]))
+
+%!assert (min (r), -0)
+%!assert (signbit (min (r)), true)
+%!assert (min (rrev), -0)
+%!assert (signbit (min (rrev)), true)
+
+%!assert (max (rneg), -0)
+%!assert (signbit (max (rneg)), true)
+
+%!assert (sort (r, "descend"), [3 2 1 -0])
+%!assert (signbit (sort (r, "descend")), logical ([0 0 0 1]))
+%!assert (signbit (sort (rrev, "ascend")), logical ([1 0 0 0]))
+
rename from test/test_recursion.m
rename to test/recursion.tst
--- a/test/test_recursion.m
+++ b/test/recursion.tst
@@ -26,7 +26,7 @@
 %!  endif
 %!endfunction
 %!
-%!assert(f (5), 120);
+%!assert (f (5), 120)
 
 %% test/octave.test/recursion/recursion-2.m
 %!function y = f (x)
@@ -38,6 +38,7 @@
 %!  endif
 %!endfunction
 %!
-%!assert(f (5), 120);
+%!assert (f (5), 120)
 
 %%FIXME: Need test for maximum recursion depth
+
rename from test/test_return.m
rename to test/return.tst
--- a/test/test_return.m
+++ b/test/return.tst
@@ -23,7 +23,7 @@
 %!  y = 2;
 %!endfunction
 %!
-%!assert(f(), 1)
+%!assert (f (), 1)
 
 %% test/octave.test/return/return-2.m
 %!test
rename from test/test_slice.m
rename to test/slice.tst
--- a/test/test_slice.m
+++ b/test/slice.tst
@@ -32,7 +32,7 @@
 %!    case 33
 %!      x(:, :, slice) = 2;
 %!    otherwise
-%!      error("invalid dim, '%d'", dim);
+%!      error ("invalid dim, '%d'", dim);
 %!  endswitch
 %!endfunction
 
rename from test/test_struct.m
rename to test/struct.tst
--- a/test/test_struct.m
+++ b/test/struct.tst
@@ -152,8 +152,8 @@
 %! c(4, 4, 4, 4).name  = "a";
 %! c(3, 3, 3, 3).value = 1;
 %! [c([1, 3], 2, :, [3, 4]).value] = deal (1);
-%! assert (length(find([c.value] == 1)), 17);
-%! assert (length(find([c.value])), 17);
+%! assert (length (find ([c.value] == 1)), 17);
+%! assert (length (find ([c.value])), 17);
 
 ## swap elements of struct array
 %!test
@@ -166,7 +166,7 @@
 %! c(4, 4, 4, 4).value = 3;
 %! c(1, 2, 3, 4).value = 2;
 %! c(3, 3, 3, 3).value = 1;
-%! d = reshape ({c.value}, size(c));
+%! d = reshape ({c.value}, size (c));
 %! assert ([d{4, 4, 4, 4}, d{1, 2, 3, 4}, d{3, 3, 3, 3}],
 %!         [3, 2, 1]);
 
rename from test/test_switch.m
rename to test/switch.tst
--- a/test/test_switch.m
+++ b/test/switch.tst
@@ -21,12 +21,12 @@
 %! a = 1;
 %! b = 2;
 %! c = 3;
-%! 
+%!
 %! switch 0 case 1 x = a; case 2 x = b; otherwise x = c; endswitch
 %! switch 1 case 1 y = a; case 2 y = b; otherwise y = c; endswitch
 %! switch 2 case 1 z = a; case 2 z = b; otherwise z = c; endswitch
 %! switch 3 case 1 p = a; case 2 p = b; otherwise p = c; endswitch
-%! 
+%!
 %! assert (x == c && y == a && z == b && p == c);
 
 %% test/octave.test/switch/switch-2.m
@@ -34,11 +34,11 @@
 %! a = 1;
 %! b = 2;
 %! c = 3;
-%! 
+%!
 %! x = zeros (1, 4);
-%! 
+%!
 %! k = 1;
-%! 
+%!
 %! for i = 0:3
 %! switch (i)
 %!   case a
@@ -50,7 +50,7 @@
 %!   endswitch
 %!   k++;
 %! endfor
-%! 
+%!
 %! assert (all (x == [3, 1, 2, 3]));
 
 %% test/octave.test/switch/switch-3.m
@@ -58,11 +58,11 @@
 %! a = 1;
 %! b = 2;
 %! c = 3;
-%! 
+%!
 %! x = zeros (1, 4);
-%! 
+%!
 %! k = 1;
-%! 
+%!
 %! for i = 0:3
 %!   switch (i)
 %!   case a
@@ -70,7 +70,7 @@
 %!   endswitch
 %!   k++;
 %! endfor
-%! 
+%!
 %! assert (all (x == [0, 1, 0, 0]));
 
 %!test
@@ -80,7 +80,7 @@
 %! otherwise
 %!   a = 2;
 %! endswitch
-%! 
+%!
 %! assert (a == 2);
 
 
rename from test/test_system.m
rename to test/system.tst
--- a/test/test_system.m
+++ b/test/system.tst
@@ -39,8 +39,8 @@
 %% test/octave.test/system/pause-1.m
 %!test
 %! pause (0);
-%! printf_assert ("ok\n");
-%! assert (prog_output_assert ("ok"));
+%! __printf_assert__ ("ok\n");
+%! assert (__prog_output_assert__ ("ok"));
 
 %% test/octave.test/system/pause-2.m
 %!error <Invalid call to pause> pause (1, 2)
@@ -48,8 +48,8 @@
 %% test/octave.test/system/sleep-1.m
 %!test
 %! sleep (0);
-%! printf_assert ("ok\n");
-%! assert (prog_output_assert ("ok"));
+%! __printf_assert__ ("ok\n");
+%! assert (__prog_output_assert__ ("ok"));
 
 %% test/octave.test/system/sleep-2.m
 %!error <Invalid call to sleep> sleep ()
@@ -60,8 +60,8 @@
 %% test/octave.test/system/usleep-1.m
 %!test
 %! usleep (0);
-%! printf_assert ("ok\n");
-%! assert (prog_output_assert ("ok"));
+%! __printf_assert__ ("ok\n");
+%! assert (__prog_output_assert__ ("ok"));
 
 %% test/octave.test/system/usleep-2.m
 %!error <Invalid call to usleep> usleep ()
@@ -155,14 +155,14 @@
 %! s1 = stat (nm);
 %! fclose (id);
 %! unlink (nm);
-%! 
+%!
 %! umask (777);
 %! nm = tmpnam ();
 %! id = fopen (nm, "wb");
 %! s2 = stat (nm);
 %! fclose (id);
 %! unlink (nm);
-%! 
+%!
 %! assert (deblank (s1.modestr), "-rw-rw-rw-");
 %! assert (deblank (s2.modestr), "----------");
 %! # Restore original umask value
@@ -361,7 +361,7 @@
 %! else
 %!   assert ("/", d1);
 %! endif
-%! assert (pwd(), xdir);
+%! assert (pwd (), xdir);
 
 %% test/octave.test/system/cd-2.m
 %!error cd (1)
@@ -372,7 +372,7 @@
 %% test/octave.test/system/getpwent-1.m
 %!testif HAVE_GETPWENT
 %! s = getpwent ();
-%! endpwent (); 
+%! endpwent ();
 %! assert ((isstruct (s)
 %! && isfield (s, "name")
 %! && isfield (s, "passwd")
@@ -389,7 +389,7 @@
 %!testif HAVE_GETPWUID
 %! x = getpwent ();
 %! y = getpwuid (x.uid);
-%! endpwent (); 
+%! endpwent ();
 %! assert (strcmp (x.name, y.name) && x.uid == y.uid && x.gid == y.gid);
 
 %% test/octave.test/system/getpwuid-2.m
@@ -402,7 +402,7 @@
 %!testif HAVE_GETPWNAM
 %! x = getpwent ();
 %! y = getpwnam (x.name);
-%! endpwent (); 
+%! endpwent ();
 %! assert (strcmp (x.name, y.name) && x.uid == y.uid && x.gid == y.gid);
 
 %% test/octave.test/system/getpwnam-2.m
@@ -416,7 +416,7 @@
 %! x = getpwent ();
 %! setpwent ();
 %! y = getpwent ();
-%! endpwent (); 
+%! endpwent ();
 %! assert (strcmp (x.name, y.name) && x.uid == y.uid && x.gid == y.gid);
 
 %% test/octave.test/system/setpwent-2.m
rename from test/test_transpose.m
rename to test/transpose.tst
rename from test/test_try.m
rename to test/try.tst
--- a/test/test_try.m
+++ b/test/try.tst
@@ -68,7 +68,7 @@
 %! assert (lasterr()(1:13), "'a' undefined");
 
 %% test/octave.test/try/try-6.m
-%!test 
+%!test
 %! try
 %!   error ("user-defined error");
 %! catch
rename from test/test_unwind.m
rename to test/unwind.tst
rename from test/test_while.m
rename to test/while.tst
--- a/test/test_while.m
+++ b/test/while.tst
@@ -21,28 +21,28 @@
 %! i = 0;
 %! while (eye (2))
 %!   i++;
-%!   printf_assert ("%d\n", i);
+%!   __printf_assert__ ("%d\n", i);
 %! endwhile
-%! assert (prog_output_assert (""));
+%! assert (__prog_output_assert__ (""));
 
 %% test/octave.test/while/while-2.m
 %!test
 %! i = 5;
 %! while (--i)
-%!   printf_assert ("%d", i);
+%!   __printf_assert__ ("%d", i);
 %! endwhile
-%! printf_assert ("\n");
-%! assert (prog_output_assert ("4321"));
+%! __printf_assert__ ("\n");
+%! assert (__prog_output_assert__ ("4321"));
 
 %% test/octave.test/while/while-3.m
 %!test
 %! i = 5;
 %! while (i)
 %!   i--;
-%!   printf_assert ("%d", i);
+%!   __printf_assert__ ("%d", i);
 %! endwhile
-%! printf_assert ("\n");
-%! assert (prog_output_assert ("43210"));
+%! __printf_assert__ ("\n");
+%! assert (__prog_output_assert__ ("43210"));
 
 %% test/octave.test/while/while-4.m
 %!test
@@ -51,10 +51,10 @@
 %!   if (i > 2)
 %!     break;
 %!   endif
-%!   printf_assert ("%d", i);
+%!   __printf_assert__ ("%d", i);
 %! endwhile
-%! printf_assert ("\n");
-%! assert (prog_output_assert ("12"));
+%! __printf_assert__ ("\n");
+%! assert (__prog_output_assert__ ("12"));
 
 %% test/octave.test/while/while-5.m
 %!test
@@ -63,8 +63,8 @@
 %!   if (i < 3)
 %!     continue;
 %!   endif
-%!   printf_assert ("%d", i);
+%!   __printf_assert__ ("%d", i);
 %! endwhile
-%! printf_assert ("\n");
-%! assert (prog_output_assert ("34"));
+%! __printf_assert__ ("\n");
+%! assert (__prog_output_assert__ ("34"));