Main Page Other Stuff (FORTRAN)
## Table of Contents
       Other Stuff (FORTRAN)
          Overview
          Note About HTML Links
          References
             Tutorials
             Required Readings
             The Permuted Index
             API Documentation
          Kernels Used
          SPICE Modules Used

       NAIF Documentation
             Required Reading and Users Guides
             HTML format documentation
             Library Source Code Documentation
             API Documentation
          Text kernels
             Text kernel format

       Lesson 1: Kernel Management with the Kernel Subsystem
          Task Statement
          Learning Goals
          Code Solution
             First, create a meta text kernel:
             Now the solution source code:
             Run the code example

       Lesson 2: The Kernel Pool
          Task Statement
          Learning Goals
          Code Solution
             Run the code example
          Related Routines

       Lesson 3: Coordinate Conversions
          Task Statement
          Learning Goals
          Code Solution
             Run the code example
          Related Routines

       Lesson 4: Advanced Time Manipulation Routines
          Task Statement
          Learning Goals
          Code Solution
             Run the code example

       Lesson 5: Error Handling
          Task Statement
          Learning Goals
          Code Solution
             Run the code example
          Task Statement
          Learning Goals
          Code Solution
             Run the code example
          Relevant Routines:

       Lesson 6: Windows, and Cells
          Programming task
          Learning Goals
          Code Solution
             Run the code example
          Related Routines

       Lesson 7: Utility and Constants Routines
          Task Statement
          Learning Goals
          Code Solution
             Run the code example
          Task Statement
          Code Solution
             Run the code example
          Related Routines
Top # Other Stuff (FORTRAN) March 01, 2023 The extensive scope of the SPICE system's functionality includes features the average user may not expect or appreciate, features NAIF refers to as "Other Stuff." This workbook includes a set of lessons to introduce the beginning to moderate user to such features. The lessons provide a brief description to several related sets of routines, associated reference documents, a programming task designed to teach the use of the routines, and an example solution to the programming problem. Top ## Overview This workbook contains lessons to demonstrate use of the less celebrated SPICE routines. `1.` Kernel Management with the Kernel Subsystem `2.` The Kernel Pool `3.` Coordinate Conversions `4.` Advanced Time Manipulation Routines `5.` Error Handling `6.` Windows and Cells `7.` Utility and Constants Routines Top ## Note About HTML Links The HTML version of this lesson contains links pointing to various HTML documents provided with the Toolkit. All of these links are relative and, in order to function, require this document to be in a certain location in the Toolkit HTML documentation directory tree. In order for the links to be resolved, if not done already by installing the lessons package under the Toolkit's ``doc/html'' directory, create a subdirectory called ``lessons'' under the ``doc/html'' directory of the ``toolkit/'' tree and copy this document to that subdirectory before loading it into a Web browser. Top ## References This section lists SPICE documents referred to in this lesson. Of these documents, the ``Tutorials'' contains the highest level descriptions with the least number of details while the ``Required Reading'' documents contain much more detailed specifications. The most complete specifications are provided in the ``API Documentation''. Top ### Tutorials The following SPICE tutorials serve as references for the discussions in this lesson:
       Name              Lesson steps/routines it describes
       ----------------  -----------------------------------------------
       concepts          Concepts of space geometry and time
       intro_to_kernels  Using kernels, meta-kernels
       time              Time systems, conversions and formats
       lsk_and_sclk      LSK and SCLK
       derived_quant     "high-level" observation geometry computations
       other_functions   Intro to some SPICE "low level" computations
       exceptions        built-in mechanism for trapping/handling errors
These tutorials are available from the NAIF server at JPL:
       https://naif.jpl.nasa.gov/naif/tutorials.html
Top ### Required Readings The Required Reading documents are provided with the Toolkit and are located under the ``toolkit/doc'' directory in the SPICE Toolkit installation tree.
       Name             Lesson steps/routines that it describes
       ---------------  -----------------------------------------
       cells.req        The SPICE cell data type
       error.req        The SPICE error handling system
       kernel.req       Loading SPICE kernels
       time.req         Time conversion
       windows.req      The SPICE window data type
Top ### The Permuted Index Another useful document distributed with the Toolkit is the permuted index. It is located under the ``toolkit/doc'' directory in the FORTRAN installation tree. This text document provides a simple mechanism by which users can discover which SPICE routines perform functions of interest, as well as the names of the source files that contain these routines. It is particularly useful for FORTRAN programmers because some of the routines are entry points; the names of these routines do not translate directly into the name of the respective source files that contain them. Top ### API Documentation The most detailed specification of a given SPICE FORTRAN routine is contained in the header section of its source code. The source code is distributed with the Toolkit and is located under the ``toolkit/src/spicelib'' path. For example the path of the source code of the STR2ET routine is
       toolkit/src/spicelib/str2et.for
Since some of the FORTRAN routines are entry points they may be part of a source file that has different name. The ``Permuted Index'' document mentioned above can be used to locate the name of their source file. Top ## Kernels Used The following kernels are used in examples provided in this lesson:
       #  FILE NAME    TYPE DESCRIPTION
       -- ------------ ---- ------------------------------------------------
       1  naif0008.tls LSK  Generic LSK
       2  de405s.bsp   SPK  Planet Ephemeris SPK
       3  pck00008.tpc PCK  Generic PCK
These SPICE kernels are included in the lesson package. Top ## SPICE Modules Used This section provides a complete list of the routines and kernels that are suggested for usage in each of the exercises in this lesson. (You may wish to not look at this list unless/until you ``get stuck'' while working on your own.)
       CHAPTER EXERCISE   ROUTINES   FUNCTIONS  KERNELS
       ------- ---------  ---------  ---------  ----------
          1    kpool      FURNSH                1-3
                          KTOTAL
                          KDATA
                          UNLOAD

          2    kervar     FURNSH     LASTNB     1-3
                          GNPOOL     EQSTR
                          DTPOOL
                          GDPOOL
                          GCPOOL

          3    coord      FURNSH     DPR        1-3
                          PROMPT
                          STR2ET
                          BODVRD
                          SPKPOS
                          RECRAD
                          RECLAT
                          RECSPH
                          RECGEO

          4    xtic       FURNSH     JYEAR      1
                          STR2ET
                          TIMOUT
                          TPICTR
                          TSETYR

          5    errsys     CHKIN      FAILED
                          ERRACT
                          PROMPT
                          CHKOUT
                          SETMSG
                          ERRDP
                          ERRINT
                          ERRCH
                          SIGERR

               aderr      ERRACT     EQSTR      1-3
                          FURNSH     FAILED
                          PROMPT
                          SPKEZR
                          RESET

          6    win        FURNSH     CARDD      1-3
                          STR2ET     SIZED
                          WNVALD
                          WNINTD
                          TOSTDO
                          WNFETD
                          ET2UTC
                          WNSUMD

          7    units      TKVRSN     EQSTR
                          PROMPT
                          CONVRT

               xconst                SPD
                                     DPR
                                     RPD
                                     CLIGHT
                                     J2100
                                     J2000
                                     TYEAR
                                     HALFPI
Refer to the headers of the various routines listed above, as detailed interface specifications are provided with the source code. Top # NAIF Documentation The technical complexity of the various SPICE subsystems mandates an extensive, user-friendly documentation set. The set differs somewhat depending on your choice of development language but provides the same information with regards to SPICE operation. The sources for a user needing information concerning SPICE are: `--` Required Readings and Users Guides `--` Library Source Code Documentation `--` API Documentation `--` Tutorials Top ### Required Reading and Users Guides NAIF Required Reading (*.req) documents introduce the functionality of particular SPICE subsystems:
       abcorr.req
       cells.req
       ck.req
       daf.req
       das.req
       dla.req
       dsk.req
       ek.req
       ellipses.req
       error.req
       frames.req
       gf.req
       kernel.req
       naif_ids.req
       pck.req
       planes.req
       problems.req
       rotation.req
       scanning.req
       sclk.req
       sets.req
       spc.req
       spk.req
       symbols.req
       time.req
       windows.req
NAIF Users Guides (*.ug) describe the proper use of particular SPICE tools:
       brief.ug
       chronos.ug
       ckbrief.ug
       commnt.ug
       convert.ug
       dskbrief.ug
       dskexp.ug
       frmdiff.ug
       inspekt.ug
       mkdsk.ug
       mkspk.ug
       msopck.ug
       simple.ug
       spacit.ug
       spkdiff.ug
       spkmerge.ug
       states.ug
       subpt.ug
       tictoc.ug
       tobin.ug
       toxfr.ug
       version.ug
These text documents exist in the 'doc' directory of the main Toolkit directory:
          ../toolkit/doc/
Top ### HTML format documentation The SPICE distributions include HTML versions of Required Readings and Users Guides, accessible from the HTML documentation directory:
          ../toolkit/doc/html/index.html
