*$ CREATE SOURCE.FOR
*COPY SOURCE
*
*=== source ===========================================================*
*
      SUBROUTINE SOURCE ( NOMORE )

      INCLUDE '(DBLPRC)'
      INCLUDE '(DIMPAR)'
      INCLUDE '(IOUNIT)'
*
*----------------------------------------------------------------------*
*                                                                      *
*     Copyright (C) 1990-2020      by    Alfredo Ferrari & Paola Sala  *
*     All Rights Reserved.                                             *
*                                                                      *
*                                                                      *
*     New source for FLUKA9x-FLUKA20xy:                                *
*                                                                      *
*     Created on 07 January 1990   by    Alfredo Ferrari & Paola Sala  *
*                                                Infn - Milan          *
*                                                                      *
*     Last change on  03-Jan-20    by             Paola Sala           *
*                                                Infn - Milan          *
*                                                                      *
*  This is just an example of a possible user written source routine.  *
*  note that the beam card still has some meaning - in the scoring the *
*  maximum momentum used in deciding the binning is taken from the     *
*  beam momentum.  Other beam card parameters are obsolete.            *
*                                                                      *
*       Output variables:                                              *
*                                                                      *
*              Nomore = if > 0 the run will be terminated              *
*                                                                      *
*----------------------------------------------------------------------*
*
      INCLUDE '(BEAMCM)'
      INCLUDE '(FHEAVY)'
      INCLUDE '(FLKSTK)'
      INCLUDE '(IOIOCM)'
      INCLUDE '(LTCLCM)'
      INCLUDE '(PAPROP)'
      INCLUDE '(SOURCM)'
      INCLUDE '(SUMCOU)'

      INCLUDE '(CASLIM)'                  ! NCASES ....

*
      LOGICAL LFIRST, LISNUT
*
      SAVE LFIRST
      DATA LFIRST / .TRUE. /
*
* ===========================     my definitions  .....
*

**      PARAMETER (NMAX=70000)           ! - size of my input file...
**      PARAMETER (NMAX=3407000)           ! - for C1  or  C2 file
*      PARAMETER (NMAX=6813000)           ! - for BIG-input, total

*      COMMON /MYCOM/ NNN, IDET(NMAX), MYIJ(NMAX), ERG(NMAX), WGT(NMAX), 
*     &                    TT(NMAX), XXX(NMAX), YYY(NMAX), ZZZ(NMAX),
*     &                    COSX(NMAX), COSY(NMAX), COSZ(NMAX)
**      COMMON /MYCOM/ ERG(NMAX), WGT(NMAX), TT(NMAX), 
**     &               XXX(NMAX), YYY(NMAX), ZZZ(NMAX),
**     &               COSX(NMAX), COSY(NMAX), COSZ(NMAX),
**     &               IDET(NMAX), MYIJ(NMAX), NNN

**
**  NNN - line number ...
**
**  IDET - detector : 5 (C1), 6 (C2)
**  MYIJ   - part. type                 - replace  IJBEAM here
**  ERG - energy, GeV 
**  WGT - ev. weight
**  TT  - ev. time, sec
**  XXX, YYY, ZZZ - coordinates,  cm
*** COSX, COSY, COSZ - normalized angles (cos)
**

*      SAVE XXX, YYY, ZZZ
*      SAVE COSX, COSY, COSZ
*      SAVE MYIJ, ERG, WGT, TT

**      SAVE /MYCOM/

*
* input format of the BIG file (generated) :
*
*     idet, itype, nev, ekin, ltot, lorig, told, time, ww,
*            xx, yy, zz, xcos, ycos, zcos
*
* idet  - C1 or C2 (5,6)
* itype - particle type
* nev   - initial ev number
* ekin  - E kinetic (GeV)
* ltot, lorig - track length with initial track (cm)
* told  - time from C1, C2 counters
* time  - time with bunch correction (sec)
* ww    - weight
* xx, yy, zz - start coordinates
* xcos, ycos, zcos - angles
* ---------------------------------------

      INTEGER NENTRY                   ! counter
      SAVE    NENTRY

      INTEGER ICYCLE, ICYCLEnew, NNN, ISTART, IEND
      SAVE    ICYCLE, ICYCLEnew, NNN, ISTART, IEND

      CHARACTER*250 LINE
      CHARACTER*80  FNAME


