#!/usr/bin/env python3

import matplotlib.pyplot as plt
import sys
import numpy as np
from astropy.table import Table

datafilename = sys.argv[1]
if len(sys.argv) > 2:
    frequency = sys.argv[2]
else:
    frequency = 1330

t = Table.read(datafilename, format='ascii')

all_sources = "Cassiopeia A", "Cygnus A", "Taurus A", "Andromeda", "Zon", "Maan", "M42", "Virgo A", "3C273", "3C295"

fig, ax = plt.subplots()
ax.set_title(f"Meting {t[0]['Time (UTC)'][:16]} UTC op {frequency} MHz")

for source in set(t['source']):
    try:
        color = "C" + str(all_sources.index(source))
    except ValueError:
        raise ValueError(f"Unknown source {source} in {datafilename}")
    t_sel = t[t['source'] == source]
    ax.plot(t_sel['separation (deg)'], t_sel['signal'], '.', label=source, color=color)
    ax.legend()
    ax.set_xlabel("Afstand (azimut, graden)")
    ax.set_xlim(-6, 6)

ax.patch.set_facecolor('white')
ax.patch.set_alpha(1)
fig.patch.set_alpha(0)

ax.set_yscale('log')

noise_table = t[np.logical_and(t['elevation (deg)'] > 20, np.logical_and(t['source'] != "Zon", np.abs(t['separation (deg)']) > 2))]
if len(noise_table) > 20:
    noiselevel = noise_table['signal'].mean()
elif ax.get_ylim()[0] < 500: # Attenuator on
    noiselevel = 70
else:
    noiselevel = 3000

yticks = []
yticklabels = []

ytick = noiselevel
db = 0
while ytick < ax.get_ylim()[1]:
    yticks.append(ytick)
    yticklabels.append(f"{db} dB")
    ytick *= 10**0.1
    db += 1
while len(yticks) > 15:
    yticks = yticks[::3]
    yticklabels = yticklabels[::3]
ax.set_yticks(yticks)
ax.set_yticklabels(yticklabels)
ax.minorticks_off()
ax.get_yaxis().set_tick_params(which='minor', size=0)
ax.get_yaxis().set_tick_params(which='minor', width=0)
ax.set_ylabel("Relatieve intensiteit")

fig.savefig(datafilename.replace(".txt", ".png"), bbox_inches="tight", facecolor=fig.get_facecolor())
