Index: branches/eam_branches/ipp-ops-20130712/pstamp/scripts/pstamp_job_run.pl
===================================================================
--- branches/eam_branches/ipp-ops-20130712/pstamp/scripts/pstamp_job_run.pl	(revision 37064)
+++ branches/eam_branches/ipp-ops-20130712/pstamp/scripts/pstamp_job_run.pl	(revision 37068)
@@ -29,4 +29,5 @@
 my ($job_id, $redirect_output, $outputBase, $rownum, $jobType, $options); 
 my ($verbose, $dbname, $dbserver, $no_update, $save_temps);
+my $very_verbose = 0; # for debugging
 
 GetOptions(
@@ -67,16 +68,27 @@
 }
 
+if ($verbose && $save_temps) {
+    # we're probably debugging turn up the verbosity
+    $very_verbose = 1;
+}
+
 if (!$dbserver) {
     $dbserver =  metadataLookupStr($ipprc->{_siteConfig}, 'PS_DBSERVER');
 }
 
+my $temproot = metadataLookupStr($ipprc->{_siteConfig}, "TEMP.DIR");
+$temproot = "/tmp" if !defined $temproot;
+
 my $missing_tools;
 
 my $pstamptool = can_run('pstamptool')  or (warn "Can't find pstamptool"  and $missing_tools = 1);
-my $ppstamp    = can_run('ppstamp') or (warn "Can't find ppstamp" and $missing_tools = 1);
-my $pstamp_get_image_job    = can_run('pstamp_get_image_job.pl') or (warn "Can't find pstamp_get_image_job.pl" and $missing_tools = 1);
-my $psgetcalibinfo    = can_run('psgetcalibinfo') or (warn "Can't find psgetcalibinfo" and $missing_tools = 1);
+my $ppstamp = can_run('ppstamp') or (warn "Can't find ppstamp" and $missing_tools = 1);
+my $pstamp_get_image_job = can_run('pstamp_get_image_job.pl') or (warn "Can't find pstamp_get_image_job.pl" and $missing_tools = 1);
+my $psgetcalibinfo = can_run('psgetcalibinfo') or (warn "Can't find psgetcalibinfo" and $missing_tools = 1);
 my $dquery_job_run = can_run('dquery_job_run.pl') or (warn "Can't find dquery_job_run.pl" and $missing_tools = 1);
 my $whichnode = can_run('whichnode') or (warn "can't find whichnode" and $missing_tools = 1);
+my $ppBackground = can_run('ppBackground') or (warn "Can't find ppBackground" and $missing_tools = 1);
+my $ppBackgroundStack = can_run('ppBackgroundStack') or (warn "Can't find ppBackgroundStack" and $missing_tools = 1);
+my $stack_bkg_mk_mdc = can_run('stack_bkg_mk_mdc.pl') or (warn "Can't find stack_bkg_mk_mdc.pl" and $missing_tools = 1);
 
 if ($missing_tools) {
@@ -120,7 +132,22 @@
     }
 
+    if ($options & $PSTAMP_RESTORE_BACKGROUND) {
+        #  this subroutine creates a background restored version of the image or fails.
+        # upon success params->{image} is replaced with the new (temporary) version
+        my $error_code = create_background_restored_images($params);
+        if ($error_code) {
+            # if error code is one of the permanant ones set state of job to stop
+            my_die("failed to create background restored images", $job_id, $error_code, 
+                $error_code >= $PSTAMP_FIRST_ERROR_CODE ? 'stop' : undef);
+        }
+    }
+
     my $image = $params->{image};
     my $mask;
     my $variance;
+
+    # We need to background restore HERE
+    # and change the image file supplied to ppstamp
+
     my $fileArgs = " -file $params->{image}";
     my @file_list = ($params->{image});
@@ -665,4 +692,97 @@
 }
 
