# 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 "./bigwig.sh infile outtag bam/bed sorted/none genome strand/none [-split]"
 exit
fi

f=$1
outf=$2
extension=$3
sorted=$4
genome=$5
strand=$6
split=$7
i=i
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 $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...=>' $outf.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...=>' $outf+.bw
  bedGraphToBigWig $f+.bedgraph $genome $outf+.bw
  echo 'making bigwig file for - strand...=>' $outf-.bw
  bedGraphToBigWig $f-.bedgraph $genome $outf-.bw
 fi

# remove intermediate files
if [ $sorted != sorted ]
  then
   rm $f
fi
rm $f*.bedgraph

