###################################################################################################################
# This R script compiles winddendro and measureJ2X files into one file
# Author: Logan Berner, OSU
# Date: Nov 4th, 2015
###################################################################################################################
rm(list=ls())
options(stringsAsFactors=FALSE)
require(dplR)
setwd("")
source('code/fun_compile_windendro2.R')
source('code/fun_compile_rwl.R')

# WinDendro files
f.win <- list.files('ringwidth_mmnts/windendro/', full.names = T)
rw.win <- compile.windendro.files(f.win, 1400,2013)

# Velmex files
f.vel <- list.files('ringwidth_mmnts/velmex/', full.names = T)
ids <- gsub(".rwl","",list.files('ringwidth_mmnts/velmex/', full.names = F))
rw.vel <- compile.rwl.files(f.vel,ids,1400,2013)

# Combine files
rw.dat <- cbind(rw.win,rw.vel)
all.na <- as.vector(which(apply(rw.dat, 1, function(x){as.vector(all(is.na(x)))}))) # trim tailing NAs
rw.dat <- rw.dat[-all.na,] 
rw.dat <- rw.dat[,order(colnames(rw.dat))] # order the series 

rw.dat <- cbind(data.frame(year=as.numeric(rownames(rw.dat))), rw.dat)

# Output combined measurements  
write.table(rw.dat, 'ringwidth_mmnts/treering_mmnts_combined.csv', sep=',', row.names = F, col.names = T)