ReadMezzAFP.cpp 26.8 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 27 28 29 30
/***************************************************************************
 *   Copyright (C) 2004 by Olivier Stezowski                               *
 *   stezow(AT)ipnl.in2p3.fr                                               *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

/** \file ReadMezzAFP.cpp compiled in libADF.so */

#ifndef ADF_ReadMezzAFP
#include "ReadMezzAFP.h"
#endif

#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
31
#include <cstdio>
32 33 34 35 36 37 38 39 40 41 42 43 44 45

ReadMezzAFP::ReadMezzAFP():
    NarvalProducer(),
    fSourceOfFrames(aMByte,ConfAgent::kRead),
    fPath("./"),
    fBaseForName("AFP_"),
    fCurrentFile(0x0),
    fCurrentFileNumber(0u),
    fMaxSize(kMaxInt_t),
    fConfMode(-1),
    fListOfFile(),
    fEndOfFrame("EndOfFrame"),
    fFrameCrystal_Out(NULL),
    fTrigger("data:crystal"),
46 47
    fdebug(false),
    fBashColor(new BashColor()),
48
    fUseKeyFilter(false),
49
    fLastKeyIsRead(false),
50 51
    fNEvts(0),
    fNIgnoredEvts(0)
52 53 54 55 56 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 82 83 84 85 86 87 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
{	
    if(fdebug) std::cout<<"\E[31;1m"<<"Construct in"<<"\E[m"<<std::endl;

    Log.GetProcessName() = "ReadMezzAFP"; GetFrameIO().SetName("ReadMezzAFP");

    // to be sure unknown frames are written in the ouput
    GetFrameIO().SetModel(ConfAgent::kSafe);
    // to protect writings in the source of frames
    fSourceOfFrames.SetModeIO(ConfAgent::kRead);

    // the input datablock is owned by BasicAFP
    GetFrameIO().Attach(&fSourceOfFrames,0x0);
    fListOfFile.clear();

    if(fdebug) std::cout<<"\E[31;1m"<<"Construct out"<<"\E[m"<<std::endl;
}

ReadMezzAFP::~ReadMezzAFP()
{  
    // in principle not needed ... just in case reset it has not been called by narval
    unsigned int error = 0u; process_reset(&error) ;

    for(int nn = 0; nn < kNSG; nn++ )
        delete [] SegmentTraces[nn];
    for(int nn = 0; nn < kNCC; nn++ )
        delete [] CoreTraces[nn];
} 

bool ReadMezzAFP::NewFile()
{	
    Log.SetProcessMethod("NewFile");
    bool ok = false;

    if ( fConfMode == -1 ) // not properly initialised
        return ok;

    // close the current file
    if ( fCurrentFile )
        ::fclose(fCurrentFile);
    fCurrentFile = 0x0;

    if ( fConfMode == 0 ) {
        // open the first file to be ready to be run
        std::string tmp = fPath;
        if ( tmp.size() > 0 && !(tmp.at(tmp.size()-1) == '/') )
            tmp += '/';

        // try to open the next file
        std::ostringstream filename;
        filename << tmp << fBaseForName
                 << std::setfill('0') << std::setw(4) << fCurrentFileNumber++;

        fCurrentFile = ::fopen(filename.str().data(),"rb");
        if ( fCurrentFile != 0x0 ) {
            Log << "A new input file has just been open "
                << filename.str() << nline;
            fSourceOfFrames.SetFile
                    (fCurrentFile,fMaxSize);
            GetFrameIO().SetStatus
                    (BaseFrameIO::kIdle);
            ok = true;
        }
        else {
            Log << warning << "Cannot open file "
                << filename.str()
                << nline;
            GetFrameIO().SetStatus(BaseFrameIO::kFinished);
        }
    }
    else {
        // try to open the next file
        while ( fCurrentFileNumber < fListOfFile.size() ) {

            fCurrentFile = ::fopen(fListOfFile[fCurrentFileNumber].data(),"rb");
            if ( fCurrentFile == 0x0 ) {
                Log << warning << "File "
                    << fListOfFile[fCurrentFileNumber]
                       << " is not a valid file "
                       << nline ;

                fCurrentFileNumber++;
                continue;
            }
            Log << info << "A new input file has just been open "
                << fListOfFile[fCurrentFileNumber]
                   << nline;
            fSourceOfFrames.SetFile(fCurrentFile,fMaxSize);
            GetFrameIO().SetStatus(BaseFrameIO::kIdle);
            ok = true;
            fCurrentFileNumber++;

            break;
        }
        if ( !ok )
            GetFrameIO().SetStatus(BaseFrameIO::kFinished);
    }
    // send the log collected in this method
    Log << dolog;

    return ok;
}

