# 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)
}

p <- read_data("penguins.csv")
p <- p[complete.cases(p[,c("flipper_length_mm","body_mass_g")]),]
pd <- data.frame(y=p$body_mass_g/1000,z=p$flipper_length_mm-200)
h <- read_data("korea-housing.csv")
hd <- data.frame(y=h$nominal,z=((seq_len(nrow(h))-1)-120)/4)
score <- function(model,data) {
  e <- data$y-predict(model,newdata=data)
  c(mae=mean(abs(e)),rmse=sqrt(mean(e^2)))
}
v <- c()
for(degree in c(1,2)) {
  formula <- if(degree==1) y~z else y~z+I(z^2)
  pm <- lm(formula,data=pd)
  hm <- lm(formula,data=hd[1:160,])
  pc <- unname(coef(pm)); hc <- unname(coef(hm))
  pv <- score(pm,pd); tr <- score(hm,hd[1:160,]); te <- score(hm,hd[161:180,])
  local <- c(setNames(pc,paste0("penguin_c",0:degree)),setNames(hc,paste0("housing_c",0:degree)),
    setNames(pv,paste0("penguin_",names(pv))),setNames(tr,paste0("training_",names(tr))),
    setNames(te,paste0("holdout_",names(te))),last_prediction=unname(predict(hm,hd[180,,drop=FALSE])))
  v <- c(v,setNames(local,paste0("degree",degree,"_",names(local))))
}
save_metrics("math05-r-results.csv",v)
