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

public class Example6
{
   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();
      IFunctionFactory    funcf = af.createFunctionFactory(tree);
      ITupleFactory          tupf  = af.createTupleFactory(tree);

      ITuple tuple = (ITuple) tree.find("tuple");
      IHistogram1D hist = hf.createHistogram1D("hist","double gaussian Hist",60, -1, 3);
      tuple.project(hist, tupf.createEvaluator("doubleGauss"));

      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","");
      double[] pars = {170, 0.7, 1, 0.1, 1, 0.3};
      gaussSum.setParameters(pars);

      fitter.setConstraint("mu0=mu1");

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

      IPlotter plotter = af.createPlotterFactory().create("Example6 Plot");
      plotter.region(0).plot(hist);
      plotter.region(0).plot(gaussSumResult.fittedFunction());
      plotter.show();
   }
}

