************************************************************************
*     
*     Program scancalibs.f
*     
*     
*************************************************************************

      program scancalibs

      include '../common/commontracker.f'
      include '../common/common_readraw.f'
c      include '../common/level0.f'
      include '../common/calib.f'
      include '../commonyoda/trk_calib_parameters.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
      character*3 aa(nfile_max)
      character*2 aaa
      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     !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*8 date 
      character*3 particle

      integer file_id(nfile_max),file_events(nfile_max)

      character*200 copystring

      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)     
      integer*4 CPU_pkt_counter
      integer pkt_type

c      integer ndummy
c      data ndummy/1000/

      logical trk_link(2)

      
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_in_file=52) !input file id number

      parameter (lun_pkt=53) !inpunt temp packet file


      parameter (max_event_number=50000) !maximum number of events
           

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

      print*,'______________________________________________'

      print*,'Number of files to be analysed:'
      read(*,*)nfile
      print*,nfile
      print*,'Date YYMMDD:'
 300  format(a6)
      read(*,300)date
      print*,date
      print*,'List of file identifiers:'
 401  format('output_',A6,'_',A3,'.dat') !file name
c 402  format('dt_temp/')        !directory
      read(*,*)(file_id(i),i=1,nfile)
      write(*,*)(file_id(i),i=1,nfile)
c      write(in_dir,402)date
c      in_dir='dt_temp/'
      in_dir='raw-data/'
      do i=1,nfile
         iii = file_id(i)
         call intstr(iii,aa(i),3)
c         write(name_temp,400)date,date,aa(i)
         write(name_temp,401)date,aa(i)
         in_file(i)=name_temp(1:LNBLNK(name_temp))
         print*,in_file(i)
         file_events(i)=0
      enddo 
      
 499  format(A40)
      print*,'output directory:'
      read(*,499)out_dir
      print*,out_dir
c      out_dir='rz/'
      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------------------------------------------------------------------------
      out_file_runinfo='scancalibs.dat'
      print*,'OUTPUT FILE: ',
     $     out_dir(1:LNBLNK(out_dir))
     $     //out_file_runinfo(1:LNBLNK(out_file_runinfo))
      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'
     $     )
*-------------------------------------------------------------
*
*     start loop on data files
*
*
*------------------------------------------------------------
*     some flags to check the data stream
      found_cal_pkt=.false.
      n_cal_pkt=0
      n_cal_pkt_last=0

      nev0_c = 0                !global event counter
      nev0_good = 0
      trk_link(1)=.false.
      trk_link(2)=.false.
                  
      do ifile = 1,nfile        !loop on data files
         
         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
         
         file_events(ifile)=0   !sigle-file event counter 
         nev_file_good = 0
c         good0 = .true.
         this_eventn=0

         this_CPU_pkt = 0
         do iev = 1,min(nev_total,max_event_number) !events loop
****************************************************************
*     this routine search for a cpu header pointing to a tracker
*     packet, and save the content in a temp file
*     >>>>>>  packet.dat  <<<<<<
            call findcpuheader(runerror,ffd,pkt_type,CPU_pkt_counter)
            if(runerror.eq.-1) goto 24
            if(runerror.eq.1) then                  
               print*,' '
               print*,'readraw: FILE: ',in_file(ifile)
               print*,'readraw: END OF FILE AT EVENT ',iev-1
               print*,'_____________________________________ '
c              goto 9900        !end loop on files 
            endif
c            print *,'>>> Previous CPU pkt',this_CPU_pkt
c            print *,'>>> Current  CPU pkt',CPU_pkt_counter
            if(CPU_pkt_counter.le.this_CPU_pkt)then
               print*,'  '
c               print*,' >> The CPU pkt number is not progressive << '
c               print*, ' (I suppose that what follows is rubbish) '
               goto 9900 !next file
            endif
            this_CPU_pkt = CPU_pkt_counter
            name_temp='packet.dat'
            if(pkt_type.eq.z'12'.or.pkt_type.eq.z'13')then
               if(pkt_type.eq.z'12')then
                  trk_link(1)=.true.
                  print*,'Found link 1 >> ',trk_link(1),trk_link(2)
               else
                  trk_link(2)=.true.
                  print*,'Found link 2 >> ',trk_link(1),trk_link(2)
               endif
