Index: trunk/psModules/src/detrend/pmDetrendDB.c
===================================================================
--- trunk/psModules/src/detrend/pmDetrendDB.c	(revision 11876)
+++ trunk/psModules/src/detrend/pmDetrendDB.c	(revision 12300)
@@ -47,8 +47,8 @@
     options->version  = NULL;
     options->dettype  = NULL;
-    options->exptime  = 0.0; 
-    options->airmass  = 0.0; 
-    options->dettemp  = 0.0; 
-    options->twilight = 0.0; 
+    options->exptime  = 0.0;
+    options->airmass  = 0.0;
+    options->dettemp  = 0.0;
+    options->twilight = 0.0;
 
     options->exptimeSet  = false; // not selected
@@ -120,7 +120,7 @@
     char *type = NULL;
     if (options->dettype) {
-	type = psMemIncrRefCounter (options->dettype);
+        type = psMemIncrRefCounter (options->dettype);
     } else {
-	type = pmDetrendTypeToString (options->type);
+        type = pmDetrendTypeToString (options->type);
     }
     unsigned int nFail;
@@ -189,10 +189,26 @@
 
     bool mdstatus;
-    results->level = 0;
     int detID = psMetadataLookupS32 (&mdstatus, md, "det_id");
+    if (!mdstatus) {
+        psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find det_id in output from detselect.");
+        psLogMsg ("psModule.detrend", PS_LOG_ERROR, "detselect response:\n %s\n", buffer->data);
+        goto failure;
+    }
     int iteration  = psMetadataLookupS32 (&mdstatus, md, "iteration");
+    if (!mdstatus) {
+        psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find iteration in output from detselect.");
+        psLogMsg ("psModule.detrend", PS_LOG_ERROR, "detselect response:\n %s\n", buffer->data);
+        goto failure;
+    }
+    psString fileLevel = psMetadataLookupStr(&mdstatus, md, "file_level");
+    if (!mdstatus || !fileLevel || strlen(fileLevel) == 0) {
+        psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find file_level in output from detselect.");
+        psLogMsg ("psModule.detrend", PS_LOG_ERROR, "detselect response:\n %s\n", buffer->data);
+        goto failure;
+    }
 
     results->detID = NULL; // it should be NULL already from the Alloc above
     psStringAppend (&results->detID, " -det_id %d -iteration %d ", detID, iteration);
+    results->level = psMemIncrRefCounter(fileLevel);
 
     psTrace("psModules.detrend", 5, "generated detID %s\n", results->detID);
@@ -225,5 +241,4 @@
 
     PS_ASSERT_PTR_NON_NULL(detID, NULL);
-    PS_ASSERT_PTR_NON_NULL(classID, NULL);
 
     bool status;
@@ -232,5 +247,8 @@
 
     // generate the detselect command
-    psStringAppend (&line, "detselect -select %s -class_id %s", detID, classID);
+    psStringAppend (&line, "detselect -select %s", detID);
+    if (classID && strlen(classID) > 0) {
+        psStringAppend(&line, " -class_id %s", classID);
+    }
     pmConfigDatabaseCommand(&line, config);
     pmConfigTraceCommand(&line);
