/*
   Copyright (C) 2015
   Matthias P. Braendli, matthias.braendli@mpb.li
    http://opendigitalradio.org
 */
/*
   This file is part of ODR-DPD.
   ODR-DPD 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 of the
   License, or (at your option) any later version.
   ODR-DPD 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 ODR-DPD.  If not, see .
 */
#include "OutputUHD.hpp"
#include "utils.hpp"
size_t read_samples(FILE* fd, std::vector& samples, size_t count)
{
    if (samples.size() < count) {
        MDEBUG("HAD TO RESIZE BUFFER!\n");
        samples.resize(count);
    }
    size_t num_read = fread((char*)&samples.front(), sizeof(complexf), count, fd);
    if (num_read == 0) {
        rewind(fd);
        num_read = fread((char*)&samples.front(), sizeof(complexf), count, fd);
    }
    return num_read;
}
int main(int argc, char **argv)
{
    double txgain = 0;
    if (argc == 1) {
        txgain = strtod(argv[1], nullptr);
        if (!(0 <= txgain and txgain < 80)) {
            MDEBUG("txgain wrong: %f\n", txgain);
            return -1;
        }
    }
    const size_t samps_per_buffer = 20480;
    OutputUHD output_uhd;
    output_uhd.Init(txgain);
    FILE* fd = fopen("input.iq", "rb");
    if (!fd) {
        MDEBUG("Could not open file\n");
        return -1;
    }
    std::vector input_samples(samps_per_buffer);
    size_t samps_read = 0;
    size_t total_samps_read = samps_read;
    double last_print_time = 0;
    do {
        samps_read = read_samples(fd, input_samples, samps_per_buffer);
        double first_sample_time = 0;
        output_uhd.Transmit(input_samples, samps_read, &first_sample_time);
        if (first_sample_time - last_print_time > 1) {
            MDEBUG("Tx %zu samples at t=%f\n", samps_read, first_sample_time);
            last_print_time = first_sample_time;
        }
        total_samps_read += samps_read;
    }
    while (samps_read);
    MDEBUG("Read %zu samples in total\n", total_samps_read);
}