Top ### Library Source Code Documentation All SPICELIB and CSPICE source files include usage and design information incorporated in a comment block known as the "header." (Every toolkit includes either the SPICELIB or CSPICE library.) A header consists of several marked sections: `--` Procedure: Routine name and one line expansion of the routine's name. `--` Abstract: A tersely worded explanation describing the routine. `--` Copyright: An identification of the copyright holder for the routine. `--` Required_Reading: A list of SPICE required reading documents relating to the routine. `--` Brief_I/O: A table of arguments, identifying each as either input, output, or both, with a very brief description of the variable. `--` Detailed_Input & Detailed_Output: An elaboration of the Brief_I/O section providing comprehensive information on argument use. `--` Parameters: Description and declaration of any parameters (constants) specific to the routine. `--` Exceptions: A list of error conditions the routine detects and signals plus a discussion of any other exceptional conditions the routine may encounter. `--` Files: A list of other files needed for the routine to operate. `--` Particulars: A discussion of the routine's function (if needed). This section may also include information relating to "how" and "why" the routine performs an operation and to explain functionality of routines that operate by side effects. `--` Examples: Descriptions and code snippets concerning usage of the routine. `--` Restrictions: Restrictions or warnings concerning use. `--` Literature_References: A list of sources required to understand the algorithms or data used in the routine. `--` Author_and_Institution: The names and affiliations for authors of the routine. `--` Version: A list of edits and the authors of those edits made to the routine since initial delivery to the SPICE system. The source code for SPICE products is stored in 'src' sub-directory of the main SPICE directory:
          ../toolkit/src/
Find the SPICELIB library source code in:
          ../toolkit/src/spicelib/
Top ### API Documentation The SPICELIB package includes the SPICELIB Reference Guide, an index of all SPICELIB APIs with hyperlinks to API specific documentation. Each API documentation page includes cross-links to any other wrapper API mentioned in the document and links to the wrapper source code.
          ...spicelib/doc/html/spicelib/index.html
Top ## Text kernels Several workbooks use SPICE text kernels. SPICE identifies a text kernel as an ASCII text file containing the mark-up tags the kernel subsystem requires to identify data assignments in that file, and "name=value" data assignments. The subsystem uses two tags:
          \begintext
and
          \begindata
to mark information blocks within the text kernel. The \begintext tag specifies all text following the tag as comment information to be ignored by the subsystem. Things to know: `1.` The \begindata tag marks the start of a data definition block. The subsystem processes all text following this marker as SPICE kernel data assignments until finding a \begintext marker. `2.` The kernel subsystem defaults to the \begintext mode until the parser encounters a \begindata tag. Once in \begindata mode the subsystem processes all text as variable assignments until the next \begintext tag. `3.` Enter the tags as the only text on a line, i.e.:
          \begintext

             ... commentary information on the data assignments ...

          \begindata

             ... data assignments ...
`4.` CSPICE delivery N0059 added to the CSPICE and Icy text kernel parsers the functionality to read non native text kernels, i.e. a Unix compiled library can read a MS Windows native text kernel, a MS Windows compiled library can read a Unix native text kernel. Mice acquires this capability from CSPICE. `5.` With regards to the FORTRAN distribution, as of delivery N0057 the FURNSH call includes a line terminator check, signaling an error on any attempt to read non-native text kernels. Top ### Text kernel format Scalar assignments.
          VAR_NAME_DP  = 1.234
          VAR_NAME_INT = 1234
          VAR_NAME_STR = 'FORBIN'
Please note the use of a single quote in string assignments. Vector assignments. Vectors must contain the same type data.
          VEC_NAME_DP  = ( 1.234   , 45.678  , 901234.5 )
          VEC_NAME_INT = ( 1234    , 456     , 789      )
          VEC_NAME_STR = ( 'FORBIN', 'FALKEN', 'ROBUR'  )

          also

          VEC_NAME_DP  = ( 1.234,
                          45.678,
                          901234.5 )

          VEC_NAME_STR = ( 'FORBIN',
                           'FALKEN',
                           'ROBUR' )
Time assignments.
          TIME_VAL = @31-JAN-2003-12:34:56.798
          TIME_VEC = ( @01-DEC-2004, @15-MAR-2004 )
The at-sign character '@' indicates a time string. The pool subsystem converts the strings to double precision TDB (a numeric value). Please note, the time strings must not contain embedded blanks. WARNING - a TDB string is not the same as a UTC string. The above examples depict direct assignments via the '=' operator. The kernel pool also permits incremental assignments via the '+=' operator. Please refer to the kernels required reading, kernel.req, for additional information. Top # Lesson 1: Kernel Management with the Kernel Subsystem Top ## Task Statement Write a program to load a meta kernel, interrogate the SPICE system for the names and types of all loaded kernels, then demonstrate the unload functionality and the resulting effects. Top ## Learning Goals This lesson demonstrates use of the kernel subsystem to load, unload, and list loaded kernels. This lesson requires creation of a SPICE meta kernel. Top ## Code Solution Top ### First, create a meta text kernel: You can use two versions of a meta kernel with code examples (kpool.tm) in this lesson. Either a kernel with explicit path information:
       KPL/MK

       \begindata

          KERNELS_TO_LOAD = ( 'kernels/spk/de405s.bsp',
                              'kernels/pck/pck00008.tpc',
                              'kernels/lsk/naif0008.tls' )

       \begintext
... or a more generic meta kernel using the PATH_VALUES/PATH_SYMBOLS functionality to declare path names as variables:
       KPL/MK

          Define the paths to the kernel directory. Use the PATH_SYMBOLS
          as aliases to the paths.

          The names and contents of the kernels referenced by this
          meta-kernel are as follows:

             File Name        Description
             ---------------  ------------------------------
             naif0008.tls     Generic LSK.
             de405s.bsp       Planet Ephemeris SPK.
             pck00008.tpc     Generic PCK.

       \begindata

          PATH_VALUES     = ( 'kernels/lsk',
                              'kernels/spk',
                              'kernels/pck' )

          PATH_SYMBOLS    = ( 'LSK', 'SPK', 'PCK' )

          KERNELS_TO_LOAD = ( '$LSK/naif0008.tls',
                              '$SPK/de405s.bsp',
                              '$PCK/pck00008.tpc' )

       \begintext
Top ### Now the solution source code:
             PROGRAM KPOOL
             IMPLICIT NONE

       C
       C     Declare the needed variables:
       C
             CHARACTER*(32) META
             CHARACTER*(32) FILE
             CHARACTER*(32) TYPE
             CHARACTER*(32) SOURCE

             INTEGER        COUNT
             INTEGER        I
             INTEGER        HANDLE

             LOGICAL        FOUND

       C
       C     Assign the path name of the meta kernel to META.
       C
             META = 'kpool.tm'

       C
       C     Load the meta kernel then use KTOTAL to interrogate the
       C     SPICE kernel subsystem for the total number of loaded kernel
       C     files. KTOTAL accepts as input values:
       C
       C                   SPK  --- all SPK files are counted in the total.
       C                   CK   --- all CK files are counted in the total.
       C                   PCK  --- all binary PCK files are counted in
       C                            the total.
       C                   EK   --- all EK files are counted in the total.
       C                   TEXT --- all text kernels that are not
       C                            meta-text kernels are included in the
       C                            total.
       C                   META --- all meta-text kernels are counted in
       C                            the total.
       C                   ALL  --- every type of kernel is counted in the
       C                            total.
       C
       C     We want the count of all kernels, so use 'ALL'.
       C
             CALL FURNSH ( META )
             CALL KTOTAL ( 'ALL', COUNT )

             WRITE(*,'(A,I1)') 'Kernel count after load:        ', COUNT

       C
       C     Loop over the number of files; interrogate the SPICE system
       C     with KDATA for the kernel names, kernel source,
       C     and the type. 'FOUND' returns a boolean indicating whether
       C     any kernel files of the specified type were loaded by
       C     the kernel subsystem. This example ignores checking 'FOUND'
       C     as kernels are known to be loaded.
       C
             DO I=1, COUNT

                CALL KDATA ( I, 'ALL', FILE, TYPE, SOURCE, HANDLE,
            .                FOUND )

                WRITE(*,*) 'File   ', FILE
                WRITE(*,*) 'Type   ', TYPE
                WRITE(*,*) 'Source ', SOURCE
                WRITE(*,*) ' '

             END DO

       C
       C     Unload one kernel then check the count.
       C
             CALL UNLOAD ( 'kernels/spk/de405s.bsp' )
             CALL KTOTAL ( 'ALL', COUNT )

       C
       C     The subsystem should report one less kernel.
       C
             WRITE(*,'(A,I1)') 'Kernel count after one unload:  ', COUNT

       C
       C     Now unload the meta kernel. This action unloads all
       C     files listed in the meta kernel.
       C
             CALL UNLOAD ( META )

       C
       C     Check the count. SPICE should return a count of zero.
       C
             CALL KTOTAL ( 'ALL', COUNT )
             WRITE(*,'(A,I1)') 'Kernel count after meta unload: ', COUNT

             END
Top ### Run the code example First we see the number of all loaded kernels returned from the KTOTAL call. Then the KDATA loop returns the name of each loaded kernel, the type of kernel (SPK, CK, TEXT, etc.) and the source of the kernel - the mechanism that loaded the kernel. The source either identifies a meta kernel, or contains an empty string. An empty source string indicates a direct load of the kernel with a FURNSH call.
       Kernel count after load:        4
        File   kpool.tm
        Type   META
        Source

        File   kernels/lsk/naif0008.tls
        Type   TEXT
        Source kpool.tm

        File   kernels/spk/de405s.bsp
        Type   SPK
        Source kpool.tm

        File   kernels/pck/pck00008.tpc
        Type   TEXT
        Source kpool.tm

       Kernel count after one unload:  3
       Kernel count after meta unload: 0
