#include <fstream>
#include <iostream>
#include <pcrecpp.h>
#include <tr1/unordered_map>

pcrecpp::RE re_ref("^\\[(\\d+)\\]");
pcrecpp::RE re_txt("(.*?)\\[(\\d+)\\]");

void process(char const * filename)
{
   std::ifstream file(filename);
   std::string line;
   while (getline(file, line) and line != "@footnote:")
      ;

   std::tr1::unordered_map<int, int> dict;
   int counter = 1;
   while (getline(file, line)) {
      int number = -1;
      if (re_ref.PartialMatch(line, &number))
         dict[number] = counter++;
   }

   file.clear();
   file.seekg(0);
   while (getline(file, line)) {
      pcrecpp::StringPiece input(line);
      pcrecpp::StringPiece prefix;
      int ref;
      while (re_txt.Consume(&input, &prefix, &ref))
         std::cout << prefix << "[" << (dict[ref] ? dict[ref] : ref) << "]";
      std::cout << input << "\n";
   }
}

int main(int argc, char ** argv)
{
   std::ios::sync_with_stdio(false);
   for (int i = 1; i != argc; ++i)
      process(argv[i]);
}
