targetsize=${1-100000}
savefile=$HOME/Save.Audit
if ps | grep -v grep | grep -s Sqpe
	then echo "Do not run TRUNC_AUDIT while S-PLUS is running"; exit 1;
	fi

# set args to the possible S working directories (with an unreadable sentinal)
if test "${S_WORK}x" = x
	then echo S_WORK not defined; exit 1
	fi
IFS=":"
set $S_WORK /junk/junk
for file
do
	if test -f $file/.Audit -a -r $file/.Audit; then break; fi
done

file=$file/.Audit
if test ! -r $file
	then echo "Can not find audit file or it did not have read permission"; exit 1
	fi
if test ! -w $file
	then echo "Can not write audit file ($file)"; exit 1
	fi

echo "Truncating audit file ($file) to most recent $targetsize characters"
if test "${targetsize}x" != x -a "${targetsize}" -eq 0
	then : >$file
	echo "Audit file reset"; exit 0
	fi 
if test -r $savefile
	then echo "Already have a $savefile"; exit 1
	fi
filesize=`wc -c $file|sed -e "s/^ *//" -e "s/ .*//"`
chopat=`expr $filesize - $targetsize`
if test $chopat -lt 0
	then echo "Audit file is currently only $filesize characters"; exit 0
	fi
sleep 10
_POSIX2_VERSION=199209 tail +${chopat}c $file |
	sed "1,/^#/d" |
	sed -n '/^[^#]/,$p' >$savefile ||
	( echo "editing failed, audit file not changed"; rm $savefile; exit 1 )

actualsize=`wc -c $savefile|sed -e "s/^ *//" -e "s/ .*//"`
if test `expr $targetsize - $actualsize` -gt 2000
	then
		echo "Problem with truncating: you requested $targetsize"
		echo "Processing produced $actualsize -- Audit file not changed"
		rm $savefile
		exit 1
	fi
echo "Audit file truncated to $actualsize characters"
mv $savefile $file || (echo "Could not replace audit file ($file)"; rm $savefile)
