#!/usr/bin/perl -w

#
# Parses arguments and calls fitscopy
#
# Usage:  
#   filtevt infile ofile cutedge=pix reg=include.reg exclreg=exclude.reg
#                       binfilt=fitsio_operation regwcs=wcs_file_for_regs
#
#
# It is the user's responsibility to position the infile at the correct 
# extension with the fitsio file name syntax
#

use File::Copy;

print join(' ',@ARGV),"\n";

# Setup external programs
@gov = split (/\//,$0); pop @gov; $BINDIR = join ('/',@gov);
if ($ENV{'FITSFILTER'}) {
  $fcopy = $ENV{'FITSFILTER'}
} else {
  $fcopy    = "$BINDIR/fitsfilter";
}
$getpar = "$BINDIR/getpar";
$evtmaskfilter = "$BINDIR/evtmaskfilter";
$iffits    = "iffits";               # from ZHTOOLS

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

# Initialize internal variables
&ini_vars;
@CLEANLIST = ();

# Setup default filters
$rowfilter = "";

# Read command line arguments
@PARS = &fixpars (@ARGV); # this is needed to escape arguments that
                          # contain parens etc
chop (
      ($infile,$ofile,$cutedge,$XCOL,$YCOL,$XCHIPCOL,$YCHIPCOL,$reg,$exclreg,$binfilt,$regwcs,$eventsname,$rowfilt,$badpixfilter,$gtifile,$filtgti,$filtbadpix) = 
`$getpar evtfile,o,cutedge,xcol,ycol,xchipcol,ychipcol,reg,exclreg,binfilt,regwcs,eventsname,rowfilt,badpixfilter,gtifile,filtgti,filtbadpix @PARS`
     );

# Set default parameter values
if ( $infile   eq $UNDEF ) { die "-evtfile unset\n"; }
if ( $ofile    eq $UNDEF ) { die "-o unset\n"; }
if ( $cutedge  eq $UNDEF ) { $cutedge  = 0; }
if ( $badpixfilter eq $UNDEF ) { $badpixfilter  = ""; }
if ( $XCOL     eq $UNDEF ) { $XCOL     = "X"; }
if ( $YCOL     eq $UNDEF ) { $YCOL     = "Y"; }
if ( $XCHIPCOL eq $UNDEF ) { $XCHIPCOL = "CHIPX"; }
if ( $YCHIPCOL eq $UNDEF ) { $YCHIPCOL = "CHIPY"; }
if ( $binfilt  eq $UNDEF ) { $binfilt  = ""; } # additional FITSIO operation
if ( $rowfilt  eq $UNDEF ) { $rowfilt  = ""; } # preliminary FITSIO operation
if ( $eventsname eq $UNDEF){ $eventsname = "EVENTS"; }
if ( $gtifile  eq $UNDEF)  { $gtifile  = $infile; } # GTI extension from events
if ( $filtgti  eq "no" || $filtgti eq $UNDEF) { $filtgti  = ""; } else { $filtgti = "yes"; }
if ( $filtbadpix eq "no" || $filtbadpix eq $UNDEF )  { $filtbadpix = ""; }


# Strip leading  and trailing [] from the user's rowfilt
if ( $rowfilt ) {
  $rowfilt =~ s/^\s*\[//;
  $rowfilt =~ s/\]\s*$//;
}

# Setup CCD filters
if ( $cutedge > 0 ) {
  my ($xmin, $xmax, $ymin, $ymax);
  $xmin = $cutedge;  $xmax = 1024-$cutedge+1;
  $ymin = $cutedge;  $ymax = 1024-$cutedge+1;
  $edgefilter = 
    "($XCHIPCOL > $xmin && $XCHIPCOL < $xmax && $YCHIPCOL > $ymin && $YCHIPCOL < $ymax)";
}
else {
  $edgefilter = "";
}

# Region filter
if ( $reg eq $UNDEF ) {
  $regfilter = "";
}
else {
  $regfile = "/tmp/includefilt$$";
 # $regfile_inc = $regfile."_inc"; $regfile_excl = $regfile."_excl";
  push (@CLEANLIST,$regfile); #,$regfile_inc,$regfile_excl);
  if ($regwcs ne $UNDEF) {
    if ( &translate_region_wcs_1 ($reg, $regfile, $regwcs) ) {
#				$infile,"toxcol=$XCOL","toycol=$YCOL") ) {
      die "translate_region_wcs_1 failed\n";   }
  }
  else { # it may be a component of the ds9 region file
    if ( -f $reg ) {
      copy($reg,$regfile);
    } else {
      open (REGFILE,"> $regfile") || 
	die "Cannot open $regfile for writing: $!\n";
      print REGFILE "$reg\n";
      close (REGFILE);
    }
  }
    
#  if ( &splitregfilter ($regfile,$regfile_inc,$regfile_excl) ) {
#    die "splitregfilter failed\n";  }
#  if ( &reversefilter ($regfile_inc,$regfile_inc) ) { 
#    die "reversefilter failed: $!\n"; }
#  $regfilter=&combine_inc_excl_filt ($regfile_inc,$regfile_excl);
  $regfilter="regfilter( \"$regfile\" )";
}


# Exclude region filter
if ( ! (  $exclreg eq $UNDEF )  ) {
 # first, determine whether the exclreg filter is fits
    $test = `$iffits $exclreg`; chop ($test);
    if ($test) {
        # exclreg filter is fits. filter the 
        # print join(' ',$evtmaskfilter,
        #             "-evtfile",$infile,
        #             "-o",$infile.".gov.$$",
        #             "-maskfilter",$exclreg,"\n");
        $status = &runprog($evtmaskfilter,
                           "-evtfile",$infile,
                           "-o","!".$infile.".gov.$$",
                           "-maskfilter",$exclreg);
        if ($status != 0) {
            exit ($status);
        }
        $infile = $infile.".gov.$$";
        push (@CLEANLIST,$infile);
        $exclreg = $UNDEF;
        $exclregfilter = "";

    } else { # follow the old procedure

        $exclregfile = "/tmp/excludefilt$$"; push @CLEANLIST,$exclregfile;
        if ($regwcs ne $UNDEF) {
            if ( &translate_region_wcs_1 ($exclreg,$exclregfile,$regwcs) ) {
                #$infile,"toxcol=$XCOL","toycol=$YCOL") ) {
                die "translate_region_wcs_1 failed\n";   }
        } else {
            copy ($exclreg, $exclregfile);
        }
#  if ( &reversefilter($exclregfile,$exclregfile) ) { 
#    die "reversefilter failed\n"; }
        $exclregfilter = "! regfilter( \"$exclregfile\" )";
    }
}

# check that the user provided the extension name
unless ( $infile =~ /\[.+\]/ ) {
  if ($eventsname) {
    $infile = $infile."\[$eventsname\]";
  }
  else {
    die "\n$infile\n --- events extension is not provided either as a part of the file name\nnor as the eventsname= parameter\n";
  }
}

# GTI filter
if ( $gtifile && $filtgti ) {
  $gtifilter = "gtifilter( \"".$gtifile."\" )";
}
else {
  $gtifilter = "";
}

# Undefine bad pixel filter if filtbadpix="" ("no" originally)
if ( ! $filtbadpix ) { $badpixfilter = "";} 

# Form row filter
$rowfilterfile = "/tmp/rowfilter$$"; push (@CLEANLIST,$rowfilterfile);
if ( &form_row_filter($rowfilterfile, $badpixfilter,
		      $rowfilt,$edgefilter,$regfilter, $exclregfilter, 
		      $gtifilter) )
  {
    die "form_row_filter failed\n";
  }
if ( $badpixfilter || $rowfilt || $edgefilter || $regfilter || $exclregfilter )
  {
    $rowfilter = "\[\@$rowfilterfile\]";
  }
else
  {
    $rowfilter = "";
  }


# Call fitscopy

print join (' ',$fcopy,
		  $infile.$rowfilter.$binfilt,
		  $ofile,"\n");


$status = &runprog (
		  $fcopy,
		  $infile.$rowfilter.$binfilt,
		  $ofile
		 );


if ( @CLEANLIST ) { 
  unlink (@CLEANLIST);
}

exit $status;
    

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





