#! /bin/sh
# This is the LHEA perl script: /cvmfs/extras-fp7.egi.eu/extras/heasoft/hitomi/x86_64-unknown-linux-gnu-libc2.19-0/bin/sxiplot.pl
# The purpose of this special block is to make this script work with
# the user's local perl, regardless of where that perl is installed.
# The variable LHEAPERL is set by the initialization script to
# point to the local perl installation.
#-------------------------------------------------------------------------------
eval '
if [ "x$LHEAPERL" = x ]; then
  echo "Please run standard LHEA initialization before attempting to run /cvmfs/extras-fp7.egi.eu/extras/heasoft/hitomi/x86_64-unknown-linux-gnu-libc2.19-0/bin/sxiplot.pl."
  exit 3
elif [ "$LHEAPERL" = noperl ]; then
  echo "During LHEA initialization, no acceptable version of Perl was found."
  echo "Cannot execute script /cvmfs/extras-fp7.egi.eu/extras/heasoft/hitomi/x86_64-unknown-linux-gnu-libc2.19-0/bin/sxiplot.pl."
  exit 3
elif [ `$LHEAPERL -v < /dev/null 2> /dev/null | grep -ic "perl"` -eq 0 ]; then
  echo "LHEAPERL variable does not point to a usable perl."
  exit 3
else
  # Force Perl into 32-bit mode (to match the binaries) if necessary:
  if [ "x$HD_BUILD_ARCH_32_BIT" = xyes ]; then
    if [ `$LHEAPERL -V 2> /dev/null | grep -ic "USE_64_BIT"` -ne 0 ]; then
      VERSIONER_PERL_PREFER_32_BIT=yes
      export VERSIONER_PERL_PREFER_32_BIT
    fi
  fi
  exec $LHEAPERL -x $0 ${1+"$@"}
fi
'
if(0);
# Do not delete anything above this comment from an installed LHEA script!
#-------------------------------------------------------------------------------
#!/usr/bin/perl
#
# File name: sxiplot.pl
# Author: A. J. Sargent NASA GSFC
# $Date: 2016/05/23 19:42:20 $
# Version: 0
#
# Plot the lightcurves of the normal SXI events, minus day-earth SXI events
# and the SAA for the SXI
#
# Tool Dependencies:
#   extractor
#   lcurve
#   fplot
# 
# Library Dependencies:
#   gen/lib/perl/ahlog
#   gen/lib/perl/ahapp
#   gen/lib/perl/ahgen
#
# Modification History:
#

# Set up
use strict;
use warnings;

use ahlog ;
use ahapp ;
use ahgen qw (:ALL) ;
use File::Copy;

# turn on AUTOFLUSH
$| = 1;

#########################
# Variable Definitions 
#########################

my $infile1    =""; # Input unfiltered event file
my $infile2   =""; # Input cleaned event file
my $ehkfile    =""; # Input EHK file

my $saaplot    =""; # Output SXI SAA plot file

my $lcthresh   =""; # Lightcurve threshold
my $binlc      =""; # Bin size for lightcurve

my $offset     =""; # Offset X axis to 0?
my $maxpts     =""; # Maximum points per graph
my $pltcmd     =""; # Any legal PLT command

my $telescop   ="HITOMI";
my $ehkcol     =0;

my $sxiploterror = 0;  # sxiplot exit status

#########################
#  Main Code Block 
#########################

ahapp::startup () ;

ahapp::begin_processing () ;

$sxiploterror = get_parameters () ;
unless ( $sxiploterror == 0 ) {
  ah_info "HIGH", ahapp::write_parameters () ;
  ahlog::ah_err "get_parameters" ;
  ahapp::end_processing($sxiploterror);
}

$sxiploterror = initialize () ;
unless ( $sxiploterror == 0 ) {
  ah_info "HIGH", ahapp::write_parameters () ;
  ahlog::ah_err "initialize" ;
  ahapp::end_processing($sxiploterror);
}

$sxiploterror = do_work () ;
unless ( $sxiploterror == 0 ) {
  ahlog::ah_err "do_work" ;
  ahapp::end_processing($sxiploterror);
}

$sxiploterror = finalize () ;
unless ( $sxiploterror == 0 ) {
  ahlog::ah_err "finalize" ;
  ahapp::end_processing($sxiploterror);
}

# We're done.
ahapp::end_processing($sxiploterror);


