#!/bin/sh

if [ x"$3" = x ]; then
  echo "usage: $0 ifile ofile regions"
  echo "The regions specification should be in physical coords and can be:"
  echo "  a region string e.g. 'circle 512 512 .1;box(606,606,3,4)'"
  echo "  a region file   e.g. 'foo.reg' (nb: s9 file OK, but no @ prefix)"
  exit 1
fi

# input parameters
IFILE=$1
OFILE=$2
REGIONS=$3

# temporary fits file
TFITS=./tfunstack.fits
rm -f ${TFITS}

# temporary funcalc command file
TFC=./tfunstack.fc
rm -f ${TFC}

# convert file to region string, if necessary
if [ -r "${REGIONS}" ]; then
  REGIONS=`cat ${REGIONS} | awk '{print $0";"}'`
fi

# generate the funcalc command file from region string
# we do this so that awk can parse the region and add in the region centers
echo "${REGIONS}"                    | \
sed '/^physical/d;s/[\(\),]/ /g'     | \
sed '/^#/d;/^global/d'		     | \
awk 'BEGIN{RS=";"};
BEGIN{
  print "local"
  print "int nreg;"
  print "int xdim, ydim;"
  print "double xmin, xmax, umin, ymax;"
  print "double xref, yref;"
  print "double xreg[1024], yreg[1024];"
  print "end"
  print "before"
  print "FunInfoGet(fun, FUN_SECT_DIM1, &xdim, FUN_SECT_DIM2, &ydim, 0);"
  print "FunInfoGet(fun, FUN_MIN1, &xmin, FUN_MAX1, &xmax, 0);"
  print "FunInfoGet(fun, FUN_MIN2, &ymin, FUN_MAX2, &ymax, 0);"
  print "xref = (xmin + xmax)/2.0;"
  print "yref = (ymin + ymax)/2.0;"
  i=1
};
{
  if( ($1!="polygon") && ($1!="pie") ){
    if( ($2 != "") && ($3 != "") ){
      print "xreg["i"]="$2";"
      print "yreg["i"]="$3";"
      i = i+1
    }
    if( i >= 1024 ){
      printf "ERROR: too many regions (1024 max)" > "dev/stderr"
      exit
    }
  }
}
END{
  print "nreg="i-1";"
  print "end"
  print "if( cur->region > nreg ){"
  print "  gerror(stderr, \"%d exceeds input reg %d\\n\", cur-> region, nreg);"
  print "  exit(1);"
  print "}"  
  print "cur->x = cur->x - xreg[cur->region] + xref;"
  print "cur->y = cur->y - yreg[cur->region] + yref;"
}' > ${TFC}

# funtools seems to rearrange the order of columns when $REGION is specified
# so here we get the column names explicitly to preserve order
COLS=`funhead ${IFILE} | egrep 'TTYPE[0-9]' | awk '{print $3}' | sed "s/'//g"`

# first filter the input file and preserve the region ids
funtable ${IFILE}"[${REGIONS}]" ${TFITS} "${COLS} "'$REGION' 

# now run the funcalc script to stack the events
funcalc -f ${TFC} ${TFITS} ${OFILE}

# clean up
rm -f ${TFC} ${TFITS}
