\chapter{Overview of auxillary routines and scripts\label{sec:MSCPROGS}}
Several diagnostic and setup tools have been developed at NERSC,
these are briefly described here. One of the main changes relative to previous
versions of the NERSC diagnostic/setup tools is that they are now gathered in
one location, with a common makefile setup. This makes porting the program code
much easier.

Many of the routines used by several different diagnostic tools have also been
put into libraries. Routines such as the conformal mapping tools, time
processing tools, and routines for reading model grid and  model restart, daily,
weekly and archive files have all been moved into a library directory. This way
duplication of work is avoided.

\section{Main directory}
The routines are gathered under the directory MSCProgs. On the svn, this directory is located
at \\[0.7em]
\indent \indent \file{./hycom/MSCProgs/}\\[0.7em]
This means, that the program are most of the time independent of the HYCOM version. However, in some case the version matter, then there will be a different executable followed by the version number. The contents of that directory are 
\begin{verbatim}
   src
   src_others
   include
   lib
   Input
   data
   scripts
   bin
   bin_setup
\end{verbatim}
The \file{src/} directory contains the code for the different routines which can
be used to diagnose HYCOM output, plus various other convenient tools.
The \file{src\_others/} directory is meant to contain 3rd party tools, which are
again used by the various tools located in the \file{src/} directory. Presently
\file{src\_others/} only contains the FES2004 tidal database routines.
%
The \file{include/} and \file{lib/} directory will contain include and library
files, respectively, which are used by the different routines in the \file{src/}
directory. 

The \file{Input/} directory is meant to contain examples of input
files used by the different diagnostic and setup tools. 
%
The \file{data/} directory contains datasets. These are typically datasets of
a relatively small size.
% 
The tools themselves are placed in the \file{bin/} and
\file{bin\_setup/} directories. The latter directory is, as the name implies,
mainly meant for tools related to the setup of NERSC-HYCOM.
%
The \file{scripts/} directory contains various useful scripts.

To compile the tools, any 3rd party tools in \file{src\_others/} should be
compiled first, and then the routines in the \file{src/} directory should be
compiled. 

\section{The ``src/'' directory}
\subsection{Overview}
The contents of the \file{src/} directory are designed to be relatively easy to
port to different systems, with a minimal amount of hand configuration. There is
a top-level makefile in this directory, which will perform the compilation in
all the subdirectories under the \file{src/} directory. The makefile can also be
used to install all the programs in the \file{src/} directory into the
\file{bin/} and \file{bin\_setup/} directories. 


The configuration files for the makefile are located in the \file{Make.Inc/}
subdirectory of \file{src/}. Proper setup of configuration files is needed to
compile the different programs correctly.
\subsection{Configuring the make include file}
To prepare the include file needed to compile the different utilities, you need
to set up a file called \file{make.inc} inside the \file{Make.Inc/} directory.
This file will contain all the macro definitions needed for compiling the
model. The macros are described in Table~\ref{tab:macros}.
\begin{table}[tb]
\begin{tabular}{| m{.2\textwidth} | p{0.6\textwidth} |}
\hline
Variable & Description \\
\hline
CF90           & Denotes the FORTRAN90 compiler to use. \\
CF77           & Denotes the FORTRAN compiler to use, usually the same as CF90. \\
CC             & Denotes the C compiler to use. \\
LD             & Denotes the linker to use, usually the same as CF90. \\
CPP            & Denotes the c preprocessor to use. \\
F90FLG         & Compiler flags for compiling free-source code (flag name is
                 a bit misleading).\\
F77FLG         & Compiler flags for compiling fixed-source code (flag name is 
                 a bit misleading).\\
FFLAGS         & FORTRAN/FORTRAN90 compiler flags. \\
CFLAGS         & C compiler flags. \\
CPPFLAGS       & C preprocessor flags.\\
LINKFLAGS      & Flags passed to the linker.\\
LIBS           & Library flags (library search directory and actual library). \\
INCLUDE        & Include flags (include search directory). \\
NCARGCF90      & FORTRAN90 Compiler wrapper for NCAR Graphics. \\
NCARGCF77      & FORTRAN Compiler wrapper for NCAR Graphics. \\
NCARGCC        & C Compiler wrapper for NCAR Graphics. \\
NCARGLD        & Linker wrapper for NCAR Graphics. \\
FFLAGSR4       & Real*4 version of FORTRAN/FORTRAN90 flags. \\
CFLAGSR4       & Real*4 version of C flags. \\
\hline
\end{tabular}
\caption{\label{tab:macros}Makefile macros set in \file{make.inc}.}
\end{table}


The CPP flags defined in the macro CPPFLAGS must be set properly for the machine
and compilers you use. Table~\ref{tab:mscCPP} gives the most common values for
the CPP flags. Note that some of the flags do the same thing. The safe option is
to define both the FFTW and the LAPACK flags and undefine the ESSL flag, which 
should work on most
architectures. On some AIX (IBM) machines the Engineering Scientific Subroutine
Library (ESSL) is also installed and can be used. If the ESSL flag is defined on
these machines, you should undefine the FFTW and LAPACK CPP flags.
\begin{table}[htb]
\begin{tabular}{| m{.2\textwidth} | p{0.6\textwidth} |}
\hline
CPP flag & Description \\
\hline
IARGC          & Flag is used to denote if the FORTRAN iargc() function must be
                 defined as external. This varies from compiler to compiler.\\
\hline
FFTW           & Define this flag to use the ``Fastest Fourier Transform in the
                 West'' routines. This popular GNU licensed FFT library is
                 installed on most HPC machines. You must also define the
                 libraries and include flags in the LIBS and INCLUDE macros. \\
\hline
LAPACK         & Define this flag to use the LAPACK library. This is also
                 installed ``everywhere''. You must also define the
                 libraries and include flags in the LIBS and INCLUDE macros.\\
\hline
ESSL           & Define this flag to use the ``Engineering Scientific Subroutine
                 Library'' library, available on AIX(IBM) machines. 
                 If you define this, FFTW and LAPACK must be
                 undefined in the CPP flags.  You must also define the
                 libraries and include flags in the LIBS and INCLUDE macros. \\
\hline
\end{tabular}
\caption{\label{tab:mscCPP}CPP flags set in the CPPFLAGS macro in \file{make.inc}.}
\end{table}
Finally note that the IARGC flag may be needed for some compilers. Set it if you
get messages about undefined iargc during compilation.

There are already several make include files inside the \file{Make.Inc/}
directory, use these as starting points when setting up the model for a new
machine. Once a suitable include file is created link or copy it to the file
\file{make.inc}.

\subsection{Compiling the code}
After the make include file \file{make.inc} has been set up the code can be compiled. First make
sure that you start with a clean slate by typing \\[.7em]
\indent\indent make clean\\[.7em]
This is mainly needed when the code is ported to a new machine, or if the
\file{make.inc} is changed. Normally it is not needed.  To compile the code
type \\[.7em]
\indent\indent make all\\[.7em]
and you should be greeted with compiler output flying over your terminal screen.
If something fails, it can usually be corrected by making sure that the file
\file{Make.Inc/make.inc} is properly set up. If compilation succeeds, the
subdirectories of the \file{src/} directory should contain the compiled
routines. To move them into the \file{bin/} and \file{bin\_setup/} directories
type \\[.7em]
\indent\indent make install\\[.7em]

If no errors occur during compilation, all the executable will be copied to the bin and bin\_setup directory.
Make sure that this is the case.
Some folder that are rarely used or in development are removed in purpose from the Makefile.
For example Note the NCAR Graphics wrappers and real*4 versions of the compiler flags
are used to compile visualization routines inside the \file{NCARG-test/}
directory. These can sometimes be hard to port to different machines. Don't be
overly alarmed if these fail to compile on some machines, there are different
diagnostics routines which do similar things.  
and the routines should be properly setup. They can now be easily accessed by
setting the PATH variable of your shell (\$MSCPROGS/bin and  \$MSCPROGS/bin\_setup).


\section{The ``src/Nersclib/'' directories and its libraries}
The \file{Nersclib/} directory contain the libraries needed to compile most of
the routines in the \file{src/} subdirectories. When you type ``gmake all'' in the \file{src/} 
directory, the contents of the \file{src/Nersclib/} will be compiled and the
output is placed in the \file{include/} and \file{lib/} directories. 
%
When the other routines in the \file{src/} directories are compiled, they will
use the contents of \file{include/} and \file{lib/} to gain access to the
functionality in these libraries.

The routines inside the \file{Nersclib/} directory cover a range of common
operations. Typically they are used for reading the model grid (longitude,
latitude, depth and masks), working with the conformal mapping routines, and reading
hycom files such as restart, daily average, weekly average and archive files.
Some
information is also available in the FORTRAN files under the \file{Nersclib/}
directory. A rough overview of the functionality of the different routines in
\file{Nersclib/} is given in Table~\ref{tab:nersclib_functions}.
\begin{table}[tb]
\centering
   \begin{threeparttable}
      \begin{tabular}{|l|p{.7\textwidth}|}
         \hline
         Fortran file in \file{Nersclib/} & Description \\
         \hline
         \file{mod\_confmap.F90} & Contains functions and routines for using the
         conformal mapping. Includes grid transformations from lon,lat to i,j.  \\
         \file{mod\_grid.F90} & Used to read model grid and topography. \\
         \file{mod\_hycomfile\_io.F90} & Use to read fields from several
         hycom-type files \\
         \file{mod\_parameters.F90} & Contains a few commonly used parameters \\
         \file{mod\_spline\_calc.F90} & Used to calculate vertical interpolation
            (spline, staircase and linear). \\
         \file{mod\_xc.F} & Low-level routine for initialising HYCOM grid size. Standard
         HYCOM routine.\\
         \file{mod\_za.F} & Low-level routine for reading HYCOM files. Standard
         HYCOM routine. \\
         \file{rotate.F90}\tnote{1} & Simple routine for rotating grid between
         east/north directions  and grid directions.\\
         \file{sort.F90}\tnote{1} & Sorting routine.\\
         \file{spherdist.F90}\tnote{1} & Routine for calculating sphere distance
         between two points.\\
         \file{machi\_c.c}\tnote{1,2} & Various machine-dependent routines.\\
         \file{machine.}\tnote{1,2} & Various machine-dependent routines.\\
         \file{wtime.F}\tnote{1,2} & Various machine-dependent routines.\\
         \hline
      \end{tabular}
      \begin{tablenotes}
         \item[1]{Does not need a use statement.}
         \item[2]{Rarely needed, Mainly used by \file{mod\_xc.F} and
         \file{mod\_za.F}. }
      \end{tablenotes}
      \caption{\label{tab:nersclib_functions}Fortran files and the use statements and
      libraries needed to access functionality of the Fortran files.}
   \end{threeparttable}
