#!/bin/bash
# -v will print out things as they are parsed.

# Should now run on any mvacs machine that is running sunos 5.7 (solaris 7?)
# Linux support is still in the works.

######################################################################
#
# WARNING -- DANGER -- Death to all who edit without notifying ALL of 
# the following:
#
# Kurt Schwehr -- schwehr@ri.cmu.edu  (Lead writer/maintainer of this script)
# Kam Tso      -- tso@telerobotics.jpl.nasa.gov
# Eric Zbinden -- zbinden@artemis.arc.nasa.gov
# Justin Maki  -- Justin.N.Maki@jpl.nasa.gov
# Jonathon Weinberg -- jdweinb@lpl.arizona.edu
# Stubbe F. Hviid -- sfhviid@linmpi.mpg.de
# Bob Reid -- breid@lpl.arizona.edu
#
######################################################################

######################################################################
#
# AUTHOR: Kurt Schwehr, schwehr@ri.cmu.edu, 412-414-8543
# START DATE: Sep-1999
#
# $Id: stereopair2wits.bash,v 1.45 1999/12/02 22:53:09 schwehr Exp $
#
# PROJECT: mvacs SSI
# 
# DESCRIPTION: Should do everything required for processing stereo
# pairs to produce output for the WITS user interface.
#
# INPUTS: leftImage rightImage [outputDir]
#
# ENV VARIABLES USED:
#
#	SSI_DATA_TOP_DIR = The root of the data tree.
#
# OUTPUT: A whole bunch of things.
#
# Notes: Designed to be called by either a luser or a MCP (master 
#		control program).
#
# See help for more.
#
#  bash -- emacs M-x info C-s bash [ret] [ret]
#     or http://www.gnu.org/manual/bash/index.html
#  ImageMagick -- http://www.wizards.dupont.com/cristy/ImageMagick.html
#  netpbm -- ftp://wuarchive.wustl.edu/graphics/graphics/packages/NetPBM/
#  stereo -- http://img.arc.nasa.gov/~zbinden/photoRealVR/topvr.html
#  wits -- http://robotics.jpl.nasa.gov/tasks/wits/homepage.html
#
#  And for everything else:
#
#  	http://www.despair.com
#
#  TODO:
#
#    Errors do not stop the execution... what to do?
#
#######################################################################

declare -ri EXIT_FAILURE=1
declare -ri EXIT_SUCCESS=0

declare -ri TERSE=1
declare -ri TRACE=4
declare -ri VERBOSE=8
declare -ri BOMBASTIC=16

if [ -z "$SSI_VERBOSITY" ]; then
    declare -i debugLevel=4
else
    declare -i debugLevel=$SSI_VERBOSITY
fi

