using CSV, DataFrames, Statistics, Base.cumsum

function read_csvs(csv_files)
        full_vec = []
        for file in csv_files
                vec = (CSV.File(file; header=false)|>Tables.matrix)[1, 1:end-1]
                push!(full_vec, vec)
        end

        return hcat(full_vec...)
end

input_dir = "per_phreeqc/"
csv_files = readdir(input_dir, join=true)
csv_files = filter(x -> occursin(r"worker_timings_\d+.csv", x), csv_files)

mat = read_csvs(csv_files)

# calculate the mean of each row
mean_vec = vec(mean(mat; dims=2))

mean_intervalls = collect(0:1000:5000)

# calculate the mean of each intervall
mean_cummulative = [mean(@view mean_vec[mean_intervalls[i]+1:mean_intervalls[i+1]])
                    for i in 1:length(mean_intervalls)-1] .* 1e3

using Plots

p = plot(mean_vec .* 1e3,
        xlabel="Iteration",
        ylabel="Runimte [ms]",
        xguidefontsize=8,
        yguidefontsize=8,
        xtickfontsize=6,
        ytickfontsize=6,
        legend=false,
        formatter=:plain,
        yminorgrid=true,
        ylimits=(0, 16),
        yticks=collect(0:2:16),
        yminorticks=4,
        linecolor=:black,
)

for i in 1:length(mean_intervalls)-1
        plot!(p, [mean_intervalls[i]; mean_intervalls[i+1]], [mean_cummulative[i]; mean_cummulative[i]],
                linecolor=:red,
                linewidth=1,
        )
end

display(p)

savefig(p, "phreeeqc_per_iteration_barite.pdf")
