#include <gcj/cni.h>

#include <stdio.h>

#include <java/lang/System.h>
#include <java/io/FileInputStream.h>
#include <java/io/FileOutputStream.h>
#include <java/io/PrintStream.h>
#include <org/xml/sax/ContentHandler.h>
#include <org/xml/sax/InputSource.h>

#include "nu/validator/htmlparser/sax/XmlSerializer.h"
#include "nu/validator/htmlparser/sax/HtmlParser.h"
#include "nu/validator/htmlparser/common/XmlViolationPolicy.h"
#include "nu/validator/htmlparser/test/SystemErrErrorHandler.h"

int main(int argc, char *argv[]) {
  using namespace java::lang;
  using namespace java::io;
  using namespace org::xml::sax;
  using namespace nu::validator::htmlparser::sax;
  using namespace nu::validator::htmlparser::common;
  using namespace nu::validator::htmlparser::test;

  JvCreateJavaVM(NULL);
  JvAttachCurrentThread(NULL, NULL);
  JvInitClass(&System::class$);
  JvInitClass(&XmlViolationPolicy::class$);

  InputStream *in;
  OutputStream *out;

  switch (argc) {
    case 1:
      in = System::in;
      out = System::out;
      break;

    case 2:
      in = new FileInputStream(JvNewStringUTF(argv[1]));
      out = System::out;
      break;

    case 3:
      in = new FileInputStream(JvNewStringUTF(argv[1]));
      out = new FileOutputStream(JvNewStringUTF(argv[2]));
      break;

    default:
      printf("Too many arguments. No arguments to use stdin/stdout. One argument to reading from file and write to stdout. Two arguments to read from first file and write to second.");
      return 1;
  }

  ContentHandler *serializer = (ContentHandler*) new XmlSerializer(out);
  HtmlParser *parser = new HtmlParser(XmlViolationPolicy::ALTER_INFOSET);

  parser->setErrorHandler((ErrorHandler*) new SystemErrErrorHandler());
  parser->setContentHandler(serializer);
  String *lexical_handler =
    JvNewStringUTF("http://xml.org/sax/properties/lexical-handler");
  parser->setProperty(lexical_handler, serializer);
  parser->parse(new InputSource(in));
  out->flush();
  out->close();

  JvDetachCurrentThread();
}

