import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import butter, filtfilt

def load_csv(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            cleaned_lines = []
            for line in f:
                line = line.strip()
                if line.endswith(','):
                    line = line[:-1]
                cleaned_lines.append(line)

        loaded_array = np.loadtxt(cleaned_lines, delimiter=',')
        if loaded_array.ndim == 1:
            loaded_array = loaded_array.reshape(-1, 1)
        return loaded_array
    except Exception as e:
        print(f"Could not load file:\n{e}")
        return -1

arr = load_csv('output\\data_fixed.csv') # Load CSV
tarr = np.transpose(arr)

t = np.arange(0, 1152000, 12.5)

envelope = np.abs(tarr[1])
cutoff = 1000e3
nyquist = 0.5 * 80e6
order = 5
b, a = butter(order, cutoff / nyquist, btype='low')

filt_envelope = filtfilt(b, a, envelope)

print(np.size(tarr[0]))

startcut = round(0.1 * np.size(tarr[1]))
endcut = round(0.5 * np.size(tarr[1]))
demodulated_voltage = np.average(tarr)

print(f'Start cut: {startcut}')
print(f'End cut: {endcut}')
print(f'Altitude demodulated: {demodulated_voltage}')

i = startcut
while np.abs(filt_envelope[i]) > np.abs(demodulated_voltage) * 0.3 and i < np.size(filt_envelope):
    i = i + 1
delay = round((np.size(tarr[1]) - i) / 0.08)

print(f'Delay: {delay} nS')

plt.figure(figsize=(12,8))

plt.subplot(2, 1, 1)
plt.plot(t, tarr[1] * (10 / 65536))
plt.title('RF Signal')
plt.xlabel('Time, nS')
plt.ylabel('Voltage, V')
plt.grid(True)

plt.subplot(2, 1, 1)
plt.plot(t, filt_envelope * (10 / 65536))
plt.title('Demodulate Signal')
plt.xlabel('Time, nS')
plt.ylabel('Voltage, V')
plt.grid(True)

plt.show()