]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - ANALYSIS/macros/AnalysisTrainNew.C
Fix in physics selection OADB
[u/mrichter/AliRoot.git] / ANALYSIS / macros / AnalysisTrainNew.C
index 32ee29327ae740c0f532d3e5c028ba65195aac47..fa49f98d95b0a7123d77a6ebbf76120bc64d1ba5 100644 (file)
@@ -1,4 +1,4 @@
-//===================== ANALYSIS TRAIN ==========================================
+//===================== 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 AnalysisTrain.C
 //    root[1] AnalysisTrainNew("grid", "full")
 // CAF mode (requires root v5-23-02 + aliroot v4-16-Rev08)
 //    root[2] AnalysisTrainNew("proof")
-// Local mode requires AliESds.root or AliAOD.root in the work directory
+// Local mode requires AliESds.root or AliAOD.root in ./data directory
 //    root[3] AnalysisTrainNew("local")
+// In proof and grid modes, a token is needed and sourcing the produced environment file.
+//
+// If 'saveTrain' flag is set, the train will generate a directory name and run
+// in this directory. A configuration file 'ConfigTrain.C' will be generated. 
+// One can replay at any time the train via:
+//    root[1] AnalysisTrainNew(ana_mode, plugin_mode, "train_default_<date>/ConfigTrain.C")
 
-const char *root_version    = "v5-23-02";
-const char *aliroot_version = "v4-16-Rev-08";
-const char *cluster         = "alicecaf.cern.ch";
-//const char *AFversion       = "AF-v4-16";
-const char *AFversion       = "";
-// Dataset name. If empty assumes local ESD/AOD. In CAF it is a dataset name.
-//               In grid has to point to an xml file or be empty if using the plugin
-// === PROOF
-const char *proof_dataset = "/COMMON/COMMON/LHC09a4_run8100X#/esdTree";
-
-// === ALIEN
-const char *dataset   = "";
-const char *alien_datadir = "/alice/sim/PDC_09/LHC09a4/";
-Int_t run_numbers[10] = {81071,     0,     0,     0,     0,
-                             0,     0,     0,     0,     0};
-
-Bool_t useDBG        = kTRUE;
-Bool_t useMC         = kFALSE;
-Bool_t usePAR        = kTRUE;
-Bool_t useTR         = kFALSE;
-Bool_t usePLUGIN     = kTRUE;
-Bool_t useCORRFW     = kFALSE; // do not change
-    
-Int_t iAODanalysis   = 0;
-Int_t iAODhandler    = 1;
-Int_t iESDfilter     = 1;
-Int_t iMUONfilter    = 0;
-Int_t iMUONcopyAOD   = 0;
-Int_t iJETAN         = 1;
-Int_t iPWG4partcorr  = 1;
-Int_t iPWG4pi0       = 1;
-Int_t iPWG3vertexing = 0;
-Int_t iPWG2femto     = 0;
-Int_t iPWG2spectra   = 1;
-Int_t iPWG2flow      = 0;
-Int_t iPWG2res       = 0;
+//==================   TRAIN NAME   ============================================
+TString     train_name         = "FILTER_DATA"; // *CHANGE ME* (no blancs or special characters)
+TString     job_tag            = "FILTER_DATA: data ESD + PhysSel + Tender -> AOD + Muons + Vertices"; // *CHANGE ME*
+//==============================================================================
+
+// ### Settings that make sense in PROOF only
+//==============================================================================
+TString     proof_cluster      = "alicecaf.cern.ch";
+Bool_t      useAFPAR           = kFALSE;  // use AF special par file
+TString     AFversion          = "AF-v4-17";
+// Change CAF dataset here
+TString     proof_dataset      = "/COMMON/COMMON/LHC09a4_run8100X#/esdTree";
+TString     proof_outdir       = "";
+
+// ### Settings that make sense when using the Alien plugin
+//==============================================================================
+Int_t       runOnData          = 1;       // Set to 1 if processing real data
+Int_t       iCollision         = 0;       // 0=pp, 1=Pb-Pb
+Bool_t      usePLUGIN          = kTRUE;   // do not change
+Bool_t      useProductionMode  = kTRUE;   // use the plugin in production mode
+// Usage of par files ONLY in grid mode and ONLY if the code is not available
+// in the deployed AliRoot versions. Par file search path: local dir, if not there $ALICE_ROOT.
+// To refresh par files, remove the ones in the workdir, then do "make <target.par>" in 
+// AliRoot.
+Bool_t      usePAR             = kFALSE;  // use par files for extra libs
+Bool_t      useCPAR            = kFALSE;  // use par files for common libs
+TString     root_version       = "v5-27-05";  // *CHANGE ME IF MORE RECENT IN GRID*
+TString     aliroot_version    = "v4-20-06-AN-1";  // *CHANGE ME IF MORE RECENT IN GRID*                                          
+// Change production base directory here
+TString     alien_datadir      = "/alice/data/2010/LHC10d";
+// AliEn output directory. If blank will become output_<train_name>
+//TString     alien_outdir       = "/alice/data/2010/LHC10b/AOD1";
+TString     alien_outdir       = "";
+// Output folder to write delta AOD's. Considered if not null.
+TString     outputSingleFolder = "";
+//TString     outputSingleFolder = "deltas";
+// Number of files merged in a chunk
+Int_t       maxMergeFiles      = 20;
+// Files that should not be merged
+TString     mergeExclude       = "AliAOD.root AliAOD.VertexingHF.root AliAOD.Jets.root deltaAODPartCorr.root AliAOD.Muons.root AliAOD.Dimuons.root";
+// Make replicas on the storages below
+TString     outputStorages      = "disk=4";
+// Number of runs per master job
+Int_t       nRunsPerMaster     = 10;
+// Maximum number of files per job (gives size of AOD)
+Int_t       nFilesPerJob       = 50;
+// Int_t       nFilesPerJob       = 1; (AOD->delta AOD production case)
+// Set the run range
+Int_t run_numbers[10] = {126432}; // **********************!!!!!!!
+//Int_t       run_range[2]       =  {114786, 114949};  // LHC09a7   *CHANGE ME*
+// ### Settings that make sense only for local analysis
+//==============================================================================
+// Change local xml dataset for local interactive analysis
+TString     local_xmldataset   = "";
+
+// ### Other flags to steer the analysis
+//==============================================================================
+Bool_t      usePhysicsSelection = kTRUE; // use physics selection
+Bool_t      useTender           = kTRUE; // use tender wagon
+Bool_t      useMergeViaJDL      = kTRUE;  // merge via JDL
+Bool_t      useFastReadOption   = kTRUE;  // use xrootd tweaks
+Bool_t      useOverwriteMode    = kTRUE;  // overwrite existing collections
+Bool_t      useDATE             = kFALSE; // use date in train name
+Bool_t      useDBG              = kTRUE;  // activate debugging
+Bool_t      useMC               = kFALSE;  // use MC info
+Bool_t      useTAGS             = kFALSE;  // use ESD tags for selection
+Bool_t      useKFILTER          = kFALSE;  // use Kinematics filter
+Bool_t      useTR               = kFALSE;  // use track references
+Bool_t      useCORRFW           = kFALSE; // do not change
+Bool_t      useAODTAGS          = kFALSE; // use AOD tags
+Bool_t      saveTrain           = kTRUE;  // save train configuration as: 
+Bool_t      saveCanvases        = kFALSE;  // save canvases created in Terminate
+Bool_t      saveProofToAlien    = kFALSE; // save proof outputs in AliEn
+
+// ### Analysis modules to be included. Some may not be yet fully implemented.
+//==============================================================================
+Int_t       iAODanalysis       = 0;      // Analysis on input AOD's
+Int_t       iAODhandler        = 1;      // Analysis produces an AOD or dAOD's
+Int_t       iESDfilter         = 1;      // ESD to AOD filter (barrel + muon tracks)
+Int_t       iMUONcopyAOD       = 1;      // Task that copies only muon events in a separate AOD (PWG3)
+Int_t       iJETAN             = 1;      // Jet analysis (PWG4)
+Int_t       iJETANdelta        = 0;      // Jet delta AODs
+Int_t       iPWG4partcorr      = 0;      // Gamma-hadron correlations task (PWG4)
+Int_t       iPWG4gammaconv     = 0;      // Gamma conversion analysis (PWG4)
+Int_t       iPWG4omega3pi      = 0;      // Omega to 3 pi analysis (PWG4)
+Int_t       iPWG3vertexing     = 1;      // Vertexing HF task (PWG3)
+Int_t       iPWG3hfe           = 0;      // Electrons analysis (PWG3)
+Int_t       iPWG3d2h           = 0;      // D0->2 hadrons (PWG3)
+Int_t        iPWG3d0mass       = 1;      // D0 mass (PWG3D2H)                                                                              
+Int_t        iPWG3d0massLS     = 1;      // D0 mass LS (PWG3D2H)                                                                           
+Int_t        iPWG3dplus        = 1;      // D+ analysis (PWG3D2H)                                                                          
+Int_t        iPWG3LSd0         = 1;      // LS D0 analysis (PWG3D2H)                                                                       
+Int_t        iPWG3LSjpsi       = 1;      // LS J/Psi analysis (PWG3D2H)                                                                    
+Int_t        iPWG3CFd0         = 1;      // CF D0 analysis (PWG3D2H)                                                                       
+Int_t        iPWG3promptd0     = 1;      // prompt D0 analysis (PWG3D2H)                                                                   
+Int_t       iPWG3MuonTrain     = 0;      // Muon analysis train
+Int_t       iPWG2femto         = 0;      // Femtoscopy task (PWG2)
+Int_t       iPWG2spectra       = 0;      // Spectra tasks (PWG2
+Int_t        iPWG2protons      = 1;         // Proton-antiproton analysis
+Int_t        iPWG2checkcascade = 1;         // Check cascades task
+Int_t        iPWG2perfcascade  = 1;         // Check performance cascade
+Int_t        iPWG2checkv0      = 1;         // Check V0 task
+Int_t        iPWG2strange      = 1;         // Strangeness task
+Int_t        iPWG2central      = 1;         // Anisothropy in central collisions
+Int_t       iPWG2flow          = 0;      // Flow analysis tasks (PWG2)
+Int_t       iPWG2res           = 0;      // Resonances task (PWG2)
+Int_t        iPWG2rsneff       = 0;      // Resonances efficiency
+Int_t       iPWG2kink          = 0;      // Kink analysis tasks (PWG2)
+Int_t        iPWG2kinkESDMC    = 1;         // Kink ESD-MC comparison (PWG2)
+Int_t        iPWG2kinkLSKstar  = 1;      // Kink like-sign K* (PWG2)
+Int_t        iPWG2kinkLSL1520  = 1;      // Kink like-sign L1520 (PWG2)
+Int_t        iPWG2kinkLSPhi    = 1;      // Kink like-sign Phi (PWG2)
+Int_t        iPWG2kinkKstarESD = 1;      // Kink Kstar ESD (PWG2)
+Int_t        iPWG2kinkKstarMC  = 1;      // Kink Kstar MC (PWG2)
+Int_t        iPWG2kinkL1520ESD = 1;      // Kink L1520 ESD (PWG2)
+Int_t        iPWG2kinkL1520MC  = 1;      // Kink L1520 MC (PWG2)
+Int_t        iPWG2kinkPhiESD   = 1;      // Kink resonances Phi ESD (PWG2)
+Int_t        iPWG2kinkPhiMC    = 1;      // Kink resonances Phi MC (PWG2)
+Int_t       iPWG2evchar        = 0;      // Event characteristics (PWG2)
+Int_t       iPWG2unicor        = 0;      // Unicor analysis (PWG2)
+Int_t       iPWG2forward       = 0;      // FMD analysis (PWG2)
 