\end{table}

The libraries installed in the \file{lib/} directories are
\begin{itemize}
\item The library \file{libconfmap.a}, which contains the functionality of the
conformal mapping routines.
\item The library \file{libhycnersc.a}, which contains all other functionality
in the fortran files under \file{Nersclib/}
\end{itemize}
Inside the \file{include/} directory are all the modules which are needed in
conjunction with the different libraries. To use functions or subroutines
associated with the different fortran files inside \file{Nersclib/},
Table~\ref{tab:nersclib} lists the combination of ``use'' statements and libraries
needed for successfully compiling the code using these routines.
\begin{table}[tb]
\centering
   \begin{threeparttable}
      \begin{tabular}{|l|l|l|}
         \hline
         Fortran file in \file{Nersclib/} & use statement needed & library needed \\
         \hline
         \file{mod\_confmap.F90} & use mod\_confmap & \file{libconfmap.a} \\
         \file{mod\_grid.F90} & use mod\_grid & \file{libhycnersc.a} \\
         \file{mod\_hycomfile\_io.F90} & use mod\_hycomfile & \file{libhycnersc.a} \\
         \file{mod\_parameters.F90} & use mod\_parameters & \file{libhycnersc.a} \\
         \file{mod\_spline\_calc.F90} & use mod\_spline\_calc & \file{libhycnersc.a} \\
         \file{mod\_xc.F} & use mod\_xc & \file{libhycnersc.a} \\
         \file{mod\_za.F} & use mod\_za & \file{libhycnersc.a} \\
         \file{rotate.F90} & --\tnote{1} & \file{libhycnersc.a} \\
         \file{sort.F90} & --\tnote{1} & \file{libhycnersc.a} \\
         \file{spherdist.F90} & --\tnote{1} & \file{libhycnersc.a} \\
         \file{machi\_c.c} & --\tnote{1,2} & \file{libhycnersc.a} \\
         \file{machine.F} & --\tnote{1,2} & \file{libhycnersc.a} \\
         \file{wtime.F} & --\tnote{1,2} & \file{libhycnersc.a} \\
         \hline
      \end{tabular}
      \begin{tablenotes}
         \item[1]{Does not need a use statement.}
         \item[2]{Rarely needed, Mainly used by \file{mod\_xc.F} and
         \file{mod\_za.F}. }
      \end{tablenotes}
      \caption{\label{tab:nersclib}Fortran files in \file{Nersclib/} and the use statements and
      libraries needed to access functionality of the Fortran files.}
   \end{threeparttable}
\end{table}
Examples of the usage of the \file{Nersclib/} can be found in almost all of the
routines located under the \file{src/} directory. Use these as staring points
for their usage.
Unfortunately the documentation is somewhat lacking apart from
what is given in the FORTRAN files. A few pointers is given below for some of
the most commonly used modules.

\paragraph{mod\_za, mod\_xc and mod\_grid:}
%
Typically, the majority of the
routines depend on functionality inside the modules mod\_xc and
mod\_za. In almost all cases these should be initialized first, through
these  statements (in that order) \\[0.7em]
\indent\indent call xcspmd() \\
\indent\indent call zaiost() \\[0.7em]
which initialize the grid size in mod\_xc and I/O setup in mod\_za. The routine
mod\_grid is another frequently used module. After mod\_xc and mod\_za has been
initialized, mod\_grid will contain grid information (depth, longitude, latitude
and more) after issuing the command\\[0.7em]
\indent\indent call get\_grid() \\[0.7em]
Examples of its use can be found in most routines in the \file{src/} directory.

\paragraph{mod\_spline\_calc:}
The module mod\_spline\_calc is used for vertical interpolation. It needs an
initialization statement before splines can be calculated. This initialization
call sets the vertical levels to interpolate to.  It is initialized
either from a input file called \file{depthlevels.in} through the initialization
call \\[0.7em]
\indent\indent  call spline\_calc\_ini\_fromfile(cmethod) \\[.7em]
or it can be initialized from arguments\\[0.7em]
\indent\indent  call spline\_calc\_ini\_frominput(cmethod,deeps,ndeep) \\[.7em]
Here, cmethod is a text string denoting the vertical interpolation method,
whereas deeps and ndeeps is an array with ndeeps elements containing the
vertical levels. TODO: clean up, refer to \file{depthlevels.in}. After that the
various spline interpolation methods can be called. Examples of its usage is in
the directory \file{src/Hyc2proj/}.

\paragraph{mod\_hycomfile\_io:}
The module mod\_hycomfile\_io is used for reading various hycom files(restart,
averages, archives).  It relies on the use of the hycomfile type. A typical way
to initalize and read fields is \\[.7em]
\indent\indent type(hycomfile) :: hfile \\
\indent\indent ...                      \\
\indent\indent call initHF(hfile,filename,ftype) \\
\indent\indent call HFReadField(hfile,fld2D,idm,jdm,'saln',1,1)\\[.7em]
which initializes the hfile type, based on filename and filetype (filetype can
be either ``restart'', ``nersc\_weekly'', ``nersc\_daily'' or ``archv''). It
then reads salinity at depth level 1 and time level 1 into the ``fld2D''
array with dimensions $(idm,jdm)$. An example of its use can be found in many
places, for instance in \file{src/ExtractNC3D/}. There is also some additional
info in the header of \file{Nersclib/mod\_hycomfile\_io.F90}. 


\paragraph{mod\_confmap:}
The module mod\_confmap sets up the conformal mapping routines, and 
is used in several places throughout the \file{src/} directory. The conformal
mapping routines also rely on an initialization statement\\[.7em]
\indent\indent call initconfmap(idm,jdm) \\[.7em]
which initializes the data inside the mod\_confmap module. Here, $idm$ and $jdm$
are the horizontal grid size dimensions. The confmap routines are used to
transform between horizontal grid indexes $(i,j)$ and longitude, latitude
values. An example of its use can be found inside the
\file{src/ConfmapRoutines/} directory.


\section{Quick explanation of the rest of ``src/''}
The following is a very short description of the directories under the
\file{src/} directory.
Most of these routines will require the grid/depth files of the models, many of them
also need the conformal mapping file \file{grid.info}. 

Note that additional info is available in most of these directories, through
README files, but also in the routines themselves. Most routines which take
arguments give additional info when run without arguments. In addition, some
routines contain directories with matlab snippets for reading/diagnosing results of the
routines.

\subsection{Average - Create 3D averages of HYCOM files\label{sec:hycave}}
This directory is for creating the routine \file{hycave}, which can be used to
calculate ``averages'' of hycom files.  The  final file will have XXX for rungen and 9999 for year 99 for month or 999 for day. (example: XXXAVE9999\_999\_9.a or XXXDAILY9999\_999\_99.a) Run with no arguments for a short
description of its usage. 

\subsection{Barstrf - Create Barotropic streamfunction}
This directory is for the routine \file{hyc2bastrf}, which is used to
calculate the barotropic stream function. Run with no arguments for a short
description of its usage.

\subsection{Conf\_grid - generation of model grids\label{sec:confmap}}
This routine is used to generate model grids using the conformal mapping tools. It creates the
regional grid/depth files which are used by HYCOM during model runs. Some
guidelines for generating model grids with this tool is given in
Section~\ref{chp:confmap}.

\subsection{ConfmapRoutines - Going between grid indexes and geographical
positions}
This directory contains routines for going from longitude latitude to
grid indexes, using the conformal mapping tools. 

\subsection{Copymem - copies ensemble members}
Creates routine \file{copymem}, used to copy from one ensemble member to
another. Mainly used during data assimilation.

\subsection{Curviint - restart file interpolation}
Creates the executable \file{curviint}.  Used to interpolate restart files from
a model onto another model grid. Help is available. This routine is also used
by the setup routine \file{curviint.sh}, see Section~\ref{sec:setup_div}.

\subsection{DateTools - convert between ordinal day to real date}
Routines used to go between real dates and ordinal days relative to a reference
date. Uses the Gregorian calendar only.

\subsection{DProfile - Vertical profiles.}
Creates the routine \file{dprofile}, which is used 
to extract vertical profiles from model files. Run with no arguments for more
info. This routine uses the ``extract'' files to specify fields to extract from
the various HYCOM files, see Section~\ref{sec:input_extract} for more info on
this file format.

\subsection{Ensstat - calculates ensemble/time statistics}
Various routines used to calculate ensemble statistics. Can also be used with
daily and weekly files. Routines can be run without arguments for usage
information.  Some routines need the ``nco'' tools to work. Note that this
routine can do ensemble statistics as well as time-domain statistics.


\subsection{ExtractNC2D - Convert from hycom files to 2D netcdf
files\label{sec:routine_exnc2d}}
Creates routines for conversion between hycom files and netcdf files with 2D
fields. Main routine is the script \file{m2nc}, which is used to process input
arguments etc. Run \file{m2nc} with no arguments for more info.
%
The routines needs input files of the ``extract'' type, described in
Section~\ref{sec:input_extract}.


\subsection{ExtractNC3D - Convert from hycom files to 3D netcdf fields}
Creates routine \file{h2nc} for conversion between hycom files and netcdf files with 3D
fields. Run \file{h2nc} with no arguments for more info.
%
Needs input files of the ``extract'' type, described in Section~\ref{sec:input_extract}.

\subsection{FindLayer - find layer thickness between threshoolds}
Routine \file{findlayer} calculates layer thickness between two levels of a
variable, for instance layer thickness of salinity between 35 and 36 psu. Run
with no arguments for more information.

