#!/usr/bin/env perl

use Carp;
use warnings;
use strict;

## report the program and machine
use Sys::Hostname;
my $host = hostname();
print "\n\n";
print "Starting script $0 on $host\n\n";

use vars qw( $VERSION );
$VERSION = '0.01';

use IPC::Cmd 0.36 qw( can_run run );
use PS::IPP::Metadata::Config;
use PS::IPP::Metadata::Stats;
use PS::IPP::Config 1.01 qw( :standard );

my $ipprc = PS::IPP::Config->new(); # IPP configuration

use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );

my ( $det_id, $iter, $exp_id, $exp_tag, $class_id, $det_type, $detrend, $input_uri, $camera, $mode, $outroot,
     $dbname, $reduction, $verbose, $no_update, $no_op, $redirect );
GetOptions(
    'det_id|d=s'        => \$det_id,
    'iteration=s'       => \$iter,
    'exp_id|e=s'        => \$exp_id,
    'exp_tag|=s'        => \$exp_tag,
    'class_id|i=s'      => \$class_id,
    'det_type|t=s'      => \$det_type,
    'detrend=s'         => \$detrend,
    'input_uri|u=s'     => \$input_uri,
    'camera|c=s'        => \$camera,
    'mode|m=s'          => \$mode,
    'outroot|w=s'       => \$outroot,   # output file base name
    'dbname|d=s'        => \$dbname, # Database name
    'reduction=s'       => \$reduction, # Reduction class
    'verbose'           => \$verbose,   # Print to stdout
    'no-update'         => \$no_update,
    'no-op'             => \$no_op,
    'redirect-output'   => \$redirect,
) or pod2usage( 2 );

pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
pod2usage( -msg => "Required options: --det_id --iteration --exp_id --exp_tag --class_id --det_type --camera --input_uri --mode --detrend --outroot (not for 'verify' mode)",
           -exitval => 3) unless
    defined $det_id    and
    defined $iter      and
    defined $exp_id    and
    defined $exp_tag   and
    defined $class_id  and
    defined $det_type  and
    defined $input_uri and
    defined $camera    and
    defined $mode      and
    defined $outroot   and
    (defined $detrend or lc($mode) eq 'verify');

$ipprc->define_camera($camera);
my $logDest     = $ipprc->filename("LOG.IMFILE", $outroot, $class_id);
if ($redirect) {
    $ipprc->redirect_output($logDest);
}

# Recipes to use as a function of detrend type and mode
$reduction = 'DETREND' unless defined $reduction;
my $recipe;                     # Name of recipe to use
if ($mode eq 'master') {
    $recipe = uc($det_type) . '_RESID';
} elsif ($mode eq 'verify') {
    $recipe = uc($det_type) . '_VERIFY';
} else {
    &my_die("Unrecognised mode: $mode", $det_id, $iter, $exp_id, $class_id, $PS_EXIT_PROG_ERROR);
}
$recipe = $ipprc->reduction($reduction, $recipe);

# values to extract from output metadata and the stats to calculate
my $STATS =
   [
       #          PPSTATS KEYWORD         STATISTIC          CHIPTOOL FLAG
       { name => "ROBUST_MEDIAN",      type => "mean",  flag => "-bg",             dtype => "float" },
       { name => "ROBUST_MEDIAN",      type => "stdev", flag => "-bg_mean_stdev",  dtype => "float" },
       { name => "ROBUST_STDEV",       type => "rms",   flag => "-bg_stdev",       dtype => "float" },
       { name => "SAMPLE_SKEWNESS",    type => "mean",  flag => "-bg_skewness",    dtype => "float" },
       { name => "SAMPLE_KURTOSIS",    type => "mean",  flag => "-bg_kurtosis",    dtype => "float" },
       { name => "FRINGE_0",           type => "mean",  flag => "-fringe_0",       dtype => "float" },
       { name => "FRINGE_ERR_0",       type => "rms",   flag => "-fringe_1",       dtype => "float" },
       { name => "FRINGE_0",           type => "stdev", flag => "-fringe_2",       dtype => "float" },
       { name => "FRINGE_RESID_0",     type => "mean",  flag => "-fringe_resid_0", dtype => "float" },
       { name => "FRINGE_RESID_ERR_0", type => "rms",   flag => "-fringe_resid_1", dtype => "float" },
       { name => "FRINGE_RESID_0",     type => "stdev", flag => "-fringe_resid_2", dtype => "float" },
   ];
