]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - ANALYSIS/AliAnalysisAlien.cxx
From Christian Klein-Boesing: New method :
[u/mrichter/AliRoot.git] / ANALYSIS / AliAnalysisAlien.cxx
index a7974283c11527a73ae8e410815e3525bc2f860c..c34875086c24b663fe1cfb49724671af08e85e3f 100644 (file)
@@ -54,16 +54,21 @@ AliAnalysisAlien::AliAnalysisAlien()
                   fMaxMergeFiles(0),
                   fNsubmitted(0),
                   fProductionMode(0),
+                  fOutputToRunNo(0),
                   fRunNumbers(),
                   fExecutable(),
+                  fExecutableCommand(),
                   fArguments(),
+                  fExecutableArgs(),
                   fAnalysisMacro(),
                   fAnalysisSource(),
+                  fAdditionalRootLibs(),
                   fAdditionalLibs(),
                   fSplitMode(),
                   fAPIVersion(),
                   fROOTVersion(),
                   fAliROOTVersion(),
+                  fExternalPackages(),
                   fUser(),
                   fGridWorkingDir(),
                   fGridDataDir(),
@@ -78,6 +83,9 @@ AliAnalysisAlien::AliAnalysisAlien()
                   fIncludePath(),
                   fCloseSE(),
                   fFriendChainName(),
