# getOdfMatrix computes the onset detection matrix for given settings of control parameters

# INPUT: 	path.wav: path to the wav which has to be analysied
#			path.time: path to the time vector of true onsets
#			ctrl: ctrl object (a list)
# 			feats: a vector of features with has to be calculated for odfMatrix. feats =NULL, all odf features are computed

# OUTPUT:	oM.true: odfMatrix with the additional column of the true onset information ((0,1)-vector)
#			time.end: length of the audio signal in seconds
# 			true.times: vector of the true onset times


getOdfMatrix=function(path.wav, path.time, ctrl, feats = NULL)
{
  # read the wave
  wav=readWave(path.wav)
  
  # normalize the signal amplitude
   if (ctrl$norm == TRUE){
   m = max(abs(wav@left))
   wav@left = wav@left / m
  }
  
  true.times=read.table(path.time)
  true.times=as.numeric(unlist(true.times))
  true.wind=fromTimeToWindow(true.times,ctrl)
  
  fa=fftArray(wav, ctrl) # comute the fourier coeffitients
  fa = specFilter(fa, ctrl)	# apply spectral filtering (optionally)
  fa = specLog(fa, ctrl) # apply spectral logarithming (optionally)
  true.01=numeric(dim(fa$ampl)[2])
  true.01[intersect(true.wind, 1:dim(fa$ampl)[2])]=1 # sometimes there is 1 window more.
  
  wind.left = min(TimeToNrOfWindows(ctrl$odfMatrix.time.left,ctrl),3)
  wind.right = min(TimeToNrOfWindows(ctrl$odfMatrix.time.right,ctrl),3)
  
  if (is.null(feats) == TRUE)
  { 
  # if no feats is given, all features are computed
  odf.Matrix = computeALLFeatures(fa, ctrl)
  }else{
  s = strsplit(feats, "_")
  sel.feat = unlist(lapply(s, function(x)x[1]))
  odf.Matrix = computeSELFeatures(fa, ctrl,sel.feat)
  }

  M = odf.Matrix
  nr = nrow(M)
  nc = ncol(M)
  rownames(M) = as.vector(sapply(rownames(odf.Matrix), function(x) {sprintf("%s_%s",x,"a")}))
  
  
  MBIG = M
  
  
  # go left
  if (wind.left != 0){
    
    M2_pr = M
    for (i in 1:wind.left){
      M2 = cbind(rep(0,nr),  M2_pr) [, 1:nc]
	  if(is.null(dim(M2))==TRUE) {M2 = t(as.matrix(M2))}
      rownames(M2) = as.vector(sapply(rownames(odf.Matrix), function(x) {sprintf("%s_left_%i",x,i)}))
      MBIG = rbind(MBIG, M2)
      M2_pr =  M2
    }
  }
  
  # go right
  if (wind.right != 0){
    
    M2_pr = M
    for (i in 1:wind.right){
      M2 = cbind(M2_pr, rep(0,nr)) [, 2:(nc+1)]
	  if(is.null(dim(M2))==TRUE) {M2 = t(as.matrix(M2))}
      rownames(M2) = as.vector(sapply(rownames(odf.Matrix), function(x) {sprintf("%s_right_%i",x,i)}))
      MBIG = rbind(MBIG, M2)
      M2_pr =  M2
    }
  }
  
  w.nan=which(MBIG %in% c("NaN", "-Inf", "Inf"))
  if (length(w.nan)!=0) 
  MBIG[w.nan]=0
  
 
  oM=as.data.frame(t(MBIG))
  true=as.factor(true.01)
  oM.true=cbind(oM,true)
  
  time.end = (length(wav@left))/ctrl$sampling.rate
  return(list (oM.true =  oM.true, time.end = time.end, true.times = true.times))
}

