#! /bin/sh
#
# Usage:
#   acis_fef_lookup infile chipid chipx chipy [verbose]
#
# See 'ahelp acis_fef_lookup' for instructions. 
# If you want the PI FEF you can no longer use this script
# to find it, since the PI RMFs generated from the PHA FEFs
# (a capability introduced in CIAO 2.3) are better than
# the RMFs generated from the PI FEFs.
#
# Notes:
#  the interface has changed since CIAO 2.2.1
#  a) We now supply the name of the event file rather
#     than the value of TSTART
#     - this allows the code to use quizcaldb to query
#       the CALDB rather than performing a manual search
#       and will also us to pick up whether the CTI
#       corection has been applied
#  b) The type parameter has been dropped, since we are
#     now using dynamic rebinning (aka "PI on the fly") to
#     create PI RMF's from PHA FEF's
#  c) Since we are now querying the CALDB the root parameter has
#     been removed
#  d) A verbose parameter has been added
#  e) We die if the .par file can not be found
#
# CIAO version: 2.3
# last update:  22 Oct 2002
#

# Usage:
#   domsg $value $message_string
#
# echo the supplied text to STDOUT IF the global variable
# $verbose is > $value
#
# Example:
#   domsg 1 "Extract background spectrum $bg from $bgevents"
#   domsg 1 Extract background spectrum $bg from $bgevents
#
domsg() {
    vval=$1
    shift
    msg=$@
    if [ $verbose -gt $vval ]; then
        echo "$msg"
    fi
}

getautopars()
{
    counter=0
    pfile=`paccess $prog`
    param_list=`cut -d, -f1 $pfile`
    acclist=`cut -d, -f3 $pfile`
    hidden_param_list=""
    auto_param_list=""
    nauto=0
    nc=1
    # count auto params
    # The acclist is a a a a h h
    # Advance by 2 chars each time
    #
    for param in $param_list
    do
	atmp=`echo $acclist | cut -c$nc`
	if [ "$atmp" = "a" ]; then
	    nauto=`expr $nauto + 1`
	    nc=`expr $nc + 2`
	    auto_param_list=`echo $auto_param_list $param`
	else
	    hidden_param_list=`echo $hidden_param_list $param`  
	fi
    done

    #echo "NAUTO = $nauto"
    #echo auto params: $auto_param_list
    #echo hidden params: $hidden_param_list

} # getautopars()

getparams()
{
    enteredParamList=""
    getautopars

    while [ $# -gt 0 ]; do
	#--- count the parameters in the command line
	counter=`expr $counter + 1`

	with_param=`echo $1 | grep '\[.*='`
	if [ "$with_param" = "$1" ]; then  
	    # a parameter with DM filter present
	    with_params=`echo $1 | grep '=.*\['`

	    if [ "$with_params" = "$1" ]; then 
		# param name was specified
		param=`echo $1 | awk -F= '{print $1}'`
		value=`echo $1 | cut -f2- -d'='`
	    else     
		# param name not specified
		param=`echo $auto_param_list | cut -f$counter -d' '`
		value="$1"
	    fi

	else    
	    # no DM filter present
	    with_params=`echo $1 | grep =`

	    if [ "$with_params" = "$1" ]; then
		# param name was specified
		param=`echo $1 | awk -F= '{print $1}'`
		value=`echo $1 | cut -f2- -d'='`

	    else     
		# param name not specified
		param=`echo $auto_param_list | cut -f$counter -d' '`
		value="$1"
	    fi
	fi

	# if the param is not automatic, counter=(counter - 1)
	# UNLESS the user hasn't supplied a parameter name, which
	# is an error
	if [ "x$param" = "x" ]; then
	    echo "Problem opening parameter file: too many positional arguments"
	    exit
	fi

	is_auto_par=`echo $auto_param_list | grep $param`
	if [ "x$is_auto_par" = "x" ]; then 
	    #not an auto parameter
	    counter=`expr $counter - 1`
	else
	    # take out the name of the param from entered_param_list
	    for test_param in $param_list
	    do
		if [ "$test_param" = "$param" ]; then
		    entered_param_list=`echo $entered_param_list $test_param`
		fi
	    done
	fi 

	#  echo pset $prog ${param}="${value}"
	pset $prog ${param}="${value}"

	# The multi-value parameters which are read in as quoted strings must
	# have their values re-quoted before feeding them to pset()
	shift

    done

    #echo "Auto entered = $entered_param_list"

} # getparams()

# Usage:
#   get_fefname $infile
#
# Use the quizcaldb routine to find the FEF file appropriate for
# analysis of the data from file $infile ($infile need not be a PHA
# spectrum, it can be the L1 or L2 event file).
# If the header of $infile does not contain the CTI_CORR keyword
# we assume the data has NOT been corrected for CTI.
#
# Since, with CIAO 2.3, we are now using "PI on the fly" as the
# default way to create PI RMF's we ***ALWAYS*** return the PHA
# FEF.
#
# sets the global variable fefname with the name of the
# FEF file (including full path and the block name)
#
get_fefname() {
    infile="$1"

    # we are using "PI on the fly" so we always want the PHA FEF
    codename="FEF_PHA"

    # has the data been CTI corrected? Due to the current design of
    # the CALDB we have to manually add the cti_corr value as a
    # boundary keyword - ie it (currently) isn't automatically read
    # from the file header
    dmkeypar infile=$infile keyword=cti_corr >/dev/null 2>&1
    if [ "`pget dmkeypar exist`" = "yes" ]; then
	# check the key is sensible
	if [ "`pget dmkeypar datatype`" = "boolean" ]; then
	    expr="cti_corr.eq.`pget dmkeypar value`"
	else
	    echo "WARNING: CTI_CORR keyword in $infile is not a boolean - ignoring it"
	    expr="cti_corr.eq.no"
	fi
    else
        # assume it hassn't been CTI corrected
	expr="cti_corr.eq.no"
    fi

    punlearn quizcaldb
    domsg 1 "Running quizcaldb"
    domsg 2 "with parameters:"
    domsg 2 "  infile=$infile"
    domsg 2 "  codename=$codename"
    domsg 2 "  expr=$expr"

    quizcaldb infile=$infile codename=$codename expr=$expr >/dev/null 2>&1

    outfile=`pget quizcaldb outfile`
    domsg 1 "quizcaldb returned:"
    domsg 1 "$outfile"

    if [ "x$outfile" = "x" ]; then
	echo " "
	echo "ERROR: $prog unable to query CALDB using"
	echo " quizcaldb infile=$infile codename=$codename expr=$expr"
	echo " "
	pset $prog outfile=""
	exit 1
    fi

    # set output variable
    fefname=$outfile

} # get_fefname()

### Code
#

# initialize
prog=acis_fef_lookup
verbose=0
pacc=`paccess $prog`
if [ "x$pacc" = "x" ]; then
    # Unable to find the parameter file
    # we don't like this...
    echo " "
    echo "ERROR: $prog unable to find its parameter file"
    echo " "
    pset $prog outfile=""
    exit 1
fi

getparams $@
i=1
for param in $param_list
  do
  entered=`echo $entered_param_list | grep $param`
  if [ "x$entered" = "x" ]; then
      tparam=`pquery $prog $param`
  else
      tparam=`pget $prog $param`
  fi
  case $i in
      1 ) infile=$tparam;;
      2 ) chipid=$tparam;;
      3 ) chipx=$tparam;;
      4 ) chipy=$tparam;;
      5 ) outfile=$tparam;;
      6 ) verbose=$tparam;;
      7 ) mode=$tparam;;
      * ) echo "Unknown parameter $param";;
  esac
  i=`expr $i + 1`
