#setwd("/home/swamp2/cacsgrad/smr5476/Desktop/Physionet/my-entry")  ## CACS
#setwd("C:\\Users\\shaaban\\Google Drive\\Physionet\\my-entry") ## Laptop
#setwd("C:\\Users\\sradwan\\Google Drive\\Physionet\\my-entry")   ## CBIT, Windows
Classify <- function(test_record){
test_record <- paste(test_record ,".wav", sep="")
suppressWarnings(suppressMessages(library("tuneR",verbose=FALSE, warn.conflicts=FALSE, quietly=TRUE)))
avg.cycle.length <<- 2000
min.cycle.length <<- 800
max.cycle.length <<- 3000
sufficent.cycles <<- 2
scale.down.factor <<- 1           # reduce frequency factor 4:1 => (2000 Hz -> 500 Hz)
Eps               <<- 5           # tolerance when looking for highest value in a complet cycle of sequence
normal   <<- -1
abnormal <<- 1
training.folder           <<- "training-c"
training.files.pattern    <<- "*.wav"
training.labels.pattern   <<- "*"

#source("KNN2.R")
if(!exists("k.nearest.neighbors2", mode="function")) source("KNN2.R")
#source("Preprocess.R")
if(!exists("Preprocess", mode="function")) source("Preprocess.R")

xxx <- PreprocessTrainingData(training.folder)
training.dataset <- xxx[[1]]
label.dataset <- xxx[[2]]
rm(xxx)

## Read the test sequence, a single record
test.dataset <- PreprocessTestSequence(test_record)

## Classify
get_sequence_pair_distance <- function(seq1, seq2, method) {
  if (method=="ACF"){
    x <- acf(seq1, plot=FALSE)$acf[,1,1]
    y <- acf(seq2, plot=FALSE)$acf[,1,1]
    d <- dist(rbind(x,y), method = "euclidean")
  }
  d[1]
}

dis.matrix.ACF <- matrix(0, ncol(test.dataset), ncol(training.dataset))
for(i in 1:ncol(test.dataset)){
  #print (i)
  for(j in 1:ncol(training.dataset)){
    dis.matrix.ACF[i,j] <- get_sequence_pair_distance(test.dataset[,i], training.dataset[,j],"ACF")
  }
}
label <- pred.ACF <- knn_test_function2(t(training.dataset), t(test.dataset), dis.matrix.ACF, label.dataset, k = 1)
#label
write.table(cbind(sub(".wav","",test_record), label), file="answers.txt", row.names = FALSE, col.names = FALSE, append = TRUE, sep=",", quote = FALSE)
}

###########
args = commandArgs(trailingOnly=TRUE)
Classify(args[1])