c--**--**--**--**--**--**--**--**--**--**--**--**--**--**--**
c     -----------
c     CALIBRATION
c     -----------
c--**--**--**--**--**--**--**--**--**--**--**--**--**--**--**

               
c               call trk_calib_pkt(runerror,ffd_pkt)
               call trkcalibpkt(runerror,name_temp)

 222           format(i3,3i6,6i4)
               do iview=1,6
                  write(lun_out_file_runinfo,222)
     $                 DSPnumber(iview),
     $                 ped_l1(iview),ped_l2(iview),ped_l3(iview),
     $                 sig_l1(iview),sig_l2(iview),sig_l3(iview),
     $                 nbad_l1(iview),nbad_l2(iview),nbad_l3(iview)
                  write(*,222)
     $                 DSPnumber(iview),
     $                 ped_l1(iview),ped_l2(iview),ped_l3(iview),
     $                 sig_l1(iview),sig_l2(iview),sig_l3(iview),
     $                 nbad_l1(iview),nbad_l2(iview),nbad_l3(iview)
               enddo

               
 2222          continue
               
            elseif(pkt_type.eq.z'10'.or.pkt_type.eq.z'30')then
c--**--**--**--**--**--**--**--**--**--**--**--**--**--**--**
c     -----
c     EVENT
c     -----
c--**--**--**--**--**--**--**--**--**--**--**--**--**--**--**
c               call trkeventpkt(runerror,name_temp)
 8800          continue
            endif               !end pkt type conditions



            if(
     $           (pkt_type.eq.z'10'.or.pkt_type.eq.z'30').and.
     $           .true.) then
c----------------------------------------------------------------
c     an EVENT was found,
c----------------------------------------------------------------
               
            elseif(
     $              (pkt_type.eq.z'12'.or.pkt_type.eq.z'13').and.
     $              trk_link(1).eqv..true..and.
     $              trk_link(2).eqv..true..and.
     $              .true.) then
               print*,trk_link(1),trk_link(2),pkt_type
c----------------------------------------------------------------
c     a calibration packet was found
c----------------------------------------------------------------
               n_cal_pkt = n_cal_pkt + 1
               nnnn=n_cal_pkt 
               call intstr(nnnn,aaa,2)
*     ***********************************************************
*     ***********************************************************
*     ***********************************************************
*     ***********************************************************
*     write the output
*     ***********************************************************
               write(lun_out_file_runinfo,*)
     $              '----- ',date,file_id(ifile),n_cal_pkt
               write(*,*)
     $              '----- ',date,file_id(ifile),n_cal_pkt

              
               

*     ***********************************************************
*     ***********************************************************
*     ***********************************************************
*     ***********************************************************
*     ***********************************************************
               
               do iview=1,nviews
                  trk_DSP_ok(iview)=0 !init DSP flag
               enddo
               trk_link(1)=.false.
               trk_link(2)=.false.
               




            endif
 9909       continue
         enddo                  !end loop on events
 9900    continue
         close(lun_in_file)


      enddo                     !end loop on data files
      
      close(lun_out_file_runinfo)

 9990 continue
      goto 9000                 !go to end
c-----------------------------------------     
c     output file creation error
c-----------------------------------------
 19   continue      
      print*,' '
      print*,'readraw: ERROR CREATING OUTPUT FILE: ',out_file
      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     event found before calibration packet  
c-----------------------------------------
 20   continue
      print*,' '
      print*,'readraw: EVENT FOUND BEFORE CALIBRATION PACKET: '
      print*,in_file(ifile)
      print*,' '
      goto 9000                !the end
c-----------------------------------------
c     particle input file reading error     
c-----------------------------------------
 23   continue
      print*,' '
      print*,'readraw: END OF FILE: ',in_file(ifile)
      print*,'readraw: FOWND AT EVENT ',iev
      print*,' '
      goto 9000                 !the end
 24   continue
      print*,' '
      print*,'readraw: ERROR READING PARTICLE FILE: ',in_file(ifile)
      print*,'readraw: READ ERROR AT EVENT ',iev
      print*,' '
      goto 9000                 !the end

c------------------------------------------------------------------------
c     
c     closes files and exits
c     
c------------------------------------------------------------------------
 9000 continue
      


      stop
      end



c      include 'readraw_subroutines.f'
c      include 'trkunpack.f'
