Index: branches/czw_branch/20120906/ippScripts/Build.PL
===================================================================
--- branches/czw_branch/20120906/ippScripts/Build.PL	(revision 34756)
+++ branches/czw_branch/20120906/ippScripts/Build.PL	(revision 34772)
@@ -128,4 +128,5 @@
         scripts/listvideocells.pl
         scripts/skycalibration.pl
+        scripts/regenerate_background.pl
     )],
     dist_abstract => 'Scripts for running the Pan-STARRS IPP',
Index: branches/czw_branch/20120906/ippScripts/MANIFEST
===================================================================
--- branches/czw_branch/20120906/ippScripts/MANIFEST	(revision 34756)
+++ branches/czw_branch/20120906/ippScripts/MANIFEST	(revision 34772)
@@ -46,3 +46,4 @@
 scripts/skycell_jpeg.pl
 scripts/lap_science.pl
+scripts/regenerate_background.pl
 t/00_distribution.t
Index: branches/czw_branch/20120906/ippScripts/scripts/addstar_run.pl
===================================================================
--- branches/czw_branch/20120906/ippScripts/scripts/addstar_run.pl	(revision 34756)
+++ branches/czw_branch/20120906/ippScripts/scripts/addstar_run.pl	(revision 34772)
@@ -300,5 +300,8 @@
 	    $command .= " -image" if $image_only;
 	    if ($stage =~ /staticsky/) {
-		$command .= " -accept-astrom ";
+		$command .= " -accept-astrom -quick-airmass";
+	    }  #careful here - this matches staticsky and staticsky_multi
+	    if ($stage =~ /skycal/) {
+		$command .= " -quick-airmass";
 	    }  #careful here - this matches staticsky and staticsky_multi
 
Index: branches/czw_branch/20120906/ippScripts/scripts/background_chip.pl
===================================================================
--- branches/czw_branch/20120906/ippScripts/scripts/background_chip.pl	(revision 34756)
+++ branches/czw_branch/20120906/ippScripts/scripts/background_chip.pl	(revision 34772)
@@ -73,5 +73,5 @@
 
 if ($redirect) {
-    $ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $chip_bg_id, $class_id, $PS_EXIT_SYS_ERROR );
+    $ipprc->redirect_to_logfile($logDest) or my_die( "Unable to redirect output", $chip_bg_id, $class_id, $PS_EXIT_SYS_ERROR );
     print STDOUT "\n\n";
     print STDOUT "Starting script $0 on $host\n\n";
@@ -155,9 +155,15 @@
 
 $ipprc->outroot_prepare($outroot);
-my $out_image = $ipprc->filename("PPBACKGROUND.OUTPUT", $outroot, $class_id);
-my $out_mask = $ipprc->filename("PPBACKGROUND.OUTPUT.MASK", $outroot, $class_id);
-my $out_stats = $ipprc->filename("PPBACKGROUND.STATS", $outroot, $class_id);
-my $out_config = $ipprc->filename("PPBACKGROUND.CONFIG", $outroot, $class_id);
-my $traceDest = $ipprc->filename("TRACE.IMFILE", $outroot, $class_id);
+#my $out_image = $ipprc->filename("PPBACKGROUND.OUTPUT", $outroot, $class_id);
+#my $out_mask = $ipprc->filename("PPBACKGROUND.OUTPUT.MASK", $outroot, $class_id);
+#my $out_stats = $ipprc->filename("PPBACKGROUND.STATS", $outroot, $class_id);
+#my $out_config = $ipprc->filename("PPBACKGROUND.CONFIG", $outroot, $class_id);
+#my $traceDest = $ipprc->filename("TRACE.IMFILE", $outroot, $class_id);
+
+my $out_image = prepare_output("PPBACKGROUND.OUTPUT", $outroot, $class_id, 1);
+my $out_mask = prepare_output("PPBACKGROUND.OUTPUT.MASK", $outroot, $class_id, 1);
+my $out_stats = prepare_output("PPBACKGROUND.STATS", $outroot, $class_id, 1);
+my $out_config = prepare_output("PPBACKGROUND.CONFIG", $outroot, $class_id, 1);
+my $traceDest = prepare_output("TRACE.IMFILE", $outroot, $class_id, 1);
 
 # Run ppImage
