************************************************************************
*     
*     Program readraw.F
*     
*     - creates output files data structure with RUNINFO and LEVEL0 ntuples
*     - reads raw data input files (FILENAME.DAT, FILENAME.PEDSIG##, 
*     ##=1..12)
*     - fills ped, sig and bad histograms with online computed (DSP) values
*     - fills RUNINFO and LEVEL0 ntuples
*     
*     needs:
*     - ./go_readraw                        go file
*     - ../data/FILENAME.DAT                input data file
*     - ../data/FILENAME.PEDSIG##, ##=1..12 input pedsig files
*     - ../common/commontracker.f           tracker general common
*     - ../common/runinfo.f                 runinfo ntuple common
*     - ../common/level0.f                  level0 ntuple common
*     - ./readevent.c                       C routine to read input file
*     
*     output:
*     - ../rz/FILENAME.rz                   ntuples out file
*     
*************************************************************************


      program readraw

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

      include '../tof/common_tof.f'


      integer trk_DSP_ok(nviews) !mask of found DSP packets
      common/DSPok/trk_DSP_ok

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
c     character*3 aa(nfile_max)
      character*2 aaa
      character*40 base_file(nfile_max) !base file name
      character*40 base_file_runinfo
      character*40 in_file(nfile_max) !input data file
      character*40 in_dir       !input data dir
      character*40 out_dir      !output dir
c      character*60 out_file     !output rz file
      character*60 out_file_runinfo !output log file
      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*10 input_string(nfile_max)
c     character*8 date 
c     character*3 particle
c     integer file_id(nfile_max)

c     integer file_events(nfile_max)

      character*200 copystring

c     integer this_eventn
c     integer this_calib

c     local variables for data unpacking 
      logical found_cal_pkt     !flag for calibration packets
      integer ffd               !input file descriptor
      integer runerror          !readevent error flag
c     integer ffd_pkt           !pkt file descriptor
c     !(file temporaneo)     
      parameter (MAXBUFFLEN=z'172c8')
      integer*4 CPU_pkt_counter
c     integer pkt_type
      integer*4 length_buffer
      integer trk_calib_used
      integer acq_build_info
      integer*1 buffer(MAXBUFFLEN)

c     integer ndummy
c     data ndummy/1000/

      logical DEBUG,ALARMs
      common/DEBUGflag/DEBUG,ALARMS

      logical trk_link(2)
      logical runheader
      logical skip
      logical exitflag
      logical default_calib_written
      
c     local parameters
      parameter (lun_out_file_runinfo=49) !txt log file id number
      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------------------------------------------------------------------------
c     
c     HBOOK initialization
c     
c------------------------------------------------------------------------

      call HLIMIT(NWPAWC)


c------------------------------------------------------------------------
c     
c     reads input informations (through < go_readraw)
c     
c------------------------------------------------------------------------

      print*,'______________________________________________'

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


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


      in_dir='raw-data/'


 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))
c     print*,base_file(i)
         write(name_temp,4401) base_file(i)(1:LNBLNK(base_file(i)))
         in_file(i)=name_temp(1:LNBLNK(name_temp))
         print*,in_file(i)
c     file_events(i)=0
      enddo 
      
 499  format(A40)
      print*,'output directory:'
      read(*,499)out_dir
      print*,out_dir
c     out_dir='rz/'

c$$$  print*,'output files:'    !../rz/PART_E_##
c$$$  print*,'(name only, without extention)'
c$$$  500  format(A40)
c$$$  read(*,500)out_file
c$$$  print*,out_file

 501  format('DW_',A10,'-',A10,'_RUNINFO.txt')
      base_file_runinfo=name_temp(1:LNBLNK(name_temp))
      write(out_file_runinfo,501) input_string(1),input_string(nfile)
      print*,'RUN INFORMATION:'
      print*,out_file_runinfo


      print*,'Total number of events to be analized:'
      read(*,*)nev_total
      print*,nev_total
      print*,'______________________________________________'




c------------------------------------------------------------------------
c     
c     Opening log-file RUNINFO
c     
c     
c------------------------------------------------------------------------

      call fdate(processing_date)
      open(UNIT=lun_out_file_runinfo
     $     ,FILE=out_dir(1:LNBLNK(out_dir))
     $     //out_file_runinfo(1:LNBLNK(out_file_runinfo))
     $     ,ACCESS='APPEND'
     $     ,FORM='FORMATTED'
     $     ,STATUS='UNKNOWN'
     $     )
      write(lun_out_file_runinfo,101)
     $     processing_date
     $     ,nfile
