#!/usr/bin/perl

$eventsfile = "$ARGV[0]";
$outfile = "$ARGV[1]";

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

if ($ENV{'FITSFILTER'}) {
  $fcopy = $ENV{'FITSFILTER'}
} else {
  $fcopy    = "$BINDIR/fitsfilter";
}

$modhead = "modifyheader";           # from ZHTOOLS
$getpar = "$BINDIR/getpar";
$dumpspec = "$BINDIR/dumpspec";
$fdelhdu = "fdelhdu";
$fappend = "fappend";

# Read common PERL subs
require "$BINDIR/perlutil.pl";

# Check external packages
&check_ftools; &check_zhtools;

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

# Read programs arguments. C program $BINDIR/getpar extracts the requested
# arguments from the command line where they are provided in either of the 
# formats
# a=1 -y 4 @par.file
# if a parameter is absent, it will be returned as "undefined"
@PARS = &fixpars (@ARGV); # this is needed to escape arguments that
                          # contain parens etc
chop (
($eventsfile,$outfile,
 $specbin,$phamax,$ecol,$bindetmap,$XCOL,$YCOL,$XDETCOL,$YDETCOL,
 $GTINAME,$EVENTSNAME,$TIMENAME,$gtifile,$chip,$fixphaspec,$maxspecchans,$extrregfile,$edetmapmin,$edetmapmax,$keepempty,$wmapinchip,$specweight) =
`$getpar evtfile,o,specbin,phamax,ecol,bindetmap,xcol,ycol,xdetcol,ydetcol,gtiname,eventsname,timename,gtifile,chip,fixphaspec,maxspecchans,extrregfile,edetmapmin,edetmapmax,keepempty,wmap_in_chip,specweight @PARS`
);

chop (($fixexposure,$fixgti,$extractor) = 
      `$getpar fixexposure,fixphagti,extractor @PARS`);

# Read required values
if ( $eventsfile eq $UNDEF ) {
  print "Events file [evtfile=] ? "; $eventsfile = <STDIN>; chop $eventsfile;
}
if ( $outfile eq $UNDEF ) {
  print "Output spectrum [o=] ? "; $outfile = <STDIN>; chop $outfile;
}

# Fill in default values;
if ( $extractor eq $UNDEF ){  $extractor  = "dumpspec";  }
if ( $specbin eq $UNDEF )  {  $specbin    = 1;           }
if ( $ecol  eq $UNDEF )    {  $ecol       = "PI";        }
if ( $bindetmap eq $UNDEF ){  $bindetmap  = 8;           }
if ( $bindetmap eq $UNDEF ){  $bindetmap  = 8;           }
if ( $edetmapmin eq $UNDEF ){ $edetmapmin = 500;         }
if ( $edetmapmax eq $UNDEF ){ $edetmapmax = 2000;        }
if ( $XCOL eq $UNDEF )     {  $XCOL       = "X";         }
if ( $YCOL eq $UNDEF )     {  $YCOL       = "Y";         }
if ( $XDETCOL eq $UNDEF )  {  $XDETCOL    = "DETX";      }
if ( $YDETCOL eq $UNDEF )  {  $YDETCOL    = "DETY";      }
if ( $GTINAME eq $UNDEF )  {  $GTINAME    = "GTI";       }
if ($EVENTSNAME eq $UNDEF ){  $EVENTSNAME = "EVENTS";    }
if ( $TIMENAME eq $UNDEF ) {  $TIMENAME   = "TIME";      }
if ( $chip eq $UNDEF )     {  $chip       = "all";       }
if ( $extrregfile eq $UNDEF){ $extrregfile= "none";      }
if ( $gtifile  eq $UNDEF ) {  $gtifile    = $eventsfile; } # Use GTI in the evt
                                                           # file by default
if ( $fixphaspec eq $UNDEF ){ $fixphaspec = "no";        }
if ( $fixexposure eq $UNDEF ){ $fixexposure = "yes";     }
if ( $fixgti      eq $UNDEF ){ $fixgti      = "yes";     }
if ( $phamax  eq $UNDEF )  {
  $phamaxpar = "";
}
else {
  $phamaxpar = "phamax=$phamax";
}  
if ( $keepempty eq "yes" ) { $keepempty = 1; } else { $keepempty = 0; }


# Initialize chip names
&ini_chip_names;
#  and find chip number
if ( ! ( $chip eq "all" ) ) {
  if ( ! defined $CHIPNUM{$chip} ) {
    die "ERROR:  Unknown chip \"$chip\"\n";
  }
  $chipnum = $CHIPNUM{$chip};
  if ( ! ( $chipnum =~ /:/ || $chipnum =~ /,/) ) {
    # $chipfilter = $chipnum.":".$chipnum;
    $chipfilter = $chipnum;
    $chipfitsiofilter = "[ccd_id == $chipnum]";
    $chipfilter = "[ccd_id=$chipfilter]";
  }
  else {
    if ( $chip eq 'fi' ) {
      $chipfitsiofilter = "[ccd_id != 5 && ccd_id != 7]";
      $chipfilter = "[ccd_id!=5&&ccd_id!=7]";
    }
    elsif ( $chip eq 'sfi' ) {
      $chipfitsiofilter = "[ccd_id < 4 || ccd_id == 6]";
      $chipfilter = "[ccd_id<4||ccd_id==6]";
    }
    elsif ( $chip eq 'bi' ) {
      $chipfitsiofilter = "[ccd_id==5||ccd_id==7]";
      $chipfilter = "[ccd_id==5||ccd_id==7]";
    }
    else {
      $chipfilter = $chipnum;
      ($chipmin,$chipmax) = split (/:/,$chipnum);
      $chipfitsiofilter = "[ccd_id >= $chipmin && ccd_id <= $chipmax]";
      $chipfilter = "[ccd_id=$chipfilter]";
    }
  }
}
else {   # no chip selection
  $chipfilter = "";
  $chipfitsiofilter = "";
}


