# make bigwig file for genome browser visulization
# usage
# makebigwig.sh <infilename> <outfile> bedorbam sorted genome strand -split
# input file types: *.bed, *.bam

# use of output: move to public_html and visualize in ucsc genome browser with the following:
# track name="xxx" color=0,0,255 type=bigWig bigDataUrl=http://rous.mit.edu/~wuxbl/xxx.bw

if [ $# -lt 6 ]
then 
 echo "./makebigwig.sh infile outfile bedorbam sorted genome [-split -strand]"
 exit
fi

f=$1
outf=$2
extension=$3
sorted=$4
genome=$5
strand=$6
split=$7
i=i
echo 'genome:' $genome
echo 'strand:' $strand

if [ $extension = bam ]
then
 i=ibam
 if [ $sorted != sorted ]
 then 
   echo 'sorting bam file...=>' $f.sorted.bam
   samtools sort $f $f.sorted
   f=$f.sorted.bam
 fi
else
 if [ $sorted != sorted ]
 then
   echo 'sorting bed file...=>' $f.sorted.bed
   sort -k1,1 -k2,2g $f > $f.sorted.bed
   f=$f.sorted.bed
 fi
fi

 echo 'making bedgraph file...=>' $f.bedgraph 
 if [ $strand != strand ]
 then
  genomeCoverageBed -bg -$i $f -g $genome $split > $f.bedgraph
  echo 'making bigwig file...=>' $f.bw
  bedGraphToBigWig $f.bedgraph $genome $outf
 else
  genomeCoverageBed -bg -$i $f -g $genome $split -strand + > $f+.bedgraph
  genomeCoverageBed -bg -$i $f -g $genome $split -strand - > $f-.bedgraph
  echo 'making bigwig file for + strand...' $f+.bw
  bedGraphToBigWig $f+.bedgraph $genome $outf+
  echo 'making bigwig file for - strand...=>' $f-.bw
  bedGraphToBigWig $f-.bedgraph $genome $outf-
 fi
 rm $f

