This is octave.info, produced by makeinfo version 4.11 from ./octave.texi.

START-INFO-DIR-ENTRY
* Octave: (octave).	Interactive language for numerical computations.
END-INFO-DIR-ENTRY

   Copyright (C) 1996, 1997, 1999, 2000, 2001, 2002, 2005, 2006, 2007
John W. Eaton.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided that
the entire resulting derived work is distributed under the terms of a
permission notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions.


File: octave.info,  Node: Filesystem Utilities,  Next: File Archiving Utilities,  Prev: Timing Utilities,  Up: System Utilities

34.2 Filesystem Utilities
=========================

Octave includes the following functions for renaming and deleting files,
creating, deleting, and reading directories, and for getting information
about the status of files.

 -- Built-in Function: [ERR, MSG] = rename (OLD, NEW)
     Change the name of file OLD to NEW.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

     *See also:* *note ls: doc-ls, *note dir: doc-dir.

 -- Built-in Function: [ERR, MSG] = link (OLD, NEW)
     Create a new link (also known as a hard link) to an existing file.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

     *See also:* *note symlink: doc-symlink.

 -- Built-in Function: [ERR, MSG] = symlink (OLD, NEW)
     Create a symbolic link NEW which contains the string OLD.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

     *See also:* *note link: doc-link, *note readlink: doc-readlink.

 -- Built-in Function: [RESULT, ERR, MSG] = readlink (SYMLINK)
     Read the value of the symbolic link SYMLINK.

     If successful, RESULT contains the contents of the symbolic link
     SYMLINK, ERR is 0 and MSG is an empty string.  Otherwise, ERR is
     nonzero and MSG contains a system-dependent error message.

     *See also:* *note link: doc-link, *note symlink: doc-symlink.

 -- Built-in Function: [ERR, MSG] = unlink (FILE)
     Delete the file named FILE.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

 -- Built-in Function: [FILES, ERR, MSG] = readdir (DIR)
     Return names of the files in the directory DIR as a cell array of
     strings.  If an error occurs, return an empty cell array in FILES.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

     *See also:* *note dir: doc-dir, *note glob: doc-glob.

 -- Built-in Function: [STATUS, MSG, MSGID] = mkdir (DIR)
 -- Built-in Function: [STATUS, MSG, MSGID] = mkdir (PARENT, DIR)
     Create a directory named DIR in the directory PARENT.

     If successful, STATUS is 1, with MSG and MSGID empty character
     strings.  Otherwise, STATUS is 0, MSG contains a system-dependent
     error message, and MSGID contains a unique message identifier.

     *See also:* *note rmdir: doc-rmdir.

 -- Built-in Function: [STATUS, MSG, MSGID] = rmdir (DIR)
 -- Built-in Function: [STATUS, MSG, MSGID] = rmdir (DIR, `"s"')
     Remove the directory named DIR.

     If successful, STATUS is 1, with MSG and MSGID empty character
     strings.  Otherwise, STATUS is 0, MSG contains a system-dependent
     error message, and MSGID contains a unique message identifier.

     If the optional second parameter is supplied with value `"s"',
     recursively remove all subdirectories as well.

     *See also:* *note mkdir: doc-mkdir, *note confirm_recursive_rmdir:
     doc-confirm_recursive_rmdir.

 -- Built-in Function: VAL = confirm_recursive_rmdir ()
 -- Built-in Function: OLD_VAL = confirm_recursive_rmdir (NEW_VAL)
     Query or set the internal variable that controls whether Octave
     will ask for confirmation before recursively removing a directory
     tree.

 -- Built-in Function: [ERR, MSG] = mkfifo (NAME, MODE)
     Create a FIFO special file named NAME with file mode MODE

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

 -- Built-in Function:  umask (MASK)
     Set the permission mask for file creation.  The parameter MASK is
     an integer, interpreted as an octal number.  If successful,
     returns the previous value of the mask (as an integer to be
     interpreted as an octal number); otherwise an error message is
     printed.

 -- Built-in Function: [INFO, ERR, MSG] = stat (FILE)
 -- Built-in Function: [INFO, ERR, MSG] = lstat (FILE)
     Return a structure S containing the following information about
     FILE.

    `dev'
          ID of device containing a directory entry for this file.

    `ino'
          File number of the file.

    `mode'
          File mode, as an integer.  Use the functions `S_ISREG',
          `S_ISDIR', `S_ISCHR', `S_ISBLK', `S_ISFIFO', `S_ISLNK', or
          `S_ISSOCK' to extract information from this value.

    `modestr'
          File mode, as a string of ten letters or dashes as would be
          returned by `ls -l'.

    `nlink'
          Number of links.

    `uid'
          User ID of file's owner.

    `gid'
          Group ID of file's group.

    `rdev'
          ID of device for block or character special files.

    `size'
          Size in bytes.

    `atime'
          Time of last access in the same form as time values returned
          from `time'.  *Note Timing Utilities::.

    `mtime'
          Time of last modification in the same form as time values
          returned from `time'.  *Note Timing Utilities::.

    `ctime'
          Time of last file status change in the same form as time
          values returned from `time'.  *Note Timing Utilities::.

    `blksize'
          Size of blocks in the file.

    `blocks'
          Number of blocks allocated for file.

     If the call is successful ERR is 0 and MSG is an empty string.  If
     the file does not exist, or some other error occurs, S is an empty
     matrix, ERR is -1, and MSG contains the corresponding system error
     message.

     If FILE is a symbolic link, `stat' will return information about
     the actual file that is referenced by the link.  Use `lstat' if
     you want information about the symbolic link itself.

     For example,

          [s, err, msg] = stat ("/vmlinuz")
                => s =
                  {
                    atime = 855399756
                    rdev = 0
                    ctime = 847219094
                    uid = 0
                    size = 389218
                    blksize = 4096
                    mtime = 847219094
                    gid = 6
                    nlink = 1
                    blocks = 768
                    mode = -rw-r--r--
                    modestr = -rw-r--r--
                    ino = 9316
                    dev = 2049
                  }
               => err = 0
               => msg =

 -- Built-in Function: [INFO, ERR, MSG] = fstat (FID)
     Return information about the open file FID.  See `stat' for a
     description of the contents of INFO.

 -- Function File: [STATUS, MSG, MSGID] = fileattrib (FILE)
     Return information about FILE.

     If successful, STATUS is 1, with RESULT containing a structure
     with the following fields:

    `Name'
          Full name of FILE.

    `archive'
          True if FILE is an archive (Windows).

    `system'
          True if FILE is a system file (Windows).

    `hidden'
          True if FILE is a hidden file (Windows).

    `directory'
          True if FILE is a directory.

    `UserRead'
    `GroupRead'
    `OtherRead'
          True if the user (group; other users) has read permission for
          FILE.

    `UserWrite'
    `GroupWrite'
    `OtherWrite'
          True if the user (group; other users) has write permission for
          FILE.

    `UserExecute'
    `GroupExecute'
    `OtherExecute'
          True if the user (group; other users) has execute permission
          for FILE.
     If an attribute does not apply (i.e., archive on a Unix system)
     then the field is set to NaN.

     With no input arguments, return information about the current
     directory.

     If FILE contains globbing characters, return information about all
     the matching files.

     *See also:* *note glob: doc-glob.

 -- Function File:  isdir (F)
     Return true if F is a directory.

 -- Built-in Function:  glob (PATTERN)
     Given an array of strings (as a char array or a cell array) in
     PATTERN, return a cell array of file names that match any of them,
     or an empty cell array if no patterns match.  Tilde expansion is
     performed on each of the patterns before looking for matching file
     names.  For example,

          glob ("/vm*")
               => "/vmlinuz"

     *See also:* *note dir: doc-dir, *note ls: doc-ls, *note stat:
     doc-stat, *note readdir: doc-readdir.

 -- Built-in Function:  fnmatch (PATTERN, STRING)
     Return 1 or zero for each element of STRING that matches any of
     the elements of the string array PATTERN, using the rules of
     filename pattern matching.  For example,

          fnmatch ("a*b", {"ab"; "axyzb"; "xyzab"})
               => [ 1; 1; 0 ]

 -- Built-in Function:  file_in_path (PATH, FILE)
 -- Built-in Function:  file_in_path (PATH, FILE, "all")
     Return the absolute name of FILE if it can be found in PATH.  The
     value of PATH should be a colon-separated list of directories in
     the format described for `path'.  If no file is found, return an
     empty matrix.  For example,

          file_in_path (EXEC_PATH, "sh")
               => "/bin/sh"

     If the second argument is a cell array of strings, search each
     directory of the path for element of the cell array and return the
     first that matches.

     If the third optional argument `"all"' is supplied, return a cell
     array containing the list of all files that have the same name in
     the path.  If no files are found, return an empty cell array.

     *See also:* *note file_in_loadpath: doc-file_in_loadpath.

 -- Built-in Function:  tilde_expand (STRING)
     Performs tilde expansion on STRING.  If STRING begins with a tilde
     character, (`~'), all of the characters preceding the first slash
     (or all characters, if there is no slash) are treated as a
     possible user name, and the tilde and the following characters up
     to the slash are replaced by the home directory of the named user.
     If the tilde is followed immediately by a slash, the tilde is
     replaced by the home directory of the user running Octave.  For
     example,

          tilde_expand ("~joeuser/bin")
               => "/home/joeuser/bin"
          tilde_expand ("~/bin")
               => "/home/jwe/bin"

 -- Built-in Function: [CNAME, STATUS, MSG] canonicalize_file_name
          (NAME)
     Return the canonical name of file NAME.

 -- Function File: [STATUS, MSG, MSGID] = movefile (F1, F2)
     Move the file F1 to the new name F2.  The name F1 may contain
     globbing patterns.  If F1 expands to multiple file names, F2 must
     be a directory.

     If successful, STATUS is 1, with MSG and MSGID empty\n\ character
     strings.  Otherwise, STATUS is 0, MSG contains a\n\
     system-dependent error message, and MSGID contains a unique\n\
     message identifier.\n\

     *See also:* *note glob: doc-glob.

 -- Function File: [STATUS, MSG, MSGID] = copyfile (F1, F2, FORCE)
     Copy the file F1 to the new name F2.  The name F1 may contain
     globbing patterns.  If F1 expands to multiple file names, F2 must
     be a directory.  If FORCE is given and equals the string "f" the
     copy operation will be forced.

     If successful, STATUS is 1, with MSG and MSGID empty\n\ character
     strings.  Otherwise, STATUS is 0, MSG contains a\n\
     system-dependent error message, and MSGID contains a unique\n\
     message identifier.\n\

     *See also:* *note glob: doc-glob, *note movefile: doc-movefile.

 -- Function File: [DIR, NAME, EXT, VER] = fileparts (FILENAME)
     Return the directory, name, extension, and version components of
     FILENAME.

     *See also:* *note fullfile: doc-fullfile.

 -- Built-in Function:  filesep ()
 -- Built-in Function:  filesep ('all')
     Return the system-dependent character used to separate directory
     names.

     If 'all' is given, the function return all valid file separators in
     the form of a string.  The list of file separators is
     system-dependent.  It is / (forward slash) under UNIX or Mac OS X,
     / and \ (forward and backward slashes) under Windows.

     *See also:* *note pathsep: doc-pathsep, *note dir: doc-dir, *note
     ls: doc-ls.

 -- Built-in Function:  filemarker ()
     Returns or sets the character used to separate filename from the
     the subfunction names contained within the file.  This can be used
     in a generic manner to interact with subfunctions.  For example

          help (["myfunc", filemarker, "mysubfunc"])

     returns the help string associated with the sub-function
     `mysubfunc' of the function `myfunc'.  Another use of `filemarker'
     is when debugging it allows easier placement of breakpoints within
     sub-functions.  For example

          dbstop (["myfunc", filemarker, "mysubfunc"])

     will set a breakpoint at the first line of the subfunction
     `mysubfunc'.

 -- Function File: FILENAME = fullfile (DIR1, DIR2, ..., FILE)
     Return a complete filename constructed from the given components.

     *See also:* *note fileparts: doc-fileparts.

 -- Function File: DIR = tempdir ()
     Return the name of the system's directory for temporary files.

 -- Function File: filename = tempname ()
     This function is an alias for `tmpnam'.

 -- Built-in Function:  P_tmpdir ()
     Return the default name of the directory for temporary files on
     this system.  The name of this directory is system dependent.

 -- Built-in Function:  is_absolute_filename (FILE)
     Return true if FILE is an absolute filename.

 -- Built-in Function:  is_rooted_relative_filename (FILE)
     Return true if FILE is a rooted-relative filename.

 -- Built-in Function:  make_absolute_filename (FILE)
     Return the full name of FILE, relative to the current directory.


File: octave.info,  Node: File Archiving Utilities,  Next: Networking Utilities,  Prev: Filesystem Utilities,  Up: System Utilities

34.3 File Archiving Utilities
=============================

 -- Function File:  bunzip2 (BZFILE, DIR)
     Unpack the bzip2 archive BZFILE to the directory DIR.  If DIR is
     not specified, it defaults to the current directory.

     *See also:* *note unpack: doc-unpack, *note bzip2: doc-bzip2,
     *note tar: doc-tar, *note untar: doc-untar, *note gzip: doc-gzip,
     *note gunzip: doc-gunzip, *note zip: doc-zip, *note unzip:
     doc-unzip.

 -- Function File: ENTRIES = gzip (FILES)
 -- Function File: ENTRIES = gzip (FILES, OUTDIR)
     Compress the list of files and/or directories specified in FILES.
     Each file is compressed separately and a new file with a '.gz'
     extension is created.  The original files are not touched.
     Existing compressed files are silently overwritten.  If OUTDIR is
     defined the compressed versions of the files are placed in this
     directory.

     *See also:* *note gunzip: doc-gunzip, *note bzip2: doc-bzip2,
     *note zip: doc-zip, *note tar: doc-tar.

 -- Function File:  gunzip (GZFILE, DIR)
     Unpack the gzip archive GZFILE to the directory DIR.  If DIR is
     not specified, it defaults to the current directory.  If the
     GZFILE is a directory, all files in the directory will be
     recursively gunzipped.

     *See also:* *note unpack: doc-unpack, *note bunzip2: doc-bunzip2,
     *note tar: doc-tar, *note untar: doc-untar, *note gzip: doc-gzip,
     *note gunzip: doc-gunzip, *note zip: doc-zip, *note unzip:
     doc-unzip.

 -- Function File: ENTRIES = tar (TARFILE, FILES, ROOT)
     Pack FILES FILES into the TAR archive TARFILE.  The list of files
     must be a string or a cell array of strings.

     The optional argument ROOT changes the relative path of FILES from
     the current directory.

     If an output argument is requested the entries in the archive are
     returned in a cell array.

     *See also:* *note untar: doc-untar, *note gzip: doc-gzip, *note
     gunzip: doc-gunzip, *note zip: doc-zip, *note unzip: doc-unzip.

 -- Function File:  untar (TARFILE, DIR)
     Unpack the TAR archive TARFILE to the directory DIR.  If DIR is
     not specified, it defaults to the current directory.

     *See also:* *note unpack: doc-unpack, *note bunzip2: doc-bunzip2,
     *note tar: doc-tar, *note gzip: doc-gzip, *note gunzip:
     doc-gunzip, *note zip: doc-zip, *note unzip: doc-unzip.

 -- Function File: ENTRIES = zip (ZIPFILE, FILES)
 -- Function File: ENTRIES = zip (ZIPFILE, FILES, ROOTDIR)
     Compress the list of files and/or directories specified in FILES
     into the archive ZIPFILES in the same directory.  If ROOTDIR is
     defined the FILES is located relative to ROOTDIR rather than the
     current directory

     *See also:* *note unzip: doc-unzip, *note tar: doc-tar.

 -- Function File:  unzip (ZIPFILE, DIR)
     Unpack the ZIP archive ZIPFILE to the directory DIR.  If DIR is
     not specified, it defaults to the current directory.

     *See also:* *note unpack: doc-unpack, *note bunzip2: doc-bunzip2,
     *note tar: doc-tar, *note untar: doc-untar, *note gzip: doc-gzip,
     *note gunzip: doc-gunzip, *note zip: doc-zip.

 -- Function File:  pack ()
     This function is provided for compatibility with MATLAB, but it
     doesn't actually do anything.

 -- Function File: FILES = unpack (FILE, DIR)
 -- Function File: FILES = unpack (FILE, DIR, FILETYPE)
     Unpack the archive FILE based on its extension to the directory
     DIR.  If FILE is a cellstr, then all files will be handled
     individually.  If DIR is not specified, it defaults to the current
     directory.  It returns a list of FILES unpacked.  If a directory
     is in the file list, then the FILETYPE to unpack must also be
     specified.

     The FILES includes the entire path to the output files.

     *See also:* *note bunzip2: doc-bunzip2, *note tar: doc-tar, *note
     untar: doc-untar, *note gzip: doc-gzip, *note gunzip: doc-gunzip,
     *note zip: doc-zip, *note unzip: doc-unzip.

 -- Function File: ENTRIES = bzip2 (FILES)
 -- Function File: ENTRIES = bzip2 (FILES, OUTDIR)
     Compress the list of files specified in FILES.  Each file is
     compressed separately and a new file with a '.bz2' extension is
     created.  The original files are not touched.  Existing compressed
     files are silently overwritten.If OUTDIR is defined the compressed
     versions of the files are placed in this directory.

     *See also:* *note bunzip2: doc-bunzip2, *note gzip: doc-gzip,
     *note zip: doc-zip, *note tar: doc-tar.


File: octave.info,  Node: Networking Utilities,  Next: Controlling Subprocesses,  Prev: File Archiving Utilities,  Up: System Utilities

34.4 Networking Utilities
=========================

 -- Loadable Function: S = urlread (URL)
 -- Loadable Function: [S, SUCCESS] = urlread (URL)
 -- Loadable Function: [S, SUCCESS, MESSAGE] = urlread (URL)
 -- Loadable Function: [...] = urlread (URL, METHOD, PARAM)
     Download a remote file specified by its URL and return its content
     in string S.  For example,

          s = urlread ("ftp://ftp.octave.org/pub/octave/README");

     The variable SUCCESS is 1 if the download was successful,
     otherwise it is 0 in which case MESSAGE contains an error message.
     If no output argument is specified and if an error occurs, then
     the error is signaled through Octave's error handling mechanism.

     This function uses libcurl.  Curl supports, among others, the HTTP,
     FTP and FILE protocols.  Username and password may be specified in
     the URL.  For example,

          s = urlread ("http://user:password@example.com/file.txt");

     GET and POST requests can be specified by METHOD and PARAM.  The
     parameter METHOD is either `get' or `post' and PARAM is a cell
     array of parameter and value pairs.  For example,

          s = urlread ("http://www.google.com/search", "get",
                       {"query", "octave"});

     *See also:* *note urlwrite: doc-urlwrite.

 -- Loadable Function:  urlwrite (URL, LOCALFILE)
 -- Loadable Function: F = urlwrite (URL, LOCALFILE)
 -- Loadable Function: [F, SUCCESS] = urlwrite (URL, LOCALFILE)
 -- Loadable Function: [F, SUCCESS, MESSAGE] = urlwrite (URL, LOCALFILE)
     Download a remote file specified by its URL and save it as
     LOCALFILE.  For example,

          urlwrite ("ftp://ftp.octave.org/pub/octave/README",
                    "README.txt");

     The full path of the downloaded file is returned in F.  The
     variable SUCCESS is 1 if the download was successful, otherwise it
     is 0 in which case MESSAGE contains an error message.  If no
     output argument is specified and if an error occurs, then the
     error is signaled through Octave's error handling mechanism.

     This function uses libcurl.  Curl supports, among others, the HTTP,
     FTP and FILE protocols.  Username and password may be specified in
     the URL, for example:

          urlwrite ("http://username:password@example.com/file.txt",
                    "file.txt");

     GET and POST requests can be specified by METHOD and PARAM.  The
     parameter METHOD is either `get' or `post' and PARAM is a cell
     array of parameter and value pairs.  For example:

          urlwrite ("http://www.google.com/search", "search.html",
                    "get", {"query", "octave"});

     *See also:* *note urlread: doc-urlread.


File: octave.info,  Node: Controlling Subprocesses,  Next: Process ID Information,  Prev: Networking Utilities,  Up: System Utilities

34.5 Controlling Subprocesses
=============================

Octave includes some high-level commands like `system' and `popen' for
starting subprocesses.  If you want to run another program to perform
some task and then look at its output, you will probably want to use
these functions.

   Octave also provides several very low-level Unix-like functions which
can also be used for starting subprocesses, but you should probably only
use them if you can't find any way to do what you need with the
higher-level functions.

 -- Built-in Function:  system (STRING, RETURN_OUTPUT, TYPE)
     Execute a shell command specified by STRING.  The second argument
     is optional.  If TYPE is `"async"', the process is started in the
     background and the process id of the child process is returned
     immediately.  Otherwise, the process is started, and Octave waits
     until it exits.  If the TYPE argument is omitted, a value of
     `"sync"' is assumed.

     If two input arguments are given (the actual value of
     RETURN_OUTPUT is irrelevant) and the subprocess is started
     synchronously, or if SYSTEM is called with one input argument and
     one or more output arguments, the output from the command is
     returned.  Otherwise, if the subprocess is executed synchronously,
     its output is sent to the standard output.  To send the output of
     a command executed with SYSTEM through the pager, use a command
     like

          disp (system (cmd, 1));

     or

          printf ("%s\n", system (cmd, 1));

     The `system' function can return two values.  The first is the
     exit status of the command and the second is any output from the
     command that was written to the standard output stream.  For
     example,

          [status, output] = system ("echo foo; exit 2");

     will set the variable `output' to the string `foo', and the
     variable `status' to the integer `2'.

 -- Function File: [STATUS, TEXT] unix (COMMAND)
 -- Function File: [STATUS, TEXT] unix (COMMAND, "-echo")
     Execute a system command if running under a Unix-like operating
     system, otherwise do nothing.  Return the exit status of the
     program in STATUS and any output sent to the standard output in
     TEXT.  If the optional second argument `"-echo"' is given, then
     also send the output from the command to the standard output.

     *See also:* *note isunix: doc-isunix, *note ispc: doc-ispc, *note
     system: doc-system.

 -- Function File: [STATUS, TEXT] = dos (COMMAND)
 -- Function File: [STATUS, TEXT] = dos (COMMAND, "-echo")
     Execute a system command if running under a Windows-like operating
     system, otherwise do nothing.  Return the exit status of the
     program in STATUS and any output sent to the standard output in
     TEXT.  If the optional second argument `"-echo"' is given, then
     also send the output from the command to the standard output.

     *See also:* *note unix: doc-unix, *note isunix: doc-isunix, *note
     ispc: doc-ispc, *note system: doc-system.

 -- Function File: [OUTPUT, STATUS] = perl (SCRIPTFILE)
 -- Function File: [OUTPUT, STATUS] = perl (SCRIPTFILE, ARGUMENT1,
          ARGUMENT2, ...)
     Invoke perl script SCRIPTFILE with possibly a list of command line
     arguments.  Returns output in OUTPUT and status in STATUS.

     *See also:* *note system: doc-system.

 -- Built-in Function: FID = popen (COMMAND, MODE)
     Start a process and create a pipe.  The name of the command to run
     is given by COMMAND.  The file identifier corresponding to the
     input or output stream of the process is returned in FID.  The
     argument MODE may be

    `"r"'
          The pipe will be connected to the standard output of the
          process, and open for reading.

    `"w"'
          The pipe will be connected to the standard input of the
          process, and open for writing.

     For example,

          fid = popen ("ls -ltr / | tail -3", "r");
          while (ischar (s = fgets (fid)))
            fputs (stdout, s);
          endwhile
               -| drwxr-xr-x  33 root  root  3072 Feb 15 13:28 etc
               -| drwxr-xr-x   3 root  root  1024 Feb 15 13:28 lib
               -| drwxrwxrwt  15 root  root  2048 Feb 17 14:53 tmp

 -- Built-in Function:  pclose (FID)
     Close a file identifier that was opened by `popen'.  You may also
     use `fclose' for the same purpose.

 -- Built-in Function: [IN, OUT, PID] = popen2 (COMMAND, ARGS)
     Start a subprocess with two-way communication.  The name of the
     process is given by COMMAND, and ARGS is an array of strings
     containing options for the command.  The file identifiers for the
     input and output streams of the subprocess are returned in IN and
     OUT.  If execution of the command is successful, PID contains the
     process ID of the subprocess.  Otherwise, PID is -1.

     For example,

          [in, out, pid] = popen2 ("sort", "-r");
          fputs (in, "these\nare\nsome\nstrings\n");
          fclose (in);
          EAGAIN = errno ("EAGAIN");
          done = false;
          do
            s = fgets (out);
            if (ischar (s))
              fputs (stdout, s);
            elseif (errno () == EAGAIN)
              sleep (0.1);
              fclear (out);
            else
              done = true;
            endif
          until (done)
          fclose (out);
          waitpid (pid);
               -| these
               -| strings
               -| some
               -| are

     Note that `popen2', unlike `popen', will not "reap" the child
     process.  If you don't use `waitpid' to check the child's exit
     status, it will linger until Octave exits.

 -- Built-in Function: VAL = EXEC_PATH ()
 -- Built-in Function: OLD_VAL = EXEC_PATH (NEW_VAL)
     Query or set the internal variable that specifies a colon separated
     list of directories to search when executing external programs.
     Its initial value is taken from the environment variable
     `OCTAVE_EXEC_PATH' (if it exists) or `PATH', but that value can be
     overridden by the command line argument `--exec-path PATH'.  At
     startup, an additional set of directories (including the shell
     PATH) is appended to the path specified in the environment or on
     the command line.  If you use the `EXEC_PATH' function to modify
     the path, you should take care to preserve these additional
     directories.

   In most cases, the following functions simply decode their arguments
and make the corresponding Unix system calls.  For a complete example
of how they can be used, look at the definition of the function
`popen2'.

 -- Built-in Function: [PID, MSG] = fork ()
     Create a copy of the current process.

     Fork can return one of the following values:

    > 0
          You are in the parent process.  The value returned from
          `fork' is the process id of the child process.  You should
          probably arrange to wait for any child processes to exit.

    0
          You are in the child process.  You can call `exec' to start
          another process.  If that fails, you should probably call
          `exit'.

    < 0
          The call to `fork' failed for some reason.  You must take
          evasive action.  A system dependent error message will be
          waiting in MSG.

 -- Built-in Function: [ERR, MSG] = exec (FILE, ARGS)
     Replace current process with a new process.  Calling `exec' without
     first calling `fork' will terminate your current Octave process and
     replace it with the program named by FILE.  For example,

          exec ("ls" "-l")

     will run `ls' and return you to your shell prompt.

     If successful, `exec' does not return.  If `exec' does return, ERR
     will be nonzero, and MSG will contain a system-dependent error
     message.

 -- Built-in Function: [READ_FD, WRITE_FD, ERR, MSG] = pipe ()
     Create a pipe and return the reading and writing ends of the pipe
     into READ_FD and WRITE_FD respectively.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

 -- Built-in Function: [FID, MSG] = dup2 (OLD, NEW)
     Duplicate a file descriptor.

     If successful, FID is greater than zero and contains the new file
     ID.  Otherwise, FID is negative and MSG contains a
     system-dependent error message.

 -- Built-in Function: [PID, STATUS, MSG] = waitpid (PID, OPTIONS)
     Wait for process PID to terminate.  The PID argument can be:

    -1
          Wait for any child process.

    0
          Wait for any child process whose process group ID is equal to
          that of the Octave interpreter process.

    > 0
          Wait for termination of the child process with ID PID.

     The OPTIONS argument can be a bitwise OR of zero or more of the
     following constants:

    `0'
          Wait until signal is received or a child process exits (this
          is the default if the OPTIONS argument is missing).

    `WNOHANG'
          Do not hang if status is not immediately available.

    `WUNTRACED'
          Report the status of any child processes that are stopped,
          and whose status has not yet been reported since they stopped.

    `WCONTINUE'
          Return if a stopped child has been resumed by delivery of
          `SIGCONT'.  This value may not be meaningful on all systems.

     If the returned value of PID is greater than 0, it is the process
     ID of the child process that exited.  If an error occurs, PID will
     be less than zero and MSG will contain a system-dependent error
     message.  The value of STATUS contains additional system-dependent
     information about the subprocess that exited.

     *See also:* *note WCONTINUE: doc-WCONTINUE, *note WCOREDUMP:
     doc-WCOREDUMP, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFCONTINUED: doc-WIFCONTINUED, *note WIFSIGNALED:
     doc-WIFSIGNALED, *note WIFSTOPPED: doc-WIFSTOPPED, *note WNOHANG:
     doc-WNOHANG, *note WSTOPSIG: doc-WSTOPSIG, *note WTERMSIG:
     doc-WTERMSIG, *note WUNTRACED: doc-WUNTRACED.

 -- Built-in Function: WCONINTUE ()
     Return the numerical value of the option argument that may be
     passed to `waitpid' to indicate that it should also return if a
     stopped child has been resumed by delivery of a `SIGCONT' signal.

     *See also:* *note waitpid: doc-waitpid, *note WNOHANG:
     doc-WNOHANG, *note WUNTRACED: doc-WUNTRACED.

 -- Built-in Function:  WCOREDUMP (STATUS)
     Given STATUS from a call to `waitpid', return true if the child
     produced a core dump.  This function should only be employed if
     `WIFSIGNALED' returned true.  The macro used to implement this
     function is not specified in POSIX.1-2001 and is not available on
     some Unix implementations (e.g., AIX, SunOS).

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG: doc-WTERMSIG, *note
     WIFSTOPPED: doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG, *note
     WIFCONTINUED: doc-WIFCONTINUED.

 -- Built-in Function:  WEXITSTATUS (STATUS)
     Given STATUS from a call to `waitpid', return the exit status of
     the child.  This function should only be employed if `WIFEXITED'
     returned true.

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG:
     doc-WTERMSIG, *note WCOREDUMP: doc-WCOREDUMP, *note WIFSTOPPED:
     doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG, *note WIFCONTINUED:
     doc-WIFCONTINUED.

 -- Built-in Function:  WIFCONTINUED (STATUS)
     Given STATUS from a call to `waitpid', return true if the child
     process was resumed by delivery of `SIGCONT'.

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG: doc-WTERMSIG, *note
     WCOREDUMP: doc-WCOREDUMP, *note WIFSTOPPED: doc-WIFSTOPPED, *note
     WSTOPSIG: doc-WSTOPSIG.

 -- Built-in Function:  WIFSIGNALED (STATUS)
     Given STATUS from a call to `waitpid', return true if the child
     process was terminated by a signal.

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note WTERMSIG:
     doc-WTERMSIG, *note WCOREDUMP: doc-WCOREDUMP, *note WIFSTOPPED:
     doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG, *note WIFCONTINUED:
     doc-WIFCONTINUED.

 -- Built-in Function:  WIFSTOPPED (STATUS)
     Given STATUS from a call to `waitpid', return true if the child
     process was stopped by delivery of a signal; this is only possible
     if the call was done using `WUNTRACED' or when the child is being
     traced (see ptrace(2)).

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG: doc-WTERMSIG, *note
     WCOREDUMP: doc-WCOREDUMP, *note WSTOPSIG: doc-WSTOPSIG, *note
     WIFCONTINUED: doc-WIFCONTINUED.

 -- Built-in Function:  WIFEXITED (STATUS)
     Given STATUS from a call to `waitpid', return true if the child
     terminated normally.

     *See also:* *note waitpid: doc-waitpid, *note WEXITSTATUS:
     doc-WEXITSTATUS, *note WIFSIGNALED: doc-WIFSIGNALED, *note
     WTERMSIG: doc-WTERMSIG, *note WCOREDUMP: doc-WCOREDUMP, *note
     WIFSTOPPED: doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG, *note
     WIFCONTINUED: doc-WIFCONTINUED.

 -- Built-in Function:  WNOHANG ()
     Return the numerical value of the option argument that may be
     passed to `waitpid' to indicate that it should return its status
     immediately instead of waiting for a process to exit.

     *See also:* *note waitpid: doc-waitpid, *note WUNTRACED:
     doc-WUNTRACED, *note WCONTINUE: doc-WCONTINUE.

 -- Built-in Function:  WSTOPSIG (STATUS)
     Given STATUS from a call to `waitpid', return the number of the
     signal which caused the child to stop.  This function should only
     be employed if `WIFSTOPPED' returned true.

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WTERMSIG: doc-WTERMSIG, *note
     WCOREDUMP: doc-WCOREDUMP, *note WIFSTOPPED: doc-WIFSTOPPED, *note
     WIFCONTINUED: doc-WIFCONTINUED.

 -- Built-in Function:  WTERMSIG (STATUS)
     Given STATUS from a call to `waitpid', return the number of the
     signal that caused the child process to terminate.  This function
     should only be employed if `WIFSIGNALED' returned true.

     *See also:* *note waitpid: doc-waitpid, *note WIFEXITED:
     doc-WIFEXITED, *note WEXITSTATUS: doc-WEXITSTATUS, *note
     WIFSIGNALED: doc-WIFSIGNALED, *note WCOREDUMP: doc-WCOREDUMP,
     *note WIFSTOPPED: doc-WIFSTOPPED, *note WSTOPSIG: doc-WSTOPSIG,
     *note WIFCONTINUED: doc-WIFCONTINUED.

 -- Built-in Function:  WUNTRACED ()
     Return the numerical value of the option argument that may be
     passed to `waitpid' to indicate that it should also return if the
     child process has stopped but is not traced via the `ptrace'
     system call

     *See also:* *note waitpid: doc-waitpid, *note WNOHANG:
     doc-WNOHANG, *note WCONTINUE: doc-WCONTINUE.

 -- Built-in Function: [ERR, MSG] = fcntl (FID, REQUEST, ARG)
     Change the properties of the open file FID.  The following values
     may be passed as REQUEST:

    `F_DUPFD'
          Return a duplicate file descriptor.

    `F_GETFD'
          Return the file descriptor flags for FID.

    `F_SETFD'
          Set the file descriptor flags for FID.

    `F_GETFL'
          Return the file status flags for FID.  The following codes
          may be returned (some of the flags may be undefined on some
          systems).

         `O_RDONLY'
               Open for reading only.

         `O_WRONLY'
               Open for writing only.

         `O_RDWR'
               Open for reading and writing.

         `O_APPEND'
               Append on each write.

         `O_CREAT'
               Create the file if it does not exist.

         `O_NONBLOCK'
               Nonblocking mode.

         `O_SYNC'
               Wait for writes to complete.

         `O_ASYNC'
               Asynchronous I/O.

    `F_SETFL'
          Set the file status flags for FID to the value specified by
          ARG.  The only flags that can be changed are `O_APPEND' and
          `O_NONBLOCK'.

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

 -- Built-in Function: [ERR, MSG] = kill (PID, SIG)
     Send signal SIG to process PID.

     If PID is positive, then signal SIG is sent to PID.

     If PID is 0, then signal SIG is sent to every process in the
     process group of the current process.

     If PID is -1, then signal SIG is sent to every process except
     process 1.

     If PID is less than -1, then signal SIG is sent to every process
     in the process group -PID.

     If SIG is 0, then no signal is sent, but error checking is still
     performed.

     Return 0 if successful, otherwise return -1.

 -- Built-in Function:  SIG ()
     Return a structure containing Unix signal names and their defined
     values.


File: octave.info,  Node: Process ID Information,  Next: Environment Variables,  Prev: Controlling Subprocesses,  Up: System Utilities

34.6 Process, Group, and User IDs
=================================

 -- Built-in Function: pgid = getpgrp ()
     Return the process group id of the current process.

 -- Built-in Function: pid = getpid ()
     Return the process id of the current process.

 -- Built-in Function: pid = getppid ()
     Return the process id of the parent process.

 -- Built-in Function: euid = geteuid ()
     Return the effective user id of the current process.

 -- Built-in Function: uid = getuid ()
     Return the real user id of the current process.

 -- Built-in Function: egid = getegid ()
     Return the effective group id of the current process.

 -- Built-in Function: gid = getgid ()
     Return the real group id of the current process.


File: octave.info,  Node: Environment Variables,  Next: Current Working Directory,  Prev: Process ID Information,  Up: System Utilities

34.7 Environment Variables
==========================

 -- Built-in Function:  getenv (VAR)
     Return the value of the environment variable VAR.  For example,

          getenv ("PATH")

     returns a string containing the value of your path.

 -- Built-in Function:  putenv (VAR, VALUE)
 -- Built-in Function:  setenv (VAR, VALUE)
     Set the value of the environment variable VAR to VALUE.


File: octave.info,  Node: Current Working Directory,  Next: Password Database Functions,  Prev: Environment Variables,  Up: System Utilities

34.8 Current Working Directory
==============================

 -- Command: cd dir
 -- Command: chdir dir
     Change the current working directory to DIR.  If DIR is omitted,
     the current directory is changed to the user's home directory.
     For example,

          cd ~/octave

     Changes the current working directory to `~/octave'.  If the
     directory does not exist, an error message is printed and the
     working directory is not changed.

     *See also:* *note mkdir: doc-mkdir, *note rmdir: doc-rmdir, *note
     dir: doc-dir.

 -- Command: ls options
     List directory contents.  For example,

          ls -l
               -| total 12
               -| -rw-r--r--   1 jwe  users  4488 Aug 19 04:02 foo.m
               -| -rw-r--r--   1 jwe  users  1315 Aug 17 23:14 bar.m

     The `dir' and `ls' commands are implemented by calling your
     system's directory listing command, so the available options may
     vary from system to system.

     *See also:* *note dir: doc-dir, *note stat: doc-stat, *note
     readdir: doc-readdir, *note glob: doc-glob, *note filesep:
     doc-filesep, *note ls_command: doc-ls_command.

 -- Function File: [OLD_CMD = ls_command (CMD)
     Set or return the shell command used by Octave's `ls' command.
     The value of CMD must be a character string.  With no arguments,
     simply return the previous value.

     *See also:* *note ls: doc-ls.

 -- Function File:  dir (DIRECTORY)
 -- Function File: [LIST] = dir (DIRECTORY)
     Display file listing for directory DIRECTORY.  If a return value
     is requested, return a structure array with the fields

          name
          bytes
          date
          isdir
          statinfo

     in which `statinfo' is the structure returned from `stat'.

     If DIRECTORY is not a directory, return information about the
     named FILENAME.  DIRECTORY may be a list of directories specified
     either by name or with wildcard characters (like * and ?)  which
     will be expanded with glob.

     Note that for symbolic links, `dir' returns information about the
     file that a symbolic link points to instead of the link itself.
     However, if the link points to a nonexistent file, `dir' returns
     information about the link.

     *See also:* *note ls: doc-ls, *note stat: doc-stat, *note lstat:
     doc-lstat, *note readdir: doc-readdir, *note glob: doc-glob, *note
     filesep: doc-filesep.

 -- Built-in Function:  pwd ()
     Return the current working directory.

     *See also:* *note dir: doc-dir, *note ls: doc-ls.


File: octave.info,  Node: Password Database Functions,  Next: Group Database Functions,  Prev: Current Working Directory,  Up: System Utilities

34.9 Password Database Functions
================================

Octave's password database functions return information in a structure
with the following fields.

`name'
     The user name.

`passwd'
     The encrypted password, if available.

`uid'
     The numeric user id.

`gid'
     The numeric group id.

`gecos'
     The GECOS field.

`dir'
     The home directory.

`shell'
     The initial shell.

   In the descriptions of the following functions, this data structure
is referred to as a PW_STRUCT.

 -- Loadable Function: PW_STRUCT = getpwent ()
     Return a structure containing an entry from the password database,
     opening it if necessary.  Once the end of the data has been
     reached, `getpwent' returns 0.

 -- Loadable Function: PW_STRUCT = getpwuid (UID).
     Return a structure containing the first entry from the password
     database with the user ID UID.  If the user ID does not exist in
     the database, `getpwuid' returns 0.

 -- Loadable Function: PW_STRUCT = getpwnam (NAME)
     Return a structure containing the first entry from the password
     database with the user name NAME.  If the user name does not exist
     in the database, `getpwname' returns 0.

 -- Loadable Function:  setpwent ()
     Return the internal pointer to the beginning of the password
     database.

 -- Loadable Function:  endpwent ()
     Close the password database.


File: octave.info,  Node: Group Database Functions,  Next: System Information,  Prev: Password Database Functions,  Up: System Utilities

34.10 Group Database Functions
==============================

Octave's group database functions return information in a structure
with the following fields.

`name'
     The user name.

`passwd'
     The encrypted password, if available.

`gid'
     The numeric group id.

`mem'
     The members of the group.

   In the descriptions of the following functions, this data structure
is referred to as a GRP_STRUCT.

 -- Loadable Function: GRP_STRUCT = getgrent ()
     Return an entry from the group database, opening it if necessary.
     Once the end of the data has been reached, `getgrent' returns 0.

 -- Loadable Function: GRP_STRUCT = getgrgid (GID).
     Return the first entry from the group database with the group ID
     GID.  If the group ID does not exist in the database, `getgrgid'
     returns 0.

 -- Loadable Function: GRP_STRUCT = getgrnam (NAME)
     Return the first entry from the group database with the group name
     NAME.  If the group name does not exist in the database,
     `getgrnam' returns 0.

 -- Loadable Function:  setgrent ()
     Return the internal pointer to the beginning of the group database.

 -- Loadable Function:  endgrent ()
     Close the group database.


File: octave.info,  Node: System Information,  Next: Hashing Functions,  Prev: Group Database Functions,  Up: System Utilities

34.11 System Information
========================

 -- Function File: [C, MAXSIZE, ENDIAN] = computer ()
     Print or return a string of the form CPU-VENDOR-OS that identifies
     the kind of computer Octave is running on.  If invoked with an
     output argument, the value is returned instead of printed.  For
     example,

          computer ()
               -| i586-pc-linux-gnu

          x = computer ()
               => x = "i586-pc-linux-gnu"

     If two output arguments are requested, also return the maximum
     number of elements for an array.

     If three output arguments are requested, also return the byte order
     of the current system as a character (`"B"' for big-endian or
     `"L"' for little-endian).

 -- Built-in Function: [UTS, ERR, MSG] = uname ()
     Return system information in the structure.  For example,

          uname ()
               => {
                     sysname = x86_64
                     nodename = segfault
                     release = 2.6.15-1-amd64-k8-smp
                     version = Linux
                     machine = #2 SMP Thu Feb 23 04:57:49 UTC 2006
                   }

     If successful, ERR is 0 and MSG is an empty string.  Otherwise,
     ERR is nonzero and MSG contains a system-dependent error message.

 -- Function File:  ispc ()
     Return 1 if Octave is running on a Windows system and 0 otherwise.

     *See also:* *note ismac: doc-ismac, *note isunix: doc-isunix.

 -- Function File:  isunix ()
     Return 1 if Octave is running on a Unix-like system and 0
     otherwise.

     *See also:* *note ismac: doc-ismac, *note ispc: doc-ispc.

 -- Function File:  ismac ()
     Return 1 if Octave is running on a Mac OS X system and 0 otherwise.

     *See also:* *note ispc: doc-ispc, *note isunix: doc-isunix.

 -- Built-in Function:  isieee ()
     Return 1 if your computer claims to conform to the IEEE standard
     for floating point calculations.

 -- Built-in Function:  OCTAVE_HOME ()
     Return the name of the top-level Octave installation directory.

 -- Built-in Function:  OCTAVE_VERSION ()
     Return the version number of Octave, as a string.

 -- Function File:  license
     Display the license of Octave.

 -- Function File:  license ("inuse")
     Display a list of packages currently being used.

 -- Function File: RETVAL = license ("inuse")
     Return a structure containing the fields `feature' and `user'.

 -- Function File: RETVAL = license ("test", FEATURE)
     Return 1 if a license exists for the product identified by the
     string FEATURE and 0 otherwise.  The argument FEATURE is case
     insensitive and only the first 27 characters are checked.

 -- Function File:  license ("test", FEATURE, TOGGLE)
     Enable or disable license testing for FEATURE, depending on
     TOGGLE, which may be one of:

    `"enable"'
          Future tests for the specified license of FEATURE are
          conducted as usual.

    `"disable"'
          Future tests for the specified license of FEATURE return 0.

 -- Function File: RETVAL = license ("checkout", FEATURE)
     Check out a license for FEATURE, returning 1 on success and 0 on
     failure.

     This function is provided for compatibility with MATLAB.

     *See also:* *note ver: doc-ver, *note version: doc-version.

 -- Function File:  version ()
     Return Octave's version number as a string.  This is also the
     value of the built-in variable `OCTAVE_VERSION'.

 -- Function File:  ver ()
     Display a header containing the current Octave version number,
     license string and operating system, followed by the installed
     package names, versions, and installation directories.

 -- Function File: v = ver ()
     Return a vector of structures, respecting Octave and each
     installed package.  The structure includes the following fields.

    `Name'
          Package name.

    `Version'
          Version of the package.

    `Revision'
          Revision of the package.

    `Date'
          Date respecting the version/revision.

 -- Function File: v = ver (`"Octave"')
     Return version information for Octave only..

 -- Function File: v = ver (PKG)
     Return version information for the specified package PKG.

     *See also:* *note license: doc-license, *note version: doc-version.

 -- Built-in Function:  octave_config_info (OPTION)
     Return a structure containing configuration and installation
     information for Octave.

     if OPTION is a string, return the configuration information for the
     specified option.


 -- Loadable Function:  getrusage ()
     Return a structure containing a number of statistics about the
     current Octave process.  Not all fields are available on all
     systems.  If it is not possible to get CPU time statistics, the
     CPU time slots are set to zero.  Other missing data are replaced
     by NaN.  Here is a list of all the possible fields that can be
     present in the structure returned by `getrusage':

    `idrss'
          Unshared data size.

    `inblock'
          Number of block input operations.

    `isrss'
          Unshared stack size.

    `ixrss'
          Shared memory size.

    `majflt'
          Number of major page faults.

    `maxrss'
          Maximum data size.

    `minflt'
          Number of minor page faults.

    `msgrcv'
          Number of messages received.

    `msgsnd'
          Number of messages sent.

    `nivcsw'
          Number of involuntary context switches.

    `nsignals'
          Number of signals received.

    `nswap'
          Number of swaps.

    `nvcsw'
          Number of voluntary context switches.

    `oublock'
          Number of block output operations.

    `stime'
          A structure containing the system CPU time used.  The
          structure has the elements `sec' (seconds) `usec'
          (microseconds).

    `utime'
          A structure containing the user CPU time used.  The structure
          has the elements `sec' (seconds) `usec' (microseconds).


File: octave.info,  Node: Hashing Functions,  Prev: System Information,  Up: System Utilities

34.12 Hashing Functions
=======================

It is often necessary to find if two strings or files are identical.
This might be done by comparing them character by character and looking
for differences.  However, this can be slow, and so comparing a hash of
the string or file can be a rapid way of finding if the files differ.

   Another use of the hashing function is to check for file integrity.
The user can check the hash of the file against a known value and find
if the file they have is the same as the one that the original hash was
produced with.

   Octave supplies the `md5sum' function to perform MD5 hashes on
strings and files.  An example of the use of `md5sum' function might be

     if exist (file, "file")
       hash = md5sum (file);
     else
       # Treat the variable "file" as a string
       hash = md5sum (file, true);
     endif

 -- Loadable Function:  md5sum (FILE)
 -- Loadable Function:  md5sum (STR, OPT)
     Calculates the MD5 sum of the file FILE.  If the second parameter
     OPT exists and is true, then calculate the MD5 sum of the string
     STR.


File: octave.info,  Node: Packages,  Next: Dynamically Linked Functions,  Prev: System Utilities,  Up: Top

35 Packages
***********

Since Octave is Free Software users are encouraged to share their
programs amongst each other.  To aid this sharing Octave supports the
installation of extra packages.  The `Octave-Forge' project is a
community-maintained set of packages that can be downloaded and
installed in Octave.  At the time of writing the `Octave-Forge' project
can be found on-line at `http://octave.sourceforge.net', but since the
Internet is an ever-changing place this may not be true at the time of
reading.  Therefore it is recommended to see the Octave website for an
updated reference.

* Menu:

* Installing and Removing Packages::
* Using Packages::
* Administrating Packages::
* Creating Packages::


File: octave.info,  Node: Installing and Removing Packages,  Next: Using Packages,  Up: Packages

35.1 Installing and Removing Packages
=====================================

Assuming a package is available in the file `image-1.0.0.tar.gz' it can
be installed from the Octave prompt with the command

     pkg install image-1.0.0.tar.gz

If the package is installed successfully nothing will be printed on the
prompt, but if an error occurred during installation it will be
reported.  It is possible to install several packages at once by
writing several package files after the `pkg install' command.  If a
different version of the package is already installed it will be
removed prior to installing the new package.  This makes it easy to
upgrade and downgrade the version of a package, but makes it impossible
to have several versions of the same package installed at once.

   To see which packages are installed type

     pkg list
     -| Package Name  | Version | Installation directory
     -| --------------+---------+-----------------------
     -|        image *|   1.0.0 | /home/jwe/octave/image-1.0.0

In this case only version 1.0.0 of the `image' package is installed.
The '*' character next to the package name shows that the image package
is loaded and ready for use.

   It is possible to remove a package from the system using the `pkg
uninstall' command like this

     pkg uninstall image

If the package is removed successfully nothing will be printed in the
prompt, but if an error occurred it will be reported.  It should be
noted that the package file used for installation is not needed for
removal, and that only the package name as reported by `pkg list'
should be used when removing a package.  It is possible to remove
several packages at once by writing several package names after the
`pkg uninstall' command.

   To minimize the amount of code duplication between packages it is
possible that one package depends on another one.  If a package depends
on another, it will check if that package is installed during
installation.  If it is not, an error will be reported and the package
will not be installed.  This behavior can be disabled by passing the
`-nodeps' flag to the `pkg install' command

     pkg install -nodeps my_package_with_dependencies.tar.gz

Since the installed package expects its dependencies to be installed it
may not function correctly.  Because of this it is not recommended to
disable dependency checking.

 -- Command: pkg COMMAND PKG_NAME
 -- Command: pkg COMMAND OPTION PKG_NAME
     This command interacts with the package manager.  Different
     actions will be taken depending on the value of COMMAND.

    `install'
          Install named packages.  For example,
               pkg install image-1.0.0.tar.gz
          installs the package found in the file `image-1.0.0.tar.gz'.

          The OPTION variable can contain options that affect the manner
          in which a package is installed.  These options can be one or
          more of

         `-nodeps'
               The package manager will disable the dependency
               checking.  That way it is possible to install a package
               even if it depends on another package that's not
               installed on the system.  *Use this option with care.*

         `-noauto'
               The package manager will not automatically load the
               installed package when starting Octave, even if the
               package requests that it is.

         `-auto'
               The package manager will automatically load the
               installed package when starting Octave, even if the
               package requests that it isn't.

         `-local'
               A local installation is forced, even if the user has
               system privileges.

         `-global'
               A global installation is forced, even if the user
               doesn't normally have system privileges

         `-verbose'
               The package manager will print the output of all of the
               commands that are performed.

    `uninstall'
          Uninstall named packages.  For example,
               pkg uninstall image
          removes the `image' package from the system.  If another
          installed package depends on the `image' package an error
          will be issued.  The package can be uninstalled anyway by
          using the `-nodeps' option.

    `load'
          Add named packages to the path.  After loading a package it is
          possible to use the functions provided by the package.  For
          example,
               pkg load image
          adds the `image' package to the path.  It is possible to load
          all installed packages at once with the command
               pkg load all

    `unload'
          Removes named packages from the path.  After unloading a
          package it is no longer possible to use the functions
          provided by the package.  This command behaves like the
          `load' command.

    `list'
          Show a list of the currently installed packages.  By
          requesting one or two output argument it is possible to get a
          list of the currently installed packages.  For example,
               installed_packages = pkg list;
          returns a cell array containing a structure for each
          installed package.  The command
               [USER_PACKAGES, SYSTEM_PACKAGES] = pkg list
          splits the list of installed packages into those who are
          installed by the current user, and those installed by the
          system administrator.

    `describe'
          Show a short description of the named installed packages,
          with the option '-verbose' also list functions provided by
          the package, e.g.:
                pkg describe -verbose all
          will describe all installed packages and the functions they
          provide.  If one output is requested a cell of structure
          containing the description and list of functions of each
          package is returned as output rather than printed on screen:
                desc = pkg ("describe", "secs1d", "image")
          If any of the requested packages is not installed, pkg
          returns an error, unless a second output is requested:
                [ desc, flag] = pkg ("describe", "secs1d", "image")
          FLAG will take one of the values "Not installed", "Loaded" or
          "Not loaded" for each of the named packages.

    `prefix'
          Set the installation prefix directory.  For example,
               pkg prefix ~/my_octave_packages
          sets the installation prefix to `~/my_octave_packages'.
          Packages will be installed in this directory.

          It is possible to get the current installation prefix by
          requesting an output argument.  For example,
               p = pkg prefix

          The location in which to install the architecture dependent
          files can be independent specified with an addition argument.
          For example

               pkg prefix ~/my_octave_packages ~/my_arch_dep_pkgs

    `local_list'
          Set the file in which to look for information on the locally
          installed packages.  Locally installed packages are those
          that are typically available only to the current user.  For
          example
               pkg local_list ~/.octave_packages
          It is possible to get the current value of local_list with
          the following
               pkg local_list

    `global_list'
          Set the file in which to look for, for information on the
          globally installed packages.  Globally installed packages are
          those that are typically available to all users.  For example
               pkg global_list /usr/share/octave/octave_packages
          It is possible to get the current value of global_list with
          the following
               pkg global_list

    `rebuild'
          Rebuilds the package database from the installed directories.
          This can be used in cases where for some reason the package
          database is corrupted.  It can also take the `-auto' and
          `-noauto' options to allow the autoloading state of a package
          to be changed.  For example

               pkg rebuild -noauto image

          will remove the autoloading status of the image package.

    `build'
          Builds a binary form of a package or packages.  The binary
          file produced will itself be an Octave package that can be
          installed normally with `pkg'.  The form of the command to
          build a binary package is

               pkg build builddir image-1.0.0.tar.gz ...

          where `builddir' is the name of a directory where the
          temporary installation will be produced and the binary
          packages will be found.  The options `-verbose' and `-nodeps'
          are respected, while the other options are ignored.


File: octave.info,  Node: Using Packages,  Next: Administrating Packages,  Prev: Installing and Removing Packages,  Up: Packages

35.2 Using Packages
===================

By default installed packages are available from the Octave prompt, but
it is possible to control this using the `pkg load' and `pkg unload'
commands.  The functions from a package can be removed from the Octave
path by typing

     pkg unload package_name

where `package_name' is the name of the package to be removed from the
path.

   In much the same way a package can be added to the Octave path by
typing

     pkg load package_name


File: octave.info,  Node: Administrating Packages,  Next: Creating Packages,  Prev: Using Packages,  Up: Packages

35.3 Administrating Packages
============================

On UNIX-like systems it is possible to make both per-user and
system-wide installations of a package.  If the user performing the
installation is `root' the packages will be installed in a system-wide
directory that defaults to `OCTAVE_HOME/share/octave/packages/'.  If
the user is not `root' the default installation directory is
`~/octave/'.  Packages will be installed in a subdirectory of the
installation directory that will be named after the package.  It is
possible to change the installation directory by using the `pkg prefix'
command

     pkg prefix new_installation_directory

The current installation directory can be retrieved by typing

     current_installation_directory = pkg prefix

   To function properly the package manager needs to keep some
information about the installed packages.  For per-user packages this
information is by default stored in the file `~/.octave_packages' and
for system-wide installations it is stored in
`OCTAVE_HOME/share/octave/octave_packages'.  The path to the per-user
file can be changed with the `pkg local_list' command

     pkg local_list /path/to/new_file

For system-wide installations this can be changed in the same way using
the `pkg global_list' command.  If these commands are called without a
new path, the current path will be returned.


File: octave.info,  Node: Creating Packages,  Prev: Administrating Packages,  Up: Packages

35.4 Creating Packages
======================

Internally a package is simply a gzipped tar file that contains a top
level directory of any given name.  This directory will in the
following be referred to as `package' and may contain the following
files


`package/DESCRIPTION'
     This is a required file containing information about the package.
     *Note The DESCRIPTION File::, for details on this file.

`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
     package contains dynamically linked functions the license must be
     compatible with the GNU General Public License.

`package/INDEX'
     This is an optional file describing the functions provided by the
     package.  If this file is not given then one with be created
     automatically from the functions in the package and the
     `Categories' keyword in the `DESCRIPTION' file.  *Note The INDEX
     file::, for details on this file.

`package/PKG_ADD'
     An optional file that includes commands that are run when the
     package is added to the users path.  Note that `PKG_ADD'
     directives in the source code of the package will also be added to
     this file by the Octave package manager.  Note that symbolic links
     are to be avoided in packages, as symbolic links do not exist on
     some file systems, and so a typical use for this file is the
     replacement of the symbolic link

          ln -s foo.oct bar.oct

     with an autoload directive like

          autoload ('bar', which ('foo'));

     *Note PKG_ADD and PKG_DEL directives::, for details on `PKG_ADD'
     directives.

`package/PKG_DEL'
     An optional file that includes commands that are run when the
     package is removed from the users path.  Note that `PKG_DEL'
     directives in the source code of the package will also be added to
     this file by the Octave package manager.  *Note PKG_ADD and
     PKG_DEL directives::, for details on `PKG_DEL' directives.

`package/pre_install.m'
     This is an optional script that is run prior to the installation
     of a package.

`package/post_install.m'
     This is an optional script that is run after the installation of a
     package.

`package/on_uninstall.m'
     This is an optional script that is run prior to the removal of a
     package.

   Besides the above mentioned files, a package can also contain on or
more of the following directories


`package/inst'
     An optional directory containing any files that are directly
     installed by the package.  Typically this will include any
     `m'-files.

`package/src'
     An optional directory containing code that must be built prior to
     the packages installation.  The Octave package manager will execute
     `./configure' in this directory if this script exists, and will
     then call `make' if a file `Makefile' exists in this directory.
     `make install' will however not be called.  If a file called
     `FILES' exists all files listed there will be copied to the `inst'
     directory, so they also will be installed.  If the `FILES' file
     doesn't exist, `src/*.m' and `src/*.oct' will be copied to the
     `inst' directory.

`package/doc'
     An optional directory containing documentation for the package.
     The files in this directory will be directly installed in a
     sub-directory of the installed package for future reference.

`package/bin'
     An optional directory containing files that will be added to the
     Octave `EXEC_PATH' when the package is loaded.  This might contain
     external scripts, etc., called by functions within the package.

* Menu:

* The DESCRIPTION File::
* The INDEX file::
* PKG_ADD and PKG_DEL directives::


File: octave.info,  Node: The DESCRIPTION File,  Next: The INDEX file,  Up: Creating Packages

35.4.1 The DESCRIPTION File
---------------------------

The `DESCRIPTION' file contains various information about the package,
such as its name, author, and version.  This file has a very simple
format


   * Lines starting with `#' are comments.

   * Lines starting with a blank character are continuations from the
     previous line.

   * Everything else is of the form `NameOfOption: ValueOfOption'.

The following is a simple example of a `DESCRIPTION' file

     Name: The name of my package
     Version: 1.0.0
     Date: 2007-18-04
     Author: The name (and possibly email) of the package author.
     Maintainer: The name (and possibly email) of the current
      package maintainer.
     Title: The title of the package
     Description: A short description of the package.  If this
      description gets too long for one line it can continue
      on the next by adding a space to the beginning of the
      following lines.
     License: GPL version 3 or later

   The package manager currently recognizes the following keywords


`Name'
     Name of the package.

`Version'
     Version of the package.

`Date'
     Date of last update.

`Author'
     Original author of the package.

`Maintainer'
     Maintainer of the package.

`Title'
     A one line description of the package.

`Description'
     A one paragraph description of the package.

`Categories'
     Optional keyword describing the package (if no `INDEX' file is
     given this is mandatory).

`Problems'
     Optional list of known problems.

`Url'
     Optional list of homepages related to the package.

`Autoload'
     Optional field that sets the default loading behavior for the
     package.  If set to `yes', `true' or `on', then Octave will
     automatically load the package when starting.  Otherwise the
     package must be manually loaded with the pkg load command.  This
     default behavior can be overridden when the package is installed.

`Depends'
     A list of other Octave packages that this package depends on.
     This can include dependencies on particular versions, with a format

          Depends: package (>= 1.0.0)

     Possible operators are `<', `<=', `==', `>=' or `>'.  If the part
     of the dependency in `()' is missing, any version of the package
     is acceptable.  Multiple dependencies can be defined either as a
     comma separated list or on separate `Depends' lines.

`License'
     An optional short description of the used license (e.g., GPL
     version 3 or newer).  This is optional since the file `COPYING' is
     mandatory.

`SystemRequirements'
     These are the external install dependencies of the package and are
     not checked by the package manager.  This is here as a hint to the
     distribution packager.  They follow the same conventions as the
     `Depends' keyword.

`BuildRequires'
     These are the external build dependencies of the package and are
     not checked by the package manager.  This is here as a hint to the
     distribution packager.  They follow the same conventions as the
     `Depends' keyword.  Note that in general, packaging systems such
     as `rpm' or `deb' and autoprobe the install dependencies from the
     build dependencies, and therefore the often a `BuildRequires'
     dependency removes the need for a `SystemRequirements' dependency.


The developer is free to add additional arguments to the `DESCRIPTION'
file for their own purposes.  One further detail to aid the packager is
that the `SystemRequirements' and `BuildRequires' keywords can have a
distribution dependent section, and the automatic build process will
use these.  An example of the format of this is

     BuildRequires: libtermcap-devel [Mandriva] libtermcap2-devel

where the first package name will be used as a default and if the RPMs
are built on a Mandriva distribution, then the second package name will
be used instead.


File: octave.info,  Node: The INDEX file,  Next: PKG_ADD and PKG_DEL directives,  Prev: The DESCRIPTION File,  Up: Creating Packages

35.4.2 The INDEX file
---------------------

The optional `INDEX' file provides a categorical view of the functions
in the package.  This file has a very simple format


   * Lines beginning with `#' are comments.

   * The first non-comment line should look like this

          toolbox >> Toolbox name

   * Lines beginning with an alphabetical character indicates a new
     category of functions.

   * Lines starting with a white space character indicate that the
     function names on the line belong to the last mentioned category.

The format can be summarized with the following example

     # A comment
     toolbox >> Toolbox name
     Category Name 1
      function1 function2 function3
      function4
     Category Name 2
      function2 function5

   If you wish to refer to a function that users might expect to find
in your package but is not there, providing a work around or pointing
out that the function is available elsewhere, you can use:

     fn = workaround description

This workaround description will not appear when listing functions in
the package with `pkg describe' but they will be published in the html
documentation online.  Workaround descriptions can use any html markup,
but keep in mind that it will be enclosed in a bold-italic environment.
For the special case of:

     fn = use <code>alternate expression</code>

the bold-italic is automatically suppressed.  You will need to use
`<code>' even in references:

     fn = use <a href="someothersite.html"><code>fn</code></a>

Sometimes functions are only partially compatible, in which case you
can list the non-compatible cases separately.  To refer to another
function in the package, use `<f>fn</f>'.  For example,

     eig (a, b) = use <f>qz</f>

Since sites may have many missing functions, you can define a macro
rather than typing the same link over and again.

     $id = expansion

defines the macro id.  You can use `$id' anywhere in the description
and it will be expanded.  For example,

     $TSA = see <a href="link_to_spctools">SPC Tools</a>
     arcov = $TSA <code>armcv</code>

id is any string of letters, numbers and `_'.


File: octave.info,  Node: PKG_ADD and PKG_DEL directives,  Prev: The INDEX file,  Up: Creating Packages

35.4.3 PKG_ADD and PKG_DEL directives
-------------------------------------

If the package contains files called `PKG_ADD' or `PKG_DEL' the
commands in these files will be executed when the package is added or
removed from the users path.  In some situations such files are a bit
cumbersome to maintain, so the package manager supports automatic
creation of such files.  If a source file in the package contains a
`PKG_ADD' or `PKG_DEL' directive they will be added to either the
`PKG_ADD' or `PKG_DEL' files.

   In `m'-files a `PKG_ADD' directive looks like this

     ## PKG_ADD: some_octave_command

Such lines should be added before the `function' keyword.  In C++ files
a `PKG_ADD' directive looks like this

     // PKG_ADD: some_octave_command

In both cases `some_octave_command' should be replaced by the command
that should be placed in the `PKG_ADD' file.  `PKG_DEL' directives work
in the same way, except the `PKG_ADD' keyword is replaced with
`PKG_DEL' and the commands get added to the `PKG_DEL' file.


File: octave.info,  Node: Dynamically Linked Functions,  Next: Test and Demo Functions,  Prev: Packages,  Up: Top

Appendix A Dynamically Linked Functions
***************************************

Octave has the possibility of including compiled code as dynamically
linked extensions and then using these extensions as if they were part
of Octave itself.  Octave can call C++ code through its native oct-file
interface or C code through its mex interface.  It can also indirectly
call functions written in any other language through a simple wrapper.
The reasons to write code in a compiled language might be either to
link to an existing piece of code and allow it to be used within
Octave, or to allow improved performance for key pieces of code.

   Before going further, you should first determine if you really need
to use dynamically linked functions at all.  Before proceeding with
writing any dynamically linked function to improve performance you
should address ask yourself

   * Can I get the same functionality using the Octave scripting
     language only?

   * Is it thoroughly optimized Octave code?  Vectorization of Octave
     code, doesn't just make it concise, it generally significantly
     improves its performance.  Above all, if loops must be used, make
     sure that the allocation of space for variables takes place
     outside the loops using an assignment to a matrix of the right
     size, or zeros.

   * Does it make as much use as possible of existing built-in library
     routines?  These are highly optimized and many do not carry the
     overhead of being interpreted.

   * Does writing a dynamically linked function represent useful
     investment of your time, relative to staying in Octave?

   Also, as oct- and mex-files are dynamically linked to Octave, they
introduce the possibility of Octave crashing due to errors in the user
code.  For example a segmentation violation in the user's code will
cause Octave to abort.

* Menu:

* Oct-Files::
* Mex-Files::
* Standalone Programs::


File: octave.info,  Node: Oct-Files,  Next: Mex-Files,  Up: Dynamically Linked Functions

A.1 Oct-Files
=============

* Menu:

* Getting Started with Oct-Files::
* Matrices and Arrays in Oct-Files::
* Character Strings in Oct-Files::
* Cell Arrays in Oct-Files::
* Structures in Oct-Files::
* Sparse Matrices in Oct-Files::
* Accessing Global Variables in Oct-Files::
* Calling Octave Functions from Oct-Files::
* Calling External Code from Oct-Files::
* Allocating Local Memory in Oct-Files::
* Input Parameter Checking in Oct-Files::
* Exception and Error Handling in Oct-Files::
* Documentation and Test of Oct-Files::


File: octave.info,  Node: Getting Started with Oct-Files,  Next: Matrices and Arrays in Oct-Files,  Up: Oct-Files

A.1.1 Getting Started with Oct-Files
------------------------------------

The basic command to build oct-files is `mkoctfile' and it can be call
from within octave or from the command line.

 -- Function File:  mkoctfile [-options] file ...
     The `mkoctfile' function compiles source code written in C, C++,
     or Fortran.  Depending on the options used with `mkoctfile', the
     compiled code can be called within Octave or can be used as a
     stand-alone application.

     `mkoctfile' can be called from the shell prompt or from the Octave
     prompt.

     `mkoctfile' accepts the following options, all of which are
     optional except for the file name of the code you wish to compile:

    `-I DIR'
          Add the include directory DIR to compile commands.

    `-D DEF'
          Add the definition DEF to the compiler call.

    `-l LIB'
          Add the library LIB to the link command.

    `-L DIR'
          Add the library directory DIR to the link command.

    `-M'
    `--depend'
          Generate dependency files (.d) for C and C++ source files.

    `-c'
          Compile but do not link.

    `-g'
          Enable debugging options for compilers.

    `-o FILE'
    `--output FILE'
          Output file name.  Default extension is .oct (or .mex if -mex
          is specified) unless linking a stand-alone executable.

    `-p VAR'
    `--print VAR'
          Print the configuration variable VAR.  Recognized variables
          are:

                  ALL_CFLAGS                FFTW_LIBS
                  ALL_CXXFLAGS              FLIBS
                  ALL_FFLAGS                FPICFLAG
                  ALL_LDFLAGS               INCFLAGS
                  BLAS_LIBS                 LDFLAGS
                  CC                        LD_CXX
                  CFLAGS                    LD_STATIC_FLAG
                  CPICFLAG                  LFLAGS
                  CPPFLAGS                  LIBCRUFT
                  CXX                       LIBOCTAVE
                  CXXFLAGS                  LIBOCTINTERP
                  CXXPICFLAG                LIBREADLINE
                  DEPEND_EXTRA_SED_PATTERN  LIBS
                  DEPEND_FLAGS              OCTAVE_LIBS
                  DL_LD                     RDYNAMIC_FLAG
                  DL_LDFLAGS                RLD_FLAG
                  F2C                       SED
                  F2CFLAGS                  XTRA_CFLAGS
                  F77                       XTRA_CXXFLAGS
                  FFLAGS

    `--link-stand-alone'
          Link a stand-alone executable file.

    `--mex'
          Assume we are creating a MEX file.  Set the default output
          extension to ".mex".

    `-s'
    `--strip'
          Strip the output file.

    `-v'
    `--verbose'
          Echo commands as they are executed.

    `file'
          The file to compile or link.  Recognized file types are

                                 .c    C source
                                 .cc   C++ source
                                 .C    C++ source
                                 .cpp  C++ source
                                 .f    Fortran source
                                 .F    Fortran source
                                 .o    object file


   Consider the short example

     #include <octave/oct.h>

     DEFUN_DLD (helloworld, args, nargout,
       "Hello World Help String")
     {
       int nargin = args.length ();
       octave_stdout << "Hello World has " << nargin
             << " input arguments and "
             << nargout << " output arguments.\n";
       return octave_value_list ();
     }

   This example although short introduces the basics of writing a C++
function that can be dynamically linked to Octave.  The easiest way to
make available most of the definitions that might be necessary for an
oct-file in Octave is to use the `#include <octave/oct.h>' header.

   The macro that defines the entry point into the dynamically loaded
function is `DEFUN_DLD'.  This macro takes four arguments, these being

  1. The function name as it will be seen in Octave,

  2. The list of arguments to the function of type `octave_value_list',

  3. The number of output arguments, which can and often is omitted if
     not used, and

  4. The string that will be seen as the help text of the function.

   The return type of functions defined with `DEFUN_DLD' is always
`octave_value_list'.

   There are a couple of important considerations in the choice of
function name.  Firstly, it must be a valid Octave function name and so
must be a sequence of letters, digits and underscores, not starting
with a digit.  Secondly, as Octave uses the function name to define the
filename it attempts to find the function in, the function name in the
`DEFUN_DLD' macro must match the filename of the oct-file.  Therefore,
the above function should be in a file `helloworld.cc', and it should be
compiled to an oct-file using the command

     mkoctfile helloworld.cc

   This will create a file called `helloworld.oct', that is the compiled
version of the function.  It should be noted that it is perfectly
acceptable to have more than one `DEFUN_DLD' function in a source file.
However, there must either be a symbolic link to the oct-file for each
of the functions defined in the source code with the `DEFUN_DLD' macro
or the autoload (*note Function Files::) function should be used.

   The rest of this function then shows how to find the number of input
arguments, how to print through the octave pager, and return from the
function.  After compiling this function as above, an example of its use
is

     helloworld (1, 2, 3)
     -| Hello World has 3 input arguments and 0 output arguments.


File: octave.info,  Node: Matrices and Arrays in Oct-Files,  Next: Character Strings in Oct-Files,  Prev: Getting Started with Oct-Files,  Up: Oct-Files

A.1.2 Matrices and Arrays in Oct-Files
--------------------------------------

Octave supports a number of different array and matrix classes, the
majority of which are based on the Array class.  The exception is the
sparse matrix types discussed separately below.  There are three basic
matrix types

`Matrix'
     A double precision matrix class defined in dMatrix.h,

`ComplexMatrix'
     A complex matrix class defined in CMatrix.h, and

`BoolMatrix'
     A boolean matrix class defined in boolMatrix.h.

   These are the basic two-dimensional matrix types of octave.  In
additional there are a number of multi-dimensional array types, these
being

`NDArray'
     A double precision array class defined in `dNDArray.h'

`ComplexNDarray'
     A complex array class defined in `CNDArray.h'

`boolNDArray'
     A boolean array class defined in `boolNDArray.h'

`int8NDArray'
`int16NDArray'
`int32NDArray'
`int64NDArray'
     8, 16, 32 and 64-bit signed array classes defined in
     `int8NDArray.h', `int16NDArray.h', etc.

`uint8NDArray'
`uint16NDArray'
`uint32NDArray'
`uint64NDArray'
     8, 16, 32 and 64-bit unsigned array classes defined in
     `uint8NDArray.h', `uint16NDArray.h', etc.

   There are several basic means of constructing matrices of
multi-dimensional arrays.  Considering the `Matrix' type as an example

   * We can create an empty matrix or array with the empty constructor.
     For example

          Matrix a;

     This can be used on all matrix and array types

   * Define the dimensions of the matrix or array with a dim_vector.
     For example

          dim_vector dv (2);
          dv(0) = 2; dv(1) = 2;
          Matrix a (dv);

     This can be used on all matrix and array types

   * Define the number of rows and columns in the matrix.  For example

          Matrix a (2, 2)

     However, this constructor can only be used with the matrix types.

   These types all share a number of basic methods and operators, a
selection of which include

 -- Method: T& operator () (octave_idx_type)
 -- Method: T& elem (octave_idx_type)
     The `()' operator or `elem' method allow the values of the matrix
     or array to be read or set.  These can take a single argument,
     which is of type `octave_idx_type', that is the index into the
     matrix or array.  Additionally, the matrix type allows two
     argument versions of the `()' operator and elem method, giving the
     row and column index of the value to obtain or set.

   Note that these functions do significant error checking and so in
some circumstances the user might prefer to access the data of the
array or matrix directly through the fortran_vec method discussed below.

 -- Method: octave_idx_type nelem (void) const
     The total number of elements in the matrix or array.

 -- Method: size_t byte_size (void) const
     The number of bytes used to store the matrix or array.

 -- Method: dim_vector dims (void) const
     The dimensions of the matrix or array in value of type dim_vector.

 -- Method: void resize (const dim_vector&)
     A method taking either an argument of type `dim_vector', or in the
     case of a matrix two arguments of type `octave_idx_type' defining
     the number of rows and columns in the matrix.

 -- Method: T* fortran_vec (void)
     This method returns a pointer to the underlying data of the matrix
     or a array so that it can be manipulated directly, either within
     Octave or by an external library.

   Operators such an `+', `-', or `*' can be used on the majority of
the above types.  In addition there are a number of methods that are of
interest only for matrices such as `transpose', `hermitian', `solve',
etc.

   The typical way to extract a matrix or array from the input
arguments of `DEFUN_DLD' function is as follows

     #include <octave/oct.h>

     DEFUN_DLD (addtwomatrices, args, , "Add A to B")
     {
       int nargin = args.length ();
       if (nargin != 2)
         print_usage ();
       else
         {
           NDArray A = args(0).array_value ();
           NDArray B = args(1).array_value ();
           if (! error_state)
             return octave_value (A + B);
         }
       return octave_value_list ();
     }

   To avoid segmentation faults causing Octave to abort, this function
explicitly checks that there are sufficient arguments available before
accessing these arguments.  It then obtains two multi-dimensional arrays
of type `NDArray' and adds these together.  Note that the array_value
method is called without using the `is_matrix_type' type, and instead
the error_state is checked before returning `A + B'.  The reason to
prefer this is that the arguments might be a type that is not an
`NDArray', but it would make sense to convert it to one.  The
`array_value' method allows this conversion to be performed
transparently if possible, and sets `error_state' if it is not.

   `A + B', operating on two `NDArray''s returns an `NDArray', which is
cast to an `octave_value' on the return from the function.  An example
of the use of this demonstration function is

     addtwomatrices (ones (2, 2), ones (2, 2))
           =>  2  2
               2  2

   A list of the basic `Matrix' and `Array' types, the methods to
extract these from an `octave_value' and the associated header is
listed below.

`RowVector'            `row_vector_value'            `dRowVector.h'
`ComplexRowVector'     `complex_row_vector_value'    `CRowVector.h'
`ColumnVector'         `column_vector_value'         `dColVector.h'
`ComplexColumnVector'  `complex_column_vector_value' `CColVector.h'
`Matrix'               `matrix_value'                `dMatrix.h'
`ComplexMatrix'        `complex_matrix_value'        `CMatrix.h'
`boolMatrix'           `bool_matrix_value'           `boolMatrix.h'
`charMatrix'           `char_matrix_value'           `chMatrix.h'
`NDArray'              `array_value'                 `dNDArray.h'
`ComplexNDArray'       `complex_array_value'         `CNDArray.h'
`boolNDArray'          `bool_array_value'            `boolNDArray.h'
`charNDArray'          `char_array_value'            `charNDArray.h'
`int8NDArray'          `int8_array_value'            `int8NDArray.h'
`int16NDArray'         `int16_array_value'           `int16NDArray.h'
`int32NDArray'         `int32_array_value'           `int32NDArray.h'
`int64NDArray'         `int64_array_value'           `int64NDArray.h'
`uint8NDArray'         `uint8_array_value'           `uint8NDArray.h'
`uint16NDArray'        `uint16_array_value'          `uint16NDArray.h'
`uint32NDArray'        `uint32_array_value'          `uint32NDArray.h'
`uint64NDArray'        `uint64_array_value'          `uint64NDArray.h'


File: octave.info,  Node: Character Strings in Oct-Files,  Next: Cell Arrays in Oct-Files,  Prev: Matrices and Arrays in Oct-Files,  Up: Oct-Files

A.1.3 Character Strings in Oct-Files
------------------------------------

In Octave a character string is just a special `Array' class.  Consider
the example

     #include <octave/oct.h>

     DEFUN_DLD (stringdemo, args, , "String Demo")
     {
       int nargin = args.length();
       octave_value_list retval;

       if (nargin != 1)
         print_usage ();
       else
         {
           charMatrix ch = args(0).char_matrix_value ();

           if (! error_state)
             {
               if (args(0).is_sq_string ())
                 retval(1) = octave_value (ch, true);
               else
                 retval(1) = octave_value (ch, true, '\'');

               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(),
     			 i, 0);
                   ch.insert (tmp.c_str(), nr-i-1, 0);
                 }
               retval(0) = octave_value (ch, true);
             }
         }
       return retval;
     }

   An example of the use of this function is

     s0 = ["First String"; "Second String"];
     [s1,s2] = stringdemo (s0)
     => s1 = Second String
             First String

     => s2 = First String
             Second String

     typeinfo (s2)
     => sq_string
     typeinfo (s1)
     => string

   One additional complication of strings in Octave is the difference
between single quoted and double quoted strings.  To find out if an
`octave_value' contains a single or double quoted string an example is

         if (args(0).is_sq_string ())
           octave_stdout <<
             "First argument is a singularly quoted string\n";
         else if (args(0).is_dq_string ())
           octave_stdout <<
             "First argument is a doubly quoted string\n";

   Note however, that both types of strings are represented by the
`charNDArray' type, and so when assigning to an `octave_value', the
type of string should be specified.  For example

     octave_value_list retval;
     charNDArray c;
     ...
     // Create single quoted string
     retval(1) = octave_value (ch, true, '\'');

     // Create a double quoted string
     retval(0) = octave_value (ch, true);


File: octave.info,  Node: Cell Arrays in Oct-Files,  Next: Structures in Oct-Files,  Prev: Character Strings in Oct-Files,  Up: Oct-Files

A.1.4 Cell Arrays in Oct-Files
------------------------------

Octave's cell type is equally accessible within oct-files.  A cell
array is just an array of `octave_value's, and so each element of the
cell array can then be treated just like any other `octave_value'.  A
simple example is

     #include <octave/oct.h>
     #include <octave/Cell.h>

     DEFUN_DLD (celldemo, args, , "Cell Demo")
     {
       octave_value_list retval;
       int nargin = args.length ();

       if (nargin != 1)
         print_usage ();
       else
         {
           Cell c = args (0).cell_value ();
           if (! error_state)
             for (octave_idx_type i = 0; i < c.nelem (); i++)
               retval(i) = c.elem (i);
         }

       return retval;
     }

   Note that cell arrays are used less often in standard oct-files and
so the `Cell.h' header file must be explicitly included.  The rest of
this example extracts the `octave_value's one by one from the cell
array and returns be as individual return arguments.  For example
consider

     [b1, b2, b3] = celldemo ({1, [1, 2], "test"})
     =>
     b1 =  1
     b2 =

        1   2

     b3 = test


File: octave.info,  Node: Structures in Oct-Files,  Next: Sparse Matrices in Oct-Files,  Prev: Cell Arrays in Oct-Files,  Up: Oct-Files

A.1.5 Structures in Oct-Files
-----------------------------

A structure in Octave is map between a number of fields represented and
their values.  The Standard Template Library `map' class is used, with
the pair consisting of a `std::string' and an octave `Cell' variable.

   A simple example demonstrating the use of structures within
oct-files is

     #include <octave/oct.h>
     #include <octave/ov-struct.h>

     DEFUN_DLD (structdemo, args, , "Struct demo.")
     {
       int nargin = args.length ();
       octave_value retval;

       if (nargin != 2)
         print_usage ();
       else
         {
           Octave_map arg0 = args(0).map_value ();
           std::string arg1 = args(1).string_value ();

           if (! error_state && arg0.contains (arg1))
             {
               // The following two lines might be written as
               //    octave_value tmp;
               //    for (Octave_map::iterator p0 =
     	  //        arg0.begin();
               //        p0 != arg0.end(); p0++ )
               //      if (arg0.key (p0) == arg1)
               //        {
               //          tmp = arg0.contents (p0) (0);
               //          break;
               //        }
               // though using seek is more concise.
               Octave_map::const_iterator p1 = arg0.seek (arg1);
               octave_value tmp =  arg0.contents(p1)(0);
               Octave_map st;
               st.assign ("selected", tmp);
               retval = octave_value (st);
             }
         }
       return retval;
     }

   An example of its use is

     x.a = 1; x.b = "test"; x.c = [1, 2];
     structdemo (x, "b")
     => selected = test

   The commented code above demonstrates how to iterate over all of the
fields of the structure, where as the following code demonstrates
finding a particular field in a more concise manner.

   As can be seen the `contents' method of the `Octave_map' class
returns a `Cell' which allows structure arrays to be represented.
Therefore, to obtain the underlying `octave_value' we write

     octave_value tmp = arg0.contents (p1) (0);

   where the trailing (0) is the () operator on the `Cell' object.  We
can equally iterate of the elements of the Cell array to address the
elements of the structure array.


File: octave.info,  Node: Sparse Matrices in Oct-Files,  Next: Accessing Global Variables in Oct-Files,  Prev: Structures in Oct-Files,  Up: Oct-Files

A.1.6 Sparse Matrices in Oct-Files
----------------------------------

There are three classes of sparse objects that are of interest to the
user.

`SparseMatrix'
     A double precision sparse matrix class

`SparseComplexMatrix'
     A complex sparse matrix class

`SparseBoolMatrix'
     A boolean sparse matrix class

   All of these classes inherit from the `Sparse<T>' template class,
and so all have similar capabilities and usage.  The `Sparse<T>' class
was based on Octave `Array<T>' class, and so users familiar with
Octave's `Array' classes will be comfortable with the use of the sparse
classes.

   The sparse classes will not be entirely described in this section,
due to their similarity with the existing `Array' classes.  However,
there are a few differences due the different nature of sparse objects,
and these will be described.  Firstly, although it is fundamentally
possible to have N-dimensional sparse objects, the Octave sparse
classes do not allow them at this time.  So all operations of the
sparse classes must be 2-dimensional.  This means that in fact
`SparseMatrix' is similar to Octave's `Matrix' class rather than its
`NDArray' class.

* Menu:

* Array and Sparse Differences::
* Creating Sparse Matrices in Oct-Files::
* Using Sparse Matrices in Oct-Files::


File: octave.info,  Node: Array and Sparse Differences,  Next: Creating Sparse Matrices in Oct-Files,  Up: Sparse Matrices in Oct-Files

A.1.6.1 The Differences between the Array and Sparse Classes
............................................................

The number of elements in a sparse matrix is considered to be the number
of non-zero elements rather than the product of the dimensions.
Therefore

     SparseMatrix sm;
     ...
     int nel = sm.nelem ();

   returns the number of non-zero elements.  If the user really
requires the number of elements in the matrix, including the non-zero
elements, they should use `numel' rather than `nelem'.  Note that for
very large matrices, where the product of the two dimensions is larger
than the representation of an unsigned int, then `numel' can overflow.
An example is `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.  The use of `numel' should therefore be avoided useless it is known
it won't overflow.

   Extreme care must be take with the elem method and the "()" operator,
which perform basically the same function.  The reason is that if a
sparse object is non-const, then Octave will assume that a request for
a zero element in a sparse matrix is in fact a request to create this
element so it can be filled.  Therefore a piece of code like

     SparseMatrix sm;
     ...
     for (int j = 0; j < nc; j++)
       for (int i = 0; i < nr; i++)
         std::cerr << " (" << i << "," << j << "): " << sm(i,j)
                   << std::endl;

   is a great way of turning the sparse matrix into a dense one, and a
very slow way at that since it reallocates the sparse object at each
zero element in the matrix.

   An easy way of preventing the above from happening is to create a
temporary constant version of the sparse matrix.  Note that only the
container for the sparse matrix will be copied, while the actual
representation of the data will be shared between the two versions of
the sparse matrix.  So this is not a costly operation.  For example,
the above would become

     SparseMatrix sm;
     ...
     const SparseMatrix tmp (sm);
     for (int j = 0; j < nc; j++)
       for (int i = 0; i < nr; i++)
         std::cerr << " (" << i << "," << j << "): " << tmp(i,j)
                   << std::endl;

   Finally, as the sparse types aren't just represented as a contiguous
block of memory, the `fortran_vec' method of the `Array<T>' is not
available.  It is however replaced by three separate methods `ridx',
`cidx' and `data', that access the raw compressed column format that
the Octave sparse matrices are stored in.  Additionally, these methods
can be used in a manner similar to `elem', to allow the matrix to be
accessed or filled.  However, in that case it is up to the user to
respect the sparse matrix compressed column format discussed previous.


File: octave.info,  Node: Creating Sparse Matrices in Oct-Files,  Next: Using Sparse Matrices in Oct-Files,  Prev: Array and Sparse Differences,  Up: Sparse Matrices in Oct-Files

A.1.6.2 Creating Sparse Matrices in Oct-Files
.............................................

You have several alternatives for creating a sparse matrix.  You can
first create the data as three vectors representing the row and column
indexes and the data, and from those create the matrix.  Or
alternatively, you can create a sparse matrix with the appropriate
amount of space and then fill in the values.  Both techniques have their
advantages and disadvantages.

   Here is an example of how to create a small sparse matrix with the
first technique

     int nz = 4, nr = 3, nc = 4;

     ColumnVector ridx (nz);
     ColumnVector cidx (nz);
     ColumnVector data (nz);

     ridx(0) = 0; ridx(1) = 0; ridx(2) = 1; ridx(3) = 2;
     cidx(0) = 0; cidx(1) = 1; cidx(2) = 3; cidx(3) = 3;
     data(0) = 1; data(1) = 2; data(2) = 3; data(3) = 4;

     SparseMatrix sm (data, ridx, cidx, nr, nc);

which creates the matrix given in section *note Storage of Sparse
Matrices::.  Note that the compressed matrix format is not used at the
time of the creation of the matrix itself, however it is used
internally.

   As previously mentioned, the values of the sparse matrix are stored
in increasing column-major ordering.  Although the data passed by the
user does not need to respect this requirement, the pre-sorting the
data significantly speeds up the creation of the sparse matrix.

   The disadvantage of this technique of creating a sparse matrix is
that there is a brief time where two copies of the data exists.
Therefore for extremely memory constrained problems this might not be
the right technique to create the sparse matrix.

   The alternative is to first create the sparse matrix with the desired
number of non-zero elements and then later fill those elements in.  The
easiest way to do this is

     int nz = 4, nr = 3, nc = 4;
     SparseMatrix sm (nr, nc, nz);
     sm(0,0) = 1; sm(0,1) = 2; sm(1,3) = 3; sm(2,3) = 4;

   That creates the same matrix as previously.  Again, although it is
not strictly necessary, it is significantly faster if the sparse matrix
is created in this manner that the elements are added in column-major
ordering.  The reason for this is that if the elements are inserted at
the end of the current list of known elements then no element in the
matrix needs to be moved to allow the new element to be inserted.  Only
the column indexes need to be updated.

   There are a few further points to note about this technique of
creating a sparse matrix.  Firstly, it is possible to create a sparse
matrix with fewer elements than are actually inserted in the matrix.
Therefore

     int nz = 4, nr = 3, nc = 4;
     SparseMatrix sm (nr, nc, 0);
     sm(0,0) = 1; sm(0,1) = 2; sm(1,3) = 3; sm(2,3) = 4;

is perfectly valid.  However it is a very bad idea.  The reason is that
as each new element is added to the sparse matrix the space allocated
to it is increased by reallocating the memory.  This is an expensive
operation, that will significantly slow this means of creating a sparse
matrix.  Furthermore, it is possible to create a sparse matrix with too
much storage, so having NZ above equaling 6 is also valid.  The
disadvantage is that the matrix occupies more memory than strictly
needed.

   It is not always easy to know the number of non-zero elements prior
to filling a matrix.  For this reason the additional storage for the
sparse matrix can be removed after its creation with the
"maybe_compress" function.  Furthermore, the maybe_compress can
deallocate the unused storage, but it can equally remove zero elements
from the matrix.  The removal of zero elements from the matrix is
controlled by setting the argument of the "maybe_compress" function to
be `true'.  However, the cost of removing the zeros is high because it
implies resorting the elements.  Therefore, if possible it is better is
the user doesn't add the zeros in the first place.  An example of the
use of "maybe_compress" is

       int nz = 6, nr = 3, nc = 4;

       SparseMatrix sm1 (nr, nc, nz);
       sm1(0,0) = 1; sm1(0,1) = 2; sm1(1,3) = 3; sm1(2,3) = 4;
       sm1.maybe_compress ();  // No zero elements were added

       SparseMatrix sm2 (nr, nc, nz);
       sm2(0,0) = 1; sm2(0,1) = 2; sm(0,2) = 0; sm(1,2) = 0;
       sm1(1,3) = 3; sm1(2,3) = 4;
       sm2.maybe_compress (true);  // Zero elements were added

   The use of the "maybe_compress" function should be avoided if
possible, as it will slow the creation of the matrices.

   A third means of creating a sparse matrix is to work directly with
the data in compressed row format.  An example of this technique might
be

     octave_value arg;
     ...
     int nz = 6, nr = 3, nc = 4;   // Assume we know the max no nz
     SparseMatrix sm (nr, nc, nz);
     Matrix m = arg.matrix_value ();

     int ii = 0;
     sm.cidx (0) = 0;
     for (int j = 1; j < nc; j++)
       {
         for (int i = 0; i < nr; i++)
           {
             double tmp = foo (m(i,j));
             if (tmp != 0.)
               {
                 sm.data(ii) = tmp;
                 sm.ridx(ii) = i;
                 ii++;
               }
           }
         sm.cidx(j+1) = ii;
      }
     sm.maybe_compress ();  // If don't know a-priori
                            // the final no of nz.

which is probably the most efficient means of creating the sparse
matrix.

   Finally, it might sometimes arise that the amount of storage
initially created is insufficient to completely store the sparse
matrix.  Therefore, the method `change_capacity' exists to reallocate
the sparse memory.  The above example would then be modified as

     octave_value arg;
     ...
     int nz = 6, nr = 3, nc = 4;   // Assume we know the max no nz
     SparseMatrix sm (nr, nc, nz);
     Matrix m = arg.matrix_value ();

     int ii = 0;
     sm.cidx (0) = 0;
     for (int j = 1; j < nc; j++)
       {
         for (int i = 0; i < nr; i++)
           {
             double tmp = foo (m(i,j));
             if (tmp != 0.)
               {
                 if (ii == nz)
                   {
                     nz += 2;   // Add 2 more elements
                     sm.change_capacity (nz);
                   }
                 sm.data(ii) = tmp;
                 sm.ridx(ii) = i;
                 ii++;
               }
           }
         sm.cidx(j+1) = ii;
      }
     sm.maybe_mutate ();  // If don't know a-priori
                          // the final no of nz.

   Note that both increasing and decreasing the number of non-zero
elements in a sparse matrix is expensive, as it involves memory
reallocation.  Also as parts of the matrix, though not its entirety,
exist as the old and new copy at the same time, additional memory is
needed.  Therefore if possible this should be avoided.


File: octave.info,  Node: Using Sparse Matrices in Oct-Files,  Prev: Creating Sparse Matrices in Oct-Files,  Up: Sparse Matrices in Oct-Files

A.1.6.3 Using Sparse Matrices in Oct-Files
..........................................

Most of the same operators and functions on sparse matrices that are
available from the Octave are equally available with oct-files.  The
basic means of extracting a sparse matrix from an `octave_value' and
returning them as an `octave_value', can be seen in the following
example

     octave_value_list retval;

     SparseMatrix sm = args(0).sparse_matrix_value ();
     SparseComplexMatrix scm =
         args(1).sparse_complex_matrix_value ();
     SparseBoolMatrix sbm = args(2).sparse_bool_matrix_value ();
     ...
     retval(2) = sbm;
     retval(1) = scm;
     retval(0) = sm;

   The conversion to an octave-value is handled by the sparse
`octave_value' constructors, and so no special care is needed.


File: octave.info,  Node: Accessing Global Variables in Oct-Files,  Next: Calling Octave Functions from Oct-Files,  Prev: Sparse Matrices in Oct-Files,  Up: Oct-Files

A.1.7 Accessing Global Variables in Oct-Files
---------------------------------------------

Global variables allow variables in the global scope to be accessed.
Global variables can easily be accessed with oct-files using the
support functions `get_global_value' and `set_global_value'.
`get_global_value' takes two arguments, the first is a string
representing the variable name to obtain.  The second argument is a
boolean argument specifying what to do in the case that no global
variable of the desired name is found.  An example of the use of these
two functions is

     #include <octave/oct.h>

     DEFUN_DLD (globaldemo, args, , "Global demo.")
     {
       int nargin = args.length ();
       octave_value retval;

       if (nargin != 1)
         print_usage ();
       else
         {
           std::string s = args(0).string_value ();
           if (! error_state)
             {
               octave_value tmp = get_global_value (s, true);
               if (tmp.is_defined ())
                 retval = tmp;
               else
                 retval = "Global variable not found";

               set_global_value ("a", 42.0);
             }
         }
       return retval;
     }

   An example of its use is

     global a b
     b = 10;
     globaldemo ("b")
     => 10
     globaldemo ("c")
     => "Global variable not found"
     num2str (a)
     => 42


File: octave.info,  Node: Calling Octave Functions from Oct-Files,  Next: Calling External Code from Oct-Files,  Prev: Accessing Global Variables in Oct-Files,  Up: Oct-Files

A.1.8 Calling Octave Functions from Oct-Files
---------------------------------------------

There is often a need to be able to call another octave function from
within an oct-file, and there are many examples of such within octave
itself.  For example the `quad' function is an oct-file that calculates
the definite integral by quadrature over a user supplied function.

   There are also many ways in which a function might be passed.  It
might be passed as one of

  1. Function Handle

  2. Anonymous Function Handle

  3. Inline Function

  4. String

   The example below demonstrates an example that accepts all four
means of passing a function to an oct-file.

     #include <octave/oct.h>
     #include <octave/parse.h>

     DEFUN_DLD (funcdemo, args, nargout, "Function Demo")
     {
       int nargin = args.length();
       octave_value_list retval;

       if (nargin < 2)
         print_usage ();
       else
         {
           octave_value_list newargs;
           for (octave_idx_type i = nargin - 1; i > 0; i--)
             newargs (i - 1) = args(i);
           if (args(0).is_function_handle ()
               || args(0).is_inline_function ())
             {
               octave_function *fcn = args(0).function_value ();
               if (! error_state)
                 retval = feval (fcn, newargs, nargout);
             }
           else if (args(0).is_string ())
             {
               std::string fcn = args (0).string_value ();
               if (! error_state)
                 retval = feval (fcn, newargs, nargout);
             }
           else
             error ("funcdemo: expected string,",
     	       " inline or function handle");
         }
       return retval;
     }

   The first argument to this demonstration is the user supplied
function and the following arguments are all passed to the user
function.

     funcdemo (@sin,1)
     => 0.84147
     funcdemo (@(x) sin(x), 1)
     => 0.84147
     funcdemo (inline ("sin(x)"), 1)
     => 0.84147
     funcdemo ("sin",1)
     => 0.84147
     funcdemo (@atan2, 1, 1)
     => 0.78540

   When the user function is passed as a string, the treatment of the
function is different.  In some cases it is necessary to always have the
user supplied function as an `octave_function' object.  In that case
the string argument can be used to create a temporary function like

     std::octave fcn_name = unique_symbol_name ("__fcn__");
     std::string fname = "function y = ";
     fname.append (fcn_name);
     fname.append ("(x) y = ");
     fcn = extract_function (args(0), "funcdemo", fcn_name,
                             fname, "; endfunction");
     ...
     if (fcn_name.length ())
       clear_function (fcn_name);

   There are two important things to know in this case.  The number of
input arguments to the user function is fixed, and in the above is a
single argument, and secondly to avoid leaving the temporary function
in the Octave symbol table it should be cleared after use.


File: octave.info,  Node: Calling External Code from Oct-Files,  Next: Allocating Local Memory in Oct-Files,  Prev: Calling Octave Functions from Oct-Files,  Up: Oct-Files

A.1.9 Calling External Code from Oct-Files
------------------------------------------

Linking external C code to Octave is relatively simple, as the C
functions can easily be called directly from C++.  One possible issue is
the declarations of the external C functions might need to be explicitly
defined as C functions to the compiler.  If the declarations of the
external C functions are in the header `foo.h', then the manner in
which to ensure that the C++ compiler treats these declarations as C
code is

     #ifdef __cplusplus
     extern "C"
     {
     #endif
     #include "foo.h"
     #ifdef __cplusplus
     }  /* end extern "C" */
     #endif

   Calling Fortran code however can pose some difficulties.  This is
due to differences in the manner in compilers treat the linking of
Fortran code with C or C++ code.  Octave supplies a number of macros
that allow consistent behavior across a number of compilers.

   The underlying Fortran code should use the `XSTOPX' function to
replace the Fortran `STOP' function.  `XSTOPX' uses the Octave
exception handler to treat failing cases in the fortran code
explicitly.  Note that Octave supplies its own replacement BLAS
`XERBLA' function, which uses `XSTOPX'.

   If the underlying code calls `XSTOPX', then the `F77_XFCN' macro
should be used to call the underlying fortran function.  The Fortran
exception state can then be checked with the global variable
`f77_exception_encountered'.  If `XSTOPX' will not be called, then the
`F77_FCN' macro should be used instead to call the Fortran code.

   There is no harm in using `F77_XFCN' in all cases, except that for
Fortran code that is short running and executes a large number of times,
there is potentially an overhead in doing so.  However, if `F77_FCN' is
used with code that calls `XSTOP', Octave can generate a segmentation
fault.

   An example of the inclusion of a Fortran function in an oct-file is
given in the following example, where the C++ wrapper is

     #include <octave/oct.h>
     #include <octave/f77-fcn.h>

     extern "C"
     {
       F77_RET_T
       F77_FUNC (fortsub, FORTSUB)
             (const int&, double*, F77_CHAR_ARG_DECL
              F77_CHAR_ARG_LEN_DECL);
     }

     DEFUN_DLD (fortdemo , args , , "Fortran Demo.")
     {
       octave_value_list retval;
       int nargin = args.length();
       if (nargin != 1)
         print_usage ();
       else
         {
           NDArray a = args(0).array_value ();
           if (! error_state)
             {
               double *av = a.fortran_vec ();
               octave_idx_type na = a.nelem ();
               OCTAVE_LOCAL_BUFFER (char, ctmp, 128);

               F77_XFCN (fortsub, FORTSUB, (na, av, ctmp
                         F77_CHAR_ARG_LEN (128)));

     	  retval(1) = std::string (ctmp);
     	  retval(0) = a;
             }
         }
       return retval;
     }

and the fortran function is

           subroutine fortsub (n, a, s)
           implicit none
           character*(*) s
           real*8 a(*)
           integer*4 i, n, ioerr
           do i = 1, n
             if (a(i) .eq. 0d0) then
               call xstopx ('fortsub: divide by zero')
             else
               a(i) = 1d0 / a(i)
             endif
           enddo
           write (unit = s, fmt = '(a,i3,a,a)', iostat = ioerr)
          $       'There are ', n,
          $       ' values in the input vector', char(0)
           if (ioerr .ne. 0) then
             call xstopx ('fortsub: error writing string')
           endif
           return
           end

   This example demonstrates most of the features needed to link to an
external Fortran function, including passing arrays and strings, as well
as exception handling.  An example of the behavior of this function is

     [b, s] = fortdemo (1:3)
     =>
       b = 1.00000   0.50000   0.33333
       s = There are   3 values in the input vector
     [b, s] = fortdemo(0:3)
     error: fortsub:divide by zero
     error: exception encountered in Fortran subroutine fortsub_
     error: fortdemo: error in fortran


File: octave.info,  Node: Allocating Local Memory in Oct-Files,  Next: Input Parameter Checking in Oct-Files,  Prev: Calling External Code from Oct-Files,  Up: Oct-Files

A.1.10 Allocating Local Memory in Oct-Files
-------------------------------------------

Allocating memory within an oct-file might seem easy as the C++
new/delete operators can be used.  However, in that case care must be
taken to avoid memory leaks.  The preferred manner in which to allocate
memory for use locally is to use the `OCTAVE_LOCAL_BUFFER' macro.  An
example of its use is

     OCTAVE_LOCAL_BUFFER (double, tmp, len)

   that returns a pointer `tmp' of type `double *' of length `len'.


File: octave.info,  Node: Input Parameter Checking in Oct-Files,  Next: Exception and Error Handling in Oct-Files,  Prev: Allocating Local Memory in Oct-Files,  Up: Oct-Files

A.1.11 Input Parameter Checking in Oct-Files
--------------------------------------------

As oct-files are compiled functions they have the possibility of causing
Octave to abort abnormally.  It is therefore important that each and
every function has the minimum of parameter checking needed to ensure
that Octave behaves well.

   The minimum requirement, as previously discussed, is to check the
number of input arguments before using them to avoid referencing a non
existent argument.  However, it some case this might not be sufficient
as the underlying code imposes further constraints.  For example an
external function call might be undefined if the input arguments are not
integers, or if one of the arguments is zero.  Therefore, oct-files
often need additional input parameter checking.

   There are several functions within Octave that might be useful for
the purposes of parameter checking.  These include the methods of the
octave_value class like `is_real_matrix', etc., but equally include
more specialized functions.  Some of the more common ones are
demonstrated in the following example

     #include <octave/oct.h>

     DEFUN_DLD (paramdemo, args, nargout,
     	   "Parameter Check Demo.")
     {
       int nargin = args.length ();
       octave_value retval;

       if (nargin != 1)
         print_usage();
       else if (nargout != 0)
         error ("paramdemo: function has no output arguments");
       else
         {
           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())
             octave_stdout << "  includes Inf or NaN values\n";
           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())
             octave_stdout <<
     	  "  includes only int, Inf or NaN values\n";
           if (m.all_integers (min_val, max_val))
             octave_stdout <<
     	  "  includes only integers in [-10,10]\n";
         }
       return retval;
     }

