class phase_align_cc(gr.hier_block):
    def __init__(self, fg, phase_avg_alpha=1e-5, phase_agc_avg_alpha=1e-5, ph_corr_type=1):
        # input two similar signals with a phase difference.
        # returns two blocks outputting the signals phase aligned, 
        # also returns the block which outputs the average phase difference.

        # Works best when the signals have the same amplitude.
        # This can be accomplished when you add agc_cc before both inputs.

        di = gr.deinterleave(gr.sizeof_gr_complex)
        mult=gr.multiply_cc()
        conj=gr.conjugate_cc()
        c2arg=gr.complex_to_arg() #fft_size)
        mult2=gr.multiply_cc()
        conj2=gr.conjugate_cc()
        phase_average=gr.single_pole_iir_filter_cc(phase_avg_alpha)
        fg.connect((di,0),(mult,0))
        fg.connect((di,1),conj,(mult,1))
        if ph_corr_type==0: #this version does not work very well
          mag=gr.complex_to_mag()
          div=gr.divide_cc() #output of this contains only phase information, magnitude is eliminated (mag==1.0)
          float_to_complex=gr.float_to_complex()
          fg.connect(mult,(div,0))
          fg.connect(mult,mag,float_to_complex,(div,1))
          fg.connect(div,phase_average,(mult2,0))
        elif ph_corr_type==1: #this version works OK, especially when both sources have amplitude 1.0 (use agc_cc for both before inputing)
          phase_agc=gr.agc_cc(phase_agc_avg_alpha,1.0,1.0) #rate,reference,gain
          fg.connect(mult,phase_average,phase_agc,(mult2,0)) #phase_average,
        elif ph_corr_type==2: #another way of doing this, this one is a bit noisy
          phasemod=gr.phase_modulator_fc(1.0)
          fg.connect(mult,c2arg,phasemod,phase_average,(mult2,0))
        fg.connect((di,1),(mult2,1))
        interleaver= gr.interleave(gr.sizeof_gr_complex)
        fg.connect((di,0),(interleaver,0))
        fg.connect(mult2,(interleaver,1))
        gr.hier_block.__init__(self, fg, di, interleaver)
        return (di,0),mult2,phase_average

