#!/bin/sh
trap "" 1 2 3 15
#******************************************************************************
#                       ISTP LZPR SOFTWARE
#               Property of the U.S. Government
#                       NASA/GSFC/Code 560
#******************************************************************************
#
# UNIT NAME: lzp_process
#
# PURPOSE: To initiate processing of raw, blk, amf, and isas data files
#
# INVOCATION METHOD: lzp_process [options] filelist
#
# CHANGE HISTORY:
# Author        Change ID  Build/Release   Date      Description of Change
# ------        ---------  ------------- ---------   ---------------------
# K. Hogie      ISTP        R1.0B         11/25/97   Original
# R. Wiechert   ISTP        R1.0          01/02/98   Added archive option
# R. Wiechert   ISTP        R1.0D         01/28/98   Added diagnostic messages
#                                                     and interactive hooks
# R. Wiechert   ISTP        R1.3          07/05/98   Log receipt time, add
#                                                     batch processing hooks
#
# NOTES:  (see embedded help text for more details)
#
#	set default values
#	parse command options and arguments
#	validate command options and arguments
#	DO for each argument in argument list
#		IF isas file THEN
#			IF first file in isas group THEN add to input file list
#		ELSE
#			add to input file list
#		ENDIF
#	DONE
#	DO for each file in input file list
#		IF not forced operation THEN
#			display entire input file list
#			allow to process, skip, remove, quit
#		ENDIF
#		IF originals in replay directory THEN
#			IF blk  file  THEN move and avoid automatic processing
#			IF amf  file  THEN move and avoid automatic processing
#			IF isas files THEN call lzp_isas to create single amf
#			IF raw  file  THEN call lzp_split to create many blks
#			cleanup and/or remove intermediate files
#			result is split file list
#		ELSE
#			IF blk  file  THEN copy and avoid automatic processing
#			IF amf  file  THEN copy and avoid automatic processing
#			IF isas files THEN call lzp_isas to create single amf
#			IF raw  file  THEN copy, call lzp_split to create many blks
#			cleanup and/or remove intermediate files
#			result is split file list
#		ENDIF
#		DO for each file in split file list
#			call lzp_rename to assign standard file name
#			IF not forced operation THEN
#				display entire split file list
#				allow to process, skip, remove, quit
#			ENDIF
#			move file into blks directory
#			IF archive directory specified THEN
#				copy standard file to archive directory
#			ENDIF
#			IF logtime specified THEN
#				start replay log
#				log receipt time
#			ENDIF
#			IF not automatic file type THEN
#				determine DPS software status
#				IF DPS software is running THEN
#					call lzp_replay to replay file
#					IF replay successful THEN
#						rename standard file to done file
#						move replay log to DPS directory
#					ELSE
#						rename standard file to error file
#						leave replay log in replay directory
#					ENDIF
#				ENDIF
#			ENDIF
#		DONE
#       DONE
#
#******************************************************************************
USER=`/usr/ucb/whoami`
OPTLOCALBIN=/opt/local/bin
USRBIN=/usr/bin
DIRHOME=`pwd`
DIRDATA=$HOME/data1
DIRBLKS=$HOME/blks
DIRCONFIG="$HOME/config"
DIRTREND="$HOME/trend"
DIRARCHIVE="/dev/null"
REPLAYRC="$HOME/.replayrc"
OPT_MISSION=""
OPT_FORMAT=""
OPT_YEAR=""
OPT_DAY=""
OPT_STATION=""
OPT_SERIAL=""
LOGTIME=""
FORCE=""
VERBOSE=""
WHOLE=""
STOP=""
HELP=""

