# Rscript rank-weekly.R selection-inputs.csv weekly-ranking.csv
args <- commandArgs(trailingOnly = TRUE)
if (length(args) != 2) stop("Pass the input CSV and the output CSV.")
rows <- read.csv(args[1], stringsAsFactors = FALSE)
stopifnot(nrow(rows) > 0, !anyDuplicated(rows$id))
# Chronicle agreement and direct evidence carry more weight than incidental mentions.
pageview_points <- ifelse(rows$pageview_rank == 0, 0,
                         ifelse(rows$pageview_rank <= 100, 9,
                                ifelse(rows$pageview_rank <= 300, 6, 3)))
rows$score <- 100 * rows$editor_pick +
  7 * rows$world + 5 * rows$us + 3 * rows$uk +
  4 * (rows$world == 1 & rows$us == 1) +
  6 * rows$focused + pmin(rows$citations, 3) +
  pageview_points - 2 * rows$monthly_only
ranked <- rows[order(rows$year, rows$week, -rows$score, rows$event_date, rows$id), ]
weekly <- ranked[!duplicated(ranked[c("year", "week")]), ]
write.csv(weekly[c("id", "year", "week", "score")], args[2], row.names = FALSE)
