Index: trunk/psphot/src/psphotChoosePSF.c
===================================================================
--- trunk/psphot/src/psphotChoosePSF.c	(revision 5048)
+++ trunk/psphot/src/psphotChoosePSF.c	(revision 5058)
@@ -12,9 +12,11 @@
 
     // array to store candidate PSF stars
+    int NSTARS = psMetadataLookupS32 (&status, config, "PSF_MAX_NSTARS");
+    if (!status) NSTARS = sources->n;
     stars = psArrayAlloc (sources->n);
     stars->n = 0;
 
     // select the candidate PSF stars (pointers to original sources)
-    for (int i = 0; i < sources->n; i++) {
+    for (int i = 0; (i < sources->n) && (stars->n < NSTARS); i++) {
 	pmSource *source = sources->data[i];
 	if (source->type != PM_SOURCE_PSFSTAR) continue;
@@ -55,8 +57,8 @@
     try = models->data[0];
     int bestN = 0;
-    float bestM = try->dApResid;
+    float bestM = try->psf->dApResid;
     for (int i = 1; i < models->n; i++) {
 	try = models->data[i];
-	float M = try->dApResid;
+	float M = try->psf->dApResid;
 	if (M < bestM) {
 	    bestM = M;
@@ -67,10 +69,10 @@
     // keep only the selected model:
     try = models->data[bestN];
-    modelName = pmModelGetType (try->modelType);
-    psLogMsg ("psphot.pspsf", 3, "selected psf model %s, ApResid: %f +/- %f\n", modelName, try->ApResid, try->dApResid);
+    pmPSF *psf = psMemCopy(try->psf);
+    psFree (models);				 // keep only the pmPSF resulting from this analysis
 
-    // keep only the pmPSF resulting from this analysis
-    pmPSF *psf = psMemCopy(try->psf);
-    psFree (models);
+    modelName = pmModelGetType (psf->type);
+    psLogMsg ("psphot.pspsf", 3, "selected psf model %s, ApResid: %f +/- %f\n", modelName, psf->ApResid, psf->dApResid);
+
     return (psf);
 }
