# F-Measure
fMeasure=function(true.times, estim.times, ctrl) # trime time in sec and estimated time in sec, delay
{
  n = length(true.times) # number of true onsets
  c = 0

  fn = 0
  fp = 0
  toler = ctrl$tolerance
  orig.estim = estim.times
 
  if (length(estim.times) == 0) {
    c = 0
    fn = n
    fp = 0
    } else{
      for (i in 1:n)
      {
        w=which(estim.times>=(true.times[i]-toler) &  estim.times<=(true.times[i]+toler)) 
        if (length(w)!=0) { 
          c = c+1 
          estim.times=estim.times[-w[1]] 
        } 
        else {
          fn = fn+1
        }
      }
      fp=length(estim.times)
    }
      
  fMeas=(2*c)/(2*c+fn+fp)
  return(list(c=c,fn=fn,fp=fp,fMeasure=fMeas))
}
  
# D-Measure
dMeasure=function(true.times, estim.times, time.end)
{
  # g=estim.times # estim times
  # t.t=true.times  #
  if (length(estim.times) == 0){
    abw = (max(true.times)/2)*length(true.times)
  }else{
    n.estim=length(estim.times) # number estimated onsets
    n.true=length(true.times)
    w.t=NULL # counter for true onsets which were already merged
    abw=0
    
    for (i in 1:n.estim) # compute deviation to the nearest true onset
    {
      w=which.min(abs(estim.times[i]-true.times))
      abw=abw+min(abs(estim.times[i]-true.times))
      w.t=c(w.t,w)
    }
    
    f.n=(1:length(true.times))[-w.t] # false negative: true osets without merge
    
    if(length(f.n)!=0){
      
      for (i in 1:length(f.n)){
        if(f.n[i] == 1){                  # if the first true onset is not merged
          absence = abs(true.times[f.n[i]+1] - true.times[f.n[i]]) / 2 # middle of the first and second onset minus 0 (here not written)
          abw = abw + absence    
        }else{
          if(f.n[i] == n.true){          # if the last onset is not merged
            absence = time.end - abs(true.times[f.n[i]-1] - true.times[f.n[i]]) / 2 # time.end - difference between the last and last but one onset
            abw = abw + absence
          } else{
            middlie.time.right = true.times[f.n[i]] + abs(true.times[f.n[i]+1] - true.times[f.n[i]]) / 2
            middlie.time.left = true.times[f.n[i]] - abs(true.times[f.n[i]-1] - true.times[f.n[i]]) / 2
            absence = abs(middlie.time.right-middlie.time.left)/2
            abw = abw + absence
          }
        }
      }
    }  
    
    
  }
  dMeas=abw/(time.end*length(true.times))              
  return(dMeas)
}
    