#!/usr/bin/env perl

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::List qw( parse_md_list );
use Statistics::Descriptive;
use File::Temp qw( tempfile );

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, $det_type, $camera, $dbname, $workdir, $no_update, $no_op);
GetOptions(
    'det_id|d=s'        => \$det_id,
    'iteration|i=s'     => \$iter,
    'camera|c=s'        => \$camera,
    'det_type|t=s'      => \$det_type,
    '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 --camera --det_type",
    -exitval => 3,
) unless defined $det_id
     and defined $iter
     and defined $camera
     and defined $det_type;

$ipprc->define_camera($camera);

use constant RECIPE1 => 'PPIMAGE_J1'; # Recipe to use for ppImage to make JPEGs
use constant RECIPE2 => 'PPIMAGE_J2'; # Recipe to use for ppImage to make JPEGs


# 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);
if ($missing_tools) { 
    warn("Can't find required tools.");
    exit($PS_EXIT_CONFIG_ERROR); 
}

my $mdcParser = PS::IPP::Metadata::Config->new;	# Parser for metadata config files

# Get list of component files
my $files;			# Array of component files
{
    my $command = "$dettool -normalizedimfile -det_id $det_id -iteration $iter"; # Command to run
    $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);
	&my_die("Unable to perform ppImage: $error_code", $det_id, $iter, $error_code);
    }
    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
	&my_die("Unable to parse metadata config doc", $det_id, $iter, $PS_EXIT_PROG_ERROR);
    $files = parse_md_list($metadata) or
	&my_die("Unable to parse metadata list", $det_id, $iter, $PS_EXIT_PROG_ERROR);
}

# Gather the statistics
my ($bg, $bg_stdev, $bg_mean_stdev); # The statistics triplet
{
    my @backgrounds;		# Array of backgrounds in each component
    my @variances;    # Array of variances for each component
    foreach my $file (@$files) {
	&my_die("Unable to find class id", $det_id, $iter, $PS_EXIT_SYS_ERROR) unless defined $file->{class_id};
	my $class_id = $file->{class_id};
	&my_die("Unable to find bg for class_id=$class_id", $det_id, $iter, $PS_EXIT_SYS_ERROR) unless defined $file->{bg};
	&my_die("Unable to find bg_mean_stdev for class_id=$class_id", $det_id, $iter, $PS_EXIT_SYS_ERROR) unless defined $file->{bg_mean_stdev};
	push @backgrounds, $file->{bg};
	push @variances, $file->{bg_stdev}**2;
    }

    {
	my $stats = Statistics::Descriptive::Sparse->new; # Statistics calculator
	$stats->add_data(@backgrounds);
	$bg = ($stats->mean() or 'NAN');
	$bg_mean_stdev = ($stats->standard_deviation() or 'NAN');
    }
    {
	my $stats = Statistics::Descriptive::Sparse->new; # Statistics calculator
	$stats->add_data(@variances);
	$bg_stdev = (sqrt( $stats->mean() ) or 'NAN');
    }
}

my ($list1File, $list1Name) = tempfile( "$camera.$det_type.norm.$det_id.$iter.b1.list.XXXX", UNLINK => 1 );
my ($list2File, $list2Name) = tempfile( "$camera.$det_type.norm.$det_id.$iter.b2.list.XXXX", UNLINK => 1 );
my @means;			# Array of means
my @stdevs;			# Array of stdevs
foreach my $file (@$files) {
    print $list1File ( $ipprc->filename( "PPIMAGE.BIN1", $file->{path_base}, $file->{class_id} ) . "\n");
    print $list2File ( $ipprc->filename( "PPIMAGE.BIN2", $file->{path_base}, $file->{class_id} ) . "\n");
    push @means, $file->{bg};
    push @stdevs, $file->{bg_stdev};
}
close $list1File;
close $list2File;

# Output products
$workdir = caturi( $workdir, "$camera.$det_type.$det_id" ) if defined $workdir;
my $outputRoot = $ipprc->file_prepare( "$camera.$det_type.norm.$det_id.$iter", $workdir );
my $jpeg1Name = $ipprc->filename("PPIMAGE.JPEG1", $outputRoot); # Binned JPEG #1
my $jpeg2Name = $ipprc->filename("PPIMAGE.JPEG2", $outputRoot); # Binned JPEG #2

unless ($no_op) {
    # Make the jpeg for binning 1
    {
	my $command = "$ppImage -list $list1Name $outputRoot -recipe PPIMAGE " . RECIPE1; # Command to run
	my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	    run(command => $command, verbose => 1);
	&my_die("Unable to find expected output file: $jpeg1Name", $det_id, $iter, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($jpeg1Name);
    }
    
    # Make the jpeg for binning 2
    {
	my $command = "$ppImage -list $list2Name $outputRoot -recipe PPIMAGE " . RECIPE2; # Command to run
	my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	    run(command => $command, verbose => 1);
	&my_die("Unable to find expected output file: $jpeg2Name", $det_id, $iter, $PS_EXIT_SYS_ERROR) unless -f $ipprc->file_resolve($jpeg2Name);
    }
}

unless ($no_update) {
    my $command = "$dettool -addnormalizedexp -det_id $det_id -iteration $iter " .
	"-recip " . RECIPE1() . "," . RECIPE2() . " -path_base $outputRoot " .
	"-bg $bg -bg_stdev $bg_stdev -bg_mean_stdev $bg_mean_stdev"; # Command to run
    $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);
	&my_die("Unable to perform dettool -addnormalizedexp: $error_code", $det_id, $iter, $error_code);
    }
}


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

    warn($msg);
    if ($det_id and $iter and not $no_update) {
	my $command = "$dettool -addprocessedimfile -det_id $det_id -iter $iter -code $exit_code";
	$command .= " -dbname $dbname" if defined $dbname;
        system ($command);
    }
    exit $exit_code;
}

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

__END__
