Write Calo QA output to a separate file
[u/mrichter/AliRoot.git] / PWG4 / macros / AnalysisTrainPWG4Jets.C
1 //===================== ANALYSIS TRAIN =========================================
2 // To use: copy this macro to your work directory, modify the global part to match
3 // your needs, then run root.
4 //    root[0] .L AnalysisTrain.C
5 // Grid full mode as below (other modes: test, offline, submit, terminate)
6 //    root[1] AnalysisTrainPWG-244Jets("grid", "full")
7 // CAF mode (requires root v5-23-02 + aliroot v4-16-Rev08)
8 //    root[2] AnalysisTrainPWG4Jets("proof")
9 // Local mode requires AliESds.root or AliAOD.root in ./data directory
10 //    root[3] AnalysisTrainPWG4Jets("local")
11 // In proof and grid modes, a token is needed and sourcing the produced environment file.
12 //
13 // If 'saveTrain' flag is set, the train will generate a directory name and run
14 // in this directory. A configuration file 'ConfigTrain.C' will be generated. 
15 // One can replay at any time the train via:
16 //    root[1] AnalysisTrainPWG4Jets(ana_mode, plugin_mode, "train_default_<date>/ConfigTrain.C")
17
18 // For Usage with fastjet run in "offline" first and then "submit"
19 // jdl and analysismacro are automatically patched after "offline" mode
20
21 // =============================================================================
22 // ### General Steering variables
23 // =============================================================================
24 //== general setup variables
25 TString     kTrainName         = "testAnalysis"; // *CHANGE ME* (no blancs or special characters)
26 TString     kJobTag            = "PWG4 Jet Tasks analysis train configured"; // *CHANGE ME*
27
28 // Usage of par files ONLY in grid mode and ONLY if the code is not available
29 // in the deployed AliRoot versions. Par file search path: local dir, if not there $ALICE_ROOT.
30 // To refresh par files, remove the ones in the workdir, then do "make <target.par>" in 
31 // AliRoot.
32 Bool_t      kUsePAR             = kFALSE;  // use par files for extra libs
33 Bool_t      kUseCPAR            = kFALSE;  // use par files for common libs
34 Bool_t      kFillAOD = kFALSE;  // switch of AOD filling for on the fly analysis
35 Int_t       kSaveAOD = 8;        // Bit switch 1 = Full AOD 2 = Jet AOD , 4 = PartCorr, 8 = JCORRAN 
36 //== general input and output variables
37
38 Int_t       iAODanalysis       = 1;      // Analysis on input AOD's
39 Int_t       iAODhandler        = 1;      // Analysis produces an AOD or dAOD's
40 Int_t       iESDfilter         = 0;      // ESD to AOD filter (barrel + muon tracks)
41 Int_t       iPhysicsSelection  = 1;      // ESD to AOD filter (barrel + muon tracks)
42 Bool_t      kUseKinefilter     = kFALSE; // use Kinematics filter
43 Bool_t      kUseMuonfilter     = kFALSE; // use Kinematics filter
44 TString     kCommonOutputFileName = "PWG4_JetTasksOutput.root";
45 TString     kCaloQAOutputFileName = "PWG4_CaloQAOutput.root";
46
47
48 //== general process variables
49
50 // ### Other flags to steer the analysis
51 //==============================================================================
52 Bool_t      kSkipTerminate      = kTRUE; // Do not call Teminate
53 Bool_t      kUseDate            = kFALSE; // use date in train name
54 Bool_t      kUseDebug           = kTRUE; // activate debugging
55 Int_t         kErrorIgnoreLevel = -1; // takes the errror print level from .rootrc 
56 // From TError.h:
57 // const Int_t kUnset    =  -1;
58 // const Int_t kPrint    =   0;
59 // const Int_t kInfo     =   1000;
60 // const Int_t kWarning  =   2000;
61 // const Int_t kError    =   3000;
62 // const Int_t kBreak    =   4000;
63 // const Int_t kSysError =   5000;
64 // const Int_t kFatal    =   6000; 
65 Int_t         kUseSysInfo         = 0; // activate debugging
66 Long_t     kNumberOfEvents     = 1234567890; // number of events to process from the chain
67 Bool_t      kUseMC              = kTRUE;  // use MC info
68 Bool_t      kIsMC               = kTRUE;  // is MC info, if false it overwrites Use(AOD)MC
69 Bool_t      kUseAODMC           = kTRUE;  // use MC infA
70 Bool_t      kUseESDTags         = kFALSE; // use ESD tags for selection
71 Bool_t      kUseTR              = kFALSE;  // use track references
72 Bool_t      kUseAODTags         = kFALSE;  // use AOD tags
73 Bool_t      kSaveTrain          = kFALSE;  // save train configuration as: 
74
75
76 // ### Analysis modules to be included. Some may not be yet fully implemented.
77 //==============================================================================
78 Int_t       iJETAN             = 1;      // Jet analysis (PWG4) // 1 write standard 2 write non-standard jets, 3 wrtie both
79 Int_t       iDIJETAN           = 1;
80 Int_t       iJETANLib          = 1;
81 Int_t       iPWG1QASym         = 0;      // Eva's QA task compiled on the fly...
82 Int_t       iPWG4JetTasks      = 0;      // all jet tasks flag for lib laoding
83 Int_t       iPWG4JetServices   = 0;      // jet spectrum analysis
84 Int_t       iPWG4JetSpectrum   = 0;      // jet spectrum analysis
85 Int_t       iPWG4JCORRAN       = 0;      // JCORRAN module
86 Int_t       iPWG4UE            = 0;      // Underlying Event analysis
87 Int_t       iPWG4CorrectionsUE            = 0;      // Underlying Event analysis
88 Int_t       iPWG4TmpSourceSara = 0;      // Underlying Event analysis not in svn
89 Int_t       iPWG4TmpSourceFrag = 0;      // Bastian's Fragmentation function not in svn
90 Int_t       iPWG4JetChem       = 0;      // Jet chemistry 
91 Int_t       iPWG4PtQAMC        = 0;      // Marta's QA tasks 
92 Int_t       iPWG4PtSpectra     = 0;      // Marta's QA tasks 
93 Int_t       iPWG4PtQATPC       = 0;      // Marta's QA tasks 
94 Int_t       iPWG4Cosmics     = 0;      // Marta's Cosmics Taks 
95 Int_t       iPWG4ThreeJets     = 0;      // Sona's thrust task
96 Int_t       iPWG4KMeans        = 0;      // Andreas' KMeans task 
97 Int_t       iPWG4Cluster       = 0;      // CKB cluster task 
98 Int_t       iEMCUtilLibs       = 0;      // Flag to satisfy dependence on EMC utils
99 Int_t       iPWG4PartCorrLibs  = 0;      // Gustavo's part corr analysis
100 Int_t       iPWG4PartCorr      = 0;      // Gustavo's part corr analysis
101 Int_t       iPWG4CaloQA        = 0;      // Gustavo's part corr analysis
102 Int_t       iPWG4JetCorr       = 0;     // Paul's jet corr analysis
103 Int_t       iPWG4Tagged        = 0;      // Gustavo's part corr analysis
104 Int_t       iPWG4omega3pi      = 0;      // Omega to 3 pi analysis (PWG4) 
105 Int_t       iPWG4GammaConv     = 0;      // Gamma Conversio
106 Int_t       kHighPtFilterMask  = 16;     // change depending on the used AOD Filter
107 TString     kDeltaAODJetName   = "AliAOD.Jets.root";     
108 TString     kDeltaAODJCORRANName   = "AliAOD.JCORRAN.root";     
109 TString     kDeltaAODPartCorrName   = "deltaAODPartCorr.root";     
110
111
112 //==============================================================================
113 // ### PROOF Steering varibales
114 //==============================================================================
115 //== proof setup variables
116 TString     kProofCluster      = "alicecaf.cern.ch";
117 Bool_t      kProofUseAFPAR     = kFALSE;  // use AF special par file
118 TString     kProofAFversion          = "AF-v4-17";
119 //== proof input and output variables
120 TString     kProofDataSet      = "/COMMON/COMMON/LHC09a4_run8100X#/esdTree";
121 Bool_t      kProofSaveToAlien   = kFALSE; // save proof outputs in AliEn train_[trainName]_ddMonthyyyy_time.C
122 TString     kProofOutdir       = "";
123 Bool_t      kProofClearPackages = kFALSE;
124 Int_t       kProofEvents = 10000;
125 Int_t       kProofOffset = 0;
126 //== proof process variables
127
128
129 //==============================================================================
130 // ### Grid plugin Steering varibiables
131 //==============================================================================
132 //== grid plugin setup variables
133 Bool_t      kPluginUse         = kTRUE;   // do not change
134 Bool_t      kPluginUseProductionMode  = kFALSE;   // use the plugin in production mode
135 TString     kPluginRootVersion       = "v5-26-00b-6";  // *CHANGE ME IF MORE RECENT IN GRID*
136 TString     kPluginAliRootVersion    = "v4-19-15-AN";  // *CHANGE ME IF MORE RECENT IN GRID*                                          
137 Bool_t      kPluginMergeViaJDL       = kTRUE;  // merge via JDL
138 Bool_t      kPluginFastReadOption   = kFALSE;  // use xrootd tweaks
139 Bool_t      kPluginOverwriteMode    = kTRUE;  // overwrite existing collections
140 Int_t       kPluginOutputToRunNumber = 1;     // write the output to subdirs named after run number
141 // TString kPluginExecutableCommand = "root -b -q";
142 TString     kPluginExecutableCommand = "source /Users/kleinb/setup_32bit_aliroot_trunk_clean_root_trunk.sh; alienroot -b -q ";
143
144 // == grid plugin input and output variables
145 TString     kGridDatadir      = "/alice/sim/PDC_08b/LHC09a1/AOD/";
146 Int_t         kGridMaxRunsFromList = 999999999;
147 TString     kGridLocalRunList = "";
148 TString     kGridOutdir       = ""; // AliEn output directory. If blank will become output_<kTrainName>
149 TString     kGridDataSet      = ""; // sub working directory not to confuse different run xmls 
150 Int_t         kGridRunRange[2]       =  {0, -1}; // Set the run range
151 TString     kGridRunPattern        = "%03d"; // important for leading zeroes!!
152 TString     kGridPassPattern       = "";
153 TString     kGridExtraFiles        = ""; // files that will be added to the input list in the JDL...
154 Int_t         kGridMaxMergeFiles      = 12; // Number of files merged in a chunk grid run range
155 TString     kGridMergeExclude       = "AliAOD.root"; // Files that should not be merged
156 TString     kGridOutputStorages      = "disk=2"; // Make replicas on the storages
157 // == grid process variables
158 Int_t       kGridRunsPerMaster     = 100; // Number of runs per master job
159 Int_t       kGridFilesPerJob       = 100; // Maximum number of files per job (gives size of AOD)
160
161 //==============================================================================
162 // ### Local Steering variables
163 //==============================================================================
164 //== local setup variables
165 //== local input and output variables
166 TString     kLocalXMLDataset   = ""; // Change local xml dataset for local interactive analysis
167 TString     kLocalDataList   = "local_deltaaod.txt"; // Change local xml dataset for local interactive analysis
168 // == local process variables
169
170
171
172 // Temporaries.
173 TString anaPars = "";
174 TString anaLibs = "";
175 TString anaLibsExtra = "";
176 TString anaSources = "";
177 // Function signatures
178 class AliAnalysisAlien;
179
180 //______________________________________________________________________________
181 void AnalysisTrainPWG4Jets(const char *analysis_mode="local", 
182                            const char *plugin_mode="",
183                            const char *config_file="",Int_t iOffset = 0)
184 {
185 // Main analysis train macro. If a configuration file is provided, all parameters
186 // are taken from there but may be altered by CheckModuleFlags.
187
188    if (strlen(config_file) && !LoadConfig(config_file)) return;
189
190    if(iOffset)kProofOffset = iOffset;
191    TString smode(analysis_mode);
192    smode.ToUpper();
193    if (kSaveTrain)WriteConfig();
194    // Check compatibility of selected modules
195    CheckModuleFlags(smode);
196    //   gROOT->ProcessLine(".trace");
197
198    printf("==================================================================\n");
199    printf("===========    RUNNING ANALYSIS TRAIN %s IN %s MODE   ==========\n", kTrainName.Data(),smode.Data());
200    printf("==================================================================\n");
201                               printf("=  Configuring analysis train for:                               =\n");
202    if (iAODanalysis) printf("=  AOD analysis                                                  =\n");
203    else                     printf("=  ESD analysis                                                  =\n");
204    if (iPhysicsSelection)   printf("=  Physics selection                                                =\n");
205    if (iESDfilter)   printf("=  ESD filter                                                    =\n");
206    if (iJETAN)       printf("=  Jet analysis                                                  =\n");
207    printf("==================================================================\n");
208
209    char *printMask = ":: %20s  %10d\n";
210    printf(printMask,"Fill AOD",(UInt_t)kFillAOD);
211    printf(printMask,"Save AOD", (UInt_t)kSaveAOD);
212    printf(printMask,"MC truth", (UInt_t)kUseMC);
213    printf(printMask,"KINE filter", (UInt_t)kUseKinefilter);
214    printf(printMask,"track refs", (UInt_t)kUseTR);
215    printf(printMask,"tags", (UInt_t)kUseESDTags);
216    printf(printMask,"AOD tags", (UInt_t)kUseAODTags);
217    printf(printMask,"debugging", (UInt_t)kUseDebug);
218    printf(printMask,"PAR files", (UInt_t)kUsePAR);
219    printf(printMask,"AliEn plugin", (UInt_t)kPluginUse);
220    printf(printMask,"PWG1 QA sym", iPWG1QASym);
221    printf(printMask,"PWG4 Source Sara",iPWG4TmpSourceSara);
222    printf(printMask,"PWG4 Source BB",iPWG4TmpSourceFrag);
223    printf(printMask,"PWG4 Jet Chem",iPWG4JetChem);
224    printf(printMask,"PWG4 Jet tasks",iPWG4JetTasks);
225    printf(printMask,"PWG4 Jet Services",iPWG4JetServices);     
226    printf(printMask,"PWG4 Jet Spectrum",iPWG4JetSpectrum);
227    printf(printMask,"PWG4 JCORRAN",iPWG4JCORRAN);
228    printf(printMask,"PWG4 UE",iPWG4UE); 
229    printf(printMask,"PWG4 Corrections UE",iPWG4CorrectionsUE); 
230    printf(printMask,"PWG4 Pt QA MC",iPWG4PtQAMC);
231    printf(printMask,"PWG4 Pt Spectra",iPWG4PtSpectra);
232    printf(printMask,"PWG4 Pt QA TPC",iPWG4PtQATPC);     
233    printf(printMask,"PWG4 Cosmics",iPWG4Cosmics);     
234    printf(printMask,"PWG4 Three Jets",iPWG4ThreeJets);
235    printf(printMask,"PWG4 KMeans",iPWG4KMeans);
236    printf(printMask,"PWG4 Cluster",iPWG4Cluster);
237    printf(printMask,"PWG4 Part Corr",iPWG4PartCorr);
238    printf(printMask,"PWG4 Calo QA",iPWG4CaloQA);
239    printf(printMask,"PWG4 Jet Corr",iPWG4JetCorr);
240    printf(printMask,"PWG4 JCORRAN",iPWG4JCORRAN);
241    printf(printMask,"PWG4 Tagged",iPWG4Tagged);
242    printf(printMask,"PWG4 omega to 3 pi ",iPWG4omega3pi);
243    printf(printMask,"PWG4 Gamma Conv",iPWG4GammaConv);
244    printf(printMask,"HighPt FilterMask",kHighPtFilterMask);    
245    
246    //==========================================================================
247    // Connect to back-end system
248    if (!Connect(smode)) {
249       ::Error("AnalysisTrain", "Could not connect to %s back-end", analysis_mode);
250       return;
251    }   
252
253    // Load common libraries and set include path
254    if (!LoadCommonLibraries(smode)) {
255       ::Error("AnalysisTrain", "Could not load common libraries");
256       return;
257    }
258
259
260     
261    // Make the analysis manager and connect event handlers
262    AliAnalysisManager *mgr  = new AliAnalysisManager("PWG4Train", "pwg4 mini train");
263    if (kCommonOutputFileName.Length()>0)mgr->SetCommonFileName(kCommonOutputFileName.Data());
264    if (kProofSaveToAlien) mgr->SetSpecialOutputLocation(kProofOutdir);
265    mgr->SetNSysInfo(0);
266    if (!strcmp(plugin_mode, "test")) mgr->SetNSysInfo(1);
267    if (kUseSysInfo)mgr->SetNSysInfo(kUseSysInfo);
268    mgr->SetSkipTerminate(kSkipTerminate);
269
270    // Load analysis specific libraries
271    if (!LoadAnalysisLibraries(smode)) {
272       ::Error("AnalysisTrain", "Could not load analysis libraries");
273      return;
274    }   
275
276    // Create input handler (input container created automatically)
277    if (iAODanalysis) {
278    // AOD input handler
279       AliAODInputHandler *aodH = new AliAODInputHandler();
280       mgr->SetInputEventHandler(aodH);
281       if (iPWG4JetTasks) aodH->AddFriend(Form("deltas/%s",kDeltaAODJetName.Data()));
282       if (iPWG4PartCorr) aodH->AddFriend(Form("deltas/%s"kDeltaAODJetName.Data()));
283    } else {   
284    // ESD input handler
285       AliESDInputHandler *esdHandler = new AliESDInputHandler();
286       if (kUseESDTags) esdHandler->SetReadTags();
287       esdHandler->SetReadFriends(kFALSE);
288       mgr->SetInputEventHandler(esdHandler);       
289       //      if(iPWG4PtQATPC&& !kTrainName.Contains("pass5"))esdHandler->SetActiveBranches("ESDfriend");
290
291    }
292
293    // Monte Carlo handler
294    if (kUseMC && !iAODanalysis) {
295       AliMCEventHandler* mcHandler = new AliMCEventHandler();
296       mgr->SetMCtruthEventHandler(mcHandler);
297       mcHandler->SetReadTR(kUseTR); 
298    }   
299    // AOD output container, created automatically when setting an AOD handler
300    if (iAODhandler) {
301       // AOD output handler
302       AliAODHandler* aodHandler   = new AliAODHandler();
303       aodHandler->SetOutputFileName("AliAOD.root");
304       aodHandler->SetFillAODforRun(kFillAOD);
305       
306       mgr->SetOutputEventHandler(aodHandler);
307       //
308       if (iAODanalysis) {
309
310         //         aodHandler->SetCreateNonStandardAOD();
311         //      if (iJETAN)aodHandler->SetOutputFileName(kDeltaAODJetName.Data());
312       } 
313       AliAnalysisDataContainer * cout_aod = mgr->GetCommonOutputContainer();
314       cout_aod->SetSpecialOutput();
315    }
316    // Debugging if needed
317
318    if (kUseDebug){
319      mgr->SetDebugLevel(3);
320    }
321    if(kUseSysInfo>0){
322      mgr->RegisterExtraFile("syswatch.root");
323      if(kGridMergeExclude.Length())kGridMergeExclude += " ";
324      kGridMergeExclude += "syswatch.root";
325    }
326    else{
327      AliLog::SetGlobalLogLevel(AliLog::kError);
328    }
329
330
331    //==========================================================================
332    // Create the chain. In this example it is created only from ALIEN files but
333    // can be done to work in batch or grid mode as well.
334    TChain *chain = CreateChain(smode, plugin_mode);
335         
336    //==========================================================================
337    // Load the tasks configuration macros for all wagons. These files are supposed now to be
338    // in the current workdir, but in AliEn they will be in the file catalog, 
339    // mapped from AliRoot and pecified in the jdl input list.
340     
341    // For now connection to top input container and common AOD output container
342    // is done in this macro, but in future these containers will be connected
343    // from each task configuration macro.
344    if(iPhysicsSelection && !iAODanalysis){
345      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
346      AliPhysicsSelectionTask* physSelTask = AddTaskPhysicsSelection(kIsMC,kTRUE,kTRUE); // last flag also adds information on  
347    }
348
349    if (iESDfilter && !iAODanalysis) {
350       //  ESD filter task configuration.
351       gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskESDFilter.C");
352       AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(kUseKinefilter,kUseMuonfilter);
353       if(kIsMC){
354         mgr->RegisterExtraFile("pyxsec_hists.root");
355         if(kGridMergeExclude.Length())kGridMergeExclude += " ";
356         kGridMergeExclude += "pyxsec_hists.root";
357
358       }
359    }   
360
361    // AOD tags
362    if (kUseAODTags) {
363       AliAnalysisTaskTagCreator* tagTask = new AliAnalysisTaskTagCreator("AOD Tag Creator");
364       mgr->AddTask(tagTask);
365       AliAnalysisDataContainer *coutTags = mgr->CreateContainer("cTag",  TTree::Class(), 
366                                            AliAnalysisManager::kOutputContainer, "AOD.tag.root");
367       mgr->ConnectInput (tagTask, 0, mgr->GetCommonInputContainer());
368       mgr->ConnectOutput(tagTask, 1, coutTags);
369    }   
370     
371     // Jet analysis
372    if (iJETAN) {
373       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJets.C");
374       AliAnalysisTaskJets *taskjets = 0;
375       if(iJETAN&1)taskjets = AddTaskJets(kHighPtFilterMask); 
376       if(iJETAN&2){
377         UInt_t selection = 0;
378         if(!kFillAOD) selection = 0xffffff&~(1<<13)&~(1<<5)&~(1<<6);
379         else selection = 0xffffff&~(1<<13);  // selection = 1<<0|1<<1|1<<2|1<<5|1<<6|1<<7|1<<8|1<<9|1<<10|1<<11|1<<12; (DA takes quite long....)
380         AddTaskJetsDelta(kDeltaAODJetName.Data(),kHighPtFilterMask,kUseAODMC,selection); 
381       }
382       if (!taskjets) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
383    }
384
385    if (iDIJETAN) {
386       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskDiJets.C");
387       AliAnalysisTaskDiJets *taskdijets = 0;
388       if(iDIJETAN&1)taskdijets = AddTaskDiJets(); 
389       if (!taskdijets) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
390       if(iDIJETAN&2){
391         taskdijets = AddTaskDiJets("jetsAOD_CDF07"); 
392         taskdijets = AddTaskDiJets("jetsAOD_DA07"); 
393         taskdijets = AddTaskDiJets("jetsAOD_FASTJET07"); 
394         taskdijets = AddTaskDiJets("jetsAOD_FASTKT07"); 
395         taskdijets = AddTaskDiJets("jetsAOD_SISCONE07"); 
396         taskdijets = AddTaskDiJets("jetsAOD_UA107");
397       }
398    }
399
400    if(iPWG1QASym){
401      gROOT->LoadMacro("$ALICE_ROOT/PWG1/PilotTrain/AddTaskQAsym.C");
402      AliAnalysisTaskQASym *taskQASym = AddTaskQAsym(-1);
403      if (!taskQASym) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQASym cannot run for this train conditions - EXCLUDED");
404    }
405
406
407
408    if(iPWG4TmpSourceSara){
409      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskEta.C");
410      AliAnalysisTaskEta *taskEta = AddTaskEta();
411      if (!taskEta) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskEta cannot run for this train conditions - EXCLUDED");
412    }
413
414    if(iPWG4TmpSourceFrag){
415      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskFragFunc.C");
416      UInt_t selection = 1<<2;
417      AliAnalysisTaskFragFunc *taskFrag = AddTaskFragFunc(kHighPtFilterMask, kUseAODMC,iPhysicsSelection, selection);
418      if (!taskFrag) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskFragFunc cannot run for this train conditions - EXCLUDED");
419    }
420
421
422    if(iPWG4JetChem){
423      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetChem.C");
424      AliAnalysisTask *taskChem = AddTaskJetChem();
425      if (!taskChem) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetChem cannot run for this train conditions - EXCLUDED");
426    }
427
428
429    if(iPWG4JetServices){
430      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetServices.C");
431      AliAnalysisTaskJetServices *taskjetServ = 0;
432      taskjetServ = AddTaskJetServices();
433      if (!taskjetServ) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetServices cannot run for this train conditions - EXCLUDED");
434      if(kGridRunRange[0]>0)taskjetServ->SetRunRange(kGridRunRange[0],kGridRunRange[1]);
435      else taskjetServ->SetRunRange(104000,125000);
436      if(!kIsMC) taskjetServ->SetRealData(kTRUE);
437      taskjetServ->SetUsePhysicsSelection((Bool_t)iPhysicsSelection);
438      taskjetServ->SetDebugLevel(0);
439    }
440
441    if(iPWG4JetSpectrum){
442      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetSpectrum2.C");
443      AliAnalysisTaskJetSpectrum2 *taskjetSpectrum = 0;
444      if(iPWG4JetSpectrum&1){
445        taskjetSpectrum = AddTaskJetSpectrum2("jets","",kHighPtFilterMask,iPhysicsSelection);      
446        if(!iAODanalysis){
447          //      taskjetSpectrum = AddTaskJetSpectrum2("jets","tracks32",32,iPhysicsSelection);       // tmp hack to give it a different name
448          //      taskjetSpectrum = AddTaskJetSpectrum2("jets","tracks64",64,iPhysicsSelection);      
449
450          if(kIsMC){
451            taskjetSpectrum = AddTaskJetSpectrum2("jetsAOD_FASTJET04","jetsAODMC_FASTJET04",kHighPtFilterMask,iPhysicsSelection,
452                                                  AliAnalysisHelperJetTasks::kIsPileUp|AliAnalysisHelperJetTasks::kPhysicsSelection|AliAnalysisHelperJetTasks::kVertexIn);  
453            taskjetSpectrum = AddTaskJetSpectrum2("jetsAOD_FASTJET04","jetsAODMC_FASTJET04",kHighPtFilterMask,iPhysicsSelection,
454                                                  AliAnalysisHelperJetTasks::kIsCosmic|AliAnalysisHelperJetTasks::kPhysicsSelection|AliAnalysisHelperJetTasks::kVertexIn);  
455            taskjetSpectrum = AddTaskJetSpectrum2("jetsAOD_FASTJET04","jetsAODMC_FASTJET04",kHighPtFilterMask,iPhysicsSelection,
456                                                  AliAnalysisHelperJetTasks::kNone);  
457            taskjetSpectrum = AddTaskJetSpectrum2("jetsAOD_FASTJET04","jetsAODMC2_FASTJET04",kHighPtFilterMask,iPhysicsSelection,
458                                                  AliAnalysisHelperJetTasks::kIsPileUp|AliAnalysisHelperJetTasks::kPhysicsSelection|AliAnalysisHelperJetTasks::kVertexIn);  
459            taskjetSpectrum = AddTaskJetSpectrum2("jetsAOD_FASTJET04","jetsAODMC2_FASTJET04",kHighPtFilterMask,iPhysicsSelection,
460                                                  AliAnalysisHelperJetTasks::kNone);  
461
462          }
463          else{
464            taskjetSpectrum = AddTaskJetSpectrum2("jetsAOD_FASTJET04","",kHighPtFilterMask,iPhysicsSelection, 
465                                                  AliAnalysisHelperJetTasks::kIsPileUp|AliAnalysisHelperJetTasks::kPhysicsSelection|AliAnalysisHelperJetTasks::kVertexIn);      
466            taskjetSpectrum = AddTaskJetSpectrum2("jetsAOD_FASTJET04","",kHighPtFilterMask,iPhysicsSelection, 
467                                                  AliAnalysisHelperJetTasks::kIsCosmic|AliAnalysisHelperJetTasks::kPhysicsSelection|AliAnalysisHelperJetTasks::kVertexIn);      
468            taskjetSpectrum = AddTaskJetSpectrum2("jetsAOD_FASTJET04","",kHighPtFilterMask,iPhysicsSelection,AliAnalysisHelperJetTasks::kNone);      
469          }
470        }
471        if (!taskjetSpectrum) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetSpectrum2 cannot run for this train conditions - EXCLUDED");
472        taskjetSpectrum->SetDebugLevel(1);
473      }
474
475      if(iPWG4JetSpectrum&2){
476        UInt_t selection = 0;
477        if(!iAODanalysis) selection = 0xffffff;
478        else selection = 1<<0|1<<1|1<<2|1<<3|1<<4|1<<5|1<<7|1<<8|1<<9;
479        AddTaskJetSpectrum2Delta(kHighPtFilterMask,kUseAODMC,iPhysicsSelection,selection);
480      }
481    }
482    if(iPWG4JCORRAN){
483      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJCORRANTask.C");
484      AliJCORRANTask* corran = AddTaskJCORRAN(kDeltaAODJCORRANName.Data(),0);
485      if(!corran)::Warning("AnalysisTrainPWG4Jets", "AliJCORRANTask cannot run for this train conditions - EXCLUDED");
486      else{
487        if(kDeltaAODJCORRANName.Length()>0)mgr->RegisterExtraFile(kDeltaAODJCORRANName.Data()); 
488      }
489    }
490
491    if(iPWG4UE){
492      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskUE.C");
493      AliAnalysisTaskUE *taskUE = 0;
494      if(iPWG4UE&1)taskUE = AddTaskUE(); 
495      if(iPWG4UE&2){
496        taskUE  =AddTaskUE("jetsAOD_CDF04","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
497        taskUE  =AddTaskUE("jetsAOD_CDF07","CDF", "LJ", "TRANSV","MSP");
498        taskUE  =AddTaskUE("jetsAOD_SISCONE04","CDF", "LJ", "TRANSV","MSP");
499        taskUE  =AddTaskUE("jetsAOD_SISCONE07","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
500        taskUE  =AddTaskUE("jetsAOD_ICDF","CDF","LJ","TRANSV","MSP");
501        taskUE  =AddTaskUE("jetsAOD_FASTKT04","CDF", "LJ", "TRANSV","MSP");
502        taskUE  =AddTaskUE("jetsAOD_FASTKT07","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
503        taskUE  =AddTaskUE("jetsAOD_NONE","CDF", "MP_eta05", "TRANSV","MSP");
504        taskUE  =AddTaskUE("jetsAOD_NONE","CDF", "MP_eta09", "TRANSV","MSP");
505      }
506
507      if (!taskUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskUE cannot run for this train conditions - EXCLUDED");
508    }
509    if(iPWG4CorrectionsUE){
510      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskCorrectionsUE.C");
511      AliAnalysisTaskCorrectionsUE *taskCorrectionsUE = 0;
512      if(iPWG4CorrectionsUE&1)taskCorrectionsUE = AddTaskCorrectionsUE("jetsAOD_NONE","CDF","MP_eta05","TRANSV","MSP",kFALSE);
513      if (!taskCorrectionsUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskCorrectionsUE cannot run for this train conditions - EXCLUDED");
514    }
515
516    if(iPWG4ThreeJets){
517      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskThreeJets.C");
518      AliAnalysisTaskThreeJets *taskThree = AddTaskThreeJets();
519      if(!taskThree)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskThreets cannot run for this train conditions - EXCLUDED");
520    }
521    if(iPWG4PtQAMC){
522      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQAMC.C");
523      AliPWG4HighPtQAMC *taskQAMC = AddTaskPWG4HighPtQAMC();
524      if (!taskQAMC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQAMC cannot run for this train conditions - EXCLUDED");
525    }
526
527    if(iPWG4PtQATPC){
528      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQATPConly.C");
529      AliPWG4HighPtQATPConly *taskQATPC = 0;
530      if(iPWG4PtQATPC&1)taskQATPC = AddTaskPWG4HighPtQATPConly(1);
531      if(iPWG4PtQATPC&2)taskQATPC = AddTaskPWG4HighPtQATPConly(2);
532
533  if (!taskQATPC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQATPC cannot run for this train conditions - EXCLUDED");
534    }
535
536    if(iPWG4Cosmics){
537      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4CosmicCandidates.C");
538
539      AliPWG4CosmicCandidates *taskPWG4CosmicCandidates = AddTaskPWG4CosmicCandidates(0);
540      taskPWG4CosmicCandidates = AddTaskPWG4CosmicCandidates(1);
541
542      if (!taskPWG4CosmicCandidates) ::Warning("AnalysisTrainPWG4Jets", "AddTaskPWG4CosmicCandidates cannot run for this train conditions - EXCLUDED");
543    }
544
545
546    if(iPWG4PtSpectra){
547      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtSpectra.C");
548      AliPWG4HighPtSpectra *taskPtSpectra = AddTaskPWG4HighPtSpectra();
549      if (!taskPtSpectra) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskPtSpectra cannot run for this train conditions - EXCLUDED");
550    }
551    if(iPWG4KMeans){
552      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskKMeans.C");
553      AliAnalysisTaskKMeans *taskKMeans = AddTaskKMeans();
554      if (!taskKMeans) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskKMenans cannot run for this train conditions - EXCLUDED");
555    }
556
557    if(iPWG4Cluster){
558      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetCluster.C");
559      AliAnalysisTaskJetCluster *taskCl = 0;
560      if(iPWG4Cluster&1){
561        taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelection,"KT");
562      }
563      if(iPWG4Cluster&2){
564        UInt_t selection = 0;
565        if(!iAODanalysis) selection = 0xffffff;
566        else selection = 1<<0|1<<1|1<<2|1<<3|1<<4|1<<5|1<<7|1<<8|1<<9;
567        AddTaskJetClusterDelta(kHighPtFilterMask,kUseAODMC,iPhysicsSelection,"KT",selection);
568      }
569      if(iPWG4Cluster&4){
570        UInt_t selection = 0;
571        if(!iAODanalysis) selection = 0xffffff;
572        else selection = 1<<0|1<<1|1<<2|1<<3|1<<4|1<<5|1<<7|1<<8|1<<9;
573        taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelection,"ANTIKT");
574        AddTaskJetClusterDelta(kHighPtFilterMask,kUseAODMC,iPhysicsSelection,"ANTIKT",selection);
575      }
576
577
578      if (!taskCl) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskCluster cannot run for this train conditions - EXCLUDED");
579
580    }
581    if(iPWG4PartCorr){
582      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPartCorr.C");
583      AliAnalysisTaskParticleCorrelation *taskpartcorrPHOS = AddTaskPartCorr("AOD", "PHOS",kFALSE,kIsMC);
584      if (!taskpartcorrPHOS) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation PHOS cannot run for this train conditions - EXCLUDED");
585      AliAnalysisTaskParticleCorrelation *taskpartcorrEMCAL = AddTaskPartCorr("AOD", "EMCAL",kFALSE,kIsMC);
586      if (!taskpartcorrEMCAL) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation EMCAL cannot run for this train conditions - EXCLUDED");
587      if(kDeltaAODPartCorrName.Length()>0)mgr->RegisterExtraFile(kDeltaAODPartCorrName.Data());
588    } 
589
590    if(iPWG4CaloQA){
591      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/QA/AddTaskCalorimeterQA.C");
592      AliAnalysisTaskParticleCorrelation *taskcaloQA =  AddTaskCalorimeterQA("ESD",kFALSE,kIsMC,kCaloQAOutputFileName.Data());
593      if(!taskcaloQA)::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation QA cannot run - EXCLUDED");
594      if(kCaloQAOutputFileName.Length()>0)mgr->RegisterExtraFile(kCaloQAOutputFileName.Data());
595    } 
596
597    if(iPWG4JetCorr){
598      //     using namespace JetCorrelHD;
599      TString cdir = gSystem->WorkingDirectory();
600      gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
601      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetCorrel.C");
602      AliAnalysisTaskJetCorrel *taskjetcorr = AddTaskJetCorrel();
603      gSystem->ChangeDirectory(cdir);
604      if (!taskjetcorr) ::Warning("AnalysisTrainNew", "AliAnalysisTaskJetCorrel  cannot run for this train conditions - EXCLUDED");
605    } 
606
607    if(iPWG4Tagged){
608      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskTaggedPhotons.C");
609      AliAnalysisTaskTaggedPhotons * taskTagged = AddTaskTaggedPhotons(kFALSE); // EMCAL
610      taskTagged = AddTaskTaggedPhotons(kTRUE); // PHOS 
611      if (!taskTagged) ::Warning("AnalysisTrainNew", "AliAnalysisTaskTaggedPhotons  cannot run for this train conditions - EXCLUDED");     
612    }
613    if (iPWG4omega3pi) {
614      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskomega3pi.C");
615      AliAnalysisTaskOmegaPi0PiPi *taskomega3pi = AddTaskomega3pi();
616      if (!taskomega3pi) ::Warning("AnalysisTrainNew", "AliAnalysisTaskomega3pi cannot run\
617  for these train conditions - EXCLUDED");
618    }
619
620    // PWG4 gamma conversion analysis
621    if (iPWG4GammaConv) {
622       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskGammaConversion.C");
623       TString cdir = gSystem->WorkingDirectory();
624       gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
625       //      TString gcArguments = "-run-on-train -run-jet -run-chic -run-neutralmeson -run-cf";
626       //      TString gcArguments = "-run-on-train -run-jet -run-neutralmeson -run-cf -use-own-xyz";
627       //      TString gcArguments = "-run-on-train -run-jet -run-neutralmeson -run-cf -use-own-xyz";
628       TString gcArguments = "-run-on-train -run-jet -run-omega-meson -run-neutralmeson";
629       TString kGCAnalysisCutSelectionId="9002111000";
630       gcArguments.Append(Form("-set-cut-selection  %s ",kGCAnalysisCutSelectionId.Data()));
631       if(!kIsMC)gcArguments += " -mc-off";
632       AliAnalysisTaskGammaConversion * taskGammaConversion = AddTaskGammaConversion(gcArguments,mgr->GetCommonInputContainer());
633       gSystem->ChangeDirectory(cdir);
634       taskGammaConversion->SelectCollisionCandidates();
635       if (!taskGammaConversion) ::Warning("AnalysisTrainNew", "AliAnalysisTaskGammaConversion cannot run for these train conditions - EXCLUDED");
636    }   
637
638
639    //==========================================================================
640    // FOR THE REST OF THE TASKS THE MACRO AddTaskXXX() is not yet implemented/
641    // Run the analysis
642    //    
643    if (kPluginUse) {
644       AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
645       AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
646    }
647    
648    if (mgr->InitAnalysis()) {
649      mgr->PrintStatus();
650      // if (kSaveTrain || strlen(config_file)) gSystem->ChangeDirectory(kTrainName);
651      if (!strcmp(plugin_mode,"submit")&&smode=="GRID"){
652        TString alien_workdir = gGrid->GetHomeDirectory();
653        if (iAODanalysis) alien_workdir += "analysisAOD";
654        else              alien_workdir += "analysisESD";
655        if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());
656        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
657        printf("=== AnalysisTrainPWG4Jets:: Registering jdl in the work directory alien://%s/%s, should be done by the manager! ===\n",
658               alien_workdir.Data(),gridhandler->GetGridOutputDir());
659
660        TString dest;
661        dest = Form("%s/%s/%s.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
662        if(AliAnalysisAlien::FileExists(dest.Data())){
663          //      Printf("%s exist on grid removing...",dest.Data());
664          //      gGrid->Rm(dest.Data());
665        }
666        TFile::Cp(Form("file:%s.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
667
668
669        TString dest;
670        dest = Form("%s/%s/%s_merge.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
671        if(AliAnalysisAlien::FileExists(dest.Data())){
672          //      Printf("%s exist on grid removing...",dest.Data());
673          //      gGrid->Rm(dest.Data());
674        }
675        TFile::Cp(Form("file:%s_merge.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
676
677        
678        dest = Form("%s/rootfiles/STEER/LQ1dRef_v1.root",gGrid->GetHomeDirectory());
679        if(AliAnalysisAlien::FileExists(dest.Data())){
680          Printf("%s exist on grid removing...",dest.Data());
681          gGrid->Rm(dest.Data());
682        }
683        TFile::Cp(Form("file:%s/STEER/LQ1dRef_v1.root",
684                       gSystem->ExpandPathName("$ALICE_ROOT")),Form("alien://%s",dest.Data()));
685      }
686      AliLog::SetGlobalLogLevel(AliLog::kError);
687      if((kUseSysInfo>0&&smode=="LOCAL")||!strcmp(plugin_mode, "test")){
688        TFile * fM = TFile::Open("manager_local.root","RECREATE");
689        mgr->Write();
690        fM->Close();
691      }
692      
693      // grmpf, aliroot error handler overwrites root
694      gErrorIgnoreLevel = kErrorIgnoreLevel;
695      if(gErrorIgnoreLevel>3000) AliLog::SetGlobalLogLevel(AliLog::kFatal);
696      StartAnalysis(smode, chain);
697      if((kUseSysInfo>0&&smode=="LOCAL")||!strcmp(plugin_mode, "test")){
698        for(int i = 0;i < mgr->GetTopTasks()->GetEntries();i++){
699          mgr->ProfileTask(i);
700        }
701      }
702      if (!strcmp(plugin_mode, "offline")&&smode=="GRID"){
703        // Offline mode path files
704        //       PatchJDL();
705        PatchAnalysisMacro();
706      }
707
708      if (kSaveTrain && smode=="GRID") {
709        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
710        TString alien_workdir = gGrid->GetHomeDirectory();
711        if (iAODanalysis) alien_workdir += "analysisAOD";
712        else              alien_workdir += "analysisESD";
713        if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());
714        //     kGridOutdir = gridhandler->GetGridOutputDir();
715        printf("=== Registering ConfigTrain.C in the work directory <%s> ===\n",
716                 alien_workdir.Data());
717        if (AliAnalysisAlien::FileExists(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data())))
718          gGrid->Rm(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
719        if (strcmp(plugin_mode, "test"))
720          TFile::Cp(Form("file:%sConfig.C",kTrainName.Data()), Form("alien://%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
721      }
722    }
723 }
724
725 //______________________________________________________________________________
726 void StartAnalysis(const char *mode, TChain *chain) {
727 // Start analysis.
728    Int_t imode = -1;
729    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
730    if (!strcmp(mode, "LOCAL")) imode = 0;
731    if (!strcmp(mode, "PROOF")) imode = 1;
732    if (!strcmp(mode, "GRID"))  imode = 2;
733    switch (imode) {
734       case 0:
735          if (!chain) {
736             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
737             return;
738          }   
739          mgr->StartAnalysis(mode, chain,kNumberOfEvents);
740          return;
741       case 1:
742          if (!kProofDataSet.Length()) {
743             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "kProofDataSet is empty");
744             return;
745          }   
746          mgr->StartAnalysis(mode, kProofDataSet, kProofEvents,kProofOffset);
747          return;
748       case 2:
749          if (kPluginUse) {
750             if (!mgr->GetGridHandler()) {
751                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Grid plugin not initialized");
752                return;
753             }   
754             mgr->StartAnalysis("grid");
755          } else {
756             if (!chain) {
757                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
758                return;
759             }   
760             mgr->StartAnalysis(mode, chain);
761          }   
762          return;
763    }      
764 }          
765     
766 //______________________________________________________________________________
767 void CheckModuleFlags(const char *mode) {
768 // Checks selected modules and insure compatibility
769    Int_t imode = -1;
770    if (!strcmp(mode, "LOCAL")) imode = 0;
771    if (!strcmp(mode, "PROOF")) imode = 1;
772    if (!strcmp(mode, "GRID"))  imode = 2;
773
774
775    if (kUseCPAR) {
776      kPluginAliRootVersion    = ""; // NO aliroot if we use CPAR
777    }
778
779    if (imode==1) {
780       if (!kUsePAR) {
781          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PAR files enabled due to PROOF analysis");
782          kUsePAR = kTRUE;
783       }   
784    }  
785    if (imode != 2) {
786       ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AliEn plugin disabled since not in GRID mode");
787       kPluginUse = kFALSE; 
788    }   
789
790
791    if(!kIsMC){
792      // switch off anthin related to MC
793      kUseMC = 0;
794      kUseAODMC = 0;
795      kUseTR = kFALSE;
796    }
797
798    if (iAODanalysis) {
799    // AOD analysis
800       if (kUseMC)
801          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "MC usage disabled in analysis on AOD's");
802       if (kUseAODTags)
803          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AOD tags usage disabled in analysis on AOD's");
804       kUseMC = kFALSE;
805       kUseTR = kFALSE;
806       kUseAODTags = kFALSE;
807       if (iESDfilter)
808          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "ESD filter disabled in analysis on AOD's");
809       iESDfilter   = 0;
810       if (iPhysicsSelection)
811          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "Physics Selection disabled in analysis on AOD's");
812       iPhysicsSelection   = 0;
813       if (!iAODhandler) {
814          if (iJETAN) 
815             ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "JETAN disabled in analysis on AOD's without AOD handler");
816          iJETAN = 0;
817          iDIJETAN = 0;
818       }
819       // Disable tasks that do not work yet on AOD data
820       if(iPWG4JCORRAN)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 JCORRAN disabled in analysis on AOD's");
821       iPWG4JCORRAN = 0;
822       if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
823       iPWG4PtQAMC        = 0;
824       if( iPWG4PtQATPC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtTPC disabled in analysis on AOD's");
825       iPWG4PtQATPC        = 0;
826       if( iPWG4Cosmics)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 Comics disabled in analysis on AOD's");
827       iPWG4Cosmics        = 0;
828
829       if( iPWG4PtSpectra)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
830       iPWG4PtSpectra     = 0;
831       if(iPWG4KMeans)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4KMeans disabled on AOD's");
832       iPWG4KMeans       = 0;
833       if (iPWG4JetCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4Jetcorr disabled on AOD's");
834       iPWG4JetCorr = 0;
835       if (iPWG4PartCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4partcorr disabled on AOD's");
836       iPWG4PartCorr = 0;
837       if (iPWG4CaloQA)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4CaloQA disabled on AOD's");
838       iPWG4CaloQA = 0;
839       if (iPWG4Tagged)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4tagged disabled on AOD's");
840       iPWG4Tagged = 0;
841       if (iPWG4omega3pi)
842         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG4omega3pi disabled on AOD's");
843       iPWG4omega3pi = 0;
844       if(iPWG1QASym)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG1 QA Sym disabled in analysis on AOD's");
845       if (iPWG4GammaConv)::Info("AnalysisPWG4Jets.C::CheckModuleFlags", "PWG4gammaconv disabled on AOD's");
846       iPWG4GammaConv = 0;   
847       iPWG1QASym     = 0;
848    } else {   
849    // ESD analysis
850      if (!kUseMC){
851        kUseTR = kFALSE;
852        
853        if(kUseKinefilter)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 Kine Filter disabled in analysis without MC");
854        kUseKinefilter = kFALSE;
855        if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis without MC");
856        iPWG4PtQAMC        = 0;
857        if( iPWG4CorrectionsUE)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 CorrectionsUE disabled in analysis without MC");
858        iPWG4CorrectionsUE = 0;
859      }
860      if (!kUseTR) {
861        if(iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "iPWG4QATPCMC disabled if not reading track references");
862        iPWG4PtQAMC        = 0;
863      }   
864      if (iJETAN){
865        iESDfilter=1;
866      }
867       if (!iESDfilter){
868         kUseKinefilter = kFALSE;
869         kUseMuonfilter = kFALSE;
870       }
871       if(!iJETAN){
872         iPWG4JetSpectrum = iPWG4UE =  iPWG4CorrectionsUE = iPWG4ThreeJets = iDIJETAN = 0;
873       }
874    }
875    iPWG4JetTasks = iPWG4JetServices||iPWG4JetSpectrum||iPWG4UE||iPWG4PtQAMC||iPWG4PtSpectra||iPWG4PtQATPC||iPWG4Cosmics||iPWG4ThreeJets||iPWG4JetChem;
876    iPWG4PartCorrLibs = iPWG4PartCorr||iPWG4Tagged||iPWG4CaloQA;
877    iEMCUtilLibs = iPWG4PartCorrLibs||iPWG4JCORRAN;
878    iJETANLib = iPWG4JetTasks||iJETAN||iDIJETAN;
879    if (iESDfilter) {iAODhandler=1;}
880    if (kUseKinefilter && !kUseMC) kUseKinefilter = kFALSE;
881    if (kUseAODTags && !iAODhandler) kUseAODTags = kFALSE;
882
883
884    
885 }
886
887 //______________________________________________________________________________
888 Bool_t Connect(const char *mode) {
889 // Connect <username> to the back-end system.
890    Int_t imode = -1;
891    if (!strcmp(mode, "LOCAL")) imode = 0;
892    if (!strcmp(mode, "PROOF")) imode = 1;
893    if (!strcmp(mode, "GRID"))  imode = 2;
894    TString username = gSystem->Getenv("alien_API_USER");
895    switch (imode) {
896       case 0:
897          break;
898       case 1:
899          if  (!username.Length()) {
900             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
901                            1. Have called: alien-token-init <username>\n \
902                            2. Have called: >source /tmp/gclient_env_$UID");
903             return kFALSE;
904          }
905          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to PROOF cluster <%s>", 
906                 username.Data(), kProofCluster.Data());
907          gEnv->SetValue("XSec.GSI.DelegProxy", "2");
908 //         TProof::Open(Form("%s@%s:31093", username.Data(), kProofCluster.Data()));       
909          TProof::Open(Form("%s@%s", username.Data(), kProofCluster.Data()));       
910          if (!gProof) {
911             if (strcmp(gSystem->Getenv("XrdSecGSISRVNAMES"), "lxfsrd0506.cern.ch"))
912                ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");
913             return kFALSE;
914          }
915          if(kProofClearPackages)gProof->ClearPackages();
916
917          if(kProofSaveToAlien){
918            TGrid::Connect("alien://");
919            if (gGrid) {
920              TString homedir = gGrid->GetHomeDirectory();
921              TString workdir = homedir + kTrainName;
922              if (!gGrid->Cd(workdir)) {
923                gGrid->Cd(homedir);
924                if (gGrid->Mkdir(workdir)) {
925                  gGrid->Cd(kTrainName);
926                  ::Info("AnalysisTrainPWG4Jets::Connect()", "Directory %s created", gGrid->Pwd());
927                }
928              }
929              gGrid->Mkdir("proof_output");
930              gGrid->Cd("proof_output");
931              kProofOutdir = Form("alien://%s", gGrid->Pwd());
932            }   
933          }
934          break;
935       case 2:      
936          if  (!username.Length()) {
937             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
938                            1. Have called: alien-token-init <username>\n \
939                            2. Have called: >source /tmp/gclient_env_$UID");
940             return kFALSE;
941          }
942          if (kPluginUse && !gSystem->Getenv("alien_CLOSE_SE")) {
943             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), 
944                            "When using the AliEn plugin it is preferable to define the \
945                            variable alien_CLOSE_SE in your environment.");
946             return kFALSE;
947          }
948          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to AliEn ...", 
949                 username.Data());
950          TGrid::Connect("alien://");
951          if (!gGrid || !gGrid->IsConnected()) return kFALSE;
952          break;
953       default:
954          ::Error("AnalysisTrainPWG4Jets.C::Connect", "Unknown run mode: %s", mode);
955          return kFALSE;
956    }
957    ::Info("AnalysisTrainPWG4Jets.C::Connect","Connected in %s mode", mode);
958    return kTRUE;
959 }
960
961 //______________________________________________________________________________
962 Bool_t LoadCommonLibraries(const char *mode)
963 {
964 // Load common analysis libraries.
965    Int_t imode = -1;
966    if (!strcmp(mode, "LOCAL")) imode = 0;
967    if (!strcmp(mode, "PROOF")) imode = 1;
968    if (!strcmp(mode, "GRID"))  imode = 2;
969    if (!gSystem->Getenv("ALICE_ROOT")) {
970       ::Error("AnalysisTrainPWG4Jets.C::LoadCommonLibraries", "Analysis train requires that analysis libraries are compiled with a local AliRoot"); 
971       return kFALSE;
972    }   
973    Bool_t success = kTRUE;
974    // ROOT libraries
975    gSystem->Load("libTree.so");
976    gSystem->Load("libGeom.so");
977    gSystem->Load("libVMC.so");
978    gSystem->Load("libPhysics.so");
979    
980    // Load framework classes. Par option ignored here.
981    switch (imode) {
982       case 0:
983       case 2:
984          if (kUseCPAR) {
985             success &= LoadLibrary("STEERBase", mode, kTRUE);
986             success &= LoadLibrary("ESD", mode, kTRUE);
987             success &= LoadLibrary("AOD", mode, kTRUE);
988             success &= LoadLibrary("ANALYSIS", mode, kTRUE);
989             success &= LoadLibrary("ANALYSISalice", mode, kTRUE);
990             success &= LoadLibrary("CORRFW", mode, kTRUE);
991          } else {   
992             success &= LoadLibrary("libSTEERBase.so", mode);
993             success &= LoadLibrary("libESD.so", mode);
994             success &= LoadLibrary("libAOD.so", mode);
995             success &= LoadLibrary("libANALYSIS.so", mode);
996             success &= LoadLibrary("libANALYSISalice.so", mode);
997             success &= LoadLibrary("libCORRFW.so", mode);
998             gROOT->ProcessLine(".include $ALICE_ROOT/include");
999          }   
1000          break;
1001       case 1:
1002          Int_t ires = -1;
1003          if (kProofUseAFPAR && !gSystem->AccessPathName(kProofAFversion)) ires = gProof->UploadPackage(kProofAFversion);
1004          if (ires < 0) {
1005             success &= LoadLibrary("STEERBase", mode);
1006             success &= LoadLibrary("ESD", mode);
1007             success &= LoadLibrary("AOD", mode);
1008             success &= LoadLibrary("ANALYSIS", mode);
1009             success &= LoadLibrary("ANALYSISalice", mode);
1010             success &= LoadLibrary("CORRFW", mode);
1011          } else { 
1012             ires = gProof->EnablePackage(kProofAFversion);
1013             if (ires<0) success = kFALSE;
1014             success &= LoadLibrary("CORRFW", mode);
1015          }
1016          break;         
1017       default:
1018          ::Error("AnalysisTrainPWG4Jets.C::LoadCommonLibraries", "Unknown run mode: %s", mode);
1019          return kFALSE;
1020    }
1021    if (success) {
1022       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    SUCCESS");
1023       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Include path for Aclic compilation:\n%s",
1024               gSystem->GetIncludePath());
1025    } else {           
1026       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    FAILED");
1027    }   
1028       
1029    return success;
1030 }
1031
1032 //______________________________________________________________________________
1033 Bool_t LoadAnalysisLibraries(const char *mode)
1034 {
1035 // Load common analysis libraries.
1036   Bool_t success = kTRUE;
1037    if (iESDfilter) {
1038       if (!LoadLibrary("PWG3base", mode, kTRUE) ||
1039           !LoadLibrary("PWG3muon", mode, kTRUE)) return kFALSE;
1040    }   
1041    // JETAN
1042    if (iJETANLib) {
1043      // this part needs some rework in case we do not need the fastjed finders for processing
1044      if (!LoadLibrary("JETAN", mode, kTRUE)) return kFALSE;
1045      if (!strcmp(mode, "PROOF")){
1046        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libCGAL.so\"\)", kTRUE); 
1047        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libfastjet.so\"\)", kTRUE); 
1048        // problem when loading siscone copiled with different gcc version??
1049        // gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libsiscone.so\"\)", kTRUE); 
1050        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libSISConePlugin.so\"\)", kTRUE);      
1051      }
1052      if(!kUsePAR){ 
1053        if (!LoadLibrary("CGAL", mode, kTRUE)) return kFALSE;
1054        if (!LoadLibrary("fastjet", mode, kTRUE)) return kFALSE;
1055        if (!LoadLibrary("siscone", mode, kTRUE)) return kFALSE;
1056        if (!LoadLibrary("SISConePlugin", mode, kTRUE)) return kFALSE;
1057      }
1058      else{
1059        // par files plus FASTJET needs some extra work... need to change
1060        // the loading sequence in the auto generated .C file
1061        if (!LoadLibrary("libCGAL.so", mode, kTRUE)) return kFALSE;
1062        if (!LoadLibrary("libfastjet.so", mode, kTRUE)) return kFALSE;
1063        if (!LoadLibrary("libsiscone.so", mode, kTRUE)) return kFALSE;
1064        if (!LoadLibrary("libSISConePlugin.so", mode, kTRUE)) return kFALSE;
1065      }
1066      if (!LoadLibrary("FASTJETAN", mode, kTRUE)) return kFALSE;
1067    }
1068    if(iPWG4JetTasks){
1069      if (!LoadLibrary("PWG4JetTasks", mode, kTRUE)) return kFALSE;
1070    }
1071
1072    if(iPWG1QASym){
1073      if (!LoadSource(Form("%s/PWG1/AliAnalysisTaskQASym.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
1074    }
1075    if(iPWG4TmpSourceSara){
1076      if(!kUsePAR)gSystem->AddIncludePath("-I$ALICE_ROOT/include/JetTasks"); // ugly hack!!
1077      if(!LoadSource(Form("%s/PWG4/JetTasks/AliAnalysisTaskEta.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
1078    }
1079    if(iPWG4TmpSourceFrag){
1080      if(!kUsePAR)gSystem->AddIncludePath("-I$ALICE_ROOT/include/JetTasks"); // ugly hack!!
1081      if(!LoadSource(Form("%s/PWG4/JetTasks/AliAnalysisTaskFragFunc.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
1082    }
1083
1084
1085    /*
1086    if(iPWG4JetChem){
1087      if(!kUsePAR)gSystem->AddIncludePath("-I$ALICE_ROOT/include/JetTasks"); // ugly hack!!
1088      if(!LoadSource(Form("%s/PWG4/JetTasks/AliAnalysisTaskJetChem.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
1089    }
1090    */
1091
1092    if(iEMCUtilLibs){
1093      if (!LoadLibrary("EMCALUtils", mode, kTRUE) ||
1094          !LoadLibrary("PHOSUtils", mode, kTRUE)) return kFALSE;
1095    }
1096
1097    if (iPWG4PartCorrLibs) {   
1098       if (!LoadLibrary("PWG4PartCorrBase", mode, kTRUE) ||
1099           !LoadLibrary("PWG4PartCorrDep", mode, kTRUE)) return kFALSE;
1100    }
1101    if(iPWG4JCORRAN){
1102      // PWG4 particle correlations
1103      if(!LoadLibrary("PWG4JCORRAN",mode,kTRUE))return kFALSE;
1104    }
1105    if (iPWG4JetCorr) { 
1106      if (!LoadLibrary("PWG4JetCorrel", mode, kTRUE)) return kFALSE;
1107    }  
1108    if (iPWG4omega3pi) {
1109      if (!LoadLibrary("PWG4omega3pi", mode, kTRUE)) return kFALSE;
1110    }
1111    if (iPWG4GammaConv) {
1112       if (!LoadLibrary("PWG4GammaConv", mode, kTRUE)) return kFALSE;
1113    }      
1114
1115    ::Info("AnalysisTrainPWG4Jets.C::LoadAnalysisLibraries", "Load other libraries:   SUCCESS");
1116    return kTRUE;
1117 }
1118
1119 //______________________________________________________________________________
1120 Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
1121 {
1122 // Load a module library in a given mode. Reports success.
1123    Int_t imode = -1;
1124    Int_t result;
1125    TString smodule(module);
1126    if (!strcmp(mode, "LOCAL")) imode = 0;
1127    if (!strcmp(mode, "PROOF")) imode = 1;
1128    if (!strcmp(mode, "GRID"))  imode = 2;
1129    TString mod(module);
1130    if (!mod.Length()) {
1131       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Empty module name");
1132       return kFALSE;
1133    }   
1134    // If a library is specified, just load it
1135    if (smodule.EndsWith(".so")) {
1136       mod.Remove(mod.Index(".so"));
1137       result = gSystem->Load(mod);
1138       if (result < 0) {
1139          ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load library %s", module);
1140          return kFALSE;
1141       }
1142       if (rec) anaLibs += Form("%s.so ",mod.Data()); 
1143       if (rec) anaLibsExtra += Form("%s.so ",mod.Data()); 
1144       return kTRUE;
1145    } 
1146    // Check if the library is already loaded
1147    if (strlen(gSystem->GetLibraries(Form("%s.so", module), "", kFALSE)) > 0)
1148       return kTRUE;    
1149    switch (imode) {
1150       case 0:
1151       case 2:
1152          if (kUsePAR) {
1153             result = SetupPar(module);
1154             if (rec) anaPars += Form("%s.par ", module);
1155          } else {
1156             result = gSystem->Load(Form("lib%s.so", module));
1157             if (rec) anaLibs += Form("lib%s.so ", module);
1158          }   
1159          break;
1160       case 1:
1161         if(!gSystem->AccessPathName(module)){
1162           ::Info("AnalysisTrainPWG4Jets.C::LoadLibrary", "Removing directory %s",module);
1163           gSystem->Exec(Form("rm -rf %s",module));
1164         }
1165          result = gProof->UploadPackage(module);
1166          if (result<0) {
1167             result = gProof->UploadPackage(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", module)));
1168             if (result<0) {
1169                ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);
1170                return kFALSE;
1171             }
1172          }   
1173          result = gProof->EnablePackage(module);
1174          break;
1175       default:
1176          return kFALSE;
1177    }         
1178    if (result < 0) {
1179       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load module %s", module);
1180       return kFALSE;
1181    }
1182    return kTRUE;
1183 }           
1184
1185
1186
1187 //______________________________________________________________________________
1188 Bool_t LoadSource(const char *source, const char *mode, Bool_t rec=kFALSE)
1189 {
1190 // Load a module library in a given mode. Reports success.
1191    Int_t imode = -1;
1192    Int_t result = -1;
1193    if (!strcmp(mode, "LOCAL")) imode = 0;
1194    if (!strcmp(mode, "PROOF")) imode = 1;
1195    if (!strcmp(mode, "GRID"))  imode = 2;
1196    TString ssource(source);
1197    TString basename = gSystem->BaseName(ssource.Data());
1198    if (!ssource.Length()) {
1199       ::Error("AnalysisTrainPWG4Jets.C::LoadSource", "Empty task name");
1200       return kFALSE;
1201    }   
1202    // we have a source code so compile it
1203    if (ssource.EndsWith(".cxx")) {
1204      // need to copy it here other wise the path is also used on grid...
1205      ssource.Remove(ssource.Index(".cxx"));
1206      basename.Remove(basename.Index(".cxx"));
1207      Printf("LoadSources:: Copying...  path %s{cxx,h}",ssource.Data());
1208      gSystem->Exec(Form("cp %s.cxx . ",ssource.Data()));
1209      gSystem->Exec(Form("cp %s.h . ",ssource.Data()));
1210      // Path to code
1211      // only needed for local compilation, in grid and proof mode 
1212      // the task headers are uploaded 
1213      //     path.Remove(path.Index(gSystem->BaseName(path.Data())));
1214      // Printf("LoadSources:: Including path %s",path.Data());
1215      //  if(path.Length()>0)gROOT->ProcessLine(Form(".include %s",path.Data()));
1216      Printf("LoadSources:: Loading...  path %s",basename.Data());
1217      switch (imode) {
1218      case 0:
1219        result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
1220        break;
1221      case 1:
1222        result = gProof->LoadMacro(Form("%s.cxx++g",basename.Data()));
1223        break;
1224      case 2:
1225        result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
1226        if (rec){
1227          // what we want to compile
1228          anaSources += Form("%s.cxx ",basename.Data()); 
1229          // what we need as input...
1230          anaLibs += Form("%s.cxx %s.h ",basename.Data(),basename.Data()); 
1231        }
1232        break;
1233      default:
1234        return kFALSE;
1235      }
1236    } 
1237    if (result < 0) {
1238       ::Error("AnalysisTrainPWG4Jets.C::LoadSources", "Could not load source %s", source);
1239       return kFALSE;
1240    }
1241    return kTRUE;
1242 }           
1243
1244
1245 //______________________________________________________________________________
1246 TChain *CreateChain(const char *mode, const char *plugin_mode)
1247 {
1248 // Create the input chain
1249    Int_t imode = -1;
1250    if (!strcmp(mode, "LOCAL")) imode = 0;
1251    if (!strcmp(mode, "PROOF")) imode = 1;
1252    if (!strcmp(mode, "GRID"))  imode = 2;
1253    TChain *chain = NULL;
1254    // Local chain
1255    switch (imode) {
1256       case 0:
1257          if (iAODanalysis) {
1258             if (!kLocalXMLDataset.Length()) {
1259                // Local AOD
1260                chain = new TChain("aodTree");
1261                TString line;
1262                ifstream in;
1263                in.open(kLocalDataList.Data());
1264                while (in.good()) {
1265                  in >> line;
1266                  if (line.Length() == 0) continue;
1267                  // cout << " line = " << line << endl;
1268                  chain->Add(line.Data());
1269                }       
1270             } else {
1271                // Interactive AOD
1272                chain = CreateChainSingle(kLocalXMLDataset, "aodTree");
1273             }
1274          } else {      
1275            if (!kLocalXMLDataset.Length()) {
1276              // Local ESD
1277              chain = new TChain("esdTree");
1278              TString line;
1279              ifstream in;
1280              in.open(kLocalDataList.Data());
1281              while (in.good()) {
1282                in >> line;
1283                if (line.Length() == 0) continue;
1284                cout << " line = " << line << endl;
1285                chain->Add(line.Data());
1286              }       
1287            } else {
1288              // Interactive ESD
1289                chain = CreateChainSingle(kLocalXMLDataset, "esdTree");
1290            }   
1291          }
1292          break;
1293       case 1:
1294          break;
1295       case 2:
1296          if (kPluginUse) {
1297 //            AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
1298 //            AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
1299          } else {
1300             TString           treeName = "esdTree";
1301             if (iAODanalysis) treeName = "aodTree";
1302             chain = CreateChainSingle("wn.xml", treeName);
1303          }
1304          break;      
1305       default:   
1306    }
1307    if (chain && chain->GetNtrees()) return chain;
1308    return NULL;
1309 }   
1310
1311 //______________________________________________________________________________
1312 TChain* CreateChainSingle(const char* xmlfile, const char *treeName)
1313 {
1314    printf("*******************************\n");
1315    printf("*** Getting the ESD Chain   ***\n");
1316    printf("*******************************\n");
1317    TAlienCollection * myCollection  = TAlienCollection::Open(xmlfile);
1318
1319    if (!myCollection) {
1320       ::Error("AnalysisTrainPWG4Jets.C::CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;
1321       return NULL ;
1322    }
1323
1324    TChain* chain = new TChain(treeName);
1325    myCollection->Reset() ;
1326    while ( myCollection->Next() ) chain->Add(myCollection->GetTURL("")) ;
1327    chain->ls();
1328    return chain;
1329 }
1330
1331 //______________________________________________________________________________
1332 Int_t SetupPar(char* pararchivename)
1333 {
1334    if (!pararchivename || !strlen(pararchivename)) return -1;
1335    char processline[1024];
1336    if (gSystem->AccessPathName(Form("%s.par", pararchivename))) {
1337       if (!gSystem->AccessPathName(Form("%s/%s.par", gSystem->Getenv("ALICE_ROOT"),pararchivename))) {
1338          ::Info("AnalysisTrainPWG4Jets.C::SetupPar", "Getting %s.par from $ALICE_ROOT", pararchivename);
1339         TFile::Cp(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", pararchivename)), 
1340                   Form("%s.par",pararchivename));
1341       } else {
1342          ::Error("AnalysisTrainPWG4Jets.C::SetupPar", "Cannot find %s.par", pararchivename);
1343          return -1;
1344       }   
1345    }
1346    if (kPluginUse && kSaveTrain) gSystem->Exec(Form("ln -s ../%s.par %s",pararchivename, kTrainName.Data()));
1347    gSystem->Exec(Form("tar xvzf %s.par", pararchivename));
1348
1349    TString ocwd = gSystem->WorkingDirectory();
1350    if (!gSystem->ChangeDirectory(pararchivename)) return -1;
1351         
1352    // check for BUILD.sh and execute
1353    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
1354       printf("*******************************\n");
1355       printf("*** Building PAR archive    ***\n");
1356       printf("*******************************\n");          
1357       if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
1358          Error("runProcess","Cannot Build the PAR Archive! - Abort!");
1359          return -1;
1360       }
1361    }
1362
1363         // check for SETUP.C and execute
1364         if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
1365             printf("*******************************\n");
1366             printf("*** Setup PAR archive       ***\n");
1367             printf("*******************************\n");
1368             gROOT->Macro("PROOF-INF/SETUP.C");
1369         }       
1370         if (!gSystem->ChangeDirectory(ocwd.Data())) return -1;
1371    return 0;
1372 }
1373
1374 //______________________________________________________________________________
1375 AliAnalysisAlien* CreateAlienHandler(const char *plugin_mode)
1376 {
1377 // Check if user has a valid token, otherwise make one. This has limitations.
1378 // One can always follow the standard procedure of calling alien-token-init then
1379 //   source /tmp/gclient_env_$UID in the current shell.
1380    if (!AliAnalysisGrid::CreateToken()) return NULL;
1381    AliAnalysisAlien *plugin = new AliAnalysisAlien();
1382 // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
1383    plugin->SetRunMode(plugin_mode);
1384    if (kPluginUseProductionMode) plugin->SetProductionMode();
1385    plugin->SetJobTag(kJobTag);
1386    plugin->SetNtestFiles(2);
1387 //   plugin->SetPreferedSE("ALICE::NIHAM::File");
1388 // Set versions of used packages
1389    plugin->SetAPIVersion("V1.1x");
1390    //   plugin->SetAPIVersion("V1.0x");
1391 //   plugin->SetAPIVersion("V2.4");
1392    plugin->SetROOTVersion(kPluginRootVersion);
1393    plugin->SetAliROOTVersion(kPluginAliRootVersion);
1394 // Declare input data to be processed.
1395 // Method 1: Create automatically XML collections using alien 'find' command.
1396 // Define production directory LFN
1397    plugin->SetGridDataDir(kGridDatadir.Data());
1398 // Set data search pattern
1399    if (iAODanalysis) plugin->SetDataPattern(" *AliAOD.root");
1400    else              plugin->SetDataPattern(Form(" %s/*/*ESD.tag.root",kGridPassPattern.Data()));
1401 // ...then add run numbers to be considered
1402 //   plugin->SetRunRange(kGridRunRange[0], kGridRunRange[1]);
1403    for (Int_t i=kGridRunRange[0]; i<=kGridRunRange[1]; i++) {
1404      Printf("AnalysisTrainPWG4Jets Adding run number %s", Form(kGridRunPattern.Data(),i));
1405      plugin->AddRunNumber(Form(kGridRunPattern.Data(),i));
1406    }   
1407
1408    if(kGridLocalRunList.Length()>0){
1409      ifstream in1;
1410      in1.open(kGridLocalRunList.Data());
1411      int iRun;
1412
1413      /*
1414      char c;
1415      char cLine[250];
1416      while(!in1.eof()){
1417        c = in1.get();
1418        if ( (c >= '0') && (c <= '9') )
1419          {
1420            in1.putback (c);
1421            in1>>iRun;
1422            Printf("AnalysisTrainPWG4Jets Adding run number from File %s", Form(kGridRunPattern.Data(),iRun));
1423            plugin->AddRunNumber(Form(kGridRunPattern.Data(),iRun));
1424        }
1425      else
1426        {
1427          in1.putback (c);
1428          in1.getline(cLine,250);
1429
1430        }
1431      }
1432      */
1433      
1434      Int_t nRun = 0;
1435
1436      // just use run numbers, negatives will be excluded
1437      while(in1>>iRun){
1438        
1439        if(iRun>0&&(nRun<kGridMaxRunsFromList)){
1440            Printf("AnalysisTrainPWG4Jets Adding run number from File %s", Form(kGridRunPattern.Data(),iRun));
1441            plugin->AddRunNumber(Form(kGridRunPattern.Data(),iRun));
1442            nRun++;
1443        }
1444        else{
1445          Printf("AnalysisTrainPWG4Jets Skipping run number from File %d", iRun);
1446        }
1447      }
1448    }
1449
1450 // Method 2: Declare existing data files (raw collections, xml collections, root file)
1451 // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
1452 // XML collections added via this method can be combined with the first method if
1453 // the content is compatible (using or not tags)
1454 //   plugin->AddDataFile("tag.xml");
1455 //   plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
1456 // Define alien work directory where all files will be copied. Relative to alien $HOME.
1457    TString alien_workdir = "";
1458    
1459    if (iAODanalysis)  alien_workdir += "analysisAOD";
1460    else               alien_workdir += "analysisESD";    
1461    if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());
1462    plugin->SetGridWorkingDir(alien_workdir.Data());
1463
1464    // Declare alien output directory. Relative to working directory.
1465    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
1466    plugin->SetGridOutputDir(kGridOutdir);
1467
1468    // Add external packages
1469    if (iJETAN||iDIJETAN) {
1470       plugin->AddExternalPackage("boost::v1_43_0");
1471       plugin->AddExternalPackage("cgal::v3.6");
1472       plugin->AddExternalPackage("fastjet::v2.4.2");
1473    }   
1474
1475
1476    // set extra libs before par file compilation
1477    anaLibs += kGridExtraFiles;
1478    anaLibs     = anaLibs.Strip();   
1479    Printf("anaLibs %s",anaLibs.Data());
1480    Printf("anaLibsExtra %s",anaLibsExtra.Data());
1481
1482    if (anaLibs.Length())          plugin->SetAdditionalLibs(anaLibs.Data());
1483    if (anaLibsExtra.Length())     plugin->SetAdditionalRootLibs(anaLibsExtra.Data());
1484
1485    TString ana_sources = "";
1486    TString ana_add = "";
1487    if (kUsePAR && anaPars.Length()) {
1488       printf("%s\n", anaPars.Data());
1489       TObjArray *arr;
1490       TObjString *objstr;
1491       arr = anaPars.Tokenize(" ");
1492       TIter next(arr);
1493       while ((objstr=(TObjString*)next())) plugin->EnablePackage(objstr->GetString());
1494       delete arr;
1495    } 
1496    
1497 // Declare the analysis source files names separated by blancs. To be compiled runtime
1498 // using ACLiC on the worker nodes.
1499    ana_sources = anaSources.Strip();
1500 // Declare all libraries (other than the default ones for the framework. These will be
1501 // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
1502
1503    if (ana_sources.Length()) plugin->SetAnalysisSource(ana_sources);
1504    plugin->SetExecutableCommand(kPluginExecutableCommand.Data());  
1505    // Declare the output file names separated by blancs.
1506    // (can be like: file.root or file.root@ALICE::Niham::File)
1507    plugin->SetMergeExcludes(kGridMergeExclude);
1508    plugin->SetMaxMergeFiles(kGridMaxMergeFiles);
1509    plugin->SetNrunsPerMaster(kGridRunsPerMaster);
1510    plugin->SetMergeViaJDL(kPluginMergeViaJDL);
1511    // Use fastread option
1512    plugin->SetFastReadOption(kPluginFastReadOption);
1513    // UseOverwrite mode
1514    plugin->SetOverwriteMode(kPluginOverwriteMode); 
1515    // Optionally define the files to be archived.
1516    //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:AliAOD.root,AOD.tag.root@ALICE::NIHAM::File");
1517    plugin->SetOutputToRunNo(kPluginOutputToRunNumber);     // write the output to subdirs named after run number
1518    
1519    // Put default output files to archive
1520    TString listhists = "";
1521    TString listaods  = "";
1522    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1523    TIter next(mgr->GetOutputs());
1524    AliAnalysisDataContainer *output;
1525    while ((output=(AliAnalysisDataContainer*)next())) {
1526       const char *filename = output->GetFileName();
1527       if (!(strcmp(filename, "default"))) {
1528         if (!mgr->GetOutputEventHandler()) continue;
1529          filename = mgr->GetOutputEventHandler()->GetOutputFileName();
1530          if (listaods.Length()) listaods += " ";
1531          listaods += filename;
1532       } else {
1533         if(!listhists.Contains(filename)){
1534           if (listhists.Length()) listhists += " ";
1535           listhists += filename;
1536         }
1537       }
1538    }
1539
1540    if (mgr->GetExtraFiles().Length()) {
1541      if (listaods.Length()) listaods += " ";
1542      listaods += mgr->GetExtraFiles();
1543    }
1544
1545    // if we do not fill the aod we do not need to store it
1546    //   kGridMergeExclude = listaods;
1547    
1548    if(kSaveAOD!=0){
1549      TString outputFiles =  "";
1550      outputFiles += mgr->GetExtraFiles();
1551      if (listhists.Length()) outputFiles += " ";
1552      outputFiles += listhists;
1553      plugin->SetDefaultOutputs(kFALSE);
1554      Printf("%s:%d Starting with the files %s",(char*)__FILE__,__LINE__,outputFiles.Data());
1555      // remove
1556      // no harm done when we try to remove something that is not there :)
1557      if(!(kSaveAOD&(1<<0))){
1558        outputFiles.ReplaceAll("AliAOD.root ","");
1559        listaods.ReplaceAll("AliAOD.root ","");
1560      }
1561      if(!(kSaveAOD&(1<<1))){
1562        if(kDeltaAODJetName.Length())outputFiles.ReplaceAll(kDeltaAODJetName.Data(),"");
1563        if(kDeltaAODJetName.Length())listaods.ReplaceAll(kDeltaAODJetName.Data(),"");
1564        
1565      }
1566      if(!(kSaveAOD&(1<<2))){
1567        if(kDeltaAODPartCorrName.Length())outputFiles.ReplaceAll(kDeltaAODPartCorrName.Data(),"");
1568        if(kDeltaAODPartCorrName.Length())listaods.ReplaceAll(kDeltaAODPartCorrName.Data(),"");
1569      }
1570      if(!(kSaveAOD&(1<<3))){
1571        if(kDeltaAODJCORRANName.Length())outputFiles.ReplaceAll(kDeltaAODJCORRANName.Data(),"");
1572        if(kDeltaAODJCORRANName.Length())listaods.ReplaceAll(kDeltaAODJCORRANName.Data(),"");
1573      }
1574      
1575      // 
1576      Printf("%s:%d Saving the files %s",(char*)__FILE__,__LINE__,outputFiles.Data());
1577      plugin->SetOutputFiles(outputFiles.Data());
1578    }
1579
1580    TString outputArchive;
1581    outputArchive = Form("log_archive.zip:std*@%s",kGridOutputStorages.Data());
1582    listaods.ReplaceAll(" ", ",");
1583    listhists.ReplaceAll(" ", ",");
1584    if (listhists.Length()) listhists = Form("hist_archive.zip:%s@%s", listhists.Data(), kGridOutputStorages.Data());
1585    if (listaods.Length())  listaods  = Form("aod_archive.zip:%s@%s", listaods.Data(), kGridOutputStorages.Data());
1586
1587    if (!listhists.Length() && !listaods.Length()) {
1588       ::Fatal("AnalysisTrainPWG4Jets", "No task output !");
1589    }
1590    
1591    if (listaods.Length()) {
1592       outputArchive += " ";
1593       outputArchive += listaods;
1594    }   
1595    if (listhists.Length()) {
1596       outputArchive += " ";
1597       outputArchive += listhists;
1598    }   
1599    plugin->SetOutputArchive(outputArchive);
1600    
1601
1602 // Optionally set a name for the generated analysis macro (default MyAnalysis.C)
1603    plugin->SetAnalysisMacro(Form("%s.C", kTrainName.Data()));
1604 // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
1605    plugin->SetSplitMaxInputFileNumber(kGridFilesPerJob);
1606 // Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
1607 //   plugin->SetMaxInitFailed(5);
1608 // Optionally resubmit threshold.
1609 //   plugin->SetMasterResubmitThreshold(90);
1610 // Optionally set time to live (default 30000 sec)
1611    plugin->SetTTL(36000); // 10h...
1612 // Optionally set input format (default xml-single)
1613    plugin->SetInputFormat("xml-single");
1614 // Optionally modify the name of the generated JDL (default analysis.jdl)
1615    plugin->SetJDLName(Form("%s.jdl", kTrainName.Data()));
1616 // Optionally modify the executable name (default analysis.sh)
1617    plugin->SetExecutable(Form("%s.sh", kTrainName.Data()));
1618 // Optionally modify job price (default 1)
1619    plugin->SetPrice(1);      
1620 // Optionally modify split mode (default 'se')    
1621    plugin->SetSplitMode("se");
1622    return plugin;
1623 }
1624
1625 //______________________________________________________________________________
1626 void WriteConfig()
1627 {
1628 // Write train configuration in a file. The file name has the format:
1629 // train_[trainName]_ddMonthyyyy_time.C
1630    if (kUseDate) {
1631       gSystem->Exec("date +%d%b%Y_%Hh%M > date.tmp");
1632       ifstream fdate("date.tmp");
1633       if (!fdate.is_open()) {
1634          ::Error("AnalysisTrainPWG4Jets.C::Export","Could not generate file name");
1635          return;
1636       }
1637       const char date[64];
1638       fdate.getline(date,64);
1639       fdate.close();
1640       gSystem->Exec("rm date.tmp");
1641       kTrainName = Form("train_%s_%s", kTrainName.Data(), date);
1642    } else {
1643       kTrainName = Form("train_%s", kTrainName.Data());
1644    }   
1645    TString cdir = gSystem->WorkingDirectory();
1646    gSystem->MakeDirectory(kTrainName);
1647    gSystem->ChangeDirectory(kTrainName);
1648    ofstream out;
1649    out.open(Form("%sConfig.C",kTrainName.Data()), ios::out); 
1650    if (out.bad()) {
1651       ::Error("AnalysisTrainPWG4Jets.C::Export", "Cannot open ConfigTrain.C for writing");
1652       return;
1653    }
1654    out << "{" << endl;
1655    out << "   kTrainName      = " << "\"" << kTrainName.Data() << "\";" << endl;
1656    out << "   kProofCluster   = " << "\"" << kProofCluster.Data() << "\";" << endl;
1657    out << "   kProofUseAFPAR        = " << kProofUseAFPAR << ";" << endl;
1658    if (kProofUseAFPAR) 
1659       out << "   kProofAFversion       = " << kProofAFversion.Data() << ";" << endl;
1660    out << "   kProofDataSet   = " << "\"" << kProofDataSet.Data() << "\";" << endl;
1661    out << "   kPluginUse       = " << kPluginUse << ";" << endl;
1662    out << "   kUsePAR          = " << kUsePAR << ";" << endl;
1663    out << "   kUseCPAR         = " << kUseCPAR << ";" << endl;
1664    out << "   kPluginRootVersion    = " << "\"" << kPluginRootVersion.Data() << "\";" << endl;
1665    out << "   kPluginAliRootVersion = " << "\"" << kPluginAliRootVersion.Data() << "\";" << endl;
1666    out << "   kGridDatadir   = " << "\"" << kGridDatadir.Data() << "\";" << endl;
1667    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
1668    out << "   kGridOutdir    = " << "\"" << kGridOutdir.Data() << "\";" << endl;
1669    out << "   kGridMaxMergeFiles   = " << kGridMaxMergeFiles << ";" << endl;
1670    out << "   kGridMergeExclude    = " << "\"" << kGridMergeExclude.Data() << "\";" << endl;
1671    out << "   kGridRunsPerMaster  = " << kGridRunsPerMaster << ";" << endl;
1672    out << "   kGridFilesPerJob    = " << kGridFilesPerJob << ";" << endl;
1673    out << "   kGridRunRange[0]    = " << kGridRunRange[0] << ";" << endl;
1674    out << "   kGridRunRange[1]    = " << kGridRunRange[1] << ";" << endl;
1675    out << "   kUseDebug          = " << kUseDebug << ";" << endl;
1676    out << "   kUseMC           = " << kUseMC << ";" << endl;
1677    out << "   kUseESDTags         = " << kUseESDTags << ";" << endl;
1678    out << "   kUseKinefilter      = " << kUseKinefilter << ";" << endl;
1679    out << "   kUseTR           = " << kUseTR << ";" << endl;
1680    out << "   kUseAODTags      = " << kUseAODTags << ";" << endl;
1681    out << "   kSaveTrain       = " << "kFALSE;" << endl << endl;
1682    out << "   // Analysis modules" << endl;
1683    out << "   iAODanalysis    = " << iAODanalysis << ";" << endl;
1684    out << "   iAODhandler     = " << iAODhandler << ";" << endl;
1685    out << "   iESDfilter      = " << iESDfilter << ";" << endl;
1686    out << "   iJETAN          = " << iJETAN << ";" << endl;
1687    out << "// Configuration fot the wagons" << endl;
1688    out << "}" << endl;
1689    ::Info("AnalysisTrainPWG4Jets.C::WriteConfig", "Train configuration wrote to file %s", Form("config_%s.C", kTrainName.Data()));
1690    gSystem->ChangeDirectory(cdir);
1691 }   
1692
1693 //______________________________________________________________________________
1694 Bool_t LoadConfig(const char *filename)
1695 {
1696 // Read train configuration from file
1697    if (gSystem->AccessPathName(filename)) {
1698       ::Error("AnalysisTrainPWG4Jets.C::LoadConfig", "Config file name not found");
1699       return kFALSE;
1700    }   
1701    gROOT->ProcessLine(Form(".x %s", filename));
1702    ::Info("AnalysisTrainPWG4Jets.C::LoadConfig", "Train configuration loaded from file %s", filename);
1703    return kTRUE;
1704 }
1705
1706 Bool_t PatchJDL(){
1707   Printf(">>> Patching JDL");
1708   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1709   AliAnalysisAlien*    gridHandler = (AliAnalysisAlien*)mgr->GetGridHandler();
1710   TGridJDL *jdl = gridHandler->GetGridJDL();
1711   if(iJETAN)jdl->AddToPackages("fastjet","v2.4.0");
1712   gridHandler->WriteJDL(kFALSE);
1713   Printf("<<<  Patching JDL");
1714   return kTRUE;
1715 }
1716
1717 Bool_t PatchAnalysisMacro(){
1718   Printf(">>> Patching AnalysisMacro");
1719   gSystem->Exec(Form("mv %s.C %s.C_tmp",kTrainName.Data(),kTrainName.Data()));
1720
1721   ifstream in1; 
1722   in1.open(Form("%s.C_tmp", kTrainName.Data()));
1723   char cLine[250];
1724   TString st;
1725   while(in1.getline(cLine,250)){
1726     st += cLine;
1727     st += "\n";
1728   }
1729   Int_t index= -1;
1730   index = st.Index("gSystem->Load(\"libPhysics\");");
1731   index += strlen("gSystem->Load(\"libPhysics\");");
1732   /*
1733     TObjArray *arr;
1734     TObjString *objstr;
1735     arr = anaLibs.Tokenize(" ");
1736     TIter next(arr);
1737
1738     add += "\n\n // added by CKB \n";
1739     while ((objstr=(TObjString*)next())){
1740       if(objstr->GetString().Contains("PWG3"))continue;
1741       if(objstr->GetString().EndsWith(".so"))add += Form("gSystem->Load(\"%s\");\n",objstr->GetString().Data());
1742     }
1743     delete arr; 
1744     */
1745     //    add += Form("AliLog::SetGlobalLogLevel(%d);\n",AliLog::GetGlobalLogLevel());
1746   TString add = "";
1747
1748   if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
1749   add += "\n\n // added by CKB \n";
1750   if(kErrorIgnoreLevel>0)add += Form("gErrorIgnoreLevel = %d;\n",kErrorIgnoreLevel);
1751   add += "\n gSystem->AddIncludePath(\"./\"); \n";
1752   if(gGrid&&kPluginAliRootVersion.Length()==0){
1753     add += "\n // Dirty hack for TRD reference data \n";
1754     add += "\n gSystem->Setenv(\"ALICE_ROOT\",\"";
1755     add += Form("alien://%s/rootfiles/",gGrid->GetHomeDirectory());
1756     add += "\"); \n";
1757   }
1758   add += "// BKC \n\n";
1759   st.Insert(index,add.Data());
1760
1761   if(kUseDebug){
1762     //    st.Insert(index,"\n gROOT->ProcessLine(\".trace\"); // CKB \n");
1763   }
1764
1765   if(kUseCPAR&&kPluginAliRootVersion.Length()==0){
1766     index = st.Index("gSystem->AddIncludePath(\"-I$"); // uncommen $ALICE_ROOT include for par files
1767     if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
1768     st.Insert(index,"// CKB comment out whehn no aliroot is provided \n //");
1769   }
1770
1771   if(AliLog::GetGlobalLogLevel()==AliLog::kFatal){
1772     index = st.Index("AliLog::SetGlobal"); // ncomment setting of log level, do my own
1773     if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
1774     st.Insert(index,"AliLog::SetGlobalLogLevel(AliLog::kFatal);// CKB \n  // CKB comment out for own setting \n  //");
1775   }
1776
1777   ofstream out;
1778   out.open(Form("%s.C", kTrainName.Data()));
1779   if (out.bad()) {
1780     return kFALSE;
1781   }
1782   out << st << endl;
1783   Printf("<<< Patching AnalysisMacro");
1784
1785
1786
1787
1788
1789   Printf(">>> Patching Merge Macro");
1790   gSystem->Exec(Form("mv %s_merge.C %s_merge.C_tmp",kTrainName.Data(),kTrainName.Data()));
1791
1792   ifstream in2; 
1793   in2.open(Form("%s_merge.C_tmp", kTrainName.Data()));
1794   TString st2;
1795   while(in2.getline(cLine,250)){
1796     st2 += cLine;
1797     st2 += "\n";
1798   }
1799   index = st2.Index("gSystem->Load(\"libPhysics\");");
1800   index += strlen("gSystem->Load(\"libPhysics\");");
1801   TString add2 = "";
1802   add2 += "\n gSystem->AddIncludePath(\"./\"); \n";
1803   if(gGrid&&kPluginAliRootVersion.Length()==0){
1804     add2 += "\n // Dirty hack for TRD reference data \n";
1805     add2 += "\n gSystem->Setenv(\"ALICE_ROOT\",\"";
1806     add2 += Form("alien://%s/rootfiles/",gGrid->GetHomeDirectory());
1807     add2 += "\"); \n";
1808   }
1809   add2 += "// BKC \n\n";
1810   if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
1811   st2.Insert(index,add.Data());
1812
1813
1814   if(kUseDebug){
1815     //    st2.Insert(index,"\n gROOT->ProcessLine(\".trace\"); // CKB \n");
1816   }
1817
1818   if(kUseCPAR&&kPluginAliRootVersion.Length()==0){
1819     index = st2.Index("gSystem->AddIncludePath(\"-I$"); // uncomment $ALICE_ROOT include for par files
1820     if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
1821     st2.Insert(index,"// CKB comment out whehn no aliroot is provided \n //");
1822   }
1823
1824   // do not exclude the extra files from merign, this is done explicitly in this train script
1825   index = st2.Index("mergeExcludes +="); // uncommen $ALICE_ROOT include for par files
1826   if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
1827   st2.Insert(index,"// CKB comment out, handled explicitly by the train macro \n //");
1828
1829
1830   ofstream out2;
1831   out2.open(Form("%s_merge.C", kTrainName.Data()));
1832   if (out2.bad()) {
1833     return kFALSE;
1834   }
1835   out2 << st2 << endl;
1836   Printf("<<< Patching Merging Macro");
1837
1838
1839
1840   return kTRUE;
1841
1842 }