#!/usr/bin/env perl

## USAGE:flatcorr_proc.pl --dbname --corr_id

## this script does the following steps:

# extract the details of the flatcorr run: dvodb, filter, camera, etc?

# relphot -D CATDIR $dvodb -grid (outgrid.fits) (filter) -region 0 360 -90 90 (other parameters?)

# dvoMakeCorr -file outgrid.fits -ref ref.fits outcorr

# dettool -register -det_type FLATCORR -filelevel (level) -workdir -inst, etc 
# foreach $imfile () 
#   dettool -register_imfile -uri, etc, etc

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 Storable qw(freeze thaw);
use File::Basename qw( basename);
use IPC::Cmd 0.36 qw( can_run run );
use PS::IPP::Metadata::Config;
use PS::IPP::Metadata::Stats;
use PS::IPP::Config 1.01 qw( :standard );

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 ($corr_id, $dvodb, $region, $filter, $dbname, $workdir, $no_update, $no_op);
GetOptions(
    'corr_id|i=s'      => \$corr_id,
    'dvodb|c=s'        => \$dvodb,
    'region|r=s'       => \$region,
    'filter|f=s'       => \$filter,
    '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: --corr_id --dvodb --region --filter",
           -exitval => 3) unless
    defined $corr_id and
    defined $dvodb and
    defined $region and
    defined $filter;

# Look for programs we need
my $missing_tools;
my $relphot     = can_run('relphot')      or (warn "Can't find relphot"      and $missing_tools = 1);
my $dvoMakeCorr = can_run('dvoMakeCorr')  or (warn "Can't find dvoMakeCorr"  and $missing_tools = 1);
my $detselect   = can_run('detselect') 	  or (warn "Can't find detselect"    and $missing_tools = 1);
my $dettool     = can_run('dettool')   	  or (warn "Can't find dettool"      and $missing_tools = 1);
my $flatcorr    = can_run('flatcorr')  	  or (warn "Can't find flatcorr"     and $missing_tools = 1);

if ($missing_tools) { 
    warn ("Can't find required tools");
    exit($PS_EXIT_CONFIG_ERROR); 
}

my($outgrid, $outcorr);

$outgrid = "$workdir/grid.$corr_id.fits";
$outcorr = "$workdir/corr.$corr_id.fits";

# parse the region (RAs,RAe:DECs,DECe) : item = +/-NNN.NNNN
my @coords = split (":", $region);
my ($RAs, $RAe) = split (",", $coords[0]);
my ($DECs, $DECe) = split (",", $coords[1]);

# Run relphot (filter) for the specified region (need to clarify the options like imfreeze)
{
    my $command = "$relphot $filter";
    $command .= "-D CATDIR $dvodb";
    $command .= "-region $RAs $RAe $DECs $DECe";
    $command .= "-grid $outgrid";
    $command .= "-imfreeze?";

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	cache_run(command => $command, verbose => 1);

    unless ($success) { 
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	&my_die ("Unable to perform relphot -grid on region $region: $error_code", $dvo_id, $region, "RELPHOT", $status, $dbname);
    }
}

# use one of the input raw images as a reference image
# XXX I'm not sure how this works: do I run this once per imfile for a given exp?
my ($reffile)
{
    my $command = "$flatcoor -flatcorrimfile -limit 1";

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	cache_run(command => $command, verbose => 1);

    unless ($success) { 
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	&my_die ("Unable to perform flatcorr -flatcorrimfile: $error_code", $dvo_id, $region, "RELPHOT", $status, $dbname);
    }

    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
	&my_die("Unable to parse metadata config doc", $dvo_id, $region, "RELPHOT", $status, $dbname, $PS_EXIT_PROG_ERROR););

    my $imfiles = parse_md_list($metadata) or 
	&my_die("Unable to parse metadata list", $dvo_id, $region, "RELPHOT", $status, $dbname, $PS_EXIT_PROG_ERROR););

    my $imfile = $imfiles->[0];
    $reffile = $imfile->{uri};
}

{
    my $command = "$dvoMakeCorr -file $outgrid -ref $reffile $outcorr";

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	cache_run(command => $command, verbose => 1);

    unless ($success) { 
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	&my_die ("Unable to perform dvoMakeCorr: $error_code", $dvo_id, $region, "RELASTRO.OBJECTS", $status, $dbname);
    }
}

{
    my $command = "$dettool -register";
    $command .= "-det_type FLATCORR";
    $command .= "-file_level $fileLevel";
    $command .= "-workdir $workdir";
    $command .= "-inst $inst";
    $command .= " -dbname $dbname" if defined $dbname;
    ## XXX what else do we need, and where do we get it?

    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
	cache_run(command => $command, verbose => 1);

    unless ($success) { 
	$error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
	&my_die ("Unable to perform addstar -resort on region $region: $error_code", $dvo_id, $region, "RELASTRO.IMAGES", $status, $dbname);
    }
}

my $command = "$flatcorr -done";
$command .= " -corr_id $corr_id";
$command .= " -stats UNKNOWN";
$command .= " -dbname $dbname" if defined $dbname;

# Push the results into the database
unless ($no_update) {
    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 regtool -addprocessedimfile: $error_code");
        exit($error_code);
    }
} else {
    print "skipping command: $command\n";
}

sub my_die
{
    my $msg = shift; # Warning message on die
    my $dvo_id    = shift;
    my $region    = shift;
    my $last_step = shift;
    my $status 	  = shift;
    my $dbname 	  = shift;

    carp($msg);
    if (defined $dvo_id && defined $region && defined $last_step && defined $status and not $no_update) {
        my $command = "$caltool -addcalrun";
	$command .= " -dvo_id $dvo_id";
        $command .= " -region $region";
	$command .= " -last_step $last_step";
	$command .= " -status $status";
        $command .= " -dbname $dbname" if defined $dbname;
        system ($command);
    }
    exit $exit_code;
}

# Pau.

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

__END__
