#!/bin/sh

# 
#  Copyright (C) 1998-2001,2003-2005,2007-2009,2011-2012,2015,2022  Smithsonian Astrophysical Observatory
#
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program; if not, write to the Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#


# wavdetect
# This script runs the Chicago wtransform and wrecon tools in series
# It reads the parameters for each tool and then calls the tools.
# In this script, parameters that are specific to wtransform are
# prefixed with "wt_".  Parameters specific to wrecon are prefixed
# "wr_".  Common parameters are prefixed "wd_".

clean_tmp_pars()
{
  tmpdir="$1"
  /bin/rm ${tmpdir}/*.par
  /bin/rmdir ${tmpdir}
}

_add_history()   
{
  tmpfile="$1"
  if [ -f ${tmpfile} ] ; then
     PFILES=${tmpdir}:${PFILES} dmhistory $tmpfile $MYNAME action=put 
  fi
}

MYNAME=wavdetect

#
# Load parameters. Escape: spaces, (), and ['s
#
tmpdir=$ASCDS_WORK_PATH/$$_param
mkdir -p $tmpdir
cp `paccess ${MYNAME}` $tmpdir
tmppar=$tmpdir/${MYNAME}.par
chmod +w $tmppar
for pp in `pdump ${MYNAME} | cut -d= -f1 | grep -v '^# EOF'` 
do
  pval=`echo $pp | pquery ${MYNAME} - "$@" | sed 's/[ ()\[]/\\\&/g'`
  eval ${pp}="${pval}"
  pset $tmppar ${pp}="${pval}"
done

# get the verbose parameter

wd_verbose=$verbose

if test $wd_verbose -ge 2; then
  echo "starting wavdetect"
fi


# get the automatic parameters
wd_infile=$infile
wr_sourcefile=$outfile
wr_scellfile=$scellfile
wr_imagefile=$imagefile
wr_defnbkgfile=$defnbkgfile



# get the parameters common to wtransform and wrecon

wd_log=$log
wd_interdir=$interdir
wd_expfile=$expfile
wd_bkginput=$bkginput
wd_bkgerrinput=$bkgerrinput
wd_scales=$scales
wd_clobber=$clobber
wd_exptime=$exptime
wd_bkgtime=$bkgtime


# get the wtransform parameters

wt_outputinfix=$outputinfix
wt_expthresh=$expthresh
wt_maxiter=$maxiter
wt_iterstop=$iterstop
wt_sigthresh=$sigthresh
wt_bkgsigthresh=$bkgsigthresh
wt_falsesrc=$falsesrc
wt_sigcalfile=$sigcalfile

if test -z $wd_interdir; then
  wd_interdir="."
fi

if test $wd_interdir != "/" ; then
  len1=`expr $wd_interdir : ".*"`
  len2=`expr $wd_interdir : ".*/"`
  if test $len1 -ne $len2; then
    wd_interdir="${wd_interdir}/"
  fi
fi
    
# set exposure correction
wt_expcor="fast"

# set these file names
my_pid="`hostname`$$"
wt_srclist="${wd_interdir}wd${my_pid}_srclist_stk"
wt_correl="${wd_interdir}wd${my_pid}_correl_stk"
wt_nbkg="${wd_interdir}wd${my_pid}_nbkg_stk"


# wavdetect produces no plain background or correlation threshold outputs
wt_thresh=none
wt_bkg=none

# wavdetect produces nbkg error outputs, but no others
wt_nbkgerr=y
wt_correlerr=n
wt_bkgerr=n

# get wrecon parameters

wr_regfile=$regfile
wr_ellsigma=$ellsigma
wr_psffile=$psffile


# set these file names
wr_fluxfile="${wd_interdir}wd${wd_outputinfix}_flux_stk"

# construct the fluxscales list for wrecon
i=0
wr_fluxscales=""
for scale in `echo $wd_scales | tr ",:;" " "` # make space separated
do
  i=`expr $i + 1`
  wr_fluxscales="${wr_fluxscales} $i"
done
scale_count=`expr $i`

# check that the number of wavelet scales is =<127
if test $scale_count -gt 127; then
  echo "ERROR: Too many wavelet scales"
  clean_tmp_pars $tmpdir
  exit 1
fi

# check wrecon parameters for errors and exit out before running wtransform
lower_case=`echo "$wd_bkginput" | tr '[A-Z]' '[a-z]'`
if test -z "$lower_case" -o "$lower_case" = "none"
then
   lcase2=`echo "$wr_defnbkgfile" | tr '[A-Z]' '[a-z]'`
   if test -z "$lcase2" -o "$lcase2" = "none"
   then
      echo "ERROR: Input background file or a default normalized background filename must be specified as input for wrecon."
      clean_tmp_pars $tmpdir
      exit 1 
   fi
fi
if test -z "$wr_scellfile"
then
   echo "ERROR: scellfile value must be specified for wavdetect to run wrecon."
   clean_tmp_pars $tmpdir
   exit 1
fi 
if test -z "$wr_imagefile"
then
   echo "ERROR: imagefile value must be specified for wavdetect to run wrecon."
   clean_tmp_pars $tmpdir
   exit 1
fi 



# run wtransform

if test $wd_verbose -ge 2; then
  echo "number of scales: $scale_count"
  echo "running wtransform"
  echo "wtransform log=$wd_log verbose=$wd_verbose \
	infile="$wd_infile" srclist=$wt_srclist correl=$wt_correl\
	nbkg=$wt_nbkg bkg=$wt_bkg outputinfix=$wt_outputinfix\
	thresh=$wt_thresh exptime=$wd_exptime expfile="$wd_expfile" \
	expcor=$wt_expcor expthresh=$wt_expthresh bkgtime=$wd_bkgtime \
	bkginput=$wd_bkginput bkgerrinput=$wd_bkgerrinput \
	xscales="$wd_scales" yscales="$wd_scales" \
	correlerr=$wt_correlerr nbkgerr=$wt_nbkgerr \
	maxiter=$wt_maxiter iterstop=$wt_iterstop \
	sigthresh=$wt_sigthresh  bkgsigthresh=$wt_bkgsigthresh \
        falsesrc=$wt_falsesrc sigcalfile=$wt_sigcalfile \
	stall=no clobber=$wd_clobber"
  echo ""
fi


if  wtransform log=$wd_log verbose=$wd_verbose \
	infile="$wd_infile" srclist=$wt_srclist correl=$wt_correl\
	nbkg=$wt_nbkg bkg=$wt_bkg outputinfix=$wt_outputinfix\
	thresh=$wt_thresh exptime=$wd_exptime expfile="$wd_expfile" \
	expcor=$wt_expcor expthresh=$wt_expthresh bkgtime=$wd_bkgtime \
	bkginput=$wd_bkginput bkgerrinput=$wd_bkgerrinput \
	xscales="$wd_scales" yscales="$wd_scales" \
	correlerr=$wt_correlerr nbkgerr=$wt_nbkgerr \
	maxiter=$wt_maxiter iterstop=$wt_iterstop \
	sigthresh=$wt_sigthresh  bkgsigthresh=$wt_bkgsigthresh \
        falsesrc=$wt_falsesrc sigcalfile=$wt_sigcalfile \
	stall=no clobber=$wd_clobber
then
 :
else
  echo "wtransform failed"
  clean_tmp_pars $tmpdir  
  exit 1
fi

# run wrecon

if test $wd_verbose -ge 2; then
echo "running wrecon"
echo "wrecon log=$wd_log verbose=$wd_verbose \
        regfile=$wr_regfile  ellsigma=$wr_ellsigma  \
	infile="$wd_infile" expfile="$wd_expfile" \
	correl=$wt_correl srclist=$wt_srclist nbkg=$wt_nbkg \
	xscales="$wd_scales" yscales="$wd_scales" expthresh=$wt_expthresh \
	bkgtime=$wd_bkgtime exptime=$wd_exptime \
	sourcefile=$wr_sourcefile \
	scellfile=$wr_scellfile imagefile=$wr_imagefile \
	defnbkgfile=$wr_defnbkgfile fluxfile=$wr_fluxfile \
	bkginput=$wd_bkginput bkgerrinput=$wd_bkgerrinput \
	psffile=$wr_psffile fluxscales="$wr_fluxscales" \
	outputinfix=$wt_outputinfix stall=no  \
	clobber=$wd_clobber "
echo ""
fi

wrecon log=$wd_log verbose=$wd_verbose \
        regfile=$wr_regfile  ellsigma=$wr_ellsigma  \
	infile="$wd_infile" expfile="$wd_expfile" \
	correl=$wt_correl srclist=$wt_srclist nbkg=$wt_nbkg \
	xscales="$wd_scales" yscales="$wd_scales" expthresh=$wt_expthresh \
	bkgtime=$wd_bkgtime exptime=$wd_exptime \
	sourcefile=$wr_sourcefile \
	scellfile=$wr_scellfile imagefile=$wr_imagefile \
	defnbkgfile=$wr_defnbkgfile fluxfile=$wr_fluxfile \
	bkginput=$wd_bkginput bkgerrinput=$wd_bkgerrinput \
	psffile=$wr_psffile fluxscales="$wr_fluxscales" \
	outputinfix=$wt_outputinfix stall=no  \
	clobber=$wd_clobber 
if test x$? != x0
then
  echo "wrecon failed"
  clean_tmp_pars $tmpdir
  exit 1
fi

_add_history $wr_sourcefile 
_add_history $wr_scellfile
_add_history $wr_imagefile
_add_history $wr_defnbkgfile

clean_tmp_pars $tmpdir

# delete intermediate results
# srclist
exec <$wt_srclist
while read line
do
 rm -rf "${wd_interdir}${line}"
done
rm $wt_srclist

# correl
exec <$wt_correl
while read line
do
 rm -rf "${wd_interdir}${line}"
done
rm $wt_correl

# nbkg
if test -z "$lower_case" -o "$lower_case" = "none"
then
  exec <$wt_nbkg
  while read line
  do
   rm -rf "${wd_interdir}${line}"
  done 
  rm $wt_nbkg
fi

# fluxfile
exec <$wr_fluxfile
while read line
do
 rm -rf "${wd_interdir}${line}"
done 
rm $wr_fluxfile


if test $wd_verbose -ge 2; then
  echo "wavdetect done!"
fi