void ReadMezzAFP::process_config (const char *directory_path, unsigned int *error_code)
{	
    // first init narval and ADF stuff (if required)
    NarvalInterface::process_config(directory_path,error_code);

    if ( (*error_code) == 0u ) { // now init your stuff
    }
}

unsigned int ReadMezzAFP::ProcessBlock(ADF::FrameBlock &out)
{ 
    if(fdebug) std::cout<<"\E[31;1m"<<"ProcessBlock in"<<"\E[m"<<std::endl;

    // attach the input/output buffer to the FrameIO system

    GetFrameIO().Attach(NULL, &out);

    // start the processing

    Frame *frame_out = fFrameCrystal_Out->GetFrame();
    CrystalInterface *cdata = GetDataPointer<CrystalInterface>(frame_out);

    frame_out->Write(); /// dummy test to obtain the frame length

    unsigned int EventLenght = frame_out->GetLength();

    while(out.Reserve(EventLenght,true))
    {
        frame_out->Reset();

        if(!ReadEvent())
        {
186 187 188 189 190 191 192 193 194 195
            if(NewFile()) continue;
            else
            {
                out.SetEoB(true);
                break;
            }
        }

        if(fLastKeyIsRead)
        {
196 197 198 199
            out.SetEoB(true);
            break;
        }

200 201
        fNEvts++;

202 203 204 205
        if( fUseKeyFilter)
        {
            if(evnumber == fNextEvtNbr)
            {
206 207 208 209
                //                fBashColor->SetInfoOut();
                //                std::cout<<"Evt Number = "<<evnumber<<" ; Ref Evt Nbr = "<<fNextEvtNbr<<std::endl;
                //                std::cout<<"TimeStamp = "<<timestamp<<" ; Ref TimeStamp = "<<fNextTS<<std::endl;
                //                fBashColor->ResetColor();
210 211 212 213
                NextKeyToFind();
            }
            else
            {
214 215 216 217
                //                fBashColor->SetWarningOut();
                //                std::cout<<"Evt Number = "<<evnumber<<" ignored, looking for Evt Nbr = "<<fNextEvtNbr<<std::endl;
                //                std::cout<<"TimeStamp = "<<timestamp<<" ignored, looking for TimeStamp = "<<fNextTS<<std::endl;
                //                fBashColor->ResetColor();
218 219 220 221 222
                fNIgnoredEvts++;
                continue;
            }
        }

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
        for(int i = 0; i < kNSG; i++) {
            segMezz = cdata->GetSegment(i);
            segMezz->GetSignal()->Set(SegmentTraces[i], fTraceLengthRaw);
            segMezz->SetE(SegE[i]);
            segMezz->SetStatus(SegStatus[i]);
            segMezz->SetID(SegID[i]);
        }
        for(int i = 0; i < kNCC; i++) {
            coreMezz = cdata->GetCore(i);
            coreMezz->GetSignal()->Set(CoreTraces[i], fTraceLengthRaw);
            coreMezz->SetE(CoreE[i]);
            coreMezz->SetStatus(CoreStatus[i]);
            coreMezz->SetID(CoreID[i]);
            coreMezz->SetT(0);
        }

        // Insert timestamp and event number
        ( ( AgataKey * ) frame_out->GetKey() )->SetTimeStamp( timestamp );
        ( ( AgataKey * ) frame_out->GetKey() )->SetEventNumber( evnumber );
        crystal_status = 0;       // all "normal" events are good

        frame_out->Write();

        fTrigger.Fired(true);
        GetFrameIO().Record();
    }

    GetFrameIO().Detach(NULL, &out);

    if(fdebug) std::cout<<"\E[31;1m"<<"ProcessBlock out"<<"\E[m"<<std::endl;

254
    if ( GetFrameIO().GetStatus() == BaseFrameIO::kFinished || fLastKeyIsRead) return 1u;
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
    else return 0u;
}	

