#!/bin/sh

POST_BIN=${LIBEXEC_DIR-/usr/pkg/bin}

####################################################### Print error and die.
error()
{
    echo $@ 1>&2
    exit 1
}

#################################################### Run a process or abort.
run()
{
    $* || error "$1 failed!"
}

########################################################### Start of script.
# Must have exactly one argument.
if [ "$1" = "" -o "$2" != "" ] ; then
    cat << ENDUSAGE 1>&2

Yodl2man-post 1.31.18

Usage: yodl2man-post FILE
This script must be started by yodl2man or yodl2ms.
ENDUSAGE
    
    exit 1
fi

# Have yodlfixlabels fix the labels and refs,
# remove leading spaces and empty lines in the inputfile. 
# Then, have awk delete multiple .PP or .IP lines.
# After that, again, remove empty lines.
run $POST_BIN/yodlfixlabels -onepass -protectdot $1 $1.$$
$POST_BIN/yodlfixlabels -labels -tableofcontents $1.$$ - | \
$POST_BIN/yodlfixlabels -onepass -roff - - | \
awk '
{
    if ($1 == ".LP")                            # .LP encountered
    {
        ipseen = 0;                             # .IP then .LP -> .LP
        ppseen++;
        lastlp = $0;
    }
    else if ($1 == ".IP")                       # .IP encountered
    {
        ppseen = 0;                             # .LP then .IP -> .IP
        ipseen++;
        lastip = $0;
    }
    else                                        # other text
    {
        if (ppseen)
            print lastlp;
        else if (ipseen)
            print lastip;

        ppseen = 0;
        ipseen = 0;
        print;
    }
}' | \
$POST_BIN/yodlfixlabels -onepass -removeblank - $1 || \
					error "postprocessing failed!"

run rm -f $1.$$