#########################
# Subroutines
#########################

sub get_parameters {

  $infile1    = ahapp::query_parameter("infile1");
  $infile2   = ahapp::query_parameter("infile2");
  $ehkfile    = ahapp::query_parameter("ehkfile");

  $saaplot    = ahapp::query_parameter("saaplot");

  $lcthresh   = ahapp::query_parameter("lcthresh");
  $binlc      = ahapp::query_parameter("binlc");

  $offset     = ahapp::query_parameter("offset");
  $maxpts     = ahapp::query_parameter("maxpts");
  $pltcmd     = ahapp::query_parameter("pltcmd");

  return 0;

}

# ------------------------------------------------------------------------------

sub initialize {

  my $status = 0;

  # Input file checking

  # Check the normal sxi event file(s)
  if ($infile1 =~ /^@/) {
    if(isRequiredFileNotFound(substr($infile1,1))) { return 1; } 
  }
  # Load the input SXI normal event files into an array
  # and make sure each file exists
  my @in_sxi_files = readInputFileList($infile1);
  unless(@in_sxi_files) {
    ahgen::ah_err "No input SXI normal event files.";
    return 1;
  }
  if (isRequiredFileNotFound(@in_sxi_files)) { return 1; }

  # Check the minus day earth sxi event file(s)
  if ($infile2 =~ /^@/) {
    if(isRequiredFileNotFound(substr($infile2,1))) { return 1; } 
  }
  # Load the input SXI normal event files into an array
  # and make sure each file exists
  my @in_sxi_mdye_files = readInputFileList($infile2);
  unless(@in_sxi_mdye_files) {
    ahgen::ah_err "No input SXI minus day-earth event files.";
    return 1;
  }
  if (isRequiredFileNotFound(@in_sxi_mdye_files)) { return 1; }

  # Check if the EHK file exists
  if (isRequiredFileNotFound($ehkfile)) { return 1; }
  if (removeOutputFileIfClobbering($saaplot,$ahapp::clobber) ) { return 1; }

  # Check if the pltcmd is a text file
  # If so, make a copy of it to a temporary file
  # and add plot and quit commands.
  # 
  # These are failsafes in case the user did not put
  # either plot or quit into their pco file
#  if ( $pltcmd =~ /^@/ ) {
#    my $pltfile    ="sxiplot.pco";
#    ahapp::add_temp_file($pltfile);
#    if(isRequiredFileNotFound(substr($pltcmd,1))) { return 1; } 
#    File::Copy::copy(substr($pltcmd,1),$pltfile);
#    open PLT,">>$pltfile";
#    print PLT "plot\n"; # force pgplot to plot the file
#    print PLT "quit\n"; # force pgplot to quit
#    close PLT;
#    $pltcmd = "\@$pltfile";
#  }

  # Get the column number for the EHK column SAA_SXI
  $ehkcol = ahgen::get_column_num($ehkfile,"EHK","SAA_SXI");
  unless ( $ehkcol ) {
    ahgen::ah_err "Could not find column SAA_SXI in file $ehkfile\[EHK]";
    return 1;
  }

  # Check the EHK file for the TIMEDEL keyword
  my $ehk_timedel = ahgen::get_keyword($ehkfile,"EHK","TIMEDEL");
  if( ahgen::get_error_flag ) {
    ahlog::ah_err "TIMEDEL keyword not defined in $ehkfile"; 
    return ahgen::get_error_flag;
  }

  # Write all parameters to this script to the log file.
  ah_info "HIGH", ahapp::write_parameters () ;

  return 0;

}

# ------------------------------------------------------------------------------

