# Base R only; no package installation required.
if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
args <- commandArgs(trailingOnly=FALSE)
filearg <- grep("^--file=",args,value=TRUE)
root <- if(length(filearg)) dirname(normalizePath(sub("^--file=","",filearg[1]))) else getwd()
data_dir <- file.path(root,"\uc2e4\uc81c\ub370\uc774\ud130")
read_data <- function(name) read.csv(file.path(data_dir,name),na.strings=c("","NA"),check.names=FALSE)
save_metrics <- function(name,v) {
  write.csv(data.frame(metric=names(v),value=as.numeric(v)),file.path(root,name),row.names=FALSE)
  print(v)
}

h <- read_data("korea-housing.csv")
a <- which(h$quarter=="2010-Q1"); b <- which(h$quarter=="2024-Q4")
intervals <- b-a; years <- intervals/4; ratio <- h$nominal[b]/h$nominal[a]
annual <- expm1(log(ratio)/years)
wb <- read_data("worldbank.csv"); wb <- wb[wb$country=="KOR",]
gdp_years <- tail(wb$year,1)-wb$year[1]
gdp_ratio <- tail(wb$gdp_pc,1)/wb$gdp_pc[1]
log_changes <- diff(log(h$nominal[a:b]))
v <- c(housing_observations=b-a+1,housing_intervals=intervals,housing_years=years,
  housing_ratio=ratio,housing_quarter_rate=expm1(log(ratio)/intervals),
  housing_annual_rate=annual,housing_log_change=log(ratio),
  housing_sum_log_changes=sum(log_changes),last_quarter_log_change=tail(log_changes,1),
  conditional_doubling_years=log(2)/log1p(annual),
  gdp_observations=nrow(wb),gdp_years=gdp_years,gdp_start=wb$gdp_pc[1],
  gdp_end=tail(wb$gdp_pc,1),gdp_ratio=gdp_ratio,gdp_annual_rate=expm1(log(gdp_ratio)/gdp_years))
stopifnot(abs(log(ratio)-sum(log_changes))<1e-12)
save_metrics("math06-r-results.csv",v)
