# Input: 	file.name: Name of the file  (like "Flute")
# 			file.direktory: name of the direktory containing 5 subdirectories: mat, mid, midiOriginal, times and wav (like "C:/MyData")
# Output: 	event.frame

# Example: 	The subdirectory "C:/MyData/midiOriginal"  should contain the original midi file, like Flute.mid
#			Flute.midi file produced by Matlab will be saved in "C:/MyData/mid"
#			Flute.mat file produced by Matlab will be saved in "C:/MyData/mat"
#			Flute.txt file with the true onset times will be saved in "C:/MyData/times"


# NOTE: Just first 60 seconds of original midi files are considered!

readMidiMatlab=function(file.name, file.direktory)
{
  library(R.matlab) 
  Matlab$startServer()
  matlab <- Matlab()
  isOpen <- open(matlab)
  
  evaluate(matlab, sprintf("a='%s';",file.name))
  evaluate(matlab, sprintf("cd %s/midiOriginal", file.direktory))
  evaluate(matlab, "m = readmidi2(sprintf('%s.mid', a));")  
  evaluate(matlab, "m2 = midiInfo(m,0);")
  
  # correct: take just first 60 s as MIDI TO WAVE Converter can convert just 60 s
  evaluate(matlab, "kor=m2((m2(:,6)<60),:);")
  
  # bag of Matlab 
  # correct the channel
  evaluate(matlab, "ch=0; l=length(unique(kor(:,2))); u=unique(kor(:,2)); for i=1:l; id_i=(kor(:,2)==u(i));  kor(id_i,2)=ch; ch=ch+1; end;")
  
  # correct the track
  evaluate(matlab, "tr=2; l=length(unique(kor(:,1))); u=unique(kor(:,1));for i=1:l;id_i=(kor(:,1)==u(i));kor(id_i,1)=tr; tr=tr+1;end")
  evaluate(matlab, "if length(unique(kor(:,2)))==1; kor(:,1)=1; end")
  
  # if readmidi has some errors, cut before first error
  evaluate(matlab, "f=find(kor(:,8)<0);")
  evaluate(matlab, "if length(f)~=0; kor = kor(1:(f(1)-1),:); end")
  evaluate(matlab, "mm=matrix2midi(kor);")
  
  evaluate(matlab, sprintf("cd %s/mid", file.direktory))
  evaluate(matlab, "writemidi(mm,sprintf('%s.mid', a));")

  # save the corrected mat file
  evaluate(matlab, sprintf("cd %s/mat", file.direktory))
  evaluate(matlab, "save(sprintf('%s.mat', a),'kor');")
  
  # save true times as txt file using R, as some problems with matlab
  evaluate(matlab, "t=kor(:,5);")
  evaluate(matlab, "ut=unique(t);")
  data1 = getVariable(matlab, c("ut"))
  write.table(data1$ut, 
              file = sprintf("%s/times/%s.txt", file.direktory, file.name),
            row.names = FALSE, col.names = FALSE)
  
  close(matlab)
 
  data.mat=readMat(sprintf("%s/mat/%s.mat", file.direktory, file.name))
  
  # transform mat file to event.frame
  event.frame=mat2eventFrame(data.mat)
  return(event.frame)
}