void ReadMezzAFP::process_initialise (unsigned int *error_code)
{
    if(fdebug) std::cout<<"\E[31;1m"<<"process_initialise in"<<"\E[m"<<std::endl;

    std::string tmp, option;

    *error_code = 0u; Log.ClearMessage(); Log.SetProcessMethod("process_initialise");

    // read an input file to get the base filename and the path
    std::string conffile = GetConfPath();
    conffile += "ReadMezzAFP.conf";

    fCurrentFileNumber = 0u;

    std::ifstream filein(conffile.data());
    if ( filein.is_open() == true ) {
        getline(filein,tmp);
        tmp += " ";
        while ( filein.good() && !filein.eof() ) { // read input stream line by line
            if ( tmp[0] == '#' ) {
                getline(filein,tmp);
                tmp += " ";
                continue;
            } // this line is a comment

            std::istringstream decode(tmp);

            if( tmp[0] == 'b' ){ // to emulate a BasicAFP

                std::string pathforfiles, basename;
                unsigned int starting_number;
                decode >> option >> pathforfiles >> basename >> starting_number;

                if ( decode.good() ) {

                    fPath = pathforfiles;
                    fBaseForName = basename;
                    fCurrentFileNumber = starting_number;

                    fConfMode = 0;
                }
            }
            if( tmp[0] == 'l' ) { // the .conf file contains the list of file to be read

                std::string filename;
                decode >> option >> filename;
                if( decode.good() )
                {
                    std::vector<std::string> token = split(filename,'/');

                    fPath = filename;
                    replace(fPath,token[token.size()-1],"");

                    fListOfFile.push_back(filename);
                }

                fConfMode = 1;
            }
            if( tmp[0] == 'r' ) { // the .conf contains a range of files to be read
                unsigned int starting_number, ending_number;
                std::string pathforfiles, basename;
                decode >> option >> pathforfiles >> basename >> starting_number >> ending_number;
                if( decode.good() && starting_number < ending_number ){

                    fPath = pathforfiles;
                    fBaseForName = basename;

                    for( unsigned int number = starting_number; number <= ending_number; number++ ){
                        std::ostringstream osfilename;
                        osfilename  << pathforfiles << basename << std::setfill('0') << std::setw(4) << number;
                        fListOfFile.push_back(osfilename.str());
                    }
                }
                fConfMode = 2;
            }
333 334 335 336 337 338
            if( tmp[0] == 'f' ) { // the .conf contains a key filter
                std::string pathforfilter;
                decode >> option >> pathforfilter;
                if(decode.good()){
                    fKeyFilterFile = 0x0;
                    fKeyFilterFile = ::fopen(pathforfilter.data(),"rb");
339
                    if(fKeyFilterFile == 0x0)
340 341 342 343 344 345 346 347 348 349 350
                    {
                        fBashColor->SetErrorOut();
                        std::cout<<"Key filter file not found, key filter ignored !"<<std::endl;
                        fBashColor->ResetColor();
                    }
                    else
                    {
                        fBashColor->SetInfoOut();
                        std::cout<<"Key filter file : "<<pathforfilter<<" will be used !"<<std::endl;
                        fBashColor->ResetColor();

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
                        ::fseek(fKeyFilterFile, 0, SEEK_END);
                        long size = ::ftell(fKeyFilterFile);

                        ::rewind(fKeyFilterFile);

                        fKeyFilterBuffer = new BufferIO(size);

                        fKeyFilterBuffer->Import(fKeyFilterFile,size);
                        fKeyFilterBuffer->SetOffset();

                        const ADF::FactoryItem item("Agata","data:psa",ADF::Version(4,0));

                        fKeyToLink = (AgataKey*)MainKeyFactory::theMainFactory().New(item);

                        NextKeyToFind();

367 368 369 370
                        fUseKeyFilter = true;
                    }
                }
            }
371 372 373 374 375 376
            getline(filein,tmp);
            tmp += " ";
        }
    }
    else
    {
377
        std::cout<<"\E[31;1m"<<conffile.data()<<" not found !"<<"\E[m"<<std::endl;
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    }
    filein.close();

    switch (fConfMode) {
    case -1:
        *error_code = 1u;
        Log << error << "Not properly initialised" << nline ;
        break;
    case 0:
        Log << info << "Init in BasicAFP mode" << nline ;
        break;
    case 1:
    case 2:
        Log << info << "List of file to be read is " << fListOfFile.size() << nline ;
        break;
    default:
        break;
    }

    // Read the crystal producer conf file

    std::string ConfFilePath = fPath;
400 401 402

    std::vector<std::string> token = split(ConfFilePath,'/');

403 404
    replace(ConfFilePath,(std::string)"/" + token[token.size()-3] + "/","/Conf/");

405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
    ConfFilePath += "CrystalProducer.conf";

    std::ifstream ProdConfFile(ConfFilePath.data());
    if ( ProdConfFile.is_open() == true )
    {
        std::string Line;

        while(ProdConfFile)
        {
            getline(ProdConfFile,Line);

            std::vector<std::string> token = split(Line,' ');

            unsigned int val;
            std::istringstream ( token[token.size()-1] ) >> val;

            if(contains(Line,"TraceLength")) fTraceLengthRaw = (unsigned int) val;
422
            if(contains(Line,"CrystalID")) crystal_id = (unsigned int) val;
423 424 425 426
        }
    }
    else
    {
427
        std::cout<<"\E[31;1m"<<ConfFilePath.data()<<" not found !"<<"\E[m"<<std::endl;
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 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
        return;
    }

    ADF::CrystalInterface::kDefaultLength = fTraceLengthRaw;

    fFrameCrystal_Out = fTrigger.SetOutputFrame("Agata", "data:crystal");

    if(fFrameCrystal_Out) {
        // link named items with local variables.
        GObject *glob = GetDataPointer<CrystalInterface>(fFrameCrystal_Out)->Global();
        glob->LinkItem("CrystalID",     &crystal_id);
        glob->LinkItem("CrystalStatus", &crystal_status);
    }

    GetFrameIO().Register(&fTrigger);

    GetFrameIO().SetModel(ConfAgent::kSafe);

    // initialise the internal structures

    evnumber = 0;
    timestamp = 0;

    for(int atseg = 0; atseg < kNSG; atseg++) {
        SegmentTraces[atseg] = new unsigned short[fTraceLengthRaw];
        memset(SegmentTraces[atseg], 0, sizeof(unsigned short)*fTraceLengthRaw);
        SegE[atseg] = 0;
        SegID[atseg] = 0;
        SegStatus[atseg] = 0;
    }
    for(int atcore = 0; atcore < kNCC; atcore++) {
        CoreTraces[atcore] = new unsigned short[fTraceLengthRaw];
        memset(CoreTraces[atcore], 0, sizeof(unsigned short)*fTraceLengthRaw);
        CoreE[atcore] = 0;
        CoreID[atcore] = 0;
        CoreStatus[atcore] = 0;
    }

    // open the first file
    if ( *error_code == 0u )
        if ( !NewFile() )
            *error_code = 2u;

    Log << dolog;

    if(fdebug) std::cout<<"\E[31;1m"<<"process_initialise out"<<"\E[m"<<std::endl;
}


