Index: /branches/eam_branches/ipp-20140423/PS-IPP-PStamp/lib/PS/IPP/PStamp/RequestFile.pm
===================================================================
--- /branches/eam_branches/ipp-20140423/PS-IPP-PStamp/lib/PS/IPP/PStamp/RequestFile.pm	(revision 36826)
+++ /branches/eam_branches/ipp-20140423/PS-IPP-PStamp/lib/PS/IPP/PStamp/RequestFile.pm	(revision 36827)
@@ -56,4 +56,5 @@
                     $PSTAMP_NOT_AUTHORIZED
                     $PSTAMP_NO_VALID_PIXELS
+                    $PSTAMP_BG_RESTORE_NOT_AVAILABLE
                     );
 our %EXPORT_TAGS = (standard => [@EXPORT_OK]);
@@ -112,4 +113,5 @@
 our $PSTAMP_NOT_AUTHORIZED   = 29;
 our $PSTAMP_NO_VALID_PIXELS  = 30;
+our $PSTAMP_BG_RESTORE_NOT_AVAILABLE = 31;
 
 
Index: /branches/eam_branches/ipp-20140423/ppBackground/src/ppBackgroundStackCamera.c
===================================================================
--- /branches/eam_branches/ipp-20140423/ppBackground/src/ppBackgroundStackCamera.c	(revision 36826)
+++ /branches/eam_branches/ipp-20140423/ppBackground/src/ppBackgroundStackCamera.c	(revision 36827)
@@ -267,5 +267,6 @@
 	    psString solutionFileName = psStringCopy(data->OTApath);
 	    psStringAppend(&solutionFileName, ".%s.fits",chipName);
-	    psFits *solutionFits = psFitsOpen(solutionFileName,"r");
+	    psString resolvedFileName = pmConfigConvertFilename(solutionFileName,config,false,false);
+	    psFits *solutionFits = psFitsOpen(resolvedFileName,"r");
 	    psImage *solution = psFitsReadImage(solutionFits,psRegionSet(0,0,0,0),0);
 	    psMetadataAddImage(data->OTA_solutions,PS_LIST_TAIL,
Index: /branches/eam_branches/ipp-20140423/ppBackground/src/ppBackgroundStackMath.c
===================================================================
--- /branches/eam_branches/ipp-20140423/ppBackground/src/ppBackgroundStackMath.c	(revision 36826)
+++ /branches/eam_branches/ipp-20140423/ppBackground/src/ppBackgroundStackMath.c	(revision 36827)
@@ -204,5 +204,5 @@
   
   pmFPAview *view    = pmFPAviewAlloc(0);
-  psStats *stats     = psStatsAlloc( PS_STAT_ROBUST_MEDIAN | PS_STAT_ROBUST_STDEV );
+  psStats *stats     = psStatsAlloc( PS_STAT_SAMPLE_MEDIAN | PS_STAT_SAMPLE_STDEV );
 
   psMetadataIterator *expIter = psMetadataIteratorAlloc(data->models, PS_LIST_HEAD, NULL);
Index: /branches/eam_branches/ipp-20140423/psLib/src/fits/psFitsScale.c
===================================================================
--- /branches/eam_branches/ipp-20140423/psLib/src/fits/psFitsScale.c	(revision 36826)
+++ /branches/eam_branches/ipp-20140423/psLib/src/fits/psFitsScale.c	(revision 36827)
@@ -1022,8 +1022,8 @@
                        /* Add random factor [-0.5,0.5): adds a variance of 1/12, */ \
                        /* but preserves the expectation value */ \
-                        value += psRandomUniform(rng) - 0.5; \
+                        value += psRandomUniform(rng) ; \
                     } \
                     /* Check for underflow and overflow; set either to max */ \
-                    (OUT)->data.OUTTYPE[y][x] = (value < min || value > max ? max : value); \
+                    (OUT)->data.OUTTYPE[y][x] = (value < min || value > max ? max : floor(value)); \
                 } \
             } \
Index: /branches/eam_branches/ipp-20140423/pstamp/scripts/psmkreq
===================================================================
--- /branches/eam_branches/ipp-20140423/pstamp/scripts/psmkreq	(revision 36826)
+++ /branches/eam_branches/ipp-20140423/pstamp/scripts/psmkreq	(revision 36827)
@@ -29,5 +29,5 @@
 my ($ra, $dec, $x, $y, $list, $output, $req_name, $req_name_base);
 
-my ($image, $mask, $variance, $jpeg, $cmf, $psf, $backmdl, $inverse);
+my ($image, $mask, $variance, $jpeg, $cmf, $psf, $backmdl, $inverse, $restorebackground);
 my ($convolved, $unconvolved, $uncompressed, $use_imfile_id, $no_wait);
 
@@ -120,4 +120,5 @@
     'convolved'         => \$convolved,
     'uncompressed'      => \$uncompressed,
+    'restorebackground' => \$restorebackground,
     'use_imfile_id'     => \$use_imfile_id,
     'do_not_wait'       => \$no_wait,
@@ -224,4 +225,5 @@
         $option_mask |= $PSTAMP_USE_IMFILE_ID   if $use_imfile_id;
         $option_mask |= $PSTAMP_SELECT_INVERSE  if $inverse;
+        $option_mask |= $PSTAMP_RESTORE_BACKGROUND  if $restorebackground;
     }
     $option_mask |= $PSTAMP_NO_WAIT_FOR_UPDATE if $no_wait;
