#!/bin/bash
# Copyright 2019 Chad Lemmen http://www.lemmen.com
#
# Modify a postscript file by adding horizontal lines


in=$(cat $1)

# A4 paper is 94 columns at 12cpi
col=94

for sym in = -; do
  # Put the line start coordinates into an array using regex to search
  # for the pattern, {n} exactly n times, {n,} at least n times
  arr=( $(grep -B 1 -E "\([$sym]{$col}\)" <<< "$in" | grep [[:digit:]] | cut -d' ' -f1-2) )

  if [ "$sym" == "-" ]; then
    linewidth=1
    #adjust=3
    # Removing both the symbols only needs to be done once in the loop
    printf "%s\n" "s/[=-]{$col}//"
  else
    linewidth=2
    #adjust=3
  fi

  for ((i=0; i<${#arr[@]}; i+=2)); do # step through index values by 2
    x="${arr[$i]}"
    y="${arr[$i+1]}"
    #y=$(bc <<< "$y + $adjust") # moving up $adjust is needed to cover the line

    # n string stringwidth pop, returns the width of a string repeated n times
    printf "%s\n" "/%%EndPageSetup/a newpath \
                                     $x $y moveto \
                                     95 string stringwidth pop $y lineto \
                                     $linewidth setlinewidth \
                                     stroke"
  done
done | sed -r -f- <(echo "$in") # use process substitution since we cannot
                                # pipe and redirect stdin at the same time