c     $     ,date
     $     ,(input_string(i),i=1,nfile)
 101  format(/
     $     ,'*** *** *** *** *** *** *** *** *** *** *** *** ***',/
     $     ,'*                                                 *',/
     $     ,'* READRAW                                         *',/     
     $     ,'*                                                 *',/
     $     ,'*** *** *** *** *** *** *** *** *** *** *** *** ***',/
     $     ,a24,/
     $     ,/
     $     ,'Data info',/
     $     ,'...................................................',/
     $     ,'Number of reduced files         ',i6,/
c     $     ,'Date                            ',a6,/
     $     ,'List of file identifiers        ',/
     $     ,A/
     $     )

c------------------------------------------------------------------------
c     
c     read run information
c     
c------------------------------------------------------------------------
c     level0=.true.             !data elaboration level
c     level1=.false.            
c     level2=.false.
c     level3=.false.

c     call read_runinfo         !some information about the run is from prompt


*-------------------------------------------------------------
*     
*     init
*     
*------------------------------------------------------------
*     some flags to check the data stream
      found_cal_pkt=.false.
      n_cal_pkt_last=0
      this_CPU_pkt = 0


      iev_total=0               !total number of events
      nev0_good = 0
      n_cal_pkt=0
      runheader=.false.

      trk_link(1)=.false.
      trk_link(2)=.false.


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

      do ifile = 1,nfile        !files loop

c------------------------------------------------------------------------
c     init
c------------------------------------------------------------------------
         default_calib_written=.false.
         exitflag=.false.
         nev_file_good = 0
         

c------------------------------------------------------------------------
c     open input file
c------------------------------------------------------------------------

         write(lun_out_file_runinfo,104)
     $        ifile
     $        ,in_file(ifile)
 104     format(/
     $        ,/
     $        '+...+...+...+...+...+...+...+...+...+...+...+...+',/
     $        ,'      Processing file    ',i2,/
     $        ,'      ',a40,/
     $        '+...+...+...+...+...+...+...+...+...+...+...+...+'
     $        )
         
         
         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     file_events(ifile)=0   !sigle-file event counter 
c     this_eventn=0
         
c     this_CPU_pkt = 0


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)))
c     print*,'LEVEL0 EVENT DATA:'
c     print*,out_file_level0

 5022    format(a,'_tof.rz')
         write(out_file_tof,5022)
     $        base_file(ifile)(1:LNBLNK(base_file(ifile)))
c     print*,'TOF EVENT DATA:'
c     print*,out_file_tof
         

         IQUEST(10)=64000          
c     permette di ottenere ntuple funzionanti nonostante
c     il messaggio dei 64K di RZOUT... !???
         
         
         write(lun_out_file_runinfo,103)
     $        out_file_level0,out_file_tof
         write(*,103)
     $        out_file_level0,out_file_tof
 103     format(
     $        '*-------------------------------------------------*',/
     $        ,'   Creating rz files',/
     $        ,'   ',a40,/
     $        ,'   ',a40,/
     $        '*-------------------------------------------------*',/
c     $           ,/
c     $           'Processing events from 1 to ',i6,/
c     $           ,/
     $        )
         

*     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
         
c     print*,'DONE'
         print*,' '
         



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        !stop if nev_total is reached
            endif

****************************************************************
*     this routine search for a cpu header pointing to a tracker
*     packet, and save the content in a temp file
*     >>>>>>  packet.dat  <<<<<<

c------------------------------------------------------------------------
c     look for a cpu packet header
c------------------------------------------------------------------------
            call findcpuheader(runerror,ffd,pkt_type,CPU_pkt_counter
     $           ,obt,buffer,length_buffer)
            
            
c     if(runerror.eq.-1) goto 24
            if(runerror.eq.-1) then                  
               print*,' '
               print*,'readraw: ERROR ON READING FILE: ',in_file(ifile)
               print*,'_____________________________________ '
               goto 9900        !next file
            endif
            if(runerror.eq.1) then                  
               print*,' '
               print*,'readraw: FILE: ',in_file(ifile)
               print*,'readraw: END OF FILE AT EVENT ',iev-1
               print*,'_____________________________________ '
               goto 9900        !next file
            endif
            if(CPU_pkt_counter.le.this_CPU_pkt)then
               print*,'  '
               print*,' Non consecutive cpu packet! '
               print*,' From ',this_CPU_pkt,' to ',CPU_pkt_counter
               goto 9900        !next file
            endif
            
            this_CPU_pkt = CPU_pkt_counter
            name_temp='packet.dat'
            
            pkt_num=CPU_pkt_counter
            