Top # Lesson 2: The Kernel Pool Top ## Task Statement Write a program to retrieve particular string and numeric text kernel variables, both scalars and arrays. Interrogate the kernel pool for assigned variable names. Top ## Learning Goals The lesson demonstrates the SPICE system's facility to retrieve different types of data (string, numeric, scalar, array) from the kernel pool. For the code examples, use this generic text kernel (kervar.tm) containing PCK-type data, kernels to load, and example time strings:
       KPL/MK

          Name the kernels to load. Use path symbols.

          The names and contents of the kernels referenced by this
          meta-kernel are as follows:

             File Name        Description
             ---------------  ------------------------------
             naif0008.tls     Generic LSK.
             de405s.bsp       Planet Ephemeris SPK.
             pck00008.tpc     Generic PCK.

       \begindata

          PATH_VALUES     = ('kernels/spk',
                             'kernels/pck',
                             'kernels/lsk')

          PATH_SYMBOLS    = ('SPK' , 'PCK' , 'LSK' )

          KERNELS_TO_LOAD = ( '$SPK/de405s.bsp',
                              '$PCK/pck00008.tpc',
                              '$LSK/naif0008.tls')

       \begintext

       Ring model data.

       \begindata

          BODY699_RING1_NAME     = 'A Ring'
          BODY699_RING1          = (122170.0 136780.0 0.1 0.1 0.5)

          BODY699_RING1_1_NAME   = 'Encke Gap'
          BODY699_RING1_1        = (133405.0 133730.0 0.0 0.0 0.0)

          BODY699_RING2_NAME     = 'Cassini Division'
          BODY699_RING2          = (117580.0 122170.0 0.0 0.0 0.0)

       \begintext

       The kernel pool recognizes values preceded by '@' as time
       values. When read, the kernel subsystem converts these
       representations into double precision ephemeris time.

       Caution: The kernel subsystem interprets the time strings
       identified by '@' as TDB. The same string passed as input
       to @STR2ET is processed as UTC.

       The three expressions stored in the EXAMPLE_TIMES array represent
       the same epoch.

       \begindata

          EXAMPLE_TIMES       = ( @APRIL-1-2004-12:34:56.789,
                                  @4/1/2004-12:34:56.789,
                                  @JD2453097.0242684
                                 )

       \begintext
The main references for pool routines are found in the source file pool.f, most pool routines exist in pool.f as entry points, or the API documentation for the particular routines. Top ## Code Solution
             PROGRAM KERVAR
             IMPLICIT NONE

       C
       C     Note, the pool routines return a boolean to 'FOUND'
       C     signaling whether the requested variable name exists
       C     in the kernel pool. The code solutions do not check the
       C     boolean value since the solutions use variables known to
       C     exist. In general, code should always check the boolean
       C     value to ensure return of valid data.
       C

       C
       C     Define the max number of kernel variables
       C     of concern for this examples.
       C
             INTEGER                     N_ITEMS
             PARAMETER                  (N_ITEMS = 20 )

       C
       C     Define the maximum length for any string.
       C
             INTEGER                     STRLEN
             PARAMETER                  (STRLEN = 80 )

       C
       C     As usual, type our variables...
       C
             INTEGER                     I
             INTEGER                     J
             INTEGER                     DIM
             INTEGER                     N_VAR
             INTEGER                     N_VAL
             INTEGER                     START

             LOGICAL                     FOUND

             DOUBLE PRECISION            DVARS    (N_ITEMS)

             CHARACTER* (STRLEN)         CVALS    (N_ITEMS)
             CHARACTER* (STRLEN)         CVARS    (N_ITEMS)
             CHARACTER* (12)             TYPE
             CHARACTER* (12)             TMPLATE

       C
       C     ...and two SPICELIB routines we use.
       C
             INTEGER                     LASTNB
             LOGICAL                     EQSTR

       C
       C     Load the example kernel containing the kernel variables.
       C     The kernels defined in KERNELS_TO_LOAD load into the
       C     kernel pool with this call.
       C
             CALL FURNSH ('kervar.tm' )

       C
       C     Initialize the START value. This values indicates
       C     index of the first element to return if a kernel
       C     variable is an array. START = 1 mean return everything.
       C     START = 2 indicates return everything but the first element.
       C
             START = 1

       C
       C     Set the template for the variable names to find. Let's
       C     look for all variables containing  the string RING.
       C     Define this with the wildcard template '*RING*'. Note:
       C     the template '*RING' would match any variable name
       C     ending with the RING string.
       C
             TMPLATE =  '*RING*'

       C
       C     We're ready to interrogate the kernel pool for
       C     the variables matching the template. GNPOOL tells us:
       C
       C        1. Does the kernel pool contain any variables that
       C           match the template (value of FOUND).
       C        2. If so, how many variables? (value of N_VAL)
       C        3. The variable names. (CVALS, an array of strings)
       C
             CALL GNPOOL ( TMPLATE, START, STRLEN, N_VAL, CVALS, FOUND )

             IF ( FOUND ) THEN
                WRITE(*,'(A,I1)') 'Number variables matching template: ',
            .                     N_VAL
                WRITE(*,*)
             ELSE
                 WRITE(*,*) 'No kernel variables matched template'
                 STOP
             ENDIF

       C
       C     Okay, now we know something about the kernel pool
       C     variables of interest to us. Let's find out more...
       C
             DO I=1, N_VAL

       C
       C        Use DTPOOL to return the dimension and TYPE,
       C        C (character) or N (numeric), of each pool
       C        variable name in the CVALS array.
       C
       C        The SPICE function LASTNB returns the index of
       C        the last non-blank character in the CVALS string.
       C        This is convenient to trim the trailing whitespace
       C        of a string.
       C
                CALL DTPOOL ( CVALS(I), FOUND, DIM, TYPE )
                WRITE(*,'(A)') CVALS(I)(1:LASTNB(CVALS(I)) )
                WRITE(*,'(A,I1,2A)') ' Number items: ', DIM,
            .                        '   Of type: ',    TYPE

       C
       C        Use the EQSTR routine to test character equality,
       C        'N' (numeric) or 'C' (character).
       C
                IF ( EQSTR( 'N', TYPE ) ) THEN

       C
       C           If TYPE equals 'N', we found a numeric array.
       C           In this case any numeric array will be an array
       C           of double precision numbers ("doubles"). GDPOOL
       C           retrieves doubles from the kernel pool. DVARS
       C           contains the array of N_VAR values.
       C
                   CALL GDPOOL ( CVALS(I), START, N_ITEMS,
            .                                     N_VAR  , DVARS, FOUND )
                   DO J=1 ,N_VAR
                      WRITE(*,'(A,F20.6)') '  Numeric value: ', DVARS(J)
                   END DO

                ELSE IF ( EQSTR( 'C', TYPE ) ) THEN

       C
       C           If TYPE equals 'C', we found a string array.
       C           GCPOOL retrieves string values from the
       C           kernel pool. CVARS contains the array of N_VAR
       C           values.
       C
                   CALL GCPOOL ( CVALS(I), START, N_ITEMS,
            .                                     N_VAR, CVARS, FOUND )
                   DO J=1 ,N_VAR
                      WRITE(*,*) '  String value: ',
            .                    CVARS(J)(1:LASTNB(CVARS(J)) )
                   END DO

                END IF

                WRITE(*,*)

             END DO

       C
       C     Now look at the time variable EXAMPLE_TIMES. Extract this
       C     value as an array of doubles.
       C
             CALL GDPOOL ( 'EXAMPLE_TIMES', START, N_ITEMS,
            .                               N_VAR  , DVARS, FOUND )

             WRITE(*,*) 'EXAMPLE_TIMES'

             DO J=1 ,N_VAR
                WRITE(*,'(A,F20.6)') '  Time value:    ', DVARS(J)
             END DO

             END
Top ### Run the code example The program runs and first reports the number of kernel pool variables matching the template, 6. The program then loops over the DTPOOL 6 times, reporting the name of each pool variable, the number of data items assigned to that variable, and the variable type. Within the DTPOOL loop, a second loop outputs the contents of the data variable using GCPOOL or GDPOOL.
       Number variables matching template: 6

       BODY699_RING1_1
        Number items: 5   Of type: N
         Numeric value:        133405.000000
         Numeric value:        133730.000000
         Numeric value:             0.000000
         Numeric value:             0.000000
         Numeric value:             0.000000

       BODY699_RING1
        Number items: 5   Of type: N
         Numeric value:        122170.000000
         Numeric value:        136780.000000
         Numeric value:             0.100000
         Numeric value:             0.100000
         Numeric value:             0.500000

       BODY699_RING2
        Number items: 5   Of type: N
         Numeric value:        117580.000000
         Numeric value:        122170.000000
         Numeric value:             0.000000
         Numeric value:             0.000000
         Numeric value:             0.000000

       BODY699_RING1_1_NAME
        Number items: 1   Of type: C
          String value: Encke Gap

       BODY699_RING2_NAME
        Number items: 1   Of type: C
          String value: Cassini Division

       BODY699_RING1_NAME
        Number items: 1   Of type: C
          String value: A Ring

        EXAMPLE_TIMES
         Time value:        134094896.789000
         Time value:        134094896.789000
         Time value:        134094896.789753
