#---------------------------------------------------------
# Pre-process aggregate-model and steady-state inputs and write 
# them into the respective functions.
#---------------------------------------------------------

println("Preprocessing Inputs ...")

# aggregate model
f = open("5_LinearizationFunctions/FSYS_agg.jl")
lines = readlines(f)
insert_index = findall(x -> x == "    # aggregate model marker", lines)[1]

g = open("1_Model/input_aggregate_model.jl")
s = read(g, String)
deblank(S::String) = filter(x -> !isspace(x), S)
number_of_equations =
    length(collect(eachmatch(r"F\[indexes.", deblank(s)))) -
    length(collect(eachmatch(r"\#F\[indexes.", deblank(s))))
open("5_LinearizationFunctions/generated_fcns/FSYS_agg_generated.jl", "w") do h
    println(
        h,
        "# This file has been automatically generated by PreprocessInputs.jl. Any user inputs might be overwritten!",
    )
    println(h, "\n")

    println(h, "\n")
    for i = 1:insert_index-1
        println(h, lines[i])
    end
    println(h, "\n")

    write(h, s)
    println(h, "\n")
    for i = insert_index+1:length(lines)
        println(h, lines[i])
    end
end
close(f)
close(g)

# aggregate steady state
f = open("5_LinearizationFunctions/prepare_linearization.jl")
lines = readlines(f)
insert_index = findall(x -> x == "    # aggregate steady state marker", lines)[1]

g = open("1_Model/input_aggregate_steady_state.jl")
s = read(g, String)

#println(s)
#println(number_of_equations)

open("5_LinearizationFunctions/generated_fcns/prepare_linearization_generated.jl", "w") do h
    println(
        h,
        "# This file has been automatically generated by PreprocessInputs.jl. Any user inputs might be overwritten!",
    )
    println(h, "\n")

    for i = 1:insert_index-1
        println(h, lines[i])
    end
    println(h, "\n")
    println(h, "@set! n_par.n_agg_eqn = $number_of_equations")
    write(h, s)
    println(h, "\n")
    for i = insert_index+1:length(lines)
        println(h, lines[i])
    end

end
close(f)
close(g)

println("Done!")
