Index: branches/czw_branch/20120906/ppStack/src/ppStack.h
===================================================================
--- branches/czw_branch/20120906/ppStack/src/ppStack.h	(revision 34410)
+++ branches/czw_branch/20120906/ppStack/src/ppStack.h	(revision 34516)
@@ -38,5 +38,6 @@
     PPSTACK_FILES_STACK,                // Stack files
     PPSTACK_FILES_UNCONV,               // Unconvolved stack files
-    PPSTACK_FILES_PHOT                  // Files for photometry
+    PPSTACK_FILES_PHOT,                 // Files for photometry
+    PPSTACK_FILES_BKG                   // Files for bkg
 } ppStackFileList;
 
@@ -111,4 +112,6 @@
 bool ppStackReadoutFinalThread(psThreadJob *job // Job to process
     );
+// Perform median stacking for background
+bool ppStackCombineBackground(ppStackThreadData *stack, ppStackOptions *options, pmConfig *config);
 
 // Return software version
Index: branches/czw_branch/20120906/ppStack/src/ppStackCamera.c
===================================================================
--- branches/czw_branch/20120906/ppStack/src/ppStackCamera.c	(revision 34410)
+++ branches/czw_branch/20120906/ppStack/src/ppStackCamera.c	(revision 34516)
@@ -156,5 +156,6 @@
             psString psf = psMetadataLookupStr(&mdok, input, "PSF"); // Name of PSF
             psString sources = psMetadataLookupStr(&mdok, input, "SOURCES"); // Name of sources
-
+	    psString bkgmodel = psMetadataLookupStr(&mdok, input, "BKGMODEL"); // Name of warped background model
+	    
             pmFPAfile *imageFile = defineFile(config, NULL, "PPSTACK.INPUT",
                                               image, PM_FPA_FILE_IMAGE); // File for image
@@ -215,4 +216,22 @@
             }
 
+	    // Grab bkgmodel information here
+	    if (!bkgmodel ||  strlen(bkgmodel) == 0) {
+	      // We have no background models.
+	    }
+	    else {
+	      pmFPAfile *inputBKG = defineFile(config,NULL,"PPSTACK.INPUT.BKGMODEL",bkgmodel,
+					       PM_FPA_FILE_IMAGE);
+	      fprintf(stderr,"ppSC: %s\n",bkgmodel);
+	      if (!inputBKG) {
+		psError(psErrorCodeLast(), false,
+			"Unable to define file from bkgmodel %d (%s)",i,bkgmodel);
+		return(false);
+	      }
+	    }// End bkgmodel
+
+
+	    
+	    
             i++;
         }
@@ -460,4 +479,25 @@
     jpeg2->save = true;
 
+    // Output background
+    pmFPAfile *outBkg = pmFPAfileDefineOutput(config,NULL,"PPSTACK.OUTPUT.BKGMODEL");
+    if (!outBkg) {
+      psError(psErrorCodeLast(), false, _("Unable to generate output file from PPSTACK.OUTPUT.BKGMODEL"));
+      return(false);
+    }
+    if (outBkg->type != PM_FPA_FILE_IMAGE) {
+      psError(PPSTACK_ERR_CONFIG, true, "PPSTACK.OUTPUT.BKGMODEL is not of type IMAGE");
+      return(false);
+    }
+    outBkg->save = true;
+    pmFPAfile *outBkgRest = pmFPAfileDefineOutput(config,NULL,"PPSTACK.OUTPUT.BKGREST");
+    if (!outBkgRest) {
+      psError(psErrorCodeLast(), false, _("Unable to generate output file from PPSTACK.OUTPUT.BKGREST"));
+      return(false);
+    }
+    if (outBkgRest->type != PM_FPA_FILE_IMAGE) {
+      psError(PPSTACK_ERR_CONFIG, true, "PPSTACK.OUTPUT.BKGREST is not of type IMAGE");
+      return(false);
+    }
+    
     // For photometry, we operate on the chip-mosaicked image
     // we create a copy of the mosaicked image for psphot so we can write out a clean image
@@ -496,4 +536,6 @@
     }
 
+    // Define output file here.
+    
     return true;
 }
Index: branches/czw_branch/20120906/ppStack/src/ppStackCleanup.c
===================================================================
--- branches/czw_branch/20120906/ppStack/src/ppStackCleanup.c	(revision 34410)
+++ branches/czw_branch/20120906/ppStack/src/ppStackCleanup.c	(revision 34516)
@@ -28,4 +28,10 @@
     options->expRO = NULL;
 
