# Autor: Bernhard Reiter

FOOTNOTE_SPLIT = "@footnote:"
regexp = Regexp.compile('\[([0-9]+)\]')

class Footnote
    @@table = {}
    @@index = 0

    def self.next(num)
        @@table[num] = @@table.key?(num) ? @@table[num] : @@index += 1
    end
end

# Monkey patch
class String
    def index_footnotes!(regexp)
        gsub!(regexp) { |num| "[#{Footnote.next(num)}]" }
    end
end

# Text laden
input = ARGV[0] != nil ? File.read(ARGV[0]) : STDIN.read
text, bib = input.split(FOOTNOTE_SPLIT)

# Fussnoten neu nummerieren und sortieren
text.index_footnotes!(regexp)
bib = bib.index_footnotes!(regexp).split("\n").sort.join("\n")

# Ausgabe
puts text, FOOTNOTE_SPLIT, bib
