#############################
# LIBRARY CHECK AND INSTALLATION
#
# Part of replication files for:
# Dill, Janina, Howlett, Marnie, & Müller-Crepon, Carl (2025).
# Do Ukrainians Still Prefer Self-Defense Against Russia At Any Cost? 
# Journal of Peace Research, forthcoming.
#
#############################




# All libraries needed
libraries <- c(
  "car",  "msm",  "fixest",  "ggplot2",  "plyr",
  "sp",  "rgeos", "stargazer", "gtools", "devtools"
)



# Missing libraries
lib.miss <- libraries[!libraries %in% installed.packages()[,"Package"]]

# Print
if(length(lib.miss) > 0){
  print(paste("Installing the following", length(lib.miss), "packages:", 
              paste(lib.miss, collapse = "; ")))
}

if(length(lib.miss) > 0){
  # install if necessary
  for(lib in lib.miss){
    # From CRAN
    install.packages(lib)
  }
  
  # Message
  fails <- libraries[!libraries %in% installed.packages()[,"Package"]]
  message(paste("Successfully installed", length(lib.miss) - length(fails), "packages."))
  if(length(fails) > 0){
    warning(paste("Failed to install the following", length(fails), "packages:", 
                  paste(fails, collapse = "; ")))
  }
} 

# cjRank library
library(devtools)
devtools::install_github(repo = "carl-mc/cjRank")

# Message
message(paste("All packages installed. "))

# Libraries
library(car)
library(msm)
library(fixest)
library(ggplot2)
library(plyr)
library(sp)
library(rgeos)
library(stargazer)
library(gtools)
library(cjRank)
message(paste("Libraries loaded. "))

# Print Library Versions
message(paste("Library versions:"))
loadedPackages()