###########################
# DEFINE HELPER FUNCTIONS #
###########################

# Helper for assignment of '.RDATA' files.
loadRData <- function(fileName) {
  load(fileName)
  get(ls()[ls() != "fileName"]) }

# Convert 'PAR$reftab' to appropriate format for upcoming merges.
refage_table <- function(tab, pint) {
  
  # Check if GO reference ages are provided.
  if (sum(tab$year == first(pint)) != 2) {
    print("Error: Uniquely specify all GO reference ages in parameter 'reftab'.")
    interrupt()
  }
  
  # Impute missing reference ages by year through LOCF method.
  tab %>% 
    mutate(year = factor(year, levels = pint)) %>% 
    complete(year, sex) %>%
    mutate(year = as.integer(as.character(year))) %>%
    group_by(sex) %>% 
    arrange(year, .by_group = TRUE) %>% 
    fill(refage, .direction = "down") %>% 
    mutate(type = "alt") %>% 
    group_by(sex) %>% 
    mutate(dage = refage - first(refage)) %>% 
    select(year, type, sex, dage) %>% 
    ungroup 
  }

# Define function for extracting prediction errors from simple regression without 
# intercept.
psd <- function(fit, h) 
  return(glance(fit)$sigma * sqrt(1 + h^2 / sum(model.frame(fit)[, 2]^2)))


# Convenience function to produce differential costs between a pair of parameter sets.
compare_projections <- function(PAR1, PAR2) {
    
    # Load necessary helper functions.
    source("scripts/other/aux_fun.R", local = TRUE)
    
    # Base run.
    print("Benchmark run")
    PAR <- PAR1
    
    source("scripts/model/2_prepare_inputs.R", local = TRUE)
    source("scripts/model/3_adjust_scenarios.R", local = TRUE)
    
    if (PAR1$cv)
      source("scripts/model/4_cross-validation.R", local = TRUE)
    
    source("scripts/model/5_reference_projection.R", local = TRUE)
    
    # Store results of benchmark run.
    RES_BENCH <- 
      select(RES_TAB, year, exp_bench = ref)
    
    # Modified run.
    print("Modified run")
    PAR <- PAR2
    
    source("scripts/model/2_prepare_inputs.R", local = TRUE)
    source("scripts/model/3_adjust_scenarios.R", local = TRUE)
    
    if (PAR1$cv)
      source("scripts/model/4_cross-validation.R", local = TRUE)
    
    source("scripts/model/5_reference_projection.R", local = TRUE)
    
    # Store results of modified run.
    RES_MODI <- 
      select(RES_TAB, year, exp_modi = ref)
    
    # Return comparison table (results under 'PAR1' minus 'PAR2').
    return(
      left_join(RES_BENCH, RES_MODI, by = "year") %>% 
        mutate(d_cost = exp_bench - exp_modi) %>% 
        select(year, exp_bench, exp_modi, d_cost))
  }
