EventBuilder.cpp 26.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include "EventBuilder.h"

#include <fstream>
#include <algorithm>
#include <memory.h>

using namespace std;

std::string EventBuilder::gMotherClass = "EventBuilder";
std::string EventBuilder::gActualClass;  // as no daughter foreseen, used to label different instances

std::string EventBuilder::gConfPath;

EventBuilder::EventBuilder(std::string name, unsigned int nch) :
  nchains(0), nevCount(0), oevCount(0),
  evq(NULL), iqueSize(NULL), isGood(NULL), minEvnum(0), minTstamp(0), minChain(0),
  inqLocker(NULL), inqLocked(NULL), inqIndex(0),
  statKeys(NULL), errState(0), noBuild1(0), noBuild2(0), allPresent(false), obufFull(false)
{
  fConfPath = gConfPath; // done explicitely as this does not (yet?) inherit from NarvalInterface
  fOdirPrefix.clear();
  useEventNumber = false;
  timeout  = 100*tst1second;
  tsumbus  = 100;
  minFold  =   1;
  verbose  = false;
27
  details  = 0;
28 29 30 31 32 33

  fActualClass = gActualClass = name;

  fUseMultiHist = true;
#ifdef EVB_MULTIHIST
  EvbSpecTdiff = NULL;
34
  sTstamps = NULL;
35 36 37 38 39 40 41 42 43 44 45 46
#endif  //EVB_MULTIHIST

  minTstamp = 0;
  numKeys = 0;

  Reset(nch);

  vCorrection.resize(nchains, 0);
  bTstampCorrection = false;
}

EventBuilder::~EventBuilder() {
47 48 49 50 51 52 53
  if(details&2) {
    for(unsigned int nn = 0; nn < nchains; nn++) {
      if(evq[nn].sTstDiff)
        delete evq[nn].sTstDiff;
      evq[nn].sTstDiff = NULL;
    }
  }
54 55 56
  if(sTstamps)
    delete sTstamps;
  sTstamps = NULL;
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  cServer.Finish();
  //PrintStat();
}

bool EventBuilder::Reset(int nch, int wminfold, int wsumbus)
{
  if(nchains > 0) {
    if(evq)      { delete [] evq;      evq      = NULL; }
    if(statKeys) { delete [] statKeys; statKeys = NULL; }
    if(iqueSize) { delete [] iqueSize; iqueSize = NULL; }
    if(isGood)   { delete [] isGood;   isGood   = NULL; }
    if(inqLocker){ delete [] inqLocker;inqLocker= NULL; }
    if(inqLocked){ delete [] inqLocked;inqLocked= NULL; }
    if(inqIndex) { delete [] inqIndex ;inqIndex = NULL; }
  }

  nchains  = nch;
  evq      = new EventQueue[nchains];
  for(unsigned int nn = 0; nn < nchains; nn++) {
    evq[nn].myID = nn;
    evq[nn].myBuilder = fActualClass;
    if(uKeyIn.size() > nn)
      evq[nn].inpKey = uKeyIn[nn];
    else
      evq[nn].inpKey = 0;
82 83 84 85 86 87
    if(details&2) {
      std::ostringstream sfn;
      sfn << "EvB_tstdiff__000-UI__"+gActualClass+"_" << setfill('0') << setw(2) << nn << setfill(' ') << ".bdat";
      evq[nn].sTstDiff = new sAppend<UInt_t>(fOdirPrefix+sfn.str(), 2048);
      evq[nn].tstOld = 0;
    }
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
  }

  inqLocker = new ChainLocker * [nchains];
  inqLocked = new bool [nchains];
  inqIndex  = new UInt_t [nchains];
  for(unsigned int nn = 0; nn < nchains; nn++) {
    inqLocker[nn] = NULL;
    inqLocked[nn] = false;
    inqIndex [nn] = 0;
  }

  statKeys = new UInt_t[nchains+1]; memset(statKeys, 0,     sizeof(UInt_t)*(nchains+1));
  iqueSize = new UInt_t[nchains  ]; memset(iqueSize, 0,     sizeof(UInt_t)*nchains);
  isGood   = new Bool_t[nchains  ]; memset(isGood,   false, sizeof(Bool_t)*nchains);
  timeout  = 100*tst1second;
  tsumbus  = wsumbus;
  minFold  = wminfold;
  errState = 0;
  noBuild1 = 0;
  noBuild2 = 0;

  nevCount = oevCount = 0;
  cServer.Reset();

  return true;
}

