SELECT
    chipRun.*,
    rawImfile.class_id,
    rawImfile.uri,
    rawExp.exp_tag,
    rawExp.exp_name,
    rawExp.camera,
    rawExp.telescope,
    rawExp.filelevel
FROM chipRun
JOIN rawExp
    USING(exp_id)
JOIN rawImfile
    USING(exp_id)
LEFT JOIN chipProcessedImfile
    ON chipRun.chip_id = chipProcessedImfile.chip_id
    AND rawImfile.exp_id = chipProcessedImfile.exp_id
    AND rawImfile.class_id = chipProcessedImfile.class_id
LEFT JOIN chipMask
    ON chipRun.label = chipMask.label
WHERE
    chipRun.state = 'new'
    AND chipProcessedImfile.chip_id IS NULL
    AND chipProcessedImfile.exp_id IS NULL
    AND chipProcessedImfile.class_id IS NULL
    AND chipMask.label IS NULL

-- new where logic for update.  we probably need to add a 'data_state'
-- field to chipProcessedImfile and update it (full, cleaned, etc) as
-- we cleanup or update
--    (chipRun.state = 'new'
--    AND chipProcessedImfile.chip_id IS NULL
--    AND chipProcessedImfile.exp_id IS NULL
--    AND chipProcessedImfile.class_id IS NULL
--    AND chipMask.label IS NULL) 
--    OR
--    (chipRun.state = 'update'
--    AND chipProcessedImfile.data_state = 'cleaned'
