import hep.aida.*;
import org.freehep.application.*;
import org.freehep.application.studio.*;

public class Example3bis
{
   public static void main(String[] argv) throws java.io.IOException
   {
      IAnalysisFactory  af     = IAnalysisFactory.create();
      // The line below is the AIDA way to open a data set.
      //ITree                     tree = af.createTreeFactory().create("JAS3DataSet.aida");
      // We use instead the following JAS3 specific way to open a tree so that we can access the
      // already opened tree.
      ITree tree = (ITree) ((Studio) Application.getApplication()).getLookup().lookup(ITree.class); 
      tree.cd("/JAS3DataSet.aida");
      IHistogramFactory hf    = af.createHistogramFactory(tree);
      IFitFactory                fitf    = af.createFitFactory();
      IFitter                        fitter = fitf.createFitter();
      ITupleFactory         tf        = af.createTupleFactory(tree);

      IHistogram1D hist = (IHistogram1D) tree.find("gauss Sum Hist");
      IHistogram1D leftGaussian = hf.createHistogram1D("leftGaussian","",hist.axis().bins(),hist.axis().lowerEdge(),hist.axis().upperEdge());
      IHistogram1D rightGaussian = hf.createHistogram1D("rightGaussian","",hist.axis().bins(),hist.axis().lowerEdge(),hist.axis().upperEdge());

      ITuple tuple = (ITuple) tree.find("tuple");

      IEvaluator eval    = tf.createEvaluator("gaussSum");
      IFilter leftFilter     = tf.createFilter("gaussSum<1.5");
      IFilter rightFilter  = tf.createFilter("gaussSum>1.5");

      tuple.project(leftGaussian,eval,leftFilter);
      tuple.project(rightGaussian,eval,rightFilter);

      double[] g1InitPars = new double[] {20,1,0.2};
      IFitResult leftResult = fitter.fit(leftGaussian,"g",g1InitPars);

      double[] g2InitPars = new double[] {45,3,1};
      IFitResult rightResult = fitter.fit(rightGaussian,"g",g2InitPars);

      IPlotter plotter = af.createPlotterFactory().create("Example3bis Plot");
      plotter.destroyRegions();
      plotter.createRegion(0,0,.66,1).plot(hist);
      plotter.region(0).plot(leftResult.fittedFunction());
      plotter.region(0).plot(rightResult.fittedFunction());
      plotter.createRegion(.66,0,.33,.5).plot(leftGaussian);
      plotter.region(1).plot(leftResult.fittedFunction());
      plotter.createRegion(.66,.5,.33,.5).plot(rightGaussian);
      plotter.region(2).plot(rightResult.fittedFunction());
      plotter.show();

   }
}