\subsection{GP - extract data from grid point files}
Various routines for extracting data from GP time series files. Routines can be
run with no arguments for more info. Activating GP timeseries in NERSC-HYCOM is
done in \file{infile.in}, See Section~\ref{sec:infile.in}.

\subsection{GPdens - grid point time series statistics}
Routine \file{gpdens} calculates statistics of a grid point time series at a
specified depth level. The focus is on current statistics, calculating speed
density, exceedence plots, tidal decomposition etc. 
The routine \file{gpdens} can be run with no arguments for more info. 
%
Activating GP timeseries in NERSC-HYCOM is
done in \file{infile.in}, See Section~\ref{sec:infile.in}.

\subsection{GridToLL - interpolation to regular lon/lat grid}
Test routine \file{gridtoll} for interpolating fields from NetCDF files (tmp1.nc, from Section Section~\ref{sec:routine_exnc2d}) to a regular
grid. example: gridtoll -98:.1:20 10:.1:60 temp01  \\
For extracting the temperature of the first layer into a grid with 1:20 and 1:60 discretization.
 

\subsection{Hyc2proj - interpolation to projection grid and
z-levels\label{sec:hyc2proj}}
This directory contains the routines \file{hyc2proj} and \file{hyc2stations},
two routines which can be used to interpolate HYCOM model results. The routine
\file{hyc2proj} interpolates HYCOM fields to a map projection and fixed
z-levels, while \file{hyc2stations} interpolates HYCOM fields to spatial
locations and fixed z-levels. The routine \file{hyc2stations} can be used to
calculate vertical cross sections, for instance. Both routines produce NetCDF
files as final output.	
The routine \file{hyc2proj} is a interpolation routine which takes command-line
arguments, run it with no arguments for a brief summary of the options. In
addition it requires a few input files to run. These files are
\begin{itemize}
\item \file{proj.in} to specify the horizontal projection to use, see
   Section\ref{sec:input_proj}.
\item \file{depthlevels.in} to specify the depth levels to interpolate to, see
   Section\ref{sec:input_depthlevels}
\item ``extract'' files to specify fields to extract from restart, daily and weekly average , see
   Section\ref{sec:input_extract}.
\end{itemize}
These input files will be read by the \file{hyc2proj} routine, and the
projection to use (from proj.in), the depth levels to interpolate to (from depthlevel.in), and the variables to
interpolate will be set accordingly (extract.???).  The interpolation itself is a two-stage
process.  It will first interpolate the model fields horizontally, using a
bi-linear interpolation method. When that is done the ocean 3D fields are still
on the hybrid vertical  grid. The vertical interpolation is then done, using a vertical
cubic spline method. There are also additional vertical interpolation methods
that can be used, such as ``staircase'' - which uses constant values when the
z-levels to interpolate to are positioned between the lower and upper interfaces
of a model layer. There is also a ``linear'' option which uses linear
interpolation between the midpoint of model layers. Both the ``staircase'' and
``linear'' methods are faster than the default spline method, but the spline
method often gives better/nicer looking results.


The routine \file{hyc2stations} is used to
interpolate model fields onto specified spatial positions. The positions are
grouped together, which can be used to define ``sections''. It also takes
command-line arguments, run with no arguments for a brief description of these.
To use the routine the following input files are needed
\begin{itemize}
\item \file{stations.in} to specify the points to interpolate to and the group
   definitions, see Section\ref{sec:input_stations}.
\item \file{depthlevels.in} to specify the depth levels to interpolate to, see
   Section\ref{sec:input_depthlevels}
\item ``extract'' files to specify fields to extract, see
   Section\ref{sec:input_extract}.
\end{itemize}
These input files are read by \file{hyc2stations} to set up the stations to
interpolate to, the vertical depth levels and fields to extract. As with
\file{hyc2proj} the interpolation is done in two stages. First bi-linear
interpolation  to the station positions, and then cubic splines in the vertical.
The routine does not support linear or staircase vertical interpolation, as
\file{hyc2proj} does.

The \file{hyc2stations} routine will organize the stations into ``groups'',
which is a way to organize the stations into disjoint sets. This way one can
group stations together to form vertical cross-sections, for instance. This
grouping is defined in the input file \file{stations.in}, described in
Section~\ref{sec:input_stations}.
%
Normally the hyc2stations routine produces one netcdf file per group defined.
However, it is possibe to modify this behaviour by setting the
CPP FLAG ``MULT\_GRP\_PER\_FILE'' in the makefile in the \file{Hyc2proj/}
directory. This way only one file  will be created, containing all the groups.

Also note that there is a small python script \file{setupstations.py} in this
directory, which can be used as an aid when setting up stations used in
\file{hyc2stations}. By specifying start and end points this routine will create
stations between these two points, in a format suitable for inclusion in
\file{stations.in}. These intermediate points are created following rhumb lines
(not great circles).

\subsection{IceDrift - calculation of sea-ice drift}
This directory contains a routine for calculating ice drift. Input is DAILY
average files, or specially formatted ensemble ice drift files. Not very well
documented. The CPP FLAG EVP\_DRIFT\_ASSIMILATION must be set in NERSC-HYCOM to
produce ensemble drift files.

\subsection{Idealized\_Grid - Setting up idealized grids and restart files}
The routines in this directory can be used to set up idealized grids and restart
files, which can be useful to test model behaviour. These files are only meant
as starting points, you will need some hand-editing to set up the configuration
you need. Basic cases such as seamount and flat-bottom channel are at least
partially implemented.

\subsection{InterpTest - unfinished interpolation ``toolchain'' }
Preliminary work on an interpolation ``toolchain'', where routines pipe result
from one program to another. Needs more work.

\subsection{MkEnsemble - creating a model ensemble}
The executable is called \file{mkensemble}. This routine can create a model ensemble. This is done by perturbing the layer thickness
in the hycom restart files, as well as perturbing the ice thickness fields in
any ice restart files. Input are given in the file \file{mkensemble.in}. The routine are working diffrently in 2.2.12 and 2.2.37. To get more info on how to run it with 2.2.12 run the executable without \file{mkensemble.in}. In version 2.2.37, this file will typically look like that:\\
\begin{verbatim}
TP4restart2011_249_00_mem
TP4restart1990_247_00ICE.uf
1              # Ensemble mem we are reading from
2              # Ensemble mem we are dumping in
0.05         # Std dev of log(d), no unit, 0.1 = 10\%
3            # Vertical correlation range   (layers)
10           # Horizontal correlation range (grid cells)
\end{verbatim}
In the first line, you specify the basename of the input file. In the second line you specify the ice input file (in the example they are not from the same initial file although this is recommended). Then you need to give the member you are reading from and to which member you are dumping the member into. It is possible to have the same input and output member.
Then follows specification about amplitude of the perturbation and the spatial correlation. In the example her, mkensemble will read the physic from TP4restart2011\_249\_00\_mem001.[a,b] and dump it into PERTTP4restart2011\_249\_00\_mem002.[a,b]. If ice record are present in the a,b files (i.e. if the FLAG SINGLE\_RESTART is activated) perturbed ice thickness will also be dumped. Beware that when HYCOM is running if SINGLE\_RESTART\_ONLY FLAG is not activated, the ice record in the a,b files have lower priority than the one in the ICE.uf. In addition, the program read the record corresponding to the first member in TP4restart1990\_247\_00ICE.uf and dump the ice fields with perturbed ice thickness into PERTURBED\_ICE.uf. If you don't have ice files or you don't want to perturb the ice, set "none" in the second line.

\subsection{Model\_input-x.x.xx: utility file}
This directory contains some program to create input files necessary for HYCOM when some specification are used. As these file are formatted differently  depending of the version of HYCOM there is one folder for each version. In 2.2.12 the only program is the one that produce the file for spatially varying thickness diffusion. Indeed, when negative value is given for thkdf4 in the blkdat.input, hycom will read a spatially varying value from a file call thkdf4.[a,b]. The reason for using spatially varying value is that thkdf4 can degrade quite strongly the stratification and should be only used when it is necessary (noise in the layer thickness below the mixed layer depth or crashes due to neg. dp). In TOPAZ we notice that thkdf4 was needed in the Gulf Stream area, but had a very bad impact at high latitude. Lower values are used there.

In 2.2.37, the program for creating spatially varying thickness diffusion is tuned for TOPAZ with the quick scheme. We use lower values in the Arctic, but needed to increase the values near the equator. There is also a different file for creating a file called sssrmx.[a,b]. This is needed when you don't want to use relaxation of salinity when you are too far away from climatology. Currently we use a constant calue of 0.5 meaning that it is strictly equivalent to defining the MATS\_RELAX flags in 2.2.12.

\subsection{Multiproc\_New - Calculate hycom average and mean SSH fields}
This directory compiles the routine \file{multiproc}, 
another routine that can be used to calculate average fields from hycom. The
output fields are dumped in the old ``pakk'' file format. Avoid using this
routine, and use the more generic routine \file{hycave} in stead, see
Section~\ref{sec:hycave}.

The routine calculates the mean ssh fields, which are used for data assimilation
purposes.

\subsection{NCARG-test - visualization routines}
If you can get NCAR graphics to install and compile, this directory contains
routines which can be used to visualize the hycom model fields. Somewhat
unfinished, but can be used to create quite nice plots.

Input files \file{cplot.in} and \file{cvplot.in} are needed for running the
routines \file{cplot} (contour plot) and \file{cvplot} (contour + vector plot)
in this directory. Note that there is no vertical interpolation done in the
routines.

Files  \file{cplot.in} and \file{cvplot.in} are briefly described in
Section~\ref{sec:input_cplot}.

\subsection{Nestbat - smoothing bathymetry towards an ``outer'' model}
This directory contains two versions of the nestbat routines. One for version
2.1 of NERSC-HYCOM, and another for version 2.2. The version 2.2 file
\file{nestbat-2.2} is used by the setup script \file{nestbat.sh} described in
Section~\ref{sec:setup_topo}.

Information is available for both of these routines when starting the programs.

