#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cerrno>

using std::cerr;
using std::cout;
using std::ifstream;
using std::string;
using std::strerror;

int main(int argc, char **argv)
{
  if (argc <  3 || argc > 5)
    {
      cerr << "usage: " << argv[0]
           << " [--strip-trailing] [--no-static] <filename> <arrayname>\n";
      return 1;
    }

  bool do_strip_trailing = false;
  bool do_static = true;
  int i = 1;
  if (string(argv[i]) == "--strip-trailing")
    {
      do_strip_trailing = true;
      i++;
    }
  if (string(argv[i]) == "--no-static")
    {
      do_static = false;
      i++;
    }
  char const * fname = argv[i++];
  char const * arr = argv[i++];
  
  ifstream fin(fname);
  if (!fin)
    {
      int e = errno;
      cerr << "could not open " << fname << " for reading: "
           << strerror(e) << '\n';
      return 1;
    }

  char c;
  string dat;
  while(fin.get(c))
    dat += c;

  if (do_strip_trailing)
    {
      int last = dat.find_last_not_of(" \t\n");
      dat.erase(last + 1);
    }

  cout << "// DO NOT EDIT\n"
       << "// this file is automatically generated from " << fname << ",\n"
       << "// any changes you make will be destroyed when it is regenerated\n"
       << "\n\n";

  if (do_static)
    cout << "static ";
  else
    // some versions of g++ object to constants marked 'extern' and defined
    // at the same time (i.e. constants declared with both 'extern' and an
    // initializer).  to shut them up, first declare the constant 'extern',
    // then define it without 'extern'.
    cout << "extern char const " << arr << "_constant[];\n";

  cout << "char const " << arr << "_constant[" << (dat.size() + 1) << "] = {\n";

  for (unsigned int i = 0; i < dat.size(); ++i)
    {
      if (i == 0) cout << '\t';
      else if (i % 14 == 0) cout << "\n\t";
      cout << static_cast<int>(dat[i]) << ", ";
    }
  cout << "0\n};\n";
}

// Local Variables:
// mode: C++
// fill-column: 76
// c-file-style: "gnu"
// indent-tabs-mode: nil
// End:
// vim: et:sw=2:sts=2:ts=2:cino=>2s,{s,\:s,+s,t0,g0,^-2,e-2,n-2,p2s,(0,=s:
