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,12)))
names(chem_eecs)<-c("Pesticide","File","HUC2","Bin","Scenario","Crop Description","Year","Peak","1-day","4-day","21-day","60-day")

zts<-read.table(file.choose(),skip=3) # read zts file
yrs<-zts[,1]

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]
  Pesticide<-t1[5]
  
  if (t1[4]=="Custom") {
    Bin<-2
  } else {
    Bin<-7
  }

  if (t2[1]=="Impervious") {
    Scenario<-"Developed"
  } else {
    Scenario<-uselist.df[grep(t2[1],uselist.df$scenario),1] 
  }
  CropDescription<-t1[2]
  
  csv<-read.csv(csv_fullpath,header=FALSE,skip=5)
 
  dayeec<-csv[,2]*10^6 # convert to ppb
  
  avg<-c(4,21,60)
  daily<-cbind(yrs,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","b1","b4","b21","b60")
  
  yrPks<-aggregate(daily[,2:5],by=list(daily[,1]),function(x) max(x,na.rm=TRUE))
  names(yrPks)[1]<-"yr"
 
  temp_eecs<-data.frame(Pesticide, csv_file, HUC2, Bin, Scenario, CropDescription, yr=1:30, Pk=-1, yrPks[,2:5])
  names(temp_eecs)<-c("Pesticide","File","HUC2","Bin","Scenario","Crop Description","Year","Peak","1-day","4-day","21-day","60-day")
  
  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_ParentDaughter_eec.csv", row.names=FALSE)
