Index: /branches/eam_branches/ipp-20230313/ippScripts/Build.PL
===================================================================
--- /branches/eam_branches/ipp-20230313/ippScripts/Build.PL	(revision 42580)
+++ /branches/eam_branches/ipp-20230313/ippScripts/Build.PL	(revision 42581)
@@ -158,4 +158,5 @@
         scripts/xcstack_skycell.pl
         scripts/xcsky.pl
+        scripts/xccal.pl
     )],
     dist_abstract => 'Scripts for running the Pan-STARRS IPP',
Index: /branches/eam_branches/ipp-20230313/ippScripts/scripts/xccal.pl
===================================================================
--- /branches/eam_branches/ipp-20230313/ippScripts/scripts/xccal.pl	(revision 42581)
+++ /branches/eam_branches/ipp-20230313/ippScripts/scripts/xccal.pl	(revision 42581)
@@ -0,0 +1,323 @@
+#!/usr/bin/env perl
+
+use warnings;
+use strict;
+
+## report the program and machine
+use Sys::Hostname;
+my $host = hostname();
+my $date = `date`;
+print "\n\n";
+print "Starting script $0 on $host at $date\n\n";
+
+use DateTime;
+my $mjd_start = DateTime->now->mjd;   # MJD of starting script
+
+use vars qw( $VERSION );
+$VERSION = '0.01';
+
+use IPC::Cmd 0.36 qw( can_run run );
+use Scalar::Util qw(looks_like_number);
+use PS::IPP::Metadata::Config;
+use PS::IPP::Metadata::List qw( parse_md_list );
+use Data::Dumper;
+use File::Temp qw( tempfile );
+use File::Basename;
+use PS::IPP::Config 1.01 qw( :standard );
+
+use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
+use Pod::Usage qw( pod2usage );
+
+# Look for programs we need
+my $missing_tools;
+my $xcskytool = can_run('xcskytool') or (warn "Can't find xcskytool" and $missing_tools = 1);
+my $psastro = can_run('psastro') or (warn "Can't find psastro" and $missing_tools = 1);
+my $fhead = can_run('fhead') or (warn "Can't find fhead" and $missing_tools = 1);
+my $fields = can_run('fields') or (warn "Can't find fields" and $missing_tools = 1);
+my $ppStatsFromMetadata = can_run('ppStatsFromMetadata') or (warn "Can't find ppStatsFromMetadata" and $missing_tools = 1);
+my $ppConfigDump = can_run('ppConfigDump') or (warn "Can't find ppConfigDump" and $missing_tools = 1);
+if ($missing_tools) {
+    warn("Can't find required tools.");
+    exit($PS_EXIT_CONFIG_ERROR);
+}
+
+sub HelpMessage {
+    print "USAGE: xccal.pl --xccal_id (xccal_id) --outroot (root) --camera (camera) [options]\n";
+    print "  --xccal_id (xccal_id) : run identifier\n";
+    print "  --camera (camera)       : Camera name\n";
+    print "  --dbname (dbname)       : Database name\n";
+    print "  --threads (N)           : Number of threads to use\n";
+    print "  --outroot (root)        : Output root name\n";
+    print "  --path_base (path_base) : path_base of input\n";
+    print "  --filter (filter)       : filter of input\n";
+    print "  --singlefilter          : the input is the result of a single filter analysis";
+    print "  --reduction (class)     : Reduction class\n";
+    print "  --verbose               : Be extra verbose\n";
+    print "  --no-update             : Don't update the database?\n";
+    print "  --no-op                 : Don't do any operations?\n";
+    print "  --redirect-output       : send output to the log file,\n";
+    print "  --save-temps            : Save temporary files?\n";
+    print "  --help                  : show this message\n";
+    exit 2;
+}
+
+my ($xccal_id, $xcstack_id, $camera, $dbname, $threads, $outroot, $path_base, $reduction, $verbose, $no_update, $no_op, $redirect, $save_temps);
+my $run_state = 'new';
+GetOptions(
+    'xccal_id=s'        => \$xccal_id,  # xcsky run id
+    'xcstack_id=s'      => \$xcstack_id,# xcstack run id
+    'camera|c=s'        => \$camera,    # Camera name
+    'dbname|d=s'        => \$dbname,    # Database name
+    'threads=s'         => \$threads,   # Number of threads to use
+    'outroot=s'         => \$outroot,   # Output root name
+    'run-state=s'       => \$run_state, # 'new' or 'update'
+    'path_base=s'       => \$path_base, # path_base of input
+    'reduction=s'       => \$reduction, # Reduction class
+    'verbose'           => \$verbose,   # Print to stdout
+    'no-update'         => \$no_update, # Don't update the database?
+    'no-op'             => \$no_op, # Don't do any operations?
+    'redirect-output'   => \$redirect,
+    'save-temps'        => \$save_temps, # Save temporary files?
+    'help'              => sub { HelpMessage() },
+) or pod2usage( 2 );
+
+pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
+
+pod2usage(
+    -msg => "Required options: --xccal_id --xcstack_id --outroot --camera --path_base",
+    -exitval => 3,
+          ) unless 
+    defined $xccal_id and
+    defined $xcstack_id and
+    defined $path_base and
+    defined $outroot and
+    defined $camera;
+
+my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $xccal_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
+
+my $logDest = $ipprc->filename("LOG.EXP", $outroot);
+$ipprc->redirect_to_logfile($logDest) or my_die( "Unable to redirect output", $xccal_id, $PS_EXIT_SYS_ERROR ) if $redirect;
+
+my $traceDest  = $ipprc->filename("TRACE.EXP", $outroot);
+my $stats      = $ipprc->filename("PSASTRO.STATS", $outroot);
+
+my $outbase = basename($outroot);
+
+# Get list of input images to xcstack photometry
+my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files
+my $files;
+
+# Recipes to use based on reduction class
+$reduction = 'DEFAULT' unless defined $reduction;
+
+# generate the input 
+my $cmdflags = "";
+
+unless ($run_state eq 'new' or $run_state eq 'update') {
+    &my_die("$run_state is not a valid value for run-state\n", $xccal_id, $PS_EXIT_CONFIG_ERROR);
+}
+my $updateMode = $run_state eq 'update';
+
+my $recipe_psastro  = $ipprc->reduction($reduction, 'STATICSKY_CALIBRATION'); # Recipe to use for psastro
+unless ($recipe_psastro) {
+    &my_die("Couldn't find selected reduction for STATICSKY_CALIBRATION: $reduction\n", $xccal_id, $PS_EXIT_CONFIG_ERROR);
+}
+
+# XXX: We are making the bad assumption here that the staticksky run used the same reduction class
+# as this xccalRun
+my $recipe_psphot = $ipprc->reduction($reduction, "STACKPHOT_PSPHOT");
+unless ($recipe_psphot) {
+    &my_die("Couldn't find selected reduction for STACKPHOT_PSPHOT: $reduction\n", $xccal_id, $PS_EXIT_CONFIG_ERROR);
+}
+
+print "reduction:      $reduction\n";
+print "recipe_psastro: $recipe_psastro\n";
+print "recipe_psphot:  $recipe_psphot\n";
+
+my $configuration = $ipprc->filename("PSASTRO.CONFIG", $outroot);
+
+# find input file
+# First check the expected file name where the xcstack_id is the FILE_ID
+
+my $file = $ipprc->filename('PSPHOT.STACK.OUTPUT', $path_base, $xcstack_id);
+if (! $ipprc->file_resolve($file)) {
+    print "\nfailed to resolve $file, is it a single-filter stack?\n";
+    # input is from a single filter static sky run which used psphot instead of psphotStack
+    # The file rule is different for psphot
+    $file = $ipprc->filename('PSPHOT.OUT.CMF.MEF', $path_base);
+    &my_die("Unable to find input for $xcstack_id", $xccal_id, $PS_EXIT_SYS_ERROR) 
+	unless $ipprc->file_exists($file);
+}
+if ($file) {
+    print "\nInput file for $xcstack_id: $file\n";
+} else {
+    &my_die("Unable to find input file for xcstack_id $xcstack_id.", $xccal_id, $PS_EXIT_SYS_ERROR);
+}
+
+my $resolved = $ipprc->file_resolve($file);
+if (!$resolved) {
+    &my_die("Unable to find input file: $file", $xccal_id, $PS_EXIT_SYS_ERROR);
+}
+
+# Perform psastro analysis
+my $output_sources_filerule = 'PSASTRO.OUTPUT.CMF';
+my $quality = 0;
+{
+    my $command = "$psastro $outroot";
+    $command .= " -file $file";
+    $command .= " -recipe PSASTRO  $recipe_psastro";
+    $command .= " -recipe PSPHOT   $recipe_psphot";
+    $command .= " -F PSASTRO.OUTPUT $output_sources_filerule";
+    $command .= " -Db PSASTRO.SAVE.CFF F" if $updateMode;
+    $command .= " -stats $stats";
+    $command .= " -recipe PPSTATS SKYCALSTATS";
+    $command .= " -dumpconfig $configuration" if $configuration;
+    $command .= " -tracedest $traceDest";
+    $command .= " -dbname $dbname" if defined $dbname;
+
+    unless ($no_op) {
+        my ( $success, $error_msg, $full_buf, $stdout_buf, $stderr_buf ) = run(command => $command, verbose => $verbose);
+	my $error_code = &parse_error_message ($success, $error_msg, $command);
+	unless ($success) {
+	    &my_die("Unable to perform $command: $error_msg", $xccal_id, $error_code);
+	}
+
+        &my_die("Couldn't find stats file: $stats", $xccal_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($stats);
+
+        {
+            my $resolved = $ipprc->file_resolve($stats) 
+                or  &my_die("failed to resolve stats file: $stats", $xccal_id, $PS_EXIT_SYS_ERROR) ;
+            my $command = "$ppStatsFromMetadata $resolved - STATICSKY_CAL";
+            my ( $success, $error_msg, $full_buf, $stdout_buf, $stderr_buf ) = run(command => $command, verbose => $verbose);
+	    my $error_code = &parse_error_message ($success, $error_msg, $command);
+	    unless ($success) {
+		&my_die("Unable to perform $command: $error_msg", $xccal_id, $error_code);
+	    }
+            $cmdflags = join "", @$stdout_buf; chomp $cmdflags;
+        }
+
+        ($quality) =  $cmdflags =~ /-quality (\d+)/;
+        if (!$quality) {
+            my $outputSources  = $ipprc->filename($output_sources_filerule, $outroot);
+            &my_die("Couldn't find expected output file: $outputSources", $xccal_id, $PS_EXIT_SYS_ERROR)
+                unless $ipprc->file_exists($outputSources);
+
+            &my_die("Couldn't find expected output file: $configuration", $xccal_id, $PS_EXIT_SYS_ERROR) 
+                unless $ipprc->file_exists($configuration);
+        }
+    } else {
+        print "Not executing: $command\n";
+    }
+}
+
+# Add the result to the database
+if (!$updateMode) {
+    my $command = "$xcskytool -xccal_id $xccal_id";
+    $command .= " -addxccalresult -path_base $outroot";
+    $command .= " $cmdflags";
+    $command .= (" -dtime_script " . ((DateTime->now->mjd - $mjd_start) * 86400));
+    $command .= " -hostname $host" if defined $host;
+    $command .= " -dbname $dbname" if defined $dbname;
+
+    unless($no_update) {
+        my ( $success, $error_msg, $full_buf, $stdout_buf, $stderr_buf ) = run(command => $command, verbose => $verbose);
+	my $error_code = &parse_error_message ($success, $error_msg, $command);
+	unless ($success) {
+	    &my_die("Unable to perform $command: $error_msg", $xccal_id, $error_code);
+	}
+    } else {
+        print "skipping $command\n";
+    }
+} else {
+    if ($quality) {
+        # First update the result
+        my $command = "$xcskytool -updatexccal -xccal_id $xccal_id -set_fault 0";
+        $command .= " -set_quality $quality";
+        $command .= " -dbname $dbname" if defined $dbname;
+
+        unless($no_update) {
+            my ( $success, $error_msg, $full_buf, $stdout_buf, $stderr_buf ) = run(command => $command, verbose => $verbose);
+	    my $error_code = &parse_error_message ($success, $error_msg, $command);
+	    unless ($success) {
+		&my_die("Unable to perform $command: $error_msg", $xccal_id, $error_code);
+	    }
+        } else {
+            print "skipping $command\n";
+        }
+    }
+    my $command = "$xcskytool -xccal_id $xccal_id";
+    $command .= ' -updatexccalrun -set_state full';
+    $command .= " -dbname $dbname" if defined $dbname;
+
+    unless($no_update) {
+        my ( $success, $error_msg, $full_buf, $stdout_buf, $stderr_buf ) = run(command => $command, verbose => $verbose);
+	my $error_code = &parse_error_message ($success, $error_msg, $command);
+	unless ($success) {
+	    &my_die("Unable to perform $command: $error_msg", $xccal_id, $error_code);
+	}
+    } else {
+        print "skipping $command\n";
+    }
+}
+
+exit 0;
+
+sub my_die
+{
+    my $msg = shift;            # Warning message on die
+    my $xccal_id = shift;        # Diff identifier
+    my $exit_code = shift;      # Exit code to add
+
+    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
+
+    warn($msg);
+    if (defined $xccal_id and not $no_update) {
+        my $command = "$xcskytool -xccal_id $xccal_id";
+        if ($updateMode) {
+            $command .= " -updatexccal -set_fault $exit_code";
+        } else {
+            $command .= " -addxccalresult -fault $exit_code";
+            $command .= (" -dtime_script " . ((DateTime->now->mjd - $mjd_start) * 86400));
+            $command .= " -hostname $host" if defined $host;
+            $command .= " -path_base $outroot" if defined $outroot;
+        }
+	$command .= " -dbname $dbname" if defined $dbname;
+        run(command => $command, verbose => $verbose);
+    }
+    exit $exit_code;
+}
+
+# if the program exited normally, the exit value is returned
+# if the program exited with a signal (abort, crash, etc), PS_EXIT_PROG_ERROR (4) is returned
+# if the program failed to run, -PS_EXIT_PROG_ERROR (-4) is returned
+sub parse_error_message {
+    my $success = shift;
+    my $error_msg = shift;
+    my $command = shift;
+
+    if ($success) { return 0; }
+
+    print "raw error_msg: $error_msg\n";
+    print "full command: $command\n";
+
+    if (&looks_like_number($error_msg)) { return (($error_msg >> 8) or ($PS_EXIT_PROG_ERROR)); }
+	
+    # which of these match?
+    my ($error_code) = $error_msg =~ m/exited with value (\d+)/;
+    if (defined $error_code) { return $error_code; }
+    
+    ($error_code) = $error_msg =~ m/died with signal (\d+)/;
+#   if (defined $error_code) { return (128 + $error_code); }
+    if (defined $error_code) { return ($PS_EXIT_PROG_ERROR); }
+    
+    # probably failed to execute:
+    return (-1*$PS_EXIT_PROG_ERROR);
+}
+
+END {
+    my $exit = $?;
+    system("sync") == 0 or die "failed to execute sync: $!";
+    $? = $exit;
+}
+
+__END__