+    options->bkgRO->data_exists = false;
+    options->bkgRO->parent->data_exists = false;
+    options->bkgRO->parent->parent->data_exists = false;
+    psFree(options->bkgRO);
+    options->bkgRO = NULL;
+    
     for (int i = 0; i < options->num; i++) {
         pmCellFreeData(options->cells->data[i]);
Index: branches/czw_branch/20120906/ppStack/src/ppStackCombineFinal.c
===================================================================
--- branches/czw_branch/20120906/ppStack/src/ppStackCombineFinal.c	(revision 34410)
+++ branches/czw_branch/20120906/ppStack/src/ppStackCombineFinal.c	(revision 34516)
@@ -3,4 +3,46 @@
 // This is the doomsday switch.
 // #define TESTING                         // Enable test output
+bool ppStackCombineBackground(ppStackThreadData *stack, ppStackOptions *options, pmConfig *config)
+{
+  psAssert(stack, "Require stack");
+  psAssert(options, "Require options");
+  psAssert(config, "Require configuration");
+
+  psTimerStart("PPSTACK_BKGMED");
+
+
+  pmReadout *bkgRO = options->bkgRO;
+  
+  psArray *inputs  = psArrayAlloc(options->num);
+  //  const psArray *cells = options->cells;
+  for (int i = 0; i < options->num; i++) {
+    ppStackFileActivationSingle(config, PPSTACK_FILES_BKG, true, i);
+    pmFPAfile *file = pmFPAfileSelectSingle(config->files, "PPSTACK.INPUT.BKGMODEL", i);
+    pmFPAview *view = ppStackFilesIterateDown(config);
+    pmReadout *ro = pmFPAviewThisReadout(view,file->fpa);
+    inputs->data[i] = ro;
+    pmFPAfileClose(file,view);
+    ppStackFileActivationSingle(config, PPSTACK_FILES_BKG, false, i);
+  }
+  if (!pmStackSimpleMedianCombine(bkgRO,inputs)) {
+    psFree(inputs);
+    return(false);
+  }
+/*   for (int i = 0; i < options->num; i++) { */
+/*     //    ppStackFilesIterateUp(config); */
+/* /\*     pmFPAfile *file = pmFPAfileSelectSingle(config->files, "PPSTACK.INPUT.BKGMODEL", i); *\/ */
+/* /\*     pmFPAview *view = ppStackFilesIterateDown(config); *\/ */
+/*     pmFPAfile *file = pmFPAfileSelectSingle(config->files, "PPSTACK.INPUT.BKGMODEL", i); */
+    
+/*     ppStackFileActivationSingle(config, PPSTACK_FILES_BKG, false, i); */
+/*   }   */
+  psFree(inputs);
+  //  psFree(stack->bkgFits);
+  bkgRO->data_exists = true;
+  return(true);
+}
+  
+
+
 
 bool ppStackCombineFinal(ppStackThreadData *stack, psArray *covariances, ppStackOptions *options,
Index: branches/czw_branch/20120906/ppStack/src/ppStackCombinePrepare.c
===================================================================
--- branches/czw_branch/20120906/ppStack/src/ppStackCombinePrepare.c	(revision 34410)
+++ branches/czw_branch/20120906/ppStack/src/ppStackCombinePrepare.c	(revision 34516)
@@ -1,5 +1,5 @@
 #include "ppStack.h"
 
-bool ppStackCombinePrepare(const char *outName, const char *expName,
+bool ppStackCombinePrepare(const char *outName, const char *expName, const char *bkgName,
                            ppStackFileList files, ppStackThreadData *stack,
                            ppStackOptions *options, pmConfig *config)
@@ -26,7 +26,13 @@
     pmCell *cell = pmFPAfileThisCell(config->files, view, outName); // Output cell
     options->outRO = pmReadoutAlloc(cell); // Output readout
-
+    
     pmCell *expCell = pmFPAfileThisCell(config->files, view, expName); // Exposure cell
     options->expRO = pmReadoutAlloc(expCell); // Output readout
+
+    pmCell *bkgCell;
+    if (bkgName) {
+      bkgCell = pmFPAfileThisCell(config->files, view, bkgName); // Bkg cell
+      options->bkgRO = pmReadoutAlloc(bkgCell); // BKG readout
+    }
 
     psFree(view);
@@ -47,4 +53,11 @@
     }
 
+    if (bkgName) {
+      if (!pmReadoutStackDefineOutput(options->bkgRO, col0, row0, numCols, numRows, false, false, 0)) {
+        psError(PPSTACK_ERR_ARGUMENTS, false, "Unable to prepare output.");
+        return false;
+      }
+    }
+
     return true;
 }
Index: branches/czw_branch/20120906/ppStack/src/ppStackFiles.c
===================================================================
--- branches/czw_branch/20120906/ppStack/src/ppStackFiles.c	(revision 34410)
+++ branches/czw_branch/20120906/ppStack/src/ppStackFiles.c	(revision 34516)
@@ -14,4 +14,7 @@
 /// Files required for the convolution
 static char *filesConvolve[] = { "PPSTACK.INPUT", "PPSTACK.INPUT.MASK", "PPSTACK.INPUT.VARIANCE", NULL };
+
+/// Files required for the background
+static char *filesBkg[] = { "PPSTACK.INPUT.BKGMODEL", NULL };
 
 /// Regular (convolved) stack files
@@ -19,8 +22,10 @@
                               "PPSTACK.OUTPUT.EXP", "PPSTACK.OUTPUT.EXPNUM", "PPSTACK.OUTPUT.EXPWT",
                               "PPSTACK.OUTPUT.JPEG1", "PPSTACK.OUTPUT.JPEG2",
+			      "PPSTACK.OUTPUT.BKGMODEL",
                               NULL };
 /// Unconvolved stack files
 static char *filesUnconv[] = { "PPSTACK.UNCONV", "PPSTACK.UNCONV.MASK", "PPSTACK.UNCONV.VARIANCE",
                                "PPSTACK.UNCONV.EXP", "PPSTACK.UNCONV.EXPNUM", "PPSTACK.UNCONV.EXPWT",
+			       "PPSTACK.OUTPUT.BKGMODEL",
                                NULL };
 