void EventBuilder::PrintStat()
{
  LOCK_COUT;
  cout << "Statistics of " << fActualClass << " after "  << nevCount << " events" << endl;
  cout << "   #   counts     good     mult";
  cout << "    [  rest badKey shifts errors maxIsize maxQsize ]" << endl;
  for(UInt_t nn = 0; nn < nchains; nn++) {
    cout << setw(4) << nn                << " "
         << setw(8) << evq[nn].totCount  << " "
         << setw(8) << evq[nn].statChan  << " "
         << setw(8) << statKeys[nn]      << " ";
    cout << "   ["
         << setw(6) << evq[nn].numEvts       << " "
         << setw(6) << evq[nn].badKeys       << " "
         << setw(6) << evq[nn].endCount      << " "
         << setw(6) << evq[nn].errCount      << " "
         << setw(8) << evq[nn].maxInputSize  << " "
         << setw(8) << evq[nn].maxQueueSize  << " ]"
         << endl;
  }
  if(statKeys[nchains]) {
    cout << setw(4) << nchains << " "
         << "         "
         << "         "
         << setw(8) << statKeys[nchains] << " ";
    cout << endl;
  }
  PrintDFAgentKeys("ADF keys at the end\n");
}

// Called after process_block has filled the input queues (or if force==true);
// builds events and put them to the output only up to capacity of obuffer
void EventBuilder::Process(void *obuffer, unsigned int osize, unsigned int *used_osize,
                           unsigned int *error_code, bool force)
{
  *used_osize = 0;
  *error_code = 0;
  oevCount    = 0;
  UInt_t rest = 0;

  // check if all queues are present
  allPresent = true;
  for(UInt_t nn = 0; nn < nchains; nn++) {
    allPresent &= evq[nn].hasData();    // any empty one will turn off the variable
  }

  bool goAhead = allPresent;    // normal condition to proceed
  if(force)                     // proceed even if not all queues have data
    goAhead = true;

  if(!goAhead)
    return;

  if(verbose) {
    for(UInt_t nn = 0; nn < nchains; nn++) {
      //iqueSize[nn] = evq[nn].Size();
      iqueSize[nn] = evq[nn].numEvts;
    }
  }

  unsigned int *obuf    = (unsigned int *)obuffer;
  unsigned int  opos    = 5; // leave space for event key
  unsigned int  osiz    = 0; // used length of output buffers
  unsigned int  osizMax = ((osize/4)*9)/10;   // never fill more than 90%
  obufFull = false;

  while(goAhead) {

    // check event
    if(useEventNumber)
      CheckEvent_Evnum();
    else
      CheckEvent_Tstamp();

    if( numKeys == 0 ) {
      // check if all queues done
      bool allDone = true;
      for(UInt_t nn = 0; nn < nchains; nn++) {
        allDone &= (evq[nn].isDone() || evq[nn].tstFirst==0xFFFFFFFFFFFFFFFFULL);
      }
      if(allDone) {
        LOCK_COUT;
        errState++;
        cout << "   " << fActualClass << "::TERMINATED all input queues " << errState << endl;
        *used_osize = osiz*4;
        *error_code = 111;  // this should put an EOD on the out queue (if connected to a BUILDER)
        return;
      }
      else {
        // this is an inconsistent state
        LOCK_COUT;
        errState++;
        cout << "   " << fActualClass << "::RESET all input queues " << errState << endl;
        for(UInt_t nn = 0; nn < nchains; nn++) {
          evq[nn].Error(nn);
        }
        if(maxErrors && errState >= maxErrors) {
          cout << "\n   " << fActualClass << "::INCONSISTENT since " << errState << " turns  ==> giving up" << endl;
          *error_code = 112;
          return;
        }
        return;
      }
    }
    errState = 0;

    // Remove valid event-fragments from their input queue
    // Send them to the output buffer if multiplicity condition is matched; discard otherwise
    for(UInt_t nn = 0; nn < nchains; nn++) {
      if(!isGood[nn])
        continue;

      UInt_t i4fs = 0;
      if(numKeys < minFold) {
        // remove it from input queue
        i4fs = evq[nn].moveOut(NULL);
      }
      else {
#ifdef EVB_MULTIHIST
        // before moving it out, increment the tstamp-diff spectrum
        if(EvbSpecTdiff && nn != minChain) {
          int tdiff = int(evq[nn].getTstamp() - minTstamp);
          EvbSpecTdiff->Incr(0, tdiff);
        }
#endif  //EVB_MULTIHIST
        // move it to the output buffer
        i4fs  = evq[nn].moveOut(obuf+opos);
        opos += i4fs; 
        evq[nn].statChan++;
      }

      // check the updated input queue
      if(evq[nn].isEmpty()) {
        allPresent = false;
        if(!force)
          goAhead  = false;
      }
      else {
        // check for inversions
        if(useEventNumber) {
          if( (evq[nn].evnFirst > evq[nn].evnLast) ||
              (evq[nn].tstFirst > evq[nn].tstLast) ) {
              evq[nn].Error(nn);
              allPresent = false;
              goAhead    = false;
          }
        }
        else {
          if( (evq[nn].tstFirst > evq[nn].tstLast) ) {
              evq[nn].Error(nn);
              allPresent = false;
              goAhead    = false;
          }
        }
      }
    }

    // if event is good, update statistics and output buffer
    if(numKeys >= minFold) {
      nevCount++;
      statKeys[numKeys]++;

      // Align to 64 bits ? // agreed that alignment is 32 bits
      //if(opos%2) {
      //  obuf[opos] = 0;
      //  opos++;
      //}

      obuf[0] = opos*4;
      obuf[1] = uKeyOut;
      obuf[2] = useEventNumber ? minEvnum : nevCount;
      obuf[3] = (unsigned int)( minTstamp      & 0xFFFFFFFF);
      obuf[4] = (unsigned int)((minTstamp>>32) & 0xFFFFFFFF);

      osiz += opos;   // total size used so far
      obuf += opos;   // advance pointer to output buffer

      oevCount++;
      cServer.Exec(minTstamp);
    }
    if(osiz > osizMax) {
      obufFull = true;
      break;
    }
    opos = 5;         // where to start writing next event, relative to obuf
  }

  *used_osize = osiz*4;
  *error_code = 0;

  LOCK_COUT;
  cServer.Prompt(-1, oevCount, *used_osize, !verbose);
  const int chainsPerLine = 6;
  if(verbose) {
    if(nchains > chainsPerLine) cout << endl << " ";
    cout << "  {";
    for(UInt_t nn = 0; nn < nchains; nn++) {
      cout << " " << setw(5) << iqueSize[nn];
    }
    cout << " |";
    if(nchains > chainsPerLine) cout << endl << "   |";
    for(UInt_t nn = 0; nn < nchains; nn++) {
      cout << " " << setw(5) << evq[nn].numEvts;
    }
    cout << " }";
    if(obufFull)
      cout << " **";
    cout << endl;
  }

  if(oevCount > 0)
    noBuild1 = noBuild2 = 0;

  if(maxErrors && ++noBuild1 >= maxErrors) {
    // something is wrong to have no outuput since so long time ==> try to reset
    if(++noBuild2 >= maxErrors) {
      cout << "\n   " << fActualClass << "::INCONSISTENT since (" << noBuild2 << " " << noBuild1 << ") turns  ==> giving up" << endl;
      *error_code = 113;
      return;
    }
    cout << "   " << fActualClass << "::RESET all input queues " << noBuild2 << "  " << noBuild1 << endl;
    for(UInt_t nn = 0; nn < nchains; nn++) {
      evq[nn].Error(nn);
    }
    noBuild1 = 0;
  }

  return;
}

