# Purpose of script: to summarize output from the COMDYN website

# Libraries ####

library(tidyverse)

# Settings ####

options(scipen = 999)

# Input ####

####

# List of route and years to run
iCombo <- read.csv("C:\\Comdyn\\ComdynInput\\comdynInput.csv")

####

# Output files created via the website
iOut <- list.files("C:\\Comdyn\\ComdynOutput")
iOut <- iOut[iOut != "FailedRecords.txt"] # Removing irrelevant file

# Processing ####

# Getting unique routes and years
pCombo <- iCombo %>%
  select(rteno, iYear, jYear) %>%
  unique()

# Getting unique routes and years
# run by the website
pOut <- data.frame(unlist(str_split(iOut, " ")))
colnames(pOut) <- "Temp"
pOut <- pOut %>%
  filter(Temp != "FailedRecords.txt") %>%
  mutate(Temp = str_replace(Temp, ".txt", "")) %>%
  separate_wider_delim(Temp, "_", names = c("rteno", "iYear", "jYear")) %>%
  mutate(
    rteno = as.integer(rteno),
    iYear = as.integer(iYear),
    jYear = as.integer(jYear),
    sVar = 1
  )

# Removing output if already exists
if (exists("outDF")) {
  rm(outDF)
}

# Looping through records from COMDYN to produce
# a summary file
for (i in 1:length(iOut)) {
  print(i)

  ####

  # Getting text output from COMDYN
  pDyn <- readLines(paste("C:\\Comdyn\\ComdynOutput\\", iOut[i], sep = ""), warn = F)

  recInfo <- unlist(str_split(str_replace(iOut[i], ".txt", ""), "_"))

  ln8 <- unlist(str_split(pDyn[8], " "))
  ln8 <- ln8[ln8 != ""]
  S1Mh <- as.numeric(ln8[12])

  ln15 <- unlist(str_split(pDyn[15], " "))
  ln15 <- ln15[ln15 != ""]
  S2Mh <- as.numeric(ln15[12])

  ln22 <- unlist(str_split(pDyn[22], " "))
  ln22 <- ln22[ln22 != ""]
  SAMh <- as.numeric(ln22[12])

  ln29 <- unlist(str_split(pDyn[29], " "))
  ln29 <- ln29[ln29 != ""]
  SBMh <- as.numeric(ln29[12])

  ln47 <- unlist(str_split(pDyn[47], " "))
  ln47 <- ln47[ln47 != ""]
  N1 <- as.numeric(ln47[2])

  ln48 <- unlist(str_split(pDyn[48], " "))
  ln48 <- ln48[ln48 != ""]
  N2 <- as.numeric(ln48[2])

  ln51 <- unlist(str_split(pDyn[51], " "))
  ln51 <- ln51[ln51 != ""]
  ce <- as.numeric(ln51[2])

  ln52 <- unlist(str_split(pDyn[52], " "))
  ln52 <- ln52[ln52 != ""]
  ct <- as.numeric(ln52[2])

  if (!exists("outDF")) {
    outDF <- data.frame(
      rteno = recInfo[1], iYear = recInfo[2], jYear = recInfo[3],
      S1Mh = S1Mh, S2Mh = S2Mh, SAMh = SAMh, SBMh = SBMh,
      N1 = N1, N2 = N2, CE = ce, CT = ct
    )
  } else {
    tempDF <- data.frame(
      rteno = recInfo[1], iYear = recInfo[2], jYear = recInfo[3],
      S1Mh = S1Mh, S2Mh = S2Mh, SAMh = SAMh, SBMh = SBMh,
      N1 = N1, N2 = N2, CE = ce, CT = ct
    )
    outDF <- rbind(outDF, tempDF)
  }
}

# Exporting ####

write.csv(outDF, "C:\\Comdyn\\ComdynOutput\\CompiledComdynOutput.csv", row.names = F)