MODULE TPCpaw
   USE IOunits
   USE TPCdata
   USE Threshold
   USE Space
   PRIVATE
   
! initialisation
   PUBLIC :: PAW_book,PAWini,PAWend
! Ntuples
   PUBLIC :: NT_book,NF_event,NF_pulsefit
! Histograms
   PUBLIC :: HF_veto,HF_deltaT,HF_seedTrack,HF_amplitude
   PUBLIC :: HF_pulse
! Calibration
   PUBLIC :: PiniCal,calSignal,calRFtime
   
   
   PRIVATE :: NF_event_line,NF_event_wideline,&
              NF_event_track,NF_event_plain
   
   CHARACTER(LEN=8),PRIVATE :: CHTOP="TPCMAIN "
   LOGICAL,PRIVATE,SAVE :: NOEvDisp
   
   INTERFACE NF_event
      MODULE PROCEDURE NF_event_line,NF_event_wideline,&
                       NF_event_track,NF_event_plain
   END INTERFACE

   CONTAINS
   
   SUBROUTINE PAW_book()
! book all histograms & Ntuples (apart from calibaration stuff)
      CHARACTER(LEN=80) :: CHline
      CHARACTER(LEN=8),DIMENSION(1000) :: CHtag
      INTEGER :: I,IT,ntag
       
! Histograms, numbers 1-649 -> calibration data

! Histograms, numbers 9000-9999: pulse shapes
! are booked and filled in the same subroutine

! Ntuples, numbers 960-999
! Ntuples, numbers 950-959 -> analyzEvent
      IF( nPads<513 )THEN
      NOEvDisp = .FALSE.
      CHtag(1) = "RUN"
      CHtag(2) = "EVENT"
      CHtag(3) = "TRACKX0"
      CHtag(4) = "TRACKT0"
      CHtag(5) = "TRACKrad"
      CHtag(6) = "TRACKsig"
      DO I=1,nPads
         WRITE(UNIT=CHline,FMT=*) I
         IT = I+6
         IF( IT <= size(CHtag) )THEN
            CHtag(IT) = "PAD"//adjustl(CHline)
         ELSE
            WRITE(UNIT=IOErr,FMT=*) "WARNING,PAW_book > CHtag too small"
            EXIT
         ENDIF
      ENDDO
      CALL NT_book(999,"Event-display",nPads+6,CHtag)
      ELSE
! ntuple can't have more than 512 rows
      NOEvDisp = .TRUE.
      ENDIF

      CHtag(1) = "EVENT"
      CHtag(2) = "GROUP"
      CHtag(3) = "ASTART"
      CHtag(4) = "AFIT"
      CHtag(5) = "T0START"
      CHtag(6) = "T0FIT"
      CHtag(7) = "CHISQ"
      ntag = 7
      CALL NT_book(998,"Pulse Fit",ntag,CHtag)

! Histograms, numbers 1000 - 1040  
      CALL HBOOK1(1001,"Event VETO",10,-1.5,8.5,0.0)     
      CALL HBOOK1(1002,"Number of seed tracks",10,-3.5,6.5,0.0)     
      CALL HBOOK1(1003,"Amplitude",200,0.0,50.0,0.0)     
      CALL HBOOK1(1004,"Amplitude",200,0.0,400.0,0.0)     
      CALL HBOOK1(1005,"Amplitude normalised",100,0.0,1.0,0.0)     
      CALL HBOOK1(1006,"Amplitude normalised",100,0.0,0.05,0.0)     
      CALL HBOOK1(1007,"Amplitude Row",200,0.0,800.0,0.0)     
      CALL HBOOK1(1008,"Amplitude max Row",200,0.0,400.0,0.0)     
      CALL HBOOK1(1009,"T0-Tmax",101,-200.0,2.0,0.0)     
      
 
   END SUBROUTINE PAW_book
   
   SUBROUTINE NT_book(NTid,CHtit,ntag,CHtag)
      INTEGER,INTENT(IN) :: NTid,ntag
      CHARACTER(LEN=8),DIMENSION(:),INTENT(IN) :: CHtag
      CHARACTER(LEN=*),INTENT(IN) :: CHtit
      INTEGER :: NWBUFF=1000
      
      CALL HBOOKN(NTid,CHtit,ntag,CHTOP,NWBUFF,CHtag)
   END SUBROUTINE NT_book
   
