#!/bin/bash
echo "Cleaning up old results..."
rm -f poisson_solution.csv numerical_solution_*.csv rel_errors.txt timing_results_100_iterations.csv
rm -f poisson_solver poisson_timing poisson
rm -f ../../projects/project1/include/*.pdf

echo "Compiling the C++ code..."
g++ -o poisson_solver poisson_solver.cpp src/*
g++ -o poisson_timing poisson_timing.cpp src/*
g++ -o poisson poisson.cpp
echo "Compilation finished."

echo "Generating reference solution..."
./poisson
uv run python/poisson_plotter.py --filename "poisson_solution.csv"

for power in 1 2 3 4 5 6 7; do
    N=$((10 ** power))
    if [ $power -lt 5 ]; then
        output_to_file=true
    else
        output_to_file=false
    fi
    echo "Running simulation for N=$N (output: $output_to_file)"
    ./poisson_solver  $N $output_to_file | tee >(awk '
        /Running Poisson solver/ { N=$7 }
        /Max relative error/    { print N"&"$4"\\\\" >> "rel_errors.txt" }
    ')
    if [ "$output_to_file" = true ]; then
        uv run python/poisson_plotter.py --filename "numerical_solution_$N.csv"
        uv run python/poisson_plotter.py --filename "numerical_solution_$N.csv" --reference "poisson_solution.csv"
    fi
done

echo "Creating Summary Plot..."
uv run python/poisson_plotter.py --reference "poisson_solution.csv" --filename "numerical_solution_*.csv"

echo "Timing the algorithm variations..."
./poisson_timing
uv run python/timing_plotter.py "timing_results_100_iterations.csv"

echo "All done!"