and an example of its use is

     paramdemo ([1, 2, NaN, Inf])
     => Properties of input array:
           includes Inf or NaN values
           includes other values than 1 and 0
           includes only int, Inf or NaN values


File: octave.info,  Node: Exception and Error Handling in Oct-Files,  Next: Documentation and Test of Oct-Files,  Prev: Input Parameter Checking in Oct-Files,  Up: Oct-Files

A.1.12 Exception and Error Handling in Oct-Files
------------------------------------------------

Another important feature of Octave is its ability to react to the user
typing `Control-C' even during calculations.  This ability is based on
the C++ exception handler, where memory allocated by the C++ new/delete
methods are automatically released when the exception is treated.  When
writing an oct-file, to allow Octave to treat the user typing
`Control-C', the `OCTAVE_QUIT' macro is supplied.  For example

     for (octave_idx_type i = 0; i < a.nelem (); i++)
       {
         OCTAVE_QUIT;
         b.elem(i) = 2. * a.elem(i);
       }

   The presence of the `OCTAVE_QUIT' macro in the inner loop allows
Octave to treat the user request with the `Control-C'.  Without this
macro, the user must either wait for the function to return before the
interrupt is processed, or press `Control-C' three times to force
Octave to exit.

   The `OCTAVE_QUIT' macro does impose a very small speed penalty, and
