************************************************************************
*     
*     Program readraw.F
*     
*     Read downlink data files and unpacks tracker physics 
*     event and calibration data
*
*
*     10-11/9/2005 modified by david fedele to read buffer-data
*     instead raw-data-file
*
*     29/11/2005 modified by david fedele to include crc control
*************************************************************************


      program readraw

      include '../common/commontracker.f'
      include '../common/common_readraw.f'
      include '../common/level0.f'
      include '../common/calib.f'

      include '../tof/common_tof.f'

c------------------------------------------------------------------------
c     
c     local variables
c     
c------------------------------------------------------------------------
      parameter (nfile_max=20)

      character*24 processing_date

c     local variables for input files
      character*60 name_temp
      character*2 aaa
      character*40 base_file(nfile_max) !base file name
      character*40 in_file(nfile_max)   !input data file
      character*40 in_dir               !input data dir
      character*40 out_dir              !output dir
      character*60 out_file_level0      !output rz file (level 0)
      character*60 out_file_calib       !output rz file (calibration)
      character*60 out_file_tof         !output rz file (TOF)
      character*60 out_file_list        !output text file (calib list)
      character*10 input_string(nfile_max)

c     local variables for data unpacking 
      integer ffd               !input file descriptor
      integer runerror          !readevent error flag
      parameter (MAXBUFFLEN=z'172c8')
      integer*4 length_buffer
      integer*1 buffer(MAXBUFFLEN)
      integer curpos            !current position in buffer
c*****************************************************
cccccc 29/11/2005 modified by david fedele
      integer startcrc
      integer stopcrc
      integer*1 crctemp
c*****************************************************

      integer acq_build_info    !runheader field telling which of the front-ends have been included in the acquisition in the run
      integer trk_calib_used    !runheader field telling which kind of calibration has been used for the events of the run      
      integer trk_calib_used_old

      logical DEBUG,ALARMs
      common/DEBUGflag/DEBUG,ALARMS

      logical trk_link(2)

c     flags
      integer last_CPU_pkt      !to check pkt_num inside a downlink is consecutive
      integer last_CPU_pkt_loc  !to check pkt_num inside a downlink is consecutive
      integer last_obt
      logical runheader
      logical runtrailer
      logical found_calib
      logical skip
      logical exitflag
      logical default_calib_written
      logical online_calib_written
      
      integer n_cal_pkt         !count calibration packets

      integer calib_default
      integer calib_lastonline  !store the identification number of the last calibration file

      character*40 calib_default_file !file containing the default calibration info
      data calib_default_file/'default_calib.rz'/

c     local parameters
      parameter (lun_out_file_calib=50) !output file id number
      parameter (lun_out_file_level0=51) !output file id number
      parameter (lun_out_file_tof=52) !output file id number

      parameter (lun_in_file=53) !input file id number


      parameter (max_event_number=50000) !maximum number of events
      
      integer last_trigger(nviews)
      common/trigger_counter/last_trigger
      data last_trigger/12*0./
      

      COMMON/QUEST/IQUEST(100)  !permette di ottenere ntuple funzionanti nonostante
                                ! il messaggio dei 64K di RZOUT...!???
      
c*****************************************************
cccccc 20/9/2005 modified by david fedele
      swcode=202
c*****************************************************
c------------------------------------------------------------------------
c     
c     HBOOK initialization
c     
c------------------------------------------------------------------------

      call HLIMIT(NWPAWC)

     
c------------------------------------------------------------------------
c     
c     reads input informations (through < go_readraw)
c     
c------------------------------------------------------------------------
      call fdate(processing_date)
      write(*,101)
     $     processing_date
 101  format(/
     $     ,'*** *** *** *** *** *** *** *** *** *** *** *** ***',/
     $     ,'*                                                 *',/
     $     ,'* READRAW                                         *',/     
     $     ,'*                                                 *',/
     $     ,'*** *** *** *** *** *** *** *** *** *** *** *** ***',/
     $     ,a24,/
     $     )

      print*,'Number of files to be analysed:'
      read(*,*)nfile
      print*,nfile

 499  format(A40)

