#!/bin/sh
# more(1), shell attempt

# TUPE says (chapter 6, p. 181), “This program is best written in C
# because it’s easy in C, and hard otherwise; the standard tools are
# not so good at mixing the input from a file or pipe with terminal
# input.”  But I think it’s not *that* hard.
if [ "$#" -eq 0 ]; then set '(stdin)'; fi
exec 3<&0                       # I’m pretty sure this already worked

for infile; do
    if [ x"$infile" = 'x(stdin)' ]; then
        exec <&3          # /dev/fd/0 didn't exist in 01983
    else
        exec <"$infile"
    fi
                                 
    eof=false
    while ! "$eof"; do
        for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 \
                 17 18 19 20 21 22 23; do
            # XXX not sure if read -r existed in 01983; it certainly
            # doesn’t in the 7th Edition Bourne shell (see readvar()
            # at /usr/src/cmd/sh/name.c:113 <- xec.c:162 <- msg.c:113)
            # but on the bright side maybe the \-processing behavior
            # -r suppresses didn’t exist either!
            if IFS= read -r line; then
                # printf "%s\n" $line would be safer; current GNU/bash
                # echo will fail if the second argument consists of
                # "-e" or "-n", though dash echo doesn’t.  But "-e\n"
                # seems to work reliably in both, and TUPE documents
                # this kind of trick as reliable at the time:
                echo -n "$line
"
            else
                eof=true
            fi
        done

        if "$eof"; then
            echo -n "(end of $infile)"
        else
            echo -n "--($infile) more--"
        fi

        # I think that even in TUPE’s time you could have done this:
        x=true; while $x; do read cmd; x=false; done </dev/tty
        # But now we can do this:
        # read cmd </dev/tty
        if [ x"$cmd" = xq ]; then exit 0; fi
    done
done
