#!/usr/bin/python
import sys, os, string

if (len(sys.argv) != 2 and len(sys.argv) != 3):
    Usage = """
Usage:
mkanalysis AnalysisName [ParentAnslysis]

Paramters:
AnalysisName           analysis name (the suffix Analysis will be added to chosen name)
ParentAnalysis         optional paramter to specify a different parent analysis wrt BaseAnalysis
"""
    print Usage
    sys.exit(-1)

name = sys.argv[1] + "Analysis"
if (len(sys.argv) == 3):
    parent = sys.argv[2]
else:
    parent = "BaseAnalysis"
    
if (not os.path.exists(name)):
    os.system("mkdir -p " + name + "/interface")
    os.system("mkdir -p " + name + "/src")
else:
    print "I'm sorry but the analysis already exists !\nYou have to change the name."
    sys.exit(-1)
    
file = open(name + "/BuildFile.xml", "w")
text = """
<use   name=\"h2gglobe\"/>
<use   name=\"roofit\"/>
<export>
  <lib   name=\"1\"/>
</export>
<Flags CXXFLAGS=\"-g\" />
"""
file.write(text)
file.close()

file = open(name + "/interface/" + name + ".h", "w")
text = """
#ifndef __XXX__
#define __XXX__

#include \"YYY\"

// ------------------------------------------------------------------------------------
class XXX : public ZZZ {
 public:
  XXX();
  virtual ~XXX();
  
  virtual const std::string & name() const { return name_; };
  
  // LoopAll analysis interface implementation
  virtual void Init(LoopAll&);
  virtual void Term(LoopAll&);
  
  virtual void ReducedOutputTree(LoopAll &l, TTree *);
  virtual void GetBranches(TTree *, std::set<TBranch *>& );

  virtual void ResetAnalysis();
  
  virtual void FillReductionVariables(LoopAll& l, int jentry);   
  virtual bool SelectEventsReduction(LoopAll&, int);
  
  virtual bool SkimEvents(LoopAll&, int);
  virtual bool SelectEvents(LoopAll&, int);
  virtual bool Analysis(LoopAll&, Int_t);
  
 protected:
  std::string name_;
};

#endif
"""
text = text.replace("XXX", name)
text = text.replace("ZZZ", parent)
if (parent == "BaseAnalysis"):
    text = text.replace("YYY", parent+".h")
else:
    text = text.replace("YYY", parent+"/interface/"+parent+".h")
file.write(text)
file.close()

file = open(name + "/src/" + name + ".cc", "w")
text = """
#include \"XXX/interface/XXX.h\"

#include <iostream>

#define XXXDEBUG 0

using namespace std;

// ----------------------------------------------------------------------------------------------------
XXX::XXX()  : 
  name_(\"XXX\")
{}

// ----------------------------------------------------------------------------------------------------
XXX::~XXX() 
{}

// ----------------------------------------------------------------------------------------------------
void XXX::Term(LoopAll& l) 
{}

// ----------------------------------------------------------------------------------------------------
void XXX::Init(LoopAll& l) {
  if(XXXDEBUG) 
    cout << \"InitRealXXX START\"<<endl;
  
  if(XXXDEBUG) 
    cout <<\"InitRealXXX END\"<<endl;
}

// ----------------------------------------------------------------------------------------------------
bool XXX::Analysis(LoopAll& l, Int_t jentry) {
  if(XXXDEBUG) 
    cout <<\"Analysis START\"<<endl;
  
  
  if(XXXDEBUG) 
    cout<<\"Analysis END\"<<endl;
}

// ----------------------------------------------------------------------------------------------------
void XXX::GetBranches(TTree *t, std::set<TBranch *>& s ) 
{}

// ----------------------------------------------------------------------------------------------------
void XXX::FillReductionVariables(LoopAll& l, int jentry) {
  if(XXXDEBUG) 
    cout<<\"myFillReduceVar START\"<<endl;
  
  if(XXXDEBUG) 
    cout<<\"myFillReduceVar END\"<<endl;
}

// ----------------------------------------------------------------------------------------------------
bool XXX::SelectEventsReduction(LoopAll& l, int jentry) {

  if(XXXDEBUG)  cout << \" ****************** SelectEventsReduction \" << endl;
  return true;
}

// ----------------------------------------------------------------------------------------------------
bool XXX::SkimEvents(LoopAll& l, int jentry) {
  return true;
}

// ----------------------------------------------------------------------------------------------------
bool XXX::SelectEvents(LoopAll& l, int jentry) {
  return true;
}

// ----------------------------------------------------------------------------------------------------
void XXX::ReducedOutputTree(LoopAll &l, TTree * outputTree) 
{}

// ----------------------------------------------------------------------------------------------------
void XXX::ResetAnalysis()
{}

"""
text = text.replace("XXX", name)
file.write(text)
file.close()