Note the final time value differs from the previous values in the final three decimal places despite the intention that all three strings represent the same time. This results from round-off when converting a decimal Julian day representation to the seconds past J2000 ET representation. Top ## Related Routines `--` GIPOOL retrieves integer values from the kernel subsystem. Top # Lesson 3: Coordinate Conversions Top ## Task Statement Write a program to convert a Cartesian 3-vector representing some location to the other coordinate representations. Use the position of the Moon with respect to Earth in an inertial and non-inertial reference frame as the example vector. Top ## Learning Goals The SPICE system provides functions to convert coordinate tuples between Cartesian and various non Cartesian coordinate systems including conversion between geodetic and rectangular coordinates. This lesson presents these coordinate transform routines for rectangular, cylindrical, and spherical systems. Top ## Code Solution
             PROGRAM COORD
             IMPLICIT NONE

       C
       C     Type the variables.
       C
             INTEGER              DIM

             CHARACTER*(32)       INRFRM
             CHARACTER*(32)       NONFRM
             CHARACTER*(32)       TIMSTR

             DOUBLE PRECISION     ET
             DOUBLE PRECISION     RANGE
             DOUBLE PRECISION     RA
             DOUBLE PRECISION     DEC
             DOUBLE PRECISION     LAT
             DOUBLE PRECISION     COLAT
             DOUBLE PRECISION     LON
             DOUBLE PRECISION     LTIME
             DOUBLE PRECISION     FLAT
             DOUBLE PRECISION     RAD   (3)
             DOUBLE PRECISION     POS   (3)

       C
       C    Declare the SPICELIB function to scale radians to degrees.
       C
             DOUBLE PRECISION     DPR

             INRFRM = 'J2000'
             NONFRM = 'IAU_EARTH'

       C
       C     Load the needed kernels using a FURNSH call on a
       C     meta kernel.
       C
             CALL FURNSH ( 'coord.tm' )

       C
       C     Prompt the user for a time string. Convert the
       C     time string to ephemeris time J2000 (ET).
       C
             CALL PROMPT ( 'Time of interest: ', TIMSTR )
             CALL STR2ET ( TIMSTR, ET )

       C
       C     Access the kernel pool data for the triaxial radii of the
       C     Earth. 'RAD(1)' holds the equatorial radius, 'RAD(2)'
       C     the polar radius.
       C
             CALL BODVRD ( 'EARTH', 'RADII', 3, DIM, RAD)

       C
       C     Calculate the flattening factor for the Earth.
       C
       C              equatorial_radius - polar_radius
       C     flat =   ________________________________
       C
       C                    equatorial_radius
       C
             FLAT = (RAD(1) - RAD(3))/RAD(1)

       C
       C     Make the SPKPOS call to determine the apparent position
       C     of the Moon w.r.t. to the Earth at ET in the inertial frame.
       C
             CALL SPKPOS ( 'MOON', ET, INRFRM, 'LT+S','EARTH',
            .               POS  , LTIME)

       C
       C     Show the current frame and time.
       C
             WRITE(*,'(2A)') ' Time : ', TIMSTR
             WRITE(*,'(2A)') '  Inertial Frame: ', INRFRM

       C
       C     First, convert the position vector
       C     X = POS(1), Y = POS(2), Z = POS(3), to RA/DEC.
       C
             CALL RECRAD ( POS, RANGE, RA, DEC )
             WRITE(*,'(A)') '   Range/Ra/Dec'
             WRITE(*,'(A,F20.6)') '    Range: ', RANGE
             WRITE(*,'(A,F20.6)') '    RA   : ', RA * DPR()
             WRITE(*,'(A,F20.6)') '    DEC  : ', DEC* DPR()

       C
       C     ...latitudinal coordinates...
       C
             CALL RECLAT ( POS, RANGE, LON, LAT )
             WRITE(*,'(A)') '   Latitudinal'
             WRITE(*,'(A,F20.6)') '    Rad  : ', RANGE
             WRITE(*,'(A,F20.6)') '    Lon  : ', LON * DPR()
             WRITE(*,'(A,F20.6)') '    Lat  : ', LAT * DPR()

       C
       C     ...spherical coordinates use the colatitude,
       C     the angle from the Z axis.
       C
             CALL RECSPH ( POS, RANGE, COLAT, LON )
             WRITE(*,'(A)') '   Spherical'
             WRITE(*,'(A,F20.6)') '    Rad  : ', RANGE
             WRITE(*,'(A,F20.6)') '    Lon  : ', LON   * DPR()
             WRITE(*,'(A,F20.6)') '    Colat: ', COLAT * DPR()

       C
       C     Make the SPKPOS call to determine the apparent position
       C     of the Moon w.r.t. to the Earth at ET in the non-inertial,
       C     body fixed, frame.
       C
             CALL SPKPOS ( 'MOON', ET, NONFRM, 'LT+S','EARTH',
            .               POS, LTIME)

             WRITE(*,*)
             WRITE(*,'(2A)') '  Non-inertial Frame: ', NONFRM

       C
       C     ...latitudinal coordinates...
       C
             CALL RECLAT ( POS, RANGE, LON, LAT )
             WRITE(*,'(A)') '   Latitudinal'
             WRITE(*,'(A,F20.6)') '    Rad  : ', RANGE
             WRITE(*,'(A,F20.6)') '    Lon  : ', LON * DPR()
             WRITE(*,'(A,F20.6)') '    Lat  : ', LAT * DPR()

       C
       C     ...spherical coordinates...
       C
             CALL RECSPH ( POS, RANGE, COLAT, LON )
             WRITE(*,'(A)') '   Spherical'
             WRITE(*,'(A,F20.6)') '    Rad  : ', RANGE
             WRITE(*,'(A,F20.6)') '    Lon  : ', LON   * DPR()
             WRITE(*,'(A,F20.6)') '    Colat: ', COLAT * DPR()

       C
       C     ...finally, convert the position to geodetic
       C     coordinates.
       C
             CALL RECGEO ( POS, RAD(1), FLAT, LON, LAT, RANGE )
             WRITE(*,'(A)') '   Geodetic'
             WRITE(*,'(A,F20.6)') '    Rad  : ', RANGE
             WRITE(*,'(A,F20.6)') '    Lon  : ', LON * DPR()
             WRITE(*,'(A,F20.6)') '    Lat  : ', LAT * DPR()

             WRITE(*,*)

             END
Top ### Run the code example Input "Feb 3 2002 TDB" to calculate the Moon's position. (the 'TDB' tag indicates a Barycentric Dynamical Time value).
       Time of interest: Feb 3 2002 TDB
Examine the Moon position in the J2000 inertial frame, display the time and frame:
        Time : Feb 3 2002 TDB
         Inertial Frame: J2000
Convert the Moon Cartesian coordinates to right ascension declination.
          Range/Ra/Dec
           Range:        369340.815193
           RA   :           203.643686
           DEC  :            -4.979010
Latitudinal. Note the difference in the expressions for longitude and right ascension though they represent a measure of the same quantity. The RA/DEC system measures RA in the interval [0,2Pi). Latitudinal coordinates measures longitude in the interval (-Pi,Pi].
          Latitudinal
           Rad  :        369340.815193
           Lon  :          -156.356314
           Lat  :            -4.979010
Spherical. Note the difference between the expression of latitude in the Latitudinal system and the corresponding Spherical colatitude. The spherical coordinate system uses the colatitude, the angle measure away from the positive Z axis. Latitude is the angle between the position vector and the x-y (equatorial) plane with positive angle defined as toward the positive Z direction
          Spherical
           Rad  :        369340.815193
           Lon  :          -156.356314
           Colat:            94.979010
The same position look-up in a body fixed (non-inertial) frame, IAU_EARTH.
         Non-inertial Frame: IAU_EARTH
Latitudinal coordinates return the geocentric latitude.
          Latitudinal
           Rad  :        369340.815193
           Lon  :            70.986950
           Lat  :            -4.989675
Spherical.
          Spherical
           Rad  :        369340.815193
           Lon  :            70.986950
           Colat:            94.989675
Geodetic. The cartographic lat/lon.
          Geodetic
           Rad  :        362962.836755
           Lon  :            70.986950
           Lat  :            -4.990249