# This is the only place we map the parameter file to script variables
done

domsg 0 "Running: $prog"
domsg 2 "with parameters:"
domsg 2 "  infile=$infile"
domsg 2 "  chipid=$chipid"
domsg 2 "  chipx=$chipx"
domsg 2 "  chipy=$chipy"
domsg 2 "  verbose=$verbose"
domsg 2 "  mode=$mode"
domsg 2 "  and CALDB is set to $CALDB"
domsg 2 "  and ASCDS_INSTALL is $ASCDS_INSTALL"

if [ ! -f $infile ]; then
    echo " "
    echo "ERROR: $prog unable to find infile"
    echo " $infile"
    echo " "
    pset $prog outfile=""
    exit 1
fi

# find the FEF
get_fefname $infile
domsg 1 "Found FEF file $fefname"

# if chipid=none or NONE then we don't need to bother
# with the spatial filter
#
if [ $chipid = "none" ] || [ $chipid = "NONE" ]; then
    echo $fefname
    pset $prog outfile=$fefname
    exit 0
fi

#
# Determine chip node and size of FEF "tile"
# (which is dependent upon chip and FP temperature)
#
# use the dm to find the chip ranges
# could just keep the XX_lo<= XX_hi>= syntax
# ie 
#  outfile="$fefname[ccd_id=$chipid,chipx_lo<=$chipx,chipx_hi>=$chipx,chipy_lo<=$chipy,chipy_hi>=$chipy]"
# but it's ugly
#
# really should do a check on output of dmlist command 
limits=`dmlist "${fefname}[ccd_id=$chipid,chipx_lo<=$chipx,chipx_hi>=$chipx,chipy_lo<=$chipy,chipy_hi>=$chipy][cols chipx,chipy]" data,clean | tail -1`

domsg 3 "FEF limits are [$limits]"
xlo=`echo $limits | cut -d' ' -f 1`
xhi=`echo $limits | cut -d' ' -f 2`
ylo=`echo $limits | cut -d' ' -f 3`
yhi=`echo $limits | cut -d' ' -f 4`
domsg 2 "Range of FEF region is $xlo to $xhi (chip x) and $ylo to $yhi (chip y)"

outfile="${fefname}[ccd_id=$chipid,chipx=${xlo}:${xhi},chipy=${ylo}:${yhi}]"
echo $outfile
pset $prog outfile=$outfile

## end
exit 0