# Twisted way to get down to the fundamental script name.
tmp=${0##/*/}
tmp=${tmp%%.bash}
tmp=${tmp##*.}
tmp=${tmp##*/}
declare -r SCRIPT_NAME=$tmp


# $1 is the level to compare against debugLevel
# $2 is the string to echo to stdout.
DebugEcho()
{
    declare -ir val=$1
    if [ "$debugLevel" -ge "$val" ]; then
	#echo $2
	echo "${SCRIPT_NAME}(`printf "%02d" $1`) $2"
    fi
}

#DebugEcho $TERSE     "Terse is on"
#DebugEcho $TRACE     "Trace is on"
DebugEcho $VERBOSE   "Verbose is on"
DebugEcho $BOMBASTIC "Bombastic is on"

DebugEcho $TRACE "debugLevel               = $debugLevel"


######################################################################
# Environment Setup Section
######################################################################


if [ -z "$SSI_SOL_UNKNOWN" ]; then
    declare -r SSI_SOL_UNKNOWN=sol_unknown
    DebugEcho $TRACE "setting SSI_SOL_UNKNOWN      = $SSI_SOL_UNKNOWN"
fi

if [ -z "$SSI_TOP_DIR" ]; then
    declare -r SSI_TOP_DIR=/proj/ops/ssi/mort7
    DebugEcho $TRACE "setting SSI_TOP_DIR      = $SSI_TOP_DIR"
fi

if [ -z "$SSI_DATA_TOP_DIR" ]; then
    declare -r SSI_DATA_TOP_DIR=${SSI_TOP_DIR}/data
    DebugEcho $TRACE "setting SSI_DATA_TOP_DIR = $SSI_DATA_TOP_DIR"
fi

if [ -z "$BIN_DIR" ]; then
    declare -r BIN_DIR=${SSI_TOP_DIR}/bin/`uname`
    DebugEcho $VERBOSE "setting BIN_DIR          = $BIN_DIR"
fi

# Location of additional java archives.
if [ -z "$JAVA_DIR" ]; then
    declare -r JAVA_DIR=${SSI_TOP_DIR}/bin/java
    DebugEcho $VERBOSE "setting JAVA_DIR         = $JAVA_DIR"
fi

if [ -z "$SCRIPT_DIR" ]; then
    declare -r SCRIPT_DIR=${SSI_TOP_DIR}/bin
    DebugEcho $VERBOSE "setting SCRIPT_DIR       = $SCRIPT_DIR"
fi

#
# INFO BLOCK
#

DebugEcho $VERBOSE "info block"

# May want to remove these.
DebugEcho $VERBOSE ""
DebugEcho $VERBOSE "RUN: $0 on `date`"
DebugEcho $VERBOSE "VERSION = preMORT5 \$Id: stereopair2wits.bash,v 1.45 1999/12/02 22:53:09 schwehr Exp $Id$"
DebugEcho $VERBOSE "SSI_TOP_DIR          = $SSI_TOP_DIR"
DebugEcho $VERBOSE "SSI_DATA_TOP_DIR     = $SSI_DATA_TOP_DIR"
DebugEcho $VERBOSE "SCRIPT_DIR           = $SCRIPT_DIR"
DebugEcho $VERBOSE "BIN_DIR              = $BIN_DIR"

declare -r OS=`uname`

# This is specific to mvacs.ucla.edu
DebugEcho $BOMBASTIC "FIX: need a better way to detect mvacs SunOS."
DebugEcho $VERBOSE "OS check for need of fortran env $OS"
if [ "$OS" = "SunOS" ]; then
    if [ -f /usr/local/scripts/fortran-env.sh ]; then
	source /usr/local/scripts/fortran-env.sh
    else
	echo "ERROR: missing /usr/local/scripts/fortran-env.sh"
	echo "  Required for running marsxyz, which"
	echo "  is linked with libF77."
	echo "  /usr/local/SUNWspro/lib"
	exit $EXIT_FAILURE
    fi
fi

DebugEcho $BOMBASTIC "should prob set umask and group(sys.ssi)"

######################################################################
# LOGGING
######################################################################

DebugEcho $BOMBASTIC "FIX: add logging redirect here."

######################################################################
# Global variables and constants
######################################################################

# These are all the programs/binaries that we rely on.
# Do not try to find them by path... nice to know what is where!

# Normal system thingies.
declare -r rm=/bin/rm	# GNU rm seems to segfault a lot on IRIX 6.5???
declare -r mv=/bin/mv
declare -r gnuDate=${BIN_DIR}/gnu_date

# Kurt's helper programs...
declare -r vicGetLabelEntries=${BIN_DIR}/vicGetLabelEntries

declare -r stereo=${BIN_DIR}/stereo
declare -r vicarXYZtoVRML=${BIN_DIR}/vicarXYZtoVRML

# fm = flight model (millions of kilometers away)
# em = engineering model (at MVACS)
declare -r stereoDefault="${SCRIPT_DIR}/stereo.default.james.fm"
#declare -r stereoDefault="${SCRIPT_DIR}/stereo.default"

declare -r vicar2rgb=${BIN_DIR}/vicar2rgb
#Used to use the pnm tools.
#declare -r rgb3toppm=${BIN_DIR}/rgb3toppm
#declare -r pnmtosgi=${BIN_DIR}/pnmtosgi

# Software by Justin Maki -- justin.maki@jpl.nasa.gov
# Does the projection from disparity to xyz points.
# Part of the "JAMES" pipeline
declare -r marsxyz=${BIN_DIR}/marsxyz


########################################
# Binaries from vicar2wits.3files  ~tso
# /u1/tso/tools/mipl/bin/vicar2wits

# m98cam4 -- Builds a cahvor calibration file from the VICAR image header.
# vicar2pic -- MIPL VICAR to width+height+data
# warp-cahvor -- 
# convert -- ImageMagick tool to change image formats.
# FIX: continue with Documentation

declare -r vicar2jpg=${BIN_DIR}/vicar2jpg
declare -r m98cam=${BIN_DIR}/m98cam6
declare -r java=${BIN_DIR}/java
#declare -r vicar2ranutil=${BIN_DIR}/vicar2ranutil_2

# Stubbe's program to check a file for valid vicar format.
declare -r check_vicar=${BIN_DIR}/check_vicar

# FIX: may want to check for the existance of all bins before continuing.

# NOTE: more declare's in the Dynamic Environment Setup section.

######################################################################
# Immediate helper functions
######################################################################

DebugEcho $VERBOSE "Immediate help functions"

# $1 is $EXIT_SUCCESS or $EXIT_FAILURE
exitHandler ()
{
    echo Should remove the tmpDir before exiting.
    exit $1
}

########################################
#
# Make sure a directory exists.
#
createVerifyDir()
{
    declare -r newDir=$1
    # FIX: do we want to remove this echo?
    #echo " createVerifyDir ( $newDir )"
    if [ ! -d $newDir ]; then
	DebugEcho $VERBOSE "Creating $newDir"
	mkdir $newDir
    fi
    if [ ! -d $newDir ]; then
	echo ls -l $newDir
	ls -l $newDir
	echo ""
	echo "ERROR: Bugger off.. $newDir is not a directory!"
	exit $EXIT_FAILURE
    else
	chgrp sys.ssi $newDir
	# Could be done better with a umask of 002 for read write.
	chmod g+s $newDir
	chmod o-w $newDir
	chmod g+w $newDir
    fi
}



# $1 is the file to check.
checkVicar ()
{
  if [ -x $check_vicar ]; then
    DebugEcho $VERBOSE "checkVicar $check_vicar $1"
    $check_vicar $1
    if [ 0 != $? ]; then
	echo "ERROR ($?) : check_vicar returned EXIT_FAILURE."
	echo "  File ($1) does not appear to be a valid vicar file."
	echo "  FAILING..."
	exit $EXIT_FAILURE
    fi
  else
    true
  fi
}


usage()
{
    DebugEcho $TRACE ""
    DebugEcho $TRACE " *** FIX this up! -- add explainations."
    echo ""
    echo "usage: $0 leftImage rightImage [outputDir]"
    echo ""
    echo "Add a description of the environment variables that can be set."
}

######################################################################
# Dynamic Environment setup.
######################################################################

DebugEcho $BOMBASTIC "Make sure we have a reasonable # of args"
if [ $# -eq 2 ]; then
    true
elif [ $# -eq 3 ]; then
    true
else
    echo
    echo "ERROR: Did not find a valid number of args."
    echo
    usage
    exit $EXIT_FAILURE
fi

declare -r leftImageSource=$1
declare -r rightImageSource=$2

checkVicar $leftImageSource	# comment this out if more speed is needed.
checkVicar $rightImageSource	# comment this out if more speed is needed.

declare -r leftImage=`basename $1`
declare -r rightImage=`basename $2`

declare -r imageRoot=${leftImage%%l.*}	# Ignore all extentions.

# create a tmp directory to store the intermediate files. The tmpDir
# contains a process ID so multiple instance of the script can run in
# parallel without interfering.

declare -r cmdName=${0##*/*/}
declare -r tmpDir=/var/tmp/$cmdName.$$
DebugEcho $TRACE "tmpDir                   = $tmpDir"

# basic name of our temp files without left/right or extention.
declare -r tmpFileBase=${tmpDir}/$imageRoot

DebugEcho $BOMBASTIC "Num args = $#"
if [ $# -eq 2 ]; then
    #echo "checking planet day num"
    tmpSol=`$vicGetLabelEntries $leftImageSource PLANET_DAY_NUMBER`
    if [ "-1" = $tmpSol ]; then
	declare -r outputDir="$SSI_SOL_UNKNOWN"
    elif [ "-9.99e+31" = $tmpSol ]; then
	declare -r outputDir="$SSI_SOL_UNKNOWN"
    elif [ "-9.99e+31 " = $tmpSol ]; then
	declare -r outputDir="$SSI_SOL_UNKNOWN"
    else
        tmpSol=${tmpSol%.*}	# Strip from the . to end for printf
	declare -r outputDir=`printf "sol%03d" $tmpSol`
    fi
elif [ $# -eq 3 ]; then
    declare -r outputDir=$3
else
    echo "ERROR: Did not find a valid number of args."
    usage
    exit $EXIT_FAILURE
fi

DebugEcho $VERBOSE "outputDir                = $outputDir"

# FIX: should do a bunch of if statements to let the user define all these.
declare -r witsTopDir=${SSI_DATA_TOP_DIR}/wits
declare -r vapDir=${SSI_DATA_TOP_DIR}/vap

declare -r dispDir=${vapDir}/disparity/$outputDir
declare -r rangeDir=${vapDir}/range/$outputDir
declare -r vrmlDir=${vapDir}/vrml/$outputDir

declare -r witsDir=${witsTopDir}/$outputDir

# '%H' is 00...23 to fix the early morning bug.  (Cinderella)
declare -r timeStamp=`$gnuDate +%Y%m%d%H%M%S`	# Bleck! But it works.

declare -r wedgeTmp=${witsDir}/tmp.${imageRoot}.${timeStamp}
declare -r wedge=${witsDir}/${imageRoot}.${timeStamp}

#echo ""
#echo "Destination Directories:"
DebugEcho $VERBOSE "    dispDir              = $dispDir"
DebugEcho $VERBOSE "    rangeDir             = $rangeDir"
DebugEcho $TRACE "    vrmlDir              = $vrmlDir"
DebugEcho $TRACE "    witsDir              = $wedge"

######################################################################
# Email logging
######################################################################
#
# This section will send an email out to an address.
# The goal is to use procmail to build a web page that shows the runs
# that occur.

#  declare -r RECIPIENT=schwehr@artemis.arc.nasa.gov

#  echo Sending mail to $RECIPIENT ...

HOSTNICK=`uname -n`

if [ 0 == 1 ]; then

cat <<- EOF #| mail $RECIPIENT 
	PROGRAM     MCP -- Master Control Program
	ARGS        $0 $1 $2 $3 $4 $5 $6
	USER        $USER
	NODE        `uname -n`
	DOMAINNAME  `domainname`
	OS          `uname`
	OSREL       `uname -r`
	PROCESSOR   `uname -p`
	NSLOOKUP    `nslookup $HOSTNICK | grep -i name`
	DATE        `date`
EOF

fi

######################################################################
# GENERIC HELPER FUNCTIONS
######################################################################

# This script may use stuff not implimented in bash 1.x
checkBashVersion()
{
    declare -ir minBashVersion=2
    declare -ir bashMajorVersion=${BASH_VERSION%%.*}

    if [ $minBashVersion -gt $bashMajorVersion ]; then
	echo "*** ERROR:"
	echo "  Found bash version $BASH_VERSION."
	echo "  Need version ${minBashVersion}.x or higher."
	exit $EXIT_FAILURE
    fi
    DebugEcho $BOMBASTIC "  Bash version okay."
}

# Just for safety, let's make sure we are in a known environment.
# If not, then someone will probably have to do some tweaking.
checkOS()
{
    declare -r okOSName=SunOS
    declare -r OSName=`uname`
    if [ $okOSName != $OSName ]; then
	echo "*** ERROR:"
	echo "  Found OS: $OSName"
	echo "  Expected: $okOSName"
	exit $EXIT_FAILURE
    fi

    DebugEcho $VERBOSE "Not checking revision of OS.  Assuming it is ok."
#    declare -r okOSrev="5.7"
#    declare -r OSrev=`uname -r`
#    if [ $okOSrev != $OSrev ]; then
#	echo "*** ERROR:"
#	echo "  Found OS rev: $OSrev"
#	echo "  Expected: $okOSrev"
#	exit $EXIT_FAILURE
#    fi

#    declare -r nodeName=`uname -n`
#    if [ "fury.mvacs.ucla.edu" != $nodeName ]; then
#	echo "*** ERROR:"
#	echo "  Must be run on fury.mvacs.ucla.edu"
#	echo "  Hopefully the VICAR guys will fix this soon."
#	exit $EXIT_FAILURE
#    fi

    #echo "  OS checks out okay."
}

showParameters()
{
    echo "stereopair2wits parameters:"
    echo "  imageRoot = $imageRoot"
    echo "  leftImage = $leftImage"
    echo "  rightImage = $rightImage"
    echo "  leftImageSource = $leftImageSource"
    echo "  rightImageSource = $rightImageSource"
    echo "  outputDir = $outputDir"
    echo "  tmpDir = $tmpDir"
    echo "  "
    echo "  $SSI_DATA_TOP_DIR"
    echo "  "
    echo "  stereo = $stereo"
    echo "  stereo.default = $stereoDefault"
    echo "  "
    echo "  m98cam = $m98cam"
    echo "  vicar2pic = $vicar2pic"
    echo "  warp-cahvor = $warpCahvor"
    echo "  pic2gif = $pic2gif"
    echo "  convert = $convert"
    echo "  combine = $combine"
    echo "  vicar2ranutil = $vicar2ranutil"
    echo "  WITS = $WITS"
    echo "  java = $java"
    echo "  WitsRange = $WitsRange"
    echo "  wedge = $wedge"
}


######################################################################
# Work Functions
######################################################################

########################################
# FUNCTION:  buildRangeMap
#
# INPUTS: leftImage, rightImage, stereo.default files.
#
# NOTES: Uses tmpDir on localhost for intermediate files.
# 	This should increase performace.  And temp files don't need a hostname.
#	tmp files have process id pre-pended to prevent collisions.

buildRangeMap ()
{
    DebugEcho $VERBOSE ""
    DebugEcho $TRACE " --- build range map ---"
    DebugEcho $VERBOSE ""

    DebugEcho $VERBOSE "Run the Ames correlator: gen a disparity file"
    $stereo -d $stereoDefault $leftImageSource $rightImageSource $tmpFileBase
    if [ 0 != $? ]; then
	echo "FIX: must remove the tmp directory before we crash the machine!"
	echo "ERROR ($?) : Ames stereo correlator returned EXIT_FAILURE."
	echo " leaving partial tmp directory to document failure."
	exit $EXIT_FAILURE
    fi
    DebugEcho $VERBOSE ""

    checkVicar ${tmpFileBase}l.vdisp
    checkVicar ${tmpFileBase}l.hdisp

    # Wits now does the conversion from lander to ssi coordinate frames.
    mv ${tmpFileBase}l.[vh]disp ${dispDir}/

    DebugEcho $BOMBASTIC "Not producing jpgs of hdisp and vdisp"
    #$vicar2jpg --quality 75 ${dispDir}/${imageRoot}l.hdisp ${dispDir}/${imageRoot}l.hdisp.jpg
    #$vicar2jpg --quality 75 ${dispDir}/${imageRoot}l.vdisp ${dispDir}/${imageRoot}l.vdisp.jpg

    DebugEcho $VERBOSE "Run marsxyz to take a disparity and make a xyz file."
    DebugEcho $BOMBASTIC "Justin, explain marsxyz.pdf & calibration directory."

    # The calibration directory contains info needed by marsxyz for camera
    # calibration.  Used to only be on fury.  Now this env variable defines
    # the location of these critical files.
    MARS_CONFIG_PATH=${SCRIPT_DIR}/calibration
    export MARS_CONFIG_PATH

    # linedisp is threshold value for maxium disparity.
    $marsxyz inp=\($leftImageSource, $rightImageSource\) \
     dispar=\(${dispDir}/${imageRoot}l.vdisp,${dispDir}/${imageRoot}l.hdisp\)\
     out=$rangeDir/${imageRoot}l.xyz err_file=${tmpFileBase}.error linedisp=50\
     coord="MVACS"

    # NOTE: vicar programs return 1 on success, 0 on failure.
    # This is the opposite of normal Unix programs.
    if [ 1 != $? ]; then
	# Wits does not report an error to stderr on trouble.
	echo "ERROR: marsxyz failed"
	echo "Abandon ship."
	echo exit $EXIT_FAILURE -- not yet...
    fi

    cp $rangeDir/${imageRoot}l.xyz ${wedgeTmp}/left-range-1.xyz
    # FIX: this should be a sym link, but was accidentally not relative.
    (cd $wedgeTmp; ln -s left-range-1.xyz left-range-1.ran)

    checkVicar $rangeDir/${imageRoot}l.xyz

    DebugEcho $VERBOSE "FIX: Eric says the -z will disappear for the mission"
    # -z flag will cause the xyz to vrml to take data from lander coord to
    # mvacs coord.  The normal without -z is to work in mvacs.
    $vicarXYZtoVRML -d $stereoDefault ${dispDir}/${imageRoot}l.hdisp \
	$rangeDir/${imageRoot}l.xyz $tmpFileBase
    
    $mv ${tmpFileBase}l.wrl  $vrmlDir/${imageRoot}l.wrl
    $mv ${tmpFileBase}lA.ppm $vrmlDir/${imageRoot}lA.ppm
    DebugEcho $VERBOSE "FIX: Kurt - convert the altitude texture to rgb."

    # FIX: output a B/W rgb image based on what DN levels?
    $vicar2rgb -bw $leftImage $vrmlDir/${imageRoot}lT.rgb
    #$rgb3toppm ${tmpFileBase}lT.pgm ${tmpFileBase}lT.pgm \
    #	${tmpFileBase}lT.pgm | $pnmtosgi > $vrmlDir/${imageRoot}lT.rgb

    # itsa file: data to display the terrain in 3D
    # Index Trangle Strip Array
    DebugEcho $VERBOSE  "JavaWits range to make an .itsa file."
    $java -classpath ${JAVA_DIR}/wits.jar \
	server.RangeFile itsa $wedgeTmp/left-range-1.xyz 4
    if [ 0 != $? ]; then
	echo $java -classpath ${JAVA_DIR}/wits.jar \
	    server.RangeFile itsa $wedgeTmp/left-range-1.xyz 4
	echo " ******************************"
	echo " ** ERROR: WitsRange failed"
	echo " ******************************"
    fi
    DebugEcho $VERBOSE ""

    DebugEcho $TRACE "Wits java generates the {left,right}.data files"
    $java -classpath ${JAVA_DIR}/wits.jar \
	server.RangeFile data $wedgeTmp/left-range-1.xyz $wedge CAHVOR
    if [ 0 != $? ]; then
	echo $java -classpath ${JAVA_DIR}/wits.jar \
	    server.RangeFile data $wedgeTmp/left-range-1.xyz $wedge CAHVOR
	echo " ******************************"
	echo             " ** ERROR: WitsRange failed"
	echo " ******************************"
    fi
    DebugEcho $VERBOSE ""
    DebugEcho $VERBOSE "Done with buildRangeMap"
}

########################################
# FUNCTION:  buildImages
#
# INPUTS: 
#
# OUTPUTS: left/right jpg images and a cahvor camera model.
#
# NOTES: replacement for buildWarpedImage,
# 		since wits no longer needs warped images.

buildImages ()
{
    DebugEcho $VERBOSE ""
    DebugEcho $TRACE " --- build images ---"
    DebugEcho $VERBOSE ""

    # This will hopefully go away when wits will be able to read the 
    # vicar file and compute the cahvor model.
    DebugEcho $VERBOSE "Create the .cahvor camera model file for each image."
    $m98cam $leftImageSource  ${wedgeTmp}/left.cahvor
    $m98cam $rightImageSource ${wedgeTmp}/right.cahvor
    DebugEcho $BOMBASTIC ""

    declare -r imgFormat=`$vicGetLabelEntries $leftImageSource FORMAT`

    # FIX: the range should really be figured out from labels in the files!
    # Should convert from radians to dn using linear fix in vicar2jpg...

    # Mask files will only be using the mask file output from the Ames
    # stereo.  No using xyz based masks.
    $vicar2jpg -i 5 --emask $leftImageSource ${tmpFileBase}l.eMask \
	${wedgeTmp}/left-masked-hi.jpg
    $vicar2jpg --anaglyph $leftImageSource $rightImageSource \
	${vapDir}/images/anaglyph/${imageRoot}-anaglyph.jpg

    if [ "'HALF'" == $imgFormat ]; then
      # --range 0 4095 
      $vicar2jpg -i 5 $leftImageSource  ${wedgeTmp}/left-bw-hi.jpg
      $vicar2jpg -i 5 $rightImageSource ${wedgeTmp}/right-bw-hi.jpg
      $vicar2jpg --anaglyph --range 0 4095 $leftImageSource $rightImageSource \
	${wedgeTmp}/anaglyph-bw-hi.jpg
      DebugEcho $BOMBASTIC "xyz mask not working... need labels in .xyz"
      #$vicar2jpg --range 0 4095 --xyzmask $leftImageSource \
	#${wedgeTmp}/left-range-1.xyz ${wedgeTmp}/left-xyzmasked-hi.jpg
    elif [ "'REAL'" == $imgFormat ]; then
        # breid and schwehr decided to let cal images autorange for now.
        $vicar2jpg -i 5 $leftImageSource  ${wedgeTmp}/left-bw-hi.jpg
        $vicar2jpg -i 5 $rightImageSource ${wedgeTmp}/right-bw-hi.jpg
        $vicar2jpg --anaglyph $leftImageSource $rightImageSource \
  	  ${wedgeTmp}/anaglyph-bw-hi.jpg
        DebugEcho $BOMBASTIC "xyz mask not working... need labels in .xyz"
    else
      echo "WARNING: FORMAT is not REAL or HALF ( $imgFormat )"
      echo "WARNING: using vicar2jpg without a range... it will autorange"
      $vicar2jpg $leftImageSource  ${wedgeTmp}/left-bw-hi.jpg
      $vicar2jpg $rightImageSource ${wedgeTmp}/right-bw-hi.jpg
      $vicar2jpg --anaglyph $leftImageSource $rightImageSource \
	${wedgeTmp}/anaglyph-bw-hi.jpg
      #$vicar2jpg --mask $leftImageSource \
      #${wedgeTmp}/left-range-1.xyz ${wedgeTmp}/left-xyzmasked-hi.jpg
    fi

    DebugEcho $BOMBASTIC ""

    DebugEcho $VERBOSE "Done with buildWarpedImage"
}


########################################
# FUNCTION:  checkFilterNum
#
# INPUTS: $1 is the image to check
#
# OUTPUTS: bails if the wrong filter number
#
# NOTES: Only want to do stereo on filter 5 (red) since
# marsxyz only has calibration data for that filter.
# See Justin Maki for more infor.

checkFilterNum ()
{
    DebugEcho $VERBOSE "..... check filter num"
    declare biteMe=`$vicGetLabelEntries $1 FILTER_NUMBER`
    # NOTE: make sure the space is there for this comparison.
    if [ "'5' " = "$biteMe" ]; then
	DebugEcho $BOMBASTIC "Found red filter... good, can do stereo on it."
    else
	echo "Not a red filter image ('5')... found $biteMe"
	DebugEcho $TRACE "Bailing on processing."
	DebugEcho $BOMBASTIC ""
	DebugEcho $VERBOSE "  ------------- END stereopait2wits -------------"
	DebugEcho $BOMBASTIC ""
	exit $EXIT_FAILURE
    fi
}



######################################################################
# Main code - starts here
######################################################################

DebugEcho $BOMBASTIC "Paranoid Mode: (standard)"
checkBashVersion
checkOS

# If the directory does not exist, create it.
# When the dir can't be created, die.
createVerifyDir $tmpDir
createVerifyDir $witsDir
createVerifyDir $wedgeTmp
createVerifyDir $vrmlDir
createVerifyDir $rangeDir
createVerifyDir $dispDir

#echo "FIX: check a link for wits based on the sol number"
#echo "From Kam..."
#echo "Before landing, we can do:"
#What the heck???????????????
#echo "ln -s /proj/ops/ssi/<phase>/data/wits/sol000 \
#        /u/1/mvacs.ucla.edu/wits/dbs-mvacs/results/<phase>"
#echo "After landing, we can do:"
#echo "ln -s /proj/ops/mspl/Landed/d/data/wits/sol<nnn> \
#        /u/1/mvacs.ucla.edu/wits/dbs-mvacs/results/sol<nnn>"

#showParameters

checkFilterNum $leftImageSource
buildRangeMap		# Also builds an itsa file... tells ansillary info.
buildImages		# Create a cahv file and a warped jpg.

mv $wedgeTmp $wedge	# Successful build of wedge, so move into place.
			# Left in place with "tmp." prefix if bombed.

#echo "FIX: add a link in wits/wqueue"
#echo ln -s $wedge $witsQueue/


$rm -rf $tmpDir # remove the tmpDir

DebugEcho $VERBOSE "FIX: scp vrml to origin.arc.nasa.gov then to hq.nasa.gov"

# FIX: Not sure about this... 
# FIX: Add ssh keys for people who can run this script, get data to ames?"

echo "exited successfully" 
exit $EXIT_SUCCESS

######################################################################
# END OF FILE

#
#
# $Log: stereopair2wits.bash,v $
# Revision 1.45  1999/12/02 22:53:09  schwehr
# Switched to the flight model stereo default file.
#
# Revision 1.44  1999/12/02 01:13:58  schwehr
# added ignore pixels to emask image
#
# Revision 1.43  1999/12/01 06:40:37  schwehr
# Oops on DebugEcho
#
# Revision 1.42  1999/11/30 23:43:41  schwehr
# Renamed left-masked.jpg to left-masked-hi.jpg per request from Backes.
#
# Revision 1.41  1999/11/25 01:00:10  schwehr
# Fixed a bad debugecho.
#
# Revision 1.40  1999/11/24 21:14:47  schwehr
# Strips of the decimal place of planet day number, so printf can handle it.
#
# Revision 1.39  1999/11/20 01:26:19  schwehr
# DebugEcho is more terse now.
# Switch sol_unknown to be configurable with SSI_SOL_UNKNOWN.
#
# Revision 1.38  1999/11/18 20:23:36  schwehr
# Produces anaglyphs for vap/images/anaglyph.
# Fixed so that wits will now get anaglyphs.
#
# Revision 1.37  1999/11/17 01:50:37  schwehr
# Fixed handling of planet day number.
# Made wits errors more obvious
#
# Revision 1.36  1999/11/16 19:56:15  schwehr
# Reduced the amount of output on a normal run by a large amount.
#
# Revision 1.35  1999/11/16 18:49:36  schwehr
# DebugEcho strips path off before showing script name.
# Added planet day number additions for the new def with PDS_FLOAT_NULL.
#
# Revision 1.34  1999/11/15 21:52:04  schwehr
# Switched marsxyz to MVACS coord frame.
#
# Revision 1.33  1999/11/15 21:47:46  schwehr
# removed the -z flag now that we are moving back to all mvacs
# coordinate frame.
#
# Revision 1.32  1999/11/12 01:26:43  schwehr
# Added temporary -z flag for vicarXYZtoVRML
#
# Revision 1.31  1999/11/10 23:06:46  schwehr
# Changed many echos to DebugEchos.
# Fixed a bug in calling of checkVicar.
#
# Revision 1.30  1999/11/10 22:26:46  schwehr
# Some cleanup of echo's.
# Put in, a hdisp to jpg line but commented it out.
# emask files are now being written ask .masked.
# Commented out the xyz mask files.
#
# Revision 1.29  1999/11/10 07:19:52  schwehr
# Change to --xyzmask
# Added checkFilterNum() looking for red images.
# Removed buildWitsImageData().
#
# Revision 1.28  1999/11/10 02:53:05  schwehr
# Fixed a bug with the naming of the hdisp files for vicarXYZtoVRML.
# Added emask jpg generation.
# Added check_vicar for .xyz files.
# Now autoranges with ignoring the top 5 pixels.  Should give better EM results.
#
# Revision 1.27  1999/11/08 19:15:35  schwehr
# Converted an off by iff block to DebugEcho VERBOSE.
# Moved stereo.default file to SCRIPT_DIR from BIN_DIR.
# Now calls vicarXYZtoVRML.
#
# Revision 1.26  1999/11/04 23:52:04  schwehr
# Turned off the forced 0..1 ranging for data going into the jpgs, as
# agreed to by breid and schwehr.  May implement better when we have a
# smarter way later.  Maybe ditch the top X percent.
#
# Revision 1.25  1999/11/04 16:05:36  schwehr
# LARGE NUM OF CHANGES (not tested):
#   Created DebugEcho()
#   debugLevel now controlled by SSI_VERBOSITY
#   Now only tries to source fortran env on Solaris.
# 	Needs better check for mvacs env.
#   Created stub exit_handler()
#   createVerifyDir() moved.
#   Created checkVicar() that is okay if it doesn't find check_vicar.
#
# Revision 1.24  1999/11/04 15:58:29  schwehr
# Fixed Cinderella bug in timeStamp.
#
# Revision 1.23  1999/10/25 06:10:43  schwehr
# Hopefully should fix the abs sym link to correct relative link.
#
# Revision 1.22  1999/10/22 20:48:38  schwehr
# Changed version to preMORT5
#
# Revision 1.21  1999/10/22 20:38:27  schwehr
# Added a scary link for Kam to link .xyz to .ran.
# 	These .ran files are not in .ran format.  This is to help the
# 	wits team not have to fix a whole bunch of hard coded
# 	parameters.  I suggest using emacs tags replace.
# check_vicar shell function not yet written.
#
# Revision 1.20  1999/10/21 00:10:35  schwehr
# Switched to preMORT5.
# Switched from .ran to .xyz
# 	.ran is definted as a format similiar to a JPL .pic
# 	.xyz is doc'ed as a vicar file.
#
# Revision 1.19  1999/10/20 23:28:10  schwehr
# Untested changes:
#    Kam's new wits data file generator.
#    Removed cat generation of .data files.
#    chgrp & chmod of new directories.
#
# Revision 1.18  1999/10/20 18:05:00  schwehr
# tmpDir is now removed at the end of processing.
# Started putting in vicarXYZtoVRML, but don't know how to call it.
# Switch from netpbm to Kurt's vicar2rgb program.
#
# Revision 1.17  1999/10/20 17:21:46  schwehr
# Minor cleanup... cosmetic.
#
# Revision 1.16  1999/10/14 05:37:07  schwehr
# Fixed the MARS_CONFIG_PATH for marsxyz.
#
# Revision 1.15  1999/10/14 03:33:27  schwehr
# Some files are getting marked as bad by Stubbe's program.  There is
#   probably something wrong with the files, but now it won't exit on
#   them.
# Justin fixed the only run on fury problem.
# Added the mask image between range missing and the original image for wits.
#
# Revision 1.14  1999/10/13 17:14:21  schwehr
# Now call Stubbe's check_vicar program to make sure we have valid vicar
# files being generated... anything we can do for error checking during
# development!!  Probably should be comment out after everything is
# stable... if that EVER happens.
#
# Revision 1.13  1999/10/13 17:06:37  schwehr
# Fixed Jonathon's email address.
# Added Stubbe's check_vicar program.
# Fix the status checking of marsxyz... opposite of Unix convention.
# Added more notes about required scp of data to nasa hq.
#
# Revision 1.12  1999/10/11 21:16:14  schwehr
# Fixed usage of BIN_DIR for gnu_date and vicGetLabelEntries.
# for vicar2jpg, range is now based on FORMAT.
#
# Revision 1.11  1999/10/11 17:26:47  shviid
# Add email sfhviid@linmpi.mpg.de to contact list
#
# Revision 1.10  1999/10/09 02:07:12  schwehr
# Added not for imcompress.
# Added anaglyph generation.
#
# Revision 1.9  1999/10/08 20:57:32  schwehr
# Now uses sol_unknown if PLANET_DAY_NUMBER does not exist.
# Added commend on where code should be added for WITS links.
#
# Revision 1.8  1999/10/08 00:11:11  schwehr
# Added notes on things to be done.
#
# Revision 1.7  1999/10/06 20:14:42  schwehr
# Untested cleanup... removed lots!
# 	Unused declares for programs.
# 	old marsxyz comments
# 	vicar2ranutil comments
# 	old java gen comments
# 	buildWarpedImage() is history!!!
# 	updatePanData()
# Added:
# 	Beginnings of mail notification uncommented.  Does not mail.
# 	Makes sure we are running of fury.
#
# Revision 1.6  1999/10/06 19:57:02  schwehr
# The last of the big merges.
# End of side step.
# This is where everything is finally in CVS and the history is
# preserved for the amusement of posterity.  Please be nice in your
# judgement!
#
# Revision 1.5  1999/10/06 19:49:50  schwehr
# This is the version from 5-Oct that generates bad .cahvor files?
# NOT a straight diff from prev version... side step.
# First retreat1 version.  Mostly just for ref before the last big merge.
#
# Revision 1.4  1999/10/06 19:26:19  schwehr
# Kurt's modification from Justin's wits_cursor_fix:
# 	a.k.a. devel-991004-stereopair2wits.bash
# 	Added email change warning.
# 	Added debug levels - not yet used.
# 	Removed change of LD_LIBRARY_PATH for ImageMagick.
# 	Big fix up of program paths.  Most relative to BIN_PATH now.
# 		m98cam5 may not like this...
# 	Fixed up sol # dection towards landed readiness.
# 	OS detection does not force 5.7 for SunOS... will bring back later.
# 	Removed some copies by just of the .xyz file.
# 	No longer call vicar2ranutil... wits can now read the xyz file.
# 	Changed the calling for generation of itsa file for Kam's changes.
# 	Added buildImage to replace buildWarpedImages.
# 		Does this cause a bug with the cahvor file?
# 	Added fix comment for marsxyz.
# 	Switched from buildWardImage to buildImages.
# 	Don't call updatePanData... NOP... Kam has a better GUI.
#
# Revision 1.3  1999/10/06 18:49:47  schwehr
# Merged in Justin's changes in wits_cursor_fix:
# 	cp the xyz file from range to wedge/left-range-1.xyz
# 	cp cahvor files from tmp to {left,right}.cahvor
# 	run pic2gif on the unwarped pics
# 	run convert on the unwarped gifs
#
# Revision 1.2  1999/10/06 18:31:49  schwehr
# Added commented out email notification from mort4 devel script.
#
# Revision 1.1.1.1  1999/09/15 20:25:48  schwehr
# The version used for mort4.
#
# Revision 1.7  1999/09/15 00:15:07  schwehr
# Now output the revision number on each run to stdout.
# Converts pgm to rgb for the vrml files.
# New variables for new directories:
# 	vapDir, dispDir, rangeDir
# xyz and disp files are now saved in vap area and not deleted.
# New function createVerifyDir().
#
# Revision 1.6  1999/09/14 17:55:21  schwehr
# Minor cleanup.  Use uname for arch.
#
# Revision 1.5  1999/09/14 16:59:46  schwehr
# Fixed default setting of variables.
#
# Revision 1.4  1999/09/14 16:44:10  schwehr
# Large amount of changes:
# 	Reordered variables to top.
# 	Began moving binaries to $SSI_TOP_DIR/bin
# 	Now put all tmp files in a subdir under /var/tmp based on PID
# 	Fixed the texture file name.
# 	Now use a "wedge" to write the wits data to.
# 	Removed a fair bit of cruft.
#
# Revision 1.3  1999/09/13 20:05:47  schwehr
# Now searches for PLANET_DAY_NUMBER.  If not found, assumes sol000.
# Moved imageNames up highter in the file.
# Moved the paranoid checks to the bottom of the file.
# Changed the default SSI_DATA_TOP_DIR to mort4
# Created a timestamp for the wits wedge.
#
# Revision 1.2  1999/09/13 16:47:29  schwehr
# Justin changed m98cam to take 2 args
#
######################################################################