! NTUPLE fill  **********************************************    
   SUBROUTINE NF_pulsefit(Xdata)
      REAL,DIMENSION(:),INTENT(IN) :: Xdata
      
      CALL HFN(998,Xdata)
   END SUBROUTINE NF_pulsefit
  
   SUBROUTINE NF_event_track(myTrack,sigma)
      TYPE(XYTrack_type),INTENT(IN) :: myTrack
      REAL(KIND=spPrec),INTENT(IN) :: sigma
      REAL(KIND=spPrec) :: X0,Phi,invRad
      REAL :: amplitude,time
      INTEGER :: I
      INTEGER,SAVE :: nEvent=0
      REAL,DIMENSION(nPads+5) :: Xdata

      IF( NOEvDisp ) RETURN
      
! only up to 100 event displays
      nEvent = nEvent+1
      IF( nEvent>100 )RETURN
      
      Xdata(1) = RunNumber
      Xdata(2) = EventNumber
      CALL getXYTrack(myTrack,X0,Phi,invRad)
      Xdata(3) = X0
      Xdata(4) = Phi
      Xdata(5) = invRad
      Xdata(6) = sigma
      DO I = 1,nPads
         CALL GetSignal(I,amplitude,time)
         Xdata(I+6) = amplitude
      ENDDO
      
      CALL HFN(999,Xdata)
   END SUBROUTINE NF_event_track
   SUBROUTINE NF_event_wideline(myLine,sigma)
      TYPE(Line_type),INTENT(IN) :: myLine
      REAL(KIND=spPrec),INTENT(IN) :: sigma
      TYPE(XYTrack_type) :: myTrack
      
      myTrack = XYTrack(myLine,0.0)
      CALL NF_event_track(myTrack,sigma)      
   END SUBROUTINE NF_event_wideline
   SUBROUTINE NF_event_line(myLine)
      TYPE(Line_type),INTENT(IN) :: myLine
      TYPE(XYTrack_type) :: myTrack
      
      myTrack = XYTrack(myLine,0.0)
      CALL NF_event_track(myTrack,1000.0_spPrec)      
   END SUBROUTINE NF_event_line
   SUBROUTINE NF_event_plain()
      TYPE(XYTrack_type) :: myTrack
      
      myTrack = XYTrack(Line(1000.0,0.0),0.0)
      CALL NF_event_track(myTrack,0.0_spPrec)      
   END SUBROUTINE NF_event_plain

! HISTOGRAM fill  ********************************************** 
   SUBROUTINE HF_veto(IVETO)
      INTEGER,INTENT(IN) :: IVETO
      
      CALL HF1(1001,REAL(IVETO),1.0)
   END SUBROUTINE HF_veto
   SUBROUTINE HF_seedTrack(IERR)
      INTEGER,INTENT(IN) :: IERR
      
      CALL HF1(1002,REAL(IERR),1.0)
   END SUBROUTINE HF_seedTrack
   SUBROUTINE HF_amplitude(iRowT)
      INTEGER,DIMENSION(:),INTENT(IN) :: iRowT
      INTEGER :: iR,iRow,iG,iGroup,iGmax
      REAL :: amplRow,ampl,T0
      
      DO iR=1,size(iRowT)
         iRow = iRowT(iR)
         CALL GetSignalRow(iRow,amplRow,T0)
         CALL HF1(1007,amplRow,1.0)
         CALL GmaxSignalRow(iRow,iGmax,ampl,T0)
         CALL HF1(1008,ampl,1.0)
