]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - PWGLF/SPECTRA/PiKaPr/HMPID/AnalysisTrainHMPID.C
end-of-line normalization
[u/mrichter/AliRoot.git] / PWGLF / SPECTRA / PiKaPr / HMPID / AnalysisTrainHMPID.C
index 1be6307c4f1c1aedea7389dac82766371bf5e2e5..976f7cb8aa0365fc7b160d73c292f2dcbf0db756 100644 (file)
-//===================== ANALYSIS TRAIN =========================================\r
-// To use: copy this macro to your work directory, modify the global part to match\r
-// your needs, then run root.\r
-//    root[0] .L AnalysisTrainHMPID.C\r
-// Grid full mode as below (other modes: test, offline, submit, terminate)\r
-//    root[1] AnalysisTrainHMPID("grid", "full")\r
-// CAF mode (requires root v5-23-02 + aliroot v4-16-Rev08)\r
-//    root[2] AnalysisTrainHMPID("proof")\r
-// Local mode requires AliESds.root or AliAOD.root in ./data directory\r
-//    root[3] AnalysisTrainHMPID("local")\r
-// In proof and grid modes, a token is needed and sourcing the produced environment file.\r
-//\r
-\r
-// =============================================================================\r
-// ### General Steering variables\r
-// =============================================================================\r
-//== general setup variables\r
-TString     kTrainName         = "hmpidAnalysis"; // (no blancs or special characters)\r
-TString     kJobTag            = "HMPID Tasks analysis train configured"; //\r
-Bool_t      kUsePAR            = kFALSE;  // use par files for extra libs\r
-Bool_t      kUseCPAR           = kFALSE;  // use par files for common libs\r
-Bool_t      kFillAOD           = kFALSE;  // switch of AOD filling for on the fly analysis\r
-\r
-Int_t       iAODhandler        = 1;      // Analysis produces an AOD or dAOD's\r
-Int_t       iESDfilter         = 0;      // ESD to AOD filter (barrel + muon tracks)\r
-Int_t       iPhysicsSelection  = 1;      // Physics selection task\r
-Bool_t      kUseKinefilter     = kFALSE; // use Kinematics filter\r
-Bool_t      kUseMuonfilter     = kFALSE; // use muon filter\r
-TString     kCommonOutputFileName = "HmpidOutput.root";\r
-\r
-\r
-//== general process variables\r
-\r
-// ### Other flags to steer the analysis\r
-//==============================================================================\r
-Bool_t      kSkipTerminate      = kFALSE; // Do not call Teminate\r
-Bool_t      kDebugLevel         = kTRUE; // activate debugging\r
-Int_t       kUseSysInfo         = 0; // activate debugging\r
-Bool_t      kUseMC              = kTRUE;  // use MC info\r
-Bool_t      kIsMC               = kFALSE;  // is MC info, if false it overwrites Use(AOD)MC\r
-Bool_t      kUseESDTags         = kFALSE; // use ESD tags for selection\r
-Bool_t      kUseTR              = kFALSE;  // use track references\r
-\r
-// ### Analysis modules to be included. Some may not be yet fully implemented.\r
-//==============================================================================\r
-Int_t       iHMPID             = 1;      // Basic HMPID analysis task\r
-Int_t       iJETAN             = 0;      // Jet analysis (PWG4) // 1 write standard 2 write non-standard jets\r
-Int_t       iJETANLib          = 0;\r
-Int_t       kHighPtFilterMask  = 16;     // change depending on the used AOD Filter\r
-\r
-\r
-//==============================================================================\r
-// ### PROOF Steering varibales\r
-//==============================================================================\r
-//== proof setup variables\r
-TString     kProofCluster      = "alice-caf.cern.ch";\r
-Bool_t      kProofUseAFPAR     = kTRUE;  // use AF special par file\r
-TString     kProofAFversion    = "VO_ALICE@AliRoot::v4-20-08-AN";\r
-//== proof input and output variables\r
-TString     kProofDataSet      = "/alice/sim/LHC10d2_117220";\r
-//== proof process variables\r
-Bool_t      kProofClearPackages = kFALSE;\r
-Int_t       kProofEvents = 10000;\r
-Int_t       kProofOffset = 0;\r
-\r
-//==============================================================================\r
-// ### Grid plugin Steering varibiables\r
-//==============================================================================\r
-//== grid plugin setup variables\r
-Bool_t      kPluginUse         = kTRUE;   // do not change\r
-Bool_t      kPluginUseProductionMode  = kFALSE;   // use the plugin in production mode\r
-TString     kPluginRootVersion       = "v5-30-03";  // *CHANGE ME IF MORE RECENT IN GRID*\r
-TString     kPluginAliRootVersion    = "v5-02-06-AN";  // *CHANGE ME IF MORE RECENT IN GRID*                                          \r
-Bool_t      kPluginMergeViaJDL       = kTRUE;  // merge via JDL\r
-Bool_t      kPluginFastReadOption    = kFALSE;  // use xrootd flags to reduce timeouts\r
-Bool_t      kPluginOverwriteMode     = kTRUE;  // overwrite existing collections\r
-Int_t       kPluginOutputToRunNumber = 1;     // write the output to subdirs named after run number\r
-TString kPluginExecutableCommand = "root -b -q";\r
-\r
-// == grid plugin input and output variables\r
-TString     kGridDatadir      = "/alice/data/2010/LHC10b";\r
-TString     kGridLocalRunList = "";\r
-TString     kGridWorkDir      = "LHC10b/pass3";   // Alien working directory\r
-TString     kGridOutdir       = ""; // AliEn output directory. If blank will become output_<kTrainName>\r
-TString     kGridDataSet      = ""; // sub working directory not to confuse different run xmls \r
-Int_t       kGridRunRange[2]       = {114783, 114783}; // Set the run range\r
-TString     kGridRunPattern        = "%03d"; // important for leading zeroes!!\r
-TString     kGridPassPattern       = "/ESDs/pass3";\r
-//TString     kGridPassPattern       = "ESDs/pass1"; to work with plugin->AddRunNumber\r
-TString     kGridExtraFiles        = ""; // files that will be added to the input list in the JDL...\r
-Int_t       kGridMaxMergeFiles      = 12; // Number of files merged in a chunk grid run range\r
-TString     kGridMergeExclude       = "AliAOD.root"; // Files that should not be merged\r
-TString     kGridOutputStorages      = "disk=2"; // Make replicas on the storages\r
-// == grid process variables\r
-Int_t       kGridRunsPerMaster     = 1; // Number of runs per master job\r
-Int_t       kGridFilesPerJob       = 100; // Maximum number of files per job (gives size of AOD)\r
-\r
-//==============================================================================\r
-// ### Local Steering variables\r
-//==============================================================================\r
-//== local setup variables\r
-//== local input and output variables\r
-TString     kLocalXMLDataset   = ""; // Change local xml dataset for local interactive analysis\r
-TString     kLocalDataList   = "list.txt"; // Change local xml dataset for local interactive analysis\r
-// == local process variables\r
-\r
-\r
-\r
-// Temporaries.\r
-TString anaPars = "";\r
-TString anaLibs = "";\r
-TString anaLibsExtra = "";\r
-TString anaSources = "";\r
-// Function signatures\r
-class AliAnalysisAlien;\r
-\r
-//______________________________________________________________________________\r
-void AnalysisTrainHMPID(const char *analysis_mode="local", const char *plugin_mode="",\r
-                        const char *config_file="",Int_t iOffset = 0)\r
-{\r
-// Main analysis train macro. If a configuration file is provided, all parameters\r
-// are taken from there but may be altered by CheckModuleFlags.\r
-\r
-   if (strlen(config_file) && !LoadConfig(config_file)) return;\r
-\r
-   if(iOffset)kProofOffset = iOffset;\r
-   TString smode(analysis_mode);\r
-   smode.ToUpper();\r
-   // Check compatibility of selected modules\r
-   CheckModuleFlags(smode);\r
-\r
-   printf("==================================================================\n");\r
-   printf("===========    RUNNING ANALYSIS TRAIN %s IN %s MODE   ==========\n", kTrainName.Data(),smode.Data());\r
-   printf("==================================================================\n");\r
-   printf("=  Configuring analysis train for:                               =\n");\r
-   printf("=  ESD analysis                                                  =\n");\r
-   if (iPhysicsSelection)   printf("=  Physics selection                                                    =\n");\r
-   if (iESDfilter)   printf("=  ESD filter                                                    =\n");\r
-   if (iJETAN)       printf("=  Jet analysis                                                  =\n");\r
-   printf("==================================================================\n");\r
-   printf(":: use MC truth      %d\n", (UInt_t)kUseMC);\r
-   printf(":: use KINE filter   %d\n", (UInt_t)kUseKinefilter);\r
-   printf(":: use track refs    %d\n", (UInt_t)kUseTR);\r
-   printf(":: use tags          %d\n", (UInt_t)kUseESDTags);\r
-   printf(":: use debugging     %d\n", (UInt_t)kDebugLevel);\r
-   printf(":: use PAR files     %d\n", (UInt_t)kUsePAR);\r
-   printf(":: use AliEn plugin  %d\n", (UInt_t)kPluginUse);\r
-   \r
-   //==========================================================================\r
-   // Connect to back-end system\r
-   if (!Connect(smode)) {\r
-      ::Error("AnalysisTrain", "Could not connect to %s back-end", analysis_mode);\r
-      return;\r
-   }   \r
-\r
-   // Load common libraries and set include path\r
-   if (!LoadCommonLibraries(smode)) {\r
-      ::Error("AnalysisTrain", "Could not load common libraries");\r
-      return;\r
-   }\r
-\r
-\r
-    \r
-   // Make the analysis manager and connect event handlers\r
-   AliAnalysisManager *mgr  = new AliAnalysisManager("HMPIDTrain", "HMPID train");\r
-   if (kCommonOutputFileName.Length()>0)mgr->SetCommonFileName(kCommonOutputFileName.Data());\r
-   mgr->SetNSysInfo(0);\r
-   if (!strcmp(plugin_mode, "test")) mgr->SetNSysInfo(1);\r
-   if (kUseSysInfo)mgr->SetNSysInfo(kUseSysInfo);\r
-   mgr->SetSkipTerminate(kSkipTerminate);\r
-\r
-   // Load analysis specific libraries\r
-   if (!LoadAnalysisLibraries(smode)) {\r
-      ::Error("AnalysisTrain", "Could not load analysis libraries");\r
-     return;\r
-   }   \r
-\r
-   // Create input handler (input container created automatically)\r
-   // ESD input handler\r
-   AliESDInputHandler *esdHandler = new AliESDInputHandler();\r
-   if (kUseESDTags) esdHandler->SetReadTags();\r
-   esdHandler->SetReadFriends(kFALSE);\r
-   mgr->SetInputEventHandler(esdHandler);       \r
-\r
-   // Monte Carlo handler\r
-   if (kUseMC) {\r
-      AliMCEventHandler* mcHandler = new AliMCEventHandler();\r
-      mgr->SetMCtruthEventHandler(mcHandler);\r
-      mcHandler->SetReadTR(kUseTR); \r
-   }   \r
-\r
-   // AOD output container, created automatically when setting an AOD handler\r
-   if (iAODhandler) {\r
-      // AOD output handler\r
-      AliAODHandler* aodHandler   = new AliAODHandler();\r
-      aodHandler->SetOutputFileName("AliAOD.root");\r
-      aodHandler->SetFillAODforRun(kFillAOD);\r
-      \r
-      mgr->SetOutputEventHandler(aodHandler);\r
-      AliAnalysisDataContainer *cout_aod = mgr->GetCommonOutputContainer();\r
-      cout_aod->SetSpecialOutput();\r
-   }\r
-\r
-   // Debugging if needed\r
-   if (kDebugLevel){\r
-      mgr->SetDebugLevel(3);\r
-   }\r
-   if(kUseSysInfo>0){\r
-      mgr->RegisterExtraFile("syswatch.root");\r
-      if(kGridMergeExclude.Length())kGridMergeExclude += " ";\r
-      kGridMergeExclude += "syswatch.root";\r
-   } else {\r
-      AliLog::SetGlobalLogLevel(AliLog::kError);\r
-   }\r
-\r
-   //==========================================================================\r
-   // Create the chain. In this example it is created only from ALIEN files but\r
-   // can be done to work in batch or grid mode as well.\r
-   TChain *chain = CreateChain(smode, plugin_mode);\r
-        \r
-   //==========================================================================\r
-   // Load the tasks configuration macros for all wagons. These files are supposed now to be\r
-   // in the current workdir, but in AliEn they will be in the file catalog, \r
-   // mapped from AliRoot and pecified in the jdl input list.\r
-   if(iPhysicsSelection){\r
-     gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");\r
-     AliPhysicsSelectionTask* physSelTask = AddTaskPhysicsSelection(); // last flag also adds information on  \r
-   }\r
-\r
-   if (iESDfilter) {\r
-      //  ESD filter task configuration.\r
-      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskESDFilter.C");\r
-      AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(kUseKinefilter,kUseMuonfilter);\r
-      if(kIsMC){\r
-         mgr->RegisterExtraFile("pyxsec_hists.root");\r
-         if(kGridMergeExclude.Length())kGridMergeExclude += " ";\r
-         kGridMergeExclude += "pyxsec_hists.root";\r
-      }\r
-   }   \r
-\r
-    // Jet analysis\r
-   if (iJETAN) {\r
-      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJets.C");\r
-      AliAnalysisTaskJets *taskjets = 0;\r
-      if (iJETAN&1) taskjets = AddTaskJets(kHighPtFilterMask); \r
-      if (!taskjets) ::Warning("AnalysisTrainHMPID", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");\r
-   }\r
-   \r
-    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");\r
-    AliAnalysisTaskPIDResponse  *taskPIDResponse = AddTaskPIDResponse();\r
-      \r
-\r
-   if(iHMPID){\r
-     gROOT->LoadMacro("$ALICE_ROOT/HMPID/AddTaskHMPID.C");\r
-     AliHMPIDAnalysisTask *taskHmpid = AddTaskHMPID(kUseMC);\r
-     taskHmpid->SelectCollisionCandidates();\r
-     if (!taskHmpid) ::Warning("AnalysisTrainHMPID", "AliAnalysisTaskHMPID cannot run for this train conditions - EXCLUDED");\r
-   }\r
-\r
-   if (kPluginUse) {\r
-      AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);\r
-      AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);\r
-   }\r
-\r
-   if (mgr->InitAnalysis()) {\r
-     mgr->PrintStatus();\r
-     if (!strcmp(plugin_mode,"submit") && smode=="GRID"){\r
-       TString alien_workdir = gGrid->GetHomeDirectory();\r
-       alien_workdir += kGridWorkDir.Data();\r
-       if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());\r
-       AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();\r
-       printf("=== AnalysisTrainHMPID:: Registering jdl in the work directory alien://%s/%s, should be done by the manager! ===\n",\r
-             alien_workdir.Data(),gridhandler->GetGridOutputDir());\r
-\r
-       TString dest;\r
-       dest = Form("%s/%s/%s.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());\r
-       if(AliAnalysisAlien::FileExists(dest.Data())){\r
-     //  Printf("%s exist on grid removing...",dest.Data());\r
-     //  gGrid->Rm(dest.Data());\r
-       }\r
-       TFile::Cp(Form("file:%s.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));\r
-\r
-\r
-       TString dest;\r
-       dest = Form("%s/%s/%s_merge.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());\r
-       if(AliAnalysisAlien::FileExists(dest.Data())){\r
-        //      Printf("%s exist on grid removing...",dest.Data());\r
-        //      gGrid->Rm(dest.Data());\r
-       }\r
-       TFile::Cp(Form("file:%s_merge.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));\r
-     }\r
-\r
-     AliLog::SetGlobalLogLevel(AliLog::kError);\r
-     if((kUseSysInfo>0 && smode=="LOCAL") || !strcmp(plugin_mode, "test")){\r
-       TFile *fM = TFile::Open("manager_local.root","RECREATE");\r
-       mgr->Write();\r
-       fM->Close();\r
-     }\r
-\r
-     StartAnalysis(smode, chain);\r
-       \r
-     if((kUseSysInfo>0 && smode=="LOCAL") || !strcmp(plugin_mode, "test")){\r
-       for(int i = 0;i < mgr->GetTopTasks()->GetEntries();i++){\r
-         mgr->ProfileTask(i);\r
-       }\r
-     }\r
-     if (!strcmp(plugin_mode, "offline") && smode=="GRID"){\r
-       // Offline mode path files\r
-       //      PatchJDL();\r
-       PatchAnalysisMacro();\r
-     }\r
-   }\r
-}\r
-\r
-\r
-//______________________________________________________________________________\r
-void StartAnalysis(const char *mode, TChain *chain) {\r
-\r
-   Int_t imode = -1;\r
-   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\r
-   if (!strcmp(mode, "LOCAL")) imode = 0;\r
-   if (!strcmp(mode, "PROOF")) imode = 1;\r
-   if (!strcmp(mode, "GRID"))  imode = 2;\r
-   switch (imode) {\r
-      case 0:\r
-         if (!chain) {\r
-            ::Error("AnalysisTrainHMPID.C::StartAnalysis", "Cannot create the chain");\r
-            return;\r
-         }\r
-         mgr->StartAnalysis(mode, chain);\r
-         return;\r
-      case 1:\r
-         if (!kProofDataSet.Length()) {\r
-            ::Error("AnalysisTrainHMPID.C::StartAnalysis", "kProofDataSet is empty");\r
-            return;\r
-         }\r
-         mgr->StartAnalysis(mode, kProofDataSet, kProofEvents,kProofOffset);\r
-         return;\r
-      case 2:\r
-         if (kPluginUse) {\r
-            if (!mgr->GetGridHandler()) {\r
-               ::Error("AnalysisTrainHMPID.C::StartAnalysis", "Grid plugin not initialized");\r
-               return;\r
-            }\r
-            mgr->StartAnalysis("grid");\r
-         } else {\r
-            if (!chain) {\r
-               ::Error("AnalysisTrainHMPID.C::StartAnalysis", "Cannot create the chain");\r
-               return;\r
-            }\r
-            mgr->StartAnalysis(mode, chain);\r
-         }\r
-      return;\r
-   }\r
-}\r
-\r
-//______________________________________________________________________________\r
-void CheckModuleFlags(const char *mode) {\r
-// Checks selected modules and insure compatibility\r
-   Int_t imode = -1;\r
-   if (!strcmp(mode, "LOCAL")) imode = 0;\r
-   if (!strcmp(mode, "PROOF")) imode = 1;\r
-   if (!strcmp(mode, "GRID"))  imode = 2;\r
-\r
-\r
-   if (kUseCPAR) {\r
-     kPluginAliRootVersion    = ""; // NO aliroot if we use CPAR\r
-   }\r
-\r
-   if (imode==1) {\r
-      if (!kUsePAR) {\r
-         ::Info("AnalysisTrainHMPID.C::CheckModuleFlags", "PAR files enabled due to PROOF analysis");\r
-         kUsePAR = kTRUE;\r
-      }   \r
-   }  \r
-   if (imode != 2) {\r
-      ::Info("AnalysisTrainHMPID.C::CheckModuleFlags", "AliEn plugin disabled since not in GRID mode");\r
-      kPluginUse = kFALSE; \r
-   }\r
-\r
-   if(!kIsMC){\r
-     // switch off anthin related to MC\r
-     kUseMC = 0;\r
-     kUseTR = kFALSE;\r
-   }\r
-\r
- // ESD analysis\r
-   if (!kUseMC){\r
-     kUseTR = kFALSE;\r
-     if(kUseKinefilter)::Info("AnalysisTrainHMPID.C::CheckModuleFlags", "Kine Filter disabled in analysis without MC");\r
-     kUseKinefilter = kFALSE;\r
-   }\r
-   if (iJETAN){\r
-     iESDfilter=1;\r
-   }\r
-   if (!iESDfilter){\r
-     kUseKinefilter = kFALSE;\r
-     kUseMuonfilter = kFALSE;\r
-   }\r
-\r
-   iJETANLib = iJETAN && 1;\r
-   if (iESDfilter) {iAODhandler=1;}\r
-   if (kUseKinefilter && !kUseMC) kUseKinefilter = kFALSE;\r
-   \r
-}\r
-\r
-\r
-//______________________________________________________________________________\r
-Bool_t Connect(const char *mode) {\r
-// Connect <username> to the back-end system.\r
-   Int_t imode = -1;\r
-   if (!strcmp(mode, "LOCAL")) imode = 0;\r
-   if (!strcmp(mode, "PROOF")) imode = 1;\r
-   if (!strcmp(mode, "GRID"))  imode = 2;\r
-   TString username = gSystem->Getenv("alien_API_USER");\r
-   switch (imode) {\r
-     case 0:\r
-       break;\r
-     case 1:\r
-       if  (!username.Length()) {\r
-         ::Error(Form("AnalysisTrainHMPID.C::Connect <%s>", mode), "Make sure you:\n \\r
-                        1. Have called: alien-token-init <username>\n \\r
-                        2. Have called: >source /tmp/gclient_env_$UID");\r
-         return kFALSE;\r
-       }\r
-       ::Info("AnalysisTrainHMPID.C::Connect", "Connecting user <%s> to PROOF cluster <%s>", \r
-                username.Data(), kProofCluster.Data());\r
-       gEnv->SetValue("XSec.GSI.DelegProxy", "2");\r
-       TProof::Open(Form("%s@%s", username.Data(), kProofCluster.Data()));       \r
-       if (!gProof) {\r
-         if (strcmp(gSystem->Getenv("XrdSecGSISRVNAMES"), "lxfsrd0506.cern.ch"))\r
-           ::Error(Form("AnalysisTrainHMPID.C::Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");\r
-           return kFALSE;\r
-         }\r
-       if(kProofClearPackages)gProof->ClearPackages();\r
-       break;\r
-     case 2:      \r
-       if  (!username.Length()) {\r
-         ::Error(Form("AnalysisTrainHMPID.C::Connect <%s>", mode), "Make sure you:\n \\r
-                        1. Have called: alien-token-init <username>\n \\r
-                        2. Have called: >source /tmp/gclient_env_$UID");\r
-         return kFALSE;\r
-       }\r
-       if (kPluginUse && !gSystem->Getenv("alien_CLOSE_SE")) {\r
-         ::Error(Form("AnalysisTrainHMPID.C::Connect <%s>", mode), \r
-                        "When using the AliEn plugin it is preferable to define the \\r
-                        variable alien_CLOSE_SE in your environment.");\r
-         return kFALSE;\r
-       }\r
-       ::Info("AnalysisTrainHMPID.C::Connect", "Connecting user <%s> to AliEn ...", \r
-                username.Data());\r
-       TGrid::Connect("alien://");\r
-       if (!gGrid || !gGrid->IsConnected()) return kFALSE;\r
-       break;\r
-     default:\r
-       ::Error("AnalysisTrainHMPID.C::Connect", "Unknown run mode: %s", mode);\r
-       return kFALSE;\r
-   }\r
-   ::Info("AnalysisTrainHMPID.C::Connect","Connected in %s mode", mode);\r
-   return kTRUE;\r
-}\r
-\r
-\r
-//______________________________________________________________________________\r
-Bool_t LoadCommonLibraries(const char *mode)\r
-{\r
-// Load common analysis libraries.\r
-   Int_t imode = -1;\r
-   if (!strcmp(mode, "LOCAL")) imode = 0;\r
-   if (!strcmp(mode, "PROOF")) imode = 1;\r
-   if (!strcmp(mode, "GRID"))  imode = 2;\r
-   if (!gSystem->Getenv("ALICE_ROOT")) {\r
-      ::Error("AnalysisTrainHMPID.C::LoadCommonLibraries", "Analysis train requires that analysis libraries are compiled with a local AliRoot"); \r
-      return kFALSE;\r
-   }   \r
-   Bool_t success = kTRUE;\r
-   // ROOT libraries\r
-   gSystem->Load("libTree.so");\r
-   gSystem->Load("libGeom.so");\r
-   gSystem->Load("libVMC.so");\r
-   gSystem->Load("libPhysics.so");\r
-   \r
-   // Load framework classes. Par option ignored here.\r
-   switch (imode) {\r
-      case 0:\r
-      case 2:\r
-         if (kUseCPAR) {\r
-            success &= LoadLibrary("STEERBase", mode, kTRUE);\r
-            success &= LoadLibrary("ESD", mode, kTRUE);\r
-            success &= LoadLibrary("AOD", mode, kTRUE);\r
-            success &= LoadLibrary("ANALYSIS", mode, kTRUE);\r
-            success &= LoadLibrary("ANALYSISalice", mode, kTRUE);\r
-            success &= LoadLibrary("CORRFW", mode, kTRUE);\r
-         } else {   \r
-            success &= LoadLibrary("libSTEERBase.so", mode);\r
-            success &= LoadLibrary("libESD.so", mode);\r
-            success &= LoadLibrary("libAOD.so", mode);\r
-            success &= LoadLibrary("libANALYSIS.so", mode);\r
-            success &= LoadLibrary("libANALYSISalice.so", mode);\r
-            success &= LoadLibrary("libCORRFW.so", mode);\r
-            gROOT->ProcessLine(".include $ALICE_ROOT/include");\r
-         }   \r
-         break;\r
-      case 1:\r
-         if (!kProofUseAFPAR) {\r
-            success &= LoadLibrary("STEERBase", mode);\r
-            success &= LoadLibrary("ESD", mode);\r
-            success &= LoadLibrary("AOD", mode);\r
-            success &= LoadLibrary("ANALYSIS", mode);\r
-            success &= LoadLibrary("ANALYSISalice", mode);\r
-            success &= LoadLibrary("CORRFW", mode);\r
-         } else { \r
-            success &= !gProof->EnablePackage(kProofAFversion);\r
-            success &= LoadLibrary("CORRFW", mode);\r
-         }\r
-         break;         \r
-      default:\r
-         ::Error("AnalysisTrainHMPID.C::LoadCommonLibraries", "Unknown run mode: %s", mode);\r
-         return kFALSE;\r
-   }\r
-   if (success) {\r
-      ::Info("AnalysisTrainHMPID.C::LoadCommodLibraries", "Load common libraries:    SUCCESS");\r
-      ::Info("AnalysisTrainHMPID.C::LoadCommodLibraries", "Include path for Aclic compilation:\n%s",\r
-              gSystem->GetIncludePath());\r
-   } else {           \r
-      ::Info("AnalysisTrainHMPID.C::LoadCommodLibraries", "Load common libraries:    FAILED");\r
-   }   \r
-      \r
-   return success;\r
-}\r
-\r
-\r
-//______________________________________________________________________________\r
-Bool_t LoadAnalysisLibraries(const char *mode)\r
-{\r
-// Load common analysis libraries.\r
-   Bool_t success = kTRUE;\r
-   if (iESDfilter) {\r
-      if (!LoadLibrary("PWG3base", mode, kTRUE) ||\r
-          !LoadLibrary("PWG3muon", mode, kTRUE)) return kFALSE;\r
-   }   \r
-\r
-   if(iHMPID){\r
-     if (!LoadSource(Form("%s/AliHMPIDAnalysisTask.cxx",gSystem->ExpandPathName(".")), mode, kTRUE))return kFALSE;\r
-   }\r
-\r
-   if (iJETANLib) {\r
-     if (!LoadLibrary("JETAN", mode, kTRUE)) return kFALSE;\r
-   }\r
-\r
-   ::Info("AnalysisTrainHMPID.C::LoadAnalysisLibraries", "Load other libraries:   SUCCESS");\r
-   return kTRUE;\r
-}\r
-\r
-\r
-//______________________________________________________________________________\r
-Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)\r
-{\r
-// Load a module library in a given mode. Reports success.\r
-   Int_t imode = -1;\r
-   Int_t result;\r
-   TString smodule(module);\r
-   if (!strcmp(mode, "LOCAL")) imode = 0;\r
-   if (!strcmp(mode, "PROOF")) imode = 1;\r
-   if (!strcmp(mode, "GRID"))  imode = 2;\r
-   TString mod(module);\r
-   if (!mod.Length()) {\r
-      ::Error("AnalysisTrainHMPID.C::LoadLibrary", "Empty module name");\r
-      return kFALSE;\r
-   }   \r
-   // If a library is specified, just load it\r
-   if (smodule.EndsWith(".so")) {\r
-      mod.Remove(mod.Index(".so"));\r
-      result = gSystem->Load(mod);\r
-      if (result < 0) {\r
-         ::Error("AnalysisTrainHMPID.C::LoadLibrary", "Could not load library %s", module);\r
-         return kFALSE;\r
-      }\r
-      if (rec) anaLibs += Form("%s.so ",mod.Data()); \r
-      if (rec) anaLibsExtra += Form("%s.so ",mod.Data()); \r
-      return kTRUE;\r
-   } \r
-   // Check if the library is already loaded\r
-   if (strlen(gSystem->GetLibraries(Form("%s.so", module), "", kFALSE)) > 0)\r
-      return kTRUE;    \r
-   switch (imode) {\r
-      case 0:\r
-      case 2:\r
-         if (kUsePAR) {\r
-            result = SetupPar(module);\r
-            if (rec) anaPars += Form("%s.par ", module);\r
-         } else {\r
-            result = gSystem->Load(Form("lib%s.so", module));\r
-            if (rec) anaLibs += Form("lib%s.so ", module);\r
-         }   \r
-         break;\r
-      case 1:\r
-            if(!gSystem->AccessPathName(module)){\r
-              ::Info("AnalysisTrainHMPID.C::LoadLibrary", "Removing directory %s",module);\r
-              gSystem->Exec(Form("rm -rf %s",module));\r
-         }\r
-         result = gProof->UploadPackage(module);\r
-         if (result<0) {\r
-            result = gProof->UploadPackage(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", module)));\r
-            if (result<0) {\r
-               ::Error("AnalysisTrainHMPID.C::LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);\r
-               return kFALSE;\r
-            }\r
-         }   \r
-         result = gProof->EnablePackage(module);\r
-         break;\r
-      default:\r
-         return kFALSE;\r
-   }         \r
-   if (result < 0) {\r
-      ::Error("AnalysisTrainHMPID.C::LoadLibrary", "Could not load module %s", module);\r
-      return kFALSE;\r
-   }\r
-   return kTRUE;\r
-}           \r
-\r
-//______________________________________________________________________________\r
-Bool_t LoadSource(const char *source, const char *mode, Bool_t rec=kFALSE)\r
-{\r
-// Load a module library in a given mode. Reports success.\r
-   Int_t imode = -1;\r
-   Int_t result = -1;\r
-   if (!strcmp(mode, "LOCAL")) imode = 0;\r
-   if (!strcmp(mode, "PROOF")) imode = 1;\r
-   if (!strcmp(mode, "GRID"))  imode = 2;\r
-   TString ssource(source);\r
-   TString basename = gSystem->BaseName(ssource.Data());\r
-   if (!ssource.Length()) {\r
-      ::Error("AnalysisTrainHMPID.C::LoadSource", "Empty task name");\r
-      return kFALSE;\r
-   }\r
-   // we have a source code so compile it\r
-   if (ssource.EndsWith(".cxx")) {\r
-     // need to copy it here other wise the path is also used on grid...\r
-     ssource.Remove(ssource.Index(".cxx"));\r
-     basename.Remove(basename.Index(".cxx"));\r
-     Printf("LoadSources:: Copying...  path %s{cxx,h}",ssource.Data());\r
-     gSystem->Exec(Form("cp %s.cxx . ",ssource.Data()));\r
-     gSystem->Exec(Form("cp %s.h . ",ssource.Data()));\r
-     // Path to code\r
-     // only needed for local compilation, in grid and proof mode \r
-     // the task headers are uploaded \r
-     //     path.Remove(path.Index(gSystem->BaseName(path.Data())));\r
-     // Printf("LoadSources:: Including path %s",path.Data());\r
-     //  if(path.Length()>0)gROOT->ProcessLine(Form(".include %s",path.Data()));\r
-     Printf("LoadSources:: Loading...  path %s",basename.Data());\r
-     switch (imode) {\r
-     case 0:\r
-       result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));\r
-       break;\r
-     case 1:\r
-       result = gProof->Load(Form("%s.cxx++g",basename.Data()));\r
-       break;\r
-     case 2:\r
-       result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));\r
-       if (rec){\r
-       // what we want to compile\r
-         anaSources += Form("%s.cxx ",basename.Data());\r
-       // what we need as input...\r
-         anaLibs += Form("%s.cxx %s.h ",basename.Data(),basename.Data());\r
-       }\r
-       break;\r
-     default:\r
-       return kFALSE;\r
-     }\r
-   }\r
-   if (result < 0) {\r
-      ::Error("AnalysisTrainHMPID.C::LoadSources", "Could not load source %s", source);\r
-      return kFALSE;\r
-   }\r
-   return kTRUE;\r
-}\r
-\r
-//______________________________________________________________________________\r
-TChain *CreateChain(const char *mode, const char *plugin_mode)\r
-{\r
-// Create the input chain\r
-   Int_t imode = -1;\r
-   if (!strcmp(mode, "LOCAL")) imode = 0;\r
-   if (!strcmp(mode, "PROOF")) imode = 1;\r
-   if (!strcmp(mode, "GRID"))  imode = 2;\r
-   TChain *chain = NULL;\r
-   // Local chain\r
-   switch (imode) {\r
-      case 0:\r
-            if (!kLocalXMLDataset.Length()) {\r
-              // Local ESD\r
-              chain = new TChain("esdTree");\r
-              TString line;\r
-              ifstream in;\r
-              in.open(kLocalDataList.Data());\r
-              while (in.good()) {\r
-                in >> line;\r
-                if (line.Length() == 0) continue;\r
-                cout << " line = " << line << endl;\r
-                chain->Add(line.Data());\r
-              }       \r
-            } else {\r
-              // Interactive ESD\r
-           chain = CreateChainSingle(kLocalXMLDataset, "esdTree");\r
-            }   \r
-         break;\r
-      case 1:\r
-         break;\r
-      case 2:\r
-         if (kPluginUse) {\r
-            AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);\r
-            AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);\r
-         } else {\r
-            TString treeName = "esdTree";\r
-            chain = CreateChainSingle("wn.xml", treeName);\r
-         }\r
-         break;      \r
-      default:   \r
-   }\r
-   if (chain && chain->GetNtrees()) return chain;\r
-   return NULL;\r
-}   \r
-\r
-//______________________________________________________________________________\r
-TChain* CreateChainSingle(const char* xmlfile, const char *treeName)\r
-{\r
-   printf("*******************************\n");\r
-   printf("*** Getting the ESD Chain   ***\n");\r
-   printf("*******************************\n");\r
-   TAlienCollection * myCollection  = TAlienCollection::Open(xmlfile);\r
-\r
-   if (!myCollection) {\r
-      ::Error("AnalysisTrainHMPID.C::CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;\r
-      return NULL ;\r
-   }\r
-\r
-   TChain* chain = new TChain(treeName);\r
-   myCollection->Reset() ;\r
-   while ( myCollection->Next() ) chain->Add(myCollection->GetTURL("")) ;\r
-   chain->ls();\r
-   return chain;\r
-}\r
-\r
-//______________________________________________________________________________\r
-Int_t SetupPar(char* pararchivename)\r
-{\r
-   if (!pararchivename || !strlen(pararchivename)) return -1;\r
-   char processline[1024];\r
-   if (gSystem->AccessPathName(Form("%s.par", pararchivename))) {\r
-      if (!gSystem->AccessPathName(Form("%s/%s.par", gSystem->Getenv("ALICE_ROOT"),pararchivename))) {\r
-         ::Info("AnalysisTrainHMPID.C::SetupPar", "Getting %s.par from $ALICE_ROOT", pararchivename);\r
-         TFile::Cp(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", pararchivename)), \r
-                   Form("%s.par",pararchivename));\r
-      } else {\r
-         ::Error("AnalysisTrainHMPID.C::SetupPar", "Cannot find %s.par", pararchivename);\r
-         return -1;\r
-      }   \r
-   }\r
-   gSystem->Exec(Form("tar xvzf %s.par", pararchivename));\r
-\r
-   TString ocwd = gSystem->WorkingDirectory();\r
-   if (!gSystem->ChangeDirectory(pararchivename)) return -1;\r
-       \r
-   // check for BUILD.sh and execute\r
-   if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {\r
-      printf("*******************************\n");\r
-      printf("*** Building PAR archive    ***\n");\r
-      printf("*******************************\n");         \r
-      if (gSystem->Exec("PROOF-INF/BUILD.sh")) {\r
-         Error("runProcess","Cannot Build the PAR Archive! - Abort!");\r
-         return -1;\r
-      }\r
-   }\r
-\r
-       // check for SETUP.C and execute\r
-       if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {\r
-           printf("*******************************\n");\r
-           printf("*** Setup PAR archive       ***\n");\r
-           printf("*******************************\n");\r
-           gROOT->Macro("PROOF-INF/SETUP.C");\r
-       }       \r
-       if (!gSystem->ChangeDirectory(ocwd.Data())) return -1;\r
-   return 0;\r
-}\r
-\r
-//______________________________________________________________________________\r
-AliAnalysisAlien* CreateAlienHandler(const char *plugin_mode)\r
-{\r
-// Check if user has a valid token, otherwise make one. This has limitations.\r
-// One can always follow the standard procedure of calling alien-token-init then\r
-//   source /tmp/gclient_env_$UID in the current shell.\r
-   if (!AliAnalysisGrid::CreateToken()) return NULL;\r
-   AliAnalysisAlien *plugin = new AliAnalysisAlien();\r
-// Set the run mode (can be "full", "test", "offline", "submit" or "terminate")\r
-   plugin->SetRunMode(plugin_mode);\r
-   if (kPluginUseProductionMode) plugin->SetProductionMode();\r
-   plugin->SetJobTag(kJobTag);\r
-   plugin->SetNtestFiles(1);\r
-//   plugin->SetPreferedSE("ALICE::NIHAM::File");\r
-// Set versions of used packages\r
-   plugin->SetAPIVersion("V1.1x");\r
-   plugin->SetROOTVersion(kPluginRootVersion);\r
-   plugin->SetAliROOTVersion(kPluginAliRootVersion);\r
-\r
-// Declare input data to be processed.\r
-// Method 1: Create automatically XML collections using alien 'find' command.\r
-// Define production directory LFN\r
-   plugin->SetGridDataDir(kGridDatadir.Data());\r
-// Set data search pattern\r
-   plugin->SetDataPattern(Form(" %s/*/*ESDs.root",kGridPassPattern.Data()));\r
-// ...then add run numbers to be considered\r
-   plugin->SetRunPrefix("000");\r
-   plugin->SetRunRange(kGridRunRange[0], kGridRunRange[1]);\r
-\r
-   if(kGridLocalRunList.Length()>0){\r
-     ifstream in1;\r
-     in1.open(kGridLocalRunList.Data());\r
-     int iRun;\r
-     // just use run numbers, negatives will be excluded\r
-     while(in1>>iRun){\r
-       if(iRun>0){\r
-       Printf("AnalysisTrainHMPID Adding run number from File %s", Form(kGridRunPattern.Data(),iRun));\r
-       plugin->AddRunNumber(Form(kGridRunPattern.Data(),iRun));\r
-       } else{\r
-         Printf("AnalysisTrainHMPID Skipping run number from File %d", iRun);\r
-       }\r
-     }\r
-   }\r
-\r
-// Method 2: Declare existing data files (raw collections, xml collections, root file)\r
-// If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())\r
-// XML collections added via this method can be combined with the first method if\r
-// the content is compatible (using or not tags)\r
-//   plugin->AddDataFile("137431.xml");\r
-//   plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");\r
-// Define alien work directory where all files will be copied. Relative to alien $HOME.\r
-   TString alien_workdir = "";\r
-\r
-   alien_workdir += kGridWorkDir.Data();\r
-   if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());\r
-   plugin->SetGridWorkingDir(alien_workdir.Data());\r
-\r
-   // Declare alien output directory. Relative to working directory.\r
-   if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());\r
-   plugin->SetGridOutputDir(kGridOutdir);\r
-\r
-   // set extra libs before par file compilation\r
-   anaLibs += kGridExtraFiles;\r
-   anaLibs  = anaLibs.Strip();   \r
-   Printf("anaLibs %s",anaLibs.Data());\r
-   Printf("anaLibsExtra %s",anaLibsExtra.Data());\r
-\r
-   if (anaLibs.Length())          plugin->SetAdditionalLibs(anaLibs.Data());\r
-   if (anaLibsExtra.Length())     plugin->SetAdditionalRootLibs(anaLibsExtra.Data());\r
-\r
-   TString ana_sources = "";\r
-   TString ana_add = "";\r
-   if (kUsePAR && anaPars.Length()) {\r
-      printf("%s\n", anaPars.Data());\r
-      TObjArray *arr;\r
-      TObjString *objstr;\r
-      arr = anaPars.Tokenize(" ");\r
-      TIter next(arr);\r
-      while ((objstr=(TObjString*)next())) plugin->EnablePackage(objstr->GetString());\r
-      delete arr;\r
-   } \r
-   \r
-// Declare the analysis source files names separated by blancs. To be compiled runtime\r
-// using ACLiC on the worker nodes.\r
-   ana_sources = anaSources.Strip();\r
-// Declare all libraries (other than the default ones for the framework. These will be\r
-// loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.\r
-\r
-   if (ana_sources.Length()) plugin->SetAnalysisSource(ana_sources);\r
-   plugin->SetExecutableCommand(kPluginExecutableCommand.Data());\r
-   // Declare the output file names separated by blancs.\r
-   // (can be like: file.root or file.root@ALICE::Niham::File)\r
-   plugin->SetUseSubmitPolicy(kFALSE);\r
-   plugin->SetMergeExcludes(kGridMergeExclude);\r
-   plugin->SetMaxMergeFiles(kGridMaxMergeFiles);\r
-   plugin->SetNrunsPerMaster(kGridRunsPerMaster);\r
-   plugin->SetMergeViaJDL(kPluginMergeViaJDL);\r
-   // Use fastread option\r
-   plugin->SetFastReadOption(kPluginFastReadOption);\r
-   // UseOverwrite mode\r
-   plugin->SetOverwriteMode(kPluginOverwriteMode);\r
-   // Optionally define the files to be archived.\r
-   //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:AliAOD.root,AOD.tag.root@ALICE::NIHAM::File");\r
-   plugin->SetOutputToRunNo(kPluginOutputToRunNumber);     // write the output to subdirs named after run number\r
-//   plugin->SetDefaultOutputs(kFALSE);\r
-\r
-   // Put default output files to archive\r
-   TString listhists = "";\r
-   TString listaods  = "";\r
-   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\r
-   TIter next(mgr->GetOutputs());\r
-   AliAnalysisDataContainer *output;\r
-   while ((output=(AliAnalysisDataContainer*)next())) {\r
-      const char *filename = output->GetFileName();\r
-      if (!(strcmp(filename, "default"))) {\r
-         if (!mgr->GetOutputEventHandler()) continue;\r
-         filename = mgr->GetOutputEventHandler()->GetOutputFileName();\r
-         if (listaods.Length()) listaods += " ";\r
-         listaods += filename;\r
-      } else {\r
-         if(!listhists.Contains(filename)){\r
-            if (listhists.Length()) listhists += " ";\r
-            listhists += filename;\r
-         }\r
-      }\r
-   }\r
-\r
-   if (mgr->GetExtraFiles().Length()) {\r
-     if (listaods.Length()) listaods += " ";\r
-     listaods += mgr->GetExtraFiles();\r
-   }\r
-\r
-   TString outputArchive;\r
-   outputArchive = Form("log_archive.zip:std*r@%s",kGridOutputStorages.Data());\r
-   listaods.ReplaceAll(" ", ",");\r
-   listhists.ReplaceAll(" ", ",");\r
-   if (listhists.Length()) listhists = Form("hist_archive.zip:%s@%s", listhists.Data(), kGridOutputStorages.Data());\r
-   if (listaods.Length())  listaods  = Form("aod_archive.zip:%s@%s", listaods.Data(), kGridOutputStorages.Data());\r
-\r
-   if (!listhists.Length() && !listaods.Length()) {\r
-      ::Fatal("AnalysisTrainHMPID", "No task output !");\r
-   }\r
-\r
-   if (listaods.Length()) {\r
-      outputArchive += " ";\r
-      outputArchive += listaods;\r
-   }\r
-   if (listhists.Length()) {\r
-      outputArchive += " ";\r
-      outputArchive += listhists;\r
-   }\r
-//   plugin->SetOutputArchive(outputArchive);\r
-\r
-// Optionally set a name for the generated analysis macro (default MyAnalysis.C)\r
-   plugin->SetAnalysisMacro(Form("%s.C", kTrainName.Data()));\r
-// Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)\r
-   plugin->SetSplitMaxInputFileNumber(kGridFilesPerJob);\r
-// Optionally set number of failed jobs that will trigger killing waiting sub-jobs.\r
-//   plugin->SetMaxInitFailed(5);\r
-// Optionally resubmit threshold.\r
-//   plugin->SetMasterResubmitThreshold(90);\r
-// Optionally set time to live (default 30000 sec)\r
-   plugin->SetTTL(30000);\r
-// Optionally set input format (default xml-single)\r
-   plugin->SetInputFormat("xml-single");\r
-// Optionally modify the name of the generated JDL (default analysis.jdl)\r
-   plugin->SetJDLName(Form("%s.jdl", kTrainName.Data()));\r
-// Optionally modify the executable name (default analysis.sh)\r
-   plugin->SetExecutable(Form("%s.sh", kTrainName.Data()));\r
-// Optionally modify job price (default 1)\r
-   plugin->SetPrice(1);      \r
-// Optionally modify split mode (default 'se')    \r
-   plugin->SetSplitMode("se");\r
-   plugin->SetCheckCopy(kFALSE);\r
-   return plugin;\r
-}\r
-\r
-//______________________________________________________________________________\r
-Bool_t LoadConfig(const char *filename)\r
-{\r
-// Read train configuration from file\r
-   if (gSystem->AccessPathName(filename)) {\r
-      ::Error("AnalysisTrainHMPID.C::LoadConfig", "Config file name not found");\r
-      return kFALSE;\r
-   }   \r
-   gROOT->ProcessLine(Form(".x %s", filename));\r
-   ::Info("AnalysisTrainHMPID.C::LoadConfig", "Train configuration loaded from file %s", filename);\r
-   return kTRUE;\r
-}\r
-\r
-//______________________________________________________________________________\r
-Bool_t PatchJDL(){\r
-  Printf(">>> Patching JDL");\r
-  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\r
-  AliAnalysisAlien*    gridHandler = (AliAnalysisAlien*)mgr->GetGridHandler();\r
-  TGridJDL *jdl = gridHandler->GetGridJDL();\r
-  if(iJETAN)jdl->AddToPackages("fastjet","v2.4.0");\r
-  gridHandler->WriteJDL(kFALSE);\r
-  Printf("<<<  Patching JDL");\r
-  return kTRUE;\r
-}\r
-\r
-//______________________________________________________________________________\r
-Bool_t PatchAnalysisMacro(){\r
-  Printf(">>> Patching AnalysisMacro");\r
-  gSystem->Exec(Form("mv %s.C %s.C_tmp",kTrainName.Data(),kTrainName.Data()));\r
-\r
-  ifstream in1; \r
-  in1.open(Form("%s.C_tmp", kTrainName.Data()));\r
-  char cLine[250];\r
-  TString st;\r
-  while(in1.getline(cLine,250)){\r
-    st += cLine;\r
-    st += "\n";\r
-  }\r
-  Int_t index= -1;\r
-  index = st.Index("gSystem->Load(\"libPhysics\");");\r
-  index += strlen("gSystem->Load(\"libPhysics\");");\r
-  /*\r
-    TObjArray *arr;\r
-    TObjString *objstr;\r
-    arr = anaLibs.Tokenize(" ");\r
-    TIter next(arr);\r
-\r
-    add += "\n\n // added by CKB \n";\r
-    while ((objstr=(TObjString*)next())){\r
-      if(objstr->GetString().Contains("PWG3"))continue;\r
-      if(objstr->GetString().EndsWith(".so"))add += Form("gSystem->Load(\"%s\");\n",objstr->GetString().Data());\r
-    }\r
-    delete arr; \r
-    */\r
-    //    add += Form("AliLog::SetGlobalLogLevel(%d);\n",AliLog::GetGlobalLogLevel());\r
-  TString add = "";\r
-\r
-  if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);\r
-  add += "\n\n // added by CKB \n";\r
-  add += "\n gSystem->AddIncludePath(\"./\"); \n";\r
-  if(gGrid && kPluginAliRootVersion.Length()==0){\r
-    add += "\n // Dirty hack for TRD reference data \n";\r
-    add += "\n gSystem->Setenv(\"ALICE_ROOT\",\"";\r
-    add += Form("alien://%s/rootfiles/",gGrid->GetHomeDirectory());\r
-    add += "\"); \n";\r
-  }\r
-  add += "// BKC \n\n";\r
-  st.Insert(index,add.Data());\r
-\r
-  if(kUseCPAR && kPluginAliRootVersion.Length()==0){\r
-    index = st.Index("gSystem->AddIncludePath(\"-I$"); // uncommen $ALICE_ROOT include for par files\r
-    if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);\r
-    st.Insert(index,"// CKB comment out whehn no aliroot is provided \n //");\r
-  }\r
-\r
-  ofstream out;\r
-  out.open(Form("%s.C", kTrainName.Data()));\r
-  if (out.bad()) {\r
-    return kFALSE;\r
-  }\r
-  out << st << endl;\r
-  Printf("<<< Patching AnalysisMacro");\r
-\r
-  Printf(">>> Patching Merge Macro");\r
-  gSystem->Exec(Form("mv %s_merge.C %s_merge.C_tmp",kTrainName.Data(),kTrainName.Data()));\r
-\r
-  ifstream in2; \r
-  in2.open(Form("%s_merge.C_tmp", kTrainName.Data()));\r
-  TString st2;\r
-  while(in2.getline(cLine,250)){\r
-    st2 += cLine;\r
-    st2 += "\n";\r
-  }\r
-  index = st2.Index("gSystem->Load(\"libPhysics\");");\r
-  index += strlen("gSystem->Load(\"libPhysics\");");\r
-  TString add2 = "";\r
-  add2 += "\n gSystem->AddIncludePath(\"./\"); \n";\r
-  if(gGrid&&kPluginAliRootVersion.Length()==0){\r
-    add2 += "\n // Dirty hack for TRD reference data \n";\r
-    add2 += "\n gSystem->Setenv(\"ALICE_ROOT\",\"";\r
-    add2 += Form("alien://%s/rootfiles/",gGrid->GetHomeDirectory());\r
-    add2 += "\"); \n";\r
-  }\r
-  add2 += "// BKC \n\n";\r
-  if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);\r
-  st2.Insert(index,add.Data());\r
-\r
-  if(kUseCPAR&&kPluginAliRootVersion.Length()==0){\r
-    index = st2.Index("gSystem->AddIncludePath(\"-I$"); // uncommen $ALICE_ROOT include for par files\r
-    if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);\r
-    st2.Insert(index,"// CKB comment out whehn no aliroot is provided \n //");\r
-  }\r
-\r
-  // do not exclude the extra files from merign, this is done explicitly in this train script\r
-  index = st2.Index("mergeExcludes +="); // uncommen $ALICE_ROOT include for par files\r
-  if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);\r
-  st2.Insert(index,"// CKB comment out, handled explicitly by the train macro \n //");\r
-\r
-\r
-  ofstream out2;\r
-  out2.open(Form("%s_merge.C", kTrainName.Data()));\r
-  if (out2.bad()) {\r
-    return kFALSE;\r
-  }\r
-  out2 << st2 << endl;\r
-  Printf("<<< Patching Merging Macro");\r
-\r
-\r
-  return kTRUE;\r
-\r
-}\r
+//===================== ANALYSIS TRAIN =========================================
+// To use: copy this macro to your work directory, modify the global part to match
+// your needs, then run root.
+//    root[0] .L AnalysisTrainHMPID.C
+// Grid full mode as below (other modes: test, offline, submit, terminate)
+//    root[1] AnalysisTrainHMPID("grid", "full")
+// CAF mode (requires root v5-23-02 + aliroot v4-16-Rev08)
+//    root[2] AnalysisTrainHMPID("proof")
+// Local mode requires AliESds.root or AliAOD.root in ./data directory
+//    root[3] AnalysisTrainHMPID("local")
+// In proof and grid modes, a token is needed and sourcing the produced environment file.
+//
+
+// =============================================================================
+// ### General Steering variables
+// =============================================================================
+//== general setup variables
+TString     kTrainName         = "hmpidAnalysis"; // (no blancs or special characters)
+TString     kJobTag            = "HMPID Tasks analysis train configured"; //
+Bool_t      kUsePAR            = kFALSE;  // use par files for extra libs
+Bool_t      kUseCPAR           = kFALSE;  // use par files for common libs
+Bool_t      kFillAOD           = kFALSE;  // switch of AOD filling for on the fly analysis
+
+Int_t       iAODhandler        = 1;      // Analysis produces an AOD or dAOD's
+Int_t       iESDfilter         = 0;      // ESD to AOD filter (barrel + muon tracks)
+Int_t       iPhysicsSelection  = 1;      // Physics selection task
+Bool_t      kUseKinefilter     = kFALSE; // use Kinematics filter
+Bool_t      kUseMuonfilter     = kFALSE; // use muon filter
+TString     kCommonOutputFileName = "HmpidOutput.root";
+
+
+//== general process variables
+
+// ### Other flags to steer the analysis
+//==============================================================================
+Bool_t      kSkipTerminate      = kFALSE; // Do not call Teminate
+Bool_t      kDebugLevel         = kTRUE; // activate debugging
+Int_t       kUseSysInfo         = 0; // activate debugging
+Bool_t      kUseMC              = kTRUE;  // use MC info
+Bool_t      kIsMC               = kFALSE;  // is MC info, if false it overwrites Use(AOD)MC
+Bool_t      kUseESDTags         = kFALSE; // use ESD tags for selection
+Bool_t      kUseTR              = kFALSE;  // use track references
+
+// ### Analysis modules to be included. Some may not be yet fully implemented.
+//==============================================================================
+Int_t       iHMPID             = 1;      // Basic HMPID analysis task
+Int_t       iJETAN             = 0;      // Jet analysis (PWG4) // 1 write standard 2 write non-standard jets
+Int_t       iJETANLib          = 0;
+Int_t       kHighPtFilterMask  = 16;     // change depending on the used AOD Filter
+
+
+//==============================================================================
+// ### PROOF Steering varibales
+//==============================================================================
+//== proof setup variables
+TString     kProofCluster      = "alice-caf.cern.ch";
+Bool_t      kProofUseAFPAR     = kTRUE;  // use AF special par file
+TString     kProofAFversion    = "VO_ALICE@AliRoot::v4-20-08-AN";
+//== proof input and output variables
+TString     kProofDataSet      = "/alice/sim/LHC10d2_117220";
+//== proof process variables
+Bool_t      kProofClearPackages = kFALSE;
+Int_t       kProofEvents = 10000;
+Int_t       kProofOffset = 0;
+
+//==============================================================================
+// ### Grid plugin Steering varibiables
+//==============================================================================
+//== grid plugin setup variables
+Bool_t      kPluginUse         = kTRUE;   // do not change
+Bool_t      kPluginUseProductionMode  = kFALSE;   // use the plugin in production mode
+TString     kPluginRootVersion       = "v5-30-03";  // *CHANGE ME IF MORE RECENT IN GRID*
+TString     kPluginAliRootVersion    = "v5-02-06-AN";  // *CHANGE ME IF MORE RECENT IN GRID*                                          
+Bool_t      kPluginMergeViaJDL       = kTRUE;  // merge via JDL
+Bool_t      kPluginFastReadOption    = kFALSE;  // use xrootd flags to reduce timeouts
+Bool_t      kPluginOverwriteMode     = kTRUE;  // overwrite existing collections
+Int_t       kPluginOutputToRunNumber = 1;     // write the output to subdirs named after run number
+TString kPluginExecutableCommand = "root -b -q";
+
+// == grid plugin input and output variables
+TString     kGridDatadir      = "/alice/data/2010/LHC10b";
+TString     kGridLocalRunList = "";
+TString     kGridWorkDir      = "LHC10b/pass3";   // Alien working directory
+TString     kGridOutdir       = ""; // AliEn output directory. If blank will become output_<kTrainName>
+TString     kGridDataSet      = ""; // sub working directory not to confuse different run xmls 
+Int_t       kGridRunRange[2]       = {114783, 114783}; // Set the run range
+TString     kGridRunPattern        = "%03d"; // important for leading zeroes!!
+TString     kGridPassPattern       = "/ESDs/pass3";
+//TString     kGridPassPattern       = "ESDs/pass1"; to work with plugin->AddRunNumber
+TString     kGridExtraFiles        = ""; // files that will be added to the input list in the JDL...
+Int_t       kGridMaxMergeFiles      = 12; // Number of files merged in a chunk grid run range
+TString     kGridMergeExclude       = "AliAOD.root"; // Files that should not be merged
+TString     kGridOutputStorages      = "disk=2"; // Make replicas on the storages
+// == grid process variables
+Int_t       kGridRunsPerMaster     = 1; // Number of runs per master job
+Int_t       kGridFilesPerJob       = 100; // Maximum number of files per job (gives size of AOD)
+
+//==============================================================================
+// ### Local Steering variables
+//==============================================================================
+//== local setup variables
+//== local input and output variables
+TString     kLocalXMLDataset   = ""; // Change local xml dataset for local interactive analysis
+TString     kLocalDataList   = "list.txt"; // Change local xml dataset for local interactive analysis
+// == local process variables
+
+
+
+// Temporaries.
+TString anaPars = "";
+TString anaLibs = "";
+TString anaLibsExtra = "";
+TString anaSources = "";
+// Function signatures
+class AliAnalysisAlien;
+
+//______________________________________________________________________________
+void AnalysisTrainHMPID(const char *analysis_mode="local", const char *plugin_mode="",
+                        const char *config_file="",Int_t iOffset = 0)
+{
+// Main analysis train macro. If a configuration file is provided, all parameters
+// are taken from there but may be altered by CheckModuleFlags.
+
+   if (strlen(config_file) && !LoadConfig(config_file)) return;
+
+   if(iOffset)kProofOffset = iOffset;
+   TString smode(analysis_mode);
+   smode.ToUpper();
+   // Check compatibility of selected modules
+   CheckModuleFlags(smode);
+
+   printf("==================================================================\n");
+   printf("===========    RUNNING ANALYSIS TRAIN %s IN %s MODE   ==========\n", kTrainName.Data(),smode.Data());
+   printf("==================================================================\n");
+   printf("=  Configuring analysis train for:                               =\n");
+   printf("=  ESD analysis                                                  =\n");
+   if (iPhysicsSelection)   printf("=  Physics selection                                                    =\n");
+   if (iESDfilter)   printf("=  ESD filter                                                    =\n");
+   if (iJETAN)       printf("=  Jet analysis                                                  =\n");
+   printf("==================================================================\n");
+   printf(":: use MC truth      %d\n", (UInt_t)kUseMC);
+   printf(":: use KINE filter   %d\n", (UInt_t)kUseKinefilter);
+   printf(":: use track refs    %d\n", (UInt_t)kUseTR);
+   printf(":: use tags          %d\n", (UInt_t)kUseESDTags);
+   printf(":: use debugging     %d\n", (UInt_t)kDebugLevel);
+   printf(":: use PAR files     %d\n", (UInt_t)kUsePAR);
+   printf(":: use AliEn plugin  %d\n", (UInt_t)kPluginUse);
+   
+   //==========================================================================
+   // Connect to back-end system
+   if (!Connect(smode)) {
+      ::Error("AnalysisTrain", "Could not connect to %s back-end", analysis_mode);
+      return;
+   }   
+
+   // Load common libraries and set include path
+   if (!LoadCommonLibraries(smode)) {
+      ::Error("AnalysisTrain", "Could not load common libraries");
+      return;
+   }
+
+
+    
+   // Make the analysis manager and connect event handlers
+   AliAnalysisManager *mgr  = new AliAnalysisManager("HMPIDTrain", "HMPID train");
+   if (kCommonOutputFileName.Length()>0)mgr->SetCommonFileName(kCommonOutputFileName.Data());
+   mgr->SetNSysInfo(0);
+   if (!strcmp(plugin_mode, "test")) mgr->SetNSysInfo(1);
+   if (kUseSysInfo)mgr->SetNSysInfo(kUseSysInfo);
+   mgr->SetSkipTerminate(kSkipTerminate);
+
+   // Load analysis specific libraries
+   if (!LoadAnalysisLibraries(smode)) {
+      ::Error("AnalysisTrain", "Could not load analysis libraries");
+     return;
+   }   
+
+   // Create input handler (input container created automatically)
+   // ESD input handler
+   AliESDInputHandler *esdHandler = new AliESDInputHandler();
+   if (kUseESDTags) esdHandler->SetReadTags();
+   esdHandler->SetReadFriends(kFALSE);
+   mgr->SetInputEventHandler(esdHandler);       
+
+   // Monte Carlo handler
+   if (kUseMC) {
+      AliMCEventHandler* mcHandler = new AliMCEventHandler();
+      mgr->SetMCtruthEventHandler(mcHandler);
+      mcHandler->SetReadTR(kUseTR); 
+   }   
+
+   // AOD output container, created automatically when setting an AOD handler
+   if (iAODhandler) {
+      // AOD output handler
+      AliAODHandler* aodHandler   = new AliAODHandler();
+      aodHandler->SetOutputFileName("AliAOD.root");
+      aodHandler->SetFillAODforRun(kFillAOD);
+      
+      mgr->SetOutputEventHandler(aodHandler);
+      AliAnalysisDataContainer *cout_aod = mgr->GetCommonOutputContainer();
+      cout_aod->SetSpecialOutput();
+   }
+
+   // Debugging if needed
+   if (kDebugLevel){
+      mgr->SetDebugLevel(3);
+   }
+   if(kUseSysInfo>0){
+      mgr->RegisterExtraFile("syswatch.root");
+      if(kGridMergeExclude.Length())kGridMergeExclude += " ";
+      kGridMergeExclude += "syswatch.root";
+   } else {
+      AliLog::SetGlobalLogLevel(AliLog::kError);
+   }
+
+   //==========================================================================
+   // Create the chain. In this example it is created only from ALIEN files but
+   // can be done to work in batch or grid mode as well.
+   TChain *chain = CreateChain(smode, plugin_mode);
+        
+   //==========================================================================
+   // Load the tasks configuration macros for all wagons. These files are supposed now to be
+   // in the current workdir, but in AliEn they will be in the file catalog, 
+   // mapped from AliRoot and pecified in the jdl input list.
+   if(iPhysicsSelection){
+     gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
+     AliPhysicsSelectionTask* physSelTask = AddTaskPhysicsSelection(); // last flag also adds information on  
+   }
+
+   if (iESDfilter) {
+      //  ESD filter task configuration.
+      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskESDFilter.C");
+      AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(kUseKinefilter,kUseMuonfilter);
+      if(kIsMC){
+         mgr->RegisterExtraFile("pyxsec_hists.root");
+         if(kGridMergeExclude.Length())kGridMergeExclude += " ";
+         kGridMergeExclude += "pyxsec_hists.root";
+      }
+   }   
+
+    // Jet analysis
+   if (iJETAN) {
+      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJets.C");
+      AliAnalysisTaskJets *taskjets = 0;
+      if (iJETAN&1) taskjets = AddTaskJets(kHighPtFilterMask); 
+      if (!taskjets) ::Warning("AnalysisTrainHMPID", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
+   }
+   
+    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
+    AliAnalysisTaskPIDResponse  *taskPIDResponse = AddTaskPIDResponse();
+      
+
+   if(iHMPID){
+     gROOT->LoadMacro("$ALICE_ROOT/HMPID/AddTaskHMPID.C");
+     AliHMPIDAnalysisTask *taskHmpid = AddTaskHMPID(kUseMC);
+     taskHmpid->SelectCollisionCandidates();
+     if (!taskHmpid) ::Warning("AnalysisTrainHMPID", "AliAnalysisTaskHMPID cannot run for this train conditions - EXCLUDED");
+   }
+
+   if (kPluginUse) {
+      AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
+      AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
+   }
+
+   if (mgr->InitAnalysis()) {
+     mgr->PrintStatus();
+     if (!strcmp(plugin_mode,"submit") && smode=="GRID"){
+       TString alien_workdir = gGrid->GetHomeDirectory();
+       alien_workdir += kGridWorkDir.Data();
+       if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());
+       AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
+       printf("=== AnalysisTrainHMPID:: Registering jdl in the work directory alien://%s/%s, should be done by the manager! ===\n",
+             alien_workdir.Data(),gridhandler->GetGridOutputDir());
+
+       TString dest;
+       dest = Form("%s/%s/%s.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
+       if(AliAnalysisAlien::FileExists(dest.Data())){
+     //  Printf("%s exist on grid removing...",dest.Data());
+     //  gGrid->Rm(dest.Data());
+       }
+       TFile::Cp(Form("file:%s.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
+
+
+       TString dest;
+       dest = Form("%s/%s/%s_merge.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
+       if(AliAnalysisAlien::FileExists(dest.Data())){
+        //      Printf("%s exist on grid removing...",dest.Data());
+        //      gGrid->Rm(dest.Data());
+       }
+       TFile::Cp(Form("file:%s_merge.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
+     }
+
+     AliLog::SetGlobalLogLevel(AliLog::kError);
+     if((kUseSysInfo>0 && smode=="LOCAL") || !strcmp(plugin_mode, "test")){
+       TFile *fM = TFile::Open("manager_local.root","RECREATE");
+       mgr->Write();
+       fM->Close();
+     }
+
+     StartAnalysis(smode, chain);
+       
+     if((kUseSysInfo>0 && smode=="LOCAL") || !strcmp(plugin_mode, "test")){
+       for(int i = 0;i < mgr->GetTopTasks()->GetEntries();i++){
+         mgr->ProfileTask(i);
+       }
+     }
+     if (!strcmp(plugin_mode, "offline") && smode=="GRID"){
+       // Offline mode path files
+       //      PatchJDL();
+       PatchAnalysisMacro();
+     }
+   }
+}
+
+
+//______________________________________________________________________________
+void StartAnalysis(const char *mode, TChain *chain) {
+
+   Int_t imode = -1;
+   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
+   if (!strcmp(mode, "LOCAL")) imode = 0;
+   if (!strcmp(mode, "PROOF")) imode = 1;
+   if (!strcmp(mode, "GRID"))  imode = 2;
+   switch (imode) {
+      case 0:
+         if (!chain) {
+            ::Error("AnalysisTrainHMPID.C::StartAnalysis", "Cannot create the chain");
+            return;
+         }
+         mgr->StartAnalysis(mode, chain);
+         return;
+      case 1:
+         if (!kProofDataSet.Length()) {
+            ::Error("AnalysisTrainHMPID.C::StartAnalysis", "kProofDataSet is empty");
+            return;
+         }
+         mgr->StartAnalysis(mode, kProofDataSet, kProofEvents,kProofOffset);
+         return;
+      case 2:
+         if (kPluginUse) {
+            if (!mgr->GetGridHandler()) {
+               ::Error("AnalysisTrainHMPID.C::StartAnalysis", "Grid plugin not initialized");
+               return;
+            }
+            mgr->StartAnalysis("grid");
+         } else {
+            if (!chain) {
+               ::Error("AnalysisTrainHMPID.C::StartAnalysis", "Cannot create the chain");
+               return;
+            }
+            mgr->StartAnalysis(mode, chain);
+         }
+      return;
+   }
+}
+
+//______________________________________________________________________________
+void CheckModuleFlags(const char *mode) {
+// Checks selected modules and insure compatibility
+   Int_t imode = -1;
+   if (!strcmp(mode, "LOCAL")) imode = 0;
+   if (!strcmp(mode, "PROOF")) imode = 1;
+   if (!strcmp(mode, "GRID"))  imode = 2;
+
+
+   if (kUseCPAR) {
+     kPluginAliRootVersion    = ""; // NO aliroot if we use CPAR
+   }
+
+   if (imode==1) {
+      if (!kUsePAR) {
+         ::Info("AnalysisTrainHMPID.C::CheckModuleFlags", "PAR files enabled due to PROOF analysis");
+         kUsePAR = kTRUE;
+      }   
+   }  
+   if (imode != 2) {
+      ::Info("AnalysisTrainHMPID.C::CheckModuleFlags", "AliEn plugin disabled since not in GRID mode");
+      kPluginUse = kFALSE; 
+   }
+
+   if(!kIsMC){
+     // switch off anthin related to MC
+     kUseMC = 0;
+     kUseTR = kFALSE;
+   }
+
+ // ESD analysis
+   if (!kUseMC){
+     kUseTR = kFALSE;
+     if(kUseKinefilter)::Info("AnalysisTrainHMPID.C::CheckModuleFlags", "Kine Filter disabled in analysis without MC");
+     kUseKinefilter = kFALSE;
+   }
+   if (iJETAN){
+     iESDfilter=1;
+   }
+   if (!iESDfilter){
+     kUseKinefilter = kFALSE;
+     kUseMuonfilter = kFALSE;
+   }
+
+   iJETANLib = iJETAN && 1;
+   if (iESDfilter) {iAODhandler=1;}
+   if (kUseKinefilter && !kUseMC) kUseKinefilter = kFALSE;
+   
+}
+
+
+//______________________________________________________________________________
+Bool_t Connect(const char *mode) {
+// Connect <username> to the back-end system.
+   Int_t imode = -1;
+   if (!strcmp(mode, "LOCAL")) imode = 0;
+   if (!strcmp(mode, "PROOF")) imode = 1;
+   if (!strcmp(mode, "GRID"))  imode = 2;
+   TString username = gSystem->Getenv("alien_API_USER");
+   switch (imode) {
+     case 0:
+       break;
+     case 1:
+       if  (!username.Length()) {
+         ::Error(Form("AnalysisTrainHMPID.C::Connect <%s>", mode), "Make sure you:\n \
+                        1. Have called: alien-token-init <username>\n \
+                        2. Have called: >source /tmp/gclient_env_$UID");
+         return kFALSE;
+       }
+       ::Info("AnalysisTrainHMPID.C::Connect", "Connecting user <%s> to PROOF cluster <%s>", 
+                username.Data(), kProofCluster.Data());
+       gEnv->SetValue("XSec.GSI.DelegProxy", "2");
+       TProof::Open(Form("%s@%s", username.Data(), kProofCluster.Data()));       
+       if (!gProof) {
+         if (strcmp(gSystem->Getenv("XrdSecGSISRVNAMES"), "lxfsrd0506.cern.ch"))
+           ::Error(Form("AnalysisTrainHMPID.C::Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");
+           return kFALSE;
+         }
+       if(kProofClearPackages)gProof->ClearPackages();
+       break;
+     case 2:      
+       if  (!username.Length()) {
+         ::Error(Form("AnalysisTrainHMPID.C::Connect <%s>", mode), "Make sure you:\n \
+                        1. Have called: alien-token-init <username>\n \
+                        2. Have called: >source /tmp/gclient_env_$UID");
+         return kFALSE;
+       }
+       if (kPluginUse && !gSystem->Getenv("alien_CLOSE_SE")) {
+         ::Error(Form("AnalysisTrainHMPID.C::Connect <%s>", mode), 
+                        "When using the AliEn plugin it is preferable to define the \
+                        variable alien_CLOSE_SE in your environment.");
+         return kFALSE;
+       }
+       ::Info("AnalysisTrainHMPID.C::Connect", "Connecting user <%s> to AliEn ...", 
+                username.Data());
+       TGrid::Connect("alien://");
+       if (!gGrid || !gGrid->IsConnected()) return kFALSE;
+       break;
+     default:
+       ::Error("AnalysisTrainHMPID.C::Connect", "Unknown run mode: %s", mode);
+       return kFALSE;
+   }
+   ::Info("AnalysisTrainHMPID.C::Connect","Connected in %s mode", mode);
+   return kTRUE;
+}
+
+
+//______________________________________________________________________________
+Bool_t LoadCommonLibraries(const char *mode)
+{
+// Load common analysis libraries.
+   Int_t imode = -1;
+   if (!strcmp(mode, "LOCAL")) imode = 0;
+   if (!strcmp(mode, "PROOF")) imode = 1;
+   if (!strcmp(mode, "GRID"))  imode = 2;
+   if (!gSystem->Getenv("ALICE_ROOT")) {
+      ::Error("AnalysisTrainHMPID.C::LoadCommonLibraries", "Analysis train requires that analysis libraries are compiled with a local AliRoot"); 
+      return kFALSE;
+   }   
+   Bool_t success = kTRUE;
+   // ROOT libraries
+   gSystem->Load("libTree.so");
+   gSystem->Load("libGeom.so");
+   gSystem->Load("libVMC.so");
+   gSystem->Load("libPhysics.so");
+   
+   // Load framework classes. Par option ignored here.
+   switch (imode) {
+      case 0:
+      case 2:
+         if (kUseCPAR) {
+            success &= LoadLibrary("STEERBase", mode, kTRUE);
+            success &= LoadLibrary("ESD", mode, kTRUE);
+            success &= LoadLibrary("AOD", mode, kTRUE);
+            success &= LoadLibrary("ANALYSIS", mode, kTRUE);
+            success &= LoadLibrary("ANALYSISalice", mode, kTRUE);
+            success &= LoadLibrary("CORRFW", mode, kTRUE);
+         } else {   
+            success &= LoadLibrary("libSTEERBase.so", mode);
+            success &= LoadLibrary("libESD.so", mode);
+            success &= LoadLibrary("libAOD.so", mode);
+            success &= LoadLibrary("libANALYSIS.so", mode);
+            success &= LoadLibrary("libANALYSISalice.so", mode);
+            success &= LoadLibrary("libCORRFW.so", mode);
+            gROOT->ProcessLine(".include $ALICE_ROOT/include");
+         }   
+         break;
+      case 1:
+         if (!kProofUseAFPAR) {
+            success &= LoadLibrary("STEERBase", mode);
+            success &= LoadLibrary("ESD", mode);
+            success &= LoadLibrary("AOD", mode);
+            success &= LoadLibrary("ANALYSIS", mode);
+            success &= LoadLibrary("ANALYSISalice", mode);
+            success &= LoadLibrary("CORRFW", mode);
+         } else { 
+            success &= !gProof->EnablePackage(kProofAFversion);
+            success &= LoadLibrary("CORRFW", mode);
+         }
+         break;         
+      default:
+         ::Error("AnalysisTrainHMPID.C::LoadCommonLibraries", "Unknown run mode: %s", mode);
+         return kFALSE;
+   }
+   if (success) {
+      ::Info("AnalysisTrainHMPID.C::LoadCommodLibraries", "Load common libraries:    SUCCESS");
+      ::Info("AnalysisTrainHMPID.C::LoadCommodLibraries", "Include path for Aclic compilation:\n%s",
+              gSystem->GetIncludePath());
+   } else {           
+      ::Info("AnalysisTrainHMPID.C::LoadCommodLibraries", "Load common libraries:    FAILED");
+   }   
+      
+   return success;
+}
+
+
+//______________________________________________________________________________
+Bool_t LoadAnalysisLibraries(const char *mode)
+{
+// Load common analysis libraries.
+   Bool_t success = kTRUE;
+   if (iESDfilter) {
+      if (!LoadLibrary("PWG3base", mode, kTRUE) ||
+          !LoadLibrary("PWG3muon", mode, kTRUE)) return kFALSE;
+   }   
+
+   if(iHMPID){
+     if (!LoadSource(Form("%s/AliHMPIDAnalysisTask.cxx",gSystem->ExpandPathName(".")), mode, kTRUE))return kFALSE;
+   }
+
+   if (iJETANLib) {
+     if (!LoadLibrary("JETAN", mode, kTRUE)) return kFALSE;
+   }
+
+   ::Info("AnalysisTrainHMPID.C::LoadAnalysisLibraries", "Load other libraries:   SUCCESS");
+   return kTRUE;
+}
+
+
+//______________________________________________________________________________
+Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
+{
+// Load a module library in a given mode. Reports success.
+   Int_t imode = -1;
+   Int_t result;
+   TString smodule(module);
+   if (!strcmp(mode, "LOCAL")) imode = 0;
+   if (!strcmp(mode, "PROOF")) imode = 1;
+   if (!strcmp(mode, "GRID"))  imode = 2;
+   TString mod(module);
+   if (!mod.Length()) {
+      ::Error("AnalysisTrainHMPID.C::LoadLibrary", "Empty module name");
+      return kFALSE;
+   }   
+   // If a library is specified, just load it
+   if (smodule.EndsWith(".so")) {
+      mod.Remove(mod.Index(".so"));
+      result = gSystem->Load(mod);
+      if (result < 0) {
+         ::Error("AnalysisTrainHMPID.C::LoadLibrary", "Could not load library %s", module);
+         return kFALSE;
+      }
+      if (rec) anaLibs += Form("%s.so ",mod.Data()); 
+      if (rec) anaLibsExtra += Form("%s.so ",mod.Data()); 
+      return kTRUE;
+   } 
+   // Check if the library is already loaded
+   if (strlen(gSystem->GetLibraries(Form("%s.so", module), "", kFALSE)) > 0)
+      return kTRUE;    
+   switch (imode) {
+      case 0:
+      case 2:
+         if (kUsePAR) {
+            result = SetupPar(module);
+            if (rec) anaPars += Form("%s.par ", module);
+         } else {
+            result = gSystem->Load(Form("lib%s.so", module));
+            if (rec) anaLibs += Form("lib%s.so ", module);
+         }   
+         break;
+      case 1:
+            if(!gSystem->AccessPathName(module)){
+              ::Info("AnalysisTrainHMPID.C::LoadLibrary", "Removing directory %s",module);
+              gSystem->Exec(Form("rm -rf %s",module));
+         }
+         result = gProof->UploadPackage(module);
+         if (result<0) {
+            result = gProof->UploadPackage(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", module)));
+            if (result<0) {
+               ::Error("AnalysisTrainHMPID.C::LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);
+               return kFALSE;
+            }
+         }   
+         result = gProof->EnablePackage(module);
+         break;
+      default:
+         return kFALSE;
+   }         
+   if (result < 0) {
+      ::Error("AnalysisTrainHMPID.C::LoadLibrary", "Could not load module %s", module);
+      return kFALSE;
+   }
+   return kTRUE;
+}           
+
+//______________________________________________________________________________
+Bool_t LoadSource(const char *source, const char *mode, Bool_t rec=kFALSE)
+{
+// Load a module library in a given mode. Reports success.
+   Int_t imode = -1;
+   Int_t result = -1;
+   if (!strcmp(mode, "LOCAL")) imode = 0;
+   if (!strcmp(mode, "PROOF")) imode = 1;
+   if (!strcmp(mode, "GRID"))  imode = 2;
+   TString ssource(source);
+   TString basename = gSystem->BaseName(ssource.Data());
+   if (!ssource.Length()) {
+      ::Error("AnalysisTrainHMPID.C::LoadSource", "Empty task name");
+      return kFALSE;
+   }
+   // we have a source code so compile it
+   if (ssource.EndsWith(".cxx")) {
+     // need to copy it here other wise the path is also used on grid...
+     ssource.Remove(ssource.Index(".cxx"));
+     basename.Remove(basename.Index(".cxx"));
+     Printf("LoadSources:: Copying...  path %s{cxx,h}",ssource.Data());
+     gSystem->Exec(Form("cp %s.cxx . ",ssource.Data()));
+     gSystem->Exec(Form("cp %s.h . ",ssource.Data()));
+     // Path to code
+     // only needed for local compilation, in grid and proof mode 
+     // the task headers are uploaded 
+     //     path.Remove(path.Index(gSystem->BaseName(path.Data())));
+     // Printf("LoadSources:: Including path %s",path.Data());
+     //  if(path.Length()>0)gROOT->ProcessLine(Form(".include %s",path.Data()));
+     Printf("LoadSources:: Loading...  path %s",basename.Data());
+     switch (imode) {
+     case 0:
+       result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
+       break;
+     case 1:
+       result = gProof->Load(Form("%s.cxx++g",basename.Data()));
+       break;
+     case 2:
+       result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
+       if (rec){
+       // what we want to compile
+         anaSources += Form("%s.cxx ",basename.Data());
+       // what we need as input...
+         anaLibs += Form("%s.cxx %s.h ",basename.Data(),basename.Data());
+       }
+       break;
+     default:
+       return kFALSE;
+     }
+   }
+   if (result < 0) {
+      ::Error("AnalysisTrainHMPID.C::LoadSources", "Could not load source %s", source);
+      return kFALSE;
+   }
+   return kTRUE;
+}
+
+//______________________________________________________________________________
+TChain *CreateChain(const char *mode, const char *plugin_mode)
+{
+// Create the input chain
+   Int_t imode = -1;
+   if (!strcmp(mode, "LOCAL")) imode = 0;
+   if (!strcmp(mode, "PROOF")) imode = 1;
+   if (!strcmp(mode, "GRID"))  imode = 2;
+   TChain *chain = NULL;
+   // Local chain
+   switch (imode) {
+      case 0:
+            if (!kLocalXMLDataset.Length()) {
+              // Local ESD
+              chain = new TChain("esdTree");
+              TString line;
+              ifstream in;
+              in.open(kLocalDataList.Data());
+              while (in.good()) {
+                in >> line;
+                if (line.Length() == 0) continue;
+                cout << " line = " << line << endl;
+                chain->Add(line.Data());
+              }       
+            } else {
+              // Interactive ESD
+           chain = CreateChainSingle(kLocalXMLDataset, "esdTree");
+            }   
+         break;
+      case 1:
+         break;
+      case 2:
+         if (kPluginUse) {
+            AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
+            AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
+         } else {
+            TString treeName = "esdTree";
+            chain = CreateChainSingle("wn.xml", treeName);
+         }
+         break;      
+      default:   
+   }
+   if (chain && chain->GetNtrees()) return chain;
+   return NULL;
+}   
+
+//______________________________________________________________________________
+TChain* CreateChainSingle(const char* xmlfile, const char *treeName)
+{
+   printf("*******************************\n");
+   printf("*** Getting the ESD Chain   ***\n");
+   printf("*******************************\n");
+   TAlienCollection * myCollection  = TAlienCollection::Open(xmlfile);
+
+   if (!myCollection) {
+      ::Error("AnalysisTrainHMPID.C::CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;
+      return NULL ;
+   }
+
+   TChain* chain = new TChain(treeName);
+   myCollection->Reset() ;
+   while ( myCollection->Next() ) chain->Add(myCollection->GetTURL("")) ;
+   chain->ls();
+   return chain;
+}
+
+//______________________________________________________________________________
+Int_t SetupPar(char* pararchivename)
+{
+   if (!pararchivename || !strlen(pararchivename)) return -1;
+   char processline[1024];
+   if (gSystem->AccessPathName(Form("%s.par", pararchivename))) {
+      if (!gSystem->AccessPathName(Form("%s/%s.par", gSystem->Getenv("ALICE_ROOT"),pararchivename))) {
+         ::Info("AnalysisTrainHMPID.C::SetupPar", "Getting %s.par from $ALICE_ROOT", pararchivename);
+         TFile::Cp(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", pararchivename)), 
+                   Form("%s.par",pararchivename));
+      } else {
+         ::Error("AnalysisTrainHMPID.C::SetupPar", "Cannot find %s.par", pararchivename);
+         return -1;
+      }   
+   }
+   gSystem->Exec(Form("tar xvzf %s.par", pararchivename));
+
+   TString ocwd = gSystem->WorkingDirectory();
+   if (!gSystem->ChangeDirectory(pararchivename)) return -1;
+       
+   // check for BUILD.sh and execute
+   if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
+      printf("*******************************\n");
+      printf("*** Building PAR archive    ***\n");
+      printf("*******************************\n");         
+      if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
+         Error("runProcess","Cannot Build the PAR Archive! - Abort!");
+         return -1;
+      }
+   }
+
+       // check for SETUP.C and execute
+       if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
+           printf("*******************************\n");
+           printf("*** Setup PAR archive       ***\n");
+           printf("*******************************\n");
+           gROOT->Macro("PROOF-INF/SETUP.C");
+       }       
+       if (!gSystem->ChangeDirectory(ocwd.Data())) return -1;
+   return 0;
+}
+
+//______________________________________________________________________________
+AliAnalysisAlien* CreateAlienHandler(const char *plugin_mode)
+{
+// Check if user has a valid token, otherwise make one. This has limitations.
+// One can always follow the standard procedure of calling alien-token-init then
+//   source /tmp/gclient_env_$UID in the current shell.
+   if (!AliAnalysisGrid::CreateToken()) return NULL;
+   AliAnalysisAlien *plugin = new AliAnalysisAlien();
+// Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
+   plugin->SetRunMode(plugin_mode);
+   if (kPluginUseProductionMode) plugin->SetProductionMode();
+   plugin->SetJobTag(kJobTag);
+   plugin->SetNtestFiles(1);
+//   plugin->SetPreferedSE("ALICE::NIHAM::File");
+// Set versions of used packages
+   plugin->SetAPIVersion("V1.1x");
+   plugin->SetROOTVersion(kPluginRootVersion);
+   plugin->SetAliROOTVersion(kPluginAliRootVersion);
+
+// Declare input data to be processed.
+// Method 1: Create automatically XML collections using alien 'find' command.
+// Define production directory LFN
+   plugin->SetGridDataDir(kGridDatadir.Data());
+// Set data search pattern
+   plugin->SetDataPattern(Form(" %s/*/*ESDs.root",kGridPassPattern.Data()));
+// ...then add run numbers to be considered
+   plugin->SetRunPrefix("000");
+   plugin->SetRunRange(kGridRunRange[0], kGridRunRange[1]);
+
+   if(kGridLocalRunList.Length()>0){
+     ifstream in1;
+     in1.open(kGridLocalRunList.Data());
+     int iRun;
+     // just use run numbers, negatives will be excluded
+     while(in1>>iRun){
+       if(iRun>0){
+       Printf("AnalysisTrainHMPID Adding run number from File %s", Form(kGridRunPattern.Data(),iRun));
+       plugin->AddRunNumber(Form(kGridRunPattern.Data(),iRun));
+       } else{
+         Printf("AnalysisTrainHMPID Skipping run number from File %d", iRun);
+       }
+     }
+   }
+
+// Method 2: Declare existing data files (raw collections, xml collections, root file)
+// If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
+// XML collections added via this method can be combined with the first method if
+// the content is compatible (using or not tags)
+//   plugin->AddDataFile("137431.xml");
+//   plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
+// Define alien work directory where all files will be copied. Relative to alien $HOME.
+   TString alien_workdir = "";
+
+   alien_workdir += kGridWorkDir.Data();
+   if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());
+   plugin->SetGridWorkingDir(alien_workdir.Data());
+
+   // Declare alien output directory. Relative to working directory.
+   if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
+   plugin->SetGridOutputDir(kGridOutdir);
+
+   // set extra libs before par file compilation
+   anaLibs += kGridExtraFiles;
+   anaLibs  = anaLibs.Strip();   
+   Printf("anaLibs %s",anaLibs.Data());
+   Printf("anaLibsExtra %s",anaLibsExtra.Data());
+
+   if (anaLibs.Length())          plugin->SetAdditionalLibs(anaLibs.Data());
+   if (anaLibsExtra.Length())     plugin->SetAdditionalRootLibs(anaLibsExtra.Data());
+
+   TString ana_sources = "";
+   TString ana_add = "";
+   if (kUsePAR && anaPars.Length()) {
+      printf("%s\n", anaPars.Data());
+      TObjArray *arr;
+      TObjString *objstr;
+      arr = anaPars.Tokenize(" ");
+      TIter next(arr);
+      while ((objstr=(TObjString*)next())) plugin->EnablePackage(objstr->GetString());
+      delete arr;
+   } 
+   
+// Declare the analysis source files names separated by blancs. To be compiled runtime
+// using ACLiC on the worker nodes.
+   ana_sources = anaSources.Strip();
+// Declare all libraries (other than the default ones for the framework. These will be
+// loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
+
+   if (ana_sources.Length()) plugin->SetAnalysisSource(ana_sources);
+   plugin->SetExecutableCommand(kPluginExecutableCommand.Data());
+   // Declare the output file names separated by blancs.
+   // (can be like: file.root or file.root@ALICE::Niham::File)
+   plugin->SetUseSubmitPolicy(kFALSE);
+   plugin->SetMergeExcludes(kGridMergeExclude);
+   plugin->SetMaxMergeFiles(kGridMaxMergeFiles);
+   plugin->SetNrunsPerMaster(kGridRunsPerMaster);
+   plugin->SetMergeViaJDL(kPluginMergeViaJDL);
+   // Use fastread option
+   plugin->SetFastReadOption(kPluginFastReadOption);
+   // UseOverwrite mode
+   plugin->SetOverwriteMode(kPluginOverwriteMode);
+   // Optionally define the files to be archived.
+   //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:AliAOD.root,AOD.tag.root@ALICE::NIHAM::File");
+   plugin->SetOutputToRunNo(kPluginOutputToRunNumber);     // write the output to subdirs named after run number
+//   plugin->SetDefaultOutputs(kFALSE);
+
+   // Put default output files to archive
+   TString listhists = "";
+   TString listaods  = "";
+   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
+   TIter next(mgr->GetOutputs());
+   AliAnalysisDataContainer *output;
+   while ((output=(AliAnalysisDataContainer*)next())) {
+      const char *filename = output->GetFileName();
+      if (!(strcmp(filename, "default"))) {
+         if (!mgr->GetOutputEventHandler()) continue;
+         filename = mgr->GetOutputEventHandler()->GetOutputFileName();
+         if (listaods.Length()) listaods += " ";
+         listaods += filename;
+      } else {
+         if(!listhists.Contains(filename)){
+            if (listhists.Length()) listhists += " ";
+            listhists += filename;
+         }
+      }
+   }
+
+   if (mgr->GetExtraFiles().Length()) {
+     if (listaods.Length()) listaods += " ";
+     listaods += mgr->GetExtraFiles();
+   }
+
+   TString outputArchive;
+   outputArchive = Form("log_archive.zip:std*r@%s",kGridOutputStorages.Data());
+   listaods.ReplaceAll(" ", ",");
+   listhists.ReplaceAll(" ", ",");
+   if (listhists.Length()) listhists = Form("hist_archive.zip:%s@%s", listhists.Data(), kGridOutputStorages.Data());
+   if (listaods.Length())  listaods  = Form("aod_archive.zip:%s@%s", listaods.Data(), kGridOutputStorages.Data());
+
+   if (!listhists.Length() && !listaods.Length()) {
+      ::Fatal("AnalysisTrainHMPID", "No task output !");
+   }
+
+   if (listaods.Length()) {
+      outputArchive += " ";
+      outputArchive += listaods;
+   }
+   if (listhists.Length()) {
+      outputArchive += " ";
+      outputArchive += listhists;
+   }
+//   plugin->SetOutputArchive(outputArchive);
+
+// Optionally set a name for the generated analysis macro (default MyAnalysis.C)
+   plugin->SetAnalysisMacro(Form("%s.C", kTrainName.Data()));
+// Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
+   plugin->SetSplitMaxInputFileNumber(kGridFilesPerJob);
+// Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
+//   plugin->SetMaxInitFailed(5);
+// Optionally resubmit threshold.
+//   plugin->SetMasterResubmitThreshold(90);
+// Optionally set time to live (default 30000 sec)
+   plugin->SetTTL(30000);
+// Optionally set input format (default xml-single)
+   plugin->SetInputFormat("xml-single");
+// Optionally modify the name of the generated JDL (default analysis.jdl)
+   plugin->SetJDLName(Form("%s.jdl", kTrainName.Data()));
+// Optionally modify the executable name (default analysis.sh)
+   plugin->SetExecutable(Form("%s.sh", kTrainName.Data()));
+// Optionally modify job price (default 1)
+   plugin->SetPrice(1);      
+// Optionally modify split mode (default 'se')    
+   plugin->SetSplitMode("se");
+   plugin->SetCheckCopy(kFALSE);
+   return plugin;
+}
+
+//______________________________________________________________________________
+Bool_t LoadConfig(const char *filename)
+{
+// Read train configuration from file
+   if (gSystem->AccessPathName(filename)) {
+      ::Error("AnalysisTrainHMPID.C::LoadConfig", "Config file name not found");
+      return kFALSE;
+   }   
+   gROOT->ProcessLine(Form(".x %s", filename));
+   ::Info("AnalysisTrainHMPID.C::LoadConfig", "Train configuration loaded from file %s", filename);
+   return kTRUE;
+}
+
+//______________________________________________________________________________
+Bool_t PatchJDL(){
+  Printf(">>> Patching JDL");
+  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
+  AliAnalysisAlien*    gridHandler = (AliAnalysisAlien*)mgr->GetGridHandler();
+  TGridJDL *jdl = gridHandler->GetGridJDL();
+  if(iJETAN)jdl->AddToPackages("fastjet","v2.4.0");
+  gridHandler->WriteJDL(kFALSE);
+  Printf("<<<  Patching JDL");
+  return kTRUE;
+}
+
+//______________________________________________________________________________
+Bool_t PatchAnalysisMacro(){
+  Printf(">>> Patching AnalysisMacro");
+  gSystem->Exec(Form("mv %s.C %s.C_tmp",kTrainName.Data(),kTrainName.Data()));
+
+  ifstream in1; 
+  in1.open(Form("%s.C_tmp", kTrainName.Data()));
+  char cLine[250];
+  TString st;
+  while(in1.getline(cLine,250)){
+    st += cLine;
+    st += "\n";
+  }
+  Int_t index= -1;
+  index = st.Index("gSystem->Load(\"libPhysics\");");
+  index += strlen("gSystem->Load(\"libPhysics\");");
+  /*
+    TObjArray *arr;
+    TObjString *objstr;
+    arr = anaLibs.Tokenize(" ");
+    TIter next(arr);
+
+    add += "\n\n // added by CKB \n";
+    while ((objstr=(TObjString*)next())){
+      if(objstr->GetString().Contains("PWG3"))continue;
+      if(objstr->GetString().EndsWith(".so"))add += Form("gSystem->Load(\"%s\");\n",objstr->GetString().Data());
+    }
+    delete arr; 
+    */
+    //    add += Form("AliLog::SetGlobalLogLevel(%d);\n",AliLog::GetGlobalLogLevel());
+  TString add = "";
+
+  if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
+  add += "\n\n // added by CKB \n";
+  add += "\n gSystem->AddIncludePath(\"./\"); \n";
+  if(gGrid && kPluginAliRootVersion.Length()==0){
+    add += "\n // Dirty hack for TRD reference data \n";
+    add += "\n gSystem->Setenv(\"ALICE_ROOT\",\"";
+    add += Form("alien://%s/rootfiles/",gGrid->GetHomeDirectory());
+    add += "\"); \n";
+  }
+  add += "// BKC \n\n";
+  st.Insert(index,add.Data());
+
+  if(kUseCPAR && kPluginAliRootVersion.Length()==0){
+    index = st.Index("gSystem->AddIncludePath(\"-I$"); // uncommen $ALICE_ROOT include for par files
+    if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
+    st.Insert(index,"// CKB comment out whehn no aliroot is provided \n //");
+  }
+
+  ofstream out;
+  out.open(Form("%s.C", kTrainName.Data()));
+  if (out.bad()) {
+    return kFALSE;
+  }
+  out << st << endl;
+  Printf("<<< Patching AnalysisMacro");
+
+  Printf(">>> Patching Merge Macro");
+  gSystem->Exec(Form("mv %s_merge.C %s_merge.C_tmp",kTrainName.Data(),kTrainName.Data()));
+
+  ifstream in2; 
+  in2.open(Form("%s_merge.C_tmp", kTrainName.Data()));
+  TString st2;
+  while(in2.getline(cLine,250)){
+    st2 += cLine;
+    st2 += "\n";
+  }
+  index = st2.Index("gSystem->Load(\"libPhysics\");");
+  index += strlen("gSystem->Load(\"libPhysics\");");
+  TString add2 = "";
+  add2 += "\n gSystem->AddIncludePath(\"./\"); \n";
+  if(gGrid&&kPluginAliRootVersion.Length()==0){
+    add2 += "\n // Dirty hack for TRD reference data \n";
+    add2 += "\n gSystem->Setenv(\"ALICE_ROOT\",\"";
+    add2 += Form("alien://%s/rootfiles/",gGrid->GetHomeDirectory());
+    add2 += "\"); \n";
+  }
+  add2 += "// BKC \n\n";
+  if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
+  st2.Insert(index,add.Data());
+
+  if(kUseCPAR&&kPluginAliRootVersion.Length()==0){
+    index = st2.Index("gSystem->AddIncludePath(\"-I$"); // uncommen $ALICE_ROOT include for par files
+    if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
+    st2.Insert(index,"// CKB comment out whehn no aliroot is provided \n //");
+  }
+
+  // do not exclude the extra files from merign, this is done explicitly in this train script
+  index = st2.Index("mergeExcludes +="); // uncommen $ALICE_ROOT include for par files
+  if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
+  st2.Insert(index,"// CKB comment out, handled explicitly by the train macro \n //");
+
+
+  ofstream out2;
+  out2.open(Form("%s_merge.C", kTrainName.Data()));
+  if (out2.bad()) {
+    return kFALSE;
+  }
+  out2 << st2 << endl;
+  Printf("<<< Patching Merging Macro");
+
+
+  return kTRUE;
+
+}