c      in_dir='raw-data/'
      print*,'raw-data directory:'
      read(*,499)in_dir
      print*,in_dir


      print*,'List of file identifiers: (DATE_NUM)'
 300  format(A10)
      read(*,300)(input_string(i),i=1,nfile)
      do i=1,nfile
      print*,input_string(i)
      enddo

 401  format('DW_',A10)         !base file name
 4401 format(a,'.dat')          !input file name

      do i=1,nfile
        write(name_temp,401)input_string(i)
        base_file(i)=name_temp(1:LNBLNK(name_temp))
        write(name_temp,4401) base_file(i)(1:LNBLNK(base_file(i)))
        in_file(i)=name_temp(1:LNBLNK(name_temp))
      enddo 
      
      print*,'output directory:'
      read(*,499)out_dir
      print*,out_dir

      print*,'Maximum number of events to be analized:'
      read(*,*)nev_total
      print*,nev_total
      print*,'---------------------------------------------------'

*-------------------------------------------------------------
*     init
*     (some flags to check the data stream)
*------------------------------------------------------------
      last_CPU_pkt = 0
      last_obt = 0
      iev_total=0               !total number of events
      found_calib=.false.
      trk_link(1)=.false.
      trk_link(2)=.false.

c      trk_calib_used=0
      which_calib=0
      calib_default=0
      calib_lastonline=0


c------------------------------------------------------------------------
c     
c     loop on files
c     
c------------------------------------------------------------------------

      do ifile = 1,nfile        !files loop

c------------------------------------------------------------------------
c     init
c------------------------------------------------------------------------
        runheader=.false.
        runtrailer=.false.
        default_calib_written=.false.
        online_calib_written=.false.
        exitflag=.false.
c        nev_file_good = 0
        n_cal_pkt=0
        n_cal_list=0            !calibration file identifier in the calibration list file
        trk_calib_used_old=0        
        n_run_pkt=0
        last_CPU_pkt_loc = 0
        
        nev0=0                  !global event counter
        nev0_good = 0           !total number of good events

        nev_run=0               !event counter relative to the run
        trk_calib_used=0
c        which_calib=0

c------------------------------------------------------------------------
c     open input file
c------------------------------------------------------------------------
        
        print*,' '
        print*,'OPENING PARTICLE FILE:'
        print*,in_file(ifile)
        print*,' '
        
        open(unit=lun_in_file, 
     $       file=in_dir(1:LNBLNK(in_dir))
     $       //in_file(ifile)(1:LNBLNK(in_file(ifile))), 
     $       status='old', 
     $       form='unformatted', 
     $       err=22)
        ffd = FNum(lun_in_file) !reads unix file descriptor
        
c------------------------------------------------------------------------
c     open output file and book ntuple structure
c------------------------------------------------------------------------
 502    format(a,'_level0.rz')
        write(out_file_level0,502)
     $       base_file(ifile)(1:LNBLNK(base_file(ifile)))

 5022   format(a,'_tof.rz')
        write(out_file_tof,5022)
     $       base_file(ifile)(1:LNBLNK(base_file(ifile)))
        
50222   format(a,'_calib.txt')
        write(out_file_list,50222)
     $       base_file(ifile)(1:LNBLNK(base_file(ifile)))
        

        IQUEST(10)=64000          
c     permette di ottenere ntuple funzionanti nonostante
c     il messaggio dei 64K di RZOUT... !???
        
        write(*,103)
     $       out_file_level0,out_file_tof
 103    format(
     $        ' ------------------------------------',/
     $       ,'   Creating rz files:',/
     $       ,'   ',a40,/
     $       ,'   ',a40,/
     $       ,' ------------------------------------',/
     $       )
*     --------------------------
*     create LEVEL0 tracker file
*     --------------------------
        call HROPEN(lun_out_file_level0,
     $       'LEVEL0',
     $       out_dir(1:LNBLNK(out_dir))
     $       //out_file_level0(1:LNBLNK(out_file_level0)),
     $       'QNP',4096,istat)  !opens rz
        if(istat.ne.0) goto 17
        call HCDIR('//LEVEL0',' ')
        call book_level0        
*     --------------------------
*     create TOF tracker file
*     --------------------------                
        call HROPEN(lun_out_file_tof,
     $       'TOF',
     $       out_dir(1:LNBLNK(out_dir))
     $       //out_file_tof(1:LNBLNK(out_file_tof)),
     $       'QNP',4096,istat)  !opens rz
        if(istat.ne.0) goto 17      
        call HCDIR('//TOF',' ')
        call book_tof        
        