! avoid divide by 0
         IF( amplRow == 0.0 ) amplRow = 1.0
         DO iG=1,nGroupsinRow(iRow)
            iGroup = iGroupofRow(iG,iRow)
            CALL GetSignalGroup(iGroup,ampl,T0)
            CALL HF1(1003,ampl,1.0)
            CALL HF1(1004,ampl,1.0)
            CALL HF1(1005,ampl/amplRow,1.0)
            CALL HF1(1006,ampl/amplRow,1.0)
         ENDDO
      ENDDO
   END SUBROUTINE HF_amplitude
  
   SUBROUTINE HF_deltaT(deltaT)
      REAL,INTENT(IN) :: deltaT
      CALL HF1(1009,deltaT,1.0)
   END SUBROUTINE HF_deltaT
      
   SUBROUTINE PiniCal()
! histograms for calbration, numbers 1-649
      CHARACTER(LEN=30) :: CHname
      INTEGER :: I
      REAL :: Xlow,Xhigh
   
      IF( Lcalhist )THEN
         DO I=1,nGroups
            WRITE(UNIT=CHname,FMT=*) "Amplitude group",I
            CALL HBOOK1(I*10+1,CHname,50,0.0,250.0,0.0)
            WRITE(UNIT=CHname,FMT=*) "Pedestal group",I
            CALL HBOOK1(I*10+2,CHname,50,210.0,240.0,0.0)
            WRITE(UNIT=CHname,FMT=*) "Pedestal fit group",I
            CALL HBOOK1(I*10+3,CHname,50,210.0,240.0,0.0)
            IF( nTbin>0 ) THEN
               WRITE(UNIT=CHname,FMT=*) "Rise time group",I
               CALL HBOOK1(I*10+5,CHname,50,0.0,60.0,0.0)
               WRITE(UNIT=CHname,FMT=*) "Fall time group",I
               CALL HBOOK1(I*10+6,CHname,50,0.0,800.0,0.0)
         
               WRITE(UNIT=CHname,FMT=*) "Pulse group",I
               CALL HBPROF(I*10+7,CHname,50,-100.0,400.0,0.0,1000.0,"S") 
            ENDIF        
         ENDDO
      ENDIF
      
      Xlow  = 0.5
      Xhigh = nGroups + Xlow
! bounds of Minuit should be excluded from the mean
      CALL HBPROF(1,"Mean Amplitude",nGroups,Xlow,Xhigh,10.0,1000.0," ")
      CALL HBPROF(2,"Mean Pedestal ",nGroups,Xlow,Xhigh,191.0,249.0," ")
      CALL HBPROF(3,"Mean Pedestal fit",nGroups,Xlow,Xhigh,191.0,249.0," ")
      IF( nTbin>0 ) THEN
         CALL HBPROF(5,"Mean Rise Time",nGroups,Xlow,Xhigh,5.5,19.5," ")
         CALL HBPROF(6,"Mean Fall Time",nGroups,Xlow,Xhigh,201.0,599.0," ")
         CALL HBPROF(7,"Mean Rise Time vs T0",40,0.0,REAL(nTbin),1.0,30.0," ")
         CALL HBPROF(8,"Mean Fall Time vs T0",40,0.0,REAL(nTbin),300.0,450.0," ")
      ENDIF
   END SUBROUTINE PiniCal
   SUBROUTINE HF_pulse(CHtitle,pulse,pmin,pmax,iH)
      REAL,DIMENSION(:),INTENT(IN) :: pulse
      REAL,INTENT(IN) :: pmin,pmax
      CHARACTER(len=*),INTENT(IN) :: CHtitle
      INTEGER,INTENT(OUT) :: iH
      INTEGER :: nBin
      INTEGER :: iHist=9000

      iH = -1
      
      IF( .NOT.Lplot )RETURN
      IF( nTbin==0 )RETURN
! DenseData -> this must be nonsense

! only histogram numbers 9000-9999
      IF( iHist > 9999 )RETURN
      iH = iHist
