
rm(list=ls(all=TRUE))# Clear environment
rm(list = ls())
if(!is.null(dev.list())) dev.off() # clear plots
cat("\014")# Clear console

# load libraries
library(mFilter)
library(bimets)
library(knitr)
library("readxl")
library(patchwork)
library(tidyr)
library("readr")
library(ggplot2)
library(ggthemes)
library(scales)
library(zoo)
require(gridExtra)
library(openxlsx)
library("reshape2")
library("scales")
source("data_prep.R")
source("write_output.R")

model_txt <- read_file("model.txt")
model = LOAD_MODEL(modelText = model_txt, showWarnings = TRUE)
data = prepare_data()
model = LOAD_MODEL_DATA(model, data)


model=ESTIMATE(model,

    TSRANGE=c(1921, 1, 1941, 1),
    forceTSRANGE = FALSE,
    tol=.000000000000001,
    CHOWTEST = FALSE,
    verbose = TRUE,
    estTech = 'OLS',
    )
exogenizeCandidates  <- list(

)

    vendog_vars <- model$vendog
    exogenizeList <- list()
    for (var_name in names(exogenizeCandidates)) {
    if (var_name %in% vendog_vars) {
        exogenizeList[[var_name]] <- exogenizeCandidates[[var_name]]
    }
    }

    
        

        model <- SIMULATE(model,
            simType='STATIC',
            TSRANGE=c(1921, 1, 1941, 1),
            simConvergence=0.000000000000001,
            # simIterLimit=2000,
            Exogenize=exogenizeList,
            simAlgo='NEWTON',
        )

        simu1 <- model$simulation
        simu2 <- head(simu1,-1)
        Year <- c(list(1921:1941))
        df_s <- data.frame(simu2)
        df_s['Year'] <- Year
        write.xlsx(df_s, "df_model.xlsx")
        write.xlsx(data.frame(data), "df_data.xlsx")

        # write outputs
        write_coeffs(model)

        