#Requires bam files and bed file containing coordinates of peaks of interest
#Generates filtered bams and library size file to upload into Galaxy

#required arguements:
#($1): bam file
#($2): bed file containing regions of interest

#Usage: filter_bam /pathtofolder/ qPCR_peaks.bed

#outputs:
#Filtered bam files containing reads in regions of interest
#read_counts: txt file containing number of mapped reads in each bam file, used for normalization

bam_file=$1
peak_file=$2
chrom_sizes=$3
ext_peak_file=$4
filtered_bam_file=$5
read_counts=$6
name=$7

bedtools slop -i $peak_file -g $chrom_sizes -b 2000 | sort -k1,1 -k2,2n - > $ext_peak_file

samtools index $bam_file

samtools view -c -F 1284 $bam_file > count
echo $name > name
paste name count > $read_counts

#create bed file of fragments for each bam file

samtools view -b -F 4 -L $ext_peak_file $bam_file > $filtered_bam_file

rm name
rm count