// Called as a PRODUCER ==> has to take care of its input queues
// As a provisional solution, after trying to read events from all
// inputs it calls the builder implemented as a filter
void EventBuilder::process_block( void *obuffer, unsigned int osize,
                                  unsigned int *used_osize,
                                  unsigned int *error_code)
{
  *used_osize = 0;
  *error_code = 0;

  for(UInt_t iq = 0; iq < nchains; iq++) {
    int who = 100*nchains+iq;      // index to be adjusted
    UInt_t iqs = 0;
    if(!inqLocked[iq]) {
      if(!inqLocker[iq]->Lock(who))
        continue;
      inqLocked[iq] = true;
    }
    iqs = inqLocker[iq]->GetDataSize(who);
    if(iqs == 0) {
      inqLocked[iq] = false;
      inqLocker[iq]->Unlock(who);
      continue;
    }
    if(iqs > inqIndex[iq]) { // can take data
      UInt_t isize = iqs - inqIndex[iq];
      char * ibuffer = inqLocker[iq]->GetDataPtr(who);
      UInt_t rest   = evq[iq].addData((UInt_t *)(ibuffer+inqIndex[iq]), isize/4, vCorrection[iq]);
      UInt_t used   = isize-4*rest;
      inqIndex[iq] += used;
      if(inqIndex[iq] == iqs) {
        inqLocker[iq]->ResetSize(who);
        inqLocked[iq] = false;
        inqIndex[iq] = 0;
        inqLocker[iq]->Unlock(who);
      }
    }
  }
  // check if it makes sense to call the real builder
  for(UInt_t iq = 0; iq < nchains; iq++) {
    if(evq[iq].numEvts == 0)
      return;
  }

  // now call the "standard" event builder
  Process(obuffer, osize, used_osize, error_code);
  return;
}