+                  fJobTag(),
+                  fOutputSingle(),
+                  fRunPrefix(),
                   fInputFiles(0),
                   fPackages(0)
 {
@@ -99,16 +107,21 @@ AliAnalysisAlien::AliAnalysisAlien(const char *name)
                   fMaxMergeFiles(0),
                   fNsubmitted(0),
                   fProductionMode(0),
+                  fOutputToRunNo(0),
                   fRunNumbers(),
                   fExecutable(),
+                  fExecutableCommand(),
                   fArguments(),
+                  fExecutableArgs(),
                   fAnalysisMacro(),
                   fAnalysisSource(),
+                  fAdditionalRootLibs(),
                   fAdditionalLibs(),
                   fSplitMode(),
                   fAPIVersion(),
                   fROOTVersion(),
                   fAliROOTVersion(),
+                  fExternalPackages(),
                   fUser(),
                   fGridWorkingDir(),
                   fGridDataDir(),
@@ -123,6 +136,9 @@ AliAnalysisAlien::AliAnalysisAlien(const char *name)
                   fIncludePath(),
                   fCloseSE(),
                   fFriendChainName(),
+                  fJobTag(),
+                  fOutputSingle(),
+                  fRunPrefix(),
                   fInputFiles(0),
                   fPackages(0)
 {
@@ -144,16 +160,21 @@ AliAnalysisAlien::AliAnalysisAlien(const AliAnalysisAlien& other)
                   fMaxMergeFiles(other.fMaxMergeFiles),
                   fNsubmitted(other.fNsubmitted),
                   fProductionMode(other.fProductionMode),
+                  fOutputToRunNo(other.fOutputToRunNo),
                   fRunNumbers(other.fRunNumbers),
                   fExecutable(other.fExecutable),
+                  fExecutableCommand(other.fExecutableCommand),
                   fArguments(other.fArguments),
+                  fExecutableArgs(other.fExecutableArgs),
                   fAnalysisMacro(other.fAnalysisMacro),
                   fAnalysisSource(other.fAnalysisSource),
+                  fAdditionalRootLibs(other.fAdditionalRootLibs),
                   fAdditionalLibs(other.fAdditionalLibs),
                   fSplitMode(other.fSplitMode),
                   fAPIVersion(other.fAPIVersion),
                   fROOTVersion(other.fROOTVersion),
                   fAliROOTVersion(other.fAliROOTVersion),
+                  fExternalPackages(other.fExternalPackages),
                   fUser(other.fUser),
                   fGridWorkingDir(other.fGridWorkingDir),
                   fGridDataDir(other.fGridDataDir),
@@ -168,6 +189,9 @@ AliAnalysisAlien::AliAnalysisAlien(const AliAnalysisAlien& other)
                   fIncludePath(other.fIncludePath),
                   fCloseSE(other.fCloseSE),
                   fFriendChainName(other.fFriendChainName),
+                  fJobTag(other.fJobTag),
+                  fOutputSingle(other.fOutputSingle),
+                  fRunPrefix(other.fRunPrefix),
                   fInputFiles(0),
                   fPackages(0)
 {
@@ -217,16 +241,21 @@ AliAnalysisAlien &AliAnalysisAlien::operator=(const AliAnalysisAlien& other)
       fMaxMergeFiles           = other.fMaxMergeFiles;
       fNsubmitted              = other.fNsubmitted;
       fProductionMode          = other.fProductionMode;
+      fOutputToRunNo           = other.fOutputToRunNo;
       fRunNumbers              = other.fRunNumbers;
       fExecutable              = other.fExecutable;
+      fExecutableCommand       = other.fExecutableCommand;
       fArguments               = other.fArguments;
+      fExecutableArgs          = other.fExecutableArgs;
       fAnalysisMacro           = other.fAnalysisMacro;
       fAnalysisSource          = other.fAnalysisSource;
+      fAdditionalRootLibs      = other.fAdditionalRootLibs;
       fAdditionalLibs          = other.fAdditionalLibs;
       fSplitMode               = other.fSplitMode;
       fAPIVersion              = other.fAPIVersion;
       fROOTVersion             = other.fROOTVersion;
       fAliROOTVersion          = other.fAliROOTVersion;
+      fExternalPackages        = other.fExternalPackages;
       fUser                    = other.fUser;
       fGridWorkingDir          = other.fGridWorkingDir;
       fGridDataDir             = other.fGridDataDir;
@@ -241,6 +270,9 @@ AliAnalysisAlien &AliAnalysisAlien::operator=(const AliAnalysisAlien& other)
       fIncludePath             = other.fIncludePath;
       fCloseSE                 = other.fCloseSE;
       fFriendChainName         = other.fFriendChainName;
+      fJobTag                  = other.fJobTag;
+      fOutputSingle            = other.fOutputSingle;
+      fRunPrefix               = other.fRunPrefix;
       if (other.fInputFiles) {
          fInputFiles = new TObjArray();
          TIter next(other.fInputFiles);
@@ -273,7 +305,15 @@ void AliAnalysisAlien::AddRunNumber(Int_t run)
 {
 // Add a run number to the list of runs to be processed.
    if (fRunNumbers.Length()) fRunNumbers += " ";
-   fRunNumbers += Form("%d", run);
+   fRunNumbers += Form("%s%d", fRunPrefix.Data(), run);
+}   
+
+//______________________________________________________________________________
+void AliAnalysisAlien::AddRunNumber(const char* run)
+{
+// Add a run number to the list of runs to be processed.
+   if (fRunNumbers.Length()) fRunNumbers += " ";
+   fRunNumbers += run;
 }   
 
 //______________________________________________________________________________
@@ -284,7 +324,15 @@ void AliAnalysisAlien::AddDataFile(const char *lfn)
    if (!fInputFiles) fInputFiles = new TObjArray();
    fInputFiles->Add(new TObjString(lfn));
 }
-   
+
+//______________________________________________________________________________
+void AliAnalysisAlien::AddExternalPackage(const char *package)
+{
+// Adds external packages w.r.t to the default ones (root,aliroot and gapi)
+   if (fExternalPackages) fExternalPackages += " ";
+   fExternalPackages += package;
+}   
+      
 //______________________________________________________________________________
 Bool_t AliAnalysisAlien::Connect()
 {
@@ -318,17 +366,20 @@ void AliAnalysisAlien::CdWork()
    } 
    TString homedir = gGrid->GetHomeDirectory();
    TString workdir = homedir + fGridWorkingDir;
-   if (!gGrid->Cd(workdir)) {
-      gGrid->Cd(homedir);
-      if (gGrid->Mkdir(workdir)) {
-         gGrid->Cd(fGridWorkingDir);
-         Info("CreateJDL", "\n#####   Created alien working directory %s", fGridWorkingDir.Data());
-      } else {
-         Warning("CreateJDL", "Working directory %s cannot be created.\n Using %s instead.",
-                 workdir.Data(), homedir.Data());
-         fGridWorkingDir = "";
-      }          
-   }      
+   if (DirectoryExists(workdir)) {
+      gGrid->Cd(workdir);
+      return;
+   }   
+   // Work directory not existing - create it
+   gGrid->Cd(homedir);
+   if (gGrid->Mkdir(workdir)) {
+      gGrid->Cd(fGridWorkingDir);
+      Info("CreateJDL", "\n#####   Created alien working directory %s", fGridWorkingDir.Data());
+   } else {
+      Warning("CreateJDL", "Working directory %s cannot be created.\n Using %s instead.",
+              workdir.Data(), homedir.Data());
+      fGridWorkingDir = "";
+   }          
 }
 
 //______________________________________________________________________________
@@ -392,7 +443,7 @@ Bool_t AliAnalysisAlien::CheckInputData()
       Error("CkeckInputData", "AliEn path to base data directory must be set.\n = Use: SetGridDataDir()");
       return kFALSE;
    }
-   if (!gGrid->Cd(fGridDataDir)) {
+   if (!DirectoryExists(fGridDataDir)) {
       Error("CheckInputData", "Data directory %s not existing.", fGridDataDir.Data());
       return kFALSE;
    }
@@ -409,7 +460,7 @@ Bool_t AliAnalysisAlien::CheckInputData()
    TObjArray *arr;
    TObjString *os;
    Int_t nruns = 0;
-   TString schunk;
+   TString schunk, schunk2;
    TString path;
    if (!checked) {
       checked = kTRUE;
@@ -426,8 +477,8 @@ Bool_t AliAnalysisAlien::CheckInputData()
       TIter next(arr);
       while ((os=(TObjString*)next())) {
          path = Form("%s/%s ", fGridDataDir.Data(), os->GetString().Data());
-         if (!gGrid->Cd(path)) {
-            Warning("CheckInputData", "Run number %s not found in path: %s", os->GetString().Data(), path.Data());
+         if (!DirectoryExists(path)) {
+            Warning("CheckInputData", "Run number %s not found in path: <%s>", os->GetString().Data(), path.Data());
             continue;
          }
          path = Form("%s/%s.xml", workdir.Data(),os->GetString().Data());
@@ -453,12 +504,12 @@ Bool_t AliAnalysisAlien::CheckInputData()
    } else {
       Info("CheckDataType", "Using run range [%d, %d]", fRunRange[0], fRunRange[1]);
       for (Int_t irun=fRunRange[0]; irun<=fRunRange[1]; irun++) {
-         path = Form("%s/%d ", fGridDataDir.Data(), irun);
-         if (!gGrid->Cd(path)) {
-            Warning("CheckInputData", "Run number %d not found in path: %s", irun, path.Data());
+         path = Form("%s/%s%d ", fGridDataDir.Data(), fRunPrefix.Data(), irun);
+         if (!DirectoryExists(path)) {
+//            Warning("CheckInputData", "Run number %d not found in path: <%s>", irun, path.Data());
             continue;
          }
-         path = Form("%s/%d.xml", workdir.Data(),irun);
+         path = Form("%s/%s%d.xml", workdir.Data(),fRunPrefix.Data(),irun);
          TString msg = "\n#####   file: ";
          msg += path;
          msg += " type: xml_collection;";
@@ -466,17 +517,22 @@ Bool_t AliAnalysisAlien::CheckInputData()
          else          msg += " using_tags: No";
          Info("CheckDataType", msg.Data());
          if (fNrunsPerMaster<2) {
-            AddDataFile(Form("%d.xml",irun));
+            AddDataFile(Form("%s%d.xml",fRunPrefix.Data(),irun));
          } else {
             nruns++;
             if (((nruns-1)%fNrunsPerMaster) == 0) {
-               schunk = Form("%d", irun);
+               schunk = Form("%s%d", fRunPrefix.Data(),irun);
             }
+            schunk2 = Form("_%s%d.xml", fRunPrefix.Data(), irun);
             if ((nruns%fNrunsPerMaster)!=0 && irun != fRunRange[1]) continue;
-            schunk += Form("_%d.xml",  irun);
+            schunk += schunk2;
             AddDataFile(schunk);
          }   
       }
+      if (!fInputFiles) {
+         schunk += schunk2;
+         AddDataFile(schunk);
+      }   
    }
    return kTRUE;      
 }   
@@ -505,20 +561,20 @@ Bool_t AliAnalysisAlien::CreateDataset(const char *pattern)
    TString file;
    TString path;
    Int_t nruns = 0;
-   TString schunk;
+   TString schunk, schunk2;
    TGridCollection *cbase=0, *cadd=0;
    if (!fRunNumbers.Length() && !fRunRange[0]) {
       if (fInputFiles && fInputFiles->GetEntries()) return kTRUE;
       // Make a single data collection from data directory.
       path = fGridDataDir;
-      if (!gGrid->Cd(path)) {
+      if (!DirectoryExists(path)) {
          Error("CreateDataset", "Path to data directory %s not valid",fGridDataDir.Data());
          return kFALSE;
       }   
-      CdWork();
+//      CdWork();
       if (TestBit(AliAnalysisGrid::kTest)) file = "wn.xml";
       else file = Form("%s.xml", gSystem->BaseName(path));
-      if (gSystem->AccessPathName(file)) {
+      if (gSystem->AccessPathName(file) || TestBit(AliAnalysisGrid::kTest)) {
          command = "find ";
          command += options;
          command += path;
@@ -550,8 +606,8 @@ Bool_t AliAnalysisAlien::CreateDataset(const char *pattern)
       TIter next(arr);
       while ((os=(TObjString*)next())) {
          path = Form("%s/%s ", fGridDataDir.Data(), os->GetString().Data());
-         if (!gGrid->Cd(path)) continue;
-         CdWork();
+         if (!DirectoryExists(path)) continue;
+//         CdWork();
          if (TestBit(AliAnalysisGrid::kTest)) file = "wn.xml";
          else file = Form("%s.xml", os->GetString().Data());
          // If local collection file does not exist, create it via 'find' command.
@@ -599,9 +655,9 @@ Bool_t AliAnalysisAlien::CreateDataset(const char *pattern)
                Info("CreateDataset", "\n#####   Dataset %s exist. Skipping creation...", schunk.Data());
                continue;
             }        
-            printf("Exporting merged collection <%s> and copying to AliEn.\n", schunk.Data());
+            printf("Exporting merged collection <%s> and copying to AliEn\n", schunk.Data());
             cbase->ExportXML(Form("file://%s", schunk.Data()),kFALSE,kFALSE, schunk, "Merged runs");
-            TFile::Cp(Form("file:%s",file.Data()), Form("alien://%s/%s",workdir.Data(), file.Data()));
+            TFile::Cp(Form("file:%s",schunk.Data()), Form("alien://%s/%s",workdir.Data(), schunk.Data()));
             if (!FileExists(schunk)) {
                Error("CreateDataset", "Copy command did NOT succeed for %s", schunk.Data());
                delete arr;
@@ -613,11 +669,11 @@ Bool_t AliAnalysisAlien::CreateDataset(const char *pattern)
    } else {
       // Process a full run range.
       for (Int_t irun=fRunRange[0]; irun<=fRunRange[1]; irun++) {
-         path = Form("%s/%d ", fGridDataDir.Data(), irun);
-         if (!gGrid->Cd(path)) continue;
-         CdWork();
+         path = Form("%s/%s%d ", fGridDataDir.Data(), fRunPrefix.Data(), irun);
+         if (!DirectoryExists(path)) continue;
+//         CdWork();
          if (TestBit(AliAnalysisGrid::kTest)) file = "wn.xml";
-         else file = Form("%d.xml", irun);
+         else file = Form("%s%d.xml", fRunPrefix.Data(), irun);
          if (FileExists(file) && fNrunsPerMaster<2 && !TestBit(AliAnalysisGrid::kTest)) {
             Info("CreateDataset", "\n#####   Dataset %s exist. Skipping creation...", file.Data());
 //            gGrid->Rm(file); 
@@ -655,17 +711,18 @@ Bool_t AliAnalysisAlien::CreateDataset(const char *pattern)
             if (FileExists(fInputFiles->At(nchunk)->GetName())) continue;
             printf("   Merging collection <%s> into %d runs chunk...\n",file.Data(),fNrunsPerMaster);
             if (((nruns-1)%fNrunsPerMaster) == 0) {
-               schunk = Form("%d", irun);
+               schunk = Form("%s%d", fRunPrefix.Data(), irun);
                cbase = (TGridCollection*)gROOT->ProcessLine(Form("new TAlienCollection(\"%s\", 1000000);",file.Data()));
             } else {
                cadd = (TGridCollection*)gROOT->ProcessLine(Form("new TAlienCollection(\"%s\", 1000000);",file.Data()));
                cbase->Add(cadd);
                delete cadd;
             }
-            if ((nruns%fNrunsPerMaster)!=0 && irun!=fRunRange[1]) {
+            schunk2 = Form("%s_%s%d.xml", schunk.Data(), fRunPrefix.Data(), irun);
+            if ((nruns%fNrunsPerMaster)!=0 && irun!=fRunRange[1] && schunk2 != fInputFiles->Last()->GetName()) {
                continue;
             }   
-            schunk += Form("_%d.xml", irun);
+            schunk = schunk2;
             if (FileExists(schunk)) {
                Info("CreateDataset", "\n#####   Dataset %s exist. Skipping creation...", schunk.Data());
                continue;
@@ -724,7 +781,7 @@ Bool_t AliAnalysisAlien::CreateJDL()
          error = kTRUE;
       } else {
          if (!fGridOutputDir.Contains("/")) fGridOutputDir = Form("%s/%s", workdir.Data(), fGridOutputDir.Data());
-         if (!gGrid->Cd(fGridOutputDir)) {
+         if (!DirectoryExists(fGridOutputDir)) {
             if (gGrid->Mkdir(fGridOutputDir)) {
                Info("CreateJDL", "\n#####   Created alien output directory %s", fGridOutputDir.Data());
             } else {
@@ -739,6 +796,8 @@ Bool_t AliAnalysisAlien::CreateJDL()
       // Set JDL fields
       fGridJDL->SetValue("User", Form("\"%s\"", fUser.Data()));
       fGridJDL->SetExecutable(fExecutable);
+      if (!fArguments.IsNull())
+         fGridJDL->SetArguments(fArguments, "Arguments for the executable command");
 //      fGridJDL->SetTTL((UInt_t)fTTL);
       fGridJDL->SetValue("TTL", Form("\"%d\"", fTTL));
       if (fMaxInitFailed > 0) 
@@ -754,10 +813,24 @@ Bool_t AliAnalysisAlien::CreateJDL()
          fGridJDL->AddToPackages("ROOT", fROOTVersion);
       if (fAPIVersion.Length()) 
          fGridJDL->AddToPackages("APISCONFIG", fAPIVersion);
+      if (!fExternalPackages.IsNull()) {
+         arr = fExternalPackages.Tokenize(" ");
+         TIter next(arr);
+         while ((os=(TObjString*)next())) {
+            TString pkgname = os->GetString();
+            Int_t index = pkgname.Index("::");
+            TString pkgversion = pkgname(index+2, pkgname.Length());
+            pkgname.Remove(index);
+            fGridJDL->AddToPackages(pkgname, pkgversion);
+         }   
+         delete arr;   
+      }   
       fGridJDL->SetInputDataListFormat(fInputFormat);
       fGridJDL->SetInputDataList("wn.xml");
       fGridJDL->AddToInputSandbox(Form("LF:%s/%s", workdir.Data(), fAnalysisMacro.Data()));
-      fGridJDL->AddToInputSandbox(Form("LF:%s/analysis.root", workdir.Data()));
+      TString analysisFile = fExecutable;
+      analysisFile.ReplaceAll(".sh", ".root");
+      fGridJDL->AddToInputSandbox(Form("LF:%s/%s", workdir.Data(),analysisFile.Data()));
       if (IsUsingTags() && !gSystem->AccessPathName("ConfigureCuts.C"))
          fGridJDL->AddToInputSandbox(Form("LF:%s/ConfigureCuts.C", workdir.Data()));
       if (fAdditionalLibs.Length()) {
@@ -788,6 +861,10 @@ Bool_t AliAnalysisAlien::CreateJDL()
       arr = fOutputFiles.Tokenize(" ");
       TIter next(arr);
       while ((os=(TObjString*)next())) {
+         // Ignore ouputs in jdl that are also in outputarchive
+         TString sout = os->GetString();
+         if (sout.Index("@")>0) sout.Remove(sout.Index("@"));
+         if (fOutputArchive.Contains(sout)) continue;
          if (!os->GetString().Contains("@") && fCloseSE.Length())
             fGridJDL->AddToOutputSandbox(Form("%s@%s",os->GetString().Data(), fCloseSE.Data())); 
          else
@@ -796,13 +873,39 @@ Bool_t AliAnalysisAlien::CreateJDL()
       delete arr;
 //      fGridJDL->SetPrice((UInt_t)fPrice);
       fGridJDL->SetValue("Price", Form("\"%d\"", fPrice));
-      fGridJDL->SetValidationCommand(Form("%s/validate.sh", workdir.Data()));
+      TString validationScript = fExecutable;
+      validationScript.ReplaceAll(".sh", "_validation.sh");
+      fGridJDL->SetValidationCommand(Form("%s/%s", workdir.Data(),validationScript.Data()));
       if (fMasterResubmitThreshold) fGridJDL->SetValue("MasterResubmitThreshold", Form("\"%d%%\"", fMasterResubmitThreshold));
       // Write a jdl with 2 input parameters: collection name and output dir name.
       WriteJDL(copy);
    }
    // Copy jdl to grid workspace   
    if (copy) {
+      // Check if an output directory was defined and valid
+      if (!fGridOutputDir.Length()) {
+         Error("CreateJDL", "You must define AliEn output directory");
+         return kFALSE;
+      } else {
+         if (!fGridOutputDir.Contains("/")) fGridOutputDir = Form("%s/%s", workdir.Data(), fGridOutputDir.Data());
+         if (!DirectoryExists(fGridOutputDir)) {
+            if (gGrid->Mkdir(fGridOutputDir)) {
+               Info("CreateJDL", "\n#####   Created alien output directory %s", fGridOutputDir.Data());
+            } else {
+               Error("CreateJDL", "Could not create alien output directory %s", fGridOutputDir.Data());
+               return kFALSE;
+            }
+         }
+         gGrid->Cd(workdir);
+      }   
+      if (TestBit(AliAnalysisGrid::kSubmit)) {
+         Info("CreateJDL", "\n#####   Copying JDL file <%s> to your AliEn output directory", fJDLName.Data());
+         TString locjdl = Form("%s/%s", fGridOutputDir.Data(),fJDLName.Data());
+         if (fProductionMode)
+            locjdl = Form("%s/%s", workdir.Data(),fJDLName.Data());
+         if (FileExists(locjdl)) gGrid->Rm(locjdl);
+         TFile::Cp(Form("file:%s",fJDLName.Data()), Form("alien://%s", locjdl.Data()));
+      }
       if (fAdditionalLibs.Length()) {
          arr = fAdditionalLibs.Tokenize(" ");
          TObjString *os;
@@ -843,11 +946,19 @@ Bool_t AliAnalysisAlien::WriteJDL(Bool_t copy)
       TIter next(fInputFiles);
       while ((os=(TObjString*)next()))
          fGridJDL->AddToInputDataCollection(Form("LF:%s,nodownload", os->GetString().Data()));
-      fGridJDL->SetOutputDirectory(Form("%s/#alien_counter_03i#", fGridOutputDir.Data()));
+      if (!fOutputSingle.IsNull())
+         fGridJDL->SetOutputDirectory(Form("#alienfulldir#/%s",fOutputSingle.Data()));
+      else                                    
+         fGridJDL->SetOutputDirectory(Form("%s/#alien_counter_03i#", fGridOutputDir.Data()));
    } else {
       // One jdl to be submitted with 2 input parameters: data collection name and output dir prefix
       fGridJDL->AddToInputDataCollection(Form("LF:%s/$1,nodownload", workdir.Data()));
-      fGridJDL->SetOutputDirectory(Form("%s/$2#alien_counter_03i#", fGridOutputDir.Data()));
+      if (!fOutputSingle.IsNull()) {
+         if (!fOutputToRunNo) fGridJDL->SetOutputDirectory(Form("#alienfulldir#/%s",fOutputSingle.Data()));
+         else fGridJDL->SetOutputDirectory(Form("%s/$2",fGridOutputDir.Data()));
+      } else {   
+         fGridJDL->SetOutputDirectory(Form("%s/$2/#alien_counter_03i#", fGridOutputDir.Data()));
+      }   
    }
       
 
@@ -857,7 +968,7 @@ Bool_t AliAnalysisAlien::WriteJDL(Bool_t copy)
    index = sjdl.Index("Executable");
    if (index >= 0) sjdl.Insert(index, "\n# This is the startup script\n");
    index = sjdl.Index("Split ");
-   if (index >= 0) sjdl.Insert(index, "\n# We split per storage element\n");
+   if (index >= 0) sjdl.Insert(index, "\n# We split per SE or file\n");
    index = sjdl.Index("SplitMaxInputFileNumber");
    if (index >= 0) sjdl.Insert(index, "\n# We want each subjob to get maximum this number of input files\n");
    index = sjdl.Index("InputDataCollection");
@@ -900,7 +1011,7 @@ Bool_t AliAnalysisAlien::WriteJDL(Bool_t copy)
    sjdl.ReplaceAll("\n\n", "\n");
    sjdl.ReplaceAll("OutputDirectory", "OutputDir");
    sjdl += "JDLVariables = \n{\n   \"Packages\",\n   \"OutputDir\"\n};\n";
-   sjdl.Prepend("JobTag = \"Automatically generated analysis JDL\";\n");
+   sjdl.Prepend(Form("Jobtag = {\n   \"comment:%s\"\n};\n", fJobTag.Data()));
    index = sjdl.Index("JDLVariables");
    if (index >= 0) sjdl.Insert(index, "\n# JDL variables\n");
    // Write jdl to file
@@ -947,6 +1058,35 @@ Bool_t AliAnalysisAlien::FileExists(const char *lfn)
    return kTRUE;
 }
 
+//______________________________________________________________________________
+Bool_t AliAnalysisAlien::DirectoryExists(const char *dirname)
+{
+// Returns true if directory exists. Can be also a path.
+   if (!gGrid) return kFALSE;
+   // Check if dirname is a path
+   TString dirstripped = dirname;
+   dirstripped = dirstripped.Strip();
+   dirstripped = dirstripped.Strip(TString::kTrailing, '/');
+   TString dir = gSystem->BaseName(dirstripped);
+   dir += "/";
+   TString path = gSystem->DirName(dirstripped);
+   TGridResult *res = gGrid->Ls(path, "-F");
+   if (!res) return kFALSE;
+   TIter next(res);
+   TMap *map;
+   TObject *obj;
+   while ((map=dynamic_cast<TMap*>(next()))) {
+      obj = map->GetValue("name");
+      if (!obj) break;
+      if (dir == obj->GetName()) {
+         delete res;
+         return kTRUE;
+      }
+   }
+   delete res;
+   return kFALSE;
+}      
+
 //______________________________________________________________________________
 void AliAnalysisAlien::CheckDataType(const char *lfn, Bool_t &is_collection, Bool_t &is_xml, Bool_t &use_tags)
 {
@@ -1100,6 +1240,13 @@ Bool_t AliAnalysisAlien::IsCollection(const char *lfn) const
    return kFALSE;
 }   
 
+//______________________________________________________________________________
+Bool_t AliAnalysisAlien::IsSingleOutput() const
+{
+// Check if single-ouput option is on.
+   return (!fOutputSingle.IsNull());
+}
+   
 //______________________________________________________________________________
 void AliAnalysisAlien::Print(Option_t *) const
 {
@@ -1119,7 +1266,7 @@ void AliAnalysisAlien::Print(Option_t *) const
    if (fRunNumbers.Length()) 
    printf("=   Run numbers to be processed: _________________ %s\n", fRunNumbers.Data());
    if (fRunRange[0])
-   printf("=   Run range to be processed: ___________________ %d-%d\n", fRunRange[0], fRunRange[1]);
+   printf("=   Run range to be processed: ___________________ %s%d-%s%d\n", fRunPrefix.Data(), fRunRange[0], fRunPrefix.Data(), fRunRange[1]);
    if (!fRunRange[0] && !fRunNumbers.Length()) {
       TIter next(fInputFiles);
       TObject *obj;
@@ -1143,9 +1290,12 @@ void AliAnalysisAlien::Print(Option_t *) const
    if (fNrunsPerMaster>0)
    printf("=   Number of runs per master job: _______________ %d\n", fNrunsPerMaster);
    printf("=   Number of files in one chunk to be merged: ___ %d\n", fMaxMergeFiles);
-   printf("=   Name of the generated execution script: ______ %s\n",fExecutable.Data());
+   printf("=   Name of the generated execution script: ______ %s\n", fExecutable.Data());
+   printf("=   Executable command: __________________________ %s\n", fExecutableCommand.Data());
    if (fArguments.Length()) 
    printf("=   Arguments for the execution script: __________ %s\n",fArguments.Data());
+   if (fExecutableArgs.Length()) 
+   printf("=   Arguments after macro name in executable______ %s\n",fExecutableArgs.Data());
    printf("=   Name of the generated analysis macro: ________ %s\n",fAnalysisMacro.Data());
    printf("=   User analysis files to be deployed: __________ %s\n",fAnalysisSource.Data());
    printf("=   Additional libs to be loaded or souces to be compiled runtime: <%s>\n",fAdditionalLibs.Data());
@@ -1186,7 +1336,9 @@ void AliAnalysisAlien::SetDefaults()
    fMaxMergeFiles              = 100;
    fRunNumbers                 = "";
    fExecutable                 = "analysis.sh";
+   fExecutableCommand          = "root -b -q";
    fArguments                  = "";
+   fExecutableArgs             = "";
    fAnalysisMacro              = "myAnalysis.C";
    fAnalysisSource             = "";
    fAdditionalLibs             = "";
@@ -1204,6 +1356,7 @@ void AliAnalysisAlien::SetDefaults()
    fOutputFiles                = "";  // Like "AliAODs.root histos.root"
    fInputFormat                = "xml-single";
    fJDLName                    = "analysis.jdl";
+   fJobTag                     = "Automatically generated analysis JDL";
    fMergeExcludes              = "";
 }   
 
@@ -1219,7 +1372,7 @@ Bool_t AliAnalysisAlien::MergeOutputs()
    }   
    // Get the output path
    if (!fGridOutputDir.Contains("/")) fGridOutputDir = Form("/%s/%s/%s", gGrid->GetHomeDirectory(), fGridWorkingDir.Data(), fGridOutputDir.Data());
-   if (!gGrid->Cd(fGridOutputDir)) {
+   if (!DirectoryExists(fGridOutputDir)) {
       Error("MergeOutputs", "Grid output directory %s not found. Terminate() will NOT be executed", fGridOutputDir.Data());
       return kFALSE;
    }
@@ -1372,6 +1525,7 @@ Bool_t AliAnalysisAlien::StartAnalysis(Long64_t /*nentries*/, Long64_t /*firstEn
             if (!mgr->GetOutputEventHandler()) continue;
             filename = mgr->GetOutputEventHandler()->GetOutputFileName();
          }
+         if (fOutputFiles.Contains(filename)) continue;
          if (fOutputFiles.Length()) fOutputFiles += " ";
          fOutputFiles += filename;
       }
@@ -1379,7 +1533,7 @@ Bool_t AliAnalysisAlien::StartAnalysis(Long64_t /*nentries*/, Long64_t /*firstEn
       if (mgr->GetExtraFiles().Length()) {
          if (fOutputFiles.Length()) fOutputFiles += " ";
          fOutputFiles += mgr->GetExtraFiles();
-      }   
+      }
    }
 //   if (!fCloseSE.Length()) fCloseSE = gSystem->Getenv("alien_CLOSE_SE");
    if (TestBit(AliAnalysisGrid::kOffline)) {
@@ -1432,7 +1586,9 @@ Bool_t AliAnalysisAlien::StartAnalysis(Long64_t /*nentries*/, Long64_t /*firstEn
       }
       delete list;
       gSystem->Exec(Form("bash %s 2>stderr", fExecutable.Data()));
-      gSystem->Exec("bash validate.sh");
+      TString validationScript = fExecutable;
+      validationScript.ReplaceAll(".sh", "_validation.sh");
+      gSystem->Exec(Form("bash %s",validationScript.Data()));
 //      gSystem->Exec("cat stdout");
       return kFALSE;
    }
@@ -1526,7 +1682,12 @@ void AliAnalysisAlien::SubmitNext()
       // Submit for a range of enumeration of runs.
       if (fNsubmitted>=nmasterjobs) {iscalled = kFALSE; return;}
       TString query;
-      query = Form("submit %s %s %03d", fJDLName.Data(), fInputFiles->At(fNsubmitted)->GetName(), fNsubmitted);
+      TString runOutDir = gSystem->BaseName(fInputFiles->At(fNsubmitted)->GetName());
+      runOutDir.ReplaceAll(".xml", "");
+      if (fOutputToRunNo)
+         query = Form("submit %s %s %s", fJDLName.Data(), fInputFiles->At(fNsubmitted)->GetName(), runOutDir.Data());
+      else
+         query = Form("submit %s %s %03d", fJDLName.Data(), fInputFiles->At(fNsubmitted)->GetName(), fNsubmitted);
       printf("********* %s\n",query.Data());
       res = gGrid->Command(query);
       if (res) {
@@ -1555,7 +1716,9 @@ void AliAnalysisAlien::SubmitNext()
 //______________________________________________________________________________
 void AliAnalysisAlien::WriteAnalysisFile()
 {
-// Write current analysis manager into the file analysis.root
+// Write current analysis manager into the file <analysisFile>
+   TString analysisFile = fExecutable;
+   analysisFile.ReplaceAll(".sh", ".root");
    if (!TestBit(AliAnalysisGrid::kSubmit)) {  
       AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
       if (!mgr || !mgr->IsInitialized()) {
@@ -1571,13 +1734,19 @@ void AliAnalysisAlien::WriteAnalysisFile()
          if (handler->InheritsFrom("AliAODInputHandler")) TObject::SetBit(AliAnalysisGrid::kUseAOD);
       }
       TDirectory *cdir = gDirectory;
-      TFile *file = TFile::Open("analysis.root", "RECREATE");
+      TFile *file = TFile::Open(analysisFile, "RECREATE");
       if (file) {
+         // Skip task Terminate calls for the grid job
+         mgr->SetSkipTerminate(kTRUE);
+         // Unless merging makes no sense
+         if (IsSingleOutput()) mgr->SetSkipTerminate(kFALSE);
          mgr->Write();
          delete file;
+         // Enable termination for local jobs
+         mgr->SetSkipTerminate(kFALSE);
       }
       if (cdir) cdir->cd();
-      Info("WriteAnalysisFile", "\n#####   Analysis manager: %s wrote to file <analysis.root>\n", mgr->GetName());
+      Info("WriteAnalysisFile", "\n#####   Analysis manager: %s wrote to file <%s>\n", mgr->GetName(),analysisFile.Data());
    }   
    Bool_t copy = kTRUE;
    if (TestBit(AliAnalysisGrid::kOffline) || TestBit(AliAnalysisGrid::kTest)) copy = kFALSE;
@@ -1585,9 +1754,9 @@ void AliAnalysisAlien::WriteAnalysisFile()
       CdWork();
       TString workdir = gGrid->GetHomeDirectory();
       workdir += fGridWorkingDir;
-      Info("CreateJDL", "\n#####   Copying file <analysis.root> containing your initialized analysis manager to your alien workspace");
-      if (FileExists("analysis.root")) gGrid->Rm("analysis.root");
-      TFile::Cp("file:analysis.root", Form("alien://%s/analysis.root", workdir.Data()));
+      Info("CreateJDL", "\n#####   Copying file <%s> containing your initialized analysis manager to your alien workspace", analysisFile.Data());
+      if (FileExists(analysisFile)) gGrid->Rm(analysisFile);
+      TFile::Cp(Form("file:%s",analysisFile.Data()), Form("alien://%s/%s", workdir.Data(),analysisFile.Data()));
    }   
 }
 
@@ -1629,7 +1798,22 @@ void AliAnalysisAlien::WriteAnalysisMacro()
       out << "   gSystem->Load(\"libGeom\");" << endl;
       out << "   gSystem->Load(\"libVMC\");" << endl;
       out << "   gSystem->Load(\"libPhysics\");" << endl << endl;
+      out << "   gSystem->Load(\"libMinuit\");" << endl << endl;
+      if (fAdditionalRootLibs.Length()) {
+       // in principle libtree /lib geom libvmc etc. can go into this list, too
+       out << "// Add aditional libraries" << endl;
+       TObjArray *list = fAdditionalRootLibs.Tokenize(" ");
+       TIter next(list);
+       TObjString *str;
+       while((str=(TObjString*)next())) {
+         if (str->GetString().Contains(".so"))
+           out << "   gSystem->Load(\"" << str->GetString().Data() << "\");" << endl;
+         }
+       if (list) delete list;
+      }
       out << "// Load analysis framework libraries" << endl;
+
+
       if (!fPackages) {
          out << "   gSystem->Load(\"libSTEERBase\");" << endl;
          out << "   gSystem->Load(\"libESD\");" << endl;
@@ -1737,7 +1921,9 @@ void AliAnalysisAlien::WriteAnalysisMacro()
          }  
       }   
       out << "// read the analysis manager from file" << endl;
-      out << "   TFile *file = TFile::Open(\"analysis.root\");" << endl;
+      TString analysisFile = fExecutable;
+      analysisFile.ReplaceAll(".sh", ".root");
+      out << "   TFile *file = TFile::Open(\"" << analysisFile << "\");" << endl;
       out << "   if (!file) return;" << endl; 
       out << "   TIter nextkey(file->GetListOfKeys());" << endl;
       out << "   AliAnalysisManager *mgr = 0;" << endl;
@@ -1747,7 +1933,7 @@ void AliAnalysisAlien::WriteAnalysisMacro()
       out << "         mgr = (AliAnalysisManager*)file->Get(key->GetName());" << endl;
       out << "   };" << endl;
       out << "   if (!mgr) {" << endl;
-      out << "      ::Error(\"" << func.Data() << "\", \"No analysis manager found in file analysis.root\");" << endl;
+      out << "      ::Error(\"" << func.Data() << "\", \"No analysis manager found in file" << analysisFile <<"\");" << endl;
       out << "      return;" << endl;
       out << "   }" << endl << endl;
       out << "   mgr->PrintStatus();" << endl;
@@ -1907,7 +2093,6 @@ void AliAnalysisAlien::WriteExecutable()
          return;
       }
       out << "#!/bin/bash" << endl;
-      out << "export GCLIENT_SERVER_LIST=\"pcapiserv04.cern.ch:10000|pcapiserv05.cern.ch:10000|pcapiserv06.cern.ch:10000|pcapiserv07.cern.ch:10000\"" << endl;
       out << "echo \"=========================================\"" << endl; 
       out << "echo \"############## PATH : ##############\"" << endl;
       out << "echo $PATH" << endl;
@@ -1921,17 +2106,28 @@ void AliAnalysisAlien::WriteExecutable()
       out << "echo $ALICE_ROOT" << endl;
       out << "echo \"############## which aliroot : ##############\"" << endl;
       out << "which aliroot" << endl;
+      out << "echo \"############## system limits : ##############\"" << endl;
+      out << "ulimit -a" << endl;
+      out << "echo \"############## memory : ##############\"" << endl;
+      out << "free -m" << endl;
       out << "echo \"=========================================\"" << endl << endl;
-//      if (TestBit(AliAnalysisGrid::kTest)) out << "root ";
-      out << "root -b -q "; 
-      out << fAnalysisMacro.Data() << endl << endl;
-      out << "echo \"======== " << fAnalysisMacro.Data() << " finished ========\"" << endl;
+      // Make sure we can properly compile par files
+      if (TObject::TestBit(AliAnalysisGrid::kUsePars)) out << "export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH" << endl;
+      out << fExecutableCommand << " "; 
+      out << fAnalysisMacro.Data() << " " << fExecutableArgs.Data() << endl << endl;
+      out << "echo \"======== " << fAnalysisMacro.Data() << " finished with exit code: $? ========\"" << endl;
+      out << "echo \"############## memory after: ##############\"" << endl;
+      out << "free -m" << endl;
+      out << "echo \"############## Last 10 lines from dmesg : ##############\"" << endl;
+      out << "dmesg | tail -n 10" << endl;
    }   
    Bool_t copy = kTRUE;
    if (TestBit(AliAnalysisGrid::kOffline) || TestBit(AliAnalysisGrid::kTest)) copy = kFALSE;
    if (copy) {
       CdWork();
       TString workdir = gGrid->GetHomeDirectory();
+      TString bindir = Form("%s/bin", workdir.Data());
+      if (!DirectoryExists(bindir)) gGrid->Mkdir(bindir);
       workdir += fGridWorkingDir;
       TString executable = Form("%s/bin/%s", gGrid->GetHomeDirectory(), fExecutable.Data());
       if (FileExists(executable)) gGrid->Rm(executable);
@@ -1972,6 +2168,8 @@ void AliAnalysisAlien::WriteValidationScript()
 // Generate the alien validation script.
    // Generate the validation script
    TObjString *os;
+   TString validationScript = fExecutable;
+   validationScript.ReplaceAll(".sh", "_validation.sh");
    if (!Connect()) {
       Error("WriteValidationScript", "Alien connection required");
       return;
@@ -1980,7 +2178,7 @@ void AliAnalysisAlien::WriteValidationScript()
    if (!TestBit(AliAnalysisGrid::kTest)) out_stream = " >> stdout";
    if (!TestBit(AliAnalysisGrid::kSubmit)) {  
       ofstream out;
-      out.open("validate.sh", ios::out);
+      out.open(validationScript, ios::out);
       out << "#!/bin/bash" << endl;
       out << "##################################################" << endl;
       out << "validateout=`dirname $0`" << endl;
@@ -2053,6 +2251,12 @@ void AliAnalysisAlien::WriteValidationScript()
          out << "fi" << endl;
       }   
       delete arr;
+      out << "if ! [ -f outputs_valid ] ; then" << endl;
+      out << "   error=1" << endl;
+      out << "   echo \"Output files were not validated by the analysis manager\" >> stdout" << endl;
+      out << "   echo \"Output files were not validated by the analysis manager\" >> stderr" << endl;
+      out << "fi" << endl;
+      
       out << "if [ $error = 0 ] ; then" << endl;
       out << "   echo \"* ----------------   Job Validated  ------------------*\""  << out_stream << endl;
       out << "fi" << endl;
@@ -2068,8 +2272,8 @@ void AliAnalysisAlien::WriteValidationScript()
       CdWork();
       TString workdir = gGrid->GetHomeDirectory();
       workdir += fGridWorkingDir;
-      Info("CreateJDL", "\n#####   Copying validation script <validate.sh> to your AliEn working space");
-      if (FileExists("validate.sh")) gGrid->Rm("validate.sh");
-      TFile::Cp("file:validate.sh", Form("alien://%s/validate.sh", workdir.Data()));
+      Info("CreateJDL", "\n#####   Copying validation script <%s> to your AliEn working space", validationScript.Data());
+      if (FileExists(validationScript)) gGrid->Rm(validationScript);
+      TFile::Cp(Form("file:%s",validationScript.Data()), Form("alien://%s/%s", workdir.Data(),validationScript.Data()));
    } 
 }