library(emuR)
library(ggplot2)
library(wrassp)

# load the database: you can download this database from: http://www.phonetik.uni-muenchen.de/%7Ejmh/lehre/Rdf/ae_emuDB.zip
file.path(mypath, "ae_emuDB")
ae.db = load_emuDB(file.path(mypath, "ae_emuDB"))
summary(ae.db)

# all segments
alle.s = query(ae.db, "Phonetic=~.+")
# segment list of [ai, ei]
dip.s = query(ae.db, "Phonetic = ai | ei")

# wav-files
dip.wav = get_trackdata(ae.db, dip.s, "MEDIAFILE_SAMPLES", resultType = "tibble")

# figure, wav-file of the first segment (starting from time 0)
temp = dip.wav$sl_rowIdx == 1
ggplot(dip.wav[temp,]) + 
  aes(y = T1, x = times_rel) + 
  geom_line()
# figure, wav-file of the first segment (original start and end times)
ggplot(dip.wav[temp,]) + 
  aes(y = T1, x = times_orig) + 
  geom_line()

# figure, wav-files all segments
ggplot(dip.wav) + 
  aes(y = T1, x = times_rel) + 
  geom_line() + 
  facet_wrap(~sl_rowIdx)

# Calculation of f0 using library(wrassp)

# list of the wav files
wav_paths = list_files(ae.db, "wav")$absolute_file_path

# function in wrassp to calculate f0
ksvF0(wav_paths)
# this is to establish what the extension is
wrasspOutputInfos[["ksvF0"]]

# verify that there are f0 files after executing the above ksvF0() command
list_files(ae.db, "f0")$absolute_file_path

# tell the Emu that there are such f0-signals for this database
add_ssffTrackDefinition(ae.db, "grund", "F0", "f0")
summary(ae.db) 
#or
list_ssffTrackDefinitions(ae.db)
# f0-data for the segment list dip.s
dip.f0 = get_trackdata(ae.db, dip.s, "grund", resultType = "tibble")

# f0-figure of first segment...
temp = dip.f0$sl_rowIdx == 1
ggplot(dip.f0[temp,]) + 
  aes(y = T1, x = times_rel) + 
  geom_line()

# of all segments
ggplot(dip.f0) + 
  aes(y = T1, x = times_rel) + 
  geom_line() + 
  facet_wrap(~sl_rowIdx)

# ensemble plot of f0 for [ai, ei]
ggplot(dip.f0) + 
  aes(y = T1, x = times_rel, col = dip.f0$labels, group=sl_rowIdx) + 
  geom_line()

# calculate the formants with library(wrassp)
forest(wav_paths)

# check what the extension is
wrasspOutputInfos[["forest"]]

# verify the files exist
list_files(ae.db, "fms")$absolute_file_path

# tell Emu that there are such files and incorporate them into the database
add_ssffTrackDefinition(ae.db, "formant", "fm", "fms")

summary(ae.db) 
#or
list_ssffTrackDefinitions(ae.db)

# Formant-Data für dip.s
dip.fm = get_trackdata(ae.db, dip.s, "formant", resultType = "tibble")

# ensemble plot of F1 for [ai, ei] as a function of time
ggplot(dip.fm) + 
  aes(y = T1, x = times_rel, col = labels, group=sl_rowIdx) + 
  geom_line()


# ensemble plot of F1 and/or F2 as a function of time

# F1 and F2 at the temporal midpoint

# Calculation of tracks on 'on the fly'