void EventBuilder::CheckEvent_Evnum()
{
  numKeys   = 0;   // number of fragments
  minEvnum  = 0xFFFFFFFF;
  minTstamp = 0xFFFFFFFFFFFFFFFFULL;
  minChain  = 0xFFFFFFFF;
  for(UInt_t nn = 0; nn < nchains; nn++) {
    if(evq[nn].hasData()) {
      minEvnum = min(minEvnum, evq[nn].evnFirst);
    }
  }
  if(minEvnum == 0xFFFFFFFF)  // ?? 
    return;

  // check how many are equal to minEvnum
  for(UInt_t nn = 0; nn < nchains; nn++) {
    isGood[nn] = false;   // preset to no action
    if(evq[nn].isEmpty())
      continue;   // empty
    if(evq[nn].evnFirst != minEvnum)
      continue;   // not in this event
    // valid if it has the right key
    // preset to move this frame to the output buffer
    if(evq[nn].tstFirst < minTstamp) {
      minTstamp = evq[nn].tstFirst;
      minChain  = nn;
    }
    evq[nn].totCount++;
    isGood[nn] = true;
    numKeys++;
  }
  minTstamp = minTstamp;
}

void EventBuilder::CheckEvent_Tstamp()
{
  numKeys   = 0;   // number of fragments
  minEvnum  = 0xFFFFFFFF;
  minTstamp = 0xFFFFFFFFFFFFFFFFULL;
  minChain  = 0xFFFFFFFF;
  for(UInt_t nn = 0; nn < nchains; nn++) {
    if(evq[nn].hasData() && evq[nn].tstFirst < minTstamp) {
      minTstamp = evq[nn].tstFirst;
      minChain  = nn;
    }
  }
  if(minTstamp == 0xFFFFFFFFFFFFFFFFULL)   // no data or all queues have EOD
    return;

443 444 445 446 447 448 449 450 451
  if(sTstamps) {
    for(UInt_t nn = 0; nn < nchains; nn++) {
      UInt_t dt = evq[nn].hasData() ? UInt_t(evq[nn].tstFirst-minTstamp) : 0;
      sTstamps->add(dt);
    }
    sTstamps->add(UInt_t(minTstamp&0xFFFFFFFF));
    sTstamps->add(UInt_t((minTstamp>>32)&0xFFFFFFFF));
  }

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
  // check how many are closer than tsumbus to minTstamp
  ULong64_t maxTstamp = minTstamp + tsumbus;  // upper margin of time window
  for(UInt_t nn = 0; nn < nchains; nn++) {
    isGood[nn] = false;   // preset to no action
    if(evq[nn].isEmpty())
      continue;   // empty
    if(evq[nn].tstFirst > maxTstamp)
      continue;   // out of time window
    // ok, preset to move this frame to the output buffer
    minEvnum = min(minEvnum, evq[nn].evnFirst);
    evq[nn].totCount++;
    isGood[nn] = true;
    numKeys++;
  }
}

