#####

  ### Run these lines first time to install packages flowCore and flowFP
  #source("http://bioconductor.org/biocLite.R")
  #biocLite('flowCore','flowFP')

############
library(flowCore)
library(flowFP)

source('writeGedata2.R')

resdir <- '~'
  # Directory where to save resulting .gedata file
datadir <- '/Users/johnsson/Forskning/Data/flowRepository'#'~' 
  # Parent directory for data from Flow Repository
flowID <- "FR-FCM-ZZYA"
dirpath <- file.path(datadir, flowID)
fcs.file.names <- list.files(dirpath, pattern='.*\\.(FCS|fcs)')
meta.data <- read.csv(file.path(dirpath, 'AML.csv'),stringsAsFactor = FALSE)

### Read data and put in one data frame
subsamp.size <- 2000 # Nbr events sampled from each file
frames <- lapply(file.path(dirpath,fcs.file.names), read.FCS, dataset = 1,
                 which.lines = sample(1:3000, subsamp.size))
names(frames) <- sapply(frames, identifier)
fs <- as(frames, "flowSet")

### Compile annotations
fcs.names <- phenoData(fs)@data$name
sample.annotations <- meta.data[match(fcs.names, meta.data$FCS.file),]

### Fingerprinting using flowFP
ffp <- flowFP(fs)
fingerprint <- counts(ffp)

### Bin (gate) annotations
bin.annotations <- data.frame(id=1:dim(fingerprint)[2])
for (p in parameters(ffp)) {
  lower.left <- sapply(binBoundary(ffp),function(boundary) {boundary@ll[p]})
  upper.right <- sapply(binBoundary(ffp),function(boundary) {boundary@ur[p]})
  bin.annotations[paste(p,"lower left")] <- lower.left
  bin.annotations[paste(p, "upper right")] <- upper.right
}

### Export to Qlucore format
writeGedata2(t(fingerprint), bin.annotations, t(sample.annotations),
             varAnnotsHeaders = names(bin.annotations), 
             sampleAnnotsHeaders = names(sample.annotations),
             file.path(resdir,paste0("fingerprintAML_n",length(fs),".gedata")))