+// ### Configuration macros used for each module
+//==============================================================================
+TString     configPWG2femto    = "$ALICE_ROOT/PWG2/FEMTOSCOPY/macros/Train/Train3/ConfigFemtoAnalysis.C";
+//TString     configPWG3d2h      = "$ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF_highmult.C";
+TString     configPWG3d2h      = "$ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF.C";
+// Temporaries.
 TString anaPars = "";
 TString anaLibs = "";
 // Function signatures
-class AliAnalysisGrid;
+class AliAnalysisAlien;
 
 //______________________________________________________________________________
-void AnalysisTrainNew(const char *analysis_mode="grid", const char *plugin_mode="test")
+void AnalysisTrainNew(const char *analysis_mode="grid", 
+                      const char *plugin_mode="full",
+                      const char *config_file="")
 {
-// Example of running analysis train
+// 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;
    TString smode(analysis_mode);
-   smode.ToUpper();    
+   smode.ToUpper();
    // Check compatibility of selected modules
    CheckModuleFlags(smode);
+   if (saveTrain)              WriteConfig();
 
    printf("==================================================================\n");
-   printf("===========    RUNNING ANALYSIS TRAIN IN %s MODE   ==========\n", smode.Data());
+   printf("===========    RUNNING ANALYSIS TRAIN %s IN %s MODE   ==========\n", train_name.Data(),smode.Data());
    printf("==================================================================\n");
    printf("=  Configuring analysis train for:                               =\n");
    if (iAODanalysis) printf("=  AOD analysis                                                  =\n");
    else              printf("=  ESD analysis                                                  =\n");
+   if (usePhysicsSelection)   printf("=  Physics selection                                                =\n");
+   if (useTender)    printf("=  TENDER                                                        =\n");
    if (iESDfilter)   printf("=  ESD filter                                                    =\n");
-   if (iMUONfilter)  printf("=  MUON filter                                                   =\n");
    if (iMUONcopyAOD) printf("=  MUON copy AOD                                                 =\n");
    if (iJETAN)       printf("=  Jet analysis                                                  =\n");
-   if (iPWG2spectra) printf("=  PWG2 proton, checkCascade, checkV0, strange                   =\n");
-   if (iPWG2femto)   printf("=  PWG2 femtoscopy                                               =\n");
+   if (iJETANdelta)  printf("=     Jet delta AODs                                             =\n");
+   if (iPWG2spectra) {
+      printf("=  PWG2 SPECTRA tasks :                                          =\n");
+      if (iPWG2protons)      printf("=     PWG2 proton-antiproton                                     =\n");
+      if (iPWG2checkcascade) printf("=     PWG2 check cascades                                        =\n");
+      if (iPWG2perfcascade)  printf("=     PWG2 performance cascades                                  =\n");
+      if (iPWG2checkv0)      printf("=     PWG2 check V0                                              =\n");
+      if (iPWG2strange)      printf("=     PWG2 strangeness                                           =\n");
+      if (iPWG2central)      printf("=     PWG2 central                                               =\n");
+   }   
+   if (iPWG2femto) {
+      printf("=  PWG2 femtoscopy                                               =\n");
+      printf("   +++ configured by: %s\n", configPWG2femto.Data());
+   }   
    if (iPWG2flow)    printf("=  PWG2 flow                                                     =\n");
    if (iPWG2res)     printf("=  PWG2 resonances                                               =\n");
-   if (iPWG3vertexing) printf("=  PWG3 vertexing                                            =\n");
-   if (iPWG4partcorr)  printf("=  PWG4 gamma-hadron correlations                            =\n");
-   if (iPWG4pi0)     printf("=  PWG4 pi0 analysis                                             =\n");
+      if (iPWG2rsneff)    printf("=     PWG2 resonances efficiency                                    =\n");
+   if (iPWG2kink) {
+      printf("=  PWG2 kink analysis tasks:                                     =\n");
+      if (iPWG2kinkESDMC)    printf("=     PWG2 ESD-MC kinks                                          =\n");
+      if (iPWG2kinkLSKstar)  printf("=     PWG2 kink like-sign analysis K*                            =\n");
+      if (iPWG2kinkLSL1520)  printf("=     PWG2 kink like-sign analysis L1520                         =\n");
+      if (iPWG2kinkLSPhi)    printf("=     PWG2 kink like-sign analysis Phi                           =\n");
+      if (iPWG2kinkKstarESD) printf("=     PWG2 kink Kstar ESD analysis                               =\n");
+      if (iPWG2kinkKstarMC)  printf("=     PWG2 kink Kstar MC analysis                                =\n");
+      if (iPWG2kinkL1520ESD) printf("=     PWG2 kink L1520 ESD analysis                               =\n");
+      if (iPWG2kinkL1520MC)  printf("=     PWG2 kink L1520 MC analysis                                =\n");
+      if (iPWG2kinkPhiESD) printf("=     PWG2 kink Phi ESD analysis                                 =\n");
+      if (iPWG2kinkPhiMC)  printf("=     PWG2 kink Phi MC analysis                                  =\n");
+  }   
+   if (iPWG2evchar)    printf("=  PWG2 event characteristics                                    =\n");
+   if (iPWG2unicor)    printf("=  PWG2 Unicor analysis                                          =\n");
+   if (iPWG2forward)   printf("=  PWG2 forward: sharing, density, bkg. correction, dNdEta       =\n");
+   if (iPWG3vertexing) printf("=  PWG3 vertexing                                                =\n");
+   if (iPWG3hfe)       printf("=  PWG3 electrons                                                =\n");
+   if (iPWG3d2h) {
+      printf("=  PWG3 D0->2 hadrons tasks                                      =\n");
+      printf("   +++ configured by: %s\n", configPWG3d2h.Data());
+      if (iPWG3d0mass)       printf("=     PWG3 D0 mass                                               =\n");                               
+      if (iPWG3d0massLS)     printf("=     PWG3 D0 mass LS                                            =\n");                               
+      if (iPWG3dplus)        printf("=     PWG3 D+ analysis                                           =\n");                               
+      if (iPWG3LSd0)         printf("=     PWG3 LS D0                                                 =\n");                               
+      if (iPWG3LSjpsi)       printf("=     PWG3 LS J/Psi                                              =\n");                               
+      if (iPWG3CFd0)         printf("=     PWG3 CF D0                                                 =\n");                               
+      if (iPWG3promptd0)     printf("=     PWG3 prompt D0                                             =\n");                               
+   }         
+   if (iPWG3MuonTrain) printf("=  PWG3 muon train                                               =\n");
+   if (iPWG4partcorr)  printf("=  PWG4 gamma-hadron, pi0 and gamma-jet correlations             =\n");
+   if (iPWG4gammaconv) printf("=  PWG4 gamma conversion                                         =\n");
+   if (iPWG4omega3pi)  printf("=  PWG4 omega to 3 pions                                         =\n");
    printf("==================================================================\n");
-   printf(":: use MC truth      %d\n", (UInt_t)useMC);
-   printf(":: use track refs    %d\n", (UInt_t)useTR);
-   printf(":: use debugging     %d\n", (UInt_t)useDBG);
-   printf(":: use PAR files     %d\n", (UInt_t)usePAR);
-   printf(":: use AliEn plugin  %d\n", (UInt_t)usePLUGIN);
+   printf(":: use physics selection: %d\n", (UInt_t)usePhysicsSelection);
+   printf(":: use xrootd tweaks:     %d\n", (UInt_t)useFastReadOption);
+   printf(":: use overwrite xml    : %d\n", (UInt_t)useOverwriteMode);
+   printf(":: use merge via JDL:     %d\n", (UInt_t)useMergeViaJDL);
+   printf(":: use MC truth:          %d\n", (UInt_t)useMC);
+   printf(":: use KINE filter:       %d\n", (UInt_t)useKFILTER);
+   printf(":: use track references:  %d\n", (UInt_t)useTR);
+   printf(":: use tags:              %d\n", (UInt_t)useTAGS);
+   printf(":: use AOD tags:          %d\n", (UInt_t)useAODTAGS);
+   printf(":: use debugging:         %d\n", (UInt_t)useDBG);
+   printf(":: use PAR files:         %d\n", (UInt_t)usePAR);
+   printf(":: use AliEn plugin:      %d\n", (UInt_t)usePLUGIN);
 
+   //==========================================================================
    // Connect to back-end system
    if (!Connect(smode)) {
       ::Error("AnalysisTrain", "Could not connect to %s back-end", analysis_mode);
@@ -94,27 +248,28 @@ void AnalysisTrainNew(const char *analysis_mode="grid", const char *plugin_mode=
    if (!LoadCommonLibraries(smode)) {
       ::Error("AnalysisTrain", "Could not load common libraries");
       return;
-   }   
+   }
     
+   // Make the analysis manager and connect event handlers
+   AliAnalysisManager *mgr  = new AliAnalysisManager("Analysis Train", "Production train");
+   if (saveProofToAlien) mgr->SetSpecialOutputLocation(proof_outdir);
+   if (!strcmp(plugin_mode, "test")) mgr->SetNSysInfo(1);
    // Load analysis specific libraries
    if (!LoadAnalysisLibraries(smode)) {
       ::Error("AnalysisTrain", "Could not load analysis libraries");
       return;
    }   
 
-    
-   //==========================================================================
-   // Make the analysis manager and connect event handlers
-   AliAnalysisManager *mgr  = new AliAnalysisManager("Analysis Train", "Production train");
-
    // Create input handler (input container created automatically)
    if (iAODanalysis) {
    // AOD input handler
       AliAODInputHandler *aodH = new AliAODInputHandler();
+      if (iPWG3d2h) aodH->AddFriend("AliAOD.VertexingHF.root");
       mgr->SetInputEventHandler(aodH);
    } else {   
    // ESD input handler
       AliESDInputHandler *esdHandler = new AliESDInputHandler();
+      if (useTAGS) esdHandler->SetReadTags();
       mgr->SetInputEventHandler(esdHandler);       
    }
    // Monte Carlo handler
@@ -127,11 +282,18 @@ void AnalysisTrainNew(const char *analysis_mode="grid", const char *plugin_mode=
    if (iAODhandler) {
       // AOD output handler
       AliAODHandler* aodHandler   = new AliAODHandler();
-      mgr->SetOutputEventHandler(aodHandler);
       aodHandler->SetOutputFileName("AliAOD.root");
+      mgr->SetOutputEventHandler(aodHandler);
+      if (iAODanalysis) {
+         aodHandler->SetFillAOD(kFALSE);
+         aodHandler->SetCreateNonStandardAOD();
+         if (iJETAN)         aodHandler->SetOutputFileName("AliAOD.Jets.root");
+//         if (iPWG3vertexing) aodHandler->SetOutputFileName("AliAOD.VertexingHF.root");
+      } 
    }
    // Debugging if needed
    if (useDBG) mgr->SetDebugLevel(3);
+   if (saveCanvases) mgr->SetSaveCanvases(kTRUE);
 
    //==========================================================================
    // Create the chain. In this example it is created only from ALIEN files but
@@ -146,63 +308,350 @@ void AnalysisTrainNew(const char *analysis_mode="grid", const char *plugin_mode=
    // For now connection to top input container and common AOD output container
    // is done in this macro, but in future these containers will be connected
    // from each task configuration macro.
+                                                                                                                                           
+   AddAnalysisTasks();                                                                                                                     
+                                                                                                                                           
+   // Run the analysis                                                                                                                     
+   //                                                                                                                                      
+   if (usePLUGIN) {                                                                                                                        
+      AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);                                                                     
+      AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);                                                              
+   }                                                                                                                                       
+                                                                                                                                           
+   if (mgr->InitAnalysis()) {                                                                                                              
+      mgr->PrintStatus();                                                                                                                  
+      if (saveTrain || strlen(config_file)) gSystem->ChangeDirectory(train_name);                                                          
+      StartAnalysis(smode, chain);                                                                                                         
+      if (saveTrain && smode=="GRID") {                                                                                                    
+         AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();                                                         
+         TString alien_workdir = gGrid->GetHomeDirectory();                                                                                
+         alien_workdir += train_name;
+         alien_outdir = gridhandler->GetGridOutputDir();                                                                                   
+         printf("=== Registering ConfigTrain.C in the work directory <%s> ===\n",                                                          
+                alien_workdir.Data());                                                                                                     
+         if (AliAnalysisAlien::FileExists(Form("%s/%sConfig.C", alien_workdir.Data(), train_name.Data())))                                 
+            gGrid->Rm(Form("%s/%sConfig.C", alien_workdir.Data(), train_name.Data()));                                                     
+         if (strcmp(plugin_mode, "test"))                                                                                                  
+            TFile::Cp(Form("file:%sConfig.C",train_name.Data()), Form("alien://%s/%sConfig.C", alien_workdir.Data(), train_name.Data()));  
+      }                                                                                                                                    
+   }                                                                                                                                       
+}                                                                                                                                          
+                                                                                                                                            
+//______________________________________________________________________________                                                           
+void AddAnalysisTasks()                                                                                                                    
+{                                                                                                                                          
+// Add all analysis task wagons to the train                                                                                               
+   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();                                                                     
+
+  //
+  // Tender and supplies
+  //
+   if (useTender) {
+      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/TenderSupplies/AddTaskTender.C");
+      AliAnalysisTaskSE *tender = AddTaskTender(kTRUE);
+//      tender->SelectCollisionCandidates();
+      tender->SetDebugLevel(2);
+   }
+   if (usePhysicsSelection) {
+   // Physics selection task
+      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
+      mgr->RegisterExtraFile("event_stat.root");
+      AliPhysicsSelectionTask *physSel = AddTaskPhysicsSelection(useMC);
+   }
 
    if (iESDfilter && !iAODanalysis) {
       //  ESD filter task configuration.
       gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskESDFilter.C");
-      AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter();
+      if (iMUONcopyAOD) {
+         printf("Registering delta AOD file\n");
+         mgr->RegisterExtraFile("AliAOD.Muons.root");
+         mgr->RegisterExtraFile("AliAOD.Dimuons.root");
+         AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(useKFILTER, kTRUE, kTRUE, usePhysicsSelection);
+      } else {
+         AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(useKFILTER, kFALSE, kFALSE, usePhysicsSelection);
+      }   
    }   
 
-   // Muon filter
-   if (iMUONfilter && !iAODanalysis) {
-      // There is no configuration from outside for this task yet.
-      AliAnalysisTaskESDMuonFilter *taskesdmuonfilter = new AliAnalysisTaskESDMuonFilter("ESD Muon Filter");
-      mgr->AddTask(taskesdmuonfilter);
-      // Connect to data containers
-      mgr->ConnectInput  (taskesdmuonfilter,  0, mgr->GetCommonInputContainer());
+   // AOD tags
+   if (useAODTAGS) {
+      AliAnalysisTaskTagCreator* tagTask = new AliAnalysisTaskTagCreator("AOD Tag Creator");
+      mgr->AddTask(tagTask);
+      AliAnalysisDataContainer *coutTags = mgr->CreateContainer("cTag",  TTree::Class(), 
+                                           AliAnalysisManager::kOutputContainer, "AOD.tag.root");
+      mgr->ConnectInput (tagTask, 0, mgr->GetCommonInputContainer());
+      mgr->ConnectOutput(tagTask, 1, coutTags);
    }   
     
-    // Jet analysis
-   if (iJETAN) {
-      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJets.C");
-      AliAnalysisTaskJets *taskjets = AddTaskJets("ESD", "UA1");
-   }
-       
+// ********** PWG2 wagons ******************************************************
+   AliAnalysisManager::SetCommonFileName("PWG2histograms.root");
+
    // Proton analysis
    if (iPWG2spectra) {
       // protons
-      gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskProtons.C");
-      AliAnalysisTaskProtons *taskprotons = AddTaskProtons();
+      if (iPWG2protons) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskProtons.C");
+        AliAnalysisTaskProtons *taskprotons = AddTaskProtons();
+        if (!taskprotons) ::Warning("AnalysisTrainNew", "AliAnalysisTaskProtons cannot run for this train conditions - EXCLUDED");
+      }  
       // cascades
-      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCheckCascade.C");
-      AliAnalysisTaskCheckCascade *taskcheckcascade = AddTaskCheckCascade();      
+      if (iPWG2checkcascade) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskCheckCascade.C");
+        AliAnalysisTaskCheckCascade *taskcheckcascade = AddTaskCheckCascade(iCollision,runOnData);
+        if (!taskcheckcascade) ::Warning("AnalysisTrainNew", "AliAnalysisTaskCheckCascade cannot run for this train conditions - EXCLUDED");
+      }  
       // v0's
-      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskCheckV0.C");
-      AliAnalysisTaskCheckV0 *taskcheckV0 = AddTaskCheckV0();
+      if (iPWG2checkv0) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskCheckV0.C");
+        AliAnalysisTaskCheckV0 *taskcheckV0 = AddTaskCheckV0();
+        if (!taskcheckV0) ::Warning("AnalysisTrainNew", "AliAnalysisTaskCheckV0 cannot run for this train conditions - EXCLUDED");
+      }  
       // strangeness
-      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskStrange.C");
-      AliAnalysisTaskStrange *taskstrange = AddTaskStrange();
-   }   
+      if (iPWG2strange) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskStrange.C");
+        AliAnalysisTaskStrange *taskstrange = AddTaskStrange();
+        if (!taskstrange) ::Warning("AnalysisTrainNew", "AliAnalysisTaskStrange cannot run for this train conditions - EXCLUDED");
+      }  
+      // performance cascades
+      if (iPWG2perfcascade) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskCheckPerformanceCascade.C");
+        AliAnalysisTaskCheckPerformanceCascade *taskperfcascade = AddTaskCheckPerformanceCascade();
+        if (!taskperfcascade) ::Warning("AnalysisTrainNew", "AliAnalysisTaskCheckPerformanceCascade cannot run for this train conditions - EXCLUDED");
+      }  
+       // central
+      if (iPWG2central) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskCentral.C");
+        AliAnalysisTaskCentral *taskcentral = AddTaskCentral();
+        if (!taskcentral) ::Warning("AnalysisTrainNew", "AliAnalysisTaskCentral cannot run for this train conditions - EXCLUDED");
+      }  
+  }   
    
