#!/usr/bin/perl

################################################################
sub usage {
  die 
"USAGE:

add_eff_superscript out=outkey bin=n @par.file

    outkey  - output keyword
    bin     - binning factor for output exposure map

    par.file should contain
     evtfile=...
     bg_file=...
     ccd_set=...
";
}

@gov = split (/\//,$0); pop @gov; $BINDIR = join ('/',@gov);

$fcopy = "$BINDIR/fitscopy";

require "$BINDIR/perlutil.pl";
&check_zhtools;

# Initialize internal variables ($UNDEF etc)
&ini_vars;

@PARS = &fixpars (@ARGV); # this is needed to escape arguments that
                          # contain parens etc

chop (($out,$bin,$bg,$ccdset) = `getpar out,bin,bg_file,ccd_set @PARS`);

foreach $var ( "out", "bin", "bg_file", "ccdset" ) {
  if ( $$var eq $UNDEF ) {
    &usage;
  }
}

chop (($bgnorm) = `getpar bgnorm @PARS`);
if ( $bgnorm eq $UNDEF ) {
  $bgnorm = 1;
}

@listevt = ();
# Make event list with the eff column
system ("$BINDIR/add_eff","o=!${out}_evt.fits",@ARGV) && die;
push @listevt,"${out}_evt.fits";

# Make background file with the eff column
system ("$BINDIR/add_eff","evtfile=$bg","o=!${out}_bg.fits",@ARGV) && die;
push @listevt,"${out}_bg.fits";

# see if readout file was set; if yes, process it also
chop (($rdt) = `getpar readout_bg_file @PARS`);
if ( $rdt ne $UNDEF ) {
  system ("$BINDIR/add_eff","evtfile=$rdt","o=!${out}_rdt.fits",@ARGV) && die;
  push @listevt,"${out}_rdt.fits";
} else {
  # remove rdt file, just in case
  unlink ("${out}_rdt.fits");
}

# fix exposure keywords
foreach $e (@listevt) {
  system ("fparkey `gtiexp $e+2` $e+1 EXPOSURE") && die;
}

# renormalize the backgroubd exposure
if ( $bgnorm != 1 ) {
  $bgwork = "${out}_bg.fits";
  system ("$fcopy","$bgwork"."[GTI][col start = start / $bgnorm; stop = stop / $bgnorm; *]","\!$bgwork.gov");
  system ("fparkey `gtiexp $bgwork.gov+2` $bgwork.gov+1 EXPOSURE") && die;
  rename ("$bgwork.gov",$bgwork);
}


# Make exposure map with the given binning factor
# exposure map DOES NOT include any efficiency variations
# (they are put inside the eff column)
# Exposure map also does not include the actual integration time. 
# Take it from gti extensions of evt and bg files
system ("$BINDIR/aspecthist",@ARGV,"o=gov$$.asp") && die;
system ("$BINDIR/chipmap2","o=gov$$.chip","bin=$bin","chips=$ccdset",@ARGV,
	"-nomirror","-noqe") && die;
system ("$BINDIR/convaspect","chipmap=gov$$.chip","asphist=gov$$.asp",
	"o=!${out}_exp.fits","-noexp") && die;
unlink ("gov$$.chip","gov$$.asp");

# create responses
system ("$BINDIR/dumpspec","o=gov$$.pha",@ARGV) && die;
system ("$BINDIR/calcarf","phafile=gov$$.pha","o=${out}.arf",@ARGV,
	"novignettin=yes","-noqe") && die;

($ccd0) = split (',',$ccdset);
system ("$BINDIR/calcrmf2","phafile=gov$$.pha","o=${out}.rmf",
	"rmfpos=$ccd0,512,512",
	@ARGV) && die;

unlink ("gov$$.pha");


################################################################
sub ini_vars {
  $UNDEF = "undefined";
}