Top ## Related Routines `--` LATREC, latitudinal to rectangular `--` LATCYL, latitudinal to cylindrical `--` LATSPH, latitudinal to spherical `--` RECCYL, rectangular to cylindrical `--` SPHREC, spherical to rectangular `--` SPHCYL, spherical to cylindrical `--` SPHLAT, spherical to latitudinal `--` CYLLAT, cylindrical to latitudinal `--` CYLSPH, cylindrical to spherical `--` CYLREC, cylindrical to rectangular `--` GEOREC, geodetic to rectangular Top # Lesson 4: Advanced Time Manipulation Routines Top ## Task Statement Demonstrate the advanced functions of the time utilities with regard to formatting of time strings for output. Formatting options include altering calendar representations of the time strings. Convert time-date strings between different SPICE-supported formats. Top ## Learning Goals Introduce the routines used for advanced manipulation of time strings. Understand the concept of ephemeris time (ET) as used in SPICE. Top ## Code Solution Caution: Be sure to assign sufficient string lengths for time formats/pictures.
             PROGRAM XTIC
             IMPLICIT NONE

       C
       C     Declare the needed variables:
       C
             CHARACTER*(256)     ERROR
             CHARACTER*(32)      META
             CHARACTER*(50)      PICTR1
             CHARACTER*(50)      PICTR2
             CHARACTER*(50)      PICTR3
             CHARACTER*(50)      TIMSTR

             DOUBLE PRECISION    ET
             DOUBLE PRECISION    ET1
             DOUBLE PRECISION    ET2
             DOUBLE PRECISION    JYEAR

             LOGICAL             OK

       C
       C     Assign the META variable to the name of the meta-kernel
       C     that contains the LSK kernel and create an arbitrary
       C     time string.
       C
             META   = 'xtic.tm'
             TIMSTR = 'Mar 15, 2003 12:34:56.789 AM PST'

       C
       C     Load the meta-kernel.
       C
             CALL FURNSH ( META )

             WRITE(*,'(2A)') 'Original time string     : ', TIMSTR

       C
       C     Convert the time string to the number of ephemeris
       C     seconds past the J2000 epoch. This is the most common
       C     internal time representation used by the SPICE
       C     system; SPICE refers to this as ephemeris time (ET).
       C
             CALL STR2ET ( TIMSTR, ET )
             WRITE(*,'(A,F20.6)') 'Corresponding ET         : ', ET

       C
       C     Make a picture of an output format. Describe a Unix-like
       C     time string then send the picture and the ET value through
       C     TIMOUT to format and convert the ET representation of
       C     the time string into the form described by PICTR1. The
       C     '::UTC-7' token indicates the time zone for the TIMSTR
       C     output - PDT. 'PDT' is part of the output, but not a time
       C     system token.
       C
             PICTR1 = 'Wkd Mon DD HR:MN:SC PDT YYYY ::UTC-7'
             CALL TIMOUT ( ET, PICTR1, TIMSTR )
             WRITE(*,'(2A)') 'Time in string format 1  : ', TIMSTR

       C
       C     Create another picture. This time combine a calendar,
       C     2 digit year, with a Julian Day format.
       C
             PICTR2 = 'Wkd Mon DD HR:MN ::UTC-7 YR (JULIAND.##### JDUTC)'
             CALL TIMOUT ( ET, PICTR2, TIMSTR )
             WRITE(*,'(2A)') 'Time in string format 2  : ', TIMSTR

       C
       C     Why create a picture by hand when SPICE can do it for you?
       C     Input a string to TPICTR with the format of interest.
       C     'OK' returns a boolean indicating whether an error
       C     occurred while parsing the picture string, if so,
       C     an error diagnostic message returns in 'ERROR'. In this
       C     example, no need exists to check the error flag since
       C     the picture string is known as correct.
       C
             CALL TPICTR ( '12:34:56.789 P.M. PDT January 1, 2006',
            .              PICTR3, OK, ERROR )

       C
       C     Confirm the TPICTR call succeeded. Report the error string
       C     if not.
       C
             IF( .NOT. OK ) THEN
                WRITE(*,*)
                WRITE(*,*) 'Error in TPICTR call: '
                WRITE(*,*)  ERROR
                STOP
             END IF

             CALL TIMOUT ( ET, PICTR3, TIMSTR )
             WRITE(*,'(2A)') 'Time in string format 3  : ', TIMSTR

       C
       C     Two digit year representations often cause problems due to
       C     the ambiguity of the century. The routine TSETYR gives the
       C     user the ability to set a default range for 2 digit year
       C     representation. SPICE uses 1969AD as the default start
       C     year so the numbers inclusive of 69 to 99 represent
       C     years 1969AD to 1999AD, the numbers inclusive of 00 to 68
       C     represent years 2000AD to 2068AD.
       C
       C     Define a time string with  a two-digit year. Since
       C     the SPICE base year is 1969, the time subsystem interprets
       C     the string as 1979.
       C
             TIMSTR = 'Mar 15, 79 12:34:56'
             CALL STR2ET ( TIMSTR, ET1 )

       C
       C     Setting 1980 as the base year causes SPICE to interpret the
       C     year values 80 to 99 as 1980AD to 1999AD; the year values
       C     00 to 79 as 2000AD to 2079AD.
       C
             CALL TSETYR ( 1980 )
             CALL STR2ET ( TIMSTR, ET2 )

       C
       C     Calculate the number of years between the two ET
       C     representations, ~100.
       C
             WRITE(*,'(A,F20.6)') 'Years between evaluations: ',
            .                     (ET2 - ET1)/JYEAR()

             END
Top ### Run the code example
       Original time string     : Mar 15, 2003 12:34:56.789 AM PST
       Corresponding ET         :     100989360.974561
       Time in string format 1  : Sat Mar 15 01:34:56 PDT 2003
       Time in string format 2  : Sat Mar 15 01:34  03 (2452713.85760 JDUTC)
       Time in string format 3  : 01:34:56.789 A.M. PDT March 15, 2003
       Years between evaluations:           100.000000
