### Remove last features
rm(list=ls())

### Dowload libraries
install.packages("devtools")
library(devtools)

###Download source file
source("http://bioconductor.org/biocLite.R")
biocLite("qvalue")
install_github("whitlock/OutFLANK")

### Install OutFLANK package
library(qvalue)
library(OutFLANK)

### Prepare the input file in terminal
# Convert vcf file to 012 file
vcftools --vcf 13688snps-582ind.recode.vcf --012 --out 13688snps-582ind.012.txt
# Replace the -1 by 9 in the 012 file

# Remove the first column
awk '{$1=""; print substr($0,1)}' 13688snps-582ind.012.txt > SNPmat.txt

# Take the loci name
cut -f 2 13688snps-582ind.012.txt.012.pos > loci_names.txt

### Download input dataframe SNPmat
SNPmat <- read.table("SNPmat.txt")
locusNames <- seq(from=1, to= 13688, by=1)
popNames <- c(replicate(31,"ANT"), replicate(23,"BON"),replicate(34,"BOO"),replicate(23,"BRA"), replicate(36,"BRO"),replicate(34,"BUZ"),replicate(31,"CAN"),replicate(26,"CAP"),replicate(36,"CAR"), replicate(30,"GAS"),replicate(30,"LOB"),replicate(29,"MAL"),replicate(34,"MAR"),replicate(36,"OFF"),replicate(33,"RHO"),replicate(33,"SEA"),replicate(32,"SID"),replicate(18,"SJI"),replicate(33,"TRI"))
  
FstDataFrame <- MakeDiploidFSTMat(SNPmat,locusNames,popNames)

### Do the analysis with trim of 0.05
OFoutput <- OutFLANK(FstDataFrame, LeftTrimFraction=0.05,RightTrimFraction=0.05, Hmin=0.1, 19,qthreshold=0.05)
write.table(OFoutput, "Output_0.5_0.1_19pop.txt", quote=F)

### Do the analysis with trim of 0.1
OFoutput <- OutFLANK(FstDataFrame, LeftTrimFraction=0.1,RightTrimFraction=0.1, Hmin=0.1, 19,qthreshold=0.05)
write.table(OFoutput, "Output_0.5_0.1_19pop_without_trim.txt", quote=F)


OutFLANKResultsPlotter(OFoutput, withOutliers = TRUE, NoCorr = TRUE, Hmin = 0.1, binwidth = 0.005, Zoom =FALSE, RightZoomFraction = 0.05, titletext = NULL)
OutFLANKResultsPlotter(OFoutput, withOutliers = TRUE, NoCorr = TRUE, Hmin = 0.1, binwidth = 0.005, Zoom =TRUE, RightZoomFraction = 0.05, titletext = "Zoom = TRUE")