#! /bin/sh
# 
#  Copyright (C) 2010-2011,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.
#



MYNAME=mean_energy_map

#
# Load parameters. Escape: spaces, (), and ['s
#


pars=`pdump ${MYNAME} | cut -d= -f1 | grep -v '^# EOF'` 
if test $? -ne 0
then
  echo "# ${MYNAME} () : ERROR: cannot open parameter file" 1>&2 
  exit 1
fi


for pp in $pars
do
  eval ${pp}=`echo $pp | pquery ${MYNAME} - "$@" | sed 's/[ ()\[]/\\\&/g'`
done


if test $verbose -gt 0
then
  printf "${MYNAME}: \n"
  for pp in $pars
  do
      printf "%10s = %s\n" $pp `eval echo $\`echo $pp\` `
  done

fi


tmp=$tmpdir/$$_wghtevt


#
# Add flux column to event file; this gives use the corrections 
# on a per event basis for the mirror and detector effects.  The
# energy is divided out from the flux to give us the weight for
# each event
# 
#
eff2evt "${infile}" - pbkfile="${pbkfile}" | \
  dmtcalc "-[cols flux,energy,sky]" $tmp exp="weight=flux/energy" clob=$clobber
if test $? -ne 0
then
  echo "# $MYNAME () : ERROR: problem running eff2evt or dmtcalc" 1>&2
  exit 1
fi


#
# Make 2 images: one is sum(flux) (ie weight*flux) divided by
# image that is sum(weight)
#
dmimgcalc "$tmp[bin sky=${binsize};flux]" "$tmp[bin sky=${binsize};weight]" \
   "$outfile" div clob=${clobber}
if test $? -ne 0
then
  echo "# $MYNAME () : ERROR: problem running dmimgcalc" 1>&2
  /bin/rm -f $tmp
  exit 1
fi

#
# Update units
#
dmhedit "$outfile" file= op=add key=BUNIT value="eV"
if test $? -ne 0
then
  echo "# $MYNAME () : ERROR: problem running dmhedit" 1>&2
  /bin/rm -f $tmp
  exit 1
fi

#
# History
#
dmhistory  "$outfile" mean_energy_map action=put
#dmhistory "$tmp"     mean_energy_map action=put


/bin/rm -f $tmp

exit 0

