#! /bin/sh
# footnotes - renumber footnotes in a text
# Heiner Steven <heiner.steven AT shelldorado.com>

awk '
   # renumrefs - renumber footnote references in "line", return result
   #
   # "createmap" controls whether new entries for the mapping table [] map
   # are created.

   function renumrefs(line, createmap,         result) {
       result = ""
       # Process all footnote references
       while (match(line, /\[[0-9][0-9]*\]/) > 0) {
           oldnum = substr(line, RSTART+1, RLENGTH-2) + 0
           if (!(oldnum in map) && createmap) {
               map[oldnum + 0] = ++lastnum
           }
           newnum = map[oldnum]

           # Replace old footnote with new one from "newnum"
           result = result substr(line, 1, RSTART) newnum "]"
           line = substr(line, RSTART + RLENGTH)
       }
       result = result line            # Use the rest of line
       return result
   }

   # Switch between the two modes: mode "list" processes the
   # footnote list, otherwise a footnote reference is processed.
   $0 == "@footnote:" { mode = "list"; next }

   # Fast path: if there is no footnote reference there is nothing to do
   $0 !~ /\[[0-9][0-9]*\]/ { print; next }

   # There is at least one foot note mark!
   {
       if (mode != "list") {
           # Read text, create reference map table
           print renumrefs($0, 1)
       } else {
           # Save list entry, will be printed at the end of the script
           notetext[newnum + 0] = renumrefs($0, 0)
       }
   }

   # The complete text has been read. Write the complete footnote list
   # in the right ascending order.
   END {
       for (i = 1; i <= lastnum; i++) { print notetext[i] }
   }
' "$@"