#!/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, $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);
}


my ($list1File, $list1Name) = tempfile( "$exp_tag.detresid.$det_id.$iter.b1.list.XXXX", UNLINK => 1 );
my ($list2File, $list2Name) = tempfile( "$exp_tag.detresid.$det_id.$iter.b2.list.XXXX", UNLINK => 1 );
my @means;			# Array of means
my @variances;			# Array of variances
my @meanStdevs;			# Array of mean stdevs
my @names;			# Array of names (class_id)
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 @meanStdevs, $file->{bg_mean_stdev};
    ## calculate the root-mean-square of the bd_stdevs
    push @variances, $file->{bg_stdev}*$file->{bg_stdev};
    push @names, $file->{class_id};
}
close $list1File;
close $list2File;

# Output products
$workdir = caturi( $workdir, "$camera.$det_type.$det_id" ) if defined $workdir;
my $outputRoot = $ipprc->file_prepare( "$exp_tag.detresid.$det_id.$iter", $workdir, ${$files}[0]->{path_base} );
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 $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);
	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 $ipprc->file_resolve($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 );

my $logName = caturi( $workdir, "$exp_tag.detreject.$det_id.$iter.log" ); # Name for log
my $logFile;
unless ($no_op) {
    $logFile = $ipprc->file_create_open( $logName );
}

# 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
    my $name = $names[$i];

    last if $no_op;

    if ($reject_imfile_mean) {
	if (abs($mean) > $reject_imfile_mean * $stdev) {
	    print $logFile "Rejecting exposure based on bad imfile mean for $name: ";
	    $reject = 1;
	} else {
	    print $logFile "Imfile mean for $name meets requirements: ";
	}
	print $logFile "$mean vs $reject_imfile_mean\n";
    }  else {
	print $logFile "No rejection on imfile mean for $name\n";
    }
    if ($reject_imfile_stdev) {
	if ($stdev > $reject_imfile_stdev) {
	    print $logFile "Rejecting exposure based on bad imfile stdev for $name: ";
	    $reject = 1;
	} else {
	    print $logFile "Imfile stdev for $name meets requirements: ";
	}
	print $logFile "$stdev vs $reject_imfile_stdev\n";

    } else {
	print $logFile "No rejection on imfile stdev for $name\n";
    }
    if ($reject_imfile_meanstdev) {
	if ($meanStdevs[$i] > $reject_imfile_meanstdev) {
	    print $logFile "Rejecting exposure based on bad imfile mean stdev for $name: ";
	    $reject = 1;
	} else {
	    print $logFile "Imfile mean stdev for $name meets requirements: ";
	}
	print $logFile "$meanStdevs[$i] vs $reject_imfile_meanstdev\n";
    } else {
	print $logFile "No rejection on imfile mean stdev for $name\n";
    }
    if ($reject_imfile_sn) {
	if ($mean < $stdev * $reject_imfile_sn) {
	    print $logFile "Rejecting exposure based on bad imfile S/N for $name: ";
	    $reject = 1;
	} else {
	    print $logFile "Imfile S/N for $name meets requirements: ";
	}
	print $logFile "mean: $mean vs stdev*SNlimit: " . $stdev * $reject_imfile_sn . "\n";
    } else {
	print $logFile "No rejection on imfile S/N for $name\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; }

## Reject based on the exposure ensemble stats
# reject if the exposure ensemble mean is deviant
unless ($no_op) {
    print $logFile "Exposure mean $mean, stdev $stdev, mean stdev $meanStdev, exp s/n: $exp_sn\n";

    if ($reject_exp_mean) {
	if (abs($mean) > $reject_exp_mean * $stdev) {
	    print $logFile "Rejecting exposure based on bad mean: ";
	    $reject = 1;
	} else {
	    print $logFile "Exposure mean meets requirements: ";
	}
	print $logFile "mean: $mean, stdev: $stdev (limit is: % $reject_exp_mean\n";
    } else {
	print $logFile "No rejection for exp mean\n";
    }
    # reject if the exposure ensemble stdev is deviant
    if ($reject_exp_stdev) {
	if ($stdev > $reject_exp_stdev) {
	    print $logFile "Rejecting exposure based on bad stdev: ";
	    $reject = 1;
	} else {
	    print $logFile "Exposure stdev meets requirements: ";
	}
	print $logFile "$stdev vs $reject_exp_stdev\n";
    } else {
	print $logFile "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 $logFile "Rejecting exposure based on bad mean stdev: ";
	    $reject = 1;
	} else {
	    print $logFile "Exposure mean stdev meets requirements: ";
	}
	print $logFile "$meanStdev vs $reject_exp_meanstdev\n";
    } else {
	print $logFile "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 $logFile "Rejecting exposure based on poor S/N: \n";
	    $reject = 1;
	} else {
	    print $logFile "Exposure S/N meets requirements: \n";
	}
	print $logFile "signal: $mean vs noise: $stdev (s/n limit is: $reject_exp_sn)\n";
    } else {
	print $logFile "No rejection for exp S/N\n";
    }

    close $logFile;
}

# Add the result into the database
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);
    }
}

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
