#!/bin/sh

# Print out a bar-chart to demonstrate the density of fixed bugs.
#
# Syntax: barchart <bugfile> [<bar-width>]
#
# Martin N Dunstan (martin@nag.co.uk)


# Store the base name of this script
PROG=`basename $0`


# Assume maximum chunk length of 240 characters.
sixty="############################################################"
hashes="${sixty}${sixty}${sixty}${sixty}"


# Default values
src_file=/dev/null
bar_width=10


# Check the command-line arguments
case $# in
   0)
      echo "Not enough arguments." 1>&2
      echo "Syntax: $PROG <bugfile> [<barwidth>]" 1>&2
      exit 1
      ;;
   1)
      src_file=$1
      ;;
   2)
      src_file=$1
      bar_width=$2
      ;;
   *)
      echo "Too many arguments"
      echo "Syntax: $PROG <bugfile> [<barwidth>]" 1>&2
      exit 1
      ;;
esac


# Check the file exists and is readable.
if [ ! -r $src_file ]
then
   echo "*** Cannot open '$src_file' for reading." 1>&2
   exit 1
fi


# Check the specified bar width.
if [ $bar_width -gt 240 ]
then
   echo "*** Maximum bar width is 240." 1>&2
   exit 1
fi

if [ $bar_width -lt 2 ]
then
   echo "*** Minimum bar width is 2." 1>&2
   exit 1
fi


# Count the number of lines.
tot_lines=`wc -l $src_file | awk '{print $1}'`


# Process the file in chunks
start=1
chunk=$bar_width
while [ $start -lt $tot_lines ]
do
   # Compute the end of this chunk.
   finish=`echo "$start $chunk +1-p" | dc`


   # How many lines are marked?
   fixed=`tail +$start $src_file |
             head -$chunk |
             grep '[[][*][]]' |
             wc -l |
             tr -d ' '`


   # What is the number of the first bug in the range (reverse listing)
   sfix=`tail +$finish $src_file |
            head -1 |
            sed -e 's/^[ ]*\([0-9]*\) .*$/\1/'`


   # What is the number of the last bug in the range (reverse listing)
   efix=`tail +$start $src_file |
            head -1 |
            sed -e 's/^[ ]*\([0-9]*\) .*$/\1/'`


   # Compute the start and end labels (right justified)
   slab=`echo "    $sfix" | sed -e 's/^.*\(....\)$/\1/'`
   elab=`echo "    $efix" | sed -e 's/^.*\(....\)$/\1/'`


   # Compute the bar.
   if [ $fixed -gt 0 ]
   then
      bar=`echo "$hashes" | cut -c -$fixed`
   else
      bar=""
   fi


   # Output the labelled bar
   echo "${slab}-${elab}: $bar"


   # Move to the next chunk.
   start=`echo "$finish 1+p" | dc`
done


# Finished
exit 0