so for loops that are known to be small it might not make sense to
include `OCTAVE_QUIT'.

   When creating an oct-file that uses an external libraries, the
function might spend a significant portion of its time in the external
library.  It is not generally possible to use the `OCTAVE_QUIT' macro in
this case.  The alternative in this case is

     BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
     ...  some code that calls a "foreign" function ...
     END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;

   The disadvantage of this is that if the foreign code allocates any
memory internally, then this memory might be lost during an interrupt,
without being deallocated.  Therefore, ideally Octave itself should
allocate any memory that is needed by the foreign code, with either the
fortran_vec method or the `OCTAVE_LOCAL_BUFFER' macro.

   The Octave unwind_protect mechanism (*note The `unwind_protect'
Statement::) can also be used in oct-files.  In conjunction with the
exception handling of Octave, it is important to enforce that certain
code is run to allow variables, etc. to be restored even if an
exception occurs.  An example of the use of this mechanism is

     #include <octave/oct.h>
     #include <octave/unwind-prot.h>

     void
     err_hand (const char *fmt, ...)
     {
       // Do nothing!!
     }

     DEFUN_DLD (unwinddemo, args, nargout, "Unwind Demo")
     {
       int nargin = args.length();
       octave_value retval;
       if (nargin < 2)
         print_usage ();
       else
         {
           NDArray a = args(0).array_value ();
           NDArray b = args(1).array_value ();

           if (! error_state)
             {
               unwind_protect::begin_frame ("Funwinddemo");
               unwind_protect_ptr
     	    (current_liboctave_warning_handler);
               set_liboctave_warning_handler(err_hand);
               retval = octave_value (quotient (a, b));
               unwind_protect::run_frame ("Funwinddemo");
             }
         }
       return retval;
     }

   As can be seen in the example

     unwinddemo (1, 0)
     => Inf
     1 / 0
     => warning: division by zero
        Inf

   The division by zero (and in fact all warnings) is disabled in the