if ( $extractor eq "dmextract" ) {
  # Extract spectrum
  print "\n Runing dmextract...\n";
  $binfilter = "[bin $ecol=1::$specbin]";
  if ($wmapinchip =~ /^y/i) {
    $bindetcol = 'chip';
  } else {
    $bindetcol = 'det';
  }
  if ( system ("dmextract","$eventsfile".$chipfilter.$binfilter,"opt=pha1",
	       "wmap=[energy=$edetmapmin:$edetmapmax][bin $bindetcol=$bindetmap]",
	       "outfile=$outfile",
	       "clobber+")
   ) {
    die "ERROR: dmextract failed\n";
  }

  # c) Find the non-zero section in the detimg and extract it
  print STDERR "..... find non-zero section:";
  chop (($xmin,$xmax,$ymin,$ymax,$immax) = `$BINDIR/detimexam $outfile`);
  if ( (! ($immax > 0)) && $keepempty ) {
    $xmin = 1; $xmax = 1; $ymin = 1; $ymax = 1;
    $immax = 1;
  }
  if ( $immax > 0 ) {
    print STDERR " ... [$xmin:$xmax,$ymin:$ymax] ...";
    print STDERR " and extract it\n";
    system ("dmcopy","$outfile"."[wmap][$xmin:$xmax,$ymin:$ymax]","$outfile"."_$$");
    system ("fdelhdu","$outfile"."_$$"."[gti]","NO","YES");
    system ("fappend","$outfile"."[spectrum]","$outfile"."_$$");
    system ("fappend","$outfile"."[gti]","$outfile"."_$$");
    rename ("$outfile"."_$$","$outfile");
  }
  else {
    print STDERR "Warning: Zero photons in $outfile. Remove $outfile and exit\n";
    unlink $outfile;
    exit 0;
  }
  if ( $fixexposure eq "yes" ) {
    $exposure = `gtiexp $gtifile\[$GTINAME\]`;
    chomp $exposure;
    system ("fparkey",$exposure,$outfile."[spectrum]","EXPOSURE");
  }
  if ( $fixgti eq "yes" ) {
    system ($fdelhdu, $outfile."[GTI]","no","yes");
    system ($fappend, $gtifile."[$GTINAME]",$outfile);
  }
  # Restore POISSON statistics
  system ($fcopy,$outfile."[spectrum][col -STAT_ERR; -COUNT_RATE; POISSERR=T]",
	  "!$outfile.$$");
  rename ("$outfile.$$",$outfile);
}
else { # default extractor
  if ( $fixphaspec eq "yes" ) {
    $detchans = $maxspecchans*$specbin;
    $spec_bin = "$ecol:1:$detchans:$specbin";
  } else {
    $spec_bin = "$ecol:1::$specbin";
  }
  if ($wmapinchip =~ /^y/i) {
    @wmapargs = ("xdetcol=CHIPX", "ydetcol=CHIPY");
  }
  else {
    @wmapargs=();
  }
  if ( $keepempty ) { $keep_empty="yes"; } else { $keep_empty="no"; }

  system ($dumpspec,"evtfile=$eventsfile"."[$EVENTSNAME]".$chipfitsiofilter,
	  "o=$outfile",
	  "specbin=$spec_bin",@wmapargs,"bindetmap=$bindetmap",
	  "edetmapmin=$edetmapmin","edetmapmax=$edetmapmax","energycol=energy",
	  "gtifile=$gtifile","keepempty=$keep_empty","specweight=$specweight");
  if ( ! -e $outfile ) { exit (0); }
}


if ( $fixphaspec eq "yes" ) {
# Fix Spectrum:
#    1) extractor numbers channels from 0; we need from 1
#    2) a) Chandra telemetry seems to have PHA's TLMAX = 36855 while
#          matrices have 2048 channels
#
# If fixphaspec == yes, the user is expected to supply the maxspecchans
# parameter
#
  $detchans = $maxspecchans;
#   system ($fcopy,
# 	  "$outfile"."[SPECTRUM][col DETCHANS = $detchans; TLMIN1=1; TLMAX1 = $maxspecchans; CHANNEL = CHANNEL + 1 ][CHANNEL <= $maxspecchans && CHANNEL > 0]",
# 	  "$outfile"."_$$");
  system ($fcopy,
	  "$outfile"."[SPECTRUM][col DETCHANS = $detchans; TLMIN1=1; TLMAX1 = $maxspecchans][CHANNEL <= $maxspecchans && CHANNEL > 0]",
	  "$outfile"."_$$");
  rename ("$outfile"."_$$","$outfile");
}





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