#!/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 qw( can_run run );
use PS::IPP::Metadata::Config;
use PS::IPP::Metadata::List qw( parse_md_list );
use Statistics::Descriptive;

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
    );
my $ipprc = PS::IPP::Config->new(); # IPP configuration
use File::Spec;

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

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

$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 imfile files
my $files;			# Array of imfile files
{
    my $command = "$dettool -residimfile -det_id $det_id -iteration $iter -exp_tag $exp_tag"; # 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);
	warn("Unable to perform dettool -residimfile: $error_code\n");
	exit($error_code);
    }

    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
	&my_die("Unable to parse metadata config doc", $det_id, $iter, $exp_tag, $PS_EXIT_PROG_ERROR);
    $files = parse_md_list($metadata) or
	&my_die("Unable to parse metadata list", $det_id, $iter, $exp_tag, $PS_EXIT_PROG_ERROR);
}

if (defined $workdir) {
    $workdir = $ipprc->convert_filename_absolute( $workdir );
} else {
    my $example = ${$files}[0]->{path_base}; # Example original root name
    my ($vol, $dir, $file) = File::Spec->splitpath( $example );
    $workdir = $dir;
}

# Generate the file list, and get the statistics
my $outputFile = "$exp_tag.detresid.$det_id.$iter"; # Root name
my $outputRoot = File::Spec->catfile( $workdir, $exp_tag, $outputFile );

my $list1Name = $outputRoot . '.b1.list'; # Name for the input file list for binning 1
my $list2Name = $outputRoot . '.b2.list'; # Name for the input file list for binning 2

my @means;			# Array of means
my @variances;			# Array of variances
my @meanStdevs;			# Array of mean stdevs
open my $list1File, '>' . $list1Name;
open my $list2File, '>' . $list2Name;
foreach my $file (@$files) {
    my $origRoot = $ipprc->convert_filename_absolute( $file->{path_base} ); # Original root name
    print $list1File ($ipprc->filename( "PPIMAGE.BIN1", $origRoot, $file->{class_id} ) . "\n");
    print $list2File ($ipprc->filename( "PPIMAGE.BIN2", $origRoot, $file->{class_id} ) . "\n");
    push @means, $file->{bg};
    push @meanStdevs, $file->{bg_mean_stdev};
    ## calculate the root-mean-square of the bd_stdevs
    push @variances, $file->{bg_stdev}*$file->{bg_stdev};

}
close $list1File;
close $list2File;

# Output products --- need to synch with the camera configuration!
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);
	unless ($success) {
	    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	    &my_die("Unable to run ppImage: $error_code", $det_id, $iter, $exp_tag, $error_code);
	}
	&my_die("Unable to find expected output file: $jpeg1Name", $det_id, $iter, $exp_tag, $PS_EXIT_SYS_ERROR) unless -f $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);
	unless ($success) {
	    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	    &my_die("Unable to run ppImage: $error_code", $det_id, $iter, $exp_tag, $error_code);
	}
	&my_die("Unable to find expected output file: $jpeg2Name", $det_id, $iter, $exp_tag, $PS_EXIT_SYS_ERROR) unless -f $jpeg2Name;
    }
}

my $expected = rejection_limit( 'EXPECTED', $det_type, $filter ); # Expected mean
# Rejection thresholds
my $reject_imfile_mean      = rejection_limit( 'IMFILE.MEAN',      $det_type, $filter );
my $reject_imfile_stdev     = rejection_limit( 'IMFILE.STDEV',     $det_type, $filter );
my $reject_imfile_meanstdev = rejection_limit( 'IMFILE.MEANSTDEV', $det_type, $filter );
my $reject_imfile_sn        = rejection_limit( 'IMFILE.SN',        $det_type, $filter );
my $reject_exp_mean         = rejection_limit( 'EXP.MEAN',         $det_type, $filter );
my $reject_exp_stdev        = rejection_limit( 'EXP.STDEV',        $det_type, $filter );
my $reject_exp_meanstdev    = rejection_limit( 'EXP.MEANSTDEV',    $det_type, $filter );
my $reject_exp_sn           = rejection_limit( 'EXP.SN',           $det_type, $filter );

# Reject based on the stats of the imfiles
# it is VALID to reject on more than one criterion
&my_die("Number of means and number of variances differ!", $det_id, $iter, $exp_tag, $PS_EXIT_PROG_ERROR) unless scalar @means == scalar @variances;
for (my $i = 0; $i < scalar @means; $i++) {
    my $mean = $means[$i];	# Mean for this imfile
    $mean -= $expected;
    my $stdev = sqrt($variances[$i]);	# Stdev for this imfile

    last if $no_op;

    if ($reject_imfile_mean) {
	if (abs($mean) > $reject_imfile_mean * $stdev) {
	    print "Rejecting exposure based on bad imfile mean for imfile $i: " .
		$mean . " vs " . $reject_imfile_mean . "\n";
	    $reject = 1;
	    last;
	}
    }  else {
	print "no rejection for imfile mean\n";
    }
    if ($reject_imfile_stdev) {
	if ($stdev > $reject_imfile_stdev) {
	    print "Rejecting exposure based on bad imfile stdev for imfile $i: " .
		$stdev . " vs " . $reject_imfile_stdev . "\n";
	    $reject = 1;
	    last;
	}
    } else {
	print "no rejection for imfile stdev\n";
    }
    if ($reject_imfile_meanstdev) {
	if ($meanStdevs[$i] > $reject_imfile_meanstdev) {
	    print "Rejecting exposure based on bad imfile mean stdev for imfile $i: " .
		$meanStdevs[$i] . " vs " . $reject_imfile_meanstdev . "\n";
	    $reject = 1;
	    last;
	}
    } else {
	print "no rejection for imfile mean stdev\n";
    }
    if ($reject_imfile_sn) {
	if ($mean < $stdev * $reject_imfile_sn) {
	    print "Rejecting exposure based on bad imfile S/N for imfile $i: \n";
	    print "mean: " . $mean . " vs " . "stdev*SNlimit: " . $stdev * $reject_imfile_sn . "\n";
	    $reject = 1;
	    last;
	}
    } else {
	print "no rejection for imfile S/N\n";
    }
}

