################################################################################
# This script takes location data (i.e. latitude/longitude) and outputs:
#   1. data files with estuary, watershed, and National Wetlands Inventory information
#   2. kml files to view in GoogleEarth
#
# Requirements: - a .csv file with latitude/longitude coordinates in decimal degrees
#               - R statistical program (downloaded from: http://cran.r-project.org/bin/windows/base/)
#               - Google Earth
#               - R packages: rgdal, sp, maptools (directions below)
#
# Geographic extent: Estuaries and watersheds for the U.S. Pacific Coast from
#                    Northern Washington to Southern California.  It does not include estuaries
#                    in Puget Sound or islands off the coast.
#
# Citation:  M.R. Frazier, D.A. Reusser, H. Lee, L.M. McCoy, C. Brown and W. Nelson. 2013.
#            WestuRe: US Pacific Coast Estuary/Watershed Data and R Tools.
#            U.S. EPA
#
# See the data viewer at: Coming Soon!
###############################################################################S

# The following commands can be cut and paste into the R workspace.
# A more advanced method is to use a data editor such as RStudio (http://rstudio.org/)
# Anything proceeded by "#" is ignored by R.


#---------------------------------------------------------------------------
# STEP 0: You only need to do this once!  You will need to install the
#         following packages to do these analyses. Once they are installed,
#         they will be saved on your computer. The next time you run this script
#         you will not need to reinstall these packages.

install.packages(c("rgdal", "sp", "maptools"))

# You will be asked to select a CRAN mirror (this is where the packages come from).
#   Just pick a location close to you, this doesn't matter too much.
# --------------------------------------------------------------------------



#-------------------------------------------------------------------------
# STEP 1: Establish the directory path to the WestuRe folder. 
#         This will be the location on your computer where the WestuRe file 
#         has been saved.
#         NOTE: Make sure that folders are separated by double backslashes,
#               and that the path is in quotes.

setwd("C:\\Documents and Settings\\mfrazi03\\Desktop\\WestuRe_v1")

#  NOTE: your specific file directory will be different!
#--------------------------------------------------------------------------



#--------------------------------------------------------------------------
# STEP 2: Direct R to the WestuRe tools in the WestuRe folder:

source("RTools\\functions.R")

# NOTE: assuming you correctly established the working directory in STEP 1
#       no changes are necessary here.
#---------------------------------------------------------------------------



#--------------------------------------------------------------------------
# STEP 3: Import your data. Your data must be saved as a csv file and the
#         latitude/longitude values must be in decimal degrees.  The "<-" can
#         be thought of as equals.  It will assign the name "MyData" to the
#         imported data.

MyData <- read.csv("C:\\Documents and Settings\\mfrazi03\\Desktop\\WestuRe_v1\\ExampleData.csv")

# NOTE: The file directory to your data will be different!
# NOTE: An example dataset was included in the WestuRe file.  You can use this
#       if you don't have a dataset.
# NOTE: Don't forget to use double back slashes in the file directory!

# Check your data for potential importing errors:

head(MyData) # first 6 rows of data
tail(MyData) # last 6 rows of data
dim(MyData)  # number of rows, number of columns
summary(MyData)
#------------------------------------------------------------------------------


#--------------------------------------------------------------------------
# STEP 4: Run the points2est function.  This function outputs:
#           - The original data with the associated NWI code variable
#           - A summary of the estuary/watershed data for each estuary with data
#           - The estuary/watershed monthly climate data (if requested by user)
#
#         The arguments for this function are:
#           1. data = name of the data that you imported into R (STEP 3)
#           2. lon = name of the longitude variable in your data
#           3. lat = name of the latitude variable in data
#           4. climate = TRUE/FALSE to indicate whether you want the monthly estuary/watershed data
#           5. FileName = name you want for the output data files
#           6. saveDir = file path that describes where to save the output data

MyNewData <- points2est(MyData, lon="x", lat="y", climate=TRUE, FileName="Samples2013", saveDir="C:\\Documents and Settings\\mfrazi03\\Desktop\\WestuRe_v1\\SampleOutput")

# NOTE: Your saveDir will be different, make sure it has double back slashes.
# NOTE: I am naming the points2est object, "MyNewData", but you could name it something else.
# NOTE: After you run this function, you should have 3 new csv files in your saveDir!
#------------------------------------------------------------------------------



