//package org.apache.fop.apps;
import org.apache.fop.apps.*;

// SAX
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

// Java
import java.io.*;
import java.net.URL;


// FOP
import org.apache.fop.messaging.MessageHandler;
import org.apache.fop.configuration.Configuration;

/**
 *  super class for all classes which start Fop from the commandline
 */

public class FOPMemoryTest   {
	
	boolean errorDump;
	
	public static void main (String [] args) {
	
	try {
	    //options = new CommandLineOptions (args);
	    FOPMemoryTest starter = new FOPMemoryTest();
	    starter.run();
	}
	catch (FOPException e) {
	    MessageHandler.errorln("ERROR: "+e.getMessage());

	}
	}
	
    	
    public FOPMemoryTest () 
	throws FOPException
    {
    }
	
    /**
     * Run the format.
     * @exception FOPException if there is an error during processing
     */
    public void run() 
	throws FOPException
    {
	
		String path="readme.fo";
		String outfilename="readme.pdf";
		int iterations=100;
	
		Driver driver = new Driver();
		driver.setRenderer("org.apache.fop.render.pdf.PDFRenderer");
			
        InputHandler inputHandler = new FOInputHandler(new File(path));
        XMLReader parser = inputHandler.getParser();

        try {
			for (int i=0 ; i<iterations; i++)
			{
				// RUN WITH
				// java -mx200m -ms200m FOPMemoryTest  to get the same total memory thru
				// iterations
				long totalmem=Runtime.getRuntime().totalMemory();
				long allmem=totalmem-Runtime.getRuntime().freeMemory();
				System.out.println(i+"th Iteration. Total mem:"+totalmem+" Allocated mem: "+allmem +" ("+allmem/1000000+" MB)"
					);
			    driver.buildFOTree(parser, inputHandler.getInputSource());
			    driver.format();
			    driver.setOutputStream(new FileOutputStream(new File(outfilename)));
			    driver.render();
				driver.reset();
				System.gc();
			}
        } catch (Exception e) {
	    if (e instanceof FOPException) {
		throw (FOPException) e;
	    }
	    throw new FOPException(e);
	}
    }
	
	

	
}


