Index: /trunk/psLib/src/fits/psFitsScale.c
===================================================================
--- /trunk/psLib/src/fits/psFitsScale.c	(revision 27248)
+++ /trunk/psLib/src/fits/psFitsScale.c	(revision 27249)
@@ -122,9 +122,34 @@
     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS);
     psStats *stats = psStatsAlloc(MEAN_STAT | STDEV_STAT); // Statistics object
-    psVector *sample = NULL;                               // Sample of pixels
     double mean, stdev;                                    // Mean and standard deviation
-    if (!psImageBackground(stats, &sample, image, mask, maskVal, rng)) {
+    if (!psImageBackground(stats, NULL, image, mask, maskVal, rng)) {
         // It could be because the image is entirely masked, in which case we don't want to error
-        if (sample->n == 0) {
+        bool good = false;              // Any good pixels?
+
+
+// Find good pixels in an image, by image type
+#define GOOD_PIXELS_CASE(TYPE) \
+      case PS_TYPE_##TYPE: \
+        for (int y = 0; y < image->numRows && !good; y++) { \
+            for (int x = 0; x < image->numCols && !good; x++) { \
+                if (mask && (mask->data.PS_TYPE_IMAGE_MASK_DATA[y][x] & maskVal)) { \
+                    continue; \
+                } \
+                if (!isfinite(image->data.TYPE[y][x])) { \
+                    continue; \
+                } \
+                good = true; \
+            } \
+        } \
+        break;
+
+        switch (image->type.type) {
+            GOOD_PIXELS_CASE(F32);
+            GOOD_PIXELS_CASE(F64);
+          default:
+            psAbort("Unsupported case: %x", image->type.type);
+        }
+
+        if (!good) {
             psLogMsg("psLib.fits", PS_LOG_DETAIL, "Image has no good pixels, setting BSCALE = 1, BZERO = 0");
             psErrorClear();
@@ -133,7 +158,8 @@
             psFree(rng);
             psFree(stats);
-            psFree(sample);
             return true;
         }
+
+        // There are some good pixels in there somewhere; psImageBackground just didn't find them
         psLogMsg("psLib.fits", PS_LOG_DETAIL,
                  "Couldn't measure background statistics for image quantisation; retrying.");
@@ -151,5 +177,4 @@
                 psFree(rng);
                 psFree(stats);
-                psFree(sample);
                 return false;
             } else {
@@ -168,5 +193,4 @@
         stdev = psStatsGetValue(stats, STDEV_STAT);
     }
-    psFree(sample);
     psFree(rng);
     psFree(stats);
