#!/bin/sh

####################################################### 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

Yet Oneother Document Language: Man or ms Postprocessor V1.22
Copyright (c) K. Kubat (ICCE) 1996-1997. All rights reserved.
Another MegaHard production!

Usage: yodl2man-post/yodl2ms-post inputfile
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 /usr/local/lib/yodl/yodlfixlabels -onepass -protectdot $1 $1.$$
/usr/local/lib/yodl/yodlfixlabels -labels -tableofcontents $1.$$ - |
/usr/local/lib/yodl/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;
    }
}' | \
/usr/local/lib/yodl/yodlfixlabels -onepass -removeblank - $1 || \
					error "postprocessing failed!"

run rm -f $1.$$

