# Purpose of script: To produce a data set summarizing the number
# of 5, 10-stop segments a species was recorded by route and year

# Libraries ####

library(tidyverse)

# Settings ####

options(scipen = 999)

# Input ####

## Data from Breeding Bird Survey (https://doi.org/10.5066/P9GS9K64)

# Route data
iRoute <- read_csv("C:\\2023Release_Nor\\routes.csv") %>%
  # Retaining routes along roadsides and randomly established with 50 points
  filter(RouteTypeID == 1 & RouteTypeDetailID == 1) %>%
  # Creating unique route ID
  mutate(rteno = paste(StateNum, Route, sep = ""))

# Weather data
iWeather <- read_csv("C:\\2023Release_Nor\\weather.csv") %>%
  # Creating unique route ID
  mutate(rteno = paste(StateNum, Route, sep = "")) %>%
  # Filtering to standard BBS protocol
  filter(RPID == 101 & QualityCurrentID == 1 & RunType == 1 & rteno %in% iRoute$rteno)

# Processing ####

# Two bookend years
i <- 2000
j <- 2004

# Compiling BBS data from 1997 to present
bbsData <- list.files(path = "C:\\2023Release_Nor\\50-StopData\\") %>%
  lapply(function(x) {
    oData <- read_csv(paste("C:/2023Release_Nor/50-StopData/", x, sep = "")) %>%
      mutate(StateNum = sprintf("%02d", as.numeric(StateNum)))
    return(oData)
  }) %>%
  bind_rows(.) %>%
  # Filtering based on routes and conditions selected above
  filter(
    RouteDataID %in% iWeather$RouteDataID,
    Year >= i & Year <= j
  ) %>%
  mutate(
    rteno = paste(StateNum, Route, sep = ""), # creating unique route identifier
    # Creating 10-stop presence/absence data
    i1 = ifelse(dplyr::select(., Stop1:Stop10) %>% rowSums(na.rm = TRUE) > 0, 1, 0),
    i2 = ifelse(dplyr::select(., Stop11:Stop20) %>% rowSums(na.rm = TRUE) > 0, 1, 0),
    i3 = ifelse(dplyr::select(., Stop21:Stop30) %>% rowSums(na.rm = TRUE) > 0, 1, 0),
    i4 = ifelse(dplyr::select(., Stop31:Stop40) %>% rowSums(na.rm = TRUE) > 0, 1, 0),
    i5 = ifelse(dplyr::select(., Stop41:Stop50) %>% rowSums(na.rm = TRUE) > 0, 1, 0)
  ) %>%
  dplyr::select(rteno, Year, AOU, i1:i5)

# Total number of observations across all segments
iOut <- bbsData %>%
  mutate(fCount = i1 + i2 + i3 + i4 + i5)

###
# Exporting ####
###

write.csv(iOut, "C:\\Input\\BBSProcessedData.csv", row.names = F)