#include <vector>
#include <printf.h>
#include <iostream>
#include <fstream>

// 0x12: 14010 (number of text?)
// 0x1B5EA(112106): first text
// 0x1b5f8(112120): second text (14 distantce from 1.)
// 9564 lines of text in the file (index doing double refs -> yes, sort|uniq|wc gives exactly 9564)
// indexs: 0, 14, 19, ..., 580862, 580998
// number1 
// Double refs:
// 869 times: 56
// 1039 times: 85
// 287 times:  578
// longest string: 6508
struct TextEntry
{
  /** offset where the text starts, offset is relative to the first string */
  unsigned int   offset; 

  /** Range: 0 - 65535, widespread */
  unsigned short number2;

  /** Range: 901 - 31372, very narrow, only 62 numbers used -> bitfield?! */
  unsigned short number3;

  /** properties that might be encoded in number2 and number3:
      text color
      text size
      character id
   */
};

void extract(const char* filename)
{
  // std::cout << "Processing: " << filename << std::endl;
  std::ifstream in(filename);

  std::vector<TextEntry> entries;
  
  unsigned int entry_count = 0;
  in.seekg(0x12, std::ios::beg);
  in.read(reinterpret_cast<char*>(&entry_count), sizeof(unsigned int));
  std::cout << "EntryCount: " << entry_count << std::endl;

  in.seekg(0x1e, std::ios::beg);


  for(unsigned int i = 0; in && (i < entry_count); ++i)
    {
      TextEntry entry;
      in.read(reinterpret_cast<char*>(&entry.offset), sizeof(unsigned int));
      in.read(reinterpret_cast<char*>(&entry.number2), sizeof(unsigned short));
      in.read(reinterpret_cast<char*>(&entry.number3), sizeof(unsigned short));

      printf("%i: %10d %10d %10d\n", i, entry.offset, entry.number2, entry.number3);
      //printf("%10d\n", entry.number1);
      entries.push_back(entry);
    }

  if (0)
    {
      int count = 0;
      std::string text;
      while(true)
        {
          char c = in.get();
      
          if (!in) break;

          if (c == 0)
            {
              std::cout << text.length() << " ### " << text << " ###" << std::endl;
              text.clear();
              count += 1;
            }
          else
            {
              text += c;
            }
        }
      std::cout << "Count: " << count << std::endl;
    }
}

int main(int argc, char** argv)
{
  for(int i = 1; i < argc; ++i)
    {
      extract(argv[i]);
    }  
}

