// $Id: genfacts.java,v 1.4 2003/06/13 15:43:08 tself Exp $


/**
 * given 1 or more DAML files, generate facts suitable for loading into JESS.
 */
public class genfacts
{
    static String quoted(String string)
    {
	return '"' + string + '"';
    }

    /**
     * escape any embedded quotes.
     */
    static String escaped(String string)
    {
	int quotes = 0;
	for (int i = 0; i < string.length(); i++)
	    {
		if (string.charAt(i) == '"')
		    quotes++;
	    }
	if (quotes == 0)
	    return string;

	// escape
	StringBuffer retval = new StringBuffer(string.length() + quotes);
	for (int i = 0; i < string.length(); i++)
	    {
		char ch = string.charAt(i);

		if (ch == '"')
		    retval.append('\\');
		retval.append(ch);
	    }
	return new String(retval);
    }

    static void usage()
    {
	System.err.println("Usage: [-triple] <daml-uri>");
   System.err.println("-triple: Causes all facts to have 'triple' as the first member");
   System.err.println("         This is necessary if you want to bind to predicates");
	System.exit(1);
    }

    public static void main(String args[])
	throws Exception
    {
	com.hp.hpl.mesa.rdf.jena.model.Model model = new com.hp.hpl.mesa.rdf.jena.mem.ModelMem();

	// parse arguments and load DAML
	if (args.length < 1)
	    usage();
   boolean triple = false;
   int start = 0;
   if(args[0].equalsIgnoreCase("-triple"))
   {
      if(args.length < 2) usage();
      triple = true;
      start = 1;
   }
	for (int i = start; i < args.length; i++)
	    model.read(args[i]);

	com.hp.hpl.mesa.rdf.jena.model.StmtIterator iterator = model.listStatements();
	while (iterator.hasNext())
	    {
		com.hp.hpl.mesa.rdf.jena.model.Statement statement = iterator.next();
		com.hp.hpl.mesa.rdf.jena.model.RDFNode object = statement.getObject();
		System.out.println("(" + (triple ? "triple ": "") + statement.getPredicate() + " " + statement.getSubject() + " " + ((object instanceof com.hp.hpl.mesa.rdf.jena.model.Literal) ? quoted(escaped(object.toString())) : object.toString()) + ")");
	    }
    }
}
