Index: branches/tap_branches/ppStack/src/ppStackCleanup.c
===================================================================
--- branches/tap_branches/ppStack/src/ppStackCleanup.c	(revision 25900)
+++ branches/tap_branches/ppStack/src/ppStackCleanup.c	(revision 27838)
@@ -4,12 +4,10 @@
 
 #include <stdio.h>
-#include <unistd.h>
 #include <pslib.h>
 #include <psmodules.h>
+#include <ppStats.h>
 
 #include "ppStack.h"
 #include "ppStackLoop.h"
-
-#define WCS_TOLERANCE 0.001             // Tolerance for WCS
 
 
@@ -22,7 +20,4 @@
     psMetadata *recipe = psMetadataLookupMetadata(NULL, config->recipes, PPSTACK_RECIPE); // ppStack recipe
     psAssert(recipe, "We've thrown an error on this before.");
-
-    bool mdok;                          // Status of MD lookup
-    bool tempDelete = psMetadataLookupBool(&mdok, recipe, "TEMP.DELETE"); // Delete temporary files?
 
 #if 0
@@ -37,59 +32,4 @@
 #endif
 
-    // Close up
-    bool wcsDone = false;           // Have we done the WCS?
-    for (int i = 0; i < options->num; i++) {
-        if (options->inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i]) {
-            continue;
-        }
-
-        ppStackThread *thread = stack->threads->data[0]; // Representative stack
-        pmReadout *inRO = thread->readouts->data[i]; // Template readout
-        if (inRO && !wcsDone) {
-            // Copy astrometry over
-            wcsDone = true;
-            pmHDU *inHDU = pmHDUFromCell(inRO->parent); // Template HDU
-            pmHDU *outHDU = pmHDUFromCell(options->outRO->parent); // Output HDU
-            pmChip *outChip = options->outRO->parent->parent; // Output chip
-            pmFPA *outFPA = outChip->parent; // Output FPA
-            if (!outHDU || !inHDU) {
-                psWarning("Unable to find HDU at FPA level to copy astrometry.");
-            } else {
-                if (!pmAstromReadWCS(outFPA, outChip, inHDU->header, 1.0)) {
-                    psErrorClear();
-                    psWarning("Unable to read WCS astrometry from input FPA.");
-                    wcsDone = false;
-                } else {
-                    if (!outHDU->header) {
-                        outHDU->header = psMetadataAlloc();
-                    }
-                    if (!pmAstromWriteWCS(outHDU->header, outFPA, outChip, WCS_TOLERANCE)) {
-                        psErrorClear();
-                        psWarning("Unable to write WCS astrometry to output FPA.");
-                        wcsDone = false;
-                    }
-                }
-            }
-        }
-
-        if (tempDelete) {
-            psString imageResolved = pmConfigConvertFilename(options->imageNames->data[i],
-                                                             config, false, false);
-            psString maskResolved = pmConfigConvertFilename(options->maskNames->data[i],
-                                                            config, false, false);
-            psString varianceResolved = pmConfigConvertFilename(options->varianceNames->data[i],
-                                                                config, false, false);
-            if (unlink(imageResolved) == -1 || unlink(maskResolved) == -1 ||
-                unlink(varianceResolved) == -1) {
-                psWarning("Unable to delete temporary files for image %d", i);
-            }
-            psFree(imageResolved);
-            psFree(maskResolved);
-            psFree(varianceResolved);
-        }
-    }
-
-    ppStackMemDump("cleanup");
-
     // Generate binned JPEGs
     {
@@ -103,9 +43,10 @@
         pmCell *cell2 = pmFPAfileThisCell(config->files, view, "PPSTACK.OUTPUT.JPEG2");
         psImageMaskType maskValue = pmConfigMaskGet("BLANK", config); // Bits to mask
+        psFree(view);
 
         pmReadout *ro1 = pmReadoutAlloc(cell1), *ro2 = pmReadoutAlloc(cell2); // Binned readouts
         if (!pmReadoutRebin(ro1, options->outRO, maskValue, bin1, bin1) ||
             !pmReadoutRebin(ro2, ro1, 0, bin2, bin2)) {
-            psError(PS_ERR_UNKNOWN, false, "Unable to bin output.");
+            psError(PPSTACK_ERR_DATA, false, "Unable to bin output.");
             psFree(ro1);
             psFree(ro2);
@@ -116,14 +57,62 @@
     }
 
-    // Put version information into the header
-    pmHDU *hdu = pmHDUFromCell(options->outRO->parent);
-    if (!hdu) {
-        psError(PS_ERR_UNKNOWN, false, "Unable to find HDU for output.");
+    // Statistics on output
+    if (options->stats) {
+        psTrace("ppStack", 1, "Gathering statistics on stacked image....\n");
+        psString maskBadStr = psMetadataLookupStr(NULL, recipe, "MASK.BAD"); // Name of bits for bad
+        psImageMaskType maskBad = pmConfigMaskGet(maskBadStr, config); // Bits to mask for bad pixels
+
+        pmFPAview *view = pmFPAviewAlloc(0); // View to readout
+        view->chip = view->cell = view->readout = 0;
+
+        ppStatsFPA(options->stats, options->outRO->parent->parent->parent, view, maskBad, config);
+
+        psFree(view);
+    }
+
+    if (!ppStackFilesIterateUp(config)) {
+        psError(psErrorCodeLast(), false, "Unable to close files.");
         return false;
     }
-    if (!hdu->header) {
-        hdu->header = psMetadataAlloc();
+    ppStackFileActivation(config, PPSTACK_FILES_STACK, false);
+    ppStackFileActivation(config, PPSTACK_FILES_PHOT, false);
+
+    // Ensure files are freed
+    {
+        options->outRO->data_exists = false;
+        options->outRO->parent->data_exists = false;
+        options->outRO->parent->parent->data_exists = false;
+        psFree(options->outRO);
+        options->outRO = NULL;
+
+        options->expRO->data_exists = false;
+        options->expRO->parent->data_exists = false;
+        options->expRO->parent->parent->data_exists = false;
+        psFree(options->expRO);
+        options->expRO = NULL;
+
+        pmFPAview *view = pmFPAviewAlloc(0);// Pointer into FPA hierarchy
+        view->chip = view->cell = 0;        // pmFPAviewFreeData doesn't want to deal with readouts
+        pmFPAfile *jpeg1 = pmFPAfileSelectSingle(config->files, "PPSTACK.OUTPUT.JPEG1", 0); // JPEG file
+        pmFPAviewFreeData(view, jpeg1);
+        pmFPAfile *jpeg2 = pmFPAfileSelectSingle(config->files, "PPSTACK.OUTPUT.JPEG2", 0); // JPEG file
+        pmFPAviewFreeData(view, jpeg2);
+        pmFPAfile *phot = NULL;         // Photometry file
+        if (options->photometry) {
+            phot = pmFPAfileSelectSingle(config->files, "PSPHOT.INPUT", 0); // Photometry file
+            pmFPAviewFreeData(view, phot);
+        }
+
+        view->readout = 0;
+        pmReadout *ro1 = pmFPAviewThisReadout(view, jpeg1->fpa); // JPEG readout
+        ro1->data_exists = ro1->parent->data_exists = ro1->parent->parent->data_exists = false;
+        pmReadout *ro2 = pmFPAviewThisReadout(view, jpeg2->fpa); // JPEG readout
+        ro2->data_exists = ro2->parent->data_exists = ro2->parent->parent->data_exists = false;
+        if (options->photometry) {
+            pmReadout *ro = pmFPAviewThisReadout(view, phot->fpa); // Photometry readout
+            ro->data_exists = ro->parent->data_exists = ro->parent->parent->data_exists = false;
+        }
+        psFree(view);
     }
-    ppStackVersionHeader(hdu->header);
 
     return true;
