# Once as many known electorate shapefiles are present in the shapefiles/seats folders, copy the oldest
# shapefile for each seat backwards in time until you hit a redistribution.

states <- c("NSW", "QLD", "VIC", "TAS", "SA", "WA", "ACT", "NT")
redist_years <- list()
redist_years[[1]] <- c(2009, 2006, 2000, 1992)
redist_years[[2]] <- c(2009, 2006, 2003, 1997, 1994, 1992)
redist_years[[3]] <- c(2010, 2003, 1994, 1989)
redist_years[[4]] <- c(2009, 2000, 1992)
redist_years[[5]] <- c(2011, 2003, 1999, 1992)
redist_years[[6]] <- c(2008, 2000, 1997, 1989)
redist_years[[7]] <- c(2005, 1997, 1994, 1992)
redist_years[[8]] <- c(2008, 2000)

seat_shp_folder <- "shapefiles/seats"
seats <- list.dirs(path=seat_shp_folder, full.names=F)
seats <- seats[-which(seats=="")]

# Load the booth data:
years <- c(1993, 1996, 1998, 2001, 2004, 2007, 2010, 2013)

for (cal_year in years) {
  print(sprintf("Loading data, %d", cal_year))
  seatboothfile_str <- sprintf("booths_data/%d.csv", cal_year)
  boothfile_str <- sprintf("booths_summing_dups/%d.csv", cal_year)
  if (cal_year == years[1]) {
    seatbooth.data <- read.csv(file=seatboothfile_str, header=T, sep=",")
    
    seatbooth.data <- seatbooth.data[, !(names(seatbooth.data) %in% c("TCP_1", "TCP_2"))]
    
    seatbooth.data$Year <- cal_year
  } else {
    temp.data <- read.csv(file=seatboothfile_str, header=T, sep=",")
    
    # Remove the TCP columns from the main data frame:
    temp.data <- temp.data[, !(names(temp.data) %in% c("TCP_1", "TCP_2"))]
    
    temp.data$Year <- cal_year
    
    seatbooth.data <- merge(seatbooth.data, temp.data, all=T)
    rm(temp.data)
  }
}

# Convert factors to strings:
i <- sapply(seatbooth.data, is.factor)
seatbooth.data[i] <- lapply(seatbooth.data[i], as.character)



for (seat in seats) {
  indices_seat <- which(seatbooth.data$Seat == seat)
  this_state <- seatbooth.data$State[floor(median(indices_seat))]
  seat_folder <- sprintf("%s/%s", seat_shp_folder, seat)
  shp_files <- list.files(seat_folder, pattern=".shp")
  shp_years <- as.numeric(sub(".shp", "", shp_files))
  
  if (length(shp_files) > 0) {
    this_redist_years <- redist_years[[which(states==this_state)]]
    copyfrom_year <- min(shp_years)
    prev_redist <- max(this_redist_years[which(this_redist_years < copyfrom_year)])
    if (length(prev_redist) == 0) {
      prev_redist <- 1900
    }
    
    copyto_years <- years[which((years > prev_redist) & (years < copyfrom_year))]
    copyfrom_files <- list.files(seat_folder, pattern=as.character(copyfrom_year))
    
    for (year in copyto_years) {
      for (copyfrom_file in copyfrom_files) {
        path_from <- sprintf("%s/%s", seat_folder, copyfrom_file)
        path_to <- sub(as.character(copyfrom_year), as.character(year), path_from)
        file.copy(path_from, path_to)
      }
    }
  }
}