load("C:/Users/David/Desktop/BiOp 9/PWC Runs/useList.df")

filedir<-choose.dir(default="C:/Users/David/Desktop/BiOp 9/PWC Runs/",caption="Select folder with PWC outputs")
dayfiles<-list.files(filedir,pattern="*daily.csv",full.names=TRUE,recursive=TRUE)

chem_eecs<-data.frame(array(dim=c(0,11)))
names(chem_eecs)<-c("File","HUC2","Bin","Scenario","Crop Description","Year","Peak","1-day","4-day","21-day","60-day")

for (i in 1:length(dayfiles)) {

	csv_fullpath<-dayfiles[i] # select csv file
	# csv_fullpath<-"~/Desktop/BiOp 9/PWC Runs/Test Runs/run_25_2_GrasslandESA7_Custom_Parent_daily.csv" # select csv file
	# csv_fullpath<-file.choose() # select csv file
	
	csv_file<-basename(csv_fullpath)
	csv_path<-dirname(csv_fullpath)
	
	t1<-unlist(strsplit(csv_file,"_"))
	esaindex<-grep("ESA",t1)
	t2<-unlist(strsplit(t1[esaindex],"ESA"))
	
	HUC2<-t2[2]
	Bin<-t1[esaindex-1]
	if (t2[1]=="Impervious") {
	  Scenario<-"Developed"
	} else {
	  Scenario<-uselist.df[grep(t2[1],uselist.df$scenario),1] 
	}
	CropDescription<-t1[2]
	
	zts_file<-paste0(paste(t1[1:(esaindex-1)],collapse="_"),".zts")
	zts_fullpath<-file.path(csv_path,zts_file)
	
	csv<-read.csv(csv_fullpath,header=FALSE,skip=5)
	zts<-read.table(zts_fullpath,skip=3) # read zts file
	
	dayeec<-csv[,2]*10^6 # convert to ppb
	
	runoff<-10^9*(zts$V6/zts$V4) # calculate runoff and convert to ppb
	runoff[is.nan(runoff)]<-0
	
	avg<-c(4,21,60)
	daily<-cbind(zts[,1],runoff)
	for (j in 1:length(avg)) {
		daily<-cbind(daily,filter(runoff,rep(1/avg[j],avg[j]),sides=1))
	}
	
	daily<-cbind(daily,dayeec)
	for (j in 1:length(avg)) {
		daily<-cbind(daily,filter(dayeec,rep(1/avg[j],avg[j]),sides=1))
	}
	
	daily<-data.frame(daily) # convert to data.frame from default of timeseries
	colnames(daily)<-c("yr","r1","r4","r21","r60","b1","b4","b21","b60")
	
	yrPks<-aggregate(daily[,2:9],by=list(daily[,1]),function(x) max(x,na.rm=TRUE))
	names(yrPks)[1]<-"yr"
	
	temp_eecs<-data.frame(csv_file, HUC2, Bin, Scenario, CropDescription, yr=1:30, Pk=-1, yrPks[,6:9])
	names(temp_eecs)<-c("File","HUC2","Bin","Scenario","Crop Description","Year","Peak","1-day","4-day","21-day","60-day")
	
	if (Bin==2) {
		runoff_eecs<-data.frame(csv_file, HUC2, B="0", Scenario, CropDescription, yr=1:30, Pk=-1, yrPks[,2:5])
		names(runoff_eecs)<-c("File","HUC2","Bin","Scenario","Crop Description","Year","Peak","1-day","4-day","21-day","60-day")
		temp_eecs<-rbind(temp_eecs,runoff_eecs)
	}

  chem_eecs<-rbind(chem_eecs,temp_eecs)
	print(paste0(i,":",length(dayfiles)))
  
}

# write.csv to save chem_eecs as input file without row names
# write.csv(chem_eecs,file="C:/Users/David/Desktop/BiOp 9/PWC Runs/bromoxynil_oct_nonag_eec.csv", row.names=FALSE)
