#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as pp

from matplotlib.animation import FuncAnimation

def load_data():
    with open(sys.argv[1], 'rb') as infile:
        header = infile.read(4)
        if header != b'CPX_':
            print(f"Error: not a complex signal file. Format {header} not implemented yet.")
            exit(1)

        T = np.fromfile(infile, dtype=np.float32, count=1)[0]
        data = np.fromfile(infile, dtype=np.complex64)

        f = np.arange(-1/(2*T), 1/(2*T), 1/T/data.size)[:data.size]

        spec = 20*np.log10(np.absolute(np.fft.fftshift(np.fft.fft(data))) / data.size)

        return spec, f


fig = pp.figure()
ax = pp.subplot()

spec, f = load_data()

line, = ax.plot(f, spec, 'b-')

ax.legend(['Spectrum'])
ax.set_xlabel('Frequency [Hz]')

def update(*args):
    try:
        spec, f = load_data()
        line.set_ydata(spec)
    except Exception as e:
        print(e)

    return [line]

anim = FuncAnimation(fig, update, interval=500)
pp.show()