*     --------------------------------
*     create tracker calibration list
*     --------------------------------                
        open(UNIT=lun_calib_list
     $       ,FILE=out_dir(1:LNBLNK(out_dir))
     $       //out_file_list(1:LNBLNK(out_file_list))
     $       ,FORM='FORMATTED'
     $       ,STATUS='UNKNOWN'
     $       )

c------------------------------------------------------------------------
c     
c     loop on events
c     
c------------------------------------------------------------------------
 
        do iev = 1,min(nev_total,max_event_number) !event loop

          skip=.false.

          iev_total=iev_total+1
          if(iev_total.eq.nev_total) then
            exitflag=.true.
            goto 9900           !close files and exit if nev_total is reached
          endif

****************************************************************
*     this routine search for a cpu header pointing to a tracker
*     packet, and save the content in a buffer

c*****************************************************
cccccc 11/9/2005 modified by david fedele
c     packet, and save the content in a temp file
*     >>>>>>  packet.dat  <<<<<<
c********************************************************
c------------------------------------------------------------------------
c     look for a cpu packet header
c------------------------------------------------------------------------
          iskipcpu=0
 88       continue
          call findcpuheader(runerror,ffd,pkt_type,pkt_num
     $         ,obt,buffer,length_buffer)
          if(runerror.ne.0) then                  
*           unexpected end of file
             if(iskipcpu.ne.0)then
                print*,'**** READRAW: WARNING ' 
     $               //'- Skipped all packets. '
     $               //'(>>> Reduce the file separately!)'
                print*,''
             endif
            goto 9900           !next file
          endif
          if(iev.eq.1.and.iskipcpu.eq.0)then
             print*,'FIRST CPU PKT: '
     $            ,'   pkt ID ',pkt_type
     $            ,' - pkt N.',pkt_num
     $            ,' - OBT ',obt
             print*,''
          endif

****  CHECK CPU-pkt SEQUENCE
* ------------------------------------------------
*     1) if at the end of the file there are pkts 
*        remained in the memory, these are skipped
* ------------------------------------------------
          if(pkt_num.le.last_CPU_pkt_loc)then
             goto 9900          !next file
          endif
* ------------------------------------------------
*     2) if through the chained downlinks the 
*        packets are not consecutive a warning is set. 
*        In case there is overlapping of pkts 
*        it search the next consecutive packet.
* ------------------------------------------------
          if(pkt_num.le.last_CPU_pkt)then
             if(iskipcpu.eq.0)then
                print*,'  '
                print*,'**** READRAW: WARNING '
     $               //'- Not consecutive CPU packet '
     $               //'(from pkt ',last_CPU_pkt,' to ',pkt_num,')'
             endif
             iskipcpu=iskipcpu+1
             good0=.false.
             if(pkt_type.eq.z'10'.or.pkt_type.eq.z'30')then
                nev0=nev0+1
*****************************************************
cccccc 20/9/2005 modified by david fedele
ccc   call init_level0
                call initlevel0             
c********************************************************
                call initlevel0
                call HCDIR('//LEVEL0',' ')            
                call HFNT(ntp_level0) !ntuple filling
                good=.false.
                call init_tof
                call HCDIR('//TOF',' ')            
                call HFNT(ntp_tof) !ntuple filling             
             endif
             if(pkt_num.eq.last_CPU_pkt.and.obt.ne.last_obt)goto 9900 !next file
             if(pkt_num.lt.last_CPU_pkt)goto 88 !search next cpu header             
          endif
          if(iskipcpu.ne.0)then
             print*,'**** READRAW: WARNING '
     $            //'- ',iskipcpu,' pkts overlap'
             
             print*,''
             print*,'NEXT CPU PKT: '
     $            ,'   pkt ID ',pkt_type
     $            ,' - pkt N.',pkt_num
     $            ,' - OBT ',obt             
             print*,''
          endif
          
          last_CPU_pkt = pkt_num
          last_CPU_pkt_loc = pkt_num
          last_obt = obt

c*****************************************************
cccccc 10/9/2005 modified by david fedele
c          name_temp='bin-aux/packet.dat'
c*****************************************************

          
******************************************************
******************************************************
******************************************************
******************************************************
******************************************************
******************************************************
******************************************************
******************************************************
                    
