kml_folder <- "shapefiles/antonygreen_kml"

list_kml <- list.files(path=kml_folder, pattern=".kml")

missing_election_years <- c(1993, 1996, 1998, 2001)

for (file in list_kml) {
  seat <- sub(".kml", "", file)
  
  output_seat <- seat
  if(seat == "MelbournePorts") { output_seat <- "Melbourne Ports" }
  out_folder <- paste("shapefiles/seats/", output_seat, sep="")
  
  path_kml <- paste(kml_folder, "/", file, sep="")
  
  seat_poly <- readOGR(path_kml, seat)
  print(as.vector(names(seat_poly)))
  
  list_polys <- as.vector(seat_poly$Name)
  
  for (poly in list_polys) {
    year_range <- sub(" [B|b]oundaries", "", poly)
    year_list <- as.numeric(strsplit(year_range, "-")[[1]])
    
    if (length(year_list) == 2) {
      if (year_list[2] < 100) {
        year_list[2] <- year_list[2] + floor(year_list[1]/100)*100
      }
    }
    
    write_years = missing_election_years[which((missing_election_years >= min(year_list)) &  (missing_election_years <= max(year_list)))]
    
    for (year in write_years) {
      year_poly <- seat_poly[which(seat_poly$Name == poly), ]
      
      filename <- paste(out_folder, "/", as.character(year), ".shp", sep="")
      if (!file.exists(filename)) {
        writeOGR(year_poly, out_folder, as.character(year), driver="ESRI Shapefile")
      }
      
    }
  }
}