@@ -41,4 +46,5 @@
       case PPSTACK_FILES_UNCONV:   return filesUnconv;
       case PPSTACK_FILES_PHOT:     return filesPhot;
+    case PPSTACK_FILES_BKG:        return filesBkg;
       default:
         psAbort("Unrecognised file list: %x", list);
@@ -86,4 +92,5 @@
     for (int i = 0; files[i] != NULL; i++) {
         pmFPAfileActivate(config->files, state, files[i]);
+	fprintf(stderr,"ACTIVE: %d %s %d\n",i,files[i],state);
     }
     return;
Index: branches/czw_branch/20120906/ppStack/src/ppStackLoop.c
===================================================================
--- branches/czw_branch/20120906/ppStack/src/ppStackLoop.c	(revision 34410)
+++ branches/czw_branch/20120906/ppStack/src/ppStackLoop.c	(revision 34516)
@@ -63,5 +63,5 @@
 
     // Prepare for combination
-    if (!ppStackCombinePrepare("PPSTACK.OUTPUT", "PPSTACK.OUTPUT.EXP", PPSTACK_FILES_STACK, stack, options, config)) {
+    if (!ppStackCombinePrepare("PPSTACK.OUTPUT", "PPSTACK.OUTPUT.EXP", "PPSTACK.OUTPUT.BKGMODEL", PPSTACK_FILES_STACK, stack, options, config)) {
         psError(psErrorCodeLast(), false, "Unable to prepare for combination.");
         psFree(stack);
@@ -84,5 +84,5 @@
         pmCellFreeData(options->cells->data[i]);
     }
-    psFree(stack);
+    //    psFree(stack);
 
     // Pixel rejection
@@ -142,4 +142,11 @@
     }
 
+    // Generate median background stack here.
+    if (!ppStackCombineBackground(stack, options, config)) {
+      psError(psErrorCodeLast(), false, "Unable to generate median of background images.");
+      psFree(stack);
+      return false;
+    }
+    ppStackFileActivation(config,PPSTACK_FILES_BKG ,false);    
     // Photometry
     psTrace("ppStack", 1, "Photometering stacked image....\n");
@@ -171,5 +178,5 @@
         return false;
     }
-    psFree(stack);
+    //    psFree(stack);
     psLogMsg("ppStack", PS_LOG_INFO, "Stage 7: Cleanup, WCS & JPEGS: %f sec", psTimerClear("PPSTACK_STEPS"));
     ppStackMemDump("cleanup");
@@ -186,5 +193,5 @@
 
         // Prepare for combination
