include("Testing.jl")
include("SPA.jl")

Wl = 2048
N = 10000

err = Testing.run_test(SPA.detect_pitch, Wl = Wl, N = N)
print(string(err*100, "% error"))

###########################################
using GLMakie, Makie.Colors
set_theme!(theme_black())
using WAV
using DSP
include("Utils.jl")
include("Testing.jl")
include("SPA.jl")
include("Segmenter.jl")

# Inputs and parameters
Wl = 2048

function get_song(file)
    y, Fs = wavread(string("Inputs/", file, ".wav"))
    low_note = Utils.getNote(1) #hz

    # Signal pre-processing
    y = [(y[i, 1] + y[i, 2]) / 2 for i = 1:length(y[:, 1])]
    function highpassfilter(signals, Fs, cutoff, order = 4)
        wdo = 2.0 * cutoff / Fs
        filth = digitalfilter(Highpass(wdo), Butterworth(order))
        filtfilt(filth, signals)
    end
    y = highpassfilter(y, Fs, low_note)
    return y, Fs
end

file = "Arpeggio"
y, Fs = get_song(file)
windows = Utils.getWindows(y, Wl)

#############
# ANALYSIS
#############
sound = []
block_length = Int(Wl * 0.125)
for i = 1:length(windows)
    window = Utils.hannWindow(windows[i])
    x_start = 1 + (i * Wl)
    x_end = (i * Wl) + Wl
    S = fft(window)[1:Int(Wl / 2)+1]
    push!(sound, Segmenter.Segment(:Pitch, x_start, x_end, SPA.detect_pitch(S, Fs)[1]))
end
sound = Segmenter.consolidate_segments(sound)

#############
# GRAPHING
#############
fig = Figure(resolution = (3840, 2160))
begin
    ax = Axis(fig[1, 1], xticks = MultiplesTicks(10, Wl, "f"))
    for segment in sound
        lines!(ax, Point2.(segment.x_start:segment.x_end, Utils.getNoteFromFreq.(float.(segment.value))), color = :green)
    end
end
display(fig)
# save(string("Outputs/", file, ".png"), fig)