#!/bin/csh

# ker2sfdu.csh <label_type> <SPICE kernel file> <sfdu file>

#
#  In order to use this script, the following programs must be
#  available via the execution path. They executed in the order shown:
#
#     maklabel - A NAIF toolkit utility which generates a label file 
#                from a SPICE kernel file.
#
#     archtype - NAIF toolkit utility for determining the architecture 
#                and type of a SPICE kernel file.
#
#     clcommnt - A command line oriented version of the commnt program.
#                This program exists temporarily, until a command line 
#                mode can be added to the commnt program.
#                
#     toxfr    - A NAIF utility  for converting binary SPICE kernels 
#                into a transfer file, i.e., a portable ASCII file that 
#                may be moved from one computing environment to another 
#                and used to build the equivalent binary kernel file.
#
#     kwikwrap - A program provided by MGSO that takes a label file and 
#                a data file and creates an SFDU.
#

#
#  This script, or programs that it invokes, require that some or all 
#  of the following environment variables be set:
#
#        $MISSION_TEMPLATE - The complete filename, including a full 
#                            path, to the mission template file. This 
#                            file contains a number of subsections each 
#                            of which defines a type of the label for 
#                            one of the SPICE kernel file types produced
#                            for that mission. A label type is defined 
#                            in a single subsection using the mission
#                            specific keywords and their values. Each of 
#                            these keyword-value pairs must fit on a single 
#                            line. Refer to MAKLABEL User's Guide document
#                            to get complete decscription of the mission
#                            template file format.
#
#                            This file is required.
#
#        $LEAPSECONDS      - The complete filename, including a full 
#                            path, to the current SPICE leapseconds file 
#                            used by a mission. This is required because 
#                            the time tags used for various SFDU values 
#                            must be in an ISO UTC format.
#
#                            This file is required for CK, binary PCK,
#                            and SPK files.
#
#        $SCLK_FILE        - The complete filename, including a full 
#                            path, to the current SPICE Spacecraft clock 
#                            (SCLK) file used by a mission. This is 
#                            required for time conversions from 
#                            spacecraft clock to UTC.
#
#                            This file is required for CK files.
#
#        $SSS_DEFAULTS     - This environment variable is used by the 
#                            MGSO SFDU wrapping software to obtain 
#                            various pieces of information. Please see 
#                            the documentation for the MGSO Standards 
#                            Support Subsystem (SSS), a subsystem 
#                            consisting of ``a global library, tools for 
#                            creating catalog template files, wrapping, 
#                            unwrapping, and validating SFDU files, and 
#                            a graphical user interface.'' The utility 
#                            program used by the C shell script 
#                            `ker2sfdu.csh' is the `kwikwrap' program 
#                            which combines a label file and a data file 
#                            producing a wrapped an SFDU data product. 
#                            This environment variable my not need to be 
#                            defined.
#
#                            If the SFDU policy table is not found in 
#                            its default location, then this environment 
#                            variable will need to be defined, and 
#                            set at least the path to the policy table:
#
#                            setenv SSS_DEFAULTS "POLICY_TABLE = ..."
#
#                             where '...' represents the complete path 
#                             to the SFDU policy table.
#
#  In addition to the files specified by the environment variables, this 
#  script requires, as its first argument, the type of the label that will
#  be generated for the file. The label types for a particular mission 
#  are defined in the mission template file whose name must be provided 
#  in the $MISSION_TEMPLATE environment variable. Please refer to MAKLABEL
#  User's Guide document to understand the format of such file and 
#  look at the particular mission template file contents to find out 
#  what specific label types are defined for that mission.
#
#  The script also requires as its second argument, the name of a SPICE 
#  kernel file that is to be converted into an SFDU for the CDB.  
#  Optionally,the name of the SFDU file to be created may be supplied as  
#  the second argument. If the name of the SFDU file is not supplied the 
#  basename of the SPICE kernel file with the extension ".sfdu" will be  
#  used as the name of the SFDU file.
#
#  When a SPICE kernel file is converted into an SFDU, binary SPICE 
#  kernels are converted into their portable transfer format before 
#  being labelled and wrapped and text SPICE kernels are simply
#  labelled and wrapped.
#
#  For example, assuming the environment variables are defined, the 
#  command
#
#     ker2sfdu.csh my_label_type my_file.bsp my_file.sfdu
#
#  would produce the wrapped SFDU file
#
#     my_file.sfdu
#

#
#  If we don't get all three parameters on the command line,
#  we can't do anything, so we display the usage and exit.
#

if ( $3 == "" ) then
   echo " "
   echo "Usage: ker2sfdu.csh <label type> <SPICE kernel file> <sfdu file>"
   echo " "
   exit (1)
endif