******************************************************
******************************************************
******************************************************
******************************************************
******************************************************
******************************************************
******************************************************
******************************************************
            

            
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

               if(pkt_type.eq.z'12')then
                  trk_link(1)=.true.
               else
                  trk_link(2)=.true.
               endif
c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**
c     -----------
c     CALIBRATION
c     -----------
c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**

               call trkcalibpkt(runerror,name_temp)
               
            elseif(pkt_type.eq.z'10'.or.pkt_type.eq.z'30')then
               
               good0=.true.
               call trkeventpkt(runerror,name_temp)
               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.
               
****  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)
     $                    write(*,8181)
     $                    idsp,last_trigger(idsp),eventn(idsp)
                     last_trigger(idsp)=eventn(idsp)
                  endif
               enddo
 8181          format(i2,' >> JUMP from trigger ',i6,' to ',i6)
               
c$$$  c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**
c$$$  c     -----
c$$$  c     EVENT
c$$$  c     -----
c$$$  c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**
            elseif(pkt_type.eq.z'83')then
               
               call trkalarmpkt(buffer,length_buffer,runerror)
               
c$$$  c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**
c$$$  c     -----
c$$$  c     ALARM
c$$$  c     -----
c$$$  c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**

            elseif(pkt_type.eq.z'20')then
               
               call runheaderpkt(buffer,length_buffer
     $              ,trk_calib_used,acq_build_info)
c     this gives the TRK_CALIB_USED field and the ACQ_BUILD_INFO only 
c     inside the runheader packet
c$$$  c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**
c$$$  c     -----
c$$$  c     RUNHEADER PACKET
c$$$  c     -----
c$$$  c--   **--**--**--**--**--**--**--**--**--**--**--**--**--**--**

c$$$  6667          format(z1,' ',z8)
c$$$  write(*,6667) trk_calib_used,acq_build_info

            endif               !end pkt type conditions
            
            
******************************************************
******************************************************
******************************************************
******************************************************
******************************************************
******************************************************


