# **************************
# set of functions used in other places
parsename <- function(fn) {
  fn<-basename(fn)
  t1<-unlist(strsplit(fn,"_"))
  esaindex<-grep("ESA",t1)
  t2<-unlist(strsplit(t1[esaindex],"ESA"))
  tmp<-paste(t1[1:(esaindex-2)],collapse="_") 
  output<-list(huc=t2[2],scenario=t2[1],bin=t1[esaindex-1],run=tmp)
  return(output)
}

meanci <- function(X1, conf = 95) {
  lenX1 <- length(X1)
  X195 <- qt(1 - (100 - conf)/200, df = lenX1 - 1) * sqrt(var(X1))/sqrt(lenX1)
  output <- c(lower.ci = mean(X1) - X195, upper.ci = mean(X1) +X195)
  return(output)
}

dist95 <- function(X1) {
  lower05 <- qnorm(0.05,mean = mean(X1), sd = sd(X1))
  upper95 <- qnorm(0.95,mean = mean(X1), sd = sd(X1))
  output <- c(lower05, upper95)
  return(output)
}
  
quant95 <- function(X1) {
  output<-quantile(X1,c(0.05,0.95))
  return(output)
}

f1in15 <- function(X1) {
  output <- qnorm(14/15,mean = mean(X1), sd = sd(X1))
  return(output)
}

# extract daily eecs from the *daily.csv file into a 3D array
dayeecs <- function(fn) {
	foo<-read.csv(fn,header=FALSE,skip=5) # read SWCC daily
	foo<-foo[,2:4]*10^6 # get peaks and convert to ppb
	foo<-foo[-seq(from=1155, length=7, by=1461),] # omit leap days
	output<-array(dim=c(365,30,3)) # create 3D array for daily eecs (day, year, value)
	for (i in 1:3){
		output[,,i]<-array(foo[,i], dim=c(365,30)) # build array from daily values (avg aqueous, avg benthic, peak aqueous)
	}
	return(output)
}

# extract yearly summaries from a *15_Parent.text
yreecs <- function(fn) {
	tmp<-scan(fn,skip=19) # read yearly summary data from *15_Parent.txt summary file
	tmparr<-array(tmp, dim=c(9,30))
	output<-t(tmparr) # 2D array (30,9) of year on rows and different summaries in columns
}

# extract overall summaries from a *15_Parent.txt file  
runeecs <- function(fn) {
	tmpfile<-readLines(fn,18) # get overall summary lines
	tmpfile<-tmpfile[6:15] # overall summary with each line having the summary value 

	# extract data from each summary line
	measlist <- vector("list",length(tmpfile))
	for (i in 1:length(tmpfile)) {
		l1<-unlist(strsplit(tmpfile[i],"="))
		names(measlist)[i]<-paste0("x",gsub("[ ,-]",".",trimws(l1[1])))	# measurement description w/o spaces, hyphens
		measlist[[i]]<-as.numeric(unlist(strsplit(l1[2]," ppb"))[1]) # measurement value
	}
	output<-measlist
}

# get array of HUC12s from comma delimited list of range
getHUC <- function(id) {
	tempHUC<-speciesHUC.df[speciesHUC.df$EntityID==id,2]
	output<-as.numeric(gsub("\\D","",unlist(strsplit(tempHUC,","))))
	return(output)
}

# get array of HUC12s from comma delimited list of critical habitat 
getHabitatHUC <- function(id) {
	tempHUC<-habitatHUC.df[habitatHUC.df$EntityID==id,2]
	output<-as.numeric(gsub("\\D","",unlist(strsplit(tempHUC,","))))
	return(output)
}