psql -e -c "CREATE TABLE pub_v3_cwsdb as SELECT * from v3_cwsdb 
            where 
--good detection in at least one band
	    rd_flg ~'[123]'
            and
--make edge cut--
            dist_edge_ew > 10.0 and dist_edge_ns > 10.0
            and
--make artifact cut--
            cc_flg !~'[C-P]'
            and
--add one,two,and three band sources down to snr7--
            ((  (j_snr >= 7.0 or (substr(rd_flg,1,1) !='0' and j_msig <= 0.1551))
                or
                (h_snr >= 7.0 or (substr(rd_flg,2,1) !='0' and h_msig <= 0.1551))
                or
                (k_snr >= 7.0 or (substr(rd_flg,3,1) !='0' and k_msig <= 0.1551))
             )
--add three band sources down to snr 5--                  
             or
             (   rd_flg !~'[0456789]' 
                 and
                 (
                 (j_snr >= 5.0 or (substr(rd_flg,1,1) !='0' and j_msig <= 0.2171))
                 or 
                 (h_snr >= 5.0 or (substr(rd_flg,2,1) !='0' and h_msig <= 0.2171))
                 or 
                 (k_snr >= 5.0 or (substr(rd_flg,3,1) !='0' and k_msig <= 0.2171))
                 )
             )
            )
            and
            (
--j band psfchisq cut --
              (substr(rd_flg,1,1)>'0' and substr(rd_flg,1,1)!='2') or (substr(rd_flg,1,1)='2' and j_psfchi < 10.0)
--h band psfchisq cut --
              or
              (substr(rd_flg,2,1)>'0' and substr(rd_flg,2,1)!='2') or (substr(rd_flg,2,1)='2' and h_psfchi < 10.0)
--k band psfchisq cut --
              or
              (substr(rd_flg,3,1)>'0' and substr(rd_flg,3,1)!='2') or (substr(rd_flg,3,1)='2' and k_psfchi < 10.0)
            )
--add ndet cut--
            and
            (
--no ndet cut for rows where the rd_flg contains a 3
	       rd_flg ~'[3]'
               or
--no ndet cut for rows where there is a psf_fit source above a magnitude threshold
               (substr(rd_flg,1,1) = '2' and j_m > 14.5) 
               or
               (substr(rd_flg,2,1) = '2' and h_m > 14.0) 
               or
               (substr(rd_flg,3,1) = '2' and k_m > 13.5)
--now the ndet cut for anything not matching the above
               or
	       (substr(ndet,2,1) between '3' and '4' and substr(ndet,1,1) >='2')
	       or   
               (substr(ndet,4,1) between '3' and '4' and substr(ndet,3,1) >='2')
	       or
               (substr(ndet,6,1) between '3' and '4' and substr(ndet,5,1) >='2')
               or
	       (substr(ndet,2,1) > '4' and substr(ndet,1,1) >= '3')
               or
	       (substr(ndet,4,1) > '4' and substr(ndet,3,1) >= '3')
               or
	       (substr(ndet,6,1) > '4' and substr(ndet,5,1) >= '3')
	       or
	       (rd_flg='222' and (substr(ndet,1,2)='22' or substr(ndet,3,2)='22' or substr(ndet,5,2)='22'))
            )
            " wsdb