.WaveDuration <- function(x, case, threshold, min.conseq){
  if(case == 'heat') {a <- which(x > threshold)} else { a <- which(x < threshold)}
  durations <- lengths(split(a, cumsum(c(TRUE, diff(a)!=1))))
  if (max(durations) < min.conseq) {duration <- 0
  } else {
    duration <- sum(durations[durations >= min.conseq])
  }
  return(duration)
}
WaveDuration <- function(x, case, threshold, min.conseq = 5, indices){
  tapply(x, INDEX = indices, FUN = .WaveDuration, case = case, threshold = threshold, min.conseq = min.conseq)
}