# 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")
d <- p[complete.cases(p[,c("flipper_length_mm","body_mass_g")]),]
same <- d[d$flipper_length_mm==181,]
vals <- unique(same$body_mass_g/1000)
first <- d[d$row_id<=3,]
b <- (first$body_mass_g[2]-first$body_mass_g[1])/1000/(first$flipper_length_mm[2]-first$flipper_length_mm[1])
a <- first$body_mass_g[1]/1000-b*first$flipper_length_mm[1]
save_metrics("math04-r-results.csv",c(complete_pairs=nrow(d),missing_pairs=nrow(p)-nrow(d),
  distinct_output_count=length(vals),first_two_slope=b,first_two_intercept=a,
  third_prediction=a+b*first$flipper_length_mm[3],sqrt_at_170=sqrt(170-170),kg_at_3750=3750/1000))