`unwinddemo' function.


File: octave.info,  Node: Documentation and Test of Oct-Files,  Prev: Exception and Error Handling in Oct-Files,  Up: Oct-Files

A.1.13 Documentation and Test of Oct-Files
------------------------------------------

The documentation of an oct-file is the fourth string parameter of the
`DEFUN_DLD' macro.  This string can be formatted in the same manner as
the help strings for user functions (*note Documentation Tips::),
however there are some issue that are particular to the formatting of
help strings within oct-files.

   The major issue is that the help string will typically be longer
than a single line of text, and so the formatting of long help strings
need to be taken into account.  There are several manners in which to
treat this issue, but the most common is illustrated in the following
example

     DEFUN_DLD (do_what_i_want, args, nargout,
       "-*- texinfo -*-\n\
     @deftypefn {Function File} {} do_what_i_say (@var{n})\n\
     A function that does what the user actually wants rather\n\
     than what they requested.\n\
     @end deftypefn")
     {
     ...
     }

where, as can be seen, end line of text within the help string is
terminated by `\n\' which is an embedded new-line in the string
together with a C++ string continuation character.  Note that the final
`\' must be the last character on the line.

   Octave also includes the ability to embed the test and demonstration
code for a function within the code itself (*note Test and Demo
Functions::).  This can be used from within oct-files (or in fact any
file) with certain provisos.  Firstly, the test and demo functions of
Octave look for a `%!' as the first characters on a new-line to
identify test and demonstration code.  This is equally a requirement for
oct-files.  Furthermore the test and demonstration code must be included
in a comment block of the compiled code to avoid it being interpreted by
the compiler.  Finally, the Octave test and demonstration code must have
access to the source code of the oct-file and not just the compiled code
as the tests are stripped from the compiled code.  An example in an
oct-file might be

     /*

     %!error (sin())
     %!error (sin(1,1))
     %!assert (sin([1,2]),[sin(1),sin(2)])

     */


File: octave.info,  Node: Mex-Files,  Next: Standalone Programs,  Prev: Oct-Files,  Up: Dynamically Linked Functions

A.2 Mex-Files
=============

Octave includes an interface to allow legacy mex-files to be compiled
and used with Octave.  This interface can also be used to share code
between Octave and non Octave users.  However, as mex-files expose the
internal API of an alternative product to Octave, and the internal
structure of Octave is different to this product, a mex-file can never
have the same performance in Octave as the equivalent oct-file.  In
particular to support the manner in which mex-files access the variables
passed to mex functions, there are a significant number of additional
copies of memory when calling or returning from a mex function.  For
this reason, new code should be written using the oct-file interface
discussed above if possible.

* Menu:

* Getting Started with Mex-Files::
* Working with Matrices and Arrays in Mex-Files::
* Character Strings in Mex-Files::
* Cell Arrays with Mex-Files::
* Structures with Mex-Files::
* Sparse Matrices with Mex-Files::
* Calling Other Functions in Mex-Files::


File: octave.info,  Node: Getting Started with Mex-Files,  Next: Working with Matrices and Arrays in Mex-Files,  Up: Mex-Files

A.2.1 Getting Started with Mex-Files
------------------------------------

The basic command to build a mex-file is either `mkoctfile --mex' or
`mex'.  The first can either be used from within Octave or from the
command line.  However, to avoid issues with the installation of other
products, the use of the command `mex' is limited to within Octave.

 -- Function File:  mex [options] file ...
     Compile source code written in C, C++, or Fortran, to a MEX file.
     This is equivalent to `mkoctfile --mex [options] file'.

     *See also:* *note mkoctfile: doc-mkoctfile.

 -- Function File:  mexext ()
     Return the filename extension used for MEX files.

   One important difference between the use of mex with other products
and with Octave is that the header file "matrix.h" is implicitly
included through the inclusion of "mex.h".  This is to avoid a conflict
with the Octave file "Matrix.h" with operating systems and compilers
that don't distinguish between filenames in upper and lower case

   Consider the short example

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[], int nrhs,
     	     const mxArray *prhs[])
     {
       mxArray *v = mxCreateDoubleMatrix (1, 1, mxREAL);
       double *data = mxGetPr (v);
       *data = 1.23456789;
       plhs[0] = v;
     }

   This simple example demonstrates the basics of writing a mex-file.
The entry point into the mex-file is defined by `mexFunction'.  Note
that the function name is not explicitly included in the `mexFunction'
and so there can only be a single `mexFunction' entry point per-file.
Also the name of the function is determined by the name of the mex-file
itself.  Therefore if the above function is in the file
`firstmexdemo.c', it can be compiled with

     mkoctfile --mex firstmexdemo.c

which creates a file `firstmexdemo.mex'.  The function can then be run
from Octave as

     firstmexdemo()
     => 1.2346

   It should be noted that the mex-file contains no help string for the
functions it contains.  To document mex-files, there should exist an
m-file in the same directory as the mex-file itself.  Taking the above
as an example, we would therefore have a file `firstmexdemo.m' that
might contain the text

     %FIRSTMEXDEMO Simple test of the functionality of a mex-file.

   In this case, the function that will be executed within Octave will
be given by the mex-file, while the help string will come from the
m-file.  This can also be useful to allow a sample implementation of the
mex-file within the Octave language itself for testing purposes.

   Although we cannot have multiple entry points into a single mex-file,
we can use the `mexFunctionName' function to determine what name the
mex-file was called with.  This can be used to alter the behavior of
the mex-file based on the function name.  For example if

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[], int nrhs,
     	     const mxArray *prhs[])
     {
       const char *nm;
       nm = mexFunctionName ();
       mexPrintf ("You called function: %s\n", nm);
       if (strcmp (nm, "myfunc") == 0)
         mexPrintf ("This is the principal function\n", nm);
       return;
     }

is in file `myfunc.c', and it is compiled with

     mkoctfile --mex myfunc.c
     ln -s myfunc.mex myfunc2.mex

   Then as can be seen by

     myfunc()
     => You called function: myfunc
         This is the principal function
     myfunc2()
     => You called function: myfunc2

the behavior of the mex-file can be altered depending on the functions
name.

   Allow the user should only include `mex.h' in their code, Octave
declares additional functions, typedefs, etc., available to the user to
write mex-files in the headers `mexproto.h' and `mxarray.h'.


File: octave.info,  Node: Working with Matrices and Arrays in Mex-Files,  Next: Character Strings in Mex-Files,  Prev: Getting Started with Mex-Files,  Up: Mex-Files

A.2.2 Working with Matrices and Arrays in Mex-Files
---------------------------------------------------

The basic mex type of all variables is `mxArray'.  All variables, such
as matrices, cell arrays or structures are all stored in this basic
type, and this type serves basically the same purpose as the
octave_value class in oct-files.  That is it acts as a container for the
more specialized types.

   The `mxArray' structure contains at a minimum, the variable it
represents name, its dimensions, its type and whether the variable is
real or complex.  It can however contain a number of additional fields
depending on the type of the `mxArray'.  There are a number of
functions to create `mxArray' structures, including
`mxCreateCellArray', `mxCreateSparse' and the generic
`mxCreateNumericArray'.

   The basic functions to access the data contained in an array is
`mxGetPr'.  As the mex interface assumes that the real and imaginary
parts of a complex array are stored separately, there is an equivalent
function `mxGetPi' that get the imaginary part.  Both of these
functions are for use only with double precision matrices.  There also
exists the generic function `mxGetData' and `mxGetImagData' that
perform the same operation on all matrix types.  For example

     mxArray *m;
     mwSize *dims;
     UINT32_T *pr;

     dims = (mwSize *) mxMalloc (2 * sizeof(mwSize));
     dims[0] = 2;
     dims[1] = 2;
     m = mxCreateNumericArray (2, dims, mxUINT32_CLASS, mxREAL);
     pr =  = (UINT32_T *) mxGetData (m);

   There are also the functions `mxSetPr', etc., that perform the
inverse, and set the data of an Array to use the block of memory pointed
to by the argument of `mxSetPr'.

   Note the type `mwSize' used above, and `mwIndex' are defined as the
native precision of the indexing in Octave on the platform on which the
mex-file is built.  This allows both 32- and 64-bit platforms to
support mex-files.  `mwSize' is used to define array dimension and
maximum number or elements, while `mwIndex' is used to define indexing
into arrays.

   An example that demonstration how to work with arbitrary real or
complex double precision arrays is given by the file `mypow2.c' as given
below.

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray* plhs[], int nrhs,
     	     const mxArray* prhs[])
     {
       mwIndex i;
       mwSize n;
       double *vri, *vro;

       if (nrhs != 1 || ! mxIsNumeric (prhs[0]))
         mexErrMsgTxt ("expects matrix");

       n = mxGetNumberOfElements (prhs[0]);
       plhs[0] = (mxArray *) mxCreateNumericArray
         (mxGetNumberOfDimensions (prhs[0]),
          mxGetDimensions (prhs[0]), mxGetClassID (prhs[0]),
          mxIsComplex (prhs[0]));
       vri = mxGetPr (prhs[0]);
       vro = mxGetPr (plhs[0]);

       if (mxIsComplex (prhs[0]))
         {
           double *vii, *vio;
           vii = mxGetPi (prhs[0]);
           vio = mxGetPi (plhs[0]);

           for (i = 0; i < n; i++)
     	{
     	  vro [i] = vri [i] * vri [i] - vii [i] * vii [i];
     	  vio [i] = 2 * vri [i] * vii [i];
     	}
         }
       else
         {
           for (i = 0; i < n; i++)
     	vro [i] = vri [i] * vri [i];
         }
     }

with an example of its use

     b = randn(4,1) + 1i * randn(4,1);
     all(b.^2 == mypow2(b))
     => 1

   The example above uses the functions `mxGetDimensions',
`mxGetNumberOfElements', and `mxGetNumberOfDimensions' to work with the
dimensions of multi-dimensional arrays.  The functions `mxGetM', and
`mxGetN' are also available to find the number of rows and columns in a
matrix.


File: octave.info,  Node: Character Strings in Mex-Files,  Next: Cell Arrays with Mex-Files,  Prev: Working with Matrices and Arrays in Mex-Files,  Up: Mex-Files

A.2.3 Character Strings in Mex-Files
------------------------------------

As mex-files do not make the distinction between single and double
quoted strings within Octave, there is perhaps less complexity in the
use of strings and character matrices in mex-files.  An example of their
use, that parallels the demo in `stringdemo.cc', is given in the file
`mystring.c', as seen below.

     #include <string.h>
     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[], int nrhs,
     	     const mxArray *prhs[])
     {
       mwIndex i, j;
       mwSize m, n;
       mxChar *pi, *po;

       if (nrhs != 1 || ! mxIsChar (prhs[0]) ||
           mxGetNumberOfDimensions (prhs[0]) > 2)
         mexErrMsgTxt ("expecting char matrix");

       m = mxGetM (prhs[0]);
       n = mxGetN (prhs[0]);
       pi = mxGetChars (prhs[0]);
       plhs[0] = mxCreateNumericMatrix (m, n, mxCHAR_CLASS,
     				   mxREAL);
       po = mxGetChars (plhs[0]);

       for (j = 0; j < n; j++)
         for (i = 0; i < m; i++)
           po [j*m + m - 1 - i] = pi [j*m + i];
     }

An example of its expected output is

     mystring(["First String"; "Second String"])
     => s1 = Second String
             First String

   Other functions in the mex interface for handling character strings