dirname = "AnalysisScripts/" + name.lower()
os.system("mkdir " + dirname)

#########################################################
file = open(dirname + "/" + name.lower() + ".dat", "w")
file.write("### Example of .dat \n")
file.write("puMap=\n")
file.write("puHist=aux/2012_5_9_Weights.root\n")
file.close()

#########################################################
file = open(dirname + "/counters.dat", "w")
file.write("ncat=1   countername=Processed   denomname1=Events denomname2=-1 denomname3=-1\n")
file.close()

#########################################################
file = open(dirname + "/inputfiles.dat", "w")
file.write("intL=370 histfile=out.root output=shifo.root\n")
file.write("typ=1 ind=1  draw=1  Nam=DYJetsToLL  Dir=/hadoop/cms/store/user/matteo/reduced/20120509123956_mc  lum=1.0e+10 xsec=3048 kfac=1.0  scal=1.\n")
file.write("typ=0 ind=0  draw=1  Nam=Data  Dir=/hadoop/cms/store/user/matteo/reduced/20120509123813_data lum=1.0e+10 xsec=1.0 kfac=1.0  scal=1. json=aux/Cert_190456-191859_8TeV_PromptReco_Collisions12_JSON.txt\n")
file.write("\n")
file.write("inputBranches reduction_output.dat\n")
file.write("\n")
file.write("analyzer " + name + " " + name.lower() + ".dat\n")
file.close()

#########################################################
file = open(dirname + "/cuts.dat", "w")
file.write("cutname=def_ECAL_Barrel ncat=1  dir=2 fin=0   minval=0.0   maxval=1.4442\n")
file.write("cutname=cut_Mgg         ncat=4  dir=2 fin=42   minval=90 minval=90 minval=90 minval=90 maxval=190 maxval=190 maxval=190 maxval=190 iread=1 plot=2 bins=50 xmin=90 xmax=190 xaxis=M_{#gamma#gamma}@(GeV/c^{2}) yaxis=pluto\n")
file.close()

#########################################################
file = open(dirname + "/plotvariables.dat", "w")
file.write("default=n")
file.write("htyp=0 plot=-1  ncat=18  xbins=160   ybins=0       xmin=80.0  xmax=240.0  ymin=0      ymax=0       name=all_mass xaxis=x yaxis=y\n")
file.close()

#########################################################
file = open(dirname + "/reduction_input.dat", "w")
file.write("->\n")
file.write("File format:\n")
file.write("        <branch_name>[:<branch_type>]\n")
file.write("where:\n")
file.write("        <branch_type> = 0 for branches to be always read\n")
file.write("        <branch_type> = 1 for branches to be read only for MC\n")
file.write("->\n")
file.close()
           
os.system("cp "+ dirname + "/reduction_input.dat " + dirname + "/reduction_output.dat")

#########################################################
file = open(dirname + "/filestoreduce.dat", "w")
file.write("output=my_reduced_tuple_foo.root\n")
file.write("Fil=/hadoop/cms/store/user/matteo/Summer12/DYJetsToLL/DYJetsToLL_1368_1_fHB.root typ=1\n")
file.write("\n")
file.write("inputBranches reduction_input.dat\n")
file.write("outputBranches reduction_output.dat\n")
file.write("\n")
file.write("analyzer " + name + " " + name.lower() + ".dat\n")

#########################################################
    
# change MakeFile
file = open("Makefile", "r")
lines = file.readlines()
file.close()

file = open("Makefile_temp", "w")
for l in lines:
    if ("SubPkgs=" in l):
        file.write(l.split("\n")[0] + " " + name + "\n")
    else:
        file.write(l)
file.close()
os.system("mv Makefile_temp Makefile")