Index: /branches/eam_branches/ipp-20140423/pstamp/scripts/pstamp_checkdependent.pl
===================================================================
--- /branches/eam_branches/ipp-20140423/pstamp/scripts/pstamp_checkdependent.pl	(revision 36826)
+++ /branches/eam_branches/ipp-20140423/pstamp/scripts/pstamp_checkdependent.pl	(revision 36827)
@@ -21,5 +21,7 @@
 use Carp;
 
-my $disable_3PI_updates = 1;
+my $disable_3PI_updates = 0;
+my $ra_max_3PI_hours = 22.5;  # disable updates for skycells with ra greater than this (hours)
+my $ra_max_3PI = $ra_max_3PI_hours * 15 * 3.14149 / 180.; # rawExp.ra is in radians
 
 # XXX: put this in a module somewhere
@@ -260,7 +262,12 @@
 
         if ($disable_3PI_updates && ($chip->{data_group} =~ /ThreePi/)) {
-            # we are getting close to the end of PV2. Do not update PV1 chips.
-            print "3PI updates are currently disabled\n";
-            return $PSTAMP_NOT_AVAILABLE;
+            # we are getting close to the end of PV2. Do not update PV1 chips if RA is above the limit.
+            my $ra = $chip->{ra};
+            if (!defined($ra) or ($ra > $ra_max_3PI)) {
+                print "3PI updates are currently disabled for RA $ra > $ra_max_3PI (radians)\n";
+                return $PSTAMP_NOT_AVAILABLE;
+            } else {
+                print "allowing 3PI updates RA $ra\n";
+            }
         } 
 
@@ -381,6 +388,11 @@
     # we are getting close to the end of PV2. optionally do not update 3Pi data.
     if ($disable_3PI_updates && ($metadata->{data_group} =~ /ThreePi/)) {
-        print "3PI updates are currently disabled\n";
-        return $PSTAMP_NOT_AVAILABLE;
+        my $ra = $metadata->{ra};
+        if (!defined $ra or ($ra > $ra_max_3PI)) {
+            print "3PI updates are currently disabled for RA $ra > $ra_max_3PI (radians)\n";
+            return $PSTAMP_NOT_AVAILABLE;
+        } else {
+            print "allowing 3PI updates RA $ra\n";
+        }
     } 
 
@@ -465,4 +477,7 @@
         }
         $chip_id = $chip->{chip_id};
+        # XXX: -scmap doesn't have ra and dec. Copy it from the warp
+        $chip->{ra} = $metadata->{ra};
+        $chip->{decl} = $metadata->{decl};
 
         # if chip has been magicked before require it to be magicked again
Index: /branches/eam_branches/ipp-20140423/pstamp/scripts/pstamp_finish.pl
===================================================================
--- /branches/eam_branches/ipp-20140423/pstamp/scripts/pstamp_finish.pl	(revision 36826)
+++ /branches/eam_branches/ipp-20140423/pstamp/scripts/pstamp_finish.pl	(revision 36827)
@@ -211,6 +211,11 @@
                         chomp $line;
                         my ($img_name, $reported_size, $reported_sum, $filetype) = split '\|', $line;
-                        # ... instead let dsreg compute the paramters by leaving them blank
-                        print $rlf "$img_name|||$filetype|\n";
+                        my $use_supplied_size = 1;
+                        if ($use_supplied_size) {
+                            print $rlf "$img_name|$reported_size|$reported_sum|$filetype|\n";
+                        } else {
+                            # ... instead let dsreg compute the paramters by leaving them blank
+                            print $rlf "$img_name|||$filetype|\n";
+                        }
 
                         # add line to the table definition file
Index: /branches/eam_branches/ipp-20140423/pstamp/scripts/pstamp_job_run.pl
===================================================================
--- /branches/eam_branches/ipp-20140423/pstamp/scripts/pstamp_job_run.pl	(revision 36826)
+++ /branches/eam_branches/ipp-20140423/pstamp/scripts/pstamp_job_run.pl	(revision 36827)
@@ -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
 {
Index: /branches/eam_branches/ipp-20140423/pstamp/scripts/pstampparse.pl
===================================================================
--- /branches/eam_branches/ipp-20140423/pstamp/scripts/pstampparse.pl	(revision 36826)
+++ /branches/eam_branches/ipp-20140423/pstamp/scripts/pstampparse.pl	(revision 36827)
@@ -182,5 +182,5 @@
     	$label = 'NCU';
 	$label_changed = 1;
-    } elsif (($lcname =~ /mpe_/) or ($lcname =~ /sd_/)) {
+    } elsif (($lcname =~ /mpe_/) or ($lcname =~ /sd_/) or ($lcname =~ /^jk/)) {
     	$label = 'MPE';
 	$label_changed = 1;
Index: /branches/eam_branches/ipp-20140423/pstamp/src/pstamp.h
===================================================================
--- /branches/eam_branches/ipp-20140423/pstamp/src/pstamp.h	(revision 36826)
+++ /branches/eam_branches/ipp-20140423/pstamp/src/pstamp.h	(revision 36827)
@@ -24,4 +24,5 @@
         PSTAMP_NOT_AUTHORIZED   = 29,
         PSTAMP_NO_VALID_PIXELS  = 30,
+        PSTAMP_BG_RESTORE_NOT_AVAILABLE = 31,
 } pstampJobErrors;
 