are `mxCreateString', `mxArrayToString', and
`mxCreateCharMatrixFromStrings'.  In a mex-file, a character string is
considered to be a vector rather than a matrix.  This is perhaps an
arbitrary distinction as the data in the mxArray for the matrix is
consecutive in any case.


File: octave.info,  Node: Cell Arrays with Mex-Files,  Next: Structures with Mex-Files,  Prev: Character Strings in Mex-Files,  Up: Mex-Files

A.2.4 Cell Arrays with Mex-Files
--------------------------------

We can perform exactly the same operations in Cell arrays in mex-files
as we can in oct-files.  An example that reduplicates the functional of
the `celldemo.cc' oct-file in a mex-file is given by `mycell.c' as below

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray* plhs[], int nrhs,
     	     const mxArray* prhs[])
     {
       mwSize n;
       mwIndex i;

       if (nrhs != 1 || ! mxIsCell (prhs[0]))
         mexErrMsgTxt ("expects cell");

       n = mxGetNumberOfElements (prhs[0]);
       n = (n > nlhs ? nlhs : n);

       for (i = 0; i < n; i++)
         plhs[i] = mxDuplicateArray (mxGetCell (prhs[0], i));
     }

which as can be seen below has exactly the same behavior as the oct-file
version.

     [b1, b2, b3] = mycell ({1, [1, 2], "test"})
     =>
     b1 =  1
     b2 =

        1   2

     b3 = test

   Note in the example the use of the `mxDuplicateArray' function.  This
is needed as the `mxArray' pointer returned by `mxGetCell' might be
deallocated.  The inverse function to `mxGetCell' is `mcSetCell' and is
defined as

     void mxSetCell (mxArray *ptr, int idx, mxArray *val);

   Finally, to create a cell array or matrix, the appropriate functions
are

     mxArray *mxCreateCellArray (int ndims, const int *dims);
     mxArray *mxCreateCellMatrix (int m, int n);


File: octave.info,  Node: Structures with Mex-Files,  Next: Sparse Matrices with Mex-Files,  Prev: Cell Arrays with Mex-Files,  Up: Mex-Files

A.2.5 Structures with Mex-Files
-------------------------------

The basic function to create a structure in a mex-file is
`mxCreateStructMatrix', which creates a structure array with a two
dimensional matrix, or `mxCreateStructArray'.

     mxArray *mxCreateStructArray (int ndims, int *dims,
                                   int num_keys,
                                   const char **keys);
     mxArray *mxCreateStructMatrix (int rows, int cols,
                                    int num_keys,
                                    const char **keys);

   Accessing the fields of the structure can then be performed with the
`mxGetField' and `mxSetField' or alternatively with the
`mxGetFieldByNumber' and `mxSetFieldByNumber' functions.

     mxArray *mxGetField (const mxArray *ptr, mwIndex index,
                          const char *key);
     mxArray *mxGetFieldByNumber (const mxArray *ptr,
                                  mwIndex index, int key_num);
     void mxSetField (mxArray *ptr, mwIndex index,
                      const char *key, mxArray *val);
     void mxSetFieldByNumber (mxArray *ptr, mwIndex index,
                              int key_num, mxArray *val);

   A difference between the oct-file interface to structures and the
mex-file version is that the functions to operate on structures in
mex-files directly include an `index' over the elements of the arrays
of elements per `field'.  Whereas the oct-file structure includes a
Cell Array per field of the structure.

   An example that demonstrates the use of structures in mex-file can be
found in the file `mystruct.c', as seen below

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray* plhs[], int nrhs,
     	     const mxArray* prhs[])
     {
       int i;
       mwIndex j;
       mxArray *v;
       const char *keys[] = { "this", "that" };

       if (nrhs != 1 || ! mxIsStruct (prhs[0]))
         mexErrMsgTxt ("expects struct");

       for (i = 0; i < mxGetNumberOfFields (prhs[0]); i++)
         for (j = 0; j < mxGetNumberOfElements (prhs[0]); j++)
           {
             mexPrintf ("field %s(%d) = ",
                        mxGetFieldNameByNumber (prhs[0], i), j);
             v = mxGetFieldByNumber (prhs[0], j, i);
             mexCallMATLAB (0, 0, 1, &v, "disp");
           }

       v = mxCreateStructMatrix (2, 2, 2, keys);

       mxSetFieldByNumber (v, 0, 0, mxCreateString ("this1"));
       mxSetFieldByNumber (v, 0, 1, mxCreateString ("that1"));
       mxSetFieldByNumber (v, 1, 0, mxCreateString ("this2"));
       mxSetFieldByNumber (v, 1, 1, mxCreateString ("that2"));
       mxSetFieldByNumber (v, 2, 0, mxCreateString ("this3"));
       mxSetFieldByNumber (v, 2, 1, mxCreateString ("that3"));
       mxSetFieldByNumber (v, 3, 0, mxCreateString ("this4"));
       mxSetFieldByNumber (v, 3, 1, mxCreateString ("that4"));

       if (nlhs)
         plhs[0] = v;
     }

   An example of the behavior of this function within Octave is then

     a(1).f1 = "f11"; a(1).f2 = "f12";
     a(2).f1 = "f21"; a(2).f2 = "f22";
     b = mystruct(a)
     => field f1(0) = f11
         field f1(1) = f21
         field f2(0) = f12
         field f2(1) = f22
         b =
         {
           this =

           (,
             [1] = this1
             [2] = this2
             [3] = this3
             [4] = this4
           ,)

           that =

           (,
             [1] = that1
             [2] = that2
             [3] = that3
             [4] = that4
           ,)

         }


File: octave.info,  Node: Sparse Matrices with Mex-Files,  Next: Calling Other Functions in Mex-Files,  Prev: Structures with Mex-Files,  Up: Mex-Files

A.2.6 Sparse Matrices with Mex-Files
------------------------------------

The Octave format for sparse matrices is identical to the mex format in
that it is a compressed column sparse format.  Also in both, sparse
matrices are required to be two-dimensional.  The only difference is
that the real and imaginary parts of the matrix are stored separately.

   The mex-file interface, as well as using `mxGetM', `mxGetN',
`mxSetM', `mxSetN', `mxGetPr', `mxGetPi', `mxSetPr' and `mxSetPi', the
mex-file interface supplies the functions

     mwIndex *mxGetIr (const mxArray *ptr);
     mwIndex *mxGetJc (const mxArray *ptr);
     mwSize mxGetNzmax (const mxArray *ptr);

     void mxSetIr (mxArray *ptr, mwIndex *ir);
     void mxSetJc (mxArray *ptr, mwIndex *jc);
     void mxSetNzmax (mxArray *ptr, mwSize nzmax);

`mxGetNzmax' gets the maximum number of elements that can be stored in
the sparse matrix.  This is not necessarily the number of non-zero
elements in the sparse matrix.  `mxGetJc' returns an array with one
additional value than the number of columns in the sparse matrix.  The
difference between consecutive values of the array returned by
`mxGetJc' define the number of non-zero elements in each column of the
sparse matrix.  Therefore

     mwSize nz, n;
     mwIndex *Jc;
     mxArray *m;
     ...
     n = mxGetN (m);
     Jc = mxGetJc (m);
     nz = Jc[n];

returns the actual number of non-zero elements stored in the matrix in
`nz'.  As the arrays returned by `mxGetPr' and `mxGetPi' only contain
the non-zero values of the matrix, we also need a pointer to the rows
of the non-zero elements, and this is given by `mxGetIr'.  A complete
example of the use of sparse matrices in mex-files is given by the file
`mysparse.c' as seen below

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray *plhs[], int nrhs,
     	     const mxArray *prhs[])
     {
       mwSize n, m, nz;
       mxArray *v;
       mwIndex i;
       double *pr, *pi;
       double *pr2, *pi2;
       mwIndex *ir, *jc;
       mwIndex *ir2, *jc2;

       if (nrhs != 1 || ! mxIsSparse (prhs[0]))
         mexErrMsgTxt ("expects sparse matrix");

       m = mxGetM (prhs [0]);
       n = mxGetN (prhs [0]);
       nz = mxGetNzmax (prhs [0]);

       if (mxIsComplex (prhs[0]))
         {
           mexPrintf ("Matrix is %d-by-%d complex",
     		 " sparse matrix", m, n);
           mexPrintf (" with %d elements\n", nz);

           pr = mxGetPr (prhs[0]);
           pi = mxGetPi (prhs[0]);
           ir = mxGetIr (prhs[0]);
           jc = mxGetJc (prhs[0]);

           i = n;
           while (jc[i] == jc[i-1] && i != 0) i--;
           mexPrintf ("last non-zero element (%d, %d) =",
     		 ir[nz-1]+ 1, i);
           mexPrintf (" (%g, %g)\n", pr[nz-1], pi[nz-1]);

           v = mxCreateSparse (m, n, nz, mxCOMPLEX);
           pr2 = mxGetPr (v);
           pi2 = mxGetPi (v);
           ir2 = mxGetIr (v);
           jc2 = mxGetJc (v);

           for (i = 0; i < nz; i++)
             {
               pr2[i] = 2 * pr[i];
               pi2[i] = 2 * pi[i];
               ir2[i] = ir[i];
             }
           for (i = 0; i < n + 1; i++)
             jc2[i] = jc[i];

           if (nlhs > 0)
             plhs[0] = v;
         }
       else if (mxIsLogical (prhs[0]))
         {
           bool *pbr, *pbr2;
           mexPrintf ("Matrix is %d-by-%d logical",
     		 " sparse matrix", m, n);
           mexPrintf (" with %d elements\n", nz);

           pbr = mxGetLogicals (prhs[0]);
           ir = mxGetIr (prhs[0]);
           jc = mxGetJc (prhs[0]);

           i = n;
           while (jc[i] == jc[i-1] && i != 0) i--;
           mexPrintf ("last non-zero element (%d, %d) = %d\n",
                      ir[nz-1]+ 1, i, pbr[nz-1]);

           v = mxCreateSparseLogicalMatrix (m, n, nz);
           pbr2 = mxGetLogicals (v);
           ir2 = mxGetIr (v);
           jc2 = mxGetJc (v);

           for (i = 0; i < nz; i++)
             {
               pbr2[i] = pbr[i];
               ir2[i] = ir[i];
             }
           for (i = 0; i < n + 1; i++)
             jc2[i] = jc[i];

           if (nlhs > 0)
             plhs[0] = v;
         }
       else
         {
           mexPrintf ("Matrix is %d-by-%d real",
     		 " sparse matrix", m, n);
           mexPrintf (" with %d elements\n", nz);

           pr = mxGetPr (prhs[0]);
           ir = mxGetIr (prhs[0]);
           jc = mxGetJc (prhs[0]);

           i = n;
           while (jc[i] == jc[i-1] && i != 0) i--;
           mexPrintf ("last non-zero element (%d, %d) = %g\n",
                     ir[nz-1]+ 1, i, pr[nz-1]);

           v = mxCreateSparse (m, n, nz, mxREAL);
           pr2 = mxGetPr (v);
           ir2 = mxGetIr (v);
           jc2 = mxGetJc (v);

           for (i = 0; i < nz; i++)
             {
               pr2[i] = 2 * pr[i];
               ir2[i] = ir[i];
             }
           for (i = 0; i < n + 1; i++)
             jc2[i] = jc[i];

           if (nlhs > 0)
             plhs[0] = v;
         }
     }


File: octave.info,  Node: Calling Other Functions in Mex-Files,  Prev: Sparse Matrices with Mex-Files,  Up: Mex-Files

A.2.7 Calling Other Functions in Mex-Files
------------------------------------------

It is also possible call other Octave functions from within a mex-file
using `mexCallMATLAB'.  An example of the use of `mexCallMATLAB' can be
see in the example below

     #include "mex.h"

     void
     mexFunction (int nlhs, mxArray* plhs[], int nrhs,
     	     const mxArray* prhs[])
     {
       char *str;

       mexPrintf ("Hello, World!\n");

       mexPrintf ("I have %d inputs and %d outputs\n", nrhs,
     	     nlhs);

       if (nrhs < 1 || ! mxIsString (prhs[0]))
         mexErrMsgTxt ("function name expected");

       str = mxArrayToString (prhs[0]);

       mexPrintf ("I'm going to call the function %s\n", str);

       mexCallMATLAB (nlhs, plhs, nrhs-1, prhs+1, str);

       mxFree (str);
     }

   If this code is in the file `myfeval.c', and is compiled to
`myfeval.mex', then an example of its use is

     myfeval("sin", 1)
     a = myfeval("sin", 1)
     => Hello, World!
         I have 2 inputs and 1 outputs
         I'm going to call the interpreter function sin
         a =  0.84147

   Note that it is not possible to use function handles or inline
functions within a mex-file.


File: octave.info,  Node: Standalone Programs,  Prev: Mex-Files,  Up: Dynamically Linked Functions

A.3 Standalone Programs
=======================

The libraries Octave itself uses, can be utilized in standalone
applications.  These applications then have access, for example, to the
array and matrix classes as well as to all the Octave algorithms.  The
following C++ program, uses class Matrix from liboctave.a or
liboctave.so.

     #include <iostream>
     #include <octave/oct.h>

     int
     main (void)
     {
       std::cout << "Hello Octave world!\n";
       int n = 2;
       Matrix a_matrix = Matrix (n, n);
       for (octave_idx_type i = 0; i < n; i++)
         {
           for (octave_idx_type j = 0; j < n; j++)
             {
               a_matrix (i, j) = (i + 1) * 10 + (j + 1);
             }
         }
       std::cout << a_matrix;
       return 0;
     }

mkoctfile can then be used to build a standalone application with a
command like

     $ mkoctfile --link-stand-alone standalone.cc -o standalone
     $ ./standalone
     Hello Octave world!
       11 12
       21 22
     $

   Note that the application `hello' will be dynamically linked against
the octave libraries and any octave support libraries.  The above
allows the Octave math libraries to be used by an application.  It does
not however allow the script files, oct-files or builtin functions of
Octave to be used by the application.  To do that the Octave interpreter
needs to be initialized first.  An example of how to do this can then be
seen in the code

     #include <iostream>
     #include <octave/oct.h>
     #include <octave/octave.h>
     #include <octave/parse.h>

     int
     main (void)
     {
       string_vector argv (2);
       argv(0) = "embedded";
       argv(1) = "-q";

       octave_main (2, argv.c_str_vec(), 1);

       octave_idx_type n = 2;
       Matrix a_matrix = Matrix (1, 2);

       std::cout << "GCD of [";
       for (octave_idx_type i = 0; i < n; i++)
         {
           a_matrix (i) = 5 * (i + 1);
           if (i != 0)
     	std::cout << ", " << 5 * (i + 2);
           else
     	std::cout << 5 * (i + 2);
         }
       std::cout << "] is ";

       octave_value_list in = octave_value (a_matrix);
       octave_value_list out = feval ("gcd", in, 1);

       if (!error_state && out.length () > 0)
         {
           a_matrix = out(0).matrix_value ();
           if (a_matrix.numel () == 1)
     	std::cout << a_matrix(0) << "\n";
           else
     	std::cout << "invalid\n";
         }
       else
         std::cout << "invalid\n";

       return 0;
     }

which is compiled and run as before as a standalone application with

     $ mkoctfile --link-stand-alone embedded.cc -o embedded
     $ ./embedded
     GCD of [10, 15] is 5
     $


File: octave.info,  Node: Test and Demo Functions,  Next: Tips and Standards,  Prev: Dynamically Linked Functions,  Up: Top

Appendix B Test and Demo Functions
**********************************

Octave includes a number of functions to allow the integration of
testing and demonstration code in the source code of the functions
themselves.

* Menu:

* Test Functions::
* Demonstration Functions::


File: octave.info,  Node: Test Functions,  Next: Demonstration Functions,  Up: Test and Demo Functions

B.1 Test Functions
==================

 -- Function File:  test NAME
 -- Function File:  test NAME quiet|normal|verbose
 -- Function File:  test ('NAME', 'quiet|normal|verbose', FID)
 -- Function File:  test ([], 'explain', FID)
 -- Function File: SUCCESS = test (...)
 -- Function File: [N, MAX] = test (...)
 -- Function File: [CODE, IDX] = test ('NAME','grabdemo')
     Perform tests from the first file in the loadpath matching NAME.
     `test' can be called as a command or as a function.  Called with a
     single argument NAME, the tests are run interactively and stop
     after the first error is encountered.

     With a second argument the tests which are performed and the
     amount of output is selected.

    'quiet'
          Don't report all the tests as they happen, just the errors.

    'normal'
          Report all tests as they happen, but don't do tests which
          require user interaction.

    'verbose'
          Do tests which require user interaction.

     The argument FID can be used to allow batch processing.  Errors
     can be written to the already open file defined by FID, and
     hopefully when Octave crashes this file will tell you what was
     happening when it did.  You can use `stdout' if you want to see
     the results as they happen.  You can also give a file name rather
     than an FID, in which case the contents of the file will be
     replaced with the log from the current test.

     Called with a single output argument SUCCESS, `test' returns true
     if all of the tests were successful.  Called with two output
     arguments N and MAX, the number of successful tests and the total
     number of tests in the file NAME are returned.

     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 CODE with IDX being a
     vector of positions of the ends of the demo blocks.

     If the second argument is 'explain', then NAME is ignored and an
     explanation of the line markers used is written to the file FID.

     *See also:* *note error: doc-error, *note assert: doc-assert,
     *note fail: doc-fail, *note demo: doc-demo, *note example:
     doc-example.

   `test' scans the named script file looking for lines which start
with `%!'.  The prefix is stripped off and the rest of the line is
processed through the Octave interpreter.  If the code generates an
error, then the test is said to fail.

   Since `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 `test'
immediately following the `%!'.  For example,

        %!test error ("this test fails!");
        %!test "test doesn't fail. it doesn't generate an error";

   When a test fails, you will see something like:

          ***** test error ('this test fails!')
        !!!!! test failed
        this test fails!

   Generally, to test if something works, you want to assert that it
produces a correct value.  A real test might look something like

        %!test
        %! A = [1, 2, 3; 4, 5, 6]; B = [1; 2];
        %! expect = [ A ; 2*A ];
        %! get = kron (B, A);
        %! if (any(size(expect) != size(get)))
        %!    error ("wrong size: expected %d,%d but got %d,%d",
        %!           size(expect), size(get));
        %! elseif (any(any(expect!=get)))
        %!    error ("didn't get what was expected.");
        %! endif

   To make the process easier, use the `assert' function.  For example,
with `assert' the previous test is reduced to:

        %!test
        %! A = [1, 2, 3; 4, 5, 6]; B = [1; 2];
        %! assert (kron (B, A), [ A; 2*A ]);

   `assert' can accept a tolerance so that you can compare results
absolutely or relatively.  For example, the following all succeed:

        %!test assert (1+eps, 1, 2*eps)          # absolute error
        %!test assert (100+100*eps, 100, -2*eps) # relative error

   You can also do the comparison yourself, but still have assert
generate the error:

        %!test assert (isempty([]))
        %!test assert ([ 1,2; 3,4 ] > 0)

   Because `assert' is so frequently used alone in a test block, there
is a shorthand form:

        %!assert (...)

   which is equivalent to:

        %!test assert (...)

   Sometimes during development there is a test that should work but is
known to fail.  You still want to leave the test in because when the
final code is ready the test should pass, but you may not be able to
fix it immediately.  To avoid unnecessary bug reports for these known
failures, mark the block with `xtest' rather than `test':

        %!xtest assert (1==0)
        %!xtest fail ('success=1','error'))

   Another use of `xtest' is for statistical tests which should pass
most of the time but are known to fail occasionally.

   Each block is evaluated in its own function environment, which means
that variables defined in one block are not automatically shared with
other blocks.  If you do want to share variables, then you must declare
them as `shared' before you use them.  For example, the following
declares the variable A, gives it an initial value (default is empty),
then uses it in several subsequent tests.

        %!shared A
        %! A = [1, 2, 3; 4, 5, 6];
        %!assert (kron ([1; 2], A), [ A; 2*A ]);
        %!assert (kron ([1, 2], A), [ A, 2*A ]);
        %!assert (kron ([1,2; 3,4], A), [ A,2*A; 3*A,4*A ]);

   You can share several variables at the same time:

        %!shared A, B

   You can also share test functions:

        %!function A = fn(B)
        %!  A = 2*B;
        %!assert (A(2),4);

   Note that all previous variables and values are lost when a new
shared block is declared.

   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 `<pattern>'.  For example:

        %!error <passes!> error('this test passes!');

   If the code doesn't generate an error, the test fails.  For example,

        %!error "this is an error because it succeeds.";

   produces

        ***** error "this is an error because it succeeds.";
        !!!!! test failed: no error

   It is important to automate the tests as much as possible, however
some tests require user interaction.  These can be isolated into demo
blocks, which if you are in batch mode, are only run when called with
`demo' or `verbose'.  The code is displayed before it is executed.  For
example,

        %!demo
        %! T=[0:0.01:2*pi]; X=sin(T);
        %! plot(T,X);
        %! you should now see a sine wave in your figure window

   produces

        > T=[0:0.01:2*pi]; X=sin(T);
        > plot(T,X);
        > you should now see a sine wave in your figure window
        Press <enter> to continue:

   Note that demo blocks cannot use any shared variables.  This is so
that they can be executed by themselves, ignoring all other tests.

   If you want to temporarily disable a test block, put `#' in place of
the block type.  This creates a comment block which is echoed in the
log file, but is not executed.  For example:

        %!#demo
        %! T=[0:0.01:2*pi]; X=sin(T);
        %! plot(T,X);
        %! you should now see a sine wave in your figure window

   Block type summary:

`%!test'
     check that entire block is correct

`%!error'
     check for correct error message

`%!warning'
     check for correct warning message

`%!demo'
     demo only executes in interactive mode

`%!#'
     comment: ignore everything within the block

`%!shared x,y,z'
     declares variables for use in multiple tests

`%!function'
     defines a function value for a shared variable

`%!assert (x, y, tol)'
     shorthand for %!test assert (x, y, tol)

   You can also create test scripts for builtins and your own C++
functions.  Just put a file of the function name on your path without
any extension and it will be picked up by the test procedure.  You can
even embed tests directly in your C++ code:

        #if 0
        %!test disp('this is a test')
        #endif

   or

        /*
        %!test disp('this is a test')
        */

   but then the code will have to be on the load path and the user will
have to remember to type test('name.cc').  Conversely, you can separate
the tests from normal Octave script files by putting them in plain
files with no extension rather than in script files.

 -- Function File:  assert (COND)
 -- Function File:  assert (COND, ERRMSG, ...)
 -- Function File:  assert (COND, MSG_ID, ERRMSG, ...)
 -- Function File:  assert (OBSERVED,EXPECTED)
 -- Function File:  assert (OBSERVED,EXPECTED,TOL)
     Produces an error if the condition is not met.  `assert' can be
     called in three different ways.

    `assert (COND)'
    `assert (COND, ERRMSG, ...)'
    `assert (COND, MSG_ID, ERRMSG, ...)'
          Called with a single argument COND, `assert' produces an
          error if COND is zero.  If called with a single argument a
          generic error message.  With more than one argument, the
          additional arguments are passed to the `error' function.

    `assert (OBSERVED, EXPECTED)'
          Produce an error if observed is not the same as expected.
          Note that observed and expected can be strings, scalars,
          vectors, matrices, lists or structures.

    `assert(OBSERVED, EXPECTED, TOL)'
          Accept a tolerance when comparing numbers.  If TOL is
          positive use it as an absolute tolerance, will produce an
          error if `abs(OBSERVED - EXPECTED) > abs(TOL)'.  If TOL is
          negative use it as a relative tolerance, will produce an
          error if `abs(OBSERVED - EXPECTED) > abs(TOL * EXPECTED)'.
          If EXPECTED is zero TOL will always be used as an absolute
          tolerance.

     *See also:* *note test: doc-test.

 -- Function File:  fail (CODE,PATTERN)
 -- Function File:  fail (CODE,'warning',PATTERN)
     Return true if CODE fails with an error message matching PATTERN,
     otherwise produce an error.  Note that CODE is a string and if
     CODE runs successfully, the error produced is:

                    expected error but got none

     If the code fails with a different error, the message produced is:

                    expected <pattern>
                    but got <text of actual error>

     The angle brackets are not part of the output.

     Called with three arguments, the behavior is similar to
     `fail(CODE, PATTERN)', but produces an error if no warning is
     given during code execution or if the code fails.



File: octave.info,  Node: Demonstration Functions,  Prev: Test Functions,  Up: Test and Demo Functions