# calculate the exposure ensemble statistics
my $meanStats = Statistics::Descriptive::Sparse->new();	# Statistics calculator for means
$meanStats->add_data(@means);
my $varianceStats = Statistics::Descriptive::Sparse->new(); # Statistics calculator for variances
$varianceStats->add_data(@variances);

my $mean = $meanStats->mean();	# Mean of the imfile means
my $meanStdev = $meanStats->standard_deviation(); # Stdev of the imfile means
if (not defined $meanStdev) {
    # this is the case for Nimfile == 1
    $meanStdev = 0;
}
my $stdev = sqrt($varianceStats->mean()); # Root-Mean-Square of the imfile stdevs (root mean of variances)
my $exp_sn = 0.0;
if ($stdev > 0) { $exp_sn = $mean / $stdev; }

print "exposure mean $mean, stdev $stdev, mean stdev $meanStdev, exp s/n: $exp_sn\n";

## Reject based on the exposure ensemble stats
# reject if the exposure ensemble mean is deviant
unless ($no_op) {
    if ($reject_exp_mean) {
	if (abs($mean) > $reject_exp_mean * $stdev) {
	    print "Rejecting exposure based on bad mean: \n";
	    print "mean: $mean, stdev: $stdev (limit is: % $reject_exp_mean\n";
	    $reject = 1;
	} 
    } else {
	print "no rejection for exp mean\n";
    }
    # reject if the exposure ensemble stdev is deviant
    if ($reject_exp_stdev) {
	if ($stdev > $reject_exp_stdev) {
	    print "Rejecting exposure based on bad mean stdev: " . $stdev . " vs " .
		$reject_exp_stdev . "\n";
	    $reject = 1;
	}
    } else {
	print "no rejection for exp stdev\n";
    }
    # reject if the exposure ensemble mean stdev is deviant
    if ($reject_exp_meanstdev) {
	if ($meanStdev > $reject_exp_meanstdev) {
	    print "Rejecting exposure based on bad mean stdev: " . $meanStdev . " vs " .
		$reject_exp_meanstdev . "\n";
	    $reject = 1;
	}
    } else {
	print "no rejection for exp mean stdev\n";
    }
    # reject if the signal-to-noise is insufficient
    if ($reject_exp_sn) {
	if (abs($mean) < abs($stdev * $reject_exp_sn)) {
	    print "Rejecting exposure based on poor S/N: \n";
	    print "signal: $mean vs noise: $stdev (s/n limit is: $reject_exp_sn)\n";
	    $reject = 1;
	}
    } else {
	print "no rejection for exp S/N\n";
    }
}

# Add the result into the database
$outputRoot = $ipprc->convert_filename_relative( $outputRoot );

my $bg = $mean;
my $bg_stdev = $stdev;
my $bg_mean_stdev = $meanStdev;

unless ($no_update) {
    my $command = "$dettool -addresidexp -det_id $det_id -iteration $iter -exp_tag $exp_tag " .
	"-recip " . RECIPE1() . "," . RECIPE2() . " -path_base $outputRoot "; # Command to run
    $command .= " -bg $bg -bg_stdev $bg_stdev -bg_mean_stdev $bg_mean_stdev";
    $command .= ' -reject' if $reject;
    $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 -addresidexp: $error_code\n");
	exit($error_code);
    }

    unlink $list1Name;
    unlink $list2Name;
}

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


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 $exit_code = shift; # Exit code to add

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


# Retrieve the requested rejection limit, dying if not extant
sub rejection_limit
{
    my $name = shift;		# Rejection limit to 
    my $type = shift;		# Type of exposure
    my $filter = shift;		# Filter

    my $value = $ipprc->rejection( $name, $det_type, $filter );
    if (not defined $value) {
	$filter = "(no filter)" if not defined $filter;
	die "Unable to determine $name rejection limit for $det_type with $filter.\n";
    }

    return $value;
}




__END__

####

## this function is not well though out.  it loads a collection of
## values (background mean and stdev) for a collection of imfile
## subcomponents.  it then measures the mean background, the
## background stdev (rms of ensemble stdevs), and the background mean
## stdev (rms of the means).  it then tries to reject based on the
## following criteria:
## (background / stdev > limit) for a single component
##    ---> this will ACCEPT for a poor images (large stdev)
## (stdev > limit)
## (mean background / stdev > limit) same problem
## (mean stdev > limit)

### I would suggest the following:
## 1) calculate the ensemble mean and stdev
## 2) for each component, is the (back - mean) / mean stdev > limit?
##    (ie, is it an outlier?)
## 3) is the component stdev > limit? (absolute test)
## 4) calculate the background stdev for the ensemble (excluding rejects)
## 5) is the mean stdev > limit (poor images)
## 6) calculate the ensemble stdev (rms) of remaining (excluding rejects)
## 7) is the ensemble stdev > limit 

## for flats, the value used for stdev should be the fractional stdev
## (stdev/mean) and no rejection should be performed on the basis of
## the mean value, but could still be done on the mean stdev

## the same logical cuts above can be applied to components in an
## imfile, imfiles in an exposure, and exposures in a stack

### this function needs to avoid div by zero: compare Signal vs Noise*limit
