#!/bin/bash
#SBATCH -t 6:00:00
#SBATCH --nodes 1
#SBATCH --export=NONE
#SBATCH --mail-user=kramsey@uri.edu
#SBATCH --mail-type=BEGIN,END,FAIL

#this script will convert bam alignment files into bedGraph format 


cd /data/kramseylab/sam/2106_RNA-Seq_sam/

for f in *.sam;

do
        PREFIX="${f%.sam}"
	DIRPATH=/data/kramseylab/bam/2106_RNA-Seq_bam
	
	#Convert sam to bam

	module load SAMtools/1.3.1-foss-2016b
	
	samtools view -bT /data/kramseylab/genomefiles/NC_007880_short.fasta -o $DIRPATH/$PREFIX.bam /data/kramseylab/sam/2106_RNA-Seq_sam/$PREFIX.sam
	samtools sort -o $DIRPATH/$PREFIX\-sorted.bam /data/kramseylab/bam/2106_RNA-Seq_bam/$PREFIX.bam 
	samtools index $DIRPATH/$PREFIX\-sorted.bam

	rm /data/kramseylab/bam/2106_RNA-Seq_bam/$PREFIX.bam

	module unload SAMtools/1.3.1-foss-2016b

	#Convert bam to bedGraph
       	module load BEDTools/2.27.1-foss-2018b


	bedtools genomecov -bg -du -split -strand - -trackline -trackopts 'name='$PREFIX'_plus color=0,0,255' -ibam $DIRPATH/$PREFIX-sorted.bam -g /data/kramseylab/genomefiles/LVS_genomefile.txt > $DIRPATH/tracks/$PREFIX\_plus.bedGraph
	bedtools genomecov -bg -du -split -strand + -trackline -trackopts 'name='$PREFIX'_minus color=255,0,0' -ibam $DIRPATH/$PREFIX-sorted.bam -g /data/kramseylab/genomefiles/LVS_genomefile.txt > $DIRPATH/tracks/$PREFIX\_minus.bedGraph

	module unload BEDTools/2.27.1-foss-2018b

shift
done