***      INTEGER DUM, I

**      double precision SFLOODR  ! radius of the sphere (sflood)
**      double precision ZMIN  ! m
**      integer N0       ! number of trials to call sflood for a given event
**      integer IETYPE, FLXGEN


* ============================     my  definitions - end .....

*
*  Statement function:
      LISNUT (IJ) = INDEX ( PRNAME (IJ), 'NEUTRI' ) .GT. 0
*======================================================================*
*                                                                      *
*                 BASIC VERSION            ...and my  inouts           *
*                                                                      *
*======================================================================*
*
* it is the code  to read in my input data for neutrons and photons
* my lines are commented with -     ! my...
*
* NMAX - it corresponds to 2e+06 beam partciles (P)
*         OR               4e+06
*
*       see ==>       SUBROUTINE READ_FILE 
*
*======================================================================


      NOMORE = 0

      ICYCLE = 0 
*  +-------------------------------------------------------------------*
*  |  First call initializations:

      IF ( LFIRST ) THEN
*  |  *** The following 3 cards are mandatory ***
         TKESUM = ZERZER
         LFIRST = .FALSE.
         LUSSRC = .TRUE.
*  |  *** User initialization ***
*
*                    .... my start - read file ...
* --------------------------------------------------------------
**
**         CALL READ_FILE          ! --- read file and fill common block
** ------------------------
*
* input file is very big : K = 100 !
*  ... try to simply read lines 
*  BUT  from  definite region of the file :
*            use parameters from SOURCE card !
*
* how to define the current cycle number !?
*
* - let us use created file : cycle.txt
*      where we write cycle number ... and then read it !
*
*  if we know tne number of lines per cycle, then we can 
*     define region to read from input file usinf
*       cycle number
* -----------------------
*
* check parameters:
*

        IPAR1 = NINT (WHASOU(1))
        IPAR2 = NINT (WHASOU(2))
        IPAR3 = NINT (WHASOU(3))

        WRITE(LUNOUT,*)         
        WRITE(LUNOUT,*) " ------             my  output ------------"         
        WRITE(LUNOUT,*) "----- PARAMETERS : "         
        WRITE(LUNOUT,*) "------------------- "         
        WRITE(LUNOUT,*) "- 1 - : ", IPAR1         
        WRITE(LUNOUT,*) "- 2 - : ", IPAR2         
        WRITE(LUNOUT,*) "- 3 - : ", IPAR3         
        WRITE(LUNOUT,*)         
        WRITE(LUNOUT,*) " - NCASES - : ", NCASES        
        WRITE(LUNOUT,*) " - NCASE  - : ", NCASE        
        WRITE(LUNOUT,*) " - MCASE  - : ", MCASE        
        WRITE(LUNOUT,*) " - NSOUIT - : ", NSOUIT        
        WRITE(LUNOUT,*) " - NCOINC - : ", NCOINC        
        WRITE(LUNOUT,*) " - MCOINC - : ", MCOINC        
        WRITE(LUNOUT,*)         
        WRITE(LUNOUT,*)         


        WRITE(LUNOUT,*)         !  put empty line in *out  file
        CALL OAUXFI('cycle.txt', LUNRD1, 'OLD', IERR)

        IF (IERR .NE. 0) THEN        ! -------------- cycle = 1

**          MYUNIT = 201              !  read here cycle number
**
**          OPEN(UNIT=MYUNIT, FILE="cycle.txt", STATUS="NEW")
***        OPEN(UNIT=MYUNIT, FILE="cycle.txt", STATUS="UNKNOWN")
**          WRITE(LUNOUT,*) " ----- 1-st  cycle : open 201 chanel "
**          WRITE(LUNOUT,*) " -----       file = cycle.txt "
**          WRITE(LUNOUT,*) 
**
**          ICYCLE = 1
**          WRITE(MYUNIT,*) ICYCLE             ! save cycle number
**
**          CLOSE (MYUNIT)                     ! ... and close file

          WRITE(LUNOUT,*) " --my--- ERROR: file = cycle.txt "
          CALL FLABRT('cycle.txt','Error reading file')

          STOP

        ELSE                        ! --------------cycle file exist

          READ( LUNRD1, '(A)', ERR=9999, END=20, IOSTAT= IOS) LINE
          READ (LINE,*, IOSTAT= IOS,ERR=10) ICYCLE

          WRITE(LUNOUT,*) " ---- cycle.txt: ICYCLE = ",ICYCLE