# function to validate filename
validate_filename()
{
   # caller should set MISSION, FORMAT, YEAR, STATION, and SERIAL
   # function returns 0 if valid filename, 1 if invalid filename
   # function does not have any side effects
   case $MISSION in
      WIND) : ;;
      POLAR) : ;;
      GEOTAIL) : ;;
      "") : ;;
      *) echo "ERROR: lzp_process: invalid mission"; return 1 ;;
   esac
   case $FORMAT in
      [A-Z]I) : ;;
      [A-Z]G) : ;;
      "") : ;;
      *) echo "ERROR: lzp_process: invalid data format"; return 1 ;;
   esac
   case $YEAR in
      19[0-9][0-9]) : ;;
      20[0-9][0-9]) : ;;
      "") : ;;
      *) echo "ERROR: lzp_process: invalid year"; return 1 ;;
   esac
   case $DAY in
      [0-3][0-9][0-9]) : ;;
      "") : ;;
      *) echo "ERROR: lzp_process: invalid day of year"; return 1 ;;
   esac
   case $STATION in
      [0-7][0-7][0-7][0-7][0-7]) : ;;
      "") : ;;
      *) echo "ERROR: lzp_process: invalid octal station"; return 1 ;;
   esac
   case $SERIAL in
      ?????) : ;;
      "") : ;;
      *) echo "ERROR: lzp_process: invalid serial number"; return 1 ;;
   esac
   return 0
}

# function to enter filename
enter_filename()
{
   # caller should set ARG_PROMPT, ARG_FIELD, and ARG_DEFAULT
   # function sets variable named by ARG_FIELD and always returns 0
   # function sets ANSWER as a side effect
   while [ forever ]
   do
      eval $ARG_FIELD="$ARG_DEFAULT"
      printf "$ARG_PROMPT [$ARG_DEFAULT]: "
      read ANSWER
      if [ "$ANSWER" ]
      then
         eval $ARG_FIELD="$ANSWER"
      fi
      validate_filename
      if [ $? = 0 ]
      then
         # accepted valid field
         return 0
      fi
   done
}

# function to enter directory
enter_directory()
{
   # caller should set ARG_PROMPT, ARG_FIELD, and ARG_DEFAULT
   # function sets variable named by ARG_FIELD and always returns 0
   # function sets ANSWER as a side effect
   while [ forever ]
   do
      eval $ARG_FIELD="$ARG_DEFAULT"
      printf "$ARG_PROMPT or /dev/null to disable\n[$ARG_DEFAULT]: "
      read ANSWER
      if [ "$ANSWER" ]
      then
         if [ -d "$ANSWER" -a -x "$ANSWER" -a -r "$ANSWER" -a -w "$ANSWER" ]
         then
            eval $ARG_FIELD="$ANSWER"
            return 0
         fi
         if [ "$ANSWER" = "/dev/null" ]
         then
            eval $ARG_FIELD="$ANSWER"
            return 0
         fi
      else
         # user accepted default
         return 0
      fi
      echo "ERROR: lzp_process: invalid directory"
   done
}

# determine runtime options
while getopts hfvwsl:d:r:c:t:a:M:F:Y:D:S:N: option
do
   case $option in
      f) FORCE="-f" ;;
      v) VERBOSE="-v" ;;
      w) WHOLE="-w" ;;
      s) STOP="-s" ;;
      d) DISPLAY="$OPTARG" ;;
      r) REPLAYRC="$OPTARG" ;;
      c) DIRCONFIG="$OPTARG" ;;
      t) DIRTREND="$OPTARG" ;;
      a) DIRARCHIVE="$OPTARG" ;;
      M) OPT_MISSION="$OPTARG" ;;
      F) OPT_FORMAT="$OPTARG" ;;
      Y) OPT_YEAR="$OPTARG" ;;
      D) OPT_DAY="$OPTARG" ;;
      S) OPT_STATION="$OPTARG" ;;
      N) OPT_SERIAL="$OPTARG" ;;
      l) LOGTIME=`expr "$OPTARG" : '\(.*,.*,.*,..:..:..,.*,....\)'` ;;
      *) HELP="-h" ;;
   esac
done

# shift past runtime options
shift `expr $OPTIND - 1`