c------------------------------------------------------------------------
c     read the packet according to packet type as indicated in the header
c------------------------------------------------------------------------
          
          if(pkt_type.eq.z'12'.or.pkt_type.eq.z'13')then
c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**
c     -----------
c     CALIBRATION
c     -----------
c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**
            if(pkt_type.eq.z'12')then
               trk_link(1)=.true.
               print*,''
               print*,'CALIB 1'
     $              ,' - pkt N.',pkt_num
     $              ,' - OBT ',obt
            else
               trk_link(2)=.true.
               print*,'CALIB 2'
     $              ,' - pkt N.',pkt_num
     $              ,' - OBT ',obt
            endif
c****************************************************
cccccc 10/9/2005 modified by david fedele
cccccc      call trkcalibpkt(runerror,name_temp) 
            curpos=1
c*****************************************************
cccccc 29/11/2005 modified by david fedele
            startcrc=0
            stopcrc=0
c***************************************************** 
            call trkcalibpkt(runerror,buffer,length_buffer,curpos,
     $           startcrc,stopcrc,crctemp)
c****************************************************

          elseif(pkt_type.eq.z'10'.or.pkt_type.eq.z'30')then
c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**
c     -----
c     EVENT
c     -----
c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**
            
c*****************************************************
cccccc 10/9/2005 modified by david fedele
c            good0=.true.
c            call init_level0
c            call trkeventpkt(runerror,name_temp) 
            curpos=1
c*****************************************************
cccccc 29/11/2005 modified by david fedele
            startcrc=0
            stopcrc=0
c***************************************************** 
            call trkeventpkt(runerror,buffer,length_buffer,curpos,
     $           startcrc,stopcrc,crctemp)
c*****************************************************
            if(runerror.ne.0)then 
              good0=.false.
              DEBUG = .true.
            endif
            
            call init_tof
            good=.true.
            call triggerunpack(buffer,length_buffer,me)
            if(me.eq.1)good=.false.
            call tofunpack(buffer,length_buffer,me)
            if(me.eq.1)good=.false. 
            
          elseif(pkt_type.eq.z'83')then
c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**
c     -----
c     ALARM
c     -----
c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**

            print*,' '
            print*,'ALARM '
     $           ,' - pkt N.',pkt_num
     $           ,' - OBT ',obt
            call trkalarmpkt(buffer,length_buffer,runerror)
            
         elseif(pkt_type.eq.z'20')then
c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**
c     -----
c     RUNHEADER PACKET
c     -----
c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**
c     this gives the TRK_CALIB_USED field and the ACQ_BUILD_INFO only 
c     inside the runheader packet
            
            runheader=.true.    !a run header has been found 
            runtrailer=.false.    !
            n_run_pkt=n_run_pkt+1 !run counter (relative to downlink)
            nev_run=0           !event counter relative to the run

            print*,'RUN # ',n_run_pkt
     $           ,' - pkt N.',pkt_num
     $           ,' - OBT ',obt

            call runheaderpkt(buffer,length_buffer
     $           ,trk_calib_used,acq_build_info)

         elseif(pkt_type.eq.z'21')then
c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**
c     -----
c     RUNTRAILER PACKET
c     -----
c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**
            runtrailer=.true.   !
            print*,'RUN # ',n_run_pkt
     $           ,' - Calib. used ',trk_calib_used 
     $           ,' - Events ',nev_run
            if(which_calib.eq.0)then
               print*,'RUN # ',n_run_pkt
     $              ,' - Calib. entry ',which_calib
     $              ,' - File **NONE**'
            else
               print*,'RUN # ',n_run_pkt
     $              ,' - Calib. entry ',which_calib
     $              ,' - File ',file_calib
            endif
            print*,'--------'
         endif                  !end pkt type conditions
         
          
******************************************************
******************************************************
******************************************************
******************************************************
******************************************************
******************************************************


c----------------------------------------------------------------
c     
c     elaborate the packet content
c     
c----------------------------------------------------------------