*            go to the next cycle :
*      and save the number 

          REWIND (LUNRD1)                   ! get the 1-st line again

          ICYCLEnew = ICYCLE + 1
          WRITE(LUNRD1,*) ICYCLEnew             ! save cycle number

          CLOSE (LUNRD1)                     ! ... and close file

        END IF                        ! -------------- end of 1-st entry

 10     CONTINUE                   
 20     CONTINUE                   

* -------------------------------
*  ... and define region of the file to read
*      according to the cycle number :
*
*      NCASES - # of events per cycle from *inp file
*
        ISTART = NCASES * (ICYCLE - 1) + 1        !  line # to start reading
        IEND   = NCASES * ICYCLE                  !  end of region to read

        WRITE(LUNOUT,*) 
        WRITE(LUNOUT,*) " ---- cycle.txt: start line = ",ISTART
        WRITE(LUNOUT,*) " ---- cycle.txt: end line   = ",IEND
        WRITE(LUNOUT,*) 

        NNN = 0

        GO TO 30
************************** 
 9999   CONTINUE
        CALL FLABRT('cycle.txt','Error reading file')
*                  ..........................
**************************

 30     CONTINUE   
     

* -----------------------------
* now read input file with events
* --------------------------------

**        WRITE(LUNOUT,*)         !  put empty line in *out  file

**      FNAME = "../../Analiz-C1/BIG-30-gen-K100"
**        FNAME = "../../../Analiz-C1/BIG-30-gen-K100"

        FNAME = "../../../Analiz-C1/BIG-30-gen-K100"   !  central flow
*        FNAME = "../../../Analiz-C1/BIG-30-gen-K100-bg"   ! backg. flow

*        FNAME = "../../../Analiz-C1/BIG-14-gen-K100"   !  central flow
*        FNAME = "../../../Analiz-C1/BIG-30_14-gen-K100-bg"

        CALL OAUXFI(FNAME, LUNRD, 'OLD', IERR)

**      CALL OAUXFI('../../../Analiz-C1/BIG-30-gen-K100', LUNRD, 'OLD', IERR)
**      CALL OAUXFI('../../Analiz-C1/BIG-30-gen-K100', LUNRD, 'OLD', IERR)
**      CALL OAUXFI('../../Analiz-C1/BIG-30-gen-K100-bg', LUNRD, 'OLD', IERR)

*        CALL OAUXFI('../r-sum/BIG-ok-86-C2 ', LUNRD, 'OLD', IERR)
*        CALL OAUXFI('../r-sum/BIG-input ', LUNRD, 'OLD', IERR)

* ---------------------------------------
*  ... now read line and convert my varaibles into
*      FLUKA standart ones ...
*
        IF ((NNN .EQ. 0) .AND. (ICYCLE .GT. 1)) THEN ! ... skip 1-st events ...
          DO 11 I = 1, ISTART-1
*           READ( LUNRD, '(A)', ERR=9999, END=20, IOSTAT= IOS) LINE
            READ( LUNRD, '(A)', IOSTAT= IOS) LINE
*           READ (LUNRD,*)                           ! ... skip 1-st events ...
 11       CONTINUE

          WRITE(LUNOUT,*)         !  put empty line in *out  file
          WRITE(LUNOUT,*)" ----- skip ISTART lines ---------- ", ISTART
          WRITE(LUNOUT,*)         !  put empty line in *out  file

        END IF

* ----------------------------------
* -----------------------------
* -------------------
        NENTRY = 0
*                        ---------------------------
*                    .... my start - end of read file ...
      END IF