void ReadMezzAFP::process_reset (unsigned int *error_code)
{
    *error_code = 0u;
    Log.ClearMessage(); Log.SetProcessMethod("process_reset");

    if ( fCurrentFile )
        ::fclose(fCurrentFile);
    fCurrentFileNumber = 0u;
    fConfMode = -1;

    GetFrameIO().Print( Log() );

    Log << dolog;
}

std::vector<std::string> ReadMezzAFP::split(std::string s, char c)
{
    const char* str = s.c_str();

    std::vector<std::string> result;

    do
    {
        const char *begin = str;

        while(*str != c && *str)
            str++;

        result.push_back(std::string(begin,str));
    }
    while (0 != *str++);

    return result;
}

bool ReadMezzAFP::replace(std::string& str, const std::string& from, const std::string& to)
{
    size_t start_pos = str.find(from);
    if(start_pos == std::string::npos) return false;
    str.replace(start_pos,from.length(), to);
    return true;
}


bool ReadMezzAFP::contains(std::string s1, std::string s2)
{
    if(s1.find(s2) != std::string::npos) return true;
    else return false;
}

unsigned int ReadMezzAFP::uncompress_single_trace_AB(unsigned char* compr, unsigned int csize, unsigned short* trace)
{
    unsigned char* compressed = compr;
    unsigned char* c_end = compr + csize;

    // first trace point is verbatim (little endian)
    unsigned char p1 = *compressed++, p2 = *compressed++;
    unsigned short ref = p2<<8 | p1;
    trace[0] = ref^0x2000;

537
    unsigned int midx;
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
    for(midx=1; compressed<c_end && midx<fTraceLengthRaw; ++midx) {
        const unsigned char packed = *compressed++;
        if( (packed & 0x80) == 0 ) {
            // three trace points as two differences
            const unsigned char p2 = *compressed++;
            const unsigned short packed2 = packed<<8 | p2;
            const int diff1 = ((packed2>>10) & 0x1F) - 15;
            const int diff2 = ((packed2>> 5) & 0x1F) - 15;
            const int diff3 = ( packed2      & 0x1F) - 15;
            ref += diff1;
            trace[midx++] = ref^0x2000;
            ref += diff2;
            trace[midx++] = ref^0x2000;
            ref += diff3;
        } else if( (packed & 0xC0) == 0xC0 ) {
            if( compressed>=c_end )
                return false;
            // one trace point as copy
            ref = (packed&0x3F)<<8 | *compressed++;
        } else {
            // one trace point as difference to previous
            const int diff1 = (packed & 0x3F) + MIN_1x6;
            ref += diff1;
        }
        trace[midx] = ref^0x2000;
    }
    return midx;
}

