#! /bin/sh

# clean up mined position marker file @mined.mar

verbose=false

minclean () {
	LC_CTYPE=C
	export LC_CTYPE
	egrep -n "." @mined.mar | 
	sed -e 's,:, ,' | sort -r +1 -2 +0rn -1 | 
	sed -e 's,^[^ ]* \([^ ]*\) \(.*\)$,\2 \1,' | uniq -f 3 | 
	sed -e 's,^\(.*\) \([^ ]*\)$,\2 \1,' > @mined.mmm
	/bin/mv @mined.mar @mined.bak

	if $remove
	then
		while read line
		do	set - $line
			if [ -f "$1" ]
			then	echo $*
			fi
		done < @mined.mmm > @mined.mar
		/bin/rm @mined.mmm
	else
		/bin/mv @mined.mmm @mined.mar
	fi

	ls -l @mined.bak @mined.mar
	rm -f @mined.bak
	}

if [ "$1" = "-" ]
then	remove=true
	shift
else	remove=false
fi
export remove

for d in ${*-.}
do	if [ -d $d ]
	then	if [ -f $d/@mined.mar ]
		then	$verbose && echo tidying $d/@mined.mar
			(cd $d; minclean)
		else	echo no @mined.mar in $d
		fi
	else	if [ "`basename $d`" = "@mined.mar" ]
		then	if [ -f $d ]
			then	$verbose && echo tidying `dirname $d`/@mined.mar
				(cd `dirname $d`; minclean)
			else	echo $d does not exist
			fi
		else	echo $d not touched
		fi
	fi
done
