Index: trunk/ippTools/share/Makefile.am
===================================================================
--- trunk/ippTools/share/Makefile.am	(revision 19244)
+++ trunk/ippTools/share/Makefile.am	(revision 19249)
@@ -132,5 +132,6 @@
      regtool_revertprocessedimfile.sql \
      stacktool_definebyquery_insert.sql \
-     stacktool_definebyquery_insert_random.sql \
+     stacktool_definebyquery_insert_random_part1.sql \
+     stacktool_definebyquery_insert_random_part2.sql \
      stacktool_definebyquery_part1.sql \
      stacktool_definebyquery_part2.sql \
Index: trunk/ippTools/share/stacktool_definebyquery_insert_random.sql
===================================================================
--- trunk/ippTools/share/stacktool_definebyquery_insert_random.sql	(revision 19244)
+++ 	(revision )
@@ -1,33 +1,0 @@
--- Use a random set of warps for the inputs to a defined stack
-INSERT INTO
-        stackInputSkyfile(stack_id, warp_id)
-SELECT
-        @STACK_ID@, -- This should be replaced with the stack_id
-        warp_id
-FROM (
-    -- Sub-select to get the random set of warps
-    SELECT
-            warpSkyfile.*,
-            rand() AS rnd_num
-    FROM warpSkyfile
-    JOIN warpRun
-        USING(warp_id, tess_id)
-    JOIN fakeRun
-        USING(fake_id, tess_id)
-    JOIN camRun
-        USING(cam_id, tess_id)
-    JOIN chipRun
-        USING(chip_id, tess_id)
-    JOIN rawExp
-        USING(exp_id, tess_id)
-    WHERE
-        skycell_id = '%s'
-        AND tess_id = '%s'
-        AND rawExp.filter = '%s'
-        AND warpSkyfile.fault = 0
-        AND warpSkyfile.ignored = 0
-    -- Sort by the random number, and take the first N
-    -- to get a random set of N.
-    ORDER BY rnd_num
-    LIMIT %d
-) AS randomWarps
Index: trunk/ippTools/share/stacktool_definebyquery_insert_random_part1.sql
===================================================================
--- trunk/ippTools/share/stacktool_definebyquery_insert_random_part1.sql	(revision 19249)
+++ trunk/ippTools/share/stacktool_definebyquery_insert_random_part1.sql	(revision 19249)
@@ -0,0 +1,32 @@
+-- This is the part 1 of 2 of a query to use a random set of warps for
+-- the inputs to a defined stack.
+-- stacktool_definebyquery_insert_random_part2.sql should be appended.
+INSERT INTO
+        stackInputSkyfile(stack_id, warp_id)
+SELECT
+        @STACK_ID@, -- This should be replaced with the stack_id
+        warp_id
+FROM (
+    -- Sub-select to get the random set of warps
+    SELECT
+            warpSkyfile.*,
+            rand() AS rnd_num
+    FROM warpSkyfile
+    JOIN warpRun
+        USING(warp_id, tess_id)
+    JOIN fakeRun
+        USING(fake_id, tess_id)
+    JOIN camRun
+        USING(cam_id, tess_id)
+    JOIN chipRun
+        USING(chip_id, tess_id)
+    JOIN rawExp
+        USING(exp_id, tess_id)
+    WHERE
+        skycell_id = '%s'
+        AND tess_id = '%s'
+        AND rawExp.filter = '%s'
+        AND warpSkyfile.fault = 0
+        AND warpSkyfile.ignored = 0
+-- Put additional constraints here
+-- stacktool_definebyquery_insert_random_part2.sql goes here
Index: trunk/ippTools/share/stacktool_definebyquery_insert_random_part2.sql
===================================================================
--- trunk/ippTools/share/stacktool_definebyquery_insert_random_part2.sql	(revision 19249)
+++ trunk/ippTools/share/stacktool_definebyquery_insert_random_part2.sql	(revision 19249)
@@ -0,0 +1,8 @@
+-- This is the part 2 of 2 of a query to use a random set of warps for
+-- the inputs to a defined stack.
+-- stacktool_definebyquery_insert_random_part1.sql should be prepended.
+    -- Sort by the random number, and take the first N
+    -- to get a random set of N.
+    ORDER BY rnd_num
+    LIMIT %d
+) AS randomWarps
Index: trunk/ippTools/src/stacktool.c
===================================================================
--- trunk/ippTools/src/stacktool.c	(revision 19244)
+++ trunk/ippTools/src/stacktool.c	(revision 19249)
@@ -141,6 +141,6 @@
     PXOPT_LOOKUP_TIME(registered, config->args, "-registered", false, false);
 
