]> git.uio.no Git - u/mrichter/AliRoot.git/blob - HLT/trigger/AliHLTGlobalTriggerComponent.cxx
putting back the lost statistics message at EOR
[u/mrichter/AliRoot.git] / HLT / trigger / AliHLTGlobalTriggerComponent.cxx
1 // $Id$
2 /**************************************************************************
3  * This file is property of and copyright by the ALICE HLT Project        *
4  * ALICE Experiment at CERN, All rights reserved.                         *
5  *                                                                        *
6  * Primary Authors: Artur Szostak <artursz@iafrica.com>                   *
7  *                  for The ALICE HLT Project.                            *
8  *                                                                        *
9  * Permission to use, copy, modify and distribute this software and its   *
10  * documentation strictly for non-commercial purposes is hereby granted   *
11  * without fee, provided that the above copyright notice appears in all   *
12  * copies and that both the copyright notice and this permission notice   *
13  * appear in the supporting documentation. The authors make no claims     *
14  * about the suitability of this software for any purpose. It is          *
15  * provided "as is" without express or implied warranty.                  *
16  **************************************************************************/
17
18 /// @file   AliHLTGlobalTriggerComponent.cxx
19 /// @author Artur Szostak <artursz@iafrica.com>
20 /// @date   26 Nov 2008
21 /// @brief  Implementation of the AliHLTGlobalTriggerComponent component class.
22 ///
23 /// The AliHLTGlobalTriggerComponent class applies the global HLT trigger to all
24 /// trigger information produced by components deriving from AliHLTTrigger.
25
26 #include "AliHLTGlobalTriggerComponent.h"
27 #include "AliHLTGlobalTriggerDecision.h"
28 #include "AliHLTGlobalTrigger.h"
29 #include "AliHLTGlobalTriggerConfig.h"
30 #include "AliHLTTriggerMenu.h"
31 #include "AliHLTCTPData.h"
32 #include "AliCDBManager.h"
33 #include "AliCDBStorage.h"
34 #include "AliCDBEntry.h"
35 #include "AliRawDataHeader.h"
36 #include "TUUID.h"
37 #include "TROOT.h"
38 #include "TSystem.h"
39 #include "TRegexp.h"
40 #include "TClonesArray.h"
41 #include "TObjString.h"
42 #include "TString.h"
43 #include "TInterpreter.h"
44 #include "TDatime.h"
45 #include "TClass.h"
46 #include "TNamed.h"
47 #include "TRandom3.h"
48 #include <fstream>
49 #include <cerrno>
50 #include <cassert>
51 #include <vector>
52 #include <algorithm>
53
54 ClassImp(AliHLTGlobalTriggerComponent)
55
56 const char* AliHLTGlobalTriggerComponent::fgkTriggerMenuCDBPath = "HLT/ConfigHLT/HLTGlobalTrigger";
57
58
59 namespace
60 {
61   /**
62    * This method is used as a comparison functor with the STL sort routines.
63    */
64   bool AliHLTDescendingNumbers(UInt_t a, UInt_t b)
65   {
66     return a > b;
67   }
68 } // end of namespace
69
70
71 AliHLTGlobalTriggerComponent::AliHLTGlobalTriggerComponent() :
72         AliHLTTrigger(),
73         fTrigger(NULL),
74         fDebugMode(false),
75         fRuntimeCompile(true),
76         fDeleteCodeFile(false),
77         fMakeSoftwareTriggers(true),
78         fCodeFileName(),
79         fClassName(),
80         fCTPDecisions(NULL),
81         fBufferSizeConst(2*(sizeof(AliHLTGlobalTriggerDecision) + sizeof(AliHLTReadoutList))),
82         fBufferSizeMultiplier(1.),
83         fIncludePaths(TObjString::Class()),
84         fIncludeFiles(TObjString::Class()),
85         fLibStateAtLoad(),
86         fBits(0),
87         fDataEventsOnly(true),
88         fMonitorPeriod(-1),
89         fUniqueID(0),
90         fSoftwareTrigger(true, "SOFTWARE"),
91         fTotalEventCounter(0),
92         fCDH(NULL)
93 {
94   // Default constructor.
95   
96   ClearInfoForNewEvent(false);
97 }
98
99
100 AliHLTGlobalTriggerComponent::~AliHLTGlobalTriggerComponent()
101 {
102   // Default destructor.
103   
104   if (fTrigger != NULL) delete fTrigger;
105
106   if (fCTPDecisions) {
107     fCTPDecisions->Delete();
108     delete fCTPDecisions;
109   }
110 }
111
112
113 void AliHLTGlobalTriggerComponent::GetOutputDataTypes(AliHLTComponentDataTypeList& list) const
114 {
115   // Returns the kAliHLTDataTypeGlobalTrigger type as output.
116   list.push_back(kAliHLTDataTypeGlobalTrigger);
117 }
118
119
120 void AliHLTGlobalTriggerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
121 {
122   // Returns the output data size estimate.
123
124   constBase = fBufferSizeConst;
125   inputMultiplier = fBufferSizeMultiplier;
126 }
127
128
129 Int_t AliHLTGlobalTriggerComponent::DoInit(int argc, const char** argv)
130 {
131   // Initialises the global trigger component.
132   
133   fDebugMode = false;
134   fClassName = "";
135   fCodeFileName = "";
136   fDeleteCodeFile = false;
137   fMakeSoftwareTriggers = true;
138   const char* configFileName = NULL;
139   const char* codeFileName = NULL;
140   fIncludePaths.Clear();
141   fIncludeFiles.Clear();
142   SetBit(kIncludeInput);
143   fDataEventsOnly = true;
144   UInt_t randomSeed = 0;
145   bool randomSeedSet = false;
146   fCDH = NULL;
147   
148   for (int i = 0; i < argc; i++)
149   {
150     if (strcmp(argv[i], "-config") == 0)
151     {
152       if (configFileName != NULL)
153       {
154         HLTWarning("Trigger configuration macro was already specified."
155                    " Will replace previous value given by -config."
156         );
157       }
158       if (argc <= i+1)
159       {
160         HLTError("The trigger configuration macro filename was not specified." );
161         return -EINVAL;
162       }
163       configFileName = argv[i+1];
164       i++;
165       continue;
166     }
167     
168     if (strcmp(argv[i], "-includepath") == 0)
169     {
170       if (argc <= i+1)
171       {
172         HLTError("The include path was not specified." );
173         return -EINVAL;
174       }
175       try
176       {
177         new (fIncludePaths[fIncludePaths.GetEntriesFast()]) TObjString(argv[i+1]);
178       }
179       catch (const std::bad_alloc&)
180       {
181         HLTError("Could not allocate more memory for the fIncludePaths array.");
182         return -ENOMEM;
183       }
184       i++;
185       continue;
186     }
187     
188     if (strcmp(argv[i], "-include") == 0)
189     {
190       if (argc <= i+1)
191       {
192         HLTError("The include file name was not specified." );
193         return -EINVAL;
194       }
195       try
196       {
197         new (fIncludeFiles[fIncludeFiles.GetEntriesFast()]) TObjString(argv[i+1]);
198       }
199       catch (const std::bad_alloc&)
200       {
201         HLTError("Could not allocate more memory for the fIncludeFiles array.");
202         return -ENOMEM;
203       }
204       i++;
205       continue;
206     }
207     
208     if (strcmp(argv[i], "-debug") == 0)
209     {
210       if (fDebugMode == true)
211       {
212         HLTWarning("The debug flag was already specified. Ignoring this instance.");
213       }
214       fDebugMode = true;
215       continue;
216     }
217     
218     if (strcmp(argv[i], "-cint") == 0)
219     {
220       fRuntimeCompile = false;
221       continue;
222     }
223     
224     if (strcmp(argv[i], "-usecode") == 0)
225     {
226       if (codeFileName != NULL)
227       {
228         HLTWarning("Custom trigger code file was already specified."
229                    " Will replace previous value given by -usecode."
230         );
231       }
232       if (argc <= i+1)
233       {
234         HLTError("The custom trigger code filename was not specified." );
235         return -EINVAL;
236       }
237       codeFileName = argv[i+1];
238       if (argc <= i+2)
239       {
240         HLTError("The custom trigger class name was not specified." );
241         return -EINVAL;
242       }
243       fClassName = argv[i+2];
244       i += 2;
245       continue;
246     }
247
248     if (strcmp(argv[i], "-skipctp") == 0)
249     {
250       HLTInfo("Skipping CTP counters in trigger decision");
251       SetBit(kSkipCTP);
252       continue;
253     }
254
255     if (strcmp(argv[i], "-forward-input") == 0)
256     {
257       HLTInfo("Forwarding input objects and trigger decisions");
258       SetBit(kForwardInput);
259       SetBit(kIncludeShort);
260       SetBit(kIncludeInput, false);
261       continue;
262     }
263
264     if (strstr(argv[i], "-include-input") == argv[i])
265     {
266       SetBit(kForwardInput,false);
267       TString param=argv[i];
268       param.ReplaceAll("-include-input", "");
269       if (param.CompareTo("=none")==0) 
270       {
271         HLTInfo("skipping objects and trigger decisions");
272         SetBit(kIncludeShort, false);
273         SetBit(kIncludeInput, false);
274       }
275       else if (param.CompareTo("=short")==0) 
276       {
277         HLTInfo("including short info on objects and trigger decisions");
278         SetBit(kIncludeShort);
279         SetBit(kIncludeInput, false);
280       }
281       else if (param.CompareTo("=both")==0) 
282       {
283         HLTInfo("including input objects, trigger decisions and short info");
284         SetBit(kIncludeShort);
285         SetBit(kIncludeInput);
286       }
287       else if (param.CompareTo("=objects")==0 || param.IsNull())
288       {
289         HLTInfo("including input objects and trigger decisions");
290         SetBit(kIncludeShort, false);
291         SetBit(kIncludeInput);
292       }
293       else
294       {
295         HLTError("unknown parameter '%s' for argument '-include-input'", param.Data());
296       }
297       continue;
298     }
299
300     if (strcmp(argv[i], "-process-all-events") == 0)
301     {
302       fDataEventsOnly = false;
303       continue;
304     }
305
306     if (strstr(argv[i], "-monitoring") == argv[i])
307     {
308       TString param=argv[i];
309       param.ReplaceAll("-monitoring", "");
310       if (param.IsNull()) 
311       {
312         // -monitoring
313         // enable monitoring trigger for all events
314         fMonitorPeriod=0;
315       } else {
316         // -monitoring=n
317         // enable monitoring trigger once every n seconds
318         param.ReplaceAll("=", "");
319         if (param.IsDigit()) {
320           fMonitorPeriod=param.Atoi();
321         } else {
322           HLTError("expecting number as parameter for argument '-monitoring=', got %s, skipping monitoring trigger", param.Data());
323         }
324       }
325       continue;
326     }
327
328     if (strcmp(argv[i], "-dont-make-software-triggers") == 0)
329     {
330       fMakeSoftwareTriggers = false;
331       continue;
332     }
333     if (strcmp(argv[i], "-randomseed") == 0)
334     {
335       if (randomSeedSet)
336       {
337         HLTWarning("The random seed was already specified previously with the option -randomseed."
338                    "Will replace the previous value of %d with the new one.",
339                    randomSeed
340         );
341       }
342       if (argc <= i+1)
343       {
344         HLTError("The number to use as the seed was not specified for the -randomseed option." );
345         return -EINVAL;
346       }
347       TString numstr = argv[i+1];
348       if (not numstr.IsDigit())
349       {
350         HLTError("The number specified in the -randomseed option is not a valid decimal integer." );
351         return -EINVAL;
352       }
353       randomSeed = numstr.Atoi();
354       randomSeedSet = true;
355       i++;
356       continue;
357     }
358     
359     HLTError("Unknown option '%s'.", argv[i]);
360     return -EINVAL;
361   } // for loop
362   
363   const AliHLTTriggerMenu* menu = NULL;
364   if (configFileName != NULL)
365   {
366     TString cmd = ".x ";
367     cmd += configFileName;
368     gROOT->ProcessLine(cmd);
369     menu = AliHLTGlobalTriggerConfig::Menu();
370   }
371   
372   // Try load the trigger menu from the CDB if it is not loaded yet with the
373   // -config option
374   int result = -ENOENT;
375   if (menu == NULL)
376   {
377     result = LoadTriggerMenu(fgkTriggerMenuCDBPath, menu);
378   }
379   if (menu == NULL)
380   {
381     HLTError("No trigger menu configuration found or specified.");
382     return result;
383   }
384   
385   if (codeFileName == NULL)
386   {
387     result = GenerateTrigger(menu, fClassName, fCodeFileName, fIncludePaths, fIncludeFiles);
388     if (result == 0) fDeleteCodeFile = true;
389   }
390   else
391   {
392     result = LoadTriggerClass(codeFileName, fIncludePaths);
393     if (result == 0) fCodeFileName = codeFileName;
394   }
395   if (result != 0) return result;
396   
397   try
398   {
399     fTrigger = AliHLTGlobalTrigger::CreateNew(fClassName.Data());
400   }
401   catch (const std::bad_alloc&)
402   {
403     HLTError("Could not allocate memory for the AliHLTGlobalTrigger instance.");
404     return -ENOMEM;
405   }
406   if (fTrigger == NULL)
407   {
408     HLTError("Could not create a new instance of '%s'.", fClassName.Data());
409     return -EIO;
410   }
411   
412   fTrigger->FillFromMenu(*menu);
413   if (fTrigger->CallFailed()) return -EPROTO;
414
415   // setup the CTP accounting in AliHLTComponent
416   SetupCTPData();
417
418   // Set the default values from the trigger menu.
419   SetDescription(menu->DefaultDescription());
420   SetTriggerDomain(menu->DefaultTriggerDomain());
421   
422   // Initialise the random number generator seed value.
423   // NOTE: The GenerateTrigger method called above will set the fUniqueID value
424   // with a random value based on a GUID that should be unique across the system.
425   // This is then used as the seed to the random number generator if the -randomseed
426   // option is not used.
427   if (not randomSeedSet) randomSeed = fUniqueID;
428   gRandom->SetSeed(randomSeed);
429   
430   fTotalEventCounter = 0;
431   return 0;
432 }
433
434
435 Int_t AliHLTGlobalTriggerComponent::DoDeinit()
436 {
437   // Cleans up the global trigger component.
438   
439   if (fTrigger != NULL)
440   {
441     delete fTrigger;
442     fTrigger = NULL;
443   }
444   
445   if (fCTPDecisions) {
446     fCTPDecisions->Delete();
447     delete fCTPDecisions;
448   }
449   fCTPDecisions=NULL;
450   fCDH = NULL;
451   
452   Int_t result = UnloadTriggerClass(fCodeFileName);
453   if (result != 0) return result;
454   
455   if (fDeleteCodeFile and !fCodeFileName.IsNull() && gSystem->AccessPathName(fCodeFileName)==0 && !fDebugMode) {
456     fCodeFileName.ReplaceAll(".cxx", "*");
457     TString command="rm "; command+=fCodeFileName;
458     gSystem->Exec(command);
459   }
460   fCodeFileName="";
461   fDeleteCodeFile=false;
462
463   return 0;
464 }
465
466
467 AliHLTComponent* AliHLTGlobalTriggerComponent::Spawn()
468 {
469   // Creates a new object instance.
470   AliHLTComponent* comp = NULL;
471   try
472   {
473     comp = new AliHLTGlobalTriggerComponent;
474   }
475   catch (const std::bad_alloc&)
476   {
477     HLTError("Could not allocate memory for a new instance of AliHLTGlobalTriggerComponent.");
478     return NULL;
479   }
480   return comp;
481 }
482
483
484 int AliHLTGlobalTriggerComponent::DoTrigger()
485 {
486   // This method will apply the global trigger decision.
487
488   if (fTrigger == NULL)
489   {
490     HLTFatal("Global trigger implementation object is NULL!");
491     return -EIO;
492   }
493
494   AliHLTUInt32_t eventType=0;
495   if (!IsDataEvent(&eventType)) {
496     if (eventType==gkAliEventTypeEndOfRun)
497     {
498       PrintStatistics(fTrigger, kHLTLogImportant);
499     }
500     if (fDataEventsOnly)
501     {
502       IgnoreEvent();  // dont generate any trigger decision.
503       return 0;
504     }
505   }
506   
507   fCDH = NULL;  // have to reset this in case ExtractTriggerData fails.
508   ExtractTriggerData(*GetTriggerData(), NULL, NULL, &fCDH, NULL);
509
510   // Copy the trigger counters in case we need to set them back to their original
511   // value because the PushBack method fails with ENOSPC.
512   TArrayL64 originalCounters = fTrigger->GetCounters();
513   if (fTrigger->CallFailed()) return -EPROTO;
514   
515   fTrigger->NewEvent();
516   if (fTrigger->CallFailed()) return -EPROTO;
517   
518   // Fill in the input data.
519   const TObject* obj = GetFirstInputObject();
520   while (obj != NULL)
521   {
522     fTrigger->Add(obj, GetDataType(), GetSpecification());
523     if (fTrigger->CallFailed()) return -EPROTO;
524     obj = GetNextInputObject();
525   }
526
527   // add trigger decisions for every CTP class
528   const AliHLTCTPData* pCTPData=CTPData();
529   if (pCTPData) {
530     AddCTPDecisions(fTrigger, pCTPData, GetTriggerData());
531   }
532   
533   bool softwareTriggerIsValid = FillSoftwareTrigger();
534   if (softwareTriggerIsValid)
535   {
536     fTrigger->Add(&fSoftwareTrigger, kAliHLTDataTypeTriggerDecision, kAliHLTVoidDataSpec);
537   }
538   
539   // Calculate the global trigger result and trigger domain, then create and push
540   // back the new global trigger decision object.
541   TString description;
542   AliHLTTriggerDomain triggerDomain;
543   bool triggerResult = false;
544   bool matchedItems = fTrigger->CalculateTriggerDecision(triggerResult, triggerDomain, description);
545   if (fTrigger->CallFailed()) return -EPROTO;
546   AliHLTGlobalTriggerDecision decision(
547       triggerResult,
548       // The following will cause the decision to be generated with default values
549       // (set in fTriggerDomain and fDescription) if the trigger result is false.
550       (matchedItems == true) ? triggerDomain : GetTriggerDomain(),
551       (matchedItems == true) ? description.Data() : GetDescription()
552     );
553
554   decision.SetUniqueID(fUniqueID);
555   decision.SetCounters(fTrigger->GetCounters(), fTotalEventCounter+1);
556   if (fTrigger->CallFailed()) return -EPROTO;
557   
558   TClonesArray shortInfo(TNamed::Class(), GetNumberOfInputBlocks());
559   
560   // Add the input objects used to make the global decision.
561   obj = GetFirstInputObject();
562   while (obj != NULL)
563   {
564     const AliHLTTriggerDecision* intrig = dynamic_cast<const AliHLTTriggerDecision*>(obj);
565     
566     if (TestBit(kForwardInput)) Forward(obj);
567     
568     if (TestBit(kIncludeInput))
569     {
570       if (intrig != NULL)
571       {
572          decision.AddTriggerInput(*intrig);
573       }
574       else
575       {
576         // The const_cast should be safe in this case because the list of inputObjects
577         // will be added to the global decision with AddInputObjectRef, which only
578         // modifies the kCanDelete bit and nothing else.
579         // This is necessary since GetFirstInputObject only returns const objects.
580         decision.AddInputObjectRef( const_cast<TObject*>(obj) );
581       }
582     }
583     
584     if (TestBit(kIncludeShort))
585     {
586       int entries = shortInfo.GetEntriesFast();
587       try
588       {
589         new (shortInfo[entries]) TNamed(obj->GetName(), obj->GetTitle());
590       }
591       catch (const std::bad_alloc&)
592       {
593         HLTError("Could not allocate more memory for the short list of input objects.");
594         return -ENOMEM;
595       }
596       if (intrig != NULL)
597       {
598         shortInfo[entries]->SetBit(BIT(16)); // indicate that this is a trigger decision
599         shortInfo[entries]->SetBit(BIT(15), intrig->Result());
600       }
601     }
602
603     obj = GetNextInputObject();
604   }
605   if (TestBit(kIncludeShort)) decision.AddInputObjectRef(&shortInfo);
606   
607   // The const_cast should be safe in this case because AddInputObjectRef just
608   // modifies the kCanDelete bit and nothing else.
609   if (!TestBit(kSkipCTP) && CTPData()) decision.AddInputObjectRef(const_cast<AliHLTCTPData*>(CTPData()));
610   
611   if (softwareTriggerIsValid and TestBit(kIncludeInput)) decision.AddTriggerInput(fSoftwareTrigger);
612   
613   static UInt_t lastTime=0;
614   TDatime time;
615   if (time.Get()-lastTime>60)
616   {
617     lastTime=time.Get();
618     PrintStatistics(fTrigger, kHLTLogImportant);
619   }
620   
621   // add readout filter to event done data
622   CreateEventDoneReadoutFilter(decision.TriggerDomain(), 3);
623
624   // add monitoring filter to event done data if enabled by setting
625   // a monitoring period >=0: -1 means off, 0 means for every event
626   // configured by argument '-monitoring[=n]'
627   if (fMonitorPeriod>=0) {
628     static UInt_t lastMonitorEvent=0;
629
630     AliHLTTriggerDomain monitoringFilter(decision.TriggerDomain());
631     if (decision.Result() &&
632         int(time.Get()-lastMonitorEvent)>fMonitorPeriod) {
633       lastMonitorEvent=time.Get();
634       // add monitoring event command for triggered events
635       CreateEventDoneReadoutFilter(decision.TriggerDomain(), 5);
636     } else {
637       // empty filter list if events are not triggered
638       // or within the monitoring interval
639       monitoringFilter.Clear();
640     }
641     // add monitoring filter list
642     CreateEventDoneReadoutFilter(monitoringFilter, 4);
643   }
644   
645   // Mask the readout list according to the CTP trigger
646   // if the classes have been initialized (mask non-zero).
647   // If we are dealing with a software trigger on the other hand then
648   // mask with the participating detector list.
649   // In both cases we must make sure that HLT is part of the readout mask.
650   if (CTPData() != NULL and CTPData()->Mask() != 0x0)
651   {
652     AliHLTReadoutList readoutlist = decision.ReadoutList();
653     AliHLTReadoutList ctpreadout = CTPData()->ReadoutList(*GetTriggerData());
654     ctpreadout.Enable(AliHLTReadoutList::kHLT);
655     readoutlist.AndEq(ctpreadout);
656     decision.ReadoutList(readoutlist); // override the readout list with the masked one.
657   }
658   else if (softwareTriggerIsValid)
659   {
660     assert(fCDH != NULL);
661     AliHLTReadoutList readoutlist = decision.ReadoutList();
662     UInt_t detectors = fCDH->GetSubDetectors();
663     AliHLTReadoutList softwareReadout(Int_t(detectors | AliHLTReadoutList::kHLT));
664     readoutlist.AndEq(softwareReadout);
665     decision.ReadoutList(readoutlist); // override the readout list with the masked one.
666   }
667
668   if (TriggerEvent(&decision, kAliHLTDataTypeGlobalTrigger) == -ENOSPC)
669   {
670     // Increase the estimated buffer space required if the PushBack methods in TriggerEvent
671     // returned the "no buffer space" error code. Also remember to set the trigger counters
672     // back to what they were, otherwise triggers will be double counted when we try to reprocess
673     // this event with larger buffers.
674     fBufferSizeConst += 1024*1024;
675     fBufferSizeMultiplier *= 2.;
676     fTrigger->SetCounters(originalCounters);
677     if (fTrigger->CallFailed()) return -EPROTO;
678     return -ENOSPC;
679   }
680   
681   ++fTotalEventCounter;
682   return 0;
683 }
684
685
686 int AliHLTGlobalTriggerComponent::Reconfigure(const char* cdbEntry, const char* chainId)
687 {
688   // Reconfigure the component by loading the trigger menu and recreating the
689   // trigger logic class.
690   
691   const char* path = fgkTriggerMenuCDBPath;
692   const char* id = "(unknown)";
693   if (cdbEntry != NULL) path = cdbEntry;
694   if (chainId != NULL and chainId[0] != '\0') id = chainId;
695   HLTInfo("Reconfiguring from '%s' for chain component '%s'.", path, id);
696   
697   const AliHLTTriggerMenu* menu = NULL;
698   int result = LoadTriggerMenu(path, menu);
699   if (result != 0) return result;
700   
701   TString className;
702   TString codeFileName;
703   result = GenerateTrigger(menu, className, codeFileName, fIncludePaths, fIncludeFiles);
704   if (result != 0) return result;
705   
706   AliHLTGlobalTrigger* trigger = NULL;
707   try
708   {
709     trigger = AliHLTGlobalTrigger::CreateNew(className.Data());
710   }
711   catch (const std::bad_alloc&)
712   {
713     HLTError("Could not allocate memory for the AliHLTGlobalTrigger instance.");
714     return -ENOMEM;
715   }
716   if (trigger == NULL)
717   {
718     HLTError("Could not create a new instance of '%s'.", className.Data());
719     // Make sure to cleanup after the new code file.
720     UnloadTriggerClass(codeFileName);
721     if (not codeFileName.IsNull() and gSystem->AccessPathName(codeFileName)==0 and not fDebugMode)
722     {
723       codeFileName.ReplaceAll(".cxx", "*");
724       TString command="rm "; command+=codeFileName;
725       gSystem->Exec(command);
726     }
727     return -EIO;
728   }
729   
730   if (fTrigger != NULL)
731   {
732     delete fTrigger;
733     fTrigger = NULL;
734   }
735   
736   fTrigger = trigger;
737   fTrigger->FillFromMenu(*menu);
738   if (fTrigger->CallFailed()) return -EPROTO;
739
740   // Set the default values from the trigger menu.
741   SetDescription(menu->DefaultDescription());
742   SetTriggerDomain(menu->DefaultTriggerDomain());
743   
744   // Cleanup the old class code.
745   UnloadTriggerClass(fCodeFileName);
746   if (fDeleteCodeFile and not fCodeFileName.IsNull() and gSystem->AccessPathName(fCodeFileName)==0 and not fDebugMode)
747   {
748     fCodeFileName.ReplaceAll(".cxx", "*");
749     TString command="rm "; command+=fCodeFileName;
750     gSystem->Exec(command);
751   }
752   fCodeFileName = codeFileName;
753   fDeleteCodeFile = true;  // Since we generated a new class.
754   
755   return 0;
756 }
757
758
759 int AliHLTGlobalTriggerComponent::LoadTriggerMenu(const char* cdbPath, const AliHLTTriggerMenu*& menu)
760 {
761   // Loads the trigger menu object from the CDB path.
762   
763   HLTDebug("Trying to load trigger menu from '%s'.", cdbPath);
764   if (AliCDBManager::Instance() == NULL)
765   {
766     HLTError("CDB manager object not found.");
767     return -EIO;
768   }
769   AliCDBStorage* store = AliCDBManager::Instance()->GetDefaultStorage();
770   if (store == NULL)
771   {
772     HLTError("Could not get the the default storage for the CDB.");
773     return -EIO;
774   }
775   Int_t version = store->GetLatestVersion(cdbPath, GetRunNo());
776   if (version < 0)
777   {
778     HLTError("Could not find an entry in the CDB for \"%s\".", cdbPath);
779     return -EIO;
780   }
781   Int_t subVersion = store->GetLatestSubVersion(cdbPath, GetRunNo(), version);
782   AliCDBEntry* entry = AliCDBManager::Instance()->Get(cdbPath, GetRunNo(), version, subVersion);
783   if (entry == NULL)
784   {
785     HLTError("Could not get the CDB entry for \"%s\".", cdbPath);
786     return -EIO;
787   }
788   TObject* obj = entry->GetObject();
789   if (obj == NULL)
790   {
791     HLTError("Configuration object for \"%s\" is missing.", cdbPath);
792     return -ENOENT;
793   }
794   if (obj->IsA() != AliHLTTriggerMenu::Class())
795   {
796     HLTError("Wrong type for configuration object in \"%s\". Found a %s but we expect a AliHLTTriggerMenu.",
797              cdbPath, obj->ClassName()
798     );
799     return -EPROTO;
800   }
801   menu = static_cast<AliHLTTriggerMenu*>(obj);
802   return 0;
803 }
804
805
806 void AliHLTGlobalTriggerComponent::GenerateFileName(TString& name, TString& filename)
807 {
808   // Creates a unique file name for the generated code.
809   
810   TUUID guid = GenerateGUID();
811   union
812   {
813     UChar_t buf[16];
814     UInt_t bufAsInt[4];
815   };
816   guid.GetUUID(buf);
817   fUniqueID = bufAsInt[0];
818   TString guidstr = guid.AsString();
819   // Replace '-' with '_' in string.
820   for (int i = 0; i < guidstr.Length(); ++i)
821   {
822     if (guidstr[i] == '-') guidstr[i] = '_';
823   }
824   name = "AliHLTGlobalTriggerImpl_";
825   name += guidstr;
826   filename = name + ".cxx";
827
828   // For good measure, check that the file names are not used. If they are then regenerate.
829   fstream file(filename.Data(), ios_base::in);
830   if (file.good())
831   {
832     file.close();
833     GenerateFileName(name, filename);
834   }
835 }
836
837
838 int AliHLTGlobalTriggerComponent::GenerateTrigger(
839     const AliHLTTriggerMenu* menu, TString& name, TString& filename,
840     const TClonesArray& includePaths, const TClonesArray& includeFiles
841   )
842 {
843   // Generates the global trigger class that will implement the specified trigger menu.
844   // See header for more details.
845   
846   GenerateFileName(name, filename);
847   HLTDebug("Generating custom HLT trigger class named %s, in file %s, using trigger menu %p.",
848     name.Data(), filename.Data(), ((void*)menu)
849   );
850   
851   // Open a text file to write the code and generate the new class.
852   fstream code(filename.Data(), ios_base::out | ios_base::trunc);
853   if (not code.good())
854   {
855     HLTError("Could not open file '%s' for writing.", filename.Data());
856     return -EIO;
857   }
858   
859   TClonesArray symbols(AliHLTTriggerMenuSymbol::Class());
860   int result = BuildSymbolList(menu, symbols);
861   if (result != 0) return result;
862   
863   code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
864   code << "#include <cstring>" << endl;
865   code << "#include \"TClass.h\"" << endl;
866   code << "#include \"TString.h\"" << endl;
867   code << "#include \"TClonesArray.h\"" << endl;
868   code << "#include \"TRandom3.h\"" << endl;
869   code << "#include \"AliHLTLogging.h\"" << endl;
870   code << "#include \"AliHLTGlobalTrigger.h\"" << endl;
871   code << "#include \"AliHLTGlobalTriggerDecision.h\"" << endl;
872   code << "#include \"AliHLTDomainEntry.h\"" << endl;
873   code << "#include \"AliHLTTriggerDomain.h\"" << endl;
874   code << "#include \"AliHLTReadoutList.h\"" << endl;
875   code << "#include \"AliHLTTriggerMenu.h\"" << endl;
876   code << "#include \"AliHLTTriggerMenuItem.h\"" << endl;
877   code << "#include \"AliHLTTriggerMenuSymbol.h\"" << endl;
878   
879   // Add any include files that were specified on the command line.
880   for (Int_t i = 0; i < includeFiles.GetEntriesFast(); i++)
881   {
882     TString file = static_cast<TObjString*>(includeFiles.UncheckedAt(i))->String();
883     code << "#include \"" << file.Data() << "\"" << endl;
884   }
885   
886   if (fDebugMode)
887   {
888     code << "#else" << endl;
889     code << "const char* gFunctionName = \"???\";" << endl;
890     code << "#define HLTDebug(msg) if (CheckFilter(kHLTLogDebug) && CheckGroup(Class_Name())) SendMessage(kHLTLogDebug, Class_Name(), ::gFunctionName, __FILE__, __LINE__, msg)" << endl;
891   }
892   code << "#endif" << endl;
893   
894   code << "class " << name << " :" << endl;
895   // Add appropriate #ifdef sections since we need to prevent inheritance from
896   // AliHLTGlobalTrigger. CINT does not seem to support multiple inheritance nor
897   // multiple levels of inheritance. Neither of the following schemes worked:
898   //
899   // 1)  class AliHLTGlobalTrigger : public AliHLTLogging {};
900   //     class AliHLTGlobalTriggerImpl_xyz : public AliHLTGlobalTrigger {};
901   //
902   // 2)  class AliHLTGlobalTrigger {};
903   //     class AliHLTGlobalTriggerImpl_xyz : public AliHLTGlobalTrigger, public AliHLTLogging {};
904   //
905   // Thus, we are forced to just inherit from AliHLTLogging when running in the CINT
906   // interpreter. But we anyway have to call the global trigger implementation class
907   // through the AliHLTGlobalTriggerWrapper so this is not such a problem.
908   code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
909   code << "  public AliHLTGlobalTrigger," << endl;
910   code << "#endif" << endl;
911   code << "  public AliHLTLogging" << endl;
912   code << "{" << endl;
913   code << "public:" << endl;
914   
915   // Generate constructor method.
916   code << "  " << name << "() :" << endl;
917   code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
918   code << "    AliHLTGlobalTrigger()," << endl;
919   code << "#endif" << endl;
920   code << "    AliHLTLogging()";
921   // Write the symbols in the trigger menu in the initialisation list.
922   for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
923   {
924     code << "," << endl;
925     AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
926     code << "    " << symbol->Name() << "()," << endl;
927     if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
928     {
929       code << "    " << symbol->Name() << "TriggerDomain()," << endl;
930     }
931     code << "    " << symbol->Name() << "DomainEntry(kAliHLTAnyDataType)";
932   }
933   for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
934   {
935     code << "," << endl << "    fMenuItemDescription" << i << "()";
936   }
937   code << endl << "  {" << endl;
938   if (fDebugMode)
939   {
940     code << "#ifdef __CINT__" << endl;
941     code << "    gFunctionName = \"" << name.Data() <<"\";" << endl;
942     code << "#endif" << endl;
943     code << "    SetLocalLoggingLevel(kHLTLogAll);" << endl;
944     code << "    HLTDebug(Form(\"Creating new instance at %p.\", this));" << endl;
945   }
946   code << "  }" << endl;
947   
948   code << "  virtual ~" << name << "() {" << endl;
949   if (fDebugMode)
950   {
951     code << "#ifdef __CINT__" << endl;
952     code << "    gFunctionName = \"~" << name.Data() << "\";" << endl;
953     code << "#endif" << endl;
954     code << "    HLTDebug(Form(\"Deleting instance at %p.\", this));" << endl;
955   }
956   code << "  }" << endl;
957   
958   // Generate the FillFromMenu method.
959   code << "  virtual void FillFromMenu(const AliHLTTriggerMenu& menu) {" << endl;
960   if (fDebugMode)
961   {
962     code << "#ifdef __CINT__" << endl;
963     code << "    gFunctionName = \"FillFromMenu\";" << endl;
964     code << "#endif" << endl;
965     code << "    HLTDebug(Form(\"Filling description entries from trigger menu for global trigger %p.\", this));" << endl;
966   }
967   code << "    fCounter.Set(menu.NumberOfItems());" << endl;
968   for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
969   {
970     code << "    fMenuItemDescription" << i << " = (menu.Item(" << i
971          << ") != NULL) ? menu.Item(" << i << ")->Description() : \"\";" << endl;
972   }
973   if (fDebugMode)
974   {
975     code << "    HLTDebug(Form(\"Finished filling description entries from trigger menu.\"));" << endl;
976     code << "    HLTDebug(Form(\"Filling domain entries from trigger menu symbols for global trigger %p.\", this));" << endl;
977   }
978   code << "    for (Int_t i = 0; i < menu.SymbolArray().GetEntriesFast(); i++) {" << endl;
979   // 30 Oct 2009 - CINT sometimes evaluates the dynamic_cast incorrectly.
980   // Have to use the TClass system for extra protection.
981   code << "      if (menu.SymbolArray().UncheckedAt(i) == NULL) continue;" << endl;
982   code << "      if (menu.SymbolArray().UncheckedAt(i)->IsA() != AliHLTTriggerMenuSymbol::Class()) continue;" << endl;
983   code << "      const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const"
984            " AliHLTTriggerMenuSymbol*>(menu.SymbolArray().UncheckedAt(i));" << endl;
985   code << "      if (symbol == NULL) continue;" << endl;
986   for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
987   {
988     AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
989     code << "      if (strcmp(symbol->RealName(), \"" << symbol->RealName() << "\") == 0) {" << endl;
990     if (fDebugMode)
991     {
992       code << "        HLTDebug(Form(\"Assinging domain entry value corresponding with symbol '%s' to '%s'.\","
993               " symbol->RealName(), symbol->BlockType().AsString().Data()));" << endl;
994     }
995     code << "        " << symbol->Name() << "DomainEntry = symbol->BlockType();" << endl;
996     code << "        continue;" << endl;
997     code << "      }" << endl;
998   }
999   code << "    }" << endl;
1000   // The following is an optimisation where symbols without any assignment operators
1001   // are treated as constant and only initialised in FillFromMenu rather than reseting
1002   // them in the NewEvent method.
1003   // Note: we putting this initialisation into the constructor can lead to seg faults
1004   // under CINT interpretation. Thus we must put it into the FillFromMenu method instead.
1005   for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
1006   {
1007     AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
1008     if (TString(symbol->AssignExpression()) != "") continue;
1009     if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0) continue;
1010     // CINT has problems with the implicit equals operator for complex types, so if
1011     // the type has an equals operater we need to write the operator call explicitly.
1012     TClass* clas = TClass::GetClass(symbol->Type());
1013     if (clas != NULL and clas->GetMethodAny("operator=") != NULL)
1014     {
1015       code << "    " << symbol->Name() << ".operator = (" << symbol->DefaultValue() << ");" << endl;
1016     }
1017     else
1018     {
1019       code << "    " << symbol->Name() << " = " << symbol->DefaultValue() << ";" << endl;
1020     }
1021   }
1022   if (fDebugMode)
1023   {
1024     code << "    HLTDebug(Form(\"Finished filling domain entries from trigger menu symbols.\"));" << endl;
1025   }
1026   code << "  }" << endl;
1027   
1028   // Generate the NewEvent method.
1029   code << "  virtual void NewEvent() {" << endl;
1030   if (fDebugMode)
1031   {
1032     code << "#ifdef __CINT__" << endl;
1033     code << "    gFunctionName = \"NewEvent\";" << endl;
1034     code << "#endif" << endl;
1035     code << "    HLTDebug(Form(\"New event for global trigger object %p, initialising variables to default values.\", this));" << endl;
1036   }
1037   // Write code to initialise the symbols in the trigger menu to their default values.
1038   for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
1039   {
1040     AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
1041     // The following is an optimisation. If the symbol does not have an assignment expression
1042     // then it is effectively a constant symbol and can be initialised earlier and only once.
1043     // In this case we initialise it in the FillFromMenu method instead.
1044     if (TString(symbol->AssignExpression()) == "") continue;
1045     // CINT has problems with the implicit equals operator for complex types, so if
1046     // the type has an equals operater we need to write the operator call explicitly.
1047     TClass* clas = TClass::GetClass(symbol->Type());
1048     if (clas != NULL and clas->GetMethodAny("operator=") != NULL)
1049     {
1050       code << "    " << symbol->Name() << ".operator = (" << symbol->DefaultValue() << ");" << endl;
1051     }
1052     else
1053     {
1054       code << "    " << symbol->Name() << " = " << symbol->DefaultValue() << ";" << endl;
1055     }
1056     if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
1057     {
1058       code << "    " << symbol->Name() << "TriggerDomain.Clear();" << endl;
1059     }
1060   }
1061   if (fDebugMode)
1062   {
1063     code << "    HLTDebug(Form(\"Finished initialising variables.\"));" << endl;
1064   }
1065   code << "  }" << endl;
1066   
1067   // Generate the Add method.
1068   bool haveAssignments = false;
1069   for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
1070   {
1071     // First check if we have any symbols with assignment expressions.
1072     // This is needed to get rid of the on the fly compilation warning about '_object_' not being used.
1073     AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
1074     TString expr = symbol->AssignExpression();
1075     if (expr == "") continue; // Skip entries that have no assignment expression.
1076     haveAssignments = true;
1077     break;
1078   }
1079   if (haveAssignments or fDebugMode)
1080   {
1081     code << "  virtual void Add(const TObject* _object_, const AliHLTComponentDataType& _type_, AliHLTUInt32_t _spec_) {" << endl;
1082   }
1083   else
1084   {
1085     code << "  virtual void Add(const TObject* /*_object_*/, const AliHLTComponentDataType& _type_, AliHLTUInt32_t _spec_) {" << endl;
1086   }
1087   if (fDebugMode)
1088   {
1089     code << "#ifdef __CINT__" << endl;
1090     code << "    gFunctionName = \"Add\";" << endl;
1091     code << "#endif" << endl;
1092   }
1093   code << "    AliHLTDomainEntry _type_spec_(_type_, _spec_);" << endl;
1094   if (fDebugMode)
1095   {
1096     code << "    HLTDebug(Form(\"Adding TObject %p, with class name '%s' from data block"
1097             " '%s', to global trigger object %p\", _object_, _object_->ClassName(),"
1098             " _type_spec_.AsString().Data(), this));" << endl;
1099     code << "    _object_->Print();" << endl;
1100     code << "    bool _object_assigned_ = false;" << endl;
1101   }
1102   for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
1103   {
1104     // Write code to check if the block type, specification and class name is correct.
1105     // Then write code to assign the variable from the input object.
1106     AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
1107     TString expr = symbol->AssignExpression();
1108     if (expr == "") continue; // Skip entries that have no assignment expression.
1109     bool isTrigDecision = strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0;
1110     if (fDebugMode)
1111     {
1112       if (isTrigDecision)
1113       {
1114         code << "    HLTDebug(Form(\"Trying to match input object to class '"
1115              << symbol->ObjectClass() << "', trigger name '" << symbol->RealName()
1116              << "' and block type '%s'\", " << symbol->Name()
1117              << "DomainEntry.AsString().Data()));" << endl;
1118       }
1119       else
1120       {
1121         code << "    HLTDebug(Form(\"Trying to match input object to class '"
1122              << symbol->ObjectClass() << "' and block type '%s'\", "
1123              << symbol->Name() << "DomainEntry.AsString().Data()));" << endl;
1124       }
1125     }
1126     // 30 Oct 2009 - CINT sometimes evaluates the dynamic_cast incorrectly.
1127     // Have to use the TClass system for extra protection.
1128     code << "    const " << symbol->ObjectClass() << "* " << symbol->Name() << "_object_ = NULL;" << endl;
1129     code << "    if (_object_->InheritsFrom(" << symbol->ObjectClass() << "::Class())) " << symbol->Name()
1130          << "_object_ = dynamic_cast<const " << symbol->ObjectClass()
1131          << "*>(_object_);" << endl;
1132     code << "    if (" << symbol->Name() << "_object_ != NULL && ";
1133     if (isTrigDecision)
1134     {
1135       code << "strcmp(" << symbol->Name() << "_object_->Name(), \""
1136            << symbol->RealName() << "\") == 0 && ";
1137     }
1138     code << symbol->Name() << "DomainEntry == _type_spec_) {" << endl;
1139     TString fullname = symbol->Name();
1140     fullname += "_object_";
1141     expr.ReplaceAll("this", fullname);
1142     code << "      this->" << symbol->Name() << " = " << expr.Data() << ";" << endl;
1143     if (isTrigDecision)
1144     {
1145       code << "      this->" << symbol->Name() << "TriggerDomain = "
1146            << fullname.Data() << "->TriggerDomain();" << endl;
1147     }
1148     if (fDebugMode)
1149     {
1150       code << "      HLTDebug(Form(\"Added TObject %p with class name '%s' to variable "
1151            << symbol->Name() << "\", _object_, _object_->ClassName()));" << endl;
1152       code << "      _object_assigned_ = true;" << endl;
1153     }
1154     code << "    }" << endl;
1155   }
1156   if (fDebugMode)
1157   {
1158     code << "    if (! _object_assigned_) {" << endl;
1159     code << "      HLTDebug(Form(\"Did not assign TObject %p"
1160             " with class name '%s' to any variable.\", _object_, _object_->ClassName()));"
1161          << endl;
1162     code << "    }" << endl;
1163   }
1164   code << "  }" << endl;
1165   
1166   // Generate the CalculateTriggerDecision method.
1167   // This requires code to be generated that checks which items in the trigger menu
1168   // have their conditions asserted and then the trigger domain is generated from
1169   // those fired items.
1170   // The processing will start from the highest priority trigger group and stop
1171   // after at least one trigger from the current priority group being processed
1172   // is positive. For each priority group all the trigger menu items are checked.
1173   // Their combined trigger condition expression must be true for the trigger priority
1174   // group to be triggered positive. The full condition expression is formed by
1175   // concatenating the individual condition expressions. If no trailing operators are
1176   // used in the individual expressions then the default condition operator is placed
1177   // between two concatenated condition expressions.
1178   // If a trigger priority group has at least one trigger fired then the trigger domain
1179   // is calculated such that it will give the same result as the concatenated trigger
1180   // domain merging expressions for all the individual trigger menu items with
1181   // positive results. Again, if no trailing operators are used in the individual
1182   // merging expressions then the default domain operator is placed between two
1183   // expression fragments.
1184   code << "  virtual bool CalculateTriggerDecision(bool& _trigger_result_, AliHLTTriggerDomain& _domain_, TString& _description_) {" << endl;
1185   if (fDebugMode)
1186   {
1187     code << "#ifdef __CINT__" << endl;
1188     code << "    gFunctionName = \"CalculateTriggerDecision\";" << endl;
1189     code << "#endif" << endl;
1190     code << "    HLTDebug(Form(\"Calculating global HLT trigger result with trigger object at %p.\", this));" << endl;
1191   }
1192   
1193   // Build a list of priorities used in the trigger menu.
1194   std::vector<UInt_t> priorities;
1195   for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1196   {
1197     const AliHLTTriggerMenuItem* item = menu->Item(i);
1198     bool priorityNotInList = std::find(priorities.begin(), priorities.end(), item->Priority()) == priorities.end();
1199     if (priorityNotInList) priorities.push_back(item->Priority());
1200   }
1201   std::sort(priorities.begin(), priorities.end(), AliHLTDescendingNumbers);
1202   // From the priority list, build the priority groups in the correct order,
1203   // i.e. highest priority first.
1204   // The priority group is a list of vectors of integers. The integers are the
1205   // index numbers into the trigger menu item list for the items which form part
1206   // of the priority group.
1207   std::vector<std::vector<Int_t> > priorityGroup;
1208   priorityGroup.insert(priorityGroup.begin(), priorities.size(), std::vector<Int_t>());
1209   for (size_t n = 0; n < priorities.size(); n++)
1210   {
1211     UInt_t priority = priorities[n];
1212     for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1213     {
1214       const AliHLTTriggerMenuItem* item = menu->Item(i);
1215       if (item->Priority() == priority) priorityGroup[n].push_back(i);
1216     }
1217   }
1218   
1219   for (size_t n = 0; n < priorityGroup.size(); n++)
1220   {
1221     if (fDebugMode)
1222     {
1223       code << "    HLTDebug(Form(\"Processing trigger priority group " << priorities[n] << "\"));" << endl;
1224     }
1225     code << "    ";
1226     if (n == 0) code << "UInt_t ";
1227     code << "_previous_match_ = 0xFFFFFFFF;" << endl;
1228     code << "    ";
1229     if (n == 0) code << "bool ";
1230     code << "_trigger_matched_ = false;" << endl;
1231     code << "    ";
1232     if (n == 0) code << "bool ";
1233     code << "_group_result_ = false;" << endl;
1234     std::vector<TString> conditionOperator;
1235     conditionOperator.insert(conditionOperator.begin(), priorityGroup[n].size(), TString(""));
1236     std::vector<TString> domainOperator;
1237     domainOperator.insert(domainOperator.begin(), priorityGroup[n].size(), TString(""));
1238     for (size_t m = 0; m < priorityGroup[n].size(); m++)
1239     {
1240       UInt_t i = priorityGroup[n][m];
1241       const AliHLTTriggerMenuItem* item = menu->Item(i);
1242       TString triggerCondition = item->TriggerCondition();
1243       TString mergeExpr = item->MergeExpression();
1244       // Replace the symbols found in the trigger condition and merging expressions
1245       // with appropriate compilable versions.
1246       for (Int_t j = 0; j < symbols.GetEntriesFast(); j++)
1247       {
1248         AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(j) );
1249         bool symbolNamesDifferent = strcmp(symbol->RealName(), symbol->Name()) != 0;
1250         if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
1251         {
1252           TString newname = symbol->Name();
1253           newname += "TriggerDomain";
1254           mergeExpr.ReplaceAll(symbol->RealName(), newname);
1255         }
1256         else
1257         {
1258           if (symbolNamesDifferent) mergeExpr.ReplaceAll(symbol->RealName(), symbol->Name());
1259         }
1260         if (symbolNamesDifferent) triggerCondition.ReplaceAll(symbol->RealName(), symbol->Name());
1261       }
1262       // We allow the trigger conditions and merging expressions to have trailing operators.
1263       // Thus, we need to extract the operators and cleanup the expressions so that they will
1264       // compile. This means that we silently ignore the trailing operator if not needed.
1265       if (ExtractedOperator(triggerCondition, conditionOperator[m]))
1266       {
1267         // If the trailing operator is the same as the default operator then reset
1268         // the value in the operator list so that the default is used in the generated
1269         // code. This creates more compact code.
1270         if (conditionOperator[m] == menu->DefaultConditionOperator()) conditionOperator[m] = "";
1271       }
1272       if (ExtractedOperator(mergeExpr, domainOperator[m]))
1273       {
1274         if (domainOperator[m] == menu->DefaultDomainOperator()) domainOperator[m] = "";
1275       }
1276       if (fDebugMode)
1277       {
1278         code << "    HLTDebug(Form(\"Trying trigger condition " << i
1279              << " (Description = '%s').\", fMenuItemDescription" << i << ".Data()));"
1280              << endl;
1281       }
1282       code << "    ";
1283       if (n == 0 and m == 0) code << "bool ";
1284       code << "_item_result_ = false;" << endl;
1285       code << "    if (" << triggerCondition << ") {" << endl;
1286       code << "      ++fCounter[" << i << "];" << endl;
1287       const char* indentation = "";
1288       // Generate the code to handle the prescalar and scale-down
1289       bool havePrescalar = item->PreScalar() != 0;
1290       bool haveScaledown = item->ScaleDown() < 1;
1291       if (havePrescalar or haveScaledown) 
1292       {
1293         indentation = "  ";
1294         code << "      if (";
1295         if (havePrescalar) code << "(fCounter[" << i << "] % " << item->PreScalar() << ") == 1";
1296         if (havePrescalar and haveScaledown) code << " && ";
1297         if (haveScaledown)
1298         {
1299           std::streamsize oldprecision = code.precision(17);
1300           code << "gRandom->Rndm() < " << item->ScaleDown();
1301           code.precision(oldprecision);
1302         }
1303         code << ") {" << endl;
1304       }
1305       code << indentation << "      _item_result_ = true;" << endl;
1306       if (fDebugMode)
1307       {
1308         code << indentation << "      HLTDebug(Form(\"Matched trigger condition " << i
1309              << " (Description = '%s').\", fMenuItemDescription" << i << ".Data()));" << endl;
1310       }
1311       if (havePrescalar or haveScaledown)
1312       {
1313         code << "      }" << endl;
1314       }
1315       code << "    }" << endl;
1316       if (m == 0)
1317       {
1318         // Since this is the first item of the trigger group,
1319         // the generated trigger logic can be simplified a little.
1320         code << "    _group_result_ = _item_result_;" << endl;
1321         code << "    if (_item_result_) {" << endl;
1322         code << "      _domain_ = " << mergeExpr.Data() << ";" << endl;
1323         code << "      _description_ = fMenuItemDescription" << i << ";" << endl;
1324         code << "      _previous_match_ = " << i << ";" << endl;
1325         code << "      _trigger_matched_ = true;" << endl;
1326         code << "    }" << endl;
1327       }
1328       else
1329       {
1330         if (conditionOperator[m-1] == "")
1331         {
1332           code << "    _group_result_ = _group_result_ "
1333                << menu->DefaultConditionOperator() << " _item_result_;" << endl;
1334         }
1335         else
1336         {
1337           code << "    _group_result_ = _group_result_ "
1338                << conditionOperator[m-1] << " _item_result_;" << endl;
1339         }
1340         code << "    if (_item_result_) {" << endl;
1341         code << "      if (_trigger_matched_) {" << endl;
1342         bool switchWillBeEmpty = true;
1343         for (size_t k = 0; k < m; k++)
1344         {
1345           if (domainOperator[k] == "") continue;
1346           switchWillBeEmpty = false;
1347         }
1348         if (switchWillBeEmpty)
1349         {
1350           code << "        _domain_ = _domain_ " << menu->DefaultDomainOperator() << " "
1351                << mergeExpr.Data() << ";" << endl;
1352         }
1353         else
1354         {
1355           code << "        switch(_previous_match_) {" << endl;
1356           for (size_t k = 0; k < m; k++)
1357           {
1358             if (domainOperator[k] == "") continue;
1359             code << "        case " << k << ": _domain_ = _domain_ "
1360                  << domainOperator[k] << " " << mergeExpr.Data() << "; break;" << endl;
1361           }
1362           code << "        default: _domain_ = _domain_ "
1363                << menu->DefaultDomainOperator() << " " << mergeExpr.Data() << ";" << endl;
1364           code << "        }" << endl;
1365         }
1366         code << "        _description_ += \",\";" << endl;
1367         code << "        _description_ += fMenuItemDescription" << i << ";" << endl;
1368         code << "      } else {" << endl;
1369         code << "        _domain_ = " << mergeExpr.Data() << ";" << endl;
1370         code << "        _description_ = fMenuItemDescription" << i << ";" << endl;
1371         code << "      }" << endl;
1372         code << "      _previous_match_ = " << i << ";" << endl;
1373         code << "      _trigger_matched_ = true;" << endl;
1374         code << "    }" << endl;
1375       }
1376     }
1377     code << "    if (_group_result_) {" << endl;
1378     if (fDebugMode)
1379     {
1380       if (n < priorities.size() - 1)
1381       {
1382         code << "      HLTDebug(Form(\"Matched triggers in trigger priority group " << priorities[n]
1383              << ". Stopping processing here because all other trigger groups have lower priority.\"));" << endl;
1384       }
1385       else
1386       {
1387         code << "      HLTDebug(Form(\"Matched triggers in trigger priority group " << priorities[n] << ".\"));" << endl;
1388       }
1389     }
1390     bool methodReturnResult = true;
1391     if (priorityGroup[n].size() > 0)
1392     {
1393       const AliHLTTriggerMenuItem* item = menu->Item(priorityGroup[n][0]);
1394       methodReturnResult = item->DefaultResult();
1395     }
1396     // Check to see if the items of the group all have the same default result.
1397     // If not then warn the user since only the first item's value will be used.
1398     for (size_t m = 1; m < priorityGroup[n].size(); m++)
1399     {
1400       const AliHLTTriggerMenuItem* item = menu->Item(priorityGroup[n][m]);
1401       if (item->DefaultResult() != methodReturnResult)
1402       {
1403         HLTWarning("Found items with different default results set for priority group %d."
1404                    "Will only use the value from the first item.",
1405                    item->Priority()
1406                   );
1407         break;
1408       }
1409     }
1410     code << "      _trigger_result_ = " << (methodReturnResult ? "true" : "false") << ";" << endl;
1411     code << "      return true;" << endl;
1412     code << "    }" << endl;
1413   }
1414   code << "    _domain_.Clear();" << endl;
1415   code << "    _description_ = \"\";" << endl;
1416   code << "    _trigger_result_ = " << (menu->DefaultResult() ? "true" : "false") << ";" << endl;
1417   code << "    return false;" << endl;
1418   code << "  }" << endl;
1419   
1420   // Generate getter and setter methods for the counters.
1421   code << "  const TArrayL64& GetCounters() const { return fCounter; }" << endl;
1422   code << "  void SetCounters(const TArrayL64& counters) { fCounter = counters; }" << endl;
1423   
1424   code << "private:" << endl;
1425   // Add the symbols in the trigger menu to the list of private variables.
1426   for (Int_t i = 0; i < symbols.GetEntriesFast(); i++)
1427   {
1428     AliHLTTriggerMenuSymbol* symbol = static_cast<AliHLTTriggerMenuSymbol*>( symbols.UncheckedAt(i) );
1429     code << "  " << symbol->Type() << " " << symbol->Name() << ";" << endl;
1430     if (strcmp(symbol->ObjectClass(), "AliHLTTriggerDecision") == 0)
1431     {
1432       code << "  AliHLTTriggerDomain " << symbol->Name() << "TriggerDomain;" << endl;
1433     }
1434     code << "  AliHLTDomainEntry " << symbol->Name() << "DomainEntry;" << endl;
1435   }
1436   for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1437   {
1438     code << "  TString fMenuItemDescription" << i << ";" << endl;
1439   }
1440   code << "  TArrayL64 fCounter;" << endl;
1441   code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
1442   code << "  ClassDef(" << name.Data() << ", 0)" << endl;
1443   code << "#else" << endl;
1444   code << "  virtual const char* Class_Name() const { return \"" << name.Data() << "\"; }" << endl;
1445   code << "#endif" << endl;
1446   code << "};" << endl;
1447   code << "#if !defined(__CINT__) || defined(__MAKECINT__)" << endl;
1448   code << "ClassImp(" << name.Data() << ")" << endl;
1449   code << "#endif" << endl;
1450   
1451   code.close();
1452   
1453   // Now we need to compile and load the new class.
1454   result = LoadTriggerClass(filename, includePaths);
1455   return result;
1456 }
1457
1458
1459 int AliHLTGlobalTriggerComponent::LoadTriggerClass(
1460     const char* filename, const TClonesArray& includePaths
1461   )
1462 {
1463   // Loads the code for a custom global trigger class implementation on the fly.
1464   
1465   HLTDebug("Loading HLT trigger class from file '%s'.", filename);
1466   
1467   TString compiler = gSystem->GetBuildCompilerVersion();
1468   if (fRuntimeCompile && (compiler.Contains("gcc") or compiler.Contains("icc")))
1469   {
1470     TString includePath;
1471 #if defined(PKGINCLUDEDIR)
1472     // this is especially for the HLT build system where the package is installed
1473     // in a specific directory including proper treatment of include files
1474     includePath.Form("-I%s", PKGINCLUDEDIR);
1475 #else
1476     // the default AliRoot behavior, all include files can be found in the
1477     // $ALICE_ROOT subfolders
1478     includePath = "-I${ALICE_ROOT}/include -I${ALICE_ROOT}/HLT/BASE -I${ALICE_ROOT}/HLT/trigger";
1479 #endif
1480     // Add any include paths that were specified on the command line.
1481     for (Int_t i = 0; i < includePaths.GetEntriesFast(); i++)
1482     {
1483       TString path = static_cast<TObjString*>(includePaths.UncheckedAt(i))->String();
1484       includePath += " -I";
1485       includePath += path;
1486     }
1487     HLTDebug("using include settings: %s", includePath.Data());
1488     gSystem->SetIncludePath(includePath);
1489     gSystem->SetFlagsOpt("-O3 -DNDEBUG");
1490     gSystem->SetFlagsDebug("-g3 -DDEBUG -D__DEBUG");
1491     
1492     int result = kTRUE;
1493     if (fDebugMode)
1494     {
1495       result = gSystem->CompileMacro(filename, "g");
1496     }
1497     else
1498     {
1499       result = gSystem->CompileMacro(filename, "O");
1500     }
1501     if (result != kTRUE)
1502     {
1503       HLTFatal("Could not compile and load global trigger menu implementation.");
1504       return -ENOENT;
1505     }
1506   }
1507   else
1508   {
1509     // Store the library state to be checked later in UnloadTriggerClass.
1510     fLibStateAtLoad = gSystem->GetLibraries();
1511     
1512     // If we do not support the compiler then try interpret the class instead.
1513     TString cmd = ".L ";
1514     cmd += filename;
1515     Int_t errorcode = TInterpreter::kNoError;
1516     gROOT->ProcessLine(cmd, &errorcode);
1517     if (errorcode != TInterpreter::kNoError)
1518     {
1519       HLTFatal("Could not load interpreted global trigger menu implementation"
1520                " (Interpreter error code = %d).",
1521                errorcode
1522       );
1523       return -ENOENT;
1524     }
1525   }
1526   
1527   return 0;
1528 }
1529
1530
1531 int AliHLTGlobalTriggerComponent::UnloadTriggerClass(const char* filename)
1532 {
1533   // Unloads the code previously loaded by LoadTriggerClass.
1534   
1535   HLTDebug("Unloading HLT trigger class in file '%s'.", filename);
1536   
1537   TString compiler = gSystem->GetBuildCompilerVersion();
1538   if (fRuntimeCompile && (compiler.Contains("gcc") or compiler.Contains("icc")))
1539   {
1540     // Generate the library name.
1541     TString libname = filename;
1542     Ssiz_t dotpos = libname.Last('.');
1543     if (0 <= dotpos and dotpos < libname.Length()) libname[dotpos] = '_';
1544     libname += ".";
1545     libname += gSystem->GetSoExt();
1546     
1547     // This is a workaround for a problem with unloading shared libraries in ROOT.
1548     // If the trigger logic library is loaded before the libAliHLTHOMER.so library
1549     // or any other library is loaded afterwards, then during the gInterpreter->UnloadFile
1550     // call all the subsequent libraries get unloded. This means that any objects created
1551     // from classes implemented in the libAliHLTHOMER.so library will generate segfaults
1552     // since the executable code has been unloaded.
1553     // We need to check if there are any more libraries loaded after the class we
1554     // are unloading and in that case don't unload the class.
1555     TString libstring = gSystem->GetLibraries();
1556     TString token, lastlib;
1557     Ssiz_t from = 0;
1558     Int_t numOfLibs = 0, posOfLib = -1;
1559     while (libstring.Tokenize(token, from, " "))
1560     {
1561       ++numOfLibs;
1562       lastlib = token;
1563       if (token.Contains(libname)) posOfLib = numOfLibs;
1564     }
1565     if (numOfLibs != posOfLib)
1566     {
1567       HLTWarning(Form("ROOT limitation! Cannot properly cleanup and unload the shared"
1568           " library '%s' since another library '%s' was loaded afterwards. Trying to"
1569           " unload this library will remove the others and lead to serious memory faults.",
1570           libname.Data(), lastlib.Data()
1571       ));
1572       return 0;
1573     }
1574     
1575     char* path = NULL;
1576     int result = 0;
1577     if ((path = gSystem->DynamicPathName(libname)) != NULL)
1578     {
1579       result = gInterpreter->UnloadFile(path);
1580       delete [] path;
1581     }
1582     if (result != TInterpreter::kNoError) return -ENOENT;
1583   }
1584   else
1585   {
1586     // This is again a workaround for the problem with unloading files in ROOT.
1587     // If the trigger logic class is loaded before the libAliHLTHOMER.so library
1588     // or any other library is loaded afterwards, then during the gInterpreter->UnloadFile
1589     // call all the subsequent libraries get unloded.
1590     // We need to check if the list of loaded libraries has changed since the last
1591     // call to LoadTriggerClass. If it has then don't unload the class.
1592     if (fLibStateAtLoad != gSystem->GetLibraries())
1593     {
1594       TString libstring = gSystem->GetLibraries();
1595       TString token;
1596       Ssiz_t from = 0;
1597       while (libstring.Tokenize(token, from, " "))
1598       {
1599         if (not fLibStateAtLoad.Contains(token)) break;
1600       }
1601       HLTWarning(Form("ROOT limitation! Cannot properly cleanup and unload the file"
1602           " '%s' since another library '%s' was loaded afterwards. Trying to unload"
1603           " this file will remove the other library and lead to serious memory faults.",
1604           filename, token.Data()
1605       ));
1606       return 0;
1607     }
1608   
1609     // If we did not compile the trigger logic then remove the interpreted class.
1610     TString cmd = ".U ";
1611     cmd += filename;
1612     Int_t errorcode = TInterpreter::kNoError;
1613     gROOT->ProcessLine(cmd, &errorcode);
1614     if (errorcode != TInterpreter::kNoError)
1615     {
1616       HLTFatal("Could not unload interpreted global trigger menu implementation"
1617                " (Interpreter error code = %d).",
1618                errorcode
1619       );
1620       return -ENOENT;
1621     }
1622   }
1623   
1624   return 0;
1625 }
1626
1627
1628 int AliHLTGlobalTriggerComponent::FindSymbol(const char* name, const TClonesArray& list)
1629 {
1630   // Searches for the named symbol in the given list.
1631   // See header for more details.
1632   
1633   for (int i = 0; i < list.GetEntriesFast(); i++)
1634   {
1635     const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const AliHLTTriggerMenuSymbol*>( list.UncheckedAt(i) );
1636     if (symbol == NULL) continue;
1637     if (strcmp(symbol->Name(), name) == 0) return i;
1638   }
1639   return -1;
1640 }
1641
1642
1643 namespace
1644 {
1645   /**
1646    * Helper routine to compare two trigger menu symbols to see if b is a subset of a.
1647    * \returns true if b is a subset of a or they are unrelated.
1648    */
1649   bool AliHLTCheckForContainment(const AliHLTTriggerMenuSymbol* a, const AliHLTTriggerMenuSymbol* b)
1650   {
1651     TString bstr = b->Name();
1652     return bstr.Contains(a->Name());
1653   }
1654
1655 } // end of namespace
1656
1657
1658 int AliHLTGlobalTriggerComponent::BuildSymbolList(const AliHLTTriggerMenu* menu, TClonesArray& list)
1659 {
1660   // Builds the list of symbols to use in the custom global trigger menu
1661   // implementation class.
1662   // See header for more details.
1663   
1664   // Note: when we build the symbol list we must use the symbol name as returned
1665   // by the Name() method and not the RealName() method when using FindSymbol.
1666   // This is so that we avoid problems with the generated code not compiling
1667   // because names like "abc-xyz" and "abc_xyz" are synonymous.
1668   // Name() returns the converted C++ symbol name as used in the generated code.
1669   
1670   for (UInt_t i = 0; i < menu->NumberOfSymbols(); i++)
1671   {
1672     const AliHLTTriggerMenuSymbol* symbol = menu->Symbol(i);
1673     if (FindSymbol(symbol->Name(), list) != -1)
1674     {
1675       HLTError("Multiple symbols with the name '%s' defined in the trigger menu.", symbol->Name());
1676       return -EIO;
1677     }
1678     try
1679     {
1680       new (list[list.GetEntriesFast()]) AliHLTTriggerMenuSymbol(*symbol);
1681     }
1682     catch (const std::bad_alloc&)
1683     {
1684       HLTError("Could not allocate more memory for the symbols list when adding a trigger menu symbol.");
1685       return -ENOMEM;
1686     }
1687   }
1688   Int_t initialEntryCount = list.GetEntriesFast();
1689   
1690   // Note: the \\. must not be the first element in the character class, otherwise
1691   // it is interpreted as an "any character" dot symbol.
1692   TRegexp exp("[_a-zA-Z][-\\._a-zA-Z0-9]*");
1693   for (UInt_t i = 0; i < menu->NumberOfItems(); i++)
1694   {
1695     const AliHLTTriggerMenuItem* item = menu->Item(i);
1696     TString str = item->TriggerCondition();
1697     Ssiz_t start = 0;
1698     do
1699     {
1700       Ssiz_t length = 0;
1701       Ssiz_t pos = exp.Index(str, &length, start);
1702       if (pos == kNPOS) break;
1703       start = pos+length;
1704       
1705       // Check if there is a numerical character before the found
1706       // regular expression. If so, then the symbol is not a valid one
1707       // and should be skipped.
1708       if (pos > 0)
1709       {
1710         bool notValid = false;
1711         switch (str[pos-1])
1712         {
1713         case '0': case '1': case '2': case '3': case '4':
1714         case '5': case '6': case '7': case '8': case '9':
1715           notValid = true;
1716           break;
1717         default:
1718           notValid = false;
1719           break;
1720         }
1721         if (notValid) continue;
1722       }
1723       TString s = str(pos, length);
1724       
1725       if (s == "and" or s == "and_eq" or s == "bitand" or s == "bitor" or
1726           s == "compl" or s == "not" or s == "not_eq" or s == "or" or
1727           s == "or_eq" or s == "xor" or s == "xor_eq" or s == "true" or
1728           s == "false"
1729          )
1730       {
1731         // Ignore iso646.h and other keywords.
1732         continue;
1733       }
1734       
1735       // We need to handle the special case where the symbol contains a dot.
1736       // In C++ this is a dereferencing operator. So we need to check if the
1737       // current symbol we are handling starts with the same string as any of
1738       // the existing symbols defined manually in the symbols table.
1739       // If we do find such a case then revert to treating the dot as an operator
1740       // rather than part of the symbol name. i.e. skip adding the automatic symbol.
1741       bool dereferencedSymbol = false;
1742       for (int j = 0; j < initialEntryCount; j++)
1743       {
1744         const AliHLTTriggerMenuSymbol* symbol = dynamic_cast<const AliHLTTriggerMenuSymbol*>( list.UncheckedAt(j) );
1745         if (symbol == NULL) continue;
1746         TString symstr = symbol->Name();
1747         symstr += ".";
1748         if (s.BeginsWith(symstr))
1749         {
1750           dereferencedSymbol = true;
1751           break;
1752         }
1753       }
1754       if (dereferencedSymbol) continue;
1755
1756       // Need to create the symbols first and check if its name is in the list
1757       // before actually adding it to the symbols list.
1758       AliHLTTriggerMenuSymbol newSymbol;
1759       newSymbol.Name(s.Data());
1760       newSymbol.Type("bool");
1761       newSymbol.ObjectClass("AliHLTTriggerDecision");
1762       newSymbol.AssignExpression("this->Result()");
1763       newSymbol.DefaultValue("false");
1764       if (FindSymbol(newSymbol.Name(), list) == -1)
1765       {
1766         try
1767         {
1768           new (list[list.GetEntriesFast()]) AliHLTTriggerMenuSymbol(newSymbol);
1769         }
1770         catch (const std::bad_alloc&)
1771         {
1772           HLTError("Could not allocate more memory for the symbols list when adding a trigger name symbol.");
1773           return -ENOMEM;
1774         }
1775       }
1776     }
1777     while (start < str.Length());
1778   }
1779   
1780   // This last part is necessary to make sure that symbols are replaced in the
1781   // trigger condition and domain merging expressions in a greedy manner.
1782   // I.e. we need to make sure that if one symbol's string representation is
1783   // contained inside another (string subset) that the longer symbol name is
1784   // always first in the symbols list.
1785   // This will work because the symbol table is traversed from first to last
1786   // element and TString::ReplaceAll is used to replace the substrings inside
1787   // the AliHLTGlobalTriggerComponent::GenerateTrigger method.
1788   std::vector<AliHLTTriggerMenuSymbol*> orderedList;
1789   for (Int_t i = 0; i < list.GetEntriesFast(); i++)
1790   {
1791     orderedList.push_back( static_cast<AliHLTTriggerMenuSymbol*>(list.UncheckedAt(i)) );
1792   }
1793   std::sort(orderedList.begin(), orderedList.end(), AliHLTCheckForContainment);
1794   //std::sort(orderedList.begin(), orderedList.end());
1795   // Now swap values around according to the orderedList.
1796   for (Int_t i = 0; i < list.GetEntriesFast(); i++)
1797   {
1798     AliHLTTriggerMenuSymbol* target = static_cast<AliHLTTriggerMenuSymbol*>(list.UncheckedAt(i));
1799     AliHLTTriggerMenuSymbol tmp = *target;
1800     *target = *orderedList[i];
1801     *orderedList[i] = tmp;
1802   }
1803   
1804   return 0;
1805 }
1806
1807
1808 bool AliHLTGlobalTriggerComponent::ExtractedOperator(TString& expr, TString& op)
1809 {
1810   // Extracts the trailing operator from the expression.
1811   
1812   Ssiz_t i = 0;
1813   // First skip the trailing whitespace.
1814   bool whitespace = true;
1815   for (i = expr.Length()-1; i >= 0 and whitespace; i--)
1816   {
1817     switch (expr[i])
1818     {
1819     case ' ': case '\t': case '\r': case '\n':
1820       whitespace = true;
1821       break;
1822     default:
1823       whitespace = false;
1824     }
1825   }
1826   if (i < 0 or whitespace) return false;
1827   
1828   // Now find the first whitespace character before the trailing symbol.
1829   bool nonwhitespace = true;
1830   for (; i >= 0 and nonwhitespace; i--)
1831   {
1832     switch (expr[i])
1833     {
1834     case ' ': case '\t': case '\r': case '\n':
1835       nonwhitespace = false;
1836       break;
1837     default:
1838       nonwhitespace = true;
1839     }
1840   }
1841   if (i < 0 or nonwhitespace) return false;
1842   
1843   // Extract the last symbols and check if it is a valid operator.
1844   TString s = expr;
1845   s.Remove(0, i+2);
1846   if (s == "and" or s == "and_eq" or s == "bitand" or s == "bitor" or
1847       s == "compl" or s == "not" or s == "not_eq" or s == "or" or
1848       s == "or_eq" or s == "xor" or s == "xor_eq" or s == "&&" or
1849       s == "&=" or s == "&" or s == "|" or s == "~" or s == "!" or
1850       s == "!=" or s == "||" or s == "|=" or s == "^" or s == "^=" or
1851       s == "==" or s == "+" or s == "-" or s == "*" or s == "/" or
1852       s == "%" or s == ">" or s == "<" or s == ">=" or s == "<="
1853      )
1854   {
1855     expr.Remove(i+1);
1856     op = s;
1857     return true;
1858   }
1859   
1860   return false;
1861 }
1862
1863
1864 bool AliHLTGlobalTriggerComponent::FillSoftwareTrigger()
1865 {
1866   // Fills the fSoftwareTrigger structure.
1867   
1868   if (fCDH == NULL) return false;
1869   UChar_t l1msg = fCDH->GetL1TriggerMessage();
1870   if ((l1msg & 0x1) == 0x0) return false;  // skip physics events.
1871   // From here on everything must be a software trigger.
1872   if (((l1msg >> 2) & 0xF) == 0xE)
1873   {
1874     fSoftwareTrigger.Name("START_OF_DATA");
1875     fSoftwareTrigger.Description("Generated internal start of data trigger.");
1876   }
1877   else if (((l1msg >> 2) & 0xF) == 0xF)
1878   {
1879     fSoftwareTrigger.Name("END_OF_DATA");
1880     fSoftwareTrigger.Description("Generated internal end of data trigger.");
1881   }
1882   else if (((l1msg >> 6) & 0x1) == 0x1)
1883   {
1884     fSoftwareTrigger.Name("CALIBRATION");
1885     fSoftwareTrigger.Description("Generated internal calibration trigger.");
1886   }
1887   else
1888   {
1889     fSoftwareTrigger.Name("SOFTWARE");
1890     fSoftwareTrigger.Description("Generated internal software trigger.");
1891   }
1892   UInt_t detectors = fCDH->GetSubDetectors();
1893   fSoftwareTrigger.ReadoutList( AliHLTReadoutList(Int_t(detectors)) );
1894   return true;
1895 }
1896
1897
1898 int AliHLTGlobalTriggerComponent::PrintStatistics(const AliHLTGlobalTrigger* pTrigger, AliHLTComponentLogSeverity level, int offset) const
1899 {
1900   // print some statistics
1901   int totalEvents=fTotalEventCounter+offset;
1902   const TArrayL64& counters = pTrigger->GetCounters();
1903   if (pTrigger->CallFailed()) return -EPROTO;
1904   for (int i = 0; i < counters.GetSize(); i++) {
1905     ULong64_t count = counters[i];
1906     float ratio=0;
1907     if (totalEvents>0) ratio=100*(float)count/totalEvents;
1908     HLTLog(level, "Item %d: total events: %d - counted events: %llu (%.1f%%)", i, totalEvents, count, ratio);
1909   }
1910   return 0;
1911 }
1912
1913 int AliHLTGlobalTriggerComponent::AddCTPDecisions(AliHLTGlobalTrigger* pTrigger, const AliHLTCTPData* pCTPData, const AliHLTComponentTriggerData* trigData)
1914 {
1915   // add trigger decisions for the valid CTP classes
1916   if (!pCTPData || !pTrigger) return 0;
1917
1918   AliHLTUInt64_t triggerMask=pCTPData->Mask();
1919   AliHLTUInt64_t bit0=0x1;
1920   if (!fCTPDecisions) {
1921     try
1922     {
1923       fCTPDecisions=new TClonesArray(AliHLTTriggerDecision::Class(), gkNCTPTriggerClasses);
1924     }
1925     catch (const std::bad_alloc&)
1926     {
1927       HLTError("Could not allocate memory for the CTP decisions array.");
1928       return -ENOMEM;
1929     }
1930     if (!fCTPDecisions) return -ENOMEM;
1931
1932     try
1933     {
1934       fCTPDecisions->ExpandCreate(gkNCTPTriggerClasses);
1935     }
1936     catch (const std::bad_alloc&)
1937     {
1938       HLTError("Could not allocate more memory for the CTP decisions array.");
1939       return -ENOMEM;
1940     }
1941     for (int i=0; i<gkNCTPTriggerClasses; i++) {
1942       const char* name=pCTPData->Name(i);
1943       if (triggerMask&(bit0<<i) && name) {
1944         AliHLTTriggerDecision* pDecision=dynamic_cast<AliHLTTriggerDecision*>(fCTPDecisions->At(i));
1945         assert(pDecision);
1946         if (!pDecision) {
1947           delete fCTPDecisions;
1948           fCTPDecisions=NULL;
1949           return -ENOENT;
1950         }
1951         pDecision->Name(name);
1952       }
1953     }
1954   }
1955
1956   for (int i=0; i<gkNCTPTriggerClasses; i++) {
1957     const char* name=pCTPData->Name(i);
1958     if ((triggerMask&(bit0<<i))==0 || name==NULL) continue;
1959     AliHLTTriggerDecision* pDecision=dynamic_cast<AliHLTTriggerDecision*>(fCTPDecisions->At(i));
1960     HLTDebug("updating CTP trigger decision %d %s (%p casted %p)", i, name, fCTPDecisions->At(i), pDecision);
1961     if (!pDecision) return -ENOENT;
1962
1963     bool result=false;
1964     // 13 March 2010 - Optimisation:
1965     // Dont use the EvaluateCTPTriggerClass method, which uses slow TFormula objects.
1966     AliHLTUInt64_t triggers = 0;
1967     if (trigData) triggers = pCTPData->ActiveTriggers(*trigData);
1968     else triggers = pCTPData->Triggers();
1969     result = (triggers&((AliHLTUInt64_t)0x1<<i)) ? true : false;
1970     //if (trigData) result=pCTPData->EvaluateCTPTriggerClass(name, *trigData);
1971     //else result=pCTPData->EvaluateCTPTriggerClass(name);
1972     pDecision->Result(result);
1973     pDecision->TriggerDomain().Clear();
1974     if (trigData) pDecision->TriggerDomain().Add(pCTPData->ReadoutList(*trigData));
1975     else pDecision->TriggerDomain().Add(pCTPData->ReadoutList());
1976
1977     pTrigger->Add(fCTPDecisions->At(i), kAliHLTDataTypeTriggerDecision, kAliHLTVoidDataSpec);
1978     if (pTrigger->CallFailed()) return -EPROTO;
1979   }
1980
1981   return 0;
1982 }