#!/bin/sh

# Find the path used to start the script. It is used for other scripts.
pgmpath=`dirname $0`
pgmpath=`cd $pgmpath > /dev/null 2>&1  &&  pwd`

# Get name of program to test.
pgm=$1
shift

# Exit if valgrind does not exist.
which valgrind > /dev/null 2>&1
if [ $? != 0 ]; then
    echo "*** memcheck of $pgm cannot be done; valgrind cannot be found ***" 1>&2
    exit 1
fi

# Use valgrind's memcheck tool on a program.
# Filter out possible errors to give an overview.
rm -f ${pgm}_tmp.valgrind
valgrind --tool=memcheck --num-callers=50 --ignore-range-below-sp=1024-1 --leak-check=yes --track-fds=yes --suppressions=$pgmpath/casacore_memcheck.supp --log-file=${pgm}_tmp.valgrind $pgm "$@"

# Check if any error, definite or possible leak, or open fd is found.
# If so, list the file and rename to keep it.
# Note that fd 0,1,2 are always open (stdin,stdout,stderr).
# Furthermore 3 and/or 4 can be open for the valgrind log file and
# the ctest output.
errors=`(grep "ERROR SUMMARY: " ${pgm}_tmp.valgrind | grep -v " 0 errors ") || echo ""`
deflost=`(grep "definitely lost: " ${pgm}_tmp.valgrind | grep -v " 0 bytes ") || echo ""`
poslost=`(grep "possibly lost: " ${pgm}_tmp.valgrind | grep -v " 0 bytes ") || echo ""`
openfds=`(grep " Open file descriptor " ${pgm}_tmp.valgrind | grep -v "descriptor [01234]:") || echo ""`
if test "$errors" != "" -o "$deflost" != "" -o "$poslost" != "" -o "$openfds" != "";
then
    cat ${pgm}_tmp.valgrind >> $pgm.checktool.valgrind
fi
rm -f ${pgm}_tmp.valgrind