//  gActualClass used to identify the setup file of the specific builder
void EventBuilder::process_config ( const Char_t *full_path, UInt_t *error_code )
{
  *error_code = 0;

  cout << gMotherClass + "::process_config() called with configuration file = " << full_path << endl;

  int rv = getKeyFromFile(full_path, "ActualClass", gActualClass);
  if(rv == 2)
    *error_code = 102; // Fatal error because the configuration file MUST be present

  gConfPath = string( full_path );
  size_t ll = gConfPath.find_last_of("/");
  if(ll != string::npos)
    gConfPath = gConfPath.substr(0, ll);
  forceTailSlash(gConfPath);

  *error_code = 0;
}

void EventBuilder::process_initialise (UInt_t *error_code)
{
  *error_code = 0;

  GetParameters(error_code);
  if(*error_code)
    return;

  // some tests on the I/O keys
  if(sKeyIn.size() < 1) {
    cout << "You should define at least one input key for " << gActualClass << endl;
    *error_code = 160;
    return;
  }
  if(sKeyIn.size() < nchains) {
    string kkk = sKeyIn[sKeyIn.size()-1];
    for(size_t nn = sKeyIn.size(); nn < nchains; nn++)
      sKeyIn.push_back(kkk);
  }
  for(size_t nn = 0; nn < sKeyIn.size(); nn++) {
    if(sKeyIn[nn].size() < 1) {
      cout << "Input key " << nn << " in " << gActualClass << " in empty" << endl;
      *error_code = 161;
      return;
    }
  }
  if(sKeyOut.size() < 1) {
    cout << "You should define the output key for " << gActualClass << endl;
    *error_code = 162;
    return;
  }

  bool ok = InitBuilder();
  if(!ok)
    *error_code = 60;
}

bool EventBuilder::InitBuilder()
{
  PrintDFAgentKeys("ADF keys at the beginning\n");

  if(!InitKeys(nchains))
    return false;

  Reset(nchains, minFold, (int)tsumbus);

  if(useEventNumber)
    cout << "\n ==> " << gActualClass << " uses EventNumber" << endl;
  else
    cout << "\n ==> " << gActualClass << " uses TimeStamp : time interval is " << tsumbus << " samples" << endl;

  cout << " ==> Minimum fold is " << minFold << endl;

  UInt_t notcorr = (UInt_t)count(vCorrection.begin(), vCorrection.end(), 0);
  bTstampCorrection = notcorr < nchains;
  if(bTstampCorrection) {
    cout << " ==> Timestamp of " << nchains - notcorr << " chains will be adjusted" << endl;
  }

#ifdef EVB_MULTIHIST
  if(fUseMultiHist) {
    hGroup.remove();
    EvbSpecTdiff = new MultiHist<unsigned int>(1, 2000);
    EvbSpecTdiff->setFileName(fOdirPrefix+"Evb?"+gActualClass+".spec");
    EvbSpecTdiff->setComment("timestamp differences");
    hGroup.add(EvbSpecTdiff);
554
    if(details&1) {
555 556 557 558
      std::ostringstream sfn;
      sfn << "Evb__000-" << nchains+2 << "-UI__";
      sTstamps = new sAppend<UInt_t>(fOdirPrefix+sfn.str()+gActualClass+".bdat", 1000*(nchains+2) );
    }
559 560 561 562 563 564 565 566 567 568 569 570 571
  }
#endif  //EVB_MULTIHIST

  cServer.SetCommandFile(GetConfPath() + gActualClass + ".live");
#ifdef EVB_MULTIHIST
  cServer.SetHistGroup(&hGroup);
#endif  //EVB_MULTIHIST

  cServer.Start(gActualClass);

  return true;
}

572 573 574 575 576 577 578 579
void EventBuilder::GetParameters()
{
  printInfo("\nKEYWORDS ACCEPTED BY EventBuilder");

  UInt_t errcode = 0xFFFFFFFF;
  GetParameters(&errcode);
}

