#!/usr/bin/ruby -W0
# Author: Vincent Landgraf <Vincent.Landgraf@t-systems.com>
index, footnodes = {}, {}
body, trailer = open(ARGV[0], 'r') { |f| f.read }.split('@footnote:')
body.scan(/\[\d+\]/).uniq.each { |r| index[r] = index.size + 1 }

trailer.scan(/^(\[\d+\])\s+(.*)$/) do
  raise "Error: Footnode #{$1} is not defined" if index[$1].nil?
  footnodes[index[$1]] = $2
end

puts body.gsub!(/(\[\d+\])/) { '[' + index[$1].to_s + ']' }
puts '@footnote:'
footnodes.keys.sort.each { |k| puts '[' + k.to_s + '] ' + footnodes[k] }
