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