#!/bin/bash

OUTPUT="$1"
INPUT="$2"

if [ -z "$OUTPUT" -o -z "$INPUT" ]; then
	echo "Usage: $0 output input"
	exit 1
fi

NUM_FRAGS=`grep '^NUM_FRAGS' "$INPUT"     | awk -F "=" '{print $2}'`
BUCKET_SIZE=`grep '^BUCKET_SIZE' "$INPUT" | awk -F "=" '{print $2}'`
export GDFONTPATH=/usr/share/fonts/truetype/segoe/

rm -rf /tmp/fhist.$$
(cat << EOF
set terminal png small size 1200, 1400 font "SegoeRg" 9
set key below box
set grid
set title 'Histogram of file sizes/fragments'
set output '$OUTPUT'
set xrange [ $BUCKET_SIZE : * ]
set logscale x 2
set y2tics border
set xlabel 'File Size'
set ylabel 'Sizes (%)'
set y2label 'Fragments (%)'
plot \\
EOF
for i in `seq 1 $NUM_FRAGS`; do
cat << EOF
'$INPUT' using (\$1 + $((BUCKET_SIZE / 2))):(\$$((i + 3)) / \$2) t '$i Fragments' axes x1y2 with points, \\
EOF
done
for i in `seq 1 $NUM_FRAGS`; do
cat << EOF
'$INPUT' using (\$1 + $((BUCKET_SIZE / 2))):(\$$((i + 3)) / \$2) notitle smooth bezier axes x1y2 with lines, \\
EOF
done
cat << EOF
'$INPUT' using (\$1 + $((BUCKET_SIZE / 2))):(\$2 / \$3) t 'File Size' axes x1y1 with linespoints lw 2
EOF
) > /tmp/fhist.$$
gnuplot /tmp/fhist.$$
rm -rf /tmp/fhist.$$

exit 0
