#!/bin/sh
#2/19/2023
#author:Chiteri
#pass in the annotation and gwas files
gnm7_models="./vigra.VC1973A.gnm7.ann1.RWBG.gene_models_main.gff3.gz"
gwas="./dtf_farmcpu_gwas_results.txt"

#Alternative is to use Vigna radiata GBrowse at LegumeInfo.

#sort the gwas with p-values (column 4, k4)
#Remember to switch this columns as per your data
#the awk prints the header first and sorts everything after and take top 5 SNPs
#You can CHANGE here depending on how many SNPs you want
topSnp="$(cat $gwas | awk '$2!~/scaffold/ && $4!~/NA/' | awk 'NR<2{print $0;next}{print$0 | "sort -g -k4,4"}' | \
awk -v OFS="\t" 'NR>1 {print $0}'|head -n 5)"

#test to confirm the file is what you expect it to be
#echo "$topSnp" | awk -v OFS="\t" '{print NF;exit}'
#echo "$topSnp" | awk -v OFS="\t" '{print $0}' 
#echo "$topSnp"

#The script below extracts the genes for the significant SNPs of interest.
##LD in this population if ~290kb
#save LD in a variable
ld=290000
#echo "$ld"
##################
#This loops through the snp_file provided
#Takes the snps and searches in the annotation file
#The output will include: 
#gene	snp	chr	start	stop	Name	Note(description)

#remove files if exists..to avoid cumulative addition if you rerun script
rm -rf snp_tempfile || true
rm -rf snp_tempfile.txt || true

#SNP	Chr	Pos	P.value	MAF	nobs	H&B.P.Value	Effect

while IFS=$'\t' read -r SNP Chr Pos Pvalue MAF nobs HBPValue effect; 
do
zcat "$gnm7_models" | sed 's/vigra.VC1973A.gnm7.chr//g' | \
awk '$1!~/^#/ && $1!~/scaffold/ && $3~/gene/{print $1, $3, $4, $5, $9}'| \
awk -v OFS='\t' -v snp="$SNP" -v gnm7c="$Chr" -v gnm7p="$Pos" -v d="$ld" '{n=split($5,arr,";");\
printf "%s ", snp; printf "%s ",$1; printf "%s ", gnm7p;printf "%s ", $2; printf "%s ", $3; printf "%s ",$4; printf "%s ",($4-$3);\
for(i in arr) if(arr[i]~/Name|Note/){ printf "%s ", arr[i]}; print "\t"}' | sed 's/Name=//g; s/Note=//g' | \
awk -v OFS='\t' -v gnm7c="$Chr" -v gnm7p="$Pos" -v d="$ld" ' ($2==gnm7c) && $5>= (gnm7p-d) && $6 <= (gnm7p+d)'>> snp_tempfile
done <<< "$topSnp"



#add header to identify columns
cat snp_tempfile |awk '$9!~/unchara|Unknown|unk|hypothe/'| \
awk 'BEGIN {print "SNP", "Chr", "Pos", "Marker", "Start", "Stop", "Size(bases)", "Name", "Description"}1' > snp_tempfile.txt

rm snp_tempfile