my $stats = PS::IPP::Metadata::Stats->new($STATS); # Stats parser

my $BINNED_STATS =
   [
       { name => "ROBUST_STDEV",   type => "rms",   flag => "-bin_stdev" },
   ];
my $binnedStats = PS::IPP::Metadata::Stats->new($BINNED_STATS); # Stats parser

# Flags to specify the particular detrend to use
use constant DETRENDS => {
    'bias'     	       => '-bias',      # Specify the bias frame
    'dark'     	       => '-dark',      # Specify the dark frame
    'dark_premask'     => '-dark',      # Specify the dark frame
    'shutter'  	       => '-shutter',   # Specify the shutter frame
    'flat'     	       => '-flat',      # Specify the flat frame
    'domeflat' 	       => '-flat',      # Specify the flat frame
    'skyflat'  	       => '-flat',      # Specify the flat frame
    'flat_premask'     => '-flat',      # Specify the flat frame
    'domeflat_premask' => '-flat',      # Specify the flat frame
    'skyflat_premask'  => '-flat',      # Specify the flat frame
    'fringe'   	       => '-fringe',    # Specify the fringe frame
    'mask'     	       => '-mask',      # Specify the mask frame
    'darkmask' 	       => '-mask',      # Specify the mask frame
    'flatmask' 	       => '-mask',      # Specify the mask frame
};

use constant DELETE_STATS => 0; # Delete the statistics file when done?

# Look for programs we need
my $missing_tools;
my $dettool = can_run('dettool') or (warn "Can't find dettool" and $missing_tools = 1);
my $ppImage = can_run('ppImage') or (warn "Can't find ppImage" and $missing_tools = 1);
my $ppStats = can_run('ppStats') or (warn "Can't find ppStats" and $missing_tools = 1);
if ($missing_tools) {
    warn("Can't find required tools.");
    exit($PS_EXIT_CONFIG_ERROR);
}

# outroot examples (HOST components must be set)
# file://data/ipp004.0/gpc1/20080130
# neb:///ipp004-v1/gpc1/20080130
# neb:///*/gpc1/20080130 (volume not specified)

# check for existing directory, generate if needed
$ipprc->outroot_prepare($outroot);

# XXX use PPIMAGE.OUTPUT.RESID for output file (compressed, with pos & neg range allowed)
# my $outputName  = $ipprc->filename("PPIMAGE.OUTPUT", $outroot, $class_id);

my $outputName  = $ipprc->filename("PPIMAGE.OUTPUT.RESID", $outroot, $class_id);
my $bin1Name    = $ipprc->filename("PPIMAGE.BIN1",   $outroot, $class_id);
my $bin2Name    = $ipprc->filename("PPIMAGE.BIN2",   $outroot, $class_id);
my $outputStats = $ipprc->filename("PPIMAGE.STATS",  $outroot, $class_id);
my $traceDest   = $ipprc->filename("TRACE.IMFILE",   $outroot, $class_id);

