#!/usr/bin/perl
#
# Threadize infile outfile
# Threadize dir outfile
#
# This is a filter that converts dbgized code to the  form  used  with
# pthreads.  The basic problem here is that everything involving stdio
# MUST  be  surrounded  by  calls  of   pthread_lock_global_np()   and
# pthread_unlock_global_np(),  or  a  horrible  death  rresults.   The
# dbg*msg() routines inherit this problem.  And due to the  fact  that
# the  C  preprocessor  can't  deal with macros with varying number of
# args, we can't define our D*() and P*() macros to look exactly  like
# simple function calls.  So we transform them to look like
#   D4 fmt,v1,v2,...  D;
# where D4 and D generate an "if(dbglvl>=4)", the lock call, a call on
# dbgdmsg, the arg list, and the unlock call. See dbg.h for the rather
# hairy definitions of the D* macros.
#
# This was originally a simple filter, but that turned  out  difficult
# to use in makefiles. So you may now call it with two args, which are
# the files to read and write.  If the first arg is  a  directory,  we
# read  dir/outfile.  This is done so that we can move the source to a
# .save directory, and then easily point at the files there.

$S = 0;		# State variable, for tracking multi-line messages.
if ($in = $ARGV[0]) {
	if (-d $in) {$in = $in . '/' . $ARGV[1]}
	open(STDIN,"<$in") || die "$0: Can't read \"$in\" [$!]\n";
}
if ($out = $ARGV[1]) {
	open(STDOUT,">$out") || die "$0: Can't write \"$out\" [$!]\n";
}
for (<STDIN>) {
	if ($S == 1 && /^(.*)\);(.*\s)$/) {
		print "$1 D; $2";
		$S = 0;
	} elsif (/^(:?[0-9a-z]?\s*)([DPV]\d\w?)\((.*)\);(.*\s)$/) {
		print "$1$2 $3 D;$4";
	} elsif (/^(:?[0-9a-z]?\s*)([DPV]\d\w?)\((.*\s)$/) {
		print "$1$2 $3";
		$S = 1;	# Inside multi-line message.
	} else {
		print;
	}
}
