      SUBROUTINE GUOUT
C
C User routine called at the end of each event
C
      implicit none

C Include files

       include 'gconsp.inc'
       include 'gcflag.inc'
       include 'mcflags.inc'
       include 'ntuple.inc'
       include 'part.inc'
       include 'gcvolu.inc'
       include 'gctrak.inc'

C local declarations

      INTEGER NH,NF,IER,MAXRAWHIT,NUMHITS,I,J
      REAL X,Y,Z
      PARAMETER (NH=10,NF=1,MAXRAWHIT=2000)
      INTEGER NUMVS(NF),MYNUMV(NF,MAXRAWHIT), ICYCLE
      REAL HITS(NH,MAXRAWHIT),ITRA(MAXRAWHIT)
      

*******************************************************************************

      CALL GPHITS('*','*')

C Fill Summary ntuple block

      EVENT = IEVENT
      VTX(1) = VERTEX(1)
      VTX(2) = VERTEX(2)
      VTX(3) = VERTEX(3)
      CALL HFNTB(1,'Summary')

C Fill Initial particles block

      DO I = 1,MAXPART
       PARTTYPE(I) = PTYPE(I)
       PARTE(I) = (PX(I)**2.+ PY(I)**2.+ PZ(I)**2.)**0.5
       PARTPX(I) = PX(I)
       PARTPY(I) = PY(I)
       PARTPZ(I) = PZ(I)
      END DO

      CALL HFNTB(1,'Initial')

C Fill holder-escaping particles block

      CALL HFNTB(1,'Escapees')

C Fill particles which enter scintillator block

      CALL HFNTB(1, 'EntScint')

C Fill the body hits block

      CALL GFHITS('FACE','BODY',NF,NH,MAXRAWHIT,0,0,ITRA,
     + MYNUMV,HITS,NUMHITS)

      N_B_HITS = 0
      J = 0
      IF (NUMHITS.GT.0) THEN
       DO I = 1,NUMHITS
        IF (I.LT.MAX_B_HITS) THEN
         N_B_HITS = N_B_HITS + 1
         J = J + 1
         X_B_HIT(J) = HITS(1,I)
         Y_B_HIT(J) = HITS(2,I)
         Z_B_HIT(J) = HITS(3,I)
         E_B_HIT(J) = HITS(9,I)
        ELSE
         E_B_HIT(J) = -1.
        END IF
       END DO
      END IF

      CALL HFNTB (1,'BodyHits')

C Fill the scintillator hits block

      CALL GFHITS('BASE','SCIN',NF,NH,MAXRAWHIT,0,0,ITRA,
     +  MYNUMV,HITS,NUMHITS)

      N_S_HITS = 0
      J=0 
      IF (NUMHITS.GT.0) THEN
        DO I=1,NUMHITS
        IF (I.LT.MAX_S_HITS) THEN
         N_S_HITS = N_S_HITS + 1
         J=J+1
         X_S_HIT(J) = HITS(1,I)
         Y_S_HIT(J) = HITS(2,I)
         Z_S_HIT(J) = HITS(3,I)
         E_S_HIT(J) = HITS(9,I)
        ELSE
         E_S_HIT(J) = -1.
        ENDIF
       ENDDO
      ENDIF

      CALL HFNTB(1,'ScinHits')
      
C      CALL HISTDO
C      CALL HROUT(1, ICYCLE, 'N')
   
 
      RETURN
      END
