ROOT logo
// #include <iostream>
// #include "AliAnalysisManager.h"
// #include "AliESDInputHandler.h"
// #include "AliMCEventHandler.h"
// #include "AliAnalysisGrid.h"
// #include "AliCentralitySelectionTask.h"
// #include "AliAnalysisCentralitySelector.h"
// #include "AliAnalysisTaskPerformanceStrange.h"
// #include "TString.h"
// #include "TChain.h"
// #include "TAlienCollection.h"
// #include <fstream>
// #include "TObjString.h"
// #include "TIterator.h"
// #include "TGrid.h"
// #include "TROOT.h"

// #include "CreateAlienHandler.C"
// #include 

using namespace std;

enum { kMyRunModeLocal = 0, kMyRunModeCAF, kMyRunModeGRID};

TList * listToLoad = new TList(); // Additional classes to be loaded, see InitAndLoadLibs

TChain * GetAnalysisChain(const char * incollection);
void InitAndLoadLibs(Int_t runMode=kMyRunModeLocal, Int_t workers=0,Bool_t debug=0) ;

void runAOD(const char * data, const char * passOrPath, Long64_t nev = -1, Long64_t offset = 0, Bool_t debug = kFALSE, Int_t runMode = 2, Bool_t isMC = 0, Bool_t usePID = kTRUE, const char* option = "",TString customSuffix = "", Int_t workers = -1, const char * gridMode="full", Int_t binMin=0, Int_t binMax = 10)
{
  // runMode:
  //
  // 0 local 
  // 1 proof
  // 2 grid

  if (nev < 0)
    nev = 1234567890;
  InitAndLoadLibs(runMode,workers,debug);

  // Create the analysis manager
  AliAnalysisManager * mgr = new AliAnalysisManager;

  /*  // Add ESD handler
  AliESDInputHandler* esdH = new AliESDInputHandler;
  // Do I need any of this? 
  // esdH->SetInactiveBranches("AliESDACORDE FMD ALIESDTZERO ALIESDZDC AliRawDataErrorLogs CaloClusters Cascades EMCALCells EMCALTrigger ESDfriend Kinks AliESDTZERO ALIESDACORDE MuonTracks TrdTracks");
  mgr->SetInputEventHandler(esdH);
  */
  //Add AOD handler
  AliAODInputHandler* aodH = new AliAODInputHandler;
  mgr->SetInputEventHandler(aodH);
  /*
  if(isMC) {
    AliMCEventHandler* handler = new AliMCEventHandler;
    handler->SetPreReadMode(AliMCEventHandler::kLmPreRead);
    mgr->SetMCtruthEventHandler(handler);
  }
  */

  // If we are running on grid, we need the alien handler
  if (runMode == kMyRunModeGRID) {
    // Create and configure the alien handler plugin
    TGrid::Connect("alien://");// Why do I need this? Without a get a bus error...
        gROOT->LoadMacro("CreateAlienHandler.C");
    AliAnalysisGrid *alienHandler = CreateAlienHandler(data, listToLoad, gridMode, isMC);  
    if (!alienHandler) {
      cout << "Cannot create alien handler" << endl;    
      exit(1);
    }
    mgr->SetGridHandler(alienHandler);  
  }
  
  // Physics selection
  gROOT->ProcessLine(".L $ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
  //  AliPhysicsSelectionTask * physicsSelectionTask = AddTaskPhysicsSelection(isMC,kTRUE,0);
    AliPhysicsSelectionTask * physicsSelectionTask = AddTaskPhysicsSelection(isMC,kTRUE,0);
  //  AliPhysicsSelectionTask * physicsSelectionTask = AddTaskPhysicsSelection(isMC,kFALSE,0);
  if(!physicsSelectionTask ) { Printf("no physSelTask"); return; }

  /*  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");
  AliCentralitySelectionTask *taskCentrality = AddTaskCentrality();
  //taskCentrality->SetPass(2);                                                                                                                                                                               i
  if(isMC) taskCentrality->SetMCInput();
  */
 // PID task
  gROOT->ProcessLine(".L $ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
  AliAnalysisTask *PIDTask = AddTaskPIDResponse(isMC,kTRUE);
  if(!PIDTask ) { Printf("no physSelTask"); return; }

  /*  // Centrality
  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");
  AliCentralitySelectionTask *taskCentrality = AddTaskCentrality();
  //taskCentrality->SetPass(2);
  if(isMC) taskCentrality->SetMCInput();
  */
  // Parse option strings
  TString optionStr(option);
  
  // remove SAVE option if set
  Bool_t doSave = kFALSE;

  if (optionStr.Contains("SAVE"))
    {
      optionStr = optionStr(0,optionStr.Index("SAVE")) + optionStr(optionStr.Index("SAVE")+4, optionStr.Length());
      doSave = kTRUE;
    }
  TString pathsuffix = "";
  // Not used, but may be useful
  Bool_t useMCKinematics = isMC;
  if (optionStr.Contains("NOMCKIN")) {
    cout << ">>>> Ignoring MC kinematics" << endl;
    useMCKinematics=kFALSE;
    pathsuffix+="_NOMCKIN";
  }
  
  gROOT->ProcessLine(".L AddTaskLambdaK0PbPbAOD.C");
  Int_t nbin = 0; // will contain the number of centrality bins
  AliAnalysisTaskPerformanceStrangeAOD ** task = AddTaskLambdaK0PbPbAOD("lambdak0.root", nbin, binMin, binMax,isMC); // FIXME also pass cuts, centrality bin type selection(5,10% percentiles, ranges...)
  // configure task
  //  else if (iAODanalysis) task->SetAnalysisType("AOD");
  // FIXME: add options to macro
  // FIXME: put physics selection inside the task
  cout << nbin << endl;
  
  for(Int_t ibin = 0; ibin < nbin; ibin++){
    cout << "ibin " << ibin << "  "<< endl;//task[ibin] << endl;
    
    task[ibin]->SetAnalysisType("AOD");
    cout << "1" << endl;
    task[ibin]->SetAnalysisMC(isMC); // 0 or 1
    cout << "2" << endl;
    task[ibin]->SetCollidingSystems(1); // 0 =pp, 1=AA
    cout << "3" << endl;
    task[ibin]->SetAnalysisCut("no");
    cout << "4" << endl;
    task[ibin]->SetQASelector(kFALSE);
    cout<< "5" << endl;
    if(usePID) 
      task[ibin]->SetUsePID("withPID"); // withPID or withoutPID
    else
      task[ibin]->SetUsePID("withoutPID"); // withPID or withoutPID
    cout << "5" << endl;
  }

  // Init and run the analy
  if (!mgr->InitAnalysis()) return;

  mgr->PrintStatus();
  
  if (runMode == kMyRunModeLocal ) {
    // If running in local mode, create chain of ESD files
    cout << "RUNNING LOCAL, CHAIN" << endl;    
    TChain * chain = GetAnalysisChain(data);
    //    chain->Print();
    mgr->StartAnalysis("local",chain,nev);
  } else if (runMode == kMyRunModeCAF) {
    mgr->StartAnalysis("proof",TString(passOrPath)+data+"#aodTree",nev);
  } else if (runMode == kMyRunModeGRID) {
    mgr->StartAnalysis("grid");
  } else {
    cout << "ERROR: unknown run mode" << endl;        
  }

  pathsuffix += customSuffix;

  if (doSave) MoveOutput(data, pathsuffix.Data());

  
}

void MoveOutput(const char * data, const char * suffix = ""){

  //  TString path("output10bins/");
  TString path("output10binsNew/");
  path = path + TString(data).Tokenize("/")->Last()->GetName() + suffix;
  
  TString fileName = "lambdak0.root";
  gSystem->mkdir(path, kTRUE);
  gSystem->Rename(fileName, path + "/" + fileName);
  for(Int_t ibin = 0; ibin < 20; ibin++){
    TString fileBin = fileName;
    fileBin.ReplaceAll(".root",Form("_%2.2d.root",ibin));
    gSystem->Rename(fileBin, path + "/" + fileBin);    
  }
  
  gSystem->Rename("event_stat.root", path + "/event_stat.root");      
  gSystem->Rename("EventStat_temp.root", path + "/EventStat_temp.root");      
  Printf(">>>>> Moved files to %s", path.Data());
}  



TChain * GetAnalysisChain(const char * incollection){
  // Builds a chain of esd files
  // incollection can be
  // - a single root file
  // - an xml collection of files on alien
  // - a ASCII containing a list of local root files

  TChain* analysisChain = 0;
  // chain
  analysisChain = new TChain("aodTree");
  if (TString(incollection).Contains(".root")){
    analysisChain->Add(incollection);
  }
  else if (TString(incollection).Contains("xml")){
    TGrid::Connect("alien://");
    TGridCollection * coll = TAlienCollection::Open (incollection);
    while(coll->Next()){
      analysisChain->Add(TString("alien://")+coll->GetLFN());
    }
  } else {
    ifstream file_collect(incollection);
    TString line;
    while (line.ReadLine(file_collect) ) {
      analysisChain->Add(line.Data());
    }
  }
  analysisChain->GetListOfFiles()->Print();

  return analysisChain;
}


void InitAndLoadLibs(Int_t runMode, Int_t workers,Bool_t debug) {
  // Loads libs and par files + custom task and classes (the order is important)
  listToLoad->Add(new TObjString("AliAnalysisTaskPerformanceStrangeAOD.cxx"));

  if (runMode == kMyRunModeCAF)
    {
      cout << "Init in CAF mode" << endl;
    
      gEnv->SetValue("XSec.GSI.DelegProxy", "2");
      Char_t* alienuser = gSystem->Getenv("alien_API_USER");
      TProof * p = TProof::Open(alienuser!=0 ? Form("%s@alice-caf.cern.ch",alienuser) : "alice-caf.cern.ch", workers>0 ? Form("workers=%d",workers) : "");
      //TProof * p = TProof::Open("skaf.saske.sk", workers>0 ? Form("workers=%d",workers) : "");    
      p->Exec("TObject *o = gEnv->GetTable()->FindObject(\"Proof.UseMergers\"); gEnv->GetTable()->Remove(o);", kTRUE); // avoid submerging
            gProof->EnablePackage("VO_ALICE@AliRoot::v5-02-19-AN");
	    //gProof->GetManager()->SetROOTVersion("VO_ALICE@ROOT::v5-30-02");
	    //gProof->EnablePackage("VO_ALICE@AliRoot::v5-02-04-AN");


      // Enable the needed package
      // FIXME: what if I don't want to use par files?
      gSystem->AddIncludePath("-I${ALICE_ROOT}/include/");
      gSystem->AddIncludePath("-I${ALICE_ROOT}/STEER/");
      
    }
  else
    {
      cout << "Init in Local or Grid mode" << endl;
      gSystem->Load("libCore.so");  
      gSystem->Load("libTree.so");
      gSystem->Load("libGeom.so");
      gSystem->Load("libVMC.so");
      gSystem->Load("libPhysics.so");
      gSystem->Load("libSTEERBase");
      gSystem->Load("libESD");
      gSystem->Load("libAOD");
      gSystem->Load("libANALYSIS");
      gSystem->Load("libOADB.so");
      gSystem->Load("libANALYSISalice");   

      // gSystem->Load("libVMC");
      gROOT->ProcessLine(".include $ALICE_ROOT/include");
      gROOT->ProcessLine(".include $ALICE_ROOT/STEER");
    }
  // Load helper classes
  TIterator * iter = listToLoad->MakeIterator();
  TObjString * name = 0;
  while ((name = (TObjString *)iter->Next())) {
    gSystem->ExpandPathName(name->String());
    cout << name->String().Data() << endl;
    if (runMode == kMyRunModeCAF) {
      gProof->Load(name->String()+(debug?"++g":"+"));   
    } else {
      gROOT->LoadMacro(name->String()+(debug?"++g":"+"));   
    }
  }

}
 runAOD.C:1
 runAOD.C:2
 runAOD.C:3
 runAOD.C:4
 runAOD.C:5
 runAOD.C:6
 runAOD.C:7
 runAOD.C:8
 runAOD.C:9
 runAOD.C:10
 runAOD.C:11
 runAOD.C:12
 runAOD.C:13
 runAOD.C:14
 runAOD.C:15
 runAOD.C:16
 runAOD.C:17
 runAOD.C:18
 runAOD.C:19
 runAOD.C:20
 runAOD.C:21
 runAOD.C:22
 runAOD.C:23
 runAOD.C:24
 runAOD.C:25
 runAOD.C:26
 runAOD.C:27
 runAOD.C:28
 runAOD.C:29
 runAOD.C:30
 runAOD.C:31
 runAOD.C:32
 runAOD.C:33
 runAOD.C:34
 runAOD.C:35
 runAOD.C:36
 runAOD.C:37
 runAOD.C:38
 runAOD.C:39
 runAOD.C:40
 runAOD.C:41
 runAOD.C:42
 runAOD.C:43
 runAOD.C:44
 runAOD.C:45
 runAOD.C:46
 runAOD.C:47
 runAOD.C:48
 runAOD.C:49
 runAOD.C:50
 runAOD.C:51
 runAOD.C:52
 runAOD.C:53
 runAOD.C:54
 runAOD.C:55
 runAOD.C:56
 runAOD.C:57
 runAOD.C:58
 runAOD.C:59
 runAOD.C:60
 runAOD.C:61
 runAOD.C:62
 runAOD.C:63
 runAOD.C:64
 runAOD.C:65
 runAOD.C:66
 runAOD.C:67
 runAOD.C:68
 runAOD.C:69
 runAOD.C:70
 runAOD.C:71
 runAOD.C:72
 runAOD.C:73
 runAOD.C:74
 runAOD.C:75
 runAOD.C:76
 runAOD.C:77
 runAOD.C:78
 runAOD.C:79
 runAOD.C:80
 runAOD.C:81
 runAOD.C:82
 runAOD.C:83
 runAOD.C:84
 runAOD.C:85
 runAOD.C:86
 runAOD.C:87
 runAOD.C:88
 runAOD.C:89
 runAOD.C:90
 runAOD.C:91
 runAOD.C:92
 runAOD.C:93
 runAOD.C:94
 runAOD.C:95
 runAOD.C:96
 runAOD.C:97
 runAOD.C:98
 runAOD.C:99
 runAOD.C:100
 runAOD.C:101
 runAOD.C:102
 runAOD.C:103
 runAOD.C:104
 runAOD.C:105
 runAOD.C:106
 runAOD.C:107
 runAOD.C:108
 runAOD.C:109
 runAOD.C:110
 runAOD.C:111
 runAOD.C:112
 runAOD.C:113
 runAOD.C:114
 runAOD.C:115
 runAOD.C:116
 runAOD.C:117
 runAOD.C:118
 runAOD.C:119
 runAOD.C:120
 runAOD.C:121
 runAOD.C:122
 runAOD.C:123
 runAOD.C:124
 runAOD.C:125
 runAOD.C:126
 runAOD.C:127
 runAOD.C:128
 runAOD.C:129
 runAOD.C:130
 runAOD.C:131
 runAOD.C:132
 runAOD.C:133
 runAOD.C:134
 runAOD.C:135
 runAOD.C:136
 runAOD.C:137
 runAOD.C:138
 runAOD.C:139
 runAOD.C:140
 runAOD.C:141
 runAOD.C:142
 runAOD.C:143
 runAOD.C:144
 runAOD.C:145
 runAOD.C:146
 runAOD.C:147
 runAOD.C:148
 runAOD.C:149
 runAOD.C:150
 runAOD.C:151
 runAOD.C:152
 runAOD.C:153
 runAOD.C:154
 runAOD.C:155
 runAOD.C:156
 runAOD.C:157
 runAOD.C:158
 runAOD.C:159
 runAOD.C:160
 runAOD.C:161
 runAOD.C:162
 runAOD.C:163
 runAOD.C:164
 runAOD.C:165
 runAOD.C:166
 runAOD.C:167
 runAOD.C:168
 runAOD.C:169
 runAOD.C:170
 runAOD.C:171
 runAOD.C:172
 runAOD.C:173
 runAOD.C:174
 runAOD.C:175
 runAOD.C:176
 runAOD.C:177
 runAOD.C:178
 runAOD.C:179
 runAOD.C:180
 runAOD.C:181
 runAOD.C:182
 runAOD.C:183
 runAOD.C:184
 runAOD.C:185
 runAOD.C:186
 runAOD.C:187
 runAOD.C:188
 runAOD.C:189
 runAOD.C:190
 runAOD.C:191
 runAOD.C:192
 runAOD.C:193
 runAOD.C:194
 runAOD.C:195
 runAOD.C:196
 runAOD.C:197
 runAOD.C:198
 runAOD.C:199
 runAOD.C:200
 runAOD.C:201
 runAOD.C:202
 runAOD.C:203
 runAOD.C:204
 runAOD.C:205
 runAOD.C:206
 runAOD.C:207
 runAOD.C:208
 runAOD.C:209
 runAOD.C:210
 runAOD.C:211
 runAOD.C:212
 runAOD.C:213
 runAOD.C:214
 runAOD.C:215
 runAOD.C:216
 runAOD.C:217
 runAOD.C:218
 runAOD.C:219
 runAOD.C:220
 runAOD.C:221
 runAOD.C:222
 runAOD.C:223
 runAOD.C:224
 runAOD.C:225
 runAOD.C:226
 runAOD.C:227
 runAOD.C:228
 runAOD.C:229
 runAOD.C:230
 runAOD.C:231
 runAOD.C:232
 runAOD.C:233
 runAOD.C:234
 runAOD.C:235
 runAOD.C:236
 runAOD.C:237
 runAOD.C:238
 runAOD.C:239
 runAOD.C:240
 runAOD.C:241
 runAOD.C:242
 runAOD.C:243
 runAOD.C:244
 runAOD.C:245
 runAOD.C:246
 runAOD.C:247
 runAOD.C:248
 runAOD.C:249
 runAOD.C:250
 runAOD.C:251
 runAOD.C:252
 runAOD.C:253
 runAOD.C:254
 runAOD.C:255
 runAOD.C:256
 runAOD.C:257
 runAOD.C:258
 runAOD.C:259
 runAOD.C:260
 runAOD.C:261
 runAOD.C:262
 runAOD.C:263
 runAOD.C:264
 runAOD.C:265
 runAOD.C:266
 runAOD.C:267
 runAOD.C:268
 runAOD.C:269
 runAOD.C:270
 runAOD.C:271
 runAOD.C:272
 runAOD.C:273
 runAOD.C:274
 runAOD.C:275
 runAOD.C:276
 runAOD.C:277
 runAOD.C:278
 runAOD.C:279
 runAOD.C:280
 runAOD.C:281
 runAOD.C:282
 runAOD.C:283
 runAOD.C:284