B.2 Demonstration Functions
===========================

 -- Function File:  demo ('NAME',N)
     Runs any examples associated with the function 'NAME'.  Examples
     are stored in the script file, or in a file with the same name but
     no extension somewhere on your path.  To keep them separate from
     the usual script code, all lines are prefixed by `%!'.  Each
     example is introduced by the keyword 'demo' flush left to the
     prefix, with no intervening spaces.  The remainder of the example
     can contain arbitrary Octave code.  For example:

             %!demo
             %! t=0:0.01:2*pi; x = sin(t);
             %! plot(t,x)
             %! %-------------------------------------------------
             %! % the figure window shows one cycle of a sine wave

     Note that the code is displayed before it is executed, so a simple
     comment at the end suffices.  It is generally not necessary to use
     disp or printf within the demo.

     Demos are run in a function environment with no access to external
     variables.  This means that all demos in your function must use
     separate initialization code.  Alternatively, you can combine your
     demos into one huge demo, with the code:

             %! input("Press <enter> to continue: ","s");

     between the sections, but this is discouraged.  Other techniques
     include using multiple plots by saying figure between each, or
     using subplot to put multiple plots in the same window.

     Also, since demo evaluates inside a function context, you cannot
     define new functions inside a demo.  Instead you will have to use
     `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,

            %!demo if 1
            %!  function y=f(x)
            %!    y=x;
            %!  endfunction
            %!  f(3)
            %! endif

     *See also:* *note test: doc-test, *note example: doc-example.

 -- Function File:  rundemos (DIRECTORY)

 -- Function File:  example ('NAME',N)
 -- Function File: [X, IDX] = example ('NAME',N)
     Display the code for example N associated with the function
     'NAME', but do not run it.  If N is not given, all examples are
     displayed.

     Called with output arguments, the examples are returned in the
     form of a string X, with IDX indicating the ending position of the
     various examples.

     See `demo' for a complete explanation.

     *See also:* *note demo: doc-demo, *note test: doc-test.

 -- Function File:  speed (F, INIT, MAX_N, F2, TOL)
 -- Function File: [ORDER, N, T_F, T_F2] = speed (...)
     Determine the execution time of an expression for various N.  The
     N are log-spaced from 1 to MAX_N.  For each N, an initialization
     expression is computed to create whatever data are needed for the
     test.  If a second expression is given, the execution times of the
     two expressions will be compared.  Called without output arguments
     the results are presented graphically.

    `F'
          The expression to evaluate.

    `MAX_N'
          The maximum test length to run.  Default value is 100.
          Alternatively, use `[min_n,max_n]' or for complete control,
          `[n1,n2,...,nk]'.

    `INIT'
          Initialization expression for function argument values.  Use K
          for the test number and N for the size of the test.  This
          should compute values for all variables listed in args.  Note
          that init will be evaluated first for k = 0, so things which
          are constant throughout the test can be computed then.  The
          default value is `X = randn (N, 1);'.

    `F2'
          An alternative expression to evaluate, so the speed of the two
          can be compared.  Default is `[]'.

    `TOL'
          If TOL is `Inf', then no comparison will be made between the
          results of expression F and expression F2.  Otherwise,
          expression F should produce a value V and expression F2
          should produce a value V2, and these shall be compared using
          `assert(V,V2,TOL)'.  If TOL is positive, the tolerance is
          assumed to be absolute.  If TOL is negative, the tolerance is
          assumed to be relative.  The default is `eps'.

    `ORDER'
          The time complexity of the expression `O(a n^p)'.  This is a
          structure with fields `a' and `p'.

    `N'
          The values N for which the expression was calculated and the
          execution time was greater than zero.

    `T_F'
          The nonzero execution times recorded for the expression F in
          seconds.

    `T_F2'
          The nonzero execution times recorded for the expression F2 in
          seconds.  If it is needed, the mean time ratio is just
          `mean(T_f./T_f2)'.


     The slope of the execution time graph shows the approximate power
     of the asymptotic running time `O(n^p)'.  This power is plotted
     for the region over which it is approximated (the latter half of
     the graph).  The estimated power is not very accurate, but should
     be sufficient to determine the general order of your algorithm.
     It should indicate if for example your implementation is
     unexpectedly `O(n^2)' rather than `O(n)' because it extends a
     vector each time through the loop rather than preallocating one
     which is big enough.  For example, in the current version of
     Octave, the following is not the expected `O(n)':

          speed ("for i = 1:n, y{i} = x(i); end", "", [1000,10000])

     but it is if you preallocate the cell array `y':

          speed ("for i = 1:n, y{i} = x(i); end", ...
                 "x = rand (n, 1); y = cell (size (x));", [1000, 10000])

     An attempt is made to approximate the cost of the individual
     operations, but it is wildly inaccurate.  You can improve the
     stability somewhat by doing more work for each `n'.  For example:

          speed ("airy(x)", "x = rand (n, 10)", [10000, 100000])

     When comparing a new and original expression, the line on the
     speedup ratio graph should be larger than 1 if the new expression
     is faster.  Better algorithms have a shallow slope.  Generally,
     vectorizing an algorithm will not change the slope of the execution
     time graph, but it will shift it relative to the original.  For
     example:

          speed ("v = sum (x)", "", [10000, 100000], ...
                 "v = 0; for i = 1:length (x), v += x(i); end")

     A more complex example, if you had an original version of `xcorr'
     using for loops and another version using an FFT, you could
     compare the run speed for various lags as follows, or for a fixed
     lag with varying vector lengths as follows:

          speed ("v = xcorr (x, n)", "x = rand (128, 1);", 100,
                 "v2 = xcorr_orig (x, n)", -100*eps)
          speed ("v = xcorr (x, 15)", "x = rand (20+n, 1);", 100,
                 "v2 = xcorr_orig (x, n)", -100*eps)

     Assuming one of the two versions is in XCORR_ORIG, this would
     compare their speed and their output values.  Note that the FFT
     version is not exact, so we specify an acceptable tolerance on the
     comparison `100*eps', and the errors should be computed
     relatively, as `abs((X - Y)./Y)' rather than absolutely as `abs(X
     - Y)'.

     Type `example('speed')' to see some real examples.  Note for
     obscure reasons, you can't run examples 1 and 2 directly using
     `demo('speed')'.  Instead use, `eval(example('speed',1))' and
     `eval(example('speed',2))'.


File: octave.info,  Node: Tips and Standards,  Next: Contributing Guidelines,  Prev: Test and Demo Functions,  Up: Top

Appendix C Tips and Standards
*****************************

This chapter describes no additional features of Octave.  Instead it
gives advice on making effective use of the features described in the
previous chapters.

* Menu:

* Style Tips::                  Writing clean and robust programs.
* Coding Tips::                 Making code run faster.
* Comment Tips::                Conventions for writing comments.
* Function Headers::            Standard headers for functions.
* Documentation Tips::          Writing readable documentation strings.


File: octave.info,  Node: Style Tips,  Next: Coding Tips,  Up: Tips and Standards

C.1 Writing Clean Octave Programs
=================================

Here are some tips for avoiding common errors in writing Octave code
intended for widespread use:

   * Since all global variables share the same name space, and all
     functions share another name space, you should choose a short word
     to distinguish your program from other Octave programs.  Then take
     care to begin the names of all global variables, constants, and
     functions with the chosen prefix.  This helps avoid name conflicts.

     If you write a function that you think ought to be added to Octave
     under a certain name, such as `fiddle_matrix', don't call it by
     that name in your program.  Call it `mylib_fiddle_matrix' in your
     program, and send mail to <maintainers@octave.org> suggesting that
     it be added to Octave.  If and when it is, the name can be changed
     easily enough.

     If one prefix is insufficient, your package may use two or three
     alternative common prefixes, so long as they make sense.

     Separate the prefix from the rest of the symbol name with an
     underscore `_'.  This will be consistent with Octave itself and
     with most Octave programs.

   * When you encounter an error condition, call the function `error'
     (or `usage').  The `error' and `usage' functions do not return.
     *Note Errors::.

   * Please put a copyright notice on the file if you give copies to
     anyone.  Use the same lines that appear at the top of the function
     files distributed with Octave.  If you have not signed papers to
     assign the copyright to anyone else, then place your name in the
     copyright notice.


File: octave.info,  Node: Coding Tips,  Next: Comment Tips,  Prev: Style Tips,  Up: Tips and Standards

C.2 Tips for Making Code Run Faster.
====================================

Here are some ways of improving the execution speed of Octave programs.

   * Vectorize loops. For instance, rather than
          for i = 1:n-1
            a(i) = b(i+1) - b(i);
          endfor

     write

          a = b(2:n) - b(1:n-1);

     This is especially important for loops with "cheap" bodies. Often
     it suffices to vectorize just the innermost loop to get acceptable
     performance. A general rule of thumb is that the "order" of the
     vectorized body should be greater or equal to the "order" of the
     enclosing loop.

   * Use built-in and library functions if possible. Built-in and
     compiled functions are very fast.  Even with a m-file library
     function, chances are good that it is already optimized, or will be
     optimized more in a future release.

   * Avoid computing costly intermediate results multiple times. Octave
     currently does not eliminate common subexpressions.

   * Be aware of lazy copies (copy-on-write). When a copy of an object
     is created, the data is not immediately copied, but rather shared.
     The actual copying is postponed until the copied data needs to be
     modified. For example:

          a = zeros (1000); # create a 1000x1000 matrix
          b = a; # no copying done here
          b(1) = 1; # copying done here

     Lazy copying applies to whole Octave objects such as matrices,
     cells, struct, and also individual cell or struct elements (not
     array elements).

     Additionally, index expressions also use lazy copying when Octave
     can determine that the indexed portion is contiguous in memory.
     For example:

          a = zeros (1000); # create a 1000x1000 matrix
          b = a(:,10:100); # no copying done here
          b = a(10:100,:); # copying done here

     This applies to arrays (matrices), cell arrays, and structs
     indexed using ().  Index expressions generating cs-lists can also
     benefit of shallow copying in some cases. In particular, when A is
     a struct array, expressions like `{a.x}, {a(:,2).x}' will use lazy
     copying, so that data can be shared between a struct array and a
     cell array.

     Most indexing expressions do not live longer than their `parent'
     objects.  In rare cases, however, a lazily copied slice outlasts
     its parent, in which case it becomes orphaned, still occupying
     unnecessarily more memory than needed.  To provide a remedy
     working in most real cases, Octave checks for orphaned lazy slices
     at certain situations, when a value is stored into a "permanent"
     location, such as a named variable or cell or struct element, and
     possibly economizes them. For example

          a = zeros (1000); # create a 1000x1000 matrix
          b = a(:,10:100); # lazy slice
          a = []; # the original a array is still allocated
          c{1} = b; # b is reallocated at this point

   * Avoid deep recursion. Function calls to m-file functions carry a
     relatively significant overhead, so rewriting a recursion as a
     loop often helps. Also, note that the maximum level of recursion is
     limited.

   * Avoid resizing matrices unnecessarily. When building a single
     result matrix from a series of calculations, set the size of the
     result matrix first, then insert values into it.  Write

          result = zeros (big_n, big_m)
          for i = over:and_over
            r1 = ...
            r2 = ...
            result (r1, r2) = new_value ();
          endfor

     instead of

          result = [];
          for i = ever:and_ever
            result = [ result, new_value() ];
          endfor

     Sometimes the number of items can't be computed in advance, and
     stack-like operations are needed. When elements are being
     repeatedly inserted at/removed from the end of an array, Octave
     detects it as stack usage and attempts to use a smarter memory
     management strategy preallocating the array in bigger chunks.
     Likewise works for cell and struct arrays.

          a = [];
          while (condition)
            ...
            a(end+1) = value; # "push" operation
            ...
            a(end) = []; # "pop" operation
            ...
          endwhile

   * Use `cellfun' intelligently. The `cellfun' function is a useful
     tool for avoiding loops. *Note Processing Data in Cell Arrays::.
     `cellfun' is often use with anonymous function handles; however,
     calling an anonymous function involves an overhead quite
     comparable to the overhead of an m-file function. Passing a handle
     to a built-in function is faster, because the interpreter is not
     involved in the internal loop. For example:

          a = {...}
          v = cellfun (@(x) det(x), a); # compute determinants
          v = cellfun (@det, a); # faster

   * Avoid calling `eval' or `feval' excessively, because they require
     Octave to parse input or look up the name of a function in the
     symbol table.

     If you are using `eval' as an exception handling mechanism and not
     because you need to execute some arbitrary text, use the `try'
     statement instead.  *Note The `try' Statement::.

   * If you are calling lots of functions but none of them will need to
     change during your run, set the variable
     `ignore_function_time_stamp' to `"all"' so that Octave doesn't
     waste a lot of time checking to see if you have updated your
     function files.


File: octave.info,  Node: Comment Tips,  Next: Function Headers,  Prev: Coding Tips,  Up: Tips and Standards

C.3 Tips on Writing Comments
============================

Here are the conventions to follow when writing comments.

`#'
     Comments that start with a single sharp-sign, `#', should all be
     aligned to the same column on the right of the source code.  Such
     comments usually explain how the code on the same line does its
     job.  In the Emacs mode for Octave, the `M-;'
     (`indent-for-comment') command automatically inserts such a `#' in
     the right place, or aligns such a comment if it is already present.

`##'
     Comments that start with a double sharp-sign, `##', should be
     aligned to the same level of indentation as the code.  Such
     comments usually describe the purpose of the following lines or
     the state of the program at that point.