# Run ppImage & ppStats
unless ($no_op) {
    my $command = "$ppImage -file $input_uri $outroot";
    $command .= " -recipe PPIMAGE $recipe";
    $command .= " -recipe PPSTATS RESIDUAL";
    $command .= " -F PPIMAGE.OUTPUT PPIMAGE.OUTPUT.RESID";
    $command .= " -stats $outputStats";
    $command .= " -tracedest $traceDest -log $logDest";
    $command .= " -dbname $dbname" if defined $dbname;

    # Detrend to use in processing
    if (lc($mode) ne 'verify') {
        my $detFlag = DETRENDS->{lc($det_type)};
        &my_die("Unrecognised detrend type: $det_type", $det_id, $iter, $exp_id, $class_id, $PS_EXIT_PROG_ERROR) unless defined $detFlag;
        $command .= " $detFlag $detrend";
    }

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);
    unless ($success) {
        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
        &my_die("Unable to perform ppImage: $error_code", $det_id, $iter, $exp_id, $class_id, $error_code);
    }
    &my_die("Couldn't find expected output file: $outputName", $det_id, $iter, $exp_id, $class_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($outputName);
    &my_die("Couldn't find expected output file: $outputStats", $det_id, $iter, $exp_id, $class_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($outputStats);
    &my_die("Couldn't find expected output file: $bin1Name", $det_id, $iter, $exp_id, $class_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($bin1Name);
    &my_die("Couldn't find expected output file: $bin2Name", $det_id, $iter, $exp_id, $class_id, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($bin2Name);

    # Load the raw output stats file
    my $statsFile;              # File handle
    open $statsFile, $ipprc->file_resolve($outputStats) or &my_die("Can't open statistics file $outputStats: $!", $det_id, $iter, $exp_id, $class_id, $PS_EXIT_SYS_ERROR);
    my @contents = <$statsFile>; # Contents of file
    close $statsFile;

    # Parse the stats file contents into a metadata
    my $mdcParser = PS::IPP::Metadata::Config->new;     # Parser for metadata config files
    my $metadata = $mdcParser->parse(join "", @contents) or &my_die("Unable to parse metadata config doc", $det_id, $iter, $exp_id, $class_id, $PS_EXIT_PROG_ERROR);

    # Parse the statistics on the residual image
    $stats->parse($metadata) or &my_die("Unable to find all values in statistics output.", $det_id, $iter, $exp_id, $class_id, $PS_EXIT_PROG_ERROR);

    # run ppStats on the binned image
    $command = "$ppStats -recipe PPSTATS RESIDUAL $bin2Name";
    ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);
    unless ($success) {
        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
        &my_die("Unable to perform ppStats: $error_code", $det_id, $iter, $exp_id, $class_id, $error_code);
    }

    # Parse the output contents into a metadata
    my $binnedMetadata = $mdcParser->parse(join "", @$stdout_buf) or &my_die("Unable to parse metadata output", $det_id, $iter, $exp_id, $class_id, $PS_EXIT_PROG_ERROR);

    # parse the binned image statistics
    $binnedStats->parse($binnedMetadata) or &my_die("Unable to find all values in statistics output.", $det_id, $iter, $exp_id, $class_id, $PS_EXIT_PROG_ERROR);
}

# Command to update the database
my $command = "$dettool -addresidimfile";
$command .= " -det_id $det_id";
$command .= " -iteration $iter";
$command .= " -exp_id $exp_id";
$command .= " -class_id $class_id";
$command .= " -recip $recipe";
$command .= " -uri $outputName";
$command .= " -path_base $outroot";
$command .= " -dbname $dbname" if defined $dbname;
$command .= $stats->cmdflags();
$command .= $binnedStats->cmdflags();

# Add the processed file to the database
unless ($no_update) {
    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
        run(command => $command, verbose => $verbose);
    unless ($success) {
        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
        warn("Unable to perform dettool -addresidimfile: $error_code\n");
        exit($error_code);
    }
} else {
    print "skipping command: $command\n";
}

sub my_die
{
    my $msg = shift; # Warning message on die
    my $det_id = shift;         # Detrend identifier
    my $iter = shift;           # Iteration
    my $exp_id = shift; # Exposure tag
    my $class_id = shift; # Class identifier
    my $exit_code = shift; # Exit code to add

    carp($msg);
    if (defined $det_id and defined $iter and defined $exp_id and not $no_update) {
        my $command = "$dettool -addresidimfile";
        $command .= " -det_id $det_id";
        $command .= " -iteration $iter";
        $command .= " -exp_id $exp_id";
        $command .= " -class_id $class_id";
	$command .= " -path_base $outroot";
        $command .= " -code $exit_code";
        $command .= " -dbname $dbname" if defined $dbname;
        system ($command);
    }
    exit $exit_code;
}

END {
    my $exit = $?;
    system("sync") == 0 or die "failed to execute sync: $!";
    $? = $exit;
}

__END__
