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

println("Preprocessing Inputs ...")

# aggregate model
model_template_file = open("Preprocessor/template_fcns/FSYS_agg.jl")
model_template_lines = readlines(model_template_file)
insert_index = findall(x -> x == "    # aggregate model marker", model_template_lines)[1]

model_input_file = open("Model/input_aggregate_model.jl")
model_input_text = read(model_input_file, String)

deblank(S::String) = filter(x -> !isspace(x), S)

open("Preprocessor/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, model_template_lines[i])
    end
    
    println(h, "\n")
    # produce replications according to magic comment
    if occursin("@R",model_input_text)
        n1      = findfirst("@R", model_input_text)
        rsym    = model_input_text[n1[end]+1]
        n2      = findfirst(r"[^\d]", model_input_text[n1[end]+2:end])
        n_rep   = parse(Int,model_input_text[n1[end]+2:n1[end]+n2[end]+1])
        for j = 1:n_rep
            if j==1
                aux = ""
                write(h, model_input_text[1:n1[1]-1])
                text = model_input_text[n1[end]+n2[end]+1:end]
            else
                aux = string(j)
                text = "\n#------------------------------------------------------------------------------\n"*
                       "# Economy/Sector " * string(j) * " starts here" *
                       "\n#------------------------------------------------------------------------------\n"*  
                       model_input_text[n1[end]+n2[end]+1:end]
            end
            
            text = replace(text, rsym => aux) 
            write(h, text)
        end
    else
        write(h, model_input_text)
    end
    println(h, "\n")
    for i = insert_index+1:length(model_template_lines)
        println(h, model_template_lines[i])
    end
end
close(model_template_file)
close(model_input_file)

# Check number of equations
Fsys_agg_file = open("Preprocessor/generated_fcns/FSYS_agg_generated.jl")
Fsys_agg_lines= readlines(Fsys_agg_file)
Fsys_agg_lines_unique = unique(Fsys_agg_lines)
number_of_equations =
    count(occursin.("F[indexes.", deblank.(Fsys_agg_lines_unique))) -
    count(occursin.("#F[indexes.", deblank.(Fsys_agg_lines_unique)))


# aggregate steady state
SS_template_file    = open("Preprocessor/template_fcns/prepare_linearization.jl")
SS_template_lines   = readlines(SS_template_file)
insert_index        = findall(x -> x == "    # aggregate steady state marker", SS_template_lines)[1]

SS_input_file       = open("Model/input_aggregate_steady_state.jl")
SS_input_text       = read(SS_input_file, String)

open("Preprocessor/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, SS_template_lines[i])
    end
    println(h, "\n")
    println(h, "@set! n_par.n_agg_eqn = $number_of_equations")
    if occursin("@R",SS_input_text)
        n1      = findfirst("@R", SS_input_text)
        rsym    = SS_input_text[n1[end]+1]
        n2      = findfirst(r"[^\d]", SS_input_text[n1[end]+2:end])
        n_rep   = parse(Int,SS_input_text[n1[end]+2:n1[end]+n2[end]+1])
        for j = 1:n_rep
            if j==1
                aux = ""
                text = SS_input_text[1:n1[1]-1]*SS_input_text[n1[end]+n2[end]+1:end]
            else
                aux = string(j)
                text = "\n#------------------------------------------------------------------------------\n"*
                       "# Economy/Sector " * string(j) * " starts here" *
                       "\n#------------------------------------------------------------------------------\n"*  
                       SS_input_text[n1[end]+n2[end]+1:end]
            end
            text = replace(text, rsym => aux) 
            write(h, text)
        end
    else
        write(h, SS_input_text)
    end
    println(h, "\n")
    for i = insert_index+1:length(SS_template_lines)
        println(h, SS_template_lines[i])
    end

end
close(SS_template_file)
close(SS_input_file)

println("Done!")