+   // Femtoscopy analysis modules
+   if (iPWG2femto) {
+      gROOT->LoadMacro("$ALICE_ROOT/PWG2/FEMTOSCOPY/macros/AddTaskFemto.C");
+      AliAnalysisTaskFemto *taskfemto = AddTaskFemto(configPWG2femto);
+      if (!taskfemto) ::Warning("AnalysisTrainNew", "AliAnalysisTaskFemto cannot run for this train conditions - EXCLUDED");
+   }   
+
+   // Kink analysis
+   if (iPWG2kink) {
+      if (iPWG2kinkESDMC) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKink.C");
+        AliAnalysisKinkESDMC *taskkink1 = AddTaskKink();
+        if (!taskkink1) ::Warning("AnalysisTrainNew", "AliAnalysisKinkESDMC cannot run for this train conditions - EXCLUDED");
+      }   
+      if (iPWG2kinkLSKstar) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResLikeSignKstar.C");
+        AliResonanceKinkLikeSign *taskkink2 = AddTaskKinkResLikeSignKstar();
+        if (!taskkink2) ::Warning("AnalysisTrainNew", "AliResonanceKinkLikeSign cannot run for this train conditions - EXCLUDED");
+      }  
+      if (iPWG2kinkLSL1520) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResLikeSignL1520.C");
+        AliResonanceKinkLikeSign *taskkink3 = AddTaskKinkResLikeSignL1520();
+        if (!taskkink3) ::Warning("AnalysisTrainNew", "AliResonanceKinkLikeSign cannot run for this train conditions - EXCLUDED");
+      }  
+      if (iPWG2kinkLSPhi) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResLikeSignPhi.C");
+        AliResonanceKinkLikeSign *taskkink4 = AddTaskKinkResLikeSignPhi();
+        if (!taskkink4) ::Warning("AnalysisTrainNew", "AliResonanceKinkLikeSign cannot run for this train conditions - EXCLUDED");
+      }  
+      if (iPWG2kinkKstarESD) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResonanceKstarESD.C");
+        AliAnalysisTaskKinkResonance *taskkink5 = AddTaskKinkResonanceKstarESD();
+        if (!taskkink5) ::Warning("AnalysisTrainNew", "AliAnalysisKinkResonanceKstarESD cannot run for this train conditions - EXCLUDED");
+      }   
+      if (iPWG2kinkKstarMC) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResonanceKstarMC.C");
+        AliAnalysisTaskKinkResonance *taskkink6 = AddTaskKinkResonanceKstarMC();
+        if (!taskkink6) ::Warning("AnalysisTrainNew", "AliAnalysisKinkResonanceKstarMC cannot run for this train conditions - EXCLUDED");
+      }   
+      if (iPWG2kinkL1520ESD) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResonanceL1520ESD.C");
+        AliAnalysisTaskKinkResonance *taskkink7 = AddTaskKinkResonanceL1520ESD();
+        if (!taskkink7) ::Warning("AnalysisTrainNew", "AliAnalysisKinkResonanceL1520ESD cannot run for this train conditions - EXCLUDED");
+      }   
+      if (iPWG2kinkL1520MC) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResonanceL1520MC.C");
+        AliAnalysisTaskKinkResonance *taskkink8 = AddTaskKinkResonanceL1520MC();
+        if (!taskkink8) ::Warning("AnalysisTrainNew", "AliAnalysisKinkResonanceL1520MC cannot run for this train conditions - EXCLUDED");
+      }   
+      if (iPWG2kinkPhiESD) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResonancePhiESD.C");
+        AliAnalysisTaskKinkResonance *taskkink9 = AddTaskKinkResonancePhiESD();
+        if (!taskkink9) ::Warning("AnalysisTrainNew", "AliAnalysisKinkResonancePhiESD cannot run for this train conditions - EXCLUDED");
+      }   
+      if (iPWG2kinkPhiMC) {
+        gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResonancePhiMC.C");
+        AliAnalysisTaskKinkResonance *taskkink10 = AddTaskKinkResonancePhiMC();
+        if (!taskkink10) ::Warning("AnalysisTrainNew", "AliAnalysisKinkResonancePhiMC cannot run for this train conditions - EXCLUDED");
+      }   
+   }   
+
+   // Event characterization
+   if (iPWG2evchar) {
+      gROOT->LoadMacro("$ALICE_ROOT/PWG2/EVCHAR/macros/AddTaskSPDdNdEta.C");
+      AliAnalysisTaskSPDdNdEta *taskspddndeta = AddTaskSPDdNdEta();
+      if (!taskspddndeta) ::Warning("AnalysisTrainNew", "AliAnalysisTaskSPDdNdEta cannot run for this train conditions - EXCLUDED");
+      taskspddndeta->SetReadMC(useMC);
+   }   
+
+   // Unicor
+   if (iPWG2unicor) {
+      gROOT->LoadMacro("$ALICE_ROOT/PWG2/UNICOR/AddTaskUnicor.C");
+      AliAnalysisTaskUnicor *taskunicor = AddTaskUnicor();
+      if (!taskunicor) ::Warning("AnalysisTrainNew", "AliAnalysisTaskUnicor cannot run for this train conditions - EXCLUDED");
+   }   
+
+   // Forward Multiplicity
+   AliAnalysisManager::SetCommonFileName("forward.root");
+   if (iPWG2forward) {
+      gROOT->LoadMacro("$ALICE_ROOT/PWG2/FORWARD/analysis2/AddTaskForwardMult.C");
+      gROOT->LoadMacro("$ALICE_ROOT/PWG2/FORWARD/analysis2/AddTaskCentralMult.C");
+      Bool_t   mc  = false;
+      UShort_t sys = 0; // 0: get from data, 1: pp, 2: AA 
+      UShort_t sNN = 0; // 0: get from data, otherwise center of mass
+                       // energy (per nucleon pair)
+      Short_t  fld = 0; // 0: get from data, otherwise L3 field in kG
+      AliAnalysisTask *taskForward = AddTaskForwardMult(mc, sys, sNN, fld);
+      if (!taskForward) 
+       ::Warning("AnalysisTrainNew", "AliForwardMultiplicityTask cannot run for this train conditions - EXCLUDED");
+      AliAnalysisTask *taskCentral = AddTaskCentralMult(mc, sys, sNN, fld);
+      if (!taskCentral) 
+       ::Warning("AnalysisTrainNew", "AliCentralMultiplicityTask cannot run for this train conditions - EXCLUDED");
+   }   
+   AliAnalysisManager::SetCommonFileName("PWG2histograms.root");
+
+   // Flow analysis
+   if (iPWG2flow) {
+      gROOT->LoadMacro("$ALICE_ROOT/PWG2/FLOW/macros/AddTaskFlow.C");
+      Bool_t SP       = kTRUE;
+      Bool_t LYZ1SUM  = kTRUE;
+      Bool_t LYZ1PROD = kTRUE;
+      Bool_t LYZ2SUM  = kFALSE; 
+      Bool_t LYZ2PROD = kFALSE;
+      Bool_t LYZEP    = kFALSE; 
+      Bool_t GFC      = kTRUE;
+      Bool_t QC       = kTRUE;
+      Bool_t FQD      = kFALSE;
+      Bool_t MCEP     = kFALSE; //does not work yet 24/12/08
+      Bool_t kineFromESD = kTRUE;
+      Bool_t METHODS[] = {SP,LYZ1SUM,LYZ1PROD,LYZ2SUM,LYZ2PROD,LYZEP,GFC,QC,FQD,MCEP};
+      // Analysis type can be ESD, AOD, MC, ESDMC0, ESDMC1
+      TString type = "AOD";
+      if (!iAODanalysis) type = "ESD";
+      // Boolean to fill/not fill the QA histograms
+      Bool_t QA = kTRUE;   
+      // Boolean to use/not use weights for the Q vector
+      Bool_t WEIGHTS[] = {kFALSE,kFALSE,kFALSE}; //Phi, v'(pt), v'(eta)
+      AliAnalysisTaskFlowEvent* taskFE = AddTaskFlow(type,METHODS,QA,WEIGHTS);
+      if (!taskFE) ::Warning("AnalysisTrainNew", "AliAnalysisTaskFlowEvent cannot run for this train conditions - EXCLUDED");
+   }   
+
+   // PWG2 resonances
+   AliAnalysisManager::SetCommonFileName("resonances.root");
+   if (iPWG2res) {
+      gROOT->LoadMacro("$ALICE_ROOT/PWG2/RESONANCES/macros/train/AddAnalysisTaskRsnNew.C");
+      gROOT->LoadMacro("$ALICE_ROOT/PWG2/RESONANCES/macros/train/AddAnalysisTaskRsnEffNew.C");
+      TString path = gROOT->GetMacroPath();
+      path += ":$ALICE_ROOT/PWG2/RESONANCES/macros/train";
+      gROOT->SetMacroPath(path);
+      AddAnalysisTaskRsn(kTRUE);
+      if (iPWG2rsneff) AddAnalysisTaskRsnEff();
+   }   
+   AliAnalysisManager::SetCommonFileName("PWG2histograms.root");
+
+// ********** PWG3 wagons ******************************************************
+   AliAnalysisManager::SetCommonFileName("PWG3histograms.root");
+           
+   // PWG3 vertexing
+   if (iPWG3vertexing) {
+      gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/macros/AddTaskVertexingHF.C");
+      if (!iPWG3d2h) TFile::Cp(gSystem->ExpandPathName(configPWG3d2h.Data()), Form("%s/ConfigVertexingHF.C", train_name.Data()));
+      AliAnalysisTaskSEVertexingHF *taskvertexingHF = AddTaskVertexingHF();
+      if (!taskvertexingHF) ::Warning("AnalysisTrainNew", "AliAnalysisTaskSEVertexingHF cannot run for this train conditions - EXCLUDED");
+      else mgr->RegisterExtraFile("AliAOD.VertexingHF.root");
+   }   
+      
+   // PWG3 electrons
+   if (iPWG3hfe) {
+      gROOT->LoadMacro("$ALICE_ROOT/PWG3/hfe/AddTaskHFE.C");
+      AliAnalysisTaskHFE *taskHFE = AddTaskHFE();
+      if (!taskHFE) ::Warning("AnalysisTrainNew", "AliAnalysisTaskHFE cannot run for this train conditions - EXCLUDED");
+   }   
+
+   // PWG3 D2h
+   if (iPWG3d2h) {
+      gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/AddD2HTrain.C");
+      TFile::Cp(gSystem->ExpandPathName(configPWG3d2h.Data()), Form("%s/ConfigVertexingHF.C", train_name.Data()));
+      AddD2HTrain(iPWG3d0mass,iPWG3d0massLS,iPWG3dplus, iPWG3LSd0, iPWG3LSjpsi, iPWG3CFd0, iPWG3promptd0);                                 
+   }   
+
+   // PWG3 muon
+   if (iPWG3MuonTrain) {
+      gROOT->LoadMacro("$ALICE_ROOT/PWG3/muon/AddPWG3MuonTrain.C");
+      // iESDAnalysis, iAODAnalysis -> flags to select if the train is AOD or ESD based
+      // iMuonDistributions, iSingleMuonANAlysis -> flags to switch on/off analysis wagons
+      Int_t isESDAnalysis = (iAODanalysis)?0:1;
+      Int_t isAODAnalysis = (iAODanalysis)?1:0;
+      Int_t addMuonDistributions = 1;
+      Int_t addSingleMuonAnalysis = 1;
+      Int_t addMuonHFAnalysis = 1;
+      Int_t ntaskmuon = AddPWG3MuonTrain(isESDAnalysis,isAODAnalysis,addMuonDistributions,addSingleMuonAnalysis,addMuonHFAnalysis);
+      printf("Added %d muon tasks\n", ntaskmuon);
+   }   
+      
+// ********** PWG4 wagons ******************************************************
+   AliAnalysisManager::SetCommonFileName("PWG4histograms.root");
+
+    // Jet analysis
+   if (iJETAN) {
+      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJets.C");
+      if (!iAODanalysis) {
+         // Default jet reconstructor running on ESD's
+         AliAnalysisTaskJets * taskjets = AddTaskJets();
+         if (!taskjets) ::Warning("AnalysisTrainNew", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
+         if (iJETANdelta) {
+            AddTaskJetsDelta("AliAOD.Jets.root");
+            mgr->RegisterExtraFile("AliAOD.Jets.root");
+         }   
+      } else {
+         // AOD-based analysis. Add all reconstructors to write into delta AOD's
+         if (iJETANdelta) {
+            Int_t ntasksjets = AddTaskJetsDelta("AliAOD.Jets.root",0,kFALSE);
+            if (ntasksjets) printf("Added %d jet reconstructors\n", ntasksjets);
+         }
+      }      
+   }
    // PWG4 hadron correlations
    if (iPWG4partcorr) {
-      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskGammaHadronCorr.C");
-      AliAnalysisTaskParticleCorrelation *taskgammahadron = AddTaskGammaHadronCorr();  
+      Bool_t isSimulation = (runOnData)?kFALSE:kTRUE;
+      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPartCorr.C");
+      AliAnalysisTaskParticleCorrelation *taskpartcorrPHOS = AddTaskPartCorr("AOD", "PHOS", kFALSE, isSimulation);
+      if (!taskpartcorrPHOS) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation PHOS cannot run for this train conditions - EXCLUDED");
+      AliAnalysisTaskParticleCorrelation *taskpartcorrEMCAL = AddTaskPartCorr("AOD", "EMCAL", kFALSE, isSimulation);
+      if (!taskpartcorrEMCAL) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation EMCAL cannot run for this train conditions - EXCLUDED");
+      mgr->RegisterExtraFile("deltaAODPartCorr.root");
    }   
-       
-   // PWG4 pi0
-   if (iPWG4pi0) {
-      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPi0.C");
-      AliAnalysisTaskParticleCorrelation *taskpi0 = AddTaskPi0();  
+
+   // PWG4 gamma conversion analysis
+   if (iPWG4gammaconv) {
+      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskGammaConversion.C");
+      TString cdir = gSystem->WorkingDirectory();
+      gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
+      TString gcArguments = "-run-on-train   -use-own-xyz  -run-jet  -run-neutralmeson -no-aod  -apply-chi2-cut -low-memory -use-v0-multiplicity -move-bg-vertex ";
+      TString kGCAnalysisCutSelectionId="900110204010001";
+      gcArguments.Append(Form(" -set-cut-selection %s",kGCAnalysisCutSelectionId.Data()));
+      if(!useMC)gcArguments += " -mc-off";
+      AliAnalysisTaskGammaConversion * taskGammaConversion = AddTaskGammaConversion(gcArguments,mgr->GetCommonInputContainer());
+      gSystem->ChangeDirectory(cdir);
+      taskGammaConversion->SelectCollisionCandidates();
+      if (!taskGammaConversion) ::Warning("AnalysisTrainNew", "AliAnalysisTaskGammaConversion cannot run for these train conditions - EXCLUDED");
    }   
-    
-   //==========================================================================
-   // FOR THE REST OF THE TASKS THE MACRO AddTaskXXX() is not yet implemented/
-   // Run the analysis
-   //    
-   if (mgr->InitAnalysis()) {
-      mgr->PrintStatus();
-      StartAnalysis(smode, chain);
+
+   // PWG4 omega to 3 pions analysis
+   if (iPWG4omega3pi) {
+      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskomega3pi.C");
+      AliAnalysisTaskOmegaPi0PiPi *taskomega3pi = AddTaskomega3pi();
+      if (!taskomega3pi) ::Warning("AnalysisTrainNew", "AliAnalysisTaskomega3pi cannot run for these train conditions - EXCLUDED");
    }   
 }
 
@@ -217,14 +666,14 @@ void StartAnalysis(const char *mode, TChain *chain) {
    switch (imode) {
       case 0:
          if (!chain) {
-            ::Error("StartAnalysis", "Cannot create the chain");
+            ::Error("AnalysisTrainNew.C::StartAnalysis", "Cannot create the chain");
             return;
          }   
          mgr->StartAnalysis(mode, chain);
          return;
       case 1:
-         if (!strlen(proof_dataset)) {
-            ::Error("StartAnalysis", "proof_dataset is empty");
+         if (!proof_dataset.Length()) {
+            ::Error("AnalysisTrainNew.C::StartAnalysis", "proof_dataset is empty");
             return;
          }   
          mgr->StartAnalysis(mode, proof_dataset, 1000);
@@ -232,13 +681,13 @@ void StartAnalysis(const char *mode, TChain *chain) {
       case 2:
          if (usePLUGIN) {
             if (!mgr->GetGridHandler()) {
-               ::Error("StartAnalysis", "Grid plugin not initialized");
+               ::Error("AnalysisTrainNew.C::StartAnalysis", "Grid plugin not initialized");
                return;
             }   
             mgr->StartAnalysis("grid");
          } else {
             if (!chain) {
-               ::Error("StartAnalysis", "Cannot create the chain");
+               ::Error("AnalysisTrainNew.C::StartAnalysis", "Cannot create the chain");
                return;
             }   
             mgr->StartAnalysis(mode, chain);
@@ -254,28 +703,93 @@ void CheckModuleFlags(const char *mode) {
    if (!strcmp(mode, "LOCAL")) imode = 0;
    if (!strcmp(mode, "PROOF")) imode = 1;
    if (!strcmp(mode, "GRID"))  imode = 2;
+   if (!iJETAN) iJETANdelta = 0;
    if (imode==1) {
-      usePAR = kTRUE;
+      if (!usePAR) {
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PAR files enabled due to PROOF analysis");
+         usePAR = kTRUE;
+      }   
+   }  
+   if (imode != 2) {
+      ::Info("AnalysisTrainNew.C::CheckModuleFlags", "AliEn plugin disabled since not in GRID mode");
+      usePLUGIN = kFALSE; 
    }   
    if (iAODanalysis) {
    // AOD analysis
+      if (useMC)
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "MC usage disabled in analysis on AOD's");
+      if (useAODTAGS)
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "AOD tags usage disabled in analysis on AOD's");
       useMC = kFALSE;
       useTR = kFALSE;
+      useAODTAGS = kFALSE;
+      if (iESDfilter)
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "ESD filter disabled in analysis on AOD's");
       iESDfilter   = 0;
-      iMUONfilter  = 0;
+      if (!iAODhandler) {
+         if (iJETAN) 
+            ::Info("AnalysisTrainNew.C::CheckModuleFlags", "JETAN disabled in analysis on AOD's without AOD handler");
+         iJETAN = 0;
+         iJETANdelta = 0;
+      }
       // Disable tasks that do not work yet on AOD data
+      if (iPWG4gammaconv)
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG4gammaconv disabled on AOD's without AOD handler");
+      iPWG4gammaconv = 0;   
+      if (iPWG2central)
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2central disabled on AOD's");
+         iPWG2central = 0;
+      if (iPWG2flow)
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2flow disabled on AOD's");
+         iPWG2flow = 0;
+      if (iPWG2femto)
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2femto disabled on AOD's");
+         iPWG2femto = 0;
+      if (iPWG2res)
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2res disabled on AOD's");
+         iPWG2res = 0;
+       if (iPWG2rsneff)
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2rsneff disabled on AOD's");
+         iPWG2rsneff = 0;
+     if (iPWG2kink)         
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2kink disabled in analysis on AOD's");
+         iPWG2kink = 0;
+      if (iPWG2unicor)         
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2unicor disabled in analysis on AOD's");
+         iPWG2unicor = 0;
+      if (iPWG2evchar)
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG4evchar disabled on AOD's");
+         iPWG2evchar = 0;
+      if (iPWG2forward)         
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2forward disabled in analysis on AOD's");
+         iPWG2forward = 0;
+      if (iPWG3hfe)
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG3hfe disabled on AOD's");
+         iPWG3hfe = 0;
+      if (iPWG4omega3pi)
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG4omega3pi disabled on AOD's");
+         iPWG4omega3pi = 0;
    } else {   
    // ESD analysis
-      iMUONcopyAOD = 0;
-      iPWG3vertexing = 0;
-   }       
-   if (iMUONfilter || iJETAN) iESDfilter=1;
-   if (iESDfilter) iAODhandler=1;
-   if (iAODanalysis || !iAODhandler) {
-      iPWG4partcorr=0;
-      iPWG4pi0=0;
+      if (!useMC) useTR = kFALSE;
+      if (!useTR) {
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "iPWG2evchar disabled if not reading track references");
+         iPWG2evchar = 0;
+      }   
+   }
+   if (!useMC) {
+      if (iPWG2perfcascade)
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2perfcascade disabled without MC info");
+      iPWG2perfcascade = 0;   
+      if (iPWG2central)
+         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2central disabled without MC info");
+         iPWG2central = 0;
    }   
-   if (iPWG2spectra || iPWG2flow) useCORRFW = kTRUE;
+   if (iJETAN && !iAODanalysis) iESDfilter=1;
+   if (iESDfilter) {iAODhandler=1; useCORRFW = kTRUE;}
+   if (iPWG2spectra || iPWG2flow || iPWG3vertexing || iPWG3hfe || iPWG2res || iPWG2rsneff) useCORRFW = kTRUE;
+   if (useKFILTER && !useMC) useKFILTER = kFALSE;
+   if (useAODTAGS && !iAODhandler) useAODTAGS = kFALSE;
 }
 
 //______________________________________________________________________________
@@ -291,43 +805,54 @@ Bool_t Connect(const char *mode) {
          break;
       case 1:
          if  (!username.Length()) {
-            ::Error(Form("Connect <%s>", mode), "Make sure you:\n \
+            ::Error(Form("AnalysisTrainNew.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("Connect", "Connecting user <%s> to PROOF cluster <%s>", 
-                username.Data(), cluster);
-         TProof::Open(Form("%s@%s", username.Data(), cluster));       
+         ::Info("AnalysisTrainNew.C::Connect", "Connecting user <%s> to PROOF cluster <%s>", 
+                username.Data(), proof_cluster.Data());
+         gEnv->SetValue("XSec.GSI.DelegProxy", "2");
+//         TProof::Open(Form("%s@%s:31093", username.Data(), proof_cluster.Data()));       
+         TProof::Open(Form("%s@%s", username.Data(), proof_cluster.Data()));       
          if (!gProof) {
             if (strcmp(gSystem->Getenv("XrdSecGSISRVNAMES"), "lxfsrd0506.cern.ch"))
-               ::Error(Form("Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");
+               ::Error(Form("AnalysisTrainNew.C::Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");
             return kFALSE;
          }
+         TGrid::Connect("alien://");
+         if (gGrid) {
+            TString homedir = gGrid->GetHomeDirectory();
+            TString workdir = homedir + train_name;
+            if (!gGrid->Cd(workdir)) {
+               gGrid->Cd(homedir);
+               if (gGrid->Mkdir(workdir)) {
+                  gGrid->Cd(train_name);
+                  ::Info("AnalysisTrainNew::Connect()", "Directory %s created", gGrid->Pwd());
+               }
+            }
+            gGrid->Mkdir("proof_output");
+            gGrid->Cd("proof_output");
+            proof_outdir = Form("alien://%s", gGrid->Pwd());
+         }   
          break;
       case 2:      
-         if  (!username.Length()) {
-            ::Error(Form("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 (usePLUGIN && !gSystem->Getenv("alien_CLOSE_SE")) {
-            ::Error(Form("Connect <%s>", mode), 
+            ::Error(Form("AnalysisTrainNew.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("Connect", "Connecting user <%s> to AliEn ...", 
+         ::Info("AnalysisTrainNew.C::Connect", "Connecting user <%s> to AliEn ...", 
                 username.Data());
          TGrid::Connect("alien://");
          if (!gGrid || !gGrid->IsConnected()) return kFALSE;
          break;
       default:
-         ::Error("Connect", "Unknown run mode: %s", mode);
+         ::Error("AnalysisTrainNew.C::Connect", "Unknown run mode: %s", mode);
          return kFALSE;
    }
-   ::Info("Connect","Connected in %s mode", mode);
+   ::Info("AnalysisTrainNew.C::Connect","Connected in %s mode", mode);
    return kTRUE;
 }
 
@@ -340,7 +865,7 @@ Bool_t LoadCommonLibraries(const char *mode)
    if (!strcmp(mode, "PROOF")) imode = 1;
    if (!strcmp(mode, "GRID"))  imode = 2;
    if (!gSystem->Getenv("ALICE_ROOT")) {
-      ::Error("LoadCommonLibraries", "Analysis train requires that analysis libraries are compiled with a local AliRoot"); 
+      ::Error("AnalysisTrainNew.C::LoadCommonLibraries", "Analysis train requires that analysis libraries are compiled with a local AliRoot"); 
       return kFALSE;
    }   
    Bool_t success = kTRUE;
@@ -349,22 +874,32 @@ Bool_t LoadCommonLibraries(const char *mode)
    gSystem->Load("libGeom.so");
    gSystem->Load("libVMC.so");
    gSystem->Load("libPhysics.so");
+   gSystem->Load("libMinuit.so");
    
    // Load framework classes. Par option ignored here.
    switch (imode) {
       case 0:
       case 2:
-         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);
-         if (useCORRFW) success &= LoadLibrary("libCORRFW.so", mode);
-         gROOT->ProcessLine(".include $ALICE_ROOT/include");
+         if (useCPAR) {
+            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);
+            if (useCORRFW) 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);
+            if (useCORRFW) success &= LoadLibrary("libCORRFW.so", mode);
+            gROOT->ProcessLine(".include $ALICE_ROOT/include");
+         }   
          break;
       case 1:
          Int_t ires = -1;
-         if (!gSystem->AccessPathName(AFversion)) ires = gProof->UploadPackage(AFversion);
+         if (useAFPAR && !gSystem->AccessPathName(AFversion)) ires = gProof->UploadPackage(AFversion);
          if (ires < 0) {
             success &= LoadLibrary("STEERBase", mode);
             success &= LoadLibrary("ESD", mode);
@@ -374,20 +909,20 @@ Bool_t LoadCommonLibraries(const char *mode)
             if (useCORRFW) success &= LoadLibrary("CORRFW", mode);
          } else { 
             ires = gProof->EnablePackage(AFversion);
+            if (ires<0) success = kFALSE;
             if (useCORRFW) success &= LoadLibrary("CORRFW", mode);
          }
-         if (ires<0) success = kFALSE;
          break;         
       default:
-         ::Error("LoadCommonLibraries", "Unknown run mode: %s", mode);
+         ::Error("AnalysisTrainNew.C::LoadCommonLibraries", "Unknown run mode: %s", mode);
          return kFALSE;
    }
    if (success) {
-      ::Info("LoadCommodLibraries", "Load common libraries:    SUCCESS");
-      ::Info("LoadCommodLibraries", "Include path for Aclic compilation:\n%s",
+      ::Info("AnalysisTrainNew.C::LoadCommodLibraries", "Load common libraries:    SUCCESS");
+      ::Info("AnalysisTrainNew.C::LoadCommodLibraries", "Include path for Aclic compilation:\n%s",
               gSystem->GetIncludePath());
    } else {           
-      ::Info("LoadCommodLibraries", "Load common libraries:    FAILED");
+      ::Info("AnalysisTrainNew.C::LoadCommodLibraries", "Load common libraries:    FAILED");
    }   
       
    return success;
@@ -398,46 +933,89 @@ Bool_t LoadAnalysisLibraries(const char *mode)
 {
 // Load common analysis libraries.
    Bool_t success = kTRUE;
-   if (iMUONfilter) {
+   if (useTender) {
+      if (!LoadLibrary("TENDER", mode, kTRUE) ||
+          !LoadLibrary("TENDERSupplies", mode, kTRUE)) return kFALSE;
+   }       
+   if (iESDfilter || iPWG3MuonTrain) {
       if (!LoadLibrary("PWG3base", mode, kTRUE) ||
           !LoadLibrary("PWG3muon", mode, kTRUE)) return kFALSE;
    }   
    // JETAN
    if (iJETAN) {
       if (!LoadLibrary("JETAN", mode, kTRUE)) return kFALSE;
-   }   
-            
+   }
+   if (iJETANdelta) {
+      if (!LoadLibrary("JETAN", mode, kTRUE) ||
+          !LoadLibrary("CGAL", mode, kTRUE) ||
+          !LoadLibrary("fastjet", mode, kTRUE) ||
+          !LoadLibrary("siscone", mode, kTRUE) ||
+          !LoadLibrary("SISConePlugin", mode, kTRUE) ||
+          !LoadLibrary("FASTJETAN", mode, kTRUE)) return kFALSE;
+   }     
    // PWG4 particle correlations
-   if (iPWG4partcorr || iPWG4pi0) {   
-      if (!LoadLibrary("PWG4PartCorrBase", mode, kTRUE) ||
+   if (iPWG4partcorr) {   
+      if (!LoadLibrary("EMCALUtils", mode, kTRUE) ||
+          !LoadLibrary("PHOSUtils", mode, kTRUE) ||
+          !LoadLibrary("PWG4PartCorrBase", mode, kTRUE) ||
           !LoadLibrary("PWG4PartCorrDep", mode, kTRUE)) return kFALSE;
-      TFile::Cp(gSystem->ExpandPathName("$(ALICE_ROOT)/PWG4/macros/ConfigAnalysisGammaHadronCorrelation.C"), "ConfigAnalysisGammaHadronCorrelation.C");
-      TFile::Cp(gSystem->ExpandPathName("$(ALICE_ROOT)/PWG4/macros/ConfigAnalysisPi0.C"), "ConfigAnalysisPi0.C");
    }
+   // PWG4 gamma conversion
+   if (iPWG4gammaconv) {
+      if (!LoadLibrary("PWG4GammaConv", mode, kTRUE)) return kFALSE;
+   }      
+   // PWG4 omega to 3 pions
+   if (iPWG4omega3pi) {
+      if (!LoadLibrary("PWG4omega3pi", mode, kTRUE)) return kFALSE;
+   }      
    // PWG2 task protons 
    if (iPWG2spectra) {
       if (!LoadLibrary("PWG2spectra", mode, kTRUE)) return kFALSE;
    }
    // PWG2 flow
    if (iPWG2flow) {
-      if (!LoadLibrary("PWG2AOD", mode, kTRUE) ||
-          !LoadLibrary("PWG2flow", mode, kTRUE)) return kFALSE;
+      if (!LoadLibrary("PWG2flowCommon", mode, kTRUE) ||
+          !LoadLibrary("PWG2flowTasks", mode, kTRUE)) return kFALSE;
    }
    // PWG2 resonances
-   if (iPWG2res) {
+   if (iPWG2res || iPWG2rsneff) {
       if (!LoadLibrary("PWG2resonances", mode, kTRUE)) return kFALSE;
    }   
+   // PWG2 kink
+   if (iPWG2kink) {
+      if (!LoadLibrary("PWG2kink", mode, kTRUE)) return kFALSE;
+   }   
+   // PWG2 unicor
+   if (iPWG2unicor) {
+      if (!LoadLibrary("PWG2unicor", mode, kTRUE)) return kFALSE;
+   }   
+   // PWG2 evchar
+   if (iPWG2evchar) {
+      if (!LoadLibrary("PWG2evchar", mode, kTRUE)) return kFALSE;
+   }   
    // PWG2 femtoscopy
    if (iPWG2femto) {
       if (!LoadLibrary("PWG2AOD", mode, kTRUE) ||
           !LoadLibrary("PWG2femtoscopy", mode, kTRUE) ||
           !LoadLibrary("PWG2femtoscopyUser", mode, kTRUE)) return kFALSE;
+//      TFile::Cp(gSystem->ExpandPathName("$(ALICE_ROOT)/PWG2/FEMTOSCOPY/macros/ConfigFemtoAnalysis.C"), Form("%s/ConfigFemtoAnalysis.C", train_name.Data()));
+//      anaLibs += "ConfigFemtoAnalysis.C ";
    }   
-   // Vertexing HF
-   if (iPWG3vertexing) {
-      if (!LoadLibrary("PWG3vertexingHF", mode, kTRUE)) return kFALSE;
+   // PWG2 FORWARD
+   if (iPWG2forward) {
+      if (!LoadLibrary("PWG2forward2", mode, kTRUE)) return kFALSE;
+   }   
+   // PWG3 Vertexing HF
+   if (iPWG3vertexing || iPWG3d2h) {
+      if (!LoadLibrary("PWG3base", mode, kTRUE) ||
+          !LoadLibrary("PWG3vertexingHF", mode, kTRUE)) return kFALSE;
    }   
-   ::Info("LoadAnalysisLibraries", "Load other libraries:   SUCCESS");
+   // PWG3 hfe
+   if (iPWG3hfe) {
+      if (!LoadLibrary("PWG3hfe", mode, kTRUE)) return kFALSE;
+   }   
+   
+   ::Info("AnalysisTrainNew.C::LoadAnalysisLibraries", "Load other libraries:   SUCCESS");
    return kTRUE;
 }
 
@@ -453,7 +1031,7 @@ Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
    if (!strcmp(mode, "GRID"))  imode = 2;
    TString mod(module);
    if (!mod.Length()) {
-      ::Error("LoadLibrary", "Empty module name");
+      ::Error("AnalysisTrainNew.C::LoadLibrary", "Empty module name");
       return kFALSE;
    }   
    // If a library is specified, just load it
@@ -461,7 +1039,7 @@ Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
       mod.Remove(mod.Index(".so"));
       result = gSystem->Load(mod);
       if (result < 0) {
-         ::Error("LoadLibrary", "Could not load library %s", module);
+         ::Error("AnalysisTrainNew.C::LoadLibrary", "Could not load library %s", module);
          return kFALSE;
       }
       if (rec) anaLibs += Form("%s.so ",mod.Data()); 
@@ -486,7 +1064,7 @@ Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
          if (result<0) {
             result = gProof->UploadPackage(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", module)));
             if (result<0) {
-               ::Error("LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);
+               ::Error("AnalysisTrainNew.C::LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);
                return kFALSE;
             }
          }   
@@ -496,7 +1074,7 @@ Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
          return kFALSE;
    }         
    if (result < 0) {
-      ::Error("LoadLibrary", "Could not load module %s", module);
+      ::Error("AnalysisTrainNew.C::LoadLibrary", "Could not load module %s", module);
       return kFALSE;
    }
    return kTRUE;
@@ -516,26 +1094,32 @@ TChain *CreateChain(const char *mode, const char *plugin_mode)
    switch (imode) {
       case 0:
          if (iAODanalysis) {
-            if (!strlen(dataset)) {
+            if (!local_xmldataset.Length()) {
                // Local AOD
                chain = new TChain("aodTree");
-               if (gSystem->AccessPathName("AliAOD.root")) 
-                  ::Error("CreateChain", "File: AliAOD.root not in current dir");
-               else chain->Add("AliAOD.root");
+               if (gSystem->AccessPathName("data/AliAOD.root")) 
+                  ::Error("AnalysisTrainNew.C::CreateChain", "File: AliAOD.root not in ./data dir");
+               else {
+                  if (!saveTrain) chain->Add("data/AliAOD.root");
+                  else            chain->Add("../data/AliAOD.root");
+               }   
             } else {
                // Interactive AOD
-               chain = CreateChainSingle(dataset, "aodTree");
+               chain = CreateChainSingle(local_xmldataset, "aodTree");
             }
          } else {      
-            if (!strlen(dataset)) {
+            if (!local_xmldataset.Length()) {
                // Local ESD
                chain = new TChain("esdTree");
-               if (gSystem->AccessPathName("AliESDs.root")) 
-                  ::Error("CreateChain", "File: AliESDs.root not in current dir");
-               else chain->Add("AliESDs.root");
+               if (gSystem->AccessPathName("data/AliESDs.root")) 
+                  ::Error("AnalysisTrainNew.C::CreateChain", "File: AliESDs.root not in ./data dir");
+               else {
+                  if (!saveTrain) chain->Add("data/AliESDs.root");
+                  else            chain->Add("../data/AliESDs.root");
+               }   
             } else {
                // Interactive ESD
-               chain = CreateChainSingle(dataset, "esdTree");
+               chain = CreateChainSingle(local_xmldataset, "esdTree");
             }   
          }
          break;
@@ -543,8 +1127,8 @@ TChain *CreateChain(const char *mode, const char *plugin_mode)
          break;
       case 2:
          if (usePLUGIN) {
-            AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
-            AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
+//            AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
+//            AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
          } else {
             TString           treeName = "esdTree";
             if (iAODanalysis) treeName = "aodTree";
@@ -566,7 +1150,7 @@ TChain* CreateChainSingle(const char* xmlfile, const char *treeName)
    TAlienCollection * myCollection  = TAlienCollection::Open(xmlfile);
 
    if (!myCollection) {
-      ::Error("CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;
+      ::Error("AnalysisTrainNew.C::CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;
       return NULL ;
    }
 
@@ -584,14 +1168,15 @@ Int_t SetupPar(char* pararchivename)
    char processline[1024];
    if (gSystem->AccessPathName(Form("%s.par", pararchivename))) {
       if (!gSystem->AccessPathName(Form("%s/%s.par", gSystem->Getenv("ALICE_ROOT"),pararchivename))) {
-         ::Info("SetupPar", "Getting %s.par from $ALICE_ROOT", pararchivename);
+         ::Info("AnalysisTrainNew.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("SetupPar", "Cannot find %s.par", pararchivename);
+         ::Error("AnalysisTrainNew.C::SetupPar", "Cannot find %s.par", pararchivename);
          return -1;
       }   
    }
+   if (usePLUGIN && saveTrain) gSystem->Exec(Form("ln -s ../%s.par %s",pararchivename, train_name.Data()));
    gSystem->Exec(Form("tar xvzf %s.par", pararchivename));
 
    TString ocwd = gSystem->WorkingDirectory();
@@ -620,7 +1205,7 @@ Int_t SetupPar(char* pararchivename)
 }
 
 //______________________________________________________________________________
-AliAnalysisGrid* CreateAlienHandler(const char *plugin_mode)
+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
@@ -629,10 +1214,17 @@ AliAnalysisGrid* CreateAlienHandler(const char *plugin_mode)
    AliAnalysisAlien *plugin = new AliAnalysisAlien();
 // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
    plugin->SetRunMode(plugin_mode);
+   if (useProductionMode) plugin->SetProductionMode();
+   if (!outputSingleFolder.IsNull()) {
+      plugin->SetOutputSingleFolder(outputSingleFolder);
+      plugin->SetOutputToRunNo();
+   }   
+   plugin->SetJobTag(job_tag);
    plugin->SetNtestFiles(1);
-   plugin->SetPreferedSE("ALICE::NIHAM::FILE");
+//   plugin->SetPreferedSE("ALICE::NIHAM::File");
 // Set versions of used packages
-   plugin->SetAPIVersion("V2.4");
+//   plugin->SetAPIVersion("V2.4");
+   plugin->SetAPIVersion("V1.1x");
    plugin->SetROOTVersion(root_version);
    plugin->SetAliROOTVersion(aliroot_version);
 // Declare input data to be processed.
@@ -640,8 +1232,14 @@ AliAnalysisGrid* CreateAlienHandler(const char *plugin_mode)
 // Define production directory LFN
    plugin->SetGridDataDir(alien_datadir);
 // Set data search pattern
-   plugin->SetDataPattern("*ESDs.root");
+   if (runOnData) {
+      plugin->SetRunPrefix("000");
+      plugin->SetDataPattern("*ESDs/pass1/*ESDs.root");
+   } else {
+      plugin->SetDataPattern("*ESDs.root");
+   }   
 // ...then add run numbers to be considered
+//   if (!iAODanalysis) plugin->SetRunRange(run_range[0], run_range[1]);
    for (Int_t i=0; i<10; i++) {
       if (run_numbers[i]==0) break;
       plugin->AddRunNumber(run_numbers[i]);
@@ -653,13 +1251,15 @@ AliAnalysisGrid* CreateAlienHandler(const char *plugin_mode)
 //   plugin->AddDataFile("tag.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.
-   plugin->SetGridWorkingDir("analysisESD");
+   plugin->SetGridWorkingDir(train_name);
 // Declare alien output directory. Relative to working directory.
-   plugin->SetGridOutputDir("output"); // In this case will be $HOME/work/output
+   if (!alien_outdir.Length()) alien_outdir = Form("output_%s",train_name.Data());
+   plugin->SetGridOutputDir(alien_outdir);
 
    TString ana_sources = "";
    TString ana_add = "";
    if (usePAR && anaPars.Length()) {
+      printf("%s\n", anaPars.Data());
       TObjArray *arr;
       TObjString *objstr;
       arr = anaPars.Tokenize(" ");
@@ -667,6 +1267,12 @@ AliAnalysisGrid* CreateAlienHandler(const char *plugin_mode)
       while ((objstr=(TObjString*)next())) plugin->EnablePackage(objstr->GetString());
       delete arr;
    } 
+// Add external packages
+   if (iJETANdelta) {
+      plugin->AddExternalPackage("boost::v1_38_0");
+      plugin->AddExternalPackage("cgal::v3.3.1");
+      plugin->AddExternalPackage("fastjet::v2.4.0");
+   }   
    
 // Declare the analysis source files names separated by blancs. To be compiled runtime
 // using ACLiC on the worker nodes.
@@ -680,28 +1286,216 @@ AliAnalysisGrid* CreateAlienHandler(const char *plugin_mode)
 // Declare the output file names separated by blancs.
 // (can be like: file.root or file.root@ALICE::Niham::File)
    plugin->SetDefaultOutputs();
-   plugin->SetMergeExcludes("AliAOD.root");
-//   plugin->SetOutputFiles("AliAOD.root");
+   plugin->SetMergeExcludes(mergeExclude);
+   plugin->SetMaxMergeFiles(maxMergeFiles);
+   plugin->SetNrunsPerMaster(nRunsPerMaster);
 // Optionally define the files to be archived.
-//   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:*.root@ALICE::NIHAM::File");
-   plugin->SetOutputArchive("log_archive.zip:stdout,stderr");
+//   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:AliAOD.root,AOD.tag.root@ALICE::NIHAM::File");
+   
+   
+   // 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;
+         listaods += ",";
+         listaods += "pyxsec_hists.root";
+      } else {
+         if (!strcmp(filename, "pyxsec_hists.root")) continue;
+         if (listhists.Contains(filename)) continue;
+         if (listhists.Length()) listhists += ",";
+         listhists += filename;
+      }
+   }
+   if (mgr->GetExtraFiles().Length()) {
+      if (listaods.Length()) listaods += ",";
+      listaods += mgr->GetExtraFiles();
+      listaods.ReplaceAll(" ", ",");
+   }
+   if (listhists.Length()) listhists = Form("hist_archive.zip:%s@%s", listhists.Data(), outputStorages.Data());
+   if (listaods.Length())  listaods  = Form("aod_archive.zip:%s@%s", listaods.Data(), outputStorages.Data());
+   if (!listhists.Length() && !listaods.Length()) {
+      ::Fatal("AnalysisTrainNew", "No task output !");
+   }
+   TString outputArchive = Form("log_archive.zip:stderr@%s", outputStorages.Data());
+   if (listaods.Length()) {
+      outputArchive += " ";
+      outputArchive += listaods;
+   }   
+   if (listhists.Length()) {
+      outputArchive += " ";
+      outputArchive += listhists;
+   }   
+// Set friends
+//   if (iAODanalysis && iPWG3d2h) 
+//      plugin->SetFriendChainName("AliAOD.VertexingHF.root");
+//   plugin->SetOutputArchive(outputArchive);
 // Optionally set a name for the generated analysis macro (default MyAnalysis.C)
-   plugin->SetAnalysisMacro("testAnalysis.C");
+   plugin->SetAnalysisMacro(Form("%s.C", train_name.Data()));
 // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
-   plugin->SetSplitMaxInputFileNumber(50);
+   plugin->SetSplitMaxInputFileNumber(nFilesPerJob);
 // 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);
+   plugin->SetTTL(70000);
 // Optionally set input format (default xml-single)
    plugin->SetInputFormat("xml-single");
 // Optionally modify the name of the generated JDL (default analysis.jdl)
-   plugin->SetJDLName("testAnalysis.jdl");
+   plugin->SetJDLName(Form("%s.jdl", train_name.Data()));
+// Optionally modify the executable name (default analysis.sh)
+   plugin->SetExecutable(Form("%s.sh", train_name.Data()));
 // Optionally modify job price (default 1)
    plugin->SetPrice(1);      
+// Merge via JDL
+   plugin->SetMergeViaJDL(useMergeViaJDL);
+// Use fastread option
+   plugin->SetFastReadOption(useFastReadOption);
+// UseOverwrite mode
+   plugin->SetOverwriteMode(useOverwriteMode);   
+   plugin->SetExecutableCommand("aliroot -b -q");
 // Optionally modify split mode (default 'se')    
    plugin->SetSplitMode("se");
    return plugin;
 }
+
+//______________________________________________________________________________
+void WriteConfig()
+{
+// Write train configuration in a file. The file name has the format:
+// train_[trainName]_ddMonthyyyy_time.C
+   if (useDATE) {
+      gSystem->Exec("date +%d%b%Y_%Hh%M > date.tmp");
+      ifstream fdate("date.tmp");
+      if (!fdate.is_open()) {
+         ::Error("AnalysisTrainNew.C::Export","Could not generate file name");
+         return;
+      }
+      const char date[64];
+      fdate.getline(date,64);
+      fdate.close();
+      gSystem->Exec("rm date.tmp");
+      train_name = Form("%s_%s", train_name.Data(), date);
+   }   
+   TString cdir = gSystem->WorkingDirectory();
+   gSystem->MakeDirectory(train_name);
+   gSystem->ChangeDirectory(train_name);
+   ofstream out;
+   out.open(Form("%sConfig.C",train_name.Data()), ios::out); 
+   if (out.bad()) {
+      ::Error("AnalysisTrainNew.C::Export", "Cannot open ConfigTrain.C for writing");
+      return;
+   }
+   out << "{" << endl;
+   out << "   train_name      = " << "\"" << train_name.Data() << "\";" << endl;
+   out << "   proof_cluster   = " << "\"" << proof_cluster.Data() << "\";" << endl;
+   out << "   useAFPAR        = " << useAFPAR << ";" << endl;
+   if (useAFPAR) 
+      out << "   AFversion       = " << AFversion.Data() << ";" << endl;
+   out << "   proof_dataset   = " << "\"" << proof_dataset.Data() << "\";" << endl;
+   out << "   usePLUGIN       = " << usePLUGIN << ";" << endl;
+   out << "   usePAR          = " << usePAR << ";" << endl;
+   out << "   useCPAR         = " << useCPAR << ";" << endl;
+   out << "   root_version    = " << "\"" << root_version.Data() << "\";" << endl;
+   out << "   aliroot_version = " << "\"" << aliroot_version.Data() << "\";" << endl;
+   out << "   alien_datadir   = " << "\"" << alien_datadir.Data() << "\";" << endl;
+   if (!alien_outdir.Length()) alien_outdir = Form("output_%s",train_name.Data());
+   out << "   alien_outdir    = " << "\"" << alien_outdir.Data() << "\";" << endl;
+   out << "   maxMergeFiles   = " << maxMergeFiles << ";" << endl;
+   out << "   mergeExclude    = " << "\"" << mergeExclude.Data() << "\";" << endl;
+   out << "   nRunsPerMaster  = " << nRunsPerMaster << ";" << endl;
+   out << "   nFilesPerJob    = " << nFilesPerJob << ";" << endl;
+//   for (Int_t i=0; i<10; i++) {
+//      if (run_numbers[i]) 
+//         out << "   run_numbers[" << i << "]  = " << run_numbers[i] << ";" << endl;
+//   }
+//   out << "   run_range[0]    = " << run_range[0] << ";" << endl;
+//   out << "   run_range[1]    = " << run_range[1] << ";" << endl;
+   out << "   usePhysicsSelection = " << usePhysicsSelection << ";" << endl;
+   out << "   useTender       = " << useTender << ";" << endl;
+   out << "   useMergeViaJDL  = " << useMergeViaJDL << ";" << endl;
+   out << "   useOverwriteMode  = " << useOverwriteMode << ";" << endl;
+   out << "   useFastReadOption = " << useFastReadOption << ";" << endl;
+   out << "   useDBG          = " << useDBG << ";" << endl;
+   out << "   useMC           = " << useMC << ";" << endl;
+   out << "   useTAGS         = " << useTAGS << ";" << endl;
+   out << "   useKFILTER      = " << useKFILTER << ";" << endl;
+   out << "   useTR           = " << useTR << ";" << endl;
+   out << "   useCORRFW       = " << useCORRFW << ";" << endl;
+   out << "   useAODTAGS      = " << useAODTAGS << ";" << endl;
+   out << "   saveTrain       = " << "kFALSE;" << endl << endl;
+   out << "   // Analysis modules" << endl;
+   out << "   iAODanalysis    = " << iAODanalysis << ";" << endl;
+   out << "   iAODhandler     = " << iAODhandler << ";" << endl;
+   out << "   iESDfilter      = " << iESDfilter << ";" << endl;
+   out << "   iMUONcopyAOD    = " << iMUONcopyAOD << ";" << endl;
+   out << "   iJETAN          = " << iJETAN << ";" << endl;
+   out << "   iJETANdelta     = " << iJETANdelta << ";" << endl;
+   out << "   iPWG4partcorr   = " << iPWG4partcorr << ";" << endl;
+   out << "   iPWG4gammaconv  = " << iPWG4gammaconv << ";" << endl;
+   out << "   iPWG4omega3pi   = " << iPWG4omega3pi << ";" << endl;
+   out << "   iPWG3vertexing  = " << iPWG3vertexing << ";" << endl;   
+   out << "   iPWG3hfe        = " << iPWG3hfe << ";" << endl;   
+   out << "   iPWG3d2h        = " << iPWG3d2h << ";" << endl;   
+   out << "     iPWG3d0mass       = " << iPWG3d0mass << ";" << endl;
+   out << "     iPWG3d0massLS     = " << iPWG3d0massLS << ";" << endl;
+   out << "     iPWG3dplus        = " << iPWG3dplus << ";" << endl;
+   out << "     iPWG3LSd0         = " << iPWG3LSd0 << ";" << endl;
+   out << "     iPWG3LSjpsi       = " << iPWG3LSjpsi << ";" << endl;
+   out << "     iPWG3CFd0         = " << iPWG3CFd0 << ";" << endl;
+   out << "     iPWG3promptd0     = " << iPWG3promptd0 << ";" << endl;
+   out << "   iPWG3MuonTrain      = " << iPWG3MuonTrain << ";" << endl;   
+   out << "   iPWG2femto      = " << iPWG2femto << ";" << endl;
+   out << "   iPWG2spectra    = " << iPWG2spectra << ";" << endl;
+   out << "     iPWG2protons      = " << iPWG2protons << ";" << endl;
+   out << "     iPWG2checkcascade = " << iPWG2checkcascade << ";" << endl;
+   out << "     iPWG2perfcascade  = " << iPWG2perfcascade << ";" << endl;
+   out << "     iPWG2checkv0      = " << iPWG2checkv0 << ";" << endl;
+   out << "     iPWG2strange      = " << iPWG2strange << ";" << endl;
+   out << "     iPWG2central      = " << iPWG2central << ";" << endl;
+   out << "   iPWG2flow       = " << iPWG2flow << ";" << endl;
+   out << "   iPWG2res        = " << iPWG2res << ";" << endl;
+   out << "     iPWG2rsneff   = " << iPWG2rsneff << ";" << endl;
+   out << "   iPWG2kink       = " << iPWG2kink << ";" << endl;
+   out << "     iPWG2kinkESDMC    = " << iPWG2kinkESDMC << ";" << endl;
+   out << "     iPWG2kinkLSKstar  = " << iPWG2kinkLSKstar << ";" << endl;
+   out << "     iPWG2kinkLSL1520  = " << iPWG2kinkLSL1520 << ";" << endl;
+   out << "     iPWG2kinkLSPhi    = " << iPWG2kinkLSPhi << ";" << endl;
+   out << "     iPWG2kinkKstarESD = " << iPWG2kinkKstarESD << ";" << endl;
+   out << "     iPWG2kinkKstarMC  = " << iPWG2kinkKstarMC << ";" << endl;
+   out << "     iPWG2kinkL1520ESD = " << iPWG2kinkL1520ESD << ";" << endl;
+   out << "     iPWG2kinkL1520MC  = " << iPWG2kinkL1520MC << ";" << endl;
+   out << "     iPWG2kinkPhiESD   = " << iPWG2kinkPhiESD << ";" << endl;
+   out << "     iPWG2kinkPhiMC    = " << iPWG2kinkPhiMC << ";" << endl;
+   out << "   iPWG2unicor     = " << iPWG2unicor << ";" << endl;
+   out << "   iPWG2evchar     = " << iPWG2evchar << ";" << endl;
+   out << "   iPWG2forward    = " << iPWG2forward << ";" << endl << endl;
+   out << "// Configuration fot the wagons" << endl;
+   out << "   configPWG2femto = \"" << configPWG2femto << "\";" << endl;
+   out << "   configPWG3d2h   = \"" << configPWG3d2h << "\";" << endl;
+   out << "}" << endl;
+   ::Info("AnalysisTrainNew.C::WriteConfig", "Train configuration wrote to file %s", Form("config_%s.C", train_name.Data()));
+   gSystem->ChangeDirectory(cdir);
+}   
+
+//______________________________________________________________________________
+Bool_t LoadConfig(const char *filename)
+{
+// Read train configuration from file
+   if (gSystem->AccessPathName(filename)) {
+      ::Error("AnalysisTrainNew.C::LoadConfig", "Config file name not found");
+      return kFALSE;
+   }   
+   gROOT->ProcessLine(Form(".x %s", filename));
+   ::Info("AnalysisTrainNew.C::LoadConfig", "Train configuration loaded from file %s", filename);
+   return kTRUE;
+}