#!/bin/sh

# Don't hack this script by hand if it's in one of your PATH directories.
# Instead, modify scripts/yodl2less.sh in the YODL source package and do
# "make -C scripts install".  This script is installed as yodl2manless AND
# as yodl2msless.  Different groff macro commands, that's all.

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

################################################### Print usage info and die.
usage()
{
    cat << ENDUSAGE
    
Yodl2less 1.31.18

Usage: yodl2less [OPTION]... FILE
Options:
    for processing, run "yodl" without arguments to see
This converter runs "yodl2ms" to convert the input file to groff
format, then runs "groff -t -Tascii -ms -P-b -P-u -P-o -P-f" and pipes the output to
the "less" pager. 
Redirect to send the output to a file, as in
    yodl2msless file > output
ENDUSAGE

    exit 1
}

###################################################### Start of main program.

# get all flags
flags=""
inf=""
while [ "$1" != "" ] ; do
    case $1 in
        -*)
            flags="$flags $1"
            shift
            ;;
        *)
            inf=$1
            shift
            ;;
    esac
done

# no input file, nogo
if [ "$inf" = "" ] ; then
    usage
fi

# determine output file
# ash chokes on these
#if [ "x${inf%%.yo}.yo" = "x$inf".yo ]; then
#    troffile=${inf%%.yo}.ms
#else
    troffile=`echo $inf | sed 's/\.yo//'`.ms
#fi

PATH=$PATH:/tmp/pkgbuild/textproc/yodl/work.alpha/yodl-1.31.18/scripts/out/
yodl2ms $flags $inf || error "YODL to ms conversion failed"

NEWLINE="\
"

# are we redirected?
if [ -t ] ; then
    # nope.. pipe into less
    groff -t -Tascii -ms -P-b -P-u -P-o -P-f $troffile | 
    sed "//,/$NEWLINE*[ ]*-[0-9]*-/d" | uniq |
    less
else
    # yep, send it wherever it goes
    groff -t -Tascii -ms -P-b -P-u -P-o -P-f $troffile |
    sed "//,/$NEWLINE*[ ]*-[0-9]*-/d" | uniq
fi
