"""Recompute the original synthetic-tone study's per-frame controls from its PCM WAV."""

import csv
import math
import struct
import sys
import wave

wav_path, csv_path = sys.argv[1:3]
with wave.open(wav_path, "rb") as audio:
    assert (audio.getnchannels(), audio.getsampwidth(), audio.getframerate()) == (1, 2, 48000)
    count = audio.getnframes()
    assert count == 576000
    pcm = struct.unpack(f"<{count}h", audio.readframes(count))
with open(csv_path) as handle:
    rows = list(csv.DictReader(handle))
assert len(rows) == 360
smooth = 0.0
for frame, row in enumerate(rows):
    assert int(row["frame"]) == frame
    rms = math.sqrt(
        sum((sample / 32768) ** 2 for sample in pcm[frame * 1600 : (frame + 1) * 1600]) / 1600
    )
    smooth = 0.75 * smooth + 0.25 * min(1, rms / 0.3)
    assert abs(float(row["pcm_rms"]) - rms) < 1e-9
    assert abs(float(row["smoothed_control"]) - smooth) < 1e-9
    assert abs(float(row["ring_radius"]) - (220 + 24 * smooth)) < 1e-6
    assert abs(float(row["bar_width"]) - 640 * smooth) < 1e-6
print("PASS all 360 source PCM RMS rows and ring and bar controls")