@@ -238,4 +244,23 @@
 ### Pau.
 
+# Prepare to write to an output file
+#   Lookup the filename in the rules.
+#   Make sure that if file exists and is a nebulous file that there is only one instance
+#   Deal with files that have been lost.
+sub prepare_output
+{
+    my $filerule = shift;
+    my $outroot  = shift;
+    my $class_id = shift;
+    my $delete = shift;
+    $delete = 0 if !defined $delete;
+
+    my $error;
+    my $output = $ipprc->prepare_output($filerule, $outroot, $class_id, $delete, \$error)
+                    or &my_die("failed to prepare output file for: $filerule", $chip_bg_id, $class_id, $error);
+    return $output;
+}
+
+
 
 sub my_die
Index: branches/czw_branch/20120906/ippScripts/scripts/background_warp.pl
===================================================================
--- branches/czw_branch/20120906/ippScripts/scripts/background_warp.pl	(revision 34756)
+++ branches/czw_branch/20120906/ippScripts/scripts/background_warp.pl	(revision 34772)
@@ -88,5 +88,5 @@
 my $logDest = $ipprc->filename("LOG.EXP", $outroot, $skycell_id) or my_die( "Unable to get log filename", $warp_bg_id, $skycell_id, $PS_EXIT_SYS_ERROR );
 
-$ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $warp_bg_id, $skycell_id, $PS_EXIT_SYS_ERROR ) if $redirect;
+$ipprc->redirect_to_logfile($logDest) or my_die( "Unable to redirect output", $warp_bg_id, $skycell_id, $PS_EXIT_SYS_ERROR ) if $redirect;
 
 # Recipes to use based on reduction class
@@ -158,11 +158,18 @@
 &my_die("Can't find input astrometry: $astrometry", $warp_bg_id, $skycell_id, $PS_EXIT_PROG_ERROR) unless $ipprc->file_exists($astrometry);
 
-my $out_image = $ipprc->filename("PSWARP.OUTPUT", $outroot, $skycell_id );
-my $out_mask = $ipprc->filename("PSWARP.OUTPUT.MASK", $outroot, $skycell_id);
-my $out_stats = $ipprc->filename("SKYCELL.STATS", $outroot, $skycell_id );
-my $out_config = $ipprc->filename("PSWARP.CONFIG", $outroot, $skycell_id);
-my $traceDest = $ipprc->filename("TRACE.EXP", $outroot, $skycell_id);
-
-my $skyFile = $ipprc->filename("SKYCELL.TEMPLATE", $outroot, $skycell_id );
+#my $out_image = $ipprc->filename("PSWARP.OUTPUT", $outroot, $skycell_id );
+#my $out_mask = $ipprc->filename("PSWARP.OUTPUT.MASK", $outroot, $skycell_id);
+#my $out_stats = $ipprc->filename("SKYCELL.STATS", $outroot, $skycell_id );
+#my $out_config = $ipprc->filename("PSWARP.CONFIG", $outroot, $skycell_id);
+#my $traceDest = $ipprc->filename("TRACE.EXP", $outroot, $skycell_id);
+
+my $out_image = prepare_output("PSWARP.OUTPUT", $outroot, $skycell_id,  1);
+my $out_mask = prepare_output("PSWARP.OUTPUT.MASK", $outroot, $skycell_id, 1);
+my $out_stats = prepare_output("SKYCELL.STATS", $outroot, $skycell_id, 1);
+my $out_config = prepare_output("PSWARP.CONFIG", $outroot, $skycell_id, 1);
+my $traceDest = prepare_output("TRACE.EXP", $outroot, $skycell_id, 1);
+
+my $skyFile = prepare_output("SKYCELL.TEMPLATE", $outroot, $skycell_id, 1);
+
 $ipprc->skycell_file( $tess_dir, $skycell_id, $skyFile, $verbose ) or &my_die("Unable to generate template skycell", $warp_bg_id, $skycell_id, $PS_EXIT_SYS_ERROR);
 
@@ -239,4 +246,18 @@
 ### Pau.
 
