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

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

	def handle_text_block()
		r = /\[(\d+)\]/
		# process file ...
		while line = @file.gets
			# unless footnote marker is found
			return if line.match(FOOTNOTE_HEADER_REGEXP)
			# change line's footnotes
			line.gsub!(r) do |m|
				# on first occurence:
				# save old footnote with count in table 
				@table[m] = @cnt += 1 unless @table[m]
				# return new footnote for replacement
				"[#{@table[m]}]"
			end
			# print line with line ending
			puts line
		end
	end

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

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

if __FILE__==$0
  # run Footnotes if file is executed
  Footnotes.new.run(ARGV.shift)
end
