# Thresholding the onset detection function

# INPUT: 	odf: onset detection feature
#			ctrl: control object

# OUTPUT: 	t.odf: threshold for odf
threshold=function(odf, ctrl)
{
  n=length(odf)
  th=numeric(n)
  
  n.left=timeToNrOfWindows(ctrl$thresh.time.left,ctrl)
  n.right=timeToNrOfWindows(ctrl$thresh.time.right,ctrl)
  
  if (ctrl$thresh.fun=="mean"){
    lambda = ctrl$thresh.lambda
    l=as.list(1:n)
    th = unlist(lapply(l, function(x){ind = max(x-n.left,1):min(x+n.right,n) ; lambda*mean(odf[ind])+ctrl$thresh.delta}))
  }
  
  if (ctrl$thresh.fun=="median"){
    lambda = ctrl$thresh.lambda
    l=as.list(1:n)
    th = unlist(lapply(l, function(x){ind = max(x-n.left,1):min(x+n.right,n) ; lambda*median(odf[ind])+ctrl$thresh.delta}))
  }
  
  if (ctrl$thresh.fun=="quantile"){
    quant = ctrl$thresh.quantile
    l=as.list(1:n)
    th = unlist(lapply(l, function(x){ind = max(x-n.left,1):min(x+n.right,n) ; quantile(odf[ind],prob=quant)+ctrl$thresh.delta}))
  }
  
  return(t.odf = th)
}