#!/usr/bin/env perl

use warnings;
use strict;
use Carp;

## 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 ($exp_id, $cam_id, $recipe, $camera, $dbname, $workdir, $dvodb, $no_update, $no_op);
GetOptions(
	   'exp_id=s'          => \$exp_id, # Exposure identifier
	   'cam_id=s'          => \$cam_id, # Camtool identifier
	   'recipe=s'          => \$recipe, # Recipe to use
	   'camera|c=s'        => \$camera, # Camera
	   'dbname|d=s'        => \$dbname, # Database name
	   'workdir|w=s'       => \$workdir, # Working directory
	   'dvodb|w=s'         => \$dvodb,  # output DVO database
	   'no-update'         => \$no_update, # Update the database?
	   'no-op'             => \$no_op, # Don't do any operations?
	   ) or pod2usage( 2 );

pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
pod2usage(
    -msg => "Required options: --exp_id --cam_id --camera",
    -exitval => 3,
) unless defined $exp_id
    and defined $cam_id
    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 $camtool = can_run('camtool') or (warn "Can't find camtool" and $missing_tools = 1);
my $ppImage = can_run('ppImage') or (warn "Can't find ppImage" and $missing_tools = 1);

# test for addstar and psastro:
my $psastro = can_run('psastro') or (warn "Can't find psastro" and $missing_tools = 1);
my $addstar = can_run('addstar') or (warn "Can't find addstar" 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 = "$camtool -pendingimfile -cam_id $cam_id"; # 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 camtool: $error_code", $cam_id, $error_code);
    }
    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
	&my_die("Unable to parse metadata config doc", $cam_id, $PS_EXIT_PROG_ERROR);
    $files = parse_md_list($metadata) or
	&my_die("Unable to parse metadata list", $cam_id, $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
#    my @ra;			# Array of ra errors
#    my @dec;			# Array of dec errors
#    my @zp;			# Array of photometric zero points
    foreach my $file (@$files) {
	&my_die("Unable to find class id", $cam_id, $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", $cam_id, $PS_EXIT_SYS_ERROR) unless defined $file->{bg};
	&my_die("Unable to find bg_mean_stdev for class_id=$class_id", $cam_id, $PS_EXIT_SYS_ERROR) unless defined $file->{bg_mean_stdev};
#	&my_die("Unable to find sigma_ra for class_id=$class_id", $cam_id, $PS_EXIT_SYS_ERROR) unless defined $file->{sigma_ra};
#	&my_die("Unable to find sigma_dec for class_id=$class_id", $cam_id, $PS_EXIT_SYS_ERROR) unless defined $file->{sigma_dec};
#	&my_die("Unable to find zp for class_id=$class_id", $cam_id, $PS_EXIT_SYS_ERROR) unless defined $file->{zp};
	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( "$exp_id.cam$cam_id.b1.list.XXXX", UNLINK => 1 ); # For binning 1
my ($list2File, $list2Name) = tempfile( "$exp_id.cam$cam_id.b2.list.XXXX", UNLINK => 1 ); # For binning 2
my ($list3File, $list3Name) = tempfile( "$exp_id.cam$cam_id.b3.list.XXXX", UNLINK => 1 ); # For astrometry

my @means;			# Array of means
my @stdevs;			# Array of stdevs
my $chipObjects; 
foreach my $file (@$files) {
    # use the path_base as OUTPUT root and convert the filenames with ipprc->filename:
    my $class_id = $file->{class_id};

    # If there is only one chip, we use this name for the input to addstar
    $chipObjects = $ipprc->filename("PSASTRO.OUTPUT", $file->{path_base}, $class_id);
    print $list1File ($ipprc->filename("PPIMAGE.BIN1", $file->{path_base}, $class_id) . "\n");
    print $list2File ($ipprc->filename("PPIMAGE.BIN2", $file->{path_base}, $class_id) . "\n");
    print $list3File ($chipObjects . "\n");
    push @means, $file->{bg};
    push @stdevs, $file->{bg_stdev};
}
close $list1File;
close $list2File;
close $list3File;

# Output products
$workdir = caturi( $workdir, $exp_id ) if defined $workdir;
my $outputRoot = $ipprc->file_prepare( "$exp_id.cam$cam_id", $workdir, ${$files}[0]->{path_base} );
my $jpeg1 = $ipprc->filename("PPIMAGE.JPEG1", $outputRoot); # Binned JPEG #1
my $jpeg2 = $ipprc->filename("PPIMAGE.JPEG2", $outputRoot); # Binned JPEG #2
my $fpaObjects = $ipprc->filename("PSASTRO.OUTPUT.MEF", $outputRoot); # MEF psastro output

# convert supplied DVO database name to UNIX filename
my $dvodbReal;
if (defined $dvodb) {
    $dvodbReal = $ipprc->convert_filename_absolute( $dvodb );
}

unless ($no_op) {

    # run psastro +mosastro on the set of chips
    # XXX note that this is wrong if imfiles are cells
    if (scalar @$files > 1) {
	my $command = "$psastro -list $list3Name $outputRoot +mosastro -chipastro " . 
	    "-F PSASTRO.OUTPUT PSASTRO.OUTPUT.MEF";
	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 psastro: $error_code", $cam_id, $error_code);
	}
    } else {
	$ipprc->file_copy($chipObjects, $fpaObjects) unless $chipObjects eq $fpaObjects;
    }
    &my_die("Unable to find expected output file: $fpaObjects", $cam_id, $PS_EXIT_PROG_ERROR) unless -f $ipprc->file_resolve($fpaObjects);

    # run addstar on either the single chip output or the single fpa output
    # XXX this construct requires the user to have a valid .ptolemyrc 
    # XXX which in turn points at ippconfig/dvo.site
    {
	my $camdir = $ipprc->dvo_cameradir(); # Camera directory for addstar
	my $command = "addstar -D CAMERA $camdir " . $ipprc->file_resolve($fpaObjects);
	
	if (defined $dvodbReal) {
	    $command .= " -D CATDIR $dvodbReal";
	}

	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 addstar: $error_code", $cam_id, $error_code);
	}
    }
    
    # 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 perform ppImage: $error_code", $cam_id, $error_code);
	}
	&my_die("Unable to find expected output file: $jpeg1", $cam_id, $PS_EXIT_PROG_ERROR) unless -f $ipprc->file_resolve($jpeg1);
    }

    # 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 perform ppImage: $error_code", $cam_id, $error_code);
	}
	&my_die("Unable to find expected output file: $jpeg2", $cam_id, $PS_EXIT_PROG_ERROR) unless -f $ipprc->file_resolve($jpeg2);
    }
}

# Add the result into the database
unless ($no_update) {

    my $command = "$camtool -addprocessedexp";
    $command .= " -cam_id $cam_id -uri UNKNOWN -path_base $outputRoot";
    $command .= " -bg $bg -bg_stdev $bg_stdev -bg_mean_stdev $bg_mean_stdev";
    $command .= " -sigma_ra 0.0 -sigma_dec 0.0";
    $command .= " -zp_mean 0.0 -zp_stdev 0.0";
    $command .= " -fwhm 0.0 -fwhm_range 0.0";
    $command .= " -n_stars 0 -n_extended 0 -n_cr 0 -n_astrom 0";
    $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 -addprocessedexp: $error_code\n");
	exit($error_code);
    }
}


sub my_die
{
    my $msg = shift; # Warning message on die
    my $cam_id = shift; # Camtool identifier
    my $exit_code = shift; # Exit code to add

    carp($msg);
    if ($cam_id and not $no_update) {
	my $command = "$camtool -addprocessedexp -cam_id $cam_id -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__
