GAMAP UTILITIES routines in *

All GAMAP Routines

List routines by category:
Atmospheric Sciences | Benchmarking | Color | Date/Time | Doc | File & I/O | BPCH Format | Scientific Data Formats | GAMAP Examples | GAMAP Internals | GAMAP Utilities | GAMAP Data Manipulation | GAMAP Models & Grids | GAMAP Plotting | General | Graphics | Math & Units | Plotting | Regridding | Strings | Structures | Time Series

List routines by alphabetical order:
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z

Last modified: Tue Apr 4 10:50:22 2017.


List of Routines


Routine Descriptions

COMPARE_FLIGHT

[Next Routine] [List of Routines]
 NAME:
        COMPARE_FLIGHT

 PURPOSE:
        Compare observations from aircraft campaigns to 
        high time-resolution CTM output (bpch files).
        This routine reads aircraft data in binary (bdt) format
        and produces an unlabeld plot and returns all the data
        you might ask for. If an aircraft mission extends beyond
        midnight GMT, the program will ask for a second model file
        which should be from the following day.

 CATEGORY:
        GAMAP Utilities, GAMAP Plotting

 CALLING SEQUENCE:
        COMPARE_FLIGHT, keywords

 INPUTS:
        None

 KEYWORD PARAMETERS:
      DATAFILE -> Name of the aircraft data file or file mask

      MODELFILE -> Name of the (first) model output file or file mask

      TRACER -> tracer number in model output (default=71)

      PSURF -> surface pressure for model grid (default=1013, because most
          aircraft data was sampled over oceans)

      FLIGHTDATA -> returns the observational data array as read
          with gte_readbin. Can also be used to pass flight data if you
          set the USE_DATA flag.

      FLIGHTVARS -> returns the variable names of the observational data.
          Must accompany FLIGHTDATA if you use USE_DATA.

      SPECIES -> the name of the observed species to plot (default CH3I).

      MODELDATA -> returns a time series of model data along the flight 
          track and a couple of min/max values:
             MODELDATA[*,0] = model value in corresponding grid box
                      [*,1] = min of neighbouring grid boxes at same level
                      [*,2] = max ...
                      [*,3] = min of neighbouring grid boxes at level below
                      [*,4] = max ...
                      [*,5] = min of neighbouring grid boxes at level above
                      [*,6] = max ...
          Note that the min/max arrays may contain values from the same
          grid boxes at the edges (i.e. there is no level below the first
          one, hence 3,4 will be identical to 1,2).

      TIME -> returns the time vector of the observations and modeldata

      /USE_DATA -> set this flag if you provide the aircraft data in the
          FLIGHTDATA array and the variable names in FLIGHTVARS. The data
          must contain variables named 'LON', 'LAT', 'ALTP' and SPECIES
          (for SPECIES see above). You must also provide a TIME vector
          which specifies UTC seconds.

 OUTPUTS:
      The extracted data is returned in MODELDATA, several other keywords
      return things read or computed in the process.

 SUBROUTINES:
      EXTRACT__FLIGHT : actual workhorse that does the extraction

 REQUIREMENTS:
      chkstru, ctm_get_data (GAMAP), gte_readbin (GTE)

 NOTES:
      Some hardwiring of default directories.

 EXAMPLE:
      simply  COMPARE_FLIGHT,tracer=1  if all you want is a plot
 
      CONVERT_FLIGHT,tracer=1,modeldata=md,time=time
      plot,time,md[*,0],color=1

 MODIFICATION HISTORY:
      mgs, 21 Apr 1999: VERSION 1.00
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/compare_flight.pro)


CTM_BOXSIZE (FUNCTION)

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_BOXSIZE  (function)

 PURPOSE:
        Computes the size of CTM grid boxes.

 CATEGORY
        GAMAP Utilities, GAMAP Models & Grids

 CALLING SEQUENCE:
        result = CTM_BOXSIZE( GRIDINFO [,RADIUS [,KEYWORDS] ] ) 

 INPUTS:
        GRIDINFO -> the structure returned by function CTM_GRID,
             which contains the following necessary fields:
	      IMX   (int   ) -> Maximum I (longitude) dimension 
             JMX   (int   ) -> Maximum J (latitude ) dimension
             YMID  (fltarr) -> Array of latitude  centers

        RADIUS -> The radius of the earth in km.  This may be 
             passed as an input parameter, or can be specified via 
             the GEOS_RADIUS, GISS_RADIUS, or FSU_RADIUS keywords.
             As default, the GEOS value of 6375.0 km is used.

 OUTPUT:
        CTM_BOXSIZE returns a 2-D (or 1D) array of CTM surface areas,
        or a 3-D array for CTM grid box volumes.  The default unit 
        is square kilometers or cubic kilometers.

 KEYWORD PARAMETERS:
        /CM2 -> Return ctm surface areas in square centimeters.
             [default: km^2].  

        /M2 -> Return ctm_surface areas in square meters.
             [default: km^2].  

        /CM3 -> Return grid box volumes in cubic centimeters.  
             [default: km^3].
 
        /M3 -> Return grid box volumes in cubic meters.  
             [default: km^3].

        /VOLUME -> Will cause CTM_BOXSIZE to return grid box volumes 
             instead of grid box surface areas.
       
        GEOS_RADIUS -> selects GEOS value for earth radius (6375.0 km) 
             [default]

        GISS_RADIUS -> selects GISS value for earth radius (6371.4 km)

        FSU_RADIUS -> selects FSU value for earth radius (6371.4 km)
      
        IJ, IL, JL -> determine which area shall be computed [default: IJ]
             NOTE: IL computes area of southern boundary

        XLEN, YLEN, ZLEN -> Returns length of linear segments 
             (lat, lon, alt) to calling program.  If /CM2 or /CM3 is 
             specified, then XLEN, YLEN, ZLEN will be in centimeters.
             If /M2 or /M3 are specified, then XLEN, YLEN, ZLEN will
             be in meters. (Default unit is km).

        NO_2D -> return 1D vector instead of 2D array

        LATIND -> for IL and JL: return result for given latitude index
             [default is equator]. This implies NO_2D. The index must
             be provided as FORTRAN index (e.g. 1..72).
 
 SUBROUTINES:
        External Subroutines Required:
        ===============================
        CHKSTRU (function)   USAGE

 REQUIREMENTS:
        None

 NOTES:
        None

 EXAMPLES:
        ; (1) Compute surface grid box areas for GISS II model in
        ;     standard resolution (4x5):

        Areakm2 = CTM_BOXSIZE( CTM_GRID( CTM_TYPE( 'GISS_II' ), /GISS )

        ; (2) Compute ctm surface areas in cm2 for GEOS 4x5 grid, return
        ;     a vector with 1 value per latitude :

        ModelInfo = CTM_TYPE( 'GEOS1', res=4 )
        GridInfo  = CTM_GRID( ModelInfo )
        AreaCm2   = CTM_BOXSIZE( GridInfo, /GEOS, /cm, /NO_2D )

        ; (3) Compute ctm grid box volumes in cm3 for GEOS 4x5 grid,
        ;     and return a 3-D array

        ModelInfo = CTM_TYPE( 'GEOS1', res=4 )
        GridInfo  = CTM_GRID( ModelInfo )
        VolumeCm3 = CTM_BOXSIZE( GridInfo, /GEOS, /Volume, /cm3 )
        

 MODIFICATION HISTORY:
        bmy, 27 Mar 1998: VERSION 1.00 (algorithm from mgs)
        mgs, 27 Mar 1998: - added NO_2D keyword
        mgs, 07 May 1998: VERSION 1.10
                          - added IJ, IL, JL, LATIND, XLEN, 
                            YLEN, and ZLEN keywords
                          - corrected polar box sizes 
                            (now uses gridinfo information)
        mgs, 08 May 1998: - corrected latindex, now uses FORTRAN convention
        mgs, 24 May 1998: - changed IL so it computes area of 
                            southern boundary
        mgs, 17 Nov 1998: - changed keywords GISS and GEOS to .._RADIUS
        bmy, 27 Jul 1999: VERSION 1.42
                          - updated comments
        bmy, 27 Jan 2000: VERSION 1.45
                          - added /CM and /M keywords,
                            deprecated /CM2 and /M2 keywords.
                          - now return a 3-D array for grid box volumes
                          - updated comments
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - now call USAGE to display doc header
                            if wrong # of arguments are passed.
                          - Deleted internal routine USE_CTM_BOXSIZE

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_boxsize.pro)


CTM_CLEANUP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_CLEANUP

 PURPOSE: 
        Free memory blocked by excessive use of the GAMAP package.
        With the /DATA_ONLY option, only the data blocks themselves
        are freed, all header information remains accessible. 
        This speeds up any further analysis.  Also calls HEAP_GC
        to do garbage collection on unused heap variables.

 CATEGORY:
        GAMAP Utilities

 CALLING SEQUENCE:
        CTM_CLEANUP [, /DATA_ONLY, /NO_GC, /NO_FILE_CLOSE ]

 INPUTS:
        none

 KEYWORD PARAMETERS:
        /DATA_ONLY -> Only free heap variables that point to the
             actual data records. Leave all 'info' intact. Default 
             is to remove everything includign the global DATAINFO 
             and FILEINFO structure arrays.  NOTE: Setting this switch
             will not perform garbage collection via routine HEAP_GC.
           
        /NO_GC -> Set this switch to suppress garbage collection of
             heap variables with HEAP_GC.

        /NO_FILE_CLOSE -> Set this switch to suppress closing of
             all open files.

 OUTPUTS:
        None

 SUBROUTINES:
        None

 REQUIREMENTS:
        None

 NOTES:
        None

 EXAMPLE:
        CTM_CLEANUP

 MODIFICATION HISTORY:
        mgs, 05 Oct 1998: VERSION 1.00
        mgs, 08 Oct 1998: - fixed DATA_ONLY part so that status is
                            reset to zero and derived data records 
                            are removed
        bmy, 21 Nov 2000: - Updated comments 
        bmy, 04 Oct 2004: GAMAP VERSION 2.03
                          - added /NO_GC keyword
                          - now call HEAP_GC to do garbage collection
                            of heap variables & pointers
        bmy, 23 Mar 2007: GAMAP VERSION 2.06
                          - Now add /NO_FILE_CLOSE keyword so as not
                            to close open files
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - close only files opened with GAMAP
        bmy, 16 May 2011: GAMAP VERSION 2.16
                          - Now make all loop indices long integers

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_cleanup.pro)


CTM_COLUMN_DU

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_COLUMN_DU

 PURPOSE:
        Calculates columns in Dobson Units for a given tracer.

 CATEGORY:
        GAMAP Utilities

 CALLING SEQUENCE:
        RESULT = CTM_COLUMN_DU( DiagN, [ Keywords ] )

 INPUTS:
        DIAGN -> Diagnostic category name (or number) containing the
             tracer data for which columns will be computed.  The
             default is 'IJ-AVG-$' (i.e. v/v mixing ratios).
             
 KEYWORD PARAMETERS:
        FILENAME -> (OPTIONAL) File containing CTM data for which 
             to compute columns.  If omitted, then the user will
             be prompted to select a file via a dialog box.

        TAU0 -> Starting TAU value of the desired data block (will
             be passed to CTM_GET_DATABLOCK).  If omitted, then 
             CTM_COLUMN_DU will read data for the first time in
             the data file.

        TRACER -> Number of tracer for which to compute columns.

        PFILENAME -> Name of the file containing surface pressure
             data (this is necessary in order to compute column
             sums).  If PFILENAME is omitted, then CTM_COLUMN_DU
             will look for surface pressure data in FILENAME.

        PTAU0 -> TAU0 value by which surface pressure data in
             PFILENAME is indexed.  If PTAU0 is omitted, then
             CTM_COLUMN_DU will use TAU0.  

        PTRACER -> Tracer number for the surface pressure data.
             Default is 1.  (For some GISS-CTM punch files, surface
             pressure is saved as tracer #0). 

        TROPFILENAME -> Name of the file containing the annual mean
             tropopause data for the GEOS-Chem model.  If TROPFILENAME
             is supplied, then columns will be computed from the
             surface up to the annual mean tropopause height.
             Otherwise, columns will be computed for the full
             vertical extent of the data.

        /DOUBLE -> If set, will return column sums as double
             precision.  Otherwise, will return column sums as
             single precision.

        MODELINFO -> Returns to the calling program the MODELINFO
             structure (i.e. output from CTM_TYPE) corresponding to 
             the data.

        GRIDINFO -> Returns to the calling program the GRIDINFO 
             structure (i.e. output from CTM_GRID) corresponding
             to the data.

        XMID -> Returns to the calling program the longitude centers
             in degrees for the extracted data block.
 
        YMID -> Returns to the calling program the latitude centers
             in degrees for the extracted data block.

        ZMID -> Returns to the calling program the altitude centers
             in # of levels for the extracted data block.
       
        /DU -> If set, will return column sums in Dobsun units.
	      Otherwise, will return column sums in molec/cm2. (jaf, 8/19/08)

        _EXTRA=e -> Picks up any extra keywords.


 OUTPUTS:
        RESULT -> a 2-D array containing the columns for TRACER
             in Dobson Units (DU).  1 DU = 2.69e16 molec/cm2.

 SUBROUTINES:
        Internal Subroutines:
        =============================================================
        CCD_GetAirMass (function)   CCD_Consistency_Check (function)
    

        External Subroutines Required:
        =============================================================
        CHKSTRU          (function)   CTM_BOXSIZE       (function)
        CTM_EXTRACT      (function)   CTM_GET_DATABLOCK (function)
        EXTRACT_FILENAME (function) 

 REQUIREMENTS:
        References routines in both GAMAP and TOOLS packages.

 NOTES:
        (1) An internal consistency check is now done to make sure
            the tracer data block is of the same model and resolution
            as the surface pressure and annual mean tropopause data blocks.

 EXAMPLE:
        Result = CTM_COLUMN_DU( 'IJ-AVG-$',          $
                                FileName='ctm.bpch'  $
                                Tracer=20,           $
                                Tau0=80304.0,        $
				 /DU )

             ; Returns O3 columns in DU from the file "ctm.bpch", 
             ; for March 1994 (TAU0 = 80304 for GEOS date 3/1/1994).

 MODIFICATION HISTORY:
        bmy, 26 Jul 1999: VERSION 1.00
        bmy, 20 Apr 2000: GAMAP VERSION 1.45
                          - renamed from "rvm_o3col"
                          - removed hardwiring, added comments
                          - added internal subroutine "CCD_Consistency_Check
                          - now can sum up to the annual mean tropopause
                            for GEOS model data blocks
        bmy, 30 Jul 2001: GAMAP VERSION 1.48
                          - bug fix: make sure to extract the same
                            lat/lon region for PS, tropopause heights
                            as we do for tracers
                          - added XMID, YMID, ZMID keywords to return
                            XMID, YMID, ZMID arrays from CTM_GET_DATABLOCK
                            to the calling program
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - Rewritten for hybrid grids, and to compute 
                            DU for a data block of less than global size
  jaf & phs, 18 Aug 2008: GAMAP VERSION 2.13
                          - added capability to read surface pressure in 
			     GEOS, which stores surface pressure as a 3-D
                            array called PEDGE-$
			   - added DU keyword so that default unit is
			     molec/cm2, and renamed "DU" output to "Column"

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_column_du.pro)


CTM_CONVERT_UNIT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_CONVERT_UNIT 

 PURPOSE:
        Wrapper program for CONVERT_UNIT.PRO

 CATEGORY:
        GAMAP Utilities

 CALLING SEQUENCE:
        CTM_CONVERT_UNIT, Data [,Keywords] 

 INPUTS:
        DATA -> The data array (or value) on which to perform
             the unit conversion.  DATA will be converted.

 KEYWORD PARAMETERS:
        CNUM -> For hydrocarbons, CNUM is the following
             ratio: ( moles C / moles hydrocarbon ).
             CNUM is needed to convert from ppbC to ppbv.

     Keyword Parameters Passed to CONVERT_UNIT:
     ==========================================
        FROM_UNIT -> An individual unit to search and replace. 
             If not given, any unit will be converted to TO_UNIT, 
             as long as the current unit belongs to 
             the same category. 

        TO_UNIT -> An individual unit to convert to. If not given, 
             all units that are converted (see FROM_UNIT) will be 
             replaced by the standard SI unit of their category.

        For the individual unit and categories see FIND_UNIT 

        _EXTRA=e  -> Picks up any extra keywords for CTM_CONVERT_UNIT.

 OUTPUTS:
        RESULT -> Returns 1 if conversion was successful, 0 otherwise.

 SUBROUTINES:
        External Subroutines Required:
        ===============================
        CONVERT_UNIT
        CONVERT_MOLCM2_KG (function)
        CONVERT_KG_MOLCM2 (function)

 REQUIREMENTS:
        None

 NOTES:
        Will first convert ppbC to ppbv

 EXAMPLE:
        CTM_CONVERT_UNIT, Data, From='ppbC', To='ppbv', $
                          CNum=5, Result=Result

             ; converts Isoprene (5 mole C / 1 mole ISOP ) from
             ; parts per billion of Carbon (ppbC) to parts per
             ; parts per billion by volume of ISOP (ppbv).
             ; RESULT = 1 if unit conversion was successful.

 MODIFICATION HISTORY:
        bmy, 29 Sep 1998: VERSION 1.00
        bmy, 07 Oct 1998: VERSION 1.01
                          - Added unit conversion for mol/cm2 -> kg etc.. 
        mgs, 11 Nov 1998: - bug fix if seconds not passed
        bmy, 21 Jun 2002: GAMAP VERSION 1.51
                          - now recognize string "molec/cm2/s"
                          - updated comments, cosmetic changes
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_convert_unit.pro)


CTM_DATAINFO (FUNCTION)

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_DATAINFO  (function)

 PURPOSE:
        Return information about available categories, tracers or 
        time steps in either a given or the global datainfo structure 
        array.

 CATEGORY:
        GAMAP Utilities, Structures

 CALLING SEQUENCE:
        RESULT = CTM_DATAINFO( [DIAGN] [,DATAINFO] [,keywords] )

 INPUTS:
        DIAGN -> A diagnostic number or category name for which
             information shall be returned on available tracers 
             or time steps. If not given, CTM_DATAINFO returns
             information about all available diagnostics instead.
 
        DATAINFO -> An optional subset of the global DataInfo 
             structure array. If given, the search will be 
             restricted to the data records contained in DATAINFO.

 KEYWORD PARAMETERS:
        /TRACER -> If set, CTM_DATAINFO returns all tracer numbers
             that are available with the given diagnostics. This
             keyword has no effect if no DIAGN is given.

        /TAU0 -> Returns information about all available time steps
             for a given diagnostics. This keyword has no effect if
             either DIAGN is not given or /TRACER is set.
    
        /TAU1 -> Same as TAU0, but for the end of the time step.

        If none of these keywords is set, CTM_DATAINFO returns the
        index values for the DATAINFO structure array that match
        the requested diagnostics.

        STATUS -> restrict search to: 0=unread data, 1=read data.
             Default is 2=no restriction

        /EXPAND -> For multilevel diagnostics, CTM_DATAINFO normally
             returns only the template (with the '$' character). Use
             this keyword to get all individual levels as well.

 OUTPUTS:
        Depending on the keywords and the DIAGN parameter, an array
        with diagmostics numbers, index values, tracer numbers, or 
        time steps is returned. 

 SUBROUTINES:
        External Subroutines Required:
        ====================================
        CTM_SELECT_DATA, CTM_DIAGINFO

 REQUIREMENTS:
        None

 NOTES:
        None

 EXAMPLE:
        ; Must read in some data first
        CTM_GET_DATA, 'IJ-AVG-$', TRACER=1, FILE=''

        ; print all tracers that are available for diag IJ-AVG-$
        PRINT, CTM_DATAINFO( 'IJ-AVG-$', /TRACER )

        ; print all time step endings for diagnostics IJ-AVG-$
        PRINT, CTM_DATAINFO( 'IJ-AVG-$', /TAU0 )

        ; print all diagnostics that are available in the file
        ; (or in all files previously read)
        PRINT, CTM_DATAINFO()

        ; print all record indices for diagnostics IJ-AVG_$
        PRINT, CTM_DATAINFO( 'IJ-AVG-$' )

 MODIFICATION HISTORY:
        mgs, 07 Oct 1998: VERSION 1.00
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_datainfo.pro)


CTM_DIAGINFO

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_DIAGINFO

 PURPOSE:
        Return information about one or all of the diagnostic 
        used by GEOS-CHEM, GISS, or other CTM's.  

 CATEGORY:
        GAMAP Utilities, Structures

 CALLING SEQUENCE:
        CTM_DIAGINFO, DIAGN, DIAGSTRU [ , Keywords ]

 INPUTS:
        DIAGN -> Diagnostic category name for which to extract the 
             information.  To retrieve information about all CTM
             diagnostic categories use the /ALL_DIAGS keyword.

 KEYWORD PARAMETERS:
        /ALL_DIAGS -> Retrieves information about all diagnostics.

        CATEGORY -> Returns to the calling program the punch
             file category name of the requested diagnostic(s)

        FILENAME -> Name of the diaginfo file (default diaginfo.dat)
             The file will be searched in the current directory first, 
             then in the directory where CTM_DIAGINFO.PRO is located.
             If not found in either location, a standard data block is
             retrieved from this file.

        /FORCE_READING -> Read from the diaginfo file (specified in
             FILENAME) and overwrite the contents of the common block.

        MAXTRACER -> Returns to the calling program the maximum
             number of tracers stored in the requested diagnostic(s).
             NOTE: This is now only necessary for backwards 
             compatibility with the GISS-II ASCII punch files.

        OFFSET -> Returns to the calling program the offset constant 
             that is used to locate tracers in the "tracerinfo.dat"
             file.  OFFSET is needed to locate the proper index from
             the "tracerinfo.dat" file.

        SPACING -> Returns to the calling program the interval
             between diagnostic offsets.

 OUTPUTS:
        DIAGSTRU -> returns a structure or structure array with the 
             following tags:
             Category  : Category name for this diagnostic
             Offset    : Offset factor used in "tracerinfo.dat" file
             Spacing   : Spacing between diagnostic offsets 
             MaxTracer : Max # of tracers stored in this diagnostic

 SUBROUTINES:
        Internal Subroutines:
        =============================================
        CD_Is_MaxTracer (function)

        External Subroutines Required:
        =============================================
        FILE_EXIST   (function)   OPEN_FILE
        ROUTINE_NAME (funciton)   STRBREAK (function)

 REQUIREMENTS:
        Requires routines from the TOOLS package.

 NOTES:
        (1) At first call, the tracer information structure array is
        read from a file.  Thereafter, the information is stored in a 
        common block where it is accessible in subsequent calls.

 EXAMPLES:
        (1)
        CTM_DIAGINFO, 'BIOGSRCE', R
        PRINT, R.CATEGORY, ':', R.MAXTRACER, ':',R.OFFSET
        IDL prints "BIOGSRCE:           0:        4700"
 
             ; Returns a structure containing tags CATEGORY,
             ; MAXTRACER, OFFSET for the "BIOGSRCE" diagnostic.
             ; as listed in the file "diaginfo.dat".

        (2)
        CTM_DIAGINFO, /ALL, CATEGORY=CATEGORY
        PRINT, CATEGORY
        IDL prints "IJ-AVG-$ IJ-24H-$ IJ-INS-$ INST-MAP ..."

             ; Return information about all category names
             ; listed in the file "diaginfo.dat".

 MODIFICATION HISTORY:
        bmy, 19 May 1998: VERSION 1.00
                          - developed from CTM_TRACERINFO.PRO v. 2.0 by
                            Martin Schultz (08 May 1998)
                            see comments to CTM_TRACERINFO.PRO for 
                            modification history of that subroutine
        bmy, 20 May 1998: - removed SCALE and UNIT structure tags & keywords
                          - added OFFSET structure tag & keyword
        bmy, 27 May 1998: - changed "tracers" to "diagnostics" in 
                            print statement.
        mgs, 13 Aug 1998: - now returns only first diagnostics for a
                            given number.  This permits to keep old
                            and new diagnostics in one file and use
                            the old diagnostics by name.
                          - introduced extra search one level above 
                            current dir.
        mgs, 17 Aug 1998: - changed defaults vor void return
                          - diaginfo.dat: MAXTRACER meaning changed!
        bmy, 17 Nov 2003: GAMAP VERSION 2.01
                          - Removed INDEX and TYPE, they're obsolete
                          - Now use new file format for "diaginfo.dat"
                            which allows for 8-digit offset numbers
                          - Added internal function CD_IS_MAXTRACER
                          - No longer read defaults from internal datablock
                          - Added SPACING keyword
                          - Updated comments 
        bmy, 09 Mar 2006: GAMAP VERSION 2.05
                          - Use "./diaginfo.dat" as default in
                            order to facilitate reading in IDL 5.5-
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - Now use the FILE_WHICH routine to
                            locate the "diaginfo.dat" file
        phs, 17 Jul 2008: GAMAP VERSION 2.12
                          - Bug fix: only use FILE_WHICH if the 
                            FILENAME keyword isn't passed.

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_diaginfo.pro)


CTM_DIFF

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_DIFF

 PURPOSE:
        Computes absolute or relative differences between two CTM
        data blocks, and creates a new entry in the global DATAINFO
        structure.

 CATEGORY:
        GAMAP Utilities

 CALLING SEQUENCE:
        CTM_DIFF, DIAGN, [, Keywords ]

 INPUTS:
        DIAGN -> A diagnostic number or category name (see
             (CTM_DIAGINFO). A value of 0 (or an empty string)
             prompts processing of all available diagnostics.
             DIAGN can also be an array of diagnostic numbers or
             category names.

 KEYWORD PARAMETERS:
        FILE -> File name or list of file names containing the data 
             blocks to be differenced.  

        ILUN -> Logical unit number, or list of logical unit numbers
             of the files that contain the data blocks to be differenced.   

        TAU0 -> A time value or list of values to restrict the search.
             Default handling as with ILUN or TRACER. TAU0 superseeds
             /FIRST, /LAST or TAURANGE.

        TRACER -> Tracer ID number, or list of tracer ID numbers.  
             CTM_DIFF will difference the data blocks for diagnostic 
             DIAGN and tracer TRACER.

        /PERCENT -> If set, will compute the percent difference
             between two data blocks as 100 * ( DATA2 - DATA1 ) / DATA1.  
             Default is to compute the absolute difference DATA2 - DATA1.  

        NEWTRACER -> Returns to the calling program the tracer values
             for the data blocks, as read in from disk.

        NEWTAU -> Returns to the calling program the TAU0 values for
             the data blocks, as read in from disk.

        RANGE -> Returns the min & max difference values to the
             calling program.

        /MASK -> If set, the absolute % difference is return, with
             data below either thresholds (see pc_thr and diff_thr)
             set to a negative value, -99 .They are "masked", and can
             be set to a specific color in a plot (see ctm_plotdiff
             usage of the same keyword) or set to NaN for future
             analysis.
             
	 PC_THR, DIFF_THR : the %-Diff and Diff THResholds to mask data if
             /MASK is set.  Default values are 1% and 1e4.

 OUTPUTS:
        CTM_DIFF will append an entry to the global DATAINFO array of
        structures pertaining to the difference between the data
        blocks.

 OUTPUT KEYWORD:
 
        OUTLUN -> set this keyword to a variable name that will hold
             the LUN associated with the newly computed difference
             data.

        SUCCESS -> 0 by default, becomes 1 if MASK is set and all
             data are below the thresholds that define the MASK.


 SUBROUTINES:
        External Subroutines Requrired:
        =========================================================
        CTM_GET_DATA             CTM_MAKE_DATAINFO (function)
        CTM_GRID     (function)  GAMAP_CMN         (include file)
        INV_INDEX    (function)  YESNO             (function)
        CTM_DIAGINFO 

 REQUIREMENTS:
        References routines from GAMAP and TOOLS packages.

        Also, currently will only look at data blocks with the same
        tracer, since differencing two different tracers is not
        always that productive. 

 NOTES:
        (1) If DATA1 corresponds to the "old" data, and DATA2
            corresponds to the "new" data, then CTM_DIFF will 
            compute the following:
         
            Abs. Diff = ( new - old )
            % Diff    = ( new - old ) / old

        (2) The DATAINFO entries created by CTM_DIFF can be read into
            GAMAP with the /NOFILE option.  The ILUN values of these 
            data blocks will be negative, indicating derived data.

        (3) The call to CTM_REGRID probably does not work yet.
             Will get around to fixing that later...

 EXAMPLE:
        (1) Call CTM_DIFF to compute an absolute difference between
            two data blocks from two different punch files, at the
            same TAU0 value, for OH (DIAGN='CHEM-L=$', TRACER=1).
            
            FILE = [ 'ctm.bpch.v4-30', 'ctm.bpch.v4-31' ] 
            CTM_DIFF, 'CHEM-L=$', FILE=FILE, TRACER=1


        (2) Call CTM_DIFF to compute a relative difference between
            two data blocks from the same punch file, at two
            different TAU0 values, for tracer 1 (Radon).

            ILUN = 20
            TAU0 = [ 74472L, 74640L ]

            CTM_DIFF, 'IJ-AVG-$', ILUN=ILUN, TAU0=TAU0, $
                  TRACER=1, /Percent
 
 MODIFICATION HISTORY:
        bmy, 23 Apr 1999: VERSION 1.00
        mgs, 18 May 1999: - some bug fixes in error checks.
                          - regridding still not tested !!
        mgs, 10 Jun 1999: - bug fix for percent diference (indexing)
        bmy, 15 Sep 1999: GAMAP VERSION 1.43
                          - now use the GRIDINFO structure from the
                            global FILEINFO structure, if it exists.
                          - bug fix in call to CTM_GET_DATABLOCK
                          - updated comments
        bmy, 14 Jan 2000: GAMAP VERSION 1.44
                          - now allow comparision of two different
                            tracer numbers (e.g. for comparing two
                            simulations w/ different tracer indices)
                          - added error checking for size of the
                            FILE, ILUN, TAU0, TRACER keywords
                          - deleted obsolete code
        bmy, 26 Jan 2000: GAMAP VERSION 1.45
                          - now allow TAU0, FILE, ILUN, TRACER to have 
                            0 elements w/o generating an error message
        bmy, 15 Nov 2001: GAMAP VERSION 1.49
                          - Now make sure that NEWTRACER is not a 
                            multiple of 100, so that the tracer #
                            will be saved correctly to the global 
                            DATAINFO structure 
        bmy, 22 Apr 2002: GAMAP VERSION 1.50
                          - updated comments
        bmy, 19 Nov 2003: GAMAP VERSION 2.01
                          - Now get spacing between diagnostic
                            offsets from CTM_DIAGINFO
        bmy, 29 Jan 2004: - Added LEV keyword so that you can
                            select just a single level
                          - If we are just comparing a single level,
                            then do not test altitude dimensions
                            of the two data blocks.
        bmy, 16 Feb 2005: GAMAP VERSION 2.03
                          - now pass _EXTRA=e to CTM_GET_DATA 
        phs, 24 Oct 2006: GAMAP VERSION 2.05
                          - replace CTM_REGRID with CTM_REGRIDH
                          - pass _EXTRA=e to CTM_REGRIDH
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - added RANGE keyword for sending min/max
                            difference values to the calling program
        phs, 25 Sep 2009: GAMAP VERSION 2.13
                          - OUTLUN kwrd returns LUN associated with
                            computed difference
                          - /MASK is available to deals with absolute
                            %-age data and masked data below PC_THR
                            and/or DIFF_THR

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_diff.pro)


CTM_EXAMPLES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_EXAMPLES

 PURPOSE:
        Quick and dirty demonstration of various CTM_* routines

 CATEGORY:
        GAMAP Examples, GAMAP Utilities

 CALLING SEQUENCE:
        CTM_EXAMPLES

 INPUTS:
        None

 KEYWORD PARAMETERS:
        /PNG -> Set this switch to create PNG files from screen
             shots of examples generated by this program.

 OUTPUTS:
        None

 SUBROUTINES:
        External Subroutines Required:
        ===============================================
        OPEN_DEVICE           MULTIPANEL
        CTM_GET_DATA          GETMODELANDGRIDINFO
        TVMAP                 PAUSE
        CTM_PLOT              SCREEN2PNG
        NYMD2TAU (function)   CTM_OVERLAY

 REQUIREMENTS:
        None

 NOTES:
        Updated with the most recent GAMAP routines.

 EXAMPLE:
        CTM_EXAMPLES, /PNG

             ; Show example plots and create screenshot output
             ; as PNG files.

 MODIFICATION HISTORY:
        mgs, 20 Aug 1998: INITIAL VERSION
        mgs, 22 Oct 1998: - adapted for new use of CTM_GET_DATA
                            some more comments
        mgs, 26 Oct 1998: - attached a few more comments about extended 
                            use of ctm_get_data at end
        mgs, 18 Nov 1998: - added call to CTM_MAKE_DATAINFO
        bmy, 06 Oct 2006: GAMAP VERSION 2.05
                          - Updated examples w/ newest GAMAP routines
                          - Added examples w/ CTM_OVERLAY and
                            FIND_CELLS_BY_COUNTRY
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - now uses FILE_WHICH to find ctm.bpch.examples

(See /n/home09/ryantosca/IDL/gamap2/examples/ctm_examples.pro)


CTM_EXTRACT (FUNCTION)

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_EXTRACT (function)

 PURPOSE:
        Extracts a block of data from a 3-D CTM data cube.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        CTM_EXTRACT, DATA, MODELINFO, GRIDINFO [,Keywords]

 INPUTS:
        DATA -> The data cube from which to extract a region.
             DATA must be 3-dimensional (e.g. lon-lat-alt, or 
             lon-lat-tracer, etc).

 KEYWORD PARAMETERS:
        MODELINFO -> The MODELINFO structure returned from function 
             CTM_TYPE.  

        GRIDINFO -> The GRIDINFO structure returned from function
             CTM_GRID.

        AVERAGE -> Bit flag indicating the dimensions over which to
             average the data:
                1 :  longitudinal
                2 :  latitudinal
                4 :  vertical
             These values can be combined. E.g., to average over 
             longitude and latitude use 3. A bit set in AVERAGE 
             superseeds the corresponding bit in TOTAL (see below).
 
        TOTAL -> Bit flag indicating the dimensions over which
             to sum the data:
                1 :  longitudinal
                2 :  latitudinal
                4 :  vertical
             These values can be combined. E.g., to integrate over
             longitude and latitude use 3. A bit set in AVERAGE
             superseeds the corresponding bit in TOTAL (see above).

        /INDEX -> If set, will interpret LAT, LEV, and LON as index 
             arrays.  If not set, will interpret LAT, LEV, and LON as 
             ranges (i.e. two-element vectors containing min and max values).

        LAT -> An index array of latitudes *OR* a two-element vector 
             specifying the min and max latitudes to be included in
             the extracted data block.  Default is [ -90, 90 ].

        LEV -> An index array of sigma levels *OR* a two-element vector 
             specifying the min and max sigma levels to be included
             in the extracted data block.  Default is [ 1, GRIDINFO.LMX ].

        LON -> An index array of longitudes *OR* a two-element vector 
             specifying the min and max longitudes to be included in
             the extracted data block.  Default is [ -180, 180 ].

        ALTRANGE -> A vector specifying the min and max altitude 
             values (or a scalar specifying a single altitude) to
             be included in the extracted data block.

        PRANGE -> A vector specifying the min and max pressure levels 
             (or a scalar specifying a single pressure level) to be
             included in the extracted data block.

        WE -> Returns to the calling program the index array of longitudes 
             for the extracted data region, ordered from west to east.

        SN -> Returns to the calling program the index array of latitudes
             for the extracted data region, ordered from South to North.
 
        UP -> Returns to the calling program the index array of vertical  
             levels for the extracted data region, ordered from surface
             to top.

        DIM -> A named variable will return the new dimension information 
             of the data block after averaging or totaling.

        _EXTRA=e   -> Picks up extra keywords for CTM_INDEX.

 OUTPUTS:
        X, Y, Z -> Arrays of latitude, longitude, or altitude values 
             corresponding to the the 1st, 2nd, and 3rd dimensions of 
             the DATA array, respectively.

 SUBROUTINES:
        CTM_INDEX 
        DEFAULT_RANGE (function)

 REQUIREMENTS:
        Uses GAMAP package subroutines.

 NOTES:
        (1) CTM_EXTRACT returns the extracted data region as 
        the function value.

        (2) Assumes a 3-D data cube as input, of dimensions (lon, lat,
        alt), or for some diagnostics (lon, lat, "tracer" number).

        (3) In the calling program, CTM_TYPE and CTM_GRID must be 
        called to compute the MODELINFO and GRIDINFO structures,
        which can then be passed to CTM_EXTRACT.

        (4) If any of the LAT, LON, LEV, ALTRANGE, PRANGE keywords are
        explicity specified, then CTM_EXTRACT will return to the
        calling program their original, unmodified values.  If any
        of these are not explicitly specified , then CTM_EXTRACT 
        will return to the calling program default values.  

 EXAMPLE:
        (1)
        MODELINFO  = CTM_TYPE( 'GEOS4', RES=4 )
        GRIDINFO   = CTM_GRID( MODELINFO )
        DATAREGION = CTM_EXTRACT( DATACUBE,                   $
                                  MODELINFO=MODELINFO,        $
                                  GRIDINFO=GRIDINFO           $
                                  LON=[-180,0], LAT=[-30,30], $ 
                                  LEV=[1,10] )

               ; Extracts from a GEOS-4 4x5 data cube a region 
               ; delimited by longitude = [-180, 0], 
               ; latitude = [-30, 30], for levels 1 to 10.

        (2)
        LON = INDGEN( 36 )
        LAT = INDGEN( 16 ) + 15
        LEV = INDGEN( 10 ) 
        MODELINFO  = CTM_TYPE( 'GEOS4' )
        GRIDINFO   = CTM_GRID( MODELINFO )
        DATAREGION = CTM_EXTRACT( DATACUBE,            $
                                  MODELINFO=MODELINFO, $
                                  GRIDINFO=GRIDINFO,   $
                                  /INDEX,  LON=LON,    $
                                  LAT=LAT, LEV=LEV )

               ; Extracts same data region as in Example (1) but 
               ; here passes explicit index arrays instead of ranges.

 MODIFICATION HISTORY:
        bmy, 16 Sep 1998: VERSION 1.00
        bmy, 17 Sep 1998: - now extracts data from data cube one 
                            dimension at a time to avoid errors
        bmy, 18 Sep 1998: VERSION 1.01
                          - INDEX, SN, WE, UP keywords added
                          - LATRANGE, LONRANGE, LEVRANGE renamed
                            to LAT, LON, LEV (since they may now 
                            contain arrays and not just ranges).
        mgs, 21 Sep 1998: - some more error checking
                          - removed MinData and MaxData 
        bmy and mgs, 22 Sep 1998: VERSION 1.02
                          - added AVERAGE and TOTAL keywords
        bmy, 24 Sep 1998: VERSION 1.03
                          - Now returns original values of LAT, LON, 
                            LEV, ALTRANGE, and PRANGE if those keywords
                            are specified.  Otherwise returns
                            defaults.
        MGS, 29 SEP 1998: - Introduced new DEFAULT_RANGE function.
        bmy, 06 Oct 1998: - fixed bug: now S = size( NEWDATA )
        bmy, 08 Oct 1998: VERSION 1.04
                          - MODELINFO and GRIDINFO are now keywords
                          - added X, Y, and Z as parameters
        bmy, 11 Feb 1999: - updated comments
        bmy, 19 Feb 1999: VERSION 1.05
                          - added FIRST keyword so that the values of
                            THISDATAINFO.FIRST can be passed from the
                            calling routine.
                          - now call ADJ_INDEX to adjust the WE,
                            SN, and UP index arrays for data blocks
                            that are less than global size.
                          - added DEBUG keyword
        mgs, 16 Mar 1999: - cosmetic changes
        mgs, 02 Apr 1999: - bug fixes that prevented use with 2D fields
                            (e.g. EPTOMS data)
        mgs, 21 May 1999: - now catches error in multitracer diagnostics
                            when user requests a level beyond LMX.
        qli, 26 May 1999: - "max(newlev) ge" corrected to "gt"
        bmy, 15 Sep 1999: VERSION 1.43
                          - removed bugs that caused data blocks to
                            always have MODELINFO.NTROP vertical
                            layers
        bmy, 04 Dec 2000: GAMAP VERSION 1.47
                          - add code for future bug fix
        bmy, 24 Apr 2001: - bug fix: now can handle longitudes
                            greater than 180 degrees
        bmy, 06 Jun 2001: - bug fix: Test if LON exists before
                            assigning it to NEWLON.
        bmy, 30 Jul 2001: GAMAP VERSION 1.48
                          - bug fix: now extract proper latitude range
                            for data blocks smaller than global size
        bmy, 26 Jun 2002: GAMAP VERSION 1.51
                          - Default value of FIRST is now [1,1,1], 
                            since this has to be in Fortran notation.
                          - also do error checking on FIRST near
                            the beginning of the program.
        bmy, 15 Nov 2002: GAMAP VERSION 1.52
                          - now can handle total/average for MOPITT grid
        bmy, 23 Aug 2004: GAMAP VERSION 2.03
                          - now can handle single-point data blocks
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
        bmy, 19 Nov 2007: GAMAP VERSION 2.11
                          - Updated comments
        bmy, 10 Dec 2007: GAMAP VERSION 2.12
                          - Now pad ALTRANGE and PRANGE to 2 elements
                            if they are passed w/ one element
        bmy, 13 Aug 2009: GAMAP VERSION 2.13
                          - Bug fix: now compute DEF_X_RANGE from the
                            grid edges for computing NEWLON.  Now
                            also works for nested grids.
  phs & bmy, 13 Oct 2009: - Bug fix: now account for ranges that
                            straddle the date line when computing
                            DEF_X_RANGE
        ccc, 21 Oct 2009: - Bug fix when PRange is passed.
        bmy, 20 Mar 2017: GAMAP VERSION 2.19
                          - Now make sure that WE, SN, UP are converted
                            from Fortran to IDL notation properly
                            when /INDEX is specified.

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_extract.pro)


CTM_GET_DATA

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_GET_DATA

 PURPOSE:
        Retrieve specific data records from CTM output files.
        Opening files, parsing header information, and loading
        of data are handled transparently and can be 
        controlled by various keywords. The routine returns a
        subset of the global DATAINFO structure that matches the
        requested category and (optional) tracer and time step(s).

        This routine should be called *whenever* you want to 
        access data and you are not sure that it has been 
        loaded previously. It provides the general user-interface
        for GAMAP (the Global Atmospheric Model output Analysis 
        Package). 

        For the future, a widget interface to this routine is 
        planned.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        CTM_GET_DATA, DATAINFO [,DIAGN] [,keywords]

 INPUTS:
        DIAGN -> A diagnostic number or category name (see
             (CTM_DIAGINFO). A value of 0 (or an empty string)
             prompts processing of all available diagnostics.
             DIAGN can also be an array of diagnostic numbers or
             category names.

 KEYWORD PARAMETERS:
        FILENAME -> (optional) If FILENAME is a fully qualified file path
             the specified file is opened without user interaction.
             If filename is empty or contains wildchards (*,?), a
             pickfile dialog will be displayed.
             If FILENAME is a named variable it will contain the full
             file path upon return so that a subsequent call to
             CTM_GET_DATA with the same FILENAME argument will not prompt
             another file selection dialog.
                If the FILENAME keyword is present, CTM_GET_DATA
             will restrict it's scope to records from the selected
             is file (even if FILENAME contains an empty string, it will 
             restrict the scope of the search!).
                If the file is found in the global FILEINFO structure or
             the USE_FILEINFO structure (i.e. it has been opened 
             previously), then it will not be parsed again; instead the
             data records are returned from memory.
                The data itself is loaded transparently via 
             CTM_RETRIEVE_DATA.

        ILUN -> An optional value or array of logical unit numbers. If
             given, the search is restricted to data from the specified
             files. Default is to use all files (unless the FILENAME
             keyword is present). If an undefined variable
             is passed into ILUN, information about all accessible files
             in the global FILEINFO structure (or USE_FILEINFO) is returned.

        TRACER -> A tracer ID number or a list of those. If given, the
             search is restricted to those tracers. Default is to use all 
             tracers. If an undefined variable is passed into TRACER, 
             and one specific diagnostics is requested with DIAGN,
             information about all accessible tracers in the global
             DATAINFO structure or USE_DATAINFO structure or the
             DATAINFO structure associated with a specific file is returned.

        TAU0 -> A time value or list of values to restrict the search.
             Default handling as with ILUN or TRACER. TAU0 superseeds
             /FIRST, /LAST or TAURANGE.

        TAURANGE -> A 2-element vector containing the first and last tau0
             value to look for. 

        /FIRST, /LAST -> extract first or last time step that is stored for
             the selected diagnostics, ilun, and tracer. Only one can be 
             be active at a time. /LAST superseeds /FIRST.

        INDEX -> A named variable that will contain the indices of the 
             records in USE_DATAINFO that match the selection criteria.
             You can test INDEX[0] ge 0 in order to see if CTM_GET_DATA has
             been successful although it is now recommended to test for
             n_elements(DATAINFO) eq 0. 
                The INDEX keyword is useful if you want to change the
             information contained in the selected DATAINFO structures
             globally.

        USE_FILEINFO -> (optional) If provided, CTM_GET_DATA will 
             restrict its search to only the files that are
             contained in USE_FILEINFO which must be a FILEINFO 
             structure array. Default is to use the global information 
             (see gamap_cmn.pro).
             If an undefined named variable is provided in USE_FILEINFO,
             it will either contain the global FILEINFO structure array 
             or the FILEINFO record of the specified file.
             USE_FILEINFO must contain entries for all logical unit numbers
             that are used in USE_DATAINFO.

        USE_DATAINFO -> (optional) Restrict search to records contained
             in USE_DATAINFO which must be a DATAINFO structure array. 
             If an undefined named variable is provided in USE_DATAINFO,
             it will either contain the global DATAINFO structure array 
             or all DATAINFO records of the specified file.
             See also USE_FILEINFO.

        /INTERNAL_USE -> Set this keyword if you want to prevent a call
             to CTM_OPEN_FILE, but instead abort in case of undefined 
             (global) FILEINFO or DATAINFO structures.

 OUTPUTS:
        DATAINFO -> An array of DATAINFO records that match the selected 
             criteria. You can then simply loop over 
             0..n_elements(DATAINFO)-1 to access all data records and 
             extract the data as *(DATAINFO[i].data).
             DATAINFO will be undefined if no records are found!!
             Always test for  IF (n_elements(DATAINFO) eq 0) ... !
             NOTE: Alternatively you can return the INDEX to the selected
             data records in the global (or USE_) datainfo structure array
             with the INDEX keyword. This may in some cases eliminate the
             need to make a local copy of the selected DATAINFO records. 

 SUBROUTINES:
       pro reopen_all_files,fileinfo
       (needed in order to get free unit numbers)

       pro make_compound_datainfo,DataInfo,category,ilun,tracer,tau0,tau1
       (make compound structure for multilevel or multitracer diagnostics)

       pro update_tracer_datainfo,datainfo,traceroffset
       (enter tracer information into global datainfo structure)

 REQUIREMENTS:
       Several ctm_* routines are used
       Also uses UNDEFINE (by D. Fanning)

 NOTES:
       Please test rigorously. In case of read errors, try using CTM_OPEN_FILE
       with the /PRINT keyword.

       If your model output (ASCII punch file) does not contain the
       dimensional information about each data block, it may cause problems
       for diagnostics that do not contain 72x46 elements.
       It's defintively a good idea to implement this little change *NOW* !

       Outline of this procedure:
       - get all data records that match selection criteria
       - create "compound" datainfo structures for multilevel and
         multitracer diagnostics (those hold 3D data blocks)
       - read data for all selected compound structures unless only
         status information requested

 EXAMPLE:
       See CTM_EXAMPLES
       

 MODIFICATION HISTORY:
        mgs, 20 Aug 1998: VERSION 1.00
        mgs, 21 Sep 1998: - changed gamap.cmn to gamap_cmn.pro
        mgs, 22 Sep 1998: - changed to accomodate usage of 
                            tracer information
        mgs, 22 Oct 1998: - old FILEINFO and DATAINFO parameters now
                            keywords USE_..., new DATAINFO parameter
                            returns selected subset of records.
                          - print statements replaced with message
                          - DEBUG messages improved
                          - catch cancelled file open dialog
        mgs, 26 Oct 1998: - datainfo now undefined at start
                          - allows for multiple categories
                          - ilun, tracer, tau0 keyword variables renamed
                            as sel_... in order to preserve them
        mgs, 04 Nov 1998: - sel_tracer now expanded to include offsets
        mgs, 10 Nov 1998: VERSION 3.0 
                          - major update! Program structure much more
                            straightforward!
        mgs, 12 Nov 1998: - bug fixes for simple diagnostics (line 732)
                            and finding offset tracers (in update_...)
                            replaced tracer by (tracer mod 100) in 3 places
        mgs, 19 Nov 1998: - bug fix with scale factor. Didn't get globally
                            updated because it was linked to unit. Need a
                            more generic global update procedure !
        mgs, 03 Dec 1998: - yet another bug fix in reopen files: needed
                            to test for negative ilun before fstat
        bmy, 21 Jan 1999: - added outer parentheses to the FORMAT
                            descriptor (255(I4,1x)) to avoid errors
        mgs, 17 Feb 1999: - bug fix for simple diagnostics: needed
                            to add dummy value to compound array.
        mgs, 16 Mar 1999: - catch error in tracerinfo.dat (more than one
                            tracer with same number)
                          - error in update_tracer... should have been
                            fixed. Some more debug output added for 
                            testing.
        mgs, 23 mar 1999: - set vertical dimension to -1 for new compound
                            datainfo records
        mgs, 24 May 1999: - updated filetype info
        mgs, 02 Jun 1999: - added retall statement after error
                            message
        bmy, 23 Nov 1999: - added /SMALLCHEM keyword for CTM_TRACERINFO
        bmy, 27 Sep 2001: GAMAP VERSION 1.49
                          - Set F77=1 for filetype 4 (DAO met fields)
                          - Now reference function LITTLE_ENDIAN
                          - Swap endian in OPEN_FILE if reading data
                            on a little-endian machine (e.g. PC) 
        bmy, 19 Nov 2003: GAMAP VERSION 2.01
                          - now test valid diagnostics using 
                            DIAGSTRU[*].CATEGORY and not DIAGSTRU[*].INDEX
                          - removed /SMALLCHEM keyword, it's obsolete
                          - Now recognizes binary files as having
                            FILETYPE values between 100 and 200
                          - Removed /SMALLCHEM flag, it's obsolete
                          - Now uses diagnostic spacing from CTM_DIAGINFO
                            and pass this to UPDATE_TRACER_DIAGINFO
        bmy, 11 Feb 2004: GAMAP VERSION 2.01a
                          - Internal routine MAKE_COMPOUND_DATAINFO
                            now passes SPACING from CTM_DIAGINFO
                            to routine CTM_DOSELECT_DATA
        bmy, 27 Oct 2004: GAMAP VERSION 2.03
                          - added QUIET keyword to suppress printing
                            information about retrieved tracers
        bmy, 06 Feb 2006: GAMAP VERSION 2.04
                          - Bug fix: use DIALOG_PICKFILE to get file name
                            before calling CTM_OPEN_FILE.  This is necessary
                            because the tests for certain file types requires
                            the file name to be known ahead of time.
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - now passes _EXTRA keyword to
                            CTM_OPEN_FILE. This allows to read nested 
                            met (GMAO) files by using /NA or /CHINA
  bmy & phs, 20 Nov 2007: GAMAP VERSION 2.11
                          - If FILENAME is not defined, then the value
                            of the filename selected via dialog box
                            will be passed back to the calling program.

 KNOWN BUGS OR WEAKNESSES:
        - handling of USE_DATAINFO and USE_FILEINFO is not carried 
          through all lower level subroutines, i.e. they may be replaced
          by *pGlobal... in some occasions. Since USE_... should always
          be a subset of *pGlobal..., no serious errors are expected
          from this weakness. 

        - known bug in update_tracer_datainfo, see comment in routine.

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_get_data.pro)


CTM_GET_DATABLOCK

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_GET_DATABLOCK

 PURPOSE:
        Extracts a data block from a CTM punch file.
        (Wrapper program for CTM_GET_DATA and CTM_EXTRACT.)

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        SUCCESS = CTM_GET_DATABLOCK(DATA [,DIAGN] [,Keywords])

 INPUTS:
        DIAGN -> A diagnostic number or category name (see
             (CTM_DIAGINFO). This must uniquely identify a
             specific data type.  DIAGN is passed to CTM_GET_DATA


 KEYWORD PARAMETERS:
     Keywords that are passed to CTM_GET_DATA:
     =========================================
        FILENAME   -> Name of the file to open.  FILENAME is passed
                      to CTM_GET_DATA.  CTM_GET_DATA will return
                      the full path name, which is then returned
                      to the calling program.

        USE_FILEINFO -> (optional) If provided, CTM_GET_DATA will 
             restrict its search to only the files that are
             contained in USE_FILEINFO which must be a FILEINFO 
             structure array. Default is to use the global information 
             (see gamap_cmn.pro).
             If an undefined named variable is provided in USE_FILEINFO,
             it will either contain the global FILEINFO structure array 
             or the FILEINFO record of the specified file.
             USE_FILEINFO and USE_DATAINFO must be consistent, and should
             either both be used or omitted. However, it is
             possible to provide the global FILEINFO structure 
             (or nothing) with a local subset of DATAINFO.

        USE_DATAINFO -> (optional) Restrict search to records contained
             in USE_DATAINFO which must be a DATAINFO structure array. 
             If an undefined named variable is provided in USE_DATAINFO,
             it will either contain the global DATAINFO structure array 
             or all DATAINFO records of the specified file.
             See also USE_FILEINFO.

     Keywords that are passed to CTM_EXTRACT:
     ========================================
        AVERAGE -> Bit flag to average over certain dimensions
             (see CTM_EXTRACT)

        TOTAL -> Bit flag to sum over certain dimensions 
             (see CTM_EXTRACT)

        /INDEX -> If set, will interpret LAT, LEV, and LON as index 
             arrays.  If not set, will interpret LAT, LEV, and LON as 
             ranges (i.e. two-element vectors containing min and max values).

        LAT -> An index array of latitudes *OR* a two-element vector 
             specifying the min and max latitudes to be included in
             the extracted data block.  Default is [ -90, 90 ].

        LEV -> An index array of sigma levels *OR* a two-element vector 
             specifying the min and max sigma levels to be included in
             the extracted data block.  Default is [ 1, GRIDINFO.LMX ].

        LON -> An index array of longitudes *OR* a two-element vector 
             specifying the min and max longitudes to be included in
             the extracted data block.  Default is [ -180, 180 ].

        ALTRANGE -> A vector specifying the min and max altitude
             values to be included in the extracted data block.

        PRANGE -> A vector specifying the min and max pressure levels 
             to be included in the extracted data block.

     Other keywords:
     ===============
        XMID, YMID, ZMID -> Arrays of values (e.g. latitude,
             longitude, or altitude) for the 1st, 2nd, and 3rd
             dimensions of the DATA array, respectively.  
             NOTE: These are *NOT* index arrays.

        THISDATAINFO -> Returns the DATAINFO structure for the
             selected data block.

        MODELINFO -> Returns to the calling program the model information 
             structure created by CTM_TYPE.
                      
        GRIDINFO -> Returns to the calling program the grid information  
             structure created by CTM_GRID.

        WE -> Returns to the calling program the index array of longitudes
             for the extracted data region, ordered from west to east.

        SN -> Returns to the calling program the index array of latitudes
             for the extracted data region, ordered from South to North 
 
        UP -> Returns to the calling program the index array of vertical
             levels for the extracted data region, ordered from surface 
             to top.

        PSURF -> Surface pressure to be used for the conversion from
             sigma layers to pressure and altitude.  For defaults 
             see function CTM_TYPE.

       _EXTRA=e -> Picks up any extra keywords for CTM_GET_DATA
              and CTM_EXTRACT.
 
 OUTPUTS:
        SUCCESS -> Returns 1 if successful or 0 otherwise.
 
        DATA -> A 2D or 3D data array

 SUBROUTINES:
        External Subroutines Required:
        ==============================
        CTM_GET_DATA
        CTM_GRID    (function)
        CTM_EXTRACT (function)

 REQUIREMENTS:
        None

 NOTES:
        (1) CTM_GET_DATABLOCK returns the extracted data block as the 
        function value.

        (2) CTM_GET_DATABLOCK is meant to be called whenever you need
        to extract data from a punch file.  If the punch file needs
        to be opened, CTM_GET_DATABLOCK will do that automatically
        (via CTM_GET_DATA).  

 EXAMPLE:
   FILENAME  = '~/amalthea/CTM4/run/ctm.pch'
   LAT       = [  -90,  90 ]
   LON       = [ -180, 180 ]
   LEV       = 1
   SUCCESS   = CTM_GET_DATABLOCK( DATA, 'IJ-AVG-$',                 $
                           XIND=XMID, YIND=YMID, ZIND=ZMID,         $
                           THISDATAINFO=THISDATAINFO,               $
                           TRACER=1,           FILENAME=FILENAME,   $
                           GRIDINFO=GRIDINFO,  MODELINFO=MODELINFO, $
                           LEV=LEV,            LAT=LAT,             $
                           LON=LON,            WE=WE,               $
                           SN=SN,              UP=UP )

   IF ( NOT SUCCESS ) THEN RETURN, 0

            ; gets a data block for the IJ-AVG-$ (ND45) diagnostic,
            ; for the first tracer, at the first timestep, with the 
            ; given latitude, longitude, and sigma level ranges.  
            ; Returns FILEINFO, DATAINFO, THISDATAINFO, WE, SN, UP, 
            ; XMID, YMID, and ZMID to the calling program.

 MODIFICATION HISTORY:
        bmy, 16 Sep 1998: VERSION 1.00
        bmy, 17 Sep 1998: - added FILENAME keyword, so that the file
                            name can be passed back to the calling
                            program. 
        bmy, 18 Sep 1998: VERSION 1.01
                          - now compatible with CTM_EXTRACT v. 1.01
                          - INDEX, SN, WE, UP keywords added
                          - LATRANGE, LONRANGE, LEVRANGE renamed
                            to LAT, LON, LEV (since they may now 
                            contain arrays and not just ranges).
        mgs, 21 Sep 1998: VERSION 1.02
                          - more error checking
                          - added PSurf keywords
                          - frees gridinfo pointer before re-assignment
                          - removed MinData and MaxData
        bmy, 22 Sep 1998: - Now pass AVERAGE and TOTAL keywords to
                            CTM_EXTRACT
        mgs, 22 Sep 1998: - added THISDATAINFO keyword
        bmy, 24 Sep 1998: - added FORWARD_FUNCTION for CTM_GRID
                            and CTM_EXTRACT
        bmy, 08 Oct 1998: VERSION 1.03
                          - FILEINFO and DATAINFO are now keywords
                          - now returns X, Y, and Z as parameters
        bmy, 03 Nov 1998: VERSION 1.04
                          - compatible with new CTM_GET_DATA routine
                          - now pass FILEINFO and DATAINFO structures 
                            via USE_FILEINFO and USE_DATAINFO keywords
        mgs, 10 Nov 1998: - once more adapted to changes in CTM_GET_DATA
                          - now extracts locally used FILEINFO structure
        bmy, 11 Feb 1999: VERSION 1.05
                          - updated comments
        bmy, 19 Feb 1999: - Renamed XIND, YIND, ZIND to XMID, YMID,
                            and ZMID, since these are not index
                            arrays, but the actual longitude,
                            latitude, or altitude values for each
                            dimension of the DATA array.
                          - added DEBUG keyword
                          - eliminate obsolete XARR, YARR, ZARR keywords
                          - added NOPRINT keyword to suppress
                            call to CTM_PRINT_DATAINFO
        mgs, 02 Apr 1999: - replace gridinfo in fileinfo only if new
                            surface pressure is requested. Necessary 
                            for 2D fields (e.g. EPTOMS)
                          - deactivated SMALLCHEM flag
                          - added error checking for FILEINFO
        bmy, 28 Apr 1999: - return THISFILEINFO as a keyword
        mgs, 30 Jun 1999: - Specification of PSURF finally works.
        bmy, 13 Dec 1999: - now use CHKSTRU instead of N_ELEMENTS  
                            to diagnose undefined GRIDINFO structure
        bmy, 04 Dec 2000: GAMAP VERSION 1.47
                          - eliminated obsolete code from 12/31/99
        bmy, 03 Jun 2001: GAMAP VERSION 1.48
                          - bug fix: also create GRIDINFO structure
                            for grids with no vertical layers
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_get_datablock.pro)


CTM_GRID (FUNCTION)

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_GRID  (function)

 PURPOSE:
        Set-up of the model grid for various models. While the
        horizontal grid information can be computed from a few
        basic parameters, the vertical structure is hardwired
        for each model seperately. Currently, the following models
        are supported: GEOS1, GEOS_STRAT, GEOS-3, GEOS-4, GEOS-5,
        GEOS-57, MERRA, GISS_II, GISS_II_PRIME, FSU, FVCCM, and MATCH.
       
 CATEGORY
        GAMAP Utilities, GAMAP Models & Grids, Structures

 CALLING SEQUENCE:
        RESULT = CTM_GRID( MTYPE [, Keywords ] )

 INPUTS:
        MTYPE --> a MODELINFO structure as returned from function 
             CTM_TYPE.  This structure  must contain the following tags: 
             resolution (a 2 element vector with DI, DJ), halfpolar, 
             center180, name, nlayers, ptop, psurf, hybrid.)
 
 OUTPUT:
        RESULT -> A structure, scalor, or vector variable depending 
             on the output keywords below.

 KEYWORD PARAMETERS:
        PSURF -> specify surface pressure in mb. Overrides 
            value passed in through modelinfo structure.

        The following keywords define output options. If none of these
        is set, a structure is returned that contains all parameters.
	   IMX     (int   ) -> Maximum I (longitude) dimension  [alt: NLON]
          JMX     (int   ) -> Maximum J (latitude ) dimension  [alt: NLAT]
          DI      (flt   ) -> Delta-I interval between grid box edges
          DJ      (flt   ) -> Delta-J interval between grid box edges
          YEDGE   (fltarr) -> Array of latitude  edges
          YMID    (fltarr) -> Array of latitude  centers
          XEDGE   (fltarr) -> Array of longitude edges   
          XMID    (fltarr) -> Array of longitude centers

          LMX     (int)    -> Maximum altitude level (layers)  [alt: NLAYERS]
          SIGMID  (fltarr) -> Array of sigma center values
          SIGEDGE (fltarr) -> Array of sigma edges
          ETAMID  (fltarr) -> Array of ETA center values
          ETAEDGE (fltarr) -> Array of ETA edge values
          PMID    (fltarr) -> Array of approx. pressure values for sigma ctrs
          PEDGE   (fltarr) -> ditto for sigma edges
          ZMID    (fltarr) -> Array of approx. mean altitudes for sigma ctrs
          ZEDGE   (fltarr) -> ditto. for sigma edges
          AP      (fltarr) -> Hybrid-grid "A" parameters
          BP      (fltarr) -> Hybrid-grid "B" parameters 

        /NO_VERTICAL --> do not return vertical grid info in structure
             In this case the MTYPE structure only needs to contain
             resolution, halfpolar and center180. This keyword is ignored if 
             a specific (vertical) output option is requested.

        DELTAZ_m --> For multi-level 'GENERIC' grids, DELTAZ_m specifies
             the height of each grid level in meters.  DELTAZ_m does not
             apply to any of the GEOS, GISS, etc. grid families.

 SUBROUTINES:
        External Subroutines Required:
        ===============================
        GETSIGMA   (function)
        GETETA     (function)
        USSA_ALT   (function)
        USSA_PRESS (function)
        ZMID       (function)

 REQUIREMENTS:
        Best if used with function CTM_TYPE.  Also requires functions
        GETSIGMA and GETETA for definition of vertical layers.

 NOTES:
        This routine is not very efficient in that it always computes 
        all the available information. But since it will not be
        called too often and does not handle large amounts of data, 
        we won't worry about computational efficiency here.

 EXAMPLE:
        MTYPE = CTM_TYPE( 'GEOS1' )
        MGRID = CTM_GRID( MTYPE )

        ; This will define the following structure (help,mgrid,/stru)

        ** Structure <10323808>, 17 tags, length=1624, refs=1:
           IMX             INT             72
           JMX             INT             46
           DI              FLOAT           5.00000
           DJ              FLOAT           4.00000
           XEDGE           FLOAT     Array[73]     (-177.500, -172.500, ...)
           YEDGE           FLOAT     Array[47]     (-90, -88, -84, ...)
           XMID            FLOAT     Array[72]     (-180.0, -175.0, ...)
           YMID            FLOAT     Array[46]     (-89, -86, -82, ...)
           LMX             INT             20
           SIGMID          FLOAT     Array[20]     (0.993936, 0.971301, ...)
           SIGEDGE         FLOAT     Array[21]     (1.00000,  0.987871, ...)
           ETAMID          FLOAT     Array[20]     (all zeroes)
           ETAEDGE         FLOAT     Array[21]     (all zeroes)
           PMID            FLOAT     Array[20]     (980.082, 957.990, ...)
           PEDGE           FLOAT     Array[21]     (986.000, 974.162, ...)
           ZEDGE           FLOAT     Array[21]
           ZMID            FLOAT     Array[20]
           AP              

        ; Or, with the use of output keywords:
             PRINT, CTM_GRID( CTM_TYPE( 'GISS_II' ), /PMID )

        ; IDL will print
             986.000      935.897      855.733      721.458      551.109 
             390.781      255.503      150.287      70.1236      10.0000

        ; A more awkward example (see yourself):
             HELP, CTM_GRID( { RESOLUTION : [3.6,3.0],           $
                               HALFPOLAR  : 0,                   $
                               CENTER180  : 0 }, /NO_VERT), /STRU

 MODIFICATION HISTORY:
        bmy, 19 Aug 1997: VERSION 1.00
        bmy, 24 Sep 1997: VERSION 1.01
        mgs, 26 Feb 1998: Version 2.00  - rewritten as a function
        mgs, 27 Feb 1998: - added vertical information
        mgs, 02 Mar 1998: - better defined interface with CTM_MODEL_TYPE
        bmy, 07 Apr 1998: - Renamed 
        mgs, 24 Apr 1998: - changed structure to named structure
        mgs, 04 May 1998: - changed back because of conflicting sizes
        mgs, 07 May 1998: - Renamed to CTM_GRID
                          - x coordinates now start with -182.5 for 
                            center180 grids
        bmy, 19 Jun 1998: - now uses USSA_ALT to compute altitudes
                            from pressure coordinates
                          - fixed some comments
                          - added FORWARD_FUNCTION statement
        mgs, 30 Jun 1999: - added PSURF keyword
        bmy, 27 Jul 1999: GAMAP VERSION 1.42
                          - now can compute pressure levels and
                            edges for hybrid sigma-pressure grids
                          - a few cosmetic changes
        bmy, 03 Jan 2000: - more cosmetic changes
        bmy, 20 Apr 2000: GAMAP VERSION 1.45
                          - now returns correct YMID values for FSU grid
        bmy, 15 Sep 2000: GAMAP VERSION 1.46
                          - fixed bug for computing YMID for grids
                            w/o halfpolar boxes.  This also fixes the
                            previous problem w/ the FSU grid.
        bmy, 03 Jul 2001: GAMAP VERSION 1.48
                          - If MTYPE.NLAYERS = 0, then create a
                            return structure w/o vertical level info
        bmy, 06 Nov 2001: GAMAP VERSION 1.49
                          - added ETAMID, ETAEDGE keywords
                          - added ETAMID, ETAEDGE tags to return structure
                          - now calls GETETA to return ETA coordinates
                            for hybrid models (such as GEOS-4/fvDAS)
                          - updated comments
        bmy, 18 Oct 2002: GAMAP VERSION 1.52
                          - deleted obsolete commented-out code
        bmy, 04 Nov 2003: GAMAP VERSION 2.01
                          - Use STRPOS to test for GEOS4 or 
                            GEOS4_30L model names
                          - Now treat GISS_II_PRIME 23-layer model
                            as a hybrid grid instead of using the
                            obsolete "fake" formulation.
        bmy, 28 Jun 2006: GAMAP VERSION 2.05
                          - bug fix for multi-level GENERIC grids
  bmy & phs, 16 Aug 2007: GAMAP VERSION 2.10
                          - now compute mXEDGE, mXMID, mYEDGE, mYMID
                            as double precision, and cast back to
                            float, so that we get correct values for
                            high-res grids like 0.5 x 0.666,
                          - cosmetic changes
                          - Special handling for GEOS-5 
                          - Now use USAGE, ROUTINE_NAME() instead of
                            function USE_CTM_GRID to display options
                          - Now return IMX, JMX as type LONG
        bmy, 03 Aug 2009: GAMAP VERSION 2.13
                          - Added DELTAZ_m to specify grid size in 
                            meters for multi-level GENERIC grids   
        bmy, 06 Aug 2010: GAMAP VERSION 2.14
                          - Added MERRA (identical to GEOS-5 grid, 
                            but retains MERRA name for clarity.)
        bmy, 28 Nov 2010: GAMAP VERSION 2.15
                          - Now use modified GETETA routine to
                            compute the pressure and ETA coords
                            consistently.
                          - Now save hybrid-grid parameters Ap and Bp 
                            to the GRIDINFO structure.
        bmy, 02 Feb 2012: GAMAP VERSION 2.16
                          - Add GEOS57 and GEOS57_47L grids, for
                            GEOS-5.7.x met data.  (These are
                            identical to the GEOS-5 and MERRA grids,
                            but we will denote them separately).
        bmy, 13 Aug 2015: GAMAP VERSION 2.19
                          - Add MERRA2 and MERRA2_47L grids

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_grid.pro)


CTM_INDEX

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_INDEX

 PURPOSE:
        Return index of CTM grid boxes for given coordinates
        (or vice versa) and allow user to interactively select
        a grid box

 CATEGORY:
        GAMAP Utilities, GAMAP Models & Grids

 CALLING SEQUENCE:
        CTM_INDEX,  [,i,j] [,keywords]

 INPUTS:
        MINFO --> Model type strucure as returned by CTM_TYPE.PRO
     or GINFO --> Model grid structure as returned by CTM_GRID.PRO
            If neither is given, the user will be prompted for a model 
            type and the grid will be computed.

        I, J --> index pair for which lon, lat coordinates shall
            be found if keyword /GET_COORDINATES is set. Also used 
            to return index values for given lon, lat pairs (this is 
            the default operation).  NOTE: I and J will be in "FORTRAN"  
            notation (e.g. the starting from 1 and not zero). To index
            IDL arrays, be sure to use I-1 and J-1. 

 KEYWORD PARAMETERS:
        CENTER --> a two element vector with (LAT, LON) coordinates
            for which the gridbox index shall be returned. Also used
            to return center coordinates for a given index pair if
            keyword /GET_COORDINATES is set.

        EDGE --> a four element vector in the MAP_SET LIMIT format
            (LAT0, LON0, LAT1, LON1). If keyword GET_COORDINATES is
            not set and no CENTER coordinates are given, I and J will 
            return two element vectors with I(0) corresponding to LON0 
            and I(1) corresponding to LON1 etc. In this case, it may
            be useful to retrieve WE_INDEX and SN_INDEX for indexing
            of CTM data arrays (note that these indices follow the IDL
            convention, i.e. starting from 0. To convert them into "true"
            CTM indices, add 1).
            If CENTER coordinates are provided or /GET_COORDINATES is set 
            then EDGE returns the grid box edges for the given or calculated 
            index pair.

        WE_INDEX --> integer array for indexing of CTM data arrays. This
            keyword is only used when EDGE is a valid 4 element vector,
            keyword GET_COORDINATES is not set and no coordinates are 
            passed in the CENTER keyword. This array is always arranged
            in west-east order (e.g. for EDGE=[0.,175.,0.,-175.] it will
            return [70, 71, 0] (GEOS1 grid)). 

        SN_INDEX --> like WE_INDEX but for latitude indexing. Note that
            latitude values in EDGE must be arranged in ascending order.

        /GET_COORDINATES --> return coordinates to given index rather
            than an index pair for given coordinates
        
        /NON_INTERACTIVE --> default action is interactive box picking per
            mouse (only need to supply MINFO in this case, but index and
            coordinates of last click will be returned in I, J, CENTER
            and EDGES repectively). Set this keyword if you want to convert
            values to and fro without drawing a map etc.

        XSIZE, YSIZE --> window size (default 900x600)

        MAPCENTER --> center coordinates for map projection [p0lat, polon ]

        COUNTRIES -> draw country boundaries

        _EXTRA --> keywords are passed to MAP_SET 
            (e.g. LIMIT=[lat0,lon0,lat1,lon1])
            Careful if you display data!

        WINDOW -> window number to plot into. Normally a new window
            is opened with the /free option. Use a specific window number
            to overlay the map onto existing data plotted with tvimage
             (see example).

        DATA -> a data array with dimensions matching your model grid
            (no error checking on this!) If DATA contains data, the value
            at the selected grid box, and a statistic for neighbouring 
            grid boxes will be displayed together with the corrdinates.

 OUTPUTS:
        Index of grid box in I, J, coordinates in named variables supplied
        with CENTER and EDGE keywords

 SUBROUTINES:

 REQUIREMENTS:
        needs CTM_TYPE for input of MINFO parameter and 
        CTM_DEFINE_GRID 

 NOTES:
        This routine makes substantial use of recursive calls. Be careful
        when changing.

 EXAMPLES:
        (1)
        CTM_INDEX, CTM_TYPE('GEOS1')

             ; Display world map and have fun. 

        (2)
        CTM_INDEX, CTM_TYPE( 'GEOS1',RESOLUTION=2 ), $
            I, J, LIMIT=[ 0.,-180., 90., -30. ]

             ; Display map of North America and select grid 
             ; boxes for GEOS 2x2.5 grid.
             ; Indices of last point are returned in I and J.

        (3)
        CTM_INDEX, CTM_TYPE('GISS_II_PRIME'),$
             I, J, CENTER=[ 42., -72.], /NON_INTERACTIVE
        print,I,J

             ; returns grid box index for Harvard Forest in 
             ; GISS CTM II' (21,33) without displaying a map

        (4)
        CTM_INDEX, CTM_TYPE('GISS_II'), $
             I, J, EDGE=[-25.,170.,0.,-100.], $
             WE_INDEX=WE, SN_INDEX=SN, /NON_INTERACTIVE

             ; returns [ 69, 70, 71, 0, 1, ... , 15 ] in WE and 
             ; [ 15, 16, ..., 21 ] in SN. I is [ 70, 16 ], and J 
             ; is [ 16, 22 ]. Note that I, J refer to CTM (= FORTRAN)
             ;  indices, whereas WS and SN are IDL array indices.
        
        (5) 
        IM    = BYTSCL( DATA,MAX=MAX(DATA))
        MINFO = CTM_TYPE( 'GENERIC', RES=[360./XDIM,180./YDIM] )
        GINFO = CTM_GRID(MINFO)
        TVIMAGE, IM, POSITION=P, /KEEP_ASPECT
        CTM_INDEX, GINFO, I, J, WINDOW=0, DATA=DATA

             ; Overlay interactive map onto data displayed with 
             ; TVIMAGE.  You should create a generic MODELINFO 
             ; structure in this case.  NOTE: replace xdim, ydim 
             ; with the dimensions of your data array!
             ; This example also demonstrates the use of ginfo vs. minfo.

 MODIFICATION HISTORY:
        mgs, 04 May 1998: VERSION 1.00
        mgs, 07 May 1998: - added MAPCENTER and _EXTRA keywords, 
                            fixed bug with lon index
                          - actually substantially rewritten
        mgs, 08 May 1998: VERSION 1.10
                          - CENTER and EDGE keywords now MAP_SET compatible
                          - added WE_INDEX and SN_INDEX keywords
                          - improved documentation
                          - bug fix for display of polar grid boxes
        mgs, 09 Jun 1998: - added COUNTRIES keyword
        mgs, 15 Jun 1998: - bug fix for WE
        mgs, 07 Oct 1998: - added interactive selection of model
        mgs, 22 Feb 1999: - added DATA, SHELLS and WINDOW keywords
        mgs, 23 Feb 1999: - can now use either minfo or ginfo as parameter
        bmy, 24 Jan 2001: GAMAP VERSION 1.47
                          - commented out annoying & useless warning msg
                          - updated comments
        bmy, 12 Mar 2003: GAMAP VERSION 2.02
                          - updated comments
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - now pass DEFAULTMODEL from @GAMAP_CMN
                            common block to SELECT_MODEL

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_index.pro)


CTM_LABEL (FUNCTION)

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_LABEL (function)

 PURPOSE:
        Returns strings for several CTM quantities.

 CATEGORY:
        GAMAP Utilities, GAMAP Plotting

 CALLING SEQUENCE:
        RESULT = CTM_LABEL( DATAINFO, MODELINFO [, Keywords ] )

 INPUTS:
        DATAINFO -> Structure returned from CTM_GET_DATA, which
             contains information about one data block
                      
        MODELINFO -> Structure returned from CTM_TYPE, which
             contains information about the particular model 


 KEYWORD PARAMETERS:
        AVERAGE -> Bit flag indicating the dimensions over which
                   to average the data:
                      1 :  longitudinal
                      2 :  latitudinal
                      4 :  vertical
             These values can be combined. E.g., to average over
             longitude and latitude use 3. A bit set in AVERAGE 
             supersedes the corresponding bit in  TOTAL (see below). 

        LAT -> Scalar value or array of latitudes used in the plot.
 
        LON -> Scalar value or array of longitudes used in the plot.
 
        LEV -> Scalar value or array of latitudes used in the plot.

        ALT -> Scalar value or array of altitudes used in the plot.

        PRS -> Scalar value or array of pressures used in the plot.

        TOTAL -> Bit flag indicating the dimensions over which
                 to sum the data:
                      1 :  longitudinal
                      2 :  latitudinal
                      4 :  vertical
             These values can be combined. E.g., to integrate over 
             longitude and latitude use 3. A bit set in AVERAGE 
             supersedes the corresponding bit in TOTAL (see above).


        FORMAT -> Specifies format for converting numeric values into
             string values, for selected fields (such as LAT and LON).
             Default is I14 (strings are trimmed).

        /NO_SPECIAL -> If set, will not place any special superscript
             or subscript characters into the strings returned in
             LABELSTRU.

 OUTPUTS:
        LABELSTRU -> Structure containing the following label fields:
             LAT:        String for latitude(s)     
             LON:        String for longitude(s)
             LEV:        String for vertical level(s)
             ALT:        String for altitude level(s)
             PRS:        String for pressure level(s)
             LATLON:     String that has format "(Lat,Lon)"
             TRACERNAME: String for the tracer name
             SCALE:      String for the tracer's scale factor
             UNIT:       String for the tracer's unit
             TAU0:       String representation of TAU0
             TAU1:       String representation of TAU1
             YMD0:       String representation of (YY)YYMMDD
                           corresponding to TAU0
             YMD1:       String representation of (YY)YYMMDD
                           corresponding to TAU1
             HMS0:       String representation of HHMMSS
                           corresponding to TAU0
             HMS1:       String representation of HHMMSS
                           corresponding to TAU1
             YEAR0:      String for the starting year (e.g. 1994)
             YEAR1:      String for the ending year 
             MONTH0:     String for the starting month name 
                          (e.g. "Jan", "Feb", "Mar", etc..)
             MONTH1:     String for the ending month name
             DAY0:       String for the starting day number (1-31)
             DAY1:       String for the ending day number (1-31)
             DATE:       String for the date (see below)
             MODEL:      String for the model name
             FAMILY      String for the model's family
             RES:        String for the resolution of the model 

 SUBROUTINES:
        External Subroutines Required:
        ==============================================
        CHKSTRU (function)     STRCHEM (function)
        STRSCI  (function)     TAU2YYMMDD (function)
   
 REQUIREMENTS:
        DATAINFO and MODELINFO must be passed to CTM_LABEL.  These
        structures are computed by the GAMAP package subroutines.

 NOTES:
        DATAINFO is created e.g. by CTM_GET_DATA (or CTM_GET_DATABLOCK)
        MODELINFO is created by CTM_TYPE

 EXAMPLE:
        CTM_LABEL, DataInfo, ModelInfo, LabelStru, Lat=10, Lon=48
       
        print, LabelStru.LAT
            'Lat=10!UN!N'       

 MODIFICATION HISTORY:
         bmy, 23 Sep 1998: VERSION 1.00
         bmy, 24 Sep 1998: - now ensure that RES is a scalar string
                           - place TAU2YYMMDD in FORWARD_FUNCTION call
         bmy, 28 Sep 1998: VERSION 1.01
                           - formats for LatStr, LonStr, LevStr
                             changed to be more consistent.
         mgs, 29 Sep 1998: - changed a few comments and fixed bug in 
                             MinLon/MaxLon
         bmy, 03 Nov 1998: - changed NAME to TRACERNAME for
                             the sake of consistency
         bmy, 12 Nov 1998: - added LABELSTRU structure tags: YEAR0,
                             YEAR1, MONTH0, MONTH1, DAY0, DAY1, and DATE
                           - now reports lats as S/N instead of -/+ 
                             and reports lons as W/E instead of -/+
         bmy, 17 Nov 1998: - now use function N_UNIQ to test for
                             the number of unique elements in
                             LAT, LON, LEV, ALT, PRS
                           - Added FORMAT keyword to specify 
                             format for LAT and LON strings
                           - updated comments
         bmy, 15 Jan 1999: - added NO_SPECIAL keyword
         bmy, 17 Feb 1999: - Now add GMT to date string for timeseries
                             animation plots (interval < 1 day)
                           - make sure that HMS0STR and HMS1STR have
                             string lengths of 6 characters
         bmy, 18 Feb 1999: - fix default DATE string for February
         mgs, 16 Mar 1999: - cosmetic changes
                           - removed SUBTRACT_ONE keyword and improved
                             choice of date format
         bmy, 13 Jul 2001: GAMAP VERSION 1.48
                           - Use updated version of STRREPL.PRO from mgs 
         bmy, 07 Nov 2001: GAMAP VERSION 1.49
                           - now use 8-digit YYYYMMDD format for
                             date variables YMD0, YMD1
         bmy, 02 Oct 2002: GAMAP VERSION 1.53
                           - now write GEOS3 instead of GEOS3_30L
         bmy, 05 Nov 2003: GAMAP VERSION 2.01
                           - now write GEOS4 instead of GEOS3_30L
                           - now use the proper time epoch for each
                             model family in call to TAU2YYMMDD
                           - updated comments
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_label.pro)


CTM_LOCATEDIFF

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_LOCATEDIFF

 PURPOSE:
        Locates data blocks which differ in two binary
        punch files or GMAO met field files.  

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        CTM_LOCATEDIFF, FILE1, FILE2 [, Keywords ]

 INPUTS:
        FILE1 -> Name of the first file to be tested.  FILE1 may be
             a binary punch file, and ASCII file, or a GMAO met field
             file.

        FILE2 -> Name of the second file to be tested.  FILE2 may be
             a binary punch file, and ASCII file, or a GMAO met field
             file.

 KEYWORD PARAMETERS:
        DIAGN -> A diagnostic category name to restrict the selection
             of data records.

        OUTFILENAME -> Name of the output file which will contain
             the location of differences found between data blocks
             in FILE1 and FILE2.  If OUTFILENAME is not specified,
             then CTM_LOCATEDIFF will print this information to
             the screen.

        /HEADERS_ONLY -> Set this switch to just print the category
             names and tracer numbers where differences occur instead
             of printing all of the data points.

        _EXTRA=e -> Picks up any extra keywords for CTM_GET_DATA.

 OUTPUTS:
        None

 SUBROUTINES:
        External subroutines required:
        ==============================
        CTM_GET_DATA   UNDEFINE
        CTM_DIAGINFO

 REQUIREMENTS:
        References routines from both GAMAP and TOOLS directories.

 NOTES:
        (1) Both FILE1 and FILE2 must contain the same diagnostic 
            categories, listed in the same order.

 EXAMPLE:
        CTM_LOCATEDIFF, 'ctm.bpch.old', 'ctm.bpch.new'

             ; Locates data blocks which differ between ctm.bpch.old
             ; and ctm.bpch.new.  You can investigate these further
             ; with routines CTM_PRINTDIFF and CTM_PLOTDIFF.

 MODIFICATION HISTORY:
        bmy, 24 Feb 2003: VERSION 1.00
        bmy, 19 Nov 2003: GAMAP VERSION 2.01
                          - Now get spacing between diagnostic
                            offsets from CTM_DIAGINFO
        bmy, 27 Feb 2004: GAMAP VERSION 2.02
                          - Rewritten to also print out locations in
                            FORTRAN notation where differences occur
                          - added DIAGN keyword to specify category name
                          - added OUTFILENAME to specify output file
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
        bmy, 01 May 2013: GAMAP VERSION 2.17
                          - Corrected error in EXAMPLE section above

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_locatediff.pro)


CTM_MAKE_DATAINFO (FUNCTION)

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_MAKE_DATAINFO (function)

 PURPOSE:
        Create a datainfo and fileinfo structure from an
        "external" data set so that it can be used seamlessly
        within the GAMAP package. The dataset can have up to
        four dimensions (however, only the first 3 are currently
        supported). The new datainfo and fileinfo structures 
        will be added to the global structure arrays.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation, Structures

 CALLING SEQUENCE:
        RESULT = CTM_MAKE_DATAINFO( DATA, DATAINFO, FILEINFO  [,Keywords] )

 INPUTS:
        DATA  -> A 1-D, 2-D, or 3-D data array.

 KEYWORD PARAMETERS:
        DIAGN -> A diagnostics name (category) or number that describes
               the data type. If not given, the user will be prompted.
               If DIAGN is a number that is not recognized as valid
               diagnostics by CTM_DIAGINFO, the number will be stored
               as string value. If DIAGN is a string, it does not have 
               to be a valid diagnostics category.

        DIM -> A 4 element vector with the DATA dimensions as
               LON, LAT, LEVEL, TIME. If not given, the dimensions
               of DATA will be entered sequentially. Use this keyword
               to properly identify e.g. a zonal mean data set as
               DIM = [ 0, 46, 20, 0 ] (for the GEOS-1).
               The order and magnitude of the dimensions in DIM must
               agree with the dimensions of the DATA array
               (e.g. if DATA(72,46) then DIM=[46,72,0,0] is not allowed).

        FILENAME-> Name of the file which is specified by the
               FILEINFO structure.  If FILENAME is not specified, 
               then the default FILENAME = "derived data".

        FILETYPE -> A numeric code to identify the file type.  If not
               specified then the default FILETYPE = -1.

        FIRSTBOX -> A 3 element vector containing IFIRST, JFIRST, and
               LFIRST, which are the starting indices for the LON,
               LAT, and LEVEL dimensions.  

        FORMAT -> A format string (for ASCII data) or descriptive
               string (for binary or self-describing data) that is
               saved to the DATAINFO structure.  Default is ''.

        GRIDINFO -> A gridinfo structure describing the grid set-up
               of the data set (see CTM_GRID). If not given, 
               CTM_MAKE_DATAINFO attempts to use the MODELINFO 
               structure to construct GRIDINFO.

        ILUN -> The file unit number that will be used to identify 
               FILEINFO and DATAINFO.  If not passed, then ILUN will
               be negative to denote derived data, and will increment
               negatively for each data block, starting at -1. 

        MODELINFO -> A modelinfo structure containing information
               about the model that generated the data (see CTM_TYPE).
               If not given, the user is prompted for a selection.

        /NO_GLOBAL -> If passed, will prevent the DATAINFO and FILEINFO
               structures from being appended to the global GAMAP
               common blocks.  Useful for saving memory.

        /NO_VERTICAL (passed via _EXTRA) -> set this keyword if you only want
               to create a 2D gridfinfo structure.

        TAU0, TAU1 -> Beginning and end of time interval that is spanned
               by DATA (as TAU value). Default is -1 for both.

        TOPTITLE -> A user defined string that may describe the data set
               in more detail.

        TRACER -> A tracer number or name that identifies the chemical 
               species or physical quantity contained in DATA. If 
               TRACER is an invalid name, it will be set to -1, and the
               string value of TRACER will be used as TRCNAME (see below). 
               If not given, the user will be prompted.

        TRCNAME -> A tracer name. Default is to use the name associated
               with that tracer number in CTM_TRACERINFO.

        SCALE -> A value that is entered in the SCALE field in DATAINFO.
               Default is 1.0.

        UNIT -> A unit string. Default is empty.

 OUTPUTS:
        DATAINFO, FILEINFO -> The datainfo and fileinfo structures
               generated from the "external" data array. These are 
               automatically appended to the global DATAINFO and FILEINFO 
               structures, unless the /NO_GLOBAL keyword is set.

 SUBROUTINES:
        External Subroutines Required:
        =========================================
        CREATE3DHSTRU, CREATE3DFSTRU, TAU2YYMMDD

 REQUIREMENTS:
        None

 NOTES:
        In the current version, no error checking is made whether the
        DATA dimensions agree with the grid information. This is the
        users responsibility. 

 EXAMPLES:
        (1)
        DATA   = DIST(72,46)
        RESULT = CTM_MAKE_DATAINFO( DATA, DATAINFO, FILEINFO )

             ; Create a 2D array and make a DATAINFO structure.
             ; The user will be prompted for model type, 
             ; diagnostics and tracer.
   
        (2)
        RESULT = CTM_MAKE_DATAINFO( DATA, DATAINFO, FILEINFO,        $
            MODEL=CTM_TYPE( 'GEOS1' ), DIAGN='IJ-AVG-$',             $ 
            TRACER=2, TAU0=NYMD2TAU(940901L), TAU1=NYMD2TAU(940930), $
            UNIT='PPBV', DIM=[0,46,20,0],                            $
            TOPTITLE='Zonal mean difference in Ox CLDS/no CLDS')

             ; Add a zonal mean difference data set (already in DATA) 

        (3)
        HELP, DATAINFO, /STRU
           ** Structure H3DSTRU, 13 tags, length=72:
              ILUN            LONG               -15
              FILEPOS         LONG                 0
              CATEGORY        STRING    'ZONE-AVG'
              TRACER          INT              2
              TRACERNAME      STRING    'Ox'
              TAU0            DOUBLE           84720.000
              TAU1            DOUBLE           85416.000
              SCALE           FLOAT           1.00000
              UNIT            STRING    'ppbv'
              FORMAT          STRING    ''
              STATUS          INT              1
              DIM             INT       Array[4]
              OFFSET          INT       Array[3]
              DATA            POINTER   

             ; Display DATAINFO structure

 MODIFICATION HISTORY:
        mgs, 09 Oct 1998: VERSION 1.00
        mgs, 19 Nov 1998: - bug fix. ILUN now always negative!
                          - unit now "required" parameter, i.e.
                            interactively asked for
        bmy, 11 Feb 1999: VERSION 1.01
                          - added OFFSET keyword so that I0, J0, and
                            L0 offsets can be stored in DATAINFO
                          - DATAINFO.TAU0 and DATAINFO.TAU1 are now
                            stored as double precision
                          - updated comments
        mgs, 16 Mar 1999: - cosmetic changes
                          - OFFSET changed into FIRSTBOX
        mgs, 30 Mar 1999: - added _EXTRA keyword for ctm_grid
                            (use for /NO_VERTICAL)
        bmy, 29 Jun 2001: GAMAP VERSION 1.48
                          - bug fix: now pass CTM_TRACERINFO the
                            tracer number plus diagnostic offset
        bmy, 06 Mar 2002: GAMAP VERSION 1.50
                          - now take TRACER mod 100L before 
                            adding the diagnostic offset to it
                            in call to CTM_TRACERINFO
        bmy, 26 Nov 2003: GAMAP VERSION 2.01
                          - added /NO_GLOBAL keyword
                          - rewrote for clarity; updated comments
                          - Now get diagnostic spacing from CTM_DIAGINFO
                          - added ILUN, FILENAME, FILETYPE keywords
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
        phs, 30 May 2008: GAMAP VERSION 2.12
                          - Minor fix to restrict FIRSTBOX to 3 elements

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_make_datainfo.pro)


CTM_MAPGRID

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_MAPGRID

 PURPOSE:
        Plots CTM grid boxes superposed atop a world map.

 CATEGORY:
        GAMAP Utilities, GAMAP Models & Grids

 CALLING SEQUENCE:
        CTM_MAPGRID, GRIDINFO [, Keywords ]

 INPUTS:
        GRIDINFO -> Output structure returned from CTM_GRID
             containing information about the particular
             grid being used.

 KEYWORD PARAMETERS:
        COLOR -> Color index for the map outline, continents, and
             title.  Default is BLACK (assuming MYCT color table).

        G_COLOR -> Color index for the grid lines.  
             Default is BLACK (assuming MYCT color table).

        LIMIT -> Vector containing [ LatMin, LonMin, LatMax, LonMax ].
             These define the latitude and longitude ranges for
             the map projection.  If LIMIT is not supplied,
             CTM_MAPGRID will construct LIMIT from the information
             supplied in GRIDINFO.

        /PS -> If set, will send output to a PostScript file.

        _EXTRA=e -> Picks up any extra keywords for OPEN_DEVICE,
             MAP_SET, MAP_CONTINENTS, PLOTS, and CLOSE_DEVICE.

 OUTPUTS:
        None

 SUBROUTINES:
        External Subroutines Required:
        =========================================
        CHKSTRU       (function)   CONVERT_LON
        OPEN_DEVICE                CLOSE_DEVICE 
        MYCT_DEFAULTS (function)
        
 REQUIREMENTS:
        None

 NOTES:
        None

 EXAMPLES:
        (1)
        GRIDINFO = CTM_GRID( CTM_TYPE( 'GEOS1', RES=2 ) )
        CTM_MAPGRID, GRIDINFO, LIMIT=[ -90, 130, 90, -130 ], /ISOTROPIC

             ; Plots a world map (pacific region, spanning
             ; the date line) for the GEOS-1 2 x 2.5 grid 


        (2)
        CTM_MAPGRID, GRIDINFO, LIMIT=[ -90, -182.5, 90, 177.5 ], /ISOTROPIC

             ; For the same grid as above, plots the entire world
             ; centered on 0 degrees lat and 0 degrees longitude.

 MODIFICATION HISTORY:
        bmy, 03 Nov 1999: VERSION 1.00
        bmy, 24 Mar 2000: VERSION 1.45
                          - now prints map labels 
                          - added /NOBORDER to MAP_SET call
        bmy, 27 May 2003: GAMAP VERSION 1.53
                          - now plots continent lines after grid lines
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_mapgrid.pro)


CTM_MASS_CHECK

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_MASS_CHECK

 PURPOSE:
        Plots the time evolution of % difference of tracer mass and 
        air mass from a CTM simulation.  Used to assess mass
        conservation in CTM transport codes.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        CTM_MASS_CHECK [, Keywords ]

 INPUTS:
        FILENAME -> Name of the CTM output file containing air mass
             and tracer concentrations.  FILENAME can be either an
             ASCII punch file or a BINARY punch file.  If omitted,
             the user will be prompted to supply FILENAME via a 
             dialog box.

 KEYWORD PARAMETERS:
        TRACER -> Number of the tracer that you wish to check for
             mass conservation.

        /PS -> Set this switch to create PostScript plot output.

        OUTFILENAME -> If /PS is set, OUTFILENAME will be the name of
             the PostScript plot output file.  Default is "mass_check.ps".

        _EXTRA=e -> Catches extra keywords for routines OPEN_DEVICE
             and CLOSE_DEVICE.

 OUTPUTS:
        None

 SUBROUTINES:
        External Subroutines Required:
        ===============================
        CLOSE_DEVICE   CTM_GET_DATA
        MULTIPANEL     OPEN_DEVICE    
        UNDEFINE

 REQUIREMENTS:
        References routines from both GAMAP and TOOLS packages.

 NOTES:
        (1) Assumes that the tracer concentration has been saved
            under the IJ-AVG-$ diagnostic category.  Also assumes 
            that the airmass has been saved under the BXHGHT-$
            diagnostic category.  

 EXAMPLE:
        CTM_MASS_CHECK, 'ctm.bpch.geos4', TRACER=4

            ; Plots the evolution of % difference of both
            ; tracer and air mass for CO from a GEOS-4 simulation.

 MODIFICATION HISTORY:
  bdf & bmy, 26 Jun 2003: GAMAP VERSION 2.03
        bmy, 06 Mar 2007: GAMAP VERSION 2.06
                          - make FILENAME an input rather than
                            a keyword argument.
                          - now pass _EXTRA=e to the PLOT command
                          - Added WINPARAM keyword
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_mass_check.pro)


CTM_NAMEXT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_NAMEXT

 PURPOSE:
        Returns the proper filename extension for CTM model names.

 CATEGORY:
        GAMAP Utilities, GAMAP Models & Grids

 CALLING SEQUENCE:
        RESULT = CTM_NAMEXT( MODELINFO )

 INPUTS:
        MODELINFO -> a MODELINFO structure (output from function
             CTM_TYPE) desribing the desired CTM model.

 KEYWORD PARAMETERS:
        None

 OUTPUTS:
        RESULT -> Returns a string containing the model name 
             (e.g. 'geos3', 'geos4', 'geos5', 'gcap', 'giss2p', 
              'generic', etc.).

 SUBROUTINES:
        External Subroutines Required:
        ==============================
        CHKSTRU (function)

 REQUIREMENTS:
        None

 NOTES:
        (1) Add more model names as is necessary.

 EXAMPLE:
        MODELINFO = CTM_TYPE( 'GEOS_STRAT', RESOLUTION=4 )
        PRINT, CTM_NAMEXT( MODELINFO )
             geoss

             ; Returns filename extension for the GEOS-STRAT model

 MODIFICATION HISTORY:
        bmy, 30 Jun 2000: GAMAP VERSION 1.46
        bmy, 02 Jul 2001: GAMAP VERSION 1.48
                          - added GENERIC as a return option
        bmy, 02 Oct 2003: GAMAP VERSION 1.53
                          - now add GEOS3_30L to the CASE statement
        bmy, 16 Oct 2003: - now add GEOS4 to the CASE statement
        bmy, 12 Feb 2004: GAMAP VERSION 2.01a
                          - added GEOS4_30L to the CASE statement
        bmy, 05 Aug 2004: GAMAP VERSION 2.02
                          - added GCAP to the CASE statement
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - added GEOS5, GEOS5_47L to the CASE statement
        bmy, 04 Jan 2010: GAMAP VERSION 2.15
                          - added MERRA, MERRA_47L to the CASE statement
        bmy, 09 Feb 2012: GAMAP VERSION 2.16
                          - added GEOS57, GEOS57_47L to the CASE statement
        mps, 06 Nov 2013: - added GEOSFP, GEOSFP_47L to the CASE statement
        mps, 28 Oct 2015: - added MERRA2, MERRA2_47L to the CASE statement

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_namext.pro)


CTM_NOYBUDGET

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_NOYBUDGET

 PURPOSE:
        Computes the NOy budget within a given 3-D region.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        CTM_NOYBUDGET [, BATCHFILE [, Keywords ] ]

 INPUTS:
        BATCHFILE (optional) -> Name of the batch file which 
             contains inputs that defines the 3-D region and NOy
             constituents.  If BATCHFILE is omitted, then the user
             will be prompted to supply a file name via a dialog box.

 KEYWORD PARAMETERS:
        LOGFILENAME (optional) -> Name of the log file where output 
             will be sent.  Default is "noy_budget.log".

 OUTPUTS:
        None

 SUBROUTINES:
        Internal Subroutines:
        --------------------------------------------------------------
        ErrorNOy                       (function)
        TruncateAndWrapForNOy          (function)
        GetNoxEmissionsForNOy          (function)  
        GetHNO3WetDepForNOy            (function)
        GetDryDepositionForNOy         (function)  
        GetNetExportForNOy             (function)
        GetNetChemicalProductionForNOy (function)  
        ReadBatchFileForNOy            (procedure)

        External Subroutines:
        --------------------------------------------------------------
        CTM_Get_Datablock (function)  CTM_BoxSize (function)

 REQUIREMENTS:
        None

 NOTES:
        (1) CTM_NOYBUDGET was developed for use with the GEOS-CTM,
            there might be some adaptation required for use with
            other models.

        (2) Only 5 "families" are considered: 
            Dry Deposition, NOx, PAN, HNO3, R4N2.

        (3) Wrapping around the date line seems to work but you
            should always double-check.

 EXAMPLE:
        CTM_NOYBUDGET, 'box1.dat', LogFileName='box1.log'
           
             ; Computes NOy budgets for the region specified in
             ; the file "box1.dat" and sends output to the 
             ; "box1.log" log file.

 MODIFICATION HISTORY:
        bmy, 28 Jan 2000: VERSION 1.00
                          - adapted original code from Isabelle Bey
        bmy, 25 May 2000: VERSION 1.45
                          - now allow the user to specify diagnostic
                            category names in the batch file
                          - added internal function "TruncateAndWrapForNOy"
                            to wrap arrays around the date line
                          - added internal procedure "ErrorNOy"
                            to do error checking for CTM_GET_DATABLOCK
                          - now can create budgets for more than one
                            diagnostic interval
                          - now allow user not to compute chemical 
                            production data for given families
        acs, 26 May 2000: - bug fixes: now do not stop the run if 
                            data blocks are not found
        bmy, 01 Aug 2000: VERSION 1.46
                          - use abs( Total( X ) ) > 0 when testing if 
                            transport fluxes are all nonzero
        bmy, 24 Jan 2001: GAMAP VERSION 1.47
                          - now no longer require all types of emissions
                            to be nonzero in order to sum them
                          - now no longer require both HNO3 LS and
                            convective wetdep to be zero in order to 
                            sum them
        bmy, 17 Jan 2002: GAMAP VERSION 1.50
                          - now call STRBREAK wrapper routine from
                            the TOOLS subdirectory for backwards
                            compatiblity for string-splitting
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_noybudget.pro)


CTM_OVERLAY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_OVERLAY

 PURPOSE:
        Calls TVMAP to plot a pixel or contour map and then overplots 
        either an aircraft flight track or individual station data 
        atop it.

 CATEGORY:
        GAMAP Utilities, GAMAP Plotting

 CALLING SEQUENCE:
        CTM_OVERLAY, DATA,   XMID,   YMID, $
                     TRACKD, TRACKX, TRACKY [, Keywords ]

 INPUTS:
        DATA -> Data array (e.g. from CTM_GET_DATA or CTM_GET_DATABLOCK)
             from which a pixel plot or contour plot will be generated.

        XMID -> Vector of longitudes corresponding to DATA.

        YMID -> Vector of latitudes corresponding to DATA

        TRACKD -> Vector of data values corresponding to the aircraft
             flight track or station data points.

        TRACKX -> Vector of longitudes corresponding to the aircraft 
             flight track or station data points.  Should be in the 
             range [-180,180].

        TRACKY -> Vector of longitudes corresponding to the aircraft
             flight track or station data points.  Should be in the 
             range [-90,90].

 KEYWORD PARAMETERS:
        C_COLORS -> Vector to specify the color levels for filled
             contour plots.  If not passed, then C_COLORS will return
             to the calling program the default color level values
             generated internally by TVMAP.
 
        C_LEVELS -> Vector containing contour levels for filled
             contour plots.  Used in conjunction with /FCONTOUR. 

        COLOR -> Color of the map outline.  Passed to TVMAP.

        /FCONTOUR -> Set this switch to generate a filled-contour
             plot instead of a pixel plot.

        /LOG -> Set this switch to use a logarithmic color table.

        MINDATA -> Minimum value of DATA.  If omitted, then MINDATA
             will be automatically set to the minimum value of DATA.

        MAXDATA -> Minimum value of DATA.  If omitted, then MINDATA
             will be automatically set to the minimum value of DATA.

        /OVERPLOT -> Set this keyword to overplot a flight track
             atop a map previously drawn by TVMAP.

        T_COLOR -> (1) If plotting aircraft flight track data, then
             T_COLOR will be used to define the color of the line.
             (2) If plotting symbol data, then T_COLOR will be used to
             describe the color of the border around the symbol.  
             To suppress printing a border around the symbol, use
             any negative value for T_COLOR (e.g. T_COLOR = -1).

        T_LINESTYLE -> IDL linestyle for the aircraft flight track.
             Takes same values as the LINESTYLE graphic keyword
             (see help pages).

        T_SYMBOL -> Argument to the SYM keyword, which will be used
             to define the individual data points if you are plotting
             station data.  Recommended value: 1 (filled circle).

        T_THICK -> Thickness of the aircraft flight track, in pixels.
 
        _EXTRA=e -> Passes extra keywords to TVMAP and OPLOT.

 OUTPUTS:
        None

 SUBROUTINES:
        Internal Subroutines:
        ==========================================
        SCALETRACK (function)

        External Subroutines Required:
        =========================================
        MULTIPANEL      MYCT_DEFAULTS (function) 
        TVMAP           RECTANGLE
        SYM (function)

 REQUIREMENTS:
        None

 NOTES:
        You can pass all of the same keywords to CTM_OVERLAY_FLIGHT
        as you do to TVMAP.    

 EXAMPLE:
        (1) Plot flight tracks atop a pixel or contour map
        --------------------------------------------------

        ; Read the data -- in this case, CO concentrations
        SUCCESS = CTM_Get_DataBlock( Data, 'IJ-AVG-$',     $
                                     File='ctm.bpch.1995', $
                                     Tra=4,                $
                                     /First,               $
                                     Lon=[-180, 180],      $
                                     Lat=[-88,   88],      $
                                     Lev=1,                $
                                     XMid=XXmid, Ymid=YYMid )
         
        
        ; Make a "fake" aircraft track
        ; Here we'll use MAP_2POINTS to create a "fake" flight 
        ; track of constant longitude (30 deg E meridian)
        nPts   = 101
        a      = MAP_2POINTS( 30, -90, 30, 90, NPATH=NPTS )
        TrackX = A[0,*]
        TrackY = A[1,*]
        TrackD = FltArr( nPts )                  
               
        ; Plot a pixel map w/ countries, continents, grid lines,
        ; and overlay a red, dashed-line flight track atop it.
        CTM_OverLay, Data, XXMid, YYMid, TrackD, TrackX, TrackY, $
           /Sample,    /Countries,    /Coasts,    /CBar,         $      
           Div=4,      Min_Val=1e-20, /Isotropic, /Grid,         $ 
           Title='Pixel map overlaid /w contour map',            $    
           T_Color=!MYCT.RED, T_Thick=2, T_LineStyle=2
         
        ; Make a second "fake" aircraft track
        ; (of course, if you have a real flight track, use it...)
        TrackX = Replicate( 72, 100 )
        TrackY = Findgen( 100 ) - 50
        TrackD = Fltarr( 100 )
         
        ; Call CTM_OVERLAY again with /OVERPLOT to 
        ; overplot the second flight track
        CTM_OverLay, Data, XXMid, YYMid, TrackD, TrackX, TrackY, $
           T_Color=!MYCT.BLUE, T_Thick=2, T_LineStyle=2, /OVERPLOT


       (2) Draw Boxes for Tagged Tracer regions
       ----------------------------------------

       ; Define (X,Y) coordinates of first tagged tracer region
       TrackX = [ 0, 60, 60,  0, 0 ]
       TrackY = [ 0,  0, 30, 30, 0 ]
       TrackD = [ 0,  0,  0,  0, 0 ]
    
       ; Call CTM_OVERLAY with all TVMAP keywords to
       ; plot the map and to initialize the map dataspace
       CTM_OverLay, Data, XXMid, YYMid, TrackD, TrackX, TrackY, $
          /Sample,    /Countries,    /Coasts,    /CBar,         $      
          Div=4,      Min_Val=1e-20, /Isotropic, /Grid,         $       
          Title='Test pixel map w/ overlay boxes',              $
          T_Thick=3,  T_Color=!MYCT.BLACK,  T_LineStyle=0
    
       ; Define second tagged tracer region
       TrackX = [ 0, 120, 120,   0, 0 ]
       TrackY = [ 0,   0, -30, -30, 0 ]
          
       ; Call CTM_OVERLAY with /OVERPLOT to overplot
       ; atop the previously defined map
       CTM_OverLay, Data, XXMid, YYMid, TrackX, TrackY, $
          /OVERPLOT, T_Thick=3, T_Color=!MYCT.RED, T_LineStyle=0


       (3) Plot individual station data points
       ----------------------------------------

       ; Define "fake" station data for demo
       ; (along the equator between 60W and 60E)
       Ind    = Where( XMid ge -60 AND XMid le 60, N )
       TrackD = Findgen(N) + 20
       TrackY = Fltarr(N)  + 0
       TrackX = Xmid[Ind]

       ; Call CTM_OVERLAY with all TVMAP keywords to
       ; plot the map and to initialize the map dataspace
       CTM_OverLay, Data, XXMid, YYMid, TrackD, TrackX, TrackY, $
          /Sample,    /Countries,    /Coasts,    /CBar,         $      
          Div=4,      Min_Val=1e-20, /Isotropic, /Grid,         $      
          T_Symbol=1, SymSize=2,                                $
          Title='Test pixel map w/ station data',           
         

 MODIFICATION HISTORY:
        bmy, 05 Oct 2006: GAMAP VERSION 2.05
                          - Modified from CTM_OVERLAY_FLIGHT and
                            renamed to CTM_OVERLAY
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
  dbm & bmy, 06 Nov 2007: - Modified to allow filled contour plots
  cdh & bmy, 18 Feb 2009: GAMAP VERSION 2.13
                          - Now pass LOG=LOG to TVMAP call to ensure
                            that TVMAP gets the /LOG keyword OK
  bmy & cph, 14 Jan 2010: GAMAP VERSION 2.14
                          - Remove the call to the PLOT command after
                            TVMAP. This does set up the approropriate
                            coordinates for map projections other
                            than /CYLINDRICAL.
                          - Now use PLOTS to plot symbols or lines
                            rather than OPLOT.
                          - Updated comments
        cdh, 24 Feb 2010: - Added /NOADVANCE keyword
        bmy, 06 Aug 2010: GAMAP VERSION 2.14
                          - Now set default values for C_COLORS
                            for filled contour plots if not specified
   bf & bmy, 18 Oct 2010: - Bug fix submitted by Bonne Ford to allow
                            more than one overlay on the same plot
        bmy, 10 Feb 2016: GAMAP VERSION 2.19
                          - If plotting symbols, suppress symbol borders
                            if T_COLOR is negative (e.g. T_COLOR=-1).
                          - Now require adding /NOADVANCE before each 
                            successive call to CTM_OVERLAY with /OVERPLOT

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_overlay.pro)


CTM_OVERLAY_WIND

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_OVERLAY_WIND

 PURPOSE:
        Calls TVMAP to plot a pixel or contour map and then overplots 
        wind data atop it.
        %%%% NOTE: Still in BETA testing! %%%%

 CATEGORY:
        GAMAP Utilities, GAMAP Plotting

 CALLING SEQUENCE:
        CTM_OVERLAY, DATA, XMID, YMID, U, V, [, Keywords ]

 INPUTS:
        DATA -> Data array (e.g. from CTM_GET_DATA or CTM_GET_DATABLOCK)
             from which a pixel plot or contour plot will be generated.

        XMID -> Vector of longitudes corresponding to DATA.

        YMID -> Vector of latitudes corresponding to DATA

        U -> Array of U-wind values

        V -> Array of V-wind values

 KEYWORD PARAMETERS:
        COLOR -> Color of the map outline.  Passed to TVMAP.

        /LOG -> Set this switch to use a logarithmic color table.

        MINDATA -> Minimum value of DATA.  If omitted, then MINDATA
             will be automatically set to the minimum value of DATA.

        MAXDATA -> Minimum value of DATA.  If omitted, then MINDATA
             will be automatically set to the minimum value of DATA.

        /OVERPLOT -> Set this keyword to overplot the wind
             atop a map previously drawn by TVMAP.
 
        _EXTRA=e -> Passes extra keywords to TVMAP and VELOCITY_FIELD.

 OUTPUTS:
        None

 SUBROUTINES:
        Internal Subroutines:
        ==========================================
        SCALETRACK (function)

        External Subroutines Required
        =========================================
        MULTIPANEL      MYCT_DEFAULTS (function) 
        TVMAP           RECTANGLE
        SYM (function)

 REQUIREMENTS:
        Uses routines from both GAMAP and TOOLS packages.

 NOTES:
        You can pass all of the same keywords to CTM_OVERLAY_FLIGHT
        as you do to TVMAP.    

 EXAMPLE:
        (1) Plot flight tracks atop a pixel or contour map
        --------------------------------------------------

        ; Read the data -- in this case, CO concentrations
        SUCCESS = CTM_Get_DataBlock( Data, 'IJ-AVG-$',     $
                                     File='ctm.bpch.1995', $
                                     Tra=4,                $
                                     /First,               $
                                     Lon=[-180, 180],      $
                                     Lat=[-88,   88],      $
                                     Lev=1,                $
                                     XMid=XXmid, Ymid=YYMid )
         

        ; Make a "fake" wind [TO DOCUMENT]
         

 MODIFICATION HISTORY:
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
        phs, 20 Mar 2008: GAMAP VERSION 2.12
                          - cleanup, updated for new TVMAP
                          - now pass Map Position to velocity_field

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_overlay_wind.pro)


CTM_OXBUDGET

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_OXBUDGET

 PURPOSE:
        Computes the Ox budget within a given 3-D region.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        CTM_OXBUDGET [, BATCHFILE [, Keywords ] ]

 INPUTS:
        BATCHFILE (optional) -> Name of the batch file which 
             contains inputs that defines the 3-D region and NOy
             constituents.  If BATCHFILE is omitted, then the user
             will be prompted to supply a file name via a dialog box.

 KEYWORD PARAMETERS:
        LOGFILENAME (optional) -> Name of the log file where output 
             will be sent.  Default is "ox_budget.log".

 OUTPUTS:
        None

 SUBROUTINES:
        Internal Subroutines:
        --------------------------------------------------------------
        ErrorOx                       (function)
        TruncateAndWrapForOx          (function)
        GetHNO3WetDepForOx            (function)             
        GetDryDepositionForOx         (function)  
        GetNetChemicalProductionForOx (function)  
        GetNetExportForOx             (function)
        ReadBatchFileForOx            (procedure)

        External Subroutines Required:
        --------------------------------------------------------------
        CTM_Get_Datablock (function)  CTM_BoxSize (function)

 REQUIREMENTS:
 

 NOTES:
        (1) CTM_OXBUDGET was developed for use with the GEOS-CTM,
            there might be some adaptation required for use with
            other models.  

        (2) Only 2 "families" are considered: Dry Deposition and Ox.

        (3) Wrapping around the date line seems to work but you
            should always double-check.

        (4) Currently, the box of consideration must be less than
            global size in order to m
       
 EXAMPLE:
        CTM_OXBUDGET, 'box1.ox', LogFileName='box1.log'
           
             ; Computes Ox budgets for the region specified in
             ; the file "box1.ox" and sends output to the 
             ; "box1.log" log file.

 MODIFICATION HISTORY:
        bmy, 28 Jan 2000: VERSION 1.00
                          - adapted original code from Isabelle Bey
        bmy, 25 May 2000: GAMAP VERSION 1.45
                          - now allow the user to specify diagnostic
                            category names in the batch file
                          - added internal function "TruncateAndWrapForOx"
                            to wrap arrays around the date line
                          - added internal procedure "ErrorOx"
                            to do error checking for CTM_GET_DATABLOCK
                          - now can create budgets for more than one
                            diagnostic interval  
                          - now allow user not to compute chemical 
                            production data for given families
        acs, 26 May 2000: - bug fixes: now do not stop the run if 
                            data blocks are not found.  
        bmy, 01 Aug 2000: GAMAP VERSION 1.46
                          - use abs( Total( X ) ) > 0 when testing if 
                            transport fluxes are all nonzero
        bmy, 13 Dec 2001: GAMAP VERSION 1.49
                          - Now do not require all transport fluxes
                            to be nonzero in order to compute budgets
                          - now truncate data blocks correctly for
                            E/W and N/S transport fluxes
                          - Now compute the total number of seconds
                            over the entire diagnostic interval
                          - Now divide fluxes by the number of diagnostic
                            time intervals in order to get average fluxes
        bmy, 17 Jan 2002: GAMAP VERSION 1.50
                          - now call STRBREAK wrapper routine from
                            the TOOLS subdirectory for backwards
                            compatiblity for string-splitting;
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
        bmy, 23 Mar 2008: GAMAP VERSION 2.12
        phs, 20 Aug 2008: GAMAP VERSION 2.13
                          - now 3D region can be as small as one box.

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_oxbudget.pro)


CTM_PLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_PLOT

 PURPOSE:
        General plotting tool for CTM data that is stored in the 
        GAMAP datainfo and fileinfo structures. CTM_PLOT can 
        handle everything from 0-D to 3-D and has many different
        plot options, especially for 2-D plots for which it was
        originally designed. E.g. full map support.

 CATEGORY:
        GAMAP Utilities, GAMAP Plotting

 CALLING SEQUENCE:
        CTM_PLOT, [ Diagn [ [ ,Keywords ] ] 

 INPUTS:
        DIAGN -> The diagnostic number (e.g. ND22, ND45, etc or 
             category name (e.g. "JV-MAP", "IJ-AVG") for which to 
             read data from the punch file. 

 KEYWORD PARAMETERS:
    Keyword parameters passed to CTM_GET_DATABLOCK:
    ===============================================
        FILENAME -> Name of the punch file to read data from.  
             FILENAME is passed to CTM_GET_DATABLOCK.  You can also
             use a file mask, in which case FILENAME will return the 
             full filename if it is a named variable. If an empty 
             filename is provided, the default search mask from 
             gamap.defaults (see gamap.cmn) will be used. If no 
             filename is given, ctm_plot will try 
             to find the records from data already loaded.

        TRACER -> Number of tracer to read from the punch file.

        TAU0, /FIRST, /LAST -> time step to be plotted

        LON -> If /INDEX is set, LON denotes the CTM longitude index
             of the box to plot.  Otherwise, LON denotes the actual
             longitude value of that box. (that is at box CENTER, phs
             4/2/08)

        LAT -> If /INDEX is set, LAT denotes the CTM latitude index
             of the box to plot.  Otherwise, LAT denotes the actual
             latitude value of that box. (that is at box CENTER, phs
             4/2/08)

        LEV -> An index array of sigma levels *OR* a two-element
             vector specifying the min and max sigma levels to be 
             included in the plot.  Default is [ 1, GRIDINFO.LMX ].
 
        ALTRANGE -> A vector specifying the min and max altitude
             values to be included in the extracted data block.

        PRANGE -> A vector specifying the min and max pressure 
             levels to be included in the extracted data block.

        /INDEX -> If set, will interpret LAT, LEV, and LON as CTM 
             indices.  If not set, will interpret LAT, LEV, and LON
             as the actual values of latitude, level, and longitude.
             NOTE: If /INDEX is set, then GAMAP cannot create plots
             for longitude ranges that span the date line!!!

        AVERAGE -> If = 0, will not average the data 
                      = 1, will average data longitudinally
                      = 2, will average data latitudinally
                      = 4, will average data vertically
             These are cumulative (e.g. AVERAGE=3 will average over 
             both lat and lon, and AVERAGE=7 will average over lat,
             lon, and vertical levels to produce 1 data point).
                       
        TOTAL -> If = 0, will not total data
                    = 1, will total data longitudinally
                    = 2, will total data latitudinally
                    = 4, will total data vertically
             These are cumulative (e.g. TOTAL=3 will total over both 
             lat and lon, and TOTAL=7 will total over lat, lon, and 
             vertical levels to produce 1 data point).

        USE_FILEINFO -> (optional) If provided, CTM_GET_DATABLOCK will 
             restrict its search to only the files that are
             contained in USE_FILEINFO which must be a FILEINFO 
             structure array. Default is to use the global information 
             (see gamap_cmn.pro).
             If an undefined named variable is provided in USE_FILEINFO,
             it will either contain the global FILEINFO structure array 
             or the FILEINFO record of the specified file.
             USE_FILEINFO and USE_DATAINFO must be consistent, and should
             either both be used or omitted. However, it is
             possible to provide the global FILEINFO structure 
             (or nothing) with a local subset of DATAINFO.

        USE_DATAINFO -> (optional) Restrict search to records contained
             in USE_DATAINFO which must be a DATAINFO structure array. 
             If an undefined named variable is provided in USE_DATAINFO,
             it will either contain the global DATAINFO structure array 
             or all DATAINFO records of the specified file.
             See also USE_FILEINFO.

    Keywords passed to CTM_CONVERT_UNIT:
    ====================================
        UNIT -> Name of the unit that the DATA array will be converted
             to. If not specified, then no unit conversion will be done.

    Keywords passed to TVMAP or TVPLOT:
    ===================================
        NOERASE -> Do not erase previous plot.
 
        POSITION -> A four-element array of normalized coordinates
             that specifies the location of map on the plot. POSITION
             has the same form as the POSITION keyword on a plot. 
             Default is [0.1, 0.05, 0.9, 0.08]. (Passed to TVMAP).

        NCOLORS -> This is the maximum color index that will be used.

        BOTTOM -> The lowest color index of the colors to be loaded
             used in the color map and color bar.

        /NOCBAR -> If set, will not plot the colorbar below the map
             in the position specified by CBPOSITION.  Default is to
             plot a colorbar.

        CBCOLOR -> Color index of the colorbar outline and
             characters.  Defaults to BLACK (from colors_default.pro).

        CBPOSITION -> A four-element array of normalized coordinates
             that specifies the location of the colorbar. BARPOSITION 
             has the same form as the POSITION keyword on a plot. 
             Default is [0.1, 0.05, 0.9, 0.08]. 

        CBUNIT -> Passes the Unit string to COLORBAR, which will be
             plotted to the right of the color bar.  NOTE: For black
             & white contour plots, the string specified by CBUNIT
             will be plotted below the X-axis.  

        CBFORMAT -> format to use in call to colorbar. Default is I12
             if abs(max(data)) < 1e4, else e12.2 (strings get trimmed)

        COLOR  -> Color index of the map outline and title characters.  
             Defaults to BLACK (from colors_default.pro). Also used as
             plot color for 1-D (line) plots.

        MPARAM -> A 3 element vector containing values for
             [ P0Lat, P0Lon, Rot ].  Default is [ 0, 0, 0 ].

        POSITION -> A four-element array of normalized coordinates
             that specifies the location of the map.  POSITION has
             the same form as the POSITION keyword on a plot. 
             Default is [0.1, 0.1, 0.9, 0.9]. 

        TITLE -> The title string that is to be placed atop the
             map window.  

        /NOCONTINENTS -> If set, will suppress adding continent lines
             to the map.  Default is to call MAP_CONTINENTS to plot
             continent outlines or filled boundaries.

        CCOLOR -> The color index of the continent outline or fill 
             region.  Default is BLACK (from colors_default.pro).
 
        CFILL -> Value passed to FILL_CONTINENTS keyword of
             MAP_CONTINENTS.  If CFILL=1 then will fill continents
             with a solid color (as specified in CCOLOR above).  
             If CFILL=2 then will fill continents with hatching.

        /NOGRID -> If set, will suppress printing of grid lines.
             Default is to call MAP_GRID to overlay grid lines.
 
        GCOLOR -> The color index of the grid lines.
             Default is BLACK (from colors_default.pro)

        /NOGLABELS -> Will suppres printing of labels for each grid
             line in TVMAP.PRO.  Default is to print grid labels
             for each grid line.

        /NOISOTROPIC -> Will suppress plotting of an isotropic map
             (i.e. one with the same X and Y scale).  Default is to 
             print an isotropic map.
  
        /CONTOUR -> Will produce a line-contour map instead of the 
             default color-pixel image map.

        /FCONTOUR -> Will produce a filled contour map instead
             of the default color-pixel image map. If you find
             that one or more color bands are not filled properly, 
             try the /CELL_FILL keyword. This is a known IDL precularity.

        C_LEVELS -> Vector containing the contour levels.  If not
             specified, TVMAP will use quasi-logarithmic levels.

        C_COLORS -> Index array of color levels for each line (or
             each fill section) of the contour map.  If not
             specified, TVMAP will select default colors from the 
             colortable.

        C_ANNOTATION -> Vector containing the contour labels.
             Default is to use string representations of C_LEVELS.

        C_FORMAT -> Format string used in converting C_LEVELS to
             the default C_ANNOTATION values.  Default is '(f8.1)'.

        C_LABELS -> Specifies which contour levels should be labeled.
             By default, every other contour level is labeled.  C_LABELS 
             allows you to override this default and explicitly
             specify the levels to label. This parameter is a vector, 
             converted to integer type if necessary.  If the LEVELS 
             keyword is specified, the elements of C_LABELS
             correspond directly to the levels specified, otherwise, 
             they correspond to the default levels chosen by the 
             CONTOUR procedure. Setting an element of the vector to 
             zero causes that contour label to not be labeled.  A
             nonzero value forces labeling. 

             NOTE: If C_LABELS is given as a scalar, then it will be
             expanded to a vector with all elements having the same value.

        /C_LINES -> Will overplot a filled-contour map with contour lines
             and labels instead of plotting a colorbar. This was the old
             default behaviour but has been changed with the advent of
             "discrete" colorbars. The old NOLINES keyword is kept
             for compatibility reasons but doesn't do anything.

        /NOLABELS -> Will suppress printing contour labels on both
             line-contour and filled-contour maps.

        OVERLAYCOLOR -> Color of the solid lines that will be
             overlaid atop a filled contour map.  Default is BLACK.

        /OVERPLOT -> Add an additional line plot to an existing one.
             You should specify LINE=n and/or COLOR=n to distinguish 
             between curves in this case. You can manually add a legend
             with legend.pro after the plot(s) are produced.
             Note that the title string will contain information on 
             your first selection only. Use an explicit TITLE for 
             best results.

        /SAMPLE -> Will cause REBIN (in TVMAP) to use nearest-
             neighbor sampling rather than bilinear interpolation.

        /LOG -> Will create a color-pixel plot with logarithmic
             scaling.  /LOG has no effect on line-contour or
             filled-contour plots, since the default contour levels
             are quasi-logarithmic.

        /POLAR -> Create a polar plot. Note that the longitude range must 
             be -180..180 and the latitude range must extend to one pole
             but not straddle the equator.


    Keywords passed to ISOPLETH_MAP:
    ================================
        ISOPLETH -> Value for which a 3-D isosurface will be computed.
             ISOPLETH_MAP assigns a default value of 35.0.  


    Other Keywords:
    ===============
        USTR -> Unit string to be plotted to the right of the colorbar.  
             If not specified, then CTM_PLOT  will construct a unit 
             string based on the value of TRACERINFO.UNIT.
             NOTE: USTR is a synonym for the keyword CBUNIT, which
             specifies the color bar unit string.

        THISDATAINFO -> Returns to the calling program the THISDATAINFO
             structure obtained by CTM_GET_DATABLOCK.

        LABELSTRU -> Returns to the calling program the structure
             of label information obtained by CTM_LABEL.
 
        YRANGE -> range of y values for color scaling (default:
             scale each plot seperately with data min and max)

        X_FORMAT, Y_FORMAT (optional) -> Specifies the format string
             (e.g. '(f10.3)', '(e14.2)' ) for the X and Y axes, when
             making line plots.  If omitted, CTM_PLOT will call
             GET_DEFAULTFORMAT to compute default format strings. 

        RESULT -> A named variable will contain the data subset that was
             plotted together with the X and/or Y coordinates in a structure.
             For 1D plots, either X or Y are -1. 3D visualization returns
             a structure including the Z coordinate.

        _EXTRA=e -> Picks up extra keywords for CTM_GET_DATABLOCK,
             CTM_LABEL, TVMAP, and TVPLOT.

 OUTPUTS:
        None

 SUBROUTINES:
        External Subroutines Required:
        ===========================================================
        CTM_DRAW_CUBE                  CONVERT_LON
        CTM_TRACERINFO                 CTM_CONVERT_UNIT
        TVMAP                          TVPLOT
        CHKSTRU           (function)   MYCT_DEFAULTS     (function)
        CTM_GET_DATABLOCK (function)   CTM_LABEL         (function) 
        REPLACE_TOKEN     (function)   CTM_BOXSIZE       (function)   
        GET_DEFAULTFORMAT (function)   GAMAP_CMN     (include file)   

        
 REQUIREMENTS:
        Also assumes colortable has been loaded with "myct.pro". 

 NOTES:
        (1) Some keywords are saved in local variables with 
        slightly different names (e.g. MCONTOUR for /CONTOUR) 
        to prevent confusion with routine names and/or keywords
        that are picked up by the _EXTRA=e facility.

        (2) Not every possible combination of keywords has been thoroghly 
        tested. *PLEASE* report reproducible errors to mgs@io.harvard.edu!!

        (3) As of 11/17/98, CTM_PLOT can only produce X-Y plots with
        either PRESSURE or ALTITUDE along the left Y-Axis.  The right
        Y-Axis is left disabled (but will fix that later on...) 

        (4) Now define X-axis labels for longitude.  The labels are
        defined correctly for data blocks that span the date line.

 EXAMPLE:
        (0)
        CTM_PLOT
             ; To plot an ozone surface map (default) of a 
             ; user-selected file

        (1)
        FileName = '~/terra/CTM4/run_code/ctm.pch.sep1'
        CTM_PLOT, 22, 1, FileName=FileName, Lev=[1,14], $
           Total=4, /NoErase 

             ; Plots vertically-summed map for tracer 1 of ND22
             ; (J-Values map).  Will erase screen before plotting map.

        (2)
        CTM_PLOT, 'JV-MAP-$', 1, FileName=FileName, Lev=[1,14], $
           Total=4, /NoErase 

             ; Same as above, but uses category name instead of 
             ; diagnostic number.
 

 MODIFICATION HISTORY:
        bmy, 21 Sep 1998: VERSION 1.00
        bmy, 22 Sep 1998: VERSION 1.01
                          - added AVERAGE and TOTAL keywords
        bmy, 22 Sep 1998: VERSION 1.10
                          - Modified for use with new versions of
                            CTM_GET_DATABLOCK, CTM_EXTRACT,
                            CTM_LABEL, REPLACE_TOKEN, and TVMAP
        bmy, 25 Sep 1998: VERSION 1.11
                          - modified for TVMAP v. 2.0
        bmy, 28 Sep 1998: VERSION 2.00
                          - modified for TVMAP v. 2.01
                          - renamed LONSHIFT to LSHIFT
        bmy, 29 Sep 1998: - added ALTRANGE and PRANGE keywords
                            (which had been previously omitted)
        bmy, 30 Sep 1998: VERSION 2.01
                          - added call to CTM_CONVERT_UNIT
                          - added LABELSTRU keyword 
        bmy, 07 Oct 1998  VERSION 2.02
                          - now works with TVMAP 3.0
                          - added /CONTOUR, /FCONTOUR, and 
                            /COLORBAR keywords
                          - removed I/O error handling (that 
                            is already done in CTM_GET_DATABLOCK)
        bmy, 08 Oct 1998: VERSION 2.03
                          - now works with CTM_GET_DATABLOCK v. 1.03
                            and CTM_EXTRACT v. 1.04
                          - added DATA and THISDATAINFO keywords so
                            that an external data block can be
                            passed.
                          - another bug fix for UNITSTR
        bmy, 03 Nov 1998: VERSION 2.04
                          - works with new CTM_GET_DATA, 
                            CTM_GET_DATABLOCK and CTM_LABEL routines
                          - Now pass the FILEINFO and DATAINFO
                            structures via USE_FILEINFO and
                            USE_DATAINFO keywords
                          - removed DATA keyword   
                          - changed %NAME% token to %TRACERNAME%
                          - Now can pass an explicit unit string
                            via the USTR keyword
        mgs, 10 Nov 1998: - adapted for use with new CTM_GET_DATABLOCK
                          - changed keyword Erase to NoErase
                          - defaults set to produce an OX surface map
                            from IJ-AVG-$ diagnostics 
                          - allow for vertical cross section plots
                            (interface to TVPLOT) : ** still needs work! **
                          - changed CBAR to NOCBAR
        bmy, 12 Nov 1998: - TRACER is now a keyword instead of
                            an argument
                          - Changed keyword CONTINENTS to
                            NOCONTINENTS and GRID to NOGRID
                          - added NOISOTROPIC, SAMPLE and
                            keywords
        bmy, 13 Nov 1998: - VERSION 3.00
                          - ***** RENAMED to CTM_PLOT *****
                          - updated documentation header
                          - renamed C_LABELS to C_ANNOTATION to
                            prevent keyword name confusion
                          - added NOLINES, NOLABELS, C_LABELS,
                            and OVERLAYCOLOR keywords for tvmap
                          - now gets default colors from 
                            DEFAULT_COLORS.PRO
                          - Error checking for LIMIT keyword
                            (OK for now...fix this later on...)
        bmy, 16 Nov 1998: - Now use %DATE% instead of %YMD1% for
                            all default plot titles
                          - now enhanced for TVPLOT v. 2.0
                          - now only convert units for a tracer 
                            if the default unit is different from
                            the desired unit!!
        bmy, 17 Nov 1998: - added /PRESSURE keyword to plot pressure
                            instead of altitude on the left Y-axis
        mgs, 17 Nov 1998: - messed around quite a bit, because of 
                            (unfortunate) changes in default_range !@#$!@
                          - added CBFormat keyword
        bmy, 23 Nov 1998: - eliminated %SCALE% token from UNITSTR,
                            to be consistent with the latest
                            upgrade to COLORBAR.PRO. 
                          - now pass SECONDS to CTM_CONVERT_UNIT
        bmy, 13 Jan 1999: - add support for line plots.  Also, if
                            the DATA array is averaged down to a
                            single point, will print the value of
                            that point and exit.
                          - use NEWXTITLE and NEWYTITLE as token-replaced
                            strings for XTITLE and YTITLE
        bmy, 15 Jan 1999: - add support for 3-D visualization plots
                          - added unit string for contour plots
                          - now place CTM_LABEL call after the case
                            statement for PLOTTYPE, so that we can
                            suppress printing of special characters
                            in plot titles.
        bmy, 19 Jan 1999: - improve 0-D output
                          - fixed [XY]Titles for line plots
                          - "unitless" is now a unit string option
                          - now use new default color names from
                            DEFAULT_COLORS.PRO
        bmy, 20 Jan 1999: - Updated comments
        mgs, 22 Jan 1999: - couple bug fixes, some code cleaning
                          - added OverPlot keyword to allow multiple
                            line plots
        bmy, 19 Feb 1999: - now pass DEBUG (from GAMAP_CMN) to 
                            CTM_GET_DATABLOCK via DEBUG keyword
                          - Rename XIND, YIND, ZIND keywords to
                            XMID, YMID, ZMID, in call to CTM_GET_DATABLOCK
        bmy, 23 Feb 1999: - Add XTICKNAME, XTICKS, XTICKV in call to
                            TVPLOT...fix for map regions smaller than 
                            the globe
                          - bug fix.../NOGRID was listed as GRID!!!
                          - added keyword /NOGLABELS, which
                            suppresses grid line labels in MAP_SET 
                          - updated comments
        bmy, 26 Feb 1999: - now calls MAP_LABELS to get latitude labels
                            for X, XZ, Y, YZ plot types.
                          - updated comments
        bmy, 04 Mar 1999: - now pass DEBUG keyword to TVMAP
                          - now use GRIDINFO.XEDGE, GRIDINFO.YEDGE
                            to compute the LIMIT keyword for MAP_SET
        mgs, 18 Mar 1999: - minor cleaning
        mgs, 23 Mar 1999: - added ILun to keyword list to prevent retrieval
                            of two otherwise identical records from two
                            different files
        bmy, 25 Mar 1999: - now line plots use MULTIPANEL
                          - if NPANELS >=2 then place the plot title
                            higher above the window, to allow for 
                            carriage-returned lines
                            for X, Y, Z, XY, XZ, YZ plots
        mgs, 25 Mar 1999: - no unit conversion if not necessary
                          - small fix to allow for 2D fields (e.g. EPTOMS)
        bmy, 14 Apr 1999: - now prints unit string at lower right of
                            XZ or YZ plots, if the colorbar is not
                            plotted
        bmy, 26 Apr 1999: - rename YRANGE to YYRANGE internally, so as
                            to avoid confusion with YRANGE plot keywords   
        mgs, 19 May 1999: - removed a few too explicit keyword settings
                            for 1D plots and fixed OverPlot option.
                            Now stores !X, !Y, and !P from last 1D plot
                            in a local common block.
        mgs, 21 May 1999: - restore !X, !Y, and !P at the end of each
                            1-D plot to allow overplotting of data.
        mgs, 25 May 1999: - needed to mess around with lonrange to get
                            it right.
        mgs & bmy, 26 May 1999: - added POLAR keyword
        bmy, 27 May 1999: - bug fix: CBUnit keyword wasn't honored
                          - neither was NoIsotropic
        mgs, 27 May 1999: - changed default behaviour for filled contours:
                            now plots no lines and colorbar. Keyword
                            NoLines changed to C_Lines.
        mgs, 28 May 1999: - added RESULT keyword to return data as plotted
                          - bug fix with wrapping round data: shouldn't be
                            done for vertical cross sections.
        mgs, 02 Jun 1999: - small bug fix for 0D results.
        mgs, bmy 03 Jun 1999: - removed "Unit:" from output
        bmy, 07 Jul 1999: - added PLOTCSFAC scale factor for multipanel
                            plots
                          - small fixes for line plots
        bmy, 02 Nov 1999: GAMAP VERSION 1.44
                          - return if THISDATAINFO contains
                            information for more than one data block
        bmy, 24 Nov 1999: - now pass _EXTRA=e to CTM_TRACERINFO
                            so that /SMALLCHEM will be passed
        bmy, 13 Dec 1999: - if GRIDINFO is undefined after returning from
                            CTM_GET_DATABLOCK, rebuild it w/ CTM_TYPE
        bmy, 03 Feb 2000: GAMAP VERSION 1.45
                          - NOTE: /INDEX does not work with lon range
                            shifting anymore.  Will fix later.
                          - also make sure LON, LAT have two elements 
                          - added X_FORMAT, Y_FORMAT keywords for line plots
                          - updated comments 
        bmy, 06 Apr 2000: - bug fix: restrict X or Y axis range for line
                            plots using the value passed from YYRANGE.
                          - cosmetic changes, updated comments
        bmy, 23 Jan 2001: GAMAP VERSION 1.47
                          - now call "isopleth_map.pro" to plot a 3-D
                            isosurface.  3-D visualization via
                            routine "ctm_draw_cube.pro" is obsolete.
                          - added ISOPLETH keyword as pass-thru to 
                            ISOPLETH_MAP
        bmy, 23 Jul 2001: GAMAP VERSION 1.48
                          - replaced call to DEFAULT_COLORS with 
                            call to MYCT_DEFAULTS() to specify
                            MYCT color table information
                          - deleted obsolete code from 1998 and 1999
        bmy, 09 Aug 2001: - bug fix: remove reference to BLACK from
                            the old "default_colors.pro"
        bmy, 24 May 2002: GAMAP VERSION 1.50
                          - Now use SI unit hPa instead of mb in axis titles
                          - delete obsolete, commented-out code
        bmy, 28 Sep 2002: GAMAP VERSION 1.51
                          - now get default NCOLORS, BOTTOM, BLACK values
                            from !MYCT system variable instead of from
                            the MYCT_DEFAULTS function
        bmy, 16 Apr 2004: GAMAP VERSION 2.02
                          - Also need to convert the units of YYRANGE
                            accordingly so that /AUTORANGE will work
        bmy, 16 Jun 2004: - Bug fix: if we do unit conversion, do not
                            let the converted value of YRANGE get
                            passed back to the main program
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - Modified for GEOS-5 fields that are
                            defined on level edges
        phs, 19 Mar 2008: GAMAP VERSION 2.12
                          - Bug fix for working with new map_labels
        phs, 02 Apr 2008: - Bug fix for XZ and YZ pixel plots

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_plot.pro)


CTM_PLOTDIFF

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_PLOTDIFF

 PURPOSE:
        Prints a lat-lon map of 2 CTM fields, their absolute difference, 
        and their percent difference.  This is a quick way of ensuring 
        that two model versions are producing identical results.

        The page will contain the following plot panels:

             Panel #1               Panel #2
             Data Block D1          Data Block D2

             Panel #3               Panel #4
             Abs Diff (D2 - D1)     % Diff (D2 - D1)

 CATEGORY:
        GAMAP Utilities, GAMAP Plotting

 CALLING SEQUENCE:
        CTM_PLOTDIFF, DIAGN, FILE1, FILE2 [, Keywords ]

 INPUTS:
        DIAGN -> A diagnostic number or category to restrict
             the record selection (default is: "IJ-AVG-$"). 

        FILE1 -> Name of the first CTM output file.  If FILE1
             is not given, or if it contains wildcard characters
             (e.g. "*"), then the user will be prompted to supply
             a file name via a pickfile dialog box.

        FILE2 ->  Name of the second CTM output file.  If FILE2
             is not given, or if it contains wildcard characters
             (e.g. "*"), then the user will be prompted to supply
             a file name via a pickfile dialog box.

 KEYWORD PARAMETERS:


        LON -> A 2-element vector specifying the longitude range that
             will be used to make the plot.  Default is [-180,180].

        LAT -> A 2-element vector specifying the latitude range that
             will be used to make the plot.  Default is [-88,88].

        LEV -> A scalar or 2-element vector which specifies the
             level(s) that will be used to make the plot.  Default
             is [ 1, 1 ].

        /PS -> Set this switch to print to a PostScript file.
 
        OUTFILENAME -> Name of the PostScript file if the /PS option 
             is set.  Default is "idl.ps".

        TRACER -> Tracer number(s) for which differences will be plotted.  

        TAU0 -> TAU value(s) (hours since 0 GMT 1 Jan 1985) at the start
             of the diagnostic data block to plot.

        DIVISIONS -> Specifies the number of colorbar divisions for 
             the quantity plot (Panels #1 and #2).  Default is 5.
             NOTE: The optimal # of divisions is !MYCT.NCOLORS/2 +1.

        DATARANGE -> Allows you to manually specify the min and max
             values of the data that will appear on the plot (Panels
             # 1 and #2).  The default is to automatically compute
             the overall min and max of both data blocks.

        MIN_VALID -> Specifies the minimum valid data for the plot. 
             Data lower than MIN_VALID will be rendered with color
             !MYCT.WHITE.  For example, MIN_VALID is useful for
             plotting emissions which only occur on land.

        DIFFDIV -> Specifies the number of colorbar divisions for 
             the difference plots (Panels #3 and #4).  Default is 8.
             NOTE: The optimal # of divisions is !MYCT.NCOLORS/2 +1.

        DIFFNCOLORS -> Sets the # of colors used to create the
             difference plots (Panels #3 and #4).  Default is 13.

        DIFFRANGE -> Allows you to manually specify the min and max
             values that will appear on the absolute difference
             plot (Panel #3).  Default is to use the dynamic range of
             the absolute difference data (symmetric around zero).

        /NODEVICE -> set to not call open_device, so you can do it
             from outside

        /NOMULTIPANEL -> set to not call multipanel, so you can do it
             from outside

        PCRANGE -> Allows you to manually specify the min and max
             values that will appear on the percentage difference
             plot (Panel #4).  Default is to use the dynamic range of
             the percentage difference data (symmetric around zero).

        PCDIV -> number of ticks in the %-Diff colorbar

        PCNCOLORS -> number of colors for the %-Diff plot

        T1, T2, DIFFTITLE -> allows you to overwrite the default
             title for the 1st, 2nd and DIff plots.


        _EXTRA=e -> Picks up extra keywords for CTM_DIFF,
             OPEN_DEVICE, and MYCT


   Keywords for the MASK feature:
   ------------------------------
        /MASK -> set to mask with a green color boxes where %-diff
             and/or diff are below some threshold. The absolute value
             of the % is plot.

	 PC_THR, DIFF_THR : the %-Diff and Diff THResholds to mask data in the
             4th plot if /MASK is set. Boxes with %-Diff or/and Diff
             below the THResholds are masked. Default values are 1%
             and 1e4.

        /ZAP -> set to skip all plots if /MASK is set and all boxes
             are masked.


 OUTPUTS:
        none

 SUBROUTINES:
        External Subroutines Required:
        =======================================================
        CHKSTRU     (function)    CLOSE_DEVICE 
        CTM_CLEANUP               COLORBAR_NDIV     (function)
        CTM_DIFF                  CTM_GET_DATABLOCK (function) 
        IS_DEFINED   (function)   EXTRACT_FILENAME  (function) 
        MULTIPANEL                OPEN_DEVICE
        

 REQUIREMENTS:
        None

 NOTES:
        (1) CTM_PLOTDIFF calls CTM_CLEANUP each time to remove
            previously read datablock info from the GAMAP common
            block.

        (2) The default TAU0 value is 0, and is not suitable if your 
            run has no output for 0 GMT 1 Jan 1985! You may have to 
            gather tau0 before running and crashing CTM_PLOTDIFF.

 EXAMPLE:
        FILE1 = 'ctm.bpch.v4-30'
        FILE2 = 'ctm.bpch.v4-31'
        CTM_PLOTDIFF, 'IJ-AVG-$', FILE1, FILE2, TRACER=1

             ; Creates 4-panel plot w/ old data, new data,
             ; new - old (abs diff), and new - old (% diff).

 MODIFICATION HISTORY:
        bmy, 17 Apr 2002: GAMAP VERSION 1.50
        bmy, 17 Jul 2002: GAMAP VERSION 1.51
                          - added TAU0 keyword
        bmy, 16 Dec 2002: GAMAP VERSION 1.52
                          - now can handle 2 different tracer numbers
                          - now can handle 2 different TAU0 values
        bmy, 29 Jan 2004: GAMAP VERSION 2.01
                          - Now pass LEV keyword to CTM_DIFF
                          - Now plot both DATA1 and DATA2 on
                            the same scale for easier comparison
        bmy, 16 Feb 2005: GAMAP VERSION 2.03
                          - Now use /QUIET and /NOPRINT keywords in
                            CTM_GET_DATA and CTM_GET_DATABLOCK to
                            suppress screen output
        phs, 24 Oct 2006: GAMAP VERSION 2.05
                          - Now use YRANGE if it is passed.  
                          - Also use DIFFRANGE (for range of the 
                            abs difference plot) if it is passed.
                          - Now use PCRANGE (for range of the
                            %age difference plot) if it is passed.
        bmy, 15 Nov 2006: GAMAP VERSION 2.06
                          - Now use blue-white-red color table
                            for abs diff and % diff plots
  bmy & phs, 04 Oct 2007: GAMAP VERSION 2.10
                          - Added DIVISIONS keyword (default=5) 
                          - Now make the default DIFFRANGE and
                            PCRANGE symmetric around zero
                          - Added DIFFDIV, DIFFNCOLORS keywords
                          - Also restore original !MYCT structure
                          - restore initial Color Table and !MyCt,
                            and return, when crashes.
                          - Now skip plotting % difference if
                            DATA1 is zero everywhere
                          - Add error trapping with CATCH
        bmy, 16 Jan 2008: GAMAP VERSION 2.12
                          - add _EXTRA=e to calls to CTM_PLOT, in order
                            to pass extra variables to that routine
        phs, 31 Jan 2008: - Add NODEVICE keyword, so device (like PS
                            file) can be open outside this routine,
                            allowing for multiple pages in a PS file
                            for example.
                          - Clipping of percentage difference range
                            is indicated with triangle.
        phs, 25 Feb 2008: - Improved error catcher
        bmy, 05 Nov 2008: GAMAP VERSION 2.13
                          - Renamed YRANGE keyword to DATARANGE in
                            order to avoid confusion with nested grids
        phs, 22 Sep 2009: - more flexible call to MYCT for diff
                            plots, so it can be overwriten from
                            caller
                          - Can select number of colors and divisions
                            for %-diff plot
                          - Can overwrite titles
                          - Can set Multipanel from outside in caller
                          - Can MASK data according to both Diff and
                            %-Diff values, in the 4th plot
        bmy, 29 Jan 2010: GAMAP VERSION 2.14
                          - Minor fix in IF statement to prevent code
                            from dying after call to CTM_DIFF.
                          

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_plotdiff.pro)


CTM_PLOTDIFF4

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_PLOTDIFF4

 PURPOSE:
        Prints a lat-lon map of 2 CTM fields, their absolute difference, 
        and their percent difference.  This is a quick way of ensuring 
        that two model versions are producing identical results.

        The page will contain the following plot panels:

             Panel #1               Panel #2
             Data Block D1          Data Block D2

             Panel #3               Panel #4
             Abs Diff (D2 - D1)     % Diff (D2 - D1) / D1

        CTM_PLOTDIFF4 is a lighter version of CTM_PLOTDIFF, and does
        not use CTM_DIFF as an intermediary routine. 

 CATEGORY:
        GAMAP Utilities, GAMAP Plotting

 CALLING SEQUENCE:
        CTM_PLOTDIFF4, DIAGN, FILE2, FILE2 [, Keywords ]

 INPUTS:
        DIAGN -> A diagnostic number or category to restrict
             the record selection (default is: "IJ-AVG-$"). 

        FILE1 -> Name of the first CTM output file.  If FILE1
             is not given, or if it contains wildcard characters
             (e.g. "*"), then the user will be prompted to supply
             a file name via a pickfile dialog box.

        FILE2 ->  Name of the second CTM output file.  If FILE2
             is not given, or if it contains wildcard characters
             (e.g. "*"), then the user will be prompted to supply
             a file name via a pickfile dialog box.

 KEYWORD PARAMETERS:

        LON -> A 2-element vector specifying the longitude range that
             will be used to make the plot.  Default is [-180,180].

        LAT -> A 2-element vector specifying the latitude range that
             will be used to make the plot.  Default is [-88,88].

        LEV -> A scalar or 2-element vector which specifies the
             level(s) that will be used to make the plot.  Default
             is [ 1, 1 ].

        /PS -> Set this switch to print to a PostScript file.
 
        OUTFILENAME -> Name of the PostScript file if the /PS option 
             is set.  Default is "idl.ps".

        TRACER -> A scalar or 2-element vector which specifies the
             tracer number(s) for each data block.  

        TAU0 -> A scalar or 2-element vector which specifies the
             TAU value(s) (hours since 0 GMT 1 Jan 1985) by which
             each data block is timestamped.

        DIVISIONS -> Specifies the number of colorbar divisions for 
             the quantity plot (Panels #1 and #2).  Default is 5.
             NOTE: The optimal # of divisions is !MYCT.NCOLORS/2 +1.

        DATARANGE -> Allows you to manually specify the min and max
             values of the data that will appear on the plot (Panels
             # 1 and #2).  The default is to automatically compute
             the overall min and max of both data blocks.

        MIN_VALID -> Specifies the minimum valid data for the plot. 
             Data lower than MIN_VALID will be rendered with color
             !MYCT.WHITE.  For example, MIN_VALID is useful for
             plotting emissions which only occur on land.

        DIFFDIV -> Specifies the number of colorbar divisions for 
             the difference plots (Panels #3 and #4).  Default is 8.
             NOTE: The optimal # of divisions is !MYCT.NCOLORS/2 +1.

        DIFFNCOLORS -> Sets the # of colors used to create the
             difference plots (Panels #3 and #4).  Default is 13.

        DIFFRANGE -> Allows you to manually specify the min and max
             values that will appear on the absolute difference
             plot (Panel #3).  Default is to use the dynamic range of
             the absolute difference data (symmetric around zero).

        /NODEVICE -> set to not call open_device, so you can do it
             from outside

        /NOMULTIPANEL -> set to not call multipanel, so you can do it
             from outside

        PCRANGE -> Allows you to manually specify the min and max
             values that will appear on the percentage difference
             plot (Panel #4).  Default is to use the dynamic range of
             the percentage difference data (symmetric around zero).

        PCDIV -> number of ticks in the %-Diff colorbar

        PCNCOLORS -> number of colors for the %-Diff plot

        TITLE_1 -> Allows you to override the default plot title for
             the first data block (1st plot panel).

        TITLE_1 -> Allows you to override the default plot title for
             the 2nd data block (2nd plot panel).

        DIFFTITLE -> Allows you to override the default plot title for
             the absolute difference plot (3rd plot panel).

        PCTITLE -> Allows you to override the default plot title for
             the percent difference plot (4th plot panel).

        _EXTRA=e -> Picks up extra keywords for CTM_DIFF,
             OPEN_DEVICE, and MYCT


   Keywords for the MASK feature:
   ------------------------------
        /MASK -> set to mask with a green color boxes where %-diff
             and/or diff are below some threshold. The absolute value
             of the % is plot.

	 PC_THR, DIFF_THR : the %-Diff and Diff THResholds to mask
	      data in the 4th plot (percent difference) if /MASK is
	      set.  Boxes with %-Diff or/and Diff below the THResholds
	      are masked. Default values are 1% and 1e4.

        /ZAP -> set to skip all plots if /MASK is set and all boxes
             are masked.;

 OUTPUTS:
        None

 SUBROUTINES:
        External Subroutines Required:
        ==========================================================
        CHKSTRU          (function)  CLOSE_DEVICE
        COLORBAR_NDIV    (function)  CTM_GET_DATABLOCK (function)
        EXTRACT_FILENAME (function)  MULTIPANEL                
        MYCT                         OPEN_DEVICE               
        TVMAP                        UNDEFINE

 REQUIREMENTS:
        Requires routines from the GAMAP package.

 NOTES:
        (1) When plotting a subset of the globe, CTM_PLOTDIFF4
            properly sets the colorbar ranges for the abs diff
            and percent diff plots.  This was an issue in the
            older CTM_PLOTDIFF.

        (2) Longitude and latitude ranges specified by LON and LAT
            will be applied to both data blocks.  

 EXAMPLE:
         CTM_PLOTDIFF4, 'IJ-AVG-$',                      $
                        'v8-03-02.bpch', 'v9-01-01.bpch, $
                        TRACER=6,      LEVEL=1,          $
                        LON=[-90,-30], LAT=[30,15]
 
             ; Creates a 4-panel difference plot for ISOPRENE
             ; (IJ-AVG-$, tracer #6) at the surface for the Amazon
             ; basin region from data in 2 different model versions.

 MODIFICATION HISTORY:
        bmy, 16 May 2011: VERSION 1.00
        bmy, 13 Jan 2014: GAMAP VERSION 2.17
                          - Bug fix: For 2-D data blocks that lack the  
                            GRIDINFO.ZMID tag name, display the altitude
                            of the data as 0.0 km.

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_plotdiff4.pro)


CTM_PLOTRATIO

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_PLOTRATIO

 PURPOSE:
        Plots the ratio of two CTM data fields.  This is one way
        to see if two model versions produce identical results.

 CATEGORY:
        GAMAP Utilities, GAMAP Plotting

 CALLING SEQUENCE:
        CTM_PLOTRATIO, DIAGN [, Keywords ]

 INPUTS:
        DIAGN -> A diagnostic number or category to restrict
             the record selection.  Default is "IJ-AVG-$". 

 KEYWORD PARAMETERS:
        FILE1 -> Name of the first CTM output file (containing the
             "old" data).  If FILE1 is not given, or if it contains 
             wildcard characters (e.g. "*"), then the user will be 
             prompted to supply a file name via a pickfile dialog box.

        FILE2 ->  Name of the second CTM output file.  If FILE2
             is not given, or if it contains wildcard characters
             (e.g. "*"), then the user will be prompted to supply
             a file name via a pickfile dialog box.

        LON -> A 2-element vector specifying the longitude range that
             will be used to make the plot.  Default is [-180,180].

        LAT -> A 2-element vector specifying the latitude range that
             will be used to make the plot.  Default is [-88,88].

        LEV -> Vertical level for which to plot data.  Default is 1.

        TITLE -> Title string for the plot.  If not specified, a
             generic title string will be generated.

        TRACER -> Number of the tracer for which differences
             will be plotted.  Default is 1.

        _EXTRA=e -> Picks up extra keywords for CTM_DIFF.

 OUTPUTS:
        None

 SUBROUTINES:
        External Subroutines Required:
        ==========================================
        CTM_CLEANUP   CTM_GET_DATABLOCK (function)
        CTM_DIFF      EXTRACT_FILENAME  (function)
        OPEN_DEVICE   CLOSE_DEVICE
        MULTIPANEL

 REQUIREMENTS:
        None

 NOTES:
        (1) The ratio plotted will be DATA2 / DATA1, where DATA2
            is contained in FILE2, and DATA1 is contained in FILE1.

        (2) For places where DATA1 = 0, DATA2 will also be set to 0.
            This avoids division by zero errors.

        (3) CTM_PLOTRATIO calls CTM_CLEANUP each time to remove
            previously read datablock info from the GAMAP common
            block.

 EXAMPLE:
        FILE1 = 'ctm.bpch.v4-30'
        FILE2 = 'ctm.bpch.v4-31'
        CTM_PLOTRATIO, 'IJ-AVG-$', $
             FILE1=FILE1, FILE2=FILE2, TRACER=1, LEV=1

             ; Plots the ratio of NOx data at the surface:
             ;   ctm.bpch.v4-31 / ctm.bpch.v4-30

 MODIFICATION HISTORY:
        bmy, 24 Apr 2002: GAMAP VERSION 1.50
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_plotratio.pro)


CTM_PLOT_TIMESERIES

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_PLOT_TIMESERIES

 PURPOSE:
        Plots station timeseries data (e.g. from the GEOS-CHEM
        ND48 diagnostic) contained in binary punch file format.
        %%%% MAY NEED UPDATING %%%%%

 CATEGORY:
        GAMAP Utilities, GAMAP Plotting

 CALLING SEQUENCE:
        CTM_PLOT_TIMESERIES, CATEGORY [ , Keywords ] 

 INPUTS:
        CATEGORY -> The diagnostic number (e.g. ND22, ND45, etc or 
             category name (e.g. "JV-MAP-$", "IJ-AVG-$") for which to 
             read data from the punch file. 

 KEYWORD PARAMETERS:
        BOTTOM -> The lowest color index of the colors to be loaded
             used in the color map and color bar.  The default is
             to use the value in system variable !MYCT.BOTTOM.

        COLOR -> Color of the plot window and/or data.  The default
             is to use the system variable !MYCT.BLACK.

        LABELSTRU -> Returns to the calling program the structure
             of label information obtained by CTM_LABEL.

        LEV -> An index array of sigma levels *OR* a two-element
             vector specifying the min and max sigma levels to be 
             included in the plot.  Default is [ 1, GRIDINFO.LMX ].
 
        OVERPLOT -> Plot data atop the previous plot window, instead
             of erasing the screen and plotting in a new window.

        RESULT -> A named variable will contain the data subset that
             was plotted together with the X and/or Y coordinates in
             a  structure.  

        TITLE -> Top title string for the plot.  If not passed, 
             then a default title string will be printed.

        UNIT -> Name of the unit that the DATA array will be converted
             to. If not specified, then no unit conversion will be done.

        XTITLE -> X-Axis title string for the plot.  If not passed, 
             then a default title string will be printed.

        YTITLE -> Y-Axis title string for the plot.  If not passed, 
             then a default title string will be printed.

        YRANGE -> range of y values for color scaling (default:
             scale each plot seperately with data min and max)

        _EXTRA=e -> Picks up extra keywords for routines called
             by CTM_PLOT_TIMESERIES.

 OUTPUTS:
        None

 SUBROUTINES:
        External Subroutines Required:
        ===========================================================
        CTM_GET_DATA              CTM_INDEX           (function)
        CTM_LABEL    (function)   GETMODELANDGRIDINFO (function)
        UNDEFINE                  REPLACE_TOKEN       (function)         

 REQUIREMENTS:
        None

 NOTES:
        None

 EXAMPLE:

 MODIFICATION HISTORY:
        bmy, 16 Apr 2004: GAMAP VERSION 2.03
                          - Initial version
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_plot_timeseries.pro)


CTM_PRINTDIFF

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_PRINTDIFF

 PURPOSE:
        Prints the sum of the differences between two CTM
        output files.  This is a quick way of ensuring that
        two model versions are producing identical results.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        CTM_PRINTDIFF, DIAGN [, Keywords ]

 INPUTS:
        DIAGN -> A diagnostic number or category to restrict
             the record selection (default is: "IJ-AVG-$").        

 KEYWORD PARAMETERS:
        FILE1 -> Name of the first CTM output file (the "old" file).
             If FILE1 is not given, or if it contains wildcard 
             characters (e.g. "*"), then the user will be prompted 
             to supply a file name via a pickfile dialog box.

        FILE2 ->  Name of the second CTM output file (the "new" file).  
             If FILE2 is not given, or if it contains wildcard 
             characters (e.g. "*"), then the user will be prompted 
             to supply a file name via a pickfile dialog box.

        TRACER -> Number of the tracer for which differences
             will be plotted.

        _EXTRA=e -> Picks up other keywords for CTM_GET_DATABLOCK.

 OUTPUTS:
        Prints the quantity:

             DIFF[L] = TOTAL( DATA2[*,*,L] - DATA1[*,*,L] ) 

        for each level L.  If DIFF[L] = 0 for all levels L, then
        FILE1 and FILE2 contain identical data.

 SUBROUTINES:
        External Subroutines Required:
        ==============================
        CTM_CLEANUP
        CTM_GET_DATABLOCK (function)

 REQUIREMENTS:
        None

 NOTES:
        (1) If DATA1 corresponds to the "old" data, and DATA2
            corresponds to the "new" data, then CTM_DIFF will 
            compute the following:
         
            Abs. Diff = ( new - old )

        (2) CTM_PRINTDIFF calls CTM_CLEANUP each time to remove
            previously read datablock info from the GAMAP common
            block.

 EXAMPLE:
        FILE1 = 'ctm.bpch.v4-30'      ; the "old" file
        FILE2 = 'ctm.bpch.v4-31'      ; the "new" file
        CTM_PRINTDIFF, 'IJ-AVG-$', $
             FILE1=FILE1, FILE2=FILE2, TRACER=1

        IDL prints:
             Level:  26 Difference: -2.3841858e-07
             Level:  25 Difference:  0.0000000e+00
             Level:  24 Difference:  0.0000000e+00
             Level:  23 Difference:  0.0000000e+00
             Level:  22 Difference: -1.4901161e-08
             Level:  21 Difference:  0.0000000e+00
             Level:  20 Difference:  0.0000000e+00
             Level:  19 Difference:  0.0000000e+00
             Level:  18 Difference:  0.0000000e+00
             Level:  17 Difference:  0.0000000e+00
             Level:  16 Difference:  0.0000000e+00
             Level:  15 Difference:  0.0000000e+00
             Level:  14 Difference: -7.4505806e-09
             Level:  13 Difference:  0.0000000e+00
             Level:  12 Difference:  0.0000000e+00
             Level:  11 Difference:  0.0000000e+00
             Level:  10 Difference:  0.0000000e+00
             Level:   9 Difference:  0.0000000e+00
             Level:   8 Difference:  0.0000000e+00
             Level:   7 Difference:  0.0000000e+00
             Level:   6 Difference:  0.0000000e+00
             Level:   5 Difference:  0.0000000e+00
             Level:   4 Difference:  0.0000000e+00
             Level:   3 Difference:  0.0000000e+00
             Level:   2 Difference:  0.0000000e+00
             Level:   1 Difference:  0.0000000e+00

             ; Prints the sum of differences at each level 
             ; betweeen two GEOS-STRAT binary punch files 
             ; for NOx (tracer=1).
            
 MODIFICATION HISTORY:
        bmy, 04 Apr 2002: GAMAP VERSION 1.50
        bmy, 22 Apr 2002: - now takes diff of DATA2 - DATA1, in order
                            to be consistent with CTM_PLOTDIFF.
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_printdiff.pro)


CTM_READ_PLANEFLIGHT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_READ_PLANEFLIGHT

 PURPOSE:
        Reads GEOS-CHEM plane flight diagnostic (ND40) data.  

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        RESULT = CTM_READ_PLANEFLIGHT( FILENAME )

 INPUTS:
        FILENAME -> Name of the file containing data from the GEOS-CHEM
             plane following diagnostic ND40.  If FILENAME is omitted,
             then a dialog box will prompt the user to supply a file name.

 KEYWORD PARAMETERS:
        None

 OUTPUTS:
        RESULT -> Array of structures containing data from read from
             the input file.  Each different plane type will have 
             a structure in RESULT containing the following tags:
 
             NPOINTS  : Number of points read from the file 
             NVARS    : Number of variables read from the file
             PLATFORM : Name of plane type (e.g. DC8, P3B, FALCON)
             DATE     : Array w/ YYYYMMDD  at each flight point [GMT date]
             TIME     : Array w  HHMM      at each flight point [GMT time]
             LAT      : Array w/ latitude  at each flight point [degrees ]
             LON      : Array w/ longitude at each flight point [degrees ]   
             PRESS    : Array w/ pressure  at each flight point [hPa     ]
             VARNAMES : Array w/ names of each variable 
             DATA     : Array w/ data for each variable

 SUBROUTINES:

        External Subroutines Required:
        ==========================================
        OPEN_FILE   STRBREAK (function)  UNDEFINE

 REQUIREMENTS:
        None

 NOTES:
        We read the data into arrays first, and then save the arrays
        into an IDL structure.  If you read the data into an array of
        structures, this executes much more slowly.  Also arrays of
        structures seem to suck up an inordinate amount of memory.

 EXAMPLES:
        PLANEINFO = CTM_READ_PLANEFLIGHT( 'plane.log.20040601' )
             ; Reads data from file into the PLANEINFO structure

        DC8 = WHERE( PLANEINFO[*].PLATFORM eq 'DC801' )
             ; Look for DC8 data

        PRINT, PLANEINFO[DC8].LAT[*]
        PRINT, PLANEINFO[DC8].LON[*]
             ; Prints latitudes and longitudes of DC8 to the screen

        IND = WHERE( PLANEINFO[DC8].VARNAMES eq 'TRA_004' )
        CO  = PLANEINFO[DC8].DATA[ *, IND ]
             ; Extracts CO (tracer #4 in a GEOS-CHEM fullchem
             ; simulation) to an array

        IND  = WHERE( PLANEINFO[DC8].VARNAMES eq 'GMAO_UWND' )
        UWND = PLANEINFO[DC8].DATA[ *, IND ]
             ; Extracts U-wind information to an array 

 MODIFICATION HISTORY:
        bmy, 23 Mar 2005: GAMAP VERSION 2.03
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_read_planeflight.pro)


CTM_RESEXT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_RESEXT

 PURPOSE:
        Returns the proper filename extension for CTM resolution.

 CATEGORY:
        GAMAP Utilities, GAMAP Models & Grids

 CALLING SEQUENCE:
        RESULT = CTM_RESEXT( MODELINFO )

 INPUTS:
        MODELINFO -> a MODELINFO structure (output from function
             CTM_TYPE) desribing the desired CTM model.

 KEYWORD PARAMETERS:
        None

 OUTPUTS:
        Returns a string containing the model resolution.
        (e.g. '05x05', '1x1', '2x25', '4x5', '8x10' etc.)

 SUBROUTINES:
        External Subroutines Required:
        ==============================
        CHKSTRU (function)

 REQUIREMENTS:
        None

 NOTES:
        (1) Add more grid resolutions as is necessary.

 EXAMPLE:
        MODELINFO = CTM_TYPE( 'GEOS4' )
        PRINT, CTM_NAMEXT( MODELINFO )
             4x5

             ; Returns filename extension for the 
             ; 4x5 GEOS-4 model grid

 MODIFICATION HISTORY:
        bmy, 30 Jun 2000: GAMAP VERSION 1.46
        bmy, 08 Aug 2000: - Added string for 0.5 x 0.5
        bmy, 08 Feb 2006: GAMAP VERSION 2.04
                          - Added strings for 1.0 x 1.25 and 
                            0.5 x 0.625
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - added string for 0.5 x 0.667
        bmy, 09 Feb 2012: GAMAP VERSION 2.10
                          - Added string for 0.25 x 0.3125

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_resext.pro)


CTM_RESTART_O3

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_RESTART_O3

 PURPOSE:
        Merges single-tracer Ox data into a full-chemistry
        CTM restart file.

 CATEGORY:
        GAMAP Utilities

 CALLING SEQUENCE:
        CTM_RESTART_O3 [, BATCHFILE [, Keywords ] ]

 INPUTS:
        BATCHFILE (optional) -> Name of the input file containing
             the names of the full chemistry restart file, the
             single tracer O3 file, the annual mean tropopause file,
             and the output file.  If BATCHFILE is omitted, then the
             user will be prompted to make a selection via a dialog box.

 KEYWORD PARAMETERS:
        /STRAT_ONLY -> Set this keyword to only merge the stratospheric
             Ox into the full chemistry restart file.  Stratospheric 
             levels are determined by reading in the annual mean 
             tropopause file (as specified in BATCHFILE).  Default is
             to merge all levels into the full chemistry restart file.

 OUTPUTS:
        Will write merged data to an output file whose name is
        specified in BATCHFILE.

 SUBROUTINES:
        External subroutines required:
        ------------------------------------------------------
        CTM_GRID     (function)  CTM_GET_DATABLOCK (function)
        CTM_GET_DATA             OPEN_FILE
        STR2BYTE     (function)

 REQUIREMENTS:
        None

 NOTES:
        CTM_RESTART_O3 is currently only applicable to the GEOS-CTM,
        since this is the only model that can run single tracer Ox.

        A Sample BATCHFILE is given below.  There must be 3 header 
        lines before the first file name:

CTM_RESTART_O3.DAT -- defines filenames to read in for merging single 
                      tracer Ox data into a full chem restart file
=============================================================================
Full Chem File : /r/amalthea/N/scratch/bmy/run_3.2/gctm.trc.941001
Ox Run File    : /r/amalthea/N/scratch/bmy/run_o3_3.2/gctm.trc.941001
T-Pause File   : /r/amalthea/Li/data/ctm/GEOS_4x5/ann_mean_trop.geos1.4x5
Output File    : /scratch/bmy/gctm.trc.941001.new
=============================================================================

 EXAMPLE:
        CTM_RESTART_O3, 'filenames.dat', /STRAT_ONLY
             
             ; Will merge stratospheric single tracer Ox into the 
             ; full chemistry restart file.  Input and output file
             ; names are given in "filenames.dat".

 MODIFICATION HISTORY:
        bmy, 17 Feb 2000: VERSION 1.45
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_restart_o3.pro)


CTM_SUM

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_SUM

 PURPOSE:
        Calculate the sum of several CTM output data blocks
        and store them in a new datainfo structure as "derived 
        data".  The user can select data blocks by diagnostics,
        tracer, tau0, or logical unit of the source file.  With 
        the AVERAGE keyword averages will be computed instead of
        totals.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        CTM_SUM [, DIAGN ] [, Keywords ]

 INPUTS:
        DIAGN -> The diagnostic category name.  Default is 'IJ-AVG-$'

 KEYWORD PARAMETERS:
        TRACER -> Tracer number(s) to look for.

        TAU0 -> beginning of time step to look for. You can
            specify a date using function nymd2tau(YYMMDD,HHMMSS)

        ILUN -> If you want to restrict summation to datablocks from
            one particular file, set the ILUN keyword to the 
            respective logical unit number.  ILUN and FILENAME are
            mutually exclusive.  If you select FILENAME then ILUN 
            will be ignored.

        FILENAME -> Instead of ILUN you may pass the name of a
            CTM data file containing data blocks to be summed.
            FILENAME and ILUN are mutually exclusive.  If you 
            select FILENAME then ILUN will be ignored.

        NEWTRACER -> Tracer number for the new tracer. Default is 
            to use the same number as the tracer in the first 
            selected data block.

        NEWTAU0 -> A new pair of values for the time stamp. Default 
            is to use the minimum tau0 and maximum tau1 from the 
            selected data blocks. If only one value is passed (tau0),
            then tau1 will be set to tau0+1.

        /AVERAGE -> set this keyword to compute a (simple) average
            instead of the total.

 OUTPUTS:
        This routne produces no output but stores a new datainfo 
        and fileinfo structure into the global arrays.

 SUBROUTINES:
        uses gamap_cmn, ctm_get_data, ctm_grid, and ctm_make_datainfo

 REQUIREMENTS:
        None

 NOTES:
        All data blocks must originate from compatible models.
        No test can be made whether an identical addition had been
        performed earlier. Hence, it is a good idea to test the
        existence of the "target" record before in order to avoid 
        duplicates.

 EXAMPLE:
        (1) 
        CTM_GET_DATA, DATAINFO, 'IJ-AVG-$', $
          TRACER=1, TAU0=NYMD2TAU( 940301L )

        IF (N_ELEMENTS(DATAINFO) EQ 0) THEN $
           CTM_SUM, 'IJ-AVG-$', TRACER=[1,2,3,4,5],  $
              TAU0=NYMD2TAU(940301L), NEWTRACER=1

           ; Add individual CH3I tracers for 03/01/1994 and 
           ; store them  as total CH3I concentration. 
           ; But first: test!

        (2)
        CTM_SUM,'IJ-AVG-$',$
           TRACER=2, FILENAME='ctm.bpch.ox', /AVERAGE 
        
           ; Compute annual averages from monthly means for Ox

 MODIFICATION HISTORY:
        mgs, 18 May 1999: VERSION 1.00
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - Added FILENAME keyword as an 
                            alternative to ILUN
                          - Updated comments, cosmetic changes
        phs, 18 Aug 2008: GAMAP VERSION 2.13
                          - Added experimental keyword DIMAVER to
                            average along any dimension of the
                            datablocks.

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_sum.pro)


CTM_SUM_EMISSIONS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_SUM_EMISSIONS

 PURPOSE:
        Computes totals of emissions in Tg [or Tg C] for the
        following diagnostics: ND28, ND29, ND32, ND36, ND46, ND13, etc.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        CTM_SUM_EMISSIONS, DIAGN [, Keywords ]

 INPUTS:
        DIAGN -> A diagnostic category name to restrict 
             the record selection (default is "ANTHSRCE").

 KEYWORD PARAMETERS:
        FILENAME -> Punch file (ASCII or Binary) from which to 
             read CTM emissions data.  If omitted, the user
             will be prompted to select a file via a dialog box.

        FORMAT -> To overwrite the default format to output the
             sum.

        TRACER -> The tracer number (or a 1-D array of tracer
             numbers) to compute emission totals for.

        /CUM_ONLY -> If this switch is set, SUM_EMISSIONS will
             only print out cumuluative totals (and skip individual
             totals for each data block).

        RESULT -> An array of structures (tag names: NAME, SUM, UNIT) 
             that returns, the name of each tracer, its cumulative
             total, and its unit to the calling program.
           
        /NO_SECONDS -> Set this switch if the data to be summed is
             independent of seconds (e.g. molec/cm2).  CTM_SUM_EMISSIONS
             will not multiply the data by the number of seconds in the 
             interval when converting to Tg.

        /KG -> Set this switch if the data to be summed is in kg
             instead of molec/cm2 or molec/cm2/s.  CTM_SUM_EMISSIONS
             will not multiply the data by the surface area of each
             grid box when converting to Tg.

        /TO_Mg -> Set this switch if you wish to display emissions
             totals in Mg instead of Tg.

        /TO_Gg -> Set this switch if you wish to display emissions
             totals in Gg instead of Tg.

        /SHORT -> Use a shorter output format to print totals.
             Default is to print out w/ the long output format.

        _EXTRA=e -> Picks up any extra keywords for CTM_GET_DATA
             or CTM_TRACERINFO.
 
 OUTPUTS:
        Prints totals in Tg or Tg C for each tracer to the screen

 SUBROUTINES:
        Internal Subroutines:
        ==================================================
        CSE_GetUnit (function)  CSE_GetAreaCm2 (function)
        CSE_GetInfo

        External Subroutines Required:
        ==================================================
        CTM_DIAGINFO            CTM_TRACERINFO
        CTM_GETDATA             CTM_BOXSIZE    (function)
        CTM_GRID    (function)  GAMAP_CMN
        TAU2YYMMDD  (function)  UNDEFINE

 REQUIREMENTS:
        None

 NOTES:
        (1) Most of the time there will be 1 data block per month,
            and the cumulative total will be a yearly total.

        (2) For NOx, a molecular weight of 14e-3 kg/mole will report
            results in Tg N.  A molecular weight of 46e-3 will report
            results in Tg NOx.  This can be changed in the file
            "tracerinfo.dat".

        (3) Should now be compatible with any model type and grid
            resolution.  As of 6/19/01, has only been tested using
            GEOS-CHEM diagnostic output.
   
 EXAMPLE:
        CTM_SUM_EMISSIONS, 'ANTHSRCE', $
                           FILENAME='ctm.bpch', TRACER=1, $
                           MODELNAME='GEOS1', RESOLUTION=4

             ; Will print emission totals for tracer #1 (NOx)
             ; for the ANTHSRCE (ND36) diagnostic, using data
             ; in file "ctm.bpch".  The data is from a GEOS-1 
             ; simulation on a 4x5 grid.

 MODIFICATION HISTORY:
        bmy, 26 Apr 2001: GAMAP VERSION 1.47
        bmy, 08 Jun 2001: - now uses correct tracer name, unit,
                            and molecular weight for CO--SRCE
        bmy, 19 Jun 2001: GAMAP VERSION 1.48
                          - added internal function CSE_GETUNIT
                            to return the proper unit string
                            ("Tg N", "Tg C", or "Tg").
                          - added internal function CSE_GETAREACM2
                            which gets the proper surface area
                            for each data block
                          - removed MODELNAME, RESOLUTION keywords
        bmy, 03 Jul 2001: - now can sum emissions from GENERIC grids
        bmy, 16 Aug 2001: - added /NO_SECONDS and /KG keywords
        bmy, 26 Sep 2001: GAMAP VERSION 1.49
                          - set XNUMOL = 1d-3 if /KG is set; this
                            will convert from g/cm2 to Tg correctly
        bmy, 21 Nov 2001: - added internal routine CSE_GETINFO
                          - now call CTM_EXTRACT to restrict the
                            totaling to any arbitrary lat/lon rectangle
        bmy, 10 Jan 2002: GAMAP VERSION 1.50
                          - Bug fix: Don't call CTM_EXTRACT if /KG is, 
                            set, since AREACM2 will be 1 in that case 
        bmy, 31 Jan 2002: - change output format from f10.4 to f12.4
        bmy, 10 Jun 2002: GAMAP VERSION 1.51
                          - added "kludge" for biomass burning files
                            if /NO_SECONDS is set; will use proper
                            mol wts & units for ACET, C3H8, C2H6
        bmy, 14 Jan 2003: GAMAP VERSION 1.52
                          - added another quick fix to get the unit strings
                            correct for sulfate and nitrogen tracers for ND13
        bmy, 19 Sep 2003: GAMAP VERSION 1.53
                          - now call PTR_FREE to free the pointer memory
        bmy, 19 Nov 2003: GAMAP VERSION 2.01
                          - now get the spacing between diagnostic
                            offsets from CTM_DIAGINFO
        bmy, 26 Mar 2004: GAMAP VERSION 2.02
                          - added FORMAT keyword
        bmy, 03 Dec 2004: GAMAP VERSION 2.03
                          - now pass /QUIET to CTM_GET DATA which
                            reduces a lot of printing to the screen
        bmy, 15 Mar 2005: - Added /TO_Gg and TO_Mg keywords, which
                            will print totals in either Gg or Mg
                            instead of the default unit of Tg
                          - Now pass _EXTRA=e to CTM_GET_DATA so that
                            we can restrict to a given time 
        bmy, 07 Apr 2006: GAMAP VERSION 2.05
                          - Added /SHORT keyword
        bmy, 29 Sep 2006: - Bug fix: now test for molec wt in kg/mole
                            in internal function CSE_GETUNIT
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
        phs, 20 Mar 2008: GAMAP VERSION 2.12
                          - updated to work with nested grid
        mps, 23 Jan 2014: - Added case for NO to CSE_GetUnit for output from
                            GEOS-Chem v9-02 and higher versions
                          - Now report NO emissions in Tg N
                          - Now print unit 'Tg C' for BC/OC tracers

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_sum_emissions.pro)


CTM_TRACERINFO

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_TRACERINFO

 PURPOSE:
        Return information about one or all tracers for a given
        GEOS-Chem, GISS, or other CTM diagnostic.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation, Structures

 CALLING SEQUENCE:
        CTM_TRACERINFO, TRACERN, TRACERSTRU [, Keywords ]

 INPUTS:
        TRACERN -> Tracer number or name for which to extract the 
            information. If TRACERN is numeric, it is interpreted as 
            an index to the FULLCHEM or SMALLCHEM tracernumber
            in the global model. If it is a string, it will be compared 
            to NAME then FULLNAME. TRACERN may contain more than one 
            element. To retrieve information about all tracers, use the
            /ALL_TRACERS keyword.

 KEYWORD PARAMETERS:
        /ALL_TRACERS -> Retrieve information about all tracers

        FILENAME --> Name of the tracerinfo file (default tracerinfo.dat)
            The file will be searched in the current directory first, then
            in the directory where ctm_tracerinfo.pro is located. If not found
            in either location, a standard data block is retrieved from this 
            file.

        /FORCE_READING -> Overwrite the contents of the common block

        FULLNAME -> Returns the (long) name of the requested tracer(s)

        INDEX -> Returns the CTM index of the requested tracer(s)

        MOLC -> Returns the carbon number of the requested tracer(s)
             (For hydrocarbons, this is the # moles C/mole tracer)

        MOLWT -> Returns the molecular weight (kg/mole) of the 
             requested tracer(s)

        NAME -> Returns the (short) name of the requested tracer(s)

        SCALE -> Standard scale factor for tracer

        UNIT -> Returns the standard unit of the requested tracer(s)
             (i.e. unit as supplied by CTM with standard scale factor 
             applied (e.g. ppbv instead of V/V))

        IS_EDGED -> Returns whether the given tracer is defined on
             level edges (IS_EDGED=1) or level centers (IS_EDGED=0).  

 OUTPUTS:
        TRACERSTRU -> returns a structure or structure array with the 
            following tags:
               NAME     : short name for tracer as used in the model
               FULLNAME : long name for tracer (may be used in titles)
               MWT      : molec. weight as kg N or kg C 
               INDEX    : tracer number
               MOLC     : carbon number for NMHC
               SCALE    : standard scale factor
               UNIT     : standard unit for tracer with scale factor applied
               IS_EDGED : Is tracer defined on level edges?

 SUBROUTINES:
        External Subroutines Required:
        ================================================
        FILE_EXIST (function)   ROUTINE_NAME (function)
        OPEN_FILE 
 
 REQUIREMENTS:
        None

 NOTES:
        At first call, the tracer information structure array is
        either read from file or retrieved from the
        DATA block at the end of this program. Thereafter, the information
        is stored in a common block where it is accessible in subsequent 
        calls.
        The newer tags MOLC, SCALE and UNIT are optional and defaulted
        to 1.0, 1.0, and 'UNDEFINED', resp.

 EXAMPLE:
        CTM_TRACERINFO, 2, RES
        PRINT, RES.NAME, RES.MWT, RES.INDEX
        ; prints        Ox    0.0480000     2

        CTM_TRACERINFO,'OX',RES
        PRINT, RES.NAME, RES.MWT, RES.INDEX
        ; prints identical results

        CTM_TRACERINFO,[1,3,5],NAME=NAME,MOLWT=MWT,MOLC=MOLC,/FORCE_READING
        PRINT, NAME, MWT, MOLC
        ; reads tracerinfo.dat file and prints 
        ; NOx PAN ALK4
        ; 0.0140000     0.121000    0.0120000
        ; 1.00000      1.00000      4.00000

 MODIFICATION HISTORY:
        mgs, 22 Apr 1998: VERSION 1.00
        mgs, 24 Apr 1998: - added NAME keyword
        bmy, 07 May 1998: - added MOLC structure field to store 
                            carbon number for NMHC
        mgs, 07 May 1998: VERSION 2.00
                          - substantially revised
        mgs, 08 May 1998: - added SCALE and UNIT tags, made them optional
        mgs, 28 May 1998: - bug fix with on_ioerror
        mgs, 09 Oct 1998: - bug fix for tracern=0, changed CALLING SEQ. entry
        mgs, 12 Nov 1998: - unit string now defaulted to 'UNDEFINED' 
        bmy, 03 Jan 2001: GAMAP VERSION 1.47
                          - skip tracer lines beginning with '#' character
        bmy, 17 Nov 2003: GAMAP VERSION 2.01
                          - Removed FULLI, SMALLI, they're obsolete
                          - now use INDEX for tracer number
                          - Now use new file format for "tracerinfo.dat"
                            which allows for 8-digit offset numbers
                          - No longer read defaults from internal datablock
                          - Updated comments 
        bmy, 06 Apr 2004: GAMAP VERSION 2.02
                          - added /VERBOSE keyword
        bmy, 09 Mar 2006: GAMAP VERSION 2.05
                          - Use "./tracerinfo.dat" as default in
                            order to facilitate reading in IDL 5.5-
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - Add IS_EDGED tag to TRACERINFO structure
                            to denote whether the tracer is defined
                            on level centers or level edges
                          - Implement temporary fix: call GET_IS_EDGED
                            to determine if a tracer is defined on
                            level edges.  There is probably a better way
                            to do this, work on that later.
                          - Now use FILE_WHICH to locate the
                            "tracerinfo.dat" file.
        phs, 30 Jun 2008: GAMAP VERSION 2.12
                          - bug fix to account for FILENAME
        phs, 22 Sep 2009: GAMAP VERSION 2.13
                          - added test on found/not found tracers

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_tracerinfo.pro)


CTM_TYPE (FUNCTION)

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_TYPE (function)

 PURPOSE:
        return basic parameters for various 3D models used in
        the Harvard tropospheric modeling group. This information
        should be sufficient for CTM_GRID to compute grid box edge
        and center vectors.

 CATEGORY:
        GAMAP Utilities, GAMAP Models & Grids, Structures

 CALLING SEQUENCE:
        MTYPE = CTM_TYPE( NAME [,FAMILY] [,KEYWORDS] )

 INPUTS:
        NAME -> a string containing the name of the model 
             (GISS_II, GISS_II_PRIME (or II_PRIME), GEOS1,
             GEOS_STRAT, FSU, MOPITT, or GENERIC (=DUMMY) )

        FAMILY -> model family (optional, will otherwise be extracted
             from NAME). Possible values: GISS or GEOS or FSU or ''

 KEYWORD PARAMETERS:
        NLAYERS -> number of vertical model layers. This number must
             correspond to the number of layers in the model output
             files and is used in conjunction with PTOP to convert
             sigma levels into pressure altitudes.
             [defaults: GEOS1=20, GEOS_STRAT=26, GISS=FSU=9 ]
     
        NTROP -> number of layers in the troposphere
             [defaults: GEOS1=14, GISS=7, FSU=12]

        PTOP -> pressure at model top
             [default 10 mbar except for GEOS_STRAT=0.1 mbar]
     
        PSURF -> average surface pressure (needed for conversion of
             sigma levels to altitudes) [default 984 mbar]
     
        RESOLUTION -> either a 2 element vector with [ DI, DJ ] or
             a scalar (DJxDI: 8=8x10, 4=4x5, 2=2x2.5, 1=1x1, 0.5=0.5x0.5)
             [default for all models is 4x5]
     
        HALFPOLAR = (1 | 0) -> indicates that polar boxes span 
             (half | same) latitude as all other boxes (DJ=const.)
             [default: 1]

        HYBRID = (1 | 0) -> indicates that the model is a 
             (sigma-pressure hybrid | pure sigma level ) model.
             [default: 0]

        /PRINT -> prints model parameters on the screen

 OUTPUTS:
        MTYPE -> A structure with the following tag names will be 
             returned:  NAME, FAMILY, NLAYERS, PTOP, PSURF, 
             RESOLUTION, HALFPOLAR, CENTER180, FULLCHEM.  If input 
             parameters are not correct, the function returns -1.

 SUBROUTINES:
        Internal Subroutines:
        =====================
        YES_NO_VAL (function)
        CHECK_RESOLUTION
        
 REQUIREMENTS:
        None

 NOTES:
        If you update this routine by adding additional models, make
        sure to update "select_model.pro" and "getsigma.pro" as well.

 EXAMPLES:
        (1)
        MTYPE = CTM_TYPE( 'GEOS1', RESOLUTION=2 )

             ; defines model parameters for the GEOS1 model 
             ; at 2 x 2.5 degree resolution.

        (2)
        MTYPE = CTM_TYPE( 'GISS_II' )
        MGRID = CTM_GRID( MTYPE )

             ; Use CTM_TYPE in conjunction with CTM_GRID to return
             ; the grid structure for the standard GISS_II model.

 MODIFICATION HISTORY:
        mgs, 02 Mar 1998: VERSION 1.00
        bmy, 07 Apr 1998: - Renamed to CTM_TYPE to keep
                            consistent with other CTM subroutines.
        mgs, 24 Apr 1998: - made structure named
        mgs, 19 May 1998: - added NTROP tag and keyword
        bmy, 19 Jun 1998: - now computes FSU model parameters
                          - GEOS_STRAT and GEOS-1 troposphere tops
                            are now computed separately
                          - added small bug fix for fullchem from mgs
        mgs, 14 Aug 1998: - added DUMMY name
        mgs, 15 Aug 1998: - added GEOS-1 as variant of GEOS1
        bmy, 21 Dec 1998: - changed NLAYERS for GEOS STRAT
        mgs, 22 Dec 1998: - small bug fix for GEOS family NTROP
        mgs, 22 Feb 1999: - added GENERIC (same as DUMMY) and allow
                            keyword settings for this name
        bmy, 23 Feb 1999: - Implemented FSU grid information
        mgs, 16 Mar 1999: VERSION 1.21 
                          - cosmetic changes
                          - changed function name yesno into yesno_val to
                            avoid conflicts.
                          - removed online tag because it's never
                            used
        bmy, 26 Jul 1999: VERSION 1.42
                          - added HYBRID keyword and tag name
                          - cosmetic changes 
        bmy, 15 Sep 1999: VERSION 1.43
                          - fixed bug for NTROP in GISS-II-PRIME, 9L
        bmy, 15 Oct 1999: VERSION 1.44
                          - now reset model names "GEOS-STRAT" and 
                            "GEOS-2" to "GEOS_STRAT" and "GEOS2"
        bmy, 03 Jan 2000: - added GEOS-2 model parameters
                          - changed NTROP to 16 for GEOS1
                          - changed NTROP to 22 for GEOS_STRAT
        bmy, 16 May 2000: VERSION 1.45
                          - reset NTROP to 19 for GEOS-STRAT    
                          - now use GEOS-2 47 layer grid    
        bmy, 01 Aug 2000: VERSION 1.46          
                          - added GEOS-3 48-layer grid
                          - added internal function CHECKRESOLUTION
                          - cosmetic changes, updated comments
        bmy, 26 Jun 2001: GAMAP VERSION 1.48
                          - fixed NTROP for GEOS-3 met fields
                          - for generic grids, return "GENERIC" in
                            uppercase as model name and family name
        bmy, 09 Oct 2001: GAMAP VERSION 1.49
                          - now accepts modelname "GEOS3_30L", and
                            returns a structure for 30-layer GEOS-3 grid
        bmy, 06 Nov 2001: - now recognizes "GEOS-4" as a modelname
                          - changed default PSURF from 986 mb to 984 mb
  clh & bmy, 18 Oct 2002: GAMAP VERSION 1.52:
                          - Now supports 7-layer MOPITT grid
        bmy, 12 Dec 2003: GAMAP VERSION 2.01
                          - Now supports "GEOS4_30L" grid
                          - Set NTROP=18 for GEOS-4 grid   
                          - Now set CENTER180=1 for GISS_II_PRIME 
                          - Now supports 52-layer NCAR-MATCH model 
                          - Cleaned up code and straightened out logic
                          - Removed SMALLCHEM, HELP keywords
        bmy, 18 Feb 2004: GAMAP VERSION 2.01a
                          - The actual NTROP from the GEOS-4 annual
                            mean tropopause is 17, not 18
        bmy, 17 Jun 2004: GAMAP VERSION 2.02a
                          - added GCAP model type for the 23L hybrid
                            GCAP grid (which is the same grid as the
                            winds for the GISS-II-PRIME)
        bmy, 01 Jun 2006: GAMAP VERSION 2.05
                          - Bug fix: GISS-II model needs CENTER180=0
  bmy & phs, 16 Aug 2007: GAMAP VERSION 2.10
                          - Modified for 47 layer GEOS-5 grid
                          - Now return NLAYERS, NTROP, HALFPOLAR,
                            CENTER180, FULLCHEM, HYBRID as type long
        bmy, 06 Aug 2010: GAMAP VERSION 2.14
                          - Added MERRA (identical to GEOS-5 grid, 
                            but retains MERRA name for clarity.)
        bmy, 28 Nov 2010: GAMAP VERSION 2.15
                          - Make the default PSURF value 1013.25 hPa,
                            (i.e. 1 atm) instead of 984hPa.
        bmy, 02 Feb 2012: GAMAP VERSION 2.16
                          - Add GEOS57 and GEOS57_47L grids, for
                            GEOS-5.7.x met data.  (These are
                            identical to the GEOS-5 and MERRA grids,
                            but we will denote them separately).
                          - Added shorthand for 0.25 x 0.3125 resolution

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_type.pro)


CTM_WRITEBPCH

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_WRITEBPCH

 PURPOSE:
        Save GAMAP datainfo records to disk 
        (in binary punch file format).

 CATEGORY:
        GAMAP Utilities, BPCH Format

 CALLING SEQUENCE:
        CTM_WRITEBPCH, DATAINFO, [, Keywords ]

 INPUTS:
        DATAINFO -> a datainfo record or an array of datainfo records
 
        FILEINFO -> a fileinfo record or an array of fileinfo records

 KEYWORD PARAMETERS:
        FILENAME -> Filename of output file. Should end in '.bpch'.

        SCALE -> An optional scaling factor. This factor will be applied 
             to _all_ data record upon saving. The globally stored records
             are not affected.

        NEWUNIT -> With this keyword you can change the unit _name_ for
             the saved data. This will _not_ perform a unit conversion!
             For a true unit conversion you must also use the SCALE
             keyword. NEWUNIT will be applied to _all_ records!

        /APPEND -> If set, then will append to an existing binary
             punch file rather than writing to a new file.

 OUTPUTS:
        A binary punch file with the selected data records will be
        created.

 SUBROUTINES:
        External Subroutines Required:
        ====================================================
        CHKSTRU      (function)   CTM_DIAGINFO
        CTM_GET_DATA (function)   DATATYPE     (function)   
        OPEN_FILE

 REQUIREMENTS:
        None

 NOTES:
        This routine forces reading of all selected data records via
        CTM_GET_DATA.  This may take a while for huge ASCII punch files.

 EXAMPLE:
        gamap [,options]  ; call gamap to read records from a file
        @gamap_cmn        ; get global datainfo structure
        d = *pglobalDataInfo 
        ind = where(d.tracer eq 2)  ; select all Ox records
        ctm_writebpch,d[ind],filename='oxconc.bpch'
        
 MODIFICATION HISTORY:
        mgs, 20 May 1999: VERSION 1.00
                          - stores binary files version 1
        mgs, 24 May 1999: VERSION 2.00
                          - stores binary files version 2
        bmy, 26 Jul 1999: VERSION 2.01
                          - now call function DATATYPE
                          - make sure only floating point data gets
                            written to binary punch file v. 2.0
        bmy, 19 Jan 2000: - updated commetns
        bmy, 07 Jun 2000: GAMAP VERSION 1.45
                          - Save TRACER mod 100L to the punch file 
                          - updated comments
        bmy, 02 Mar 2001: GAMAP VERSION 1.47
                          - added FILEINFO as an argument; will use
                            PGLOBALFILEINFO structure if not passed
                          - removed obsolete comments
        bmy, 13 Mar 2001: - now supports Windows, MacOS, and Unix/Linux
        bmy, 07 Jun 2001: - removed obsolete code from 7/26/99
  mje & bmy, 17 Dec 2001: GAMAP VERSION 1.49
                          - added /APPEND keyword in order to
                            append to an existing binary punch file
                          - updated comments
        bmy, 15 Oct 2002: GAMAP VERSION 1.52
                          - added LEVELSAVE keyword to define certain
                            levels which to save to disk
                          - Updated comments, cosmetic changes
        bmy, 19 Nov 2003: GAMAP VERSION 2.01
                          - now get diagnostic spacing from CTM_DIAGINFO
                            and write TRACER mod SPACING to the BPCH file.
        bmy, 27 May 2004: GAMAP VERSION 2.02
                          - Bug fix: Don't call CTM_GET_DATA to initialize
                            data pointers if this has been done already
                          - removed LEVELSAVE keyword
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - Now save 4D datablock if the tag
                            of FILEINFO[0].FILETYPE = 106;

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_writebpch.pro)


CTM_WRITENC

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        CTM_WRITENC

 PURPOSE:
        Save GAMAP datainfo records to disk (in netCDF format)

 CATEGORY:
        GAMAP Utilities, Scientific Data Formats

 CALLING SEQUENCE:
        CTM_WRITENC, DATAINFO, FILENAME=FILENAME

 INPUTS:
        DATAINFO -> a datainfo record or an array of datainfo records

 KEYWORD PARAMETERS:
        FILENAME -> Filename of output file. Should end in '.bpch'.

        SCALE -> An optional scaling factor. This factor will be applied 
             to _all_ data record upon saving. The globally stored records
             are not affected.

        NEWUNIT -> With this keyword you can change the unit _name_ for
             the saved data. This will _not_ perform a unit conversion!
             For a true unit conversion you must also use the SCALE
             keyword. NEWUNIT will be applied to _all_ records!

 OUTPUTS:
        A binary punch file with the selected data records will be
        created.

 SUBROUTINES:
        External Subroutines Required:
        ====================================
        CTM_GET_DATA
        OPEN_FILE
        DATATYPE

 REQUIREMENTS:
        Must have a version of IDL w/ the netCDF library installed.

 NOTES:
        This routine forces reading of all selected data records via
        ctm_get_data. This may take a while for huge ASCII punch files.

 EXAMPLE:
        gamap [,options]  ; call gamap to read records from a file
        @gamap_cmn        ; get global datainfo structure
        d = *pglobalDataInfo 
        ind = where(d.tracer eq 2)  ; select all Ox records
        ctm_writebpch,d[ind],filename='oxconc.bpch'
        
 MODIFICATION HISTORY:
        mgs, 20 May 1999: GAMAP VERSION 1.47
                          - adapted from "ctm_writebpch.pro"
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/ctm_writenc.pro)


EXAMPLE_ANIM_TS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        EXAMPLE_ANIM_TS

 PURPOSE:
        Illustrates how to use XINTERANIMATE with GAMAP 
        timeseries routine GC_COMBINE_ND49.

 CATEGORY:
        GAMAP Examples, GAMAP Utilities

 CALLING SEQUENCE:
        EXAMPLE_ANIM_TS [, Keywords ]

 INPUTS:
        None

 KEYWORD PARAMETERS:
        None

 OUTPUTS:
        None

 SUBROUTINES:
        External Subroutines Required:
        ================================================
        GC_COMBINE_ND49         MULTIPANEL
        MYCT                    PROGRAM_DIR (function)
        TAU2YYMMDD (function)   TVMAP

 REQUIREMENTS:
        Requires routines from the GAMAP package.

 NOTES:
        None

 EXAMPLE:
        EXAMPLE_ANIM_TS
             ; Creates sample animation from timeseries data.

 MODIFICATION HISTORY:
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.11

(See /n/home09/ryantosca/IDL/gamap2/examples/example_anim_ts.pro)


EXAMPLE_ND48_ND49

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        EXAMPLE_ND48_ND49

 PURPOSE:
        Creates several example plots to illustrate the use of GAMAP
        timeseries routines GC_COMBINE_ND48 and GC_COMBINE_ND49.

 CATEGORY:
        GAMAP Examples, GAMAP Utilities, Time Series

 CALLING SEQUENCE:
        EXAMPLE_ND48_ND49 [, Keywords ]

 INPUTS:
        None

 KEYWORD PARAMETERS:
        /PNG -> Set this switch to save screen output
             Portable Network Graphics (PNG) format.

 OUTPUTS:
        None

 SUBROUTINES:
        External Subroutines Required:
        =========================================
        GC_COMBINE_ND48   GC_COMBINE_ND49
        MULTIPANEL        PROGRAM_DIR (function)
        SCREEN2PNG

 REQUIREMENTS:
        Requires routines from the GAMAP package.

 NOTES:
        None

 EXAMPLE:
        EXAMPLE_ND48_ND49, /PNG
             ; Create example plots and save to PNG file.

 MODIFICATION HISTORY:
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.11

(See /n/home09/ryantosca/IDL/gamap2/examples/example_nd48_nd49.pro)


EXAMPLE_OVERPLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        EXAMPLE_OVERPLOT

 PURPOSE:
        Example program for overlay of data with model results.
        This program is meant to provide a demonstration example
        rather than a ready-to-use program, so please copy it
        and adapt it to your needs.
          For a try, just call EXAMPLE_OVERPLOT with no options.
        Before you rewrite this code, try some of the keyword 
        options to get a feel how it works.

 CATEGORY:
        GAMAP Examples, GAMAP Utilities

 CALLING SEQUENCE:
        EXAMPLE_OVERPLOT [,DATA [,ALTITUDE]] [,keywords]

 INPUTS:
        DATA -> A vector with your vertical profile data. If nothing
           is supplied, a dummy ozone profile is generated.

        ALTITUDE -> Altitude vector correspondign to your data. If not
           supplied, a vector will be created ranging from 0-12 km.

 KEYWORD PARAMETERS:
        Keywords to select certain model results:
        DIAGN -> Name (or number) of a diagnostic. Default is 'IJ-AVG-$'

        TRACER -> A tracer number (default is 2 = 'Ox')

        TAU0 -> A time step value. You can specify a date using the
             NYMD2TAU function.

        Keywords to select the geographical domain:
        LONRANGE, LATRANGE -> 2-element vectors specifying the minimum
             and maximum longitude and latitude for the model results
             to be considered. Not that LONRANGE[1] < LONRANGE[0] is 
             possible, denoting a region across the Pacific.

        Keywords to change the appearance of the plot:
        TITLE -> Give your plot a title. Default is 'EXAMPLE PLOT'
             with longitude and latitude rang and date.
             If you are sure that you select only one data record each
             time, you can leave it up to CTM_PLOT to construct a title
             (simply remove the TITLE keyword in the call to CTM_PLOT).
             Note that you can take advantage of various "variables"
             with the '%NAME%' notation (see GAMAP documentation for
             details).

        _EXTRA -> Look at the documentation of CTM_PLOT and add your
             favorite keywords to the call to EXAMPLE_OVERPLOT. You are
             likely to use XRANGE or XSTYLE. 

 OUTPUTS:
        just a plot ;-)

 SUBROUTINES:
        none

 REQUIREMENTS:
        uses ctm_get_dat and ctm_plot as well as everything that is
        needed by these to.

 NOTES:

 EXAMPLE:
        EXAMPLE_OVERPLOT

        data = your_fancy_reading_routine(filename)
        EXAMPLE_OVERPLOT,data,tau0=nymd2tau(940601L)

 MODIFICATION HISTORY:
        mgs, 21 May 1999: VERSION 1.00
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/examples/example_overplot.pro)


EXAMPLE_POLAR

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        EXAMPLE_POLAR

 PURPOSE:
        Quick and dirty examples of polar plots made with CTM_PLOT.

 CATEGORY:
        GAMAP Examples, GAMAP Utilities

 CALLING SEQUENCE:
        EXAMPLE_POLAR

 INPUTS:
        None

 KEYWORD PARAMETERS:
        /PS -> Set this switch to write output to a PostScript file.

 OUTPUTS:
        None

 SUBROUTINES:
        External Subroutines Required:
        =================================
        MYCT     CTM_PLOT   MULTIPANEL

 REQUIREMENTS:
        None

 NOTES:
        none

 EXAMPLE:
        EXAMPLE_POLAR, /PS
             ; Create polar plots and save to PostScript file.

 MODIFICATION HISTORY:
        mgs, 20 Aug 1998: INITIAL VERSION
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - now uses FILE_WHICH to find ctm.bpch.examples
                          - rewritten for clarity
        bmy, 14 Mar 2008: GAMAP VERSION 2.12
                          - Bug fix: save output from FILE_WHICH to
                            FILE (instead of FILENAME)
                                

(See /n/home09/ryantosca/IDL/gamap2/examples/example_polar.pro)


EXAMPLE_TVMAP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        EXAMPLE_TVMAP

 PURPOSE:
        Generates several example plots using CTM_PLOT and TVMAP.

 CATEGORY:
        GAMAP Examples, GAMAP Utilities

 CALLING SEQUENCE:
        EXAMPLE_TVMAP [, Keywords ]

 INPUTS:
        None

 KEYWORD PARAMETERS:
        /PNG -> Set this switch to save screen output
             Portable Network Graphics (PNG) format.

 OUTPUTS:
        None

 SUBROUTINES:
        External Subroutines Required:
        ====================================
        CTM_PLOT     MULTIPANEL
        MYCT         NYMD2TAU  (function)
        SCREEN2PNG   TVMAP

 REQUIREMENTS:
        Requires routines from the GAMAP package.

 NOTES:
        None

 EXAMPLE:

        EXAMPLE_TVMAP, /SAMPLE
             ; Create example plots with pixel plots for all plots.

        EXAMPLE_TVMAP, /PNG
             ; Create example plots and save to a PNG file.

 MODIFICATION HISTORY:
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.11

(See /n/home09/ryantosca/IDL/gamap2/examples/example_tvmap.pro)


FIND_CELLS_BY_COUNTRY

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        FIND_CELLS_BY_COUNTRY

 PURPOSE:
        Returns an index array which can be used to determine 
        which CTM grid boxes lie within a given country.

 CATEGORY:
        GAMAP Utilities

 CALLING SEQUENCE:
        RESULT = FIND_CELLS_BY_COUNTRY( COUNTRYID, GRIDINFO [, Keywords] )

 INPUTS:
        COUNTRYID -> Name of the country you are interested in, OR
             the country ID number ID from "countries.table".  

        GRIDINFO -> Structure from CTM_GRID which defines the output
             CTM model grid in which you wish to find a given country.

 KEYWORD PARAMETERS:
        /MAXIMIZE -> Set this switch to search for all grid boxes that
             contain any portion of the specified country.  The
             default is to determine the specified country by the
             center of the grid box.

        /INDEX -> Set this switch to return RESULT as an 1-D index 
             vector (i.e. similar to output from the WHERE command). 

 OUTPUTS:
        RESULT -> Integer index array for OUTGRID.  Grid boxes where 
             RESULT[I,J] = 1 designate the desired country.  If the
             /INDEX flag is set then RESULT will be an 1-D index
             vector (i.e. similar to output from the WHERE command). 
       
 SUBROUTINES:
        Internal Subroutines:
        ============================
        GET_COUNTRY_NUMBER (function)

        External Subroutines Required:
        ===========================================
        CHKSTRU  (function)    CTM_GRID (function)
        CTM_TYPE (function)    DATATYPE (function)
        STRBREAK (function) 

 REQUIREMENTS:
        None

 NOTES:
        (1) Requires the following input files:
            (a) countries.table                
            (b) countries.generic.025x025.gif

        (2) The search algorithm is brute-force (i.e. FOR loops
            over lat & lon).  Maybe in a later version we can 
            optimize this w/ IDL array notation.

 MODIFICATION HISTORY:
  tmf & bmy, 01 Jul 2006: GAMAP VERSION 2.05
                          - Initial version
  bmy & phs, 27 Jul 2007: GAMAP VERSION 2.10
                          - Use FILE_WHICH to find countries.table
                          - Use FILE_WHICH to find countries.gif 

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/find_cells_by_country.pro)


FIND_TRACER_INDEX

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        FIND_TRACER_INDEX

 PURPOSE:
        Given the diagnostic category and tracer name, returns the
        tracer number as specified in the "tracerinfo.dat" file.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        RESULT = FIND_TRACER_INDEX( DIAGN, NAME )

 INPUTS:
        DIAGN -> Diagnostic category name as specified in the
             "diaginfo.dat" file (e.g. "IJ-AVG-$", "GMAO-2D", etc.).

        NAME -> Tracer name as specified in the "tracerinfo.dat"
              file (e.g. NOx, Ox, CO, PS, TAUCLI, etc.)

 KEYWORD PARAMETERS:
        None

 OUTPUTS:
        RESULT -> Tracer number corresponding to NAME and DIAGN.

 SUBROUTINES:
        External subroutines required:
        ------------------------------
        CTM_DIAGINFO   CTM_TRACERINFO

 REQUIREMENTS:
        Requires routines from the GAMAP package.

 NOTES:
        Here, "tracer" is used in the wider sense.  It can be can be 
        any quantity saved out from a CTM diagnostic output, as long
        as it is specified by "diaginfo.dat" and "tracerinfo.dat".

 EXAMPLE:
        PRINT, FIND_TRACER_INDEX( 'GMAO-2D', 'PS' )
        IDL prints   5931

             ; Returns the tracer index number for the "PS"
             ; quantity in the "GMAO-2D" diagnostic category.
             
 MODIFICATION HISTORY:
        bmy, 06 Aug 2010: VERSION 1.00

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/find_tracer_index.pro)


GAMAP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        GAMAP

 PURPOSE:
        Menu-driven user interface for creating plots with
        the GAMAP package subroutines. The actual data retrieval
        and plotting is done with ctm_plot.pro. This routine
        mainly collects all user requests and passes them on to
        CTM_PLOT.

 CATEGORY:
        GAMAP Utilities, GAMAP Plotting

 CALLING SEQUENCE:
        GAMAP, [ DiagN [, Keywords ] ]

 INPUTS:
        DIAGN -> A diagnostic number or category to restrict
             the record selection (default is: use all).

 KEYWORD PARAMETERS:
        General keywords:
        -----------------------------------------------------------------
        FILENAME -> CTM output file name. Default is to display a
             pickfile dialog and let the user select. You can have
             wildcards ('*', '?') in your filename which restricts
             the file selection.

        /NOFILE -> Don't query for filename but display all records that
             have already been loaded. This can save you a couple of
             mouse clicks when you want to create several plots with
             data from one file, and it also useful when you want
             to plot data from 'external' files that were converted
             with ctm_make_datainfo. If a filename is given or no
             data were loaded, the file selection dialog will appear
             anyhow.

        /RESETDEFAULTS -> If set, will reset all GAMAP values to their
             defaults.

        /HELP -> Displays a help page.

        RESULT -> Returns a structure with the data subset as plotted and
             the respective X and Y coordinates. Returns only one data
             record though.

        TOPTITLE -> Add a specific title centered on top of each page
             of output.

        Keywords to restrict the number of records displayed for selection:
        -----------------------------------------------------------------
        TRACER -> A tracer number to restrict record selection

        TAU0 -> Time value (at beginning of record)

        DATE -> 6 digit date (e.g. 940101) at the beginning of the
             output record (this gets translated into a TAU0
             value via the function nymd2tau). You can specify more
             than one date at a time using a vector (e.g. [940101, 940301]).
             For the GISS model(s), you also have to specify /GISS_Date in
             order to get correct tau values. The time is assumed to
             be 00 GMT. For other times use the TAU0 keyword as
             TAU0=nymd2tau(dates,times).

        /GISS_Date -> set this flag if you are using the DATE keyword
             with GISS model output.

        Keywords defining output options (these override defaults in
        gamap.defaults)
        -----------------------------------------------------------------
        /PS -> If set, will directly send output to the 'idl.ps' file.
             If not set, GAMAP will prompt the user whether to create
             the 'idl.ps' file.

        OUTFILENAME -> Name of file to send PostScript output to.

        /NOTIMESTAMP -> Do not include a user ID and time stamp
             on the postscript plot. Unnecessary if the TIMESTAMP value
             in gamap.defaults is set to 0.

        XSIZE, YSIZE, XOFFSET, YOFFSET -> GAMAP will pass these
             keywords to routine OPEN_DEVICE, for setting the size
             and margins of PostScript output.  

        /DO_BMP -> If set, GAMAP will save animation frames as BMP
             files.  If not set, GAMAP will prompt the user whether
             to save animation frames to BMP files.  DO_BMP overrides
             the default setting in "gamap.defaults".

        BMPFILENAME -> Name of BMP file to save animation frames to.
             If the token %N% is used in BMPFILENAME, then GAMAP
             will replace %N% with the actual frame number.  If
             BMPFILENAME is not set, or if DO_BMP is set to *QUERY in
             "gamap.defaults", GAMAP will prompt user to supply
             BMPFILENAME.

        /DO_GIF -> If set, GAMAP will save animation frames as GIF
             files.  If not set, GAMAP will prompt the user whether
             to save animation frames to GIF files.  DO_GIF overrides
             the default setting in "gamap.defaults".

        GIFFILENAME -> Name of GIF file to save animation frames to.
             If the token %N% is used in GIFFILENAME, then GAMAP
             will replace %N% with the actual frame number.  If
             GIFFILENAME is not set, or if DO_GIF is set to *QUERY in
             "gamap.defaults", GAMAP will prompt user to supply
             GIFFILENAME.

        /DO_JPEG -> If set, GAMAP will save animation frames as BMP
             files.  If not set, GAMAP will prompt the user whether
             to save animation frames to JPEG files.  DO_JPEG overrides
             the default setting in "gamap.defaults".

        JPEGFILENAME -> Name of JPEG file to save animation frames to.
             If the token %N% is used in JPEGFILENAME, then GAMAP
             will replace %N% with the actual frame number.  If
             JPEGFILENAME is not set, or if DO_JPEG is set to *QUERY in
             "gamap.defaults", GAMAP will prompt user to supply
             JPEGFILENAME.

        /DO_PNG -> If set, GAMAP will save animation frames as PNG
             files.  If not set, GAMAP will prompt the user whether
             to save animation frames to PNG files.  DO_PNG overrides
             the default setting in "gamap.defaults".

        PNGFILENAME -> Name of PNG file to save animation frames to.
             If the token %N% is used in PNGFILENAME, then GAMAP
             will replace %N% with the actual frame number.  If
             PNGFILENAME is not set, or if DO_PNG is set to *QUERY in
             "gamap.defaults", GAMAP will prompt user to supply
             PNGFILENAME.

        /DO_TIFF -> If set, GAMAP will save animation frames as TIFF
             files.  If not set, GAMAP will prompt the user whether
             to save animation frames to TIFF files.  DO_TIFF overrides
             the default setting in "gamap.defaults".

        TIFFFILENAME -> Name of TIFF file to save animation frames to.
             If the token %N% is used in TIFFFILENAME, then GAMAP
             will replace %N% with the actual frame number.  If
             TIFFFILENAME is not set, or if DO_PNG is set to *QUERY in
             "gamap.defaults", GAMAP will prompt user to supply
             TIFFFILENAME.

        /POLAR -> Set this keyword for polar pots. This forces latitude
             ranges to extend to one pole and longitude ranges to span
             the globe. Polar plots only work for global (at least 
             longitudinally) data sets.  Currently, polar plots are 
             supported only for contour plots.

        _EXTRA=e -> Picks up extra keywords for CTM_PLOT, etc...

 OUTPUTS:

 SUBROUTINES:
        Internal subroutines:
        ------------------------------------------------------
        GAMAP_CheckDataBlockConsistency (function)
        GAMAP_FindNearestCenters        (function)
        GAMAP_GetDataBlockRanges        (function)
        GAMAP_GetDefaultRanges
        GAMAP_AutoYRange                (function)
        GAMAP_PrintDimInfo
        GAMAP_QueryAnimationOptions
        GAMAP_QueryAverageOrTotal
        GAMAP_QueryPostScriptOptions
        GAMAP_SelectDataBlocks          (function)
        GAMAP_SelectPlotType
        GAMAP_QueryIsoPleth
        GAMAP_StoreGridInfo
        GAMAP_UserRangeEntry            (function)
        GAMAP_GetFrameFileName          (function)


        Also uses external subroutines:
        ------------------------------------------------------
        CHOICE        (function)    CLOSE_DEVICE
        CTM_PLOT                    OPEN_DEVICE
        STRREPL       (function)    STRWHERE    (function)
        DEFAULT_RANGE (function)    CHKSTRU     (function)
        REPLACE_TOKEN (function)    CTM_GRID    (function)
        MAKE_SELECTION(function)    TVREAD      (function)

 REQUIREMENTS:
        None

 NOTES:
        (1) GAMAP can read ASCII punch files with GEOS or GISS, model II
            diagnostics, binary punch files (as defined in Jan 1999),
            and GEOS-CTM binary restart files. Binary punch files
            are processed much faster and allow "windowing" of output.

        (2) For pixel plots, GAMAP can only plot cylindrical maps
            with rectangular projections.  Arbitrary map projections
            should be possible with any type of contour plot. For 
            polar plots, use the /POLAR keyword. Other projections 
            have not been tested and may lead to unexpected results.

        (3) GAMAP forces map ranges to coincide with the grid box
            edges, so that the map and pixel plot will be aligned.
            Each "pixel" size corresponds to one full grid box.
            For grids with half-polar boxes, it is therefore recommended
            not to plot the polar latitudes, since those boxes will
            show up as full-size boxes and shift the rest of the plot
            accordingly.

        (4) When the user selects multiple data blocks, GAMAP will produce
            a multi-panel plot if !p.multi indicates more than one panel
            on the screen (use the MULTIPANEL procedure to turn it on).
            If you plot only one panel per screen, GAMAP will automatically
            start XInterAnimate to present your own movie to you. Be
            aware that XInterAnimate is limited by your system resources.
            With default window sizes, we can usually display at least
            30 frames.  ADDENDUM: 3-D isopleth maps will not be
            animated. (bmy, 1/22/01)

        (5) Animation frames can also be written to GIF or MPEG
            files.  Defaults can be set in "gamap.defaults", or
            specified via the command line. You can also save individual
            GAMAP plots as GIF files. If you want to animate them later
            (e.g. using ULead's GIF-Animator), make sure to specify the
            RANGE keyword to get identical color schemes (or use contours).

        (6) The GAMAP authors wish to point out that it is still relatively
            expensive to produce color plots on the printer. We encourage
            you to try out contour plots and make a test print on a black
            and white printer before you make a color print.

        (7) The 3-D isopleth maps do not quite work with MULTIPANEL, since
            they are produced with screen capture in the Z-Buffer.  Hence  
            Hence, the X window device has to be re-initialized each time, 
            which negates the MULTIPANEL utility.  PostScript plots of 3-D
            isopleth maps will print one plot per page.  We can live with
            this for the time being.  Isopleth maps can also be written
            to GIF files.

        (8) Now uses D. Fanning's TVREAD function to perform better
            device-independent screen capture. (cf. www.dfanning.com)

 EXAMPLES:
        (1)
        GAMAP
            ; operates fully interactively

        MULTIPANEL,nplots=6       ; turn on multi-panel environment
        GAMAP
            ; same as above, but produce multi-panel plots with
            ; 6 plots per page

        (2)
        GAMAP, 'IJ-AVG-$', tra=4
            ; Will create a CO (tracer=4) plot for the ND45 diagnostic.
            ; GAMAP will display dialog pickfile box and will scan the
            ; file for all records with ND45 and tracer 4. Those will be
            ; displayed and the user can then select a record to be plotted.

        (3)
        GAMAP, [ 'IJ-AVG-$', 'BIOBSRCE' ], tra=[2,4], $
               date=[19940601, 19940801], $
            FileName='~bmy/terra/CTM4/ctm.pch',/ps
            ; In this example the file is fully specified, hence no file
            ; selection dialog will be displayed. GAMAP scans the file
            ; for all records of 'IJ-AVG-$' and 'BIOBSRCE' and tracers
            ; 2 (OX) and 4 (NOX) and it seelcts only those records that
            ; begin on the first of JUNE or AUGUST 1994. Because the ps
            ; flag is set, the output will be directed to the postscript
            ; file 'idl.ps' without first being displayed on the screen.


 MODIFICATION HISTORY:
        mgs, 12 Nov 1998: VERSION 1.00
        bmy, 16 Nov 1998: - added defaults for LAT, LEV, LON, PTYPE
                          - now prompts for PS
                          - now prompts user for /PS output
        bmy, 17 Nov 1998: - now call DEFAULT_RANGE to ensure that
                            that LAT, LON, LEVEL have two elements,
                            even if there is only one unique value.
                          - now uses N_UNIQ.PRO to test for the number
                            of unique elements in LON, LAT, and LEVEL.
        mgs, 17 Nov 1998: - finishing touches for first release.
                          - added NOFILE keyword
                          - added plot type b/w contours
        mgs, 18 Nov 1998: - added timestamp as default when closing
                            postscript files
        bmy, 08 Jan 1999: - Will also prompt for totaling (if
                            averaging is not selected)
        bmy, 13 Jan 1999: - now prompt user for OUTFILENAME
        bmy, 15 Jan 1999: VERSION 1.02
                          - add support for 3-D data slices
                          - clean up user interface so that the user
                            menu of plotting options is only invoked
                            when plotting a 2-D map.
        bmy, 19 Jan 1999: - added binary flag masking
                          - added defaults for averaging and selection
                          - improved echoback of information to user
        bmy, 20 Jan 1999: - prompts user again if data block selection
                            or averaging selection is out of range
                          - fixed bug: now default data block
                            selection is saved.
                          - Reset PS to 0 and OUTFILENAME to '' if we
                            are plotting a 0-D or 3-D data block
                          - updated comments
        mgs, 21 Jan 1999: - dimensional information now in subroutine
                          - improved binary masking
                          - added several Quit options
                          - Postscript options now controlled from
                            gamap.defaults
                          - removed NoTimeStamp keyword (now set in
                            gamap.defaults)
        bmy, 12 Feb 1999: VERSION 1.03
                          - now works with data blocks that are
                            sub-regions of the globe
                          - added functions GAMAP_GetDataBlockRanges
                            GAMAP_SelectDataBlock, and
                            GAMAP_QueryAverageOrTotal
                          - updated comments
        bmy, 17 Feb 1999: VERSION 1.20
                          - Replace DATAINFO.OFFSET by DATAINFO.FIRST,
                            which contains the I, J, L indices of
                            the first grid box
                          - Animation facility added
                          - added functions GAMAP_GetModelInfo,
                            GAMAP_CheckDataBlockConsistency,
                            GAMAP_SelectPlotType, and
                            GAMAP_QueryPostScriptOptions.
                          - Also renamed function GAMAP_SelectDataBlock to
                            GAMAP_SelectDataBlocks, since one can now
                            select multiple data blocks
        bmy, 18 Feb 1999: - added /RESETDEFAULTS keyword
                          - removed /ANIMATE keyword
        bmy, 19 Feb 1999: - added NOAUTOYRANGE keyword
                          - added function GAMAP_AutoYRange
                          - added GIFFILENAME keyword
                          - added GIF_SAV to common block SAVEVALUES
                          - call REPLACE_TOKEN to replace token text
                            in DEFAULTGIFFILENAME
        bmy, 22 Feb 1999: - added more animation options
                          - added DO_GIF, DO_MPEG, DO_ANIMATE, and
                            MPEGFILENAME keywords
                          - added GAMAP_QueryAnimationOptions routine
        bmy, 23 Feb 1999: - small bug fixes
        bmy, 04 Mar 1999: - added internal routines GAMAP_FindNearestEdges
                            and GAMAP_GetDefaultRanges
                          - now force lat/lon ranges to coincide with
                            grid box edges
                          - warn user if lat range contains half-polar
                            boxes, since TVIMAGE will treat them as
                            whole boxes and the map overlay will be
                            inaccurate!
        bmy, 05 Mar 1999: - Clean up FILEINFO/DATAINFO matching process
                          - renamed/reorganized internal functions\
        bmy, 20 Mar 1999: - bug fix for default ranges (may need more
                            fixing later on)
        mgs, 22 Mar 1999: - added ALREADY_PS flag for multi-panel use
                          - animation now only if !p.multi does not
                            have more than 1 panel to display
        mgs, 23 Mar 1999: - improved comments and examples
                          - removed unnecessary function MatchFileInfo...
                            (easier with make_selection)
                          - changed all "string booleans" to booleans
                          - Do_Animation now an entirely local variable
        mgs, 25 Mar 1999: - few minor bug fixes
                          - improved handling of default ranges
                          - detect out of range in record selection
                          - now allows for 2D field plots
        bmy, 17 May 1999: - now resolve DEFAULT_RANGE explicitly and
                            call DEFRANGE_STR2NUM separately
                          - few minor fixes in GAMAP_UserRangeEntry for
                            data blocks that straddle the date line.
        mgs, 19 May 1999: - some more cleaning
                          - implemented SAVE option after data record
                            selection
                          - user selection for longitudes greatly improved
                          - some adjustments in FindNearestEdges, notably
                            for range 0..360. Unfortunately, the 0 meridian
                            gridline will be omitted in such plots. If we
                            wanted to include it we would need to carry
                            an extra GLOBAL flag because lower and upper
                            edges (grid box indices) are identical.
        mgs, 20 May 1999: - added option to save record seelction to file.
        mgs, 24 May 1999: - yet more work had to be done to make lon/lat
                            selection as user would expect it to work.
                          - renamed FindNearestEdges to ..Centers
        mgs, 25 May 1999: - still more fiddling. Yuck!

                          RELEASE OF GAMAP VERSION 1.40

        bmy, 26 May 1999: - Added polar plot capabilities
                          - fixed reset of plot ranges when latitude is +-90
        mgs, 27 May 1999: - already_ps flag now also prevents user query.
                          - default lat range for global fields now back
                            to -88..88 only for "reset" conditions. Otherwise
                            -90..90 is recognized and remembered.
        mgs, 28 May 1999: - added RESULT keyword.
                          - added TOPTITLE keyword.
        bmy, 28 May 1999: - restrict plot type menu for polar plots
  bmy & mgs, 02 Jun 1999: - add /NOERASE to MULTIPANEL call when
                            testing for last plot on page
                          - updated some comments
        mgs, 30 Jun 1999: - make sure to return only one lat/lon box
                            if user enters single value (even on edges).
        bmy, 07 Jul 1999: - small bug fixes
        bmy, 15 Sep 1999: GAMAP VERSION 1.43
                          - changes for 23L GISS-II-PRIME model
                          - minor bug fixes
        bmy, 25 Oct 1999: GAMAP VERSION 1.44
                          - added /MULTIPLE keyword -- option to
                            write to a GIF file w/ multiple frames
        bmy, 23 Nov 1999: - /SMALLCHEM now works correctly!
        bmy, 26 Apr 2000: GAMAP VERSION 1.45
                          - now make sure tracer numbers are mod 100L
                            when saving data blocks to disk
        bmy, 19 Jun 2000: - now create NS string array by concatenating 
                            smaller arrays of < 1024 elements
        bmy, 20 Jun 2000: - bug fix -- set NS[0] blank for string output
        bmy, 03 Oct 2000: GAMAP VERSION 1.46
        bmy, 22 Jan 2001: GAMAP VERSION 1.47
                          - removed obsolete code
                          - now produce a 3-D isopleth map instead of
                            calling the volume slicer routine
                          - added ISOPLETH keyword
                          - added internal subroutine GAMAP_QueryIsopleth
                          - allow PostScript output for 3-D maps, and
                            suppress animation for 3-D maps.
        bmy, 13 Mar 2001: - remove a couple more instances of the 
                            obsolete STR_SEP routine.  Replaced with
                            STRSPLIT( /EXTRACT ).  
        bmy, 28 Jun 2001: GAMAP VERSION 1.48
                          - bug fix in GAMAP_StoreDataInfo: for
                            GENERIC grids with NLAYERS=0, be sure to
                            call CTM_GRID with the /NO_VERTICAL flag.
        bmy, 29 Aug 2001: - added XSIZE, YSIZE, XOFFSET, YOFFSET 
                            keywords to pass to OPEN_DEVICE 
  mje & bmy, 17 Dec 2001: GAMAP VERSION 1.49
                          - add _EXTRA=e in call to CTM_WRITEBPCH, 
                            so that we can pass the /APPEND keyword 
        bmy, 17 Jan 2002: GAMAP VERSION 1.50
                          - now call STRBREAK wrapper routine from
                            the TOOLS subdirectory for backwards
                            compatiblity for string-splitting
                          - use FORWARD_FUNCTION to declare STRBREAK
        bmy, 24 Jan 2002: - deleted obsolete code
        bmy, 06 Dec 2002: GAMAP VERSION 1.52
                          - removed /DO_MPEG and MPEGFILENAME keywords
                          - now use D. Fanning's TVREAD for better
                            device-independent screen capture
                          - removed /MULTIPLE keyword for GIF output
                          - added /DO_PNG, /DO_BMP, /DO_JPEG,
                            /DO_TIFF keywords
                          - added internal function GAMAP_GetFrameFileName
        bmy, 13 Nov 2003: GAMAP VERSION 2.01
                          - comment out XINTERANIMATE options
        bmy, 27 Aug 2004: GAMAP VERSION 2.03
                          - now call CTM_PLOT_TIMESERIES to plot data
                            from bpch files containing GEOS-CHEM station
                            timeseries output (e.g. ND48 diagnostic)
        bmy, 27 Oct 2004: - now pass /QUIET keyword to GAMAP_AUTOYRANGE,
                            CTM_PLOT_TIMESERIES, and CTM_PLOT
                          - hardwire QUIET=1 in to suppress extra printing
        bmy, 28 Jun 2005: GAMAP VERSION 2.04
                          - Strip white spaces in FILENAME, if present
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
  bmy & phs, 20 Nov 2007: GAMAP VERSION 2.11
                          - If any 4D data blocks are encountered,
                            then only use the first 3 dimensions
        phs, 22 Sep 2009: GAMAP VERSION 2.13
                          - Added /NoDialog to all call to TVRead
        bmy, 26 Feb 2010: GAMAP VERSION 2.14
                          - Now allow polar maps to use pixel plots
        bmy, 11 Feb 2011: GAMAP VERSION 2.15
                          - Updated welcome screen

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/gamap.pro)


GC_COMBINE_ND48

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        GC_COMBINE_ND48

 PURPOSE:
        Combine timeseries data from the Geos-CHEM ND48
        diagnostics contained in one or more binary punch files.

        The goal is to combine, for one station, all the data blocks
        (there is one per time step) into one single 4-D data block
        (we want the time to be the 4th dimension). This is basically
        to take advantage of support for 4D dataset in GAMAP v2-10.

        GEOS-Chem ND48 (as in v7-04-12) outputs one file for all
        stations and all time steps. GC_COMBINE_ND48 will write one
        file but each timeseries will be in one data block instead of
        as many as the number of timesteps. This will make reading
        the timeseries with CTM_GET_DATA a lot faster.

        Two basic signal processing before saving the data can be
        applied: moving average and/or daily maximum.

        LIMITATION: daily maximum will not make sense if series do
        not cover full days.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation, Time Series

 CALLING SEQUENCE:
        GC_COMBINE_ND48 [, Keywords ]

 OPTIONAL INPUTS:

        By defaults all stations are processed. And one output file
        is created that contains all the stations timeseries.

 KEYWORD PARAMETERS:

        ;============ For I/O files/directory =====================

        INFILE -> one or more station file(s) from ND48
              diagnostic. If more than one file is processed, it is
              assumed that, once sorted in alphabetical order, they
              are in chronological order (this is automatically the
              case, if you insert YYYYMMDD into ND48 filenames in
              input.geos).

        INDIR -> Directory where to look for "stations" files. Can be
             either input or output keyword:

             Input: when defined, ALL files satisfying the MASK
                    keyword in the directory will be selected.

             Ouput: set to a variable name that will contains the DIR
                    of the selected files.

             It is ignored (both input and output roles) if INFILE is
             provided.

             If neither INFILE nor INDIR is set, then a dialog window
             that allows multiple files selection (keep CTRL or SHIFT
             key down) will pop-up.


        MASK -> Pattern Mask to find files in INDIR. Default is
             "stations*".

        OUTFILENAME -> Name of the file that will contain the
             new timeseries. Default is 'combined'+INFILE[0], in the
             same directory as stations file. If the full path is not
             included, the file is created in the working directory.

            The routine prevents from overwriting any input file.

        ;================= Data Selection ======================

        STATIONNB -> Station(s) number. Can be one or more elements
              (up to the number of stations in ND48). Use to select a
              subset of the stations instead of all of them.

        TIME -> vector for selecting time span. The data covering
              [min(TIME),max(TIME)] are selected. If only one
              element, then the closest-in-time data is selected.

              If min and/or max of TIME is outside the range of
              available time steps, the first or last available time
              step is used.

              Note 1: this is also an output keyword. Then, if passed
              by reference, TIME becomes the time vector in
              output. See example (6).

              Note 2: if using DMAX or DAVG, then TIME should be long 
              integer (YYYYMMDD), if not it should be Tau format.

        ;================= Signal Processing ======================

        MAVG -> to apply a running average filter to the series. MAVG
              value will define the boxcar size and must be GE
              3. Even numbers are increased by +1. The IDL SMOOTH
              routine is called and accept _extra keywords (NAN,
              EDGE_TRUNCATE, and MISSING).

        DMAX -> to select the daily maxima of the time series. If
              both MAVG and Dmax are set, the moving average is
              performed first and you get the daily max of the moving
              average. (Local time is not accounted for: days start
              and end at 0 UT everywhere).

        DAVG -> to select the daily average of the time series. If
              both MAVG and DAVG are set, the moving average is
              performed first and you get the daily average of the
              moving average. (Local time is not accounted for: days
              start and end at 0 UT everywhere).


        ;================= Output keywords ========================

        All the following keywords will apply to only ONE
        station. The last one is used if none or more than one is
        requested.

        DATA -> set to a variable name that will hold the selected
             timeseries data on exit. This is a 4D array
             (1,1,lev,time) even though only one station is
             selected.

        LON -> set to a variable name that will hold the
             longitude of the data set on exit.

        LAT -> set to a variable name that will hold the
             latitude of the data set on exit.

        LEV -> set to a variable name that will hold the vector
             of levels for the data set on exit.

        TIME -> set to a variable name that will hold the time
             vector for the station on exit. Given as Tau values,
             unless DMAX or DAVG is set, then as YYYYMMDD.

        LOCALTIME -> if set, the TIME vector is in local time
             instead of UT. Has no effect if /DMAX or /DAVG.


        ;================= Others ========================

        NOSAVE -> set to not save output into a BPCH file. Useful if
             you just want to check results with output keywords.

        VERBOSE -> Set to print informational message about the time
             series. particularly useful to double check
             area/location selected with subset keywords.

        _EXTRA=e -> Picks up extra keywords for SMOOTH and
                 DIALOG_PICKFILE.


 OUTPUTS:
        See output keywords above.

 SUBROUTINES:

 REQUIREMENTS:
        References many routines from GAMAP package. Requires GAMAP
        v2.10 for handling 4D dataset.

 NOTES:
       If memory issues show up, try to save one timeseries (i.e.,
       one station at a time).

 EXAMPLES:

        ;; (1) Read multiple timeseries files selected w/ a pop-up
        window (use SHIFT key for muliple selections). Save with the
        default filename in the default directory:

        GC_COMBINE_ND48


        ;; (2) Like example (1), but saves only the daily max of the
        ;;     9-hours average timeseries:

        GC_COMBINE_ND48, /dmax, mavg=8



        ;; (3) read ALL stations files from directory '~/path/'
        ;; without a pop-up window (no interactivity, good for batch
        ;; processing). Default MASk and outfile name are used.

        GC_COMBINE_ND48, indir='~/path/'


        ;; (4) Like example (3) but select only the first available
        ;; station, and save the result in a specified file:

        GC_COMBINE_ND48, Station=1, indir='~/path/', outfile='~/path/series1.bpch'


        ;; (5) read files from directory '~/path/', and select 3rd station.
        ;; Do not save combined timeseries. Get outputs in variables
        ;; data, lon, lat and time.

        GC_COMBINE_ND48, indir='~/path/', station=3, data=data, lon=lon, lat=lat, time=time

        Help, reform(data)
        PLOT, time, data[0,0,0,*], title='Lon= strtrim(lon,2)+'- Lat='+strtrim(lat,2)


        ;; (6) Like (5), but limit the time to 23rd-28th of July
        ;;     2001. Not the use of two commands to get the output
        ;;     time vector.

        time = [nymd2tau(20010723L,20010728l)]
        GC_COMBINE_ND48, indir='~/path/', station=3, data=data, lon=lon, lat=lat, time=time 
        HELP, time


 MODIFICATION HISTORY:
        phs, 31 Jul 2007: GAMAP VERSION 2.10
                          - Initial version
        phs, 11 Oct 2007: - few bugs fix
                          - added output keywords
        phs, 15 Oct 2007: - added LOCALTIME keyword
        phs, 18 Oct 2007: - do not save if output file is one of the
                            input file.
        phs, 26 Oct 2007: - TIME can be use to select the time span
                            of the series.
                            Added DAVG keyword.
        phs, 30 Oct 2007: - couple of minor fixes.
        phs, 11 Aug 2009: - major fix: bug fix when same tracer 
                            in several stations 
        bmy, 12 Mar 2009: GAMAP VERSION 2.14
                          - Typo at line 429 fixed

(See /n/home09/ryantosca/IDL/gamap2/timeseries/gc_combine_nd48.pro)


GC_COMBINE_ND49

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        GC_COMBINE_ND49

 PURPOSE:
        Combine timeseries data from several bpch files into 4D
        data. Typically used with Geos-CHEM ND49 timeseries output
        and met fields in bpch files (a3, a6, i6). 
        
        For met fields, see example (9) and (10).

        Each ND49 and Met Fields file has data for one day. But,
        files with time series that do no cover a day per file, can
        also be processed. See example (11), but keep in mind that
        the daily max or average options are then **** MEANINGLESS
        ****, and should not be used.


        WHAT IS DONE:
        
        (1) We combine all the data blocks for one tracer (there is
        one per time step) into one single 4-D data block (with time
        in 4th dimension). This takes advantage of support for 4D
        dataset introduced in GAMAP v2-10.

        (2) The combined series can be saved into a binary punch
        file. You end up with one file per tracer that covers many
        days of output, instead of one file per day for all
        tracers. The space saving can be more than 60%.

        (3) A subarea (even a single location) can be extracted. But
        for multiple but not contiguous locations, call the routine
        as many time as needed.

        (4) Shorter timeseries can be selected/saved, by specifying
        Tau range, or day (as YYYYMMDD long integer) range if daily
        max or average is selected.

        (5) Two basic signal processing before saving the data can be
        performed: moving average and/or daily
        maximum/minimum/average.

        ## LIMITATION ## : full days considered for ND49, ie,
        GEOS-Chem runs should start and end at midnight (YYYYMMDD
        000000 in input.geos)

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation, Time Series

 CALLING SEQUENCE:
        GC_COMBINE_ND49 [, TRACER ][, CATEGORY ][, Keywords ]

 INPUTS:
        TRACER -> The tracer number. Default is 1.

        CATEGORY -> The category name (default is "IJ-AVG-$")
             for which to read data.

 KEYWORD PARAMETERS:

        ;============ For I/O files/directory =====================

        FILELIST -> list of files to process. Usually used as output
             keyword to get the list of files selected with INDIR and
             MASK or through a dialog window.
             Can be used as input. Then INDIR and MASK are ignored.

        INDIR -> Directory where to look for MASK files.  If
             provided, ALL files satisfying the MASK keyword in the
             directory will be selected. If not provided, a dialog
             window that allows multiple files selection (keep SHIFT
             key down) will pop-up. See EXAMPLES below for tips.

             If set to an undefined variable name, it will hold the
             directory of the selected files (output keyword).

             NOTE: If more than one file is processed, it is assumed
             that, once sorted in alphabetical order, they are in
             chronological order (this is the case with GEOS-Chem
             default naming of ND49 output files: they contain
             YYYYMMDD).

        MASK -> Pattern Mask to find files in INDIR. Default is
             "ts*.bpch".

        OUTDIR -> Output directory where to save the file with the
             new timeseries data set will be. Default is INDIR. If
             the user has not write permission in INDIR, writintg is
             cancelled.

        OUTFILENAME -> Name of the file that will contain the
             timeseries. Default is 'combts_%TRACERNAME%.bpch', for
             COMB ined  T ime  S eries.

            The routine prevents from overwriting any input file.

        ;============ To extract subset of data ===================

        LON -> A one or two-elements vector specifying the longitude
            of one location or one area. If LON is outside the ND49
            area, the program print a warning, and uses border
            value.

        LAT -> same as LON, but for Latitudes

        LEV -> same as LON, but for Levels. Refers to the model grid.


        ; - - you can also select indices into the requested 3D cube:

        LLEV -> A one or two-element vector specifying the min and
             max of available levels to be included in the file.
             Default is ALL available levels.
             Default FORTRAN indexing is used: LLEV #1 is the first
             level ***requested*** in ND49. See LEV above otherwise.

        ILON, JLAT -> same as LLEV but for Longitude and Latitude
             indices. Starting at 1 at the first ***requested***
             grid box in ND49.


        TIME -> vector for selecting time span. The data covering
              [min(TIME),max(TIME)] are selected. If only one
              element, then the closest-in-time data are selected.
              TIME must be given as Tau (double) or YYYYMMDD (long)
              if /DMAX or /DAVG.
              If both DMAX (or DAVG) and LOCALTIME are set, TIME is
              ignored. 

          ** TIP ** if you select a short time span, it may be
                    useful to limit the number of files to process
                    by redefining MASK or using FILELIST. That will
                    speed up the process.


        ;================= Signal Processing ======================

        MAVG -> to apply a running average filter to the series. MAVG
              value will define the boxcar size and must be GE
              3. Even numbers are increased by +1. The IDL SMOOTH
              routine is called and accept _extra keywords (NaN,
              Edge_truncate, missing).

        DMAX -> to select the daily maxima of the time series. If
              both MAVG and Dmax are set, the moving average is
              performed first and you get the daily max of the moving
              average.

        DAVG -> to select the daily average of the time series. If
              both MAVG and DAVG are set, the moving average is
              performed first and you get the daily average of the
              moving average.

        LOCALTIME -> to get DAVG or DMAX computed over local days
              instead of UT days. See details below.


        ;================= Output keywords ========================

        DATA -> set to a variable name that will hold the selected
             timeseries data on exit. This is a 4D array
             (nLon, nLat, nLevel, ntime) even if only one location is
             selected.

        OUTLON -> set to a variable name that will hold the vector
             of longitudes of the data set on exit.

        OUTLAT -> set to a variable name that will hold the vector
             of latitudes of the data set on exit.

        OUTLEV -> set to a variable name that will hold the vector
             of Levels of the data set on exit.

        OUTALT -> set to a variable name that will hold the vector
             of altitudes for the data set on exit.

        OUTTIME -> set to a variable name that will hold the time
             vector corresponding to the data set on exit. Format
             is Tau, or YYYYMMDD if /DMAX.

        LOCALTIME -> if set, OUTTIME becomes a Nb_OutLon X Nb_TimeStep
             array, with each vector OUTTIME[i,*] holding the time
             vector in local time instead of UT. That vector will
             apply to all j and k for DATA[i,j,k,*].


           Specific case of...  both DMAX (or DAVG) and LOCALTIME
             being set. The daily max (average) is obtained after
             shifting the timeseries, so they start at 00 LT
             everywhere (or the first available time step just before
             00 LT). The first max (average) value is for the first
             complete local day of the series. The OUTTIME array is
             then a [numbers of complete days, 2] array that gives
             the local YYYYMMDD for both positive and negative
             longitudes.

             See also note about TAU0/TAU1 below.

             Note that the time step of the series must be small
             enough for the DMAX/DAVG w/r/t Local Time to be
             reliable.


        ;================= Others ========================

        NOSAVE -> set to not save output into a BPCH file. Useful if
             you just want to check results with output keywords.

        VERBOSE -> Set to print informational message about the time
             series. Particularly useful to double check the
             area/location selected with subset keywords.

        _EXTRA=e -> Picks up extra keywords for SMOOTH and
                 DIALOG_PICKFILE.


 OUTPUTS:
        See output keywords above.

 SUBROUTINES:

 REQUIREMENTS:
        References many routines from GAMAP package. Requires GAMAP
        v2.10 for saving 4D dataset into binary punch file.

 NOTES:
        ######## ND49 and Met Fields only. For ND48, see  ########
        ######## GC_COMBINE_ND48 (not as well maintained) ########

        Written with batch processing in mind. It is recommended to
        save all ND49 outputs into one dedicated directory, and to
        use keywords (INDIR, OUTDIR, OUTFILE..) and save the new
        combined timeseries in a new directory.

        About TAU0 and TAU1 : in the DataInfo structure, they are set
        to the beginning and end of the timeseries. For daily data,
        we compute them by setting HH:MM:SS to 00:00:00. If LocalTime
        is set, UT is still used for TAU0 and TAU1, so we can use
        only one value. If both LocalTime and DMAX are set, tau0 and
        tau1 give the first and last (local) days for longitudes less
        than 0 (west). For East longitudes, you need to add one day
        to these to get the correct date.
 

 EXAMPLES:
        ;; In the following examples, it is assumed that tracer 1
        ;; has been saved with ND49


        ;; (1) Read multiple timeseries files selected w/ a pop-up
        window (use SHIFT key for muliple selections). Saved series
        at ALL available locations into default directory and filename:

            GC_COMBINE_ND49

        exactly the same as:

            GC_COMBINE_ND49, 1, 'IJ-AVG-$'


        ;; (2) Like example (1), but saves only the daily max of the
        ;; 9-hours average timeseries:

            GC_COMBINE_ND49, 1, 'IJ-AVG-$', /dmax, mavg=8


        ;; (3) Like example (1), but do not save the timeseries. Get
        ;; the timeseries in the variable TS in output:

            GC_COMBINE_ND49, 1, 'IJ-AVG-$', /nosave, data=TS


        ;; (4) read **ALL** MASK-files from directory '~/path/'
        ;; without a pop-up window (no interactivity, good for batch
        ;; processing):

            GC_COMBINE_ND49, 1, 'IJ-AVG-$', indir='~/path/', outfile='series1.dat'


        ;; (5) Like example (4), but with selection of ONE station:

            GC_COMBINE_ND49, 1, 'IJ-AVG-$', indir='~/path/', outfile='station1.bpch',$
                             lon=-65., lat=45., lev=1


        ;; (6) Like example (5), but with shorter time series (from
        ;; 2001/7/20 20:00 to 2001/7/23 2:00):

            GC_COMBINE_ND49, 1, 'IJ-AVG-$', indir='~/path/', outfile='station1.bpch',$
                             lon=-65., lat=45., lev=1, $
                             Time=[nymd2tau(20010720l,200000l),nymd2tau(20010723l,20000l)]


        ;; (7) Like example (6), but select Daily Max and for few
        ;;  days only (from 23rd to 28th of July 2001):

            GC_COMBINE_ND49, 1, 'IJ-AVG-$', indir='~/path/', outfile='station1.bpch',$
                             lon=-65., lat=45., lev=1, /DMax,
                             Time=[20010723L,20010728L]


        ;; (8) read **ALL** MASK-files from a directory selected with
        ;; a pop-up window:

            GC_COMBINE_ND49, 1, 'IJ-AVG-$', indir=dialog_pickfile(/dir)



        ;; (9) read CLOUD FRACTION from GEOS-4 met fields. Interactive way.

            GC_COMBINE_ND49, nosave=1, data=ts,  $
                             mask='/as/data/master/ctm/GEOS_4x5.d/GEOS_4_v4/1985/02/*a6*', $
                             7, 'GMAO-2d', outtime=time


        ;; (10) read CLOUD FRACTION from GEOS-4 met fields. All data
        from February 1985 automatically:

            GC_COMBINE_ND49, nosave=1, data=ts,  $
                             indir='/as/data/master/ctm/GEOS_4x5.d/GEOS_4_v4/1985/02/', $
                             mask='*a6*', $
                             7, 'GMAO-2d', outtime=time


        ;; (11) Read 3 series of 2004 GFED2 emissions (3hr, 8-day and
                monthly):

         ; -- get data from MASK and DIRECTORY
         dir3hr  = '/as/data/geos/GEOS_1x1/GFED2_3hr_200901/2004/'
         dirMon  = '/as/data/geos/GEOS_1x1/GFED2_200601/2004/'
         dir8day = '/as/data/geos/GEOS_1x1/GFED2_8day_200712/2004/'
   
         mask3hr =  'GFED2.3hr.C_20040*.generic.1x1'
         maskMon =  'GFED2_C_2004*.generic.1x1'
         mask8day = 'GFED2_8day_C_2004*.generic.1x1'

         gc_combine_nd49, 99, 'GFED2-BB', /nosave,       data=d3hr,      $
                          mask=mask3hr,   indir=dir3hr,  outTime=tau3hr, /verb

         gc_combine_nd49, 99, 'GFED2-BB', /nosave,       data=d8day,      $
                          mask=mask8day,  indir=dir8day, outTime=tau8day, /verb

         gc_combine_nd49, 99, 'GFED2-BB', /nosave,       data=dMon,      $
                          mask=maskMon,   indir=dirMon,  outTime=tauMon, /verb



         ;-- Julian Time for each data set (the half time step is added to
         ;   get the time series centered on their period, since we plot
         ;   histograms, with psym=10)
         temp   = tau2yymmdd( tau3hr + 1.5 )
         Jul3hr = JulDay(temp.month, temp.day, temp.year, temp.hour, temp.minute)

         temp    = tau2yymmdd( tau8day + (4.*24.) )
         Jul8day = JulDay(temp.month, temp.day, temp.year, temp.hour, temp.minute)

         temp   = tau2yymmdd(tauMon + 15.*24.)
         JulMon = JulDay(temp.month, temp.day, temp.year, temp.hour, temp.minute)

         ; -- convert from [g C/m2/time-period] to [Tg C/time-period]
         GridInfo = CTM_GRID( CTM_TYPE( 'generic', res=[1., 1.] ) )
         Surface  = CTM_BOXSIZE( GridInfo, /cm2 )

         dim = size(surface, /dimensions)

         d3hr  = d3hr  * rebin( Surface, dim[0], dim[1], 1, (size(d3hr))[4] )
         d8day = d8day * rebin( Surface, dim[0], dim[1], 1, (size(d8day))[4] )
         dMon  = dMon  * rebin( Surface, dim[0], dim[1], 1, (size(dMon))[4] )

         d3hr  = d3hr  * 1e-9
         d8day = d8day * 1e-9
         dMon  = dMon  * 1e-9

         ; -- Sum data over space, and convert to [ Tg C/s ]
         sum3hr  = total( total( total(d3hr,  1), 1), 1) / (3. * 3600.)
         sum8day = total( total( total(d8day, 1), 1), 1) / (8. *24. * 3600.)


         ; -- Plot time series

         dummy = label_date( date_format=['%D', '%M'] )

         plot, Jul3hr, sum3hr, /ynozero, color=!myct.black, $
                title='Total GFED2 emissions in 2004 (Tg C/sec)', $
                /xstyle, $
                xtickformat=['label_date', 'label_date', 'label_date'], $
                xtickunit=['day', 'month'], $
                position=[0.1, 0.15, 0.9, 0.9], $
                psym=10


          oplot, Jul8day, sum8day, thick=2., color=!myct.black, psym=10




 MODIFICATION HISTORY:
        phs,  6 Jun 2007: GAMAP VERSION 2.05
                          - Initial version
        phs, 25 Jul 2007: GAMAP VERSION 2.10
                          - added Moving Average and Daily Max as
                            signal processing available before 
                            saving/passing data.
                          - added Lon and Lat keywords to select one
                            location or a smaller area.
                          - added output keywords.
        phs,  4 Oct 2007: - Bug fix for OUTTIME keyword
        phs, 12 Oct 2007: - Added OUTLEV output keyword, and LEV
                            input keyword.
                          - INDIR can be used as output keyword.
        phs, 15 Oct 2007: - added LOCALTIME keyword
        phs, 18 Oct 2007: - do not save if output file is one of the
                            input file.
        phs, 26 Oct 2007: - bug fix for LON and LAT
                          - added TIME keyword to limit
                            timeseries in time.
        phs, 28 Oct 2007: - DMAX accounts for LOCALTIME if set.
                          - Bug fix for OutTime when /DMax.
        phs, 04 Apr 2008: GAMAP VERSION 2.12
                          - added DAVG keyword
                          - now cleanup the /no_global pointers
                          - added the FILELIST keyword
        phs, 17 Jul 2008: - Added comments
        phs, 15 Aug 2008: GAMAP VERSION 2.13
                          - Bug fix for OutTime when /DMax or /DMean
                            and input are from at least two different
                            months
   mb & phs, 02 Dec 2008: - DIM is forced to 32-bit integer (LONG)
        phs, 08 Jan 2009: - Now can process files that cover time
                            periods different from one day. 
        bmy, 14 Apr 2010: GAMAP VERSION 2.14
                          - Add _EXTRA=e to CTM_GET_DATA so as to pass
                            down any flags for nested grids 

(See /n/home09/ryantosca/IDL/gamap2/timeseries/gc_combine_nd49.pro)


GETMODELANDGRIDINFO

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        GETMODELANDGRIDINFO

 PURPOSE:
        Given a DATAINFO structure, returns the corresponding
        MODELINFO and GRIDINFO structures. 

 CATEGORY:
        GAMAP Utilities, GAMAP Models & Grids, Structures

 CALLING SEQUENCE:
        CTM_GETMODELANDGRIDINFO, THISDATAINFO, MODELINFO, GRIDINFO

 INPUTS:
        THISDATAINFO -> A single of DATAINFO structure which 
             contains the following fields:

             ** Structure H3DSTRU, 13 tags, length=72:
                ILUN            LONG      
                FILEPOS         LONG      
                CATEGORY        STRING    
                TRACER          INT       
                TRACERNAME      STRING    
                TAU0            DOUBLE    
                TAU1            DOUBLE    
                SCALE           FLOAT     
                UNIT            STRING    
                FORMAT          STRING    
                STATUS          INT       
                DIM             INT       
                OFFSET          INT       
                DATA            POINTER   

 KEYWORD PARAMETERS:
        LON -> set to a variable that will hold the longitude
             centers of the data set. Grid Offsets of data that
             do not cover the globe are accounted for.
 
        LAT -> same as LON, but for Latitude centers.

        LEVEL -> same as LON, but holds levels indices, starting at 1.

 OUTPUTS:
        MODELINFO -> Returns to the calling program the model 
             information structure (see "ctm_type.pro") which
             corresponds to THISDATAINFO.
                      
        GRIDINFO -> Returns to the calling program the grid 
             information structure (see "ctm_grid.pro") which
             corresponds to THISDATAINFO.

 SUBROUTINES:
        External Subroutines Required:
        ==============================
        GAMAP_CMN (include file)  
        CTM_GRID  (function)

 REQUIREMENTS:
        None

 NOTES:
        None

 EXAMPLE:
        ; Read data from "myfile.bpch"
        ; DATAINFO is an array of structures
        CTM_GET_DATA, DATAINFO, FILE='myfile.bpch'

        ; Loop over all data blocks in the file
        FOR D = 0L, N_ELEMENTS( DATAINFO )-1L DO BEGIN

            ; Pick the DATAINFO structure for the Dth data block 
            THISDATAINFO = DATAINFO[D].DATA

            ; Get MODELINFO and GRIDINFO structures for the Dth data block
            GETMODELANDGRIDINFO, THISDATAINFO, MODELINFO, GRIDINFO

             ...
        ENDFOR

 MODIFICATION HISTORY:
        bmy, 24 Apr 2002: GAMAP VERSION 1.50
        bmy, 28 Jun 2006: GAMAP VERSION 2.05
                          - Bug fix for multi-level GENERIC grids
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
        phs, 13 May 2008: GAMAP VERSION 2.12
                          - Added LON and LAT keyword to return data
                          (not global grid) longitude and latitude centers.
        phs,  8 Oct 2008: GAMAP VERSION 2.13
                          - Added LEVEL keyword to return levels.

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/getmodelandgridinfo.pro)


GET_IS_EDGED (FUNCTION)

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        GET_IS_EDGED  (function)

 PURPOSE:
        Determine if a GEOS-5 data field is defined on the
        vertical grid box edges or centers.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        RESULT = GET_IS_EDGED( NAME )

 INPUTS:
        NAME -> Name of the tracer or met field to be tested.

 KEYWORD PARAMETERS:

 OUTPUTS:
        RESULT -> Returns 1 if the tracer or met field specified by
             NAME is defined on grid box vertical edges, or 0
             otherwise.

 SUBROUTINES:
        None

 REQUIREMENTS:
        None

 NOTES:
        (1) This is currently a KLUDGE.  Figure out a more 
            robust way of determining if fields are defined on 
            level edges or level centers later on. (bmy, 7/16/07)

        (2) Add more names to the CASE statement as necessary.

 EXAMPLES:
        (1)
        PRINT, GET_IS_EDGED( 'PEDGE' )
          1
             ; The GEOS-5 PEDGE field is defined on the vertical
             ; grid edges, so GET_IS_EDGED returns 1.

        (2)
        PRINT, GET_IS_EDGED( 'UWND' )
          0

             ; The GEOS-5 UWND field is defined on the vertical
             ; grid centers, so GET_IS_EDGED returns 0.

 MODIFICATION HISTORY:
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/internals/get_is_edged.pro)


ISOPLETH_MAP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        ISOPLETH_MAP

 PURPOSE:
        Plots a 3-D (longitude, latitude, altitude) isopleth of
        a data concentration field atop a world map.

 CATEGORY:
        GAMAP Utilities

 CALLING SEQUENCE:
        ISOPLETH_3D

 INPUTS:
        DATA -> The data array to be plotted.  DATA must be
             3-dimensional.

        XMID, YMID, ZMID -> XMID is the array of longitude grid box
             centers.  YMID is the array of latitude grid box centers.  
             ZMID is the array of altitude grid box centers.  
             ISOPLETH_MAP will be able to label the X, Y, and Z axes
             based on the values of XMID, YMID, ZMID.

 KEYWORD PARAMETERS:
        ISOPLETH -> Value of data for which to show an iso-contour surface.  
             Default is 35.0 [ppbv].

        /LOW -> Set this keyword to display the low side of the iso-contour 
             surface (i.e., the contour surfaces enclose high data values). 
             If this keyword is omitted or is 0, the high side of the 
             contour surface is displayed and the contour encloses low
             data values. If this parameter is incorrectly specified,
             errors in shading will result.  

        TITLE1 -> First line of the title that is to be placed atop the plot
             window.  TITLE is passed explicitly to avoid keyword name
             duplication in the _EXTRA=e facility.  A default title
             string of "Volume Rendering" will be used if TITLE is not
             passed explicitly.
 
        TITLE2 -> Second line of the title string for the top of the plot
             window.  This line should be used for specifying the value
             and units of the isosurface.  A default string such as:
             "ISOSURFACE = 20.000 [ppbv]" will be created if TITLE2 is
             not passed explicitly.  Also, if TITLE2 is not passed 
             explicitly, the format descriptor string passed via the
             FORMAT keyword will be used to determine the number of
             decimal places 

        USTR -> String to specify the units of the isocontour surface
             (e.g. '[ppbv]', '[kg/s]', etc).  Default is a null
             string, ''.

        FORMAT -> Format descriptor string used in generating a default
             value of TITLE2.  Default is '(f14.3)'.

        MPARAM -> A 3 element vector containing values for
             [ P0Lat, P0Lon, Rot ], for the MAP_SET command.  
             Default is [ 0, 0, 0 ]. Elements not specified are 
             automatically set to zero.

        LIMIT -> A four-element vector which specifies the latitude
             and longitude extent of the map.  The elements of LIMIT
             are arranged thus: [ LatMin, LonMin, LatMax, LonMax ].
             Default is to set LIMIT = [ -90, -180, 90, 180 ] (i.e.
             to include the entire globe). P0Lon will be computed
             to fit into the LIMIT range unless it is explicitely
             requested in MParam.

        MCOLOR -> Color index of the map outline and title characters.
             Default is 1 (MYCT black).

        ACOLOR -> Color index of the 3-D axes which surround the map
             plot.  Defaults is 1 (MYCT black).

        [XYZ]MARGIN -> A 2-element array specifying the margin on
             the left (bottom) and right (top) sides of the plot
             window, in units of character size. Defaults are 
             XMARGIN=[ 5, 3 ], YMARGIN=[ 3, 3], ZMARGIN=[ 3, 3 ].
             These are used to put some "white space" into the plot
             window for aesthetic purposes.

        WINPARAM -> An integer vector with up to 5 elements:
             WINPARAM(0) = window number  (if negative, a window
                           will be opened with the /FREE option.
             WINPARAM(1) = X dimension of window in pixels (width)
             WINPARAM(2) = Y dimension of window in pixels (height)

 OUTPUTS:
        A picture will be displayed in the X-window device.

 SUBROUTINES:
        External Subroutines Required:
        ================================
        OPEN_DEVICE     CLOSE_DEVICE
        MULTIPANEL      MAP_LABELS
        TVIMAGE

 REQUIREMENTS:
        References routines from both GAMAP and TOOLS packages

 NOTES:
        (1) Does not quite work for multi-panel plots, due to the 
            screen capturing done in the Z-buffer.  

        (2) Verified that the map and data coincide (bmy, 1/19/01)

 EXAMPLE:
      ISOPLETH_MAP, DATA, XMID, YMID, ZMID, $
         ISOPLETH=40, MPARAM=[0, 180, 0], MCOLOR=1, ACOLOR=1

             ; Will display a 35 [ppbv] isopleth with black
             ; map labels, lines, and axes.  MPARAM is set to
             ; accept longitude values (XMID) in the range of
             ; 0 - 360.  

 MODIFICATION HISTORY:
        bmy, 23 Jan 2001: GAMAP VERSION 1.47
                          - based on example code by David Fanning
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
        phs, 17 Jul 2008: GAMAP VERSION 2.12
                          - Now set N_COLORS to !D.TBLE_SIZE 
        phs, 17 Jul 2008: GAMAP VERSION 2.13
                          - Bug fix: !D.TBLE_SIZE should be !D.TABLE_SIZE
        phs, 14 Oct 2009: - added AZ (so it is used for surface and
                            not map_set) and ZVALUE keywords
                          - added _EXTRA keyword to open_device for PS
                          - more control over TITLE2
        phs, 29 Oct 2009: GAMAP VERSION 2.14
                          - now draws the fram even if there is no
                            iso-surface

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/isopleth_map.pro)


PLANE_PLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        PLANE_PLOT

 PURPOSE: 
        Plots data from the GEOS-CHEM plane following diagnostic
        atop a world map.  Multiple flights can be plotted.

 CATEGORY:
        GAMAP Utilities, GAMAP Plotting

 CALLING SEQUENCE:
        PLANE_PLOT, VAR, FLTID [, Keywords ]

 INPUTS:
        VAR -> Variable name for which to plot data.  VAR should
             match the variable names in the GEOS-CHEM input file
             "Planeflight.dat" (e.g. TRA_001, GMAO_TEMP, REA_O1D, etc.)
           
        FLTID -> Flight ID(s) for which to plot data.  These should
             match the flight ID's in the GEOS-CHEM input file
             "Planeflight.dat" (e.g. P3B01, DC801, etc.)

 KEYWORD PARAMETERS:
        FILENAME -> Name of the file containing GEOS-CHEM plane 
             following diagnostic output.  If FILENAME is omitted,
             then a dialog box will prompt the user to supply a file
             name.

        LIMIT -> A 4-element vector with [MINLAT,MINLON,MAXLAT,MAXLON],
             which will specify the bottom left and top right corners
             of the map plot in degrees.  Default is to plot the 
             entire Northern Hemisphere [0,-180,90,180].

        MPARAM -> A 3 element vector which specifies the LAT0, LON0,
             and ROT values to be passed to MAP_SET.  Default is
             [0,0,0].
        
        SYMBOL -> Number of the symbol used to plot each data point.
             SYMBOL corresponds to the types of symbols defined with
             the routine "sym.pro" in the TOOLS package.  Default is
             1 (filled circle).

        SYMSIZE -> Size of the plot symbol.  Default is 1.5

        _EXTRA=e -> Passes extra keywords to MAP_SET, MAP_GRID,
             and MAP_CONTINENTS.

 OUTPUTS:
        None

 SUBROUTINES:
        External Subroutines Required:
        =================================
        COLORBAR
        CTM_READ_PLANEFLIGHT (function)
        UNDEFINE

 REQUIREMENTS:
        None

 NOTES:
        None

 EXAMPLES:
        PLANE_PLOT, 'O3', 'P3B04',           $
                     LIMIT=[20,-120,50,-60], $
                     FILENAME='plane.log'
        
             ; Plots GEOS-CHEM O3 data (stored in "plane.log) from
             ; the model grid boxes corresponding to flight P3BO4 
             ; over the USA.
 
        PLANE_PLOT, 'O3', ['P3B04','DC801'], $
                     LIMIT=[20,-120,50,-60], $
                     FILENAME='plane.log'

             ; Plots GEOS-CHEM O3 data (stored in "plane.log) from
             ; the model grid boxes corresponding to flights P3BO4 
             ; and DC801 over the USA.

 MODIFICATION HISTORY:
        bmy, 23 Apr 2004: GAMAP VERSION 2.03
        bmy, 13 Mar 2006: GAMAP VERSION 2.05
                          - Slight modifications for new version
                            of ctm_read_planeflight.pro
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/plane_plot.pro)


PLOTSIGMA

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        PLOTSIGMA

 PURPOSE:
        PLOTSIGMA plots the sigma level extent of various CTM's
        (including GISS-II, GISS-II', GEOS-1, GEOS-STRAT, GEOS-2,
        and FSU) side by side for comparison.  Useful for making
        viewgraphs.

 CATEGORY:
        GAMAP Utilities, GAMAP Models & Grids

 CALLING SEQUENCE:
        PLOTSIGMA, MODELNAME [, keywords ]

 INPUTS:
        MODELNAME -> A string (or array of strings) containing the 
             names of the models to be plotted.  Default is [ 'GEOS1' ].

 KEYWORD PARAMETERS:
        /PLEFT -> Will cause pressure to be plotted (with regular
             spacing) along the left Y-axis.  Default is to plot 
             altitude (with regular spacing) along the left Y-axis).  

        /PS -> Causes output to be sent to the PostScript Device.

        SURFP -> The surface pressure in mb used to convert sigma
             levels into absolute pressures.  Default is 1010.

        YRANGE -> Specifies the plotting range [Ymin, Ymax]
             along the left Y-axis.  Default is [ 0, 32 ] km.

 OUTPUTS:
        None

 SUBROUTINES:
        External subroutines required:
        --------------------------------------------
        CTM_TYPE   (function)   CTM_GRID (function)
        USSA_PRESS (function)   USSA_ALT (function)
        MYCT_DEFAULTS (function) 

 REQUIREMENTS:
        None
         
 NOTES:
        None
        
 EXAMPLE:
        PLOTSIGMA, /PLEFT, $
            ['GISS_II', 'GEOS1', 'GEOS_STRAT', 'FSU' ], $
            YRANGE=[1010, 150], SURFP=1010.0

            ; plots sigma levels for GISS-II, GEOS-1, GEOS-STRAT,
            ; and FSU models, with pressure on the left Y-axis,
            ; assuming a surface pressure of 1010 mb, for the range
            ; of 1010 mb to 150 mb.

        PLOTSIGMA, $
            ['GISS_II', 'GEOS1', 'GEOS_STRAT', 'FSU' ], $
            YRANGE=[0, 16], SURFP=1010.0

            ; Same as above, but plots with altitude on left Y-axis,
            ; and for the range 0 km - 16 km.


 MODIFICATION HISTORY:
        bmy, 15 Aug 1997: VERSION 1.00
        bmy, 30 Oct 1997: VERSION 1.01
        bmy, 15 Jun 1998: VERSION 1.10
                          - now uses CTM_TYPE, CTM_GRID
        bmy, 17 Jun 1998: GAMAP VERSION 1.20
        bmy, 19 Jun 1998: - add array for color indices
                          - also supports FSU model
        bmy, 03 Jan 2000: GAMAP VERSION 1.44
                          - eliminate call to MYCT and keywords
                          - cosmetic changes
        bmy, 06 Sep 2000: GAMAP VERSION 1.46
                          - added text string for GEOS-3     
        bmy, 26 Jun 2001: GAMAP VERSION 1.48
                          - now pass _EXTRA=e to PLOT command
                          - added extra error checking
        bmy, 23 Jul 2001: - now use MYCT_DEFAULTS() to set up
                            MYCT color information
        bmy, 28 Sep 2002: GAMAP VERSION 1.51
                          - now gets color information from the 
                            !MYCT system variable
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - Modified for GEOS-4 and GEOS-5

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/plotsigma.pro)


READ_EPTOMS

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        READ_EPTOMS

 PURPOSE:
        Read Earth Probe TOMS data as retrieved from 
        http://jwocky.gsfc.nasa.gov and store them as datainfo
        records so that they can be displayed with GAMAP.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        READ_EPTOMS [,DATA] [,keywords]

 INPUTS:

 KEYWORD PARAMETERS:
        FILENAME -> filename of TOMS data

        DATAINFO -> A named variable will return the newly
             created daatinfo structure.

        MODELINFO, GRIDINFO -> named variables will return 
             the "model" and grid information for the EP-TOMS
             data. The grid is a 2-dimensional "generic" grid.

 OUTPUTS:
        DATA -> contains 2D array with EP-TOMS data (for use without
             GAMAP).

 SUBROUTINES:
        uses open_file, ctm_type, ctm_grid, ctm_make_datainfo

 REQUIREMENTS:
        None

 NOTES:
        For tropical ozone in March, I used the following options
        in the call to GAMAP:
           myct,27,ncol=32,bot=20,range=[0.15,0.8]
           c_lev = [150,200,220,230,240,250,260,270,280,  $
                    290,300,310,320,330,340,350,375,400]
           gamap,/nofile,c_lev=c_lev,c_col=[0,17,2*indgen(21)+18],  $
                    /cbar,mlinethick=2,ncolors=32,bottom=18,  $
                    cbmin=220,cbmax=400,div=10  [,frame0=4]
           
           (the frame0 keyword is used to save GIF files)

 EXAMPLE:
        read_eptoms,file='/data/pem-tb/satellite/eptoms/*.ept'
        gamap [... options]

 MODIFICATION HISTORY:
        mgs, 02 Apr 1999: VERSION 1.00
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/read_eptoms.pro)


READ_MLD

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        READ_MLD

 PURPOSE:
        Read Ocean mixed layer depth data as retrieved from 
        http://www.nodc.noaa.gov/OC5/mixdoc.html and store 
        them as datainfo records so that they can be displayed 
        with GAMAP.

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation

 CALLING SEQUENCE:
        READ_MLD [,DATA] [,keywords]

 INPUTS:
        None

 KEYWORD PARAMETERS:
        FILENAME -> filename of MLD data

        DATAINFO -> A named variable will return the newly
             created daatinfo structure.

        MODELINFO, GRIDINFO -> named variables will return 
             the "model" and grid information for the EP-TOMS
             data. The grid is a 2-dimensional "generic" grid.

 OUTPUTS:
        DATA -> contains 2D array with mixed layer depth data 
             (for use without GAMAP).

 SUBROUTINES:
        uses open_file, ctm_type, ctm_grid, ctm_make_datainfo

 REQUIREMENTS:
        None

 NOTES:
        In the call to GAMAP you must use the /NOFILE option.

 EXAMPLE:
        READ_MLD, FILE='~/download/mixed_layer_depth/mld*'
        GAMAP, /NOFILE, ...

 MODIFICATION HISTORY:
        mgs, 30 Jun 1999: VERSION 1.00 (derived from read_eptoms)
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/read_mld.pro)


TEST_MET

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        TEST_MET

 PURPOSE:
        Prints out the name, time, and min/max of data of GMAO or
        GISS/GCAP met data files which are used as input to GEOS-Chem.

 CATEGORY:
        GAMAP Utilities

 CALLING SEQUENCE:
        TEST_MET, MODELINFO [, Keywords ]

 INPUTS:
        MODELINFO -> Structure from CTM_TYPE which defines the model
             name, resolution, and other parameters.  NOTE: If the 
             met field files contain an IDENT string then TEST_MET
             will ignore the MODELINFO structure passed and instead
             will parse the IDENT string to obtain the model name
             and resolution.  (NOTE: GEOS-4, GEOS-5, and GCAP met
             fields contain an identification string which is read in
             to determine the proper model name.  For these met fields
             you won't need to supply MODELINFO.)

 KEYWORD PARAMETERS:
        FILENAME -> Name of the binary met field file to examine.  If 
             FILENAME is not passed, then the user will be prompted
             to supply a file name via a dialog box query.

        /VERBOSE -> If set, then will echo extra information
             to the screen.

        XINDEX -> A 2-element vector containing the minimum and
             maximum longitude indices (in FORTRAN notation) which 
             define the nested model grid.

        YINDEX -> A 2-element vector containing the minimum and
             maximum longitude indices (in FORTRAN notation) which 
             define the nested model grid.

        XRANGE -> A 2-element vector containing the minimum and
             maximum box center longitudes which define the nested
             model grid. Default is [-180,180].

        YRANGE -> A 2-element vector containing the minimum and
             maximum box center latitudes which define the nested
             model grid. Default is [-90,90].

        PLOTLEVEL -> If specified, then TEST_MET will plot a lon-lat
             map of the given vertical level of the data.  Useful for
             debugging purposes.

        _EXTRA=e -> Picks up extra keywords for OPEN_FILE.

 OUTPUTS:
        None

 SUBROUTINES:
        External Subroutines Required:
        ================================
        OPEN_FILE   CTM_GRID (function)

 REQUIREMENTS:
        None

 NOTES:
        None

 EXAMPLE:
        TEST_MET, CTM_TYPE( 'GEOS3', res=2 ), FILE='20010115.i6.2x25'

             ; Prints out information from the 2 x 2.5
             ; GEOS-3 I-6 met field file for 2001/01/15. 

 MODIFICATION HISTORY:
        bmy, 24 May 2005: GAMAP VERSION 2.04
                          - now renamed from "test_dao.pro"
                          - added fields for GISS/GCAP model
                          - now looks for an IDENT string 
        bmy, 12 Dec 2006: GAMAP VERSION 2.06
                          - Modifications for GEOS-5 met fields
                          - Added XINDEX, YINDEX keywords
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
                          - Added extra GEOS-5 fields
        bmy, 21 Feb 2008: GAMAP VERSION 2.12
                          - Now be sure to swap the endian when 
                            opening the file on little-endian 
                            machines
        bmy, 06 Aug 2010: GAMAP VERSION 2.14
                          - Added modifications for MERRA data
        bmy, 17 Aug 2010: - Added SEAICE** fields for MERRA

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/test_met.pro)


TSDIAG

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        TSDIAG

 PURPOSE:
        Reads and plots CTM time series (station) data. The
        data are returned in a structure together with longitude,
        latitude, altitude, and time information. TSDIAG tries to
        construct a time vector from the TAU information stored
        in the file. This may not always work (e.. it is assumed 
        that time steps are 1 hour).
           While reading, TSDIAG displays a '.' for each new station
        encountered, and a '+' if a station is continued. If you want 
        more detailed output, set the /VERBOSE flag.

        %%% NOTE: May need updating %%%

 CATEGORY:
        GAMAP Utilities, GAMAP Data Manipulation, GAMAP Plotting

 CALLING SEQUENCE:
        TSDIAG [,RESULT] [,keywords]

 INPUTS:
        None

 KEYWORD PARAMETERS:
        FILENAME    -> Path of the input file containing CTM 
                       Data data.

        SCALE -> A global scale factor that will be applied to all
                 data. Default is 1. Note that concentration data is
                 stored as v/v, hence for ppt you should set 
                 SCALE=1.E-12.

        /VERBOSE -> display detailed information on what is being read.
                 
        /PLOT -> set this flag to produce quick-and-dirty plots of the 
                 time-series data.

 OUTPUTS:
        RESULT -> A structure containing LON, LAT, ALT and Data data
               together with TRACER and a "global" TIME array.

 SUBROUTINES:
        OPEN_DEVICE               CLOSE_DEVICE
        CTM_TRACERINFO            FILE_EXIST (function)
        STRSCINOT (function)

 REQUIREMENTS:

 NOTES:
        Lines with the Data data (Header = 'TB' or 'DV') will be
        read from disk.  Statistics are ignored for now.

 EXAMPLE:
        ; read time series data from file and return result structure
        ; in variable TSDATA
        tsdiag, TSDATA, FILENAME='ctm.ts' 

 MODIFICATION HISTORY:
        bmy, 06 May 1998: VERSION 1.00
        bmy, 07 May 1998: VERSION 1.01
                          - added PPBC and INTERVAL keywords
                          - now calls FILE_EXIST to make sure
                            the input file exists 
        bmy, 27 May 1998  - now uses CTM_DIAGINFO to return
                            the proper tracer offset
        bmy, 28 May 1998  - now uses SCALE, UNIT, and MOLC information
                            as returned by CTM_TRACERINFO.
                          - now uses EXP_STR to compute a 
                            power-of-ten string for the plot title
        bmy, 29 May 1998  - now calls CLEANPLOT to initialize
                            all system variables
        bmy, 02 Jun 1998  - now uses STRSCI and STRCHEM string
                            formatting functions
        mgs, 11 Jun 1998: - couple of bug fixes
        mgs, 15 Jun 1998: - default tick interval now 48 h
        mgs, 22 Jun 1998: - added Data and CSTEPS keywords
        mgs, 20 Nov 1998: - now uses convert_unit 
        hsu, 22 Mar 1999: - increased MAXSTEPS and changed input format
        mgs, 04 May 1999: - added MS as a tracer offset (100*MS)
        mgs, 05 May 1999: - ... and a little bug fix
        mgs, 19 May 1999: - updated comments
                          - default SCALE factor now 1 instead of 1.E-12
                          - CLEANPLOT no longer called
        mgs, 24 May 1999: - added VERBOSE keyword
                          - fixed at least two bugs
                          - improved output. Now need to say /VERBOSE in
                            order to get details.
        mgs, 25 May 1999: - new format had MS and N swapped.
        bmy, 27 Jul 1999: GAMAP VERSION 1.42
                          - updated comments
        bmy, 30 Jan 2002: GAMAP VERSION 1.50
                          - Now use STRBREAK to split each line into 
                            elements of data
                          - Also no longer restrict data to be > 0
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/tsdiag.pro)


TSPLOT

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        TSPLOT

 PURPOSE:
        Create a plot of station data time series using the
        data structure as returned from TSDIAG.PRO. This routine
        is a simple outline for how to use this structure and 
        not meant to produce publisheable plots. Tip: use
        MULTIPANEL.PRO to save paper.
 
        %%% THIS MAY NOW BE OBSOLETE %%%

 CATEGORY:
        GAMAP Utilities, GAMAP Plotting

 CALLING SEQUENCE:
        TSPLOT, TSSTRU, INDEX, SCALE=SCALE

 INPUTS:
        TSSTRU -> The data structure as returned from TSDIAG.PRO

        INDEX -> A vector with station indices that are to be plotted.
            If no index is given, the program will loop through all 
            records.

 KEYWORD PARAMETERS:
        SCALE -> A scaling factor to be applied to the dat abefore plotting.

 OUTPUTS:
        None

 SUBROUTINES:
        None

 REQUIREMENTS:
        None

 NOTES:
        None

 EXAMPLE:
        ; read station data
        TSDIAG,TSSTRU,FILE='ctm.ts'

        ; set page for 16 panels
        MULTIPANEL, 16

        ; plot data from all stations as pptv
        TSPLOT, TSSTRU, SCALE=1.e12

        ; turn multipanel off
        MULTIPANEL, /OFF

 MODIFICATION HISTORY:
        mgs, 30 Jun 1999: VERSION 1.00
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/tsplot.pro)


TVMAP

[Previous Routine] [Next Routine] [List of Routines]
 NAME:
        TVMAP

 PURPOSE:
        TVMAP produces one of the following plots:
          (1) A color-pixel image,   overlaid with a world map
          (2) A line-contour plot,   overlaid with a world map
          (3) A filled-contour plot, overlaid with a world map

 CATEGORY:
        GAMAP Utilities, GAMAP Plotting

 CALLING SEQUENCE:
        TVMAP, Data, [ Xarr, YArr [ [, keywords ] ]

 INPUTS:
        DATA -> 2-D array of values to be plotted as a color map.
             The first dimension is longitude, the second is latitude.

        XARR, YARR -> If plotting a line-contour map or filled-contour map,
             then XARR is the array of X-axis values, and YARR is the
             array of Y-Axis values that are needed to construct the
             the contours.  XARR and YARR are not needed to produce a
             color-pixel image map; however, if XARR and YARR are
             passed, TVMAP will be able to label the longitude and
             latitude lines accordingly and set the proper default limits.

 KEYWORD PARAMETERS:
        BLACK -> The color index corresponding to black.
             Default is !MYCT.BLACK.

        /CONUS -> a Lambert's azimuthal equal area projection for
             CONtiguous U.S., w/ specific LIMIT and P0lat, P0lon, Rot.

        MAX_VALID -> maximum valid data value for color-pixel plots
             Data above MAX_VALID will be shown in white, unless
             TOPOUTOFRANGE is set to another color index.

        MIN_VALID -> minimum valid data value for color-pixel plots.  
             (or minimum contour level for contour plots).  Data 
             below MIN_VALID will be shown in white, unless
             BOTOUTOFRANGE is set to another color index.

        TOPOUTOFRANGE ( BOTOUTOFRANGE ) -> color index to indicate
             data above MAX_VALID (below MIN_VALID). Default is
             white. The color is also shown with a box (or TRiangle)
             near the colorbar (if any). If negative, the box is not
             shown with the colorbar.

        /NOERASE -> This keyword prevents erasing the screen (or page)
            when setting a multi-panel environment or after a page was
            filled.  /NOERASE is automatically turned ON when the /OFF
            keyword is given.  NOTE: On the PostScript device, when
            the page is filled, it automatically places the next plot
            on the next page.  You can use the /NOERASE keyword to
            suppress this behavior, especially if you are manually
            placing plots on the page.

        CSFAC -> Character size for the map labels and X, Y titles.
             Default settings for CSFAC vary according to the number
             of plots per page and type of plot device.

        TCSFAC -> Character size for the top title.  Default
             settings for TCSFAC vary according to the number
             of plots per page and type of plot device.

        /NOADVANCE -> Set this switch to prevent TVMAP from advancing
             to the next plot panel on the page.  This is useful if
             you desire to overplot something atop the pixel map or
             contour map.

        /POLYFILL -> to use IDL POLYFILL routine instead of MAP_IMAGE
             to do the pixel plot (see /SAMPLE). Use this keyword
             with default cylindrical projection only. Use it also if
             you think that MAP_IMAGE does not neatly reproduces the
             boxes.

        /RECTANGLE -> to plot a rectangle around the map. Default is
             to have one for non-polar projection, and none for polar 
             projection. Set to 0 or 1 to override default.  NOTE:
             setting the /HORIZON keyword will disable this option.

        /SAMPLE -> to do "pixel plot" (ie grid boxes are colored)
             instead of contour. 

        /HORIZON -> Set this switch to call IDL routine MAP_HORIZON
             to draw a horizon line around the boundaries of the map.
             Use this feature if the map projection you are using is
             elliptical or interrupted.  NOTE: /HORIZON will override
             override the /RECTANGLE keyword setting.

        WINDOWPOSITION -> Returns the position of the plot window
             in normal coordinates to the calling program.  This can
             be used by a subsequent call to PLOT if you want to
             overplot symbols atop the contour or pixel plot created
             by TVMAP.

        _EXTRA=e -> Picks up extra keywords (not listed below, unless
             noted) for BYTSCL, COLORBAR, TVIMAGE, MAP_SET, MAP_GRID,
             MAP_CONTINENTS, MAP_LABELS and CONTOUR.

    Keywords passed to both BYTSCL and COLORBAR:
    ============================================
        MAXDATA -> Maximum value of the DATA array to use in the
             byte scaling.  Default is max( DATA ).

        MINDATA -> Minimum value of the DATA array to use in the
             byte scaling.  Default is min( DATA ).

        BOTTOM -> The lowest color index of the colors to be used
             for byte-scaling the color map and colorbar.  Default
             is 20 (or !D.N_COLORS-1 if 20 is too large).

        NCOLORS -> This is the maximum color index that will be used.
             Default is 120 (or !D.N_COLORS-BOTTOM, if 120 is too large).

        /LOG -> Will create a color-pixel plot with logarithmic
             scaling.  /LOG has no effect on line-contour or
             filled-contour plots, since the default contour levels
             are quasi-logarithmic.

    Additional keywords passed to COLORBAR:
    =======================================
        /CBAR -> If set, will plot a horizontal colorbar below the
             map in the position specified by CBPOSITION.  Default is
             to NOT plot a colorbar.

        CBCOLOR -> Color index of the colorbar outline and
             characters.  Defaults to BLACK (see above).

        CBPOSITION -> A four-element array of normalized coordinates
             that specifies the location of the colorbar.  CBPOSITION
             has the same form as the POSITION keyword on a plot.
             Default is [0.1, 0.05, 0.9, 0.08].

        CBUNIT -> Passes the Unit string to COLORBAR, which will be
             plotted to the right of the color bar.

        CBFORMAT -> format to use in call to colorbar. Default is I12
             if abs(max(data)) < 1e4, else e12.2 (strings get trimmed)

        CBMIN, CBMAX -> Explicitly sets the min and max values of
             the colorbar range.  If not set, TVMAP will set
             CBMIN = min( DATA ) and CBMAX = max( DATA ).

        CBTICKLEN -> Specifies the color bar tick length as a
             fraction of the colorbar height (for horizontal
             colorbars) or width (for vertical colorbars).

        CBVERTICAL -> If set, will plot a vertical bar on the right
             side of the map.

        CBSCALE -> If set, then the printed tick labels are scaled by
             powers of 10 to minimize overlap.
 
        DIVISIONS -> Number of labels for the colorbar.  Default is 4.

        /TRIANGLE -> to replace box that indicate Out Of Range data 
             with a triangle.

        TOPLEVELVALUE -> to define the last annotation of the
             colorbar when using the C_LEVELS keyword

    Keywords passed to MAP_SET:
    ===========================
        COLOR -> Color index of the map outline and title characters.
             Defaults to BLACK (see above).

        MPARAM -> A 3 element vector containing values for
             [ P0Lat, P0Lon, Rot ].  Default is [ 0, 0, 0 ].
             Elements not specified are automatically set to zero.

        /ISOTROPIC  -> If set, will produce a map with the same scale
             in the X and Y directions.  Default is not to plot an
             isotropic-scale map. Note, however, that if TVMAP is
             called from CTM_PLOT, the default is to plot a map that
             keeps the aspect ratio (which is about the same as
             isotropic).

        LIMIT -> A four-element vector which specifies the latitude
             and longitude extent of the map.  The elements of LIMIT
             are arranged thus: [ LatMin, LonMin, LatMax, LonMax ].
             Default is to set LIMIT = [ -90, -180, 90, 180 ] (i.e.
             to include the entire globe). P0Lon will be computed
             to fit into the LIMIT range unless it is explicitely
             requested in MParam.

        POLAR -> Plot a polar stereographic projection. If set and
             equal 1 then the plot goes from the pole to a latitude
             defined by either the extend of the data or by the user
             through the LIMIT keyword. If set and equal to 2, then
             the full hemisphere is plot, regardless of the data or
             LIMIT settings.
              Note that setting the /STEREOGRAPHIC keyword wouldn't
             work.

        POSITION -> A four-element array of normalized coordinates
             that specifies the location of the map.  POSITION has
             the same form as the POSITION keyword on a plot.
             Default is [0.0, 0.15, 1.0, 1.0] with Horizontal Color
             Bar, and [0., 0., 0.82, 1.0] with Vertical CBar.

        MARGIN -> specify a margin around the plot in normalized
            coordinates. This keyword does not change any IDL
            system variables and will thus only become "visible"
            if you use the POSITION returned by MULTIPANEL in
            subsequent plot commands.  MARGIN can either be one value
            which will be applied to all four margins, or a 2-element
            vector which results in equal values for the left and
            right and equal values for the bottom and top margins,
            or a 4-element vector with [left,bottom,right,top].  The
            default MARGIN setting is [ 0.05, 0.04, 0.03, 0.07 ].

        OMARGIN -> specify a page margin around all panels in normalized
            coordinates. Works like MARGIN.

        SCALEMAPSET -> To pass the SCALE keyword to MAP_SET.

        TITLE -> The title string that is to be placed atop the
             plot window.  TITLE is passed explicitly to avoid keyword
             name duplication in the _EXTRA=e facility.


    Keywords passed to MAP_LABELS:
    ==================================
    
        LATS, LONS -> Array of latitudes (longitudes) used to
            construct the map labels.  If LATS has one element, the
            LATS vector is build with LATS+n*DLAT, with as n as
            needed to cover the map range. If it has more than one
            element, it is not modified and it is the final grid.

        DLAT, DLON -> Latitude (longitude) interval between grid
            lines. Passed with _extra.


    Keywords passed to MAP_CONTINENTS:
    ==================================
        /CONTINENTS -> If set, will call MAP_CONTINENTS to plot
             continent outlines or filled boundaries.  Default is 0.

        /COUNTRIES -> If set, will call MAP_CONTINENTS to draw the
             political boundaries of countries as of 1993.

        /COASTS -> If set, will call MAP_CONTINENTS to draw the coast
             lines of continental regions.

        CCOLOR -> The color index of the continent outline or fill
             region.  Default is BLACK (see above).

        CFILL -> Value passed to FILL_CONTINENTS keyword of MAP_CONTINENTS.
             If CFILL=1 then will fill continents with a solid color
             (as specified in CCOLOR above).  If CFILL=2 then will fill
             continents with hatching.

        /USA -> Set this switch to turn on US State boundaries.

    Keywords passed to MAP_GRID:
    ============================
        /BOX_AXES -> If set, then MAP_GRID will print alternating
             light & dark regions with the lon & lat labels around
             the border of the plot.  This is passed directly to
             MAP_GRID.  NOTE: BOX_AXES is the default for the CONUS
             option.

        /GRID -> If set, will call MAP_GRID to plot grid lines and
             labels. Labels can be turned off with /NOGLABELS.
             Default is _not_ to plot grid lines.

        GCOLOR -> The color index of the grid lines. Default is
             BLACK (see above).

        /NOGXLABELS -> If set, TVMAP will suppress printing longitude
             labels for each grid line.

        /NOGYLABELS -> If set, TVMAP will suppress printing latitude
             labels for each grid line.

    Keywords passed to CONTOUR:
    ===========================
        /CONTOUR -> Will produce a line-contour map instead of the
             default color-pixel image map.

        /FCONTOUR -> Will produce a filled-contour map instead
             of the default color-pixel image map.

        C_LEVELS -> Vector containing the contour levels.  If not
             specified, will use preset default levels.

        C_ANNOTATION -> Vector containing the contour labels.
             Default is to use string representations of C_LEVELS.

        C_FORMAT -> Format string used in converting C_LEVELS to
             the default C_ANNOTATION values.  Default is '(f8.1)'.

        C_COLORS -> Index array of color levels for contour lines or
             fill regions.  If not specified then will use uniformly
             spaced default color levels.  If C_COLORS is set to a
             scalar value, then all contour lines will have the same
             color value.

        C_LABELS -> Specifies which contour levels should be labeled.
             By default, every other contour level is labeled.  C_LABELS
             allows you to override this default and explicitly
             specify the levels to label. This parameter is a vector,
             converted to integer type if necessary.  If the LEVELS
             keyword is specified, the elements of C_LABELS
             correspond directly to the levels specified, otherwise,
             they correspond to the default levels chosen by the
             CONTOUR procedure. Setting an element of the vector to
             zero causes that contour label to not be labeled.  A
             nonzero value forces labeling.

        /C_LINES -> Will overplot a filled-contour map with contour lines
             and labels instead of plotting a colorbar. This was the old
             default behaviour but has been changed with the advent of
             "discrete" colorbars. The old NOLINES keyword is kept
             for compatibility reasons but doesn't do anything.

        /NOLABELS -> Will suppress printing contour labels on both
             line-contour and filled-contour maps.

        OVERLAYCOLOR -> Color of the solid lines that will be
             overlaid atop a filled contour map.  Default is BLACK.

    Keywords passed to MAP_IMAGE (prior: to REBIN):
    ==============================================
        /SAMPLE -> Used to rebin the byte-scaled image array to a
             larger size.  If /SAMPLE is set, then MAP_IMAGE will use
             nearest-neighbor sampling rather than bilinear
             interpolation. 

    Keyword passed to TVIMAGE:
    ===============================================
        SCALEMAPIMAGE -> Sets the number of pixels per graphic coordinate
             in PostScript and other devices with scalable
             pixels. Larger values produce better resolution output,
             but much larger file sizes. The default value is
             0.04. Use a larger number for higher resolution if your 
             image does not exactly fit on the map projection. 

 OUTPUTS:
        None

 SUBROUTINES:
        External subroutines required:
        ------------------------------
        COLORBAR          ( by Martin Schultz & David Fanning )
        TVIMAGE           ( by David Fanning                  )
        RECTANGLE         ( by Martin Schultz                 )
        CONVERT_LON       ( by Martin Schultz                 )
        INV_INDEX         ( function, by Martin Schultz       )
        MAP_LABELS        ( by Martin Schultz & Bob Yantosca  )
        LOGLEVELS         ( by Martin Schultz                 )
        GET_DEFAULTFORMAT ( by Martin Schultz                 )
        MYCT_DEFAULTS     ( by Bob Yantosca                   )

 REQUIREMENTS:
        Assumes that a MYCT colortable has been loaded.

 NOTES:
        (1) The _EXTRA facility now picks up keywords for multiple
        routines (this is a new feature in IDL v. 5.0+!!)

        (2) Some keywords are saved in local variables with
        slightly different names (e.g. MCONTOUR for /CONTOUR)
        to prevent confusion with routine names and/or keywords
        that are picked up by the _EXTRA=e facility.

        (4) For contour plots, contour labels will be specified
        using the C_ANNOTATION keyword.  The downside is that
        by using C_ANNOTATION, this disables the C_LABELS keyword
        and so one cannot specify which contour lines will get
        labels.  The solution would be to expand the C_LABELS
        vector so that it has the same number of elements as
        C_ANNOTATION, and then to individually zero the
        corresponding elements of C_ANNOTATION before making
        the contour plot.  Don't have enough time for this now,
        but maybe can deal with this at a later time...

        (5) Now references the !MYCT system variable.  This should
        be defined at the start of your IDL session when "myct.pro"
        is called from "idl_startup.pro".

 LIMITATIONS:

       (1) The case of plot over the dateline is working fine only if
       LIMIT[3] is negative and LIMIT[1] is positive. Other cases are
       not specifically handled and results may not be reliable.


       (2) Since we are using MAP_IMAGE, pixel plots do start and end
        at longitude and latitude centers of the grid by default,
        like contour plots. More map coverage is done in three cases:

          (2a) Data sets that cover the globe will fill the map with
          coarse pixel plots.
         
          (2b) Data sets that cover the globe will fill the map only
          in the longitude direction with smooth pixel and contour
          plot. Plots start and stop at the first and last latitudes
          centers.
         
          (2c) Data sets that do not cover the globe will start and
          end at grid edges with coarse pixels, only if the limit of
          the map is less than half grid size away from the the
          first/last latitude and longitude centers. This limitation
          is due to the method used to pad the data outside the
          domain delimited by X/Y arrays.

       (3) MAP_IMAGE assumes that an evenly spaced data set is
       passed. If X or Y array is not evenly spaced, pixels plots are
       flawed and not reliable. Contour plots are ok.

        

 EXAMPLE:
        (1)
        MAXDATA = MAX( DATA, MIN=MINDATA )
        TVMAP, DATA, XMID, YMID,                                  $
               MAXDATA=MAXDATA, MINDATA=MINDATA, CBUNIT='v/v',    $
               /CBAR,           DIVISIONS=4,     FORMAT='(F6.2)', $
               /CONTINENTS,     /GRID,           /ISOTROPIC
               /SAMPLE,         TITLE='O3 at 10 km'

        (2)
        MAXDATA = MAX( DATA, MIN=MINDATA )
        TVMAP, DATA, XMID, YMID,                                  $
               MAXDATA=MAXDATA, MINDATA=MINDATA, CBUNIT='v/v',    $
               /CBAR,           DIVISIONS=4,     FORMAT='(F6.2)', $
               /CONTINENTS,     /GRID,           /ISOTROPIC
               TITLE='O3 at 10 km'

             ; Plots a 2-D "smooth" pixel map.

        (3)
        MAXDATA = MAX( DATA, MIN=MINDATA )
        TVMAP, DATA, XMID, YMID,                                  $
               MAXDATA=MAXDATA, MINDATA=MINDATA, CBUNIT='v/v',    $
               /CBAR,           DIVISIONS=4,     FORMAT='(F6.2)', $
               /CONTINENTS,     /GRID,           /ISOTROPIC       $
               /FCONTOUR,       TITLE='O3 at 10 km',              $
               C_LEVELS=[10,20,30,40,50,60,70,80,90,100]

             ; Plots a 2-D filled contour map.

        (4)
        MAXDATA = MAX( DATA, MIN=MINDATA )
        TVMAP, DATA, XMID, YMID,                                  $
               MAXDATA=MAXDATA, MINDATA=MINDATA, CBUNIT='v/v',    $
               /CBAR,           DIVISIONS=4,     FORMAT='(F6.2)', $
               /CONTINENTS,     /GRID,           /ISOTROPIC       $
               /FCONTOUR,       TITLE='O3 at 10 km',              $
               C_LEVELS=[10,20,30,40,50,60,70,80,90,100],         $
               /NOGXLABELS,     /NOGYLABELS,     /BOX_AXES

             ; Same as Example (3), but prints prints box-style
             ; axes via the /BOX_AXES feature of MAP_GRID.

 MODIFICATION HISTORY:
        bmy, 13 Apr 1998: VERSION 1.00
        bmy, 11 Jun 1998: - now returns if there is
                            nothing to plot
        mgs, 15 Jun 1998: - bug fix: n_elements instead of
                            keyword_set
        bmy, 22 Sep 1998: VERSION 1.10
                          - Now use _EXTRA=e to pass keywords to
                            BYTSCL, TVIMAGE, MAP_SET, and COLORBAR
                          - added MAPTITLE and UNIT keywords to
                            avoid keyword name duplication in
                            _EXTRA=e.
        bmy, 25 Sep 1998: VERSION 2.00
                          - now calls MAP_CONTINENTS and MAP_GRID
                          - keywords renamed for consistency
                          - reduced default size for CBPOSITION
        bmy, 28 Sep 1998: VERSION 2.01
                          - MPOSITION renamed to POSITION, MCOLOR to
                            COLOR, MTITLE to TITLE for consistency
                          - LONSHIFT renamed to LSHIFT to avoid
                            problems with ambiguous keyword names
        bmy, 07 Sep 1998: VERSION 3.00
                          - now can plot contour map or color-pixel
                            map (added CONTOUR and FCONTOUR keywords,
                            and XARR and YARR parameters)
                          - The colorbar is now optional, and is
                            turned on via the /COLORBAR switch.
        bmy, 12 Nov 1998: VERSION 3.01
                          - added ISOTROPIC, SAMPLE, KEEP_ASPECT_RATIO,
                            C_LABELS, and C_FORMAT keywords
                          - now isotropic-scale color-image plots
                            and isotropic-scale contour plots are
                            handled correctly
                          - Use mgs-style default levels & colors for
                            contour and filled-contour maps.
        bmy, 13 Nov 1998: - updated comments
                          - renamed C_LEVELS to C_ANNOTATION to
                            prevent keyword name confusion
                          - added NOLINES, NOLABELS, C_LABELS,
                            and OVERLAYCOLOR keywords
                          - contour lines and labels can be
                            suppressed correctly
                          - added mgs fix so that PostScript
                            pixel-maps appear smoother
                          - a border is now plotted around the
                            map window, without inserting any of that
                            annoying "cushion" space.
                          - added LOG keyword for logarithmic
                            contours and/or pixel colors
                          - use KEYWORD_SET more often
        mgs, 17 Nov 1998: - re-arranged calls to map_set and tvimage
                            in order to maximize size
                          - output of title now seperate from map_set
                          - added CBFormat keyword
        mgs, 19 Nov 1998: - CBFormat now handled in colorbar.pro
        mgs, 20 Nov 1998: - bug fix for map_set for contour plots
        mgs, 03 Dec 1998: - filled continents now added before contours
                          - CFILL keyword checked for consistency
        bmy, 08 Feb 1999: - If /LOG is set, make sure that we don't
                            take the log of zero and incur a math error
                          - add call to function INV_INDEX
        bmy, 23 Feb 1999: - added /GLABELS keyword to turn on/off printing
                            of labels for each grid line on the map
                          - added call to CONVERT_LON for longitudes
                            that straddle the date line
        bmy, 26 Feb 1999: - added LIMIT as an explicit keyword
                          - now uses MAP_LABELS to construct grid labels
                          - updated comments
        bmy, 04 Mar 1999: - added DEBUG keyword for debug output
        mgs, 17 Mar 1999: - some cleaning:
                          - LSHIFT, DLON, and GLABELS made obsolete
                          - new keyword NOGLABELS
                          - P0Lon now computed from LIMIT information.
                          - Updated call to map_labels
                          - For contour plots: XArr, YArr no longer
                            mandatory (although they should be provided)
                          - much smarter default contour levels
        mgs, 22 Mar 1999: - added multi-panel ability through use of
                            the new MULTIPANEL routine. This alters the
                            meaning of MPosition and CB_Position: they now
                            refer to positions in the current plot panel!
        mgs, 23 Mar 1999: - fixed a few minor things
                          - charsize is now adjusted according to number
                            of panels on page
        bmy, 25 Mar 1999: - If CBAR=0, then print unit string below
                            plot (formerly was done in CTM_PLOT)
                          - now use updated GET_DEFAULTFORMAT
                          - updated comments
                          - if NPANELS >=2 then place the plot title
                            higher above the window, to allow for
                            carriage-returned lines
        mgs, 23 Apr 1999: - added CBMin and CBMax keywords for
                            tighter colorbar control
        mgs, 19 May 1999: - title shifted a little higher if it has
                            more than 1 line.
  bmy & mgs, 26 May 1999: - added POLAR keyword and respective support.
        bmy, 27 May 1999: - bug fix for isotropic contour plots
        mgs, 27 May 1999: - added support for discrete colorbars and
                            changed default behaviour for filled
                            contour plots: now plots a colorbar and
                            no lines.
        bmy, 03 Jun 1999: - For polar plots, if the latitude range
                            spans more than 60 degrees, only plot
                            labels for [ 30, 60, 90 ] degrees.
        mgs, 03 Jun 1999: - CFill now also allowed for filled contours
                            or pixel plots (data will be overplotted)
        bmy, 09 Jun 1999: - Set CBUnit to '' if nothing passed
        bmy, 21 Jun 1999: - Added MIN_VALID keyword.
        bmy, 06 Jul 1999: - bug fix for min_valid: ge replaces gt.
        bmy, 07 Jul 1999: - Save C_COLORS in a temp variable.  Also
                            define C_COLORS so that grayscales won't
                            appear in Postscript plots
                          - multi-panel plots are now well-separated
                            from each other (for PostScript output)
        bmy, 08 Jul 1999: - more minor fixes
        bmy, 18 Nov 1999: - increase default left margin by a little
        bmy, 31 Mar 2000: GAMAP VERSION 1.45
                          - make CSFAC and TITLECSFAC into keywords
        bmy, 10 May 2000: - make sure XARR and YARR (if passed) are 1D vectors
                          - now use XARR, YARR to set default limits
                          - rearranged keyword settings code for clarity
                          - added more debug output (when /DEBUG is set)
        bmy, 26 May 2000: - updated comments
        bmy, 13 Jun 2000: - added /COUNTRIES and /COASTS keywords.
                            Setting /COUNTRIES, /COASTS, or /CONTINENTS
                            will now invoke routine MAP_CONTINENTS
        bmy, 30 Jan 2001: GAMAP VERSION 1.47
                          - if NOGLABELS=0 and GRID=0, will print out
                            grid labels w/o printing out grid lines
                          - added MARGIN keyword for MULTIPANEL
                          - also allow coarse plots with /SAMPLE
                            when using the Z-buffer device
        bmy, 07 Jun 2001: - removed some obsolete code & comments
        bmy, 02 Jul 2001: GAMAP VERSION 1.48
                          - added /NOGXLABELS and /NOGYLABELS keywords
                            to suppress printing either lon or lat
                            grid labels, if so desired.
        bmy, 13 Jul 2001: - bug fix: remove _EXTRA=e from MAP_SET call
                            when making pixel plots.  This prevents extra
                            grid lines from being drawn on the map.
        bmy, 23 Jul 2001: - now call MYCT_DEFAULTS to specify default
                            values for BLACK, BOTTOM, NCOLORS, etc
                            if these keywords are not passed explicitly.
        bmy, 31 Oct 2001: GAMAP VERSION 1.49
                          - add /NOADVANCE keyword to prevent advancing
                            to the next page (in case you want to overplot)
        bmy, 08 May 2002: GAMAP VERSION 1.50
                          - If the data array has more than 100,000 elements,
                            then assign it a dithering factor of 1, so that
                            we don't run out of memory when trying to plot it
        bmy, 20 Jun 2002: GAMAP VERSION 1.51
                          - added WINDOWPOSITION keyword to return
                            the position vector of the plot window
                            region to the calling program
        bmy, 28 Sep 2002: - now gets MYCT default parameters from the
                            !MYCT system variable
        bmy, 10 Oct 2002: - bug fix: MCOLOR=!MYCT.BLACK setting has
                            now been restored (was left commented out)
        bmy, 14 Nov 2002: GAMAP VERSION 1.52
                          - If GLABELS=0, then this also sets GXLABELS=0
                            and GYLABELS=0.
                          - Removed obsolete keywords
                          - Removed reference to MYCT_DEFAULTS.
        bmy, 02 Mar 2004: GAMAP VERSION 2.02
                          - added OMARGIN keyword so that we can put
                            an outer margin around all plot panels
        bmy, 28 May 2004: - Now returns the modified value of
                            C_COLORS to the calling program
                          - added CBTICKLEN keyword to specify the
                            color bar tick length
        bmy, 23 Aug 2005: GAMAP VERSION 2.04
                          - added MAX_VALID keyword
                          - now adjust MINDATA to MIN_VALID and
                            MAXDATA to MAX_VALID internally
                          - Now pass _EXTRA=e to XYOUTS
  tmf & bmy, 04 Oct 2006: GAMAP VERSION 2.05
                          - Replace /ERASE keyword with /NOERASE
                            to facilitate manual positioning of
                            plots.  Pass /NOERASE to MULTIPANEL.
  bmy & phs, 18 Sep 2007: GAMAP VERSION 2.10
                          - Don't reset data below MIN_VALID to 
                            MIN_VALID for contour plots
                          - fix MAX_VALID for contour plots.
                          - fix CBar behavior when C_LEVELS is passed
 cdh/phs/bmy 26 Nov 2007: GAMAP VERSION 2.11
                          - do not modify input DATA & X/YARR
                          - add support for VERTICAL COLORBAR
                          - add support for CONUS projection
                          - now all map projections are supported for
                            all 4 types of plots.
                          - now data Latitudes and Longitudes (X/Yarr)
                            are taken into account in Pixel
                            plot: no more need to clip the data
                            before plotting, TVMAP will do it, like
                            it already does for Contour plots.
                          - added Full Hemisphere Polar plot option,
                            regardless of DATA range and LIMIT keyword
                          - added RECTANGLE keyword to overwrite
                            default behavior
                          - map plotting coordinate system active at
                            exit, allowing for easy oplot
                          - default LIMIT for small data set corrected
                          - various fixes for across-the-dateline plots
                          - remove obsolete KEEP_ASPECT_RATIO keyword
                          - add /HORIZON keyword to call MAP_HORIZON
                          - updated comments
        phs, 19 Dec 2007: - new default map limit in case of
                            non-global smooth pixel and contour
                            plots.
                          - plots start and end at box edges in few 
                            new cases.
                          - replace /CENTER with /MINUS_ONE in call
                            to CONGRID
        phs, 12 Feb 2008: GAMAP VERSION 2.12
                          - Fixes for MIN_VALID and MAX_VALID 
                          - The test for the LIMIT keyword is now to check
                            "if ( n_elements(limit) ne 4 )".  This allows you
                            to disable the LIMIT keyword by also setting
                            LIMIT=0.
        phs, 28 Feb 2008: - Couple of small padding improvements
                          - added SCALEMAPSET and SCALEMAPIMAGE to pass
                            their respective SCALE keyword to MAP_SET and
                            MAP_IMAGE.
                          - LONS and LATS keyword added, so the grid can
                            be specified. Work with DLAT and DLON, the
                            grid spacings that can be passed to MAP_LABELS
                            thru the _extra keyword.
  cdh & phs, 21 Mar 2008: - added minimum support for LIMIT input as
                            8-elements vector
        phs, 17 Apr 2008: - Added the TopOutOfRange and BotOutOfRange
                            keywords, so default color (white) for Out-Of
                            -Range data can be overwritten.
        phs,  6 May 2008: - Added the GXLABELS and GYLABELS keywords
                            to specify which grid line to label.
        phs, 19 Jun 2008: - Set default SCALE value for MapImage
                            (ScaleMapImage keyword) to 0.04 if PS device.
        phs, 25 Mar 2009: GAMAP VERSION 2.13
                          - Added NAN_COLOR to specify color to use
                            for NaN and Infinite data 
 cdh, eml, phs, 19 Sep 2009: - Now C_LEVELS works with pixel plots and
                            any projection.
                          - Added LATS, LONS (to specify the grid), and
                            TOPLEVELVALUE (to specify the last level
                            in the colorbar when using C_LEVELS)
                            keywords
                          - fixed limit of CONUS projection
        phs, 29 Oct 2009: GAMAP VERSION 2.14
                          - added the polyfill keyword

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/tvmap.pro)


TVPLOT

[Previous Routine] [List of Routines]
 NAME:
        TVPLOT

 PURPOSE:
        TVPLOT produces one of the following plots:
          (1) A color-pixel image,   overlaid atop X-Y plot axes
          (2) A line-contour plot,   overlaid atop X-Y plot axes
          (3) A filled-contour plot, overlaid atop X-Y plot axes

 CATEGORY:
        GAMAP Utilities, GAMAP Plotting

 CALLING SEQUENCE:
        TVPLOT, Data, Xarr, Yarr, [, keywords ]

 INPUTS:
        DATA -> 2-D array of values to be plotted.
        
        XARR -> array of X-axis (horizontal axis) values needed to
             construct the plot.  The number of elements in XARR must
             equal the number of elements of the first dimension of DATA.

        ZARR -> ZARR is the array of Z-axis (vertical axis) values
             needed to construct the plot.  The number of elements
             in ZARR must equal the number of elements of the second
             dimension of DATA.  If ZARR[0] > ZARR[N_Elements(ZARR)-1]
             then TVPLOT will assume pressure is to be plotted on the
             Y-axis.

 KEYWORD PARAMETERS:
        BLACK -> The color index corresponding to black.
             Default is !MYCT.BLACK (from !MYCT system variable.)

        /NOERASE -> This keyword prevents erasing the screen (or page)
            when setting a multi-panel environment or after a page was
            filled.  /NOERASE is automatically turned ON when the /OFF
            keyword is given.  NOTE: On the PostScript device, when
            the page is filled, it automatically places the next plot
            on the next page.  You can use the /NOERASE keyword to
            suppress this behavior, especially if you are manually
            placing plots on the page.
 
        CSFAC -> Character size for the map labels and plot titles. 
             Default settings for CSFAC vary according to the number 
             of plots per page and type of plot device.

        /NOADVANCE -> Set this switch to prevent TVMAP from advancing
             to the next plot panel on the page.  This is useful if
             you desire to overplot something atop the pixel plot or
             contour plot.

        MARGIN -> specify a margin around the plot in normalized
            coordinates. This keyword does not change any IDL
            system variables and will thus only become "visible"
            if you use the POSITION returned by MULTIPANEL in
            subsequent plot commands.  MARGIN can either be one value
            which will be applied to all four margins, or a 2-element
            vector which results in equal values for the left and
            right and equal values for the bottom and top margins,
            or a 4-element vector with [left,bottom,right,top].  The
            default MARGIN setting is [ 0.05, 0.04, 0.00, 0.02 ].
            -> adds 0.02 to the left margin for Y-axis title
            -> adds 0.03 to the bottom margin for X-axis title
            -> adds 0.03 to the right margin for vertical color bar
            -> adds 0.02 to the top margin for more than 2 plots/page

        OMARGIN -> specify a page margin around all panels in normalized
            coordinates. Works like MARGIN.

        WINDOWPOSITION -> Returns the position of the plot window
             in normal coordinates to the calling program.  This can
             be used by a subsequent call to PLOT if you want to
             overplot symbols atop the contour or pixel plot created
             by TVPLOT.

        _EXTRA=e -> Picks up extra keywords (not listed below) for
             BYTSCL, COLORBAR, TVIMAGE, MAP_SET, MAP_GRID,
             MAP_CONTINENTS, and CONTOUR.


    Keywords for both BYTSCL and COLORBAR:
    ======================================
        MAXDATA -> Maximum value of the DATA array to use in the
             byte scaling.  Default is max( DATA ).

        MINDATA -> Minimum value of the DATA array to use in the
             byte scaling.  Default is min( DATA ).

        BOTTOM -> The lowest color index of the colors to be used
             for byte-scaling the color map and colorbar.  Default 
             is !MYCT.BOTTOM (from the !MYCT system variable).

        NCOLORS -> This is the maximum color index that will be used.
             Default is !MYCT.NCOLOR (from the !MYCT system variable).

        /LOG -> Will create a color-pixel plot with logarithmic
             scaling.  /LOG has no effect on line-contour or
             filled-contour plots, since the default contour levels
             are logarithmic.


    Additional keywords for COLORBAR:
    =================================
        /CBAR -> If set, will plot the colorbar below the map in the 
             position specified by CBPOSITION.  Default is to NOT
             plot a colorbar.
 
        CBCOLOR -> Color index of the colorbar outline and
             characters.  Defaults to BLACK (see above).

        CBPOSITION -> A four-element array of normalized coordinates
             that specifies the location of the colorbar.  CBPOSITION 
             has the same form as the POSITION keyword on a plot. 
             Default is [0.1, 0.05, 0.9, 0.08]. 

        CBUNIT -> Passes the Unit string to COLORBAR, which will be
             plotted to the right of the color bar.

        CBFORMAT -> format to use in call to colorbar. Default is I12
             if abs(max(data)) < 1e4, else e12.2 (strings get trimmed)

        CBMIN, CBMAX -> Explicitly sets the min and max values of
             the colorbar range.  If not set, TVPLOT will set 
             CBMIN = min( DATA ) and CBMAX = max( DATA ).

        CBTICKLEN -> Specifies the color bar tick length as a
             fraction of the colorbar height (for horizontal
             colorbars) or width (for vertical colorbars).

        CBSCALE -> If set, then the printed tick labels are scaled by
             powers of 10 to minimize overlap.
 
        DIVISIONS -> Number of labels for the colorbar.  Default is 4.

        /CBVERTICAL -> Will draw a vertical colorbar instead of
             a horizontal one.  Default is to draw a horizontal
             colorbar.


    Keywords for INTERPOLATION:
    ===========================
    
        /SAMPLE -> Used to get COARSE pixel plot. REBIN is called,
             and uses the nearest-neighbor sampling.
             Note that REBIN is used even if SAMPLE is not set, when
             device is PostScript. It uses the bilinear interpolation
             then.

        /NOZINTERP -> set to switch off the vertical
             interpolation. This can be used only if the ZARR is
             evenly spaced.


    Keywords for PLOT:
    ===================

        BOTOUTOFRANGE -> Color index for data below
             MIN_VALID. Default is white, or last color in color
             table if !MYCT is not defined. If set to negative, the
             color is used in the plot only, and not in the colorbar. 

        POSITION -> A four-element array of normalized coordinates
             that specifies the location of the map.  POSITION has
             the same form as the POSITION keyword on a plot. 
             Default is [0.1, 0.1, 0.9, 0.9]. 

        TITLE -> The title string that is to be placed atop the
             plot window.  TITLE is passed explicitly to avoid keyword
             name duplication in the _EXTRA=e facility.
  
        COLOR -> Color index for the plot window outline and titles.  
             Default is BLACK.

        XSTYLE, YSTYLE -> Style settings for the X and Y axes.  See 
             the "Graphics Keywords" settings man page for more info.
             XSTYLE and YSTYLE are passed as explicit keywords to
             avoid keyword name confusion in the _EXTRA=e facility. 

        XRANGE, YRANGE -> Two-element vectors for the X-axis and Y-axis 
             plot ranges, of the form [Xmin,Xmax] and [YMin,Ymax].
             XRANGE and YRANGE are passed as explicit keywords to
             avoid keyword name confusion in the _EXTRA=e facility. 

        XTITLE, YTITLE -> Titles for the X and Y axes.  XTITLE and 
             YTITLE are passed as explicit keywords to avoid keyword 
             name confusion in the _EXTRA=e facility. 

        NOXLABEL, NOYLABEL -> Suppress printing tick labels for X and Y axes.


    Keywords for CONTOUR:
    =====================
        /CONTOUR -> Will produce a line-contour map instead of the 
             default color-pixel image map.

        /FCONTOUR -> Will produce a filled-contour map instead
             of the default color-pixel image map.

        C_LEVELS -> Vector containing the contour levels.  If not
             specified, will use preset default levels (see below).

        C_ANNOTATION -> Vector containing the contour labels.
             Default is to use string representations of C_LEVELS.

        C_FORMAT -> Format string used in converting C_LEVELS to
             the default C_ANNOTATION values.  Default is '(f8.1)'.

        C_COLORS -> Index array of color levels for contour lines or
             fill regions.  If not specified then will use uniformly
             spaced default color levels.  If C_COLORS is set to a 
             scalar value, then all contour lines will have the same
             color value.

        C_LABELS -> Specifies which contour levels should be labeled.
             By default, every other contour level is labeled.  C_LABELS 
             allows you to override this default and explicitly
             specify the levels to label. This parameter is a vector, 
             converted to integer type if necessary.  If the LEVELS 
             keyword is specified, the elements of C_LABELS
             correspond directly to the levels specified, otherwise, 
             they correspond to the default levels chosen by the 
             CONTOUR procedure. Setting an element of the vector to 
             zero causes that contour label to not be labeled.  A
             nonzero value forces labeling.
 
        /C_LINES -> Will overplot a filled-contour map with contour lines
             and labels instead of plotting a colorbar. This was the old
             default behaviour but has been changed with the advent of
             "discrete" colorbars. The old NOLINES keyword is kept
             for compatibility reasons but doesn't do anything.

        /NOLABELS -> Will suppress printing contour labels on both
             line-contour and filled-contour maps.

        OVERLAYCOLOR -> Color of the solid lines that will be
             overlaid atop a filled contour map.  Default is BLACK.


 OUTPUTS:
        None

 SUBROUTINES:
        External Subroutines Required:
        ==================================================
        COLORBAR              GET_DEFAULTFORMAT (function)        
        INV_INDEX (function)  LOGLEVELS (function)  
        TVIMAGE          
        
 REQUIREMENTS:
        Assumes that a MYCT colortable has been loaded.

 NOTES:
        (1) The _EXTRA facility picks extra keywords for BYTSCL,
            TVIMAGE, PLOT and COLORBAR, etc...  This is a new 
            feature in IDL v. 5.0+!! 

        (2) For contour plots, contour labels will be specified
            using the C_ANNOTATION keyword.  The downside is that
            by using C_ANNOTATION, this disables the C_LABELS keyword
            and so one cannot specify which contour lines will get
            labels.  The solution would be to expand the C_LABELS
            vector so that it has the same number of elements as
            C_ANNOTATION, and then to individually zero the
            corresponding elements of C_ANNOTATION before making
            the contour plot.  Don't have enough time for this now,
            but maybe can deal with this at a later time...

 EXAMPLE:
        POSITION   = [0.1, 0.1,  0.9, 0.9 ] ; position for map
        CBPOSITION = [0.1, 0.05, 0.9, 0.08] ; position for colorbar

        TVPLOT, DATA, XARR, YARR,                           $
               MAXDATA=MAXDATA,    MINDATA=MINDATA,         $
               POSITION=POSITION,  CBPOSITION=CBPOSITION,   $
               /ERASE,             TITLE='Avg O3',          $
               XTITLE='Longitude', YTITLE='Altitude',       $
               DIVISIONS=4,        FORMAT='(F6.2)'

 MODIFICATION HISTORY:
        bmy, 27 Apr 1998:  VERSION 1.00
        bmy, 04 Jun 1998:  - now can plot separate X or Y axes
                             if [XY]STYLE = 4 or 8
        mgs, 15 Jun 1998:  - bug fix n_elements instead of keyword_set
                           - now does spline interpolation in the
                             vertical in order to get correct
                             altitudes
        bmy, 21 Sep 1998:  - Rename EXTRA1, EXTRA2, etc, to names
                             that have more meaning (e.g. E_BYT for
                             BytScl, E_TV for TVImage, etc.)
        bmy, 22 Sep 1998:  VERSION 1.10
                           - now uses _EXTRA=e facility to pass extra
                             keywords to BYTSCL, TVIMAGE, PLOT, and
                             COLORBAR.
                           - add PLOTTITLE (for PLOT) and UNIT (for
                             COLORBAR) keywords to prevent keyword
                             name duplication in _EXTRA=e.
        mgs, 11 Nov 1998:  - added CBar keyword
        bmy, 16 Nov 1998:  VERSION 2.00
                           - now can produce line-contour and filled-
                             contour plots as well as image plots
                           - now calls REBIN to rebin the byte-scaled
                             image array to higher resolution for
                             PostScript output.
                           - added the following keywords: /LOG,
                             /SAMPLE, /CONTOUR, /FCONTOUR, C_ANNOTATION,
                             C_LEVELS, C_LABELS, /NOLABELS, /NOLINES, 
        bmy, 17 Nov 1998:  - For image plots, now only display plot axes
                             AFTER the image plot has been made.  This
                             reduces the "apparent" wait time for the 
                             user.
                           - renamed keywords to XA_TITLE, XA_RANGE, 
                             XA_TICKNAME, etc to avoid keyword name
                             duplication in the _EXTRA=e facility.
        mgs, 17 Nov 1998:  - added CBFormat keyword
        bmy, 18 Nov 1998:  - also added floating point format for 
                             CBFORMAT when abs(max(Data)) < 10
        mgs, 19 Nov 1998:  - CBFormat no whandled in colorbar.pro
        bmy, 27 Jan 1999:  - added defaults for XRANGE and YRANGE
        bmy, 08 Jan 1999:  - If /LOG is set, make sure that we don't
                             take the log of zero and incur a math error
                           - add call to function INV_INDEX  
        mgs, 18 Mar 1999:  - cleaned up
                           - now uses loglevels and has smarter default 
                             contour levels
        mgs, 22 Mar 1999:  - added multi-panel ability through use of
                             the new MULTIPANEL routine. This alters the
                             meaning of MPosition and CB_Position: they now
                             refer to positions in the current plot panel!
        mgs, 23 Mar 1999:  - fixed a few minor things
                           - charsize is now adjusted according to number
                             of panels on page
        bmy, 25 Mar 1999:  - now use updated GET_DEFAULTFORMAT
                           - if NPANELS >=2 then place the plot title
                             higher above the window, to allow for 
                             carriage-returned lines
                           - updated comments
        bmy, 27 Apr 1999:  - commented out !x.charsize=csfac and
                             !y.charsize=csfac lines...these messed
                             up the plot window sizes
                           - updated comments
        bmy, 28 Apr 1999:  - added CBMin and CBMax keywords for 
                             tighter colorbar control
        mgs, 19 May 1999: - title shifted a little higher if it has
                            more than 1 line.
        mgs, 21 May 1999: - variable name for TITLE now MTITLE as in
                            TVMAP.
        mgs, 27 May 1999: - changed default behaviour for filled contours:
                            now plots "discrete" colorbar and no lines.
                            Keyword NoLines changed to C_Lines.
        bmy, 10 Jun 1999: - CBUnit defaults to '
        mgs, 06 Jul 1999: - adjusted charsize for multipanel plots
        bmy, 07 Jul 1999: - Save C_COLORS in a temp variable.  Also
                            define C_COLORS so that grayscales won't
                            appear in Postscript plots
                          - multi-panel plots are now well-separated
                            from each other (for PostScript output)
        bmy, 08 Jul 1999: - more minor fixes
        bmy, 18 Nov 1999: - increase default left margin by a little
        bmy, 31 Mar 2000: GAMAP VERSION 1.45
                          - made CSFAC a keyword
        bmy, 23 Jul 2001: GAMAP VERSION 1.48
                          - now call MYCT_DEFAULTS to specify default
                            values for BLACK, BOTTOM, NCOLORS, etc
                            if these keywords are not passed explicitly.
        bmy, 07 Jul 2001: - removed obsolete code from 1998 and 1999
        bmy, 31 Oct 2001: GAMAP VERSION 1.49
                          - add /NOADVANCE keyword to prevent advancing
                            to the next page (in case you want to overplot)
        bmy, 28 Sep 2002: GAMAP VERSION 1.51
                          - now gets MYCT default parameters from the
                            !MYCT system variable
        bmy, 15 Nov 2002: GAMAP VERSION 1.52
                          - Added MIN_VALID keyword to skip missing
                            data values for pixel plots
        bmy, 18 Dec 2003: - For pixel plots, now linearly interpolate
                            when creating NDATA instead of using a
                            cubic spline.  This is more accurate.
                          - Prevent NDATA from being extrapolated wildly
                            due to the slope at the surface and top level
                            of the plot.  
        bmy, 06 Jan 2003: - Now interpolate NDATA correctly when pressure
                            or altitude is on the Y-axis.
                          - Removed obsolete keywords XA_TITLE, YA_TITLE,
                          - XA_RANGE, YA_RANGE, XA_TICKNAME, YA_TICKNAME
                          - Now define default YRANGE = [ ZBOT, ZTOP ]
                            to make Y-axis labels correct for both pressure
                            and altitude on the Y-axis.
                          - Removed ZBOT, ZTOP from the keyword list; 
                            these are now internal variables. 
                          - updated comments
        bmy, 02 Mar 2004: GAMAP VERSION 2.02
                          - added MARGIN keyword a la TVMAP
                          - added OMARGIN keyword
        bmy, 28 May 2004: - Now returns the modified value of
                            C_COLORS to the calling program
                          - added CBTICKLEN keyword to specify the
                            color bar tick length
        bmy, 30 Nov 2004: GAMAP VERSION 2.03
                          - added WINDOWPOSITION keyword  
        bmy, 12 Jul 2005: GAMAP VERSION 2.04
                          - added /ISOTROPIC keyword
                          - added /NOZINTERP keyword to prevent interpolation
                            to a fine grid of 100 pts in the vertical dim.
  bmy & phs, 13 Jul 2007: GAMAP VERSION 2.10
  bmy & phs, 26 Nov 2007: GAMAP VERSION 2.11
                          - Minor fix for margins w/ for new TVIMAGE
                          - Also reset !P.MULTI=0 when using TVIMAGE
                            so that it will use the internally computed
                            position vector.  Reset after TVIMAGE call.
                          - Make sure to label last colorbar division
                            for contour plots
                          - Vertical colorbar options and MIN_VALID, 
                            MAX_VALID keywords are the same as TVMAP
                          - Extra space is now added to the default
                            MARGIN values for vertical colorbar
                            and multiple plots per page.
                          - Adjust default CBPOSITION values such
                            that the colorbar will be placed either
                            0.05 below or 0.02 to the right of the plot
        phs, 04 Apr 2008: GAMAP VERSION 2.12
                          - now produces a better coarse pixel plot
                            for altitude vs latitude or longitude
                            plots, even though the initial box size
                            is not exactly reproduced. 
 cdh, eml, phs, 24 Sep 2009: GAMAP VERSION 2.13
                          - fixes for LOG10 plots
                          - new improved interpolation scheme in Z
                            direction
                          - C_LEVELS works with /SAMPLE
                          - added checks on NAN when looking at
                            min/max, added NAN_COLOR to specify a
                            color for NaN
                          - added BOTOUTOFRANGE to set color of data
                            below Min_Valid
                          - check if !MYCT is defined
 xyue & bmy, 24 Jan 2011: GAMAP VERSION 2.15
                          - Replace /ERASE keyword with /NOERASE
                            to facilitate manual positioning of
                            plots.  Pass /NOERASE to MULTIPANEL.
                            This is now consistent w/ TVMAP.

(See /n/home09/ryantosca/IDL/gamap2/gamap_util/tvplot.pro)