\subsection{Nesting-2.2}
These are nesting routines needed to set up version 2.2 of NERSC-HYCOM. The
routines are \file{nestini} which prepares the nesting relaxation masks,
\file{nestports}, which sets up the ports file needed for barotropic nesting in
NERSC-HYCOM 2.2. The routine \file{nestpivots} is used to set up the outer model
for nesting, by setting up details of the interpolation from the outer model
grid to the inner grid.


\subsection{Nest\_Offline-2.1}
This directory contains nesting routines which were used in version 2.1 of
NERSC-HYCOM in order to produce file from an outer model. This is a work in progress , but interpolation from mercator or HYCOM with different stratification should be possible.
TODO:Should be  ported to version 2.2......

\subsection{NORSEXClim - climatology from NORSEX ice concentration}
Program can be used to calculate a NORSEX  ice concentration climatology, and
interpolate it to a projection grid, similar that of \file{hyc2proj}, see
Section~\ref{sec:hyc2proj}. Note that some of the projections defined in
\file{hyc2proj} are not available for this routine (usesold version of
mod\_toproj.F90 in \file{Hyc2proj/}). Also, the NORSEX files read are
ascii files produced at NIERSC (I think).

TODO: In short, this routine may require some updates. Routine
\file{mod\_toproj.F90} may be updated and moved to \file{Nersclib/} since
various tools use it.