c$$$c----------------------------------------------------------------
c$$$c     
c$$$c     elaborate the packet content
c$$$c     
c$$$c----------------------------------------------------------------
c$$$
c$$$c----------------------------------------------------------------
c$$$c     calibration packet: if both 12 and 13 calibration packets
c$$$c     (corresponding to the X and Y views (in which order?!))
c$$$c     have been found, store them
c$$$c----------------------------------------------------------------
c$$$            if(
c$$$     $           (pkt_type.eq.z'12'.or.pkt_type.eq.z'13').and.
c$$$     $           trk_link(1).and.
c$$$     $           trk_link(2).and.
c$$$     $           .true.) then
c$$$c     print*,trk_link(1),trk_link(2),pkt_type
c$$$c----------------------------------------------------------------
c$$$c     a calibration packet has been found
c$$$c     create a new calibration file: DW_DATE_NUM_NN_calib.rz
c$$$c     where NN=n_cal_pkt
c$$$c     --> book and fill histos
c$$$c----------------------------------------------------------------
c$$$
c$$$               n_cal_pkt = n_cal_pkt + 1
c$$$               nnnn=n_cal_pkt 
c$$$               call intstr(nnnn,aaa,2)
c$$$ 503           format(a,'_',a2,'_calib.rz')
c$$$               write(out_file_calib,503)
c$$$     $              base_file(ifile)(1:LNBLNK(base_file(ifile))),
c$$$     $              aaa
c$$$               
c$$$               write(lun_out_file_runinfo,106)out_file_calib
c$$$               write(*,106)out_file_calib
c$$$ 106           format(
c$$$     $              '*----------------------------------------------*',/
c$$$     $              ,'   Creating CALIBRATION rz file',/
c$$$     $              ,'   ',a40,/
c$$$     $              ,'*---------------------------------------------*'
c$$$     $              )
c$$$               
c$$$               call HROPEN(lun_out_file_calib,
c$$$     $              'RUNINFO',
c$$$     $              out_dir(1:LNBLNK(out_dir))
c$$$     $              //out_file_calib(1:LNBLNK(out_file_calib)),
c$$$     $              'QNP',4096,istat) !opens rz
c$$$               if(istat.ne.0) goto 19
c$$$               call HCDIR('//RUNINFO',' ')
c$$$
c$$$c     print*,out_dir(1:LNBLNK(out_dir))
c$$$c     $              //out_file_calib(1:LNBLNK(out_file_calib))
c$$$               
c$$$               
c$$$               call book_histos
c$$$               call fill_histos
c$$$               
c$$$               call HCDIR('//RUNINFO',' ')
c$$$               do iview=1,nviews
c$$$c     if(trk_DSP_ok(iview).eq.1)then
c$$$                  call HROUT(id_hi_bad+iview,ICYCLE,'T')
c$$$                  call HROUT(id_hi_ped+iview,ICYCLE,'T')
c$$$                  call HROUT(id_hi_sig+iview,ICYCLE,'T')
c$$$                  call HDELET(id_hi_bad+iview)
c$$$                  call HDELET(id_hi_ped+iview)
c$$$                  call HDELET(id_hi_sig+iview)
c$$$c     endif
c$$$               enddo
c$$$               call HREND('RUNINFO')
c$$$               close(lun_out_file_calib)
c$$$               do iview=1,nviews
c$$$                  trk_DSP_ok(iview)=0 !init DSP flag
c$$$               enddo
c$$$               trk_link(1)=.false.
c$$$               trk_link(2)=.false.
c$$$               
c$$$c     print*,'///////////////////////'
c$$$c     stop
c$$$
c$$$               runheader=.false. !QQQQQQQQQ HA SENSO MESSO QUI?!???
c$$$
c$$$
c$$$
c$$$
c$$$c----------------------------------------------------------------
c$$$c     runheader packet: use trk_calib_used and acq_build_info info
c$$$c----------------------------------------------------------------
c$$$            elseif(
c$$$     $              (pkt_type.eq.z'20')
c$$$     $              .and..true.) then
c$$$               
c$$$               runheader=.true. !a run header has been found
c$$$               
c$$$
c$$$               if((trk_calib_used.eq.z'1') !use previous calibration
c$$$     $              .or.(trk_calib_used.eq.z'2')) then
c$$$
c$$$                  if(n_cal_pkt.eq.0) then
c$$$                     print*,'READRAW: WARNING:' 
c$$$     $                    //' Missing calibration for run starting at'
c$$$     $                    //' event ',iev,'runheader packet'
c$$$     $                    //' number: ',CPU_pkt_counter,'Using'
c$$$     $                    //' default one. Readraw should be run on'
c$$$     $                    //' a complete set of data !'
c$$$                     goto 777
c$$$                  endif
c$$$
c$$$                  calib=out_file_calib(1:LNBLNK(out_file_calib))
c$$$
c$$$
c$$$c----------------------------------------------------------------
c$$$c     if default calibration has been used, create a XXX_00_calib.rz
c$$$c     with default calibration
c$$$c----------------------------------------------------------------
c$$$               elseif((trk_calib_used.eq.z'104') !use default calibration
c$$$     $                 .and.(.not.default_calib_written)) then
c$$$
c$$$ 777              continue
c$$$
c$$$                  default_calib_written=.true.
c$$$                  
c$$$ 504              format(a,'_00_calib.rz')
c$$$                  write(out_file_calib,504)
c$$$     $                 base_file(ifile)(1:LNBLNK(base_file(ifile)))
c$$$c     write(out_file_calib,503)out_file(1:LNBLNK(out_file))
c$$$c     print*,'CREATING DEFAULT CALIBRATION FILE:'
c$$$c     print*,out_file_calib
c$$$                  
c$$$                  write(lun_out_file_runinfo,1033)
c$$$     $                 out_file_calib
c$$$                  write(*,1033)
c$$$     $                 out_file_calib
c$$$ 1033             format(
c$$$     $                 '*-------------------------------------------*',/
c$$$     $                 ,'   Creating DEFAULT calibration rz file',/
c$$$     $                 ,'   ',a40,/
c$$$     $                 '*-------------------------------------------*',/
c$$$c     $           ,/
c$$$c     $           'Processing events from 1 to ',i6,/
c$$$c     $           ,/
c$$$     $                 )
c$$$                  
c$$$                  copystring='cp '
c$$$     $                 //out_dir(1:LNBLNK(out_dir))
c$$$     $                 //'default_calib.rz '
c$$$     $                 //out_dir(1:LNBLNK(out_dir))
c$$$     $                 //out_file_calib(1:LNBLNK(out_file_calib))
c$$$c     print*,copystring
c$$$                  call system(copystring)
c$$$
c$$$                  calib=out_file_calib(1:LNBLNK(out_file_calib))
c$$$
c$$$               else
c$$$                  print*,'READRAW: ERROR:' 
c$$$     $                 //' Wrong calibration identifier for run' 
c$$$     $                 //' starting at event ',iev,'(runheader packet' 
c$$$     $                 //' number: ',CPU_pkt_counter,'). Skipping to' 
c$$$     $                 //' next file'
c$$$                  goto 9900     !next file
c$$$               endif
c$$$
c$$$
c$$$
c$$$c----------------------------------------------------------------
c$$$c     check if the tracker has been included in this run
c$$$c----------------------------------------------------------------
c$$$               
c$$$               if(iand(acq_build_info,z'00ffff00')
c$$$     $              .eq.z'00000000') then
c$$$                  skip=.true.   !skip the event if no DSP has been included in ACQ
c$$$               endif
c$$$
c$$$
c$$$
c$$$c----------------------------------------------------------------
c$$$c     event packet. z'10'=compressed, z'30'=full
c$$$c----------------------------------------------------------------
c$$$
c$$$            elseif(
c$$$     $              (pkt_type.eq.z'10'.or.pkt_type.eq.z'30')
c$$$     $              .and..true.) then
c$$$               
c$$$               if((pkt_type.eq.z'10').and.(.not.runheader)) then !compressed event have to be inside a run
c$$$                  print*,'READRAW: ERROR: no runheader for ' 
c$$$     $                 //' event ',iev,'event packet'
c$$$     $                 //' number: ',CPU_pkt_counter
c$$$               endif
c$$$
c$$$               if(.not.skip) then
c$$$
c$$$C     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
c$$$C     then the nt-uple is filled
c$$$C     - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
c$$$
c$$$                  if(good0) nev_file_good = nev_file_good +1
c$$$
c$$$                  nev0 = iev
c$$$                  nev_trk= iev
c$$$
c$$$
c$$$                  
c$$$                  call HCDIR('//LEVEL0',' ')            
c$$$                  call HFNT(ntp_level0) !ntuple filling
c$$$                  
c$$$                  call HCDIR('//TOF',' ')            
c$$$                  call HFNT(ntp_tof) !ntuple filling
c$$$                  
c$$$                  if(mod(iev,100).eq.0)print*,iev
c$$$
c$$$
c$$$                  dsptot=0
c$$$                  do iview=1,nviews
c$$$                     dsptot=dsptot+trk_DSP_ok(iview)
c$$$                     trk_DSP_ok(iview)=0 !init DSP flag
c$$$                  enddo
c$$$                  
c$$$                  if(dsptot.lt.nviews)then
c$$$                     print *,'DSP pkt found: '
c$$$     $                    ,(trk_DSP_ok(iview),iview=1,12)
c$$$                     print *,'---> CPU physics pkt --- ',this_CPU_pkt
c$$$                     print *,''
c$$$                  elseif(DEBUG)then
c$$$                     print *,'---> CPU physics pkt --- ',this_CPU_pkt
c$$$                     print *,''
c$$$                     DEBUG = .false.
c$$$                  endif
c$$$                  
c$$$               endif
c$$$
c$$$
c$$$
c$$$               
c$$$c----------------------------------------------------------------
c$$$c     alarm packet
c$$$c----------------------------------------------------------------
c$$$            elseif(
c$$$     $              pkt_type.eq.z'83'.and.
c$$$     $              .true.) then
c$$$               
c$$$               print*,''
c$$$               print*,'@@@@@@@@@@@@ ALARM @@@@@@@@@@@@@@@'
c$$$               print*,''
c$$$
c$$$
c$$$            endif               !pkt_type condition

 9909       continue
c     close(lun_pkt)

         enddo                  !end loop on events

 9900    continue




c------------------------------------------------------------------------
c     
c     closes files and exits
c     
c------------------------------------------------------------------------
         close(lun_in_file)
         
         nev0_good = nev0_good + nev_file_good
         write(lun_out_file_runinfo,107)
c     $        file_events(ifile),
     $        iev,
     $        nev_file_good
 107     format(
     $        'Number of events                ',i8,/
     $        ,'Good events                     ',i8,/
     $        ,'...................................................',/
     $        )


         print*,' '
         print*,'CLOSING FILES:'
         print*,out_file_level0
         print*,out_file_tof
         print*,' '
         
         call HCDIR('//LEVEL0',' ')
         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',' ')
         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_out_file_runinfo)





         if(exitflag) goto 9990 !nev_total has been reached --> exit
         
      enddo                     !end loop on files

      
 9990 continue
      write(lun_out_file_runinfo,108)
     $     iev_total,nev0_good
 108  format(/
     $     ,'|------------------------------------------------|',/
     $     ,'|  Number of processed events                    |',/
     $     ,'|  Total ',i8,'                                |'/
     $     ,'|  Good  ',i8,'                                |'/
     $     ,'|------------------------------------------------|',/
     $     )


      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
