# 文件名
DIR=$1
SAMPLE=$2
SUFFIX=$3
BAMFILE="${DIR}/${SAMPLE}${SUFFIX}"
WGSEXTPATH="/home/linyize/WGSExtractv4"

mkdir tmp/${SAMPLE}

# hg19格式化
#samtools view -H ${BAMFILE} | sed "s/SN:chr1/SN:1/g; s/SN:chr2/SN:2/g; s/SN:chr3/SN:3/g; s/SN:chr4/SN:4/g; s/SN:chr5/SN:5/g; s/SN:chr6/SN:6/g; s/SN:chr7/SN:7/g; s/SN:chr8/SN:8/g; s/SN:chr9/SN:9/g; s/SN:chr10/SN:10/g; s/SN:chr11/SN:11/g; s/SN:chr12/SN:12/g; s/SN:chr13/SN:13/g; s/SN:chr14/SN:14/g; s/SN:chr15/SN:15/g; s/SN:chr16/SN:16/g; s/SN:chr17/SN:17/g; s/SN:chr18/SN:18/g; s/SN:chr19/SN:19/g; s/SN:chr20/SN:20/g; s/SN:chr21/SN:21/g; s/SN:chr22/SN:22/g;" | samtools reheader - ${BAMFILE} > tmp/${SAMPLE}/${SAMPLE}_reheader.bam
#BAMFILE="tmp/${SAMPLE}/${SAMPLE}_reheader.bam"

samtools index ${BAMFILE}
bcftools mpileup --ignore-RG -T ${WGSEXTPATH}/reference/microarray/All_SNPs_GRCh37_ref.tab.gz -f ${WGSEXTPATH}/reference/genomes/hs37d5.fa.gz -Ou ${BAMFILE} | bcftools call --ploidy-file ${WGSEXTPATH}/reference/microarray/ploidy.txt -V indels -m -P 0 --threads 16 -Oz -o tmp/${SAMPLE}/CombKit_called.vcf.gz
tabix -p vcf tmp/${SAMPLE}/CombKit_called.vcf.gz
bcftools annotate -Oz -a ${WGSEXTPATH}/reference/microarray/All_SNPs_GRCh37_ref.tab.gz -c CHROM,POS,ID tmp/${SAMPLE}/CombKit_called.vcf.gz > tmp/${SAMPLE}/CombKit_annotated.vcf.gz
tabix -p vcf tmp/${SAMPLE}/CombKit_annotated.vcf.gz
bcftools query -f '%ID	%CHROM	%POS[	%TGT]\n' tmp/${SAMPLE}/CombKit_annotated.vcf.gz -o tmp/${SAMPLE}/CombKit_result.tab
sed 's/chr//; s/	M	/	MT	/g; s/\///; s/\.\.$/--/; s/TA$/AT/; s/TC$/CT/; s/TG$/GT/; s/GA$/AG/;     s/GC$/CG/; s/CA$/AC/' tmp/${SAMPLE}/CombKit_result.tab | sort -t $'	' -k2,3 -V > tmp/${SAMPLE}/CombKit_result_sorted.tab

cat ${WGSEXTPATH}/reference/microarray/raw_file_templates/head/23andMe_V3.txt tmp/${SAMPLE}/CombKit_result_sorted.tab > tmp/${SAMPLE}/${SAMPLE}_CombinedKit.txt
#python3 /Users/sra/WGSExtractv3/program/aconv.py 23andMe_V5 tmp/${SAMPLE}_CombinedKit.txt tmp/${SAMPLE}

zip -mj ${DIR}/${SAMPLE}_CombinedKit.zip tmp/${SAMPLE}/${SAMPLE}_CombinedKit.txt

rm -rf tmp/${SAMPLE}