c----------------------------------------------------------------
c     calibration packet: if both 12 and 13 calibration packets
c     (corresponding to the X and Y views (in which order?!))
c     have been found, store them
c----------------------------------------------------------------
          if(
     $         (pkt_type.eq.z'12'.or.pkt_type.eq.z'13').and.
     $         trk_link(1).and.
     $         trk_link(2).and.
     $         .true.) then
c     print*,trk_link(1),trk_link(2),pkt_type
c----------------------------------------------------------------
c     a calibration packet has been found
c     create a new calibration file: DW_DATE_NUM_NN_calib.rz
c     where NN=n_cal_pkt
c     --> book and fill histos
c----------------------------------------------------------------
            found_calib=.true.

            n_cal_pkt = n_cal_pkt + 1
            nnnn=n_cal_pkt 
            call intstr(nnnn,aaa,2)
 503        format(a,'_',a2,'_calib.rz')
            write(out_file_calib,503)
     $           base_file(ifile)(1:LNBLNK(base_file(ifile))),
     $           aaa

            write(*,106)out_file_calib
 106        format(
     $            ' ------------------------------------',/
     $           ,'   Creating CALIBRATION rz file ',/
     $           ,'   ',a40,/
     $           ,' ------------------------------------',/
     $           )
            
            call HROPEN(lun_out_file_calib,
     $           'CALIB',
     $           out_dir(1:LNBLNK(out_dir))
     $           //out_file_calib(1:LNBLNK(out_file_calib)),
     $           'QNP',4096,istat) !opens rz
            if(istat.ne.0) goto 19
            call HCDIR('//CALIB',' ')

            call book_histos
            call fill_histos
            
            call HCDIR('//CALIB',' ')
            do iview=1,nviews
              call HROUT(id_hi_bad+iview,ICYCLE,'T')
              call HROUT(id_hi_ped+iview,ICYCLE,'T')
              call HROUT(id_hi_sig+iview,ICYCLE,'T')
              call HDELET(id_hi_bad+iview)
              call HDELET(id_hi_ped+iview)
              call HDELET(id_hi_sig+iview)
            enddo
            call HREND('CALIB')
            close(lun_out_file_calib)
            do iview=1,nviews
              trk_DSP_ok(iview)=0 !init DSP flag
            enddo
            trk_link(1)=.false.
            trk_link(2)=.false.
            

*           +++++++++++++++++++++++++++++++++++++++++++++++++++++++
*           add a entry to the calibration list file
*           +++++++++++++++++++++++++++++++++++++++++++++++++++++++
            file_calib=out_file_calib(1:LNBLNK(out_file_calib))
            online_calib_written=.false.
c            call add_calib_entry
c            calib_lastonline=n_cal_list !store the identification number of the last calibration file used
*           +++++++++++++++++++++++++++++++++++++++++++++++++++++++

c----------------------------------------------------------------
c     runheader packet: use trk_calib_used and acq_build_info info
c----------------------------------------------------------------
         elseif(
     $           (pkt_type.eq.z'20')
     $           .and..true.) then
                        
            if((trk_calib_used.eq.1) !use previous calibration
     $           .or.(trk_calib_used.eq.2)) then
                              
               if(.not.found_calib) then 
c----------------------------------------------------------------
*     here if the first file is not the first of a data set
c----------------------------------------------------------------
                  print*,'**** READRAW: WARNING ' 
     $                 //'- Missing calibration! (useless run)' 
               else
                  if(.not.online_calib_written) then 
c----------------------------------------------------------------
*     for the first run of a file, create a new entry in the calibration list file, 
*     pointing to the last calibration of the previous file (out_file_calib)
c----------------------------------------------------------------
*                    ++++++++++++++++++++++++++++++++++++++++++++++
                     file_calib=
     $                    out_file_calib(1:LNBLNK(out_file_calib))
                     call add_calib_entry
                     calib_lastonline=n_cal_list
*                    ++++++++++++++++++++++++++++++++++++++++++++++
                     online_calib_written=.true.
                  endif                     
*     for a normal event, use the last online-calibration file
                  which_calib=calib_lastonline !<<<<<<<<<<<<<<<<<
               endif              
c----------------------------------------------------------------
c     if default calibration has been used, write the default 
c     calibration file name in the calibration list file
c----------------------------------------------------------------
            elseif((trk_calib_used.eq.104) !use default calibration
     $             ) then

              if(.not.default_calib_written)then