-        if (!ppStackCombinePrepare("PPSTACK.UNCONV", "PPSTACK.UNCONV.EXP", PPSTACK_FILES_UNCONV,
+        if (!ppStackCombinePrepare("PPSTACK.UNCONV", "PPSTACK.UNCONV.EXP", "PPSTACK.OUTPUT.BKGMODEL", PPSTACK_FILES_UNCONV,
                                    stack, options, config)) {
             psError(psErrorCodeLast(), false, "Unable to prepare for combination.");
Index: branches/czw_branch/20120906/ppStack/src/ppStackLoop.h
===================================================================
--- branches/czw_branch/20120906/ppStack/src/ppStackLoop.h	(revision 34410)
+++ branches/czw_branch/20120906/ppStack/src/ppStackLoop.h	(revision 34516)
@@ -32,4 +32,5 @@
     const char *outName,                // Name of output file
     const char *expName,                // Name of exposure file
+    const char *bkgName,                // Name of background file
     ppStackFileList files,              // Files of interest
     ppStackThreadData *stack,           // Stack
Index: branches/czw_branch/20120906/ppStack/src/ppStackOptions.h
===================================================================
--- branches/czw_branch/20120906/ppStack/src/ppStackOptions.h	(revision 34410)
+++ branches/czw_branch/20120906/ppStack/src/ppStackOptions.h	(revision 34516)
@@ -48,4 +48,7 @@
     // Rejection
     psArray *rejected;                  // Rejected pixels
+    // Background
+    pmReadout *bkgRO;                   // Output background readout
+    psArray   *bkgImages;               // Input background images
 } ppStackOptions;
 
Index: branches/czw_branch/20120906/ppStack/src/ppStackReadout.c
===================================================================
--- branches/czw_branch/20120906/ppStack/src/ppStackReadout.c	(revision 34410)
+++ branches/czw_branch/20120906/ppStack/src/ppStackReadout.c	(revision 34516)
@@ -194,5 +194,4 @@
 
 
-
 bool ppStackReadoutFinal(const pmConfig *config, pmReadout *outRO, pmReadout *expRO, const psArray *readouts,
                          const psVector *mask, const psArray *rejected, const psVector *weightings,
Index: branches/czw_branch/20120906/ppStack/src/ppStackSetup.c
===================================================================
--- branches/czw_branch/20120906/ppStack/src/ppStackSetup.c	(revision 34410)
+++ branches/czw_branch/20120906/ppStack/src/ppStackSetup.c	(revision 34516)
@@ -89,4 +89,5 @@
     options->origMasks = psArrayAlloc(num);
     options->origVariances = psArrayAlloc(num);
+    options->bkgImages = psArrayAlloc(num);
     pmFPAview *view = pmFPAviewAlloc(0);
     for (int i = 0; i < num; i++) {
@@ -103,4 +104,8 @@
             options->origVariances->data[i] = pmFPAfileName(file, view, config);
         }
+/* 	{ */
+/* 	  pmFPAfile *file = pmFPAfileSelectSingle(config->files, "PPSTACK.INPUT.BKGMODEL", i); */
+/* 	  options->bkgImages->data[i] = pmFPAfileName(file, view, config); */
+/* 	} */
     }
     psFree(view);
Index: branches/czw_branch/20120906/ppStack/src/ppStackThread.c
===================================================================
--- branches/czw_branch/20120906/ppStack/src/ppStackThread.c	(revision 34410)
+++ branches/czw_branch/20120906/ppStack/src/ppStackThread.c	(revision 34516)
@@ -35,4 +35,7 @@
             psFitsClose(stack->varianceFits->data[i]);
         }
+/*         if (stack->bkgFits->data[i]) { */
+/*             psFitsClose(stack->bkgFits->data[i]); */
+/*         } */
         stack->imageFits->data[i] = stack->maskFits->data[i] = stack->varianceFits->data[i] = NULL;
     }
@@ -40,4 +43,5 @@
     psFree(stack->maskFits);
     psFree(stack->varianceFits);
+    psFree(stack->bkgFits);
     return;
 }
@@ -53,5 +57,5 @@
     const psArray *varianceNames = conv ? options->convVariances : options->origVariances; // Variance names
     const psArray *covariances = conv ? options->convCovars : options->origCovars; // Covariance matrices
-
+    const psArray *bkgNames = options->bkgImages;
     PS_ASSERT_ARRAY_NON_NULL(cells, NULL);
     if (imageNames) {
@@ -77,4 +81,5 @@
     stack->maskFits   = psArrayAlloc(numInputs);
     stack->varianceFits = psArrayAlloc(numInputs);
+    stack->bkgFits    = psArrayAlloc(numInputs);
     for (int i = 0; i < numInputs; i++) {
         if (!cells->data[i]) {
@@ -95,8 +100,9 @@
             psFree(resolved); \
         }
-
+	fprintf(stderr,"%d %s\n",i,(char*) bkgNames->data[i]);
         IMAGE_OPEN(imageNames, stack->imageFits, i);
         IMAGE_OPEN(maskNames, stack->maskFits, i);
         IMAGE_OPEN(varianceNames, stack->varianceFits, i);
+	//	IMAGE_OPEN(bkgNames, stack->bkgFits, i);
     }
 
Index: branches/czw_branch/20120906/ppStack/src/ppStackThread.h
===================================================================
--- branches/czw_branch/20120906/ppStack/src/ppStackThread.h	(revision 34410)
+++ branches/czw_branch/20120906/ppStack/src/ppStackThread.h	(revision 34516)
@@ -25,4 +25,5 @@
     psArray *maskFits;                  // FITS file pointers for masks
     psArray *varianceFits;              // FITS file pointers for variances
+    psArray *bkgFits;                   // FITS file pointers for background models
 } ppStackThreadData;
 