#--------------------------------------------------------------------------
# STEP 5: Run the points2kml function.  This function outputs:
#           - kml file of your sample points
#           - kml file of the NWI estuary boundaries
#           - kml file of the watershed boundaries
#
#         The arguments for this function are:
#           1. x = name of the points2est object (Step 5)
#           2. kmlWS = TRUE/FALSE, indicates whether to return watershed data
#           3. kmlNWI = TRUE/FALSE, indicates whether to return NWI data
#           4. IDvar = name of sample identification variable in your data frame object.
#                      This will be used to label the sample points in the kml file.
#                      If you have no ID variable, delete this argument.
#           5. FileName = name you want for the output data files
#           6. saveDir = file path that describes where to save the output data

points2kml(x=MyNewData, kmlWS=TRUE, kmlNWI=TRUE, IDvar="Site", FileName="Samples2013", saveDir="C:\\Documents and Settings\\mfrazi03\\Desktop\\WestuRe_v1\\SampleOutput")

# NOTE: Your saveDir will be different, make sure it has double back slashes.
# NOTE: You should now have up to 3 additional .kml files in your directory.
#       If Google Earth is installed on your computer, you can double click on these
#       files and they will open in Google Earth.
# NOTE: This function may take several minutes if you have data in several estuaries.
# NOTE: "&" symbols will cause kml files to crash
#------------------------------------------------------------------------------




################################################################################
# Additional functionality
################################################################################

# The following code demonstrates how to act with the WestuRe data more directly
# within R. This may be particularly helpful for people with more advanced skills.


#------------------------------------------------------------------------------
# OPTIONAL: Accessing and working with the data generated by points2est

# Directly accessing the datasets and merging the sample and estuary data:
data <- data.frame(MyNewData[[1]])    # original data with associated NWI codes
ests <- MyNewData[[2]]                # estuary/watershed data for each estuary with samples
monthlyClimate <- MyNewData[[3]]      # monthly climate data for each estuary/watershed with samples

head(data)          #provides the first 6 lines of data
head(ests)
head(monthlyClimate)

# Plotting the geographic data:
library(maps)
map("state", c("Washington", "Oregon"))
plot(MyNewData[["watershedPoly"]], add=TRUE, col="gray")
plot(MyNewData[["NWIPoly"]], add=TRUE, col="black")

# Merging the original data with the estuary/watershed scale data
fullData <- merge(data, ests, by="wsID", all.x=TRUE)
#------------------------------------------------------------------------------



#------------------------------------------------------------------------------
# OPTIONAL: Getting estuary data and kml files using estuary name
#           (rather than sample points)

# Follow steps one and two from above:
setwd("C:\\Documents and Settings\\mfrazi03\\Desktop\\WestuRe_V1")
#  NOTE: your file path will be different!
source("RTools\\functions.R")

# Load the full estuary dataset:
estuaryData <- read.csv("Data\\EstuaryData.csv")

# List of estuary names:
sort(estuaryData$estName)

# Identify the estuaries you want data for:
ests <- c("San Diego River Estuary", "Seaside Creek Estuary")

# The names2est function is used.
# This function is similar to the points2est function, but the csv file is replaced by a list of estuary names
MyNewData <- names2est(ests, climate=TRUE, FileName="TestMay2012", saveDir="C:\\Documents and Settings\\mfrazi03\\Desktop\\WestuRe_v1\\SampleOutput")
points2kml(x=MyNewData, kmlWS=TRUE, kmlNWI=TRUE, IDvar="estName", FileName="TestMay2012", saveDir="C:\\Documents and Settings\\mfrazi03\\Desktop\\WestuRe_v1\\SampleOutput")

#------------------------------------------------------------------------------
# OPTIONAL: Saving particular watersheds as SHP files 

# Read the shp file directly
watershed <- readOGR(dsn=".\\Data\\Watershed", layer="Watershed", verbose=FALSE)
plot(watershed)

# Subset the data so it only includes watersheds of interest (can ID these from the watershed file)
new <- watershed[watershed$wsID %in% c("P210x", "P215x01"),]
plot(new)

# save the shp file 
writeOGR(new, "ExampleWatersheds", "ExampleWatersheds", driver="ESRI Shapefile")


