#!/usr/bin/env bash
set -u

# Run troff discarding stdout, but capture stderr
((line=$LINENO+3))
result=$(
  (echo ".lf $line $0"; cat <<'EOF'
.
.nr debug 1
.de debugmsg
.  if \\n[debug] .tm \\$*
..
.de errormsg
.  tm ERROR: \\$*
.  nr nerrors (\\n[nerrors]+1)
..
.nr nerrors 0
.
.\"  **TESTER FOR PROPOSED FIXED .substring (not how it works now) **
.\"  
.\" .substring xx n1 n2
.\"    Replace string xx with the substring defined by zero-based indicies 
.\"    n1 and n2. Or, put another way, delete any characters outside the
.\"    range (n1..n2).  If n2 is omitted then all characters after index
.\"    n1 are included in the substring.
.\"
.\"    If n1 > n2 or if n1 equals the length of the string, then nothing
.\"    is selected and the string is set to empty if it was not already empty.
.\"
.\"    Behavior is undefined if n1 > (n2+1) or if either index is negative.
.\"    
.de jtest \" input_string n1 n2 expected_result
.  if \\n[.$]<4 .ab jtest: Wrong arg count 
.  ds t*input "\\$1
.  ds t*n1 \\$2
.  ds t*n2 \\$3
.  ds t*expected "\\$4
.  shift 4
.  ds t*comment "\\$*
.
.  ds t*str "\\*[t*input]
.  ie '\\*[t*n2]'' .substring t*str \\*[t*n1]
.  el              .substring t*str \\*[t*n1] \\*[t*n2]
\\*[t*cmd]
.  ie '\\*[t*str]'\\*[t*expected]' \{\
.    debugmsg .substring '\\*[t*input]' \\*[t*n1] \\*[t*n2] -> '\\*[t*str]' (OK) \\*[comment]
.  \}
.  el \{\
.    errormsg .substring '\\*[t*input]' \\*[t*n1] \\*[t*n2] yielded '\\*[t*str]', EXPECTED '\\*[t*expected]' \\*[comment]
.  \}
..
.
.debugmsg --- Pick a single character from non-empty ---
.jtest "abc" 0 0 "a"
.jtest "abc" 1 1 "b"
.jtest "abc" 2 2 "c"
.
.debugmsg --- Pick multiple characters from non-empty ---
.jtest "abcd" 0 1 "ab"
.jtest "abcd" 1 1 "b"
.jtest "abcd" 0 3 "abcd"
.jtest "abcd" 1 3 "bcd"
.jtest "abcd" 2 3 "cd"
.jtest "abcd" 3 3 "d"
.
.debugmsg --- Omit n2 with non-empty input and non-empty result ---
.jtest "abc" 0 "" "abc"
.jtest "abc" 1 "" "bc"
.jtest "abc" 2 "" "c"
.jtest "a"   0 "" "a"
.
.debugmsg --- Specify empty substring with n2==(n1-1) ---
.jtest "abcd" 3 2 ""
.jtest "abcd" 2 1 ""
.jtest "abcd" 1 0 ""
.jtest "abcd" 0 -1 ""
.
.debugmsg --- Specify empty substring with n1==length and n2 omitted ---
.jtest "abcd" 4 "" ""
.jtest "abc" 3 "" ""
.jtest "ab" 2 "" ""
.jtest "a" 1 "" ""
.jtest "" 0 "" ""
.
.if \n[nerrors] .ab Aborting, got \n[nerrors] errors.
EOF
) | troff -wall 2>&1 >/dev/null
)
stat=$?
echo "Exit status was $stat"
echo "$result"
exit $stat
