\input texinfo 

@c
@comment *** Start of HTML stuff ***
@comment # HTML support, via comments in texinfo:
@comment #
@comment #   `@c HTML some-stuff'
@comment #       Pass "some-stuff", or in other words all the text following
@comment #       the HTML token on the same line, directly to the output file.
@comment #
@comment #       For example, you might do one of the following:
@comment #
@comment # (1) Let user see gif image.
@comment #       @c HTML <A HREF="file.gif">Click to see plot</A> <P>
@comment # 
@comment # (2) Let user ftp to a location.
@comment #       @c HTML <A HREF="ftp:#location">the Gri FTP site.</A> <P>
@comment #
@comment # (3) Ignore some texinfo stuff.
@comment #       @c HTML <!--
@comment #       some texinfo lines
@comment #       @c HTML -->
@comment #
@comment # (4) Create new file, possibly named and titled.
@comment #       @c HTML <!-- newfile filename "other_words_for_title" "margin_note" -->
@comment # if it occurs on a line all by itself, causes 
@comment # this perlscript to chop files here.  The filename
@comment # will be as specified.  The other_words 
@comment # will be used as the title.  If neither the
@comment # filename nor the other_words are present, then
@comment # this script makes up filenames using numbers, e.g.,
@comment # gri1.html, gri2.html.  If the filename is ".",
@comment # then this same naming scheme is used, but the titles
@comment # are used.
@comment #
@comment # (5) Plant a comment to be stripped out as a latex command
@comment #     @c HTML <!-- latex: some-stuff -->
@comment *** End of HTML stuff ***
@c
@comment OVERRIDE some defaults in texinfo.tex
@iftex
@message{}
@message{gri.texi: overriding parskip, }
@global@parskip=4pt             @c space between paragraphs

@message{overriding baselineskip, }
@global@baselineskip=12pt       @c line spacing
@message{overriding lispnarrowing }
@c @global@lispnarrowing=0.2cm  @c left margin on examples
@global@widowpenalty=10000      @c Prevent widows
@global@clubpenalty=10000       @c Prevent orphans


@message{}
@end iftex
@comment %**start of header
@setfilename gri.info
@settitle Gri
@set GRI-VERSION 2.12.26
@set GRI-PREVIOUS-VERSION 2.12.25
@set AUTHOR-EMAIL dankelley@@users.sourceforge.net
@include version.texi
@c %**end of header
@iftex
@finalout
@end iftex
@setchapternewpage odd
@titlepage
@title Gri

@ifnottex
@image{./examples/logo}
@end ifnottex



@subtitle A Program to Make Science Graphs
@subtitle Version @value{GRI-VERSION}
@subtitle 2015
@author Dan E. Kelley
@page
@vskip 0pt plus 1filll
Copyright @copyright{} 1991-2015 Dan Kelley
@sp 2
@end titlepage

@dircategory Scientific Applications
@direntry
* Gri: (gri).  Programming language for scientific illustration
@end direntry

@summarycontents
@contents


@node   Top, Introduction, (dir), (dir)
@comment node-name, next, previous, up
@top Gri
@c HTML <!--

Gri is an extensible plotting language designed for scientists.  It can
draw x-y plots, contour plots, and image plots, and has rudimentary
programming capabilities.  It is not mouse driven, nor gui-based;
rather, it is an interpreted scriping language.  Users regard it as an
analogue to the latex document formatting language: users gain
considerable power, at the price of a moderate learning curve.

This manual describes Gri version
@value{GRI-VERSION} @c , updated @value{UPDATED},
(c) 1991-2015, Dan Kelley

Gri is released with the GNU Public License (@ref{License}).

@c HTML -->

@c HTML <map name="navigate_top">
@c HTML <area alt="Introduction" shape="rect" coords="581,2,599,24" href="Introduction.html">
@c HTML </map>
@c HTML <map name="navigate_bottom">
@c HTML <area alt="Introduction" shape="rect" coords="581,2,599,24" href="Introduction.html">
@c HTML </map>
@c HTML
@c HTML <A HREF="logo.html">
@c HTML <IMG align=left ALT="Gri Logo" SRC="logo.png"></A>
@c HTML Gri is an extensible
@c HTML plotting language for producing scientific graphs, such as
@c HTML <A HREF="X-Y.html">x-y plots</A>, 
@c HTML <A HREF="ContourPlots.html">contour plots</A>, and
@c HTML <A HREF="Images.html">image plots</A>.
@c HTML <p>
@c HTML This document describes Gri @value{GRI-VERSION},
@c HTML <br>(c) 1991-2008 <A HREF="http://www.phys.ocean.dal.ca/~kelley"> Dan Kelley.</A>
@comment HTML Gri is distributed
@comment HTML with a <A HREF="License.html">license</A> that permits 
@comment HTML sharing in an OpenSource way.
@c HTML <p><br>
@c HTML <b>New users:</b>
@c HTML To see if Gri might be useful to you, spend a few minutes
@c HTML reading the
@c HTML <A HREF="Introduction.html">introduction</A>, the
@c HTML <A HREF="SimpleExample.html">simple example</A> tutorial, the
@c HTML <A HREF="./FAQ.html">FAQ</A> and the 
@c HTML <A HREF="http://gri.sourceforge.net/gri-cookbook/index.html"> 
@c HTML cookbook.</A>

@c HTML It is also a good idea to check out the real-world
@c HTML <A HREF="Examples.html">examples</A>.
@c HTML Then you should return here to scan the table of contents.  
@c HTML <P>
@c HTML <b>Experienced users:</b>
@c HTML To check the syntax of a command, consult
@c HTML the <A HREF="ListOfGriCommands.html"> list
@c HTML of Gri commands</A>.  See
@c HTML the <A HREF="History.html">history</a>
@c HTML to learn how Gri has changed over time.
@c HTML <p>
@c HTML <b>Open-Source Development:</b>
@c HTML Gri is distributed under an OpenSource licence (GPL).
@c HTML To monitor (or contribute to) the development
@c HTML process, visit
@c HTML <a href="http://gri.sourceforge.net">
@c HTML <tt>gri.sourceforge.net</tt></a>.
@c HTML <p>
@c HTML <b>See also:</b>
@c HTML The <a href="http://www.phys.ocean.dal.ca/~kelley/gre">
@c HTML Gre language</a> combines Gri features with Perl features.
@c HTML <br>
@c HTML <!--
@menu
* Introduction::                What Gri is for
* Simple Example::              Introductory example
* Invoking Gri::                Running/viewing/printing Gri
* Getting More Control::        Controlling axes, text, color, etc.

* X-y Plots::                   Drawing x-y linegraphs/scattergraphs
* Contour Plots::               Drawing contour plots
* Images::                      Drawing black+white or color images

* Examples::                    Some real-world examples
* Handling Data::               Dealing with oddly-configured data
* Commands::                    All about the many Gri commands
* Programming::                 How to program in the Gri language
* Environment::                 Related tools
* Emacs Mode::                  Editing Gri code inside Emacs
* History::                     How Gri has changed over time
* Installation::                How to install Gri
* Bugs::                        How to report on bugs
* Test Suite::                  Series of test programs
* Gri in the Press::            Further reading
* Acknowledgments::             Many folks have helped me with Gri
* License::                     Gri is open-source!

Three indices
* Concept Index::               Detailed index
* Index of Commands::           Commands in Gri
* Index of Builtins::           Builtin variables
@end menu
@c HTML -->

@c HTML <!-- newfile Introduction.html "Gri: introduction" "Introduction" -->

@node   Introduction, Simple Example, Top, Top
@comment  node-name,  next,  previous,  up
@chapter Introduction

@strong{Gri is a programming language for drawing science-style graphs}.
It is not mouse-driven, and it does not draw business-style graphs
(e.g. pie charts, three-dimensional graphs).  Gri has substantial power
in advanced applications.  It has been proven to be easy to learn; for
simple applications, the learning curve is less than an hour.  Many
users regard Gri as the plotting equivalent of the La@TeX{} document
preparation system.

@strong{Computers Gri works on:} unix computers of many types, plus
Microsoft Windows, and Macintosh OSX.  You'll find Gri pre-packaged
for various unixes, e.g. linux/debian, linux/redhat, and freeBSD. 

@strong{Capabilities of Gri} are those scientists commonly want, since Gri
was written by a scientist.  It is not so useful for business people --
e.g., Gri draws xy graphs (@ref{X-y Plots}), contour plots
(@ref{Contour Plots}), and image plots
(@ref{Images}), but it will
not draw pie-charts unless you teach it how.  The list of capabilities
of Gri is similar to many packages, but unlike many of the other
packages, Gri gives you control over line widths, fonts, grayscales,
etc.  (@ref{Getting More Control}), and it is a programming language
of moderate power.

@strong{The Gri drawing metaphor} is that of pen on paper.  The ink in the
pen is opaque.  An item drawn in white ink will erase a previously drawn
underlying object drawn in black ink.  For example, to draw a timeseries
curve in which the region between positive data values and the y=0 axis
is filled with black ink, you might use (@code{draw curve filled}) to
draw the timeseries with black ink (the default color), blackening the
area between the curve and the lower axis.  Then you could load white
ink into the pen (using the @code{set graylevel 1} or 
@code{set graylevel white} command) and white-out a box drawn between the zero
line and the lower axis.  Then you'd load black ink back into the pen
(@code{set graylevel 0}) and draw the curve again, so that the negative
part would appear again.

@strong{Input/output} in Gri may be interactive or non-interactive.  For
interactive use, type @code{gri} at the system commandline prompt.  For
non-interactive use, with Gri commands in a command-file called
@file{cmd.gri}, type @code{gri cmd.gri}.  

@strong{Gri output} is in the PostScript page description language.  The
output is therefore of high quality, device-independent, capable of
being inserted into popular text processors (e.g. LaTeX), and easily
displayed.

@strong{Online help:} the Gri command @code{help} makes Gri
list the first words of all known commands, along with a hint for
getting further help.  To get more information, type @code{help}
followed by a command-name (e.g. @code{help read}).  There is also a
tiny bit of information stored online and categorized by topic.  Get
this by typing for example @code{help - strings} (@ref{Online Help}).

@strong{Data analysis} in Gri is limited.  It has rudimentary data
analysis functions, such as regression, column manipulation, smoothing,
etc, but it is not intended as an integrated analysis/graphics package.

@strong{System calls} are an easy and important facet of Gri.  It is easy
to use operating system commands within Gri (@ref{System};
@ref{Operating System};
@ref{Get Env}).  This
allows you to use familiar, powerful tools, and keeps Gri simple.
Particularly useful is the ability to read files through operating
system filters (@ref{Open}).

@strong{Programming Gri} is quite straightforward, and users familiar with
other programming languages find it easy.  If Gri lacks a drawing
method, you can add it fairly easily, since Gri has programming elements
such as @code{if} statements (@ref{If Statements}), @code{while} loops
(@ref{While}), facilities for interacting with the user 
(@ref{Query}), and mechanisms for storing numbers in "variables"
(@ref{Variables}),
and text strings in "synonyms" (@ref{Synonyms}).  The Gri syntax can
be augmented easily (@ref{Adding New Commands}), and these
augmentations can be stored in a startup file (@ref{Resource File}),
creating personalized versions of Gri.


@cindex FTP site, cookbook
@strong{Manuals:} Gri has an online texinfo manual, a PostScript manual, a
WWW manual, a
@c HTML <A HREF="http://gri.sourceforge.net/gri-cookbook/index.html"> 
cookbook 
@c HTML </A> 
@cindex Gri newsgroup
@cindex newsgroup
and several reference cards.  It also has several discussion groups
(@ref{Discussion Group}).


@strong{Version Numbering Scheme}
@cindex gri version
@cindex version numbers

When you launch Gri interactively (without naming a commandfile, i.e. by
just typing @code{gri} at the unix prompt), you'll see something like

@example
 gri - scientific graphic program (version @value{GRI-VERSION})
 GPL Copyright 2015 by Dan E. Kelley.

 Type `help' for an overview of Gri commands, or see the
 full manual at
     /usr/share/doc/gri-@value{GRI-VERSION}/html/index.html
 and its text-only version in the 'gri' INFO node.  

 Visit http://gri.sourceforge.net for updates and resources.
gri: 
@end example

@noindent

The last line is a prompt, suggesting that you type in Gri commands.
You may type @code{quit} to get out of gri.

The first line gives the version number.  You can also get this by
running Gri with the command @code{gri -v}.  Version numbers have three
numbers separated by periods.  The first number increments for major
changes, the second for smaller changes, the third for still smaller
changes.  The second number also indicates whether a copy is an
experimental version or a more reliable release version.  Experimental
versions have the second digit being an odd integer, while release
versions have this digit being even.


@c HTML <!-- newfile SimpleExample.html "Gri: simple example" "Simple example" -->

@node   Simple Example, Invoking Gri, Introduction, Top
@comment  node-name,  next,  previous, up
@chapter Simple Gri Program and How to Run it
@cindex first-time usage
@cindex hint, first-time usage
@cindex beginners, simple example
@cindex drawing x-y graphs, simple
This chapter introduces Gri with a common example: an x-y graph.  The
example is discussed in detail later (@ref{X-y Plots}).  The data files
and command files here and throughout the manual should be available to
you in a directory @file{.../gri/examples} on unix machines.




@section Gri Command file

@cindex example 01, linegraph using data in a separate file

Here is a Gri command file to plot a linegraph of a set of (x,y) data,
stored as space-separated columns in a file called @file{example1.dat}:

@example
# Example 1 -- Linegraph of data in separate file
open example1.dat     # Open the data file
read columns x y      # Read (x,y) columns
draw curve            # Draw data curve
draw title "Example 1"# Title above plot
@end example

@noindent
The first line is a comment, as are all things following hash symbols (@code{#}).
(An exception to this rule is made within strings contained
within the double-quote character @code{"}.  This allows @code{sed}
system commands to work as expected; (@ref{System}).)

The other lines are Gri command lines; (@ref{X-y Plots}) for more
explanation.


@section Data File
The data file @file{example1.dat} looks like:

@example
0.05 12.5  # first point
0.25 19    # second point
0.5  15    # third point
0.75 15    # ... you get the idea!
0.95 13
@end example

@noindent
Note that spaces (or tabs) separate numbers.  Any data line may have a
comment on it, just as any command line may.


@section Running The Command File
Type @file{gri example1.gri} at the system prompt.  Gri will create a
PostScript file called @file{example1.ps}.  For details on running Gri
see @ref{Invoking Gri}.



@section Output Graph
The output PostScript file is called @file{example1.ps}.

@c HTML <A HREF="example1.png">
@c HTML <IMG ALT="Example 1" SRC="example1-tiny.png" ALIGN=top>
@c HTML </A>
@c HTML Click the plot to enlarge it.)
@c HTML <P>
@c HTML It looks something like the miniature shown above.

@c BUG: pdftex ignores the size.
@image{./examples/example1, 300pt}

@cindex example 01, linegraph using data in a separate file

To view Gri output, use your favorite PostScript previewer.

Note that in the above example, Gri automatically chose reasonable
scales for the axes, based on the range of the data.  The next chapter
illustrates that Gri also gives you control over such things.


@c HTML <!-- newfile InvokingGri.html "Gri: running" "Invoking Gri" -->

@node   Invoking Gri, Getting More Control, Simple Example, Top
@comment  node-name,  next,  previous,  up
@chapter Invoking Gri
@section Invoking Gri in a nutshell
First, the short story.  In 90 percent of cases, Gri is run as

@example
gri myscript
@end example

where the file @file{myscript.gri} holds a script (list of Gri
commands), and Gri will create a PostScript file called
@file{myscript.ps} with the output.  

Some folks like to give the @file{.gri} suffix explicitly, so they
would invoke Gri as

@example
gri myscript.gri
@end example

@noindent instead.  

If you'd rather not have @file{myscript.ps} as the PostScript output file
name (let's say you prefer @file{graph1.ps}) you'd do

@example
gri -output graph1.ps myscript.gri
@end example

Few readers will need to know more than this.  But, for the rest, the
table in the next section gives full details on all the optional
arguments that Gri can handle.

@section Using Gri to draw things
To draw things, invoke Gri as

@example
gri [OPTIONS] [CmdFile [optional_arguments]]
@end example

@cindex @code{[]} syntax for optional words in commands
@cindex optional words in commands, @code{[]} syntax

@noindent
where the square brackets indicate that the enclosed items
are optional.  The @code{OPTIONS} item may consist of one 
or more of the following (explained below):

@example
[-batch]
[-b]
[-chatty N]
[-c      N]
[-debug]
[-d]
[-directory_default]
[-directory pathname]
[-help]
[-h]
[-no_bounding_box]
[-no_cmd_in_ps]
[-no_startup_message]
[-output PS_file_name|SVG_file_name]
[-private]
[-no_private]
[-publication] 
[-p]
[-superuser N]
[-trace]
[-t]
[-yes]
[-y]
[-version]
[-v]
[-warn_offpage]
[-no_warn_offpage]
@end example
@noindent
@cindex colon on commandline
@cindex commandline flag colon
@cindex arguments on commandline, accessing
@cindex commandline arguments, accessing
@cindex @code{argv}, RPN operator to access commandline arguments
@cindex @code{argc}, RPN operator to access commandline arguments

Here, the optional @code{optional_arguments} are a mechanism to
customize the action of the given Gri script from the commandline.
After Gri processes standard arguments (e.g. @code{-t} for tracing), it
puts the remaining commandline arguments into a list.  This behavior is
borrowed from C and othe languages, so Gri borrows the name of the list
as well: it's called the "arg" list, and its elements are available with
the RPN operators named @file{argc} (@ref{Solitary Operators})
and @file{argv} (@ref{Unary Operators}).

For a note on usage within the Emacs gri-mode, see @ref{Filename
arguments when running gri}.


@strong{Details of command-line options}
@cindex options on Gri command-line
@cindex command-line options

@itemize @bullet

@item  @code{-batch} or @code{-b}
@cindex batch processing
@cindex @code{-batch} command-line option
Stops Gri from printing out prompts and hints.

@item  @code{-chatty N} or @code{-c N}
@cindex @code{-chatty} command-line option
Make Gri print out various informative messages.  The numerical
value gives a level of chattiness.  A value
of 1, the default if the @code{-chatty} code is not supplied, tells Gri to
keep you informed of some important things, like the success in gridding
data for contouring.  Higher values make Gri tell you more:

Information printed at various chatty levels:
@itemize @bullet

@item @strong{0}
The bare minimum is printed.  Thus invoking Gri as @code{gri -c 0}@dots{}
will make it as quiet as can be.

@item @strong{1 or higher} (the default)
The full filenames of the commandfiles are displayed at startup time.

@code{convert columns to grid} prints percentage of grid filled, as well
as a suite of diagnostics, if you've let it calculate the region of
influence automatically.  It also prints a warning of the time it
expects to take, before starting the calculation.

@code{convert grid to image} prints characteristics of image created,
including amount of image clipped.

@code{read grid data} reports number of data values it could not read
(since they were nonnumeric).

@code{draw symbol} reports number of data points not drawn because they
were missing or outside clip region (if one exists).

@item @strong{2 or higher}
@code{draw contour} prints value of contour being drawn.

@code{open "...|"} prints the command to be passed to the operating
system as well as the name of the temporary file being created; also
notifies user when the temporary file is destroyed.

@code{show image} reports histograms in intensity bands of 8 units, 
instead of the default 16 units.

@item @strong{3 or higher}
@code{show image} reports histograms in intensity bands of 4 units, 
instead of the default 16 units.

@end itemize

@item  @code{-debug} or @code{-d}
@cindex @code{-debug} command-line option
@vindex @code{..debug..}, for debugging (by normal users)
Sets the built-in variable flag @code{..debug..} that you can use to
isolate blocks of code.

@item  @code{-directory_default} 
@cindex @code{-directory_default} command-line option
Reports directory where @file{gri.cmd} is expected to be found, either
in the default location or the one specified by @code{-directory}
commandline option.

@item  @code{-directory pathname} 
@cindex @code{-directory} command-line option
Specifies the directory where Gri looks for the startup file
@file{gri.cmd}.  (This file teaches Gri the standard commands; Gri will
report an error and die if it cannot find this file.)  If this switch is
not provided -- and it is normally not -- then Gri looks for
@file{gri.cmd} in a standard system directory (sometimes,
but not always,
@file{/usr/local/share/gri/@value{GRI-VERSION}}) which was specified 
during the compilation of the Gri program itself.  For more on how Gri looks
for @file{gri.cmd}, see the subsection below.

@item  @code{-no_bounding_box}
@cindex postscript bounding box
@cindex bounding box
@cindex @code{-no_bounding_box} command-line option
Make the so-called ``bounding box'' in the PostScript file be the full
page.  The bounding box is used by some PostScript previewers to clip
the image to just the drawn parts of the page, and is used by the
@code{epsfbox} macro in @code{latex} to automatically determine the
geometry of the graph for inclusion in text.  Normally the bounding box
is calculated automatically, to enclose all the items drawn on the page.
But the box may also be set with the @code{set bounding box} command
(@ref{Set Bounding Box}).

@item  @code{-no_cmd_in_ps}
@cindex -no_cmd_in_ps
Prevent Gri from inserting the lines of the commandfile into the
PostScript file as comments.  (These comments can be used by the
@code{-creator} commandline option (see above), but they take up a little
bit of space and users might sometimes want to get rid of them.)

@item  @code{-no_warn_offpage}
@cindex postscript bounding box
@cindex bounding box
@cindex @code{-no_warn_offpage} command-line option
Do not warn if items are offpage.  (Contrast this with @code{-warn_offpage}.)

@item @code{-output PS_file_name}
@cindex specifying the PostScript file name
@cindex PostScript file name, specifying
@cindex commandline option @code{-output PS_file_name}
@cindex -output PS_file_name commandline option
Specify the PostScript filename.  If this is not specified, the
PostScript filename is derived from the name of the commandfile
(e.g. @file{mygraph.gri} produces @file{mygraph.ps}), or, for
interactive use, it will have a name like @file{gri-00.ps}, or
@file{gri-01.ps} if the former file exists, etc.

@item @code{-output SVG_file_name}
@cindex specifying the SVG file name
@cindex SVG file name, specifying
@cindex commandline option @code{-output SVG_file_name}
@cindex -output SVG_file_name commandline option
Specify the SVG filename.  This is a pre-feature, as of version 2.12.x,
meaning that SVG output is not working properly yet.  If you specify an
SVG file name, you will see a long list of warnings.  These are
debugging messages, and are not specific to your actual Gri script.  For
example, you will see warnings about centring strings, even if you are
not centering any strings.  This manual does not contain a list of
working features (or broken features) for SVG output; the idea is that a
discussion of such things be done using the bug-reporting system of the
Gri website @ref{Reporting Bugs}.  In addition to bugs, the author is
interested in users' opinions on the scheme of the SVG, especially the
hieararchy of groupings of graphical elements.  It is because such
things are being altered that this is designated a pre-feature.

@item  @code{-no_startup_message}
@cindex startup message
@cindex @code{-no_startup_message} command-line option
Stops Gri from printing the startup message.


@item  @code{-private}
@cindex @code{-private} command-line option
@cindex private, command-line flag
Prevents inserting any information about the user into the PostScript
file (see @code{-no_private}, next).  As of version 2.12.10, 
this privacy option is assumed by default.

@item  @code{-no_private}
@cindex @code{-no_private} command-line option
@cindex no_private, command-line flag
Instructs Gri to include comments in the PostScript file that identify
the user, state the commandline arguments used in invoking Gri, and
that list all the commands that were executed.  This information can
be recovered by calling Gri on the PostScript file, with the
@code{-creator} commandline argument.  Until version 2.12.10,
the default was to include this information, but a change was
made out of privacy concerns.

@item  @code{-publication} or @code{-p}
@cindex @code{-publication} command-line option
@cindex publication quality, command-line flag
Sets the built-in variable @code{..publication..} to 1.  You may use
this to distinguish between working plots and publication plots, as in
this example:

@example
if !..publication..
  draw time stamp
  draw title "working version of plot"
end if
@end example

@item  @code{-superuser}
@cindex @code{-superuser} command-line option
@vindex @code{..superuser..}, for debugging (by developers)
(This option is included here only for completeness.  It should only be
used by developers (who will alter the code to print debugging
information if @code{-superuser} is set in addition to @code{-debug}).
An optional value can be inserted (e.g. @code{-superuser 2}) to set the
debugging level (retrievable by the function superuser()) to indicated
integer value.  Specifying the @code{-superuser} command-line option
sets the built-in variable @code{..superuser..} to 1 or the specified
value.)

For flag meanings, see @code{superuser} command (@ref{Superuser}).
Using the question-mark symbol @code{?} instead of a flag number makes
Gri print out the list of flags.

@item  @code{-trace} or @code{-t}
@cindex @code{-trace} command-line option
@cindex tracing execution, command-line option
Makes Gri print out command lines as they are executed; this has the
same effect as the @code{set trace} command.

@item  @code{-version} or @code{-v}
@cindex @code{-version} command-line option
Display version information and exit successfully.

@item  @code{-warn_offpage}
@cindex command-line option @code{-warn_offpage}
@cindex @code{-warn_offpage} command-line option
Causes warnings to be issued for all items drawn far off a 8.5x11 inch
page.  This is the default.  (Contrast with @code{-no_warn_offpage}.)

@item  @code{-yes} or @code{-y}
@cindex @code{-yes} command-line option
@vindex @code{..use_default_for_query..}, simulate @code{-yes} commandline flag
@cindex interaction with user, @code{-y} command-line option
Bypasses all @code{query} commands, making Gri act as though the user
typed a carriage-return (thus giving the default) for each @code{query}.

@item  @code{-help} or @code{-h}
@cindex @code{-help} command-line option
Prints explanation of options.

@item @code{CommandFile}
@cindex @code{\\.path_commands.} builtin synonym
@cindex builtin synonym @code{\\.path_commands.}
@cindex @code{CommandFile} command-line option
@cindex command files
@cindex files, Command-file
@cindex command-line, specifying command file
If a command file @code{CommandFile} is specified, then commands will
be read from that file instead of the keyboard.  If the @code{chatty}
level is 1 or larger, Gri prints the names of the commandfiles at
startup time.  It is conventional but not necessary that the filename
ends in @code{.gri}.  If the filename does end in @code{.gri}, you may
delete this suffix; Gri will assume it as implied. 

@end itemize

@strong{Executable scripts.} If you don't need to supply commandline
options, you can put the following line as the first line in your Gri
program

@example
#!/usr/bin/gri
@end example

@noindent (or point to wherever Gri is located on your machine), and
@code{chmod +x} the file.  Then you can run Gri simply by naming the
file.  There is no particular advantage in this, except for saving the
typing of a few characters, but some folks like this.


@cindex @file{gri.cmd}, how it is located
@strong{How Gri locates the} @file{gri.cmd} @strong{file}.
In a normal installation, Gri finds the @file{gri.cmd} file all by
itself.  However, developers and some others may wish to control where
Gri looks for this file.  The rules below specify how Gri looks for
@file{gri.cmd}.
@table @emph

@item Case 1
If @code{-directory} was given on the commandline used to invoke Gri
(e.g. @code{gri -directory /some/place mycommand_file.gri}), then
Gri will use the @file{gri.cmd} in the named directory.  An error will
result if @file{gri.cmd} is not found there.

@item Case 2
If @code{-directory} was not given on the commandline, then
Gri looks for @file{gri.cmd} in a location that was specified during
compilation.  If @file{gri.cmd} is found there, then it is used.  If it
is not found, then Gri checks to see if an environment variable named
@code{GRI_DIRECTORY_LIBRARY} is defined.  If so, then Gri takes this to
be the name of a directory that contains the @file{gri.cmd} file.  If
@file{gri.cmd} is not found there, an error results.
@end table



@section Extracting commandfile from a PostScript file
@cindex recovering commands from a PostScript file
@cindex command-line option @code{-creator}
@cindex @code{-creator} command-line option

@example
gri -creator PostScriptFile
@end example

@noindent @strong{See also} @code{-no_cmd_in_ps}.

The @code{-creator} flag makes gri examine the indicate PostScript file,
and produce a facsimile of the command file (or interactively-typed
commands) that created this PostScript file.  (This only works if the
Gri command that created the PostScript file used the
@code{-no_private} commandline argument.)

@c REMOVED_AFTER_2_8_x @section Fixing a broken PostScript file
@c REMOVED_AFTER_2_8_x To make Gri repair a PostScript file created by a Gri job that failed
@c REMOVED_AFTER_2_8_x midway through:
@c REMOVED_AFTER_2_8_x
@c REMOVED_AFTER_2_8_x @example
@c REMOVED_AFTER_2_8_x gri -repair bad.ps good.ps
@c REMOVED_AFTER_2_8_x @end example
@c REMOVED_AFTER_2_8_x
@c REMOVED_AFTER_2_8_x This may very well not work, and the author only provides it in case it
@c REMOVED_AFTER_2_8_x may help you.  Essentially all it does it try to complete a so-called
@c REMOVED_AFTER_2_8_x PostScript "path", if Gri died in the middle of drawing a path.  Please
@c REMOVED_AFTER_2_8_x don't expect too much from this command, and don't expect bug fixes to
@c REMOVED_AFTER_2_8_x it.

@c HTML <!-- newfile GettingMoreControl.html "Gri: getting more control" "Getting more control" -->

@node   Getting More Control, Simple Example Revisited, Invoking Gri, Top
@comment  node-name,  next,  previous,  up
@chapter Controlling Axes, Fonts, Colors, etc

Gri provides a great many things that you can control, if you want to.
An introduction to some of these things is presented in the sections
below.

@menu
* Simple Example Revisited::    Adding more details
* Axis Scaling::                Gri automatically scales and draws axes
* Log And Linear::              Selecting log/linar axes
* Length::                      Adjusting axis length
* Range::                       Adjusting axis range
* Labels::                      Adjusting labels on axes
* Position::                    Positioning the axes
* Fonts::                       Setting fonts
* Pen Color::                   Controlling Pen color
@end menu

@c HTML <!-- newfile SimpleExampleRevisited.html "Gri: simple example revisited" "Getting more control" -->

@node   Simple Example Revisited, Axis Scaling, Getting More Control, Getting More Control
@section An example
@cindex scales
@cindex axes, scales
@cindex font, selecting
Below is a followup to the previous example, which names the x and the y
axes.

@example
# Fancier version of Example 1
open example1.dat
read columns x y
set x name "Time, hours"
set y name "U, m/s"
draw curve
@end example

The difference is that the x and y axes are named with a @code{set}
command.  There are many @code{set} commands, and they are all pretty
simple, e.g. @code{set x size 15} makes the x-axis be 15 centimeters
long, instead of the default of 10 centimeters.  Indeed, you can control
anything you want in gri, e.g. graph size, line width, fonts, etc etc.
Speaking of fonts, the @code{$\alpha$} type of latex formatting of Greek
letters is supported in a limited way.  
Also, Gri handles ISO-Latin-1 encodings as well as the U.S. style.


The example below illustrates a few more @code{set} commands.  This
example is intentionally complicated, being about a good example of the
level of complexity of many plots made by Gri.  Read the comments to see
what is being done, and consult the plot as you read the commandfile.

@cindex multiple panels
@cindex example 03 (controlling scales, etc)



@c HTML <A HREF="example3.png">
@c HTML <IMG ALT="Example 3" SRC="example3-tiny.png"
@c HTML ALIGN=top> 
@c HTML </A>
@c HTML <A HREF="example3.html">The command-file.</A> <P>

@image{./examples/example3, 300pt}
@cindex example 03, controlling scales, etc


@c HTML <!--
@example
# Example 3 -- Controlling scales, etc
#
# Example of how to control axis scales, etc.  This example makes
# two panels, plotting the same data in different ways.
#
#
# ----- PANEL 1 ------------------------------------------------
#
# Set up the x axis.
#
# Make the x axis run from 0 to 1, with labelled tics each 0.25. 
set x axis 0   1   .25
# Make the x-axis be 5 cm long; in other words, make the plot 5 cm wide.
set x size 5
# Put 2 cm of space between the left edge of the plot and the left
# edge of the paper.
set x margin 2
# Give the x-axis the name "t" with subscript 0.
set x name "$t_0$"
#
# Set up the y axis.
#
# Make the y axis run from 10 to 20, with labelled tics at intervals
# of 5 and smaller, unlabelled tics, at intervals of 1.  Other
# commands are similar to those for the x-axis.
set y axis 10 20 5 1
set y size 10
set y margin 2
set y name "F"
#
# Now, read our simple data set.
open example1.dat
read columns x y
close
#
# Draw a curve connecting these (x,y) data.  Note that the axes, as
# defined above, will be drawn automatically along with the curve.
draw curve 


#
# ----- PANEL 2 ------------------------------------------------
#
# OK, now for a more complicated version.  We'll keep the same data, but
# redraw it in a new panel, to the right of the first graph.  So, the
# first step is to increase the x margin.  The @{rpn@} command simply
# creates a number which is the sum of the old x margin (stored in 
# the variable ..xmargin..) and the old plot width (stored in
# the variable ..xsize..), plus an extra 1 cm
set x margin @{rpn ..xsize.. ..xmargin.. + 1 +@}
# 
# Set the line thickness for the curve to 1 point (0.3 mm) and the
# axis line thickness to 0.2 points (0.1 mm).
set line width 1.0              # points
set line width axis 0.2         # points
# Set the tics to be 1.5 mm.
set tic size 0.15               # centimetres
# Draw axes and frame, with axes offset from frame.  Some
# people find this more attractive.
set axes style offset
draw axes 1
# Now draw the actual curve.
draw curve
# Superimpose dots (diameter 1.5 mm) at the data.
set symbol size 0.15
draw symbol bullet
#
# All done.
# Draw a title above the plot.
set font size 20
\label = "Example 3 -- scales, axes, etc"
draw label "\label" at          \
    @{rpn 8.5 2.54 * "\label" width - 2 /@} \
    @{rpn ..ytop.. yusertocm 2 +@}\
    cm
@end example
@c HTML -->


@c HTML <!-- newfile AxisScaling.html "Gri: axis scaling" "Getting more control" -->

@node   Axis Scaling, Log And Linear, Simple Example Revisited, Getting More Control
@comment  node-name,  next,  previous,  up
@section Axis scaling
@cindex axes, and mathematical operations on columns
@cindex axes, autoscaling of
@vindex @code{..xlast..}, last drawn x value
@vindex @code{..ylast..}, last drawn y value
@vindex @code{..xmargin..}, left margin
@vindex @code{..ymargin..}, bottom margin
@vindex @code{..xsize..}, x-axis length
@vindex @code{..ysize..}, y-axis length
@vindex @code{..xleft..}, x value at left of plot
@vindex @code{..xright..}, x value at right of plot
@vindex @code{..xinc..}, x increment on axes
@vindex @code{..ybottom..}, y value at bottom of plot
@vindex @code{..ytop..}, y value at top of plot
@vindex @code{..yinc..}, y increment on axes

Gri normally assumes that you are plotting scientific graphs, and
therefore whenever it sees a command like @code{draw curve} or
@code{draw symbol}, it draws an appropriate axis first.  You can turn
this feature off, by using @code{draw axes none} before the other
@code{draw} command.

Furthermore, Gri picks axis scales by itself, by scanning the (@code{x},
@code{y}) columns.  If you don't like the scales Gri picks, you can
override them (@ref{Range}).

Gri normally draws axes labelled at left and bottom, and with an axis
frame with tics all around.  If you don't like this default axis style
you can specify other styles.  For example, if the commands 
@code{draw x axis} and @code{draw y axis} are placed before the @code{draw curve}
command, Gri will realize you've already specified axes, and just draw
them on the left and bottom sides of the box, without completing the
axis frame.

For your general use, Gri stores the minimum and maximum x and y
values of the @strong{axes} in the variables @code{..xleft..},
@code{..xright..}, @code{..ybottom..}, and @code{..ytop..}.  It also
stores the increments used in labelling these axes in the
@code{..xinc..}  and @code{..yinc..} variables.

To determine the minimum and maximum values of column data, you
may use the built-in RPN functions @code{min}, @code{max}, and
@code{mean} (@ref{Manipulation of Columns etc}).  

Gri stores the last (x,y) pair on a curve (whether data or axis) in the
@code{..xlast..} and @code{..ylast..} variables

Gri stores the axis sizes in @code{..xsize..} and @code{..ysize..}.  It
stores the space to the left of the plot in @code{..xmargin..} and the
space below the plot in @code{..ymargin..}.


@c HTML <!-- newfile LogAndLinearAxes.html "Gri: log and linear axes" "Getting more control" -->

@node   Log And Linear, Length, Axis Scaling, Getting More Control
@comment  node-name,  next,  previous,  up
@section Logarithmic and linear axes
@cindex logarithmic axes
@cindex axes, logarithmic
@cindex linear axes
@cindex axes, linear
Axes are linear by default; to make logarithmic axes, use commands
@code{set x type log} and @code{set y type log}.



@c HTML <!-- newfile AxisLength.html "Gri: axis length" "Getting more control" -->

@node   Length, Range, Log And Linear, Getting More Control
@comment  node-name,  next,  previous,  up
@section Axis Length
@cindex axes, guide to choosing length of
@cindex length of axes, guide on choosing
@cindex data files, protecting against movement of
The axes are normally 10 centimetres long.  To set the axis lengths (in
centimetres), use commands like @code{set x size 5} and 
@code{set y size 7}.  Some people like the ratio of axes to be in the
so-called golden ratio @code{(root(5)-1)/2}; to get that, you could do
this: 
@cindex axis sizes, scaled with golden ratio
@cindex golden ratio, used for axes sizes

@example
set x size 15
set y size @{rpn ..xsize.. 5 0.5 power 1 - 2 / *@}
@end example

@cindex scaling for maps
@cindex maps, scaling
For maps, you'll want the plot scaled so that shapes retain their aspect
ratio.  To do this, do @code{set x size .cm.} and then do 
@code{resize y for maps} (or vice versa).


@c HTML <!-- newfile AxisRange.html "Gri: axis range" "Getting more control" -->

@node   Range, Labels, Length, Getting More Control
@comment  node-name,  next,  previous,  up
@section Axis Range
@cindex axes, range of values on
@cindex range of axes
To override axis ranges set by Gri, use @code{set x axis} and 
@code{set y axis}.  With these commands, you specify the range of the axes; you
may also set the interval for numbered tics, and an interval for
unnumbered tics.  The unnumbered tics must be at an interval that
divides evenly into the numbered tic interval, but the numbered tic
interval need not divide into the min/max range.  Thus, 
@code{set x axis 0 1.1 0.5} will create an axis that will range from 0 to 1.1, with
labelled tics at the values 0, 0.5 and 1.


@c HTML <!-- newfile AxisLabels.html "Gri: axis labels" "Getting more control" -->

@node   Labels, Position, Range, Getting More Control
@comment  node-name,  next,  previous,  up
@section Axis Name
@cindex labels, on axes
@cindex axes, labels for
To set the name of the x axis, use @code{set x name "string"}, and
similarly for the y-axis.  The default names are @code{x} and @code{y}.


@c HTML <!-- newfile AxisPosition.html "Gri: axis position" "Getting more control" -->

@node   Position, Fonts, Labels, Getting More Control
@comment  node-name,  next,  previous,  up
@section Axis location
@cindex axes, location of
@cindex positioning axes
If you don't like the default position of axes (at left and bottom), you
may get Gri to draw axes anywhere you like, using commands like
@code{draw y axis at right} (so the y axis is at the right-hand end of
the x range) or @code{draw x axis at top} (so the x axis is at the top
of the plot); you may even specify an exact location, such as 
@code{draw x axis at 22.2}.

Normally, the x axis is placed at the bottom end of the y axis, and the
y axis is placed at the left end of the x axis.  Some people prefer a
style in which the axes are positioned a small offset away from these
locations.  To get this effect, you may either position the axes
yourself, or simply use the @code{set axes style offset} command
(@ref{Set}).  If you want this axis style for all their plots, put the
line @code{set axes style offset} in your @file{~/.grirc} startup file
(@ref{Resource File}).


@c HTML <!-- newfile Fonts.html "Gri: fonts" "Getting more control" -->

@node   Fonts, Pen Color, Position, Getting More Control
@comment  node-name,  next,  previous,  up
@section Fonts
Fonts are selected with @code{set font to} (@ref{Set Font To}) and font
sizes are selected with @code{set font size} (@ref{Set Font Size}).

Much more about text, including how to draw mathematical symbols, how to
use subscripts and superscipts, how to write non-English (accented)
European text, etc, is discussed (@ref{Text}).


@c HTML <!-- newfile PenColor.html "Gri: pen color" "Getting more control" -->

@node   Pen Color, X-y Plots, Fonts, Getting More Control
@comment  node-name,  next,  previous,  up
@section Colour of ink in pen
@cindex graylevel, explanation
@cindex lines, gray, explanation

The darkness of the ``pen'' used in drawing commands (for either lines or
for text) is set by @code{set graylevel .brightness.}.  A brightness
value of 0 corresponds to black ink, and a brightness value of 1
corresponds to white ink.  Values outside this range are clipped to the
nearer endpoint.  Values inside this range choose a proportional
graylevel in between; for example, @code{set graylevel 0.5} gives a 50
percent gray tone.

The graylevel applies to text as well as lines.  Often you'll want to
draw a gray line and a black label beside it, or you'll want to set a
graylevel temporarily.  Here's how to do it:

@example
# Save old graylevl, set, then reset to old
.old_gray. = ..graylevel..
set graylevel 0.5
draw curve
set graylevel 0
draw label for last curve "TEST"
set graylevel .old_gray.
@end example


The color of the "pen" may be set to any value you can describe with an
RGB (red, green, blue) or HSB (hue, saturation, brightness)
specification, or a color name.  This pen color applies to everything,
even text.

@noindent @b{The} @code{set color \name} @b{command}

Set the pen color to the indicated name.  There are two types of
names: hexadecimal-triplet names and English names.  

@anchor{pen-color-hexadecimal}
Hexadecimal-triplet names are of a form often used in web-pages.  They
consist of exactly 6 characters, which are divided by Gri into three
sets of two characters, specifying the red component, the green
component, and the blue component of the color, respectively.  These
components are in hexadecimal notation, i.e. ranging from 00 to FF,
indicating values from 0 to 255.  For example,
@example
set color ACD4EF
@end example
@noindent
sets a pastel blue color, almost the color of a robin's egg.

The English colors are written simply in the form
@example
set color blue
@end example
@noindent
where the color is from the following list.  (Gri requires that you
use the exact form shown, including the capitilization.)  The color
mixes are identical to those used in X11.

@cindex builtin colors, list of 
@cindex colors, list of

@example
NAME               RED    GREEN  BLUE
"white"            1.000  1.000  1.000
"LightGray"        0.827  0.827  0.827
"darkslategray"    0.184  0.310  0.310
"black"            0.000  0.000  0.000
"red"              1.000  0.000  0.000
"brown"            0.647  0.165  0.165
"tan"              0.824  0.706  0.549
"orange"           1.000  0.647  0.000
"yellow"           1.000  1.000  0.000
"green"            0.000  1.000  0.000
"ForestGreen"      0.133  0.545  0.133
"cyan"             0.000  1.000  1.000
"blue"             0.000  0.000  1.000
"skyblue"          0.529  0.808  0.922
"magenta"          1.000  0.000  1.000
@end example

@noindent
To get more colors than those provided in the above list, use the
@code{read colornames} command.

You should do a test case for your printer to see which colors you find
most to your liking.  You'll want to pick colors that look different
from each other.  In some cases you might want to avoid dithered colors,
since they look too broken on really thin lines.  For example, on my
printer I like the following colors: @code{black}, @code{red},
@code{yellow}, @code{green}, @code{cyan}, and @code{magenta}.


@noindent @b{The} @code{set color rgb .red. .green. .blue.} @b{command}

This command sets the color using the red-green-blue color model.  If
you are familiar with how colors add (e.g. red plus green yields
yellow), then you might like this, but most people find it easier to use
the @code{set color hsb ...} style described below.

Set the individual color components as follows.  The numbers
@code{.red.}, @code{.green.} and @code{.blue.} range from 0 (for no
contribution of that color component to the final color) to 1 (for
maximal contribution).  Values less than 0 are clipped to 0; values
greater than 1 are clipped to 1. EXAMPLES:

@example
set color rgb 0   0   0  # black
set color rgb 1   1   1  # white
set color rgb 1   0   0  # bright red
set color rgb 0.5 0   0  # dark red
set color rgb 0   1   0  # pure green
set color rgb 1   1   0  # yellow: red + green
@end example


@noindent @b{The} @code{set color hsb .hue. .saturation. .brightness.} @b{command}

In this color model, the color ("hue") is specified with a single
parameter.  Many people find this easier than using the corresponding
@code{rgb} command.

@cindex hint, color palette range
Set the individual color components as follows.  The numbers
@code{.hue.}, @code{.saturation.} and @code{.brightness.} range from 0
to 1.  The color, represented by @code{.hue.}, ranges from 0 for pure
red, through 1/3 for pure green, and 2/3 for pure blue, and back to 1
again for pure red.  (HINT: It is a good idea to limit the total range
of hue you use to 2/3, instead of 1; otherwise you'll get confused by
(nearly) repeated colors at the crossover.  For example, limit the hue
to range from 1/3 to 1, or 0 to 2/3.)  The purity of the color,
represented by @code{.saturation.}, ranges from 0 (none of the hue is
visible) to 1 (the maximal amount is present).  Less saturated colours
are like those you would get from mixing black paint into colored
paint.  The brightness of the color, represented by @code{.brightness.},
ranges from 0 (black) to 1 (maximal brightness).  Lowering brightness is
like decreasing the intensity of the light you shine on a painting.

Hue, saturation, and brightness values are all clipped to the range 0 to 1.
EXAMPLES:

@example
set color hsb 0    1   1  # pure, bright red
set color hsb 0    1 0.5  # half black, half red
set color hsb .333 1   1  # pure, bright green
@end example





@c HTML <!-- newfile X-Y.html "Gri: xy plots" "X-Y Plots" -->

@node   X-y Plots, Linegraphs, Pen Color, Top
@comment  node-name,  next,  previous,  up
@chapter X-Y Plots

@menu
* Linegraphs::                  x-y graphs with data connected by line segments
* Scattergraphs::               x-y graphs with data indicated by symbols
* Formula Plots::
@end menu

@node   Linegraphs, Scattergraphs, X-y Plots, X-y Plots    
@comment  node-name,  next,  previous,  up
@section Linegraphs
The following Gri commands will draw a linegraph.  For the output graph
(@ref{Getting More Control}).
@cindex linegraphs
@cindex x-y graphs
@cindex drawing linegraphs
@cindex example 01, linegraph using data in a separate file

This plots a simple linegraph:

@c HTML <A HREF="example1.png">
@c HTML <IMG ALT="Example 1" SRC="example1-tiny.png"
@c HTML ALIGN=top>
@c HTML </A>


@example
# Example 1 -- Linegraph using data in a separate file

open example1.dat      # Open the data file
read columns x y       # Read (x,y) columns
draw curve             # Draw data curve
draw title "Example 1" # Title above plot
@end example

Here's what the command lines mean:

@itemize @bullet
@item
The first line is a comment.  Anything to the right of a hash-mark
@code{#} is considered to be a comment.  (This symbol is also called a
"pound".)

@cindex comments, @code{#} style
@item
The second line is blank.  Gri ignores blank lines between commands.
@item
@code{open example1.dat} tells Gri to open the indicated file (in
the current directory) as an input data file.  You can specify files
outside the current directory by using conventional unix-shell pathnames
(e.g., @code{open ~/data/TS/section1/T_S.dat} or 
@code{open ../data/file.dat}).  You can even use "synonyms" (@ref{Synonyms}.) in
filenames, as in @code{open \BASENAME.dat}.
@item
@code{read columns x y} tells Gri to start reading columnar data,
the first column being @code{x}, the second @code{y}.  @code{x} and
@code{y} are predefined names for whatever ends up on the horizontal and
vertical axes.  

@cindex reading columns of data
@cindex format for columnar data
@cindex data format
@cindex multiple datasets in one file

The number of data needn't be specified.  Gri reads columns until a
blank line or end-of-file is found.  You can tell Gri how many lines to
read with a command like @code{read columns 10 x y}.  Multiple datasets
can reside within one file; provided that they are separated by a single
blank line, Gri can access them by multiple @code{read} commands.

Like C, Gri expects numbers to be separated by one or more spaces or
tabs.  Commas are not allowed.  If the columns were reversed, the
command would be @code{read columns y x}.  If there were an initial
column of extraneous data, the command would be 
@code{read columns * x y}, or @code{read columns x=2 y=3}
(@ref{Read Columns}).
@item
@code{draw curve} tells Gri to draw a curve connecting the points
in the @code{x} and @code{y} columns. A nice scale will be selected
automatically.  (You can change this or any other plot characteristics
easily, as you'll see later.)
@cindex drawing data lines
@item
@code{draw title} tells Gri to write the indicated string
centered above the plot. The title @strong{must} be enclosed in quotes.
@cindex titles, drawing above plot
@cindex drawing titles
@item
@code{quit} tells Gri to exit.
@end itemize

Gri will draw axes automatically, and pick its own scales.

If you wish to draw several curves which cross each other, you should
try using @code{draw curve overlying} instead of
@code{draw curve}.  This will make it easier to distinguish the
different curves.


@node   Scattergraphs, Formula Plots, Linegraphs, X-y Plots
@comment  node-name,  next,  previous,  up
@section Scattergraphs
@cindex scattergraphs
This section contains two examples, the first being a fuller explanation
of all the bells and whistles, the second being a simple explanation
of how to get a very quick plot, given just a file containing a matrix
of grid data.


To get a scattergraph with symbols at the data points, substitute
@code{draw symbol} for @code{draw curve}.  Both symbols and a curve
result if both @code{draw curve} and @code{draw symbols} are used.
See @ref{Getting More Control} for an example.

By default, the symbol used is an x.  To get another symbol, use a
command like @code{draw symbol 0} or @code{draw symbol plus}.  

To change the symbol size from the default of 0.2 cm use commands like
@code{set symbol size 0.1} to set to 1 mm (@ref{Set Symbol Size}).

@subsection Coding data with symbols
@cindex symbols
To get different symbols for different data points, insert symbol codes
from the above list as a column along with the x-y data, and substitute
the command @code{read columns x y z}, and then draw them with
@code{draw symbol}.  Gri will interpret the rounded-integer
values of the @code{z} columns as symbol codes.  Note that even if
you've read in a z column which you intend to represent symbols, it will
be overridden if you designate a specific symbol in your 
@code{draw symbols} command; thus @code{draw symbol 0} puts a @code{+}
at the data points whether or not you've read in a symbol column.

@subsection Drawing a symbol legend
@cindex legend for symbol
@cindex symbol legend

The following example shows how you might write a symbol legend for a
plot.  The legend is drawn 1 cm to the right of the right-hand side of
the axes, with the bottom of the legend one quarter of the way up the
plot; @ref{Draw Symbol Legend}.  The lines in the legend are
double-spaced vertically.  To change the location of the legend, alter
the @code{.legend_x. =} and @code{.legend_y. =} lines.  To change the
spacing, alter the @code{.legend_y. +=} line.

@example
set x axis -1 5 1
set y axis -1 5 1
read columns x y z
0 0 0
1 1 1
2 2 2
3 3 3

draw symbol

# Legend
.leg_x. = @{rpn ..xmargin.. ..xsize.. + 1 +@}
.leg_y. = @{rpn ..ymargin.. ..ysize.. 4 / +@}
draw symbol legend 0 "Foo" at .leg_x. .leg_y. cm
.leg_y. += @{rpn "M" ascent 2 *@}
draw symbol legend 1 "Bar" at .leg_x. .leg_y. cm
.leg_y. += @{rpn "M" ascent 2 *@}
@end example


@subsection Coding data with symbol colors
@cindex color, symbols
@cindex symbols in color
To get different colors for different symbols, read a color code into
the z column, and do for example @code{draw symbol bullet color hue z}.
The numerical color code ranges from 0 (red) through to 1, passing
through green at 1/3 and blue at 2/3.

@node   Formula Plots, Contour Plots, Scattergraphs, X-y Plots
@comment  node-name,  next,  previous,  up
@section Formula Plots
@cindex functions, how to plot
@cindex formulae, how to plot
There are two methods for formula graphs.

@enumerate

@item @strong{Use the system yourself.}
Do as in this example:

@example
open "awk 'BEGIN@{for(i=0;i<3.141;i+=0.05)\
    @{print(i,cos(i))@}@}' |"
read columns x y
close
draw curve
@end example

@noindent

@item @strong{Let Gri calculate things for you}

The simplest is to let Gri
calculate things for you with the @code{create columns from function}
command (@ref{Create}).  The command assumes that you have defined
the synonym called @code{\function} which defines @code{y} in terms of
@code{x}.

Gri uses the program @code{awk} to create the columns, and cannot work
without it.  

Here is an example of using @code{create columns from function}:

@example
show "First 2 terms of perturbation expansion"
set y axis name horizontal
set y name "sea-level"
set x name "$\omega$t"

\b = "0.4" # perturbation parameter b=dH/H
\xmin = "0"
\xmax = "6.28"
\xinc = "3.14 / 20"
\function = "cos(x)"
set x axis \xmin \xmax
create columns from function
draw curve
draw title "SOLID LINE  \function"

\function = "(cos(x)+\b/2*(1-cos(2*x)))"
create columns from function
set dash 1
draw curve
draw title "DASHED LINE \function"

draw title "b = \b"
@end example

Here's another example, in which the curve @code{y = 1/(\int + \sl*x)}
is drawn through some data.  Note how @code{sprintf} is used to set
@code{\xmin} and @code{\xmax} using the scales that Gri has determined
in reading the data.

@example
open file.data
read columns x y
close
draw symbol bullet
\int = "-0.1235"
\sl = "0.003685"
sprintf \xmin "%f" ..xleft..
sprintf \xmax "%f" ..xright..
\function = "1/(\int + x * \sl)"
create columns from function
draw curve
@end example

@end enumerate




@c HTML <!-- newfile ContourPlots.html "Gri: contour plots" "Contour Plots" -->

@node   Contour Plots, Pre-gridded Data, Formula Plots, Top
@comment  node-name,  next,  previous,  up
@chapter Contour Plots
@cindex contours
Contour plots can be done with either pregridded data or randomly
distributed (ie, ungridded) data.
@menu
* Pre-gridded Data::            Contouring f(x1, y1, x2, y2, ...)
* Ungridded Data::              Contouring f(x, y) where (x,y) are not on a grid
@end menu

@node   Pre-gridded Data, Ungridded Data, Contour Plots, Contour Plots
@comment  node-name,  next,  previous,  up
@section Pre-gridded Data
@cindex contours, pre-gridded data
This section presents two examples of contouring pre-gridded data, the
first example illustrating a boilerplate program to contour data
stored in a simple matrix form in a file, the second example
illustrating a case with more control of the details (e.g., a nonuniform
grid).


@subsection Simple example

This example was hardwired to know the size of the grid, etc.  Here's 
an example which is more general, in that it determines the dimensions
of the grid data from using unix system commands.  Note that the grid is
set to run from 0 to 1 in both x and y; you'll most likely want
to change that after you see the initial plot, but this should get you 
started.

@cindex grid data, determining geometry from file
@cindex image data, determining geometry from file

@example
\file = "somefile.dat"
\rows = system wc \file      | awk '@{print $1@}'
\cols = system head -1 \file | awk '@{print NF@}'
set x grid 0 1 /\cols
set y grid 0 1 /\rows
open \file
read grid data \rows \cols
close
draw contour
@end example


@subsection Complicated example

To get a simple contour graph based on pre-gridded
data, with full control of axes, etc, do something like this:
@cindex drawing contours of pregridded data
@cindex example 04 (contouring pregridded data)

@c HTML <A HREF="example4.png">
@c HTML <IMG ALT="Example 4" SRC="example4-tiny.png"
@c HTML ALIGN=top>
@c HTML </A>
@c HTML <A HREF="example4.html">The command-file.</A> <P>

@image{./examples/example4, 300pt}


@c HTML <!--
@example
# Example 4 -- Simple contour graph

#
# Read x-grid; blank-line means stop reading.
read grid x
0
.2
1

# Note that the x-grid was irregular.  The y-grid
# in this example is regular, so we can just set
# it to range from 10 to 20, incrementing by 2.5.
set y grid 10 20 2.5
# Thus we now have a grid 3 wide and 5 high.  Let's
# read the actual data now.
read grid data
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7

# Now draw contours (automatically set; we could
# have done `draw contour 2' to draw contour for
# value 2 or `draw contour 1 10 2' to draw contours
# ranging from 1 to 10 with an increment of 2.)
draw contour
draw title "Example 4"
@end example
@c HTML -->


Here several new things have been introduced.

First, you've got to define a grid in xy space.  This example uses a
non-uniform x-grid, and reads it in from the commandfile.  In this form,
the blank line is essential; it tells Gri that the end of data has been
located; if you like, you can specify the number of lines to read, as in
@code{read grid x 3}.

The y-grid for this example is uniform, however, so it may be specified
with the @code{set y grid} command.  It obtains values (10, 12.5, 15,
17.5, 20).  The @code{set x|y grid} commands accept negative increments.
Furthermore, it is possible to specify the number of steps, rather than
the increment size, by putting @code{/} before the third number; thus
@code{set x grid 0 1 /5} and @code{set x grid 0 1 0.2} are equivalent.

Having defined a grid, it is time to read in the gridded data.  Here this
is done with the @code{read grid data} command.  Since Gri already knows
the grid dimensions, it will read the data appropriately.  You could
also have told it (@code{read grid data 3 5}).  

The first dataline is the top of the y-grid.  In other words, the data
appear in the file just as they would on the graph, assuming that the
x-grid and y-grid both increase.  

Sometimes you want to read in the transpose of a matrix.  Gri lets you
do that.  If the @code{bycolumns} keyword is present at the end of the
@code{read grid} command, the first dataline will contain the first
@strong{column}, of the data.

If you have an extraneous column of data to the left of your data
matrix, do @code{read grid data * 2 3}

Now Gri has the grid in its head.  We tell it to draw some contours
with the @code{draw contour} command.   As the comments in the example
show, the contour values will be selected automatically, but you can
alter that.





@node   Ungridded Data, Images, Pre-gridded Data, Contour Plots    
@comment  node-name,  next,  previous,  up
@section Ungridded data
@cindex contours, ungridded data
@cindex gridding data, advice on methods
When you have f=f(x,y) points at random x and y, you must cast them onto
a grid to contour them.  This is a difficult problem.  There are many
ways to grid data, and all have both good and bad features.  You should
try various methods, and various settings of the parameters of the
methods.  If you have a favorite gridding method that you prefer, you
should probably pre-grid the data yourself.  If not, Gri can do it for
you.  Gri has two methods for doing this, the ``boxcar'' method and the
``objective analysis'' method.  Each method puts holes in the grid
wherever there are too few data to map to grid points, unless you
specifically ask to fill in the whole grid.

The next two sections show first an example, then a discussion of the
methods and how to use them.

@subsection Example
@cindex drawing contours of ungridded data
@cindex Barnes method for gridding data

This example uses data taken from Figure 5 of S. E.  Koch and M.
DesJardins and P. J. Kocin, 1983.  ``An interactive Barnes objective map
anlaysis scheme for use with satellite and conventional data,'', J.
Climate Appl.  Met., vol 22, p. 1487-1503.  Readers should compare
Figures 5 and 6 of that paper to the results shown here.

@c HTML <A HREF="example5.png">
@c HTML <IMG ALT="Example 5" SRC="example5-tiny.png"
@c HTML ALIGN=top>
@c HTML </A>
@c HTML <A HREF="example5.html">The command-file.</A> <P>


@image{./examples/example5}
@cindex example 05 - Contouring ungridded data, from figure


@c HTML <!--
@example
# Example 5 - Contouring ungridded data, from figure
# 5 of Koch et al., 1983, J. Climate Appl. Met.,
# volume 22, pages 1487-1503.
open example5.dat
read columns x y z
close
set x size 12
set x axis 0 12 2
set y size 10
set y axis 0 10 2
draw axes
set line width symbol 0.2
set symbol size 0.2
draw symbol bullet
set font size 8
draw values
set x grid 0 12 0.25
set y grid 0 10 0.25

# Use default method (Barnes)
convert columns to grid

set font size 10
draw contour 0 40 2
set font size 12
draw title "Example 5 -- wind (Fig5 Koch et al, 1983)"
@end example
@c HTML -->



@subsection Discussion of Methods

The various commands for converting columns to a grid are given in
(@ref{Convert Columns To Grid}).  Generally, the Barnes method is best.


@c HTML <!-- newfile Images.html "Gri: image plots" "Image Plots" -->

@node   Images, Reading and Creating Image Data, Ungridded Data, Top
@comment  node-name,  next,  previous,  up
@chapter Image Plots
@cindex image plots, general

Gri can read in images stored in various formats.  It can also create
image data internally, by converting gridded data, which is quite handy
in some contouring applications.

@cindex American Geophysical Union, recommended image gray levels

Note: if your diagram is to be reproduced by a journal, it is unlikely
that the reproduction will be able to distinguish between any two
graylevels which differ by less than 0.2.  Also, graylevels less than
0.2 may appear as pure black, while those of 0.8 or more may appear as
pure white.  These guidelines are as specified by American Geophysical
Union (publishers of J. Geophysical Res.), as of 1998.


@menu
* Reading and Creating Image Data:: Reading image, and creating from grid data
* Image PostScript Output::     How the image is embedded in the PostScript
* Example Image::               How to plot a satellite image
@end menu

@node Reading and Creating Image Data, Image PostScript Output, Images, Images
@comment  node-name,  next,  previous,  up
@section Reading and Creating Image Data
@cindex converting grids to images
@cindex grid, converting to image
@cindex data, images
@cindex image, data format

Gri can do black and white image plots, such as satellite images.  There
are several ways to create image data in Gri
@itemize @bullet
@item
Create images from gridded data using @code{convert grid to image}.  For
examples see @ref{Grayscale Images}),
@ref{Combination},
and @ref{Contouring}.
@item
Read raw ascii image data files.  Use @code{read grid}.
@item
Read PGM (portable graymap) ascii files.  (That is, a file with magic
characters @code{P1} or @code{P3} at the start.)  Use the 
@code{read image pgm} command, for a file opened in ascii mode with
@code{open filename}. 
@item
Read raw binary data, with or without headers.  Use @code{read image},
after skipping any header bytes using the @code{skip} command, for a
file opened in binary mode with @code{open filename binary}.
@item
Read a Sun ``rasterfile'' file (but only in uncompressed form).  Use
@code{read image rasterfile} for a file opened in binary mode with
@code{open filename binary}.
@item
Read a PGM (portable graymap) binary file.  (A file with magic
characters @code{P2} or @code{P4} at the start.)  Use the 
@code{read image pgm} for a file opened in binary mode with
@code{open filename binary}. 
@item
Aside: Images can be converted to grids (for contouring) using
@code{convert image to grid}
(@ref{Convert}).
@end itemize

Once the image is created, its grayscale/colorscale may be manipulated
with the commands @code{set image grayscale} and 
@code{set image colorscale}, which permit linear and histogram-equalized
blendings over the grayscale or color range, or with
@code{read image grayscale} and 
@code{read image colorscale}, which permit reading in the grayscale or
color values individually, one for each of the 256 pixel values.

It is important to understand the structure of image data.  Gri works
only with 8-bit image data.  This means that a given pixel of the image
may have only one of 256 possible values.  The example below uses a
satellite image of surface temperature.  The suppliers of the data
dictate that pixel value 0 corresponds to a temperature of 5C, and a
pixel value of 255 corresponds to 30.5C, so the resolution is 0.1C per
pixel value.  This resolution will be apparent if the output of the
example below is previewed on a grayscale/color monitor --- notice the
quantization in the palette.  This resolution issue is not very
important with satellite images, since you have to use what you are
given by the suppliers of the data.  However, the issue is very important
when you are converting grid data to images.  When Gri converts grid
data to image data, it neccessarily discards information, because the
grid data have resolution to about 6 digits, whereas the image data have
only 8-bit (2-3 digit) resolution.  The @code{set image range} commands
determines the range of this 8-bit resolution in terms of user units.
All other things being equal, it would be preferable to use the smallest
range consistent with the range of your data.  If your grid data ranged
from 0 to 1, say, you might @code{set image range 0 1}.  This would give
a resolution in the image of 1/255 in the user units.  But, when Gri
converts the grid into an image, it will @strong{clip} all data outside
the indicated range.  In this case, any data greater than 1 in the grid
would translate to @strong{exactly} 1 in the image.  Naturally there is a
tradeoff between having a range large enough to encompass any data in
the grid, and a range small enough to yield adequate resolution.  In
most cases, 8-bit resolution will be adequate, but it is good to be
aware of the limitations.  One should always @code{draw image palette},
and check it on a color monitor for bandedness, which is a sign of
resolution problems.



@node  Image PostScript Output, Example Image, Reading and Creating Image Data, Images
@comment  node-name,  next,  previous,  up
@section About The PostScript Output
@cindex image, PostScript output
@cindex postscript output, embedded images

Programmers Note: Gri inserts some special comments in the PostScript
file, to help programmers extract the image data; to extract the
information, you'll have to understand how PostScript handles images.
Gri inserts a single comment line before a line ending in the token
@code{im}:

@example
%BEGIN_IMAGE
170.70 170.70 534.86 534.86 128 128 im
@end example
@noindent
The first four numbers are the (x,y) locations of the lower-left and
upper-right corners of the image, in units of points on the page (72
points = 1 inch).  The fifth and sixth numbers are the width of the
image and the height of the image.  The keyword @code{im} is always
present on this line.  Gri inserts the following comment line at the end
of the image data

@example
%END_IMAGE
@end example

@node  Example Image, Examples, Image PostScript Output, Images
@comment  node-name,  next,  previous,  up
@section Example (Satellite image)
@cindex satellite images

Here's an example that will plot different types of images, depending on
your answers to @code{query} questions.  The file called
@file{\filename} is the data file, in binary format with one byte
(@code{unsigned char} in C) for each pixel, stored with the northwest
pixel first, and the pixel to the east of that next. The file called
@code{\mask} is in the same format, and the numbers are 0 if the point
is over the sea and 1 if over land.  The mask file is used in computing
the histograms, which is done if @code{\histo} is 1.

The file in this example covers 128 * 128 pixels over the Gulf of
Maine. The numbers in @code{\filename} correspond to surface
temperatures according to the equation 

@example
T = 5 + 0.1 * pixel_value
@end example

@noindent
which explains the following lines in the command file:

@example
\0val = "5"             # 0 in image
\255val = "30.5"        # 255 in image
@end example

@cindex images, histogram scaling
@cindex images, linear scaling

Depending on @code{\histo}, the graymap will be linear or
histogram-enhanced. The histogram method
consists of dividing the cumulative histogram for the values in the
image up into 256 levels, and assigning a graylevel to each.  This has
the effect of creating maximal contrast in all ranges of graylevel. It
points up features really well, but it is a nonlinear mapping, so it is
not good for telling you where gradients are strong or weak.

@c HTML <!--
Examples are shown for linear mapping and histogram mapping.
@c HTML -->
@cindex histogram enhancement of image plots
@cindex drawing image plots
@cindex drawing satellite images

@c HTML <A HREF="example6.png">
@c HTML <IMG ALT="Example 6" SRC="example6-tiny.png"
@c HTML ALIGN=top>
@c HTML </A>
@c HTML <A HREF="example6.html">The command-file.</A> <P>


@image{./examples/example6}

@image{./examples/example6histogram}
@cindex example 06, plot IR image of Gulf of Maine

@c HTML <!--
@example
# Example 6 -- Plot IR image of Gulf of Maine
# Define characteristics of norda images
# Note that the pixel to temperature conversion formula is
#
#   Temperature = 5C + pixel_value / 10
#
# where pixel_value ranges from 0 to 255.  Thus, a pixel value of 0
# corresponds to a temperature of 5C, and 255 corresponds to 30.5C;
# this is why the limits \0val and \255val, for use by the `set image
# range' command, take on these values.
\0val = "5"                     # 0 in image
\255val = "30.5"                # 255 in image
.rows. = 128
.cols. = 128
.pixel_width. = 2
.km. = @{rpn .cols. .pixel_width. *@}

# get filenames
query \filename "Name image file" ("example6image.dat")
query \maskname "Name mask  file" ("example6mask.dat")

# get data, then mask, each in 8-bit image format
open \filename 8bit
set image range \0val \255val
read image .rows. .cols. box 0 0 .km. .km.
close
open \maskname 8bit
read image mask .rows. .cols.
close

# find out what grayscale method to use
query \histo "Do histogram enhancement? (yes|no)" ("no")
query \minT  "T/deg for white on page?          " ("10")
query \maxT  "T/deg for black on page?          " ("15")
\incT = "1"

# set up scales. 
set x size 12.8
set y size 12.8
set x name "km"
set y name "km"
set x axis 0 .km. 32
set y axis 0 .km. 32

# plot image, grayscale, and histogram
if @{"\histo" == "yes"@}
    set image grayscale using histogram black \maxT white \minT
else
    set image grayscale black \maxT white \minT
end if
draw image
draw image palette left \minT right \maxT increment \incT
draw image histogram
if @{"\histo" == "yes"@}
    draw title "Example 6: grayscale histogram enhanced"
else
    draw title "Example 6: grayscale linear \minT to \maxT"
end if
@end example
@c HTML -->



@c HTML <!-- newfile Examples.html "Gri: extra examples" "Examples" -->

@node   Examples, Box Plots, Example Image, Top
@comment node-name,  next,  previous,  up
@chapter Real-world examples
@cindex cookbook
The example files in this manual should be available to you directly,
having been installed with Gri; if not, ask your system manager to check
the FTP site.

Additionally, I've collected a few real life examples here.  Other
sources are the Gri cookbook, available at
@url{http://gri.sourceforge.net/gri-cookbook/index.html}.


@menu
* Box Plots::                   Tukey box plots, which show histograms
* Contouring::                  sample contour plot
* Grayscale Images::            create and plot image, from gridded data
* Combination::                 image and contour combination plot
* Fancy::                       fancy plot with lots of tricks
* Legend::                      plot with annotated curves and legend
* Polygons::                    read geometry, then draw polygon
* TS Diagram::                  temperature-salinity diagrams
* PDF Diagram::                 probability-density function
* Running Means::               skyline plot of running means
* Finite Element Model Mesh::   plotting mesh of FEM-type model
* Handling Data::               samples of handling data
@end menu


@c HTML <!-- newfile BoxPlots.html "Gri: box plots" "Examples" -->

@node   Box Plots, Contouring, Examples, Examples
@comment  node-name,  next,  previous,  up
@section Box plots
Box plots were invented by Tukey for eda (exploratory data analysis).
They show nonparametric statistics.  The centre of the box is the
median.  The box edges show the first quartile (q1) and the third
quartile (q3).  The distance from q3 to q1 is called the inter-quartile
range.  The whiskers (lines with crosses on them) extend to the furthest
points still within 1.5 inter-quartile ranges of q1 and q3.  Beyond the
whiskers, all outliers are shown, in open circles up to a distance of 3
inter-quartile ranges beyond q1 and q3, and in closed circles beyond
that.  Below is an example that uses a "new command" to define each box
plot (@ref{Adding New Commands}).

@c HTML <A HREF="example7.png">
@c HTML <IMG ALT="Example 7" SRC="example7-tiny.png"
@c HTML ALIGN=top>
@c HTML </A>
@c HTML <A HREF="example7.html">The command-file.</A> <P>


@image{./examples/example7}

@cindex example 07, box plots of mixing efficiency vs density ratio (meddy)


@c HTML <!--
@example
# Example 7 -- Box plots of mixing efficiency vs density ratio (meddy)

`Draw y boxplot from \file at .x.'
Draw a y boxplot for data in given file, at given 
value of x.
@{
    open \.word4.
    read columns * y
    close
    draw y box plot at \.word6.
@}
if !..publication..
    draw time stamp
end if
set x axis 1 3 1 0.1
set x name "Density Ratio, $R_\rho$"
set x margin 4
set y axis -2 1 1
#
# Must fool gri into not drawing the axes, because the y data
# are already in logspace.
draw axes none
Draw y boxplot from example7a.dat at 1.3
Draw y boxplot from example7b.dat at 1.4
Draw y boxplot from example7c.dat at 1.5
Draw y boxplot from example7d.dat at 1.6
Draw y boxplot from example7e.dat at 1.7
Draw y boxplot from example7f.dat at 1.8
Draw y boxplot from example7g.dat at 1.9
delete y scale
set y name "Efficiency, $\Gamma$"
set y type log
set y axis 0.01 10 1
draw axes
draw title "Example 7 -- Box plot"
@end example
@c HTML -->


@c HTML <!-- newfile ContouringExample.html "Gri: contouring example" "Examples" -->


@node   Contouring, Grayscale Images, Box Plots, Examples
@comment  node-name,  next,  previous,  up
@section Contouring
This example plots a section of dT/drho vs x and rho (actually, sigma-t,
as the label indicates).  The contours are unlabelled; I'm only
interested in the zero crossings.

There are some other useful tricks in this example, such as calling
@code{awk} and @code{wc} from the unix system.

(In the plot shown, all @code{query} questions were answered with
carriage return, yielding the defaults; the @code{-p} flag was specified
on execution, so the time stamp was not drawn.)

@c HTML <A HREF="example8.png">
@c HTML <IMG ALT="Example 8" SRC="example8-tiny.png"
@c HTML ALIGN=top>
@c HTML </A>
@c HTML <A HREF="example8.html">The command-file.</A> <P>


@image{./examples/example8}

@cindex example 08, plot T=T(x,rho) section of eubex data



@c HTML <!--
@example
# Example 8 -- Plot T=T(x,rho) section of eubex data

`Initialize Parameters'
@{
    \FILE_DATA = "example8a.dat" # T vs rho
    \FILE_LOCN = "example8b.dat" # section distances
    set missing value -99.0
    #
    # Following values from ~/eubex/processing/to_rho_bins/do_rho_inter
    \RHO_MIN = "28.1"
    \RHO_MAX = "27.5"
    \RHO_INC = "-0.002"
    \NY = "301"
    \xmin = "350"
    \xmax = "0"
    \xinc = "-100"
    \ymin = "28.1"
    \ymax = "27.8"
    \yinc = "-0.1"
    \zmin = "0"
    \zmax = "2.5"
@}
`Initialize Axes'
/*
Set up axes
*/
@{
    set x name "km"
    set x size 10
    set x axis \xmin \xmax \xinc
    set y name "$\sigma_T$"
    set y size 5
    set y axis name horizontal
    set y axis \ymin \ymax \yinc
    set y format "%.1f"
@}
`Initialize Files'
@{
    query \data "Data file?   " ("\FILE_DATA")
    query \locn "Station locn?" ("\FILE_LOCN")
@}
`Read Data'
@{
    # Read x-locations
    system awk '@{print $2@}' < \locn > TMP
    system wc TMP | awk '@{print $1@}' > NUM
    open NUM
    read .gridx_number.
    close
    system rm NUM 
    open TMP
    read grid x .gridx_number.
    close
    system rm TMP
    # Create y-locations
    set y grid \RHO_MIN \RHO_MAX \RHO_INC
    #
    # Read data
    open \data
    read grid data \NY .gridx_number.
    close
@}
`Plot Contours'
@{
    set graylevel .contour_graylevel.
    set clip on
    set line width 0.5
    draw contour -3 3 0.25 unlabelled
    #
    # wide line at 0 degrees
    set line width 2
    draw contour 0 unlabelled
@}
`Plot Image And Maybe Contours'
@{
    \imagefile = "image"
    set image range \zmin \zmax
    convert grid to image box \xmin  \ymin \xmax \ymax
    query \dohisto "Do histogram scaling? (yes|no)" ("yes")
    \incs = "no"
    if @{"\dohisto" == "yes"@}
	set image grayscale using histogram
    else
	\zinc = "0.25"
	query \incs "In linear scaling, band at an increment of \zinc?" ("yes")
	if @{"\incs" == "yes"@}
	    set image grayscale black \zmin white \zmax increment \zinc
	else
	    set image grayscale black \zmin white \zmax
	end if
    end if
    write image rasterfile to \imagefile
    show "wrote image rasterfile `\imagefile '"
    draw image
    draw image palette
    query \do_contours "Do contours as well (yes|no)" ("yes")
    if @{"\do_contours" == "yes"@}
	Plot Contours
    end if
    draw title "Example 8 -- \data black=\zmin white=\zmax"
    if @{"\dohisto" == "yes"@}
	draw title "Histogram enhanced grayscales"
    else
	if @{"\incs" == "yes"@}
	    draw title "Grayscale banded at intervals of \zinc"
	end if
    end if
@}
Initialize Parameters
Initialize Axes
Initialize Files
Read Data
query \doimage "Draw image (yes|no)" ("no")
if @{"\doimage" == "yes"@}
    .contour_graylevel. = 1	# white contours 
    Plot Image And Maybe Contours
else
    .contour_graylevel. = 0	# black contours 
    Plot Contours
    draw title "Example 8"
end if
@end example
@c HTML -->



@c HTML <!-- newfile ImageExample.html "Gri: image example" "Examples" -->

@node   Grayscale Images, Combination, Contouring, Examples
@comment  node-name,  next,  previous,  up
@section Image created from coarsely gridded data
This example reads gridded ascii station data (@code{Read Data}),
creates an interpolated image (@code{convert grid ...}), and then plots
the image.  

There are some other useful tricks in this example, such as calling
@code{awk} and @code{wc} from the unix system.

(In the plot shown, all @code{query} questions were answered with
carriage return, yielding the defaults; the @code{-p} flag was specified
on execution, so the time stamp was not drawn.)
@cindex axes, automatic drawing of

@c HTML <A HREF="example9.png">
@c HTML <IMG ALT="Example 9" SRC="example9-tiny.png"
@c HTML ALIGN=top>
@c HTML </A>
@c HTML <A HREF="example9.html">The command-file.</A> <P>

@image{./examples/example9}

@cindex example 09, plot dTdrho-rho section


@c HTML <!--
@example
# Example 9 -- Plot dTdrho-rho section

`Initialize Parameters'
@{
    \FILE_DATA = "example9a.dat" # T vs rho
    \FILE_LOCN = "example9b.dat" # section distances
    #
    # Following values from ~/eubex/processing/to_rho_bins/do_rho_inter
    \RHO_MIN = "28.1"
    \RHO_MAX = "27.5"
    \RHO_INC = "-0.002"
    \NY = "301"
    set missing value -99.0
    \xmin = "350"
    \xmax = "0"
    \xinc = "-100"
    \ymin = "28.1"
    \ymax = "27.8"
    \yinc = "-0.1"
    \zmin = "-10"		# black
    \zmax = "0"			# white
@}
`Initialize Axes'
Set up axes.
@{
    set x name "km"
    set x size 10
    set x axis \xmin \xmax \xinc
    set y size 5
    set y name "$\sigma_T$"
    set y axis name horizontal
    set y axis \ymin \ymax \yinc
    set y format %.1lf
    draw axes none
@}
`Initialize Files'
@{
    query \data "Data file?   " ("\FILE_DATA")
    query \locn "Station locn?" ("\FILE_LOCN")
@}
`Read Data'
@{
    # Read x-locations
    system awk '@{print $2@}' < \locn > TMP
    system wc TMP | awk '@{print $1@}' > NUM
    open NUM
    read .gridx_number.
    close
    system rm NUM 
    open TMP
    read grid x .gridx_number.
    close
    system rm TMP
    # Create y-locations
    set y grid \RHO_MIN \RHO_MAX \RHO_INC
    #
    # Read data
    open \data
    read grid data \NY .gridx_number.
    close
@}
Initialize Parameters
Initialize Axes
Initialize Files
Read Data
set image range \zmin \zmax
set image colorscale hsb 0 1 1 \zmin   hsb .6 1 1 \zmax
convert grid to image box \xmin  \ymin \xmax \ymax
#
# Draw the image, then draw the axes.  Note that the image has
# extends beyond the axes frame, so we will turn clipping
# on before drawing it, to make a clean picture.
set clip postscript on
draw image
set clip postscript off
draw axes

#
# All done.
draw title "Example 9"
if @{"\dohisto" == "yes"@}
    draw title "Histogram enhanced grayscales"
end if
@end example
@c HTML -->


@c HTML <!-- newfile ImageWithContours.html "Gri: image and contours" "Examples" -->

@node   Combination, Fancy, Grayscale Images, Examples
@comment  node-name,  next,  previous,  up
@section Combination of image and contour
@cindex image plot, with contours
@cindex contours on images

The following example reads gridded data and creates an image as in the
previous example, but also superimposes unlabelled white contour lines.

(In the plot shown, all @code{query} questions were answered with
carriage return, yielding the defaults; the @code{-p} flag was specified
on execution, so the time stamp was not drawn.)
@cindex example 10 (image plot with contours)

@c HTML <A HREF="example10.png">
@c HTML <IMG ALT="Example 10" SRC="example10-tiny.png"
@c HTML ALIGN=top>
@c HTML </A>
@c HTML <A HREF="example10.html">The command-file.</A> <P>

@image{./examples/example10}

@cindex example 10, draw image plot of flushing of dye out of cove


@c HTML <!--
@example
# Example 10 -- Draw image plot of flushing of dye out of cove
if !..publication..
    draw time stamp
end if
\file = "example10.dat"
query \contours "Superimpose contours? (yes|no)" ("yes")
query \file     "Input file name               " ("\file")
open \file
read line \header
read \D
read .nx.
read .ny.
set x name "distance along cove"
set y name "time"
set x grid 0 1 /.nx.
set x axis 0 1 0.5 0.1
set y grid 0 .ny. / .ny.
set y axis 0 .ny.
read grid data * * .ny. .nx.
set image range 0 20
set image grayscale black 20 white 0 increment 5
convert grid to image 
draw image
if @{"\contours" == "yes"@}
    set graylevel 1.0
    draw contour 0 20 1 unlabelled
    set graylevel 0.0
end if
draw axes
draw image palette left -1 right 21 increment 5
draw title "Example 10 -- file=\file header=`\header'"
@end example
@c HTML -->

@ifhtml
A color version of this is possible using @code{set image colorscale}
as shown here:
@cindex example 10color, draw color image plot
@end ifhtml

@c HTML <A HREF="example10color.png">
@c HTML <IMG ALT="Example 10 in colour" SRC="example10color-tiny.png"
@c HTML ALIGN=top>
@c HTML </A>
@c HTML <A HREF="example10color.html">The command-file.</A> <P>


@c HTML <!--
@example
# Example 10color -- Draw color image plot

# Test various colorscales.
# INSTRUCTIONS: Uncomment one of the following '\scale = ' statements

# CASE 1: From black at high values to white at low values
#\scale = "rgb 0 0 0 20.0 rgb 1 1 1  0.0 increment 5"

# CASE 2: From skyblue at 20 to tan for 0; traverse RGB space
#         See also case 5, which names the colors.
#\scale = "rgb 0.529 0.808 0.922 20.0 rgb 0.824 0.706 0.549 0.0 increment 5"

# CASE 3: From skyblue at 20 to tan for 0; traverse HSB space
#         Is it just me, or is this uglier than case 2?
#\scale = "hsb 0.548 0.426 0.922 20.0 hsb 0.095 0.334 0.824 0.0 increment 5"

# CASE 4: Use a spectrum; traverse HSB space
#\scale = "hsb 0 1 1 20.0 hsb 0.6666 1 1  0.0 increment 5"

# CASE 5: From skyblue to tan, traversing RGB space (by default)
#         (Compare case 2, which uses similar endpoints, with
#         colors specified with RGB values, and larger increment.)
#\scale = "skyblue 20.0 tan 0.0 increment 2"

# CASE 6: From skyblue to tan, traversing RGB space (by default)
#         Compare 2 and 5; note this has continuous increment
#\scale = "skyblue 20.0 tan 0.0"

# CASE 7: From blue to brown
\scale = "blue 20.0 brown 0.0 increment 2.5"

open example10.dat
read line \header
read \D
read .nx.
read .ny.
set x name "distance along cove"
set y name "time"
set x grid 0 1 /.nx.
set x axis 0 1 0.5 0.1
set y grid 0 .ny. / .ny.
set y axis 0 .ny.
read grid data * * .ny. .nx.
set image range 0 20
convert grid to image 
set image colorscale \scale
draw image

# Draw contours in white ink
set graylevel 1.0
draw contour 0 20 1 unlabelled
set graylevel 0.0

draw axes                               # redraw in case whited out 
draw image palette left -1 right 21 increment 5
set font size 9

# Title tells what method used
draw title "Used `draw image colorscale \scale'"
@end example
@c HTML -->



@c HTML <!-- newfile FancyPlot.html "Gri: adding bells and whistles" "Examples" -->


@node   Fancy, Legend, Combination, Examples
@comment  node-name,  next,  previous,  up
@section Fancy x-y linegraph
@cindex fancy plot
The following code shows a fancy plot with lots of bells and whistles.
@cindex multiple panels, example
@cindex labels, example
@cindex graylevel for lines, example

@c HTML <A HREF="example11.png">
@c HTML <IMG ALT="Example 11" SRC="example11-tiny.png"
@c HTML ALIGN=top>
@c HTML </A>
@c HTML <A HREF="example11.html">The command-file.</A> <P>



@image{./examples/example11, 400pt}

@cindex example 11, fancy plot



@c HTML <!--
@example
# Example 11 -- Fancy plot
# Pen sizes, etc.
#
.thin. = 0.5                    # for whole data set
.thick. = 2                     # for bravo time period
.gray_for_guiding_lines. = 0.75 # for guiding lines
.tmin. = 1964                   # time axis
.tmax. = 1974
.tinc. = 5
.tincinc. = 1
.missing_value. = -9
\file = "./example11.dat"
#
# Guiding lines to draw on both panels.
#
.1xl. = 1962
.1yb. = -3
.1xr. = 1968
.1yt. = 3
.1slope. = @{rpn .1yt. .1yb. - .1xr. .1xl. - /@}
.1intercept. = @{rpn .1yb. .1slope. .1xl. * -@}
.2xl. = 1966.4
.2yb. = 3
.2xr. = 1980
.2yt. = -1
.2slope. = @{rpn .2yt. .2yb. - .2xr. .2xl. - /@}
.2intercept. = @{rpn .2yb. .2slope. .2xl. * -@}
#
# PANEL 1: Bravo time period.
#
set x margin 3
set x size 15
set y margin 3
set y size 5
# Draw border big enough for this and next panel.
draw border box @{rpn ..xmargin.. 2 -@} \
    @{rpn ..ymargin.. 2 -@} \
    @{rpn ..xmargin.. ..xsize.. + 2 +@} \
    @{rpn ..ymargin.. ..ysize.. 2 * 3 + + 2 +@} \
    0.2 0.75
set missing value .missing_value.
set ignore error eof
set x name "Year"
set x axis .tmin. .tmax. .tinc. .tincinc.
set y name "Area / 10$^5$km$^2$"
set y axis -3 3 1
draw axes
#
# Draw index lines 1 and 2.
# 
# Upward sloped line.
set line width .thin.
set graylevel .gray_for_guiding_lines.
if @{rpn .1intercept. ..xright.. .1slope. * + ..ytop.. <@}
    draw line from              \
        ..xleft..               \
        @{rpn .1intercept. ..xleft.. .1slope. * +@} \
        to                      \
        @{rpn ..ytop.. .1intercept. - .1slope. /@} \
        ..ytop..
else
    draw line from              \
        ..xleft..               \
        @{rpn .1intercept. ..xleft.. .1slope. * +@} \
        to                      \
        ..xright..              \
        @{rpn .1intercept. ..xright.. .1slope. * +@}
end if
set graylevel 0
# 
# Downward sloped line.
set line width .thin.
set graylevel .gray_for_guiding_lines.
if @{rpn .2intercept. ..xleft.. .2slope. * + ..ytop.. <@}
    draw line from              \
        @{rpn ..ytop.. .2intercept. - .2slope. /@} \
        ..ytop..                \
        to                      \
        ..xright..              \
        @{rpn .2intercept. ..xright.. .2slope. * +@}  
else
    draw line from              \
        ..xleft..               \
        @{rpn .2intercept. ..xleft.. .2slope. * +@} \
        to                      \
        ..xright..              \
        @{rpn .2intercept. ..xright.. .2slope. * +@}
end if
set graylevel 0
#
# Finally, draw the data curve on top, after first
# whiting out a background.
set input data window x .tmin. .tmax.
open \file
read columns x y
close
y /= 1e5
set line width ..linewidthaxis..
draw zero line
set line width @{rpn .thick. 3 *@}
set graylevel 1
draw curve
set graylevel 0
set line width .thick.
draw curve

#
# PANEL 2: Longer timescale.
#
delete x scale
set x margin bigger 5
set x size 10
set x name ""
set y name ""
set y margin bigger @{rpn ..ysize.. 3 +@}
#
# Draw long data set in thin pen.
set input data window x off
open \file
read columns x y
close
y /= 1e5
#
# Draw guiding lines, axes, etc.
set x axis 1952 1980 5 1
draw axes frame
set line width .thin.
set graylevel .gray_for_guiding_lines.
draw line from .1xl. .1yb. to .1xr. .1yt.
draw line from .2xl. .2yb. to .2xr. .2yt.
set graylevel 0
set line width ..linewidthaxis..
draw zero line


draw x axis at bottom
.old. = ..fontsize..
set font size 0
draw y axis at left
set font size .old.
delete .old.
#
# Draw full curve (first whiting out region around it).
set line width @{rpn .thin. 4 *@}
set graylevel 1
draw curve
set graylevel 0
set line width .thin.
draw curve
#
# Draw bravo time period (first whiting out region around it).
set input data window x .tmin. .tmax.
open \file
read columns x y
close
y /= 1e5
set line width @{rpn .thick. 3 *@}
set graylevel 1
draw curve
set graylevel 0
set line width .thick.
draw curve
#
# Done
set font size 20
\label = "Example 11 (Arctic ice anomaly)"
draw label "\label" at          \
    @{rpn 8.5 2.54 * "\label" width - 2 /@} \
    @{rpn ..ytop.. yusertocm 0.7 +@} \
    cm
if !..publication..
    draw time stamp
end if
@end example
@c HTML -->




@c HTML <!-- newfile Legend.html "Gri: drawing legends for curve types etc" "Examples" -->


@node   Legend, Polygons, Fancy, Examples
@comment  node-name,  next,  previous,  up
@section Legends and annotated lines
@cindex drawing legends
@cindex legends
@cindex annotating lines
The following example shows how to handle annotated curves and legends. 


@c HTML <A HREF="example12.png">
@c HTML <IMG ALT="Example 12" SRC="example12-tiny.png"
@c HTML ALIGN=top>
@c HTML </A>
@c HTML <A HREF="example12.html">The command-file.</A> <P>

@image{./examples/example12}

@cindex example 12, linegraph with key inside plot


@c HTML <!--
@example
# Example 12 -- Linegraph with key inside plot
set font size 10                # points (1in = 72pt)
set x size 10                   # cm
set y size 10                   # cm
set x name "Height"
set y name "Total Energy"

# Following axis setups not necessary; will autoscale if you
# remove these.
set x margin 3
set x axis 800 960 20
set y margin 3
set y axis -0.4 1 0.2

# Read data.  Format is columns (x, y1, y2, y3, y4)
open example12.dat
read columns x y
draw curve
draw label for last curve "1"

rewind
set line width @{rpn ..linewidth.. 1.5 *@}
read columns x * y
draw curve
draw label for last curve "2"

rewind
set line width @{rpn ..linewidth.. 1.5 *@}
read columns x * * y
draw curve
draw label for last curve "3"

rewind
set line width @{rpn ..linewidth.. 1.5 *@}
read columns x * * * y
draw curve
draw label for last curve "4"

# Draw the key.  
# NOTES:
# (1) This key is inside the plot; its location was chosen 
#     after looking at the data.  To put the key in a different 
#     location, alter the .key_topleft_x. and .key_topleft_y. 
#     variables.  For example, you could put the key to the 
#     right of the plot by changing the next line to:
#     `.key_topleft_x. = @{rpn ..xsize.. 0.5 +@}'
# (2) The variable .dy_inc. is the spacing between lines in
#     the key.  It should be OK even if you change the
#     font size above.
.key_topleft_x. = 0.5           # cm right of left axis
.key_topleft_y. = 0.5           # cm below top axis
.dy_inc. = @{rpn ..fontsize.. pttocm 1.5 *@}

draw label "1 = Model 1A" at    \
    @{rpn ..xleft.. xusertocm .key_topleft_x. +@} \
    @{rpn ..ytop.. yusertocm .key_topleft_y. -@} cm

.key_topleft_y. += .dy_inc.
draw label "2 = Model 2A" at    \
    @{rpn ..xleft.. xusertocm .key_topleft_x. +@} \
    @{rpn ..ytop.. yusertocm .key_topleft_y. -@} cm

.key_topleft_y. += .dy_inc.
draw label "3 = Model 1B" at    \
    @{rpn ..xleft.. xusertocm .key_topleft_x. +@} \
    @{rpn ..ytop.. yusertocm .key_topleft_y. -@} cm

.key_topleft_y. += .dy_inc.
draw label "4 = Model 2B" at    \
    @{rpn ..xleft.. xusertocm .key_topleft_x. +@} \
    @{rpn ..ytop.. yusertocm .key_topleft_y. -@} cm

draw title "Example 12 -- Total heating vs height of boundary layer"
@end example
@c HTML -->


@c HTML <!-- newfile Polygons.html "Gri: drawing polygons" "Examples" -->

@node   Polygons, TS Diagram, Legend, Examples
@comment  node-name,  next,  previous,  up
@section Drawing gray polygons
@cindex polygons, filled
@cindex gray level, example for polygons
The following example shows how to draw polygons of a graylevel that is
read in.  It also draws a bullet (within the polygon).  See the help
lines at the start.

@example
`Draw Polygon And Bullet'
Draw a polygon of a given graylevel, with a bullet
(black dot) at an indicated location.  The polygon
coordinates are read in by this command, as are
the graylevel and the location of the bullet.

Variables used:
  .black.
  .white.

Input data read: 

line   1:
  A code (which is ignored) and a graylevel
  to draw the polygon with. The value for this
  graylevel ranges from .black. (which codes
  to black ink on the paper) to .white.
  (which codes to blank paper).

line   2:
  An (x,y) location for the bullet.

line   3:
  Skipped.

line 4-n:
  Locations of vertices of polygon, ended with a blank line.
@{
  read .code. .graylevel. # Read line 1
  read .x. .y.            # Read line 2
  skip                    # Skip line 3
  read columns x y        # Read a polygon
  # Adjust .graylevel. to range between 0
  # (for black ink) and 1 (for white paper),
  # then set graylevel and draw polygon. 
  .graylevel. = @{rpn .graylevel. \
      .black. - .white. .black. - /@}
  set graylevel .graylevel.
  draw curve filled
  # Draw black bullet
  set graylevel 0
  draw symbol bullet at .x. .y.
  # Clean up local storage.
  delete .code. 
  delete .graylevel.
  delete .x.
  delete .y.
@}
@end example


@c HTML <!-- newfile TSDiagram.html "Gri: drawing TS diagrams" "Examples" -->

@node   TS Diagram, PDF Diagram, Polygons, Examples
@comment  node-name,  next,  previous,  up
@section Temperature-Salinity Diagram
@cindex oceanographic plots
@cindex oceanographic plots, isopycnals on TS diagrams
@cindex T-S diagram, example of drawing
@cindex temperature-salinity diagram
@cindex isopycnals
Here is how you might draw an oceanographic "TS" (temperature salinity)
diagram: 
@cindex example 13, TS diagram, with isopycnals

@c HTML <A HREF="example13.png">
@c HTML <IMG ALT="Example 13" SRC="example13-tiny.png"
@c HTML ALIGN=top>
@c HTML </A>
@c HTML <A HREF="example13.html">The command-file.</A>


@image{./examples/example13}

@c HTML <!--
@example
# Example 13 -- TS diagram, with isopycnals
#
# Draw Axes
set line width axis 0.25
set line width 0.75
.tic_size. = 0.1                # cm
set symbol size 0.03
.isopycnal_fontsize. = 8        # for isopycnal labels
.axes_fontsize. = 10            # for axes
set font size .axes_fontsize.
set x margin 2
set x size 10
set y margin 2
set y size 10
.Smin. = 33.4
.Smax. = 35.0
.Sinc. = 0.5
.Sincinc. = 0.1
.thetamin. = -2.0
.thetamax. = 11.0
.thetainc. = 1.0
.thetaincinc. = 1.0
set tic size .tic_size.
set x name "Salinity / PSU"
set y name "Potential Temperature / $\circ$C"
set x axis .Smin. .Smax. .Sinc. .Sincinc.
set y axis .thetamin. .thetamax. .thetainc. .thetaincinc.
set axes style offset
draw axes 1
set clip on
.old. = ..fontsize..
set font size .isopycnal_fontsize.
draw isopycnal 26.00
draw isopycnal 26.50 unlabelled
draw isopycnal 27.00
draw isopycnal 27.50 unlabelled
draw isopycnal 28.00
draw isopycnal 28.50 unlabelled
draw isopycnal 29.00
set clip off
set font size .old.
#
# Draw the data.
open example13.dat
read columns x y
draw symbol bullet
set font size ..
draw title "Example 13 -- TS diagram, with isopycnals"
@end example
@c HTML -->

@c HTML <!-- newfile PDFDiagram.html "Gri: PDF Diagram" "Examples" -->


@node   PDF Diagram,  Running Means, TS Diagram, Examples
@comment  node-name,  next,  previous,  up
@section Probability Density Function Diagram
@cindex probability density function diagram
@cindex perl, use to create probability density function
A common application is to draw the probability density function for
(x,y) data.  Gri has no builtin facility to do this, but the following
example shows how to create the gridded PDF data using a call to the
@code{perl} system command.  The gridded data thus generated are
contoured, creating a PDF diagram.  As the comments in the program
state, the first call to Perl is specific to a particular dataset, and
can be ignored on first reading; it just creates the file
@file{tmp-xy.\.pid.}.

@example
# Draw prob-density-function TS diagram for Bravo data

# This first call to perl is specific to the
# particular (weird) dataset.  All that matters
# is that a file of (x,y) data is created, and
# stored in the file called `tmp-xy.\.pid.'
system perl <<"EOF"
#
# Slurp in x[], y[] data
$dir = "/users/dek/kelley/Labrador/bravo/data";
$Sfile = "$dir/S_25db_1day";
$Tfile = "$dir/T_25db_1day";
open(S, "$Sfile") || die "Can't open input $Sfile";
open(T, "$Tfile") || die "Can't open input $Tfile";
open(ST, ">tmp-xy.\.pid.") 
    || die "Can't open tmp-xy.\.pid.";
$day = 5;
$year = 1964;
while(<S>) @{
    @@S = split;
    $_ = <T>;
    @@T = split;
    if (240 < $day && $day < 360) @{
        for ($i = 0; $i < $#S; $i++) @{ #all depths
            print ST "$S[$i] $T[$i]\n";
        @}
    @}
    $day += 1;
    if ($day > 365) @{
        $year++;
        $day = 0;
    @}
    if ($year > 1967) @{ last; @}
@}
EOF

#
# Create 2D PDF for (x,y) data in file \infile
# storing the results in \outfile.  X ranges
# between the indicated limits, with the indicated
# binsize, as does y.  The synonyms defined
# on the next 4 lines are the only input this
# perlscript needs; the perlscript itself is
# quite general.  For details of what it does,
# particularly the scaling of the PDF, see
# the perl comments.
\xmin = "33.5"; \xmax = "35.5"; \xinc = "0.05";
\ymin = "-2.0"; \ymax = "11.0"; \yinc = "0.25";
\infile = "tmp-xy.\.pid."
\outfile = "tmp-grid.\.pid."
system perl <<"EOF"
#
# Prepare 2 dimensional probability-density-function
# dataset for contouring by Gri.  This reads (x,y)
# data from a file called $infile (defined below)
# and creates an output file called $outfile 
# (also defined below) containing the
# x-grid, the y-grid, and then the grid data, 
# suitable for reading/contouring by the Gri
# commands
#       open tmp-grid.\.pid.
#       read .number_of_data.
#       read grid x
#       read grid y
#       read grid data
#       draw contour
# 
# The values in the output grid are defined so
# that they sum to the reciprocal of the 
# product of the x binsize and y binsize (see
# definition of $factor below).
#
$xmin = \xmin; $xmax = \xmax; $xinc = \xinc;
$ymin = \ymin; $ymax = \ymax; $yinc = \yinc;
$infile = "\infile";
$outfile = "\outfile";
#
# Slurp in the x[], y[] data, storing 
# the total number of data in $n.
open(IN,  "$infile")   || die "Can't open infile";
open(OUT, ">$outfile") || die "Can't open outfile";
$n = 0;
while(<IN>) @{
    ($x[$n], $y[$n]) = split;
    $n++;
@}
#
# Zero out matrix (stored in a linear array scanned 
# as one reads a book).
$cols = int(1 + ($xmax - $xmin) / $xinc);
$rows = int(1 + ($ymax - $ymin) / $yinc);
for ($y = $ymax; $y > $ymin; $y -= $yinc) @{
    for ($x = $xmin; $x < $xmax; $x += $xinc) @{
        $l = int(($x - $xmin) / $xinc 
            + $cols * int(($y - $ymin) / $yinc));
        $sum[$l] = 0;
    @}
@}
#
# Cumulate (x,y) data into the matrix
$inside = 0;
for ($i = 0; $i < $n; $i++) @{
    if ($ymin <= $y[$i] && $y[$i] <= $ymax 
        && $xmin <= $x[$i] && $x[$i] <= $xmax) @{
        $l = int(($x[$i] - $xmin) / $xinc 
            + $cols * int(($y[$i] - $ymin) / $yinc));
        $sum[$l]++;
        $inside++;
    @} else @{
        print STDERR "($y[$i], $x[$i]) clipped\n";
    @}
@}
#
# Print number of points (to allow renormalization
# if the user wishes)
print OUT "$inside\n";
#
# Print x grid, y grid, then grid itself
for ($x = $xmin; $x < $xmax; $x += $xinc) @{
    printf OUT "%lg\n", $x;
@}
print OUT "\n";
for ($y = $ymax; $y > $ymin; $y -= $yinc) @{
    printf OUT "%lg\n", $y;
@}
print OUT "\n";
#
# The $factor variable scales the PDF.
$factor = 1 / $xinc / $yinc / $inside;
for ($y = $ymax; $y > $ymin; $y -= $yinc) @{
    for ($x = $xmin; $x < $xmax; $x += $xinc) @{
        $l = int(($x - $xmin) / $xinc 
            + $cols * int(($y - $ymin) / $yinc));
        printf OUT "%lg ", $factor * $sum[$l];
    @}
    print OUT "\n";
@}
EOF

# Axes
set x margin 3
set x margin 6
set x name "Salinity [PSU]"
set y name "Potential Temperature [$\circ$C]"
set x axis 34.5 34.8 0.1
set y axis 5 9 1
draw axes

# PDF
open tmp-grid.\.pid.
read .number_of_data.
read grid x
read grid y
read grid data
.smooth. = 0

# Contours.  Use clipping, since the axes are
# zooming in on part of the PDF.
set font size 8
set contour label position centered
set clip postscript on
set line width rapidograph 4x0
draw contour 0.2 2.2 0.4 unlabelled
set line width rapidograph 0
draw contour 0.4 2.4 0.4 
set clip postscript off
end if
@end example


@c HTML <!-- newfile RunningMeans.html "Gri: running means" "Examples" -->


@node   Running Means, Finite Element Model Mesh, PDF Diagram, Examples
@comment  node-name,  next,  previous,  up
@section Running-Mean Skyline Diagram
@cindex  Running-Mean Skyline Diagram
Timeseries data are often cast into running means; e.g. a temperature
record might be cast into monthly mean values.  The following example
shows how to use a perl script to accomplish this easily, producing a
graph with both the raw data (bullets) and the running mean (a skyline
plot).

@example
`Bin with  x .min. .max. .inc. \in_file \out_file'

Creates \out_file from \in_file.  In each of these
files, column 1 represents x and column 2 represents
y.  The \out_file file contains the average values
of y in x bands of width .inc., centred at .min.,
(.min.+.inc.), up to .max, and with missing values
inserted in bands with no x-data in \in_file.
Each x-band is represented in \out_file by a
plateau in y, and adjacent bands with
non-missing data are connnected by vertical
lines; the effect is a skyline plot of the
banded means.  Sample application: plot
monthly means of a variable.
@{
    if @{rpn \.words. 8 !=@}
        show "ERROR: `\.proper_usage.' called without"
        show " giving all parameters"
        quit 1
    end if
    system perl <<"EOF"
    $min = \.word3.;
    $max = \.word4.;
    $inc = \.word5.;
    open(IN,   "\.word6.")
        || die "`\.proper_usage': no \\in_file";
    open(OUT, ">\.word7.")
        || die "`\.proper_usage': no \\out_file";

    $n = ($max - $min) / $inc;
    #
    # Set up bins.
    for($i = 0; $i <= $n; $i++) @{
       $xx[$i] = 0;
       $yy[$i] = 0;
       $nn[$i] = 0;
    @}
    while(<IN>) @{
        ($x, $y) = split(' ');
        $i = int(0.5 + ($x - $min) / $inc);
        $i =      0 if $i <      0;
        $i = $n - 1 if $i > $n - 1;
        $xx[$i] += $x;
        $yy[$i] += $y;
        $nn[$i]++;
    @}
    for($i = 0; $i <= $n; $i++) @{
        if ($nn[$i] > 0) @{
            $xx[$i] /= $nn[$i];
            $yy[$i] /= $nn[$i];
            $xleft  = $min + $inc * ($i - 0.5);
            $xright = $min + $inc * ($i + 0.5);
            #
            # If datum to left non-missing,
            # just draw vertical line
            # down to the last yy value.
            if ($i > 0 && $nn[$i - 1] > 0) @{
                print OUT "$xleft $yy[$i - 1]\n";
            @} else @{
                print OUT "$xleft \.missingvalue.\n"
            @}
            print OUT "$xleft  $yy[$i]\n";
            print OUT "$xright $yy[$i]\n";
        @}
    @}
EOF
@}

# Bin into months
Bin with x 1964 1974 @{rpn 1 12 /@} \
    timeseries.dat tmp.dat
open tmp.dat
read columns x y
close
draw curve                      # skyline of means
open timeseries.dat
read columns x y
close
draw symbol bullet              # data
system rm -f tmp.dat            # clean up
@end example


@c HTML <!-- newfile FEM.html "Gri: Finite Element Model mesh" "Examples" -->


@node   Finite Element Model Mesh, Handling Data, Running Means, Examples
@comment  node-name,  next,  previous,  up
@section Finite Element Model mesh
@cindex  Finite Element Model mesh
@cindex FEM mesh plot
@cindex mesh plot for FEM

Finite Element Models (used in fluid mechanics) employ non-rectangular
meshes, and plotting these meshes requires a few intermediate steps.
Consider the common case of triangular elements.  Suppose two data files
exist describing the mesh, the first, @file{model.nodes} say, consists
of a description of the x-y coordinates of the nodes (vertices) of the
triangles.  The second, @file{model.elements} say, consists of a
description of which triplet of nodes defines each triangle in the mesh.
Here, from a sample application, is a node file called
@file{model.nodes}:

@example
1	1	1
2	2	1
3	1	2
4	3	1.5
5	2	2
6	1.5	3
@end example
@noindent
Here is the corresponding file of the elements, called @file{model.elements}

@example
1	1	2	3
2	2	5	3
3	2	4	5
4	3	5	6
@end example

@noindent
In each of these files, the first column is a reference number.  Thus,
@file{model.elements} indicates that the first triangle is defined by
the nodes numbered @code{1}, @code{2} and @code{3} as defined in
@file{model.nodes}.  More specifically, the triangle is defined by
vertices at (x,y) locations (1,1), (2,1), and (1,2).

A Gri program, named @file{FEM.gri}, to draw the nodes is the following.

@example
set missing value -99.99
# Create data using perl-script ...
system FEM.pl model.nodes model.elements > tmp
# ... then plot it ...
open tmp
read columns x y
close
draw curve
# ... and, finally, clean up the temporary file
system rm tmp
@end example

@noindent
The work of interpreting the data files is done by the perlscript that
follows, named @file{FEM.pl}

@example
#!/usr/bin/perl -w
$missing = -99.99;              # missing value
$node_file = $ARGV[0];
$element_file = $ARGV[1];
open (NODE, $node_file)
    or die "Cannot open '$node_file' file";
open (ELEM, $element_file)
    or die "Cannot open '$element_file' file";

# Read in node information, creating arrays 
# named $node_x[] and $node_y[]. Check that 
# the first column (the index) makes sense.
$max_node = 1;
while(<NODE>) @{
    ($index, $node_x[$max_node], $node_y[$max_node])
        = split;
    die "Node mismatch at index=$index" 
        if ($index != $max_node);
    $max_node++;
@}

# Read in triangle elements, into arrays
# $a[], $b[], and $c[].  Check that the 
# first column (the index) makes sense.
$max_elem = 1;
while(<ELEM>) @{
    ($index, $a[$max_elem], $b[$max_elem], $c[$max_elem]) 
        = split;
    die "Element mismatch at index=$index" 
        if ($index != $max_elem);
    $max_elem++;
@}

# Print out triangles suitable for plotting in gri.
for ($i = 1; $i < $max_elem; $i++) @{
    print $node_x[$a[$i]], " ", $node_y[$a[$i]], "\n";
    print $node_x[$b[$i]], " ", $node_y[$b[$i]], "\n";
    print $node_x[$c[$i]], " ", $node_y[$c[$i]], "\n";
    # Repeat first, to close the triangle.
    print $node_x[$a[$i]], " ", $node_y[$a[$i]], "\n";
    print $missing, " ", $missing, "\n";
@}
@end example

@c HTML The resultant image is below.
@c HTML <IMG ALT="FEM image" SRC="FEM.png">




@c HTML <!-- newfile HandlingData.html "Gri: handling data" "Examples" -->

@node   Handling Data, Handling Headers, Finite Element Model Mesh, Examples
@comment node-name,  next,  previous,  up
@section Handling Data
@cindex data, dealing with odd datasets

@menu
* Handling Headers::            How to skip or read header lines
* Ignoring Columns::            Ignoring columns that are not of interest
* Column Algebra::              How to do algebra on columns
* Combining Columns::           Combining columns from separate files
* Plotting Several Columns::    Plotting several y-columns vs one x-column
@end menu


@c HTML <!-- newfile HandlingHeaders.html "Gri: handling headers" "Examples" -->

@node   Handling Headers, Ignoring Columns, Handling Data, Handling Data
@comment  node-name,  next,  previous,  up

@subsection Handling headers

@cindex skipping header lines
@cindex header lines, skipping
@b{Case 1 -- known number of header lines.}
This is easy.  If you know that the file has, say, 10 header lines, you
can just do this:

@example
open file
skip 10
read columns x y
...
@end example

@b{Case 2 -- header itself indicates number of header lines.}
Quite often the first line of a file will indicate the number of header
lines.  For example, suppose the first line contains a single number,
indicating the number of header lines to follow:

@example
open file
read .skip.
skip .skip.
read columns x y
...
@end example

@b{Case 3 -- header lines marked by a textual key.}
Sometimes header lines are indicated by a textual key, for example, the
characters @code{HEADER} at the start of the line in the file.  The easy
way to skip such a header is to use a system command.  Depending on your
familiarity with the operating system (here presumed to be Unix), you
might choose to use Grep, Awk, or Perl.  Here are examples:

@example
open "grep -v '^HEADER' file |"
@end example

For more on the @code{|} mechanism, see @ref{Open}.  The Grep command
prints lines which do not match the indicated string
(because of the @code{-v} switch), and the @code{^} character stands for
the start of the line (@ref{Grep}).  Thus all lines with the key word at the
@strong{start} of the line are skiped.

@cindex reading information from header lines
@cindex header lines, reading information from
@b{Case 4 -- reading and using information in header.}
Consider a dataset in which the first line gives the time of
observation, followed by a list of observations.  This might be, for
example, an indication of the data taken from a weather balloon released
at a particular time from a fixed location, with the main data being air
temperature as a function of elevation of the balloon.  The time
indication might be, for instance, the hour number.  One might need to
know the time to print a label on the diagram.  You could do that by:

@example
open file
read .time.
read columns x y
draw curve
sprintf \label "Time of observation is %f hour" .time.
draw title "\label"
@end example

@noindent
where the @code{sprintf} command has been used to change the numerical
time indication into a synonym that can be inserted into a quoted string
for drawing the title of the diagram (@ref{Sprintf}).  Here the time has
been assumed to be a decimal hour.  You might also have three numbers on
the line, perhaps a day, an hour and a minute.  Then you could do
something like

@example
open file
read .d. .h. .m.
read columns x y
draw curve
sprintf \label "Obs. %.0f:%.0f, day %.0f" .h. .m. .d.
draw title "\label"
@end example

@noindent
Here the @code{%.0f} code is used to ensure no numbers will be written
after the decimal point.  Naturally, you could convert this to a decimal
day, by e.g.

@example
...
.dday. = @{rpn .day. .hour. 24 / .min. 24 / 60 /@}
sprintf \label "Decimal day is %.4f" .dday.
...
@end example

@noindent
(Some of you might know how many minutes in a day, but I'm silly so I
kept the extra mathematical step -- nothing is lost by being
straightforward!)

@c HTML <!-- newfile IgnoringColumns.html "Gri: ignoring columns" "Examples" -->

@node   Ignoring Columns, Column Algebra, Handling Headers, Handling Data
@comment  node-name,  next,  previous,  up
@subsection Ignoring columns that are not of interest
Quite often a dataset will have many columns, of which only a couple are
of interest to you.  Consider for example oceanographic data which
has columns storing, in order, these variables: (1) depth in water
column, (2) "in situ" temperature, (3) "potential" temperature, (4)
salinity, (5) conductivity, (6) density, (7) sigma-theta, (8) sound
speed, and (9) oxygen concentration.  But you might only be interested
in plotting a graph of salinity on the x-axis and depth on the y-axis.
Here are several ways to do this:

@example
open file
read columns y * * x
draw curve
@end example

@noindent
where the @code{*} is a place-keeper to indicate to skip that column.
For a large number of columns, or as an aesthetic choice, you might
prefer to write this a

@example
open file
read columns y=1 x=4
draw curve
@end example

Many users would just as soon not bother with this syntax, preferring
instead to use system tools with which they are more familiar.  So a
Gawk user might write

@example
open "gawk '@{print($1, $4)@}' file |"
read columns y x
draw curve
@end example

@noindent
For more on the Gawk command see @ref{Awk}.


@c HTML <!-- newfile ColumnAlgebra.html "Gri: column algebra" "Examples" -->

@node   Column Algebra, Combining Columns, Ignoring Columns, Handling Data
@comment  node-name,  next,  previous,  up
@subsection Algebra on column data
Suppose the file contains (x,y), but you wish to plot 2y times x.  You
could do the doubling of y within Gri, as

@example
open file
read columns x y
y *= 2
draw curve
@end example

@noindent
or you could use a system tool, e.g. gawk, as in this example (@ref{Awk}).

@example
open "gawk '@{print($1,2*$2)@}' file|"
read columns x y
draw curve
@end example

The latter is preferable in the sense that it is more powerful.  The
reason for this is that Gri allows you to manipulate the x and y
columns, using so-called RPN mathematics (@ref{rpn Mathematics}), but
you cannot blend the columns.  For example, you cannot easily form the
ratio y/x in Gri.  (Actually, you can, by looping through your data and
doing the calculation index by index, but if you knew that already you
wouldn't need to be reading this section!)  Such blending is trivial in
the operating system, though, as in the following Gawk example (@ref{Awk}).

@example
open "gawk 'print @{($1, $2/$1)@}' file |"
read columns x y
draw curve
@end example

@c HTML <!-- newfile CombiningColumns.html "Gri: combining columns" "Examples" -->

@node   Combining Columns, Plotting Several Columns, Column Algebra, Handling Data
@comment  node-name,  next,  previous,  up
@subsection Combining columns from different files
Suppose you want to plot a column (@code{y}, say) from one file versus a
second column (@code{x}) from a second data file.  The easy way is to
use a system command to create a new file, for example the Unix command
@code{paste} -- but of course you don't want to clutter your filesystem
with such files, so you should do this withing Gri:

@example
open "paste file1 file2 |"
read columns x y
draw curve
@end example


@c HTML <!-- newfile PlottingSeveralColumns.html "Gri: plotting several columns" "Examples" -->

@node   Plotting Several Columns, Commands, Combining Columns, Handling Data
@comment  node-name,  next,  previous,  up
@subsection Plotting several y-columns versus on x-column
Sometimes you'll have a datafile with the first column being x, and the
other columns being various things to plot versus x.  For example, you
might have the data

@example
1  8 11  9
2 22 21 20
3 11 10  9
4 20 15 10
@end example

@noindent
in a file called @code{test.dat}.  Let's say the x-column is time, and
the y-columns are the readings from three temperature sensors.  The
following illustrates how you might plot these data.  If you think the
new-command which starts this script is useful, just insert it in your
@file{~/.grirc} file and you can just use it without re-defining it each
time.  This will give Gri a command called @code{draw curves}.

@example
`draw curves \xname \y1name ...'
Draw multiple y columns versus an x column.  Assumes
that the datafile is open, and that x is in the first
column, with the y values in one or more following 
columns.

The number of columns is figured out from the options, 
as is the name of the x-axis, and the labels to be 
used on each of the y curves.
@{
  # NB. the 3 below lets us skip the words 'draw' 
  # and 'curves', and the name of the x-column.
  .num_of_y_columns. = @{rpn wordc 3 -@}
  if @{rpn .num_of_y_columns. 1 >@}
    show "ERROR: `draw curves' needs at least 1 y column!"
    quit
  end if

  set x name @{rpn 2 wordv@}
  set y name ""

  # Loop through the columns.
  .col. = 0
  while @{rpn .num_of_y_columns. .col. <@}
    # The x-values will be in column 1, with y-values
    # in columns 2, 3, ..., of the file.
    .ycol. = @{rpn .col. 2 +@}
    rewind
    read columns x=1 y=.ycol.
    # At this point, you may want to change line thickness,
    # thickness, color, dash-type, etc.  For illustration,
    # let's set dash type to the column number.
    set dash .col.
    draw curve
    draw label for last curve @{rpn .col. 3 + wordv@}
    .col. += 1
  end while
@}

open test.dat
draw curves time y1 y2 y3
@end example


@c HTML <!-- newfile Commands.html "Gri: complete list of commands" "Gri Commands" -->

@node   Commands, Overview Of Gri Commands, Plotting Several Columns, Top
@comment  node-name,  next,  previous,  up
@chapter List of Commands in the Gri Language
@cindex programming, complete list of Gri commands
@cindex syntax of Gri commands
@cindex keywords of Gri commands
@menu
* Overview Of Gri Commands::    General classification of commands
* Command Syntax::              Syntax of the commands
* List Of Gri Commands::        
@end menu

@c HTML <!-- newfile CommandsOverview.html "Gri: Overview of commands" "Gri Commands" -->

@node   Overview Of Gri Commands, Command Syntax, Commands, Commands
@comment  node-name,  next,  previous,  up
@section Overview of Gri Commands
@cindex types of gri commands
@cindex overview of gri commands
@cindex gri commands, categories of

The Gri commands may be divided roughly into a few categories, as indicated in the following list.

@itemize @bullet

@item @strong{Working with files}:
Commands are @code{open}, @code{close}, @code{skip}, @code{read}, and
@code{rewind}.

@item @strong{Controlling parameters of the drawn material}:
Various @code{set} commands control values of parameters, like size of plot,
linewidth, font, etc.

@item @strong{Drawing things}:
Various @code{draw} commands let you draw data, axes, etc.

@item @strong{Interacting with the user}:
The @code{query} command gets instructions from the user.  The
@code{show} command displays messages to user.

@item @strong{Controlling program flow}:
The @code{if} statement controls optional execution of commands
(@ref{If Statements}).  The @code{while} statement allows loops.

@item @strong{Moving around in directories}:
The @code{pwd}, @code{cd} and @code{ls} commands do the usual unix
things.

@item @strong{Using the operating system}
The @code{system} command passes instructions to the operating system;
the output may be saved into a synonym by using 
@code{\syn = system ...}.  The @code{get env} command determines the value of any
unix environment variables the system has defined.  For more discussion
(@ref{Operating System}).

@item @strong{Statistical operations}:
Some very limited capabilities exist; for example, @code{regress} does
linear regression.

@item @strong{Mathematical operations}:
Simple mathematical manipulation of column, grid, and image data is
provided.  Also, wherever Gri expects a number, it will accept a
reverse-polish expression; for example, @code{set x size 10} could also
be written @code{set x size @{rpn 20 2 /@}}.  For details
(@ref{Mathematics}).
@end itemize


@c HTML <!-- newfile CommandSyntax.html "Gri: Command Syntax" "Gri Commands" -->
@node   Command Syntax, List Of Gri Commands, Overview Of Gri Commands, Commands
@comment  node-name,  next,  previous,  up
@section Command syntax
The syntax description is enclosed within angled single quotes, optional
items are enclosed in square brackets, multiword items are enclosed in
curly braces, and vertical bars separate different legitimate choices.
For example, the documentation item for the command for drawing contours

@example
`draw contour \
    [.value. |  \
      @{.min. .max. .inc. [.inc_unlabelled.]@}] \
    [unlabelled]'
@end example

@noindent
indicates that following are legal:

@example
draw contour                   # gri selects levels
draw contour unlabelled        # " but unlabelled
draw contour 10                # single contour line
draw contour 10 unlabelled     # " but unlabelled
draw contour 0 100 10          # contours at z=0,1,
draw contour 0 10 1 unlabelled # " but unlabelled
# contours at 0, 0.1, ... labelled at 0, 1
draw contour 0 10 1 0.1
@end example

@noindent
Note that items enclosed in braces must appear in their entirety; for
example,

@example
draw contour 0 10              # WRONG; missing .inc.
@end example

@noindent
which might look similar @code{draw contour .min. .max. .inc.} to you,
looks like garbage to Gri.  Gri will recognize it as an attempt at the
@code{draw contour} command (because the first 2 words match the syntax)
but it will then get confused, spit out an error message, and quit.



@c HTML <!-- newfile ListOfGriCommands.html "Gri: List of commands" "Gri: Commands" -->
@node   List Of Gri Commands, Assert, Command Syntax, Commands
@comment  node-name,  next,  previous,  up
@section List of all Gri commands

Commands are listed below in the order in which they are defined in the
@file{gri.cmd} file (@ref{Invoking Gri}).  What you see here
is similar to, but not identical to, the text of the online help.  Gri
usually accepts both American and English spellings
(As an example of spelling latitude, Gri accepts @code{grey} anywhere the
manual says @code{gray}, and @code{colour} for @code{color}.)

@cindex gri commands, complete list of
@cindex commands, complete list of
@cindex spelling of gri commands
@cindex gray vs Grey spelling
@cindex grey vs Gray spelling
@cindex colour vs Color spelling



@menu
* Assert::                      Assert something to be true (for debugging)
* Cd::                          Change directory
* Close::                       Close a file
* Convert::                     Convert various data types
* Create::                      Create columns from specified function
* Debug::                       Set to debugging mode
* Delete::                      Delete various data structures
* Differentiate::               Differentiate things
* Draw::                        Draw various things
* End Group::                   End a group
* Expecting::                   Make Gri warn of incompatibilites
* Filter::                      Filter (smooth) various data structures
* Flip::                        Flip or transpose grid or image
* Get Env::                     Get a unix environment variable
* Group::                       Start a group of drawn objects
* Heal::                        Interpolate across missing values
* Help::                        Give on-line help
* If::                          If and if/else statements
* Ignore::                      Ignore some of data recently read in
* Input::                       Input PostScript file into output file
* Insert::                      Run another command file
* Interpolate::                 Interpolate grid data to new x/y grid
* List::                        List source of a gri command
* Ls::                          List files in current directory
* Mask::                        Mask the image
* New::                         Get space for new variable or synonym
* Newpage::                     Start a new page
* New Postscript File::         Start a new PostScript file
* Open::                        Open a data file
* Postscript::                  Insert a line into the PostScript file
* Pwd::                         Print working directory
* Query::                       Get user input
* Quit::                        Exit from gri
* Read::                        Read something
* Regress::                     Do linear regressions on columnar data
* Reorder::                     Reorder columns
* Rescale::                     Re-determine scales for x/y axes
* Resize::                      Resize plot width/height for maps
* Return::                      Return early from command or insert file
* Rewind::                      Rewind data file to beginning
* Rpnfunction::                 Define an rpn function
* Set::                         Set various preference flags, etc
* Show::                        Show values of various things
* Skip::                        Skip some lines in data file
* Sleep::                       Sleep for a while
* Smooth::                      Smooth data
* Source::                      Run another command file
* Sprintf::                     Print variable values into a synonym
* State::                       Save or restore the graphics state
* Superuser::                   Enable some programmers debugging commands
* System::                      Performing system commands within gri
* Unlink::                      Delete file
* While::                       Loop over some code while a condition is true
* Write::                       Write data to a file
@end menu




@c HTML <!-- newfile Assert.html "Gri: `assert' command" "Gri Commands" -->

@node   Assert, Cd, List Of Gri Commands, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{assert}
@cindex debugging, with @code{assert} command
@cindex @code{assert} command, for debugging
@findex assert

@example
`assert .condition. ["message"]
@end example

@noindent
The condition may be a variable, a synonym, or an RPN expression.  If
this condition is true (i.e. evaluates to a non-zero number), do
nothing.  If the condition is false, the program will terminate with an
error condition (in unix, it will terminate with a non-zero exit code).

Before termination, a message will be printed, the form of which depends
on the optional @code{"message"} string.

If no @code{"message"} string is given, the the printed message will
indicate the name of the command-file and the line at which the assert
command was encountered.

If a @code{"message"} string is given, and if it ends in a newline
(@code{"\\n"}), then this string is printed.

If a @code{"message"} string is given, and if it does not end in
@code{"\\n"}, then the string is printed along with an indication of the
location in the command-file.

(Perl users will recognize this as being patterned on the @code{"die"}
command.)



@c HTML <!-- newfile Cd.html "Gri: `cd' command" "Gri Commands" -->

@node   Cd, Close, Assert, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{cd}
@cindex changing directories
@cindex directories, changing
@cindex @code{cd} command
@findex cd

@example
`cd [\pathname]'
@end example

@noindent
If a pathname specified, change to that directory.  Normal unix
filenames are used, as in the C-shell convention.  For example, the
commands @code{cd ~/src} and @code{cd $HOME/src} are equivalent.  You may
specify relative pathnames as in @code{cd ../sister_directory}.

If no \pathname directory path is specified, go to the home directory,
exactly as @code{cd ~} and @code{cd $HOME} do.


@c HTML <!-- newfile Close.html "Gri: `close' command" "Gri Commands" -->

@node   Close, Convert, Cd, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection  @code{close}
@cindex files, closing
@cindex closing files
@findex close
@cindex @code{close} command

@example
`close [\filename]'
@end example

@noindent
If no filename is specified, close the most recently opened data-file;
otherwise close the indicated file.


@c HTML <!-- newfile Convert.html "Gri: `convert' command" "Gri Commands" -->

@node   Convert, Convert Columns To Grid, Close, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection The @code{convert} commands

@menu
* Convert Columns To Grid::      Create grid from (x,y,f) data
* Convert Columns To Spline::    Create spline (x',y') from (x,y) data
* Convert Grid To Columns::      Create (x,y,f) data from grid
* Convert Grid To Image::        Create an image from grid data
* Convert Image To Grid::        Create a grid from image data
@end menu


@node   Convert Columns To Grid, Convert Columns To Spline, Convert, Convert
@comment  node-name,  next,  previous,  up
@subsubsection @code{convert columns to grid}
@findex convert columns to grid
@cindex @code{convert columns to grid} command
Various forms exist:

@example
`convert columns to grid OPTIONS'
@end example

@noindent
where the @code{OPTIONS} may be omitted or
selected from this list:

@example
`neighbor'
`boxcar    [.xr. .yr. [.n. .e.]]'
`objective [.xr. .yr. [.n. .e.]]'
`barnes    [.xr. .yr. .gamma. .iter.]'
@end example

@noindent
For more discussion on the methods see @ref{Ungridded Data}.

All these commands ``grid'' columnar (x,y,z) data.  That is, they fill
up a grid based on some form of interpolation of the possibly randomly-spaced 
columnar data.  There are many methods in existence for doing
this, and Gri implements several of them as alternatives.

The grid will have been defined by commands such as @code{set x grid},
@code{set y grid}, @code{read grid x} and @code{read grid y}.  As of
version 2.1.9, Gri does not require a grid to have been pre-defined; it
will create a regular 20 by 20 grid, spanning the range of x and y data,
as a default.  This is a good starting point in many cases.

@table @emph

@item `neighbor' method
Very fast but very limited.

@item `boxcar' method
Slower but a lot better.  Still, this can produce noisy contours if the
data are not densely and uniformly ditributed through domain.

@item `objective' method
Somewhat slower than `boxcar', but produces better fields since the
averaging function is smooth.

@item `barnes' method
Somewhat slower than `objective', but only by a constant factor (that
is, independent of number of data).  This produces by far the best
results, since the smoothing function has variable spatial scale.  This
is the default method if no method is supplied.
@end table

All except the @code{neighbor} method may take optional arguments to
define the x and y scales of the smoothing function (called @code{.xr.}
and @code{.yr.}).  (The barnes method has two other optional arguments
-- see below.)  If you do not supply these arguments, Gri will make a
reasonable choice and inform you of its decision.  Many users find that
it is best to @code{convert columns to grid} with no additional
parameters as a first step, to get advice on values to use for the
optional parameters.

The default @code{.xr.} and @code{.yr.} are calculated by determining
the span in x and in y directions, and dividing each by the square root
of the number of data points.  These numbers are then multiplied by the
square root of 2.  The method is as proposed by S. E. Koch and M.
DesJardins and P. J. Kocin, 1983.  ``An interactive Barnes objective map
anlaysis scheme for use with satellite and conventional data,'',
J. Climate Appl.  Met., vol 22, p. 1487-1503.

If @code{.xr.} and @code{.yr.} were supplied but negative, then Gri
interprets this as an instruction to modify the default values,
described in last paragraph, by multiplying by the absolute values of
the negative numbers given, instead of muliplying by square root of 2.

If the @code{chatty} option is turned on 
then Gri will print out the values of
(dx,dy) that it has 
calculated; this gives you some guidance for supplying your own values
of @code{(.xr.,.yr.)} if you choose to supply them yourself.  It is also
a good idea to let these parameters be a guide for your grid spacing;
for example, Koch et al., 1983, suggest using grid spacing of 0.3 to 0.5
times (dx,dy).

And now, the details @dots{}

@itemize @bullet

@item @strong{``Neighbor'' method}
The @code{convert columns to grid neighbor} method is useful for (x,y,z)
data which are already gridded (i.e., for which x and y take only values
which lie on the grid), or nearly gridded.  The (x,y,z) data are scanned
from start to finish. For each data point, the nearest grid point is
found.  Nearness is measured as Cartesian distance, with scale factor
given by the distance between the first and second grid points.  In
other words, distance is given by D=sqrt(dx*dx+dy*dy) where dx is ratio
of distance from data point to nearest grid point, in x-units, divided
by the difference between the first two elements of the x-grid, and dy
is similarly defined.  Once the grid point nearest the data point is
determined, Gri adds the z-value to a list of possible values to store
in the grid.  Once the entire data set has been scanned, Gri then goes
back to each grid point, and chooses the z-value of the data point that
was nearest to the grid point -- that is, it stores the z value of the
(x,y,z) data triplet which has minimal D value.  Note that this scheme
is independent of the order of the data within the columns.

@cindex computational cost, of @code{convert columns to grid} command

The @code{neighbor} method is useful when the data are already
pre-gridded, meaning that the (x,y,z) triplets have x and y values which
are already aligned with the grid.  @strong{Computational cost:} For
@code{P} data points, @code{X} x-grid points, and @code{Y} y-grid
points, the method calculation cost is proportional to
@code{P*[log2(X)+log2(Y)]} where @code{log2} is logarithm base 2.
As discussed below, this is often several orders of magnitude lower than
the other methods of gridding.

@item @strong{``Objective'' method}
In the @code{objective} method, a smoothing technique known as objective
mapping is applied.  It is essentially a variable-size smoothing filter
of approximately Gaussian shape (it is method ``two'' of Levy and Brown
[1986 J. Geophysical Res. vol 91, p 5153-5158]) The parameters
@code{.xr.} and @code{.yr.} give the width of the filter.

With the optional additional parameters @code{.n.} and @code{.e.} are
specified, then grid values will be assigned the missing value if there
are fewer than @code{.n.} (x,y,f) data in the neighborhood of the
gridpoint, even after enlarging the neighborhood by widening and
heightening by root(2) up to @code{.e.} times.  (The enlargement is only
done if fewer than @code{.n.} points are found.)  If these parameters
are not specified in the command, then values @code{.n.}=5 and
@code{.e.}=1 are assumed.  The special case where @code{.e.} is negative
tells Gri to @strong{always} fill in each grid point, by extending the
neighborhood to enclose the entire dataset if necessary.

@strong{Computational cost:} For @code{P} data points, @code{X} x-grid
points, and @code{Y} y-grid points, the method calculation cost is
proportional to @code{P*X*Y}.  Given that @code{X} and @code{Y} are
determined by the requirement for smoothness of contours and the size of
the graph, they are more or less fixed for all applications.  They are
often in the range of 20 or so -- on 10 cm wide graph, this yields a
contour footprint of 1/2 cm, which is often small enough to yield smooth
contours.  Therefore, the computational cost scales linearly with the
number of data points.  Compared to the ``neighborhood'' method, this is
more costly by a factor of @code{X*Y/log_2(X)/log_2(Y)} which is
normally in the range from 20 to 50.

@item @strong{``Boxcar'' method}
In the @code{boxcar} method, the grid points are derived from simple
averages calculated in rectangles @code{.xr.} wide and @code{.yr.} tall,
centred on the gridpoints.  The @code{.n.} and @code{.e.} parameters
have similar meanings as in the ``objective'' method.

@strong{Computational cost:} Roughly same as @code{objective} method
described above.

@item @strong{``Barnes'' method}
This is the default scheme.

The Barnes algorithm is applied.  If no parameters are specified,
@code{.xr.} and @code{.yr.} are determined as above, with @code{.gamma.}
set to 0.5, and @code{.iter.} set to 2 so that two iterations are done.
On successive iterations, the smoothing lengthscales @code{.xr} and
@code{.yr} are each reduced by multiplying by the square root of
@code{.gamma.}.  Smaller @code{.gamma.} values yield better resolution
of small-scale features on successive iterations.  Koch et al., 1983,
recommend using a @code{.gamma.} value in the range 0.2 to 1, with two
iterations.

Provided that all the grid points are close enough to at least some
column data, the entire grid is filled.  But if @code{.xr.} and
@code{.yr.} are too small, the weighting function can fall to zero,
since it is exponential in the sum of the squares of the
x-distance/@code{.xr.} and the y-distance/@code{.yr.}; in that case
missing values result at those grid points.  On a 32 bit computer, the
weighting function will fall to zero when x-distance/@code{.xr.}  and
y-distance/@code{.yr.}  are less than about 15 to 20.

If weights have been read in (@ref{Read Columns}), then these values are
applied in addition to the distance-based weighting.  (The normalization
means that weights for two data points of e.g. 1 and 2 will yield the
same result as if the weights had been given as 10 and 20.)

The computational cost at each iteration scales as @code{P*X*Y)}.  This
is comparable to that of the ``objective'' and ``boxcar'' methods.
Since normally two iterations are done, ``barnes'' is about double the
cost of these methods.  (Note: versions prior to 2.1.8 were much slower
for large datasets, being proportional to @code{P*P}.)

References: (1) Section 3.6 in Roger Daley, 1991, ``Atmospheric data
analysis,'' Cambridge Press, New York. (2) S. E. Koch and M. DesJardins
and P. J. Kocin, 1983.  ``An interactive Barnes objective map anlaysis
scheme for use with satellite and conventional data,'', J. Climate Appl.
Met., vol 22, p. 1487-1503.
@end itemize

The Barnes algorithm is as follows:

@tex
The gridded field is estimated iteratively.  Successive iterations
retain largescale features from previous iterations, while adding
details at smaller scales.

The first estimate of the gridded field, here denoted $G_{ij}^{(0)}$
(the parenthetic superscript indicating the order of the iteration) is
given by a weighted sum of the input data, with $z_k$ denoting the
k-th $z$ value.

$$
G_{ij}^{(0)}
=
{ {\sum_1^{n_k} W_{ijk}^{(0)} z_k} \over {\sum_1^{n_k} W_{ijk}^{(0)}} }
$$

The weights $W_{ijk}^{(0)}$ are defined in terms of a Gaussian
function decaying with distance from observation point to grid point:

$$
W_{ijk}^{(0)}
=
\exp \left[ - { {(x_k-X_i)^2} \over {L_x^2} }
            - { {(y_k-Y_j)^2} \over {L_y^2} } \right]
$$

\noindent
Here $L_x$ and $L_y$ are lengths which define the smallest
$(x,y)$ scales over which the gridded field will have significant
variations (for details of the spectral response see Koch et al. 1983).

Note: if the user has supplied weights then these
are multiplied into the normal distance-based weights; i.e. $w_i
W_{ijk}$ is used instead of $W_{ijk}$.

The second iteration derives a grid $G_{ij}^{(1)}$ in terms of the first
grid $G_{ij}^{(0)}$ and ``analysis values'' $f_k^{(0)}$ calculated at
the $(x_k,y_k)$ using a formula analogous to the above.
(Interpolation based on the first estimate of the grid $G_{ij}^{(0)}$
can also be used to calculate $f_k^{(0)}$, with equivalent results for a
grid of sufficiently fine mesh.)  In this iteration, however, the
weighted average is based on the difference between the data and the
gridded field, so that no further adjustment of the gridded field is
done in regions where it is already close to through the observed
values.  The second estimate of the gridded field is given by

$$
G_{ij}^{(1)}
=
G_{ij}^{(0)} 
+ 
{ {\sum_1^{n_k} W_{ijk}^{(1)} (f_k - f_k^{(0)})} \over {\sum_1^{n_k} W_{ijk}^{(1)}}
}
$$

\noindent
where the weights $w_{ik,1}$ are defined by analogy with
$W_{ik}^{(0)}$ except that $L_x$ and $L_y$ are replaced by
$\gamma^{1/2}L_x$ and $\gamma^{1/2}L_y$.  The nondimensional parameter
$\gamma$ ($0<\gamma<1$) controls the degree to which the focus is
improved on the second iteration.  Just as the weighting function
forced the gridded field to be smooth over scales smaller than $L_x$
and $L_y$ on the first iteration, so it forces the second estimate of
the gridded field to be smooth over the smaller scales
$\gamma^{1/2}L_x$ and $\gamma^{1/2}L_y$.

The first iteration yields a gridded field which represents the
observations over scales larger than $(L_x,L_y)$, while successive
iterations fill in details at smaller scales, without greatly
modifying the larger scale field.

In principle, the iterative process may be continued an arbitrary
number of times, each time reducing the scale of variation in the
gridded field by the factor $\gamma^{1/2}$.  Koch et al. 1983
suggest that there is little utility in performing more than two
iterations, providing an appropriate choice of the focussing parameter
$\gamma$ has been made.  Thus the gridding procedure defines a gridded
field based on three tunable parameters: $(L_x,L_y,\gamma)$.
@end tex


@ifinfo
The gridded field is estimated iteratively.  Successive iterations
retain largescale features from previous iterations, while adding
details at smaller scales.

The first estimate of the gridded field, here denoted
@code{G_(ij)^0} (the superscript indicating the order of the
iteration) is given by a weighted sum of the input data, with
@code{z_k} denoting the k-th @code{z} value.

@example
             sum_1^n W_(ijk)^0 z_k
G_(ij)^(0) = ----------------------
               sum_1^n W_(ijk)0
@end example
@noindent
where the notation @code{sum_1^n} means to sum the elements
for the @code{k} index ranging from 1 to @code{n}.

The weights @code{W_(ijk)^0} are defined in terms of a Guassian
function decaying with distance from observation point to grid point:

@example
               (   (x_k - X_i)^2       (y_k - Y_j)^2  )
W_(ijk)^0 = exp(-  --------------  -  --------------- )
               (      L_x^2                L_y^2      )
@end example

@noindent
Here @code{L_x} and @code{L_y} are lengths which define the smallest
@code{(x,y)} scales over which the gridded field will have significant
variations (for details of the spectral response see Koch et al. 1983).

Note: if the user has supplied weights then these
are applied in addition to the distance-based weights.  That is,
@code{w_i W_(ijk)} is used instead of @code{W_(ijk)}.

The second iteration derives a grid @code{G_(ij)^1} in terms of the
first grid @code{G_(ij)^0} and ``analysis values'' @code{f_k^0}
calculated at the @code{(x_k,y_k)} using a formula analogous to that
above.  (Interpolation based on the first estimate of the grid
@code{G_(ij)^0} can also be used to calculate @code{f_k^0}, with
equivalent results for a grid of sufficiently fine mesh.)  In this
iteration, however, the weighted average is based on the difference
between the data and the gridded field, so that no further adjustment
of the gridded field is done in regions where it is already close to
through the observed values.  The second estimate of the gridded field
is given by

@example
                       sum_1^n W_(ijk)^1 (f_k - f_k^0)
G_(ij)^1 = G_(ij)^0 +  -------------------------------
                              sum_1^n W_(ijk)^1
@end example

@noindent where the weights @code{w_@{ik,1@}} are defined by analogy
with @code{W_@{ik@}^0} except that @code{L_x} and @code{L_y} are
replaced by @code{gamma^@{1/2@}L_x} and @code{gamma^@{1/2@}L_y}.  The
nondimensional parameter @code{gamma} (@code{0<gamma<1}) controls the
degree to which the focus is improved on the second iteration.  Just
as the weighting function forced the gridded field to be smooth over
scales smaller than @code{L_x} and @code{L_y} on the first iteration,
so it forces the second estimate of the gridded field to be smooth
over the smaller scales @code{gamma^@{1/2@}L_x} and
@code{gamma^@{1/2@}L_y}.

The first iteration yields a gridded field which represents the
observations over scales larger than @code{(L_x,L_y)}, while successive
iterations fill in details at smaller scales, without greatly
modifying the larger scale field.

In principle, the iterative process may be continued an arbitrary number
of times, each time reducing the scale of variation in the gridded field
by the factor @code{gamma^@{1/2@}}.  Koch et al. 1983 suggest that there
is little utility in performing more than two iterations, providing an
appropriate choice of the focussing parameter @code{gamma} has been made.
Thus the gridding procedure defines a gridded field based on three
tunable parameters: @code{(L_x,L_y,gamma)}.
@end ifinfo





@node   Convert Columns To Spline, Convert Grid To Columns, Convert Columns To Grid, Convert
@comment  node-name,  next,  previous,  up
@subsubsection @code{convert columns to spline}
@cindex spline, fitting to (x,y) data
@findex convert columns to spline
@cindex @code{convert columns to spline} command

@example
`convert columns to spline \
    [.gamma.] \
    [.xmin. .xmax. .xinc.]'
@end example

Fit a normal or taut interpolating spline, y=y(x), through the (x,y)
data.  Then subsample this spline to get a new set of (x,y) data.  If
the spline x-values, @code{.xmin.}, etc, are not specified, the spline
ranges from the smallest x-value with legitimate data to the largest
one, with 200 steps in between.

The parameter @code{.gamma.} determines the type of spline used.  If
@code{.gamma.} is not specified, or is given as zero, a standard
interpolating spline is used.  A knot appears at each x location, with
cubic polynomials spanning the space between the knots.  If
@code{.gamma.} lies between 0 and 6, a taut spline is used; this tends
to have fewer wiggles than a normal spline.  If @code{.gamma.}  lies in
the range 0 to 3, a taut spline is used, with the possible insertion of
knots between interior x pairs.  The value 2.5 is used commonly.  If
@code{.gamma.} lies in the range 3 to 6, extra knots are permitted in
the x pairs at the ends of the domain.  A value of 5.5 is used commonly.

@strong{Reference} Chapter 16 of Carl de Boar, 1987. ``A Practical Guide
to Splines'' Springer-Verlag.

@example
read columns x y  # function is y=x^2
0 0
1 1
2 4
3 9
4 16

set symbol size 0.2
draw symbol bullet
convert columns to spline
draw curve
@end example


@node   Convert Grid To Columns, Convert Grid To Image, Convert Columns To Spline, Convert 
@comment  node-name,  next,  previous,  up
@subsubsection @code{convert grid to columns}
@findex convert grid to columns
@cindex columns, creating from grid
@cindex @code{convert grid to columns} command

@example
`convert grid to columns'
@end example

@noindent
Create column data from grid data.  Each non-missing gridpoint is
translated into a single (x,y,z) triplet.  If column data already exist,
then they are first erased.  This command is useful in changing the grid
configuration, perhaps from a non-uniform grid to a uniform grid.  In
the following example, a new grid with x=(0, 0.05, 0.1, ..., 0.1) and
y=(10, 11, ..., 20) is created.  The default gridding method
(@code{convert columns to grid}) is used here, but of course one is free
to adjust the method as usual.

@example
# ... read/create grid
convert grid to columns
delete grid
set x grid  0  1 0.05
set y grid 10 20 1
convert columns to grid
@end example


@node   Convert Grid To Image, Convert Image To Grid, Convert Grid To Columns, Convert
@comment  node-name,  next,  previous,  up
@subsubsection @code{convert grid to image}
@findex convert grid to image
@cindex image, creating from grid
@cindex @code{convert grid to image} command

@example
`convert grid to image [directly] [size .width. .height.] \
    [box .xleft. .ybottom. .xright. .ytop.]'
@end example

@noindent
With no options specified, convert grid to a 128x128 image,
using an image range as previously set by @code{set image range}, and using
interpolation (see below).

With the @code{directly} option, no interpolation is used; each grid
point is used to calculate the colour of a single image pixel.  Since
images are always uniform in Gri, this will only work if the grid is
also uniform, i.e. there must be a constant distance between columns
in the grid, and the same for the rows.  This method is useful for
fine-grained grids, especially if they contain isolated points (e.g. a
numerical model might have a trace of points representing a river).

With the @code{size} options @code{.width.} and @code{.height.}
specified, they set the number of rectangular patches in the image.
Interpolation is used.

With the @code{box} options specified, they set the bounding box for
the image.  If @code{box} is not given, the image spans the same
bounding box as the grid as set by @code{set x grid} and @code{set y
grid}.  Again, interpolation is used in this form.

Normally, missing values in the grid become white in the image, but this
can be changed using the @code{set image missing value color to}@dots{}
command.

@cindex image, interpolation from grid
@cindex interpolation, from grid to image

@b{Interpolation method:} The interpolation scheme is the same used for
contouring.  Image points that lie outside the grid domain are
considered missing.  For points within the grid, the first step is to
locate the patch of the grid upon which the pixel lies.  Then the 4
neighboring grid points are examined, and one of the following cases
holds.
@enumerate
@item
If 3 or more of them are missing, the pixel is considered missing.
@item
If just one of the neighboring grid points is missing, then the image
pixel value is determined by bilinear interpolation on the remaining 3
non-missing grid points.  (This amounts to fitting a plane to three
measurements of height.)
@item
If all 4 of the grid points are non-missing, then the rectangle defined
by the grid patch is subdivided into four triangles.  The triangles are
defined by the two diagonal lines joining opposite corners of the
rectangle.  An ``image point'' is constructed at the center of the grid
patch, with f(x,y) value taken to be the average of the values of the
four neighbors.  This value is taken to be the value at the common
vertex of the four triangles, and then bilinear interpolation is used to
calculate the image pixel value.
@end enumerate

@node   Convert Image To Grid, Create, Convert Grid To Image, Convert
@comment  node-name,  next,  previous,  up
@subsubsection @code{convert image to grid}
@findex convert image to grid
@cindex @code{convert image to grid} command
@cindex grid, creating from image

@example
`convert image to grid'
@end example

@noindent
Convert image to grid, using current graylevel/colorlevel mapping.  For
example, if one had a linear mapping of pixel values 0->255 into the
user values 10->20, as in

@example
set image range 10 20
set image grayscale black 10 white 20
@end example

@noindent
then the output grid will be of value 10 where the pixel value is 0,
etc.  If the image is in color, the grid values will represent the
result of mapping the colors to grayscale in the standard way (Foley and
VanDam, 1984). [BUG: as of 1.063, the colorscale is ignored completely,
and I'm not sure what happens.] The image data are interpolated onto the
grid using a nearest-neighbor substitution.  This command insists that
the image x/y grids have already been defined.





@c HTML <!-- newfile Create.html "Gri: `create' command" "Gri Commands" -->

@node   Create, Create Columns From Function, Convert Image To Grid, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection The @code{create} commands
@menu
* Create Columns From Function:: prepare to draw a function
* Create Image Grayscale::       prepare to draw banded image
@end menu

@node   Create Columns From Function, Create Image Grayscale, Create, Create
@comment  node-name,  next,  previous,  up
@subsubsection @code{create columns from function}
@findex create
@cindex @code{create columns from function} command

@example
`create columns from function'
@end example

@noindent
Plot a function of x which is defined in synonym \function.

@example
ENVIRONMENT
\function = function to plot.
\xmin     = minimum x value
\xmax     = maximum x value
\xinc     = increment in x values
     
EXAMPLE
\function = "cos(x)"
\xmin     = "0"
\xmax     = "2 * 3.14"
\xinc     = "0.1"
create columns from function
draw curve
@end example     

@noindent
NOTE: This only works on machines which have the @code{awk} command
available at the commandline.  This means most unix machines and some
vax machines.

@node   Create Image Grayscale, Debug, Create Columns From Function, Create
@comment  node-name,  next,  previous,  up
@subsubsection @code{create image grayscale}
@cindex image, banded
@findex create image grayscale

@example
`create image grayscale banded .band.'
@end example

@noindent
Make a banded grayscale with in units of .band. pixel values each.
Thus, pixel values 0 to (.band. - 1) on the image will map to 0, while
values from .band. to (2 * .band. - 1) will map to .band., etc.  For
example, .band. = 2 gives grayscale = (0 0 2 2 4 4 6 6 ... 252 252 254
254).

@c HTML <!-- newfile Debug.html "Gri: `debug' command" "Gri Commands" -->

@node   Debug, Delete, Create Image Grayscale, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{debug}
@cindex debugging
@findex debug
@cindex @code{debug} command

@example
`debug [.n.]|[clipped values in draw commands]|off'
@end example

@noindent
With no optional parameters, sets the value of @code{..debug..} to 1.
(Normally, @code{..debug..} is 0.)  You may use @code{..debug..} in 
@code{if}
statements, etc.  Note that @code{..debug..} is also set to 1 when gri
is invoked with the commandline switch @code{-d}.

With @code{.n.} specified, @code{..debug..} is set to @code{.n.}; a
value of zero for @code{.n.} turns debugging off, while 1 turns it on.
Higher values may be used for deeper debugging, if you choose:

@example
if @{rpn ..debug.. 2 <@}
  # Code to do if ..debug.. is greater than 2.
end if
@end example

@noindent
Note that you can assign to @code{..debug..} as you can to any other
variable; @code{debug .n.} is equivalent to @code{..debug.. = .n.}.
     
With the @code{clipped} option, Gri prints any clipped data encountered
during any @code{draw ...} commands, EXCEPT in the case of
@code{postscript} clipping, where no check is possible.  (Note that
@code{..debug..} is not affected.)

All these forms of debugging are cancelled by @code{debug off}.


@c HTML <!-- newfile Delete.html "Gri: `delete' command" "Gri Commands" -->

@node   Delete, Differentiate, Debug, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{delete}
@cindex deleting variables, synonyms, scales, etc
@cindex grid, deleting
@cindex scales, deleting
@cindex synonyms, deleting
@cindex variables, deleting
@findex delete
@cindex @code{delete} command

@example
`delete .variable.|\synonym [.variable.|\synonym [...]]'
`delete columns [where missing]'
`delete columns [randomly .fraction.]'
`delete grid'
`delete [x|y] scale'
@end example

@noindent
Delete some item or characteristic.

@itemize @bullet

@item @code{delete .variable.}
Delete definition of variable @code{.variable.}, making it undefined.
Any number of variables or synonyms may be specified on one line.

@item @code{delete \synonym}
Delete definition of synonym @code{\synonym}, making it undefined.  Any
number of variables or synonyms may be specified on one line.

@item @code{delete \@@alias}
Delete the item named by the alias (@ref{Alias Synonyms}).

@item @code{delete} with an @code{&} item
Delete the item in the calling program.

@item @code{delete columns}
Delete column data.

@item @code{delete columns where missing}
Completely delete all column data for which any one of x, y, etc is missing.

@item @code{delete columns randomly .fraction.}
Randomly select fraction @code{.fraction.}  of the non-missing column
data, and designate them as being missing.

@item @code{delete grid}
Delete grid data.

@item @code{delete scale}
Delete scales for both x and y, so next @code{read columns} will set it. 

@item @code{delete x scale}
Delete scales for x, so next @code{read columns} will set it.

@item @code{delete y scale}
Delete scales for y, so next @code{read columns} will set it.
@end itemize


@c HTML <!-- newfile Differentiate.html "Gri: `differentiate' command" "Gri Commands" -->

@node   Differentiate, Draw, Delete, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{differentiate}
@cindex differentiation
@findex differentiate
@cindex @code{differentiate} command

@example
`differentiate @{x|y wrt index|y|x@} | @{grid wrt x|y@}'
@end example

@noindent
Differentiate column data or grid data.  Only the @code{x} and @code{y}
columns may be differentiated.  They may be differentiated either with
respect to (``wrt'') the index (forming a first difference) or with
respect to the other column.  The derivative is done with the
backwards-difference algorithm.  Grid data may differentiated with
respect to @code{x} direction or @code{y} direction.  Grid
differentiation is done with a centred difference, with endpoints being
assigned the derivative of the neighboring interior point (so that the
second derivative is zero at the edges of the grid).


@c HTML <!-- newfile Draw.html "Gri: About draw commands" "Gri Commands" -->

@node   Draw, Draw Arc, Differentiate, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection The @code{draw} commands
@findex draw
Draw commands do actual drawing on the page.  You can draw axes,
lineplots, symbols, contours, images, and text.  

@strong{NOTE} Gri likes drawings to have axes, so if a @code{draw} command
is executed before any axes have been drawn, Gri will draw axes after it
draws the item.  (You can get drawings without axes by preceding any
other @code{draw} commands with the command @code{draw axes none}.)
Many users have been surprised by the results of this rule.  For
example, if you do @code{set graylevel 0.5} before @code{draw curve},
you'll find that the axes are drawn in gray also.  To avoid this, make
sure to do @code{draw axes} before you modify the graylevel.)

@menu
* Draw Arc::                    Draw an arc segment
* Draw Arrow::                  Draw single arrow
* Draw Arrows::                 Draw many arrows (using columns)
* Draw Axes If Needed::         Draw axes if haven't done so yet
* Draw Axes::                   Draw axes
* Draw Border Box::             Draw border around plot
* Draw Box::                    Draw a box, possibly filled
* Draw Circle::                 Draw a circle
* Draw Contour::                Draw contour(s)
* Draw Curve::                  Draw a curve of y(x) column data
* Draw Essay::                  Draw text, adjusting position for each line
* Draw Gri Logo::               Draw a Gri logo
* Draw Grid::                   Draw the location of grid points
* Draw Image Histogram::        Draw histogram of values in image
* Draw Image Palette::          Draw palette used in image plots
* Draw Image::                  Draw image
* Draw Isopycnal::              Draw isopycnal line on TS plot
* Draw Isospice::               Draw iso-spice line on TS plot
* Draw Label Boxed::            Draw a label in a box
* Draw Label Whiteunder::       Draw a label with white ink under it
* Draw Label For Last Curve::   What it says
* Draw Label::                  Draw text somewhere
* Draw Line From::              Draw line segment
* Draw Line Legend::            Draw legend displaying line types
* Draw Lines::                  Draw sequence of parallel lines
* Draw Patches::                Draw grayscale patches showing z(x,y)
* Draw Polygon::                Draw a polygon
* Draw Regression Line::        Draw line from regression between x and y
* Draw Symbol At::              Draw a symbol at a point
* Draw Symbol Legend::          Draw a symbol and a string describing it
* Draw Symbol::                 Draw symbols at (x,y), or at a point
* Draw Time Stamp::             Draw a timestamp at top of plot
* Draw Title::                  Draw a title for plot
* Draw Values::                 Draw numbers beside z(x,y)
* Draw X Axis::                 Draw the x axis
* Draw X Box Plot::             Draw box plots showing x spread
* Draw Y Axis::                 Draw the y axis
* Draw Y Box Plot::             Draw box plots showing y spread
* Draw Zero Line::              Draw y=0 or x=0
@end menu

@node   Draw Arc, Draw Arrow, Draw, Draw
@comment  node-name,  next,  previous,  up
@subsubsection The @code{draw arc} command
@findex draw arc
@cindex arc, drawing
@cindex drawing arcs

@example
`draw arc [filled] .xc_cm. .yc_cm. .r_cm. .angle_1. .angle_2.'
@end example

Draw an "arc", that is, a portion of a circle.  The center of the
circle is at the coordinate (@code{.xc_cm.}, @code{.yc_cm.}), and the
circle radius is @code{.r_cm.}, all three quantities being in cm on
the page, @emph{not} in user-units.  The arc starts at angle
@code{.angle_1.}, measured in degrees counterclockwise from a
horizontal line, and extends to angle @code{.angle_2.}, in the same
units.

If the keyword @code{filled} is present, the arc is filled with the
current color.  Otherwise it is drawn with the current "curve"
linewidth @ref{Set Line Width}.

@node   Draw Arrow, Draw Arrows, Draw Arc, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw arrow}
@cindex arrows, drawing single

@example
draw arrow from .x0. .y0. to .x1. .y1. [cm]
@end example

With no optional parameters, draw an arrow from (@code{.x0.},
@code{.y0.}) to (@code{.x1.}, @code{.y1.}), where coordinates are in
user units.  The arrow head will be at (@code{.x1.}, @code{.y1.}), and
its size is as set by most recent call to @code{set arrow size}.  With
the @code{cm} keyword present, the coordinates are in centimetres on the
page.  NOTE: This will not cause auto-drawing of axes.

@node   Draw Arrows, Draw Axes If Needed, Draw Arrow, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw arrows}
@findex draw arrows
@cindex @code{draw arrows} command

@example
`draw arrows'
@end example

@noindent
Draw a vector field consisting of arrows emanating from the coordinates
stored in the (x, y) columns.  The lengths and orientations of the
arrows are stored in the (u, v) columns, and the scale for the (u,v)
columns is set by @code{set u scale} and @code{set v scale}.  @strong{See also}
(1) To set arrow size, use @code{set arrow size}.  (2) To get a single
arrow, use @code{draw arrow}.


@node   Draw Axes If Needed, Draw Axes, Draw Arrows, Draw
@comment  node-name,  next,  previous,  up
@findex draw axes if needed
@cindex @code{draw axes if needed} command
@subsubsection @code{draw axes if needed}

@example
`draw axes if needed'
@end example

@noindent
Draw axes frame if required.  Used within gri commands that auto-draw axes.
NOTE: this should only be done by developers.



@node   Draw Axes, Draw Border Box, Draw Axes If Needed, Draw
@comment  node-name,  next,  previous,  up
@findex draw axes
@cindex @code{draw axes} command
@subsubsection @code{draw axes}

@example
`draw axes [.style.|frame|none]'
@end example

@noindent
With no style (@code{.style.}) specified, draw x-y axes frame labelled
at left and bottom. The value of @code{.style.} determines the style of
axes: 
@itemize @bullet

@item @code{.style. = 0}
Draw x-y axes frame labelled at left and bottom.  Since this is the
default, it's best to leave it out altogether to make your code easier to
understand.

@item @code{.style. = 1}
Draw axes without tics at top and right

@item @code{.style. = 2}
Draw axes frame with no tics or labels; same as @code{draw axes frame}
@end itemize

With the keyword @code{frame} specified, draw axes frame with no tics or
labels (just like @code{.style.} = 2, but preferable because it makes for
code that is easier to read and understand).

With the keyword @code{none} specified, prevent Gri from automatically
drawing axes when drawing curves.

Note: @code{set axes style} can also be used to set axes properties,
and then simply using @code{draw axes}, or letting axes be auto-drawn,
will result in the desired effect (@ref{Set Axes Style}).  However, if
the @code{draw axes} command explicitly asks for a particular style,
then it over-rides the style set by @code{Set Axes Style}.


@node   Draw Border Box, Draw Box, Draw Axes, Draw
@comment  node-name,  next,  previous,  up
@findex draw border box
@cindex @code{draw border box} command
@subsubsection @code{draw border box}

@example
`draw border box .xleft. .ybottom. .xright. .ytop. \
    .width_cm. .brightness.'
@end example

@noindent
Draw gray box, as decoration or alignment key for pastup. The box, with
outer lower left corner at (@code{.xleft.}, @code{.ybottom.}) and outer
upper right corner at (@code{.xright}., @code{.ytop.}) -- both coordinates
being in centimetres on the page -- is drawn with thickness
@code{.width_cm.} and with graylevel @code{.brightness.} (0 for black; 1
for white).  The gray line is drawn inside the box.  After drawing the
gray line, a thin black line is drawn along the outside edge.

If the geometry is not specified with @code{.xleft.} and the other
parameters, then a reasonable margin is used around the present axes
area, and the defaults (@code{.border.} = 0.2, @code{.brightness.} =
0.75) are used.

NOTE: This command does not cause auto-drawing of axes.


@node   Draw Box, Draw Circle, Draw Border Box, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw box}
@findex draw box
@cindex @code{draw box} command

@example
`draw box filled .xleft. .ybottom. .xright. .ytop. [cm|pt]'
@end example

@noindent 
Draw filled box spanning indicated range, with lower-left corner at
(@code{.xleft.}, @code{.ybottom.}) and upper-right corner at
(@code{.xright.}, @code{.ytop.}).  The corners are specified in user
coordinates, unless the optional @code{cm} or @code{pt} keyword is
present, in which case they are in centimetres or points on the page.
An error will result if you specify user coordinates but they aren't
defined yet.

No checking is done on the rectangle; for example, there is no
requirement that @code{.xleft.} be to the left of @code{.xright.} in your
coordinate system.

NOTE: if the box is specified in user units, this command will cause
auto-drawing of axes, but not if the box is specified in @code{cm}
or @code{pt} units

@example
`draw box .xleft. .ybottom. .xright. .ytop. [cm|pt]'
@end example

@noindent
Draw box spanning indicated range, with lower-left corner at
(@code{.xleft.}, @code{.ybottom.)} and upper-right corner at (@code{.xright.},
@code{.ytop.}).

The corners are specified in user coordinates, unless the optional
@code{cm} or @code{pt} keyword is present, in which case they are in
centimetres or points on the page.  An error will result if you
specify user coordinates but they aren't defined yet.

No checking is done on the rectangle; for example, there is no
requirement that @code{.xleft.} be to the left of @code{.xright.} in your
coordinate system.


@node   Draw Circle, Draw Contour, Draw Box, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw circle}
@cindex circles, drawing
@findex draw circle
@cindex @code{draw circle} command

@example
draw circle with radius .r_cm. at .x_cm. .y_cm.
@end example

@noindent
Draw circle of specified radius (in cm) at the specified
location (in cm on the page).


@node   Draw Contour, Draw Curve, Draw Circle, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw contour}
@cindex drawing contours
@cindex contouring
@findex draw contour
@cindex @code{draw contour} command

@example
`draw contour [@{.value. \
  [unlabelled | @{labelled "\label"@}]@} \
  | @{.min. .max. .inc. \
    [.inc_unlabelled.] [unlabelled]@}]'
@end example

@noindent
This command draws contours based on the "grid" data previously read in
by a @code{read grid data} command or created by gridding column data
with a @code{create grid from columns} command.  If the grid data don't
exist, or if the x and y locations of the grid points do not exist (see
@code{set x grid}, @code{set y grid}, etc), Gri will complain.

With no optional parameters, draw labelled contours at an interval
that is picked automatically based on the range of the data.
     
With a single numerical value (@code{.value.}), draw the indicated
contour.  With the addition of @code{labelled "\label"}, put the
indicated label instead of a numeric label.  This can be useful for
using scientific notation instead of computer notation for exponents,
e.g.  @code{draw contour 1e-5 labelled "10$^@{-5@}$"}.

With (@code{.min.}, @code{.max.} and @code{.inc.}) given, draw
contours for z(x,y) = @code{.min.}, z(x,y) = @code{.min. + .inc.},
z(x,y) = @code{.min. + 2*.inc.}, ..., z(x,y) = @code{.max.}

With the additional value @code{.inc_unlabelled.} specified, extra
unlabelled contours are drawn at this finer interval.

With the optional parameter @code{unlabelled} at the end of any form
of this command (except the @code{labelled "\label"} variation, of
course), Gri will not label the contour(s).

@strong{Hint:} It can be effective to draw contours at a certain interval
with labels, and a thicker pen, e.g.

@example
set line width rapidograph 3x0
draw contour -2 5 1 0.25
set line width rapidograph 1
draw contour -2 5 1
@end example

@b{Interpolation method:} The interpolation scheme is the same used for
converting grid-values to image values (@ref{Convert Grid To Image}).

@strong{See also} @code{set contour labels}


@node   Draw Curve, Draw Essay, Draw Contour, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw curve}
@findex draw curve
@cindex @code{draw curve} command
@cindex x-y graphs
@cindex region painting
@cindex paint regions with color
@cindex filled regions
@cindex drawing curves
@cindex curves, drawing
Several forms exist.

@example
`draw curve'
@end example

@noindent
Draws a curve connecting the points (x,y), which have been read in by a
command like @code{read columns x y}.  Line segments are drawn between
all (x,y) points, except: (1) no line segments are drawn to any missing
data (see @code{set missing value}), and (2) if clipping is turned on
(see @code{set clip on}), no line segments are drawn outside the
clipping region.  @strong{See also} @code{draw curve overlying}

@example
`draw curve overlying'
@end example

@noindent
Like @code{draw curve}, except that before drawing, the area underneath
the curve (+/- one linewidth) is whited out.  This clarifies graphs
where curves overlie other curves or the axes.  
@strong{See also} @code{draw curve}.

@example
`draw curve filled [to @{.y. y@}|@{.x. x@}]'
@end example

@noindent
The form @code{draw curve filled ...} draws filled curves.  If the
@code{to .value.} is not specified, fill the region defined by the x-y points
using the current paint colour (see @code{set graylevel}).  To complete
the shape, an extra line is drawn between the first and last points.

The form @code{draw curve filled to .y. y} fills the region between y(x)
and y = @code{.y.}; do not connect the first and last points as in the
case where @code{to .yvalue.} is not specified.

The form @code{draw curve filled to .x. x} fills the region between x(y)
and x = @code{.x.}





@node   Draw Essay, Draw Gri Logo, Draw Curve, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw essay}
@findex draw essay
@cindex @code{draw essay} command

@example
`draw essay "text"|reset'
@end example

@noindent
Draw indicated text on the page.  Succeeding calls draw text further and
further down the page, starting at the top.

The current font size is used; to alter this, use @code{set font size}
before @code{draw essay}.

When @code{reset} is present instead of text, the drawing position is
reset to the top of the page.  Use this after a @code{new page} command
to ensure that the next text lines will appear at the top of the page as
expected.  EXAMPLE:

@example
set font size 2 cm
draw essay "Line 1, at top of page"
draw essay "Line 2, below top line"
@end example


@node   Draw Gri Logo, Draw Grid, Draw Essay, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw gri logo}
@findex draw gri logo
@cindex @code{draw gri logo} command
@cindex logo, how to draw

@example
`draw gri logo .x_cm. .y_cm. .height_cm. .style. \fgcolor \bgcolor'
@end example

@noindent
Draw a Gri logo at given location with given style and colors.  The
lower-left corner of the logo will be @code{.x_cm.} centimeters from the
left-hand side of the page and @code{.y_cm.} centimeters from the bottom
of the page.  The logo will be @code{.height_cm.} centimeters tall.  The
textual parameters @code{\fgcolor} and @code{\bgcolor} give the foreground and
background colors, respectively, and these are used in styles as noted
in the table below

@example
.style.    style
=======    ===================
   0       stroke curve
   1       fill with color \fgcolor, no background
   2       fill with color \fgcolor it in tight box of color \bgcolor
   3       as 2 but in square box
   4       draw in \fgcolor on top of shifted copy in \bgcolor
@end example

An example is given below

@example
draw gri logo 1 1 3 4 blue green
@end example

@node   Draw Grid, Draw Image Histogram, Draw Gri Logo, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw grid}
@findex draw grid
@cindex @code{draw grid} comman

@example
`draw grid'
@end example

@noindent
Draw plus-signs at locations where grid data are non-missing.

@node   Draw Image Histogram, Draw Image Palette, Draw Grid, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw image histogram}
@findex draw image histogram
@cindex @code{draw image histogram} command
@cindex image, histogra

@example
`draw image histogram \
  [box .llx_cm. .lly_cm. .urx_cm. .ury_cm.]'
@end example

@noindent
With no optional parameters, draw histogram of all unmasked parts of the
image, placing it above the current top of the plot.

When the @code{box} options are present, they specify the box (in
centimetre coordinates on the page) in which the histogram plot is to be
done.



@node   Draw Image Palette, Draw Image, Draw Image Histogram, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw image palette}
@findex draw image palette
@cindex @code{draw image palette} comman

@example
`draw image palette 
   [axisleft|axisright|axistop|axisbottom] 
   [left .left. right .right. [increment .inc.]] 
   [box .xleft_cm. .ybottom_cm. .xright_cm. .ytop_cm.]'
@end example

@noindent
@cindex image, drawing palette
@cindex image, drawing colorscale palette
@cindex colorscale, drawing
@cindex palette for image colorscale, drawing 
With no optional parameters, draw palette for image, placed above the
current top showing values ranging from @code{.min_value.} to
@code{.max_value.} as given in @code{set image range}.

Optional keywords (@code{axisleft}, etc) control the orientation of the
palette, the default being @code{axisbottom}.

The optional parameters @code{.left.} and @code{.right.} may be used to
specify the range to be drawn in the palette.  If the additional
optional parameter @code{.inc.} is present, it specifies the interval
between tics on the scale; if not present, the tics are at increments of
2 * (@code{.right.} - @code{.left}.).  (If @code{.inc.}  has the wrong
sign, it will be corrected without warning.)

When the optional @code{box} parameters are present, they prescribe the
bounding box to contain the palette.  The units are centimetres on the
page.  If these parameters are not present, the box will be drawn above
the image plot.

@cindex hint, palette range
@strong{Hint} It is a good idea to make the palette range @code{.left.} to
@code{.right.} extend a little beyond the range of full white and full
black, since otherwise neither pure white nor pure black will appear in
the colorbar.  For example

@example
set image grayscale black 0 white 1 increment 0.1
draw image palette left -0.1 right 1.1 increment 0.1
@end example

@cindex hint, contour lines on image palette
@strong{Hint} Continuous-tone images with superimposed contours are often
effective.  To get the contour lines drawn on the image palette, do
something like this

@example
draw image
.left.   = 0
.right.  = 9
.inc.    = 1
.space.  = 3
.height. = 1
draw image palette left .left. \
  right .right. \
  increment .inc. \
  box \
    ..xmargin.. \
    @{rpn ..ymargin.. ..ysize.. + .space. + @} \
    @{rpn ..xmargin.. ..xsize.. +@} \
    @{rpn ..ymargin.. ..ysize.. + .space. + .height. + @}
draw contour .left. .right. .inc. unlabelled

.c. = .left.
while @{rpn .right. .c. <= @}
  .c_cm. = @{rpn .c. .left. - \
   .right. .left. - / \
    ..xsize.. * ..xmargin.. +@}
  draw line from \
    .c_cm. \
    @{rpn ..ymargin.. ..ysize.. + .space. + @}\
    to \
    .c_cm. \
    @{rpn ..ymargin.. ..ysize.. + .space. + .height. +@} \
    cm
  .c. += 1
end while
@end example


@node   Draw Image, Draw Isopycnal, Draw Image Palette, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw image}
@findex draw image
@cindex @code{draw image} comman

@example
`draw image'
@end example

@noindent
Draw black/white image made by @code{convert grid to image} or by
@code{read image}.


@node   Draw Isopycnal, Draw Isospice, Draw Image, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw isopycnal}
@findex draw isopycnal
@cindex @code{draw isopycnal} command
@cindex T-S diagram, drawing isopycnals on
@cindex temperature-salinity diagram, drawing isopycnals on
@cindex isopycnals
@cindex oceanographic plots isopycnals on TS diagram

@example
`draw isopycnal \
   [unlabelled] .density. [.P_sigma. [.P_theta.]]'
@end example

Draw isopycnal curve for a temperature-salinity diagram.  This curve is
the locus of temperature and salinity values which yield seawater of the
indicated density, at the indicated pressure.  The UNESCO equation of
state is used.

For the results to make sense, the x-axis should be salinity and the
y-axis should be either in-situ temperature or potential temperature.

The @code{.density.} unit is kg/m^3.  If the supplied value exceeds 100
then it will be taken to indicate the actual density; otherwise it will
be taken to indicate density minus 1000 kg/m^3.  (The deciding value of
100 kg/m^3 was chosen since water never has this density; the more
intuitive value of 1000 kg/m^3 would be inappropriate since water can
have that density at some temperatures.)  Thus, 1020 and 20 each
correspond to an actual density of 1020 kg/m^3.

The reference pressure for density, @code{.P_sigma.}, is in decibars
(roughly corresponding to meters of water depth).  If no value is
supplied, a pressure of 0 dbar (i.e. atmospheric pressure) is used.

The reference pressure for theta, @code{.P_theta.}, is in decibars, and
defaults to zero (i.e. atmospheric pressure) if not supplied.  This
option is used if the y-axis is potential temperature referenced to a
pressure other than the surface.  Normally the potential temperature is,
however, referenced to the surface, so that specifying a value for
@code{.P_theta.} is uncommon.

By default, labels will be drawn on the isopycnal curve; this may be
prevented by supplying the keyword @code{unlabelled}.  If labels are
drawn, they will be of order 1000, or of order 10 to 30, according to
the value of @code{.density.} supplied (see above).  The label format
defaults to "%g" in the C-language format notation, and may be
controlled by @code{set contour format}.  The label position may be
controlled by @code{set contour label position} command (bug: only
non-centered style works).  Setting label position is useful if labels
collide with data points.  Labels are drawn in the whiteunder mode, so
they can white-out data below.  For this reason it is common to draw
data points after drawing isopycnals.

If the y-axis is in-situ temperature, the command should be called
without specifying @code{.P_sigma.}, or, equivalently, with
@code{.P_sigma.} = 0.  That is, the resultant curve will
correspond to the (S,T) solution to the equation

@example
.density. = RHO(S, T, 0)
@end example

@noindent
where @code{RHO=RHO(S,T,p)} is the UNESCO equation of state for
seawater.  This is a curve of constant sigma_T.

If the y-axis is potential temperature referenced to the surface,
@code{.P_theta.} should not be specified, or should be specified to be
zero.  The resultant curve corresponds to a constant value of
potential density referenced to pressure @code{.P_sigma.}, i.e. the
(S,theta) solution to the equation

@example
.density. = RHO(S, theta, .P_sigma.)
@end example

@noindent
For example, with @code{.P_sigma.=0} (the default), the result
is a curve of constant sigma_theta.

If the y-axis is potential temperature referenced to some pressure other
than that at the surface, @code{.P_theta.} should be supplied.  The
resultant curve will be the (S,theta) solution to the equation

@example
.density. = RHO(S, T', .P_sigma.)
@end example

@noindent
where

@example
T'=THETA(S, theta, .P_theta., .P_sigma.)
@end example

@noindent
where @code{THETA=THETA(S,T,P,Pref)} is the UNESCO formula for potential
temperature of a water-parcel moved to a reference pressure of
@code{Pref}.  Note that @code{theta}, potential temperature referenced
to pressure @code{.P_theta.}, is the variable assumed to exist on
the y-axis.




@node   Draw Isospice, Draw Label Boxed, Draw Isopycnal, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw isospice}
@findex draw isospice
@cindex @code{draw isospice} command
@cindex T-S diagram, drawing spice lines on
@cindex temperature-salinity diagram, drawing spice lines on
@cindex spice lines, on TS diagram
@cindex oceanographic plots, iso-spice lines on TS diagrams

@example
`draw isospice .spice. [unlabelled]'
@end example

@noindent
Draw an iso-spice line for a "TS" diagram, using (S, T) data stored in
files in a subdirectory named @code{iso-spice0} in a directory named by
the unix environment variable @code{GRI_EOS_DIR}.  You must set this
environment variable yourself, in the normal unix way.  If
@code{GRI_EOS_DIR} is not defined, Gri looks in the directory
@file{/data/po/ocean/EOS/iso0}; of course, this will work only
for people on the same machine as the author.

Only certain iso-spice lines are stored in these files, so only certain
values of @code{.spice.} are allowed.  They are 21.75, 22.00, 22.25,
..., 30.75.  You must supply @code{.density.} in exactly this format
(with 2 decimal places), or else Gri will not find the appropriate TS
file, and will give a "can't open file" error.  NB: isopycnals ranging
from about 23.00 to 26.00 cross a TS diagram spanning 34<S<36 and
0<T<10.

The line is labelled at the right with the density value, unless the
@code{unlabelled} option is given.

Clipping should be on when drawing iso-spice lines.  A warning will be
given if the isospice line does not intersect the clipping region.

EXAMPLE

@example
set clip on
draw isospice line 27.00
draw isospice line 27.50 unlabelled
@end example


@node   Draw Label Boxed, Draw Label Whiteunder, Draw Isospice, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw label}
@findex draw label boxed
@cindex @code{draw label boxed} command
@cindex text strings, drawing
@cindex drawing text strings
@cindex drawing labels
@cindex labels, drawing text anywhere

@example
`draw label boxed "string" at .xleft. .ybottom. [cm]'
@end example

@noindent
Draw boxed label for plot, located with lower-left corner at indicated
(x,y) position (specified in user units or in cm on the page).  The
current font size and pen color are used.  The geometry derives from the
current font size, with the label being centered within the box.


@node   Draw Label Whiteunder, Draw Label For Last Curve, Draw Label Boxed, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw label whiteunder}
@findex draw label whiteunder
@cindex @code{draw label whiteunder} command

@example
`draw label whiteunder "\string" at .xleft. .ybottom. [cm]'
@end example

@noindent
Draw label for plot, located with lower-left corner at indicated (x,y)
position (specified in user units or in cm on the page).  Whiteout is
used to clean up the area under the label.  BUGS: Cannot handle angled
text; doesn't check for super/subscripts.


@node   Draw Label For Last Curve, Draw Label, Draw Label Whiteunder, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw label for last curve}
@findex draw label for last curve
@cindex @code{draw label for last curve} command
@cindex drawing labels on xy curves
@cindex labels, for xy curves

@example
`draw label for last curve "label"'
@end example

@noindent
Draw a label for the last curve drawn, using the @code{..xlast..} and
@code{..ylast..} built-in variables.


@node   Draw Label, Draw Line From, Draw Label For Last Curve, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw label}
@findex draw label
@cindex @code{draw label} command

@example
`draw label "\string" [centered|rightjustified] \
    at .x. .y. [cm|pt] \
    [rotated .deg.]'
@end example

@noindent
With no optional parameters, draw string at given location in USER units.

With the @code{cm} or @code{pt} keyword is present, the location is in
centimetres or points on the page.

With the @code{rotated} keyword present, the angle in degrees from the
horizontal, measured positive in the counterclockwise direction, is
given.

With the keyword @code{centered} present, the text is centered at the
given location; similarly the keyword @code{rightjustified} makes the
text end at the given location.



@node   Draw Line From, Draw Line Legend, Draw Label, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw line from ... to}
@findex draw line
@cindex @code{draw line} command

@example
`draw line from .x0. .y0. to .x1. .y1. [cm|pt]'
@end example

@noindent
With no optional parameters, draw a line from (@code{.x0.},
@code{.y0.})  to (@code{.x1.}, @code{.y1}.), where coordinates are in
user units.  With the @code{cm} or @code{pt} keyword present, the
coordinates are in centimetres or points on the page.  NOTE: This will
not cause auto-drawing of axes.



@node   Draw Line Legend, Draw Lines, Draw Line From, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw line legend}
@findex draw line legend
@cindex @code{draw line legend} command

@example
`draw line legend "label" at .x. .y. [cm] [length .cm.]'
@end example

@noindent
Draw a legend identifying the current line type with the given label.  A
short horizontal line is drawn starting at the location (`.x.',
@code{.y.}), which may be specified in centimetres or, the default, in
user coordinates.  The line length is normally 1 cm, but this length can
be set by the last option.  The indicated label string is drawn 0.25 cm
to the right of the line.
     
@strong{See also} @code{draw symbol legend ...}.
     
EXAMPLE (of keeping track of the desired location for the legend)

@example
.offset. = 1                    # cm to offset legends
# ... get salinity data
set line width 0.25
draw curve
draw line legend "Salinity" at .x. .y. 
# ... get temperature data
set line width 1.0
set dash 0.45 0.05
draw curve
.y. += .offset.
draw line legend "Temperature" at .x. .y.
@end example


@node   Draw Lines, Draw Patches, Draw Line Legend, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw lines}
@findex draw lines
@cindex @code{draw lines} command

@example
`draw lines @{vertically .left. .right. .inc.@} | \
    @{horizontally .bottom. .top. .inc.@}'
@end example

@noindent
Draw several lines, either vertically or horizontally.  This can be
useful in drawing gridlines for axes, etc.  The following example shows
how to draw thin gray lines extending from the labelled tics on the x
axis (ie, at 0, 0.1, 0.2, ... 1):

@example
set x axis 0 1 0.1 0.05
set y axis 10 20 10
draw axes
set graylevel 0.75
set line width 0.5
draw lines vertically 0 1 0.1
set graylevel 0
@end example




@node   Draw Patches, Draw Polygon, Draw Lines, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw patches}
@findex draw patches
@cindex @code{draw patches} command
@cindex drawing patches
@cindex patches, drawing

@example
`draw patches .width. .height. [cm]'
@end example

@noindent
With the optional @code{cm} keyword not present, draw column data z(x,y)
as gray patches according to the grayscale as set by most recent
@code{set image grayscale}.  The patches are aligned along the
horizontal, and have the indicated size in user units.

With the optional keyword @code{cm} is present, the patch size is
specified in centimetres.




@node   Draw Polygon, Draw Regression Line, Draw Patches, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw polygon}
@findex draw polygon
@cindex @code{draw polygon} command
@cindex polygons, drawing
@cindex drawing polygons

@example
`draw polygon [filled] .x0. .y0. .x1. .y1. [other pairs] [user|cm|pt]'
@end example

@noindent
Draw a polygon connecting the indicated points, specified in user
units.  The last point is joined to the first by a line segment.  At
least two points must be specified.  If the @code{filled} keyword is
present, the polygon is filled with the current pen color.  If no unit
is given, user units are used.


@node   Draw Regression Line, Draw Symbol At, Draw Polygon, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw regression line}
@findex draw regression line
@cindex @code{draw regression line} command

@example
`draw regression line [clipped]'
@end example

@noindent
Fit and draw a regression line to column data, of the form
 @code{y = ..coeff0.. + ..coeff1.. * x}, exporting @code{..coeff0..},
@code{..coeff0_sig..}, @code{..coeff1..}  and @code{..coeff1_sig..}  as
global variables (@ref{Regress}).

@noindent
Normally, the line is not clipped to the axes frame, but it will be if
the keyword @code{clipped} is given.

@noindent
HINT: to label the plot you might do the following:

@example
sprintf \label "y = %f + %f * x. R$^2$=%f" \
  ..coeff0.. ..coeff1.. ..R2..
draw title "The linear fit is \label"
@end example
     


@node   Draw Symbol At, Draw Symbol Legend, Draw Regression Line, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw symbol ... at}
@findex draw symbol at
@cindex @code{draw symbol at} command

@cindex symbols, drawing single ones
@cindex drawing single symbols

@example
`draw symbol .code.|\name at .x. .y. [cm|pt]'
@end example

@noindent
Draw a symbol at given (single) location.  The location is normally in
user coordinates; it will be in centimetres on the page if the optional
@code{cm} or @code{pt} keyword is given.

With the optional numerical/name code specified, then the symbol of
that number or name is drawn at each (x,y) datum, whether or not a
z-column exists.  The numerical/name codes are:

@c HTML <center><IMG SRC="./resources/symbols.gif" ALT="Symbols in gri"></center>
@c HTML <p>

@c HTML <!--
@example
 # name                description            
-- ----                -----------            
 0 plus                +
 1 times               x
 2 box                 box
 3 circ                circle
 4 diamond             diamond
 5 triangleup          triangle with base at bottom
 6 triangleright       triangle with base at left
 7 triangledown        triangle with base at top
 8 triangleleft        triangle with base at right
 9 asterisk            *
10 star                star of David
11 filledbox           filled box
12 bullet              filled circle
13 filleddiamond       filled diamond
14 filledtriangleup    filled triangleup
15 filledtriangleright filled triangleright
16 filledtriangledown  filled triangledown
17 filledtriangleleft  filled triangleleft
@end example
@c HTML -->


@node   Draw Symbol Legend, Draw Symbol, Draw Symbol At, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw symbol legend}
@findex draw symbol legend
@cindex @code{draw symbol legend} command

@example
`draw symbol legend \symbol_name "label" \
    at .x. .y. [cm]'
@end example

@noindent
Draw indicated symbol at indicated location, with the indicated label
beside it.  The label is drawn one M-space to the right of the symbol,
vertically centered on the indicated @code{.y.} location.



@node   Draw Symbol, Draw Time Stamp, Draw Symbol Legend, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw symbol}
@findex draw symbol
@cindex @code{draw symbol} command

@example
`draw symbol [[.code.|\name]    \
    | [graylevel z]             \
      [color [hue z|.h.]        \
             [brightness .b.]   \
             [saturation .s.]]]'
@end example

@noindent
With no optional parameters, draw symbols at the (x,y) data.  If a
z-column has been read with @code{read columns}, then its value codes
the symbol to draw, according to the table below.  (The value of z is
first rounded to the nearest integer.)  If no z-column has been read,
the symbol X is drawn at each datum.

With the optional numerical/name code specified, then the symbol of
that number or name is drawn at each (x,y) datum, whether or not a
z-column exists.  The numerical/name codes are:
@c HTML <center><IMG SRC="./resources/symbols.gif" ALT="Symbols in Gri"></center>
@c HTML <p>

@c HTML <!--
@example
 # name                description            
-- ----                -----------            
 0 plus                +
 1 times               x
 2 box                 box
 3 circ                circle
 4 diamond             diamond
 5 triangleup          triangle with base at bottom
 6 triangleright       triangle with base at left
 7 triangledown        triangle with base at top
 8 triangleleft        triangle with base at right
 9 asterisk            *
10 star                star of David
11 filledbox           filled box
12 bullet              filled circle
13 filleddiamond       filled diamond
14 filledtriangleup    filled triangleup
15 filledtriangleright filled triangleright
16 filledtriangledown  filled triangledown
17 filledtriangleleft  filled triangleleft
@end example
@c HTML -->

With the optional @code{graylevel z} fields specified, the graylevel is
given by the @code{z} column (0=black, 1=white).

With the optional @code{color} field specified, the color is
specified, either directly in the command (the @code{hue .h.} form) or
in the z column.  For more information on color, refer to the 
@code{set color hsb ...} command.

Examples: both @code{draw symbol bullet color} and 
@code{draw symbol bullet color hue z} draw bullets whose hue is given by
the value in the z column.  The hue (or the color, in other words)
blends smoothly across the spectrum as the numerical value ranges from 0
to 1.  The value 0yields red, 1/3 yields green, 2/3 yields blue, etc.
If the @code{brightness} and the @code{saturation} are not specified,
they both default to the value 1, which yields pure, bright colors.

Example: draw all in green dots
@code{draw symbol bullet color hue 0.333 brightness 1 saturation 1}


Example: display spectrum of dots

@example
set symbol size 0.3
open "awk 'END@{ \
    for(c=0;c<1;c+=1/40) \
        print(c,c,c)@}' | "
read columns x y z
close
draw symbol bullet color hue z
@end example




@node   Draw Time Stamp, Draw Title, Draw Symbol, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw time stamp}
@findex draw times stamp
@cindex @code{draw time stamp} command

@example
`draw time stamp \
    [fontsize .points. \
        [at .x_cm. .y_cm. cm \
            [with angle .deg.]]]'
@end example

@noindent
Draw the command-file name, PostScript file name, and time, at the top
of graph.  Normally, the timestamp is drawn at the top of the page, in a
fontsize of 10 points.  But the user can specify the fontsize, and
additionally the location (in cm) and additionally the angle measured in
degrees anticlockwise from the horizontal.

NOTE: If you want to have the plot drawn in landscape mode, ensure
that @code{set page landscape} precedes @code{draw time stamp.}



@node   Draw Title, Draw Values, Draw Time Stamp, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw title}
@findex draw title
@cindex @code{draw title} command

@example
`draw title "\string"'
@end example

@noindent
Draw the indicated string above the plot.



@node   Draw Values, Draw X Axis, Draw Title, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw values}
@findex draw values
@cindex @code{draw values} command

@example
draw values                 \
    [.dx. .dy.]             \
    [\format]               \
    [separation .xcm. .ycm.]
@end example

@noindent
Draw values of @code{z} column, at corresponding (@code{x}, @code{y})
locations.  If the @code{separation} keyword is present, the distance
between successive points is checked, and points are skipped unless the
x and y separations exceed the indicated distances.

@itemize @bullet

@item @code{draw values}
Draw the values of @code{z(x,y)}, positioned 1/2 M-space to the right of
@code{(x,y)} and vertically centred on @code{y}.  The values are written
in a good general format known as @code{%lg}, in C terminology.

@item @code{draw values %.2f}
Draw values of @code{z(x,y)} positioned as described above, but using
the indicated format string.  This format string specifies that 2
numbers be used after the decimal place, and that floating point should
be used.  See any C manual for format codes.

@item @code{draw values .dx. .dy.}
Print values of @code{z(x,y)} at indicated offset vector
(@code{.dx.},@code{.dy.}), measured in centimeters, from the values of
@code{(x,y)} at which the data are defined.

@item @code{draw values .dx. .dy. %.3f}
Print values of @code{z(x,y)} at indicated distance from @code{(x,y)},
indicated format.
@end itemize



@node   Draw X Axis, Draw X Box Plot, Draw Values, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw x axis}
@findex draw x axis
@cindex @code{draw x axis} command

@example
draw x axis [at bottom|top|@{.y. [cm]@} [lower|upper]]
@end example

@noindent
Draw an x axis, optionally at a specified location and of a specified
style.
@itemize @bullet

@item @code{draw x axis}
Draw a lower x axis (ie, one with the numbers below the line) at the
bottom of the box defined by @code{set y axis}.

@item @code{draw x axis at bottom}
Draw a lower x axis (ie, one with the numbers below the line) at the
bottom of the box defined by @code{set y axis}.

@item @code{draw x axis at top}
Draw an upper x axis (ie, one with the numbers above the line) at the
top of the box defined by @code{set y axis} (or above any existing
stacked x axes there)

@item @code{draw x axis at .y.}
Draw a lower x axis at indicated value of @code{.y.}.

@item @code{draw x axis at .y. upper}
Draw an upper x axis at indicated value of .y.
@end itemize



@node   Draw X Box Plot, Draw Y Axis, Draw X Axis, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw x box plot}
@findex draw x box plot
@cindex @code{draw x box plot} command

@example
draw x box plot at .y. [size .cm.]
@end example

@noindent
Draw Tukey box plots (which give a summary of histogram properties).
Box plots were invented by Tukey for eda (exploratory data analysis).
The centre of the box is the median.  The box edges show the first
quartile (q1) and the third quartile (q3).  The distance from q3 to q1
is called the inter-quartile range.  The whiskers (i.e., the lines with
crosses at the end) extend from q1 and q3 to the furthest data points
which are still within a distance of 1.5 inter-quartile ranges from q1
and q3.  Beyond the whiskers, all outliers are shown: open circles are
used for data within a distance of 3 inter-quartile ranges beyond q1 and
q3, and in closed circles beyond that.

As a side effect, this command stores q1, q2, and q3 
into variables @code{..q1..}, @code{..q2..}, and @code{..q3..}.


@itemize @bullet

@item @code{draw x box plot at .y.}
Draw Tukey's box plot, spreading in the x direction, centered at
y=@code{.y.} and of default width 0.5 cm.

@item @code{draw x box plot at .y. size .cm.}
Draw Tukey's box plot, spreading in the x direction, centered at
y=@code{.y.} and of width @code{.cm.} centimetres.
@end itemize



@node   Draw Y Axis, Draw Y Box Plot, Draw X Box Plot, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw y axis}
@findex draw y axis
@cindex @code{draw y axis} command

@example
draw y axis [at left|right|@{.x. cm@} [left|right]]
@end example

@noindent
Draw a y axis, optionally at a specified location and of a specified
style.

@itemize @bullet

@item @code{draw y axis}
Draw a left-hand-side y axis (ie, one with the numbers to the left of
the line) at left of box defined by `set x axis'

@item @code{draw y axis at left}
Draw a left-hand-side y axis (ie, one with the numbers to the left of
the line) at left of box defined by @code{set x axis}.

@item @code{draw y axis at right}
Draw a right-hand-side y axis (ie, one with the numbers to the right of
the line) at right of box defined by @code{set x axis}.

@item @code{draw y axis at .x.}
Draw a left-hand-side y axis (ie, one with the numbers to the left of
the line) at indicated value of @code{.x.}

@item @code{draw y axis at .x. right}
Draw a right-hand-side y axis (ie, one with the numbers to the right of
the line) at indicated value of @code{.x.}
@end itemize



@node   Draw Y Box Plot, Draw Zero Line, Draw Y Axis, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw y box plot}
@findex draw y box plot
@cindex @code{draw y box plot} command

@example
draw y box plot at .x. [size .cm]
@end example

@noindent
Draw Tukey box plots (which give summary of histogram properties).
@itemize @bullet

@item @code{draw y box plot at .x.}
Draw Tukey's box plot, spreading in the y direction, centered at
x=@code{.x.} and of default width 0.5 cm.

@item @code{draw y box plot at .x. size .cm.}
Draw Tukey's box plot, spreading in the y direction, centered at
x=@code{.x.} and of width @code{.cm.} centimetres.
@end itemize

As a side effect, this command stores q1, q2, and q3 
into variables @code{..q1..}, @code{..q2..}, and @code{..q3..}.



@node   Draw Zero Line, End Group, Draw Y Box Plot, Draw
@comment  node-name,  next,  previous,  up
@subsubsection @code{draw zero line}
@findex draw zero line
@cindex @code{draw zero line} command

@example
draw zero line [horizontally|vertically]
@end example

@noindent
Draw lines corresponding to x=0 or y=0.
@itemize @bullet

@item @code{draw zero line}
Draw line y=0 if it is within axes.

@item @code{draw zero line horizontally}
Draw line y=0 if it is within axes.

@item @code{draw zero line vertically}
Draw line x=0 if it is within axes.
@end itemize


@c HTML <!-- newfile EndGroup.html "Gri: `end group' command" "Gri Commands" -->

@node   End Group, Expecting, Draw Zero Line, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsubsection @code{end grouip}
@findex end group
@cindex @code{end group} command

@example
end group
@end example

@noindent
@emph{Command not implemented yet.  Syntax may change.}





@c HTML <!-- newfile Expecting.html "Gri: `expecting' command" "Gri Commands" -->

@node   Expecting, Filter, End Group, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{expecting}
@cindex changes to Gri, protection against
@cindex protection against changes to Gri
@findex expecting
@cindex @code{expecting} command
@cindex incompatibilities, keeping track of

@example
expecting version a.b
expecting version a.b.c
@end example

@noindent 

Show a list of incompatibilites that have been introduced since the
named version.  This command can make your commandfiles more reliable
against changes to Gri.

There are two forms of the version number.  Modern versions use the
triplet form, e.g.  @code{expecting version 2.8.7}, but prior to
October 1996 the version numbers were written in decimal form, so that
you would write @code{expecting version 1.069} for example.

@c HTML <!-- newfile Filter.html "Gri: `filter' command" "Gri Commands" -->

@node   Filter, Flip, Expecting, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{filter}
@cindex columns, filtering
@cindex images, filtering
@cindex filtering image data
@cindex filtering column data
@cindex smoothing column data

@findex filter
@cindex @code{filter} command

@itemize @bullet

@item @code{filter column x|y|z|u|v|weight recursively a[0] a[1] ... b[0] b[1] ...}
Filter indicated column, using a two-pass recursive filter.  The first
pass runs from the start to the end, while the second pass runs from the
end to the start; in this way, the phase shift inherent in this type of
filter is removed entirely.  The coefficients are used in the following
formula (demonstrated on the @code{x} column):

@example
x_new[i] = b[0] * x[i] \
  + b[1] * x[i-1] \
  + b[2] * x[i-2] \
  + ... \
  - a[1] * x_new[i-1] \
  - a[2] * x_new[i-2] \
  - ...
@end example

@noindent
Thus, for example, setting @code{a[i]} = 0 results in a simple
backwards-looking moving-average filter applied in two passes.  The real
power of this type of filter, however, comes when non-zero @code{a[i]}
coefficients are given, thus adding recursion (i.e., @code{x_new[i]}
depends on @code{x_new[i-...]}).  See any standard reference on digital
filters for an explanation.  You might find that the Matlab command
@code{butter} an easy way to design filter coefficients.  Here are some
examples:

@example
# Filter x column with simple 2-point moving
# average.  (This slurs into a 3-point moving
# average, in effect, since the filter is run
# forwards and then backwards.)
filter column x recursively 0 0 0.5 0.5

# Use filter designed with the Matlab 
# command butter(2,0.1), which creates a 
# 2nd order lowpass butterworth filter
# with a cutoff frequency of 0.1 
# (in units which have a frequency 
# of 1 corresponding to one-half the
# sampling rate).
filter column x recursively \
    1     -1.561  0.6414 \
    0.0201 0.0402 0.0201
@end example

@item @code{filter grid rows|columns recursively a[0] a[1] ... b[0] b[1] ...}
@noindent
Apply recursive filter (see @code{filter column ... recursively} for
meaning of this filter operation) to the individual rows or columns of
the grid data.  For example, the command 
@code{filter grid columns recursively 0 0 0.5 0.5} 
applies a 2-point moving average filter across the columns,
smoothing the grid in the x-direction.

@item @code{filter image highpass}
Remove low-wavenumber components from image (ie, sharpen edges).  Do
this by subtracting a Laplacian smoothed version of the image.

@item @code{filter image lowpass}
Remove high-wavenumber components from image (ie, smooth shapes).  Do
this by Laplacian smoothing.
@end itemize

@strong{See also} @ref{Smooth}.


@c HTML <!-- newfile Flip.html "Gri: `flip' command" "Gri Commands" -->

@node   Flip, Get Env, Filter, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{flip}
@cindex grid, flipping
@cindex image, flipping
@cindex flipping grids and images
@findex flip
@cindex @code{flip} command

@example
`flip grid|image x|y'
@end example

@noindent
Flip grid or image by relecting it about a horizontal or vertical
centerline.
@itemize @bullet

@item @code{flip grid x}
Flip grid so right-hand side becomes left-hand side.

@item @code{flip grid y}
Flip grid so bottom side becomes top side.

@item @code{flip image x}
Flip image so right-hand side becomes left-hand side.

@item @code{flip image y}
Flip image so bottom side becomes top side.
@end itemize



@c HTML <!-- newfile GetEnv.html "Gri: `get env' command" "Gri Commands" -->


@node   Get Env, Group, Flip, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{get env}
@cindex environment variables
@cindex unix environment variables
@cindex operating system, getenv
@cindex operating system, environment variables
@findex get env
@cindex @code{get env} command

@example
`get env \result \environment_variable'
@end example

@noindent
Get the value of an "environment variable" from the unix operating system,
and store the result in the indicated synonym.  This makes most sense on
unix systems (hence the name, patterned after the unix command
@code{getenv}).  This command can be useful in making gri programs
resistant to changes in data-file locations.  Suppose, for example,
there is a file called @file{data}, normally in a local directory called
@code{Bravo}.  The line @code{open Bravo/data} will fail if the Bravo
directory is moved.  But if the name of the datafile is stored in an
unix environment variable, @code{DIR_BRAVO} say, then the gri program will
work no matter where the Bravo data are moved, so long as an appropriate
environment variable is modified when the data are moved.  Example:

@example
get env \dir DIR_BRAVO
if @{rpn "\dir" "" ==@}
    show "Cannot determine location of the Bravo data,"
    show "which should be stored in the environment"
    show "variable DIR_BRAVO.  You should"
    show "do something like"
    show "export DIR_BRAVO='/data/Bravo/'"
    show "in your ~/.environment file"
    quit
end if
open \dir/data
...
@end example


@c HTML <!-- newfile Group.html "Gri: `group' command" "Gri Commands" -->

@node   Group, Heal, Get Env, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{group}
@findex group
@cindex @code{group} command

@example
`group ["\name"]'
@end example

@noindent
@emph{Command not implemented yet.  Syntax may change.}


@c HTML <!-- newfile Heal.html "Gri: `heal' command" "Gri Commands" -->

@node   Heal, Help, Group, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{heal}
@findex heal
@cindex @code{heal} command

@example
heal columns|@{columns along x|y@}
@end example
The @code{heal} command heals over gaps in either columnar or gridded
data.  This is done by linear interpolation across the missing-value
gaps.

@itemize @bullet

@item @code{heal columns}
@noindent
Fill in missing values in x, y, z, ... columns, by linear interpolation
to neighboring valid data.  All gaps in the data will get replaced
by a linear function of index which matches the data at the indices just
before and just after the gap.  For example, if the y data were
like

@example
111
3
-9
-9
-9
7
333
@end example

@noindent
where @code{-9} is the missing-value code, then they would get
replace by

@example
111
3
4
5
6
7
333
@end example

@noindent
Notes: (1) This is done @strong{independently} for all existing columns.
(2) Gaps at the start and end of the columns are not filled in.

@item @code{heal grid along x}
@noindent
Scan in the x direction, filling in missing values by linear
interpolation.  Since this uses the the x-grid, you must first have done
@code{read grid x} or @code{set x grid}.

@item @code{heal grid along y}
@noindent
Scan in the y direction, filling in missing values by linear
interpolation.  Since this uses the the y-grid, you must first have done
@code{read grid y} or @code{set y grid}.
@end itemize


@c HTML <!-- newfile Help.html "Gri: `help' command" "Gri Commands" -->

@node   Help, If, Heal, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{help}
@findex help
@cindex @code{help} command

@example
`help [*|command_name|@{- topic@}]'
@end example

@noindent
Give help on a command or topic.
@itemize @bullet

@item @code{help}
Print a general help message.

@item @code{help *}
Prints complete help info.

@item @code{help command_name}
Prints help on the command whose name begins with the
string @code{command_name}.  The string may be several words long; e.g.
@code{help set} or @code{help set x axis}.

@item @code{help - topic_name}
The minus sign tells Gri that the string to follow it is a topic, not a
command.  Topics Gri knows about are listed by the one-word @code{help}
request.
@end itemize



@c HTML <!-- newfile If.html "Gri: `if' command" "Gri Commands" -->

@node   If, Ignore, Help, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{if}
@cindex if statements
@findex if
@cindex @code{if} command
(@strong{See also} @ref{If Statements}.)

@example
`if @{[!] .flag.@}|\flag|@{@{"string1" == "string2"@}@}'
@end example

@noindent
Control program flow.  The @code{if} block is ended with a line
containing @code{end if}.  Optional @code{else} and @code{else if}
blocks are allowed.  Note that rpn expressions are allowed, and a
special form of string comparison is allowed, as in the examples below.

@example     
if .flag.
  # List of Gri commands to be done if .flag. is 1.
  # This list may extend across any number of lines.
end if
@end example

@noindent
If the variable @code{.flag.} is not equal to 0, do the code between the
@code{if} line and the @code{end if} line.

@example
if .flag.
  # Commands done if .flag. is 1
else
  # Commands done if .flag. is 0
end if
@end example

@noindent
If the variable @code{.flag.} is not equal to 0, do the code between the
@code{if} line and the @code{else} line.  If @code{.flag.} is equal to
0, do the code between the @code{else} line and the @code{end if} line.

@example
if ! .flag.
  # Commands done if .flag. is 0
end if
@end example

@noindent
If the variable @code{.flag.} is equal to 0, do the code between the
@code{if} line and the @code{end if} line.


@example
if @{rpn .flag. 10 <@}
  # Commands done if 10 is less than .flag.
end if
@end example

@noindent
If the variable @code{.flag.} is greater than 10, 
do the code between the
@code{if} line and the @code{end if} line.

@example
if \smooth
  # Commands done if \smooth is 1
else
  # Commands done if \smooth is 0
end if
@end example

@noindent
If the number stored in the synonym @code{\smooth} is not equal to 0, do
the code between the @code{if} line and the @code{else} line.  If the
synonym stores a representation of a number not equal to zero, do the
@code{else} part.  If the synonym contains text that does not decode to
a number, generate error message.

@example
if @{"\item" == "Temperature"@}
  # Commands done if the synonym \item is equal to the
  # indicated text string.
end if
@end example

@noindent
If the synonym @code{\item} has the value @code{Temperature} stored in
it, do the indicated code.

@example
if @{rpn "\item" "Temperature" ==@}
  # Commands done if the synonym \item
  # equals indicated text string.
end if
@end example

@noindent
As above, but using the @code{rpn} calculator 
(@ref{rpn Mathematics}).   

@example
if @{rpn "\item" "Temperature" !=@}
  # ...
end if
@end example

@noindent
As above, but do the indicated code if @code{\item} is @strong{not} equal
to @code{Temperature}.



@c HTML <!-- newfile Ignore.html "Gri: `ignore' command" "Gri Commands" -->

@node   Ignore, Input, If, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{ignore}
@findex ignore
@cindex @code{ignore} command

@example
`ignore last .n.'
@end example

@noindent
Ignores last @code{.n.} lines read by @code{read columns}.


@c HTML <!-- newfile Input.html "Gri: `input' command" "Gri Commands" -->

@node   Input, Insert, Ignore, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{input}
@findex input
@cindex @code{input} command

@example
`input \ps_filename \
  [.xcm. .ycm. \
    [.xmag. .ymag. \
      [.rot_deg.]]]'
@end example

@noindent
Input the named PostScript file directly into the Gri output PostScript
file.  (If the filename has punctuation, insert it in double quotes,
e.g. @code{input "../thefile"}.)  If no options are specified, the file
is input at normal scale, with normal margins.  (Aside to PostScript
programmers: the named file is sandwiched between @code{gsave} and
@code{grestore} commands.)  If @code{.xcm.} and @code{.ycm.} are
specified, then the origin is moved to the named location first.  If, in
addition, @code{.xmag.} and @code{.ymag.} are specified, then these are
used as scale factors after translation.  Finally, if @code{.rot_deg.}
is specified in addition, then the indicated counterclockwise rotation
is applied after translation and scaling.  Hint: if the results look
wrong, the first thing to do is to think carefully about the order of
the (translation, scaling, rotation) operations.



@c HTML <!-- newfile Insert.html "Gri: `insert' command" "Gri Commands" -->

@node   Insert, Interpolate, Input, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{insert}
@findex insert
@cindex @code{insert} command

@example
`insert \filename'
@end example

@noindent
Perform the commands in the indicated file.

If the file name is absolute (i.e. starts with @code{.}, or with
@code{/} or with @code{~}) then an error results if the file is not
present (or cannot be read by this user).

However, if the file name starts with a normal letter, Gri will try
harder to locate the file.  If it is not in the local directory, and if
a @code{set path to "PATH" for commands} has been done, then Gri will
search the colon-separated directories for the file (@ref{Set Path To}).

If you don't want path-searching done, use the @code{source} command
instead (@ref{Source}).



@c HTML <!-- newfile Interpolate.html "Gri: `interpolate' command" "Gri Commands" -->

@node   Interpolate, List, Insert, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{interpolate}
@findex interpolate
@cindex @code{interpolate} command
@cindex contouring, interpolating to new grid
@cindex grid, interpolating from one to another

@example
interpolate x grid to .left. .right. .inc.|@{/.cols.@}'
interpolate y grid to .bottom. .top. .inc.|@{/.rows.@}'
@end example

@noindent
Transform grid by interpolating between existing grid data, according to
a new x or y grid specified in the manner of @code{set x grid} and
@code{set y grid}.  Note that the new grid is neccessarily regular,
while the first grid needn't have been.  The data of the new grid are
constructed by interpolation, using the same interpolation algorithm as
the @code{convert grid to image} command.



@c HTML <!-- newfile List.html "Gri: `list' command" "Gri Commands" -->

@node   List, Ls, Interpolate, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{list}
@findex list
@cindex @code{list} command

@example
`list \command-syntax'
@end example

@noindent
List the source of a gri command.  Often this is just the name of a C
function internal to gri (try @code{list list} for an example), but when
the command is written in the gri programming language the source will
be more understandable (try @code{list set panel}).


@c HTML <!-- newfile Ls.html "Gri: `ls' command" "Gri Commands" -->

@node   Ls, Mask, List, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{ls}
@cindex files, listing
@cindex directory listing
@findex ls
@cindex @code{ls} command

@example
`ls [\file_specification]'
@end example

@noindent
List files in current directory.  (The current directory can be printed
by the gri command @code{pwd} and can be set by the gri command
@code{cd}.)  @code{ls \file_specification} lists files in current
directory which match the file specification.  Normal unix file
specification options are understood.


@c HTML <!-- newfile Mask.html "Gri: `mask' command" "Gri Commands" -->

@node   Mask, New, Ls, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{mask}
@cindex masking image
@cindex image, masking
@findex mask
@cindex @code{mask} command

@example
`mask the image [to @{uservalue .u.@}|@{imagevalue .i.@}]'
@end example

@noindent
Examine both the image and the mask pixel by pixel.  For any pixels
which have a mask value of 1 (which indicates an invalid region of the
image), change the image value.  If no @code{to} phrase is present,
change the image value to 0 in pixel units.  If the 
@code{to uservalue .u.} phrase is present, change the pixel to hold the
imagevalue that 
corresponds to this uservalue (see @code{set image range} command for
a discussion of this correspondance).  If the @code{to imagevalue .i.}
phrase is present,
change the pixel to hold that imagevalue (in range 0 to 255 inclusive
for 8-bit images).


@c HTML <!-- newfile New.html "Gri: `new' command" "Gri Commands" -->

@node   New, Newpage, Mask, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{new}
@findex new
@cindex @code{new} command
@cindex synonyms, multiple copies of
@cindex synonyms, making local versions
@cindex variables, making local versions
@cindex variables, multiple copies of

@example
new .variable_name. | \synonym_name \
   [.variable_name. | \synonym_name \
   [...]]
@end example

@noindent
@code{new} sets aside storage for new version of the named variable(s)
and/or synonym(s).  Any number of variables and synonyms may be
specified.  If a given variable/synonym already exists, this will create
a new version of it, and future assignments will be stored in this new
version @strong{without} affecting the pre-existing version.  If the
variable/synonym is @code{delete}ed, the new version is deleted, making
the old, unaltered, version accessible again.

This command is used mostly for temporary use, to prevent clashing with
existing values.  Suppose you want to change the font size inside a new
command or an if block.  Then you might do the following, where the
variable @code{.tmp.} is used to store the old font size.  Note that the
use of the @code{new/delete} statements prevents the assignment to the
local version of the variable @code{.tmp.} from affecting the value
known outside the @code{if} block, if in fact @code{.tmp.} happened to
exist outside the block.

@example
set font size 10
draw label "This is in fontsize 10" at 10 2 cm
if .want_title.
  new .tmp.
  .tmp. = ..fontsize..
  set font size 22
  draw label "This is 22 font" at 10 5 cm
  set font size .tmp.
  delete .tmp.
end if
draw label "This is 10 font" at 10 8 cm
@end example

@strong{Special case}: for local synonyms (e.g. @code{\.word1.}, etc.),
the @code{new} operator checks to see whether the synonym is standing
for an "ampersand" argument, signalling a changeable argument that is a
variable or a synonym.  In such a case, @code{new} creates a new
instance of the item in the calling context.  The test suite has
examples (@ref{Test Suite}).

@c HTML <!-- newfile Newpage.html "Gri: `newpage' command" "Gri Commands" -->

@node   Newpage, New Postscript File, New, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{new page}
@cindex page breaks
@findex new page
@cindex @code{new page} command

@example
`new page'
@end example

@noindent
Finish the present page, and start a new page.  All settings (of
linewidth, axes, landscape/portrait, etc) are retained on the new page.
Among these settings is the flag that tells gri whether you need axes
plotted along with your data.


@node   New Postscript File, Open, Newpage, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{new postscript file}
@findex new postscript file
@cindex @code{new postscript file} command

@example
`new postscript file "name"'
@end example

@noindent
Finish the present Postscript file, and start a new page with the given
name.  All settings (of linewidth, axes, landscape/portrait, etc.) and
data are retained on the new file.



@c HTML <!-- newfile Open.html "Gri: `open' command" "Gri Commands" -->

@node   Open, Opening Simple Files, New Postscript File, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{open}
@findex open
@cindex @code{open} command
@cindex netCDF files, opening
@cindex operating system, filtering datafiles
@cindex system commands acting as datafiles
@cindex data files, opening
@cindex opening data files
There are two styles of @code{open} command.  In the first style, a
simple file is to be opened.  In the second style a unix-like "pipe" is
opened, i.e. Gri will read the output of a system command instead of a
file.
@menu
* Opening Simple Files:: 
* Opening Pipes::
* Opening URLs::
@end menu


@node   Opening Simple Files, Ascii Files, Open, Open
@comment  node-name,  next,  previous,  up
@subsubsection Opening simple files

@menu
* Ascii Files::
* Binary Files::
* NetCDF Files::
@end menu

@node   Ascii Files, Binary Files, Opening Simple Files, Opening Simple Files
@comment  node-name,  next,  previous,  up
@b{Ascii Files}
Most applications involve ascii files, and these are very easy to handle
in Gri.  For example given a data file named @file{foo.dat}, just use
the command

@example
open foo.dat
@end example

@noindent
and then you can read the data using various commands.  Thus a complete
program might be

@example
open foo.dat
read columns x y
draw curve
@end example

If a filename contains blanks or punctuation symbols, you must put it in
double quotes (@code{"}), e.g.

@example
open "foo bar.dat"
@end example

Indeed, Gri accepts double-quotes on any @code{open} command and some
folks use it on all commands, as a matter of habit.

Gri can handle compressed files appropriately, e.g.

@example
open foo.data.gz
@end example

@noindent
so that there is no need to uncompress data for use with Gri.

@cindex compressed files, opening
@cindex gzipped files, opening
@cindex opening gzipped
@cindex opening compressed files

Gri is quite persistant in looking for your file, and if a given file is
not found, it will then check to see if a compressed version is
available, and use that instead.  Thus

@example
open foo.dat
@end example

@noindent
will look for a file named @file{foo.dat.gz} if @file{foo.dat} is not
available.  (Only files compressed with the GNU @code{gzip} utility are
handled.)

If the @code{open} command was successful in opening the file, it will
set the value of the synonym @code{\.return_value.} to the @b{full}
pathname of the file.  Thus, if @code{open a.dat} is done in directory
@code{/home/gri}, then @code{\.return_value.} will equal
the string @code{/home/gri/a.dat}.


@node   Binary Files, NetCDF Files, Ascii Files, Opening Simple Files
@comment  node-name,  next,  previous,  up
@cindex binary data

@b{Binary Files}
@cindex endian file compatibility, caution
@cindex little-endian vs big-endian data, caution
@cindex big-endian vs little-endian data, caution
Like most computer programs, Gri has some trouble with binary files.
One big issue is the so-called "endian" character of the computer.  Some
computers store multi-byte values with the most significant bytes first,
while others store them with the most significant bytes last.  The
problem is that nothing is stored in data files to indicate which
convention was employed.  For this reason, a version of Gri compiled on
a so-called "big-endian" computer will misinterpret multi-byte values
that were created on a so-called "little-endian" computer.  Many folks
in the scientific community have converted to using the NetCDF format
(see next section) for precisely this reason, since this format is
independent of the endian character of the computer.

Presuming an appropriate endian character, however, reading is
straightforward.  A command of the form

@example
open foo.dat binary
@end example

@noindent
tells Gri that the data are stored in a binary format.  With the above
syntax, Gri expects images to be in @code{unsigned char} (8 bits), while
other data, such as columns and grids, are expected to be in 32-bit
format (suitable for reading into a so-called "float" variable in the C
programming language).

You may also specify the format directly, as in the following examples;
Gri then interprets all data as being in the indicated format and then
converts to the internal format before using the data.

@example
open \filename binary uchar
open \filename binary 8bit
open \filename binary int
open \filename binary float
open \filename binary double
open \filename binary 16bit
@end example

As with ascii files, Gri will automatically uncompress any files that
are compressed, and if it fails to find a given filename, it will try to
open a compressed version of it (i.e. one with a @file{.gz} suffix).


@node   NetCDF Files, Opening Pipes, Binary Files, Opening Simple Files
@comment  node-name,  next,  previous,  up
@b{NetCDF Files}
@cindex netcdf data
The NetCDF format provides the best of both worlds.  It is binary, so
that data are relatively compact, and may be read very quickly.
(Reading ascii data is time-consuming in C++, the language in which Gri
is written.)  But it does not suffer the endian problem problem of
normal binary files (see previous section), since information about the
endian character is stored in the file itself, and Gri uses this
information to decode the data without difficulty, regardless of the
endian characteristics of the computer on which Gri is running and of
the computer that created the data.

For more information on netCDF format, see

@code{http://www.unidata.ucar.edu/packages/netcdf/index.html}
@c HTML <a href="http://www.unidata.ucar.edu/packages/netcdf/index.html">
@c HTML here </a>.

The syntax of opening NetCDF files is as below

@example
open foo.nc netCDF
@end example

@noindent
and the syntax for reading such files is described in sections on the
various @code{read} commands (see e.g. @ref{Read Columns}).



@node   Opening Pipes, Opening URLs, NetCDF Files, Open
@comment  node-name,  next,  previous,  up
@subsubsection Opening pipes
@cindex pipes, opening files through them

Sometimes it makes sense to get Gri to work with the results of another
command in the OS.  Gri handles this by creating a so-called "pipe",
thus reading the output from the other command.  (Readers familiar with
the unix OS will know what pipes are all about, and especially why they
are a good thing.  Other readers might wish to skip this section.)

Suppose we wish to plot an x-y plot using just the first few lines of a
datafile named @file{foo.dat}.  Unix users will know that a good way to
see the first few lines of such a file would be to type the command
@code{head foo.dat}.  They also know that these lines could be provided
to a second unix command, named @file{do_foo} say, by the command
@code{head foo.dat | do_foo}.  This uses a so-called "pipe", designated
by the vertical line (called a pipe symbol below).

Gri can read the output from system commands by using a syntax in which
the (quoted) system command ends in a pipe symbol, e.g.

@example
open "head foo.dat |"
@end example

@noindent
as in the example above.

@strong{Aside}: When pipe-open commands are used, Gri creates a temporary
file (often located in @file{/usr/tmp}, but that varies with machine).
This is automatically cleaned up when Gri completes executation, but if
Gri dies (or is interrupted) before it finishes, you'll be left with an
extra file in this temporary-storage directory.  It's up to you to clean
that directory up from time to time.

Some common examples of pipe-open commands are given below.

@enumerate

@item
@cindex csv data
@cindex data, csv
@cindex data, comma-separated values
@cindex data, stored in comma-separated values
@cindex data, from a spreadsheet
@cindex data, spreadsheet
@cindex comma-separated values
@cindex spreadsheet data
@strong{Comma-separated values} are common in files created by, or
intended for, spreadsheets.  Since Gri expects data elements to be
separated by blanks (or tabs), you'll have to convert the commas into
blanks.  There are many ways to do that using pipes, e.g.
@file{sed} system utility, e.g.

@example
open "sed -e 's/,/ /g' foo.dat |"
@end example

Other unix facilities, such as @code{tr} will also work, of course.  If
the file has headers, you'll want to remove them also.  This can be done
with the @code{skip} command (@ref{Skip}) but you could also do it at
the open stage, e.g. to remove the first two lines, use

@example
open "sed -e 's/,/ /g' foo.dat | tail +2 |"
@end example

@item
@strong{Manipulating column data} is done by e.g.

@example
open "cat foo.dat | awk '@{$1, $2 * 22@}' |"
@end example

@noindent
where @file{awk} has been used to multiply the second column in the file
named @file{foo.dat} by 22.


@item
@strong{Time-based and geographical data} are sometimes encountered.  For
an example, suppose that longitude/latitude (i.e. x/y) data are stored
in Hour.minutesecond format, e.g. 12.2133 means hour 12, minute 21,
second 33.  Gri doesn't read HMS format, but gawk can be told to:

@cindex geography, converting hour-minute-second to decimal hour
@cindex maps, converting hour-minute-second to decimal hour
@cindex conversion, hour-minute-second to decimal hour
@cindex hms format
@cindex hour, minute, second data
@cindex gawk, using to convert files from HMS to decimal

@example
open "cat datafile.HMS |        \
    awk '@{                      \
    split($1, hms, \".\");      \
    h = hms[1];                 \
    m = int(hms[2] / 100);      \
    s = hms[2] - 100 * m;       \
    x = h + m / 60 + s / 3600;  \
    split($2, hms, \".\");      \
    h = hms[1];                 \
    m = int(hms[2] / 100);      \
    s = hms[2] - 100 * m;       \
    y = h + m / 60 + s / 3600;  \
    print(x,y)                  \
    @}' | "
    read columns x y
@end example

@item
@strong{Timeseries data} are often stored in formats that blend letters
and numbers.  For one thing, using letters (e.g. @code{aug}) removes an
ambiguity in numerically-based data.  (Example: 02/03/2000 means one
thing to an American and another thing in the rest of the world.
However, everybody agrees on what 2000-Feb-03 means.)  Suppose, for
example, that we have data in a format such as

@example
Tue_Jul_25_11:07:51 0.62
Tue_Jul_25_11:22:51 0.59
Tue_Jul_25_11:37:51 0.56    
@end example

@noindent
(stored in a file called @file{foo.dat} say) and we want a graph of the
y-variable (0.62, 0.59, 0.56) versus x-variable, time expressed say as
seconds in the day.  Then here is how that could be done:

@example
open "cat foo.dat |\
    sed -e 's/_/ /g' -e 's/:/ /g' |\
    awk '@{print ($4*3600+$5*60+$6, $7)@}' |"
read columns x y
draw curve
@end example

Note that the actual day information is skipped in this example;
seasoned @code{awk} users could easily fill in the code to handle
datasets spanning several days.
@end enumerate

@node   Opening URLs, Postscript, Opening Pipes, Open
@comment  node-name,  next,  previous,  up
@subsubsection Opening URLs
@cindex URL, how to open

Gri can open a URL, @emph{if} you have the @code{wget} program on your
machine.  (@code{wget} is available from the GNU website
@url{http://www.gnu.org/software/wget/}.)

The URL must be enclosed in quotes (since otherwise, 
Gri will interpret the @code{//} sequence as indicating an old way
of denoting comments).  For example,
@example
open "http://gri.sourceforge.net/gridoc/examples/example1.dat"
read columns x y
show columns
@end example

If you don't have @code{wget} installed on your machine, the above won't
work, but you can always use another fetching program, with a system
call, as in the following:
@example
\url = "http://gri.sourceforge.net/gridoc/html/examples/example1.dat"
open "lynx -dump \url |"
read columns x y
draw curve
@end example




@c HTML <!-- newfile PostScript.html "Gri: `postscript' command" "Gri Commands" -->

@node   Postscript, Pwd, Opening URLs, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{postscript}
@cindex write PostScript commands directly to output file
@cindex postscript file, write to
@findex postscript
@cindex @code{postscript} command

@example
`postscript \string'
@end example

@noindent
Write the indicated string to the PostScript output file, after
substitution of synonyms if there are any.  Example:

@example
\a = "45"  # angle
\w = "8.5" # page width
postscript gsave \w 72 mul 0 translate \a rotate
# ... other code to do stuff
postscript grestore
@end example

Here is how to draw an image palette vertically instead of horizontally:

@example
\X = "3"	# cm
\Y = "10"	# cm
\a = "90"       # degrees counterclockwise
postscript gsave \X 28.35 mul \Y 28.35 mul translate \a rotate
# Palette is at user's origin
draw image palette box 0 0 10 1
postscript grestore
@end example

NOTE: the @code{postscript} command is @strong{very} dangerous, and should
normally only be used by developers.  Most of the code concerning this
is in the file @file{doline.cc}; look for the string
@code{postscriptCmd} to find the relevant code.


@c HTML <!-- newfile Pwd.html "Gri: `pwd' command" "Gri Commands" -->

@node   Pwd, Query, Postscript, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{pwd}
@cindex directory, how to find out
@findex pwd
@cindex @code{pwd} command

@example
`pwd'
@end example

@noindent
Print current directory (which can be set by @code{cd}).



@c HTML <!-- newfile Query.html "Gri: `query' command" "Gri Commands" -->

@node   Query, Quit, Pwd, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{query}
@findex query
@cindex @code{query} command
@cindex user interaction, @code{query} command
@cindex interaction with user, @code{query} command

@example
`query \synonym|.variable. \
  ["\prompt" ["\default"|.default.]]'
@end example

@noindent
Ask the user for the value of a variable (number) or synonym (text
string).  Gri recognizes the type of the item being asked for, either a
variable or synonym, by the presence of a dot or backslash in the second
word of the command line.  If a prompt string is given (in quotes), then
this string is shown to the user.  If a default is given (in
parentheses), then it will be displayed also, and if the user types
carriage-return, then that item will be assigned to the variable or
synonym.  If the default has more than one item, then Gri considers this
a restrictive list of possibilities, and will demand that the answer be
in that list, going into an infinite query loop until an item from the
list (or carriage-return, meaning take first item) is found.  The items
in the list are to be separated by spaces, not commas or any other
non-whitespace characters.

NOTE: The @code{-y} command-line option bypasses all query commands,
fooling Gri into thinking that the user typed a carriage-return to all
questions.  Thus the defaults, if they exist, are selected.


@c HTML <!-- newfile Quit.html "Gri: `quit' command" "Gri Commands" -->

@node   Quit, Read, Query, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{quit}
@cindex quiting Gri
@cindex stopping Gri
@findex quit
@cindex @code{quit} command

@example
`quit [.exit_status.]'
@end example

@noindent
Exits the gri program.  If an exit status (@code{.exit_status.}) is
specified, then Gri returns this value, rounded to the nearest integer,
as the ``exit status'' (a concept meaningful mostly in the unix
environment, where it designates an error).
 

@c HTML <!-- newfile Read.html "Gri: Read commands" "Gri Commands" -->

@node   Read, Read Colornames, Quit, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection The @code{read} commands

There are several varieties of @code{read} command.  Those commands used
for reading numerical information (e.g. @code{read columns}) are able to
decode variables and synonyms as well as simple numbers.

@menu
* Read Colornames::             Read colornames
* Read Columns::                Read (x,y,...) columnar data
* Read Grid::                   Read grid for contouring
* Read Image Colorscale::       Read colormap for color image
* Read Image Grayscale::        Read colormap for gray image
* Read Image Mask::             Read mask for image
* Read Image::                  Read image
* Read From::                   Change which open file looked at
* Read Synonym or Variable::    Read individual synonym or variable
* Read Line::                   Read whole line
@end menu


@node   Read Colornames, Read Columns, Read, Read
@comment  node-name,  next,  previous,  up
@subsubsection @code{read colornames}
@findex read colornames
@cindex @code{read} command
@cindex @code{read colornames} command
@cindex colors, reading from X11 database
@cindex X11 colors, reading

@example
`read colornames from RGB ["\filename"]'
@end example

@noindent
With no filename given, reads an X11-format @code{rgb.txt} file that
is provided with gri.  Otherwise, reads the named file and tries to
interpret it as an X11 file.  The file format has 4 or more columns,
the first three giving the red, green and blue values in the range 0
to 255, and the last columns giving the colorname (which may have more
than one word). Once you have read in a colorname table, the named
colors may be used as builtin colors (@ref{Set Color}).  To view the
names and RGB values of the colors Gri knows, including builtin ones
and ones from @code{read colornames}, use @code{show colornames}.

This command is akin to @code{set colorname} (@ref{Set Colorname}),
except that the latter uses the Gri notation of color constituents being
in the range from 0 to 1, whereas for @code{read colornames} uses an
X11 database, so that the color constitutents range from 0 to 255.


@node   Read Columns, Read Grid, Read Colornames, Read
@comment  node-name,  next,  previous,  up
@subsubsection @code{read columns}
@findex read columns
@cindex @code{read columns} command

@example
`read columns ...'
@end example

Read numbers into columns.  These columns have predefined
meanings and names.  For example, @code{read columns x y} instructs Gri
to read data into columns called @code{x} and @code{y}; it is these data
that Gri will use if you tell it to @code{draw curve}.  Other columns
are: @code{z}, used for contouring a function @code{z=z(x,y)};
@code{weight}, used for weighting data points; @code{u} and @code{v},
used for arrow (vector) plots.

If the keyword @code{appending} is given as the last word on the
@code{read columns} line, then the new data will be appended to any
existing columnar data; otherwise they will overwrite any existing data.

As a special case, if the @code{x} column is not indicated
(e.g. @code{read columns y}) then Gri creates x-values automatically, in
the sequence 0, 1, 2, etc.

@itemize @bullet

@item @code{read columns x y}
Read @code{x} in column 1, @code{y} in column 2 until blank-line found.
Only the first two numbers on each line will be read; any extra numbers
(or words) on the line will be ignored.

@item @code{read columns * y * * x}
Read @code{x} in column 5, @code{y} in column 2.  The @code{*} character
is a spacer.  It instructs Gri to skip the first, third, and fourth
words on the data line.  These words need not be numbers.  This example
illustrates a general mechanism of using the @code{*} character to skip
over unwanted items in the data file.  Note that there is no need to
supply @code{*} characters for trailing extraneous words; Gri will skip
them anywary.  Finally, note that any order of @code{x} and @code{y}
(and the other columns; see below) is allowed.

@item @code{read columns y=2 x=5} or @code{read columns x=5 y=2}
As above; read @code{x} in column 5 and @code{y} in column 2.  The
column number may be specified in this manner for all the named column
variables.  No spaces are allowed before or after the @code{=} sign.
The first column is called column 1.  Whether this format is used or the
@code{*} format is a matter of choice, except that numbered format also
permits using a given number to fill several variables (for example
@code{read columns x=1 y=2 u=1 v=2}).

@cindex netCDF files, reading columns

@item @code{read columns x="netCDF_name" ...}
If the file is a @code{netCDF} file, opened
by e.g. @code{open myfile.nc netCDF}, then the @code{netCDF} variables
for the columns, e.g. 

@example
open latlon.nc netCDF
read columns x="longitude" y="latitude"
@end example

@noindent
Note: the data @strong{must} be stored as the @code{netCDF} ``float''
type.

For more information on netCDF format, see

@code{http://www.unidata.ucar.edu/packages/netcdf/index.html}
@c HTML <a href="http://www.unidata.ucar.edu/packages/netcdf/index.html">
@c HTML here </a>.

@item @code{read columns * y z * x}
Read @code{x} in column 5, @code{y} in column 2, and @code{z} in column
3.  The @code{z} column is used for contouring.

@item @code{read columns x y u v}
@cindex direction field, how to read
@cindex vector field, how to read
@cindex arrows, how to read direction field
Read @code{x} and @code{y} in first two columns, and the ``arrow'' data
@code{u} and @code{v} as third and fourth columns.

@item @code{read columns .rows. x y}
Read @code{.rows.} rows of column data.
@end itemize

@cindex column data, x in one file and y in another

Sometimes you'll have @code{x} in one file and @code{y} in another.  In
that case, use the operating system or an editor to put the columns in
one file.  In unix, the easy way is

@example
open "paste file_with_x file_with_y |"
read columns x y
@end example


NOTE FOR BINARY FILES: For ascii files, Gri will proceed to a new line
after it has read the items requested; it skips any words appearing on
the data line after the last object of interest.  Thus 
@code{read columns x y} will read the first two columns and ignore any other
columns that might be present.  But for binary files, Gri has no way of
knowing how to "skip" to the next line (see @code{skip} command), so you
will have to flesh out the @code{read columns} command with as many
spacers as are present in your data.  For example, if you have four
numbers in each data record and want to interpret the first two as
@code{x} and @code{y}, you would use @code{read columns x y * *} to read
the data.


RETURN VALUE:
@cindex @code{\.return_value.}, from @code{read columns}
Sets @code{\.return_value} to 
@code{N rows N non-missing N inside-clip-region}  


@node   Read Grid, Read Image Colorscale, Read Columns, Read
@comment  node-name,  next,  previous,  up
@subsubsection @code{read grid}
@findex read grid
@cindex reading grid data
@cindex grid, reading
@cindex @code{read grid} command

@code{read grid} commands read grid characteristics.  (The ``grid'' is
the object that is contoured.)

For normal ascii or binary files, the commands to read the grid's
x-locations, y-locations and data are:

@example
`read grid x [.rows.]'
`read grid y [.rows.]'
`read grid data [spacers] \
  [.rows. .cols.] [spacers] [bycolumns]'
@end example

@cindex netCDF files, reading grid data
For @code{netCDF} files, the commands are as follows (note that it is
not possible to specify the number of data to read, nor to read the grid
by columns).

@example
`read grid x = "variable_name"'
`read grid y = "variable_name"'
`read grid data = "variable_name"'
@end example

@noindent
The ordering of the y-grid data is the same as if they were read from a
normal file: the first number is considered to be at the top of the
plot.

For more information on netCDF format, see

@code{http://www.unidata.ucar.edu/packages/netcdf/index.html}
@c HTML <a href="http://www.unidata.ucar.edu/packages/netcdf/index.html">
@c HTML here </a>.


Details of the non-netCDF commands:
@itemize @bullet

@item @code{read grid x [.cols.]}
Read the @code{x} locations of the grid points, one number per line.
If @code{.cols.} is supplied, then that many values will be read;
otherwise, reading will stop at end-of-file or blank-line.

@item @code{read grid y [.rows.]}
As above, but for y grid;  @code{.rows.} is the number of rows.  The
first number to be read corresponds to the location of the @strong{top}
edge of the grid.  Thus, if you were to view the column of numbers with
a text editor, they would be oriented the same way as the corresponding
elements will appear on the page.

@item @code{read grid data [.rows. .cols.]}
Read data for a grid having @code{.rows.} and @code{.cols.} columns.
(If @code{.rows.} and @code{.cols.} are not supplied, but the grid
already exists, then those pre-existing values are used.  If they are
specified here, then they are checked for consistency with the
pre-existing values if they exist.) Gri will read @code{.rows.} lines,
each containing @code{.cols.} numbers.  (Extra information in the file
can be skipped; see discussion of the @code{*} keyword below.)  Gri
will interpret the first line it reads as the grid data corresponding
to a value of y equal to @code{y[.rows.]}.  Thus, file should be
arranged like this:

@example
f(x[1], y[.rows.])  ...  f(x[.cols.], y[.rows.])
        .
        .
        .
f(x[1], y[3])       ...  f(x[.cols], y[3])
f(x[1], y[2])       ...  f(x[.cols], y[2])
f(x[1], y[1])       ...  f(x[.cols], y[1])
@end example
 
@item @code{read grid data [.rows. .cols.] bycolumns}
As above, but the @code{bycolumns} keyword tells Gri to read the data
one column at a time, instead of one row at a time.  Each line is
expected to contain @code{.rows.} numbers (as opposed to @code{.cols.}
numbers, as in the format where the @code{bycolumns} keyword is not
present).  (Extra information in the file can be skipped; see
discussion of the @code{*} keyword below).  The first line of the data
file contains the first column of the gridded data, corresponding to x
equal to @code{x[1]}).  The file should look like this:

@example
f(x[1], y[1])     ...     f(x[1], y[.cols.])
f(x[2], y[1])     ...     f(x[2], y[.cols.])
f(x[3], y[1])     ...     f(x[3], y[.cols.])
        .
        .
        .
f(x[.rows.],y[1]) ...  f(x[.rows.], y[.cols.])
@end example

@item @code{read grid data * * [.rows. .cols.]}
As @code{read grid data .rows. .cols.} except that the first two words
on each line are skipped.  As usual, trailing extraneous numbers are
also skipped.
@end itemize

@strong{See also} @code{set x grid}, @code{set y grid}


@noindent
RETURN VALUE:
@cindex @code{\.return_value.}, from @code{read grid ...}

@code{read grid x} sets @code{\.return_value} to @code{N cols}

@code{read grid y} sets @code{\.return_value} to @code{N rows}

@code{read grid data} sets @code{\.return_value} to @code{N rows N cols}


@node   Read Image Colorscale, Read Image Grayscale, Read Grid, Read
@comment  node-name,  next,  previous,  up
@subsubsection @code{read image colorscale}
@findex read image colorscale
@cindex @code{read image colorscale} command
@cindex image colorscale, reading
@cindex colorscale of image, reading from file

@example
`read image colorscale [rgb|hsb]'
@end example

@noindent
Read colorscale for image, from 256 lines each containing values for
Red, Green, and Blue (or Hue, Saturation and Brightness), separated by
whitespace.  The values are expected to be in the range 0 to 1, and are
clipped to these limits if not.  

For hints on how to create such an input file, 
@ref{Read Image Grayscale}.  If the example given there has the
following code instead, 

@example
open "awk 'BEGIN @{               \
     for(i=0;i<256;i++) @{        \
       print((i - 50)/50, 1, 1)  \
     @}                           \
   @}' |"
read image colorscale hsb
@end example

@noindent
then a linear full-color spectrum running from red at 10C to magenta at
15C is achieved.


@node   Read Image Grayscale, Read Image Mask, Read Image Colorscale, Read
@comment  node-name,  next,  previous,  up
@subsubsection @code{read image grayscale}
@findex read image grayscale
@cindex @code{read image grayscale} command
@cindex @code{read image greyscale} command
@cindex image grayscale, reading
@cindex grayscale of image, reading from file

@example
`read image grayscale'
@end example

@noindent
Read grayscale for an image, from 256 lines each containing a
single value.  The values are expected to be in the range 0 to 1, and
are clipped to these limits if not.  For 8-bit images, Gri multiplies
these values by 255, and uses this list for the grayscale mapping.  Such
a list is created by @code{write image grayscale}.

As an example, consider the code fragment (@ref{Images}).

@example
set image range 5 30.5
set image grayscale black 10 white 15
@end example

@noindent
is equivalent to

@example
set image range 5 30.5
open "awk 'BEGIN @{\
  for(i=0;i<256;i++) @{\
    print(1-(i-50)/50)\
  @} \
@}' |"
read image grayscale
close
@end example

@noindent
because the image formula is
@quotation
Temperature = 5C + 0.1C * pixelvalue
@end quotation
@noindent
where the pixelvalue ranges from 0 to 255.  Therefore, a temperature of
10C is a pixelvalue of 50, and 15C is 100.  To get a grayscale ranging
between these values, therefore, we create a linear function which maps
the 50th pixelvalue into grayvalue 1, and the 100th pixelvalue into
grayvalue 0.  That is what the awk line does; to see the actual numbers,
you could insert the line @code{write image grayscale to TMP} and look at
the file @file{TMP} (bear in mind that Gri will clip the values to the
range 0 to 1).

Sometimes you will have a file, say named @file{map.dat}, with RGB
numbers in the range 0-255, rather than 0-1 as Gri requires.  To read
them, use the operating system to convert the numbers for you
(@ref{Open}).

@example
open "cat map.dat \
  | awk '@{print(($1+$2+$3)/3/255)@}' |"
read image grayscale
close
@end example


@node   Read Image Mask, Read Image, Read Image Grayscale, Read
@comment  node-name,  next,  previous,  up
@subsubsection @code{read image mask}
@findex read image mask
@cindex @code{read image mask} command
@cindex mask for image, reading
@cindex image mask, reading

@example
`read image mask rasterfile|@{.rows. .cols.@}'
@end example

@noindent
Read image mask.  The mask is associated with the image read in by the
@code{read image} command in the following way.  When computing image
histograms, Gri ignores any pixels in the image for which the
corresponding pixel in the mask is set to @code{1}.

@itemize @bullet

@item @code{read image mask rasterfile}
The image size is specified in the rasterfile file itself, so 
it is not specified.

@item @code{read image mask .rows. .cols.}
The file must contain @code{.rows.*.cols.} binary data.  Pixel 
order is the same as for images.
@end itemize


@node   Read Image, Read From, Read Image Mask, Read
@comment  node-name,  next,  previous,  up
@subsubsection @code{read image}
@findex read image
@cindex @code{read image} command
@cindex images, reading
@noindent
There are several types of @code{read image} commands, depending on the
file format.  If the file is "raw", with no embedded information about
things like the width and height, then we need to specify everything, as
in the first format given below.  The other formats make use of the
header information in, e.g. PGM files.

@strong{Headerless images}

@example
`read image .rows. .cols. \
  [box .xleft. .ybottom. .xright. .ytop.] \
  [bycolumns]'
@end example

@noindent
With no options specified (@code{read image .rows. .cols.}), read binary
data defining an @code{image}.  The image range must have previously
have been set by @code{set image range}.  The data are as written by
"unsigned char" format in C.

When the @code{box} option is specified, the geometry of the image, in
user coordinates, is specified in terms of the cartesian coordinates of
the lower-left corner (@code{.xleft.}, @code{.ybottom.}) and upper-right
corner (@code{.xright.}, @code{.ytop.}).  If the @code{box} option is not
specified, this geometry can be specified with either @code{read x grid}
or @code{set x grid}, plus either @code{read y grid} or 
@code{set y grid}.

With the @code{bycolumns} keyword present, the image is read sweeping
from top-to-bottom, then left-to-right, instead of the usual order.


@strong{Sun rasterfile images}

@example
`read image rasterfile [box .xleft. .ybottom. .xright. .ytop.]'
@end example

@noindent
Read image in Sun rasterfile format.  Image geometry is inferred from
the header, so @code{.rows.} and @code{.cols} parameters are not given.

@strong{PGM images}

@example
`read image pgm [box .xleft. .ybottom. .xright. .ytop.]'
@end example

@noindent
Read image in PGM (Portable Gray Map) format.  Image geometry is
inferred from the header, so @code{.rows.} and @code{.cols} parameters
are not given.  Both ascii and binary PGM formats are supported (that
is, files with magic characters of P2 and P5).

@strong{NOTE} that there are many image formats and Gri doesn't try to
deal with them all.  The idea is to use another program to convert
images to a file format that Gri understands.  In the future Gri may
support PNG and other popular formats, especially in the Linux versions,
for which libraries exist to ease the input.



@node   Read From, Read Synonym or Variable, Read Image, Read
@comment  node-name,  next,  previous,  up
@subsubsection @code{read from \filename}
@findex read from
@cindex @code{read from} command
@cindex file, selecting between open files

@example
`read from \filename'
@end example

@noindent
Cause future @code{read} commands to read from the indicated file.  If
that file is not open, an error message will result.  Use 
@code{read from \filename} to shuffle reading among several open files.

Gri can look up filenames for @code{read from} in terms of their
@b{full} pathnames or their @b{local} pathnames.  Thus, a local file
called @code{a.dat} in the directory @code{/home/gri} can be referred to
by @code{read from a.dat} or by @code{read from /home/gri/a.dat}, which
comes in handy if you need to work with two files of the same name, in
other directories.  However, since Gri has the ability to search for
files in a "path" (@ref{Set Path To}), you may not have specified an
exact path name; this is why the @code{open} command provides a return
value which names the full pathname (@ref{Opening Simple Files}).


@node   Read Synonym or Variable, Read Line, Read From, Read
@comment  node-name,  next,  previous,  up
@subsubsection @code{read} synonym/variable
@findex read
@cindex @code{read ...} command
@cindex variables, reading
@cindex synonyms, reading
@cindex reading variables
@cindex reading synonyms

@example
`read [* [*...]] \synonym|.variable. [\synonym|.variable. [...]]@}'
@end example

@noindent
Read one or more items from the next line of the input file.  These
items may be synonyms or variables.  The token @code{*} indicates
that the word in the datafile should be skipped.  As usual, the datafile
may be embedded in the commandfile, providing the last data line is blank.

Normally one would use synonyms for words, and variables for numbers.
The items are separated by one or more "whitespace" characters
(e.g. space or TAB).  Thus, if a file contained the line

@example
Temperature 10.3
@end example

@noindent
then the line

@example        
read \var_name .var_value.
@end example    

@noindent
would have the same result as

@example        
\var_name = "Temperature"
.var_value. = 10.3
@end example

This command ignores any trailing items on the line.  That is, the next
@code{read} command will start on the next line of the file.  In a
sense then, you get just one shot at analysing the input line in your
datafile.  If you need flexibility, you may wish to read the
@strong{whole} contents of the line into a synonym, which may be done
using the @code{read line} command instead, to read it in as a string.
(@ref{Read Line}).

@cindex reading attributes in NetCDF files
@cindex netCDF files, reading attributes, units, etc

If the input file is in the netCDF format, the
indicated item will be read.  For example, 
@code{read \time:_MissingValue} reads the missing value for the variable
called @code{time}.  This conveniently allows your data file to dictate
axes names, units, missing values, etc.  Example:

@example
# Plot profile of TU81N (age-corrected tritium)
open profile.nc netCDF
read columns x="TU81N" y="z"
read \@{z:_FillValue@}		# assume same for all
read \@{z:long_name@}
read \@{z:units@}
read \@{TU81N:long_name@}
read \@{TU81N:units@}
close
set missing value \@{z:_FillValue@}
set x name "\@{TU81N:long_name@} (\@{TU81N:units)@}"
set y name "\@{z:long_name@} (\@{z:units)@}"
set y axis decreasing
draw curve
@end example

For more information on netCDF format, see
@code{http://www.unidata.ucar.edu/packages/netcdf/index.html}
@c HTML <a href="http://www.unidata.ucar.edu/packages/netcdf/index.html">
@c HTML here </a>.



@node   Read Line, Regress, Read Synonym or Variable, Read
@comment  node-name,  next,  previous,  up
@subsubsection @code{read line}
@findex read line
@cindex @code{read line raw} command
@cindex @code{read line} command
@cindex lines in data files, parsing
@cindex parsing headers in data files
@cindex variables, reading
@cindex synonyms, reading
@cindex reading variables
@cindex reading synonyms

@example
`read line \synonym'
@end example

@noindent
Read the next line of the datafile (or commandfile), trim off a trailing
comment if there is one, and then store the next line of datafile into
the named synonym.

@c HTML <!-- newfile Regress.html "Gri: `regress' command" "Gri Commands" -->

@node   Regress, Reorder, Read Line, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{regress}
@cindex statistics, performing regression
@cindex linear regression
@cindex regression, linear
@findex regress
@cindex @code{regress} command

@example
`regress @{y vs x [linear]@}|@{x vs y [linear]@}'
@end example     

@noindent
Perform linear regression of @code{y} as a function of @code{x} or @code{x} as
a function of @code{y}.

@itemize @bullet

@item @code{regress y vs x}
Linear regression of y vs x.  Several quantities are reported and also
saved into builtin variables.  The intercept is defined as
@code{..coeff0..}, its 95 percent confidence limit is defined as
@code{..coeff0_sig..}.  Thus the confidence range is
@code{..coeff0..-..coeff0_sig..} to @code{..coeff0..+..coeff0_sig..}.
Similarly the slope and confidence limit are stored in @code{..coeff1..}
and @code{..coeff1_sig..}

The squared correlation coefficient is stored in @code{..R2..}.

@strong{Historical note} prior to version 2.1.15, a different meaning was
attached to @code{..coeff0_sig..} and @code{..coeff1_sig..}; they used
be defined as standard errors, without having been multiplied by the
appropriate student-t coefficient.

@item @code{regress x vs y}
Linear regression of x vs y; for notation see above.

@item @code{regress y vs x linear}
Linear regression of y vs x; for notation see above.

@item @code{regress x vs y linear}
Linear regression of x vs y; for notation see above.
@end itemize
@noindent

@c HTML <!-- newfile Reorder.html "Gri: `reorder' command" "Gri Commands" -->

@node   Reorder, Rescale, Regress, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{reorder}
@cindex columns, reordering
@cindex reordering Columns
@findex reorder
@cindex @code{reorder} command

@example
`reorder columns randomly \
  |@{ascending in x|y|z@} \
  |@{descending in x|y|z@}'
@end example

@noindent
Reorder the columns in various ways.  

In the @code{randomly} style, the column data are shuffled randomly by
index, retaining the correspondance between a given x and y.  This is
useful with @code{draw symbol} using colored dots -- it prevents the
overpainting of one dot on another from biasing the color field to
values that happened to occur near the end of the column data.  If you
prefer the overpainting to be done in random order, use this command to
reorder the columns randomly.  The random number is selected using the
system @code{rand} call, with the seed being provided by the PID
(process ID) of the job.

The @code{ascending} and @code{descending} styles do what you'd expect.



@c HTML <!-- newfile Rescale.html "Gri: `rescale' command" "Gri Commands" -->

@node   Rescale, Resize, Reorder, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{rescale}
@cindex axes, forcing rescaling
@cindex rescaling axes
@cindex math on columns, rescaling after
@findex rescale
@cindex @code{rescale} command

@example
`rescale'
@end example     

@noindent
Re-determine the scales for the x and y axes.  Typically used after a
column math operation, when you want the new data to be auto-scaled.
(Note: normally, if the axes have already been drawn, Gri won't rescale
automatically just because you modify the column data.  This is designed
so that you can add offsets to curves, etc, while staying in saved axes.
But if the axes have not been drawn yet when you modify the column data,
then Gri will automatically rescale the axes it is planning to draw.)



@c HTML <!-- newfile Resize.html "Gri: `resize' command" "Gri Commands" -->

@node   Resize, Return, Rescale, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{resize}
@cindex maps, scales
@findex resize x
@cindex @code{resize x} command

@example
`resize @{x for maps@}|@{y for maps@}'
@end example

@noindent
Resize the axes frame region in such a way that geographical objects
appear in correct proportions.  This assumes that y is degrees latitude
and x is degrees longitude.

@itemize @bullet

@item @code{resize x for maps}
Resize the plot width for maps, assuming that x represents longitude and
y represents latitude.  Before using this, you must have defined scales
for both x and y, and a size for y (ie, you must have done 
@code{set x axis ...}, @code{set y axis ...} and @code{set y size});
this command 
sets the x size, thus eliminating @code{set x size.} The result is that,
at the central latitude (y), a centimetre on the page will correspond to
an equal distance on the earth, in both the north-south and east-west
directions.

@item @code{resize y for maps}
Resize the plot height for maps, assuming that x represents longitude
and y represents latitude.  Before using this, you must have defined
scales for both x and y, and a size for x (ie, you must have done
@code{set x axis ...}, @code{set y axis ...} and @code{set x size});
this command sets the y size, thus eliminating @code{set y size.} The
result is that, at the central latitude (y), a centimetre on the page
will correspond to an equal distance on the earth, in both the
north-south and east-west directions.  

@strong{See also} @code{resize x for maps}.
@end itemize


@c HTML <!-- newfile Return.html "Gri: `return' command" "Gri Commands" -->

@node   Return, Rewind, Resize, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{return}
@findex return
@cindex @code{return} command

@example
`return'
@end example

@noindent
Return early from a user-defined function or an @code{insert} file.  Or,
in the main gri program, do the same thing as @code{quit}.


@c HTML <!-- newfile Rewind.html "Gri: `rewind' command" "Gri Commands" -->

@node   Rewind, Rpnfunction, Return, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{rewind}
@findex rewind
@cindex @code{rewind} command

@example
`rewind \filename'
@end example

@noindent
Rewind a data-file to the beginning.  If no filename is given, this is
done for the currently active file; otherwise the named file is rewound.


@c HTML <!-- newfile Rpnfunction.html "Gri: `rpnfunction' command" "Gri Commands" -->

@node  Rpnfunction, Set, Rewind, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{rpnfunction}
@cindex rpn functions
@cindex defining rpn functions
@cindex functions in rpn expressions
@findex rpnfunction
@cindex @code{rpnfunction} command

@example
`rpnfunction name replacement-words'
@end example

@noindent
Create a new keyword for use in rpn expressions.  Inside any RPN
expression which follows this line, the word @code{name} will be
substituted with the indicated replacement words.  

For example,
the following shows the definition and use of a function which computes
the sine of twice an angle, by multiplying whatever is on the stack by
@code{2}, and then taking the sine of the result.

@example
rpnfunction sin2 2 * sin
show "expect the number 1 to follow: " @{rpn 45 sin2@}
@end example

The replacement words will have any synonyms in them translated first,
unless they start with an underscore followed by a double backslash.
Similarly, variables are substituted unless they start with an
underscore.  These exceptions are to allow the use of the @code{defined}
operator (@ref{rpn Mathematics}).

Note: The mathematical constants @code{e} and @code{pi} are stored using
@code{rpnfunctions}.  Also, two @code{rpnfunctions} are provided for
finding the slope and intercept of a line joining two points, e.g.
@cindex linear interpolation
@cindex @code{linear_slope} rpn operator
@cindex @code{linear_intercept} rpn operator
@cindex rpn operator @code{linear_slope}
@cindex rpn operator @code{linear_intercept}

@example
# Expect answers 1 and 10 ...
show "slope=" @{rpn 0 1 1 11 linear_slope@}
show "inter=" @{rpn 0 1 1 11 linear_intercept@}
@end example

These are useful in @code{set grid missing above .intercept. .slope.}
and @code{set z missing above .intercept. .slope.}.


@c HTML <!-- newfile Set.html "Gri: Set commands" "Gri Commands" -->

@node   Set, Set Axes Style, Rpnfunction, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection The @code{set} commands
@findex set
@cindex @code{set} command
Set various flags and parameters which Gri will use in later commands.
@menu
* Set Axes Style::              Set type of axes
* Set Arrow Size::              Set size for arrow heads
* Set Arrow Type::              Set type of arrow heads
* Set Beep::                    Set error beeping on or off
* Set Bounding Box::            Set PostScript bounding box
* Set Clip::                    Set clipping region
* Set Color::                   Set color of pen
* Set Colorname::               Create a color name
* Set Contour Format::          Set format for numbers on contours
* Set Contour Label For::       Set existence of contour labels
* Set Contour Label Position::  Set spacing of contour labels
* Set Contour Labels::          Control various things about contour lables
* Set Dash::                    Set style of dashed lines
* Set Environment::             (Developer cmd)
* Set Error Action::            Set error behavior
* Set Flag::                    Set flag to control Gri (developer cmd)
* Set Font Color::              Set color of pen used for text
* Set Font Encoding::           Set font encoding vector
* Set Font Size::               Set size of text
* Set Font To::                 Set font for text
* Set Graylevel::               Set graylevel of pen
* Set Grid Missing::            Set missing region of grid
* Set Ignore Initial Newline::  Set to ignore initial blank line
* Set Ignore Error Eof::        Set ability to tolerate EOF on files
* Set Image Colorscale::        Set colorscale mapping for image
* Set Image Grayscale::         Set grayscale mapping for image
* Set Image Missing Value Color::  Set missing value color in image
* Set Image Range::             Set range of data that image can hold
* Set Input Data Window::       Set data window for reading columns
* Set Input Data Separator::    Set separator between data items
* Set Line Cap::                Set line end (cap) type
* Set Line Join::               Set method for intersections of line segments
* Set Line Width::              Set width of lines
* Set Missing Value::           Set "missing" value
* Set Page Size::               Set page size
* Set Page::                    Set page style
* Set Panel::                   Establish geometry for a panel of multipanel plot
* Set Panels::                  Prepare for multipanel plot
* Set Path To::                 Set search-path for data or command files
* Set Postscript Filename::     Set name of PostScript file
* Set Symbol Size::             Set size of symbols
* Set Tic Size::                Set size of tics on axes
* Set Trace::                   Set printout of statements as executed
* Set Transparency::            Set transparency of the pen
* Set U Scale::                 Set scale for u (i.e. x) component of arrows
* Set V Scale::                 Set scale for v (i.e. y) component of arrows
* Set X Axis::                  Set range of x axis
* Set X Format::                Set format for numbers on x axis
* Set X Grid::                  Set x mesh of contour grid
* Set X Margin::                Set margin to left of x axis
* Set X Name::                  Set name of x axis
* Set X Size::                  Set length of x axis
* Set X Type::                  Set type of x axis (log/linear)
* Set Y Axis::                  Set range of y axis
* Set Y Format::                Set format for numbers on y axis
* Set Y Grid::                  Set y mesh of contour grid
* Set Y Margin::                Set margin below y axis
* Set Y Name::                  Set name of y axis
* Set Y Size::                  Set length of y axis
* Set Y Type::                  Set type of y axis (log/linear)
* Set Z Missing::               Set missing region of z column
@end menu

@node   Set Axes Style, Set Arrow Size, Set, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set axes style}
@findex set axes style
@cindex @code{set axes style} command

@example
set axes style .style.     \
  | @{offset [.dist_cm.]@} \
  | rectangular|none|default
@end example

@noindent
Tell Gri how you want the axes to look, when they are drawn later.

@itemize @bullet

@item @code{set axes style 0}
Set axes to be rectangular, with an x-y axis frame labelled at the left
and bottom and tic marks on all axes.

@item @code{set axes style 1}
As style @code{0}, but only put tics on the lower and left axes.

@item @code{set axes style 2}
As style @code{0} but without labels or tics on any axis, 
i.e. just an axis frame.

@item @code{set axes style offset [.dist_cm.]}
Set axes so that the actual x and y axes will be drawn with a space
separating them from the data area.  The space, if not set by the
@code{.distance_cm.} option, will be equal to the current tic size (see
@code{set tic size}).  This command can be used together with any other
@code{set axes style} command.  It applies to both the @code{draw axes}
command and with any @code{draw x|y axis} command in which the axis
location is not explicitly given.

@item @code{set axes style rectangular}
Set axes to be rectangular, with an x-y axes frame labelled at the left
and bottom.

@item @code{set axes style none}
Tell gri not to bother drawing axes before drawing curves, etc.

@item @code{set axes style default}
Same as @code{set axes style 0}, and with @code{offset} turned off.
@end itemize

@node   Set Arrow Size, Set Arrow Type, Set Axes Style, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set arrow size}
@findex set arrow size
@cindex @code{set arrow size} command
@cindex arrows, setting size of heads

@example
`set arrow size .size.           \
  | @{as .num. percent of length@} \
  | default'
@end example

@noindent
Set the arrowsize (which is stored in the builtin variable
@code{..arrowsize..}). 

@itemize @bullet

@item @code{set arrow size .size.}
Set the arrow size (ie, half-width of the arrowhead) to @code{.size.}
centimetres.

@item @code{set arrow size as .num. percent of length}
Set the arrow size to be the indicated percentage of arrow length, as in
"HWP" in the singles ads.  (As a flag to this, @code{..arrowsize..} is
set to the negative of the fractional size measured in percent.)

@item @code{set arrow size default}
Set the arrow size to the default of 0.2 cm.
@end itemize

@node   Set Arrow Type, Set Beep, Set Arrow Size, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set arrow type}
@findex set arrow type
@cindex @code{set arrow type} command
@cindex arrows

@example
set arrow type .which.
@end example

Set type of arrow, according to the value of @code{.which.}, rounded to
the nearest integer.  A rounded @code{.which.} value of 0 yields the
default arrows, drawn with three line strokes.  Value 1 yields outlined
arrows, sometimes used on definition sketches.  Value 2 yields filled,
swept-back arrow heads.

This command uses the ``line join'' parameters that are presently active
(@ref{Set Line Join}).  So, by default, the arrow ends are rounded
(because the default line-join parameter is 1).  To get pointy ends,
first set the line join parameter to 0.



@node   Set Beep, Set Bounding Box, Set Arrow Type, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set beep}
@findex set beep
@cindex @code{set beep} command
@cindex errors, beeping
@cindex beeping on errors

@example
`set beep on|off'
@end example

@noindent
The command @code{set beep on} makes gri beep on errors and
@code{query}.  @code{set beep off} (the default) turns this beeping off.


@node   Set Bounding Box, Set Clip, Set Beep, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set bounding box}
@findex set bounding box
@cindex @code{set bounding box} command
@cindex bounding box, setting

@example
`set bounding box .xleft. .ybottom. .xright. .ytop. [pt|cm]'
@end example

@noindent
Set the PostScript bounding box for the graph to the indicated values.  The
bounding box is used by some programs to determine the region of the
page on which marks have been made.  For example, La@TeX{} uses the
bounding box to decide how to position figures in documents.

Normally, the bounding box is computed automatically unless the
@code{-no_bounding_box} commandline option has been specified;
(@ref{Invoking Gri}).  But if @code{set bounding box} is
done, the automatically computed value is ignored and the given box is
used instead.  Use this if Gri makes mistakes in its automatic selection
of bounding box.

The coordinates of the bounding box may be specified in (1) user
coordinates, as defined @strong{at the moment} the command is executed, or
(2) in points on the page, measured from an origin at the lower-left
(72 point per inch), or (3) in centimeters on the page.  Which coordinate
system is used depends on the last keyword -- use @code{pt} for points,
@code{cm} for centimeters, and nothing at all for user-units.

The most common use is in points, since that is how many other
application packages, e.g. La@TeX{} and dvips, specify the bounding box.

If the box is specified in the user units, the user units in effect
@strong{at the moment} of executing the @code{set bounding box} command
are used.  This must be born in mind if the coordinate system is
changing during the execution of the program, e.g.  if margins are
changing or the x and y axes are changing.  For this reason it often
makes sense to put this command at the end of the commandfile.


@node   Set Clip, Set Color, Set Bounding Box, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set clip}
@findex set clip
@cindex @code{set clip} command

@example
`set clip [postscript] \
  @{on [.xleft. .xright. .ybottom. .ytop.]@} \
  @{to curve@} \
  | off'
@end example

@noindent
Control clipping of following drawing commands.  Note that the
commands have two styles, one of which includes the keyword
@code{postscript}.  PostScript clipping does a cleaner job, but it
results in larger file sizes.  @emph{Important} if you are using
@code{postscript} clipping, then you be @emph{sure} to turn it off
using @code{set clip postscript off}, instead of @code{set clip off};
otherwise Gri will get mixed up.

@itemize @bullet

@item @code{set clip on}
Don't plot data outside axes.

@item @code{set clip postscript on}
As above, but Postscript clipping.

@item @code{set clip on .xleft. .xright. .ybottom. .ytop.}
Don't plot data outside indicated box.

@item @code{set clip postscript on .xleft. .xright. .ybottom. .ytop.}
As above, but Postscript clipping.

@item @code{set clip off}
Plot all data, whether inside the axes or not.

@item @code{set clip postscript off}
As above, but Postscript clipping.

@item @code{set clip to curve} set clip to the curve, as
would be drawn by a @code{draw curve filled} command, i.e. to the
polygon constructed by running along the xy points, in order, followed
by a final segment from the last point back to the first point.  This is a 
"postscript" clip, as explained in the next item.

@item @code{set clip postscript to curve}
As above, but Postscript clipping.

@example
draw axes
set clip postscript on 10 20 0 1
draw curve
set clip postscript off
@end example

@item @code{set clip postscript off}
Turn PostScript clipping off.
@strong{See also} @code{set input data window}.
@cindex data, clipping using @code{set input clip}
@cindex clipping data using @code{set input clip}
@end itemize

@node   Set Color, Set Colorname, Set Clip, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set color}
@findex set color
@findex set colour
@cindex @code{set color} command
@cindex @code{set colour} command

@example
`set color \name               | \
    @{rgb .red. .green. .blue.@} | \
@{hsb .hue. .saturation. .brightness.@}'
@end example

@noindent
Set the color of the ``pen'' used for drawing lines and text.  Normally
lines and text are drawn in the same color, but the text color can be
specified independently if desired (@ref{Set Font Color}).  This might be
useful to get contour lines of one color and labels of another.  The
spelling @code{colour} is also accepted.

In the @code{set color \name} style, set the drawing color to the
indicated name, either from the builtin list (@code{white},
@code{LightGray}, @code{darkslategray}, @code{black}, @code{red},
@code{brown}, @code{tan}, @code{orange}, @code{yellow}, @code{green},
@code{ForestGreen}, @code{cyan}, @code{blue}, @code{skyblue},
@code{magenta}), or from a list created by @code{read colornames}.  In
the latter case, if the colorname has more than one word in it, use
quotes, e.g. @code{set color "ghost white"}.
     
In the @code{set color rgb ...} style, set the individual color
components as indicated.  The numbers @code{.red.}, @code{.green.} and
@code{.blue.} range from 0 (for no contribution of that color component
to the final color) to 1 (for maximal contribution).  Values less than 0
are clipped to 0; values greater than 1 are clipped to 1.  EXAMPLES:

@example
set color rgb 0   0   0 # black
set color rgb 1   1   1 # white
set color rgb 1   0   0 # bright red
set color rgb 0.5 0   0 # dark red (only 50 percent)
set color rgb 0   1   0 # pure green
set color rgb 1   1   0 # yellow: red + green
@end example

In the @code{set color hsb ...} style, set the individual color
components as indicated.  The numbers @code{.hue.}, @code{.saturation.}
and @code{.brightness.} range from 0 to 1.  The color, represented by
.hue., ranges from 0 for pure red, through 1/3 for pure green, and 2/3
for pure blue, and back to 1 again for pure red. The purity of the
color, represented by .saturation., ranges from 0 (none of the hue is
visible) to 1 (the maximal amount is present).  The brightness of the
color, represented by @code{.brightness.}, ranges from 0 (black) to 1
(maximal brigntness).  Values less than 0 are clipped to 0; values
greater than 1 are clipped to 1.  EXAMPLES:

@example
set color hsb 0    1   1 # pure, bright red
set color hsb 0    1 0.5 # half black, half red
set color hsb .333 1   1 # pure, bright green
@end example


@node   Set Colorname, Set Contour Format, Set Color, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set colorname}
@findex set colorname
@cindex @code{set color name} command

@example
`set colorname \name @{rgb .red. .green. .blue.@} \
                   | @{hsb .hue. .saturation. .brightness.@}'
@end example

@noindent
Create a colorname with the indicated color.  The color components range
from 0 to 1, and will be clipped to these values if they are outside
this range.  EXAMPLE (borrowing a color from @file{/usr/lib/X11/rgb.txt}):

@example
set colorname peachpuff rgb 1 @{rpn 218 255 / @}  @{rpn 185 255 / @}
draw box filled 2 2 3 3 cm
@end example

This command is akin to @code{read colornames} (@ref{Read Colornames}),
except that the latter uses an X11 database, so the color constituents
range from 0 to 255, whereas for @code{set colorname} they range from 0
to 1.



@node   Set Contour Format, Set Contour Label For, Set Colorname, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set contour format}
@findex set contour format
@cindex @code{set contour format} command

@example
`set contour format \style|default'
@end example

@noindent
Normally, Gri draws the numeric labels of contours using a format code
called @code{%g} in the "C" language.  You may specify any other "long"
format using this command.  For example, @code{set contour format %.1f}
tells Gri to use one decimal place in the numbers, and also to prefer
the "float" notation to the exponential notation.  @code{set contour
format default} resets to the default @code{%f} format.  You may use
quotes around the format if you need to, to make the item be a single
word (e.g. @code{set contour format "%.1f m/s"}).



@node Set Contour Label For, Set Contour Label Position, Set Contour Format, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set contour label for}
@findex set contour label for
@cindex @code{set contour label for} command

@example
`set contour label for lines exceeding .x. cm'
@end example

@noindent
Make it so contour lines shorter than @code{.x.} centimeters will not be
labelled. 



@node   Set Contour Label Position, Set Contour Labels, Set Contour Label For, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set contour label position}
@findex set contour label position
@cindex @code{set contour label position} command
@cindex contours, spacing of labels on
@cindex labels, on contours

@example
`set contour label position \
  @{.start_cm. .between_cm.@} \
  | centered \
  | default'
@end example

@noindent
By default, contour labels are drawn at the location 1 cm into the
contour curve, measured from the startpoint of the contour (e.g., for
contours crossing the axes frames, the label will be 1 cm from the
frame), and then at a uniform distance along the contour.  By default,
this uniform distance is the average dimension of the plotting area
inside the axes.  If @code{.start_cm.} and @code{.between_cm.} are
specified, the first label is drawn at a distance @code{.start_cm.} from
the start of the contour, and thereafter at a separation of
@code{.between_cm.}.

If the @code{centered} option is used, then the contour labels are
centered along the length of the line.



@node   Set Contour Labels, Set Dash, Set Contour Label Position, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set contour labels}
@findex set contour labels
@cindex @code{set contour labels} command
@cindex contours, orientation of labels
@cindex contours, whiting/nowhiting under the labels
@cindex labels on contour lines, controlling orientation and white-under

@example
set contour labels rotated \
  | horizontal \
  | whiteunder \
  | nowhiteunder
@end example

@noindent
The first two options control whether contour labels are rotated to line
up with the contour lines, or whether they are horizontal (the default).

The second two options control whether the region under contour labels
is whited out before drawing the label.  The default is
@code{whiteunder}, which has the visual effect of the label having been
drawn on a piece of paper and then pasted on.  This can look jarring
when the material under the contour is an image.  When
@code{nowhiteunder} is specified, the contour line is broken to make
space for the text, but no whiting out is done.

@node   Set Dash, Set Environment, Set Contour Labels, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set dash}
@findex set dash
@cindex @code{set dash} command
@cindex dashed lines
@cindex lines, dashed
@vindex @code{..length_dash..}, length/cm of dashes
@vindex @code{..length_blank..}, length/cm of blanks

@example
`set dash [.n.|@{.dash_cm. .blank_cm. ...@}|off]'
@end example

@noindent
Control dash-style for following @code{draw curve} and @code{draw line}
commands. 

@itemize @bullet

@item @code{set dash}
Set to dashed line (0.4cm dashes, 0.1cm blanks).

@item @code{set dash .n.}
Set to indicated pre-defined dashed line, according to table:

@example
.n. dash/cm blank/cm
 0        -        -   ... (Solid line)
 1      0.2      0.1
 2      0.4      0.1
 3      0.6      0.1
 4      0.8      0.1
 5      1.0      0.1
10      w        w
11      w        2w
12      w        3w
13      w        4w
14      w        5w
15      w        6w
@end example

@noindent
Where @code{w} is written, it indicates the current linewidth.  Thus,
types 10 through 15 give square-dotted lines.
     
@item @code{set dash .dash_cm. .blank_cm. .dash_cm. .blank_cm. ...}
Set to indicated dashed line.  The series of lengths @code{.dash_cm.}
and @code{.blank_cm.} give the lengths of dash and blank portions
(measured in centimeters).  Any number of dash/blank lengths may be
given.  For example, @code{set dash 0.5 0.1 0.1 0.1} looks good.
     
@item @code{set dash off}
Turn dashing off, setting to a solid line.
@end itemize

@node   Set Environment, Set Error Action, Set Dash, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set environment}
@findex set environment
@cindex @code{set environment} command
@cindex developer command @code{set environment}

@example
`set environment'
@end example

@noindent
Set environment (graylevel, axis length, etc) so that following plotting
commands will make use of anything set by either a @code{set} command or
by direct manipulation of builtin variables like @code{..xsize..}, etc.
NOTE: this should @strong{only} be done by developers.


@node   Set Error Action, Set Flag, Set Environment, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set error}
@findex set error
@cindex @code{set error} command
@cindex Handling errors with @code{set error} command

@example
`set error action to core dump'
@end example

@noindent
Make Gri dump core when any error is found, to facilitate debugging.

@node   Set Flag, Set Font Color, Set Error Action, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set flag}
@findex set flag
@cindex @code{set flag} command
@cindex developer command @code{set flag}

@example
`set flag \name [off]'
@end example

@noindent
Set the indicated flag to YES.  The name of the flag is contained in a
single word, e.g. @code{set flag dan_28sep_test}.  The action of the
flags may change with time and is undocumented.  This command is
provided to enable selected users (e.g., the developer himself) to use
test features of Gri before they are frozen into a fixed syntax and
action.  The keyword @code{off} turns the indicated flag off.  NOTE:
this should @strong{only} be done by developers.

@example
FLAG         DATE     ACTION

jinyu1       29sep94  'convert columns to grid'
                       outputs (x,y,z,z_predicted)

emulate_gre   9jun97  'E' format on axes yields
                      scientific notation

kelley1      17jun97  for kelley only - quit contour
                      trace if hit nonlegit

kelley2      17jun97  for kelley only: print
                      info while contour tracing
@end example


@node   Set Font Color, Set Font Encoding, Set Flag, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set font color}
@findex set font color
@findex set font colour
@cindex font, setting color of
@cindex text, color used for
@cindex color, for text
@cindex @code{set font color} command
@cindex @code{set font colour} command

@example
set font color \name           | \
    @{rgb .red. .green. .blue.@} | \
@{hsb .hue. .saturation. .brightness.@}
@end example

@noindent
The syntax is the same as @code{set color}, except that this applies to
text only.  By default, text is drawn in the same color as lines, so
text color is changed as line color is changed (e.g. by using the
@code{set color} or @code{set graylevel} commands)).  However, once
@code{set font color} is used in a Gri program, the font thereafter
maintains a separate color from the lines.


@node   Set Font Encoding, Set Font Size, Set Font Color, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set font encoding}
@findex set font encoding
@cindex font, setting encoding vector of
@cindex text, encoding vector of
@cindex font encoding
@cindex @code{set font encoding} command
@cindex postscript-standard font encoding
@cindex ISO latin 1 font encoding

@example
set font encoding PostscriptStandard | isolatin1
@end example

@noindent
Permits one to control the so-called ``font encoding'' used in text.
The default font encoding is ISO-Latin-1, which is best for English and
other European languages.  To learn how to enter accents in a text
editor, and for a brief overview of font encodings,
(@ref{Non-English Text}).

If the so-called ``Postscript Standard'' font encoding is required, this
command permits changing the encoding.

Note: few users will ever need this command.  If you don't even know
what ``font encoding'' is about, ignore this command!



@node   Set Font Size, Set Font To, Set Font Encoding, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set font size}
@findex set font size
@cindex @code{set font size} command
@cindex font size

@example
`set font size @{.size. [cm]@}|default'
@end example

@noindent
Set the size of the font for drawing of text.

@itemize @bullet

@item @code{set font size .size.}
Set font size to @code{.size.} points.  (A point is 1/72 of an inch,
or 1/28 of a centimetre.)

@item @code{set font size .size. cm}
Set font size to @code{.size.} centimetres.

@item @code{set font size default}
Set font size to default = 12 pts.
@end itemize

@cindex American Geophysical Union, recommended font size

If your figure is to be reproduced by a journal, you should check with
them about the range of font size they need.  This will, of course,
depend on whether your figure is reduced or enlarged during
reproduction.  For example, American Geophysical Union (publishers of
J. Geophysical Res.) recommends that one use fonts no smaller than 8
points.  They also recommend that the range in fontsize in a given
figure not exceed 2.



@node   Set Font To, Set Graylevel, Set Font Size, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set font to}
@findex set font to
@cindex @code{set font to} command

@example
`set font to \fontname'
@end example

@noindent
Set font to named style.  Note that the backslash is @strong{not} to be
written, but here merely means that this word has several alternatives.
For example, one might say @code{set font to Courier}.  The allowed
fontnames are: 
@code{Courier}, a typewriter font (and the only monospaced font in Gri);
@code{Helvetica} (the default), a sans-serif font commonly used in drafting scientific graphs;
@code{HelveticaBold}, a bold version of Helvetica;
@code{Times} (also called @code{TimesRoman}), a font used in most newspapers;
@code{TimesBold}, a bold version of Times;
@code{Palatino} (also called @code{PalatinoRoman}), similar to Times;
@code{Symbol}, included for completeness, is a
mathematical font in which "a" becomes $\alpha$ of the math mode, etc.
For reference on these fonts see any book on PostScript.  The default
font is @code{Helvetica}.


@node   Set Graylevel, Set Grid Missing, Set Font To, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set graylevel}
@findex set graylevel
@findex set greylevel
@cindex @code{set graylevel} command
@cindex @code{set greylevel} command
@cindex graylevel, command
@cindex lines, gray, command

@example
`set graylevel .brightness.|white|black'
@end example

@noindent
Set graylevel for lines to indicated numerical value between 0=black and
1=white, or to the named color.

@cindex American Geophysical Union, recommended gray levels

Note: if your diagram is to be reproduced by a journal, it is unlikely
that the reproduction will be able to distinguish between any two
graylevels which differ by less than 0.2.  Also, graylevels less than
0.2 may appear as pure black, while those of 0.8 or more may appear as
pure white.  These guidelines are as specified by American Geophysical
Union (publishers of J. Geophysical Res.), as of 1998.



@node   Set Grid Missing, Set Ignore Initial Newline, Set Graylevel, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set grid missing}
@findex set grid missing
@cindex @code{set grid missing} command
@cindex grid, missing values
@cindex contouring, clipping out invalid areas

General format is

@example
`set grid missing \
  @{above|below .intercept. .slope@} \
  | @{inside curve@}'
@end example

@noindent
The style

@example
`set grid missing above|below .intercept. .slope'
@end example

@noindent
sets grid to missing value for all points above/below the line defined
by
@tex
$y = {\rm .intercept.} + {\rm .slope.} x$
@end tex
@ifinfo
y = .intercept. + .slope. * x
@end ifinfo

The style

@example
`set grid missing inside curve'
@end example

@noindent
sets the grid to the missing value throughout an area described
by the curve last read in with @code{read columns}.  This is
useful for e.g. excluding land areas while contouring ocean
properties.  The curve may contain several "islands," each
tracing (clockwise) a region inside of which the grid is to
considered missing.  If the first point in an island doesn't
match the last, then an imaginary line is assumed which connects
them.  Multiple islands may be separated by missing-value codes.

@strong{See also} @code{Set Z Missing}.

@node   Set Ignore Initial Newline, Set Ignore Error Eof, Set Grid Missing, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set ignore initial newline}
@findex set ignore initial newline
@cindex @code{set ignore initial newline} command

@example
`set ignore initial newline [off]'
@end example

@noindent
Make Gri ignore a newline if it occurs as the first character of the
next data file.  This is used for files made by FORTRAN programs on
VAX/VMS computers.


@node   Set Ignore Error Eof, Set Image Colorscale, Set Ignore Initial Newline, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set ignore error eof}
@findex set ignore error eof
@cindex @code{set ignore error eof} command
@cindex files, testing for eof
@cindex eof on files
@cindex testing for end of file
@cindex testing for file eof

@example
`set ignore error eof'
@end example

@noindent
Stop Gri from considering that to encounter an end of file in future
@code{read} commands consitutes an error; Gri will simply warn about
future EOFs.




@node   Set Image Colorscale, Set Image Grayscale, Set Ignore Error Eof, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set image colorscale}
@findex set image colorscale
@findex set image colourscale
@cindex @code{set image colorscale} command
@cindex @code{set image colourscale} command
@cindex colorscale, setting for images
@cindex image plots, setting colorscale

@example
set image colorscale hsb .h. .s. .b. .im_value. \
    hsb .h. .s. .b. .im_value. [increment .im_value.]
set image colorscale rgb .r. .g. .b. .im_value. \
    rgb .r. .g. .b. .im_value. [increment .im_value.]
set image colorscale \
  \name .im_value. \
  \name .im_value. \
  [increment .im_value.]
@end example

@noindent
Set colorscale mapping for image, using HSB (hue, saturation,
brightness) specification, RGB (red, green, blue) color specification,
or named colors.  The image range must previously have been set by
@code{set image range}, so that the @code{.im_value.} values will have
meaning.  Two pairs of (color, image-value) are given, and possibly an
increment.  Normally the colors are smoothly blended between the
endpoints, but if an increment is supplied, the colors are quantized.
The HSB method allows creation of spectral palettes, while the other two
methods create simple blending between the two endpoints.

EG: To get a spectrum ranging between pure red (H=0) for image value of
-10.0, and pure blue (H=2/3) for image value of 10.0, do this:

@example
set image colorscale hsb 0 1 1 -10 hsb .666 1 1 10
@end example

EG: To get a scale running from pure red (at image-value 10.0) into pure
blue (at image-value 25.1), but with the colors blending intuitively in
between (i.e., blending as paint might), use @code{rgb} color
specification, as follows:

@example
set image colorscale rgb 1 0 0 10 rgb  0 0 1 25.1
@end example

EG: To get a quantized blend between the X11 colors @code{skyblue} at
image value of 0 and @code{tan} at image value of 20, and with steps at
image values incrementing by 5, do this:

@example
set image colorscale skyblue 0 tan 20 increment 5
@end example

@noindent
Note that the traversal is through RGB space, so it is
intuitive, not spectral.  See @code{set color} for a list of X11 colors
known to Gri.

See also @code{read image colorscale} (@ref{Read Image Colorscale}).

@node   Set Image Grayscale, Set Image Missing Value Color, Set Image Colorscale, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set image grayscale}
@findex set image grayscale
@findex set image greyscale
@findex set image grayscale using histogram
@findex set image greyscale using histogram
@cindex @code{set image grayscale} command
@cindex @code{set image greyscale} command
@cindex @code{set image grayscale using histogram} command
@cindex @code{set image greyscale using histogram} command
@cindex grayscale, setting for images
@cindex image plots, setting grayscale

@example
`set image grayscale using histogram \
  [black .bl. white .wh.]'

`set image grayscale \
  [black .bl. white .wh. [increment .inc.]]'
@end example

@noindent
Set up a grayscale mapping for images.  The image range must have
previously have been set by @code{set image range}.

@example
`set image grayscale using histogram [black .bl. white .wh.]'
@end example

@noindent
Create a grayscale mapping using linearized cumulative histogram
enhancement.  The image must already exist.

This creates maximal contrast in each range of graylevels,
and is useful for tracing subtle features between different images (for
example, it makes it easier to trace fronts between successive satellite
images).  The entire histogram is expanded, from the smallest value in
the image to the largest.

With no options specified, the histogram is done from 0 in the image to
255 in the image.  If the black/white options are specified, the
histogram is done between these values.

@example
`set image grayscale \
  [black .bl. white .wh. [increment .inc.]]'
@end example

@noindent
With no optional parameters, create a grayscale mapping for the current
image, scaling it from black for the mininum value in the image to white
for the maximum value.  The image range must have previously have been
set by @code{set image range}.

The optional parameters @code{.wh.} and @code{.bl.} specify the values
to be drawn in white and black in the image, with smooth linear blending
in between.

Normally the blending from white to black is smooth (linear), but if the
additional optional parameter @code{.inc.} is specified, the blending is
quantized, jumping to darker values at (@code{.wh.} + @code{.inc.}),
(@code{.wh.} + 2* @code{.inc.}), etc.  (The sign of @code{.inc.} will be
altered, if necessary, to ensure that (@code{.wh.} + @code{.inc.}) is
between @code{.wh.} and @code{.inc.}.)  The colour switches to pure
white at the value @code{.wh.}, and remains pure white everywhere on the
"white" side of this value.  Similarly, the transition to pure black
occurs at the value @code{.bl.}.  In other words, neither pure white nor
pure black is present inside the interval from @code{.wh.} to
@code{.bl.}.  Therefore, when using the @code{draw image palette}
command, you might want to extend the range by one increment so as to
get an example of both pure white and pure black.

@example
.w. = 0
.b. = 1
.i. = 0.2
set image grayscale white .w. black .b. increment .i.
draw image palette left \
  @{rpn .w. .i. -@} \
  right @{rpn .b. .i. +@} \
  increment .i.
@end example


@node   Set Image Missing Value Color, Set Image Range, Set Image Grayscale, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set image missing value color}
@findex set image missing value color
@findex set image missing value colour
@cindex @code{set image missing value color} command
@cindex @code{set image missing value colour} command

@example
`set image missing value color to white|black|\
    @{graylevel .brightness.@}|@{rgb .r. .g. .b.@}`
@end example

@noindent
Set the color of ``missing'' pixels (white by default).  The image range
must have previously have been set by @code{set image range}.  Pixels
with missing values can result from creating images from grids which
have missing values; see the @code{convert grid to image} command.  The
@code{.brightness.} parameter in the @code{graylevel} style ranges from
0 for black to 1 for white.  The @code{rgb} parameters allow setting to
full color.


@node   Set Image Range, Set Input Data Window, Set Image Missing Value Color, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set image range}
@findex set image range
@cindex @code{set image range} command

@example
`set image range @{.min_value. .max_value.@}|@{from grid@}'
@end example

@noindent
In the first style, specify the minimum and maximum image values.  In the
second, set the image range from the range of the grid data.

In either case, Gri needs to know the image range because it stores images in a
limited format capable of holding only 256 distinct values.  Unlike some other
programs, Gri encourages (forces) the user to specify things in terms of
user-units, not image-units.  This has the advantage of working regardless of
the number of bits per pixel.  Thus, for example, @code{set image grayscale},
@code{set image colorscale}, @code{draw image grayscale}, etc, all use *user*
units.

When an image is created by @code{convert grid to image}, values outside the
range spanned by @code{.0value.} and @code{.255value.} are clipped.  (There is
no need, however, for @code{.0value.} to be less than @code{.255value.}.) This
clipping discards information, so make sure the range you give is larger than
the range of data in the grid.

EXAMPLE: consider a satellite image in which an internal value of 0 is meant to
correspond to 0 degrees Celsius, and an internal value of 255 corresponds to
25.5 degrees.  (This is a common scale.)  Then Gri command @code{set image
range 0 25.5} would establish the required range.  If this range were combined
with a linear grayscale mapping (see @code{set image grayscale}), the resultant
granularity in the internal representation of the user values would be
(25.5-0)/255 or 0.1 degrees Celsius; temperature variations from pixel to pixel
which were less than 0.1 degrees would be lost.
    
All other image commands *require* that the range has been set.  Thus, all
these commands fail unless @code{set image range} has been done: @code{draw
image}, @code{draw image palette}, @code{read image}, @code{convert grid to
image}, @code{set image grayscale}, and @code{set image colorscale}.
    
NOTE: If a range already exists when @code{set image range} is used, then the
settings are altered.  Thoughtless usage can therefore lead to confusing
results.  (The situation is like setting an axis scale, plotting a curve with
no axes, then altering the scale and plotting the new axes.  It's legal but not
necessarily smart.)


@node   Set Input Data Window, Set Input Data Separator, Set Image Range, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set input data window}
@findex set input data window
@cindex @code{set input data window} command

@example
`set input data window x|y @{.min. .max.@}|off'
@end example

@noindent
Create a data window for following @code{read} statements.

@itemize @bullet

@item @code{set input data window x .min. .max.}
For future reading commands, ignore all data with x less than
@code{.min.} or x greater than @code{.max.} The data not in the interval
will not be read in at all.  This will hold until 
@code{set data window x off} is done, in which case all data will be read in.

@item @code{set input data window x off}
Return to normal conditions, in which all data are read in.

@item @code{set input data window y .min. .max.}
Analgous to command for x.

@item @code{set input data window y off}
Analagous to command for x.
@end itemize

EXAMPLE: To set the input data window as the current x axis plus a
border of 5 centimetres to left and right, do the following:

@example
set input data window x \
  @{rpn ..xleft..  xusertocm 5 - xcmtouser@} \
  @{rpn ..xright.. xusertocm 5 + xcmtouser@}
@end example

@strong{See also} @code{set clip}
@cindex input data window
@cindex data, clipping using @code{set input data window}
@cindex clipping data using @code{set input data window}



@node   Set Input Data Separator, Set Line Cap, Set Input Data Window, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set input data separator}
@findex set input data separator
@cindex @code{set input data separator} command

@example
`set input data separator TAB|default'
@end example

@noindent
Set the separator between data items.  The @code{default} method is to
assume that data items are separated by one or more spaces or tabs, and
also to ignore any spaces or tabs at the start of a data line.

In the @code{TAB} method the data are assumed to be separated by a
SINGLE tab character.  (Multiple tabs will result in null values being
assigned to items -- almost certainly not what you want!)  Also, initial
spaces and tabs on lines are NOT skipped.

Use the @code{TAB} method only after thinking carefully about the above,
since the assignment of null values is problematic.



@node   Set Line Cap, Set Line Join, Set Input Data Separator, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set line cap}
@findex set line cap
@cindex @code{set line cap} command
@cindex setting line cap type
@cindex line cap

@example
`set line cap .type.'
@end example

@noindent
Set the type of ends (caps) of lines.  Use @code{.type.} of value 0 for
square ends, cut off precisely at the end of line, or 1 for round ends
which overhang half the line width, or 2 for square ends which overhang
half the line width.  The selected style is used for the ends of line
segments, as well as at corners.  In PostScript parlance, therefore,
this command sets both the linecap and the linejoin parameters.

This command only applies to lines drawn with @code{draw curve},
@code{draw line} and @code{draw polygon}.  Axes are always drawn with a
line cap of 0.



@node   Set Line Join, Set Line Width, Set Line Cap, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set line join}
@findex set line join
@cindex @code{set line join} command
@cindex setting line join type
@cindex line join

@example
`set line join .type.'
@end example

@noindent
Set the type of intersection of lines.  Use @code{.type.} of value 0 for
mitered joins (pointy ends that may extend beyond the data points), a
value of 1 for rounded ends (the default), or a value of 2 for bevelled
(squared-off) ends.  See the @code{setlinejoin} command in any text on
the PostScript language for more information.

This command only applies to lines drawn with @code{draw curve},
@code{draw line} and @code{draw polygon}.  Axes are always drawn with a
line join of 0.



@node   Set Line Width, Set Missing Value, Set Line Join, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set line width}
@findex set line width
@cindex @code{set line width} command
@cindex setting line width
@cindex line width

@example
`set line width \
  [axis|symbol|all] \
  .width_pt. \
  | @{rapidograph \name@} \
  | default'
@end example

@noindent
Set the width of lines used to draw curves (default), axes, symbols, or
all of the above.  The width may be set to a value specified in points
(conversion: 72 pt = 1 inch), to a named rapidograph width, or to the
default value.  The initial default values are: 0.709pt (or rapidograph
3x0) for curves; 0.369pt (or rapidograph 6x0) for axes; 0.369pt (or
rapidograph 6x0) for symbols.  (To learn more about standard
pen widths, see the ISO 9175-1 documents.)

@cindex American Geophysical Union, recommended line thickness

If your figure is to be reproduced by a journal, you should check with
them about the range of line thicknesses they recommend.  This will, of
course, depend on whether your figure is reduced or enlarged during
reproduction.  For example, American Geophysical Union (publishers of
J. Geophysical Res.) recommends that one use line thicknesses no less
than 0.5 points and no more than 4 points.



@cindex rapidograph scaling for line width
@cindex slides, suggested line widths
@cindex overhead projection images, suggested line widths
@cindex projected images, suggested line widths

The rapidograph settings match the standard set of widths used in
technical fountain pens.  The table below gives width names along with
the width in points and centimetres, as given in the specifications
supplied with Rapidograph technical fountain pens.  Names marked by the
symbol @code{*} are in sequence increasing by the factor root(2).  Texts
on technical drawing often suggest using linewidths in the ratio of 2 or
root(2).  On many printers, the variation in width from root(2) increase
is too subtle to see, so the factor-of-2 rule may be preferable.  To get
sizes in a sequence doubling in width, pick from the list (@code{6x0},
@code{3x0}, @code{1}, @code{3.5} @code{7}).  To get a sequence
increasing in width by root(2), pick from the list (@code{6x0},
@code{4x0}, @code{3x0}, @code{0}, @code{1}, @code{2.5}, @code{3.5},
@code{6}, @code{7}).  The eye can distinguish curves with linewidths
differing by a factor of root(2) if the image is of high quality, but a
factor of 2 is usually better.  Similarly, for overhead projections and
projected slides, one would do well to use linewidths differing by a
factor of 4.


This is the list of @code{rapidograph} linewidths:

@example
  Name      pt    cm
  ====    =====  =====
*  6x0    0.369  0.013
*  4x0    0.510  0.018
*  3x0    0.709  0.025
    00    0.850  0.03
*    0    0.992  0.035
*    1    1.417  0.05
     2    1.701  0.06
*    2.5  1.984  0.07
     3    2.268  0.08
*    3.5  2.835  0.1
     4    3.402  0.12
*    6    3.969  0.14
*    7    5.669  0.2
@end example




@node   Set Missing Value, Set Page Size, Set Line Width, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set missing value}
@findex set missing value
@cindex @code{set missing value} command
@cindex missing values

@example
`set missing value .value.|none'
@end example

@noindent
If a numerical value is given, set the 
missing-value code to that value, and also 
store this value in the builtin variable
@code{..missingvalue..} and the builtin synonym @code{\.missingvalue..}
also.  After this command, Gri will ignore any data that are within 
0.1 percent of this value.  (This feature is commonly used in geophysical
data.)

If @code{none} is given, turn off this feature.

The default is that the feature is turned off.



@node   Set Page Size, Set Page, Set Missing Value, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set page size}
@findex set page
@cindex @code{set page size} command

@example
`set page size letter|legal|folio|tabloid|A0|A1|A2|A3|A4|A5'
@end example

@noindent
Set the page dimension, as indicated below.
@table @emph

@item letter
American "letter" size: 8.5 x 11 inches

@item legal
American "legal" size: 8.5 x 14 inches

@item folio
American "folio" size: 8.5 x 13 inches

@item tabloid
American "tabloid" size: 11 x 17 inches

@item A5
Metric size: 14.8 x 21.0 cm

@item A4
Metric size: 21.0 x 29.7 cm

@item A3
Metric size: 29.7 x 42.0 cm

@item A2
Metric size: 42.0 x 59.4 cm

@item A1
Metric size: 59.4 x 84.1 cm

@item A0
Metric size: 84.1 x 118.9 cm
@end table

The effect is to possibly alter the PostScript "bounding box."  If all
the drawn material fits within the indicated page, then the bounding
box is not altered.  (In other words, Gri will still keep the bounding
box tight on the drawn items.)  

However, if any drawn item extends beyond the indicated size, it will
be clipped to the boundary.


@node   Set Page, Set Panel, Set Page Size, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set page}
@findex set page
@cindex @code{set page} command

@example
`set page portrait \
  | landscape \
  | @{factor .mag.@} \
  | @{translate .xcm. .ycm.@}'
@end example

@noindent
Control orientation or scaling of what is drawn on the paper.

@cindex portrait orientation of page
@cindex orientation of page, portrait
@cindex page orientation, portrait
@itemize @bullet

@item @code{set page portrait}
Print graph normally (default).

@cindex landscape orientation of page
@cindex orientation of page, landscape
@cindex page orientation, landscape

@item @code{set page landscape}
Print graph sideways.

@item @code{set page factor .mag.}
Scale everything to be drawn on the paper by the indicated magnification
factor.  This @strong{must} be called before any drawing commands.

@item @code{set page translate .xcm. .ycm.}
Translate everything to be drawn on the paper by the indicated x/y
distances.  This @strong{must} be called before any drawing commands.
@end itemize     

@strong{Note}: The order of the factor/translate commands matters, so you
may need to experiment.  For example,

@example
set page translate 2 1
set page factor 0.5
@end example

@noindent
moves anything that would have been drawn at the lower-left corner of
the paper onto the point 2cm from the left side and 1cm from the bottom
side of the paper, and then applies the multiplication factor.
Reversing the order gives quite different results.  PostScript gurus
should note that the following two commands are inserted into the
PostScript file:

@example
56.900000 28.450000 translate
0.500000 0.500000 scale
@end example


@node   Set Panel, Set Panels, Set Page, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set panel}
@findex set panel
@cindex @code{set panel} command
@cindex Multi-panel plots
@cindex Window-pane plots

@example
set panel .row. .col.
@end example

@noindent
Establish the geometry for the panel in the indicated row and column;
that is, select which defined panel to draw into.  The
bottom row has @code{.row.} = 1, and the leftmost column has
@code{.col.} = 1.  This must be used only after defining the panel
layout using @code{Panels .row. .col. .dx_cm. .dy_cm.}.


@node   Set Panels, Set Path To, Set Panel, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set panels}
@findex set panels
@cindex @code{set panels} command
@cindex Multi-panel plots
@cindex Window-pane plots

@example
set panels .rows. .cols. [.dx_cm. .dy_cm.]
@end example

@noindent
Set up for multipanel plots, with spacing @code{.dx_cm.} between the
columns and @code{.dy_cm.} between the rows.  If the spacings are not
supplied, 2cm is used.  The panels fill the rectangle which would
otherwise contain the single axis frame, as set by @code{set x size} and
@code{set x margin}, etc.

The global variables @code{.panel_dx.}, @code{.panel_dy.},
@code{.panel_xmargin.}, @code{.panel_ymargin.}, @code{.panel_xsize.},
and @code{.panel_ysize} are created, to be used by later calls to
@code{set panel}.

EXAMPLE 

@example
# Draw 2 panels across, 3 up the page.

# The Panel interiors will be in region cornered
# by (2,2), (12,22) cm
set x margin 2
set y margin 2
set x size 10
set y size 20
set panels 2 3

# Create dummy scale
set x axis 0 1
set y axis 0 1

# Draw blank axes
et panel 1 1
raw axes
set panel 1 2
draw axes
set panel 1 3
draw axes
set panel 2 1
draw axes
set panel 2 2
draw axes
set panel 2 3
draw axes
@end example

@strong{See also} @code{set panel .row. .col.}


@node   Set Path To, Set Postscript Filename, Set Panels, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set path}
@findex set path
@cindex @code{set path} command
@cindex path, for command files
@cindex path, for data files
@cindex command files, path to search for
@cindex data files, path to search for
@cindex @code{\\.path_data.} builtin synonym
@cindex @code{\\.path_commands.} builtin synonym
@cindex builtin synonym @code{\\.path_data.}
@cindex builtin synonym @code{\\.path_commands.}

@example
set path to "\path"|default for data|commands
@end example

@noindent
Set the directory path that @code{open} will search for data files, or
that @code{insert} will search for command files.  This search will
@emph{not} be done if the filename starts with a @code{/}, @code{~}, or
@code{.} character.

The path is formatted in a colon-separated manner, following the normal
Unix convention, and searching is from left to right.  For example, the
path @code{".:/usr/lib/gri"} tells Gri to search for the file first in
the local directory (named @file{.}), and if it is not found there, to
look next in the directory named @file{/usr/lib/gri}.

The indicated path is stored in either @code{\.path_data.} or
@code{\.path_commands.}, as appropriate.  At startup time, each of these
paths is set to @file{"."}, the current directory, and this value is
reset if the @code{default} keyword is provided to this command.

If you need to know where the file was eventually found, save the
@code{\.return_value.} just after the @code{open} command was executed.
For example, the following defines the synonym @code{\uk}, which is the
full pathname of the file containing some sort of data about Great
Britain.  

@example
set path to "/atlases/world:/atlases/northern_hemisphere" for data
open britain.dat        # we don't know where file is ...
\gb = "\.return_value." # ... until now!

# Can later do command such as
#    read from \gb
# or
#    rewind \gb
# to work with this particular file, even if
# there is another file open that also is
# named "britain.dat".
@end example

@node   Set Postscript Filename, Set Symbol Size, Set Path To, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set postscript filename}
@findex set postscript filename
@cindex @code{set postscript filename} command
@cindex name, of PostScript file
@cindex postscript filename

@example
`set postscript filename "\name"'
@end example

@noindent
Set name of PostScript file, over-riding the present name.


@node   Set Symbol Size, Set Tic Size, Set Postscript Filename, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set symbol size}
@findex set symbol size
@cindex @code{set symbol size} command
@cindex setting symbol size
@cindex symbols, setting size

@example
`set symbol size .diameter_cm.|default'
@end example

@noindent
Control the diameter of symbols drawn by @code{draw symbol} command.

@itemize @bullet

@item @code{set symbol size .diameter_cm.}
Make symbol size be @code{.diameter_cm.} centimeters in diameter.

@item @code{set symbol size default}
Set to default diameter of 0.1 cm.
@end itemize


@node   Set Tic Size, Set Trace, Set Symbol Size, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set tic size}
@cindex axes, setting tic size
@cindex tic size, setting
@findex set tic size
@cindex @code{set tic size} command

@example
`set tic size .size.|default'
@end example

@noindent
Control size of tics on axes.
@itemize @bullet

@item @code{set tic size .size.}
Set tic size to @code{.size.} centimetres.

@item @code{set tic size default}
Set tic size to default of 0.2 cm.

@item @code{set tics in|out}
Make axis tics point inward or outward.  The default is outward.
@end itemize


@node   Set Trace, Set Transparency, Set Tic Size, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set trace}
@findex set trace
@cindex @code{set trace} command

@example
`set trace [on|off]'
@end example

@noindent
Control printing of command lines as they are processed.

@itemize @bullet

@item @code{set trace}
Make Gri print command lines as they are processed.

@item @code{set trace on}
Same as @code{set trace}.

@item @code{set trace off}
Prevent printing command lines (default).
@end itemize

@node   Set Transparency, Set U Scale, Set Trace, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set transparency}
@findex set transparency
@cindex @code{set transparency} command

@example
`set transparency .transparency.'
@end example

@noindent

Set the transparency of drawn items, 0 for opaque and 1 for invisibly
faint.  @emph{This command is provisional, as of summer 2004, and 
this part of the documentation needs to be fleshed out so
users can build intuition on transparency.  For example, 
a quick quiz: what color do you think comes from drawing
red on top of yellow, or on top of blue?
}


@node   Set U Scale, Set V Scale, Set Transparency, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set u scale}
@findex set u scale
@cindex @code{set u scale} command

@example
`set u scale .cm_per_unit.|@{as x@}'
@end example

@noindent
Set scale for x-component of arrows.

@itemize @bullet

@item @code{set u scale .cm_per_unit.}
Set scale for @code{u} component of arrows.  

@item @code{set u scale as x}
Set scale for u component of arrows to be the same as the x-scale.
Equivalent to 
@code{set u scale as @{rpn ..xsize.. ..xright.. ..xleft.. - /@}}.
@end itemize

NOTE: this only works if the x-scale is LINEAR (see @code{set x type}).



@node   Set V Scale, Set X Axis, Set U Scale, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set v scale}
@findex set v scale
@cindex @code{set v scale} command

@example
`set v scale .cm_per_unit.|@{as y@}'
@end example

@noindent
Set scale for y-component of arrows.

@itemize @bullet

@item @code{set v scale .cm_per_unit.}
Set scale for @code{v} component of arrows.

@item @code{set v scale as y}
Set scale for v component of arrows to be the same as the y-scale.
Equivalent to 
@code{set v scale as @{rpn ..ysize.. ..ytop.. ..ybottom.. - /@}}.
@end itemize

NOTE: this only works if the y-scale is LINEAR (see @code{set y type}).


@node   Set X Axis, Set X Format, Set V Scale, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set x axis}
@findex set x axis
@cindex @code{set x axis} command

@example
`set x axis top'
`set x axis bottom'
`set x axis increasing'
`set x axis decreasing'
`set x axis unknown'
`set x axis .left. .right. [.incBig. [.incSml.]] [labelling .labelling_value.]'
`set x axis labels [add] .position_1. "label_1" [.position_2. "label_2" [...]]'
`set x axis labels automatic'
@end example

@noindent
Control various things about the x axis.

@itemize @bullet

@item @code{set x axis top}
Make next x-axis to be drawn have labels above the axis.

@item @code{set x axis bottom}
Make next x-axis to be drawn have labels below the axis.

@item @code{set x axis increasing}
Make next x-axis to be drawn have numeric labels increasing to the
right.  This applies only if autoscaling is done; otherwise, the
supplied values (@code{.left. .right. [.incBig.  [.incSml.]]}) are used.

@item @code{set x axis decreasing}
Make next x-axis to be drawn have numeric labels decreasing to the
right.  This applies only if autoscaling is done; otherwise, the
supplied values (@code{.left. .right. [.incBig.  [.incSml.]]}) are used.

@item @code{set x axis unknown}
Make Gri forget any existing scale for the x axis, whether set by
another @code{set x axis} command or automatically, during reading of
data.  This is essentially a synonym for @code{delete x scale}.

@item @code{set x axis .left. .right.}
Make x-axis range from @code{.left.} to @code{.right.}

@item @code{set x axis .left. .right. .incBig.}
Make x-axis range from @code{.left.} to @code{.right.}, with labelled
increments at @code{.incBig.} Note: In the case of log axes, and
provided that @code{set x type log} has been called previously, the
@code{.incBig.} parameter has a different meaning: it is the interval,
in decades, between numbered labels; the default is 1.  

@item @code{set x axis .left. .right. .incBig. labelling .labelling_value.} 
As above, but with the axis labels including the indicated value, and
incremented larger and smaller by @code{.incBig}.  (This does not work
for logarithmic axes.)

@item @code{set x axis .left .right. .incBig. .incSml.}
Make x-axis range from @code{.left.} to @code{.right.}, with labelled
increments at @code{.incBig.}, and small tics at @code{.incSml.}  NOTE:
if the axis is logarithmic, the value of @code{.incSml.} takes on a
special meaning: if it is positive then small tics are put at values 2,
3, 4, etc. between the decades, but if @code{.incSml.} is negative then
no such small tics are used.

@item @code{set x axis .left .right. .incBig. .incSml. labelling .labelling_value.} 
As above, but with the axis labels including the indicated value, and
incremented larger and smaller by @code{.incBig}. (This does not work
for logarithmic axes.)


@item @code{set x axis labels .position. "label" [.position. "label" [...]]}
@cindex axis labels, controlling
@cindex day-of-week axis
Override the automatic labelling at axis tics, and instead put the
indicated labels at the indicated x values.  For example, a
day-of-week axis can be created by the code:

@example
set x axis 0 7 1
set x axis labels 0.5 "Mon" 1.5 "Tue" 2.5 "Wed" \
                  3.5 "Thu" 4.5 "Fri" 5.5 "Sat" \
                  6.5 "Sun"
@end example

The command replaces any existing labels, unless the `add' keyword is
present, in which case the new label information is appended to any
existing information.


@item @code{set x axis labels automatic}
Return to automatically-generated axis labels, undoing the command of
the previous item.

@end itemize


@node   Set X Format, Set X Grid, Set X Axis, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set x format}
@findex set x format
@cindex @code{set x format} command

@example
`set x format \format|default|off
@end example

@noindent
Set format for numbers on x axis.  The format is specified in the manner
of the "C" programming language.  The C formats (i.e., @code{%f},
@code{%e} and @code{%g}) are permitted.  
For example, @code{set x format %.1f} tells Gri to use 1 decimal place,
and to prefer the "float" notation to the exponential notation.  The
form @code{set x format off} tells Gri not to write numbers on the axis.
To get spaces in your format, enclose the format string in
double-quotes, e.g., you might use @code{set x format "%.0f$\circ$ W"}
for a map, or @code{set x format "%f "} to make the numbers appear to
the left of their normal location. 

The default format is @code{%lg}.


@node   Set X Grid, Set X Margin, Set X Format, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set x grid}
@findex set x grid
@cindex @code{set x grid} command

@example
`set x grid .left. .right. .inc.|@{/.cols.@}'
@end example

@noindent
Create x-grid for contour or image.  If a grid already exists, an error
will be declared; the way to interpolate from an existing grid to a new
one is with the @code{interpolate x grid} command.

@itemize @bullet

@item @code{set x grid .left. .right. .inc.}
Create x-grid ranging from the value @code{.left.} at the left to
@code{.right.} at the right, stepping by an increment of @code{.inc.}. 

@item @code{set x grid .left. .right. /.cols.}
Create x-grid with @code{.cols.} points, ranging from the value
@code{.left.} at the left to @code{.right.} at the right.
@end itemize


@node   Set X Margin, Set X Name, Set X Grid, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set x margin}
@findex set x margin
@cindex @code{set x margin} command

@example
`set x margin @{[bigger|smaller] .size.@}|default'
@end example

@noindent
Control x margin, that is, the space between the left-hand side of the
page and the left-hand side of the plotting area.  (Note that axis
labels are drawn inside the margin; the margin extends to the axis line,
not to the labels.)

@itemize @bullet

@item @code{set x margin .size.}
Set left margin to @code{.size.} cm.  It is permissible to have negative
margins, with the expected effect.

@item @code{set x margin bigger .size.}
Increases left margin by @code{.size.} cm.

@item @code{set x margin smaller .size.}
Decreases left margin by @code{.size.} cm.
@item @code{set x margin default}
Set left margin to default = 6 cm.
@end itemize



@node   Set X Name, Set X Size, Set X Margin, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set x name}
@findex set x name
@cindex @code{set x name} command

@example
`set x name "\name"|default'
@end example

@noindent
Set name of x-axis to the indicated string.  An empty string
(@code{set x name ""}) causes the x axis to be unlabelled.  The
@code{default} is @code{"x"}.



@node   Set X Size, Set X Type, Set X Name, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set x size}
@findex set x size
@cindex @code{set x size} command

@example
`set x size .width_cm.|default'
@end example

@noindent
Set the width of the plotting area.  This does not include axis labels,
only the interior part of the plot.


@itemize @bullet

@item @code{set x size .width_cm.}
Set width of x-axis in centimeters.

@item @code{set x size default}
Set width of x-axis to default = 10 cm.
@end itemize


@node   Set X Type, Set Y Axis, Set X Size, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set x type}
@findex set x type
@cindex @code{set x type} command

@example
set x type linear|log|@{map E|W|N|S@}
@end example

@noindent
Control transformation function mapping user units to centimetres on the
page.  


@itemize @bullet

@item @code{set x type linear}
Set to linear axis.

@item @code{set x type log}
Set to log axis.  To avoid clashes in the linear to log transform, this
command should precede the creation of an axis scale, either explicitly
through the @code{set x axis .left. .right. ...} command or implicitly
through the @code{read columns} command.

@item @code{set x type map E|W|N|S}
@cindex maps, format of x axis
Set to be a map.  This means that whole numbers on the axis will have a
degree sign written after them (and then the letter @code{E}, etc) and
that numbers which are multiples of 1/60 will be written in
degree-minute format, and that similarly numbers which are divisible by
1/3600 will be in degree-minute-second format.  If none of these things
apply, the axis labels will be written in decimal degrees.  Note that
this command overrides any format set by @code{set x format}.

BUG: this only has an effect if the axis is not already of type
@code{log}. 
@end itemize



@node   Set Y Axis, Set Y Format, Set X Type, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set y axis}
@findex set y axis
@cindex @code{set y axis} command

@example
`set y axis left'
`set y axis right'
`set y axis increasing'
`set y axis decreasing'
`set y axis .bottom. .top. [.incBig. [.incSml.]] [labelling .labelling_value.]'
`set y axis labels [add] .position_1. "label_1" [.position_2. "label_2" [...]]'
`set y axis labels automatic'
@end example

@noindent
Control various things about the y axis.

@itemize @bullet

@item @code{set y axis name horizontal}
Make y-axis name be horizontal.

@item @code{set y axis name vertical}
Make y-axis name be vertical (default).

@item @code{set y axis left}
Make next y-axis to be drawn have labels to the left of the axis.

@item @code{set y axis right}
Make next y-axis to be drawn have labels to the right of the axis.

@item @code{set y axis increasing}
Make next y-axis to be drawn have numeric labels increasing up the page.
This applies only if autoscaling is done; otherwise, the supplied values
(@code{.left. .right. [.incBig.  [.incSml.]]}) are used.

@item @code{set y axis decreasing}
Make next y-axis to be drawn have numeric labels decreasing up the page.
This applies only if autoscaling is done; otherwise, the supplied values
(@code{.left. .right. [.incBig.  [.incSml.]]}) are used.

@item @code{set y axis unknown}
Make Gri forget any existing scale for the y axis, whether set by
another @code{set y axis} command or automatically, during reading of
data.  This is essentially a synonym for @code{delete y scale}.

@item @code{set y axis .bottom. .top.}
Make y-axis range from @code{.bottom.} to @code{.top.}

@item @code{set y axis .bottom. .top. .incBig.}
Make y-axis range from @code{.bottom.} to @code{.top.}, with labelled
increments at @code{.incBig.}

@item @code{set y axis .bottom. .top. .incBig. labelling .labelling_value.}
As above, but with the axis labels including the indicated value, and
incremented larger and smaller by @code{.incBig}. (This does not work
for logarithmic axes.)

@item @code{set y axis .bottom. .top. .incBig. .incSml.}
Make y-axis range from @code{.bottom.} to @code{.top.}, with labelled
increments at @code{.incBig.}, and small tics at @code{.incSml.}  NOTE:
if the axis is logarithmic, the value of @code{.incSml.} takes on a
special meaning: if it is positive then small tics are put at values 2,
3, 4, etc. between the decades, but if @code{.incSml.} is negative then
no such small tics are used.

@item @code{set y axis .bottom. .top. .incBig. .incSml. labelling .labelling_value.}
As above, but with the axis labels including the indicated value, and
incremented larger and smaller by @code{.incBig}. (This does not work
for logarithmic axes.)

@item @code{set y axis labels .position. "label" [.position. "label" [...]]}
Override the automatic labelling at axis tics, and instead put the
indicated labels at the indicated y values.  For example, a
physical-condition axis can be created by the code:

@example
set y axis 0 1 0.5
set y axis labels 0.25 "Weak" 0.75 "Strong"
@end example

The command replaces any existing labels, unless the `add' keyword is
present, in which case the new label information is appended to any
existing information.


@item @code{set y axis labels automatic}
Return to automatically-generated axis labels, undoing the command of
the previous item.

@item @code{set y axis name vertical}
Cause future y axes to be drawn with the name aligned vertically (the default).

@item @code{set y axis name horizontal}
Cause future y axes to be drawn with the name aligned horizontally.

@end itemize


@node   Set Y Format, Set Y Grid, Set Y Axis, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set y format}
@findex set y format
@cindex @code{set y format} command

@example
`set y format \format|default|off'
@end example

@noindent
Set format for numbers on y axis.  The format is specified in the manner
of the "C" programming language.  The C formats (i.e., @code{%f},
@code{%e} and @code{%lg}) are permitted.  For example, 
@code{set y format %.1f} tells Gri to use 1 decimal place, and to prefer
the "float" notation to the exponential notation.  
The form @code{set y format off} 
tells Gri not to write numbers on the axis.  To get spaces in your
format, enclose the format string in double-quotes, e.g., you might use
@code{set y format "%.0f$\circ$ N"} for a map, or 
@code{set y format "%f"} to make the numbers appear to the right of
their normal location.

The default format is @code{%lg}.

@node   Set Y Grid, Set Y Margin, Set Y Format, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set y grid}
@findex set y grid
@cindex @code{set y grid} command

@example
`set y grid .bottom. .top. .inc.|@{/.rows.@}'
@end example

@noindent
Create y-grid for contour or image.  If a grid already exists, an error
will be declared; the way to interpolate from an existing grid to a new
one is with the @code{interpolate x grid} command.

@itemize @bullet

@item @code{set y grid .bottom. .top. .inc.}
Create y-grid ranging from the value @code{.bottom.} at the bottom to
@code{.top.} at the top, stepping by an increment of @code{.inc.}.

@item @code{set y grid .bottom. .top. /.rows.}
Create y-grid with @code{.rows.} points, ranging from the value
@code{.bottom.} at the bottom to @code{.top.} at the top.
@end itemize



@node   Set Y Margin, Set Y Name, Set Y Grid, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set y margin}
@findex set y margin
@cindex @code{set y margin} command

@example
`set y margin @{[bigger|smaller] .size.@}|default'
@end example

@noindent
Control y margin, that is, the space between the bottom side of the page
and the bottom of the plotting area.  (Note that axis labels are drawn
inside the margin; the margin extends to the axis line, not to the
labels.)

@itemize @bullet

@item @code{set y margin .size.}
Set bottom margin to @code{.size.} centimeters.  It is permissible to
have negative margins, with the expected effect.

@item @code{set y margin bigger .size.}
Increases bottom margin by @code{.size.} centimeters.

@item @code{set y margin smaller .size.}
Decreases bottom margin by @code{.size.} centimeters.

@item @code{set y margin default}
Set bottom margin to default = 6 cm.
@end itemize



@node   Set Y Name, Set Y Size, Set Y Margin, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set y name}
@findex set y name
@cindex @code{set y name} command

@example
`set y name "\name"|default'
@end example

@noindent
Set name of y-axis to the indicated string.  An empty string
(@code{set y name ""}) causes the x axis to be unlabelled.  The
@code{default} is @code{"y"}.



@node   Set Y Size, Set Y Type, Set Y Name, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set y size}
@findex set y size
@cindex @code{set y size} command

@example
`set y size .height_cm.|default'
@end example

@noindent
Set the width of the plotting area.  This does not include axis labels,
only the interior part of the plot.

@itemize @bullet

@item @code{set y size .height_cm.}
Set height of y-axis in centimeters.

@item @code{set y size default}
Set width of y-axis to default = 10 cm.
@end itemize



@node   Set Y Type,  Set Z Missing, Set Y Size, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set y type}
@findex set y type
@cindex @code{set y type} command

@example
set y type linear|log|@{map N|S|E|W@}
@end example

@noindent
Control transformation function mapping user units to centimetres on the
page.  

@itemize @bullet

@item @code{set y type linear}
Set to linear axis.

@item @code{set y type log}
Set to log axis.  To avoid clashes in the linear to log transform, this
command should precede the creation of an axis scale, either explicitly
through the @code{set y axis .left. .right. ...} command or implicitly
through the @code{read columns} command.

@item @code{set y type map N|S|E|W}
@cindex maps, format of y axis
Set to be a map.  This means that whole numbers on the axis will have a
degree sign written after them (and then the letter @code{N}, etc), and
that numbers which are multiples of 1/60 will be written in
degree-minute format, and that similarly numbers which are divisible by
1/3600 will be in degree-minute-second format.  If none of these things
apply, the axis labels will be written in decimal degrees.  Note that
this command overrides any format set by @code{set y format}.

BUG: this only has an effect if the axis is not already of type
@code{log}. 
@end itemize

@node   Set Z Missing, Show, Set Y Type, Set
@comment  node-name,  next,  previous,  up
@subsubsection @code{set z missing}
@findex set z missing
@cindex @code{set z missing} command

@example
set z missing above|below .intercept. .slope.
@end example

@noindent
Set @code{z} column to be missing whenever the associated @code{y} and
@code{x} columns are above/below the line defined by
@tex
$y = {\rm .intercept.} + {\rm .slope.} x$
@end tex
@ifinfo
y = .intercept. + .slope. * x
@end ifinfo


@c HTML <!-- newfile Show.html "Gri: `show' command" "Gri Commands" -->

@node   Show, Skip, Set Z Missing, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{show}
@findex show
@cindex @code{show} command

@example
`show ...'
@end example

@noindent
Show some information by printing it to standard output.

@itemize @bullet

@item @code{show all}
Show lots of information about plot.

@item @code{show axes}
@cindex axes, displaying information about
Show information about axes.

@item @code{show color}
Show the current pen color used for lines and text.  This is not to be
confused with image color, which is independent.

@item @code{show colornames}
@cindex RGB values of known colors
@cindex color, displaying names and RGB values of
Show all colors known by name, as defined by @code{read colornames}
command and also the builtin colors defined automatically
(e.g. @code{white}, @code{black}, @code{red}, etc),
(@ref{Read Colornames}).

@item @code{show columns}
Show x, y, z, u, v column data.

@item @code{show columns statistics}
@cindex statistics of column data
@cindex column, displaying statistics of
Show means, std devs, etc for columns.

@item @code{show flags}
Show values of all flags. (Developers only.)

@item @code{show grid}
@cindex grid data, displaying
Show an indication of the grid data (used for contouring).

@item @code{show grid mask}
@cindex grid mask, displaying
Show 1 if grid data are valid or 0 if contours will not extend into this
region.
@c REMOVED FOR 2.6.0 @item @code{show hint of the day}
@c REMOVED FOR 2.6.0 @cindex hint of the day, displaying
@c REMOVED FOR 2.6.0 Show a Gri hint for today, picked at random from hints stored on the web
@c REMOVED FOR 2.6.0 at 
@c REMOVED FOR 2.6.0 @c HTML <A HREF="http://gri.sourceforge.net/gridoc/html/HINTS.html">
@c REMOVED FOR 2.6.0 @file{http://gri.sourceforge.net/gridoc/html/HINTS.html}
@c REMOVED FOR 2.6.0 @c HTML </A>
@c REMOVED FOR 2.6.0 These will be downloaded at most once per day.  Since the download might
@c REMOVED FOR 2.6.0 take a couple of seconds, the hint is only downloaded once per day,
@c REMOVED FOR 2.6.0 being cached for later uses in the given day, in a user file called
@c REMOVED FOR 2.6.0 @file{~/.gri-hint-cache}.  This command will 
@c REMOVED FOR 2.6.0 produce warning if the system program @code{lynx} is not available for
@c REMOVED FOR 2.6.0 downloading.

@item @code{show image}
@cindex image, displaying histogram of
Show information about image, such as a histogram of values, and, if the
image is small enough, the actual data.

@item @code{show license}
Show the license for Gri, which outlines how users are allowed to share
it freely.

@item @code{show misc}
Show miscellaneous information about the plot, the data, etc.

@item @code{show next line}
Show next line of data-file.

@item @code{show synonyms}
@cindex synonyms, displaying list of
Show values of all synonyms, whether built-in or user-defined.

@item @code{show stopwatch}
@cindex timing things
@cindex stopwatch, for timing things
@cindex @code{show stopwatch} command
Show elapsed time since first call to this command in the given Gri program.

@item @code{show time}
Show the current time.

@item @code{show traceback}
@cindex traceback
Show traceback (i.e., the tree of commands being done at this instant).

@item @code{show variables}
@cindex variables, displaying list of
Show values of all variables, whether built-in or user-defined.

@item @code{show .value.}
Show value of indicated variable.

@item @code{show @{rpn ...@}}
Show result of computing indicated expression.

@item @code{show "some text"}
@cindex @code{show} command, how to get a tab
@cindex @code{show} command, how to get a newline
@cindex tab, in a @code{show} command
@cindex newline, in a @code{show} command
Print the indicated string.  You may use a double-slash to prevent Gri
from substituting synonym values; thus it is common to do e.g.

@example
\var = "Temperature"
show "Plotting \\var = 'var'"
@end example

@noindent
which will produce the output line

@example
Plotting \\var = 'Temperature'
@end example

@item @code{show "time=" .time. "; depth=" .depth.}
Print strings and values as indicated.  If the last item is ellipses
(three dots with no spaces between them), then no newline is printed;
this makes the next @code{show} statement print on the same line.

@cindex @code{\<<}, for newline in @code{show} commands
@cindex @code{\>>}, for horizontal tab in @code{show} commands
@cindex newline, using @code{\<<} in @code{show}
@cindex tab, using @code{\>>} in @code{show}
@cindex @code{show} command, using @code{\<<} for newline
@cindex @code{show} command, @code{\>>} for horizontal tab

To get a newline in a printed string, use the three-character glyph
@code{\<<}, and to get a horizontal tab, use @code{\>>}, as in the
examples below

@example
\a = "HI"
show "\\a=\a"		
system echo -e "a\\nb"
show "first line\<<second line"
show "first line\<<\>>(tabbed) second line"
show "first line\<<\>>(tabbed) second line"
@end example

@end itemize


@c HTML <!-- newfile Skip.html "Gri: `skip' command" "Gri Commands" -->

@node   Skip, Sleep, Show, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{skip}
@findex skip
@cindex @code{skip} command
@cindex data files, positioning within
@cindex files, positioning within

@example
`skip [forward|backward] [.n.]'
@end example


@itemize @bullet

@item @code{skip}
For ascii files, skip next line in the data file.  For binary files,
skip forward 1 byte.

@item @code{skip backward}
For ascii files, skip backward 1 line in the data file.  For binary
files, skip backward 1 byte.

@item @code{skip .n.} or @code{forward .n.}
For ascii files, skip forward @code{.n.} lines in the data file.  For
binary files, skip forward @code{.n.} bytes.

@item @code{skip backward .n.}
For ascii files, skip backward @code{.n.} lines in the data file.  For
binary files, skip backward @code{.n.} bytes.
@end itemize


@c HTML <!-- newfile Sleep.html "Gri: `sleep' command" "Gri Commands" -->

@node   Sleep, Smooth, Skip, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{sleep}
@cindex sleep, causing Gri to
@cindex process, causing Gri to sleep
@cindex @code{sleep} command

@example
`sleep .sec.'
@end example

Cause Gri to sleep for the indicated number of seconds, which should be
a positive integer.  This command is ignored if @code{.sec.} is zero or
negative, and the value of @code{.sec.} is first rounded to the nearest
integer.

Normally, this command is used only by the developer, as a way to slow
down Gri execution, to allow easier monitoring for debugging purposes.
Beware: it is tricky to kill a sleeping job!


@c HTML <!-- newfile Smooth.html "Gri: `smooth' command" "Gri Commands" -->

@node   Smooth, Source, Sleep, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{smooth}
@cindex columns, filtering
@cindex smoothing column data
@findex smooth
@cindex @code{smooth} command
All these smoothing commands ignore the @strong{location} of the data.  For
equispaced data these algorithms have the standard interpretation in
terms of digital filters.  For non-equispaced data, the interpretation
is up to the user.

@example
`smooth @{x [.n.]@} \
  | @{y [.n.]@} \
  | @{grid data [.f.|@{along x|y@}]@}'
@end example

The @code{smooth x} command does smoothing by the following formula

@example
x[i-1]   x[i]   x[i+1]
------ + ---- + ------
  4       2       4
@end example

The @code{smooth x .n.} command does boxcar smoothing with centred
boxcars @code{.n.} points wide.  The @code{smooth y} command does the
same as @code{smooth x}, but on the @code{y} column.

@cindex grid data, smoothing
@cindex smoothing grid data
@cindex contours, smoothing grid data
@findex smooth grid data
@cindex @code{smooth grid data} command
There are several methods of smoothing grid data.  Note that isolated
missing values are filled in by each method.  (Let the author know if
you'd like that `feature' to be an option.)

The @code{smooth grid data} command smooths gridded data, by weighted
average in a plus-shaped window about each gridpoint.  The smoothing
algorithm replaces each interior gridpoint value @code{z[i][j]} by

@example
z[i][j]   z[i-1][j] + z[i+1][j] + z[i][j-1] + z[i][j+1]
------- + ---------------------------------------------
   2                          8
@end example     

@noindent
Points along the edges are smoothed by the same formula, after
inventing image points outside the domain by planar extrapolation.

The @code{smooth grid data .f.} command performs partial smoothing.  A
temporary fully-smoothed grid @code{zSMOOTH[i][h]} is constructed as
above, and a linear combination of this grid and the original grid is
used as the replacement grid:

@example
z[i][j] = (1-f) * z[i][j] + f * zSMOOTH[i][j]
@end example

@noindent
where @code{f} is the value indicated on the command line.  
Thus, @code{smooth grid data 0} performs no smoothing at all, while
@code{smooth grid data 1} is equivalent to @code{smooth grid data}.

The @code{smooth grid data along x} command smooths the grid data
across @code{x} (i.e., horizontally), by replacing each value
@code{z[i][j]} with the value

@example
z[i][j]   z[i-1][j] + z[i+1][j]
------- + ---------------------
   2                4
@end example

@noindent
Points along the edges are smoothed by the same formula, after
inventing image points outside the domain by linear extrapolation.

The @code{smooth grid data along y} command does the same thing as
@code{smooth grid data along x}, but the smoothing is along @code{y}.


@strong{See also} @ref{Filter}, a generalization of @code{smooth x|y}
which allows for more sophisticated filters.



@c HTML <!-- newfile Source.html "Gri: `source' command" "Gri Commands" -->

@node   Source, Sprintf, Smooth, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{source}
@findex source
@cindex @code{source} command, for running another command file
@cindex running a commandfile

@example
`source \filename'
@end example

@noindent
Perform the commands in the indicated file.

If the file cannot be found, an error results.  Contrast this with the
@code{insert} command (@ref{Insert}), which has the ability to search
for the file through a user-specified path (@ref{Set Path To}).


@c HTML <!-- newfile Sprintf.html "Gri: `sprintf' command" "Gri Commands" -->

@node   Sprintf, State, Source, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{sprintf}
@findex sprintf
@cindex @code{sprintf} command
@cindex variables, storing values within synonyms (strings)
@cindex strings, storing variable values within
@cindex synonyms, storing variable values within

@example
`sprintf \synonym "format" .variable. [.variable. [...]]'
@end example

@noindent
Write numbers into a synonym (text string).  This is useful for
labelling plots.

@noindent
@code{sprintf \out "a = %lf b = %.2f" .a. .b.} - Create a synonym
called @code{\out}, and print the values of the variables @code{.a.} and
@code{.b.} into it.  If @code{.a.} = 1 and @code{.b.} = 0.112, then
@code{\out} will be @code{"a = 1 b = 0.11"}

Formatting codes are as in the C programming language, eg:

@example
%.2f  -- Use floating point with 2 decimal places.
%9.2f -- As above, but number takes 9 characters.
%e    -- Use exponential notation.
@end example

@noindent
@strong{CAUTION}: Variables are stored in the @strong{floating point} in
Gri, so you must use a format like @code{"%f"},
@strong{not} an integer code like @code{"%d"}.
If you want an integer, use @code{"%.0f"}.
@cindex format, for sprintf command


@c HTML <!-- newfile State.html "Gri: `state' command" "Gri Commands" -->

@node   State, Superuser, Sprintf, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{state}
@cindex saving graphics state
@cindex restoring graphics state
@cindex graphics state, saving and restoring
@findex @code{state} command

@example
`state save|restore|display'
@end example

@noindent
The @code{save} operation pushes a record of the graphics state (pen and
font characteristics, margins, axis lengths, min/max/inc values on axes,
etc) onto a stack.  The @code{restore} operation replaces the present
state with whatever is on top of the stack, and then pops the stack.
Use @code{display} to see some of the state properties.

The @code{state} command is useful for temporary changes of axis
properties, etc.

BUG: only line characteristics (width, color) and font characteristics
(font, size, color) are saved so far.  In fact, the full list of what
should be saved has not yet been finalized by the author.


@c HTML <!-- newfile Superuser.html "Gri: `superuser' command" "Gri Commands" -->

@node   Superuser, System, State, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{superuser}
@cindex debugging using superuser flags
@cindex superuser flags
@findex superuser
@cindex @code{superuser} command

@example
`superuser [value]'
@end example

@noindent
Allow extra debugging information and commands.  Normally, this command
and the corresponding commandline flag @code{-superuser} are only used
by programmers altering the Gri source.

These are the flags and their meanings:
@itemize @bullet

@item @strong{1} Print cmdline before/after substituting synonyms.

@item @strong{2} Print cmdline before/after substituting rpn expressions.

@item @strong{4} Print all new commands as they are being defined

@item @strong{8} Print the system commands that are used with
@code{open "...|"} and in other instances.

@item @strong{128} Changeable; only author should use this.

@item @strong{256} Changeable; only author should use this.
@end itemize
Note that all flags are equal to 2 raised to an integer power.  Since
the flag values are detected by a bitwise OR, you can combine flags by
adding; thus specifying a flag of 5 yields flags 1 and 4 together;
specifying 15 yields flags 1, 2, 4 and 8.


@c HTML <!-- newfile System.html "Gri: `system' command" "Gri Commands" -->

@node   System, Unlink, Superuser, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{system}
@cindex gawk, sample of use
@cindex operating system commands, printing results of
@cindex system commands, printing results of
@cindex operating system commands, assigned to synonyms
@cindex system commands, assigned to synonyms
@findex system
@cindex @code{system} command

@example
`system \system-command'
@end example

@noindent
Tell the operating system to perform the indicated action.  Whatever
string follows the word @code{system} is passed directly to the
operating system, @strong{after} substitution of synonyms if any exist.

@cindex comments, and system commands
@cindex quoting in system commands
If your system command contains double-slashes, you must protect them
from Gri (which will interpret them as comments) by enclosing in
double-quotes, e.g. @code{system cat A | sed -e "s/foo//g" | cat > B}.
(In the particular case of the @code{sed} command you could also do
@code{system cat A | sed -e "s:foo::g" | cat > B}.

Note that @code{rpn} expressions are not evaluated, and variable values
are not substituted before passing the string to the operating system.
The exit status is stored in the builtin variable
@code{..exit_status..}. 

There are two ways to use the system:
@itemize @bullet
@item
@strong{Assign output to synonym}: The form @code{\synonym = system ...}
does the system command and then inserts the output from that command
into the indicated synonym.)

@item @strong{Just run a command}: The command @code{system ls} will list
the files in the current directory.
@end itemize

For long commands, there are two approaches, the second preferred:
@itemize @bullet
@item
@strong{Use continuation lines}: String a lot of information onto one
effective system line, using the @code{\} line-continuation character
at the ends of lines.  The problem is that it is very easy to lose one of
these backslashes.  The next method is better.
@item
@strong{Here-is syntax} The here-is syntax of many unix shells is also
provided.  If the system command contains the characters @code{<<}
followed by a word (with no space between!) then Gri will issue a system
command which includes not only this line but also all succeeding lines,
until a line is found which matches the indicated word precisely (with
no leading space allowed).  The @code{<< "WORD"} syntax is also
supported, meaning that the operating system is being told not to mess
with the dollar-signs -- needed in perl.

Be careful using this inside a new-command.  Gri
Recognizes the end of the body of a new-command by a line with @code{@}}
in the @strong{first column}, and no non-white characters thereafter.  
If you system command happens to use a line with a curly brace (as in a
loop in perl, for example), you must put whitespace before the brace.
This won't affect the system command, but it will let Gri correctly
realize that this is @strong{not} the end of the new-command.  For more
information on new-commands (@ref{Parsing}).

@strong{Caution:} Before sending the string to the system, Gri first
translates any synonyms present.  Be careful with this, since system
commands calling awk, etc, very often use backslashes for the newline
character @code{\n} within strings.  If you have a synonym whose name
starts with @code{\n}, you can get a conflict.  For example, the awk
command @code{print "foo\nbar";} should print a line with @code{foo} on
it, followed by a line with @code{bar} on it, but it will instead print
a single line with @code{fooMISTAKE}, if you had previously defined a
synonym as @code{\nbar = "MISTAKE"}.  One way to avoid this mistake is
to make sure any @code{\n} characters appear at the end of strings, and
then simply avoid having a synonym named @code{\n}.

Here is a Perl example.

@example
\m = "Foo bar"
system perl <<"EOF"
$a = 100;
print "foo bar is \m, and a is $a\n";
print "BETTER: foo bar is \m, and a is $a\n";
print "Q: was a 100?\n";
EOF
@end example

@end itemize


@strong{Some more examples}:
@itemize @bullet
@item
To get the first 15 lines of a file called @file{foo.dat} inserted into
another file called @file{bar.dat}, you might do the following.  Only
the first method works; the second will fail because @code{.n.} will not
be translated before passing to the operating system.

@example
\num = "-15"
system head \num foo.dat > bar.dat
# Following will not work correctly because .num. 
# will not be translated
.num. = -15
system head .num. foo.dat > bar.dat
@end example

@item
Issue a unix command to get a listing of files in the current
working directory, and pipe them into the @code{more} system command.

@example
system ls -l *c | more
@end example

@item
Store the date and time into a synonym, and use it in a
title:

@example
\time = system date
...
draw title "Plotted at time \time"
@end example

@item
Use @code{awk} to prepare a two-column table of x, ranging
from 0 to 1 in steps of 0.1, and sin(x).  The table is stored in a file
whose suffix is the process ID of the Gri job.  This file is then
opened, and the data plotted.  Finally, a system command is issued to
remove the temporary file.

@example
system awk 'BEGIN @{ \
    for (x=0; x<1; x+=0.1) @{ \
      printf("%f %f\n", x, sin(x)) \
    @} \
  @}'  > tmp.\.pid.
open tmp.\.pid.
read columns x y
close
system rm tmp.\.pid.
draw curve
@end example

@strong{Note}: in unix, this command calls the Bourne shell, not the C-shell
that is often used interactively.  For many simple uses, the only
difference from normal interactive use will be that @code{~} is not
expanded to the home directory.  For example, you should write

@example
system awk -f $HOME/foo/bar/cmd.gawk
@end example

@noindent
instead of the 

@example
system awk -f ~/foo/bar/cmd.gawk
@end example

@noindent
that you might expect from interactive C-shell use.
@noindent
RETURN VALUE:
@cindex @code{\.return_value.}, from @code{system ...}
Sets @code{\.return_value} to system status
@code{N status}
@end itemize



@c HTML <!-- newfile Unlink.html "Gri: `unlink' command" "Gri Commands" -->

@node   Unlink, While, System, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{unlink}
@cindex removing files with unlink
@cindex unlink, to remove files
@findex unlink
@cindex @code{unlink} command

@example
`unlink \filename'
@end example
@noindent 
Delete a filename and possibly the file to which it refers.  On
non-unix machines, this simply means to delete the file.  On unix
machines, the action is more subtle.  The unix OS permits several
processes to use a given file at once.  Therefore, @code{unlink}
doesn't immediately remove the file, but instead waits until other
processes are done with it.  Most users will never realize the
difference, however, and it is safe to think of @code{unlink} as
simply removing the file.  To learn more, type @code{man unlink} in a
unix shell.

A common use of @code{unlink} is to remove files that were created
with the @code{tmpname} facility (@ref{Using OS Inside Gri}), e.g.
@example
\tmp = tmpname
# do some system commands to put data into this file
open \tmp
read columns x y
draw curve
unlink \tmp
@end example



@c HTML <!-- newfile While.html "Gri: `while' command" "Gri Commands" -->

@node   While, Write, Unlink, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection @code{while}
@cindex loops
@findex while
@cindex @code{while} command

@example
`while .test.|@{rpn ...@}'
@end example

@noindent
Perform statements in loop while the value of @code{.test.} or the RPN
expression is nonzero.  The end of the loop designated by a line
containing the words @code{end while}.  The value @code{.test.} may be
an rpn expression.  To leave the loop prematurely, use a @code{break}
statement.  Upon encountering a @code{break} statement, Gri jumps to the
line immediately following the loop.  If the @code{-chatty} option is
nonzero, a notification is printed every 1000 passes through the loop,
as a debugging measure to catch unintended infinite loops.

@noindent
@strong{Examples}:

@itemize @bullet
@item
Loop forever, printing a message over and over.

@example
while 1
  show "This loops forever. Need to 'break'"
end while
@end example

@item
Read number pairs from a file, plotting bullets at 
the indicated locations.  Note the use of an infinite
loop, with a break condition following an
end-of-file test.  (Do not be tempted to write 
such loops as @code{while !..eof..} because that
would not catch the end of file until the next
time through the loop.  The result would be
to draw the last bullet twice, since the @code{read}
will not update the variables when the end of
file is encountered.)
@example
while 1
  read .x. .y.
  if ..eof..
    break
  end if
  draw symbol bullet at .x. .y.
end while

@end example
@item
Loop 10 times, printing the values of @code{.i.} as they range 0, 1,
@dots{}, 9.  After exiting from the loop, @code{.i.} will equal 10.  Be
@strong{careful} to use the correct rpn greater-than test to avoid an
infinite loop.

@example
.i. = 0
while @{rpn .i. 10 >@}
  show .i.
  .i. += 1
end while
@end example

@end itemize


@c HTML <!-- newfile Write.html "Gri: Write commands" "Gri Commands" -->

@node   Write, Write Columns, While, List Of Gri Commands
@comment  node-name,  next,  previous,  up
@subsection The @code{write} commands
@findex write
@cindex @code{write} command
The @code{write} commands write various things.
@cindex file, saving results into
@cindex save results in a file

If the filename is @file{stdout}, the information is written to the
standard output device (ie, the screen); if it is @file{stderr}, the
information is written to the standard error device (ie, the screen).

@strong{IMPORTANT NOTE}: The @code{write} commands @strong{append} to the
output file, as opposed to overwriting the contents of the file.
Therefore if you've run the Gri script before, and want fresh output,
make sure to do something like the following

@example
system rm -f the_grid.dat
write grid to grid.dat
@end example

@menu
* Write Columns::               Write columns to a file
* Write Contour::               Write contour (x,y) data to a file
* Write Grid::                  Write grid data to a file
* Write Image::                 Write various properties of image to a file
@end menu

@node   Write Columns, Write Contour, Write, Write
@comment  node-name,  next,  previous,  up
@subsubsection @code{write columns}
@cindex writing to a file, column data
@cindex column data, writing to a file
@cindex data in columns, writing to a file

@example
`write columns to \filename'
@end example

@noindent
Append data columns to the end of the indicated file.

@node   Write Contour, Write Grid, Write Columns, Write
@comment  node-name,  next,  previous,  up
@subsubsection @code{write contour}
@cindex writing to a file, contour data
@cindex contour data, writing to a file
@cindex data in contours, writing to a file

@example
`write contour .value. to \filename'
@end example

@noindent
Append to the named file the (x,y) pairs defining the contour of the indicated value.

The first line of output is a header line, containing two numbers: the
contour value and the missing value.  Then the (x,y) pairs are written a
line at a time, with missing values being used to indicate ends of
segments.  A blank line is written after the last data pair.  For
example, if the contour contained two closed regions, Gri would output a
pair of missing values as one of the xy pairs, to denote the separation
of the two curves.  You could read and plot the output as in this
example

@example
write contour 10 to contour.out
open contour.out
read .contour_value. .missing.
set missing value .missing.
read columns x y
draw curve
@end example

@node   Write Grid, Write Image, Write Contour, Write
@comment  node-name,  next,  previous,  up
@subsubsection @code{write grid}
@cindex writing to a file, grid data
@cindex grid data, writing to a file
@cindex data in grid, writing to a file
@cindex grid data, write to file

@example
`write grid to \filename [bycolumns]'
@end example

@noindent
Append grid to the end of the named file.  Storage is in @code{%f}
format, and is in normal image order.  If the keyword @code{bycolumns}
is present, then the grid is transposed first, in such a way that
@code{read grid data bycolumns} performed on that file will read back
the original grid data.

@node   Write Image, Programming, Write Grid, Write
@comment  node-name,  next,  previous,  up
@subsubsection @code{write image}
@cindex writing to a file, image data
@cindex image data, writing to a file
@cindex data in image, writing to a file

@example
`write image ... to \filename'
@end example

@noindent
The variants of this command write various things about the image to the
named file, as illustrated in the following table.

@itemize @bullet

@item @code{write image to image.dat}
@cindex image data, write to file
Append image to the end of the named file.  Storage is by unsigned-char,
and is in normal image order.  There is no header.

@item @code{write image rasterfile to image.dat}
Append image to the end of the named file, in Sun Rasterfile format.

@item @code{write image pgm to mask.dat}
Append image mask to the end of the named file, in PGM 'rawbits' format.

@item @code{write image mask to mask.dat}
@cindex image mask data, write to file
Append image mask to the end of the named file. Storage is by
unsigned-char, and is in normal image order.

@item @code{write image mask rasterfile to mask.dat}
Append image mask to the end of the named file, in Sun Rasterfile
format.

@item @code{write image mask pgm to mask.dat}
Append image mask to the end of the named file, in PGM 'rawbits' format.

@item @code{write image colorscale to colorscale.dat}
@cindex image palette data, write to file
Append image colorscale transform to the end of the named file.  Storage
is a series of 256 lines, each containing 3 numbers (for Red, Green and
Blue) in the range 0 to 1.  The file is suitable for reading with the
@code{read image colorscale} command.

@item @code{write image grayscale to grayscale.dat}
Append image grayscale transform to the end of the named file.  Storage
is a series of 256 lines, each containing a number in the range 0 to 1.
The file is suitable for reading with the @code{read image grayscale}
command.
@end itemize



@c HTML <!-- newfile Programming.html "Gri: programming" "Programming Gri" -->

@node   Programming, Defaults, Write Image, Top
@comment  node-name,  next,  previous,  up
@chapter Programming in the Gri Language
@cindex programming in Gri

The Gri programming language has @code{if} statements to control program
flow, and a @code{while} statement to repeat commands.  There are two
data types in Gri: ``variables'' (to store numbers) and ``synonyms'' (to
store character strings).  Gri recognizes commands by matching
statements against its list of known commands.  This list is extensible;
it is easy to add new commands as extensions to Gri.

@menu
* Defaults::                    How Gri normally acts
* Online Help::                 Getting help from gri itself
* Long Command Lines::          Continued lines
* Variables::                   Variables (for storing numbers) 
* Synonyms::                    Synonyms (for storing character strings) 
* If Statements::               If statements
* Loops::                       Repeating command lines
* Mathematics::                 Doing mathematics on columns, grids etc
* rpn Mathematics::             Doing mathematics on variables 
* Text::                        Doing things with characters strings 
* Adding New Commands::         How to customize Gri by adding new commands
* Missing Values::              How to specify missing data
* Hints::                       Hints for good Gri programming
* Debugging::                   Debugging Gri programs
* Error Messages::              What to do about Gri error messages
* Missing Values::              Missing value code
* Operating System::            Using Gri in OS and OS in Gri
* Resource File::               Personalizing Gri
@end menu


@c HTML <!-- newfile Defaults.html "Gri: defaults" "Programming Gri" -->

@node   Defaults, Online Help, Programming, Programming
@comment  node-name,  next,  previous,  up
@section Defaults
@cindex default values
At startup time, Gri sets the values of some things, like font size.
Since Gri is still under development, some of these defaults might
change, so you should not rely on them remaining the same.    Presently,
the defaults are equivalent to:

@example
set arrow size 0.2         # (cm)
set axes style 0
set beep off
set clip off
set clip postscript off
set contour format %lg
set contour label position ? ?
set contour labels horizontal
set contour labels whiteunder
set dash off
set font size 12           # (pt)
set font to helvetica
set graylevel 0            # Black ink
set ignore initial newline off
set input data window x off
set input data window y off
# Following set (curve, axes, symbol) widths to width
# of rapidograph pens called (6x0, 3x0,  6x0)
set line width 0.709        # (pt) for curves
set line width axis 0.369   # (pt) for axes
set line width symbol 0.369 # (pt) for symbols
set missing value 1.0e22
set page portrait
set page factor 1
set symbol size 0.1        # (cm)
set tic size 0.2           # (cm)
set tics out
set trace off
set x format %lg
set x margin 6.0           # (cm)
set x name "x"
set x size 10              # (cm)
set x type linear
set y axis name vertical
set y format %lg
set y margin 6.0           # (cm)
set y name "y"
set y size 10              # (cm)
set y type linear
@end example

@noindent
(NOTE: Programmers may alter the gri source file
@file{defaults.h} and then recompile Gri, if they feel the need to
change these things.  Also, see the file @file{startup.c} and the
function @code{gr_begin()} in @file{gr.c}.)


@c HTML <!-- newfile OnlineHelp.html "Gri: online help" "Programming Gri" -->

@node   Online Help, Long Command Lines, Defaults, Programming
@comment  node-name,  next,  previous,  up
@section Online Help
@cindex help, online
@cindex online help
Type @code{help} to get a list of available commands and other topics of
interest. Here's how Gri responds

@example
Type `help' followed by a command-name:
 assert      cd            close         convert
 create      debug         delete        differentiate
 draw        expecting     filter        flip
 get         help          if            ignore
 input       insert        interpolate   list
 ls          mask          move          new
 open        pwd           query         quit
 read        regress       reorder       rescale
 resize      return        rewind        set
 show        skip          sleep         smooth
 source      sprintf       state         superuser
 system      write
Or type `help -' followed by a topic from this list:
 example     extending     files         math
 strings     synonyms      variables     manual
@end example

Some commands have more words than shown.  You can type these additional
words to narrow the help down; otherwise Gri will give you help
on all commands that begin with the indicated words.  For example, try
@code{help set} and @code{help set x}.  When you ask for help on a
multi-word command, Gri tells you about all commands which begin
with the words you've typed.  Thus,

@example
help
help draw
help draw zero
help draw zero line
@end example

@noindent 
narrow in on the command @code{draw zero line}.  The response to the
most complete request is

@example
`draw zero line [horizontally|vertically]'
  draw zero line
    Draw line y=0 if it is within axes
  draw zero line horizontally
    Draw line y=0 if it is within axes
  draw zero line vertically
    Draw line x=0 if it is within axes
@end example

The part enclosed in angled quotes is the syntactical description of the
command.  (NOTE: The square brackets indicate an optional word (in this
case) or words.  The vertical bar indicates that either the item on the
left or the item on the right may appear; it is a logical OR operator.
The only other special characters in syntax descriptions are the braces
@code{@{@}}, which are used to enclose multiple words which act as one
unit; they are used to clarify the choices presented to the OR
operator.)  Following the syntactical description are examples.  Each
example is indented 2 spaces, and a description of it (which always
starts with an upper-case character and ends with a period, to indicate
that it is an English description) follows that, indented by an
additional 2 spaces.


@c HTML <!-- newfile LongCommandLines.html "Gri: long command lines" "Programming Gri" -->

@node  Long Command Lines, Variables, Online Help, Programming
@comment  node-name,  next,  previous,  up
@section Long Command Lines

@cindex continued lines
@cindex commands extending over several lines

To extend a command across several lines, use a backslash @code{\} at
the @strong{very} end of all lines but the last:

@example
draw line from \
  10 20 \
  to \
  10 30
@end example



@c HTML <!-- newfile Variables.html "Gri: variables" "Programming Gri" -->

@node   Variables, About Variables, Long Command Lines, Programming
@comment  node-name,  next,  previous,  up
@section Variables
@cindex numbers, stored in variables
@cindex variables
@cindex programming, variables

@menu
* About Variables::             What variables are used for, and how
* User Variables::              Defining your own variables
* Built-in Variables::          Variables pre-defined by Gri
@end menu

@node   About Variables, User Variables, Variables, Variables
@comment  node-name,  next,  previous,  up
@subsection About variables
Variables store numbers.  As it reads your program, Gri 
substitutes variable values any place a variable appears where a number
normally would.  For example, in the code below @code{.number.} is a
variable storing the value 10, so the two @code{read} statements have
the same effect:

@example
.number. = 10
read columns .number. x y
read columns 10 x y
@end example

Variable names begin and end with a single period (example:
@code{.num.}).  (Gri uses this odd notation to distinguish variable
names from ``normal'' words, which is necessary because Gri does not
have a limited list of keywords as other languages do.  Thus, the C
programming language is happy to let you use a variable name like
@code{latitude}, since it is not a keyword, but Gri is not, since it
might like to use that word itself in a new command.)

You should not use names beginning and ending with double periods,
because Gri uses names like that to store built-in variables for its own
use (e.g., @code{..xsize..} saves the width of the plot).

To store a number into a variable, use a command like

@example
.time. = 10
@end example

@noindent
or

@example
.time. = @{rpn 10 sin@}
@end example

Storage is automatically set aside when you assign into a nonexistent
variable; no ``declaration'' statements are required as in the C
language.

The Gri command, @code{new} (@ref{New}), allows you to have several
``versions'' of a variable.  This is useful for local storage in new
commands, inside @code{if} statements, etc, since it lets you use
temporary variables without worrying about overwriting values outside
the local block of code.  The syntax is @code{new .variable. = value}
(where, as usual, @code{value} may be an rpn expression 
(@ref{rpn Mathematics}).  Here is an example:

@example
`foo bar'
@{
  new .a.         # Get storage
  .a. = 10        # Store a local value
  show "Locally, .a.=" .a. " (expect 10)"
  delete .a.      # Delete this local one
@}
.a. = 1
show "Global version has .a.=" .a. " (expect 1)"
foo bar
@end example

To see if a given named variable (or synonym) exists, use the RPN
operator @code{defined} (@ref{rpn Mathematics}).


@node   User Variables, Built-in Variables, About Variables, Variables
@comment  node-name,  next,  previous,  up
@subsection User variables
@cindex variables, defined by user
@cindex user-defined variables
You can get Gri to read values for variables from your file.  Here's how
to read a number from a header line and then read that many lines of
columnar data:

@example
open file.dat
read .num.
read columns .num. x y
@end example

You can define variables within the Gri program:

@example
.num. = 10
read columns .num. x y
@end example

@cindex interaction with user, @code{query} command
You can get variables interactively from the user, using the
@code{query} command.  (If the user types carriage-return, or if the
command-line flag @code{-y} was specified when invoking Gri, the value
100 will be assigned to @code{.num.}).
For example, 

@example
query .num. "Number of rows to read?" (100)
read columns .num. x y
@end example

Gri allows you to use a previous value of the variable in the default
string, as in this example:

@example
.start. = 8                             # default
.stop. = 2                              # default
query .start. "Start time? " (.start.)
query .stop.  "Stop time?  " (.stop.)
@end example

Variables can be manipulated using reverse polish notation (RPN)
mathematical operations (@ref{rpn Mathematics}).

Variables are often useful in @code{if} statements.  Here are some
examples:

@example
read .num_pts.
if .num_pts.
  show "There are some data"
  read columns .num_pts. x y
else
  show "There are no data"
end if
# ...
read .latitude.
if @{rpn .latitude. 10 <@}
  read .num.
  read .num. x y
  draw curve
else
  show "Skipping data North of 10deg N"
  read .num.
  skip .num.
end if  
@end example


@node   Built-in Variables, Synonyms, User Variables, Variables
@comment  node-name,  next,  previous,  up
@subsection Built-in variables
@cindex variables, built-in
@cindex built-in variables
Built-in variables (@ref{Index of Builtins}) have names which begin and
end with @strong{two} periods.  For example, @code{..xsize..} is the width
of the x-axis in centimetres.  You may use these variables as you wish
(example: @code{..xsize.. = 4} is an alternative to 
@code{set x size 4}), but you must be aware that these are not ``free''
variables for you to use for arbitrary purposes.  You can find out what
the built-in variables are by the command @code{show variables}.

There are two types of variables
@itemize @bullet
@item
@strong{Startup} variables, which are created by Gri at startup time.
These variables can be relied upon to exist (barring changes in Gri
itself), unless you @code{delete} them.
@item
@strong{Spontaneous} variables (which are created by certain Gri commands,
and only exist if these commands have been executed).  For example, the
@code{regress} command defines @code{..coeff0..} (the intercept of the
fitted line), @code{..coeff1..} (the slope of the fitted line),
@code{..R2..} (the correlation coefficient).
@end itemize

To see the values of the built-in variables (along with the user
variables), use @code{show variables}.  Here are some useful builtin
variables: 

@itemize @bullet

@item @code{..arrowsize..}
@cindex arrows, size of heads stored in @code{..arrowsize..}
@vindex @code{..arrowsize..}, size of arrows
Stores either a positive number representing the halfwidth of arrowheads
measured in centimetres, or a negative number giving the negative of the
ratio of arrowhead halfwidth to arrow length (@ref{Set Arrow Size}).

@item @code{..batch..}
@cindex batch processing
@vindex @code{..batch..}, flag used for batch mode
Flag used for batch mode.

@item @code{..debug..}
@vindex @code{..debug..}, flag used for debugging
@cindex debug command-line option
@cindex debugging, using @code{..debug..}
Equal to 1 if the @code{-debug} command-line flag was set.  Flag used
for debugging (@ref{Invoking Gri}).  The @code{..debug..}
built-in variable is useful in isolating code to use only in test runs.
For example, you might use

@example
if ..debug..
  show "Following are the column data"
  show columns 
end if
@end example

When you run the program with command-line @code{gri -debug file.gri}
the code in the @code{if} block will print out the columnar data, but
when you run it with @code{gri file.gri} these lines are not printed.

@item @code{..eof..}
@vindex @code{..eof..}, flag indicating end-of-file
Flag indicating whether an end-of-file was encountered on the last
@code{read columns}.

@item @code{..words_in_dataline..}
@vindex @code{..words_in_dataline..}
@cindex reading data, checks
@cindex data files, words in lines
Number of words on last dataline.  This is useful in constructs like

@example
open tmp.dat
.num. = 0
while 1
  read .a. .b.
  if !..words_in_dataline..
    show "Got empty line or EOF, so break loop"
    break
  end if
  show "a=" .a. "b=" .b.
  show "; words in line=" ..words_in_dataline..
  .num. += 1
end while
show "Got " .num. "data lines."
@end example


@item @code{..fontsize..}
@cindex font, size
@vindex @code{..fontsize..}, size of letters
Size of letters, measured in points; there are 72.27 points in an inch
and 28.45 points in a centimetre.  The mathematical operators
@code{pttocm} and @code{cmtopt}, which do conversion between points and
centimetres, are often useful in labelling data curves 
(@ref{rpn Mathematics}).

@item @code{..graylevel..}
@cindex gray level
@vindex @code{..graylevel..}, graylevel (0=black)
Graylevel to use in drawing lines, text, etc.  Black ink is 0; white
paper is 1.  @strong{See also} @code{..red..} etc.

@item @code{..image_height..}
@vindex @code{..image_height..}, height of image
Height of image, or 0 if no image defined yet.

@item @code{..image_width..}
@vindex @code{..image_width..}, width of image
Width of image, or 0 if no image defined yet.

@item @code{..length_dash..}
@vindex @code{..length_dash..}, length/cm of dashes
Length in cm of dashes in dashed lines.

@item @code{..length_blank..}
@vindex @code{..length_blank..}, length/cm of blanks
Length in cm of blanks in dashed lines.

@item @code{..linewidth..}
@vindex @code{..linewidth..}, width of lines
Width of lines for data curves (@ref{Set Line Width}).

@item @code{..linewidthaxis..}
@vindex @code{..linewidthaxis..}, width of lines on axis
Width of lines on axes (@ref{Set Line Width}).

@item @code{..linewidthsymbol..}
@vindex @code{..linewidthsymbol..}, width of lines in symbols
Width of lines in symbols (@ref{Set Line Width}).

@item @code{..missingvalue..}
@vindex @code{..missingvalue..}, missing value code
Missing value code, also stored in the synonym @code{\.missingvalue.};
(@ref{Set Missing Value}).

@item @code{..num_col_data..}
@vindex @code{..num_col_data..}, number column data
Number of column data that exist.  You might want to use this after
@code{read columns} to see if a data file actually had any data in it,
or use it in accessing individual elements of columns 
(@ref{rpn Mathematics}).

@item @code{..publication..}
@cindex publication quality plots, built-in variable @code{..publication..}
@vindex @code{..publication..}, flag for final copy of plot
Flag for final copy of plot.  The command-line option @code{-p} sets the
value of @code{..publication..} to 1.  A typical, and highly
recommended, code fragment is

@example
if !..publication..
  draw time stamp
end if
@end example


@item @code{..red..}, @code{..green..}, @code{..blue..}
@vindex @code{..blue..}
Description of present color.  The values are between 0 and 1, with
(0,0,0) being black and (1,1,1) being white.  If color is gray, all
these will be equal.  You may assign to these, but it will @strong{not}
change the color.

@item @code{..symbolsize..}
@cindex symbol size, stored in @code{..symbolsize..}
@vindex @code{..symbolsize..}, size of symbols
Size of symbols in centimetres.

@item @code{..superuser..}
@vindex @code{..superuser..}, was -superuser flag set?
Equal to 0 if the flag was not set, or equal to the flag if it was.

@item @code{..tic_direction..}
@vindex @code{..tic_direction..}, direction of axis tics
Direction of axis tics, 1 for inside or 0 for outside.

@item @code{..tic_size..}
@vindex @code{..tic_size..}, size/cm of axis tics
Size of axis tics in centimetres.

@item @code{..trace..}
@vindex @code{..trace..}, for tracing program execution
Equal to 1 if the @code{-trace} command-line flag was set.  Used for
tracing program execution.

@item @code{..xinc..}
@vindex @code{..xinc..}, x increment on axes
x increment on axes.

@item @code{..xleft..}
@vindex @code{..xleft..}, x value at left of plot
x value at left of plot.

@item @code{..xmargin..}
@cindex margins
@vindex @code{..xmargin..}, left margin
Left margin, in centimetres.

@item @code{..xright..}
@vindex @code{..xright..}, x value at right of plot
x value at right of plot.

@item @code{..xsize..}
@cindex length of axes
@cindex axes, length of
@vindex @code{..xsize..}, x-axis length
x-axis length in centimetres.

@item @code{..ybottom..}
@vindex @code{..ybottom..}, y value at bottom of plot
y value at bottom of plot.

@item @code{..yinc..}
@vindex @code{..yinc..}, y increment on axes
y increment on axes.

@item @code{..ymargin..}
@vindex @code{..ymargin..}, bottom margin
Bottom margin in centimetres.

@item @code{..ysize..}
@vindex @code{..ysize..}, y-axis length
y-axis length in centimetres.

@item @code{..ytop..}
@vindex @code{..ytop..}, y value at top of plot
y value at top of plot

@item @code{..exit_status..}
@vindex @code{..exit_status..}, exit status from @code{system} call
The exit status from the most recent @code{system} call (or 0 if no
system calls have been done yet).
@end itemize





You may use any of these built-in variables anywhere.  For example,
here's how to stack 3 graphs vertically on the page:

@example
.offset. = @{rpn ..ysize.. 3 + @}
open file1
read columns x y
close
draw axes
draw curve 

..ymargin.. += .offset.
open file2
read columns x y
draw axes 
draw curve 
close

..ymargin.. += .offset.  
open file3 
read columns x y 
draw axes 
draw curve 
close
@end example

@cindex mathematics, rpn notation, example
The first line needs a bit of explanation. It is a reverse-polish
expression.  The format is @code{@{} followed by @code{rpn} followed by
an expression followed by @code{@}}.  Within the expression, spaces must
separate operands.  This makes @code{.offset.} equal to the height of
y-axis plus 3 cm, so plots are separated by 3 cm.  To learn more about
@code{@{rpn ... @}} (@ref{rpn Mathematics}).

Another possibly unfamiliar thing is the code @code{+=}.  It means take
the thing on the left hand side, and add to it the thing on the right
hand side.  (In this case, it is used to increase the y margin by the
value of @code{.offset.}.)


@c HTML <!-- newfile Synonyms.html "Gri: synonyms" "Programming Gri" -->

@node   Synonyms, Naming Convention, Built-in Variables, Programming
@comment  node-name,  next,  previous,  up
@section Synonyms
@cindex character variables (synonyms)
@cindex synonyms, for storing character strings
@cindex programming, synonyms
@cindex synonyms, naming convention
Synonyms are used by Gri to store character strings.  Gri denotes
synonyms with words beginning with backslash (e.g., @code{\syn}),
following the @TeX{} convention.  

@menu
* Naming Convention::             Their names with a backslash, e.g. @code{\syn}
* Using Synonyms::                Some usage examples
* Important Builtin Synonyms::    e.g. @code{\.command_file.}
* Alias Synonyms::                e.g. @code{\@@alias}
* Local Synonyms::                Working with the arguments of newcommands
@end menu


@node   Naming Convention, Using Synonyms, Synonyms, Synonyms
@comment  node-name,  next,  previous,  up
@subsection Naming convention for synonyms
@cindex naming convention for synonyms 
@cindex synonyms, naming convention

Synonym names begin with a backslash (e.g., @code{\filename}).  After
the backslash, Gri expects a letter (upper or lower case) or one or more
periods.  Following this is an arbitrary string of letters, numbers, or
underscores.  If there are periods at the start, then the same number of
periods must be used at the end.  The following are some examples
@example
\simple = "Howdie"
\.longer_example. = "Dots and underscores are ok too"
\a2 = "OK for number at end ..."
\a3bb = "... and inside"
@end example

Gri defines several synonyms for its own use, so that if you modify
these, you may get strange results.  Each of these starts and ends with
a single period.

There is an exception to the above rule, one which mostly comes up when
using netCDF files which may have variable names that may contain
punctuation.  Gri permits synonym names to have punctuation characters
(but not blanks or tabs) in synonym names, provided that the second
character in the name is an opening brace and that the last character is
a closing brace, e.g.

@example
\@{foo.bar@} = "Foo bar"
@end example

@noindent  This is used particularly for files in the netCDF format,
for reading variable attributes, which by netCDF convention use a colon
(@code{:}) to separate variable name and attribute name (@ref{Read
Synonym or Variable}).  For more information on netCDF format, see

@code{http://www.unidata.ucar.edu/packages/netcdf/index.html}
@c HTML <a href="http://www.unidata.ucar.edu/packages/netcdf/index.html">
@c HTML here </a>.

Synonyms may be freely embedded in strings (a common example is
@code{draw title "Data from file `\datafile'"}.  They may also appear
anywhere in commands (e.g., @code{open \filename}).  The exception to
this rule is that Gri ignores your synonyms within math mode, in order
to prevent clashes (e.g. you might define @code{\alpha} as a synonym
storing the value @code{"foo bar"}, but Gri will ignore this within
math-mode, so that @code{$\alpha$} will still mean the Greek letter
alpha).

To get a backslash in a string without Gri thinking it is part of a
synonym, use two backslashes (e.g., 
@code{show "The backslash character \\ is used for synonyms."}).  This
may sometimes be required in 
@code{system}
commands (@ref{System}), to prevent Gri from converting
substrings like @code{\n} (which many system commands use to represent
the newline character).  For example, the command 
@code{system perl -e 'print "foo\nbar";'} will be mangled if Gri has
already been told that
@code{\nbar} is a synonym.  (There will be no problem if @code{\nbar} is
not an existing synonym, since Gri will then just leave it in place.)
To be sure that no mangling can occur, replace each backslash with two
backslashes.  This tells Gri not to try to substitute a synonym at that
location.  In the example below, the first system call prints
@code{fooled you!} on one line line, because Gri substituted for what it
thought was a synonym called @code{\nbar}; the second (correctly) prints
@code{foo} on one line and @code{bar} on the next.
@cindex @code{system} command, how to get a tab
@cindex @code{system} command, how to get a newline
@cindex tab, in a @code{system} command
@cindex newline, in a @code{system} command

@example
\nbar = "led you!"
system perl -e 'print "foo\nbar\n";'
system perl -e 'print "foo\\nbar\\n";'
@end example

Similarly, if your system command is expecting to see @code{\t} (for a
tab character), then you must write @code{\\t} to prevent Gri from
trying to substitute a synonym named @code{\t}.

The @code{show} command has a special syntax for permitting newlines and
tabs in strings (@ref{Show}).


@node   Using Synonyms, Generalizing Code, Naming Convention, Synonyms
@comment  node-name,  next,  previous,  up
@subsection Some uses for synonyms
@cindex character variables (synonyms)
@cindex synonyms, extracting individual words from
@cindex synonyms, assigning values to
@cindex synonyms, constructing using the operating system
@cindex user-defined synonyms
@cindex synonyms, for storing output from system commands
@cindex operating system commands, assigned to synonyms
@cindex system commands, assigned to synonyms
@cindex operating system, example of using to construct filenames
@cindex system commands, example of using to construct filenames
@cindex filenames, constructing using the operating system

Synonyms store strings and are useful for anything strings are useful
for, e.g. filenames, plot labels, names of variables, etc.

@menu
* Generalizing Code::
* Storing OS Output::
* Storing User Responses::
* Storing File Contents::
* Extracting Words From Strings::
@end menu

@node   Generalizing Code, Storing OS Output, Using Synonyms, Using Synonyms
@comment  node-name,  next,  previous,  up
@subsubsection Using synonyms to generalize code

Synonyms are often used to store filenames, since then only a single
line of a file may need to be altered, in order to work with another
file, e.g.

@example
\filename = "columns.dat"
open \filename
# a lot more code using the file name
@end example


@node   Storing OS Output, Storing User Responses, Generalizing Code, Using Synonyms
@comment  node-name,  next,  previous,  up

@subsubsection Using synonyms to store OS output
Synonyms provided a convenient way to store information from the OS.

@example
# Show the date.
\date = system date
show "Time is \date"

# Show the command file name, then use the system
# to construct a filename with the same beginning
# but ".dat" as the ending instead of ".gri".
show "The commandfile name is \.command_file."
\fn = system echo `basename \.command_file. .gri`.dat
show "A filename constructed from this is \fn"
@end example

This example uses the Unix system commands @code{echo} and
@code{basename} to  construct a filename ending in @file{.dat}, from the
command file name (stored in the builtin string @code{\.command_file.}),
assuming that the command file name ends in @file{.gri}.

NOTE: As usual, if the system command contains the Gri comment
designator (the string @code{#}), protect it with double-quotes
(@ref{System}).


@node   Storing User Responses, Storing File Contents, Storing OS Output, Using Synonyms
@comment  node-name,  next,  previous,  up

@subsubsection Storing user responses via @code{query}

You can ask the user for the contents of strings:
@cindex interaction with user, @code{query} command

@example
query \filename "What's the data file?" ("file.dat")
@end example

@noindent
The prompt @code{What's the name of the data file?} is typed to the
terminal, and whatever string the user types is inserted into the
synonym @code{\filename}. If the user types nothing, but simply presses
carriage return, the (optional) default string (which must be enclosed
in parentheses as shown) is put into @code{\filename}. Note that the
default is ignored if it is not written properly: it must be enclosed in
double quotes enclosed in parentheses, with no intervening spaces.


@node   Storing File Contents, Extracting Words From Strings, Storing User Responses, Using Synonyms
@comment  node-name,  next,  previous,  up

@subsubsection Storing File Contents
You can read the contents of synonyms from a file:

@example
open \directory_file
read \file_name
close
open \file_name
read columns x y
@end example

@noindent
The first (space-separated) word is read into the the first synonym after
the @code{read} command, the second word into the second synonym, and so on.
If the word you want is not near the front of the line, you can use the command 
@code{read line} to get the whole line, then use the method described above 
to extract the word you want.  Indexing begins with 0, remember.


@node   Extracting Words From Strings, Important Builtin Synonyms, Storing File Contents, Using Synonyms
@comment  node-name,  next,  previous,  up

@subsubsection Working with words within strings

Sometimes a synonym will contain several words that you need to work
with indidually (e.g. it might contain a list of files that should be
processed).  There are two ways to do this.

@table @emph


@item The @code{word of} syntax.
@example
\sentence = "This sentence has five words"
\first_word = word 0 of "\sentence"
\last_word = word 4 of "This sentence has five words"
@end example


@item The @code{[]} syntax
@cindex @code{[]} syntax for selecting words in synonyms
Individual words of synonyms may be accessed by prefixing the synonym
name with the index number of the word (starting at 0) enclosed in
square brackets.  

The number in the square brackets may be a constant, a variable, or a
synonym, but not a more complicated expression.  If the index value is a
floating-point number, it is first rounded to the nearest integer.  If
the index value is negative or exceeds the number of words minus 1, then
an empty string is retrieved.

If @strong{no number} appears in the square brackets, the result is the
number of words in a synonym.

@example
\syn = "This has 4 words in it"
show "\[0]syn   ... gives 'This'"
show "\[1]syn   ... gives 'has'"
.i. = 3
show \[.i.]syn  ... gives 'words'"
\i = "3"
show \[\i]syn   ... gives 'words'"
show "\[]syn    ... gives '6', i.e. number of words"
@end example

@end table




@node   Important Builtin Synonyms, Alias Synonyms, Extracting Words From Strings, Synonyms
@comment  node-name,  next,  previous,  up
@subsection Some important builtin synonyms
@cindex synonyms, global
@cindex global synonyms
@cindex built-in synonyms, global
@cindex global built-in synonyms
@cindex synonyms, built-in, list of
@cindex return value, @code{\.return_value.}
@vindex @code{\.return_value.}, Return value
@vindex @code{\.ps_file.}, PostScript file name
@vindex @code{\.readfrom_file.}, data file name
@vindex @code{\.command_file.}, command-file name
@vindex @code{\.missingvalue.}, command-file name
@vindex @code{\.home.}, home directory
@vindex @code{\.system.}, operating system name
@vindex @code{\.user.}, user's login name
@vindex @code{\.time.}, time and date
@cindex directory, stored in synonym @code{\.wd.}
@cindex working directory, stored in synonym @code{\.wd.}
@cindex @code{\.wd.} synonym, storing working directory
@vindex @code{\.wd.}, working directory
@vindex @code{\.version.}, version of Gri
@vindex @code{\.pid.}, process ID of job
Within mathematics mode (portions of strings enclosed within
dollar-signs), Gri stores the definitions of many Greek letters and
mathematical symbols as math-mode synonyms (@ref{Mathematical Text}).

Global synonyms are shared among commands.  To see the built-in global
synonyms (@ref{Index of Builtins})
use @code{show synonyms}, which
produces output that looks something like the following.

@example
Synonyms...
    \.missingvalue.           = "10000000000000000000000.000000"
    \.return_value.           = ""
    \.version.                = "2.7.0"
    \.pid.                    = "3043"
    \.wd.                     = "/home/kelley"
    \.time.                   = "Sun May 20 13:18:32 2001"
    \.user.                   = "kelley"
    \.host.                   = "Intrusion.phys.ocean.dal.ca"
    \.system.                 = "unix"
    \.home.                   = "/home/kelley"
    \.lib_dir.                = "/usr/share/gri"
    \.command_file.           = "stdin"
    \.readfrom_file.          = "stdin"
    \.ps_file.                = "gri-00.ps"
    \.path_data.              = "."
    \.path_commands.          = "."
@end example

@cindex time
@cindex date
@cindex @code{\.return_value.}, general
These things will be obvious to unix users; for example
@code{\.pid.} is the process ID of the job (often used in names for
temporary files), and @code{\.wd.} is the working directory (often used
in @code{draw title} commands to indicate in which directory the gri job
was run.  

Some commands set @code{\.return_value.} to non-blank; the
meaning of the return value varies from command to command.





@node   Alias Synonyms, Local Synonyms, Important Builtin Synonyms, Synonyms
@comment  node-name,  next,  previous,  up
@subsection Alias synonyms: the @code{\@@alias} syntax
@cindex alias synonyms, with the @code{\@@alias} notation
@cindex @code{\@@alias} notation
@cindex synonyms, aliasing with the @code{\@@alias} notation

Sometimes you need to work with a variable or a synonym whose name can
only be determined at run-time, perhaps through interaction with the
user, examination of a datafile, or examination of the command provided
to the OS when invoking Gri.

Gri handles this by so-called "alias" synonyms, which store the names of
other items.

The syntax is simple.  Suppose that a synonym, called @code{\pointer}
say, contains the @strong{name of} another synonym, or a variable.  Then
you may use @code{\@@pointer} anyplace you would normally use the item
named.

@table @emph

@item Illustrations of using the value of a named item
The following prints an approximation to Pi followed by the name of
movie star.
@example
.pi. = 3.14
\pi_pointer = ".pi."
show \@@pi_pointer  # just like 'show .pi.'

\hero = "Gregory Peck"
\our_hero = "\\hero"
show "\@@our_hero"  # just like 'show "\hero"'
@end example


@item Illustrations of assigning to a named item
The following prints an approximation to 2*Pi and yet another star; the
point is that the alias appears to the left of an assignment operator.
@example
# Print approximation to 2*Pi
.pi. = 3.14
\pi_pointer = ".pi."
\@@pi_pointer *= 2
show .pi.

# Stars don't shine alone
\hero = "Gregory Peck"
\our_hero = "\\hero"
\@@our_hero = "Harrison Ford"
show "\hero"
@end example

@end table



@node   Local Synonyms, If Statements, Alias Synonyms, Synonyms
@comment  node-name,  next,  previous,  up
@subsection Local synonyms
@cindex synonyms, local
@cindex local synonyms
@vindex @code{\.proper_usage.}
@vindex @code{\.words.}
@vindex @code{\.word0.}
@vindex @code{\.word1.}
@cindex built-in synonyms, local
@cindex local built-in synonyms
@cindex command lines, parsing in new Gri commands
@cindex programming, parsing command lines
@cindex programming, using local built-in synonyms
Local synonyms are created by Gri upon entry to a Gri command.  You use
them to parse the command line that was used in calling the new command,
to look for options, gather filenames, etc.  Local synonyms are known
only from within the local Gri command.  They are not listed by
@code{show synonyms}, but they can be used freely in commands like
@code{show "Number of words is \.words."}.

@itemize @bullet
@item
Within any new Gri command, the number of words in the line that called
the command is available in @code{\.words.}.  The RPN operator @code{wordc} 
also yields the same value (@ref{Solitary Operators}).
@item
The first word in the calling line is @code{\.word0.}, the second
@code{\.word1.}, etc.  (Note that this is the C convention, @strong{not} the
FORTRAN convention.  If @code{\.words.} is 2, then @code{\.word0.} and
@code{\.word1.} are defined, but @code{\.word2.}, which FORTRAN programmers
expect, will not be defined.)  If you don't know the place of the synonym
in advance (i.e. 0 versus 1, for @code{\.word0.} versus @code{\.word1.}), 
then use the RPN operator @code{wordv} instead (@ref{Unary Operators}).
@item
Within any new Gri command, the proper calling usage is available in
@code{\.proper_usage.}.  This is useful in tests of syntax 
(@ref{Adding New Commands}).  For example:

@example
`draw depths from \file'
Draw depth data stored in indicated file.  If the 
filename contains periods or slashes, you'll
have to enclose it in double quotes, as
in the second example:
  draw depths from file upper_cove
  draw depths from file ../old_data/upper_cove
@{
  if @{rpn \.words. 4 !=@}
    show "FATAL ERROR in `\.proper_usage.':"
    show "  Need 4 words; got \.words. words."
    quit
  end if
  # Right number of words, so continue onward...
@}
@end example

@end itemize
These synonyms help you scan for optional words in commands.  Suppose
you have defined a new command @code{New Thing [option]}.  If you call
it with @code{New Thing}, then (within @code{New Thing}) @code{\.words.}
will be @code{"2"}, @code{\.word0.} will be @code{"New"} and @code{\.word1.}
will be @code{"Thing"}.  On the other hand, if you call it with
@code{New Thing 22.3} then @code{\.words.} will be @code{3},
@code{\.word0.} will be @code{"New"}, @code{\.word1.} will be
@code{"Thing"} as before, and @code{\.word2.} will be @code{"22.3"}.

@strong{EXAMPLE}  Here is a new command to label lines drawn by 
@code{draw curve}: 

@example
`Draw Label For Last Curve "label"'
Draw a label for the last curve drawn, using
..xlast.. and ..ylast.. built-in variables.
@{
  new .draw_label_for_last_curve_graylevel.
  .draw_label_for_last_curve_graylevel. = ..graylevel..
  set graylevel 0
  draw label "\.word5." at \
      @{rpn ..xlast.. xusertocm 0.1 + xcmtouser@} \
      @{rpn ..ylast.. yusertocm \
          ..fontsize.. pttocm 2 / -
          ycmtouser@}
  set graylevel .draw_label_for_last_curve_graylevel.
  delete .draw_label_for_last_curve_graylevel.
@}
open file.dat
read columns x y
draw curve
\label = "Illustration"
Draw Label For Last Curve "\label"
@end example

@noindent
(Note that Gri has a built-in command 
@code{draw label for last curve "\label"} written much as above, so
there is no need for you to enter 
this new command into your @file{.grirc} file.  But you might want to
check @file{gri.cmd} to see how a full
command does checking of the calling syntax
(@ref{Invoking Gri}).


@c HTML <!-- newfile IfStatements.html "Gri: if statements" "Programming Gri" -->

@node   If Statements, Loops, Local Synonyms, Programming
@comment  node-name,  next,  previous,  up
@section If Statements
@cindex programming, if statements
@cindex if statements
Gri has @code{if} statements to make your programs more flexible.
Here's an example:
@cindex interaction with user, @code{query} command

@example
query \thick "Use thick lines? (0 or 1)" ("0")
if \thick
  set line width 2
else
  set line width 0.5
end if
@end example

@noindent
If you answer 1 to the question, the line thickness will be set at 2
points.  If you answer 0 then a thin line will be used.  If you press
carriage return a thin line will be used.

The item following the @code{if} can be 
@itemize @bullet
@item
a number (1 means true; anything else means false)
@item
a variable (1 means true; anything else means false). Example:

@example
if .plot_contours.
  draw contour
end if
@end example

@item
a synonym which expands to a number (1 means true; anything else means
false). Example:

@example
\plot_contours = "1"
if \plot_contours
  draw contour
end if
@end example

(Don't worry about the fact that synonyms are strings; Gri
expands the string value before interpreting the @code{if} statement.)
@item
an expression of the form @code{@{string1 == string2 @}}.  The symbol
@code{==} is an operator which tests for string equality.  This expands
to @code{1} if the strings are equal, or @code{0} otherwise.  The
strings may be either synonyms or string constants.  If the string
constant contains only one word, then it is not necessary to enclose it
in quotes, but it is clearer to do so.  Examples:
@cindex labels, on axes

@example
if @{"\variable" == "Salinity"@}
  set x name "Salinity"
else 
  set x name "Unknown"
end if
@end example

@item
a rpn (reverse polish notation) expression 
(@ref{rpn Mathematics}):

@example
if @{rpn .time. 100 <@}
  # ie, (100 < time), not (time < 100)
  show "Time > 100"
else if @{rpn .time. 100 >@}
  show "Time < 100"
else if @{rpn "\item" "later" ==@}
  show "Time ... later babe"
else
  show "Time is equal to 100"
end if
if @{rpn .time. 10 * 100 ==@}
  show "Time is equal to 10"
else
  show "Time is not equal to 10"
end if
@end example

@end itemize

There is no need to put the else part in if you don't need it. You
can do

@example
set line width 0.5
if \use_thick_lines
  set line width 2
end if
@end example

@noindent
if you wish.

If you want just the else part, you can do

@example
if ! \use_thick_lines
  set line width 0.5
end if
@end example

(The exclamation point denotes logical negation: @code{! true} equals
@code{false}.)

If statements may be nested many levels deep.  You may also have
@code{else if} blocks, as in:

@example
if @{"\variable" == "S"@}
  set x name "Salinity"
  set x axis 32 33 0.5 .1
else if @{"\variable" == "T"@}
  set x name "Temperature"
  set x axis 15 20 1 0.5
else
  set x name "Unknown"
end if
@end example


@c HTML <!-- newfile Loops.html "Gri: Loops" "Programming Gri" -->
@node   Loops, Mathematics, If Statements, Programming
@comment  node-name,  next,  previous,  up
@section Loops
Gri provides only one type of loop, the @code{while} loop, described
elsewhere (@ref{While}).


@c HTML <!-- newfile Mathematics.html "Gri: Mathematics" "Programming Gri" -->

@node   Mathematics, rpn Mathematics, Loops, Programming
@comment  node-name,  next,  previous,  up
@section Mathematics
Gri lets you do some simple mathematical manipulations on your
column and grid data.

@subsection Column data
@cindex column mathematics
@cindex mathematics, on columns
@cindex powers, of columns or variables
@cindex exponentiation
@cindex logarithms
The column operators are @code{=}, @code{+=}, @code{-=}, @code{*=},
@code{/=}, @code{^=} (exponentiation) and @code{_=} (logarithm).  There
must be spaces before and after the operators, but no space between the
2 letters of the operators. The operations may be applied not only to
@code{x} and @code{y} as shown, but also to @code{z} (used to hold data
to be contoured or written as symbols), and @code{u} and @code{v} (used
to store vector fields).

The axis scales are @strong{not} changed by mathematical operations on the
columns, regardless of whether the scales were set manually or by Gri
command (@ref{Axis Scaling}).

Elements of columns are available by the @code{@@} reverse polish
operator (@ref{rpn Mathematics}).

Examples:
@itemize @bullet
@item
To multiply all the x data by 10, use @code{x *= 10}; to add 5 to each
y-value, use @code{y += 5}.
@item
To set all the y data to 10, do @code{y = 10}.  (This will only work if
you've already read column data.)
@end itemize

See also @ref{Tertiary Operators} for a method of assigning or altering column data
using the RPN operator.

@subsection Grid data
@cindex grid data mathematical operations
@cindex mathematics, on grid data
Various commands let you alter grid data as used in contouring
(@ref{Contour Plots}).  Possible commands are as follows.

@example
grid data = number
grid data += number
grid data -= number
grid data *= number
grid data /= number
grid data ^= number # take data to power 'number'
grid data _= number # take log base 'number'
grid x = number
grid x += number
#... others as in `grid data'
grid y = number
grid y += number
#... others as in `grid data'
@end example


@subsubsection Image data
@cindex image mathematical operations
@cindex mathematics, on images
Various commands let you alter image data (@ref{Images}.).
Possible commands are as follows.

@example
image += number
image -= number
image *= number
image /= number
image ^= number # power
image _= number # logarithm
@end example

@subsubsection Image grayscale/colorscale
@cindex colorscale modification
@cindex grayscale modification
@cindex image grayscale/colorscale modification
@cindex mathematics, on image grayscale/colorscale
Various commands let you alter image data (@ref{Images}).
Possible commands are as follows.

@example
image grayscale += number
image grayscale  -= number
image grayscale  *= number
image grayscale  /= number
image grayscale  ^= number # power
image grayscale  _= number # logarithm
image colorscale += number
image colorscale  -= number
image colorscale  *= number
image colorscale  /= number
image colorscale  ^= number # power
image colorscale  _= number # logarithm
@end example

@subsubsection Variables
@cindex scalar operations
@cindex mathematics, on variables
Possible commands are:

@example
.variable. = number
.variable. += number
.variable. -= number
.variable. *= number
.variable. /= number
.variable. ^= number # power
.variable. _= number # logarithm
@end example


@c HTML <!-- newfile ReversePolishMath.html "Gri: Reverse Polish Mathematics" "Programming Gri" -->

@page

@node   rpn Mathematics, Stack Operators, Mathematics, Programming
@comment  node-name,  next,  previous,  up
@section Rpn (reverse-polish notation) Calculator
@cindex examples of @code{rpn} mathematics
@cindex @code{rpn} mathematics, examples
@cindex mathematics, @code{rpn} notation, description
Gri can do simple mathematics on numbers.  The syntax is reverse-polish
notation (@code{rpn}), which is used in some calculators.  Most users
can learn rpn in a few minutes, so don't worry if you don't know RPN
yet.

@strong{Syntax}: rpn expressions can be used anywhere Gri expects a number.
RPN expressions start with a opening curly brace (@code{@{}) which is
immediately followed by the word @code{rpn}.  rpn expressions end with a
closing curly brace (@code{@}}).  Instead of @code{set x size 10} you
could write @code{set x size @{rpn 20 2 /@}}, where the expression
@code{@{rpn 20 2 /@}} tells Gri to insert the number 20 onto a stack,
then insert the number 2 above it on the stack, and then divide the top
two items on the stack.  The following are equivalent:

@example
set x size @{rpn 20 2 /@}           # 10 = 20/2
set x size @{rpn 30 2 / 5 -@}       # 10 = (30/2-5)
set x size @{rpn pi 3.1415 / 10 *@} # 10 = 10*pi/pi
@end example

If an rpn expression contains a variable whose value is ``missing'',
then the value of the result of the expression will also be missing
(unless the value of the missing variable is thrown away with a
``pop'' operator).  However, if a missing value just happens to occur
as the result of an intermediate calculation, then the result is not
considered to be missing.

RPN operations can be divided roughly into the following groups.

@menu
* Stack Operators::             Operate on the rpn stack
* Rpn Functions::               Define a new rpn operator
* Tertiary Operators::          Act on top three items on stack
* Binary Operators::            Act on top two items on stack
* Unary Operators::             Act on top item on stack
* Solitary Operators::          Act alone
* Manipulation of Columns etc:: Act on data columns
* rpn Examples::                A few examples
@end menu

@c HTML <!-- newfile StackOperators.html "Gri: RPN stack operators" "Programming Gri" -->

@node   Stack Operators, Rpn Functions, rpn Mathematics, rpn Mathematics
@comment  node-name,  next,  previous,  up
@subsection Stack Operators
@cindex @code{pop} rpn stack operator
@cindex rpn stack operator @code{pop}
@cindex @code{dup} rpn stack operator
@cindex rpn stack operator @code{dup}
@cindex @code{exch} rpn stack operator
@cindex rpn stack operator @code{exch}
@cindex @code{roll_left} rpn stack operator
@cindex rpn stack operator @code{roll_left}
@cindex @code{roll_right} rpn stack operator
@cindex rpn stack operator @code{roll_right}
@cindex @code{pstack} rpn stack operator
@cindex rpn stack operator @code{pstack}

Stack operators manipulate or display the stack.  

@code{pop} removes the top item from the stack (@ref{Unary Operators}).

@code{dup} duplicates the top item on the stack (@ref{Unary Operators}).

@code{exch} reorders the top two items on the stack (@ref{Binary Operators}).

@code{pstack} prints the items on the stack (without changing the
stack).

@code{roll_right} rolls the items to the right.

@code{roll_left} rolls the items to the left.

For example, the following shows how you might use @code{exch} or
@code{roll_right} to change the sense of a subtraction.

@example
show @{rpn 1 2            -@} " ... yields -1"
show @{rpn 1 2 exch       -@} " ... yields  1"
show @{rpn 1 2 roll_right -@} " ... yields  1"
@end example



@c HTML <!-- newfile RpnFunction.html "Gri: RPN functions" "Programming Gri" -->

@node   Rpn Functions, Tertiary Operators, Stack Operators, rpn Mathematics
@comment  node-name,  next,  previous,  up
@subsection Rpn function Operators
@code{rpnfunction} operators are user-defined operators.  The parser
replaces any such operator with the user-defined rpn expression.  The
@code{rpnfunction} operators are both general and powerful.  An
@code{rpnfunction} may be composed of any legal primitive rpn constructs
or even other legal @code{rpnfunction} constructs.  For details,
(@ref{Rpnfunction}).


@c HTML <!-- newfile TertiaryOperators.html "Gri: tertiary operators" "Programming Gri" -->

@node   Tertiary Operators, Binary Operators, Rpn Functions, rpn Mathematics
@comment  node-name,  next,  previous,  up
@subsection Tertiary Rpn Operators
@table @code


@item @{rpn 0 4 "hello" substr @}
@cindex RPN operator @code{substr}
@cindex substrings, getting with RPN operator @code{substr}
@cindex @code{substr} RPN operator
Extract 4 characters from the indicated string, starting at character
number 0 (i.e. the start of the string).  In other words, replace the
three items on the top of the stack with the single item
@code{\"hell\"}.
@end table


@c HTML <!-- newfile BinaryOperators.html "Gri: RPN binary operators" "Programming Gri" -->

@node   Binary Operators, Unary Operators, Tertiary Operators, rpn Mathematics
@comment  node-name,  next,  previous,  up
@subsection Binary Operators

@cindex binary operators in rpn expressions
@cindex logical operators in rpn expressions
@cindex comparison operators in rpn expressions
@cindex @code{<} comparison operator in rpn expressions
@cindex @code{>} comparison operator in rpn expressions
@cindex @code{==} comparison operator in rpn expressions
@cindex mathematical operators in rpn expressions
@cindex conversion between user and page units
@cindex page units, converting to user units
@cindex user units, converting to page units
@cindex larger of two numbers, rpn operator @code{sup} 
@cindex smaller of two numbers, rpn operator @code{inf}
@cindex rpn operator @code{sup}, finds larger of pair
@cindex rpn operator @code{inf}, finds smaller of pair
@cindex @code{sup} rpn operator, finds larger of pair
@cindex @code{inf} rpn operator, finds smaller of pair

Binary operators act on the @strong{top two} items on the stack.  Most
binary operators replace two items on the stack with one item, e.g.
@code{@{rpn 1 2 /@}} yields 0.5.  However, a few binary operators
replace one pair of items with a new pair of items, e.g. the
@code{xyusertocm} operator replaces an (x,y) pair in user coordinates
with an (xcm,ycm) pair in coordinates of centimeters on the page.

The binary operators are illustrated below, in rough alphabetical order.

@table @code

@item @{rpn 3 2 +@}
@cindex @code{+} rpn operator
@cindex rpn operator @code{+}
Add 2 to 3.

@item @{rpn 3 2 -@}
@cindex @code{-} rpn operator
@cindex rpn operator @code{-}
Subtract 2 from 3.

@item @{rpn 3 2 *@}
@cindex @code{*} rpn operator
@cindex rpn operator @code{*}
Multiply 3 by 2.

@item @{rpn 3 2 /@}
@cindex @code{/} rpn operator
@cindex rpn operator @code{/}
Divide 3 by 2.

@item @{rpn 3 2 <@}
@cindex @code{<} rpn operator
@cindex rpn operator @code{<}
@cindex HP calculators, RPN notation different from
@cindex RPN notation, difference from old-series HP calculators

Test whether 2 is less than 3, yielding 1.  Note: this convention may
be confusing to users who are familiar with HP calculators from
decades past.  Present-day calculators use this convention, but
possibly older calculators used the reverse convention, using @code{>}
where Gri uses @code{<}.


@item @{rpn 3 2 <=@}
@cindex @code{<=} rpn operator
@cindex rpn operator @code{<=}
Test whether 2 is less than or equal to 3.


@item @{rpn 3 2 >@}
@cindex rpn operator @code{>}
Test whether 2 is greater than 3, yielding 0.


@item @{rpn 3 2 >=@}
@cindex @code{>=} rpn operator
@cindex rpn operator @code{>=}
Test whether 2 is greater than or equal to 3, yielding 0.


@item @{rpn 3 2 ==@}
@cindex rpn operator @code{==}
Test whether 2 and 3 are equal, yielding 0.  (Do not confuse this with
the asignment operator @code{=}, described next.)


@item @{rpn 10 ".ten." =@}
@cindex @code{=} rpn operator assigns to variables, synonyms, and columns
@cindex rpn operator @code{=}
@cindex assigning to columns, variables and synonyms within RPN expressions
@cindex variables, assigning within RPN expressions
@cindex synonyms, assigning within RPN expressions
@cindex columns, assigning within RPN expressions
@cindex column dat, assigning within RPN expressions

Assign the value @code{10} to the variable named @code{.ten.}.  The
variable name must be put in quotes, or else Gri will insert the value
of the variable (if it exists) into the expression, instead of trying
to assign to it.

After the assignment is done, the stack is cleared of both the value and
the variable name.  For example, in the following code
@example
@{rpn 3.1415 ".pi." =@}
show .pi.
@end example
the first line evaluates to a blank line, and the second prints the value of Pi.

NOTE: Do not confuse this with the @code{==} equality operator
described above.

@item @{rpn "hello" "\\greeting" =@} 
Assign the value @code{"hello"} to the synonym @code{\greeting}.  See
notes at the above item.

@item @{rpn 3.14159 0 "x" =@}
Assign the value Pi to the first element (at index @code{0}) 
of the @code{x} column.  All columns may be assigned to in this way, e.g.
the following is a technique for plotting a quadratic function:
@example
.i. = 0
.n. = 10
while @{rpn .i. .n. >@}
    @{rpn .i. .n. 1 - /     .i. "x" =@}
    @{rpn x .i. @@ 2 power  .i. "y" =@}
    .i. += 1
end while
draw curve
@end example

@item @{rpn 0 1 &@}
@cindex @code{&} rpn operator
@cindex rpn operator @code{&}
Test whether 0 and 1 are both true, yielding 0.

@item @{rpn 0 1 and@}
@cindex @code{and} rpn operator
@cindex rpn operator @code{and}
Test whether 0 and 1 are both true, yielding 0.

@item @{rpn y x area@}
Calculate the area under the curve y=y(x).  For details
(@ref{Manipulation of Columns etc}).

@item @{rpn 0 1 |@}
@cindex @code{|} rpn operator
@cindex rpn operator @code{|}
Test whether either 0 or 1 is true, yielding 1.

@item @{rpn 0 1 or@}
@cindex @code{or} rpn operator
@cindex rpn operator @code{or}
Test whether either 0 or 1 is true, yielding 1.

@item @{rpn 2 3 exch@}
@cindex @code{exch} rpn operator
@cindex rpn operator @code{exch}
Exchange 2 and 3 on the stack, yielding @code{3 2} on the stack.  (See
also @code{pop} and @code{dup}.)


@item @{rpn x 0 @@@}
@cindex @code{@@} rpn operator, for accessing columnar data
Yields the value of the first number in the x column.  A similar form
also works for @code{y}, etc.  (@ref{Manipulation of Columns etc}).


@item @{rpn 2 3 inf@}
@cindex @code{inf} rpn operator
@cindex rpn operator @code{inf}
Pick the smaller of two values, yielding 3.  (Opposite to @code{sup}.)


@item @{rpn 2 3 power@}
@cindex @code{power} rpn operator
@cindex rpn operator @code{power}
@cindex HP calculators, RPN notation different from
@cindex RPN notation, difference from old-series HP calculators
Take 2 to the 3rd power, yielding 8.  Note: This convention may be
confusing to users who are familiar with HP calculators from decades
past.  Present-day calculators use this convention, which they write as
@code{y^x}, but older calculators used the reverse convention, labelling
the key @code{x^y}.



@item @{rpn 2 3 remainder@}
@cindex @code{remainder} rpn operator
@cindex rpn operator @code{remainder}
Calculate the remainder after dividing 2 by 3, yielding 2.  The return value
for @code{@{rpn A B remainder@}} is @code{B - n * A}, where @code{n} is
the quotient of @code{A/B}, rounded towards zero to an integer.  In this
case, @code{2/3} rounds to an @code{n} value of zero, yielding 2 as the
resulting remainder.


@item @{rpn "heLLo" "s/L/l/g" sed@}
@cindex @code{sed} rpn operator
@cindex rpn operator @code{sed}
Switch all instances of @code{L} into @code{l}, yielding the string
@code{"hello"} on the stack.  This can be helpful for working with
filenames, etc.  The work is preformed with a system call to the
@code{sed} utility (present on unix systems), and therefore this
command will fail if @code{sed} is not installed, or if the OS cannot
be contacted.


@item @{rpn "file" ".dat" strcat@}
@cindex @code{strcat} rpn operator
@cindex rpn operator @code{strcat}
Concatenate the two strings, yielding the string @code{"file.dat"}.


@item @{rpn 2 3 sup@}
@cindex @code{sup} rpn operator
@cindex rpn operator @code{sup}
Pick the larger of two values, yielding 3.  (Opposite to @code{inf}.)

@end table


@c HTML <!-- newfile UnaryOperators.html "Gri: RPN unary operators" "Programming Gri" -->

@node   Unary Operators, Solitary Operators, Binary Operators, rpn Mathematics
@comment  node-name,  next,  previous,  up
@subsection Unary Operators
@cindex rpn, system calls
@cindex rpn, conversion of string to number
@cindex system calls in rpn expressions
@cindex string, conversion to number in rpn expressions
@cindex conversion, string to number, in rpn expressions
@cindex checking for missing value in rpn expressions
@cindex missing value, checking for in rpn  expressions

Unary operators replace the last item on the stack with another item.
For example, the @code{sin} operator takes the sine of the number on the
top of the stack; e.g., @code{@{rpn 45 sin@}} yields the sine of 45 degrees.

The unary operators are illustrated below, in rough alphabetical order.

@table @code

@item @{rpn 0 !@}
@cindex @code{!} rpn operator
@cindex rpn operator @code{!}
@cindex logical negation, @code{!} rpn operator
@cindex negation, @code{!} rpn operator
Replace 0 (false) with its logical negation 1 (true).

@item @{rpn 0 not@}
@cindex @code{not} rpn operator
@cindex rpn operator @code{not}
@cindex logical negation, @code{not} rpn operator
@cindex negation, @code{not} rpn operator
Replace 0 (false) with its logical negation 1 (true).

@item @{rpn -3 abs@}
@cindex @code{abs} rpn operator
@cindex rpn operator @code{abs}
Calculate the absolute value of @code{-3}.


@item @{rpn 0.5 acos@}
@cindex @code{acos} rpn operator
@cindex rpn operator @code{acos}
Calculate the inverse cosine of 0.5, yielding 60 (degrees).

@item @{rpn 2 acosh@}
@cindex @code{acosh} rpn operator
@cindex rpn operator @code{acosh}
Calculate the inverse hyperbolic cosine of 2, yielding 1.317.  (Note:
argument must equal or exceed 1, or an error results.)

@anchor{age-rpn-operator} 
@item @{rpn "filename" age@}
@cindex makefiles, emulating action with the @code{age} rpn operator
@cindex file age, determined with the @code{age} rpn operator
@cindex @code{age} rpn operator
@cindex rpn operator @code{age}
Calculate the ``age'' of the indicated file, in seconds.  An age of
zero indicates that the file was created, or last modified, within 1
second of the execution of the @code{age} operator.


On unix (and similar) machines, the calculation is done on unix
machines with the @code{stat()} subroutine.  On other machines, the
@code{age} operator may cause an error.

The age of a non-existent file is reported as the number of seconds
since the system clock's reference time, i.e. since 1970-jan-1 on unix
machines.  This convention is so that scripts like that in the example
below will work as intended.

A typical use of this command is the creation of data-files from shell
scripts, as illustrated below.  The idea is to update (or create) the
file @file{file.dat} using the system-executable script
@file{creator.pl}, but only to do so if @file{creator.pl} is younger
than @file{file.dat}.
@example
if @{rpn "file.dat" age "creator.pl" age <@}
   system "./creator.pl > file.dat"
end if
open file.dat
@end example
For the convenience in such usage, a non-existent file is assigned the
maximum possible file age on the given OS, e.g. on a unix machine, the
age is reported as though the non-existent file had been created on
January 1, 1970 on a unix machine.


@item @{rpn 0.5 asin@}
@cindex @code{asin} rpn operator
@cindex rpn operator @code{asin}
Calculate the inverse sine of 0.5, yielding 30 (degrees).


@item @{rpn 1 atan@}
@cindex @code{atan} rpn operator
@cindex rpn operator @code{atan}
Calculate the inverse tangent of 1, yielding 45 (degrees).


@item @{rpn 0.5 atanh@}
@cindex @code{atan} rpn operator
@cindex rpn operator @code{atan}
Calculate the inverse hyperbolic tangent of 0.5, yielding 0.549306
(radians).


@item @{rpn 0 argv@}
@cindex @code{argv} rpn operator, access commandline arguments
@cindex arguments on command line, accessing with @code{argv} rpn operator
@cindex commandline arguments, accessing with @code{argv} rpn operator
Returns the name of the Gri command-file, which is considered as the first
"optional" argument.  (It may seem odd that the name of the command-file
is considered an option, but Gri does this for consistency with C and
other languages.  It is useful.)  Other arguments provided when Gri
was invoked are provided as @code{rpn 1 argv}, etc.

A string consisting of a single blank character results if one tries to
access beyond the list of arguments that were actually supplied.  See
also the @code{argc} solitary operator (@ref{Solitary Operators}), which
returns the number of optional arguments.

For example, if Gri is invoked as

@example
gri myscript.gri file1.dat file2.dat
@end example

@noindent
and if @file{myscript.gri} contained

@example
.n. = @{rpn argc@}
.i. = 0
while @{rpn .n. .i. <@}
    show "argument " .i. " is " @{rpn .i. argv@}
    .i. += 1
end while
@end example

@noindent
then the output would be

@example
argument 0 is myscript.gri
argument 1 is file1.dat
argument 2 is file2.dat
@end example

For usage within the Emacs gri-mode, see 
@ref{Filename arguments when running gri}.


@item @{rpn "hi" ascent@}
@cindex @code{ascent} rpn operator
@cindex rpn operator @code{ascent}
Determine ascent of this string (in cm), in the present font and
fontsize.  (See also @code{descent} and @code{width}.)


@item @{rpn "3.1" atof@}
@cindex @code{atof} rpn operator
@cindex rpn operator @code{atof}
Calculate the numerical value contained in indicated string.


@item @{rpn 1.5 ceil@}
@cindex @code{ceil} rpn operator
@cindex rpn operator @code{ceil}
Calculate the next higher integer, yielding 2.  (Opposite of @code{floor}.)


@item @{rpn 45 cos@}
@cindex @code{cos} rpn operator
@cindex rpn operator @code{cos}
Calculate the cosine of 45 degrees, yielding 0.707.


@item @{rpn 1 cosh@}
@cindex @code{cosh} rpn operator
@cindex rpn operator @code{cosh}
Calculate the hyperbolic cosine of 1 (radian), yielding 1.543.


@item @{rpn 1 cmtopt@}
@cindex @code{cmtopt} rpn operator
@cindex rpn operator @code{cmtopt}
Convert from 1 centimeter to so-called ``point'' units, yielding 28.45.
(Opposite of @code{pttocm}.)

@item @{rpn 170 dec2hex@}
@cindex converting decimal values to hexadecimal strings
@cindex hexadecimal, converting to from decimal
Convert a number into a string which is its hexadecimal
representation.  Before the conversion, the number is rounded to the
nearest integer, and if the result is negative, an error results.  The
string is double-quoted, with letters (if there are any) being in
upper case.  

For example
@code{\hex = @{rpn  63  dec2hex@}}
is equivalent to
@code{\hex = "3F"}.

Compare with @code{hex2dec}, the inverse.

@item @{rpn "\\syn" defined@}
@cindex testing for existence of a synonym
@cindex synonyms, checking for existence of
@cindex existence of a synonym, testing
Test whether the synonym is defined at the moment, returning 1 if
so and 0 if not.  (Note the double-backslash in the synonym name, which
is required.)


@item @{rpn ".var." defined@}
@cindex existence of a variable, testing
@cindex testing for existence of a variable
@cindex variables, checking for existence of
Test whether the variable is defined at the moment, returning 1 if
so and 0 if not.


@item @{rpn "\\@@alias" defined@}
@cindex testing for existence of an aliased synonym
@cindex alias synonyms, checking for existence of
@cindex existence of an alias synonym, testing
Test whether the variable/synonym item that is named by the alias
(@ref{Alias Synonyms}) is defined at the moment, returning 1 if so and 0
if not.




@item @{rpn "hi" descent@}
@cindex @code{descent} rpn operator
@cindex rpn operator @code{descent}
Calculate the descent (below the baseline in cm) for the given string,
in the present font and fontsize.  (See also @code{ascent} and
@code{width}.)


@item @{rpn "/home/me/data/timeseries" directory_exists@}
@cindex @code{directory_exists} rpn operator
@cindex file permissions, testing with @code{file_exists} and @code{directory_exists}
@cindex rpn operator @code{directory_exists}
Determine whether indicate directory exists, yielding @code{1} if it does
and @code{0} otherwise.  (See also @code{file_exists}.)


@item @{rpn 2 dup@}
@cindex @code{dup} rpn operator
@cindex rpn operator @code{dup}
Duplicate the top item on stack, yielding @code{2 2} on the stack.
(See also @code{exch} and @code{pop}.)


@item @{rpn 1 exp@}
@cindex @code{exp} rpn operator
@cindex rpn operator @code{exp}
Calculate the value of @code{e} raised to the indicated power, yielding 2.71828.


@item @{rpn 2 exp10@}
@cindex @code{exp10} rpn operator
@cindex rpn operator @code{exp10}
Calculate the value of @code{10} raised to the indicated power, yielding 100.


@item @{rpn "foo.dat" file_exists@}
@cindex @code{file_exists} rpn operator
@cindex rpn operator @code{file_exists}
Determine whether the indicate file exists, yielding @code{1} if it does
and @code{0} otherwise.  (See also @code{directory_exists}.)


@item @{rpn 1.5 floor@}
@cindex @code{floor} rpn operator
@cindex rpn operator @code{floor}
Calculate the nearest smaller integer, yielding 1.  (Opposite of
@code{ceil}.)


@item @{rpn "AA" hex2dec@}
@cindex converting hexadecimal strings to decimal values
@cindex hexadecimal, converting to decimal
Convert a string, representing a hexadecimal value, into an integer.
The string must be double-quoted, and it may contain either lower- or
upper-case letters; this is in contrast to the inverse function,
@code{dec2hex}, which returns upper-case.  

This operator is most often used in working with colours, since Gri
handles colour components in decimal terms, whereas many other
applications refer to the components in hexadecimal notation.

Compare with @code{dec2hex}, the inverse.


@item @{rpn 3 ismissing@}
@cindex @code{ismissing} rpn operator
@cindex rpn operator @code{ismissing}
Yields 1 if the indicated value is a ``missing value'' or 0 otherwise. 


@item @{rpn 100 log@}
@cindex @code{log} rpn operator
@cindex rpn operator @code{log}
Calculate the base-10 logarithm of 100, yielding 2.


@item @{rpn 10 ln@}
@cindex @code{ln} rpn operator
@cindex rpn operator @code{ln}
Calculate the natural logarithm of 10, yielding 2.30259.


@item @{rpn x mean@}
Yields the mean value of the (non-missing) numbers in the x column.  A
similar form also works for @code{y}, etc. 
(@ref{Manipulation of Columns etc}).


@item @{rpn x max@}
Yields the largest value of the (non-missing) numbers in the x column.  A
similar form also works for @code{y}, etc. 
(@ref{Manipulation of Columns etc}).


@item @{rpn x min@}
Yields the smallest value of the (non-missing) numbers in the x column.  A
similar form also works for @code{y}, etc. 
(@ref{Manipulation of Columns etc}).


@item @{rpn 28.45 pttocm@}
@cindex @code{pttocm} rpn operator
@cindex rpn operator @code{pttocm}
Calculate the number of centimeters in 28.45 printers points, yielding 1.
(Opposite of @code{cmtopt}.)


@item @{rpn 1 2 pop@}
@cindex @code{pop} rpn operator
@cindex rpn operator @code{pop}
Remove the top item from the stack, yielding @code{1} on the stack.
Generates an error if the stack is empty.  (See also @code{exch} and
@code{dup}.)


@item @{rpn 4 sqrt@}
@cindex @code{sqrt} rpn operator
@cindex rpn operator @code{sqrt}
Calculate the square root of 4, yielding 2.  (Negative arguments yield
errors.)


@item @{rpn 45 sin@}
@cindex @code{sin} rpn operator
@cindex rpn operator @code{sin}
Calculate the sine of 45 (degrees), yielding 0.707107.


@item @{rpn 2 sinh@}
@cindex @code{sinh} rpn operator
@cindex rpn operator @code{sinh}
Calculate the hyperbolic sine of 2, yielding 3.62686.


@item @{rpn "hello" strlen@}
@cindex @code{strlen} rpn operator
@cindex rpn operator @code{strlen}
Determine the number of characters in string, including the quotation
marks, e.g. 7 here.


@item @{rpn "date" system@}
@cindex @code{system} rpn operator
@cindex rpn operator @code{system}
Call the indicated system function and insert its ouput on the stack,
yielding the date as a character string.


@item @{rpn 45 tan@}
@cindex @code{tan} rpn operator
@cindex rpn operator @code{tan}
Calculate the tangent of 45 (degrees), yielding 1.


@item @{rpn tanh@}
@cindex @code{tanh} rpn operator
@cindex rpn operator @code{tanh}
Calculate the hyperbolic tangent of 2, yielding 0.964028.


@item @{rpn "hi" width@}
@cindex @code{width} rpn operator
@cindex rpn operator @code{width}
Determine width of this string (in cm), in the present font and fontsize.
(See also @code{ascent} and @code{descent}.)


@item @{rpn 0 wordv@}
@cindex RPN operator @code{wordv}
@cindex @code{wordv} RPN operator
Returns the first word used in invoking the present command.  Similar
to the @code{\.word0.} synonym (@ref{Local Synonyms}).  Example:

@example
`let us test .it.'
@{
  .w. = 0
  while @{rpn .w. wordc >@}
    show "The " .w. "-th word is `" @{rpn .w. wordv@} "'."
    .w. += 1
  end while
@}
let us test "this thing"
let us test "this" "thing"
let us test "Pi is" @{rpn 3.14@}
@end example

If you are using this to parse options given to the command, it is up to
you to skip the non-optional words in the command.  In this case, for
example, we skipped the first three words (@code{let}, @code{us}, and
@code{test}).


@item @{rpn 1 xusertocm@}
@cindex @code{xusertocm} rpn operator
@cindex rpn operator @code{xusertocm}
Calculate the x coordinate, in centimeters measured from left-hand side of
page, corresponding to a user-value of x=1.  (Opposite of
@code{xcmtouser}.)


@item @{rpn 1 xcmtouser@}
@cindex @code{xcmtouser} rpn operator
@cindex rpn operator @code{xcmtouser}
Calculate the x value, in user units, for a point that is 1 centimeter from
the left-hand edge of the paper.  (Opposite of @code{xusertocm}.)


@item @{rpn 1 yusertocm@}
@cindex @code{yusertocm} rpn operator
@cindex rpn operator @code{yusertocm}
Calculate the y coordinate, in centimeters measured from bottom side of
page, corresponding to a user-value of x=1.  (Opposite of
@code{ycmtouser}.)


@item @{rpn 1 ycmtouser@}
@cindex @code{ycmtouser} rpn operator
@cindex rpn operator @code{ycmtouser}
Calculate the y value, in user units, for a point that is 1 centimeter from
the bottom edge of the paper.  (Opposite of @code{yusertocm}.)


@end table







@c HTML <!-- newfile SolitaryOperators.html "Gri: RPN solitary operators" "Programming Gri" -->

@node   Solitary Operators, Manipulation of Columns etc, Unary Operators, rpn Mathematics
@comment  node-name,  next,  previous,  up

@subsection Solitary Operators
@cindex rpn operator @code{argc}, yielding number of commandline arguments
@cindex @code{argc} rpn operator, yielding number of commandline arguments

Solitary operators do not act on items on the stack; rather, they
generate items themselves and insert them on the stack.

The solitary operators are illustrated below, in alphabetical order.

@table @code

@item @{rpn argc@}
Yields number of command-line arguments given by the user when Gri was
invoked.  Thus, invoking Gri as

@example
gri myfile.gri file1.dat file2.dat
@end example

@noindent
yields 3, for arguments @file{myfile.gri}, @code{file1.dat},
and @code{file2.dat}.  These arguments are accessible through
the @code{argv} unary operator (@ref{Unary Operators}).


@item @{rpn e@}
@cindex e, base of natural logarithms, in RPN expressions
Yields the base of natural logarithms, i.e. @code{2.718}...


@item @{rpn pi@}
@cindex pi, in RPN expressions
Yields Pi, i.e. @code{3.141}...


@item @{rpn rand@}
@cindex RPN operator @code{rand}
@cindex @code{rand} RPN operator
@cindex random numbers, generating in RPN expressions
Generate a random number in the range 0 to 1, using the C subroutine
@code{drand48()} if it is available, otherwise the less well-distributed
@code{rand()} subroutine.


@item @{rpn wordc@}
@cindex RPN operator @code{wordc}
@cindex @code{wordc} RPN operator
Returns number of words used in invoking the present command.  Similar
to the @code{\.words.} synonym (@ref{Local Synonyms}).  Example:

@example
`let us test .it.'
@{
  show "This command has " @{rpn wordc@} " words"
@}
let us test 10
let us test @{rpn 3 1 +@}
let us test "this"
let us test "this thing"
@end example

The operator @code{wordv} may be used to extract the words of the
command (@ref{Unary Operators}).
@end table



@c HTML <!-- newfile ManipulatingColumns.html "Gri: RPN column manipulation" "Programming Gri" -->

@node   Manipulation of Columns etc, rpn Examples, Solitary Operators, rpn Mathematics
@comment  node-name,  next,  previous,  up

@subsection Manipulation of Columns etc

@subsubsection Columns
@cindex column data, accessing individual values and stats
@cindex standard deviation, column data
@vindex @code{..num_col_data..}, number column data



Individual data in the @code{x}, @code{y}, @code{z}, @code{u}, @code{v}
and @code{weight} columns can be accessed with the @code{@@} operator.
The first point has index 0.  Examples:

@example
show "first x is " @{rpn x 0 @@ @}
show "last  x is " @{rpn x ..num_col_data.. 1 - @@ @}
show "and here are all the data:"
.i. = 0
while @{rpn .i. ..num_col_data.. >@}
    show @{rpn x .i. @@ @}
    .i. += 1
end while
@end example


@cindex maximum, column data
@cindex minimum, column data
@cindex statistics, column data
@cindex column data, statistics
@cindex mean, calculating for column data
@cindex standard deviation, calculating for column data
@cindex skewness, calculating for column data
@cindex kurtosis, calculating for column data
The mean value is available from the @code{mean} operator (e.g.,
@code{.xmean. = @{rpn x mean @}}, while the standard deviation is given
by @code{stddev}, the skewness is given by @code{skewness},
and the kurtosis is given by @code{kurtosis} (using the definition
that yields 3 for a gaussian distribution).

The minimal and maximal values are given by
@code{min} and @code{max}.

@cindex @code{area} rpn operator
@cindex rpn operator @code{area}
@cindex area under curve
The area under the curve y=y(x) is found by @code{@{rpn y x area @}},
defined by
@ifinfo
@code{0.5 * sum ( (y[i] + y[i-1]) * (x[i] - x[i-1]) )}
for @code{i} ranging from 1 to @code{..num_col_data..}-1.
@end ifinfo
@tex
${1}\over{2} \left( \sum_1^{n-1} (y_i + y_{i-1}) (x_i - x_{i-1}) \right)$
for data with $i$ ranging $0$--$..num\_col\_data..-1$
@end tex

@subsubsection Grid
@cindex grid data -- accessing individual values and stats
@cindex maximum, grid data
@cindex minimum, grid data
@cindex grid data -- minimum, maximum, mean

Grid data can be accessed with e.g. @code{@{rpn grid min @} },
@code{@{rpn grid max @} }, and @code{@{rpn grid mean @} }.

@cindex rpn operator @code{interpolate}
@cindex grid, interpolating to given (x,y) value
@cindex  interpolating grid to given (x,y) value
The value of the grid at a given @code{(.x.,.y.)} coordinate may be
found by by e.g. @code{@{rpn grid .x. .y. interpolate@}}.  The
interpolation scheme is the same as that used in converting grids to
images.


@c HTML <!-- newfile RPNexamples.html "Gri: RPN examples" "Programming Gri" -->

@node   rpn Examples, Text, Manipulation of Columns etc, rpn Mathematics
@comment  node-name,  next,  previous,  up
@subsection rpn Examples

Here are some reverse-polish expressions and the corresponding algebraic
interpretations:

@itemize @bullet

@item @code{@{rpn 1 2 + 10 / @}}
= (1+2)/10       

@item @code{@{rpn .a. .b. + .c. + .d. / @}}
= (.a.+.b.+.c.)/.d.

@item @code{@{rpn e 2 / @}}
= e/2 (Gri knows values of ``e'' and ``pi'')

@item @code{@{rpn 23 sin 100 * 12 cos + @}}
= cos(12) + 100sin(23)

@item @code{@{rpn 5 2 power @}}
= 25

@item @code{@{rpn 2 log exp @}}
= exp(log 2)

@item @code{@{rpn 2 ln exp10 @}}
= 10^ln2

@item @code{@{rpn 1.7 floor @}}
= 1 (rounds down to nearest integer.  Note that the floor of -1.7 is -2)

@item @code{@{rpn 10.1 2 remainder @}}
= 0.1 (remainder of 10.1 after division by 2; see C function @code{remainder(x,y)})

@item @code{@{rpn -10.1 2 remainder @}}
= -0.1

@item @code{@{rpn -10.1 -2 remainder @}}
= -0.1

@item @code{@{rpn .num. 10 > @}}
= 1 if 10 exceeds .num., or 0 otherwise
@end itemize

@noindent
NOTES:
@itemize @bullet
@cindex trigonometric operations in rpn math
@cindex mathematics, trigonometric operations
@item
The units of @code{sin}, @code{cos}, etc, are degrees, not radians.  
@item
@cindex page units
@cindex user units
@cindex mapping page location units to user units
@cindex transforming page location units to user units
@cindex scales, accessing
@cindex mathematics, rpn notation, example
The scales of the plot are accessible to @code{rpn}.  For example, with
the command

@example
draw label "hi" at 10 20
@end example

@noindent
you draw the indicated string at the indicated location in
user coordinates.  To put it 0.15 centimetres to the right of this
location and 0.1 centimetres lower, you could do as follows:

@example
draw label "\label" at \
    @{rpn .x. xusertocm 0.15 + xcmtouser@} \
    @{rpn .y. yusertocm 0.10 - ycmtouser@}
@end example

(Note that the x and y scales have individual translations from "user"
to "cm" coordinates.)
@item
Some conversion factors are built into @code{rpn}; @code{cmtopt}
converts from centimetres to points (by dividing by 28.45; the
conversion factor to inches is 72.27) while @code{pttocm} converts from
points to centimetres.  For example, here is how to label a data curve
with a label placed near the last y-value of the data set:
@cindex drawing labels for data curves
@cindex labels, on data curves

@example
draw curve
.y. = @{rpn ..ylast.. yusertocm 0.5 - ycmtouser@}
draw label "Smoothed" at ..xlast.. .y.
@end example

@end itemize


@c HTML <!-- newfile Text.html "Gri: Text in Gri" "Text" -->

@node   Text, Embedded Synonyms, rpn Examples, Programming
@comment  node-name,  next,  previous,  up
@section Text Strings

Any text can be drawn in any size; Gri does not limit font size to a
list, e.g. 10 point, 12 points, etc.  Several fonts are available in
Gri, e.g. Times, Helvetica, etc.; these are all standard PostScript
fonts.  Support for some non-English languages (e.g. French) is also
provided.  And, finally, Gri supports inclusion of simple mathematical
expressions (Greek letters, superscripts, etc.) in text, using a
LaTeX-style syntax.

@menu
* Embedded Synonyms::           Embedding synonyms in text strings
* Mathematical Text::           Mathematical symbols and Greek letters
* Non-English Text::            French, etc.
* Adjustment Of Character Position:: thinspaces
@end menu


@c HTML <!-- newfile EmbeddedSynonyms.html "Gri: embedded synonyms" "Text" -->

@node   Embedded Synonyms, Mathematical Text, Text, Text
@comment  node-name,  next,  previous,  up
@subsection Embedding synonyms in quoted text strings
@cindex synonyms, embedding in quoted text strings
@cindex text strings, embedding synonyms within
@strong{Outside} math strings, you can embed your synonyms at will.  For
example, you can include the name of a data file in the title of your
plot as follows
@cindex interaction with user, @code{query} command

@example
query \filename "File to read from?" ("data.file")
open \filename
read columns x y
draw curve
draw title "data from \filename"
@end example

Within math strings (ie, between matched dollar-signs), these synonyms
are disabled, and only the mathematical symbols and Greek letters work.


@c HTML <!-- newfile MathematicalText.html "Gri: mathematical text" "Text" -->

@node   Mathematical Text, Non-English Text, Embedded Synonyms, Text
@comment  node-name,  next,  previous,  up
@subsection Mathematical text

@subsubsection Subscripts
@cindex subscripts
@cindex text, subscripts
As in @TeX{} and La@TeX{}, you must be in math-mode to use subscripts;
in other words, you must enclose the string or substring in
dollar-signs.  For single-character subscripts, insert an underline
prior to the character to be subscripted:

@example
draw title "$a_2$"
@end example

@noindent
For multiple-character subscripts, insert braces before and after the
item to be subscripted:

@example
draw title "$a_@{22@}$"
@end example

@subsubsection Superscripts
@cindex superscripts
@cindex text, superscripts
As in @TeX{} and La@TeX{}, you must be in math-mode to use superscripts;
in other words, you must enclose the string or substring in
dollar-signs.  For single-character superscripts, insert a carat prior
to the character to be superscripted:

@example
draw title "$a^2$"
@end example

@noindent
For multiple-character superscripts, insert braces before and after the
item to be superscripted:

@example
draw title "$a^@{22@}$"
@end example

@subsubsection Mathematical symbols
@cindex mathematical Symbols
@cindex greek Letters
@cindex text, mathematical symbols
@cindex text, Greek letters
As in @TeX{} and LaTeX, you indicate mathematical symbols and Greek
letters with backslash sequences.  The following LaTeX symbols are
defined in math mode in Gri (cf tables in Lamport's section 3):

@ifinfo
@example
\Delta \Downarrow \Gamma \Im \Lambda \Leftarrow
\Leftrightarrow \Omega \Pi \Phi \Psi \Re
\Rightarrow \Sigma \Theta \Uparrow \Upsilon \Xi
\alpha \approx \ast \beta \bullet \chi \circ
\cong \delta \div \downarrow \epsilon \equiv
\eta \exists \forall \gamma \geq \gg \in \infty
\iota \kappa \lambda \langle \leftarrow
\leftrightarrow \leq \ll \mu \nabla \neq \nu
\omega \partial \phi \pi \pm \prod \propto \psi
\rangle \rho \rightarrow \sigma \sim \subset
\subseteq \sum \supset \supseteq \surd \sqrt
\tau \theta \times \uparrow \upsilon \varpi
\wedge \xi \zeta \vartheta \varsigma \varphi
\aleph \oplus \otimes \wp \prime \emptyset
\angle \neg \clubsuit \diamondsuit \spadesuit
\cdot \lfloor \lceil \rceil \rfloor
@end example
@end ifinfo

@tex
({\tt $\backslash$Delta}, $\Delta$),
({\tt $\backslash$Downarrow}, $\Downarrow$),
({\tt $\backslash$Gamma}, $\Gamma$),
({\tt $\backslash$Im}, $\Im$),
({\tt $\backslash$Lambda}, $\Lambda$),
({\tt $\backslash$Leftarrow}, $\Leftarrow$),
({\tt $\backslash$Leftrightarrow}, $\Leftrightarrow$),
({\tt $\backslash$Omega}, $\Omega$),
({\tt $\backslash$Phi}, $\Phi$),
({\tt $\backslash$Pi}, $\Pi$),
({\tt $\backslash$Psi}, $\Psi$),
({\tt $\backslash$Re}, $\Re$),
({\tt $\backslash$Rightarrow}, $\Rightarrow$),
({\tt $\backslash$Sigma}, $\Sigma$),
({\tt $\backslash$Theta}, $\Theta$),
({\tt $\backslash$Uparrow}, $\Uparrow$),
({\tt $\backslash$Upsilon}, $\Upsilon$),
({\tt $\backslash$Xi}, $\Xi$),
({\tt $\backslash$alpha}, $\alpha$),
({\tt $\backslash$approx}, $\approx$),
({\tt $\backslash$ast}, $\ast$),
({\tt $\backslash$beta}, $\beta$),
({\tt $\backslash$bullet}, $\bullet$),
({\tt $\backslash$chi}, $\chi$),
({\tt $\backslash$circ}, $\circ$),
({\tt $\backslash$cong}, $\cong$),
({\tt $\backslash$delta}, $\delta$),
({\tt $\backslash$div}, $\div$),
({\tt $\backslash$downarrow}, $\downarrow$),
({\tt $\backslash$epsilon}, $\epsilon$),
({\tt $\backslash$equiv}, $\equiv$),
({\tt $\backslash$eta}, $\eta$),
({\tt $\backslash$exists}, $\exists$),
({\tt $\backslash$forall}, $\forall$),
({\tt $\backslash$gamma}, $\gamma$),
({\tt $\backslash$geq}, $\geq$),
({\tt $\backslash$gg}, $\gg$),
({\tt $\backslash$in}, $\in$),
({\tt $\backslash$int}, $\int$),
({\tt $\backslash$infty}, $\infty$),
({\tt $\backslash$iota}, $\iota$),
({\tt $\backslash$kappa}, $\kappa$),
({\tt $\backslash$lambda}, $\lambda$),
({\tt $\backslash$langle}, $\langle$),
({\tt $\backslash$leftarrow}, $\leftarrow$),
({\tt $\backslash$leftrightarrow}, $\leftrightarrow$),
({\tt $\backslash$leq}, $\leq$),
({\tt $\backslash$ll}, $\ll$),
({\tt $\backslash$mu}, $\mu$),
({\tt $\backslash$nabla}, $\nabla$),
({\tt $\backslash$neq}, $\neq$),
({\tt $\backslash$nu}, $\nu$),
({\tt $\backslash$omega}, $\omega$),
({\tt $\backslash$partial}, $\partial$),
({\tt $\backslash$phi}, $\phi$),
({\tt $\backslash$pi}, $\pi$),
({\tt $\backslash$pm}, $\pm$),
({\tt $\backslash$prod}, $\prod$),
({\tt $\backslash$propto}, $\propto$),
({\tt $\backslash$psi}, $\psi$),
({\tt $\backslash$rangle}, $\rangle$),
({\tt $\backslash$rho}, $\rho$),
({\tt $\backslash$rightarrow}, $\rightarrow$),
({\tt $\backslash$sigma}, $\sigma$),
({\tt $\backslash$sim}, $\sim$),
({\tt $\backslash$subset}, $\subset$),
({\tt $\backslash$subseteq}, $\subseteq$),
({\tt $\backslash$sum}, $\sum$),
({\tt $\backslash$supset}, $\supset$),
({\tt $\backslash$supseteq}, $\supseteq$),
({\tt $\backslash$surd}, $\surd$),
({\tt $\backslash$sqrt}, $\surd$),
({\tt $\backslash$tau}, $\tau$),
({\tt $\backslash$theta}, $\theta$),
({\tt $\backslash$times}, $\times$),
({\tt $\backslash$uparrow}, $\uparrow$),
({\tt $\backslash$upsilon}, $\upsilon$),
({\tt $\backslash$varpi}, $\varpi$),
({\tt $\backslash$wedge}, $\wedge$),
({\tt $\backslash$xi}, $\xi$),
({\tt $\backslash$zeta}, $\zeta$),
({\tt $\backslash$vartheta}, $\vartheta$),
({\tt $\backslash$varsigma}, $\varsigma$),
({\tt $\backslash$varphi}, $\varphi$),
({\tt $\backslash$aleph}, $\aleph$),
({\tt $\backslash$oplus}, $\oplus$),
({\tt $\backslash$otimes}, $\otimes$),
({\tt $\backslash$wp}, $\wp$),
({\tt $\backslash$prime}, $\prime$),
({\tt $\backslash$emptyset}, $\emptyset$),
({\tt $\backslash$angle}, $\angle$),
({\tt $\backslash$neg}, $\neg$),
({\tt $\backslash$clubsuit}, $\clubsuit$),
({\tt $\backslash$diamondsuit}, $\diamondsuit$),
({\tt $\backslash$spadesuit}, $\spadesuit$)
({\tt $\backslash$cdot}, $\cdot$)
({\tt $\backslash$lfloor}, $\lfloor$)
({\tt $\backslash$lceil}, $\lceil$)
({\tt $\backslash$rceil}, $\rceil$)
({\tt $\backslash$rfloor}, $\rfloor$)
@end tex

@c HTML <A HREF="./resources/math_symbols.gif">Click here</A> to see the 
@c HTML symbols and their names.

@noindent
For example, you might use these as follows:

@example
draw title "$\alpha$ = thermal expansion coefficient"
@end example

Sometimes you'll want a mathematical symbol to be adjacent to a normal
text string, with no space between.  You can do this by enclosing in
braces, as in LaTeX.

@cindex text, inserting forward/backward space
@cindex space in text
@cindex superscripts and subscripts -- how to align using @code{\!}
@cindex aligning superscripts and subscripts with @code{\!}

@TeX{} and La@TeX{} handle combinations of superscripts and subscripts
very cleanly, putting one above the other.  Presently, Gri does not do
this; for example @code{set x name "$A_1^2$"} will have the 2 appearing
to the right of the 1 instead of above it.  Proper positioning will be
added to a later version of Gri, but in the meantime you can achieve the
desired effect with the @TeX{} ``negative thinspace'' psuedo-character
in math-mode.  Using this feature will not hurt you when the new Gri
becomes available.  The symbol for a negative thinspace is @code{\!} in
math-mode.  It has no meaning in nonmath mode.  A thinspace is 1/6 of an
``em-space'' (a @TeX{} term, normally equal to the width of the
character ``M'' in the current font).  In most fonts, numbers are half
the width of the letter ``M'', so that 3 negative thinspaces will move
leftward over a single number.  Thus, if the example above becomes
@code{set x name "$A_1\!\!\!^2"}, the 2 will be positioned above the 1.
(Equivalently, you could write @code{set x name "$A^2\!\!_1$"}.)
Depending on the actual characters you have in the super/subscripts, you
might need more or less thinspaces; some experimentation might be
required.  Also, note that the symbol @code{\,} in math mode is a
positive thinspace (which moves the next character a little bit to the
right).  Thus, you can add a little extra spaces between characters by
doing something like @code{set x name "A$\,$B"}.

To get a hat over a single character, do something like the following
(which draws a hat over the character "h"):
@cindex hat, drawing hat on top of character

@example
draw label "h$@{\!\!\!^@{^\wedge@}@}$" at 10 12 cm
@end example

@cindex overbar, drawing line on top of character
@cindex latex overline command, emulating
@cindex overline, emulating latex command
To get an overbar on a rho, do this:

@example
draw label "$\rho\!\!\!\!^-$" at 3 3 cm
@end example



@c HTML <!-- newfile NonEnglishText.html "Gri: non-English text" "Text" -->

@node   Non-English Text, Adjustment Of Character Position, Mathematical Text, Text
@comment  node-name,  next,  previous,  up
@subsection Non-English characters

@cindex iso-latin-1 font encoding
@cindex text, ISO characters
@cindex accented characters in text
@cindex non-English language text
@cindex French accents in text

Gri relies on the ``standard'' PostScript fonts, however, and it
suffers all limitations of these fonts.

Gri supports both English and some other European-derived languages,
permitting text with accents on letters.  (It does not support
Oriental or other languages at this time.)  The accents are supported
by using the so-called ISO-Latin-1 font-encoding scheme (also called
the ISO-8859-1 scheme), and so, from what the author can gather from
his reading, Gri should support various languages from western
European, e.g. English, French, Spanish, Catalan, Basque, Portuguese,
Italian, Albanian, Rhaeto-Romanic, Dutch, German, Danish, Swedish,
Norwegian, Finnish, Faroese, Icelandic, Irish, Scottish, and as well
as Afrikaans and Swahili.

Gri uses the ISO-Latin-1 font encodings by default, although the
so-called `standard' font-encoding may also be selected with the
@code{Set Font Encoding} command (@ref{Set Font Encoding}).  For more
on font encodings see any book on PostScript fonts ... although the
bottom line is that if you are using accented characters in your work,
then you probably already know about encodings, and if you don't use
accents then you needn't learn about this topic except for the
pleasure of learning about other languages.

The method of handling accented characters is very simple.  If you can type it,
Gri can draw it!  It is up to you to determine how to enter the accents.  Most
text editors permit this, and it seems fair to say that users who need accented
characters already know how to type them into their editors.

@c For complete information about entering iso-latin-1 characters in Emacs,
@c consult your Emacs manual in the section
@c @ifinfo
@c @ref{(emacs)Single-Byte Character Support}
@c @end ifinfo
@c @ifhtml
@c @code{(emacs)Single-Byte Character Support}
@c @end ifhtml
@c which describes the available methods suitable for the Emacs version you
@c are using.  A few examples are nevertheless provided below.
@c 
@c Consider the task of inserting French text, with the Emacs
@c text-editor. There are several ways of doing this (and you may wish to
@c consult your emacs info manual).  A method that works in emacs-19 up to
@c current emacs-20 versions uses the emacs @file{iso-transl.el} package by
@c putting the following in your @file{~/.emacs} file:
@c 
@c @example
@c (require 'iso-transl)
@c (iso-transl-set-language "French")
@c (standard-display-european t)
@c @end example
@c 
@c Loading the iso-transl package defines three ways of entering the non-ASCII
@c printable characters with codes above 127: the prefix @kbd{C-x 8}, or
@c the @key{Alt} key, or a dead accent key.  For example, you can enter
@c uppercase A-umlaut as @kbd{C-x 8 " A} or @kbd{Alt-" A} (if you have an
@c Alt key) or @kbd{umlaut A} (if you have an umlaut/diaeresis key).
@c 
@c A more recently introduced method is to enter the mode which allows
@c quick insertion of iso-latin-1 characters. Do the Emacs command 
@c @code{M-x iso-accents-mode} (either manually, or in a hook that's done
@c automatically). Now, suppose the x-axis is to represent temperature. All
@c you'd have to do is type in the command
@c 
@c @example
@c set x name "Temp'erature"
@c @end example
@c 
@c As you type, the quote mark will dissappear, and reappear as an accent on the
@c @code{e}.  And then, Gri will recognize this as an accented character and it
@c will draw the accent on the axis label.

@c Perhaps the future default way of accomplishing this task is to use MULE
@c support directly.  First, customize MULE using 
@c @code{M-x customize-group RET mule} setting the
@c @code{current language environment} (e.g. latin-1) and
@c the @code{default input method} (e.g. latin-1-prefix).  Then, invoking
@c @code{M-x toggle-input-method} (e.g. @key{C-\}) toggles into a mode similar
@c to the @code{iso-accents-mode} minor-mode described above.

@c HTML <!-- newfile AdjustingCharacterPosition.html "Gri: adjusting character position" "Text" -->

@node   Adjustment Of Character Position, Adding New Commands, Non-English Text, Text
@comment  node-name,  next,  previous,  up
@subsection Adjustment Of Character Position
@cindex text, thin-spaces within
@cindex thin-space in text
Micro-positioning is available within math-mode, via the
symbols @code{\!} (which means go left one thin-space) and @code{\,}
(which means go right one thin-space).  (A thin-space is 1/6 the width of
the letter ``M'').


@c HTML <!-- newfile NewCommands.html "Gri: Adding new commands" "Programming Gri" -->

@node   Adding New Commands, Purpose, Adjustment Of Character Position, Programming
@comment  node-name,  next,  previous,  up
@section Adding new commands to Gri
@cindex commands, how to add new ones to Gri
@cindex new commands, how to add to Gri
@cindex adding new commands to Gri
@cindex extending Gri by adding new commands
Gri provides so-called "newcommands" as a sort of subroutine syntax on steroids.
@menu
* Purpose::                       What newcommands are for
* Parsing::                       How Gri parses commands
* Simple New Command::            Simple example of adding new command
* Complicated New Command::       More complicated example
* Changeable Command Arguments::  The &.var. and &\syn syntax
@end menu

@c HTML <!-- newfile PurposeOfSynonyms.html "Gri: Purpose of Synonyms" "Programming Gri" -->
@node   Purpose, Parsing, Adding New Commands, Adding New Commands
@comment  node-name,  next,  previous,  up
@subsection Purpose of newcommands
Gri can be extended easily.  Primitive commands (e.g. @code{set x name})
can be supplemented with so-called "new commands."  New commands are a
little like subroutines other programming languages.  For example, you
might find that you often draw filled curves with a particular graylevel
(say 0.5), and then return the graylevel to the previous value.  This
requires you to do the following each time:

@example
new .old_graylevel.
.old_graylevel. = ..graylevel..
set graylevel 0.5
draw curve filled to 0 y
set graylevel .old_graylevel.
delete .old_graylevel.
@end example

@noindent
This gets a bit tedious, and it would obviously be nicer to just say
something like

@example
Draw my kinda curve
@end example

To make this shortcut, you'd tell Gri about the existence of a new
command called @code{Draw my kinda curve}, and tell it that the new
command can be accomplished by the longer code fragment written above.

Once you've learned how to make new commands, you are likely to use them
a lot.  The following explains how you add new commands.  For advice on
programming style, etc., (@ref{Resource File}).


@c HTML <!-- newfile ParsingSynonyms.html "Gri: How synonyms are parsed" "Programming Gri" -->
@node   Parsing, Simple New Command, Purpose, Adding New Commands
@comment  node-name,  next,  previous,  up
@subsection How Gri parses commands
@cindex new commands, how they are parsed
Whenever Gri reads a command line, it compares it with its list of
commands.  This list is searched in this order: (1) the universal
@file{gri.cmd} file (@ref{Invoking Gri}), (2) your resource
file (@ref{Resource File}), if it exists, and then (3) your command
file itself.  Gri stops searching when it finds a Gri command that
matches the command line.  "Matching" means that the command line is
identical in all words in a Gri command, scanning from the left, until
it encounters a word containing
@itemize @bullet
@item
A quote (e.g. @code{"string"})
@item
A synonym name (e.g. @code{\file})
@item
A variable name (e.g. @code{.number.})
@item
An opening square bracket (e.g. @code{[option]})
@item
An opening brace (e.g.  @code{@{a|b@}})
@item
A choice between two items (e.g.  @code{first|second})
@item
A variable-name with a @code{&} character immediately to the left 
(e.g. @code{&.var.}).  This is a signal that the variable may be 
changed inside the newcommand (@ref{The Ampersand Syntax}).
@item
A synonym-name with a @code{&} character immediately to the left 
(e.g. @code{&\syn}).  This is a signal that the synonym may be 
changed inside the newcommand (@ref{The Ampersand Syntax}).
@end itemize

When Gri finds a command that matches your command line, it assumes that
this is the intended command, and searches no further.  This means that
you must be careful not to have your command hidden by other commands.
For example, if your resource file contained these lines, Gri would
@strong{never} execute the second new command, because calls to it match
the first command.  To avoid this, you may either reverse the order of
the definitions, so that Gri will find the proper routine, or rename one
of the routines.

@example
`Draw foo'
Draw a foo.
@{
  show "drawing a foo"
@}
`Draw foo bar'
Draw a foo bar.
@{
  show "drawing a foo bar"
@}
@end example

Gri searches the @file{gri.cmd} file first, so any new command that you
create that clashes with built-in commands will be ignored by Gri
(@ref{Invoking Gri}).  Gri will warn you of this, and proceed,
ignoring your newer definition.  To get around this, 
you can use capital letters
to begin the words of your new command.  By convention, Gri never uses
capital letters in this way, so a clash is impossible (except with any
similar command you might have defined previously, such as in your
@file{~/.grirc} file).

@c HTML <!-- newfile SimpleNewCommand.html "Gri: creating a simple new command" "Programming Gri" -->

@node   Simple New Command, Complicated New Command, Parsing, Adding New Commands
@comment node-name,  next,  previous,  up
@subsection Simple example of a new command
@cindex new commands, simple example
To make a new command called @code{Show The Time} insert the following
into your @file{~/.grirc} resource file or into your command-file
somewhere near the top, or at least before you use the command.

@example
`Show The Time'
New command to show the time of day.
@{
  show "\.time."
@}
@end example

@noindent
EXPLANATION:
@itemize @bullet

@item 
The name of the new command is enclosed in angled single-quote marks.
The words of the new command should begin with upper-case letters to
prevent a name clash with a present or future built-in Gri command.
@strong{Formatting convention:} Make sure that the entire definition
string, from the opening angled quote to the ending angled quote,
appears on one line.  Otherwise Gri will give an error like

@example
ERROR: Can't extract syntax for new command
@end example

@item
Following the name line, you may optionally insert any number of lines
which will become the @code{help} information for the new command.  See
the file @file{gri.cmd} for the recommended stylistic conventions in
writing help information (@ref{Invoking Gri}). If your @code{help} text
includes an example that uses an opening brace (@code{@{}) you must
escape the brace with a backslash, e.g. (@code{\@{}).
@item
Following the help lines, if they exist, the body of the new command is
given, sandwiched between a starting line containing an opening brace
(@code{@{}) as the @strong{only} nonwhite character, and an ending line
containing a closing brace (@code{@}}) as the only nonwhite character.
Any valid Gri commands may be used in the body of the new command.  It
is acceptable to use other new commands in the body. Recursion is also
allowed -- a new command is allowed to call itself (although there is a
limit on nesting, of perhaps a thousand or so; this varies with the
version of Gri).  @strong{Formatting convention:} It is usual, but not
necessary, to use an indentation level of 2 spaces in the body of the
new command.
@end itemize
@noindent
The new command is invoked by @code{Show The Time}.  Help for the
command is found by @code{help Show The Time} or @code{help Show}.


@c HTML <!-- newfile ComplicatedNewCommand.html "Gri: creating a complicated new command" "Programming Gri" -->

@node   Complicated New Command, Changeable Command Arguments, Simple New Command, Adding New Commands
@comment node-name,  next,  previous,  up
@subsection Complicated example of a new command
@cindex extending Gri by adding new commands, complicated example
@cindex adding new commands, complicated example
@cindex new commands, complicated example
The following example from the global @file{gri.cmd} file illustrates
how to parse/check the commandline (@ref{Local Synonyms}), which is a
good practice in any code you expect to re-use.  The first @code{if}
statement checks that the word @code{at} is in the right place (this
would not have been checked by the syntax matcher, the word having
followed a string).  The presence of the keyword @code{cm} is checked
for, and user units or cm units are used accordingly.  Local variables
are created (@code{new}) and then destroyed (@code{delete}) so that
this new command cannot affect outside code.

@example
`draw label whiteunder "\string" at .xleft. .ybottom. [cm]'
Draw label for plot, located with lower-left corner
at indicated (x,y) position (specified in user
units or in cm on the page).  Whiteout is used
to clean up the area under the label.  BUGS:
Cannot handle angled text; doesn't check for
super/subscripts.
@{
    if @{rpn "\.word4." "at" !=@}
      show "ERROR: 5th word must be `at', not `\.word4.'"
      show traceback
      quit
    end if 
    new .x. .y. .oldgray. .space.
    if @{rpn \.words. 7 ==@}
      .x. = @{rpn \.word5. xusertocm@}
      .y. = @{rpn \.word6. yusertocm@}
    else if @{rpn \.words. 8 ==@}
      if @{rpn "\.word7." "cm" !=@}
        show "ERROR: Require 8th word to be `cm'"
        show traceback
        quit
      end if
      .x. = \.word5.
      .y. = \.word6.
    else
      show "ERROR: Require 7 or 8 words, not \.words."
      show traceback
      quit
    end if
    # Coordinates now in cm.  Next, white out a box
    # under the text (and .space. centimetres
    # beyond text), then draw label.
    .space. = 0.1               # Space of 1mm
    .oldgray. = ..graylevel..
    set graylevel white
    draw box filled                          \
      @{rpn .x. .space. -@}                    \
      @{rpn .y. .space. -@}                    \
      @{rpn .x. "\.word3." width + .space. +@} \
      @{rpn .y. "M" ascent + .space. + @} cm
    set graylevel .oldgray.
    draw label "\.word3." at .x. .y. cm
    delete .x. .y. .oldgray. .space.
@}
@end example


@c HTML <!-- newfile ChangeableCommandArguments.html "Gri: making a newcommand change its arguments" "Programming Gri" -->

@node   Changeable Command Arguments, The Ampersand Syntax, Complicated New Command, Adding New Commands
@comment node-name,  next,  previous,  up
@subsection Altering command arguments -- the @code{&} syntax
@cindex command arguments, how to alter
@cindex newcommand arguments, how to alter
@cindex arguments to new commands, how to alter
@cindex the @code{&.variable.} notation
@cindex the @code{&\synonym} notation
@cindex variables, and the @code{&} syntax
@cindex synonym, and the @code{&} syntax

The Gri language permits a newcommand to change variables and synonyms
passed as arguments, using a syntax that is quite similar to that
employed by the C++ language.

@menu
* The Ampersand Syntax::                Denoting changeable arguments
* Doubling A Variable::                 Variables (e.g. @code{&.variable.})
* Manipulating A Synonym::              Synonyms (e.g. @code{&\synonym})
* Nesting::                             Newcommands called by newcommands
* Using New And Delete::                Isolating local variables and synonyms
* Determining Calling Information::     The @code{\&.word?.} and @code{\&&.word?.} syntax
* Implementation of Ampersand Syntax::  Algorithm Gri uses
@end menu


@node   The Ampersand Syntax, Doubling A Variable, Changeable Command Arguments, Changeable Command Arguments
@comment  node-name,  next,  previous,  up
@subsubsection Overview of the @code{&} syntax

Normally the arguments to a newcommand are parsed into either numerical
values or strings, before execution is passed into the newcommand.  This
is a akin to the scheme called "call by value" in some programming
languages.  Gri also provides a syntax, borrowed from C++, that permits
a newcommand to alter the contents of variable or synonym arguments.

The technique is simple.  To permit a newcommand to modify an argument
that is a variable or a synonym, just put a @code{&} to the left of the
item on the calling line.  Then, within the newcommand, the
corresponding local synonym (i.e. @code{\.word1.}, etc.) will behave as
though it were the instance of the original variable or synonym.

The @code{&} is placed to the left of the variable-name or synonym-name
without intervening space.  For example @code{foo &.var. &\syn} tells
the parser that the newcommand named @code{foo} may possibly alter the
values of the variable @code{.var.} and the synonym @code{\syn}, as they
exist in the calling context.

It is important to note that Gri pays very little attention to the
@code{&} in a syntax-declaration line.  All it does is to note that the
item to the right of the @code{&} is not a fixed word in the newcommand
being defined; this follows the usual rules for parsing newcommand syntax
(@ref{Parsing}).


@node   Doubling A Variable, Manipulating A Synonym, The Ampersand Syntax, Changeable Command Arguments
@comment  node-name,  next,  previous,  up
@subsubsection Example: doubling a variable

Consider the task of adding a fixed amount to a variable.  If the
variable we wish to double is @code{.x.}, we might write

@example
`double_a_particular_variable'
@{ 
    .x. = @{rpn .x. 2 *@}
@}
.x. = 10
double_a_particular_variable
@end example

@noindent
Code such as that presented above occurs in many applications.  (Turn
the multiplication into an addition, and change @code{.x.} to
@code{..ymargin..}, and you'll start to see the core of an application
that draws multiple graph panels, one above another.)  However, the code
is too specific to be of much general use!

What if we want to double some other variable instead?  The code below
shows how to do that.

@example
`double &.value.'
@{
    \.word1. = @{rpn \.word1. 2 *@}      # line 3
@}
.x. = 10                               # line 5
double &.x.
.y. = 3.14
double &.y.
@end example

@noindent
At line 3 Gri interprets the @code{\.word1.} to the @strong{left} of the
equals sign as a reference to the variable that is set to the value 10
in line 5.  Similarly, the @code{\.word1.} to the @strong{right} of the
equals sign evaluates to 10, the value in the calling program.

Gri automatically determines whether an item is a variable or a synonym,
and does the correct thing.  Thus, for example, if line 3 above were written as

@example
\.word1. = "hello"                 # ERROR
@end example

@noindent
an error would be reported, since @code{double} was called with a
variable as an argument, and variables cannot hold strings.

@node   Manipulating A Synonym, Nesting, Doubling A Variable, Changeable Command Arguments
@comment  node-name,  next,  previous,  up
@subsubsection Example: manipulating a synonym

Synonyms are treated in the same way, as is illustrated in the following
example.

@noindent
Q: what does the following print?

@example
`add_a_dat &\filename'
@{
    \.word1. = @{rpn "\.word1." ".dat" strcat@}
@}
\filename = "test"
add_a_dat &\filename
show "\filename"
@end example

@noindent
A: it prints @code{test.dat}.


@node   Nesting, Using New And Delete, Manipulating A Synonym, Changeable Command Arguments
@comment  node-name,  next,  previous,  up
@subsubsection Nesting

One newcommand may call another, letting a deeply-nested newcommand
alter values of synonyms and variables that may otherwise be hidden
behind @code{new} items of the same name.  This is done by using the
@code{&} notation at each step.  The following provides an example of
passing a variable through two levels of newcommands.

@noindent
Q: what does the following print?

@example
`food critic &food'                 
@{                                  
    \.word2. = "\.word2.s"          
    yummy &\.word2.                 
@}                                  
`yummy &foods'                      
@{                                  
    \.word1. = "\.word1. are tasty" 
@}                                   
\a = "apple"                         
food critic &\a                      
show "\a"                            
@end example

@noindent
A: it prints @code{apples are tasty}.



@node   Using New And Delete, Determining Calling Information, Nesting, Changeable Command Arguments
@comment  node-name,  next,  previous,  up
@subsubsection About @code{new} and @code{delete}

@cindex @code{new}, used on changeable arguments
@cindex @code{delete}, used on changeable arguments
@cindex changeable arguments, using @code{new} on 
@cindex changeable arguments, using @code{delete} on 

If @code{new} and @code{delete} are executed on local synonyms inside
newcommands (e.g.  @code{new \.word1.})  they create and destroy
variables and synonyms in the context of the @strong{calling program}.

For example, consider the following.

@noindent
Q: what does the following print?

@example
`poetry &\s'
@{
    new \s                             # line 3
    \s = "rose"
    \.word1. = "\.word1. is a \s"      # line 5
    delete \s                          # line 6
@}
\s = "A rose "                         # line 8
poetry &\s
show "\s"
@end example

@noindent
A: it prints @code{A rose is a rose}.

The key point here is that the instance of the synonym named @code{\s}
in the calling program, set in line 8, is modified by the @code{poetry}
newcommand, in line 6.  This modification involves the use of a synonym,
@strong{also named} @code{\s}, that "lives" wholly within the newcommand,
being created in line 3 and destroyed in line 6.  


@node   Determining Calling Information, Implementation of Ampersand Syntax, Using New And Delete, Changeable Command Arguments
@comment  node-name,  next,  previous,  up
@subsubsection Determining calling information

@cindex @code{\&} and @code{\&&} notation
@cindex newcommands, determining calling argument names with @code{\&}
@cindex newcommands, determining calling argument level with @code{\&&}

Newcommands may determine the name and the nesting level of changeable
calling arguments.  To get the name, put a single ampersand after the
backslash of the local synonym of interest.  To get the nesting level (0
for main program, etc.) put two ampersands after the backslash.
@example
`NC &.var.'
@{
    show "\&.word1. (expect '.a.')"
    show "\&&.word1. (expect 0)"
@}
.a. = 1
NC &.a.
@end example

@strong{Note}: neither of these items may be used an lvalue.  That is,
they may not be used to the left of an equals sign.  But you can always
get around that by clever use of alias synonyms (@ref{Alias Synonyms}).



@node   Implementation of Ampersand Syntax, Hints, Determining Calling Information, Changeable Command Arguments
@comment  node-name,  next,  previous,  up
@subsubsection How Gri implements the @code{&} syntax

@cindex @code{&} syntax, how it is parsed
@cindex parsing of the @code{&} syntax

When the parser encounters an unquoted @code{&} followed immediately by
the name of a variable or a synonym, it converts the whole token
(@code{&} plus name) into a specially-encoded string that can be
recognized inside newcommands.  (This is @strong{only} done if the
@code{&} and the variable name are @strong{not} enclosed in double
quotes.)

This specially-encoded string contains not just the name of the variable
or synonym, but also the current level of nesting of newcommands.  In
this way a newcommand can have its own private versions of variables,
created by @code{new}, that won't be misinterpreted for the
identically-named variables in the calling program.

The format of these specially-encoded strings is
@code{#\bn\ba\bm\be\b:\bN \b_ \bl\be\bv\be\bl\b:\bL#\b},
where @code{N} stands for
the name of the variable/synonym, @code{L} stands for the current level,
and @code{\b} is the backspace character (hexadecimal 08 in the ascii
table).  This string is designed to be strange enough that users are
unlikely to use it themselves.  The coding scheme is not entirely
arbitrary, however; note that if the backspace characters are ignored
the result has the form @code{name:N_level:L}.  It's also worth noting
that if this string were printed on a terminal that erased characters
when typing backspaces the result would be of the form @code{N_L}.

Examples: @code{@.a.} in the main program
(i.e. at level 0) encodes to
@code{#\bn\ba\bm\be\b:\b.a. \b_ \bl\be\bv\be\bl\b:\b0#\b}
and @code{&\my_syn} inside a newcommand called by the main program
(i.e. at level 1) encodes to
@code{#\bn\ba\bm\be\b:\b\my_syn \b_ \bl\be\bv\be\bl\b:\b1#\b}.

Inside a newcommand, Gri checks to see if builtin synonyms
(e.g. @code{\.word1.}) hold such specially-encoded strings.  If so, then
the appropriate versions of the variables are used in preference to any
variables that may have been newly created by @code{new} inside the
newcommand.



@c HTML <!-- newfile Hints.html "Gri: Hints for Gri programming" "Programming Gri" -->

@node   Hints, Debugging, Implementation of Ampersand Syntax, Programming
@comment  node-name,  next,  previous,  up
@section Hints for Gri Programming
@cindex hints

Here are some hints for good Gri programs:

@itemize @bullet
@item
Whenever working with grids (for contouring) or images, make use of the
@code{show grid} or @code{show image} commands.  They will give you
useful information about the statistics (min/max/histogram) of the items. 
@item
Use the operating system, not Gri, to manipulate your data.  For
example, if you have a file whose first column is x times 100, and third
is the arcsin of y, you could do:

@example
open "gawk '@{print $1/100, sin($3)@}' |"
read columns x y
@end example

If you have x and y in a non-decimal geographical format
(e.g. hour.minute-second format), use the operating system to convert
for you (@ref{Open}).
@item
Use the @code{pstack} operator liberally in your rpn expressions
to see what is going on (@ref{rpn Mathematics}).
@item
While developing programs, put a @code{show columns statistics} command
after every @code{read column} command, to check that the data have been
read correctly.
@item
Development time can be minimized by limiting the number of data being
processed.  For example, in a multi-panel plot, it is often necessary to
try various alternatives before aesthetic scales and page layout is
achieved.  The process can be speeded up by limiting the number of data
being processed, as shown below.  (If Gri finds fewer data in the file
than specified, it will simply use the data that it found; so when the
program works, just change @code{.n.} into something large.)

@example
.n. = 100 # 10000 for later
...
# Panel 1
read columns .n. x y
...
# Panel 2
read columns .n. x y
...
@end example

@item
Create new commands to do repetitive work.
@item
Use @code{draw time stamp} on all plots except for publication versions:

@example
if !..publication..
  draw time stamp
end if
@end example

@item
For multiple panels on one page, do @code{delete x scale} 
or @code{delete y scale} before each
new panel, so you will start afresh.  Clearly identify 
code for particular panels with
comments.  This reduces errors you might get if you shuffle things
later.
@item
Use the @code{..num_col_data..} built-in variable to see how many data
have passed the @code{set input data window} data window in the last
@code{read columns} command.  The following example shows how to
avoid drawing an unwanted curve:

@example
open \f
read columns x y
close
if ..num_col_data..
  draw curve
  draw label "\f" at \
      @{rpn ..xlast.. xusertocm 0.5@} \
      @{rpn ..ylast.. yusertocm 0.2@} cm
end if
@end example

@cindex hint, using @code{query} to interact with user
@item
Use synonyms and @code{query} for filenames.  This makes programs much
more flexible.  Note that you can string synonyms together:

@example
\dir = "~/EOS/iso0/"
query \file "Give file in directory \dir" ("1.dat")
open \dir/\file
@end example

It is also a good idea to give a restrictive list of possibilities in
your @code{query} command, to avoid complicated @code{if} commands later
(@ref{Query}).
@item
Use multiple @code{draw title} commands:

@example
draw title "Atlantic water entering Arctic Ocean"
draw title "\.command_file. \.time."
@end example

@item
Use the @code{query} command to interact with the user (@ref{Query}).  The results can be stored in variables and synonyms.

@end itemize


@c HTML <!-- newfile Debugging.html "Gri: Debugging Gri programs" "Programming Gri" -->

@node   Debugging, Error Messages, Hints, Programming
@comment  node-name,  next,  previous,  up
@section Debugging Gri Programs
@cindex debugging Gri programs
@cindex problems and how to cope with them
Here are some hints for debugging Gri programs:
@itemize @bullet
@item
If no data appear on an xy plot, insert @code{show columns statistics}
or @code{show columns} after the @code{read columns} command.  It may be
that you have fixed your axes, and that the axes frame does not include
the data.
@item
@cindex tracing execution, using @code{..trace..}
If you get an error message, rerun your Gri program using the
@code{-trace} command-line option, to see which line is causing the
problem.  This often reveals logic errors (e.g. in (@code{if}
statements).  You may also turn tracing on or off at any point in your
Gri program by setting the built-in variable @code{..trace..} to 1 or 0.
Many Gri users have the Gri command aliased to be in trace mode by
default. 
@item
If Gri complains of a syntax error, consult the printed manual, one of
the online manuals, or the online help facility (@ref{Online Help}).
@item
Check the version number (printed at startup) to see if a new version of
Gri has been installed, and check the manual for known incompatabilities.
@item
Sprinkle @code{show} commands throughout your program, to see what's
happening.  Even when you are sure your program works, it is a good idea
to embed @code{show} statements so are they executed if the
@code{-debug} flag is set:

@example
if ..debug..
  show "X=" .x. "and label is `\label'"
end if
@end example


@item 
If your @code{draw} commands don't draw anything, check to see
whether you've fooled yourself by enforcing an improper scaling; remove
explict scaling (@code{set x axis ...}), clipping (@code{set clip}), data
selection windows (@code{set input data window x|y}) and missing values
(@code{set missing value}).  Another trick is to read only a portion of
the data set (@code{read columns 10 x y}) and then print out all the
values (@code{show columns}).
@end itemize

If you determine that the bug is in Gri, not in your program, please
report the bug, so that other users will not have the same hassle;
(@ref{Reporting Bugs}).



@c HTML <!-- newfile ErrorMessages.html "Gri: error messages" "Programming Gri" -->
@node   Error Messages, Missing Values, Debugging, Programming
@comment  node-name,  next,  previous,  up
@section Error Messages
@cindex error messages
Gri error messages are in three types:
@enumerate
@item
Operating system error messages, such as @code{segmentation fault}.
These should never appear, and indicate a bug in Gri.  Please report
these to the author (@ref{Reporting Bugs}).
@item
Internal Gri error messages.  The message starts with the words
@code{FATAL error}, and quotes a file number and a line number, e.g.

@example
FATAL error: startup.c:199: ...
@end example

@noindent
Such errors indicate either a deficiency in your computer (e.g.
insufficient storage space) or an internal bug in Gri.  If the message
does not indicate running out of storage, please report the error to the
author (@ref{Reporting Bugs}).

For fatal error messages on a unix system, Gri dumps core, unless you
have turned that feature off, with the @code{ulimit -c 0} unix command
in a startup file.  This creates a file called @file{core}, which can
help you in diagnosing the Gri bug.  If you have the @code{gdb}
debugger, just type @code{gdb gri core} and then type @code{where} to
get a traceback stack.  Please email this with your other information
about the Gri bug.
@item
An indication that your commandfile is flawed, either in syntax or in
meaning.  These messages end with a line indicating the offending line
in your commandfile, e.g. the command @code{set x axis 0 1 -1} yields:

@example
ERROR: `set x axis .left. .right. .incBig.'
        has .incBig. of wrong sign
 Bad command:  `set x axis 0 1 -1 '
@end example

@noindent
Normally, such error messages do not indicate a flaw in Gri, but rather
in your reasoning, so report them to the author only if you are very
sure that a Gri bug must underly them.
@end enumerate



@c HTML <!-- newfile MissingValues.html "Gri: missing values" "Programming Gri" -->
@node   Missing Values, Operating System, Error Messages, Programming
@comment  node-name,  next,  previous,  up
@section Missing data
@cindex data, missing values
@cindex missing value code
@cindex NaN for missing value code
@vindex @code{..missingvalue..}, value for missing data
Most Gri commands will ignore data points equal to a "missing value."
For example, @code{draw curve} connects only points which are not equal
(to within 0.01 percent) of the missing value.  The curve has holes at
missing data.  Initially the missing-value is set to 1.0e22.  You may
alter this value with @code{set missing value .value.}.  
The built-in variable @code{..missingvalue..} stores the current value
of the missing-value.

Additionally, Gri will ignore anything it reads that is equal to the
string @code{NaN} or @code{Inf}.  These are produced by matlab, C, and
other programs when dividing by zero, etc.

Gri also ignores mathematical operations on data items which are equal to 
the missing value.  Thus, for example, if your missing value is -99 then 
the command @code{x += 1} will not change the values equal to -99 to -98,
since this would have the side-effect of making the datum no longer be
considered missing.


@c HTML <!-- newfile OperatingSystem.html "Gri: operating system" "Programming Gri" -->

@node   Operating System, Using OS Inside Gri, Missing Values, Programming
@comment  node-name,  next,  previous,  up
@section Interaction Between Gri and Operating System
@cindex awk, sample of use
@cindex operating system commands, printing results of
@cindex system commands, printing results of
@cindex operating system commands, assigned to synonyms
@cindex system commands, assigned to synonyms

@menu
* Using OS Inside Gri::         Accessing the OS from inside Gri
* Using Gri Inside OS::         Tricks for using Gri in unix
@end menu

@node   Using OS Inside Gri, Using Gri Inside OS, Operating System, Operating System
@comment  node-name,  next,  previous,  up
@subsection Using the OS from within Gri

Gri uses the operating system internally for things like paging through
help information.

@cindex system calls, using dollar-parenthesis shell syntax
@cindex protecting Gri programs against datafile movement
@cindex unix, dollar-parenthesis notation within Gri commands
@cindex @code{\$()} syntax for system commands
@cindex dollar-parenthesis syntax for system commands
The operating system may be called @strong{within} Gri commands, using a
syntax borrowed from the @code{Bash} unix shell.  After substituting
synonyms in the commandline, Gri scans for dollar-parenthesis blocks
(e.g. @code{\$(system-command)}, replacing them with the textual result
of sending the indicated system-command to the OS.  The replacements are
done from left to right in the commandline, starting at the deepest
nesting level.

@cindex pathname of commandfile
@cindex commandfile, pathname
Often the dollar-parentheis syntax is used in title commands, to
indicate the full pathname of the Gri commandfile, e.g.

@example
draw title "\$(pwd)/\.command_file."
@end example

In assignment to synonyms, expansion of dollar-parenthesis is not done.
Thus the operating system is called twice on the second line below, and
not at all on the first line; to see this, run it as @code{gri -s8 -t}.

@example
\dir = "\$(echo $MY_DIR)"
show "\$(head -1 \dir/MY_FILE)"
@end example

@strong{Syntax Note} Dollar-parenthesis blocks must be prefixed with
backslash to avoid confusion with math expressions within strings, for
example to avoid breaking @code{draw label "$(x,y)$" at 3 3 cm}.  This
is an example of how @TeX{} notation and unix shell notation collide.

@strong{Example} It is a good idea to employ unix environment variables to name
directories containing data, so that Gri scripts will work unchanged
even if the data are moved (so long as the environment variables are
altered), e.g.

@cindex using environment variables for directory names
@cindex strings, embedding OS output into
@cindex OS, embedding system output into strings
@cindex calling OS from within strings

@example
# Figure how many lines in a file
\dir ="$(echo DIRECTORY_WHERE_I_STORE_SOLAR_DATA)"
open "\dir/solar_data_file_name`
...
open "\$(echo DIR_ANOTHER)/another_data_set"
@end example

@noindent
Another method is to pass instructions to the operating system with the
@code{system} command.  This discards output.  Whatever follows the word
@code{system} is first scanned for synonyms (but not rpn expressions or
variables); after replacement of any existing synonyms, the line is
passed directly to the operating system.  Any results are printed on the
terminal.

Frequently used system commands are @code{awk}, @code{head}, @code{grep} and
@code{sed}.  Examples:

@itemize @bullet
@item
Here's how to paste several files together to form a temporary file for
plotting.  (Notice that a temporary file incorporating the PID of the job
is created and later removed.)

@example
system paste -d" " 1.dat 2.dat 3.dat > tmp.\.pid.
open tmp.\.pid.
read columns x y
close
system rm tmp.\.pid.
@end example

@item
Here's how to plot each line in a file called @file{inp} which has
the string @code{;} at the start of the line.

@example
system cat inp | grep -v "^;" | cat > tmp.\.pid.
open tmp.\.pid.
read columns x y
system rm tmp.\.pid.
@end example

@item
Here's how to use the @code{awk} system command to create a tabulated
function for plotting.

@example
system awk                             \
    'BEGIN @{                           \
       for (x=0; x<1; x+=0.1) @{        \
         printf ("%f %f\n", x, sin(x)) \
       @}                               \
     @}'                                \
    > tmp.\.pid.
open tmp.\.pid.
read columns x y
close
system rm tmp.\.pid.
draw curve
@end example

@cindex pipes, opening files through them
@cindex opening files through pipes

@noindent
This example is more cleanly written using the piping facility of the
@code{open} command (which automatically creates a temporary file, and
destroys it when @code{close} is done)

@example
open "awk 'BEGIN @{       \
  for(x=0;x<1;x+=0.1) @{  \
    print(x,sin(x))      \
  @}                      \
@}'|"
read columns x y
close
draw curve
@end example


@item Sometimes you need just a single output item from the operating
system.  In this case, you can store the results from the operating
system in a synonym by using the @code{\synonym = system ...}
assignment command.  
@item
@cindex temporary file allocation
@cindex file, temporary
@cindex filename, temporary
@cindex @code{tmpname}
subroutine A related command is @code{\synonym = tmpname}, which
stores in the synonym the name of a temporary file created by the
system.  The file is created with the @code{tmpname} system call, so
it is guaranteed not to clash with any existing files.  Typically, the
filename is something like @file{/usr/tmp/griAAAa1233}.  In many cases
you'll want to remove the file within Gri, once you're done, and that
can be done with @code{unlink} (@ref{Unlink}) or with a
@code{system rm -f} command.  A useful bit of code is as follows
@example
\file = tmpname
system ... SOME_SYSTEM_COMMANDS ... > \file
... use this new file for something ...
unlink \file
@end example

@end itemize


@node   Using Gri Inside OS, Resource File, Using OS Inside Gri, Operating System
@comment  node-name,  next,  previous,  up
@subsection Using Gri from within the OS

@strong{This section only applies to unix systems.}

Save the following into a file called @file{p} and then make it
executable using @code{chmod}.  It runs Gri on a named file, with the 
@code{-yes} flag set
so that any @code{query} commands are automatically answered in the
affirmative, and then displays the results in a Ghostscript window.
(USAGE: @code{p cmdfile.gri})

@example
#!/usr/bin/sh
# Run Gri, then plot in gs window
case $# in
1)
        base=`basename $1 .gri | sed -e s/.*,#`
        gri -yes $base.gri && ghostview $base.ps
        ;;
*)
        echo "Proper usage: $0 cmdfile.gri"
        ;;
esac
@end example


@c HTML <!-- newfile ResourceFile.html "Gri: The Gri resource file" "Programming Gri" -->

@node   Resource File, Environment, Using Gri Inside OS, Programming
@comment  node-name,  next,  previous,  up
@section Sample Resource File
@cindex files, @file{~/.grirc} initialization file
@cindex @file{~/.grirc} initialization file
@cindex initialization commands
@cindex startup commands
@cindex resource files

The following shows a sample @file{~/.grirc} resource file.  Much of the
code here is adding new commands (@ref{Adding New Commands}.)

@example
# Some folks like tics to point inwards ...
set tics in

# Hey, I'm bored with Helvetica font, and
# Palatino is a bit prettier than Times
set font to PalatinoRoman

# Now for something a bit less trivial.
# This lets me draw a set of y-values
# against a single x-value, by e.g.
#    open xyyy.dat
#    draw curves time T1 T2 T3
# where the first column of the file is
# time, and the others are temperatures
# at various sensors.
`draw curves \xname \y1name ...'
Draw multiple y columns versus an x column.  Assumes
that the datafile is open, and that x is in the first
column, with the y values in one or more following 
columns.

The number of columns is figured out from the options, 
as is the name of the x-axis, and the labels to be 
used on each of the y curves.
@{
  # NB. the 3 below lets us skip the words 'draw' 
  # and 'curves', and the name of the x-column.
  .num_of_y_columns. = @{rpn wordc 3 -@}
  if @{rpn .num_of_y_columns. 1 >@}
    show "ERROR: `draw curves' needs at least 1 y column!"
    quit
  end if

  set x name @{rpn 2 wordv@}
  set y name ""

  # Loop through the columns.
  .col. = 0
  while @{rpn .num_of_y_columns. .col. <@}
    # The x-values will be in column 1, with y-values
    # in columns 2, 3, ..., of the file.
    .ycol. = @{rpn .col. 2 +@}
    rewind
    read columns x=1 y=.ycol.
    # At this point, you may want to change line thickness,
    # thickness, color, dash-type, etc.  For illustration,
    # let's set dash type to the column number.
    set dash .col.
    draw curve
    draw label for last curve @{rpn .col. 3 + wordv@}
    .col. += 1
  end while
@}
@end example





@c HTML <!-- newfile Environment.html "Gri: extra programs that work with Gri" "Gri Extras" -->

@node   Environment, Extras, Resource File, Top
@comment  node-name,  next,  previous,  up
@chapter Environment

Gri comes with a few ancillary programs that may be useful.  Gri also
provides a simple scheme to use other system tools (e.g. @code{awk}).
These are discussed here.  And speaking of discussing, this chapter ends
with a note about a mail-list Gri discussion group.

@menu
* Extras::                      Extra things provided with Gri
* Using System Tools::          Using Gri with other tools
* Discussion Group::            Gri email list
@end menu

@c HTML <!-- newfile Extras.html "Gri: Extras" "Gri Environment" -->

@node   Extras, gri_merge, Environment, Environment
@comment  node-name,  next,  previous,  up
@section Extra things provided with Gri

@menu
* gri_merge::                   Merge files to one page
* gri_unpage::                  Separate multipage doc into separate files
@end menu

@node   gri_merge, gri_unpage, Extras, Extras
@comment  node-name,  next,  previous,  up
@subsection @code{gri_merge} -- combine PostScript files
@cindex gri_merge
Merge separate PostScript files, created by Gri, into one page.  To
learn how it works, type @code{gri_merge -h} at the system prompt, to
see:

@example
PURPOSE: Strings Gri PostScript files together.

BUGS:    With old versions, of gri, make sure to match each `set clip
 postscript on' with a `set clip postscript off'.

USAGE (style 1):
    gri_merge [OPTIONS] CxR a.ps b.ps ... > merged_file.ps
 Merges the files onto one page, in 'C' columns and 'R' rows.  The C*R
 files are given in the order of words on a page.  The page is
 presumed to be 8.5x11 in size, as are all the input files, and the
 input files are sized to fit, and kept in natural scale.

USAGE (style 2):
    gri_merge [OPTIONS] xcm ycm enlarge a.ps [b.ps ...] > merged_file.ps
 Where `enlarge' is a scale factor applied after offsetting `xcm' to
 the right and `ycm' upward.

EXAMPLE (style 2):
 The following
   gri_merge  2 12 .5 a.ps \
            12 12 .5 b.ps \
             2  2 .5 c.ps \
            12  2 .5 d.ps > all.ps
 produces 4 panels from gri plots done using margins and sizes
 as specified in the following lines in a gri commandfile
   set x margin 2
   set x size 15
   set y margin 2
   set y size 15
 The OPTIONS, available if your 'perl' has 'getopts' library, are:
   -u graylevel -- set graylevel for underlay beneath panels, by default 0.75.
                   Values range from 0 (black) to 1 (white), although a value
                   of precisely 1 means do NOT draw underlay.
   -b graylevel -- Set value for background under individual panels, again 0 
                   for black to 1 for white, with 1 meaning no drawing.
   -h           -- Print this help message and quit.
@end example


@node   gri_unpage, Using System Tools, gri_merge, Extras
@comment  node-name,  next,  previous,  up
@subsection @code{gri_unpage} -- split pages into files
@cindex gri_unpage
Given a multipage PostScript file, @code{gri_unpage} creates several new
PostScript files, one for each page.  To learn how it works, type
@code{gri_unpage -h} at the system prompt, to see:

@example
PURPOSE: Chop multipage Gri PostScript file into one file per page.
USAGE:   gri_unpage name.ps -- create files name-1.ps, name-2.ps, etc, one
                               for each page of name.ps.
         gri_unpage -h      -- print this help message

BUGS:    1. Bounding box is always 8.5x11 inches.
         2. Assumes that all Gri fonts are used even if they aren't.
@end example


@c HTML <!-- newfile SystemTools.html "Gri: Using System Tools With Gri" "Gri Environment" -->

@node   Using System Tools, Why Use The Environment, gri_unpage, Environment
@comment  node-name,  next,  previous,  up
@section Using System Tools With Gri

Using system tools to manipulate your data makes sense for several
reasons.  First, you may be familiar with those tools already.  Second,
learning these tools will help you in all your work.  

@menu
* Why Use The Environment::     Introduction
* Grep::                        Search files for patterns
* Sed::                         Serial editor
* Awk::                         Search and manipulate data
* Perl::                        Search and manipulate data
@end menu

@node   Why Use The Environment, Grep, Using System Tools, Using System Tools
@comment  node-name,  next,  previous,  up
@subsection Introduction

Each of the programs listed in the sections below is available for Unix.
Some (e.g. Perl and the Awk variant called Gawk) are available on other
operating systems as well.  Each of these tools is fully documented in
Unix manpages, so here I'll just give an indication of a couple of
useful techniques you might want to use.

Bear in mind that these tools can do very similar jobs.  For example,
Awk can do much of what Sed and Grep can do, but also a whole lot more.
If you don't know Sed or Grep, I suggest you learn Awk instead.  Then
again, Perl can also do anything Gawk can do, and a whole lot more!
(For one thing, it is easier to work with multiple files in Perl.)  In
fact, Perl is the most powerful of this list.  If you know none of these
tools, you might want to learn Perl instead of the others.  But Perl is
more complicated for simple work than Awk is, so the most reasonable
path might be to learn both Awk and Perl.

For simple applications, you will probably want to use these tools in a
piped open command, e.g.

@example
open "awk '@{print $1, $3/$2@}' MyFile |"
@end example

@noindent
which creates a temporary file (automatically erased when Gri finishes)
which contains the output from running the system command that preceeds
the pipe symbol (@code{|}) (@ref{Open}).

(Here and in all the examples of this chapter, it is assumed that the
user's input file is named @file{MyFile}.)

For more complicated appplications, you may use the Gri @code{system}
command as follows.

@example
system perl   >tmp  <<"EOF"
open(IN, "MyFile");
while(<IN>) @{
    ($x, $y) = split;
    print "$x", " ", cos($y), "\n";
@}
EOF
open tmp
read columns x y
draw curve
system rm -f tmp
@end example

@noindent
Here a temporary file, named @file{tmp}, has been used to store the
results of the calculation.  Note that this file was specifically
cleaned up by the second @code{system} command.  (Many folks, including
the author, would prefer to take the perl script out of the above and
make it a standalone executable script, calling it from Gri with the
one-line form.  But it is just a matter of style.)



@node   Grep, Sed, Why Use The Environment, Using System Tools
@comment  node-name,  next,  previous,  up
@subsection Grep

@cindex grep system tool
@cindex overview of grep system tool

The most common application of Grep is to select lines matching a
pattern, or not matching a pattern.  Here is how to skip all lines with
the word "HEADER" in them:

@example
open "grep -v 'HEADER' MyFile |"
...
@end example

@noindent
Note that Gawk and Perl do this just as easily.


@node Sed, Awk, Grep, Using System Tools
@comment  node-name,  next,  previous,  up
@subsection Sed

@cindex sed system tool
@cindex overview of sed system tool

Sed is normally used for simple changes to files.  For example, if you
have columnar data which are separated with comma characters instead of
whitespace, you could make it Gri compatible by 

@example
open "sed -e 's/,/ /g' MyFile |"
@end example

@noindent
Where the @code{-e} flag indicates that the next item is a command to
Sed, in this case a command to switch ("s") the comma character with the
blank character, globally ("g") across each line of the file.  See also
the overview of Perl.

@node Awk, Perl, Sed, Using System Tools
@comment  node-name,  next,  previous,  up
@subsection Awk

@cindex awk system tool
@cindex gawk system tool
@cindex overview of awk system tool

Awk is great for one-liners.  If your system lacks Awk, you can procure
the GNU version, called Gawk, from the web for free.  For better or
worse, Gawk is not fully compatible with Awk.  The good thing is that
Gawk is pretty much the same on all operating systems, whereas the
installed Awk may not be.  I use Gawk instead of Awk, for this reason
and because it is normally faster.

The main concept in Awk is of "patterns" and "actions."  In the Awk
syntax, actions are written in braces following patterns written with no
braces.  (This will become clear presently.)

Whenever a line in the data file matches the pattern, the action is
done.

The default pattern is to match to every line in the file.  This is done
if no pattern is supplied.

The default action is to print the line, and this is done if no action
is supplied.

Here are a few examples.  To skip first 10 lines of a file:

@example
open "awk 'NR>10' MyFile |"
read ...
@end example

@noindent
Here the pattern was that @code{NR} (a special Awk variable for the
number of the record, starting with 1 for the first line of the file)
exceeded 10.  And the action was taken by default since nothing was
supplied between braces, to print this line.

@noindent
To plot the cosine of the second column against the first column:

@example
open "awk '@{print ($1, cos($2))@}' MyFile |"
read columns x y
draw curve
@end example

@noindent
Here no pattern was supplied, so the action was done for every line.

Combining these two forms, then, and supplying both a pattern and an
action, here is how one might print the first and eighth columns of the
file @file{MyFile}, but only for the first 10 lines of the file:

@example
open "awk NR<=10 @{print ($1, $8)@} MyFile |"
@end example




@node  Perl, Discussion Group, Awk, Using System Tools
@comment  node-name,  next,  previous,  up
@subsection Perl

@cindex perl system tool
@cindex overview of perl system tool

Perl can do almost @strong{anything} with your data, since it is a full
programming language designed to also emulate several Unix utilities.

In perl, as in other commands, the commandline switch @code{-e}
indicates that a Perl command is given in the next word of the command
line.  The commandline switch @code{-p} indicates to print the line,
after any indicated Perl actions have been done on it.  Here, for
example, is how one would emulate a Sed replacement of comma by blank:

@example
open "perl -pe 's/,/ /g' MyFile |"
@end example

Perl also has a commandline switch @code{-a} indicating that lines
should be "autosplit" into an array called @code{$F}.  The first element
of this array is @code{$F[0]}.  Splitting is normally done on
white-space character(s), although this may be changed if desired.
Here, for example, is how to take the cosine of the second column of a
file, and print this after the first column:

@example
open "perl -pea 'print($F[0], cos($F[1]))' MyFile |"
@end example


@c HTML <!-- newfile DiscussionGroup.html "Gri: Discussion Group" "Gri Discussion Group" -->

@node   Discussion Group, Emacs Mode, Perl, Environment
@comment  node-name,  next,  previous,  up
@cindex discussion Group
@cindex email list
@section Gri Discussion Group
Before emailing to the Gri newsgroup, it is a good idea to consult the
@c HTML <A HREF="./FAQ.html"> 
@c HTML FAQ
@c HTML </A>
list of answers to Frequently Asked Questions.


As of summer 2000, Gri traffic has been moved to the web-based
discussion groups at the SourceForge website
@url{http://gri.sourceforge.net}
about which little need be said here, because the website is very
easy to use.

@c HTML <!-- newfile Emacs.html "Gri: Emacs editing mode" "Emacs editing mode" -->

@node   Emacs Mode, About Gri Mode, Discussion Group, Top
@comment  node-name,  next,  previous,  up
@chapter Editing Gri Files in GNU Emacs

@cindex gri code, editing
@cindex editing Gri code with Emacs
@cindex emacs, editing mode for Gri
@cindex gri-mode, editing in emacs

If you use the GNU Emacs (or XEmacs) text editor, writing Gri command
files is made easier with the Gri editing mode (gri-mode.el),
written by Peter S. Galbraith
@c HTML <A HREF="mailto:Peter S Galbraith <psg@debian.org>">
@code{<psg@@debian.org>}.
@c HTML </A>

@menu
* About Gri Mode::
* Gri-mode screenshots::                  What it looks like.
* Installing gri-mode.el::                The nuts and bolts.
* Major Gri-mode commands::               It knows about Gri commands.
* Other features::                        IMenu, Toolbar, etc.
* Dealing with many Gri versions::        gri-mode handles it.
* Filename arguments when running gri::   gri-set-command-postarguments.
@end menu

@c HTML <!-- newfile AboutGriMode.html "Gri Mode: About Gri Mode" "Gri Mode:About Gri Mode" -->

@node   About Gri Mode, Gri-mode screenshots, Emacs Mode, Emacs Mode
@comment  node-name,  next,  previous,  up
@section About Gri Mode

Gri mode has all the wonderful things you've come to expect from Emacs modes.
Here's a brief overview of the features:
@itemize @bullet
@item
It can @strong{complete} partially typed commands, builtin variables
and synonyms (@code{gri-complete}, @key{M-Tab}) and help you edit the
syntax that was thus inserted for you (@code{gri-option-select},
@kbd{C-c C-o}; @code{gri-option-kill}, @kbd{C-c C-k}).
@item
It can provide a short help synopsis concerning the command on the
current line (@code{gri-help-this-command}, @kbd{C-c C-h}), or load the
info manual for that command (@code{gri-info-this-command}, @kbd{C-c
C-i}).  It knows the list of all Gri commands, and can provide help or
info regarding any of them (@code{gri-help}, @kbd{C-c M-h};
@code{gri-info}, @kbd{C-c M-i}) using command name completion at the
prompt (@key{Tab}). 
@item
All Gri commands are listed in a pull-down menu from the menubar, which
you can use to either enter the text of the selected command, or obtain
help or info about it.
@item
It can help you find an unknown command by listing all
containing a given word (@code{gri-apropos}, @kbd{C-c C-a}).
@item
It fontifies your Gri code using colour coding.
@item
It indents if statements, loops, and so on (@code{gri-indent-line}, @key{Tab}).
@item
It can let you run Gri and view its output without leaving the editor 
(@code{gri-run}, @kbd{C-c C-r}).  If an error is encountered, Emacs will 
rearrange the buffer so the cursor is on the bad line of the Gri command-file.
@item
If you've already run Gri, and therefore have a PostScript output file,
the mode will let you view that file (@code{gri-view}, @kbd{C-c C-v})
even if that file is compressed.
@end itemize

@noindent
Thus one never has to leave Emacs; type @kbd{C-c C-r} to run Gri, and if
there is no error, the graph comes up automatically.  If there was an error,
gri-mode will move editing point to the line with the error and display
the error message. Given that the mode can complete partially typed commands, 
this means a substantial saving in development time.

Inside gri-mode, type @kbd{C-h m} for help on the mode, including a list
of all commands and key definitions.


@c HTML <!-- newfile GriModeScreenshots.html "Gri Mode: Screenshots" "Gri Mode: Screenshots" -->

@node   Gri-mode screenshots, Screenshot 1, About Gri Mode, Emacs Mode
@comment  node-name,  next,  previous,  up
@section Gri-mode screenshots, what it looks like.
@cindex gri-mode, screenshots

@cindex screen snapshots, using Gri
@cindex snapshots of computer screen, using Gri

@comment Now handle PostScript version
@iftex
In the first screenshot, the user has entered the text
@code{set font} and has pressed @key{M-Tab} twice
to see the list of possible completions.  The
@file{*Completions*} buffer is displayed in a separate
frame because the user is using the @file{framepop.el}
add-on package.  A similar effect can be obtained using
@code{special display} buffers in Emacs.

@image{./screenshots/gri-screenshot-1, 400pt}

Here, the user has selected the command @code{set font to} and,
forgetting what valid font name could be used, then invoked @kbd{C-c
C-h} to get help about that command. The user found the needed
information and finished typing in `Helvetica'.

@image{./screenshots/gri-screenshot-2, 400pt}

Here we see the user cascading through the Gri commands pull-down menu
until @code{draw axes} is reached.

@image{./screenshots/gri-screenshot-3, 400pt}

With the output previewed in a @code{gv} window after pressing @kbd{C-c
C-v}, the user is ready to print the file using a pull-down menu.

@image{./screenshots/gri-screenshot-4, 400pt}
@end iftex

@comment Now handle more complicated HTML version
@c @ifhtml

@comment First the index images pointing to new HTML files.
@c HTML <p>
@c HTML <A HREF="ScreenShot1.html">
@c HTML <IMG ALT="Possible completions to `set font'." 
@c HTML SRC="./screenshots/gri-screenshot-1-tiny.png" ALIGN=left></A>
@c HTML gri-mode displays possible completions to entered text.
@c HTML <br clear=left>
@c HTML <p>
@c HTML <A HREF="ScreenShot2.html">
@c HTML <IMG ALT="Displaying Help about current command." 
@c HTML SRC="./screenshots/gri-screenshot-2-tiny.png" ALIGN=left></A>
@c HTML gri-mode displays help about the current command.
@c HTML <br clear=left>
@c HTML <p>
@c HTML <A HREF="ScreenShot3.html">
@c HTML <IMG ALT="Cascading the command pull-down menu." 
@c HTML SRC="./screenshots/gri-screenshot-3-tiny.png" ALIGN=left></A>
@c HTML The pull-down menu listing all gri commands.
@c HTML <br clear=left>
@c HTML <p>
@c HTML <A HREF="ScreenShot4.html">
@c HTML <IMG ALT="Getting set to print the PostScript output." 
@c HTML SRC="./screenshots/gri-screenshot-4-tiny.png" ALIGN=left></A>
@c HTML The `Perform' menu to run gri, preview, print...
@c HTML <br clear=left>
@c HTML <p>

@comment Next, generate these new HTML files (sneaky).

@menu
* Screenshot 1::
* Screenshot 2::
* Screenshot 3::
* Screenshot 4::
@end menu


@c HTML <!-- newfile ScreenShot1.html "Gri: Screenshot 1" "Screenshot 1" -->
@node   Screenshot 1, Screenshot 2, Gri-mode screenshots, Gri-mode screenshots
@comment  node-name,  next,  previous,  up
@subsection Screenshot 1

@c HTML <!--
@ifinfo
Screenshots are not visible in the info node; see the online
HTML documents.
@end ifinfo
@c HTML -->

In the first screenshot, the user has entered the text @code{set font}
and has pressed @key{M-Tab} twice to see the list of possible
completions.  The @file{*Completions*} buffer is displayed in a
separate frame because the user is using the @file{framepop.el} add-on
package.  A similar effect can be obtained using @code{special
buffers} in Emacs.

@c HTML <IMG SRC="./screenshots/gri-screenshot-1.png"></A>

@c HTML <!-- newfile ScreenShot2.html "Gri: Screenshot 2" "Screenshot 2" -->
@node   Screenshot 2, Screenshot 3, Screenshot 1, Gri-mode screenshots
@comment  node-name,  next,  previous,  up
@subsection Screenshot 2

@c HTML <!--
@ifinfo
Screenshots are not visible in the info node; see the online
HTML documents.
@end ifinfo
@c HTML -->

Here, the user has selected the command @code{set font to} and,
forgetting what valid font name could be used, then invoked @kbd{C-c
C-h} to get help about that command. The user found the needed
information and finished typing in `Courier'.
Meanwhile, an idle timer displays the default setting for this command in
the minibuffer after a few seconds of inactivity.

@c HTML <IMG SRC="./screenshots/gri-screenshot-2.png"></A>

@c HTML <!-- newfile ScreenShot3.html "Gri: Screenshot 3" "Screenshot 3" -->
@node   Screenshot 3, Screenshot 4, Screenshot 2, Gri-mode screenshots
@comment  node-name,  next,  previous,  up
@subsection Screenshot 3

@c HTML <!--
@ifinfo
Screenshots are not visible in the info node; see the online
HTML documents.
@end ifinfo
@c HTML -->

Here we see the user cascading through the Gri commands pull-down menu
until @code{draw axes} is reached.  This menu can be used to display Info
(or help) about a given command, or to insert the selection.  The default
is Info.  This menu is a good way to browse for a command when you don't
exactly remember its name.

@c HTML <IMG SRC="./screenshots/gri-screenshot-3.png"></A>

@c HTML <!-- newfile ScreenShot4.html "Gri: Screenshot 4" "Screenshot 4" -->
@node   Screenshot 4, Installing gri-mode.el, Screenshot 3, Gri-mode screenshots
@comment  node-name,  next,  previous,  up
@subsection Screenshot 4

@c HTML <!--
@ifinfo
Screenshots are not visible in the info node; see the online
HTML documents.
@end ifinfo
@c HTML -->

With the output previewed in a @code{gv} window after pressing @kbd{C-c
C-v} (or pressing the @code{gv} icon in the toolbar, or selecting it from
the @code{Perform} pull-down menu), the user is ready to print the file,
here using the @code{Perform} pull-down menu.

@c HTML <IMG SRC="./screenshots/gri-screenshot-4.png"></A>
@c @end ifhtml

@c HTML <!-- newfile InstallingGriMode.html "Gri Mode: Installation" "Gri Mode: Installation" -->
@node   Installing gri-mode.el, Step 1, Screenshot 4, Emacs Mode
@comment  node-name,  next,  previous,  up
@section Installing gri-mode.el, the nuts and bolts.
@cindex gri-mode, installing

The Emacs @file{gri-mode.el} file is now bundled with gri, so odds are
you already have it.  If not, you will find it at gri's web site
@c HTML <A HREF="http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/gri/gri/gri-mode.el">
http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/gri/gri/gri-mode.el
@c HTML </A>

The following installation steps appear a @strong{bit} complicated.
That's only because gri has changed how it gets installed a few times,
and gri-mode.el works with all of these various methods.  If you use gri
from a Linux package (Debian or Red Hat) or if you compiled it yourself using 
the default configuration, you won't need to do much.

To install @file{gri-mode.el}, follow these 4 steps.  If gri-mode is
already installed, you can skip the first two steps and move on to the
last two, in which you tell Emacs that you'd like to use Gri mode when
you edit files that end in @file{.gri}, the Gri suffix.  (Actually, if
you're using Debian linux, you can skip all of these steps since the
system will assume that you want gri-mode if you're editing a Gri file.)

@menu
* Step 1::  Placing gri-mode.el where Emacs can find it.
* Step 2::  Configuring gri-mode to where gri lives on your system.
* Step 3::  Telling emacs to load gri-mode
* Step 4::  Extra user configuration of gri-mode.
@end menu

@node   Step 1, Step 2, Installing gri-mode.el, Installing gri-mode.el
@comment  node-name,  next,  previous,  up
@subsection Placing gri-mode.el where Emacs can find it.
@cindex gri-mode, Placing gri-mode.el where Emacs can find it.

(Those using gri from gri's @strong{RPM} package, a @strong{Debian} package
or a @strong{Red Hat} package users can skip this, as it is done
for them)

Extra @file{.el} files like @file{gri-mode.el} that are not part of Emacs
should be stored in a directory where Emacs will find them when you ask
it to load them.  The files should therefore be found in Emacs'
@strong{load-path}.  To see the directory list currently in the load-path,
do this in Emacs:

@example
C-h v load-path
@end example

If you have access to system directories, put gri-mode.el in a
@strong{site-lisp} directory, such as
@file{/usr/local/share/emacs/site-lisp/} That way all users will have
access to the files.

If you don't have access to a site-lisp directory (e.g. you have only a
user account), then create a directory where your extra @file{.el} files
will be stored and add it to Emacs' load-path.  For example, say you
created the directory @file{~/emacs} and stored gri-mode.el there, you would
then put this near the top of your @file{~/.emacs} file:

@example
(setq load-path (cons "~/emacs" load-path))
@end example

@node   Step 2, Step 3, Step 1, Installing gri-mode.el
@comment  node-name,  next,  previous,  up
@subsection Telling gri-mode where gri resides
@cindex gri-mode, Configuring gri-mode to where gri lives on your system

(Those using gri from gri's @strong{RPM} package, a @strong{Debian} package
or a @strong{Red Hat} package users can skip this, as it is done
for them)

You may skip this section if gri is installed on your system as
@file{/usr/local/bin/gri-@value{GRI-VERSION}} and
@file{/usr/local/share/gri/@value{GRI-VERSION}/gri.cmd} (the default
when compiling gri yourself).  If not, then you may need to set the Emacs
variable @code{gri*directory-tree} in a startup file such as in your
@file{~/.emacs} file.

The Emacs variable @code{gri*directory-tree} is used to configure
gri-mode to tell it where Gri is installed on your system. For the
default gri installation paths used in this gri release, gri-mode
expects to find the gri executable and the file gri.cmd as:
@code{gri*directory-tree/@value{GRI-VERSION}/gri.cmd}
and @code{/usr/local/bin/gri-}@value{GRI-VERSION}
where @code{gri*directory-tree} is by default set to
@file{/usr/local/share/gri/}.

If you have only one version of gri installed on your system, gri-mode
will also look to find @file{gri.cmd} and the gri executable like so:
@enumerate
@item
Gri executable in the PATH, with startup file
@file{gri*directory-tree/gri.cmd}.
@item
Gri executable in the PATH, with startup file
@file{gri*directory-tree/lib/gri.cmd}.
@item
Gri executable @code{gri*directory-tree/bin/gri}, with startup file
@code{gri*directory-tree/lib/gri.cmd}.
@end enumerate

However, gri-mode was designed to support, and ease the use of,
@strong{multiple installed versions} of gri.  To use this feature, you
must use the gri version number as a directory name under the
@code{gri*directory-tree} path, like this:

@example
gri*directory-tree/VERSION/bin/gri
gri*directory-tree/VERSION/lib/gri.cmd
@end example

(e.g. @file{/opt/gri/2.040/bin/gri} and
@file{/opt/gri/2.040/lib/gri.cmd} with @code{gri*directory-tree} set to
@code{"/opt/gri"})

or without the @strong{lib} and @strong{bin} subdirectories if the executable is
found in the PATH named like @file{gri-VERSION} (This is the way Debian
packages are set up):
the file @file{gri*directory-tree/VERSION/gri.cmd}
and the @file{gri-VERSION} executable in the PATH
(e.g. @file{/usr/share/gri/2.1.18/gri.cmd} and
@file{/usr/bin/gri-2.1.18} with @code{gri*directory-tree} set to
@code{"/usr/share/gri"})

@strong{Important note:} You may have more than one tree and make a list
of them:

@example
(setq gri*directory-tree '("/opt/gri/" "/usr/share/gri/"))
@end example

@strong{Examples:}

@enumerate
@item
 If you use a RedHat package
 installed like:

@example
/usr/bin/gri
/usr/share/gri/gri.cmd
@end example

@noindent
then you'd also use:

@example
(setq gri*directory-tree "/usr/share/gri/")
@end example

 but gri-mode would know of only one installed version of gri.

@item
 If you use a Debian GNU/Linux installation like:

@example
/usr/bin/gri -> /usr/bin/gri-2.1.18
/usr/share/gri/2.1.18/gri.cmd
@end example

@noindent
then you'd use:

@example
(setq gri*directory-tree "/usr/share/gri/")
@end example

 Note that all gri binaries must exist in the path with version number
 suffixes (e.g. @file{gri-2.1.18}) since there is no
 @file{/usr/share/gri/2.1.18/bin/} directory (using a similar structure
 to @file{opt/gri} below) where gri-mode can find the binary
 corresponding to a given version number.

@item
 If you had multiple versions of Gri installed like so (this reflects
 the installation paths used in older gri releases): 

@example
/opt/gri/2.040/bin/gri
/opt/gri/2.040/lib/gri.cmd
/opt/gri/2.041/bin/gri
/opt/gri/2.041/lib/gri.cmd
@end example

then you'd use:

@example
(setq gri*directory-tree "/opt/gri/")
@end example

@end enumerate

@node   Step 3, Step 4, Step 2, Installing gri-mode.el
@comment  node-name,  next,  previous,  up
@subsection Telling emacs to load gri-mode
@cindex gri-mode, Telling emacs to load gri-mode

(Those using a @strong{Debian} package can skip this, as it is done
for them)

To tell emacs to use this mode with @file{.gri} files, you can load
gri-mode whenever a new emacs session is starting by adding the
following line to your @file{~/.emacs} file:

@example
(require 'gri-mode)
@end example

This is a good method when you only start emacs once a week and
use it for every file you edit (as you should).  

If you startup a fresh emacs every time you edit then you probably only
want to load gri-mode into emacs when you need it.  In that case,
instead of the @code{require} statement above, add the following lines
to your @file{~/.emacs} file:

@example
(autoload 'gri-mode "gri-mode" "Enter Gri-mode." t)
(setq auto-mode-alist (cons '("\\.gri$" . gri-mode) auto-mode-alist))
@end example

The first line tells Emacs that it will find out what it needs to know
about running the command @code{M-x gri-mode} by loading the file
@file{gri-mode.el}.  The second line tells it to run the command
@code{M-x gri-mode} when a file with extension @file{.gri} is visited
(thus using gri-mode with all those files).

@node   Step 4, Major Gri-mode commands, Step 3, Installing gri-mode.el
@comment  node-name,  next,  previous,  up
@subsection Extra user configuration of gri-mode
@cindex gri-mode, Extra user configuration of gri-mode

@strong{All users should do this at some time.}

At this point, gri-mode should start up when you edit a gri file.  You
may optionally customize gri-mode by:

@enumerate

@item 
 using the Custom interface (see the Help or Gri-Help menu or run the
 command @code{M-x gri-customize}), or

@item 
 manually setting variables in your @file{~/.emacs} file.  These are
 briefly described by typing @kbd{C-h m} while in gri-mode.  Then, for
 further infomation, use emacs' @code{describe-variable} command, bound
 to @kbd{C-h v}.  For example, for more information about the
 @code{gri*WWW-program} variable, you'd type @code{C-h v gri*WWW-program}
 (note that emacs does @key{Tab} completion, so pressing the
 @key{Tab} key after typing-in gri will display all gri related
 variables.)
@end enumerate

@c HTML <!-- newfile MajorGriModeCommands.html "Gri Mode: Major Commands" "Gri Mode: Major Commands" -->
@node   Major Gri-mode commands, Gri command names, Step 4, Emacs Mode
@comment  node-name,  next,  previous,  up
@section Major Gri-mode commands.
@cindex gri-mode, major commands

This section describes the major gri-mode commands, briefly showing how
they can increase your productivity.


@menu
* Gri command names::     How gri-mode names all gri commands.
* Possible completions::  A list of all valid commands matching so far.
* Command abbreviations:: Abbreviating many words at one time.
* Variable completion::   Completion of builtin variable and synonyms. 
* Editing the syntax::    What to do after gri-complete.
* User commands::         gri-mode knows about ~/.grirc.
* Gri code fragments::    Use them as short-cuts.
* Info interface::        Getting help about the current command.
@end menu

@c HTML <!-- newfile GriModeCommandNames.html "Gri Mode: command names" "Gri Mode: command names" -->
@node   Gri command names, Possible completions, Major Gri-mode commands, Major Gri-mode commands
@comment  node-name,  next,  previous,  up
@subsection How gri-mode names Gri commands
@cindex gri-mode, gri command names
@cindex gri-mode, how it names gri commands

A major feature of Gri mode is the completion of partially typed
commands.  Let's examine how
gri-mode decides to name gri commands.  A name is determined by removing
bracketed options from the syntax line of a given command.  This is
different from what the gri parser does.  In this way, the gri command

@example
draw label "\string" [centered|rightjustified] at .x. .y. [cm] [rotated .deg.]
@end example

@noindent
is named by gri-mode simply @code{draw label at}.  Note how the `at'
stays in the name because it is not optional.  So when you see
@code{draw label at} in gri-mode's menus or prompts, you are more likely
to associate the name with what the command actually does.

@c HTML <!-- newfile GriModeCompletions.html "Gri Mode: command completion" "Gri Mode: command completion" -->
@node   Possible completions, Command abbreviations, Gri command names, Major Gri-mode commands
@comment  node-name,  next,  previous,  up
@subsection Possible completions of gri command names
@cindex gri-mode, possible completions

When you press @key{M-tab} to complete a command name (or a variable
or synonym name as described below), gri-mode will
expand it as much as it can and do nothing further.  If you type in
nothing more and insist by using @code{gri-complete} (@key{M-tab})
again, gri-mode will respond by showing all possible completions in the
@file{*completions*} buffer.  In this way you can use
@code{gri-complete} word-by-word to abbreviate commands without ever
displaying completions, like you would for file completion in emacs or
bash.

If a completion is ambiguous, but could be exact, invoke
gri-complete a second time to complete it. e.g.

@example
sh@key{M-tab}
@end example

@noindent
expands to

@example
show
@end example

@noindent
and informs you that 12 possible completions exists; then

@example
show@key{M-tab}
@end example

@noindent
will display these completions in the completions buffer; then typing
@key{M-tab} again forces completion to a complete but not unique
possibility:

@example
show .value.|@{rpn ...@}|"\text" [.value.|@{rpn ...@}|text [...]]
@end example

Completions are shown immediately (without invoking gri-complete again)
if the completions window is already displayed or if there are 3
possibilities or less.  In this case they are displayed in the
minibuffer.

Note: The @file{*completions*} window is deleted after a command is fully
completed.  @code{gri-complete} uses its own @file{*completions*}
buffer, which is not displayed in the buffer-list to avoid clutter.

@c HTML <!-- newfile GriModeCompletions2.html "Gri Mode: command completion" "Gri Mode: command completion" -->
@node   Command abbreviations, Variable completion, Possible completions, Major Gri-mode commands
@comment  node-name,  next,  previous,  up
@subsection Command name abbreviation
@cindex gri-mode, command name abbreviation

gri-mode uses command name abbreviations in a non-Unix way in that all
words that compose the command name may be abbreviated (and not only
the word preceding the cursor).  For example, one can type in 

@example
dr x a@key{M-tab}
@end example

@noindent
and it will expand1 all the words to

@example
draw x axis [at bottom|top|@{.y. [cm]@} [lower|upper]]
@end example

This is reminiscent of VMS, which the author was used to when
gri-mode.el was initially created.  It's likely that a gri-mode.el
rewritten from scratch wouldn't have this feature since it's not part
of the Unix mindset.

@c HTML <!-- newfile GriModeCompletionVarSyn.html "Gri Mode: variable completion" "Gri Mode: variable completion" -->
@node   Variable completion, Editing the syntax, Command abbreviations, Major Gri-mode commands
@comment  node-name,  next,  previous,  up
@subsection Variable (and synonym) completion
@cindex gri-mode, variable completion
@cindex gri-mode, sysnonym completion

It's also possible to do @key{M-tab} completion on gri builtin
variable and synonym names while editing a command.  Simply type in
the leading @code{.} (dot) or @code{\} (slash) character and
invoke completion with @key{M-tab}.

For example, 

@example
..x@key{M-tab}
@end example

@noindent
displays a completions buffer listing the possible completions:

@example
..xmargin..                        ..xsize.. 
..xleft..                          ..xright.. 
..xlast..
@end example

@noindent
Typing in an extra @code{m} will complete to @code{..xmargin..} and
the following help information will be displayed in the minibuffer:

@example
margin to left of axis area. Default is 6 cm.
@end example

@c HTML <!-- newfile GriModeEditing.html "Gri Mode: editing completed syntax" "Gri Mode: editing completed syntax" -->
@node   Editing the syntax, User commands, Variable completion, Major Gri-mode commands
@comment  node-name,  next,  previous,  up
@subsection Editing the syntax output by gri-complete
@cindex gri-mode, editing gri syntax

You might wonder what to do with all the bracketed code left behind by
@code{gri-complete}.  It certainly won't go through the gri parser
without error, so you have to edit it out.
 
The tools provided in gri-mode are @code{gri-option-select} (@kbd{C-C
C-o}) and @code{gri-kill-option} (@kbd{C-C C-k}) to narrow in on a
particular gri command, given a syntax description left on the line by
@code{gri-complete}.  The cursor location is used to decide which gri
command(s) to narrow to.

For example, if @code{gri-complete} is used on the line `dr x a', the
result will be a line like 

@example
draw x axis [at bottom|top|@{.y. [cm]@} [lower|upper]]
@end example

This is the gri way of describing many commands at once.  The above
syntax description is a shortcut formulation for all of:

@example
draw x axis
draw x axis at bottom
draw x axis at bottom top
draw x axis at bottom bottom
draw x axis at top
draw x axis at top top
draw x axis at top bottom
draw x axis at .y. cm
draw x axis at .y. cm lower
draw x axis at .y. cm upper
@end example

The @code{gri-option-select} (@kbd{C-C C-o}) command provides easy
navigation to select one of these commands.  The narrowing process is
governed by the cursor position.  For example, to get the command
narrowed down to

@example
draw x axis at bottom [lower|upper]
@end example

@noindent
place the cursor somewhere in the word `bottom' and invoke
@code{gri-option-select}.  To complete the narrowing process, selecting

@example
draw x axis at bottom lower
@end example

@noindent
move the cursor to some place in the word `lower' and invoke
@code{gri-option-select again}.  On the other hand, to get

@example
draw x axis at bottom
@end example

@noindent
you would have put the cursor over either the word `lower' or `upper',
and invoke @code{gri-kill-option} (@kbd{C-C C-k}) instead.

You might want to practice using this example to learn
how to do it.  If you make a mistake, note that the normal Emacs undo
works.


@c HTML <!-- newfile GriModeUserCommands.html "Gri Mode: user commands" "Gri Mode: user commands" -->
@node   User commands, Gri code fragments, Editing the syntax, Major Gri-mode commands
@comment  node-name,  next,  previous,  up
@subsection User commands with gri-mode
@cindex gri-mode, user-defined commands

User gri commands defined in @file{~/.grirc} (@ref{Resource File}) or at
the beginning of a gri file can also be used with @code{gri-complete}.
Note that user commands are added from the current buffer whenever
`gri-mode' is invoked.  They may override previous user commands, but
not gri system commands.

@c HTML <!-- newfile GriModeCodeFragments.html "Gri Mode: code fragments" "Gri Mode: code fragments" -->
@node   Gri code fragments, Info interface, User commands, Major Gri-mode commands
@comment  node-name,  next,  previous,  up
@subsection Inserting gri code fragments in Emacs
@cindex gri-mode, gri code fragments
@cindex gri-mode, enter chunks of code with short-cuts

Since gri version 1.063, gri has special commands that begin with
a question mark `?'.  These special commands have no options, and
are composed only of standard gri commands.  Their purpose is to
provide a short-cut for entering many lines of gri at once (e.g.
bits of sample code about contouring grids, or your own preamble
which you use at the time to set fonts and line widths).

@code{gri-complete} acts in a special way with these commands, by
replacing the abbreviated name which you are completing by all the lines
contained within the gri command.

The user is allowed to define new fragments in @file{~/.grirc}, and also
to override the gri system fragments.  You can therefore fine-tune gri's
fragments to your taste.  To see the names of all gri fragments, type in
a question mark at the beginning of a line in a gri buffer and press
@key{M-Tab} twice to @code{gri-complete} it and display possible
choices.  The gri commands used to replace them are found in the
@file{*gri-syntax*} buffer.

@c HTML <!-- newfile GriModeUserInterface.html "Gri Mode: user interface" "Gri Mode: user interface" -->
@node   Info interface, Other features, Gri code fragments, Major Gri-mode commands
@comment  node-name,  next,  previous,  up
@subsection Info interface for help on current command
@cindex gri-mode, Info interface

The Info system is built into Emacs (@kbd{C-h i}), and provides an easy
method of navigation on-line help (including this manual).  We suggest
that you install the gri info files on your system (they are already
installed with packaged versions of gri in Debian or Red Hat formats).

Not only will Info (@kbd{C-h i}) be able to navigate through all of
gri's inline manual, but gri-mode's function
@code{gri-info-this-command} (@kbd{C-c C-i}) will display the correct
info page about the gri command being edited on the current line.

Additionally, gri-mode has the command @code{gri-info} (@kbd{C-c M-i})
which will prompt you (using @key{tab} completion) for any command to
list Info about.  There's also a menu-bar pull-down menu which lists all
gri commands, and you can get to Info from that too.

@c HTML <!-- newfile EmacsFeatures.html "Gri: Other Features of gri-mode" "Emacs Mode: Other Features of gri-mode" -->
@node  Other features, Dealing with many Gri versions, Info interface, Emacs Mode
@comment  node-name,  next,  previous,  up
@section Other features of gri-mode
@cindex gri-mode, imenu support
@cindex gri-mode, toolbar

@itemize @bullet
@item
@code{IMenu support}:
IMenu is a GNU/Emacs package used to source code files.  It can be
setup for a particular mode to list a menu of function definitions and
variable declarations.  In gri-mode, the IMenu is available from the
menubar and provides links to @code{new command declarations} as well
as value settings for @code{variables} and @code{synomyns}.
@item
@code{Toolbar support}: 
XEmacs21 and Emacs-21 have support for a toolbar (a set of iconic
buttons that are shortcuts for commands), however the two editors
don't not have compatible toolbar setups.  Currently gri-mode only
defines a single icon for XEmacs (to run gri on the current buffer)
and defines three for GNU/Emacs (to run gri, to view the postscript
file, and to lookup Info about the command on the current line).
@item
@code{Idle Help}: 
When GNU/Emacs sits idle with the cursor on a command line, it looks
up any defaults the command may have and displays the information in
the minibuffer.  For example, sitting on a line that says @code{set
font size 10}, it will display @code{set font size: default is 12 point in variable ..fontsize..}.  
@end itemize


@c HTML <!-- newfile Emacs4.html "Gri: Dealing with many Gri versions" "Emacs Mode: Dealing with many Gri versions" -->
@node   Dealing with many Gri versions, Filename arguments when running gri, Other features, Emacs Mode
@comment  node-name,  next,  previous,  up
@section Dealing with many Gri versions, gri-mode handles it.
@cindex gri-mode, handling multiple Gri versions

Earlier we explained that you might have many versions of gri installed
on your system (@ref{Installing gri-mode.el}).  You may use gri-mode to
access these various versions with the following gri-mode commands:

@itemize @bullet
@item
@code{gri-set-version}: 
Tells gri-mode to use a given version as the default for all your gri
files.  Tab completion is available listing all available versions (if
they are not all listed, that means that the Emacs variable
@code{gri*directory-tree} is not correctly set  
(@ref{Installing gri-mode.el})).  Your selection is stored in the file
@file{~/.gri-using-version} and is remembered across editing
sessions. If you select @strong{default} as your answer, gri-mode reverts
to using the default version of gri as installed on your system (which
may change after you update it) and deletes the
@file{~/.gri-using-version} file.

@item
@code{gri-set-local-version}: 
Tells gri-mode to use a given version of gri @strong{this} gri file
(the one currently being edited when you invoke the command).  Tab
completion is again available to list all available versions.  Your
selection overrides the default version selected by
@code{gri-set-version} for this file, and is stored as an Emacs variable
at the bottom of the gri file.  It is remembered across editing
sessions. If you select @strong{default} as your answer, gri-mode reverts
to using the default version of gri as selected by
@code{gri-set-version} and deletes the Emacs variable setting at the
bottom of the gri file.
@end itemize

@c HTML <!-- newfile Emacs5.html "Gri: Filename arguments when running gri" "Emacs Mode: Filename arguments when running gri" -->
@node Filename arguments when running gri, History, Dealing with many Gri versions, Emacs Mode
@comment  node-name,  next,  previous,  up
@section Filename arguments when running gri
@cindex gri-mode, handling filename command arguments
@cindex gri-mode, handling argv and argc

Usually, gri is run specifying only a gri command file to process, which
lends itself well to the gri-mode command @code{gri-run}.  But Gri can
be also invoked from the command line using optional arguments, usually
filenames but not necessarily, e.g.

@example
$ gri somefile.gri datafile.dat datafile2.dat ...
@end example

@noindent
or

@example
$ gri somefile.gri *.dat
@end example

The arguments are accessed with RPN operators @file{argc} and
@file{argv} (@ref{Unary Operators}).

gri-mode provides a method to set the arguments (usually filenames) to
use when @code{gri-run} is called in a specific gri script.  Use the
gri-mode command @code{gri-set-command-postarguments} to setup a
string that gri-mode will use, and the gri-mode command
@code{gri-unset-command-postarguments} to clear it.  For ease-of-use,
these commands are made available from the menubar under the
@code{Perform -> Run Settings} entries.  The specified string will be
stored in the locally-defined (aka buffer-local) variable
@code{gri-command-postarguments} and will be written within a gri
comment at the bottom of the file such that Emacs remembers it across
editing sessions.

@c HTML <!-- newfile History.html "Gri: History of Gri" "History of Gri Versions" -->
@node   History, Stable Stream, Filename arguments when running gri, Top
@comment  node-name,  next,  previous,  up
@chapter History of Gri Versions

Gri, like many modern software projects, has two ``streams'' of
development running side by side.  One is called ``stable,'' the other
``unstable.''  @emph{Most users should use the stable stream}, which
has been well tested.  (The unstable version is for users who wish to
try out new features that are under development.)

Stable versions always have an even number as the middle number in
their version designation, e.g. @code{2.6.0}, while unstable versions
always have an odd number there, e.g. @code{2.7.0}.  This middle
number indicates a sort of family of related releases.  Within a
stable stream, all versions sharing a given middle number have the
same features; new releases are made only to fix bugs.  Thus, version
@code{2.6.1} fixed bugs in version @code{2.6.0}.

To learn more about the bugs, and their resolution, visit the bugs page at
@uref{http://sourceforge.net/tracker/?func=browse&group_id=5511&atid=105511,gri.sourceforge.net}
and adjust the "status" menu to read "closed".

@menu
* Stable Stream::
* Unstable Stream::
* Deprecated Commands::
@end menu


@c HTML <!-- newfile StableStream.html "Gri: Stable Stream" "Gri: History" -->
@node   Stable Stream, Version 2.12, History, History
@comment  node-name,  next,  previous,  up
@section Stable Stream

In any given stable stream, only the version with a @code{0} as the
last number in the triplet has new features; the later versions only
correct flaws.  For example, version @code{2.6.0} offers new features
compared to any of the @code{2.4.x} versions, but @code{2.6.1} differs
only in the fixing of bugs.

@menu
* Version 2.12::
* Version 2.10::
* Version 2.8::
* Version 2.6::
* Version 2.4::
* Version 2.2::
@end menu

@c HTML <!-- newfile Version_2_12.html "Gri: Version 2.12" "Gri: Version 2.12" -->
@node   Version 2.12, Version 2.10, Stable Stream, Stable Stream
@comment  node-name,  next,  previous,  up
@subsection Version 2.12
@cindex version 2.12

@comment ADD-NEW-BUG-FIXES-HERE
@subsubsection Version 2.12.26 [2017 January 27 @uref{https://en.wikipedia.org/wiki/Martyrs%27_Day_(India), Martyrs' Day (India)}]
@strong{Bug fixes}
@itemize @bullet
@item @dots{} prevent some problems in debian build process
@end itemize


@subsubsection Version 2.12.25 [2015 July 24 @uref{https://en.wikipedia.org/wiki/Pioneer_Day_(Utah), Pioneer Day (Utah)}]
@strong{Bug fixes}
@itemize @bullet
@item @dots{} prevent some problems in debian build process
@end itemize


@subsubsection Version 2.12.24 [2013 August 9 @uref{http://en.wikipedia.org/wiki/International_Day_of_the_World%27s_Indigenous_People, International Day of the World's Indigenous People}]
@strong{Bug fixes}
@itemize @bullet
@item @dots{} obey commandline argument naming postscript file (debian bug 719033)

@end itemize


@subsubsection Version 2.12.23 [2011 July 6 @uref{http://en.wikipedia.org/wiki/Malawi, Malawai Independence Day}]
@strong{Bug fixes}
@itemize @bullet
@item
@uref{https://sourceforge.net/projects/gri/forums/forum/16975/topic/4596628/index/page/1}
@dots{} @code{pgm} images grayscale was wrong
@end itemize

@subsubsection Version 2.12.22
@strong{Bug fixes}
@itemize @bullet
@item
Fix github bug
@uref{http://github.com/dankelley/gri/issues#issue/5}
@dots{} @code{draw image} failed on some black/white images
@end itemize

@subsubsection Version 2.12.21 [2010 June 8 @uref{http://en.wikipedia.org/wiki/World_Oceans_Day, World Ocean Day}]
@strong{Bug Fixes}
@itemize @bullet
@item
Fix github bug
@uref{http://github.com/dankelley/gri/issues#issue/1}
@dots{} @code{convert grid to image directly} misplaced image ``patches'' by one patch width and one patch height
@end itemize


@subsubsection Version 2.12.20 [2010 April 9 @uref{http://en.wikipedia.org/wiki/Vimy_Ridge_Day, Vimy Ridge Day}]
@strong{New Features}
@itemize @bullet
@item
add @code{labelling} option to @code{set x axis} and @code{set y axis}.

@item
add @code{directly} option to @code{convert grid to image}.
@end itemize

@strong{Bug Fixes}
@itemize @bullet
@item
Fix SourceForge bug
@uref{https://sourceforge.net/forum/forum.php?thread_id=2913919&forum_id=16974,#2913919}
@dots{} SVG: all symbols are "." 
@item
Fix SourceForge bug
@uref{https://sourceforge.net/forum/forum.php?thread_id=2913893&forum_id=16974,#2913893}
@dots{} svg segfault on draw label
@item
Fix SourceForge bug
@uref{https://sourceforge.net/forum/forum.php?thread_id=2913841&forum_id=16974,#2913841}
@dots{} svg draw box filled not filled 
@item
Fix SourceForge bug
@uref{https://sourceforge.net/forum/forum.php?thread_id=2913840&forum_id=16974,#2913840}
@dots{} svg images are upside-down 
@item
Fix SourceForge bug
@uref{https://sourceforge.net/forum/forum.php?thread_id=2913838&forum_id=16974,#2913838}
@dots{} image postscript clip problem 
@end itemize

@subsubsection Version 2.12.19 [2009 July 17 @uref{http://en.wikipedia.org/wiki/World_Day_for_International_Justice, World Day for International Justice}]

@strong{New Features}
@itemize @bullet
@item
Fix SourceForge ``bug''
@uref{https://sourceforge.net/forum/forum.php?thread_id=2977816&forum_id=16974,#2977816}
@dots{} Fedora packaging requires more precise license declarations.
@end itemize

@strong{Bug Fixes}
@itemize @bullet
@item
Fix SourceForge bug
@uref{https://sourceforge.net/forum/forum.php?thread_id=3266884&forum_id=16974,#3266884}
@dots{} error in docs for strlen.
@end itemize


@subsubsection Version 2.12.18 [2008 Sep 8 @uref{http://en.wikipedia.org/wiki/International_Literacy_Day, International Literacy Day}]

@strong{Bug Fixes}
@itemize @bullet

@item
Improve security of temporary-file handling.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=1985862&group_id=5511&atid=105511,#1985862}
@dots{} SVG output had axis linewidth equal to curve line width.

@end itemize


@subsubsection Version 2.12.17 [2008 May 29 @uref{http://en.wikipedia.org/wiki/Oak_Apple_Day, Oak Apple Day (England)}]

@strong{New Features}
@itemize @bullet

@item  Add GNU readline support so that interactive mode will have history, command editing, etc.

@end itemize

@strong{Bug Fixes}
@itemize @bullet

@item
Fix SourceForge bug
@uref{https://sourceforge.net/tracker/?func=detail&atid=105511&aid=1913577&group_id=5511,#1913577}
@dots{} superscripts did not end correctly, if preceeded by an inline @code{@{@}} block.

@item
Fix SourceForge bug
@uref{https://sourceforge.net/tracker/index.php?func=detail&aid=1761562&group_id=5511&atid=105511,#1761562}
@dots{} y axis name printed upside down, for log axes in which user specified a high values at the bottom end of the axis

@end itemize


@subsubsection Version 2.12.16 [2007 Jul 20 @uref{http://en.wikipedia.org/wiki/Apollo_11, anniversary of the first moon landing}]

@strong{Bug Fixes}
@itemize @bullet

@item
Fix Debian bug
@uref{http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=130802,#130802}
@dots{} postscript problem in landscape mode, refreshed in gv viewer

@item
Fix Debian bug
@uref{http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=434010,#434010}
@dots{} @code{set page landscape} requires @code{set page size} first, but it should really default to something reasonable instead.

@end itemize


@subsubsection Version 2.12.15 [2007 Apr 16 @uref{http://en.wikipedia.org/wiki/Mawlid, celebration of birthday of Muhammad}]

@strong{Bug Fixes}
@itemize @bullet

@item
Fix SourceForge bug
@uref{https://sourceforge.net/tracker/index.php?func=detail&aid=1700978&group_id=5511&atid=105511,#1700978}
@dots{} html concept index mostly broken

@item
Fix SourceForge bug
@uref{https://sourceforge.net/tracker/index.php?func=detail&aid=1698924&group_id=5511&atid=105511,#1698924}
@dots{} box plots show missing data

@item
Fix Debian bug #417217
@dots{} will not compile in GCC 4.3

@item
Fix SourceForge bug
@uref{https://sourceforge.net/tracker/index.php?func=detail&aid=1698116&group_id=5511&atid=105511,#1698116}
@dots{} poorly-positioned name of RHS y-axis

@end itemize


@subsubsection Version 2.12.14 [2007 Jan 08: @uref{http://en.wikipedia.org/wiki/Seijin_shiki, Coming-of-Age Day (Japan)}]
@strong{Bug Fixes}
@itemize @bullet

@item
Fix SourceForge bug
@uref{https://sourceforge.net/tracker/index.php?func=detail&aid=1630768&group_id=5511&atid=105511,#1630768}
@dots{} Fix to segfault in clipped images (a bug that may have developed after version 2.13.3)
@end itemize


@subsubsection Version 2.12.13 [2006 Nov 06: @uref{http://en.wikipedia.org/wiki/Public_holidays_in_Tajikistan, Constitution Day (Tajikistan)}]
@strong{Bug Fixes}
@itemize @bullet

@item
Fix SourceForge bug
@uref{https://sourceforge.net/tracker/index.php?func=detail&aid=1591475&group_id=5511&atid=105511,#1591475}
@dots{} Fix to compile in Solaris CC

@item
Fix SourceForge bug
@uref{https://sourceforge.net/tracker/index.php?func=detail&aid=1591062&group_id=5511&atid=105511,#1591062}
@dots{} Fix to compile in OpenBSD

@end itemize

@subsubsection Version 2.12.12 [2006 July 16: @uref{http://en.wikipedia.org/wiki/Yellow_Pig%27s_Day,Yellow Pigs Day}]
@strong{Bug Fixes}
@itemize @bullet

@item
Fix SourceForge bug
@uref{https://sourceforge.net/tracker/index.php?func=detail&aid=1523033&group_id=5511&atid=105511,#1523033}
@dots{} Malloc error (freeing something already freed?)

@item
Fix SourceForge bug
@uref{https://sourceforge.net/tracker/index.php?func=detail&aid=1523032&group_id=5511&atid=105511,#1523032}
@dots{} @code{create columns from function} bug, if there is an existing directory called @code{tmp}.

@item
Fix SourceForge bug
@uref{https://sourceforge.net/tracker/index.php?func=detail&aid=1491105&group_id=5511&atid=105511,#1491105}
@dots{} @code{set x axis labels} had no affect for log axes (same for y)

@end itemize


@subsubsection Version 2.12.11 [2006 Mar 30: Hindu New Year]
@strong{Bug Fixes}
@itemize @bullet
  
@item
Fix SourceForge bug
@uref{https://sourceforge.net/tracker/index.php?func=detail&aid=1449546&group_id=5511&atid=105511,#1449546}
@dots{} x axis limits not correctly inferred from @code{set x grid} (same for y).

@end itemize

@subsubsection Version 2.12.10 [2006 Jan 26: Australia Day]
@strong{Bug Fixes}
@itemize @bullet
  
@item
Fix SourceForge bug
@uref{https://sourceforge.net/tracker/?func=detail&atid=105511&aid=1408259&group_id=5511
,#1408259}
@dots{} PostScript file contained private information.  This was fixed by adding
new commandline arguments @code{-private} and @code{-no_private}, the
former of which (the new default) means to not include the user's name,
the invocation arguments, or the command-file contents (@ref{Invoking Gri}).

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=12851803&group_id=5511&atid=105511,#1285180}
@dots{} NaN was mishandled.  (The bug may have arisen in version 2.12.7 or thereabouts.)

@item
Port to the @uref{http://www.freebsd.org/,FreeBSD} operating system,
with help from Christopher Illies and Roman Neuhauser.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=1217273&group_id=5511&atid=105511,#1217273}
@dots{} missing some version numbers within docs

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=1196613&group_id=5511&atid=105511,#1196613}
@dots{} user-supplied x-axis labels can run offscale (fix for y-axis later...)

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=1198341&group_id=5511&atid=105511,#1198341}
@dots{} x-axis labels incorrectly rotated (sometimes)

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=1199280&group_id=5511&atid=105511,#1199280}
@dots{} warning about @code{malloc} for RPN assignments

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=1196115&group_id=5511&atid=105511,#1196115}
@dots{} @code{gri_unpage} and @code{gri_merge} mis-installed

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=1153209&group_id=5511&atid=105511,#1153209}
@dots{} Emacs mode incompatible with new version of @code{gv} PostScript viewer

Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=1101172&group_id=5511&atid=105511,#1101172}
@dots{} @code{gri -help} incorrectly stated meaning of last argument(s)

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=835711&group_id=5511&atid=105511,#835711}
@dots{} @code{draw gri logo} fails.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=1098269&group_id=5511&atid=105511,#1098269}
@dots{} problem compiling on AMD64 machine.  (Solution provided by Andreas Jochens, a Debian user.)

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=867515&group_id=5511&atid=105511,#867515}
@dots{} problem with junk appearing in images.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=875881&group_id=5511&atid=105511,#875881}
@dots{} problem compiling with gcc 2.95.3 compiler.

@end itemize


@subsubsection Version 2.12.9 [2005 Jan 6: @uref{http://en.wikipedia.org/wiki/Epiphany_%28feast%29,Feast of Epiphany}]
@strong{Bug Fixes}
@itemize @bullet

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=1094087&group_id=5511&atid=105511,#1094087}
@dots{} @code{set path to} incorrectly parsed colon-separated paths

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=1085788&group_id=5511&atid=105511,#1085788}
@dots{} @code{image *=}, @code{image /=}, @code{image ^=}, and @code{image _=} all gave incorrect results

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=1084123&group_id=5511&atid=105511,#1084123}
@dots{} does not compile in fink


@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=676767&group_id=5511&atid=105511,#676767}
@dots{} on fink systems, @code{help} does not work

@end itemize


@subsubsection Version 2.12.8 [2004]
@strong{Bug Fixes}
@itemize @bullet

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=1019141&group_id=5511&atid=105511,#1019141}
@dots{} @code{draw arc} ignores the present pen color


@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=997741&group_id=5511&atid=105511,#997741}
@dots{} PostScript broken on images with y-axis decreasing, and enclosed by PostScript clipping


@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=978822&group_id=5511&atid=105511,#978822}
@dots{} documentation wrong on @code{set path to}

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=932203&group_id=5511&atid=105511,#932203}
@dots{} misplaced labels caused by @code{set x axis labels}

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=928277&group_id=5511&atid=105511,#928277}
@dots{} @code{draw polygon} should take @code{cm} and @code{pt} units

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=930259&group_id=5511&atid=105511,#930259}
@dots{} fix @code{draw arc}'s drawing of an extra line (thanks for the fix, Wolfgang Voegeli)

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=923719&group_id=5511&atid=105511,#923719}
@dots{} @code{draw curve overlying} ignored the effect of @code{set dash}

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=914125&group_id=5511&atid=105511,#914125}
@dots{} offpage points in axes were reported as having been drawn by @code{draw curve}.


@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=877613&group_id=5511&atid=105511,#877613}
@dots{} @code{help} (and other commands using temporary files) does not work in OSX/Fink version.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=874483&group_id=5511&atid=105511,#874483}
@dots{} @code{state save} doesn't keep track of @code{dash} settings.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=873245&group_id=5511&atid=105511,#873245}
@dots{} inaccurate times are given in the warnings about slow operations on OSX platform (days are reported instead of seconds)

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=871477&group_id=5511&atid=105511,#871477}
@dots{} the `missing value' feature should not be the default.  The solution
involved adding a new command @code{set missing value none}, which 
is now the default.

@end itemize


@subsubsection Version 2.12.7 [2003 Sep 4]

@strong{Bug Fixes}
@itemize @bullet

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=800022&group_id=5511&atid=105511,#800022}
AKA Debian bug
@uref{http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=208589,#208589}, 
@dots{} did not build on some Debian platforms because it was based 
on an old version of @code{automake}.

@end itemize


@subsubsection Version 2.12.6 [2003 Sep 1: Labour Day]

@strong{New Features}
@itemize @bullet

@item
Add @code{age} RPN function, for testing file ages (@ref{age-rpn-operator}).

@end itemize

@strong{Bug Fixes}
@itemize @bullet

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=773850&group_id=5511&atid=105511,#773850}
@dots{} bounding-box is increased by @code{draw symbol} even if (rectangular) postscript clipping is active.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=760130&group_id=5511&atid=105511,#760130}
@dots{} Solaris cannot compile with @key{C-l} in Makefile.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=743134&group_id=5511&atid=105511,#743134}
@dots{} bounding box not limited by @code{set clip postscript}

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=750561&group_id=5511&atid=105511,#750561}
@dots{} during compilation, @code{make} rebuilds HTML docs even if up-to-date

@end itemize



@subsubsection Version 2.12.5 [2003 May 19: Victoria Day]

@strong{New Features}
@itemize @bullet
@item
Apply a patch provided Kawamura Masao, relating to (a) errors in the
documentation of file locations and (b) a programming error hidden
behind an unset precompiler flag.

@item
Add hexadecimal colornames (@ref{pen-color-hexadecimal}).

@end itemize

@strong{Bug Fixes}
@itemize
@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=739761&group_id=5511&atid=105511,#739761}
@dots{} @code{draw time stamp} named the command-file incorrectly

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=720607&group_id=5511&atid=105511,#720607}
@dots{} the emacs mode looked for html documentation files in an incorrect location on linux/redhat systems

@end itemize


@subsubsection Version 2.12.4 [2003 Apr 06]
@strong{Bug Fixes}
@itemize
@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=696073&group_id=5511&atid=105511,#696073}
@dots{} did not handle @code{\$()} syntax correctly.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=715884&group_id=5511&atid=105511,#715884}
@dots{} mixup on protected-quotes within double-quoted strings

@item
Fix Debian bug
@uref{http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=183912,#183912}
@dots{} would not compile on m86k architecture.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=711354&group_id=5511&atid=105511,#711354}
@dots{} @code{Creator:} comment in PostScript file named the command-file incorrectly,
if there were options on the gri invocation command.  Since this naming of the
command-file was not especially useful, and since nobody has complained of this bug
but the author, the feature has simply been deleted.  Just complain if you want it back!

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=706202&group_id=5511&atid=105511,#706202}
@dots{} A hint about the page orientation was not given in the Postscript
comments.  The lack of this hint has no affect on printing, etc.,
only viewing in some viewers.

@end itemize


@subsubsection Version 2.12.3 [2003 Mar 1]
@strong{Bug Fixes}
@itemize
@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=685919&group_id=5511&atid=105511,#685919}
@dots{} @code{-output} commandline argument failed on @file{.eps} file extension.

@end itemize


@subsubsection Version 2.12.2 [2003 Feb 7: Munro Day at @uref{http://www.dal.ca/,Dalhousie University}]

@strong{Bug Fixes}

@itemize
 
@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=675304&group_id=5511&atid=105511,#675304}
@dots{} Segmentation fault can occur on @code{read image pgm}
if an image already exists, e.g. created by
@code{convert grid to image}.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=647234&group_id=5511&atid=105511,#647234}
@dots{} Source file @file{draw.cc} will not compile on MAC OS X 10.1.5 at optimization level 2, so drop the level to no optimization, as a temporary measure.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=671022&group_id=5511&atid=105511,#671022}
@dots{} @code{flip image x|y} did not flip images correctly, except in special circumstances.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=669603&group_id=5511&atid=105511,#669603}
@dots{} @code{skip backward .n.} erroneously skipped forward

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=667754&group_id=5511&atid=105511,#667754}
@dots{} @code{read image pgm} segfaults on memory if an image has already been created by @code{convert grid to image}

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=664388&group_id=5511&atid=105511,#664388}
@dots{} @code{read image pgm} fails if an image already exists

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=654129&group_id=5511&atid=105511,#654129}
@dots{} ignoring @file{~/.grirc} file

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=654127&group_id=5511&atid=105511,#654127}
@dots{} configure scripts are broken

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=649132&group_id=5511&atid=105511,#649132}
@dots{} removed unused LDFLAGS phrase from Makefile

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=649134&group_id=5511&atid=105511,#649134}
@dots{} tweak gcc optimization

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=649136&group_id=5511&atid=105511,#649136}
@dots{} examples 8 and 9 broken

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=641406&group_id=5511&atid=105511,#641406}
@dots{} RPN too aggressive on missing values

@end itemize


@subsubsection Version 2.12.1 [2002 Sep 25]
@strong{Bug Fixes}

@itemize

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=613075&group_id=5511&atid=105511,#613075}
@dots{} RPN operators @code{sin}, @code{cos}, and @code{tan} were limited in range (new bug in last release)

@end itemize



@subsubsection Version 2.12.0 [2002 Sep 15: @uref{http://www.terryfox.org/,Terry Fox Day}, Canada.]

@strong{New Features}

@itemize @bullet

@item
Add @code{sed} RPN operator, to work on strings @ref{Binary Operators}.

@item
Add @code{skewness} and @code{kurtosis} RPN operators, to work on 
columns @ref{Manipulation of Columns etc}.

@end itemize


@strong{Removed Features}

@itemize

@item
n/a

@end itemize


@strong{Bug Fixes}

@itemize

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=606303&group_id=5511&atid=105511,#606303}
@dots{} web-pages were not valid html-4.0.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=593958&group_id=5511&atid=105511,#593958}
@dots{} missing-values should be ignored if they occur in intermediate results of RPN calculations.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=600395&group_id=5511&atid=105511,#600395}
@dots{} won't compile with recently released version (3.2) of GCC compiler.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=600223&group_id=5511&atid=105511,#600233}
@dots{} segfaults if some RPN operators are used on stacks that do
not contain enough entries (e.g. @code{show @{rpn cosh@}}). 
@end itemize


@c HTML <!-- newfile Version_2_10.html "Gri: Version 2.10" "Gri: Version 2.10" -->
@node   Version 2.10, Version 2.8, Version 2.12, Stable Stream
@comment  node-name,  next,  previous,  up
@subsection Version 2.10
@cindex version 2.10

@subsubsection Version 2.10.1 [2002 Jun 1]

@strong{Bug Fixes}

@itemize

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=562911&group_id=5511&atid=105511,#562911}
@dots{} won't build with @file{gcc-3.0} compiler.  This was reported by
the Debian hppa builder as Debian bug
@uref{http://bugs.debian.org/148572,#148572}.


@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=562558&group_id=5511&atid=105511,#562558}
@dots{} @code{draw title} terminates program if have non-positive data and had initially specified log axes.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=562014&group_id=5511&atid=105511,#562014}
@dots{} won't build if @code{popt} library is unavailable.  This was reported by
the Debian ia64 builder as Debian bug
@uref{http://bugs.debian.org/148493,#148493}.


@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=558463&group_id=5511&atid=105511,#558463}
@dots{} in HTML docs, the ``press'' margin tag was misdirected.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=562017&group_id=5511&atid=105511,#562017}
@dots{} parser fails with DOS end-of-line.

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=562113&group_id=5511&atid=105511,#562113}
@dots{} @code{new page} postscript error in @file{gv} viewer.

@end itemize


@subsubsection Version 2.10.0 [2002 May 20: Victoria Day]

@strong{New Features}

@itemize @bullet

@item
In the documentation, change the names of some variables to be
clearer: @code{ll_x} is now written @code{xleft}, etc.

@item
Add RPN binary operators @code{and}, @code{or} for logical operations
@ref{Binary Operators}, along with negation operator @code{not}
@ref{Unary Operators}.

@item
Add @code{draw arc} command (@ref{Draw Arc}).

@item
Add @code{set x axis labels} (@ref{Set X Axis}) and
@code{set y axis labels} (@ref{Set Y Axis}) commands.

@item
Permit specification of @code{pt} units for 
@code{draw label} (@ref{Draw Label}), 
@code{draw box} (@ref{Draw Box}),
@code{draw symbol at} (@ref{Draw Symbol At}),
and
@code{draw line from} (@ref{Draw Line From}).

@item
Add @code{set clip to curve} (@ref{Set Clip}) command. 
@emph{Caution:} this
needs extension, and may have a bug if called twice in succession [but
is this with an intervening @code{set clip off}]

@item
Add @code{group} and @code{end group} commands, in preparation for SVG
output.  So far these commands do nothing, and are basically just a
signal that users should not create commands with these names since Gri
will need them soon.

@item
Add @code{..xinc..} and @code{..yinc..} builtin variables (@ref{Axis Scaling}).

@item
Make the @code{open} command accept URLs as filenames (@ref{Open}).

@end itemize



@strong{Removed Features}

@itemize

@item
Remove @code{gri -repair old.ps new.ps} since (a) it was only half
functional, (b) it was hard to code in the new scheme of
argument-processing and (c) the author was not aware of anybody every
having used it.

@item
Make the @code{-chatty} commandline option require a value (@ref{Invoking Gri}).

@end itemize



@strong{Bug Fixes}

@itemize

@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=552009&group_id=5511&atid=105511">
#552009
@c HTML </a>
(@code{rpn} can segfault if @code{!=} operator is written as @code{=!})

@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=546109&group_id=5511&atid=105511">
#546109
@c HTML </a>
(bounding box wrong if postscript clipping used)
@c HTML </a>

@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=514495&group_id=5511&atid=105511">
#514495
@c HTML </a>
in which @code{set clip to curve} failed to handle missing values in the curve.
@c HTML </a>

@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=450465&group_id=5511&atid=105511">
#450465
@c HTML </a>
(@code{create columns from function} was broken).

@end itemize




@c HTML <!-- newfile Version_2_8.html "Gri: Version 2.8" "Gri: Version 2.8" -->
@node   Version 2.8, Version 2.6, Version 2.10, Stable Stream
@comment  node-name,  next,  previous,  up
@subsection Version 2.8

@subsubsection Version 2.8.7 [2002 Apr 03]
@itemize @bullet
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=482120&group_id=5511&atid=105511">
#482120
@c HTML </a>
(@code{regress} ignores data weights)
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=508657&group_id=5511&atid=105511">
#508657
@c HTML </a>
(missing backslash in drawing undefined synonyms)

@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=523450&group_id=5511&atid=105511">
#523450
@c HTML </a>
(log axes detect non-positive values too late)
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=521045&group_id=5511&atid=105511">
#521045
@c HTML </a>
(installation/compilation with Solaris Workshop V6 Update 2 compiler)
@end itemize



@subsubsection Version 2.8.6 [2002 Feb 14]
@itemize @bullet
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=513002&group_id=5511&atid=105511">
#513002
@c HTML </a>
(minor documentation error in @code{set clip})
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=509592&group_id=5511&atid=105511">
#509592
@c HTML </a>
(HTML docs had midordered indices)
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=506534&group_id=5511&atid=105511">
#506534
@c HTML </a>
(map axes give wrong minutes in negative regions).  Thanks, Brian, for the patch on this!
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=508088&group_id=5511&atid=105511">
#508088
@c HTML </a>
(grimode: gv should update, not be relaunched)
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=506490&group_id=5511&atid=105511">
#506490
@c HTML </a>
(@code{-v} commandline option returned wrong version number)
@end itemize


@subsubsection Version 2.8.5 [2001 Dec 13]
@itemize @bullet
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=492472&group_id=5511&atid=105511">
#492472
@c HTML </a>
(@code{inf} rpn operator caused segfault)
@end itemize

@subsection Version 2.8.4 [2001 Oct 4]
@itemize @bullet
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=467973&group_id=5511&atid=105511">
#467973
@c HTML </a>
(@code{gri -version} gave wrong version number, breaking the Emacs Gri mode.)
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=468014&group_id=5511&atid=105511">
#468014
@c HTML </a>
(@code{draw grid} disobeyed pencolor.)
@end itemize

@subsubsection Version 2.8.3 [2001 Oct 1]
@itemize @bullet
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=462243&group_id=5511&atid=105511">
#462243
@c HTML </a>
(endian problem in Rasterfile images + reading problem in PGM images).
@end itemize

@subsubsection Version 2.8.2 [2001 Sep 19]
@itemize @bullet
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=461444&group_id=5511&atid=105511">
#461444
@c HTML </a>
(wouldn't compile with the @code{mingw32} compiler, for windows 32 machines). 
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=454557&group_id=5511&atid=105511">
#454557
@c HTML </a>
(wouldn't compile with the pre-release version 3.0.1 of the GNU c++ compiler,
in the case in which netCDF was already installed)
@end itemize

@subsubsection Version 2.8.1 [2001 Sep 7]
@itemize @bullet
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=450465&group_id=5511&atid=105511">
#450465
@c HTML </a>
(@code{create columns from function} was broken).
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=454557&group_id=5511&atid=105511">
#454557
@c HTML </a>
(wouldn't compile with the pre-release version 3.0.1 of the GNU c++ compiler)
@end itemize


@subsection Version 2.8.0 [2001 Jul 30]

@b{New command syntax}
@itemize @bullet
@item
Add @code{unlink} command as a unix-familiar way to delete files
(@ref{Unlink}).
@item
Add @code{set page size} command to clip to a given page size
(@ref{Set Page}).
@item
Add @code{substr} RPN operator to permit extraction of sub-strings
(@ref{Tertiary Operators}).
@item
Add @code{default} possibility for the @code{set x name} and the
@code{set y name} commands.
@item
@cindex underscore, in numbers
@cindex numbers, using underscore to separate thousand parts
@cindex thousand parts, indicating in numbers using underscore
Add Perl-like ability to put underscores in numerical constants, to
guide your eye.  These underscores are ignored by Gri, so that for
example @code{.v. = 1_000} and @code{.v. = 1000} are equivalent as far
as Gri is concerned.
@end itemize

@b{Emacs mode} (@ref{Emacs Mode})
@itemize @bullet
@item
Give @key{M-Tab} the
ability to complete builtin variables and synonyms as well as
commands
@item
Add ``idle-timer minibuffer help'' to display defaults for builtin
variables under the cursor.
@item
Add fontification of builtin variables @emph{only}
if they are spelled correctly.
@end itemize


@b{Developer changes}
@itemize @bullet
@item
Add @code{make source-arch-indep} target in sources.  This will build a
source tar file in which all the architecture-independent material
(documentation in HTML, postscript and Info formats) is pre-made.  This
makes it easier to install gri on a host that doesn't have TeX and
ImageMagick installed.
@item
Complete the port to IBM's compiler for their AIX operating system.
@end itemize


@c HTML <!-- newfile Version_2_6.html "Gri: Version 2.6" "Gri: Version 2.6" -->
@node   Version 2.6, Version 2.4, Version 2.8, Stable Stream
@comment  node-name,  next,  previous,  up
@subsection Version 2.6

@subsection Version 2.6.4 [2001 Jul 9: Dan's birthday]
@itemize @bullet
@item
Fix SourceForge bug 
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=435688&group_id=5511&atid=105511">
#435688
@c HTML </a>
(remnants of @code{polar} column type, no longer supported, remained in documentation)
@item
Fix SourceForge bug 
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=435603&group_id=5511&atid=105511">
#435603
@c HTML </a>
(@code{set dash} produced broken PostScript)
@item
Fix SourceForge bug 
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=431114&group_id=5511&atid=105511">
#431114
@c HTML </a>
(@code{-0} could appear on axes)
@end itemize

@subsection Version 2.6.3 [2001 Jun 22]
@itemize @bullet
@item
Fix SourceForge bug 
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=433250&group_id=5511&atid=105511">
#433250
@c HTML </a>
(@code{draw symbol} ignored dashing state sometimes)
@item
Fix SourceForge bug 
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=432549&group_id=5511&atid=105511">
#432549
@c HTML </a>
(contours sometimes unlabelled)
@item
Tweak internal coding for compilation on AIX compilers.
@end itemize



@subsubsection Version 2.6.2 [2001 May 19]
@itemize @bullet
@item
Fix SourceForge bug 
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=425174&group_id=5511&atid=105511">
#425174
@c HTML </a>
(synonym interpolation broken on e.g. @code{show "[\syn]"}
@item
Fix SourceForge bug 
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=425175&group_id=5511&atid=105511">
#425175
@c HTML </a>
(@code{while !..eof..} acted ignored end of file)
@end itemize


@subsubsection Version 2.6.1 [2001 May 10]
@itemize @bullet
@item
Fix SourceForge bug 
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=420499&group_id=5511&atid=105511">
#420499
@c HTML </a>
(gri-mode.el compatibility issues with emacs-21;  Mostly bad old code.)
@item
Fix SourceForge bug 
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=421076&group_id=5511&atid=105511">
#421076
@c HTML </a>
(byte-compiled gri-mode.el has broken IMenu support;  Affects Debian package.)
@item
Fix SourceForge bug 
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=419599&group_id=5511&atid=105511">
#419599
@c HTML </a>
(wouldn't compile under GNU g++ 3.x compiler)
@item
Fix SourceForge bug 
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=418065&group_id=5511&atid=105511">
#418065
@c HTML </a>
(documentation mentions back-tic notation, which is not available)
@item
Fix SourceForge bug 
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=417333&group_id=5511&atid=105511">
#417333
@c HTML </a>
(vague error message @code{RPN string operator})
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=415277&group_id=5511&atid=105511">
#415277
@c HTML </a>
(make fails on MSDOS)
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=415149&group_id=5511&atid=105511">
#415149
@c HTML </a>
(@code{file.cc} parse error on MSDOS)
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=414520&group_id=5511&atid=105511">
#414520
@c HTML </a>
(@code{draw symbol ... at} should automatically produces axes unless the location is in @code{cm} coordinates)
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=414010&group_id=5511&atid=105511">
#414010
@c HTML </a>
(items in the html concept index were in an odd order)
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=413986&group_id=5511&atid=105511">
#413986
@c HTML </a>
(@code{~username} was broken in @code{open})
@item
Fix SourceForge bug
@c HTML <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=411904&group_id=5511&atid=105511">
#411904
@c HTML </a>
(@code{/} was ugly in math mode)
@end itemize


@subsubsection Version 2.6.0 [2001 April 1]
@itemize @bullet
@item
Permit @code{rewind} to take a filename.
@item
Make @code{open} set @code{\.return_value.} to the full pathname of the
file that was opened.
@item
Add @code{set path} command (@ref{Set Path To}).
@item
Remove functioning of @code{GRIINPUTS} environment variable, since this
is more cleanly handled with the newly added @code{set path to} command
(@ref{Set Path To}).
@item
Remove @code{\.awk.} synonym, which was deemed to be unhelpful.  Users
with many scripts that use this variable might wish to put a line like
@example
\.awk. = "gawk"
@end example
in their @file{~/.grirc} file.
@item
Change the format of images in the PostScript output file, as a
workaround for a bug in the @code{ps2pdf} program.
@item
Add ``ampersand'' (@code{\&} and @code{\&&})
syntax to permit newcommands to
look up the name and nesting level of changeable arguments
(@ref{Changeable Command Arguments}).
@item
Add ``at-sign'' (@code{@@}) syntax for aliases
(@ref{Alias Synonyms}).
@item
Add ability to embed newlines in @code{show} 
commands with the @code{\<<} sequence (@ref{Show}).
@item
Add ability to embed TAB characters in @code{show} 
commands with the @code{\>>} sequence (@ref{Show}).
@item
Make various @code{read} commands (@ref{Read}) able to decode synonyms
as well as variables and simple numbers.
@item
Add @code{strlen} RPN operator (@ref{Unary Operators}).
@item
Add @code{default} option to @code{set x format} and 
@code{set y format} commands.
@item
Add @code{new postscript file} (@ref{New Postscript File}) command.
@item
Switch email list from @code{majordomo} to GNU @code{mailman}.
@item
No longer remove comments from data lines that are read.  This served
little function, interfered with recent user code, and could be
accomplished by reading through a @code{sed} pipe in any case.
@item
Make the first element of the @code{argv} array be the name of 
the command-file.  (This makes Gri consistent with languages such
as C.)
@item
Add chapter on test suite (@ref{Test Suite}).
@item
Let newcommands have changeable arguments (@ref{Changeable Command Arguments}).
@item
Remove @code{-s} as an abbreviation for the commandline option @code{-superuser}.
@item
Remove the @code{:} syntax from the commandline options.
@item
Add commandline option @code{-output PS_file_name}.
@item
Add @code{assert} command (@ref{Assert}).
@item
Add test suite (mainly for developers).
@item
Add @code{sleep} command (@ref{Sleep}).
@item
Remove command @code{show hint of the day}, since I no longer permission
to use cgi-bin to provide the hints via web-server.
@item
Permit indexing of synonym words with variables, in addition to
constants.
@item
Fix bug in interpolating synonyms in the test-expression of @code{while} loops.
@item
Put source on the
Source Forge open-source development website, at
@url{http://gri.sourceforge.net}.
Gri users can benefit from this site in may ways.  First, it is a great
way to keep track of new versions.  With a mouse-click you can cause
SourceForge to email you whenever a new version of Gri is released.
Second, SourceForge has
newsgroups
(@url{http://sourceforge.net/forum/?group_id=5511})
and email lists
(@url{http://sourceforge.net/mail/?group_id=5511})
devoted to Gri.  These are archived, so that you can stop monitoring
them for a while and then go back and see what you've missed.  Third,
Source Forge has a powerful
bug-tracking facility.
(@url{http://sourceforge.net/bugs/?group_id=5511})
With this you may check for existing bugs reported by users, submit new
bug reports, and also track the process of bug removal (e.g. optionally
receiving emails when the bug is removed).
@item
Add @code{set colorname} command (@ref{Set Colorname}).
@item
Add @code{source} command (@ref{Source}).
@item
Add RPN operators @code{wordc} (@ref{Solitary Operators}) and
@code{wordv} (@ref{Unary Operators}) for accessing the words in the
present Gri command.
@item
Add RPN operators @code{argc} (@ref{Solitary Operators}) and
@code{argv} (@ref{Unary Operators}) for accessing the command-line
arguments used when Gri was invoked from the operating system.
@item
Add automatic support for compressed data files.  So far, this only
works with gzipped files (@ref{Open}).
@item
Add two new RPN operators, @code{file_exists} and
@code{directory_exists} (@ref{Unary Operators}).
@item
Reorganize parts of manual (e.g.  changing the section about the Emacs
@file{gri-mode.el} into a chapter, with screen snapshots).
@item
Improve the HTML form of the manual (e.g. color-code the Gri syntax in
examples, provide access to all the indices, use Jpeg format, et.).
@item
Add several new features to @code{gri-mode.el}:

1) Add a menubar pull-down menu listing all Gri commands,
      allowing the user to get @code{Help} or @code{Info} on any command or
      @code{Insert} it in the current Gri file.

2) Add a menubar pull-down entry to @code{Perform} to set
      @code{gri-run} settings such as flag options passed to gri. 

3) Gri info file can have @strong{.info} extension now.

4) Made @code{gri-apropos} an alias for @code{gri-help-apropos}.

5) gri-mode now uses the customize interface (See
      @code{gri-customize}).

6) The @code{~/.gri-syntax} file has changed format.  As a
      side-effect, spaces are used instead of hyphens to display Gri commands,
      and one can now select a command with the mouse in the
      @strong{Completions} buffer.

@end itemize



@c HTML <!-- newfile Version_2_4.html "Gri: Version 2.4" "Gri: Version 2.4" -->
@node   Version 2.4, Version 2.2, Version 2.6, Stable Stream
@comment  node-name,  next,  previous,  up
@subsection Version 2.4

@subsubsection Version 2.4.4 [2000 May 7]
Change so that only a warning is printed if mathematical operations are
requested on empty arrays (e.g. @code{y += 10}).  Previously, an error
was reported and Gri exited with an error condition, which is bothersome
in scripts that rely on successful completion of the Gri job.

Port to the BeOS operating system.

@subsubsection Version 2.4.3 [2000 Apr 1]
Change location of all files, to be consistent with Redhat convention.
Previously, things were in @code{/opt/gri}; now they are in more
standard locations.

@subsubsection Version 2.4.2 [2000 Mar 25]
Remove bug in which @code{convert grid to image} produced incorrect
images, visible as a patchy appearance with coarse grids.

@subsubsection Version 2.4.1 [2000Jan 31]
Remove bug in which @code{convert image to grid} failed to take note of
the gri minimum and maximum, so that contouring of the grid was not
possible for grids created from images.

@subsubsection Version 2.4.0 [2000 Jan 05]
Add @code{set input data separator}.  Make @code{read columns} work with
various input separators. Make @code{read .x.}, etc, work with various
input separators.



@c HTML <!-- newfile Version_2_2.html "Gri: Version 2.2" "Gri: Version 2.2" -->
@node   Version 2.2, Unstable Stream, Version 2.4, Stable Stream
@comment  node-name,  next,  previous,  up
@subsection Version 2.2

@subsubsection Version 2.2.6 [1999 Nov 25]
Make web-based manual easier to read by putting a light-grey background
under sample code.

@subsubsection Version 2.2.5 [1999 Nov 10]
Fix bug in RPN calculations that prevented using a negative exponent.

@subsubsection Version 2.2.4 [1999 Nov 7]
Add @code{set font encoding}, and also change the encoding to
ISO-Latin-1.  (This doesn't hurt old code since Gri didn't make any
claims to handle characters outside the normal printing-set before
anyway.)

Fix bug in which there were 4 dead links in the HTML version of manual.

Clean up some problems with Debian distribution (thanks, Peter Galbraith!).

@subsubsection Version 2.2.3 [1999 Jun 30]
Fix bug in which word-of-synonym (e.g. @code{\[0]mysyn}) was not
detected correctly (thanks to bug report from Kazuhiko Nakayama in
Japan)

@subsubsection Version 2.2.2 [-]
Clean a few spelling and cross-reference errors in documentation.

@subsubsection Version 2.2.1 [1999 Mar 31]
For debian, properly locate the @code{netcdf} library, if it is
installed. 

Remove remnants of old commands for polar axes.

Correct error in which the right-most and upper-most pixel of images
created by @code{convert grid to image} may be blank (or not, depending
on roundoff error) under certain conditions of exact matchup between
grid spacing and image spacing.

Don't create PostScript file if the commandfile is non-existent, or if
there were errors on the commandline.

@subsubsection Version 2.2.0 [1999 Mar 25]
First debian release.  Versions exist for intel, alpha, 68K and powerpc.



@c HTML <!-- newfile UnstableStream.html "Gri: Unstable Stream" "Gri: History" -->
@node   Unstable Stream, Development Version, Version 2.2, History
@comment  node-name,  next,  previous,  up
@section Unstable Stream

@menu
* Development Version::
* Plans::
@end menu


@c HTML <!-- newfile Development_Version.html "Gri: Development Version" "Gri: Development Version" -->
@node   Development Version, Plans, Unstable Stream, Unstable Stream
@comment  node-name,  next,  previous,  up
@subsection Development Version

The list below shows changes that have been made in the development
version of Gri, i.e. the version on CVS at
@url{http://gri.sourceforge.net}.  Some or all of these features may
enter the next stable stream of Gri, but it is important to note that
@emph{anything} that's listed here may be changed without notice!  The
main exception is bug fixes, which will enter the stable stream unless
they are found to create new bugs.

@subsubsection New Features

@itemize @bullet
@item
n/a
@end itemize


@subsubsection Removed Features

@itemize @bullet
@item
n/a
@end itemize


@subsubsection Bug Fixes

@itemize @bullet

@item
Fix SourceForge bug
@uref{http://sourceforge.net/tracker/index.php?func=detail&aid=618041&group_id=5511&atid=105511,#618041}
@dots{} solaris compile error, relating to the subroutine @code{gethostname()} in the @file{startup.cc} source code file.


@end itemize




@c HTML <!-- newfile Plans.html "Gri: plans for future versions" "Gri: plans for future versions" -->

@node   Plans, Deprecated Commands, Development Version, Unstable Stream
@comment  node-name,  next,  previous,  up
@subsection Plans
@c FOR NEXT RELEASE:
@c 1) Fix bug in @code{read colorname} that caused it to try to
@c    interpret comments in the X11 color-name file as though
@c    they were actual colors.
@c
@c 2) Improve writing in the @code{read image} section of this manual.
@c
@c 3) Fix bugs in the HTML version of the manual, as reported
@c    by the 'tidy' checking programme.

@cindex plans for future versions
@cindex command-line interface
@cindex image formats, other than 8-bit

Some plans for future versions are given below.  A more extensive
list, together with target timescales and notes on the progress
towards completion, is available in the to-do list at the development
site (@url{http://gri.sourceforge.net}), which is also the place to go
if you have suggestions for other changes to Gri.

@cindex endian file compatibility, plans
@cindex little-endian vs big-endian data, plans
@cindex big-endian vs little-endian data, plans

@subsubsection High Priority

@enumerate

@item Add ability to generate SVG (scalable vector graphics) output.  This
file type can be edited with GUI-based tools, making it easy for users
to put the final touches on graphs "manually."  This feature will
require a great deal of work, mainly to do with grouping of graphical
elements, and so I'll need to rely on advice from users.

@item Switch to @code{popt} library for the processing of command-line 
options.  (Docs on this are at
@url{http://cvs.gnome.org/lxr/source/popt}.)

@item Change @code{set axes style} from number-based selection to
word-based selection, and print a deprecation warning if the
number-based syntax is used.

@item Switch from @code{tmpname} to @code{mkstemp} subroutine, for temporary filenames.

@item Add readline support, to handle history, command-line editing, etc, 
for interactive usage
(Docs on this are at
@url{http://cnswww.cns.cwru.edu/~chet/readline/readline.html}.)

@end enumerate


@subsubsection Medium priority

@enumerate

@item Add optimal interpolation as another method for gridding
data (@ref{Convert Columns To Grid}).

@item Add ability to read PNG images (@ref{Read Image})
(Docs on this are at @url{http://www.libpng.org/pub/png/}.)

@end enumerate


@subsubsection Low priority

@enumerate

@item Add non-RPN mathematics.

@item Add graphical output to the screen as commands are executed.  

@item Add support for both little-endian and big-endian binary data.

@end enumerate



@c HTML <!-- newfile DeprecatedCommands.html "Gri: Deprecated Commands" "Gri: History" -->
@node   Deprecated Commands, Installation, Plans, History
@comment  node-name,  next,  previous,  up
@section Deprecated Commands
@cindex deprecated commands

@itemize @bullet
@item @emph{version 2.9.0}
@itemize @bullet
@item Replace @code{set y axis label horizontal} with @code{set y axis name horizontal}.
@item Replace @code{set y axis label vertical} with @code{set y axis name vertical}.
@end itemize
@end itemize



@c HTML <!-- newfile Installation.html "Gri: installing Gri" "Installing Gri" -->

@node   Installation, Unix-install, Deprecated Commands, Top
@comment  node-name,  next,  previous,  up
@chapter Installing Gri

@menu
* Unix-install::                
* Msdos-install::               
* OS2-install::
* Mac-install::               
* Beos-install::               
@end menu

@c HTML <!-- newfile Unix-install.html "Gri: installing Gri" "Installing Gri" -->

@node   Unix-install, Archiving Old Versions, Installation, Installation
@comment  node-name,  next,  previous,  up
@section Unix Installation
@cindex directory structure of Gri installation

@menu
* Archiving Old Versions::      Keeping the old and the new
* Linux::                       Installing on linux
* Precompiled Unix::            Installing precompiled versions
* Uncompiled Unix::             Compiling and installing
@end menu


@c HTML <!-- newfile Archiving.html "Gri: archiving old versions" "Gri: archiving old versions" -->
@node   Archiving Old Versions, Linux, Unix-install, Unix-install
@comment  node-name,  next,  previous,  up
@section Archiving Old Versions

Gri, like other complex programs, sometimes changes in such a way as to
break old scripts.  This is less so of changes since about 1998 or so,
since the syntax became pretty firm about that time.  

Still, disk costs are so cheap that you would be well-advised to keep a
backup version of Gri, whenever you update.  This is pretty simple; you
need to keep a copy of the executable and the library file, and you need
to write a tiny shellscript that calls this particular executable with
this particular library file.  For example, you might do the following

@example
mkdir -m 755 -p           /usr/local/share/gri/@value{GRI-VERSION}
cp /usr/bin/gri           /usr/local/share/gri/@value{GRI-VERSION}
cp /usr/share/gri/gri.cmd /usr/local/share/gri/@value{GRI-VERSION}
@end example

@noindent
and then create a shellscript called
@file{/usr/local/bin/gri-@value{GRI-VERSION}} containing

@example
#!/usr/bin/sh
/usr/local/share/gri/@value{GRI-VERSION}/gri \
    -directory /usr/local/share/gri/@value{GRI-VERSION} \
    "$@@"
@end example

@noindent
to invoke this version of Gri.

To be able to access this old version of gri from within the Emacs
gri-mode, you would reset the Emacs variable @code{gri*directory-tree}
like so in the file @file{~/.emacs} 
(@ref{Step 2} in 
@ref{Installing gri-mode.el})

@example
(setq gri*directory-tree
    '("/usr/local/share/gri/" "/usr/share/gri/"))
@end example




@c HTML <!-- newfile linux-install.html "Gri: installing Gri" "Installing Gri" -->

@node   Linux, Precompiled Unix, Archiving Old Versions, Unix-install
@comment  node-name,  next,  previous,  up
@subsection Installation on Linux computers

@cindex linux distributions
@cindex debian
@cindex redhat
@cindex RPM version of installation package
@cindex installation, debian linux
@cindex installation, redhat linux
@cindex installation, linux redhat/debian

Installation is easy on various flavors of linux.  Versions
are available from the official distributions and also at
@c HTML <A HREF="http://sourceforge.net/project/showfiles.php?group_id=5511">
@file{http://sourceforge.net/project/showfiles.php?group_id=5511}
@c HTML </A>

The RedHat version supports intel platforms only, while the Debian
version supports intel, alpha, 68K and powerpc.  Installation follows
the normal method for these distributions ... if you have the
distribution, you surely know what to do.  If you don't, you may want to
switch when you see that you can install Gri by clicking an icon in a
window, or by typing, e.g. in RedHat linux:

@example
rpm -i gri-@value{GRI-VERSION}
@end example

Debian-linux installation may be done with any of several GUI-based
tools, or with the following system command:

@example
dkpg -i gri_@value{GRI-VERSION}-1_i386.deb
@end example

@noindent
or via a properly configured @code{apt} interface that will fetch the
latest version from the net:

@example
apt-get install gri
@end example


@c HTML <!-- newfile precompiled-unix.html "Gri: installing Gri" "Installing Gri" -->

@node   Precompiled Unix, Uncompiled Unix, Linux, Unix-install
@comment  node-name,  next,  previous,  up
@subsection Pre-compiled unix versions
Pre-compiled versions of Gri exist for various computers, e.g. SPARC
(both sunOS and solaris), IBM-RS, Sequent, and Linux.  The following
instructions, which assume a version number @value{GRI-VERSION}, and a
SPARC solaris machine, show how to install these.

The compressed tar file, with a name like
@file{gri-binary-SunOS5-@value{GRI-VERSION}.tar.gz} (in this example a
Sun OS 5 binary is assumed, with gri version number @value{GRI-VERSION})
contains a directory which holds the executable Gri file, @file{gri},
the library file @file{gri.cmd}, an instructions file, @file{README},
and a Makefile to install Gri.

Here's how to install Gri, starting with this tar file:

@enumerate
@item
First, uncompress (unzip) the file, and un-tar it, by doing

@example
gunzip -c gri-binary-SunOS5-@value{GRI-VERSION}.tar.gz | tar xvf -
@end example

@noindent
or

@example
zcat gri-binary-SunOS5-@value{GRI-VERSION}.tar.gz | tar xvf -
@end example

@noindent
This will yield a new directory, with a name like
@file{gri-binary-SunOS5-@value{GRI-VERSION}}, which contains the
indicated files.
@item
Follow the instructions in the @file{README} file to install Gri.
@end enumerate


@c HTML <!-- newfile uncompiled-unix.html "Gri: installing Gri" "Installing Gri" -->

@node   Uncompiled Unix, Msdos-install, Precompiled Unix, Unix-install
@comment  node-name,  next,  previous,  up
@section Compilation on Unix computers
The following steps indicate how to compile Gri on unix computers.  The
procedure is quite standard.

@cindex configure script, how to use to compile gri
@cindex compiling gri
@cindex how to compile gri

@table @emph

@item Requirements
You'll need a C++ compiler that is modern enough to handle 'templates'
(i.e. almost any compiler from 1998 onward).  Don't worry -- if your
compiler isn't new enough, you'll see that in a minute or two!  

You'll need TeX and texinfo to make the info files, and optionally the
netCDF library (if you wish gri to be able to read netCDF binary data
files).  To make the HTML manual, you'll need imagemagick, info, gs and its
fonts.

On Debian GNU/Linux systems, the required packages are listed as
Build-Depends in the @file{control} file found in the @file{debian}
directory, to which you must add the package @file{build-essential}.


@item Unpack the source
Type 

@example
gunzip gri-@value{GRI-VERSION}.tgz
tar xvf gri-@value{GRI-VERSION}.tar
@end example

@noindent
(or similar commands) to uncompress and untar the contents.  This will
yield a new directory named @file{gri-@value{GRI-VERSION}} which
contains many files.


@item Move to the Gri directory

@example
cd gri-@value{GRI-VERSION}
@end example


@item Configure your compiler
Next you must "configure" the Gri source files.  During this step, a
series of tests will be made about your operating system and your
compiler.  Most of these tests need no interaction from you, but there
is one overall choice that you may wish to make: the place on your
filesystem where Gri (and many associated library and documentation
files) will reside.  To get the default installation, with files
residing within the directory @file{/usr/local}, type

@example
./configure
@end example

@noindent
at this time.  If you'd rather the files go into another location, run
the @code{configure} script differently, e.g.  to get the Gri files to
reside within the @file{/opt} directory, type:

@example
./configure --prefix=/opt
@end example

@noindent
In response, you'll see the results of several tests of the properties
of your operating system, your C++ compiler, etc.  Normally you can
ignore these results.

@cindex handling multiple gri versions
@cindex multiple gri versions
@cindex versions, handling multiple

As an example, typing @code{./configure} without a @code{--prefix}
option yields the directory tree (@code{...} indicates several files not
displayed in this list, for brevity).  In this example,
the most up-to-date version is @value{GRI-VERSION}, but a previous
version @value{GRI-PREVIOUS-VERSION} has also been retained.  (Note that
only one copy of the documentation is retained; this is all that's
needed, since old versions are documented there as well as new
versions.)

@example
/usr/local
|-- bin
|   |-- gri -> gri-@value{GRI-VERSION}
|   |-- gri-@value{GRI-VERSION}
|   |-- gri-@value{GRI-PREVIOUS-VERSION}
|   |-- gri_merge
|   `-- gri_unpage
|-- info
|   |-- ...
`-- share
    `-- gri
        |-- 2.6.0
        |   |-- gri.cmd
        |   |-- license.txt
        |   |-- logo.dat
        |   `-- startup.msg
        |-- 2.4.0
        |   |-- gri.cmd
        |   |-- license.txt
        |   |-- logo.dat
        |   `-- startup.msg
        `-- doc
            |-- examples
            |   |-- ...
            `-- html
                |-- ...
                |-- resources
                |   |-- ...
                `-- screenshots
                    |-- ...
@end example

@b{Trouble-shooting 1}: If the permission of the @file{configure} file is
wrong, you'll get an error like @code{Permission denied}; if so, try
typing @code{sh ./configure} to run it in the Bourne shell.  If that
fails, you are going to have to do some old-fashioned work!  Start by
copying the generic Makefile called @file{Makefile.generic} into
@file{Makefile}, and try the following steps, perhaps editing the
@file{Makefile} if you run into errors.


@b{Trouble-shooting 2}: Gri uses a C++ feature called 'templates'.
Unfortunately, templates are handled in different ways by different
compilers.  At least as of Spring 1997, the GNU compiler, vsn 2.7.x
(used by many Gri folks) has problems with templates.  Therefore the
configure script will check to see if you are using the GNU c++
compiler, and if you are it will check whether the ("template
repository") compiler flag @code{-frepo} is known on your machine.  If
it is not, an alternative method of templates will be used.  But if it
is, you'll be asked, for confirmation, whether you wish to use the
@code{-frepo} flag.  On many machines (e.g. Solaris) you should answer
@code{n} to this question.  The prompt will explain.  Also, note that
you can avoid the prompt by running configure as either of the two
below:

@example
./configure --enable-frepo
./configure --disable-frepo
@end example

(Such switches will be ignored unless you're using the GNU compiler.)

@b{Trouble-shooting 3}: If optional system libraries like the netCDF
library, if it exists, are installed in nonstandard places, you might
have to change the unix environment variable @code{LD_LIBRARY_PATH}.
For example, on my machine the @code{netcdf} library is not installed in
@file{/usr/lib}, as the @code{configure} script assumes, but rather in
@file{/usr/local/share/netcdf/lib}.  Therefore I have the following line
in one of my startup files:

@example
export LD_LIBRARY_PATH=/usr/lib:/usr/local/share/netcdf/lib
@end example


@item Compiling Gri
Now compile Gri by typing

@example
make
@end example


@item Testing Gri
@cindex test suite
Type

@example
make check
@end example

@noindent
to do some tests on the version of Gri that you just compiled.  If no
errors are reported, you may go to the next step.


@item Installing Gri
Assuming compilation succeeds, install @file{gri} and the ancillary file
@file{gri.cmd}, by typing

@example
make install
@end example

If you wish to see where files where be installed, first try a dry run
typing 

@example
make -n install
@end example


@item Cleaning up
Once these things are done, you may type

@example
make clean
cd doc ; make clean
@end example

@noindent
to clean up some files.  Of course, you could just erase the whole
source, but the source is probably worth a penny of hard-drive space,
isn't it?
@end table



@c HTML <!-- newfile msdos-install.html "Gri: installing Gri" "Installing Gri" -->

@node   Msdos-install,  OS2-install, Uncompiled Unix, Installation
@comment  node-name,  next,  previous,  up
@section Compilation on x86 (PC-style) Computers

Versions exist for MSDOS, windows, and Linux operating systems.
(Actually, the windows version is just the MSDOS version, which can be
run inside an msdos window within windows-95, windows-NT, etc.)

@subsection MSDOS Operating System
@cindex compilation under MSDOS
@cindex MSDOS compilation

To compile and install Gri under MSDOS, do this:
@enumerate
@item
To begin, install @code{DJGPP V2}, if it is not on your system already.
It can be found at
@url{http://www.delorie.com/djgpp}
@item
Uncompress and extract from gri source package (@ref{Uncompiled Unix}).
@item
Type @code{make -f Makefile.dj2} to compile.  If it fails, you might
have to edit the file @file{Makefile.dj2} to match the characteristics
of your system.  Please inform the author,
@c HTML <A HREF="mailto:Dan.Kelley@Dal.CA"> 
Dan Kelley
@c HTML </A>
at Dan.Kelley@@Dal.CA, if you think your modifications might be useful
to others.
@item
Type @code{make -f Makefile.dj2 install} to install it (normally on the
@code{C:} drive).
@end enumerate 

If you encounter problems, read the first few lines of the Makefile
(i.e. the file @file{Makefile.dj2}) for hints on things to try.  For
example, in the present version of @file{Makefile.dj2} these hints are
given:
@enumerate
@item
There is a good chance that this Makefile will work as is, so try that
first.
@item
If you have the @file{netcdf} library (used for certain types of
atmospheric and oceanographic datasets), then un-comment and possibly
edit the appropriate @code{NETCDF_...} lines below, as instructed by the
comments preceding these lines.
@item
If you don't want Gri inserted in the directory @file{c:/gri}, edit the
@code{instdir = ...} line below.
@item
If you get error messages about the @file{stdcxx} library, edit the
@code{LIBS} line below, rewriting @file{-lstdcxx} as @file{-lstdcx}.
@item
If you get compilation errors relating to @code{time} or to
@code{ftime}, try putting the token @code{-DHAVE_FTIME=1} in the list of
similar token in the @code{DEFS = ...} line.  For consistency
(basically, so the author can help you if you do this), put it right
after the @code{-D_GRI_=1} token.
@end enumerate

To view the output, use a PostScript viewer such as GSview.



@subsection LINUX Operating System
@cindex compilation under Linux
@cindex linux compilation
@cindex LINUX compilation
Linux is a good emulation of unix, and it is free.  Gri for linux is
compiled and installed according to the normal unix instructions.
The compiled version is with a name like 
@code{gri-binary-solaris-2.1.10.tar.gz}; treat it as in other unix
systems (@ref{Uncompiled Unix}).



@c HTML <!-- newfile os2-install.html "Gri: installing Gri" "Installing Gri" -->
@node   OS2-install, Mac-install, Msdos-install, Installation
@comment  node-name,  next,  previous,  up
@section Compilation under OS/2
@cindex compilation under OS/2
@cindex OS/2 unix compilation

Gri compiles, using the gcc compiler under OS/2, provided that the
included @code{Makefile.os2} is used.  Be sure to edit the first few
lines to change filenames as required, especially taking care to
account for whether the netCDF library is installed, etc.



@c HTML <!-- newfile mac-install.html "Gri: installing Gri" "Installing Gri" -->

@node   Mac-install, Beos-install, OS2-install, Installation
@comment  node-name,  next,  previous,  up
@section Compilation in Macintosh OS X
@cindex compilation in Macintosh OS X
@cindex macintosh unix compilation
@cindex darwinport
@cindex fink

The OS X system provides a BSD unix that suites Gri very well. With the (free)
developer package, it also provides a very up-to-date version of the @code{gcc}
compiler. Thus, installing Gri on Macintosh can be done using the normal Unix
instructions.

But there are also easier ways. Gri is compatible with Fink and Darwinports, the
two popular packaging systems on OS X. If you use OS X and do not have Fink or
Darwinports installed, then you should probably install one, or both. Each
distribution has strengths, and each has weaknesses, and it is difficult to
provide a firm recommendation between the two.

@emph{Caveat.} As of mid-2007, neither distribution appears to handle package
dependencies as well as is done by popular linux distributions. For example, in
working through the steps listed below, the author found that his Darwinports
system had a problem with a system library that handles internationalization. The
"update" operation of the system was insufficient to solve the problem, and so it
was necessary to do some web searching to find a patch. The patch failed, but
another search revealed a second (hand-edit) patch that got it working. In excess
4 CPU hours were required to rebuild the packages that were broken.

If you'd like to build a local Darwinports version of Gri, to get the
latest version instead of whatever version is provided by Darwinports,
follow these steps:

@itemize @bullet

@item Download the source from CVS at SourceForge. (If you don't know what the previous
sentence means, you will quite likely have difficulties with the other steps.)

@item Visit the @code{darwinports} directory of the newly-created directory tree, and type
@example
sudo port -d -v build
@end example
to build it. This will take several minutes, during which you
may find it helpful to do a search on "darwinport build". For example, the 
O'Reilly page
(@url{http://www.oreillynet.com/pub/a/mac/2004/04/09/darwinports.html?page=3},
last checked in July 2007)
is very good.  Note that you will be
building from the source that is stored on SourceForge, not from the Darwinports
source. That's the trick of issuing the @code{build version} of the @code{port}
command.

@item Do a "destroot" operation:
@example
sudo port -d -v destroot
@end example

@item Install it:
@example
sudo port -d -v install
@end example
Note: if you already have an older version of Gri in the Darwinports system, you must first
issue the command
@example
sudo port deactivate gri
@end example

@end itemize


@c HTML <!-- newfile Beos-install.html "Gri: bugs" "Gri Bugs" -->

@node   Beos-install, Bugs, Mac-install, Installation
@comment  node-name,  next,  previous,  up
@section Compilation under BeOS
@cindex compilation under BeOS
@cindex BeOS unix compilation

The BeOS system compiles Gri cleanly without modification; just follow
the instructions for unix.


@c HTML <!-- newfile Bugs.html "Gri: bugs" "Gri Bugs" -->

@node   Bugs, Known Bugs, Beos-install, Top
@comment  node-name,  next,  previous,  up
@chapter Bugs

@menu
* Known Bugs::                  Bugs in the current version 
* Reporting Bugs::              How to report bugs
* Killing Bugs::                How to (try to) kill bugs
@end menu

@c HTML <!-- newfile KnownBugs.html "Gri: bugs" "Gri Bugs" -->

@node   Known Bugs, Reporting Bugs, Bugs, Bugs
@comment  node-name,  next,  previous,  up
@section Known bugs
@cindex bugs in Gri

To get a list of known bugs, in the present or past versions, visit
@url{http://sourceforge.net/tracker/?atid=105511&group_id=5511&func=browse}.

@c HTML <!-- newfile ReportingBugs.html "Gri: bugs" "Gri Bugs" -->

@node   Reporting Bugs, Killing Bugs, Known Bugs, Bugs
@comment  node-name,  next,  previous,  up
@cindex bugs, how to report
@section Reporting Bugs

Bug reports help make Gri more reliable and useful for all users, so
please report any bugs you find.  The scheme will be familiar to you, if
you've participated in open-source work before.

@enumerate

@item
Visit the bug-tracking part of the Source Forge Gri development site, at
@url{http://sourceforge.net/bugs/?group_id=5511}
to see whether your bug has already been reported.  You may find that it
has been reported and fixed already in a new version, in which case you
should archive your existing Gri version and upgrade.  If the bug has
been reported and @strong{not} fixed, then you may still wish to add a
supplemental bug report, so the author knows that this bug is of concern
to you as well as the others.  (Plus, reporting it this way ensures that
you'll receive an email when the bug is fixed.)

@item
Debugging is made easier if the problem is reduced in scope.
Therefore, please reduce your application and your data to the
simplest case that produces the error.

@item
@cindex bug, resulting in bus error
@cindex bug, resulting in segmentation fault
@cindex bus error, what to do
@cindex segmentation fault, what to do
@cindex debugger used with Gri
If you know how, please try to find the bug yourself.  After all, Gri
is open-source for a reason!  The procedure is described in the next
section (@ref{Killing Bugs}).

@end enumerate


@c HTML <!-- newfile KillingBugs.html "Gri: bugs" "Gri Bugs" -->

@node   Killing Bugs, Debugging Software You Will Need, Reporting Bugs, Bugs
@comment  node-name,  next,  previous,  up
@cindex bugs, how to kill them
@section Killing Bugs
@menu
* Debugging Software You Will Need:: 
* Debugging at a Glance::          
* Debugging Example::
@end menu

@node   Debugging Software You Will Need, Debugging at a Glance, Killing Bugs, Killing Bugs
@comment  node-name,  next,  previous,  up
@subsection Software that you'll need
This section is intended to help you find and kill bugs yourself, by
indicating how the author does this work.  Since Gri is open-source,
all users are invited to try to kill bugs themselves!

If you know nothing of C or C++, you may as well not read further,
since there is little chance of your making progress.  On the other
hand, experienced programmers won't need any of the advice I give
below.

You'll need the Gri source and a C++ compiler.  It also helps if you
have @code{gdb}, the GNU debugger, installed; the instructions below
assume that's the case.  Also, the instructions assume that you're
using the Emacs editor, and running @code{gdb} from within Emacs.
Otherwise, you'll want to glance at the documentation on @code{gdb} to
see how to use it in standalone mode.

@node   Debugging at a Glance, Debugging Example, Debugging Software You Will Need, Killing Bugs
@comment  node-name,  next,  previous,  up
@cindex electric fence, for debugging
@subsection Debugging at a glance
The list below is a sketch of what you might try, and in what order.

@itemize @bullet

@item Check the bug list to see if other users have found your bug,
and also to see if there is a workaround.

@item Try a more recent version of gri.  If it works, you might wish to 
archive the version you have at the moment and upgrade.

@item If you suspect your bug has something to do with system calls, 
as in the @code{system} command (@ref{System}) or as in piped input
files (@ref{Open}), you should re-run the script with 
@code{gri -superuser8} instead of with @code{gri}.  This will cause
Gri to print out all commands that it is handing over to the operating
system; you may see the error that way.  (Hint: it may help to
interactively cut/paste the commands into your OS shell to see what the 
action of the command is.)

@item If your bug results in early termination, you should run Gri
inside a debugger (e.g. GDB, assumed henceforth).  When the program
terminates, type @code{where} to see where termination occured.  Often
this will give a clue.  In many cases, early termination results from
faults in memory allocation.  To check memory allocation, you'll need to
recompile Gri, linking it against a debugging memory allocator.  Many
such tools exist; see comments in the @code{Makefile} for a hint at how
to use a popular one, called ``Electric Fence.''

@item If your bug does not result in early termination, you may find 
the best scheme is to trim your example down as much as possible, and
then run Gri inside the GDB (or other debugger) so that you can monitor
program execution.  The next section explains this in detail.
@end itemize


@node   Debugging Example, Test Suite, Debugging at a Glance, Killing Bugs
@comment  node-name,  next,  previous,  up
@subsection A debugging Example
Let's take a recent bug as an example.  Peter Galbraith found that the
gri script

@example
set color hsb 0.999 1 1
draw box filled 2 2 3 3 cm
set color hsb 1.000 1 1
draw box filled 4 2 5 3 cm
@end example

@noindent
produced odd results in a previous version of Gri; the color patches
should have been of nearly the same color, but the first one was red, as
expected, and the second was magenta.

The list below shows how I found Peter's bug.  Experienced C or C++
programmers will find all of this very familiar, and will really only
need to read item 6 of the list below, since that's the only action that
is really specific to Gri.  (Note: for display purposes, I've broken
some of the lines in the files into two lines in this list.)

@enumerate


@item Copy the above script (called @file{test.gri}) into the Gri source 
directory, and the script into an Emacs buffer.  @b{Note:} all the
following steps are done within Emacs, and the items in parentheses are
the Emacs keys to get the indicated actions.


@item If you're working from a pre-compiled version, you'll need to get the
source first and do a compile yourself (@ref{Uncompiled Unix}).  Then do
a @code{make tags} command (type this to the unix shell) to create a
so-called "tag" table.


@item Run Gri in this emacs buffer (@kbd{C-cC-r}) noting from the 
postscript window that pops up that the colors are, indeed, mixed up.


@item Load up the @code{gdb} debugger by typing @kbd{M-x gdb gri}.  This
will open a new Emacs buffer in which you may type commands.  We'll be
switching back and forth between this buffer and various source files.


@item Reasoning that the error probably occurs at @code{set color} or
@code{draw box}, try replacing the latter by a command such as
@code{draw label "hi" at 3 3 cm"}.  The color is still wrong, indicating
that it is the @code{set color} command that has the problem.


@item Next, we must find where the C++ code corresponding to the
@code{set color} command resides.  As it turns out, all @code{set}
commands are defined in the source file @code{set.cc}, and this command
is defined in a subroutine called @code{set_colorCmd()}.  But the author
knows this -- how would you?  The answer is to look in the
@file{gri.cmd} file, for the @code{set color} command.  (Search for the
string @code{`set color }.) Then read down to see the body of the
command, enclosed in braces; you'll see

@example
@{
    extern "C" bool set_colorCmd(void);
@}
@end example

@noindent
which indicates that the subroutine name is @code{set_colorCmd()}.


@item Next we need to edit this subroutine to see what it is doing.
There are several ways to find it (e.g. @code{grep} through the source
files), but the easiest is to use the "tags" feature of Emacs, by typing
@kbd{M-. set_colorCmd}.  This will bring you to the indicated
subroutine.


@item Have a look through this subroutine to see what it is doing.  It
looks very much like many other Gri subroutines.  A check is done on the
number of words provided to the command, in the 

@example
	switch (_nword) @{
@end example

@noindent
line.  (That's line @file{set.cc:484} at the moment -- but it may be
different by the time you read this file, if I've changed it!)  We are
calling it with 6 words (@code{set color hsb 1.000 1 1}), so move down
to the line

@example
	case 6:
@end example

@noindent
and you'll see that there is an @code{if} statement seeing whether this
word is @code{rgb} or @code{hsv}.  These statements are checking
@code{_word[2]}, which is the third word of the command.  (In Gri, as in
C, words start at zero.  Thus, for this command, @code{_word[0]} is
@code{set}, @code{_word[1]} is @code{color}, and @code{_word[2]} is
expected to be either @code{rgb} or @code{hsb}.  We are having problems
with the @code{hsb} style, so we'll move down to that code.  The code
that's being executed is as follows.

@example
@} else if (!strcmp(_word[2], "hsb")) @{
        // `set color hsb .hue. .saturation. .brightness.'
        double          hue, saturation, brightness;
        Require(getdnum(_word[3], &hue),
                READ_WORD_ERROR(".hue."));
        Require(getdnum(_word[4], &saturation),
                READ_WORD_ERROR(".saturation."));
        Require(getdnum(_word[5], &brightness), 
                READ_WORD_ERROR(".brightness."));
        // Clip if necessary
        CHECK_HSB_RANGE(hue);
        CHECK_HSB_RANGE(saturation);
        CHECK_HSB_RANGE(brightness);
        gr_hsv2rgb(hue, saturation, brightness,
                &red, &green, &blue);
        PUT_VAR("..red..", red);
        PUT_VAR("..green..", green);
        PUT_VAR("..blue..", blue);
        c.setHSV(hue, saturation, brightness);
        _griState.set_color_line(c);
        if (_griState.separate_text_color() == false)
                _griState.set_color_text(c);
        return true;
@end example

The @code{Require} lines are ensuring that we could decode the values of
the variables @code{hue}, etc, from the commandline.  Then we clip the
range of these values.  Then we convert from @code{hsb} color format to
@code{rgb} color format, save the values of the colors in Gri variables
with @code{PUT_VAR}, and then set the color with @code{c.setHSV}.
Finally we save this color in the Gri "state" with
@code{_griState.set_color_line(c)}.

As it turns out, Gri outputs all colors to the PostScript file in RGB
format, so the we may well suspect that the problem is in the
@code{gr_hsv2rgb()} line. 


@item We have an idea where to look now, so let's go to the line just after 
it, in the editor, and insert a "breakpoint" there by typing
@kbd{C-x SPC}.  Then move to the @code{gdb} buffer and re-run Gri
by typing 

@example
run -directory . test.gri
@end example

@noindent
to run Gri on our script.  Then, magic happens!  Gri stops at the
indicated breakpoint, and Emacs will display both the @code{gdb} buffer
and the @code{set.cc} buffer.  The latter has a margin indication
telling what line were are on.  You may now type @code{gdb} commands in
the @code{gdb} buffer.  In particular, type

@example
p hue
@end example

@noindent
to print the hue.  Then type

@example
p red
@end example

@noindent
to see the red value.  Then type

@example
c
@end example

@noindent
to continue running Gri.  It will pause again.  Check the hue and red
values again, as above.  If you like, play around with hue value in the
Gri script @file{test.gri} and run gri again (type @code{r} in
@code{gdb}).  This seems to indicate that the conversion is working
strangely.


@item To see how the conversion is done, clear the breakpoints by typing
@kbd{delete} in the @code{gdb} buffer, then insert a breakpoint
@strong{before} @code{gr_hsv2rgb} is called.  Then, run Gri again (@kbd{r}
in the @code{gdb} buffer).  When it stops just before this subroutine,
type @kbd{s} to "step into" the subroutine.  Then you'll see a
conversion code from the (wonderful) textbook of Foley and Van Dam.
You'll see

@example
void
gr_hsv2rgb(double h, double s, double v, 
           double *r, double *g, double *b)
@{
	h = 6.0 * pin0_1(h);
	s = pin0_1(s);
	v = pin0_1(v);
	int i = (int) floor(h);
	if (i > 5)
		i = 5; // Prevent problem if hue is exactly 1
	double f = h - i;
	double p = v * (1.0 - s);
        ...
@end example

@noindent
in the present version of Gri, but in the previous (buggy) version, the
@code{if} statement was missing.  Without this @code{if} statement, Gri
produced wrong colors.  With the statement, the colors are correct.
@end enumerate
And so ends the example.  You may wish to read the Foley and Van Dam
textbook to see just what I'm doing in @code{gr_hsv2rgb}, but suffice it
to say that the problem in the (older) version of Gri was that @code{i}
could take the value 6 if the hue was exactly equal to 1, and that was
erroneous.

In reading the code, you may notice that it is formatted in a uniform
way: the Kernighan and Ritchie scheme (from their classic C textbook),
with 8-character indents.  I get this by putting the following lines
in the @file{~/.emacs} file, which is used to customize the Emacs editor:

@example
(defun my-c-mode-common-hook ()
  (c-set-style "K&R")
  (setq c-basic-offset 8)
  )
(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
@end example

If you submit patches, please use the same format as I've done, so
that I can more easily see the changes you've made.


@c HTML <!-- newfile TestSuite.html "Gri: Test Suite" "Test Suite" -->

@node   Test Suite, Gri in the Press, Debugging Example, Top
@comment  node-name,  next,  previous,  up
@chapter Test Suite

@cindex test suite
@cindex suite of test files

The following test files are invoked by typing @code{make test}, after
compiling Gri.  They are provided here because they are examples of
scripts that are @strong{known to work} for the version of Gri described
in this manual.

Heavy use is made of the @code{assert} command (@ref{Assert}) in these
test files.  Thus the @strong{code itself} demonstrates the features,
instead of comments in the code.  This is advantageous since comments
tend to be incorrect!



@c HTML <a href="tst_suite/tst_IO.html">Test file `<tt>tst_IO.gri</tt>'.</a><p>
@iftex
@sp 1
@noindent Test file @file{tst_IO.gri}:

@cartouche
@include tst_suite/tst_IO.texi
@end cartouche
@end iftex

@c HTML <a href="tst_suite/tst_control.html">Test file `<tt>tst_control.gri</tt>'.</a><p>
@iftex
@sp 1
@noindent Test file @file{tst_control.gri}:

@cartouche
@include tst_suite/tst_control.texi
@end cartouche
@end iftex

@c HTML <a href="tst_suite/tst_rpn.html">Test file `<tt>tst_rpn.gri</tt>'.</a><p>
@iftex
@sp 1
@noindent Test file @file{tst_rpn.gri}:

@cartouche
@include tst_suite/tst_rpn.texi
@end cartouche
@end iftex


@c HTML <a href="tst_suite/tst_var_syn.html">Test file `<tt>tst_var_syn.gri</tt>'.</a><p>
@iftex
@sp 1
@noindent Test file @file{tst_var_syn.gri}:

@cartouche
@include tst_suite/tst_var_syn.texi
@end cartouche
@end iftex


@c HTML <!-- newfile GriInThePress.html "Gri: in the Press" "Gri: in the Press" -->

@node   Gri in the Press, Acknowledgments, Test Suite, Top
@comment  node-name,  next,  previous,  up
@chapter Gri in the Press
@cindex scientific journals with Gri graphs

A gentle introduction to Gri is provided in a Linux Journal article, available at
@url{http://www2.linuxjournal.com/lj-issues/issue75/3743.html}
on the web.

In March 2000, I emailed some Gri users to ask for the names of
scientific journals in which they have published Gri-produced graphs.
The list, which mainly arrived on Sunday in response to an email I
sent Saturday (don't Gri users take a break?) is presented below, to
indicate the range of Gri use in the press.

@b{Journals in Oceanography, Atmospheric Science, Earth Science, etc.}
@itemize @bullet

@item @strong{Bulletin on Coastal Oceanography} (in Japanese with English
abstract)

@item @strong{Fisheries Oceanography}

@item @strong{Deep-Sea Research}

@item @strong{EOS, Transactions of the American Geophysical Union}

@item @strong{Estuarine, Coastal and Shelf Science}

@item @strong{Geophysical Research Letters}

@item @strong{Journal of Atmospheric and Oceanic Technology}

@item @strong{Journal of Geophysical Research}

@item @strong{Journal of Marine Research}

@item @strong{Journal of Plankton Research}

@item @strong{Journal of Physical Oceanography}

@item @strong{Journal of the Japan Scoiety for Marine Surveys and Technology}
(in Japanese with English abstract)

@item @strong{Limnology and Oceanography}

@item @strong{Marine Biology}

@item @strong{Marine Ecology Progress Series}

@item @strong{Monthly Weather Review}

@item @strong{Oceanography}

@item @strong{Paleoceanography}

@item @strong{Progress in Oceanography}

@item @strong{Quaternary Research}

@item @strong{Scientia Marina}

@item @strong{South African Journal of Marine Science}

@item @strong{Umi no Kenkyu} (Japanese version for Journal of Oceanography, in
Japanese with English abstract)
@end itemize

@b{Journals in Physics, Chemistry, etc.}
@itemize @bullet

@item @strong{Applied Physics A}

@item @strong{Journal of Fluid Mechanics}

@item @strong{Journal of Physical Chemistry B}

@item @strong{Physica D}

@item @strong{Physics of Fluids}

@item @strong{Physics A}

@item @strong{Physics Letters B}

@item @strong{Physical Review C}

@item @strong{Physical Review Letters}

@item @strong{Research on Chemical Intermediates}

@item @strong{Theoretical Computational Fluid Dynamics}
@end itemize

@b{Other Journals}
@itemize @bullet

@item @strong{Nature}
@end itemize

@b{Books, Monographs, etc.}
@itemize @bullet

@item @strong{The Atlas of Hawai'i} (University of Hawai'i Press)

@item @strong{Differential Equations with Applications to Biology} (American Mathematical Society)

@item @strong{Ocean Drilling Program} publications
@end itemize


@c HTML <!-- newfile Acknowledgments.html "Gri: Acknowledgments" "Acknowledgments" -->

@node   Acknowledgments, License, Gri in the Press, Top
@comment  node-name,  next,  previous,  up
@chapter Acknowledgments
@cindex user input to Gri
@cindex acknowledgments

Over the years, many Gri users have been kind enough to help in its development. Some
have done so by sending in bug reports, others by requesting features, others by
submitting patches.  A few of their names are:
Ivo Alxneit,
@cindex contributor, Ivo Alxneit
@cindex Ivo Alxneit (contributor)
Karin Bryan,
@cindex Karin Bryan (contributor)
@cindex contributor, Karin Bryan
Sara Bennett,
@cindex Sara Bennett (contributor)
@cindex contributor, Sara Bennett
Luke Blaikie,
@cindex Luke Blaikie (contributor)
@cindex contributor, Luke Blaikie
Dave Brickman,
@cindex Dave Brickman (contributor)
@cindex contributor, Dave Brickman
Steve Cayford,
@cindex Steve Cayford (contributor)
@cindex contributor, Steve Cayford
Clyde Clements,
@cindex Clyde Clements (contributor)
@cindex contributor, Clyde Clements
Andrew Collier,
@cindex Andrew Collier (contributor)
@cindex contributor, Andrew Collier
Pierre Flament,
@cindex Pierre Flament (contributor)
@cindex contributor, Pierre Flament
Peter Galbraith,
@cindex Peter Galbraith (contributor)
@cindex contributor, Peter Galbraith
Dave Hebert,
@cindex Dave Hebert (contributor)
@cindex contributor, Dave Hebert
David A. Holland,
@cindex David A Holland (contributor)
@cindex contributor, David A. Holland
Christopher Illies,
@cindex Christopher Illies (contributor)
@cindex contributor, Christopher Illies
Cody Kirkpatrick,
@cindex Cody Kirkpatrick (contributor)
@cindex contributor, Cody Kirkpatrick
Thomas Larsen,
@cindex Thomas Larsen (contributor)
@cindex contributor, Thomas Larsen
Alejandro López-Valencia,
@cindex Alejandro Lopez-Valencia (contributor)
@cindex contributor, Alejandro Lopez-Valencia
Kawamura Masao,
@cindex Kawamura Masao (contributor)
@cindex contributor, Kawamura Masao
Steve Matheson,
@cindex Steve Matheson (contributor)
@cindex contributor, Steve Matheson
Brian May,
@cindex Brian May, contributor
@cindex contributor, Brian May
Ed Nather,
@cindex Ed Nather (contributor)
@cindex contributor, Ed Nather
Roman Neuhauser,
@cindex Roman Neuhauser (contributor)
@cindex contributor, Roman Neuhauser
Carl Osterwisch,
@cindex Carl Osterwisch (contributor)
@cindex contributor, Carl Osterwisch
Richard Andrew Miles Outerbridge,
@cindex Richard Andrew Miles Outerbridge (contributor)
@cindex contributor, Richard Andrew Miles Outerbridge
Tim Powers,
@cindex Tim Powers (contributor)
@cindex contributor, Tim Powers
Jinyu Sheng,
@cindex Jinyu Sheng (contributor)
@cindex contributor, Jinyu Sheng
Toru Suzuki,
@cindex Toru Suzuki (contributor)
@cindex contributor, Toru Suzuki
Keith Thompson,
@cindex Keith Thompson (contributor)
@cindex contributor, Keith Thompson
David Trueman,
@cindex David Trueman (contributor)
@cindex contributor, David Trueman
Wolfgang Voegeli,
@cindex contributor and bug-fixer, Wolfgang Voegeli
@cindex Wolfgang Voegeli (contributor and bug fixer)
Jeff Whitaker,
@cindex Jeff Whitaker (contributor)
@cindex contributor, Jeff Whitaker
and George White.
@cindex George White (contributor)
@cindex contributor, George White

Prime among these is Peter Galbraith, who has been a close collaborator in Gri
development and in my scientific work, for two (!) decades.

To all, thanks.


@c HTML <!-- newfile License.html  "Gri: License" "License" -->

@node   License, Concept Index, Acknowledgments, Top
@comment  node-name,  next,  previous,  up
@chapter License
@cindex license
Gri is distributed under the GPL public license, an Open Source license
that provides certain rights and freedom to users, notably the access
to source code and the right to modify it and/or redistribute it.
The full text of the GPL license is given below.

@example
		    GNU GENERAL PUBLIC LICENSE
		       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software
     Foundation, Inc.  59 Temple Place, Suite
     330, Boston, MA 02111-1307 USA

 Everyone is permitted to copy and distribute
 verbatim copies of this license document, but
 changing it is not allowed.

			    Preamble

  The licenses for most software are designed to
take away your freedom to share and change it.
By contrast, the GNU General Public License is
intended to guarantee your freedom to share and
change free software--to make sure the software
is free for all its users.  This General Public
License applies to most of the Free Software
Foundation's software and to any other program
whose authors commit to using it.  (Some other
Free Software Foundation software is covered by
the GNU Library General Public License instead.)
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 this service 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 make
restrictions that forbid anyone to deny you these
rights or to ask you to surrender the rights.
These restrictions translate to certain
responsibilities for you if you distribute copies
of the software, or if you modify it.

  For example, if you distribute copies of such a
program, whether gratis or for a fee, you must
give the recipients all the rights that you have.
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.

  We protect your rights with two steps: (1)
copyright the software, and (2) offer you this
license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we
want to make certain that everyone understands
that there is no warranty for this free software.
If the software is modified by someone else and
passed on, we want its recipients to know that
what they have is not the original, so that any
problems introduced by others will not reflect on
the original authors' reputations.

  Finally, any free program is threatened
constantly by software patents.  We wish to avoid
the danger that redistributors of a free program
will individually obtain patent licenses, in
effect making the program proprietary.  To
prevent this, we have made it clear that any
patent must be licensed for everyone's free use
or not licensed at all.

  The precise terms and conditions for copying,
distribution and modification follow.

		    GNU GENERAL PUBLIC LICENSE

   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION
   AND MODIFICATION

  0. This License applies to any program or other
work which contains a notice placed by the
copyright holder saying it may be distributed
under the terms of this General Public License.
The "Program", below, refers to any such program
or work, and a "work based on the Program" means
either the Program or any derivative work under
copyright law: that is to say, a work containing
the Program or a portion of it, either verbatim
or with modifications and/or translated into
another language.  (Hereinafter, translation is
included without limitation in the term
"modification".)  Each licensee is addressed as
"you".

Activities other than copying, distribution and
modification are not covered by this License;
they are outside its scope.  The act of running
the Program is not restricted, and the output
from the Program is covered only if its contents
constitute a work based on the Program
(independent of having been made by running the
Program).  Whether that is true depends on what
the Program does.

  1. You may copy and distribute 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 and disclaimer of
warranty; keep intact all the notices that refer
to this License and to the absence of any
warranty; and give any other recipients of the
Program a copy of this License along with the
Program.

You may charge a fee for the physical act of
transferring a copy, and you may at your option
offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the
Program or any portion of it, thus forming a work
based on the Program, and copy and distribute
such modifications or work under the terms of
Section 1 above, provided that you also meet all
of these conditions:

    a) You must cause the modified files to carry
    prominent notices stating that you changed
    the files and the date of any change.

    b) You must cause any work that you
    distribute or publish, that in whole or in
    part contains or is derived from the Program
    or any part thereof, to be licensed as a
    whole at no charge to all third parties under
    the terms of this License.

    c) If the modified program normally reads
    commands interactively when run, you must
    cause it, when started running for such
    interactive use in the most ordinary way, to
    print or display an announcement including an
    appropriate copyright notice and a notice
    that there is no warranty (or else, saying
    that you provide a warranty) and that users
    may redistribute the program under these
    conditions, and telling the user how to view
    a copy of this License.  (Exception: if the
    Program itself is interactive but does not
    normally print such an announcement, your
    work based on the Program is not required to
    print an announcement.)

These requirements apply to the modified work as
a whole.  If identifiable sections of that work
are not derived from the Program, and can be
reasonably considered independent and separate
works in themselves, then this License, and its
terms, do not apply to those sections when you
distribute them as separate works.  But when you
distribute the same sections as part of a whole
which is a work based on the Program, the
distribution of the whole must be on the terms of
this License, whose permissions for other
licensees extend to the entire whole, and thus to
each and every part regardless of who wrote it.

Thus, it is not the intent of this section to
claim rights or contest your rights to work
written entirely by you; rather, the intent is to
exercise the right to control the distribution of
derivative or collective works based on the
Program.

In addition, mere aggregation of another work not
based on the Program with the Program (or with a
work based on the Program) on a volume of a
storage or distribution medium does not bring the
other work under the scope of this License.

  3. You may copy and distribute the Program (or
a work based on it, under Section 2) in object
code or executable form under the terms of
Sections 1 and 2 above provided that you also do
one of the following:

    a) Accompany it with the complete
    corresponding machine-readable source code,
    which must be distributed under the terms of
    Sections 1 and 2 above on a medium
    customarily used for software interchange;
    or,

    b) Accompany it with a written offer, valid
    for at least three years, to give any third
    party, for a charge no more than your cost of
    physically performing source distribution, a
    complete machine-readable copy of the
    corresponding source code, to be distributed
    under the terms of Sections 1 and 2 above on
    a medium customarily used for software
    interchange; or,

    c) Accompany it with the information you
    received as to the offer to distribute
    corresponding source code.  (This alternative
    is allowed only for noncommercial
    distribution and only if you received the
    program in object code or executable form
    with such an offer, in accord with Subsection
    b above.)

The source code for a work means the preferred
form of the work for making modifications to it.
For an executable work, complete source code
means all the source code for all modules it
contains, plus any associated interface
definition files, plus the scripts used to
control compilation and installation of the
executable.  However, as a special exception, the
source code distributed need not include anything
that is normally distributed (in either source or
binary form) with the major components (compiler,
kernel, and so on) of the operating system on
which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is
made by offering access to copy from a designated
place, then offering equivalent access to copy
the source code from the same place counts as
distribution of the source code, even though
third parties are not compelled to copy the
source along with the object code.

  4. You may not copy, modify, sublicense, or
distribute the Program except as expressly
provided under this License.  Any attempt
otherwise to copy, modify, sublicense or
distribute the Program is void, and will
automatically terminate your rights under this
License.  However, parties who have received
copies, or rights, from you under this License
will not have their licenses terminated so long
as such parties remain in full compliance.

  5. You are not required to accept this License,
since you have not signed it.  However, nothing
else grants you permission to modify or
distribute the Program or its derivative works.
These actions are prohibited by law if you do not
accept this License.  Therefore, by modifying or
distributing the Program (or any work based on
the Program), you indicate your acceptance of
this License to do so, and all its terms and
conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or
any work based on the Program), the recipient
automatically receives a license from the
original licensor to copy, distribute or modify
the Program subject to these terms and
conditions.  You may not impose any further
restrictions on the recipients' exercise of the
rights granted herein.  You are not responsible
for enforcing compliance by third parties to this
License.

  7. If, as a consequence of a court judgment or
allegation of patent infringement or for any
other reason (not limited to patent issues),
conditions are imposed on you (whether by court
order, agreement or otherwise) that contradict
the conditions of this License, they do not
excuse you from the conditions of this License.
If you cannot distribute so as to satisfy
simultaneously your obligations under this
License and any other pertinent obligations, then
as a consequence you may not distribute the
Program at all.  For example, if a patent license
would not permit royalty-free redistribution of
the Program by all those who receive copies
directly or indirectly through you, then the only
way you could satisfy both it and this License
would be to refrain entirely from distribution of
the Program.

If any portion of this section is held invalid or
unenforceable under any particular circumstance,
the balance of the section is intended to apply
and the section as a whole is intended to apply
in other circumstances.

It is not the purpose of this section to induce
you to infringe any patents or other property
right claims or to contest validity of any such
claims; this section has the sole purpose of
protecting the integrity of the free software
distribution system, which is implemented by
public license practices.  Many people have made
generous contributions to the wide range of
software distributed through that system in
reliance on consistent application of that
system; it is up to the author/donor to decide if
he or she is willing to distribute software
through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear
what is believed to be a consequence of the rest
of this License.

  8. If the distribution and/or use of the
Program is restricted in certain countries either
by patents or by copyrighted interfaces, the
original copyright holder who places the Program
under this License may add an explicit
geographical distribution limitation excluding
those countries, so that distribution is
permitted only in or among countries not thus
excluded.  In such case, this License
incorporates the limitation as if written in the
body of this License.

  9. The Free Software Foundation may publish
revised and/or new versions of the 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 a version
number of this License which applies to it and
"any later version", you have the option of
following the terms and conditions either of that
version or of any later version published by the
Free Software Foundation.  If the Program does
not specify a version number of this License, you
may choose any version ever published by the Free
Software Foundation.

  10. If you wish to incorporate parts of the
Program into other free programs whose
distribution conditions are different, write to
the author to ask for permission.  For software
which is copyrighted by the Free Software
Foundation, write to the Free Software
Foundation; we sometimes make exceptions for
this.  Our decision will be guided by the two
goals of preserving the free status of all
derivatives of our free software and of promoting
the sharing and reuse of software generally.

			    NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF
CHARGE, 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.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE
LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT
HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE 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.

		     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
convey 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)
    yyyy <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 2 of the License, or (at your
    option) any later version.

    This program is distributed in the hope that
    it will be useful, but WITHOUT ANY WARRANTY;
    without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR
    PURPOSE.  See the GNU General Public License
    for more details.

    You should have received a copy of the GNU
    General Public License along with this
    program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330,
    Boston, MA 02111-1307 USA


Also add information on how to contact you by
electronic and paper mail.

If the program is interactive, make it output a
short notice like this when it starts in an
interactive mode:

    Gnomovision version 69, Copyright (C) yyyy
    name of author Gnomovision 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, the commands you use
may be called something other than `show w' and
`show c'; they could even be mouse-clicks or menu
items--whatever suits your program.

You should also get your employer (if you work as
a programmer) or your school, if any, to sign a
"copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright
  interest in the program `Gnomovision' (which
  makes passes at compilers) written by James
  Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This 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 Library General Public License instead of
this License.
@end example




@c HTML <!--

@node   Concept Index, Index of Commands, License, Top
@comment node-name, next, previous, up
@unnumbered Index, general
@printindex cp

@node   Index of Commands, Index of Builtins, Concept Index, Top
@comment node-name, next, previous, up
@unnumbered Index of Commands
@printindex fn

@node   Index of Builtins, , Index of Commands, Top
@comment  node-name,  next,  previous,  up
@unnumbered Index of Built-in Variables and Synonyms
@printindex vr

@c HTML -->

@c @summarycontents
@c @contents
@bye
