Index: trunk/psphot/src/psphotGalaxyShape.c
===================================================================
--- trunk/psphot/src/psphotGalaxyShape.c	(revision 36441)
+++ trunk/psphot/src/psphotGalaxyShape.c	(revision 36633)
@@ -205,4 +205,5 @@
 	if (!(source->tmpFlags & PM_SOURCE_TMPF_MOMENTS_MEASURED)) continue;
 	if (source->mode & PM_SOURCE_MODE_MOMENTS_FAILURE) continue;
+        if (!source->modelPSF) continue;
 
 	// psphotSetRadiusMomentsExact sets the radius based on Mrf
@@ -274,13 +275,19 @@
 
             int i = source->galaxyFits->chisq->n - 1;
-            float thisChisq = source->galaxyFits->chisq->data.F32[i];
-            if (isfinite(thisChisq) && (!isfinite(chisqBest) || thisChisq < chisqBest)) {
-                chisqBest = thisChisq;
-                fRmajorBest = fRmajor;
-                fRminorBest = fRminor;
+            float flux = source->galaxyFits->Flux->data.F32[i];
+            if (isfinite(flux)) {
+                float thisChisq = source->galaxyFits->chisq->data.F32[i];
+                if (isfinite(thisChisq) && isfinite(flux) && (!isfinite(chisqBest) || thisChisq < chisqBest)) {
+                    chisqBest = thisChisq;
+                    fRmajorBest = fRmajor;
+                    fRminorBest = fRminor;
+                }
             }
+            // reset I0 to avoid potential problems on the next iteration
+            PAR[PM_PAR_I0] = 1.0;
 	}
     }
 
+#define SAVE_BEST_MODEL
 #ifdef SAVE_BEST_MODEL
     // Save model with smallest chisq
@@ -301,15 +308,16 @@
         psphotGalaxyShapeSource (pcm, source, maskVal, psfSize, false);
 
-        // Replace modelEXT with this model
-        // XXX: only do this if the model is good
-        psFree (source->modelEXT);
-
-        source->modelEXT = psMemIncrRefCounter (pcm->modelConv);
-        source->type = PM_SOURCE_TYPE_EXTENDED;
-        source->mode |= PM_SOURCE_MODE_EXTMODEL;
-        source->mode |= PM_SOURCE_MODE_NONLINEAR_FIT;
-
-        // cache the model flux
-        pmPCMCacheModel (source, maskVal, psfSize, fitOptions->nsigma);
+        // Replace modelEXT with this model, if the model is good
+        if (isfinite(PAR[PM_PAR_I0])) {
+            psFree (source->modelEXT);
+
+            source->modelEXT = psMemIncrRefCounter (pcm->modelConv);
+            source->type = PM_SOURCE_TYPE_EXTENDED;
+            source->mode |= PM_SOURCE_MODE_EXTMODEL;
+            source->mode |= PM_SOURCE_MODE_NONLINEAR_FIT;
+
+            // cache the model flux
+            pmPCMCacheModel (source, maskVal, psfSize, fitOptions->nsigma);
+        }
     }
 