# display help text
if [ "$HELP" = "-h" -o $# -eq 0 ]
then
more <<END_USAGE_TEXT
 
USAGE:     lzp_process [-hfvws] [-d display] [-r replayrc] [-c config]
                       [-t trend] [-a archive] [-M mission] [-F format]
                       [-Y year] [-D day] [-S station] [-N serial#]
                       [-l time] filelist
 
PURPOSE:   Processes the specified files through the LZP system with the
           specified configuration and manual overrides, invoking the
           standard splitter/renamer/replay scripts, copying the results
           into optional trend and archive directories.  Processing may
           be carried out with varying degrees of automation.
 
OPTIONS:   -h      display help screen
           -f      force automatic processing
           -v      enable verbose messaging mode
           -w      process whole files without splitting
           -s      stop after files have been synchronized
           -d      specify display address for user interface

           -r      specify replayrc file for LZP configuration
           -c      specify config directory for IRTS configuration
           -t      specify trend directory for trend file transfers
           -a      specify archive directory for raw data archive

           -M      override mission field of standard filenames
           -F      override format field of standard filenames
           -Y      override year field of standard filenames
           -D      override day field of standard filenames
           -S      override station field of standard filenames
           -N      override serial# field of standard filenames

           -l      specify original file receipt time
 
SYNOPSIS:  The specified files are copied to and processed in the replay
           staging area.  Additional copies may be routed to an archive
           directory if specified as an option.  Processing consists of
           passing each file through a splitter or transform whose purpose
           is to demultiplex different blocks into separate files by data
           source and format.  The demultiplexed files are then passed
           through a renamer in order to assign standard filenames which
           readily identify the mission, data format, year, day, station,
           and serial number pertaining to data within the original file.
           If an archive directory was specified, the renamed files are
           copied to that archive.  The following files are recognized:

                *.blk                  *.amf
                *.blk_hold             *.amf_hold
                *.blk_replay           *.amf_replay
                *.blk_replay_error     *.amf_replay_error
                *.blk_replay_done      *.amf_replay_done
                *.*_replay_log         GE_SD_ISAS_*

           Original files may be modified if processed directly within
           the replay staging area.  Precious files should be kept in
           and processed from another directory.  Interactive processing
           will normally result in either replay error or replay done.
           Log files resulting from a successful replay will be moved to
           the appropriate DPS data directory.  Temporary files will be
           removed as soon as possible.

           By default lzp_process behaves interactively, frequently
           prompting the user for various inputs.  This is useful for
           special one-time processing but can be inefficient for batch
           processing.  The -f option may be used to force automatic
           batch processing behaviour, preventing interactive prompts.

           The -vws options are used to limit the amount of status
           information which is generated, and the extent to which the
           given files are processed through the LZP system.  The -v
           option is typically specified only when executing as a cron
           job, while the -ws options are typically specified only
           when executed manually.  The -v option is used to generate
           verbose processing logs.  The -w option is used to prevent
           demultiplexing of the raw input files.  The -s option is used
           to halt processing immediately after frame synchronization.
           Halting after frame synchronization is most useful when the
           operator intends to examine and/or edit intermediate files
           before further processing through the system.  The -vws
           options are not specified by default.

           The -d option is used to specify the display address for
           those LZP subsystems requiring a graphical user interface.
           The current display address is used by default.  If the
           current display is invalid, then the software may attempt
           the addresses listed in the replayrc as well as the console
           address in the listed order.

           The -rcta options may be used to specify alternate replayrc,
           config, trend, and archive locations.  This is useful when
           processing multiple files in non-standard fashion without
           interfering with standard configuration files and standard
           operating procedures.  The /dev/null device may be specified
           in order to disable any of the replayrc, config, trend, or
           archiving functions.  By default, the replayrc, config, and
           trend objects are located within the mission home directory.
           Although the archive also appears within the mission home
           directory, the archive is set to /dev/null by default.  The
           archive location must be specified explicitly in order to
           enable archiving functions.
 
           The -MFYDSN options are used to override specific fields
           within the standard filenames which are assigned as files
           are processed through the LZP system.  In particular, the
           -Y option is useful in forcing a year when processing older
           data since the system always assumes the current year.

           The -l option is used only when called by lzp_checkftp,
           presumably as a cron job.  Humans should make no attempts
           at using the -l option which causes original file receipt
           times to be logged.

NOTES:     A transform script replaces the splitter script in the case
           of ISAS contingency files.  The transform script is used to
           transform groups of ISAS contingency files into amf files.

           The lzp_replay script is called directly for files which
           cannot be ingested automatically by the DPS software.  See
           the lzp_replay help text for more information.

           The following example shows how to process all files within
           the /export/home/baseline directory in interactive fashion.
           Note that these files will be preserved since the baseline
           directory is not typically used as the replay staging area,
           however no files will be archived since -a is not specified:
           lzp_process /export/home/baseline/*

END_USAGE_TEXT
exit 1
fi

# validate directory options
for option in $DIRBLKS $DIRCONFIG $DIRTREND $DIRARCHIVE
do
   if [ "$option" != "/dev/null" ]
   then
      if [ ! -d "$option" -o ! -x "$option" -o ! -r "$option" -o ! -w "$option" ]
      then
         echo "ERROR: lzp_process: $option"
         exit 1
      fi
   fi
done

# validate filename options
MISSION="$OPT_MISSION"
FORMAT="$OPT_FORMAT"
YEAR="$OPT_YEAR"
DAY="$OPT_DAY"
STATION="$OPT_STATION"
SERIAL="$OPT_SERIAL"
validate_filename
if [ $? != 0 ]
then
   # validate_filename prints error messages
   exit 1
fi

# filter input file list
while [ $# -gt 0 ]
do
   ISAS=`expr "$1" : '\(.*_SD_ISAS_.*\)\.S..'`
   if [ "$ISAS" ]
   then
      if [ "$ISAS.S01" != "$1" ]
      then
         ISAS=""
      else
         for ISAS_FILE in $ISAS_FILE_LIST
         do
            if [ "$ISAS.S01" = "$ISAS_FILE" ]
            then
               ISAS=""
               break
            fi
         done
      fi
      if [ "$ISAS" ]
      then
         # keep only first segment of each group
         ISAS_FILE_LIST="$ISAS_FILE_LIST $ISAS.S01"
      fi
   else
      if [ "$1" != "TempFTPfile" ]
      then
         # keep all non-isas files regardless
         TOTAL_FILE_LIST="$TOTAL_FILE_LIST $1"
      fi
   fi
   shift 1
done

# process filtered input file list
TOTAL_FILE_LIST="$ISAS_FILE_LIST $TOTAL_FILE_LIST"
set -- $TOTAL_FILE_LIST
while [ $# -gt 0 ]
do

   ANSWER=N
   if [ "$FORCE" != "-f" ]
   then
      while [ forever ]
      do
         clear
         echo ""
         echo "======================================================================"
         echo ""
         for WORD in $TOTAL_FILE_LIST
         do
            if [ "$WORD" = "$1" ]
            then
               echo "   ---> $WORD"
            else
               echo "        $WORD"
            fi
         done
         echo ""
         echo "======================================================================"
         echo ""
         printf "Process current file? (Yes/Whole/Skip/Remove/Quit) "
         read ANSWER
         if [ "$ANSWER" ]
         then
            ANSWER=`echo $ANSWER | tr '[a-z]' '[A-Z]' | tr -cd 'YWSRQ'`
            if [ "$ANSWER" ]
            then
               break
            fi
         fi
      done

      if [ "$ANSWER" = "R" ]
      then
         printf "\nREMOVING FILE...\n"
         ISAS=`expr "$1" : '\(.*_SD_ISAS_.*\)\.S..'`
         if [ "$ISAS" ]
         then
            $USRBIN/rm -f $ISAS.S*
         else
            $USRBIN/rm -f $1
         fi
      fi

      case $ANSWER in
        Y*) WHOLE="" ;;
         W) WHOLE="-w" ;;
         Q) exit 0 ;;
         *) shift 1; continue ;;
      esac
   fi

   cd $DIRHOME
   DIRNAME=`dirname $1`
   FILENAME=`basename $1`
   if [ -d "$DIRNAME" -a -x "$DIRNAME" -a -f "$DIRNAME/$FILENAME" -a -r "$DIRNAME/$FILENAME" ]
   then

      if [ "$FORCE" != "-f" ]
      then
         # large files may take a little while
         printf "\nCOPYING FILE...\n"
      fi

      BLK=`expr "$FILENAME"  : '\(.*\.blk\).*'`
      AMF=`expr "$FILENAME"  : '\(.*\.amf\).*'`
      ISAS=`expr "$FILENAME" : '\(.*_SD_ISAS_.*\)\.S..'`
      LOG=`expr "$FILENAME"  : '\(.*\..*_replay_log\).*'`
      TMP=`expr "$FILENAME"  : '\(.*\.tmp\).*'`
      SPLIT_FILE_LIST=""
      RAW=""

      cd $DIRNAME
      DIRNAME=`pwd`
      cd $DIRBLKS
      if [ "$DIRNAME" = `pwd` ]
      then
         # originals are located in the blks directory
         if [ ! "$TMP" -a ! "$LOG" ]
         then
            if [ "$BLK" ]
            then
               # already split, prevent automatic processing
               $USRBIN/mv -f $FILENAME $BLK"_hold" 2>/dev/null
               SPLIT_FILE_LIST=$BLK"_hold"
            else
               if [ "$AMF" ]
               then
                  # impossible to split amf files, simply rename
                  $USRBIN/mv -f $FILENAME $AMF"_hold" 2>/dev/null
                  SPLIT_FILE_LIST=$AMF"_hold"
               else
                  if [ "$ISAS" ]
                  then
                     # transform file group into single amf file
                     FILENAME=`$OPTLOCALBIN/lzp_isas -f $VERBOSE $ISAS.S*`
                     AMF=`expr "$FILENAME" : '\(.*\.amf\).*'`
                     # impossible to split amf files, simply rename
                     $USRBIN/mv -f $FILENAME $AMF"_hold" 2>/dev/null
                     SPLIT_FILE_LIST=$AMF"_hold"
                  else
                     # normal path for automatic processing of raw data
                     if [ "$WHOLE" = "-w" ]
                     then
                        SPLIT_FILE_LIST=$FILENAME
                        RAW=$FILENAME
                     else
                        SPLIT_FILE_LIST=`$OPTLOCALBIN/lzp_split -f $VERBOSE $FILENAME`
                        RAW=$FILENAME
                     fi
                  fi
               fi
            fi
         fi
      else
         # originals are located in another directory
         if [ ! "$TMP" -a ! "$LOG" ]
         then
            if [ "$BLK" ]
            then
               # already split
               SPLIT_FILE_LIST=$BLK"_hold"
               trap "$USRBIN/rm -f $DIRBLKS/$SPLIT_FILE_LIST 2>/dev/null; exit 1" 1 2 3 15
               $USRBIN/cp -p $DIRNAME/$FILENAME $DIRBLKS/$SPLIT_FILE_LIST 2>/dev/null
               trap "" 1 2 3 15
            else
               if [ "$AMF" ]
               then
                  # impossible to split
                  SPLIT_FILE_LIST=$AMF"_hold"
                  trap "$USRBIN/rm -f $DIRBLKS/$SPLIT_FILE_LIST 2>/dev/null; exit 1" 1 2 3 15
                  $USRBIN/cp -p $DIRNAME/$FILENAME $DIRBLKS/$SPLIT_FILE_LIST 2>/dev/null
                  trap "" 1 2 3 15
               else
                  if [ "$ISAS" ]
                  then
                     # transform file group into single amf file
                     FILENAME=`$OPTLOCALBIN/lzp_isas $VERBOSE $DIRNAME/$ISAS.S*`
                     AMF=`expr "$FILENAME" : '\(.*\.amf\).*'`
                     # impossible to split amf files, simply rename
                     $USRBIN/mv -f $FILENAME $AMF"_hold" 2>/dev/null
                     SPLIT_FILE_LIST=$AMF"_hold"
                  else
                     # normal path for manual processing of raw data
                     trap "$USRBIN/rm -f $DIRBLKS/$FILENAME 2>/dev/null; exit 1" 1 2 3 15
                     $USRBIN/cp -p $DIRNAME/$FILENAME $DIRBLKS/$FILENAME 2>/dev/null
                     trap "" 1 2 3 15
                     if [ "$WHOLE" = "-w" ]
                     then
                        SPLIT_FILE_LIST=$FILENAME
                        RAW=$FILENAME
                     else
                        SPLIT_FILE_LIST=`$OPTLOCALBIN/lzp_split -f $VERBOSE $FILENAME`
                        RAW=$FILENAME
                     fi
                  fi
               fi
            fi
         fi
      fi

      ANSWER=N
      for SPLIT_FILE in $SPLIT_FILE_LIST
      do
         RESULT=""
         EXTENSION=""
         if [ "$AMF" -o "$ISAS" ]
         then
            RESULT="$SPLIT_FILE"
            EXTENSION=amf_replay
         else
            RESULT=`$OPTLOCALBIN/lzp_rename -n -d $SPLIT_FILE 2>/dev/null`
            case $LOGTIME in
               "") EXTENSION=blk_replay ;;
               *) EXTENSION=blk ;;
            esac
         fi

         case $OPT_MISSION in
            "") MISSION=`expr   "$RESULT" : '\(.*\)_.._...._..._....._.....\..*'` ;;
            *) MISSION="$OPT_MISSION" ;;
         esac
         case $OPT_FORMAT in
            "") FORMAT=`expr    "$RESULT" : '.*_\(..\)_...._..._....._.....\..*'` ;;
            *) FORMAT="$OPT_FORMAT" ;;
         esac
         case $OPT_YEAR in
            "") YEAR=`expr      "$RESULT" : '.*_.._\(....\)_..._....._.....\..*'` ;;
            *) YEAR="$OPT_YEAR" ;;
         esac
         case $OPT_DAY in
            "") DAY=`expr       "$RESULT" : '.*_.._...._\(...\)_....._.....\..*'` ;;
            *) DAY="$OPT_DAY" ;;
         esac
         case $OPT_STATION in
            "") STATION=`expr   "$RESULT" : '.*_.._...._..._\(.....\)_.....\..*'` ;;
            *) STATION="$OPT_STATION" ;;
         esac
         case $OPT_SERIAL in
            "") SERIAL=`expr    "$RESULT" : '.*_.._...._..._....._\(.....\)\..*'` ;;
            *) SERIAL="$OPT_SERIAL" ;;
         esac

         ANSWER=N
         while [ "$FORCE" != "-f" ]
         do
            case $STOP in
               -s) STOP="Yes" ;;
               *) STOP="No" ;;
            esac

            clear
            echo ""
            echo "======================================================================"
            echo "     Original File = $1"
            for WORD in $SPLIT_FILE_LIST
            do
               if [ "$WORD" = "$SPLIT_FILE" ]
               then
                  echo "   ---> Split File = $WORD"
               else
                  echo "        Split File = $WORD"
               fi
            done
            echo "     Standard Name = $RESULT"
            echo "======================================================================"
            echo ""
            echo "      Mission Name = $MISSION"
            echo "       Data Format = $FORMAT"
            echo "   Spacecraft Year = $YEAR"
            echo "    Spacecraft Day = $DAY"
            echo "      Station Code = $STATION"
            echo "     Serial Number = $SERIAL"
            echo "    File Extension = $EXTENSION"
            echo "  Config Directory = $DIRCONFIG"
            echo "   Trend Directory = $DIRTREND"
            echo " Archive Directory = $DIRARCHIVE"
            echo "     Replayrc File = $REPLAYRC"
            echo "   Display Address = $DISPLAY"
            echo "   Stop After Sync = $STOP"
            echo ""

            case $STOP in
               Y*) STOP="-s" ;;
               *) STOP="" ;;
            esac

            printf "Are these parameters correct? (Yes/No/Skip/Remove/Quit) "
            read ANSWER
            if [ "$ANSWER" ]
            then
               ANSWER=`echo $ANSWER | tr '[a-z]' '[A-Z]' | tr -cd 'YNSRQ'`
               if [ "$RESULT" = "" ]
               then
                  if [ "$ANSWER" = "Y" -o "$ANSWER" = "YS" ]
                  then
                     printf "\nWARNING: file contains questionable data\n"
                     printf "Process file anyway? (Yes/No) "
                     read ANSWER
                     ANSWER=`echo $ANSWER | tr '[a-z]' '[A-Z]' | tr -cd 'YN'`
                     case $ANSWER in
                        Y) ANSWER=Y ;;
                        *) continue ;;
                     esac
                  fi
               fi
               case $ANSWER in
                 Y*) break ;;
                  S) break ;;
                  R) break ;;
                  Q) exit 0 ;;
               esac
               echo ""

               ARG_PROMPT="Enter Mission Name"
               ARG_FIELD=MISSION; ARG_DEFAULT="$MISSION"
               enter_filename
               ARG_PROMPT="Enter Data Format FF"
               ARG_FIELD=FORMAT; ARG_DEFAULT="$FORMAT"
               enter_filename
               ARG_PROMPT="Enter Spacecraft Year YYYY"
               ARG_FIELD=YEAR; ARG_DEFAULT="$YEAR"
               enter_filename
               ARG_PROMPT="Enter Spacecraft Day DDD"
               ARG_FIELD=DAY; ARG_DEFAULT="$DAY"
               enter_filename
               ARG_PROMPT="Enter Octal Station SSSSS"
               ARG_FIELD=STATION; ARG_DEFAULT="$STATION"
               enter_filename
               ARG_PROMPT="Enter Serial Number NNNNN"
               ARG_FIELD=SERIAL; ARG_DEFAULT="$SERIAL"
               enter_filename
               ARG_PROMPT="Enter File Extension"
               ARG_FIELD=EXTENSION; ARG_DEFAULT="$EXTENSION"
               enter_filename

               ARG_PROMPT="\nEnter Config Directory"
               ARG_FIELD=DIRCONFIG; ARG_DEFAULT="$DIRCONFIG"
               enter_directory
               ARG_PROMPT="\nEnter Trend Directory"
               ARG_FIELD=DIRTREND; ARG_DEFAULT="$DIRTREND"
               enter_directory
               ARG_PROMPT="\nEnter Archive Directory"
               ARG_FIELD=DIRARCHIVE; ARG_DEFAULT="$DIRARCHIVE"
               enter_directory

               ARG_PROMPT="\nEnter Replayrc File"
               ARG_FIELD=REPLAYRC; ARG_DEFAULT="$REPLAYRC"
               enter_filename
               if [ ! -f "$REPLAYRC" -a "$REPLAYRC" != "/dev/null" ]
               then
                  echo "WARNING: lzp_process: file does not exist"
               fi

               ARG_PROMPT="\nEnter Display Address"
               ARG_FIELD=DISPLAY; ARG_DEFAULT="$DISPLAY"
               enter_filename
               case $DISPLAY in
                  *:*) : ;;
                  *) echo "WARNING: lzp_process: bad display address"
               esac

               printf "\nStop After Sync? (Yes/No) "
               read STOP
               case $STOP in
                  [yY]*) STOP="-s" ;;
                  *) STOP="" ;;
               esac
            fi
         done

         # remove or skip file as requested
         case $ANSWER in
            R) printf "\nREMOVING FILE...\n"; $USRBIN/rm -f "$SPLIT_FILE"; continue ;;
            S) continue ;;
         esac

         if [ "$FORCE" != "-f" -o "$VERBOSE" = "-v" ]
         then
            # large files may take a little while
            printf "\nRENAMING DATA FILE...\n"
         fi

         # rename and archive file as requested
         RESULT="$MISSION"_"$FORMAT"_"$YEAR"_"$DAY"_"$STATION"_"$SERIAL"."$EXTENSION"
         $USRBIN/mv -f $SPLIT_FILE $DIRBLKS/$RESULT 2>/dev/null
         if [ -f "$RESULT" -a -r "$RESULT" ]
         then
            if [ "$VERBOSE" = "-v" ]
            then
               echo ""
               echo "  Original File = $SPLIT_FILE"
               echo "   Renamed File = $RESULT"
               echo "   Archive Path = $DIRARCHIVE"
            fi
            trap "$USRBIN/rm -f $DIRARCHIVE/$RESULT 2>/dev/null; exit 1" 1 2 3 15
            $USRBIN/cp -p $RESULT $DIRARCHIVE 2>/dev/null
            if [ $? != 0 ]
            then
               echo "ERROR: lzp_process: cp $RESULT $DIRARCHIVE"
            fi
            trap "" 1 2 3 15
         else
            echo "ERROR: lzp_process: mv $SPLIT_FILE $RESULT"
            RESULT=""
         fi

         # log either receipt time or manual replay flag
         if [ "$RESULT" ]
         then
            case $EXTENSION in
               *_replay*) LOGFILE="$RESULT"_log ;;
               *) LOGFILE="$RESULT"_replay_log ;;
            esac
            echo "" >> $LOGFILE
            if [ "$LOGTIME" ]
            then
               LOGTIME=`echo "$LOGTIME" | tr '[,]' '[ ]'`
               echo "$LOGTIME FTP REPLAY RECEIVED" >> $LOGFILE
            else
               echo "`date` MANUAL REPLAY STARTED" >> $LOGFILE
            fi
         fi

         # initiate manual replay if automatic ingestion impossible
         if [ "$RESULT" -a "$EXTENSION" != "blk" ]
         then
            if [ "$FORCE" != "-f" -o "$VERBOSE" = "-v" ]
            then
               printf "\nINITIATING MANUAL REPLAY...\n"
            fi
            PER=`/usr/bin/ps -u $USER -o args | grep 'perLib/PER' | grep -v grep`
            SCID=`echo $PER | awk '{ print $2 }'`; SCID=${SCID:=0}
            PORT=`echo $PER | awk '{ print $3 }'`; PORT=${PORT:=0}
            if [ -d "$DIRDATA/$SCID" -a -x "$DIRDATA/$SCID" -a -r "$DIRDATA/$SCID" ]
            then
               # DPS software is running
               ANSWER=Y
            else
               ANSWER=N
               echo "ERROR: lzp_process: DPS software is down"
               if [ "$FORCE" != "-f" ]
               then
                  printf "Continue replay anyway? (Yes/No) "
                  read ANSWER
               fi
            fi
            ANSWER=`echo $ANSWER | tr '[a-z]' '[A-Z]' | tr -cd 'YN'`
            if [ "$ANSWER" = "Y" ]
            then
               export DISPLAY
               TRAPSUFFIX="_error 2>/dev/null; echo INTERRUPT; exit 1"
               trap "$USRBIN/mv -f $RESULT $RESULT$TRAPSUFFIX" 1 2 3 15
               option="$STOP -r $REPLAYRC -c $DIRCONFIG -t $DIRTREND -a $DIRARCHIVE"
               if [ "$FORCE" != "-f" ]
               then
                  # add interactive flag
                  option="-i $option"
               fi
               lzp_replay $option $DIRBLKS $RESULT $DIRDATA/$SCID $PORT
               if [ $? = 0 ]
               then
                  LOGFILE=$RESULT"_log" # recalculate without making any assumptions
                  SESSIONID=`grep "DPS Session ID =" $LOGFILE 2>/dev/null | tail -1`
                  SESSIONID=`echo "$SESSIONID" | awk '{ print $5 }'`
                  if [ -d "$DIRDATA/$SCID/$SESSIONID" -a -x "$DIRDATA/$SCID/$SESSIONID" ]
                  then
                     $USRBIN/mv -f $LOGFILE $DIRDATA/$SCID/$SESSIONID 2>/dev/null
                  fi
                  $USRBIN/mv -f $RESULT $RESULT"_done" 2>/dev/null
               else
                  $USRBIN/mv -f $RESULT $RESULT"_error" 2>/dev/null
               fi
               trap "" 1 2 3 15
            fi
         fi
      done
   else
      echo "ERROR: lzp_process: $1"
   fi

   if [ "$FORCE" != "-f" -a "$ANSWER" != "S" ]
   then
      printf "\nPress enter to continue... "
      read ANSWER
   fi

   shift 1
done
exit 0