+# use ppBackground or ppBackgroundStack to produce background restored images
+sub create_background_restored_images {
+    my $params = shift;
+    my $stage = $params->{stage};
+
+    if ($stage ne 'stack' and $stage ne 'chip') {
+        # this function is only supported for chip and stack stage
+        # perhaps the parser should catch this ...
+        print STDERR "background restoration not currently supported for stage $params->{stage}\n";
+        return $PSTAMP_BG_RESTORE_NOT_AVAILABLE;
+    }
+
+    my $tempdir = tempdir("$temproot/pstamp.$job_id.XXXX", CLEANUP => !$save_temps);
+    my $imagedb = $params->{imagedb};
+    my $camera = $params->{camera};
+
+    # reinstantiate IPP Configuration using the now known camera so that we get the applicable file rules
+    $ipprc = PS::IPP::Config->new($camera);
+
+    my $input_image = $params->{image};
+    my $input_mask = $params->{mask};
+    my $input_variance = $params->{weight};
+
+    if ($stage eq 'stack') {
+        my $stack_id = $params->{stack_id};
+        my $mdcfile = "$tempdir/stk.$stack_id.bkg_input.mdc";
+        {
+            my $command = "$stack_bkg_mk_mdc --stack_id $stack_id --camera $camera --dbname $imagedb > $mdcfile";
+            my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
+                run(command => $command, verbose => $verbose);
+            unless ($success) {
+                $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
+                &my_die("Unable to perform stack_bg_mk_mdc.pl: $error_code", $job_id, $PS_EXIT_CONFIG_ERROR, 'run');
+            }
+        }
+
+        my $outroot = "$tempdir/stk.$stack_id";
+
+        # XXX: get otapath from a config file or detrend system
+        my $otapath = "neb:///detrends/background_OTA_models.20140527/test_solutions";
+        {
+            my $command = "$ppBackgroundStack $outroot -input $mdcfile -image $input_image"
+               . " -OTApath $otapath" ;
+            $command .= " -mask $input_mask" if $input_mask;
+            my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
+                run(command => $command, verbose => $very_verbose);
+            unless ($success) {
+                # we turned off verbosity because ppBackgroundStack emits too much output
+                # XXX: perhaps use a log file and save it with the job data
+                print STDERR join "", @$stderr_buf;
+                $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
+                &my_die("Unable to perform ppBackgroundStack: $error_code", $job_id, $PS_EXIT_CONFIG_ERROR, 'run');
+            }
+        }
+        # it's all good change the image to be passed to ppstamp
+        $params->{image} = $ipprc->filename('PPBACKGROUND.STACK.OUTPUT', $outroot) or
+                &my_die("Unable to resolve ppBackgroundStack output file name", $job_id, $PS_EXIT_UNKNOWN_ERROR, 'run');
+
+    } elsif ($stage eq 'chip') {
+        my $input_mdl = $params->{backmdl};
+        my $chip_id = $params->{chip_id};
+        my $class_id = $params->{class_id};
+        my $outroot = "$tempdir/bgrestored.ch.$chip_id";
+        {
+            my $command = "$ppBackground $outroot -background $input_mdl -image $input_image";
+            # XXX: I think ppBackground might always require mask and variance images
+            $command .= " -mask $input_mask";
+            $command .= " -variance $input_variance";
+
+            my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
+                run(command => $command, verbose => $verbose);
+            unless ($success) {
+                print STDERR join "", @$stderr_buf;
+                $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
+                &my_die("Unable to perform ppBackground: $error_code", $job_id, $PS_EXIT_CONFIG_ERROR, 'run');
+            }
+        }
+        $params->{image} = $ipprc->filename('PPBACKGROUND.OUTPUT', $outroot, $class_id) or
+                &my_die("Unable to resolve ppBackgroundStack output image name", $job_id, $PS_EXIT_CONFIG_ERROR, 'run');
+        $params->{mask} = $ipprc->filename('PPBACKGROUND.OUTPUT.MASK', $outroot, $class_id) or
+                &my_die("Unable to resolve ppBackgroundStack output mask name", $job_id, $PS_EXIT_CONFIG_ERROR, 'run');
+        $params->{weight} = $ipprc->filename('PPBACKGROUND.OUTPUT.VARIANCE', $outroot, $class_id) or
+                &my_die("Unable to resolve ppBackgroundStack output variance name", $job_id, $PS_EXIT_CONFIG_ERROR, 'run');
+
+    } else {
+        # can't get here
+        &my_die( "background restoration not currently supported for stage $params->{stage}\n",
+            $job_id, $PS_EXIT_PROG_ERROR, 'stop'); ;
+    }
+
+    return 0;
+}
+
 sub my_die
 {
