#! /bin/bash
# "@(#) $Id: ferosPackGuessTGZ,v 1.9 2005/11/26 08:33:41 jpritcha Exp $"

usage() {
  echo "Usage: ferosPackGuessTGZ [-hv] [-t tar.gz] [-W WLC-pref] <NNNN>"
  echo " "
  echo "<NNNN>"
  echo "   File number as in guess<NNNN>.tar.gz"
  echo "-v"
  echo "   Verbose"

  exit $exstat
}

FFpref="FF"
WLCpref="ThAr"

while [ -n "$1" ]
do
  case $1 in
    -h)   usage;;
    -t)   targz=$2; shift; shift;;
    -v)   vbose="v"; shift;;
    -F)   FFpref="${2}"; shift; shift;;
    -W)   WLCpref="${2}"; shift; shift;;
     *)   NNNN=$1; shift;;
  esac
done

if [ ${NNNN:-0} == 0 ]; then
  echo "Error!!! Must at least supply file number NNNN as in guess<NNNN>.tar.gz"
  exit 1
fi

if [ -e ${INTROOT}/bin/ferosSetEnvVars ]; then
  . ${INTROOT}/bin/ferosSetEnvVars
fi

[ -z "${targz}" ] && targz=guess${NNNN}.tar.gz
if [ -e ${targz} ]; then
  ThArIm="${WLCpref}${NNNN}.mt"
  if [ ! -e "${ThArIm}" ]; then
    echo "Error!!! Can not find image ${ThArIm}"
    exstat=1
    usage
  fi
# Get Variables from header...
  if [ ! -z "`gethead ${ThArIm} PROGID`" ]; then
## Probably a BIAS image...
    ProgId="`gethead ${ThArIm} PROGID`"
    YYYYMMDD="`gethead ${ThArIm} DATE-OBS`"
    TMSTART="`gethead ${ThArIm} TM_START`"
    ArchFile="`gethead ${ThArIm} ARCFILE`"
    DSoN="`dateStartofNight.pl $YYYYMMDD $TMSTART`"
    ArchTar="${ArchFile/fits/tar}"
  elif [ ! -z "`gethead ${ThArIm} 'HIERARCH ESO OBS PROG ID'`" ]; then
## Probably a FIERA image...
    ProgId="`gethead ${ThArIm} 'HIERARCH ESO OBS PROG ID'`"
    ArchFile="`gethead ${ThArIm} ARCFILE`"
#    dateObs="`gethead ${ThArIm} DATE-OBS`"
#    ymd="`echo $dateObs | cut -b1-10`"
#    hh="`echo $dateObs | cut -b12-13`" ; hh=`printf %d $hh`
#    mm="`echo $dateObs | cut -b15-16`" ; mm=`printf %d $mm`
#    ss="`echo $dateObs | cut -b18-19`" ; ss=`printf %d $ss`
#    (( tmstart = hh * 3600 + mm * 60 + ss ))
#    DSoN="`dateStartofNight.pl $ymd $tmstart`"
    mjd="`gethead ${ThArIm} MJD-OBS`"
    DSoN="`ferosMJD2DSofN.pl $mjd`"
    ArchTar="${ArchFile/fits/tar}"
  fi

# Make Directories if necessary
  if [ ! -d "${ProgId}" ]; then
    mkdir "${ProgId}"
  fi
  if [ ! -d "${ProgId}/${DSoN}" ]; then
    mkdir "${ProgId}/${DSoN}"
  fi

# Make the tar file with the data...
  if [ "${vbose:-0}" == "v" ]; then
    echo "create symbolic link ${ProgId}/${DSoN}/${targz} to ../../${targz}"
  fi
  ln -fs ../../${targz} ${ProgId}/${DSoN}/${targz}
# Make the tar file that will be used to copy across to VADRL
  tar --force-local -hc${vbose}f pack${targz/.gz} ${ProgId}/${DSoN}/${targz}
  gzip -9${vbose} --force pack${targz/.gz}

# Process tar file onto VADRL
  if [ "${FEROSProcImage:-N}" == "Y" ]; then
    ferosProcImage --pidir ${FEROS_DRS}/procImage/VA `pwd`/pack${targz}
  fi

fi

exit