bool ReadMezzAFP::ReadEvent()
{
    int lenChanData;      // MAX number of samples
    int lenChanTotal;     // lenChanHeader + lenChanData
    int lenMezzTotal;     // lenMezzHeader + lenChanTotaln*Chan
    int NChan = 6;

    lenChanData   = fTraceLengthRaw;
    lenChanTotal  = mezzanineChanHeader + lenChanData;
    lenMezzTotal  = mezzanineMezzHeader + lenChanTotal*NChan;

    unsigned short* dbuffer = new unsigned short[lenMezzTotal];

    for(int mezz=0 ; mezz<7 ; mezz++)
    {
        memset(dbuffer, 0, sizeof(unsigned short)*lenMezzTotal);

        fread((void *)dbuffer, sizeof(unsigned short), mezzanineMezzHeader, fCurrentFile);

        unsigned short SlotId = dbuffer[0] & 0x0F ;
        evnumber = (unsigned int) dbuffer[1] | (unsigned int) dbuffer[2] << 16;
        timestamp = (unsigned long long)dbuffer[3] | (unsigned long long)dbuffer[4] << 16 | (unsigned long long)dbuffer[5] << 32;
        unsigned short TraceLen = dbuffer[6];
        unsigned short MezzLen= dbuffer[7];
591
        //        unsigned short DomainId = dbuffer[8] & 0xFF;
592 593 594 595
        unsigned int ActMezzLen = dbuffer[15];

        if(::feof(fCurrentFile))
        {
596 597 598 599
            if(SlotId != 0)
            {
                fBashColor->SetWarningOut();
                std::cout<<"File stoped after reading the header of mezzanine ID : "<<SlotId<<std::endl;
Stezowski Olivier's avatar
Stezowski Olivier committed
600 601
                std::cout<<"Timestamp = "<<timestamp<<std::endl;
                std::cout<<"Event number = "<<evnumber<<std::endl;
602 603
                fBashColor->ResetColor();
            }
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
            delete [] dbuffer;
            return false;
        }

        if(SlotId<1 || SlotId>7)
        {
            std::cout<<"\E[31;1m"<<"Bad Header"<<"\E[m"<<std::endl;
        }

        //        std::cout<<"Mezzanine Header :"<<std::endl;
        //        std::cout<<"SlotId = "<<SlotId<<std::endl;
        //        std::cout<<"EvNumb = "<<evnumber<<std::endl;
        //        std::cout<<"Tstamp = "<<timestamp<<std::endl;
        //        std::cout<<"TraceLen = "<<TraceLen<<std::endl;
        //        std::cout<<"MezzLen = "<<MezzLen<<std::endl;
        //        std::cout<<"DomainId = "<<DomainId<<std::endl;
        //        std::cout<<"ActMezzLen = "<<ActMezzLen<<std::endl<<std::endl;
        //        std::cout<<std::endl;

        if(TraceLen!=fTraceLengthRaw) std::cout<<"\E[31;1m"<<"Number of samples different from configuration file"<<"\E[m"<<std::endl;
        unsigned short nSamp = TraceLen;

        // read and decompress
        int toread = ActMezzLen;

        unsigned short *compBuffer = new unsigned short[toread];
        memset(compBuffer, 0, sizeof(unsigned short)*toread);

        toread -= mezzanineMezzHeader;

        fread(compBuffer, sizeof(unsigned short), toread, fCurrentFile);
        if(::feof(fCurrentFile))
        {
637 638 639 640
            if(SlotId != 7)
            {
                fBashColor->SetWarningOut();
                std::cout<<"File stoped after reading the traces of mezzanine ID : "<<SlotId<<std::endl;
Stezowski Olivier's avatar
Stezowski Olivier committed
641 642
                std::cout<<"Timestamp = "<<timestamp<<std::endl;
                std::cout<<"Event number = "<<evnumber<<std::endl;
643 644
                fBashColor->ResetColor();
            }
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
            delete [] compBuffer;
            delete [] dbuffer;
            return false;
        }

        int numchan = (MezzLen-mezzanineMezzHeader)/(TraceLen+mezzanineChanHeader);

        if(numchan!=NChan)
        {
            std::cout<<"\E[31;1m"<<"Number of channels non equal to 6"<<"\E[m"<<std::endl;
            lenMezzTotal  = mezzanineMezzHeader + lenChanTotal*numchan;
            unsigned short* newdbuffer = new unsigned short[lenMezzTotal];
            unsigned short* oldbuffer = dbuffer;
            memcpy(dbuffer, newdbuffer, sizeof(unsigned short)*lenMezzTotal);
            delete [] oldbuffer;
            dbuffer =  newdbuffer;
        }

        unsigned short *pD = dbuffer + mezzanineMezzHeader;
        unsigned short *pC = compBuffer;

        for(int nn = 0; nn < numchan; nn++) {
            memcpy(pD, pC, sizeof(unsigned short)*mezzanineChanHeader);
            pC += mezzanineChanHeader;
            pD += mezzanineChanHeader;
            unsigned int csize = pD[-1];
            unsigned int ctype = pD[-2] & 0xF;
            int ll = 0;
            if(ctype!=1)
            {
                std::cout<<"WARNING : Compression type unkown !"<<std::endl;
                break;
            }
            else
            {
                ll = uncompress_single_trace_AB((unsigned char *)pC, 2*csize, pD);
            }
            pD[-1] = 0; // remove compression tags
            pD[-2] = 0;
            pC += csize;;
            pD += ll;
        }

        dbuffer += mezzanineMezzHeader;

        for(int i=0 ; i<numchan ; i++)
        {
            int ID = dbuffer[0];

            int ener32 = dbuffer[2];
            ener32 = (ener32 << 16) | dbuffer[1];

            float Ener = float(ener32)/(1<<16);
            int Status = dbuffer[3];
            //            int CompType = dbuffer[6];
            //            int CompTraceLen = dbuffer[7];

            if(SlotId==1 && (ID==0 || ID==1))
            {
704 705 706
                CoreE[ID] = Ener;
                CoreStatus[ID] = Status;
                CoreID[ID] = ID;
707 708 709 710
            }
            else if(SlotId==1) {;}
            else
            {
711 712 713 714 715 716 717 718 719 720 721 722 723
                SegE[(SlotId-2)*6+(5-ID)] = Ener;
                SegStatus[(SlotId-2)*6+(5-ID)] = Status;
                SegID[(SlotId-2)*6+(5-ID)] = (SlotId-2)*6+(5-ID);

                //                fBashColor->SetColor(BashColor::kGreen);
                //                std::cout<<"ID          = "<<ID<<std::endl;
                //                fBashColor->SetColor(BashColor::kYellow);
                //                std::cout<<"5-ID          = "<<5-ID<<std::endl;
                //                fBashColor->SetColor(BashColor::kBlue);
                //                std::cout<<"SlotId          = "<<SlotId<<std::endl;
                //                fBashColor->SetColor(BashColor::kRed);
                //                std::cout<<"(SlotId-2)*6+ID = "<<(SlotId-2)*6+ID<<std::endl;
                //                fBashColor->ResetColor();
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
            }

            //            std::cout<<"trace ID = "<<ID<<std::endl;
            //            std::cout<<"Ener = "<<Ener<<std::endl;
            //            std::cout<<"Status = "<<Status<<std::endl;
            //            std::cout<<"CompType = "<<CompType<<std::endl;
            //            std::cout<<"CompTraceLen = "<<CompTraceLen<<std::endl;

            dbuffer += mezzanineChanHeader;

            unsigned short tmp16;

            for(int j=0 ; j<nSamp ; j++)
            {
                tmp16  = dbuffer[j];
                tmp16 &= 0x3FFF;                        // keep 14 bits
                tmp16 ^= 0x2000;                        // reverse highest ADC bit
                //            tmp16  = 0x3FFF - tmp16;                // change sign

                //                std::cout<<"samp "<<j<<" : "<<tmp16<<std::endl;

                if(SlotId==1 && (ID==0 || ID==1)) CoreTraces[ID][j] = tmp16;
                else if(SlotId==1) break;
747
                else SegmentTraces[(SlotId-2)*6+(5-ID)][j] = tmp16;
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
            }

            dbuffer += nSamp;

            //            std::cout<<std::endl;
        }

        delete [] compBuffer;
        dbuffer -= lenMezzTotal;
    }

    delete [] dbuffer;

    return true;
}
763 764 765