Top # Lesson 5: Error Handling Top ## Task Statement Show the behavior of the various error modes by writing a program to signal an error, check for an error signal, set the long and short error strings, set error behavior (DEFAULT, RETURN, ABORT, RETURN). Top ## Learning Goals This lesson introduces the basics of the error subsystem and its various the response modes: DEFAULT, RETURN, ABORT, RETURN, IGNORE, the error output modes: SHORT, LONG, EXPLAIN TRACEBACK, DEFAULT, ALL, NONE, and the error traceback message. Top ## Code Solution
             PROGRAM ERRSYS
             IMPLICIT NONE

       C
       C     Define needed variables.
       C
             CHARACTER*(32)    ERRCON

             LOGICAL           DOLOOP
             LOGICAL           FAILED

             DOLOOP         = .TRUE.

       C
       C     Check into the error subsystem to create a traceback
       C     showing the call tree. A CHKOUT must balance every
       C     CHKIN.
       C
             CALL CHKIN( 'ERRSYSF' )

       C
       C     Before we start, what's the initial (default)
       C     error state? ERRACT both sets the state and
       C     reports the state.
       C
             CALL ERRACT ( 'GET', ERRCON )
             WRITE(*,'(2A)') 'Default error state: ', ERRCON

       C
       C     Now start an input loop so we can try different
       C     settings for error modes.
       C
             DO WHILE ( DOLOOP )

       C
       C        Again use ERRACT to retrieve the current error mode.
       C
                CALL ERRACT ( 'GET', ERRCON )
                WRITE(*,'(2A)') 'Current error state: ', ERRCON

       C
       C        Okay, input one of the response settings strings
       C        then set the error subsystem mode to that value.
       C
                CALL PROMPT ( 'Set error condition (DEFAULT, REPORT, '
            .              // 'ABORT, RETURN, IGNORE): ', ERRCON )
                CALL ERRACT ( 'SET', ERRCON )

       C
       C        Cause an error signal.
       C
                CALL DOERR

       C
       C        Check for an error signal via a call to FAILED.
       C        At this point we see an important difference
       C        between the error mode's responses to an error
       C        signal.
       C
                IF ( .NOT. FAILED() ) THEN

                   WRITE(*,'(2A)') 'No error signal noted.'

                ELSE

                   WRITE(*,'(2A)') 'Error signal noted.'

                END IF

             END DO

       C
       C     Check out of the error subsystem tho' we'll
       C     never hit this call.
       C
             CALL CHKOUT ( 'ERRSYSF' )

             STOP
             END

       C
       C     This subroutine initiates a SPICE error signal.
       C
             SUBROUTINE DOERR

       C
       C     Check into the error subsystem as before.
       C
             CALL CHKIN( 'DOERR' )

       C
       C     Let's signal an error. The string passed by SETMSG
       C     is the long error message. You may place markers in the
       C     long message string then later substitute other data
       C     items for those markers.
       C
             CALL SETMSG ( 'A truly horrendous event occurred '
            .          //  'during execution of this program. '
            .          //  'Data added to long error message string: '
            .          //  'A double #, an int #, and a string #.' )

       C
       C     Now substitute other data into the long message string.
       C     Note the substitutions work on the first found marker.
       C
             CALL ERRDP ( '#', 186282.397D0 )
             CALL ERRINT( '#', 666          )
             CALL ERRCH ( '#', 'A STRING'   )

       C
       C     SIGERR causes the error signal with the string passed
       C     from SETMSG. Set the error flag in the SPICE error
       C     subsystem and execute the proper error response.
       C
             CALL SIGERR ( 'OOPS(SOMETHINGBAD)' )

             CALL CHKOUT( 'DOERR' )

             RETURN
             END
Top ### Run the code example o- Demo the "DEFAULT" mode:
       Default error state: DEFAULT
       Current error state: DEFAULT
The subsystem is in error state DEFAULT. Let the subsystem run to the error signal in DEFAULT mode:
       Set error condition (DEFAULT, REPORT, ABORT, RETURN, IGNORE): DEFAULT
What subsystem reaction occurs in this state?
       =====================================================================
       ===========

       Toolkit version: N0067

       OOPS(SOMETHINGBAD) --

       A truly horrendous event occurred during execution of this program. D
       ata added
       to long error message string: A double 1.8628239700000E+05, an int 66
       6, and a
       string A STRING.

       A traceback follows.  The name of the highest level module is first.
       ERRSYSF --> DOERR

       Oh, by the way:  The SPICELIB error handling actions are USER-TAILORA
       BLE.  You
       can choose whether the Toolkit aborts or continues when errors occur,
        which
       error messages to output, and where to send the output.  Please read
       the ERROR
       "Required Reading" file, or see the routines ERRACT, ERRDEV, and ERRP
       RT.

       =====================================================================
       ===========
Notice we see no error signal status line. The program quit when it signaled an error. The program output the error messages, an additional information blurb ("Oh by the way"), the Toolkit version, and the traceback list. o- Rerun the program in "REPORT" mode:
       Default error state: DEFAULT
       Current error state: DEFAULT
       Set error condition (DEFAULT, REPORT, ABORT, RETURN, IGNORE): REPORT

       =====================================================================
       ===========

       Toolkit version: N0067

       OOPS(SOMETHINGBAD) --

       A truly horrendous event occurred during execution of this program. D
       ata added
       to long error message string: A double 1.8628239700000E+05, an int 66
       6, and a
       string A STRING.

       A traceback follows.  The name of the highest level module is first.
       ERRSYSF --> DOERR

       =====================================================================
       ===========
       Error signal noted.
       Current error state: REPORT
       Set error condition (DEFAULT, REPORT, ABORT, RETURN, IGNORE):
The error output ceases after the traceback then returns into the calling routine. Note the error signal marker indicates detection of the signal. The subsystem in REPORT mode does not print the information blurb. The SPICE system can continue to run after an error signal with the error state set to REPORT - this mode flags an error then allows the program to continue the run. It may happen that the cause of the error condition causes instability in the SPICE system. o- Rerun to test "ABORT" mode:
       Default error state: DEFAULT
       Current error state: DEFAULT
       Set error condition (DEFAULT, REPORT, ABORT, RETURN, IGNORE): ABORT
How does the subsystem respond in ABORT mode?
       =====================================================================
       ===========

       Toolkit version: N0067

       OOPS(SOMETHINGBAD) --

       A truly horrendous event occurred during execution of this program. D
       ata added
       to long error message string: A double 1.8628239700000E+05, an int 66
       6, and a
       string A STRING.

       A traceback follows.  The name of the highest level module is first.
       ERRSYSF --> DOERR

       =====================================================================
       ===========
ABORT responds quite like DEFAULT except the error output does not include the information blurb shown in the DEFAULT output. All execution stops when the error signals. o- Run the program to demo the "RETURN" mode:
       Default error state: DEFAULT
       Current error state: DEFAULT
       Set error condition (DEFAULT, REPORT, ABORT, RETURN, IGNORE): RETURN
RETURN mode provides the highest measure of flexibility to deal with error signals. On output:
       =====================================================================
       ===========

       Toolkit version: N0067

       OOPS(SOMETHINGBAD) --

       A truly horrendous event occurred during execution of this program. D
       ata added
       to long error message string: A double 1.8628239700000E+05, an int 66
       6, and a
       string A STRING.

       A traceback follows.  The name of the highest level module is first.
       ERRSYSF --> DOERR

       =====================================================================
       ===========
       Error signal noted.
       Current error state: RETURN
The subroutine signals an error then returns similar to REPORT mode. However, this mode includes another property. If we make another pass through the command loop:
       Set error condition (DEFAULT, REPORT, ABORT, RETURN, IGNORE): return
       Error signal noted.
       Current error state: RETURN
We see no error output. The main property of the RETURN mode is to allow program execution to continue but immediately return from all SPICE routines that check the state of the RETURN function. This mode restricts program flow after an error signal. o- And the final mode to test, "IGNORE":
       Default error state: DEFAULT
       Current error state: DEFAULT
       Set error condition (DEFAULT, REPORT, ABORT, RETURN, IGNORE): IGNORE
       No error signal noted.
       Current error state: IGNORE
       Set error condition (DEFAULT, REPORT, ABORT, RETURN, IGNORE):
No error output, no error signal. IGNORE mode prevents expression of all error subsystem functions; the subsystem does not set RETURN or FAILED. While using IGNORE mode the user cannot identify an error signal. Carefully consider program requirements before any use of IGNORE mode. Top ## Task Statement Write an interactive program to return a state vector based on a user's input. Code the program with the capability to recover from user input mistakes, inform the user of the mistake, then continue to run. Top ## Learning Goals Learn how to write a program that has the capability to recover from expected SPICE errors. Top ## Code Solution
             PROGRAM ADERR
             IMPLICIT NONE

       C
       C     Declare our variables.
       C
             CHARACTER*( 32 )    TARG

             LOGICAL             DOLOOP
             LOGICAL             EQSTR
             LOGICAL             FAILED

             DOUBLE PRECISION    STATE(6)
             DOUBLE PRECISION    LTIME

       C
       C     First important action. The DEFAULT error setting
       C     in the SPICE system displays an error message when
       C     an error signals then quits the program. We want the
       C     error message, but no 'quit.'
       C
       C     The RETURN mode signals an error then returns to the
       C     caller. Just what we need. REPORT mode performs almost
       C     the same function as RETURN, however RETURN mode
       C     sets the RETURN() value to TRUE and so the program does
       C     not execute those SPICE routines that check the RETURN()
       C     value. Consider REPORT mode useful for debugging.
       C
             CALL ERRACT( 'SET', 'RETURN'  )

       C
       C     Load the data we need for state evaluation.
       C
             CALL FURNSH( 'aderr.tm' )

       C
       C     Set a flag to start/stop and continue the
       C     inquiry loop.
       C
             DOLOOP     = .TRUE.

       C
       C     Start our input query loop to the user.
       C
             DO WHILE ( DOLOOP )

       C
       C        For simplicity, we request only one input.
       C        The program calculates the state vector from
       C        Earth to the user specified target (TARG) in the
       C        J2000 frame, at ephemeris time zero, using
       C        aberration correction LT+S (light time plus
       C        stellar aberration).
       C
                CALL PROMPT ( 'Target: ', TARG )

                IF (  EQSTR( TARG, 'NONE' ) ) THEN

       C
       C           An exit condition. If the user inputs NONE
       C           for a target name, set the loop to stop...
       C
                   DOLOOP = .FALSE.

                ELSE

       C
       C           ...otherwise evaluate the state between the Earth
       C           and the target.
       C
                   CALL SPKEZR ( TARG, 0.D0, 'J2000', 'LT+S', 'EARTH',
            .                    STATE, LTIME )

       C
       C           What if the program can't perform the evaluation?
       C           Since we set the error subsystem to RETURN we know
       C           a failed SPKEZR call sets the FAILED flag to
       C           TRUE then returns control to the calling routine.
       C           The SPICE system also outputs an error message
       C           informing the user of the problem's cause.
       C
       C           Examine the state of FAILED() to determine if we
       C           output a state vector or not.
       C
                   IF ( .NOT. FAILED() ) THEN
                      WRITE(*,'(A,3(X,F20.6))') 'R :', STATE(1),
            .                                STATE(2), STATE(3)
                      WRITE(*,'(A,3(X,F20.6))') 'V :', STATE(4),
            .                                STATE(5), STATE(6)
                      WRITE(*,'(A,F20.6)')  'LT: ',    LTIME

                   ELSE

       C
       C              Problem. The FAILED() routine returned a TRUE.
       C              Reset the error subsystem for another pass.
       C
                      CALL RESET()

                   END IF

                END IF

             END DO

             END
Top ### Run the code example Now run the code with various inputs to observe behavior. Begin the run using known astronomical bodies, e.g. "Moon", "Mars", "Pluto barycenter" and "Puck". Recall the SPICE default units are kilometers, kilometers per second, kilograms, and seconds. The 'R' marker identifies the (X,Y,Z) position of the body in kilometers, the 'V' marker identifies the velocity of the body in kilometers per second, and the 'LT' marker identifies the one-way light time between the bodies at the requested evaluation time.
       Target: Moon
       R :       -291584.616595       -266693.402359        -76095.647558
       V :             0.643439            -0.666066            -0.301310
       LT:             1.342311
       Target: Mars
       R :     234536077.419136    -132584383.595569     -63102685.706191
       V :            30.961373            28.932996            13.113031
       LT:           923.001080
       Target: Pluto barycenter
       R :   -1451304742.838526   -4318174144.406321    -918251433.587357
       V :            35.079843             3.053138            -0.036762
       LT:         15501.258293
       Target: Puck

       =====================================================================
       ===========

       Toolkit version: N0067

       SPICE(SPKINSUFFDATA) --

       Insufficient ephemeris data has been loaded to compute the state of 7
       15 (PUCK)
       relative to 0 (SOLAR SYSTEM BARYCENTER) at the ephemeris epoch 2000 J
       AN 01
       12:00:00.000.

       A traceback follows.  The name of the highest level module is first.
       SPKEZR --> SPKEZ --> SPKACS --> SPKAPS --> SPKLTC --> SPKGEO

       =====================================================================
       ===========
       Target:
Perplexing. What happened? The kernel files named in meta.tm did not include ephemeris data for Puck. When the SPK subsystem tried to evaluate Puck's position, the evaluation failed due to lack of data, so an error signaled. The above error signifies an absence of state information at ephemeris time 2000 JAN 01 12:00:00.000 (the requested time, ephemeris time zero). Since the program set the error mode to RETURN, program execution continues. Try another look-up, this time for "Casper"
       Target: Casper

       =====================================================================
       ===========

       Toolkit version: N0067

       SPICE(IDCODENOTFOUND) --

       The target, 'Casper', is not a recognized name for an ephemeris objec
       t. The
       cause of this problem may be that you need an updated version of the
       SPICE
       Toolkit. Alternatively you may call SPKEZ directly if you know the SP
       ICE ID
       codes for both 'Casper' and 'EARTH'

       A traceback follows.  The name of the highest level module is first.
       SPKEZR

       =====================================================================
       ===========
       Target:
An easy to understand error. The SPICE system does not contain information on a body named 'Casper.' Another look-up, this time, "Venus".
       Target: Venus
       R :     -80970027.540532    -139655772.573898     -53860125.958201
       V :            31.166910           -27.001056           -12.316514
       LT:           567.655074
       Target:
The look-up succeeded despite two errors in our run. The SPICE system can respond to error conditions (not system errors) in much the same fashion as languages with catch/throw instructions. Top ## Relevant Routines: `--` ERRDEV sets the device for error output. `--` ERRPRT sets the error message items for output on an error signal. `--` RETURN returns TRUE if a routine should return to caller on entry. Top # Lesson 6: Windows, and Cells Top ## Programming task Given the times of line-of-sight for a vehicle from a ground station and the times for an acceptable Sun-station-vehicle phase angle, write a program to determine the time intervals common to both configurations. Top ## Learning Goals This lesson introduces the concepts of the SPICE data types 'cell' and 'window'. A 'cell' is a data structure designed to provide easy and safe manipulation of typed array data. A FORTRAN SPICE cell consists of a structured 1xN array. A user should create cells by use of the appropriate SPICE calls. NAIF recommends against manual creation of cells. A 'window' is a type of cell containing ordered, double precision values describing a collection of zero or more intervals. We define an interval, 'i', as all double precision values bounded by and including an ordered pair of numbers,
          [ a , b ]
             i   i
where
          a    <   b
           i   -    i
The intervals within a window are both ordered and disjoint. That is, the beginning of each interval is greater than the end of the previous interval:
          b  <  a
           i     i+1
A common use of the windows facility is to calculate the intersection set of a number of time intervals. Top ## Code Solution
             PROGRAM WIN
             IMPLICIT NONE

       C
       C     Define our variable types.
       C
             INTEGER           LBCELL
             PARAMETER        (LBCELL = -5 )

             INTEGER           MAXSIZ
             PARAMETER        (MAXSIZ = 8 )

             INTEGER           I
             INTEGER           SMALL
             INTEGER           LARGE

             CHARACTER * 32    LOS   ( MAXSIZ )
             CHARACTER * 32    PHASE ( MAXSIZ )
             CHARACTER * 26    UTCSTR( 2 )

       C
       C     Define the cells to use as windows.
       C     The windows can hold 8 data values i.e.
       C     four intervals.
       C
             DOUBLE PRECISION  LOSWIN(LBCELL:MAXSIZ)
             DOUBLE PRECISION  PHSWIN(LBCELL:MAXSIZ)
             DOUBLE PRECISION  SCHED (LBCELL:MAXSIZ)

             DOUBLE PRECISION  LEFT
             DOUBLE PRECISION  RIGHT
             DOUBLE PRECISION  MEAS
             DOUBLE PRECISION  AVG
             DOUBLE PRECISION  STDDEV

       C
       C     SPICELIB functions associated with windows.
       C
             INTEGER           CARDD
             INTEGER           SIZED

       C
       C    Define sets of time intervals. For the purposes of this
       C    tutorial program, define time intervals representing
       C    an unobscured line of sight between a ground station
       C    and some  body.
       C
             DATA     LOS / 'Jan 1, 2003 22:15:02', 'Jan 2, 2003 4:43:29' ,
            .               'Jan 4, 2003 9:55:30' , 'Jan 4, 2003 11:26:52',
            .               'Jan 5, 2003 11:09:17', 'Jan 5, 2003 13:00:41',
            .               'Jan 6, 2003 00:08:13', 'Jan 6, 2003 2:18:01'
            .             /

       C
       C    A second set of intervals representing the times for which
       C    an acceptable phase angle exits between the ground station,
       C    the body and the Sun.
       C
             DATA   PHASE / 'Jan 2, 2003 00:03:30', 'Jan 2, 2003 19:00:00',
            .               'Jan 3, 2003 8:00:00' , 'Jan 3, 2003 9:50:00' ,
            .               'Jan 5, 2003 12:00:00', 'Jan 5, 2003 12:45:00',
            .               'Jan 6, 2003 00:30:00', 'Jan 6, 2003 23:00:00'
            .             /

       C
       C     Load our meta kernel for the leapseconds data.
       C
             CALL FURNSH ( 'win.tm' )

       C
       C     Windows consist of double precision values, convert the
       C     time tags defined in the LOS and PHASE arrays to
       C     double precision ET. Store the double values in the
       C     LOSWIN and PHSWIN arrays. Null out SCHED before attempting
       C     to validate - this removes any garbage values.
       C
             DO I = 1, 8
                CALL STR2ET( LOS(I)  , LOSWIN(I) )
                CALL STR2ET( PHASE(I), PHSWIN(I) )
                SCHED(I) = 0.d0
             END DO

       C
       C     Validate the windows from the double precision cells.
       C     Since we use 4 intervals, the set the window to accept 8
       C     data values ( 4 * 2 = 8 ). Since we require no more than
       C     8 data values, assign a window size of 8.
       C
             CALL WNVALD ( 8, 8, LOSWIN )
             CALL WNVALD ( 8, 8, PHSWIN )
             CALL WNVALD ( 8, 8, SCHED  )

       C
       C     The issue for consideration, at what times do line of
       C     sight events coincide with acceptable phase angles?
       C     Perform the set operation AND on LOSWIN, PHSWIN,
       C     place the results in the window SCHED.
       C
             CALL WNINTD( LOSWIN, PHSWIN, SCHED )

             CALL TOSTDO ( ' ' )
             WRITE(*,'(A,I2)') 'No. data values in SCHED           : ',
            .                                                CARDD(SCHED)
             WRITE(*,'(A,I2)') 'Space available for values in SCHED: ',
            .                                                SIZED(SCHED)

       C
       C     Output the results. The number of intervals in SCHED
       C     is half the number of data points (the cardinality).
       C     Use a call to CARDD to retrieve the window's cardinality.
       C
             CALL TOSTDO ( ' ' )
             CALL TOSTDO ( 'Time intervals meeting defined criterion.')

             DO I = 1, CARDD( SCHED )/2

       C
       C        Extract from the derived SCHED the values defining the
       C        time intervals, [LEFT, RIGHT].
       C
                CALL WNFETD ( SCHED, I, LEFT, RIGHT )

       C
       C        Convert the ET values to UTC for human comprehension.
       C
                CALL ET2UTC ( LEFT , 'C', 3, UTCSTR(1) )
                CALL ET2UTC ( RIGHT, 'C', 3, UTCSTR(2) )

       C
       C        Output the UTC string and the corresponding index
       C        for the interval.
       C
                WRITE(*,'(I2,4A)') I, '  ', UTCSTR(1), ' ',UTCSTR(2)

             END DO

       C
       C     Summarize the SCHED window.
       C
             CALL TOSTDO ( ' ' )
             CALL TOSTDO ( 'Summary of SCHED window' )
             CALL WNSUMD ( SCHED, MEAS, AVG, STDDEV, SMALL, LARGE )

             WRITE(*,'(A,F16.6)') 'o Total measure of SCHED    : ', MEAS
             WRITE(*,'(A,F16.6)') 'o Average measure of SCHED  : ', AVG
             WRITE(*,'(A,F16.6)') 'o Standard deviation of '
             WRITE(*,'(A,F16.6)') '  the measures in SCHED     : ',
            .                                                     STDDEV

       C
       C     The values for SMALL and LARGE refer to the indexes of the
       C     values in the array (SCHED). The shortest interval
       C     is [ SCHED(SMALL), SCHED(SMALL+1)]; the longest is
       C     [ SCHED(LARGE), SCHED(LARGE+1)]. Output the indexes for
       C     the shortest and longest intervals.
       C
       C
             WRITE(*,'(A,I2)') 'o Index of shortest interval: ',
            .                                               (SMALL+1)/2
             WRITE(*,'(A,I2)') 'o Index of longest interval : ',
            .                                               (LARGE+1)/2

             END
Top ### Run the code example The output window has the name SCHED (schedule). Output the amount of data held in SCHED compared to the maximum possible amount.
       No. data values in SCHED           :  6
       Space available for values in SCHED:  8
List the time intervals for which a line of sight exists during the time of a proper phase angle.
       Time intervals meeting defined criterion.
        1  2003 JAN 02 00:03:30.000   2003 JAN 02 04:43:29.000
        2  2003 JAN 05 12:00:00.000   2003 JAN 05 12:45:00.000
        3  2003 JAN 06 00:30:00.000   2003 JAN 06 02:18:01.000
Finally, an analysis of the SCHED data. The measure of an interval [a,b] (a <= b) equals b-a. Real values output in units of seconds.
       Summary of SCHED window
       o Total measure of SCHED    :     25980.000009
       o Average measure of SCHED  :      8660.000003
       o Standard deviation of
         the measures in SCHED     :      5958.550217
       o Index of shortest interval:  2
       o Index of longest interval :  1
Top ## Related Routines `--` WNCOMD determines the compliment of a window with respect to a defined interval. `--` WNCOND contracts a window's intervals. `--` WNDIFD : Calculate the difference between two windows; i.e. every point existing in the first but not the second. `--` WNELMD returns TRUE or FALSE if a value exists in a window. `--` WNEXPD expands the size of the intervals in a window. `--` WNEXTD extracts a window's endpoints . `--` WNFILD fills gaps between intervals in a window. `--` WNFLTD filter/removes small intervals from a window. `--` WNINCD determines if an interval exists within a window. `--` WNINSD inserts an interval into a window. `--` WNRELD compares two windows. Comparison operations available, equality '=', inequality '<>', subset '<=' and '>=', proper subset '<' and '>'. `--` WNUNID calculates the union of two windows. Top # Lesson 7: Utility and Constants Routines Top ## Task Statement Write an interactive program to convert values between various units. Demonstrate the flexibility of the unit conversion routine, the string equality function, and show the version ID function. Top ## Learning Goals SPICE provides several routines to perform commonly needed tasks. Among these: `--` convert values between unit expressions `--` determine the equality of strings `--` indicate whether a file exists `--` identify the toolkit version SPICE also includes a set of functions that return constant values often used in astrodynamics, time calculations, and geometry. Top ## Code Solution
             PROGRAM UNITS
             IMPLICIT NONE

       C
       C     Define the few variables
       C     needed for data input and output.
       C
             CHARACTER* (32)   FUNITS
             CHARACTER* (32)   TUNITS

             DOUBLE PRECISION  FVALUE
             DOUBLE PRECISION  TVALUE

       C
       C     Define the TKVRSN return value.
       C
             CHARACTER*(12)    VERS

       C
       C     Display the Toolkit version string with a
       C     TKVRSN call.
       C
             CALL TKVRSN( 'TOOLKIT', VERS )
             WRITE(*,*)
             WRITE(*,'(2A)') 'Convert demo program compiled against '
            .       //       'SPICE Toolkit ', VERS
             WRITE(*,*)

       C
       C     The user first inputs the name of a unit of measure.
       C     Send the name through TOSTAN for de-aliasing.
       C
             CALL PROMPT ( 'From Units : ', FUNITS )
             CALL TOSTAN ( FUNITS )

       C
       C     Input a double precision value to express in a new
       C     unit format.
       C
             WRITE(*,'(A13$)') 'From Value : '
             READ (*,*)         FVALUE

       C
       C     Now the user inputs the name of the output units.
       C     Again we send the units name through TOSTAN for
       C     de-aliasing.
       C
             CALL PROMPT ( 'To Units   : ', TUNITS )
             CALL TOSTAN ( TUNITS )

       C
       C     Call CONVRT to perform the conversion. CONVRT
       C     signals an error if:
       C        1. Either unit is unknown.
       C        2. The input and output units are not in the same
       C           class (length, angular measure, or time).
       C
             CALL CONVRT ( FVALUE, FUNITS, TUNITS, TVALUE )

       C
       C     Output the results.
       C
             WRITE(*,'(F12.6,2A)') TVALUE, ' ' , TUNITS

             STOP
             END

       C
       C     As a convenience, let's alias a few common terms
       C     to their appropriate counterpart. Use EQSTR to
       C     compare strings. The comparison ignores letter
       C     case and trailing/leading spaces.
       C
             SUBROUTINE TOSTAN ( ALIAS )
             IMPLICIT NONE

             LOGICAL           EQSTR
             CHARACTER*(*)     ALIAS

       C
       C     Start de-aliasing. Check the input string
       C     against a set of defined (allowed) aliases.
       C
             IF ( EQSTR( ALIAS, 'meter' ) ) THEN

       C
       C        First, a 'meter' by any other name is a
       C        'METER' and smells as sweet ...
       C
                ALIAS = 'METERS'

             ELSE IF ( EQSTR( ALIAS, 'klicks'     )   .OR.
            .          EQSTR( ALIAS, 'KILOMETERS' )   .OR.
            .          EQSTR( ALIAS, 'KILOMETER'  ) ) THEN

       C
       C        ... 'klicks', 'KILOMETERS' and
       C        'KILOMETER' identifies 'KM'....
       C
                ALIAS = 'KM'

             ELSE IF ( EQSTR( ALIAS, 'secs' ) )THEN

       C
       C        ... 'secs' to 'SECONDS'.
       C
                ALIAS = 'SECONDS'

             ELSE IF ( EQSTR( ALIAS, 'miles' ) )THEN

       C
       C        ... and finally 'miles' to 'STATUTE_MILES'.
       C        Normal people think in statute miles. Only
       C        sailors think in nautical miles - one
       C        minute of arc at the equator.
       C
                ALIAS = 'STATUTE_MILES'

             END IF

       C
       C     Much better, so return. If the input matched
       C     none of the aliases, this routine did nothing.
       C
             RETURN
             END
Top ### Run the code example Run a few conversions through the application to ensure it works. The intro banner gives us the Toolkit version against which the application was linked:
       Convert demo program compiled against SPICE Toolkit N0067

       From Units : klicks
       From Value : 3
       To Units   : miles
           1.864114 STATUTE_MILES
Now we know. Three kilometers equals 1.864 miles. Legend states Pheidippides ran from the Marathon Plain to Athens. The modern marathon race (inspired by this event) spans 26.2 miles. How far in kilometers?
       Convert demo program compiled against SPICE Toolkit N0067

       From Units : miles
       From Value : 26.2
       To Units   : km
          42.164813 km
Top ## Task Statement Write a program to output SPICE constants and use those constants to calculate some rudimentary values. Top ## Code Solution
             PROGRAM XCONST
             IMPLICIT NONE

       C
       C     As required in FORTRAN define the (return) type for
       C     the functions. All the functions have the same calling
       C     sequence:
       C
       C        VALUE = function_name()
       C        CALL some_procedure( function_name() )
       C        WRITE(*,*) function_name()
       C
             DOUBLE PRECISION      CLIGHT
             DOUBLE PRECISION      DPR
             DOUBLE PRECISION      RPD
             DOUBLE PRECISION      SPD
             DOUBLE PRECISION      J2000
             DOUBLE PRECISION      HALFPI
             DOUBLE PRECISION      J2100
             DOUBLE PRECISION      TYEAR

       C
       C     First a simple example using the seconds per day
       C     constant...
       C
             WRITE(*,'(A,F19.12)') 'Number of (S)econds (P)er (D)ay    '
            .       //             '     : ', SPD()

       C
       C     ...then show the value of degrees per radian, 180/Pi...
       C
             WRITE(*,'(A,F19.16)') 'Number of (D)egrees (P)er (R)adian '
            .       //             '     : ', DPR()

       C
       C     ...and the inverse, radians per degree, Pi/180.
       C     It is obvious DPR() equals 1.D/RPD(), or more simply
       C     DPR() * RPD() equals 1
       C
             WRITE(*,'(A,F19.16)') 'Number of (R)adians (P)er (D)egree '
            .       //             '     : ', RPD()

       C
       C     What's the value for the astrophysicist's favorite
       C     physical constant (in a vacuum)?
       C
             WRITE(*,'(A,F19.12)') 'Speed of light in KM per second    '
            .       //             '     : ', CLIGHT()

       C
       C     How long (in Julian days) from the J2000 epoch to the
       C     J2100 epoch?
       C
             WRITE(*,'(A)') 'Number of days between epochs J2000'
             WRITE(*,'(A,F19.12)') '  and J2100                        '
            .       //             '     : ', J2100() - J2000()

       C
       C     Redo the calculation returning seconds...
       C
             WRITE(*,'(A)') 'Number of seconds between epochs'
             WRITE(*,'(A,F19.5)') '  J2000 and J2100                 '
            .       //             '      : ',
            .            SPD() * (J2100() - J2000() )

       C
       C     ...then tropical years.
       C
             WRITE(*,'(A)') 'Number of tropical years between'
             WRITE(*,'(A,F19.12)') '  epochs J2000 and J2100          '
            .       //             '      : ',
            .            ( SPD() / TYEAR() ) * (J2100() - J2000() )

       C
       C     Finally, how can I convert a radian value to degrees.
       C
             WRITE(*,'(A,F19.16)') 'Number of degrees in Pi/2 radians '
            .       //             'of arc: ', HALFPI() * DPR()

       C
       C     and degrees to radians.
       C
             WRITE(*,'(A,F19.16)') 'Number of radians in 250 degrees '
            .       //             'of arc : ', 250.D0 * RPD()

             END
Top ### Run the code example
       Number of (S)econds (P)er (D)ay         :  86400.000000000000
       Number of (D)egrees (P)er (R)adian      : 57.2957795130823229
       Number of (R)adians (P)er (D)egree      :  0.0174532925199433
       Speed of light in KM per second         : 299792.457999999984
       Number of days between epochs J2000
         and J2100                             :  36525.000000000000
       Number of seconds between epochs
         J2000 and J2100                       :    3155760000.00000
       Number of tropical years between
         epochs J2000 and J2100                :    100.002135902909
       Number of degrees in Pi/2 radians of arc: 90.0000000000000000
       Number of radians in 250 degrees of arc :  4.3633231299858242
Top ## Related Routines `--` EXISTS returns a boolean indicating the existence of a file. `--` B1900 : Julian Date of the epoch Besselian Date 1900.0 `--` B1950 : Julian date of the epoch Besselian Date 1950.0 `--` J1900 : Julian date of 1900 JAN 0.5 this corresponds to calendar date 1899 DEC 31 12:00:00 `--` J1950 : Julian date of 1950 JAN 1.0 this corresponds to calendar date 1950 JAN 01 00:00:00 `--` TWOPI : double precision value of 2 * Pi `--` PI : double precision value of Pi `--` JYEAR : seconds per Julian year (365.25 Julian days)