#!/bin/sh

TMP=${TMP-/tmp}

nmfile=$TMP/mpr.nm.$$
sedfile=$TMP/mpr.sed.$$
logfile=$TMP/mpr.log.$$
flfile=

fileopt=
fofiles=
lineopt=
ignoreopt=
noparm=

I=,

while test $# -gt 0; do
	case "$1" in
		-p)	noparm=-p;;
		-f)	fileopt=true;;
		-F )	fileopt=true; fofiles=$2; shift;;
		-F*)	fileopt=true; fofiles=`echo $1 | sed 's/-F//'`;;
		-l)	lineopt=true;;
		-i )	ignoreopt=$2; shift;;
		-i*)	ignoreopt=`echo $1 | sed 's/-i//'`;;
		-I )	I=$2; shift;;
		-I*)	I=`echo $1 | sed 's/-I//'`;;
		--)	shift; break;;
		-*)	echo "mpr: ignoring unknown option $1" >&2;;
		*)	break;;
	esac
	shift
done

if test $# -ne 1; then
	echo "usage: mpr [-p] [[-f|-F foo.c,bar.c] [-l]] [-Ix] [-i foo,bar,..] a.out <mpr.log" >&2
	exit 1
fi

if test "$fileopt" != ""; then
	flfile=$TMP/mpr.fl.$$
fi

status=1
set -e

# reliably clean up after ourselves
trap 'set +e; rm -f $nmfile $logfile $sedfile $flfile; trap 0; exit $status' 0 1 2 15

>$sedfile
mprnm $noparm -- $1 >$nmfile

# this sucks, but both mprfl and mprmap need to read mpr.log
# (we compress it just in case mpr.log is huge)
gzip >$logfile

if test "$fileopt" != ""; then
	gzip -dc $logfile | mprfl $1 "$fofiles" >$flfile
	if test "$lineopt" = ""; then
		echo "s/,[0-9]*):/):/g" >>$sedfile
	fi
fi

echo $ignoreopt |

# spaghetti courtesy of C++ (sigh)

sed -e 's/\*/\\*/g'	\
    -e 's/\^/\\^/g'	\
    -e 's/\//\\\//g'	\
    -e 's/\[/\\[/g'	\
    -e 's/\]/\\]/g'	|

awk -F$I '{
	for (i=1; i<=NF; i++) {
		printf "s/:%s+*:/:/\n", $i
		printf "s/:%s([^:]*):/:/\n", $i
	}
}' >>$sedfile

gzip -dc $logfile | mprmap $nmfile $flfile |

# Please note that the quality of your sed(1) could make
# an enormous difference to the runtime of the command below.
# For example, SCO's sed is horrendously slow. In that case,
# either replace your sed, or replace with the following less
# general command that should be equivalent to the current one
# in most cases:
#
# sed -f $sedfile					\
#   -e 's/^m:malloc_hook:malloc:/m:/'			\
#   -e 's/^m:malloc_hook([^:]*):malloc([^:]*):/m:/'	\
#   -e 's/^f:free_hook:free:/f:/'			\
#   -e 's/^f:free_hook([^:]*):free([^:]*):/f:/'		\
#   -e 's/^r:realloc_hook:realloc:/r:/'			\
#   -e 's/^r:realloc_hook([^:]*):realloc([^:]*):/r:/'

sed -f $sedfile				\
    -e 's/^m.*:malloc:/m:/'		\
    -e 's/^f.*:free:/f:/'		\
    -e 's/^r.*:realloc:/r:/'		\
    -e 's/^m.*:malloc([^:]*):/m:/'	\
    -e 's/^f.*:free([^:]*):/f:/'	\
    -e 's/^r.*:realloc([^:]*):/r:/'

status=0	# trap handles exit
