from matplotlib import pyplot as plt
from ctypes import *
import numpy as np

from read_data_file import db20n


def read_sim_output(filename, is_float=False):
    fid = open(filename, "r")
    lines = fid.readlines()
    fid.close()

    data = [int(line) for line in lines]
    data = np.array(data)

    if is_float:
        as_floats = c_float * data.size
        data = as_floats.from_buffer(data.astype(np.int32))
        data = np.array(data)

    return data


def main():
    data = read_sim_output("sim_out.bin")
    data[data >= 2**15] -= 2**16
    data = data[0::2] + 1j * data[1::2]


    x = np.fft.fft(data)
    f_axis = np.fft.fftfreq(x.size, d=1/750)

    x = np.fft.fftshift(x)
    f_axis = np.fft.fftshift(f_axis)


    plt.figure()
    plt.plot(f_axis, db20n(x))


    plt.figure()
    plt.plot(data.real)
    plt.plot(data.imag)
    plt.title('HDL Sim Output - IQ')
    plt.grid()

    plt.figure()
    plt.plot(np.unwrap(np.angle(data)))
    plt.title('HDL Sim Output - Phase')
    plt.grid()

    plt.show()

if __name__ == '__main__':
    main()