*  |
*  +-------------------------------------------------------------------*
*  Push one source particle to the stack. Note that you could as well
*  push many but this way we reserve a maximum amount of space in the
*  stack for the secondaries to be generated
*  Npflka is the stack counter: of course any time source is called it
*  must be =0
****      NPFLKA = NPFLKA + 1

*  +-------------------------------------------------------------------*
*
*  -->  and now  read input file ...


      READ( LUNRD, '(A)', ERR=12, END=21, IOSTAT= IOS) LINE
      READ (LINE,*, IOSTAT= IOS,ERR=12) 
     &   IDD, IP, NN, EK, DUM, DUM, T, T2, W, X, Y, Z, XC, YC, ZC

      NNN = NNN + 1

      IF (NNN .LT. 3) THEN
         WRITE(LUNOUT,*) "-my- read : ios =",IOS, " N = ",NNN
         WRITE(LUNOUT,'(A)') LINE
      ENDIF
*         WRITE(LUNOUT,*) 
*      IF (NNN .GE. (IEND-1)) THEN
      IF (NNN .GE. (NCASES-1)) THEN
         WRITE(LUNOUT,*) "-my- read : END "
         WRITE(LUNOUT,'(A)') LINE
      ENDIF

*      IF ( MOD (NCASE, 100000) .EQ. 0)  THEN
      IF ( MOD (NNN, 100000) .EQ. 0)  THEN
*      IF ( MOD (NNN, 200000) .EQ. 0)  THEN
         WRITE(LUNOUT,*) " my total NNN  = ", NNN
         WRITE(LUNOUT,*) 
*         WRITE(LUNOUT,*) 
      END IF

      GO TO 22

* ------------------
     
 12   CONTINUE               ! read error
      WRITE(LUNOUT,*) " **** read error ! - kak tak ? ...."

      GO TO 22
* ------------------

 21   CONTINUE
      WRITE(LUNOUT,*) " ... end of file ...."

      GO TO 22
* ------------------

 22   CONTINUE
*
* .... convert my variables into FLUKA ones
*
      IJBEAM = IP                      ! particle index

***   about time : T  or T2 -> see below 
  
      XBEAM = X
      YBEAM = Y
      ZBEAM = Z

*       UBEAM = XC
      VBEAM = YC
      WBEAM = ZC
      UBEAM = SQRT ( ONEONE - YC**2 - ZC**2 )  ! normalise vector: XC

* -----------------------

      NENTRY = NENTRY + 1
*
*            .... my part - end of the part ...
*
*  +-------------------------------------------------------------------*


       NPFLKA = NPFLKA + 1
*  Wt is the weight of the particle
***      WTFLK  (NPFLKA) = ONEONE
       WTFLK  (NPFLKA) = W                ! my - put my weight,, not 1

       WEIPRI = WEIPRI + WTFLK (NPFLKA)

*  Particle type (1=proton.....). Ijbeam is the type set by the BEAM
*  card
*  +-------------------------------------------------------------------*
*  |  (Radioactive) isotope:
***      IF ( IJBEAM .EQ. -2 .AND. LRDBEA ) THEN
      IF ( IJBEAM .EQ. -2 .AND. LRDBEA ) THEN      

         IARES  = IPROA
         IZRES  = IPROZ
         IISRES = IPROM
         CALL STISBM ( IARES, IZRES, IISRES )
         IJHION = IPROM  * 100000 + MOD ( IPROZ, 100 ) * 1000 + IPROA
         IJHION = IJHION * 100    + KXHEAV
         IONID  = IJHION
         CALL DCDION ( IONID )
         CALL SETION ( IONID )
         EEXSTK (NPFLKA) = EXENRG (IONID)
         TMNSTK (NPFLKA) = TMNLF  (IONID)
         ILVSTK (NPFLKA) = IEXLVL (IONID)
         LFRPHN (NPFLKA) = .FALSE.