-    if (!psListLength(where->list) && 
-	!psMetadataLookupBool(NULL, config->args, "-all")) {
+    if (!psListLength(where->list) &&
+        !psMetadataLookupBool(NULL, config->args, "-all")) {
         psFree(where);
         psError(PXTOOLS_ERR_DATA, false, "search parameters are required");
@@ -159,9 +159,9 @@
         psFree(whereClause);
     }
-    psFree(where);
 
     psString groupby = pxDataGet("stacktool_definebyquery_part2.sql");
     if (!groupby) {
         psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
+        psFree(where);
         return false;
     }
@@ -202,4 +202,5 @@
         psError(PS_ERR_UNKNOWN, false, "database error");
         psFree(select);
+        psFree(where);
         return false;
     }
@@ -217,5 +218,5 @@
                 psError(PXTOOLS_ERR_PROG, false, "unknown error");
         }
-
+        psFree(where);
         return false;
     }
@@ -223,4 +224,5 @@
         psTrace("stacktool", PS_LOG_INFO, "no rows found");
         psFree(output);
+        psFree(where);
         return true;
     }
@@ -228,5 +230,5 @@
     psString insert = NULL;             // Insertion query
     if (randomLimit > 0) {
-        insert = pxDataGet("stacktool_definebyquery_insert_random.sql");
+        insert = pxDataGet("stacktool_definebyquery_insert_random_part1.sql");
     } else {
         insert = pxDataGet("stacktool_definebyquery_insert.sql");
@@ -234,9 +236,29 @@
     if (!insert) {
         psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
-        return false;
+        psFree(where);
+        return false;
+    }
+
+    if (psListLength(where->list)) {
+        psString whereClause = psDBGenerateWhereConditionSQL(where, NULL);
+        psStringAppend(&select, " AND %s", whereClause);
+        psFree(whereClause);
+    }
+    psFree(where);
+
+    if (randomLimit > 0) {
+        psString part2 = pxDataGet("stacktool_definebyquery_insert_random_part2.sql");
+        if (!part2) {
+            psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
+            psFree(insert);
+            return false;
+        }
+        psStringAppend(&insert, "%s", part2);
+        psFree(part2);
     }
 
     if (!psDBTransaction(config->dbh)) {
         psError(PS_ERR_UNKNOWN, false, "database error");
+        psFree(where);
         return false;
     }
@@ -288,9 +310,9 @@
             0,                          // ID
             "new",                      // state
-            workdir, 
+            workdir,
             NULL,                       // workdir_state
-            registered, 
-            skycell_id, 
-            tess_id, 
+            registered,
+            skycell_id,
+            tess_id,
             filter);
 
@@ -324,8 +346,8 @@
         psFree(idString);
 
-	// XXX this insert uses a select to generate the list of warp_ids for the stack,
-	// we have applied a set of criteria above (WHERE) to select the relevant warps
-	// this insert needs to use exactly the same restrictions (race condition is probably not critical)
-	// the insert below seems to only restrict matches to the skycell, tess, and filter
+        // XXX this insert uses a select to generate the list of warp_ids for the stack,
+        // we have applied a set of criteria above (WHERE) to select the relevant warps
+        // this insert needs to use exactly the same restrictions (race condition is probably not critical)
+        // the insert below seems to only restrict matches to the skycell, tess, and filter
         if ((randomLimit > 0 && !p_psDBRunQuery(config->dbh, thisInsert, skycell_id, tess_id, filter,
                                                 randomLimit)) ||
@@ -384,12 +406,12 @@
 
     stackRunRow *run = stackRunRowAlloc(
-	0, 				// ID
-	"new", 				// state
-	workdir, 
-	NULL, 				// workdir_state
-	registered, 
-	skycell_id, 
-	tess_id, 
-	filter);
+        0,                              // ID
+        "new",                          // state
+        workdir,
+        NULL,                           // workdir_state
+        registered,
+        skycell_id,
+        tess_id,
+        filter);
 
     if (!run) {