\subsection{ObsCompare - compare model with observations}
This routine contains several routines for comparing observations and models.
The main routines are 
\begin{itemize}
\item Routine \file{argocmp}, which reads ARGO NetCDF files containing
temperature and salinity profiles. These are compared wih HYCOM files, and the
result of the comparison is dumped to text files. It is also possible to parse
the HYCOM data into the ARGO NetCDF file.
%
\item Routine \file{argo\_extract\_profiles\_new.sh}, which is a shell script.
Input is a HYCOM file (usually daily average. It looks for ARGO files matching
that date, downloads them if necessary and runs the \file{argocmp} program.
%
\item Routine \file{argoreduce} is a routine which can be used to calculate
regional statistics from the ARGO vs model comparisons. Operates on text output
from the \file{argocmp} routine.  Needs the input file \file{regiondefs.in},
described in Section~\ref{sec:input_regdef}.
%
\item Routine \file{slacmp} can be used to compare SLA from SSALTO/DUACS with
the SLA from the model. In theory this routine can be compiled with OpenDAP
support, but presently it needs local netcdf files for the comparison. Also
needs the file \file{regiondefs.in} if regional statistics are to be calculated,
The format of this file is described in Section~\ref{sec:input_regdef}.
%
\item Routine \file{slacmp\_ftp.sh} is a shell script which takes a hycom
(daily) file as input. From this file a date is calculated, and the
corresponding SLA file from SSALTO/DUACS is downloaded. The routine
\file{slacmp} described above is then run.
\end{itemize}
Most of these routines have extra information in them when called with no
arguments, in addition there is a README file in the source directory with some
information.

\subsection{Old\_Forcing - Routines for creating ``old'' forcing
files\label{sec:old_forcing}.}
This directory contains the source code for generating forcing based on various
data sets. The main routine  is called \file{old\_newf} (...) , and the routine is
used by some of the forcing scripts when initializing NERSC-HYCOM forcing, see
Section~\ref{sec:setup_force}.

The data set used by this routine is relatively small and located in the
\file{data/} subdirectory of the ``MSCProgs'' main directory. The ``Old'' in the
name should tell you that this data is from an old data set.  Avoid using it. 

\subsection{Old\_Levitus - Routines for creating ``old'' SST and SSS
fields\label{sec:old_levitus}}
This directory contains the source code for generating forcing based on various
data sets. The main routine  is called \file{old\_levini}, and the routine is
used by some of the forcing scripts when initializing NERSC-HYCOM forcing, see
Section~\ref{sec:setup_force}.

The data set used by this routine is relatively small and located in the
\file{data/} subdirectory of the ``MSCProgs'' main directory. The ``Old'' in the
name should tell you that this data is from an old data set, with (among other
things) large errors in the Arctic. Avoid using it. 

\subsection{Relax - model relaxation utilities }
Contains the routine \file{rmunew} which can be used to create a relaxation mask
in HYCOM. The routine is interactive, requiring input as it runs. This routine
is used by the \file{relax\_rmu.sh} script during the relaxation setup of HYCOM,
see Section~\ref{sec:setup_relax}. TODO: make this use depthlevel.in as input.


\subsection{RelaxToNetCDF - Get relaxation fields into NetCDF files}
The routine \file{PHCtomodel.sh} can be used to interpolate from z-level climatologies used when
initializing HYCOM, onto projection and fixed depth levels.  The depth are currently hardcoded in the script.
The aproach used is similar to that of the \file{hyc2proj} routine, see Section~\ref{sec:hyc2proj}.
It needs the input file \file{proj.in} (see section~\ref{sec:input_proj}). 


\subsection{River\_Forcing - prepare river forcing from point
sources\label{sec:river_forcing}}
The routine \file{rivers} is used to convert from point source river data files
to a two-dimensional field, spreading the discharge along the model coast. Input
files give point river data, specified in a file called \file{rivers.dat}.

The \file{rivers} routine can be called with no arguments to get some more
information.


\subsection{Section - Extract section data and transports\label{sec:section}}
The \file{Section/} subdirectory contain routines for extracting data from
sections to NetCDF files, and routines for calculating transport estimates from
hycom files. There are several programs in this directory, but their
functionality is most easily accessed using three different scripts; they are
\file{m2section}, \file{m2transport} and \file{m2transport2}.

All the scripts in this directory will first call a routine
\file{section\_intersect}, whose purpose is to set up the grid points which are
needed to calculate transports and to interpolate section details. The sections
are specified in the  file \file{sections.in}, see
Section~\ref{sec:input_sections}. Once a section is read, the grid points along
a section are calculated. 

The first step in this calculation is to locate the
points which are on one side of the section. The sections follow great circles
between the two points defining the start and end points of the section. Let
these two points be called $\vec{r}_1$ and $\vec{r}_2$ in cartesian coordinates,
and let the grid points in cartesian coordinages be given as $\vec{r}_{ij}$.
%
Also, remember that the line segment from $\vec{r}_1$ to $\vec{r}_2$
is a part of a great circle, so it ``splits'' the earth into two hemispheres.
%
\begin{figure}[tb]
  \centering
  \subfloat[Initial section with great circle between points $\vec{r}_1$
        $\vec{r}_2$\label{fig:seca}]%
     {\includegraphics[width=.50\textwidth]{Pics/section_init}}%
  \subfloat[Points on one side of great circle excluded from set\label{fig:secb}]%
     {\includegraphics[width=.50\textwidth]{Pics/section_maskhemi}}\\
  \subfloat[Remaining set after application of indicator function\label{fig:secc}]%
     {\includegraphics[width=.50\textwidth]{Pics/section_maskgeodesic}}%
  \subfloat[Final set after excluding points outside of line segment $r\vec{r}_1,\vec{r}_2$\label{fig:secd}]%
     {\includegraphics[width=.50\textwidth]{Pics/section_maskfinal}}%
  \caption{The stepwise process of extracting section points, used by
  \file{m2section}, \file{m2transport}, and \file{m2transport2}.}
  \label{fig:sec}
\end{figure}
All grid points $\vec{r}_{i,j}$ on one side of the hemisphere defined by the great circle
must satisfy this criterion:
\begin{equation}
   A = \left\{ \vec{r}_{i,j} \text{ such that } \left( \vec{r}_1 \times \vec{r}_2
   \right) \cdot  \vec{r}_{i,j} > 0\right\} \,.
\end{equation}
The resulting set $A$ of model grid points is illustrated in
Figure~\ref{fig:secb} by the grey squares.
%
Secondly, all points on the edges of the domain must be retrieved, a step which
is done seperately for the $u$ and $v$ positions of the C-grid. Let $1_A(\vec{r}_{i,j})$ be the
indicator function of set $A$, defined as
\begin{equation}
   1_A(\vec{r}_{i,j}) = 
      \begin{cases} 
         1 & \text{if $\vec{r}_{i,j} \in A$} \\
         0 & \text{if $\vec{r}_{i,j} \notin A$} 
      \end{cases}
      \, .
\end{equation}
All points on the edges of the domain defined by the set $A$ can then be retrieved 
by the following procedure
\begin{align}
   B_u &=\left\{ \vec{r}_{i,j} \in A \text{ such that } f(\vec{r}_{i,j}) = 1_A(\vec{r}_{i,j}) -
      1_A(\vec{r}_{i+1,j}) \ne 0 \right\}\,, \\
   B_v &=\left\{ \vec{r}_{i,j} \in A \text{ such that } g(\vec{r}_{i,j}) = 1_A(\vec{r}_{i,j}) -
   1_A(\vec{r}_{i,j+1}) \ne 0 \right\}\,. 
\end{align}
The resulting set $B_u$ is illustrated in Figure~\ref{fig:secc}. Note that in
addition to being used as a mask for points close to the boundary, the functions
$f(\vec{r}_{i,j})$ and $g(\vec{r}_{i,j})$ will also have information on directionality. This is
used to set up positive transport directions in the routines
\file{m2transport} and \file{m2transport2}.
%
Note that the set $B_u$ and $B_c$ will contain points which are on the great
circle, but outside of the segment $r1$, $r2$. We can remove these by these
conditions
\begin{align}
   C_u &= \left\{ \vec{r}_{i,j} \in B_u \text{ such that } 
      \left( \vec{r}_1 \times \vec{r}_{i,j} \right) \cdot
      \left( \vec{r}_{i,j} \times \vec{r}_2 \right) >0 \right\} \,,
   \\
   C_v &= \left\{ \vec{r}_{i,j} \in C_u \text{ such that } 
      \left( \vec{r}_1 \times \vec{r}_{i,j} \right) \cdot
      \left( \vec{r}_{i,j} \times \vec{r}_2 \right) >0 \right\}\,.
\end{align}
The final sets of grid points $C_u$ and $C_v$ can now be used for plotting purposes, and for
calculating transports in conjunction with the indicator functions $f_{i,j}$ and
$g_{i,j}$. An illustration of the set $C_u$ is given in Figure~\ref{fig:secd}.


The functionality of the FORTRAN routines can most easily  be accessed by
running the  various scripts inside the \file{Sections/} directory. These
scripts are also installed inside the \file{bin/} directory. The routines are
\begin{itemize}
\item \file{m2section} - this script can be used to extract data along a section
specified in the file \file{sections.in}, see Section~\ref{sec:input_sections}. 
To specify which fields to extract, use the ``extract'' files described in
section~\ref{sec:input_extract}. This routine is run with the files to process as
input arguments. Run \file{m2nc} with no arguments for additional information.
Sections are dumped to files \file{section001.nc}, \file{section002.nc} ...
There are matlab routines in the subfolder that can easily show a map of the section on a map (showsection.m) and plot easily the section with several option (sectionplot.m).
%
\item \file{m2transport} - this script will calculate barotropic transports
across a section. It will also try to calculate ice transports. Output is in
ascii files named \file{transport\_net001.dat}  \file{transport\_net002.dat}.
As it only need to read the 2D field barotropic velocity, it is really fast. 
There is also an option to dump to a netcdf file called \file{transports.nc} when you compile the code.§
You will need to specify the sections in the file
\file{sections.in}, see Section~\ref{sec:input_sections}. Run \file{m2transport}
with no arguments for short info on its usage.
%
\item \file{m2transport2} - this script will calculate transports
across a section, but with a more fine-grained approach than \file{m2transport}.
You will need to specify the sections in the file
\file{sections.in}, see Section~\ref{sec:input_sections}. You will also have to
define how to calculate transports in \file{transports.in}, See
Section~\ref{sec:input_transport}, where you can
calculate transport between two depth levels, transport of water masses between two
temperature levels , and more. It is also possible to use several critera at the same time.
Run \file{m2transport2} with no arguments for short info on its usage. Files are dumped to ascii files
with names defined in  \file{transport.in}, and also the file
\file{transports2.nc}.
%
\item \file{m2transport2} with scalar transport.  With
\file{m2transport2} you can also calculate scalar transports in addition to
volume transports. The routine \file{m2transport2} will look for a file 
\file{scalartransports.in} which can be used to calculate these transports, such
as heat transport.  The format of \file{scalartransports.in} is described in
Section~\ref{sec:input_transport}
\end{itemize}
The section code is re-written and  should be more robust than in earlier
versions. The calculation of points along the sections is also done in a more
straightforward way.

When calculating the transports and sections, the files \file{section001.dat},
\file{section002.dat} ... will contain information on the points along the
sections. The files \file{section001.dat}, \file{section002.dat} ... will contain
information on the transport points and positive directions defined for the
sections. 
%
The positive directions of a section can be found by the following rule. When
standing at the first point of a section, and looking towards the next point of
the section, then the positive direction is towards your right-hand side.

Remember that the sections follow great circle/geodesic lines on the sphere, 
not ``straight lines'' in longitude, latitude space (aka rhumb lines).

\subsection{SSHFromState - calculate SSH from restart files}
The small routine \file{ssh\_from\_restart} calculates the ssh fields from data
in the restart files. Mainly used for assimilation purposes. Run with no
arguments for short info on its usage.


\subsection{Synoptic\_Forcing-X.X.X- Creating forcing fields for HYCOM
\label{sec:synoptic-2.2}}
The routines in this directory are used to generate forcing fields for HYCOM. The function involves the horizontal interpolation of forcing fields from several
different data sets, the application of parameterizations to create new
atmospheric forcing variables from the raw data sets, and finally saving the
resulting atmospheric forcing fields to a file format which can be read by
HYCOM. The raw datasets which can be used to produce HYCOM forcing are various
ECMWF operational data sets, the ERA40 reanalysis, ERA interim reanalysis, the NCEP reanalysis and some
other data sets. There are 3 different folders for this routine. The version 2.1 is kept but is deprecated. The difference between version 2.2.12 and 2.2.37 is that in the latter, the code is developed so that there are better agreement with the forcing produced with inline forcing. This means that a single routine is used for making the interpolation. It is worth noticing that when the forcing are preprocess, it is not possible to use KARA2002 implementation because the latter set the coefficient drag dependent on the discrepancies between the  atmospheric surface temperature and the sea surface temperature (which is not yet available). However, a formulation called KARALIGHT has been set up so that you can still benefit from more accurate approach that computes the coefficient drag from the wind speed.


The directory consists of these routines
\begin{itemize}
\item \file{forfun\_nersc-2.2.12} or \file{forfun\_nersc-2.2.37} calculates the forcing fields needed to run
NERSC-HYCOM. It is typically called like this \\[.7em]
\indent \indent forfun\_nersc-2.2 synoptic\_option climatology\_option\\[.7em]
where the synoptic forcing option and climate forcing option can be any of the
options given in Table~\ref{tab:forcing}, with the exception of the ``prep''
option for synoptic forcing. If the routine is run with synoptic forcing fields
(i.e the synoptic option is anything apart from ``month''), then the file
\file{infile.in} will be parsed to find the start and end times of the
integration, and synoptic forcing for that range will be produced. If called
with synoptic option as ``month'' monthly climatologies will be calculated. In
that case \file{infile.in} is not needed.
%
\item \file{force\_perturb-2.2} can be used to add random forcing fields to an
already existing forcing data set. Not really necessary at the moment. Still as work in progress (not compile by the main makefile)


%
\item \file{ncep\_clim} is used to calculate a climatology from the NCEP data
set. This climatology can then be used by the \file{forfun\_nersc-2.2} routine.
There is also a routine \file{get\_ncep\_ftp.sh} for downloading these
data - which are continually updated. 
\end{itemize}
In addition there is also a README file with some additional info. Note that the
routine \file{forfun\_nersc-2.2} is used in the scripts which set up the
NERSC-HYCOM datasets (\file{nersc\_clim.sh} and \file{nersc\_synoptic.sh}) in
Section~\ref{sec:setup_force}.

\subsection{Tides\_CSR - CSR tidal forcing}
This directory contains the routine \file{csr2mod\_GE} which calculates tidal
boundary forcing used in NERSC-HYCOM. This routine has been modified from
previous versions, and uses the regional grid and depth files to 
set the grid size and calculate the forcing. Diagnostic output is also dumped in
a NetCDF file.  This routine is used to set up the
tidal forcing in \file{nersc\_csr.sh}, see Section~\ref{sec:setup_tide}.

\subsection{Tides\_FES - FES tidal forcing}
This directory contains the routine \file{csr2mod\_GE} which calculates tidal
boundary forcing used in NERSC-HYCOM. This routine has been modified from
previous versions, and uses the regional grid and depth files to 
set the grid size and calculate the forcing. Diagnostic output is also dumped in
a NetCDF file.  This routine is used to set up the
tidal forcing in \file{nersc\_fes.sh}, see Section~\ref{sec:setup_tide}.

\subsection{TRIP - river forcing\label{sec:river_trip}}
The routines in this directory can be used to set up river forcing by using
routines from the TRIP database [Oki and Sund], 1986, combined with runoff data from
ERA40 or ERA-i. The TRIP database is used to calculate the paths of surface water flow,
while the runoff data gives new water added to the surface. You need to define which TRIP data set to used in the makefile (TRIP05 is better). 
There are four routines in this directory.
\begin{itemize}
\item \file{trip\_path} - a diagnostic routine which calculates paths and prints
some information in text files. Identifies among other things the major runoff
catchment basins and their associated river outlets.
%
\item \file{trip\_weights} - routine calculates the mapping from the ERA40 runoff
grid to the TRIP dat. Needed to position the runoff data on the TRIP grid.
%
\item \file{trip\_flow} - routine calculates the flow of water from their
origin toward the river outlets. The flow directions are given on the TRIP grid.
Output is dumped to netcdf files. The routine \file{trip\_weights} must be run
before running this routine.
%
\item \file{trip\_tohycom} - the only really HYCOM-specific routine. Uses output
from \file{trip\_flow} to calculate river climatologies for HYCOM. With some
minor changes to this routine and to NERSC-HYCOM itself, it should be possible
to modify this routine to create synoptic fields of river discharge. Here, you may need to adjust the search radius or the land radius depending on the model resolution. There is a search radius that can be large (typically 300 km) and you need to define also the ellipse on which you are reducing the salinity from the river delta. (along shore radius and across shore radius).

\end{itemize}
%
\subsection{ZONAL}
This directory contains routines for creating zonal averages (\file{zonal})  and
meridional overturning stream function(\file{mosf}). The latter needs some work
to function properly.

\section{The ``Input/'' directory  - examples of  input files}
This directory contains some examples of input files needed to run the
diagnostic tools.
\subsection{``extract'' files\label{sec:input_extract}}
Several routines use the extract files to read which files are to be processed.
These files are different for different file types, and they are also processed
differently by various routines. A typical extract file for restart files 
\file{extract.restart} looks somewhat like this (line numbers added)
\begin{verbatim}
 1: 4                      # Version of tecconv program
 2: dp       dp            # Field used to determine layer interfaces
 3: 2 T T T                # 2-D, sphere, rotate, index velocities   
 4: 1 270 1 210            # section plot ia:ib ja:jb
 5: 1 1   XX XX   X        # extracted layers for 3-d fields (not used for 2-d)
 6: saln    01 01   T 
 7: temp    01 10   T 
 8: ficem   00 00   T 
 9: hicem   00 00   T 
10: ssh     00 00   T 
15: ubavg   00 00   T
16: vbavg   00 00   T
17: pbavg   00 00   T
21: dpmixl  00 00   T
\end{verbatim}
The first line in this file is a version number that can be changed when the
format changes. The second line used to denote the field which determines the layer
interfaces, but no routines in in the MSCProgs subdirectories use this anymore.

The third line is mainly used by the routines \file{m2nc} and \file{h2nc}. The
first number is not really used anymore, whereas the 2nd to fourth logical
values denote whether to dump velocities on original model grid, whether they
should also be dumped to east/west components, and finally if they should be
dumped th sphere velocities(3D vectors).

Lines 4 and 5 can also be ignored. From line 6 and onward are the specifications
of fields to extract. The format is first field name to extract, the range of
layers to extract for and finally a logical value which denotes if the fields
should be extracted at all. The different routines do different things with
these processing lines:
\begin{itemize}
\item The routines \file{m2nc} and  \file{h2nc} will use all the information
when exctracting data to netcdf files. 
\item The section routine \file{m2section} and the depth profile routine
\file{dprofile}  will just use the field name and the
processing flag.  All alyers are extracted.
\item The interpolation routine \file{hyc2proj} will just use the field name and
processing flag as well, because the model will be interpolated to fixed
z-levels.
\end{itemize}

The different HYCOM files contain different fields, and names of fields which
are the same (for instance salinity) can vary across different files. Due to
this, there are different extract files for different file types. They are named
\file{extract.restart}, \file{extract.archv}, \file{extract.daily}, and 
\file{extract.weekly}. Examples of these files can be found in the \file{Input/}
directory. The field names in these files correspond to field name entries in
the respective ``.b'' files of the .a/.b file pairs. If ou are missing a field
name which you want to extract you can look in the ``.b'' file for the field
name - if it is present you can add a new line with this field name  to the
extract files. 

\subsection{Projection file ``proj.in'' \label{sec:input_proj}}
The projection file  \file{proj.in} can be used to interpolate from the model
grid to a given projection. Available projections are ``polar\_stereographic'',
``regular'', ``mercator'' and ``native''. The regular projection is not really a projection,
it is a uniform, rectilinear longitude latitude grid. Similarly with the
``native'' option which is just the native model grid.
%
Note that the polar
stereographic projection in reality is a a stereographic projection (ahemm..),
and can be defined anywhere on the sphere. An illustration of the different
projections can be seen in Figure~\ref{fig:proj}
\begin{figure}[tb]
  \centering
  \subfloat[Mercator projection\label{fig:proja}]%
     {\includegraphics[width=.45\textwidth]{Pics/mercator2}}
  \subfloat[``Regular'' projection\label{fig:projb}]%
     {\includegraphics[width=.45\textwidth]{Pics/regular2}}\\
  \subfloat[Stereographic projection\label{fig:projc}]%
     {\includegraphics[width=.45\textwidth]{Pics/regular2}}
  \subfloat[``native'' projection\label{fig:projd}]%
     {\includegraphics[width=.45\textwidth]{Pics/native2}}%
  \caption{Different projections which can be specified by \file{proj.in}.}
  \label{fig:proj}
\end{figure}

There are example \file{proj.in} files for the different projections in th
\file{Input/} directory.  The input file \file{proj.in} for the 
various projections is  described below.

\paragraph{``regular'' projection option:} This option will create a projection
grid which is rectilinear in longitude-latitude space.  With this option, the input file
\file{proj.in} should look somewhat like this (line numbers added):
\begin{verbatim}
1: regular
2: -30.0               # Longitude of W edge
3:  82.0               # Longitude of E edge
4: 0.200               # Longitude grid spacing
5:  45.0               # Latitude of S edge
6:  88.0               # Latitude of N edge
7: 0.100               # Latitude grid spacing
\end{verbatim}
The first line denotes that the ``regular'' projection method is used. Lines 2-4 denote the first
longitude point to interpolate to, the last longitude point to interpolate to, and the
spacing between longitude points.  The latitude values are given in a similar manner on lines 5-7. 

The number of longitude and latitude points in the example
above becomes
\begin{align}
   N_\mathrm{\lambda} &= \lfloor (82 - (-30)) / 0.2 \rfloor +1  = 561 \\
   N_\mathrm{\phi} &= \lfloor (88 - 45)    / 0.1 \rfloor +1  = 431
\end{align}
where the braces denote the ``floor'' function. Likewise, the mapping from projection
grind indices to longitude, latitude positions become
\begin{align}
   \lambda[i] &=  -30.0 + 0.2 \times i &&\forall  i \in \left\{ 1, 2, \dots,
   N_\mathrm{\lambda} \right\} 
   \\
   \phi[j] &=   45.0 + 0.1 \times j &&\forall  j \in \left\{ 1, 2, \dots,
   N_\mathrm{\phi} \right\}
\end{align}
The ``regular'' projection option will
interpolate the model values to the two-dimensional grid defined by the 
indexes $i$ and $j$, and their geographical  positions  will be positions
$(\lambda[i],\phi[j]$).
The grid will have the size $N_\mathrm{\lambda}\times N_\mathrm{\phi}$.

\paragraph{``native'' projection option:} With this option there is no
horizontal interpolation, as the model values will be kept on the original
(native) model
grid. You can, however extract subsets of the model grid. For this projection
option the file \file{proj.in} looks like this 
\begin{verbatim}
1: native 
2:     1               # first grid index in 1st grid dimension
3:   200               # last  grid index in 1st grid dimension
4:     1               # 1st grid dimension  skip
5:     1               # first grid index in 2nd grid dimension
6:   100               # last  grid index in 2nd grid dimension
7:     1               # 1st grid dimension  skip
\end{verbatim}
This file is very similar in form to the ``regular'' option. 
The first line denotes that the ``native'' projection method is used. Lines 2-4
denote the first grid index to use, the last grid index to use and the spacing
between the grid indexes, all for the first model grid dimension.  The second
grid dimension values are given in a similar manner on lines 5-7. 

The number grid points in the first and second  grid dimension for the example
above becomes
\begin{align}
   N_\mathrm{x} &= \lfloor (200 - 1) / 1 \rfloor +1  = 200 \\
   N_\mathrm{y} &= \lfloor (100 - 1) / 1 \rfloor +1  = 100
\end{align}
where the braces denote the ``floor'' function.
The resulting ``subgrid'' will have the size $N_\mathrm{i}\times N_\mathrm{j}$.

Note that by setting the last grid index to $-1$, the size of the
model grids are used in stead (e.g $idm$ or $jdm$).




\paragraph{``polar\_stereographic'' projection option:} With this option the
stereographic projecion is enabled.  For this projection
option the file \file{proj.in} looks like this (line numbers added)
\begin{verbatim}
 1: polar_stereographic
 2: -3800.              # First x-point   [~km]
 3:  3800.              # Last  x-point   [~km]   
 4:  12.5               # X-point spacing [~km] 
 5: -5500.              # First y-point   [~km]
 6:  5500.              # Last  y-point   [~km]  
 7:  12.5               # Y-point spacing [~km]
 8: -45.0               # Central longitude 
 9:  90.0               # Central latitude 
10:  0.01               # Conversion factor    
11:  F                  # Rotate to output grid
\end{verbatim}
The first line denotes that the ``polar\_stereographic'' projection method is used. Lines 2-4
denote the first x-projection point to use, the last x-projection point to use and the spacing
between the x-points.  The y projection values are given in a similar manner on
lines 5-7. 


The number of grid points in the first and second  grid dimension for the example
above becomes
\begin{align}
   N_\mathrm{x} &= \lfloor (3800 -(-3800)) / 12.5 \rfloor +1  = 609 \\
   N_\mathrm{y} &= \lfloor (5500 -(-5500)) / 12.5 \rfloor +1  = 881
\end{align}
where the braces denote the ``floor'' function.
The mapping from projection grid indices to $x$, $y$ projection coordinates become
\begin{align}
   x[i] &=  -3800.0 + 12.5\times i &&\forall  i \in \left\{ 1, 2, \dots, N_\mathrm{x} \right\} 
   \\
   y[j] &=  -4500.0 + 12.5\times j &&\forall  j \in \left\{ 1, 2, \dots, N_\mathrm{y} \right\}
\end{align}
The resulting grid will have the size $N_\mathrm{x}\times N_\mathrm{y}$.

Lines 8-9 denote that the center point $(x,y)=(0,0)$ of the projection will be
placed at {$45^\circ$\,W}  and {$90^\circ$\,N}. The conversion factor on line 10
only affects the projection coordinate values in the resulting NetCDF file (the
factor was needed for some visualization tools). The final flag on line 11 says
if vectors should be rotated to the projection grid. If set to false, vectors
will be rotated to east/north directions, otherwise they will be rotated to the
projection grid.

To visualize the projection when creating \file{proj.in}, think of the first and
last ($x$,$y$) coordinate points as distances extending away from the central longitude
and latitude points. As an approximation, the projection coordinate units can be
considered roughly equal to kilometers. 
For the definition of stereographic projection, see for instance \\[.4em]
\indent\indent
\href{http://mathworld.wolfram.com/StereographicProjection.html}{http://mathworld.wolfram.com/StereographicProjection.html}.\\[.4em]
TODO: Clear up
\paragraph{``mercator'' projection option:} This option uses the following
\file{proj.in}:
\begin{verbatim}
mercator
1: -100.0              # Longitude W edge
2:   20.0              # Longitude E edge
3:    400              # number of points in E-W dir
4:  -20.0              # Latitude of S edge
5:   70.0              # Latitude of N edge
6:    200              # Number of points in S-N dir
7:     0.              #Central longitude
\end{verbatim}
The input specifies the first and last longitude values in line 1, the last
longitude value, and the number of points in the longitude direction
($N_\mathrm{x}$) is specified in line 3. Similarly the latitude values are
given in lines 4-6. Note that it is the size of the grid which is given on line
3 and 6, {\it not} the grid increment which is the case of the other
projections. The grid is constructed in ``Mercator''-space by using uniform
spacing in the projection coordinates.
%
The final line consists of the central longitude of the projection, which
defines the location of $x=0$ in the projection.

The first and last longitude ($\lambda[1]$ and $\lambda[N_\mathrm{x}]$)
values and the first and last latitude values ($\phi[1]$ and
$\phi[N_\mathrm{y}]$) are given in the input files, as well as the size of the
projection grid through $N_\mathrm{x}$ and $N_\mathrm{y}$.
Let $f(\lambda[i])$
and $g(\phi[j])$ be the Mercator transformations from longitude, latitude values to
projection coordinates. The grid is constructed  like this
\begin{align}
   x[i] &=  f(\lambda[1]) + \frac{f(\lambda[N_\mathrm{x}]) - f(\lambda[1])}{ N_\mathrm{x} - 1 }
   \times \left(i-1\right) \\
   y[i] &=  g(\phi[1]) + \frac{g(\phi[N_\mathrm{x}]) - g(\phi[1])}{ N_\mathrm{y} - 1 }
   \times \left(i-1\right)
\end{align}
and these grid positions can be retrieved through the inverse functions
$f^{-1}(x[i])$, $g^{-1}(y[j])$. These are the locations where the projection
routines will interpolate the model. For the definition of the Mercator transformation
itself, see for instance\\[.4em]
\indent\indent\href{http://mathworld.wolfram.com/MercatorProjection.html}{http://mathworld.wolfram.com/MercatorProjection.html}




\subsection{Stations file ``stations.in'' \label{sec:input_stations}}
The stations file is used with the routine  \file{hyc2stations} to set up
station positions to interpolate the model to, and join these into ``groups''
which are logically connected, such as ocean cross-sections. The file
\file{stations.in} will specify these points as well as names of the groups. The
file typically looks like this
\begin{verbatim}
#FRAM_STRAIT
-20.00   79.00
-19.37   79.04
-18.74   79.07
-18.10   79.11
-17.46   79.14
-16.82   79.17
-16.17   79.20
-15.52   79.23
-14.87   79.25
-14.21   79.28
-13.55   79.30
     ....
 14.61   79.02
 15.00   79.00
#DENMARK_STRAIT
-37.00   66.10
-36.69   66.11
-36.39   66.12
-36.08   66.13
-35.77   66.14
-35.46   66.15
-35.15   66.16
-34.84   66.17
     ....
-22.80   66.01
-22.68   66.00
\end{verbatim}
where most of the stations have been left out for brewity. The format is as
follows. Each group must start with a name, and this is indicated by the ``\#''
in the first column of \file{stations.in}. In the example there are two groups;
``FRAM\_STRAIT'' and ``DENMARK\_STRAIT''. After the name, follows the stations
for that particular group, these stations are read until the end of the file, or
until the next group name.

Using the group logic, it is relatively simple to link together station positions into
sections. The tool \file{setupstations.py} (see Section~\ref{sec:hyc2proj}) can
be used for this purpose by extracting station positions along rhumb lines.


\subsection{Depthlevels file ``depthlevels.in'' \label{sec:input_depthlevels}}
The \file{depthlevels.in} file is a simple file which sets up the vertical depth
levels the model should be interpolated to. Its format is the number of depth
levels on the first line, and on the following lines are the depthlevels
themselves. Like in this example:
\begin{verbatim}
12                  # Number of z levels
5.0 
30.0 
50.0  
100.0 
200.0
400.0 
700.0 
1000.0
1500.0 
2000.0 
2500.0 
3000.0
\end{verbatim}

\subsection{Section file ``sections.in'' \label{sec:input_sections}}
This file is used by the routines 
\file{m2section}, \file{m2transport}, and \file{m2transport2}, to set up the
grid points which are used to plot sections and calculate transports. The
contents of the file \file{sections.in} typically looks like this(line numbers
added)
\begin{verbatim}
 1:1.2 F               # File version and verbosity flag
 2: #####
 3: ##### Sections:  lon,lat pairs for start and end point.
 4: FRAM_STRAIT
 5: -20. 79.
 6:   0. 79.
 7: 15.  79.
 8: #
 9: DENMARK_STRAIT
10: -37.  66.1
11: -22.68 66.
\end{verbatim}
The first four lines are file version flags and a header. The remaining lines
denotes the  section definitions. The sections are given by first, a descriptive
name, then points defining the section, and finally a ``\#'' sign in the first
coloumn to denote the end of a section specification. 

As an example, the section named ``FRAM\_STRAIT'' will consist of a section
segment from $(-20.0,79.0)$ to $(0.0,79.0)$ , and then a new section segment
from $(0.0,79.0)$ to  $(15.0,79.0)$, all given in longitude/latitude pairs.
These section segments will be joined together when calculating the final
section for ``FRAM\_STRAIT''. 
%
It is possible to specify more segments, with a maximum hardcoded value of $50$
sections. 

A sample \file{sections.in} file can be found in the directory \file{Input/}.

\subsection{Transport file ``transport.in'' and scalar transport file
``scalartransport.in''\label{sec:input_transport}}
\paragraph{Transport file \file{transport.in}}
The transport specification file \file{transport.in} is used by the routine
\file{m2transport2} in Section~\ref{sec:section}. The file depends on the 
\file{sections.in} file as well.

In file \file{transport.in}, more detailed transport specifications can be set
up. The transports are given names, they are then linked to the sections defined
in \file{sections.in}. Finally the transport can be applied to specific water
masses, by defining thresholds for the water masses involved in the transports.
For instance, it is possible to calculate the transport, involving only  water
masses with a salinity larger than $35$\,psu. An example of \file{transport.in}
is given here
\begin{verbatim}
T1                   FRAM_STRAIT          SALINITY     +    -999.99     34.9 
T2                   FRAM_STRAIT          SALINITY     -    -999.99     34.9 
T3                   FRAM_STRAIT          SALINITY     +      34.9     999.99
T4                   FRAM_STRAIT          SALINITY     -      34.9     999.99
T5                   DENMARK_STRAIT       DENSITY      +    -999.99     27.8 
T6                   DENMARK_STRAIT       DENSITY      -    -999.99     27.8 
T7                   DENMARK_STRAIT       DENSITY      +      27.80    999.99
T8                   DENMARK_STRAIT       DENSITY      -      27.80    999.99
T9                   DENMARK_STRAIT       MULTIPLE
T9                   DENMARK_STRAIT       DENSITY      n      27.80    999.99
T9                   DENMARK_STRAIT       TEMPERATURE  n       5.00    999.99
T9                   DENMARK_STRAIT       END          
\end{verbatim}
The first column is the unique name of the transport. The second column is the
name of the section to use for this transport, this name must be defined in
\file{sections.in},described in Section~\ref{sec:input_sections}. 

The remaining columns sets the threshold criteria for water masses used in the
transport calculations. The third column describes the variable to use for
threshold criteria, it can be  ``SALINITY'', ``TEMPERATURE'', ``DENSITY'' or
``DEPTH''. The values in column five and six are the lower and upper values of
the variable, any water mass with a value between these two estimates are
included in the transport estimates.
%
As an example, for
the transport named ``T1'' above, only waters with salinity larger than -999.99
(i.e. all waters) and less than 34.9 is to be included in the transport
estimates.

The fourth column denotes direction, where ``+'' is positive
transport only, ``-'' is negative transport only, and ``n'' is net transport.
%
The positive directions of a section can be found by the following rule. When
standing at the first point of a section, and looking towards the next point of
the section, then the positive direction is towards your right-hand side.

For T9 multiple criteria are used. The list should start with a line for wich the 
criteria variable are MULTIPLE. The following lines consists of each criteria.
You must end the criteria list with END.


\paragraph{Scalar transport - ``scalartransport.in''}
This file can be used to make the routine \file{m2transport2} calculate
transport for additional tracer fields, such as for nutrients in biological
models. The format is
\begin{verbatim}
'temp     '  6. 3987000
'saln     '  0. 1.
\end{verbatim}
Here the first column denotes the variable to calculate the scalar transport
for. The second column is an offset value which is subtracted from the variable
when the transport is calculated. Finally, the third column is a scale factor,
which is multiplied with the final scalar transport estimate. The example on the
first line above will calculate temperature transport relative to 6 degrees
Celsius, with a scale factor of $3987000 \approx c_{p} \times \rho$, where $c_p$
is the heat capacity of sea water and $\rho$ is water density. Line 1 would
therefore give a heat transport estimate relative to 6 degrees celsius.

\subsection{The regiondefs file ``regiondefs.in'' \label{sec:input_regdef}}
This file is  used to calculate regional averages from the model. It allows you
to identify regions by their names and by the vertices outlining outlining the
region. An example is shown below(line numbers added)
\begin{verbatim}
 1: 2                                # Number of regions
 2: 4 TEST1                          # Number of points and name of 1st region
 3: -30 40                           # lon/lat pair - 1st point
 4:  30 40                           # lon/lat pair - 2nd point
 5:  30 60                           # lon/lat pair - 3rd point
 6: -30 60                           # lon/lat pair - 4th point
 7: 4 TEST2                          # Number of points ansd name of 2nd region
 8: -30 20                           # etc etc ...
 9:  30 20
10:  30 60
11: -30 60
\end{verbatim}
The first line gives the number of regions to read from the file. On the next
line is the number of vertices ($N$) for the region, followed by the unique name of
the region. Lines 3-6 then contain the $N$ positions of the vertices. Lines 7-11
contain another region definition and so on.

\begin{figure}[hbt]
  \subfloat[Convex region\label{fig:convexa}]
     {\includegraphics[width=.45\textwidth]{Pics/Convex_polygon_illustration1}}
  \subfloat[Non-convex region\label{fig:convexb}]
     {\includegraphics[width=.45\textwidth]{Pics/Convex_polygon_illustration2}}
  \caption{Examples of convex and non-convex regions.}
  \label{fig:convex}
\end{figure}

Two things are important when defining a region. First of all the region most be
convex. Roughly speaking this means that every straight line between two points
inside the region must be contained entirely inside the region, see 
Figure~\ref{fig:convex}. Secondly, the path around the region formed when
specifying must be traversed either clockwise or anticlockwise. These are
limitations which should be fairly easy to circumvent. For instance by splitting
a non-convex region into two  convex regions.


\subsection{The NCAR graphics input files -  ``cplot.in'' and ``cvplot.in'' \label{sec:input_cplot}}

\section{Matlab tools\label{sec:matlab}}

\subsection{abfile\label{sec:matlab_abfile}}
The matlab tool ``abfile'' is a object-oriented approach to reading  data from
hycom files into matlab. The tool consists of one file, \file{abfile.m}, and is
presently able to read several types of input files. The file type you want to
read must be given as an input argument to the abfile constructor method. The
abfile toolbox is documented in matlab. Type ``help abfile'' for some info. You
can also get information on abfile methods by typing ``help abfile.abfile'' or
``help abfile.getfield'' for instance. To see a list of abfile methods, type
``methods(abfile)'' in matlab. For a brief explanation and examples of usage,
read the following paragraphs.

\paragraph{Initializing file objects}
To use the abfile tool to read hycom data files, you must first create a abfile
object, this is done by calling the abfile constructor. A typical call looks
like this in matlab\\[.5em]
\indent\indent obj=abfile('F00restart2007\_330\_00.a','restart')\\[.5em]
This initializes the abfile object ``obj'', by reading header data for the file
\file{F00restart2007\_330\_00.a}, and by saying that this file is a restart file
in the second argument. 
Possible file types are ``restart'', ``archv'', ``nersc\_daily'',
``nersc\_weekly'', ``forcing'', ``regional\_grid'', ``relax'' and ``raw''. The
last file type is for a file which doesnt fit any of the other file types. In
this case data is read ``blindly'', without any knowledge of the names of the
fields in the file.

\paragraph{Reading field data}
Once the abfile object is created, you can start working
with it. Typical methods are reading fields for a given model layer, a given
time step, and for a given variable name. There are also methods for inquiring
the contents of the file. The following statement
will read the temperature variable for time step 1 and vertical level 1 into the
variable ``fld''\\[.5em]
\indent\indent fld=obj.getfield('temp',1,1 ); 
\footnote{Note that an equivalent way of doing this is with the statement
``fld=getfield(obj,'temp',1,1 );''. Use the approach you prefer.} \\[.5em]
Here the first argument ``temp'' is the variable to extract from the restart
file, the second variable is the vertical depth level to extract, and the third
argument is the time step to extract. It is also possible to pass empty data to
the routine to retrieve several depth levels or several time levels in one go.
The following will read all vertical depth levels for time step 1\\[.5em]
\indent\indent fld=obj.getfield('temp',[],1 ); \\[.5em]
Be careful with this approach, however, as it is an excellent way of abusing the
memory of the machine you work on.

\paragraph{Reading point data}
In addition to reading field data, it is also possible to read point data from a
file. This is done with the method ``getpoint'', an example of this routine is \\[.5em]
\indent\indent   pnt=obj.getpoint(100,100,'temp',[],1);\\[.5em]
which will read all vertical levels of the temperature variable, at time step 1,
and at grid position $(100,100)$ into the variable ``pnt''. You can also supply several 
points to this routine by specifying vectors for the points:\\[.5em]
\indent\indent   pnt=obj.getpoint([100 100],[100 101],'temp',[],1);\\[.5em]
This will read the data at grid positions $(100,100)$ and $(100,101)$.

\paragraph{Inquiring on the contents of a file}
There are also methods by which you can inquire the contents of a file. The
methods can inquire on the variables, layers and time steps present in a file.
To inquire for variable names use the ``getfieldnames'' method\\[.5em]
\indent\indent obj.getfieldnames()\\[.5em]
which returns the names of variables in the file, these names can then be passed to
the getfield and getpoint methods. To inquire on the vertical layer indexes use
the following methods \\[.5em]
\indent\indent obj.getlevels()\\[.5em]
\indent\indent obj.getlevels('temp')\\[.5em]
The first method will retrieve all possible layer indexes for the file as a whole, while
the second method will retrieve all possible layer indexes for the temperature
variable. Note that 2D variables usually return $0$ as layer index. Similarly
you can inquire for time levels in the file
the following methods \\[.5em]
\indent\indent obj.gettimes()\\[.5em]
\indent\indent obj.gettimes('temp')\\[.5em]
Some files have just one time index (ex ``nersc\_daily'') while others can have
several (ex ``restart'').

\subsection{Hycomvis\label{sec:matlab_hycomvis}}
The hycomvis tool can be used to visualize the contents of a hycom file. It uses
the ``abfile'', Section~\ref{sec:matlab_abfile} tool to read the contents of the
hycom files. The tool is started from the matlab command-line by specifying the
file(s) to process and the file types. The file types are the same as those
given to the abfile tool. The following command shows how to start hycomvis with
two ``nersc\_daily'' files, and one ``nersc\_daily'' file\\[.5em]
\indent\indent hycomvis(\{'IDDDAILY\_1991\_217\_1992\_073.a',
'IDDDAILY\_1991\_217\_1992\_074.a'\},'nersc\_daily');\\[.5em]
\indent\indent hycomvis('IDDDAILY\_1991\_217\_1992\_073.a','nersc\_daily');\\[.5em]
Note that the ``nersc\_daily'' files are in the first example passed to the hycomvis routine as a
cellstring array, denoted by the curly braces. In the second case only a single
file is passed to hycomvis as a character string.  It is also possible to pass a
character array to the routine - you can for instance pass the output of the
``ls'' function in matlab to the hycomvis routine : \\[.5em]
\indent\indent files=ls('IDDDAILY*.a');\\[.5em]
\indent\indent hycomvis(files,'nersc\_daily');\\[.5em]
Once hycomvis starts, you should be presented with the GUI shown inf
Figure~\ref{fig:hycomvisGUI}.

\begin{figure}[bt]
  \subfloat[hycomvis GUI\label{fig:hycomvisGUI}]
     {\includegraphics[width=.45\textwidth]{Pics/hycomvisGUI}}
  \subfloat[hycomvis section plot of temperature for the section selected
            in Figure~\ref{fig:hycomvisGUI}\label{fig:hycomvis_section}]
     {\includegraphics[width=.45\textwidth]{Pics/hycomvis_section}}
  \caption{The hycomvis GUI and example plots}
  \label{fig:hycomvis}
\end{figure}

The GUI consists of a selection map, buttons and menus. By clicking and dragging
in the selection map (the bathymetry plot), you can select regions,
cross-sections or stations, depending on the plotting mode you are in.
The hycomvis tool has two plotting modes, given by the buttons in the upper
left-hand side. It can be plotting either in ``Section'' mode or in
``Horizontal'' model. When ``Section'' mode is enabled, clicking will give a
selection as a point indicated by a magenta ``+'' sign. By click-and-drag you
will select a section, indicated by a magenta line. In this mode you can create Section plots or
station plots, indicated by the active buttons in the ``Plot Actions'' button
group. An example of a section plot is shown in
Figure~\ref{fig:hycomvis_section}.
%
When Horizontal mode is enabled, click-and-drag operations in the bathymetry map
will create rectangular areas. 
In this mode you can create horizontal field plots, indicated by the active
button in the ``Plot Actions'' button group.

In both modes you can select the active file in the Files menu, or go to the
next file in the file menu by clicking ``Next File'' button. You can also select
the variable to display in the ``Variable and level selection'' menu. In
``Horizontal'' plot mode you can also select the layer index to plot.
%
It is possible to have several plots of different types  open at the same. A
feature of the hycomvis tool  is  that the plots created are updated as the file
changes. When you select a new file in the Files menu, or click ``Next File'',
any plots you have created will be updated with the contents of the new file.
%
To close the plots created by hycomvis, click the ``Clear Plots'' button. This
will not close the main hycomvis window.

The hycomvis tool has no methods for changing the properties of the plots which
are created . Some
features of the plots are kept as the plots are updated, however:
\begin{itemize}
\item Section plots keep the color axis (caxis), X limits (the 'XLim' axes property),
and Y Limits (the 'YLim' axes property).
\item Horizontal plots keep the color axis(caxis).
\item Station plots keep the X limits(the 'XLim' axes property)  and Y Limits(the
'YLim' axes property).
\end{itemize}
This means that you can change these properties of the plots created by hycomvis, and
any plot updates should keep these changes. 



\subsection{Topofix\label{sec:matlab_topofix}}
Topofix is a small matlab GUI for modifying a depth matrix. It consists of many
of the bethymetry modification tasks that you would typically do with the conformal mapping tools
\ref{chp:confmap}. The GUI consists of a bathymetry map, and several buttons doing
various tasks. In the map  you can select points with mouse clicks, and regions
with click-and drag operations. You can start the topofix utility in two ways,
either by specifying the size  of the model grid; \\[.5em]
\indent\indent topofix('size',[216,144]); \\[.5em]
In this case topofix will read the grid from any \file{regional.depth.a} file
you have in the working directory. Another way to start it is by specifying the
depths matrix as an input \\[.5em]
\indent\indent topofix('depths',depth); \\[.5em]
where ``depth'' is a matlab variable.  This can be handy if you want to do some advanced operations
in matlab which you can't do in topofix, such as bathymetry smoothing, for
instance. 

\begin{figure}[bt]
\centering
     {\includegraphics[width=.65\textwidth]{Pics/topofix_main}}
  \caption{The topofix GUI}
  \label{fig:topofix}
\end{figure}
When topofix starts successfully, you should have a GUI similar to
Figure~\ref{fig:topofix}. In the bathymethry view,
click and drag operations will select regions in the map
view. Figure~\ref{fig:topofix} shows a selected region as a rectangular box.
The buttons on the left-hand side do various tasks:
\begin{description}
\item[Reset View] Click this button if you want to reset the view for any
reason.
\item[Toggle Grid] Switches the grid lines on and off.
\item[Change color axis] By modifying the min and max values directly below this
box, and clicking this box the min and max colormap values will change. 
\item[Check isolated] Checks for points with more than three land neighbours and
closes them.
\item[Workspace dump] Puts the current depth matrix in the matlab workspace.
This way you can modify them ``by hand'' in matlab.
\item[File dump]Saves the bathymetry to hycom depth files. The names are
prefixed with ``topofix.'', so you wont overwrite existing
\file{regional.depth.[ab]} files
\item[Reset depths]Resets the depths to what they were when you started topofix. 
\item[Undo last]Undoes the last bathymetry change operation.
\item[Modify selection]By typing a value in the text box below, you can modify the
depths of the current selection in the map. 
\end{description}
In addition to this you can probe for values by clicking on a point in the map.
The longitude, latitude and depth values will then show up as values in the
information on the lower left-hand side. It is also possible to zoom in on a
region in the map by using the zoom button on the toolbar of the figure, just
remember to disable the zoom button before you start modifying bathymetry values
again. If you are unable to zoom out again, you can press the ``Reset View''
button.

Note that there are no buttons for modifying the east/west, south/north
boundaries, this should be done by the conformal mapping routines,
section~\ref{chp:confmap}.