*  |
*  +-------------------------------------------------------------------*
*  |  Heavy ion:

      ELSE IF ( IJBEAM .EQ. -2 ) THEN

         IJHION = IPROM  * 100000 + MOD ( IPROZ, 100 ) * 1000 + IPROA
         IJHION = IJHION * 100    + KXHEAV
         IONID  = IJHION
         CALL DCDION ( IONID )
         CALL SETION ( IONID )
         EEXSTK (NPFLKA) = EXENRG (IONID)
         TMNSTK (NPFLKA) = TMNLF  (IONID)
         ILVSTK (NPFLKA) = IEXLVL (IONID)
         ILOFLK (NPFLKA) = IJHION
*  |  Flag this is prompt radiation
         LRADDC (NPFLKA) = .FALSE.
*  |  Group number for "low" energy neutrons, set to 0 anyway
         IGROUP (NPFLKA) = 0
*  |  Parent radioactive isotope:
         IRDAZM (NPFLKA) = 0
*  |  Particle age (s)
         AGESTK (NPFLKA) = +ZERZER
*  |  Kinetic energy of the particle (GeV)
         TKEFLK (NPFLKA) = SQRT ( PBEAM**2 + AM (IONID)**2 )
     &                   - AM (IONID)
*  |  Particle momentum
         PMOFLK (NPFLKA) = PBEAM
*        PMOFLK (NPFLKA) = SQRT ( TKEFLK (NPFLKA) * ( TKEFLK (NPFLKA)
*    &                          + TWOTWO * AM (IONID) ) )
         LFRPHN (NPFLKA) = .FALSE.
*  |
*  +-------------------------------------------------------------------*
*  |  Normal hadron:        -  ! it is my case : N  and G ....

      ELSE
         IONID = IJBEAM

         EEXSTK (NPFLKA) = EXENRG (IJBEAM)
         TMNSTK (NPFLKA) = TMNLF  (IJBEAM)
         ILVSTK (NPFLKA) = IEXLVL (IJBEAM)

         ILOFLK (NPFLKA) = IJBEAM

*  |  Flag this is prompt radiation
         LRADDC (NPFLKA) = .FALSE.
*  |  Group number for "low" energy neutrons, set to 0 anyway
         IGROUP (NPFLKA) = 0
*  |  Parent radioactive isotope:
         IRDAZM (NPFLKA) = 0

*  |  Particle age (s)
***         AGESTK (NPFLKA) = +ZERZER

***         AGESTK (NPFLKA) = T             ! my : time-history > 0  ! <T>=0
         AGESTK (NPFLKA) = T2           ! my : time-history > 0  ! <T>= 30

*  |  Kinetic energy of the particle (GeV)
***         TKEFLK (NPFLKA) = SQRT ( PBEAM**2 + AM (IONID)**2 )
***     &                   - AM (IONID)
         TKEFLK (NPFLKA) = EK                ! my :  particle energy...

*  |  Particle momentum
***         PMOFLK (NPFLKA) = PBEAM
         PMOFLK (NPFLKA) = SQRT ( TKEFLK (NPFLKA) * ( TKEFLK (NPFLKA)
     &                       + TWOTWO * AM (IONID) ) )

*        PMOFLK (NPFLKA) = SQRT ( TKEFLK (NPFLKA) * ( TKEFLK (NPFLKA)
*    &                          + TWOTWO * AM (IONID) ) )

*  |  +----------------------------------------------------------------*
*  |  |  Check if it is a neutrino, if so force the interaction
*  |  |  (unless the relevant flag has been disabled)
         IF ( LISNUT (IJBEAM) .AND. LNUFIN ) THEN
            LFRPHN (NPFLKA) = .TRUE.
*  |  |
*  |  +----------------------------------------------------------------*
*  |  |  Not a neutrino
         ELSE
            LFRPHN (NPFLKA) = .FALSE.
         END IF
*  |  |
*  |  +----------------------------------------------------------------*
      END IF

*  |
*  +-------------------------------------------------------------------*
*  From this point .....
*  Particle generation (1 for primaries)
      LOFLK  (NPFLKA) = 1
*  User dependent flag:
      LOUSE  (NPFLKA) = 0
*  No channeling:
      KCHFLK (NPFLKA) = 0
      ECRFLK (NPFLKA) = ZERZER