The indentation commands of the Octave mode in Emacs, such as `M-;'
(`indent-for-comment') and `TAB' (`octave-indent-line') automatically
indent comments according to these conventions, depending on the number
of semicolons.  *Note Manipulating Comments: (emacs)Comments.


File: octave.info,  Node: Function Headers,  Next: Documentation Tips,  Prev: Comment Tips,  Up: Tips and Standards

C.4 Conventional Headers for Octave Functions
=============================================

Octave has conventions for using special comments in function files to
give information such as who wrote them.  This section explains these
conventions.

   The top of the file should contain a copyright notice, followed by a
block of comments that can be used as the help text for the function.
Here is an example:

     ## Copyright (C) 1996, 1997, 2007 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/>.

     ## usage: [IN, OUT, PID] = popen2 (COMMAND, ARGS)
     ##
     ## Start a subprocess with two-way communication.  COMMAND
     ## specifies the name of the command to start.  ARGS is an
     ## array of strings containing options for COMMAND.  IN and
     ## OUT are the file ids of the input and streams for the
     ## subprocess, and PID is the process id of the subprocess,
     ## or -1 if COMMAND could not be executed.
     ##
     ## Example:
     ##
     ##  [in, out, pid] = popen2 ("sort", "-nr");
     ##  fputs (in, "these\nare\nsome\nstrings\n");
     ##  fclose (in);
     ##  while (ischar (s = fgets (out)))
     ##    fputs (stdout, s);
     ##  endwhile
     ##  fclose (out);

   Octave uses the first block of comments in a function file that do
not appear to be a copyright notice as the help text for the file.  For
Octave to recognize the first comment block as a copyright notice, it
must start with the word `Copyright' after stripping the leading
comment characters.

   After the copyright notice and help text come several "header
comment" lines, each beginning with `## HEADER-NAME:'.  For example,

     ## Author: jwe
     ## Keywords: subprocesses input-output
     ## Maintainer: jwe

   Here is a table of the conventional possibilities for HEADER-NAME:

`Author'
     This line states the name and net address of at least the principal
     author of the library.

          ## Author: John W. Eaton <jwe@octave.org>

`Maintainer'
     This line should contain a single name/address as in the Author
     line, or an address only, or the string `jwe'.  If there is no
     maintainer line, the person(s) in the Author field are presumed to
     be the maintainers.  The example above is mildly bogus because the
     maintainer line is redundant.

     The idea behind the `Author' and `Maintainer' lines is to make
     possible a function to "send mail to the maintainer" without
     having to mine the name out by hand.

     Be sure to surround the network address with `<...>' if you
     include the person's full name as well as the network address.

`Created'
     This optional line gives the original creation date of the file.
     For historical interest only.

`Version'
     If you wish to record version numbers for the individual Octave
     program, put them in this line.

`Adapted-By'
     In this header line, place the name of the person who adapted the
     library for installation (to make it fit the style conventions, for
     example).

`Keywords'
     This line lists keywords.  Eventually, it will be used by an
     apropos command to allow people will find your package when
     they're looking for things by topic area.  To separate the
     keywords, you can use spaces, commas, or both.

   Just about every Octave function ought to have the `Author' and
`Keywords' header comment lines.  Use the others if they are
appropriate.  You can also put in header lines with other header
names--they have no standard meanings, so they can't do any harm.


File: octave.info,  Node: Documentation Tips,  Prev: Function Headers,  Up: Tips and Standards

C.5 Tips for Documentation Strings
==================================

As noted above, documentation is typically in a commented header block
on an Octave function following the copyright statement.  The help
string shown above is an unformatted string and will be displayed as is
by Octave.  Here are some tips for the writing of documentation strings.

   * Every command, function, or variable intended for users to know
     about should have a documentation string.

   * An internal variable or subroutine of an Octave program might as
     well have a documentation string.

   * The first line of the documentation string should consist of one
     or two complete sentences that stand on their own as a summary.

     The documentation string can have additional lines that expand on
     the details of how to use the function or variable.  The
     additional lines should also be made up of complete sentences.

   * For consistency, phrase the verb in the first sentence of a
     documentation string as an infinitive with "to" omitted.  For
     instance, use "Return the frob of A and B." in preference to
     "Returns the frob of A and B."  Usually it looks good to do
     likewise for the rest of the first paragraph.  Subsequent
     paragraphs usually look better if they have proper subjects.

   * Write documentation strings in the active voice, not the passive,
     and in the present tense, not the future.  For instance, use
     "Return a list containing A and B." instead of "A list containing
     A and B will be returned."

   * Avoid using the word "cause" (or its equivalents) unnecessarily.
     Instead of, "Cause Octave to display text in boldface," write just
     "Display text in boldface."

   * Do not start or end a documentation string with whitespace.

   * Format the documentation string so that it fits in an Emacs window
     on an 80-column screen.  It is a good idea for most lines to be no
     wider than 60 characters.

     However, rather than simply filling the entire documentation
     string, you can make it much more readable by choosing line breaks
     with care.  Use blank lines between topics if the documentation
     string is long.

   * *Do not* indent subsequent lines of a documentation string so that
     the text is lined up in the source code with the text of the first
     line.  This looks nice in the source code, but looks bizarre when
     users view the documentation.  Remember that the indentation
     before the starting double-quote is not part of the string!

   * The documentation string for a variable that is a yes-or-no flag
     should start with words such as "Nonzero means...", to make it
     clear that all nonzero values are equivalent and indicate
     explicitly what zero and nonzero mean.

   * When a function's documentation string mentions the value of an
     argument of the function, use the argument name in capital letters
     as if it were a name for that value.  Thus, the documentation
     string of the operator `/' refers to its second argument as
     `DIVISOR', because the actual argument name is `divisor'.

     Also use all caps for meta-syntactic variables, such as when you
     show the decomposition of a list or vector into subunits, some of
     which may vary.

   Octave also allows extensive formatting of the help string of
functions using Texinfo.  The effect on the online documentation is
relatively small, but makes the help string of functions conform to the
help of Octave's own functions.  However, the effect on the appearance
of printed or online documentation will be greatly improved.

   The fundamental building block of Texinfo documentation strings is
the Texinfo-macro `@deftypefn', which takes three arguments: The class
the function is in, its output arguments, and the function's signature.
Typical classes for functions include `Function File' for standard
Octave functions, and `Loadable Function' for dynamically linked
functions.  A skeletal Texinfo documentation string therefore looks
like this

     -*- texinfo -*-
     @deftypefn{Function File} {@var{ret} =} fn (...)
     @cindex index term
     Help text in Texinfo format.  Code samples should be marked
     like @code{sample of code} and variables should be marked
     as @var{variable}.
     @seealso{fn2}
     @end deftypefn

   This help string must be commented in user functions, or in the help
string of the `DEFUN_DLD' macro for dynamically loadable functions.
The important aspects of the documentation string are

-*- texinfo -*-
     This string signals Octave that the following text is in Texinfo
     format, and should be the first part of any help string in Texinfo
     format.

@deftypefn{class} ... @end deftypefn
     The entire help string should be enclosed within the block defined
     by deftypefn.

@cindex index term
     This generates an index entry, and can be useful when the function
     is included as part of a larger piece of documentation.  It is
     ignored within Octave's help viewer.  Only one index term may
     appear per line but multiple @cindex lines are valid if the
     function should be filed under different terms.

@var{variable}
     All variables should be marked with this macro.  The markup of
     variables is then changed appropriately for display.

@code{sample of code}
     All samples of code should be marked with this macro for the same
     reasons as the @var macro.

@seealso{function2}
     This is a comma separated list of function names that allows cross
     referencing from one function documentation string to another.

   Texinfo format has been designed to generate output for online
viewing with text terminals as well as generating high-quality printed
output.  To these ends, Texinfo has commands which control the
diversion of parts of the document into a particular output processor.
Three formats are of importance: info, html and TeX.  These are
selected with

     @ifinfo
     Text area for info only
     @end ifinfo

     @ifhtml
     Text area for HTML only
     @end ifhtml

     @tex
     Text area for TeX only
     @end tex

   Note that often TeX output can be used in html documents and so often
the `@ifhtml' blocks are unnecessary.  If no specific output processor
is chosen, by default, the text goes into all output processors.  It is
usual to have the above blocks in pairs to allow the same information
to be conveyed in all output formats, but with a different markup.
Currently, most Octave documentation only makes a distinction between
TeX and all other formats.  Therefore, the following construct is seen
repeatedly.

     @tex
     text for TeX only
     @end tex
     @ifnottex
     text for info, HTML, plaintext
     @end ifnottex

   Another important feature of Texinfo that is often used in Octave
help strings is the `@example' environment.  An example of its use is

     @example
     @group
     @code{2 * 2}
     @result{} 4
     @end group
     @end example

   which produces

     `2 * 2'
     => 4

   The `@group' block prevents the example from being split across a
page boundary, while the `@result{}' macro produces a right arrow
signifying the result of a command.  If your example is larger than 20
lines it is better NOT to use grouping so that a reasonable page
boundary can be calculated.

   In many cases a function has multiple ways in which it can be called,
and the `@deftypefnx' macro can be used to give alternatives.  For
example

     -*- texinfo -*-
     @deftypefn{Function File} {@var{a} =} fn (@var{x}, ...)
     @deftypefnx{Function File} {@var{a} =} fn (@var{y}, ...)
     Help text in Texinfo format.
     @end deftypefn

   Many complete examples of Texinfo documentation can be taken from the
help strings for the Octave functions themselves.  A relatively complete
example of which is the `nchoosek' function.  The Texinfo documentation
string for `nchoosek' is

     -*- texinfo -*-
     @deftypefn {Function File} {} nchoosek (@var{n}, @var{k})

     Compute the binomial coefficient or all combinations of
     @var{n}.  If @var{n} is a scalar then, calculate the
     binomial coefficient of @var{n} and @var{k}, defined as

     @tex
     $$
      {n \choose k} = {n (n-1) (n-2) \cdots (n-k+1) \over k!}
     $$
     @end tex
     @ifnottex

     @example
     @group
      /   \
      | n |    n (n-1) (n-2) ... (n-k+1)
      |   |  = -------------------------
      | k |               k!
      \   /
     @end group
     @end example
     @end ifnottex

     If @var{n} is a vector, this generates all combinations
     of the elements of @var{n}, taken @var{k} at a time,
     one row per combination.  The resulting @var{c} has size
     @code{[nchoosek (length (@var{n}),@var{k}), @var{k}]}.

     @code{nchoosek} works only for non-negative integer arguments; use
     @code{bincoeff} for non-integer scalar arguments and for using vector
     arguments to compute many coefficients at once.

     @seealso{bincoeff}
     @end deftypefn

   which demonstrates most of the concepts discussed above.


File: octave.info,  Node: Contributing Guidelines,  Next: Trouble,  Prev: Tips and Standards,  Up: Top

Appendix D Contributing Guidelines
**********************************

This chapter is dedicated to those who wish to contribute code to
Octave.

* Menu:

* How to Contribute::
* General Guidelines::
* Octave Sources (m-files)::
* C++ Sources::
* Other Sources::


File: octave.info,  Node: How to Contribute,  Next: General Guidelines,  Up: Contributing Guidelines

D.1 How to Contribute
=====================

The mailing list for Octave development discussion and sending
contributions is <maintainers@octave.org>.  This concerns the
development of Octave core, i.e., code that goes to Octave directly.
You may consider developing and publishing a package instead; a great
place for this is the allied Octave-Forge project
(`http://octave.sf.net').  Note that the Octave project is inherently
more conservative and follows narrower rules.

   The preferable form of contribution is creating a Mercurial
changeset and sending it via e-mail to the octave-maintainers mailing
list.  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 make more contributions, you should really get familiar
with Mercurial.  A good place to start is
`http://www.selenic.com/mercurial/wiki/index.cgi/Tutorial'.  There you
will also find help how to install Mercurial.

   A simple contribution sequence could look like this:
     hg clone http://www.octave.org/hg/octave
                                  # make a local copy of the octave
                                  # source repository
     cd octave
     # change some sources...
     hg commit -m "make Octave the coolest software ever"
                                  # commit the changeset into your
                                  # local repository
     hg export -o ../cool.diff tip
                                  # export the changeset to a diff
                                  # file
     # send ../cool.diff via email

   You may want to get familiar with Mercurial queues to manage your
changesets.  Here is a slightly less simple example using Mercurial
queues, where you work on two unrelated changesets in parallel and
update one of the changesets after discussion in the maintainers
mailing list:
     hg qnew nasty_bug            # create a new patch
     # change sources...
     hg qref                      # save the changes into the patch
     # change even more...
     hg qref -m "solution to nasty bug!"
                                  # save again with commit message
     hg export -o ../nasty.diff tip
                                  # export the patch
     # send ../nasty.diff via email
     hg qpop                      # undo the application of the patch
                                  # and remove the changes from the
                                  # source tree
     hg qnew doc_improvements     # create an unrelated patch
     # change doc sources...
     hg qref -m "could not find myfav.m in the doc"
                                  # save the changes into the patch
     hg export -o ../doc.diff tip
                                  # export the second patch
     # send ../doc.diff tip via email
     hg qpop
     # discussion in the maintainers mailing list ...
     hg qpush nasty_bug           # apply the patch again
     # change sources yet again ...
     hg qref
     hg export -o ../nasty2.diff tip
     # send ../nasty2.diff via email


File: octave.info,  Node: General Guidelines,  Next: Octave Sources (m-files),  Prev: How to Contribute,  Up: Contributing Guidelines

D.2 General Guidelines
======================

All Octave's sources are distributed under the General Public License
(GPL).  Currently, Octave uses GPL version 3.  For details about this
license, see `http://www.gnu.org/licenses/gpl.html'.  Therefore,
whenever you create a new source file, it should have the following
comment header (use appropriate year, name and comment marks):

     ## Copyright (C) 1996, 1997, 2007 John W. Eaton <jwe@octave.org>
     ##
     ## 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/>.

   Always include ChangeLog entries in changesets.  After making your
source changes, record and briefly describe the changes in the nearest
ChangeLog file upwards in the directory tree.  Use the previous entries
as a template.  Your entry should contain your name and email, and the
path to the modified source file relative to the parent directory of
the ChangeLog file.  If there are more functions in the file, you
should also include the name of the modified function (in parentheses
after file path).  Example:

     2008-04-02  David Bateman  <dbateman@free.fr>

             * graphics.cc (void gnuplot_backend::close_figure (const
             octave_value&) const): Allow for an input and output stream.

The ChangeLog entries should describe what is changed, not why.  Any
explanation of why a change is needed should appear as comments in the
code, particularly if there is something that might not be obvious to
someone reading it later.

   The preferred comment mark for places that may need further
attention is FIXME.


File: octave.info,  Node: Octave Sources (m-files),  Next: C++ Sources,  Prev: General Guidelines,  Up: Contributing Guidelines

D.3 Octave Sources (m-files)
============================

Don't use tabs.  Tabs cause trouble.  If you are used to them, set up
your editor so that it converts tabs to spaces.  Indent the bodies of
the statement blocks.  Recommended indent is 2 spaces.  When calling
functions, put spaces after commas and before the calling parentheses,
like this:

       x = max (sin (y+3), 2);

An exception are matrix and vector constructors:

       [sin(x), cos(x)]

Here, putting spaces after `sin', `cos' would result in a parse error.
In indexing expression, do not put a space after the identifier (this
differentiates indexing and function calls nicely).  The space after
comma is not necessary if index expressions are simple, i.e., you may
write
       A(:,i,j)

but

       A([1:i-1;i+1:n], XI(:,2:n-1))

   Use lowercase names if possible.  Uppercase is acceptable for
variable names consisting of 1-2 letters.  Do not use mixed case names.
Function names must be lowercase.  Function names are global, so choose
them wisely.

   Always use a specific end-of-block statement (like `endif',
`endswitch') rather than generic `end'.  Enclose the `if', `while',
`until' and `switch' conditions in parentheses, like in C:

     if (isvector (a))
       s = sum(a);
     endif

Do not do this, however, with `for':

     for i = 1:n
       b(i) = sum (a(:,i));
     endfor


File: octave.info,  Node: C++ Sources,  Next: Other Sources,  Prev: Octave Sources (m-files),  Up: Contributing Guidelines

D.4 C++ Sources
===============

Don't use tabs.  Tabs cause trouble.  If you are used to them, set up
your editor so that it converts tabs to spaces.  Format function
headers like this:

     static bool
     matches_patterns (const string_vector& patterns, int pat_idx,
     		  int num_pat, const std::string& name)

The function name should start in column 1, and multi-line argument
lists should be aligned on the first char after the open parenthesis.
You should put a space after the left open parenthesis and after
commas, for both function definitions and function calls.

   Recommended indent is 2 spaces.  When indenting, indent the
statement after control structures (like `if', `while', etc.). If there
is a compound statement, indent both the curly braces and the body of
the statement (so that the body gets indented by two indents).  Example:

     if (have_args)
       {
         idx.push_back (first_args);
         have_args = false;
       }
     else
       idx.push_back (make_value_list (*p_args, *p_arg_nm, &tmp));

If you have nested `if' statements, use extra braces for extra
clarification.

   Split long expressions in such a way that a continuation line starts
with an operator rather than identifier.  If the split occurs inside
braces, continuation should be aligned with the first char after the
innermost braces enclosing the split.  Example:

     SVD::type type = ((nargout == 0 || nargout == 1)
                       ? SVD::sigma_only
                       : (nargin == 2) ? SVD::economy : SVD::std);

Consider putting extra braces around a multiline expression to make it
more readable, even if they are not necessary.  Also, do not hesitate
to put extra braces anywhere if it improves clarity.

   Try declaring variables just before they're needed.  Use local
variables of blocks - it helps optimization.  Don't write multi-line
variable declaration with a single type specification and multiple
variables.  If the variables don't fit on single line, repeat the type
specification.  Example:

     octave_value retval;

     octave_idx_type nr = b.rows ();
     octave_idx_type nc = b.cols ();

     double d1, d2;

   Use lowercase names if possible.  Uppercase is acceptable for
variable names consisting of 1-2 letters.  Do not use mixed case names.

   Try to use Octave's types and classes if possible.  Otherwise, try
to use C++ standard library.  Use of STL containers and algorithms is
encouraged.  Use templates wisely to reduce code duplication.  Avoid
comma expressions, labels and gotos, and explicit typecasts.  If you
need to typecast, use the modern C++ casting operators.  In functions,
try to reduce the number of `return' statements - use nested `if'
statements if possible.


File: octave.info,  Node: Other Sources,  Prev: C++ Sources,  Up: Contributing Guidelines

D.5 Other Sources
=================

Apart from C++ and Octave language (m-files), Octave's sources include
files written in C, Fortran, M4, perl, unix shell, AWK, texinfo and
TeX.  There are not many rules to follow when using these other
languages; some of them are summarized below.  In any case, the golden
rule is: if you modify a source file, try to follow any conventions you
can detect in the file or other similar files.

   For C you should obviously follow all C++ rules that can apply.

   If you happen to modify a Fortran file, you should stay within
Fortran 77 with common extensions like `END DO'.  Currently, we want
all sources to be compilable with the f2c and g77 compilers, without
special flags if possible.  This usually means that non-legacy
compilers also accept the sources.

   The M4 macro language is mainly used for autoconf configuration
files.  You should follow normal M4 rules when contributing to these
files.  Some M4 files come from external source, namely the Autoconf
archive `http://autoconf-archive.cryp.to'.

   If you give a code example in the documentation written in texinfo
with the `@example' environment, you should be aware that the text
within such an environment will not be wrapped.  It is recommended that
you keep the lines short enough to fit on pages in the generated pdf or
ps documents.  Here is a ruler (in an `@example' environment) for
finding the appropriate line width:

              1         2         3         4         5         6
     123456789012345678901234567890123456789012345678901234567890


File: octave.info,  Node: Trouble,  Next: Installation,  Prev: Contributing Guidelines,  Up: Top

Appendix E Known Causes of Trouble
**********************************

   This section describes known problems that affect users of Octave.
Most of these are not Octave bugs per se--if they were, we would fix
them.  But the result for a user may be like the result of a bug.

   Some of these problems are due to bugs in other software, some are
missing features that are too much work to add, and some are places
where people's opinions differ as to what is best.

* Menu:

* Actual Bugs::                 Bugs we will fix later.
* Reporting Bugs::
* Bug Criteria::
* Bug Lists::
* Bug Reporting::
* Sending Patches::
* Service::


File: octave.info,  Node: Actual Bugs,  Next: Reporting Bugs,  Up: Trouble

E.1 Actual Bugs We Haven't Fixed Yet
====================================

   * Output that comes directly from Fortran functions is not sent
     through the pager and may appear out of sequence with other output
     that is sent through the pager.  One way to avoid this is to force
     pending output to be flushed before calling a function that will
     produce output from within Fortran functions.  To do this, use the
     command

          fflush (stdout)

     Another possible workaround is to use the command

          page_screen_output (false);

     to turn the pager off.

   A list of ideas for future enhancements is distributed with Octave.
See the file `PROJECTS' in the top level directory in the source
distribution.


File: octave.info,  Node: Reporting Bugs,  Next: Bug Criteria,  Prev: Actual Bugs,  Up: Trouble

E.2 Reporting Bugs
==================

Your bug reports play an essential role in making Octave reliable.

   When you encounter a problem, the first thing to do is to see if it
is already known.  *Note Trouble::.  If it isn't known, then you should
report the problem.

   Reporting a bug may help you by bringing a solution to your problem,
or it may not.  In any case, the principal function of a bug report is
to help the entire community by making the next version of Octave work
better.  Bug reports are your contribution to the maintenance of Octave.

   In order for a bug report to serve its purpose, you must include the
information that makes it possible to fix the bug.

   If you have Octave working at all, the easiest way to prepare a
complete bug report is to use the Octave function `bug_report'.  When
you execute this function, Octave will prompt you for a subject and then
invoke the editor on a file that already contains all the configuration
information.  When you exit the editor, Octave will mail the bug report
for you.

 -- Function File:  bug_report ()
     Have Octave create a bug report template file, invoke your favorite
     editor, and submit the report to the bug-octave mailing list when
     you are finished editing.

* Menu:

* Bug Criteria::
* Where: Bug Lists.             Where to send your bug report.
* Reporting: Bug Reporting.     How to report a bug effectively.
* Patches: Sending Patches.     How to send a patch for Octave.


File: octave.info,  Node: Bug Criteria,  Next: Bug Lists,  Prev: Reporting Bugs,  Up: Trouble

E.3 Have You Found a Bug?
=========================

If you are not sure whether you have found a bug, here are some
guidelines:

   * If Octave gets a fatal signal, for any input whatever, that is a
     bug.  Reliable interpreters never crash.

   * If Octave produces incorrect results, for any input whatever, that
     is a bug.

   * Some output may appear to be incorrect when it is in fact due to a
     program whose behavior is undefined, which happened by chance to
     give the desired results on another system.  For example, the
     range operator may produce different results because of
     differences in the way floating point arithmetic is handled on
     various systems.

   * If Octave produces an error message for valid input, that is a bug.

   * If Octave does not produce an error message for invalid input,
     that is a bug.  However, you should note that your idea of
     "invalid input" might be my idea of "an extension" or "support for
     traditional practice".

   * If you are an experienced user of programs like Octave, your
     suggestions for improvement are welcome in any case.


File: octave.info,  Node: Bug Lists,  Next: Bug Reporting,  Prev: Bug Criteria,  Up: Trouble

E.4 Where to Report Bugs
========================

If you have Octave working at all, the easiest way to prepare a complete
bug report is to use the Octave function `bug_report'.  When you
execute this function, Octave will prompt you for a subject and then
invoke the editor on a file that already contains all the configuration
information.  When you exit the editor, Octave will mail the bug report
for you.

   If for some reason you cannot use Octave's `bug_report' function,
send bug reports for Octave to <bug@octave.org>.

   *Do not send bug reports to `help-octave'*.  Most users of Octave do
not want to receive bug reports.  Those that do have asked to be on the
mailing list.


File: octave.info,  Node: Bug Reporting,  Next: Sending Patches,  Prev: Bug Lists,  Up: Trouble

E.5 How to Report Bugs
======================

Send bug reports for Octave to one of the addresses listed in *note Bug
Lists::.

   The fundamental principle of reporting bugs usefully is this:
*report all the facts*.  If you are not sure whether to state a fact or
leave it out, state it!

   Often people omit facts because they think they know what causes the
problem and they conclude that some details don't matter.  Thus, you
might assume that the name of the variable you use in an example does
not matter.  Well, probably it doesn't, but one cannot be sure.
Perhaps the bug is a stray memory reference which happens to fetch from
the location where that name is stored in memory; perhaps, if the name
were different, the contents of that location would fool the
interpreter into doing the right thing despite the bug.  Play it safe
and give a specific, complete example.

   Keep in mind that the purpose of a bug report is to enable someone to
fix the bug if it is not known.  Always write your bug reports on the
assumption that the bug is not known.

   Sometimes people give a few sketchy facts and ask, "Does this ring a
bell?"  This cannot help us fix a bug.  It is better to send a complete
bug report to begin with.

   Try to make your bug report self-contained.  If we have to ask you
for more information, it is best if you include all the previous
information in your response, as well as the information that was
missing.

   To enable someone to investigate the bug, you should include all
these things:

   * The version of Octave.  You can get this by noting the version
     number that is printed when Octave starts, or running it with the
     `-v' option.

   * A complete input file that will reproduce the bug.

     A single statement may not be enough of an example--the bug might
     depend on other details that are missing from the single statement
     where the error finally occurs.

   * The command arguments you gave Octave to execute that example and
     observe the bug.  To guarantee you won't omit something important,
     list all the options.

     If we were to try to guess the arguments, we would probably guess
     wrong and then we would not encounter the bug.

   * The type of machine you are using, and the operating system name
     and version number.

   * The command-line arguments you gave to the `configure' command when
     you installed the interpreter.

   * A complete list of any modifications you have made to the
     interpreter source.

     Be precise about these changes--show a context diff for them.

   * Details of any other deviations from the standard procedure for
     installing Octave.

   * A description of what behavior you observe that you believe is
     incorrect.  For example, "The interpreter gets a fatal signal,"
     or, "The output produced at line 208 is incorrect."

     Of course, if the bug is that the interpreter gets a fatal signal,
     then one can't miss it.  But if the bug is incorrect output, we
     might not notice unless it is glaringly wrong.

     Even if the problem you experience is a fatal signal, you should
     still say so explicitly.  Suppose something strange is going on,
     such as, your copy of the interpreter is out of synch, or you have
     encountered a bug in the C library on your system.  Your copy
     might crash and the copy here would not.  If you said to expect a
     crash, then when the interpreter here fails to crash, we would
     know that the bug was not happening.  If you don't say to expect a
     crash, then we would not know whether the bug was happening.  We
     would not be able to draw any conclusion from our observations.

     Often the observed symptom is incorrect output when your program
     is run.  Unfortunately, this is not enough information unless the
     program is short and simple.  It is very helpful if you can
     include an explanation of the expected output, and why the actual
     output is incorrect.

   * If you wish to suggest changes to the Octave source, send them as
     context diffs.  If you even discuss something in the Octave source,
     refer to it by context, not by line number, because the line
     numbers in the development sources probably won't match those in
     your sources.

   Here are some things that are not necessary:

   * A description of the envelope of the bug.

     Often people who encounter a bug spend a lot of time investigating
     which changes to the input file will make the bug go away and
     which changes will not affect it.  Such information is usually not
     necessary to enable us to fix bugs in Octave, but if you can find
     a simpler example to report _instead_ of the original one, that is
     a convenience.  Errors in the output will be easier to spot,
     running under the debugger will take less time, etc.  Most Octave
     bugs involve just one function, so the most straightforward way to
     simplify an example is to delete all the function definitions
     except the one in which the bug occurs.

     However, simplification is not vital; if you don't want to do
     this, report the bug anyway and send the entire test case you used.

   * A patch for the bug.  Patches can be helpful, but if you find a
     bug, you should report it, even if you cannot send a fix for the
     problem.


File: octave.info,  Node: Sending Patches,  Next: Service,  Prev: Bug Reporting,  Up: Trouble

E.6 Sending Patches for Octave
==============================

If you would like to write bug fixes or improvements for Octave, that is
very helpful.  When you send your changes, please follow these
guidelines to avoid causing extra work for us in studying the patches.

   If you don't follow these guidelines, your information might still be
useful, but using it will take extra work.  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.
     Unidiff 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.


File: octave.info,  Node: Service,  Prev: Sending Patches,  Up: Trouble

E.7 How To Get Help with Octave
===============================

The mailing list <help@octave.org> exists for the discussion of matters
related to using and installing Octave.  If would like to join the
discussion, please send a short note to <help*-request*@octave.org>.

   *Please do not* send requests to be added or removed from the
mailing list, or other administrative trivia to the list itself.

   If you think you have found a bug in the installation procedure,
however, you should send a complete bug report for the problem to
<bug@octave.org>.  *Note Bug Reporting::, for information that will
help you to submit a useful report.


File: octave.info,  Node: Installation,  Next: Emacs Octave Support,  Prev: Trouble,  Up: Top

Appendix F Installing Octave
****************************

   Here is the procedure for installing Octave from scratch on a Unix
system.

   * Run the shell script `configure'.  This will determine the features
     your system has (or doesn't have) and create a file named
     `Makefile' from each of the files named `Makefile.in'.

     Here is a summary of the configure options that are most
     frequently used when building Octave:

    `--prefix=PREFIX'
          Install Octave in subdirectories below PREFIX.  The default
          value of PREFIX is `/usr/local'.

    `--srcdir=DIR'
          Look for Octave sources in the directory DIR.

    `--enable-bounds-check'
          Enable bounds checking for indexing operators in the internal
          array classes.  This option is primarily used for debugging
          Octave.  Building Octave with this option has a negative
          impact on performance and is not recommended for general use.

    `--enable-64'
          This is an *experimental* option to enable Octave to use
          64-bit integers for array dimensions and indexing on 64-bit
          platforms.  You probably don't want to use this option unless
          you know what you are doing.

          If you use `--enable-64', you must ensure that your Fortran
          compiler generates code with 8 byte signed `INTEGER' values,
          and that your BLAS and LAPACK libraries are compiled to use 8
          byte signed integers for array dimensions and indexing.

    `--enable-shared'
          Create shared libraries (this is the default).  If you are
          planning to use the dynamic loading features, you will
          probably want to use this option.  It will make your `.oct'
          files much smaller and on some systems it may be necessary to
          build shared libraries in order to use dynamically linked
          functions.

          You may also want to build a shared version of `libstdc++',
          if your system doesn't already have one.

    `--enable-dl'
          Use `dlopen' and friends to make Octave capable of dynamically
          linking externally compiled functions (this is the default if
          `--enable-shared' is specified).  This option only works on
          systems that actually have these functions.  If you plan on
          using this feature, you should probably also use
          `--enable-shared' to reduce the size of your `.oct' files.

    `--without-blas'
          Compile and use the generic BLAS and LAPACK versions included
          with Octave.  By default, configure first looks for BLAS and
          LAPACK matrix libraries on your system, including optimized
          BLAS implementations such as the free ATLAS 3.0, as well as
          vendor-tuned libraries.  (The use of an optimized BLAS will
          generally result in several-times faster matrix operations.)
          Only use this option if your system has BLAS/LAPACK libraries
          that cause problems for some reason.  You can also use
          `--with-blas=lib' to specify a particular BLAS library  that
          configure doesn't check for automatically.

    `--without-ccolamd'
          Don't use CCOLAMD, disable some sparse matrix functionality.

    `--without-colamd'
          Don't use COLAMD, disable some sparse matrix functionality.

    `--without-curl'
          Don't use the cURL, disable the `urlread' and `urlwrite'
          functions.

    `--without-cxsparse'
          Don't use CXSPARSE, disable some sparse matrix functionality.

    `--without-umfpack'
          Don't use UMFPACK, disable some sparse matrix functionality.

    `--without-fftw'
          Use the included FFTPACK library instead of the FFTW library.

    `--without-glpk'
          Don't use the GLPK library for linear programming.

    `--without-hdf5'
          Don't use the HDF5 library for reading and writing HDF5 files.

    `--without-zlib'
          Don't use the zlib library, disable data file compression and
          support for recent MAT file formats.

    `--without-lapack'
          Compile and use the generic BLAS and LAPACK versions included
          with Octave.  By default, configure first looks for BLAS and
          LAPACK matrix libraries on your system, including optimized
          BLAS implementations such as the free ATLAS 3.0, as well as
          vendor-tuned libraries.  (The use of an optimized BLAS will
          generally result in several-times faster matrix operations.)
          Only use this option if your system has BLAS/LAPACK libraries
          that cause problems for some reason.  You can also use
          `--with-blas=lib' to specify a particular BLAS library  that
          configure doesn't check for automatically.

    `--without-framework-carbon'
          Don't use framework Carbon headers, libraries and specific
          source code for compilation even if the configure test
          succeeds (the default value is `--with-framework-carbon').
          This is a platform specific configure option for Mac systems.

    `--without-framework-opengl'
          Don't use framework OpenGL headers, libraries and specific
          source code for compilation even if the configure test
          succeeds.  If this option is given then OpenGL headers and
          libraries in standard system locations are tested (the
          default value is `--with-framework-opengl').  This is a
          platform specific configure option for Mac systems.

    `--help'
          Print a summary of the options recognized by the configure
          script.

     See the file `INSTALL' for more general information about the
     command line options used by configure.  That file also contains
     instructions for compiling in a directory other than where the
     source is located.

   * Run make.

     You will need a recent version of GNU Make.  Modifying Octave's
     makefiles to work with other make programs is probably not worth
     your time.  We recommend you get and compile GNU Make instead.

     For plotting, you will need to have gnuplot installed on your
     system.  Gnuplot is a command-driven interactive function plotting
     program.  Gnuplot is copyrighted, but freely distributable.  The
     `gnu' in gnuplot is a coincidence--it is not related to the GNU
     project or the FSF in any but the most peripheral sense.

     To compile Octave, you will need a recent version of GNU Make.
     You will also need a recent version of `g++' or other ANSI C++
     compiler.  You will also need a Fortran 77 compiler or `f2c'.  If
     you use `f2c', you will need a script like `fort77' that works
     like a normal Fortran compiler by combining `f2c' with your C
     compiler in a single script.

     If you plan to modify the parser you will also need GNU `bison' and
     `flex'.  If you modify the documentation, you will need GNU
     Texinfo, along with the patch for the `makeinfo' program that is
     distributed with Octave.

     GNU Make, `gcc', and `libstdc++', `gnuplot', `bison', `flex', and
     Texinfo are all available from many anonymous ftp archives.  The
     primary site is `ftp.gnu.org', but it is often very busy.  A list
     of sites that mirror the software on `ftp.gnu.org' is available by
     anonymous ftp from `ftp://ftp.gnu.org/pub/gnu/GNUinfo/FTP'.

     You will need about 1 gigabyte of disk storage to work with when
     building Octave from source (considerably less if you don't
     compile with debugging symbols).  To do that, use the command

          make CFLAGS=-O CXXFLAGS=-O LDFLAGS=

     instead of just `make'.

   * If you encounter errors while compiling Octave, first check the
     list of known problems below to see if there is a workaround or
     solution for your problem.  If not, see *note Trouble::, for
     information about how to report bugs.

   * Once you have successfully compiled Octave, run `make install'.

     This will install a copy of Octave, its libraries, and its
     documentation in the destination directory.  As distributed,
     Octave is installed in the following directories.  In the table
     below, PREFIX defaults to `/usr/local', VERSION stands for the
     current version number of the interpreter, and ARCH is the type of
     computer on which Octave is installed (for example,
     `i586-unknown-gnu').

    `PREFIX/bin'
          Octave and other binaries that people will want to run
          directly.

    `PREFIX/lib'
          Libraries like libcruft.a and liboctave.a.

    `PREFIX/share'
          Architecture-independent data files.

    `PREFIX/include/octave'
          Include files distributed with Octave.

    `PREFIX/man/man1'
          Unix-style man pages describing Octave.

    `PREFIX/info'
          Info files describing Octave.

    `PREFIX/share/octave/VERSION/m'
          Function files distributed with Octave.  This includes the
          Octave version, so that multiple versions of Octave may be
          installed at the same time.

    `PREFIX/lib/octave/VERSION/exec/ARCH'
          Executables to be run by Octave rather than the user.

    `PREFIX/lib/octave/VERSION/oct/ARCH'
          Object files that will be dynamically loaded.

    `PREFIX/share/octave/VERSION/imagelib'
          Image files that are distributed with Octave.

* Menu:

* Installation Problems::


File: octave.info,  Node: Installation Problems,  Up: Installation

F.1 Installation Problems
=========================

This section contains a list of problems (and some apparent problems
that don't really mean anything is wrong) that may show up during
installation of Octave.

   * On some SCO systems, `info' fails to compile if `HAVE_TERMIOS_H'
     is defined in `config.h'.  Simply removing the definition from
     `info/config.h' should allow it to compile.

   * If `configure' finds `dlopen', `dlsym', `dlclose', and `dlerror',
     but not the header file `dlfcn.h', you need to find the source for
     the header file and install it in the directory `usr/include'.
     This is reportedly a problem with Slackware 3.1.  For Linux/GNU
     systems, the source for `dlfcn.h' is in the `ldso' package.

   * Building `.oct' files doesn't work.

     You should probably have a shared version of `libstdc++'.  A patch
     is needed to build shared versions of version 2.7.2 of `libstdc++'
     on the HP-PA architecture.  You can find the patch at
     `ftp://ftp.cygnus.com/pub/g++/libg++-2.7.2-hppa-gcc-fix'.

   * On some alpha systems there may be a problem with the `libdxml'
     library, resulting in floating point errors and/or segmentation
     faults in the linear algebra routines called by Octave.  If you
     encounter such problems, then you should modify the configure
     script so that `SPECIAL_MATH_LIB' is not set to `-ldxml'.

   * On FreeBSD systems Octave may hang while initializing some internal
     constants.  The fix appears to be to use

          options      GPL_MATH_EMULATE

     rather than

          options      MATH_EMULATE

     in the kernel configuration files (typically found in the directory
     `/sys/i386/conf'.  After making this change, you'll need to rebuild
     the kernel, install it, and reboot.

   * If you encounter errors like

          passing `void (*)()' as argument 2 of
            `octave_set_signal_handler(int, void (*)(int))'

     or

          warning: ANSI C++ prohibits conversion from `(int)'
                   to `(...)'

     while compiling `sighandlers.cc', you may need to edit some files
     in the `gcc' include subdirectory to add proper prototypes for
     functions there.  For example, Ultrix 4.2 needs proper
     declarations for the `signal' function and the `SIG_IGN' macro in
     the file `signal.h'.

     On some systems the `SIG_IGN' macro is defined to be something like
     this:

          #define  SIG_IGN  (void (*)())1

     when it should really be something like:

          #define  SIG_IGN  (void (*)(int))1

     to match the prototype declaration for the `signal' function.  This
     change should also be made for the `SIG_DFL' and `SIG_ERR'
     symbols.  It may be necessary to change the definitions in
     `sys/signal.h' as well.

     The `gcc' `fixincludes' and `fixproto' scripts should probably fix
     these problems when `gcc' installs its modified set of header
     files, but I don't think that's been done yet.

     *You should not change the files in `/usr/include'*.  You can find
     the `gcc' include directory tree by running the command

          gcc -print-libgcc-file-name

     The directory of `gcc' include files normally begins in the same
     directory that contains the file `libgcc.a'.

   * Some of the Fortran subroutines may fail to compile with older
     versions of the Sun Fortran compiler.  If you get errors like

          zgemm.f:
          	zgemm:
          warning: unexpected parent of complex expression subtree
          zgemm.f, line 245: warning: unexpected parent of complex
            expression subtree
          warning: unexpected parent of complex expression subtree
          zgemm.f, line 304: warning: unexpected parent of complex
            expression subtree
          warning: unexpected parent of complex expression subtree
          zgemm.f, line 327: warning: unexpected parent of complex
            expression subtree
          pcc_binval: missing IR_CONV in complex op
          make[2]: *** [zgemm.o] Error 1

     when compiling the Fortran subroutines in the `libcruft'
     subdirectory, you should either upgrade your compiler or try
     compiling with optimization turned off.

   * On NeXT systems, if you get errors like this:

          /usr/tmp/cc007458.s:unknown:Undefined local
                symbol LBB7656
          /usr/tmp/cc007458.s:unknown:Undefined local
                symbol LBE7656

     when compiling `Array.cc' and `Matrix.cc', try recompiling these
     files without `-g'.

   * Some people have reported that calls to shell_cmd and the pager do
     not work on SunOS systems.  This is apparently due to having
     `G_HAVE_SYS_WAIT' defined to be 0 instead of 1 when compiling
     `libg++'.

   * On NeXT systems, linking to `libsys_s.a' may fail to resolve the
     following functions

          _tcgetattr
          _tcsetattr
          _tcflow

     which are part of `libposix.a'.  Unfortunately, linking Octave with
     `-posix' results in the following undefined symbols.

          .destructors_used
          .constructors_used
          _objc_msgSend
          _NXGetDefaultValue
          _NXRegisterDefaults
          .objc_class_name_NXStringTable
          .objc_class_name_NXBundle

     One kluge around this problem is to extract `termios.o' from
     `libposix.a', put it in Octave's `src' directory, and add it to
     the list of files to link together in the makefile.  Suggestions
     for better ways to solve this problem are welcome!

   * If Octave crashes immediately with a floating point exception, it
     is likely that it is failing to initialize the IEEE floating point
     values for infinity and NaN.

     If your system actually does support IEEE arithmetic, you should
     be able to fix this problem by modifying the function
     `octave_ieee_init' in the file `lo-ieee.cc' to correctly
     initialize Octave's internal infinity and NaN variables.

     If your system does not support IEEE arithmetic but Octave's
     configure script incorrectly determined that it does, you can work
     around the problem by editing the file `config.h' to not define
     `HAVE_ISINF', `HAVE_FINITE', and `HAVE_ISNAN'.

     In any case, please report this as a bug since it might be
     possible to modify Octave's configuration script to automatically
     determine the proper thing to do.

   * If Octave is unable to find a header file because it is installed
     in a location that is not normally searched by the compiler, you
     can add the directory to the include search path by specifying
     (for example) `CPPFLAGS=-I/some/nonstandard/directory' as an
     argument to `configure'.  Other variables that can be specified
     this way are `CFLAGS', `CXXFLAGS', `FFLAGS', and `LDFLAGS'.
     Passing them as options to the configure script also records them
     in the `config.status' file.  By default, `CPPFLAGS' and `LDFLAGS'
     are empty, `CFLAGS' and `CXXFLAGS' are set to `"-g -O"' and
     `FFLAGS' is set to `"-O"'.



File: octave.info,  Node: Emacs Octave Support,  Next: Copying,  Prev: Installation,  Up: Top

Appendix G Emacs Octave Support
*******************************

The development of Octave code can greatly be facilitated using Emacs
with Octave mode, a major mode for editing Octave files which can e.g.
automatically indent the code, do some of the typing (with Abbrev mode)
and show keywords, comments, strings, etc. in different faces (with
Font-lock mode on devices that support it).

   It is also possible to run Octave from within Emacs, either by
directly entering commands at the prompt in a buffer in Inferior Octave
mode, or by interacting with Octave from within a file with Octave
code.  This is useful in particular for debugging Octave code.

   Finally, you can convince Octave to use the Emacs info reader for
`help -i'.

   All functionality is provided by the Emacs Lisp package EOS (for
"Emacs Octave Support").  This chapter describes how to set up and use
this package.

   Please contact <Kurt.Hornik@wu-wien.ac.at> if you have any questions
or suggestions on using EOS.

* Menu:

* Installing EOS::
* Using Octave Mode::
* Running Octave From Within Emacs::
* Using the Emacs Info Reader for Octave::


File: octave.info,  Node: Installing EOS,  Next: Using Octave Mode,  Up: Emacs Octave Support

G.1 Installing EOS
==================

The Emacs package EOS consists of the three files `octave-mod.el',
`octave-inf.el', and `octave-hlp.el'.  These files, or better yet their
byte-compiled versions, should be somewhere in your Emacs load-path.

   If you have GNU Emacs with a version number at least as high as
19.35, you are all set up, because EOS is respectively will be part of
GNU Emacs as of version 19.35.

   Otherwise, copy the three files from the `emacs' subdirectory of the
Octave distribution to a place where Emacs can find them (this depends
on how your Emacs was installed).  Byte-compile them for speed if you
want.


File: octave.info,  Node: Using Octave Mode,  Next: Running Octave From Within Emacs,  Prev: Installing EOS,  Up: Emacs Octave Support

G.2 Using Octave Mode
=====================

If you are lucky, your sysadmins have already arranged everything so
that Emacs automatically goes into Octave mode whenever you visit an
Octave code file as characterized by its extension `.m'.  If not,
proceed as follows.

  1. To begin using Octave mode for all `.m' files you visit, add the
     following lines to a file loaded by Emacs at startup time,
     typically your `~/.emacs' file:

          (autoload 'octave-mode "octave-mod" nil t)
          (setq auto-mode-alist
                (cons '("\\.m$" . octave-mode) auto-mode-alist))

  2. Finally, to turn on the abbrevs, auto-fill and font-lock features
     automatically, also add the following lines to one of the Emacs
     startup files:
          (add-hook 'octave-mode-hook
                    (lambda ()
                      (abbrev-mode 1)
                      (auto-fill-mode 1)
                      (if (eq window-system 'x)
                          (font-lock-mode 1))))
     See the Emacs manual for more information about how to customize
     Font-lock mode.

   In Octave mode, the following special Emacs commands can be used in
addition to the standard Emacs commands.

`C-h m'
     Describe the features of Octave mode.

`LFD'
     Reindent the current Octave line, insert a newline and indent the
     new line (`octave-reindent-then-newline-and-indent').  An abbrev
     before point is expanded if `abbrev-mode' is non-`nil'.

`TAB'
     Indents current Octave line based on its contents and on previous
     lines (`indent-according-to-mode').

`;'
     Insert an "electric" semicolon (`octave-electric-semi').  If
     `octave-auto-indent' is non-`nil', reindent the current line.  If
     `octave-auto-newline' is non-`nil', automagically insert a newline
     and indent the new line.

``'
     Start entering an abbreviation (`octave-abbrev-start').  If Abbrev
     mode is turned on, typing ``C-h' or ``?' lists all abbrevs.  Any
     other key combination is executed normally.  Note that all Octave
     abbrevs start with a grave accent.

`M-LFD'
     Break line at point and insert continuation marker and alignment
     (`octave-split-line').

`M-TAB'
     Perform completion on Octave symbol preceding point, comparing that
     symbol against Octave's reserved words and built-in variables
     (`octave-complete-symbol').

`M-C-a'
     Move backward to the beginning of a function
     (`octave-beginning-of-defun').  With prefix argument N, do it that
     many times if N is positive;  otherwise, move forward to the N-th
     following beginning of a function.

`M-C-e'
     Move forward to the end of a function (`octave-end-of-defun').
     With prefix argument N, do it that many times if N is positive;
     otherwise, move back to the N-th preceding end of a function.

`M-C-h'
     Puts point at beginning and mark at the end of the current Octave
     function, i.e., the one containing point or following point
     (`octave-mark-defun').

`M-C-q'
     Properly indents the Octave function which contains point
     (`octave-indent-defun').

`M-;'
     If there is no comment already on this line, create a code-level
     comment (started by two comment characters) if the line is empty,
     or an in-line comment (started by one comment character) otherwise
     (`octave-indent-for-comment').  Point is left after the start of
     the comment which is properly aligned.

`C-c ;'
     Puts the comment character `#' (more precisely, the string value of
     `octave-comment-start') at the beginning of every line in the
     region (`octave-comment-region').  With just `C-u' prefix
     argument, uncomment each line in the region.  A numeric prefix
     argument N means use N comment characters.

`C-c :'
     Uncomments every line in the region (`octave-uncomment-region').

`C-c C-p'
     Move one line of Octave code backward, skipping empty and comment
     lines (`octave-previous-code-line').  With numeric prefix argument
     N, move that many code lines backward (forward if N is negative).

`C-c C-n'
     Move one line of Octave code forward, skipping empty and comment
     lines (`octave-next-code-line').  With numeric prefix argument N,
     move that many code lines forward (backward if N is negative).

`C-c C-a'
     Move to the `real' beginning of the current line
     (`octave-beginning-of-line').  If point is in an empty or comment
     line, simply go to its beginning;  otherwise, move backwards to the
     beginning of the first code line which is not inside a continuation
     statement, i.e., which does not follow a code line ending in `...'
     or `\', or is inside an open parenthesis list.

`C-c C-e'
     Move to the `real' end of the current line (`octave-end-of-line').
     If point is in a code line, move forward to the end of the first
     Octave code line which does not end in `...' or `\' or is inside an
     open parenthesis list.  Otherwise, simply go to the end of the
     current line.

`C-c M-C-n'
     Move forward across one balanced begin-end block of Octave code
     (`octave-forward-block').  With numeric prefix argument N, move
     forward across N such blocks (backward if N is negative).

`C-c M-C-p'
     Move back across one balanced begin-end block of Octave code
     (`octave-backward-block').  With numeric prefix argument N, move
     backward across N such blocks (forward if N is negative).

`C-c M-C-d'
     Move forward down one begin-end block level of Octave code
     (`octave-down-block').  With numeric prefix argument, do it that
     many times;  a negative argument means move backward, but still go
     down one level.

`C-c M-C-u'
     Move backward out of one begin-end block level of Octave code
     (`octave-backward-up-block').  With numeric prefix argument, do it
     that many times; a negative argument means move forward, but still
     to a less deep spot.

`C-c M-C-h'
     Put point at the beginning of this block, mark at the end
     (`octave-mark-block').  The block marked is the one that contains
     point or follows point.

`C-c ]'
     Close the current block on a separate line (`octave-close-block').
     An error is signaled if no block to close is found.

`C-c f'
     Insert a function skeleton, prompting for the function's name,
     arguments and return values which have to be entered without
     parentheses (`octave-insert-defun').

`C-c C-h'
     Search the function, operator and variable indices of all info
     files with documentation for Octave for entries (`octave-help').
     If used interactively, the entry is prompted for with completion.
     If multiple matches are found, one can cycle through them using
     the standard `,' (`Info-index-next') command of the Info reader.

     The variable `octave-help-files' is a list of files to search
     through and defaults to `'("octave")'.  If there is also an Octave
     Local Guide with corresponding info file, say, `octave-LG', you can
     have `octave-help' search both files by
          (setq octave-help-files '("octave" "octave-LG"))
     in one of your Emacs startup files.


   A common problem is that the <RET> key does _not_ indent the line to
where the new text should go after inserting the newline.  This is
because the standard Emacs convention is that <RET> (aka `C-m') just
adds a newline, whereas <LFD> (aka `C-j') adds a newline and indents
it.  This is particularly inconvenient for users with keyboards which
do not have a special <LFD> key at all;  in such cases, it is typically
more convenient to use <RET> as the <LFD> key (rather than typing
`C-j').

   You can make <RET> do this by adding
     (define-key octave-mode-map "\C-m"
       'octave-reindent-then-newline-and-indent)
   to one of your Emacs startup files.  Another, more generally
applicable solution is
     (defun RET-behaves-as-LFD ()
       (let ((x (key-binding "\C-j")))
         (local-set-key "\C-m" x)))
     (add-hook 'octave-mode-hook 'RET-behaves-as-LFD)
   (this works for all modes by adding to the startup hooks, without
having to know the particular binding of <RET> in that mode!).  Similar
considerations apply for using <M-RET> as <M-LFD>.  As Barry A. Warsaw
<bwarsaw@cnri.reston.va.us> says in the documentation for his
`cc-mode', "This is a very common question.  `:-)' If you want this to
be the default behavior, don't lobby me, lobby RMS!"

   The following variables can be used to customize Octave mode.

`octave-auto-indent'
     Non-`nil' means auto-indent the current line after a semicolon or
     space.  Default is `nil'.

`octave-auto-newline'
     Non-`nil' means auto-insert a newline and indent after semicolons
     are typed.  The default value is `nil'.

`octave-blink-matching-block'
     Non-`nil' means show matching begin of block when inserting a
     space, newline or `;' after an else or end keyword.  Default is
     `t'.  This is an extremely useful feature for automatically
     verifying that the keywords match--if they don't, an error message
     is displayed.

`octave-block-offset'
     Extra indentation applied to statements in block structures.
     Default is 2.

`octave-continuation-offset'
     Extra indentation applied to Octave continuation lines.  Default
     is 4.

`octave-continuation-string'
     String used for Octave continuation lines.  Normally `\'.

`octave-mode-startup-message'
     If `t' (default), a startup message is displayed when Octave mode
     is called.


   If Font Lock mode is enabled, Octave mode will display
   * strings in `font-lock-string-face'

   * comments in `font-lock-comment-face'

   * the Octave reserved words (such as all block keywords) and the text
     functions (such as `cd' or `who') which are also reserved using
     `font-lock-keyword-face'

   * the built-in operators (`&&', `==', ...) using
     `font-lock-reference-face'

   * and the function names in function declarations in
     `font-lock-function-name-face'.

   There is also rudimentary support for Imenu (currently, function
names can be indexed).

   You can generate TAGS files for Emacs from Octave `.m' files using
the shell script `octave-tags' that is installed alongside your copy of
Octave.

   Customization of Octave mode can be performed by modification of the
variable `octave-mode-hook'.  If the value of this variable is
non-`nil', turning on Octave mode calls its value.

   If you discover a problem with Octave mode, you can conveniently
send a bug report using `C-c C-b' (`octave-submit-bug-report').  This
automatically sets up a mail buffer with version information already
added.  You just need to add a description of the problem, including a
reproducible test case and send the message.


File: octave.info,  Node: Running Octave From Within Emacs,  Next: Using the Emacs Info Reader for Octave,  Prev: Using Octave Mode,  Up: Emacs Octave Support

G.3 Running Octave From Within Emacs
====================================

The package `octave' provides commands for running an inferior Octave
process in a special Emacs buffer.  Use
     M-x run-octave
   to directly start an inferior Octave process.  If Emacs does not know
about this command, add the line
     (autoload 'run-octave "octave-inf" nil t)
   to your `.emacs' file.

   This will start Octave in a special buffer the name of which is
specified by the variable `inferior-octave-buffer' and defaults to
`"*Inferior Octave*"'.  From within this buffer, you can interact with
the inferior Octave process `as usual', i.e., by entering Octave
commands at the prompt.  The buffer is in Inferior Octave mode, which
is derived from the standard Comint mode, a major mode for interacting
with an inferior interpreter.  See the documentation for `comint-mode'
for more details, and use `C-h b' to find out about available special
keybindings.

   You can also communicate with an inferior Octave process from within
files with Octave code (i.e., buffers in Octave mode), using the
following commands.

`C-c i l'
     Send the current line to the inferior Octave process
     (`octave-send-line').  With positive prefix argument N, send that
     many lines.  If `octave-send-line-auto-forward' is non-`nil', go
     to the next unsent code line.

`C-c i b'
     Send the current block to the inferior Octave process
     (`octave-send-block').

`C-c i f'
     Send the current function to the inferior Octave process
     (`octave-send-defun').

`C-c i r'
     Send the region to the inferior Octave process
     (`octave-send-region').

`C-c i s'
     Make sure that `inferior-octave-buffer' is displayed
     (`octave-show-process-buffer').

`C-c i h'
     Delete all windows that display the inferior Octave buffer
     (`octave-hide-process-buffer').

`C-c i k'
     Kill the inferior Octave process and its buffer
     (`octave-kill-process').

   The effect of the commands which send code to the Octave process can
be customized by the following variables.
`octave-send-echo-input'
     Non-`nil' means echo input sent to the inferior Octave process.
     Default is `t'.

`octave-send-show-buffer'
     Non-`nil' means display the buffer running the Octave process after
     sending a command (but without selecting it).  Default is `t'.

   If you send code and there is no inferior Octave process yet, it
will be started automatically.

   The startup of the inferior Octave process is highly customizable.
The variable `inferior-octave-startup-args' can be used for specifying
command lines arguments to be passed to Octave on startup as a list of
strings.  For example, to suppress the startup message and use
`traditional' mode, set this to `'("-q" "--traditional")'.  You can
also specify a startup file of Octave commands to be loaded on startup;
note that these commands will not produce any visible output in the
process buffer.  Which file to use is controlled by the variable
`inferior-octave-startup-file'.  If this is `nil', the file
`~/.emacs-octave' is used if it exists.

   And finally, `inferior-octave-mode-hook' is run after starting the
process and putting its buffer into Inferior Octave mode.  Hence, if you
like the up and down arrow keys to behave in the interaction buffer as
in the shell, and you want this buffer to use nice colors, add
     (add-hook 'inferior-octave-mode-hook
               (lambda ()
                 (turn-on-font-lock)
                 (define-key inferior-octave-mode-map [up]
                   'comint-previous-input)
                 (define-key inferior-octave-mode-map [down]
                   'comint-next-input)))
   to your `.emacs' file.  You could also swap the roles of `C-a'
(`beginning-of-line') and `C-c C-a' (`comint-bol') using this hook.

     *Note* that if you set your Octave prompts to something different
     from the defaults, make sure that `inferior-octave-prompt' matches
     them.  Otherwise, _nothing_ will work, because Emacs will not know
     when Octave is waiting for input, or done sending output.


File: octave.info,  Node: Using the Emacs Info Reader for Octave,  Prev: Running Octave From Within Emacs,  Up: Emacs Octave Support

G.4 Using the Emacs Info Reader for Octave
==========================================

You may also use the Emacs Info reader with Octave's `doc' function.
For this, the package `gnuserv' needs to be installed.

   If `gnuserv' is installed, add the lines
     (autoload 'octave-help "octave-hlp" nil t)
     (require 'gnuserv)
     (gnuserv-start)
   to your `.emacs' file.

   You can use either `plain' Emacs Info or the function `octave-help'
as your Octave info reader (for `help -i').  In the former case, use
`info_program ("info-emacs-info")'.  The latter is perhaps more
attractive because it allows to look up keys in the indices of
_several_ info files related to Octave (provided that the Emacs
variable `octave-help-files' is set correctly).  In this case, use
`info_program ("info-emacs-octave-help")'.

   If you use Octave from within Emacs, it is best to add these
settings to your `~/.emacs-octave' startup file (or the file pointed to
by the Emacs variable `inferior-octave-startup-file').


File: octave.info,  Node: Copying,  Next: Concept Index,  Prev: Emacs Octave Support,  Up: Top

Appendix H GNU GENERAL PUBLIC LICENSE
*************************************

                        Version 3, 29 June 2007

     Copyright (C) 2007 Free Software Foundation, Inc. `http://fsf.org/'

     Everyone is permitted to copy and distribute verbatim copies of this
     license document, but changing it is not allowed.

Preamble
========

The GNU General Public License is a free, copyleft license for software
and other kinds of works.

   The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains
free software for all its users.  We, the Free Software Foundation, use
the GNU General Public License for most of our software; it applies
also to any other work released this way by its authors.  You can apply
it to your programs, too.

   When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

   To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you
have certain responsibilities if you distribute copies of the software,
or if you modify it: responsibilities to respect the freedom of others.

   For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

   Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

   For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

   Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the
manufacturer can do so.  This is fundamentally incompatible with the
aim of protecting users' freedom to change the software.  The
systematic pattern of such abuse occurs in the area of products for
individuals to use, which is precisely where it is most unacceptable.
Therefore, we have designed this version of the GPL to prohibit the
practice for those products.  If such problems arise substantially in
other domains, we stand ready to extend this provision to those domains
in future versions of the GPL, as needed to protect the freedom of
users.

   Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

   The precise terms and conditions for copying, distribution and
modification follow.

TERMS AND CONDITIONS
====================

  0. Definitions.

     "This License" refers to version 3 of the GNU General Public
     License.

     "Copyright" also means copyright-like laws that apply to other
     kinds of works, such as semiconductor masks.

     "The Program" refers to any copyrightable work licensed under this
     License.  Each licensee is addressed as "you".  "Licensees" and
     "recipients" may be individuals or organizations.

     To "modify" a work means to copy from or adapt all or part of the
     work in a fashion requiring copyright permission, other than the
     making of an exact copy.  The resulting work is called a "modified
     version" of the earlier work or a work "based on" the earlier work.

     A "covered work" means either the unmodified Program or a work
     based on the Program.

     To "propagate" a work means to do anything with it that, without
     permission, would make you directly or secondarily liable for
     infringement under applicable copyright law, except executing it
     on a computer or modifying a private copy.  Propagation includes
     copying, distribution (with or without modification), making
     available to the public, and in some countries other activities as
     well.

     To "convey" a work means any kind of propagation that enables other
     parties to make or receive copies.  Mere interaction with a user
     through a computer network, with no transfer of a copy, is not
     conveying.

     An interactive user interface displays "Appropriate Legal Notices"
     to the extent that it includes a convenient and prominently visible
     feature that (1) displays an appropriate copyright notice, and (2)
     tells the user that there is no warranty for the work (except to
     the extent that warranties are provided), that licensees may
     convey the work under this License, and how to view a copy of this
     License.  If the interface presents a list of user commands or
     options, such as a menu, a prominent item in the list meets this
     criterion.

  1. Source Code.

     The "source code" for a work means the preferred form of the work
     for making modifications to it.  "Object code" means any
     non-source form of a work.

     A "Standard Interface" means an interface that either is an
     official standard defined by a recognized standards body, or, in
     the case of interfaces specified for a particular programming
     language, one that is widely used among developers working in that
     language.

     The "System Libraries" of an executable work include anything,
     other than the work as a whole, that (a) is included in the normal
     form of packaging a Major Component, but which is not part of that
     Major Component, and (b) serves only to enable use of the work
     with that Major Component, or to implement a Standard Interface
     for which an implementation is available to the public in source
     code form.  A "Major Component", in this context, means a major
     essential component (kernel, window system, and so on) of the
     specific operating system (if any) on which the executable work
     runs, or a compiler used to produce the work, or an object code
     interpreter used to run it.

     The "Corresponding Source" for a work in object code form means all
     the source code needed to generate, install, and (for an executable
     work) run the object code and to modify the work, including
     scripts to control those activities.  However, it does not include
     the work's System Libraries, or general-purpose tools or generally
     available free programs which are used unmodified in performing
     those activities but which are not part of the work.  For example,
     Corresponding Source includes interface definition files
     associated with source files for the work, and the source code for
     shared libraries and dynamically linked subprograms that the work
     is specifically designed to require, such as by intimate data
     communication or control flow between those subprograms and other
     parts of the work.

     The Corresponding Source need not include anything that users can
     regenerate automatically from other parts of the Corresponding
     Source.

     The Corresponding Source for a work in source code form is that
     same work.

  2. Basic Permissions.

     All rights granted under this License are granted for the term of
     copyright on the Program, and are irrevocable provided the stated
     conditions are met.  This License explicitly affirms your unlimited
     permission to run the unmodified Program.  The output from running
     a covered work is covered by this License only if the output,
     given its content, constitutes a covered work.  This License
     acknowledges your rights of fair use or other equivalent, as
     provided by copyright law.

     You may make, run and propagate covered works that you do not
     convey, without conditions so long as your license otherwise
     remains in force.  You may convey covered works to others for the
     sole purpose of having them make modifications exclusively for
     you, or provide you with facilities for running those works,
     provided that you comply with the terms of this License in
     conveying all material for which you do not control copyright.
     Those thus making or running the covered works for you must do so
     exclusively on your behalf, under your direction and control, on
     terms that prohibit them from making any copies of your
     copyrighted material outside their relationship with you.

     Conveying under any other circumstances is permitted solely under
     the conditions stated below.  Sublicensing is not allowed; section
     10 makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

     No covered work shall be deemed part of an effective technological
     measure under any applicable law fulfilling obligations under
     article 11 of the WIPO copyright treaty adopted on 20 December
     1996, or similar laws prohibiting or restricting circumvention of
     such measures.

     When you convey a covered work, you waive any legal power to forbid
     circumvention of technological measures to the extent such
     circumvention is effected by exercising rights under this License
     with respect to the covered work, and you disclaim any intention
     to limit operation or modification of the work as a means of
     enforcing, against the work's users, your or third parties' legal
     rights to forbid circumvention of technological measures.

  4. Conveying Verbatim Copies.

     You may convey verbatim copies of the Program's source code as you
     receive it, in any medium, provided that you conspicuously and
     appropriately publish on each copy an appropriate copyright notice;
     keep intact all notices stating that this License and any
     non-permissive terms added in accord with section 7 apply to the
     code; keep intact all notices of the absence of any warranty; and
     give all recipients a copy of this License along with the Program.

     You may charge any price or no price for each copy that you convey,
     and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

     You may convey a work based on the Program, or the modifications to
     produce it from the Program, in the form of source code under the
     terms of section 4, provided that you also meet all of these
     conditions:

       a. The work must carry prominent notices stating that you
          modified it, and giving a relevant date.

       b. The work must carry prominent notices stating that it is
          released under this License and any conditions added under
          section 7.  This requirement modifies the requirement in
          section 4 to "keep intact all notices".

       c. You must license the entire work, as a whole, under this
          License to anyone who comes into possession of a copy.  This
          License will therefore apply, along with any applicable
          section 7 additional terms, to the whole of the work, and all
          its parts, regardless of how they are packaged.  This License
          gives no permission to license the work in any other way, but
          it does not invalidate such permission if you have separately
          received it.

       d. If the work has interactive user interfaces, each must display
          Appropriate Legal Notices; however, if the Program has
          interactive interfaces that do not display Appropriate Legal
          Notices, your work need not make them do so.

     A compilation of a covered work with other separate and independent
     works, which are not by their nature extensions of the covered
     work, and which are not combined with it such as to form a larger
     program, in or on a volume of a storage or distribution medium, is
     called an "aggregate" if the compilation and its resulting
     copyright are not used to limit the access or legal rights of the
     compilation's users beyond what the individual works permit.
     Inclusion of a covered work in an aggregate does not cause this
     License to apply to the other parts of the aggregate.

  6. Conveying Non-Source Forms.

     You may convey a covered work in object code form under the terms
     of sections 4 and 5, provided that you also convey the
     machine-readable Corresponding Source under the terms of this
     License, in one of these ways:

       a. Convey the object code in, or embodied in, a physical product
          (including a physical distribution medium), accompanied by the
          Corresponding Source fixed on a durable physical medium
          customarily used for software interchange.

       b. Convey the object code in, or embodied in, a physical product
          (including a physical distribution medium), accompanied by a
          written offer, valid for at least three years and valid for
          as long as you offer spare parts or customer support for that
          product model, to give anyone who possesses the object code
          either (1) a copy of the Corresponding Source for all the
          software in the product that is covered by this License, on a
          durable physical medium customarily used for software
          interchange, for a price no more than your reasonable cost of
          physically performing this conveying of source, or (2) access
          to copy the Corresponding Source from a network server at no
          charge.

       c. Convey individual copies of the object code with a copy of
          the written offer to provide the Corresponding Source.  This
          alternative is allowed only occasionally and noncommercially,
          and only if you received the object code with such an offer,
          in accord with subsection 6b.

       d. Convey the object code by offering access from a designated
          place (gratis or for a charge), and offer equivalent access
          to the Corresponding Source in the same way through the same
          place at no further charge.  You need not require recipients
          to copy the Corresponding Source along with the object code.
          If the place to copy the object code is a network server, the
          Corresponding Source may be on a different server (operated
          by you or a third party) that supports equivalent copying
          facilities, provided you maintain clear directions next to
          the object code saying where to find the Corresponding Source.
          Regardless of what server hosts the Corresponding Source, you
          remain obligated to ensure that it is available for as long
          as needed to satisfy these requirements.

       e. Convey the object code using peer-to-peer transmission,
          provided you inform other peers where the object code and
          Corresponding Source of the work are being offered to the
          general public at no charge under subsection 6d.


     A separable portion of the object code, whose source code is
     excluded from the Corresponding Source as a System Library, need
     not be included in conveying the object code work.

     A "User Product" is either (1) a "consumer product", which means
     any tangible personal property which is normally used for personal,
     family, or household purposes, or (2) anything designed or sold for
     incorporation into a dwelling.  In determining whether a product
     is a consumer product, doubtful cases shall be resolved in favor of
     coverage.  For a particular product received by a particular user,
     "normally used" refers to a typical or common use of that class of
     product, regardless of the status of the particular user or of the
     way in which the particular user actually uses, or expects or is
     expected to use, the product.  A product is a consumer product
     regardless of whether the product has substantial commercial,
     industrial or non-consumer uses, unless such uses represent the
     only significant mode of use of the product.

     "Installation Information" for a User Product means any methods,
     procedures, authorization keys, or other information required to
     install and execute modified versions of a covered work in that
     User Product from a modified version of its Corresponding Source.
     The information must suffice to ensure that the continued
     functioning of the modified object code is in no case prevented or
     interfered with solely because modification has been made.

     If you convey an object code work under this section in, or with,
     or specifically for use in, a User Product, and the conveying
     occurs as part of a transaction in which the right of possession
     and use of the User Product is transferred to the recipient in
     perpetuity or for a fixed term (regardless of how the transaction
     is characterized), the Corresponding Source conveyed under this
     section must be accompanied by the Installation Information.  But
     this requirement does not apply if neither you nor any third party
     retains the ability to install modified object code on the User
     Product (for example, the work has been installed in ROM).

     The requirement to provide Installation Information does not
     include a requirement to continue to provide support service,
     warranty, or updates for a work that has been modified or
     installed by the recipient, or for the User Product in which it
     has been modified or installed.  Access to a network may be denied
     when the modification itself materially and adversely affects the
     operation of the network or violates the rules and protocols for
     communication across the network.

     Corresponding Source conveyed, and Installation Information
     provided, in accord with this section must be in a format that is
     publicly documented (and with an implementation available to the
     public in source code form), and must require no special password
     or key for unpacking, reading or copying.

  7. Additional Terms.

     "Additional permissions" are terms that supplement the terms of
     this License by making exceptions from one or more of its
     conditions.  Additional permissions that are applicable to the
     entire Program shall be treated as though they were included in
     this License, to the extent that they are valid under applicable
     law.  If additional permissions apply only to part of the Program,
     that part may be used separately under those permissions, but the
     entire Program remains governed by this License without regard to
     the additional permissions.

     When you convey a copy of a covered work, you may at your option
     remove any additional permissions from that copy, or from any part
     of it.  (Additional permissions may be written to require their own
     removal in certain cases when you modify the work.)  You may place
     additional permissions on material, added by you to a covered work,
     for which you have or can give appropriate copyright permission.

     Notwithstanding any other provision of this License, for material
     you add to a covered work, you may (if authorized by the copyright
     holders of that material) supplement the terms of this License
     with terms:

       a. Disclaiming warranty or limiting liability differently from
          the terms of sections 15 and 16 of this License; or

       b. Requiring preservation of specified reasonable legal notices
          or author attributions in that material or in the Appropriate
          Legal Notices displayed by works containing it; or

       c. Prohibiting misrepresentation of the origin of that material,
          or requiring that modified versions of such material be
          marked in reasonable ways as different from the original
          version; or

       d. Limiting the use for publicity purposes of names of licensors
          or authors of the material; or

       e. Declining to grant rights under trademark law for use of some
          trade names, trademarks, or service marks; or

       f. Requiring indemnification of licensors and authors of that
          material by anyone who conveys the material (or modified
          versions of it) with contractual assumptions of liability to
          the recipient, for any liability that these contractual
          assumptions directly impose on those licensors and authors.

     All other non-permissive additional terms are considered "further
     restrictions" within the meaning of section 10.  If the Program as
     you received it, or any part of it, contains a notice stating that
     it is governed by this License along with a term that is a further
     restriction, you may remove that term.  If a license document
     contains a further restriction but permits relicensing or
     conveying under this License, you may add to a covered work
     material governed by the terms of that license document, provided
     that the further restriction does not survive such relicensing or
     conveying.

     If you add terms to a covered work in accord with this section, you
     must place, in the relevant source files, a statement of the
     additional terms that apply to those files, or a notice indicating
     where to find the applicable terms.

     Additional terms, permissive or non-permissive, may be stated in
     the form of a separately written license, or stated as exceptions;
     the above requirements apply either way.

  8. Termination.

     You may not propagate or modify a covered work except as expressly
     provided under this License.  Any attempt otherwise to propagate or
     modify it is void, and will automatically terminate your rights
     under this License (including any patent licenses granted under
     the third paragraph of section 11).

     However, if you cease all violation of this License, then your
     license from a particular copyright holder is reinstated (a)
     provisionally, unless and until the copyright holder explicitly
     and finally terminates your license, and (b) permanently, if the
     copyright holder fails to notify you of the violation by some
     reasonable means prior to 60 days after the cessation.

     Moreover, your license from a particular copyright holder is
     reinstated permanently if the copyright holder notifies you of the
     violation by some reasonable means, this is the first time you have
     received notice of violation of this License (for any work) from
     that copyright holder, and you cure the violation prior to 30 days
     after your receipt of the notice.

     Termination of your rights under this section does not terminate
     the licenses of parties who have received copies or rights from
     you under this License.  If your rights have been terminated and
     not permanently reinstated, you do not qualify to receive new
     licenses for the same material under section 10.

  9. Acceptance Not Required for Having Copies.

     You are not required to accept this License in order to receive or
     run a copy of the Program.  Ancillary propagation of a covered work
     occurring solely as a consequence of using peer-to-peer
     transmission to receive a copy likewise does not require
     acceptance.  However, nothing other than this License grants you
     permission to propagate or modify any covered work.  These actions
     infringe copyright if you do not accept this License.  Therefore,
     by modifying or propagating a covered work, you indicate your
     acceptance of this License to do so.

 10. Automatic Licensing of Downstream Recipients.

     Each time you convey a covered work, the recipient automatically
     receives a license from the original licensors, to run, modify and
     propagate that work, subject to this License.  You are not
     responsible for enforcing compliance by third parties with this
     License.

     An "entity transaction" is a transaction transferring control of an
     organization, or substantially all assets of one, or subdividing an
     organization, or merging organizations.  If propagation of a
     covered work results from an entity transaction, each party to that
     transaction who receives a copy of the work also receives whatever
     licenses to the work the party's predecessor in interest had or
     could give under the previous paragraph, plus a right to
     possession of the Corresponding Source of the work from the
     predecessor in interest, if the predecessor has it or can get it
     with reasonable efforts.

     You may not impose any further restrictions on the exercise of the
     rights granted or affirmed under this License.  For example, you
     may not impose a license fee, royalty, or other charge for
     exercise of rights granted under this License, and you may not
     initiate litigation (including a cross-claim or counterclaim in a
     lawsuit) alleging that any patent claim is infringed by making,
     using, selling, offering for sale, or importing the Program or any
     portion of it.

 11. Patents.

     A "contributor" is a copyright holder who authorizes use under this
     License of the Program or a work on which the Program is based.
     The work thus licensed is called the contributor's "contributor
     version".

     A contributor's "essential patent claims" are all patent claims
     owned or controlled by the contributor, whether already acquired or
     hereafter acquired, that would be infringed by some manner,
     permitted by this License, of making, using, or selling its
     contributor version, but do not include claims that would be
     infringed only as a consequence of further modification of the
     contributor version.  For purposes of this definition, "control"
     includes the right to grant patent sublicenses in a manner
     consistent with the requirements of this License.

     Each contributor grants you a non-exclusive, worldwide,
     royalty-free patent license under the contributor's essential
     patent claims, to make, use, sell, offer for sale, import and
     otherwise run, modify and propagate the contents of its
     contributor version.

     In the following three paragraphs, a "patent license" is any
     express agreement or commitment, however denominated, not to
     enforce a patent (such as an express permission to practice a
     patent or covenant not to sue for patent infringement).  To
     "grant" such a patent license to a party means to make such an
     agreement or commitment not to enforce a patent against the party.

     If you convey a covered work, knowingly relying on a patent
     license, and the Corresponding Source of the work is not available
     for anyone to copy, free of charge and under the terms of this
     License, through a publicly available network server or other
     readily accessible means, then you must either (1) cause the
     Corresponding Source to be so available, or (2) arrange to deprive
     yourself of the benefit of the patent license for this particular
     work, or (3) arrange, in a manner consistent with the requirements
     of this License, to extend the patent license to downstream
     recipients.  "Knowingly relying" means you have actual knowledge
     that, but for the patent license, your conveying the covered work
     in a country, or your recipient's use of the covered work in a
     country, would infringe one or more identifiable patents in that
     country that you have reason to believe are valid.

     If, pursuant to or in connection with a single transaction or
     arrangement, you convey, or propagate by procuring conveyance of, a
     covered work, and grant a patent license to some of the parties
     receiving the covered work authorizing them to use, propagate,
     modify or convey a specific copy of the covered work, then the
     patent license you grant is automatically extended to all
     recipients of the covered work and works based on it.

     A patent license is "discriminatory" if it does not include within
     the scope of its coverage, prohibits the exercise of, or is
     conditioned on the non-exercise of one or more of the rights that
     are specifically granted under this License.  You may not convey a
     covered work if you are a party to an arrangement with a third
     party that is in the business of distributing software, under
     which you make payment to the third party based on the extent of
     your activity of conveying the work, and under which the third
     party grants, to any of the parties who would receive the covered
     work from you, a discriminatory patent license (a) in connection
     with copies of the covered work conveyed by you (or copies made
     from those copies), or (b) primarily for and in connection with
     specific products or compilations that contain the covered work,
     unless you entered into that arrangement, or that patent license
     was granted, prior to 28 March 2007.

     Nothing in this License shall be construed as excluding or limiting
     any implied license or other defenses to infringement that may
     otherwise be available to you under applicable patent law.

 12. No Surrender of Others' Freedom.

     If 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 convey a covered work so as to satisfy
     simultaneously your obligations under this License and any other
     pertinent obligations, then as a consequence you may not convey it
     at all.  For example, if you agree to terms that obligate you to
     collect a royalty for further conveying from those to whom you
     convey the Program, the only way you could satisfy both those
     terms and this License would be to refrain entirely from conveying
     the Program.

 13. Use with the GNU Affero General Public License.

     Notwithstanding any other provision of this License, you have
     permission to link or combine any covered work with a work licensed
     under version 3 of the GNU Affero General Public License into a
     single combined work, and to convey the resulting work.  The terms
     of this License will continue to apply to the part which is the
     covered work, but the special requirements of the GNU Affero
     General Public License, section 13, concerning interaction through
     a network will apply to the combination as such.

 14. Revised Versions of this License.

     The Free Software Foundation may publish revised and/or new
     versions of the GNU 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
     Program specifies that a certain numbered version of the GNU
     General Public License "or any later version" applies to it, you
     have the option of following the terms and conditions either of
     that numbered version or of any later version published by the
     Free Software Foundation.  If the Program does not specify a
     version number of the GNU General Public License, you may choose
     any version ever published by the Free Software Foundation.

     If the Program specifies that a proxy can decide which future
     versions of the GNU General Public License can be used, that
     proxy's public statement of acceptance of a version permanently
     authorizes you to choose that version for the Program.

     Later license versions may give you additional or different
     permissions.  However, no additional obligations are imposed on any
     author or copyright holder as a result of your choosing to follow a
     later version.

 15. Disclaimer of Warranty.

     THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
     APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE
     COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM IS WITH YOU.
     SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
     NECESSARY SERVICING, REPAIR OR CORRECTION.

 16. Limitation of Liability.

     IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
     WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES
     AND/OR CONVEYS THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER
     PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF
     THE POSSIBILITY OF SUCH DAMAGES.

 17. Interpretation of Sections 15 and 16.

     If the disclaimer of warranty and limitation of liability provided
     above cannot be given local legal effect according to their terms,
     reviewing courts shall apply local law that most closely
     approximates an absolute waiver of all civil liability in
     connection with the Program, unless a warranty or assumption of
     liability accompanies a copy of the Program in return for a fee.


END OF TERMS AND CONDITIONS
===========================

How to Apply These Terms to Your New Programs
=============================================

If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.

   To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.

     ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
     Copyright (C) YEAR NAME OF AUTHOR

     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/'.

   Also add information on how to contact you by electronic and paper
mail.

   If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

     PROGRAM Copyright (C) YEAR NAME OF AUTHOR
     This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
     This is free software, and you are welcome to redistribute it
     under certain conditions; type `show c' for details.

   The hypothetical commands `show w' and `show c' should show the
appropriate parts of the General Public License.  Of course, your
program's commands might be different; for a GUI interface, you would
use an "about box".

   You should also get your employer (if you work as a programmer) or
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  For more information on this, and how to apply and follow
the GNU GPL, see `http://www.gnu.org/licenses/'.

   The GNU General Public License does not permit incorporating your
program into proprietary programs.  If your program is a subroutine
library, you may consider it more useful to permit linking proprietary
applications with the library.  If this is what you want to do, use the
GNU Lesser General Public License instead of this License.  But first,
please read `http://www.gnu.org/philosophy/why-not-lgpl.html'.

