Index: trunk/psastro/src/psastroConvert.c
===================================================================
--- trunk/psastro/src/psastroConvert.c	(revision 10855)
+++ trunk/psastro/src/psastroConvert.c	(revision 11551)
@@ -1,4 +1,4 @@
 # include "psastro.h"
-// XXX leak free 2006.04.27
+// leak free 2006.04.27
 
 bool psastroConvertFPA (pmFPA *fpa, psMetadata *recipe) {
@@ -29,22 +29,40 @@
 }
 
-// XXX pass/apply the WCS information?
+// pass/apply the WCS information?
 bool psastroConvertReadout (pmReadout *readout, psMetadata *recipe) {
 
+    bool status;
+
+    // PSPHOT.SOURCES carries the pmSource objects (from psphot analysis or loaded externally)
     psArray *sources = psMetadataLookupPtr (NULL, readout->analysis, "PSPHOT.SOURCES");
     if (sources == NULL)
         return false;
 
-    psArray *rawstars = pmSourceToAstromObj (sources);
+    // convert the pmSource objects into pmAstromObj objects (drop !STAR and SATSTAR?)
+    psArray *inStars = pmSourceToAstromObj (sources);
 
-    psMetadataAdd (readout->analysis, PS_LIST_TAIL, "PSASTRO.RAWSTARS", PS_DATA_ARRAY, "astrometry objects", rawstars);
-    psLogMsg ("psastro", 4, "loaded %ld sources\n", rawstars->n);
+    // sort in ascending magnitude order
+    psArraySort (inStars, psastroSortByMag);
 
-    psFree (rawstars);
+    // we are going to select the brighter Nmax subset for astrometry 
+    int nMax = psMetadataLookupS32 (&status, recipe, "PSASTRO.MAX.NSTAR");
+    if (!status || (nMax < 10)) nMax = 300; // 10 is really somewhat absurd as a lower limit
+
+    // choose the first nMax sources
+    psArray *rawStars = psArrayAlloc (PS_MIN (nMax, inStars->n));
+    for (int i = 0; i < rawStars->n; i++) {
+	rawStars->data[i] = psMemIncrRefCounter (inStars->data[i]);
+    }
+
+    psMetadataAdd (readout->analysis, PS_LIST_TAIL, "PSASTRO.RAWSTARS", PS_DATA_ARRAY, "astrometry objects", rawStars);
+    psLogMsg ("psastro", 4, "loaded %ld sources, using %ld of %ld good sources\n", sources->n, rawStars->n, inStars->n);
+
+    psFree (inStars);
+    psFree (rawStars);
 
     return true;
 }
 
-// XXX select a magnitude range?
+// select a magnitude range?
 psArray *pmSourceToAstromObj (psArray *sources) {
 
@@ -55,4 +73,5 @@
 
         // only accept the PSF sources?
+	// XXX drop SATSTAR?
         if (source->type != PM_SOURCE_TYPE_STAR) continue;
 
@@ -79,2 +98,18 @@
     return objects;
 }
+
+// sort by Mag (ascending)
+int psastroSortByMag (const void **a, const void **b)
+{
+    pmAstromObj *A = *(pmAstromObj **) a;
+    pmAstromObj *B = *(pmAstromObj **) b;
+
+    psF32 mA = (isfinite(A->Mag)) ? A->Mag : FLT_MAX;
+    psF32 mB = (isfinite(B->Mag)) ? B->Mag : FLT_MAX;
+
+    psF32 diff = mA - mB;
+    if (diff > FLT_EPSILON) return (+1);
+    if (diff < FLT_EPSILON) return (-1);
+    return (0);
+}
+