#
#  We have three parameters: the first parameter is a label type, 
#  the second is the name of a spice kernel file and the third parameter 
#  isthe name of an output sfdu-wrapped file.
#

set LBLTYPE  = $1
set KERFILE  = $2
set SFDUFILE = $3

#
#  We need some temporary file names here, so we just make them. The $$
#  will make them unique, using the process ID of the current process.
#
#  Set the name of the temporary label file we will make.
#
set LABELFILE = {$KERFILE:r}.label-$$

#
#  Set the name of the temporary SPICE transfer file we will make.
#
set TRANSFERFILE = {$KERFILE:r}.transfer-$$

#
#  Make the label file. If the label file does not exist after the 
#  maklabel command, there was an error, so exit.
#
maklabel mgso $LBLTYPE $KERFILE $LABELFILE > error-$$.log

if ( ! -e $LABELFILE ) then
   echo " "
   echo "ERROR: maklabel failed."
   echo " "
   cat error-$$.log
   echo " "
   rm error-$$.log
   exit (1)
endif
rm error-$$.log

#
#  Get the architecture and type of the file. Based on the architecture, 
#  we add comments and convert it to a rtransfer file or just wrap it.
#

set ARCHTYPE = `archtype $KERFILE`

set ARCH = $ARCHTYPE[1]
set TYPE = $ARCHTYPE[2]

if ( ( $ARCH == "DAF") || ( $ARCH == "DAS" ) ) then
#
#  Add the "\beginlabel" and "\endlabel" delimiters to the label data
#  so we can place the labels into the comment area of an kernel file.
#  We do this by using a filter that just wraps the labels in the label 
#  file, creating a new file which we will use for wrapping the SFDU.
#  If this fails for some reason, exit.
#
   echo "\beginlabel"  > $LABELFILE.d
   cat $LABELFILE     >> $LABELFILE.d
   echo "\endlabel"   >> $LABELFILE.d

   if ( ! ($status == 0) ) then
      if ( -e $LABELFILE ) then
         rm $LABELFILE
      endif
      if ( -e $LABELFILE.d ) then
         rm $LABELFILE.d
      endif
      exit (1)
   endif

#
#  Add the delimited labels to the SPICE binary kernel file. There is no 
#  easy way to see if this fails, because the NAIF software traps its 
#  own errors and exits, always giving a zero (0) status to the 
#  environment (Fortran does not allow any other mechanism unless there 
#  is a runtime failure).
#
#  If this becomes a problem, the comments could be extracted and 
#  compared to the original file. IF they compare OK, except possibly 
#  for some white space differences, then it worked.
#
   clcommnt -a $KERFILE $LABELFILE.d

#
#  Convert the binary kernel files into its transfer format for 
#  storage on the CDB. If this fails, the SPICE transfer file will not 
#  be created, so we need to clean up and exit.
#
   toxfr $KERFILE $TRANSFERFILE > /dev/null

   if ( ! -e $TRANSFERFILE ) then
      if ( -e $LABELFILE ) then
         rm $LABELFILE
      endif
      if ( -e $LABELFILE.d ) then
         rm $LABELFILE.d
      endif
      echo " "
      echo "ERROR: toxfr failed."
      echo " "
      exit (1)
   endif

   set WRAPFILE = $TRANSFERFILE

else if ( $ARCH == "KPL" ) then

   set WRAPFILE = $KERFILE

else if ( $ARCH == "UNK" ) then
   echo " "
   echo "ERROR: The architecture of the file $KERFILE could not be"
   echo "determined. Are you sure that it is a SPICE kernel file?"
   echo " "
   exit (1)
endif

#
#  Now we have all of the bits we need to SFDU wrap a file for the CDB, 
#  so we do it. If this fails, we assume that kwikwrap will return a 
#  nonzero value to the environment.
#
kwikwrap -t -f $SFDUFILE -k $LABELFILE -i $WRAPFILE

if ( ! ($status == 0) ) then
   if ( -e $TRANSFERFILE ) then
      rm $TRANSFERFILE
   endif
   if ( -e $LABELFILE ) then
      rm $LABELFILE
   endif
   if ( -e $LABELFILE.d ) then
      rm $LABELFILE.d
   endif
   if ( -e $SFDUFILE ) then
      rm $SFDUFILE
   endif
   echo " "
   echo "ERROR: kwikwrap failed."
   echo " "
   exit (1)
endif

#
#  Clean up after ourselves. We should have no problem deleting the 
#  things we created.
#
if ( -e $TRANSFERFILE ) then
   rm $TRANSFERFILE
endif
if ( -e $LABELFILE ) then
   rm $LABELFILE
endif
if ( -e $LABELFILE.d ) then
   rm $LABELFILE.d
endif
