#!/bin/bash

# looping through vcf files
for file1 in *_p2.vcf; do
	base=$(basename $file1 _p2.vcf)
	file2=$base'_p3.vcf'
	cat $file1 | vcf-sort > $file1'.sorted'
	cat $file2 | vcf-sort > $file2'.sorted'
	bcftools reheader --samples p3_samples.txt -o $file2'.new_ID.sorted' $file2'.sorted'
	bgzip -c $file1'.sorted' > $file1'.sorted.gz'
	bgzip -c $file2'.new_ID.sorted' > $file2'.new_ID.sorted.gz'
	tabix -f -p vcf $file1'.sorted.gz'
	tabix -f -p vcf $file2'.new_ID.sorted.gz'
	bcftools merge $file1'.sorted.gz' $file2'.new_ID.sorted.gz' -Oz -o $base'.comb.vcf.gz'
	bgzip -d $base'.comb.vcf.gz'
	sed 's/\.\/\./0|0/g' $base'.comb.vcf' > $base'.comb.noNA.vcf'
	rm $base'.comb.vcf'
	bgzip -c $base'.comb.noNA.vcf' > $base'.comb.noNA.vcf.gz'
	rm $base'.comb.noNA.vcf'
	# indexing vcf files
	tabix -f -p vcf $base'.comb.noNA.vcf.gz'
	# calculating Fst in 80,001 bp windows
	vcftools --gzvcf $base'.comb.noNA.vcf.gz' --weir-fst-pop p2_samples.txt --weir-fst-pop p3_samples.txt --fst-window-size 80001 --fst-window-step 80001 --out $base'.80001.noNA.fst'
	rm $file1'.sorted'
	rm $file2'.sorted'
	rm $file2'.new_ID.sorted'
	rm $file1'.sorted.gz'
	rm $file2'.new_ID.sorted.gz'
	rm $file1'.sorted.gz.tbi'
	rm $file2'.new_ID.sorted.gz.tbi'
done