580 581
void EventBuilder::GetParameters(UInt_t *error_code)
{
582
  bool doList = *error_code == 0xFFFFFFFF;
583 584
  *error_code = 0;

585
  string configFileName = GetConfPath() + gMotherClass + ".conf";
586
  ifstream configfile( configFileName.c_str() );
587 588 589 590 591 592 593 594

  if(!doList) {
    if(!configfile.good()) {
      cout << endl << "Error opening " << configFileName << endl;
      *error_code = 102;
      return;
    }
    cout << endl << gMotherClass + "::GetParameters() reading from --> " << configFileName << endl;
595 596
  }

597
  string kcmd, line, keyw, data, value;
598
  bool ok = true;
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
  bool found = false;
  while(doList || getline(configfile, line)) {

    if(!doList) {
      if(!stringSplit(line, " \t", keyw, data))
        continue;       // empty or comment lines
      cout << line;
      ok     = false;
      found = false;
    }

    kcmd = "ActualClass";
    if(doList)
      printInfo(kcmd, "%s", "name of daughter class");
    else if( !found && stringEq(kcmd, keyw) ) {
      found = true;
615 616 617 618
      ok = data.size() > 0;
      gActualClass = data;
      //fActualClass = gActualClass = data;
    }
619 620 621 622 623 624

    kcmd = "SaveDataDir";
    if(doList)
      printInfo(kcmd, "%s", "where to write data and spectra");
    else if( !found && stringEq(kcmd, keyw) ) {
      found = true;
625 626 627 628
      ok = data.size() > 0;
      fOdirPrefix = data;
      forceTailSlash(fOdirPrefix);
    }
629 630 631 632 633 634

    kcmd = "BuilderType";
    if(doList)
      printInfo(kcmd, "%s", "builder type  (TimeStamp | EventNumber)");
    else if( !found && stringEq(kcmd, keyw) ) {
      found = true;
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
      stringSplit(data, " \t", keyw, value);
      if( stringEq(keyw, "TimeStamp") ) {
        useEventNumber = false;
        if(value.size() > 0) {
          int nn = atoi(value.c_str());
          if(nn > 0)
            tsumbus = nn;
        }
        ok = true;
      }
      else if( stringEq(keyw, "EventNumber") ) {
        useEventNumber = true;
        ok = true;
      }
      else {
        ok = false;
      }
    }
653 654 655 656 657 658

    kcmd = "KeyIn";
    if(doList)
      printInfo(kcmd, "%s", "symbolic_name (e.g. data:psa)");
    else if( !found && stringEq(kcmd, keyw) ) {
      found = true;
659 660 661
      ok = (data.length() > 1);
      sKeyIn.push_back(data);
    }
662 663 664 665 666 667

    kcmd = "KeyOut";
    if(doList)
      printInfo(kcmd, "%s", "symbolic_name (e.g. event:data:psa)");
    else if( !found && stringEq(kcmd, keyw) ) {
      found = true;
668 669 670
      ok = (data.length() > 1);
      sKeyOut = data;
    }
671 672 673 674 675 676

    kcmd = "MinFold";
    if(doList)
      printInfo(kcmd, "%d", "minimum number of detectors for valid events");
    else if( !found && stringEq(kcmd, keyw) ) {
      found = true;
677 678
      ok = 1 == sscanf(data.c_str(), "%d", &minFold);
    }
679 680 681 682 683 684

    kcmd = "TimestampCorrect";
    if(doList)
      printInfo(kcmd, "%d %d", "Queue Value");
    else if( !found && stringEq(kcmd, keyw) ) {
      found = true;
685
      UInt_t ind(nchains);
686
      Int_t val(0);
687 688 689 690 691
      ok = 2 == sscanf(data.c_str(), "%d %d", &ind, &val);
      if(ok && ind < nchains) {
        vCorrection[ind] = val;
      }
    }
692 693 694 695 696 697

    kcmd = "TimestampFixBug24";
    if(doList)
      printInfo(kcmd, "%d", "Queue");
    else if( !found && stringEq(kcmd, keyw) ) {
      found = true;
698 699 700 701 702 703 704
      UInt_t ind(nchains);
       Int_t val(0);
      ok = 1 == sscanf(data.c_str(), "%d", &ind);
      if(ok && ind < nchains) {
        vCorrection[ind] = 0x7FFFFFFF;
      }
    }
705 706 707 708 709 710

    kcmd = "NoMultiHist";
    if(doList)
      printInfo(kcmd, "", "exclude flat binary spectra");
    else if( !found && stringEq(kcmd, keyw) ) {
      found = true;
711 712 713
      fUseMultiHist = false;
      ok = true;
    }
714 715 716 717 718 719 720 721 722 723 724 725 726 727

    kcmd = "Details";
    if(doList)
      printInfo(kcmd, "%d", "b1=tstamp_snapshot for all events  b2=tstamp_diff for all input queues");
    else if( !found && stringEq(kcmd, keyw) ) {
      found = true;
      ok = 1 == sscanf(data.c_str(), "%d", &details);
    }

    kcmd = "Verbose";
    if(doList)
      printInfo(kcmd, "", "verbosity of printouts");
    else if( !found && stringEq(kcmd, keyw) ) {
      found = true;
728 729 730
      verbose = true;
      ok = true;
    }
731 732 733 734 735

    if(doList)
      return;

    if(!found) {
736
      cout << "   --> ignored";
737 738
      cout << endl;
      GetParameters();
739 740 741 742 743
      ok = true;
    }

    if(!ok) {
      cout << "   --> error reading argument(s)" << endl;
744 745 746
      cout << endl;
      GetParameters();
      cout << endl;
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
      *error_code = 103;
      return;
    }
    cout << endl;
  }

}

