#!/bin/sh
# Known bugs: Doesn't cope with NL embedded in notes
count=`sed -e 's/^$/�/' -e 's/[^�]/ /g' $1 | tr -d '\n' | \
  tr ' ' '\n' | fgrep -c '�����'`
if [ $count -gt 0 ]; then
    echo $count instances of a block of more than four blank lines
    exit 1
fi
three=`sed -e 's/^$/�/' -e 's/[^�]/ /g' $1 | tr -d '\n' | \
  tr ' ' '\n' | fgrep -c -x '���'`
cat $1 > denote.in
while read handled; do
    count=`fgrep -c "$handled" denote.in`
    if [ "$count" -eq 0 ]; then
	echo "Handled note ($handled) does not appear"
	exit 1
    fi
    pattern=`echo $handled | sh escape.sh`
    case $handled in
	[\*\**)
	    sed -e "s/\(..*\)$pattern/\1/g" -e "s/$pattern\(..*\)/\1/g" \
	      denote.in > denote.tmp
	    count=`fgrep -c "$handled" denote.tmp`
	    if [ "$count" -eq 0 ]; then
		mv denote.tmp denote.in
	    else
		sed "s/$pattern//" denote.tmp > denote.in
		count=`sed -e 's/^$/�/' -e 's/[^�]/ /g' denote.in | tr -d '\n' | \
		  tr ' ' '\n' | fgrep -c -x '���'`
		if [ $count -ge $three ]; then
		    sed "/$pattern/d" denote.tmp > denote.in
		    count=`sed -e 's/^$/�/' -e 's/[^�]/ /g' denote.in | tr -d '\n' | \
		      tr ' ' '\n' | fgrep -c -x '���'`
		    if [ $count -ge $three ]; then
			echo "Can't decide whether to delete NL at end of note:"
			echo "$handled"
			exit 1
		    fi
		fi
		three=$count
	    fi
	    ;;
	*)
	    replacement=`echo $handled | sed 's/\[\*\*[^]]*\]//'`
	    sed "s/$pattern/$replacement/" denote.in > denote.tmp
	    mv denote.tmp denote.in
	    ;;
    esac
done < denote.handled
if [ $three -gt 0 ]; then
    echo denote.in: $three instances of a block of three blank lines
    exit 1
fi
sed -e 's/\[\*\*not clear\]/[**unclear]/g' denote.in > $2
