#!/bin/bash

if [ $# -lt 1 ]
	then
		echo "No options found!"
		exit 1
fi
usageHelp="Usage: ${0##*/} [-o out directory] [-g genome directory] [-b bedGraph file] \n"
printHelpAndExit() {
    echo -e "$usageHelp"
	exit "$1"
}

while getopts "o:g:b:h" opt; do
    case $opt in
	o)outdir=$OPTARG ;;
	g)genome=$OPTARG ;;
	b)bgfile=$OPTARG ;;
	h) printHelpAndExit 0;;
	*) echo "No reasonable options found!" && exit 1;;
	esac
done

windowsizes=(5000)
stepsizes=(10)
bgtype="[50-50].OpChr"

outdir=$(realpath $outdir)
genome=$(realpath $genome)
bgfile=$(realpath $bgfile)



for winsize in ${windowsizes[*]}; do 
	for stsize in ${stepsizes[*]}; do
		#bedtools makewindows -g ~/files/references/galGal5/galGal5.rg.chromsizes -w $winsize -s $stsize | gzip -9 -c > ~/files/references/galGal5/galGal5_mask_w${winsize::-3}k_s${stsize}bp.bed.gz
		bedtools map -a ${genome}/galGal5_mask_w${winsize::-3}k_s${stsize}bp.bed.gz -b $bgfile -c 4 -o mean -null "0" > ${outdir}/merged_mean_w${winsize::-3}k_s${stsize}bp${bgtype}.bedGraph
		awk -v wnsz=${winsize} -v stsz=${stsize} '{if (($3-$2) >= wnsz) {ev=($2+$3)/2; $2=ev-stsz/2; $3=ev+stsz/2; print $0}}' ${outdir}/merged_mean_w${winsize::-3}k_s${stsize}bp${bgtype}.bedGraph > ${outdir}/merged_mean_w${winsize::-3}k_s${stsize}bp_norm${bgtype}.bedGraph
		bedGraphToBigWig ${outdir}/merged_mean_w${winsize::-3}k_s${stsize}bp_norm${bgtype}.bedGraph ${genome}/galGal5.rg.chromsizes ${outdir}/merged_mean_w${winsize::-3}k_s${stsize}bp_norm${bgtype}.bw
		rm ${outdir}/merged_mean_w${winsize::-3}k_s${stsize}bp${bgtype}.bedGraph ${outdir}/merged_mean_w${winsize::-3}k_s${stsize}bp_norm${bgtype}.bedGraph
	done
done

