#!/bin/sh

# NOTE: "freeing unalloced mem" msgs are sent to stderr
# (a questionable feature since the malloc library shd detect this) 

AWK=${AWK-awk}

if test $# -ne 0 -a $# -ne 1; then
	echo "usage: mprlk [log]" >&2
	exit 1
fi

MPRFILTER=`mprfilter mprlk "$@"` || exit 1

$MPRFILTER |

$AWK -F: '
	/^m/ {	if ($NF)
			malloc[$NF]=sprintf("%d:%s", NR, $0) }

	/^f/ {	if ($NF && !malloc[$NF])
			printf "mprlk: %s (NR=%d)\n", $0, NR |"cat 1>&2"
		delete malloc[$NF] }

	/^r/ {	if ($(NF-1) && !malloc[$(NF-1)]) {
			printf "mprlk: %s (NR=%d)\n", $0, NR |"cat 1>&2"
			delete malloc[$(NF-1)]
		}
		if (!$(NF-2) || $NF)
			delete malloc[$(NF-1)]
		if ($NF)
			malloc[$NF]=sprintf("%d:%s", NR, $0) }

	END  {	for (i in malloc)
			print malloc[i] }' |

sort -n -t: | cut -d: -f2- |

$AWK -F: '
	/^m/ { if ($(NF-1)) print }
	/^r/ { if ($(NF-2)) print }'

exit 0
