#include "vtkObject.h"

#include <string>
#include <vector>

class Output
{
public:
  Output()
    {
    }
  ~Output()
    {
    this->Stream.rdbuf()->freeze(0);
    }
  ostrstream Stream;

  int ProcessFile(const char* file, const char* title)
    {
    FILE* fp = fopen(file, "r");
    if ( !fp )
      {
      cout << "Canot open file: " << file << endl;
      return VTK_ERROR;
      }
    int ch;
    this->Stream << "// Define the " << title << " interfaces." << endl
      << "//" << endl 
      << "// Generated from file: " << file << endl
      << "//" << endl
      << "const char* vtkPVInitialize::Standard" << title << "Interfaces =" 
      << endl << "\"";
    int start = 1;
    int preproc = 0;
    while ( ( ch = fgetc(fp) ) != EOF )
      {
      if ( preproc )
        {
        this->Stream << (unsigned char)ch;
        if ( ch == '\n' )
          {
          preproc = 0;
          this->Stream << "\"";
          }
        }
      else
        {
        if ( ch == '\n' )
          {
          this->Stream << "\\n\"" << endl << "\"";
          start = 1;
          }
        else if ( start && ch == '#' )
          {
          preproc = 1;
          this->Stream << "\\n\"" << endl << "#";
          }
        else if ( ch == '\\' )
          {
          this->Stream << "\\\\";
          start = 0;
          }
        else if ( ch == '\"' )
          {
          this->Stream << "\\\"";
          start = 0;
          }
        else
          {
          this->Stream << (unsigned char)ch;
          start = 0;
          }
        }
      }
    this->Stream << "\\n\";" << endl;
    fclose(fp);
    return VTK_OK;
    }
};

int main(int argc, char* argv[])
{
  if ( argc < 4 )
    {
    cout << "Usage: " << argv[0] << " <output-file> <input-path> <modules>..." << endl;
    return 1;
    }
  Output ot;
  ot.Stream << "// Loadable modules" << endl
    << "//" << endl
    << "// Generated by " << argv[0] << endl
    << "//" << endl
    << "#ifndef __vtkPVDefaultModules_h" << endl
    << "#define __vtkPVDefaultModules_h" << endl
    << "" << endl
    << "#include \"vtkToolkits.h\"" << endl
    << "#include \"vtkPVConfig.h\"" << endl
    << "" << endl;

  vtkstd::string output = argv[1];
  vtkstd::string input = argv[2];

  int cc;
  for ( cc = 3; cc < argc; cc ++ )
    {
    vtkstd::string fname = input + "/" + argv[cc] + ".xml";

    if ( ot.ProcessFile(fname.c_str(), argv[cc]) != VTK_OK )
      {
      cout << "Problem generating header file from XML file: " << fname.c_str() << endl;
      return 1;
      }
    }
  ot.Stream << "" << endl
    << "#endif" << endl;
  ot.Stream << ends;
  FILE* fp = fopen(output.c_str(), "w");
  if ( !fp )
    {
    cout << "Cannot open output file: " << output.c_str() << endl;
    return 1;
    }
  fprintf(fp, "%s", ot.Stream.str());
  fclose(fp);
  return 0;
}