c              if(calib_default.eq.0)then
c     777                 continue
                default_calib_written=.true.
*               +++++++++++++++++++++++++++++++++++++++++++++++++++
*               add a entry to the calibration list file
*               +++++++++++++++++++++++++++++++++++++++++++++++++++
                file_calib=calib_default_file
                call add_calib_entry
                calib_default=n_cal_list                     
*               +++++++++++++++++++++++++++++++++++++++++++++++++++
              endif
              which_calib=calib_default !<<<<<<<<<<<<<<<<<<<
             
            else
              print*,'**** READRAW: ERROR:' 
     $             //' Wrong calibration identifier for run' 
     $             //' starting at event ',iev,'(runheader packet' 
     $             //' number: ',pkt_num,')'
              which_calib=0
            endif


c----------------------------------------------------------------
c     check if the tracker has been included in this run
c----------------------------------------------------------------
            
            if(iand(acq_build_info,z'00ffff00')
     $           .eq.z'00000000') then
              skip=.true.       !skip the event if no DSP has been included in ACQ
            endif

c----------------------------------------------------------------
c- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
c
c
c     event packet. 
c     z'10'=normal event, 
c     z'30'=full event for special calibration
c
c
c- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
c----------------------------------------------------------------
          elseif(
     $           (pkt_type.eq.z'10'.or.pkt_type.eq.z'30')
     $           .and..true.) then

          
            if((pkt_type.eq.z'10')
     $            .and.(.not.runheader)
     $            .and.nev_run.eq.0) then
               print*,'**** READRAW: WARNING - Missing RunHeader '
            endif

            if(.not.skip) then

            
****  CHECK TRIGGER SEQUENCE  ****
*     ---------------------------------------------------------
               do idsp=1,nviews
                  if(trk_DSP_ok(idsp).eq.1)then
                     if(eventn(idsp).ne.(last_trigger(idsp)+1)
     $                    .and.eventn(idsp).ne.1
     $                    .and.last_trigger(idsp).ne.0)
     $                    write(*,8181)
     $                    idsp,last_trigger(idsp),eventn(idsp)
     $                    ,last_CPU_pkt
                     last_trigger(idsp)=eventn(idsp)
                  endif
               enddo
 8181          format('DSP ',i2,' >> JUMP from trigger ',i6,' to '
     $              ,i6,'    (CPU pkt N.',i8,')')
*     ---------------------------------------------------------
****  CHECK NUMBER OF DSP PACKETS
               dsptot=0
               do iview=1,nviews
                  dsptot=dsptot+trk_DSP_ok(iview)
                  trk_DSP_ok(iview)=0 !init DSP flag
               enddo
               
               if(dsptot.lt.nviews)then
                  good0=.false.
                  print *,'DSP pkt found: '
     $                 ,(trk_DSP_ok(iview),iview=1,12)
     $                 ,' (CPU pkt N.',last_CPU_pkt,')'
               elseif(DEBUG)then
                  print*,' (CPU pkt N.',last_CPU_pkt,')'
                  DEBUG = .false.
               endif
*     ---------------------------------------------------------

            
*     ---------------------------------------------------------
*     for the first event of a file, create a new entry in the 
*     calibration list file, pointing to the last calibration 
*     of the previous file (out_file_calib)
*     ---------------------------------------------------------
               if((nev_run.eq.0).and.
     $              (.not.runheader).and.
     $              which_calib.ne.0) then 
                  call add_calib_entry                  
                  if(which_calib.eq.calib_lastonline)then
                     calib_lastonline=n_cal_list
                     online_calib_written=.true.
                  elseif(which_calib.eq.calib_default)then
                     calib_default=n_cal_list
                     default_calib_written=.true.
                  endif
                  which_calib=n_cal_list 
               endif                     
*     ---------------------------------------------------------



*              event counter relative to the run
               if(pkt_type.eq.z'10')nev_run=nev_run+1
                             
C     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
C     then the nt-uple is filled
C     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

               if(good0.and.which_calib.ne.0) nev0_good = nev0_good +1

c               nev_trk= iev

               nev0=nev0+1
               call HCDIR('//LEVEL0',' ')            
               call HFNT(ntp_level0) !ntuple filling
               
               call HCDIR('//TOF',' ')            
               call HFNT(ntp_tof) !ntuple filling
               
               
            endif
            


            
