#!/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 Data::Dumper;

use PS::IPP::Config qw($PS_EXIT_SUCCESS
		       $PS_EXIT_UNKNOWN_ERROR
		       $PS_EXIT_SYS_ERROR
		       $PS_EXIT_CONFIG_ERROR
		       $PS_EXIT_PROG_ERROR
		       $PS_EXIT_DATA_ERROR
		       $PS_EXIT_TIMEOUT_ERROR
		       caturi
		       );
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_tag, $class_id, $det_type, $detrend,
        $input_uri, $camera, $mode, $dbname, $workdir, $no_update, $no_op);
GetOptions(
    'det_id|d=s'        => \$det_id,
    'iteration=s'       => \$iter,
    'exp_tag|e=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,
    'dbname|d=s'        => \$dbname, # Database name
    'workdir|w=s'       => \$workdir,	# Working directory, for output files
    'no-update'         => \$no_update,
    'no-op'             => \$no_op,
) or pod2usage( 2 );

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

$ipprc->define_camera($camera);

# Recipes to use, as a function of the detrend type
use constant RECIPES => {
    'master' => {		# We're creating a master --- already processed the input
	'bias'     => 'PPIMAGE_B',	# Bias only
	'dark'     => 'PPIMAGE_D',	# Dark only
	'shutter'  => 'PPIMAGE_S',	# Shutter only
	'flat'     => 'PPIMAGE_F',	# Flat-field only
	'domeflat' => 'PPIMAGE_F',	# Flat-field only
	'skyflat'  => 'PPIMAGE_F',	# Flat-field only
	'fringe'   => 'PPIMAGE_R',	# Fringe only
    },
    'verify' => {		# We're checking the master --- input is not already processed
	'bias'     => 'PPIMAGE_OB',	# Bias only
	'dark'     => 'PPIMAGE_OBD',	# Dark only
	'shutter'  => 'PPIMAGE_OBDS',	# Shutter only
	'flat'     => 'PPIMAGE_OBDSF',	# Flat-field only
	'domeflat' => 'PPIMAGE_OBDSF',	# Flat-field only
	'skyflat'  => 'PPIMAGE_OBDSF',	# Flat-field only
	'fringe'   => 'PPIMAGE_OBDSFR',	# Fringe only
    },
};

# Flags to specify the particular detrend to use
use constant DETRENDS => {
    'bias'     => '-bias',	# Specify the bias frame
    'dark'     => '-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
    'fringe'   => '-fringe',	# Specify the fringe 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); 
}
$ppImage .= " -dbname $dbname" if defined $dbname;

# Recipe to use in processing
&my_die("Unrecognised mode: $mode", $det_id, $iter, $exp_tag, $class_id, $PS_EXIT_PROG_ERROR) unless defined RECIPES->{$mode};
my $recipe = RECIPES->{$mode}->{lc($det_type)};
&my_die("Unrecognised detrend type: $det_type", $det_id, $iter, $exp_tag, $class_id, $PS_EXIT_PROG_ERROR) unless defined $recipe;

$workdir = caturi( $workdir, "$camera.$det_type.$det_id" ) if defined $workdir;

my $outputRoot = $ipprc->file_prepare( "$exp_tag/$exp_tag.detresid.$det_id.$iter", $workdir, $input_uri );
my $outputName = $ipprc->filename("PPIMAGE.OUTPUT", $outputRoot, $class_id);
my $bin1Name =  $ipprc->filename("PPIMAGE.BIN1", $outputRoot, $class_id);
my $bin2Name =  $ipprc->filename("PPIMAGE.BIN2", $outputRoot, $class_id);
my $outputStats = $outputRoot . '.' . $class_id . '.stats';

# Run ppImage & ppStats
my $stats = PS::IPP::Metadata::Stats->new(); # Stats parser
my $binnedStats = PS::IPP::Metadata::Stats->new(); # Stats parser
unless ($no_op) {
    my $command = "$ppImage -file $input_uri $outputRoot";
    $command .= " -recipe PPIMAGE $recipe";
    $command .= " -recipe PPSTATS RESIDUAL";
    $command .= " -stats $outputStats";

    # 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_tag, $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 => 1);
    unless ($success) {
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	&my_die("Unable to perform ppImage: $error_code", $det_id, $iter, $exp_tag, $class_id, $error_code);
    }
    &my_die("Couldn't find expected output file: $outputName", $det_id, $iter, $exp_tag, $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_tag, $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_tag, $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_tag, $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_tag, $class_id, $PS_EXIT_SYS_ERROR);
    my @contents = <$statsFile>; # Contents of file
    close $statsFile;

    # Parse the statistics on the residual image
    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_tag, $class_id, $PS_EXIT_PROG_ERROR);
    $stats->parse($metadata) or &my_die("Unable to find all values in statistics output.", $det_id, $iter, $exp_tag, $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 => 1);
    unless ($success) {
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	&my_die("Unable to perform ppStats: $error_code", $det_id, $iter, $exp_tag, $class_id, $error_code);
    }

    # parse the binned image statistics
    my $binnedMetadata = $mdcParser->parse(join "", @$stdout_buf) or &my_die("Unable to parse metadata output", $det_id, $iter, $exp_tag, $class_id, $PS_EXIT_PROG_ERROR);
    $binnedStats->parse($binnedMetadata) or &my_die("Unable to find all values in statistics output.", $det_id, $iter, $exp_tag, $class_id, $PS_EXIT_PROG_ERROR);
}

# Add the processed file to the database
my $bg            = ($stats->bg_mean() or 'NAN');
my $bg_stdev      = ($stats->bg_stdev() or 'NAN');
my $bg_mean_stdev = ($stats->bg_mean_stdev() or 'NAN');
my $bin_stdev	  = ($binnedStats->bg_stdev() or 'NAN');
#my $fringe_0 	  = ($stats->frng_00() or 'NAN');
#my $fringe_1 	  = ($stats->frng_00D() or 'NAN'); ## XXX for a test: this should be only frng_00D
#my $fringe_2 	  = ($stats->frng_01() or 'NAN');

# XXX temporary until paul fixes the metadata lookups above
my $fringe_0 	  = 'NAN';
my $fringe_1 	  = 'NAN';
my $fringe_2 	  = 'NAN';

unless ($no_update) {
    my $command = "$dettool -addresidimfile -det_id $det_id -iteration $iter";
    $command .= " -exp_tag $exp_tag -class_id $class_id";
    $command .= " -recip $recipe -uri $outputName -path_base $outputRoot";
    $command .= " -bg $bg -bg_stdev $bg_stdev -bg_mean_stdev $bg_mean_stdev";
    $command .= " -bin_stdev $bin_stdev";
    $command .= " -fringe_0 $fringe_0 -fringe_1 $fringe_1 -fringe_2 $fringe_2";
    $command .= " -dbname $dbname" if defined $dbname;

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	run(command => $command, verbose => 1);
    unless ($success) {
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	warn("Unable to perform dettool -addresidimfile: $error_code\n");
	exit($error_code);
    }
}

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

    carp($msg);
    if ($det_id and $iter and $exp_tag and not $no_update) {
	my $command = "$dettool -addresidimfile -det_id $det_id -iteration $iter -exp_tag $exp_tag -class_id $class_id -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__
