#
# This R code was used to draw formant graph / calculate Euclidean data in:
# http://www.languagebits.com/?p=785
#
# Romeo Mlinar <mlinar [a] languagebits.com>
#
# License: GPL 3
#

DrawDiphMovementJoinedByLen <- function(flen='s'){
  #
  # Draw the starting and the ending vowel of a diphthong,
  # marked with an arrow.
  # 
    # Length in title
    if (flen == 's'){
      plen <- 'short diphthongs'
      s.ref.1 <- res.fpi.refs1
      s.ref.2 <- res.fpi.refs2
      s.cor.1 <- res.fpi.cors1
      s.cor.2 <- res.fpi.cors2
      s.ref <- res.fpi.refs
    }
    else {
      plen <- 'long diphthongs'
      s.ref.1 <- res.fpi.refl1
      s.ref.2 <- res.fpi.refl2
      s.cor.1 <- res.fpi.corl1
      s.cor.2 <- res.fpi.corl2
      s.ref <- res.fpi.refl
    }
    # Compile title
    title <- paste("Target movements in corpora",
                   "\n(", plen, ")", sep='')

     DrawPlotFormants(title=title, sdata=s.ref)

    legend(2600, 830,
         c('Referent data', 'Corpus data'),
         cex=0.9,
         lty=c(1, 2))

     DrawMovement(sdata1=s.ref.1, sdata2=s.ref.2, lt=1)
     DrawMovement(sdata1=s.cor.1, sdata2=s.cor.2, lt=2)
  }

DrawMovement <- function(sdata1, sdata2, lt=1){
  #
  # Draw the 1st and the 2nd element of the diphthong,
  # joined by an arrow.
  #
  points(sdata1$f2, sdata1$f1, pch=substr(sdata1$ipa, 1, 1))
  points(sdata2$f2, sdata2$f1, pch=substr(sdata2$ipa, 2, 2))
  segments(x0=sdata1$f2, y0=sdata1$f1,
           x1=sdata2$f2, y1=sdata2$f1,
           par(lty=lt))
  arrows(sdata1$f2, sdata1$f1,
         sdata2$f2, sdata2$f1,
         length  = 0.15)
  par.default <- par(no.readonly=TRUE)
}

DiphthongDistance <- function(fq1, fq2){
  #
  # Calculate distances between A with coordinates (F1, F2) and
  # B (F1, F2) for each diphthong.
  #
  # fq1 - first target frequencies
  # fq2 - second target frequencies
  #
  if (nrow(fq1) != nrow(fq2)){
    stop("Number of rows must be same.")
  }

  # Coordinates
  x1 <- fq1$f1
  y1 <- fq1$f2

  x2 <- fq2$f1
  y2 <- fq2$f2

  #Labels

  ascii <- substr(fq1$ascii, 1, 4)
  ipa <- substr(fq1$ipa, 1, 3)

  distance <- c()

  for (i in (1:nrow(fq1))){
    d <- euc.dist2(fd[,i][1], fd[,i][2], fd[,i][3], fd[,i][4])
    distance <- c(distance, as.numeric(d))
  }

  frame.distance <- data.frame(ascii=ascii,
                               ipa=ipa,
                               dist=round(distance, 2))

  return(frame.distance)
}

euc.dist2 <- function(x1, y1, x2, y2){
  #
  # The Euclidean distance for two dimensions.
  #
  return(sqrt((x1-x2)^2+(y1-y2)^2))
}