+sub prepare_output
+{
+    my $filerule = shift;
+    my $outroot  = shift;
+    my $skycell_id = shift;
+    my $delete = shift;
+    $delete = 0 if !defined $delete;
+
+    my $error;
+    my $output = $ipprc->prepare_output($filerule, $outroot, $skycell_id, $delete, \$error)
+                    or &my_die("failed to prepare output file for: $filerule", $warp_bg_id, $skycell_id, $error);
+    return $output;
+}
+
 
 sub my_die
Index: branches/czw_branch/20120906/ippScripts/scripts/destreak_restore_camera.pl
===================================================================
--- branches/czw_branch/20120906/ippScripts/scripts/destreak_restore_camera.pl	(revision 34756)
+++ branches/czw_branch/20120906/ippScripts/scripts/destreak_restore_camera.pl	(revision 34772)
@@ -440,6 +440,6 @@
     }
 
+    my $backup_url = shift;
     my $original_url = shift;
-    my $backup_url = shift;
 
     # rename the backup as the orig
@@ -449,5 +449,5 @@
     my $moved;
     eval {
-        $moved = nebulous->move($backup_url, $original_url);
+        $moved = $nebulous->move($backup_url, $original_url);
     };
     if ($@ or not $moved) {
Index: branches/czw_branch/20120906/ippScripts/scripts/detrend_process_imfile.pl
===================================================================
--- branches/czw_branch/20120906/ippScripts/scripts/detrend_process_imfile.pl	(revision 34756)
+++ branches/czw_branch/20120906/ippScripts/scripts/detrend_process_imfile.pl	(revision 34772)
@@ -27,4 +27,6 @@
 my $ppImage = can_run('ppImage') or (warn "Can't find ppImage" and $missing_tools = 1);
 my $ppStatsFromMetadata = can_run('ppStatsFromMetadata') or (warn "Can't find ppStatsFromMetadata" and $missing_tools = 1);
+my $nebrepair = can_run('neb-repair') or (warn "Can't find neb-repair" and $missing_tools = 1);
+
 if ($missing_tools) {
     warn("Can't find required tools.");
@@ -124,4 +126,11 @@
 # Run ppImage
 unless ($no_op) {
+    my $repair_cmd = "$nebrepair $input_uri";
+    my ($repair_success, $repair_error_code, $repair_full_buf, $repair_stdout_buf, $repair_stderr_buf ) = run(command => $repair_cmd, verbose => $verbose);
+    unless ($repair_success) {
+	&my_die("Unable to attempt repair: $input_uri $repair_error_code", $det_id, $exp_id, $class_id $PS_EXIT_SYS_ERROR);
+    }
+
+
     my $command = "$ppImage -file $input_uri $outroot";
     $command .= " -recipe PPIMAGE $ppimage_recipe";
Index: branches/czw_branch/20120906/ippScripts/scripts/lap_science.pl
===================================================================
--- branches/czw_branch/20120906/ippScripts/scripts/lap_science.pl	(revision 34756)
+++ branches/czw_branch/20120906/ippScripts/scripts/lap_science.pl	(revision 34772)
@@ -671,4 +671,21 @@
 # 	}
 	# Do quality checks here
+	if ($verbose) {
+	    printf("TEST: %d %d %d\n",$exposure->{exp_id},$exposure->{chip_id},$exposure->{chip_component_count});
+	}
+	# Checks to ensure we do not divide by zero.  Mostly happens with old diffs, it seems.
+	if ($exposure->{chip_component_count} == 0) {
+	    $exposure->{chip_component_count} = 1;
+	}
+	if ($exposure->{cam_component_count} == 0) {
+	    $exposure->{cam_component_count} = 1;
+	}
+	if ($exposure->{warp_component_count} == 0) {
+	    $exposure->{warp_component_count} = 1;
+	}
+	if ($exposure->{diff_component_count} == 0) {
+	    $exposure->{diff_component_count} = 1;
+	}
+
 	my $is_bad_quality = 0;
 	if ((defined($exposure->{chipRun_state}))&&($exposure->{chipRun_state} eq 'full')&&
Index: branches/czw_branch/20120906/ippScripts/scripts/publish_file.pl
===================================================================
--- branches/czw_branch/20120906/ippScripts/scripts/publish_file.pl	(revision 34756)
+++ branches/czw_branch/20120906/ippScripts/scripts/publish_file.pl	(revision 34772)
@@ -32,4 +32,5 @@
 my $pubtool = can_run('pubtool') or (warn "Can't find pubtool" and $missing_tools = 1);
 my $camtool = can_run('camtool') or (warn "Can't find camtool" and $missing_tools = 1);
+my $regtool = can_run('regtool') or (warn "Can't find regtool" and $missing_tools = 1);
 my $difftool = can_run('difftool') or (warn "Can't find difftool" and $missing_tools = 1);
 my $ppMops = can_run('ppMops') or (warn "Can't find ppMops" and $missing_tools = 1);
@@ -44,5 +45,5 @@
 my ( $pub_id, $camera, $stage, $stage_id, $fileset, $format, $product, $workdir, $need_magic );
 my ( $dbname, $verbose, $no_update, $no_op, $save_temps, $redirect );
-my ( $output_format );
+my ( $output_format, $difftype );
 
 GetOptions(
@@ -72,5 +73,6 @@
     defined $stage and
     defined $stage_id and
-    defined $workdir;
+    defined $workdir and
+    defined $dbname;
 
 my $outroot = "$workdir/$product.$pub_id"; # Output root name
@@ -166,5 +168,5 @@
     my %negative;               # Data for negative diff detections
     foreach my $comp ( @$components ) {
-        my $path_base = $comp->{path_base}; # Base name for file
+	my $path_base = $comp->{path_base}; # Base name for file
         if (!$need_magic and $comp->{magicked}) {
             # This client is authorized to receive uncensored detections
@@ -194,4 +196,45 @@
 
         $filename = $resolved;
+
+	my $cam_id = $comp->{cam_id_1};
+	#print "Getting info from camera stage $cam_id\n";
+	my $cam_command =  "$camtool -processedexp -cam_id $cam_id";
+	$cam_command .= " -dbname $dbname" if defined $dbname;
+	my ( $cam_success, $cam_error_code, $cam_full_buf, $cam_stdout_buf, $cam_stderr_buf ) =
+	    run(command => $cam_command, verbose => $verbose);
+	&my_die( "Unable to retrieve filename", $pub_id, $PS_EXIT_SYS_ERROR) unless $cam_success;
+	my $cam_metadata = $mdcParser->parse(join "", @$cam_stdout_buf) or
+	    &my_die("Unable to parse metadata config", $pub_id, $PS_EXIT_PROG_ERROR);
+	my $cam_components = parse_md_list($cam_metadata) or
+	    &my_die("Unable to parse metadata list", $pub_id, $PS_EXIT_PROG_ERROR);
+	&my_die("More than one entry for cam_id $stage_id", $pub_id, $PS_EXIT_PROG_ERROR) if scalar @$cam_components > 1;
+	my $cam_comp = $$cam_components[0];
+
+	my $exp_id = $comp->{exp_id_1};
+	#print "Getting info from raw stage $exp_id\n";
+	my $reg_command =  "$regtool -processedimfile -exp_id $exp_id";
+	$reg_command .= " -dbname $dbname" if defined $dbname;
+	my ( $reg_success, $reg_error_code, $reg_full_buf, $reg_stdout_buf, $reg_stderr_buf ) =
+	    run(command => $reg_command, verbose => $verbose);
+	&my_die( "Unable to retrieve filename", $pub_id, $PS_EXIT_SYS_ERROR) unless $reg_success;
+	my $reg_metadata = $mdcParser->parse(join "", @$reg_stdout_buf) or
+	    &my_die("Unable to parse metadata config", $pub_id, $PS_EXIT_PROG_ERROR);
+	my $reg_components = parse_md_list($reg_metadata) or
+	    &my_die("Unable to parse metadata list", $pub_id, $PS_EXIT_PROG_ERROR);
+	my $reg_comp = $$reg_components[0];
+
+	# Now get the difftype value from diff->{diff_mode}
+	my $difftype = "";
+	if ($comp->{diff_mode} == 1) {
+	    $difftype = "WW";
+	} elsif ($comp->{diff_mode} == 2) {
+	    $difftype = "WS";
+	} elsif ($comp->{diff_mode} == 3) {
+	    $difftype = "SW"; # Not used yet
+	} elsif ($comp->{diff_mode} == 4) {
+	    $difftype = "SS";
+	} else {
+	    $difftype = "Unsupported diff_mode value: [" . $comp->{diff_mode} . "]";
+	}
 
         my $data = { zp => $zp,
@@ -207,6 +250,12 @@
                      output_format => $comp->{output_format},
                      direction => 1,
+		     comment => $reg_comp->{comment},
+		     obsmode => $reg_comp->{obs_mode},
+		     difftype => $difftype,
+		     sky => $cam_comp->{bg},
+		     shutoutc => $reg_comp->{dateobs},
         };
 
+	#warn("Checking for positive");
         diff_check(\%positive, $data, "positive");
 
@@ -239,6 +288,12 @@
                          diff_id => $comp->{diff_id},
                          direction => 0,
+			 comment => $reg_comp->{comment},
+			 obsmode => $reg_comp->{obs_mode},
+			 difftype => $difftype,
+			 sky => $cam_comp->{bg},
+			 shutoutc => $reg_comp->{dateobs},
             };
 
+	    #warn("Checking for negative");
             diff_check(\%negative, $data, "negative");
 
@@ -288,6 +343,4 @@
     &my_die( "Unable to register with data store", $pub_id, $PS_EXIT_SYS_ERROR) unless $success;
 }
-
-
 
 ### Pau.
@@ -311,4 +364,9 @@
     $data->{diff_id} = $comp->{diff_id} unless defined $data->{diff_id};
     $data->{direction} = $comp->{direction} unless defined $data->{direction};
+    $data->{comment} = $comp->{comment} unless defined $data->{comment};
+    $data->{obsmode} = $comp->{obsmode} unless defined $data->{obsmode};
+    $data->{difftype} = $comp->{difftype} unless defined $data->{difftype};
+    $data->{sky} = $comp->{sky} unless defined $data->{sky};
+    $data->{shutoutc} = $comp->{shutoutc} unless defined $data->{shutoutc};
 
     &my_die("zp value for $name doesn't match", $pub_id, $PS_EXIT_SYS_ERROR) if defined $data->{zp} and $comp->{zp} != $data->{zp};
@@ -323,4 +381,9 @@
     &my_die("diff_id value for $name doesn't match", $pub_id, $PS_EXIT_SYS_ERROR) if defined $data->{diff_id} and $comp->{diff_id} != $data->{diff_id};
     &my_die("direction value for $name doesn't match", $pub_id, $PS_EXIT_SYS_ERROR) if defined $data->{direction} and $comp->{direction} != $data->{direction};
+    &my_die("comment value for $name doesn't match", $pub_id, $PS_EXIT_SYS_ERROR) if defined $data->{comment} and $comp->{comment} ne $data->{comment};
+    &my_die("obsmode value for $name doesn't match", $pub_id, $PS_EXIT_SYS_ERROR) if defined $data->{obsmode} and $comp->{obsmode} ne $data->{obsmode};
+    &my_die("difftype value for $name doesn't match", $pub_id, $PS_EXIT_SYS_ERROR) if defined $data->{difftype} and $comp->{difftype} ne $data->{difftype};
+    &my_die("sky value for $name doesn't match", $pub_id, $PS_EXIT_SYS_ERROR) if defined $data->{sky} and $comp->{sky} != $data->{sky};
+    &my_die("shutoutc value for $name doesn't match", $pub_id, $PS_EXIT_SYS_ERROR) if defined $data->{shutoutc} and $comp->{shutoutc} ne $data->{shutoutc};
 
     return 1;
@@ -350,4 +413,9 @@
     $command .= " -astrom_rms " . $data->{astrom} if defined $data->{astrom};
     $command .= " -version " . $data->{output_format} if defined $data->{output_format};
+    $command .= " -comment \"" . $data->{comment} . "\"" if defined $data->{comment};
+    $command .= " -obsmode " . $data->{obsmode} if defined $data->{obsmode};
+    $command .= " -difftype " . $data->{difftype} if defined $data->{difftype};
+    $command .= " -sky " . $data->{sky} if defined $data->{sky};
+    $command .= " -shutoutc \"" . $data->{shutoutc} . "\"" if defined $data->{shutoutc};
 
     unless ($no_op) {
Index: branches/czw_branch/20120906/ippScripts/scripts/regenerate_background.pl
===================================================================
--- branches/czw_branch/20120906/ippScripts/scripts/regenerate_background.pl	(revision 34756)
+++ branches/czw_branch/20120906/ippScripts/scripts/regenerate_background.pl	(revision 34772)
@@ -10,7 +10,12 @@
 use IPC::Cmd 0.36 qw( can_run run );
 use File::Spec;
+use File::Temp qw( tempfile );
 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 );
+use PS::IPP::Metadata::Config;
+use PS::IPP::Metadata::List qw( parse_md_list );
+
+
 
 my $ppConfigDump = can_run('ppConfigDump');
@@ -67,5 +72,5 @@
     my $astromSource;               # The astrometry source
     {
-	my $command = "$ppConfigDump -camera $camera -recipe PSWARP DEFAULT -dump-recipe PSWARP -";
+	my $command = "$ppConfigDump -camera $camera -recipe PSWARP BACKGROUND -dump-recipe PSWARP -";
 	my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
 	    run(command => $command, verbose => $verbose);
@@ -97,5 +102,5 @@
     }
 
-    my $in_md = $mdcParser->parse_list(join "", @$stdout_buf) or
+    my $in_md = $mdcParser->parse(join "", @$stdout_buf) or
 	&my_die("Unable to parse metadata config doc", $stage, $stage_id, $PS_EXIT_PROG_ERROR);
     $imfiles  = parse_md_list($in_md) or
@@ -165,9 +170,10 @@
 		&my_die("Unable to generate template skycell",$skycell_id,$warp_id,$PS_EXIT_SYS_ERROR);
 	}
-
+	my $bkgOut_log = prepare_output("LOG.EXP",$path_base . ".BKG_REG",$skycell_id,1);
 
 	# Construct pswarp command
 	my $pswarp_command = "$pswarp ";
 	$pswarp_command .= " -list $bkgList_name -astromlist $astromList_name -bkglist $bkgList_name ";
+	$pswarp_command .= " ${path_base} ";
 	$pswarp_command .= " $skyCell_name ";
 	$pswarp_command .= " -F PSPHOT.PSF.SAVE PSPHOT.PSF.SKY.SAVE -F PSPHOT.OUTPUT PSPHOT.OUT.CMF.MEF ";
@@ -186,4 +192,16 @@
 	unless ($success) {
 	    $error_code = (($error_code >> 8)  or $PS_EXIT_PROG_ERROR);
+	    &my_die("Unable to perform pswarp: $error_code", $stage, $stage_id, $error_code);
+	}
+	
+	my $update_command = "$warptool ";
+	$update_command .= " -updateskyfile -warp_id $warp_id -skycell_id $skycell_id ";
+	$update_command .= " -set_background_model 1 ";
+	$update_command .= " -dbname $dbname " if defined $dbname;
+
+	( $success, $error_code, $full_buf, $stdout_buf, $stderrr_buf ) = 
+	    run(command => $update_command, verbose => $verbose);
+	unless ($success) {
+	    $error_code = (($error_code >> 8)  or $PS_EXIT_PROG_ERROR);
 	    &my_die("Unable to perform warptool: $error_code", $stage, $stage_id, $error_code);
 	}
@@ -223,5 +241,7 @@
     
     my $num = 0;
-    
+    my $path_base = '/tmp/x';
+    my $expTime   = 60;
+
     my ($inputMDC_file, $inputMDC_name) = tempfile("/tmp/bkgreg.stack.mdc.${stage_id}.XXXX",
 						   UNLINK => !$save_temps);
@@ -242,5 +262,7 @@
     }
     close($inputMDC_file);
-    
+
+    my $bkgOut_log = prepare_output("LOG.IMFILE",$path_base . "BKG_REG",$skycell_id,1);    
+
     my $ppStack_command = "$ppStackMedian -input $inputMDC_name $path_base ";
     $ppStack_command   .= " -recipe PPSTACK STACK -recipe PPSUB STACK -recipe PSPHOT STACK ";
@@ -253,5 +275,5 @@
     $ppStack_command   .= " -Db PHOTOMETRY F -Db VARIANCE F -Db CONVOLVE F ";
     $ppStack_command   .= " -Df DEFAULT.EXPTIME $expTime ";
-    $ppStack_command   .= " -threads $threads -log $bkgOut_log ";
+    $ppStack_command   .= " -threads 1 -log $bkgOut_log ";
     $ppStack_command   .= " -dbname $dbname " if defined $dbname;
 
Index: branches/czw_branch/20120906/ippScripts/scripts/skycalibration.pl
===================================================================
--- branches/czw_branch/20120906/ippScripts/scripts/skycalibration.pl	(revision 34756)
+++ branches/czw_branch/20120906/ippScripts/scripts/skycalibration.pl	(revision 34772)
@@ -33,4 +33,5 @@
 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);
@@ -191,4 +192,33 @@
 }
 
+my $resolved = $ipprc->file_resolve($file);
+if (!$resolved) {
+    &my_die("Unable to find input file: $file", $skycal_id, $PS_EXIT_SYS_ERROR);
+}
+
+# read the input header to find the number of detections and the number of detections
+# with extended model
+my $n_detections = 0;
+my $n_extended = 0;
+{
+    my $command = "echo $resolved | $fields -n SkyChip.psf NAXIS2";
+    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
+            run(command => $command, verbose => 0);
+        # fields does not return 0 on success
+    (undef, $n_detections)  = split " ", join "", @$stdout_buf;
+    chomp $n_detections;
+    &my_die("Unable to find number of detections from $file: ", $skycal_id, $PS_EXIT_SYS_ERROR)
+        unless defined $n_detections;
+
+    $command = "echo $resolved | $fields -n SkyChip.hdr NDET_EXT";
+    ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
+            run(command => $command, verbose => 0);
+    (undef, $n_extended)  = split " ", join "", @$stdout_buf;
+    chomp $n_extended;
+    &my_die("Unable to find number of extended objects from $file: ", $skycal_id, $PS_EXIT_SYS_ERROR)
+        unless defined $n_extended;
+}
+
+
 # Perform psastro analysis
 my $output_sources_filerule =  'PSASTRO.OUTPUT.CMF';
@@ -246,4 +276,6 @@
 {
     my $command = "$staticskytool -skycal_id $skycal_id";
+    $command .= " -n_detections $n_detections";
+    $command .= " -n_extended $n_extended";
     $command .= " -addskycalresult -path_base $outroot";
     $command .= " $cmdflags";
Index: branches/czw_branch/20120906/ippScripts/scripts/staticsky.pl
===================================================================
--- branches/czw_branch/20120906/ippScripts/scripts/staticsky.pl	(revision 34756)
+++ branches/czw_branch/20120906/ippScripts/scripts/staticsky.pl	(revision 34772)
@@ -124,5 +124,5 @@
 my $nInputs = @$files;
 
-if ($nInputs > 1) {
+if (1) {
         my $recipe_psphot  = $ipprc->reduction($reduction, 'STACKPHOT_PSPHOT'); # Recipe to use for psphot
         my $recipe_ppsub   = $ipprc->reduction($reduction, 'STACKPHOT_PPSUB'); # Recipe to use for ppsub
@@ -266,4 +266,5 @@
         }
 } else {
+    # XXX This mode is no longer used. We run psphotStack even if there is only one filter
         # single input. Run psphot
         # find the recipe
@@ -302,9 +303,10 @@
             $mask   = $ipprc->filename("PPSTACK.UNCONV.MASK",     $path_base ); # Mask name
             $variance = $ipprc->filename("PPSTACK.UNCONV.VARIANCE", $path_base ); # Weight name
+            $expnum = $ipprc->filename("PPSTACK.OUTPUT.EXPNUM", $path_base ); # Expnum name
         } else {
             $image  = $ipprc->filename("PPSTACK.OUTPUT",          $path_base ); # Image name
             $mask   = $ipprc->filename("PPSTACK.OUTPUT.MASK",     $path_base ); # Mask name
             $variance = $ipprc->filename("PPSTACK.OUTPUT.VARIANCE", $path_base ); # Weight name
-            $expnum = $ipprc->filename("PPSTACK.OUTPUT.EXPNUM", $path_base ); # Weight name
+            $expnum = $ipprc->filename("PPSTACK.OUTPUT.EXPNUM", $path_base ); # Expnum name
         }
 
