updated settings for track cuts
[u/mrichter/AliRoot.git] / PWG4 / macros / AnalysisTrainPWG4Jets.C
1 //===================== ANALYSIS TRAIN =========================================
2 // To use: copy this macro to your work directory, modify the global part to match
3 // your needs, then run root.
4 //    root[0] .L AnalysisTrain.C
5 // Grid full mode as below (other modes: test, offline, submit, terminate)
6 //    root[1] AnalysisTrainPWG-244Jets("grid", "full")
7 // CAF mode (requires root v5-23-02 + aliroot v4-16-Rev08)
8 //    root[2] AnalysisTrainPWG4Jets("proof")
9 // Local mode requires AliESds.root or AliAOD.root in ./data directory
10 //    root[3] AnalysisTrainPWG4Jets("local")
11 // In proof and grid modes, a token is needed and sourcing the produced environment file.
12 //
13 // If 'saveTrain' flag is set, the train will generate a directory name and run
14 // in this directory. A configuration file 'ConfigTrain.C' will be generated. 
15 // One can replay at any time the train via:
16 //    root[1] AnalysisTrainPWG4Jets(ana_mode, plugin_mode, "train_default_<date>/ConfigTrain.C")
17
18 // For Usage with fastjet run in "offline" first and then "submit"
19 // jdl and analysismacro are automatically patched after "offline" mode
20
21 // =============================================================================
22 // ### General Steering variables
23 // =============================================================================
24 //== general setup variables
25 TString     kTrainName         = "testAnalysis"; // *CHANGE ME* (no blancs or special characters)
26 TString     kJobTag            = "PWG4 Jet Tasks analysis train configured"; // *CHANGE ME*
27
28 // Usage of par files ONLY in grid mode and ONLY if the code is not available
29 // in the deployed AliRoot versions. Par file search path: local dir, if not there $ALICE_ROOT.
30 // To refresh par files, remove the ones in the workdir, then do "make <target.par>" in 
31 // AliRoot.
32 Bool_t      kUsePAR             = kFALSE;  // use par files for extra libs
33 Bool_t      kUseCPAR            = kFALSE;  // use par files for common libs
34 Bool_t      kFillAOD = kTRUE;  // switch of AOD filling for on the fly analysis
35 Bool_t      kFilterAOD = kTRUE;
36 Int_t       kSaveAOD = 8;        // Bit switch 1 = Full AOD 2 = Jet AOD , 4 = PartCorr, 8 = JCORRAN 
37 //== general input and output variables
38
39 Int_t       iAODanalysis       = 1;      // Analysis on input AOD's
40 Int_t       iFilterAnalysis       = 0;      // Analysis on input AOD's
41 Int_t       iAODhandler        = 1;      // Analysis produces an AOD or dAOD's
42 Int_t       iCentralitySelection  = 0;      // Use the centrality
43 Int_t       iESDfilter         = 0;      // ESD to AOD filter (barrel + muon tracks)
44 Int_t       iPhysicsSelection  = 1;      // ESD to AOD filter (barrel + muon tracks)
45 UInt_t      iPhysicsSelectionFlag = 1; // set by pyshics selection and passed to the task, kMB, kUserDefined etc
46 Bool_t      useTender           = kFALSE; // use tender wagon 
47 Bool_t      kUseKinefilter     = kFALSE; // use Kinematics filter
48 Bool_t      kUseMuonfilter     = kFALSE; // use Kinematics filter
49 TString     kCommonOutputFileName = "PWG4_JetTasksOutput.root";
50 TString     kCaloQAOutputFileName = "PWG4_CaloQAOutput.root";
51
52
53 //== general process variables
54
55 // ### Other flags to steer the analysis
56 //==============================================================================
57 Bool_t      kSkipTerminate      = kTRUE; // Do not call Teminate
58 Bool_t      kUseDate            = kFALSE; // use date in train name
59 Bool_t      kUseDebug           = kTRUE; // activate debugging
60 Int_t         kErrorIgnoreLevel = -1; // takes the errror print level from .rootrc 
61 // From TError.h:
62 // const Int_t kUnset    =  -1;
63 // const Int_t kPrint    =   0;
64 // const Int_t kInfo     =   1000;
65 // const Int_t kWarning  =   2000;
66 // const Int_t kError    =   3000;
67 // const Int_t kBreak    =   4000;
68 // const Int_t kSysError =   5000;
69 // const Int_t kFatal    =   6000; 
70 Int_t         kUseSysInfo         = 0; // activate debugging
71 Long64_t    kNumberOfEvents     = 1234567890; // number of events to process from the chain
72 Bool_t      kUseMC              = kTRUE;  // use MC info
73 Bool_t      kIsMC               = kTRUE;  // is MC info, if false it overwrites Use(AOD)MC
74 Bool_t      kUseAODMC           = kTRUE;  // use MC infA
75 Bool_t      kUseESDTags         = kFALSE; // use ESD tags for selection
76 Bool_t      kUseTR              = kFALSE;  // use track references
77 Bool_t      kUseAODTags         = kFALSE;  // use AOD tags
78 Bool_t      kSaveTrain          = kFALSE;  // save train configuration as: 
79 Bool_t      kIsPbPb             = kFALSE;  // Pb+Pb
80
81
82 // ### Analysis modules to be included. Some may not be yet fully implemented.
83 //==============================================================================
84 Int_t       iJETAN             = 1;      // Jet analysis (PWG4) // 1 write standard 2 write non-standard jets, 3 wrtie both
85 Int_t       iJETSUBTRACT        = 1;      // Jet background subtration
86 TList       kJetListSpectrum;             // list of jets contains TObjString of possible jet finder names
87 TExMap      kJetMapSpectrum;             // Maps the jet finder pairs to be used in the spectrum task second number negative no pair other wise (j1+1) + (1000 * (j2+1)) +10000 * (j3+1)
88 TExMap      kJetBackMapSpectrum;             // Maps the jet finder pairs with the background branch used, just for countint of trackrefs
89 Int_t       kJetMapOffset[3] = {10000,100,1};
90 TString     kDefaultJetBranch     = "";      // is currently set when filled (iJETAN or clusters) or from config macro 
91 TString     kDefaultJetBackgroundBranch            = "";      // is currently set when filled (jet clsuters  
92 TString     kDefaultJetBackgroundBranchCut1        = "";      // is currently set when filled (jet clsuters  
93 TString     kDefaultJetBackgroundBranch_extra     = "";      // is currently set when filled (jet clsuters) 
94 TString     kJetSubtractBranches     = "";      // is currently set when filled (jet clsuters  
95 TString     kJetSubtractBranchesCut1     = "";      // is currently set when filled (jet clsuters  
96 TString     kJetSubtractBranches_extra     = "";      // is currently set when filled (jet clsuters  
97
98 TString     kDefaultJetBranchMC     = "";      // is currently set when filled (iJETAN or clusters) or from config macro 
99 TString     kDefaultJetBackgroundBranchMC     = "";      // is currently set when filled (jet clsuters  
100 TString     kDefaultJetBranchMC2     = "";      // is currently set when filled (iJETAN or clusters) or from config macro 
101 TString     kDefaultJetBackgroundBranchMC2     = "";      // is currently set when filled (jet clsuters  
102 TString     kJetSubtractMask1 = "B0";
103 TString     kJetSubtractMask2 = "B%d";
104 Int_t       iDIJETAN           = 1;
105 Int_t       iJETANLib          = 1;
106 Int_t       iPWG1QASym         = 0;      // Eva's QA task compiled on the fly...
107 Int_t       iPWG4FastEmbedding = 0;      // Generate non-standard AOD for embedding
108 Int_t       iPWG4JetTasks      = 0;      // all jet tasks flag for lib laoding
109 Int_t       iPWG4JetServices   = 0;      // jet spectrum analysis
110 Int_t       iPWG4JetSpectrum   = 0;      // jet spectrum analysis
111 Int_t       iPWG4JetResponse   = 0;      // jet response matrix
112 Int_t       iPWG4JCORRAN       = 0;      // JCORRAN module
113 Int_t       iPWG4UE            = 0;      // Underlying Event analysis
114 Int_t       iPWG4LeadingUE     = 0;      // Underlying Event analysis
115 Int_t       iPWG4CorrectionsUE = 0;      // Underlying Event analysis
116 Int_t       iPWG4TmpSourceSara = 0;      // Underlying Event analysis not in svn
117 Int_t       iPWG4Fragmentation = 1;      // Official Fragmentation
118 Int_t       iPWG4JetChem       = 0;      // Jet chemistry 
119 Int_t       iPWG4PtQAMC        = 0;      // Marta's QA tasks 
120 Int_t       iPWG4PtTrackQA     = 0;      // Marta's QA tasks  
121 Int_t       iPWG4PtSpectra     = 0;      // Marta's QA tasks 
122 Int_t       iPWG4PtQATPC       = 0;      // Marta's QA tasks 
123 Int_t       iPWG4Cosmics     = 0;      // Marta's Cosmics Taks 
124 Int_t       iPWG4ThreeJets     = 0;      // Sona's thrust task
125 Int_t       iPWG4QGSep     = 0;          // Sona's QG Separation task
126 Int_t       iPWG4Minijet       = 0;      // Eva's Mini Jet Task cluster task 
127 Int_t       iPWG4KMeans        = 0;      // Andreas' KMeans task 
128 Int_t       iPWG4Cluster       = 0;      // CKB cluster task 
129 Int_t       iEMCUtilLibs       = 0;      // Flag to satisfy dependence on EMC utils
130 Int_t       iPWG4PartCorrLibs  = 0;      // Gustavo's part corr analysis
131 Int_t       iPWG4PartCorr      = 0;      // Gustavo's part corr analysis
132 Int_t       iPWG4CaloQA        = 0;      // Gustavo's part corr analysis
133 Int_t       iPWG4JetCorr       = 0;     // Paul's jet corr analysis
134 Int_t       iPWG4Tagged        = 0;      // Gustavo's part corr analysis
135 Int_t       iPWG4omega3pi      = 0;      // Omega to 3 pi analysis (PWG4) 
136 Int_t       iPWG4GammaConvLib     = 0;      // Gamma Conversio
137 Int_t       iPWG4GammaConv     = 0;      // Gamma Conversio
138 Int_t       iPWG4CaloConv     = 0;      // Gamma Conversio
139 Int_t       kHighPtFilterMask  = 32;     // change depending on the used AOD Filter
140 TString     kDeltaAODJetName   = "AliAOD.Jets.root";     
141 TString     kDeltaAODJetNameInput   = "";     
142 TString     kDeltaAODJCORRANName   = "AliAOD.JCORRAN.root";     
143 TString     kDeltaAODPartCorrName   = "AliAOD.PartCorr.root";     
144 TString     kFastEmbeddingAOD  = "emb/AliAOD.root";
145 TString     kFastEmbAODList    = "";
146
147 //==============================================================================
148 // ### PROOF Steering varibales
149 //==============================================================================
150 //== proof setup variables
151 TString     kProofCluster      = "alicecaf.cern.ch";
152 Bool_t      kProofUseAFPAR     = kFALSE;  // use AF special par file
153 TString     kProofAFversion          = "AF-v4-17";
154 //== proof input and output variables
155 TString     kProofDataSet      = "/COMMON/COMMON/LHC09a4_run8100X#/esdTree";
156 Bool_t      kProofSaveToAlien   = kFALSE; // save proof outputs in AliEn train_[trainName]_ddMonthyyyy_time.C
157 TString     kProofOutdir       = "";
158 Bool_t      kProofClearPackages = kFALSE;
159 Int_t       kProofEvents = 10000;
160 Int_t       kProofOffset = 0;
161 //== proof process variables
162
163
164 //==============================================================================
165 // ### Grid plugin Steering varibiables
166 //==============================================================================
167 //== grid plugin setup variables
168 Bool_t      kPluginUse         = kTRUE;   // do not change
169 Bool_t      kPluginUseProductionMode  = kFALSE;   // use the plugin in production mode
170 TString     kPluginRootVersion       = "v5-28-00c";  // *CHANGE ME IF MORE RECENT IN GRID*
171 TString     kPluginAliRootVersion    = "v4-21-01a-AN";  // *CHANGE ME IF MORE RECENT IN GRID*                                          
172 Bool_t      kPluginMergeViaJDL       = kTRUE;  // merge via JDL
173 Bool_t      kPluginFastReadOption   = kFALSE;  // use xrootd tweaks
174 Bool_t      kPluginOverwriteMode    = kTRUE;  // overwrite existing collections
175 Int_t       kPluginOutputToRunNumber = 1;     // write the output to subdirs named after run number
176 // TString kPluginExecutableCommand = "root -b -q";
177 TString     kPluginExecutableCommand = "source /Users/kleinb/setup_32bit_aliroot_trunk_clean_root_trunk.sh; alienroot -b -q ";
178
179 // == grid plugin input and output variables
180 TString     kGridDatadir      = "/alice/sim/PDC_08b/LHC09a1/AOD/";
181 Int_t         kGridMaxRunsFromList = 999999999;
182 Int_t         kGridOffsetRunFromList = 0; // skip the first n runs from the list
183 TString     kGridLocalRunList = "";
184 TString     kGridOutdir       = ""; // AliEn output directory. If blank will become output_<kTrainName>
185 TString     kGridDataSet      = ""; // sub working directory not to confuse different run xmls 
186 TString     kGridExtraAliendirLevel = ""; // sub working directory not to confuse different run xmls 
187 Int_t         kGridRunRange[2]       =  {0, -1}; // Set the run range
188 TString     kGridRunPattern        = "%03d"; // important for leading zeroes!!
189 TString     kGridPassPattern       = "";
190 TString     kGridExtraFiles        = ""; // files that will be added to the input list in the JDL...
191 Int_t         kGridMaxMergeFiles      = 25; // Number of files merged in a chunk grid run range
192 TString     kGridMergeExclude       = "AliAOD.root"; // Files that should not be merged
193 TString     kGridOutputStorages      = "disk=2"; // Make replicas on the storages
194 // == grid process variables
195 Int_t       kGridRunsPerMaster     = 100; // Number of runs per master job
196 Int_t       kGridFilesPerJob       = 100; // Maximum number of files per job (gives size of AOD)
197
198 //==============================================================================
199 // ### Local Steering variables
200 //==============================================================================
201 //== local setup variables
202 //== local input and output variables
203 TString     kLocalXMLDataset   = ""; // Change local xml dataset for local interactive analysis
204 TString     kLocalDataList   = "local_deltaaod.txt"; // Change local xml dataset for local interactive analysis
205 // == local process variables
206
207 TString kPluginMode = "";
208 TString kAnalysisMode = "";
209
210
211 // Temporaries.
212 TString anaPars = "";
213 TString anaLibs = "";
214 TString anaLibsExtra = "";
215 TString anaSources = "";
216 // Function signatures
217 class AliAnalysisAlien;
218 class AliAnalysisManager;
219
220 //______________________________________________________________________________
221 void AnalysisTrainPWG4Jets(const char *analysis_mode="local", 
222                            const char *plugin_mode="",
223                            const char *config_file="",Int_t iOffset = 0,Int_t iTotal = 0)
224 {
225 // Main analysis train macro. If a configuration file is provided, all parameters
226 // are taken from there but may be altered by CheckModuleFlags.
227
228   // these flag may be needed by the config file
229   kPluginMode   = plugin_mode;
230   kAnalysisMode = analysis_mode;
231   
232   if (strlen(config_file) && !LoadConfig(config_file)) return;
233   if(iTotal>0)kGridMaxRunsFromList = iTotal; // overwrites the settings from config file
234   if(iOffset)kGridOffsetRunFromList = iOffset;
235   if(iOffset)kProofOffset = iOffset;
236
237
238    TString smode(analysis_mode);
239    smode.ToUpper();
240    if (kSaveTrain)WriteConfig();
241    // Check compatibility of selected modules 
242    CheckModuleFlags(smode);
243    //     gROOT->ProcessLine(".trace");
244
245    printf("==================================================================\n");
246    printf("===========    RUNNING ANALYSIS TRAIN %s IN %s MODE   ==========\n", kTrainName.Data(),smode.Data());
247    printf("==================================================================\n");
248                               printf("=  Configuring analysis train for:                               =\n");
249    if (iAODanalysis) printf("=  AOD analysis                                                  =\n");
250    else                     printf("=  ESD analysis                                                  =\n");
251    if (iPhysicsSelection)   printf("=  Physics selection                                                =\n");
252    if(iCentralitySelection)printf("=  Centrality selection                                                =\n");
253    if (useTender)   printf("=  Using tender                                                =\n");
254    if (iESDfilter)   printf("=  ESD filter                                                    =\n");
255    if (iJETAN)       printf("=  Jet analysis                                                  =\n");
256    printf("==================================================================\n");
257
258    char *printMask = ":: %20s  %10d\n";
259    printf(printMask,"Fill AOD",(UInt_t)kFillAOD);
260    printf(printMask,"Save AOD", (UInt_t)kSaveAOD);
261    printf(printMask,"MC truth", (UInt_t)kUseMC);
262    printf(printMask,"KINE filter", (UInt_t)kUseKinefilter);
263    printf(printMask,"track refs", (UInt_t)kUseTR);
264    printf(printMask,"tags", (UInt_t)kUseESDTags);
265    printf(printMask,"AOD tags", (UInt_t)kUseAODTags);
266    printf(printMask,"debugging", (UInt_t)kUseDebug);
267    printf(printMask,"PAR files", (UInt_t)kUsePAR);
268    printf(printMask,"AliEn plugin", (UInt_t)kPluginUse);
269    printf(printMask,"JETAN subtract", (UInt_t)iJETSUBTRACT);
270    printf(printMask,"PWG1 QA sym", iPWG1QASym);
271    printf(printMask,"PWG4 Source Sara",iPWG4TmpSourceSara);
272    printf(printMask,"PWG4 Fragmentation",iPWG4Fragmentation);
273    printf(printMask,"PWG4 Jet Chem",iPWG4JetChem);
274    printf(printMask,"PWG4 Jet tasks",iPWG4JetTasks);
275    printf(printMask,"PWG4 Jet Services",iPWG4JetServices);     
276    printf(printMask,"PWG4 Jet Spectrum",iPWG4JetSpectrum);
277    printf(printMask,"PWG4 JCORRAN",iPWG4JCORRAN);
278    printf(printMask,"PWG4 UE",iPWG4UE); 
279    printf(printMask,"PWG4 Leading UE",iPWG4LeadingUE); 
280    printf(printMask,"PWG4 Corrections UE",iPWG4CorrectionsUE); 
281    printf(printMask,"PWG4 Pt QA MC",iPWG4PtQAMC);
282    printf(printMask,"PWG4 Pt QA track",iPWG4PtTrackQA);
283    printf(printMask,"PWG4 Pt Spectra",iPWG4PtSpectra);
284    printf(printMask,"PWG4 Pt QA TPC",iPWG4PtQATPC);     
285    printf(printMask,"PWG4 Cosmics",iPWG4Cosmics);     
286    printf(printMask,"PWG4 Three Jets",iPWG4ThreeJets);
287    printf(printMask,"PWG4 QGSep",iPWG4QGSep);
288    printf(printMask,"PWG4 Minijet",iPWG4Minijet);
289    printf(printMask,"PWG4 KMeans",iPWG4KMeans);
290    printf(printMask,"PWG4 Cluster",iPWG4Cluster);
291    printf(printMask,"PWG4 Part Corr",iPWG4PartCorr);
292    printf(printMask,"PWG4 Calo QA",iPWG4CaloQA);
293    printf(printMask,"PWG4 Jet Corr",iPWG4JetCorr);
294    printf(printMask,"PWG4 JCORRAN",iPWG4JCORRAN);
295    printf(printMask,"PWG4 Tagged",iPWG4Tagged);
296    printf(printMask,"PWG4 omega to 3 pi ",iPWG4omega3pi);
297    printf(printMask,"PWG4 Gamma Conv",iPWG4GammaConv);
298    printf(printMask,"PWG4 Calo Conv",iPWG4CaloConv);
299    printf(printMask,"HighPt FilterMask",kHighPtFilterMask);    
300    
301    //==========================================================================
302    // Connect to back-end system
303    if (!Connect(smode)) {
304       ::Error("AnalysisTrain", "Could not connect to %s back-end", analysis_mode);
305       return;
306    }   
307
308    // Load common libraries and set include path
309    if (!LoadCommonLibraries(smode)) {
310       ::Error("AnalysisTrain", "Could not load common libraries");
311       return;
312    }
313
314
315     
316    // Make the analysis manager and connect event handlers
317    AliAnalysisManager *mgr  = new AliAnalysisManager("PWG4Train", "pwg4 mini train");
318    if (kCommonOutputFileName.Length()>0)mgr->SetCommonFileName(kCommonOutputFileName.Data());
319    if (kProofSaveToAlien) mgr->SetSpecialOutputLocation(kProofOutdir);
320    mgr->SetNSysInfo(0);
321    if (!strcmp(plugin_mode, "test")) mgr->SetNSysInfo(1);
322    if (kUseSysInfo)mgr->SetNSysInfo(kUseSysInfo);
323    mgr->SetSkipTerminate(kSkipTerminate);
324
325    // Load analysis specific libraries
326    if (!LoadAnalysisLibraries(smode)) {
327       ::Error("AnalysisTrain", "Could not load analysis libraries");
328      return;
329    }   
330
331    // Create input handler (input container created automatically)
332    if (iAODanalysis) {
333    // AOD input handler
334       AliAODInputHandler *aodH = new AliAODInputHandler();
335       mgr->SetInputEventHandler(aodH);
336       if (kDeltaAODJetNameInput.Length()){
337         Printf("Adding Friend %s",kDeltaAODJetNameInput.Data());
338         aodH->AddFriend(kDeltaAODJetNameInput.Data());
339       }
340       //      if (iPWG4PartCorr) aodH->AddFriend(Form("deltas/%s"kDeltaAODJetName.Data()));
341    } else {   
342    // ESD input handler
343       AliESDInputHandler *esdHandler = new AliESDInputHandler();
344       if (kUseESDTags) esdHandler->SetReadTags();
345       esdHandler->SetReadFriends(kFALSE);
346       mgr->SetInputEventHandler(esdHandler);       
347       //      if(iPWG4PtQATPC&& !kTrainName.Contains("pass5"))esdHandler->SetActiveBranches("ESDfriend");
348
349    }
350
351    // Monte Carlo handler
352    if (kUseMC && !iAODanalysis) {
353       AliMCEventHandler* mcHandler = new AliMCEventHandler();
354       mgr->SetMCtruthEventHandler(mcHandler);
355       mcHandler->SetReadTR(kUseTR); 
356    }   
357    // AOD output container, created automatically when setting an AOD handler
358    if (iAODhandler) {
359       // AOD output handler
360       AliAODHandler* aodHandler   = new AliAODHandler();
361       aodHandler->SetOutputFileName("AliAOD.root");
362       aodHandler->SetFillAODforRun(kFillAOD);
363       //
364       mgr->SetOutputEventHandler(aodHandler);
365       AliAnalysisDataContainer * cout_aod = mgr->GetCommonOutputContainer();
366       cout_aod->SetSpecialOutput();
367    }
368    // Debugging if needed
369
370    if (kUseDebug){
371      mgr->SetDebugLevel(3);
372    }
373    if(kUseSysInfo>0){
374      mgr->RegisterExtraFile("syswatch.root");
375      if(kGridMergeExclude.Length())kGridMergeExclude += " ";
376      kGridMergeExclude += "syswatch.root";
377    }
378    else{
379      AliLog::SetGlobalLogLevel(AliLog::kError);
380    }
381
382
383    //==========================================================================
384    // Create the chain. In this example it is created only from ALIEN files but
385    // can be done to work in batch or grid mode as well.
386    TChain *chain = CreateChain(smode, plugin_mode);
387         
388    //==========================================================================
389    // Load the tasks configuration macros for all wagons. These files are supposed now to be
390    // in the current workdir, but in AliEn they will be in the file catalog, 
391    // mapped from AliRoot and pecified in the jdl input list.
392     
393    // For now connection to top input container and common AOD output container
394    // is done in this macro, but in future these containers will be connected
395    // from each task configuration macro.
396    
397    //                                                                                                                              
398    // Tender and supplies. Needs to be called for every event.                                                                     
399    //                                                                                                                              
400
401    if (useTender) {
402       gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/TenderSupplies/AddTaskTender.C");
403       AliAnalysisTaskSE *tender = AddTaskTender(kTRUE);
404       //      tender->SelectCollisionCandidates();                                                                                      
405       tender->SetDebugLevel(2);
406    }
407
408    
409    Float_t fTrackEtaWindow = 0.9;
410    Float_t fJetEtaWindow   = 0.5;
411
412    /*
413    if(kIsPbPb){// for pass1
414      Float_t fTrackEtaWindow = 0.8;
415      Float_t fJetEtaWindow   = 0.4;
416    }
417    */
418
419
420    if(iPhysicsSelection && !iAODanalysis){
421      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
422      Int_t iTriggerHIC = 0;
423      Bool_t rejectBkg = true;
424      if(kIsPbPb){
425        iTriggerHIC = 2;
426        rejectBkg = false; // for the moment...
427      }
428      AliPhysicsSelectionTask* physSelTask = AddTaskPhysicsSelection(kIsMC,rejectBkg);  
429
430      mgr->RegisterExtraFile("EventStat_temp.root");
431      mgr->AddStatisticsTask();
432    }
433    else{
434      iPhysicsSelectionFlag = AliVEvent::kMB;
435    }
436
437    if(iCentralitySelection){
438
439      // has to run before AOD filter
440      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCentrality.C");
441      //     const char* file1="$ALICE_ROOT/ANALYSIS/macros/AliCentralityBy1D_137161.root";
442      //     const char* file2="$ALICE_ROOT/ANALYSIS/macros/AliCentralityByFunction_137161.root";
443      AliCentralitySelectionTask *taskC = AddTaskCentrality();
444       if (!taskC) ::Warning("AnalysisTrainPWG4Jets", "AliCentralitySelectionTask cannot run for this train conditions - EXCLUDED");
445    }
446
447    if (iESDfilter && !iAODanalysis) {
448       //  ESD filter task configuration.
449       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskESDFilterPWG4Train.C");
450       AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(kUseKinefilter,kUseMuonfilter);
451       taskesdfilter->SetEnableFillAOD(!kFilterAOD);
452       taskesdfilter->DisableV0s();
453       taskesdfilter->DisableCascades();
454       taskesdfilter->DisableKinks();
455       taskesdfilter->DisablePmdClusters();
456       taskesdfilter->DisableCaloClusters();
457       taskesdfilter->DisableCells();
458
459       if(kIsMC){
460         mgr->RegisterExtraFile("pyxsec_hists.root");
461         if(kGridMergeExclude.Length())kGridMergeExclude += " ";
462         kGridMergeExclude += "pyxsec_hists.root";
463
464       }
465    }   
466
467    // AOD tags
468    if (kUseAODTags) {
469       AliAnalysisTaskTagCreator* tagTask = new AliAnalysisTaskTagCreator("AOD Tag Creator");
470       mgr->AddTask(tagTask);
471       AliAnalysisDataContainer *coutTags = mgr->CreateContainer("cTag",  TTree::Class(), 
472                                            AliAnalysisManager::kOutputContainer, "AOD.tag.root");
473       mgr->ConnectInput (tagTask, 0, mgr->GetCommonInputContainer());
474       mgr->ConnectOutput(tagTask, 1, coutTags);
475    }   
476
477    if (iPWG4FastEmbedding) {
478      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskFastEmbedding.C");
479      AliAnalysisTaskFastEmbedding *taskEmbedding = 0;
480      if(kFastEmbAODList.Length()) taskEmbedding = AddTaskFastEmbedding(kFastEmbAODList, 1);
481      else                         taskEmbedding = AddTaskFastEmbedding(kFastEmbeddingAOD, 0);
482      taskEmbedding->SetJetBranch("jetsAOD_UA104_B0_Filter00256_Cut01000");
483      // taskEmbedding->SetEvtSelecMode(AliAnalysisTaskFastEmbedding::kEventsAll);
484      // taskEmbedding->SetDebugLevel(10);
485    }
486
487     // Jet analysis
488    if (iJETAN) {
489       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJets.C");
490       AliAnalysisTaskJets *taskjets = 0;
491       if(iJETAN&1){
492         /*
493         taskjets = AddTaskJets(kHighPtFilterMask); 
494         taskjets->SetName("StandardJets");
495         taskjets->SetNonStdBranch("");
496         */
497       }
498       if(iJETAN&2){
499         // Set only few jet finders  backgroudn subtraction w an wo 
500         
501         taskjets = AddTaskJets("AOD","UA1",0.4,kHighPtFilterMask,1.,0); // no background subtraction
502         if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
503         TString cTmp("");       
504         cTmp = taskjets->GetNonStdBranch();
505         if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
506
507         taskjets = AddTaskJets("AOD","UA1",0.4,kHighPtFilterMask,2.,0); // no background subtraction
508         if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
509         TString cTmp("");       
510         cTmp = taskjets->GetNonStdBranch();
511         if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
512
513
514         // STANDARD UA jet finders pT cut 1 GeV background mode 2 R = 0.4
515         if(kIsPbPb){
516           taskjets = AddTaskJets("AOD","UA1",0.4,kHighPtFilterMask,1.,2); // background subtraction
517           if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
518           cTmp = taskjets->GetNonStdBranch();
519           if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
520           taskjets = AddTaskJets("AOD","UA1",0.4,kHighPtFilterMask,2.,2); // background subtraction
521           if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
522           cTmp = taskjets->GetNonStdBranch();
523           if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
524         }
525
526
527
528         // SICONE 
529         /*
530         taskjets = AddTaskJets("AOD","SISCONE",0.4,kHighPtFilterMask,0.15,0); //no background subtraction to be done later....
531         if(kDeltaAODJetName.Length()>0)taskjets->SetNonStdOutputFile(kDeltaAODJetName.Data());
532         cTmp = taskjets->GetNonStdBranch();
533         if(cTmp.Length()>0)kJetSubtractBranches += Form("%s ",cTmp.Data());
534         if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
535         */
536         if(kUseAODMC){
537           // STANDARD UA jet finders pT cut 1 GeV background mode 2 R = 0.4
538           if(kIsPbPb){
539             taskjets = AddTaskJets("AODMC","UA1",0.4,kHighPtFilterMask,1.,2); // background subtraction
540             cTmp = taskjets->GetNonStdBranch();
541             if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
542             taskjets = AddTaskJets("AODMC2","UA1",0.4,kHighPtFilterMask,1.,2); // background subtraction
543             cTmp = taskjets->GetNonStdBranch();
544             if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
545           }
546           else{
547             taskjets = AddTaskJets("AODMC","UA1",0.4,kHighPtFilterMask,1.,0); // no background subtraction
548             cTmp = taskjets->GetNonStdBranch();
549             if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
550             taskjets = AddTaskJets("AODMC2","UA1",0.4,kHighPtFilterMask,1.,0); // no background subtraction
551             cTmp = taskjets->GetNonStdBranch();
552             if(cTmp.Length())kJetListSpectrum.Add(new TObjString(cTmp.Data()));
553           }
554         }
555         if(kDeltaAODJetName.Length()>0)mgr->RegisterExtraFile(kDeltaAODJetName.Data()); 
556       }
557       if (!taskjets) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
558    }
559
560
561    if (iPWG4FastEmbedding && iJETAN) {
562      AliAnalysisTaskJets *taskEmbJets = AddTaskJets("AODextra", "FASTJET", 0.4, kHighPtFilterMask);
563      taskEmbJets->ReadAODFromOutput();
564      kJetSubtractBranches_extra += Form("%s ", taskEmbJets->GetNonStdBranch());
565
566      taskEmbJets = AddTaskJets("AODextraonly", "FASTJET", 0.4, kHighPtFilterMask);
567      taskEmbJets->ReadAODFromOutput();
568     
569      taskEmbJets = AddTaskJets("AODextra", "UA1", 0.4, kHighPtFilterMask,1.,0);
570      taskEmbJets->ReadAODFromOutput();
571      taskEmbJets = AddTaskJets("AODextraonly", "UA1", 0.4, kHighPtFilterMask,1.,0);
572      taskEmbJets->ReadAODFromOutput();
573      taskEmbJets = AddTaskJets("AODextra", "UA1", 0.4, kHighPtFilterMask,1.,2);
574      taskEmbJets->ReadAODFromOutput();
575    }
576
577    if(iPWG4Cluster){
578      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetCluster.C");
579      AliAnalysisTaskJetCluster *taskCl = 0;
580      Float_t fCenUp = 0;
581      Float_t fCenLo = 0;
582      if(kIsPbPb&&!kIsMC){
583        fCenLo = 0;
584        fCenUp = 80;
585      }
586      if(iPWG4Cluster&1){
587
588        if(kIsPbPb){
589          taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow,0); // this one is for the background and random jets, random cones with no skip
590          taskCl->SetBackgroundCalc(kTRUE);
591          taskCl->SetNRandomCones(1);
592          taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
593          //      taskCl->SetDebugLevel(11);
594          taskCl->SetCentralityCut(fCenLo,fCenUp);
595          taskCl->SetGhostEtamax(fTrackEtaWindow);
596          kDefaultJetBackgroundBranch = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch());
597          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
598          kJetListSpectrum.Add(new TObjString(Form("%sRandomConeSkip%02d",taskCl->GetJetOutputBranch(),0)));
599          kJetListSpectrum.Add(new TObjString(Form("%sRandomCone_random",taskCl->GetJetOutputBranch())));
600          kJetSubtractBranches += Form("%s%s ",taskCl->GetJetOutputBranch(),"RandomConeSkip00");
601          kJetSubtractBranches += Form("%s%s ",taskCl->GetJetOutputBranch(),"RandomCone_random");
602
603          taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1, kDeltaAODJetName.Data(),2.0,fTrackEtaWindow,0); // this one is for the background and random jets, random cones with no skip
604          taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
605          taskCl->SetNRandomCones(1);
606          taskCl->SetBackgroundCalc(kTRUE);
607          taskCl->SetCentralityCut(fCenLo,fCenUp);
608          taskCl->SetGhostEtamax(fTrackEtaWindow);
609          if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
610          kDefaultJetBackgroundBranchCut1 = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch());
611          kJetSubtractBranchesCut1 += Form("%s%s ",taskCl->GetJetOutputBranch(),"RandomConeSkip00");
612          kJetSubtractBranchesCut1 += Form("%s%s ",taskCl->GetJetOutputBranch(),"RandomCone_random");
613          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
614          kJetListSpectrum.Add(new TObjString(Form("%sRandomConeSkip%02d",taskCl->GetJetOutputBranch(),0)));
615          kJetListSpectrum.Add(new TObjString(Form("%sRandomCone_random",taskCl->GetJetOutputBranch())));
616
617          if (iPWG4FastEmbedding) {
618            AliAnalysisTaskJetCluster *taskClEmb = 0;
619            taskClEmb = AddTaskJetCluster("AODextra","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow); // this one is for the background and random jets
620          taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
621            taskClEmb->SetBackgroundCalc(kTRUE);
622            taskClEmb->SetCentralityCut(fCenLo,fCenUp);
623            taskClEmb->SetGhostEtamax(fTrackEtaWindow);
624            if(iAODanalysis==2)taskClEmb->SetAODTrackInput(kTRUE);
625            kDefaultJetBackgroundBranch_extra = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskClEmb->GetJetOutputBranch());
626
627            taskClEmb = AddTaskJetCluster("AODextraonly","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow); // this one is for the background and random jets
628            taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
629            taskClEmb->SetBackgroundCalc(kFALSE);
630            taskClEmb->SetCentralityCut(fCenLo,fCenUp);
631            taskClEmb->SetGhostEtamax(fTrackEtaWindow);
632            if(iAODanalysis==2)taskClEmb->SetAODTrackInput(kTRUE);
633            
634            taskClEmb = AddTaskJetCluster("AODextra","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.4,0,1,kDeltaAODJetName.Data(),0.15,fTrackEtaWindow);
635          taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
636            taskClEmb->SetCentralityCut(fCenLo,fCenUp);
637            taskClEmb->SetBackgroundBranch(kDefaultJetBackgroundBranch_extra.Data());
638            kJetSubtractBranches_extra += Form("%s ",taskClEmb->GetJetOutputBranch());
639            if(iAODanalysis==2)taskClEmb->SetAODTrackInput(kTRUE);
640
641            taskClEmb = AddTaskJetCluster("AODextraonly","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.4,0,1,kDeltaAODJetName.Data(),0.15,fTrackEtaWindow);
642            taskClEmb->SetCentralityCut(fCenLo,fCenUp);
643            if(iAODanalysis==2)taskClEmb->SetAODTrackInput(kTRUE);
644          }
645
646          taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.2,0,1, kDeltaAODJetName.Data(),0.15); // this one is for the background and random jets
647          taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
648          taskCl->SetBackgroundCalc(kTRUE);
649          taskCl->SetCentralityCut(fCenLo,fCenUp);
650          taskCl->SetGhostEtamax(fTrackEtaWindow);
651          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
652          if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
653        }
654        else{
655          taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.6,0,1,kDeltaAODJetName.Data(),0.15); // this one is for the background jets
656          taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
657          taskCl->SetBackgroundCalc(kTRUE);
658          kDefaultJetBackgroundBranch = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch());
659          taskCl->SetGhostEtamax(fTrackEtaWindow);
660          if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
661          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
662
663          taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1,kDeltaAODJetName.Data(),0.15); 
664          taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
665          taskCl->SetBackgroundCalc(kTRUE);
666          taskCl->SetGhostEtamax(fTrackEtaWindow);
667          if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
668          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
669        } 
670
671        taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.4,2,1,kDeltaAODJetName.Data(),0.15);
672        taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
673        taskCl->SetCentralityCut(fCenLo,fCenUp);
674        if(kIsPbPb)taskCl->SetBackgroundBranch(kDefaultJetBackgroundBranch.Data());
675        //       taskCl->SetDebugLevel(3);
676  
677        taskCl->SetNRandomCones(1);
678        if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
679        kDefaultJetBranch = taskCl->GetJetOutputBranch();
680        kJetSubtractBranches += Form("%s ",taskCl->GetJetOutputBranch());
681        kJetSubtractBranches += Form("%s%s ",taskCl->GetJetOutputBranch(),"RandomConeSkip02");
682        kJetSubtractBranches += Form("%s%s ",taskCl->GetJetOutputBranch(),"RandomCone_random");
683        kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
684        kJetListSpectrum.Add(new TObjString(Form("%sRandomConeSkip%02d",taskCl->GetJetOutputBranch(),2)));
685        kJetListSpectrum.Add(new TObjString(Form("%sRandomCone_random",taskCl->GetJetOutputBranch())));
686
687        taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.4,2,1,kDeltaAODJetName.Data(),2.0);
688        taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
689        taskCl->SetCentralityCut(fCenLo,fCenUp);
690        if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
691        if(kIsPbPb)taskCl->SetBackgroundBranch(kDefaultJetBackgroundBranchCut1.Data());
692        kJetSubtractBranchesCut1 += Form("%s ",taskCl->GetJetOutputBranch());
693        kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
694
695        if(iFilterAnalysis==2){
696          if(kIsPbPb)taskCl->SetJetTriggerPtCut(50.);
697          else taskCl->SetJetTriggerPtCut(20.);
698        }
699
700        // tmp track qa...
701        taskCl = AddTaskJetCluster("AOD","",1<<4|1<<8,iPhysicsSelectionFlag,"ANTIKT",0.4,2,1,kDeltaAODJetName.Data(),2.0);
702        taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
703        taskCl->SetCentralityCut(fCenLo,fCenUp);
704        taskCl->SetFilterMask(1<<4|1<<8,1);
705
706
707        taskCl = AddTaskJetCluster("AOD","",1<<9|1<<8,iPhysicsSelectionFlag,"ANTIKT",0.4,2,1,kDeltaAODJetName.Data(),2.0);
708        taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
709        taskCl->SetCentralityCut(fCenLo,fCenUp);
710        taskCl->SetFilterMask(1<<9|1<<8,2);
711
712        
713
714        taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.2,0,1,kDeltaAODJetName.Data(),0.15);
715        taskCl->SetCentralityCut(fCenLo,fCenUp);
716        taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
717        if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
718        if(kIsPbPb)taskCl->SetBackgroundBranch(kDefaultJetBackgroundBranch.Data());
719        kJetSubtractBranches += Form("%s ",taskCl->GetJetOutputBranch());
720        kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
721
722        if(kUseAODMC){
723          if(kIsPbPb){
724            taskCl = AddTaskJetCluster("AODMC","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow); // this one is for the background and random jets
725            taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
726            taskCl->SetBackgroundCalc(kTRUE);
727            taskCl->SetGhostEtamax(0.9);
728            kDefaultJetBackgroundBranchMC = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch());
729            if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);     
730          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
731
732            taskCl = AddTaskJetCluster("AODMC2","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.4,0,1, kDeltaAODJetName.Data(),0.15); // this one is for the background and random jets
733          taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
734            taskCl->SetBackgroundCalc(kTRUE);
735            taskCl->SetGhostEtamax(fTrackEtaWindow);
736            kDefaultJetBackgroundBranchMC2 = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch(),fTrackEtaWindow); 
737            if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
738            kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
739          }
740          else{
741            taskCl = AddTaskJetCluster("AODMC","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.6,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow); // this one is for the background and random jets
742            taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
743            taskCl->SetBackgroundCalc(kTRUE);
744            taskCl->SetGhostEtamax(fTrackEtaWindow);
745            kDefaultJetBackgroundBranchMC = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch());
746          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));       
747
748            taskCl = AddTaskJetCluster("AODMC2","",kHighPtFilterMask,iPhysicsSelectionFlag,"KT",0.6,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow); // this one is for the background and random jets
749            taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
750            taskCl->SetBackgroundCalc(kTRUE);
751            taskCl->SetGhostEtamax(fTrackEtaWindow);
752            kDefaultJetBackgroundBranchMC2 = Form("%s_%s",AliAODJetEventBackground::StdBranchName(),taskCl->GetJetOutputBranch()); 
753            if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
754            kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
755            // pp background calcs...
756          }
757          
758          taskCl = AddTaskJetCluster("AODMC","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.4,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow); 
759          taskCl->SetGhostEtamax(fTrackEtaWindow);
760          taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
761          if(kIsPbPb)taskCl->SetBackgroundBranch(kDefaultJetBackgroundBranchMC.Data());   
762          kDefaultJetBranchMC = taskCl->GetJetOutputBranch();
763          if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
764          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
765
766          taskCl = AddTaskJetCluster("AODMC2","",kHighPtFilterMask,iPhysicsSelectionFlag,"ANTIKT",0.4,0,1, kDeltaAODJetName.Data(),0.15,fTrackEtaWindow);
767          taskCl->SetEventSelection(kTRUE); // saves some computing time, not all vertices are processed
768          if(kIsPbPb)taskCl->SetBackgroundBranch(kDefaultJetBackgroundBranchMC2.Data());  
769          kDefaultJetBranchMC2 = taskCl->GetJetOutputBranch();
770          if(iAODanalysis==2)taskCl->SetAODTrackInput(kTRUE);
771          kJetListSpectrum.Add(new TObjString(taskCl->GetJetOutputBranch()));
772        }
773        
774        
775        if (!taskCl) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskCluster cannot run for this train conditions - EXCLUDED");
776      }
777    }
778
779
780    if(iJETSUBTRACT&&kJetSubtractBranches.Length()){
781      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetBackgroundSubtract.C");
782      AliAnalysisTaskJetBackgroundSubtract *taskSubtract = 0;
783      if(kJetSubtractBranches.Length()){
784
785
786
787
788        for(int iB = 1;iB<3;iB++){
789          if(iB>2)continue;
790          taskSubtract = AddTaskJetBackgroundSubtract(kJetSubtractBranches,iB,kJetSubtractMask1.Data(),kJetSubtractMask2.Data());
791          taskSubtract->SetBackgroundBranch(kDefaultJetBackgroundBranch.Data());         taskSubtract->SelectCollisionCandidates(iPhysicsSelectionFlag);
792          if(kDeltaAODJetName.Length()>0)taskSubtract->SetNonStdOutputFile(kDeltaAODJetName.Data());
793          //      taskSubtract->SetDebugLevel(10);
794          TString cTmp;       
795          TObjArray *objArr = kJetSubtractBranches.Tokenize(" ");
796          for(int iJB = 0;iJB<objArr->GetEntries();iJB++){
797            TObjString *ostr = (TObjString*)objArr->At(iJB);
798            cTmp = ostr->GetString().Data();
799            cTmp.ReplaceAll(kJetSubtractMask1.Data(),Form(kJetSubtractMask2.Data(),iB));
800            kJetListSpectrum.Add(new TObjString(cTmp.Data()));
801          }
802          
803          //     taskSubtract->SetDebugLevel(3);
804          if(iB==2){
805            if(kJetSubtractBranches.Contains(kDefaultJetBranch.Data())&&kIsPbPb){
806              kDefaultJetBranch.ReplaceAll(taskSubtract->GetToReplace(),Form(taskSubtract->GetReplacementMask(),taskSubtract->GetSubtractionMethod()));
807            }
808          }
809          
810        }
811
812        //
813        // cut1
814        Int_t iB = 2;
815        taskSubtract = AddTaskJetBackgroundSubtract(kJetSubtractBranchesCut1,iB,kJetSubtractMask1.Data(),kJetSubtractMask2.Data(),"Cut2000");
816        taskSubtract->SetBackgroundBranch(kDefaultJetBackgroundBranchCut1.Data());               
817        taskSubtract->SelectCollisionCandidates(iPhysicsSelectionFlag);
818        if(kDeltaAODJetName.Length()>0)taskSubtract->SetNonStdOutputFile(kDeltaAODJetName.Data());
819
820        objArr = kJetSubtractBranchesCut1.Tokenize(" ");
821        for(int iJB = 0;iJB<objArr->GetEntries();iJB++){
822          TObjString *ostr = (TObjString*)objArr->At(iJB);
823          cTmp = ostr->GetString().Data();
824          cTmp.ReplaceAll(kJetSubtractMask1.Data(),Form(kJetSubtractMask2.Data(),iB));
825          kJetListSpectrum.Add(new TObjString(cTmp.Data()));
826        }
827
828
829      }
830      if(kJetSubtractBranches_extra.Length()){
831        taskSubtract = AddTaskJetBackgroundSubtract(kJetSubtractBranches_extra,2,kJetSubtractMask1.Data(),kJetSubtractMask2.Data(),"extra");
832        taskSubtract->SetBackgroundBranch(kDefaultJetBackgroundBranch_extra.Data());
833        taskSubtract->SelectCollisionCandidates(iPhysicsSelectionFlag);
834        //taskSubtract->SetDebugLevel(3);
835        if(kDeltaAODJetName.Length()>0)taskSubtract->SetNonStdOutputFile(kDeltaAODJetName.Data());
836        if(kJetSubtractBranches_extra.Contains(kDefaultJetBranch.Data())){
837          kDefaultJetBranch.ReplaceAll(taskSubtract->GetToReplace(),Form(taskSubtract->GetReplacementMask(),taskSubtract->GetSubtractionMethod()));
838        }
839      }
840      if (!taskSubtract) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetBackgroundSubtrac cannot run for this train conditions - EXCLUDED");     
841    }
842
843    if (iDIJETAN) {
844       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskDiJets.C");
845       AliAnalysisTaskDiJets *taskdijets = 0;
846       if(iDIJETAN&1)taskdijets = AddTaskDiJets(); 
847       if (!taskdijets) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
848       if(iDIJETAN&2){
849         taskdijets = AddTaskDiJets("jetsAOD_CDF07"); 
850         taskdijets = AddTaskDiJets("jetsAOD_DA07"); 
851         taskdijets = AddTaskDiJets("jetsAOD_FASTJET07"); 
852         taskdijets = AddTaskDiJets("jetsAOD_FASTKT07"); 
853         taskdijets = AddTaskDiJets("jetsAOD_SISCONE07"); 
854         taskdijets = AddTaskDiJets("jetsAOD_UA107");
855       }
856    }
857
858    if(iPWG1QASym){
859      gROOT->LoadMacro("$ALICE_ROOT/PWG1/PilotTrain/AddTaskQAsym.C");
860      AliAnalysisTaskQASym *taskQASym = AddTaskQAsym(-1);
861      if (!taskQASym) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQASym cannot run for this train conditions - EXCLUDED");
862    }
863
864
865
866    if(iPWG4TmpSourceSara){
867      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskEta.C");
868      AliAnalysisTaskEta *taskEta = AddTaskEta();
869      if (!taskEta) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskEta cannot run for this train conditions - EXCLUDED");
870    }
871
872
873    if(iPWG4JetServices){
874      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetServices.C");
875      AliAnalysisTaskJetServices *taskjetServ = 0;
876      taskjetServ = AddTaskJetServices();
877      if (!taskjetServ) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetServices cannot run for this train conditions - EXCLUDED");
878      if(kGridRunRange[0]>0)taskjetServ->SetRunRange(kGridRunRange[0],kGridRunRange[1]);
879      else taskjetServ->SetRunRange(110000,160000);
880      taskjetServ->SetMCData(kIsMC);
881      taskjetServ->SetUsePhysicsSelection((Bool_t)iPhysicsSelection);
882      taskjetServ->SetPhysicsSelectionFlag(iPhysicsSelectionFlag); // 
883      taskjetServ->SetNonStdFile(kDeltaAODJetName.Data());
884      taskjetServ->SetTrackEtaWindow(fTrackEtaWindow);
885      taskjetServ->SetFilterMask(kHighPtFilterMask);
886      if(kIsPbPb){
887        if(kDeltaAODJetName.Length()>0&&kFilterAOD)taskjetServ->SetFilterAODCollisions(kTRUE);
888        //       else if(iAODanalysis)taskjetServ->SetFilterAODCollisions(kTRUE);
889        //       taskjetServ->SetDebugLevel(3);
890        taskjetServ->SetZVertexCut(8.);
891      }
892      if(iAODanalysis){
893        //  
894        taskjetServ->SetAODInput(kTRUE);
895      }
896    }
897
898    if(iPWG4JetSpectrum){
899      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetSpectrum2.C");
900      AliAnalysisTaskJetSpectrum2 *taskjetSpectrum = 0;
901      TString bkgClusters = kDefaultJetBackgroundBranch.Data(); 
902      bkgClusters.ReplaceAll(Form("%s_",AliAODJetEventBackground::StdBranchName()),"");
903      Printf("############# Possible jet branches ###################");
904      for(int iJF = 0;iJF < kJetListSpectrum.GetSize();iJF++){
905        TObjString *objStr = (TObjString*)kJetListSpectrum.At(iJF);
906        Printf("%3d: %s",iJF+1,objStr->GetString().Data());
907      }
908
909      if(iPWG4JetSpectrum&1){
910        if(kIsPbPb){
911          for(int iJF = 0;iJF < kJetListSpectrum.GetSize();iJF++){
912            Long64_t value = kJetMapSpectrum(iJF+1);
913            Printf("iJF: %d value: %d", iJF+1,(Int_t)value);
914            if(value==0)continue;
915            TObjString *objStr = (TObjString*)kJetListSpectrum.At(iJF);
916            TString bName1 = objStr->GetString().Data();
917            TString bName2[3];
918            
919            TObjString *objStrBkg = (TObjString*)kJetListSpectrum.At(iJF);
920            TString bBkgName1(""); 
921            TString bBkgName2[3];
922            
923            Long64_t valueBkg1 = kJetBackMapSpectrum(iJF+1);
924            if(valueBkg1>0){
925              TObjString *objStrBkg = (TObjString*)kJetListSpectrum.At(valueBkg1-1);
926              bBkgName1 = objStrBkg->GetString().Data();
927            }
928            Int_t iPartner = 0;
929            if(value>0){
930              Int_t iJF2 = -1; 
931              for(int i = 0;i<3;i++){
932                iJF2 = value/kJetMapOffset[i]-1;
933                value = value%kJetMapOffset[i];
934                Printf("%d %d", iJF2+1,(Int_t)value);
935                if(iJF2>=0&&iJF2<kJetListSpectrum.GetSize()){
936                  TObjString *objStr2 = (TObjString*)kJetListSpectrum.At(iJF2);
937                  bName2[iPartner] = objStr2->GetString().Data();
938                  Long64_t valueBkg2 = kJetBackMapSpectrum(iJF2+1);
939                  if(valueBkg2>0){
940                    TObjString *objStrBkg2 = (TObjString*)kJetListSpectrum.At(valueBkg2-1);
941                    bBkgName2[iPartner] = objStrBkg2->GetString().Data();
942                  }
943                  iPartner++;
944                }
945              }
946            }
947            
948            
949            // loop over all centralities
950            for(int ic = 0;ic<5;ic++){
951              if(ic!=0)continue;
952              Bool_t bDone = kFALSE;
953              for(int i = 0;i<TMath::Max(iPartner,1);i++){
954                if(bName2[i].Length()){
955                  taskjetSpectrum = AddTaskJetSpectrum2(bName1.Data(),bName2[i].Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,ic);
956                  bDone = kTRUE; 
957                }
958                else{
959                  if(!bDone){
960                    taskjetSpectrum = AddTaskJetSpectrum2(bName1.Data(),bName2[i].Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,ic);
961                    bDone = kTRUE; 
962                  }
963                  else{
964                    continue;
965                  }
966                }
967                Printf("%s/%s %s/%s",bName1.Data(),bBkgName1.Data(),bName2[i].Data(),bBkgName2[i].Data());
968
969                // setting all the other things...
970                taskjetSpectrum->SetTrackEtaWindow(fTrackEtaWindow);
971                taskjetSpectrum->SetJetEtaWindow(fJetEtaWindow);
972
973                // negative values do not fill the track histos
974                taskjetSpectrum->SetFlagJetType(AliAnalysisTaskJetSpectrum2::kJetGenFull,-1);
975                taskjetSpectrum->SetFlagJetType(AliAnalysisTaskJetSpectrum2::kJetGen,-1);              
976                if(!bName1.Contains("ANTIKT")||bName1.Contains("Cone")){
977                  taskjetSpectrum->SetFlagJetType(AliAnalysisTaskJetSpectrum2::kJetRecFull,-1);
978                  taskjetSpectrum->SetFlagJetType(AliAnalysisTaskJetSpectrum2::kJetRec,-1);            
979                }
980
981
982                if(bName2[i].Length()==0){
983                  taskjetSpectrum->SetFlagJetType(AliAnalysisTaskJetSpectrum2::kJetGenFull,0);
984                  taskjetSpectrum->SetFlagJetType(AliAnalysisTaskJetSpectrum2::kJetGen,0);
985                }
986                if(iAODanalysis==1){
987                  taskjetSpectrum->SetAODJetInput(kTRUE);
988                  taskjetSpectrum->SetAODTrackInput(kTRUE);
989                }
990                else if (iAODanalysis==2){
991                  taskjetSpectrum->SetAODTrackInput(kTRUE);
992                  taskjetSpectrum->SetAODJetInput(kFALSE);
993                }
994                //              taskjetSpectrum->SetDebugLevel(11);
995                taskjetSpectrum->SetBranchBkgRec(bBkgName1.Data());
996                taskjetSpectrum->SetBranchBkgGen(bBkgName2[i].Data());
997              } 
998            }
999          }
1000        }
1001        else{ // ! PbPb
1002          Int_t i = 0;
1003
1004          taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),
1005                                                "",kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
1006          
1007
1008          
1009          if(kDefaultJetBranchMC.Length()){
1010            taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),
1011                                                kDefaultJetBranchMC.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
1012            //      taskjetSpectrum->SetMinJetPt(10);
1013            taskjetSpectrum->SetTrackEtaWindow(fTrackEtaWindow);
1014            taskjetSpectrum->SetJetEtaWindow(fJetEtaWindow);
1015            taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
1016            taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
1017            if(iAODanalysis)SetAODInput(taskjetSpectrum);
1018          }
1019          if(kDefaultJetBranchMC2.Length()){
1020            taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),
1021                                                  kDefaultJetBranchMC2.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
1022            //      taskjetSpectrum->SetMinJetPt(10);
1023            taskjetSpectrum->SetTrackEtaWindow(fTrackEtaWindow);
1024            taskjetSpectrum->SetJetEtaWindow(fJetEtaWindow);
1025            taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
1026            taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
1027            if(iAODanalysis)SetAODInput(taskjetSpectrum);
1028          }
1029
1030          /*
1031          TString tmp2(kDefaultJetBranch.Data());
1032          tmp2.ReplaceAll(Form(kJetSubtractMask2.Data(),0),Form(kJetSubtractMask2.Data(),2));
1033          taskjetSpectrum = AddTaskJetSpectrum2(tmp2.Data(),kDefaultJetBranch.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
1034          //      taskjetSpectrum->SetDebugLevel(3);
1035          //        taskjetSpectrum->SetMinJetPt(10);
1036          taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
1037          taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
1038          taskjetSpectrum->SetTrackEtaWindow(0.8);
1039          taskjetSpectrum->SetJetEtaWindow(0.4);
1040
1041          // check the old subtracted vs. the new subtracted
1042          TString tmp3(kDefaultJetBranch.Data());
1043          tmp3.ReplaceAll(Form(kJetSubtractMask2.Data(),0),Form(kJetSubtractMask2.Data(),3));
1044          taskjetSpectrum = AddTaskJetSpectrum2(tmp3.Data(),kDefaultJetBranch.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
1045          //      taskjetSpectrum->SetDebugLevel(3);
1046          //        taskjetSpectrum->SetMinJetPt(10);
1047          taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
1048          taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
1049          taskjetSpectrum->SetTrackEtaWindow(0.8);
1050          taskjetSpectrum->SetJetEtaWindow(0.4);
1051          if(iAODanalysis)SetAODInput(taskjetSpectrum);
1052          */
1053        }
1054        if (!taskjetSpectrum) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetSpectrum2 cannot run for this train conditions - EXCLUDED");
1055      }
1056    }
1057    AliAnalysisManager::SetCommonFileName("PWG4_Fragmentation.root");
1058    if(iPWG4Fragmentation){
1059      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskFragmentationFunction.C");
1060        AliAnalysisTaskFragmentationFunction *taskFrag = 0;
1061        if(kUseAODMC){
1062
1063        }
1064        else{
1065
1066
1067          for(int ic = 1;ic < 5;ic++){
1068            // Anti-kT
1069            taskFrag = AddTaskFragmentationFunction(1<<23,kHighPtFilterMask, ic);
1070            if(kDeltaAODJetName.Length()>0)taskFrag->SetNonStdFile(kDeltaAODJetName.Data());
1071            if(iAODanalysis==2)taskFrag->UseAODInputJets(kFALSE);
1072
1073            // UA1
1074            taskFrag = AddTaskFragmentationFunction(1<<0,kHighPtFilterMask, ic); 
1075            if(kDeltaAODJetName.Length()>0)taskFrag->SetNonStdFile(kDeltaAODJetName.Data());
1076            if(iAODanalysis==2)taskFrag->UseAODInputJets(kFALSE);
1077
1078          // SISCONE 
1079            if(ic==1){
1080              /*
1081                taskFrag = AddTaskFragmentationFunction(1<<28,kHighPtFilterMask, ic);
1082                taskFrag = AddTaskFragmentationFunction(1<<29,kHighPtFilterMask, ic);
1083                taskFrag = AddTaskFragmentationFunction(1<<30,kHighPtFilterMask, ic);
1084              */
1085
1086
1087
1088              // Anti-kT B2 - B3
1089              if(!iAODanalysis==1){
1090                taskFrag = AddTaskFragmentationFunction(1<<26,kHighPtFilterMask, ic);
1091                if(kDeltaAODJetName.Length()>0)taskFrag->SetNonStdFile(kDeltaAODJetName.Data());
1092                if(iAODanalysis==2)taskFrag->UseAODInputJets(kFALSE);
1093                
1094                taskFrag = AddTaskFragmentationFunction(1<<27,kHighPtFilterMask, ic);
1095                if(kDeltaAODJetName.Length()>0)taskFrag->SetNonStdFile(kDeltaAODJetName.Data());
1096                if(iAODanalysis==2)taskFrag->UseAODInputJets(kFALSE);
1097              }
1098            }
1099
1100          } 
1101
1102
1103        }
1104        if (!taskFrag) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskFragmentationFunction cannot run for this train conditions - EXCLUDED");
1105    }
1106
1107    if(iPWG4JetChem){
1108      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetChem.C");
1109      AliAnalysisTask *taskChem = AddTaskJetChem(kHighPtFilterMask);
1110      if (!taskChem) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetChem cannot run for this train conditions - EXCLUDED");
1111    }
1112
1113    if (iPWG4JetResponse) {
1114      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetResponse.C");
1115      AliAnalysisTask *taskJetResponse = 0;
1116
1117      if(iJETAN){
1118         taskJetResponse = AddTaskJetResponse("jets", "FASTJET", 0.4, kHighPtFilterMask, 0.15, 0);
1119         taskJetResponse = AddTaskJetResponse("jets", "FASTJET", 0.4, kHighPtFilterMask, 0.15, 1);
1120
1121         taskJetResponse = AddTaskJetResponse("jets", "UA1", 0.4, kHighPtFilterMask, 1., 0);
1122         taskJetResponse = AddTaskJetResponse("jets", "UA1", 0.4, kHighPtFilterMask, 1., 2);
1123      }
1124      if(iPWG4Cluster){
1125         taskJetResponse = AddTaskJetResponse("clusters", "ANTIKT", 0.4, kHighPtFilterMask, 0.15, 0);
1126         taskJetResponse = AddTaskJetResponse("clusters", "ANTIKT", 0.4, kHighPtFilterMask, 0.15, 1);
1127      }
1128      if (!taskJetResponse) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetResponse cannot run for this train conditions - EXCLUDED");
1129
1130    }
1131
1132    if(iPWG4JCORRAN){
1133      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJCORRANTask.C");
1134      AliJCORRANTask* corran = AddTaskJCORRAN(kDeltaAODJCORRANName.Data(),0);
1135      if(!corran)::Warning("AnalysisTrainPWG4Jets", "AliJCORRANTask cannot run for this train conditions - EXCLUDED");
1136      else{
1137        if(kDeltaAODJCORRANName.Length()>0)mgr->RegisterExtraFile(kDeltaAODJCORRANName.Data()); 
1138      }
1139    }
1140
1141    if(iPWG4UE){
1142      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskUE.C");
1143      AliAnalysisTaskUE *taskUE = 0;
1144      if(iPWG4UE&1)taskUE = AddTaskUE(); 
1145      if(iPWG4UE&2){
1146        taskUE  =AddTaskUE("jetsAOD_CDF04","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
1147        //       taskUE  =AddTaskUE("jetsAOD_CDF07","CDF", "LJ", "TRANSV","MSP");
1148        taskUE  =AddTaskUE("jetsAOD_SISCONE04","CDF", "LJ", "TRANSV","MSP");
1149        //       taskUE  =AddTaskUE("jetsAOD_SISCONE07","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
1150        taskUE  =AddTaskUE("jetsAOD_ICDF","CDF","LJ","TRANSV","MSP");
1151        taskUE  =AddTaskUE("jetsAOD_FASTKT04","CDF", "LJ", "TRANSV","MSP");
1152        //       taskUE  =AddTaskUE("jetsAOD_FASTKT07","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
1153        taskUE  =AddTaskUE("jetsAOD_NONE","CDF", "MP_eta05", "TRANSV","MSP");
1154        taskUE  =AddTaskUE("jetsAOD_NONE","CDF", "MP_eta09", "TRANSV","MSP");
1155      }
1156
1157      if (!taskUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskUE cannot run for this train conditions - EXCLUDED");
1158    }
1159
1160    if(iPWG4LeadingUE){
1161      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskLeadingTrackUE.C");
1162      AliAnalysisTaskLeadingTrackUE *taskLeadingUE = AddTaskLeadingTrackUE(kUseMC);
1163      if (!taskLeadingUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTasLeadingTrackkUE cannot run for this train conditions - EXCLUDED");
1164      //     taskLeadingUE->SetFilterBit(64);
1165    }
1166
1167
1168    if(iPWG4CorrectionsUE){
1169      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskCorrectionsUE.C");
1170      AliAnalysisTaskCorrectionsUE *taskCorrectionsUE = 0;
1171      if(iPWG4CorrectionsUE&1)taskCorrectionsUE = AddTaskCorrectionsUE("jetsAOD_NONE","CDF","MP_eta05","TRANSV","MSP",kFALSE);
1172      if (!taskCorrectionsUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskCorrectionsUE cannot run for this train conditions - EXCLUDED");
1173    }
1174
1175    if(iPWG4ThreeJets){
1176      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskThreeJets.C");
1177      AliAnalysisTaskThreeJets *taskThree = AddTaskThreeJets();
1178      if(!taskThree)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskThreets cannot run for this train conditions - EXCLUDED");
1179    }
1180    if(iPWG4QGSep){
1181      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskQGSep.C");
1182      AliAnalysisTaskQGSep *taskQGSep = AddTaskQGSep(kUseMC,iAODanalysis);
1183      if(!taskQGSep)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQGSep cannot run for this train conditions - EXCLUDED");
1184    }
1185   
1186
1187    if(iPWG4Minijet){
1188      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskMinijet.C");
1189      AliAnalysisTaskMinijet *taskMini = AddTaskMinijet(-1,"esd",kUseMC,kGridDataSet);
1190      // if we ha highmult trigger add another task
1191      if(!taskMini)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskMinjet cannot run for this train conditions - EXCLUDED");
1192    }
1193
1194    AliAnalysisManager::SetCommonFileName("PWG4_HighPtQA.root");
1195    if(iPWG4PtQAMC){
1196      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQAMC.C");
1197      AliPWG4HighPtQAMC *taskQAMC = 0;
1198      if(kUseMC){
1199        if(iPWG4PtQAMC&1){
1200          taskQAMC = AddTaskPWG4HighPtQAMC(kGridDataSet.Data(),0);
1201          taskQAMC = AddTaskPWG4HighPtQAMC(kGridDataSet.Data(),1);
1202          taskQAMC = AddTaskPWG4HighPtQAMC(kGridDataSet.Data(),2);
1203          taskQAMC = AddTaskPWG4HighPtQAMC(kGridDataSet.Data(),3);
1204        }
1205      }
1206      if (!taskQAMC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQAMC cannot run for this train conditions - EXCLUDED");
1207    }
1208
1209    if(iPWG4PtTrackQA){
1210      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtTrackQA.C");
1211
1212      AddTaskPWG4HighPtTrackQAAll(kGridDataSet.Data(),kIsPbPb,iAODanalysis);
1213
1214    }
1215
1216    if(iPWG4PtQATPC){
1217      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQATPConly.C");
1218      AliPWG4HighPtQATPConly *taskQATPC = 0;
1219      if(iPWG4PtQATPC&1)taskQATPC = AddTaskPWG4HighPtQATPConly(kGridDataSet.Data(),1);
1220      if(iPWG4PtQATPC&2)taskQATPC = AddTaskPWG4HighPtQATPConly(kGridDataSet.Data(),2);
1221
1222  if (!taskQATPC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQATPC cannot run for this train conditions - EXCLUDED");
1223    }
1224
1225    if(iPWG4Cosmics){
1226      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4CosmicCandidates.C");
1227
1228      AliPWG4CosmicCandidates *taskPWG4CosmicCandidates = AddTaskPWG4CosmicCandidates(0);
1229      taskPWG4CosmicCandidates = AddTaskPWG4CosmicCandidates(1);
1230
1231      if (!taskPWG4CosmicCandidates) ::Warning("AnalysisTrainPWG4Jets", "AddTaskPWG4CosmicCandidates cannot run for this train conditions - EXCLUDED");
1232    }
1233
1234
1235    if(iPWG4PtSpectra){
1236      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtSpectra.C");
1237      AddTaskPWG4HighPtSpectraAll(kGridDataSet.Data(),kIsPbPb);
1238    }
1239
1240    if(iPWG4KMeans){
1241      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskKMeans.C");
1242      AliAnalysisTaskKMeans *taskKMeans = AddTaskKMeans();
1243      if (!taskKMeans) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskKMenans cannot run for this train conditions - EXCLUDED");
1244    }
1245
1246    if(iPWG4PartCorr){
1247      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPartCorr.C");
1248      AliAnalysisTaskParticleCorrelation *taskpartcorrPHOS = AddTaskPartCorr("AOD", "PHOS",kFALSE,kIsMC);
1249      if (!taskpartcorrPHOS) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation PHOS cannot run for this train conditions - EXCLUDED");
1250      AliAnalysisTaskParticleCorrelation *taskpartcorrEMCAL = AddTaskPartCorr("AOD", "EMCAL",kFALSE,kIsMC);
1251      if (!taskpartcorrEMCAL) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation EMCAL cannot run for this train conditions - EXCLUDED");
1252      if(kDeltaAODPartCorrName.Length()>0)mgr->RegisterExtraFile(kDeltaAODPartCorrName.Data());
1253    } 
1254
1255    if(iPWG4CaloQA){
1256      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/QA/AddTaskCalorimeterQA.C");
1257      AliAnalysisTaskParticleCorrelation *taskcaloQA =  AddTaskCalorimeterQA("ESD",kFALSE,kIsMC,kCaloQAOutputFileName.Data());
1258      if(!taskcaloQA)::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation QA cannot run - EXCLUDED");
1259      //  if(kCaloQAOutputFileName.Length()>0)mgr->RegisterExtraFile(kCaloQAOutputFileName.Data());
1260    } 
1261
1262    if(iPWG4JetCorr){
1263      //     using namespace JetCorrelHD;
1264      TString cdir = gSystem->WorkingDirectory();
1265      gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
1266      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetCorrel.C");
1267      AliAnalysisTaskJetCorrel *taskjetcorr = AddTaskJetCorrel();
1268      gSystem->ChangeDirectory(cdir);
1269      if (!taskjetcorr) ::Warning("AnalysisTrainNew", "AliAnalysisTaskJetCorrel  cannot run for this train conditions - EXCLUDED");
1270    } 
1271
1272    if(iPWG4Tagged){
1273      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskTaggedPhotons.C");
1274      AliAnalysisTaskTaggedPhotons * taskTagged = AddTaskTaggedPhotons(kFALSE); // EMCAL
1275      taskTagged = AddTaskTaggedPhotons(kTRUE); // PHOS 
1276      if (!taskTagged) ::Warning("AnalysisTrainNew", "AliAnalysisTaskTaggedPhotons  cannot run for this train conditions - EXCLUDED");     
1277    }
1278    if (iPWG4omega3pi) {
1279      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskomega3pi.C");
1280      AliAnalysisTaskOmegaPi0PiPi *taskomega3pi = AddTaskomega3pi();
1281      if (!taskomega3pi) ::Warning("AnalysisTrainNew", "AliAnalysisTaskomega3pi cannot run\
1282  for these train conditions - EXCLUDED");
1283    }
1284
1285    // PWG4 gamma conversion analysis
1286    if (iPWG4GammaConv) {
1287       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskGammaConversion.C");
1288       TString cdir = gSystem->WorkingDirectory();
1289       gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
1290       //      TString gcArguments = "-run-on-train -run-jet -run-chic -run-neutralmeson -run-cf";
1291       //      TString gcArguments = "-run-on-train -run-jet -run-neutralmeson -run-cf -use-own-xyz";
1292       //      TString gcArguments = "-run-on-train -run-jet -run-neutralmeson -run-cf -use-own-xyz";
1293       TString gcArguments = "-run-on-train -run-jet -run-omega-meson -use-own-xyz -run-neutralmeson -no-aod";
1294       //      TString kGCAnalysisCutSelectionId="9003562000100310";
1295       //      TString kGCAnalysisCutSelectionId="9003562000100312";
1296       //      gcArguments.Append(Form(" -set-cut-selection %s ",kGCAnalysisCutSelectionId.Data()));
1297       if(!kIsMC)gcArguments += " -mc-off";
1298       AliAnalysisTaskGammaConversion * taskGammaConversion = AddTaskGammaConversion(gcArguments,mgr->GetCommonInputContainer());
1299       gSystem->ChangeDirectory(cdir);
1300       taskGammaConversion->SelectCollisionCandidates();
1301       if (!taskGammaConversion) ::Warning("AnalysisTrainNew", "AliAnalysisTaskGammaConversion cannot run for these train conditions - EXCLUDED");
1302    }   
1303
1304    if (iPWG4CaloConv) {
1305       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskCaloConv.C");
1306       AliAnalysisTaskCaloConv * taskCaloConv = AddTaskCaloConv();
1307       if (!taskCaloConv) ::Warning("AnalysisTrainNew", "AliAnalysisTaskCaloConv cannot run for these train conditions - EXCLUDED");
1308    }   
1309
1310
1311
1312    //==========================================================================
1313    // FOR THE REST OF THE TASKS THE MACRO AddTaskXXX() is not yet implemented/
1314    // Run the analysis
1315    //    
1316    if (kPluginUse) {
1317       AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
1318       AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
1319    }
1320    
1321    if (mgr->InitAnalysis()) {
1322      mgr->PrintStatus();
1323      // if (kSaveTrain || strlen(config_file)) gSystem->ChangeDirectory(kTrainName);
1324      if (!strcmp(plugin_mode,"submit")&&smode=="GRID"){
1325        TString alien_workdir = gGrid->GetHomeDirectory();
1326        if (iAODanalysis) alien_workdir += "analysisAOD";
1327        else              alien_workdir += "analysisESD";
1328        if(kGridDataSet.Length()>0)alien_workdir += Form("/%s%s",kGridDataSet.Data(),kGridExtraAliendirLevel.Data());
1329        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
1330        printf("=== AnalysisTrainPWG4Jets:: Registering jdl in the work directory alien://%s/%s, should be done by the manager! ===\n",
1331               alien_workdir.Data(),gridhandler->GetGridOutputDir());
1332
1333        TString dest;
1334        dest = Form("%s/%s/%s.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
1335        if(AliAnalysisAlien::FileExists(dest.Data())){
1336          Printf("%s exist on grid removing...",dest.Data());
1337          gGrid->Rm(dest.Data());
1338        }
1339        Printf("%s copy ...",dest.Data());
1340        TFile::Cp(Form("file:%s.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
1341
1342
1343        TString dest;
1344        dest = Form("%s/%s/%s_merge.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
1345        if(AliAnalysisAlien::FileExists(dest.Data())){
1346          Printf("%s exist on grid removing...",dest.Data());
1347          gGrid->Rm(dest.Data());
1348        }
1349        Printf("%s copy ...",dest.Data());
1350        TFile::Cp(Form("file:%s_merge.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
1351        
1352        dest = Form("%s/%s/%s_merge_final.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
1353        if(AliAnalysisAlien::FileExists(dest.Data())){
1354          Printf("%s exist on grid removing...",dest.Data());
1355          gGrid->Rm(dest.Data());
1356        }
1357        Printf("%s copy ...",dest.Data());
1358        TFile::Cp(Form("file:%s_merge.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
1359      }
1360      AliLog::SetGlobalLogLevel(AliLog::kError);
1361      if((kUseSysInfo>0&&smode=="LOCAL")||!strcmp(plugin_mode, "test")){
1362        TFile * fM = TFile::Open("manager_local.root","RECREATE");
1363        mgr->Write();
1364        fM->Close();
1365      }
1366      
1367      // grmpf, aliroot error handler overwrites root
1368      gErrorIgnoreLevel = kErrorIgnoreLevel;
1369      if(gErrorIgnoreLevel>3000) AliLog::SetGlobalLogLevel(AliLog::kFatal);
1370      StartAnalysis(smode, chain);
1371      if((kUseSysInfo>0&&smode=="LOCAL")||!strcmp(plugin_mode, "test")){
1372        for(int i = 0;i < mgr->GetTopTasks()->GetEntries();i++){
1373          mgr->ProfileTask(i);
1374        }
1375      }
1376      if (!strcmp(plugin_mode, "offline")&&smode=="GRID"){
1377        // Offline mode path files
1378        //       PatchJDL();
1379        //       PatchAnalysisMacro();
1380      }
1381
1382      if (kSaveTrain && smode=="GRID") {
1383        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
1384        TString alien_workdir = gGrid->GetHomeDirectory();
1385        if (iAODanalysis) alien_workdir += "analysisAOD";
1386        else              alien_workdir += "analysisESD";
1387        if(kGridDataSet.Length()>0)alien_workdir += Form("/%s%s",kGridDataSet.Data(),kGridExtraAliendirLevel.Data());
1388        //     kGridOutdir = gridhandler->GetGridOutputDir();
1389        printf("=== Registering ConfigTrain.C in the work directory <%s> ===\n",
1390                 alien_workdir.Data());
1391        if (AliAnalysisAlien::FileExists(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data())))
1392          gGrid->Rm(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
1393        if (strcmp(plugin_mode, "test"))
1394          TFile::Cp(Form("file:%sConfig.C",kTrainName.Data()), Form("alien://%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
1395      }
1396    }
1397 }
1398
1399 //______________________________________________________________________________
1400 void StartAnalysis(const char *mode, TChain *chain) {
1401 // Start analysis.
1402    Int_t imode = -1;
1403    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1404    if (!strcmp(mode, "LOCAL")) imode = 0;
1405    if (!strcmp(mode, "PROOF")) imode = 1;
1406    if (!strcmp(mode, "GRID"))  imode = 2;
1407    switch (imode) {
1408       case 0:
1409          if (!chain) {
1410             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
1411             return;
1412          }   
1413          mgr->StartAnalysis(mode, chain,kNumberOfEvents);
1414          return;
1415       case 1:
1416          if (!kProofDataSet.Length()) {
1417             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "kProofDataSet is empty");
1418             return;
1419          }   
1420          mgr->StartAnalysis(mode, kProofDataSet, kProofEvents,kProofOffset);
1421          return;
1422       case 2:
1423          if (kPluginUse) {
1424             if (!mgr->GetGridHandler()) {
1425                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Grid plugin not initialized");
1426                return;
1427             }   
1428             mgr->StartAnalysis("grid",chain,kNumberOfEvents);
1429          } else {
1430             if (!chain) {
1431                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
1432                return;
1433             }   
1434             //            mgr->StartAnalysis(mode, chain);
1435             mgr->StartAnalysis(mode, chain,kNumberOfEvents);
1436          }   
1437          return;
1438    }      
1439 }          
1440     
1441 //______________________________________________________________________________
1442 void CheckModuleFlags(const char *mode) {
1443 // Checks selected modules and insure compatibility
1444    Int_t imode = -1;
1445    if (!strcmp(mode, "LOCAL")) imode = 0;
1446    if (!strcmp(mode, "PROOF")) imode = 1;
1447    if (!strcmp(mode, "GRID"))  imode = 2;
1448
1449
1450    if (kUseCPAR) {
1451      kPluginAliRootVersion    = ""; // NO aliroot if we use CPAR
1452    }
1453
1454    if (imode==1) {
1455       if (!kUsePAR) {
1456          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PAR files enabled due to PROOF analysis");
1457          kUsePAR = kTRUE;
1458       }   
1459    }  
1460    if (imode != 2) {
1461       ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AliEn plugin disabled since not in GRID mode");
1462       kPluginUse = kFALSE; 
1463    }   
1464
1465
1466    if(!kIsMC){
1467      // switch off anthin related to MC
1468      kUseMC = 0;
1469      kUseAODMC = 0;
1470      kUseTR = kFALSE;
1471    }
1472
1473    // Decide if we have PbPb
1474    if(kGridDataSet.CompareTo("LHC10h")==0||kGridDataSet.Contains("LHC10h")) {
1475      Printf("Using settings for Pb+Pb");
1476      kIsPbPb = true;
1477    }
1478
1479    
1480
1481    if (iAODanalysis) {
1482    // AOD analysis
1483       if (kUseMC)
1484          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "MC usage disabled in analysis on AOD's");
1485       if (kUseAODTags)
1486          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AOD tags usage disabled in analysis on AOD's");
1487       kUseMC = kFALSE;
1488       kUseTR = kFALSE;
1489       kUseAODTags = kFALSE;
1490       if (iESDfilter)
1491          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "ESD filter disabled in analysis on AOD's");
1492       iESDfilter   = 0;
1493       if (iPhysicsSelection)
1494          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "Physics Selection disabled in analysis on AOD's");
1495       iPhysicsSelection   = 0;
1496       if (!iAODhandler) {
1497          if (iJETAN) 
1498             ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "JETAN disabled in analysis on AOD's without AOD handler");
1499          iJETAN = 0;
1500          iDIJETAN = 0;
1501       }
1502       // Disable tasks that do not work yet on AOD data
1503       if(iPWG4JCORRAN)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 JCORRAN disabled in analysis on AOD's");
1504       iPWG4JCORRAN = 0;
1505       if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
1506       iPWG4PtQAMC        = 0;
1507       if( iPWG4PtQATPC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtTPC disabled in analysis on AOD's");
1508       iPWG4PtQATPC        = 0;
1509       if( iPWG4Cosmics)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 Comics disabled in analysis on AOD's");
1510       iPWG4Cosmics        = 0;
1511
1512       if( iPWG4PtSpectra)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
1513       iPWG4PtSpectra     = 0;
1514       if(iPWG4KMeans)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4KMeans disabled on AOD's");
1515       iPWG4KMeans       = 0;
1516       if (iPWG4JetCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4Jetcorr disabled on AOD's");
1517       iPWG4JetCorr = 0;
1518       if (iPWG4PartCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4partcorr disabled on AOD's");
1519       iPWG4PartCorr = 0;
1520       if (iPWG4CaloQA)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4CaloQA disabled on AOD's");
1521       iPWG4CaloQA = 0;
1522       if (iPWG4Tagged)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4tagged disabled on AOD's");
1523       iPWG4Tagged = 0;
1524       if (iPWG4omega3pi)
1525         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG4omega3pi disabled on AOD's");
1526       iPWG4omega3pi = 0;
1527       if(iPWG1QASym)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG1 QA Sym disabled in analysis on AOD's");
1528       if (iPWG4GammaConv)::Info("AnalysisPWG4Jets.C::CheckModuleFlags", "PWG4gammaconv disabled on AOD's");
1529       iPWG4GammaConv = 0;   
1530       iPWG1QASym     = 0;
1531       iCentralitySelection = 0;
1532    } else {   
1533    // ESD analysis
1534
1535      if(kIsPbPb){
1536        iCentralitySelection = 1;
1537      }
1538
1539      if (!kUseMC){
1540        kUseTR = kFALSE;
1541        
1542        if(kUseKinefilter)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 Kine Filter disabled in analysis without MC");
1543        kUseKinefilter = kFALSE;
1544        if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis without MC");
1545        iPWG4PtQAMC        = 0;
1546        if( iPWG4CorrectionsUE)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 CorrectionsUE disabled in analysis without MC");
1547        iPWG4CorrectionsUE = 0;
1548      }
1549      if (iJETAN){
1550        iESDfilter=1;
1551      }
1552       if (!iESDfilter){
1553         kUseKinefilter = kFALSE;
1554         kUseMuonfilter = kFALSE;
1555       }
1556       if(!iJETAN){
1557         iPWG4JetSpectrum = iPWG4UE =  iPWG4CorrectionsUE = iPWG4ThreeJets = iPWG4QGSep = iDIJETAN = 0;
1558       }
1559    }
1560    iPWG4JetTasks = iPWG4JetServices||iPWG4JetSpectrum||iPWG4UE||iPWG4LeadingUE||iPWG4PtQAMC||iPWG4PtTrackQA||iPWG4PtSpectra||iPWG4PtQATPC||iPWG4Cosmics||iPWG4ThreeJets||iPWG4QGSep||iPWG4JetChem||iPWG4Minijet||iPWG4Fragmentation;
1561    iPWG4PartCorrLibs = iPWG4PartCorr||iPWG4Tagged||iPWG4CaloQA;
1562    iPWG4GammaConvLib = iPWG4GammaConv||iPWG4CaloConv;
1563
1564
1565    iEMCUtilLibs = iPWG4JetTasks||iPWG4PartCorrLibs||iPWG4JCORRAN||iPWG4GammaConvLib||iJETAN;
1566    iJETANLib = iPWG4JetTasks||iJETAN||iDIJETAN;
1567
1568    if (iESDfilter) {iAODhandler=1;}
1569    if (kUseKinefilter && !kUseMC) kUseKinefilter = kFALSE;
1570    if (kUseAODTags && !iAODhandler) kUseAODTags = kFALSE;
1571
1572
1573    
1574 }
1575
1576 //______________________________________________________________________________
1577 Bool_t Connect(const char *mode) {
1578 // Connect <username> to the back-end system.
1579    Int_t imode = -1;
1580    if (!strcmp(mode, "LOCAL")) imode = 0;
1581    if (!strcmp(mode, "PROOF")) imode = 1;
1582    if (!strcmp(mode, "GRID"))  imode = 2;
1583    TString username = gSystem->Getenv("alien_API_USER");
1584    switch (imode) {
1585       case 0:
1586          break;
1587       case 1:
1588          if  (!username.Length()) {
1589             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
1590                            1. Have called: alien-token-init <username>\n \
1591                            2. Have called: >source /tmp/gclient_env_$UID");
1592             return kFALSE;
1593          }
1594          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to PROOF cluster <%s>", 
1595                 username.Data(), kProofCluster.Data());
1596          gEnv->SetValue("XSec.GSI.DelegProxy", "2");
1597 //         TProof::Open(Form("%s@%s:31093", username.Data(), kProofCluster.Data()));       
1598          TProof::Open(Form("%s@%s", username.Data(), kProofCluster.Data()));       
1599          if (!gProof) {
1600             if (strcmp(gSystem->Getenv("XrdSecGSISRVNAMES"), "lxfsrd0506.cern.ch"))
1601                ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");
1602             return kFALSE;
1603          }
1604          if(kProofClearPackages)gProof->ClearPackages();
1605
1606          if(kProofSaveToAlien){
1607            TGrid::Connect("alien://");
1608            if (gGrid) {
1609              TString homedir = gGrid->GetHomeDirectory();
1610              TString workdir = homedir + kTrainName;
1611              if (!gGrid->Cd(workdir)) {
1612                gGrid->Cd(homedir);
1613                if (gGrid->Mkdir(workdir)) {
1614                  gGrid->Cd(kTrainName);
1615                  ::Info("AnalysisTrainPWG4Jets::Connect()", "Directory %s created", gGrid->Pwd());
1616                }
1617              }
1618              gGrid->Mkdir("proof_output");
1619              gGrid->Cd("proof_output");
1620              kProofOutdir = Form("alien://%s", gGrid->Pwd());
1621            }   
1622          }
1623          break;
1624       case 2:      
1625          if  (!username.Length()) {
1626             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
1627                            1. Have called: alien-token-init <username>\n \
1628                            2. Have called: >source /tmp/gclient_env_$UID");
1629             return kFALSE;
1630          }
1631          if (kPluginUse && !gSystem->Getenv("alien_CLOSE_SE")) {
1632             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), 
1633                            "When using the AliEn plugin it is preferable to define the \
1634                            variable alien_CLOSE_SE in your environment.");
1635             return kFALSE;
1636          }
1637          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to AliEn ...", 
1638                 username.Data());
1639          TGrid::Connect("alien://");
1640          if (!gGrid || !gGrid->IsConnected()) return kFALSE;
1641          break;
1642       default:
1643          ::Error("AnalysisTrainPWG4Jets.C::Connect", "Unknown run mode: %s", mode);
1644          return kFALSE;
1645    }
1646    ::Info("AnalysisTrainPWG4Jets.C::Connect","Connected in %s mode", mode);
1647    return kTRUE;
1648 }
1649
1650 //______________________________________________________________________________
1651 Bool_t LoadCommonLibraries(const char *mode)
1652 {
1653    if (!gSystem->Getenv("ALICE_ROOT")) {
1654       ::Error("AnalysisTrainPWG4Jets.C", "Analysis train requires that ALICE_ROOT is set to pick up Configurations"); 
1655       return kFALSE;
1656    }   
1657    
1658    // Load common analysis libraries.
1659    Int_t imode = -1;
1660    if (!strcmp(mode, "LOCAL")) imode = 0;
1661    if (!strcmp(mode, "PROOF")) imode = 1;
1662    if (!strcmp(mode, "GRID"))  imode = 2;
1663    Bool_t success = kTRUE;
1664    // ROOT libraries
1665    gSystem->Load("libTree.so");
1666    gSystem->Load("libGeom.so");
1667    gSystem->Load("libVMC.so");
1668    gSystem->Load("libPhysics.so");
1669    
1670    // Load framework classes. Par option ignored here.
1671    switch (imode) {
1672       case 0:
1673       case 2:
1674          if (kUseCPAR) {
1675             success &= LoadLibrary("STEERBase", mode, kTRUE);
1676             success &= LoadLibrary("ESD", mode, kTRUE);
1677             success &= LoadLibrary("AOD", mode, kTRUE);
1678             success &= LoadLibrary("ANALYSIS", mode, kTRUE);
1679             success &= LoadLibrary("OADB", mode, kTRUE);
1680             success &= LoadLibrary("ANALYSISalice", mode, kTRUE);
1681             success &= LoadLibrary("ROOTFILES", mode, kTRUE);
1682             //            success &= LoadLibrary("EventMixing", mode,kTRUE);
1683             success &= LoadLibrary("CORRFW", mode, kTRUE);
1684          } else {   
1685             success &= LoadLibrary("libSTEERBase.so", mode);
1686             success &= LoadLibrary("libESD.so", mode);
1687             success &= LoadLibrary("libAOD.so", mode);
1688             success &= LoadLibrary("libANALYSIS.so", mode);
1689             success &= LoadLibrary("libOADB.so", mode, kTRUE);
1690             success &= LoadLibrary("libANALYSISalice.so", mode);
1691             //            success &= LoadLibrary("libEventMixing.so", mode);
1692             success &= LoadLibrary("libCORRFW.so", mode);
1693             gROOT->ProcessLine(".include $ALICE_ROOT/include");
1694          }   
1695          break;
1696       case 1:
1697          Int_t ires = -1;
1698          if (kProofUseAFPAR && !gSystem->AccessPathName(kProofAFversion)) ires = gProof->UploadPackage(kProofAFversion);
1699          if (ires < 0) {
1700             success &= LoadLibrary("STEERBase", mode);
1701             success &= LoadLibrary("ESD", mode);
1702             success &= LoadLibrary("AOD", mode);
1703             success &= LoadLibrary("ANALYSIS", mode);
1704             success &= LoadLibrary("ANALYSISalice", mode);
1705             success &= LoadLibrary("EventMixing", mode);
1706             success &= LoadLibrary("CORRFW", mode);
1707          } else { 
1708             ires = gProof->EnablePackage(kProofAFversion);
1709             if (ires<0) success = kFALSE;
1710             success &= LoadLibrary("CORRFW", mode);
1711          }
1712          break;         
1713       default:
1714          ::Error("AnalysisTrainPWG4Jets.C::LoadCommonLibraries", "Unknown run mode: %s", mode);
1715          return kFALSE;
1716    }
1717    if (success) {
1718       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    SUCCESS");
1719       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Include path for Aclic compilation:\n%s",
1720               gSystem->GetIncludePath());
1721    } else {           
1722       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    FAILED");
1723    }   
1724       
1725    return success;
1726 }
1727
1728 //______________________________________________________________________________
1729 Bool_t LoadAnalysisLibraries(const char *mode)
1730 {
1731 // Load common analysis libraries.
1732   Bool_t success = kTRUE;
1733   if (useTender) {
1734       if (!LoadLibrary("TENDER", mode, kTRUE) ||
1735           !LoadLibrary("TENDERSupplies", mode, kTRUE)) return kFALSE;
1736    }
1737    if (iESDfilter) {
1738      /*
1739       if (!LoadLibrary("PWG3base", mode, kTRUE) ||
1740           !LoadLibrary("PWG3muon", mode, kTRUE)) return kFALSE;
1741      */
1742    }   
1743    // JETAN
1744    if (iJETANLib) {
1745      // this part needs some rework in case we do not need the fastjed finders for processing
1746      if(iEMCUtilLibs){
1747        if (!LoadLibrary("EMCALUtils", mode, kTRUE) ||
1748            !LoadLibrary("PHOSUtils", mode, kTRUE)) return kFALSE;
1749      }
1750      if (!LoadLibrary("JETAN", mode, kTRUE)) return kFALSE;
1751      if (!strcmp(mode, "PROOF")){
1752        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libCGAL.so\"\)", kTRUE); 
1753        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libfastjet.so\"\)", kTRUE); 
1754        // problem when loading siscone copiled with different gcc version??
1755        // gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libsiscone.so\"\)", kTRUE); 
1756        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libSISConePlugin.so\"\)", kTRUE);      
1757      }
1758      if(!kUsePAR){ 
1759        if (!LoadLibrary("CGAL", mode, kTRUE)) return kFALSE;
1760        if (!LoadLibrary("fastjet", mode, kTRUE)) return kFALSE;
1761        if (!LoadLibrary("siscone", mode, kTRUE)) return kFALSE;
1762        if (!LoadLibrary("SISConePlugin", mode, kTRUE)) return kFALSE;
1763      }
1764      else{
1765        // par files plus FASTJET needs some extra work... need to change
1766        // the loading sequence in the auto generated .C file
1767        if (!LoadLibrary("libCGAL.so", mode, kTRUE)) return kFALSE;
1768        if (!LoadLibrary("libfastjet.so", mode, kTRUE)) return kFALSE;
1769        if (!LoadLibrary("libsiscone.so", mode, kTRUE)) return kFALSE;
1770        if (!LoadLibrary("libSISConePlugin.so", mode, kTRUE)) return kFALSE;
1771      }
1772      if (!LoadLibrary("FASTJETAN", mode, kTRUE)) return kFALSE;
1773    }
1774    if(iPWG4JetTasks){
1775      if (!LoadLibrary("PWG4JetTasks", mode, kTRUE)) return kFALSE;
1776    }
1777
1778    if(iPWG1QASym){
1779      if (!LoadSource(Form("%s/PWG1/AliAnalysisTaskQASym.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
1780    }
1781    if(iPWG4TmpSourceSara){
1782      if(!kUsePAR)gSystem->AddIncludePath("-I$ALICE_ROOT/include/JetTasks"); // ugly hack!!
1783      if(!LoadSource(Form("%s/PWG4/JetTasks/AliAnalysisTaskEta.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
1784    }
1785
1786    if (iPWG4PartCorrLibs) {   
1787       if (!LoadLibrary("PWG4PartCorrBase", mode, kTRUE) ||
1788           !LoadLibrary("PWG4PartCorrDep", mode, kTRUE)) return kFALSE;
1789    }
1790    if(iPWG4JCORRAN){
1791      // PWG4 particle correlations
1792      if(!LoadLibrary("PWG4JCORRAN",mode,kTRUE))return kFALSE;
1793    }
1794    if (iPWG4JetCorr) { 
1795      if (!LoadLibrary("PWG4JetCorrel", mode, kTRUE)) return kFALSE;
1796    }  
1797    if (iPWG4omega3pi) {
1798      if (!LoadLibrary("PWG4omega3pi", mode, kTRUE)) return kFALSE;
1799    }
1800    if (iPWG4GammaConvLib) {
1801       if (!LoadLibrary("PWG4GammaConv", mode, kTRUE)) return kFALSE;
1802    }      
1803
1804    ::Info("AnalysisTrainPWG4Jets.C::LoadAnalysisLibraries", "Load other libraries:   SUCCESS");
1805    return kTRUE;
1806 }
1807
1808 //______________________________________________________________________________
1809 Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
1810 {
1811 // Load a module library in a given mode. Reports success.
1812    Int_t imode = -1;
1813    Int_t result;
1814    TString smodule(module);
1815    if (!strcmp(mode, "LOCAL")) imode = 0;
1816    if (!strcmp(mode, "PROOF")) imode = 1;
1817    if (!strcmp(mode, "GRID"))  imode = 2;
1818    TString mod(module);
1819    if (!mod.Length()) {
1820       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Empty module name");
1821       return kFALSE;
1822    }   
1823    // If a library is specified, just load it
1824    if (smodule.EndsWith(".so")) {
1825       mod.Remove(mod.Index(".so"));
1826       result = gSystem->Load(mod);
1827       if (result < 0) {
1828          ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load library %s", module);
1829          return kFALSE;
1830       }
1831       if (rec) anaLibs += Form("%s.so ",mod.Data()); 
1832       if (rec) anaLibsExtra += Form("%s.so ",mod.Data()); 
1833       return kTRUE;
1834    } 
1835    // Check if the library is already loaded
1836    if (strlen(gSystem->GetLibraries(Form("%s.so", module), "", kFALSE)) > 0)
1837       return kTRUE;    
1838    switch (imode) {
1839       case 0:
1840       case 2:
1841          if (kUsePAR) {
1842             result = SetupPar(module);
1843             if (rec) anaPars += Form("%s.par ", module);
1844          } else {
1845             result = gSystem->Load(Form("lib%s.so", module));
1846             if (rec) anaLibs += Form("lib%s.so ", module);
1847          }   
1848          break;
1849       case 1:
1850         if(!gSystem->AccessPathName(module)){
1851           ::Info("AnalysisTrainPWG4Jets.C::LoadLibrary", "Removing directory %s",module);
1852           gSystem->Exec(Form("rm -rf %s",module));
1853         }
1854          result = gProof->UploadPackage(module);
1855          if (result<0) {
1856             result = gProof->UploadPackage(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", module)));
1857             if (result<0) {
1858                ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);
1859                return kFALSE;
1860             }
1861          }   
1862          result = gProof->EnablePackage(module);
1863          break;
1864       default:
1865          return kFALSE;
1866    }         
1867    if (result < 0) {
1868       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load module %s", module);
1869       return kFALSE;
1870    }
1871    return kTRUE;
1872 }           
1873
1874
1875
1876 //______________________________________________________________________________
1877 Bool_t LoadSource(const char *source, const char *mode, Bool_t rec=kFALSE)
1878 {
1879 // Load a module library in a given mode. Reports success.
1880    Int_t imode = -1;
1881    Int_t result = -1;
1882    if (!strcmp(mode, "LOCAL")) imode = 0;
1883    if (!strcmp(mode, "PROOF")) imode = 1;
1884    if (!strcmp(mode, "GRID"))  imode = 2;
1885    TString ssource(source);
1886    TString basename = gSystem->BaseName(ssource.Data());
1887    if (!ssource.Length()) {
1888       ::Error("AnalysisTrainPWG4Jets.C::LoadSource", "Empty task name");
1889       return kFALSE;
1890    }   
1891    // we have a source code so compile it
1892    if (ssource.EndsWith(".cxx")) {
1893      // need to copy it here other wise the path is also used on grid...
1894      ssource.Remove(ssource.Index(".cxx"));
1895      basename.Remove(basename.Index(".cxx"));
1896      Printf("LoadSources:: Copying...  path %s{cxx,h}",ssource.Data());
1897      gSystem->Exec(Form("cp %s.cxx . ",ssource.Data()));
1898      gSystem->Exec(Form("cp %s.h . ",ssource.Data()));
1899      // Path to code
1900      // only needed for local compilation, in grid and proof mode 
1901      // the task headers are uploaded 
1902      //     path.Remove(path.Index(gSystem->BaseName(path.Data())));
1903      // Printf("LoadSources:: Including path %s",path.Data());
1904      //  if(path.Length()>0)gROOT->ProcessLine(Form(".include %s",path.Data()));
1905      Printf("LoadSources:: Loading...  path %s",basename.Data());
1906      switch (imode) {
1907      case 0:
1908        result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
1909        break;
1910      case 1:
1911        result = gProof->LoadMacro(Form("%s.cxx++g",basename.Data()));
1912        break;
1913      case 2:
1914        result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
1915        if (rec){
1916          // what we want to compile
1917          anaSources += Form("%s.cxx ",basename.Data()); 
1918          // what we need as input...
1919          anaLibs += Form("%s.cxx %s.h ",basename.Data(),basename.Data()); 
1920        }
1921        break;
1922      default:
1923        return kFALSE;
1924      }
1925    } 
1926    if (result < 0) {
1927       ::Error("AnalysisTrainPWG4Jets.C::LoadSources", "Could not load source %s", source);
1928       return kFALSE;
1929    }
1930    return kTRUE;
1931 }           
1932
1933
1934 //______________________________________________________________________________
1935 TChain *CreateChain(const char *mode, const char *plugin_mode)
1936 {
1937 // Create the input chain
1938    Int_t imode = -1;
1939    if (!strcmp(mode, "LOCAL")) imode = 0;
1940    if (!strcmp(mode, "PROOF")) imode = 1;
1941    if (!strcmp(mode, "GRID"))  imode = 2;
1942    TChain *chain = NULL;
1943    // Local chain
1944    switch (imode) {
1945       case 0:
1946          if (iAODanalysis) {
1947             if (!kLocalXMLDataset.Length()) {
1948                // Local AOD
1949                chain = new TChain("aodTree");
1950                TString line;
1951                ifstream in;
1952                in.open(kLocalDataList.Data());
1953                Int_t ic = 0;
1954                while (in.good()) {
1955                  in >> line;
1956                  if (line.Length() == 0) continue;
1957                  Printf("%d adding %s",ic,line.Data());
1958                  chain->Add(line.Data());
1959                  ic++;
1960                }       
1961             } else {
1962                // Interactive AOD
1963                chain = CreateChainSingle(kLocalXMLDataset, "aodTree");
1964             }
1965          } else {      
1966            if (!kLocalXMLDataset.Length()) {
1967              // Local ESD
1968              chain = new TChain("esdTree");
1969              TString line;
1970              ifstream in;
1971              in.open(kLocalDataList.Data());
1972              while (in.good()) {
1973                in >> line;
1974                if (line.Length() == 0) continue;
1975                cout << " line = " << line << endl;
1976                chain->Add(line.Data());
1977              }       
1978            } else {
1979              // Interactive ESD
1980                chain = CreateChainSingle(kLocalXMLDataset, "esdTree");
1981            }   
1982          }
1983          break;
1984       case 1:
1985          break;
1986       case 2:
1987          if (kPluginUse) {
1988 //            AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
1989 //            AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
1990          } else {
1991             TString           treeName = "esdTree";
1992             if (iAODanalysis) treeName = "aodTree";
1993             chain = CreateChainSingle("wn.xml", treeName);
1994          }
1995          break;      
1996       default:   
1997    }
1998    if (chain && chain->GetNtrees()) return chain;
1999    return NULL;
2000 }   
2001
2002 //______________________________________________________________________________
2003 TChain* CreateChainSingle(const char* xmlfile, const char *treeName)
2004 {
2005    printf("*******************************\n");
2006    printf("*** Getting the ESD Chain   ***\n");
2007    printf("*******************************\n");
2008    TAlienCollection * myCollection  = TAlienCollection::Open(xmlfile);
2009
2010    if (!myCollection) {
2011       ::Error("AnalysisTrainPWG4Jets.C::CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;
2012       return NULL ;
2013    }
2014
2015    TChain* chain = new TChain(treeName);
2016    myCollection->Reset() ;
2017    while ( myCollection->Next() ) chain->Add(myCollection->GetTURL("")) ;
2018    chain->ls();
2019    return chain;
2020 }
2021
2022 //______________________________________________________________________________
2023 Int_t SetupPar(char* pararchivename)
2024 {
2025    if (!pararchivename || !strlen(pararchivename)) return -1;
2026    char processline[1024];
2027    if (gSystem->AccessPathName(Form("%s.par", pararchivename))) {
2028       if (!gSystem->AccessPathName(Form("%s/%s.par", gSystem->Getenv("ALICE_ROOT"),pararchivename))) {
2029          ::Info("AnalysisTrainPWG4Jets.C::SetupPar", "Getting %s.par from $ALICE_ROOT", pararchivename);
2030         TFile::Cp(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", pararchivename)), 
2031                   Form("%s.par",pararchivename));
2032       } else {
2033          ::Error("AnalysisTrainPWG4Jets.C::SetupPar", "Cannot find %s.par", pararchivename);
2034          return -1;
2035       }   
2036    }
2037    if (kPluginUse && kSaveTrain) gSystem->Exec(Form("ln -s ../%s.par %s",pararchivename, kTrainName.Data()));
2038    gSystem->Exec(Form("tar xvzf %s.par", pararchivename));
2039
2040    TString ocwd = gSystem->WorkingDirectory();
2041    if (!gSystem->ChangeDirectory(pararchivename)) return -1;
2042         
2043    // check for BUILD.sh and execute
2044    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
2045       printf("*******************************\n");
2046       printf("*** Building PAR archive    ***\n");
2047       printf("*******************************\n");          
2048       if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
2049          Error("runProcess","Cannot Build the PAR Archive! - Abort!");
2050          return -1;
2051       }
2052    }
2053
2054         // check for SETUP.C and execute
2055         if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
2056             printf("*******************************\n");
2057             printf("*** Setup PAR archive       ***\n");
2058             printf("*******************************\n");
2059             gROOT->Macro("PROOF-INF/SETUP.C");
2060         }       
2061         if (!gSystem->ChangeDirectory(ocwd.Data())){
2062           Error("Change back directory",Form("Cannot change to %s",ocwd.Data()));
2063           return -1;
2064         }
2065    return 0;
2066 }
2067
2068 //______________________________________________________________________________
2069 AliAnalysisAlien* CreateAlienHandler(const char *plugin_mode)
2070 {
2071 // Check if user has a valid token, otherwise make one. This has limitations.
2072 // One can always follow the standard procedure of calling alien-token-init then
2073 //   source /tmp/gclient_env_$UID in the current shell.
2074 //   if (!AliAnalysisGrid::CreateToken()) return NULL;
2075    AliAnalysisAlien *plugin = new AliAnalysisAlien();
2076 // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
2077    plugin->SetRunMode(plugin_mode);
2078    if (kPluginUseProductionMode) plugin->SetProductionMode();
2079    plugin->SetJobTag(kJobTag);
2080    plugin->SetNtestFiles(1);
2081 //   plugin->SetPreferedSE("ALICE::NIHAM::File");
2082 // Set versions of used packages
2083    plugin->SetAPIVersion("V1.1x");
2084    //   plugin->SetAPIVersion("V1.0x");
2085 //   plugin->SetAPIVersion("V2.4");
2086    plugin->SetROOTVersion(kPluginRootVersion);
2087    plugin->SetAliROOTVersion(kPluginAliRootVersion);
2088 // Declare input data to be processed.
2089 // Method 1: Create automatically XML collections using alien 'find' command.
2090 // Define production directory LFN
2091    plugin->SetGridDataDir(kGridDatadir.Data());
2092 // Set data search pattern
2093    if (iAODanalysis) plugin->SetDataPattern(Form(" %s/*/*AliAOD.root",kGridPassPattern.Data()));
2094    else              plugin->SetDataPattern(Form(" %s/*/*AliESDs.root",kGridPassPattern.Data()));
2095 // ...then add run numbers to be considered
2096 //   plugin->SetRunRange(kGridRunRange[0], kGridRunRange[1]);
2097    for (Int_t i=kGridRunRange[0]; i<=kGridRunRange[1]; i++) {
2098      Printf("AnalysisTrainPWG4Jets Adding run number %s", Form(kGridRunPattern.Data(),i));
2099      plugin->AddRunNumber(Form(kGridRunPattern.Data(),i));
2100    }   
2101
2102    if(kGridLocalRunList.Length()>0){
2103      ifstream in1;
2104      in1.open(kGridLocalRunList.Data());
2105      int iRun;
2106      int icount = 0;
2107      Int_t nRun = 0;
2108      // just use run numbers, negatives will be excluded
2109      while(in1>>iRun){
2110        if(iRun>=0){
2111          if(iRun>=0&&nRun>=kGridOffsetRunFromList&&(nRun<kGridMaxRunsFromList)){
2112            Printf("AnalysisTrainPWG4Jets Adding run number from File %d: %s",nRun,Form(kGridRunPattern.Data(),iRun));
2113            plugin->AddRunNumber(Form(kGridRunPattern.Data(),iRun));
2114
2115          }
2116          else{
2117            Printf("AnalysisTrainPWG4Jets Skipping run number from File %d: %d",nRun, iRun);
2118          }
2119          nRun++;
2120        }
2121        else{
2122          Printf("AnalysisTrainPWG4Jets Skipping run number from File %d: %d",nRun, iRun);
2123        }
2124      }
2125    }
2126 // Method 2: Declare existing data files (raw collections, xml collections, root file)
2127 // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
2128 // XML collections added via this method can be combined with the first method if
2129 // the content is compatible (using or not tags)
2130 //   plugin->AddDataFile("tag.xml");
2131 //   plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
2132 // Define alien work directory where all files will be copied. Relative to alien $HOME.
2133    TString alien_workdir = "";
2134    
2135    if (iAODanalysis)  alien_workdir += "analysisAOD";
2136    else               alien_workdir += "analysisESD";    
2137        if(kGridDataSet.Length()>0)alien_workdir += Form("/%s%s",kGridDataSet.Data(),kGridExtraAliendirLevel.Data());
2138    plugin->SetGridWorkingDir(alien_workdir.Data());
2139
2140    // Declare alien output directory. Relative to working directory.
2141    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
2142    plugin->SetGridOutputDir(kGridOutdir);
2143
2144    // Add external packages
2145    plugin->AddExternalPackage("boost::v1_43_0");
2146    plugin->AddExternalPackage("cgal::v3.6");
2147    plugin->AddExternalPackage("fastjet::v2.4.2");
2148
2149
2150    // set extra libs before par file compilation
2151    anaLibs += kGridExtraFiles;
2152    anaLibs     = anaLibs.Strip();   
2153    Printf("anaLibs %s",anaLibs.Data());
2154    Printf("anaLibsExtra %s",anaLibsExtra.Data());
2155
2156    if (anaLibs.Length())          plugin->SetAdditionalLibs(anaLibs.Data());
2157    if (anaLibsExtra.Length())     plugin->SetAdditionalRootLibs(anaLibsExtra.Data());
2158
2159    TString ana_sources = "";
2160    TString ana_add = "";
2161    if (kUsePAR && anaPars.Length()) {
2162       printf("%s\n", anaPars.Data());
2163       TObjArray *arr;
2164       TObjString *objstr;
2165       arr = anaPars.Tokenize(" ");
2166       TIter next(arr);
2167       while ((objstr=(TObjString*)next())) plugin->EnablePackage(objstr->GetString());
2168       delete arr;
2169    } 
2170    
2171 // Declare the analysis source files names separated by blancs. To be compiled runtime
2172 // using ACLiC on the worker nodes.
2173    ana_sources = anaSources.Strip();
2174 // Declare all libraries (other than the default ones for the framework. These will be
2175 // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
2176
2177    if (ana_sources.Length()) plugin->SetAnalysisSource(ana_sources);
2178    plugin->SetExecutableCommand(kPluginExecutableCommand.Data());  
2179    // Declare the output file names separated by blancs.
2180    // (can be like: file.root or file.root@ALICE::Niham::File)
2181    plugin->SetMergeExcludes(kGridMergeExclude);
2182    plugin->SetMaxMergeFiles(kGridMaxMergeFiles);
2183    plugin->SetNrunsPerMaster(kGridRunsPerMaster);
2184    plugin->SetMergeViaJDL(kPluginMergeViaJDL);
2185    // Use fastread option
2186    plugin->SetFastReadOption(kPluginFastReadOption);
2187    // UseOverwrite mode
2188    plugin->SetOverwriteMode(kPluginOverwriteMode); 
2189    // Optionally define the files to be archived.
2190    //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:AliAOD.root,AOD.tag.root@ALICE::NIHAM::File");
2191    plugin->SetOutputToRunNo(kPluginOutputToRunNumber);     // write the output to subdirs named after run number
2192    
2193    // Put default output files to archive
2194    TString listhists = "";
2195    TString listaods  = "";
2196    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
2197    TIter next(mgr->GetOutputs());
2198    AliAnalysisDataContainer *output;
2199    while ((output=(AliAnalysisDataContainer*)next())) {
2200       const char *filename = output->GetFileName();
2201       if (!(strcmp(filename, "default"))) {
2202         if (!mgr->GetOutputEventHandler()) continue;
2203          filename = mgr->GetOutputEventHandler()->GetOutputFileName();
2204          if (listaods.Length()) listaods += " ";
2205          listaods += filename;
2206       } else {
2207         if(!listhists.Contains(filename)){
2208           if (listhists.Length()) listhists += " ";
2209           listhists += filename;
2210         }
2211       }
2212    }
2213
2214    if (mgr->GetExtraFiles().Length()) {
2215      if (listaods.Length()) listaods += " ";
2216      listaods += mgr->GetExtraFiles();
2217    }
2218
2219    // if we do not fill the aod we do not need to store it
2220    //   kGridMergeExclude = listaods;
2221    
2222    if(kSaveAOD>=0){
2223      TString outputFiles =  "";
2224      outputFiles += mgr->GetExtraFiles();
2225      if (listhists.Length()) outputFiles += " ";
2226      outputFiles += listhists;
2227      plugin->SetDefaultOutputs(kFALSE);
2228      Printf("%s:%d Starting with the files %s",(char*)__FILE__,__LINE__,outputFiles.Data());
2229      // remove
2230      // no harm done when we try to remove something that is not there :)
2231      if(!(kSaveAOD&(1<<0))){
2232        outputFiles.ReplaceAll("AliAOD.root ","");
2233        listaods.ReplaceAll("AliAOD.root ","");
2234      }
2235      if(!(kSaveAOD&(1<<1))){
2236        if(kDeltaAODJetName.Length())outputFiles.ReplaceAll(kDeltaAODJetName.Data(),"");
2237        if(kDeltaAODJetName.Length())listaods.ReplaceAll(kDeltaAODJetName.Data(),"");
2238        
2239      }
2240      if(!(kSaveAOD&(1<<2))){
2241        if(kDeltaAODPartCorrName.Length())outputFiles.ReplaceAll(kDeltaAODPartCorrName.Data(),"");
2242        if(kDeltaAODPartCorrName.Length())listaods.ReplaceAll(kDeltaAODPartCorrName.Data(),"");
2243      }
2244      if(!(kSaveAOD&(1<<3))){
2245        if(kDeltaAODJCORRANName.Length())outputFiles.ReplaceAll(kDeltaAODJCORRANName.Data(),"");
2246        if(kDeltaAODJCORRANName.Length())listaods.ReplaceAll(kDeltaAODJCORRANName.Data(),"");
2247      }
2248      
2249      // 
2250      plugin->SetDefaultOutputs(kFALSE);
2251      Printf("%s:%d Saving the files %s",(char*)__FILE__,__LINE__,outputFiles.Data());
2252      plugin->SetOutputFiles(outputFiles.Data());
2253    }
2254
2255    TString outputArchive;
2256    outputArchive = Form("log_archive.zip:std*@%s","disk=1");
2257    listaods.ReplaceAll(" ", ",");
2258    listhists.ReplaceAll(" ", ",");
2259    if (listhists.Length()){
2260      outputArchive += " ";
2261      outputArchive += "root_archive.zip:";
2262      outputArchive += listhists;
2263      if (listaods.Length()){
2264        outputArchive += ",";
2265        outputArchive += listaods;
2266      }
2267      outputArchive += Form("@%s", kGridOutputStorages.Data());
2268    }
2269    else{
2270      
2271      if (listaods.Length()){
2272        // we have only aod'ish output
2273        outputArchive += " ";
2274        outputArchive += "root_archive.zip:";
2275        outputArchive += listaods;
2276        outputArchive += Form("@%s", kGridOutputStorages.Data());
2277      }
2278      else{
2279        // no other outputs than std..
2280       ::Fatal("AnalysisTrainPWG4Jets", "No task output !");
2281      }
2282    }
2283
2284    plugin->SetDefaultOutputs(kFALSE);
2285    plugin->SetOutputArchive(outputArchive);
2286
2287
2288    // Optionally set a name for the generated analysis macro (default MyAnalysis.C)
2289    plugin->SetAnalysisMacro(Form("%s.C", kTrainName.Data()));
2290    // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
2291    plugin->SetSplitMaxInputFileNumber(kGridFilesPerJob);
2292    // Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
2293    //   plugin->SetMaxInitFailed(5);
2294    // Optionally resubmit threshold.
2295    // plugin->SetMasterResubmitThreshold(90);
2296    // Optionally set time to live (default 30000 sec)
2297    plugin->SetTTL(80000); // 22h...
2298    // Optionally set input format (default xml-single)
2299    plugin->SetInputFormat("xml-single");
2300    // Optionally modify the name of the generated JDL (default analysis.jdl)
2301    plugin->SetJDLName(Form("%s.jdl", kTrainName.Data()));
2302    // Optionally modify the executable name (default analysis.sh)
2303    plugin->SetExecutable(Form("%s.sh", kTrainName.Data()));
2304    // Optionally modify job price (default 1)
2305    plugin->SetPrice(1);      
2306    // Optionally modify split mode (default 'se')    
2307    plugin->SetSplitMode("se");
2308    return plugin;
2309 }
2310
2311 //______________________________________________________________________________
2312 void WriteConfig()
2313 {
2314 // Write train configuration in a file. The file name has the format:
2315 // train_[trainName]_ddMonthyyyy_time.C
2316    if (kUseDate) {
2317       gSystem->Exec("date +%d%b%Y_%Hh%M > date.tmp");
2318       ifstream fdate("date.tmp");
2319       if (!fdate.is_open()) {
2320          ::Error("AnalysisTrainPWG4Jets.C::Export","Could not generate file name");
2321          return;
2322       }
2323       const char date[64];
2324       fdate.getline(date,64);
2325       fdate.close();
2326       gSystem->Exec("rm date.tmp");
2327       kTrainName = Form("train_%s_%s", kTrainName.Data(), date);
2328    } else {
2329       kTrainName = Form("train_%s", kTrainName.Data());
2330    }   
2331    TString cdir = gSystem->WorkingDirectory();
2332    gSystem->MakeDirectory(kTrainName);
2333    gSystem->ChangeDirectory(kTrainName);
2334    ofstream out;
2335    out.open(Form("%sConfig.C",kTrainName.Data()), ios::out); 
2336    if (out.bad()) {
2337       ::Error("AnalysisTrainPWG4Jets.C::Export", "Cannot open ConfigTrain.C for writing");
2338       return;
2339    }
2340    out << "{" << endl;
2341    out << "   kTrainName      = " << "\"" << kTrainName.Data() << "\";" << endl;
2342    out << "   kProofCluster   = " << "\"" << kProofCluster.Data() << "\";" << endl;
2343    out << "   kProofUseAFPAR        = " << kProofUseAFPAR << ";" << endl;
2344    if (kProofUseAFPAR) 
2345       out << "   kProofAFversion       = " << kProofAFversion.Data() << ";" << endl;
2346    out << "   kProofDataSet   = " << "\"" << kProofDataSet.Data() << "\";" << endl;
2347    out << "   kPluginUse       = " << kPluginUse << ";" << endl;
2348    out << "   kUsePAR          = " << kUsePAR << ";" << endl;
2349    out << "   kUseCPAR         = " << kUseCPAR << ";" << endl;
2350    out << "   kPluginRootVersion    = " << "\"" << kPluginRootVersion.Data() << "\";" << endl;
2351    out << "   kPluginAliRootVersion = " << "\"" << kPluginAliRootVersion.Data() << "\";" << endl;
2352    out << "   kGridDatadir   = " << "\"" << kGridDatadir.Data() << "\";" << endl;
2353    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
2354    out << "   kGridOutdir    = " << "\"" << kGridOutdir.Data() << "\";" << endl;
2355    out << "   kGridMaxMergeFiles   = " << kGridMaxMergeFiles << ";" << endl;
2356    out << "   kGridMergeExclude    = " << "\"" << kGridMergeExclude.Data() << "\";" << endl;
2357    out << "   kGridRunsPerMaster  = " << kGridRunsPerMaster << ";" << endl;
2358    out << "   kGridFilesPerJob    = " << kGridFilesPerJob << ";" << endl;
2359    out << "   kGridRunRange[0]    = " << kGridRunRange[0] << ";" << endl;
2360    out << "   kGridRunRange[1]    = " << kGridRunRange[1] << ";" << endl;
2361    out << "   kUseDebug          = " << kUseDebug << ";" << endl;
2362    out << "   kUseMC           = " << kUseMC << ";" << endl;
2363    out << "   kUseESDTags         = " << kUseESDTags << ";" << endl;
2364    out << "   kUseKinefilter      = " << kUseKinefilter << ";" << endl;
2365    out << "   kUseTR           = " << kUseTR << ";" << endl;
2366    out << "   kUseAODTags      = " << kUseAODTags << ";" << endl;
2367    out << "   kSaveTrain       = " << "kFALSE;" << endl << endl;
2368    out << "   // Analysis modules" << endl;
2369    out << "   iAODanalysis    = " << iAODanalysis << ";" << endl;
2370    out << "   iAODhandler     = " << iAODhandler << ";" << endl;
2371    out << "   iESDfilter      = " << iESDfilter << ";" << endl;
2372    out << "   iJETAN          = " << iJETAN << ";" << endl;
2373    out << "// Configuration fot the wagons" << endl;
2374    out << "}" << endl;
2375    ::Info("AnalysisTrainPWG4Jets.C::WriteConfig", "Train configuration wrote to file %s", Form("config_%s.C", kTrainName.Data()));
2376    gSystem->ChangeDirectory(cdir);
2377 }   
2378
2379 //______________________________________________________________________________
2380 Bool_t LoadConfig(const char *filename)
2381 {
2382 // Read train configuration from file
2383    if (gSystem->AccessPathName(filename)) {
2384       ::Error("AnalysisTrainPWG4Jets.C::LoadConfig", "Config file name not found");
2385       return kFALSE;
2386    }   
2387    gROOT->ProcessLine(Form(".x %s", filename));
2388    ::Info("AnalysisTrainPWG4Jets.C::LoadConfig", "Train configuration loaded from file %s", filename);
2389    return kTRUE;
2390 }
2391
2392 Bool_t PatchJDL(){
2393   Printf(">>> Patching JDL");
2394   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
2395   AliAnalysisAlien*    gridHandler = (AliAnalysisAlien*)mgr->GetGridHandler();
2396   TGridJDL *jdl = gridHandler->GetGridJDL();
2397   if(iJETAN)jdl->AddToPackages("fastjet","v2.4.0");
2398   gridHandler->WriteJDL(kFALSE);
2399   Printf("<<<  Patching JDL");
2400   return kTRUE;
2401 }
2402
2403 Bool_t PatchAnalysisMacro(){
2404   Printf(">>> Patching AnalysisMacro");
2405   gSystem->Exec(Form("mv %s.C %s.C_tmp",kTrainName.Data(),kTrainName.Data()));
2406
2407   ifstream in1; 
2408   in1.open(Form("%s.C_tmp", kTrainName.Data()));
2409   char cLine[250];
2410   TString st;
2411   while(in1.getline(cLine,250)){
2412     st += cLine;
2413     st += "\n";
2414   }
2415   Int_t index= -1;
2416   index = st.Index("gSystem->Load(\"libPhysics\");");
2417   index += strlen("gSystem->Load(\"libPhysics\");");
2418   /*
2419     TObjArray *arr;
2420     TObjString *objstr;
2421     arr = anaLibs.Tokenize(" ");
2422     TIter next(arr);
2423
2424     add += "\n\n // added by CKB \n";
2425     while ((objstr=(TObjString*)next())){
2426       if(objstr->GetString().Contains("PWG3"))continue;
2427       if(objstr->GetString().EndsWith(".so"))add += Form("gSystem->Load(\"%s\");\n",objstr->GetString().Data());
2428     }
2429     delete arr; 
2430     */
2431     //    add += Form("AliLog::SetGlobalLogLevel(%d);\n",AliLog::GetGlobalLogLevel());
2432   TString add = "";
2433
2434   if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2435   add += "\n\n // added by CKB \n";
2436   if(kErrorIgnoreLevel>0)add += Form("gErrorIgnoreLevel = %d;\n",kErrorIgnoreLevel);
2437   add += "\n gSystem->AddIncludePath(\"./\"); \n";
2438   add += "\n gSystem->SetFPEMask(); \n";
2439
2440
2441   if(gGrid&&kPluginAliRootVersion.Length()==0){
2442     /*
2443     add += "\n // Dirty hack for TRD reference data \n";
2444     add += "\n gSystem->Setenv(\"ALICE_ROOT\",\"";
2445     add += Form("alien://%s/rootfiles/",gGrid->GetHomeDirectory());
2446     add += "\"); \n";
2447     */
2448   }
2449
2450   add += "// BKC \n\n";
2451   st.Insert(index,add.Data());
2452
2453   if(kUseDebug){
2454     //    st.Insert(index,"\n gROOT->ProcessLine(\".trace\"); // CKB \n");
2455   }
2456
2457   if(kUseCPAR&&kPluginAliRootVersion.Length()==0){
2458     index = st.Index("gSystem->AddIncludePath(\"-I$"); // uncommen $ALICE_ROOT include for par files
2459     if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2460     st.Insert(index,"// CKB comment out whehn no aliroot is provided \n //");
2461   }
2462
2463   if(AliLog::GetGlobalLogLevel()==AliLog::kFatal){
2464     index = st.Index("AliLog::SetGlobal"); // ncomment setting of log level, do my own
2465     if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2466     st.Insert(index,"AliLog::SetGlobalLogLevel(AliLog::kFatal);// CKB \n  // CKB comment out for own setting \n  //");
2467   }
2468
2469   ofstream out;
2470   out.open(Form("%s.C", kTrainName.Data()));
2471   if (out.bad()) {
2472     return kFALSE;
2473   }
2474   out << st << endl;
2475   Printf("<<< Patching AnalysisMacro");
2476
2477
2478
2479
2480
2481   Printf(">>> Patching Merge Macro");
2482   gSystem->Exec(Form("mv %s_merge.C %s_merge.C_tmp",kTrainName.Data(),kTrainName.Data()));
2483
2484   ifstream in2; 
2485   in2.open(Form("%s_merge.C_tmp", kTrainName.Data()));
2486   TString st2;
2487   while(in2.getline(cLine,250)){
2488     st2 += cLine;
2489     st2 += "\n";
2490   }
2491   index = st2.Index("gSystem->Load(\"libPhysics\");");
2492   index += strlen("gSystem->Load(\"libPhysics\");");
2493   TString add2 = "";
2494   add2 += "\n gSystem->AddIncludePath(\"./\"); \n";
2495   if(gGrid&&kPluginAliRootVersion.Length()==0){
2496     /*
2497     add2 += "\n // Dirty hack for TRD reference data \n";
2498     add2 += "\n gSystem->Setenv(\"ALICE_ROOT\",\"";
2499     add2 += Form("alien://%s/rootfiles/",gGrid->GetHomeDirectory());
2500     add2 += "\"); \n";
2501     */
2502   }
2503   add2 += "// BKC \n\n";
2504   if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2505   st2.Insert(index,add.Data());
2506
2507
2508   if(kUseDebug){
2509     //    st2.Insert(index,"\n gROOT->ProcessLine(\".trace\"); // CKB \n");
2510   }
2511
2512   if(kUseCPAR&&kPluginAliRootVersion.Length()==0){
2513     index = st2.Index("gSystem->AddIncludePath(\"-I$"); // uncomment $ALICE_ROOT include for par files
2514     if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2515     st2.Insert(index,"// CKB comment out whehn no aliroot is provided \n //");
2516   }
2517
2518   // do not exclude the extra files from merign, this is done explicitly in this train script
2519   //  index = st2.Index("mergeExcludes +="); // uncommen $ALICE_ROOT include for par files
2520   //  if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2521   // st2.Insert(index,"// CKB comment out, handled explicitly by the train macro \n //");
2522
2523
2524   ofstream out2;
2525   out2.open(Form("%s_merge.C", kTrainName.Data()));
2526   if (out2.bad()) {
2527     return kFALSE;
2528   }
2529   out2 << st2 << endl;
2530   Printf("<<< Patching Merging Macro");
2531
2532
2533
2534   return kTRUE;
2535
2536 }