! limit the histogram size
      nBin = min(size(pulse),400)
      CALL HBOOK1(iHist,CHtitle,nBin,pmin,pmax,0.0)
      CALL HPAK(iHist,pulse)
      iHist = iHist+1
   END SUBROUTINE HF_pulse

   SUBROUTINE calSignal(iGroup,ampl,t0,ped)
      INTEGER,INTENT(IN) :: iGroup
      REAL,INTENT(IN) :: ampl,t0,ped
      INTEGER :: it0,i
      REAL :: pulse

         IF( Lcalhist )CALL HF1(iGroup*10+1,ampl,1.0)
         CALL HFILL(1,REAL(iGroup),ampl,1.0)
         
         IF( Lcalhist )CALL HF1(iGroup*10+2,ped,1.0)
         CALL HFILL(2,REAL(iGroup),ped,1.0)
               
         IF( Lcalhist .AND. nTbin>0 )THEN
! get the t0 in pulse(0)
            it0 = anint(t0) 
            DO i=lbound(ADC,1),ubound(ADC,1)
               IF( ampl > 10.0 )THEN
                  pulse = (ped-ADC(i,iGroup)) / ampl
               ELSE
                  pulse = -1.0
               ENDIF
               CALL HFILL(iGroup*10+7,real(i-it0),pulse,1.0)
            ENDDO
         ENDIF
   END SUBROUTINE calSignal
   SUBROUTINE calRFtime(iGroup,rTime,fTime,t0,ped)
      INTEGER,INTENT(IN) :: iGroup
      REAL,INTENT(IN) :: rTime,fTime,t0,ped
   
      IF( nTbin<=0 ) RETURN
      
      IF( Lcalhist )CALL HF1(iGroup*10+3,ped,1.0)
      CALL HFILL(3,REAL(iGroup),ped,1.0)
       
      IF( Lcalhist )CALL HF1(iGroup*10+5,rTime,1.0)
      CALL HFILL(5,REAL(iGroup),rTime,1.0)
      CALL HFILL(7,t0,rTime,1.0)
        
      IF( Lcalhist )CALL HF1(iGroup*10+6,fTime,1.0)
      CALL HFILL(6,REAL(iGroup),fTime,1.0)
      CALL HFILL(8,t0,fTime,1.0)
         
   END SUBROUTINE calRFtime
! *** OPEN / CLOSE **************************************************
   SUBROUTINE PAWini(CHPAW)
      USE IOunits
    
      CHARACTER(LEN=*),INTENT(IN) :: CHPAW
      INTEGER :: LREC,ISTAT

! this is the commonblock for PAW
      CALL PAWCOM()
      
      LREC = 1024
      CALL HROPEN(IOPAW,CHTOP,CHPAW,"N",LREC,ISTAT)
      IF( ISTAT /= 0 )THEN
         WRITE(UNIT=IOErr,FMT=*) "ERROR, PAWINI> Cant open file"
         STOP
      ENDIF
      
   END SUBROUTINE PAWini
      
   SUBROUTINE PAWend()
      INTEGER :: ID,ICYCLE,IOS
      LOGICAL :: HEXIST
      
      ID = 0
      ICYCLE = 0
      CALL HMDIR("CALIBDATA"," ")
      CALL HCDIR("CALIBDATA"," ")
      DO ID=11,649
         IF( HEXIST(ID) )THEN
            CALL HROUT(ID,ICYCLE," ")
            CALL HDELET(ID)
         ENDIF
      ENDDO
      
      CALL HCDIR("\"," ")
      CALL HMDIR("PULSE"," ")
      CALL HCDIR("PULSE"," ")
      DO ID=9000,9999
         IF( HEXIST(ID) )THEN
            CALL HROUT(ID,ICYCLE," ")
            CALL HDELET(ID)
         ENDIF
      ENDDO

      CALL HCDIR("\"," ")

      CALL HROUT(0,ICYCLE," ")
      
      CALL HREND(CHTOP)
      CALL CLOSEFILE(IOPaw,IOS)
      
   END SUBROUTINE PAWend
END MODULE TPCpaw
