# INPUT:	event.frame: either output of mat2eventFrame or a data frame with the following columns:    
#           	  "track.number", (could be just NA)
#           	  "channel.number", (integer number: channel of the event in the row) 
#           	  "note.number",    (integer number from 0 to 127 (for piano, e.g. from 21 to 107))
#           	  "velocity",       (loudness, integer number from 1 to 100, middle value is 50)
#           	  "start.time",     (strat times in seconds)
#           	  "end.time",       (end time in seconds)
#           	  "message.number.note.on", (unimportant for this application, could be NA's)
#           	  "message.number.note.on" (unimportant for this application, could be NA's)
#
# 			ctrl: MakeRealConverterControl object

# OUTPUT:	wave.object: the wav-object
#			notes.path: path to the notes used for the generation (could be usefull if notes are sampled randomly)



midi2wave=function(event.frame,ctrl)
{
  # pre-proceeding. Remove some rows, which denote notes playing 0 seconds. It happens due some bugs in 
  # readmidi2 function in matlab
  w=which(event.frame$end.time == 0)
  if(length(w) != 0) 
    event.frame = event.frame[-w,]
  
  # number of channels
  nr.chan = length(table(event.frame$channel.number))
  
  # check whether all channels have an instrument
  if(length(ctrl$instruments) != nr.chan) 
    stop("Number of instrumnets is unequal to the number of channels in event.frame")
  
  # number of onsets
  nr.onsets = dim(event.frame)[1]
  
  #length of the complete music piese in samples  
  nr.samples = event.frame$end.time[nr.onsets]*44100
  
  start.point = as.integer(event.frame$start.time[1]*44100+1)

  waves.to.channel = list()
  
  # get event data.frame to each channel
  event.channel = split(data.frame(event.frame),event.frame$channel.number)
  
  # get a wave to each channel
  waves.to.channel = lapply(event.channel,makeTrack,ctrl,nr.samples)
  
  # sum amplitudes of all channels
  common.wave.amplit = 0
  notes.path = list()
  for(i in 1:length(waves.to.channel))
  {
    common.wave.amplit = common.wave.amplit+waves.to.channel[[i]]$channel.wave@left
    notes.path[[i]] = waves.to.channel[[i]]$new.notes.path
  }
  
  # produce the wav
  wave.object<- Wave(left = common.wave.amplit, samp.rate = 44100, bit=16)
  wave.object=tuneR::normalize(wave.object, unit="16")
  
  if(ctrl$wave.to.channel==TRUE) 
    wave.object=c(waves.to.channel, wave.object)

  return(list(wave.object = wave.object, notes.path = notes.path))
}
