class Footnotes
       FOOTNOTE_HEADER = '@footnotes:'
       FOOTNOTE_HEADER_REGEXP = %r(^#{FOOTNOTE_HEADER})

       def initialize
               @cnt = 0
               @table = {}
       end

       def handle_text_block()
               r = /\[(\d+)\]/
               while line = @file.gets
                       return if line.match(FOOTNOTE_HEADER_REGEXP)
                       line.gsub!(r) do |m|
                               @table[m] = @cnt += 1 unless @table[m]
                               "[#{@table[m]}]"
                       end
                       puts line
               end
       end

       def handle_footnotes()
               footnotes = {}
               r = /^(\[\d+\])/
               while line = @file.gets
                       old_note = line[r, 1]
                       next unless old_note
                       new_note = @table[old_note]
                       next unless new_note
                       footnotes[new_note] = line[old_note.length..-1]
               end
               footnotes.sort.each { |idx,ref| print "[#{idx}]#{ref}" }
       end

       def run(file)
               @file = file ? File.open(file, 'r') : STDIN
               handle_text_block
               puts FOOTNOTE_HEADER
               handle_footnotes
   @file.close
       end
end

if __FILE__==$0
 Footnotes.new.run(ARGV.shift)
end