signal= cplx_randn(SIGLEN)
sc_half_seq= cplx_randn(SCLEN)
sc_seq= np.concatenate((sc_half_seq[-CPLEN:], sc_half_seq, sc_half_seq))


start= (len(signal) - len(sc_seq)) // 2
end= start + len(sc_seq)

signal[start:end]+= sc_seq

for (fqname, fqoff) in (('nooff', 0), ('fqoff', 0.01)):
    df= np.exp(1j * np.linspace(0, fqoff * SIGLEN, len(signal)))
    fqadj= signal * df

    detection= fqadj[SCLEN:] * fqadj[:-SCLEN].conj()
    detection= np.convolve(detection, np.ones(SCLEN) / SCLEN, mode='valid')

    for (name, src) in (('abs', abs(detection)), ('arg', np.angle(detection))):
        fig= Figure()
        canvas= FigureCanvas(fig)
        ax= fig.add_subplot('111')

        sl= len(src)
        
        ax.plot(
            np.linspace(-sl/2, sl/2, sl),
            src, 'b'
        )

        canvas.print_pdf('sc_detector_output_{}_{}.pdf'.format(fqname, name))
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot('111')

    ax.set_title('Δt={}T, a={}'.format(delay / SAMP_RATE, mag))

    target = list()

    for i in range(64):
        seq = np.zeros(IMPRESLEN)
        seq[::SAMP_RATE] = rand.choice((-1, 1), IMPRESLEN // SAMP_RATE)

        full = np.convolve(seq, imp_res)
        start = (len(full) - 3 * SAMP_RATE) // 2
        end = (len(full) + 3 * SAMP_RATE) // 2

        full[:-delay] += mag * full[delay:]
        full /= 1 + mag

        crop = full[start:end]

        crop += 0.01 * rand.randn(len(crop))

        target.append(crop)

    for tgt in target:
        ax.plot(np.linspace(0, 0.1, len(tgt)), tgt, 'b')

    canvas.print_pdf('eye_diagram_multipath_{}_{}m.pdf'.format(
        delay, int(mag * 1000)))