/* 
 * Copyright (c) 2021 Satlab A/S <satlab@satlab.com>
 * 
 * This is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 * 
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this software; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <gnuradio/io_signature.h>
#include <volk/volk.h>
#include "phase_stepper_impl.h"

namespace gr {
  namespace satlab {

    phase_stepper::sptr
    phase_stepper::make(uint64_t timeout_samples, float step_size)
    {
      return gnuradio::get_initial_sptr
        (new phase_stepper_impl(timeout_samples, step_size));
    }

    void
    phase_stepper_impl::kick(void)
    {
        d_last_kick = nitems_read(0);
    }

    void
    phase_stepper_impl::handle_kick(pmt::pmt_t pdu)
    {
        kick();
    }

    int phase_stepper_impl::work(int noutput_items,
                                 gr_vector_const_void_star& input_items,
                                 gr_vector_void_star& output_items)
    {
        gr_complex* iptr = (gr_complex*)input_items[0];
        gr_complex* optr = (gr_complex*)output_items[0];

        if (nitems_read(0) - d_last_kick > d_timeout_samples) {
            d_phase = d_phase * exp(gr_complex(0.0, -1.0) * d_step_size);
            kick();
        }

        volk_32fc_s32fc_multiply_32fc(optr, iptr, d_phase, noutput_items);

        return noutput_items;
    }

    void phase_stepper_impl::set_timeout(uint64_t samples)
    {
        d_timeout_samples = samples;
    }

    phase_stepper_impl::phase_stepper_impl(uint64_t timeout_samples, float step_size)
      : gr::sync_block("phase_stepper",
              gr::io_signature::make(1, 1, sizeof(gr_complex)),
              gr::io_signature::make(1, 1, sizeof(gr_complex))),
        d_last_kick(0),
	d_step_size(step_size),
        d_phase(gr_complex(1.0f, 0.0f)),
        d_timeout_samples(timeout_samples)
    {
        message_port_register_in(pmt::mp("kick"));
        set_msg_handler(pmt::mp("kick"), [this](pmt::pmt_t msg) {
                this->handle_kick(msg);
        });
        kick();
    }
  } /* namespace satlab */
} /* namespace gr */