void EventBuilder::process_start ( UInt_t *error_code )
{
  cout << fActualClass << "::process_start called " << endl;

  cServer.Start(fActualClass);

  *error_code = 0;
}

void EventBuilder::process_stop ( UInt_t *error_code )
{
  cout << fActualClass << "::process_stop called " <<  endl;
  PrintStat();

  cServer.Finish();
  nevCount = 0;

  *error_code = 0;
}

void EventBuilder::process_reset ( UInt_t *error_code )
{
  cout << fActualClass << "::process_reset called " <<  endl;
  *error_code = 0;

  cServer.Reset();
  nevCount = 0;
}

void EventBuilder::process_pause ( UInt_t *error_code )
{
  cout << fActualClass << "::process_pause called " << endl;
  *error_code = 0;
}

void EventBuilder::process_resume ( UInt_t *error_code )
{
  cout << fActualClass << "::process_resume called " << endl;
  *error_code = 0;
}

#ifdef EVB_INHERITS_FROM_NARVAL_PRODUCER

// The ifdef is not needed as we can access the  AgataKeyFactory::theFactory
// also if we don't  inherit from the NarvalProducer.
// It is sufficient to include ADF.conf

#include "AgataKeyFactory.h"

// Mapping of simbolic names to numeric values taken from AgataKeyFactory
// The numeric values could change in case of reconfiguration and therefore
// they should be asked again after that (with all complications of the case).
// This is however not happening in real practice and therefore we ignore it.
bool EventBuilder::InitKeys(unsigned int nv)
{
  // fill undefined sKeys with the last given
  while(sKeyIn.size() < nchains) {
    sKeyIn.push_back(sKeyIn[sKeyIn.size()-1]);
  }

  // sKey --> uKey
  uKeyIn.clear();
  UInt_t mess;
  Bool_t ok = false;
  int nerrors = 0;
  for(unsigned int nn = 0; nn < nv; nn++) {
    mess = 0;
    ok =  ADF::AgataKeyFactory::theFactory()->GetMessage(sKeyIn[nn], mess);
    if(!ok) {
      cout << "EventBuilder::InitKeys could not map \"" << sKeyIn[nn] << "\" to a numeric value" << endl;
      nerrors++;
    }
    uKeyIn.push_back(mess);
  }
  mess = 0;
  ok =  ADF::AgataKeyFactory::theFactory()->GetMessage(sKeyOut, mess);
  if(!ok) {
    cout << "EventBuilder::InitKeys could not map \"" << sKeyOut << "\" to a numeric value" << endl;
    nerrors++;
  }
  uKeyOut = mess;

  return (nerrors == 0);
}

void EventBuilder::PrintDFAgentKeys(std::string str)
{
  return;

  using namespace ADF;

  if(str.size())
    cout << str;

  const std::map<std::string,std::pair<UInt_t,UInt_t> > & messTab = AgataKeyFactory::theFactory()->GetKnownKeys();
  std::map<std::string,std::pair<UInt_t,UInt_t> >::const_iterator im;
  int nn = 0;
  for (im = messTab.begin() ; im !=  messTab.end() ; im++, nn++ ) { 
    cout << setw(3) << nn << "   " << setw(25) << left << im->first << right << " " << hex << "0x" << im->second.first << dec << endl;
  }

  UInt_t m1, m2;
  Bool_t ok = false;
  ok =  AgataKeyFactory::theFactory()->GetMessage("event:data", m1);
  ok =  AgataKeyFactory::theFactory()->GetMessage("event:data", m1, m2);
  ok =  AgataKeyFactory::theFactory()->GetMessage("data", m1, m2);

  im = messTab.find("event:data");
  if(im != messTab.end())
    m1 = im->second.first;

}