c----------------------------------------------------------------
c     alarm packet
c----------------------------------------------------------------
         elseif(
     $           pkt_type.eq.z'83'.and.
     $           .true.) then
            
            print*,''
            print*,'@@@@@@@@@@@@ ALARM @@@@@@@@@@@@@@@'
            print*,''


          endif                 !pkt_type condition

 9909     continue


        enddo                   !end loop on events

 9900   continue

        if(.not.runtrailer)then
           print*,'RUN # ',n_run_pkt
     $          ,' - Calib. used ',trk_calib_used
     $          ,' - Events ',nev_run
           if(which_calib.eq.0)then
              print*,'RUN # ',n_run_pkt
     $             ,' - Calib. entry ',which_calib
     $             ,' - File **NONE**'
           else
              print*,'RUN # ',n_run_pkt
     $             ,' - Calib. entry ',which_calib
     $             ,' - File ',file_calib
           endif
        print*,' '
        endif



c------------------------------------------------------------------------
c     
c     closes files and exits
c     
c------------------------------------------------------------------------
      
c*****************************************************
cccccc 10/9/2005 modified by david fedele
c  call system('rm -f '//name_temp)
c*****************************************************
        close(lun_in_file)
        
c        nev0_good = nev0_good + nev_file_good

        print*,' '
        print*,'CLOSING FILES:'
        print*,out_file_level0
        print*,out_file_tof
        print*,' '
        
        call HCDIR('//LEVEL0',' ')
c        call HPRNTU(ntp_level0) !prints ntuple structure
c     deletes all but the last cycles of all key 
c     from the current working RZ directory
        call RZPURG(-1)    
        call HROUT(ntp_level0,ICYCLE,'T')
        call HREND('LEVEL0')
        close(lun_out_file_level0)

        call HCDIR('//TOF',' ')
c        call HPRNTU(ntp_tof)    !prints ntuple structure
c     deletes all but the last cycles of all key 
c     from the current working RZ directory
        call RZPURG(-1)    
        call HROUT(ntp_tof,ICYCLE,'T')
        call HREND('TOF')
        close(lun_out_file_tof)


        close(lun_calib_list)


        write(*,107)
c     $       iev,
c     $       nev_file_good
     $       nev0,
     $       nev0_good
 107    format(
     $        ' ------------------------------------',/
     $       ,' | Number of events ',i8,'        |'/
     $       ,' | Good events      ',i8,'        |'/
     $       ,' ------------------------------------',/
     $       )



        if(exitflag) goto 9990  !nev_total has been reached --> exit
        
           print*,'LAST CPU PKT: '
     $       ,'   pkt ID ',pkt_type
     $       ,' - pkt N.',pkt_num
     $       ,' - OBT ',obt
           

      enddo                     !end loop on files
      
 9990 continue


      goto 9000                 !go to end
c-----------------------------------------
c     level0 file creation error
c-----------------------------------------
 17   continue      
      print*,' '
      print*,'readraw: ERROR CREATING OUTPUT FILE: ',out_file_level0
      print*,istat
      print*,' '
      print*,' '
      goto 9000                 !the end
c-----------------------------------------
c     tof file creation error
c-----------------------------------------
 18   continue      
      print*,' '
      print*,'readraw: ERROR CREATING OUTPUT FILE: ',out_file_tof
      print*,istat
      print*,' '
      print*,' '
      goto 9000                 !the end
c-----------------------------------------
c     calibration file creation error
c-----------------------------------------
 19   continue      
      print*,' '
      print*,'readraw: ERROR CREATING OUTPUT FILE: ',out_file_calib
      print*,istat
      print*,' '
      print*,' '
      goto 9000                 !the end
c-----------------------------------------
c     particle input file opening error     
c-----------------------------------------
 22   continue
      print*,' '
      print*,'readraw: ERROR OPENING PARTICLE FILE: ',in_file(ifile)
      print *,in_dir
      print *,in_dir(1:LNBLNK(in_dir))
     $     //in_file(ifile)(1:LNBLNK(in_file(ifile)))
      print*,' '
      goto 9000                 !the end


c------------------------------------------------------------------------
c     
c     exit
c     
c------------------------------------------------------------------------
 9000 continue


      stop
      end