*  Extra infos:
      INFSTK (NPFLKA) = 0
      LNFSTK (NPFLKA) = 0
      ANFSTK (NPFLKA) = ZERZER
*  Parent variables:
      IPRSTK (NPFLKA) = 0
      EKPSTK (NPFLKA) = ZERZER
*  User dependent spare variables:
      DO 100 ISPR = 1, MKBMX1
         SPAREK (ISPR,NPFLKA) = ZERZER
 100  CONTINUE
*  User dependent spare flags:
      DO 200 ISPR = 1, MKBMX2
         ISPARK (ISPR,NPFLKA) = 0
 200  CONTINUE
*  Save the track number of the stack particle:
      ISPARK (MKBMX2,NPFLKA) = NPFLKA
      NPARMA = NPARMA + 1
      NUMPAR (NPFLKA) = NPARMA
      NEVENT (NPFLKA) = 0
      DFNEAR (NPFLKA) = +ZERZER
*  ... to this point: don't change anything
*  +-------------------------------------------------------------------*

      AKNSHR (NPFLKA) = -TWOTWO

*  Cosines (tx,ty,tz)
      TXFLK  (NPFLKA) = UBEAM
      TYFLK  (NPFLKA) = VBEAM
      TZFLK  (NPFLKA) = WBEAM
*     TZFLK  (NPFLKA) = SQRT ( ONEONE - TXFLK (NPFLKA)**2
*    &                       - TYFLK (NPFLKA)**2 )

*  Polarization cosines:
      TXPOL  (NPFLKA) = -TWOTWO
      TYPOL  (NPFLKA) = +ZERZER
      TZPOL  (NPFLKA) = +ZERZER

*  Particle coordinates
      XFLK   (NPFLKA) = XBEAM
      YFLK   (NPFLKA) = YBEAM
      ZFLK   (NPFLKA) = ZBEAM

*  Calculate the total kinetic energy of the primaries: don't change
*  +-------------------------------------------------------------------*
*  |  (Radioactive) isotope:
      IF ( IJBEAM .EQ. -2 .AND. LRDBEA ) THEN

*  |
*  +-------------------------------------------------------------------*
*  |  Heavy ion:
      ELSE IF ( ILOFLK (NPFLKA) .EQ. -2 .OR.
     &          ILOFLK (NPFLKA) .GT. 100000 ) THEN
         TKESUM = TKESUM + TKEFLK (NPFLKA) * WTFLK (NPFLKA)
*  |
*  +-------------------------------------------------------------------*
*  |  Standard particle:
      ELSE IF ( ILOFLK (NPFLKA) .NE. 0 ) THEN
         TKESUM = TKESUM + ( TKEFLK (NPFLKA) + AMDISC (ILOFLK(NPFLKA)) )
     &          * WTFLK (NPFLKA)
*  |
*  +-------------------------------------------------------------------*
*  |
      ELSE
         TKESUM = TKESUM + TKEFLK (NPFLKA) * WTFLK (NPFLKA)
      END IF
*  |
*  +-------------------------------------------------------------------*
      RADDLY (NPFLKA) = ZERZER

*  Here we ask for the region number of the hitting point.
*     NREG (NPFLKA) = ...
*  The following line makes the starting region search much more
*  robust if particles are starting very close to a boundary:
      CALL GEOCRS ( TXFLK (NPFLKA), TYFLK (NPFLKA), TZFLK (NPFLKA) )
      CALL GEOREG ( XFLK  (NPFLKA), YFLK  (NPFLKA), ZFLK  (NPFLKA),
     &              NRGFLK(NPFLKA), IDISC )

*  Do not change these cards:
      CALL GEOHSM ( NHSPNT (NPFLKA), 1, -11, MLATTC )
      NLATTC (NPFLKA) = MLATTC
      CMPATH (NPFLKA) = ZERZER
      CALL SOEVSV
      RETURN

*=== End of subroutine Source =========================================*
*                  ... my : end of job .....
*** 9999 CONTINUE
***      CALL FLABRT('SOURCE','Error reading source file')
*                  ..........................
      END




**************************************************
*=======================================================


*===================================================


