-- This is the first part of the query to get a list of skycells with
-- warps to be stacked, along with the number of warps already in a
-- stack.  It needs to be completed by part 2 (see below).

SELECT
    skycell_id,
    tess_id,
    filter,
    num_warp,
    MAX(num_stack) AS num_stack
FROM ((
    -- Number of stack-ready warps as a function of skycell and filter
    SELECT
        skycell_id,
        tess_id,
        filter,
        COUNT(warpSkyfile.skycell_id) AS num_warp -- number of warps that can be stacked
    FROM warpRun
        JOIN warpSkyfile 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
        warpRun.state = 'stop'
    AND warpSkyfile.ignored = 0
    AND warpSkyfile.fault = 0
    -- Here should follow the SQL in stacktool_definebyquery_part2.sql,
    -- after any additional WHERE conditions have been added

