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

public class Example4
{
   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");
      IFitFactory             fitf    = af.createFitFactory();
      IFitter                     fitter = fitf.createFitter();
      IFitData                 data = fitf.createFitData();
      IFunctionFactory funcf = af.createFunctionFactory(tree);

      IHistogram1D hist = (IHistogram1D) tree.find("gauss Sum Hist");

      data.create1DConnection(hist);

      data.range(0).excludeAll();;
      data.range(0).include(0,1.5);
      double[] g1InitPars = new double[] {20,1,0.2};
      IFitResult result1 = fitter.fit(data,"g",g1InitPars);

      data.range(0).excludeAll();;
      data.range(0).include(1.5,5);
      double[] g2InitPars = new double[] {45,3,1};
      IFitResult result2 = fitter.fit(data,"g",g2InitPars);

      IFunction gaussSum = funcf.createFunctionFromScript("gaussSum",1,"N*( a*exp( -0.5*(mu0-x[0])*(mu0-x[0])/(s0*s0) )+(1-a)*exp( -0.5*(mu1-x[0])*(mu1-x[0])/(s1*s1) ))","N,a,mu0,s0,mu1,s1","");
      gaussSum.setParameter("N", (hist.axis().upperEdge()-hist.axis().lowerEdge())*hist.entries()/hist.axis().bins());
      gaussSum.setParameter("a", result1.fittedParameter("amplitude")/result2.fittedParameter("amplitude"));
      gaussSum.setParameter("mu0", result1.fittedParameter("mean"));
      gaussSum.setParameter("s0", result1.fittedParameter("sigma"));
      gaussSum.setParameter("mu1", result2.fittedParameter("mean"));
      gaussSum.setParameter("s1", result2.fittedParameter("sigma"));

      fitter.fitParameterSettings("a").setStepSize(0.001);

      IFitResult gaussSumResult = fitter.fit(hist,gaussSum);


      IPlotter plotter = af.createPlotterFactory().create("Example4 Plot");
      plotter.destroyRegions();
      plotter.createRegion(0,0,.66,1).plot(hist);
      plotter.region(0).plot(gaussSumResult.fittedFunction());
      plotter.createRegion(.66,0,.33,.5).plot(hist);
      plotter.region(1).plot(result1.fittedFunction());
      plotter.createRegion(.66,.5,.33,.5).plot(hist);
      plotter.region(2).plot(result2.fittedFunction());
      plotter.show();
   }
}