void ReadMezzAFP::NextKeyToFind()
{
766
    if(fKeyFilterBuffer->FreeSize()==0)
767 768 769 770
    {
        fBashColor->SetInfoOut();
        std::cout<<"The last key of the key filter file has been read."<<std::endl;
        fBashColor->ResetColor();
771
        fLastKeyIsRead = true;
772 773 774
        return;
    }

775
    fKeyToLink->Link((*fKeyFilterBuffer),fKeyFilterBuffer->Offset(),fKeyToLink->GetKeyLength());
776

777
    fKeyFilterBuffer->SetOffset(fKeyFilterBuffer->Offset()+fKeyToLink->GetKeyLength());
778

779 780 781 782 783 784 785 786
    fNextTS = fKeyToLink->GetTimeStamp();
    fNextEvtNbr = fKeyToLink->GetEventNumber();

    //        fBashColor->SetColor(BashColor::kRed);
    //        std::cout<<"timestamp = "<<fNextTS<<std::endl;
    //        std::cout<<"EventNumber = "<<fNextEvtNbr<<std::endl;
    //        std::cout<<AgataKeyFactory::theFactory()->GetMessage(fKeyToLink->GetMessage());
    //        fBashColor->ResetColor();
787 788 789 790 791 792 793 794
}

void ReadMezzAFP::PrintStats()
{
    fBashColor->SetInfoOut();

    std::cout<<"********  MezzAFP producer stats:  ********"<<std::endl<<std::endl;

795
    std::cout<<"Number of imput events    : "<<fNEvts<<std::endl;
796
    std::cout<<"Number of filtered events : "<<fNEvts-fNIgnoredEvts<<" ( "<<((float)(fNEvts-fNIgnoredEvts))/((float)fNEvts)*100.<<"\% )"<<std::endl;
797
    std::cout<<"Number of ignored events  : "<<fNIgnoredEvts<<" ( "<<((float)fNIgnoredEvts)/((float)fNEvts)*100.<<"% )"<<std::endl;
798 799 800 801 802 803

    std::cout<<std::endl<<"*******************************************"<<std::endl;

    fBashColor->ResetColor();
    return;
}