#!/bin/sh

CALGARY=/home/sitkarev/Downloads/calgary
filelist="bib book1 book2 geo obj1 obj2 news paper1 paper2 paper3 paper4 \
	  paper5 paper6 pic progc progl progp trans"
faillist=""

function md5digest
{
  md5sum $1 | cut -f 1 -d ' '
}

function do_benchmark
{
  local totalsize=0
  local comprsize=0
  local rate=0

  for file in $filelist
  do
    file="${CALGARY}/${file}"
    tmp=`tempfile`
    cat ${file} | ./encode -r 2>/dev/null > ${tmp}
    totalsize=$((totalsize + `stat -c %s ${file}`))
    comprsize=$((comprsize + `stat -c %s ${tmp}`))
    rm -f ${tmp}
  done
  
  rate=`echo -e "scale=3; ${totalsize}/${comprsize}" | bc`

  printf "total size %d, compressed size %d\n" ${totalsize} ${comprsize}
  printf "compression rate %s\n" ${rate}
}

for file in $filelist
do
  file="${CALGARY}/${file}"
  digest=`md5digest ${file}`

  # Check MD5 sum with compression with finalization of the last read only.
  digest2=`cat ${file} | ./encode 2>/dev/null | \
	  ./decode 2>/dev/null | md5digest -`
  if [ ${digest} != ${digest2} ]
  then
    echo "MD5 sum test0 failed on ${file}: "
    echo "   ${digest} != ${digest2}"
    if [ -z "${faillist}" ]; then
      faillist=`basename ${file}`
    else
      faillist="${faillist} `basename ${file}`"
    fi
  fi

  # Check MD5 sum with compression with each read finalized.
  digest2=`cat ${file} | ./encode -i 2>/dev/null | \
	  ./decode 2>/dev/null | md5digest -`
  if [ ${digest} != ${digest2} ]
  then
    echo "MD5 sum test1 failed on ${file}: "
    echo "   ${digest} != ${digest2}"
    if [ -x "${faillist}" ]; then
      faillist=`basename ${file}`
    else
      faillist="${faillist} `basename ${file}`"
    fi
  fi

done

if [ -n "${faillist}" ]; then
  echo "Failed files:${faillist}"
  exit 1
fi

do_benchmark

exit 0

