noinjs += 1

sims = newtbl

if verbose:
    print("Loaded %d injections" % len(sims))
    inj_format = "".join("%s: %s   " % name_format for name_format in zip(
        inj_approx.param_names, inj_approx.param_formats))

# main worker loop
# FIXME: this (potentially) breaks using mixed template bank approximants
match_map = np.empty(len(sims),
                     dtype=[("match", np.float32),
                            ("inj_sigmasq", np.float32)])
inj_bank = Bank(noise_model, flow)
tmplts = lsctables.SnglInspiralTable()
for j, sim in enumerate(sims):

    inj_wf = inj_approx.from_sim(sim, bank=inj_bank)
    inj_ind = opts.injection_min + j
    if verbose:
        print("injection %d/%d" % (j + 1, len(sims)))
        print(inj_format % inj_wf.params)

    # NB: sigmasq set during argmax_match
    match_tup = bank.argmax_match(inj_wf)

    if verbose:
        print("\tbest matching template:  ", end=' ')
        print(bank._templates[match_tup[1]].params)
        print("\tbest match:  %f\n" % match_tup[0])
    sngl_inspiral = lsctables.SnglInspiralTable.get_table(tmpdoc)
    seed_waveform = waveforms[approx]
    bank.add_from_sngls(sngl_inspiral, seed_waveform)

    if opts.verbose:
        print "Added %d %s templates from %s to bank." % (len(sngl_inspiral), approx, seed_file)

    tmpdoc.unlink()
    del sngl_inspiral, tmpdoc

if opts.verbose:
    print "Initialized the template bank with %d templates." % len(bank)

# write bank to h5 file, but note that from_sngls() has resorted the
# bank by neighborhood_param
sngls = lsctables.SnglInspiralTable()
for s in bank._templates:
    sngls.append(s.to_sngl())
h5file.create_dataset("/sngl_inspiral", data=ligolw_table_to_array(sngls), compression='gzip', compression_opts=1)
h5file.flush()
del sngls[:]

# pick injection parameters
xmldoc2 = utils.load_filename(inj_file, contenthandler=ContentHandler)
ligolw_copy_process(xmldoc2, fake_xmldoc)
sims = lsctables.SimInspiralTable.get_table(xmldoc2)

#
# sometime inspinj doesn't give us everything we want, so we give the
# user a little extra control here over the injections acutally used
#