#else // #ifdef EVB_INHERITS_FROM_NARVAL_PRODUCER

// Mapping of simbolic names to numeric values taken from ADF.conf and hardwired
bool EventBuilder::InitKeys(unsigned int nv)
{
  // fill undefined sKeys with the last given
  while(sKeyIn.size() < nchains) {
    sKeyIn.push_back(sKeyIn[sKeyIn.size()-1]);
  }

  // sKey --> uKey
  uKeyIn.clear();
  for(unsigned int nn = 0; nn <= nv; nn++) {
    unsigned int theKey = 0;
    std::string strKey = (nn < nv) ? sKeyIn[nn] : sKeyOut;
    
    if(strKey == "agata")               theKey = 0x0A000000;

    if(strKey == "data")                theKey = 0x0A000100;
    if(strKey == "data:crystal")        theKey = 0xFA010101;
    if(strKey == "data:ccrystal")       theKey = 0xFA010111;
    if(strKey == "data:psa")            theKey = 0xFA010102;
    if(strKey == "data:eb")             theKey = 0xFA010103;
    if(strKey == "data:merger")         theKey = 0xFA010104;
    if(strKey == "data:tracked")        theKey = 0xFA010105;
    if(strKey == "data:ranc0")          theKey = 0xFA0201A0;
    if(strKey == "data:ranc1")          theKey = 0xFA0201A1;
    if(strKey == "data:ranc2")          theKey = 0xFA0201A2;

    if(strKey == "meta")                theKey = 0x0A001100;
    if(strKey == "meta:eof")            theKey = 0xFA001100;
    if(strKey == "meta:sync")           theKey = 0xFA011101;
    if(strKey == "meta:vertex")         theKey = 0xFA011102;

    if(strKey == "conf" )               theKey = 0x0A000200;
    if(strKey == "conf:global")         theKey = 0xFA000200;
    if(strKey == "conf:crystal")        theKey = 0xFA010201;
    if(strKey == "conf:psa")            theKey = 0xFA010202;
    if(strKey == "conf:eb")             theKey = 0xFA010203;
    if(strKey == "conf:merger")         theKey = 0xFA010204;
    if(strKey == "conf:tracked")        theKey = 0xFA010205;
    if(strKey == "conf:ranc0")          theKey = 0xFA0202A0;
    if(strKey == "conf:ranc0")          theKey = 0xFA0202A1;
    if(strKey == "conf:ranc0")          theKey = 0xFA0202A2;

    if(strKey == "algo")                theKey = 0xFA000300;
    if(strKey == "algo:crystal")        theKey = 0xFA010301;
    if(strKey == "algo:ccrystal")       theKey = 0xFA010311;
    if(strKey == "algo:psa")            theKey = 0xFA010302;
    if(strKey == "algo:eb")             theKey = 0xFA010303;
    if(strKey == "algo:merger")         theKey = 0xFA010304;
    if(strKey == "algo:tracked")        theKey = 0xFA010305;

    if(strKey == "info")                theKey = 0xFA000400;

    if(strKey == "rmess")               theKey = 0xFA000500;

    if(strKey == "cmess")               theKey = 0xFA000600;

    if(strKey == "event")               theKey = 0xCA000000;
    if(strKey == "event:data")          theKey = 0xCA000100;
    if(strKey == "event:data:crystal")  theKey = 0xCA010101;
    if(strKey == "event:data:psa")      theKey = 0xCA010102;
    if(strKey == "event:data:tracked")  theKey = 0xCA010103;

    if(nn < nv)
      uKeyIn.push_back(theKey);
    else
      uKeyOut = theKey;
  }
  return true;
}

void EventBuilder::PrintDFAgentKeys(std::string)
{
  return;
}

#endif  //  #ifdef EVB_INHERITS_FROM_NARVAL_PRODUCER  # else