#!/usr/bin/env tclsh8.5
#
# Renumber references and sort appendix
#
# (c) 2008 Michael Schlenker
#
# Handle the problem in multiple passes.
# 1. Find numbered footnotes and create renumbered mapping
# 2. Apply mapping to all numbers
# 3. Sort the footnote appendix and memorize indices
# 4. Output the head part, than iterate over the appendix
#

# we use Tcl 8.5 features
package require Tcl 8.5
# import +/-
namespace path ::tcl::mathop

proc main {file} {
    set fd [open $file]
    fconfigure $fd    -encoding iso8859-15
    fconfigure stdout -encoding iso8859-15
    set data [renumber [read $fd]]
    close $fd 
    lassign [sort_appendix $data] first parts

    # dump the head part
    puts [string range $data 0 $first]
    # output the footnote appendix
    foreach item $parts {
	lassign $item no start end
    	puts [format "\[%d\] %s" $no [string range $data $start $end]]
    }
}

proc renumber {data} {
    set map [dict create]
    foreach item [regexp -all -inline {\[\d+\]} $data] {
    	if {! [dict exists $map $item] } { dict set map $item "\[[incr count]\]"}	
    }
    string map $map $data
}

proc sort_appendix {data} {
   # find appendix
   set mark [string last "@footnote:" $data]
   # find entries
   foreach {full part} [regexp -start $mark -all -inline -indices {\n\[(\d+)\]} $data] {
       lassign $full end start
       set end [+ $end -1]
       set start [+ $start 2]
       if {[info exists item]} {
           lappend items [list $item $oldstart $end]
       } else {
	   # first entry
       	   set first $end
       }
       set oldstart $start
       set item [string range $data {*}$part]
   }
   # last entry, up to end of file
   lappend items [list $item $oldstart [- [string length $data] 2]]
   return [list $first [lsort -index 0 -integer $items]]
}

main [lindex $argv 0]