sub do_work {

  my $status = 0;

  # Set up the temporary file names
  my $sxi_norm_lc = "sxi_norm.lc";
  my $sxi_mdye_lc = "sxi_mdye.lc";
  my $sxi_saa_lc = "sxi_saa.lc";
  my $filename  = "";

  ahapp::add_temp_file($sxi_norm_lc);
  ahapp::add_temp_file($sxi_mdye_lc);
  ahapp::add_temp_file($sxi_saa_lc);

  ########################
  # Extract lightcurves
  ########################

  # Extract the general SXI lightcurve
  $status = ahgen::run_ftool("extractor",
                             "filename=$infile1\[PI= 0: 4095]",
                             "eventsout=NONE", "regionfile=NONE", "qdpfile=NONE",
                             "fitsbinlc=$sxi_norm_lc",
                             "lcthresh=$lcthresh",
                             "lctzero=yes",
                             "xronwn=NONE", "unbinlc=NONE", "phafile=NONE", "imgfile=NONE", "timefile=NONE",
                             "adjustgti=no", "gstring=NONE", "timeorder=no",
                             "xcolf=X",
                             "ycolf=Y",
                             "xcolh=DETX", 
                             "ycolh=DETY",
                             "xfkey=TLMAX", "yfkey=TLMAX", "xhkey=TLMAX", "yhkey=TLMAX", "phamax=TLMAX",
                             "specbin=1", "binh=1", "binf=1",
                             "binlc=$binlc",
                             "tcol=TIME",
                             "ecol=PI",
                             "ccol=NONE",
                             "gcol=GRADE",
                             "gti=GTI", "events=EVENTS",
                             "gtitxt=NONE", "timeref=40000.00",
                             "wtmapb=no", "wtmapfix=yes", "swmapx=no", "swmapy=no", "wmapver=2",
                             "gtinam=GTI",
                             "exitnow=no");

  if ( $status ) {
    ahlog::ah_err "extractor failed.";
    return $status;
  }

  # Extract the SXI minus day-earth lightcurve 
  $status = ahgen::run_ftool("extractor",
                             "filename=$infile2\[PI= 0: 4095]",
                             "eventsout=NONE", "regionfile=NONE", "qdpfile=NONE",
                             "fitsbinlc=$sxi_mdye_lc",
                             "lcthresh=$lcthresh",
                             "lctzero=yes",
                             "xronwn=NONE", "unbinlc=NONE", "phafile=NONE", "imgfile=NONE", "timefile=NONE",
                             "adjustgti=no", "gstring=NONE", "timeorder=no",
                             "xcolf=X",
                             "ycolf=Y",
                             "xcolh=DETX", 
                             "ycolh=DETY",
                             "xfkey=TLMAX", "yfkey=TLMAX", "xhkey=TLMAX", "yhkey=TLMAX", "phamax=TLMAX",
                             "specbin=1", "binh=1", "binf=1",
                             "binlc=$binlc",
                             "tcol=TIME",
                             "ecol=PI",
                             "ccol=NONE",
                             "gcol=GRADE",
                             "gti=GTI", "events=EVENTS",
                             "gtitxt=NONE", "timeref=40000.00",
                             "wtmapb=no", "wtmapfix=yes", "swmapx=no", "swmapy=no", "wmapver=2",
                             "gtinam=GTI",
                             "exitnow=no");

  if ( $status ) {
    ahlog::ah_err "extractor failed.";
    return $status;
  }

  ########################
  # Merge SXI lightcurves
  ########################

  # Make the merged SXI SAA lightcurve
  $status = ahgen::run_ftool("lcurve",
                             "nser=3",
                             "cfile3=$ehkfile vy$ehkcol",
                             "cfile2=$sxi_mdye_lc",
                             "cfile1=$sxi_norm_lc",
                             "window=-",
                             "dtnb=$binlc",
                             "nbint=900",
                             "plot=n",
                             "plotdev=/XW",
                             "plotdnum=4",
                             "outfile=$sxi_saa_lc");
  if ( $status ) {
    ahlog::ah_err "lcurve failed.";
    return $status;
  }

  ########################
  # Plot the SXI data
  ########################

  # Run FPLOT to create the SXI postscript file
  $filename = $sxi_saa_lc . "[RATE][col TIME;RATENORMAL=RATE1;RATEMDYE=RATE2;SXI_SAA=RATE3;]";
  $status = ahgen::run_ftool("fplot",
                             "infile=$filename",
                             "maxpts=$maxpts",
                             "offset=$offset",
                             "xparm=TIME",
                             "yparm=RATENORMAL RATEMDYE SXI_SAA",
                             "rows=-",
                             "device=$saaplot/ps",
                             "pltcmd=$pltcmd",
                             "binmode=DEFAULT",
                             "sensecase=no",
                           );
  if ( $status ) {
    ahlog::ah_err "fplot failed.";
    return $status;
  }

  return 0;

}

# ------------------------------------------------------------------------------

sub finalize {

  my $status = 0;

  return 0;
  
}

# ------------------------------------------------------------------------------
